repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/augmentation_class.py | import torch
import torchvision.transforms as tt
from . import augmentation_pool as aug_pool
from .rand_augment import RandAugment
class ReduceChannelwithNormalize:
""" Reduce alpha channel of RGBA """
def __init__(self, mean, scale, zca):
self.mean = mean
self.scale = scale
self.zca ... | 2,986 | 25.433628 | 102 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/__init__.py | from . import augmentation_pool | 31 | 31 | 31 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/builder.py | from .augmentation_class import WeakAugmentation, StrongAugmentation
def gen_strong_augmentation(img_size, mean, std, flip=True, crop=True, alg="fixmatch", zca=False):
return StrongAugmentation(img_size, mean, std, flip, crop, alg, zca)
def gen_weak_augmentation(img_size, mean, std, flip=True, crop=True, noise=... | 411 | 40.2 | 98 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/augmentation/rand_augment.py | import numpy as np
from . import augmentation_pool
from . import utils
class RandAugment:
"""
RandAugment class
Parameters
--------
nops: int
number of operations per image
magnitude: int
maximmum magnitude
alg: str
algorithm name
"""
def __init__(self, nop... | 1,351 | 27.765957 | 90 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/consistency.py | import torch
from .utils import sharpening, tempereture_softmax
class ConsistencyRegularization:
"""
Basis Consistency Regularization
Parameters
--------
consistency: str
consistency objective name
threshold: float
threshold to make mask
sharpen: float
sharpening te... | 1,674 | 26.916667 | 97 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/utils.py | import torch
import torch.nn as nn
def make_pseudo_label(logits, threshold):
max_value, hard_label = logits.softmax(1).max(1)
mask = (max_value >= threshold)
return hard_label, mask
def sharpening(soft_labels, temp):
soft_labels = soft_labels.pow(temp)
return soft_labels / soft_labels.abs().sum(... | 1,736 | 27.47541 | 84 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/vat.py | import torch
from .consistency import ConsistencyRegularization
class VAT(ConsistencyRegularization):
"""
Virtual Adversarial Training https://arxiv.org/abs/1704.03976
Parameters
--------
consistency: str
consistency objective name
threshold: float
threshold to make mask
sh... | 2,419 | 26.5 | 108 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/pseudo_label.py | import torch
import torch.nn.functional as F
from .consistency import ConsistencyRegularization
from ..consistency.cross_entropy import CrossEntropy
from .utils import make_pseudo_label, sharpening
class PseudoLabel(ConsistencyRegularization):
"""
PseudoLabel
Parameters
--------
consistency: str
... | 1,136 | 25.44186 | 97 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/__init__.py | 0 | 0 | 0 | py | |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/builder.py | from .ict import ICT
from .consistency import ConsistencyRegularization
from .pseudo_label import PseudoLabel
from .vat import VAT
def gen_ssl_alg(name, cfg):
if name == "ict": # mixed target <-> mixed input
return ICT(
cfg.consistency,
cfg.threshold,
cfg.sharpen,
... | 1,207 | 26.454545 | 58 | py |
pytorch-consistency-regularization | pytorch-consistency-regularization-master/ssl_lib/algs/ict.py | import torch
from .consistency import ConsistencyRegularization
from .utils import mixup
class ICT(ConsistencyRegularization):
"""
Interpolation Consistency Training https://arxiv.org/abs/1903.03825
Parameters
--------
consistency: str
consistency objective name
threshold: float
... | 1,377 | 24.054545 | 109 | py |
TAME-GP | TAME-GP-main/tools/dim_red_and_alignment.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 14:41:58 2022
@author: Edoardo Balzani & Pedro Herrera Vidal
"""
import sys
sys.path.append('../core/')
from data_structure import *
import numpy as np
from sklearn.decomposition import PCA, FactorAnalysis
from scipy.linalg import orthogonal_pr... | 16,965 | 36.452539 | 170 | py |
TAME-GP | TAME-GP-main/core/inference.py | """
Core inference functions.
Likelihoods gradients and hessians of all model components are implemented as individual functions and combined in
a single method.
"""
import numpy as np
from time import perf_counter
import scipy.sparse
from scipy.optimize import minimize
from scipy.linalg import block_diag, lapack
impo... | 21,109 | 35.271478 | 163 | py |
TAME-GP | TAME-GP-main/core/marginal_likelihood.py | import numpy as np
from expectation_maximization import computeLL
from scipy.stats import multivariate_normal, poisson
from scipy.linalg import block_diag
from data_processing_tools import makeK_big, logpdf_multnorm, logDetCompute
from time import perf_counter
from copy import deepcopy
from inference import multiTrialI... | 6,447 | 36.929412 | 172 | py |
TAME-GP | TAME-GP-main/core/learnGaussianParam.py | import numpy as np
from scipy.optimize import minimize
from data_processing_tools import approx_grad
from copy import deepcopy
def MStepGauss(x1, mean_post, cov_post):
"""
M-step updates for trial stacked data\n
Parameters
==========
:param x1:
- Gaussian observations for all trials
... | 11,820 | 35.039634 | 144 | py |
TAME-GP | TAME-GP-main/core/gen_synthetic_data.py | import numpy as np
from inference import *
from learnPoissonParam import *
from data_structure import *
from data_processing_tools import emptyStruct
class dataGen(object):
def __init__(self, trNum, T=50, D=4, K0=2, K2=5, K3=3, N=7, N1=6, meanZ0Levels=[0], infer=True, setTruePar=True,add_trend=False):
sup... | 10,673 | 39.279245 | 133 | py |
TAME-GP | TAME-GP-main/core/expectation_maximization.py | import numpy as np
from inference import multiTrialInference
from learnGaussianParam import learn_GaussianParams,full_GaussLL
from learnPoissonParam import all_trial_PoissonLL,poissonELL_Sparse,grad_poissonELL_Sparse,hess_poissonELL_Sparse,newton_opt_CSR
from learnGPParams import all_trial_GPLL
from data_processing_too... | 12,216 | 41.127586 | 128 | py |
TAME-GP | TAME-GP-main/core/learnPoissonParam.py | """
Some of the code here is adapted from Machens et al. implementation of P-GPFA.
"""
import numpy as np
from scipy.optimize import minimize
from data_processing_tools import approx_grad,block_inv, fast_stackCSRHes_memoryPreAllocation, compileTrialStackedObsAndLatent
import scipy.sparse as sparse
import csr
def expe... | 14,703 | 36.896907 | 146 | py |
TAME-GP | TAME-GP-main/core/learnGPParams.py | import os
import numpy as np
from data_processing_tools import makeK_big
def allTrial_grad_expectedLLGPPrior(lam , meanPost, covPost, binSize,eps=0.001,Tmax=600,isGrad=False, trial_num=None):
"""
Average over trial of the expected log-likelihood of the GP prior as a funciton of the time constant
:param la... | 8,500 | 40.876847 | 147 | py |
TAME-GP | TAME-GP-main/core/data_structure.py | """
Implement a class that handles the input dataset conveniently.
The class needs to store spikes and task variables, initialize parameters and select appropriately the data for the fits.
"""
import numpy as np
from data_processing_tools import emptyStruct,gs
from copy import deepcopy
from sklearn.cross_decomposition ... | 23,968 | 40.254733 | 150 | py |
TAME-GP | TAME-GP-main/core/mpi_expectation_maximization.py | from mpi4py import MPI
import numpy as np
from inference import multiTrialInference
from learnGaussianParam import learn_GaussianParams,full_GaussLL
from learnPoissonParam import all_trial_PoissonLL,poissonELL_Sparse,grad_poissonELL_Sparse,hess_poissonELL_Sparse,newton_opt_CSR
from learnGPParams import all_trial_GPLL
f... | 18,125 | 38.66302 | 128 | py |
TAME-GP | TAME-GP-main/core/mpi_expectation_maximizaiton_noinit.py | from mpi4py import MPI
import numpy as np
from inference import multiTrialInference
from learnGaussianParam import learn_GaussianParams,full_GaussLL
from learnPoissonParam import all_trial_PoissonLL,poissonELL_Sparse,grad_poissonELL_Sparse,hess_poissonELL_Sparse,newton_opt_CSR
from learnGPParams import all_trial_GPLL
f... | 13,098 | 37.754438 | 128 | py |
TAME-GP | TAME-GP-main/core/data_processing_tools.py | import numpy as np
from scipy.linalg import block_diag
from copy import deepcopy
from numba import jit
import csr
from scipy.stats import multivariate_normal
def compileTrialStackedObsAndLatent(data, idx_latent, trial_list, T, xDim, K0, K1):
x = np.zeros((T, xDim))
mean_post = np.zeros((T, K0 + K1))
cov_p... | 12,055 | 30.643045 | 133 | py |
TAME-GP | TAME-GP-main/initialization/expectation_maximization_factorized.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basedir,'core'))
from learnGaussianParam import learn_GaussianParams,full_GaussLL
from learnPoissonParam import all_trial_PoissonLL,poissonELL_Sparse,grad_poissonELL_Sparse,hess_poissonELL... | 17,238 | 41.990025 | 128 | py |
TAME-GP | TAME-GP-main/initialization/data_processing_tools_factorized.py | import numpy as np
import csr
import os,inspect,sys
basedir = os.path.dirname(os.path.dirname(inspect.getfile(inspect.currentframe())))
sys.path.append(os.path.join(basedir,'core'))
from data_processing_tools import emptyStruct,sortGradient_idx
from numba import jit
def preproc_post_mean_factorizedModel(dat, returnD... | 3,916 | 35.607477 | 151 | py |
TAME-GP | TAME-GP-main/initialization/inference_factorized.py | """
Core inference functions.
Likelihoods gradients and hessians of all model components are implemented as individual functions and combined in
a single method.
"""
import numpy as np
import os,sys,inspect
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basedir,'core'... | 26,402 | 37.942478 | 155 | py |
TAME-GP | TAME-GP-main/tests/test_GPLearning.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basedir,'core'))
from data_structure import *
import unittest
from scipy.linalg import block_diag
from scipy.optimize import minimize
from scipy.stats import pearsonr
from gen_synthetic_d... | 3,416 | 43.960526 | 121 | py |
TAME-GP | TAME-GP-main/tests/test_complete_likelihood.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('base folder:', basedir)
sys.path.append(os.path.join(basedir,'core'))
from inference import (PpCCA_logLike,grad_PpCCA_logLike,hess_PpCCA_logLike,makeK_big,approx_grad,retrive_t_blocks_fom_cov)
from data_structu... | 4,946 | 46.114286 | 139 | py |
TAME-GP | TAME-GP-main/tests/test_logLike.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basedir,'core'))
from inference import (makeK_big,GPLogLike,grad_GPLogLike,hess_GPLogLike,
gaussObsLogLike,grad_gaussObsLogLike,hess_gaussObsLogLike,
... | 7,696 | 54.374101 | 167 | py |
TAME-GP | TAME-GP-main/tests/test_Mstep.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basedir,'core'))
from inference import (inferTrial,makeK_big,retrive_t_blocks_fom_cov,multiTrialInference)
from data_structure import P_GPCCA
import unittest
from learnGaussianParam import... | 18,939 | 47.316327 | 141 | py |
TAME-GP | TAME-GP-main/tests/test_initialization_inference_noStim.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('base folder:', basedir)
sys.path.append(os.path.join(basedir,'core'))
sys.path.append(os.path.join(basedir,'initialization'))
from inference_factorized import reconstruct_post_mean_and_cov, factorized_logLike,\... | 9,918 | 47.622549 | 147 | py |
TAME-GP | TAME-GP-main/tests/test_initialization_inference.py | import numpy as np
import os,sys
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('base folder:', basedir)
sys.path.append(os.path.join(basedir,'core'))
sys.path.append(os.path.join(basedir,'initialization'))
from inference_factorized import reconstruct_post_mean_and_cov, factorized_logLike,\... | 9,871 | 47.392157 | 147 | py |
TAME-GP | TAME-GP-main/bads_optim/badsOptim.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 10 21:03:41 2022
@author: edoardo
"""
import matlab
import matlab.engine as eng
import numpy as np
import os
from time import perf_counter
class badsOptim(object):
def __init__(self,dat):
print('preparing for bads optim')
self.... | 3,189 | 38.382716 | 113 | py |
TAME-GP | TAME-GP-main/bads_optim/test_bads.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 10 17:02:16 2022
@author: edoardo
"""
import matlab
import matlab.engine as eng
import numpy as np
import sys
import seaborn as sbs
import matplotlib.pylab as plt
plt.close('all')
sys.path.append('/Users/edoardo/Work/Code/P-GPCCA/core/')
from data_p... | 2,388 | 25.252747 | 118 | py |
rulstm | rulstm-master/FEATEXT/extract_example_obj.py | import torch
import numpy as np
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
env = lmdb.open('features/obj', map_size=1099511627776)
video_name = 'P01_01_frame_... | 681 | 26.28 | 80 | py |
rulstm | rulstm-master/FEATEXT/extract_example_rgb.py | import torch
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
from argparse import ArgumentParser
env = lmdb.open('features/rgb', map_size=1099511627776)
device = ... | 1,291 | 26.489362 | 83 | py |
rulstm | rulstm-master/FEATEXT/extract_example_flow.py | import torch
from torch import nn
from pretrainedmodels import bninception
from torchvision import transforms
from glob import glob
from PIL import Image
import lmdb
from tqdm import tqdm
from os.path import basename
from argparse import ArgumentParser
env = lmdb.open('features/flow', map_size=1099511627776)
device =... | 1,787 | 29.827586 | 85 | py |
rulstm | rulstm-master/RULSTM/main.py | """Main training/test program for RULSTM"""
from argparse import ArgumentParser
from dataset import SequenceDataset
from os.path import join
from models import RULSTM, RULSTMFusion
import torch
from torch.utils.data import DataLoader
from torch.nn import functional as F
from utils import topk_accuracy, ValueMeter, topk... | 30,172 | 46.219092 | 208 | py |
rulstm | rulstm-master/RULSTM/utils.py | """ Set of utilities """
import numpy as np
class MeanTopKRecallMeter(object):
def __init__(self, num_classes, k=5):
self.num_classes = num_classes
self.k = k
self.reset()
def reset(self):
self.tps = np.zeros(self.num_classes)
self.nums = np.zeros(self.num_classes)
... | 5,648 | 30.735955 | 128 | py |
rulstm | rulstm-master/RULSTM/dataset.py | """ Implements a dataset object which allows to read representations from LMDB datasets in a multi-modal fashion
The dataset can sample frames for both the anticipation and early recognition tasks."""
import numpy as np
import lmdb
from tqdm import tqdm
from torch.utils import data
import pandas as pd
def read_repres... | 9,400 | 43.554502 | 134 | py |
rulstm | rulstm-master/RULSTM/models.py | from torch import nn
import torch
from torch.nn.init import normal, constant
import numpy as np
from torch.nn import functional as F
class OpenLSTM(nn.Module):
""""An LSTM implementation that returns the intermediate hidden and cell states.
The original implementation of PyTorch only returns the last cell vect... | 6,687 | 40.540373 | 131 | py |
rulstm | rulstm-master/FasterRCNN/tools/detect_video.py | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | 4,411 | 29.013605 | 78 | py |
chase | chase-master/python/src/example.py | # MLP for Pima Indians Dataset with grid search via sklearn
#import tensorflow as tf
from sklearn.cross_validation import train_test_split, cross_val_predict, cross_val_score
from sklearn.metrics import accuracy_score
import os
os.environ['THEANO_FLAGS']="device=cpu,openmp=True"
import datetime
from keras.models impor... | 3,449 | 34.204082 | 92 | py |
chase | chase-master/python/src/deprecated/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/deprecated/classifier_tag.py | '''USE THIS FILE TO APPLY PRE-TRAINED MODEL TO TAG DATA'''
from ml import util
import os
def tag(cpus, model, task, test_data,sys_out):
print("start testing stage :: testing data size:", len(test_data))
print("test with CPU cores: [%s]" % cpus)
######################### SGDClassifier ####################... | 1,626 | 38.682927 | 106 | py |
chase | chase-master/python/src/index/sample_query.py | '''
Firstly start the server by:
$ cd solr-6.6.0/bin
$ ./solr start -s [/home/.../chase/data/solr]
Tips for using solr server (https://cwiki.apache.org/confluence/display/solr/Running+Solr)
- always remember TO STOP THE SERVER when you finish, by typing './solr stop -all'
- it is better to make a back up of the index... | 6,616 | 42.248366 | 135 | py |
chase | chase-master/python/src/index/indexupdate_wrapper.py |
'''order of update:
for every [time_interval]
1. tag_indexupdate - update all tag scores, this requires a list of tags for a list of tweets. Where those tweets come from
depends on individual choices
2. tweet_indexupdate - classify all tweets; compute tweet risk score using tag_index
'''
| 291 | 31.444444 | 123 | py |
chase | chase-master/python/src/index/util.py | import urllib.request
import pickle
solr_core_tweets="tweets"
solr_core_tags="tags"
solr_url="http://localhost:8983/solr"
tag_index_field_text="tag_text"
tag_index_field_type="type"
tag_index_field_frequency="frequency"
tag_index_field_frequencyh="frequencyh"
tag_index_field_pmi="pmi"
tag_index_field_risk_score="r... | 600 | 20.464286 | 50 | py |
chase | chase-master/python/src/index/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/index/tag_indexupdate.py | import logging
import numpy
import pandas as pd
import sys
from SolrClient import SolrClient
from ml import feature_extractor as fe
# get data about tags in existing tag index
from index import util
logger = logging.getLogger(__name__)
def get_existing(solr: SolrClient, core_name, pagesize):
stop = False
s... | 6,772 | 33.207071 | 107 | py |
chase | chase-master/python/src/index/tweet_indexupdate.py | import logging
import numpy
from ml import feature_extractor
from ml import util, text_preprocess
from ml import classifier_traintest as ct
import datetime
import sys
from SolrClient import SolrClient
from index import util as iu
from ml import util as mu
from ml.vectorizer import fv_chase_basic
logger = logging.g... | 5,972 | 34.135294 | 124 | py |
chase | chase-master/python/src/dc/datacollector_twitter_proxy.py | import logging
import random
import re
import sys
import json
import os
import traceback
import urllib.request
import pandas as pd
import csv
import time
from time import sleep
import datetime
import tweepy
from SolrClient import SolrClient
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener, ... | 17,651 | 38.756757 | 110 | py |
chase | chase-master/python/src/dc/data_sampler.py | import csv
import logging
import os
import random
from SolrClient import SolrClient
SOLR_SERVER="http://localhost:8983/solr"
SOLR_CORE="chase_searchapi"
#KEYWORDS='ban+kill+die+evil+hate+attack+terrorist+terrorism+threat+#DeportallMuslims+#refugeesnotwelcome'
KEYWORDS='*'
logger = logging.getLogger(__name__)
LOG_D... | 2,864 | 29.157895 | 106 | py |
chase | chase-master/python/src/dc/util.py | import csv
import os
import pandas as pd
def merge_annotations(in_folder, out_file):
tag_lookup={}
id_lookup={}
for file in sorted(os.listdir(in_folder)):
print(file)
with open(in_folder+"/"+file, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=... | 3,793 | 32.875 | 104 | py |
chase | chase-master/python/src/dc/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/dc/datacollector_waseem_vote.py | import csv
import pandas as pd
# racism=0, sexism=1,neither=2,both=3
def create_expert_corpus(out_file, in_file):
with open(out_file, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
wr... | 4,894 | 29.981013 | 111 | py |
chase | chase-master/python/src/util/identity_group_words_analysier.py | '''
This file is created to analyse the correlation between
- presence of identity group words (see https://www.aclweb.org/anthology/2020.acl-main.483.pdf)
this list of 25 words are here: /home/zz/Work/data/identity_group_words.txt
- sentiment of the text containing that igw
- whether it is hate or not
'''
import panda... | 6,221 | 33.955056 | 98 | py |
chase | chase-master/python/src/util/xmlprocessor.py | import csv
import os
from xml.dom import minidom
import re
pattern_num=re.compile(r"^[0-9]+$")
def parse_folder(in_folder, out_file):
writer=csv.writer(open(out_file,'w'))
header=["ds","id","count","hate_speech","offensive_language","neither","class","tweet"]
writer.writerow(header)
count=0
for ... | 2,157 | 25.975 | 91 | py |
chase | chase-master/python/src/util/logger.py |
import logging
import os
logger = logging.getLogger(__name__)
LOG_DIR=os.getcwd()+"/logs"
logging.basicConfig(filename=LOG_DIR+'/log.txt', level=logging.INFO, filemode='w')
| 176 | 18.666667 | 82 | py |
chase | chase-master/python/src/util/csv_data_splitter.py | import csv
in_file="/home/zz/Work/chase/data/ml/ml/rm/labeled_data_all.csv"
out_file="/home/zz/Work/chase/data/ml/ml/rm/labeled_data_tweets_only.csv"
with open(in_file, newline='') as csvfile:
csvr = csv.reader(csvfile, delimiter=',', quotechar='"')
with open(out_file, 'w', newline='\n') as csvfile:
... | 527 | 30.058824 | 73 | py |
chase | chase-master/python/src/util/csv_result_processor.py | import csv
in_file="/home/zz/SCORES_w.csv"
out_file="/home/zz/SCORES_w_dm1.csv"
with open(in_file, newline='') as csvfile:
csvr = csv.reader(csvfile, delimiter=',', quotechar='"')
with open(out_file, 'w', newline='\n') as csvfile:
csvw = csv.writer(csvfile, delimiter=',',
... | 803 | 26.724138 | 73 | py |
chase | chase-master/python/src/util/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/ml/classifier_gridsearch.py | '''USE THIS FILE TO TRAIN AND EVALUATE A MODEL'''
import datetime
import os
import numpy as np
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import RFECV
from sklearn.feature_selection import SelectFromModel
from sklearn... | 9,743 | 42.5 | 114 | py |
chase | chase-master/python/src/ml/text_preprocess.py | import re
import enchant
import splitter
d = enchant.Dict('en_UK')
dus = enchant.Dict('en_US')
space_pattern = '\s+'
giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'
'[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
mention_regex = '@[\w\-]+'
emoji_regex = '&#[0-9]{4,6};'
#This is the original preprocess... | 2,602 | 35.661972 | 122 | py |
chase | chase-master/python/src/ml/classifier_dnn.py | import os
from numpy.random import seed
seed(1)
os.environ['PYTHONHASHSEED'] = '0'
os.environ['THEANO_FLAGS'] = "floatX=float64,device=cpu,openmp=True"
# os.environ['THEANO_FLAGS']="openmp=True"
os.environ['OMP_NUM_THREADS'] = '16'
import theano
theano.config.openmp = True
# import tensorflow as tf
# tf.set_random... | 23,117 | 39.629174 | 137 | py |
chase | chase-master/python/src/ml/feature_extractor.py | import datetime
import functools
import pickle
import enchant
import logging
import numpy as np
import pandas as pd
from nltk import word_tokenize
from nltk.util import skipgrams
from sklearn.externals import joblib
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import... | 13,926 | 39.485465 | 145 | py |
chase | chase-master/python/src/ml/multiclassifier_dnn.py | import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEnco... | 1,381 | 31.139535 | 89 | py |
chase | chase-master/python/src/ml/tweet_normalizer.py | import csv
import re
import pandas as pd
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
text_processor = TextPreProcessor(
# terms that will be normalized
# normalize=['url', 'email', 'percent', 'm... | 3,515 | 38.954545 | 142 | py |
chase | chase-master/python/src/ml/nlp.py | import re
import nltk
from nltk import PorterStemmer, WordNetLemmatizer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS
sentiment_analyzer = VS()
stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()
stopwords = nltk.corpus.stopwords.words("english")
other_exclusions = ["#ff", "ff", "r... | 1,654 | 35.777778 | 107 | py |
chase | chase-master/python/src/ml/util.py | import csv
import pickle
import datetime
import random
import pandas
from sklearn.cross_validation import train_test_split
import os
import numpy as np
import pandas as pd
from sklearn.metrics import precision_recall_fscore_support
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import Stand... | 20,790 | 35.733216 | 110 | py |
chase | chase-master/python/src/ml/data_mixer.py | import csv
import random
import numpy
import pandas as pd
import re
from nltk import PorterStemmer
import nltk
from ml import text_preprocess as tp
def index_data(file_input, tweet_col, label_col):
stemmer = PorterStemmer()
raw_data = pd.read_csv(file_input, sep=',', encoding="utf-8")
label_instances = {... | 14,178 | 38.277008 | 111 | py |
chase | chase-master/python/src/ml/__init__.py | import os
__version__ = '0.1'
__license__ = 'Apache'
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
| 112 | 15.142857 | 56 | py |
chase | chase-master/python/src/ml/dnn_model_creator.py | from keras.engine import Model
from keras.layers import Dropout, GlobalMaxPooling1D, Dense, Conv1D, MaxPooling1D, Bidirectional, Concatenate, Flatten, \
GRU
from keras.layers import LSTM
from keras import backend as K
from keras.models import Sequential
from keras.regularizers import L1L2
def create_regularizer(... | 28,293 | 42.866667 | 158 | py |
chase | chase-master/python/src/ml/classifier_traintest.py | import csv
import logging
import numpy
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
import os
from ml import util
LOG_DIR = os.getcwd() + "/logs"
logger = logging.getLogger(__name__)
loggin... | 5,938 | 41.421429 | 117 | py |
chase | chase-master/python/src/ml/vectorizer/feature_vectorizer.py |
class FeatureVectorizer:
def __init__(self):
pass
def transform_inputs(self, tweets_original, tweets_cleaned, out_folder, flag):
pass
| 160 | 19.125 | 82 | py |
chase | chase-master/python/src/ml/vectorizer/fv_chase_basic_othering.py | import datetime
from ml import feature_extractor as fe
from ml import text_preprocess as tp
from ml import nlp
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from ml.vectorizer import feature_vectorizer as fv
from util import logger as logger
class FeatureVectorizerC... | 4,300 | 43.802083 | 117 | py |
chase | chase-master/python/src/ml/vectorizer/fv_chase_skipgram.py | '''everything is the same as chase_basic, but skip gram replaces ngram (skipgram is a superset)'''
import datetime
from ml import feature_extractor as fe
from ml import text_preprocess as tp
from ml import nlp
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from ml.ve... | 5,292 | 46.684685 | 119 | py |
chase | chase-master/python/src/ml/vectorizer/fv_davison.py | import datetime
from ml import feature_extractor as fe
from ml import text_preprocess as tp
from ml import nlp
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from ml.vectorizer import feature_vectorizer as fv
from util import logger
class FeatureVectorizerDavidson(fv... | 3,322 | 40.5375 | 100 | py |
chase | chase-master/python/src/ml/vectorizer/fv_chase_skipgram_pos_only.py | '''everything is the same as chase_basic, but skip gram replaces ngram (skipgram is a superset)'''
import datetime
from ml import feature_extractor as fe
from ml import text_preprocess as tp
from ml import nlp
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from ml.ve... | 4,716 | 43.92381 | 119 | py |
chase | chase-master/python/src/ml/vectorizer/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/ml/vectorizer/fv_chase_basic.py | import datetime
import logging
from ml import feature_extractor as fe
from ml import text_preprocess as tp
from ml import nlp
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from ml.vectorizer import feature_vectorizer as fv
logger = logging.getLogger(__name__)
clas... | 3,911 | 41.064516 | 105 | py |
chase | chase-master/python/src/analysis/word_distribution_calculator.py | import csv
from ml import classifier_dnn as cd
import pandas as pd
# for each feature belonging to each class, calculate its distribution score, which is:
# freq(f1, c1)/#c1 / freq(f1, non-c1)/#non-c1
def calc_feature_score_distribution(input_data_file, sys_out, output_data_folder, word_norm_option, label_col):
... | 16,928 | 39.021277 | 128 | py |
chase | chase-master/python/src/analysis/tweet_normalizer_effect.py | from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
from analysis import embedding_vocab_checker as evc
import pandas as pd
text_processor = TextPreProcessor(
# terms that will be normalized
# normal... | 2,747 | 35.64 | 96 | py |
chase | chase-master/python/src/analysis/embedding_vocab_checker.py | import functools
import re
import gensim
import pandas as pd
import logging
import pickle
import datetime
from ml import text_preprocess as tp
from sklearn.feature_extraction.text import CountVectorizer
from ml import nlp
logger = logging.getLogger(__name__)
def get_word_vocab(tweets, out_folder, normalize_option):... | 5,245 | 33.064935 | 90 | py |
chase | chase-master/python/src/analysis/data_vocab_checker.py | import functools
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
from ml import nlp
from ml import text_preprocess as tp
def get_word_vocab(tweets, normalize_option):
word_vectorizer = CountVectorizer(
# vectorizer = sklearn.feature_extraction.text.CountVectorizer(
... | 5,673 | 34.4625 | 98 | py |
chase | chase-master/python/src/analysis/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/analysis/longtail_corrected_instance_analysis.py | import csv
import os
import pandas as pd
from ml import classifier_dnn as cd
# for each feature belonging to each class, calculate its distribution score, which is:
# freq(f1, c1)/#c1 / freq(f1, non-c1)/#non-c1
def calc_instance_unique_feature_percent(input_data_file, sys_out,
... | 8,655 | 41.22439 | 128 | py |
chase | chase-master/python/src/analysis/error_analyzer.py | import csv
import os
import pandas as pd
# given a gs_data file, find the corresponding splits used in experiment (75:25, the 25 part).
# given error files by each model, find the errors made by ALL models.
# output the message, the class, to outfolder
from sklearn.cross_validation import train_test_split
def collec... | 3,696 | 37.915789 | 94 | py |
chase | chase-master/python/src/exp/exp_traintest.py | from ml.vectorizer import fv_davison
def create_settings(sys_out, data_train, data_test):
#sys_out='../../../output' #where the system will save its required files, such as the trained models
#data_in='../../../data/labeled_data.csv'
#data_in='/home/zqz/Work/hate-speech-and-offensive-language/data/labeled_... | 1,467 | 46.354839 | 105 | py |
chase | chase-master/python/src/exp/classifier_traintest_main.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import os
import sys
import pandas as pd
from sklearn.cross_validation import train_test_split
from exp import classifier_gridsearch_main as cgm
from exp import exp_traintest as exp
from ml import classifier_gridsearch ... | 11,626 | 43.377863 | 110 | py |
chase | chase-master/python/src/exp/exp_gridsearch.py |
from ml.vectorizer import feature_vectorizer as fv
# each setting can use a different FeatureVectorizer to create different features. this way we can create a batch of experiments to run
def create_settings(sys_out, data_in, label, scores_per_ds, fvect: fv.FeatureVectorizer,
fs_options):
#sys_... | 3,857 | 51.849315 | 135 | py |
chase | chase-master/python/src/exp/classifier_gridsearch_main.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import sys
import os
import numpy
import pandas as pd
from sklearn.model_selection import train_test_split
from exp import exp_gridsearch as exp
from ml import classifier_gridsearch as cl
from ml import util
from ml.vec... | 9,924 | 43.707207 | 171 | py |
chase | chase-master/python/src/exp/__init__.py | 0 | 0 | 0 | py | |
chase | chase-master/python/src/exp/exp_gridsearch_with_sfeat.py | import sys
from exp.classifier_traintest_main import ChaseClassifier
from ml.vectorizer import fv_davison
from util import logger as ec
def create_settings(sys_out, data_path):
# sys_out='../../../output' #where the system will save its required files, such as the trained models
# data_in='../../../data/labe... | 2,602 | 47.203704 | 123 | py |
chase | chase-master/python/src/davidson/classifier.py | """
This file contains code to
(a) Load the pre-trained classifier and
associated files.
(b) Transform new input data into the
correct format for the classifier.
(c) Run the classifier on the transformed
data and return results.
"""
import pandas as pd
from sklearn.feature_selection import S... | 2,610 | 30.457831 | 118 | py |
chase | chase-master/python/src/davidson/translator.py | import pandas as pd
import os
print(os.getcwd())
#datain = pd.read_csv("../../../data/annotation/keywordfilered_merged.csv",sep=',', encoding="latin-1", usecols='oft')
#datain = open("../../../data/annotation/tagfilered_merged.csv",mode='r',encoding="latin-1")
#print(datain)
#linedata = []
#line = datain.readline()
#... | 5,364 | 41.92 | 118 | py |
nussl | nussl-master/setup.py | from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
with open('extra_requirements.txt') as f:
extra_requirements = f.read().splitlines()
setup(
name='nussl',
version="1.1.9",... | 1,763 | 33.588235 | 91 | py |
nussl | nussl-master/nussl/__init__.py | try:
import vamp
vamp_imported = True
except Exception:
vamp_imported = False
# Current nussl version
__version__ = '1.1.9'
class ImportErrorClass(object):
def __init__(self, lib, **kwargs):
raise ImportError(
f'Cannot import {type(self).__name__} because {lib} is not installed')
... | 725 | 20.352941 | 87 | py |
nussl | nussl-master/nussl/evaluation/evaluation_base.py | from itertools import permutations, combinations
import numpy as np
from .. import AudioSignal
from ..core import utils
class EvaluationBase(object):
"""
Base class for all Evaluation classes for source separation algorithms in nussl.
Contains common functions for all evaluation techniques. This class ... | 11,214 | 43.681275 | 100 | py |
nussl | nussl-master/nussl/evaluation/report_card.py | import pandas as pd
import json
import termtables
import numpy as np
import os
import textwrap
import copy
def truncate(values, decs=2):
return np.trunc(values*10**decs)/(10**decs)
def aggregate_score_files(json_files, aggregator=np.nanmedian):
"""
Takes a list of json files output by an Evaluation meth... | 12,181 | 40.719178 | 90 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.