转载:Python 与 C++ 程序的简单实例对比

什么是DHCP Snooping?如何配置DHCP Snooping? 功能描述防护类型防御伪造 DHCP 服务器、避免地址冲突、增强网络安全性使用场景企业园区网、校园网、大型局域网配合机制IP Source Guard、DAI、防止 ARP 欺骗部署难度⭐⭐(简单)“DHCP Snooping,是内网 DHCP 安全防护的第一道门神。” 🛡️。 阅读详情
  CSDN |  社区 |  技术中心 |  BLOG首页 |  我的首页 |  个人档案 |  联系作者 |  聚合  |   |  搜索 |  登录
  9篇原创: 0篇翻译: 0篇转载: 4485次点击: 24个评论: 0个Trackbacks
作者tag: c/c++ CSDN 推荐tag: c++  tag  python  vector  source 

        一位网友正在学校做课程设计题目,要求在一个文件中找到给定单词出现的位置并统计出现次数。这是一个比较简单的文本处理问题, 于是, 我给他用 python 写了一个,并打赌在5分钟内用不到30行程序解决问题。 我作到了,下面是程序:

if __name__=='__main__':
    file_name = raw_input('Input the file you want to find in:')
    try:
        in_file = open(file_name,'r')
        lines = in_file.readlines()


        tag_tok = ''
        while tag_tok.upper() != 'Q':
            tag_tok = raw_input('Input the word you want to find(Q for quit):')
            if tag_tok.upper() != 'Q':
                count = 0
                line_no = 0
                for line in lines:
                    line_no = line_no + 1
                    inline_cnt = line.count(tag_tok)
                    count = count + inline_cnt
                    if inline_cnt > 0:
                        print 'Find %s %d time(s) in line :%d'%(tag_tok,inline_cnt,line_no)
                        print line
                print '---------------------------------'
                print 'Total fount %s %d time(s)'%(tag_tok, count)
    except:
        print "Can't open file %s"%(file_name)

但是,这个网友还不满足非要一个 C++的程序,理由是他们老师不会python , 正好我也想试试用C++解决和python做下对比:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int BruteFind(const char *x, int m, const char *y, int n ,vector<int>& colpos) {
  int i, j, cnt=0;
  /* Searching */
  for (j = 0; j <= n - m; ++j) {
   for (i = 0; i < m && x
== y[i + j]; ++i);
    if (i >= m){
     colpos[cnt++] = j;
     if(cnt == colpos.size())
      colpos.resize(cnt * 2);
    }
  }
  return cnt;
}

int count_string(string source, string tag, vector<int>& colpos){
  int find_cnt = 0;
  find_cnt = BruteFind(tag.c_str(), tag.size(), source.c_str(),source.size(),colpos);

  return find_cnt;
}

int main(){
string file_name, line;
vector<string> lines;
  lines.resize(10);
  
cout << "Input the file name:";
cin  >> file_name;

ifstream in_file;
try{
     in_file.open(file_name.c_str());
     if(!in_file)
       throw(file_name);
  }
  catch(string file_name){
     cout << "Fatal error: File not found."<<endl;
     exit(1);
  }

int line_count = 0;

do{
    getline(in_file, lines[line_count]);
    line_count ++;
    
    if(line_count == lines.size()){
     lines.resize(line_count * 2);
    }
  }while(in_file.eof()==0);

string tag_tok;
vector<int> colpos;
colpos.resize(10);

do{
  cout << "Input the word you want to find(Q for quit):";
  cin >> tag_tok;
  if(tag_tok == "Q"){
   break;
  }
  
  int count = 0, line_no = 0 , inline_count;
  for(line_no = 0 ;line_no < line_count ; line_no++){
   inline_count = count_string(lines[line_no], tag_tok, colpos);
   count += inline_count;
   if(inline_count > 0){
    cout << "Find " << tag_tok << " " << inline_count << " time(s) in line " << line_no ;
    cout << " , column pos is ( ";
    
    for(int i = 0 ;i< inline_count ;i++){
     cout << colpos
<< ' ';
    }
    cout << " )" << endl;
    cout << lines[line_no] << endl;
   }
  }
  cout << "--------------------------------" <<endl;
  cout << "Total fount " << tag_tok << " " << count << " time(s)" << endl;
}while(tag_tok != "Q");

in_file.close();
return 0;
}

这个程序用了30分钟。

从程序长度和编程时间上,粗略对比下:

Python  5 分钟 22行

C++       30 分钟 60多行

从这个简单的例子中可以大体看到 脚本语言与C++语言中在开发时的差异了。



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=27682


[ 收藏到我的网摘]   albertlee发表于 2004年06月27日 11:52:00

相关文章:



特别推荐:

#    周星星 发表于2004-06-27 13:03:00  IP: 219.145.130.*
:)Python是一个很好的动态语言,个人认为它可以成为C++最好的帮手。但对于同一个算法而言Python不可能比C++快,这是由运行机制决定的。
我也想用C++实现一下试试看,但实在看不懂题目要求:
a. "给定单词出现的位置" 是不是所有出现的位置,位置以什么来表示,是单词在文件中的偏移吗?
b. 对于文本"aaa",这其中算有个几个"aa",是算一个,还是算两个,如果是算一个,是算前一个,还是算后一个?
而看您写的C++代码,说实话,变量太多,而且变量的作用域都非常的大,一时半会我也看不懂。
想通过运行您写的C++代码来反推出题目要求,可以在VC6.0中又编译不通过,遗憾。

#   whatever 发表于2004-06-27 13:56:00  IP: 155.97.192.*
你的例子证明了:不同语言有各自的适用范围--不过,这个话谁都懂,似乎不用证明。:)

#   albertlee 发表于2004-06-28 10:57:00  IP: 218.69.101.*
程序是在网吧写的. 那个C++程序是在 Borland C++ 5.5下编译过的.

#    周星星 发表于2004-06-30 15:37:00  IP: 219.145.130.*
看你写的python代码明白了你的意图
你用了python中的count函数,而你在C++没有利用已有的类似函数,而是自己写算法,这当然没法比啦
C++的count函数统计的元素,而search函数才是查找子序列。

#    乾坤一笑 发表于2004-06-30 18:00:00  IP: 218.79.105.*
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;

int main(int argc, char *argv[])
{
string strFile, strTarget, strBuf;
vector<string> lines;

// get Data from file & console
cout<< "Input file Name : "; cin >> strFile; ifstream inFile(strFile.c_str());
if (!inFile) { cerr<< "Error when open file! halt!"; return -1; }
cout << "Input the word you want to find(Q for quit):";
cin >> strTarget; if (strTarget == "Q" || strTarget =="q" ) return 0;
do { getline( inFile, strBuf ); lines.push_back(strBuf);
} while (inFile.eof()==0);

// deal with data
int countInLine = 0, countTotal = 0, lineNo = 0;
for (vector<string>::iterator iter=lines.begin(); iter<lines.end(); iter++ ) {
string::size_type pos = 0; int prePos = 0; string strTmp;
while ( (pos = (*iter).find_first_of(' ',pos)) != string::npos) { // slipt words
strTmp = (*iter).substr(prePos, pos-prePos);
if (strTmp==strTarget) countInLine++; prePos = 1 + pos++; }
strTmp = (*iter).substr(prePos, pos-prePos); // deal with the last word
if (strTmp==

#   albertlee 发表于2004-07-01 18:12:00  IP: 211.97.50.*
多谢星星哥

#    周星星 发表于2004-07-01 11:23:00  IP: 219.145.130.*
为了突出算法,我将条件输入去掉了

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
using namespace std;

struct SmileOnce
{
void operator()( const string& line )
{
cout << "LINE" << ++linenum << ' ';
for( char const* p=line.begin(); (p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};

int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
for_each( istream_iterator<string>(ifstream(filename.c_str())),istream_iterator<string>(),SmileOnce(str,num) );
cout << "共找到" << num << "处." << endl;
return 0;
}

#    周星星 发表于2004-07-03 15:14:00  IP: 219.140.161.*
原 来所犯错误:istream_iterator<linestring>(file)迭代的是字符串,而不是文件中的行,需要自己写一个 linestring和对应的istream& operator >>( istream& in, linestring& rch )

经VC++6.0和DevC++4948编译运行测试通过

class linestring : public string{};
inline istream& operator >>( istream& in, linestring& rch )
{
return getline( in, rch );
}

struct SmileOnce
{
void operator()( const string& line )
{
++linenum;
string::const_iterator p = search(line.begin(),line.end(),str.begin(),str.end());
if( p!=line.end() )
{
cout << "LINE" << linenum << ": " << (p-line.begin()+1);
++num;
p+=str.length();
for( ;(p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};

int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
ifstream file( filename.c_

#   albertlee 发表于2004-07-05 10:58:00  IP: 211.97.50.*
学习先,看来我对C++的了解实在太浅薄了。

不过我也使接触C++好长时间的人了,虽然没学好,但是这是不是从反面说明了Python的简单易学呢?

#   glacjay 发表于2004-12-24 20:25:00  IP: 218.94.9.*
应该可以各取所长吧,好像是用C++写具体的类,然后用PYTHON调用,忘了从哪里看的.

#   计算机界的律师 发表于2004-12-28 09:49:00  IP: 221.212.232.*
你们的语言学的还可以啊???

不错啊

#   计算机界的律师 发表于2004-12-28 09:51:00  IP: 221.212.232.*
我这有一个小程序,我打算用文件和类对象实现,如何做啊??

#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND

for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}

#   计算机界的律师 发表于2004-12-28 09:55:00  IP: 221.212.175.*
我也在做课程设计,但是学校要求用类对象,文件及类库实现随机化.
高手指教啊??

#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND

for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}

#   fidys 发表于2005-04-03 19:24:00  IP: 202.117.212.*
Vc7.0 Win32 Console 程序
// Find.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

typedef istream_iterator<string> In_str;
In_str end;

//统计类
class Count
{
public:
Count(string const & f) :ob(f),line(0),count(0){}
void operator()(char const * second)
{
istringstream is(second);
In_str begin(is);
++line;
for(int x=1;begin!=end;++x,++begin)
{
if(ob==(*begin)) {++count;place.push_back(make_pair(x,line));}
}
}
void out()
{
cout<<"/n你想找的字符出现了"<<count<<"次。/n";
if(count)
{
cout<<"分别出现在以下位置:/n";
for(int i=0;i<count;i++)
{
cout<<"第"<<i+1<<"次在 第"<<place[i].second<<"行,第"<<place[i].first<<"个单词的位置出现/n";
}
}
}
private:
vector<pair<int,int> > place;
long count;
string ob;
long line;
};

//主程序
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"请输入文件名:";
std::ifstream fp((*In_str(cin)).c_str());
if(fp)
{
cout<<"/n输入你想找的字符:";
Count cn(*In_str(cin));

发表评论

 
大名:
网址:
评论 
   
width="0" scrolling="no" height="0" frameborder="no" src="http://www.csdn.net/ggmm/dd333.htm" border="0" name="myframe" id="myframe">
 
液态神经网络(Liquid Neural Networks)从线虫大脑到下一代 AI 液态神经网络(Liquid Neural Networks,LNN)是一类具有动态内部结构的神经网络,其灵感来源于生物神经系统,尤其是大脑中神经元如何以复杂、非线性的方式响应外部刺激。与传统神经网络不同,液态神经网络的每个神经元在处理输入时,不再是静态线性或非线性变换,而是基于一个微分方程模型进行响应。这种建模方式使神经元的行为具有时间连续性和动态适应性。换句话说,它不仅“记住”过去的信息,还能根据当前环境实时调整自身的动态特性,这对于感知、决策、预测等任务都非常关键。 阅读详情

相关推荐

CUBEMX ADC 单/多通道+DMA

本文使用的是STM3F103C8T6 Cubemx进行单/多通道DMA配置。

记录学习 1409

Python实例浅谈--Python与C/C++相互调用

转载链接:Python实例浅谈之三Python与C/C++相互调用_乌托邦2号的博客-CSDN博客_python 调用c++类 目录 一、问题 二、Python调用C/C++ 1、Python调用C动态链接库 2、Python调用C++(类)动态链接库 3、Python调用C/C++可执行程序 三、C/C++调用Python 一、问题 Python模块和C/C++的动态库间相互调用在实际的应用中会有所涉及,在此作一总结。 二、Python调用C/C++ 1、P...

cbzhunian 740

STM8S全解析之系列文章4---STM8S芯片项目升级引导程序(使用中断接收升级数据)

STM8S全解析之系列文章4—STM8S芯片项目升级引导程序(使用中断接收升级数据) 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 例如:第一章 Python 机器学习入门之pandas的使用 文章目录STM8S全解析之系列文章4---STM8S芯片项目升级引导程序(使用中断接收升级数据)前言一、Flash划分boot和App二、使用步骤1.引入库2.读入数据总结 前言 用过STM8S都知道它没有中断向量重定向,也就意味着STM8S的中断向量没办法指向其他的位置,间接说明升级的引导

weixin_39853312的博客 1039

Python调用c++可执行程序

1、c++编译程序 #include <iostream> using namespace std; int test() { int a = 10, b = 5; return a+b; } int main() { cout<<"---begin---"<<endl...

weixin_30625691的博客 955

数字孪生模型构建理论及应用

源自:计算机集成制造系统作者:陶飞 张贺 戚庆林 徐 俊 孙铮 胡天亮 刘晓军 刘庭煜 关俊涛 陈畅宇 孟凡伟 张辰源 李志远 魏永利 朱铭浩 肖斌数字孪生作为实现数字化转型和促进智能化升级的重要使能途径,一直备受各行各业关注,已从理论研究走向了实际应用阶段。数字孪生是以多维虚拟模型和融合数据双驱动,通过虚实闭环交互,来实现监控、仿真、预测、优化等实际功能服务和应用需求,其中数字孪生模型构建是实现数字孪生落地应用的前提。

renhongxia1的博客 1万+

以太网详解(一)-MAC/PHY/MII/RMII/GMII/RGMII基本介绍

网络设备中肯定离开不MAC和PHY,本篇文章将详细介绍下以太网中一些常见术语与接口。 MAC和PHY结构 从硬件角度来看以太网是由CPU,MAC,PHY三部分组成的,如下图示意: 上图中DMA集成在CPU,CPU,MAC,PHY并不是集成在同一个芯片内,由于PHY包含大量模拟器件,而MAC是典型的数字电路,考虑到芯片面积及模拟/数字混合架构的原因,**将MAC集成进CPU而将PHY留在片外,这种...

sternlycore的博客 13万+

对比 C++ 和 Python,谈谈指针与引用

花下猫语:本文是学习群内 樱雨楼 小姐姐的投稿。之前已发布过她的一篇作品《当谈论迭代器时,我谈些什么?》,大受好评。本文依然是对比 C++ 与 Python,来探讨编程语言中极其重要的概念。祝大家读有所获,学有所成! 樱雨楼 | 原创作者 豌豆花下猫 | 编辑润色 本文原创并首发于公众号【Python猫】,未经授权,请勿转载。 原文地址:https://mp.weixin.qq.com...

weixin_35647812的博客 1120

【数据集】30 m地表温度LST数据集

【数据集】30 m地表温度LST数据集

WW、forever的博客 1153

Python 是否适合作为系统编程语言?与 Rust、C++ 的对比分析

``html Python 是否适合作为系统编程语言?与 Rust、C++ 的对比分析。

2501_91139348的博客 1595

【科研绘图系列】R语言绘制代谢物与临床表型相关性的森林图

本研究通过森林图展示了特定代谢物与三种临床比较之间的相关性分析结果。这种方法不仅直观地展示了每个代谢物的效应大小和不确定性,还允许我们比较不同代谢物在不同临床比较中的影响。森林图的结果表明,某些代谢物在特定临床比较中显示出显著的相关性,这可能为理解疾病的代谢机制提供了重要线索。

专注生信领域 572

在 SAP HANA 里为视图创建 Analytic Privilege,真正把同一份数据按角色切开

摘要:本文介绍了SAP HANA中基于业务角色的动态数据权限控制方法。通过Analytic Privilege技术,可以在同一视图上为不同角色设置不同的数据访问范围,实现行级安全控制。核心机制包括:1) 创建带有STRUCTURED PRIVILEGE CHECK的视图;2) 建立授权对象和用户映射表;3) 开发条件提供过程动态生成过滤条件;4) 创建结构化权限对象绑定条件提供器。这种设计使权限规则与业务数据解耦,便于维护变更,适合销售区域、财务数据等多角色访问控制场景。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 2404

Python调用C++程序的几种方法

Python调用C++程序的几种方法 转载 ZONG_XP 最后发布于2018-07-20 15:43:58 阅读数 14826 收藏 展开 参考:https://www.jb51.net/article/104159.htm 0 前言 大家都知道Python的优点是开发效率高,使用方便,C++则是运行效率高,这两者可以相辅相成,不管是在Python项目中嵌入C++代码,或是在C++项目中用Pyt...

啸风 1072

商用车电子电气零部件电磁兼容条件和试验(15)—HV-LV 耦合衰减(HV-LV)

本系列文章主要讲解商用车电子/电气零部件或系统的传导抗干扰、传导发射和辐射抗干扰、电场辐射发射以及静电放电等试验内容及要求,高压试验项目内容及要求。

零零刷的博客 298

python与c++的区别-c++和python的区别有哪些

程序有两种执行方式,解释执行和编译执行。PYTHON是一种脚本语言,是解释执行的,不需要经过编译,所以很方便快捷,且能够很好地跨平台,写一些小工具小程序特别合适。而C++则是一种需要编译后运行语言,在特定的机器上编译后在特定的机上运行,运行效率高,安全稳定。但编译后的程序一般是不跨平台的。学习一种编程语言不能看它热不热。而是要看它在某个领域的作用。就像汇编,虽然现在不热了,但是它在某些行业内还是很...

weixin_37988176的博客 3316

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python调用cpp文件_[转载] python 调用c++处理数组和图片

基本流程:定义cpp文件实现算法逻辑,因为编译器在编译的时候是会把c++函数改名,所以对于python调用的函数是要声明为以c的方式编译 #include "execute.h"extern "C"{Execute execute;void show_matrix(int *matrix, int rows, int columns) {execute.show_matrix(matrix, ro...

weixin_39747293的博客 591

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

[转载] python与c/c++相比有哪些优势

参考链接: Python输入和C++, Java速度对比 理论上,python的确比C/C++慢(我对Java的开发没有经验,无法评论)。这一点不用质疑。 C/C++是编绎语言,直接使用的是机器指令,而python总是跑在的虚拟机上, 把一个逻辑直接转换为机器指令,和把同样的逻辑转换为字节码,然后再转换为机器码来执行相比, 总是要高上一大截,这一点,有各种各样的性能报告,我没有必要,也没有必要去做出这样一个报告来, 我记得大概的数值是一到两个数量级,用C++的话来说,这就是所谓的抽象惩罚。 但实践上,.

ld909的博客 273

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

1. Python和Java、PHP、C、C#、C++等其他语言的对比?

转载:https://www.cnblogs.com/ppf3678/p/10739261.html 1.C语言,它既有高级语言的特点,又具有汇编语言的特点,它是结构式语言。C语言应用指针:可以直接进行靠近硬件的操作,但是C的指针操作不做保护,也给它带来了很多不安全的因素。C++在这方面做了改进,在保留了指针操作的同时又增强了安全性,受到了一些用户的支持,但是,由于这些改进增加语言的复杂度,也为...

CHERISHGF的博客 2021

python 指针_对比 C++ 和 Python,谈谈指针与引用

花下猫语:本文是学习群内 樱雨楼 小姐姐的投稿。之前已发布过她的一篇作品《当谈论迭代器时,我谈些什么?》,大受好评。本文依然是对比 C++ 与 Python,来探讨编程语言中极其重要的概念。祝大家读有所获,学有所成!樱雨楼 | 原创作者豌豆花下猫 | 编辑润色本文原创并首发于公众号【Python猫】,未经授权,请勿转载。0 引言指针(Pointer)是 C、C++ 以及 Java、Go 等语言的一...

weixin_39994806的博客 126

php与python缺点_Python与其他语言的对比

Python与其他语言的对比来源:北京兄弟连IT培训学校时间:2019/7/31 10:39:59python作为一门编程语言,它的诞生虽然很偶然,但是它得到程序员的喜爱却是必然之路,以下是Python与其他编程语言的优缺点对比:1. Python优势:简单易学,能够把用其他语言制作的各种模块很轻松地联结在一起。劣势:速度较慢,且有一些特定情况下才会出现(无法重现)的 bug2. C/C++优势:...

weixin_39564368的博客 153

Python 与 C++ 的交互编程

基础知识 编译语言和解释语言 尽管现在很多编程技术都在交融,出现了不少带有编译系统的解释语言,和带有复杂运行时系统的编译语言,但通常我们还是可以比较明确的区分它们。在这个大前提下,Python和C++属于这个两类技术中比较极端的代表。 编译时和运行时 C++的强大之处在于高效的生成产品和强大复杂的编译系统。利用C++的语法,可以生成非常灵活强大的程序,而这其中大部分

chenkent888的专栏 919

C++中调用Python脚本(转载)

转载▼ 标签: 杂谈 C++中调用Python脚本的意义就不讲了,至少你可以把它当成文本形式的动态链接库,需要的时候还可以改一改,只要不改变接口, C++的程序一旦编译好了,再改就没那么方便了先看Python的代码 代码: #test functiondef add(a,b):print "in python function add"print "a = " + str(a)print...

dfskchfk72506的博客 214

c++中的引用和python中的引用_对比 C++ 和 Python,谈谈指针与引用

花下猫语:本文是学习群内 樱雨楼 小姐姐的投稿。之前已发布过她的一篇作品《当谈论迭代器时,我谈些什么?》,大受好评。本文依然是对比 C++ 与 Python,来探讨编程语言中极其重要的概念。祝大家读有所获,学有所成!樱雨楼 | 原创作者豌豆花下猫 | 编辑润色本文原创并首发于公众号【Python猫】,未经授权,请勿转载。0 引言指针(Pointer)是 C、C++ 以及 Java、Go 等语言的一...

weixin_39920629的博客 228

Python 与 C++ 写文件效率对比

Python使用C++库使用write函数:大约32分钟 Python使用C++库使用fwrite函数(Python无读缓存,写缓存64M):大约5分钟 原生C++使用fwrite函数(读缓存64M,写缓存64M):大约4分钟 转载于:https://www.cnblogs.com/jhc888007/p/9037137.html...

weixin_30914981的博客 510

python程序代码头文件_将Python代码嵌入C++程序进行编写

原博文2015-11-04 16:56 −将Python代码嵌入C++程序进行编写的实例,python嵌入 把python嵌入的C++里面需要做一些步骤 安装python程序,这样才能使用python的头文件和库 在我们写的源文件中增加“Python.h&rd...04814相关推荐2010-02-03 22:54 −Code highlighting produced by ...

weixin_39890633的博客 144
上一篇: 转载:剪贴板大观园
下一篇: 转载:怎么从文本文件某一行开始读取文本内容
prophet08
博客等级 码龄20年 2粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值