RNN代码-发一个测试一下看好使不

import pandas as pd 
import numpy as np
from sklearn import datasets, linear_model,svm
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import LSTM, TimeDistributed, Dense, Dropout, Activation
from keras import metrics

import os


def maxminnorm(array):
    '''
    归一化处理
    '''
    maxcols=array.max(axis=0)
    mincols=array.min(axis=0)
    data_shape = array.shape
    data_rows = data_shape[0]
    data_cols = data_shape[1]
    t=np.empty((data_rows,data_cols))
    for i in range(data_cols):
        t[:,i]=(array[:,i]-mincols[i])/(maxcols[i]-mincols[i])
    return t

def load_data_regression():
  '''
  加载用于回归问题的数据集
  '''
  #导入用到的库
  
  #载入数据集
  Boston = datasets.load_boston()
  # print(Boston.feature_names)
  x = Boston.data   #shape:(506, 13)
  y = Boston.target   #shape:(506,)
  
  #将第3列转化为one-hot编码格式
  x3 = x[:,3]
  x4 = pd.get_dummies(x3)
  x = np.delete(x,3,1)
  x = np.column_stack((x,x4[0].values.tolist()))
  x = np.column_stack((x,x4[1].values.tolist()))

  #其他列进行归一化处理
  x = maxminnorm(x)

  # 拆分成训练集和测试集,测试集大小为原始数据集大小的 1/4
  return train_test_split(x,y,test_size = 0.25,random_state = 0)#分割数据集为训练集与测试集
  

os.environ['KERAS_BACKEND']='tensorflow'

x_train,x_test,y_train,y_test=load_data_regression()
trainX = x_train.reshape((x_train.shape[0],1,x_train.shape[1]))
testX = x_test.reshape((x_test.shape[0],1,x_test.shape[1]))
trainY = y_train
testY = y_test

#####建立模型
model = Sequential()
model.add(LSTM(128, input_shape=(trainX.shape[1], trainX.shape[2])))
model.add(Dropout(0.05))
model.add(Dense(1))
model.add(Activation('linear'))
#model.compile(loss='mae', optimizer='sgd',metrics=[metrics.categorical_accuracy])
model.compile(loss='mae', optimizer='adam',metrics=[metrics.categorical_accuracy])

history = model.fit(trainX, trainY, epochs=100, batch_size=25, validation_data=(testX, testY), verbose=2, shuffle=False)
# 评估模型,输出预测结果
loss,accuracy = model.evaluate(testX,testY, verbose=0)
print('\ntest loss',loss)
print('accuracy',accuracy)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值