机器学习-tensorflow

为什么80%的码农都做不了架构师?>>>   hot3.png

例子1

先从helloworld开始: 

t@ubuntu:~$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> hello=tf.constant('hello,tensorFlow!')
>>> sess = tf.Session()
>>> print sess.run(hello)
hello,tensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(122) 
>>> print sess.run(a+b)
132

接下去两个步骤:1,学python;2,看ts;

例子2

手写数字识别,在ubuntu中安装部署好环境;

代码源自https://github.com/niektemme/tensorflow-mnist-predict

创建训练用python代码

# Copyright 2016 Niek Temme.
# Adapted form the on the MNIST biginners tutorial by Google. 
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================="""A very simple MNIST classifier.
Documentation at
http://niektemme.com/ @@to doThis script is based on the Tensoflow MNIST beginners tutorial
See extensive documentation for the tutorial at
https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html
"""#import modules
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data#import data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)# init_op = tf.global_variables_initializer() 看版本,使用该行还是使用下面那行
init_op = tf.initialize_all_variables()
saver = tf.train.Saver()# Train the model and save the model to disk as a model.ckpt file
# file is stored in the same directory as this python script is started
"""
The use of 'with tf.Session() as sess:' is taken from the Tensor flow documentation
on on saving and restoring variables.
https://www.tensorflow.org/versions/master/how_tos/variables/index.html
"""
with tf.Session() as sess:sess.run(init_op)for i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})save_path = saver.save(sess, "/tmp/model.ckpt")print ("Model saved in file: ", save_path)

测试代码

# Copyright 2016 Niek Temme. 
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================="""Predict a handwritten integer (MNIST beginners).Script requires
1) saved model (model.ckpt file) in the same location as the script is run from.
(requried a model created in the MNIST beginners tutorial)
2) one argument (png file location of a handwritten integer)Documentation at:
http://niektemme.com/ @@to do
"""#import modules
import sys
import tensorflow as tf
from PIL import Image,ImageFilterdef predictint(imvalue):"""This function returns the predicted integer.The imput is the pixel values from the imageprepare() function."""# Define the model (same as when creating the model file)x = tf.placeholder(tf.float32, [None, 784])W = tf.Variable(tf.zeros([784, 10]))b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(x, W) + b)init_op = tf.global_variables_initializer()saver = tf.train.Saver()"""Load the model.ckpt filefile is stored in the same directory as this python script is startedUse the model to predict the integer. Integer is returend as list.Based on the documentatoin athttps://www.tensorflow.org/versions/master/how_tos/variables/index.html"""with tf.Session() as sess:sess.run(init_op)saver.restore(sess, "/tmp/model.ckpt")#print ("Model restored.")prediction=tf.argmax(y,1)return prediction.eval(feed_dict={x: [imvalue]}, session=sess)def imageprepare(argv):"""This function returns the pixel values.The imput is a png file location."""im = Image.open(argv).convert('L')width = float(im.size[0])height = float(im.size[1])newImage = Image.new('L', (28, 28), (255)) #creates white canvas of 28x28 pixelsif width > height: #check which dimension is bigger#Width is bigger. Width becomes 20 pixels.nheight = int(round((20.0/width*height),0)) #resize height according to ratio widthif (nheigth == 0): #rare case but minimum is 1 pixelnheigth = 1  # resize and sharpenimg = im.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)wtop = int(round(((28 - nheight)/2),0)) #caculate horizontal pozitionnewImage.paste(img, (4, wtop)) #paste resized image on white canvaselse:#Height is bigger. Heigth becomes 20 pixels. nwidth = int(round((20.0/height*width),0)) #resize width according to ratio heightif (nwidth == 0): #rare case but minimum is 1 pixelnwidth = 1# resize and sharpenimg = im.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)wleft = int(round(((28 - nwidth)/2),0)) #caculate vertical pozitionnewImage.paste(img, (wleft, 4)) #paste resized image on white canvas#newImage.save("sample.png")tv = list(newImage.getdata()) #get pixel values#normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.tva = [ (255-x)*1.0/255.0 for x in tv] return tva#print(tva)def main(argv):"""Main function."""imvalue = imageprepare(argv)predint = predictint(imvalue)print (predint[0]) #first value in listif __name__ == "__main__":main(sys.argv[1])

运行结果:

150414_VKrk_856051.png

矩阵-线性代数-http://www2.edu-edu.com.cn/lesson_crs78/self/j_0022/soft/ch0605.html

 

这本书不错:超智能体https://yjango.gitbooks.io/superorganism/content/dai_ma_yan_shi_2.html

 

转载于:https://my.oschina.net/u/856051/blog/869692

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/291062.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C# 多个异步方法的异常处理

、如果调用两个异步方法,每个都会抛出异常,该如何处理呢 ? 在下面的示例中,第一个 ThrowAfter 方法被调用,2s 后抛出异常(含消息 first)。该方法结束后,另一个 ThrowAfter 方法也被调用,1s 后也抛出异常。…

linux解pdf隐写工具,Linux版PDF解密工具PDFDecryptionTool-Deepin-amd64.deb下载

PDF解密工具PDFDecryptionTool的deb安装包提供下载了,可用在Deepin 20.2等Linux发行版中。该工具用于解除PDF文件的所有者权限的密码,解除编辑、复制等限制。另外,PDFDecryptionToolWin.py为Windows版本,针对Windows优化了下UI&am…

Mysql中explain命令查看语句执行概况

Mysql中可以使用explain命令查看查询语句的执行方式,使用方法举例:explain 查询语句 例如:explain select * from user_info 几个重要的字段说明: table:此次查询操作是关联哪张数据表 type:连接查询操作类…

Android之java.lang.UnsatisfiedLinkError(Failed to register native method ***callMethod1())解决办法

1、问题 Failed to register native method com.example.chenyu.test.JniClient.callMethod1() java.lang.UnsatisfiedLinkError: JNI_ERR returned from JNI_OnLoad in "/data/app/com.example.chenyu.test-2/lib/arm/libFirstJni.so" 如下图 2、解决办法 原因:…

代码段编辑器SnippetEditor 2.1

1.选择程序版本 2.可以创建文件夹 3.新建片段 4.给片段取名 5.双击进行编辑 6.点击保存 7.直接使用 转载于:https://www.cnblogs.com/shiworkyue/p/3844993.html

HUAWEI nova 青春版闪速快充,让追剧不再断电

笔者是一个对追剧到极致要求的人,每每有好看的影剧出来,都迫不及待想要一次看个够本。但是事与愿违,手机总是很不争气,虽然电池续航能力不算太差,但是对于我们这种追剧重症患者来说是完全不够的,每次出门还…

飞信linux下载文件,OpenFetion(飞信for Linux)

这是OpenFetion(飞信for Linux),openfetion是使用GTK 编写的基于libofetion的用户界面。软件功能程序简洁轻快,界面美观,支持libofetion当前提供的所有功能。软件优势它是目前GNU/Linux平台上最优秀的飞信客户端程序,也是基于libo…

免费开源Blazor在线Ico转换工具

1. 功能效果演示 仓库地址:IcoTool[1]在线演示地址:https://tool.dotnet9.com/ico[2]演示下文件上传、转换结果:通过该工具及代码,能了解到:使用Blazor怎么上传文件到服务器(Blazor Server)。怎么从服务器下载文件。如…

【02】CC - 有意义的命名

为什么80%的码农都做不了架构师?>>> 1、提防使用不同之处较小的名称 XYZControllerForEfficientHandlingOfStrings 与 XYZControllerForEfficientStorageOfStrings 在IDE下,都有自动补全,这种细微的差别,容易补全错&a…

linux7 语言包,Centos 7中文语言包的安装及中文支持

1、修改配置文件etc/locale.confLANG"zh_CN.UTF-8"2、查看更改后的系统语言变量[root5c46832b5c01 ~]# localelocale: Cannot set LC_CTYPE to default locale: No such file or directorylocale: Cannot set LC_MESSAGES to default locale: No such file or direct…

如何在构建docker镜像时执行SonarQube扫描.NET Core应用

前言SonarQube是一款静态代码质量分析工具,它常用于检测代码中的Bug、漏洞和代码异味,并且能够集成在IDE、Jenkins、Git等服务中,方便随时查看代码质量分析报告。一般情况下,我们在Jenkins管道中配置SonarQube,在编译过…

Win10系列:VC++ Direct3D模板介绍1

Visual Studio为开发Direct3D应用程序提供了便捷的模版,读者可以不必手动去新建Direct3D中所使用到的基础资源,而只需专注于图形的绘制。本小节主要为读者介绍这个模版中用于绘制图形的主要函数及其功能,为了能让读者更为清楚地了解如何使用此…

linux+arch系统下载,Linux

大小: 695MB更新时间:2021-02-04适用电脑:系统盘大于20G超过1GMHz的处理器最佳64位处理器Arch Linux是一份独立开发的、为i686优化的Linux发行,它面向高级Linux用户。它使用自行开发的包管理器pacman来为最新的应用软件提供 更新升…

Android---AlarmManager(全局定时器/闹钟)指定时长或以周期形式执行某项操作

AlarmManager的使用机制有的称呼为全局定时器,有的称呼为闹钟。通过对它的使用,个人觉得叫全局定时器比较合适,其实它的作用和Timer有点相似。都有两种相似的用法:(1)在指定时长后执行某项操作(…

C# 实例解释面向对象编程中的里氏替换原则

在面向对象编程中,SOLID 是五个设计原则的首字母缩写,旨在使软件设计更易于理解、灵活和可维护。这些原则是由美国软件工程师和讲师罗伯特C马丁(Robert Cecil Martin)提出的许多原则的子集,在他2000年的论文《设计原则与设计模式》中首次提出…

Android之JNI ERROR (app bug): accessed stale global reference 0xb39533f2 (index 19708 in a table of s

1、问题 2、原因 我在jni里面是这样写的 (*env)->CallVoidMethod(env, obj, method3, "chenyu"); 3、解决办法 把这个 (*env)->CallVoidMethod(env, obj, method3, "chenyu"); 改为这个 (*env)->CallVoidMethod(env, obj, method3, (*env)-&g…

工业互联网的最后一公里

最后一公里,出自中国共产党十八大以来的新名词之一,指政策始终“走在路上”,服务始终“停在嘴上”,实惠没有真正“落在身上”的“末梢堵塞”问题。要让人民群众真正得实惠,就要切实解决好“最后一公里”问题。1、移动互…

介绍这个库:C# Blazor中显示Markdown文件

1 讲目的 前几天上线了一个在线Icon转换工具[1],为了让大家使用放心,改了点代码,在转换下载Icon图标后立即删除临时文件,并在工具下面贴上了工具的开发步骤和代码,大家看这样改是否合适,见Issue 1[2]。这篇…

Linux 信号量 生产者消费者小例题

菜鸟偶遇信号量,擦出火花(只有不熟才会有火花)。于是上网搜资料和看《Unix环境高级编程》实现了几个小例题,高手请勿喷!这几位写得非常好啊: 题目来源: http://www.it165.net/os/html/201312/70…

C/C++语言之通过定义指针函数方式来实现在一个cpp文件里面获取另外一个cpp文件函数的返回值

1、定义函数指针 typedef int (* fun) (); static fun f; 2、代码实现 3、结果 4、总结 我们可以这样使用 在a.h文件里面里面定义函数指针,并且有个传递函数指针的方法 typedef std::string (*fun)();void f2(fun f 1); 然后在a.cpp文件里面实现f2方法 static fun f;…