動かざることバグの如し

近づきたいよ 君の理想に

pandasでA column-vector y was passed when a 1d array was expected

環境

症状

適当に

model = RandomForestRegressor.fit(x_train, y_train)

とかしてると

DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)

って怒られる。先に進めなくてつらい

解決策

model.fit(x_train, y_train.values.ravel())

なんでこれで直るのかはまた今度 取り急ぎ

参考リンク

MySQLで取得した結果をCSVに出力する

自分用メモ

INTO OUTFILEを使う場合

MySQLサーバーがオンプレミスの場合はこっち

SELECT * FROM users INTO OUTFILE '/tmp/users.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';

スクリプト経由で出力する場合

クラウドのサーバーだと権限的にINTO OUTFILE使おうとすると

ERROR 1045 (28000): Access denied for user '{ユーザ名}'@'%' (using password: YES)

ってなる。つまり権限がない

そんなときはパイプを使う

mysql -h example.com -uuser -p mydatabase -e "select * from users" | sed -e 's/\t/","/g' > /tmp/users.csv

1セルごとに「"」で囲みたい場合は以下

mysql -h example.com -uuser -p mydatabase -e "select * from users" | sed -e 's/^/"/g' | sed -e 's/$/"/g' | sed -e 's/\t/","/g' > /tmp/users.csv

参考リンク

rubyで可変長引数を受け取るメソッドに配列で引数を渡す

常識すぎるのか、ググってもなかなか出てこなかったのでメモ

可変長引数とは

rubyでは仮引数名の頭に「*」をつけると可変長で受け取ることができる。

def myfunc(*args)
  p args
end

myfunc(1, "hello", true)
# => [1, "hello", true]

問題点

が、ここで配列をそのまま渡したらなんとかなるんじゃね?wとか思ってやってみたが、配列を1変数として受け取ってしまう(よく考えると当然である

myfunc([1, "hello", true])
# => [[1, "hello", true]]

解決策

渡す側にも「*」つけたらいけた

myfunc(*[1, "hello", true])
# => [1, "hello", true]

発端

そもそもこれを調べる理由として、RailsActiverecord

Post.all.pluck(:id,;title)

のようにするとそのカラムのデータだけ入った配列を取得できるので便利だったのだが、渡すカラム一覧をPost.column_namesのように配列で渡したかったって話

ソースコード見てもdef pluck(*keys) endだったのでこれでいけた

参考リンク

[ruby-list:45295] Re: メソッドの可変長引数に配列の全要素を渡したい

rails db:migrateでALTER TABLEする時は気をつけろという話

結論

    reversible do |direction|
      direction.up { execute "ALTER TABLE battles ADD PRIMARY KEY (id);" }
    end

環境

なぜつけるのか

railsマイグレーションでindexつけたりとか特殊なことをしようとするときはexecute()を使うこともあると思う。

が、db:migrateは成功するものの、

== 20180611044744 CreateBattles: migrating ====================================
-- create_table(:battles, {:id=>false})
   -> 0.1625s
-- execute("ALTER TABLE battles ADD PRIMARY KEY (id);")
   -> 0.2046s
== 20180611044744 CreateBattles: migrated (0.3674s) ===========================

db:rollbackで戻ろうとするとActiveRecord::IrreversibleMigrationでコケる。

== 20180611044744 CreateBattles: reverting ====================================
rails aborted!
StandardError: An error has occurred, all later migrations canceled:



This migration uses execute, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.


/db/migrate/20180611044744_create_battles.rb:43:in `change'
bin/rails:4:in `<main>'

Caused by:
ActiveRecord::IrreversibleMigration: 

This migration uses execute, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.


/db/migrate/20180611044744_create_battles.rb:43:in `change'
bin/rails:4:in `<main>'
Tasks: TOP => db:rollback
(See full trace by running task with --trace)

冒頭で書いたように、ちゃんとreversibleブロックの中で実行すると大丈夫 reversibleは可逆の意味

    reversible do |direction|
      direction.up { execute "ALTER TABLE battles ADD PRIMARY KEY (id);" }
    end

詳しくは以下

Active Record マイグレーション | Rails ガイド 3.9 reversibleを使用する

本来はdownも書くんだけど、今回はprymary keyの追加なので割愛

UbuntuでSVG対応のImageMagickをインストールする

以前にMacのときに以下のようなエラーになった。

thr3a.hatenablog.com

この時は問題が発生したのは手元のMacだけで、デプロイ先のUbuntuでは最初からSVG対応のImageMagickだったので問題なかった。

が、どうもUbuntu 18.04でapt経由でインストールするとSVG対応していない

# convert -version
Version: ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org
Copyright: © 1999-2017 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC Modules OpenMP 
Delegates (built-in): bzlib djvu fftw fontconfig freetype jbig jng jpeg lcms lqr ltdl lzma openexr pangocairo png tiff wmf x xml zlib

なんでやねん。。

解決方法

ビルドするしかない 基本的には公式サイトのドキュメント通りにやればおk

ここから好みのバージョンをダウンロード 今回は6.9を選択

wget https://www.imagemagick.org/download/ImageMagick-6.9.9-50.tar.gz
tar xvzf ImageMagick-6.9.9-50.tar.gz
cd ImageMagick

configure

 ./configure --disable-openmp --with-quantum-depth=8 --with-rsvg --disable-hdri

重要なのは--with-rsvg をつけること。あとは以下のサイトを参考に弱小マシンでの最適化を行った

ImageMagickを弱小鯖用にビルド&インストールする

make VPS 1coreで約七分

make

install

make install

確認 キタ━━━━(゚∀゚)━━━━!!

$ convert --version
Version: ImageMagick 6.9.9-50 Q8 x86_64 2018-06-09 https://www.imagemagick.org
Copyright: © 1999-2018 ImageMagick Studio LLC
License: https://www.imagemagick.org/script/license.php
Features: Cipher DPC 
Delegates (built-in): bzlib cairo djvu fontconfig freetype jbig jng jpeg lcms lqr lzma openexr png rsvg tiff wmf x xml zlib