Configure PyQt, TensorFlow and other environments under PyCharm

This blog is also an extension of the blog " Using PyQt to Write GUI Programs in ROS ".

 

table of Contents

1. Software installation

 Two, environment configuration

Three, install other libraries

 Fourth, the construction of PyQt in PyCharm


 

1. Software installation

Pycharm is a better IDE for python. The download of PyCharm is https://www.jetbrains.com/pycharm/download , the community version can be selected, it is free to use, and the installation process is very simple.

The installation of Python can be downloaded directly from the official website https://www.python.org/downloads/ . The latest version is the 3.7 series. It is recommended to download the executable program for installation, and install it directly according to the default option, and pip must be checked. It is recommended that python be placed in the system environment variable, so open cmd and enter python and press Enter to check whether python is installed successfully and its corresponding version. .

 

 Two, environment configuration

Double-click the installed pycharm. When you open it for the first time, you will be asked to select the python interpreter. Generally, the default is to load the virtual environment. This is not recommended. Directly select the interpreter just loaded into the system, as follows.

Create a new project, so that you can import some python libraries, such as math, sys, socket, etc.

 

Three, install other libraries

Python mainly has two package manager systems, one is conda (this requires anaconda to be installed) and the other is pip. Python's package manager system is too powerful and easy to use, I just can't put it down, see https://pypi.org/project/pip/ for details .

pip is a scripting language, and its running directory is under the Scripts folder of the installed python environment.

The use of pip is as follows, generally using the install command.

For example, to install PyQt5 (this is a python package based on the Qt library, suitable for using python to make some GUI programs), directly enter in cmd

pip install PyQt5

Then press Enter to start the installation, see https://pypi.org/project/PyQt5 for details . The installation may not be successful the first time, because it depends on some other libraries and will be installed first. If it fails, execute the instruction again.

Similarly, TensorFlow is installed in the same way.

pip install tensorflow

See https://pypi.org/project/tensorflow for details . It has to be installed several times to succeed, because it depends on third-party libraries such as numpy.

To verify whether TensorFlow is installed successfully, you can write a simple program in python IDLE to verify:

import tensorflow as tf
import numpy as np
# 引入图表
import matplotlib.pyplot as plt
 
# 没有激励就是线性
def add_layer(inputs,in_size,out_size,activation_function=None):
	Weights = tf.Variable(tf.random_normal([in_size,out_size]))# 随机生成一个矩阵,有in_size行数和out_size列数
	biases = tf.Variable(tf.zeros([1,out_size])+0.1)# 这个是个一维数组,行数只有1,列数为out_size,这里+0.1表示他每个值都是0.1
	Wx_plus_b = tf.matmul(inputs,Weights)+biases# 矩阵相乘再加biases
	if activation_function  is None:
		outputs = Wx_plus_b# 如果没有激励,则直接就是这个线性函数
	else:
		outputs = activation_function(Wx_plus_b)# 如果有激励,则把线性函数传进激励函数(进行过滤或缩放等操作)
	return outputs
 
# 这个x_data是这样的:产生300个[x],其值从-1开始到1不等距分布
# [-0.001234234]
# [-0.002453244]
# .
# .
# .
# [0.932423425]
# [0.993242424]
x_data = np.linspace(-1,1,300)[:,np.newaxis]
 
# 噪点,结构与x_data类似有负有正
# 以0为中点,方差为0.05波动
# 这个数与0之间的差值的平方值,最大为0.05,即这个数的平方不能大于0.05
 
noise = np.random.normal(0,0.05,x_data.shape)
 
# 令y_data等于x_data的二次方,再减去0.5,然后加上一个随机噪声,这样x跟y就不是完全线性相关的
 
y_data = np.square(x_data) - 0.5 + noise
 
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
 
# 定义隐藏层。输入神经元1个,隐藏层神经元10个,激励函数:非线性函数
#(inputs,in_size,out_size,activation_function=None)
#(输入数据,输入参数个数,输出参数根数,激励函数)
l1 = add_layer(xs,1,10,activation_function = tf.nn.relu)
 
# 定义输出层。l1,神经元10个,输出1
# 输出层,就是预测值
predition = add_layer(l1,10,1,activation_function = None)
 
# tf.square(ys - predition) (对每个例子)实际值减预测值的平方
# 对刚才的平方,所有例子求和
# 对刚才求的和求一个平均值
 
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - predition),
	reduction_indices = [1]))
# 梯度下降法优化器
# 参数是学习效率
# 优化器的目标是最小化误差
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
 
init = tf.initialize_all_variables()
 
sess = tf.Session()
sess.run(init)
 
# 在此显示图形
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)# x和对应的y
plt.ion()#有这个语句就不阻塞会继续往下走
plt.show()
 
for i in range(1000):
	sess.run(train_step,feed_dict = {xs:x_data,ys:y_data})
	if i% 50:
		#print(sess.run(loss,feed_dict = {xs:x_data,ys:y_data}))
		try:
			ax.lines.remove(lines[0])
		except Exception:
			pass
		prediction_value = sess.run(predition,feed_dict={xs:x_data})
		lines  = ax.plot(x_data,prediction_value,'r-',lw=5)#红线是预测的线
		plt.pause(0.1)#暂停0.1秒
# 如果打印的loss越来越小,说明是收敛的,训练有效
# 检验发现,10000次训练不会比1000此训练loss更小,说明不收敛(不是无限收敛)

Then run, the following interface will appear.

 

So we can study some machine learning algorithms.

The libraries installed with pip can be found in Python37\Lib\site-packages.

 

 Fourth, the construction of PyQt in PyCharm

To do UI interface design, you also need to install the pyqt5-tools tool, which is actually some auxiliary tools such as Qt Designer, and convert Qt's ui, qrc and other files into python description.

Open pycharm and add External Tools in Settings/Tools. There are three main ones. QtDesigner is used to design the interface, pyuic is used to convert .ui files to python descriptions, and pyrcc is used to convert .qrc files to python descriptions. Friends who are familiar with Qt should have a good understanding of QtDesigner, while pyuic and pyrcc are in the Python37\Scripts folder and are also operated by scripts.

The usage of pyrcc is as follows:

The usage of pyuic is as follows:

 Generally, the -o command is enough to output the generated code to a file.

Therefore, the settings in pycharm are as follows:

  • QtDesigner

  •  pyuic, enter $FileDir$\$FileName$ -o $FileDir$\$FileNameWithoutExtension$.py in Arguments, fill in $FileDir$ in Working directory, you can find some keywords in the insert macro next to it.

  •  pyrcc, enter $FileDir$\$FileName$ -o $FileDir$\$FileNameWithoutExtension$_rc.py in Arguments, and fill in $FileDir$ in Working directory.

 After filling in and saving, you can start to write PyQt program. 

At this point, create a new project to test the PyQt library. Use QtDesinger to write a simple interface, then right-click to select pyuic in External Tools, and a .py file with the same name will be generated at this time; create a new qrc file, enter some pictures and other information, and then right-click to select pyrcc in External Tools, it will generate a file with _ rc.py file. The project directory is shown below:

 

The code of main.py is as follows:

from PyQt5 import QtWidgets
import sys
from test import *
from rqc_rc import *
import numpy as np
from matplotlib import pyplot as plt

i = 1

x = np.arange(-5, 5, 0.1)
y = x*x+5
plt.title("python plot demo")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.plot(x, y, '-*')
plt.show()


class TestUi(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(TestUi, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.pushButton.pressed.connect(self.slot_btn_1)

    def slot_btn_1(self):
        global i
        print(i)
        self.ui.lineEdit.setText(str(i))
        i = i + 1


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    widget = TestUi()
    widget.show()
    sys.exit(app.exec())

Among them, matplotlib is quite similar to matlab, purely for testing, you can ignore it.

The running effect of the final program is as follows:

 

Enjoy!

 

Guess you like

Origin blog.csdn.net/u014610460/article/details/101108549
Recommended