Search is not available for this dataset
repo_id stringlengths 12 110 | file_path stringlengths 24 164 | content stringlengths 3 89.3M | __index_level_0__ int64 0 0 |
|---|---|---|---|
public_repos/lit-llama | public_repos/lit-llama/howto/convert_lora_weights.md | # Merging LoRA weights into base model weights
Purpose: By merging our selected LoRA weights into the base model weights, we can benefit from all base model optimisation such as quantisation (available in this repo), pruning, caching, etc.
## How to run?
After you have finish finetuning using LoRA, select your weig... | 0 |
public_repos/lit-llama | public_repos/lit-llama/quantize/gptq.py | # This adapts GPTQ's quantization process: https://github.com/IST-DASLab/gptq/
# E. Frantar et al GPTQ: Accurate Post-training Compression for GPT, arXiv:2210.17323
# portions copyright by the authors licensed under the Apache License 2.0
import gc
import sys
import time
from pathlib import Path
from typing import Opti... | 0 |
public_repos/lit-llama | public_repos/lit-llama/finetune/full.py | """
Instruction-tuning on the Alpaca dataset using a regular finetuning procedure (updating all layers).
Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/i... | 0 |
public_repos/lit-llama | public_repos/lit-llama/finetune/adapter_v2.py | """
Instruction-tuning with LLaMA-Adapter v2 on the Alpaca dataset following the paper
LLaMA-Adapter V2: Parameter-Efficient Visual Instruction Model
https://arxiv.org/abs/2304.15010
This script runs on a single GPU by default. You can adjust the `micro_batch_size` to fit your GPU memory.
You can finetune within 1 ho... | 0 |
public_repos/lit-llama | public_repos/lit-llama/finetune/lora.py | """
Instruction-tuning with LoRA on the Alpaca dataset.
Note: If you run into a CUDA error "Expected is_sm80 to be true, but got false", uncomment the line
`torch.backends.cuda.enable_flash_sdp(False)` in the script below (see https://github.com/Lightning-AI/lit-llama/issues/101).
"""
import sys
from pathlib import Pa... | 0 |
public_repos/lit-llama | public_repos/lit-llama/finetune/adapter.py | """
Instruction-tuning with LLaMA-Adapter on the Alpaca dataset following the paper
LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention
https://arxiv.org/abs/2303.16199
This script runs on a single GPU by default. You can adjust the `micro_batch_size` to fit your GPU memory.
You can finet... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_adapter.py | from dataclasses import asdict
import pytest
import sys
import torch
@pytest.mark.skipif(sys.platform == "win32", reason="EmptyInitOnDevice on CPU not working for Windows.")
@pytest.mark.parametrize("model_size", ["7B", "13B", "30B", "65B"])
def test_config_identical(model_size, lit_llama):
import lit_llama.adapt... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_rope.py | import torch
@torch.no_grad()
def test_rope(lit_llama, orig_llama) -> None:
torch.manual_seed(1)
bs, seq_len, n_head, n_embed = 1, 6, 2, 8
x = torch.randint(0, 10000, size=(bs, seq_len, n_head, n_embed // n_head)).float()
freqs_cis = orig_llama.precompute_freqs_cis(n_embed // n_head, seq_len)
ll... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_prepare_shakespeare.py | import os
import subprocess
import sys
from pathlib import Path
wd = (Path(__file__).parent.parent / "scripts").absolute()
def test_prepare(tmp_path):
sys.path.append(str(wd))
import prepare_shakespeare
prepare_shakespeare.prepare(tmp_path)
assert set(os.listdir(tmp_path)) == {"train.bin", "tokeni... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_prepare_redpajama.py | import json
import os
import subprocess
import sys
from pathlib import Path
from unittest import mock
from unittest.mock import Mock, call, ANY
wd = (Path(__file__).parent.parent / "scripts").absolute()
import requests
def train_tokenizer(destination_path):
destination_path.mkdir(parents=True, exist_ok=True)
... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_rmsnorm.py | import torch
@torch.no_grad()
def test_rmsnorm(lit_llama, orig_llama) -> None:
block_size = 16
vocab_size = 16
sample = torch.rand(size=(2, block_size, vocab_size), dtype=torch.float32)
eps = 1e-6
orig_llama_rmsnorm = orig_llama.RMSNorm(vocab_size, eps=eps)(sample)
llama_rmsnorm = lit_llama.... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/conftest.py | import sys
from pathlib import Path
import pytest
wd = Path(__file__).parent.parent.absolute()
@pytest.fixture()
def orig_llama():
sys.path.append(str(wd))
from scripts.download import download_original
download_original(wd)
import original_model
return original_model
@pytest.fixture()
def... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_adapter_v2.py | import pytest
import sys
@pytest.mark.skipif(sys.platform == "win32", reason="EmptyInitOnDevice on CPU not working for Windows.")
@pytest.mark.parametrize("model_size", ["7B", "13B", "30B", "65B"])
def test_config_identical(model_size, lit_llama):
import torch.nn as nn
import lit_llama.adapter as llama_adapte... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_packed_dataset.py | import os
from unittest.mock import MagicMock
import requests
from torch.utils.data import IterableDataset
def train_tokenizer(destination_path):
destination_path.mkdir(parents=True, exist_ok=True)
# download the tiny shakespeare dataset
input_file_path = destination_path / "input.txt"
if not input_... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_generate.py | import functools
import subprocess
import sys
from contextlib import contextmanager, redirect_stdout
from io import StringIO
from pathlib import Path
from unittest import mock
from unittest.mock import Mock, call, ANY
import torch
wd = Path(__file__).parent.parent.absolute()
@functools.lru_cache(maxsize=1)
def load... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_utils.py | import tempfile
import pathlib
import torch
class ATensor(torch.Tensor):
pass
def test_lazy_load_basic(lit_llama):
import lit_llama.utils
with tempfile.TemporaryDirectory() as tmpdirname:
m = torch.nn.Linear(5, 3)
path = pathlib.Path(tmpdirname)
fn = str(path / "test.pt")
... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_model.py | import torch
import pytest
import sys
def copy_mlp(llama_mlp, orig_llama_mlp) -> None:
orig_llama_mlp.w1.weight.copy_(llama_mlp.c_fc1.weight)
orig_llama_mlp.w3.weight.copy_(llama_mlp.c_fc2.weight)
orig_llama_mlp.w2.weight.copy_(llama_mlp.c_proj.weight)
def copy_attention(llama_attn, orig_llama_attn) -> ... | 0 |
public_repos/lit-llama | public_repos/lit-llama/tests/test_lora.py | import torch
def test_lora_layer_replacement(lit_llama):
from lit_llama.lora import lora, CausalSelfAttention as LoRACausalSelfAttention
from lit_llama.model import LLaMA, LLaMAConfig
config = LLaMAConfig()
config.n_layer = 2
config.n_head = 4
config.n_embd = 8
config.block_size = 8
... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/download.py | import os
from typing import Optional
from urllib.request import urlretrieve
files = {
"original_model.py": "https://gist.githubusercontent.com/lantiga/fd36849fb1c498da949a0af635318a7b/raw/7dd20f51c2a1ff2886387f0e25c1750a485a08e1/llama_model.py",
"original_adapter.py": "https://gist.githubusercontent.com/awael... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/convert_checkpoint.py | import gc
import shutil
from pathlib import Path
from typing import Dict
import torch
from tqdm import tqdm
"""
Sample usage:
```bash
python -m scripts.convert_checkpoint -h
python -m scripts.convert_checkpoint converted
```
"""
def convert_state_dict(state_dict: Dict[str, torch.Tensor], dtype: torch.dtype = torc... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/prepare_redpajama.py | import json
import glob
import os
from pathlib import Path
import sys
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
import numpy as np
from tqdm import tqdm
from lit_llama import Tokenizer
import lit_llama.packed_dataset as packed_dataset
fil... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/convert_lora_weights.py | import sys
import time
from pathlib import Path
from typing import Optional
import lightning as L
import torch
import torch.nn as nn
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from lit_llama import LLaMA
from lit_llama.utils import EmptyInit... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/prepare_shakespeare.py | # MIT License
# Copyright (c) 2022 Andrej Karpathy
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/prepare_alpaca.py | """Implementation derived from https://github.com/tloen/alpaca-lora"""
import sys
from pathlib import Path
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
import torch
import requests
import json
from torch.utils.data import random_split
from lit_... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/prepare_dolly.py | """Implementation derived from https://github.com/tloen/alpaca-lora"""
import sys
from pathlib import Path
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
import torch
import requests
import json
from torch.utils.data import random_split
from lit_... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/convert_hf_checkpoint.py | import collections
import contextlib
import gc
import json
import shutil
import sys
from pathlib import Path
import torch
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from lit_llama.model import LLaMA, LLaMAConfig
from lit_llama.utils import E... | 0 |
public_repos/lit-llama | public_repos/lit-llama/scripts/prepare_any_text.py | """Implementation derived from https://github.com/tloen/alpaca-lora"""
import sys
from pathlib import Path
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
import torch
import requests
import json
from torch.utils.data import random_split
from lit_... | 0 |
public_repos/lit-llama | public_repos/lit-llama/generate/full.py | import sys
import time
import warnings
from pathlib import Path
from typing import Optional
import lightning as L
import torch
# support running without installing as a package
wd = Path(__file__).absolute().parent.parent
sys.path.append(str(wd))
from lit_llama import LLaMA, Tokenizer
from lit_llama.utils import qua... | 0 |
public_repos/lit-llama | public_repos/lit-llama/generate/adapter_v2.py | import sys
import time
import warnings
from pathlib import Path
from typing import Optional
import lightning as L
import torch
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from generate import generate
from lit_llama import Tokenizer
from lit_... | 0 |
public_repos/lit-llama | public_repos/lit-llama/generate/lora.py | import sys
import time
import warnings
from pathlib import Path
from typing import Optional
import lightning as L
import torch
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from generate import generate
from lit_llama import Tokenizer, LLaMA
fr... | 0 |
public_repos/lit-llama | public_repos/lit-llama/generate/adapter.py | import sys
import time
import warnings
from pathlib import Path
from typing import Optional
import lightning as L
import torch
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from generate import generate
from lit_llama import Tokenizer
from lit_... | 0 |
public_repos | public_repos/nltk_contrib/MANIFEST.in | include LICENSE.txt
include INSTALL.txt
include README.txt
| 0 |
public_repos | public_repos/nltk_contrib/LICENSE.txt | Copyright (C) 2001-2011 NLTK Project
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 applicable law or agreed to in writing, softwa... | 0 |
public_repos | public_repos/nltk_contrib/README.txt | Natural Language Toolkit, Contrib Area (NLTK-Contrib) www.nltk.org
Authors: Steven Bird <sb@csse.unimelb.edu.au>
Edward Loper <edloper@gradient.cis.upenn.edu>
Ewan Klein <ewan@inf.ed.ac.uk>
Copyright (C) 2001-2011 NLTK Project
For license information, see LICENSE.txt
| 0 |
public_repos | public_repos/nltk_contrib/setup.py | #!/usr/bin/env python
#
# Distutils setup script for NLTK-Contrib
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# Ewan Klein <ewan@inf.ed.ac.uk>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.... | 0 |
public_repos | public_repos/nltk_contrib/Makefile | # Natural Language Toolkit: source Makefile
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
PYTHON = python
VERSION = $(shell $(PYTHON) -c 'import nltk; prin... | 0 |
public_repos | public_repos/nltk_contrib/INSTALL.txt | To install NLTK-Contrib, run setup.py from an administrator account, e.g.:
sudo python setup.py install
For full installation instructions, please see http://www.nltk.org/download
| 0 |
public_repos | public_repos/nltk_contrib/setup-eggs.py | #!/usr/bin/env python
#
# Distutils setup script for NLTK-Contrib
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# Ewan Klein <ewan@inf.ed.ac.uk>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/speer.cfg | %start Start
Start -> S
S/?x -> NP VP/?x
NP/NP ->
NP[plural=?p] -> N[plural=?p] | Det[plural=?p] N[plural=?p]
VP[tense=?t] -> V[tense=?t]
VP[tense=?t]/?x -> V[tense=?t] NP/?x
VP[tense=?t]/?x -> V[tense=?t] NP/?x PP
VP[tense=?t]/?x -> V[tense=?t] NP PP/?x
R -> COMP S/NP
NP[plural=?p] -> NP[plural=?p] R
NP[plural=?p]/... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/wals.py | # Natural Language Toolkit: WALS interface
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Michael Wayne Goodman <goodmami@uw.edu>
#
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
#
# For more information about WALS (the World Atlas of Language Structures),
# see http://wals.info. WALS is c... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/README.txt | Status of NLTK-Contrib Projects
-------------------------------
nltk.demo/app/projects = new home for mature packages that aren't libraries
installed in user space?
agreement
bioreader MIGRATE into nltk.corpus
ccg MIGRATE [merge into nltk.parse, or a new package?]
classifier* investigate
c... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/timex.py | # Code for tagging temporal expressions in text
# For details of the TIMEX format, see http://timex2.mitre.org/
import re
import string
import os
import sys
# Requires eGenix.com mx Base Distribution
# http://www.egenix.com/products/python/mxBase/
try:
from mx.DateTime import *
except ImportError:
print """
R... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/referring.py | # Natural Language Toolkit: Generating referring expressions
#
# Author: Margaret Mitchell <itallow@u.washington.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
import sys
import re
class IncrementalAlgorithm:
"""
An implementation of the Incremental Algorithm, introduced in:
... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/stringcomp.py | # Natural Language Toolkit
# String Comparison Module
# Author: Tiago Tresoldi <tresoldi@users.sf.net>
"""
String Comparison Module.
Author: Tiago Tresoldi <tresoldi@users.sf.net>
Based on previous work by Qi Xiao Yang, Sung Sam Yuan, Li Zhao, Lu Chun,
and Sung Peng.
"""
def stringcomp (fx, fy):
"""
Return a... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/textgrid.py | # Natural Language Toolkit: TextGrid analysis
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Margaret Mitchell <itallow@gmail.com>
# Steven Bird <sb@csse.unimelb.edu.au> (revisions)
# URL: <http://www.nltk.org>
# For license information, see LICENSE.TXT
#
"""
Tools for reading TextGrid files, the format us... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/featuredemo.py | from nltk.parse import GrammarFile
from nltk.parse.featurechart import *
"""
An interactive interface to the feature-based parser. Run "featuredemo.py -h" for
command-line options.
This interface will read a grammar from a *.cfg file, in the format of
test.cfg. It will prompt for a filename for the grammar (unless on... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/concord.py | # Natural Language Toolkit: Concordance System
#
# Copyright (C) 2005 University of Melbourne
# Author: Peter Spiller
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
from nltk.corpus import brown
from math import *
import re, string
from nltk.probability import *
class SentencesIndex(object):... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/test2.cfg | %start S
S[sem=<app(?vp, ?subj)>] -> NP[sem=?subj] V[sem=?v]
NP[sem = <kim>] -> 'Kim'
V[sem = <\x.(sleeps x)>] -> 'sleeps'
| 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/combined.py | import math
import os
# tagger importing
from nltk import tag
from nltk.tag import SequentialBackoff
# work-around while marshal is not moved into standard tree
from nltk_contrib.marshal import MarshalDefault ; Default = MarshalDefault
from nltk_contrib.marshal import MarshalUnigram ; Unigram = MarshalUnigram
from nlt... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/seqclass.py | from nltk.classify import iis
import yaml
import os
class SequentialClassifier(object):
def __init__(self, left=2, right=0):
#left = look back
#right = look forward
self._model = []
self._left = left
self._right = right
self._leftcontext = [None] * (left)
self._histo... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/test2.out | Grammar with 1 productions (start state = S[])
S[sem='(?vp ?subj)'] -> NP[sem=?subj] V[sem=?v]
|.K.s.|
Processing queue 0
? S == S[sem='(?vp ?subj)']
|
| Unify "pos" feature:
| ? 'S' == 'S'
| > 'S'
|
| Unify "/" feature:
| ? None == None
| > None
|
> S[sem='(?vp ?subj)'... | 0 |
public_repos/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/__init__.py | # Natural Language Toolkit (NLTK) Contrib Area
#
# Copyright (C) 2001-2011 NLTK Project
# Authors: Steven Bird <sb@csse.unimelb.edu.au>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: http://www.nltk.org/
# For license information, see LICENSE.TXT
| 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/langid.py | """
Sam Huston 2007
This is a simulation of the article:
"Evaluation of a language identification system for mono- and multilingual text documents"
by Artemenko, O; Mandl, T; Shramko, M; Womser-Hacker, C.
presented at: Applied Computing 2006, 21st Annual ACM Symposium on Applied Computing; 23-27 April 2006
This imple... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/annotationgraph.py | # Natural Language Toolkit: Annotation Graphs
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
from nltk import Tree, Index
class AnnotationGraph(object):
def __init__(self, t):
self._edges... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/fsa.py | # Natural Language Toolkit: Finite State Automata
#
# Copyright (C) 2001-2006 NLTK Project
# Authors: Steven Bird <sb@ldc.upenn.edu>
# Rob Speer <rspeer@mit.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
A module for finite state automata.
Operations are based on Aho, Sethi... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/marshalbrill.py | # Natural Language Toolkit: Brill Tagger
#
# Copyright (C) 2001-2005 NLTK Project
# Authors: Christopher Maloof <cjmaloof@gradient.cis.upenn.edu>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@ldc.upenn.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/kimmo.help | ; pykimmo.help
; PyKimmo version 1.78
;
; Professor Bob Berwick
; Beracah Yankama
; Error messages & troubleshooting at the bottom.
::INTRO::
PyKimmo is intended to bridge some of the learning gaps in using PCKIMMO.
By providing a gui, with rule rendering and instant feedback on rule
success while editing, we hop... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/lex.py | """
Ewan Klein, March 2007
Experimental module to provide support for implementing English morphology by
feature unification.
Main challenge is to find way of encoding morphosyntactic rules. Current idea is to let a concatenated form such as 'walk + s' be encoded as a dictionary C{'stem': 'walk', 'affix': 's'}. This ... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/huffman.py | # Simple Huffman encoding/decoding, Steven Bird
# http://en.wikipedia.org/wiki/Huffman_coding
import nltk
from operator import itemgetter
def huffman_tree(text):
coding = nltk.FreqDist(text).items()
coding.sort(key=itemgetter(1))
while len(coding) > 1:
a, b = coding[:2]
pair = (a[0], b[0])... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/marshal.py | # Marshaling code, contributed by Tiago Tresoldi
# This saves/loads models to/from plain text files.
# Unlike Python's shelve and pickle utilities,
# this is useful for inspecting or tweaking the models.
# We may incorporate this as a marshal method in each model.
# TODO: describe each tagger marshal format in the epy... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/paradigm.py | # Natural Language Toolkit: Paradigm Visualisation
#
# Copyright (C) 2005 University of Melbourne
# Author: Will Hardy
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
# Front end to a Python implementation of David
# Penton's paradigm visualisation model.
# Author:
#
# Run: To run, first load... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/didyoumean.py | # Spelling corrector by Maxime Biais http://www.biais.org/blog/
# http://snippets.dzone.com/posts/show/3395
from nltk import PorterStemmer
from nltk.corpus import brown
import sys
from collections import defaultdict
import operator
def sortby(nlist ,n, reverse=0):
nlist.sort(key=operator.itemgetter(n), reverse... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/kimmo.py | # Natural Language Toolkit: Kimmo Morphological Analyzer
#
# Copyright (C) 2001-2007 MIT
# Author: Carl de Marcken <carl@demarcken.org>
# Beracah Yankama <beracah@mit.edu>
# Robert Berwick <berwick@ai.mit.edu>
#
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
Kimmo Morpholo... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/misc/paradigmquery.py | # Natural Language Toolkit: Paradigm Visualisation
#
# Copyright (C) 2005 University of Melbourne
# Author: Will Hardy
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
# Parses a paradigm query and produces an XML representation of
# that query. This is part of a Python implementation of David
... | 0 |
public_repos/nltk_contrib/nltk_contrib | public_repos/nltk_contrib/nltk_contrib/hadoop/readme | hadooplib direcotry provide the service of this library. It contains the base class for map and reduce class, the default input formatter and ouput collector
other directory contains different demo programs to illustrate how to use this library
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/run.bat | @echo off
python wordcount_mapper.py < brown-ca01 | sort.exe | python wordcount_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/brown-ca01 |
The/at Fulton/np-tl County/nn-tl Grand/jj-tl Jury/nn-tl said/vbd Friday/nr an/at investigation/nn of/in Atlanta's/np$ recent/jj primary/nn election/nn produced/vbd ``/`` no/at evidence/nn ''/'' that/cs any/dti irregularities/nns took/vbd place/nn ./.
The/at jury/nn further/rbr said/vbd in/in term-end/nn presentme... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/run.sh | #!/bin/sh
export LC_ALL=C
cat brown-ca01 | ./wordcount_mapper.py | sort | ./wordcount_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/wordcount_reducer.py |
from hadooplib.reducer import ReducerBase
class WordCountReducer(ReducerBase):
"""
count the occurences of each word
"""
def reduce(self, key, values):
"""
for each word, accmulate all the partial sum
@param key: word
@param values: list of partical sum
"""
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/wordcount_mapper.py |
from hadooplib.mapper import MapperBase
class WordCountMapper(MapperBase):
"""
count the occurences of each word
"""
def map(self, key, value):
"""
for each word in input, output a (word, 1) pair
@param key: None, no use
@param value: line from input
"""
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/word_count/runStreaming.sh | #!/bin/sh
streamer="/usr/local/hadoop/contrib/streaming/hadoop-*-streaming.jar"
hadoop="/usr/local/hadoop/bin/hadoop"
$hadoop dfs -rmr wordcount-out
$hadoop jar $streamer -mapper wordcount_mapper.py -reducer wordcount_reducer.py -input wordcount-input -output wordcount-out -file EM_mapper.py -file EM_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/hadooplib/outputcollector.py | class LineOutput:
"""
default output class, output key and value
as (key, value) pair separated by separator
"""
@staticmethod
def collect(key, value, separator = '\t'):
"""
collect the key and value, output them to
a line separated by a separator character
@p... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/hadooplib/reducer.py | from itertools import groupby
from operator import itemgetter
from inputformat import KeyValueInput
from outputcollector import LineOutput
class ReducerBase:
"""
Base class for every reduce tasks
Your reduce class should extend this base class
and override the reduce function
"""
def __ini... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/hadooplib/inputformat.py | from sys import stdin
class TextLineInput:
"""
treat the input as lines of text
emit None as key and text line as value
"""
@staticmethod
def read_line(file=stdin):
"""
read and parse input file, for each line, yield a (None, line) pair
@return: yield a (None, li... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/hadooplib/mapper.py | from inputformat import TextLineInput
from outputcollector import LineOutput
class MapperBase:
"""
Base class for every map tasks
Your map class should extend this base class
and override the map function
"""
def __init__(self):
"""
set the default input formatter and o... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/hadooplib/util.py | """
utility to convert data representation between tuple and string
provide convenient methods for parsing the input string to tuple and
formatting the tuple to string output
"""
def tuple2str(t, separator = ' '):
"""
convert tuple into string expression
@param t: tuple to be converted
@type t: C{tup... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/male.txt | Aamir
Aaron
Abbey
Abbie
Abbot
Abbott
Abby
Abdel
Abdul
Abdulkarim
Abdullah
Abe
Abel
Abelard
Abner
Abraham
Abram
Ace
Adair
Adam
Adams
Addie
Adger
Aditya
Adlai
Adnan
Adolf
Adolfo
Adolph
Adolphe
Adolpho
Adolphus
Adrian
Adrick
Adrien
Agamemnon
Aguinaldo
Aguste
Agustin
Aharon
Ahmad
Ahmed
Ahmet
Ajai
Ajay
Al
Alaa
Alain
Alan
Al... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/name_mapper1.py | from hadooplib.mapper import MapperBase
class NameMapper(MapperBase):
"""
map a name to its first character
e.g. Adam -> (Adam, A)
"""
def map(self, key, value):
"""
map a name to its first character
@param key: None
@param value: name
"""
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/swap_mapper.py | from hadooplib.mapper import MapperBase
from hadooplib.inputformat import KeyValueInput
class SwapMapper(MapperBase):
"""
swap (key, value) pair to (value, key) pair,
i.e. swap the role of key and value
e.g. word 1 -> 1 word
"""
def __init__(self):
MapperBase.__init__(self)
# ... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/run.bat | @echo off
type male.txt | python name_mapper1.py | unixsort | cat | python swap_mapper.py | unixsort | python value_aggregater.py | python name_mapper2.py | unixsort | python similiar_name_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/run.sh | #!/bin/sh
export LC_ALL=C
cat male.txt | ./name_mapper1.py |sort | /bin/cat | ./swap_mapper.py | sort | ./value_aggregater.py | ./name_mapper2.py | sort | ./similiar_name_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/name_mapper2.py | from hadooplib.inputformat import KeyValueInput
from hadooplib.mapper import MapperBase
from hadooplib.util import tuple2str
class Name2Names(MapperBase):
"""
map a name to the name before and after it
e.g. (A, Ada Adam Adams) -> (Adam, Ada Adams)
"""
def __init__(self):
MapperBase.__init... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/value_aggregater.py | from hadooplib.reducer import ReducerBase
from hadooplib.util import tuple2str
class ValueAggregater(ReducerBase):
"""
aggregate the values having the same key.
e.g. (animal, cat)
(animal, dog)
(animal, mouse)
->
(animal, cat dog mouse)
"""
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/similiar_name_reducer.py | from hadooplib.reducer import ReducerBase
class Name2SimiliarName(ReducerBase):
"""
find the most simliar name for the given name,
from the name before and after it
e.g. (Adam, Ada Adams) -> (Adam, Ada)
"""
def reduce(self, key, values):
"""
find the most simliar name for the... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/name_similarity/runStreaming.sh | streamer="/usr/local/hadoop/contrib/streaming/hadoop-*-streaming.jar"
hadoop="/usr/local/hadoop/bin/hadoop"
$hadoop dfs -rmr output-1
$hadoop jar $streamer -mapper name_mapper1.py -reducer /bin/cat -input name -output output-1 -file name_mapper1.py
$hadoop dfs -rmr output-2
$hadoop jar $streamer -mapper swap_mapper.... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/runStreaming.py | """
this script shows how to iteratively run the MapReduce task
"""
from subprocess import Popen
import sys
# convergence threshold
diff = 0.0001
oldlog = 0
newlog = 1
iter = 100
i = 0
# while not converged or not reach maximum iteration number
while (abs(newlog - oldlog) > diff and i <= iter):
print "oldlog", o... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/EM_reducer.py | from hadooplib.reducer import ReducerBase
from hadooplib.util import *
from nltk.tag.hmm import _log_add, _NINF
from numpy import *
import sys
class EM_Reducer(ReducerBase):
"""
combine local hmm parameters to estimate a global parameter
"""
def reduce(self, key, values):
"""
combine ... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/untagged | hhhhhthhthhhthhhhhhhhhhhhhhhhhhhththhhhhhhhhhhhhhhhhhthhhhthhhhhhhhhhhhhhhhhthhhhhhhhhhhhhhhthhhhhhhthththt
hhhhhthhthhhthhhhhhhhhhhhhhhhhhhththhhhhhhhhhhhhhhhhhthhhhthhhhhhhhhhhhhhhhhthhhhhhhhhhhhhhhthhhhhhhthththt
hhhhhthhthhhthhhhhhhhhhhhhhhhhhhththhhhhhhhhhhhhhhhhhthhhhthhhhhhhhhhhhhhhhhthhhhhhhhhhhhhhhthhhhhhhthth... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/EM_mapper.py | from nltk import FreqDist, ConditionalFreqDist, ConditionalProbDist, \
DictionaryProbDist, DictionaryConditionalProbDist, LidstoneProbDist, \
MutableProbDist, MLEProbDist, UniformProbDist, HiddenMarkovModelTagger
from nltk.tag.hmm import _log_add
from hadooplib.mapper import MapperBase
from hadooplib.util impo... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/hmm_parameter | Pi 1 0.5
Pi 0 0.5
A 0 0 0.5
A 0 1 0.5
A 1 0 0.5
A 1 1 0.5
B 0 h 0.5
B 0 t 0.5
B 1 h 0.5
B 1 t 0.5
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/run.bat | @echo off
python EM_mapper.py < untagged | python EM_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/run.sh | #!/bin/sh
./EM_mapper.py < untagged | ./EM_reducer.py
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/EM/runStreaming.sh | #!/bin/sh
streamer="/usr/local/hadoop/contrib/streaming/hadoop-*-streaming.jar"
hadoop="/usr/local/hadoop/bin/hadoop"
$hadoop dfs -rmr EM-out
$hadoop jar $streamer -mapper EM_mapper.py -reducer EM_reducer.py -input EM-input -output EM-out -file EM_mapper.py -file EM_reducer.py -file hmm_parameter
| 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/idf_reduce.py | from hadooplib.reducer import ReducerBase
class IDFReducer(ReducerBase):
def reduce(self, key, values):
sum = 0
try:
for value in values:
sum += int(value)
self.outputcollector.collect(key, sum)
except ValueError:
#count was not a numbe... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/tfidf_reduce1.py |
from hadooplib.reducer import ReducerBase
from math import log
class TFIDFReducer1(ReducerBase):
"""
computing the TF*IDF value for every word
(word, [filename occurences...]) -> (word, [filename TF*IDF...])
"""
def reduce(self, key, values):
"""
computing the TF*IDF value for ev... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/tfidf_map1.py | from hadooplib.mapper import MapperBase
from hadooplib.inputformat import KeyValueInput
class TFIDFMapper1(MapperBase):
"""
keep only the word in the key field
remove filename from key and put it into value
(word filename, number) -> (word, filename number)
e.g. (dog 1.txt, 1) -> (dog, 1.txt 1)
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/idf_map.py | from hadooplib.mapper import MapperBase
from hadooplib.inputformat import KeyValueInput
class IDFMapper(MapperBase):
"""
output (word All, 1) for every (word filename, tf) pair
(word filename, tf) -> (word All, 1)
"""
def __init__(self):
MapperBase.__init__(self)
# use KeyValueInp... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/tf_map.py | from hadooplib.mapper import MapperBase
class TFMapper(MapperBase):
"""
get the filename (one filename per line),
open the file and count the term frequency.
"""
def map(self, key, value):
"""
output (word filename, 1) for every word in files
@param key: None
@par... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/tf_reduce.py | from hadooplib.reducer import ReducerBase
class TFReducer(ReducerBase):
"""
sum the occurences of every word
"""
def reduce(self, key, values):
"""
@param key: word
@param values: list of partial sum
"""
sum = 0
try:
for value in values:
... | 0 |
public_repos/nltk_contrib/nltk_contrib/hadoop | public_repos/nltk_contrib/nltk_contrib/hadoop/tf_idf/tfidf_map2.py | from hadooplib.mapper import MapperBase
from hadooplib.inputformat import KeyValueInput
class TFIDFMapper2(MapperBase):
"""
sort TF*IDF value by filename
(word, [filename TF*IDF...]) -> (filename TF*IDF, word)
"""
def __init__(self):
MapperBase.__init__(self)
self.set_inputformat(... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.