반응형

비슷한 말로 '말초적'

반응형
반응형

gensim + word2vec 모델 만들어서 사용하기 



참고 : https://www.lucypark.kr/courses/2015-ba/text-mining.html



#Load data

from konlpy.corpus import kobill

docs_ko = [kobill.open(i).read() for i in kobill.fileids()]


#Tokenize

from konlpy.tag import Twitter; t = Twitter()

pos = lambda d: ['/'.join(p) for p in t.pos(d)]

texts_ko = [pos(doc) for doc in docs_ko]


#Train

from gensim.models import word2vec

wv_model_ko = word2vec.Word2Vec(texts_ko)

wv_model_ko.init_sims(replace=True)

wv_model_ko.save('ko_word2vec.model')    #model create


#Test - 유사도 분석

wv_model_ko.most_similar(pos('정부'))

wv_model_ko.most_similar(pos('초등학교'))





  * 저장된 model 사용하기 : https://radimrehurek.com/gensim/models/word2vec.html


Initialize a model with e.g.:

>>> model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)

Persist a model to disk with:

>>> model.save(fname)
>>> model = Word2Vec.load(fname)  # you can continue training with the loaded model!

The word vectors are stored in a KeyedVectors instance in model.wv. This separates the read-only word vector lookup operations in KeyedVectors from the training code in Word2Vec.

>>> model.wv['computer']  # numpy vector of a word
array([-0.00449447, -0.00310097,  0.02421786, ...], dtype=float32)


model 이 잘 불러와졌는지 확인하려면 model의 내용을 보자. 

model.vocab 하며 내용을 볼 수 있다. 

most_similar 에서 vocaburary에 단어가 없다고 에러나오면 내용을 확인 후 다시 검색해보면 된다. 

저장된 vocab이 '국어' 인지, '국어/Noun' 인지 확인 바람요! 


>>>len(model.vocab)

9867

>>>model.vocab 



Code for the word2vec HTTP server running at https://rare-technologies.com/word2vec-tutorial/#bonus_app



*** 대화 형 word2vec 데모 용 전체 HTTP 서버 코드 : 

     https://github.com/RaRe-Technologies/w2v_server_googlenews



모델 저장 및로드

표준 gensim 메소드를 사용하여 모델을 저장 /로드 할 수 있습니다.

1
2
model.save('/tmp/mymodel')
new_model = gensim.models.Word2Vec.load('/tmp/mymodel')

내부적으로 피클을 사용하는 선택적 mmap를 프로세스 간 메모리 공유 디스크 파일에서 직접 가상 메모리에 모델의 내부 큰 NumPy와 행렬을 보내고 '.

또한 텍스트 및 이진 형식을 사용하여 원본 C 도구로 만든 모델을로드 할 수 있습니다.

1
2
model = Word2Vec.load_word2vec_format('/tmp/vectors.txt', binary=False)
# using gzipped/bz2 input works too, no need to unzip:
model = Word2Vec.load_word2vec_format('/tmp/vectors.bin.gz', binary=True)

온라인 교육 / 훈련 재개

고급 사용자는 모델을로드하고 더 많은 문장으로 계속 교육 할 수 있습니다.

1
2
model = gensim.models.Word2Vec.load('/tmp/mymodel')
model.train(more_sentences)

시뮬레이트 할 학습 속도 감소에 따라 total_words 매개 변수를 train ()에 맞게 조정해야 할 수도 있습니다 .

C 도구 load_word2vec_format ()에 의해 생성 된 모델로는 교육을 재개 할 수 없습니다 당신은 여전히 ​​그것들을 질의 / 유사성을 위해 사용할 수 있지만, 훈련에 필수적인 정보 (보캐 트리)가 거기에 없습니다.

모델 사용

Word2vec는 여러 단어 유사 작업을 즉시 지원합니다.

1
2
4
5
6
model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)
[('queen', 0.50882536)]
model.doesnt_match("breakfast cereal dinner lunch";.split())
'cereal'
model.similarity('woman', 'man')
0.73723527

응용 프로그램에서 원시 출력 벡터가 필요한 경우에는 단어 단위로 이들에 액세스 할 수 있습니다

1
2
model['computer'# raw NumPy vector of a word
array([-0.00449447, -0.003100970.02421786, ...], dtype=float32)

... 또는 en-masse를 model.syn0 의 2D NumPy 행렬로 사용 하십시오 .



...

반응형
반응형

Flask 설치 - http://flask-docs-kr.readthedocs.io/ko/latest/installation.html


소개 : https://code.tutsplus.com/ko/tutorials/an-introduction-to-pythons-flask-framework--net-28822



플라스크는 작고 강력한 파이썬의 웹 프레임워크 입니다. 플라스크는 배우기 쉽고, 짧은 시간에 웹앱을 만들수 있습니다.


Flask의 세계에 오신것을 환영합니다.

Flask: web development, one drop at a time

Flask 문서에 오신것을 환영합니다. 이 문서는 다양한 파트로 나누어져 있습니다. 저자는 설치하기 와 빠르게 시작하기 를 먼저 보실것을 추천합니다. 빠르게 시작하기 뿐만아니라, 어떻게 Flask 어플리케이션을 만들 수 있는지 좀 더 상세하게 다루는 튜토리얼 또한 볼 수 있습니다.

만약 여러분이 오히려 Flask의 내부로 직접 뛰어 들고 싶은 경우라면,
API 문서를 확인하십시오. 일반적으로 사용되는 패턴들은

Flask를 위한 패턴들 섹션을 확인하면 됩니다..

Flask는 두개의 외부 라이브러리에 의존합니다.: 바로 Jinja2 템플릿엔진과 Werkzeug WSGI 툴킷입니다. 이 라이브러리들은 이 문서에서 다루지않습니다. 만약 여러분이 이 라이브러리들에 대해서 깊이 알고 싶다면 다음의 링크를 확인하십시오.


반응형
반응형

[MSSQL] 세로 데이터 가로로 출력 (데이터 한줄로 출력) STUFF, FOR XML PATH


http://ggmouse.tistory.com/127




DECLARE @string AS VARCHAR(1000);

SET @string = '';

 

WITH TABLE_A (NAME) AS (

    SELECT '손꽁쥐' UNION ALL

    SELECT '윤선생' UNION ALL

    SELECT '황박사'

)

 

SELECT @string = NAME + ', ' + @string FROM TABLE_A

SELECT @string AS '가로출력' 




--  

WITH TABLE_A (CLASS, NAME) AS (

    SELECT 'A', '손꽁쥐' UNION ALL

    SELECT 'B', '윤선생' UNION ALL

    SELECT 'A', '황박사'

)

SELECT * FROM

(

    SELECT CLASS, STUFF((SELECT ',' + NAME FROM TABLE_A WHERE CLASS = A.CLASS FOR XML PATH('')), 1, 1, '') AS 'Result'

    FROM TABLE_A AS A

) A

GROUP BY A.CLASS, A.Result


반응형
반응형

Unofficial Windows Binaries for Python Extension Packages



Python 확장 패키지 용 비공식 Windows 바이너리
Christoph Gohlke, Irvine, 캘리포니아 대학의 형광 동력학 실험실.
이 페이지는 Python 프로그래밍 언어의 공식 CPython 배포판을위한 많은 과학적 오픈 소스 확장 패키지의 32 비트 및 64 비트 Windows 바이너리를 제공합니다.
파일은 비공식적 인 형식 (비공식, 비 인식, 개인, 지원되지 않음, 무보증, 책임 없음, "있는 그대로"제공됨)이며 테스트 및 평가 목적으로 제공됩니다.
다운로드가 실패하면이 페이지를 새로 고침하고, JavaScript를 활성화하고, 다운로드 관리자를 비활성화하고, 프록시를 비활성화하고, 캐시를 지우고 Firefox를 사용하십시오. 필요에 따라 수동으로 파일을 다운로드하십시오.
대부분의 바이너리는 PyPI 또는 프로젝트 공개 개정 관리 시스템에서 찾을 수있는 소스 코드로 작성됩니다. 소스 코드 변경 사항은 프로젝트 관리자에게 제출되었거나 패키지에 포함되어 있습니다.
라이센스 제한 및 종속성에 대해서는 개별 패키지의 문서를 참조하십시오.
pip 버전 8 이상을 사용하여 다운로드 한 .whl 파일을 설치하십시오. 이 페이지는 pip 패키지 색인이 아닙니다.
많은 바이너리는 numpy-1.11 + mkl과 Microsoft Visual C ++ 2008 (CPython 2.7 용 x64, x86 및 SP1), Visual C ++ 2010 (x64, CPython 3.4 용 x86) 또는 Visual C ++ 2015 (x64 및 x86 용 CPython 3.5 및 3.6) 재배포 가능 패키지
numpy + mkl을 의존하는 다른 패키지보다 먼저 설치하십시오.
바이너리는 Windows> = 6.0에서 가장 최근의 공식 CPython 배포판과 호환됩니다. Blender, Maya, ArcGIS, OSGeo4W, ABAQUS, Cygwin, Pythonxy, Canopy, EPD, Anaconda, WinPython 등에 포함 된 Python 배포판에서는 작동하지 않을 가능성이 많습니다. 많은 바이너리는 Windows XP 또는 Wine과 호환되지 않습니다.
패키지는 ZIP 또는 7z 파일로, 수동 또는 스크립팅 설치 또는 재 패키징이 가능합니다.
이 파일은 어떠한 종류의 보증이나 지원없이 "있는 그대로"제공됩니다. 품질 및 성능에 대한 모든 위험은 귀하와 함께 있습니다.
이 페이지에 표명 된 의견이나 진술은 형광 역학 연구소 또는 캘리포니아 주립 대학의 지위 또는 승인으로 간주되어서는 안됩니다.


반응형
반응형

matplotlib의 scatter 만들기 . 그래프


Scatter Plots in Python  https://plot.ly/python/line-and-scatter/
reference : https://plot.ly/python/reference/#scatter


plot 버전 체크  


>>import plotly
>>plotly.__version__



scatter 만들기


import plotly.plotly as py

import plotly.graph_objs as go


# Create random data with numpy

import numpy as np


N = 1000

random_x = np.random.randn(N)

random_y = np.random.randn(N)


# Create a trace

trace = go.Scatter(

    x = random_x,

    y = random_y,

    mode = 'markers'

)


data = [trace]


# Plot and embed in ipython notebook!

py.iplot(data, filename='basic-scatter')


# or plot with: plot_url = py.plot(data, filename='basic-line')



...


반응형
반응형

파이썬에서 유니코드 스트림 다루기


# 입력 스트림과 출력 스트림을 연다

input = open("input.txt", "rt", encoding="utf-16")  

output = open("output.txt", "wt", encoding="utf-8")


# 유니코드 데이터 조각들을 스트리밍한다

with input, output:  

    while True:

        # 데이터 조각을 읽고

        chunk = input.read(4096)

        if not chunk:

            break

        # 수직 탭을 삭제한다

        chunk = chunk.replace("\u000B", "")

        # 데이터 조각을 쓴다

        output.write(chunk)



반응형
반응형

응용: 쉘 스크립트를 이용해 해당 디렉토리의 파일들 모두 변경 


- char-convert.sh

#!/bin/bash

 

LIST=`ls -A1 | grep ".csv"`

 

for file in $LIST

do

  python ./char-convert.py $file

done


- char-convert.py

#!/usr/bin/python

#-*- coding: utf-8 -*-

  

import codecs

import sys

 

file = sys.argv[1]

file2 = file.split('.csv')[0]+"-2.csv"

 

infile = codecs.open(file, 'r', encoding='utf-8')

outfile = codecs.open(file2, 'w', encoding='euc_kr')

  

for line in infile:

  line = line.replace(u'\xa0', ' ')  

  outfile.write(line)

    

infile.close()

outfile.close()


...

반응형

+ Recent posts