安装tensorflow与tensorflowjs并对应版本

pip install tensorflow

pip install tensorflowjs

>>import tensorflow

>>import tensorflowjs

如果没问题也没报错,证明安装好了

如果机器比较老,或者安装过程中一直报错,安装完后也无法使用(问题多的折磨人)

参考以下配置(测试好久发现下面的配置可以成功):

pip uninstall tensorflow

pip install tensorflow==1.5

对应的tensorflowjs版本:

pip install tensorflowjs==0.1.1

python版本:python3.6  64bit

安装好后,测试一个demo:

(这是经典的MNIST机器学习demo,用于识别手写数字,具体查看https://gogul09.github.io/software/digit-recognizer-tf-js)

import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.datasets import mnist
from keras.utils import np_utils
import tensorflowjs as tfjs

#固定随机种子的可重复性
np.random.seed(9)

#用户输入
nb_epoch            = 25
num_classes         = 10
batch_size          = 64
train_size          = 60000
test_size           = 10000
v_length            = 784
model_save_path     = "output/mlp"

#将mnist数据拆分为train并进行测试
(trainData, trainLabels), (testData, testLabels) = mnist.load_data()

#重塑和规模数据
trainData   = trainData.reshape(train_size, v_length)
testData    = testData.reshape(test_size, v_length)
trainData   = trainData.astype("float32")
testData    = testData.astype("float32")
trainData  /= 255
testData   /= 255

# 将类向量转换为二进制类矩阵——>一热编码
mTrainLabels  = np_utils.to_categorical(trainLabels, num_classes)
mTestLabels   = np_utils.to_categorical(testLabels, num_classes)

# 创造MLP model
model = Sequential()
model.add(Dense(512, input_shape=(v_length,)))
model.add(Activation("relu"))
model.add(Dense(256))
model.add(Activation("relu"))
model.add(Dropout(0.2))
model.add(Dense(num_classes))
model.add(Activation("softmax"))

# #编译模型
model.compile(loss="categorical_crossentropy",
              optimizer="rmsprop",
              metrics=["accuracy"])

# fit the model
history = model.fit(trainData, 
                    mTrainLabels,
                    validation_data=(testData, mTestLabels),
                    batch_size=batch_size,
                    nb_epoch=nb_epoch,
                    verbose=2)

# 评价 model
scores = model.evaluate(testData, mTestLabels, verbose=0)

# 打印结果
print ("[INFO] test score - {}".format(scores[0]))
print ("[INFO] test accuracy - {}".format(scores[1]))

# save tf.js specific files in model_save_path
tfjs.converters.save_keras_model(model, model_save_path)

运行结束:

安装tensorflow与tensorflowjs并对应版本_第1张图片

可以看到在录目中多出一个output文件夹:

安装tensorflow与tensorflowjs并对应版本_第2张图片

好了,tensorflow.js就可以完美的导入训练出来的库了

你可能感兴趣的:(python3,核心编程)