Keras安装配置
Keras是一个用于深度学习的高级神经网络库,可以快速搭建深度学习模型。Keras可以使用TensorFlow、CNTK或Theano作为后端,支持Python 2.7、3.5和3.6,支持GPU和CPU。
要安装Keras,需要安装Python,使用pip安装Keras:
pip install keras
安装完成后,可以使用Python环境中的Keras API来构建深度学习模型:
from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(units=64, activation='relu', input_dim=100)) model.add(Dense(units=10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5, batch_size=32)
要使用Keras的GPU加速功能,还需要安装GPU驱动,安装完成后,可以在Keras中使用GPU:
import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) from keras.backend.tensorflow_backend import set_session set_session(sess)
TensorFlow安装配置
TensorFlow是一个开源的机器学习框架,支持Python、C++、Java等多种语言,可以用于构建和训练深度学习模型。
要安装TensorFlow,可以使用pip安装:
pip install tensorflow
安装完成后,可以使用TensorFlow提供的API来构建深度学习模型:
import tensorflow as tf # 定义输入和输出 x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) # 构建网络 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b # 定义损失函数和优化器 cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 训练模型 sess = tf.InteractiveSession() tf.global_variables_initializer().run() for _ 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}))
要使用TensorFlow的GPU加速功能,还需要安装GPU驱动,安装完成后,可以在TensorFlow中使用GPU:
import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config)