神经网络python_带有Python的AI –神经网络

神经网络python

神经网络python

带有Python的AI –神经网络 (AI with Python – Neural Networks)

Neural networks are parallel computing devices that are an attempt to make a computer model of brain. The main objective behind is to develop a system to perform various computational task faster than the traditional systems. These tasks include Pattern Recognition and Classification, Approximation, Optimization and Data Clustering.

神经网络是试图创建大脑计算机模型的并行计算设备。 背后的主要目标是开发一种比传统系统更快地执行各种计算任务的系统。 这些任务包括模式识别和分类,近似,优化和数据聚类。

什么是人工神经网络(ANN) (What is Artificial Neural Networks (ANN))

Artificial Neural network (ANN) is an efficient computing system whose central theme is borrowed from the analogy of biological neural networks. ANNs are also named as Artificial Neural Systems, Parallel Distributed Processing Systems, and Connectionist Systems. ANN acquires large collection of units that are interconnected in some pattern to allow communications between them. These units, also referred to as nodes or neurons, are simple processors which operate in parallel.

人工神经网络(ANN)是一种高效的计算系统,其中心主题是从生物神经网络的类比中借鉴而来的。 人工神经网络也被称为人工神经系统,并行分布式处理系统和连接系统。 ANN获取大量以某种模式互连以允许它们之间进行通信的单元集合。 这些单元,也称为节点神经元 ,是并行运行的简单处理器。

Every neuron is connected with other neuron through a connection link. Each connection link is associated with a weight having the information about the input signal. This is the most useful information for neurons to solve a particular problem because the weight usually excites or inhibits the signal that is being communicated. Each neuron is having its internal state which is called activation signal. Output signals, which are produced after combining input signals and activation rule, may be sent to other units.

每个神经元通过连接链接与其他神经元连接 。 每个连接链接与具有有关输入信号信息的权重相关联。 这对于神经元解决特定问题是最有用的信息,因为重量通常会激发或抑制正在传达的信号。 每个神经元都有其内部状态,称为激活信号 。 组合输入信号和激活规则后产生的输出信号可以发送到其他单元。

If you want to study neural networks in detail then you can follow the link − Artificial Neural Network.

如果要详细研究神经网络,则可以单击链接- 人工神经网络

安装有用的软件包 (Installing Useful Packages)

For creating neural networks in Python, we can use a powerful package for neural networks called NeuroLab. It is a library of basic neural networks algorithms with flexible network configurations and learning algorithms for Python. You can install this package with the help of the following command on command prompt −

为了在Python中创建神经网络,我们可以使用功能强大的神经网络软件包NeuroLab 。 它是基本神经网络算法的库,具有灵活的网络配置和Python学习算法。 您可以在命令提示符下的以下命令的帮助下安装此软件包-


pip install NeuroLab

If you are using the Anaconda environment, then use the following command to install NeuroLab −

如果您正在使用Anaconda环境,则使用以下命令安装NeuroLab-


conda install -c labfabulous neurolab

建立神经网络 (Building Neural Networks)

In this section, let us build some neural networks in Python by using the NeuroLab package.

在本节中,让我们使用NeuroLab软件包在Python中构建一些神经网络。

基于感知器的分类器 (Perceptron based Classifier)

Perceptrons are the building blocks of ANN. If you want to know more about Perceptron, you can follow the link − artificial_neural_network

感知器是人工神经网络的基础。 如果您想了解更多有关Perceptron的信息,则可以点击链接-Artificial_neural_network

Following is a stepwise execution of the Python code for building a simple neural network perceptron based classifier −

以下是Python代码的逐步执行,用于构建基于神经网络感知器的简单分类器-

Import the necessary packages as shown −

导入所需的软件包,如下所示:


import matplotlib.pyplot as plt
import neurolab as nl

Enter the input values. Note that it is an example of supervised learning, hence you will have to provide target values too.

输入输入值。 请注意,这是监督学习的示例,因此您也必须提供目标值。


input = [[0, 0], [0, 1], [1, 0], [1, 1]]
target = [[0], [0], [0], [1]]

Create the network with 2 inputs and 1 neuron −

创建具有2个输入和1个神经元的网络-


net = nl.net.newp([[0, 1],[0, 1]], 1)

Now, train the network. Here, we are using Delta rule for training.

现在,训练网络。 在这里,我们使用Delta规则进行训练。


error_progress = net.train(input, target, epochs=100, show=10, lr=0.1)

Now, visualize the output and plot the graph −

现在,可视化输出并绘制图形-


plt.figure()
plt.plot(error_progress)
plt.xlabel('Number of epochs')
plt.ylabel('Training error')
plt.grid()
plt.show()

You can see the following graph showing the training progress using the error metric −

您可以看到下图显示了使用误差指标的训练进度-

Perceptron based Classifier

单层神经网络 (Single - Layer Neural Networks)

In this example, we are creating a single layer neural network that consists of independent neurons acting on input data to produce the output. Note that we are using the text file named neural_simple.txt as our input.

在此示例中,我们正在创建一个单层神经网络,该网络由作用于输入数据以产生输出的独立神经元组成。 请注意,我们正在使用名为Neuro_simple.txt的文本文件作为输入。

Import the useful packages as shown −

导入有用的软件包,如下所示:


import numpy as np
import matplotlib.pyplot as plt
import neurolab as nl

Load the dataset as follows −

如下加载数据集-


input_data = np.loadtxt(“/Users/admin/neural_simple.txt')

The following is the data we are going to use. Note that in this data, first two columns are the features and last two columns are the labels.

以下是我们将要使用的数据。 请注意,在此数据中,前两列是要素,后两列是标签。


array([[2. , 4. , 0. , 0. ],
      [1.5, 3.9, 0. , 0. ],
      [2.2, 4.1, 0. , 0. ],
      [1.9, 4.7, 0. , 0. ],
      [5.4, 2.2, 0. , 1. ],
      [4.3, 7.1, 0. , 1. ],
      [5.8, 4.9, 0. , 1. ],
      [6.5, 3.2, 0. , 1. ],
      [3. , 2. , 1. , 0. ],
      [2.5, 0.5, 1. , 0. ],
      [3.5, 2.1, 1. , 0. ],
      [2.9, 0.3, 1. , 0. ],
      [6.5, 8.3, 1. , 1. ],
      [3.2, 6.2, 1. , 1. ],
      [4.9, 7.8, 1. , 1. ],
      [2.1, 4.8, 1. , 1. ]])

Now, separate these four columns into 2 data columns and 2 labels −

现在,将这四列分为2个数据列和2个标签-


data = input_data[:, 0:2]
labels = input_data[:, 2:]

Plot the input data using the following commands −

使用以下命令绘制输入数据-


plt.figure()
plt.scatter(data[:,0], data[:,1])
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.title('Input data') 

Now, define the minimum and maximum values for each dimension as shown here −

现在,为每个尺寸定义最小值和最大值,如下所示:


dim1_min, dim1_max = data[:,0].min(), data[:,0].max()
dim2_min, dim2_max = data[:,1].min(), data[:,1].max()

Next, define the number of neurons in the output layer as follows −

接下来,如下定义输出层中神经元的数量-


nn_output_layer = labels.shape[1]

Now, define a single-layer neural network −

现在,定义一个单层神经网络-


dim1 = [dim1_min, dim1_max]
dim2 = [dim2_min, dim2_max]
neural_net = nl.net.newp([dim1, dim2], nn_output_layer)

Train the neural network with number of epochs and learning rate as shown −

训练神经网络的时期数和学习率,如图所示-


error = neural_net.train(data, labels, epochs = 200, show = 20, lr = 0.01)

Now, visualize and plot the training progress using the following commands −

现在,使用以下命令可视化并绘制训练进度图-


plt.figure()
plt.plot(error)
plt.xlabel('Number of epochs')
plt.ylabel('Training error')
plt.title('Training error progress')
plt.grid()
plt.show()

Now, use the test data-points in above classifier −

现在,在上面的分类器中使用测试数据点-


print('\nTest Results:')
data_test = [[1.5, 3.2], [3.6, 1.7], [3.6, 5.7],[1.6, 3.9]] for item in data_test:
   print(item, '-->', neural_net.sim([item])[0])

You can find the test results as shown here −

您可以找到测试结果,如下所示-


[1.5, 3.2] --> [1. 0.]
[3.6, 1.7] --> [1. 0.]
[3.6, 5.7] --> [1. 1.]
[1.6, 3.9] --> [1. 0.]

You can see the following graphs as the output of the code discussed till now −

您可以看到以下图形作为到目前为止讨论的代码的输出-

Single Layer Neural Networks
Number of Epochs

多层神经网络 (Multi-Layer Neural Networks)

In this example, we are creating a multi-layer neural network that consists of more than one layer to extract the underlying patterns in the training data. This multilayer neural network will work like a regressor. We are going to generate some data points based on the equation: y = 2x2+8.

在此示例中,我们正在创建一个多层神经网络,该网络由一层以上的层组成,以提取训练数据中的基础模式。 这种多层神经网络将像回归器一样工作。 我们将基于以下公式生成一些数据点:y = 2x 2 +8。

Import the necessary packages as shown −

导入所需的软件包,如下所示:


import numpy as np
import matplotlib.pyplot as plt
import neurolab as nl

Generate some data point based on the above mentioned equation −

根据上述方程式生成一些数据点-


min_val = -30
max_val = 30
num_points = 160
x = np.linspace(min_val, max_val, num_points)
y = 2 * np.square(x) + 8
y /= np.linalg.norm(y)

Now, reshape this data set as follows −

现在,按如下所示重塑此数据集:


data = x.reshape(num_points, 1)
labels = y.reshape(num_points, 1)

Visualize and plot the input data set using the following commands −

使用以下命令可视化并绘制输入数据集-


plt.figure()
plt.scatter(data, labels)
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.title('Data-points')

Now, build the neural network having two hidden layers with neurolab with ten neurons in the first hidden layer, six in the second hidden layer and one in the output layer.

现在,建立具有与所述第一隐藏层神经元10, 在第二隐蔽层和一个输出层neurolab两个隐含层的神经网络。


neural_net = nl.net.newff([[min_val, max_val]], [10, 6, 1])

Now use the gradient training algorithm −

现在使用梯度训练算法-


neural_net.trainf = nl.train.train_gd

Now train the network with goal of learning on the data generated above −

现在训练网络,以学习上面生成的数据为目标-


error = neural_net.train(data, labels, epochs = 1000, show = 100, goal = 0.01)

Now, run the neural networks on the training data-points −

现在,在训练数据点上运行神经网络-


output = neural_net.sim(data)
y_pred = output.reshape(num_points)

Now plot and visualization task −

现在绘图和可视化任务-


plt.figure()
plt.plot(error)
plt.xlabel('Number of epochs')
plt.ylabel('Error')
plt.title('Training error progress')

Now we will be plotting the actual versus predicted output −

现在我们将绘制实际输出与预测输出的关系图-


x_dense = np.linspace(min_val, max_val, num_points * 2)
y_dense_pred = neural_net.sim(x_dense.reshape(x_dense.size,1)).reshape(x_dense.size)
plt.figure()
plt.plot(x_dense, y_dense_pred, '-', x, y, '.', x, y_pred, 'p')
plt.title('Actual vs predicted')
plt.show()

As a result of the above commands, you can observe the graphs as shown below −

由于上述命令,您可以观察到如下图所示的图形-

Multi Layer Neural Networks
Training Error Progress
Actual vs Predicted

翻译自: https://www.tutorialspoint.com/artificial_intelligence_with_python/artificial_intelligence_with_python_neural_networks.htm

神经网络python

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值