Tensorflow入门--图与会话

第1关:Hello,Tensorflow

本关任务:编写使用python一个Tensorlfow的Hello,World程序。

import tensorflow as tf
c = tf.constant('Hello World')
sess = tf.Session()
print(sess.run(c))
sess.close()

第2关:计算图与会话

本关任务:使用Tensorflow实现矩阵乘法。

# -*- coding: utf-8 -*-
import tensorflow as tf

def matmul(a,b):
    '''
    a(list):矩阵a
    b(list):矩阵b
    result(ndarray):矩阵相乘结果
    '''
    #********* Begin *********#
    a = tf.constant(a)
    b = tf.constant(b)
    c = tf.matmul(a,b)
    with tf.Session() as sess:
        result=sess.run(c)
    #********* End *********#
    return result

第3关:Tensorflow实现线性回归

本关任务:使用Tensorflow实现线性回归方法,并对股票数进行预测。

# -*- coding: utf-8 -*-
import math
import numpy as np
import pandas as pd
from sklearn.preprocessing import scale
import tensorflow as tf
def preprocess_data(df):
    '''
    df(DataFrame):原始数据
    X(ndarray):处理后数据特征
    y(ndarray):处理后数据标签
    '''
    #*********Bengin*********#
    # 定义预测列变量,它存放研究对象的标签名
    forecast_col = 'Adj. Close' 
    # 定义预测天数,这里设置为所有数据量长度的1%
    forecast_out = int(math.ceil(0.1*len(df)))
    # 只用到df中下面的几个字段['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']
    df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]    
    # 构造两个新的列
    # HL_PCT为股票最高价与最低价的变化百分比
    df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
    # HL_PCT为股票收盘价与开盘价的变化百分比
    df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0
    # 下面为真正用到的特征字段['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']
    df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
    # 因为scikit-learn并不会处理空数据,需要把为空的数据都设置为一个比较难出现的值,这里取-9999,
    df.fillna(-99999, inplace=True)
    # 用label代表该字段,是预测结果
    df['label'] = df[forecast_col].shift(-forecast_out)
    #构造X
    X = np.array(df.drop(['label'], 1))   
    X = scale(X)
    X = X[:-forecast_out]
    # 抛弃label列中为空的那些行
    df.dropna(inplace=True)
    y = np.array(df['label'])
    #将标签reshape成(-1,1)
    y = y.reshape(-1,1)
    #*********End*********#
    return X,y
def tf_predict(sess,train_data,train_label,test_data,lr,n_iters):
    '''
    sess:tf.Session创建的会话
    train_data(ndarray):训练数据
    train_label(ndarray):训练标签
    test_data(ndarray):测试数据
    lr(float):学习率
    n_iters(int):训练轮数
    test_predict(ndarray):测试集预测标签
    '''
    #*********Bengin*********#
    data = tf.placeholder(tf.float32, [None, 4])
    
    real_label = tf.placeholder(tf.float32, [None, 1])
    
    weight = tf.Variable(tf.random_normal([4, 1]), dtype=tf.float32)
    
    bias = tf.Variable(tf.ones([1]), dtype=tf.float32)
    
    y_label = tf.add(tf.matmul(data, weight), bias)
    
    loss = tf.reduce_mean(tf.square(real_label - y_label))
    
    train = tf.train.AdamOptimizer(lr).minimize(loss)
    
    sess.run(tf.global_variables_initializer())
    
    for i in range(n_iters):
        sess.run(train,feed_dict={data: train_data, real_label: train_label})    
    test_predict = sess.run(y_label,feed_dict={data: test_data})
    sess.close()
    #*********End*********#
    return test_predict

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值