在Anaconda中的安装Kersa,Tensorflow,之后导入Pycharm中,并给出一个简单的实例演示

一、关于 Kersa,Tensorflow 在Anaconda中的安装

打开Anaconda Prompt,下图红色框中

在这里插入图片描述

在打开的终端中依次输入以下代码

# 1-升级pip
pip -m pip install --upgrade pip -i https://pypi.douban.com/simple
# 2-新建虚拟环境
conda create -n news python=3.6
# news是虚拟环境的名称,可以根据自己需要修改
# 3-激活/进入创建的虚拟环境
activate news
# 以后在news环境中需要在终端中新添加库或者更新的话,都要用上面这个代码先进入这个虚拟环境中
# 4-依次下载tensorflow以及keras
pip install tensorflow==1.15.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install keras==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple

最后看到success,表示安装成功。

二、将安装后的虚拟环境导入进Pycharm中

1.在打开的Pycharm中,右下角,进入解释器设置。

在这里插入图片描述

2.添加本地解释器

在这里插入图片描述

3.选择conda环境

在这里插入图片描述
注意:我这个是添加好了的,第一次添加应该是只有第一行的,这时候在你自己下载好的Anaconda文件夹里,envs这个文件夹里找到你刚刚建立的news环境的路径,导入,应用。

三、一个实列Kersa、Tensorflow的实例

Simple MNIST convnet(MNIST数字分类)
用下面这个链接,进入官网下载其数据集,mnist.npz
https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz

在这里插入图片描述

下面进行训练数据

# 训练代码以及运行结果
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers

num_classes = 10 # All digits are 10 classes.
input_shape = (28, 28, 1)

path = 'mnist.npz'# https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
f = np.load(path, allow_pickle=True)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test'] # the data, split between train and test sets

# plot 4 images as gray scale
plt.subplot(331)
plt.imshow(x_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(332)
plt.imshow(x_train[1], cmap=plt.get_cmap('gray'))
plt.subplot(333)
plt.imshow(x_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(334)
plt.imshow(x_train[3], cmap=plt.get_cmap('gray'))
plt.subplot(335)
plt.imshow(x_train[4], cmap=plt.get_cmap('gray'))
plt.subplot(336)
plt.imshow(x_train[5], cmap=plt.get_cmap('gray'))
plt.subplot(337)
plt.imshow(x_test[6], cmap=plt.get_cmap('gray'))
plt.subplot(338)
plt.imshow(x_test[7], cmap=plt.get_cmap('gray'))
plt.subplot(339)
plt.imshow(x_test[8], cmap=plt.get_cmap('gray'))#imshow函数的官方文档:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow
# show the plot
plt.show()

# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print("x_test shape:", x_test.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
y_train = keras.utils.to_categorical(y_train, num_classes)# convert class vectors to binary class matrices
y_test = keras.utils.to_categorical(y_test, num_classes)#将类别标签转换为onehot编码,onehot编码是一种方便计算机处理的二元编码

model = keras.Sequential(
    [
        keras.Input(shape=input_shape),
        layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Flatten(),
        layers.Dropout(0.5),
        layers.Dense(num_classes, activation="softmax"),
    ]
)
model.summary()

batch_size = 128
epochs = 15
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) #binary_crossentropy 二进制交叉熵用于二分类问题中,categorical_crossentropy分类交叉熵适用于多分类问题
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)

score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])

model.save('mnist_Model.h5')

训练后会生成一个mnist_Model.h5文件。
在这里插入图片描述

注意:新导入的环境可能缺少numpy库,在pycharm中添加即可
在这里插入图片描述

有了mnist_Model.h5文件后,进行预测

# 预测代码以及运行结果
from tensorflow.keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt

mnist_model = load_model('mnist_Model.h5')# load the trained mnist_model
path = 'mnist.npz'# http://yann.lecun.com/exdb/mnist/mnist.npz
f = np.load(path, allow_pickle=True)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test'] # Get the train and test sets data
X_Train99,Y_Train99 = x_train[99],y_train[99]# Select one from train data sets
X_Test999,Y_Test999 = x_test[999],y_test[999]# Select one from test data sets

print(X_Train99.shape)
X_Train99.shape=(1,28,28,1)
predict_Y_Train99 = mnist_model.predict(X_Train99)
print(predict_Y_Train99)
print('Train data set 99th picture:' + '\noriginal:'+str(Y_Train99) + '\npredicted:'+str(np.argmax(predict_Y_Train99)))
X_Train99.shape=(28,28)
plt.imshow(X_Train99,cmap='gray')
plt.title('Train data set 99th picture:' + '\noriginal:'+str(Y_Train99) + '\npredicted:'+str(np.argmax(predict_Y_Train99)))
plt.show()

print(X_Test999.shape)
X_Test999.shape=(1,28,28,1)
predict_Y_Test999 = mnist_model.predict(X_Test999)
print(predict_Y_Test999)
print('Test data set 999th picture:' +'\noriginal:'+str(Y_Test999)+'\npredicted:'+str(np.argmax(predict_Y_Test999)))
X_Test999.shape=(28,28)
plt.imshow(X_Test999,cmap='gray')
plt.title('Test data set 999th picture:' +'\noriginal:'+str(Y_Test999)+'\npredicted:'+str(np.argmax(predict_Y_Test999)))
plt.show()

对于可能出现的一种错误

AttributeError: 'str' object has no attribute 'decode'

解决方法为:
打开终端
在这里插入图片描述
输入下面代码进入建立的虚拟环境中

# 激活/进入创建的虚拟环境
activate news
# 以后在news环境中需要在终端中新添加库或者更新的话,都要用上面这个代码先进入这个虚拟环境中

在虚拟环境中输入:

pip install h5py==2.8.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 12
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Mistrain_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值