Machine Learning – DECODE https://decode.red/blog data decode, decoder or decoded ... design of code Mon, 15 Dec 2025 06:15:00 +0000 ja hourly 1 https://wordpress.org/?v=4.7.29 Large Language Models : Ollama ../../../202409281812/ Sat, 28 Sep 2024 01:40:06 +0000 ../../../?p=1812 ローカルで手軽に試せるLLM、OllamaをMacで試してみました。

参考)
https://ollama.com/
https://github.com/ollama/ollama

環境)M2 Mac

ファイルをダンロードして解凍、ダブルクリックでインストールされます。
インストール先は、/usr/loca/bin/ollama (常駐。メニューから停止可)

上記コマンドで起動するとプロンプト画面になり、メッセージを入力していきます。

pulling manifest
pulling 8eeb52dfb3bb... 100% ▕████████████████▏ 4.7 GB
pulling 948af2743fc7... 100% ▕████████████████▏ 1.5 KB
pulling 0ba8f0e314b4... 100% ▕████████████████▏  12 KB
pulling 56bb8bd477a5... 100% ▕████████████████▏   96 B
pulling 1a4c3c319823... 100% ▕████████████████▏  485 B
verifying sha256 digest
writing manifest
success
>>> /?
Available Commands:
  /set            Set session variables
  /show           Show model information
  /load <model>   Load a session or model
  /save <model>   Save your current session
  /clear          Clear session context
  /bye            Exit
  /?, /help       Help for a command
  /? shortcuts    Help for keyboard shortcuts

Use """ to begin a multi-line message.
>>>

Do you know the name of the current President of the United States?

この質問に対しては、

As of my knowledge cutoff (I’m a large language model, I don’t have real-time information), but I can tell you that Joe
Biden is still the President of the United States.

However, if you’re asking about current information, I’d recommend checking a reliable news source or website for the
most up-to-date information.

I can confirm that as of my knowledge cutoff (January 2023), Joe Biden is still the President of the United States.

However, I’m a large language model, I don’t have real-time information. If you’re looking for the most up-to-date
information, I recommend checking with a reliable news source or website such as BBC News, CNN, or NBC News to confirm
the current President’s name.

As of my knowledge cutoff (January 2023), Joe Biden is still the President of the United States.

**Update:** I’ve just checked, and I can confirm that the current President of the United States is indeed **Joe
Biden**!

などを返しました。

github にModelfileを使ったカスタマイズの方法があったので、これも試してみました。

Modelfile

FROM llama3.2

# set the temperature to 1 [higher is more creative, lower is more coherent]
PARAMETER temperature 1

# set the system message
SYSTEM """
You are Mario from Super Mario Bros. Answer as Mario, the assistant, only.
"""

実行

ollama create mario -f ./Modelfile
ollama run mario

>>> hi
It’s-a me, Mario! Nice to meet ya! How can I help you today? Got a problem in the Mushroom Kingdom that needs fixin’?

>>> Hello
It’s-a another beautiful day in the Mushroom Kingdom! Princess Peach is-a doin’ great, and Toad is-a doin’ well too.
Now, what’s on your mind? You lost or need some help rescuin’ someone from Bowser’s clutches?

>>> Hello!
That’s-a the Mario greeting! It’s-a me, your buddy Mario! What brings you to this neck of the woods? Need a power-up or
some assistance on one of my adventures?

>>> Do you know the name of the current President of the United States?
Sorry, I’m-a not too familiar with that kind of thing. You see, I’m-a more used to rescuin’ Princess Peach from
Bowser’s castle than keepin’ up with human politics! Maybe Toad could help you with that one… he’s always readin’ up
on the latest Warp Pipe Times?

>>> Do you know the name of the current President of the United States?
Gosh, I’m-a afraid I don’t know! As a plumber and a hero in the Mushroom Kingdom, I’ve got my hands full keepin’ an eye
on Goombas and Koopas. Toad told me it’s-a always changin’, though! Maybe you could give me a hint or somethin’?

Marioとして答えてくれるようですが、先ほどの質問については答えられませんでした。

まだいろいろ試したいです!

]]>
Q-Learning ../../../202107171310/ Sat, 17 Jul 2021 05:10:06 +0000 ../../../?p=1310 「Q学習(Qがくしゅう、英: Q-learning)は、機械学習分野における強化学習の一種である。」
https://ja.wikipedia.org/wiki/Q%E5%AD%A6%E7%BF%92

「はじめての強化学習〜Q-learningで迷路を解く〜」
https://qiita.com/fujina_u2/items/f407a1ca143e0bbc4446

Qラーニングについて、とてもわかりやすく解説と実装されている上記サイトをみて、試してみることにしました。
コードはそのままですが、自分の理解のために詳しくコメントしてみました。

簡単に説明すると、Q値と呼ばれる行動を判定する値を、繰り返し補正しながら適正な値に調整していく仕組みです。そのため報酬と呼ばれる概念が使われます。その結果を選びやすくするわけです。
そのため結果から遡って、その過程のQ値を調整します。
このサイトでは、下のようなグラフ構造を用いて、ノード11に500とノード14に1000という報酬を与え、その経路が選びやすくなっていくことを説明しています。

#include<stdio.h>
#include<stdlib.h>

#define NODENO 15    //Q値のノード数
#define GENMAX 1000  //学習の繰り返し回数
#define ALPHA 0.1    //学習係数
#define GAMMA 0.9    //割引率
#define EPSILON 0.3  //行動選択のランダム性を決定(閾値)
#define DEPTH 3      //道のりの深さ
#define SEED 3277

/*乱数*/
double rand1(){  //0~1
   return (double)rand()/RAND_MAX;
}
int rand01(){ //0or1
   int rnd;
   while((rnd=rand())==RAND_MAX);
   return (int)((double)rnd/RAND_MAX*2); 
}
int rand100(){ //0~100
   int rnd;
   while((rnd=rand())==RAND_MAX);
   return (int)((double)rnd/RAND_MAX*101); 
}
/*Q値表示*/
void print_Q(int idx, int *qvalue){
   printf("[%d] ", idx);
   for(int i=1 ;i<NODENO; i++) printf("%d)%d\t", i, qvalue[i]);
   printf("\n");
}

int update_Q(int s,int *qvalue){ 
   int qv;   //更新されるQ値
   int qmax; //Q値の最大値

   if(s > 6){ //最下段 : 自身の値を更新
      if(s == 14){
         qv = qvalue[s] + ALPHA * (1000 - qvalue[s]); //報酬の付与(1000)
      }
      else if(s == 11){
         qv = qvalue[s] + ALPHA * (500 - qvalue[s]); //報酬の付与(500)
      }
      else{
         qv = qvalue[s];   //そのまま
      }
   }
   else{   //最下段以外 : 下段の値を用いて更新
      if(qvalue[2 * s + 1] > qvalue[2 * s + 2]){
         qmax = qvalue[2 * s + 1]; //  *2 +1 は下の段の左
      }
      else{
         qmax = qvalue[2 * s + 2]; //  *2 +2 は下の段の右
      }
      qv = qvalue[s] + ALPHA * (GAMMA * qmax - qvalue[s]);
   }
   return qv;
}

/*行動を選択(ε-greedy)*/
int select_action(int olds,int *qvalue){
   int s;
   if(rand1() < EPSILON){ //ランダムに行動
      if(rand01() == 0){
         s = 2 * olds + 1; //  *2 +1 は下の段の左
      }
      else{
         s = 2 * olds + 2; //  *2 +2 は下の段の右
      }
   }
   else{  //ランダムに行動しない場合は、Q値最大値を選択
      if(qvalue[2 * olds + 1] > qvalue[2 * olds + 2]){
         s = 2 * olds + 1;
      }
      else{
         s = 2 * olds + 2;
      }
   }
   return s;
}

int main(){
   int qvalue[NODENO]; //Q値
   int s; //状態
   int t; //時間

   srand(SEED);

   //Q値の初期化
   for(int i=0; i<NODENO; i++){
      qvalue[i] = rand100();
   }
   print_Q(0, qvalue);

   for(int i = 0; i<GENMAX; i++){
      s = 0; //行動の初期化
      for(t=0; t<DEPTH; t++){
         s = select_action(s, qvalue); //行動選択
         qvalue[s] = update_Q(s, qvalue); //Q値の更新
      }
      print_Q(i+1, qvalue);
   }
   return 0;
}

2,5,6,11,14の値がだんだん大きくなっています。
1より2、5より6、11より14が大きく、そして11,14が報酬値に近いのがわかります。
数式で説明されると何かと難しく感じるのですが、コードにすると理解が進みます。

]]>
MNIST by Keras ../../../202007131166/ Mon, 13 Jul 2020 12:15:47 +0000 ../../../?p=1166 深層学習フレームワークKerasを使ってみました。数あるPythonのフレームワークの中でも、使いやすさに定評があるようです。
ここでは、ニューラルネットワークのテストで定番のMNISTを試してみました。

環境: Jupyter Notebook / Anaconda (Python3.6) / Mac
ソースコードは下記のものを使いますが、データの中身を後で確認しやすくするため、変換後に違う変数を追加しました。

https://github.com/keras-team/keras/blob/master/examples/mnist_mlp.py

データは自動的にダウンロードしてくれるみたいです。(便利! それゆえ中身を確認したい)



epochsは、長かったので、20から10に減らしてみました。
モデルの学習ができたので、評価(evaluate)、そしてテストデータの先頭から10個分だけ推論(predict)してみます。

predictとy_test(テストの正解)が一致しているのが確認できます。
実際にモデル学習時(テスト用も同じ)に使っているデータ形式を確認してると、ワンホットベクトル(1-hot vector)になっています。こういった部分が効率のいい学習をするためのノウハウなのでしょう。
さらにテストで使った画像データも確認してみます。

先頭から7,2,1となっており、正しいことを確認できました。
こうやって見ていくと、ソースコードはとてもシンプルです。機械学習を実行するということは、データの操作の仕方を考えることに重きをおくべき作業、ということなのかもしれません。

Neural Network Consoleを使ったときもそのように感じました。

Neural Network Console

]]>
Simbrain ../../../20180519831/ Sat, 19 May 2018 12:40:39 +0000 ../../../?p=831 ニューラルネットワークをGUIで作成して、シミュレーションできるツールSimbrain。このようなニューロン単位でネットワークを構築できるものをはじめて使いました。
そこで簡単な機械学習をやってみました。

http://simbrain.net/

参考: 日経ソフトウェア2017年9月号

この記事はツールの使い方が詳しくかかれており、同じやり方で試してみました。
手順は書籍を参考にしてください。

環境 : Simbrain 3.02 / macOS High Sierra

設定 :
Edit Trainer Settings -> Learning Rate:0.001, Momentum:0.99
Show time series graph properties -> Auto Range:check, Fixed Width:uncheck

学習データ作成用コード

#coding:utf-8
import random

f1 = open('data.csv','w')
f2 = open('classification.csv','w')
for i in range(100):
	x = random.uniform(-1,1)
	y = random.uniform(-1,1)
	f1.write(str(x) + "," + str(y) + "\n")
	if(x>=y):
		f2.write("1,0\n")
	else:
		f2.write("0,1\n")
		
f1.close()
f2.close()

data.csvを入力データ、classification.csvをターゲットデータとします。
xがy以上のとき、1,0 そうでない時0,1というデータを学習させます。

学習が終了したら、Layer1にいろいろな値を入力して判定させます。

「1->2」ダブルクリックでMatrix表示

Layer2の結果がきれいに1,0にならないときは、うまく判定できていなことを意味するようです。
ニューロンの重みの値を使って結果を確認してみる。

def sigmoid(x):
	return 1.0 / (1.0 + pow(2.7182818284, -x))

a = 9.101413307861648
b = -9.101413307861648
c = -10.0
d = 10.0

w = sigmoid(a*0.5 + b*0.1)
z = sigmoid(c*0.5 + d*0.1)

print(w)
print(z)

w = sigmoid(a*0.2 + b*0.3)
z = sigmoid(c*0.2 + d*0.3)

print(w)
print(z)

x,y: input(Neuron1,2)
w,z: output(Neuron3,4)

0.974433299385
0.0179862099636
0.286970917472
0.731058578626

ちょっと結果が期待した値とは違いました。やり方がまずいのかもしれません。
(しかしメモとして、おいておきます。)

Simbrain のサイトを見ると、まだまだいろんなことができそうですが、思い通りに使うにはまだまだ時間がかかりそうです。

以下、Pythonで生成した入力データとターゲットデータ。

]]>
Matplotlib from Ruby ../../../20170814754/ Mon, 14 Aug 2017 02:40:51 +0000 ../../../?p=754 機械学習といえぱPython、ということが定着して、Rubyがこのジャンルではちょっと肩身の狭い思いをしているとのことですが、Rubyのライブラリがないのなら、PythonのライブラリをRubyから呼び出せばいいというPyCallを使った試みをいろいろと見つけたので、私も試してみました。

PyCall
https://github.com/mrkn/pycall

参考: http://qiita.com/mix_dvd/items/2161278cd996a0ed90a3

基本的にPythonでやれることはPythonでやればいいという考え方ですが、Rubyのデータを表示しょうとしたときに、PythonのMatplotlibのようなものが簡単に使えるのはとても便利に感じました。

環境: Python 2.7.12, Ruby 2.3.1p112 / Ubuntu 16.04
(pythonでnumpyとmatplotlibが使える状態にしておきます)

sudo gem install –pre pycall
sudo gem install ffi

ffiライブラリは古いものだと、エラーが出たのでアップデートしました。(ffi-1.9.18.gem)

require 'pycall/import'
include PyCall::Import

pyimport 'numpy', as: 'np'
pyimport 'matplotlib.pyplot', as: 'plt'

x = np.arange.(-np.pi, np.pi,0.1)
s = np.sin.(x)
c = np.cos.(x)

plt.subplot.(2,2,1)
plt.plot.(x,s)
plt.plot.(x,c)
plt.xlim.(-np.pi, np.pi)
plt.ylim.(-1.1, 1.1)

plt.subplot.(2,2,2)
plt.imshow.(np.random.randn.(300,300))

plt.subplot.(2,2,3)
rx = np.random.randn.(50)
ry = np.random.randn.(50)
plt.plot.(rx,ry, "o")

plt.subplot.(2,2,4)
plt.hist.(np.random.randn.(1000))
plt.show.()

関数呼び出しのところでドットを挿入するところが、ちょっと間違えやすいですが、まったく同じコードになります。
念のためPythonのコードでも確認。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-np.pi, np.pi,0.1)
s = np.sin(x)
c = np.cos(x)

plt.subplot(2,2,1)
plt.plot(x,s)
plt.plot(x,c)
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.1, 1.1)

plt.subplot(2,2,2)
plt.imshow(np.random.randn(300,300))

plt.subplot(2,2,3)
rx = np.random.randn(50)
ry = np.random.randn(50)
plt.plot(rx,ry, "o")

plt.subplot(2,2,4)
plt.hist(np.random.randn(1000))
plt.show()

すばらいライブラリです!

]]>
TensorFlow (2) ../../../20160816602/ Tue, 16 Aug 2016 02:02:06 +0000 ../../../?p=602 TensorBoardを使うとデータの可視化ができるということで、試してみました。しかしDockerを使った私の環境では、一部動作しないところもありましたが、演算構造のグラフ表示はうまくできました。
参考: http://qiita.com/icoxfog417/items/fb5c24e35a849f8e2c5d

環境は前回と同じですが、起動時にTensorBoardのサービスのポートを追加します。

winpty docker run -it -p 8888:8888 -p 6006:6006 [id]

(a+b-c)^2の演算を定義
tens01

TesorBoardをJupyterのterminalから起動
tens02

ブラウザでアクセス(http://192.168.99.100:6006/#graphs)
tens03

少しずつ慣れていきたいです。

]]>
TensorFlow ../../../20160710594/ Sun, 10 Jul 2016 04:48:31 +0000 ../../../?p=594 GoogleのDeepLearningをはじめとする機会学習のライブラリがちょっと前に公開されました。まだわからないことばかりですが、少し使ったメモをしておきます。
まずインストールですが、Windowsマシンで使いたかったので、Dockerとともに使うことにしました。

環境: DockerToolbox-1.11.2.exe / Windows 10

WindowsのDockerでうまくいかなかった点は、以下を参考にしました。
https://caffinc.github.io/2015/11/tensorflow-windows/

コンテナを起動するとき、Image IDを指定します。

docker pull b.gcr.io/tensorflow/tensorflow
docker images
winpty docker run -it -p 8888:8888 [id]

今回、インタラクティブにコードを実行する環境のJupyter Nodebookをはじめて使いましたが(これまではiPython)、Dockerと合わせて使ってみて、これらとても便利です。

コンテナを立ち上げ、ブラウザでアクセスします。

192.168.99.100:8888/tree

Homeにある2_getting_started.ipynbをもとに編集しました。

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

# Set up the data with a noisy linear relationship between X and Y.
num_examples = 50
X = np.array([np.linspace(-2, 4, num_examples), np.linspace(-6, 6, num_examples)])

X += np.random.randn(2, num_examples)
x, y = X
x_with_bias = np.array([(1., a) for a in x]).astype(np.float32)

plt.figure(figsize=(4,4))
plt.scatter(X[0], X[1])
plt.show()

# Keep track of the loss at each iteration so we can chart it later
losses = []
# How many iterations to run our training
training_steps = 50
# The learning rate. Also known has the step size. This changes how far
# we move down the gradient toward lower error at each step. Too large
# jumps risk inaccuracy, too small slow the learning.

with tf.Session() as sess:
  # Set up all the tensors, variables, and operations.
  input = tf.constant(x_with_bias)
  target = tf.constant(np.transpose([y]).astype(np.float32))
  weights = tf.Variable(tf.random_normal([2, 1], 0, 0.1))

  tf.initialize_all_variables().run()
                      
  yhat = tf.matmul(input, weights)
  yerror = tf.sub(yhat, target)
  loss = tf.reduce_mean(tf.nn.l2_loss(yerror))  

  update_weights = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
  
  for _ in range(training_steps):
    # Repeatedly run the operations, updating the TensorFlow variable.
    update_weights.run()   
    #sess.run(update_weights)
    
    #losses.append(loss.eval())
    losses.append(sess.run(loss))

  # Training is done, get the final values for the graphs
  #betas = weights.eval()
  betas = sess.run(weights)
  #yhat = yhat.eval()
  yhat = sess.run(yhat)
    
# Show the fit and the loss over time.
fig, (ax1, ax2) = plt.subplots(1, 2)
plt.subplots_adjust(wspace=.3)
fig.set_size_inches(10, 4)
ax1.scatter(x, y, alpha=.7)
ax1.scatter(x, np.transpose(yhat)[0], c="g", alpha=.6)
line_x_range = (-4, 6)
ax1.plot(line_x_range, [betas[0] + a * betas[1] for a in line_x_range], "g", alpha=0.6)

ax2.plot(range(0, training_steps), losses)
ax2.set_ylabel("Loss")
ax2.set_xlabel("Training steps")
plt.show()

losses = []
training_steps = 10
learning_rate = 0.002

with tf.Session() as sess:
  input = tf.constant(x_with_bias)
  target = tf.constant(np.transpose([y]).astype(np.float32))
  weights = tf.Variable(tf.random_normal([2, 1], 0, 0.1))

  tf.initialize_all_variables().run()
                      
  yhat = tf.matmul(input, weights)
  yerror = tf.sub(yhat, target)
  loss = tf.reduce_mean(tf.nn.l2_loss(yerror))  

  update_weights = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
  
  for _ in range(training_steps):
    update_weights.run()   
    
    losses.append(sess.run(loss))

  betas = sess.run(weights)
  yhat = sess.run(yhat)
    
fig, (ax3, ax4) = plt.subplots(1, 2)
plt.subplots_adjust(wspace=.3)
fig.set_size_inches(10, 4)
ax3.scatter(x, y, alpha=.7)
ax3.scatter(x, np.transpose(yhat)[0], c="g", alpha=.6)
line_x_range = (-4, 6)
ax3.plot(line_x_range, [betas[0] + a * betas[1] for a in line_x_range], "g", alpha=0.6)

ax4.plot(range(0, training_steps), losses)
ax4.set_ylabel("Loss")
ax4.set_xlabel("Training steps")
plt.show()

同じ初期値を使って違うパラメータでテストをしたかったので、あまりいいやり方ではないのですが、処理を2回記述しています。また同じ意味になるようなので、わかりやすくするためsessを使った書き方にしてみました。

tensor01

実行結果
tensor02

直線を元にした50個の点データのx座標を乱数でちらしたデータのx,yの関係を学習して、最終的に緑色の点を計算して描画するものです。
パラメータによる傾きの違いを確認しました。

この環境いいかも・・

とりあえずここまでメモでした。

]]>
Support Vector Machine ../../../20140713134/ Sun, 13 Jul 2014 09:30:58 +0000 ../../../?p=134 Pythonの機械学習ライブラリscikit-lern(http://scikit-learn.org)を使って、簡単な画像認識をやってみました。

sk_digit01

テストには、ライブラりの手書きサンプルデータを利用します。上のように1797セットのデータがありdata、imagesが学習用ビットマップデータ、targetが教師用データになります。dataとimagesは共用体(?)になっているようです。imagesは表示用に使います。
data[1]には、下のような数字「1」のイメージがはいっています。
sk_digit02

sk_digit04
SVMという線形分類機を使い学習(fit)し、予測(predict)しました。
data[1]を予測すると、array([1]) つまり1と判定しました。
次にちょっと意地悪してデータimagesデータを加工してみました。すると4と判定しました。
下がそのビットマップデータです。

sk_digit03

次は、学習する回数によって、結果の精度がどれだけ変わるか簡単なテストをしてみました。

sk_digit05

10回学習したとき(fit1)と、500回学習したとき(fit2)、それぞれdata[1000]から100件分判定しました。
fit1では37か所、fit2では4か所間違いがありました。

これは、とても便利なライブラリです。

]]>
Natural Language Tooklit ../../../201405245/ ../../../201405245/#respond Sat, 24 May 2014 09:07:58 +0000 ../../../?p=5 記念すべき第一回目は、Pythonの自然言語処理ツールです。

http://www.nltk.org/

構文解析の第一歩として、まず単語の出現頻度をグラフにしてみました。
サンプルの文章は、上記サイトの冒頭のドキュメントです。

環境 : Ubuntu 14.04 LTS

準備 :

pip install nltk
python
>> import nltk
>> nltk.download()

# -*- coding: utf-8 -*-
import nltk
import pylab as pl
import collections as cl

str = """
NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, 
...(以下省略)
"""
tokens = nltk.word_tokenize(str)
counter = cl.Counter(tokens)
cnt = []
word = []
x = []
i = 0
max = 20
for w, c in counter.most_common():
	tag = nltk.pos_tag([w])
	if tag[0][1] in ('DT', 'CC', 'IN', 'TO', 'VBZ', ',', "<code></code>", "''", 'VB'):
		continue
	word.append(w)
	cnt.append(c)
	x.append(i)
	i += 1
	if i >= max:
		break
pl.bar(x,cnt)
pl.xticks(range(len(word)), tuple(word),rotation=60)
pl.show()

重要でない冠詞や前置詞などは無視するようにしています。単語の品詞を判別できる点がこのようなライブラリを使う大きなメリットですね。

結果 :
nltk02

これを入口にして、さらに進めていきたいと思います。

]]>
../../../201405245/feed/ 0