def prediction(): with tf.variable_scope("sec_lstm", reuse=tf.AUTO_REUSE): pred, _ = lstm(1) #预测时只输入[1,time_step,input_size]的测试数据 saver = tf.train.Saver(tf.global_variables()) with tf.Session() as sess: saver.restore(sess, 'model_save1\\modle.ckpt') #参数恢复 # I run the code in windows 10,so use 'model_save1\\modle.ckpt' # if you run it in Linux,please use 'model_save1/modle.ckpt' # 取训练集最后一行为测试样本。shape=[1,time_step,input_size] prev_seq = train_x[-1] predict = [] # 得到之后100个预测结果 for i in range(100): next_seq = sess.run(pred, feed_dict={X: [prev_seq]}) predict.append(next_seq[-1]) # 每次得到最后一个时间步的预测结果,与之前的数据加在一起,形成新的测试样本 prev_seq = np.vstack((prev_seq[1:], next_seq[-1])) # 以折线图表示结果 plt.figure() plt.plot(list(range(len(normalize_data))), normalize_data, color='b') plt.plot(list( range(len(normalize_data), len(normalize_data) + len(predict))), predict, color='r') plt.show()
def prediction(time_step=20): X = tf.placeholder(tf.float32, shape=[None, time_step, input_size]) mean, std, test_x, test_y = get_test_data(time_step) with tf.variable_scope("sec_lstm", reuse=tf.AUTO_REUSE): pred, _ = lstm(X) saver = tf.train.Saver(tf.global_variables()) with tf.Session() as sess: # 参数恢复 module_file = tf.train.latest_checkpoint('model_save2') saver.restore(sess, module_file) test_predict = [] for step in range(len(test_x) - 1): prob = sess.run(pred, feed_dict={X: [test_x[step]], keep_prob: 1}) predict = prob.reshape((-1)) test_predict.extend(predict) test_y = np.array(test_y) * std[7] + mean[7] test_predict = np.array(test_predict) * std[7] + mean[7] acc = np.average( np.abs(test_predict - test_y[:len(test_predict)]) / test_y[:len(test_predict)]) # 偏差程度 print("The accuracy of this predict:", acc) # 以折线图表示结果 plt.figure() plt.plot( list(range(len(test_predict))), test_predict, color='b', ) plt.plot(list(range(len(test_y))), test_y, color='r') plt.show()
def drowPicture(History): pyplot.plot(History.history['loss']) pyplot.plot(History.history['val_loss']) pyplot.plot(History.history['acc']) pyplot.plot(History.history['val_acc']) pyplot.title('model train vs validation loss') pyplot.ylabel('loss') pyplot.xlabel('epoch') pyplot.legend(['train', 'validation'], loc='upper right') pyplot.show()
def main_test(): print("主要测试") import numpy as np s = np.random.uniform(1, 2, 1000) # print(np.all(s >= 2)) # print(s) # exit() import Example_matplotlib.pyplot as plt count, bins, ignored = plt.hist(s, 15, density=True) plt.plot(bins, np.ones_like(bins), linewidth=2, color='r') plt.show()
def plot_forecasts(series, forecasts, n_test): # plot the entire dataset in blue pyplot.plot(series.values) # plot the forecasts in red for i in range(len(forecasts)): off_s = len(series) - n_test + i - 1 off_e = off_s + len(forecasts[i]) + 1 xaxis = [x for x in range(off_s, off_e)] yaxis = [series.values[off_s]] + forecasts[i] pyplot.plot(xaxis, yaxis, color='red') # show the plot pyplot.show()
def plot_forecasts(series, forecasts, n_test): # 蓝线画出真实数据 pyplot.plot(series.values) # 红线画出预测值 for i in range(len(forecasts)): off_s = len(series) - n_test + i - 1 off_e = off_s + len(forecasts[i]) + 1 # 赋值x轴坐标 xaxis = [x for x in range(off_s, off_e)] # 赋值y轴坐标 yaxis = [series.values[off_s]] + forecasts[i] pyplot.plot(xaxis, yaxis, color='red') pyplot.show()
def plot_forcasts(series, forcasts, n_test): # 原始数据 pyplot.plot(series.values) # 预测数据 for i in range(len(forcasts)): off_s = len(series) - n_test + i - 1 off_e = off_s + len(forcasts[i]) + 1 xaxis = [x for x in range(off_s, off_e)] yaxis = [series.values[off_s]] + forcasts[i] print('xaxis') print(xaxis) print('yaxis') print(yaxis) print('series.values[off_s]') print(series.values[off_s]) pyplot.plot(xaxis, yaxis, color='red') pyplot.show()
def plot_results(xlog, ulog): t = [0.25 * x for x in range(xlog.shape[1])] plt.figure() plt.subplot(311) plt.plot(t, xlog[3, :], label="altitude", color="b") plt.ylabel('altitude') plt.subplot(312) plt.plot(t, xlog[1, :], label="pitch angle", color="r") plt.ylabel('pitch angle') plt.subplot(313) plt.plot(t, ulog[0, :], label="elevator angle", color="g") plt.ylabel('elevator angle') plt.show()
# @Time : 2019/9/27 0027 13:57 # @Author :zhu # @File : pro_view.py # @task description : import tensorflow as tf import numpy as np import Example_matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (14, 8) # 生成随机数 n_observations = 100 xs = np.linspace(-3, 3, n_observations) ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations) plt.scatter(xs, ys) plt.show() # 定义容器,放入X和Y X = tf.placeholder(tf.float32, name="X") Y = tf.placeholder(tf.float32, name="Y") # 定义权重和偏置,对应与一次线性函数y = wx + b w = tf.Variable(tf.random_normal([1]), name="weight") b = tf.Variable(tf.random_normal([1]), name="bias") # 进行计算预测Y_Pre Y_Pre = tf.add(tf.multiply(X, w), b) # 计算损失的函数值,就是平方差 loss = tf.square(Y - Y_Pre, name="loss") # 初始化 learning_rate = 0.01 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # 给出迭代次数,并且加入 Session执行 n_samples = xs.shape[0]
# 使用构造的网络模型进行预测训练 lstm_model.predict(train_reshaped, batch_size=1) #print(lstm_model.predict(train_reshaped, batch_size=1)) # 遍历测试数据,对数据进行单步预测 predictions = list() for i in range(len(test_scaled)): # 将(12,2)的2D训练集test_scaled拆分成X,y; # 其中X是第i行的0到-1列,形状是(1,)的包含一个元素的一维数组;y是第i行,倒数第1列,是一个数值; X, y = test_scaled[i, 0:-1], test_scaled[i, -1] # 将训练好的模型lstm_model,X变量,传入预测函数,定义步长为1, yhat = forecast_lstm(lstm_model, 1, X) print(yhat.shape) # 对预测出的y值逆缩放 yhat = invert_scale(scaler, X, yhat) # 对预测出的y值逆差分转换 #yhat = inverse_difference(raw_values, yhat, len(test_scaled)+1-i) # 存储预测的y值 predictions.append(yhat) # 获取真实的y值 expected = raw_values[len(train) + i + 1] # print('Month=%d, Predicted=%f, Expected=%f' % (i + 1, yhat, expected)) # 求真实值和预测值之间的标准差 rmse = sqrt(mean_squared_error(raw_values[-testNum:], predictions)) print('Test RMSE: %.3f' % rmse) # 作图展示 pyplot.plot(raw_values[-testNum:]) pyplot.plot(predictions) pyplot.show()
def pic_map(): import numpy as np import pandas as pd import Example_matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from Example_matplotlib.patches import Polygon from Example_matplotlib.colors import rgb2hex from Example_matplotlib.collections import PatchCollection from Example_matplotlib import pylab plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(20, 10)) # 长和宽 # m= Basemap(llcrnrlon=73, llcrnrlat=18, urcrnrlon=135, urcrnrlat=55) #指定中国的经纬度 m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100) # ‘lcc'将投影方式设置为兰伯特投影 # projection='ortho' # 投影方式设置为正投影——类似地球仪 CHN = r'C:\Users\Administrator\Desktop\MyProject\Test_module\Test_matplotlib\data_base' m.readshapefile(CHN + r'\gadm36_CHN_shp\gadm36_CHN_1', 'states', drawbounds=True) # 加省界 # 读取数据 df = pd.read_csv('./data_base/data/chnpop.csv') df['省名'] = df.省名.str[:2] df.set_index('省名', inplace=True) # 把每个省的数据映射到colormap上 statenames = [] colors = {} patches = [] cmap = plt.cm.YlOrRd # 国旗色红黄色调 vmax = 10**8 vmin = 3 * 10**6 # 处理地图包里的省名 for shapedict in m.states_info: statename = shapedict['NL_NAME_1'] p = statename.split('|') if len(p) > 1: s = p[1] else: s = p[0] s = s[:2] if s == '黑龍': s = '黑龙' statenames.append(s) pop = df['人口数'][s] colors[s] = cmap(np.sqrt( (pop - vmin) / (vmax - vmin)))[:3] # 根据归一化后的人口数映射颜色 # exit() ax = plt.gca() for nshape, seg in enumerate(m.states): color = rgb2hex(colors[statenames[nshape]]) poly = Polygon(seg, facecolor=color, edgecolor=color) patches.append(poly) ax.add_patch(poly) # 图片绘制加上台湾(台湾不可或缺) m.readshapefile(CHN + '\gadm36_TWN_shp\gadm36_TWN_1', 'taiwan', drawbounds=True) for nshape, seg in enumerate(m.taiwan): poly = Polygon(seg, facecolor='w') patches.append(poly) ax.add_patch(poly) # 添加colorbar 渐变色legend colors1 = [i[1] for i in colors.values()] colorVotes = plt.cm.YlOrRd p = PatchCollection(patches, cmap=colorVotes) p.set_array(np.array(colors1)) pylab.colorbar(p) #4266831.094478747, 1662846.3046657 lon = 4097273.638675578 lat = 4008859.232616643 x, y = m(lon, lat) plt.text(x, y, '国都', fontsize=120, fontweight='bold', ha='left', va='bottom', color='k') m.scatter(x, y, s=200, marker='*', facecolors='r', edgecolors='B') # 绘制首都 plt.title(u'祝鑫泉画的World Map ', fontsize=24) plt.savefig("./data_base/result/Chinese_Map1.png", dpi=100) # 指定分辨率 plt.show()