#! /usr/bin/python3
import os
os.environ[ 'TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.utils import np_utils
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img
from sklearn.model_selection import train_test_split
from PIL import Image
X = []
Y = []
# サンプル入力
for picture in list_pictures('./samle'):
img = img_to_array(load_img(picture, grayscale=True, target_size=(200,200)))
X.append(img)
Y.append(0)
# 参考情報入力
for picture in list_pictures('./reference'):
img = img_to_array(load_img(picture, grayscale=True, target_size=(200,200)))
X.append(img)
Y.append(1)
X = np.asarray(X)
Y = np.asarray(Y)
X = X.astype('float32')
X = X / 255.0
Y = np_utils.to_categorical(Y, 2)
indices = np.array(range(X.shape[0]))
# 学習用データとテストデータ
X_train, X_test, Y_train, Y_test, indices_train, indices_test = train_test_split(X, Y, indices, test_size=0.2, random_state=111)
print('X shape:', X.shape)
print('Y shape:', Y.shape)
print(X.shape[0], 'all samples') # すべてのサンプル数
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
print('Y_train shape:', Y_train.shape)
print('Y_test shape:', Y_test.shape)
print(X_train.shape[0], 'train samples') # 訓練サンプル数
print(X_test.shape[0], 'test samples') # テストサンプル数
#----------------------------------------------------------------------------------------------------------------------------------
#plt.imshow(X[100]) # 入力画像の例を表示
#plt.imshow(X_test[100].reshape([40, 40])) # 入力画像の例を表示
#plt.gray()
#print(X_train[100])
#print(X_test[100])
#print(Y_train[100])
#print(Y_test[100])
#---------------------------------------------------------------------------------------------------------------------------------
# CNNのモデルの作成
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1)))
model.add(Dropout(0.5))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.summary() # モデル情報の表示
#-------------------------------------------------------------------------------------------------------------------------------------
batch_size = 128 # バッチサイズ
nb_epoch = 10 # 繰り返し回数
#--------------------------------------------------------------------------------------------------------------------------------------
# 学習パラメータの設定
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
# モデルの学習
history = model.fit(X_train, Y_train,
batch_size=batch_size, epochs=nb_epoch,
validation_data=(X_test, Y_test))
# 学習結果の評価
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
2018年1月15日月曜日
2017年12月29日金曜日
lubuntuでupgradeできなくなるエラー(16.04.3 LTS)
sudo apt upgrade
を入力すると、
grub-pc (2.02~beta2-36ubuntu3.14) を設定しています ...
/var/lib/dpkg/info/grub-pc.config: 15: /etc/default/grub: GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true: not found
パッケージ grub-pc の処理中にエラーが発生しました
というエラーメッセージが表示される。
etc/defaut/grub中の
GRUB_DEFAULT=saved
GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true
の先頭にコメントアウトを下記のようにつけると、無事、upgradeできた。
#GRUB_DEFAULT=saved
#GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true
を入力すると、
grub-pc (2.02~beta2-36ubuntu3.14) を設定しています ...
/var/lib/dpkg/info/grub-pc.config: 15: /etc/default/grub: GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true: not found
パッケージ grub-pc の処理中にエラーが発生しました
というエラーメッセージが表示される。
etc/defaut/grub中の
GRUB_DEFAULT=saved
GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true
の先頭にコメントアウトを下記のようにつけると、無事、upgradeできた。
#GRUB_DEFAULT=saved
#GRUB_SAVEDEFAULT:GRUB_SAVEDEFAULT=true
2017年12月12日火曜日
2017年11月4日土曜日
2017年10月26日木曜日
Tensorflowでの警告メッセージの消し方
Tensorflowにおいて、スクリプトを実行すると、「CPU拡張命令セットが使えますよ」的なメッセージがでるので、それを消すためにはスクリプトに下記の命令を書いておく。
import os
os.environ[ 'TF_CPP_MIN_LOG_LEVEL'] = '2'
import os
os.environ[ 'TF_CPP_MIN_LOG_LEVEL'] = '2'
2017年10月17日火曜日
Tensorflow mnistデータの演習
参考ホームページから、下記コードをJupyter notebookにコピペして走らせてみる。
0
31
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
「得られた結果」
0
31
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
「得られた結果」
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting MNIST_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From D:\Users\shige\Anaconda3\lib\site-packages\tensorflow\python\util\tf_should_use.py:170: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
0.9169
参考リンク(MNIST for ML beginners)
2017年10月14日土曜日
2017年10月12日木曜日
Anacondaで異なる環境を立ち上げる方法
Anaconda Navigatorで真ん中上部のタブを「Not installed」にして、jupyter関連のプログラムをインストールする。そうすると、Environmentsの好きな環境のところをクリックすると「Open with JupyterNotebook」を選択できるようになる。
AnacondaへのTensorflowインストール(Windows)
Windows版アナコンダには、Tensorflowが入っていないので、JupyterNotebookから
import tensorflow as tf
と打つと、
ModuleNotFoundError: No module named 'tensorflow'と返される。
そこで、Anacondaのプログラムから「Anaconda Navigator」を立ち上げて、真ん中上部のタブ「installed」から「Not installed」を選ぶ。その後は、tensorflowにチェックをつけてapplyボタンを押す。
import tensorflow as tf
と打つと、
ModuleNotFoundError: No module named 'tensorflow'と返される。
そこで、Anacondaのプログラムから「Anaconda Navigator」を立ち上げて、真ん中上部のタブ「installed」から「Not installed」を選ぶ。その後は、tensorflowにチェックをつけてapplyボタンを押す。
登録:
投稿 (Atom)
