Python3
from sklearn.metrics import silhouette_samples silhouette_samples で、Memory Error にならない関数を作ってくれている。 stackoverflow.com
matplotlib について、一回tutorial やったほうが良いかも Tutorials — Matplotlib 2.2.2 documentation
python-remrin.hatenadiary.jp
以下のコマンドで、取り出す。 mysql -uroot -N information_schema -e "select table_name from tables where table_schema = 'tablename' and table_name like 'prefix_%'" > table.txt
正解率が90%と低めに出た。。原因は今度調べよう import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) mnist.train.images.shape => (55000, 784) n_feat…
結構すごい。。表記ゆれとかも吸収できそう。 from gensim.models import word2vec ls = [] for row in df_id['review_comment'].values[:100000]: ls.append(_split_to_rawwords(row)) model = word2vec.Word2Vec(ls, size=500, window=5, min_count=5, wor…
レビューの分析方法をまとめる。 import os import glob import sys from datetime import (datetime, date, timedelta) import logging import re import shutil import tempfile import pandas as pd import numpy as np from scipy.sparse.csc import csc…
sparseな行列についての実装 import numpy as np from scipy.sparse import coo_matrix ) a = np.arange(30).reshape(10,3) print(a) [[ 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 25 26] [27 28 29]] b, c, d …
Building a Recommendation System in TensorFlow: Overview | Solutions | Google Cloud
applyとかassignとかpipeとかapplymapとか。numpyで対応していたところもあって知らなかった。 qiita.com stackoverflow.com stackoverflow.com
tab で 4 space 入れる方法。 #!/usr/bin/env python # -*- encoding:utf-8 -*- # vim:tabstop=4:shiftwidth=4:expandtab print('aaa') /* vim:set ts=4 sw=4 et ws is nowrap ft=java fenc=utf-8 ff=dos: */ class JSample13_1{ public static void main(St…
クラスタリングアルゴリズムの中で、クラスタが球状という前提を持たずに、 クラスタラベルを割り当てる。 from sklearn.datasets import make_moons X, y = make_moons( n_samples=200, noise=0.05, random_state=0 ) plt.scatter(X[:, 0 ], X[:, 1]) plt.t…
データ作成 shape: (5, 3) のランダム行列を作成 import pandas as pd import numpy as np np.random.seed(123) variables = ['X', 'Y', 'Z'] labels = ['ID_0', 'ID_1', 'ID_2', 'ID_3', 'ID_4'] X = np.random.random_sample([5, 3])*10 ## pandas のデー…
## クラスタリングのサンプルを作成 from sklearn.datasets import make_blobs X, y = make_blobs( n_samples=150, n_features=2, centers=3, cluster_std=0.5, shuffle=True, random_state=True ) ## クラスタリングを描画 plt.scatter(X[:, 0], X[:, 1], c…
一般的に、アンサンブル分類器の方が、個別の分類器より性能が高い from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import ( StandardScaler, LabelEncoder, ) iris = datasets.load_iris(…
以下の投稿で load したX_train, y_train,... を利用。 kidnohr.hatenadiary.com 適合率と再現率と F1 スコア 適合率(PRE)と再現率(REC)について、F1 スコアという性能指標が存在する。 PRE = TP / ( TP + FP ) REC = TP / ( TP + FN ) f1 = 2 * ( PRE *…
サポートベクトルマシンのパイプラインのトレーニング from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.model_selection import GridSearchCV …
make_pipelineを通して、(入力)=>(変換器(複数))=>(推定器)=>(出力) のwrapperを利用できる。 変換器は fit & transform 推定器は fit import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import Label…
次元削減で特徴抽出する方法を本から抜粋 df_wine = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None) from sklearn.ensemble import RandomForestClassifier feat_labels = df_wine.columns[1:] fore…
機械学習の結果、2 個の特徴の座標と分類結果をわかりやすく図で出力している import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def plot_dicision_regions(X, y, classifier, test_idx=None, resolusions…
tarfile はZipとは違うアプローチが必要 import tarfile workpath = '/tmp/test.tgz' filename = 'test1.tsv' with tarfile.open(workpath) as tfile: if filename not in tfile.getnames(): raise Exception('No such file %s' % filename) with tfile.extr…
以下の形式のsample.csvからデータを取得し、sklean の LDA でトピック抽出する。 id text 1 今日は晴れ。明日は雨 2 今日はカープが優勝した。 ... ... text2topic.py #!/usr/bin/env python # coding:utf-8 from __future__ import print_function from ti…
tfidfを用いてなにかできないかと模索。 結果、検索で引っかかつキーワードが出てきただけ。。 The Term Vector Component | Apache Solr Reference Guide 7.1 #!/usr/bin/env python # coding:utf-8 import requests import json from heapq import heappus…
djangoでtestをするとき、django-nose、coverageが使える。 $ pip install nose $ pip install django-nose $ pip install coverage settigns.py INSTALLED_APPS += ['django_nose', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--wi…
ファイルを書き出す manyrowstsv.py #!/usr/bin/env python # coding:utf-8 import signal import sys import os import glob import logging import logging.handlers import shutil import tempfile import random import datetime import string import c…
問題 s => t に最大量のデータを流す場合、最大どれだけのデータを送信できるか。 class MaxTraffic(object): def __init__(self, N=5): self.N = N self.edge = [[] for i in range(N)] self.used = [0 for i in range(N)] self.inf = 10 ** 9 def append(s…
面白い問題があったのでPythonで記載。 問題 1 N個の牛小屋について、M頭の牛を買っている。 x・・・牛小屋の位置 最も近い牛の間隔を最大化するためにどうするか 解法 最小・最大化問題について、収束判定するために二分探索が用いられるらしい --> 総当た…
stackoverflow.com
いまさら編集距離 (Levenshtein Distance) を実装するぜ | takuti.me
class MinimumSpanningTree(object): def __init__(self, v): self.v = v self.e = 0 self.mincost = [float("inf") for i in range(v)] self.cost = [[float("inf") for i in range(v)] for i in range(v)] self.used = [0 for i in range(v)] def append(s…