Theano:线性回归

import theano
from theano import tensor as T
import numpy as np
import matplotlib.pyplot as plt

def model(X, w):
    return X * w

trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.3
X = T.scalar()
Y = T.scalar()
W = T.scalar()
w = theano.shared(np.asarray(0., dtype=theano.config.floatX))
y = model(X, w)
cost = T.mean(T.sqr(y - Y))
gradient = T.grad(cost=cost, wrt=w)
updates = [[w, w - gradient * 0.01]]
#define training function
train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True)
for i in range(100):
    for x, y in zip(trX, trY):
        train(x, y)
#define predict function
yy = X * W
predict = theano.function(inputs = [X, W], outputs = yy)


testX = np.linspace(-1, 1, 50)
testY = 2 * testX + np.random.randn(*testX.shape) * 0.3

y_pred = []
for x in testX:
    yi = predict(x, w.get_value())
    y_pred.append(yi)

fig = plt.figure()
ax = fig.add_subplot(211)
ax.plot(trX, trY, '.')
plt.title('training data')
ax = fig.add_subplot(212)
l1 = ax.plot(testX, y_pred,'.r')
l2 = ax.plot(testX, testY,'o')
plt.title('predict result')
ax.legend(('predict data','real data'), 'upper left')
plt.show()
print w.get_value() #something around 2

线性回归的训练数据和相应的预测结果如下图

这里写图片描述
用theano训练的线性回归模型,上一幅图为训练数据,下一幅图为真实数据和预测结果的对比

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值