Keras搭建神经网络BPNN(回归问题)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets,preprocessing
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import mean_squared_error

 

import warnings
warnings.filterwarnings('ignore')

#读取数据
dataset = datasets.load_boston()
X,Y = dataset.data,dataset.target

scale_x = preprocessing.MinMaxScaler(feature_range=(0,1))
scale_y = preprocessing.MinMaxScaler(feature_range=(0,1))
x = scale_x.fit_transform(X)
y = scale_y.fit_transform(Y.reshape(-1,1))
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=1)
dim = x.shape[1]

print('--------------------')

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Keras是一个基于Python的深度学习库,提供了许多便捷的API用于神经网络搭建Keras框架的特点是高度模块化、易于扩展、支持GPU和CPU的混合计算、用户友好,可以方便的构建各种神经网络模型并进行训练和预测。 在Keras搭建神经网络,首先需要确定神经网络的模型。Keras支持多种模型构建方法,包括序列模型、函数式模型和子类化API等。 序列模型是最简单的一种,它是一个线性的神经网络模型,是多个网络层的线性堆叠,其中的每一层都是前一层的输出作为下一层的输入。可以用以下方式构建一个序列模型: ``` from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(units=32, activation='relu', input_dim=100)) model.add(Dense(units=10, activation='softmax')) ``` 函数式模型可以用于构建更复杂的模型,如多输入和多输出的神经网络。可以用以下方式构建一个函数式模型: ``` from keras.layers import Input, Dense from keras.models import Model # This returns a tensor inputs = Input(shape=(784,)) # a layer instance is callable on a tensor, and returns a tensor x = Dense(64, activation='relu')(inputs) x = Dense(64, activation='relu')(x) predictions = Dense(10, activation='softmax')(x) # This creates a model that includes # the Input layer and three Dense layers model = Model(inputs=inputs, outputs=predictions) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ``` 子类化API提供了更加灵活的构建方式,可以通过自定义网络层和模型的方式实现复杂的神经网络。可以用以下方式构建一个子类化API模型: ``` import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = layers.Dense(64, activation='relu') self.dense2 = layers.Dense(64, activation='relu') self.dense3 = layers.Dense(10, activation='softmax') def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) x = self.dense3(x) return x model = MyModel() model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-3), loss=keras.losses.SparseCategoricalCrossentropy(), metrics=[keras.metrics.SparseCategoricalAccuracy()]) ``` 无论采用何种方式搭建神经网络,都需要进行模型的编译和训练。模型的编译需要指定优化器、损失函数和评估指标。模型的训练则需要指定训练集、验证集、批处理大小和训练轮数等参数。可以用以下方式训练和评估模型: ``` history = model.fit(x_train, y_train, batch_size=64, epochs=5, validation_data=(x_val, y_val)) test_scores = model.evaluate(x_test, y_test, verbose=2) print('Test loss:', test_scores[0]) print('Test accuracy:', test_scores[1]) ``` 以上是Keras搭建神经网络的基本流程,需要根据具体问题和数据集的不同进行调整和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值