网络上有各种各样的win7 64bit安装theano的方法,我也试过好多,各种各样的问题。因为之前没了解过MinGw等东西,所以安装起来比较费劲,经过不断的尝试,最终我按照以下过程安装成功。
其实过程很简单,首先说一下安装条件:
- win10 (32和64都可以,下载安装包时一定要选择对应的)
- vs2010(不一定非要是vs2010,恰好我有vs2010,应该是配置GPU编程时需要用到vs的编译器)
- Anaconda(转到官方下载,打开之后稍微等一会就会出来下载链接了。之所以选择它是因为它内置了python,以及numpy、scipy两个必要库和一些其他库,比起自己安装要省事。至于版本随便选择了,如果想安装python3.4就下载对应的Anaconda3。本教程使用Anaconda,也就是对应的python2.7版本。安装过程无差别。)
安装过程:
一、卸载之前版本。
把之前单独安装的Python等统统卸载掉。学python的时候直接安装了python2.7,先把他卸载掉,因为Anaconda里边包含了python。
二、安装Anaconda。
这个超级简单,安装目录我用的是的 D:\Anaconda2 。这个特别要注意:安装路径千万不要有空格!!!血的教训
三、安装MinGw。
其他教程讲在环境变量中添加 path D:\Anaconda2\MinGW\bin;D:\Anaconda2\MinGW\x86_64-w64-mingw32\lib; ,但是你会发现 D:\Anaconda2\ 下面根本没有MinGw这个目录,所以最好的方法就是用命令安装,不需要自己下载什么mingw-steup.exe等。
安装方法:
- 打开CMD(注意是windows命令提示符,并不是进入到python环境下,否则会提示语法错误,因为conda命令就是在windows下面执行的。);
- 输入conda install mingw libpython,然后回车,会出现安装进度,稍等片刻即可安装完毕。此时就有D:\Anaconda2\MinGw目录了。
四、配置环境变量。
- 编辑用户变量中的path变量(如果没有就新建一个,一般会有的),在后边追加D:\Anaconda2;D:\Anaconda2\Scripts; 不要漏掉分号,此处因为我的Anaconda的安装目录是D:\Anaconda2,此处需要根据自己的安装目录填写。
- 在用户变量中新建变量pythonpath,变量值为D:\Anaconda2\Lib\site-packages\theano; ,此处就是指明安装的theano的目录是哪,但是现在咱们还没有安装,所以不着急,先写完再说。
- 打开cmd,会看到窗口里边有个路径,我的是C:\Users\Administrator>,根据自己的路径,找到对应的目录,在该目录下新建一个文本文档.theanorc.txt (注意有两个“.”),编辑它,写入以下内容:
[global]
openmp=False
[blas]
ldflags=
[gcc]
cxxflags=-ID:\Anaconda2\MinGW
其中红体字部分是你安装的Anaconda的路径,一定不要弄错。否则找不到MinGw。 - 最好重启一下电脑。
五、安装Theano。
不需要手动下载zip等压缩包,直接用命令安装最简单。
- 打开CMD,方法和安装MinGw一样,不要进入python。
- 输入pip install theano,回车后就是赏心悦目的下载进度条,这个很小,所以安装的比较快。
这里我的安装出现了pip命令不能识别的问题
Unable to create process using '""
暂时用 python -m pip install theano来代替了
- 在cmd中,输入python 进入到python环境下,然后先输入import theano回车,需要等一段时间。
- 继续输入theano.test()。又会输出好长一段信息,只要没有error就说明安装成功了。我安装时等了一段时间还在输出,我就ctrl+c退出了。(其实我发现,有部分error信息也没有关系,theano的功能也可以正常使用,包括theano.function(),所以如果有同学无论如何配置还是有error信息的话,可以暂时忽略掉,直接跑一段程序试一下,可以去测试一下卷积操作运算代码。
六、使用GPU
因为博主电脑是AMD的显卡,CUDA显然不支持,也不用想把GPU利用起来。
七、深度学习框架Keras
- 打开CMD,方法和安装MinGw一样,不要进入python。
- 输入pip install theano,回车后就是赏心悦目的下载进度条。
同样pip命令识别不了,用的 python -m pip install keras代替
注:在Anaconda Prompt中是识别pip命令的,上述两个pip命令也可以直接在这里面装,效果是一样的。
八、小例子
1、theano测试
from __future__ import print_function
"""
Created on Tue Aug 16 14:05:45 2016 @author: Administrator
""" """
This tutorial introduces logistic regression using Theano and stochastic
gradient descent. Logistic regression is a probabilistic, linear classifier. It is parametrized
by a weight matrix :math:`W` and a bias vector :math:`b`. Classification is
done by projecting data points onto a set of hyperplanes, the distance to
which is used to determine a class membership probability. Mathematically, this can be written as: .. math::
P(Y=i|x, W,b) &= softmax_i(W x + b) \\
&= \frac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}} The output of the model or prediction is then done by taking the argmax of
the vector whose i'th element is P(Y=i|x). .. math:: y_{pred} = argmax_i P(Y=i|x,W,b) This tutorial presents a stochastic gradient descent optimization method
suitable for large datasets. References: - textbooks: "Pattern Recognition and Machine Learning" -
Christopher M. Bishop, section 4.3.2 """ __docformat__ = 'restructedtext en' import six.moves.cPickle as pickle
import gzip
import os
import sys
import timeit import numpy import theano
import theano.tensor as T class LogisticRegression(object):
"""Multi-class Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W`
and bias vector :math:`b`. Classification is done by projecting data
points onto a set of hyperplanes, the distance to which is used to
determine a class membership probability.
""" def __init__(self, input, n_in, n_out):
""" Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch) :type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie :type n_out: int
:param n_out: number of output units, the dimension of the space in
which the labels lie """
# start-snippet-1
# initialize with 0 the weights W as a matrix of shape (n_in, n_out)
self.W = theano.shared(
value=numpy.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
)
# initialize the biases b as a vector of n_out 0s
self.b = theano.shared(
value=numpy.zeros(
(n_out,),
dtype=theano.config.floatX
),
name='b',
borrow=True
) # symbolic expression for computing the matrix of class-membership
# probabilities
# Where:
# W is a matrix where column-k represent the separation hyperplane for
# class-k
# x is a matrix where row-j represents input training sample-j
# b is a vector where element-k represent the free parameter of
# hyperplane-k
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) # symbolic description of how to compute prediction as class whose
# probability is maximal
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
# end-snippet-1 # parameters of the model
self.params = [self.W, self.b] # keep track of model input
self.input = input def negative_log_likelihood(self, y):
"""Return the mean of the negative log-likelihood of the prediction
of this model under a given target distribution. .. math:: \frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) =
\frac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|}
\log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\
\ell (\theta=\{W,b\}, \mathcal{D}) :type y: theano.tensor.TensorType
:param y: corresponds to a vector that gives for each example the
correct label Note: we use the mean instead of the sum so that
the learning rate is less dependent on the batch size
"""
# start-snippet-2
# y.shape[0] is (symbolically) the number of rows in y, i.e.,
# number of examples (call it n) in the minibatch
# T.arange(y.shape[0]) is a symbolic vector which will contain
# [0,1,2,... n-1] T.log(self.p_y_given_x) is a matrix of
# Log-Probabilities (call it LP) with one row per example and
# one column per class LP[T.arange(y.shape[0]),y] is a vector
# v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ...,
# LP[n-1,y[n-1]]] and T.mean(LP[T.arange(y.shape[0]),y]) is
# the mean (across minibatch examples) of the elements in v,
# i.e., the mean log-likelihood across the minibatch.
return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])
# end-snippet-2 def errors(self, y):
"""Return a float representing the number of errors in the minibatch
over the total number of examples of the minibatch ; zero one
loss over the size of the minibatch :type y: theano.tensor.TensorType
:param y: corresponds to a vector that gives for each example the
correct label
""" # check if y has same dimension of y_pred
if y.ndim != self.y_pred.ndim:
raise TypeError(
'y should have the same shape as self.y_pred',
('y', y.type, 'y_pred', self.y_pred.type)
)
# check if y is of the correct datatype
if y.dtype.startswith('int'):
# the T.neq operator returns a vector of 0s and 1s, where 1
# represents a mistake in prediction
return T.mean(T.neq(self.y_pred, y))
else:
raise NotImplementedError() def load_data(dataset):
''' Loads the dataset :type dataset: string
:param dataset: the path to the dataset (here MNIST)
''' #############
# LOAD DATA #
############# # Download the MNIST dataset if it is not present
data_dir, data_file = os.path.split(dataset)
if data_dir == "" and not os.path.isfile(dataset):
# Check if dataset is in the data directory.
new_path = os.path.join(
os.path.split(__file__)[0],
"..",
"data",
dataset
)
if os.path.isfile(new_path) or data_file == 'mnist.pkl.gz':
dataset = new_path if (not os.path.isfile(dataset)) and data_file == 'mnist.pkl.gz':
from six.moves import urllib
origin = (
'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
)
print('Downloading data from %s' % origin)
urllib.request.urlretrieve(origin, dataset) print('... loading data') # Load the dataset
with gzip.open(dataset, 'rb') as f:
try:
train_set, valid_set, test_set = pickle.load(f, encoding='latin1')
except:
train_set, valid_set, test_set = pickle.load(f)
# train_set, valid_set, test_set format: tuple(input, target)
# input is a numpy.ndarray of 2 dimensions (a matrix)
# where each row corresponds to an example. target is a
# numpy.ndarray of 1 dimension (vector) that has the same length as
# the number of rows in the input. It should give the target
# to the example with the same index in the input. def shared_dataset(data_xy, borrow=True):
""" Function that loads the dataset into shared variables The reason we store our dataset in shared variables is to allow
Theano to copy it into the GPU memory (when code is run on GPU).
Since copying data into the GPU is slow, copying a minibatch everytime
is needed (the default behaviour if the data is not in a shared
variable) would lead to a large decrease in performance.
"""
data_x, data_y = data_xy
shared_x = theano.shared(numpy.asarray(data_x,
dtype=theano.config.floatX),
borrow=borrow)
shared_y = theano.shared(numpy.asarray(data_y,
dtype=theano.config.floatX),
borrow=borrow)
# When storing data on the GPU it has to be stored as floats
# therefore we will store the labels as ``floatX`` as well
# (``shared_y`` does exactly that). But during our computations
# we need them as ints (we use labels as index, and if they are
# floats it doesn't make sense) therefore instead of returning
# ``shared_y`` we will have to cast it to int. This little hack
# lets ous get around this issue
return shared_x, T.cast(shared_y, 'int32') test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set) rval = [(train_set_x, train_set_y), (valid_set_x, valid_set_y),
(test_set_x, test_set_y)]
return rval def sgd_optimization_mnist(learning_rate=0.13, n_epochs=1000,
dataset='mnist.pkl.gz',
batch_size=600):
"""
Demonstrate stochastic gradient descent optimization of a log-linear
model This is demonstrated on MNIST. :type learning_rate: float
:param learning_rate: learning rate used (factor for the stochastic
gradient) :type n_epochs: int
:param n_epochs: maximal number of epochs to run the optimizer :type dataset: string
:param dataset: the path of the MNIST dataset file from
http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz """
datasets = load_data(dataset) train_set_x, train_set_y = datasets[0]
valid_set_x, valid_set_y = datasets[1]
test_set_x, test_set_y = datasets[2] # compute number of minibatches for training, validation and testing
n_train_batches = train_set_x.get_value(borrow=True).shape[0] // batch_size
n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] // batch_size
n_test_batches = test_set_x.get_value(borrow=True).shape[0] // batch_size ######################
# BUILD ACTUAL MODEL #
######################
print('... building the model') # allocate symbolic variables for the data
index = T.lscalar() # index to a [mini]batch # generate symbolic variables for input (x and y represent a
# minibatch)
x = T.matrix('x') # data, presented as rasterized images
y = T.ivector('y') # labels, presented as 1D vector of [int] labels # construct the logistic regression class
# Each MNIST image has size 28*28
classifier = LogisticRegression(input=x, n_in=28 * 28, n_out=10) # the cost we minimize during training is the negative log likelihood of
# the model in symbolic format
cost = classifier.negative_log_likelihood(y) # compiling a Theano function that computes the mistakes that are made by
# the model on a minibatch
test_model = theano.function(
inputs=[index],
outputs=classifier.errors(y),
givens={
x: test_set_x[index * batch_size: (index + 1) * batch_size],
y: test_set_y[index * batch_size: (index + 1) * batch_size]
}
) validate_model = theano.function(
inputs=[index],
outputs=classifier.errors(y),
givens={
x: valid_set_x[index * batch_size: (index + 1) * batch_size],
y: valid_set_y[index * batch_size: (index + 1) * batch_size]
}
) # compute the gradient of cost with respect to theta = (W,b)
g_W = T.grad(cost=cost, wrt=classifier.W)
g_b = T.grad(cost=cost, wrt=classifier.b) # start-snippet-3
# specify how to update the parameters of the model as a list of
# (variable, update expression) pairs.
updates = [(classifier.W, classifier.W - learning_rate * g_W),
(classifier.b, classifier.b - learning_rate * g_b)] # compiling a Theano function `train_model` that returns the cost, but in
# the same time updates the parameter of the model based on the rules
# defined in `updates`
train_model = theano.function(
inputs=[index],
outputs=cost,
updates=updates,
givens={
x: train_set_x[index * batch_size: (index + 1) * batch_size],
y: train_set_y[index * batch_size: (index + 1) * batch_size]
}
)
# end-snippet-3 ###############
# TRAIN MODEL #
###############
print('... training the model')
# early-stopping parameters
patience = 5000 # look as this many examples regardless
patience_increase = 2 # wait this much longer when a new best is
# found
improvement_threshold = 0.995 # a relative improvement of this much is
# considered significant
validation_frequency = min(n_train_batches, patience // 2)
# go through this many
# minibatche before checking the network
# on the validation set; in this case we
# check every epoch best_validation_loss = numpy.inf
test_score = 0.
start_time = timeit.default_timer() done_looping = False
epoch = 0
while (epoch < n_epochs) and (not done_looping):
epoch = epoch + 1
for minibatch_index in range(n_train_batches): minibatch_avg_cost = train_model(minibatch_index)
# iteration number
iter = (epoch - 1) * n_train_batches + minibatch_index if (iter + 1) % validation_frequency == 0:
# compute zero-one loss on validation set
validation_losses = [validate_model(i)
for i in range(n_valid_batches)]
this_validation_loss = numpy.mean(validation_losses) print(
'epoch %i, minibatch %i/%i, validation error %f %%' %
(
epoch,
minibatch_index + 1,
n_train_batches,
this_validation_loss * 100.
)
) # if we got the best validation score until now
if this_validation_loss < best_validation_loss:
#improve patience if loss improvement is good enough
if this_validation_loss < best_validation_loss * \
improvement_threshold:
patience = max(patience, iter * patience_increase) best_validation_loss = this_validation_loss
# test it on the test set test_losses = [test_model(i)
for i in range(n_test_batches)]
test_score = numpy.mean(test_losses) print(
(
' epoch %i, minibatch %i/%i, test error of'
' best model %f %%'
) %
(
epoch,
minibatch_index + 1,
n_train_batches,
test_score * 100.
)
) # save the best model
with open('best_model.pkl', 'wb') as f:
pickle.dump(classifier, f) if patience <= iter:
done_looping = True
break end_time = timeit.default_timer()
print(
(
'Optimization complete with best validation score of %f %%,'
'with test performance %f %%'
)
% (best_validation_loss * 100., test_score * 100.)
)
print('The code run for %d epochs, with %f epochs/sec' % (
epoch, 1. * epoch / (end_time - start_time)))
print(('The code for file ' +
os.path.split(__file__)[1] +
' ran for %.1fs' % ((end_time - start_time))), file=sys.stderr) def predict():
"""
An example of how to load a trained model and use it
to predict labels.
""" # load the saved model
classifier = pickle.load(open('best_model.pkl')) # compile a predictor function
predict_model = theano.function(
inputs=[classifier.input],
outputs=classifier.y_pred) # We can test it on some examples from test test
dataset='mnist.pkl.gz'
datasets = load_data(dataset)
test_set_x, test_set_y = datasets[2]
test_set_x = test_set_x.get_value() predicted_values = predict_model(test_set_x[:10])
print("Predicted values for the first 10 examples in test set:")
print(predicted_values) if __name__ == '__main__':
sgd_optimization_mnist()
2、Keras测试
'''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
''' from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils batch_size = 128
nb_classes = 10
nb_epoch = 12 # input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
nb_pool = 2
# convolution kernel size
nb_conv = 3 # the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes) model = Sequential() model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode='valid',
input_shape=(1, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
model.add(Dropout(0.25)) model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy']) model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, 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])
参考链接:
2. 小白Windows7/10 64Bit安装Theano并实现GPU加速(没有MinGw等,详细步骤)
3. https://bitbucket.org/pypa/distlib/issues/47/exe-launcher-fails-if-there-is-a-space-in
4. http://*.com/questions/24627525/fatal-error-in-launcher-unable-to-create-process-using-c-program-files-x86/26428562#26428562
5. Theano 安装教程
6. Installation of Theano on Windows
7. http://*.com/questions/33687103/how-to-install-theano-on-anaconda-python-2-7-x64-on-windows?noredirect=1&lq=1
8. Keras官方教程
9. Theano官方教程