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)
RNN代码-发一个测试一下看好使不
最新推荐文章于 2024-05-05 20:10:01 发布