博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Keras + LSTM 做回归demo 2
阅读量:5036 次
发布时间:2019-06-12

本文共 2232 字,大约阅读时间需要 7 分钟。

接上回, 这次做了一个多元回归

这里贴一下代码

import numpy as npnp.random.seed(1337)from sklearn.model_selection import train_test_splitimport matplotlib.pyplot as pltimport kerasfrom keras.models import Sequentialfrom keras.layers import Activationfrom keras.layers import LSTMfrom keras.layers import Dropoutfrom keras.layers import Denseimport pandas as pd

  

datan = 1000# 真实参数ori_weights = [5, -4, 3, -2, 1]colsn = len(ori_weights)bias = -1ori = np.zeros((1, colsn))ori[0] = np.asarray(ori_weights)
# 列信息cols_name = [chr(65+i) for i in range(colsn)]X = np.zeros((colsn, datan))for i in range(colsn):    X[i] = np.random.normal(1, 0.1, datan)# 真实YY = np.matmul(ori, X) + bias + np.random.normal(-0.1, 0.1, (datan, ))
# 数据预览df = pd.DataFrame(X.T, columns=cols_name)df['Y'] = df.apply(lambda row: np.matmul(ori, [row[k] for k in df.columns] )[0]+bias, axis=1)df['target'] = Y[0]df.head()

  

 

X_train, X_test, Y_train, Y_test = train_test_split(X.T, Y.T, test_size=0.33, random_state=42)

  

neurons = 128          activation_function = 'tanh'  loss = 'mse'                  optimizer="adam"              dropout = 0.01 batch_size = 12          epochs = 200

  

model = Sequential()model.add(LSTM(neurons, return_sequences=True, input_shape=(1, colsn), activation=activation_function))model.add(Dropout(dropout))model.add(LSTM(neurons, return_sequences=True, activation=activation_function))model.add(Dropout(dropout))model.add(LSTM(neurons, activation=activation_function))model.add(Dropout(dropout))model.add(Dense(output_dim=1, input_dim=1))

  

model.compile(loss=loss, optimizer=optimizer)

  

epochs = 2001for step in range(epochs):    cost = model.train_on_batch(X_train[:, np.newaxis], Y_train)    if step % 30 == 0:        print(f'{step} train cost: ', cost)

  

# testprint('Testing ------------')cost = model.evaluate(X_test[:, np.newaxis], Y_test, batch_size=40)print('test cost:', cost)

  

# plotting the predictionY_pred = model.predict(X_test[:, np.newaxis])#sdf = pd.DataFrame({'test':list(Y_test.T[0]), 'pred':list(Y_pred.T[0])})sdf.sort_values(by='test', inplace=True)#plt.scatter(range(len(Y_test)), list(sdf.test))plt.plot(range(len(Y_test)), list(sdf.pred), 'r--')plt.show()

  

  

 

 

  

 

转载于:https://www.cnblogs.com/fadedlemon/p/10530244.html

你可能感兴趣的文章
利用python打开摄像头并保存
查看>>
System函数的使用说明
查看>>
Selenium-测试对象操作之:获取浏览器滚动条滚动距离
查看>>
Linux下MySQL数据库安装与配置
查看>>
Extjs String转Json
查看>>
oracle入门(4)——少而常用的命令
查看>>
打印机设置(PrintDialog)、页面设置(PageSetupDialog) 及 RDLC报表如何选择指定打印机...
查看>>
Java 虚拟机部分面试题
查看>>
二叉树的遍历问题总结
查看>>
Spring之面向切面编程AOP
查看>>
MATLAB GUI程序设计中使文本框接收多行输入的方法
查看>>
全文检索-Elasticsearch (四) elasticsearch.net 客户端
查看>>
Oracle DBMS_SESSION
查看>>
sublime复制当前行到下一行
查看>>
WPF 3D变换应用
查看>>
ArchLinux安装开源VMware Tools
查看>>
DB2 锁升级示例1
查看>>
16.RDD实战
查看>>
MainFrame知识小结(20120210)—dfsort/syncsort中的数据类型
查看>>
D - Flip tile
查看>>